tcp_usrreq.c revision 167036
1/*-
2 * Copyright (c) 1982, 1986, 1988, 1993
3 *	The Regents of the University of California.
4 * Copyright (c) 2006-2007 Robert N. M. Watson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 *	From: @(#)tcp_usrreq.c	8.2 (Berkeley) 1/3/94
32 * $FreeBSD: head/sys/netinet/tcp_usrreq.c 167036 2007-02-26 22:25:21Z mohans $
33 */
34
35#include "opt_ddb.h"
36#include "opt_inet.h"
37#include "opt_inet6.h"
38#include "opt_tcpdebug.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/malloc.h>
43#include <sys/kernel.h>
44#include <sys/sysctl.h>
45#include <sys/mbuf.h>
46#ifdef INET6
47#include <sys/domain.h>
48#endif /* INET6 */
49#include <sys/socket.h>
50#include <sys/socketvar.h>
51#include <sys/protosw.h>
52#include <sys/proc.h>
53#include <sys/jail.h>
54
55#ifdef DDB
56#include <ddb/ddb.h>
57#endif
58
59#include <net/if.h>
60#include <net/route.h>
61
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#ifdef INET6
65#include <netinet/ip6.h>
66#endif
67#include <netinet/in_pcb.h>
68#ifdef INET6
69#include <netinet6/in6_pcb.h>
70#endif
71#include <netinet/in_var.h>
72#include <netinet/ip_var.h>
73#ifdef INET6
74#include <netinet6/ip6_var.h>
75#include <netinet6/scope6_var.h>
76#endif
77#include <netinet/tcp.h>
78#include <netinet/tcp_fsm.h>
79#include <netinet/tcp_seq.h>
80#include <netinet/tcp_timer.h>
81#include <netinet/tcp_var.h>
82#include <netinet/tcpip.h>
83#ifdef TCPDEBUG
84#include <netinet/tcp_debug.h>
85#endif
86
87/*
88 * TCP protocol interface to socket abstraction.
89 */
90extern	char *tcpstates[];	/* XXX ??? */
91
92static int	tcp_attach(struct socket *);
93static int	tcp_connect(struct tcpcb *, struct sockaddr *,
94		    struct thread *td);
95#ifdef INET6
96static int	tcp6_connect(struct tcpcb *, struct sockaddr *,
97		    struct thread *td);
98#endif /* INET6 */
99static void	tcp_disconnect(struct tcpcb *);
100static void	tcp_usrclosed(struct tcpcb *);
101static void	tcp_fill_info(struct tcpcb *, struct tcp_info *);
102
103#ifdef TCPDEBUG
104#define	TCPDEBUG0	int ostate = 0
105#define	TCPDEBUG1()	ostate = tp ? tp->t_state : 0
106#define	TCPDEBUG2(req)	if (tp && (so->so_options & SO_DEBUG)) \
107				tcp_trace(TA_USER, ostate, tp, 0, 0, req)
108#else
109#define	TCPDEBUG0
110#define	TCPDEBUG1()
111#define	TCPDEBUG2(req)
112#endif
113
114/*
115 * TCP attaches to socket via pru_attach(), reserving space,
116 * and an internet control block.
117 */
118static int
119tcp_usr_attach(struct socket *so, int proto, struct thread *td)
120{
121	struct inpcb *inp;
122	struct tcpcb *tp = NULL;
123	int error;
124	TCPDEBUG0;
125
126	inp = sotoinpcb(so);
127	KASSERT(inp == NULL, ("tcp_usr_attach: inp != NULL"));
128	TCPDEBUG1();
129
130	error = tcp_attach(so);
131	if (error)
132		goto out;
133
134	if ((so->so_options & SO_LINGER) && so->so_linger == 0)
135		so->so_linger = TCP_LINGERTIME;
136
137	inp = sotoinpcb(so);
138	tp = intotcpcb(inp);
139out:
140	TCPDEBUG2(PRU_ATTACH);
141	return error;
142}
143
144/*
145 * tcp_detach is called when the socket layer loses its final reference
146 * to the socket, be it a file descriptor reference, a reference from TCP,
147 * etc.  At this point, there is only one case in which we will keep around
148 * inpcb state: time wait.
149 *
150 * This function can probably be re-absorbed back into tcp_usr_detach() now
151 * that there is a single detach path.
152 */
153static void
154tcp_detach(struct socket *so, struct inpcb *inp)
155{
156	struct tcpcb *tp;
157#ifdef INET6
158	int isipv6 = INP_CHECK_SOCKAF(so, AF_INET6) != 0;
159#endif
160
161	INP_INFO_WLOCK_ASSERT(&tcbinfo);
162	INP_LOCK_ASSERT(inp);
163
164	KASSERT(so->so_pcb == inp, ("tcp_detach: so_pcb != inp"));
165	KASSERT(inp->inp_socket == so, ("tcp_detach: inp_socket != so"));
166
167	tp = intotcpcb(inp);
168
169	if (inp->inp_vflag & INP_TIMEWAIT) {
170		/*
171		 * There are two cases to handle: one in which the time wait
172		 * state is being discarded (INP_DROPPED), and one in which
173		 * this connection will remain in timewait.  In the former,
174		 * it is time to discard all state (except tcptw, which has
175		 * already been discarded by the timewait close code, which
176		 * should be further up the call stack somewhere).  In the
177		 * latter case, we detach from the socket, but leave the pcb
178		 * present until timewait ends.
179		 *
180		 * XXXRW: Would it be cleaner to free the tcptw here?
181		 */
182		if (inp->inp_vflag & INP_DROPPED) {
183			KASSERT(tp == NULL, ("tcp_detach: INP_TIMEWAIT && "
184			    "INP_DROPPED && tp != NULL"));
185#ifdef INET6
186			if (isipv6) {
187				in6_pcbdetach(inp);
188				in6_pcbfree(inp);
189			} else {
190#endif
191				in_pcbdetach(inp);
192				in_pcbfree(inp);
193#ifdef INET6
194			}
195#endif
196		} else {
197#ifdef INET6
198			if (isipv6)
199				in6_pcbdetach(inp);
200			else
201#endif
202				in_pcbdetach(inp);
203			INP_UNLOCK(inp);
204		}
205	} else {
206		/*
207		 * If the connection is not in timewait, we consider two
208		 * two conditions: one in which no further processing is
209		 * necessary (dropped || embryonic), and one in which TCP is
210		 * not yet done, but no longer requires the socket, so the
211		 * pcb will persist for the time being.
212		 *
213		 * XXXRW: Does the second case still occur?
214		 */
215		if (inp->inp_vflag & INP_DROPPED ||
216		    tp->t_state < TCPS_SYN_SENT) {
217			tcp_discardcb(tp);
218#ifdef INET6
219			if (isipv6) {
220				in6_pcbdetach(inp);
221				in6_pcbfree(inp);
222			} else {
223#endif
224				in_pcbdetach(inp);
225				in_pcbfree(inp);
226#ifdef INET6
227			}
228#endif
229		} else {
230#ifdef INET6
231			if (isipv6)
232				in6_pcbdetach(inp);
233			else
234#endif
235				in_pcbdetach(inp);
236		}
237	}
238}
239
240/*
241 * pru_detach() detaches the TCP protocol from the socket.
242 * If the protocol state is non-embryonic, then can't
243 * do this directly: have to initiate a pru_disconnect(),
244 * which may finish later; embryonic TCB's can just
245 * be discarded here.
246 */
247static void
248tcp_usr_detach(struct socket *so)
249{
250	struct inpcb *inp;
251	struct tcpcb *tp;
252	TCPDEBUG0;
253
254	inp = sotoinpcb(so);
255	KASSERT(inp != NULL, ("tcp_usr_detach: inp == NULL"));
256	INP_INFO_WLOCK(&tcbinfo);
257	INP_LOCK(inp);
258	KASSERT(inp->inp_socket != NULL,
259	    ("tcp_usr_detach: inp_socket == NULL"));
260	TCPDEBUG1();
261
262	tcp_detach(so, inp);
263	tp = NULL;
264	TCPDEBUG2(PRU_DETACH);
265	INP_INFO_WUNLOCK(&tcbinfo);
266}
267
268/*
269 * Give the socket an address.
270 */
271static int
272tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
273{
274	int error = 0;
275	struct inpcb *inp;
276	struct tcpcb *tp = NULL;
277	struct sockaddr_in *sinp;
278
279	sinp = (struct sockaddr_in *)nam;
280	if (nam->sa_len != sizeof (*sinp))
281		return (EINVAL);
282	/*
283	 * Must check for multicast addresses and disallow binding
284	 * to them.
285	 */
286	if (sinp->sin_family == AF_INET &&
287	    IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
288		return (EAFNOSUPPORT);
289
290	TCPDEBUG0;
291	INP_INFO_WLOCK(&tcbinfo);
292	inp = sotoinpcb(so);
293	KASSERT(inp != NULL, ("tcp_usr_bind: inp == NULL"));
294	INP_LOCK(inp);
295	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
296		error = EINVAL;
297		goto out;
298	}
299	tp = intotcpcb(inp);
300	TCPDEBUG1();
301	error = in_pcbbind(inp, nam, td->td_ucred);
302out:
303	TCPDEBUG2(PRU_BIND);
304	INP_UNLOCK(inp);
305	INP_INFO_WUNLOCK(&tcbinfo);
306
307	return (error);
308}
309
310#ifdef INET6
311static int
312tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
313{
314	int error = 0;
315	struct inpcb *inp;
316	struct tcpcb *tp = NULL;
317	struct sockaddr_in6 *sin6p;
318
319	sin6p = (struct sockaddr_in6 *)nam;
320	if (nam->sa_len != sizeof (*sin6p))
321		return (EINVAL);
322	/*
323	 * Must check for multicast addresses and disallow binding
324	 * to them.
325	 */
326	if (sin6p->sin6_family == AF_INET6 &&
327	    IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr))
328		return (EAFNOSUPPORT);
329
330	TCPDEBUG0;
331	INP_INFO_WLOCK(&tcbinfo);
332	inp = sotoinpcb(so);
333	KASSERT(inp != NULL, ("tcp6_usr_bind: inp == NULL"));
334	INP_LOCK(inp);
335	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
336		error = EINVAL;
337		goto out;
338	}
339	tp = intotcpcb(inp);
340	TCPDEBUG1();
341	inp->inp_vflag &= ~INP_IPV4;
342	inp->inp_vflag |= INP_IPV6;
343	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
344		if (IN6_IS_ADDR_UNSPECIFIED(&sin6p->sin6_addr))
345			inp->inp_vflag |= INP_IPV4;
346		else if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
347			struct sockaddr_in sin;
348
349			in6_sin6_2_sin(&sin, sin6p);
350			inp->inp_vflag |= INP_IPV4;
351			inp->inp_vflag &= ~INP_IPV6;
352			error = in_pcbbind(inp, (struct sockaddr *)&sin,
353			    td->td_ucred);
354			goto out;
355		}
356	}
357	error = in6_pcbbind(inp, nam, td->td_ucred);
358out:
359	TCPDEBUG2(PRU_BIND);
360	INP_UNLOCK(inp);
361	INP_INFO_WUNLOCK(&tcbinfo);
362	return (error);
363}
364#endif /* INET6 */
365
366/*
367 * Prepare to accept connections.
368 */
369static int
370tcp_usr_listen(struct socket *so, int backlog, struct thread *td)
371{
372	int error = 0;
373	struct inpcb *inp;
374	struct tcpcb *tp = NULL;
375
376	TCPDEBUG0;
377	INP_INFO_WLOCK(&tcbinfo);
378	inp = sotoinpcb(so);
379	KASSERT(inp != NULL, ("tcp_usr_listen: inp == NULL"));
380	INP_LOCK(inp);
381	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
382		error = EINVAL;
383		goto out;
384	}
385	tp = intotcpcb(inp);
386	TCPDEBUG1();
387	SOCK_LOCK(so);
388	error = solisten_proto_check(so);
389	if (error == 0 && inp->inp_lport == 0)
390		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
391	if (error == 0) {
392		tp->t_state = TCPS_LISTEN;
393		solisten_proto(so, backlog);
394	}
395	SOCK_UNLOCK(so);
396
397out:
398	TCPDEBUG2(PRU_LISTEN);
399	INP_UNLOCK(inp);
400	INP_INFO_WUNLOCK(&tcbinfo);
401	return (error);
402}
403
404#ifdef INET6
405static int
406tcp6_usr_listen(struct socket *so, int backlog, struct thread *td)
407{
408	int error = 0;
409	struct inpcb *inp;
410	struct tcpcb *tp = NULL;
411
412	TCPDEBUG0;
413	INP_INFO_WLOCK(&tcbinfo);
414	inp = sotoinpcb(so);
415	KASSERT(inp != NULL, ("tcp6_usr_listen: inp == NULL"));
416	INP_LOCK(inp);
417	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
418		error = EINVAL;
419		goto out;
420	}
421	tp = intotcpcb(inp);
422	TCPDEBUG1();
423	SOCK_LOCK(so);
424	error = solisten_proto_check(so);
425	if (error == 0 && inp->inp_lport == 0) {
426		inp->inp_vflag &= ~INP_IPV4;
427		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
428			inp->inp_vflag |= INP_IPV4;
429		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
430	}
431	if (error == 0) {
432		tp->t_state = TCPS_LISTEN;
433		solisten_proto(so, backlog);
434	}
435	SOCK_UNLOCK(so);
436
437out:
438	TCPDEBUG2(PRU_LISTEN);
439	INP_UNLOCK(inp);
440	INP_INFO_WUNLOCK(&tcbinfo);
441	return (error);
442}
443#endif /* INET6 */
444
445/*
446 * Initiate connection to peer.
447 * Create a template for use in transmissions on this connection.
448 * Enter SYN_SENT state, and mark socket as connecting.
449 * Start keep-alive timer, and seed output sequence space.
450 * Send initial segment on connection.
451 */
452static int
453tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
454{
455	int error = 0;
456	struct inpcb *inp;
457	struct tcpcb *tp = NULL;
458	struct sockaddr_in *sinp;
459
460	sinp = (struct sockaddr_in *)nam;
461	if (nam->sa_len != sizeof (*sinp))
462		return (EINVAL);
463	/*
464	 * Must disallow TCP ``connections'' to multicast addresses.
465	 */
466	if (sinp->sin_family == AF_INET
467	    && IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
468		return (EAFNOSUPPORT);
469	if (jailed(td->td_ucred))
470		prison_remote_ip(td->td_ucred, 0, &sinp->sin_addr.s_addr);
471
472	TCPDEBUG0;
473	INP_INFO_WLOCK(&tcbinfo);
474	inp = sotoinpcb(so);
475	KASSERT(inp != NULL, ("tcp_usr_connect: inp == NULL"));
476	INP_LOCK(inp);
477	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
478		error = EINVAL;
479		goto out;
480	}
481	tp = intotcpcb(inp);
482	TCPDEBUG1();
483	if ((error = tcp_connect(tp, nam, td)) != 0)
484		goto out;
485	error = tcp_output(tp);
486out:
487	TCPDEBUG2(PRU_CONNECT);
488	INP_UNLOCK(inp);
489	INP_INFO_WUNLOCK(&tcbinfo);
490	return (error);
491}
492
493#ifdef INET6
494static int
495tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
496{
497	int error = 0;
498	struct inpcb *inp;
499	struct tcpcb *tp = NULL;
500	struct sockaddr_in6 *sin6p;
501
502	TCPDEBUG0;
503
504	sin6p = (struct sockaddr_in6 *)nam;
505	if (nam->sa_len != sizeof (*sin6p))
506		return (EINVAL);
507	/*
508	 * Must disallow TCP ``connections'' to multicast addresses.
509	 */
510	if (sin6p->sin6_family == AF_INET6
511	    && IN6_IS_ADDR_MULTICAST(&sin6p->sin6_addr))
512		return (EAFNOSUPPORT);
513
514	INP_INFO_WLOCK(&tcbinfo);
515	inp = sotoinpcb(so);
516	KASSERT(inp != NULL, ("tcp6_usr_connect: inp == NULL"));
517	INP_LOCK(inp);
518	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
519		error = EINVAL;
520		goto out;
521	}
522	tp = intotcpcb(inp);
523	TCPDEBUG1();
524	if (IN6_IS_ADDR_V4MAPPED(&sin6p->sin6_addr)) {
525		struct sockaddr_in sin;
526
527		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
528			error = EINVAL;
529			goto out;
530		}
531
532		in6_sin6_2_sin(&sin, sin6p);
533		inp->inp_vflag |= INP_IPV4;
534		inp->inp_vflag &= ~INP_IPV6;
535		if ((error = tcp_connect(tp, (struct sockaddr *)&sin, td)) != 0)
536			goto out;
537		error = tcp_output(tp);
538		goto out;
539	}
540	inp->inp_vflag &= ~INP_IPV4;
541	inp->inp_vflag |= INP_IPV6;
542	inp->inp_inc.inc_isipv6 = 1;
543	if ((error = tcp6_connect(tp, nam, td)) != 0)
544		goto out;
545	error = tcp_output(tp);
546
547out:
548	TCPDEBUG2(PRU_CONNECT);
549	INP_UNLOCK(inp);
550	INP_INFO_WUNLOCK(&tcbinfo);
551	return (error);
552}
553#endif /* INET6 */
554
555/*
556 * Initiate disconnect from peer.
557 * If connection never passed embryonic stage, just drop;
558 * else if don't need to let data drain, then can just drop anyways,
559 * else have to begin TCP shutdown process: mark socket disconnecting,
560 * drain unread data, state switch to reflect user close, and
561 * send segment (e.g. FIN) to peer.  Socket will be really disconnected
562 * when peer sends FIN and acks ours.
563 *
564 * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
565 */
566static int
567tcp_usr_disconnect(struct socket *so)
568{
569	struct inpcb *inp;
570	struct tcpcb *tp = NULL;
571	int error = 0;
572
573	TCPDEBUG0;
574	INP_INFO_WLOCK(&tcbinfo);
575	inp = sotoinpcb(so);
576	KASSERT(inp != NULL, ("tcp_usr_disconnect: inp == NULL"));
577	INP_LOCK(inp);
578	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
579		error = ECONNRESET;
580		goto out;
581	}
582	tp = intotcpcb(inp);
583	TCPDEBUG1();
584	tcp_disconnect(tp);
585out:
586	TCPDEBUG2(PRU_DISCONNECT);
587	INP_UNLOCK(inp);
588	INP_INFO_WUNLOCK(&tcbinfo);
589	return (error);
590}
591
592/*
593 * Accept a connection.  Essentially all the work is
594 * done at higher levels; just return the address
595 * of the peer, storing through addr.
596 */
597static int
598tcp_usr_accept(struct socket *so, struct sockaddr **nam)
599{
600	int error = 0;
601	struct inpcb *inp = NULL;
602	struct tcpcb *tp = NULL;
603	struct in_addr addr;
604	in_port_t port = 0;
605	TCPDEBUG0;
606
607	if (so->so_state & SS_ISDISCONNECTED)
608		return (ECONNABORTED);
609
610	inp = sotoinpcb(so);
611	KASSERT(inp != NULL, ("tcp_usr_accept: inp == NULL"));
612	INP_LOCK(inp);
613	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
614		error = ECONNABORTED;
615		goto out;
616	}
617	tp = intotcpcb(inp);
618	TCPDEBUG1();
619
620	/*
621	 * We inline in_setpeeraddr and COMMON_END here, so that we can
622	 * copy the data of interest and defer the malloc until after we
623	 * release the lock.
624	 */
625	port = inp->inp_fport;
626	addr = inp->inp_faddr;
627
628out:
629	TCPDEBUG2(PRU_ACCEPT);
630	INP_UNLOCK(inp);
631	if (error == 0)
632		*nam = in_sockaddr(port, &addr);
633	return error;
634}
635
636#ifdef INET6
637static int
638tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
639{
640	struct inpcb *inp = NULL;
641	int error = 0;
642	struct tcpcb *tp = NULL;
643	struct in_addr addr;
644	struct in6_addr addr6;
645	in_port_t port = 0;
646	int v4 = 0;
647	TCPDEBUG0;
648
649	if (so->so_state & SS_ISDISCONNECTED)
650		return (ECONNABORTED);
651
652	inp = sotoinpcb(so);
653	KASSERT(inp != NULL, ("tcp6_usr_accept: inp == NULL"));
654	INP_LOCK(inp);
655	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
656		error = ECONNABORTED;
657		goto out;
658	}
659	tp = intotcpcb(inp);
660	TCPDEBUG1();
661
662	/*
663	 * We inline in6_mapped_peeraddr and COMMON_END here, so that we can
664	 * copy the data of interest and defer the malloc until after we
665	 * release the lock.
666	 */
667	if (inp->inp_vflag & INP_IPV4) {
668		v4 = 1;
669		port = inp->inp_fport;
670		addr = inp->inp_faddr;
671	} else {
672		port = inp->inp_fport;
673		addr6 = inp->in6p_faddr;
674	}
675
676out:
677	TCPDEBUG2(PRU_ACCEPT);
678	INP_UNLOCK(inp);
679	if (error == 0) {
680		if (v4)
681			*nam = in6_v4mapsin6_sockaddr(port, &addr);
682		else
683			*nam = in6_sockaddr(port, &addr6);
684	}
685	return error;
686}
687#endif /* INET6 */
688
689/*
690 * This is the wrapper function for in_setsockaddr. We just pass down
691 * the pcbinfo for in_setsockaddr to lock. We don't want to do the locking
692 * here because in_setsockaddr will call malloc and can block.
693 */
694static int
695tcp_sockaddr(struct socket *so, struct sockaddr **nam)
696{
697	return (in_setsockaddr(so, nam, &tcbinfo));
698}
699
700/*
701 * This is the wrapper function for in_setpeeraddr. We just pass down
702 * the pcbinfo for in_setpeeraddr to lock.
703 */
704static int
705tcp_peeraddr(struct socket *so, struct sockaddr **nam)
706{
707	return (in_setpeeraddr(so, nam, &tcbinfo));
708}
709
710/*
711 * Mark the connection as being incapable of further output.
712 */
713static int
714tcp_usr_shutdown(struct socket *so)
715{
716	int error = 0;
717	struct inpcb *inp;
718	struct tcpcb *tp = NULL;
719
720	TCPDEBUG0;
721	INP_INFO_WLOCK(&tcbinfo);
722	inp = sotoinpcb(so);
723	KASSERT(inp != NULL, ("inp == NULL"));
724	INP_LOCK(inp);
725	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
726		error = ECONNRESET;
727		goto out;
728	}
729	tp = intotcpcb(inp);
730	TCPDEBUG1();
731	socantsendmore(so);
732	tcp_usrclosed(tp);
733	error = tcp_output(tp);
734
735out:
736	TCPDEBUG2(PRU_SHUTDOWN);
737	INP_UNLOCK(inp);
738	INP_INFO_WUNLOCK(&tcbinfo);
739
740	return (error);
741}
742
743/*
744 * After a receive, possibly send window update to peer.
745 */
746static int
747tcp_usr_rcvd(struct socket *so, int flags)
748{
749	struct inpcb *inp;
750	struct tcpcb *tp = NULL;
751	int error = 0;
752
753	TCPDEBUG0;
754	inp = sotoinpcb(so);
755	KASSERT(inp != NULL, ("tcp_usr_rcvd: inp == NULL"));
756	INP_LOCK(inp);
757	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
758		error = ECONNRESET;
759		goto out;
760	}
761	tp = intotcpcb(inp);
762	TCPDEBUG1();
763	tcp_output(tp);
764
765out:
766	TCPDEBUG2(PRU_RCVD);
767	INP_UNLOCK(inp);
768	return (error);
769}
770
771/*
772 * Do a send by putting data in output queue and updating urgent
773 * marker if URG set.  Possibly send more data.  Unlike the other
774 * pru_*() routines, the mbuf chains are our responsibility.  We
775 * must either enqueue them or free them.  The other pru_* routines
776 * generally are caller-frees.
777 */
778static int
779tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
780	     struct sockaddr *nam, struct mbuf *control, struct thread *td)
781{
782	int error = 0;
783	struct inpcb *inp;
784	struct tcpcb *tp = NULL;
785	int headlocked = 0;
786#ifdef INET6
787	int isipv6;
788#endif
789	TCPDEBUG0;
790
791	/*
792	 * We require the pcbinfo lock in two cases:
793	 *
794	 * (1) An implied connect is taking place, which can result in
795	 *     binding IPs and ports and hence modification of the pcb hash
796	 *     chains.
797	 *
798	 * (2) PRUS_EOF is set, resulting in explicit close on the send.
799	 */
800	if ((nam != NULL) || (flags & PRUS_EOF)) {
801		INP_INFO_WLOCK(&tcbinfo);
802		headlocked = 1;
803	}
804	inp = sotoinpcb(so);
805	KASSERT(inp != NULL, ("tcp_usr_send: inp == NULL"));
806	INP_LOCK(inp);
807	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
808		if (control)
809			m_freem(control);
810		if (m)
811			m_freem(m);
812		error = ECONNRESET;
813		goto out;
814	}
815#ifdef INET6
816	isipv6 = nam && nam->sa_family == AF_INET6;
817#endif /* INET6 */
818	tp = intotcpcb(inp);
819	TCPDEBUG1();
820	if (control) {
821		/* TCP doesn't do control messages (rights, creds, etc) */
822		if (control->m_len) {
823			m_freem(control);
824			if (m)
825				m_freem(m);
826			error = EINVAL;
827			goto out;
828		}
829		m_freem(control);	/* empty control, just free it */
830	}
831	if (!(flags & PRUS_OOB)) {
832		sbappendstream(&so->so_snd, m);
833		if (nam && tp->t_state < TCPS_SYN_SENT) {
834			/*
835			 * Do implied connect if not yet connected,
836			 * initialize window to default value, and
837			 * initialize maxseg/maxopd using peer's cached
838			 * MSS.
839			 */
840			INP_INFO_WLOCK_ASSERT(&tcbinfo);
841#ifdef INET6
842			if (isipv6)
843				error = tcp6_connect(tp, nam, td);
844			else
845#endif /* INET6 */
846			error = tcp_connect(tp, nam, td);
847			if (error)
848				goto out;
849			tp->snd_wnd = TTCP_CLIENT_SND_WND;
850			tcp_mss(tp, -1);
851		}
852		if (flags & PRUS_EOF) {
853			/*
854			 * Close the send side of the connection after
855			 * the data is sent.
856			 */
857			INP_INFO_WLOCK_ASSERT(&tcbinfo);
858			socantsendmore(so);
859			tcp_usrclosed(tp);
860		}
861		if (headlocked) {
862			INP_INFO_WUNLOCK(&tcbinfo);
863			headlocked = 0;
864		}
865		if (tp != NULL) {
866			if (flags & PRUS_MORETOCOME)
867				tp->t_flags |= TF_MORETOCOME;
868			error = tcp_output(tp);
869			if (flags & PRUS_MORETOCOME)
870				tp->t_flags &= ~TF_MORETOCOME;
871		}
872	} else {
873		/*
874		 * XXXRW: PRUS_EOF not implemented with PRUS_OOB?
875		 */
876		SOCKBUF_LOCK(&so->so_snd);
877		if (sbspace(&so->so_snd) < -512) {
878			SOCKBUF_UNLOCK(&so->so_snd);
879			m_freem(m);
880			error = ENOBUFS;
881			goto out;
882		}
883		/*
884		 * According to RFC961 (Assigned Protocols),
885		 * the urgent pointer points to the last octet
886		 * of urgent data.  We continue, however,
887		 * to consider it to indicate the first octet
888		 * of data past the urgent section.
889		 * Otherwise, snd_up should be one lower.
890		 */
891		sbappendstream_locked(&so->so_snd, m);
892		SOCKBUF_UNLOCK(&so->so_snd);
893		if (nam && tp->t_state < TCPS_SYN_SENT) {
894			/*
895			 * Do implied connect if not yet connected,
896			 * initialize window to default value, and
897			 * initialize maxseg/maxopd using peer's cached
898			 * MSS.
899			 */
900			INP_INFO_WLOCK_ASSERT(&tcbinfo);
901#ifdef INET6
902			if (isipv6)
903				error = tcp6_connect(tp, nam, td);
904			else
905#endif /* INET6 */
906			error = tcp_connect(tp, nam, td);
907			if (error)
908				goto out;
909			tp->snd_wnd = TTCP_CLIENT_SND_WND;
910			tcp_mss(tp, -1);
911			INP_INFO_WUNLOCK(&tcbinfo);
912			headlocked = 0;
913		} else if (nam) {
914			INP_INFO_WUNLOCK(&tcbinfo);
915			headlocked = 0;
916		}
917		tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
918		tp->t_flags |= TF_FORCEDATA;
919		error = tcp_output(tp);
920		tp->t_flags &= ~TF_FORCEDATA;
921	}
922out:
923	TCPDEBUG2((flags & PRUS_OOB) ? PRU_SENDOOB :
924		  ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
925	INP_UNLOCK(inp);
926	if (headlocked)
927		INP_INFO_WUNLOCK(&tcbinfo);
928	return (error);
929}
930
931/*
932 * Abort the TCP.  Drop the connection abruptly.
933 */
934static void
935tcp_usr_abort(struct socket *so)
936{
937	struct inpcb *inp;
938	struct tcpcb *tp = NULL;
939	TCPDEBUG0;
940
941	inp = sotoinpcb(so);
942	KASSERT(inp != NULL, ("tcp_usr_abort: inp == NULL"));
943
944	INP_INFO_WLOCK(&tcbinfo);
945	INP_LOCK(inp);
946	KASSERT(inp->inp_socket != NULL,
947	    ("tcp_usr_abort: inp_socket == NULL"));
948
949	/*
950	 * If we still have full TCP state, and we're not dropped, drop.
951	 */
952	if (!(inp->inp_vflag & INP_TIMEWAIT) &&
953	    !(inp->inp_vflag & INP_DROPPED)) {
954		tp = intotcpcb(inp);
955		TCPDEBUG1();
956		tcp_drop(tp, ECONNABORTED);
957		TCPDEBUG2(PRU_ABORT);
958	}
959	if (!(inp->inp_vflag & INP_DROPPED)) {
960		SOCK_LOCK(so);
961		so->so_state |= SS_PROTOREF;
962		SOCK_UNLOCK(so);
963		inp->inp_vflag |= INP_SOCKREF;
964	}
965	INP_UNLOCK(inp);
966	INP_INFO_WUNLOCK(&tcbinfo);
967}
968
969/*
970 * TCP socket is closed.  Start friendly disconnect.
971 */
972static void
973tcp_usr_close(struct socket *so)
974{
975	struct inpcb *inp;
976	struct tcpcb *tp = NULL;
977	TCPDEBUG0;
978
979	inp = sotoinpcb(so);
980	KASSERT(inp != NULL, ("tcp_usr_close: inp == NULL"));
981
982	INP_INFO_WLOCK(&tcbinfo);
983	INP_LOCK(inp);
984	KASSERT(inp->inp_socket != NULL,
985	    ("tcp_usr_close: inp_socket == NULL"));
986
987	/*
988	 * If we still have full TCP state, and we're not dropped, initiate
989	 * a disconnect.
990	 */
991	if (!(inp->inp_vflag & INP_TIMEWAIT) &&
992	    !(inp->inp_vflag & INP_DROPPED)) {
993		tp = intotcpcb(inp);
994		TCPDEBUG1();
995		tcp_disconnect(tp);
996		TCPDEBUG2(PRU_CLOSE);
997	}
998	if (!(inp->inp_vflag & INP_DROPPED)) {
999		SOCK_LOCK(so);
1000		so->so_state |= SS_PROTOREF;
1001		SOCK_UNLOCK(so);
1002		inp->inp_vflag |= INP_SOCKREF;
1003	}
1004	INP_UNLOCK(inp);
1005	INP_INFO_WUNLOCK(&tcbinfo);
1006}
1007
1008/*
1009 * Receive out-of-band data.
1010 */
1011static int
1012tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
1013{
1014	int error = 0;
1015	struct inpcb *inp;
1016	struct tcpcb *tp = NULL;
1017
1018	TCPDEBUG0;
1019	inp = sotoinpcb(so);
1020	KASSERT(inp != NULL, ("tcp_usr_rcvoob: inp == NULL"));
1021	INP_LOCK(inp);
1022	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
1023		error = ECONNRESET;
1024		goto out;
1025	}
1026	tp = intotcpcb(inp);
1027	TCPDEBUG1();
1028	if ((so->so_oobmark == 0 &&
1029	     (so->so_rcv.sb_state & SBS_RCVATMARK) == 0) ||
1030	    so->so_options & SO_OOBINLINE ||
1031	    tp->t_oobflags & TCPOOB_HADDATA) {
1032		error = EINVAL;
1033		goto out;
1034	}
1035	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
1036		error = EWOULDBLOCK;
1037		goto out;
1038	}
1039	m->m_len = 1;
1040	*mtod(m, caddr_t) = tp->t_iobc;
1041	if ((flags & MSG_PEEK) == 0)
1042		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1043
1044out:
1045	TCPDEBUG2(PRU_RCVOOB);
1046	INP_UNLOCK(inp);
1047	return (error);
1048}
1049
1050struct pr_usrreqs tcp_usrreqs = {
1051	.pru_abort =		tcp_usr_abort,
1052	.pru_accept =		tcp_usr_accept,
1053	.pru_attach =		tcp_usr_attach,
1054	.pru_bind =		tcp_usr_bind,
1055	.pru_connect =		tcp_usr_connect,
1056	.pru_control =		in_control,
1057	.pru_detach =		tcp_usr_detach,
1058	.pru_disconnect =	tcp_usr_disconnect,
1059	.pru_listen =		tcp_usr_listen,
1060	.pru_peeraddr =		tcp_peeraddr,
1061	.pru_rcvd =		tcp_usr_rcvd,
1062	.pru_rcvoob =		tcp_usr_rcvoob,
1063	.pru_send =		tcp_usr_send,
1064	.pru_shutdown =		tcp_usr_shutdown,
1065	.pru_sockaddr =		tcp_sockaddr,
1066	.pru_sosetlabel =	in_pcbsosetlabel,
1067	.pru_close =		tcp_usr_close,
1068};
1069
1070#ifdef INET6
1071struct pr_usrreqs tcp6_usrreqs = {
1072	.pru_abort =		tcp_usr_abort,
1073	.pru_accept =		tcp6_usr_accept,
1074	.pru_attach =		tcp_usr_attach,
1075	.pru_bind =		tcp6_usr_bind,
1076	.pru_connect =		tcp6_usr_connect,
1077	.pru_control =		in6_control,
1078	.pru_detach =		tcp_usr_detach,
1079	.pru_disconnect =	tcp_usr_disconnect,
1080	.pru_listen =		tcp6_usr_listen,
1081	.pru_peeraddr =		in6_mapped_peeraddr,
1082	.pru_rcvd =		tcp_usr_rcvd,
1083	.pru_rcvoob =		tcp_usr_rcvoob,
1084	.pru_send =		tcp_usr_send,
1085	.pru_shutdown =		tcp_usr_shutdown,
1086	.pru_sockaddr =		in6_mapped_sockaddr,
1087 	.pru_sosetlabel =	in_pcbsosetlabel,
1088	.pru_close =		tcp_usr_close,
1089};
1090#endif /* INET6 */
1091
1092/*
1093 * Common subroutine to open a TCP connection to remote host specified
1094 * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1095 * port number if needed.  Call in_pcbconnect_setup to do the routing and
1096 * to choose a local host address (interface).  If there is an existing
1097 * incarnation of the same connection in TIME-WAIT state and if the remote
1098 * host was sending CC options and if the connection duration was < MSL, then
1099 * truncate the previous TIME-WAIT state and proceed.
1100 * Initialize connection parameters and enter SYN-SENT state.
1101 */
1102static int
1103tcp_connect(tp, nam, td)
1104	register struct tcpcb *tp;
1105	struct sockaddr *nam;
1106	struct thread *td;
1107{
1108	struct inpcb *inp = tp->t_inpcb, *oinp;
1109	struct socket *so = inp->inp_socket;
1110	struct in_addr laddr;
1111	u_short lport;
1112	int error;
1113
1114	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1115	INP_LOCK_ASSERT(inp);
1116
1117	if (inp->inp_lport == 0) {
1118		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1119		if (error)
1120			return error;
1121	}
1122
1123	/*
1124	 * Cannot simply call in_pcbconnect, because there might be an
1125	 * earlier incarnation of this same connection still in
1126	 * TIME_WAIT state, creating an ADDRINUSE error.
1127	 */
1128	laddr = inp->inp_laddr;
1129	lport = inp->inp_lport;
1130	error = in_pcbconnect_setup(inp, nam, &laddr.s_addr, &lport,
1131	    &inp->inp_faddr.s_addr, &inp->inp_fport, &oinp, td->td_ucred);
1132	if (error && oinp == NULL)
1133		return error;
1134	if (oinp)
1135		return EADDRINUSE;
1136	inp->inp_laddr = laddr;
1137	in_pcbrehash(inp);
1138
1139	/*
1140	 * Compute window scaling to request:
1141	 * Scale to fit into sweet spot.  See tcp_syncache.c.
1142	 * XXX: This should move to tcp_output().
1143	 * XXX: This should be based on the actual MSS.
1144	 */
1145	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1146	    (0x1 << tp->request_r_scale) < tcp_minmss)
1147		tp->request_r_scale++;
1148
1149	soisconnecting(so);
1150	tcpstat.tcps_connattempt++;
1151	tp->t_state = TCPS_SYN_SENT;
1152	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
1153	tp->iss = tcp_new_isn(tp);
1154	tp->t_bw_rtseq = tp->iss;
1155	tcp_sendseqinit(tp);
1156
1157	return 0;
1158}
1159
1160#ifdef INET6
1161static int
1162tcp6_connect(tp, nam, td)
1163	register struct tcpcb *tp;
1164	struct sockaddr *nam;
1165	struct thread *td;
1166{
1167	struct inpcb *inp = tp->t_inpcb, *oinp;
1168	struct socket *so = inp->inp_socket;
1169	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
1170	struct in6_addr *addr6;
1171	int error;
1172
1173	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1174	INP_LOCK_ASSERT(inp);
1175
1176	if (inp->inp_lport == 0) {
1177		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1178		if (error)
1179			return error;
1180	}
1181
1182	/*
1183	 * Cannot simply call in_pcbconnect, because there might be an
1184	 * earlier incarnation of this same connection still in
1185	 * TIME_WAIT state, creating an ADDRINUSE error.
1186	 * in6_pcbladdr() also handles scope zone IDs.
1187	 */
1188	error = in6_pcbladdr(inp, nam, &addr6);
1189	if (error)
1190		return error;
1191	oinp = in6_pcblookup_hash(inp->inp_pcbinfo,
1192				  &sin6->sin6_addr, sin6->sin6_port,
1193				  IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)
1194				  ? addr6
1195				  : &inp->in6p_laddr,
1196				  inp->inp_lport,  0, NULL);
1197	if (oinp)
1198		return EADDRINUSE;
1199	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1200		inp->in6p_laddr = *addr6;
1201	inp->in6p_faddr = sin6->sin6_addr;
1202	inp->inp_fport = sin6->sin6_port;
1203	/* update flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
1204	inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
1205	if (inp->in6p_flags & IN6P_AUTOFLOWLABEL)
1206		inp->in6p_flowinfo |=
1207		    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1208	in_pcbrehash(inp);
1209
1210	/* Compute window scaling to request.  */
1211	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1212	    (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.sb_hiwat)
1213		tp->request_r_scale++;
1214
1215	soisconnecting(so);
1216	tcpstat.tcps_connattempt++;
1217	tp->t_state = TCPS_SYN_SENT;
1218	callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
1219	tp->iss = tcp_new_isn(tp);
1220	tp->t_bw_rtseq = tp->iss;
1221	tcp_sendseqinit(tp);
1222
1223	return 0;
1224}
1225#endif /* INET6 */
1226
1227/*
1228 * Export TCP internal state information via a struct tcp_info, based on the
1229 * Linux 2.6 API.  Not ABI compatible as our constants are mapped differently
1230 * (TCP state machine, etc).  We export all information using FreeBSD-native
1231 * constants -- for example, the numeric values for tcpi_state will differ
1232 * from Linux.
1233 */
1234static void
1235tcp_fill_info(tp, ti)
1236	struct tcpcb *tp;
1237	struct tcp_info *ti;
1238{
1239
1240	INP_LOCK_ASSERT(tp->t_inpcb);
1241	bzero(ti, sizeof(*ti));
1242
1243	ti->tcpi_state = tp->t_state;
1244	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
1245		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1246	if (tp->sack_enable)
1247		ti->tcpi_options |= TCPI_OPT_SACK;
1248	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
1249		ti->tcpi_options |= TCPI_OPT_WSCALE;
1250		ti->tcpi_snd_wscale = tp->snd_scale;
1251		ti->tcpi_rcv_wscale = tp->rcv_scale;
1252	}
1253
1254	ti->tcpi_rtt = ((u_int64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
1255	ti->tcpi_rttvar = ((u_int64_t)tp->t_rttvar * tick) >> TCP_RTTVAR_SHIFT;
1256
1257	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1258	ti->tcpi_snd_cwnd = tp->snd_cwnd;
1259
1260	/*
1261	 * FreeBSD-specific extension fields for tcp_info.
1262	 */
1263	ti->tcpi_rcv_space = tp->rcv_wnd;
1264	ti->tcpi_snd_wnd = tp->snd_wnd;
1265	ti->tcpi_snd_bwnd = tp->snd_bwnd;
1266}
1267
1268/*
1269 * The new sockopt interface makes it possible for us to block in the
1270 * copyin/out step (if we take a page fault).  Taking a page fault at
1271 * splnet() is probably a Bad Thing.  (Since sockets and pcbs both now
1272 * use TSM, there probably isn't any need for this function to run at
1273 * splnet() any more.  This needs more examination.)
1274 *
1275 * XXXRW: The locking here is wrong; we may take a page fault while holding
1276 * the inpcb lock.
1277 */
1278int
1279tcp_ctloutput(so, sopt)
1280	struct socket *so;
1281	struct sockopt *sopt;
1282{
1283	int	error, opt, optval;
1284	struct	inpcb *inp;
1285	struct	tcpcb *tp;
1286	struct	tcp_info ti;
1287
1288	error = 0;
1289	inp = sotoinpcb(so);
1290	KASSERT(inp != NULL, ("tcp_ctloutput: inp == NULL"));
1291	INP_LOCK(inp);
1292	if (sopt->sopt_level != IPPROTO_TCP) {
1293		INP_UNLOCK(inp);
1294#ifdef INET6
1295		if (INP_CHECK_SOCKAF(so, AF_INET6))
1296			error = ip6_ctloutput(so, sopt);
1297		else
1298#endif /* INET6 */
1299		error = ip_ctloutput(so, sopt);
1300		return (error);
1301	}
1302	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
1303		error = ECONNRESET;
1304		goto out;
1305	}
1306	tp = intotcpcb(inp);
1307
1308	switch (sopt->sopt_dir) {
1309	case SOPT_SET:
1310		switch (sopt->sopt_name) {
1311#ifdef TCP_SIGNATURE
1312		case TCP_MD5SIG:
1313			error = sooptcopyin(sopt, &optval, sizeof optval,
1314					    sizeof optval);
1315			if (error)
1316				break;
1317
1318			if (optval > 0)
1319				tp->t_flags |= TF_SIGNATURE;
1320			else
1321				tp->t_flags &= ~TF_SIGNATURE;
1322			break;
1323#endif /* TCP_SIGNATURE */
1324		case TCP_NODELAY:
1325		case TCP_NOOPT:
1326			error = sooptcopyin(sopt, &optval, sizeof optval,
1327					    sizeof optval);
1328			if (error)
1329				break;
1330
1331			switch (sopt->sopt_name) {
1332			case TCP_NODELAY:
1333				opt = TF_NODELAY;
1334				break;
1335			case TCP_NOOPT:
1336				opt = TF_NOOPT;
1337				break;
1338			default:
1339				opt = 0; /* dead code to fool gcc */
1340				break;
1341			}
1342
1343			if (optval)
1344				tp->t_flags |= opt;
1345			else
1346				tp->t_flags &= ~opt;
1347			break;
1348
1349		case TCP_NOPUSH:
1350			error = sooptcopyin(sopt, &optval, sizeof optval,
1351					    sizeof optval);
1352			if (error)
1353				break;
1354
1355			if (optval)
1356				tp->t_flags |= TF_NOPUSH;
1357			else {
1358				tp->t_flags &= ~TF_NOPUSH;
1359				error = tcp_output(tp);
1360			}
1361			break;
1362
1363		case TCP_MAXSEG:
1364			error = sooptcopyin(sopt, &optval, sizeof optval,
1365					    sizeof optval);
1366			if (error)
1367				break;
1368
1369			if (optval > 0 && optval <= tp->t_maxseg &&
1370			    optval + 40 >= tcp_minmss)
1371				tp->t_maxseg = optval;
1372			else
1373				error = EINVAL;
1374			break;
1375
1376		case TCP_INFO:
1377			error = EINVAL;
1378			break;
1379
1380		default:
1381			error = ENOPROTOOPT;
1382			break;
1383		}
1384		break;
1385
1386	case SOPT_GET:
1387		switch (sopt->sopt_name) {
1388#ifdef TCP_SIGNATURE
1389		case TCP_MD5SIG:
1390			optval = (tp->t_flags & TF_SIGNATURE) ? 1 : 0;
1391			error = sooptcopyout(sopt, &optval, sizeof optval);
1392			break;
1393#endif
1394		case TCP_NODELAY:
1395			optval = tp->t_flags & TF_NODELAY;
1396			error = sooptcopyout(sopt, &optval, sizeof optval);
1397			break;
1398		case TCP_MAXSEG:
1399			optval = tp->t_maxseg;
1400			error = sooptcopyout(sopt, &optval, sizeof optval);
1401			break;
1402		case TCP_NOOPT:
1403			optval = tp->t_flags & TF_NOOPT;
1404			error = sooptcopyout(sopt, &optval, sizeof optval);
1405			break;
1406		case TCP_NOPUSH:
1407			optval = tp->t_flags & TF_NOPUSH;
1408			error = sooptcopyout(sopt, &optval, sizeof optval);
1409			break;
1410		case TCP_INFO:
1411			tcp_fill_info(tp, &ti);
1412			error = sooptcopyout(sopt, &ti, sizeof ti);
1413			break;
1414		default:
1415			error = ENOPROTOOPT;
1416			break;
1417		}
1418		break;
1419	}
1420out:
1421	INP_UNLOCK(inp);
1422	return (error);
1423}
1424
1425/*
1426 * tcp_sendspace and tcp_recvspace are the default send and receive window
1427 * sizes, respectively.  These are obsolescent (this information should
1428 * be set by the route).
1429 */
1430u_long	tcp_sendspace = 1024*32;
1431SYSCTL_ULONG(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_RW,
1432    &tcp_sendspace , 0, "Maximum outgoing TCP datagram size");
1433u_long	tcp_recvspace = 1024*64;
1434SYSCTL_ULONG(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
1435    &tcp_recvspace , 0, "Maximum incoming TCP datagram size");
1436
1437/*
1438 * Attach TCP protocol to socket, allocating
1439 * internet protocol control block, tcp control block,
1440 * bufer space, and entering LISTEN state if to accept connections.
1441 */
1442static int
1443tcp_attach(so)
1444	struct socket *so;
1445{
1446	register struct tcpcb *tp;
1447	struct inpcb *inp;
1448	int error;
1449#ifdef INET6
1450	int isipv6 = INP_CHECK_SOCKAF(so, AF_INET6) != 0;
1451#endif
1452
1453	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
1454		error = soreserve(so, tcp_sendspace, tcp_recvspace);
1455		if (error)
1456			return (error);
1457	}
1458	so->so_rcv.sb_flags |= SB_AUTOSIZE;
1459	so->so_snd.sb_flags |= SB_AUTOSIZE;
1460	INP_INFO_WLOCK(&tcbinfo);
1461	error = in_pcballoc(so, &tcbinfo);
1462	if (error) {
1463		INP_INFO_WUNLOCK(&tcbinfo);
1464		return (error);
1465	}
1466	inp = sotoinpcb(so);
1467#ifdef INET6
1468	if (isipv6) {
1469		inp->inp_vflag |= INP_IPV6;
1470		inp->in6p_hops = -1;	/* use kernel default */
1471	}
1472	else
1473#endif
1474	inp->inp_vflag |= INP_IPV4;
1475	tp = tcp_newtcpcb(inp);
1476	if (tp == NULL) {
1477#ifdef INET6
1478		if (isipv6) {
1479			in6_pcbdetach(inp);
1480			in6_pcbfree(inp);
1481		} else {
1482#endif
1483			in_pcbdetach(inp);
1484			in_pcbfree(inp);
1485#ifdef INET6
1486		}
1487#endif
1488		INP_INFO_WUNLOCK(&tcbinfo);
1489		return (ENOBUFS);
1490	}
1491	tp->t_state = TCPS_CLOSED;
1492	INP_UNLOCK(inp);
1493	INP_INFO_WUNLOCK(&tcbinfo);
1494	return (0);
1495}
1496
1497/*
1498 * Initiate (or continue) disconnect.
1499 * If embryonic state, just send reset (once).
1500 * If in ``let data drain'' option and linger null, just drop.
1501 * Otherwise (hard), mark socket disconnecting and drop
1502 * current input data; switch states based on user close, and
1503 * send segment to peer (with FIN).
1504 */
1505static void
1506tcp_disconnect(tp)
1507	register struct tcpcb *tp;
1508{
1509	struct inpcb *inp = tp->t_inpcb;
1510	struct socket *so = inp->inp_socket;
1511
1512	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1513	INP_LOCK_ASSERT(inp);
1514
1515	/*
1516	 * Neither tcp_close() nor tcp_drop() should return NULL, as the
1517	 * socket is still open.
1518	 */
1519	if (tp->t_state < TCPS_ESTABLISHED) {
1520		tp = tcp_close(tp);
1521		KASSERT(tp != NULL,
1522		    ("tcp_disconnect: tcp_close() returned NULL"));
1523	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
1524		tp = tcp_drop(tp, 0);
1525		KASSERT(tp != NULL,
1526		    ("tcp_disconnect: tcp_drop() returned NULL"));
1527	} else {
1528		soisdisconnecting(so);
1529		sbflush(&so->so_rcv);
1530		tcp_usrclosed(tp);
1531		if (!(inp->inp_vflag & INP_DROPPED))
1532			tcp_output(tp);
1533	}
1534}
1535
1536/*
1537 * User issued close, and wish to trail through shutdown states:
1538 * if never received SYN, just forget it.  If got a SYN from peer,
1539 * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
1540 * If already got a FIN from peer, then almost done; go to LAST_ACK
1541 * state.  In all other cases, have already sent FIN to peer (e.g.
1542 * after PRU_SHUTDOWN), and just have to play tedious game waiting
1543 * for peer to send FIN or not respond to keep-alives, etc.
1544 * We can let the user exit from the close as soon as the FIN is acked.
1545 */
1546static void
1547tcp_usrclosed(tp)
1548	register struct tcpcb *tp;
1549{
1550
1551	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1552	INP_LOCK_ASSERT(tp->t_inpcb);
1553
1554	switch (tp->t_state) {
1555
1556	case TCPS_CLOSED:
1557	case TCPS_LISTEN:
1558		tp->t_state = TCPS_CLOSED;
1559		tp = tcp_close(tp);
1560		/*
1561		 * tcp_close() should never return NULL here as the socket is
1562		 * still open.
1563		 */
1564		KASSERT(tp != NULL,
1565		    ("tcp_usrclosed: tcp_close() returned NULL"));
1566		break;
1567
1568	case TCPS_SYN_SENT:
1569	case TCPS_SYN_RECEIVED:
1570		tp->t_flags |= TF_NEEDFIN;
1571		break;
1572
1573	case TCPS_ESTABLISHED:
1574		tp->t_state = TCPS_FIN_WAIT_1;
1575		break;
1576
1577	case TCPS_CLOSE_WAIT:
1578		tp->t_state = TCPS_LAST_ACK;
1579		break;
1580	}
1581	if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
1582		soisdisconnected(tp->t_inpcb->inp_socket);
1583		/* To prevent the connection hanging in FIN_WAIT_2 forever. */
1584		if (tp->t_state == TCPS_FIN_WAIT_2) {
1585			int timeout;
1586
1587			timeout = (tcp_fast_finwait2_recycle) ?
1588				tcp_finwait2_timeout : tcp_maxidle;
1589			callout_reset(tp->tt_2msl, timeout,
1590				      tcp_timer_2msl, tp);
1591		}
1592	}
1593}
1594
1595#ifdef DDB
1596static void
1597db_print_indent(int indent)
1598{
1599	int i;
1600
1601	for (i = 0; i < indent; i++)
1602		db_printf(" ");
1603}
1604
1605static void
1606db_print_tstate(int t_state)
1607{
1608
1609	switch (t_state) {
1610	case TCPS_CLOSED:
1611		db_printf("TCPS_CLOSED");
1612		return;
1613
1614	case TCPS_LISTEN:
1615		db_printf("TCPS_LISTEN");
1616		return;
1617
1618	case TCPS_SYN_SENT:
1619		db_printf("TCPS_SYN_SENT");
1620		return;
1621
1622	case TCPS_SYN_RECEIVED:
1623		db_printf("TCPS_SYN_RECEIVED");
1624		return;
1625
1626	case TCPS_ESTABLISHED:
1627		db_printf("TCPS_ESTABLISHED");
1628		return;
1629
1630	case TCPS_CLOSE_WAIT:
1631		db_printf("TCPS_CLOSE_WAIT");
1632		return;
1633
1634	case TCPS_FIN_WAIT_1:
1635		db_printf("TCPS_FIN_WAIT_1");
1636		return;
1637
1638	case TCPS_CLOSING:
1639		db_printf("TCPS_CLOSING");
1640		return;
1641
1642	case TCPS_LAST_ACK:
1643		db_printf("TCPS_LAST_ACK");
1644		return;
1645
1646	case TCPS_FIN_WAIT_2:
1647		db_printf("TCPS_FIN_WAIT_2");
1648		return;
1649
1650	case TCPS_TIME_WAIT:
1651		db_printf("TCPS_TIME_WAIT");
1652		return;
1653
1654	default:
1655		db_printf("unknown");
1656		return;
1657	}
1658}
1659
1660static void
1661db_print_tflags(u_int t_flags)
1662{
1663	int comma;
1664
1665	comma = 0;
1666	if (t_flags & TF_ACKNOW) {
1667		db_printf("%sTF_ACKNOW", comma ? ", " : "");
1668		comma = 1;
1669	}
1670	if (t_flags & TF_DELACK) {
1671		db_printf("%sTF_DELACK", comma ? ", " : "");
1672		comma = 1;
1673	}
1674	if (t_flags & TF_NODELAY) {
1675		db_printf("%sTF_NODELAY", comma ? ", " : "");
1676		comma = 1;
1677	}
1678	if (t_flags & TF_NOOPT) {
1679		db_printf("%sTF_NOOPT", comma ? ", " : "");
1680		comma = 1;
1681	}
1682	if (t_flags & TF_SENTFIN) {
1683		db_printf("%sTF_SENTFIN", comma ? ", " : "");
1684		comma = 1;
1685	}
1686	if (t_flags & TF_REQ_SCALE) {
1687		db_printf("%sTF_REQ_SCALE", comma ? ", " : "");
1688		comma = 1;
1689	}
1690	if (t_flags & TF_RCVD_SCALE) {
1691		db_printf("%sTF_RECVD_SCALE", comma ? ", " : "");
1692		comma = 1;
1693	}
1694	if (t_flags & TF_REQ_TSTMP) {
1695		db_printf("%sTF_REQ_TSTMP", comma ? ", " : "");
1696		comma = 1;
1697	}
1698	if (t_flags & TF_RCVD_TSTMP) {
1699		db_printf("%sTF_RCVD_TSTMP", comma ? ", " : "");
1700		comma = 1;
1701	}
1702	if (t_flags & TF_SACK_PERMIT) {
1703		db_printf("%sTF_SACK_PERMIT", comma ? ", " : "");
1704		comma = 1;
1705	}
1706	if (t_flags & TF_NEEDSYN) {
1707		db_printf("%sTF_NEEDSYN", comma ? ", " : "");
1708		comma = 1;
1709	}
1710	if (t_flags & TF_NEEDFIN) {
1711		db_printf("%sTF_NEEDFIN", comma ? ", " : "");
1712		comma = 1;
1713	}
1714	if (t_flags & TF_NOPUSH) {
1715		db_printf("%sTF_NOPUSH", comma ? ", " : "");
1716		comma = 1;
1717	}
1718	if (t_flags & TF_NOPUSH) {
1719		db_printf("%sTF_NOPUSH", comma ? ", " : "");
1720		comma = 1;
1721	}
1722	if (t_flags & TF_MORETOCOME) {
1723		db_printf("%sTF_MORETOCOME", comma ? ", " : "");
1724		comma = 1;
1725	}
1726	if (t_flags & TF_LQ_OVERFLOW) {
1727		db_printf("%sTF_LQ_OVERFLOW", comma ? ", " : "");
1728		comma = 1;
1729	}
1730	if (t_flags & TF_LASTIDLE) {
1731		db_printf("%sTF_LASTIDLE", comma ? ", " : "");
1732		comma = 1;
1733	}
1734	if (t_flags & TF_RXWIN0SENT) {
1735		db_printf("%sTF_RXWIN0SENT", comma ? ", " : "");
1736		comma = 1;
1737	}
1738	if (t_flags & TF_FASTRECOVERY) {
1739		db_printf("%sTF_FASTRECOVERY", comma ? ", " : "");
1740		comma = 1;
1741	}
1742	if (t_flags & TF_WASFRECOVERY) {
1743		db_printf("%sTF_WASFRECOVERY", comma ? ", " : "");
1744		comma = 1;
1745	}
1746	if (t_flags & TF_SIGNATURE) {
1747		db_printf("%sTF_SIGNATURE", comma ? ", " : "");
1748		comma = 1;
1749	}
1750	if (t_flags & TF_FORCEDATA) {
1751		db_printf("%sTF_FORCEDATA", comma ? ", " : "");
1752		comma = 1;
1753	}
1754	if (t_flags & TF_TSO) {
1755		db_printf("%sTF_TSO", comma ? ", " : "");
1756		comma = 1;
1757	}
1758}
1759
1760static void
1761db_print_toobflags(char t_oobflags)
1762{
1763	int comma;
1764
1765	comma = 0;
1766	if (t_oobflags & TCPOOB_HAVEDATA) {
1767		db_printf("%sTCPOOB_HAVEDATA", comma ? ", " : "");
1768		comma = 1;
1769	}
1770	if (t_oobflags & TCPOOB_HADDATA) {
1771		db_printf("%sTCPOOB_HADDATA", comma ? ", " : "");
1772		comma = 1;
1773	}
1774}
1775
1776static void
1777db_print_tcpcb(struct tcpcb *tp, const char *name, int indent)
1778{
1779
1780	db_print_indent(indent);
1781	db_printf("%s at %p\n", name, tp);
1782
1783	indent += 2;
1784
1785	db_print_indent(indent);
1786	db_printf("t_segq first: %p   t_segqlen: %d   t_dupacks: %d\n",
1787	   LIST_FIRST(&tp->t_segq), tp->t_segqlen, tp->t_dupacks);
1788
1789	db_print_indent(indent);
1790	db_printf("tt_rexmt: %p   tt_persist: %p   tt_keep: %p\n",
1791	    tp->tt_rexmt, tp->tt_persist, tp->tt_keep);
1792
1793	db_print_indent(indent);
1794	db_printf("tt_2msl: %p   tt_delack: %p   t_inpcb: %p\n", tp->tt_2msl,
1795	    tp->tt_delack, tp->t_inpcb);
1796
1797	db_print_indent(indent);
1798	db_printf("t_state: %d (", tp->t_state);
1799	db_print_tstate(tp->t_state);
1800	db_printf(")\n");
1801
1802	db_print_indent(indent);
1803	db_printf("t_flags: 0x%x (", tp->t_flags);
1804	db_print_tflags(tp->t_flags);
1805	db_printf(")\n");
1806
1807	db_print_indent(indent);
1808	db_printf("snd_una: 0x%08x   snd_max: 0x%08x   snd_nxt: x0%08x\n",
1809	    tp->snd_una, tp->snd_max, tp->snd_nxt);
1810
1811	db_print_indent(indent);
1812	db_printf("snd_up: 0x%08x   snd_wl1: 0x%08x   snd_wl2: 0x%08x\n",
1813	   tp->snd_up, tp->snd_wl1, tp->snd_wl2);
1814
1815	db_print_indent(indent);
1816	db_printf("iss: 0x%08x   irs: 0x%08x   rcv_nxt: 0x%08x\n",
1817	    tp->iss, tp->irs, tp->rcv_nxt);
1818
1819	db_print_indent(indent);
1820	db_printf("rcv_adv: 0x%08x   rcv_wnd: %lu   rcv_up: 0x%08x\n",
1821	    tp->rcv_adv, tp->rcv_wnd, tp->rcv_up);
1822
1823	db_print_indent(indent);
1824	db_printf("snd_wnd: %lu   snd_cwnd: %lu   snd_bwnd: %lu\n",
1825	   tp->snd_wnd, tp->snd_cwnd, tp->snd_bwnd);
1826
1827	db_print_indent(indent);
1828	db_printf("snd_ssthresh: %lu   snd_bandwidth: %lu   snd_recover: "
1829	    "0x%08x\n", tp->snd_ssthresh, tp->snd_bandwidth,
1830	    tp->snd_recover);
1831
1832	db_print_indent(indent);
1833	db_printf("t_maxopd: %u   t_rcvtime: %lu   t_startime: %lu\n",
1834	    tp->t_maxopd, tp->t_rcvtime, tp->t_starttime);
1835
1836	db_print_indent(indent);
1837	db_printf("t_rttime: %d   t_rtsq: 0x%08x   t_bw_rtttime: %d\n",
1838	    tp->t_rtttime, tp->t_rtseq, tp->t_bw_rtttime);
1839
1840	db_print_indent(indent);
1841	db_printf("t_bw_rtseq: 0x%08x   t_rxtcur: %d   t_maxseg: %u   "
1842	    "t_srtt: %d\n", tp->t_bw_rtseq, tp->t_rxtcur, tp->t_maxseg,
1843	    tp->t_srtt);
1844
1845	db_print_indent(indent);
1846	db_printf("t_rttvar: %d   t_rxtshift: %d   t_rttmin: %u   "
1847	    "t_rttbest: %u\n", tp->t_rttvar, tp->t_rxtshift, tp->t_rttmin,
1848	    tp->t_rttbest);
1849
1850	db_print_indent(indent);
1851	db_printf("t_rttupdated: %lu   max_sndwnd: %lu   t_softerror: %d\n",
1852	    tp->t_rttupdated, tp->max_sndwnd, tp->t_softerror);
1853
1854	db_print_indent(indent);
1855	db_printf("t_oobflags: 0x%x (", tp->t_oobflags);
1856	db_print_toobflags(tp->t_oobflags);
1857	db_printf(")   t_iobc: 0x%02x\n", tp->t_iobc);
1858
1859	db_print_indent(indent);
1860	db_printf("snd_scale: %u   rcv_scale: %u   request_r_scale: %u\n",
1861	    tp->snd_scale, tp->rcv_scale, tp->request_r_scale);
1862
1863	db_print_indent(indent);
1864	db_printf("requested_s_scale: %u   ts_recent: %u   ts_recent_age: "
1865	    "%lu\n", tp->requested_s_scale, tp->ts_recent, tp->ts_recent_age);
1866
1867	db_print_indent(indent);
1868	db_printf("ts_offset: %u   last_ack_sent: 0x%08x   snd_cwnd_prev: "
1869	    "%lu\n", tp->ts_offset, tp->last_ack_sent, tp->snd_cwnd_prev);
1870
1871	db_print_indent(indent);
1872	db_printf("snd_ssthresh_prev: %lu   snd_recover_prev: 0x%08x   "
1873	    "t_badrxtwin: %lu\n", tp->snd_ssthresh_prev,
1874	    tp->snd_recover_prev, tp->t_badrxtwin);
1875
1876	db_print_indent(indent);
1877	db_printf("snd_limited: %u   rcv_second: %lu   rcv_pps: %lu   "
1878	    "tcv_byps: %lu\n", tp->snd_limited, tp->rcv_second, tp->rcv_pps,
1879	    tp->rcv_byps);
1880
1881	db_print_indent(indent);
1882	db_printf("sack_enable: %d   snd_numholes: %d  snd_holes first: %p\n",
1883	    tp->sack_enable, tp->snd_numholes, TAILQ_FIRST(&tp->snd_holes));
1884
1885	db_print_indent(indent);
1886	db_printf("snd_fack: 0x%08x   rcv_numsacks: %d   sack_newdata: "
1887	    "0x%08x\n", tp->snd_fack, tp->rcv_numsacks, tp->sack_newdata);
1888
1889	/* Skip sackblks, sackhint. */
1890
1891	db_print_indent(indent);
1892	db_printf("t_rttlow: %d   rfbuf_ts: %u   rfbuf_cnt: %d\n",
1893	    tp->t_rttlow, tp->rfbuf_ts, tp->rfbuf_cnt);
1894}
1895
1896DB_SHOW_COMMAND(tcpcb, db_show_tcpcb)
1897{
1898	struct tcpcb *tp;
1899
1900	if (!have_addr) {
1901		db_printf("usage: show tcpcb <addr>\n");
1902		return;
1903	}
1904	tp = (struct tcpcb *)addr;
1905
1906	db_print_tcpcb(tp, "tcpcb", 0);
1907}
1908#endif
1909