]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_usrreq.c
riscv: Call identify_cpu() earlier for CPU 0
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_usrreq.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *      The Regents of the University of California.
6  * Copyright (c) 2006-2007 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  *      From: @(#)tcp_usrreq.c  8.2 (Berkeley) 1/3/94
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #include "opt_ddb.h"
44 #include "opt_inet.h"
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
47 #include "opt_kern_tls.h"
48 #include "opt_tcpdebug.h"
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/arb.h>
53 #include <sys/limits.h>
54 #include <sys/malloc.h>
55 #include <sys/refcount.h>
56 #include <sys/kernel.h>
57 #include <sys/ktls.h>
58 #include <sys/qmath.h>
59 #include <sys/sysctl.h>
60 #include <sys/mbuf.h>
61 #ifdef INET6
62 #include <sys/domain.h>
63 #endif /* INET6 */
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <sys/protosw.h>
67 #include <sys/proc.h>
68 #include <sys/jail.h>
69 #include <sys/syslog.h>
70 #include <sys/stats.h>
71
72 #ifdef DDB
73 #include <ddb/ddb.h>
74 #endif
75
76 #include <net/if.h>
77 #include <net/if_var.h>
78 #include <net/route.h>
79 #include <net/vnet.h>
80
81 #include <netinet/in.h>
82 #include <netinet/in_kdtrace.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/in_var.h>
86 #include <netinet/ip_var.h>
87 #ifdef INET6
88 #include <netinet/ip6.h>
89 #include <netinet6/in6_pcb.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet6/scope6_var.h>
92 #endif
93 #include <netinet/tcp.h>
94 #include <netinet/tcp_fsm.h>
95 #include <netinet/tcp_seq.h>
96 #include <netinet/tcp_timer.h>
97 #include <netinet/tcp_var.h>
98 #include <netinet/tcp_log_buf.h>
99 #include <netinet/tcpip.h>
100 #include <netinet/cc/cc.h>
101 #include <netinet/tcp_fastopen.h>
102 #include <netinet/tcp_hpts.h>
103 #ifdef TCPPCAP
104 #include <netinet/tcp_pcap.h>
105 #endif
106 #ifdef TCPDEBUG
107 #include <netinet/tcp_debug.h>
108 #endif
109 #ifdef TCP_OFFLOAD
110 #include <netinet/tcp_offload.h>
111 #endif
112 #include <netipsec/ipsec_support.h>
113
114 #include <vm/vm.h>
115 #include <vm/vm_param.h>
116 #include <vm/pmap.h>
117 #include <vm/vm_extern.h>
118 #include <vm/vm_map.h>
119 #include <vm/vm_page.h>
120
121 /*
122  * TCP protocol interface to socket abstraction.
123  */
124 #ifdef INET
125 static int      tcp_connect(struct tcpcb *, struct sockaddr *,
126                     struct thread *td);
127 #endif /* INET */
128 #ifdef INET6
129 static int      tcp6_connect(struct tcpcb *, struct sockaddr *,
130                     struct thread *td);
131 #endif /* INET6 */
132 static void     tcp_disconnect(struct tcpcb *);
133 static void     tcp_usrclosed(struct tcpcb *);
134 static void     tcp_fill_info(struct tcpcb *, struct tcp_info *);
135
136 static int      tcp_pru_options_support(struct tcpcb *tp, int flags);
137
138 #ifdef TCPDEBUG
139 #define TCPDEBUG0       int ostate = 0
140 #define TCPDEBUG1()     ostate = tp ? tp->t_state : 0
141 #define TCPDEBUG2(req)  if (tp && (so->so_options & SO_DEBUG)) \
142                                 tcp_trace(TA_USER, ostate, tp, 0, 0, req)
143 #else
144 #define TCPDEBUG0
145 #define TCPDEBUG1()
146 #define TCPDEBUG2(req)
147 #endif
148
149 /*
150  * tcp_require_unique port requires a globally-unique source port for each
151  * outgoing connection.  The default is to require the 4-tuple to be unique.
152  */
153 VNET_DEFINE(int, tcp_require_unique_port) = 0;
154 SYSCTL_INT(_net_inet_tcp, OID_AUTO, require_unique_port,
155     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_require_unique_port), 0,
156     "Require globally-unique ephemeral port for outgoing connections");
157 #define V_tcp_require_unique_port       VNET(tcp_require_unique_port)
158
159 /*
160  * TCP attaches to socket via pru_attach(), reserving space,
161  * and an internet control block.
162  */
163 static int
164 tcp_usr_attach(struct socket *so, int proto, struct thread *td)
165 {
166         struct inpcb *inp;
167         struct tcpcb *tp = NULL;
168         int error;
169         TCPDEBUG0;
170
171         inp = sotoinpcb(so);
172         KASSERT(inp == NULL, ("tcp_usr_attach: inp != NULL"));
173         TCPDEBUG1();
174
175         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
176                 error = soreserve(so, V_tcp_sendspace, V_tcp_recvspace);
177                 if (error)
178                         goto out;
179         }
180
181         so->so_rcv.sb_flags |= SB_AUTOSIZE;
182         so->so_snd.sb_flags |= SB_AUTOSIZE;
183         error = in_pcballoc(so, &V_tcbinfo);
184         if (error)
185                 goto out;
186         inp = sotoinpcb(so);
187 #ifdef INET6
188         if (inp->inp_vflag & INP_IPV6PROTO) {
189                 inp->inp_vflag |= INP_IPV6;
190                 if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
191                         inp->inp_vflag |= INP_IPV4;
192                 inp->in6p_hops = -1;    /* use kernel default */
193         }
194         else
195 #endif
196                 inp->inp_vflag |= INP_IPV4;
197         tp = tcp_newtcpcb(inp);
198         if (tp == NULL) {
199                 error = ENOBUFS;
200                 in_pcbdetach(inp);
201                 in_pcbfree(inp);
202                 goto out;
203         }
204         tp->t_state = TCPS_CLOSED;
205         INP_WUNLOCK(inp);
206         TCPSTATES_INC(TCPS_CLOSED);
207 out:
208         TCPDEBUG2(PRU_ATTACH);
209         TCP_PROBE2(debug__user, tp, PRU_ATTACH);
210         return (error);
211 }
212
213 /*
214  * tcp_usr_detach is called when the socket layer loses its final reference
215  * to the socket, be it a file descriptor reference, a reference from TCP,
216  * etc.  At this point, there is only one case in which we will keep around
217  * inpcb state: time wait.
218  */
219 static void
220 tcp_usr_detach(struct socket *so)
221 {
222         struct inpcb *inp;
223         struct tcpcb *tp;
224
225         inp = sotoinpcb(so);
226         KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
227         INP_WLOCK(inp);
228         KASSERT(so->so_pcb == inp && inp->inp_socket == so,
229                 ("%s: socket %p inp %p mismatch", __func__, so, inp));
230
231         tp = intotcpcb(inp);
232
233         if (inp->inp_flags & INP_TIMEWAIT) {
234                 /*
235                  * There are two cases to handle: one in which the time wait
236                  * state is being discarded (INP_DROPPED), and one in which
237                  * this connection will remain in timewait.  In the former,
238                  * it is time to discard all state (except tcptw, which has
239                  * already been discarded by the timewait close code, which
240                  * should be further up the call stack somewhere).  In the
241                  * latter case, we detach from the socket, but leave the pcb
242                  * present until timewait ends.
243                  *
244                  * XXXRW: Would it be cleaner to free the tcptw here?
245                  *
246                  * Astute question indeed, from twtcp perspective there are
247                  * four cases to consider:
248                  *
249                  * #1 tcp_usr_detach is called at tcptw creation time by
250                  *  tcp_twstart, then do not discard the newly created tcptw
251                  *  and leave inpcb present until timewait ends
252                  * #2 tcp_usr_detach is called at tcptw creation time by
253                  *  tcp_twstart, but connection is local and tw will be
254                  *  discarded immediately
255                  * #3 tcp_usr_detach is called at timewait end (or reuse) by
256                  *  tcp_twclose, then the tcptw has already been discarded
257                  *  (or reused) and inpcb is freed here
258                  * #4 tcp_usr_detach is called() after timewait ends (or reuse)
259                  *  (e.g. by soclose), then tcptw has already been discarded
260                  *  (or reused) and inpcb is freed here
261                  *
262                  *  In all three cases the tcptw should not be freed here.
263                  */
264                 if (inp->inp_flags & INP_DROPPED) {
265                         in_pcbdetach(inp);
266                         if (__predict_true(tp == NULL)) {
267                                 in_pcbfree(inp);
268                         } else {
269                                 /*
270                                  * This case should not happen as in TIMEWAIT
271                                  * state the inp should not be destroyed before
272                                  * its tcptw.  If INVARIANTS is defined, panic.
273                                  */
274 #ifdef INVARIANTS
275                                 panic("%s: Panic before an inp double-free: "
276                                     "INP_TIMEWAIT && INP_DROPPED && tp != NULL"
277                                     , __func__);
278 #else
279                                 log(LOG_ERR, "%s: Avoid an inp double-free: "
280                                     "INP_TIMEWAIT && INP_DROPPED && tp != NULL"
281                                     , __func__);
282 #endif
283                                 INP_WUNLOCK(inp);
284                         }
285                 } else {
286                         in_pcbdetach(inp);
287                         INP_WUNLOCK(inp);
288                 }
289         } else {
290                 /*
291                  * If the connection is not in timewait, we consider two
292                  * two conditions: one in which no further processing is
293                  * necessary (dropped || embryonic), and one in which TCP is
294                  * not yet done, but no longer requires the socket, so the
295                  * pcb will persist for the time being.
296                  *
297                  * XXXRW: Does the second case still occur?
298                  */
299                 if (inp->inp_flags & INP_DROPPED ||
300                     tp->t_state < TCPS_SYN_SENT) {
301                         tcp_discardcb(tp);
302                         in_pcbdetach(inp);
303                         in_pcbfree(inp);
304                 } else {
305                         in_pcbdetach(inp);
306                         INP_WUNLOCK(inp);
307                 }
308         }
309 }
310
311 #ifdef INET
312 /*
313  * Give the socket an address.
314  */
315 static int
316 tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
317 {
318         int error = 0;
319         struct inpcb *inp;
320         struct tcpcb *tp = NULL;
321         struct sockaddr_in *sinp;
322
323         sinp = (struct sockaddr_in *)nam;
324         if (nam->sa_family != AF_INET) {
325                 /*
326                  * Preserve compatibility with old programs.
327                  */
328                 if (nam->sa_family != AF_UNSPEC ||
329                     nam->sa_len < offsetof(struct sockaddr_in, sin_zero) ||
330                     sinp->sin_addr.s_addr != INADDR_ANY)
331                         return (EAFNOSUPPORT);
332                 nam->sa_family = AF_INET;
333         }
334         if (nam->sa_len != sizeof(*sinp))
335                 return (EINVAL);
336
337         /*
338          * Must check for multicast addresses and disallow binding
339          * to them.
340          */
341         if (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
342                 return (EAFNOSUPPORT);
343
344         TCPDEBUG0;
345         inp = sotoinpcb(so);
346         KASSERT(inp != NULL, ("tcp_usr_bind: inp == NULL"));
347         INP_WLOCK(inp);
348         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
349                 error = EINVAL;
350                 goto out;
351         }
352         tp = intotcpcb(inp);
353         TCPDEBUG1();
354         INP_HASH_WLOCK(&V_tcbinfo);
355         error = in_pcbbind(inp, nam, td->td_ucred);
356         INP_HASH_WUNLOCK(&V_tcbinfo);
357 out:
358         TCPDEBUG2(PRU_BIND);
359         TCP_PROBE2(debug__user, tp, PRU_BIND);
360         INP_WUNLOCK(inp);
361
362         return (error);
363 }
364 #endif /* INET */
365
366 #ifdef INET6
367 static int
368 tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
369 {
370         int error = 0;
371         struct inpcb *inp;
372         struct tcpcb *tp = NULL;
373         struct sockaddr_in6 *sin6;
374         u_char vflagsav;
375
376         sin6 = (struct sockaddr_in6 *)nam;
377         if (nam->sa_family != AF_INET6)
378                 return (EAFNOSUPPORT);
379         if (nam->sa_len != sizeof(*sin6))
380                 return (EINVAL);
381
382         /*
383          * Must check for multicast addresses and disallow binding
384          * to them.
385          */
386         if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
387                 return (EAFNOSUPPORT);
388
389         TCPDEBUG0;
390         inp = sotoinpcb(so);
391         KASSERT(inp != NULL, ("tcp6_usr_bind: inp == NULL"));
392         INP_WLOCK(inp);
393         vflagsav = inp->inp_vflag;
394         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
395                 error = EINVAL;
396                 goto out;
397         }
398         tp = intotcpcb(inp);
399         TCPDEBUG1();
400         INP_HASH_WLOCK(&V_tcbinfo);
401         inp->inp_vflag &= ~INP_IPV4;
402         inp->inp_vflag |= INP_IPV6;
403 #ifdef INET
404         if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
405                 if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
406                         inp->inp_vflag |= INP_IPV4;
407                 else if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
408                         struct sockaddr_in sin;
409
410                         in6_sin6_2_sin(&sin, sin6);
411                         if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
412                                 error = EAFNOSUPPORT;
413                                 INP_HASH_WUNLOCK(&V_tcbinfo);
414                                 goto out;
415                         }
416                         inp->inp_vflag |= INP_IPV4;
417                         inp->inp_vflag &= ~INP_IPV6;
418                         error = in_pcbbind(inp, (struct sockaddr *)&sin,
419                             td->td_ucred);
420                         INP_HASH_WUNLOCK(&V_tcbinfo);
421                         goto out;
422                 }
423         }
424 #endif
425         error = in6_pcbbind(inp, nam, td->td_ucred);
426         INP_HASH_WUNLOCK(&V_tcbinfo);
427 out:
428         if (error != 0)
429                 inp->inp_vflag = vflagsav;
430         TCPDEBUG2(PRU_BIND);
431         TCP_PROBE2(debug__user, tp, PRU_BIND);
432         INP_WUNLOCK(inp);
433         return (error);
434 }
435 #endif /* INET6 */
436
437 #ifdef INET
438 /*
439  * Prepare to accept connections.
440  */
441 static int
442 tcp_usr_listen(struct socket *so, int backlog, struct thread *td)
443 {
444         int error = 0;
445         struct inpcb *inp;
446         struct tcpcb *tp = NULL;
447
448         TCPDEBUG0;
449         inp = sotoinpcb(so);
450         KASSERT(inp != NULL, ("tcp_usr_listen: inp == NULL"));
451         INP_WLOCK(inp);
452         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
453                 error = EINVAL;
454                 goto out;
455         }
456         tp = intotcpcb(inp);
457         TCPDEBUG1();
458         SOCK_LOCK(so);
459         error = solisten_proto_check(so);
460         INP_HASH_WLOCK(&V_tcbinfo);
461         if (error == 0 && inp->inp_lport == 0)
462                 error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
463         INP_HASH_WUNLOCK(&V_tcbinfo);
464         if (error == 0) {
465                 tcp_state_change(tp, TCPS_LISTEN);
466                 solisten_proto(so, backlog);
467 #ifdef TCP_OFFLOAD
468                 if ((so->so_options & SO_NO_OFFLOAD) == 0)
469                         tcp_offload_listen_start(tp);
470 #endif
471         }
472         SOCK_UNLOCK(so);
473
474         if (IS_FASTOPEN(tp->t_flags))
475                 tp->t_tfo_pending = tcp_fastopen_alloc_counter();
476
477 out:
478         TCPDEBUG2(PRU_LISTEN);
479         TCP_PROBE2(debug__user, tp, PRU_LISTEN);
480         INP_WUNLOCK(inp);
481         return (error);
482 }
483 #endif /* INET */
484
485 #ifdef INET6
486 static int
487 tcp6_usr_listen(struct socket *so, int backlog, struct thread *td)
488 {
489         int error = 0;
490         struct inpcb *inp;
491         struct tcpcb *tp = NULL;
492         u_char vflagsav;
493
494         TCPDEBUG0;
495         inp = sotoinpcb(so);
496         KASSERT(inp != NULL, ("tcp6_usr_listen: inp == NULL"));
497         INP_WLOCK(inp);
498         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
499                 error = EINVAL;
500                 goto out;
501         }
502         vflagsav = inp->inp_vflag;
503         tp = intotcpcb(inp);
504         TCPDEBUG1();
505         SOCK_LOCK(so);
506         error = solisten_proto_check(so);
507         INP_HASH_WLOCK(&V_tcbinfo);
508         if (error == 0 && inp->inp_lport == 0) {
509                 inp->inp_vflag &= ~INP_IPV4;
510                 if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
511                         inp->inp_vflag |= INP_IPV4;
512                 error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
513         }
514         INP_HASH_WUNLOCK(&V_tcbinfo);
515         if (error == 0) {
516                 tcp_state_change(tp, TCPS_LISTEN);
517                 solisten_proto(so, backlog);
518 #ifdef TCP_OFFLOAD
519                 if ((so->so_options & SO_NO_OFFLOAD) == 0)
520                         tcp_offload_listen_start(tp);
521 #endif
522         }
523         SOCK_UNLOCK(so);
524
525         if (IS_FASTOPEN(tp->t_flags))
526                 tp->t_tfo_pending = tcp_fastopen_alloc_counter();
527
528         if (error != 0)
529                 inp->inp_vflag = vflagsav;
530
531 out:
532         TCPDEBUG2(PRU_LISTEN);
533         TCP_PROBE2(debug__user, tp, PRU_LISTEN);
534         INP_WUNLOCK(inp);
535         return (error);
536 }
537 #endif /* INET6 */
538
539 #ifdef INET
540 /*
541  * Initiate connection to peer.
542  * Create a template for use in transmissions on this connection.
543  * Enter SYN_SENT state, and mark socket as connecting.
544  * Start keep-alive timer, and seed output sequence space.
545  * Send initial segment on connection.
546  */
547 static int
548 tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
549 {
550         struct epoch_tracker et;
551         int error = 0;
552         struct inpcb *inp;
553         struct tcpcb *tp = NULL;
554         struct sockaddr_in *sinp;
555
556         sinp = (struct sockaddr_in *)nam;
557         if (nam->sa_family != AF_INET)
558                 return (EAFNOSUPPORT);
559         if (nam->sa_len != sizeof (*sinp))
560                 return (EINVAL);
561
562         /*
563          * Must disallow TCP ``connections'' to multicast addresses.
564          */
565         if (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
566                 return (EAFNOSUPPORT);
567         if (ntohl(sinp->sin_addr.s_addr) == INADDR_BROADCAST)
568                 return (EACCES);
569         if ((error = prison_remote_ip4(td->td_ucred, &sinp->sin_addr)) != 0)
570                 return (error);
571
572         TCPDEBUG0;
573         inp = sotoinpcb(so);
574         KASSERT(inp != NULL, ("tcp_usr_connect: inp == NULL"));
575         INP_WLOCK(inp);
576         if (inp->inp_flags & INP_TIMEWAIT) {
577                 error = EADDRINUSE;
578                 goto out;
579         }
580         if (inp->inp_flags & INP_DROPPED) {
581                 error = ECONNREFUSED;
582                 goto out;
583         }
584         tp = intotcpcb(inp);
585         TCPDEBUG1();
586         NET_EPOCH_ENTER(et);
587         if ((error = tcp_connect(tp, nam, td)) != 0)
588                 goto out_in_epoch;
589 #ifdef TCP_OFFLOAD
590         if (registered_toedevs > 0 &&
591             (so->so_options & SO_NO_OFFLOAD) == 0 &&
592             (error = tcp_offload_connect(so, nam)) == 0)
593                 goto out_in_epoch;
594 #endif
595         tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
596         error = tp->t_fb->tfb_tcp_output(tp);
597 out_in_epoch:
598         NET_EPOCH_EXIT(et);
599 out:
600         TCPDEBUG2(PRU_CONNECT);
601         TCP_PROBE2(debug__user, tp, PRU_CONNECT);
602         INP_WUNLOCK(inp);
603         return (error);
604 }
605 #endif /* INET */
606
607 #ifdef INET6
608 static int
609 tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
610 {
611         struct epoch_tracker et;
612         int error = 0;
613         struct inpcb *inp;
614         struct tcpcb *tp = NULL;
615         struct sockaddr_in6 *sin6;
616         u_int8_t incflagsav;
617         u_char vflagsav;
618
619         TCPDEBUG0;
620
621         sin6 = (struct sockaddr_in6 *)nam;
622         if (nam->sa_family != AF_INET6)
623                 return (EAFNOSUPPORT);
624         if (nam->sa_len != sizeof (*sin6))
625                 return (EINVAL);
626
627         /*
628          * Must disallow TCP ``connections'' to multicast addresses.
629          */
630         if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
631                 return (EAFNOSUPPORT);
632
633         inp = sotoinpcb(so);
634         KASSERT(inp != NULL, ("tcp6_usr_connect: inp == NULL"));
635         INP_WLOCK(inp);
636         vflagsav = inp->inp_vflag;
637         incflagsav = inp->inp_inc.inc_flags;
638         if (inp->inp_flags & INP_TIMEWAIT) {
639                 error = EADDRINUSE;
640                 goto out;
641         }
642         if (inp->inp_flags & INP_DROPPED) {
643                 error = ECONNREFUSED;
644                 goto out;
645         }
646         tp = intotcpcb(inp);
647         TCPDEBUG1();
648 #ifdef INET
649         /*
650          * XXXRW: Some confusion: V4/V6 flags relate to binding, and
651          * therefore probably require the hash lock, which isn't held here.
652          * Is this a significant problem?
653          */
654         if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
655                 struct sockaddr_in sin;
656
657                 if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
658                         error = EINVAL;
659                         goto out;
660                 }
661                 if ((inp->inp_vflag & INP_IPV4) == 0) {
662                         error = EAFNOSUPPORT;
663                         goto out;
664                 }
665
666                 in6_sin6_2_sin(&sin, sin6);
667                 if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
668                         error = EAFNOSUPPORT;
669                         goto out;
670                 }
671                 if (ntohl(sin.sin_addr.s_addr) == INADDR_BROADCAST) {
672                         error = EACCES;
673                         goto out;
674                 }
675                 if ((error = prison_remote_ip4(td->td_ucred,
676                     &sin.sin_addr)) != 0)
677                         goto out;
678                 inp->inp_vflag |= INP_IPV4;
679                 inp->inp_vflag &= ~INP_IPV6;
680                 NET_EPOCH_ENTER(et);
681                 if ((error = tcp_connect(tp, (struct sockaddr *)&sin, td)) != 0)
682                         goto out_in_epoch;
683 #ifdef TCP_OFFLOAD
684                 if (registered_toedevs > 0 &&
685                     (so->so_options & SO_NO_OFFLOAD) == 0 &&
686                     (error = tcp_offload_connect(so, nam)) == 0)
687                         goto out_in_epoch;
688 #endif
689                 error = tp->t_fb->tfb_tcp_output(tp);
690                 goto out_in_epoch;
691         } else {
692                 if ((inp->inp_vflag & INP_IPV6) == 0) {
693                         error = EAFNOSUPPORT;
694                         goto out;
695                 }
696         }
697 #endif
698         if ((error = prison_remote_ip6(td->td_ucred, &sin6->sin6_addr)) != 0)
699                 goto out;
700         inp->inp_vflag &= ~INP_IPV4;
701         inp->inp_vflag |= INP_IPV6;
702         inp->inp_inc.inc_flags |= INC_ISIPV6;
703         NET_EPOCH_ENTER(et);
704         if ((error = tcp6_connect(tp, nam, td)) != 0)
705                 goto out_in_epoch;
706 #ifdef TCP_OFFLOAD
707         if (registered_toedevs > 0 &&
708             (so->so_options & SO_NO_OFFLOAD) == 0 &&
709             (error = tcp_offload_connect(so, nam)) == 0)
710                 goto out_in_epoch;
711 #endif
712         tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
713         error = tp->t_fb->tfb_tcp_output(tp);
714 out_in_epoch:
715         NET_EPOCH_EXIT(et);
716 out:
717         /*
718          * If the implicit bind in the connect call fails, restore
719          * the flags we modified.
720          */
721         if (error != 0 && inp->inp_lport == 0) {
722                 inp->inp_vflag = vflagsav;
723                 inp->inp_inc.inc_flags = incflagsav;
724         }
725
726         TCPDEBUG2(PRU_CONNECT);
727         TCP_PROBE2(debug__user, tp, PRU_CONNECT);
728         INP_WUNLOCK(inp);
729         return (error);
730 }
731 #endif /* INET6 */
732
733 /*
734  * Initiate disconnect from peer.
735  * If connection never passed embryonic stage, just drop;
736  * else if don't need to let data drain, then can just drop anyways,
737  * else have to begin TCP shutdown process: mark socket disconnecting,
738  * drain unread data, state switch to reflect user close, and
739  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
740  * when peer sends FIN and acks ours.
741  *
742  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
743  */
744 static int
745 tcp_usr_disconnect(struct socket *so)
746 {
747         struct inpcb *inp;
748         struct tcpcb *tp = NULL;
749         struct epoch_tracker et;
750         int error = 0;
751
752         TCPDEBUG0;
753         NET_EPOCH_ENTER(et);
754         inp = sotoinpcb(so);
755         KASSERT(inp != NULL, ("tcp_usr_disconnect: inp == NULL"));
756         INP_WLOCK(inp);
757         if (inp->inp_flags & INP_TIMEWAIT)
758                 goto out;
759         if (inp->inp_flags & INP_DROPPED) {
760                 error = ECONNRESET;
761                 goto out;
762         }
763         tp = intotcpcb(inp);
764         TCPDEBUG1();
765         tcp_disconnect(tp);
766 out:
767         TCPDEBUG2(PRU_DISCONNECT);
768         TCP_PROBE2(debug__user, tp, PRU_DISCONNECT);
769         INP_WUNLOCK(inp);
770         NET_EPOCH_EXIT(et);
771         return (error);
772 }
773
774 #ifdef INET
775 /*
776  * Accept a connection.  Essentially all the work is done at higher levels;
777  * just return the address of the peer, storing through addr.
778  */
779 static int
780 tcp_usr_accept(struct socket *so, struct sockaddr **nam)
781 {
782         int error = 0;
783         struct inpcb *inp = NULL;
784         struct tcpcb *tp = NULL;
785         struct in_addr addr;
786         in_port_t port = 0;
787         TCPDEBUG0;
788
789         if (so->so_state & SS_ISDISCONNECTED)
790                 return (ECONNABORTED);
791
792         inp = sotoinpcb(so);
793         KASSERT(inp != NULL, ("tcp_usr_accept: inp == NULL"));
794         INP_WLOCK(inp);
795         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
796                 error = ECONNABORTED;
797                 goto out;
798         }
799         tp = intotcpcb(inp);
800         TCPDEBUG1();
801
802         /*
803          * We inline in_getpeeraddr and COMMON_END here, so that we can
804          * copy the data of interest and defer the malloc until after we
805          * release the lock.
806          */
807         port = inp->inp_fport;
808         addr = inp->inp_faddr;
809
810 out:
811         TCPDEBUG2(PRU_ACCEPT);
812         TCP_PROBE2(debug__user, tp, PRU_ACCEPT);
813         INP_WUNLOCK(inp);
814         if (error == 0)
815                 *nam = in_sockaddr(port, &addr);
816         return error;
817 }
818 #endif /* INET */
819
820 #ifdef INET6
821 static int
822 tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
823 {
824         struct inpcb *inp = NULL;
825         int error = 0;
826         struct tcpcb *tp = NULL;
827         struct in_addr addr;
828         struct in6_addr addr6;
829         struct epoch_tracker et;
830         in_port_t port = 0;
831         int v4 = 0;
832         TCPDEBUG0;
833
834         if (so->so_state & SS_ISDISCONNECTED)
835                 return (ECONNABORTED);
836
837         inp = sotoinpcb(so);
838         KASSERT(inp != NULL, ("tcp6_usr_accept: inp == NULL"));
839         NET_EPOCH_ENTER(et);
840         INP_WLOCK(inp);
841         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
842                 error = ECONNABORTED;
843                 goto out;
844         }
845         tp = intotcpcb(inp);
846         TCPDEBUG1();
847
848         /*
849          * We inline in6_mapped_peeraddr and COMMON_END here, so that we can
850          * copy the data of interest and defer the malloc until after we
851          * release the lock.
852          */
853         if (inp->inp_vflag & INP_IPV4) {
854                 v4 = 1;
855                 port = inp->inp_fport;
856                 addr = inp->inp_faddr;
857         } else {
858                 port = inp->inp_fport;
859                 addr6 = inp->in6p_faddr;
860         }
861
862 out:
863         TCPDEBUG2(PRU_ACCEPT);
864         TCP_PROBE2(debug__user, tp, PRU_ACCEPT);
865         INP_WUNLOCK(inp);
866         NET_EPOCH_EXIT(et);
867         if (error == 0) {
868                 if (v4)
869                         *nam = in6_v4mapsin6_sockaddr(port, &addr);
870                 else
871                         *nam = in6_sockaddr(port, &addr6);
872         }
873         return error;
874 }
875 #endif /* INET6 */
876
877 /*
878  * Mark the connection as being incapable of further output.
879  */
880 static int
881 tcp_usr_shutdown(struct socket *so)
882 {
883         int error = 0;
884         struct inpcb *inp;
885         struct tcpcb *tp = NULL;
886         struct epoch_tracker et;
887
888         TCPDEBUG0;
889         NET_EPOCH_ENTER(et);
890         inp = sotoinpcb(so);
891         KASSERT(inp != NULL, ("inp == NULL"));
892         INP_WLOCK(inp);
893         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
894                 error = ECONNRESET;
895                 goto out;
896         }
897         tp = intotcpcb(inp);
898         TCPDEBUG1();
899         socantsendmore(so);
900         tcp_usrclosed(tp);
901         if (!(inp->inp_flags & INP_DROPPED))
902                 error = tp->t_fb->tfb_tcp_output(tp);
903
904 out:
905         TCPDEBUG2(PRU_SHUTDOWN);
906         TCP_PROBE2(debug__user, tp, PRU_SHUTDOWN);
907         INP_WUNLOCK(inp);
908         NET_EPOCH_EXIT(et);
909
910         return (error);
911 }
912
913 /*
914  * After a receive, possibly send window update to peer.
915  */
916 static int
917 tcp_usr_rcvd(struct socket *so, int flags)
918 {
919         struct epoch_tracker et;
920         struct inpcb *inp;
921         struct tcpcb *tp = NULL;
922         int error = 0;
923
924         TCPDEBUG0;
925         inp = sotoinpcb(so);
926         KASSERT(inp != NULL, ("tcp_usr_rcvd: inp == NULL"));
927         INP_WLOCK(inp);
928         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
929                 error = ECONNRESET;
930                 goto out;
931         }
932         tp = intotcpcb(inp);
933         TCPDEBUG1();
934         /*
935          * For passively-created TFO connections, don't attempt a window
936          * update while still in SYN_RECEIVED as this may trigger an early
937          * SYN|ACK.  It is preferable to have the SYN|ACK be sent along with
938          * application response data, or failing that, when the DELACK timer
939          * expires.
940          */
941         if (IS_FASTOPEN(tp->t_flags) &&
942             (tp->t_state == TCPS_SYN_RECEIVED))
943                 goto out;
944         NET_EPOCH_ENTER(et);
945 #ifdef TCP_OFFLOAD
946         if (tp->t_flags & TF_TOE)
947                 tcp_offload_rcvd(tp);
948         else
949 #endif
950         tp->t_fb->tfb_tcp_output(tp);
951         NET_EPOCH_EXIT(et);
952 out:
953         TCPDEBUG2(PRU_RCVD);
954         TCP_PROBE2(debug__user, tp, PRU_RCVD);
955         INP_WUNLOCK(inp);
956         return (error);
957 }
958
959 /*
960  * Do a send by putting data in output queue and updating urgent
961  * marker if URG set.  Possibly send more data.  Unlike the other
962  * pru_*() routines, the mbuf chains are our responsibility.  We
963  * must either enqueue them or free them.  The other pru_* routines
964  * generally are caller-frees.
965  */
966 static int
967 tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
968     struct sockaddr *nam, struct mbuf *control, struct thread *td)
969 {
970         struct epoch_tracker et;
971         int error = 0;
972         struct inpcb *inp;
973         struct tcpcb *tp = NULL;
974 #ifdef INET
975 #ifdef INET6
976         struct sockaddr_in sin;
977 #endif
978         struct sockaddr_in *sinp;
979 #endif
980 #ifdef INET6
981         int isipv6;
982 #endif
983         u_int8_t incflagsav;
984         u_char vflagsav;
985         bool restoreflags;
986         TCPDEBUG0;
987
988         /*
989          * We require the pcbinfo "read lock" if we will close the socket
990          * as part of this call.
991          */
992         NET_EPOCH_ENTER(et);
993         inp = sotoinpcb(so);
994         KASSERT(inp != NULL, ("tcp_usr_send: inp == NULL"));
995         INP_WLOCK(inp);
996         vflagsav = inp->inp_vflag;
997         incflagsav = inp->inp_inc.inc_flags;
998         restoreflags = false;
999         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1000                 if (control)
1001                         m_freem(control);
1002                 error = ECONNRESET;
1003                 goto out;
1004         }
1005         if (control != NULL) {
1006                 /* TCP doesn't do control messages (rights, creds, etc) */
1007                 if (control->m_len) {
1008                         m_freem(control);
1009                         error = EINVAL;
1010                         goto out;
1011                 }
1012                 m_freem(control);       /* empty control, just free it */
1013                 control = NULL;
1014         }
1015         tp = intotcpcb(inp);
1016         if ((flags & PRUS_OOB) != 0 &&
1017             (error = tcp_pru_options_support(tp, PRUS_OOB)) != 0)
1018                 goto out;
1019
1020         TCPDEBUG1();
1021         if (nam != NULL && tp->t_state < TCPS_SYN_SENT) {
1022                 switch (nam->sa_family) {
1023 #ifdef INET
1024                 case AF_INET:
1025                         sinp = (struct sockaddr_in *)nam;
1026                         if (sinp->sin_len != sizeof(struct sockaddr_in)) {
1027                                 error = EINVAL;
1028                                 goto out;
1029                         }
1030                         if ((inp->inp_vflag & INP_IPV6) != 0) {
1031                                 error = EAFNOSUPPORT;
1032                                 goto out;
1033                         }
1034                         if (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
1035                                 error = EAFNOSUPPORT;
1036                                 goto out;
1037                         }
1038                         if (ntohl(sinp->sin_addr.s_addr) == INADDR_BROADCAST) {
1039                                 error = EACCES;
1040                                 goto out;
1041                         }
1042                         if ((error = prison_remote_ip4(td->td_ucred,
1043                             &sinp->sin_addr)))
1044                                 goto out;
1045 #ifdef INET6
1046                         isipv6 = 0;
1047 #endif
1048                         break;
1049 #endif /* INET */
1050 #ifdef INET6
1051                 case AF_INET6:
1052                 {
1053                         struct sockaddr_in6 *sin6;
1054
1055                         sin6 = (struct sockaddr_in6 *)nam;
1056                         if (sin6->sin6_len != sizeof(*sin6)) {
1057                                 error = EINVAL;
1058                                 goto out;
1059                         }
1060                         if ((inp->inp_vflag & INP_IPV6PROTO) == 0) {
1061                                 error = EAFNOSUPPORT;
1062                                 goto out;
1063                         }
1064                         if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
1065                                 error = EAFNOSUPPORT;
1066                                 goto out;
1067                         }
1068                         if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1069 #ifdef INET
1070                                 if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
1071                                         error = EINVAL;
1072                                         goto out;
1073                                 }
1074                                 if ((inp->inp_vflag & INP_IPV4) == 0) {
1075                                         error = EAFNOSUPPORT;
1076                                         goto out;
1077                                 }
1078                                 restoreflags = true;
1079                                 inp->inp_vflag &= ~INP_IPV6;
1080                                 sinp = &sin;
1081                                 in6_sin6_2_sin(sinp, sin6);
1082                                 if (IN_MULTICAST(
1083                                     ntohl(sinp->sin_addr.s_addr))) {
1084                                         error = EAFNOSUPPORT;
1085                                         goto out;
1086                                 }
1087                                 if ((error = prison_remote_ip4(td->td_ucred,
1088                                     &sinp->sin_addr)))
1089                                         goto out;
1090                                 isipv6 = 0;
1091 #else /* !INET */
1092                                 error = EAFNOSUPPORT;
1093                                 goto out;
1094 #endif /* INET */
1095                         } else {
1096                                 if ((inp->inp_vflag & INP_IPV6) == 0) {
1097                                         error = EAFNOSUPPORT;
1098                                         goto out;
1099                                 }
1100                                 restoreflags = true;
1101                                 inp->inp_vflag &= ~INP_IPV4;
1102                                 inp->inp_inc.inc_flags |= INC_ISIPV6;
1103                                 if ((error = prison_remote_ip6(td->td_ucred,
1104                                     &sin6->sin6_addr)))
1105                                         goto out;
1106                                 isipv6 = 1;
1107                         }
1108                         break;
1109                 }
1110 #endif /* INET6 */
1111                 default:
1112                         error = EAFNOSUPPORT;
1113                         goto out;
1114                 }
1115         }
1116         if (!(flags & PRUS_OOB)) {
1117                 sbappendstream(&so->so_snd, m, flags);
1118                 m = NULL;
1119                 if (nam && tp->t_state < TCPS_SYN_SENT) {
1120                         /*
1121                          * Do implied connect if not yet connected,
1122                          * initialize window to default value, and
1123                          * initialize maxseg using peer's cached MSS.
1124                          */
1125 #ifdef INET6
1126                         if (isipv6)
1127                                 error = tcp6_connect(tp, nam, td);
1128 #endif /* INET6 */
1129 #if defined(INET6) && defined(INET)
1130                         else
1131 #endif
1132 #ifdef INET
1133                                 error = tcp_connect(tp,
1134                                     (struct sockaddr *)sinp, td);
1135 #endif
1136                         /*
1137                          * The bind operation in tcp_connect succeeded. We
1138                          * no longer want to restore the flags if later
1139                          * operations fail.
1140                          */
1141                         if (error == 0 || inp->inp_lport != 0)
1142                                 restoreflags = false;
1143
1144                         if (error) {
1145                                 /* m is freed if PRUS_NOTREADY is unset. */
1146                                 sbflush(&so->so_snd);
1147                                 goto out;
1148                         }
1149                         if (IS_FASTOPEN(tp->t_flags))
1150                                 tcp_fastopen_connect(tp);
1151                         else {
1152                                 tp->snd_wnd = TTCP_CLIENT_SND_WND;
1153                                 tcp_mss(tp, -1);
1154                         }
1155                 }
1156                 if (flags & PRUS_EOF) {
1157                         /*
1158                          * Close the send side of the connection after
1159                          * the data is sent.
1160                          */
1161                         socantsendmore(so);
1162                         tcp_usrclosed(tp);
1163                 }
1164                 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
1165                     ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
1166                     (tp->t_fbyte_out == 0) &&
1167                     (so->so_snd.sb_ccc > 0)) {
1168                         tp->t_fbyte_out = ticks;
1169                         if (tp->t_fbyte_out == 0)
1170                                 tp->t_fbyte_out = 1;
1171                         if (tp->t_fbyte_out && tp->t_fbyte_in)
1172                                 tp->t_flags2 |= TF2_FBYTES_COMPLETE;
1173                 }
1174                 if (!(inp->inp_flags & INP_DROPPED) &&
1175                     !(flags & PRUS_NOTREADY)) {
1176                         if (flags & PRUS_MORETOCOME)
1177                                 tp->t_flags |= TF_MORETOCOME;
1178                         error = tp->t_fb->tfb_tcp_output(tp);
1179                         if (flags & PRUS_MORETOCOME)
1180                                 tp->t_flags &= ~TF_MORETOCOME;
1181                 }
1182         } else {
1183                 /*
1184                  * XXXRW: PRUS_EOF not implemented with PRUS_OOB?
1185                  */
1186                 SOCKBUF_LOCK(&so->so_snd);
1187                 if (sbspace(&so->so_snd) < -512) {
1188                         SOCKBUF_UNLOCK(&so->so_snd);
1189                         error = ENOBUFS;
1190                         goto out;
1191                 }
1192                 /*
1193                  * According to RFC961 (Assigned Protocols),
1194                  * the urgent pointer points to the last octet
1195                  * of urgent data.  We continue, however,
1196                  * to consider it to indicate the first octet
1197                  * of data past the urgent section.
1198                  * Otherwise, snd_up should be one lower.
1199                  */
1200                 sbappendstream_locked(&so->so_snd, m, flags);
1201                 SOCKBUF_UNLOCK(&so->so_snd);
1202                 m = NULL;
1203                 if (nam && tp->t_state < TCPS_SYN_SENT) {
1204                         /*
1205                          * Do implied connect if not yet connected,
1206                          * initialize window to default value, and
1207                          * initialize maxseg using peer's cached MSS.
1208                          */
1209
1210                         /*
1211                          * Not going to contemplate SYN|URG
1212                          */
1213                         if (IS_FASTOPEN(tp->t_flags))
1214                                 tp->t_flags &= ~TF_FASTOPEN;
1215 #ifdef INET6
1216                         if (isipv6)
1217                                 error = tcp6_connect(tp, nam, td);
1218 #endif /* INET6 */
1219 #if defined(INET6) && defined(INET)
1220                         else
1221 #endif
1222 #ifdef INET
1223                                 error = tcp_connect(tp,
1224                                     (struct sockaddr *)sinp, td);
1225 #endif
1226                         /*
1227                          * The bind operation in tcp_connect succeeded. We
1228                          * no longer want to restore the flags if later
1229                          * operations fail.
1230                          */
1231                         if (error == 0 || inp->inp_lport != 0)
1232                                 restoreflags = false;
1233
1234                         if (error != 0) {
1235                                 /* m is freed if PRUS_NOTREADY is unset. */
1236                                 sbflush(&so->so_snd);
1237                                 goto out;
1238                         }
1239                         tp->snd_wnd = TTCP_CLIENT_SND_WND;
1240                         tcp_mss(tp, -1);
1241                 }
1242                 tp->snd_up = tp->snd_una + sbavail(&so->so_snd);
1243                 if ((flags & PRUS_NOTREADY) == 0) {
1244                         tp->t_flags |= TF_FORCEDATA;
1245                         error = tp->t_fb->tfb_tcp_output(tp);
1246                         tp->t_flags &= ~TF_FORCEDATA;
1247                 }
1248         }
1249         TCP_LOG_EVENT(tp, NULL,
1250             &inp->inp_socket->so_rcv,
1251             &inp->inp_socket->so_snd,
1252             TCP_LOG_USERSEND, error,
1253             0, NULL, false);
1254
1255 out:
1256         /*
1257          * In case of PRUS_NOTREADY, the caller or tcp_usr_ready() is
1258          * responsible for freeing memory.
1259          */
1260         if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1261                 m_freem(m);
1262
1263         /*
1264          * If the request was unsuccessful and we changed flags,
1265          * restore the original flags.
1266          */
1267         if (error != 0 && restoreflags) {
1268                 inp->inp_vflag = vflagsav;
1269                 inp->inp_inc.inc_flags = incflagsav;
1270         }
1271         TCPDEBUG2((flags & PRUS_OOB) ? PRU_SENDOOB :
1272                   ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1273         TCP_PROBE2(debug__user, tp, (flags & PRUS_OOB) ? PRU_SENDOOB :
1274                    ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1275         INP_WUNLOCK(inp);
1276         NET_EPOCH_EXIT(et);
1277         return (error);
1278 }
1279
1280 static int
1281 tcp_usr_ready(struct socket *so, struct mbuf *m, int count)
1282 {
1283         struct epoch_tracker et;
1284         struct inpcb *inp;
1285         struct tcpcb *tp;
1286         int error;
1287
1288         inp = sotoinpcb(so);
1289         INP_WLOCK(inp);
1290         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1291                 INP_WUNLOCK(inp);
1292                 mb_free_notready(m, count);
1293                 return (ECONNRESET);
1294         }
1295         tp = intotcpcb(inp);
1296
1297         SOCKBUF_LOCK(&so->so_snd);
1298         error = sbready(&so->so_snd, m, count);
1299         SOCKBUF_UNLOCK(&so->so_snd);
1300         if (error == 0) {
1301                 NET_EPOCH_ENTER(et);
1302                 error = tp->t_fb->tfb_tcp_output(tp);
1303                 NET_EPOCH_EXIT(et);
1304         }
1305         INP_WUNLOCK(inp);
1306
1307         return (error);
1308 }
1309
1310 /*
1311  * Abort the TCP.  Drop the connection abruptly.
1312  */
1313 static void
1314 tcp_usr_abort(struct socket *so)
1315 {
1316         struct inpcb *inp;
1317         struct tcpcb *tp = NULL;
1318         struct epoch_tracker et;
1319         TCPDEBUG0;
1320
1321         inp = sotoinpcb(so);
1322         KASSERT(inp != NULL, ("tcp_usr_abort: inp == NULL"));
1323
1324         NET_EPOCH_ENTER(et);
1325         INP_WLOCK(inp);
1326         KASSERT(inp->inp_socket != NULL,
1327             ("tcp_usr_abort: inp_socket == NULL"));
1328
1329         /*
1330          * If we still have full TCP state, and we're not dropped, drop.
1331          */
1332         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1333             !(inp->inp_flags & INP_DROPPED)) {
1334                 tp = intotcpcb(inp);
1335                 TCPDEBUG1();
1336                 tp = tcp_drop(tp, ECONNABORTED);
1337                 if (tp == NULL)
1338                         goto dropped;
1339                 TCPDEBUG2(PRU_ABORT);
1340                 TCP_PROBE2(debug__user, tp, PRU_ABORT);
1341         }
1342         if (!(inp->inp_flags & INP_DROPPED)) {
1343                 SOCK_LOCK(so);
1344                 so->so_state |= SS_PROTOREF;
1345                 SOCK_UNLOCK(so);
1346                 inp->inp_flags |= INP_SOCKREF;
1347         }
1348         INP_WUNLOCK(inp);
1349 dropped:
1350         NET_EPOCH_EXIT(et);
1351 }
1352
1353 /*
1354  * TCP socket is closed.  Start friendly disconnect.
1355  */
1356 static void
1357 tcp_usr_close(struct socket *so)
1358 {
1359         struct inpcb *inp;
1360         struct tcpcb *tp = NULL;
1361         struct epoch_tracker et;
1362         TCPDEBUG0;
1363
1364         inp = sotoinpcb(so);
1365         KASSERT(inp != NULL, ("tcp_usr_close: inp == NULL"));
1366
1367         NET_EPOCH_ENTER(et);
1368         INP_WLOCK(inp);
1369         KASSERT(inp->inp_socket != NULL,
1370             ("tcp_usr_close: inp_socket == NULL"));
1371
1372         /*
1373          * If we still have full TCP state, and we're not dropped, initiate
1374          * a disconnect.
1375          */
1376         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1377             !(inp->inp_flags & INP_DROPPED)) {
1378                 tp = intotcpcb(inp);
1379                 TCPDEBUG1();
1380                 tcp_disconnect(tp);
1381                 TCPDEBUG2(PRU_CLOSE);
1382                 TCP_PROBE2(debug__user, tp, PRU_CLOSE);
1383         }
1384         if (!(inp->inp_flags & INP_DROPPED)) {
1385                 SOCK_LOCK(so);
1386                 so->so_state |= SS_PROTOREF;
1387                 SOCK_UNLOCK(so);
1388                 inp->inp_flags |= INP_SOCKREF;
1389         }
1390         INP_WUNLOCK(inp);
1391         NET_EPOCH_EXIT(et);
1392 }
1393
1394 static int
1395 tcp_pru_options_support(struct tcpcb *tp, int flags)
1396 {
1397         /*
1398          * If the specific TCP stack has a pru_options
1399          * specified then it does not always support
1400          * all the PRU_XX options and we must ask it.
1401          * If the function is not specified then all
1402          * of the PRU_XX options are supported.
1403          */
1404         int ret = 0;
1405
1406         if (tp->t_fb->tfb_pru_options) {
1407                 ret = (*tp->t_fb->tfb_pru_options)(tp, flags);
1408         }
1409         return (ret);
1410 }
1411
1412 /*
1413  * Receive out-of-band data.
1414  */
1415 static int
1416 tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
1417 {
1418         int error = 0;
1419         struct inpcb *inp;
1420         struct tcpcb *tp = NULL;
1421
1422         TCPDEBUG0;
1423         inp = sotoinpcb(so);
1424         KASSERT(inp != NULL, ("tcp_usr_rcvoob: inp == NULL"));
1425         INP_WLOCK(inp);
1426         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1427                 error = ECONNRESET;
1428                 goto out;
1429         }
1430         tp = intotcpcb(inp);
1431         error = tcp_pru_options_support(tp, PRUS_OOB);
1432         if (error) {
1433                 goto out;
1434         }
1435         TCPDEBUG1();
1436         if ((so->so_oobmark == 0 &&
1437              (so->so_rcv.sb_state & SBS_RCVATMARK) == 0) ||
1438             so->so_options & SO_OOBINLINE ||
1439             tp->t_oobflags & TCPOOB_HADDATA) {
1440                 error = EINVAL;
1441                 goto out;
1442         }
1443         if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
1444                 error = EWOULDBLOCK;
1445                 goto out;
1446         }
1447         m->m_len = 1;
1448         *mtod(m, caddr_t) = tp->t_iobc;
1449         if ((flags & MSG_PEEK) == 0)
1450                 tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1451
1452 out:
1453         TCPDEBUG2(PRU_RCVOOB);
1454         TCP_PROBE2(debug__user, tp, PRU_RCVOOB);
1455         INP_WUNLOCK(inp);
1456         return (error);
1457 }
1458
1459 #ifdef INET
1460 struct pr_usrreqs tcp_usrreqs = {
1461         .pru_abort =            tcp_usr_abort,
1462         .pru_accept =           tcp_usr_accept,
1463         .pru_attach =           tcp_usr_attach,
1464         .pru_bind =             tcp_usr_bind,
1465         .pru_connect =          tcp_usr_connect,
1466         .pru_control =          in_control,
1467         .pru_detach =           tcp_usr_detach,
1468         .pru_disconnect =       tcp_usr_disconnect,
1469         .pru_listen =           tcp_usr_listen,
1470         .pru_peeraddr =         in_getpeeraddr,
1471         .pru_rcvd =             tcp_usr_rcvd,
1472         .pru_rcvoob =           tcp_usr_rcvoob,
1473         .pru_send =             tcp_usr_send,
1474         .pru_ready =            tcp_usr_ready,
1475         .pru_shutdown =         tcp_usr_shutdown,
1476         .pru_sockaddr =         in_getsockaddr,
1477         .pru_sosetlabel =       in_pcbsosetlabel,
1478         .pru_close =            tcp_usr_close,
1479 };
1480 #endif /* INET */
1481
1482 #ifdef INET6
1483 struct pr_usrreqs tcp6_usrreqs = {
1484         .pru_abort =            tcp_usr_abort,
1485         .pru_accept =           tcp6_usr_accept,
1486         .pru_attach =           tcp_usr_attach,
1487         .pru_bind =             tcp6_usr_bind,
1488         .pru_connect =          tcp6_usr_connect,
1489         .pru_control =          in6_control,
1490         .pru_detach =           tcp_usr_detach,
1491         .pru_disconnect =       tcp_usr_disconnect,
1492         .pru_listen =           tcp6_usr_listen,
1493         .pru_peeraddr =         in6_mapped_peeraddr,
1494         .pru_rcvd =             tcp_usr_rcvd,
1495         .pru_rcvoob =           tcp_usr_rcvoob,
1496         .pru_send =             tcp_usr_send,
1497         .pru_ready =            tcp_usr_ready,
1498         .pru_shutdown =         tcp_usr_shutdown,
1499         .pru_sockaddr =         in6_mapped_sockaddr,
1500         .pru_sosetlabel =       in_pcbsosetlabel,
1501         .pru_close =            tcp_usr_close,
1502 };
1503 #endif /* INET6 */
1504
1505 #ifdef INET
1506 /*
1507  * Common subroutine to open a TCP connection to remote host specified
1508  * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1509  * port number if needed.  Call in_pcbconnect_setup to do the routing and
1510  * to choose a local host address (interface).  If there is an existing
1511  * incarnation of the same connection in TIME-WAIT state and if the remote
1512  * host was sending CC options and if the connection duration was < MSL, then
1513  * truncate the previous TIME-WAIT state and proceed.
1514  * Initialize connection parameters and enter SYN-SENT state.
1515  */
1516 static int
1517 tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1518 {
1519         struct inpcb *inp = tp->t_inpcb, *oinp;
1520         struct socket *so = inp->inp_socket;
1521         struct in_addr laddr;
1522         u_short lport;
1523         int error;
1524
1525         NET_EPOCH_ASSERT();
1526         INP_WLOCK_ASSERT(inp);
1527         INP_HASH_WLOCK(&V_tcbinfo);
1528
1529         if (V_tcp_require_unique_port && inp->inp_lport == 0) {
1530                 error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1531                 if (error)
1532                         goto out;
1533         }
1534
1535         /*
1536          * Cannot simply call in_pcbconnect, because there might be an
1537          * earlier incarnation of this same connection still in
1538          * TIME_WAIT state, creating an ADDRINUSE error.
1539          */
1540         laddr = inp->inp_laddr;
1541         lport = inp->inp_lport;
1542         error = in_pcbconnect_setup(inp, nam, &laddr.s_addr, &lport,
1543             &inp->inp_faddr.s_addr, &inp->inp_fport, &oinp, td->td_ucred);
1544         if (error && oinp == NULL)
1545                 goto out;
1546         if (oinp) {
1547                 error = EADDRINUSE;
1548                 goto out;
1549         }
1550         /* Handle initial bind if it hadn't been done in advance. */
1551         if (inp->inp_lport == 0) {
1552                 inp->inp_lport = lport;
1553                 if (in_pcbinshash(inp) != 0) {
1554                         inp->inp_lport = 0;
1555                         error = EAGAIN;
1556                         goto out;
1557                 }
1558         }
1559         inp->inp_laddr = laddr;
1560         in_pcbrehash(inp);
1561         INP_HASH_WUNLOCK(&V_tcbinfo);
1562
1563         /*
1564          * Compute window scaling to request:
1565          * Scale to fit into sweet spot.  See tcp_syncache.c.
1566          * XXX: This should move to tcp_output().
1567          */
1568         while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1569             (TCP_MAXWIN << tp->request_r_scale) < sb_max)
1570                 tp->request_r_scale++;
1571
1572         soisconnecting(so);
1573         TCPSTAT_INC(tcps_connattempt);
1574         tcp_state_change(tp, TCPS_SYN_SENT);
1575         tp->iss = tcp_new_isn(&inp->inp_inc);
1576         if (tp->t_flags & TF_REQ_TSTMP)
1577                 tp->ts_offset = tcp_new_ts_offset(&inp->inp_inc);
1578         tcp_sendseqinit(tp);
1579
1580         return 0;
1581
1582 out:
1583         INP_HASH_WUNLOCK(&V_tcbinfo);
1584         return (error);
1585 }
1586 #endif /* INET */
1587
1588 #ifdef INET6
1589 static int
1590 tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1591 {
1592         struct inpcb *inp = tp->t_inpcb;
1593         int error;
1594
1595         INP_WLOCK_ASSERT(inp);
1596         INP_HASH_WLOCK(&V_tcbinfo);
1597
1598         if (V_tcp_require_unique_port && inp->inp_lport == 0) {
1599                 error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1600                 if (error)
1601                         goto out;
1602         }
1603         error = in6_pcbconnect(inp, nam, td->td_ucred);
1604         if (error != 0)
1605                 goto out;
1606         INP_HASH_WUNLOCK(&V_tcbinfo);
1607
1608         /* Compute window scaling to request.  */
1609         while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1610             (TCP_MAXWIN << tp->request_r_scale) < sb_max)
1611                 tp->request_r_scale++;
1612
1613         soisconnecting(inp->inp_socket);
1614         TCPSTAT_INC(tcps_connattempt);
1615         tcp_state_change(tp, TCPS_SYN_SENT);
1616         tp->iss = tcp_new_isn(&inp->inp_inc);
1617         if (tp->t_flags & TF_REQ_TSTMP)
1618                 tp->ts_offset = tcp_new_ts_offset(&inp->inp_inc);
1619         tcp_sendseqinit(tp);
1620
1621         return 0;
1622
1623 out:
1624         INP_HASH_WUNLOCK(&V_tcbinfo);
1625         return error;
1626 }
1627 #endif /* INET6 */
1628
1629 /*
1630  * Export TCP internal state information via a struct tcp_info, based on the
1631  * Linux 2.6 API.  Not ABI compatible as our constants are mapped differently
1632  * (TCP state machine, etc).  We export all information using FreeBSD-native
1633  * constants -- for example, the numeric values for tcpi_state will differ
1634  * from Linux.
1635  */
1636 static void
1637 tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti)
1638 {
1639
1640         INP_WLOCK_ASSERT(tp->t_inpcb);
1641         bzero(ti, sizeof(*ti));
1642
1643         ti->tcpi_state = tp->t_state;
1644         if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
1645                 ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1646         if (tp->t_flags & TF_SACK_PERMIT)
1647                 ti->tcpi_options |= TCPI_OPT_SACK;
1648         if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
1649                 ti->tcpi_options |= TCPI_OPT_WSCALE;
1650                 ti->tcpi_snd_wscale = tp->snd_scale;
1651                 ti->tcpi_rcv_wscale = tp->rcv_scale;
1652         }
1653         if (tp->t_flags2 & TF2_ECN_PERMIT)
1654                 ti->tcpi_options |= TCPI_OPT_ECN;
1655
1656         ti->tcpi_rto = tp->t_rxtcur * tick;
1657         ti->tcpi_last_data_recv = ((uint32_t)ticks - tp->t_rcvtime) * tick;
1658         ti->tcpi_rtt = ((u_int64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
1659         ti->tcpi_rttvar = ((u_int64_t)tp->t_rttvar * tick) >> TCP_RTTVAR_SHIFT;
1660
1661         ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1662         ti->tcpi_snd_cwnd = tp->snd_cwnd;
1663
1664         /*
1665          * FreeBSD-specific extension fields for tcp_info.
1666          */
1667         ti->tcpi_rcv_space = tp->rcv_wnd;
1668         ti->tcpi_rcv_nxt = tp->rcv_nxt;
1669         ti->tcpi_snd_wnd = tp->snd_wnd;
1670         ti->tcpi_snd_bwnd = 0;          /* Unused, kept for compat. */
1671         ti->tcpi_snd_nxt = tp->snd_nxt;
1672         ti->tcpi_snd_mss = tp->t_maxseg;
1673         ti->tcpi_rcv_mss = tp->t_maxseg;
1674         ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
1675         ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
1676         ti->tcpi_snd_zerowin = tp->t_sndzerowin;
1677 #ifdef TCP_OFFLOAD
1678         if (tp->t_flags & TF_TOE) {
1679                 ti->tcpi_options |= TCPI_OPT_TOE;
1680                 tcp_offload_tcp_info(tp, ti);
1681         }
1682 #endif
1683 }
1684
1685 /*
1686  * tcp_ctloutput() must drop the inpcb lock before performing copyin on
1687  * socket option arguments.  When it re-acquires the lock after the copy, it
1688  * has to revalidate that the connection is still valid for the socket
1689  * option.
1690  */
1691 #define INP_WLOCK_RECHECK_CLEANUP(inp, cleanup) do {                    \
1692         INP_WLOCK(inp);                                                 \
1693         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {            \
1694                 INP_WUNLOCK(inp);                                       \
1695                 cleanup;                                                \
1696                 return (ECONNRESET);                                    \
1697         }                                                               \
1698         tp = intotcpcb(inp);                                            \
1699 } while(0)
1700 #define INP_WLOCK_RECHECK(inp) INP_WLOCK_RECHECK_CLEANUP((inp), /* noop */)
1701
1702 int
1703 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
1704 {
1705         int     error;
1706         struct  inpcb *inp;
1707         struct  tcpcb *tp;
1708         struct tcp_function_block *blk;
1709         struct tcp_function_set fsn;
1710
1711         error = 0;
1712         inp = sotoinpcb(so);
1713         KASSERT(inp != NULL, ("tcp_ctloutput: inp == NULL"));
1714         if (sopt->sopt_level != IPPROTO_TCP) {
1715 #ifdef INET6
1716                 if (inp->inp_vflag & INP_IPV6PROTO) {
1717                         error = ip6_ctloutput(so, sopt);
1718                         /*
1719                          * In case of the IPV6_USE_MIN_MTU socket option,
1720                          * the INC_IPV6MINMTU flag to announce a corresponding
1721                          * MSS during the initial handshake.
1722                          * If the TCP connection is not in the front states,
1723                          * just reduce the MSS being used.
1724                          * This avoids the sending of TCP segments which will
1725                          * be fragmented at the IPv6 layer.
1726                          */
1727                         if ((error == 0) &&
1728                             (sopt->sopt_dir == SOPT_SET) &&
1729                             (sopt->sopt_level == IPPROTO_IPV6) &&
1730                             (sopt->sopt_name == IPV6_USE_MIN_MTU)) {
1731                                 INP_WLOCK(inp);
1732                                 if ((inp->inp_flags &
1733                                     (INP_TIMEWAIT | INP_DROPPED))) {
1734                                         INP_WUNLOCK(inp);
1735                                         return (ECONNRESET);
1736                                 }
1737                                 inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
1738                                 tp = intotcpcb(inp);
1739                                 if ((tp->t_state >= TCPS_SYN_SENT) &&
1740                                     (inp->inp_inc.inc_flags & INC_ISIPV6)) {
1741                                         struct ip6_pktopts *opt;
1742
1743                                         opt = inp->in6p_outputopts;
1744                                         if ((opt != NULL) &&
1745                                             (opt->ip6po_minmtu ==
1746                                             IP6PO_MINMTU_ALL)) {
1747                                                 if (tp->t_maxseg > TCP6_MSS) {
1748                                                         tp->t_maxseg = TCP6_MSS;
1749                                                 }
1750                                         }
1751                                 }
1752                                 INP_WUNLOCK(inp);
1753                         }
1754                 }
1755 #endif /* INET6 */
1756 #if defined(INET6) && defined(INET)
1757                 else
1758 #endif
1759 #ifdef INET
1760                 {
1761                         error = ip_ctloutput(so, sopt);
1762                 }
1763 #endif
1764                 return (error);
1765         }
1766         INP_WLOCK(inp);
1767         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1768                 INP_WUNLOCK(inp);
1769                 return (ECONNRESET);
1770         }
1771         tp = intotcpcb(inp);
1772         /*
1773          * Protect the TCP option TCP_FUNCTION_BLK so
1774          * that a sub-function can *never* overwrite this.
1775          */
1776         if ((sopt->sopt_dir == SOPT_SET) &&
1777             (sopt->sopt_name == TCP_FUNCTION_BLK)) {
1778                 INP_WUNLOCK(inp);
1779                 error = sooptcopyin(sopt, &fsn, sizeof fsn,
1780                     sizeof fsn);
1781                 if (error)
1782                         return (error);
1783                 INP_WLOCK_RECHECK(inp);
1784                 blk = find_and_ref_tcp_functions(&fsn);
1785                 if (blk == NULL) {
1786                         INP_WUNLOCK(inp);
1787                         return (ENOENT);
1788                 }
1789                 if (tp->t_fb == blk) {
1790                         /* You already have this */
1791                         refcount_release(&blk->tfb_refcnt);
1792                         INP_WUNLOCK(inp);
1793                         return (0);
1794                 }
1795                 if (tp->t_state != TCPS_CLOSED) {
1796                         /*
1797                          * The user has advanced the state
1798                          * past the initial point, we may not
1799                          * be able to switch.
1800                          */
1801                         if (blk->tfb_tcp_handoff_ok != NULL) {
1802                                 /*
1803                                  * Does the stack provide a
1804                                  * query mechanism, if so it may
1805                                  * still be possible?
1806                                  */
1807                                 error = (*blk->tfb_tcp_handoff_ok)(tp);
1808                         } else
1809                                 error = EINVAL;
1810                         if (error) {
1811                                 refcount_release(&blk->tfb_refcnt);
1812                                 INP_WUNLOCK(inp);
1813                                 return(error);
1814                         }
1815                 }
1816                 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1817                         refcount_release(&blk->tfb_refcnt);
1818                         INP_WUNLOCK(inp);
1819                         return (ENOENT);
1820                 }
1821                 /*
1822                  * Release the old refcnt, the
1823                  * lookup acquired a ref on the
1824                  * new one already.
1825                  */
1826                 if (tp->t_fb->tfb_tcp_fb_fini) {
1827                         struct epoch_tracker et;
1828                         /*
1829                          * Tell the stack to cleanup with 0 i.e.
1830                          * the tcb is not going away.
1831                          */
1832                         NET_EPOCH_ENTER(et);
1833                         (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
1834                         NET_EPOCH_EXIT(et);
1835                 }
1836 #ifdef TCPHPTS
1837                 /* Assure that we are not on any hpts */
1838                 tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_ALL);
1839 #endif
1840                 if (blk->tfb_tcp_fb_init) {
1841                         error = (*blk->tfb_tcp_fb_init)(tp);
1842                         if (error) {
1843                                 refcount_release(&blk->tfb_refcnt);
1844                                 if (tp->t_fb->tfb_tcp_fb_init) {
1845                                         if((*tp->t_fb->tfb_tcp_fb_init)(tp) != 0)  {
1846                                                 /* Fall back failed, drop the connection */
1847                                                 INP_WUNLOCK(inp);
1848                                                 soabort(so);
1849                                                 return(error);
1850                                         }
1851                                 }
1852                                 goto err_out;
1853                         }
1854                 }
1855                 refcount_release(&tp->t_fb->tfb_refcnt);
1856                 tp->t_fb = blk;
1857 #ifdef TCP_OFFLOAD
1858                 if (tp->t_flags & TF_TOE) {
1859                         tcp_offload_ctloutput(tp, sopt->sopt_dir,
1860                              sopt->sopt_name);
1861                 }
1862 #endif
1863 err_out:
1864                 INP_WUNLOCK(inp);
1865                 return (error);
1866         } else if ((sopt->sopt_dir == SOPT_GET) &&
1867             (sopt->sopt_name == TCP_FUNCTION_BLK)) {
1868                 strncpy(fsn.function_set_name, tp->t_fb->tfb_tcp_block_name,
1869                     TCP_FUNCTION_NAME_LEN_MAX);
1870                 fsn.function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
1871                 fsn.pcbcnt = tp->t_fb->tfb_refcnt;
1872                 INP_WUNLOCK(inp);
1873                 error = sooptcopyout(sopt, &fsn, sizeof fsn);
1874                 return (error);
1875         }
1876         /* Pass in the INP locked, called must unlock it */
1877         return (tp->t_fb->tfb_tcp_ctloutput(so, sopt, inp, tp));
1878 }
1879
1880 /*
1881  * If this assert becomes untrue, we need to change the size of the buf
1882  * variable in tcp_default_ctloutput().
1883  */
1884 #ifdef CTASSERT
1885 CTASSERT(TCP_CA_NAME_MAX <= TCP_LOG_ID_LEN);
1886 CTASSERT(TCP_LOG_REASON_LEN <= TCP_LOG_ID_LEN);
1887 #endif
1888
1889 #ifdef KERN_TLS
1890 static int
1891 copyin_tls_enable(struct sockopt *sopt, struct tls_enable *tls)
1892 {
1893         struct tls_enable_v0 tls_v0;
1894         int error;
1895
1896         if (sopt->sopt_valsize == sizeof(tls_v0)) {
1897                 error = sooptcopyin(sopt, &tls_v0, sizeof(tls_v0),
1898                     sizeof(tls_v0));
1899                 if (error)
1900                         return (error);
1901                 memset(tls, 0, sizeof(*tls));
1902                 tls->cipher_key = tls_v0.cipher_key;
1903                 tls->iv = tls_v0.iv;
1904                 tls->auth_key = tls_v0.auth_key;
1905                 tls->cipher_algorithm = tls_v0.cipher_algorithm;
1906                 tls->cipher_key_len = tls_v0.cipher_key_len;
1907                 tls->iv_len = tls_v0.iv_len;
1908                 tls->auth_algorithm = tls_v0.auth_algorithm;
1909                 tls->auth_key_len = tls_v0.auth_key_len;
1910                 tls->flags = tls_v0.flags;
1911                 tls->tls_vmajor = tls_v0.tls_vmajor;
1912                 tls->tls_vminor = tls_v0.tls_vminor;
1913                 return (0);
1914         }
1915
1916         return (sooptcopyin(sopt, tls, sizeof(*tls), sizeof(*tls)));
1917 }
1918 #endif
1919
1920 int
1921 tcp_default_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
1922 {
1923         int     error, opt, optval;
1924         u_int   ui;
1925         struct  tcp_info ti;
1926 #ifdef KERN_TLS
1927         struct tls_enable tls;
1928 #endif
1929         struct cc_algo *algo;
1930         char    *pbuf, buf[TCP_LOG_ID_LEN];
1931 #ifdef STATS
1932         struct statsblob *sbp;
1933 #endif
1934         size_t  len;
1935
1936         /*
1937          * For TCP_CCALGOOPT forward the control to CC module, for both
1938          * SOPT_SET and SOPT_GET.
1939          */
1940         switch (sopt->sopt_name) {
1941         case TCP_CCALGOOPT:
1942                 INP_WUNLOCK(inp);
1943                 if (sopt->sopt_valsize > CC_ALGOOPT_LIMIT)
1944                         return (EINVAL);
1945                 pbuf = malloc(sopt->sopt_valsize, M_TEMP, M_WAITOK | M_ZERO);
1946                 error = sooptcopyin(sopt, pbuf, sopt->sopt_valsize,
1947                     sopt->sopt_valsize);
1948                 if (error) {
1949                         free(pbuf, M_TEMP);
1950                         return (error);
1951                 }
1952                 INP_WLOCK_RECHECK_CLEANUP(inp, free(pbuf, M_TEMP));
1953                 if (CC_ALGO(tp)->ctl_output != NULL)
1954                         error = CC_ALGO(tp)->ctl_output(tp->ccv, sopt, pbuf);
1955                 else
1956                         error = ENOENT;
1957                 INP_WUNLOCK(inp);
1958                 if (error == 0 && sopt->sopt_dir == SOPT_GET)
1959                         error = sooptcopyout(sopt, pbuf, sopt->sopt_valsize);
1960                 free(pbuf, M_TEMP);
1961                 return (error);
1962         }
1963
1964         switch (sopt->sopt_dir) {
1965         case SOPT_SET:
1966                 switch (sopt->sopt_name) {
1967 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1968                 case TCP_MD5SIG:
1969                         INP_WUNLOCK(inp);
1970                         if (!TCPMD5_ENABLED())
1971                                 return (ENOPROTOOPT);
1972                         error = TCPMD5_PCBCTL(inp, sopt);
1973                         if (error)
1974                                 return (error);
1975                         INP_WLOCK_RECHECK(inp);
1976                         goto unlock_and_done;
1977 #endif /* IPSEC */
1978
1979                 case TCP_NODELAY:
1980                 case TCP_NOOPT:
1981                         INP_WUNLOCK(inp);
1982                         error = sooptcopyin(sopt, &optval, sizeof optval,
1983                             sizeof optval);
1984                         if (error)
1985                                 return (error);
1986
1987                         INP_WLOCK_RECHECK(inp);
1988                         switch (sopt->sopt_name) {
1989                         case TCP_NODELAY:
1990                                 opt = TF_NODELAY;
1991                                 break;
1992                         case TCP_NOOPT:
1993                                 opt = TF_NOOPT;
1994                                 break;
1995                         default:
1996                                 opt = 0; /* dead code to fool gcc */
1997                                 break;
1998                         }
1999
2000                         if (optval)
2001                                 tp->t_flags |= opt;
2002                         else
2003                                 tp->t_flags &= ~opt;
2004 unlock_and_done:
2005 #ifdef TCP_OFFLOAD
2006                         if (tp->t_flags & TF_TOE) {
2007                                 tcp_offload_ctloutput(tp, sopt->sopt_dir,
2008                                     sopt->sopt_name);
2009                         }
2010 #endif
2011                         INP_WUNLOCK(inp);
2012                         break;
2013
2014                 case TCP_NOPUSH:
2015                         INP_WUNLOCK(inp);
2016                         error = sooptcopyin(sopt, &optval, sizeof optval,
2017                             sizeof optval);
2018                         if (error)
2019                                 return (error);
2020
2021                         INP_WLOCK_RECHECK(inp);
2022                         if (optval)
2023                                 tp->t_flags |= TF_NOPUSH;
2024                         else if (tp->t_flags & TF_NOPUSH) {
2025                                 tp->t_flags &= ~TF_NOPUSH;
2026                                 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2027                                         struct epoch_tracker et;
2028
2029                                         NET_EPOCH_ENTER(et);
2030                                         error = tp->t_fb->tfb_tcp_output(tp);
2031                                         NET_EPOCH_EXIT(et);
2032                                 }
2033                         }
2034                         goto unlock_and_done;
2035
2036                 case TCP_REMOTE_UDP_ENCAPS_PORT:
2037                         INP_WUNLOCK(inp);
2038                         error = sooptcopyin(sopt, &optval, sizeof optval,
2039                             sizeof optval);
2040                         if (error)
2041                                 return (error);
2042                         if ((optval < TCP_TUNNELING_PORT_MIN) ||
2043                             (optval > TCP_TUNNELING_PORT_MAX)) {
2044                                 /* Its got to be in range */
2045                                 return (EINVAL);
2046                         }
2047                         if ((V_tcp_udp_tunneling_port == 0) && (optval != 0)) {
2048                                 /* You have to have enabled a UDP tunneling port first */
2049                                 return (EINVAL);
2050                         }
2051                         INP_WLOCK_RECHECK(inp);
2052                         if (tp->t_state != TCPS_CLOSED) {
2053                                 /* You can't change after you are connected */
2054                                 error = EINVAL;
2055                         } else {
2056                                 /* Ok we are all good set the port */
2057                                 tp->t_port = htons(optval);
2058                         }
2059                         goto unlock_and_done;
2060
2061                 case TCP_MAXSEG:
2062                         INP_WUNLOCK(inp);
2063                         error = sooptcopyin(sopt, &optval, sizeof optval,
2064                             sizeof optval);
2065                         if (error)
2066                                 return (error);
2067
2068                         INP_WLOCK_RECHECK(inp);
2069                         if (optval > 0 && optval <= tp->t_maxseg &&
2070                             optval + 40 >= V_tcp_minmss)
2071                                 tp->t_maxseg = optval;
2072                         else
2073                                 error = EINVAL;
2074                         goto unlock_and_done;
2075
2076                 case TCP_INFO:
2077                         INP_WUNLOCK(inp);
2078                         error = EINVAL;
2079                         break;
2080
2081                 case TCP_STATS:
2082                         INP_WUNLOCK(inp);
2083 #ifdef STATS
2084                         error = sooptcopyin(sopt, &optval, sizeof optval,
2085                             sizeof optval);
2086                         if (error)
2087                                 return (error);
2088
2089                         if (optval > 0)
2090                                 sbp = stats_blob_alloc(
2091                                     V_tcp_perconn_stats_dflt_tpl, 0);
2092                         else
2093                                 sbp = NULL;
2094
2095                         INP_WLOCK_RECHECK(inp);
2096                         if ((tp->t_stats != NULL && sbp == NULL) ||
2097                             (tp->t_stats == NULL && sbp != NULL)) {
2098                                 struct statsblob *t = tp->t_stats;
2099                                 tp->t_stats = sbp;
2100                                 sbp = t;
2101                         }
2102                         INP_WUNLOCK(inp);
2103
2104                         stats_blob_destroy(sbp);
2105 #else
2106                         return (EOPNOTSUPP);
2107 #endif /* !STATS */
2108                         break;
2109
2110                 case TCP_CONGESTION:
2111                         INP_WUNLOCK(inp);
2112                         error = sooptcopyin(sopt, buf, TCP_CA_NAME_MAX - 1, 1);
2113                         if (error)
2114                                 break;
2115                         buf[sopt->sopt_valsize] = '\0';
2116                         INP_WLOCK_RECHECK(inp);
2117                         CC_LIST_RLOCK();
2118                         STAILQ_FOREACH(algo, &cc_list, entries)
2119                                 if (strncmp(buf, algo->name,
2120                                     TCP_CA_NAME_MAX) == 0)
2121                                         break;
2122                         CC_LIST_RUNLOCK();
2123                         if (algo == NULL) {
2124                                 INP_WUNLOCK(inp);
2125                                 error = EINVAL;
2126                                 break;
2127                         }
2128                         /*
2129                          * We hold a write lock over the tcb so it's safe to
2130                          * do these things without ordering concerns.
2131                          */
2132                         if (CC_ALGO(tp)->cb_destroy != NULL)
2133                                 CC_ALGO(tp)->cb_destroy(tp->ccv);
2134                         CC_DATA(tp) = NULL;
2135                         CC_ALGO(tp) = algo;
2136                         /*
2137                          * If something goes pear shaped initialising the new
2138                          * algo, fall back to newreno (which does not
2139                          * require initialisation).
2140                          */
2141                         if (algo->cb_init != NULL &&
2142                             algo->cb_init(tp->ccv) != 0) {
2143                                 CC_ALGO(tp) = &newreno_cc_algo;
2144                                 /*
2145                                  * The only reason init should fail is
2146                                  * because of malloc.
2147                                  */
2148                                 error = ENOMEM;
2149                         }
2150                         INP_WUNLOCK(inp);
2151                         break;
2152
2153                 case TCP_REUSPORT_LB_NUMA:
2154                         INP_WUNLOCK(inp);
2155                         error = sooptcopyin(sopt, &optval, sizeof(optval),
2156                             sizeof(optval));
2157                         INP_WLOCK_RECHECK(inp);
2158                         if (!error)
2159                                 error = in_pcblbgroup_numa(inp, optval);
2160                         INP_WUNLOCK(inp);
2161                         break;
2162
2163 #ifdef KERN_TLS
2164                 case TCP_TXTLS_ENABLE:
2165                         INP_WUNLOCK(inp);
2166                         error = copyin_tls_enable(sopt, &tls);
2167                         if (error)
2168                                 break;
2169                         error = ktls_enable_tx(so, &tls);
2170                         break;
2171                 case TCP_TXTLS_MODE:
2172                         INP_WUNLOCK(inp);
2173                         error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2174                         if (error)
2175                                 return (error);
2176
2177                         INP_WLOCK_RECHECK(inp);
2178                         error = ktls_set_tx_mode(so, ui);
2179                         INP_WUNLOCK(inp);
2180                         break;
2181                 case TCP_RXTLS_ENABLE:
2182                         INP_WUNLOCK(inp);
2183                         error = sooptcopyin(sopt, &tls, sizeof(tls),
2184                             sizeof(tls));
2185                         if (error)
2186                                 break;
2187                         error = ktls_enable_rx(so, &tls);
2188                         break;
2189 #endif
2190
2191                 case TCP_KEEPIDLE:
2192                 case TCP_KEEPINTVL:
2193                 case TCP_KEEPINIT:
2194                         INP_WUNLOCK(inp);
2195                         error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2196                         if (error)
2197                                 return (error);
2198
2199                         if (ui > (UINT_MAX / hz)) {
2200                                 error = EINVAL;
2201                                 break;
2202                         }
2203                         ui *= hz;
2204
2205                         INP_WLOCK_RECHECK(inp);
2206                         switch (sopt->sopt_name) {
2207                         case TCP_KEEPIDLE:
2208                                 tp->t_keepidle = ui;
2209                                 /*
2210                                  * XXX: better check current remaining
2211                                  * timeout and "merge" it with new value.
2212                                  */
2213                                 if ((tp->t_state > TCPS_LISTEN) &&
2214                                     (tp->t_state <= TCPS_CLOSING))
2215                                         tcp_timer_activate(tp, TT_KEEP,
2216                                             TP_KEEPIDLE(tp));
2217                                 break;
2218                         case TCP_KEEPINTVL:
2219                                 tp->t_keepintvl = ui;
2220                                 if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2221                                     (TP_MAXIDLE(tp) > 0))
2222                                         tcp_timer_activate(tp, TT_2MSL,
2223                                             TP_MAXIDLE(tp));
2224                                 break;
2225                         case TCP_KEEPINIT:
2226                                 tp->t_keepinit = ui;
2227                                 if (tp->t_state == TCPS_SYN_RECEIVED ||
2228                                     tp->t_state == TCPS_SYN_SENT)
2229                                         tcp_timer_activate(tp, TT_KEEP,
2230                                             TP_KEEPINIT(tp));
2231                                 break;
2232                         }
2233                         goto unlock_and_done;
2234
2235                 case TCP_KEEPCNT:
2236                         INP_WUNLOCK(inp);
2237                         error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2238                         if (error)
2239                                 return (error);
2240
2241                         INP_WLOCK_RECHECK(inp);
2242                         tp->t_keepcnt = ui;
2243                         if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2244                             (TP_MAXIDLE(tp) > 0))
2245                                 tcp_timer_activate(tp, TT_2MSL,
2246                                     TP_MAXIDLE(tp));
2247                         goto unlock_and_done;
2248
2249 #ifdef TCPPCAP
2250                 case TCP_PCAP_OUT:
2251                 case TCP_PCAP_IN:
2252                         INP_WUNLOCK(inp);
2253                         error = sooptcopyin(sopt, &optval, sizeof optval,
2254                             sizeof optval);
2255                         if (error)
2256                                 return (error);
2257
2258                         INP_WLOCK_RECHECK(inp);
2259                         if (optval >= 0)
2260                                 tcp_pcap_set_sock_max(
2261                                         (sopt->sopt_name == TCP_PCAP_OUT) ?
2262                                         &(tp->t_outpkts) : &(tp->t_inpkts),
2263                                         optval);
2264                         else
2265                                 error = EINVAL;
2266                         goto unlock_and_done;
2267 #endif
2268
2269                 case TCP_FASTOPEN: {
2270                         struct tcp_fastopen tfo_optval;
2271
2272                         INP_WUNLOCK(inp);
2273                         if (!V_tcp_fastopen_client_enable &&
2274                             !V_tcp_fastopen_server_enable)
2275                                 return (EPERM);
2276
2277                         error = sooptcopyin(sopt, &tfo_optval,
2278                                     sizeof(tfo_optval), sizeof(int));
2279                         if (error)
2280                                 return (error);
2281
2282                         INP_WLOCK_RECHECK(inp);
2283                         if ((tp->t_state != TCPS_CLOSED) &&
2284                             (tp->t_state != TCPS_LISTEN)) {
2285                                 error = EINVAL;
2286                                 goto unlock_and_done;
2287                         }
2288                         if (tfo_optval.enable) {
2289                                 if (tp->t_state == TCPS_LISTEN) {
2290                                         if (!V_tcp_fastopen_server_enable) {
2291                                                 error = EPERM;
2292                                                 goto unlock_and_done;
2293                                         }
2294
2295                                         if (tp->t_tfo_pending == NULL)
2296                                                 tp->t_tfo_pending =
2297                                                     tcp_fastopen_alloc_counter();
2298                                 } else {
2299                                         /*
2300                                          * If a pre-shared key was provided,
2301                                          * stash it in the client cookie
2302                                          * field of the tcpcb for use during
2303                                          * connect.
2304                                          */
2305                                         if (sopt->sopt_valsize ==
2306                                             sizeof(tfo_optval)) {
2307                                                 memcpy(tp->t_tfo_cookie.client,
2308                                                        tfo_optval.psk,
2309                                                        TCP_FASTOPEN_PSK_LEN);
2310                                                 tp->t_tfo_client_cookie_len =
2311                                                     TCP_FASTOPEN_PSK_LEN;
2312                                         }
2313                                 }
2314                                 tp->t_flags |= TF_FASTOPEN;
2315                         } else
2316                                 tp->t_flags &= ~TF_FASTOPEN;
2317                         goto unlock_and_done;
2318                 }
2319
2320 #ifdef TCP_BLACKBOX
2321                 case TCP_LOG:
2322                         INP_WUNLOCK(inp);
2323                         error = sooptcopyin(sopt, &optval, sizeof optval,
2324                             sizeof optval);
2325                         if (error)
2326                                 return (error);
2327
2328                         INP_WLOCK_RECHECK(inp);
2329                         error = tcp_log_state_change(tp, optval);
2330                         goto unlock_and_done;
2331
2332                 case TCP_LOGBUF:
2333                         INP_WUNLOCK(inp);
2334                         error = EINVAL;
2335                         break;
2336
2337                 case TCP_LOGID:
2338                         INP_WUNLOCK(inp);
2339                         error = sooptcopyin(sopt, buf, TCP_LOG_ID_LEN - 1, 0);
2340                         if (error)
2341                                 break;
2342                         buf[sopt->sopt_valsize] = '\0';
2343                         INP_WLOCK_RECHECK(inp);
2344                         error = tcp_log_set_id(tp, buf);
2345                         /* tcp_log_set_id() unlocks the INP. */
2346                         break;
2347
2348                 case TCP_LOGDUMP:
2349                 case TCP_LOGDUMPID:
2350                         INP_WUNLOCK(inp);
2351                         error =
2352                             sooptcopyin(sopt, buf, TCP_LOG_REASON_LEN - 1, 0);
2353                         if (error)
2354                                 break;
2355                         buf[sopt->sopt_valsize] = '\0';
2356                         INP_WLOCK_RECHECK(inp);
2357                         if (sopt->sopt_name == TCP_LOGDUMP) {
2358                                 error = tcp_log_dump_tp_logbuf(tp, buf,
2359                                     M_WAITOK, true);
2360                                 INP_WUNLOCK(inp);
2361                         } else {
2362                                 tcp_log_dump_tp_bucket_logbufs(tp, buf);
2363                                 /*
2364                                  * tcp_log_dump_tp_bucket_logbufs() drops the
2365                                  * INP lock.
2366                                  */
2367                         }
2368                         break;
2369 #endif
2370
2371                 default:
2372                         INP_WUNLOCK(inp);
2373                         error = ENOPROTOOPT;
2374                         break;
2375                 }
2376                 break;
2377
2378         case SOPT_GET:
2379                 tp = intotcpcb(inp);
2380                 switch (sopt->sopt_name) {
2381 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2382                 case TCP_MD5SIG:
2383                         INP_WUNLOCK(inp);
2384                         if (!TCPMD5_ENABLED())
2385                                 return (ENOPROTOOPT);
2386                         error = TCPMD5_PCBCTL(inp, sopt);
2387                         break;
2388 #endif
2389
2390                 case TCP_NODELAY:
2391                         optval = tp->t_flags & TF_NODELAY;
2392                         INP_WUNLOCK(inp);
2393                         error = sooptcopyout(sopt, &optval, sizeof optval);
2394                         break;
2395                 case TCP_MAXSEG:
2396                         optval = tp->t_maxseg;
2397                         INP_WUNLOCK(inp);
2398                         error = sooptcopyout(sopt, &optval, sizeof optval);
2399                         break;
2400                 case TCP_REMOTE_UDP_ENCAPS_PORT:
2401                         optval = ntohs(tp->t_port);
2402                         INP_WUNLOCK(inp);
2403                         error = sooptcopyout(sopt, &optval, sizeof optval);
2404                         break;
2405                 case TCP_NOOPT:
2406                         optval = tp->t_flags & TF_NOOPT;
2407                         INP_WUNLOCK(inp);
2408                         error = sooptcopyout(sopt, &optval, sizeof optval);
2409                         break;
2410                 case TCP_NOPUSH:
2411                         optval = tp->t_flags & TF_NOPUSH;
2412                         INP_WUNLOCK(inp);
2413                         error = sooptcopyout(sopt, &optval, sizeof optval);
2414                         break;
2415                 case TCP_INFO:
2416                         tcp_fill_info(tp, &ti);
2417                         INP_WUNLOCK(inp);
2418                         error = sooptcopyout(sopt, &ti, sizeof ti);
2419                         break;
2420                 case TCP_STATS:
2421                         {
2422 #ifdef STATS
2423                         int nheld;
2424                         TYPEOF_MEMBER(struct statsblob, flags) sbflags = 0;
2425
2426                         error = 0;
2427                         socklen_t outsbsz = sopt->sopt_valsize;
2428                         if (tp->t_stats == NULL)
2429                                 error = ENOENT;
2430                         else if (outsbsz >= tp->t_stats->cursz)
2431                                 outsbsz = tp->t_stats->cursz;
2432                         else if (outsbsz >= sizeof(struct statsblob))
2433                                 outsbsz = sizeof(struct statsblob);
2434                         else
2435                                 error = EINVAL;
2436                         INP_WUNLOCK(inp);
2437                         if (error)
2438                                 break;
2439
2440                         sbp = sopt->sopt_val;
2441                         nheld = atop(round_page(((vm_offset_t)sbp) +
2442                             (vm_size_t)outsbsz) - trunc_page((vm_offset_t)sbp));
2443                         vm_page_t ma[nheld];
2444                         if (vm_fault_quick_hold_pages(
2445                             &curproc->p_vmspace->vm_map, (vm_offset_t)sbp,
2446                             outsbsz, VM_PROT_READ | VM_PROT_WRITE, ma,
2447                             nheld) < 0) {
2448                                 error = EFAULT;
2449                                 break;
2450                         }
2451
2452                         if ((error = copyin_nofault(&(sbp->flags), &sbflags,
2453                             SIZEOF_MEMBER(struct statsblob, flags))))
2454                                 goto unhold;
2455
2456                         INP_WLOCK_RECHECK(inp);
2457                         error = stats_blob_snapshot(&sbp, outsbsz, tp->t_stats,
2458                             sbflags | SB_CLONE_USRDSTNOFAULT);
2459                         INP_WUNLOCK(inp);
2460                         sopt->sopt_valsize = outsbsz;
2461 unhold:
2462                         vm_page_unhold_pages(ma, nheld);
2463 #else
2464                         INP_WUNLOCK(inp);
2465                         error = EOPNOTSUPP;
2466 #endif /* !STATS */
2467                         break;
2468                         }
2469                 case TCP_CONGESTION:
2470                         len = strlcpy(buf, CC_ALGO(tp)->name, TCP_CA_NAME_MAX);
2471                         INP_WUNLOCK(inp);
2472                         error = sooptcopyout(sopt, buf, len + 1);
2473                         break;
2474                 case TCP_KEEPIDLE:
2475                 case TCP_KEEPINTVL:
2476                 case TCP_KEEPINIT:
2477                 case TCP_KEEPCNT:
2478                         switch (sopt->sopt_name) {
2479                         case TCP_KEEPIDLE:
2480                                 ui = TP_KEEPIDLE(tp) / hz;
2481                                 break;
2482                         case TCP_KEEPINTVL:
2483                                 ui = TP_KEEPINTVL(tp) / hz;
2484                                 break;
2485                         case TCP_KEEPINIT:
2486                                 ui = TP_KEEPINIT(tp) / hz;
2487                                 break;
2488                         case TCP_KEEPCNT:
2489                                 ui = TP_KEEPCNT(tp);
2490                                 break;
2491                         }
2492                         INP_WUNLOCK(inp);
2493                         error = sooptcopyout(sopt, &ui, sizeof(ui));
2494                         break;
2495 #ifdef TCPPCAP
2496                 case TCP_PCAP_OUT:
2497                 case TCP_PCAP_IN:
2498                         optval = tcp_pcap_get_sock_max(
2499                                         (sopt->sopt_name == TCP_PCAP_OUT) ?
2500                                         &(tp->t_outpkts) : &(tp->t_inpkts));
2501                         INP_WUNLOCK(inp);
2502                         error = sooptcopyout(sopt, &optval, sizeof optval);
2503                         break;
2504 #endif
2505                 case TCP_FASTOPEN:
2506                         optval = tp->t_flags & TF_FASTOPEN;
2507                         INP_WUNLOCK(inp);
2508                         error = sooptcopyout(sopt, &optval, sizeof optval);
2509                         break;
2510 #ifdef TCP_BLACKBOX
2511                 case TCP_LOG:
2512                         optval = tp->t_logstate;
2513                         INP_WUNLOCK(inp);
2514                         error = sooptcopyout(sopt, &optval, sizeof(optval));
2515                         break;
2516                 case TCP_LOGBUF:
2517                         /* tcp_log_getlogbuf() does INP_WUNLOCK(inp) */
2518                         error = tcp_log_getlogbuf(sopt, tp);
2519                         break;
2520                 case TCP_LOGID:
2521                         len = tcp_log_get_id(tp, buf);
2522                         INP_WUNLOCK(inp);
2523                         error = sooptcopyout(sopt, buf, len + 1);
2524                         break;
2525                 case TCP_LOGDUMP:
2526                 case TCP_LOGDUMPID:
2527                         INP_WUNLOCK(inp);
2528                         error = EINVAL;
2529                         break;
2530 #endif
2531 #ifdef KERN_TLS
2532                 case TCP_TXTLS_MODE:
2533                         optval = ktls_get_tx_mode(so);
2534                         INP_WUNLOCK(inp);
2535                         error = sooptcopyout(sopt, &optval, sizeof(optval));
2536                         break;
2537                 case TCP_RXTLS_MODE:
2538                         optval = ktls_get_rx_mode(so);
2539                         INP_WUNLOCK(inp);
2540                         error = sooptcopyout(sopt, &optval, sizeof(optval));
2541                         break;
2542 #endif
2543                 default:
2544                         INP_WUNLOCK(inp);
2545                         error = ENOPROTOOPT;
2546                         break;
2547                 }
2548                 break;
2549         }
2550         return (error);
2551 }
2552 #undef INP_WLOCK_RECHECK
2553 #undef INP_WLOCK_RECHECK_CLEANUP
2554
2555 /*
2556  * Initiate (or continue) disconnect.
2557  * If embryonic state, just send reset (once).
2558  * If in ``let data drain'' option and linger null, just drop.
2559  * Otherwise (hard), mark socket disconnecting and drop
2560  * current input data; switch states based on user close, and
2561  * send segment to peer (with FIN).
2562  */
2563 static void
2564 tcp_disconnect(struct tcpcb *tp)
2565 {
2566         struct inpcb *inp = tp->t_inpcb;
2567         struct socket *so = inp->inp_socket;
2568
2569         NET_EPOCH_ASSERT();
2570         INP_WLOCK_ASSERT(inp);
2571
2572         /*
2573          * Neither tcp_close() nor tcp_drop() should return NULL, as the
2574          * socket is still open.
2575          */
2576         if (tp->t_state < TCPS_ESTABLISHED &&
2577             !(tp->t_state > TCPS_LISTEN && IS_FASTOPEN(tp->t_flags))) {
2578                 tp = tcp_close(tp);
2579                 KASSERT(tp != NULL,
2580                     ("tcp_disconnect: tcp_close() returned NULL"));
2581         } else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
2582                 tp = tcp_drop(tp, 0);
2583                 KASSERT(tp != NULL,
2584                     ("tcp_disconnect: tcp_drop() returned NULL"));
2585         } else {
2586                 soisdisconnecting(so);
2587                 sbflush(&so->so_rcv);
2588                 tcp_usrclosed(tp);
2589                 if (!(inp->inp_flags & INP_DROPPED))
2590                         tp->t_fb->tfb_tcp_output(tp);
2591         }
2592 }
2593
2594 /*
2595  * User issued close, and wish to trail through shutdown states:
2596  * if never received SYN, just forget it.  If got a SYN from peer,
2597  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
2598  * If already got a FIN from peer, then almost done; go to LAST_ACK
2599  * state.  In all other cases, have already sent FIN to peer (e.g.
2600  * after PRU_SHUTDOWN), and just have to play tedious game waiting
2601  * for peer to send FIN or not respond to keep-alives, etc.
2602  * We can let the user exit from the close as soon as the FIN is acked.
2603  */
2604 static void
2605 tcp_usrclosed(struct tcpcb *tp)
2606 {
2607
2608         NET_EPOCH_ASSERT();
2609         INP_WLOCK_ASSERT(tp->t_inpcb);
2610
2611         switch (tp->t_state) {
2612         case TCPS_LISTEN:
2613 #ifdef TCP_OFFLOAD
2614                 tcp_offload_listen_stop(tp);
2615 #endif
2616                 tcp_state_change(tp, TCPS_CLOSED);
2617                 /* FALLTHROUGH */
2618         case TCPS_CLOSED:
2619                 tp = tcp_close(tp);
2620                 /*
2621                  * tcp_close() should never return NULL here as the socket is
2622                  * still open.
2623                  */
2624                 KASSERT(tp != NULL,
2625                     ("tcp_usrclosed: tcp_close() returned NULL"));
2626                 break;
2627
2628         case TCPS_SYN_SENT:
2629         case TCPS_SYN_RECEIVED:
2630                 tp->t_flags |= TF_NEEDFIN;
2631                 break;
2632
2633         case TCPS_ESTABLISHED:
2634                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2635                 break;
2636
2637         case TCPS_CLOSE_WAIT:
2638                 tcp_state_change(tp, TCPS_LAST_ACK);
2639                 break;
2640         }
2641         if (tp->t_state >= TCPS_FIN_WAIT_2) {
2642                 soisdisconnected(tp->t_inpcb->inp_socket);
2643                 /* Prevent the connection hanging in FIN_WAIT_2 forever. */
2644                 if (tp->t_state == TCPS_FIN_WAIT_2) {
2645                         int timeout;
2646
2647                         timeout = (tcp_fast_finwait2_recycle) ?
2648                             tcp_finwait2_timeout : TP_MAXIDLE(tp);
2649                         tcp_timer_activate(tp, TT_2MSL, timeout);
2650                 }
2651         }
2652 }
2653
2654 #ifdef DDB
2655 static void
2656 db_print_indent(int indent)
2657 {
2658         int i;
2659
2660         for (i = 0; i < indent; i++)
2661                 db_printf(" ");
2662 }
2663
2664 static void
2665 db_print_tstate(int t_state)
2666 {
2667
2668         switch (t_state) {
2669         case TCPS_CLOSED:
2670                 db_printf("TCPS_CLOSED");
2671                 return;
2672
2673         case TCPS_LISTEN:
2674                 db_printf("TCPS_LISTEN");
2675                 return;
2676
2677         case TCPS_SYN_SENT:
2678                 db_printf("TCPS_SYN_SENT");
2679                 return;
2680
2681         case TCPS_SYN_RECEIVED:
2682                 db_printf("TCPS_SYN_RECEIVED");
2683                 return;
2684
2685         case TCPS_ESTABLISHED:
2686                 db_printf("TCPS_ESTABLISHED");
2687                 return;
2688
2689         case TCPS_CLOSE_WAIT:
2690                 db_printf("TCPS_CLOSE_WAIT");
2691                 return;
2692
2693         case TCPS_FIN_WAIT_1:
2694                 db_printf("TCPS_FIN_WAIT_1");
2695                 return;
2696
2697         case TCPS_CLOSING:
2698                 db_printf("TCPS_CLOSING");
2699                 return;
2700
2701         case TCPS_LAST_ACK:
2702                 db_printf("TCPS_LAST_ACK");
2703                 return;
2704
2705         case TCPS_FIN_WAIT_2:
2706                 db_printf("TCPS_FIN_WAIT_2");
2707                 return;
2708
2709         case TCPS_TIME_WAIT:
2710                 db_printf("TCPS_TIME_WAIT");
2711                 return;
2712
2713         default:
2714                 db_printf("unknown");
2715                 return;
2716         }
2717 }
2718
2719 static void
2720 db_print_tflags(u_int t_flags)
2721 {
2722         int comma;
2723
2724         comma = 0;
2725         if (t_flags & TF_ACKNOW) {
2726                 db_printf("%sTF_ACKNOW", comma ? ", " : "");
2727                 comma = 1;
2728         }
2729         if (t_flags & TF_DELACK) {
2730                 db_printf("%sTF_DELACK", comma ? ", " : "");
2731                 comma = 1;
2732         }
2733         if (t_flags & TF_NODELAY) {
2734                 db_printf("%sTF_NODELAY", comma ? ", " : "");
2735                 comma = 1;
2736         }
2737         if (t_flags & TF_NOOPT) {
2738                 db_printf("%sTF_NOOPT", comma ? ", " : "");
2739                 comma = 1;
2740         }
2741         if (t_flags & TF_SENTFIN) {
2742                 db_printf("%sTF_SENTFIN", comma ? ", " : "");
2743                 comma = 1;
2744         }
2745         if (t_flags & TF_REQ_SCALE) {
2746                 db_printf("%sTF_REQ_SCALE", comma ? ", " : "");
2747                 comma = 1;
2748         }
2749         if (t_flags & TF_RCVD_SCALE) {
2750                 db_printf("%sTF_RECVD_SCALE", comma ? ", " : "");
2751                 comma = 1;
2752         }
2753         if (t_flags & TF_REQ_TSTMP) {
2754                 db_printf("%sTF_REQ_TSTMP", comma ? ", " : "");
2755                 comma = 1;
2756         }
2757         if (t_flags & TF_RCVD_TSTMP) {
2758                 db_printf("%sTF_RCVD_TSTMP", comma ? ", " : "");
2759                 comma = 1;
2760         }
2761         if (t_flags & TF_SACK_PERMIT) {
2762                 db_printf("%sTF_SACK_PERMIT", comma ? ", " : "");
2763                 comma = 1;
2764         }
2765         if (t_flags & TF_NEEDSYN) {
2766                 db_printf("%sTF_NEEDSYN", comma ? ", " : "");
2767                 comma = 1;
2768         }
2769         if (t_flags & TF_NEEDFIN) {
2770                 db_printf("%sTF_NEEDFIN", comma ? ", " : "");
2771                 comma = 1;
2772         }
2773         if (t_flags & TF_NOPUSH) {
2774                 db_printf("%sTF_NOPUSH", comma ? ", " : "");
2775                 comma = 1;
2776         }
2777         if (t_flags & TF_MORETOCOME) {
2778                 db_printf("%sTF_MORETOCOME", comma ? ", " : "");
2779                 comma = 1;
2780         }
2781         if (t_flags & TF_LQ_OVERFLOW) {
2782                 db_printf("%sTF_LQ_OVERFLOW", comma ? ", " : "");
2783                 comma = 1;
2784         }
2785         if (t_flags & TF_LASTIDLE) {
2786                 db_printf("%sTF_LASTIDLE", comma ? ", " : "");
2787                 comma = 1;
2788         }
2789         if (t_flags & TF_RXWIN0SENT) {
2790                 db_printf("%sTF_RXWIN0SENT", comma ? ", " : "");
2791                 comma = 1;
2792         }
2793         if (t_flags & TF_FASTRECOVERY) {
2794                 db_printf("%sTF_FASTRECOVERY", comma ? ", " : "");
2795                 comma = 1;
2796         }
2797         if (t_flags & TF_CONGRECOVERY) {
2798                 db_printf("%sTF_CONGRECOVERY", comma ? ", " : "");
2799                 comma = 1;
2800         }
2801         if (t_flags & TF_WASFRECOVERY) {
2802                 db_printf("%sTF_WASFRECOVERY", comma ? ", " : "");
2803                 comma = 1;
2804         }
2805         if (t_flags & TF_SIGNATURE) {
2806                 db_printf("%sTF_SIGNATURE", comma ? ", " : "");
2807                 comma = 1;
2808         }
2809         if (t_flags & TF_FORCEDATA) {
2810                 db_printf("%sTF_FORCEDATA", comma ? ", " : "");
2811                 comma = 1;
2812         }
2813         if (t_flags & TF_TSO) {
2814                 db_printf("%sTF_TSO", comma ? ", " : "");
2815                 comma = 1;
2816         }
2817         if (t_flags & TF_FASTOPEN) {
2818                 db_printf("%sTF_FASTOPEN", comma ? ", " : "");
2819                 comma = 1;
2820         }
2821 }
2822
2823 static void
2824 db_print_tflags2(u_int t_flags2)
2825 {
2826         int comma;
2827
2828         comma = 0;
2829         if (t_flags2 & TF2_ECN_PERMIT) {
2830                 db_printf("%sTF2_ECN_PERMIT", comma ? ", " : "");
2831                 comma = 1;
2832         }
2833 }
2834
2835 static void
2836 db_print_toobflags(char t_oobflags)
2837 {
2838         int comma;
2839
2840         comma = 0;
2841         if (t_oobflags & TCPOOB_HAVEDATA) {
2842                 db_printf("%sTCPOOB_HAVEDATA", comma ? ", " : "");
2843                 comma = 1;
2844         }
2845         if (t_oobflags & TCPOOB_HADDATA) {
2846                 db_printf("%sTCPOOB_HADDATA", comma ? ", " : "");
2847                 comma = 1;
2848         }
2849 }
2850
2851 static void
2852 db_print_tcpcb(struct tcpcb *tp, const char *name, int indent)
2853 {
2854
2855         db_print_indent(indent);
2856         db_printf("%s at %p\n", name, tp);
2857
2858         indent += 2;
2859
2860         db_print_indent(indent);
2861         db_printf("t_segq first: %p   t_segqlen: %d   t_dupacks: %d\n",
2862            TAILQ_FIRST(&tp->t_segq), tp->t_segqlen, tp->t_dupacks);
2863
2864         db_print_indent(indent);
2865         db_printf("tt_rexmt: %p   tt_persist: %p   tt_keep: %p\n",
2866             &tp->t_timers->tt_rexmt, &tp->t_timers->tt_persist, &tp->t_timers->tt_keep);
2867
2868         db_print_indent(indent);
2869         db_printf("tt_2msl: %p   tt_delack: %p   t_inpcb: %p\n", &tp->t_timers->tt_2msl,
2870             &tp->t_timers->tt_delack, tp->t_inpcb);
2871
2872         db_print_indent(indent);
2873         db_printf("t_state: %d (", tp->t_state);
2874         db_print_tstate(tp->t_state);
2875         db_printf(")\n");
2876
2877         db_print_indent(indent);
2878         db_printf("t_flags: 0x%x (", tp->t_flags);
2879         db_print_tflags(tp->t_flags);
2880         db_printf(")\n");
2881
2882         db_print_indent(indent);
2883         db_printf("t_flags2: 0x%x (", tp->t_flags2);
2884         db_print_tflags2(tp->t_flags2);
2885         db_printf(")\n");
2886
2887         db_print_indent(indent);
2888         db_printf("snd_una: 0x%08x   snd_max: 0x%08x   snd_nxt: x0%08x\n",
2889             tp->snd_una, tp->snd_max, tp->snd_nxt);
2890
2891         db_print_indent(indent);
2892         db_printf("snd_up: 0x%08x   snd_wl1: 0x%08x   snd_wl2: 0x%08x\n",
2893            tp->snd_up, tp->snd_wl1, tp->snd_wl2);
2894
2895         db_print_indent(indent);
2896         db_printf("iss: 0x%08x   irs: 0x%08x   rcv_nxt: 0x%08x\n",
2897             tp->iss, tp->irs, tp->rcv_nxt);
2898
2899         db_print_indent(indent);
2900         db_printf("rcv_adv: 0x%08x   rcv_wnd: %u   rcv_up: 0x%08x\n",
2901             tp->rcv_adv, tp->rcv_wnd, tp->rcv_up);
2902
2903         db_print_indent(indent);
2904         db_printf("snd_wnd: %u   snd_cwnd: %u\n",
2905            tp->snd_wnd, tp->snd_cwnd);
2906
2907         db_print_indent(indent);
2908         db_printf("snd_ssthresh: %u   snd_recover: "
2909             "0x%08x\n", tp->snd_ssthresh, tp->snd_recover);
2910
2911         db_print_indent(indent);
2912         db_printf("t_rcvtime: %u   t_startime: %u\n",
2913             tp->t_rcvtime, tp->t_starttime);
2914
2915         db_print_indent(indent);
2916         db_printf("t_rttime: %u   t_rtsq: 0x%08x\n",
2917             tp->t_rtttime, tp->t_rtseq);
2918
2919         db_print_indent(indent);
2920         db_printf("t_rxtcur: %d   t_maxseg: %u   t_srtt: %d\n",
2921             tp->t_rxtcur, tp->t_maxseg, tp->t_srtt);
2922
2923         db_print_indent(indent);
2924         db_printf("t_rttvar: %d   t_rxtshift: %d   t_rttmin: %u\n",
2925             tp->t_rttvar, tp->t_rxtshift, tp->t_rttmin);
2926
2927         db_print_indent(indent);
2928         db_printf("t_rttupdated: %lu   max_sndwnd: %u   t_softerror: %d\n",
2929             tp->t_rttupdated, tp->max_sndwnd, tp->t_softerror);
2930
2931         db_print_indent(indent);
2932         db_printf("t_oobflags: 0x%x (", tp->t_oobflags);
2933         db_print_toobflags(tp->t_oobflags);
2934         db_printf(")   t_iobc: 0x%02x\n", tp->t_iobc);
2935
2936         db_print_indent(indent);
2937         db_printf("snd_scale: %u   rcv_scale: %u   request_r_scale: %u\n",
2938             tp->snd_scale, tp->rcv_scale, tp->request_r_scale);
2939
2940         db_print_indent(indent);
2941         db_printf("ts_recent: %u   ts_recent_age: %u\n",
2942             tp->ts_recent, tp->ts_recent_age);
2943
2944         db_print_indent(indent);
2945         db_printf("ts_offset: %u   last_ack_sent: 0x%08x   snd_cwnd_prev: "
2946             "%u\n", tp->ts_offset, tp->last_ack_sent, tp->snd_cwnd_prev);
2947
2948         db_print_indent(indent);
2949         db_printf("snd_ssthresh_prev: %u   snd_recover_prev: 0x%08x   "
2950             "t_badrxtwin: %u\n", tp->snd_ssthresh_prev,
2951             tp->snd_recover_prev, tp->t_badrxtwin);
2952
2953         db_print_indent(indent);
2954         db_printf("snd_numholes: %d  snd_holes first: %p\n",
2955             tp->snd_numholes, TAILQ_FIRST(&tp->snd_holes));
2956
2957         db_print_indent(indent);
2958         db_printf("snd_fack: 0x%08x   rcv_numsacks: %d\n",
2959             tp->snd_fack, tp->rcv_numsacks);
2960
2961         /* Skip sackblks, sackhint. */
2962
2963         db_print_indent(indent);
2964         db_printf("t_rttlow: %d   rfbuf_ts: %u   rfbuf_cnt: %d\n",
2965             tp->t_rttlow, tp->rfbuf_ts, tp->rfbuf_cnt);
2966 }
2967
2968 DB_SHOW_COMMAND(tcpcb, db_show_tcpcb)
2969 {
2970         struct tcpcb *tp;
2971
2972         if (!have_addr) {
2973                 db_printf("usage: show tcpcb <addr>\n");
2974                 return;
2975         }
2976         tp = (struct tcpcb *)addr;
2977
2978         db_print_tcpcb(tp, "tcpcb", 0);
2979 }
2980 #endif