xref: /dflybsd-src/sys/netinet/in_pcb.c (revision abd448c3b2d3508465e48d9cfdb163ef88fc242e)
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_ipsec.h"
67 #include "opt_inet6.h"
68 
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/domain.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/proc.h>
78 #include <sys/priv.h>
79 #include <sys/jail.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82 
83 #include <sys/thread2.h>
84 #include <sys/socketvar2.h>
85 #include <sys/msgport2.h>
86 
87 #include <machine/limits.h>
88 
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.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 #ifdef IPSEC
103 #include <netinet6/ipsec.h>
104 #include <netproto/key/key.h>
105 #include <netproto/ipsec/esp_var.h>
106 #endif
107 
108 #ifdef FAST_IPSEC
109 #if defined(IPSEC) || defined(IPSEC_ESP)
110 #error "Bad idea: don't compile with both IPSEC and FAST_IPSEC!"
111 #endif
112 
113 #include <netproto/ipsec/ipsec.h>
114 #include <netproto/ipsec/key.h>
115 #define	IPSEC
116 #endif /* FAST_IPSEC */
117 
118 #define INP_LOCALGROUP_SIZMIN	8
119 #define INP_LOCALGROUP_SIZMAX	256
120 
121 struct in_addr zeroin_addr;
122 
123 /*
124  * These configure the range of local port addresses assigned to
125  * "unspecified" outgoing connections/packets/whatever.
126  */
127 int ipport_lowfirstauto = IPPORT_RESERVED - 1;	/* 1023 */
128 int ipport_lowlastauto = IPPORT_RESERVEDSTART;	/* 600 */
129 
130 int ipport_firstauto = IPPORT_RESERVED;		/* 1024 */
131 int ipport_lastauto = IPPORT_USERRESERVED;	/* 5000 */
132 
133 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;	/* 49152 */
134 int ipport_hilastauto = IPPORT_HILASTAUTO;	/* 65535 */
135 
136 #define RANGECHK(var, min, max) \
137 	if ((var) < (min)) { (var) = (min); } \
138 	else if ((var) > (max)) { (var) = (max); }
139 
140 int udpencap_enable = 1;	/* enabled by default */
141 int udpencap_port = 4500;	/* triggers decapsulation */
142 
143 static int
144 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
145 {
146 	int error;
147 
148 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
149 	if (!error) {
150 		RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
151 		RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
152 
153 		RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
154 		RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
155 
156 		RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
157 		RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
158 	}
159 	return (error);
160 }
161 
162 #undef RANGECHK
163 
164 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
165 
166 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
167 	   &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
168 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
169 	   &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
170 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
171 	   &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
172 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
173 	   &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
174 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
175 	   &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
176 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
177 	   &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
178 
179 /*
180  * in_pcb.c: manage the Protocol Control Blocks.
181  *
182  * NOTE: It is assumed that most of these functions will be called from
183  * a critical section.  XXX - There are, unfortunately, a few exceptions
184  * to this rule that should be fixed.
185  *
186  * NOTE: The caller should initialize the cpu field to the cpu running the
187  * protocol stack associated with this inpcbinfo.
188  */
189 
190 void
191 in_pcbinfo_init(struct inpcbinfo *pcbinfo)
192 {
193 	LIST_INIT(&pcbinfo->pcblisthead);
194 	pcbinfo->cpu = -1;
195 	pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave), M_PCB,
196 				    M_WAITOK | M_ZERO);
197 }
198 
199 struct baddynamicports baddynamicports;
200 
201 /*
202  * Check if the specified port is invalid for dynamic allocation.
203  */
204 int
205 in_baddynamic(u_int16_t port, u_int16_t proto)
206 {
207 	switch (proto) {
208 	case IPPROTO_TCP:
209 		return (DP_ISSET(baddynamicports.tcp, port));
210 	case IPPROTO_UDP:
211 #ifdef IPSEC
212 		/* Cannot preset this as it is a sysctl */
213 		if (port == udpencap_port)
214 			return (1);
215 #endif
216 		return (DP_ISSET(baddynamicports.udp, port));
217 	default:
218 		return (0);
219 	}
220 }
221 
222 
223 /*
224  * Allocate a PCB and associate it with the socket.
225  */
226 int
227 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
228 {
229 	struct inpcb *inp;
230 #ifdef IPSEC
231 	int error;
232 #endif
233 
234 	inp = kmalloc(pcbinfo->ipi_size, M_PCB, M_WAITOK|M_ZERO|M_NULLOK);
235 	if (inp == NULL)
236 		return (ENOMEM);
237 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
238 	inp->inp_pcbinfo = inp->inp_cpcbinfo = pcbinfo;
239 	inp->inp_socket = so;
240 #ifdef IPSEC
241 	error = ipsec_init_policy(so, &inp->inp_sp);
242 	if (error != 0) {
243 		kfree(inp, M_PCB);
244 		return (error);
245 	}
246 #endif
247 #ifdef INET6
248 	if (INP_SOCKAF(so) == AF_INET6 && ip6_v6only)
249 		inp->inp_flags |= IN6P_IPV6_V6ONLY;
250 	if (ip6_auto_flowlabel)
251 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
252 #endif
253 	soreference(so);
254 	so->so_pcb = inp;
255 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
256 	pcbinfo->ipi_count++;
257 	return (0);
258 }
259 
260 /*
261  * Unlink a pcb with the intention of moving it to another cpu with a
262  * different pcbinfo.  While unlinked nothing should attempt to dereference
263  * inp_pcbinfo, NULL it out so we assert if it does.
264  */
265 void
266 in_pcbunlink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
267 {
268 	KKASSERT(inp->inp_pcbinfo == pcbinfo);
269 
270 	LIST_REMOVE(inp, inp_list);
271 	pcbinfo->ipi_count--;
272 	inp->inp_pcbinfo = NULL;
273 }
274 
275 /*
276  * Relink a pcb into a new pcbinfo.
277  */
278 void
279 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
280 {
281 	KKASSERT(inp->inp_pcbinfo == NULL);
282 	inp->inp_pcbinfo = pcbinfo;
283 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
284 	pcbinfo->ipi_count++;
285 }
286 
287 int
288 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
289 {
290 	struct socket *so = inp->inp_socket;
291 	unsigned short *lastport;
292 	struct sockaddr_in *sin;
293 	struct sockaddr_in jsin;
294 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
295 	struct ucred *cred = NULL;
296 	u_short lport = 0;
297 	int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
298 	int error;
299 
300 	if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
301 		return (EADDRNOTAVAIL);
302 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
303 		return (EINVAL);	/* already bound */
304 
305 	if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
306 		wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
307 	if (td->td_proc)
308 		cred = td->td_proc->p_ucred;
309 
310 	/*
311 	 * This has to be atomic.  If the porthash is shared across multiple
312 	 * protocol threads (aka tcp) then the token will be non-NULL.
313 	 */
314 	if (pcbinfo->porttoken)
315 		lwkt_gettoken(pcbinfo->porttoken);
316 
317 	if (nam != NULL) {
318 		sin = (struct sockaddr_in *)nam;
319 		if (nam->sa_len != sizeof *sin) {
320 			error = EINVAL;
321 			goto done;
322 		}
323 #ifdef notdef
324 		/*
325 		 * We should check the family, but old programs
326 		 * incorrectly fail to initialize it.
327 		 */
328 		if (sin->sin_family != AF_INET) {
329 			error = EAFNOSUPPORT;
330 			goto done;
331 		}
332 #endif
333 		if (!prison_replace_wildcards(td, nam)) {
334 			error = EINVAL;
335 			goto done;
336 		}
337 		lport = sin->sin_port;
338 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
339 			/*
340 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
341 			 * allow complete duplication of binding if
342 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
343 			 * and a multicast address is bound on both
344 			 * new and duplicated sockets.
345 			 */
346 			if (so->so_options & SO_REUSEADDR)
347 				reuseport = SO_REUSEADDR | SO_REUSEPORT;
348 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
349 			sin->sin_port = 0;		/* yech... */
350 			bzero(&sin->sin_zero, sizeof sin->sin_zero);
351 			if (ifa_ifwithaddr((struct sockaddr *)sin) == NULL) {
352 				error = EADDRNOTAVAIL;
353 				goto done;
354 			}
355 		}
356 		if (lport != 0) {
357 			struct inpcb *t;
358 
359 			/* GROSS */
360 			if (ntohs(lport) < IPPORT_RESERVED &&
361 			    cred &&
362 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0)) {
363 				error = EACCES;
364 				goto done;
365 			}
366 			if (so->so_cred->cr_uid != 0 &&
367 			    !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
368 				t = in_pcblookup_local(pcbinfo,
369 						       sin->sin_addr,
370 						       lport,
371 						       INPLOOKUP_WILDCARD,
372 						       cred);
373 				if (t &&
374 				    (!in_nullhost(sin->sin_addr) ||
375 				     !in_nullhost(t->inp_laddr) ||
376 				     (t->inp_socket->so_options &
377 					 SO_REUSEPORT) == 0) &&
378 				    (so->so_cred->cr_uid !=
379 				     t->inp_socket->so_cred->cr_uid)) {
380 #ifdef INET6
381 					if (!in_nullhost(sin->sin_addr) ||
382 					    !in_nullhost(t->inp_laddr) ||
383 					    INP_SOCKAF(so) ==
384 					    INP_SOCKAF(t->inp_socket))
385 #endif
386 					{
387 						error = EADDRINUSE;
388 						goto done;
389 					}
390 				}
391 			}
392 			if (cred && !prison_replace_wildcards(td, nam)) {
393 				error = EADDRNOTAVAIL;
394 				goto done;
395 			}
396 			t = in_pcblookup_local(pcbinfo, sin->sin_addr, lport,
397 					       wild, cred);
398 			if (t && !(reuseport & t->inp_socket->so_options)) {
399 #ifdef INET6
400 				if (!in_nullhost(sin->sin_addr) ||
401 				    !in_nullhost(t->inp_laddr) ||
402 				    INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))
403 #endif
404 				{
405 					error = EADDRINUSE;
406 					goto done;
407 				}
408 			}
409 		}
410 		inp->inp_laddr = sin->sin_addr;
411 	}
412 	if (lport == 0) {
413 		ushort first, last;
414 		int count;
415 
416 		jsin.sin_family = AF_INET;
417 		jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
418 		if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
419 			inp->inp_laddr.s_addr = INADDR_ANY;
420 			error = EINVAL;
421 			goto done;
422 		}
423 		inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
424 
425 		inp->inp_flags |= INP_ANONPORT;
426 
427 		if (inp->inp_flags & INP_HIGHPORT) {
428 			first = ipport_hifirstauto;	/* sysctl */
429 			last  = ipport_hilastauto;
430 			lastport = &pcbinfo->lasthi;
431 		} else if (inp->inp_flags & INP_LOWPORT) {
432 			if (cred &&
433 			    (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
434 				inp->inp_laddr.s_addr = INADDR_ANY;
435 				goto done;
436 			}
437 			first = ipport_lowfirstauto;	/* 1023 */
438 			last  = ipport_lowlastauto;	/* 600 */
439 			lastport = &pcbinfo->lastlow;
440 		} else {
441 			first = ipport_firstauto;	/* sysctl */
442 			last  = ipport_lastauto;
443 			lastport = &pcbinfo->lastport;
444 		}
445 		/*
446 		 * Simple check to ensure all ports are not used up causing
447 		 * a deadlock here.
448 		 *
449 		 * We split the two cases (up and down) so that the direction
450 		 * is not being tested on each round of the loop.
451 		 */
452 		if (first > last) {
453 			/*
454 			 * counting down
455 			 */
456 			count = first - last;
457 
458 			do {
459 				if (count-- < 0) {	/* completely used? */
460 					inp->inp_laddr.s_addr = INADDR_ANY;
461 					error = EADDRNOTAVAIL;
462 					goto done;
463 				}
464 				--*lastport;
465 				if (*lastport > first || *lastport < last)
466 					*lastport = first;
467 				lport = htons(*lastport);
468 			} while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
469 						    lport, wild, cred));
470 		} else {
471 			/*
472 			 * counting up
473 			 */
474 			count = last - first;
475 
476 			do {
477 				if (count-- < 0) {	/* completely used? */
478 					inp->inp_laddr.s_addr = INADDR_ANY;
479 					error = EADDRNOTAVAIL;
480 					goto done;
481 				}
482 				++*lastport;
483 				if (*lastport < first || *lastport > last)
484 					*lastport = first;
485 				lport = htons(*lastport);
486 			} while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
487 						    lport, wild, cred));
488 		}
489 	}
490 	inp->inp_lport = lport;
491 
492 	jsin.sin_family = AF_INET;
493 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
494 	if (!prison_replace_wildcards(td, (struct sockaddr*)&jsin)) {
495 		inp->inp_laddr.s_addr = INADDR_ANY;
496 		inp->inp_lport = 0;
497 		error = EINVAL;
498 		goto done;
499 	}
500 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
501 
502 	if (in_pcbinsporthash(inp) != 0) {
503 		inp->inp_laddr.s_addr = INADDR_ANY;
504 		inp->inp_lport = 0;
505 		error = EAGAIN;
506 		goto done;
507 	}
508 	error = 0;
509 done:
510 	if (pcbinfo->porttoken)
511 		lwkt_reltoken(pcbinfo->porttoken);
512 	return error;
513 }
514 
515 static struct inpcb *
516 in_pcblookup_addrport(struct inpcbinfo *pcbinfo, struct in_addr laddr,
517     u_short lport, struct in_addr faddr, u_short fport, struct ucred *cred)
518 {
519 	struct inpcb *inp;
520 	struct inpcbporthead *porthash;
521 	struct inpcbport *phd;
522 	struct inpcb *match = NULL;
523 
524 	/*
525 	 * If the porthashbase is shared across several cpus we need
526 	 * to lock.
527 	 */
528 	if (pcbinfo->porttoken)
529 		lwkt_gettoken(pcbinfo->porttoken);
530 
531 	/*
532 	 * Best fit PCB lookup.
533 	 *
534 	 * First see if this local port is in use by looking on the
535 	 * port hash list.
536 	 */
537 	porthash = &pcbinfo->porthashbase[
538 			INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
539 	LIST_FOREACH(phd, porthash, phd_hash) {
540 		if (phd->phd_port == lport)
541 			break;
542 	}
543 	if (phd != NULL) {
544 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
545 #ifdef INET6
546 			if ((inp->inp_vflag & INP_IPV4) == 0)
547 				continue;
548 #endif
549 			if (inp->inp_laddr.s_addr != INADDR_ANY &&
550 			    inp->inp_laddr.s_addr != laddr.s_addr)
551 				continue;
552 
553 			if (inp->inp_faddr.s_addr != INADDR_ANY &&
554 			    inp->inp_faddr.s_addr != faddr.s_addr)
555 				continue;
556 
557 			if (inp->inp_fport != 0 && inp->inp_fport != fport)
558 				continue;
559 
560 			if (cred == NULL ||
561 			    cred->cr_prison ==
562 			    inp->inp_socket->so_cred->cr_prison) {
563 				match = inp;
564 				break;
565 			}
566 		}
567 	}
568 	if (pcbinfo->porttoken)
569 		lwkt_reltoken(pcbinfo->porttoken);
570 	return (match);
571 }
572 
573 int
574 in_pcbconn_bind(struct inpcb *inp, const struct sockaddr *nam,
575     struct thread *td)
576 {
577 	struct proc *p = td->td_proc;
578 	unsigned short *lastport;
579 	const struct sockaddr_in *sin = (const struct sockaddr_in *)nam;
580 	struct sockaddr_in jsin;
581 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
582 	struct ucred *cred = NULL;
583 	u_short lport = 0;
584 	ushort first, last;
585 	int count, error, dup = 0;
586 
587 	if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
588 		return (EADDRNOTAVAIL);
589 
590 	KKASSERT(inp->inp_laddr.s_addr != INADDR_ANY);
591 	if (inp->inp_lport != 0)
592 		return (EINVAL);	/* already bound */
593 
594 	KKASSERT(p);
595 	cred = p->p_ucred;
596 
597 	/*
598 	 * This has to be atomic.  If the porthash is shared across multiple
599 	 * protocol threads (aka tcp) then the token will be non-NULL.
600 	 */
601 	if (pcbinfo->porttoken)
602 		lwkt_gettoken(pcbinfo->porttoken);
603 
604 	jsin.sin_family = AF_INET;
605 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
606 	if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
607 		inp->inp_laddr.s_addr = INADDR_ANY;
608 		error = EINVAL;
609 		goto done;
610 	}
611 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
612 
613 	inp->inp_flags |= INP_ANONPORT;
614 
615 	if (inp->inp_flags & INP_HIGHPORT) {
616 		first = ipport_hifirstauto;	/* sysctl */
617 		last  = ipport_hilastauto;
618 		lastport = &pcbinfo->lasthi;
619 	} else if (inp->inp_flags & INP_LOWPORT) {
620 		if (cred &&
621 		    (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
622 			inp->inp_laddr.s_addr = INADDR_ANY;
623 			goto done;
624 		}
625 		first = ipport_lowfirstauto;	/* 1023 */
626 		last  = ipport_lowlastauto;	/* 600 */
627 		lastport = &pcbinfo->lastlow;
628 	} else {
629 		first = ipport_firstauto;	/* sysctl */
630 		last  = ipport_lastauto;
631 		lastport = &pcbinfo->lastport;
632 	}
633 
634 again:
635 	/*
636 	 * Simple check to ensure all ports are not used up causing
637 	 * a deadlock here.
638 	 *
639 	 * We split the two cases (up and down) so that the direction
640 	 * is not being tested on each round of the loop.
641 	 */
642 	if (first > last) {
643 		/*
644 		 * counting down
645 		 */
646 		count = first - last;
647 
648 		do {
649 			if (count-- < 0) {	/* completely used? */
650 				inp->inp_laddr.s_addr = INADDR_ANY;
651 				error = EADDRNOTAVAIL;
652 				goto done;
653 			}
654 			--*lastport;
655 			if (*lastport > first || *lastport < last)
656 				*lastport = first;
657 			lport = htons(*lastport);
658 		} while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
659 				sin->sin_addr, sin->sin_port, cred));
660 	} else {
661 		/*
662 		 * counting up
663 		 */
664 		count = last - first;
665 
666 		do {
667 			if (count-- < 0) {	/* completely used? */
668 				inp->inp_laddr.s_addr = INADDR_ANY;
669 				error = EADDRNOTAVAIL;
670 				goto done;
671 			}
672 			++*lastport;
673 			if (*lastport < first || *lastport > last)
674 				*lastport = first;
675 			lport = htons(*lastport);
676 		} while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
677 				sin->sin_addr, sin->sin_port, cred));
678 	}
679 
680 	/* This could happen on loopback interface */
681 	if (sin->sin_port == lport &&
682 	    sin->sin_addr.s_addr == inp->inp_laddr.s_addr) {
683 		if (dup) {
684 			/*
685 			 * Duplicate again; give up
686 			 */
687 			inp->inp_laddr.s_addr = INADDR_ANY;
688 			error = EADDRNOTAVAIL;
689 			goto done;
690 		}
691 		dup = 1;
692 		goto again;
693 	}
694 	inp->inp_lport = lport;
695 
696 	jsin.sin_family = AF_INET;
697 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
698 	if (!prison_replace_wildcards(td, (struct sockaddr*)&jsin)) {
699 		inp->inp_laddr.s_addr = INADDR_ANY;
700 		inp->inp_lport = 0;
701 		error = EINVAL;
702 		goto done;
703 	}
704 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
705 
706 	if (in_pcbinsporthash(inp) != 0) {
707 		inp->inp_laddr.s_addr = INADDR_ANY;
708 		inp->inp_lport = 0;
709 		error = EAGAIN;
710 		goto done;
711 	}
712 	error = 0;
713 done:
714 	if (pcbinfo->porttoken)
715 		lwkt_reltoken(pcbinfo->porttoken);
716 	return error;
717 }
718 
719 /*
720  *   Transform old in_pcbconnect() into an inner subroutine for new
721  *   in_pcbconnect(): Do some validity-checking on the remote
722  *   address (in mbuf 'nam') and then determine local host address
723  *   (i.e., which interface) to use to access that remote host.
724  *
725  *   This preserves definition of in_pcbconnect(), while supporting a
726  *   slightly different version for T/TCP.  (This is more than
727  *   a bit of a kludge, but cleaning up the internal interfaces would
728  *   have forced minor changes in every protocol).
729  */
730 int
731 in_pcbladdr_find(struct inpcb *inp, struct sockaddr *nam,
732     struct sockaddr_in **plocal_sin, struct thread *td, int find)
733 {
734 	struct in_ifaddr *ia;
735 	struct ucred *cred = NULL;
736 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
737 	struct sockaddr *jsin;
738 	int jailed = 0, alloc_route = 0;
739 
740 	if (nam->sa_len != sizeof *sin)
741 		return (EINVAL);
742 	if (sin->sin_family != AF_INET)
743 		return (EAFNOSUPPORT);
744 	if (sin->sin_port == 0)
745 		return (EADDRNOTAVAIL);
746 	if (td && td->td_proc && td->td_proc->p_ucred)
747 		cred = td->td_proc->p_ucred;
748 	if (cred && cred->cr_prison)
749 		jailed = 1;
750 	if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
751 		ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
752 		/*
753 		 * If the destination address is INADDR_ANY,
754 		 * use the primary local address.
755 		 * If the supplied address is INADDR_BROADCAST,
756 		 * and the primary interface supports broadcast,
757 		 * choose the broadcast address for that interface.
758 		 */
759 		if (sin->sin_addr.s_addr == INADDR_ANY)
760 			sin->sin_addr = IA_SIN(ia)->sin_addr;
761 		else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
762 		    (ia->ia_ifp->if_flags & IFF_BROADCAST))
763 			sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
764 	}
765 	if (find) {
766 		struct route *ro;
767 
768 		ia = NULL;
769 		/*
770 		 * If route is known or can be allocated now,
771 		 * our src addr is taken from the i/f, else punt.
772 		 * Note that we should check the address family of the cached
773 		 * destination, in case of sharing the cache with IPv6.
774 		 */
775 		ro = &inp->inp_route;
776 		if (ro->ro_rt &&
777 		    (!(ro->ro_rt->rt_flags & RTF_UP) ||
778 		     ro->ro_dst.sa_family != AF_INET ||
779 		     satosin(&ro->ro_dst)->sin_addr.s_addr !=
780 				      sin->sin_addr.s_addr ||
781 		     inp->inp_socket->so_options & SO_DONTROUTE)) {
782 			RTFREE(ro->ro_rt);
783 			ro->ro_rt = NULL;
784 		}
785 		if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
786 		    (ro->ro_rt == NULL ||
787 		    ro->ro_rt->rt_ifp == NULL)) {
788 			/* No route yet, so try to acquire one */
789 			bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
790 			ro->ro_dst.sa_family = AF_INET;
791 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
792 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
793 				sin->sin_addr;
794 			rtalloc(ro);
795 			alloc_route = 1;
796 		}
797 		/*
798 		 * If we found a route, use the address
799 		 * corresponding to the outgoing interface
800 		 * unless it is the loopback (in case a route
801 		 * to our address on another net goes to loopback).
802 		 */
803 		if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
804 			if (jailed) {
805 				if (jailed_ip(cred->cr_prison,
806 				    ro->ro_rt->rt_ifa->ifa_addr)) {
807 					ia = ifatoia(ro->ro_rt->rt_ifa);
808 				}
809 			} else {
810 				ia = ifatoia(ro->ro_rt->rt_ifa);
811 			}
812 		}
813 		if (ia == NULL) {
814 			u_short fport = sin->sin_port;
815 
816 			sin->sin_port = 0;
817 			ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
818 			if (ia && jailed && !jailed_ip(cred->cr_prison,
819 			    sintosa(&ia->ia_addr)))
820 				ia = NULL;
821 			if (ia == NULL)
822 				ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
823 			if (ia && jailed && !jailed_ip(cred->cr_prison,
824 			    sintosa(&ia->ia_addr)))
825 				ia = NULL;
826 			sin->sin_port = fport;
827 			if (ia == NULL &&
828 			    !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
829 				ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
830 			if (ia && jailed && !jailed_ip(cred->cr_prison,
831 			    sintosa(&ia->ia_addr)))
832 				ia = NULL;
833 
834 			if (!jailed && ia == NULL)
835 				goto fail;
836 		}
837 		/*
838 		 * If the destination address is multicast and an outgoing
839 		 * interface has been set as a multicast option, use the
840 		 * address of that interface as our source address.
841 		 */
842 		if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
843 		    inp->inp_moptions != NULL) {
844 			struct ip_moptions *imo;
845 			struct ifnet *ifp;
846 
847 			imo = inp->inp_moptions;
848 			if (imo->imo_multicast_ifp != NULL) {
849 				struct in_ifaddr_container *iac;
850 
851 				ifp = imo->imo_multicast_ifp;
852 				ia = NULL;
853 				TAILQ_FOREACH(iac,
854 				&in_ifaddrheads[mycpuid], ia_link) {
855 					if (iac->ia->ia_ifp == ifp) {
856 						ia = iac->ia;
857 						break;
858 					}
859 				}
860 				if (ia == NULL)
861 					goto fail;
862 			}
863 		}
864 		/*
865 		 * Don't do pcblookup call here; return interface in plocal_sin
866 		 * and exit to caller, that will do the lookup.
867 		 */
868 		if (ia == NULL && jailed) {
869 			if ((jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL)) != NULL ||
870 			    (jsin = prison_get_local(cred->cr_prison, AF_INET, NULL)) != NULL) {
871 				*plocal_sin = satosin(jsin);
872 			} else {
873 				/* IPv6 only Jail */
874 				goto fail;
875 			}
876 		} else {
877 			*plocal_sin = &ia->ia_addr;
878 		}
879 	}
880 	return (0);
881 fail:
882 	if (alloc_route) {
883 		struct route *ro = &inp->inp_route;
884 
885 		if (ro->ro_rt != NULL)
886 			RTFREE(ro->ro_rt);
887 		bzero(ro, sizeof(*ro));
888 	}
889 	return (EADDRNOTAVAIL);
890 }
891 
892 int
893 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
894     struct sockaddr_in **plocal_sin, struct thread *td)
895 {
896 	return in_pcbladdr_find(inp, nam, plocal_sin, td,
897 	    (inp->inp_laddr.s_addr == INADDR_ANY));
898 }
899 
900 /*
901  * Outer subroutine:
902  * Connect from a socket to a specified address.
903  * Both address and port must be specified in argument sin.
904  * If don't have a local address for this socket yet,
905  * then pick one.
906  */
907 int
908 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
909 {
910 	struct sockaddr_in *if_sin;
911 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
912 	int error;
913 
914 	/* Call inner routine to assign local interface address. */
915 	if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
916 		return (error);
917 
918 	if (in_pcblookup_hash(inp->inp_cpcbinfo, sin->sin_addr, sin->sin_port,
919 			      inp->inp_laddr.s_addr ?
920 				inp->inp_laddr : if_sin->sin_addr,
921 			      inp->inp_lport, FALSE, NULL) != NULL) {
922 		return (EADDRINUSE);
923 	}
924 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
925 		if (inp->inp_lport == 0) {
926 			error = in_pcbbind(inp, NULL, td);
927 			if (error)
928 				return (error);
929 		}
930 		inp->inp_laddr = if_sin->sin_addr;
931 	}
932 	inp->inp_faddr = sin->sin_addr;
933 	inp->inp_fport = sin->sin_port;
934 	in_pcbinsconnhash(inp);
935 	return (0);
936 }
937 
938 void
939 in_pcbdisconnect(struct inpcb *inp)
940 {
941 
942 	inp->inp_faddr.s_addr = INADDR_ANY;
943 	inp->inp_fport = 0;
944 	in_pcbremconnhash(inp);
945 	if (inp->inp_socket->so_state & SS_NOFDREF)
946 		in_pcbdetach(inp);
947 }
948 
949 void
950 in_pcbdetach(struct inpcb *inp)
951 {
952 	struct socket *so = inp->inp_socket;
953 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
954 
955 #ifdef IPSEC
956 	ipsec4_delete_pcbpolicy(inp);
957 #endif /*IPSEC*/
958 	inp->inp_gencnt = ++ipi->ipi_gencnt;
959 	KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
960 	in_pcbremlists(inp);
961 	so->so_pcb = NULL;
962 	sofree(so);			/* remove pcb ref */
963 	if (inp->inp_options)
964 		m_free(inp->inp_options);
965 	if (inp->inp_route.ro_rt)
966 		rtfree(inp->inp_route.ro_rt);
967 	ip_freemoptions(inp->inp_moptions);
968 	inp->inp_vflag = 0;
969 	kfree(inp, M_PCB);
970 }
971 
972 /*
973  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
974  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
975  * in struct pr_usrreqs, so that protocols can just reference then directly
976  * without the need for a wrapper function.  The socket must have a valid
977  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
978  * except through a kernel programming error, so it is acceptable to panic
979  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
980  * because there actually /is/ a programming error somewhere... XXX)
981  */
982 int
983 in_setsockaddr(struct socket *so, struct sockaddr **nam)
984 {
985 	struct inpcb *inp;
986 	struct sockaddr_in *sin;
987 
988 	/*
989 	 * Do the malloc first in case it blocks.
990 	 */
991 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
992 	sin->sin_family = AF_INET;
993 	sin->sin_len = sizeof *sin;
994 
995 	crit_enter();
996 	inp = so->so_pcb;
997 	if (!inp) {
998 		crit_exit();
999 		kfree(sin, M_SONAME);
1000 		return (ECONNRESET);
1001 	}
1002 	sin->sin_port = inp->inp_lport;
1003 	sin->sin_addr = inp->inp_laddr;
1004 	crit_exit();
1005 
1006 	*nam = (struct sockaddr *)sin;
1007 	return (0);
1008 }
1009 
1010 void
1011 in_setsockaddr_dispatch(netmsg_t msg)
1012 {
1013 	int error;
1014 
1015 	error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1016 	lwkt_replymsg(&msg->lmsg, error);
1017 }
1018 
1019 int
1020 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1021 {
1022 	struct inpcb *inp;
1023 	struct sockaddr_in *sin;
1024 
1025 	/*
1026 	 * Do the malloc first in case it blocks.
1027 	 */
1028 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1029 	sin->sin_family = AF_INET;
1030 	sin->sin_len = sizeof *sin;
1031 
1032 	crit_enter();
1033 	inp = so->so_pcb;
1034 	if (!inp) {
1035 		crit_exit();
1036 		kfree(sin, M_SONAME);
1037 		return (ECONNRESET);
1038 	}
1039 	sin->sin_port = inp->inp_fport;
1040 	sin->sin_addr = inp->inp_faddr;
1041 	crit_exit();
1042 
1043 	*nam = (struct sockaddr *)sin;
1044 	return (0);
1045 }
1046 
1047 void
1048 in_setpeeraddr_dispatch(netmsg_t msg)
1049 {
1050 	int error;
1051 
1052 	error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1053 	lwkt_replymsg(&msg->lmsg, error);
1054 }
1055 
1056 void
1057 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
1058 		void (*notify)(struct inpcb *, int))
1059 {
1060 	struct inpcb *inp, *ninp;
1061 
1062 	/*
1063 	 * note: if INP_PLACEMARKER is set we must ignore the rest of
1064 	 * the structure and skip it.
1065 	 */
1066 	crit_enter();
1067 	LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
1068 		if (inp->inp_flags & INP_PLACEMARKER)
1069 			continue;
1070 #ifdef INET6
1071 		if (!(inp->inp_vflag & INP_IPV4))
1072 			continue;
1073 #endif
1074 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1075 		    inp->inp_socket == NULL)
1076 			continue;
1077 		(*notify)(inp, err);		/* can remove inp from list! */
1078 	}
1079 	crit_exit();
1080 }
1081 
1082 void
1083 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
1084 {
1085 	struct inpcb *inp;
1086 	struct ip_moptions *imo;
1087 	int i, gap;
1088 
1089 	for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
1090 		if (inp->inp_flags & INP_PLACEMARKER)
1091 			continue;
1092 		imo = inp->inp_moptions;
1093 		if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
1094 			/*
1095 			 * Unselect the outgoing interface if it is being
1096 			 * detached.
1097 			 */
1098 			if (imo->imo_multicast_ifp == ifp)
1099 				imo->imo_multicast_ifp = NULL;
1100 
1101 			/*
1102 			 * Drop multicast group membership if we joined
1103 			 * through the interface being detached.
1104 			 */
1105 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1106 			    i++) {
1107 				if (imo->imo_membership[i]->inm_ifp == ifp) {
1108 					in_delmulti(imo->imo_membership[i]);
1109 					gap++;
1110 				} else if (gap != 0)
1111 					imo->imo_membership[i - gap] =
1112 					    imo->imo_membership[i];
1113 			}
1114 			imo->imo_num_memberships -= gap;
1115 		}
1116 	}
1117 }
1118 
1119 /*
1120  * Check for alternatives when higher level complains
1121  * about service problems.  For now, invalidate cached
1122  * routing information.  If the route was created dynamically
1123  * (by a redirect), time to try a default gateway again.
1124  */
1125 void
1126 in_losing(struct inpcb *inp)
1127 {
1128 	struct rtentry *rt;
1129 	struct rt_addrinfo rtinfo;
1130 
1131 	if ((rt = inp->inp_route.ro_rt)) {
1132 		bzero(&rtinfo, sizeof(struct rt_addrinfo));
1133 		rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1134 		rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1135 		rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1136 		rtinfo.rti_flags = rt->rt_flags;
1137 		rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1138 		if (rt->rt_flags & RTF_DYNAMIC) {
1139 			rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1140 			    rt_mask(rt), rt->rt_flags, NULL);
1141 		}
1142 		inp->inp_route.ro_rt = NULL;
1143 		rtfree(rt);
1144 		/*
1145 		 * A new route can be allocated
1146 		 * the next time output is attempted.
1147 		 */
1148 	}
1149 }
1150 
1151 /*
1152  * After a routing change, flush old routing
1153  * and allocate a (hopefully) better one.
1154  */
1155 void
1156 in_rtchange(struct inpcb *inp, int err)
1157 {
1158 	if (inp->inp_route.ro_rt) {
1159 		rtfree(inp->inp_route.ro_rt);
1160 		inp->inp_route.ro_rt = NULL;
1161 		/*
1162 		 * A new route can be allocated the next time
1163 		 * output is attempted.
1164 		 */
1165 	}
1166 }
1167 
1168 /*
1169  * Lookup a PCB based on the local address and port.
1170  */
1171 struct inpcb *
1172 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1173 		   u_int lport_arg, int wild_okay, struct ucred *cred)
1174 {
1175 	struct inpcb *inp;
1176 	int matchwild = 3, wildcard;
1177 	u_short lport = lport_arg;
1178 	struct inpcbporthead *porthash;
1179 	struct inpcbport *phd;
1180 	struct inpcb *match = NULL;
1181 
1182 	/*
1183 	 * If the porthashbase is shared across several cpus we need
1184 	 * to lock.
1185 	 */
1186 	if (pcbinfo->porttoken)
1187 		lwkt_gettoken(pcbinfo->porttoken);
1188 
1189 	/*
1190 	 * Best fit PCB lookup.
1191 	 *
1192 	 * First see if this local port is in use by looking on the
1193 	 * port hash list.
1194 	 */
1195 	porthash = &pcbinfo->porthashbase[
1196 			INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
1197 	LIST_FOREACH(phd, porthash, phd_hash) {
1198 		if (phd->phd_port == lport)
1199 			break;
1200 	}
1201 	if (phd != NULL) {
1202 		/*
1203 		 * Port is in use by one or more PCBs. Look for best
1204 		 * fit.
1205 		 */
1206 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1207 			wildcard = 0;
1208 #ifdef INET6
1209 			if ((inp->inp_vflag & INP_IPV4) == 0)
1210 				continue;
1211 #endif
1212 			if (inp->inp_faddr.s_addr != INADDR_ANY)
1213 				wildcard++;
1214 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
1215 				if (laddr.s_addr == INADDR_ANY)
1216 					wildcard++;
1217 				else if (inp->inp_laddr.s_addr != laddr.s_addr)
1218 					continue;
1219 			} else {
1220 				if (laddr.s_addr != INADDR_ANY)
1221 					wildcard++;
1222 			}
1223 			if (wildcard && !wild_okay)
1224 				continue;
1225 			if (wildcard < matchwild &&
1226 			    (cred == NULL ||
1227 			     cred->cr_prison ==
1228 					inp->inp_socket->so_cred->cr_prison)) {
1229 				match = inp;
1230 				matchwild = wildcard;
1231 				if (matchwild == 0) {
1232 					break;
1233 				}
1234 			}
1235 		}
1236 	}
1237 	if (pcbinfo->porttoken)
1238 		lwkt_reltoken(pcbinfo->porttoken);
1239 	return (match);
1240 }
1241 
1242 static struct inpcb *
1243 inp_localgroup_lookup(const struct inpcbinfo *pcbinfo,
1244     struct in_addr laddr, uint16_t lport, uint32_t pkt_hash)
1245 {
1246 	struct inpcb *local_wild = NULL;
1247 	const struct inp_localgrphead *hdr;
1248 	const struct inp_localgroup *grp;
1249 
1250 	hdr = &pcbinfo->localgrphashbase[
1251 	    INP_PCBLOCALGRPHASH(lport, pcbinfo->localgrphashmask)];
1252 #ifdef INP_LOCALGROUP_HASHTHR
1253 	pkt_hash >>= ncpus2_shift;
1254 #endif
1255 
1256 	/*
1257 	 * Order of socket selection:
1258 	 * 1. non-wild.
1259 	 * 2. wild.
1260 	 *
1261 	 * NOTE:
1262 	 * - Local group does not contain jailed sockets
1263 	 * - Local group does not contain IPv4 mapped INET6 wild sockets
1264 	 */
1265 	LIST_FOREACH(grp, hdr, il_list) {
1266 #ifdef INET6
1267 		if (!(grp->il_vflag & INP_IPV4))
1268 			continue;
1269 #endif
1270 		if (grp->il_lport == lport) {
1271 			int idx;
1272 
1273 #ifdef INP_LOCALGROUP_HASHTHR
1274 			idx = pkt_hash / grp->il_factor;
1275 			KASSERT(idx < grp->il_inpcnt && idx >= 0,
1276 			    ("invalid hash %04x, cnt %d or fact %d",
1277 			     pkt_hash, grp->il_inpcnt, grp->il_factor));
1278 #else
1279 			/*
1280 			 * Modulo-N is used here, which greatly reduces
1281 			 * completion queue token contention, thus more
1282 			 * cpu time is saved.
1283 			 */
1284 			idx = pkt_hash % grp->il_inpcnt;
1285 #endif
1286 
1287 			if (grp->il_laddr.s_addr == laddr.s_addr)
1288 				return grp->il_inp[idx];
1289 			else if (grp->il_laddr.s_addr == INADDR_ANY)
1290 				local_wild = grp->il_inp[idx];
1291 		}
1292 	}
1293 	if (local_wild != NULL)
1294 		return local_wild;
1295 	return NULL;
1296 }
1297 
1298 /*
1299  * Lookup PCB in hash list.
1300  */
1301 struct inpcb *
1302 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1303     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1304     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1305 {
1306 	struct inpcbhead *head;
1307 	struct inpcb *inp, *jinp=NULL;
1308 	u_short fport = fport_arg, lport = lport_arg;
1309 
1310 	/*
1311 	 * First look for an exact match.
1312 	 */
1313 	head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1314 	    laddr.s_addr, lport, pcbinfo->hashmask)];
1315 	LIST_FOREACH(inp, head, inp_hash) {
1316 #ifdef INET6
1317 		if (!(inp->inp_vflag & INP_IPV4))
1318 			continue;
1319 #endif
1320 		if (in_hosteq(inp->inp_faddr, faddr) &&
1321 		    in_hosteq(inp->inp_laddr, laddr) &&
1322 		    inp->inp_fport == fport && inp->inp_lport == lport) {
1323 			/* found */
1324 			if (inp->inp_socket == NULL ||
1325 			    inp->inp_socket->so_cred->cr_prison == NULL) {
1326 				return (inp);
1327 			} else {
1328 				if  (jinp == NULL)
1329 					jinp = inp;
1330 			}
1331 		}
1332 	}
1333 	if (jinp != NULL)
1334 		return (jinp);
1335 	if (wildcard) {
1336 		struct inpcb *local_wild = NULL;
1337 		struct inpcb *jinp_wild = NULL;
1338 #ifdef INET6
1339 		struct inpcb *local_wild_mapped = NULL;
1340 #endif
1341 		struct inpcontainer *ic;
1342 		struct inpcontainerhead *chead;
1343 		struct sockaddr_in jsin;
1344 		struct ucred *cred;
1345 
1346 		/*
1347 		 * Check local group first
1348 		 */
1349 		if (pcbinfo->localgrphashbase != NULL &&
1350 		    m != NULL && (m->m_flags & M_HASH) &&
1351 		    !(ifp && ifp->if_type == IFT_FAITH)) {
1352 			inp = inp_localgroup_lookup(pcbinfo,
1353 			    laddr, lport, m->m_pkthdr.hash);
1354 			if (inp != NULL)
1355 				return inp;
1356 		}
1357 
1358 		/*
1359 		 * Order of socket selection:
1360 		 * 1. non-jailed, non-wild.
1361 		 * 2. non-jailed, wild.
1362 		 * 3. jailed, non-wild.
1363 		 * 4. jailed, wild.
1364 		 */
1365 		jsin.sin_family = AF_INET;
1366 		chead = &pcbinfo->wildcardhashbase[
1367 		    INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1368 		LIST_FOREACH(ic, chead, ic_list) {
1369 			inp = ic->ic_inp;
1370 			jsin.sin_addr.s_addr = laddr.s_addr;
1371 #ifdef INET6
1372 			if (!(inp->inp_vflag & INP_IPV4))
1373 				continue;
1374 #endif
1375 			if (inp->inp_socket != NULL)
1376 				cred = inp->inp_socket->so_cred;
1377 			else
1378 				cred = NULL;
1379 			if (cred != NULL && jailed(cred)) {
1380 				if (jinp != NULL)
1381 					continue;
1382 				else
1383 					if (!jailed_ip(cred->cr_prison,
1384 					    (struct sockaddr *)&jsin))
1385 						continue;
1386 			}
1387 			if (inp->inp_lport == lport) {
1388 				if (ifp && ifp->if_type == IFT_FAITH &&
1389 				    !(inp->inp_flags & INP_FAITH))
1390 					continue;
1391 				if (inp->inp_laddr.s_addr == laddr.s_addr) {
1392 					if (cred != NULL && jailed(cred))
1393 						jinp = inp;
1394 					else
1395 						return (inp);
1396 				}
1397 				if (inp->inp_laddr.s_addr == INADDR_ANY) {
1398 #ifdef INET6
1399 					if (INP_CHECK_SOCKAF(inp->inp_socket,
1400 							     AF_INET6))
1401 						local_wild_mapped = inp;
1402 					else
1403 #endif
1404 						if (cred != NULL &&
1405 						    jailed(cred))
1406 							jinp_wild = inp;
1407 						else
1408 							local_wild = inp;
1409 				}
1410 			}
1411 		}
1412 		if (local_wild != NULL)
1413 			return (local_wild);
1414 #ifdef INET6
1415 		if (local_wild_mapped != NULL)
1416 			return (local_wild_mapped);
1417 #endif
1418 		if (jinp != NULL)
1419 			return (jinp);
1420 		return (jinp_wild);
1421 	}
1422 
1423 	/*
1424 	 * Not found.
1425 	 */
1426 	return (NULL);
1427 }
1428 
1429 struct inpcb *
1430 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1431     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1432     boolean_t wildcard, struct ifnet *ifp)
1433 {
1434 	return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1435 	    laddr, lport_arg, wildcard, ifp, NULL);
1436 }
1437 
1438 /*
1439  * Insert PCB into connection hash table.
1440  */
1441 void
1442 in_pcbinsconnhash(struct inpcb *inp)
1443 {
1444 	struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1445 	struct inpcbhead *bucket;
1446 	u_int32_t hashkey_faddr, hashkey_laddr;
1447 
1448 #ifdef INET6
1449 	if (inp->inp_vflag & INP_IPV6) {
1450 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1451 		hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1452 	} else {
1453 #endif
1454 		hashkey_faddr = inp->inp_faddr.s_addr;
1455 		hashkey_laddr = inp->inp_laddr.s_addr;
1456 #ifdef INET6
1457 	}
1458 #endif
1459 
1460 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1461 		("already on wildcardhash"));
1462 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1463 		("already on connhash"));
1464 	inp->inp_flags |= INP_CONNECTED;
1465 
1466 	/*
1467 	 * Insert into the connection hash table.
1468 	 */
1469 	bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1470 	    inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1471 	LIST_INSERT_HEAD(bucket, inp, inp_hash);
1472 }
1473 
1474 /*
1475  * Remove PCB from connection hash table.
1476  */
1477 void
1478 in_pcbremconnhash(struct inpcb *inp)
1479 {
1480 	KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1481 	LIST_REMOVE(inp, inp_hash);
1482 	inp->inp_flags &= ~INP_CONNECTED;
1483 }
1484 
1485 /*
1486  * Insert PCB into port hash table.
1487  */
1488 int
1489 in_pcbinsporthash(struct inpcb *inp)
1490 {
1491 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1492 	struct inpcbporthead *pcbporthash;
1493 	struct inpcbport *phd;
1494 
1495 	/*
1496 	 * If the porthashbase is shared across several cpus we need
1497 	 * to lock.
1498 	 */
1499 	if (pcbinfo->porttoken)
1500 		lwkt_gettoken(pcbinfo->porttoken);
1501 
1502 	/*
1503 	 * Insert into the port hash table.
1504 	 */
1505 	pcbporthash = &pcbinfo->porthashbase[
1506 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1507 
1508 	/* Go through port list and look for a head for this lport. */
1509 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1510 		if (phd->phd_port == inp->inp_lport)
1511 			break;
1512 	}
1513 
1514 	/* If none exists, malloc one and tack it on. */
1515 	if (phd == NULL) {
1516 		KKASSERT(pcbinfo->portsave != NULL);
1517 		phd = pcbinfo->portsave;
1518 		pcbinfo->portsave = NULL;
1519 		phd->phd_port = inp->inp_lport;
1520 		LIST_INIT(&phd->phd_pcblist);
1521 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1522 	}
1523 
1524 	inp->inp_phd = phd;
1525 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1526 
1527 	if (pcbinfo->porttoken)
1528 		lwkt_reltoken(pcbinfo->porttoken);
1529 	if (pcbinfo->portsave == NULL) {
1530 		pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1531 					    M_PCB, M_INTWAIT | M_ZERO);
1532 	}
1533 	return (0);
1534 }
1535 
1536 static struct inp_localgroup *
1537 inp_localgroup_alloc(struct inp_localgrphead *hdr, u_char vflag,
1538     uint16_t port, const union in_dependaddr *addr, int size)
1539 {
1540 	struct inp_localgroup *grp;
1541 
1542 	grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
1543 	    M_TEMP, M_INTWAIT | M_ZERO);
1544 	grp->il_vflag = vflag;
1545 	grp->il_lport = port;
1546 	grp->il_dependladdr = *addr;
1547 	grp->il_inpsiz = size;
1548 
1549 	LIST_INSERT_HEAD(hdr, grp, il_list);
1550 
1551 	return grp;
1552 }
1553 
1554 static void
1555 inp_localgroup_free(struct inp_localgroup *grp)
1556 {
1557 	LIST_REMOVE(grp, il_list);
1558 	kfree(grp, M_TEMP);
1559 }
1560 
1561 static struct inp_localgroup *
1562 inp_localgroup_resize(struct inp_localgrphead *hdr,
1563     struct inp_localgroup *old_grp, int size)
1564 {
1565 	struct inp_localgroup *grp;
1566 	int i;
1567 
1568 	grp = inp_localgroup_alloc(hdr, old_grp->il_vflag,
1569 	    old_grp->il_lport, &old_grp->il_dependladdr, size);
1570 
1571 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
1572 	    ("invalid new local group size %d and old local group count %d",
1573 	     grp->il_inpsiz, old_grp->il_inpcnt));
1574 	for (i = 0; i < old_grp->il_inpcnt; ++i)
1575 		grp->il_inp[i] = old_grp->il_inp[i];
1576 	grp->il_inpcnt = old_grp->il_inpcnt;
1577 	grp->il_factor = old_grp->il_factor;
1578 
1579 	inp_localgroup_free(old_grp);
1580 
1581 	return grp;
1582 }
1583 
1584 static void
1585 inp_localgroup_factor(struct inp_localgroup *grp)
1586 {
1587 	grp->il_factor =
1588 	    ((uint32_t)(0xffff >> ncpus2_shift) / grp->il_inpcnt) + 1;
1589 	KASSERT(grp->il_factor != 0, ("invalid local group factor, "
1590 	    "ncpus2_shift %d, inpcnt %d", ncpus2_shift, grp->il_inpcnt));
1591 }
1592 
1593 static void
1594 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1595 {
1596 	struct inp_localgrphead *hdr;
1597 	struct inp_localgroup *grp;
1598 	struct ucred *cred;
1599 
1600 	if (pcbinfo->localgrphashbase == NULL)
1601 		return;
1602 
1603 	/*
1604 	 * XXX don't allow jailed socket to join local group
1605 	 */
1606 	if (inp->inp_socket != NULL)
1607 		cred = inp->inp_socket->so_cred;
1608 	else
1609 		cred = NULL;
1610 	if (cred != NULL && jailed(cred))
1611 		return;
1612 
1613 #ifdef INET6
1614 	/*
1615 	 * XXX don't allow IPv4 mapped INET6 wild socket
1616 	 */
1617 	if ((inp->inp_vflag & INP_IPV4) &&
1618 	    inp->inp_laddr.s_addr == INADDR_ANY &&
1619 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6))
1620 		return;
1621 #endif
1622 
1623 	hdr = &pcbinfo->localgrphashbase[
1624 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1625 
1626 	LIST_FOREACH(grp, hdr, il_list) {
1627 		if (grp->il_vflag == inp->inp_vflag &&
1628 		    grp->il_lport == inp->inp_lport &&
1629 		    memcmp(&grp->il_dependladdr,
1630 		        &inp->inp_inc.inc_ie.ie_dependladdr,
1631 		        sizeof(grp->il_dependladdr)) == 0) {
1632 			break;
1633 		}
1634 	}
1635 	if (grp == NULL) {
1636 		/* Create new local group */
1637 		grp = inp_localgroup_alloc(hdr, inp->inp_vflag,
1638 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
1639 		    INP_LOCALGROUP_SIZMIN);
1640 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
1641 		if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
1642 			static int limit_logged = 0;
1643 
1644 			if (!limit_logged) {
1645 				limit_logged = 1;
1646 				kprintf("local group port %d, "
1647 				    "limit reached\n", ntohs(grp->il_lport));
1648 			}
1649 			return;
1650 		}
1651 
1652 		/* Expand this local group */
1653 		grp = inp_localgroup_resize(hdr, grp, grp->il_inpsiz * 2);
1654 	}
1655 
1656 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
1657 	    ("invalid local group size %d and count %d",
1658 	     grp->il_inpsiz, grp->il_inpcnt));
1659 	grp->il_inp[grp->il_inpcnt] = inp;
1660 	grp->il_inpcnt++;
1661 	inp_localgroup_factor(grp);
1662 }
1663 
1664 void
1665 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1666 {
1667 	struct inpcontainer *ic;
1668 	struct inpcontainerhead *bucket;
1669 
1670 	in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
1671 
1672 	bucket = &pcbinfo->wildcardhashbase[
1673 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1674 
1675 	ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1676 	ic->ic_inp = inp;
1677 	LIST_INSERT_HEAD(bucket, ic, ic_list);
1678 }
1679 
1680 /*
1681  * Insert PCB into wildcard hash table.
1682  */
1683 void
1684 in_pcbinswildcardhash(struct inpcb *inp)
1685 {
1686 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1687 
1688 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1689 		("already on connhash"));
1690 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1691 		("already on wildcardhash"));
1692 	inp->inp_flags |= INP_WILDCARD;
1693 
1694 	in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1695 }
1696 
1697 static void
1698 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1699 {
1700 	struct inp_localgrphead *hdr;
1701 	struct inp_localgroup *grp;
1702 
1703 	if (pcbinfo->localgrphashbase == NULL)
1704 		return;
1705 
1706 	hdr = &pcbinfo->localgrphashbase[
1707 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1708 
1709 	LIST_FOREACH(grp, hdr, il_list) {
1710 		int i;
1711 
1712 		for (i = 0; i < grp->il_inpcnt; ++i) {
1713 			if (grp->il_inp[i] != inp)
1714 				continue;
1715 
1716 			if (grp->il_inpcnt == 1) {
1717 				/* Free this local group */
1718 				inp_localgroup_free(grp);
1719 			} else {
1720 				/* Pull up inpcbs */
1721 				for (; i + 1 < grp->il_inpcnt; ++i)
1722 					grp->il_inp[i] = grp->il_inp[i + 1];
1723 				grp->il_inpcnt--;
1724 				inp_localgroup_factor(grp);
1725 
1726 				if (grp->il_inpsiz > INP_LOCALGROUP_SIZMIN &&
1727 				    grp->il_inpcnt <= (grp->il_inpsiz / 4)) {
1728 					/* Shrink this local group */
1729 					grp = inp_localgroup_resize(hdr, grp,
1730 					    grp->il_inpsiz / 2);
1731 				}
1732 			}
1733 			return;
1734 		}
1735 	}
1736 }
1737 
1738 void
1739 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1740 {
1741 	struct inpcontainer *ic;
1742 	struct inpcontainerhead *head;
1743 
1744 	in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
1745 
1746 	/* find bucket */
1747 	head = &pcbinfo->wildcardhashbase[
1748 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1749 
1750 	LIST_FOREACH(ic, head, ic_list) {
1751 		if (ic->ic_inp == inp)
1752 			goto found;
1753 	}
1754 	return;			/* not found! */
1755 
1756 found:
1757 	LIST_REMOVE(ic, ic_list);	/* remove container from bucket chain */
1758 	kfree(ic, M_TEMP);		/* deallocate container */
1759 }
1760 
1761 /*
1762  * Remove PCB from wildcard hash table.
1763  */
1764 void
1765 in_pcbremwildcardhash(struct inpcb *inp)
1766 {
1767 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1768 
1769 	KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1770 	in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1771 	inp->inp_flags &= ~INP_WILDCARD;
1772 }
1773 
1774 /*
1775  * Remove PCB from various lists.
1776  */
1777 void
1778 in_pcbremlists(struct inpcb *inp)
1779 {
1780 	struct inpcbinfo *pcbinfo;
1781 
1782 	if (inp->inp_lport) {
1783 		struct inpcbport *phd;
1784 
1785 		pcbinfo = inp->inp_pcbinfo;
1786 		if (pcbinfo->porttoken)
1787 			lwkt_gettoken(pcbinfo->porttoken);
1788 
1789 		phd = inp->inp_phd;
1790 		LIST_REMOVE(inp, inp_portlist);
1791 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1792 			LIST_REMOVE(phd, phd_hash);
1793 			kfree(phd, M_PCB);
1794 		}
1795 		if (pcbinfo->porttoken)
1796 			lwkt_reltoken(pcbinfo->porttoken);
1797 	}
1798 	if (inp->inp_flags & INP_WILDCARD) {
1799 		in_pcbremwildcardhash(inp);
1800 	} else if (inp->inp_flags & INP_CONNECTED) {
1801 		in_pcbremconnhash(inp);
1802 	}
1803 	LIST_REMOVE(inp, inp_list);
1804 	inp->inp_pcbinfo->ipi_count--;
1805 }
1806 
1807 int
1808 prison_xinpcb(struct thread *td, struct inpcb *inp)
1809 {
1810 	struct ucred *cr;
1811 
1812 	if (td->td_proc == NULL)
1813 		return (0);
1814 	cr = td->td_proc->p_ucred;
1815 	if (cr->cr_prison == NULL)
1816 		return (0);
1817 	if (inp->inp_socket && inp->inp_socket->so_cred &&
1818 	    inp->inp_socket->so_cred->cr_prison &&
1819 	    cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1820 		return (0);
1821 	return (1);
1822 }
1823 
1824 int
1825 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1826 {
1827 	struct inpcbinfo *pcbinfo = arg1;
1828 	struct inpcb *inp, *marker;
1829 	struct xinpcb xi;
1830 	int error, i, n;
1831 
1832 	/*
1833 	 * The process of preparing the TCB list is too time-consuming and
1834 	 * resource-intensive to repeat twice on every request.
1835 	 */
1836 	if (req->oldptr == NULL) {
1837 		n = pcbinfo->ipi_count;
1838 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1839 		return 0;
1840 	}
1841 
1842 	if (req->newptr != NULL)
1843 		return EPERM;
1844 
1845 	/*
1846 	 * OK, now we're committed to doing something.  Re-fetch ipi_count
1847 	 * after obtaining the generation count.
1848 	 */
1849 	n = pcbinfo->ipi_count;
1850 
1851 	marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1852 	marker->inp_flags |= INP_PLACEMARKER;
1853 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1854 
1855 	i = 0;
1856 	error = 0;
1857 
1858 	while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1859 		LIST_REMOVE(marker, inp_list);
1860 		LIST_INSERT_AFTER(inp, marker, inp_list);
1861 
1862 		if (inp->inp_flags & INP_PLACEMARKER)
1863 			continue;
1864 		if (prison_xinpcb(req->td, inp))
1865 			continue;
1866 		bzero(&xi, sizeof xi);
1867 		xi.xi_len = sizeof xi;
1868 		bcopy(inp, &xi.xi_inp, sizeof *inp);
1869 		if (inp->inp_socket)
1870 			sotoxsocket(inp->inp_socket, &xi.xi_socket);
1871 		if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1872 			break;
1873 		++i;
1874 	}
1875 	LIST_REMOVE(marker, inp_list);
1876 	if (error == 0 && i < n) {
1877 		bzero(&xi, sizeof xi);
1878 		xi.xi_len = sizeof xi;
1879 		while (i < n) {
1880 			error = SYSCTL_OUT(req, &xi, sizeof xi);
1881 			++i;
1882 		}
1883 	}
1884 	kfree(marker, M_TEMP);
1885 	return(error);
1886 }
1887 
1888 int
1889 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
1890 {
1891 	struct inpcbinfo *pcbinfo = arg1;
1892 	struct inpcb *inp;
1893 	struct xinpcb *xi;
1894 	int nxi;
1895 
1896 	*nxi0 = 0;
1897 	*xi0 = NULL;
1898 
1899 	/*
1900 	 * The process of preparing the PCB list is too time-consuming and
1901 	 * resource-intensive to repeat twice on every request.
1902 	 */
1903 	if (req->oldptr == NULL) {
1904 		int n = pcbinfo->ipi_count;
1905 
1906 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1907 		return 0;
1908 	}
1909 
1910 	if (req->newptr != NULL)
1911 		return EPERM;
1912 
1913 	if (pcbinfo->ipi_count == 0)
1914 		return 0;
1915 
1916 	nxi = 0;
1917 	xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
1918 		     M_WAITOK | M_ZERO | M_NULLOK);
1919 	if (xi == NULL)
1920 		return ENOMEM;
1921 
1922 	LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
1923 		struct xinpcb *xi_ptr = &xi[nxi];
1924 
1925 		if (prison_xinpcb(req->td, inp))
1926 			continue;
1927 
1928 		xi_ptr->xi_len = sizeof(*xi_ptr);
1929 		bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
1930 		if (inp->inp_socket)
1931 			sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
1932 		++nxi;
1933 	}
1934 
1935 	if (nxi == 0) {
1936 		kfree(xi, M_TEMP);
1937 		return 0;
1938 	}
1939 
1940 	*nxi0 = nxi;
1941 	*xi0 = xi;
1942 
1943 	return 0;
1944 }
1945 
1946 void
1947 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
1948 {
1949 	struct sockaddr_in *sin;
1950 
1951 	KASSERT(faddr->sa_family == AF_INET,
1952 	    ("not AF_INET faddr %d", faddr->sa_family));
1953 
1954 	sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
1955 	sin->sin_family = AF_INET;
1956 	sin->sin_len = sizeof(*sin);
1957 	sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
1958 	sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
1959 
1960 	so->so_faddr = (struct sockaddr *)sin;
1961 }
1962