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