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