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