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