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