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