inpcb: in_pcblookup_addrport() must have been protected by port token
[dragonfly.git] / sys / netinet / in_pcb.c
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993, 1995
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *      @(#)in_pcb.c    8.4 (Berkeley) 5/24/95
63  * $FreeBSD: src/sys/netinet/in_pcb.c,v 1.59.2.27 2004/01/02 04:06:42 ambrisko Exp $
64  */
65
66 #include "opt_ipsec.h"
67 #include "opt_inet6.h"
68
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/domain.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/proc.h>
78 #include <sys/priv.h>
79 #include <sys/jail.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82
83 #include <sys/thread2.h>
84 #include <sys/socketvar2.h>
85 #include <sys/msgport2.h>
86
87 #include <machine/limits.h>
88
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.h>
92
93 #include <netinet/in.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip_var.h>
97 #ifdef INET6
98 #include <netinet/ip6.h>
99 #include <netinet6/ip6_var.h>
100 #endif /* INET6 */
101
102 #ifdef IPSEC
103 #include <netinet6/ipsec.h>
104 #include <netproto/key/key.h>
105 #include <netproto/ipsec/esp_var.h>
106 #endif
107
108 #ifdef FAST_IPSEC
109 #if defined(IPSEC) || defined(IPSEC_ESP)
110 #error "Bad idea: don't compile with both IPSEC and FAST_IPSEC!"
111 #endif
112
113 #include <netproto/ipsec/ipsec.h>
114 #include <netproto/ipsec/key.h>
115 #define IPSEC
116 #endif /* FAST_IPSEC */
117
118 #define INP_LOCALGROUP_SIZMIN   8
119 #define INP_LOCALGROUP_SIZMAX   256
120
121 struct in_addr zeroin_addr;
122
123 /*
124  * These configure the range of local port addresses assigned to
125  * "unspecified" outgoing connections/packets/whatever.
126  */
127 int ipport_lowfirstauto = IPPORT_RESERVED - 1;  /* 1023 */
128 int ipport_lowlastauto = IPPORT_RESERVEDSTART;  /* 600 */
129
130 int ipport_firstauto = IPPORT_RESERVED;         /* 1024 */
131 int ipport_lastauto = IPPORT_USERRESERVED;      /* 5000 */
132
133 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;    /* 49152 */
134 int ipport_hilastauto = IPPORT_HILASTAUTO;      /* 65535 */
135
136 #define RANGECHK(var, min, max) \
137         if ((var) < (min)) { (var) = (min); } \
138         else if ((var) > (max)) { (var) = (max); }
139
140 int udpencap_enable = 1;        /* enabled by default */
141 int udpencap_port = 4500;       /* triggers decapsulation */
142
143 static int
144 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
145 {
146         int error;
147
148         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
149         if (!error) {
150                 RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
151                 RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
152
153                 RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
154                 RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
155
156                 RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
157                 RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
158         }
159         return (error);
160 }
161
162 #undef RANGECHK
163
164 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
165
166 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
167            &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
168 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
169            &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
170 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
171            &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
172 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
173            &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
174 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
175            &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
176 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
177            &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
178
179 /*
180  * in_pcb.c: manage the Protocol Control Blocks.
181  *
182  * NOTE: It is assumed that most of these functions will be called from
183  * a critical section.  XXX - There are, unfortunately, a few exceptions
184  * to this rule that should be fixed.
185  *
186  * NOTE: The caller should initialize the cpu field to the cpu running the
187  * protocol stack associated with this inpcbinfo.
188  */
189
190 void
191 in_pcbinfo_init(struct inpcbinfo *pcbinfo)
192 {
193         LIST_INIT(&pcbinfo->pcblisthead);
194         pcbinfo->cpu = -1;
195         pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave), M_PCB,
196                                     M_WAITOK | M_ZERO);
197 }
198
199 struct baddynamicports baddynamicports;
200
201 /*
202  * Check if the specified port is invalid for dynamic allocation.
203  */
204 int
205 in_baddynamic(u_int16_t port, u_int16_t proto)
206 {
207         switch (proto) {
208         case IPPROTO_TCP:
209                 return (DP_ISSET(baddynamicports.tcp, port));
210         case IPPROTO_UDP:
211 #ifdef IPSEC
212                 /* Cannot preset this as it is a sysctl */
213                 if (port == udpencap_port)
214                         return (1);
215 #endif
216                 return (DP_ISSET(baddynamicports.udp, port));
217         default:
218                 return (0);
219         }
220 }
221
222
223 /*
224  * Allocate a PCB and associate it with the socket.
225  */
226 int
227 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
228 {
229         struct inpcb *inp;
230 #ifdef IPSEC
231         int error;
232 #endif
233
234         inp = kmalloc(pcbinfo->ipi_size, M_PCB, M_WAITOK|M_ZERO|M_NULLOK);
235         if (inp == NULL)
236                 return (ENOMEM);
237         inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
238         inp->inp_pcbinfo = inp->inp_cpcbinfo = pcbinfo;
239         inp->inp_socket = so;
240 #ifdef IPSEC
241         error = ipsec_init_policy(so, &inp->inp_sp);
242         if (error != 0) {
243                 kfree(inp, M_PCB);
244                 return (error);
245         }
246 #endif
247 #ifdef INET6
248         if (INP_SOCKAF(so) == AF_INET6 && ip6_v6only)
249                 inp->inp_flags |= IN6P_IPV6_V6ONLY;
250         if (ip6_auto_flowlabel)
251                 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
252 #endif
253         soreference(so);
254         so->so_pcb = inp;
255         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
256         pcbinfo->ipi_count++;
257         return (0);
258 }
259
260 /*
261  * Unlink a pcb with the intention of moving it to another cpu with a
262  * different pcbinfo.  While unlinked nothing should attempt to dereference
263  * inp_pcbinfo, NULL it out so we assert if it does.
264  */
265 void
266 in_pcbunlink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
267 {
268         KASSERT(inp->inp_pcbinfo == pcbinfo, ("pcbinfo mismatch"));
269         KASSERT(inp->inp_cpcbinfo == pcbinfo, ("cpcbinfo mismatch"));
270         KASSERT((inp->inp_flags & (INP_WILDCARD | INP_CONNECTED)) == 0,
271             ("already linked"));
272
273         LIST_REMOVE(inp, inp_list);
274         pcbinfo->ipi_count--;
275         inp->inp_pcbinfo = NULL;
276         inp->inp_cpcbinfo = NULL;
277 }
278
279 /*
280  * Relink a pcb into a new pcbinfo.
281  */
282 void
283 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
284 {
285         KASSERT(inp->inp_pcbinfo == NULL, ("has pcbinfo"));
286         KASSERT(inp->inp_cpcbinfo == NULL, ("has cpcbinfo"));
287         KASSERT((inp->inp_flags & (INP_WILDCARD | INP_CONNECTED)) == 0,
288             ("already linked"));
289
290         inp->inp_cpcbinfo = pcbinfo;
291         inp->inp_pcbinfo = pcbinfo;
292         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
293         pcbinfo->ipi_count++;
294 }
295
296 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
502         if (in_pcbinsporthash(inp) != 0) {
503                 inp->inp_laddr.s_addr = INADDR_ANY;
504                 inp->inp_lport = 0;
505                 error = EAGAIN;
506                 goto done;
507         }
508         error = 0;
509 done:
510         if (pcbinfo->porttoken)
511                 lwkt_reltoken(pcbinfo->porttoken);
512         return error;
513 }
514
515 static struct inpcb *
516 in_pcblookup_addrport(struct inpcbinfo *pcbinfo, struct in_addr laddr,
517     u_short lport, struct in_addr faddr, u_short fport, struct ucred *cred)
518 {
519         struct inpcb *inp;
520         struct inpcbporthead *porthash;
521         struct inpcbport *phd;
522         struct inpcb *match = NULL;
523
524         /*
525          * If the porthashbase is shared across several cpus, it must
526          * have been locked.
527          */
528         if (pcbinfo->porttoken)
529                 ASSERT_LWKT_TOKEN_HELD(pcbinfo->porttoken);
530
531         /*
532          * Best fit PCB lookup.
533          *
534          * First see if this local port is in use by looking on the
535          * port hash list.
536          */
537         porthash = &pcbinfo->porthashbase[
538                         INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
539         LIST_FOREACH(phd, porthash, phd_hash) {
540                 if (phd->phd_port == lport)
541                         break;
542         }
543         if (phd != NULL) {
544                 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
545 #ifdef INET6
546                         if ((inp->inp_vflag & INP_IPV4) == 0)
547                                 continue;
548 #endif
549                         if (inp->inp_laddr.s_addr != INADDR_ANY &&
550                             inp->inp_laddr.s_addr != laddr.s_addr)
551                                 continue;
552
553                         if (inp->inp_faddr.s_addr != INADDR_ANY &&
554                             inp->inp_faddr.s_addr != faddr.s_addr)
555                                 continue;
556
557                         if (inp->inp_fport != 0 && inp->inp_fport != fport)
558                                 continue;
559
560                         if (cred == NULL ||
561                             cred->cr_prison ==
562                             inp->inp_socket->so_cred->cr_prison) {
563                                 match = inp;
564                                 break;
565                         }
566                 }
567         }
568         return (match);
569 }
570
571 int
572 in_pcbconn_bind(struct inpcb *inp, const struct sockaddr *nam,
573     struct thread *td)
574 {
575         struct proc *p = td->td_proc;
576         unsigned short *lastport;
577         const struct sockaddr_in *sin = (const struct sockaddr_in *)nam;
578         struct sockaddr_in jsin;
579         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
580         struct ucred *cred = NULL;
581         u_short lport = 0;
582         ushort first, last;
583         int count, error, dup = 0;
584
585         if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
586                 return (EADDRNOTAVAIL);
587
588         KKASSERT(inp->inp_laddr.s_addr != INADDR_ANY);
589         if (inp->inp_lport != 0)
590                 return (EINVAL);        /* already bound */
591
592         KKASSERT(p);
593         cred = p->p_ucred;
594
595         jsin.sin_family = AF_INET;
596         jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
597         if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
598                 inp->inp_laddr.s_addr = INADDR_ANY;
599                 return (EINVAL);
600         }
601         inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
602
603         inp->inp_flags |= INP_ANONPORT;
604
605         if (inp->inp_flags & INP_HIGHPORT) {
606                 first = ipport_hifirstauto;     /* sysctl */
607                 last  = ipport_hilastauto;
608                 lastport = &pcbinfo->lasthi;
609         } else if (inp->inp_flags & INP_LOWPORT) {
610                 if (cred &&
611                     (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
612                         inp->inp_laddr.s_addr = INADDR_ANY;
613                         return (error);
614                 }
615                 first = ipport_lowfirstauto;    /* 1023 */
616                 last  = ipport_lowlastauto;     /* 600 */
617                 lastport = &pcbinfo->lastlow;
618         } else {
619                 first = ipport_firstauto;       /* sysctl */
620                 last  = ipport_lastauto;
621                 lastport = &pcbinfo->lastport;
622         }
623
624         /*
625          * This has to be atomic.  If the porthash is shared across multiple
626          * protocol threads (aka tcp) then the token will be non-NULL.
627          */
628         if (pcbinfo->porttoken)
629                 lwkt_gettoken(pcbinfo->porttoken);
630
631 again:
632         /*
633          * Simple check to ensure all ports are not used up causing
634          * a deadlock here.
635          *
636          * We split the two cases (up and down) so that the direction
637          * is not being tested on each round of the loop.
638          */
639         if (first > last) {
640                 /*
641                  * counting down
642                  */
643                 count = first - last;
644
645                 do {
646                         if (count-- < 0) {      /* completely used? */
647                                 inp->inp_laddr.s_addr = INADDR_ANY;
648                                 error = EADDRNOTAVAIL;
649                                 goto done;
650                         }
651                         --*lastport;
652                         if (*lastport > first || *lastport < last)
653                                 *lastport = first;
654                         lport = htons(*lastport);
655                 } while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
656                                 sin->sin_addr, sin->sin_port, cred));
657         } else {
658                 /*
659                  * counting up
660                  */
661                 count = last - first;
662
663                 do {
664                         if (count-- < 0) {      /* completely used? */
665                                 inp->inp_laddr.s_addr = INADDR_ANY;
666                                 error = EADDRNOTAVAIL;
667                                 goto done;
668                         }
669                         ++*lastport;
670                         if (*lastport < first || *lastport > last)
671                                 *lastport = first;
672                         lport = htons(*lastport);
673                 } while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
674                                 sin->sin_addr, sin->sin_port, cred));
675         }
676
677         /* This could happen on loopback interface */
678         if (sin->sin_port == lport &&
679             sin->sin_addr.s_addr == inp->inp_laddr.s_addr) {
680                 if (dup) {
681                         /*
682                          * Duplicate again; give up
683                          */
684                         inp->inp_laddr.s_addr = INADDR_ANY;
685                         error = EADDRNOTAVAIL;
686                         goto done;
687                 }
688                 dup = 1;
689                 goto again;
690         }
691         inp->inp_lport = lport;
692
693         if (in_pcbinsporthash(inp) != 0) {
694                 inp->inp_laddr.s_addr = INADDR_ANY;
695                 inp->inp_lport = 0;
696                 error = EAGAIN;
697                 goto done;
698         }
699         error = 0;
700 done:
701         if (pcbinfo->porttoken)
702                 lwkt_reltoken(pcbinfo->porttoken);
703         return error;
704 }
705
706 /*
707  *   Transform old in_pcbconnect() into an inner subroutine for new
708  *   in_pcbconnect(): Do some validity-checking on the remote
709  *   address (in mbuf 'nam') and then determine local host address
710  *   (i.e., which interface) to use to access that remote host.
711  *
712  *   This preserves definition of in_pcbconnect(), while supporting a
713  *   slightly different version for T/TCP.  (This is more than
714  *   a bit of a kludge, but cleaning up the internal interfaces would
715  *   have forced minor changes in every protocol).
716  */
717 int
718 in_pcbladdr_find(struct inpcb *inp, struct sockaddr *nam,
719     struct sockaddr_in **plocal_sin, struct thread *td, int find)
720 {
721         struct in_ifaddr *ia;
722         struct ucred *cred = NULL;
723         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
724         struct sockaddr *jsin;
725         int jailed = 0, alloc_route = 0;
726
727         if (nam->sa_len != sizeof *sin)
728                 return (EINVAL);
729         if (sin->sin_family != AF_INET)
730                 return (EAFNOSUPPORT);
731         if (sin->sin_port == 0)
732                 return (EADDRNOTAVAIL);
733         if (td && td->td_proc && td->td_proc->p_ucred)
734                 cred = td->td_proc->p_ucred;
735         if (cred && cred->cr_prison)
736                 jailed = 1;
737         if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
738                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
739                 /*
740                  * If the destination address is INADDR_ANY,
741                  * use the primary local address.
742                  * If the supplied address is INADDR_BROADCAST,
743                  * and the primary interface supports broadcast,
744                  * choose the broadcast address for that interface.
745                  */
746                 if (sin->sin_addr.s_addr == INADDR_ANY)
747                         sin->sin_addr = IA_SIN(ia)->sin_addr;
748                 else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
749                     (ia->ia_ifp->if_flags & IFF_BROADCAST))
750                         sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
751         }
752         if (find) {
753                 struct route *ro;
754
755                 ia = NULL;
756                 /*
757                  * If route is known or can be allocated now,
758                  * our src addr is taken from the i/f, else punt.
759                  * Note that we should check the address family of the cached
760                  * destination, in case of sharing the cache with IPv6.
761                  */
762                 ro = &inp->inp_route;
763                 if (ro->ro_rt &&
764                     (!(ro->ro_rt->rt_flags & RTF_UP) ||
765                      ro->ro_dst.sa_family != AF_INET ||
766                      satosin(&ro->ro_dst)->sin_addr.s_addr !=
767                                       sin->sin_addr.s_addr ||
768                      inp->inp_socket->so_options & SO_DONTROUTE)) {
769                         RTFREE(ro->ro_rt);
770                         ro->ro_rt = NULL;
771                 }
772                 if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
773                     (ro->ro_rt == NULL ||
774                     ro->ro_rt->rt_ifp == NULL)) {
775                         /* No route yet, so try to acquire one */
776                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
777                         ro->ro_dst.sa_family = AF_INET;
778                         ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
779                         ((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
780                                 sin->sin_addr;
781                         rtalloc(ro);
782                         alloc_route = 1;
783                 }
784                 /*
785                  * If we found a route, use the address
786                  * corresponding to the outgoing interface
787                  * unless it is the loopback (in case a route
788                  * to our address on another net goes to loopback).
789                  */
790                 if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
791                         if (jailed) {
792                                 if (jailed_ip(cred->cr_prison, 
793                                     ro->ro_rt->rt_ifa->ifa_addr)) {
794                                         ia = ifatoia(ro->ro_rt->rt_ifa);
795                                 }
796                         } else {
797                                 ia = ifatoia(ro->ro_rt->rt_ifa);
798                         }
799                 }
800                 if (ia == NULL) {
801                         u_short fport = sin->sin_port;
802
803                         sin->sin_port = 0;
804                         ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
805                         if (ia && jailed && !jailed_ip(cred->cr_prison,
806                             sintosa(&ia->ia_addr)))
807                                 ia = NULL;
808                         if (ia == NULL)
809                                 ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
810                         if (ia && jailed && !jailed_ip(cred->cr_prison,
811                             sintosa(&ia->ia_addr)))
812                                 ia = NULL;
813                         sin->sin_port = fport;
814                         if (ia == NULL &&
815                             !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
816                                 ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
817                         if (ia && jailed && !jailed_ip(cred->cr_prison,
818                             sintosa(&ia->ia_addr)))
819                                 ia = NULL;
820
821                         if (!jailed && ia == NULL)
822                                 goto fail;
823                 }
824                 /*
825                  * If the destination address is multicast and an outgoing
826                  * interface has been set as a multicast option, use the
827                  * address of that interface as our source address.
828                  */
829                 if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
830                     inp->inp_moptions != NULL) {
831                         struct ip_moptions *imo;
832                         struct ifnet *ifp;
833
834                         imo = inp->inp_moptions;
835                         if (imo->imo_multicast_ifp != NULL) {
836                                 struct in_ifaddr_container *iac;
837
838                                 ifp = imo->imo_multicast_ifp;
839                                 ia = NULL;
840                                 TAILQ_FOREACH(iac,
841                                 &in_ifaddrheads[mycpuid], ia_link) {
842                                         if (iac->ia->ia_ifp == ifp) {
843                                                 ia = iac->ia;
844                                                 break;
845                                         }
846                                 }
847                                 if (ia == NULL)
848                                         goto fail;
849                         }
850                 }
851                 /*
852                  * Don't do pcblookup call here; return interface in plocal_sin
853                  * and exit to caller, that will do the lookup.
854                  */
855                 if (ia == NULL && jailed) {
856                         if ((jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL)) != NULL ||
857                             (jsin = prison_get_local(cred->cr_prison, AF_INET, NULL)) != NULL) {
858                                 *plocal_sin = satosin(jsin);
859                         } else {
860                                 /* IPv6 only Jail */
861                                 goto fail;
862                         }
863                 } else {
864                         *plocal_sin = &ia->ia_addr;
865                 }
866         }
867         return (0);
868 fail:
869         if (alloc_route) {
870                 struct route *ro = &inp->inp_route;
871
872                 if (ro->ro_rt != NULL)
873                         RTFREE(ro->ro_rt);
874                 bzero(ro, sizeof(*ro));
875         }
876         return (EADDRNOTAVAIL);
877 }
878
879 int
880 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
881     struct sockaddr_in **plocal_sin, struct thread *td)
882 {
883         return in_pcbladdr_find(inp, nam, plocal_sin, td,
884             (inp->inp_laddr.s_addr == INADDR_ANY));
885 }
886
887 /*
888  * Outer subroutine:
889  * Connect from a socket to a specified address.
890  * Both address and port must be specified in argument sin.
891  * If don't have a local address for this socket yet,
892  * then pick one.
893  */
894 int
895 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
896 {
897         struct sockaddr_in *if_sin;
898         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
899         int error;
900
901         /* Call inner routine to assign local interface address. */
902         if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
903                 return (error);
904
905         if (in_pcblookup_hash(inp->inp_cpcbinfo, sin->sin_addr, sin->sin_port,
906                               inp->inp_laddr.s_addr ?
907                                 inp->inp_laddr : if_sin->sin_addr,
908                               inp->inp_lport, FALSE, NULL) != NULL) {
909                 return (EADDRINUSE);
910         }
911         if (inp->inp_laddr.s_addr == INADDR_ANY) {
912                 if (inp->inp_lport == 0) {
913                         error = in_pcbbind(inp, NULL, td);
914                         if (error)
915                                 return (error);
916                 }
917                 inp->inp_laddr = if_sin->sin_addr;
918         }
919         inp->inp_faddr = sin->sin_addr;
920         inp->inp_fport = sin->sin_port;
921         in_pcbinsconnhash(inp);
922         return (0);
923 }
924
925 void
926 in_pcbdisconnect(struct inpcb *inp)
927 {
928
929         inp->inp_faddr.s_addr = INADDR_ANY;
930         inp->inp_fport = 0;
931         in_pcbremconnhash(inp);
932         if (inp->inp_socket->so_state & SS_NOFDREF)
933                 in_pcbdetach(inp);
934 }
935
936 void
937 in_pcbdetach(struct inpcb *inp)
938 {
939         struct socket *so = inp->inp_socket;
940         struct inpcbinfo *ipi = inp->inp_pcbinfo;
941
942 #ifdef IPSEC
943         ipsec4_delete_pcbpolicy(inp);
944 #endif /*IPSEC*/
945         inp->inp_gencnt = ++ipi->ipi_gencnt;
946         KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
947         in_pcbremlists(inp);
948         so->so_pcb = NULL;
949         sofree(so);                     /* remove pcb ref */
950         if (inp->inp_options)
951                 m_free(inp->inp_options);
952         if (inp->inp_route.ro_rt)
953                 rtfree(inp->inp_route.ro_rt);
954         ip_freemoptions(inp->inp_moptions);
955         inp->inp_vflag = 0;
956         kfree(inp, M_PCB);
957 }
958
959 /*
960  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
961  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
962  * in struct pr_usrreqs, so that protocols can just reference then directly
963  * without the need for a wrapper function.  The socket must have a valid
964  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
965  * except through a kernel programming error, so it is acceptable to panic
966  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
967  * because there actually /is/ a programming error somewhere... XXX)
968  */
969 int
970 in_setsockaddr(struct socket *so, struct sockaddr **nam)
971 {
972         struct inpcb *inp;
973         struct sockaddr_in *sin;
974
975         /*
976          * Do the malloc first in case it blocks.
977          */
978         sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
979         sin->sin_family = AF_INET;
980         sin->sin_len = sizeof *sin;
981
982         crit_enter();
983         inp = so->so_pcb;
984         if (!inp) {
985                 crit_exit();
986                 kfree(sin, M_SONAME);
987                 return (ECONNRESET);
988         }
989         sin->sin_port = inp->inp_lport;
990         sin->sin_addr = inp->inp_laddr;
991         crit_exit();
992
993         *nam = (struct sockaddr *)sin;
994         return (0);
995 }
996
997 void
998 in_setsockaddr_dispatch(netmsg_t msg)
999 {
1000         int error;
1001
1002         error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1003         lwkt_replymsg(&msg->lmsg, error);
1004 }
1005
1006 int
1007 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1008 {
1009         struct inpcb *inp;
1010         struct sockaddr_in *sin;
1011
1012         /*
1013          * Do the malloc first in case it blocks.
1014          */
1015         sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1016         sin->sin_family = AF_INET;
1017         sin->sin_len = sizeof *sin;
1018
1019         crit_enter();
1020         inp = so->so_pcb;
1021         if (!inp) {
1022                 crit_exit();
1023                 kfree(sin, M_SONAME);
1024                 return (ECONNRESET);
1025         }
1026         sin->sin_port = inp->inp_fport;
1027         sin->sin_addr = inp->inp_faddr;
1028         crit_exit();
1029
1030         *nam = (struct sockaddr *)sin;
1031         return (0);
1032 }
1033
1034 void
1035 in_setpeeraddr_dispatch(netmsg_t msg)
1036 {
1037         int error;
1038
1039         error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1040         lwkt_replymsg(&msg->lmsg, error);
1041 }
1042
1043 void
1044 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
1045                 void (*notify)(struct inpcb *, int))
1046 {
1047         struct inpcb *inp, *ninp;
1048
1049         /*
1050          * note: if INP_PLACEMARKER is set we must ignore the rest of
1051          * the structure and skip it.
1052          */
1053         crit_enter();
1054         LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
1055                 if (inp->inp_flags & INP_PLACEMARKER)
1056                         continue;
1057 #ifdef INET6
1058                 if (!(inp->inp_vflag & INP_IPV4))
1059                         continue;
1060 #endif
1061                 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1062                     inp->inp_socket == NULL)
1063                         continue;
1064                 (*notify)(inp, err);            /* can remove inp from list! */
1065         }
1066         crit_exit();
1067 }
1068
1069 void
1070 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
1071 {
1072         struct inpcb *inp;
1073         struct ip_moptions *imo;
1074         int i, gap;
1075
1076         for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
1077                 if (inp->inp_flags & INP_PLACEMARKER)
1078                         continue;
1079                 imo = inp->inp_moptions;
1080                 if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
1081                         /*
1082                          * Unselect the outgoing interface if it is being
1083                          * detached.
1084                          */
1085                         if (imo->imo_multicast_ifp == ifp)
1086                                 imo->imo_multicast_ifp = NULL;
1087
1088                         /*
1089                          * Drop multicast group membership if we joined
1090                          * through the interface being detached.
1091                          */
1092                         for (i = 0, gap = 0; i < imo->imo_num_memberships;
1093                             i++) {
1094                                 if (imo->imo_membership[i]->inm_ifp == ifp) {
1095                                         in_delmulti(imo->imo_membership[i]);
1096                                         gap++;
1097                                 } else if (gap != 0)
1098                                         imo->imo_membership[i - gap] =
1099                                             imo->imo_membership[i];
1100                         }
1101                         imo->imo_num_memberships -= gap;
1102                 }
1103         }
1104 }
1105
1106 /*
1107  * Check for alternatives when higher level complains
1108  * about service problems.  For now, invalidate cached
1109  * routing information.  If the route was created dynamically
1110  * (by a redirect), time to try a default gateway again.
1111  */
1112 void
1113 in_losing(struct inpcb *inp)
1114 {
1115         struct rtentry *rt;
1116         struct rt_addrinfo rtinfo;
1117
1118         if ((rt = inp->inp_route.ro_rt)) {
1119                 bzero(&rtinfo, sizeof(struct rt_addrinfo));
1120                 rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1121                 rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1122                 rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1123                 rtinfo.rti_flags = rt->rt_flags;
1124                 rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1125                 if (rt->rt_flags & RTF_DYNAMIC) {
1126                         rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1127                             rt_mask(rt), rt->rt_flags, NULL);
1128                 }
1129                 inp->inp_route.ro_rt = NULL;
1130                 rtfree(rt);
1131                 /*
1132                  * A new route can be allocated
1133                  * the next time output is attempted.
1134                  */
1135         }
1136 }
1137
1138 /*
1139  * After a routing change, flush old routing
1140  * and allocate a (hopefully) better one.
1141  */
1142 void
1143 in_rtchange(struct inpcb *inp, int err)
1144 {
1145         if (inp->inp_route.ro_rt) {
1146                 rtfree(inp->inp_route.ro_rt);
1147                 inp->inp_route.ro_rt = NULL;
1148                 /*
1149                  * A new route can be allocated the next time
1150                  * output is attempted.
1151                  */
1152         }
1153 }
1154
1155 /*
1156  * Lookup a PCB based on the local address and port.
1157  */
1158 struct inpcb *
1159 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1160                    u_int lport_arg, int wild_okay, struct ucred *cred)
1161 {
1162         struct inpcb *inp;
1163         int matchwild = 3, wildcard;
1164         u_short lport = lport_arg;
1165         struct inpcbporthead *porthash;
1166         struct inpcbport *phd;
1167         struct inpcb *match = NULL;
1168
1169         /*
1170          * If the porthashbase is shared across several cpus we need
1171          * to lock.
1172          */
1173         if (pcbinfo->porttoken)
1174                 lwkt_gettoken(pcbinfo->porttoken);
1175
1176         /*
1177          * Best fit PCB lookup.
1178          *
1179          * First see if this local port is in use by looking on the
1180          * port hash list.
1181          */
1182         porthash = &pcbinfo->porthashbase[
1183                         INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
1184         LIST_FOREACH(phd, porthash, phd_hash) {
1185                 if (phd->phd_port == lport)
1186                         break;
1187         }
1188         if (phd != NULL) {
1189                 /*
1190                  * Port is in use by one or more PCBs. Look for best
1191                  * fit.
1192                  */
1193                 LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1194                         wildcard = 0;
1195 #ifdef INET6
1196                         if ((inp->inp_vflag & INP_IPV4) == 0)
1197                                 continue;
1198 #endif
1199                         if (inp->inp_faddr.s_addr != INADDR_ANY)
1200                                 wildcard++;
1201                         if (inp->inp_laddr.s_addr != INADDR_ANY) {
1202                                 if (laddr.s_addr == INADDR_ANY)
1203                                         wildcard++;
1204                                 else if (inp->inp_laddr.s_addr != laddr.s_addr)
1205                                         continue;
1206                         } else {
1207                                 if (laddr.s_addr != INADDR_ANY)
1208                                         wildcard++;
1209                         }
1210                         if (wildcard && !wild_okay)
1211                                 continue;
1212                         if (wildcard < matchwild &&
1213                             (cred == NULL ||
1214                              cred->cr_prison == 
1215                                         inp->inp_socket->so_cred->cr_prison)) {
1216                                 match = inp;
1217                                 matchwild = wildcard;
1218                                 if (matchwild == 0) {
1219                                         break;
1220                                 }
1221                         }
1222                 }
1223         }
1224         if (pcbinfo->porttoken)
1225                 lwkt_reltoken(pcbinfo->porttoken);
1226         return (match);
1227 }
1228
1229 struct inpcb *
1230 in_pcblocalgroup_last(const struct inpcbinfo *pcbinfo,
1231     const struct inpcb *inp)
1232 {
1233         const struct inp_localgrphead *hdr;
1234         const struct inp_localgroup *grp;
1235         int i;
1236
1237         if (pcbinfo->localgrphashbase == NULL)
1238                 return NULL;
1239
1240         hdr = &pcbinfo->localgrphashbase[
1241             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1242
1243         LIST_FOREACH(grp, hdr, il_list) {
1244                 if (grp->il_vflag == inp->inp_vflag &&
1245                     grp->il_lport == inp->inp_lport &&
1246                     memcmp(&grp->il_dependladdr,
1247                         &inp->inp_inc.inc_ie.ie_dependladdr,
1248                         sizeof(grp->il_dependladdr)) == 0) {
1249                         break;
1250                 }
1251         }
1252         if (grp == NULL || grp->il_inpcnt == 1)
1253                 return NULL;
1254
1255         KASSERT(grp->il_inpcnt >= 2,
1256             ("invalid localgroup inp count %d", grp->il_inpcnt));
1257         for (i = 0; i < grp->il_inpcnt; ++i) {
1258                 if (grp->il_inp[i] == inp) {
1259                         int last = grp->il_inpcnt - 1;
1260
1261                         if (i == last)
1262                                 last = grp->il_inpcnt - 2;
1263                         return grp->il_inp[last];
1264                 }
1265         }
1266         return NULL;
1267 }
1268
1269 static struct inpcb *
1270 inp_localgroup_lookup(const struct inpcbinfo *pcbinfo,
1271     struct in_addr laddr, uint16_t lport, uint32_t pkt_hash)
1272 {
1273         struct inpcb *local_wild = NULL;
1274         const struct inp_localgrphead *hdr;
1275         const struct inp_localgroup *grp;
1276
1277         hdr = &pcbinfo->localgrphashbase[
1278             INP_PCBLOCALGRPHASH(lport, pcbinfo->localgrphashmask)];
1279 #ifdef INP_LOCALGROUP_HASHTHR
1280         pkt_hash >>= ncpus2_shift;
1281 #endif
1282
1283         /*
1284          * Order of socket selection:
1285          * 1. non-wild.
1286          * 2. wild.
1287          *
1288          * NOTE:
1289          * - Local group does not contain jailed sockets
1290          * - Local group does not contain IPv4 mapped INET6 wild sockets
1291          */
1292         LIST_FOREACH(grp, hdr, il_list) {
1293 #ifdef INET6
1294                 if (!(grp->il_vflag & INP_IPV4))
1295                         continue;
1296 #endif
1297                 if (grp->il_lport == lport) {
1298                         int idx;
1299
1300 #ifdef INP_LOCALGROUP_HASHTHR
1301                         idx = pkt_hash / grp->il_factor;
1302                         KASSERT(idx < grp->il_inpcnt && idx >= 0,
1303                             ("invalid hash %04x, cnt %d or fact %d",
1304                              pkt_hash, grp->il_inpcnt, grp->il_factor));
1305 #else
1306                         /*
1307                          * Modulo-N is used here, which greatly reduces
1308                          * completion queue token contention, thus more
1309                          * cpu time is saved.
1310                          */
1311                         idx = pkt_hash % grp->il_inpcnt;
1312 #endif
1313
1314                         if (grp->il_laddr.s_addr == laddr.s_addr)
1315                                 return grp->il_inp[idx];
1316                         else if (grp->il_laddr.s_addr == INADDR_ANY)
1317                                 local_wild = grp->il_inp[idx];
1318                 }
1319         }
1320         if (local_wild != NULL)
1321                 return local_wild;
1322         return NULL;
1323 }
1324
1325 /*
1326  * Lookup PCB in hash list.
1327  */
1328 struct inpcb *
1329 in_pcblookup_pkthash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1330     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1331     boolean_t wildcard, struct ifnet *ifp, const struct mbuf *m)
1332 {
1333         struct inpcbhead *head;
1334         struct inpcb *inp, *jinp=NULL;
1335         u_short fport = fport_arg, lport = lport_arg;
1336
1337         /*
1338          * First look for an exact match.
1339          */
1340         head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1341             laddr.s_addr, lport, pcbinfo->hashmask)];
1342         LIST_FOREACH(inp, head, inp_hash) {
1343 #ifdef INET6
1344                 if (!(inp->inp_vflag & INP_IPV4))
1345                         continue;
1346 #endif
1347                 if (in_hosteq(inp->inp_faddr, faddr) &&
1348                     in_hosteq(inp->inp_laddr, laddr) &&
1349                     inp->inp_fport == fport && inp->inp_lport == lport) {
1350                         /* found */
1351                         if (inp->inp_socket == NULL ||
1352                             inp->inp_socket->so_cred->cr_prison == NULL) {
1353                                 return (inp);
1354                         } else {
1355                                 if  (jinp == NULL)
1356                                         jinp = inp;
1357                         }
1358                 }
1359         }
1360         if (jinp != NULL)
1361                 return (jinp);
1362         if (wildcard) {
1363                 struct inpcb *local_wild = NULL;
1364                 struct inpcb *jinp_wild = NULL;
1365 #ifdef INET6
1366                 struct inpcb *local_wild_mapped = NULL;
1367 #endif
1368                 struct inpcontainer *ic;
1369                 struct inpcontainerhead *chead;
1370                 struct sockaddr_in jsin;
1371                 struct ucred *cred;
1372
1373                 /*
1374                  * Check local group first
1375                  */
1376                 if (pcbinfo->localgrphashbase != NULL &&
1377                     m != NULL && (m->m_flags & M_HASH) &&
1378                     !(ifp && ifp->if_type == IFT_FAITH)) {
1379                         inp = inp_localgroup_lookup(pcbinfo,
1380                             laddr, lport, m->m_pkthdr.hash);
1381                         if (inp != NULL)
1382                                 return inp;
1383                 }
1384
1385                 /*
1386                  * Order of socket selection:
1387                  * 1. non-jailed, non-wild.
1388                  * 2. non-jailed, wild.
1389                  * 3. jailed, non-wild.
1390                  * 4. jailed, wild.
1391                  */
1392                 jsin.sin_family = AF_INET;
1393                 chead = &pcbinfo->wildcardhashbase[
1394                     INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1395                 LIST_FOREACH(ic, chead, ic_list) {
1396                         inp = ic->ic_inp;
1397                         jsin.sin_addr.s_addr = laddr.s_addr;
1398 #ifdef INET6
1399                         if (!(inp->inp_vflag & INP_IPV4))
1400                                 continue;
1401 #endif
1402                         if (inp->inp_socket != NULL)
1403                                 cred = inp->inp_socket->so_cred;
1404                         else
1405                                 cred = NULL;
1406                         if (cred != NULL && jailed(cred)) {
1407                                 if (jinp != NULL)
1408                                         continue;
1409                                 else
1410                                         if (!jailed_ip(cred->cr_prison,
1411                                             (struct sockaddr *)&jsin))
1412                                                 continue;
1413                         }
1414                         if (inp->inp_lport == lport) {
1415                                 if (ifp && ifp->if_type == IFT_FAITH &&
1416                                     !(inp->inp_flags & INP_FAITH))
1417                                         continue;
1418                                 if (inp->inp_laddr.s_addr == laddr.s_addr) {
1419                                         if (cred != NULL && jailed(cred))
1420                                                 jinp = inp;
1421                                         else
1422                                                 return (inp);
1423                                 }
1424                                 if (inp->inp_laddr.s_addr == INADDR_ANY) {
1425 #ifdef INET6
1426                                         if (INP_CHECK_SOCKAF(inp->inp_socket,
1427                                                              AF_INET6))
1428                                                 local_wild_mapped = inp;
1429                                         else
1430 #endif
1431                                                 if (cred != NULL &&
1432                                                     jailed(cred))
1433                                                         jinp_wild = inp;
1434                                                 else
1435                                                         local_wild = inp;
1436                                 }
1437                         }
1438                 }
1439                 if (local_wild != NULL)
1440                         return (local_wild);
1441 #ifdef INET6
1442                 if (local_wild_mapped != NULL)
1443                         return (local_wild_mapped);
1444 #endif
1445                 if (jinp != NULL)
1446                         return (jinp);
1447                 return (jinp_wild);
1448         }
1449
1450         /*
1451          * Not found.
1452          */
1453         return (NULL);
1454 }
1455
1456 struct inpcb *
1457 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1458     u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1459     boolean_t wildcard, struct ifnet *ifp)
1460 {
1461         return in_pcblookup_pkthash(pcbinfo, faddr, fport_arg,
1462             laddr, lport_arg, wildcard, ifp, NULL);
1463 }
1464
1465 /*
1466  * Insert PCB into connection hash table.
1467  */
1468 void
1469 in_pcbinsconnhash(struct inpcb *inp)
1470 {
1471         struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1472         struct inpcbhead *bucket;
1473         u_int32_t hashkey_faddr, hashkey_laddr;
1474
1475 #ifdef INET6
1476         if (inp->inp_vflag & INP_IPV6) {
1477                 hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1478                 hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1479         } else {
1480 #endif
1481                 hashkey_faddr = inp->inp_faddr.s_addr;
1482                 hashkey_laddr = inp->inp_laddr.s_addr;
1483 #ifdef INET6
1484         }
1485 #endif
1486
1487         KASSERT(!(inp->inp_flags & INP_WILDCARD),
1488                 ("already on wildcardhash"));
1489         KASSERT(!(inp->inp_flags & INP_CONNECTED),
1490                 ("already on connhash"));
1491         inp->inp_flags |= INP_CONNECTED;
1492
1493         /*
1494          * Insert into the connection hash table.
1495          */
1496         bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1497             inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1498         LIST_INSERT_HEAD(bucket, inp, inp_hash);
1499 }
1500
1501 /*
1502  * Remove PCB from connection hash table.
1503  */
1504 void
1505 in_pcbremconnhash(struct inpcb *inp)
1506 {
1507         KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1508         LIST_REMOVE(inp, inp_hash);
1509         inp->inp_flags &= ~INP_CONNECTED;
1510 }
1511
1512 /*
1513  * Insert PCB into port hash table.
1514  */
1515 int
1516 in_pcbinsporthash(struct inpcb *inp)
1517 {
1518         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1519         struct inpcbporthead *pcbporthash;
1520         struct inpcbport *phd;
1521
1522         /*
1523          * If the porthashbase is shared across several cpus we need
1524          * to lock.
1525          */
1526         if (pcbinfo->porttoken)
1527                 lwkt_gettoken(pcbinfo->porttoken);
1528
1529         /*
1530          * Insert into the port hash table.
1531          */
1532         pcbporthash = &pcbinfo->porthashbase[
1533             INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1534
1535         /* Go through port list and look for a head for this lport. */
1536         LIST_FOREACH(phd, pcbporthash, phd_hash) {
1537                 if (phd->phd_port == inp->inp_lport)
1538                         break;
1539         }
1540
1541         /* If none exists, malloc one and tack it on. */
1542         if (phd == NULL) {
1543                 KKASSERT(pcbinfo->portsave != NULL);
1544                 phd = pcbinfo->portsave;
1545                 pcbinfo->portsave = NULL;
1546                 phd->phd_port = inp->inp_lport;
1547                 LIST_INIT(&phd->phd_pcblist);
1548                 LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1549         }
1550
1551         inp->inp_phd = phd;
1552         LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1553
1554         if (pcbinfo->porttoken)
1555                 lwkt_reltoken(pcbinfo->porttoken);
1556         if (pcbinfo->portsave == NULL) {
1557                 pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1558                                             M_PCB, M_INTWAIT | M_ZERO);
1559         }
1560         return (0);
1561 }
1562
1563 static struct inp_localgroup *
1564 inp_localgroup_alloc(struct inp_localgrphead *hdr, u_char vflag,
1565     uint16_t port, const union in_dependaddr *addr, int size)
1566 {
1567         struct inp_localgroup *grp;
1568
1569         grp = kmalloc(__offsetof(struct inp_localgroup, il_inp[size]),
1570             M_TEMP, M_INTWAIT | M_ZERO);
1571         grp->il_vflag = vflag;
1572         grp->il_lport = port;
1573         grp->il_dependladdr = *addr;
1574         grp->il_inpsiz = size;
1575
1576         LIST_INSERT_HEAD(hdr, grp, il_list);
1577
1578         return grp;
1579 }
1580
1581 static void
1582 inp_localgroup_free(struct inp_localgroup *grp)
1583 {
1584         LIST_REMOVE(grp, il_list);
1585         kfree(grp, M_TEMP);
1586 }
1587
1588 static struct inp_localgroup *
1589 inp_localgroup_resize(struct inp_localgrphead *hdr,
1590     struct inp_localgroup *old_grp, int size)
1591 {
1592         struct inp_localgroup *grp;
1593         int i;
1594
1595         grp = inp_localgroup_alloc(hdr, old_grp->il_vflag,
1596             old_grp->il_lport, &old_grp->il_dependladdr, size);
1597
1598         KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
1599             ("invalid new local group size %d and old local group count %d",
1600              grp->il_inpsiz, old_grp->il_inpcnt));
1601         for (i = 0; i < old_grp->il_inpcnt; ++i)
1602                 grp->il_inp[i] = old_grp->il_inp[i];
1603         grp->il_inpcnt = old_grp->il_inpcnt;
1604         grp->il_factor = old_grp->il_factor;
1605
1606         inp_localgroup_free(old_grp);
1607
1608         return grp;
1609 }
1610
1611 static void
1612 inp_localgroup_factor(struct inp_localgroup *grp)
1613 {
1614         grp->il_factor =
1615             ((uint32_t)(0xffff >> ncpus2_shift) / grp->il_inpcnt) + 1;
1616         KASSERT(grp->il_factor != 0, ("invalid local group factor, "
1617             "ncpus2_shift %d, inpcnt %d", ncpus2_shift, grp->il_inpcnt));
1618 }
1619
1620 static void
1621 in_pcbinslocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1622 {
1623         struct inp_localgrphead *hdr;
1624         struct inp_localgroup *grp;
1625         struct ucred *cred;
1626
1627         if (pcbinfo->localgrphashbase == NULL)
1628                 return;
1629
1630         /*
1631          * XXX don't allow jailed socket to join local group
1632          */
1633         if (inp->inp_socket != NULL)
1634                 cred = inp->inp_socket->so_cred;
1635         else
1636                 cred = NULL;
1637         if (cred != NULL && jailed(cred))
1638                 return;
1639
1640 #ifdef INET6
1641         /*
1642          * XXX don't allow IPv4 mapped INET6 wild socket
1643          */
1644         if ((inp->inp_vflag & INP_IPV4) &&
1645             inp->inp_laddr.s_addr == INADDR_ANY &&
1646             INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6))
1647                 return;
1648 #endif
1649
1650         hdr = &pcbinfo->localgrphashbase[
1651             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1652
1653         LIST_FOREACH(grp, hdr, il_list) {
1654                 if (grp->il_vflag == inp->inp_vflag &&
1655                     grp->il_lport == inp->inp_lport &&
1656                     memcmp(&grp->il_dependladdr,
1657                         &inp->inp_inc.inc_ie.ie_dependladdr,
1658                         sizeof(grp->il_dependladdr)) == 0) {
1659                         break;
1660                 }
1661         }
1662         if (grp == NULL) {
1663                 /* Create new local group */
1664                 grp = inp_localgroup_alloc(hdr, inp->inp_vflag,
1665                     inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
1666                     INP_LOCALGROUP_SIZMIN);
1667         } else if (grp->il_inpcnt == grp->il_inpsiz) {
1668                 if (grp->il_inpsiz >= INP_LOCALGROUP_SIZMAX) {
1669                         static int limit_logged = 0;
1670
1671                         if (!limit_logged) {
1672                                 limit_logged = 1;
1673                                 kprintf("local group port %d, "
1674                                     "limit reached\n", ntohs(grp->il_lport));
1675                         }
1676                         return;
1677                 }
1678
1679                 /* Expand this local group */
1680                 grp = inp_localgroup_resize(hdr, grp, grp->il_inpsiz * 2);
1681         }
1682
1683         KASSERT(grp->il_inpcnt < grp->il_inpsiz,
1684             ("invalid local group size %d and count %d",
1685              grp->il_inpsiz, grp->il_inpcnt));
1686         grp->il_inp[grp->il_inpcnt] = inp;
1687         grp->il_inpcnt++;
1688         inp_localgroup_factor(grp);
1689 }
1690
1691 void
1692 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1693 {
1694         struct inpcontainer *ic;
1695         struct inpcontainerhead *bucket;
1696
1697         in_pcbinslocalgrphash_oncpu(inp, pcbinfo);
1698
1699         bucket = &pcbinfo->wildcardhashbase[
1700             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1701
1702         ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1703         ic->ic_inp = inp;
1704         LIST_INSERT_HEAD(bucket, ic, ic_list);
1705 }
1706
1707 /*
1708  * Insert PCB into wildcard hash table.
1709  */
1710 void
1711 in_pcbinswildcardhash(struct inpcb *inp)
1712 {
1713         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1714
1715         KASSERT(!(inp->inp_flags & INP_CONNECTED),
1716                 ("already on connhash"));
1717         KASSERT(!(inp->inp_flags & INP_WILDCARD),
1718                 ("already on wildcardhash"));
1719         inp->inp_flags |= INP_WILDCARD;
1720
1721         in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1722 }
1723
1724 static void
1725 in_pcbremlocalgrphash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1726 {
1727         struct inp_localgrphead *hdr;
1728         struct inp_localgroup *grp;
1729
1730         if (pcbinfo->localgrphashbase == NULL)
1731                 return;
1732
1733         hdr = &pcbinfo->localgrphashbase[
1734             INP_PCBLOCALGRPHASH(inp->inp_lport, pcbinfo->localgrphashmask)];
1735
1736         LIST_FOREACH(grp, hdr, il_list) {
1737                 int i;
1738
1739                 for (i = 0; i < grp->il_inpcnt; ++i) {
1740                         if (grp->il_inp[i] != inp)
1741                                 continue;
1742
1743                         if (grp->il_inpcnt == 1) {
1744                                 /* Free this local group */
1745                                 inp_localgroup_free(grp);
1746                         } else {
1747                                 /* Pull up inpcbs */
1748                                 for (; i + 1 < grp->il_inpcnt; ++i)
1749                                         grp->il_inp[i] = grp->il_inp[i + 1];
1750                                 grp->il_inpcnt--;
1751                                 inp_localgroup_factor(grp);
1752
1753                                 if (grp->il_inpsiz > INP_LOCALGROUP_SIZMIN &&
1754                                     grp->il_inpcnt <= (grp->il_inpsiz / 4)) {
1755                                         /* Shrink this local group */
1756                                         grp = inp_localgroup_resize(hdr, grp,
1757                                             grp->il_inpsiz / 2);
1758                                 }
1759                         }
1760                         return;
1761                 }
1762         }
1763 }
1764
1765 void
1766 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1767 {
1768         struct inpcontainer *ic;
1769         struct inpcontainerhead *head;
1770
1771         in_pcbremlocalgrphash_oncpu(inp, pcbinfo);
1772
1773         /* find bucket */
1774         head = &pcbinfo->wildcardhashbase[
1775             INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1776
1777         LIST_FOREACH(ic, head, ic_list) {
1778                 if (ic->ic_inp == inp)
1779                         goto found;
1780         }
1781         return;                 /* not found! */
1782
1783 found:
1784         LIST_REMOVE(ic, ic_list);       /* remove container from bucket chain */
1785         kfree(ic, M_TEMP);              /* deallocate container */
1786 }
1787
1788 /*
1789  * Remove PCB from wildcard hash table.
1790  */
1791 void
1792 in_pcbremwildcardhash(struct inpcb *inp)
1793 {
1794         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1795
1796         KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1797         in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1798         inp->inp_flags &= ~INP_WILDCARD;
1799 }
1800
1801 /*
1802  * Remove PCB from various lists.
1803  */
1804 void
1805 in_pcbremlists(struct inpcb *inp)
1806 {
1807         struct inpcbinfo *pcbinfo;
1808
1809         if (inp->inp_lport) {
1810                 struct inpcbport *phd;
1811
1812                 pcbinfo = inp->inp_pcbinfo;
1813                 if (pcbinfo->porttoken)
1814                         lwkt_gettoken(pcbinfo->porttoken);
1815
1816                 phd = inp->inp_phd;
1817                 LIST_REMOVE(inp, inp_portlist);
1818                 if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1819                         LIST_REMOVE(phd, phd_hash);
1820                         kfree(phd, M_PCB);
1821                 }
1822                 if (pcbinfo->porttoken)
1823                         lwkt_reltoken(pcbinfo->porttoken);
1824         }
1825         if (inp->inp_flags & INP_WILDCARD) {
1826                 in_pcbremwildcardhash(inp);
1827         } else if (inp->inp_flags & INP_CONNECTED) {
1828                 in_pcbremconnhash(inp);
1829         }
1830         LIST_REMOVE(inp, inp_list);
1831         inp->inp_pcbinfo->ipi_count--;
1832 }
1833
1834 int
1835 prison_xinpcb(struct thread *td, struct inpcb *inp)
1836 {
1837         struct ucred *cr;
1838
1839         if (td->td_proc == NULL)
1840                 return (0);
1841         cr = td->td_proc->p_ucred;
1842         if (cr->cr_prison == NULL)
1843                 return (0);
1844         if (inp->inp_socket && inp->inp_socket->so_cred &&
1845             inp->inp_socket->so_cred->cr_prison &&
1846             cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1847                 return (0);
1848         return (1);
1849 }
1850
1851 int
1852 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1853 {
1854         struct inpcbinfo *pcbinfo = arg1;
1855         struct inpcb *inp, *marker;
1856         struct xinpcb xi;
1857         int error, i, n;
1858
1859         /*
1860          * The process of preparing the TCB list is too time-consuming and
1861          * resource-intensive to repeat twice on every request.
1862          */
1863         if (req->oldptr == NULL) {
1864                 n = pcbinfo->ipi_count;
1865                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1866                 return 0;
1867         }
1868
1869         if (req->newptr != NULL)
1870                 return EPERM;
1871
1872         /*
1873          * OK, now we're committed to doing something.  Re-fetch ipi_count
1874          * after obtaining the generation count.
1875          */
1876         n = pcbinfo->ipi_count;
1877
1878         marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1879         marker->inp_flags |= INP_PLACEMARKER;
1880         LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1881
1882         i = 0;
1883         error = 0;
1884
1885         while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1886                 LIST_REMOVE(marker, inp_list);
1887                 LIST_INSERT_AFTER(inp, marker, inp_list);
1888
1889                 if (inp->inp_flags & INP_PLACEMARKER)
1890                         continue;
1891                 if (prison_xinpcb(req->td, inp))
1892                         continue;
1893                 bzero(&xi, sizeof xi);
1894                 xi.xi_len = sizeof xi;
1895                 bcopy(inp, &xi.xi_inp, sizeof *inp);
1896                 if (inp->inp_socket)
1897                         sotoxsocket(inp->inp_socket, &xi.xi_socket);
1898                 if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1899                         break;
1900                 ++i;
1901         }
1902         LIST_REMOVE(marker, inp_list);
1903         if (error == 0 && i < n) {
1904                 bzero(&xi, sizeof xi);
1905                 xi.xi_len = sizeof xi;
1906                 while (i < n) {
1907                         error = SYSCTL_OUT(req, &xi, sizeof xi);
1908                         ++i;
1909                 }
1910         }
1911         kfree(marker, M_TEMP);
1912         return(error);
1913 }
1914
1915 int
1916 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
1917 {
1918         struct inpcbinfo *pcbinfo = arg1;
1919         struct inpcb *inp;
1920         struct xinpcb *xi;
1921         int nxi;
1922
1923         *nxi0 = 0;
1924         *xi0 = NULL;
1925
1926         /*
1927          * The process of preparing the PCB list is too time-consuming and
1928          * resource-intensive to repeat twice on every request.
1929          */
1930         if (req->oldptr == NULL) {
1931                 int n = pcbinfo->ipi_count;
1932
1933                 req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1934                 return 0;
1935         }
1936
1937         if (req->newptr != NULL)
1938                 return EPERM;
1939
1940         if (pcbinfo->ipi_count == 0)
1941                 return 0;
1942
1943         nxi = 0;
1944         xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
1945                      M_WAITOK | M_ZERO | M_NULLOK);
1946         if (xi == NULL)
1947                 return ENOMEM;
1948
1949         LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
1950                 struct xinpcb *xi_ptr = &xi[nxi];
1951
1952                 if (prison_xinpcb(req->td, inp))
1953                         continue;
1954
1955                 xi_ptr->xi_len = sizeof(*xi_ptr);
1956                 bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
1957                 if (inp->inp_socket)
1958                         sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
1959                 ++nxi;
1960         }
1961
1962         if (nxi == 0) {
1963                 kfree(xi, M_TEMP);
1964                 return 0;
1965         }
1966
1967         *nxi0 = nxi;
1968         *xi0 = xi;
1969
1970         return 0;
1971 }
1972
1973 void
1974 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
1975 {
1976         struct sockaddr_in *sin;
1977
1978         KASSERT(faddr->sa_family == AF_INET,
1979             ("not AF_INET faddr %d", faddr->sa_family));
1980
1981         sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
1982         sin->sin_family = AF_INET;
1983         sin->sin_len = sizeof(*sin);
1984         sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
1985         sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
1986
1987         so->so_faddr = (struct sockaddr *)sin;
1988 }