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