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