xref: /dflybsd-src/sys/netinet/in_pcb.c (revision 6cd7b6532631428e69a83c882781e039f88550f6)
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993, 1995
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
63  * $FreeBSD: src/sys/netinet/in_pcb.c,v 1.59.2.27 2004/01/02 04:06:42 ambrisko Exp $
64  */
65 
66 #include "opt_inet6.h"
67 
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/malloc.h>
71 #include <sys/mbuf.h>
72 #include <sys/domain.h>
73 #include <sys/protosw.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/proc.h>
77 #include <sys/caps.h>
78 #include <sys/jail.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 
82 #include <sys/socketvar2.h>
83 #include <sys/msgport2.h>
84 
85 #include <machine/limits.h>
86 
87 #include <net/if.h>
88 #include <net/if_types.h>
89 #include <net/route.h>
90 #include <net/netisr2.h>
91 #include <net/toeplitz2.h>
92 
93 #include <netinet/in.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip_var.h>
97 #ifdef INET6
98 #include <netinet/ip6.h>
99 #include <netinet6/ip6_var.h>
100 #endif /* INET6 */
101 
102 #define INP_LOCALGROUP_SIZMIN	8
103 #define INP_LOCALGROUP_SIZMAX	256
104 
105 static struct inpcb *in_pcblookup_local(struct inpcbporthead *porthash,
106 		struct in_addr laddr, u_int lport_arg, int wild_okay,
107 		struct ucred *cred);
108 
109 struct in_addr zeroin_addr;
110 
111 /*
112  * These configure the range of local port addresses assigned to
113  * "unspecified" outgoing connections/packets/whatever.
114  */
115 int ipport_lowfirstauto = IPPORT_RESERVED - 1;	/* 1023 */
116 int ipport_lowlastauto = IPPORT_RESERVEDSTART;	/* 600 */
117 
118 int ipport_firstauto = IPPORT_RESERVED;		/* 1024 */
119 int ipport_lastauto = IPPORT_USERRESERVED;	/* 5000 */
120 
121 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;	/* 49152 */
122 int ipport_hilastauto = IPPORT_HILASTAUTO;	/* 65535 */
123 
124 #define RANGECHK(var, min, max) \
125 	if ((var) < (min)) { (var) = (min); } \
126 	else if ((var) > (max)) { (var) = (max); }
127 
128 int udpencap_enable = 1;	/* enabled by default */
129 int udpencap_port = 4500;	/* triggers decapsulation */
130 
131 /*
132  * Per-netisr inpcb markers.
133  * NOTE: they should only be used in netisrs.
134  */
135 static struct inpcb		*in_pcbmarkers;
136 static struct inpcontainer	*in_pcbcontainer_markers;
137 
138 static int
139 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
140 {
141 	int error;
142 
143 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
144 	if (!error) {
145 		RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
146 		RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
147 
148 		RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
149 		RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
150 
151 		RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
152 		RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
153 	}
154 	return (error);
155 }
156 
157 #undef RANGECHK
158 
159 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
160 
161 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
162 	   &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
163 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
164 	   &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
165 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
166 	   &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
167 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
168 	   &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
169 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
170 	   &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
171 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
172 	   &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
173 
174 /* Initialized by ip_init() */
175 int ip_porthash_trycount;
176 SYSCTL_INT(_net_inet_ip, OID_AUTO, porthash_trycount, CTLFLAG_RW,
177     &ip_porthash_trycount, 0,
178     "Number of tries to find local port matching hash of 4-tuple");
179 
180 /*
181  * in_pcb.c: manage the Protocol Control Blocks.
182  *
183  * NOTE: It is assumed that most of these functions will be called from
184  * a critical section.  XXX - There are, unfortunately, a few exceptions
185  * to this rule that should be fixed.
186  *
187  * NOTE: The caller should initialize the cpu field to the cpu running the
188  * protocol stack associated with this inpcbinfo.
189  */
190 
191 void
192 in_pcbinfo_init(struct inpcbinfo *pcbinfo, int cpu, boolean_t shared)
193 {
194 	KASSERT(cpu >= 0 && cpu < netisr_ncpus, ("invalid cpu%d", cpu));
195 	pcbinfo->cpu = cpu;
196 
197 	LIST_INIT(&pcbinfo->pcblisthead);
198 	pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave), M_PCB,
199 				    M_WAITOK | M_ZERO);
200 
201 	if (shared) {
202 		pcbinfo->infotoken = kmalloc(sizeof(struct lwkt_token),
203 		    M_PCB, M_WAITOK);
204 		lwkt_token_init(pcbinfo->infotoken, "infotoken");
205 	} else {
206 		pcbinfo->infotoken = NULL;
207 	}
208 }
209 
210 void
211 in_pcbportinfo_set(struct inpcbinfo *pcbinfo, struct inpcbportinfo *portinfo,
212     int portinfo_cnt)
213 {
214 
215 	KASSERT(portinfo_cnt > 0, ("invalid portinfo_cnt %d", portinfo_cnt));
216 	pcbinfo->portinfo = portinfo;
217 	pcbinfo->portinfo_cnt = portinfo_cnt;
218 }
219 
220 struct baddynamicports baddynamicports;
221 
222 /*
223  * Check if the specified port is invalid for dynamic allocation.
224  */
225 int
226 in_baddynamic(u_int16_t port, u_int16_t proto)
227 {
228 	switch (proto) {
229 	case IPPROTO_TCP:
230 		return (DP_ISSET(baddynamicports.tcp, port));
231 	case IPPROTO_UDP:
232 		return (DP_ISSET(baddynamicports.udp, port));
233 	default:
234 		return (0);
235 	}
236 }
237 
238 void
239 in_pcbonlist(struct inpcb *inp)
240 {
241 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
242 
243 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
244 	    ("not in the correct netisr"));
245 	KASSERT((inp->inp_flags & INP_ONLIST) == 0, ("already on pcblist"));
246 	inp->inp_flags |= INP_ONLIST;
247 
248 	GET_PCBINFO_TOKEN(pcbinfo);
249 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
250 	pcbinfo->ipi_count++;
251 	REL_PCBINFO_TOKEN(pcbinfo);
252 }
253 
254 void
255 in_pcbofflist(struct inpcb *inp)
256 {
257 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
258 
259 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
260 	    ("not in the correct netisr"));
261 	KASSERT(inp->inp_flags & INP_ONLIST, ("not on pcblist"));
262 	inp->inp_flags &= ~INP_ONLIST;
263 
264 	GET_PCBINFO_TOKEN(pcbinfo);
265 	LIST_REMOVE(inp, inp_list);
266 	KASSERT(pcbinfo->ipi_count > 0,
267 	    ("invalid inpcb count %d", pcbinfo->ipi_count));
268 	pcbinfo->ipi_count--;
269 	REL_PCBINFO_TOKEN(pcbinfo);
270 }
271 
272 /*
273  * Allocate a PCB and associate it with the socket.
274  */
275 int
276 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
277 {
278 	struct inpcb *inp;
279 
280 	inp = kmalloc(pcbinfo->ipi_size, M_PCB, M_WAITOK|M_ZERO|M_NULLOK);
281 	if (inp == NULL)
282 		return (ENOMEM);
283 	inp->inp_lgrpindex = -1;
284 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
285 	inp->inp_pcbinfo = pcbinfo;
286 	inp->inp_socket = so;
287 #ifdef INET6
288 	if (INP_CHECK_SOCKAF(so, AF_INET6)) {
289 		if (ip6_auto_flowlabel)
290 			inp->inp_flags |= IN6P_AUTOFLOWLABEL;
291 		inp->inp_af = AF_INET6;
292 	} else
293 #endif
294 	inp->inp_af = AF_INET;
295 	soreference(so);
296 	so->so_pcb = inp;
297 
298 	in_pcbonlist(inp);
299 	return (0);
300 }
301 
302 /*
303  * Unlink a pcb with the intention of moving it to another cpu with a
304  * different pcbinfo.  While unlinked nothing should attempt to dereference
305  * inp_pcbinfo, NULL it out so we assert if it does.
306  */
307 void
308 in_pcbunlink_flags(struct inpcb *inp, struct inpcbinfo *pcbinfo, int flags)
309 {
310 	KASSERT(inp->inp_pcbinfo == pcbinfo, ("pcbinfo mismatch"));
311 	KASSERT((inp->inp_flags & (flags | INP_CONNECTED)) == 0,
312 	    ("already linked"));
313 
314 	in_pcbofflist(inp);
315 	inp->inp_pcbinfo = NULL;
316 }
317 
318 void
319 in_pcbunlink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
320 {
321 	in_pcbunlink_flags(inp, pcbinfo, INP_WILDCARD);
322 }
323 
324 /*
325  * Relink a pcb into a new pcbinfo.
326  */
327 void
328 in_pcblink_flags(struct inpcb *inp, struct inpcbinfo *pcbinfo, int flags)
329 {
330 	KASSERT(inp->inp_pcbinfo == NULL, ("has pcbinfo"));
331 	KASSERT((inp->inp_flags & (flags | INP_CONNECTED)) == 0,
332 	    ("already linked"));
333 
334 	inp->inp_pcbinfo = pcbinfo;
335 	in_pcbonlist(inp);
336 }
337 
338 void
339 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
340 {
341 	return in_pcblink_flags(inp, pcbinfo, INP_WILDCARD);
342 }
343 
344 static boolean_t
345 in_pcbporthash_update(struct inpcbportinfo *portinfo,
346     struct inpcb *inp, u_short lport, struct ucred *cred, int wild)
347 {
348 	struct inpcbporthead *porthash;
349 
350 	/*
351 	 * This has to be atomic.  If the porthash is shared across multiple
352 	 * protocol threads, e.g. tcp and udp, then the token must be held.
353 	 */
354 	porthash = in_pcbporthash_head(portinfo, lport);
355 	GET_PORTHASH_TOKEN(porthash);
356 
357 	if (in_pcblookup_local(porthash, inp->inp_laddr, lport, wild, cred)) {
358 		REL_PORTHASH_TOKEN(porthash);
359 		return FALSE;
360 	}
361 	inp->inp_lport = lport;
362 	in_pcbinsporthash(porthash, inp);
363 
364 	REL_PORTHASH_TOKEN(porthash);
365 	return TRUE;
366 }
367 
368 static int
369 in_pcbsetlport(struct inpcb *inp, int wild, struct ucred *cred)
370 {
371 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
372 	struct inpcbportinfo *portinfo;
373 	u_short first, last, lport, step, first0, last0;
374 	int count, error;
375 	int portinfo_first, portinfo_idx;
376 	uint32_t cut;
377 
378 	/*
379 	 * We force matches against wildcard ports in order to
380 	 * avoid auto-assigning lport to such ports, which would
381 	 * cause problems for same-machine connect()s.
382 	 */
383 	wild = INPLOOKUP_WILDCARD;
384 
385 	inp->inp_flags |= INP_ANONPORT;
386 
387 	step = pcbinfo->portinfo_cnt;
388 	portinfo_first = mycpuid % pcbinfo->portinfo_cnt;
389 	portinfo_idx = portinfo_first;
390 
391 	if (inp->inp_flags & INP_HIGHPORT) {
392 		first0 = ipport_hifirstauto;	/* sysctl */
393 		last0  = ipport_hilastauto;
394 	} else if (inp->inp_flags & INP_LOWPORT) {
395 		if (cred &&
396 		    (error = caps_priv_check(cred, SYSCAP_NONET_RESPORT)))
397 		{
398 			inp->inp_laddr.s_addr = INADDR_ANY;
399 			return error;
400 		}
401 		first0 = ipport_lowfirstauto;	/* 1023 */
402 		last0  = ipport_lowlastauto;	/* 600 */
403 	} else {
404 		first0 = ipport_firstauto;	/* sysctl */
405 		last0  = ipport_lastauto;
406 	}
407 	if (first0 > last0) {
408 		lport = last0;
409 		last0 = first0;
410 		first0 = lport;
411 	}
412 	KKASSERT(last0 >= first0);
413 
414 	cut = karc4random();
415 loop:
416 	portinfo = &pcbinfo->portinfo[portinfo_idx];
417 	first = first0;
418 	last = last0;
419 
420 	/*
421 	 * Simple check to ensure all ports are not used up causing
422 	 * a deadlock here.
423 	 */
424 	in_pcbportrange(&last, &first, portinfo->offset, step);
425 	lport = last - first;
426 	count = lport / step;
427 
428 	lport = rounddown(cut % lport, step) + first;
429 	KKASSERT(lport % step == portinfo->offset);
430 
431 	for (;;) {
432 		if (count-- < 0) {	/* completely used? */
433 			error = EADDRNOTAVAIL;
434 			break;
435 		}
436 
437 		if (__predict_false(lport < first || lport > last)) {
438 			lport = first;
439 			KKASSERT(lport % step == portinfo->offset);
440 		}
441 
442 		if (in_pcbporthash_update(portinfo, inp, htons(lport),
443 					  cred, wild)) {
444 			error = 0;
445 			break;
446 		}
447 
448 		lport += step;
449 		KKASSERT(lport % step == portinfo->offset);
450 	}
451 
452 	if (error) {
453 		/* Try next portinfo */
454 		portinfo_idx++;
455 		portinfo_idx %= pcbinfo->portinfo_cnt;
456 		if (portinfo_idx != portinfo_first)
457 			goto loop;
458 		inp->inp_laddr.s_addr = INADDR_ANY;
459 	}
460 	return error;
461 }
462 
463 static __inline struct inpcbporthead *
464 OBTAIN_LPORTHASH_TOKEN(struct inpcbinfo *pcbinfo, u_short lport)
465 {
466 	struct inpcbportinfo *portinfo;
467 	struct inpcbporthead *porthash;
468 	u_short lport_ho = ntohs(lport);
469 
470 	/*
471 	 * Locate the proper portinfo based on lport
472 	 */
473 	portinfo = &pcbinfo->portinfo[lport_ho % pcbinfo->portinfo_cnt];
474 	KKASSERT((lport_ho % pcbinfo->portinfo_cnt) == portinfo->offset);
475 
476 	porthash = in_pcbporthash_head(portinfo, lport);
477 	GET_PORTHASH_TOKEN(porthash);
478 
479 	return porthash;
480 }
481 
482 static int
483 in_pcbbind_laddr(struct sockaddr_in *sin, struct in_addr *laddr,
484     struct thread *td)
485 {
486 	struct sockaddr_in jsin;
487 
488 	if (!prison_replace_wildcards(td, (struct sockaddr *)sin))
489 		return (EINVAL);
490 
491 	if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
492 	    sin->sin_addr.s_addr != INADDR_ANY) {
493 		sin->sin_port = 0;		/* yech... */
494 		bzero(&sin->sin_zero, sizeof sin->sin_zero);
495 		if (ifa_ifwithaddr((struct sockaddr *)sin) == NULL)
496 			return (EADDRNOTAVAIL);
497 	}
498 
499 	*laddr = sin->sin_addr;
500 
501 	jsin.sin_family = AF_INET;
502 	jsin.sin_addr.s_addr = laddr->s_addr;
503 	if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
504 		laddr->s_addr = INADDR_ANY;
505 		return (EINVAL);
506 	}
507 	laddr->s_addr = jsin.sin_addr.s_addr;
508 
509 	return (0);
510 }
511 
512 static int
513 in_pcbbind_laddrport_check(const struct socket *so, struct sockaddr_in *sin,
514     struct inpcbporthead *porthash, int wild, struct ucred *cred,
515     struct thread *td)
516 {
517 	int reuseport = (so->so_options & SO_REUSEPORT);
518 	struct inpcb *t;
519 
520 	ASSERT_PORTHASH_TOKEN_HELD(porthash);
521 
522 	if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
523 		/*
524 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
525 		 * allow complete duplication of binding if
526 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
527 		 * and a multicast address is bound on both
528 		 * new and duplicated sockets.
529 		 */
530 		if (so->so_options & SO_REUSEADDR)
531 			reuseport = SO_REUSEADDR | SO_REUSEPORT;
532 	}
533 
534 	if (so->so_cred->cr_uid != 0 &&
535 	    !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
536 		t = in_pcblookup_local(porthash, sin->sin_addr, sin->sin_port,
537 				       INPLOOKUP_WILDCARD, cred);
538 		if (t && t->inp_socket != so &&
539 		    (so->so_cred->cr_uid != t->inp_socket->so_cred->cr_uid))
540 			return (EADDRINUSE);
541 	}
542 	if (cred && !prison_replace_wildcards(td, (struct sockaddr *)sin))
543 		return (EADDRNOTAVAIL);
544 
545 	/*
546 	 * When binding to a local port if the best match is against
547 	 * an accepted socket we generally want to allow the binding.
548 	 * This means that there is no longer any specific socket
549 	 * bound or bound for listening.
550 	 */
551 	t = in_pcblookup_local(porthash, sin->sin_addr, sin->sin_port,
552 			       wild, cred);
553 	if (t && t->inp_socket != so &&
554 	    (reuseport & t->inp_socket->so_options) == 0 &&
555 	    (t->inp_socket->so_state & SS_ACCEPTMECH) == 0)
556 		return (EADDRINUSE);
557 
558 	return (0);
559 }
560 
561 int
562 in_pcbsrcaddr_check(const struct inpcb *inp, struct sockaddr_in *sin,
563     struct in_addr *laddr, struct thread *td)
564 {
565 	const struct socket *so = inp->inp_socket;
566 	struct inpcbporthead *porthash;
567 	struct ucred *cred = NULL;
568 	int wild = 0;
569 	int error;
570 
571 	/* inp must be bound beforehand. */
572 	KKASSERT(inp->inp_lport != 0);
573 	KKASSERT(sin->sin_len == sizeof(*sin));
574 
575 	if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
576 		wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
577 	if (td->td_proc)
578 		cred = td->td_proc->p_ucred;
579 
580 	/* Always use inp_lport */
581 	sin->sin_port = inp->inp_lport;
582 
583 	error = in_pcbbind_laddr(sin, laddr, td);
584 	if (error)
585 		return (error);
586 
587 	if (IN_MULTICAST(ntohl(laddr->s_addr))) {
588 		/* Unlike bind, multicast src address is not allowed. */
589 		return (EINVAL);
590 	}
591 
592 	if (inp->inp_laddr.s_addr == laddr->s_addr) {
593 		/*
594 		 * src address is same as what we bound to.
595 		 *
596 		 * inp_laddr == INADDR_ANY && srcaddr == INADDR_ANY
597 		 * is allowed, which does not really matter.
598 		 */
599 		return (0);
600 	} else if (inp->inp_laddr.s_addr != INADDR_ANY &&
601 	    !IN_MULTICAST(ntohl(inp->inp_laddr.s_addr))) {
602 		/* Already bound to a specific address */
603 		return (EINVAL);
604 	}
605 
606 	/*
607 	 * This has to be atomic.  If the porthash is shared across
608 	 * multiple protocol threads, e.g. tcp and udp then the token
609 	 * must be held.
610 	 */
611 	porthash = OBTAIN_LPORTHASH_TOKEN(inp->inp_pcbinfo, inp->inp_lport);
612 
613 	/*
614 	 * Restore the sin_port whacked by in_pcbbind_ladddr();
615 	 * sin->sin_port is checked by in_pcbbind_laddrport_check().
616 	 */
617 	sin->sin_port = inp->inp_lport;
618 
619 	error = in_pcbbind_laddrport_check(so, sin, porthash, wild, cred, td);
620 	if (error)
621 		laddr->s_addr = INADDR_ANY;
622 
623 	REL_PORTHASH_TOKEN(porthash);
624 	return (error);
625 }
626 
627 int
628 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
629 {
630 	const struct socket *so = inp->inp_socket;
631 	struct ucred *cred = NULL;
632 	int wild = 0;
633 
634 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
635 		return (EINVAL);	/* already bound */
636 
637 	if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
638 		wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
639 	if (td->td_proc)
640 		cred = td->td_proc->p_ucred;
641 
642 	if (nam != NULL) {
643 		struct sockaddr_in *sin = (struct sockaddr_in *)nam;
644 		struct inpcbporthead *porthash;
645 		u_short lport;
646 		int error;
647 
648 		if (nam->sa_len != sizeof *sin)
649 			return (EINVAL);
650 #ifdef notdef
651 		/*
652 		 * We should check the family, but old programs
653 		 * incorrectly fail to initialize it.
654 		 */
655 		if (sin->sin_family != AF_INET)
656 			return (EAFNOSUPPORT);
657 #endif
658 
659 		/*
660 		 * Save sin_port for later use, since it will
661 		 * be whacked by in_pcbbind_laddr().
662 		 */
663 		lport = sin->sin_port;
664 
665 		error = in_pcbbind_laddr(sin, &inp->inp_laddr, td);
666 		if (error)
667 			return (error);
668 
669 		if (lport == 0) {
670 			/* Auto-select local port */
671 			return in_pcbsetlport(inp, wild, cred);
672 		}
673 
674 		/* GROSS */
675 		if (ntohs(lport) < IPPORT_RESERVED && cred &&
676 		    (error = caps_priv_check(cred, SYSCAP_NONET_RESPORT)))
677 		 {
678 			inp->inp_laddr.s_addr = INADDR_ANY;
679 			return (error);
680 		}
681 
682 		/*
683 		 * This has to be atomic.  If the porthash is shared across
684 		 * multiple protocol threads, e.g. tcp and udp then the token
685 		 * must be held.
686 		 */
687 		porthash = OBTAIN_LPORTHASH_TOKEN(inp->inp_pcbinfo, lport);
688 
689 		/*
690 		 * Restore the sin_port whacked by in_pcbbind_ladddr();
691 		 * sin->sin_port is checked by in_pcbbind_laddrport_check().
692 		 */
693 		sin->sin_port = lport;
694 
695 		error = in_pcbbind_laddrport_check(so, sin, porthash,
696 						   wild, cred, td);
697 		if (error) {
698 			inp->inp_laddr.s_addr = INADDR_ANY;
699 			goto done;
700 		}
701 
702 		inp->inp_lport = lport;
703 		in_pcbinsporthash(porthash, inp);
704 		error = 0;
705 done:
706 		REL_PORTHASH_TOKEN(porthash);
707 		return (error);
708 	} else {
709 		struct sockaddr_in jsin;
710 
711 		jsin.sin_family = AF_INET;
712 		jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
713 		if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
714 			inp->inp_laddr.s_addr = INADDR_ANY;
715 			return (EINVAL);
716 		}
717 		inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
718 
719 		return in_pcbsetlport(inp, wild, cred);
720 	}
721 }
722 
723 /*
724  * Lookup a PCB based on the local and remote address and port.
725  *
726  * This function is only used when scanning for a free port.
727  */
728 static struct inpcb *
729 in_pcblookup_localremote(struct inpcbporthead *porthash, struct in_addr laddr,
730 			 u_short lport, struct in_addr faddr, u_short fport,
731 			 struct ucred *cred)
732 {
733 	struct inpcb *inp;
734 	struct inpcbport *phd;
735 	struct inpcb *match = NULL;
736 	struct prison *pscan;
737 	struct prison *pr;
738 
739 	/*
740 	 * If the porthashbase is shared across several cpus, it must
741 	 * have been locked.
742 	 */
743 	ASSERT_PORTHASH_TOKEN_HELD(porthash);
744 
745 	/*
746 	 * Best fit PCB lookup.
747 	 *
748 	 * First see if this local port is in use by looking on the
749 	 * port hash list.
750 	 */
751 	LIST_FOREACH(phd, porthash, phd_hash) {
752 		if (phd->phd_port == lport)
753 			break;
754 	}
755 	if (phd != NULL) {
756 		pr = cred ? cred->cr_prison : NULL;
757 
758 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
759 #ifdef INET6
760 			if (!INP_ISIPV4(inp))
761 				continue;
762 #endif
763 			if (inp->inp_laddr.s_addr == INADDR_ANY) {
764 				if (inp->inp_socket && inp->inp_socket->so_cred)
765 					pscan = inp->inp_socket->so_cred->cr_prison;
766 				else
767 					pscan = NULL;
768 				if (pr != pscan)
769 					continue;
770 			} else {
771 				if (inp->inp_laddr.s_addr != laddr.s_addr)
772 					continue;
773 			}
774 
775 			if (inp->inp_faddr.s_addr != INADDR_ANY &&
776 			    inp->inp_faddr.s_addr != faddr.s_addr)
777 				continue;
778 
779 			if (inp->inp_fport != 0 && inp->inp_fport != fport)
780 				continue;
781 
782 			match = inp;
783 			break;
784 		}
785 	}
786 	return (match);
787 }
788 
789 static boolean_t
790 in_pcbporthash_update4(struct inpcbportinfo *portinfo, struct inpcb *inp,
791 		       u_short lport, const struct sockaddr_in *sin,
792 		       struct ucred *cred)
793 {
794 	struct inpcbporthead *porthash;
795 
796 	/*
797 	 * This has to be atomic.  If the porthash is shared across multiple
798 	 * protocol threads, e.g. tcp and udp, then the token must be held.
799 	 */
800 	porthash = in_pcbporthash_head(portinfo, lport);
801 	GET_PORTHASH_TOKEN(porthash);
802 
803 	if (in_pcblookup_localremote(porthash, inp->inp_laddr, lport,
804 				     sin->sin_addr, sin->sin_port, cred)) {
805 		REL_PORTHASH_TOKEN(porthash);
806 		return FALSE;
807 	}
808 	inp->inp_lport = lport;
809 	in_pcbinsporthash(porthash, inp);
810 
811 	REL_PORTHASH_TOKEN(porthash);
812 	return TRUE;
813 }
814 
815 int
816 in_pcbbind_remote(struct inpcb *inp, const struct sockaddr *remote,
817     struct thread *td)
818 {
819 	struct proc *p = td->td_proc;
820 	const struct sockaddr_in *sin = (const struct sockaddr_in *)remote;
821 	struct sockaddr_in jsin;
822 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
823 	struct ucred *cred = NULL;
824 	u_short first, last, lport;
825 	int count, hash_count;
826 	int error, selfconn = 0;
827 	int cpuid = mycpuid;
828 	uint32_t hash_base = 0, hash;
829 
830 	ASSERT_NETISR_NCPUS(cpuid);
831 
832 	if (TAILQ_EMPTY(&in_ifaddrheads[cpuid])) /* XXX broken! */
833 		return (EADDRNOTAVAIL);
834 
835 	KKASSERT(inp->inp_laddr.s_addr != INADDR_ANY);
836 	if (inp->inp_lport != 0)
837 		return (EINVAL);	/* already bound */
838 
839 	KKASSERT(p);
840 	cred = p->p_ucred;
841 
842 	jsin.sin_family = AF_INET;
843 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
844 	if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
845 		inp->inp_laddr.s_addr = INADDR_ANY;
846 		return (EINVAL);
847 	}
848 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
849 
850 	hash_count = ip_porthash_trycount;
851 	if (hash_count > 0) {
852 		hash_base = toeplitz_piecemeal_addr(sin->sin_addr.s_addr) ^
853 		    toeplitz_piecemeal_addr(inp->inp_laddr.s_addr) ^
854 		    toeplitz_piecemeal_port(sin->sin_port);
855 	} else {
856 		hash_count = 0;
857 	}
858 
859 	inp->inp_flags |= INP_ANONPORT;
860 
861 	if (inp->inp_flags & INP_HIGHPORT) {
862 		first = ipport_hifirstauto;	/* sysctl */
863 		last  = ipport_hilastauto;
864 	} else if (inp->inp_flags & INP_LOWPORT) {
865 		if (cred &&
866 		    (error = caps_priv_check(cred, SYSCAP_NONET_RESPORT)))
867 		 {
868 			inp->inp_laddr.s_addr = INADDR_ANY;
869 			return (error);
870 		}
871 		first = ipport_lowfirstauto;	/* 1023 */
872 		last = ipport_lowlastauto;	/* 600 */
873 	} else {
874 		first = ipport_firstauto;	/* sysctl */
875 		last  = ipport_lastauto;
876 	}
877 	if (first > last) {
878 		lport = last;
879 		last = first;
880 		first = lport;
881 	}
882 	KKASSERT(last >= first);
883 
884 	count = last - first;
885 	lport = (karc4random() % count) + first;
886 	count += hash_count;
887 
888 	/*
889 	 * Simple check to ensure all ports are not used up causing
890 	 * a deadlock here.
891 	 */
892 	for (;;) {
893 		u_short lport_no;
894 
895 		if (count-- < 0) {	/* completely used? */
896 			error = EADDRNOTAVAIL;
897 			break;
898 		}
899 
900 		if (__predict_false(lport < first || lport > last))
901 			lport = first;
902 		lport_no = htons(lport);
903 
904 		/* This could happen on loopback interface */
905 		if (__predict_false(sin->sin_port == lport_no &&
906 		    sin->sin_addr.s_addr == inp->inp_laddr.s_addr)) {
907 			if (!selfconn) {
908 				++count; /* don't count this try */
909 				selfconn = 1;
910 			}
911 			goto next;
912 		}
913 
914 		if (hash_count) {
915 			--hash_count;
916 			hash = hash_base ^
917 			    toeplitz_piecemeal_port(lport_no);
918 			if (netisr_hashcpu(hash) != cpuid && hash_count)
919 				goto next;
920 		}
921 
922 		if (in_pcbporthash_update4(
923 			    &pcbinfo->portinfo[lport % pcbinfo->portinfo_cnt],
924 			    inp, lport_no, sin, cred)) {
925 			error = 0;
926 			break;
927 		}
928 next:
929 		++lport;
930 	}
931 
932 	if (error)
933 		inp->inp_laddr.s_addr = INADDR_ANY;
934 	return (error);
935 }
936 
937 /*
938  * Figure out the local interface address to pair against the requested
939  * target address, as well as validate the target address.
940  */
941 int
942 in_pcbladdr_find(struct inpcb *inp, struct sockaddr *nam,
943 		 struct sockaddr_in **plocal_sin, struct thread *td, int find)
944 {
945 	struct in_ifaddr_container *iac;
946 	struct in_ifaddr *ia;
947 	struct ucred *cred = NULL;
948 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
949 	struct sockaddr *jsin;
950 	struct prison *pr;
951 	struct route *ro;
952 	int alloc_route = 0;
953 
954 	if (nam->sa_len != sizeof *sin)
955 		return (EINVAL);
956 	if (sin->sin_family != AF_INET)
957 		return (EAFNOSUPPORT);
958 	if (sin->sin_port == 0)
959 		return (EADDRNOTAVAIL);
960 
961 	/*
962 	 * Are we in a jail?
963 	 */
964 	pr = NULL;
965 	if (td && td->td_proc && td->td_proc->p_ucred)
966 		cred = td->td_proc->p_ucred;
967 	if (cred)
968 		pr = cred->cr_prison;
969 
970 	/*
971 	 * If the destination address is INADDR_ANY then use the primary
972 	 * local address.
973 	 *
974 	 * If the supplied address is INADDR_BROADCAST, and the primary
975 	 * interface supports broadcast, choose the broadcast address for
976 	 * that interface.
977 	 *
978 	 * If jailed, locate an interface address acceptable to the jail.
979 	 */
980 	if (sin->sin_addr.s_addr == INADDR_ANY) {
981 		TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
982 			ia = iac->ia;
983 			if (pr == NULL ||
984 			    jailed_ip(pr, sintosa(&ia->ia_addr))) {
985 				sin->sin_addr = IA_SIN(ia)->sin_addr;
986 				break;
987 			}
988 		}
989 	} else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST) {
990 		TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
991 			ia = iac->ia;
992 			if ((pr == NULL ||
993 			     jailed_ip(pr, sintosa(&ia->ia_addr))) &&
994 			    (iac->ia->ia_ifp->if_flags & IFF_BROADCAST)) {
995 				sin->sin_addr =
996 				    satosin(&ia->ia_broadaddr)->sin_addr;
997 				break;
998 			}
999 		}
1000 	}
1001 
1002 	/*
1003 	 * If asked to do a search, use the cached route or do a route table
1004 	 * lookup to try to find an acceptable local interface IP.
1005 	 */
1006 	if (find == 0)
1007 		return 0;
1008 
1009 	ia = NULL;
1010 
1011 	/*
1012 	 * If we have a cached route, check to see if it is acceptable.
1013 	 * If not, free it.
1014 	 */
1015 	ro = &inp->inp_route;
1016 	if (ro->ro_rt &&
1017 	    (!(ro->ro_rt->rt_flags & RTF_UP) ||
1018 	     ro->ro_dst.sa_family != AF_INET ||
1019 	     satosin(&ro->ro_dst)->sin_addr.s_addr !=
1020 			      sin->sin_addr.s_addr ||
1021 	     inp->inp_socket->so_options & SO_DONTROUTE)) {
1022 		RTFREE(ro->ro_rt);
1023 		ro->ro_rt = NULL;
1024 	}
1025 
1026 	/*
1027 	 * If we do not have a route, construct one and do a lookup,
1028 	 * unless we are forbidden to do so.
1029 	 *
1030 	 * Note that we should check the address family of the cached
1031 	 * destination, in case of sharing the cache with IPv6.
1032 	 */
1033 	if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
1034 	    (ro->ro_rt == NULL || ro->ro_rt->rt_ifp == NULL)) {
1035 		bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
1036 		ro->ro_dst.sa_family = AF_INET;
1037 		ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
1038 		((struct sockaddr_in *)&ro->ro_dst)->sin_addr = sin->sin_addr;
1039 		rtalloc(ro);
1040 		alloc_route = 1;
1041 	}
1042 
1043 	/*
1044 	 * If we found a route, use the address corresponding to the
1045 	 * outgoing interface.
1046 	 *
1047 	 * If jailed, try to find a compatible address on the outgoing
1048 	 * interface.
1049 	 */
1050 	if (ro->ro_rt) {
1051 		ia = ifatoia(ro->ro_rt->rt_ifa);
1052 		if (pr == NULL)
1053 			goto skip;
1054 		if (jailed_ip(pr, sintosa(&ia->ia_addr)))
1055 			goto skip;
1056 		TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
1057 			if (iac->ia->ia_ifp != ia->ia_ifp)
1058 				continue;
1059 			ia = iac->ia;
1060 			if (jailed_ip(pr, sintosa(&ia->ia_addr)))
1061 				goto skip;
1062 		}
1063 		ia = NULL;
1064 	}
1065 skip:
1066 
1067 	/*
1068 	 * If the route didn't work or there was no route,
1069 	 * fall-back to the first address in in_ifaddrheads[].
1070 	 *
1071 	 * If jailed and this address is not available for
1072 	 * the jail, leave ia set to NULL.
1073 	 */
1074 	if (ia == NULL) {
1075 		u_short fport = sin->sin_port;
1076 
1077 		sin->sin_port = 0;
1078 		ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
1079 		if (ia && pr && !jailed_ip(pr, sintosa(&ia->ia_addr)))
1080 			ia = NULL;
1081 
1082 		if (ia == NULL)
1083 			ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
1084 		if (ia && pr && !jailed_ip(pr, sintosa(&ia->ia_addr)))
1085 			ia = NULL;
1086 
1087 		sin->sin_port = fport;
1088 		if (ia == NULL && !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
1089 			ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
1090 
1091 		if (ia && pr && !jailed_ip(pr, sintosa(&ia->ia_addr)))
1092 			ia = NULL;
1093 
1094 		if (pr == NULL && ia == NULL)
1095 			goto fail;
1096 	}
1097 
1098 	/*
1099 	 * If the destination address is multicast and an outgoing
1100 	 * interface has been set as a multicast option, use the
1101 	 * address of that interface as our source address.
1102 	 */
1103 	if (pr == NULL && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
1104 	    inp->inp_moptions != NULL) {
1105 		struct ip_moptions *imo;
1106 		struct ifnet *ifp;
1107 
1108 		imo = inp->inp_moptions;
1109 		if ((ifp = imo->imo_multicast_ifp) != NULL) {
1110 			struct in_ifaddr_container *iac;
1111 
1112 			ia = NULL;
1113 			TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
1114 				if (iac->ia->ia_ifp == ifp) {
1115 					ia = iac->ia;
1116 					break;
1117 				}
1118 			}
1119 			if (ia == NULL)
1120 				goto fail;
1121 		}
1122 	}
1123 
1124 	/*
1125 	 * If we still don't have a local address, and are jailed,
1126 	 * use the jail's first non-localhost IP.  If there isn't
1127 	 * one, use the jail's first localhost IP.
1128 	 *
1129 	 * Don't do pcblookup call here; return interface in plocal_sin
1130 	 * and exit to caller, that will do the lookup.
1131 	 */
1132 	if (ia == NULL && pr) {
1133 		jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL);
1134 		if (jsin == NULL)
1135 			jsin = prison_get_local(cred->cr_prison, AF_INET, NULL);
1136 		if (jsin)
1137 			*plocal_sin = satosin(jsin);
1138 		else
1139 			goto fail;
1140 	} else if (ia) {
1141 		*plocal_sin = &ia->ia_addr;
1142 	} else {
1143 		goto fail;
1144 	}
1145 	return (0);
1146 fail:
1147 	if (alloc_route)
1148 		in_pcbresetroute(inp);
1149 	return (EADDRNOTAVAIL);
1150 }
1151 
1152 int
1153 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
1154 	    struct sockaddr_in **plocal_sin, struct thread *td)
1155 {
1156 	return in_pcbladdr_find(inp, nam, plocal_sin, td,
1157 				(inp->inp_laddr.s_addr == INADDR_ANY));
1158 }
1159 
1160 /*
1161  * Outer subroutine:
1162  * Connect from a socket to a specified address.
1163  * Both address and port must be specified in argument sin.
1164  * If don't have a local address for this socket yet,
1165  * then pick one.
1166  */
1167 int
1168 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
1169 {
1170 	struct sockaddr_in *if_sin;
1171 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1172 	int error;
1173 
1174 	if_sin = NULL;	/* avoid gcc warnings */
1175 
1176 	/* Call inner routine to assign local interface address. */
1177 	if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
1178 		return (error);
1179 
1180 	if (in_pcblookup_hash(inp->inp_pcbinfo, sin->sin_addr, sin->sin_port,
1181 			      inp->inp_laddr.s_addr ?
1182 				inp->inp_laddr : if_sin->sin_addr,
1183 			      inp->inp_lport, FALSE, NULL) != NULL) {
1184 		return (EADDRINUSE);
1185 	}
1186 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
1187 		if (inp->inp_lport == 0) {
1188 			error = in_pcbbind(inp, NULL, td);
1189 			if (error)
1190 				return (error);
1191 		}
1192 		inp->inp_laddr = if_sin->sin_addr;
1193 	}
1194 	inp->inp_faddr = sin->sin_addr;
1195 	inp->inp_fport = sin->sin_port;
1196 	in_pcbinsconnhash(inp);
1197 	return (0);
1198 }
1199 
1200 void
1201 in_pcbdisconnect(struct inpcb *inp)
1202 {
1203 
1204 	in_pcbremconnhash(inp);
1205 	inp->inp_faddr.s_addr = INADDR_ANY;
1206 	inp->inp_fport = 0;
1207 }
1208 
1209 void
1210 in_pcbdetach(struct inpcb *inp)
1211 {
1212 	struct socket *so = inp->inp_socket;
1213 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
1214 
1215 	inp->inp_gencnt = ++ipi->ipi_gencnt;
1216 	KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
1217 	in_pcbremlists(inp);
1218 	so->so_pcb = NULL;
1219 	sofree(so);			/* remove pcb ref */
1220 	if (inp->inp_options)
1221 		m_free(inp->inp_options);
1222 	if (inp->inp_route.ro_rt)
1223 		rtfree(inp->inp_route.ro_rt);
1224 	ip_freemoptions(inp->inp_moptions);
1225 	kfree(inp, M_PCB);
1226 }
1227 
1228 /*
1229  * The socket may have an invalid PCB, i.e. NULL.  For example, a TCP
1230  * socket received RST.
1231  */
1232 static int
1233 in_setsockaddr(struct socket *so, struct sockaddr **nam)
1234 {
1235 	struct inpcb *inp;
1236 	struct sockaddr_in *sin;
1237 
1238 	KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
1239 	inp = so->so_pcb;
1240 	if (!inp)
1241 		return (ECONNRESET);
1242 
1243 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1244 	sin->sin_family = AF_INET;
1245 	sin->sin_len = sizeof *sin;
1246 	sin->sin_port = inp->inp_lport;
1247 	sin->sin_addr = inp->inp_laddr;
1248 
1249 	*nam = (struct sockaddr *)sin;
1250 	return (0);
1251 }
1252 
1253 void
1254 in_setsockaddr_dispatch(netmsg_t msg)
1255 {
1256 	int error;
1257 
1258 	error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1259 	lwkt_replymsg(&msg->lmsg, error);
1260 }
1261 
1262 /*
1263  * The socket may have an invalid PCB, i.e. NULL.  For example, a TCP
1264  * socket received RST.
1265  */
1266 int
1267 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1268 {
1269 	struct inpcb *inp;
1270 	struct sockaddr_in *sin;
1271 
1272 	KASSERT(curthread->td_type == TD_TYPE_NETISR, ("not in netisr"));
1273 	inp = so->so_pcb;
1274 	if (!inp)
1275 		return (ECONNRESET);
1276 
1277 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1278 	sin->sin_family = AF_INET;
1279 	sin->sin_len = sizeof *sin;
1280 	sin->sin_port = inp->inp_fport;
1281 	sin->sin_addr = inp->inp_faddr;
1282 
1283 	*nam = (struct sockaddr *)sin;
1284 	return (0);
1285 }
1286 
1287 void
1288 in_setpeeraddr_dispatch(netmsg_t msg)
1289 {
1290 	int error;
1291 
1292 	error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1293 	lwkt_replymsg(&msg->lmsg, error);
1294 }
1295 
1296 void
1297 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int err,
1298     inp_notify_t notify)
1299 {
1300 	struct inpcb *inp, *marker;
1301 
1302 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
1303 	    ("not in the correct netisr"));
1304 	marker = in_pcbmarker();
1305 
1306 	/*
1307 	 * NOTE:
1308 	 * - If INP_PLACEMARKER is set we must ignore the rest of the
1309 	 *   structure and skip it.
1310 	 * - It is safe to nuke inpcbs here, since we are in their own
1311 	 *   netisr.
1312 	 */
1313 	GET_PCBINFO_TOKEN(pcbinfo);
1314 
1315 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1316 	while ((inp = LIST_NEXT(marker, inp_list)) != NULL) {
1317 		LIST_REMOVE(marker, inp_list);
1318 		LIST_INSERT_AFTER(inp, marker, inp_list);
1319 
1320 		if (inp->inp_flags & INP_PLACEMARKER)
1321 			continue;
1322 #ifdef INET6
1323 		if (!INP_ISIPV4(inp))
1324 			continue;
1325 #endif
1326 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1327 		    inp->inp_socket == NULL)
1328 			continue;
1329 		(*notify)(inp, err);		/* can remove inp from list! */
1330 	}
1331 	LIST_REMOVE(marker, inp_list);
1332 
1333 	REL_PCBINFO_TOKEN(pcbinfo);
1334 }
1335 
1336 void
1337 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1338 {
1339 	struct inpcb *inp, *marker;
1340 
1341 	/*
1342 	 * We only need to make sure that we are in netisr0, where all
1343 	 * multicast operation happen.  We could check inpcbinfo which
1344 	 * does not belong to netisr0 by holding the inpcbinfo's token.
1345 	 * In this case, the pcbinfo must be able to be shared, i.e.
1346 	 * pcbinfo->infotoken is not NULL.
1347 	 */
1348 	ASSERT_NETISR0;
1349 	KASSERT(pcbinfo->cpu == 0 || pcbinfo->infotoken != NULL,
1350 	    ("pcbinfo could not be shared"));
1351 
1352 	/*
1353 	 * Get a marker for the current netisr (netisr0).
1354 	 *
1355 	 * It is possible that the multicast address deletion blocks,
1356 	 * which could cause temporary token releasing.  So we use
1357 	 * inpcb marker here to get a coherent view of the inpcb list.
1358 	 *
1359 	 * While, on the other hand, moptions are only added and deleted
1360 	 * in netisr0, so we would not see staled moption or miss moption
1361 	 * even if the token was released due to the blocking multicast
1362 	 * address deletion.
1363 	 */
1364 	marker = in_pcbmarker();
1365 
1366 	GET_PCBINFO_TOKEN(pcbinfo);
1367 
1368 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1369 	while ((inp = LIST_NEXT(marker, inp_list)) != NULL) {
1370 		struct ip_moptions *imo;
1371 
1372 		LIST_REMOVE(marker, inp_list);
1373 		LIST_INSERT_AFTER(inp, marker, inp_list);
1374 
1375 		if (inp->inp_flags & INP_PLACEMARKER)
1376 			continue;
1377 		imo = inp->inp_moptions;
1378 		if (INP_ISIPV4(inp) && imo != NULL) {
1379 			int i, gap;
1380 
1381 			/*
1382 			 * Unselect the outgoing interface if it is being
1383 			 * detached.
1384 			 */
1385 			if (imo->imo_multicast_ifp == ifp)
1386 				imo->imo_multicast_ifp = NULL;
1387 
1388 			/*
1389 			 * Drop multicast group membership if we joined
1390 			 * through the interface being detached.
1391 			 */
1392 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1393 			    i++) {
1394 				if (imo->imo_membership[i]->inm_ifp == ifp) {
1395 					/*
1396 					 * NOTE:
1397 					 * This could block and the pcbinfo
1398 					 * token could be passively released.
1399 					 */
1400 					in_delmulti(imo->imo_membership[i]);
1401 					gap++;
1402 				} else if (gap != 0)
1403 					imo->imo_membership[i - gap] =
1404 					    imo->imo_membership[i];
1405 			}
1406 			imo->imo_num_memberships -= gap;
1407 		}
1408 	}
1409 	LIST_REMOVE(marker, inp_list);
1410 
1411 	REL_PCBINFO_TOKEN(pcbinfo);
1412 }
1413 
1414 /*
1415  * Check for alternatives when higher level complains
1416  * about service problems.  For now, invalidate cached
1417  * routing information.  If the route was created dynamically
1418  * (by a redirect), time to try a default gateway again.
1419  */
1420 void
1421 in_losing(struct inpcb *inp)
1422 {
1423 	struct rtentry *rt;
1424 	struct rt_addrinfo rtinfo;
1425 
1426 	if ((rt = inp->inp_route.ro_rt)) {
1427 		bzero(&rtinfo, sizeof(struct rt_addrinfo));
1428 		rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1429 		rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1430 		rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1431 		rtinfo.rti_flags = rt->rt_flags;
1432 		rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1433 		if (rt->rt_flags & RTF_DYNAMIC) {
1434 			rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1435 			    rt_mask(rt), rt->rt_flags, NULL);
1436 		}
1437 		inp->inp_route.ro_rt = NULL;
1438 		rtfree(rt);
1439 		/*
1440 		 * A new route can be allocated
1441 		 * the next time output is attempted.
1442 		 */
1443 	}
1444 }
1445 
1446 /*
1447  * After a routing change, flush old routing
1448  * and allocate a (hopefully) better one.
1449  */
1450 void
1451 in_rtchange(struct inpcb *inp, int err)
1452 {
1453 	if (inp->inp_route.ro_rt) {
1454 		rtfree(inp->inp_route.ro_rt);
1455 		inp->inp_route.ro_rt = NULL;
1456 		/*
1457 		 * A new route can be allocated the next time
1458 		 * output is attempted.
1459 		 */
1460 	}
1461 }
1462 
1463 /*
1464  * Lookup a PCB based on the local address and port.
1465  *
1466  * This function is only used when scanning for a free port.
1467  */
1468 static struct inpcb *
1469 in_pcblookup_local(struct inpcbporthead *porthash, struct in_addr laddr,
1470 		   u_int lport_arg, int wild_okay, struct ucred *cred)
1471 {
1472 	struct prison *pscan;
1473 	struct prison *pr;
1474 	struct inpcb *inp;
1475 	int matchwild = 3, wildcard;
1476 	u_short lport = lport_arg;
1477 	struct inpcbport *phd;
1478 	struct inpcb *match = NULL;
1479 
1480 	/*
1481 	 * If the porthashbase is shared across several cpus, it must
1482 	 * have been locked.
1483 	 */
1484 	ASSERT_PORTHASH_TOKEN_HELD(porthash);
1485 
1486 	/*
1487 	 * Best fit PCB lookup.
1488 	 *
1489 	 * First see if this local port is in use by looking on the
1490 	 * port hash list.
1491 	 */
1492 	LIST_FOREACH(phd, porthash, phd_hash) {
1493 		if (phd->phd_port == lport)
1494 			break;
1495 	}
1496 	if (phd != NULL) {
1497 		pr = cred ? cred->cr_prison : NULL;
1498 
1499 		/*
1500 		 * Port is in use by one or more PCBs. Look for best
1501 		 * fit.
1502 		 *
1503 		 * If in a prison we may wish to allow the jail to override
1504 		 * a wildcard listen on the host.  Since the jail forces its
1505 		 * own wildcard listens to a specific set of jail IPs, this
1506 		 * override allows most services on the host to remain as
1507 		 * they were and still be 'jail friendly'.
1508 		 */
1509 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1510 			wildcard = 0;
1511 #ifdef INET6
1512 			if (!INP_ISIPV4(inp))
1513 				continue;
1514 #endif
1515 			if (inp->inp_faddr.s_addr != INADDR_ANY)
1516 				wildcard++;
1517 
1518 			/*
1519 			 * Prison are independent of each other in terms
1520 			 * of allowing bindings.  This can result in multiple
1521 			 * overloaded bindings which in_pcblookup_pkthash()
1522 			 * will have to sort out.
1523 			 *
1524 			 * Allow wildcarded entries to co-exist with specific
1525 			 * entries.  Specific entries override wildcarded
1526 			 * entries.
1527 			 */
1528 			if (inp->inp_socket && inp->inp_socket->so_cred)
1529 				pscan = inp->inp_socket->so_cred->cr_prison;
1530 			else
1531 				pscan = NULL;
1532 			if (pr != pscan)
1533 				continue;
1534 			if (inp->inp_laddr.s_addr == INADDR_ANY) {
1535 				if (laddr.s_addr != INADDR_ANY)
1536 					wildcard++;
1537 			} else {
1538 				if (laddr.s_addr == INADDR_ANY)
1539 					wildcard++;
1540 				else if (inp->inp_laddr.s_addr != laddr.s_addr)
1541 					continue;
1542 			}
1543 			if (wildcard && !wild_okay)
1544 				continue;
1545 			if (wildcard < matchwild) {
1546 				match = inp;
1547 				matchwild = wildcard;
1548 				if (matchwild == 0)
1549 					break;
1550 			}
1551 		}
1552 	}
1553 	return (match);
1554 }
1555 
1556 struct inpcb *
1557 in_pcblocalgroup_last(const struct inpcbinfo *pcbinfo,
1558     const struct inpcb *inp)
1559 {
1560 	const struct inp_localgrphead *hdr;
1561 	const struct inp_localgroup *grp;
1562 	int i;
1563 
1564 	if (pcbinfo->localgrphashbase == NULL)
1565 		return NULL;
1566 
1567 	GET_PCBINFO_TOKEN(pcbinfo);
1568 
1569 	hdr = &pcbinfo->localgrphashbase[
1570 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1571 
1572 	LIST_FOREACH(grp, hdr, il_list) {
1573 		if (grp->il_af == inp->inp_af &&
1574 		    grp->il_lport == inp->inp_lport &&
1575 		    memcmp(&grp->il_dependladdr,
1576 			&inp->inp_inc.inc_ie.ie_dependladdr,
1577 			sizeof(grp->il_dependladdr)) == 0) {
1578 			break;
1579 		}
1580 	}
1581 	if (grp == NULL || grp->il_inpcnt == 1) {
1582 		REL_PCBINFO_TOKEN(pcbinfo);
1583 		return NULL;
1584 	}
1585 
1586 	KASSERT(grp->il_inpcnt >= 2,
1587 	    ("invalid localgroup inp count %d", grp->il_inpcnt));
1588 	for (i = 0; i < grp->il_inpcnt; ++i) {
1589 		if (grp->il_inp[i] == inp) {
1590 			int last = grp->il_inpcnt - 1;
1591 
1592 			if (i == last)
1593 				last = grp->il_inpcnt - 2;
1594 			REL_PCBINFO_TOKEN(pcbinfo);
1595 			return grp->il_inp[last];
1596 		}
1597 	}
1598 	REL_PCBINFO_TOKEN(pcbinfo);
1599 	return NULL;
1600 }
1601 
1602 static struct inpcb *
1603 inp_localgroup_lookup(const struct inpcbinfo *pcbinfo,
1604     struct in_addr laddr, uint16_t lport, uint32_t pkt_hash)
1605 {
1606 	struct inpcb *local_wild;
1607 	struct inpcb *jinp;
1608 	struct inpcb *jinp_wild;
1609 	struct inpcb *inp;
1610 	const struct inp_localgrphead *hdr;
1611 	const struct inp_localgroup *grp;
1612 	struct sockaddr_in jsin;
1613 	struct prison *pr;
1614 	struct ucred *cred;
1615 	int idx;
1616 	int net_listen_ov_local;
1617 	int net_listen_ov_wild;
1618 
1619 	ASSERT_PCBINFO_TOKEN_HELD(pcbinfo);
1620 
1621 	hdr = &pcbinfo->localgrphashbase[
1622 	    INP_PCBLOCALGRPHASH(lport, pcbinfo->localgrphashmask)];
1623 
1624 	/*
1625 	 * Order of socket selection:
1626 	 * 1. non-wild.
1627 	 * 2. wild.
1628 	 *
1629 	 * NOTE: Local group does not contain jailed sockets
1630 	 */
1631 	jsin.sin_family = AF_INET;
1632 	jsin.sin_addr.s_addr = laddr.s_addr;
1633 
1634 	jinp = NULL;
1635 	jinp_wild = NULL;
1636 	local_wild = NULL;
1637 	net_listen_ov_local = 0;
1638 	net_listen_ov_wild = 0;
1639 
1640 	LIST_FOREACH(grp, hdr, il_list) {
1641 #ifdef INET6
1642 		if (grp->il_af != AF_INET)
1643 			continue;
1644 #endif
1645 		if (grp->il_lport != lport)
1646 			continue;
1647 
1648 		/*
1649 		 * look for a match
1650 		 */
1651 		idx = netisr_hashlsb(pkt_hash) % grp->il_inpcnt;
1652 		inp = grp->il_inp[idx];
1653 
1654 		/*
1655 		 * Modulo-N is used here, which greatly reduces
1656 		 * completion queue token contention, thus more
1657 		 * cpu time is saved.
1658 		 */
1659 		if (grp->il_jailed) {
1660 			if (inp->inp_socket == NULL)
1661 				continue;
1662 			cred = inp->inp_socket->so_cred;
1663 			if (cred == NULL)
1664 				continue;
1665 			pr = cred->cr_prison;
1666 			if (pr == NULL)
1667 				continue;
1668 			if (!jailed_ip(pr, (struct sockaddr *)&jsin))
1669 				continue;
1670 			if (grp->il_laddr.s_addr == laddr.s_addr) {
1671 				jinp = inp;
1672 				if (PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_NET_LISTEN_OVERRIDE))
1673 					net_listen_ov_local = 1;
1674 
1675 			} else if (grp->il_laddr.s_addr == INADDR_ANY &&
1676 				   jinp_wild == NULL) {
1677 				jinp_wild = inp;
1678 				if (PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_NET_LISTEN_OVERRIDE))
1679 					net_listen_ov_wild = 1;
1680 			}
1681 		} else {
1682 			if (grp->il_laddr.s_addr == laddr.s_addr) {
1683 				return inp;
1684 			} else if (grp->il_laddr.s_addr == INADDR_ANY) {
1685 				local_wild = inp;
1686 			}
1687 		}
1688 	}
1689 
1690 	if (net_listen_ov_local)
1691 		return jinp;
1692 	if (net_listen_ov_wild)
1693 		return jinp_wild;
1694 	if (local_wild)
1695 		return (local_wild);
1696 	if (jinp)
1697 		return (jinp);
1698 	return (jinp_wild);
1699 }
1700 
1701 /*
1702  * Lookup PCB in hash list.
1703  *
1704  * This is used to match incoming packets to a pcb
1705  */
1706 struct inpcb *
1707 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1708     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1709     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1710 {
1711 	struct inpcbhead *head;
1712 	struct inpcb *inp, *jinp=NULL;
1713 	u_short fport = fport_arg, lport = lport_arg;
1714 
1715 	/*
1716 	 * First look for an exact match.
1717 	 */
1718 	head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1719 						  laddr.s_addr, lport,
1720 						  pcbinfo->hashmask)];
1721 	LIST_FOREACH(inp, head, inp_hash) {
1722 #ifdef INET6
1723 		if (!INP_ISIPV4(inp))
1724 			continue;
1725 #endif
1726 		if (in_hosteq(inp->inp_faddr, faddr) &&
1727 		    in_hosteq(inp->inp_laddr, laddr) &&
1728 		    inp->inp_fport == fport && inp->inp_lport == lport) {
1729 			/*
1730 			 * Found specific address, host overrides jailed
1731 			 * inpcb.
1732 			 */
1733 			if (inp->inp_socket == NULL ||
1734 			    inp->inp_socket->so_cred->cr_prison == NULL) {
1735 				return (inp);
1736 			}
1737 			if (jinp == NULL)
1738 				jinp = inp;
1739 		}
1740 	}
1741 	if (jinp != NULL)
1742 		return (jinp);
1743 
1744 	/*
1745 	 * We generally get here for connections to wildcarded listeners.
1746 	 * Any wildcarded listeners in jails must be restricted to the
1747 	 * jailed IPs only.
1748 	 */
1749 	if (wildcard) {
1750 		struct inpcb *local_wild = NULL;
1751 		struct inpcb *jinp_wild = NULL;
1752 		struct inpcontainer *ic;
1753 		struct inpcontainerhead *chead;
1754 		struct sockaddr_in jsin;
1755 		struct ucred *cred;
1756 		struct prison *pr;
1757 		int net_listen_ov_local = 0;
1758 		int net_listen_ov_wild = 0;
1759 
1760 		GET_PCBINFO_TOKEN(pcbinfo);
1761 
1762 		/*
1763 		 * Check local group first.  When present, the localgroup
1764 		 * hash utilizes the same non-jailed-vs/jailed priortization
1765 		 * that the normal wildcardhash does.
1766 		 */
1767 		if (pcbinfo->localgrphashbase != NULL &&
1768 		    m != NULL && (m->m_flags & M_HASH)) {
1769 			inp = inp_localgroup_lookup(pcbinfo, laddr, lport,
1770 						    m->m_pkthdr.hash);
1771 			if (inp != NULL) {
1772 				REL_PCBINFO_TOKEN(pcbinfo);
1773 				return inp;
1774 			}
1775 		}
1776 
1777 		/*
1778 		 * Order of socket selection:
1779 		 *
1780 		 * 1. non-jailed, non-wild.
1781 		 * 2. non-jailed, wild.		(allow_listen_override on)
1782 		 * 3. jailed, non-wild.
1783 		 * 4. jailed, wild.
1784 		 * 5. non-jailed, wild.		(allow_listen_override off)
1785 		 *
1786 		 * NOTE: jailed wildcards are still restricted to the jail
1787 		 *	 IPs.
1788 		 *
1789 		 * NOTE: (1) and (3) already handled above.
1790 		 */
1791 		jsin.sin_family = AF_INET;
1792 		chead = &pcbinfo->wildcardhashbase[
1793 		    INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1794 
1795 		LIST_FOREACH(ic, chead, ic_list) {
1796 			inp = ic->ic_inp;
1797 			if (inp->inp_flags & INP_PLACEMARKER)
1798 				continue;
1799 
1800 			/*
1801 			 * Basic validation
1802 			 */
1803 #ifdef INET6
1804 			if (!INP_ISIPV4(inp))
1805 				continue;
1806 #endif
1807 			if (inp->inp_lport != lport)
1808 				continue;
1809 
1810 			/*
1811 			 * Calculate prison, setup jsin for jailed_ip()
1812 			 * check.
1813 			 */
1814 			jsin.sin_addr.s_addr = laddr.s_addr;
1815 			pr = NULL;
1816 			cred = NULL;
1817 			if (inp->inp_socket) {
1818 				cred = inp->inp_socket->so_cred;
1819 				if (cred)
1820 					pr = cred->cr_prison;
1821 			}
1822 
1823 			/*
1824 			 * Assign jinp, jinp_wild, and local_wild as
1825 			 * appropriate, track whether the jail supports
1826 			 * listen overrides.
1827 			 */
1828 			if (pr) {
1829 				if (!jailed_ip(pr, (struct sockaddr *)&jsin))
1830 					continue;
1831 				if (inp->inp_laddr.s_addr == laddr.s_addr &&
1832 				    jinp == NULL) {
1833 					jinp = inp;
1834 					if (PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_NET_LISTEN_OVERRIDE))
1835 						net_listen_ov_local = 1;
1836 				}
1837 				if (inp->inp_laddr.s_addr == INADDR_ANY &&
1838 				    jinp_wild == NULL) {
1839 					jinp_wild = inp;
1840 					if (PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_NET_LISTEN_OVERRIDE))
1841 						net_listen_ov_wild = 1;
1842 				}
1843 			} else {
1844 				if (inp->inp_laddr.s_addr == laddr.s_addr) {
1845 					REL_PCBINFO_TOKEN(pcbinfo);
1846 					return (inp);
1847 				}
1848 				if (inp->inp_laddr.s_addr == INADDR_ANY)
1849 					local_wild = inp;
1850 			}
1851 		}
1852 
1853 		REL_PCBINFO_TOKEN(pcbinfo);
1854 
1855 		if (net_listen_ov_local)
1856 			return jinp;
1857 		if (net_listen_ov_wild)
1858 			return jinp_wild;
1859 		if (local_wild)
1860 			return (local_wild);
1861 		if (jinp)
1862 			return (jinp);
1863 		return (jinp_wild);
1864 	}
1865 
1866 	/*
1867 	 * Not found.
1868 	 */
1869 	return (NULL);
1870 }
1871 
1872 struct inpcb *
1873 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1874     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1875     boolean_t wildcard, struct ifnet *ifp)
1876 {
1877 	return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1878 	    laddr, lport_arg, wildcard, ifp, NULL);
1879 }
1880 
1881 /*
1882  * Insert PCB into connection hash table.
1883  */
1884 void
1885 in_pcbinsconnhash(struct inpcb *inp)
1886 {
1887 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1888 	struct inpcbhead *bucket;
1889 	u_int32_t hashkey_faddr, hashkey_laddr;
1890 
1891 #ifdef INET6
1892 	if (INP_ISIPV6(inp)) {
1893 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1894 		hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1895 	} else {
1896 #endif
1897 		hashkey_faddr = inp->inp_faddr.s_addr;
1898 		hashkey_laddr = inp->inp_laddr.s_addr;
1899 #ifdef INET6
1900 	}
1901 #endif
1902 
1903 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
1904 	    ("not in the correct netisr"));
1905 	ASSERT_INP_NOTINHASH(inp);
1906 	inp->inp_flags |= INP_CONNECTED;
1907 
1908 	/*
1909 	 * Insert into the connection hash table.
1910 	 */
1911 	bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1912 	    inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1913 	LIST_INSERT_HEAD(bucket, inp, inp_hash);
1914 }
1915 
1916 /*
1917  * Remove PCB from connection hash table.
1918  */
1919 void
1920 in_pcbremconnhash(struct inpcb *inp)
1921 {
1922 	struct inpcbinfo *pcbinfo __debugvar = inp->inp_pcbinfo;
1923 
1924 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
1925 	    ("not in the correct netisr"));
1926 	KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1927 
1928 	LIST_REMOVE(inp, inp_hash);
1929 	inp->inp_flags &= ~INP_CONNECTED;
1930 }
1931 
1932 /*
1933  * Insert PCB into port hash table.
1934  */
1935 void
1936 in_pcbinsporthash(struct inpcbporthead *pcbporthash, struct inpcb *inp)
1937 {
1938 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1939 	struct inpcbport *phd;
1940 
1941 	/*
1942 	 * If the porthashbase is shared across several cpus, it must
1943 	 * have been locked.
1944 	 */
1945 	ASSERT_PORTHASH_TOKEN_HELD(pcbporthash);
1946 
1947 	/*
1948 	 * Insert into the port hash table.
1949 	 */
1950 
1951 	/* Go through port list and look for a head for this lport. */
1952 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1953 		if (phd->phd_port == inp->inp_lport)
1954 			break;
1955 	}
1956 
1957 	/* If none exists, use saved one and tack it on. */
1958 	if (phd == NULL) {
1959 		KKASSERT(pcbinfo->portsave != NULL);
1960 		phd = pcbinfo->portsave;
1961 		pcbinfo->portsave = NULL;
1962 		phd->phd_port = inp->inp_lport;
1963 		LIST_INIT(&phd->phd_pcblist);
1964 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1965 	}
1966 
1967 	inp->inp_porthash = pcbporthash;
1968 	inp->inp_phd = phd;
1969 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1970 
1971 	/*
1972 	 * Malloc one inpcbport for later use.  It is safe to use
1973 	 * "wait" malloc here (port token would be released, if
1974 	 * malloc ever blocked), since all changes to the porthash
1975 	 * are done.
1976 	 */
1977 	if (pcbinfo->portsave == NULL) {
1978 		pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1979 					    M_PCB, M_INTWAIT | M_ZERO);
1980 	}
1981 }
1982 
1983 void
1984 in_pcbinsporthash_lport(struct inpcb *inp)
1985 {
1986 	struct inpcbporthead *porthash;
1987 
1988 	porthash = OBTAIN_LPORTHASH_TOKEN(inp->inp_pcbinfo, inp->inp_lport);
1989 	in_pcbinsporthash(porthash, inp);
1990 	REL_PORTHASH_TOKEN(porthash);
1991 }
1992 
1993 void
1994 in_pcbremporthash(struct inpcb *inp)
1995 {
1996 	struct inpcbporthead *porthash;
1997 	struct inpcbport *phd;
1998 
1999 	if (inp->inp_phd == NULL)
2000 		return;
2001 	KASSERT(inp->inp_lport != 0, ("inpcb has no lport"));
2002 
2003 	porthash = inp->inp_porthash;
2004 	KASSERT(porthash != NULL, ("no porthash"));
2005 
2006 	GET_PORTHASH_TOKEN(porthash);
2007 
2008 	phd = inp->inp_phd;
2009 	LIST_REMOVE(inp, inp_portlist);
2010 	if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2011 		LIST_REMOVE(phd, phd_hash);
2012 		kfree(phd, M_PCB);
2013 	}
2014 
2015 	REL_PORTHASH_TOKEN(porthash);
2016 
2017 	inp->inp_phd = NULL;
2018 	/* NOTE: Don't whack inp_lport, which may be used later */
2019 }
2020 
2021 static struct inp_localgroup *
2022 inp_localgroup_alloc(u_char af, uint16_t port,
2023     const union in_dependaddr *addr, int size)
2024 {
2025 	struct inp_localgroup *grp;
2026 
2027 	grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
2028 		      M_TEMP, M_INTWAIT | M_ZERO);
2029 	grp->il_af = af;
2030 	grp->il_lport = port;
2031 	grp->il_dependladdr = *addr;
2032 	grp->il_inpsiz = size;
2033 
2034 	return grp;
2035 }
2036 
2037 static void
2038 inp_localgroup_free(struct inp_localgroup *grp)
2039 {
2040 	kfree(grp, M_TEMP);
2041 }
2042 
2043 static void
2044 inp_localgroup_destroy(struct inp_localgroup *grp)
2045 {
2046 	LIST_REMOVE(grp, il_list);
2047 	inp_localgroup_free(grp);
2048 }
2049 
2050 static void
2051 inp_localgroup_copy(struct inp_localgroup *grp,
2052 		    const struct inp_localgroup *old_grp)
2053 {
2054 	int i;
2055 
2056 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
2057 	    ("invalid new local group size %d and old local group count %d",
2058 	     grp->il_inpsiz, old_grp->il_inpcnt));
2059 	for (i = 0; i < old_grp->il_inpcnt; ++i)
2060 		grp->il_inp[i] = old_grp->il_inp[i];
2061 	grp->il_inpcnt = old_grp->il_inpcnt;
2062 }
2063 
2064 static void
2065 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
2066 {
2067 	struct inp_localgrphead *hdr;
2068 	struct inp_localgroup *grp, *grp_alloc = NULL;
2069 	u_char isjailed;
2070 	int i, idx;
2071 
2072 	ASSERT_PCBINFO_TOKEN_HELD(pcbinfo);
2073 
2074 	if (pcbinfo->localgrphashbase == NULL)
2075 		return;
2076 
2077 	/*
2078 	 * Further separate groups by whether the inp is jailed or not.
2079 	 * This allows the inp_localgroup_lookup() code to manage port
2080 	 * overloading between jails and non-jails.
2081 	 *
2082 	 * XXX all jails are collected into one group, which works fine
2083 	 *     as we expect the jails to be listening on different addresses.
2084 	 *     If this changes in the future we may have to break the groups
2085 	 *     up by prison pointer as well.
2086 	 */
2087 	if (inp->inp_socket && inp->inp_socket->so_cred)
2088 		isjailed = jailed(inp->inp_socket->so_cred);
2089 	else
2090 		isjailed = 0;
2091 
2092 	hdr = &pcbinfo->localgrphashbase[
2093 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
2094 
2095 again:
2096 	LIST_FOREACH(grp, hdr, il_list) {
2097 		if (grp->il_af == inp->inp_af &&
2098 		    grp->il_lport == inp->inp_lport &&
2099 		    grp->il_jailed == isjailed &&
2100 		    memcmp(&grp->il_dependladdr,
2101 			   &inp->inp_inc.inc_ie.ie_dependladdr,
2102 			   sizeof(grp->il_dependladdr)) == 0) {
2103 			break;
2104 		}
2105 	}
2106 	if (grp == NULL) {
2107 		/*
2108 		 * Create a new local group
2109 		 */
2110 		if (grp_alloc == NULL) {
2111 			grp_alloc = inp_localgroup_alloc(inp->inp_af,
2112 			    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
2113 			    INP_LOCALGROUP_SIZMIN);
2114 			/*
2115 			 * Local group allocation could block and the
2116 			 * local group w/ the same property might have
2117 			 * been added by others when we were blocked;
2118 			 * check again.
2119 			 */
2120 			goto again;
2121 		} else {
2122 			/* Local group has been allocated; link it */
2123 			grp = grp_alloc;
2124 			grp->il_jailed = isjailed;
2125 			grp_alloc = NULL;
2126 			LIST_INSERT_HEAD(hdr, grp, il_list);
2127 		}
2128 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
2129 #if 0
2130 		/*
2131 		 * REMOVED - Ensure that all entries are placed in the
2132 		 *	     localgroup so jail operations can be
2133 		 *	     deterministic on a il_lport basis.
2134 		 */
2135 		if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
2136 			static int limit_logged = 0;
2137 
2138 			if (!limit_logged) {
2139 				limit_logged = 1;
2140 				kprintf("local group port %d, "
2141 				    "limit reached\n", ntohs(grp->il_lport));
2142 			}
2143 			if (grp_alloc != NULL) {
2144 				/*
2145 				 * This would happen if the local group
2146 				 * w/ the same property was expanded when
2147 				 * our local group allocation blocked.
2148 				 */
2149 				inp_localgroup_free(grp_alloc);
2150 			}
2151 			return;
2152 		}
2153 #endif
2154 
2155 		/*
2156 		 * Expand this local group
2157 		 */
2158 		if (grp_alloc == NULL ||
2159 		    grp->il_inpcnt >= grp_alloc->il_inpsiz) {
2160 			if (grp_alloc != NULL)
2161 				inp_localgroup_free(grp_alloc);
2162 			grp_alloc = inp_localgroup_alloc(grp->il_af,
2163 			    grp->il_lport, &grp->il_dependladdr,
2164 			    grp->il_inpsiz * 2);
2165 			/*
2166 			 * Local group allocation could block and the
2167 			 * local group w/ the same property might have
2168 			 * been expanded by others when we were blocked;
2169 			 * check again.
2170 			 */
2171 			goto again;
2172 		}
2173 
2174 		/*
2175 		 * Save the old local group, link the new one, and then
2176 		 * destroy the old local group
2177 		 */
2178 		inp_localgroup_copy(grp_alloc, grp);
2179 		LIST_INSERT_HEAD(hdr, grp_alloc, il_list);
2180 		inp_localgroup_destroy(grp);
2181 
2182 		grp = grp_alloc;
2183 		grp->il_jailed = isjailed;
2184 		grp_alloc = NULL;
2185 	} else {
2186 		/*
2187 		 * Found the local group
2188 		 */
2189 		if (grp_alloc != NULL) {
2190 			/*
2191 			 * This would happen if the local group w/ the
2192 			 * same property was added or expanded when our
2193 			 * local group allocation blocked.
2194 			 */
2195 			inp_localgroup_free(grp_alloc);
2196 			grp_alloc = NULL;
2197 		}
2198 	}
2199 
2200 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
2201 	    ("invalid local group size %d and count %d",
2202 	     grp->il_inpsiz, grp->il_inpcnt));
2203 
2204 	/*
2205 	 * Keep the local group sorted by the inpcb local group index
2206 	 * in ascending order.
2207 	 *
2208 	 * This eases the multi-process userland application which uses
2209 	 * SO_REUSEPORT sockets and binds process to the owner cpu of
2210 	 * the SO_REUSEPORT socket:
2211 	 * If we didn't sort the local group by the inpcb local group
2212 	 * index and one of the process owning an inpcb in this local
2213 	 * group restarted, e.g. crashed and restarted by watchdog,
2214 	 * other processes owning a inpcb in this local group would have
2215 	 * to detect that event, refetch its socket's owner cpu, and
2216 	 * re-bind.
2217 	 */
2218 	idx = grp->il_inpcnt;
2219 	for (i = 0; i < idx; ++i) {
2220 		struct inpcb *oinp = grp->il_inp[i];
2221 
2222 		if (oinp->inp_lgrpindex > i) {
2223 			if (inp->inp_lgrpindex < 0) {
2224 				inp->inp_lgrpindex = i;
2225 			} else if (inp->inp_lgrpindex != i) {
2226 				if (bootverbose) {
2227 					kprintf("inp %p: grpidx %d, "
2228 					    "assigned to %d, cpu%d\n",
2229 					    inp, inp->inp_lgrpindex, i,
2230 					    mycpuid);
2231 				}
2232 			}
2233 			grp->il_inp[i] = inp;
2234 
2235 			/* Pull down inpcbs */
2236 			for (; i < grp->il_inpcnt; ++i) {
2237 				struct inpcb *oinp1 = grp->il_inp[i + 1];
2238 
2239 				grp->il_inp[i + 1] = oinp;
2240 				oinp = oinp1;
2241 			}
2242 			grp->il_inpcnt++;
2243 			return;
2244 		}
2245 	}
2246 
2247 	if (inp->inp_lgrpindex < 0) {
2248 		inp->inp_lgrpindex = idx;
2249 	} else if (inp->inp_lgrpindex != idx) {
2250 		if (bootverbose) {
2251 			kprintf("inp %p: grpidx %d, assigned to %d, cpu%d\n",
2252 			    inp, inp->inp_lgrpindex, idx, mycpuid);
2253 		}
2254 	}
2255 	grp->il_inp[idx] = inp;
2256 	grp->il_inpcnt++;
2257 }
2258 
2259 void
2260 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
2261 {
2262 	struct inpcontainer *ic;
2263 	struct inpcontainerhead *bucket;
2264 
2265 	GET_PCBINFO_TOKEN(pcbinfo);
2266 
2267 	in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
2268 
2269 	bucket = &pcbinfo->wildcardhashbase[
2270 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
2271 
2272 	ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
2273 	ic->ic_inp = inp;
2274 	LIST_INSERT_HEAD(bucket, ic, ic_list);
2275 
2276 	REL_PCBINFO_TOKEN(pcbinfo);
2277 }
2278 
2279 /*
2280  * Insert PCB into wildcard hash table.
2281  */
2282 void
2283 in_pcbinswildcardhash(struct inpcb *inp)
2284 {
2285 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2286 
2287 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
2288 	    ("not in correct netisr"));
2289 	ASSERT_INP_NOTINHASH(inp);
2290 	inp->inp_flags |= INP_WILDCARD;
2291 
2292 	in_pcbinswildcardhash_oncpu(inp, pcbinfo);
2293 }
2294 
2295 static void
2296 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
2297 {
2298 	struct inp_localgrphead *hdr;
2299 	struct inp_localgroup *grp;
2300 
2301 	ASSERT_PCBINFO_TOKEN_HELD(pcbinfo);
2302 
2303 	if (pcbinfo->localgrphashbase == NULL)
2304 		return;
2305 
2306 	hdr = &pcbinfo->localgrphashbase[
2307 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
2308 
2309 	LIST_FOREACH(grp, hdr, il_list) {
2310 		int i;
2311 
2312 		for (i = 0; i < grp->il_inpcnt; ++i) {
2313 			if (grp->il_inp[i] != inp)
2314 				continue;
2315 
2316 			if (grp->il_inpcnt == 1) {
2317 				/* Destroy this local group */
2318 				inp_localgroup_destroy(grp);
2319 			} else {
2320 				/* Pull up inpcbs */
2321 				for (; i + 1 < grp->il_inpcnt; ++i)
2322 					grp->il_inp[i] = grp->il_inp[i + 1];
2323 				grp->il_inpcnt--;
2324 			}
2325 			return;
2326 		}
2327 	}
2328 }
2329 
2330 void
2331 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
2332 {
2333 	struct inpcontainer *ic;
2334 	struct inpcontainerhead *head;
2335 
2336 	GET_PCBINFO_TOKEN(pcbinfo);
2337 
2338 	in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
2339 
2340 	/* find bucket */
2341 	head = &pcbinfo->wildcardhashbase[
2342 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
2343 
2344 	LIST_FOREACH(ic, head, ic_list) {
2345 		if (ic->ic_inp == inp)
2346 			goto found;
2347 	}
2348 	REL_PCBINFO_TOKEN(pcbinfo);
2349 	return;			/* not found! */
2350 
2351 found:
2352 	LIST_REMOVE(ic, ic_list);	/* remove container from bucket chain */
2353 	REL_PCBINFO_TOKEN(pcbinfo);
2354 	kfree(ic, M_TEMP);		/* deallocate container */
2355 }
2356 
2357 /*
2358  * Remove PCB from wildcard hash table.
2359  */
2360 void
2361 in_pcbremwildcardhash(struct inpcb *inp)
2362 {
2363 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2364 
2365 	KASSERT(&curthread->td_msgport == netisr_cpuport(pcbinfo->cpu),
2366 	    ("not in correct netisr"));
2367 	KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
2368 
2369 	in_pcbremwildcardhash_oncpu(inp, pcbinfo);
2370 	inp->inp_lgrpindex = -1;
2371 	inp->inp_flags &= ~INP_WILDCARD;
2372 }
2373 
2374 /*
2375  * Remove PCB from various lists.
2376  */
2377 void
2378 in_pcbremlists(struct inpcb *inp)
2379 {
2380 	in_pcbremporthash(inp);
2381 	if (inp->inp_flags & INP_WILDCARD) {
2382 		in_pcbremwildcardhash(inp);
2383 	} else if (inp->inp_flags & INP_CONNECTED) {
2384 		in_pcbremconnhash(inp);
2385 	}
2386 
2387 	if (inp->inp_flags & INP_ONLIST)
2388 		in_pcbofflist(inp);
2389 }
2390 
2391 int
2392 prison_xinpcb(struct thread *td, struct inpcb *inp)
2393 {
2394 	struct ucred *cr;
2395 
2396 	if (td->td_proc == NULL)
2397 		return (0);
2398 	cr = td->td_proc->p_ucred;
2399 	if (cr->cr_prison == NULL)
2400 		return (0);
2401 	if (inp->inp_socket && inp->inp_socket->so_cred &&
2402 	    inp->inp_socket->so_cred->cr_prison &&
2403 	    cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
2404 		return (0);
2405 	return (1);
2406 }
2407 
2408 int
2409 in_pcblist_range(SYSCTL_HANDLER_ARGS)
2410 {
2411 	struct inpcbinfo *pcbinfo_arr = arg1;
2412 	int pcbinfo_arrlen = arg2;
2413 	struct inpcb *marker;
2414 	int cpu, origcpu;
2415 	int error, n;
2416 
2417 	KASSERT(pcbinfo_arrlen <= netisr_ncpus && pcbinfo_arrlen >= 1,
2418 	    ("invalid pcbinfo count %d", pcbinfo_arrlen));
2419 
2420 	/*
2421 	 * The process of preparing the TCB list is too time-consuming and
2422 	 * resource-intensive to repeat twice on every request.
2423 	 */
2424 	n = 0;
2425 	if (req->oldptr == NULL) {
2426 		for (cpu = 0; cpu < pcbinfo_arrlen; ++cpu)
2427 			n += pcbinfo_arr[cpu].ipi_count;
2428 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
2429 		return 0;
2430 	}
2431 
2432 	if (req->newptr != NULL)
2433 		return EPERM;
2434 
2435 	marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
2436 	marker->inp_flags |= INP_PLACEMARKER;
2437 
2438 	/*
2439 	 * OK, now we're committed to doing something.  Re-fetch ipi_count
2440 	 * after obtaining the generation count.
2441 	 */
2442 	error = 0;
2443 	origcpu = mycpuid;
2444 	for (cpu = 0; cpu < pcbinfo_arrlen && error == 0; ++cpu) {
2445 		struct inpcbinfo *pcbinfo = &pcbinfo_arr[cpu];
2446 		struct inpcb *inp;
2447 		struct xinpcb xi;
2448 		int i;
2449 
2450 		lwkt_migratecpu(cpu);
2451 
2452 		GET_PCBINFO_TOKEN(pcbinfo);
2453 
2454 		n = pcbinfo->ipi_count;
2455 
2456 		LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
2457 		i = 0;
2458 		while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
2459 			LIST_REMOVE(marker, inp_list);
2460 			LIST_INSERT_AFTER(inp, marker, inp_list);
2461 
2462 			if (inp->inp_flags & INP_PLACEMARKER)
2463 				continue;
2464 			if (prison_xinpcb(req->td, inp))
2465 				continue;
2466 
2467 			bzero(&xi, sizeof xi);
2468 			xi.xi_len = sizeof xi;
2469 			bcopy(inp, &xi.xi_inp, sizeof *inp);
2470 			if (inp->inp_socket)
2471 				sotoxsocket(inp->inp_socket, &xi.xi_socket);
2472 			if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
2473 				break;
2474 			++i;
2475 		}
2476 		LIST_REMOVE(marker, inp_list);
2477 
2478 		REL_PCBINFO_TOKEN(pcbinfo);
2479 
2480 		if (error == 0 && i < n) {
2481 			bzero(&xi, sizeof xi);
2482 			xi.xi_len = sizeof xi;
2483 			while (i < n) {
2484 				error = SYSCTL_OUT(req, &xi, sizeof xi);
2485 				if (error)
2486 					break;
2487 				++i;
2488 			}
2489 		}
2490 	}
2491 
2492 	lwkt_migratecpu(origcpu);
2493 	kfree(marker, M_TEMP);
2494 	return error;
2495 }
2496 
2497 int
2498 in_pcblist_ncpus(SYSCTL_HANDLER_ARGS)
2499 {
2500 
2501 	return (in_pcblist_range(oidp, arg1, netisr_ncpus, req));
2502 }
2503 
2504 void
2505 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
2506 {
2507 	struct sockaddr_in *sin;
2508 
2509 	KASSERT(faddr->sa_family == AF_INET,
2510 	    ("not AF_INET faddr %d", faddr->sa_family));
2511 
2512 	sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
2513 	sin->sin_family = AF_INET;
2514 	sin->sin_len = sizeof(*sin);
2515 	sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
2516 	sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
2517 
2518 	so->so_faddr = (struct sockaddr *)sin;
2519 }
2520 
2521 void
2522 in_pcbportinfo_init(struct inpcbportinfo *portinfo, int hashsize,
2523     u_short offset)
2524 {
2525 	memset(portinfo, 0, sizeof(*portinfo));
2526 
2527 	portinfo->offset = offset;
2528 	portinfo->porthashbase = phashinit(hashsize, M_PCB,
2529 	    &portinfo->porthashcnt);
2530 }
2531 
2532 void
2533 in_pcbportrange(u_short *hi0, u_short *lo0, u_short ofs, u_short step)
2534 {
2535 	int hi, lo;
2536 
2537 	if (step == 1)
2538 		return;
2539 
2540 	hi = *hi0;
2541 	lo = *lo0;
2542 
2543 	hi = rounddown(hi, step);
2544 	hi += ofs;
2545 	if (hi > (int)*hi0)
2546 		hi -= step;
2547 
2548 	lo = roundup(lo, step);
2549 	lo -= (step - ofs);
2550 	if (lo < (int)*lo0)
2551 		lo += step;
2552 
2553 	*hi0 = hi;
2554 	*lo0 = lo;
2555 }
2556 
2557 void
2558 in_pcbglobalinit(void)
2559 {
2560 	int cpu;
2561 
2562 	in_pcbmarkers = kmalloc(netisr_ncpus * sizeof(struct inpcb), M_PCB,
2563 	    M_WAITOK | M_ZERO);
2564 	in_pcbcontainer_markers =
2565 	    kmalloc(netisr_ncpus * sizeof(struct inpcontainer), M_PCB,
2566 	    M_WAITOK | M_ZERO);
2567 
2568 	for (cpu = 0; cpu < netisr_ncpus; ++cpu) {
2569 		struct inpcontainer *ic = &in_pcbcontainer_markers[cpu];
2570 		struct inpcb *marker = &in_pcbmarkers[cpu];
2571 
2572 		marker->inp_flags |= INP_PLACEMARKER;
2573 		ic->ic_inp = marker;
2574 	}
2575 }
2576 
2577 struct inpcb *
2578 in_pcbmarker(void)
2579 {
2580 
2581 	ASSERT_NETISR_NCPUS(mycpuid);
2582 	return &in_pcbmarkers[mycpuid];
2583 }
2584 
2585 struct inpcontainer *
2586 in_pcbcontainer_marker(void)
2587 {
2588 
2589 	ASSERT_NETISR_NCPUS(mycpuid);
2590 	return &in_pcbcontainer_markers[mycpuid];
2591 }
2592 
2593 void
2594 in_pcbresetroute(struct inpcb *inp)
2595 {
2596 	struct route *ro = &inp->inp_route;
2597 
2598 	if (ro->ro_rt != NULL)
2599 		RTFREE(ro->ro_rt);
2600 	bzero(ro, sizeof(*ro));
2601 }
2602