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