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