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