]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/in_pcb.c
Improve style in in_pcbinslbgrouphash() and related subroutines.
[FreeBSD/FreeBSD.git] / sys / netinet / in_pcb.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1991, 1993, 1995
5  *      The Regents of the University of California.
6  * Copyright (c) 2007-2009 Robert N. M. Watson
7  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8  * All rights reserved.
9  *
10  * Portions of this software were developed by Robert N. M. Watson under
11  * contract to Juniper Networks, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      @(#)in_pcb.c    8.4 (Berkeley) 5/24/95
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #include "opt_ddb.h"
44 #include "opt_ipsec.h"
45 #include "opt_inet.h"
46 #include "opt_inet6.h"
47 #include "opt_ratelimit.h"
48 #include "opt_pcbgroup.h"
49 #include "opt_rss.h"
50
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mbuf.h>
56 #include <sys/callout.h>
57 #include <sys/eventhandler.h>
58 #include <sys/domain.h>
59 #include <sys/protosw.h>
60 #include <sys/rmlock.h>
61 #include <sys/smp.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sockio.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/refcount.h>
68 #include <sys/jail.h>
69 #include <sys/kernel.h>
70 #include <sys/sysctl.h>
71
72 #ifdef DDB
73 #include <ddb/ddb.h>
74 #endif
75
76 #include <vm/uma.h>
77
78 #include <net/if.h>
79 #include <net/if_var.h>
80 #include <net/if_types.h>
81 #include <net/if_llatbl.h>
82 #include <net/route.h>
83 #include <net/rss_config.h>
84 #include <net/vnet.h>
85
86 #if defined(INET) || defined(INET6)
87 #include <netinet/in.h>
88 #include <netinet/in_pcb.h>
89 #include <netinet/ip_var.h>
90 #include <netinet/tcp_var.h>
91 #ifdef TCPHPTS
92 #include <netinet/tcp_hpts.h>
93 #endif
94 #include <netinet/udp.h>
95 #include <netinet/udp_var.h>
96 #endif
97 #ifdef INET
98 #include <netinet/in_var.h>
99 #endif
100 #ifdef INET6
101 #include <netinet/ip6.h>
102 #include <netinet6/in6_pcb.h>
103 #include <netinet6/in6_var.h>
104 #include <netinet6/ip6_var.h>
105 #endif /* INET6 */
106
107 #include <netipsec/ipsec_support.h>
108
109 #include <security/mac/mac_framework.h>
110
111 #define INPCBLBGROUP_SIZMIN     8
112 #define INPCBLBGROUP_SIZMAX     256
113
114 static struct callout   ipport_tick_callout;
115
116 /*
117  * These configure the range of local port addresses assigned to
118  * "unspecified" outgoing connections/packets/whatever.
119  */
120 VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;    /* 1023 */
121 VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;    /* 600 */
122 VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;     /* 10000 */
123 VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;       /* 65535 */
124 VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;      /* 49152 */
125 VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;        /* 65535 */
126
127 /*
128  * Reserved ports accessible only to root. There are significant
129  * security considerations that must be accounted for when changing these,
130  * but the security benefits can be great. Please be careful.
131  */
132 VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;    /* 1023 */
133 VNET_DEFINE(int, ipport_reservedlow);
134
135 /* Variables dealing with random ephemeral port allocation. */
136 VNET_DEFINE(int, ipport_randomized) = 1;        /* user controlled via sysctl */
137 VNET_DEFINE(int, ipport_randomcps) = 10;        /* user controlled via sysctl */
138 VNET_DEFINE(int, ipport_randomtime) = 45;       /* user controlled via sysctl */
139 VNET_DEFINE(int, ipport_stoprandom);            /* toggled by ipport_tick */
140 VNET_DEFINE(int, ipport_tcpallocs);
141 VNET_DEFINE_STATIC(int, ipport_tcplastcount);
142
143 #define V_ipport_tcplastcount           VNET(ipport_tcplastcount)
144
145 static void     in_pcbremlists(struct inpcb *inp);
146 #ifdef INET
147 static struct inpcb     *in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
148                             struct in_addr faddr, u_int fport_arg,
149                             struct in_addr laddr, u_int lport_arg,
150                             int lookupflags, struct ifnet *ifp);
151
152 #define RANGECHK(var, min, max) \
153         if ((var) < (min)) { (var) = (min); } \
154         else if ((var) > (max)) { (var) = (max); }
155
156 static int
157 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
158 {
159         int error;
160
161         error = sysctl_handle_int(oidp, arg1, arg2, req);
162         if (error == 0) {
163                 RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
164                 RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
165                 RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
166                 RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
167                 RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
168                 RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
169         }
170         return (error);
171 }
172
173 #undef RANGECHK
174
175 static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0,
176     "IP Ports");
177
178 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
179         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
180         &VNET_NAME(ipport_lowfirstauto), 0, &sysctl_net_ipport_check, "I", "");
181 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
182         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
183         &VNET_NAME(ipport_lowlastauto), 0, &sysctl_net_ipport_check, "I", "");
184 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first,
185         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
186         &VNET_NAME(ipport_firstauto), 0, &sysctl_net_ipport_check, "I", "");
187 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last,
188         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
189         &VNET_NAME(ipport_lastauto), 0, &sysctl_net_ipport_check, "I", "");
190 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
191         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
192         &VNET_NAME(ipport_hifirstauto), 0, &sysctl_net_ipport_check, "I", "");
193 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
194         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
195         &VNET_NAME(ipport_hilastauto), 0, &sysctl_net_ipport_check, "I", "");
196 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
197         CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
198         &VNET_NAME(ipport_reservedhigh), 0, "");
199 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
200         CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
201 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomized,
202         CTLFLAG_VNET | CTLFLAG_RW,
203         &VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
204 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomcps,
205         CTLFLAG_VNET | CTLFLAG_RW,
206         &VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
207         "allocations before switching to a sequental one");
208 SYSCTL_INT(_net_inet_ip_portrange, OID_AUTO, randomtime,
209         CTLFLAG_VNET | CTLFLAG_RW,
210         &VNET_NAME(ipport_randomtime), 0,
211         "Minimum time to keep sequental port "
212         "allocation before switching to a random one");
213 #endif /* INET */
214
215 /*
216  * in_pcb.c: manage the Protocol Control Blocks.
217  *
218  * NOTE: It is assumed that most of these functions will be called with
219  * the pcbinfo lock held, and often, the inpcb lock held, as these utility
220  * functions often modify hash chains or addresses in pcbs.
221  */
222
223 static struct inpcblbgroup *
224 in_pcblbgroup_alloc(struct inpcblbgrouphead *hdr, u_char vflag,
225     uint16_t port, const union in_dependaddr *addr, int size)
226 {
227         struct inpcblbgroup *grp;
228         size_t bytes;
229
230         bytes = __offsetof(struct inpcblbgroup, il_inp[size]);
231         grp = malloc(bytes, M_PCB, M_ZERO | M_NOWAIT);
232         if (!grp)
233                 return (NULL);
234         grp->il_vflag = vflag;
235         grp->il_lport = port;
236         grp->il_dependladdr = *addr;
237         grp->il_inpsiz = size;
238         CK_LIST_INSERT_HEAD(hdr, grp, il_list);
239         return (grp);
240 }
241
242 static void
243 in_pcblbgroup_free_deferred(epoch_context_t ctx)
244 {
245         struct inpcblbgroup *grp;
246
247         grp = __containerof(ctx, struct inpcblbgroup, il_epoch_ctx);
248         free(grp, M_PCB);
249 }
250
251 static void
252 in_pcblbgroup_free(struct inpcblbgroup *grp)
253 {
254
255         CK_LIST_REMOVE(grp, il_list);
256         epoch_call(net_epoch_preempt, &grp->il_epoch_ctx,
257             in_pcblbgroup_free_deferred);
258 }
259
260 static struct inpcblbgroup *
261 in_pcblbgroup_resize(struct inpcblbgrouphead *hdr,
262     struct inpcblbgroup *old_grp, int size)
263 {
264         struct inpcblbgroup *grp;
265         int i;
266
267         grp = in_pcblbgroup_alloc(hdr, old_grp->il_vflag,
268             old_grp->il_lport, &old_grp->il_dependladdr, size);
269         if (grp == NULL)
270                 return (NULL);
271
272         KASSERT(old_grp->il_inpcnt < grp->il_inpsiz,
273             ("invalid new local group size %d and old local group count %d",
274              grp->il_inpsiz, old_grp->il_inpcnt));
275
276         for (i = 0; i < old_grp->il_inpcnt; ++i)
277                 grp->il_inp[i] = old_grp->il_inp[i];
278         grp->il_inpcnt = old_grp->il_inpcnt;
279         in_pcblbgroup_free(old_grp);
280         return (grp);
281 }
282
283 /*
284  * PCB at index 'i' is removed from the group. Pull up the ones below il_inp[i]
285  * and shrink group if possible.
286  */
287 static void
288 in_pcblbgroup_reorder(struct inpcblbgrouphead *hdr, struct inpcblbgroup **grpp,
289     int i)
290 {
291         struct inpcblbgroup *grp, *new_grp;
292
293         grp = *grpp;
294         for (; i + 1 < grp->il_inpcnt; ++i)
295                 grp->il_inp[i] = grp->il_inp[i + 1];
296         grp->il_inpcnt--;
297
298         if (grp->il_inpsiz > INPCBLBGROUP_SIZMIN &&
299             grp->il_inpcnt <= grp->il_inpsiz / 4) {
300                 /* Shrink this group. */
301                 new_grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz / 2);
302                 if (new_grp != NULL)
303                         *grpp = new_grp;
304         }
305 }
306
307 /*
308  * Add PCB to load balance group for SO_REUSEPORT_LB option.
309  */
310 static int
311 in_pcbinslbgrouphash(struct inpcb *inp)
312 {
313         const static struct timeval interval = { 60, 0 };
314         static struct timeval lastprint;
315         struct inpcbinfo *pcbinfo;
316         struct inpcblbgrouphead *hdr;
317         struct inpcblbgroup *grp;
318         uint32_t idx;
319
320         pcbinfo = inp->inp_pcbinfo;
321
322         INP_WLOCK_ASSERT(inp);
323         INP_HASH_WLOCK_ASSERT(pcbinfo);
324
325         if (pcbinfo->ipi_lbgrouphashbase == NULL)
326                 return (0);
327
328         /*
329          * Don't allow jailed socket to join local group.
330          */
331         if (inp->inp_socket != NULL && jailed(inp->inp_socket->so_cred))
332                 return (0);
333
334 #ifdef INET6
335         /*
336          * Don't allow IPv4 mapped INET6 wild socket.
337          */
338         if ((inp->inp_vflag & INP_IPV4) &&
339             inp->inp_laddr.s_addr == INADDR_ANY &&
340             INP_CHECK_SOCKAF(inp->inp_socket, AF_INET6)) {
341                 return (0);
342         }
343 #endif
344
345         idx = INP_PCBLBGROUP_PORTHASH(inp->inp_lport,
346             pcbinfo->ipi_lbgrouphashmask);
347         hdr = &pcbinfo->ipi_lbgrouphashbase[idx];
348         CK_LIST_FOREACH(grp, hdr, il_list) {
349                 if (grp->il_vflag == inp->inp_vflag &&
350                     grp->il_lport == inp->inp_lport &&
351                     memcmp(&grp->il_dependladdr,
352                     &inp->inp_inc.inc_ie.ie_dependladdr,
353                     sizeof(grp->il_dependladdr)) == 0)
354                         break;
355         }
356         if (grp == NULL) {
357                 /* Create new load balance group. */
358                 grp = in_pcblbgroup_alloc(hdr, inp->inp_vflag,
359                     inp->inp_lport, &inp->inp_inc.inc_ie.ie_dependladdr,
360                     INPCBLBGROUP_SIZMIN);
361                 if (grp == NULL)
362                         return (ENOBUFS);
363         } else if (grp->il_inpcnt == grp->il_inpsiz) {
364                 if (grp->il_inpsiz >= INPCBLBGROUP_SIZMAX) {
365                         if (ratecheck(&lastprint, &interval))
366                                 printf("lb group port %d, limit reached\n",
367                                     ntohs(grp->il_lport));
368                         return (0);
369                 }
370
371                 /* Expand this local group. */
372                 grp = in_pcblbgroup_resize(hdr, grp, grp->il_inpsiz * 2);
373                 if (grp == NULL)
374                         return (ENOBUFS);
375         }
376
377         KASSERT(grp->il_inpcnt < grp->il_inpsiz,
378             ("invalid local group size %d and count %d", grp->il_inpsiz,
379             grp->il_inpcnt));
380
381         grp->il_inp[grp->il_inpcnt] = inp;
382         grp->il_inpcnt++;
383         return (0);
384 }
385
386 /*
387  * Remove PCB from load balance group.
388  */
389 static void
390 in_pcbremlbgrouphash(struct inpcb *inp)
391 {
392         struct inpcbinfo *pcbinfo;
393         struct inpcblbgrouphead *hdr;
394         struct inpcblbgroup *grp;
395         int i;
396
397         pcbinfo = inp->inp_pcbinfo;
398
399         INP_WLOCK_ASSERT(inp);
400         INP_HASH_WLOCK_ASSERT(pcbinfo);
401
402         if (pcbinfo->ipi_lbgrouphashbase == NULL)
403                 return;
404
405         hdr = &pcbinfo->ipi_lbgrouphashbase[
406             INP_PCBLBGROUP_PORTHASH(inp->inp_lport,
407                 pcbinfo->ipi_lbgrouphashmask)];
408
409         CK_LIST_FOREACH(grp, hdr, il_list) {
410                 for (i = 0; i < grp->il_inpcnt; ++i) {
411                         if (grp->il_inp[i] != inp)
412                                 continue;
413
414                         if (grp->il_inpcnt == 1) {
415                                 /* We are the last, free this local group. */
416                                 in_pcblbgroup_free(grp);
417                         } else {
418                                 /* Pull up inpcbs, shrink group if possible. */
419                                 in_pcblbgroup_reorder(hdr, &grp, i);
420                         }
421                         return;
422                 }
423         }
424 }
425
426 /*
427  * Different protocols initialize their inpcbs differently - giving
428  * different name to the lock.  But they all are disposed the same.
429  */
430 static void
431 inpcb_fini(void *mem, int size)
432 {
433         struct inpcb *inp = mem;
434
435         INP_LOCK_DESTROY(inp);
436 }
437
438 /*
439  * Initialize an inpcbinfo -- we should be able to reduce the number of
440  * arguments in time.
441  */
442 void
443 in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
444     struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
445     char *inpcbzone_name, uma_init inpcbzone_init, u_int hashfields)
446 {
447
448         INP_INFO_LOCK_INIT(pcbinfo, name);
449         INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");     /* XXXRW: argument? */
450         INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
451 #ifdef VIMAGE
452         pcbinfo->ipi_vnet = curvnet;
453 #endif
454         pcbinfo->ipi_listhead = listhead;
455         CK_LIST_INIT(pcbinfo->ipi_listhead);
456         pcbinfo->ipi_count = 0;
457         pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
458             &pcbinfo->ipi_hashmask);
459         pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
460             &pcbinfo->ipi_porthashmask);
461         pcbinfo->ipi_lbgrouphashbase = hashinit(hash_nelements, M_PCB,
462             &pcbinfo->ipi_lbgrouphashmask);
463 #ifdef PCBGROUP
464         in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
465 #endif
466         pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
467             NULL, NULL, inpcbzone_init, inpcb_fini, UMA_ALIGN_PTR, 0);
468         uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
469         uma_zone_set_warning(pcbinfo->ipi_zone,
470             "kern.ipc.maxsockets limit reached");
471 }
472
473 /*
474  * Destroy an inpcbinfo.
475  */
476 void
477 in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
478 {
479
480         KASSERT(pcbinfo->ipi_count == 0,
481             ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
482
483         hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
484         hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
485             pcbinfo->ipi_porthashmask);
486         hashdestroy(pcbinfo->ipi_lbgrouphashbase, M_PCB,
487             pcbinfo->ipi_lbgrouphashmask);
488 #ifdef PCBGROUP
489         in_pcbgroup_destroy(pcbinfo);
490 #endif
491         uma_zdestroy(pcbinfo->ipi_zone);
492         INP_LIST_LOCK_DESTROY(pcbinfo);
493         INP_HASH_LOCK_DESTROY(pcbinfo);
494         INP_INFO_LOCK_DESTROY(pcbinfo);
495 }
496
497 /*
498  * Allocate a PCB and associate it with the socket.
499  * On success return with the PCB locked.
500  */
501 int
502 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
503 {
504         struct inpcb *inp;
505         int error;
506
507 #ifdef INVARIANTS
508         if (pcbinfo == &V_tcbinfo) {
509                 INP_INFO_RLOCK_ASSERT(pcbinfo);
510         } else {
511                 INP_INFO_WLOCK_ASSERT(pcbinfo);
512         }
513 #endif
514
515         error = 0;
516         inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
517         if (inp == NULL)
518                 return (ENOBUFS);
519         bzero(&inp->inp_start_zero, inp_zero_size);
520         inp->inp_pcbinfo = pcbinfo;
521         inp->inp_socket = so;
522         inp->inp_cred = crhold(so->so_cred);
523         inp->inp_inc.inc_fibnum = so->so_fibnum;
524 #ifdef MAC
525         error = mac_inpcb_init(inp, M_NOWAIT);
526         if (error != 0)
527                 goto out;
528         mac_inpcb_create(so, inp);
529 #endif
530 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
531         error = ipsec_init_pcbpolicy(inp);
532         if (error != 0) {
533 #ifdef MAC
534                 mac_inpcb_destroy(inp);
535 #endif
536                 goto out;
537         }
538 #endif /*IPSEC*/
539 #ifdef INET6
540         if (INP_SOCKAF(so) == AF_INET6) {
541                 inp->inp_vflag |= INP_IPV6PROTO;
542                 if (V_ip6_v6only)
543                         inp->inp_flags |= IN6P_IPV6_V6ONLY;
544         }
545 #endif
546         INP_WLOCK(inp);
547         INP_LIST_WLOCK(pcbinfo);
548         CK_LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
549         pcbinfo->ipi_count++;
550         so->so_pcb = (caddr_t)inp;
551 #ifdef INET6
552         if (V_ip6_auto_flowlabel)
553                 inp->inp_flags |= IN6P_AUTOFLOWLABEL;
554 #endif
555         inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
556         refcount_init(&inp->inp_refcount, 1);   /* Reference from inpcbinfo */
557
558         /*
559          * Routes in inpcb's can cache L2 as well; they are guaranteed
560          * to be cleaned up.
561          */
562         inp->inp_route.ro_flags = RT_LLE_CACHE;
563         INP_LIST_WUNLOCK(pcbinfo);
564 #if defined(IPSEC) || defined(IPSEC_SUPPORT) || defined(MAC)
565 out:
566         if (error != 0) {
567                 crfree(inp->inp_cred);
568                 uma_zfree(pcbinfo->ipi_zone, inp);
569         }
570 #endif
571         return (error);
572 }
573
574 #ifdef INET
575 int
576 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
577 {
578         int anonport, error;
579
580         INP_WLOCK_ASSERT(inp);
581         INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
582
583         if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
584                 return (EINVAL);
585         anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
586         error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
587             &inp->inp_lport, cred);
588         if (error)
589                 return (error);
590         if (in_pcbinshash(inp) != 0) {
591                 inp->inp_laddr.s_addr = INADDR_ANY;
592                 inp->inp_lport = 0;
593                 return (EAGAIN);
594         }
595         if (anonport)
596                 inp->inp_flags |= INP_ANONPORT;
597         return (0);
598 }
599 #endif
600
601 /*
602  * Select a local port (number) to use.
603  */
604 #if defined(INET) || defined(INET6)
605 int
606 in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
607     struct ucred *cred, int lookupflags)
608 {
609         struct inpcbinfo *pcbinfo;
610         struct inpcb *tmpinp;
611         unsigned short *lastport;
612         int count, dorandom, error;
613         u_short aux, first, last, lport;
614 #ifdef INET
615         struct in_addr laddr;
616 #endif
617
618         pcbinfo = inp->inp_pcbinfo;
619
620         /*
621          * Because no actual state changes occur here, a global write lock on
622          * the pcbinfo isn't required.
623          */
624         INP_LOCK_ASSERT(inp);
625         INP_HASH_LOCK_ASSERT(pcbinfo);
626
627         if (inp->inp_flags & INP_HIGHPORT) {
628                 first = V_ipport_hifirstauto;   /* sysctl */
629                 last  = V_ipport_hilastauto;
630                 lastport = &pcbinfo->ipi_lasthi;
631         } else if (inp->inp_flags & INP_LOWPORT) {
632                 error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
633                 if (error)
634                         return (error);
635                 first = V_ipport_lowfirstauto;  /* 1023 */
636                 last  = V_ipport_lowlastauto;   /* 600 */
637                 lastport = &pcbinfo->ipi_lastlow;
638         } else {
639                 first = V_ipport_firstauto;     /* sysctl */
640                 last  = V_ipport_lastauto;
641                 lastport = &pcbinfo->ipi_lastport;
642         }
643         /*
644          * For UDP(-Lite), use random port allocation as long as the user
645          * allows it.  For TCP (and as of yet unknown) connections,
646          * use random port allocation only if the user allows it AND
647          * ipport_tick() allows it.
648          */
649         if (V_ipport_randomized &&
650                 (!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
651                 pcbinfo == &V_ulitecbinfo))
652                 dorandom = 1;
653         else
654                 dorandom = 0;
655         /*
656          * It makes no sense to do random port allocation if
657          * we have the only port available.
658          */
659         if (first == last)
660                 dorandom = 0;
661         /* Make sure to not include UDP(-Lite) packets in the count. */
662         if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
663                 V_ipport_tcpallocs++;
664         /*
665          * Instead of having two loops further down counting up or down
666          * make sure that first is always <= last and go with only one
667          * code path implementing all logic.
668          */
669         if (first > last) {
670                 aux = first;
671                 first = last;
672                 last = aux;
673         }
674
675 #ifdef INET
676         /* Make the compiler happy. */
677         laddr.s_addr = 0;
678         if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
679                 KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
680                     __func__, inp));
681                 laddr = *laddrp;
682         }
683 #endif
684         tmpinp = NULL;  /* Make compiler happy. */
685         lport = *lportp;
686
687         if (dorandom)
688                 *lastport = first + (arc4random() % (last - first));
689
690         count = last - first;
691
692         do {
693                 if (count-- < 0)        /* completely used? */
694                         return (EADDRNOTAVAIL);
695                 ++*lastport;
696                 if (*lastport < first || *lastport > last)
697                         *lastport = first;
698                 lport = htons(*lastport);
699
700 #ifdef INET6
701                 if ((inp->inp_vflag & INP_IPV6) != 0)
702                         tmpinp = in6_pcblookup_local(pcbinfo,
703                             &inp->in6p_laddr, lport, lookupflags, cred);
704 #endif
705 #if defined(INET) && defined(INET6)
706                 else
707 #endif
708 #ifdef INET
709                         tmpinp = in_pcblookup_local(pcbinfo, laddr,
710                             lport, lookupflags, cred);
711 #endif
712         } while (tmpinp != NULL);
713
714 #ifdef INET
715         if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
716                 laddrp->s_addr = laddr.s_addr;
717 #endif
718         *lportp = lport;
719
720         return (0);
721 }
722
723 /*
724  * Return cached socket options.
725  */
726 int
727 inp_so_options(const struct inpcb *inp)
728 {
729         int so_options;
730
731         so_options = 0;
732
733         if ((inp->inp_flags2 & INP_REUSEPORT_LB) != 0)
734                 so_options |= SO_REUSEPORT_LB;
735         if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
736                 so_options |= SO_REUSEPORT;
737         if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
738                 so_options |= SO_REUSEADDR;
739         return (so_options);
740 }
741 #endif /* INET || INET6 */
742
743 /*
744  * Check if a new BINDMULTI socket is allowed to be created.
745  *
746  * ni points to the new inp.
747  * oi points to the exisitng inp.
748  *
749  * This checks whether the existing inp also has BINDMULTI and
750  * whether the credentials match.
751  */
752 int
753 in_pcbbind_check_bindmulti(const struct inpcb *ni, const struct inpcb *oi)
754 {
755         /* Check permissions match */
756         if ((ni->inp_flags2 & INP_BINDMULTI) &&
757             (ni->inp_cred->cr_uid !=
758             oi->inp_cred->cr_uid))
759                 return (0);
760
761         /* Check the existing inp has BINDMULTI set */
762         if ((ni->inp_flags2 & INP_BINDMULTI) &&
763             ((oi->inp_flags2 & INP_BINDMULTI) == 0))
764                 return (0);
765
766         /*
767          * We're okay - either INP_BINDMULTI isn't set on ni, or
768          * it is and it matches the checks.
769          */
770         return (1);
771 }
772
773 #ifdef INET
774 /*
775  * Set up a bind operation on a PCB, performing port allocation
776  * as required, but do not actually modify the PCB. Callers can
777  * either complete the bind by setting inp_laddr/inp_lport and
778  * calling in_pcbinshash(), or they can just use the resulting
779  * port and address to authorise the sending of a once-off packet.
780  *
781  * On error, the values of *laddrp and *lportp are not changed.
782  */
783 int
784 in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
785     u_short *lportp, struct ucred *cred)
786 {
787         struct socket *so = inp->inp_socket;
788         struct sockaddr_in *sin;
789         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
790         struct in_addr laddr;
791         u_short lport = 0;
792         int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
793         int error;
794
795         /*
796          * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
797          * so that we don't have to add to the (already messy) code below.
798          */
799         int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
800
801         /*
802          * No state changes, so read locks are sufficient here.
803          */
804         INP_LOCK_ASSERT(inp);
805         INP_HASH_LOCK_ASSERT(pcbinfo);
806
807         if (CK_STAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
808                 return (EADDRNOTAVAIL);
809         laddr.s_addr = *laddrp;
810         if (nam != NULL && laddr.s_addr != INADDR_ANY)
811                 return (EINVAL);
812         if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
813                 lookupflags = INPLOOKUP_WILDCARD;
814         if (nam == NULL) {
815                 if ((error = prison_local_ip4(cred, &laddr)) != 0)
816                         return (error);
817         } else {
818                 sin = (struct sockaddr_in *)nam;
819                 if (nam->sa_len != sizeof (*sin))
820                         return (EINVAL);
821 #ifdef notdef
822                 /*
823                  * We should check the family, but old programs
824                  * incorrectly fail to initialize it.
825                  */
826                 if (sin->sin_family != AF_INET)
827                         return (EAFNOSUPPORT);
828 #endif
829                 error = prison_local_ip4(cred, &sin->sin_addr);
830                 if (error)
831                         return (error);
832                 if (sin->sin_port != *lportp) {
833                         /* Don't allow the port to change. */
834                         if (*lportp != 0)
835                                 return (EINVAL);
836                         lport = sin->sin_port;
837                 }
838                 /* NB: lport is left as 0 if the port isn't being changed. */
839                 if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
840                         /*
841                          * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
842                          * allow complete duplication of binding if
843                          * SO_REUSEPORT is set, or if SO_REUSEADDR is set
844                          * and a multicast address is bound on both
845                          * new and duplicated sockets.
846                          */
847                         if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
848                                 reuseport = SO_REUSEADDR|SO_REUSEPORT;
849                         /*
850                          * XXX: How to deal with SO_REUSEPORT_LB here?
851                          * Treat same as SO_REUSEPORT for now.
852                          */
853                         if ((so->so_options &
854                             (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
855                                 reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
856                 } else if (sin->sin_addr.s_addr != INADDR_ANY) {
857                         sin->sin_port = 0;              /* yech... */
858                         bzero(&sin->sin_zero, sizeof(sin->sin_zero));
859                         /*
860                          * Is the address a local IP address?
861                          * If INP_BINDANY is set, then the socket may be bound
862                          * to any endpoint address, local or not.
863                          */
864                         if ((inp->inp_flags & INP_BINDANY) == 0 &&
865                             ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
866                                 return (EADDRNOTAVAIL);
867                 }
868                 laddr = sin->sin_addr;
869                 if (lport) {
870                         struct inpcb *t;
871                         struct tcptw *tw;
872
873                         /* GROSS */
874                         if (ntohs(lport) <= V_ipport_reservedhigh &&
875                             ntohs(lport) >= V_ipport_reservedlow &&
876                             priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
877                             0))
878                                 return (EACCES);
879                         if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
880                             priv_check_cred(inp->inp_cred,
881                             PRIV_NETINET_REUSEPORT, 0) != 0) {
882                                 t = in_pcblookup_local(pcbinfo, sin->sin_addr,
883                                     lport, INPLOOKUP_WILDCARD, cred);
884         /*
885          * XXX
886          * This entire block sorely needs a rewrite.
887          */
888                                 if (t &&
889                                     ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
890                                     ((t->inp_flags & INP_TIMEWAIT) == 0) &&
891                                     (so->so_type != SOCK_STREAM ||
892                                      ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
893                                     (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
894                                      ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
895                                      (t->inp_flags2 & INP_REUSEPORT) ||
896                                      (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
897                                     (inp->inp_cred->cr_uid !=
898                                      t->inp_cred->cr_uid))
899                                         return (EADDRINUSE);
900
901                                 /*
902                                  * If the socket is a BINDMULTI socket, then
903                                  * the credentials need to match and the
904                                  * original socket also has to have been bound
905                                  * with BINDMULTI.
906                                  */
907                                 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
908                                         return (EADDRINUSE);
909                         }
910                         t = in_pcblookup_local(pcbinfo, sin->sin_addr,
911                             lport, lookupflags, cred);
912                         if (t && (t->inp_flags & INP_TIMEWAIT)) {
913                                 /*
914                                  * XXXRW: If an incpb has had its timewait
915                                  * state recycled, we treat the address as
916                                  * being in use (for now).  This is better
917                                  * than a panic, but not desirable.
918                                  */
919                                 tw = intotw(t);
920                                 if (tw == NULL ||
921                                     ((reuseport & tw->tw_so_options) == 0 &&
922                                         (reuseport_lb &
923                                             tw->tw_so_options) == 0)) {
924                                         return (EADDRINUSE);
925                                 }
926                         } else if (t &&
927                                    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
928                                    (reuseport & inp_so_options(t)) == 0 &&
929                                    (reuseport_lb & inp_so_options(t)) == 0) {
930 #ifdef INET6
931                                 if (ntohl(sin->sin_addr.s_addr) !=
932                                     INADDR_ANY ||
933                                     ntohl(t->inp_laddr.s_addr) !=
934                                     INADDR_ANY ||
935                                     (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
936                                     (t->inp_vflag & INP_IPV6PROTO) == 0)
937 #endif
938                                                 return (EADDRINUSE);
939                                 if (t && (! in_pcbbind_check_bindmulti(inp, t)))
940                                         return (EADDRINUSE);
941                         }
942                 }
943         }
944         if (*lportp != 0)
945                 lport = *lportp;
946         if (lport == 0) {
947                 error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
948                 if (error != 0)
949                         return (error);
950
951         }
952         *laddrp = laddr.s_addr;
953         *lportp = lport;
954         return (0);
955 }
956
957 /*
958  * Connect from a socket to a specified address.
959  * Both address and port must be specified in argument sin.
960  * If don't have a local address for this socket yet,
961  * then pick one.
962  */
963 int
964 in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
965     struct ucred *cred, struct mbuf *m)
966 {
967         u_short lport, fport;
968         in_addr_t laddr, faddr;
969         int anonport, error;
970
971         INP_WLOCK_ASSERT(inp);
972         INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
973
974         lport = inp->inp_lport;
975         laddr = inp->inp_laddr.s_addr;
976         anonport = (lport == 0);
977         error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
978             NULL, cred);
979         if (error)
980                 return (error);
981
982         /* Do the initial binding of the local address if required. */
983         if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
984                 inp->inp_lport = lport;
985                 inp->inp_laddr.s_addr = laddr;
986                 if (in_pcbinshash(inp) != 0) {
987                         inp->inp_laddr.s_addr = INADDR_ANY;
988                         inp->inp_lport = 0;
989                         return (EAGAIN);
990                 }
991         }
992
993         /* Commit the remaining changes. */
994         inp->inp_lport = lport;
995         inp->inp_laddr.s_addr = laddr;
996         inp->inp_faddr.s_addr = faddr;
997         inp->inp_fport = fport;
998         in_pcbrehash_mbuf(inp, m);
999
1000         if (anonport)
1001                 inp->inp_flags |= INP_ANONPORT;
1002         return (0);
1003 }
1004
1005 int
1006 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
1007 {
1008
1009         return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
1010 }
1011
1012 /*
1013  * Do proper source address selection on an unbound socket in case
1014  * of connect. Take jails into account as well.
1015  */
1016 int
1017 in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
1018     struct ucred *cred)
1019 {
1020         struct ifaddr *ifa;
1021         struct sockaddr *sa;
1022         struct sockaddr_in *sin;
1023         struct route sro;
1024         int error;
1025
1026         KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
1027         /*
1028          * Bypass source address selection and use the primary jail IP
1029          * if requested.
1030          */
1031         if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
1032                 return (0);
1033
1034         error = 0;
1035         bzero(&sro, sizeof(sro));
1036
1037         sin = (struct sockaddr_in *)&sro.ro_dst;
1038         sin->sin_family = AF_INET;
1039         sin->sin_len = sizeof(struct sockaddr_in);
1040         sin->sin_addr.s_addr = faddr->s_addr;
1041
1042         /*
1043          * If route is known our src addr is taken from the i/f,
1044          * else punt.
1045          *
1046          * Find out route to destination.
1047          */
1048         if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
1049                 in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
1050
1051         /*
1052          * If we found a route, use the address corresponding to
1053          * the outgoing interface.
1054          * 
1055          * Otherwise assume faddr is reachable on a directly connected
1056          * network and try to find a corresponding interface to take
1057          * the source address from.
1058          */
1059         NET_EPOCH_ENTER();
1060         if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
1061                 struct in_ifaddr *ia;
1062                 struct ifnet *ifp;
1063
1064                 ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin,
1065                                         inp->inp_socket->so_fibnum));
1066                 if (ia == NULL) {
1067                         ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0,
1068                                                 inp->inp_socket->so_fibnum));
1069
1070                 }
1071                 if (ia == NULL) {
1072                         error = ENETUNREACH;
1073                         goto done;
1074                 }
1075
1076                 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1077                         laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1078                         goto done;
1079                 }
1080
1081                 ifp = ia->ia_ifp;
1082                 ia = NULL;
1083                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1084
1085                         sa = ifa->ifa_addr;
1086                         if (sa->sa_family != AF_INET)
1087                                 continue;
1088                         sin = (struct sockaddr_in *)sa;
1089                         if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1090                                 ia = (struct in_ifaddr *)ifa;
1091                                 break;
1092                         }
1093                 }
1094                 if (ia != NULL) {
1095                         laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1096                         goto done;
1097                 }
1098
1099                 /* 3. As a last resort return the 'default' jail address. */
1100                 error = prison_get_ip4(cred, laddr);
1101                 goto done;
1102         }
1103
1104         /*
1105          * If the outgoing interface on the route found is not
1106          * a loopback interface, use the address from that interface.
1107          * In case of jails do those three steps:
1108          * 1. check if the interface address belongs to the jail. If so use it.
1109          * 2. check if we have any address on the outgoing interface
1110          *    belonging to this jail. If so use it.
1111          * 3. as a last resort return the 'default' jail address.
1112          */
1113         if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
1114                 struct in_ifaddr *ia;
1115                 struct ifnet *ifp;
1116
1117                 /* If not jailed, use the default returned. */
1118                 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1119                         ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
1120                         laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1121                         goto done;
1122                 }
1123
1124                 /* Jailed. */
1125                 /* 1. Check if the iface address belongs to the jail. */
1126                 sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
1127                 if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1128                         ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
1129                         laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1130                         goto done;
1131                 }
1132
1133                 /*
1134                  * 2. Check if we have any address on the outgoing interface
1135                  *    belonging to this jail.
1136                  */
1137                 ia = NULL;
1138                 ifp = sro.ro_rt->rt_ifp;
1139                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1140                         sa = ifa->ifa_addr;
1141                         if (sa->sa_family != AF_INET)
1142                                 continue;
1143                         sin = (struct sockaddr_in *)sa;
1144                         if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
1145                                 ia = (struct in_ifaddr *)ifa;
1146                                 break;
1147                         }
1148                 }
1149                 if (ia != NULL) {
1150                         laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1151                         goto done;
1152                 }
1153
1154                 /* 3. As a last resort return the 'default' jail address. */
1155                 error = prison_get_ip4(cred, laddr);
1156                 goto done;
1157         }
1158
1159         /*
1160          * The outgoing interface is marked with 'loopback net', so a route
1161          * to ourselves is here.
1162          * Try to find the interface of the destination address and then
1163          * take the address from there. That interface is not necessarily
1164          * a loopback interface.
1165          * In case of jails, check that it is an address of the jail
1166          * and if we cannot find, fall back to the 'default' jail address.
1167          */
1168         if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
1169                 struct sockaddr_in sain;
1170                 struct in_ifaddr *ia;
1171
1172                 bzero(&sain, sizeof(struct sockaddr_in));
1173                 sain.sin_family = AF_INET;
1174                 sain.sin_len = sizeof(struct sockaddr_in);
1175                 sain.sin_addr.s_addr = faddr->s_addr;
1176
1177                 ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain),
1178                                         inp->inp_socket->so_fibnum));
1179                 if (ia == NULL)
1180                         ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0,
1181                                                 inp->inp_socket->so_fibnum));
1182                 if (ia == NULL)
1183                         ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
1184
1185                 if (cred == NULL || !prison_flag(cred, PR_IP4)) {
1186                         if (ia == NULL) {
1187                                 error = ENETUNREACH;
1188                                 goto done;
1189                         }
1190                         laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1191                         goto done;
1192                 }
1193
1194                 /* Jailed. */
1195                 if (ia != NULL) {
1196                         struct ifnet *ifp;
1197
1198                         ifp = ia->ia_ifp;
1199                         ia = NULL;
1200                         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1201                                 sa = ifa->ifa_addr;
1202                                 if (sa->sa_family != AF_INET)
1203                                         continue;
1204                                 sin = (struct sockaddr_in *)sa;
1205                                 if (prison_check_ip4(cred,
1206                                     &sin->sin_addr) == 0) {
1207                                         ia = (struct in_ifaddr *)ifa;
1208                                         break;
1209                                 }
1210                         }
1211                         if (ia != NULL) {
1212                                 laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
1213                                 goto done;
1214                         }
1215                 }
1216
1217                 /* 3. As a last resort return the 'default' jail address. */
1218                 error = prison_get_ip4(cred, laddr);
1219                 goto done;
1220         }
1221
1222 done:
1223         NET_EPOCH_EXIT();
1224         if (sro.ro_rt != NULL)
1225                 RTFREE(sro.ro_rt);
1226         return (error);
1227 }
1228
1229 /*
1230  * Set up for a connect from a socket to the specified address.
1231  * On entry, *laddrp and *lportp should contain the current local
1232  * address and port for the PCB; these are updated to the values
1233  * that should be placed in inp_laddr and inp_lport to complete
1234  * the connect.
1235  *
1236  * On success, *faddrp and *fportp will be set to the remote address
1237  * and port. These are not updated in the error case.
1238  *
1239  * If the operation fails because the connection already exists,
1240  * *oinpp will be set to the PCB of that connection so that the
1241  * caller can decide to override it. In all other cases, *oinpp
1242  * is set to NULL.
1243  */
1244 int
1245 in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
1246     in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
1247     struct inpcb **oinpp, struct ucred *cred)
1248 {
1249         struct rm_priotracker in_ifa_tracker;
1250         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1251         struct in_ifaddr *ia;
1252         struct inpcb *oinp;
1253         struct in_addr laddr, faddr;
1254         u_short lport, fport;
1255         int error;
1256
1257         /*
1258          * Because a global state change doesn't actually occur here, a read
1259          * lock is sufficient.
1260          */
1261         INP_LOCK_ASSERT(inp);
1262         INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
1263
1264         if (oinpp != NULL)
1265                 *oinpp = NULL;
1266         if (nam->sa_len != sizeof (*sin))
1267                 return (EINVAL);
1268         if (sin->sin_family != AF_INET)
1269                 return (EAFNOSUPPORT);
1270         if (sin->sin_port == 0)
1271                 return (EADDRNOTAVAIL);
1272         laddr.s_addr = *laddrp;
1273         lport = *lportp;
1274         faddr = sin->sin_addr;
1275         fport = sin->sin_port;
1276
1277         if (!CK_STAILQ_EMPTY(&V_in_ifaddrhead)) {
1278                 /*
1279                  * If the destination address is INADDR_ANY,
1280                  * use the primary local address.
1281                  * If the supplied address is INADDR_BROADCAST,
1282                  * and the primary interface supports broadcast,
1283                  * choose the broadcast address for that interface.
1284                  */
1285                 if (faddr.s_addr == INADDR_ANY) {
1286                         IN_IFADDR_RLOCK(&in_ifa_tracker);
1287                         faddr =
1288                             IA_SIN(CK_STAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
1289                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1290                         if (cred != NULL &&
1291                             (error = prison_get_ip4(cred, &faddr)) != 0)
1292                                 return (error);
1293                 } else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
1294                         IN_IFADDR_RLOCK(&in_ifa_tracker);
1295                         if (CK_STAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
1296                             IFF_BROADCAST)
1297                                 faddr = satosin(&CK_STAILQ_FIRST(
1298                                     &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
1299                         IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1300                 }
1301         }
1302         if (laddr.s_addr == INADDR_ANY) {
1303                 error = in_pcbladdr(inp, &faddr, &laddr, cred);
1304                 /*
1305                  * If the destination address is multicast and an outgoing
1306                  * interface has been set as a multicast option, prefer the
1307                  * address of that interface as our source address.
1308                  */
1309                 if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1310                     inp->inp_moptions != NULL) {
1311                         struct ip_moptions *imo;
1312                         struct ifnet *ifp;
1313
1314                         imo = inp->inp_moptions;
1315                         if (imo->imo_multicast_ifp != NULL) {
1316                                 ifp = imo->imo_multicast_ifp;
1317                                 IN_IFADDR_RLOCK(&in_ifa_tracker);
1318                                 CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1319                                         if ((ia->ia_ifp == ifp) &&
1320                                             (cred == NULL ||
1321                                             prison_check_ip4(cred,
1322                                             &ia->ia_addr.sin_addr) == 0))
1323                                                 break;
1324                                 }
1325                                 if (ia == NULL)
1326                                         error = EADDRNOTAVAIL;
1327                                 else {
1328                                         laddr = ia->ia_addr.sin_addr;
1329                                         error = 0;
1330                                 }
1331                                 IN_IFADDR_RUNLOCK(&in_ifa_tracker);
1332                         }
1333                 }
1334                 if (error)
1335                         return (error);
1336         }
1337         oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1338             laddr, lport, 0, NULL);
1339         if (oinp != NULL) {
1340                 if (oinpp != NULL)
1341                         *oinpp = oinp;
1342                 return (EADDRINUSE);
1343         }
1344         if (lport == 0) {
1345                 error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1346                     cred);
1347                 if (error)
1348                         return (error);
1349         }
1350         *laddrp = laddr.s_addr;
1351         *lportp = lport;
1352         *faddrp = faddr.s_addr;
1353         *fportp = fport;
1354         return (0);
1355 }
1356
1357 void
1358 in_pcbdisconnect(struct inpcb *inp)
1359 {
1360
1361         INP_WLOCK_ASSERT(inp);
1362         INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1363
1364         inp->inp_faddr.s_addr = INADDR_ANY;
1365         inp->inp_fport = 0;
1366         in_pcbrehash(inp);
1367 }
1368 #endif /* INET */
1369
1370 /*
1371  * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1372  * For most protocols, this will be invoked immediately prior to calling
1373  * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
1374  * socket, in which case in_pcbfree() is deferred.
1375  */
1376 void
1377 in_pcbdetach(struct inpcb *inp)
1378 {
1379
1380         KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1381
1382 #ifdef RATELIMIT
1383         if (inp->inp_snd_tag != NULL)
1384                 in_pcbdetach_txrtlmt(inp);
1385 #endif
1386         inp->inp_socket->so_pcb = NULL;
1387         inp->inp_socket = NULL;
1388 }
1389
1390 /*
1391  * in_pcbref() bumps the reference count on an inpcb in order to maintain
1392  * stability of an inpcb pointer despite the inpcb lock being released.  This
1393  * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1394  * but where the inpcb lock may already held, or when acquiring a reference
1395  * via a pcbgroup.
1396  *
1397  * in_pcbref() should be used only to provide brief memory stability, and
1398  * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1399  * garbage collect the inpcb if it has been in_pcbfree()'d from another
1400  * context.  Until in_pcbrele() has returned that the inpcb is still valid,
1401  * lock and rele are the *only* safe operations that may be performed on the
1402  * inpcb.
1403  *
1404  * While the inpcb will not be freed, releasing the inpcb lock means that the
1405  * connection's state may change, so the caller should be careful to
1406  * revalidate any cached state on reacquiring the lock.  Drop the reference
1407  * using in_pcbrele().
1408  */
1409 void
1410 in_pcbref(struct inpcb *inp)
1411 {
1412
1413         KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1414
1415         refcount_acquire(&inp->inp_refcount);
1416 }
1417
1418 /*
1419  * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1420  * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1421  * return a flag indicating whether or not the inpcb remains valid.  If it is
1422  * valid, we return with the inpcb lock held.
1423  *
1424  * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1425  * reference on an inpcb.  Historically more work was done here (actually, in
1426  * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1427  * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
1428  * about memory stability (and continued use of the write lock).
1429  */
1430 int
1431 in_pcbrele_rlocked(struct inpcb *inp)
1432 {
1433         struct inpcbinfo *pcbinfo;
1434
1435         KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1436
1437         INP_RLOCK_ASSERT(inp);
1438
1439         if (refcount_release(&inp->inp_refcount) == 0) {
1440                 /*
1441                  * If the inpcb has been freed, let the caller know, even if
1442                  * this isn't the last reference.
1443                  */
1444                 if (inp->inp_flags2 & INP_FREED) {
1445                         INP_RUNLOCK(inp);
1446                         return (1);
1447                 }
1448                 return (0);
1449         }
1450         
1451         KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1452 #ifdef TCPHPTS
1453         if (inp->inp_in_hpts || inp->inp_in_input) {
1454                 struct tcp_hpts_entry *hpts;
1455                 /*
1456                  * We should not be on the hpts at 
1457                  * this point in any form. we must
1458                  * get the lock to be sure.
1459                  */
1460                 hpts = tcp_hpts_lock(inp);
1461                 if (inp->inp_in_hpts)
1462                         panic("Hpts:%p inp:%p at free still on hpts",
1463                               hpts, inp);
1464                 mtx_unlock(&hpts->p_mtx);
1465                 hpts = tcp_input_lock(inp);
1466                 if (inp->inp_in_input) 
1467                         panic("Hpts:%p inp:%p at free still on input hpts",
1468                               hpts, inp);
1469                 mtx_unlock(&hpts->p_mtx);
1470         }
1471 #endif
1472         INP_RUNLOCK(inp);
1473         pcbinfo = inp->inp_pcbinfo;
1474         uma_zfree(pcbinfo->ipi_zone, inp);
1475         return (1);
1476 }
1477
1478 int
1479 in_pcbrele_wlocked(struct inpcb *inp)
1480 {
1481         struct inpcbinfo *pcbinfo;
1482
1483         KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1484
1485         INP_WLOCK_ASSERT(inp);
1486
1487         if (refcount_release(&inp->inp_refcount) == 0) {
1488                 /*
1489                  * If the inpcb has been freed, let the caller know, even if
1490                  * this isn't the last reference.
1491                  */
1492                 if (inp->inp_flags2 & INP_FREED) {
1493                         INP_WUNLOCK(inp);
1494                         return (1);
1495                 }
1496                 return (0);
1497         }
1498
1499         KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1500 #ifdef TCPHPTS
1501         if (inp->inp_in_hpts || inp->inp_in_input) {
1502                 struct tcp_hpts_entry *hpts;
1503                 /*
1504                  * We should not be on the hpts at 
1505                  * this point in any form. we must
1506                  * get the lock to be sure.
1507                  */
1508                 hpts = tcp_hpts_lock(inp);
1509                 if (inp->inp_in_hpts)
1510                         panic("Hpts:%p inp:%p at free still on hpts",
1511                               hpts, inp);
1512                 mtx_unlock(&hpts->p_mtx);
1513                 hpts = tcp_input_lock(inp);
1514                 if (inp->inp_in_input) 
1515                         panic("Hpts:%p inp:%p at free still on input hpts",
1516                               hpts, inp);
1517                 mtx_unlock(&hpts->p_mtx);
1518         }
1519 #endif
1520         INP_WUNLOCK(inp);
1521         pcbinfo = inp->inp_pcbinfo;
1522         uma_zfree(pcbinfo->ipi_zone, inp);
1523         return (1);
1524 }
1525
1526 /*
1527  * Temporary wrapper.
1528  */
1529 int
1530 in_pcbrele(struct inpcb *inp)
1531 {
1532
1533         return (in_pcbrele_wlocked(inp));
1534 }
1535
1536 void
1537 in_pcblist_rele_rlocked(epoch_context_t ctx)
1538 {
1539         struct in_pcblist *il;
1540         struct inpcb *inp;
1541         struct inpcbinfo *pcbinfo;
1542         int i, n;
1543
1544         il = __containerof(ctx, struct in_pcblist, il_epoch_ctx);
1545         pcbinfo = il->il_pcbinfo;
1546         n = il->il_count;
1547         INP_INFO_WLOCK(pcbinfo);
1548         for (i = 0; i < n; i++) {
1549                 inp = il->il_inp_list[i];
1550                 INP_RLOCK(inp);
1551                 if (!in_pcbrele_rlocked(inp))
1552                         INP_RUNLOCK(inp);
1553         }
1554         INP_INFO_WUNLOCK(pcbinfo);
1555         free(il, M_TEMP);
1556 }
1557
1558 static void
1559 inpcbport_free(epoch_context_t ctx)
1560 {
1561         struct inpcbport *phd;
1562
1563         phd = __containerof(ctx, struct inpcbport, phd_epoch_ctx);
1564         free(phd, M_PCB);
1565 }
1566
1567 static void
1568 in_pcbfree_deferred(epoch_context_t ctx)
1569 {
1570         struct inpcb *inp;
1571         int released __unused;
1572
1573         inp = __containerof(ctx, struct inpcb, inp_epoch_ctx);
1574
1575         INP_WLOCK(inp);
1576 #ifdef INET
1577         struct ip_moptions *imo = inp->inp_moptions;
1578         inp->inp_moptions = NULL;
1579 #endif
1580         /* XXXRW: Do as much as possible here. */
1581 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1582         if (inp->inp_sp != NULL)
1583                 ipsec_delete_pcbpolicy(inp);
1584 #endif
1585 #ifdef INET6
1586         struct ip6_moptions *im6o = NULL;
1587         if (inp->inp_vflag & INP_IPV6PROTO) {
1588                 ip6_freepcbopts(inp->in6p_outputopts);
1589                 im6o = inp->in6p_moptions;
1590                 inp->in6p_moptions = NULL;
1591         }
1592 #endif
1593         if (inp->inp_options)
1594                 (void)m_free(inp->inp_options);
1595         inp->inp_vflag = 0;
1596         crfree(inp->inp_cred);
1597 #ifdef MAC
1598         mac_inpcb_destroy(inp);
1599 #endif
1600         released = in_pcbrele_wlocked(inp);
1601         MPASS(released);
1602 #ifdef INET6
1603         ip6_freemoptions(im6o);
1604 #endif
1605 #ifdef INET
1606         inp_freemoptions(imo);
1607 #endif  
1608 }
1609
1610 /*
1611  * Unconditionally schedule an inpcb to be freed by decrementing its
1612  * reference count, which should occur only after the inpcb has been detached
1613  * from its socket.  If another thread holds a temporary reference (acquired
1614  * using in_pcbref()) then the free is deferred until that reference is
1615  * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
1616  * work, including removal from global lists, is done in this context, where
1617  * the pcbinfo lock is held.
1618  */
1619 void
1620 in_pcbfree(struct inpcb *inp)
1621 {
1622         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1623
1624         KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1625         KASSERT((inp->inp_flags2 & INP_FREED) == 0,
1626             ("%s: called twice for pcb %p", __func__, inp));
1627         if (inp->inp_flags2 & INP_FREED) {
1628                 INP_WUNLOCK(inp);
1629                 return;
1630         }
1631
1632 #ifdef INVARIANTS
1633         if (pcbinfo == &V_tcbinfo) {
1634                 INP_INFO_LOCK_ASSERT(pcbinfo);
1635         } else {
1636                 INP_INFO_WLOCK_ASSERT(pcbinfo);
1637         }
1638 #endif
1639         INP_WLOCK_ASSERT(inp);
1640         INP_LIST_WLOCK(pcbinfo);
1641         in_pcbremlists(inp);
1642         INP_LIST_WUNLOCK(pcbinfo);
1643         RO_INVALIDATE_CACHE(&inp->inp_route);
1644         /* mark as destruction in progress */
1645         inp->inp_flags2 |= INP_FREED;
1646         INP_WUNLOCK(inp);
1647         epoch_call(net_epoch_preempt, &inp->inp_epoch_ctx, in_pcbfree_deferred);
1648 }
1649
1650 /*
1651  * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1652  * port reservation, and preventing it from being returned by inpcb lookups.
1653  *
1654  * It is used by TCP to mark an inpcb as unused and avoid future packet
1655  * delivery or event notification when a socket remains open but TCP has
1656  * closed.  This might occur as a result of a shutdown()-initiated TCP close
1657  * or a RST on the wire, and allows the port binding to be reused while still
1658  * maintaining the invariant that so_pcb always points to a valid inpcb until
1659  * in_pcbdetach().
1660  *
1661  * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1662  * in_pcbnotifyall() and in_pcbpurgeif0()?
1663  */
1664 void
1665 in_pcbdrop(struct inpcb *inp)
1666 {
1667
1668         INP_WLOCK_ASSERT(inp);
1669 #ifdef INVARIANTS
1670         if (inp->inp_socket != NULL && inp->inp_ppcb != NULL)
1671                 MPASS(inp->inp_refcount > 1);
1672 #endif
1673
1674         /*
1675          * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1676          * the hash lock...?
1677          */
1678         inp->inp_flags |= INP_DROPPED;
1679         if (inp->inp_flags & INP_INHASHLIST) {
1680                 struct inpcbport *phd = inp->inp_phd;
1681
1682                 INP_HASH_WLOCK(inp->inp_pcbinfo);
1683                 in_pcbremlbgrouphash(inp);
1684                 CK_LIST_REMOVE(inp, inp_hash);
1685                 CK_LIST_REMOVE(inp, inp_portlist);
1686                 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
1687                         CK_LIST_REMOVE(phd, phd_hash);
1688                         epoch_call(net_epoch_preempt, &phd->phd_epoch_ctx, inpcbport_free);
1689                 }
1690                 INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1691                 inp->inp_flags &= ~INP_INHASHLIST;
1692 #ifdef PCBGROUP
1693                 in_pcbgroup_remove(inp);
1694 #endif
1695         }
1696 }
1697
1698 #ifdef INET
1699 /*
1700  * Common routines to return the socket addresses associated with inpcbs.
1701  */
1702 struct sockaddr *
1703 in_sockaddr(in_port_t port, struct in_addr *addr_p)
1704 {
1705         struct sockaddr_in *sin;
1706
1707         sin = malloc(sizeof *sin, M_SONAME,
1708                 M_WAITOK | M_ZERO);
1709         sin->sin_family = AF_INET;
1710         sin->sin_len = sizeof(*sin);
1711         sin->sin_addr = *addr_p;
1712         sin->sin_port = port;
1713
1714         return (struct sockaddr *)sin;
1715 }
1716
1717 int
1718 in_getsockaddr(struct socket *so, struct sockaddr **nam)
1719 {
1720         struct inpcb *inp;
1721         struct in_addr addr;
1722         in_port_t port;
1723
1724         inp = sotoinpcb(so);
1725         KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1726
1727         INP_RLOCK(inp);
1728         port = inp->inp_lport;
1729         addr = inp->inp_laddr;
1730         INP_RUNLOCK(inp);
1731
1732         *nam = in_sockaddr(port, &addr);
1733         return 0;
1734 }
1735
1736 int
1737 in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1738 {
1739         struct inpcb *inp;
1740         struct in_addr addr;
1741         in_port_t port;
1742
1743         inp = sotoinpcb(so);
1744         KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1745
1746         INP_RLOCK(inp);
1747         port = inp->inp_fport;
1748         addr = inp->inp_faddr;
1749         INP_RUNLOCK(inp);
1750
1751         *nam = in_sockaddr(port, &addr);
1752         return 0;
1753 }
1754
1755 void
1756 in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1757     struct inpcb *(*notify)(struct inpcb *, int))
1758 {
1759         struct inpcb *inp, *inp_temp;
1760
1761         INP_INFO_WLOCK(pcbinfo);
1762         CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1763                 INP_WLOCK(inp);
1764 #ifdef INET6
1765                 if ((inp->inp_vflag & INP_IPV4) == 0) {
1766                         INP_WUNLOCK(inp);
1767                         continue;
1768                 }
1769 #endif
1770                 if (inp->inp_faddr.s_addr != faddr.s_addr ||
1771                     inp->inp_socket == NULL) {
1772                         INP_WUNLOCK(inp);
1773                         continue;
1774                 }
1775                 if ((*notify)(inp, errno))
1776                         INP_WUNLOCK(inp);
1777         }
1778         INP_INFO_WUNLOCK(pcbinfo);
1779 }
1780
1781 void
1782 in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1783 {
1784         struct inpcb *inp;
1785         struct ip_moptions *imo;
1786         int i, gap;
1787
1788         INP_INFO_WLOCK(pcbinfo);
1789         CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1790                 INP_WLOCK(inp);
1791                 imo = inp->inp_moptions;
1792                 if ((inp->inp_vflag & INP_IPV4) &&
1793                     imo != NULL) {
1794                         /*
1795                          * Unselect the outgoing interface if it is being
1796                          * detached.
1797                          */
1798                         if (imo->imo_multicast_ifp == ifp)
1799                                 imo->imo_multicast_ifp = NULL;
1800
1801                         /*
1802                          * Drop multicast group membership if we joined
1803                          * through the interface being detached.
1804                          *
1805                          * XXX This can all be deferred to an epoch_call
1806                          */
1807                         for (i = 0, gap = 0; i < imo->imo_num_memberships;
1808                             i++) {
1809                                 if (imo->imo_membership[i]->inm_ifp == ifp) {
1810                                         IN_MULTI_LOCK_ASSERT();
1811                                         in_leavegroup_locked(imo->imo_membership[i], NULL);
1812                                         gap++;
1813                                 } else if (gap != 0)
1814                                         imo->imo_membership[i - gap] =
1815                                             imo->imo_membership[i];
1816                         }
1817                         imo->imo_num_memberships -= gap;
1818                 }
1819                 INP_WUNLOCK(inp);
1820         }
1821         INP_INFO_WUNLOCK(pcbinfo);
1822 }
1823
1824 /*
1825  * Lookup a PCB based on the local address and port.  Caller must hold the
1826  * hash lock.  No inpcb locks or references are acquired.
1827  */
1828 #define INP_LOOKUP_MAPPED_PCB_COST      3
1829 struct inpcb *
1830 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1831     u_short lport, int lookupflags, struct ucred *cred)
1832 {
1833         struct inpcb *inp;
1834 #ifdef INET6
1835         int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1836 #else
1837         int matchwild = 3;
1838 #endif
1839         int wildcard;
1840
1841         KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1842             ("%s: invalid lookup flags %d", __func__, lookupflags));
1843
1844         INP_HASH_LOCK_ASSERT(pcbinfo);
1845
1846         if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1847                 struct inpcbhead *head;
1848                 /*
1849                  * Look for an unconnected (wildcard foreign addr) PCB that
1850                  * matches the local address and port we're looking for.
1851                  */
1852                 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1853                     0, pcbinfo->ipi_hashmask)];
1854                 CK_LIST_FOREACH(inp, head, inp_hash) {
1855 #ifdef INET6
1856                         /* XXX inp locking */
1857                         if ((inp->inp_vflag & INP_IPV4) == 0)
1858                                 continue;
1859 #endif
1860                         if (inp->inp_faddr.s_addr == INADDR_ANY &&
1861                             inp->inp_laddr.s_addr == laddr.s_addr &&
1862                             inp->inp_lport == lport) {
1863                                 /*
1864                                  * Found?
1865                                  */
1866                                 if (cred == NULL ||
1867                                     prison_equal_ip4(cred->cr_prison,
1868                                         inp->inp_cred->cr_prison))
1869                                         return (inp);
1870                         }
1871                 }
1872                 /*
1873                  * Not found.
1874                  */
1875                 return (NULL);
1876         } else {
1877                 struct inpcbporthead *porthash;
1878                 struct inpcbport *phd;
1879                 struct inpcb *match = NULL;
1880                 /*
1881                  * Best fit PCB lookup.
1882                  *
1883                  * First see if this local port is in use by looking on the
1884                  * port hash list.
1885                  */
1886                 porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1887                     pcbinfo->ipi_porthashmask)];
1888                 CK_LIST_FOREACH(phd, porthash, phd_hash) {
1889                         if (phd->phd_port == lport)
1890                                 break;
1891                 }
1892                 if (phd != NULL) {
1893                         /*
1894                          * Port is in use by one or more PCBs. Look for best
1895                          * fit.
1896                          */
1897                         CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1898                                 wildcard = 0;
1899                                 if (cred != NULL &&
1900                                     !prison_equal_ip4(inp->inp_cred->cr_prison,
1901                                         cred->cr_prison))
1902                                         continue;
1903 #ifdef INET6
1904                                 /* XXX inp locking */
1905                                 if ((inp->inp_vflag & INP_IPV4) == 0)
1906                                         continue;
1907                                 /*
1908                                  * We never select the PCB that has
1909                                  * INP_IPV6 flag and is bound to :: if
1910                                  * we have another PCB which is bound
1911                                  * to 0.0.0.0.  If a PCB has the
1912                                  * INP_IPV6 flag, then we set its cost
1913                                  * higher than IPv4 only PCBs.
1914                                  *
1915                                  * Note that the case only happens
1916                                  * when a socket is bound to ::, under
1917                                  * the condition that the use of the
1918                                  * mapped address is allowed.
1919                                  */
1920                                 if ((inp->inp_vflag & INP_IPV6) != 0)
1921                                         wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1922 #endif
1923                                 if (inp->inp_faddr.s_addr != INADDR_ANY)
1924                                         wildcard++;
1925                                 if (inp->inp_laddr.s_addr != INADDR_ANY) {
1926                                         if (laddr.s_addr == INADDR_ANY)
1927                                                 wildcard++;
1928                                         else if (inp->inp_laddr.s_addr != laddr.s_addr)
1929                                                 continue;
1930                                 } else {
1931                                         if (laddr.s_addr != INADDR_ANY)
1932                                                 wildcard++;
1933                                 }
1934                                 if (wildcard < matchwild) {
1935                                         match = inp;
1936                                         matchwild = wildcard;
1937                                         if (matchwild == 0)
1938                                                 break;
1939                                 }
1940                         }
1941                 }
1942                 return (match);
1943         }
1944 }
1945 #undef INP_LOOKUP_MAPPED_PCB_COST
1946
1947 static struct inpcb *
1948 in_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
1949     const struct in_addr *laddr, uint16_t lport, const struct in_addr *faddr,
1950     uint16_t fport, int lookupflags)
1951 {
1952         struct inpcb *local_wild;
1953         const struct inpcblbgrouphead *hdr;
1954         struct inpcblbgroup *grp;
1955         uint32_t idx;
1956
1957         INP_HASH_LOCK_ASSERT(pcbinfo);
1958
1959         hdr = &pcbinfo->ipi_lbgrouphashbase[INP_PCBLBGROUP_PORTHASH(lport,
1960             pcbinfo->ipi_lbgrouphashmask)];
1961
1962         /*
1963          * Order of socket selection:
1964          * 1. non-wild.
1965          * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
1966          *
1967          * NOTE:
1968          * - Load balanced group does not contain jailed sockets
1969          * - Load balanced group does not contain IPv4 mapped INET6 wild sockets
1970          */
1971         local_wild = NULL;
1972         CK_LIST_FOREACH(grp, hdr, il_list) {
1973 #ifdef INET6
1974                 if (!(grp->il_vflag & INP_IPV4))
1975                         continue;
1976 #endif
1977                 if (grp->il_lport != lport)
1978                         continue;
1979
1980                 idx = INP_PCBLBGROUP_PKTHASH(faddr->s_addr, lport, fport) %
1981                     grp->il_inpcnt;
1982                 if (grp->il_laddr.s_addr == laddr->s_addr)
1983                         return (grp->il_inp[idx]);
1984                 if (grp->il_laddr.s_addr == INADDR_ANY &&
1985                     (lookupflags & INPLOOKUP_WILDCARD) != 0)
1986                         local_wild = grp->il_inp[idx];
1987         }
1988         return (local_wild);
1989 }
1990
1991 #ifdef PCBGROUP
1992 /*
1993  * Lookup PCB in hash list, using pcbgroup tables.
1994  */
1995 static struct inpcb *
1996 in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1997     struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1998     u_int lport_arg, int lookupflags, struct ifnet *ifp)
1999 {
2000         struct inpcbhead *head;
2001         struct inpcb *inp, *tmpinp;
2002         u_short fport = fport_arg, lport = lport_arg;
2003         bool locked;
2004
2005         /*
2006          * First look for an exact match.
2007          */
2008         tmpinp = NULL;
2009         INP_GROUP_LOCK(pcbgroup);
2010         head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2011             pcbgroup->ipg_hashmask)];
2012         CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2013 #ifdef INET6
2014                 /* XXX inp locking */
2015                 if ((inp->inp_vflag & INP_IPV4) == 0)
2016                         continue;
2017 #endif
2018                 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2019                     inp->inp_laddr.s_addr == laddr.s_addr &&
2020                     inp->inp_fport == fport &&
2021                     inp->inp_lport == lport) {
2022                         /*
2023                          * XXX We should be able to directly return
2024                          * the inp here, without any checks.
2025                          * Well unless both bound with SO_REUSEPORT?
2026                          */
2027                         if (prison_flag(inp->inp_cred, PR_IP4))
2028                                 goto found;
2029                         if (tmpinp == NULL)
2030                                 tmpinp = inp;
2031                 }
2032         }
2033         if (tmpinp != NULL) {
2034                 inp = tmpinp;
2035                 goto found;
2036         }
2037
2038 #ifdef  RSS
2039         /*
2040          * For incoming connections, we may wish to do a wildcard
2041          * match for an RSS-local socket.
2042          */
2043         if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2044                 struct inpcb *local_wild = NULL, *local_exact = NULL;
2045 #ifdef INET6
2046                 struct inpcb *local_wild_mapped = NULL;
2047 #endif
2048                 struct inpcb *jail_wild = NULL;
2049                 struct inpcbhead *head;
2050                 int injail;
2051
2052                 /*
2053                  * Order of socket selection - we always prefer jails.
2054                  *      1. jailed, non-wild.
2055                  *      2. jailed, wild.
2056                  *      3. non-jailed, non-wild.
2057                  *      4. non-jailed, wild.
2058                  */
2059
2060                 head = &pcbgroup->ipg_hashbase[INP_PCBHASH(INADDR_ANY,
2061                     lport, 0, pcbgroup->ipg_hashmask)];
2062                 CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
2063 #ifdef INET6
2064                         /* XXX inp locking */
2065                         if ((inp->inp_vflag & INP_IPV4) == 0)
2066                                 continue;
2067 #endif
2068                         if (inp->inp_faddr.s_addr != INADDR_ANY ||
2069                             inp->inp_lport != lport)
2070                                 continue;
2071
2072                         injail = prison_flag(inp->inp_cred, PR_IP4);
2073                         if (injail) {
2074                                 if (prison_check_ip4(inp->inp_cred,
2075                                     &laddr) != 0)
2076                                         continue;
2077                         } else {
2078                                 if (local_exact != NULL)
2079                                         continue;
2080                         }
2081
2082                         if (inp->inp_laddr.s_addr == laddr.s_addr) {
2083                                 if (injail)
2084                                         goto found;
2085                                 else
2086                                         local_exact = inp;
2087                         } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2088 #ifdef INET6
2089                                 /* XXX inp locking, NULL check */
2090                                 if (inp->inp_vflag & INP_IPV6PROTO)
2091                                         local_wild_mapped = inp;
2092                                 else
2093 #endif
2094                                         if (injail)
2095                                                 jail_wild = inp;
2096                                         else
2097                                                 local_wild = inp;
2098                         }
2099                 } /* LIST_FOREACH */
2100
2101                 inp = jail_wild;
2102                 if (inp == NULL)
2103                         inp = local_exact;
2104                 if (inp == NULL)
2105                         inp = local_wild;
2106 #ifdef INET6
2107                 if (inp == NULL)
2108                         inp = local_wild_mapped;
2109 #endif
2110                 if (inp != NULL)
2111                         goto found;
2112         }
2113 #endif
2114
2115         /*
2116          * Then look for a wildcard match, if requested.
2117          */
2118         if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2119                 struct inpcb *local_wild = NULL, *local_exact = NULL;
2120 #ifdef INET6
2121                 struct inpcb *local_wild_mapped = NULL;
2122 #endif
2123                 struct inpcb *jail_wild = NULL;
2124                 struct inpcbhead *head;
2125                 int injail;
2126
2127                 /*
2128                  * Order of socket selection - we always prefer jails.
2129                  *      1. jailed, non-wild.
2130                  *      2. jailed, wild.
2131                  *      3. non-jailed, non-wild.
2132                  *      4. non-jailed, wild.
2133                  */
2134                 head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
2135                     0, pcbinfo->ipi_wildmask)];
2136                 CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
2137 #ifdef INET6
2138                         /* XXX inp locking */
2139                         if ((inp->inp_vflag & INP_IPV4) == 0)
2140                                 continue;
2141 #endif
2142                         if (inp->inp_faddr.s_addr != INADDR_ANY ||
2143                             inp->inp_lport != lport)
2144                                 continue;
2145
2146                         injail = prison_flag(inp->inp_cred, PR_IP4);
2147                         if (injail) {
2148                                 if (prison_check_ip4(inp->inp_cred,
2149                                     &laddr) != 0)
2150                                         continue;
2151                         } else {
2152                                 if (local_exact != NULL)
2153                                         continue;
2154                         }
2155
2156                         if (inp->inp_laddr.s_addr == laddr.s_addr) {
2157                                 if (injail)
2158                                         goto found;
2159                                 else
2160                                         local_exact = inp;
2161                         } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2162 #ifdef INET6
2163                                 /* XXX inp locking, NULL check */
2164                                 if (inp->inp_vflag & INP_IPV6PROTO)
2165                                         local_wild_mapped = inp;
2166                                 else
2167 #endif
2168                                         if (injail)
2169                                                 jail_wild = inp;
2170                                         else
2171                                                 local_wild = inp;
2172                         }
2173                 } /* LIST_FOREACH */
2174                 inp = jail_wild;
2175                 if (inp == NULL)
2176                         inp = local_exact;
2177                 if (inp == NULL)
2178                         inp = local_wild;
2179 #ifdef INET6
2180                 if (inp == NULL)
2181                         inp = local_wild_mapped;
2182 #endif
2183                 if (inp != NULL)
2184                         goto found;
2185         } /* if (lookupflags & INPLOOKUP_WILDCARD) */
2186         INP_GROUP_UNLOCK(pcbgroup);
2187         return (NULL);
2188
2189 found:
2190         if (lookupflags & INPLOOKUP_WLOCKPCB)
2191                 locked = INP_TRY_WLOCK(inp);
2192         else if (lookupflags & INPLOOKUP_RLOCKPCB)
2193                 locked = INP_TRY_RLOCK(inp);
2194         else
2195                 panic("%s: locking bug", __func__);
2196         if (__predict_false(locked && (inp->inp_flags2 & INP_FREED))) {
2197                 if (lookupflags & INPLOOKUP_WLOCKPCB)
2198                         INP_WUNLOCK(inp);
2199                 else
2200                         INP_RUNLOCK(inp);
2201                 return (NULL);
2202         } else if (!locked)
2203                 in_pcbref(inp);
2204         INP_GROUP_UNLOCK(pcbgroup);
2205         if (!locked) {
2206                 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2207                         INP_WLOCK(inp);
2208                         if (in_pcbrele_wlocked(inp))
2209                                 return (NULL);
2210                 } else {
2211                         INP_RLOCK(inp);
2212                         if (in_pcbrele_rlocked(inp))
2213                                 return (NULL);
2214                 }
2215         }
2216 #ifdef INVARIANTS
2217         if (lookupflags & INPLOOKUP_WLOCKPCB)
2218                 INP_WLOCK_ASSERT(inp);
2219         else
2220                 INP_RLOCK_ASSERT(inp);
2221 #endif
2222         return (inp);
2223 }
2224 #endif /* PCBGROUP */
2225
2226 /*
2227  * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
2228  * that the caller has locked the hash list, and will not perform any further
2229  * locking or reference operations on either the hash list or the connection.
2230  */
2231 static struct inpcb *
2232 in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2233     u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
2234     struct ifnet *ifp)
2235 {
2236         struct inpcbhead *head;
2237         struct inpcb *inp, *tmpinp;
2238         u_short fport = fport_arg, lport = lport_arg;
2239
2240 #ifdef INVARIANTS
2241         KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
2242             ("%s: invalid lookup flags %d", __func__, lookupflags));
2243         if (!mtx_owned(&pcbinfo->ipi_hash_lock))
2244                 MPASS(in_epoch_verbose(net_epoch_preempt, 1));
2245 #endif
2246         /*
2247          * First look for an exact match.
2248          */
2249         tmpinp = NULL;
2250         head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
2251             pcbinfo->ipi_hashmask)];
2252         CK_LIST_FOREACH(inp, head, inp_hash) {
2253 #ifdef INET6
2254                 /* XXX inp locking */
2255                 if ((inp->inp_vflag & INP_IPV4) == 0)
2256                         continue;
2257 #endif
2258                 if (inp->inp_faddr.s_addr == faddr.s_addr &&
2259                     inp->inp_laddr.s_addr == laddr.s_addr &&
2260                     inp->inp_fport == fport &&
2261                     inp->inp_lport == lport) {
2262                         /*
2263                          * XXX We should be able to directly return
2264                          * the inp here, without any checks.
2265                          * Well unless both bound with SO_REUSEPORT?
2266                          */
2267                         if (prison_flag(inp->inp_cred, PR_IP4))
2268                                 return (inp);
2269                         if (tmpinp == NULL)
2270                                 tmpinp = inp;
2271                 }
2272         }
2273         if (tmpinp != NULL)
2274                 return (tmpinp);
2275
2276         /*
2277          * Then look in lb group (for wildcard match).
2278          */
2279         if (pcbinfo->ipi_lbgrouphashbase != NULL &&
2280                 (lookupflags & INPLOOKUP_WILDCARD)) {
2281                 inp = in_pcblookup_lbgroup(pcbinfo, &laddr, lport, &faddr,
2282                     fport, lookupflags);
2283                 if (inp != NULL) {
2284                         return (inp);
2285                 }
2286         }
2287
2288         /*
2289          * Then look for a wildcard match, if requested.
2290          */
2291         if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
2292                 struct inpcb *local_wild = NULL, *local_exact = NULL;
2293 #ifdef INET6
2294                 struct inpcb *local_wild_mapped = NULL;
2295 #endif
2296                 struct inpcb *jail_wild = NULL;
2297                 int injail;
2298
2299                 /*
2300                  * Order of socket selection - we always prefer jails.
2301                  *      1. jailed, non-wild.
2302                  *      2. jailed, wild.
2303                  *      3. non-jailed, non-wild.
2304                  *      4. non-jailed, wild.
2305                  */
2306
2307                 head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
2308                     0, pcbinfo->ipi_hashmask)];
2309                 CK_LIST_FOREACH(inp, head, inp_hash) {
2310 #ifdef INET6
2311                         /* XXX inp locking */
2312                         if ((inp->inp_vflag & INP_IPV4) == 0)
2313                                 continue;
2314 #endif
2315                         if (inp->inp_faddr.s_addr != INADDR_ANY ||
2316                             inp->inp_lport != lport)
2317                                 continue;
2318
2319                         injail = prison_flag(inp->inp_cred, PR_IP4);
2320                         if (injail) {
2321                                 if (prison_check_ip4(inp->inp_cred,
2322                                     &laddr) != 0)
2323                                         continue;
2324                         } else {
2325                                 if (local_exact != NULL)
2326                                         continue;
2327                         }
2328
2329                         if (inp->inp_laddr.s_addr == laddr.s_addr) {
2330                                 if (injail)
2331                                         return (inp);
2332                                 else
2333                                         local_exact = inp;
2334                         } else if (inp->inp_laddr.s_addr == INADDR_ANY) {
2335 #ifdef INET6
2336                                 /* XXX inp locking, NULL check */
2337                                 if (inp->inp_vflag & INP_IPV6PROTO)
2338                                         local_wild_mapped = inp;
2339                                 else
2340 #endif
2341                                         if (injail)
2342                                                 jail_wild = inp;
2343                                         else
2344                                                 local_wild = inp;
2345                         }
2346                 } /* LIST_FOREACH */
2347                 if (jail_wild != NULL)
2348                         return (jail_wild);
2349                 if (local_exact != NULL)
2350                         return (local_exact);
2351                 if (local_wild != NULL)
2352                         return (local_wild);
2353 #ifdef INET6
2354                 if (local_wild_mapped != NULL)
2355                         return (local_wild_mapped);
2356 #endif
2357         } /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
2358
2359         return (NULL);
2360 }
2361
2362 /*
2363  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
2364  * hash list lock, and will return the inpcb locked (i.e., requires
2365  * INPLOOKUP_LOCKPCB).
2366  */
2367 static struct inpcb *
2368 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2369     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2370     struct ifnet *ifp)
2371 {
2372         struct inpcb *inp;
2373
2374         INP_HASH_RLOCK(pcbinfo);
2375         inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
2376             (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
2377         if (inp != NULL) {
2378                 if (lookupflags & INPLOOKUP_WLOCKPCB) {
2379                         INP_WLOCK(inp);
2380                         if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2381                                 INP_WUNLOCK(inp);
2382                                 inp = NULL;
2383                         }
2384                 } else if (lookupflags & INPLOOKUP_RLOCKPCB) {
2385                         INP_RLOCK(inp);
2386                         if (__predict_false(inp->inp_flags2 & INP_FREED)) {
2387                                 INP_RUNLOCK(inp);
2388                                 inp = NULL;
2389                         }
2390                 } else
2391                         panic("%s: locking bug", __func__);
2392 #ifdef INVARIANTS
2393                 if (inp != NULL) {
2394                         if (lookupflags & INPLOOKUP_WLOCKPCB)
2395                                 INP_WLOCK_ASSERT(inp);
2396                         else
2397                                 INP_RLOCK_ASSERT(inp);
2398                 }
2399 #endif
2400         }
2401         INP_HASH_RUNLOCK(pcbinfo);
2402         return (inp);
2403 }
2404
2405 /*
2406  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
2407  * from which a pre-calculated hash value may be extracted.
2408  *
2409  * Possibly more of this logic should be in in_pcbgroup.c.
2410  */
2411 struct inpcb *
2412 in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
2413     struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
2414 {
2415 #if defined(PCBGROUP) && !defined(RSS)
2416         struct inpcbgroup *pcbgroup;
2417 #endif
2418
2419         KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2420             ("%s: invalid lookup flags %d", __func__, lookupflags));
2421         KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2422             ("%s: LOCKPCB not set", __func__));
2423
2424         /*
2425          * When not using RSS, use connection groups in preference to the
2426          * reservation table when looking up 4-tuples.  When using RSS, just
2427          * use the reservation table, due to the cost of the Toeplitz hash
2428          * in software.
2429          *
2430          * XXXRW: This policy belongs in the pcbgroup code, as in principle
2431          * we could be doing RSS with a non-Toeplitz hash that is affordable
2432          * in software.
2433          */
2434 #if defined(PCBGROUP) && !defined(RSS)
2435         if (in_pcbgroup_enabled(pcbinfo)) {
2436                 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2437                     fport);
2438                 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2439                     laddr, lport, lookupflags, ifp));
2440         }
2441 #endif
2442         return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2443             lookupflags, ifp));
2444 }
2445
2446 struct inpcb *
2447 in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
2448     u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
2449     struct ifnet *ifp, struct mbuf *m)
2450 {
2451 #ifdef PCBGROUP
2452         struct inpcbgroup *pcbgroup;
2453 #endif
2454
2455         KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
2456             ("%s: invalid lookup flags %d", __func__, lookupflags));
2457         KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
2458             ("%s: LOCKPCB not set", __func__));
2459
2460 #ifdef PCBGROUP
2461         /*
2462          * If we can use a hardware-generated hash to look up the connection
2463          * group, use that connection group to find the inpcb.  Otherwise
2464          * fall back on a software hash -- or the reservation table if we're
2465          * using RSS.
2466          *
2467          * XXXRW: As above, that policy belongs in the pcbgroup code.
2468          */
2469         if (in_pcbgroup_enabled(pcbinfo) &&
2470             !(M_HASHTYPE_TEST(m, M_HASHTYPE_NONE))) {
2471                 pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
2472                     m->m_pkthdr.flowid);
2473                 if (pcbgroup != NULL)
2474                         return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
2475                             fport, laddr, lport, lookupflags, ifp));
2476 #ifndef RSS
2477                 pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
2478                     fport);
2479                 return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
2480                     laddr, lport, lookupflags, ifp));
2481 #endif
2482         }
2483 #endif
2484         return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
2485             lookupflags, ifp));
2486 }
2487 #endif /* INET */
2488
2489 /*
2490  * Insert PCB onto various hash lists.
2491  */
2492 static int
2493 in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
2494 {
2495         struct inpcbhead *pcbhash;
2496         struct inpcbporthead *pcbporthash;
2497         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2498         struct inpcbport *phd;
2499         u_int32_t hashkey_faddr;
2500         int so_options;
2501
2502         INP_WLOCK_ASSERT(inp);
2503         INP_HASH_WLOCK_ASSERT(pcbinfo);
2504
2505         KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
2506             ("in_pcbinshash: INP_INHASHLIST"));
2507
2508 #ifdef INET6
2509         if (inp->inp_vflag & INP_IPV6)
2510                 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2511         else
2512 #endif
2513         hashkey_faddr = inp->inp_faddr.s_addr;
2514
2515         pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2516                  inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2517
2518         pcbporthash = &pcbinfo->ipi_porthashbase[
2519             INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
2520
2521         /*
2522          * Add entry to load balance group.
2523          * Only do this if SO_REUSEPORT_LB is set.
2524          */
2525         so_options = inp_so_options(inp);
2526         if (so_options & SO_REUSEPORT_LB) {
2527                 int ret = in_pcbinslbgrouphash(inp);
2528                 if (ret) {
2529                         /* pcb lb group malloc fail (ret=ENOBUFS). */
2530                         return (ret);
2531                 }
2532         }
2533
2534         /*
2535          * Go through port list and look for a head for this lport.
2536          */
2537         CK_LIST_FOREACH(phd, pcbporthash, phd_hash) {
2538                 if (phd->phd_port == inp->inp_lport)
2539                         break;
2540         }
2541         /*
2542          * If none exists, malloc one and tack it on.
2543          */
2544         if (phd == NULL) {
2545                 phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
2546                 if (phd == NULL) {
2547                         return (ENOBUFS); /* XXX */
2548                 }
2549                 bzero(&phd->phd_epoch_ctx, sizeof(struct epoch_context));
2550                 phd->phd_port = inp->inp_lport;
2551                 CK_LIST_INIT(&phd->phd_pcblist);
2552                 CK_LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
2553         }
2554         inp->inp_phd = phd;
2555         CK_LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
2556         CK_LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
2557         inp->inp_flags |= INP_INHASHLIST;
2558 #ifdef PCBGROUP
2559         if (do_pcbgroup_update)
2560                 in_pcbgroup_update(inp);
2561 #endif
2562         return (0);
2563 }
2564
2565 /*
2566  * For now, there are two public interfaces to insert an inpcb into the hash
2567  * lists -- one that does update pcbgroups, and one that doesn't.  The latter
2568  * is used only in the TCP syncache, where in_pcbinshash is called before the
2569  * full 4-tuple is set for the inpcb, and we don't want to install in the
2570  * pcbgroup until later.
2571  *
2572  * XXXRW: This seems like a misfeature.  in_pcbinshash should always update
2573  * connection groups, and partially initialised inpcbs should not be exposed
2574  * to either reservation hash tables or pcbgroups.
2575  */
2576 int
2577 in_pcbinshash(struct inpcb *inp)
2578 {
2579
2580         return (in_pcbinshash_internal(inp, 1));
2581 }
2582
2583 int
2584 in_pcbinshash_nopcbgroup(struct inpcb *inp)
2585 {
2586
2587         return (in_pcbinshash_internal(inp, 0));
2588 }
2589
2590 /*
2591  * Move PCB to the proper hash bucket when { faddr, fport } have  been
2592  * changed. NOTE: This does not handle the case of the lport changing (the
2593  * hashed port list would have to be updated as well), so the lport must
2594  * not change after in_pcbinshash() has been called.
2595  */
2596 void
2597 in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
2598 {
2599         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2600         struct inpcbhead *head;
2601         u_int32_t hashkey_faddr;
2602
2603         INP_WLOCK_ASSERT(inp);
2604         INP_HASH_WLOCK_ASSERT(pcbinfo);
2605
2606         KASSERT(inp->inp_flags & INP_INHASHLIST,
2607             ("in_pcbrehash: !INP_INHASHLIST"));
2608
2609 #ifdef INET6
2610         if (inp->inp_vflag & INP_IPV6)
2611                 hashkey_faddr = INP6_PCBHASHKEY(&inp->in6p_faddr);
2612         else
2613 #endif
2614         hashkey_faddr = inp->inp_faddr.s_addr;
2615
2616         head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2617                 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2618
2619         CK_LIST_REMOVE(inp, inp_hash);
2620         CK_LIST_INSERT_HEAD(head, inp, inp_hash);
2621
2622 #ifdef PCBGROUP
2623         if (m != NULL)
2624                 in_pcbgroup_update_mbuf(inp, m);
2625         else
2626                 in_pcbgroup_update(inp);
2627 #endif
2628 }
2629
2630 void
2631 in_pcbrehash(struct inpcb *inp)
2632 {
2633
2634         in_pcbrehash_mbuf(inp, NULL);
2635 }
2636
2637 /*
2638  * Remove PCB from various lists.
2639  */
2640 static void
2641 in_pcbremlists(struct inpcb *inp)
2642 {
2643         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2644
2645 #ifdef INVARIANTS
2646         if (pcbinfo == &V_tcbinfo) {
2647                 INP_INFO_RLOCK_ASSERT(pcbinfo);
2648         } else {
2649                 INP_INFO_WLOCK_ASSERT(pcbinfo);
2650         }
2651 #endif
2652
2653         INP_WLOCK_ASSERT(inp);
2654         INP_LIST_WLOCK_ASSERT(pcbinfo);
2655
2656         inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2657         if (inp->inp_flags & INP_INHASHLIST) {
2658                 struct inpcbport *phd = inp->inp_phd;
2659
2660                 INP_HASH_WLOCK(pcbinfo);
2661
2662                 /* XXX: Only do if SO_REUSEPORT_LB set? */
2663                 in_pcbremlbgrouphash(inp);
2664
2665                 CK_LIST_REMOVE(inp, inp_hash);
2666                 CK_LIST_REMOVE(inp, inp_portlist);
2667                 if (CK_LIST_FIRST(&phd->phd_pcblist) == NULL) {
2668                         CK_LIST_REMOVE(phd, phd_hash);
2669                         epoch_call(net_epoch_preempt, &phd->phd_epoch_ctx, inpcbport_free);
2670                 }
2671                 INP_HASH_WUNLOCK(pcbinfo);
2672                 inp->inp_flags &= ~INP_INHASHLIST;
2673         }
2674         CK_LIST_REMOVE(inp, inp_list);
2675         pcbinfo->ipi_count--;
2676 #ifdef PCBGROUP
2677         in_pcbgroup_remove(inp);
2678 #endif
2679 }
2680
2681 /*
2682  * Check for alternatives when higher level complains
2683  * about service problems.  For now, invalidate cached
2684  * routing information.  If the route was created dynamically
2685  * (by a redirect), time to try a default gateway again.
2686  */
2687 void
2688 in_losing(struct inpcb *inp)
2689 {
2690
2691         RO_INVALIDATE_CACHE(&inp->inp_route);
2692         return;
2693 }
2694
2695 /*
2696  * A set label operation has occurred at the socket layer, propagate the
2697  * label change into the in_pcb for the socket.
2698  */
2699 void
2700 in_pcbsosetlabel(struct socket *so)
2701 {
2702 #ifdef MAC
2703         struct inpcb *inp;
2704
2705         inp = sotoinpcb(so);
2706         KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2707
2708         INP_WLOCK(inp);
2709         SOCK_LOCK(so);
2710         mac_inpcb_sosetlabel(so, inp);
2711         SOCK_UNLOCK(so);
2712         INP_WUNLOCK(inp);
2713 #endif
2714 }
2715
2716 /*
2717  * ipport_tick runs once per second, determining if random port allocation
2718  * should be continued.  If more than ipport_randomcps ports have been
2719  * allocated in the last second, then we return to sequential port
2720  * allocation. We return to random allocation only once we drop below
2721  * ipport_randomcps for at least ipport_randomtime seconds.
2722  */
2723 static void
2724 ipport_tick(void *xtp)
2725 {
2726         VNET_ITERATOR_DECL(vnet_iter);
2727
2728         VNET_LIST_RLOCK_NOSLEEP();
2729         VNET_FOREACH(vnet_iter) {
2730                 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS here */
2731                 if (V_ipport_tcpallocs <=
2732                     V_ipport_tcplastcount + V_ipport_randomcps) {
2733                         if (V_ipport_stoprandom > 0)
2734                                 V_ipport_stoprandom--;
2735                 } else
2736                         V_ipport_stoprandom = V_ipport_randomtime;
2737                 V_ipport_tcplastcount = V_ipport_tcpallocs;
2738                 CURVNET_RESTORE();
2739         }
2740         VNET_LIST_RUNLOCK_NOSLEEP();
2741         callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2742 }
2743
2744 static void
2745 ip_fini(void *xtp)
2746 {
2747
2748         callout_stop(&ipport_tick_callout);
2749 }
2750
2751 /* 
2752  * The ipport_callout should start running at about the time we attach the
2753  * inet or inet6 domains.
2754  */
2755 static void
2756 ipport_tick_init(const void *unused __unused)
2757 {
2758
2759         /* Start ipport_tick. */
2760         callout_init(&ipport_tick_callout, 1);
2761         callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2762         EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2763                 SHUTDOWN_PRI_DEFAULT);
2764 }
2765 SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, 
2766     ipport_tick_init, NULL);
2767
2768 void
2769 inp_wlock(struct inpcb *inp)
2770 {
2771
2772         INP_WLOCK(inp);
2773 }
2774
2775 void
2776 inp_wunlock(struct inpcb *inp)
2777 {
2778
2779         INP_WUNLOCK(inp);
2780 }
2781
2782 void
2783 inp_rlock(struct inpcb *inp)
2784 {
2785
2786         INP_RLOCK(inp);
2787 }
2788
2789 void
2790 inp_runlock(struct inpcb *inp)
2791 {
2792
2793         INP_RUNLOCK(inp);
2794 }
2795
2796 #ifdef INVARIANT_SUPPORT
2797 void
2798 inp_lock_assert(struct inpcb *inp)
2799 {
2800
2801         INP_WLOCK_ASSERT(inp);
2802 }
2803
2804 void
2805 inp_unlock_assert(struct inpcb *inp)
2806 {
2807
2808         INP_UNLOCK_ASSERT(inp);
2809 }
2810 #endif
2811
2812 void
2813 inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2814 {
2815         struct inpcb *inp;
2816
2817         INP_INFO_WLOCK(&V_tcbinfo);
2818         CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2819                 INP_WLOCK(inp);
2820                 func(inp, arg);
2821                 INP_WUNLOCK(inp);
2822         }
2823         INP_INFO_WUNLOCK(&V_tcbinfo);
2824 }
2825
2826 struct socket *
2827 inp_inpcbtosocket(struct inpcb *inp)
2828 {
2829
2830         INP_WLOCK_ASSERT(inp);
2831         return (inp->inp_socket);
2832 }
2833
2834 struct tcpcb *
2835 inp_inpcbtotcpcb(struct inpcb *inp)
2836 {
2837
2838         INP_WLOCK_ASSERT(inp);
2839         return ((struct tcpcb *)inp->inp_ppcb);
2840 }
2841
2842 int
2843 inp_ip_tos_get(const struct inpcb *inp)
2844 {
2845
2846         return (inp->inp_ip_tos);
2847 }
2848
2849 void
2850 inp_ip_tos_set(struct inpcb *inp, int val)
2851 {
2852
2853         inp->inp_ip_tos = val;
2854 }
2855
2856 void
2857 inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2858     uint32_t *faddr, uint16_t *fp)
2859 {
2860
2861         INP_LOCK_ASSERT(inp);
2862         *laddr = inp->inp_laddr.s_addr;
2863         *faddr = inp->inp_faddr.s_addr;
2864         *lp = inp->inp_lport;
2865         *fp = inp->inp_fport;
2866 }
2867
2868 struct inpcb *
2869 so_sotoinpcb(struct socket *so)
2870 {
2871
2872         return (sotoinpcb(so));
2873 }
2874
2875 struct tcpcb *
2876 so_sototcpcb(struct socket *so)
2877 {
2878
2879         return (sototcpcb(so));
2880 }
2881
2882 /*
2883  * Create an external-format (``xinpcb'') structure using the information in
2884  * the kernel-format in_pcb structure pointed to by inp.  This is done to
2885  * reduce the spew of irrelevant information over this interface, to isolate
2886  * user code from changes in the kernel structure, and potentially to provide
2887  * information-hiding if we decide that some of this information should be
2888  * hidden from users.
2889  */
2890 void
2891 in_pcbtoxinpcb(const struct inpcb *inp, struct xinpcb *xi)
2892 {
2893
2894         xi->xi_len = sizeof(struct xinpcb);
2895         if (inp->inp_socket)
2896                 sotoxsocket(inp->inp_socket, &xi->xi_socket);
2897         else
2898                 bzero(&xi->xi_socket, sizeof(struct xsocket));
2899         bcopy(&inp->inp_inc, &xi->inp_inc, sizeof(struct in_conninfo));
2900         xi->inp_gencnt = inp->inp_gencnt;
2901         xi->inp_ppcb = (uintptr_t)inp->inp_ppcb;
2902         xi->inp_flow = inp->inp_flow;
2903         xi->inp_flowid = inp->inp_flowid;
2904         xi->inp_flowtype = inp->inp_flowtype;
2905         xi->inp_flags = inp->inp_flags;
2906         xi->inp_flags2 = inp->inp_flags2;
2907         xi->inp_rss_listen_bucket = inp->inp_rss_listen_bucket;
2908         xi->in6p_cksum = inp->in6p_cksum;
2909         xi->in6p_hops = inp->in6p_hops;
2910         xi->inp_ip_tos = inp->inp_ip_tos;
2911         xi->inp_vflag = inp->inp_vflag;
2912         xi->inp_ip_ttl = inp->inp_ip_ttl;
2913         xi->inp_ip_p = inp->inp_ip_p;
2914         xi->inp_ip_minttl = inp->inp_ip_minttl;
2915 }
2916
2917 #ifdef DDB
2918 static void
2919 db_print_indent(int indent)
2920 {
2921         int i;
2922
2923         for (i = 0; i < indent; i++)
2924                 db_printf(" ");
2925 }
2926
2927 static void
2928 db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2929 {
2930         char faddr_str[48], laddr_str[48];
2931
2932         db_print_indent(indent);
2933         db_printf("%s at %p\n", name, inc);
2934
2935         indent += 2;
2936
2937 #ifdef INET6
2938         if (inc->inc_flags & INC_ISIPV6) {
2939                 /* IPv6. */
2940                 ip6_sprintf(laddr_str, &inc->inc6_laddr);
2941                 ip6_sprintf(faddr_str, &inc->inc6_faddr);
2942         } else
2943 #endif
2944         {
2945                 /* IPv4. */
2946                 inet_ntoa_r(inc->inc_laddr, laddr_str);
2947                 inet_ntoa_r(inc->inc_faddr, faddr_str);
2948         }
2949         db_print_indent(indent);
2950         db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
2951             ntohs(inc->inc_lport));
2952         db_print_indent(indent);
2953         db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
2954             ntohs(inc->inc_fport));
2955 }
2956
2957 static void
2958 db_print_inpflags(int inp_flags)
2959 {
2960         int comma;
2961
2962         comma = 0;
2963         if (inp_flags & INP_RECVOPTS) {
2964                 db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2965                 comma = 1;
2966         }
2967         if (inp_flags & INP_RECVRETOPTS) {
2968                 db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2969                 comma = 1;
2970         }
2971         if (inp_flags & INP_RECVDSTADDR) {
2972                 db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2973                 comma = 1;
2974         }
2975         if (inp_flags & INP_ORIGDSTADDR) {
2976                 db_printf("%sINP_ORIGDSTADDR", comma ? ", " : "");
2977                 comma = 1;
2978         }
2979         if (inp_flags & INP_HDRINCL) {
2980                 db_printf("%sINP_HDRINCL", comma ? ", " : "");
2981                 comma = 1;
2982         }
2983         if (inp_flags & INP_HIGHPORT) {
2984                 db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2985                 comma = 1;
2986         }
2987         if (inp_flags & INP_LOWPORT) {
2988                 db_printf("%sINP_LOWPORT", comma ? ", " : "");
2989                 comma = 1;
2990         }
2991         if (inp_flags & INP_ANONPORT) {
2992                 db_printf("%sINP_ANONPORT", comma ? ", " : "");
2993                 comma = 1;
2994         }
2995         if (inp_flags & INP_RECVIF) {
2996                 db_printf("%sINP_RECVIF", comma ? ", " : "");
2997                 comma = 1;
2998         }
2999         if (inp_flags & INP_MTUDISC) {
3000                 db_printf("%sINP_MTUDISC", comma ? ", " : "");
3001                 comma = 1;
3002         }
3003         if (inp_flags & INP_RECVTTL) {
3004                 db_printf("%sINP_RECVTTL", comma ? ", " : "");
3005                 comma = 1;
3006         }
3007         if (inp_flags & INP_DONTFRAG) {
3008                 db_printf("%sINP_DONTFRAG", comma ? ", " : "");
3009                 comma = 1;
3010         }
3011         if (inp_flags & INP_RECVTOS) {
3012                 db_printf("%sINP_RECVTOS", comma ? ", " : "");
3013                 comma = 1;
3014         }
3015         if (inp_flags & IN6P_IPV6_V6ONLY) {
3016                 db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
3017                 comma = 1;
3018         }
3019         if (inp_flags & IN6P_PKTINFO) {
3020                 db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
3021                 comma = 1;
3022         }
3023         if (inp_flags & IN6P_HOPLIMIT) {
3024                 db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
3025                 comma = 1;
3026         }
3027         if (inp_flags & IN6P_HOPOPTS) {
3028                 db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
3029                 comma = 1;
3030         }
3031         if (inp_flags & IN6P_DSTOPTS) {
3032                 db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
3033                 comma = 1;
3034         }
3035         if (inp_flags & IN6P_RTHDR) {
3036                 db_printf("%sIN6P_RTHDR", comma ? ", " : "");
3037                 comma = 1;
3038         }
3039         if (inp_flags & IN6P_RTHDRDSTOPTS) {
3040                 db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
3041                 comma = 1;
3042         }
3043         if (inp_flags & IN6P_TCLASS) {
3044                 db_printf("%sIN6P_TCLASS", comma ? ", " : "");
3045                 comma = 1;
3046         }
3047         if (inp_flags & IN6P_AUTOFLOWLABEL) {
3048                 db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
3049                 comma = 1;
3050         }
3051         if (inp_flags & INP_TIMEWAIT) {
3052                 db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
3053                 comma  = 1;
3054         }
3055         if (inp_flags & INP_ONESBCAST) {
3056                 db_printf("%sINP_ONESBCAST", comma ? ", " : "");
3057                 comma  = 1;
3058         }
3059         if (inp_flags & INP_DROPPED) {
3060                 db_printf("%sINP_DROPPED", comma ? ", " : "");
3061                 comma  = 1;
3062         }
3063         if (inp_flags & INP_SOCKREF) {
3064                 db_printf("%sINP_SOCKREF", comma ? ", " : "");
3065                 comma  = 1;
3066         }
3067         if (inp_flags & IN6P_RFC2292) {
3068                 db_printf("%sIN6P_RFC2292", comma ? ", " : "");
3069                 comma = 1;
3070         }
3071         if (inp_flags & IN6P_MTU) {
3072                 db_printf("IN6P_MTU%s", comma ? ", " : "");
3073                 comma = 1;
3074         }
3075 }
3076
3077 static void
3078 db_print_inpvflag(u_char inp_vflag)
3079 {
3080         int comma;
3081
3082         comma = 0;
3083         if (inp_vflag & INP_IPV4) {
3084                 db_printf("%sINP_IPV4", comma ? ", " : "");
3085                 comma  = 1;
3086         }
3087         if (inp_vflag & INP_IPV6) {
3088                 db_printf("%sINP_IPV6", comma ? ", " : "");
3089                 comma  = 1;
3090         }
3091         if (inp_vflag & INP_IPV6PROTO) {
3092                 db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
3093                 comma  = 1;
3094         }
3095 }
3096
3097 static void
3098 db_print_inpcb(struct inpcb *inp, const char *name, int indent)
3099 {
3100
3101         db_print_indent(indent);
3102         db_printf("%s at %p\n", name, inp);
3103
3104         indent += 2;
3105
3106         db_print_indent(indent);
3107         db_printf("inp_flow: 0x%x\n", inp->inp_flow);
3108
3109         db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
3110
3111         db_print_indent(indent);
3112         db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
3113             inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
3114
3115         db_print_indent(indent);
3116         db_printf("inp_label: %p   inp_flags: 0x%x (",
3117            inp->inp_label, inp->inp_flags);
3118         db_print_inpflags(inp->inp_flags);
3119         db_printf(")\n");
3120
3121         db_print_indent(indent);
3122         db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
3123             inp->inp_vflag);
3124         db_print_inpvflag(inp->inp_vflag);
3125         db_printf(")\n");
3126
3127         db_print_indent(indent);
3128         db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
3129             inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
3130
3131         db_print_indent(indent);
3132 #ifdef INET6
3133         if (inp->inp_vflag & INP_IPV6) {
3134                 db_printf("in6p_options: %p   in6p_outputopts: %p   "
3135                     "in6p_moptions: %p\n", inp->in6p_options,
3136                     inp->in6p_outputopts, inp->in6p_moptions);
3137                 db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
3138                     "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
3139                     inp->in6p_hops);
3140         } else
3141 #endif
3142         {
3143                 db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
3144                     "inp_ip_moptions: %p\n", inp->inp_ip_tos,
3145                     inp->inp_options, inp->inp_moptions);
3146         }
3147
3148         db_print_indent(indent);
3149         db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
3150             (uintmax_t)inp->inp_gencnt);
3151 }
3152
3153 DB_SHOW_COMMAND(inpcb, db_show_inpcb)
3154 {
3155         struct inpcb *inp;
3156
3157         if (!have_addr) {
3158                 db_printf("usage: show inpcb <addr>\n");
3159                 return;
3160         }
3161         inp = (struct inpcb *)addr;
3162
3163         db_print_inpcb(inp, "inpcb", 0);
3164 }
3165 #endif /* DDB */
3166
3167 #ifdef RATELIMIT
3168 /*
3169  * Modify TX rate limit based on the existing "inp->inp_snd_tag",
3170  * if any.
3171  */
3172 int
3173 in_pcbmodify_txrtlmt(struct inpcb *inp, uint32_t max_pacing_rate)
3174 {
3175         union if_snd_tag_modify_params params = {
3176                 .rate_limit.max_rate = max_pacing_rate,
3177         };
3178         struct m_snd_tag *mst;
3179         struct ifnet *ifp;
3180         int error;
3181
3182         mst = inp->inp_snd_tag;
3183         if (mst == NULL)
3184                 return (EINVAL);
3185
3186         ifp = mst->ifp;
3187         if (ifp == NULL)
3188                 return (EINVAL);
3189
3190         if (ifp->if_snd_tag_modify == NULL) {
3191                 error = EOPNOTSUPP;
3192         } else {
3193                 error = ifp->if_snd_tag_modify(mst, &params);
3194         }
3195         return (error);
3196 }
3197
3198 /*
3199  * Query existing TX rate limit based on the existing
3200  * "inp->inp_snd_tag", if any.
3201  */
3202 int
3203 in_pcbquery_txrtlmt(struct inpcb *inp, uint32_t *p_max_pacing_rate)
3204 {
3205         union if_snd_tag_query_params params = { };
3206         struct m_snd_tag *mst;
3207         struct ifnet *ifp;
3208         int error;
3209
3210         mst = inp->inp_snd_tag;
3211         if (mst == NULL)
3212                 return (EINVAL);
3213
3214         ifp = mst->ifp;
3215         if (ifp == NULL)
3216                 return (EINVAL);
3217
3218         if (ifp->if_snd_tag_query == NULL) {
3219                 error = EOPNOTSUPP;
3220         } else {
3221                 error = ifp->if_snd_tag_query(mst, &params);
3222                 if (error == 0 &&  p_max_pacing_rate != NULL)
3223                         *p_max_pacing_rate = params.rate_limit.max_rate;
3224         }
3225         return (error);
3226 }
3227
3228 /*
3229  * Query existing TX queue level based on the existing
3230  * "inp->inp_snd_tag", if any.
3231  */
3232 int
3233 in_pcbquery_txrlevel(struct inpcb *inp, uint32_t *p_txqueue_level)
3234 {
3235         union if_snd_tag_query_params params = { };
3236         struct m_snd_tag *mst;
3237         struct ifnet *ifp;
3238         int error;
3239
3240         mst = inp->inp_snd_tag;
3241         if (mst == NULL)
3242                 return (EINVAL);
3243
3244         ifp = mst->ifp;
3245         if (ifp == NULL)
3246                 return (EINVAL);
3247
3248         if (ifp->if_snd_tag_query == NULL)
3249                 return (EOPNOTSUPP);
3250
3251         error = ifp->if_snd_tag_query(mst, &params);
3252         if (error == 0 &&  p_txqueue_level != NULL)
3253                 *p_txqueue_level = params.rate_limit.queue_level;
3254         return (error);
3255 }
3256
3257 /*
3258  * Allocate a new TX rate limit send tag from the network interface
3259  * given by the "ifp" argument and save it in "inp->inp_snd_tag":
3260  */
3261 int
3262 in_pcbattach_txrtlmt(struct inpcb *inp, struct ifnet *ifp,
3263     uint32_t flowtype, uint32_t flowid, uint32_t max_pacing_rate)
3264 {
3265         union if_snd_tag_alloc_params params = {
3266                 .rate_limit.hdr.type = (max_pacing_rate == -1U) ?
3267                     IF_SND_TAG_TYPE_UNLIMITED : IF_SND_TAG_TYPE_RATE_LIMIT,
3268                 .rate_limit.hdr.flowid = flowid,
3269                 .rate_limit.hdr.flowtype = flowtype,
3270                 .rate_limit.max_rate = max_pacing_rate,
3271         };
3272         int error;
3273
3274         INP_WLOCK_ASSERT(inp);
3275
3276         if (inp->inp_snd_tag != NULL)
3277                 return (EINVAL);
3278
3279         if (ifp->if_snd_tag_alloc == NULL) {
3280                 error = EOPNOTSUPP;
3281         } else {
3282                 error = ifp->if_snd_tag_alloc(ifp, &params, &inp->inp_snd_tag);
3283
3284                 /*
3285                  * At success increment the refcount on
3286                  * the send tag's network interface:
3287                  */
3288                 if (error == 0)
3289                         if_ref(inp->inp_snd_tag->ifp);
3290         }
3291         return (error);
3292 }
3293
3294 /*
3295  * Free an existing TX rate limit tag based on the "inp->inp_snd_tag",
3296  * if any:
3297  */
3298 void
3299 in_pcbdetach_txrtlmt(struct inpcb *inp)
3300 {
3301         struct m_snd_tag *mst;
3302         struct ifnet *ifp;
3303
3304         INP_WLOCK_ASSERT(inp);
3305
3306         mst = inp->inp_snd_tag;
3307         inp->inp_snd_tag = NULL;
3308
3309         if (mst == NULL)
3310                 return;
3311
3312         ifp = mst->ifp;
3313         if (ifp == NULL)
3314                 return;
3315
3316         /*
3317          * If the device was detached while we still had reference(s)
3318          * on the ifp, we assume if_snd_tag_free() was replaced with
3319          * stubs.
3320          */
3321         ifp->if_snd_tag_free(mst);
3322
3323         /* release reference count on network interface */
3324         if_rele(ifp);
3325 }
3326
3327 /*
3328  * This function should be called when the INP_RATE_LIMIT_CHANGED flag
3329  * is set in the fast path and will attach/detach/modify the TX rate
3330  * limit send tag based on the socket's so_max_pacing_rate value.
3331  */
3332 void
3333 in_pcboutput_txrtlmt(struct inpcb *inp, struct ifnet *ifp, struct mbuf *mb)
3334 {
3335         struct socket *socket;
3336         uint32_t max_pacing_rate;
3337         bool did_upgrade;
3338         int error;
3339
3340         if (inp == NULL)
3341                 return;
3342
3343         socket = inp->inp_socket;
3344         if (socket == NULL)
3345                 return;
3346
3347         if (!INP_WLOCKED(inp)) {
3348                 /*
3349                  * NOTE: If the write locking fails, we need to bail
3350                  * out and use the non-ratelimited ring for the
3351                  * transmit until there is a new chance to get the
3352                  * write lock.
3353                  */
3354                 if (!INP_TRY_UPGRADE(inp))
3355                         return;
3356                 did_upgrade = 1;
3357         } else {
3358                 did_upgrade = 0;
3359         }
3360
3361         /*
3362          * NOTE: The so_max_pacing_rate value is read unlocked,
3363          * because atomic updates are not required since the variable
3364          * is checked at every mbuf we send. It is assumed that the
3365          * variable read itself will be atomic.
3366          */
3367         max_pacing_rate = socket->so_max_pacing_rate;
3368
3369         /*
3370          * NOTE: When attaching to a network interface a reference is
3371          * made to ensure the network interface doesn't go away until
3372          * all ratelimit connections are gone. The network interface
3373          * pointers compared below represent valid network interfaces,
3374          * except when comparing towards NULL.
3375          */
3376         if (max_pacing_rate == 0 && inp->inp_snd_tag == NULL) {
3377                 error = 0;
3378         } else if (!(ifp->if_capenable & IFCAP_TXRTLMT)) {
3379                 if (inp->inp_snd_tag != NULL)
3380                         in_pcbdetach_txrtlmt(inp);
3381                 error = 0;
3382         } else if (inp->inp_snd_tag == NULL) {
3383                 /*
3384                  * In order to utilize packet pacing with RSS, we need
3385                  * to wait until there is a valid RSS hash before we
3386                  * can proceed:
3387                  */
3388                 if (M_HASHTYPE_GET(mb) == M_HASHTYPE_NONE) {
3389                         error = EAGAIN;
3390                 } else {
3391                         error = in_pcbattach_txrtlmt(inp, ifp, M_HASHTYPE_GET(mb),
3392                             mb->m_pkthdr.flowid, max_pacing_rate);
3393                 }
3394         } else {
3395                 error = in_pcbmodify_txrtlmt(inp, max_pacing_rate);
3396         }
3397         if (error == 0 || error == EOPNOTSUPP)
3398                 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
3399         if (did_upgrade)
3400                 INP_DOWNGRADE(inp);
3401 }
3402
3403 /*
3404  * Track route changes for TX rate limiting.
3405  */
3406 void
3407 in_pcboutput_eagain(struct inpcb *inp)
3408 {
3409         struct socket *socket;
3410         bool did_upgrade;
3411
3412         if (inp == NULL)
3413                 return;
3414
3415         socket = inp->inp_socket;
3416         if (socket == NULL)
3417                 return;
3418
3419         if (inp->inp_snd_tag == NULL)
3420                 return;
3421
3422         if (!INP_WLOCKED(inp)) {
3423                 /*
3424                  * NOTE: If the write locking fails, we need to bail
3425                  * out and use the non-ratelimited ring for the
3426                  * transmit until there is a new chance to get the
3427                  * write lock.
3428                  */
3429                 if (!INP_TRY_UPGRADE(inp))
3430                         return;
3431                 did_upgrade = 1;
3432         } else {
3433                 did_upgrade = 0;
3434         }
3435
3436         /* detach rate limiting */
3437         in_pcbdetach_txrtlmt(inp);
3438
3439         /* make sure new mbuf send tag allocation is made */
3440         inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
3441
3442         if (did_upgrade)
3443                 INP_DOWNGRADE(inp);
3444 }
3445 #endif /* RATELIMIT */