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