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