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