xref: /dragonfly/sys/netinet/in_pcb.c (revision 4ff4d99f)
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 = 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 	KASSERT(inp->inp_pcbinfo == pcbinfo, ("pcbinfo mismatch"));
269 	KASSERT((inp->inp_flags & (INP_WILDCARD | INP_CONNECTED)) == 0,
270 	    ("already linked"));
271 
272 	LIST_REMOVE(inp, inp_list);
273 	pcbinfo->ipi_count--;
274 	inp->inp_pcbinfo = NULL;
275 }
276 
277 /*
278  * Relink a pcb into a new pcbinfo.
279  */
280 void
281 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
282 {
283 	KASSERT(inp->inp_pcbinfo == NULL, ("has pcbinfo"));
284 	KASSERT((inp->inp_flags & (INP_WILDCARD | INP_CONNECTED)) == 0,
285 	    ("already linked"));
286 
287 	inp->inp_pcbinfo = pcbinfo;
288 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
289 	pcbinfo->ipi_count++;
290 }
291 
292 static int
293 in_pcbsetlport(struct inpcb *inp, int wild, struct ucred *cred)
294 {
295 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
296 	struct inpcbportinfo *portinfo;
297 	u_short first, last, lport, step;
298 	u_short *lastport;
299 	int count, error;
300 	int portinfo_first, portinfo_idx;
301 
302 	inp->inp_flags |= INP_ANONPORT;
303 
304 	step = pcbinfo->portinfo_mask + 1;
305 	portinfo_first = mycpuid & pcbinfo->portinfo_mask;
306 	portinfo_idx = portinfo_first;
307 loop:
308 	portinfo = &pcbinfo->portinfo[portinfo_idx];
309 
310 	if (inp->inp_flags & INP_HIGHPORT) {
311 		first = ipport_hifirstauto;	/* sysctl */
312 		last  = ipport_hilastauto;
313 		lastport = &portinfo->lasthi;
314 	} else if (inp->inp_flags & INP_LOWPORT) {
315 		if (cred &&
316 		    (error =
317 		     priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
318 			inp->inp_laddr.s_addr = INADDR_ANY;
319 			return error;
320 		}
321 		first = ipport_lowfirstauto;	/* 1023 */
322 		last  = ipport_lowlastauto;	/* 600 */
323 		lastport = &portinfo->lastlow;
324 	} else {
325 		first = ipport_firstauto;	/* sysctl */
326 		last  = ipport_lastauto;
327 		lastport = &portinfo->lastport;
328 	}
329 
330 	/*
331 	 * This has to be atomic.  If the porthash is shared across multiple
332 	 * protocol threads (aka tcp) then the token must be held.
333 	 */
334 	GET_PORT_TOKEN(portinfo);
335 
336 	/*
337 	 * Simple check to ensure all ports are not used up causing
338 	 * a deadlock here.
339 	 *
340 	 * We split the two cases (up and down) so that the direction
341 	 * is not being tested on each round of the loop.
342 	 */
343 	if (first > last) {
344 		/*
345 		 * counting down
346 		 */
347 		in_pcbportrange(&first, &last, portinfo->offset, step);
348 		count = (first - last) / step;
349 
350 		do {
351 			if (count-- < 0) {	/* completely used? */
352 				error = EADDRNOTAVAIL;
353 				goto done;
354 			}
355 			*lastport -= step;
356 			if (*lastport > first || *lastport < last)
357 				*lastport = first;
358 			KKASSERT((*lastport & pcbinfo->portinfo_mask) ==
359 			    portinfo->offset);
360 			lport = htons(*lastport);
361 		} while (in_pcblookup_local(portinfo, inp->inp_laddr, lport,
362 		    wild, cred));
363 	} else {
364 		/*
365 		 * counting up
366 		 */
367 		in_pcbportrange(&last, &first, portinfo->offset, step);
368 		count = (last - first) / step;
369 
370 		do {
371 			if (count-- < 0) {	/* completely used? */
372 				error = EADDRNOTAVAIL;
373 				goto done;
374 			}
375 			*lastport += step;
376 			if (*lastport < first || *lastport > last)
377 				*lastport = first;
378 			KKASSERT((*lastport & pcbinfo->portinfo_mask) ==
379 			    portinfo->offset);
380 			lport = htons(*lastport);
381 		} while (in_pcblookup_local(portinfo, inp->inp_laddr, lport,
382 		    wild, cred));
383 	}
384 	inp->inp_lport = lport;
385 	in_pcbinsporthash(portinfo, inp);
386 	error = 0;
387 done:
388 	REL_PORT_TOKEN(portinfo);
389 
390 	if (error) {
391 		/* Try next portinfo */
392 		portinfo_idx++;
393 		portinfo_idx &= pcbinfo->portinfo_mask;
394 		if (portinfo_idx != portinfo_first)
395 			goto loop;
396 		inp->inp_laddr.s_addr = INADDR_ANY;
397 	}
398 	return error;
399 }
400 
401 int
402 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
403 {
404 	struct socket *so = inp->inp_socket;
405 	struct sockaddr_in jsin;
406 	struct ucred *cred = NULL;
407 	int wild = 0;
408 
409 	if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
410 		return (EADDRNOTAVAIL);
411 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
412 		return (EINVAL);	/* already bound */
413 
414 	if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
415 		wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
416 	if (td->td_proc)
417 		cred = td->td_proc->p_ucred;
418 
419 	if (nam != NULL) {
420 		struct sockaddr_in *sin = (struct sockaddr_in *)nam;
421 		struct inpcbinfo *pcbinfo;
422 		struct inpcbportinfo *portinfo;
423 		struct inpcb *t;
424 		u_short lport, lport_ho;
425 		int reuseport = (so->so_options & SO_REUSEPORT);
426 		int error;
427 
428 		if (nam->sa_len != sizeof *sin)
429 			return (EINVAL);
430 #ifdef notdef
431 		/*
432 		 * We should check the family, but old programs
433 		 * incorrectly fail to initialize it.
434 		 */
435 		if (sin->sin_family != AF_INET)
436 			return (EAFNOSUPPORT);
437 #endif
438 		if (!prison_replace_wildcards(td, nam))
439 			return (EINVAL);
440 
441 		lport = sin->sin_port;
442 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
443 			/*
444 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
445 			 * allow complete duplication of binding if
446 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
447 			 * and a multicast address is bound on both
448 			 * new and duplicated sockets.
449 			 */
450 			if (so->so_options & SO_REUSEADDR)
451 				reuseport = SO_REUSEADDR | SO_REUSEPORT;
452 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
453 			sin->sin_port = 0;		/* yech... */
454 			bzero(&sin->sin_zero, sizeof sin->sin_zero);
455 			if (ifa_ifwithaddr((struct sockaddr *)sin) == NULL)
456 				return (EADDRNOTAVAIL);
457 		}
458 
459 		inp->inp_laddr = sin->sin_addr;
460 
461 		jsin.sin_family = AF_INET;
462 		jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
463 		if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
464 			inp->inp_laddr.s_addr = INADDR_ANY;
465 			return (EINVAL);
466 		}
467 		inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
468 
469 		if (lport == 0) {
470 			/* Auto-select local port */
471 			return in_pcbsetlport(inp, wild, cred);
472 		}
473 		lport_ho = ntohs(lport);
474 
475 		/* GROSS */
476 		if (lport_ho < IPPORT_RESERVED && cred &&
477 		    (error =
478 		     priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
479 			inp->inp_laddr.s_addr = INADDR_ANY;
480 			return (error);
481 		}
482 
483 		/*
484 		 * Locate the proper portinfo based on lport
485 		 */
486 		pcbinfo = inp->inp_pcbinfo;
487 		portinfo =
488 		    &pcbinfo->portinfo[lport_ho & pcbinfo->portinfo_mask];
489 		KKASSERT((lport_ho & pcbinfo->portinfo_mask) ==
490 		    portinfo->offset);
491 
492 		/*
493 		 * This has to be atomic.  If the porthash is shared across
494 		 * multiple protocol threads (aka tcp) then the token must
495 		 * be held.
496 		 */
497 		GET_PORT_TOKEN(portinfo);
498 
499 		if (so->so_cred->cr_uid != 0 &&
500 		    !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
501 			t = in_pcblookup_local(portinfo, sin->sin_addr, lport,
502 			    INPLOOKUP_WILDCARD, cred);
503 			if (t &&
504 			    (!in_nullhost(sin->sin_addr) ||
505 			     !in_nullhost(t->inp_laddr) ||
506 			     (t->inp_socket->so_options & SO_REUSEPORT) == 0) &&
507 			    (so->so_cred->cr_uid !=
508 			     t->inp_socket->so_cred->cr_uid)) {
509 #ifdef INET6
510 				if (!in_nullhost(sin->sin_addr) ||
511 				    !in_nullhost(t->inp_laddr) ||
512 				    INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))
513 #endif
514 				{
515 					inp->inp_laddr.s_addr = INADDR_ANY;
516 					error = EADDRINUSE;
517 					goto done;
518 				}
519 			}
520 		}
521 		if (cred && !prison_replace_wildcards(td, nam)) {
522 			inp->inp_laddr.s_addr = INADDR_ANY;
523 			error = EADDRNOTAVAIL;
524 			goto done;
525 		}
526 		t = in_pcblookup_local(portinfo, sin->sin_addr, lport,
527 		    wild, cred);
528 		if (t && !(reuseport & t->inp_socket->so_options)) {
529 #ifdef INET6
530 			if (!in_nullhost(sin->sin_addr) ||
531 			    !in_nullhost(t->inp_laddr) ||
532 			    INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))
533 #endif
534 			{
535 				inp->inp_laddr.s_addr = INADDR_ANY;
536 				error = EADDRINUSE;
537 				goto done;
538 			}
539 		}
540 		inp->inp_lport = lport;
541 		in_pcbinsporthash(portinfo, inp);
542 		error = 0;
543 done:
544 		REL_PORT_TOKEN(portinfo);
545 		return (error);
546 	} else {
547 		jsin.sin_family = AF_INET;
548 		jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
549 		if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
550 			inp->inp_laddr.s_addr = INADDR_ANY;
551 			return (EINVAL);
552 		}
553 		inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
554 
555 		return in_pcbsetlport(inp, wild, cred);
556 	}
557 }
558 
559 static struct inpcb *
560 in_pcblookup_localremote(struct inpcbportinfo *portinfo, struct in_addr laddr,
561     u_short lport, struct in_addr faddr, u_short fport, struct ucred *cred)
562 {
563 	struct inpcb *inp;
564 	struct inpcbporthead *porthash;
565 	struct inpcbport *phd;
566 	struct inpcb *match = NULL;
567 
568 	/*
569 	 * If the porthashbase is shared across several cpus, it must
570 	 * have been locked.
571 	 */
572 	ASSERT_PORT_TOKEN_HELD(portinfo);
573 
574 	/*
575 	 * Best fit PCB lookup.
576 	 *
577 	 * First see if this local port is in use by looking on the
578 	 * port hash list.
579 	 */
580 	porthash = &portinfo->porthashbase[
581 			INP_PCBPORTHASH(lport, portinfo->porthashmask)];
582 	LIST_FOREACH(phd, porthash, phd_hash) {
583 		if (phd->phd_port == lport)
584 			break;
585 	}
586 	if (phd != NULL) {
587 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
588 #ifdef INET6
589 			if ((inp->inp_vflag & INP_IPV4) == 0)
590 				continue;
591 #endif
592 			if (inp->inp_laddr.s_addr != INADDR_ANY &&
593 			    inp->inp_laddr.s_addr != laddr.s_addr)
594 				continue;
595 
596 			if (inp->inp_faddr.s_addr != INADDR_ANY &&
597 			    inp->inp_faddr.s_addr != faddr.s_addr)
598 				continue;
599 
600 			if (inp->inp_fport != 0 && inp->inp_fport != fport)
601 				continue;
602 
603 			if (cred == NULL ||
604 			    cred->cr_prison ==
605 			    inp->inp_socket->so_cred->cr_prison) {
606 				match = inp;
607 				break;
608 			}
609 		}
610 	}
611 	return (match);
612 }
613 
614 int
615 in_pcbbind_remote(struct inpcb *inp, const struct sockaddr *remote,
616     struct thread *td)
617 {
618 	struct proc *p = td->td_proc;
619 	unsigned short *lastport;
620 	const struct sockaddr_in *sin = (const struct sockaddr_in *)remote;
621 	struct sockaddr_in jsin;
622 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
623 	struct inpcbportinfo *portinfo;
624 	struct ucred *cred = NULL;
625 	u_short first, last, lport, step;
626 	int count, error, dup;
627 	int portinfo_first, portinfo_idx;
628 
629 	if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
630 		return (EADDRNOTAVAIL);
631 
632 	KKASSERT(inp->inp_laddr.s_addr != INADDR_ANY);
633 	if (inp->inp_lport != 0)
634 		return (EINVAL);	/* already bound */
635 
636 	KKASSERT(p);
637 	cred = p->p_ucred;
638 
639 	jsin.sin_family = AF_INET;
640 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
641 	if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
642 		inp->inp_laddr.s_addr = INADDR_ANY;
643 		return (EINVAL);
644 	}
645 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
646 
647 	inp->inp_flags |= INP_ANONPORT;
648 
649 	step = pcbinfo->portinfo_mask + 1;
650 	portinfo_first = mycpuid & pcbinfo->portinfo_mask;
651 	portinfo_idx = portinfo_first;
652 loop:
653 	portinfo = &pcbinfo->portinfo[portinfo_idx];
654 	dup = 0;
655 
656 	if (inp->inp_flags & INP_HIGHPORT) {
657 		first = ipport_hifirstauto;	/* sysctl */
658 		last  = ipport_hilastauto;
659 		lastport = &portinfo->lasthi;
660 	} else if (inp->inp_flags & INP_LOWPORT) {
661 		if (cred &&
662 		    (error =
663 		     priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
664 			inp->inp_laddr.s_addr = INADDR_ANY;
665 			return (error);
666 		}
667 		first = ipport_lowfirstauto;	/* 1023 */
668 		last  = ipport_lowlastauto;	/* 600 */
669 		lastport = &portinfo->lastlow;
670 	} else {
671 		first = ipport_firstauto;	/* sysctl */
672 		last  = ipport_lastauto;
673 		lastport = &portinfo->lastport;
674 	}
675 
676 	/*
677 	 * This has to be atomic.  If the porthash is shared across multiple
678 	 * protocol threads (aka tcp) then the token must be held.
679 	 */
680 	GET_PORT_TOKEN(portinfo);
681 
682 again:
683 	/*
684 	 * Simple check to ensure all ports are not used up causing
685 	 * a deadlock here.
686 	 *
687 	 * We split the two cases (up and down) so that the direction
688 	 * is not being tested on each round of the loop.
689 	 */
690 	if (first > last) {
691 		/*
692 		 * counting down
693 		 */
694 		in_pcbportrange(&first, &last, portinfo->offset, step);
695 		count = (first - last) / step;
696 
697 		do {
698 			if (count-- < 0) {	/* completely used? */
699 				error = EADDRNOTAVAIL;
700 				goto done;
701 			}
702 			*lastport -= step;
703 			if (*lastport > first || *lastport < last)
704 				*lastport = first;
705 			KKASSERT((*lastport & pcbinfo->portinfo_mask) ==
706 			    portinfo->offset);
707 			lport = htons(*lastport);
708 		} while (in_pcblookup_localremote(portinfo, inp->inp_laddr,
709 		    lport, sin->sin_addr, sin->sin_port, cred));
710 	} else {
711 		/*
712 		 * counting up
713 		 */
714 		in_pcbportrange(&last, &first, portinfo->offset, step);
715 		count = (last - first) / step;
716 
717 		do {
718 			if (count-- < 0) {	/* completely used? */
719 				error = EADDRNOTAVAIL;
720 				goto done;
721 			}
722 			*lastport += step;
723 			if (*lastport < first || *lastport > last)
724 				*lastport = first;
725 			KKASSERT((*lastport & pcbinfo->portinfo_mask) ==
726 			    portinfo->offset);
727 			lport = htons(*lastport);
728 		} while (in_pcblookup_localremote(portinfo, inp->inp_laddr,
729 		    lport, sin->sin_addr, sin->sin_port, cred));
730 	}
731 
732 	/* This could happen on loopback interface */
733 	if (sin->sin_port == lport &&
734 	    sin->sin_addr.s_addr == inp->inp_laddr.s_addr) {
735 		if (dup) {
736 			/*
737 			 * Duplicate again; give up
738 			 */
739 			error = EADDRNOTAVAIL;
740 			goto done;
741 		}
742 		dup = 1;
743 		goto again;
744 	}
745 	inp->inp_lport = lport;
746 	in_pcbinsporthash(portinfo, inp);
747 	error = 0;
748 done:
749 	REL_PORT_TOKEN(portinfo);
750 
751 	if (error) {
752 		/* Try next portinfo */
753 		portinfo_idx++;
754 		portinfo_idx &= pcbinfo->portinfo_mask;
755 		if (portinfo_idx != portinfo_first)
756 			goto loop;
757 		inp->inp_laddr.s_addr = INADDR_ANY;
758 	}
759 	return error;
760 }
761 
762 /*
763  *   Transform old in_pcbconnect() into an inner subroutine for new
764  *   in_pcbconnect(): Do some validity-checking on the remote
765  *   address (in mbuf 'nam') and then determine local host address
766  *   (i.e., which interface) to use to access that remote host.
767  *
768  *   This preserves definition of in_pcbconnect(), while supporting a
769  *   slightly different version for T/TCP.  (This is more than
770  *   a bit of a kludge, but cleaning up the internal interfaces would
771  *   have forced minor changes in every protocol).
772  */
773 int
774 in_pcbladdr_find(struct inpcb *inp, struct sockaddr *nam,
775     struct sockaddr_in **plocal_sin, struct thread *td, int find)
776 {
777 	struct in_ifaddr *ia;
778 	struct ucred *cred = NULL;
779 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
780 	struct sockaddr *jsin;
781 	int jailed = 0, alloc_route = 0;
782 
783 	if (nam->sa_len != sizeof *sin)
784 		return (EINVAL);
785 	if (sin->sin_family != AF_INET)
786 		return (EAFNOSUPPORT);
787 	if (sin->sin_port == 0)
788 		return (EADDRNOTAVAIL);
789 	if (td && td->td_proc && td->td_proc->p_ucred)
790 		cred = td->td_proc->p_ucred;
791 	if (cred && cred->cr_prison)
792 		jailed = 1;
793 	if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
794 		ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
795 		/*
796 		 * If the destination address is INADDR_ANY,
797 		 * use the primary local address.
798 		 * If the supplied address is INADDR_BROADCAST,
799 		 * and the primary interface supports broadcast,
800 		 * choose the broadcast address for that interface.
801 		 */
802 		if (sin->sin_addr.s_addr == INADDR_ANY)
803 			sin->sin_addr = IA_SIN(ia)->sin_addr;
804 		else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
805 		    (ia->ia_ifp->if_flags & IFF_BROADCAST))
806 			sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
807 	}
808 	if (find) {
809 		struct route *ro;
810 
811 		ia = NULL;
812 		/*
813 		 * If route is known or can be allocated now,
814 		 * our src addr is taken from the i/f, else punt.
815 		 * Note that we should check the address family of the cached
816 		 * destination, in case of sharing the cache with IPv6.
817 		 */
818 		ro = &inp->inp_route;
819 		if (ro->ro_rt &&
820 		    (!(ro->ro_rt->rt_flags & RTF_UP) ||
821 		     ro->ro_dst.sa_family != AF_INET ||
822 		     satosin(&ro->ro_dst)->sin_addr.s_addr !=
823 				      sin->sin_addr.s_addr ||
824 		     inp->inp_socket->so_options & SO_DONTROUTE)) {
825 			RTFREE(ro->ro_rt);
826 			ro->ro_rt = NULL;
827 		}
828 		if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
829 		    (ro->ro_rt == NULL ||
830 		    ro->ro_rt->rt_ifp == NULL)) {
831 			/* No route yet, so try to acquire one */
832 			bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
833 			ro->ro_dst.sa_family = AF_INET;
834 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
835 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
836 				sin->sin_addr;
837 			rtalloc(ro);
838 			alloc_route = 1;
839 		}
840 		/*
841 		 * If we found a route, use the address
842 		 * corresponding to the outgoing interface
843 		 * unless it is the loopback (in case a route
844 		 * to our address on another net goes to loopback).
845 		 */
846 		if (ro->ro_rt &&
847 		    !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
848 			if (jailed) {
849 				if (jailed_ip(cred->cr_prison,
850 				    ro->ro_rt->rt_ifa->ifa_addr)) {
851 					ia = ifatoia(ro->ro_rt->rt_ifa);
852 				}
853 			} else {
854 				ia = ifatoia(ro->ro_rt->rt_ifa);
855 			}
856 		}
857 		if (ia == NULL) {
858 			u_short fport = sin->sin_port;
859 
860 			sin->sin_port = 0;
861 			ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
862 			if (ia && jailed && !jailed_ip(cred->cr_prison,
863 			    sintosa(&ia->ia_addr)))
864 				ia = NULL;
865 			if (ia == NULL)
866 				ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
867 			if (ia && jailed && !jailed_ip(cred->cr_prison,
868 			    sintosa(&ia->ia_addr)))
869 				ia = NULL;
870 			sin->sin_port = fport;
871 			if (ia == NULL &&
872 			    !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
873 				ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
874 			if (ia && jailed && !jailed_ip(cred->cr_prison,
875 			    sintosa(&ia->ia_addr)))
876 				ia = NULL;
877 
878 			if (!jailed && ia == NULL)
879 				goto fail;
880 		}
881 		/*
882 		 * If the destination address is multicast and an outgoing
883 		 * interface has been set as a multicast option, use the
884 		 * address of that interface as our source address.
885 		 */
886 		if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
887 		    inp->inp_moptions != NULL) {
888 			struct ip_moptions *imo;
889 			struct ifnet *ifp;
890 
891 			imo = inp->inp_moptions;
892 			if (imo->imo_multicast_ifp != NULL) {
893 				struct in_ifaddr_container *iac;
894 
895 				ifp = imo->imo_multicast_ifp;
896 				ia = NULL;
897 				TAILQ_FOREACH(iac,
898 				&in_ifaddrheads[mycpuid], ia_link) {
899 					if (iac->ia->ia_ifp == ifp) {
900 						ia = iac->ia;
901 						break;
902 					}
903 				}
904 				if (ia == NULL)
905 					goto fail;
906 			}
907 		}
908 		/*
909 		 * Don't do pcblookup call here; return interface in plocal_sin
910 		 * and exit to caller, that will do the lookup.
911 		 */
912 		if (ia == NULL && jailed) {
913 			if ((jsin = prison_get_nonlocal(
914 				cred->cr_prison, AF_INET, NULL)) != NULL ||
915 			    (jsin = prison_get_local(
916 				cred->cr_prison, AF_INET, NULL)) != NULL) {
917 				*plocal_sin = satosin(jsin);
918 			} else {
919 				/* IPv6 only Jail */
920 				goto fail;
921 			}
922 		} else {
923 			*plocal_sin = &ia->ia_addr;
924 		}
925 	}
926 	return (0);
927 fail:
928 	if (alloc_route) {
929 		struct route *ro = &inp->inp_route;
930 
931 		if (ro->ro_rt != NULL)
932 			RTFREE(ro->ro_rt);
933 		bzero(ro, sizeof(*ro));
934 	}
935 	return (EADDRNOTAVAIL);
936 }
937 
938 int
939 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
940     struct sockaddr_in **plocal_sin, struct thread *td)
941 {
942 	return in_pcbladdr_find(inp, nam, plocal_sin, td,
943 	    (inp->inp_laddr.s_addr == INADDR_ANY));
944 }
945 
946 /*
947  * Outer subroutine:
948  * Connect from a socket to a specified address.
949  * Both address and port must be specified in argument sin.
950  * If don't have a local address for this socket yet,
951  * then pick one.
952  */
953 int
954 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
955 {
956 	struct sockaddr_in *if_sin;
957 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
958 	int error;
959 
960 	/* Call inner routine to assign local interface address. */
961 	if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
962 		return (error);
963 
964 	if (in_pcblookup_hash(inp->inp_pcbinfo, sin->sin_addr, sin->sin_port,
965 			      inp->inp_laddr.s_addr ?
966 				inp->inp_laddr : if_sin->sin_addr,
967 			      inp->inp_lport, FALSE, NULL) != NULL) {
968 		return (EADDRINUSE);
969 	}
970 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
971 		if (inp->inp_lport == 0) {
972 			error = in_pcbbind(inp, NULL, td);
973 			if (error)
974 				return (error);
975 		}
976 		inp->inp_laddr = if_sin->sin_addr;
977 	}
978 	inp->inp_faddr = sin->sin_addr;
979 	inp->inp_fport = sin->sin_port;
980 	in_pcbinsconnhash(inp);
981 	return (0);
982 }
983 
984 void
985 in_pcbdisconnect(struct inpcb *inp)
986 {
987 
988 	inp->inp_faddr.s_addr = INADDR_ANY;
989 	inp->inp_fport = 0;
990 	in_pcbremconnhash(inp);
991 }
992 
993 void
994 in_pcbdetach(struct inpcb *inp)
995 {
996 	struct socket *so = inp->inp_socket;
997 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
998 
999 #ifdef IPSEC
1000 	ipsec4_delete_pcbpolicy(inp);
1001 #endif /*IPSEC*/
1002 	inp->inp_gencnt = ++ipi->ipi_gencnt;
1003 	KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
1004 	in_pcbremlists(inp);
1005 	so->so_pcb = NULL;
1006 	sofree(so);			/* remove pcb ref */
1007 	if (inp->inp_options)
1008 		m_free(inp->inp_options);
1009 	if (inp->inp_route.ro_rt)
1010 		rtfree(inp->inp_route.ro_rt);
1011 	ip_freemoptions(inp->inp_moptions);
1012 	inp->inp_vflag = 0;
1013 	kfree(inp, M_PCB);
1014 }
1015 
1016 /*
1017  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
1018  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
1019  * in struct pr_usrreqs, so that protocols can just reference then directly
1020  * without the need for a wrapper function.  The socket must have a valid
1021  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
1022  * except through a kernel programming error, so it is acceptable to panic
1023  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
1024  * because there actually /is/ a programming error somewhere... XXX)
1025  */
1026 int
1027 in_setsockaddr(struct socket *so, struct sockaddr **nam)
1028 {
1029 	struct inpcb *inp;
1030 	struct sockaddr_in *sin;
1031 
1032 	/*
1033 	 * Do the malloc first in case it blocks.
1034 	 */
1035 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1036 	sin->sin_family = AF_INET;
1037 	sin->sin_len = sizeof *sin;
1038 
1039 	crit_enter();
1040 	inp = so->so_pcb;
1041 	if (!inp) {
1042 		crit_exit();
1043 		kfree(sin, M_SONAME);
1044 		return (ECONNRESET);
1045 	}
1046 	sin->sin_port = inp->inp_lport;
1047 	sin->sin_addr = inp->inp_laddr;
1048 	crit_exit();
1049 
1050 	*nam = (struct sockaddr *)sin;
1051 	return (0);
1052 }
1053 
1054 void
1055 in_setsockaddr_dispatch(netmsg_t msg)
1056 {
1057 	int error;
1058 
1059 	error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1060 	lwkt_replymsg(&msg->lmsg, error);
1061 }
1062 
1063 int
1064 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1065 {
1066 	struct inpcb *inp;
1067 	struct sockaddr_in *sin;
1068 
1069 	/*
1070 	 * Do the malloc first in case it blocks.
1071 	 */
1072 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1073 	sin->sin_family = AF_INET;
1074 	sin->sin_len = sizeof *sin;
1075 
1076 	crit_enter();
1077 	inp = so->so_pcb;
1078 	if (!inp) {
1079 		crit_exit();
1080 		kfree(sin, M_SONAME);
1081 		return (ECONNRESET);
1082 	}
1083 	sin->sin_port = inp->inp_fport;
1084 	sin->sin_addr = inp->inp_faddr;
1085 	crit_exit();
1086 
1087 	*nam = (struct sockaddr *)sin;
1088 	return (0);
1089 }
1090 
1091 void
1092 in_setpeeraddr_dispatch(netmsg_t msg)
1093 {
1094 	int error;
1095 
1096 	error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1097 	lwkt_replymsg(&msg->lmsg, error);
1098 }
1099 
1100 void
1101 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
1102 		void (*notify)(struct inpcb *, int))
1103 {
1104 	struct inpcb *inp, *ninp;
1105 
1106 	/*
1107 	 * note: if INP_PLACEMARKER is set we must ignore the rest of
1108 	 * the structure and skip it.
1109 	 */
1110 	crit_enter();
1111 	LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
1112 		if (inp->inp_flags & INP_PLACEMARKER)
1113 			continue;
1114 #ifdef INET6
1115 		if (!(inp->inp_vflag & INP_IPV4))
1116 			continue;
1117 #endif
1118 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1119 		    inp->inp_socket == NULL)
1120 			continue;
1121 		(*notify)(inp, err);		/* can remove inp from list! */
1122 	}
1123 	crit_exit();
1124 }
1125 
1126 void
1127 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
1128 {
1129 	struct inpcb *inp;
1130 	struct ip_moptions *imo;
1131 	int i, gap;
1132 
1133 	for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
1134 		if (inp->inp_flags & INP_PLACEMARKER)
1135 			continue;
1136 		imo = inp->inp_moptions;
1137 		if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
1138 			/*
1139 			 * Unselect the outgoing interface if it is being
1140 			 * detached.
1141 			 */
1142 			if (imo->imo_multicast_ifp == ifp)
1143 				imo->imo_multicast_ifp = NULL;
1144 
1145 			/*
1146 			 * Drop multicast group membership if we joined
1147 			 * through the interface being detached.
1148 			 */
1149 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1150 			    i++) {
1151 				if (imo->imo_membership[i]->inm_ifp == ifp) {
1152 					in_delmulti(imo->imo_membership[i]);
1153 					gap++;
1154 				} else if (gap != 0)
1155 					imo->imo_membership[i - gap] =
1156 					    imo->imo_membership[i];
1157 			}
1158 			imo->imo_num_memberships -= gap;
1159 		}
1160 	}
1161 }
1162 
1163 /*
1164  * Check for alternatives when higher level complains
1165  * about service problems.  For now, invalidate cached
1166  * routing information.  If the route was created dynamically
1167  * (by a redirect), time to try a default gateway again.
1168  */
1169 void
1170 in_losing(struct inpcb *inp)
1171 {
1172 	struct rtentry *rt;
1173 	struct rt_addrinfo rtinfo;
1174 
1175 	if ((rt = inp->inp_route.ro_rt)) {
1176 		bzero(&rtinfo, sizeof(struct rt_addrinfo));
1177 		rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1178 		rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1179 		rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1180 		rtinfo.rti_flags = rt->rt_flags;
1181 		rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1182 		if (rt->rt_flags & RTF_DYNAMIC) {
1183 			rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1184 			    rt_mask(rt), rt->rt_flags, NULL);
1185 		}
1186 		inp->inp_route.ro_rt = NULL;
1187 		rtfree(rt);
1188 		/*
1189 		 * A new route can be allocated
1190 		 * the next time output is attempted.
1191 		 */
1192 	}
1193 }
1194 
1195 /*
1196  * After a routing change, flush old routing
1197  * and allocate a (hopefully) better one.
1198  */
1199 void
1200 in_rtchange(struct inpcb *inp, int err)
1201 {
1202 	if (inp->inp_route.ro_rt) {
1203 		rtfree(inp->inp_route.ro_rt);
1204 		inp->inp_route.ro_rt = NULL;
1205 		/*
1206 		 * A new route can be allocated the next time
1207 		 * output is attempted.
1208 		 */
1209 	}
1210 }
1211 
1212 /*
1213  * Lookup a PCB based on the local address and port.
1214  */
1215 struct inpcb *
1216 in_pcblookup_local(struct inpcbportinfo *portinfo, struct in_addr laddr,
1217 		   u_int lport_arg, int wild_okay, struct ucred *cred)
1218 {
1219 	struct inpcb *inp;
1220 	int matchwild = 3, wildcard;
1221 	u_short lport = lport_arg;
1222 	struct inpcbporthead *porthash;
1223 	struct inpcbport *phd;
1224 	struct inpcb *match = NULL;
1225 
1226 	/*
1227 	 * If the porthashbase is shared across several cpus, it must
1228 	 * have been locked.
1229 	 */
1230 	ASSERT_PORT_TOKEN_HELD(portinfo);
1231 
1232 	/*
1233 	 * Best fit PCB lookup.
1234 	 *
1235 	 * First see if this local port is in use by looking on the
1236 	 * port hash list.
1237 	 */
1238 	porthash = &portinfo->porthashbase[
1239 			INP_PCBPORTHASH(lport, portinfo->porthashmask)];
1240 	LIST_FOREACH(phd, porthash, phd_hash) {
1241 		if (phd->phd_port == lport)
1242 			break;
1243 	}
1244 	if (phd != NULL) {
1245 		/*
1246 		 * Port is in use by one or more PCBs. Look for best
1247 		 * fit.
1248 		 */
1249 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1250 			wildcard = 0;
1251 #ifdef INET6
1252 			if ((inp->inp_vflag & INP_IPV4) == 0)
1253 				continue;
1254 #endif
1255 			if (inp->inp_faddr.s_addr != INADDR_ANY)
1256 				wildcard++;
1257 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
1258 				if (laddr.s_addr == INADDR_ANY)
1259 					wildcard++;
1260 				else if (inp->inp_laddr.s_addr != laddr.s_addr)
1261 					continue;
1262 			} else {
1263 				if (laddr.s_addr != INADDR_ANY)
1264 					wildcard++;
1265 			}
1266 			if (wildcard && !wild_okay)
1267 				continue;
1268 			if (wildcard < matchwild &&
1269 			    (cred == NULL ||
1270 			     cred->cr_prison ==
1271 					inp->inp_socket->so_cred->cr_prison)) {
1272 				match = inp;
1273 				matchwild = wildcard;
1274 				if (matchwild == 0) {
1275 					break;
1276 				}
1277 			}
1278 		}
1279 	}
1280 	return (match);
1281 }
1282 
1283 struct inpcb *
1284 in_pcblocalgroup_last(const struct inpcbinfo *pcbinfo,
1285     const struct inpcb *inp)
1286 {
1287 	const struct inp_localgrphead *hdr;
1288 	const struct inp_localgroup *grp;
1289 	int i;
1290 
1291 	if (pcbinfo->localgrphashbase == NULL)
1292 		return NULL;
1293 
1294 	hdr = &pcbinfo->localgrphashbase[
1295 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1296 
1297 	LIST_FOREACH(grp, hdr, il_list) {
1298 		if (grp->il_vflag == inp->inp_vflag &&
1299 		    grp->il_lport == inp->inp_lport &&
1300 		    memcmp(&grp->il_dependladdr,
1301 			&inp->inp_inc.inc_ie.ie_dependladdr,
1302 			sizeof(grp->il_dependladdr)) == 0) {
1303 			break;
1304 		}
1305 	}
1306 	if (grp == NULL || grp->il_inpcnt == 1)
1307 		return NULL;
1308 
1309 	KASSERT(grp->il_inpcnt >= 2,
1310 	    ("invalid localgroup inp count %d", grp->il_inpcnt));
1311 	for (i = 0; i < grp->il_inpcnt; ++i) {
1312 		if (grp->il_inp[i] == inp) {
1313 			int last = grp->il_inpcnt - 1;
1314 
1315 			if (i == last)
1316 				last = grp->il_inpcnt - 2;
1317 			return grp->il_inp[last];
1318 		}
1319 	}
1320 	return NULL;
1321 }
1322 
1323 static struct inpcb *
1324 inp_localgroup_lookup(const struct inpcbinfo *pcbinfo,
1325     struct in_addr laddr, uint16_t lport, uint32_t pkt_hash)
1326 {
1327 	struct inpcb *local_wild = NULL;
1328 	const struct inp_localgrphead *hdr;
1329 	const struct inp_localgroup *grp;
1330 
1331 	hdr = &pcbinfo->localgrphashbase[
1332 	    INP_PCBLOCALGRPHASH(lport, pcbinfo->localgrphashmask)];
1333 #ifdef INP_LOCALGROUP_HASHTHR
1334 	pkt_hash >>= ncpus2_shift;
1335 #endif
1336 
1337 	/*
1338 	 * Order of socket selection:
1339 	 * 1. non-wild.
1340 	 * 2. wild.
1341 	 *
1342 	 * NOTE:
1343 	 * - Local group does not contain jailed sockets
1344 	 * - Local group does not contain IPv4 mapped INET6 wild sockets
1345 	 */
1346 	LIST_FOREACH(grp, hdr, il_list) {
1347 #ifdef INET6
1348 		if (!(grp->il_vflag & INP_IPV4))
1349 			continue;
1350 #endif
1351 		if (grp->il_lport == lport) {
1352 			int idx;
1353 
1354 #ifdef INP_LOCALGROUP_HASHTHR
1355 			idx = pkt_hash / grp->il_factor;
1356 			KASSERT(idx < grp->il_inpcnt && idx >= 0,
1357 			    ("invalid hash %04x, cnt %d or fact %d",
1358 			     pkt_hash, grp->il_inpcnt, grp->il_factor));
1359 #else
1360 			/*
1361 			 * Modulo-N is used here, which greatly reduces
1362 			 * completion queue token contention, thus more
1363 			 * cpu time is saved.
1364 			 */
1365 			idx = pkt_hash % grp->il_inpcnt;
1366 #endif
1367 
1368 			if (grp->il_laddr.s_addr == laddr.s_addr)
1369 				return grp->il_inp[idx];
1370 			else if (grp->il_laddr.s_addr == INADDR_ANY)
1371 				local_wild = grp->il_inp[idx];
1372 		}
1373 	}
1374 	if (local_wild != NULL)
1375 		return local_wild;
1376 	return NULL;
1377 }
1378 
1379 /*
1380  * Lookup PCB in hash list.
1381  */
1382 struct inpcb *
1383 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1384     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1385     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1386 {
1387 	struct inpcbhead *head;
1388 	struct inpcb *inp, *jinp=NULL;
1389 	u_short fport = fport_arg, lport = lport_arg;
1390 
1391 	/*
1392 	 * First look for an exact match.
1393 	 */
1394 	head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1395 	    laddr.s_addr, lport, pcbinfo->hashmask)];
1396 	LIST_FOREACH(inp, head, inp_hash) {
1397 #ifdef INET6
1398 		if (!(inp->inp_vflag & INP_IPV4))
1399 			continue;
1400 #endif
1401 		if (in_hosteq(inp->inp_faddr, faddr) &&
1402 		    in_hosteq(inp->inp_laddr, laddr) &&
1403 		    inp->inp_fport == fport && inp->inp_lport == lport) {
1404 			/* found */
1405 			if (inp->inp_socket == NULL ||
1406 			    inp->inp_socket->so_cred->cr_prison == NULL) {
1407 				return (inp);
1408 			} else {
1409 				if  (jinp == NULL)
1410 					jinp = inp;
1411 			}
1412 		}
1413 	}
1414 	if (jinp != NULL)
1415 		return (jinp);
1416 	if (wildcard) {
1417 		struct inpcb *local_wild = NULL;
1418 		struct inpcb *jinp_wild = NULL;
1419 #ifdef INET6
1420 		struct inpcb *local_wild_mapped = NULL;
1421 #endif
1422 		struct inpcontainer *ic;
1423 		struct inpcontainerhead *chead;
1424 		struct sockaddr_in jsin;
1425 		struct ucred *cred;
1426 
1427 		/*
1428 		 * Check local group first
1429 		 */
1430 		if (pcbinfo->localgrphashbase != NULL &&
1431 		    m != NULL && (m->m_flags & M_HASH) &&
1432 		    !(ifp && ifp->if_type == IFT_FAITH)) {
1433 			inp = inp_localgroup_lookup(pcbinfo,
1434 			    laddr, lport, m->m_pkthdr.hash);
1435 			if (inp != NULL)
1436 				return inp;
1437 		}
1438 
1439 		/*
1440 		 * Order of socket selection:
1441 		 * 1. non-jailed, non-wild.
1442 		 * 2. non-jailed, wild.
1443 		 * 3. jailed, non-wild.
1444 		 * 4. jailed, wild.
1445 		 */
1446 		jsin.sin_family = AF_INET;
1447 		chead = &pcbinfo->wildcardhashbase[
1448 		    INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1449 		LIST_FOREACH(ic, chead, ic_list) {
1450 			inp = ic->ic_inp;
1451 			jsin.sin_addr.s_addr = laddr.s_addr;
1452 #ifdef INET6
1453 			if (!(inp->inp_vflag & INP_IPV4))
1454 				continue;
1455 #endif
1456 			if (inp->inp_socket != NULL)
1457 				cred = inp->inp_socket->so_cred;
1458 			else
1459 				cred = NULL;
1460 			if (cred != NULL && jailed(cred)) {
1461 				if (jinp != NULL)
1462 					continue;
1463 				else
1464 					if (!jailed_ip(cred->cr_prison,
1465 					    (struct sockaddr *)&jsin))
1466 						continue;
1467 			}
1468 			if (inp->inp_lport == lport) {
1469 				if (ifp && ifp->if_type == IFT_FAITH &&
1470 				    !(inp->inp_flags & INP_FAITH))
1471 					continue;
1472 				if (inp->inp_laddr.s_addr == laddr.s_addr) {
1473 					if (cred != NULL && jailed(cred))
1474 						jinp = inp;
1475 					else
1476 						return (inp);
1477 				}
1478 				if (inp->inp_laddr.s_addr == INADDR_ANY) {
1479 #ifdef INET6
1480 					if (INP_CHECK_SOCKAF(inp->inp_socket,
1481 							     AF_INET6))
1482 						local_wild_mapped = inp;
1483 					else
1484 #endif
1485 						if (cred != NULL &&
1486 						    jailed(cred))
1487 							jinp_wild = inp;
1488 						else
1489 							local_wild = inp;
1490 				}
1491 			}
1492 		}
1493 		if (local_wild != NULL)
1494 			return (local_wild);
1495 #ifdef INET6
1496 		if (local_wild_mapped != NULL)
1497 			return (local_wild_mapped);
1498 #endif
1499 		if (jinp != NULL)
1500 			return (jinp);
1501 		return (jinp_wild);
1502 	}
1503 
1504 	/*
1505 	 * Not found.
1506 	 */
1507 	return (NULL);
1508 }
1509 
1510 struct inpcb *
1511 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1512     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1513     boolean_t wildcard, struct ifnet *ifp)
1514 {
1515 	return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1516 	    laddr, lport_arg, wildcard, ifp, NULL);
1517 }
1518 
1519 /*
1520  * Insert PCB into connection hash table.
1521  */
1522 void
1523 in_pcbinsconnhash(struct inpcb *inp)
1524 {
1525 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1526 	struct inpcbhead *bucket;
1527 	u_int32_t hashkey_faddr, hashkey_laddr;
1528 
1529 #ifdef INET6
1530 	if (inp->inp_vflag & INP_IPV6) {
1531 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1532 		hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1533 	} else {
1534 #endif
1535 		hashkey_faddr = inp->inp_faddr.s_addr;
1536 		hashkey_laddr = inp->inp_laddr.s_addr;
1537 #ifdef INET6
1538 	}
1539 #endif
1540 
1541 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1542 		("already on wildcardhash"));
1543 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1544 		("already on connhash"));
1545 	inp->inp_flags |= INP_CONNECTED;
1546 
1547 	/*
1548 	 * Insert into the connection hash table.
1549 	 */
1550 	bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1551 	    inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1552 	LIST_INSERT_HEAD(bucket, inp, inp_hash);
1553 }
1554 
1555 /*
1556  * Remove PCB from connection hash table.
1557  */
1558 void
1559 in_pcbremconnhash(struct inpcb *inp)
1560 {
1561 	KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1562 	LIST_REMOVE(inp, inp_hash);
1563 	inp->inp_flags &= ~INP_CONNECTED;
1564 }
1565 
1566 /*
1567  * Insert PCB into port hash table.
1568  */
1569 void
1570 in_pcbinsporthash(struct inpcbportinfo *portinfo, struct inpcb *inp)
1571 {
1572 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1573 	struct inpcbporthead *pcbporthash;
1574 	struct inpcbport *phd;
1575 
1576 	/*
1577 	 * If the porthashbase is shared across several cpus, it must
1578 	 * have been locked.
1579 	 */
1580 	ASSERT_PORT_TOKEN_HELD(portinfo);
1581 
1582 	/*
1583 	 * Insert into the port hash table.
1584 	 */
1585 	pcbporthash = &portinfo->porthashbase[
1586 	    INP_PCBPORTHASH(inp->inp_lport, portinfo->porthashmask)];
1587 
1588 	/* Go through port list and look for a head for this lport. */
1589 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1590 		if (phd->phd_port == inp->inp_lport)
1591 			break;
1592 	}
1593 
1594 	/* If none exists, use saved one and tack it on. */
1595 	if (phd == NULL) {
1596 		KKASSERT(pcbinfo->portsave != NULL);
1597 		phd = pcbinfo->portsave;
1598 		pcbinfo->portsave = NULL;
1599 		phd->phd_port = inp->inp_lport;
1600 		LIST_INIT(&phd->phd_pcblist);
1601 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1602 	}
1603 
1604 	inp->inp_portinfo = portinfo;
1605 	inp->inp_phd = phd;
1606 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1607 
1608 	/*
1609 	 * Malloc one inpcbport for later use.  It is safe to use
1610 	 * "wait" malloc here (port token would be released, if
1611 	 * malloc ever blocked), since all changes to the porthash
1612 	 * are done.
1613 	 */
1614 	if (pcbinfo->portsave == NULL) {
1615 		pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1616 					    M_PCB, M_INTWAIT | M_ZERO);
1617 	}
1618 }
1619 
1620 void
1621 in_pcbinsporthash_lport(struct inpcb *inp)
1622 {
1623 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1624 	struct inpcbportinfo *portinfo;
1625 	u_short lport_ho;
1626 
1627 	/* Locate the proper portinfo based on lport */
1628 	lport_ho = ntohs(inp->inp_lport);
1629 	portinfo = &pcbinfo->portinfo[lport_ho & pcbinfo->portinfo_mask];
1630 	KKASSERT((lport_ho & pcbinfo->portinfo_mask) == portinfo->offset);
1631 
1632 	GET_PORT_TOKEN(portinfo);
1633 	in_pcbinsporthash(portinfo, inp);
1634 	REL_PORT_TOKEN(portinfo);
1635 }
1636 
1637 static struct inp_localgroup *
1638 inp_localgroup_alloc(u_char vflag,
1639     uint16_t port, const union in_dependaddr *addr, int size)
1640 {
1641 	struct inp_localgroup *grp;
1642 
1643 	grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
1644 	    M_TEMP, M_INTWAIT | M_ZERO);
1645 	grp->il_vflag = vflag;
1646 	grp->il_lport = port;
1647 	grp->il_dependladdr = *addr;
1648 	grp->il_inpsiz = size;
1649 
1650 	return grp;
1651 }
1652 
1653 static void
1654 inp_localgroup_free(struct inp_localgroup *grp)
1655 {
1656 	kfree(grp, M_TEMP);
1657 }
1658 
1659 static void
1660 inp_localgroup_destroy(struct inp_localgroup *grp)
1661 {
1662 	LIST_REMOVE(grp, il_list);
1663 	inp_localgroup_free(grp);
1664 }
1665 
1666 static void
1667 inp_localgroup_copy(struct inp_localgroup *grp,
1668     const struct inp_localgroup *old_grp)
1669 {
1670 	int i;
1671 
1672 	KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
1673 	    ("invalid new local group size %d and old local group count %d",
1674 	     grp->il_inpsiz, old_grp->il_inpcnt));
1675 	for (i = 0; i < old_grp->il_inpcnt; ++i)
1676 		grp->il_inp[i] = old_grp->il_inp[i];
1677 	grp->il_inpcnt = old_grp->il_inpcnt;
1678 	grp->il_factor = old_grp->il_factor;
1679 }
1680 
1681 static void
1682 inp_localgroup_factor(struct inp_localgroup *grp)
1683 {
1684 	grp->il_factor =
1685 	    ((uint32_t)(0xffff >> ncpus2_shift) / grp->il_inpcnt) + 1;
1686 	KASSERT(grp->il_factor != 0, ("invalid local group factor, "
1687 	    "ncpus2_shift %d, inpcnt %d", ncpus2_shift, grp->il_inpcnt));
1688 }
1689 
1690 static void
1691 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1692 {
1693 	struct inp_localgrphead *hdr;
1694 	struct inp_localgroup *grp, *grp_alloc = NULL;
1695 	struct ucred *cred;
1696 
1697 	if (pcbinfo->localgrphashbase == NULL)
1698 		return;
1699 
1700 	/*
1701 	 * XXX don't allow jailed socket to join local group
1702 	 */
1703 	if (inp->inp_socket != NULL)
1704 		cred = inp->inp_socket->so_cred;
1705 	else
1706 		cred = NULL;
1707 	if (cred != NULL && jailed(cred))
1708 		return;
1709 
1710 #ifdef INET6
1711 	/*
1712 	 * XXX don't allow IPv4 mapped INET6 wild socket
1713 	 */
1714 	if ((inp->inp_vflag & INP_IPV4) &&
1715 	    inp->inp_laddr.s_addr == INADDR_ANY &&
1716 	    INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6))
1717 		return;
1718 #endif
1719 
1720 	hdr = &pcbinfo->localgrphashbase[
1721 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1722 
1723 again:
1724 	LIST_FOREACH(grp, hdr, il_list) {
1725 		if (grp->il_vflag == inp->inp_vflag &&
1726 		    grp->il_lport == inp->inp_lport &&
1727 		    memcmp(&grp->il_dependladdr,
1728 		        &inp->inp_inc.inc_ie.ie_dependladdr,
1729 		        sizeof(grp->il_dependladdr)) == 0) {
1730 			break;
1731 		}
1732 	}
1733 	if (grp == NULL) {
1734 		/*
1735 		 * Create a new local group
1736 		 */
1737 		if (grp_alloc == NULL) {
1738 			grp_alloc = inp_localgroup_alloc(inp->inp_vflag,
1739 			    inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
1740 			    INP_LOCALGROUP_SIZMIN);
1741 			/*
1742 			 * Local group allocation could block and the
1743 			 * local group w/ the same property might have
1744 			 * been added by others when we were blocked;
1745 			 * check again.
1746 			 */
1747 			goto again;
1748 		} else {
1749 			/* Local group has been allocated; link it */
1750 			grp = grp_alloc;
1751 			grp_alloc = NULL;
1752 			LIST_INSERT_HEAD(hdr, grp, il_list);
1753 		}
1754 	} else if (grp->il_inpcnt == grp->il_inpsiz) {
1755 		if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
1756 			static int limit_logged = 0;
1757 
1758 			if (!limit_logged) {
1759 				limit_logged = 1;
1760 				kprintf("local group port %d, "
1761 				    "limit reached\n", ntohs(grp->il_lport));
1762 			}
1763 			if (grp_alloc != NULL) {
1764 				/*
1765 				 * This would happen if the local group
1766 				 * w/ the same property was expanded when
1767 				 * our local group allocation blocked.
1768 				 */
1769 				inp_localgroup_free(grp_alloc);
1770 			}
1771 			return;
1772 		}
1773 
1774 		/*
1775 		 * Expand this local group
1776 		 */
1777 		if (grp_alloc == NULL ||
1778 		    grp->il_inpcnt >= grp_alloc->il_inpsiz) {
1779 			if (grp_alloc != NULL)
1780 				inp_localgroup_free(grp_alloc);
1781 			grp_alloc = inp_localgroup_alloc(grp->il_vflag,
1782 			    grp->il_lport, &grp->il_dependladdr,
1783 			    grp->il_inpsiz * 2);
1784 			/*
1785 			 * Local group allocation could block and the
1786 			 * local group w/ the same property might have
1787 			 * been expanded by others when we were blocked;
1788 			 * check again.
1789 			 */
1790 			goto again;
1791 		}
1792 
1793 		/*
1794 		 * Save the old local group, link the new one, and then
1795 		 * destroy the old local group
1796 		 */
1797 		inp_localgroup_copy(grp_alloc, grp);
1798 		LIST_INSERT_HEAD(hdr, grp_alloc, il_list);
1799 		inp_localgroup_destroy(grp);
1800 
1801 		grp = grp_alloc;
1802 		grp_alloc = NULL;
1803 	} else {
1804 		/*
1805 		 * Found the local group
1806 		 */
1807 		if (grp_alloc != NULL) {
1808 			/*
1809 			 * This would happen if the local group w/ the
1810 			 * same property was added or expanded when our
1811 			 * local group allocation blocked.
1812 			 */
1813 			inp_localgroup_free(grp_alloc);
1814 			grp_alloc = NULL;
1815 		}
1816 	}
1817 
1818 	KASSERT(grp->il_inpcnt < grp->il_inpsiz,
1819 	    ("invalid local group size %d and count %d",
1820 	     grp->il_inpsiz, grp->il_inpcnt));
1821 	grp->il_inp[grp->il_inpcnt] = inp;
1822 	grp->il_inpcnt++;
1823 	inp_localgroup_factor(grp);
1824 }
1825 
1826 void
1827 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1828 {
1829 	struct inpcontainer *ic;
1830 	struct inpcontainerhead *bucket;
1831 
1832 	in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
1833 
1834 	bucket = &pcbinfo->wildcardhashbase[
1835 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1836 
1837 	ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1838 	ic->ic_inp = inp;
1839 	LIST_INSERT_HEAD(bucket, ic, ic_list);
1840 }
1841 
1842 /*
1843  * Insert PCB into wildcard hash table.
1844  */
1845 void
1846 in_pcbinswildcardhash(struct inpcb *inp)
1847 {
1848 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1849 
1850 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1851 		("already on connhash"));
1852 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1853 		("already on wildcardhash"));
1854 	inp->inp_flags |= INP_WILDCARD;
1855 
1856 	in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1857 }
1858 
1859 static void
1860 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1861 {
1862 	struct inp_localgrphead *hdr;
1863 	struct inp_localgroup *grp;
1864 
1865 	if (pcbinfo->localgrphashbase == NULL)
1866 		return;
1867 
1868 	hdr = &pcbinfo->localgrphashbase[
1869 	    INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1870 
1871 	LIST_FOREACH(grp, hdr, il_list) {
1872 		int i;
1873 
1874 		for (i = 0; i < grp->il_inpcnt; ++i) {
1875 			if (grp->il_inp[i] != inp)
1876 				continue;
1877 
1878 			if (grp->il_inpcnt == 1) {
1879 				/* Destroy this local group */
1880 				inp_localgroup_destroy(grp);
1881 			} else {
1882 				/* Pull up inpcbs */
1883 				for (; i + 1 < grp->il_inpcnt; ++i)
1884 					grp->il_inp[i] = grp->il_inp[i + 1];
1885 				grp->il_inpcnt--;
1886 				inp_localgroup_factor(grp);
1887 			}
1888 			return;
1889 		}
1890 	}
1891 }
1892 
1893 void
1894 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1895 {
1896 	struct inpcontainer *ic;
1897 	struct inpcontainerhead *head;
1898 
1899 	in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
1900 
1901 	/* find bucket */
1902 	head = &pcbinfo->wildcardhashbase[
1903 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1904 
1905 	LIST_FOREACH(ic, head, ic_list) {
1906 		if (ic->ic_inp == inp)
1907 			goto found;
1908 	}
1909 	return;			/* not found! */
1910 
1911 found:
1912 	LIST_REMOVE(ic, ic_list);	/* remove container from bucket chain */
1913 	kfree(ic, M_TEMP);		/* deallocate container */
1914 }
1915 
1916 /*
1917  * Remove PCB from wildcard hash table.
1918  */
1919 void
1920 in_pcbremwildcardhash(struct inpcb *inp)
1921 {
1922 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1923 
1924 	KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1925 	in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1926 	inp->inp_flags &= ~INP_WILDCARD;
1927 }
1928 
1929 /*
1930  * Remove PCB from various lists.
1931  */
1932 void
1933 in_pcbremlists(struct inpcb *inp)
1934 {
1935 	if (inp->inp_lport) {
1936 		struct inpcbportinfo *portinfo;
1937 		struct inpcbport *phd;
1938 
1939 		/*
1940 		 * NOTE:
1941 		 * inp->inp_portinfo is _not_ necessary same as
1942 		 * inp->inp_pcbinfo->portinfo.
1943 		 */
1944 		portinfo = inp->inp_portinfo;
1945 		GET_PORT_TOKEN(portinfo);
1946 
1947 		phd = inp->inp_phd;
1948 		LIST_REMOVE(inp, inp_portlist);
1949 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1950 			LIST_REMOVE(phd, phd_hash);
1951 			kfree(phd, M_PCB);
1952 		}
1953 
1954 		REL_PORT_TOKEN(portinfo);
1955 	}
1956 	if (inp->inp_flags & INP_WILDCARD) {
1957 		in_pcbremwildcardhash(inp);
1958 	} else if (inp->inp_flags & INP_CONNECTED) {
1959 		in_pcbremconnhash(inp);
1960 	}
1961 	LIST_REMOVE(inp, inp_list);
1962 	inp->inp_pcbinfo->ipi_count--;
1963 }
1964 
1965 int
1966 prison_xinpcb(struct thread *td, struct inpcb *inp)
1967 {
1968 	struct ucred *cr;
1969 
1970 	if (td->td_proc == NULL)
1971 		return (0);
1972 	cr = td->td_proc->p_ucred;
1973 	if (cr->cr_prison == NULL)
1974 		return (0);
1975 	if (inp->inp_socket && inp->inp_socket->so_cred &&
1976 	    inp->inp_socket->so_cred->cr_prison &&
1977 	    cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1978 		return (0);
1979 	return (1);
1980 }
1981 
1982 int
1983 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1984 {
1985 	struct inpcbinfo *pcbinfo = arg1;
1986 	struct inpcb *inp, *marker;
1987 	struct xinpcb xi;
1988 	int error, i, n;
1989 
1990 	/*
1991 	 * The process of preparing the TCB list is too time-consuming and
1992 	 * resource-intensive to repeat twice on every request.
1993 	 */
1994 	if (req->oldptr == NULL) {
1995 		n = pcbinfo->ipi_count;
1996 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1997 		return 0;
1998 	}
1999 
2000 	if (req->newptr != NULL)
2001 		return EPERM;
2002 
2003 	/*
2004 	 * OK, now we're committed to doing something.  Re-fetch ipi_count
2005 	 * after obtaining the generation count.
2006 	 */
2007 	n = pcbinfo->ipi_count;
2008 
2009 	marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
2010 	marker->inp_flags |= INP_PLACEMARKER;
2011 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
2012 
2013 	i = 0;
2014 	error = 0;
2015 
2016 	while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
2017 		LIST_REMOVE(marker, inp_list);
2018 		LIST_INSERT_AFTER(inp, marker, inp_list);
2019 
2020 		if (inp->inp_flags & INP_PLACEMARKER)
2021 			continue;
2022 		if (prison_xinpcb(req->td, inp))
2023 			continue;
2024 		bzero(&xi, sizeof xi);
2025 		xi.xi_len = sizeof xi;
2026 		bcopy(inp, &xi.xi_inp, sizeof *inp);
2027 		if (inp->inp_socket)
2028 			sotoxsocket(inp->inp_socket, &xi.xi_socket);
2029 		if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
2030 			break;
2031 		++i;
2032 	}
2033 	LIST_REMOVE(marker, inp_list);
2034 	if (error == 0 && i < n) {
2035 		bzero(&xi, sizeof xi);
2036 		xi.xi_len = sizeof xi;
2037 		while (i < n) {
2038 			error = SYSCTL_OUT(req, &xi, sizeof xi);
2039 			++i;
2040 		}
2041 	}
2042 	kfree(marker, M_TEMP);
2043 	return(error);
2044 }
2045 
2046 int
2047 in_pcblist_global_cpu0(SYSCTL_HANDLER_ARGS)
2048 {
2049 	boolean_t migrate = FALSE;
2050 	int origcpu = mycpuid;
2051 	int error;
2052 
2053 	if (origcpu != 0) {
2054 		migrate = TRUE;
2055 		lwkt_migratecpu(0);
2056 	}
2057 
2058 	error = in_pcblist_global(oidp, arg1, arg2, req);
2059 
2060 	if (migrate)
2061 		lwkt_migratecpu(origcpu);
2062 	return error;
2063 }
2064 
2065 int
2066 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
2067 {
2068 	struct inpcbinfo *pcbinfo = arg1;
2069 	struct inpcb *inp;
2070 	struct xinpcb *xi;
2071 	int nxi;
2072 
2073 	*nxi0 = 0;
2074 	*xi0 = NULL;
2075 
2076 	/*
2077 	 * The process of preparing the PCB list is too time-consuming and
2078 	 * resource-intensive to repeat twice on every request.
2079 	 */
2080 	if (req->oldptr == NULL) {
2081 		int n = pcbinfo->ipi_count;
2082 
2083 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
2084 		return 0;
2085 	}
2086 
2087 	if (req->newptr != NULL)
2088 		return EPERM;
2089 
2090 	if (pcbinfo->ipi_count == 0)
2091 		return 0;
2092 
2093 	nxi = 0;
2094 	xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
2095 		     M_WAITOK | M_ZERO | M_NULLOK);
2096 	if (xi == NULL)
2097 		return ENOMEM;
2098 
2099 	LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
2100 		struct xinpcb *xi_ptr = &xi[nxi];
2101 
2102 		if (prison_xinpcb(req->td, inp))
2103 			continue;
2104 
2105 		xi_ptr->xi_len = sizeof(*xi_ptr);
2106 		bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
2107 		if (inp->inp_socket)
2108 			sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
2109 		++nxi;
2110 	}
2111 
2112 	if (nxi == 0) {
2113 		kfree(xi, M_TEMP);
2114 		return 0;
2115 	}
2116 
2117 	*nxi0 = nxi;
2118 	*xi0 = xi;
2119 
2120 	return 0;
2121 }
2122 
2123 void
2124 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
2125 {
2126 	struct sockaddr_in *sin;
2127 
2128 	KASSERT(faddr->sa_family == AF_INET,
2129 	    ("not AF_INET faddr %d", faddr->sa_family));
2130 
2131 	sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
2132 	sin->sin_family = AF_INET;
2133 	sin->sin_len = sizeof(*sin);
2134 	sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
2135 	sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
2136 
2137 	so->so_faddr = (struct sockaddr *)sin;
2138 }
2139 
2140 void
2141 in_pcbportinfo_init(struct inpcbportinfo *portinfo, int hashsize,
2142     boolean_t shared, u_short offset)
2143 {
2144 	memset(portinfo, 0, sizeof(*portinfo));
2145 
2146 	portinfo->offset = offset;
2147 	portinfo->lastport = offset;
2148 	portinfo->lastlow = offset;
2149 	portinfo->lasthi = offset;
2150 
2151 	portinfo->porthashbase = hashinit(hashsize, M_PCB,
2152 	    &portinfo->porthashmask);
2153 
2154 	if (shared) {
2155 		portinfo->porttoken = kmalloc(sizeof(struct lwkt_token),
2156 		    M_PCB, M_WAITOK);
2157 		lwkt_token_init(portinfo->porttoken, "porttoken");
2158 	}
2159 }
2160 
2161 void
2162 in_pcbportrange(u_short *hi0, u_short *lo0, u_short ofs, u_short step)
2163 {
2164 	int hi, lo;
2165 
2166 	if (step == 1)
2167 		return;
2168 
2169 	hi = *hi0;
2170 	lo = *lo0;
2171 
2172 	hi = rounddown2(hi, step);
2173 	hi += ofs;
2174 	if (hi > (int)*hi0)
2175 		hi -= step;
2176 
2177 	lo = roundup2(lo, step);
2178 	lo -= (step - ofs);
2179 	if (lo < (int)*lo0)
2180 		lo += step;
2181 
2182 	*hi0 = hi;
2183 	*lo0 = lo;
2184 }
2185