Do not return an EINVAL error for certain abort and disconnect cases.
[dragonfly.git] / sys / netinet / tcp_usrreq.c
1 /*
2  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2003, 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      From: @(#)tcp_usrreq.c  8.2 (Berkeley) 1/3/94
67  * $FreeBSD: src/sys/netinet/tcp_usrreq.c,v 1.51.2.17 2002/10/11 11:46:44 ume Exp $
68  * $DragonFly: src/sys/netinet/tcp_usrreq.c,v 1.51 2008/09/29 20:52:23 dillon Exp $
69  */
70
71 #include "opt_ipsec.h"
72 #include "opt_inet6.h"
73 #include "opt_tcpdebug.h"
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/kernel.h>
78 #include <sys/malloc.h>
79 #include <sys/sysctl.h>
80 #include <sys/globaldata.h>
81 #include <sys/thread.h>
82
83 #include <sys/mbuf.h>
84 #ifdef INET6
85 #include <sys/domain.h>
86 #endif /* INET6 */
87 #include <sys/socket.h>
88 #include <sys/socketvar.h>
89 #include <sys/protosw.h>
90
91 #include <sys/thread2.h>
92 #include <sys/msgport2.h>
93
94 #include <net/if.h>
95 #include <net/netisr.h>
96 #include <net/route.h>
97
98 #include <net/netmsg2.h>
99
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #ifdef INET6
103 #include <netinet/ip6.h>
104 #endif
105 #include <netinet/in_pcb.h>
106 #ifdef INET6
107 #include <netinet6/in6_pcb.h>
108 #endif
109 #include <netinet/in_var.h>
110 #include <netinet/ip_var.h>
111 #ifdef INET6
112 #include <netinet6/ip6_var.h>
113 #endif
114 #include <netinet/tcp.h>
115 #include <netinet/tcp_fsm.h>
116 #include <netinet/tcp_seq.h>
117 #include <netinet/tcp_timer.h>
118 #include <netinet/tcp_var.h>
119 #include <netinet/tcpip.h>
120 #ifdef TCPDEBUG
121 #include <netinet/tcp_debug.h>
122 #endif
123
124 #ifdef IPSEC
125 #include <netinet6/ipsec.h>
126 #endif /*IPSEC*/
127
128 /*
129  * TCP protocol interface to socket abstraction.
130  */
131 extern  char *tcpstates[];      /* XXX ??? */
132
133 static int      tcp_attach (struct socket *, struct pru_attach_info *);
134 static int      tcp_connect (struct tcpcb *, struct sockaddr *,
135                                  struct thread *);
136 #ifdef INET6
137 static int      tcp6_connect (struct tcpcb *, struct sockaddr *,
138                                  struct thread *);
139 #endif /* INET6 */
140 static struct tcpcb *
141                 tcp_disconnect (struct tcpcb *);
142 static struct tcpcb *
143                 tcp_usrclosed (struct tcpcb *);
144
145 #ifdef TCPDEBUG
146 #define TCPDEBUG0       int ostate = 0
147 #define TCPDEBUG1()     ostate = tp ? tp->t_state : 0
148 #define TCPDEBUG2(req)  if (tp && (so->so_options & SO_DEBUG)) \
149                                 tcp_trace(TA_USER, ostate, tp, 0, 0, req)
150 #else
151 #define TCPDEBUG0
152 #define TCPDEBUG1()
153 #define TCPDEBUG2(req)
154 #endif
155
156 /*
157  * TCP attaches to socket via pru_attach(), reserving space,
158  * and an internet control block.
159  */
160 static int
161 tcp_usr_attach(struct socket *so, int proto, struct pru_attach_info *ai)
162 {
163         int error;
164         struct inpcb *inp;
165         struct tcpcb *tp = 0;
166         TCPDEBUG0;
167
168         crit_enter();
169         inp = so->so_pcb;
170         TCPDEBUG1();
171         if (inp) {
172                 error = EISCONN;
173                 goto out;
174         }
175
176         error = tcp_attach(so, ai);
177         if (error)
178                 goto out;
179
180         if ((so->so_options & SO_LINGER) && so->so_linger == 0)
181                 so->so_linger = TCP_LINGERTIME;
182         tp = sototcpcb(so);
183 out:
184         TCPDEBUG2(PRU_ATTACH);
185         crit_exit();
186         return error;
187 }
188
189 /*
190  * pru_detach() detaches the TCP protocol from the socket.
191  * If the protocol state is non-embryonic, then can't
192  * do this directly: have to initiate a pru_disconnect(),
193  * which may finish later; embryonic TCB's can just
194  * be discarded here.
195  */
196 static int
197 tcp_usr_detach(struct socket *so)
198 {
199         int error = 0;
200         struct inpcb *inp;
201         struct tcpcb *tp;
202         TCPDEBUG0;
203
204         crit_enter();
205         inp = so->so_pcb;
206
207         /*
208          * If the inp is already detached it may have been due to an async
209          * close.  Just return as if no error occured.
210          */
211         if (inp == NULL) {
212                 crit_exit();
213                 return 0;
214         }
215
216         /*
217          * It's possible for the tcpcb (tp) to disconnect from the inp due
218          * to tcp_drop()->tcp_close() being called.  This may occur *after*
219          * the detach message has been queued so we may find a NULL tp here.
220          */
221         if ((tp = intotcpcb(inp)) != NULL) {
222                 TCPDEBUG1();
223                 tp = tcp_disconnect(tp);
224                 TCPDEBUG2(PRU_DETACH);
225         }
226         crit_exit();
227         return error;
228 }
229
230 /*
231  * Note: ignore_error is non-zero for certain disconnection races
232  * which we want to silently allow, otherwise close() may return
233  * an unexpected error.
234  */
235 #define COMMON_START(so, inp, ignore_error)                     \
236         TCPDEBUG0;              \
237                                 \
238         crit_enter();           \
239         inp = so->so_pcb;       \
240         do {                    \
241                  if (inp == NULL) {                             \
242                          crit_exit();                           \
243                          return (ignore_error ? 0 : EINVAL);    \
244                  }                                              \
245                  tp = intotcpcb(inp);                           \
246                  TCPDEBUG1();                                   \
247         } while(0)
248
249 #define COMMON_END(req) out: TCPDEBUG2(req); crit_exit(); return error; goto out
250
251
252 /*
253  * Give the socket an address.
254  */
255 static int
256 tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
257 {
258         int error = 0;
259         struct inpcb *inp;
260         struct tcpcb *tp;
261         struct sockaddr_in *sinp;
262
263         COMMON_START(so, inp, 0);
264
265         /*
266          * Must check for multicast addresses and disallow binding
267          * to them.
268          */
269         sinp = (struct sockaddr_in *)nam;
270         if (sinp->sin_family == AF_INET &&
271             IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
272                 error = EAFNOSUPPORT;
273                 goto out;
274         }
275         error = in_pcbbind(inp, nam, td);
276         if (error)
277                 goto out;
278         COMMON_END(PRU_BIND);
279
280 }
281
282 #ifdef INET6
283 static int
284 tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
285 {
286         int error = 0;
287         struct inpcb *inp;
288         struct tcpcb *tp;
289         struct sockaddr_in6 *sin6p;
290
291         COMMON_START(so, inp, 0);
292
293         /*
294          * Must check for multicast addresses and disallow binding
295          * to them.
296          */
297         sin6p = (struct sockaddr_in6 *)nam;
298         if (sin6p->sin6_family == AF_INET6 &&
299             IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr)) {
300                 error = EAFNOSUPPORT;
301                 goto out;
302         }
303         inp->inp_vflag &= ~INP_IPV4;
304         inp->inp_vflag |= INP_IPV6;
305         if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
306                 if (IN6_IS_ADDR_UNSPECIFIED(&sin6p->sin6_addr))
307                         inp->inp_vflag |= INP_IPV4;
308                 else if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
309                         struct sockaddr_in sin;
310
311                         in6_sin6_2_sin(&sin, sin6p);
312                         inp->inp_vflag |= INP_IPV4;
313                         inp->inp_vflag &= ~INP_IPV6;
314                         error = in_pcbbind(inp, (struct sockaddr *)&sin, td);
315                         goto out;
316                 }
317         }
318         error = in6_pcbbind(inp, nam, td);
319         if (error)
320                 goto out;
321         COMMON_END(PRU_BIND);
322 }
323 #endif /* INET6 */
324
325 #ifdef SMP
326 struct netmsg_inswildcard {
327         struct netmsg           nm_netmsg;
328         struct inpcb            *nm_inp;
329         struct inpcbinfo        *nm_pcbinfo;
330 };
331
332 static void
333 in_pcbinswildcardhash_handler(struct netmsg *msg0)
334 {
335         struct netmsg_inswildcard *msg = (struct netmsg_inswildcard *)msg0;
336
337         in_pcbinswildcardhash_oncpu(msg->nm_inp, msg->nm_pcbinfo);
338         lwkt_replymsg(&msg->nm_netmsg.nm_lmsg, 0);
339 }
340 #endif
341
342 /*
343  * Prepare to accept connections.
344  */
345 static int
346 tcp_usr_listen(struct socket *so, struct thread *td)
347 {
348         int error = 0;
349         struct inpcb *inp;
350         struct tcpcb *tp;
351 #ifdef SMP
352         int cpu;
353 #endif
354
355         COMMON_START(so, inp, 0);
356         if (inp->inp_lport == 0) {
357                 error = in_pcbbind(inp, NULL, td);
358                 if (error != 0)
359                         goto out;
360         }
361
362         tp->t_state = TCPS_LISTEN;
363 #ifdef SMP
364         /*
365          * We have to set the flag because we can't have other cpus
366          * messing with our inp's flags.
367          */
368         inp->inp_flags |= INP_WILDCARD_MP;
369         for (cpu = 0; cpu < ncpus2; cpu++) {
370                 struct netmsg_inswildcard *msg;
371
372                 if (cpu == mycpu->gd_cpuid) {
373                         in_pcbinswildcardhash(inp);
374                         continue;
375                 }
376
377                 msg = kmalloc(sizeof(struct netmsg_inswildcard), M_LWKTMSG,
378                               M_INTWAIT);
379                 netmsg_init(&msg->nm_netmsg, &netisr_afree_rport, 0,
380                             in_pcbinswildcardhash_handler);
381                 msg->nm_inp = inp;
382                 msg->nm_pcbinfo = &tcbinfo[cpu];
383                 lwkt_sendmsg(tcp_cport(cpu), &msg->nm_netmsg.nm_lmsg);
384         }
385 #else
386         in_pcbinswildcardhash(inp);
387 #endif
388         COMMON_END(PRU_LISTEN);
389 }
390
391 #ifdef INET6
392 static int
393 tcp6_usr_listen(struct socket *so, struct thread *td)
394 {
395         int error = 0;
396         struct inpcb *inp;
397         struct tcpcb *tp;
398 #ifdef SMP
399         int cpu;
400 #endif
401
402         COMMON_START(so, inp, 0);
403         if (inp->inp_lport == 0) {
404                 if (!(inp->inp_flags & IN6P_IPV6_V6ONLY))
405                         inp->inp_vflag |= INP_IPV4;
406                 else
407                         inp->inp_vflag &= ~INP_IPV4;
408                 error = in6_pcbbind(inp, (struct sockaddr *)0, td);
409         }
410         if (error == 0)
411                 tp->t_state = TCPS_LISTEN;
412 #ifdef SMP
413         /*
414          * We have to set the flag because we can't have other cpus
415          * messing with our inp's flags.
416          */
417         inp->inp_flags |= INP_WILDCARD_MP;
418         for (cpu = 0; cpu < ncpus2; cpu++) {
419                 struct netmsg_inswildcard *msg;
420
421                 if (cpu == mycpu->gd_cpuid) {
422                         in_pcbinswildcardhash(inp);
423                         continue;
424                 }
425
426                 msg = kmalloc(sizeof(struct netmsg_inswildcard), M_LWKTMSG,
427                               M_INTWAIT);
428                 netmsg_init(&msg->nm_netmsg, &netisr_afree_rport, 0,
429                             in_pcbinswildcardhash_handler);
430                 msg->nm_inp = inp;
431                 msg->nm_pcbinfo = &tcbinfo[cpu];
432                 lwkt_sendmsg(tcp_cport(cpu), &msg->nm_netmsg.nm_lmsg);
433         }
434 #else
435         in_pcbinswildcardhash(inp);
436 #endif
437         COMMON_END(PRU_LISTEN);
438 }
439 #endif /* INET6 */
440
441 #ifdef SMP
442 static void
443 tcp_output_dispatch(struct netmsg *nmsg)
444 {
445         struct lwkt_msg *msg = &nmsg->nm_lmsg;
446         struct tcpcb *tp = msg->u.ms_resultp;
447         int error;
448
449         error = tcp_output(tp);
450         lwkt_replymsg(msg, error);
451 }
452 #endif
453
454 /*
455  * Initiate connection to peer.
456  * Create a template for use in transmissions on this connection.
457  * Enter SYN_SENT state, and mark socket as connecting.
458  * Start keep-alive timer, and seed output sequence space.
459  * Send initial segment on connection.
460  */
461 static int
462 tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
463 {
464         int error = 0;
465         struct inpcb *inp;
466         struct tcpcb *tp;
467         struct sockaddr_in *sinp;
468 #ifdef SMP
469         lwkt_port_t port;
470 #endif
471
472         COMMON_START(so, inp, 0);
473
474         /*
475          * Must disallow TCP ``connections'' to multicast addresses.
476          */
477         sinp = (struct sockaddr_in *)nam;
478         if (sinp->sin_family == AF_INET
479             && IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
480                 error = EAFNOSUPPORT;
481                 goto out;
482         }
483
484         if (!prison_remote_ip(td, (struct sockaddr*)sinp)) {
485                 error = EAFNOSUPPORT; /* IPv6 only jail */
486                 goto out;
487         }
488
489         if ((error = tcp_connect(tp, nam, td)) != 0)
490                 goto out;
491
492 #ifdef SMP
493         port = tcp_addrport(inp->inp_faddr.s_addr, inp->inp_fport,
494                             inp->inp_laddr.s_addr, inp->inp_lport);
495         if (port != &curthread->td_msgport) {
496                 struct netmsg nmsg;
497                 struct lwkt_msg *msg;
498
499                 netmsg_init(&nmsg, &curthread->td_msgport, 0,
500                             tcp_output_dispatch);
501                 msg = &nmsg.nm_lmsg;
502                 msg->u.ms_resultp = tp;
503
504                 error = lwkt_domsg(port, msg, 0);
505         } else
506 #endif
507                 error = tcp_output(tp);
508         COMMON_END(PRU_CONNECT);
509 }
510
511 #ifdef INET6
512 static int
513 tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
514 {
515         int error = 0;
516         struct inpcb *inp;
517         struct tcpcb *tp;
518         struct sockaddr_in6 *sin6p;
519
520         COMMON_START(so, inp, 0);
521
522         /*
523          * Must disallow TCP ``connections'' to multicast addresses.
524          */
525         sin6p = (struct sockaddr_in6 *)nam;
526         if (sin6p->sin6_family == AF_INET6
527             && IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr)) {
528                 error = EAFNOSUPPORT;
529                 goto out;
530         }
531
532         if (!prison_remote_ip(td, nam)) {
533                 error = EAFNOSUPPORT; /* IPv4 only jail */
534                 goto out;
535         }
536
537         if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
538                 struct sockaddr_in sin;
539
540                 if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
541                         error = EINVAL;
542                         goto out;
543                 }
544
545                 in6_sin6_2_sin(&sin, sin6p);
546                 inp->inp_vflag |= INP_IPV4;
547                 inp->inp_vflag &= ~INP_IPV6;
548                 if ((error = tcp_connect(tp, (struct sockaddr *)&sin, td)) != 0)
549                         goto out;
550                 error = tcp_output(tp);
551                 goto out;
552         }
553         inp->inp_vflag &= ~INP_IPV4;
554         inp->inp_vflag |= INP_IPV6;
555         inp->inp_inc.inc_isipv6 = 1;
556         if ((error = tcp6_connect(tp, nam, td)) != 0)
557                 goto out;
558         error = tcp_output(tp);
559         COMMON_END(PRU_CONNECT);
560 }
561 #endif /* INET6 */
562
563 /*
564  * Initiate disconnect from peer.
565  * If connection never passed embryonic stage, just drop;
566  * else if don't need to let data drain, then can just drop anyways,
567  * else have to begin TCP shutdown process: mark socket disconnecting,
568  * drain unread data, state switch to reflect user close, and
569  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
570  * when peer sends FIN and acks ours.
571  *
572  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
573  */
574 static int
575 tcp_usr_disconnect(struct socket *so)
576 {
577         int error = 0;
578         struct inpcb *inp;
579         struct tcpcb *tp;
580
581         COMMON_START(so, inp, 1);
582         tp = tcp_disconnect(tp);
583         COMMON_END(PRU_DISCONNECT);
584 }
585
586 /*
587  * Accept a connection.  Essentially all the work is
588  * done at higher levels; just return the address
589  * of the peer, storing through addr.
590  */
591 static int
592 tcp_usr_accept(struct socket *so, struct sockaddr **nam)
593 {
594         int error = 0;
595         struct inpcb *inp;
596         struct tcpcb *tp = NULL;
597         TCPDEBUG0;
598
599         crit_enter();
600         inp = so->so_pcb;
601         if (so->so_state & SS_ISDISCONNECTED) {
602                 error = ECONNABORTED;
603                 goto out;
604         }
605         if (inp == 0) {
606                 crit_exit();
607                 return (EINVAL);
608         }
609         tp = intotcpcb(inp);
610         TCPDEBUG1();
611         in_setpeeraddr(so, nam);
612         COMMON_END(PRU_ACCEPT);
613 }
614
615 #ifdef INET6
616 static int
617 tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
618 {
619         int error = 0;
620         struct inpcb *inp;
621         struct tcpcb *tp = NULL;
622         TCPDEBUG0;
623
624         crit_enter();
625         inp = so->so_pcb;
626
627         if (so->so_state & SS_ISDISCONNECTED) {
628                 error = ECONNABORTED;
629                 goto out;
630         }
631         if (inp == 0) {
632                 crit_exit();
633                 return (EINVAL);
634         }
635         tp = intotcpcb(inp);
636         TCPDEBUG1();
637         in6_mapped_peeraddr(so, nam);
638         COMMON_END(PRU_ACCEPT);
639 }
640 #endif /* INET6 */
641 /*
642  * Mark the connection as being incapable of further output.
643  */
644 static int
645 tcp_usr_shutdown(struct socket *so)
646 {
647         int error = 0;
648         struct inpcb *inp;
649         struct tcpcb *tp;
650
651         COMMON_START(so, inp, 0);
652         socantsendmore(so);
653         tp = tcp_usrclosed(tp);
654         if (tp)
655                 error = tcp_output(tp);
656         COMMON_END(PRU_SHUTDOWN);
657 }
658
659 /*
660  * After a receive, possibly send window update to peer.
661  */
662 static int
663 tcp_usr_rcvd(struct socket *so, int flags)
664 {
665         int error = 0;
666         struct inpcb *inp;
667         struct tcpcb *tp;
668
669         COMMON_START(so, inp, 0);
670         tcp_output(tp);
671         COMMON_END(PRU_RCVD);
672 }
673
674 /*
675  * Do a send by putting data in output queue and updating urgent
676  * marker if URG set.  Possibly send more data.  Unlike the other
677  * pru_*() routines, the mbuf chains are our responsibility.  We
678  * must either enqueue them or free them.  The other pru_* routines
679  * generally are caller-frees.
680  */
681 static int
682 tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
683              struct sockaddr *nam, struct mbuf *control, struct thread *td)
684 {
685         int error = 0;
686         struct inpcb *inp;
687         struct tcpcb *tp;
688 #ifdef INET6
689         int isipv6;
690 #endif
691         TCPDEBUG0;
692
693         crit_enter();
694         inp = so->so_pcb;
695
696         if (inp == NULL) {
697                 /*
698                  * OOPS! we lost a race, the TCP session got reset after
699                  * we checked SS_CANTSENDMORE, eg: while doing uiomove or a
700                  * network interrupt in the non-critical section of sosend().
701                  */
702                 if (m)
703                         m_freem(m);
704                 if (control)
705                         m_freem(control);
706                 error = ECONNRESET;     /* XXX EPIPE? */
707                 tp = NULL;
708                 TCPDEBUG1();
709                 goto out;
710         }
711 #ifdef INET6
712         isipv6 = nam && nam->sa_family == AF_INET6;
713 #endif /* INET6 */
714         tp = intotcpcb(inp);
715         TCPDEBUG1();
716         if (control) {
717                 /* TCP doesn't do control messages (rights, creds, etc) */
718                 if (control->m_len) {
719                         m_freem(control);
720                         if (m)
721                                 m_freem(m);
722                         error = EINVAL;
723                         goto out;
724                 }
725                 m_freem(control);       /* empty control, just free it */
726         }
727         if(!(flags & PRUS_OOB)) {
728                 ssb_appendstream(&so->so_snd, m);
729                 if (nam && tp->t_state < TCPS_SYN_SENT) {
730                         /*
731                          * Do implied connect if not yet connected,
732                          * initialize window to default value, and
733                          * initialize maxseg/maxopd using peer's cached
734                          * MSS.
735                          */
736 #ifdef INET6
737                         if (isipv6)
738                                 error = tcp6_connect(tp, nam, td);
739                         else
740 #endif /* INET6 */
741                         error = tcp_connect(tp, nam, td);
742                         if (error)
743                                 goto out;
744                         tp->snd_wnd = TTCP_CLIENT_SND_WND;
745                         tcp_mss(tp, -1);
746                 }
747
748                 if (flags & PRUS_EOF) {
749                         /*
750                          * Close the send side of the connection after
751                          * the data is sent.
752                          */
753                         socantsendmore(so);
754                         tp = tcp_usrclosed(tp);
755                 }
756                 if (tp != NULL) {
757                         if (flags & PRUS_MORETOCOME)
758                                 tp->t_flags |= TF_MORETOCOME;
759                         error = tcp_output(tp);
760                         if (flags & PRUS_MORETOCOME)
761                                 tp->t_flags &= ~TF_MORETOCOME;
762                 }
763         } else {
764                 if (ssb_space(&so->so_snd) < -512) {
765                         m_freem(m);
766                         error = ENOBUFS;
767                         goto out;
768                 }
769                 /*
770                  * According to RFC961 (Assigned Protocols),
771                  * the urgent pointer points to the last octet
772                  * of urgent data.  We continue, however,
773                  * to consider it to indicate the first octet
774                  * of data past the urgent section.
775                  * Otherwise, snd_up should be one lower.
776                  */
777                 ssb_appendstream(&so->so_snd, m);
778                 if (nam && tp->t_state < TCPS_SYN_SENT) {
779                         /*
780                          * Do implied connect if not yet connected,
781                          * initialize window to default value, and
782                          * initialize maxseg/maxopd using peer's cached
783                          * MSS.
784                          */
785 #ifdef INET6
786                         if (isipv6)
787                                 error = tcp6_connect(tp, nam, td);
788                         else
789 #endif /* INET6 */
790                         error = tcp_connect(tp, nam, td);
791                         if (error)
792                                 goto out;
793                         tp->snd_wnd = TTCP_CLIENT_SND_WND;
794                         tcp_mss(tp, -1);
795                 }
796                 tp->snd_up = tp->snd_una + so->so_snd.ssb_cc;
797                 tp->t_flags |= TF_FORCE;
798                 error = tcp_output(tp);
799                 tp->t_flags &= ~TF_FORCE;
800         }
801         COMMON_END((flags & PRUS_OOB) ? PRU_SENDOOB :
802                    ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
803 }
804
805 /*
806  * Abort the TCP.
807  */
808 static int
809 tcp_usr_abort(struct socket *so)
810 {
811         int error = 0;
812         struct inpcb *inp;
813         struct tcpcb *tp;
814
815         COMMON_START(so, inp, 1);
816         tp = tcp_drop(tp, ECONNABORTED);
817         COMMON_END(PRU_ABORT);
818 }
819
820 /*
821  * Receive out-of-band data.
822  */
823 static int
824 tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
825 {
826         int error = 0;
827         struct inpcb *inp;
828         struct tcpcb *tp;
829
830         COMMON_START(so, inp, 0);
831         if ((so->so_oobmark == 0 &&
832              (so->so_state & SS_RCVATMARK) == 0) ||
833             so->so_options & SO_OOBINLINE ||
834             tp->t_oobflags & TCPOOB_HADDATA) {
835                 error = EINVAL;
836                 goto out;
837         }
838         if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
839                 error = EWOULDBLOCK;
840                 goto out;
841         }
842         m->m_len = 1;
843         *mtod(m, caddr_t) = tp->t_iobc;
844         if ((flags & MSG_PEEK) == 0)
845                 tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
846         COMMON_END(PRU_RCVOOB);
847 }
848
849 /* xxx - should be const */
850 struct pr_usrreqs tcp_usrreqs = {
851         .pru_abort = tcp_usr_abort,
852         .pru_accept = tcp_usr_accept,
853         .pru_attach = tcp_usr_attach,
854         .pru_bind = tcp_usr_bind,
855         .pru_connect = tcp_usr_connect,
856         .pru_connect2 = pru_connect2_notsupp,
857         .pru_control = in_control,
858         .pru_detach = tcp_usr_detach,
859         .pru_disconnect = tcp_usr_disconnect,
860         .pru_listen = tcp_usr_listen,
861         .pru_peeraddr = in_setpeeraddr,
862         .pru_rcvd = tcp_usr_rcvd,
863         .pru_rcvoob = tcp_usr_rcvoob,
864         .pru_send = tcp_usr_send,
865         .pru_sense = pru_sense_null,
866         .pru_shutdown = tcp_usr_shutdown,
867         .pru_sockaddr = in_setsockaddr,
868         .pru_sosend = sosend,
869         .pru_soreceive = soreceive,
870         .pru_sopoll = sopoll
871 };
872
873 #ifdef INET6
874 struct pr_usrreqs tcp6_usrreqs = {
875         .pru_abort = tcp_usr_abort,
876         .pru_accept = tcp6_usr_accept,
877         .pru_attach = tcp_usr_attach,
878         .pru_bind = tcp6_usr_bind,
879         .pru_connect = tcp6_usr_connect,
880         .pru_connect2 = pru_connect2_notsupp,
881         .pru_control = in6_control,
882         .pru_detach = tcp_usr_detach,
883         .pru_disconnect = tcp_usr_disconnect,
884         .pru_listen = tcp6_usr_listen,
885         .pru_peeraddr = in6_mapped_peeraddr,
886         .pru_rcvd = tcp_usr_rcvd,
887         .pru_rcvoob = tcp_usr_rcvoob,
888         .pru_send = tcp_usr_send,
889         .pru_sense = pru_sense_null,
890         .pru_shutdown = tcp_usr_shutdown,
891         .pru_sockaddr = in6_mapped_sockaddr,
892         .pru_sosend = sosend,
893         .pru_soreceive = soreceive,
894         .pru_sopoll = sopoll
895 };
896 #endif /* INET6 */
897
898 static int
899 tcp_connect_oncpu(struct tcpcb *tp, struct sockaddr_in *sin,
900                   struct sockaddr_in *if_sin)
901 {
902         struct inpcb *inp = tp->t_inpcb, *oinp;
903         struct socket *so = inp->inp_socket;
904         struct tcpcb *otp;
905         struct rmxp_tao *taop;
906         struct rmxp_tao tao_noncached;
907
908         oinp = in_pcblookup_hash(&tcbinfo[mycpu->gd_cpuid],
909             sin->sin_addr, sin->sin_port,
910             inp->inp_laddr.s_addr != INADDR_ANY ?
911                 inp->inp_laddr : if_sin->sin_addr,
912             inp->inp_lport, 0, NULL);
913         if (oinp != NULL) {
914                 if (oinp != inp && (otp = intotcpcb(oinp)) != NULL &&
915                     otp->t_state == TCPS_TIME_WAIT &&
916                     (ticks - otp->t_starttime) < tcp_msl &&
917                     (otp->t_flags & TF_RCVD_CC))
918                         tcp_close(otp);
919                 else
920                         return (EADDRINUSE);
921         }
922         if (inp->inp_laddr.s_addr == INADDR_ANY)
923                 inp->inp_laddr = if_sin->sin_addr;
924         inp->inp_faddr = sin->sin_addr;
925         inp->inp_fport = sin->sin_port;
926         inp->inp_cpcbinfo = &tcbinfo[mycpu->gd_cpuid];
927         in_pcbinsconnhash(inp);
928
929         /* Compute window scaling to request.  */
930         while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
931             (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.ssb_hiwat)
932                 tp->request_r_scale++;
933
934         soisconnecting(so);
935         tcpstat.tcps_connattempt++;
936         tp->t_state = TCPS_SYN_SENT;
937         callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
938         tp->iss = tcp_new_isn(tp);
939         tcp_sendseqinit(tp);
940
941         /*
942          * Generate a CC value for this connection and
943          * check whether CC or CCnew should be used.
944          */
945         if ((taop = tcp_gettaocache(&tp->t_inpcb->inp_inc)) == NULL) {
946                 taop = &tao_noncached;
947                 bzero(taop, sizeof *taop);
948         }
949
950         tp->cc_send = CC_INC(tcp_ccgen);
951         if (taop->tao_ccsent != 0 &&
952             CC_GEQ(tp->cc_send, taop->tao_ccsent)) {
953                 taop->tao_ccsent = tp->cc_send;
954         } else {
955                 taop->tao_ccsent = 0;
956                 tp->t_flags |= TF_SENDCCNEW;
957         }
958
959         return (0);
960 }
961
962 #ifdef SMP
963
964 struct netmsg_tcp_connect {
965         struct netmsg           nm_netmsg;
966         struct tcpcb            *nm_tp;
967         struct sockaddr_in      *nm_sin;
968         struct sockaddr_in      *nm_ifsin;
969 };
970
971 static void
972 tcp_connect_handler(netmsg_t netmsg)
973 {
974         struct netmsg_tcp_connect *msg = (void *)netmsg;
975         int error;
976
977         error = tcp_connect_oncpu(msg->nm_tp, msg->nm_sin, msg->nm_ifsin);
978         lwkt_replymsg(&msg->nm_netmsg.nm_lmsg, error);
979 }
980
981 #endif
982
983 /*
984  * Common subroutine to open a TCP connection to remote host specified
985  * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
986  * port number if needed.  Call in_pcbladdr to do the routing and to choose
987  * a local host address (interface).  If there is an existing incarnation
988  * of the same connection in TIME-WAIT state and if the remote host was
989  * sending CC options and if the connection duration was < MSL, then
990  * truncate the previous TIME-WAIT state and proceed.
991  * Initialize connection parameters and enter SYN-SENT state.
992  */
993 static int
994 tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
995 {
996         struct inpcb *inp = tp->t_inpcb;
997         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
998         struct sockaddr_in *if_sin;
999         int error;
1000 #ifdef SMP
1001         lwkt_port_t port;
1002 #endif
1003
1004         if (inp->inp_lport == 0) {
1005                 error = in_pcbbind(inp, (struct sockaddr *)NULL, td);
1006                 if (error)
1007                         return (error);
1008         }
1009
1010         /*
1011          * Cannot simply call in_pcbconnect, because there might be an
1012          * earlier incarnation of this same connection still in
1013          * TIME_WAIT state, creating an ADDRINUSE error.
1014          */
1015         error = in_pcbladdr(inp, nam, &if_sin, td);
1016         if (error)
1017                 return (error);
1018
1019 #ifdef SMP
1020         port = tcp_addrport(sin->sin_addr.s_addr, sin->sin_port,
1021             inp->inp_laddr.s_addr ?
1022                 inp->inp_laddr.s_addr : if_sin->sin_addr.s_addr,
1023             inp->inp_lport);
1024
1025         if (port != &curthread->td_msgport) {
1026                 struct netmsg_tcp_connect msg;
1027                 struct route *ro = &inp->inp_route;
1028
1029                 /*
1030                  * in_pcbladdr() may have allocated a route entry for us
1031                  * on the current CPU, but we need a route entry on the
1032                  * target CPU, so free it here.
1033                  */
1034                 if (ro->ro_rt != NULL)
1035                         RTFREE(ro->ro_rt);
1036                 bzero(ro, sizeof(*ro));
1037
1038                 netmsg_init(&msg.nm_netmsg, &curthread->td_msgport, 0,
1039                             tcp_connect_handler);
1040                 msg.nm_tp = tp;
1041                 msg.nm_sin = sin;
1042                 msg.nm_ifsin = if_sin;
1043                 error = lwkt_domsg(port, &msg.nm_netmsg.nm_lmsg, 0);
1044         } else
1045 #endif
1046                 error = tcp_connect_oncpu(tp, sin, if_sin);
1047
1048         return (error);
1049 }
1050
1051 #ifdef INET6
1052 static int
1053 tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1054 {
1055         struct inpcb *inp = tp->t_inpcb, *oinp;
1056         struct socket *so = inp->inp_socket;
1057         struct tcpcb *otp;
1058         struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
1059         struct in6_addr *addr6;
1060         struct rmxp_tao *taop;
1061         struct rmxp_tao tao_noncached;
1062         int error;
1063
1064         if (inp->inp_lport == 0) {
1065                 error = in6_pcbbind(inp, (struct sockaddr *)0, td);
1066                 if (error)
1067                         return error;
1068         }
1069
1070         /*
1071          * Cannot simply call in_pcbconnect, because there might be an
1072          * earlier incarnation of this same connection still in
1073          * TIME_WAIT state, creating an ADDRINUSE error.
1074          */
1075         error = in6_pcbladdr(inp, nam, &addr6, td);
1076         if (error)
1077                 return error;
1078         oinp = in6_pcblookup_hash(inp->inp_cpcbinfo,
1079                                   &sin6->sin6_addr, sin6->sin6_port,
1080                                   IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ?
1081                                       addr6 : &inp->in6p_laddr,
1082                                   inp->inp_lport,  0, NULL);
1083         if (oinp) {
1084                 if (oinp != inp && (otp = intotcpcb(oinp)) != NULL &&
1085                     otp->t_state == TCPS_TIME_WAIT &&
1086                     (ticks - otp->t_starttime) < tcp_msl &&
1087                     (otp->t_flags & TF_RCVD_CC))
1088                         otp = tcp_close(otp);
1089                 else
1090                         return (EADDRINUSE);
1091         }
1092         if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1093                 inp->in6p_laddr = *addr6;
1094         inp->in6p_faddr = sin6->sin6_addr;
1095         inp->inp_fport = sin6->sin6_port;
1096         if ((sin6->sin6_flowinfo & IPV6_FLOWINFO_MASK) != 0)
1097                 inp->in6p_flowinfo = sin6->sin6_flowinfo;
1098         in_pcbinsconnhash(inp);
1099
1100         /* Compute window scaling to request.  */
1101         while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1102             (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.ssb_hiwat)
1103                 tp->request_r_scale++;
1104
1105         soisconnecting(so);
1106         tcpstat.tcps_connattempt++;
1107         tp->t_state = TCPS_SYN_SENT;
1108         callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
1109         tp->iss = tcp_new_isn(tp);
1110         tcp_sendseqinit(tp);
1111
1112         /*
1113          * Generate a CC value for this connection and
1114          * check whether CC or CCnew should be used.
1115          */
1116         if ((taop = tcp_gettaocache(&tp->t_inpcb->inp_inc)) == NULL) {
1117                 taop = &tao_noncached;
1118                 bzero(taop, sizeof *taop);
1119         }
1120
1121         tp->cc_send = CC_INC(tcp_ccgen);
1122         if (taop->tao_ccsent != 0 &&
1123             CC_GEQ(tp->cc_send, taop->tao_ccsent)) {
1124                 taop->tao_ccsent = tp->cc_send;
1125         } else {
1126                 taop->tao_ccsent = 0;
1127                 tp->t_flags |= TF_SENDCCNEW;
1128         }
1129
1130         return (0);
1131 }
1132 #endif /* INET6 */
1133
1134 /*
1135  * The new sockopt interface makes it possible for us to block in the
1136  * copyin/out step (if we take a page fault).  Taking a page fault while
1137  * in a critical section is probably a Bad Thing.  (Since sockets and pcbs
1138  * both now use TSM, there probably isn't any need for this function to 
1139  * run in a critical section any more.  This needs more examination.)
1140  */
1141 int
1142 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
1143 {
1144         int     error, opt, optval;
1145         struct  inpcb *inp;
1146         struct  tcpcb *tp;
1147
1148         error = 0;
1149         crit_enter();           /* XXX */
1150         inp = so->so_pcb;
1151         if (inp == NULL) {
1152                 crit_exit();
1153                 return (ECONNRESET);
1154         }
1155         if (sopt->sopt_level != IPPROTO_TCP) {
1156 #ifdef INET6
1157                 if (INP_CHECK_SOCKAF(so, AF_INET6))
1158                         error = ip6_ctloutput(so, sopt);
1159                 else
1160 #endif /* INET6 */
1161                 error = ip_ctloutput(so, sopt);
1162                 crit_exit();
1163                 return (error);
1164         }
1165         tp = intotcpcb(inp);
1166
1167         switch (sopt->sopt_dir) {
1168         case SOPT_SET:
1169                 error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1170                                       sizeof optval);
1171                 if (error)
1172                         break;
1173                 switch (sopt->sopt_name) {
1174                 case TCP_NODELAY:
1175                 case TCP_NOOPT:
1176                         switch (sopt->sopt_name) {
1177                         case TCP_NODELAY:
1178                                 opt = TF_NODELAY;
1179                                 break;
1180                         case TCP_NOOPT:
1181                                 opt = TF_NOOPT;
1182                                 break;
1183                         default:
1184                                 opt = 0; /* dead code to fool gcc */
1185                                 break;
1186                         }
1187
1188                         if (optval)
1189                                 tp->t_flags |= opt;
1190                         else
1191                                 tp->t_flags &= ~opt;
1192                         break;
1193
1194                 case TCP_NOPUSH:
1195                         if (optval)
1196                                 tp->t_flags |= TF_NOPUSH;
1197                         else {
1198                                 tp->t_flags &= ~TF_NOPUSH;
1199                                 error = tcp_output(tp);
1200                         }
1201                         break;
1202
1203                 case TCP_MAXSEG:
1204                         if (optval > 0 && optval <= tp->t_maxseg)
1205                                 tp->t_maxseg = optval;
1206                         else
1207                                 error = EINVAL;
1208                         break;
1209
1210                 default:
1211                         error = ENOPROTOOPT;
1212                         break;
1213                 }
1214                 break;
1215
1216         case SOPT_GET:
1217                 switch (sopt->sopt_name) {
1218                 case TCP_NODELAY:
1219                         optval = tp->t_flags & TF_NODELAY;
1220                         break;
1221                 case TCP_MAXSEG:
1222                         optval = tp->t_maxseg;
1223                         break;
1224                 case TCP_NOOPT:
1225                         optval = tp->t_flags & TF_NOOPT;
1226                         break;
1227                 case TCP_NOPUSH:
1228                         optval = tp->t_flags & TF_NOPUSH;
1229                         break;
1230                 default:
1231                         error = ENOPROTOOPT;
1232                         break;
1233                 }
1234                 if (error == 0)
1235                         soopt_from_kbuf(sopt, &optval, sizeof optval);
1236                 break;
1237         }
1238         crit_exit();
1239         return (error);
1240 }
1241
1242 /*
1243  * tcp_sendspace and tcp_recvspace are the default send and receive window
1244  * sizes, respectively.  These are obsolescent (this information should
1245  * be set by the route).
1246  *
1247  * Use a default that does not require tcp window scaling to be turned
1248  * on.  Individual programs or the administrator can increase the default.
1249  */
1250 u_long  tcp_sendspace = 57344;  /* largest multiple of PAGE_SIZE < 64k */
1251 SYSCTL_INT(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_RW,
1252     &tcp_sendspace , 0, "Maximum outgoing TCP datagram size");
1253 u_long  tcp_recvspace = 57344;  /* largest multiple of PAGE_SIZE < 64k */
1254 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
1255     &tcp_recvspace , 0, "Maximum incoming TCP datagram size");
1256
1257 /*
1258  * Attach TCP protocol to socket, allocating
1259  * internet protocol control block, tcp control block,
1260  * bufer space, and entering LISTEN state if to accept connections.
1261  */
1262 static int
1263 tcp_attach(struct socket *so, struct pru_attach_info *ai)
1264 {
1265         struct tcpcb *tp;
1266         struct inpcb *inp;
1267         int error;
1268         int cpu;
1269 #ifdef INET6
1270         int isipv6 = INP_CHECK_SOCKAF(so, AF_INET6) != 0;
1271 #endif
1272
1273         if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
1274                 error = soreserve(so, tcp_sendspace, tcp_recvspace,
1275                                   ai->sb_rlimit);
1276                 if (error)
1277                         return (error);
1278         }
1279         cpu = mycpu->gd_cpuid;
1280         error = in_pcballoc(so, &tcbinfo[cpu]);
1281         if (error)
1282                 return (error);
1283         inp = so->so_pcb;
1284 #ifdef INET6
1285         if (isipv6) {
1286                 inp->inp_vflag |= INP_IPV6;
1287                 inp->in6p_hops = -1;    /* use kernel default */
1288         }
1289         else
1290 #endif
1291         inp->inp_vflag |= INP_IPV4;
1292         tp = tcp_newtcpcb(inp);
1293         if (tp == 0) {
1294                 int nofd = so->so_state & SS_NOFDREF;   /* XXX */
1295
1296                 so->so_state &= ~SS_NOFDREF;    /* don't free the socket yet */
1297 #ifdef INET6
1298                 if (isipv6)
1299                         in6_pcbdetach(inp);
1300                 else
1301 #endif
1302                 in_pcbdetach(inp);
1303                 so->so_state |= nofd;
1304                 return (ENOBUFS);
1305         }
1306         tp->t_state = TCPS_CLOSED;
1307         return (0);
1308 }
1309
1310 /*
1311  * Initiate (or continue) disconnect.
1312  * If embryonic state, just send reset (once).
1313  * If in ``let data drain'' option and linger null, just drop.
1314  * Otherwise (hard), mark socket disconnecting and drop
1315  * current input data; switch states based on user close, and
1316  * send segment to peer (with FIN).
1317  */
1318 static struct tcpcb *
1319 tcp_disconnect(struct tcpcb *tp)
1320 {
1321         struct socket *so = tp->t_inpcb->inp_socket;
1322
1323         if (tp->t_state < TCPS_ESTABLISHED)
1324                 tp = tcp_close(tp);
1325         else if ((so->so_options & SO_LINGER) && so->so_linger == 0)
1326                 tp = tcp_drop(tp, 0);
1327         else {
1328                 soisdisconnecting(so);
1329                 sbflush(&so->so_rcv.sb);
1330                 tp = tcp_usrclosed(tp);
1331                 if (tp)
1332                         tcp_output(tp);
1333         }
1334         return (tp);
1335 }
1336
1337 /*
1338  * User issued close, and wish to trail through shutdown states:
1339  * if never received SYN, just forget it.  If got a SYN from peer,
1340  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
1341  * If already got a FIN from peer, then almost done; go to LAST_ACK
1342  * state.  In all other cases, have already sent FIN to peer (e.g.
1343  * after PRU_SHUTDOWN), and just have to play tedious game waiting
1344  * for peer to send FIN or not respond to keep-alives, etc.
1345  * We can let the user exit from the close as soon as the FIN is acked.
1346  */
1347 static struct tcpcb *
1348 tcp_usrclosed(struct tcpcb *tp)
1349 {
1350
1351         switch (tp->t_state) {
1352
1353         case TCPS_CLOSED:
1354         case TCPS_LISTEN:
1355                 tp->t_state = TCPS_CLOSED;
1356                 tp = tcp_close(tp);
1357                 break;
1358
1359         case TCPS_SYN_SENT:
1360         case TCPS_SYN_RECEIVED:
1361                 tp->t_flags |= TF_NEEDFIN;
1362                 break;
1363
1364         case TCPS_ESTABLISHED:
1365                 tp->t_state = TCPS_FIN_WAIT_1;
1366                 break;
1367
1368         case TCPS_CLOSE_WAIT:
1369                 tp->t_state = TCPS_LAST_ACK;
1370                 break;
1371         }
1372         if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
1373                 soisdisconnected(tp->t_inpcb->inp_socket);
1374                 /* To prevent the connection hanging in FIN_WAIT_2 forever. */
1375                 if (tp->t_state == TCPS_FIN_WAIT_2)
1376                         callout_reset(tp->tt_2msl, tcp_maxidle,
1377                                       tcp_timer_2msl, tp);
1378         }
1379         return (tp);
1380 }