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