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