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