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