xref: /f-stack/freebsd/netinet/in_pcb.c (revision d3f2221c)
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 if (lport == 0)
1118 {
1119     struct ifaddr *ifa;
1120     struct ifnet *ifp;
1121     struct sockaddr_in ifp_sin;
1122     unsigned loop_count = 0;
1123     bzero(&ifp_sin, sizeof(ifp_sin));
1124     ifp_sin.sin_addr.s_addr = laddr.s_addr;
1125     ifp_sin.sin_family = AF_INET;
1126     ifp_sin.sin_len = sizeof(ifp_sin);
1127     ifa = ifa_ifwithnet((struct sockaddr *)&ifp_sin, 0, RT_ALL_FIBS);
1128     if (ifa == NULL) {
1129     	ifp_sin.sin_addr.s_addr = faddr.s_addr;
1130     	ifa = ifa_ifwithnet((struct sockaddr *)&ifp_sin, 0, RT_ALL_FIBS);
1131     	if ( ifa == NULL )
1132         	return (EADDRNOTAVAIL);
1133     }
1134     ifp = ifa->ifa_ifp;
1135     while (lport == 0) {
1136         int rss;
1137         error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1138             cred);
1139         if (error)
1140             return (error);
1141         rss = ff_rss_check(ifp->if_softc, faddr.s_addr, laddr.s_addr,
1142             fport, lport);
1143         if (rss) {
1144             break;
1145         }
1146         lport = 0;
1147         /* Note:
1148          * if all ports are completely used, just return.
1149          * this ugly code is not a correct way, it just lets loop quit.
1150          * we will fix it as soon as possible.
1151          */
1152         if (++loop_count >= 65535) {
1153             return (EADDRNOTAVAIL);
1154         }
1155     }
1156 }
1157 #endif
1158 	*laddrp = laddr.s_addr;
1159 	*lportp = lport;
1160 	*faddrp = faddr.s_addr;
1161 	*fportp = fport;
1162 	return (0);
1163 }
1164 
1165 void
1166 in_pcbdisconnect(struct inpcb *inp)
1167 {
1168 
1169 	INP_WLOCK_ASSERT(inp);
1170 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1171 
1172 	inp->inp_faddr.s_addr = INADDR_ANY;
1173 	inp->inp_fport = 0;
1174 	in_pcbrehash(inp);
1175 }
1176 #endif /* INET */
1177 
1178 /*
1179  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1180  * For most protocols, this will be invoked immediately prior to calling
1181  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
1182  * socket, in which case in_pcbfree() is deferred.
1183  */
1184 void
1185 in_pcbdetach(struct inpcb *inp)
1186 {
1187 
1188 	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1189 
1190 	inp->inp_socket->so_pcb = NULL;
1191 	inp->inp_socket = NULL;
1192 }
1193 
1194 /*
1195  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1196  * stability of an inpcb pointer despite the inpcb lock being released.  This
1197  * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1198  * but where the inpcb lock may already held, or when acquiring a reference
1199  * via a pcbgroup.
1200  *
1201  * in_pcbref() should be used only to provide brief memory stability, and
1202  * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1203  * garbage collect the inpcb if it has been in_pcbfree()'d from another
1204  * context.  Until in_pcbrele() has returned that the inpcb is still valid,
1205  * lock and rele are the *only* safe operations that may be performed on the
1206  * inpcb.
1207  *
1208  * While the inpcb will not be freed, releasing the inpcb lock means that the
1209  * connection's state may change, so the caller should be careful to
1210  * revalidate any cached state on reacquiring the lock.  Drop the reference
1211  * using in_pcbrele().
1212  */
1213 void
1214 in_pcbref(struct inpcb *inp)
1215 {
1216 
1217 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1218 
1219 	refcount_acquire(&inp->inp_refcount);
1220 }
1221 
1222 /*
1223  * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1224  * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1225  * return a flag indicating whether or not the inpcb remains valid.  If it is
1226  * valid, we return with the inpcb lock held.
1227  *
1228  * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1229  * reference on an inpcb.  Historically more work was done here (actually, in
1230  * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1231  * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
1232  * about memory stability (and continued use of the write lock).
1233  */
1234 int
1235 in_pcbrele_rlocked(struct inpcb *inp)
1236 {
1237 	struct inpcbinfo *pcbinfo;
1238 
1239 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1240 
1241 	INP_RLOCK_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_RUNLOCK(inp);
1250 			return (1);
1251 		}
1252 		return (0);
1253 	}
1254 
1255 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1256 
1257 	INP_RUNLOCK(inp);
1258 	pcbinfo = inp->inp_pcbinfo;
1259 	uma_zfree(pcbinfo->ipi_zone, inp);
1260 	return (1);
1261 }
1262 
1263 int
1264 in_pcbrele_wlocked(struct inpcb *inp)
1265 {
1266 	struct inpcbinfo *pcbinfo;
1267 
1268 	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1269 
1270 	INP_WLOCK_ASSERT(inp);
1271 
1272 	if (refcount_release(&inp->inp_refcount) == 0) {
1273 		/*
1274 		 * If the inpcb has been freed, let the caller know, even if
1275 		 * this isn't the last reference.
1276 		 */
1277 		if (inp->inp_flags2 & INP_FREED) {
1278 			INP_WUNLOCK(inp);
1279 			return (1);
1280 		}
1281 		return (0);
1282 	}
1283 
1284 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1285 
1286 	INP_WUNLOCK(inp);
1287 	pcbinfo = inp->inp_pcbinfo;
1288 	uma_zfree(pcbinfo->ipi_zone, inp);
1289 	return (1);
1290 }
1291 
1292 /*
1293  * Temporary wrapper.
1294  */
1295 int
1296 in_pcbrele(struct inpcb *inp)
1297 {
1298 
1299 	return (in_pcbrele_wlocked(inp));
1300 }
1301 
1302 /*
1303  * Unconditionally schedule an inpcb to be freed by decrementing its
1304  * reference count, which should occur only after the inpcb has been detached
1305  * from its socket.  If another thread holds a temporary reference (acquired
1306  * using in_pcbref()) then the free is deferred until that reference is
1307  * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
1308  * work, including removal from global lists, is done in this context, where
1309  * the pcbinfo lock is held.
1310  */
1311 void
1312 in_pcbfree(struct inpcb *inp)
1313 {
1314 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1315 
1316 	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1317 
1318 #ifdef INVARIANTS
1319 	if (pcbinfo == &V_tcbinfo) {
1320 		INP_INFO_LOCK_ASSERT(pcbinfo);
1321 	} else {
1322 		INP_INFO_WLOCK_ASSERT(pcbinfo);
1323 	}
1324 #endif
1325 	INP_WLOCK_ASSERT(inp);
1326 
1327 	/* XXXRW: Do as much as possible here. */
1328 #ifdef IPSEC
1329 	if (inp->inp_sp != NULL)
1330 		ipsec_delete_pcbpolicy(inp);
1331 #endif
1332 	INP_LIST_WLOCK(pcbinfo);
1333 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1334 	in_pcbremlists(inp);
1335 	INP_LIST_WUNLOCK(pcbinfo);
1336 #ifdef INET6
1337 	if (inp->inp_vflag & INP_IPV6PROTO) {
1338 		ip6_freepcbopts(inp->in6p_outputopts);
1339 		if (inp->in6p_moptions != NULL)
1340 			ip6_freemoptions(inp->in6p_moptions);
1341 	}
1342 #endif
1343 	if (inp->inp_options)
1344 		(void)m_free(inp->inp_options);
1345 #ifdef INET
1346 	if (inp->inp_moptions != NULL)
1347 		inp_freemoptions(inp->inp_moptions);
1348 #endif
1349 	if (inp->inp_route.ro_rt) {
1350 		RTFREE(inp->inp_route.ro_rt);
1351 		inp->inp_route.ro_rt = (struct rtentry *)NULL;
1352 	}
1353 	if (inp->inp_route.ro_lle)
1354 		LLE_FREE(inp->inp_route.ro_lle);	/* zeros ro_lle */
1355 
1356 	inp->inp_vflag = 0;
1357 	inp->inp_flags2 |= INP_FREED;
1358 	crfree(inp->inp_cred);
1359 #ifdef MAC
1360 	mac_inpcb_destroy(inp);
1361 #endif
1362 	if (!in_pcbrele_wlocked(inp))
1363 		INP_WUNLOCK(inp);
1364 }
1365 
1366 /*
1367  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1368  * port reservation, and preventing it from being returned by inpcb lookups.
1369  *
1370  * It is used by TCP to mark an inpcb as unused and avoid future packet
1371  * delivery or event notification when a socket remains open but TCP has
1372  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1373  * or a RST on the wire, and allows the port binding to be reused while still
1374  * maintaining the invariant that so_pcb always points to a valid inpcb until
1375  * in_pcbdetach().
1376  *
1377  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1378  * in_pcbnotifyall() and in_pcbpurgeif0()?
1379  */
1380 void
1381 in_pcbdrop(struct inpcb *inp)
1382 {
1383 
1384 	INP_WLOCK_ASSERT(inp);
1385 
1386 	/*
1387 	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1388 	 * the hash lock...?
1389 	 */
1390 	inp->inp_flags |= INP_DROPPED;
1391 	if (inp->inp_flags & INP_INHASHLIST) {
1392 		struct inpcbport *phd = inp->inp_phd;
1393 
1394 		INP_HASH_WLOCK(inp->inp_pcbinfo);
1395 		LIST_REMOVE(inp, inp_hash);
1396 		LIST_REMOVE(inp, inp_portlist);
1397 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1398 			LIST_REMOVE(phd, phd_hash);
1399 			free(phd, M_PCB);
1400 		}
1401 		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1402 		inp->inp_flags &= ~INP_INHASHLIST;
1403 #ifdef PCBGROUP
1404 		in_pcbgroup_remove(inp);
1405 #endif
1406 	}
1407 }
1408 
1409 #ifdef INET
1410 /*
1411  * Common routines to return the socket addresses associated with inpcbs.
1412  */
1413 struct sockaddr *
1414 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1415 {
1416 	struct sockaddr_in *sin;
1417 
1418 	sin = malloc(sizeof *sin, M_SONAME,
1419 		M_WAITOK | M_ZERO);
1420 	sin->sin_family = AF_INET;
1421 	sin->sin_len = sizeof(*sin);
1422 	sin->sin_addr = *addr_p;
1423 	sin->sin_port = port;
1424 
1425 	return (struct sockaddr *)sin;
1426 }
1427 
1428 int
1429 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1430 {
1431 	struct inpcb *inp;
1432 	struct in_addr addr;
1433 	in_port_t port;
1434 
1435 	inp = sotoinpcb(so);
1436 	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1437 
1438 	INP_RLOCK(inp);
1439 	port = inp->inp_lport;
1440 	addr = inp->inp_laddr;
1441 	INP_RUNLOCK(inp);
1442 
1443 	*nam = in_sockaddr(port, &addr);
1444 	return 0;
1445 }
1446 
1447 int
1448 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1449 {
1450 	struct inpcb *inp;
1451 	struct in_addr addr;
1452 	in_port_t port;
1453 
1454 	inp = sotoinpcb(so);
1455 	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1456 
1457 	INP_RLOCK(inp);
1458 	port = inp->inp_fport;
1459 	addr = inp->inp_faddr;
1460 	INP_RUNLOCK(inp);
1461 
1462 	*nam = in_sockaddr(port, &addr);
1463 	return 0;
1464 }
1465 
1466 void
1467 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1468     struct inpcb *(*notify)(struct inpcb *, int))
1469 {
1470 	struct inpcb *inp, *inp_temp;
1471 
1472 	INP_INFO_WLOCK(pcbinfo);
1473 	LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1474 		INP_WLOCK(inp);
1475 #ifdef INET6
1476 		if ((inp->inp_vflag & INP_IPV4) == 0) {
1477 			INP_WUNLOCK(inp);
1478 			continue;
1479 		}
1480 #endif
1481 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1482 		    inp->inp_socket == NULL) {
1483 			INP_WUNLOCK(inp);
1484 			continue;
1485 		}
1486 		if ((*notify)(inp, errno))
1487 			INP_WUNLOCK(inp);
1488 	}
1489 	INP_INFO_WUNLOCK(pcbinfo);
1490 }
1491 
1492 void
1493 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1494 {
1495 	struct inpcb *inp;
1496 	struct ip_moptions *imo;
1497 	int i, gap;
1498 
1499 	INP_INFO_WLOCK(pcbinfo);
1500 	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1501 		INP_WLOCK(inp);
1502 		imo = inp->inp_moptions;
1503 		if ((inp->inp_vflag & INP_IPV4) &&
1504 		    imo != NULL) {
1505 			/*
1506 			 * Unselect the outgoing interface if it is being
1507 			 * detached.
1508 			 */
1509 			if (imo->imo_multicast_ifp == ifp)
1510 				imo->imo_multicast_ifp = NULL;
1511 
1512 			/*
1513 			 * Drop multicast group membership if we joined
1514 			 * through the interface being detached.
1515 			 */
1516 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1517 			    i++) {
1518 				if (imo->imo_membership[i]->inm_ifp == ifp) {
1519 					in_delmulti(imo->imo_membership[i]);
1520 					gap++;
1521 				} else if (gap != 0)
1522 					imo->imo_membership[i - gap] =
1523 					    imo->imo_membership[i];
1524 			}
1525 			imo->imo_num_memberships -= gap;
1526 		}
1527 		INP_WUNLOCK(inp);
1528 	}
1529 	INP_INFO_WUNLOCK(pcbinfo);
1530 }
1531 
1532 /*
1533  * Lookup a PCB based on the local address and port.  Caller must hold the
1534  * hash lock.  No inpcb locks or references are acquired.
1535  */
1536 #define INP_LOOKUP_MAPPED_PCB_COST	3
1537 struct inpcb *
1538 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1539     u_short lport, int lookupflags, struct ucred *cred)
1540 {
1541 	struct inpcb *inp;
1542 #ifdef INET6
1543 	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1544 #else
1545 	int matchwild = 3;
1546 #endif
1547 	int wildcard;
1548 
1549 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1550 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1551 
1552 	INP_HASH_LOCK_ASSERT(pcbinfo);
1553 
1554 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1555 		struct inpcbhead *head;
1556 		/*
1557 		 * Look for an unconnected (wildcard foreign addr) PCB that
1558 		 * matches the local address and port we're looking for.
1559 		 */
1560 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1561 		    0, pcbinfo->ipi_hashmask)];
1562 		LIST_FOREACH(inp, head, inp_hash) {
1563 #ifdef INET6
1564 			/* XXX inp locking */
1565 			if ((inp->inp_vflag & INP_IPV4) == 0)
1566 				continue;
1567 #endif
1568 			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1569 			    inp->inp_laddr.s_addr == laddr.s_addr &&
1570 			    inp->inp_lport == lport) {
1571 				/*
1572 				 * Found?
1573 				 */
1574 				if (cred == NULL ||
1575 				    prison_equal_ip4(cred->cr_prison,
1576 					inp->inp_cred->cr_prison))
1577 					return (inp);
1578 			}
1579 		}
1580 		/*
1581 		 * Not found.
1582 		 */
1583 		return (NULL);
1584 	} else {
1585 		struct inpcbporthead *porthash;
1586 		struct inpcbport *phd;
1587 		struct inpcb *match = NULL;
1588 		/*
1589 		 * Best fit PCB lookup.
1590 		 *
1591 		 * First see if this local port is in use by looking on the
1592 		 * port hash list.
1593 		 */
1594 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1595 		    pcbinfo->ipi_porthashmask)];
1596 		LIST_FOREACH(phd, porthash, phd_hash) {
1597 			if (phd->phd_port == lport)
1598 				break;
1599 		}
1600 		if (phd != NULL) {
1601 			/*
1602 			 * Port is in use by one or more PCBs. Look for best
1603 			 * fit.
1604 			 */
1605 			LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1606 				wildcard = 0;
1607 				if (cred != NULL &&
1608 				    !prison_equal_ip4(inp->inp_cred->cr_prison,
1609 					cred->cr_prison))
1610 					continue;
1611 #ifdef INET6
1612 				/* XXX inp locking */
1613 				if ((inp->inp_vflag & INP_IPV4) == 0)
1614 					continue;
1615 				/*
1616 				 * We never select the PCB that has
1617 				 * INP_IPV6 flag and is bound to :: if
1618 				 * we have another PCB which is bound
1619 				 * to 0.0.0.0.  If a PCB has the
1620 				 * INP_IPV6 flag, then we set its cost
1621 				 * higher than IPv4 only PCBs.
1622 				 *
1623 				 * Note that the case only happens
1624 				 * when a socket is bound to ::, under
1625 				 * the condition that the use of the
1626 				 * mapped address is allowed.
1627 				 */
1628 				if ((inp->inp_vflag & INP_IPV6) != 0)
1629 					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1630 #endif
1631 				if (inp->inp_faddr.s_addr != INADDR_ANY)
1632 					wildcard++;
1633 				if (inp->inp_laddr.s_addr != INADDR_ANY) {
1634 					if (laddr.s_addr == INADDR_ANY)
1635 						wildcard++;
1636 					else if (inp->inp_laddr.s_addr != laddr.s_addr)
1637 						continue;
1638 				} else {
1639 					if (laddr.s_addr != INADDR_ANY)
1640 						wildcard++;
1641 				}
1642 				if (wildcard < matchwild) {
1643 					match = inp;
1644 					matchwild = wildcard;
1645 					if (matchwild == 0)
1646 						break;
1647 				}
1648 			}
1649 		}
1650 		return (match);
1651 	}
1652 }
1653 #undef INP_LOOKUP_MAPPED_PCB_COST
1654 
1655 #ifdef PCBGROUP
1656 /*
1657  * Lookup PCB in hash list, using pcbgroup tables.
1658  */
1659 static struct inpcb *
1660 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1661     struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1662     u_int lport_arg, int lookupflags, struct ifnet *ifp)
1663 {
1664 	struct inpcbhead *head;
1665 	struct inpcb *inp, *tmpinp;
1666 	u_short fport = fport_arg, lport = lport_arg;
1667 
1668 	/*
1669 	 * First look for an exact match.
1670 	 */
1671 	tmpinp = NULL;
1672 	INP_GROUP_LOCK(pcbgroup);
1673 	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1674 	    pcbgroup->ipg_hashmask)];
1675 	LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1676 #ifdef INET6
1677 		/* XXX inp locking */
1678 		if ((inp->inp_vflag & INP_IPV4) == 0)
1679 			continue;
1680 #endif
1681 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1682 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1683 		    inp->inp_fport == fport &&
1684 		    inp->inp_lport == lport) {
1685 			/*
1686 			 * XXX We should be able to directly return
1687 			 * the inp here, without any checks.
1688 			 * Well unless both bound with SO_REUSEPORT?
1689 			 */
1690 			if (prison_flag(inp->inp_cred, PR_IP4))
1691 				goto found;
1692 			if (tmpinp == NULL)
1693 				tmpinp = inp;
1694 		}
1695 	}
1696 	if (tmpinp != NULL) {
1697 		inp = tmpinp;
1698 		goto found;
1699 	}
1700 
1701 #ifdef	RSS
1702 	/*
1703 	 * For incoming connections, we may wish to do a wildcard
1704 	 * match for an RSS-local socket.
1705 	 */
1706 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1707 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1708 #ifdef INET6
1709 		struct inpcb *local_wild_mapped = NULL;
1710 #endif
1711 		struct inpcb *jail_wild = NULL;
1712 		struct inpcbhead *head;
1713 		int injail;
1714 
1715 		/*
1716 		 * Order of socket selection - we always prefer jails.
1717 		 *      1. jailed, non-wild.
1718 		 *      2. jailed, wild.
1719 		 *      3. non-jailed, non-wild.
1720 		 *      4. non-jailed, wild.
1721 		 */
1722 
1723 		head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
1724 		    lport, 0, pcbgroup->ipg_hashmask)];
1725 		LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1726 #ifdef INET6
1727 			/* XXX inp locking */
1728 			if ((inp->inp_vflag & INP_IPV4) == 0)
1729 				continue;
1730 #endif
1731 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1732 			    inp->inp_lport != lport)
1733 				continue;
1734 
1735 			injail = prison_flag(inp->inp_cred, PR_IP4);
1736 			if (injail) {
1737 				if (prison_check_ip4(inp->inp_cred,
1738 				    &laddr) != 0)
1739 					continue;
1740 			} else {
1741 				if (local_exact != NULL)
1742 					continue;
1743 			}
1744 
1745 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1746 				if (injail)
1747 					goto found;
1748 				else
1749 					local_exact = inp;
1750 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1751 #ifdef INET6
1752 				/* XXX inp locking, NULL check */
1753 				if (inp->inp_vflag & INP_IPV6PROTO)
1754 					local_wild_mapped = inp;
1755 				else
1756 #endif
1757 					if (injail)
1758 						jail_wild = inp;
1759 					else
1760 						local_wild = inp;
1761 			}
1762 		} /* LIST_FOREACH */
1763 
1764 		inp = jail_wild;
1765 		if (inp == NULL)
1766 			inp = local_exact;
1767 		if (inp == NULL)
1768 			inp = local_wild;
1769 #ifdef INET6
1770 		if (inp == NULL)
1771 			inp = local_wild_mapped;
1772 #endif
1773 		if (inp != NULL)
1774 			goto found;
1775 	}
1776 #endif
1777 
1778 	/*
1779 	 * Then look for a wildcard match, if requested.
1780 	 */
1781 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1782 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1783 #ifdef INET6
1784 		struct inpcb *local_wild_mapped = NULL;
1785 #endif
1786 		struct inpcb *jail_wild = NULL;
1787 		struct inpcbhead *head;
1788 		int injail;
1789 
1790 		/*
1791 		 * Order of socket selection - we always prefer jails.
1792 		 *      1. jailed, non-wild.
1793 		 *      2. jailed, wild.
1794 		 *      3. non-jailed, non-wild.
1795 		 *      4. non-jailed, wild.
1796 		 */
1797 		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
1798 		    0, pcbinfo->ipi_wildmask)];
1799 		LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1800 #ifdef INET6
1801 			/* XXX inp locking */
1802 			if ((inp->inp_vflag & INP_IPV4) == 0)
1803 				continue;
1804 #endif
1805 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1806 			    inp->inp_lport != lport)
1807 				continue;
1808 
1809 			injail = prison_flag(inp->inp_cred, PR_IP4);
1810 			if (injail) {
1811 				if (prison_check_ip4(inp->inp_cred,
1812 				    &laddr) != 0)
1813 					continue;
1814 			} else {
1815 				if (local_exact != NULL)
1816 					continue;
1817 			}
1818 
1819 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1820 				if (injail)
1821 					goto found;
1822 				else
1823 					local_exact = inp;
1824 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1825 #ifdef INET6
1826 				/* XXX inp locking, NULL check */
1827 				if (inp->inp_vflag & INP_IPV6PROTO)
1828 					local_wild_mapped = inp;
1829 				else
1830 #endif
1831 					if (injail)
1832 						jail_wild = inp;
1833 					else
1834 						local_wild = inp;
1835 			}
1836 		} /* LIST_FOREACH */
1837 		inp = jail_wild;
1838 		if (inp == NULL)
1839 			inp = local_exact;
1840 		if (inp == NULL)
1841 			inp = local_wild;
1842 #ifdef INET6
1843 		if (inp == NULL)
1844 			inp = local_wild_mapped;
1845 #endif
1846 		if (inp != NULL)
1847 			goto found;
1848 	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
1849 	INP_GROUP_UNLOCK(pcbgroup);
1850 	return (NULL);
1851 
1852 found:
1853 	in_pcbref(inp);
1854 	INP_GROUP_UNLOCK(pcbgroup);
1855 	if (lookupflags & INPLOOKUP_WLOCKPCB) {
1856 		INP_WLOCK(inp);
1857 		if (in_pcbrele_wlocked(inp))
1858 			return (NULL);
1859 	} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1860 		INP_RLOCK(inp);
1861 		if (in_pcbrele_rlocked(inp))
1862 			return (NULL);
1863 	} else
1864 		panic("%s: locking bug", __func__);
1865 	return (inp);
1866 }
1867 #endif /* PCBGROUP */
1868 
1869 /*
1870  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
1871  * that the caller has locked the hash list, and will not perform any further
1872  * locking or reference operations on either the hash list or the connection.
1873  */
1874 static struct inpcb *
1875 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1876     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
1877     struct ifnet *ifp)
1878 {
1879 	struct inpcbhead *head;
1880 	struct inpcb *inp, *tmpinp;
1881 	u_short fport = fport_arg, lport = lport_arg;
1882 
1883 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1884 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1885 
1886 	INP_HASH_LOCK_ASSERT(pcbinfo);
1887 
1888 	/*
1889 	 * First look for an exact match.
1890 	 */
1891 	tmpinp = NULL;
1892 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1893 	    pcbinfo->ipi_hashmask)];
1894 	LIST_FOREACH(inp, head, inp_hash) {
1895 #ifdef INET6
1896 		/* XXX inp locking */
1897 		if ((inp->inp_vflag & INP_IPV4) == 0)
1898 			continue;
1899 #endif
1900 		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1901 		    inp->inp_laddr.s_addr == laddr.s_addr &&
1902 		    inp->inp_fport == fport &&
1903 		    inp->inp_lport == lport) {
1904 			/*
1905 			 * XXX We should be able to directly return
1906 			 * the inp here, without any checks.
1907 			 * Well unless both bound with SO_REUSEPORT?
1908 			 */
1909 			if (prison_flag(inp->inp_cred, PR_IP4))
1910 				return (inp);
1911 			if (tmpinp == NULL)
1912 				tmpinp = inp;
1913 		}
1914 	}
1915 	if (tmpinp != NULL)
1916 		return (tmpinp);
1917 
1918 	/*
1919 	 * Then look for a wildcard match, if requested.
1920 	 */
1921 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1922 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1923 #ifdef INET6
1924 		struct inpcb *local_wild_mapped = NULL;
1925 #endif
1926 		struct inpcb *jail_wild = NULL;
1927 		int injail;
1928 
1929 		/*
1930 		 * Order of socket selection - we always prefer jails.
1931 		 *      1. jailed, non-wild.
1932 		 *      2. jailed, wild.
1933 		 *      3. non-jailed, non-wild.
1934 		 *      4. non-jailed, wild.
1935 		 */
1936 
1937 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1938 		    0, pcbinfo->ipi_hashmask)];
1939 		LIST_FOREACH(inp, head, inp_hash) {
1940 #ifdef INET6
1941 			/* XXX inp locking */
1942 			if ((inp->inp_vflag & INP_IPV4) == 0)
1943 				continue;
1944 #endif
1945 			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1946 			    inp->inp_lport != lport)
1947 				continue;
1948 
1949 			injail = prison_flag(inp->inp_cred, PR_IP4);
1950 			if (injail) {
1951 				if (prison_check_ip4(inp->inp_cred,
1952 				    &laddr) != 0)
1953 					continue;
1954 			} else {
1955 				if (local_exact != NULL)
1956 					continue;
1957 			}
1958 
1959 			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1960 				if (injail)
1961 					return (inp);
1962 				else
1963 					local_exact = inp;
1964 			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1965 #ifdef INET6
1966 				/* XXX inp locking, NULL check */
1967 				if (inp->inp_vflag & INP_IPV6PROTO)
1968 					local_wild_mapped = inp;
1969 				else
1970 #endif
1971 					if (injail)
1972 						jail_wild = inp;
1973 					else
1974 						local_wild = inp;
1975 			}
1976 		} /* LIST_FOREACH */
1977 		if (jail_wild != NULL)
1978 			return (jail_wild);
1979 		if (local_exact != NULL)
1980 			return (local_exact);
1981 		if (local_wild != NULL)
1982 			return (local_wild);
1983 #ifdef INET6
1984 		if (local_wild_mapped != NULL)
1985 			return (local_wild_mapped);
1986 #endif
1987 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1988 
1989 	return (NULL);
1990 }
1991 
1992 /*
1993  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
1994  * hash list lock, and will return the inpcb locked (i.e., requires
1995  * INPLOOKUP_LOCKPCB).
1996  */
1997 static struct inpcb *
1998 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1999     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2000     struct ifnet *ifp)
2001 {
2002 	struct inpcb *inp;
2003 
2004 	INP_HASH_RLOCK(pcbinfo);
2005 	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2006 	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
2007 	if (inp != NULL) {
2008 		in_pcbref(inp);
2009 		INP_HASH_RUNLOCK(pcbinfo);
2010 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
2011 			INP_WLOCK(inp);
2012 			if (in_pcbrele_wlocked(inp))
2013 				return (NULL);
2014 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2015 			INP_RLOCK(inp);
2016 			if (in_pcbrele_rlocked(inp))
2017 				return (NULL);
2018 		} else
2019 			panic("%s: locking bug", __func__);
2020 	} else
2021 		INP_HASH_RUNLOCK(pcbinfo);
2022 	return (inp);
2023 }
2024 
2025 /*
2026  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2027  * from which a pre-calculated hash value may be extracted.
2028  *
2029  * Possibly more of this logic should be in in_pcbgroup.c.
2030  */
2031 struct inpcb *
2032 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2033     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2034 {
2035 #if defined(PCBGROUP) && !defined(RSS)
2036 	struct inpcbgroup *pcbgroup;
2037 #endif
2038 
2039 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2040 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2041 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2042 	    ("%s: LOCKPCB not set", __func__));
2043 
2044 	/*
2045 	 * When not using RSS, use connection groups in preference to the
2046 	 * reservation table when looking up 4-tuples.  When using RSS, just
2047 	 * use the reservation table, due to the cost of the Toeplitz hash
2048 	 * in software.
2049 	 *
2050 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
2051 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
2052 	 * in software.
2053 	 */
2054 #if defined(PCBGROUP) && !defined(RSS)
2055 	if (in_pcbgroup_enabled(pcbinfo)) {
2056 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2057 		    fport);
2058 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2059 		    laddr, lport, lookupflags, ifp));
2060 	}
2061 #endif
2062 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2063 	    lookupflags, ifp));
2064 }
2065 
2066 struct inpcb *
2067 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2068     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2069     struct ifnet *ifp, struct mbuf *m)
2070 {
2071 #ifdef PCBGROUP
2072 	struct inpcbgroup *pcbgroup;
2073 #endif
2074 
2075 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2076 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
2077 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2078 	    ("%s: LOCKPCB not set", __func__));
2079 
2080 #ifdef PCBGROUP
2081 	/*
2082 	 * If we can use a hardware-generated hash to look up the connection
2083 	 * group, use that connection group to find the inpcb.  Otherwise
2084 	 * fall back on a software hash -- or the reservation table if we're
2085 	 * using RSS.
2086 	 *
2087 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
2088 	 */
2089 	if (in_pcbgroup_enabled(pcbinfo) &&
2090 	    !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2091 		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2092 		    m->m_pkthdr.flowid);
2093 		if (pcbgroup != NULL)
2094 			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2095 			    fport, laddr, lport, lookupflags, ifp));
2096 #ifndef RSS
2097 		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2098 		    fport);
2099 		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2100 		    laddr, lport, lookupflags, ifp));
2101 #endif
2102 	}
2103 #endif
2104 	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2105 	    lookupflags, ifp));
2106 }
2107 #endif /* INET */
2108 
2109 /*
2110  * Insert PCB onto various hash lists.
2111  */
2112 static int
2113 in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
2114 {
2115 	struct inpcbhead *pcbhash;
2116 	struct inpcbporthead *pcbporthash;
2117 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2118 	struct inpcbport *phd;
2119 	u_int32_t hashkey_faddr;
2120 
2121 	INP_WLOCK_ASSERT(inp);
2122 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2123 
2124 	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2125 	    ("in_pcbinshash: INP_INHASHLIST"));
2126 
2127 #ifdef INET6
2128 	if (inp->inp_vflag & INP_IPV6)
2129 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2130 	else
2131 #endif
2132 	hashkey_faddr = inp->inp_faddr.s_addr;
2133 
2134 	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2135 		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2136 
2137 	pcbporthash = &pcbinfo->ipi_porthashbase[
2138 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2139 
2140 	/*
2141 	 * Go through port list and look for a head for this lport.
2142 	 */
2143 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
2144 		if (phd->phd_port == inp->inp_lport)
2145 			break;
2146 	}
2147 	/*
2148 	 * If none exists, malloc one and tack it on.
2149 	 */
2150 	if (phd == NULL) {
2151 		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2152 		if (phd == NULL) {
2153 			return (ENOBUFS); /* XXX */
2154 		}
2155 		phd->phd_port = inp->inp_lport;
2156 		LIST_INIT(&phd->phd_pcblist);
2157 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2158 	}
2159 	inp->inp_phd = phd;
2160 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2161 	LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2162 	inp->inp_flags |= INP_INHASHLIST;
2163 #ifdef PCBGROUP
2164 	if (do_pcbgroup_update)
2165 		in_pcbgroup_update(inp);
2166 #endif
2167 	return (0);
2168 }
2169 
2170 /*
2171  * For now, there are two public interfaces to insert an inpcb into the hash
2172  * lists -- one that does update pcbgroups, and one that doesn't.  The latter
2173  * is used only in the TCP syncache, where in_pcbinshash is called before the
2174  * full 4-tuple is set for the inpcb, and we don't want to install in the
2175  * pcbgroup until later.
2176  *
2177  * XXXRW: This seems like a misfeature.  in_pcbinshash should always update
2178  * connection groups, and partially initialised inpcbs should not be exposed
2179  * to either reservation hash tables or pcbgroups.
2180  */
2181 int
2182 in_pcbinshash(struct inpcb *inp)
2183 {
2184 
2185 	return (in_pcbinshash_internal(inp, 1));
2186 }
2187 
2188 int
2189 in_pcbinshash_nopcbgroup(struct inpcb *inp)
2190 {
2191 
2192 	return (in_pcbinshash_internal(inp, 0));
2193 }
2194 
2195 /*
2196  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2197  * changed. NOTE: This does not handle the case of the lport changing (the
2198  * hashed port list would have to be updated as well), so the lport must
2199  * not change after in_pcbinshash() has been called.
2200  */
2201 void
2202 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2203 {
2204 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2205 	struct inpcbhead *head;
2206 	u_int32_t hashkey_faddr;
2207 
2208 	INP_WLOCK_ASSERT(inp);
2209 	INP_HASH_WLOCK_ASSERT(pcbinfo);
2210 
2211 	KASSERT(inp->inp_flags & INP_INHASHLIST,
2212 	    ("in_pcbrehash: !INP_INHASHLIST"));
2213 
2214 #ifdef INET6
2215 	if (inp->inp_vflag & INP_IPV6)
2216 		hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2217 	else
2218 #endif
2219 	hashkey_faddr = inp->inp_faddr.s_addr;
2220 
2221 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2222 		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2223 
2224 	LIST_REMOVE(inp, inp_hash);
2225 	LIST_INSERT_HEAD(head, inp, inp_hash);
2226 
2227 #ifdef PCBGROUP
2228 	if (m != NULL)
2229 		in_pcbgroup_update_mbuf(inp, m);
2230 	else
2231 		in_pcbgroup_update(inp);
2232 #endif
2233 }
2234 
2235 void
2236 in_pcbrehash(struct inpcb *inp)
2237 {
2238 
2239 	in_pcbrehash_mbuf(inp, NULL);
2240 }
2241 
2242 /*
2243  * Remove PCB from various lists.
2244  */
2245 static void
2246 in_pcbremlists(struct inpcb *inp)
2247 {
2248 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2249 
2250 #ifdef INVARIANTS
2251 	if (pcbinfo == &V_tcbinfo) {
2252 		INP_INFO_RLOCK_ASSERT(pcbinfo);
2253 	} else {
2254 		INP_INFO_WLOCK_ASSERT(pcbinfo);
2255 	}
2256 #endif
2257 
2258 	INP_WLOCK_ASSERT(inp);
2259 	INP_LIST_WLOCK_ASSERT(pcbinfo);
2260 
2261 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2262 	if (inp->inp_flags & INP_INHASHLIST) {
2263 		struct inpcbport *phd = inp->inp_phd;
2264 
2265 		INP_HASH_WLOCK(pcbinfo);
2266 		LIST_REMOVE(inp, inp_hash);
2267 		LIST_REMOVE(inp, inp_portlist);
2268 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2269 			LIST_REMOVE(phd, phd_hash);
2270 			free(phd, M_PCB);
2271 		}
2272 		INP_HASH_WUNLOCK(pcbinfo);
2273 		inp->inp_flags &= ~INP_INHASHLIST;
2274 	}
2275 	LIST_REMOVE(inp, inp_list);
2276 	pcbinfo->ipi_count--;
2277 #ifdef PCBGROUP
2278 	in_pcbgroup_remove(inp);
2279 #endif
2280 }
2281 
2282 /*
2283  * Check for alternatives when higher level complains
2284  * about service problems.  For now, invalidate cached
2285  * routing information.  If the route was created dynamically
2286  * (by a redirect), time to try a default gateway again.
2287  */
2288 void
2289 in_losing(struct inpcb *inp)
2290 {
2291 
2292 	if (inp->inp_route.ro_rt) {
2293 		RTFREE(inp->inp_route.ro_rt);
2294 		inp->inp_route.ro_rt = (struct rtentry *)NULL;
2295 	}
2296 	if (inp->inp_route.ro_lle)
2297 		LLE_FREE(inp->inp_route.ro_lle);	/* zeros ro_lle */
2298 	return;
2299 }
2300 
2301 /*
2302  * A set label operation has occurred at the socket layer, propagate the
2303  * label change into the in_pcb for the socket.
2304  */
2305 void
2306 in_pcbsosetlabel(struct socket *so)
2307 {
2308 #ifdef MAC
2309 	struct inpcb *inp;
2310 
2311 	inp = sotoinpcb(so);
2312 	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2313 
2314 	INP_WLOCK(inp);
2315 	SOCK_LOCK(so);
2316 	mac_inpcb_sosetlabel(so, inp);
2317 	SOCK_UNLOCK(so);
2318 	INP_WUNLOCK(inp);
2319 #endif
2320 }
2321 
2322 /*
2323  * ipport_tick runs once per second, determining if random port allocation
2324  * should be continued.  If more than ipport_randomcps ports have been
2325  * allocated in the last second, then we return to sequential port
2326  * allocation. We return to random allocation only once we drop below
2327  * ipport_randomcps for at least ipport_randomtime seconds.
2328  */
2329 static void
2330 ipport_tick(void *xtp)
2331 {
2332 	VNET_ITERATOR_DECL(vnet_iter);
2333 
2334 	VNET_LIST_RLOCK_NOSLEEP();
2335 	VNET_FOREACH(vnet_iter) {
2336 		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
2337 		if (V_ipport_tcpallocs <=
2338 		    V_ipport_tcplastcount + V_ipport_randomcps) {
2339 			if (V_ipport_stoprandom > 0)
2340 				V_ipport_stoprandom--;
2341 		} else
2342 			V_ipport_stoprandom = V_ipport_randomtime;
2343 		V_ipport_tcplastcount = V_ipport_tcpallocs;
2344 		CURVNET_RESTORE();
2345 	}
2346 	VNET_LIST_RUNLOCK_NOSLEEP();
2347 	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2348 }
2349 
2350 static void
2351 ip_fini(void *xtp)
2352 {
2353 
2354 	callout_stop(&ipport_tick_callout);
2355 }
2356 
2357 /*
2358  * The ipport_callout should start running at about the time we attach the
2359  * inet or inet6 domains.
2360  */
2361 static void
2362 ipport_tick_init(const void *unused __unused)
2363 {
2364 
2365 	/* Start ipport_tick. */
2366 	callout_init(&ipport_tick_callout, 1);
2367 	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2368 	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2369 		SHUTDOWN_PRI_DEFAULT);
2370 }
2371 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2372     ipport_tick_init, NULL);
2373 
2374 void
2375 inp_wlock(struct inpcb *inp)
2376 {
2377 
2378 	INP_WLOCK(inp);
2379 }
2380 
2381 void
2382 inp_wunlock(struct inpcb *inp)
2383 {
2384 
2385 	INP_WUNLOCK(inp);
2386 }
2387 
2388 void
2389 inp_rlock(struct inpcb *inp)
2390 {
2391 
2392 	INP_RLOCK(inp);
2393 }
2394 
2395 void
2396 inp_runlock(struct inpcb *inp)
2397 {
2398 
2399 	INP_RUNLOCK(inp);
2400 }
2401 
2402 #ifdef INVARIANTS
2403 void
2404 inp_lock_assert(struct inpcb *inp)
2405 {
2406 
2407 	INP_WLOCK_ASSERT(inp);
2408 }
2409 
2410 void
2411 inp_unlock_assert(struct inpcb *inp)
2412 {
2413 
2414 	INP_UNLOCK_ASSERT(inp);
2415 }
2416 #endif
2417 
2418 void
2419 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2420 {
2421 	struct inpcb *inp;
2422 
2423 	INP_INFO_WLOCK(&V_tcbinfo);
2424 	LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2425 		INP_WLOCK(inp);
2426 		func(inp, arg);
2427 		INP_WUNLOCK(inp);
2428 	}
2429 	INP_INFO_WUNLOCK(&V_tcbinfo);
2430 }
2431 
2432 struct socket *
2433 inp_inpcbtosocket(struct inpcb *inp)
2434 {
2435 
2436 	INP_WLOCK_ASSERT(inp);
2437 	return (inp->inp_socket);
2438 }
2439 
2440 struct tcpcb *
2441 inp_inpcbtotcpcb(struct inpcb *inp)
2442 {
2443 
2444 	INP_WLOCK_ASSERT(inp);
2445 	return ((struct tcpcb *)inp->inp_ppcb);
2446 }
2447 
2448 int
2449 inp_ip_tos_get(const struct inpcb *inp)
2450 {
2451 
2452 	return (inp->inp_ip_tos);
2453 }
2454 
2455 void
2456 inp_ip_tos_set(struct inpcb *inp, int val)
2457 {
2458 
2459 	inp->inp_ip_tos = val;
2460 }
2461 
2462 void
2463 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2464     uint32_t *faddr, uint16_t *fp)
2465 {
2466 
2467 	INP_LOCK_ASSERT(inp);
2468 	*laddr = inp->inp_laddr.s_addr;
2469 	*faddr = inp->inp_faddr.s_addr;
2470 	*lp = inp->inp_lport;
2471 	*fp = inp->inp_fport;
2472 }
2473 
2474 struct inpcb *
2475 so_sotoinpcb(struct socket *so)
2476 {
2477 
2478 	return (sotoinpcb(so));
2479 }
2480 
2481 struct tcpcb *
2482 so_sototcpcb(struct socket *so)
2483 {
2484 
2485 	return (sototcpcb(so));
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_HDRINCL) {
2547 		db_printf("%sINP_HDRINCL", comma ? ", " : "");
2548 		comma = 1;
2549 	}
2550 	if (inp_flags & INP_HIGHPORT) {
2551 		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2552 		comma = 1;
2553 	}
2554 	if (inp_flags & INP_LOWPORT) {
2555 		db_printf("%sINP_LOWPORT", comma ? ", " : "");
2556 		comma = 1;
2557 	}
2558 	if (inp_flags & INP_ANONPORT) {
2559 		db_printf("%sINP_ANONPORT", comma ? ", " : "");
2560 		comma = 1;
2561 	}
2562 	if (inp_flags & INP_RECVIF) {
2563 		db_printf("%sINP_RECVIF", comma ? ", " : "");
2564 		comma = 1;
2565 	}
2566 	if (inp_flags & INP_MTUDISC) {
2567 		db_printf("%sINP_MTUDISC", comma ? ", " : "");
2568 		comma = 1;
2569 	}
2570 	if (inp_flags & INP_RECVTTL) {
2571 		db_printf("%sINP_RECVTTL", comma ? ", " : "");
2572 		comma = 1;
2573 	}
2574 	if (inp_flags & INP_DONTFRAG) {
2575 		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2576 		comma = 1;
2577 	}
2578 	if (inp_flags & INP_RECVTOS) {
2579 		db_printf("%sINP_RECVTOS", comma ? ", " : "");
2580 		comma = 1;
2581 	}
2582 	if (inp_flags & IN6P_IPV6_V6ONLY) {
2583 		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2584 		comma = 1;
2585 	}
2586 	if (inp_flags & IN6P_PKTINFO) {
2587 		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2588 		comma = 1;
2589 	}
2590 	if (inp_flags & IN6P_HOPLIMIT) {
2591 		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2592 		comma = 1;
2593 	}
2594 	if (inp_flags & IN6P_HOPOPTS) {
2595 		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2596 		comma = 1;
2597 	}
2598 	if (inp_flags & IN6P_DSTOPTS) {
2599 		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2600 		comma = 1;
2601 	}
2602 	if (inp_flags & IN6P_RTHDR) {
2603 		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2604 		comma = 1;
2605 	}
2606 	if (inp_flags & IN6P_RTHDRDSTOPTS) {
2607 		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2608 		comma = 1;
2609 	}
2610 	if (inp_flags & IN6P_TCLASS) {
2611 		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2612 		comma = 1;
2613 	}
2614 	if (inp_flags & IN6P_AUTOFLOWLABEL) {
2615 		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2616 		comma = 1;
2617 	}
2618 	if (inp_flags & INP_TIMEWAIT) {
2619 		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
2620 		comma  = 1;
2621 	}
2622 	if (inp_flags & INP_ONESBCAST) {
2623 		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2624 		comma  = 1;
2625 	}
2626 	if (inp_flags & INP_DROPPED) {
2627 		db_printf("%sINP_DROPPED", comma ? ", " : "");
2628 		comma  = 1;
2629 	}
2630 	if (inp_flags & INP_SOCKREF) {
2631 		db_printf("%sINP_SOCKREF", comma ? ", " : "");
2632 		comma  = 1;
2633 	}
2634 	if (inp_flags & IN6P_RFC2292) {
2635 		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2636 		comma = 1;
2637 	}
2638 	if (inp_flags & IN6P_MTU) {
2639 		db_printf("IN6P_MTU%s", comma ? ", " : "");
2640 		comma = 1;
2641 	}
2642 }
2643 
2644 static void
2645 db_print_inpvflag(u_char inp_vflag)
2646 {
2647 	int comma;
2648 
2649 	comma = 0;
2650 	if (inp_vflag & INP_IPV4) {
2651 		db_printf("%sINP_IPV4", comma ? ", " : "");
2652 		comma  = 1;
2653 	}
2654 	if (inp_vflag & INP_IPV6) {
2655 		db_printf("%sINP_IPV6", comma ? ", " : "");
2656 		comma  = 1;
2657 	}
2658 	if (inp_vflag & INP_IPV6PROTO) {
2659 		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2660 		comma  = 1;
2661 	}
2662 }
2663 
2664 static void
2665 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2666 {
2667 
2668 	db_print_indent(indent);
2669 	db_printf("%s at %p\n", name, inp);
2670 
2671 	indent += 2;
2672 
2673 	db_print_indent(indent);
2674 	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2675 
2676 	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2677 
2678 	db_print_indent(indent);
2679 	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
2680 	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2681 
2682 	db_print_indent(indent);
2683 	db_printf("inp_label: %p   inp_flags: 0x%x (",
2684 	   inp->inp_label, inp->inp_flags);
2685 	db_print_inpflags(inp->inp_flags);
2686 	db_printf(")\n");
2687 
2688 	db_print_indent(indent);
2689 	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
2690 	    inp->inp_vflag);
2691 	db_print_inpvflag(inp->inp_vflag);
2692 	db_printf(")\n");
2693 
2694 	db_print_indent(indent);
2695 	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
2696 	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2697 
2698 	db_print_indent(indent);
2699 #ifdef INET6
2700 	if (inp->inp_vflag & INP_IPV6) {
2701 		db_printf("in6p_options: %p   in6p_outputopts: %p   "
2702 		    "in6p_moptions: %p\n", inp->in6p_options,
2703 		    inp->in6p_outputopts, inp->in6p_moptions);
2704 		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
2705 		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2706 		    inp->in6p_hops);
2707 	} else
2708 #endif
2709 	{
2710 		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
2711 		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2712 		    inp->inp_options, inp->inp_moptions);
2713 	}
2714 
2715 	db_print_indent(indent);
2716 	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
2717 	    (uintmax_t)inp->inp_gencnt);
2718 }
2719 
2720 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2721 {
2722 	struct inpcb *inp;
2723 
2724 	if (!have_addr) {
2725 		db_printf("usage: show inpcb <addr>\n");
2726 		return;
2727 	}
2728 	inp = (struct inpcb *)addr;
2729 
2730 	db_print_inpcb(inp, "inpcb", 0);
2731 }
2732 #endif /* DDB */
2733