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