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