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