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