xref: /dflybsd-src/sys/netinet/in_pcb.c (revision 5b9e25a85d29df90eb65d380ed6887dfeff7c012)
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 	pkt_hash >>= ncpus2_shift;
1253 
1254 	/*
1255 	 * Order of socket selection:
1256 	 * 1. non-wild.
1257 	 * 2. wild.
1258 	 *
1259 	 * NOTE:
1260 	 * - Local group does not contain jailed sockets
1261 	 * - Local group does not contain IPv4 mapped INET6 wild sockets
1262 	 */
1263 	LIST_FOREACH(grp, hdr, il_list) {
1264 #ifdef INET6
1265 		if (!(grp->il_vflag & INP_IPV4))
1266 			continue;
1267 #endif
1268 		if (grp->il_lport == lport) {
1269 			int idx;
1270 
1271 			idx = pkt_hash / grp->il_factor;
1272 			KASSERT(idx < grp->il_inpcnt && idx >= 0,
1273 			    ("invalid hash %04x, cnt %d or fact %d",
1274 			     pkt_hash, grp->il_inpcnt, grp->il_factor));
1275 
1276 			if (grp->il_laddr.s_addr == laddr.s_addr)
1277 				return grp->il_inp[idx];
1278 			else if (grp->il_laddr.s_addr == INADDR_ANY)
1279 				local_wild = grp->il_inp[idx];
1280 		}
1281 	}
1282 	if (local_wild != NULL)
1283 		return local_wild;
1284 	return NULL;
1285 }
1286 
1287 /*
1288  * Lookup PCB in hash list.
1289  */
1290 struct inpcb *
1291 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1292     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1293     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1294 {
1295 	struct inpcbhead *head;
1296 	struct inpcb *inp, *jinp=NULL;
1297 	u_short fport = fport_arg, lport = lport_arg;
1298 
1299 	/*
1300 	 * First look for an exact match.
1301 	 */
1302 	head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1303 	    laddr.s_addr, lport, pcbinfo->hashmask)];
1304 	LIST_FOREACH(inp, head, inp_hash) {
1305 #ifdef INET6
1306 		if (!(inp->inp_vflag & INP_IPV4))
1307 			continue;
1308 #endif
1309 		if (in_hosteq(inp->inp_faddr, faddr) &&
1310 		    in_hosteq(inp->inp_laddr, laddr) &&
1311 		    inp->inp_fport == fport && inp->inp_lport == lport) {
1312 			/* found */
1313 			if (inp->inp_socket == NULL ||
1314 			    inp->inp_socket->so_cred->cr_prison == NULL) {
1315 				return (inp);
1316 			} else {
1317 				if  (jinp == NULL)
1318 					jinp = inp;
1319 			}
1320 		}
1321 	}
1322 	if (jinp != NULL)
1323 		return (jinp);
1324 	if (wildcard) {
1325 		struct inpcb *local_wild = NULL;
1326 		struct inpcb *jinp_wild = NULL;
1327 #ifdef INET6
1328 		struct inpcb *local_wild_mapped = NULL;
1329 #endif
1330 		struct inpcontainer *ic;
1331 		struct inpcontainerhead *chead;
1332 		struct sockaddr_in jsin;
1333 		struct ucred *cred;
1334 
1335 		/*
1336 		 * Check local group first
1337 		 */
1338 		if (pcbinfo->localgrphashbase != NULL &&
1339 		    m != NULL && (m->m_flags & M_HASH) &&
1340 		    !(ifp && ifp->if_type == IFT_FAITH)) {
1341 			inp = inp_localgroup_lookup(pcbinfo,
1342 			    laddr, lport, m->m_pkthdr.hash);
1343 			if (inp != NULL)
1344 				return inp;
1345 		}
1346 
1347 		/*
1348 		 * Order of socket selection:
1349 		 * 1. non-jailed, non-wild.
1350 		 * 2. non-jailed, wild.
1351 		 * 3. jailed, non-wild.
1352 		 * 4. jailed, wild.
1353 		 */
1354 		jsin.sin_family = AF_INET;
1355 		chead = &pcbinfo->wildcardhashbase[
1356 		    INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1357 		LIST_FOREACH(ic, chead, ic_list) {
1358 			inp = ic->ic_inp;
1359 			jsin.sin_addr.s_addr = laddr.s_addr;
1360 #ifdef INET6
1361 			if (!(inp->inp_vflag & INP_IPV4))
1362 				continue;
1363 #endif
1364 			if (inp->inp_socket != NULL)
1365 				cred = inp->inp_socket->so_cred;
1366 			else
1367 				cred = NULL;
1368 			if (cred != NULL && jailed(cred)) {
1369 				if (jinp != NULL)
1370 					continue;
1371 				else
1372 					if (!jailed_ip(cred->cr_prison,
1373 					    (struct sockaddr *)&jsin))
1374 						continue;
1375 			}
1376 			if (inp->inp_lport == lport) {
1377 				if (ifp && ifp->if_type == IFT_FAITH &&
1378 				    !(inp->inp_flags & INP_FAITH))
1379 					continue;
1380 				if (inp->inp_laddr.s_addr == laddr.s_addr) {
1381 					if (cred != NULL && jailed(cred))
1382 						jinp = inp;
1383 					else
1384 						return (inp);
1385 				}
1386 				if (inp->inp_laddr.s_addr == INADDR_ANY) {
1387 #ifdef INET6
1388 					if (INP_CHECK_SOCKAF(inp->inp_socket,
1389 							     AF_INET6))
1390 						local_wild_mapped = inp;
1391 					else
1392 #endif
1393 						if (cred != NULL &&
1394 						    jailed(cred))
1395 							jinp_wild = inp;
1396 						else
1397 							local_wild = inp;
1398 				}
1399 			}
1400 		}
1401 		if (local_wild != NULL)
1402 			return (local_wild);
1403 #ifdef INET6
1404 		if (local_wild_mapped != NULL)
1405 			return (local_wild_mapped);
1406 #endif
1407 		if (jinp != NULL)
1408 			return (jinp);
1409 		return (jinp_wild);
1410 	}
1411 
1412 	/*
1413 	 * Not found.
1414 	 */
1415 	return (NULL);
1416 }
1417 
1418 struct inpcb *
1419 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1420     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1421     boolean_t wildcard, struct ifnet *ifp)
1422 {
1423 	return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1424 	    laddr, lport_arg, wildcard, ifp, NULL);
1425 }
1426 
1427 /*
1428  * Insert PCB into connection hash table.
1429  */
1430 void
1431 in_pcbinsconnhash(struct inpcb *inp)
1432 {
1433 	struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1434 	struct inpcbhead *bucket;
1435 	u_int32_t hashkey_faddr, hashkey_laddr;
1436 
1437 #ifdef INET6
1438 	if (inp->inp_vflag & INP_IPV6) {
1439 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1440 		hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1441 	} else {
1442 #endif
1443 		hashkey_faddr = inp->inp_faddr.s_addr;
1444 		hashkey_laddr = inp->inp_laddr.s_addr;
1445 #ifdef INET6
1446 	}
1447 #endif
1448 
1449 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1450 		("already on wildcardhash"));
1451 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1452 		("already on connhash"));
1453 	inp->inp_flags |= INP_CONNECTED;
1454 
1455 	/*
1456 	 * Insert into the connection hash table.
1457 	 */
1458 	bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1459 	    inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1460 	LIST_INSERT_HEAD(bucket, inp, inp_hash);
1461 }
1462 
1463 /*
1464  * Remove PCB from connection hash table.
1465  */
1466 void
1467 in_pcbremconnhash(struct inpcb *inp)
1468 {
1469 	KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1470 	LIST_REMOVE(inp, inp_hash);
1471 	inp->inp_flags &= ~INP_CONNECTED;
1472 }
1473 
1474 /*
1475  * Insert PCB into port hash table.
1476  */
1477 int
1478 in_pcbinsporthash(struct inpcb *inp)
1479 {
1480 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1481 	struct inpcbporthead *pcbporthash;
1482 	struct inpcbport *phd;
1483 
1484 	/*
1485 	 * If the porthashbase is shared across several cpus we need
1486 	 * to lock.
1487 	 */
1488 	if (pcbinfo->porttoken)
1489 		lwkt_gettoken(pcbinfo->porttoken);
1490 
1491 	/*
1492 	 * Insert into the port hash table.
1493 	 */
1494 	pcbporthash = &pcbinfo->porthashbase[
1495 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1496 
1497 	/* Go through port list and look for a head for this lport. */
1498 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1499 		if (phd->phd_port == inp->inp_lport)
1500 			break;
1501 	}
1502 
1503 	/* If none exists, malloc one and tack it on. */
1504 	if (phd == NULL) {
1505 		KKASSERT(pcbinfo->portsave != NULL);
1506 		phd = pcbinfo->portsave;
1507 		pcbinfo->portsave = NULL;
1508 		phd->phd_port = inp->inp_lport;
1509 		LIST_INIT(&phd->phd_pcblist);
1510 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1511 	}
1512 
1513 	inp->inp_phd = phd;
1514 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1515 
1516 	if (pcbinfo->porttoken)
1517 		lwkt_reltoken(pcbinfo->porttoken);
1518 	if (pcbinfo->portsave == NULL) {
1519 		pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1520 					    M_PCB, M_INTWAIT | M_ZERO);
1521 	}
1522 	return (0);
1523 }
1524 
1525 static struct inp_localgroup *
1526 inp_localgroup_alloc(struct inp_localgrphead *hdr, u_char vflag,
1527     uint16_t port, const union in_dependaddr *addr, int size)
1528 {
1529 	struct inp_localgroup *grp;
1530 
1531 	grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
1532 	    M_TEMP, M_INTWAIT | M_ZERO);
1533 	grp->il_vflag = vflag;
1534 	grp->il_lport = port;
1535 	grp->il_dependladdr = *addr;
1536 	grp->il_inpsiz = size;
1537 
1538 	LIST_INSERT_HEAD(hdr, grp, il_list);
1539 
1540 	return grp;
1541 }
1542 
1543 static void
1544 inp_localgroup_free(struct inp_localgroup *grp)
1545 {
1546 	LIST_REMOVE(grp, il_list);
1547 	kfree(grp, M_TEMP);
1548 }
1549 
1550 static struct inp_localgroup *
1551 inp_localgroup_resize(struct inp_localgrphead *hdr,
1552     struct inp_localgroup *old_grp, int size)
1553 {
1554 	struct inp_localgroup *grp;
1555 	int i;
1556 
1557 	grp = inp_localgroup_alloc(hdr, old_grp->il_vflag,
1558 	    old_grp->il_lport, &old_grp->il_dependladdr, size);
1559 
1560 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
1561 	    ("invalid new local group size %d and old local group count %d",
1562 	     grp->il_inpsiz, old_grp->il_inpcnt));
1563 	for (i = 0; i < old_grp->il_inpcnt; ++i)
1564 		grp->il_inp[i] = old_grp->il_inp[i];
1565 	grp->il_inpcnt = old_grp->il_inpcnt;
1566 	grp->il_factor = old_grp->il_factor;
1567 
1568 	inp_localgroup_free(old_grp);
1569 
1570 	return grp;
1571 }
1572 
1573 static void
1574 inp_localgroup_factor(struct inp_localgroup *grp)
1575 {
1576 	grp->il_factor =
1577 	    ((uint32_t)(0xffff >> ncpus2_shift) / grp->il_inpcnt) + 1;
1578 	KASSERT(grp->il_factor != 0, ("invalid local group factor, "
1579 	    "ncpus2_shift %d, inpcnt %d", ncpus2_shift, grp->il_inpcnt));
1580 }
1581 
1582 static void
1583 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1584 {
1585 	struct inp_localgrphead *hdr;
1586 	struct inp_localgroup *grp;
1587 	struct ucred *cred;
1588 
1589 	if (pcbinfo->localgrphashbase == NULL)
1590 		return;
1591 
1592 	/*
1593 	 * XXX don't allow jailed socket to join local group
1594 	 */
1595 	if (inp->inp_socket != NULL)
1596 		cred = inp->inp_socket->so_cred;
1597 	else
1598 		cred = NULL;
1599 	if (cred != NULL && jailed(cred))
1600 		return;
1601 
1602 #ifdef INET6
1603 	/*
1604 	 * XXX don't allow IPv4 mapped INET6 wild socket
1605 	 */
1606 	if ((inp->inp_vflag & INP_IPV4) &&
1607 	    inp->inp_laddr.s_addr == INADDR_ANY &&
1608 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6))
1609 		return;
1610 #endif
1611 
1612 	hdr = &pcbinfo->localgrphashbase[
1613 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1614 
1615 	LIST_FOREACH(grp, hdr, il_list) {
1616 		if (grp->il_vflag == inp->inp_vflag &&
1617 		    grp->il_lport == inp->inp_lport &&
1618 		    memcmp(&grp->il_dependladdr,
1619 		        &inp->inp_inc.inc_ie.ie_dependladdr,
1620 		        sizeof(grp->il_dependladdr)) == 0) {
1621 			break;
1622 		}
1623 	}
1624 	if (grp == NULL) {
1625 		/* Create new local group */
1626 		grp = inp_localgroup_alloc(hdr, inp->inp_vflag,
1627 		    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
1628 		    INP_LOCALGROUP_SIZMIN);
1629 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
1630 		if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
1631 			static int limit_logged = 0;
1632 
1633 			if (!limit_logged) {
1634 				limit_logged = 1;
1635 				kprintf("local group port %d, "
1636 				    "limit reached\n", ntohs(grp->il_lport));
1637 			}
1638 			return;
1639 		}
1640 
1641 		/* Expand this local group */
1642 		grp = inp_localgroup_resize(hdr, grp, grp->il_inpsiz * 2);
1643 	}
1644 
1645 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
1646 	    ("invalid local group size %d and count %d",
1647 	     grp->il_inpsiz, grp->il_inpcnt));
1648 	grp->il_inp[grp->il_inpcnt] = inp;
1649 	grp->il_inpcnt++;
1650 	inp_localgroup_factor(grp);
1651 }
1652 
1653 void
1654 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1655 {
1656 	struct inpcontainer *ic;
1657 	struct inpcontainerhead *bucket;
1658 
1659 	in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
1660 
1661 	bucket = &pcbinfo->wildcardhashbase[
1662 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1663 
1664 	ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1665 	ic->ic_inp = inp;
1666 	LIST_INSERT_HEAD(bucket, ic, ic_list);
1667 }
1668 
1669 /*
1670  * Insert PCB into wildcard hash table.
1671  */
1672 void
1673 in_pcbinswildcardhash(struct inpcb *inp)
1674 {
1675 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1676 
1677 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1678 		("already on connhash"));
1679 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1680 		("already on wildcardhash"));
1681 	inp->inp_flags |= INP_WILDCARD;
1682 
1683 	in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1684 }
1685 
1686 static void
1687 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1688 {
1689 	struct inp_localgrphead *hdr;
1690 	struct inp_localgroup *grp;
1691 
1692 	if (pcbinfo->localgrphashbase == NULL)
1693 		return;
1694 
1695 	hdr = &pcbinfo->localgrphashbase[
1696 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1697 
1698 	LIST_FOREACH(grp, hdr, il_list) {
1699 		int i;
1700 
1701 		for (i = 0; i < grp->il_inpcnt; ++i) {
1702 			if (grp->il_inp[i] != inp)
1703 				continue;
1704 
1705 			if (grp->il_inpcnt == 1) {
1706 				/* Free this local group */
1707 				inp_localgroup_free(grp);
1708 			} else {
1709 				/* Pull up inpcbs */
1710 				for (; i + 1 < grp->il_inpcnt; ++i)
1711 					grp->il_inp[i] = grp->il_inp[i + 1];
1712 				grp->il_inpcnt--;
1713 				inp_localgroup_factor(grp);
1714 
1715 				if (grp->il_inpsiz > INP_LOCALGROUP_SIZMIN &&
1716 				    grp->il_inpcnt <= (grp->il_inpsiz / 4)) {
1717 					/* Shrink this local group */
1718 					grp = inp_localgroup_resize(hdr, grp,
1719 					    grp->il_inpsiz / 2);
1720 				}
1721 			}
1722 			return;
1723 		}
1724 	}
1725 }
1726 
1727 void
1728 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1729 {
1730 	struct inpcontainer *ic;
1731 	struct inpcontainerhead *head;
1732 
1733 	in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
1734 
1735 	/* find bucket */
1736 	head = &pcbinfo->wildcardhashbase[
1737 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1738 
1739 	LIST_FOREACH(ic, head, ic_list) {
1740 		if (ic->ic_inp == inp)
1741 			goto found;
1742 	}
1743 	return;			/* not found! */
1744 
1745 found:
1746 	LIST_REMOVE(ic, ic_list);	/* remove container from bucket chain */
1747 	kfree(ic, M_TEMP);		/* deallocate container */
1748 }
1749 
1750 /*
1751  * Remove PCB from wildcard hash table.
1752  */
1753 void
1754 in_pcbremwildcardhash(struct inpcb *inp)
1755 {
1756 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1757 
1758 	KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1759 	in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1760 	inp->inp_flags &= ~INP_WILDCARD;
1761 }
1762 
1763 /*
1764  * Remove PCB from various lists.
1765  */
1766 void
1767 in_pcbremlists(struct inpcb *inp)
1768 {
1769 	struct inpcbinfo *pcbinfo;
1770 
1771 	if (inp->inp_lport) {
1772 		struct inpcbport *phd;
1773 
1774 		pcbinfo = inp->inp_pcbinfo;
1775 		if (pcbinfo->porttoken)
1776 			lwkt_gettoken(pcbinfo->porttoken);
1777 
1778 		phd = inp->inp_phd;
1779 		LIST_REMOVE(inp, inp_portlist);
1780 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1781 			LIST_REMOVE(phd, phd_hash);
1782 			kfree(phd, M_PCB);
1783 		}
1784 		if (pcbinfo->porttoken)
1785 			lwkt_reltoken(pcbinfo->porttoken);
1786 	}
1787 	if (inp->inp_flags & INP_WILDCARD) {
1788 		in_pcbremwildcardhash(inp);
1789 	} else if (inp->inp_flags & INP_CONNECTED) {
1790 		in_pcbremconnhash(inp);
1791 	}
1792 	LIST_REMOVE(inp, inp_list);
1793 	inp->inp_pcbinfo->ipi_count--;
1794 }
1795 
1796 int
1797 prison_xinpcb(struct thread *td, struct inpcb *inp)
1798 {
1799 	struct ucred *cr;
1800 
1801 	if (td->td_proc == NULL)
1802 		return (0);
1803 	cr = td->td_proc->p_ucred;
1804 	if (cr->cr_prison == NULL)
1805 		return (0);
1806 	if (inp->inp_socket && inp->inp_socket->so_cred &&
1807 	    inp->inp_socket->so_cred->cr_prison &&
1808 	    cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1809 		return (0);
1810 	return (1);
1811 }
1812 
1813 int
1814 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1815 {
1816 	struct inpcbinfo *pcbinfo = arg1;
1817 	struct inpcb *inp, *marker;
1818 	struct xinpcb xi;
1819 	int error, i, n;
1820 
1821 	/*
1822 	 * The process of preparing the TCB list is too time-consuming and
1823 	 * resource-intensive to repeat twice on every request.
1824 	 */
1825 	if (req->oldptr == NULL) {
1826 		n = pcbinfo->ipi_count;
1827 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1828 		return 0;
1829 	}
1830 
1831 	if (req->newptr != NULL)
1832 		return EPERM;
1833 
1834 	/*
1835 	 * OK, now we're committed to doing something.  Re-fetch ipi_count
1836 	 * after obtaining the generation count.
1837 	 */
1838 	n = pcbinfo->ipi_count;
1839 
1840 	marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1841 	marker->inp_flags |= INP_PLACEMARKER;
1842 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1843 
1844 	i = 0;
1845 	error = 0;
1846 
1847 	while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1848 		LIST_REMOVE(marker, inp_list);
1849 		LIST_INSERT_AFTER(inp, marker, inp_list);
1850 
1851 		if (inp->inp_flags & INP_PLACEMARKER)
1852 			continue;
1853 		if (prison_xinpcb(req->td, inp))
1854 			continue;
1855 		bzero(&xi, sizeof xi);
1856 		xi.xi_len = sizeof xi;
1857 		bcopy(inp, &xi.xi_inp, sizeof *inp);
1858 		if (inp->inp_socket)
1859 			sotoxsocket(inp->inp_socket, &xi.xi_socket);
1860 		if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1861 			break;
1862 		++i;
1863 	}
1864 	LIST_REMOVE(marker, inp_list);
1865 	if (error == 0 && i < n) {
1866 		bzero(&xi, sizeof xi);
1867 		xi.xi_len = sizeof xi;
1868 		while (i < n) {
1869 			error = SYSCTL_OUT(req, &xi, sizeof xi);
1870 			++i;
1871 		}
1872 	}
1873 	kfree(marker, M_TEMP);
1874 	return(error);
1875 }
1876 
1877 int
1878 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
1879 {
1880 	struct inpcbinfo *pcbinfo = arg1;
1881 	struct inpcb *inp;
1882 	struct xinpcb *xi;
1883 	int nxi;
1884 
1885 	*nxi0 = 0;
1886 	*xi0 = NULL;
1887 
1888 	/*
1889 	 * The process of preparing the PCB list is too time-consuming and
1890 	 * resource-intensive to repeat twice on every request.
1891 	 */
1892 	if (req->oldptr == NULL) {
1893 		int n = pcbinfo->ipi_count;
1894 
1895 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1896 		return 0;
1897 	}
1898 
1899 	if (req->newptr != NULL)
1900 		return EPERM;
1901 
1902 	if (pcbinfo->ipi_count == 0)
1903 		return 0;
1904 
1905 	nxi = 0;
1906 	xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
1907 		     M_WAITOK | M_ZERO | M_NULLOK);
1908 	if (xi == NULL)
1909 		return ENOMEM;
1910 
1911 	LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
1912 		struct xinpcb *xi_ptr = &xi[nxi];
1913 
1914 		if (prison_xinpcb(req->td, inp))
1915 			continue;
1916 
1917 		xi_ptr->xi_len = sizeof(*xi_ptr);
1918 		bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
1919 		if (inp->inp_socket)
1920 			sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
1921 		++nxi;
1922 	}
1923 
1924 	if (nxi == 0) {
1925 		kfree(xi, M_TEMP);
1926 		return 0;
1927 	}
1928 
1929 	*nxi0 = nxi;
1930 	*xi0 = xi;
1931 
1932 	return 0;
1933 }
1934 
1935 void
1936 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
1937 {
1938 	struct sockaddr_in *sin;
1939 
1940 	KASSERT(faddr->sa_family == AF_INET,
1941 	    ("not AF_INET faddr %d", faddr->sa_family));
1942 
1943 	sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
1944 	sin->sin_family = AF_INET;
1945 	sin->sin_len = sizeof(*sin);
1946 	sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
1947 	sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
1948 
1949 	so->so_faddr = (struct sockaddr *)sin;
1950 }
1951