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