tcp/usrreq: TCP socket must not be reattached
[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. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *      From: @(#)tcp_usrreq.c  8.2 (Berkeley) 1/3/94
63  * $FreeBSD: src/sys/netinet/tcp_usrreq.c,v 1.51.2.17 2002/10/11 11:46:44 ume Exp $
64  */
65
66 #include "opt_ipsec.h"
67 #include "opt_inet.h"
68 #include "opt_inet6.h"
69 #include "opt_tcpdebug.h"
70
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/malloc.h>
75 #include <sys/sysctl.h>
76 #include <sys/globaldata.h>
77 #include <sys/thread.h>
78
79 #include <sys/mbuf.h>
80 #ifdef INET6
81 #include <sys/domain.h>
82 #endif /* INET6 */
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/socketops.h>
86 #include <sys/protosw.h>
87
88 #include <sys/thread2.h>
89 #include <sys/msgport2.h>
90 #include <sys/socketvar2.h>
91
92 #include <net/if.h>
93 #include <net/netisr.h>
94 #include <net/route.h>
95
96 #include <net/netmsg2.h>
97 #include <net/netisr2.h>
98
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #ifdef INET6
102 #include <netinet/ip6.h>
103 #endif
104 #include <netinet/in_pcb.h>
105 #ifdef INET6
106 #include <netinet6/in6_pcb.h>
107 #endif
108 #include <netinet/in_var.h>
109 #include <netinet/ip_var.h>
110 #ifdef INET6
111 #include <netinet6/ip6_var.h>
112 #include <netinet6/tcp6_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_timer2.h>
119 #include <netinet/tcp_var.h>
120 #include <netinet/tcpip.h>
121 #ifdef TCPDEBUG
122 #include <netinet/tcp_debug.h>
123 #endif
124
125 #ifdef IPSEC
126 #include <netinet6/ipsec.h>
127 #endif /*IPSEC*/
128
129 /*
130  * TCP protocol interface to socket abstraction.
131  */
132 extern  char *tcpstates[];      /* XXX ??? */
133
134 static int      tcp_attach (struct socket *, struct pru_attach_info *);
135 static void     tcp_connect (netmsg_t msg);
136 #ifdef INET6
137 static void     tcp6_connect (netmsg_t msg);
138 static int      tcp6_connect_oncpu(struct tcpcb *tp, int flags,
139                                 struct mbuf **mp,
140                                 struct sockaddr_in6 *sin6,
141                                 struct in6_addr *addr6);
142 #endif /* INET6 */
143 static struct tcpcb *
144                 tcp_disconnect (struct tcpcb *);
145 static struct tcpcb *
146                 tcp_usrclosed (struct tcpcb *);
147
148 #ifdef TCPDEBUG
149 #define TCPDEBUG0       int ostate = 0
150 #define TCPDEBUG1()     ostate = tp ? tp->t_state : 0
151 #define TCPDEBUG2(req)  if (tp && (so->so_options & SO_DEBUG)) \
152                                 tcp_trace(TA_USER, ostate, tp, 0, 0, req)
153 #else
154 #define TCPDEBUG0
155 #define TCPDEBUG1()
156 #define TCPDEBUG2(req)
157 #endif
158
159 static int      tcp_lport_extension = 1;
160 SYSCTL_INT(_net_inet_tcp, OID_AUTO, lportext, CTLFLAG_RW,
161     &tcp_lport_extension, 0, "");
162
163 /*
164  * For some ill optimized programs, which try to use TCP_NOPUSH
165  * to improve performance, will have small amount of data sits
166  * in the sending buffer.  These small amount of data will _not_
167  * be pushed into the network until more data are written into
168  * the socket or the socket write side is shutdown.
169  */ 
170 static int      tcp_disable_nopush = 1;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, disable_nopush, CTLFLAG_RW,
172     &tcp_disable_nopush, 0, "TCP_NOPUSH socket option will have no effect");
173
174 /*
175  * Allocate socket buffer space.
176  */
177 static int
178 tcp_usr_preattach(struct socket *so, int proto __unused,
179     struct pru_attach_info *ai)
180 {
181         int error;
182
183         if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
184                 error = soreserve(so, tcp_sendspace, tcp_recvspace,
185                                   ai->sb_rlimit);
186                 if (error)
187                         return (error);
188         }
189         atomic_set_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE | SSB_PREALLOC);
190         atomic_set_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE | SSB_PREALLOC);
191
192         return 0;
193 }
194
195 /*
196  * TCP attaches to socket via pru_attach(), reserving space,
197  * and an internet control block.  This socket may move to
198  * other CPU later when we bind/connect.
199  */
200 static void
201 tcp_usr_attach(netmsg_t msg)
202 {
203         struct socket *so = msg->base.nm_so;
204         struct pru_attach_info *ai = msg->attach.nm_ai;
205         int error;
206         struct inpcb *inp;
207         struct tcpcb *tp = NULL;
208         TCPDEBUG0;
209
210         soreference(so);
211         inp = so->so_pcb;
212         KASSERT(inp == NULL, ("tcp socket attached"));
213         TCPDEBUG1();
214
215         error = tcp_attach(so, ai);
216         if (error)
217                 goto out;
218
219         if ((so->so_options & SO_LINGER) && so->so_linger == 0)
220                 so->so_linger = TCP_LINGERTIME;
221         tp = sototcpcb(so);
222 out:
223         sofree(so);             /* from ref above */
224         TCPDEBUG2(PRU_ATTACH);
225         lwkt_replymsg(&msg->lmsg, error);
226 }
227
228 /*
229  * pru_detach() detaches the TCP protocol from the socket.
230  * If the protocol state is non-embryonic, then can't
231  * do this directly: have to initiate a pru_disconnect(),
232  * which may finish later; embryonic TCB's can just
233  * be discarded here.
234  */
235 static void
236 tcp_usr_detach(netmsg_t msg)
237 {
238         struct socket *so = msg->base.nm_so;
239         int error = 0;
240         struct inpcb *inp;
241         struct tcpcb *tp;
242         TCPDEBUG0;
243
244         inp = so->so_pcb;
245
246         /*
247          * If the inp is already detached or never attached, it may have
248          * been due to an async close or async attach failure.  Just return
249          * as if no error occured.
250          *
251          * It's possible for the tcpcb (tp) to disconnect from the inp due
252          * to tcp_drop()->tcp_close() being called.  This may occur *after*
253          * the detach message has been queued so we may find a NULL tp here.
254          */
255         if (inp) {
256                 if ((tp = intotcpcb(inp)) != NULL) {
257                         TCPDEBUG1();
258                         tp = tcp_disconnect(tp);
259                         TCPDEBUG2(PRU_DETACH);
260                 }
261         }
262         lwkt_replymsg(&msg->lmsg, error);
263 }
264
265 /*
266  * NOTE: ignore_error is non-zero for certain disconnection races
267  * which we want to silently allow, otherwise close() may return
268  * an unexpected error.
269  *
270  * NOTE: The variables (msg) and (tp) are assumed.
271  */
272 #define COMMON_START(so, inp, ignore_error)                     \
273         TCPDEBUG0;                                              \
274                                                                 \
275         inp = so->so_pcb;                                       \
276         do {                                                    \
277                 if (inp == NULL) {                              \
278                         error = ignore_error ? 0 : EINVAL;      \
279                         tp = NULL;                              \
280                         goto out;                               \
281                 }                                               \
282                 tp = intotcpcb(inp);                            \
283                 TCPDEBUG1();                                    \
284         } while(0)
285
286 #define COMMON_END1(req, noreply)                               \
287         out: do {                                               \
288                 TCPDEBUG2(req);                                 \
289                 if (!(noreply))                                 \
290                         lwkt_replymsg(&msg->lmsg, error);       \
291                 return;                                         \
292         } while(0)
293
294 #define COMMON_END(req)         COMMON_END1((req), 0)
295
296 /*
297  * Give the socket an address.
298  */
299 static void
300 tcp_usr_bind(netmsg_t msg)
301 {
302         struct socket *so = msg->bind.base.nm_so;
303         struct sockaddr *nam = msg->bind.nm_nam;
304         struct thread *td = msg->bind.nm_td;
305         int error = 0;
306         struct inpcb *inp;
307         struct tcpcb *tp;
308         struct sockaddr_in *sinp;
309
310         COMMON_START(so, inp, 0);
311
312         /*
313          * Must check for multicast addresses and disallow binding
314          * to them.
315          */
316         sinp = (struct sockaddr_in *)nam;
317         if (sinp->sin_family == AF_INET &&
318             IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
319                 error = EAFNOSUPPORT;
320                 goto out;
321         }
322         error = in_pcbbind(inp, nam, td);
323         if (error)
324                 goto out;
325
326         COMMON_END(PRU_BIND);
327 }
328
329 #ifdef INET6
330
331 static void
332 tcp6_usr_bind(netmsg_t msg)
333 {
334         struct socket *so = msg->bind.base.nm_so;
335         struct sockaddr *nam = msg->bind.nm_nam;
336         struct thread *td = msg->bind.nm_td;
337         int error = 0;
338         struct inpcb *inp;
339         struct tcpcb *tp;
340         struct sockaddr_in6 *sin6p;
341
342         COMMON_START(so, inp, 0);
343
344         /*
345          * Must check for multicast addresses and disallow binding
346          * to them.
347          */
348         sin6p = (struct sockaddr_in6 *)nam;
349         if (sin6p->sin6_family == AF_INET6 &&
350             IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr)) {
351                 error = EAFNOSUPPORT;
352                 goto out;
353         }
354         error = in6_pcbbind(inp, nam, td);
355         if (error)
356                 goto out;
357         COMMON_END(PRU_BIND);
358 }
359 #endif /* INET6 */
360
361 struct netmsg_inswildcard {
362         struct netmsg_base      base;
363         struct inpcb            *nm_inp;
364 };
365
366 static void
367 in_pcbinswildcardhash_handler(netmsg_t msg)
368 {
369         struct netmsg_inswildcard *nm = (struct netmsg_inswildcard *)msg;
370         int cpu = mycpuid, nextcpu;
371
372         in_pcbinswildcardhash_oncpu(nm->nm_inp, &tcbinfo[cpu]);
373
374         nextcpu = cpu + 1;
375         if (nextcpu < ncpus2)
376                 lwkt_forwardmsg(netisr_cpuport(nextcpu), &nm->base.lmsg);
377         else
378                 lwkt_replymsg(&nm->base.lmsg, 0);
379 }
380
381 static void
382 tcp_sosetport(struct lwkt_msg *msg, lwkt_port_t port)
383 {
384         sosetport(((struct netmsg_base *)msg)->nm_so, port);
385 }
386
387 /*
388  * Prepare to accept connections.
389  */
390 static void
391 tcp_usr_listen(netmsg_t msg)
392 {
393         struct socket *so = msg->listen.base.nm_so;
394         struct thread *td = msg->listen.nm_td;
395         int error = 0;
396         struct inpcb *inp;
397         struct tcpcb *tp;
398         struct netmsg_inswildcard nm;
399         lwkt_port_t port0 = netisr_cpuport(0);
400
401         COMMON_START(so, inp, 0);
402
403         if (&curthread->td_msgport != port0) {
404                 lwkt_msg_t lmsg = &msg->listen.base.lmsg;
405
406                 KASSERT((msg->listen.nm_flags & PRUL_RELINK) == 0,
407                     ("already asked to relink"));
408
409                 in_pcbunlink(so->so_pcb, &tcbinfo[mycpuid]);
410                 msg->listen.nm_flags |= PRUL_RELINK;
411
412                 /* See the related comment in tcp_connect() */
413                 lwkt_setmsg_receipt(lmsg, tcp_sosetport);
414                 lwkt_forwardmsg(port0, lmsg);
415                 /* msg invalid now */
416                 return;
417         }
418         KASSERT(so->so_port == port0, ("so_port is not netisr0"));
419
420         if (msg->listen.nm_flags & PRUL_RELINK) {
421                 msg->listen.nm_flags &= ~PRUL_RELINK;
422                 in_pcblink(so->so_pcb, &tcbinfo[mycpuid]);
423         }
424         KASSERT(inp->inp_pcbinfo == &tcbinfo[0], ("pcbinfo is not tcbinfo0"));
425
426         if (tp->t_flags & TF_LISTEN)
427                 goto out;
428
429         if (inp->inp_lport == 0) {
430                 error = in_pcbbind(inp, NULL, td);
431                 if (error)
432                         goto out;
433         }
434
435         tp->t_state = TCPS_LISTEN;
436         tp->t_flags |= TF_LISTEN;
437         tp->tt_msg = NULL; /* Catch any invalid timer usage */
438
439         if (ncpus2 > 1) {
440                 /*
441                  * Put this inpcb into wildcard hash on other cpus.
442                  */
443                 ASSERT_INP_NOTINHASH(inp);
444                 netmsg_init(&nm.base, NULL, &curthread->td_msgport,
445                             MSGF_PRIORITY, in_pcbinswildcardhash_handler);
446                 nm.nm_inp = inp;
447                 lwkt_domsg(netisr_cpuport(1), &nm.base.lmsg, 0);
448         }
449         in_pcbinswildcardhash(inp);
450         COMMON_END(PRU_LISTEN);
451 }
452
453 #ifdef INET6
454
455 static void
456 tcp6_usr_listen(netmsg_t msg)
457 {
458         struct socket *so = msg->listen.base.nm_so;
459         struct thread *td = msg->listen.nm_td;
460         int error = 0;
461         struct inpcb *inp;
462         struct tcpcb *tp;
463         struct netmsg_inswildcard nm;
464
465         COMMON_START(so, inp, 0);
466
467         if (tp->t_flags & TF_LISTEN)
468                 goto out;
469
470         if (inp->inp_lport == 0) {
471                 error = in6_pcbbind(inp, NULL, td);
472                 if (error)
473                         goto out;
474         }
475
476         tp->t_state = TCPS_LISTEN;
477         tp->t_flags |= TF_LISTEN;
478         tp->tt_msg = NULL; /* Catch any invalid timer usage */
479
480         if (ncpus2 > 1) {
481                 /*
482                  * Put this inpcb into wildcard hash on other cpus.
483                  */
484                 KKASSERT(so->so_port == netisr_cpuport(0));
485                 ASSERT_IN_NETISR(0);
486                 KKASSERT(inp->inp_pcbinfo == &tcbinfo[0]);
487                 ASSERT_INP_NOTINHASH(inp);
488
489                 netmsg_init(&nm.base, NULL, &curthread->td_msgport,
490                             MSGF_PRIORITY, in_pcbinswildcardhash_handler);
491                 nm.nm_inp = inp;
492                 lwkt_domsg(netisr_cpuport(1), &nm.base.lmsg, 0);
493         }
494         in_pcbinswildcardhash(inp);
495         COMMON_END(PRU_LISTEN);
496 }
497 #endif /* INET6 */
498
499 /*
500  * Initiate connection to peer.
501  * Create a template for use in transmissions on this connection.
502  * Enter SYN_SENT state, and mark socket as connecting.
503  * Start keep-alive timer, and seed output sequence space.
504  * Send initial segment on connection.
505  */
506 static void
507 tcp_usr_connect(netmsg_t msg)
508 {
509         struct socket *so = msg->connect.base.nm_so;
510         struct sockaddr *nam = msg->connect.nm_nam;
511         struct thread *td = msg->connect.nm_td;
512         int error = 0;
513         struct inpcb *inp;
514         struct tcpcb *tp;
515         struct sockaddr_in *sinp;
516
517         COMMON_START(so, inp, 0);
518
519         /*
520          * Must disallow TCP ``connections'' to multicast addresses.
521          */
522         sinp = (struct sockaddr_in *)nam;
523         if (sinp->sin_family == AF_INET
524             && IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
525                 error = EAFNOSUPPORT;
526                 goto out;
527         }
528
529         if (!prison_remote_ip(td, (struct sockaddr*)sinp)) {
530                 error = EAFNOSUPPORT; /* IPv6 only jail */
531                 goto out;
532         }
533
534         tcp_connect(msg);
535         /* msg is invalid now */
536         return;
537 out:
538         if (msg->connect.nm_m) {
539                 m_freem(msg->connect.nm_m);
540                 msg->connect.nm_m = NULL;
541         }
542         if (msg->connect.nm_flags & PRUC_HELDTD)
543                 lwkt_rele(td);
544         if (error && (msg->connect.nm_flags & PRUC_ASYNC)) {
545                 so->so_error = error;
546                 soisdisconnected(so);
547         }
548         lwkt_replymsg(&msg->lmsg, error);
549 }
550
551 #ifdef INET6
552
553 static void
554 tcp6_usr_connect(netmsg_t msg)
555 {
556         struct socket *so = msg->connect.base.nm_so;
557         struct sockaddr *nam = msg->connect.nm_nam;
558         struct thread *td = msg->connect.nm_td;
559         int error = 0;
560         struct inpcb *inp;
561         struct tcpcb *tp;
562         struct sockaddr_in6 *sin6p;
563
564         COMMON_START(so, inp, 0);
565
566         /*
567          * Must disallow TCP ``connections'' to multicast addresses.
568          */
569         sin6p = (struct sockaddr_in6 *)nam;
570         if (sin6p->sin6_family == AF_INET6
571             && IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr)) {
572                 error = EAFNOSUPPORT;
573                 goto out;
574         }
575
576         if (!prison_remote_ip(td, nam)) {
577                 error = EAFNOSUPPORT; /* IPv4 only jail */
578                 goto out;
579         }
580
581         /* Reject v4-mapped address */
582         if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
583                 error = EADDRNOTAVAIL;
584                 goto out;
585         }
586
587         inp->inp_inc.inc_isipv6 = 1;
588         tcp6_connect(msg);
589         /* msg is invalid now */
590         return;
591 out:
592         if (msg->connect.nm_m) {
593                 m_freem(msg->connect.nm_m);
594                 msg->connect.nm_m = NULL;
595         }
596         lwkt_replymsg(&msg->lmsg, error);
597 }
598
599 #endif /* INET6 */
600
601 /*
602  * Initiate disconnect from peer.
603  * If connection never passed embryonic stage, just drop;
604  * else if don't need to let data drain, then can just drop anyways,
605  * else have to begin TCP shutdown process: mark socket disconnecting,
606  * drain unread data, state switch to reflect user close, and
607  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
608  * when peer sends FIN and acks ours.
609  *
610  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
611  */
612 static void
613 tcp_usr_disconnect(netmsg_t msg)
614 {
615         struct socket *so = msg->disconnect.base.nm_so;
616         int error = 0;
617         struct inpcb *inp;
618         struct tcpcb *tp;
619
620         COMMON_START(so, inp, 1);
621         tp = tcp_disconnect(tp);
622         COMMON_END(PRU_DISCONNECT);
623 }
624
625 /*
626  * Accept a connection.  Essentially all the work is
627  * done at higher levels; just return the address
628  * of the peer, storing through addr.
629  */
630 static void
631 tcp_usr_accept(netmsg_t msg)
632 {
633         struct socket *so = msg->accept.base.nm_so;
634         struct sockaddr **nam = msg->accept.nm_nam;
635         int error = 0;
636         struct inpcb *inp;
637         struct tcpcb *tp = NULL;
638         TCPDEBUG0;
639
640         inp = so->so_pcb;
641         if (so->so_state & SS_ISDISCONNECTED) {
642                 error = ECONNABORTED;
643                 goto out;
644         }
645         if (inp == NULL) {
646                 error = EINVAL;
647                 goto out;
648         }
649
650         tp = intotcpcb(inp);
651         TCPDEBUG1();
652         in_setpeeraddr(so, nam);
653         COMMON_END(PRU_ACCEPT);
654 }
655
656 #ifdef INET6
657 static void
658 tcp6_usr_accept(netmsg_t msg)
659 {
660         struct socket *so = msg->accept.base.nm_so;
661         struct sockaddr **nam = msg->accept.nm_nam;
662         int error = 0;
663         struct inpcb *inp;
664         struct tcpcb *tp = NULL;
665         TCPDEBUG0;
666
667         inp = so->so_pcb;
668
669         if (so->so_state & SS_ISDISCONNECTED) {
670                 error = ECONNABORTED;
671                 goto out;
672         }
673         if (inp == NULL) {
674                 error = EINVAL;
675                 goto out;
676         }
677         tp = intotcpcb(inp);
678         TCPDEBUG1();
679         in6_setpeeraddr(so, nam);
680         COMMON_END(PRU_ACCEPT);
681 }
682 #endif /* INET6 */
683
684 /*
685  * Mark the connection as being incapable of further output.
686  */
687 static void
688 tcp_usr_shutdown(netmsg_t msg)
689 {
690         struct socket *so = msg->shutdown.base.nm_so;
691         int error = 0;
692         struct inpcb *inp;
693         struct tcpcb *tp;
694
695         COMMON_START(so, inp, 0);
696         socantsendmore(so);
697         tp = tcp_usrclosed(tp);
698         if (tp)
699                 error = tcp_output(tp);
700         COMMON_END(PRU_SHUTDOWN);
701 }
702
703 /*
704  * After a receive, possibly send window update to peer.
705  */
706 static void
707 tcp_usr_rcvd(netmsg_t msg)
708 {
709         struct socket *so = msg->rcvd.base.nm_so;
710         int error = 0, noreply = 0;
711         struct inpcb *inp;
712         struct tcpcb *tp;
713
714         COMMON_START(so, inp, 0);
715
716         if (msg->rcvd.nm_pru_flags & PRUR_ASYNC) {
717                 noreply = 1;
718                 so_async_rcvd_reply(so);
719         }
720         tcp_output(tp);
721
722         COMMON_END1(PRU_RCVD, noreply);
723 }
724
725 /*
726  * Do a send by putting data in output queue and updating urgent
727  * marker if URG set.  Possibly send more data.  Unlike the other
728  * pru_*() routines, the mbuf chains are our responsibility.  We
729  * must either enqueue them or free them.  The other pru_* routines
730  * generally are caller-frees.
731  */
732 static void
733 tcp_usr_send(netmsg_t msg)
734 {
735         struct socket *so = msg->send.base.nm_so;
736         int flags = msg->send.nm_flags;
737         struct mbuf *m = msg->send.nm_m;
738         int error = 0;
739         struct inpcb *inp;
740         struct tcpcb *tp;
741         TCPDEBUG0;
742
743         KKASSERT(msg->send.nm_control == NULL);
744         KKASSERT(msg->send.nm_addr == NULL);
745         KKASSERT((flags & PRUS_FREEADDR) == 0);
746
747         inp = so->so_pcb;
748
749         if (inp == NULL) {
750                 /*
751                  * OOPS! we lost a race, the TCP session got reset after
752                  * we checked SS_CANTSENDMORE, eg: while doing uiomove or a
753                  * network interrupt in the non-critical section of sosend().
754                  */
755                 m_freem(m);
756                 error = ECONNRESET;     /* XXX EPIPE? */
757                 tp = NULL;
758                 TCPDEBUG1();
759                 goto out;
760         }
761         tp = intotcpcb(inp);
762         TCPDEBUG1();
763
764 #ifdef foo
765         /*
766          * This is no longer necessary, since:
767          * - sosendtcp() has already checked it for us
768          * - It does not work with asynchronized send
769          */
770
771         /*
772          * Don't let too much OOB data build up
773          */
774         if (flags & PRUS_OOB) {
775                 if (ssb_space(&so->so_snd) < -512) {
776                         m_freem(m);
777                         error = ENOBUFS;
778                         goto out;
779                 }
780         }
781 #endif
782
783         /*
784          * Pump the data into the socket.
785          */
786         if (m) {
787                 ssb_appendstream(&so->so_snd, m);
788                 sowwakeup(so);
789         }
790         if (flags & PRUS_OOB) {
791                 /*
792                  * According to RFC961 (Assigned Protocols),
793                  * the urgent pointer points to the last octet
794                  * of urgent data.  We continue, however,
795                  * to consider it to indicate the first octet
796                  * of data past the urgent section.
797                  * Otherwise, snd_up should be one lower.
798                  */
799                 tp->snd_up = tp->snd_una + so->so_snd.ssb_cc;
800                 tp->t_flags |= TF_FORCE;
801                 error = tcp_output(tp);
802                 tp->t_flags &= ~TF_FORCE;
803         } else {
804                 if (flags & PRUS_EOF) {
805                         /*
806                          * Close the send side of the connection after
807                          * the data is sent.
808                          */
809                         socantsendmore(so);
810                         tp = tcp_usrclosed(tp);
811                 }
812                 if (tp != NULL && !tcp_output_pending(tp)) {
813                         if (flags & PRUS_MORETOCOME)
814                                 tp->t_flags |= TF_MORETOCOME;
815                         error = tcp_output_fair(tp);
816                         if (flags & PRUS_MORETOCOME)
817                                 tp->t_flags &= ~TF_MORETOCOME;
818                 }
819         }
820         COMMON_END1((flags & PRUS_OOB) ? PRU_SENDOOB :
821                    ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND),
822                    (flags & PRUS_NOREPLY));
823 }
824
825 /*
826  * NOTE: (so) is referenced from soabort*() and netmsg_pru_abort()
827  *       will sofree() it when we return.
828  */
829 static void
830 tcp_usr_abort(netmsg_t msg)
831 {
832         struct socket *so = msg->abort.base.nm_so;
833         int error = 0;
834         struct inpcb *inp;
835         struct tcpcb *tp;
836
837         COMMON_START(so, inp, 1);
838         tp = tcp_drop(tp, ECONNABORTED);
839         COMMON_END(PRU_ABORT);
840 }
841
842 /*
843  * Receive out-of-band data.
844  */
845 static void
846 tcp_usr_rcvoob(netmsg_t msg)
847 {
848         struct socket *so = msg->rcvoob.base.nm_so;
849         struct mbuf *m = msg->rcvoob.nm_m;
850         int flags = msg->rcvoob.nm_flags;
851         int error = 0;
852         struct inpcb *inp;
853         struct tcpcb *tp;
854
855         COMMON_START(so, inp, 0);
856         if ((so->so_oobmark == 0 &&
857              (so->so_state & SS_RCVATMARK) == 0) ||
858             so->so_options & SO_OOBINLINE ||
859             tp->t_oobflags & TCPOOB_HADDATA) {
860                 error = EINVAL;
861                 goto out;
862         }
863         if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
864                 error = EWOULDBLOCK;
865                 goto out;
866         }
867         m->m_len = 1;
868         *mtod(m, caddr_t) = tp->t_iobc;
869         if ((flags & MSG_PEEK) == 0)
870                 tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
871         COMMON_END(PRU_RCVOOB);
872 }
873
874 static void
875 tcp_usr_savefaddr(struct socket *so, const struct sockaddr *faddr)
876 {
877         in_savefaddr(so, faddr);
878 }
879
880 #ifdef INET6
881 static void
882 tcp6_usr_savefaddr(struct socket *so, const struct sockaddr *faddr)
883 {
884         in6_savefaddr(so, faddr);
885 }
886 #endif
887
888 static int
889 tcp_usr_preconnect(struct socket *so, const struct sockaddr *nam,
890     struct thread *td __unused)
891 {
892         const struct sockaddr_in *sinp;
893
894         sinp = (const struct sockaddr_in *)nam;
895         if (sinp->sin_family == AF_INET &&
896             IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
897                 return EAFNOSUPPORT;
898
899         soisconnecting(so);
900         return 0;
901 }
902
903 /* xxx - should be const */
904 struct pr_usrreqs tcp_usrreqs = {
905         .pru_abort = tcp_usr_abort,
906         .pru_accept = tcp_usr_accept,
907         .pru_attach = tcp_usr_attach,
908         .pru_bind = tcp_usr_bind,
909         .pru_connect = tcp_usr_connect,
910         .pru_connect2 = pr_generic_notsupp,
911         .pru_control = in_control_dispatch,
912         .pru_detach = tcp_usr_detach,
913         .pru_disconnect = tcp_usr_disconnect,
914         .pru_listen = tcp_usr_listen,
915         .pru_peeraddr = in_setpeeraddr_dispatch,
916         .pru_rcvd = tcp_usr_rcvd,
917         .pru_rcvoob = tcp_usr_rcvoob,
918         .pru_send = tcp_usr_send,
919         .pru_sense = pru_sense_null,
920         .pru_shutdown = tcp_usr_shutdown,
921         .pru_sockaddr = in_setsockaddr_dispatch,
922         .pru_sosend = sosendtcp,
923         .pru_soreceive = sorecvtcp,
924         .pru_savefaddr = tcp_usr_savefaddr,
925         .pru_preconnect = tcp_usr_preconnect,
926         .pru_preattach = tcp_usr_preattach
927 };
928
929 #ifdef INET6
930 struct pr_usrreqs tcp6_usrreqs = {
931         .pru_abort = tcp_usr_abort,
932         .pru_accept = tcp6_usr_accept,
933         .pru_attach = tcp_usr_attach,
934         .pru_bind = tcp6_usr_bind,
935         .pru_connect = tcp6_usr_connect,
936         .pru_connect2 = pr_generic_notsupp,
937         .pru_control = in6_control_dispatch,
938         .pru_detach = tcp_usr_detach,
939         .pru_disconnect = tcp_usr_disconnect,
940         .pru_listen = tcp6_usr_listen,
941         .pru_peeraddr = in6_setpeeraddr_dispatch,
942         .pru_rcvd = tcp_usr_rcvd,
943         .pru_rcvoob = tcp_usr_rcvoob,
944         .pru_send = tcp_usr_send,
945         .pru_sense = pru_sense_null,
946         .pru_shutdown = tcp_usr_shutdown,
947         .pru_sockaddr = in6_setsockaddr_dispatch,
948         .pru_sosend = sosendtcp,
949         .pru_soreceive = sorecvtcp,
950         .pru_savefaddr = tcp6_usr_savefaddr
951 };
952 #endif /* INET6 */
953
954 static int
955 tcp_connect_oncpu(struct tcpcb *tp, int flags, struct mbuf *m,
956                   struct sockaddr_in *sin, struct sockaddr_in *if_sin)
957 {
958         struct inpcb *inp = tp->t_inpcb, *oinp;
959         struct socket *so = inp->inp_socket;
960         struct route *ro = &inp->inp_route;
961
962         KASSERT(inp->inp_pcbinfo == &tcbinfo[mycpu->gd_cpuid],
963             ("pcbinfo mismatch"));
964
965         oinp = in_pcblookup_hash(inp->inp_pcbinfo,
966                                  sin->sin_addr, sin->sin_port,
967                                  (inp->inp_laddr.s_addr != INADDR_ANY ?
968                                   inp->inp_laddr : if_sin->sin_addr),
969                                 inp->inp_lport, 0, NULL);
970         if (oinp != NULL) {
971                 m_freem(m);
972                 return (EADDRINUSE);
973         }
974         if (inp->inp_laddr.s_addr == INADDR_ANY)
975                 inp->inp_laddr = if_sin->sin_addr;
976         inp->inp_faddr = sin->sin_addr;
977         inp->inp_fport = sin->sin_port;
978         in_pcbinsconnhash(inp);
979
980         /*
981          * We are now on the inpcb's owner CPU, if the cached route was
982          * freed because the rtentry's owner CPU is not the current CPU
983          * (e.g. in tcp_connect()), then we try to reallocate it here with
984          * the hope that a rtentry may be cloned from a RTF_PRCLONING
985          * rtentry.
986          */
987         if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
988             ro->ro_rt == NULL) {
989                 bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
990                 ro->ro_dst.sa_family = AF_INET;
991                 ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
992                 ((struct sockaddr_in *)&ro->ro_dst)->sin_addr =
993                         sin->sin_addr;
994                 rtalloc(ro);
995         }
996
997         /*
998          * Now that no more errors can occur, change the protocol processing
999          * port to the current thread (which is the correct thread).
1000          *
1001          * Create TCP timer message now; we are on the tcpcb's owner
1002          * CPU/thread.
1003          */
1004         tcp_create_timermsg(tp, &curthread->td_msgport);
1005
1006         /*
1007          * Compute window scaling to request.  Use a larger scaling then
1008          * needed for the initial receive buffer in case the receive buffer
1009          * gets expanded.
1010          */
1011         if (tp->request_r_scale < TCP_MIN_WINSHIFT)
1012                 tp->request_r_scale = TCP_MIN_WINSHIFT;
1013         while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1014                (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.ssb_hiwat
1015         ) {
1016                 tp->request_r_scale++;
1017         }
1018
1019         soisconnecting(so);
1020         tcpstat.tcps_connattempt++;
1021         tp->t_state = TCPS_SYN_SENT;
1022         tcp_callout_reset(tp, tp->tt_keep, tp->t_keepinit, tcp_timer_keep);
1023         tp->iss = tcp_new_isn(tp);
1024         tcp_sendseqinit(tp);
1025         if (m) {
1026                 ssb_appendstream(&so->so_snd, m);
1027                 m = NULL;
1028                 if (flags & PRUS_OOB)
1029                         tp->snd_up = tp->snd_una + so->so_snd.ssb_cc;
1030         }
1031
1032         /*
1033          * Close the send side of the connection after
1034          * the data is sent if flagged.
1035          */
1036         if ((flags & (PRUS_OOB|PRUS_EOF)) == PRUS_EOF) {
1037                 socantsendmore(so);
1038                 tp = tcp_usrclosed(tp);
1039         }
1040         return (tcp_output(tp));
1041 }
1042
1043 /*
1044  * Common subroutine to open a TCP connection to remote host specified
1045  * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1046  * port number if needed.  Call in_pcbladdr to do the routing and to choose
1047  * a local host address (interface).
1048  * Initialize connection parameters and enter SYN-SENT state.
1049  */
1050 static void
1051 tcp_connect(netmsg_t msg)
1052 {
1053         struct socket *so = msg->connect.base.nm_so;
1054         struct sockaddr *nam = msg->connect.nm_nam;
1055         struct thread *td = msg->connect.nm_td;
1056         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1057         struct sockaddr_in *if_sin = NULL;
1058         struct inpcb *inp;
1059         struct tcpcb *tp;
1060         int error;
1061         lwkt_port_t port;
1062
1063         COMMON_START(so, inp, 0);
1064
1065         /*
1066          * Reconnect our pcb if we have to
1067          */
1068         if (msg->connect.nm_flags & PRUC_RECONNECT) {
1069                 msg->connect.nm_flags &= ~PRUC_RECONNECT;
1070                 in_pcblink(so->so_pcb, &tcbinfo[mycpu->gd_cpuid]);
1071         }
1072
1073         /*
1074          * Bind if we have to
1075          */
1076         if (inp->inp_lport == 0) {
1077                 if (tcp_lport_extension) {
1078                         KKASSERT(inp->inp_laddr.s_addr == INADDR_ANY);
1079
1080                         error = in_pcbladdr(inp, nam, &if_sin, td);
1081                         if (error)
1082                                 goto out;
1083                         inp->inp_laddr.s_addr = if_sin->sin_addr.s_addr;
1084
1085                         error = in_pcbbind_remote(inp, nam, td);
1086                         if (error)
1087                                 goto out;
1088
1089                         msg->connect.nm_flags |= PRUC_HASLADDR;
1090                 } else {
1091                         error = in_pcbbind(inp, NULL, td);
1092                         if (error)
1093                                 goto out;
1094                 }
1095         }
1096
1097         if ((msg->connect.nm_flags & PRUC_HASLADDR) == 0) {
1098                 /*
1099                  * Calculate the correct protocol processing thread.  The
1100                  * connect operation must run there.  Set the forwarding
1101                  * port before we forward the message or it will get bounced
1102                  * right back to us.
1103                  */
1104                 error = in_pcbladdr(inp, nam, &if_sin, td);
1105                 if (error)
1106                         goto out;
1107         }
1108         KKASSERT(inp->inp_socket == so);
1109
1110         port = tcp_addrport(sin->sin_addr.s_addr, sin->sin_port,
1111                             (inp->inp_laddr.s_addr != INADDR_ANY ?
1112                              inp->inp_laddr.s_addr : if_sin->sin_addr.s_addr),
1113                             inp->inp_lport);
1114
1115         if (port != &curthread->td_msgport) {
1116                 lwkt_msg_t lmsg = &msg->connect.base.lmsg;
1117
1118                 /*
1119                  * in_pcbladdr() may have allocated a route entry for us
1120                  * on the current CPU, but we need a route entry on the
1121                  * inpcb's owner CPU, so free it here.
1122                  */
1123                 in_pcbresetroute(inp);
1124
1125                 /*
1126                  * We are moving the protocol processing port the socket
1127                  * is on, we have to unlink here and re-link on the
1128                  * target cpu.
1129                  */
1130                 in_pcbunlink(so->so_pcb, &tcbinfo[mycpu->gd_cpuid]);
1131                 msg->connect.nm_flags |= PRUC_RECONNECT;
1132                 msg->connect.base.nm_dispatch = tcp_connect;
1133
1134                 /*
1135                  * Use message put done receipt to change this socket's
1136                  * so_port, i.e. _after_ this message was put onto the
1137                  * target netisr's msgport but _before_ the message could
1138                  * be pulled from the target netisr's msgport, so that:
1139                  * - The upper half (socket code) will not see the new
1140                  *   msgport before this message reaches the new msgport
1141                  *   and messages for this socket will be ordered.
1142                  * - This message will see the new msgport, when its
1143                  *   handler is called in the target netisr.
1144                  *
1145                  * NOTE:
1146                  * We MUST use messege put done receipt to change this
1147                  * socket's so_port:
1148                  * If we changed the so_port in this netisr after the
1149                  * lwkt_forwardmsg (so messages for this socket will be
1150                  * ordered) and changed the so_port in the target netisr
1151                  * at the very beginning of this message's handler, we
1152                  * would suffer so_port overwritten race, given this
1153                  * message might be forwarded again.
1154                  *
1155                  * NOTE:
1156                  * This mechanism depends on that the netisr's msgport
1157                  * is spin msgport (currently it is :).
1158                  *
1159                  * If the upper half saw the new msgport before this
1160                  * message reached the target netisr's msgport, the
1161                  * messages sent from the upper half could reach the new
1162                  * msgport before this message, thus there would be
1163                  * message reordering.  The worst case could be soclose()
1164                  * saw the new msgport and the detach message could reach
1165                  * the new msgport before this message, i.e. the inpcb
1166                  * could have been destroyed when this message was still
1167                  * pending on or on its way to the new msgport.  Other
1168                  * weird cases could also happen, e.g. inpcb->inp_pcbinfo,
1169                  * since we have unlinked this inpcb from the current
1170                  * pcbinfo first.
1171                  */
1172                 lwkt_setmsg_receipt(lmsg, tcp_sosetport);
1173                 lwkt_forwardmsg(port, lmsg);
1174                 /* msg invalid now */
1175                 return;
1176         } else if (msg->connect.nm_flags & PRUC_HELDTD) {
1177                 /*
1178                  * The original thread is no longer needed; release it.
1179                  */
1180                 lwkt_rele(td);
1181                 msg->connect.nm_flags &= ~PRUC_HELDTD;
1182         }
1183         error = tcp_connect_oncpu(tp, msg->connect.nm_sndflags,
1184                                   msg->connect.nm_m, sin, if_sin);
1185         msg->connect.nm_m = NULL;
1186 out:
1187         if (msg->connect.nm_m) {
1188                 m_freem(msg->connect.nm_m);
1189                 msg->connect.nm_m = NULL;
1190         }
1191         if (msg->connect.nm_flags & PRUC_HELDTD)
1192                 lwkt_rele(td);
1193         if (error && (msg->connect.nm_flags & PRUC_ASYNC)) {
1194                 so->so_error = error;
1195                 soisdisconnected(so);
1196         }
1197         lwkt_replymsg(&msg->connect.base.lmsg, error);
1198         /* msg invalid now */
1199 }
1200
1201 #ifdef INET6
1202
1203 static void
1204 tcp6_connect(netmsg_t msg)
1205 {
1206         struct tcpcb *tp;
1207         struct socket *so = msg->connect.base.nm_so;
1208         struct sockaddr *nam = msg->connect.nm_nam;
1209         struct thread *td = msg->connect.nm_td;
1210         struct inpcb *inp;
1211         struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
1212         struct in6_addr *addr6;
1213         lwkt_port_t port;
1214         int error;
1215
1216         COMMON_START(so, inp, 0);
1217
1218         /*
1219          * Reconnect our pcb if we have to
1220          */
1221         if (msg->connect.nm_flags & PRUC_RECONNECT) {
1222                 msg->connect.nm_flags &= ~PRUC_RECONNECT;
1223                 in_pcblink(so->so_pcb, &tcbinfo[mycpu->gd_cpuid]);
1224         }
1225
1226         /*
1227          * Bind if we have to
1228          */
1229         if (inp->inp_lport == 0) {
1230                 error = in6_pcbbind(inp, NULL, td);
1231                 if (error)
1232                         goto out;
1233         }
1234
1235         /*
1236          * Cannot simply call in_pcbconnect, because there might be an
1237          * earlier incarnation of this same connection still in
1238          * TIME_WAIT state, creating an ADDRINUSE error.
1239          */
1240         error = in6_pcbladdr(inp, nam, &addr6, td);
1241         if (error)
1242                 goto out;
1243
1244         port = tcp6_addrport(); /* XXX hack for now, always cpu0 */
1245
1246         if (port != &curthread->td_msgport) {
1247                 lwkt_msg_t lmsg = &msg->connect.base.lmsg;
1248
1249                 /*
1250                  * in_pcbladdr() may have allocated a route entry for us
1251                  * on the current CPU, but we need a route entry on the
1252                  * inpcb's owner CPU, so free it here.
1253                  */
1254                 in_pcbresetroute(inp);
1255
1256                 in_pcbunlink(so->so_pcb, &tcbinfo[mycpu->gd_cpuid]);
1257                 msg->connect.nm_flags |= PRUC_RECONNECT;
1258                 msg->connect.base.nm_dispatch = tcp6_connect;
1259
1260                 /* See the related comment in tcp_connect() */
1261                 lwkt_setmsg_receipt(lmsg, tcp_sosetport);
1262                 lwkt_forwardmsg(port, lmsg);
1263                 /* msg invalid now */
1264                 return;
1265         }
1266         error = tcp6_connect_oncpu(tp, msg->connect.nm_sndflags,
1267                                    &msg->connect.nm_m, sin6, addr6);
1268         /* nm_m may still be intact */
1269 out:
1270         if (msg->connect.nm_m) {
1271                 m_freem(msg->connect.nm_m);
1272                 msg->connect.nm_m = NULL;
1273         }
1274         lwkt_replymsg(&msg->connect.base.lmsg, error);
1275         /* msg invalid now */
1276 }
1277
1278 static int
1279 tcp6_connect_oncpu(struct tcpcb *tp, int flags, struct mbuf **mp,
1280                    struct sockaddr_in6 *sin6, struct in6_addr *addr6)
1281 {
1282         struct mbuf *m = *mp;
1283         struct inpcb *inp = tp->t_inpcb;
1284         struct socket *so = inp->inp_socket;
1285         struct inpcb *oinp;
1286
1287         /*
1288          * Cannot simply call in_pcbconnect, because there might be an
1289          * earlier incarnation of this same connection still in
1290          * TIME_WAIT state, creating an ADDRINUSE error.
1291          */
1292         oinp = in6_pcblookup_hash(inp->inp_pcbinfo,
1293                                   &sin6->sin6_addr, sin6->sin6_port,
1294                                   (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ?
1295                                       addr6 : &inp->in6p_laddr),
1296                                   inp->inp_lport,  0, NULL);
1297         if (oinp)
1298                 return (EADDRINUSE);
1299
1300         if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1301                 inp->in6p_laddr = *addr6;
1302         inp->in6p_faddr = sin6->sin6_addr;
1303         inp->inp_fport = sin6->sin6_port;
1304         if ((sin6->sin6_flowinfo & IPV6_FLOWINFO_MASK) != 0)
1305                 inp->in6p_flowinfo = sin6->sin6_flowinfo;
1306         in_pcbinsconnhash(inp);
1307
1308         /*
1309          * Now that no more errors can occur, change the protocol processing
1310          * port to the current thread (which is the correct thread).
1311          *
1312          * Create TCP timer message now; we are on the tcpcb's owner
1313          * CPU/thread.
1314          */
1315         tcp_create_timermsg(tp, &curthread->td_msgport);
1316
1317         /* Compute window scaling to request.  */
1318         if (tp->request_r_scale < TCP_MIN_WINSHIFT)
1319                 tp->request_r_scale = TCP_MIN_WINSHIFT;
1320         while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1321             (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.ssb_hiwat) {
1322                 tp->request_r_scale++;
1323         }
1324
1325         soisconnecting(so);
1326         tcpstat.tcps_connattempt++;
1327         tp->t_state = TCPS_SYN_SENT;
1328         tcp_callout_reset(tp, tp->tt_keep, tp->t_keepinit, tcp_timer_keep);
1329         tp->iss = tcp_new_isn(tp);
1330         tcp_sendseqinit(tp);
1331         if (m) {
1332                 ssb_appendstream(&so->so_snd, m);
1333                 *mp = NULL;
1334                 if (flags & PRUS_OOB)
1335                         tp->snd_up = tp->snd_una + so->so_snd.ssb_cc;
1336         }
1337
1338         /*
1339          * Close the send side of the connection after
1340          * the data is sent if flagged.
1341          */
1342         if ((flags & (PRUS_OOB|PRUS_EOF)) == PRUS_EOF) {
1343                 socantsendmore(so);
1344                 tp = tcp_usrclosed(tp);
1345         }
1346         return (tcp_output(tp));
1347 }
1348
1349 #endif /* INET6 */
1350
1351 /*
1352  * The new sockopt interface makes it possible for us to block in the
1353  * copyin/out step (if we take a page fault).  Taking a page fault while
1354  * in a critical section is probably a Bad Thing.  (Since sockets and pcbs
1355  * both now use TSM, there probably isn't any need for this function to 
1356  * run in a critical section any more.  This needs more examination.)
1357  */
1358 void
1359 tcp_ctloutput(netmsg_t msg)
1360 {
1361         struct socket *so = msg->base.nm_so;
1362         struct sockopt *sopt = msg->ctloutput.nm_sopt;
1363         int     error, opt, optval, opthz;
1364         struct  inpcb *inp;
1365         struct  tcpcb *tp;
1366
1367         error = 0;
1368         inp = so->so_pcb;
1369         if (inp == NULL) {
1370                 error = ECONNRESET;
1371                 goto done;
1372         }
1373         tp = intotcpcb(inp);
1374
1375         /* Get socket's owner cpuid hint */
1376         if (sopt->sopt_level == SOL_SOCKET &&
1377             sopt->sopt_dir == SOPT_GET &&
1378             sopt->sopt_name == SO_CPUHINT) {
1379                 if (tp->t_flags & TF_LISTEN) {
1380                         /*
1381                          * Listen sockets owner cpuid is always 0,
1382                          * which does not make sense if SO_REUSEPORT
1383                          * is not set.
1384                          */
1385                         if (so->so_options & SO_REUSEPORT)
1386                                 optval = (inp->inp_lgrpindex & ncpus2_mask);
1387                         else
1388                                 optval = -1; /* no hint */
1389                 } else {
1390                         optval = mycpuid;
1391                 }
1392                 soopt_from_kbuf(sopt, &optval, sizeof(optval));
1393                 goto done;
1394         }
1395
1396         if (sopt->sopt_level != IPPROTO_TCP) {
1397                 if (sopt->sopt_level == IPPROTO_IP) {
1398                         switch (sopt->sopt_name) {
1399                         case IP_MULTICAST_IF:
1400                         case IP_MULTICAST_VIF:
1401                         case IP_MULTICAST_TTL:
1402                         case IP_MULTICAST_LOOP:
1403                         case IP_ADD_MEMBERSHIP:
1404                         case IP_DROP_MEMBERSHIP:
1405                                 /*
1406                                  * Multicast does not make sense on
1407                                  * TCP sockets.
1408                                  */
1409                                 error = EOPNOTSUPP;
1410                                 goto done;
1411                         }
1412                 }
1413 #ifdef INET6
1414                 if (INP_CHECK_SOCKAF(so, AF_INET6))
1415                         ip6_ctloutput_dispatch(msg);
1416                 else
1417 #endif /* INET6 */
1418                 ip_ctloutput(msg);
1419                 /* msg invalid now */
1420                 return;
1421         }
1422
1423         switch (sopt->sopt_dir) {
1424         case SOPT_SET:
1425                 error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1426                                       sizeof optval);
1427                 if (error)
1428                         break;
1429                 switch (sopt->sopt_name) {
1430                 case TCP_FASTKEEP:
1431                         if (optval > 0)
1432                                 tp->t_keepidle = tp->t_keepintvl;
1433                         else
1434                                 tp->t_keepidle = tcp_keepidle;
1435                         tcp_timer_keep_activity(tp, 0);
1436                         break;
1437 #ifdef TCP_SIGNATURE
1438                 case TCP_SIGNATURE_ENABLE:
1439                         if (tp->t_state == TCPS_CLOSED) {
1440                                 /*
1441                                  * This is the only safe state that this
1442                                  * option could be changed.  Some segments
1443                                  * could already have been sent in other
1444                                  * states.
1445                                  */
1446                                 if (optval > 0)
1447                                         tp->t_flags |= TF_SIGNATURE;
1448                                 else
1449                                         tp->t_flags &= ~TF_SIGNATURE;
1450                         } else {
1451                                 error = EOPNOTSUPP;
1452                         }
1453                         break;
1454 #endif /* TCP_SIGNATURE */
1455                 case TCP_NODELAY:
1456                 case TCP_NOOPT:
1457                         switch (sopt->sopt_name) {
1458                         case TCP_NODELAY:
1459                                 opt = TF_NODELAY;
1460                                 break;
1461                         case TCP_NOOPT:
1462                                 opt = TF_NOOPT;
1463                                 break;
1464                         default:
1465                                 opt = 0; /* dead code to fool gcc */
1466                                 break;
1467                         }
1468
1469                         if (optval)
1470                                 tp->t_flags |= opt;
1471                         else
1472                                 tp->t_flags &= ~opt;
1473                         break;
1474
1475                 case TCP_NOPUSH:
1476                         if (tcp_disable_nopush)
1477                                 break;
1478                         if (optval)
1479                                 tp->t_flags |= TF_NOPUSH;
1480                         else {
1481                                 tp->t_flags &= ~TF_NOPUSH;
1482                                 error = tcp_output(tp);
1483                         }
1484                         break;
1485
1486                 case TCP_MAXSEG:
1487                         /*
1488                          * Must be between 0 and maxseg.  If the requested
1489                          * maxseg is too small to satisfy the desired minmss,
1490                          * pump it up (silently so sysctl modifications of
1491                          * minmss do not create unexpected program failures).
1492                          * Handle degenerate cases.
1493                          */
1494                         if (optval > 0 && optval <= tp->t_maxseg) {
1495                                 if (optval + 40 < tcp_minmss) {
1496                                         optval = tcp_minmss - 40;
1497                                         if (optval < 0)
1498                                                 optval = 1;
1499                                 }
1500                                 tp->t_maxseg = optval;
1501                         } else {
1502                                 error = EINVAL;
1503                         }
1504                         break;
1505
1506                 case TCP_KEEPINIT:
1507                         opthz = ((int64_t)optval * hz) / 1000;
1508                         if (opthz >= 1)
1509                                 tp->t_keepinit = opthz;
1510                         else
1511                                 error = EINVAL;
1512                         break;
1513
1514                 case TCP_KEEPIDLE:
1515                         opthz = ((int64_t)optval * hz) / 1000;
1516                         if (opthz >= 1) {
1517                                 tp->t_keepidle = opthz;
1518                                 tcp_timer_keep_activity(tp, 0);
1519                         } else {
1520                                 error = EINVAL;
1521                         }
1522                         break;
1523
1524                 case TCP_KEEPINTVL:
1525                         opthz = ((int64_t)optval * hz) / 1000;
1526                         if (opthz >= 1) {
1527                                 tp->t_keepintvl = opthz;
1528                                 tp->t_maxidle = tp->t_keepintvl * tp->t_keepcnt;
1529                         } else {
1530                                 error = EINVAL;
1531                         }
1532                         break;
1533
1534                 case TCP_KEEPCNT:
1535                         if (optval > 0) {
1536                                 tp->t_keepcnt = optval;
1537                                 tp->t_maxidle = tp->t_keepintvl * tp->t_keepcnt;
1538                         } else {
1539                                 error = EINVAL;
1540                         }
1541                         break;
1542
1543                 default:
1544                         error = ENOPROTOOPT;
1545                         break;
1546                 }
1547                 break;
1548
1549         case SOPT_GET:
1550                 switch (sopt->sopt_name) {
1551 #ifdef TCP_SIGNATURE
1552                 case TCP_SIGNATURE_ENABLE:
1553                         optval = (tp->t_flags & TF_SIGNATURE) ? 1 : 0;
1554                         break;
1555 #endif /* TCP_SIGNATURE */
1556                 case TCP_NODELAY:
1557                         optval = tp->t_flags & TF_NODELAY;
1558                         break;
1559                 case TCP_MAXSEG:
1560                         optval = tp->t_maxseg;
1561                         break;
1562                 case TCP_NOOPT:
1563                         optval = tp->t_flags & TF_NOOPT;
1564                         break;
1565                 case TCP_NOPUSH:
1566                         optval = tp->t_flags & TF_NOPUSH;
1567                         break;
1568                 case TCP_KEEPINIT:
1569                         optval = ((int64_t)tp->t_keepinit * 1000) / hz;
1570                         break;
1571                 case TCP_KEEPIDLE:
1572                         optval = ((int64_t)tp->t_keepidle * 1000) / hz;
1573                         break;
1574                 case TCP_KEEPINTVL:
1575                         optval = ((int64_t)tp->t_keepintvl * 1000) / hz;
1576                         break;
1577                 case TCP_KEEPCNT:
1578                         optval = tp->t_keepcnt;
1579                         break;
1580                 default:
1581                         error = ENOPROTOOPT;
1582                         break;
1583                 }
1584                 if (error == 0)
1585                         soopt_from_kbuf(sopt, &optval, sizeof optval);
1586                 break;
1587         }
1588 done:
1589         lwkt_replymsg(&msg->lmsg, error);
1590 }
1591
1592 /*
1593  * tcp_sendspace and tcp_recvspace are the default send and receive window
1594  * sizes, respectively.  These are obsolescent (this information should
1595  * be set by the route).
1596  *
1597  * Use a default that does not require tcp window scaling to be turned
1598  * on.  Individual programs or the administrator can increase the default.
1599  */
1600 u_long  tcp_sendspace = 57344;  /* largest multiple of PAGE_SIZE < 64k */
1601 SYSCTL_INT(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_RW,
1602     &tcp_sendspace , 0, "Maximum outgoing TCP datagram size");
1603 u_long  tcp_recvspace = 57344;  /* largest multiple of PAGE_SIZE < 64k */
1604 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
1605     &tcp_recvspace , 0, "Maximum incoming TCP datagram size");
1606
1607 /*
1608  * Attach TCP protocol to socket, allocating internet protocol control
1609  * block, tcp control block, buffer space, and entering CLOSED state.
1610  */
1611 static int
1612 tcp_attach(struct socket *so, struct pru_attach_info *ai)
1613 {
1614         struct tcpcb *tp;
1615         struct inpcb *inp;
1616         int error;
1617         int cpu;
1618 #ifdef INET6
1619         boolean_t isipv6 = INP_CHECK_SOCKAF(so, AF_INET6);
1620 #endif
1621
1622         if (ai != NULL) {
1623                 error = tcp_usr_preattach(so, 0 /* don't care */, ai);
1624                 if (error)
1625                         return (error);
1626         } else {
1627                 /* Post attach; do nothing */
1628         }
1629
1630         cpu = mycpu->gd_cpuid;
1631
1632         /*
1633          * Set the default pcbinfo.  This will likely change when we
1634          * bind/connect.
1635          */
1636         error = in_pcballoc(so, &tcbinfo[cpu]);
1637         if (error)
1638                 return (error);
1639         inp = so->so_pcb;
1640 #ifdef INET6
1641         if (isipv6)
1642                 inp->in6p_hops = -1;    /* use kernel default */
1643 #endif
1644         tp = tcp_newtcpcb(inp);
1645         if (tp == NULL) {
1646                 /*
1647                  * Make sure the socket is destroyed by the pcbdetach.
1648                  */
1649                 soreference(so);
1650 #ifdef INET6
1651                 if (isipv6)
1652                         in6_pcbdetach(inp);
1653                 else
1654 #endif
1655                 in_pcbdetach(inp);
1656                 sofree(so);     /* from ref above */
1657                 return (ENOBUFS);
1658         }
1659         tp->t_state = TCPS_CLOSED;
1660         /* Keep a reference for asynchronized pru_rcvd */
1661         soreference(so);
1662         return (0);
1663 }
1664
1665 /*
1666  * Initiate (or continue) disconnect.
1667  * If embryonic state, just send reset (once).
1668  * If in ``let data drain'' option and linger null, just drop.
1669  * Otherwise (hard), mark socket disconnecting and drop
1670  * current input data; switch states based on user close, and
1671  * send segment to peer (with FIN).
1672  */
1673 static struct tcpcb *
1674 tcp_disconnect(struct tcpcb *tp)
1675 {
1676         struct socket *so = tp->t_inpcb->inp_socket;
1677
1678         if (tp->t_state < TCPS_ESTABLISHED) {
1679                 tp = tcp_close(tp);
1680         } else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
1681                 tp = tcp_drop(tp, 0);
1682         } else {
1683                 lwkt_gettoken(&so->so_rcv.ssb_token);
1684                 soisdisconnecting(so);
1685                 sbflush(&so->so_rcv.sb);
1686                 tp = tcp_usrclosed(tp);
1687                 if (tp)
1688                         tcp_output(tp);
1689                 lwkt_reltoken(&so->so_rcv.ssb_token);
1690         }
1691         return (tp);
1692 }
1693
1694 /*
1695  * User issued close, and wish to trail through shutdown states:
1696  * if never received SYN, just forget it.  If got a SYN from peer,
1697  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
1698  * If already got a FIN from peer, then almost done; go to LAST_ACK
1699  * state.  In all other cases, have already sent FIN to peer (e.g.
1700  * after PRU_SHUTDOWN), and just have to play tedious game waiting
1701  * for peer to send FIN or not respond to keep-alives, etc.
1702  * We can let the user exit from the close as soon as the FIN is acked.
1703  */
1704 static struct tcpcb *
1705 tcp_usrclosed(struct tcpcb *tp)
1706 {
1707
1708         switch (tp->t_state) {
1709
1710         case TCPS_CLOSED:
1711         case TCPS_LISTEN:
1712                 tp->t_state = TCPS_CLOSED;
1713                 tp = tcp_close(tp);
1714                 break;
1715
1716         case TCPS_SYN_SENT:
1717         case TCPS_SYN_RECEIVED:
1718                 tp->t_flags |= TF_NEEDFIN;
1719                 break;
1720
1721         case TCPS_ESTABLISHED:
1722                 tp->t_state = TCPS_FIN_WAIT_1;
1723                 break;
1724
1725         case TCPS_CLOSE_WAIT:
1726                 tp->t_state = TCPS_LAST_ACK;
1727                 break;
1728         }
1729         if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
1730                 soisdisconnected(tp->t_inpcb->inp_socket);
1731                 /* To prevent the connection hanging in FIN_WAIT_2 forever. */
1732                 if (tp->t_state == TCPS_FIN_WAIT_2) {
1733                         tcp_callout_reset(tp, tp->tt_2msl, tp->t_maxidle,
1734                             tcp_timer_2msl);
1735                 }
1736         }
1737         return (tp);
1738 }