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