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