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