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