tcp_usrreq.c revision 169454
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 169454 2007-05-10 15:58:48Z rwatson $
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
698	return (in_setsockaddr(so, nam));
699}
700
701/*
702 * This is the wrapper function for in_setpeeraddr. We just pass down
703 * the pcbinfo for in_setpeeraddr to lock.
704 */
705static int
706tcp_peeraddr(struct socket *so, struct sockaddr **nam)
707{
708
709	return (in_setpeeraddr(so, nam));
710}
711
712/*
713 * Mark the connection as being incapable of further output.
714 */
715static int
716tcp_usr_shutdown(struct socket *so)
717{
718	int error = 0;
719	struct inpcb *inp;
720	struct tcpcb *tp = NULL;
721
722	TCPDEBUG0;
723	INP_INFO_WLOCK(&tcbinfo);
724	inp = sotoinpcb(so);
725	KASSERT(inp != NULL, ("inp == NULL"));
726	INP_LOCK(inp);
727	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
728		error = ECONNRESET;
729		goto out;
730	}
731	tp = intotcpcb(inp);
732	TCPDEBUG1();
733	socantsendmore(so);
734	tcp_usrclosed(tp);
735	error = tcp_output(tp);
736
737out:
738	TCPDEBUG2(PRU_SHUTDOWN);
739	INP_UNLOCK(inp);
740	INP_INFO_WUNLOCK(&tcbinfo);
741
742	return (error);
743}
744
745/*
746 * After a receive, possibly send window update to peer.
747 */
748static int
749tcp_usr_rcvd(struct socket *so, int flags)
750{
751	struct inpcb *inp;
752	struct tcpcb *tp = NULL;
753	int error = 0;
754
755	TCPDEBUG0;
756	inp = sotoinpcb(so);
757	KASSERT(inp != NULL, ("tcp_usr_rcvd: inp == NULL"));
758	INP_LOCK(inp);
759	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
760		error = ECONNRESET;
761		goto out;
762	}
763	tp = intotcpcb(inp);
764	TCPDEBUG1();
765	tcp_output(tp);
766
767out:
768	TCPDEBUG2(PRU_RCVD);
769	INP_UNLOCK(inp);
770	return (error);
771}
772
773/*
774 * Do a send by putting data in output queue and updating urgent
775 * marker if URG set.  Possibly send more data.  Unlike the other
776 * pru_*() routines, the mbuf chains are our responsibility.  We
777 * must either enqueue them or free them.  The other pru_* routines
778 * generally are caller-frees.
779 */
780static int
781tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
782    struct sockaddr *nam, struct mbuf *control, struct thread *td)
783{
784	int error = 0;
785	struct inpcb *inp;
786	struct tcpcb *tp = NULL;
787	int headlocked = 0;
788#ifdef INET6
789	int isipv6;
790#endif
791	TCPDEBUG0;
792
793	/*
794	 * We require the pcbinfo lock in two cases:
795	 *
796	 * (1) An implied connect is taking place, which can result in
797	 *     binding IPs and ports and hence modification of the pcb hash
798	 *     chains.
799	 *
800	 * (2) PRUS_EOF is set, resulting in explicit close on the send.
801	 */
802	if ((nam != NULL) || (flags & PRUS_EOF)) {
803		INP_INFO_WLOCK(&tcbinfo);
804		headlocked = 1;
805	}
806	inp = sotoinpcb(so);
807	KASSERT(inp != NULL, ("tcp_usr_send: inp == NULL"));
808	INP_LOCK(inp);
809	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
810		if (control)
811			m_freem(control);
812		if (m)
813			m_freem(m);
814		error = ECONNRESET;
815		goto out;
816	}
817#ifdef INET6
818	isipv6 = nam && nam->sa_family == AF_INET6;
819#endif /* INET6 */
820	tp = intotcpcb(inp);
821	TCPDEBUG1();
822	if (control) {
823		/* TCP doesn't do control messages (rights, creds, etc) */
824		if (control->m_len) {
825			m_freem(control);
826			if (m)
827				m_freem(m);
828			error = EINVAL;
829			goto out;
830		}
831		m_freem(control);	/* empty control, just free it */
832	}
833	if (!(flags & PRUS_OOB)) {
834		sbappendstream(&so->so_snd, m);
835		if (nam && tp->t_state < TCPS_SYN_SENT) {
836			/*
837			 * Do implied connect if not yet connected,
838			 * initialize window to default value, and
839			 * initialize maxseg/maxopd using peer's cached
840			 * MSS.
841			 */
842			INP_INFO_WLOCK_ASSERT(&tcbinfo);
843#ifdef INET6
844			if (isipv6)
845				error = tcp6_connect(tp, nam, td);
846			else
847#endif /* INET6 */
848			error = tcp_connect(tp, nam, td);
849			if (error)
850				goto out;
851			tp->snd_wnd = TTCP_CLIENT_SND_WND;
852			tcp_mss(tp, -1);
853		}
854		if (flags & PRUS_EOF) {
855			/*
856			 * Close the send side of the connection after
857			 * the data is sent.
858			 */
859			INP_INFO_WLOCK_ASSERT(&tcbinfo);
860			socantsendmore(so);
861			tcp_usrclosed(tp);
862		}
863		if (headlocked) {
864			INP_INFO_WUNLOCK(&tcbinfo);
865			headlocked = 0;
866		}
867		if (tp != NULL) {
868			if (flags & PRUS_MORETOCOME)
869				tp->t_flags |= TF_MORETOCOME;
870			error = tcp_output(tp);
871			if (flags & PRUS_MORETOCOME)
872				tp->t_flags &= ~TF_MORETOCOME;
873		}
874	} else {
875		/*
876		 * XXXRW: PRUS_EOF not implemented with PRUS_OOB?
877		 */
878		SOCKBUF_LOCK(&so->so_snd);
879		if (sbspace(&so->so_snd) < -512) {
880			SOCKBUF_UNLOCK(&so->so_snd);
881			m_freem(m);
882			error = ENOBUFS;
883			goto out;
884		}
885		/*
886		 * According to RFC961 (Assigned Protocols),
887		 * the urgent pointer points to the last octet
888		 * of urgent data.  We continue, however,
889		 * to consider it to indicate the first octet
890		 * of data past the urgent section.
891		 * Otherwise, snd_up should be one lower.
892		 */
893		sbappendstream_locked(&so->so_snd, m);
894		SOCKBUF_UNLOCK(&so->so_snd);
895		if (nam && tp->t_state < TCPS_SYN_SENT) {
896			/*
897			 * Do implied connect if not yet connected,
898			 * initialize window to default value, and
899			 * initialize maxseg/maxopd using peer's cached
900			 * MSS.
901			 */
902			INP_INFO_WLOCK_ASSERT(&tcbinfo);
903#ifdef INET6
904			if (isipv6)
905				error = tcp6_connect(tp, nam, td);
906			else
907#endif /* INET6 */
908			error = tcp_connect(tp, nam, td);
909			if (error)
910				goto out;
911			tp->snd_wnd = TTCP_CLIENT_SND_WND;
912			tcp_mss(tp, -1);
913			INP_INFO_WUNLOCK(&tcbinfo);
914			headlocked = 0;
915		} else if (nam) {
916			INP_INFO_WUNLOCK(&tcbinfo);
917			headlocked = 0;
918		}
919		tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
920		tp->t_flags |= TF_FORCEDATA;
921		error = tcp_output(tp);
922		tp->t_flags &= ~TF_FORCEDATA;
923	}
924out:
925	TCPDEBUG2((flags & PRUS_OOB) ? PRU_SENDOOB :
926		  ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
927	INP_UNLOCK(inp);
928	if (headlocked)
929		INP_INFO_WUNLOCK(&tcbinfo);
930	return (error);
931}
932
933/*
934 * Abort the TCP.  Drop the connection abruptly.
935 */
936static void
937tcp_usr_abort(struct socket *so)
938{
939	struct inpcb *inp;
940	struct tcpcb *tp = NULL;
941	TCPDEBUG0;
942
943	inp = sotoinpcb(so);
944	KASSERT(inp != NULL, ("tcp_usr_abort: inp == NULL"));
945
946	INP_INFO_WLOCK(&tcbinfo);
947	INP_LOCK(inp);
948	KASSERT(inp->inp_socket != NULL,
949	    ("tcp_usr_abort: inp_socket == NULL"));
950
951	/*
952	 * If we still have full TCP state, and we're not dropped, drop.
953	 */
954	if (!(inp->inp_vflag & INP_TIMEWAIT) &&
955	    !(inp->inp_vflag & INP_DROPPED)) {
956		tp = intotcpcb(inp);
957		TCPDEBUG1();
958		tcp_drop(tp, ECONNABORTED);
959		TCPDEBUG2(PRU_ABORT);
960	}
961	if (!(inp->inp_vflag & INP_DROPPED)) {
962		SOCK_LOCK(so);
963		so->so_state |= SS_PROTOREF;
964		SOCK_UNLOCK(so);
965		inp->inp_vflag |= INP_SOCKREF;
966	}
967	INP_UNLOCK(inp);
968	INP_INFO_WUNLOCK(&tcbinfo);
969}
970
971/*
972 * TCP socket is closed.  Start friendly disconnect.
973 */
974static void
975tcp_usr_close(struct socket *so)
976{
977	struct inpcb *inp;
978	struct tcpcb *tp = NULL;
979	TCPDEBUG0;
980
981	inp = sotoinpcb(so);
982	KASSERT(inp != NULL, ("tcp_usr_close: inp == NULL"));
983
984	INP_INFO_WLOCK(&tcbinfo);
985	INP_LOCK(inp);
986	KASSERT(inp->inp_socket != NULL,
987	    ("tcp_usr_close: inp_socket == NULL"));
988
989	/*
990	 * If we still have full TCP state, and we're not dropped, initiate
991	 * a disconnect.
992	 */
993	if (!(inp->inp_vflag & INP_TIMEWAIT) &&
994	    !(inp->inp_vflag & INP_DROPPED)) {
995		tp = intotcpcb(inp);
996		TCPDEBUG1();
997		tcp_disconnect(tp);
998		TCPDEBUG2(PRU_CLOSE);
999	}
1000	if (!(inp->inp_vflag & INP_DROPPED)) {
1001		SOCK_LOCK(so);
1002		so->so_state |= SS_PROTOREF;
1003		SOCK_UNLOCK(so);
1004		inp->inp_vflag |= INP_SOCKREF;
1005	}
1006	INP_UNLOCK(inp);
1007	INP_INFO_WUNLOCK(&tcbinfo);
1008}
1009
1010/*
1011 * Receive out-of-band data.
1012 */
1013static int
1014tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
1015{
1016	int error = 0;
1017	struct inpcb *inp;
1018	struct tcpcb *tp = NULL;
1019
1020	TCPDEBUG0;
1021	inp = sotoinpcb(so);
1022	KASSERT(inp != NULL, ("tcp_usr_rcvoob: inp == NULL"));
1023	INP_LOCK(inp);
1024	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
1025		error = ECONNRESET;
1026		goto out;
1027	}
1028	tp = intotcpcb(inp);
1029	TCPDEBUG1();
1030	if ((so->so_oobmark == 0 &&
1031	     (so->so_rcv.sb_state & SBS_RCVATMARK) == 0) ||
1032	    so->so_options & SO_OOBINLINE ||
1033	    tp->t_oobflags & TCPOOB_HADDATA) {
1034		error = EINVAL;
1035		goto out;
1036	}
1037	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
1038		error = EWOULDBLOCK;
1039		goto out;
1040	}
1041	m->m_len = 1;
1042	*mtod(m, caddr_t) = tp->t_iobc;
1043	if ((flags & MSG_PEEK) == 0)
1044		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1045
1046out:
1047	TCPDEBUG2(PRU_RCVOOB);
1048	INP_UNLOCK(inp);
1049	return (error);
1050}
1051
1052struct pr_usrreqs tcp_usrreqs = {
1053	.pru_abort =		tcp_usr_abort,
1054	.pru_accept =		tcp_usr_accept,
1055	.pru_attach =		tcp_usr_attach,
1056	.pru_bind =		tcp_usr_bind,
1057	.pru_connect =		tcp_usr_connect,
1058	.pru_control =		in_control,
1059	.pru_detach =		tcp_usr_detach,
1060	.pru_disconnect =	tcp_usr_disconnect,
1061	.pru_listen =		tcp_usr_listen,
1062	.pru_peeraddr =		tcp_peeraddr,
1063	.pru_rcvd =		tcp_usr_rcvd,
1064	.pru_rcvoob =		tcp_usr_rcvoob,
1065	.pru_send =		tcp_usr_send,
1066	.pru_shutdown =		tcp_usr_shutdown,
1067	.pru_sockaddr =		tcp_sockaddr,
1068	.pru_sosetlabel =	in_pcbsosetlabel,
1069	.pru_close =		tcp_usr_close,
1070};
1071
1072#ifdef INET6
1073struct pr_usrreqs tcp6_usrreqs = {
1074	.pru_abort =		tcp_usr_abort,
1075	.pru_accept =		tcp6_usr_accept,
1076	.pru_attach =		tcp_usr_attach,
1077	.pru_bind =		tcp6_usr_bind,
1078	.pru_connect =		tcp6_usr_connect,
1079	.pru_control =		in6_control,
1080	.pru_detach =		tcp_usr_detach,
1081	.pru_disconnect =	tcp_usr_disconnect,
1082	.pru_listen =		tcp6_usr_listen,
1083	.pru_peeraddr =		in6_mapped_peeraddr,
1084	.pru_rcvd =		tcp_usr_rcvd,
1085	.pru_rcvoob =		tcp_usr_rcvoob,
1086	.pru_send =		tcp_usr_send,
1087	.pru_shutdown =		tcp_usr_shutdown,
1088	.pru_sockaddr =		in6_mapped_sockaddr,
1089 	.pru_sosetlabel =	in_pcbsosetlabel,
1090	.pru_close =		tcp_usr_close,
1091};
1092#endif /* INET6 */
1093
1094/*
1095 * Common subroutine to open a TCP connection to remote host specified
1096 * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1097 * port number if needed.  Call in_pcbconnect_setup to do the routing and
1098 * to choose a local host address (interface).  If there is an existing
1099 * incarnation of the same connection in TIME-WAIT state and if the remote
1100 * host was sending CC options and if the connection duration was < MSL, then
1101 * truncate the previous TIME-WAIT state and proceed.
1102 * Initialize connection parameters and enter SYN-SENT state.
1103 */
1104static int
1105tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1106{
1107	struct inpcb *inp = tp->t_inpcb, *oinp;
1108	struct socket *so = inp->inp_socket;
1109	struct in_addr laddr;
1110	u_short lport;
1111	int error;
1112
1113	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1114	INP_LOCK_ASSERT(inp);
1115
1116	if (inp->inp_lport == 0) {
1117		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1118		if (error)
1119			return error;
1120	}
1121
1122	/*
1123	 * Cannot simply call in_pcbconnect, because there might be an
1124	 * earlier incarnation of this same connection still in
1125	 * TIME_WAIT state, creating an ADDRINUSE error.
1126	 */
1127	laddr = inp->inp_laddr;
1128	lport = inp->inp_lport;
1129	error = in_pcbconnect_setup(inp, nam, &laddr.s_addr, &lport,
1130	    &inp->inp_faddr.s_addr, &inp->inp_fport, &oinp, td->td_ucred);
1131	if (error && oinp == NULL)
1132		return error;
1133	if (oinp)
1134		return EADDRINUSE;
1135	inp->inp_laddr = laddr;
1136	in_pcbrehash(inp);
1137
1138	/*
1139	 * Compute window scaling to request:
1140	 * Scale to fit into sweet spot.  See tcp_syncache.c.
1141	 * XXX: This should move to tcp_output().
1142	 * XXX: This should be based on the actual MSS.
1143	 */
1144	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1145	    (0x1 << tp->request_r_scale) < tcp_minmss)
1146		tp->request_r_scale++;
1147
1148	soisconnecting(so);
1149	tcpstat.tcps_connattempt++;
1150	tp->t_state = TCPS_SYN_SENT;
1151	tcp_timer_activate(tp, TT_KEEP, tcp_keepinit);
1152	tp->iss = tcp_new_isn(tp);
1153	tp->t_bw_rtseq = tp->iss;
1154	tcp_sendseqinit(tp);
1155
1156	return 0;
1157}
1158
1159#ifdef INET6
1160static int
1161tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1162{
1163	struct inpcb *inp = tp->t_inpcb, *oinp;
1164	struct socket *so = inp->inp_socket;
1165	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
1166	struct in6_addr *addr6;
1167	int error;
1168
1169	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1170	INP_LOCK_ASSERT(inp);
1171
1172	if (inp->inp_lport == 0) {
1173		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1174		if (error)
1175			return error;
1176	}
1177
1178	/*
1179	 * Cannot simply call in_pcbconnect, because there might be an
1180	 * earlier incarnation of this same connection still in
1181	 * TIME_WAIT state, creating an ADDRINUSE error.
1182	 * in6_pcbladdr() also handles scope zone IDs.
1183	 */
1184	error = in6_pcbladdr(inp, nam, &addr6);
1185	if (error)
1186		return error;
1187	oinp = in6_pcblookup_hash(inp->inp_pcbinfo,
1188				  &sin6->sin6_addr, sin6->sin6_port,
1189				  IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)
1190				  ? addr6
1191				  : &inp->in6p_laddr,
1192				  inp->inp_lport,  0, NULL);
1193	if (oinp)
1194		return EADDRINUSE;
1195	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1196		inp->in6p_laddr = *addr6;
1197	inp->in6p_faddr = sin6->sin6_addr;
1198	inp->inp_fport = sin6->sin6_port;
1199	/* update flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
1200	inp->in6p_flowinfo &= ~IPV6_FLOWLABEL_MASK;
1201	if (inp->in6p_flags & IN6P_AUTOFLOWLABEL)
1202		inp->in6p_flowinfo |=
1203		    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1204	in_pcbrehash(inp);
1205
1206	/* Compute window scaling to request.  */
1207	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1208	    (TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.sb_hiwat)
1209		tp->request_r_scale++;
1210
1211	soisconnecting(so);
1212	tcpstat.tcps_connattempt++;
1213	tp->t_state = TCPS_SYN_SENT;
1214	tcp_timer_activate(tp, TT_KEEP, tcp_keepinit);
1215	tp->iss = tcp_new_isn(tp);
1216	tp->t_bw_rtseq = tp->iss;
1217	tcp_sendseqinit(tp);
1218
1219	return 0;
1220}
1221#endif /* INET6 */
1222
1223/*
1224 * Export TCP internal state information via a struct tcp_info, based on the
1225 * Linux 2.6 API.  Not ABI compatible as our constants are mapped differently
1226 * (TCP state machine, etc).  We export all information using FreeBSD-native
1227 * constants -- for example, the numeric values for tcpi_state will differ
1228 * from Linux.
1229 */
1230static void
1231tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti)
1232{
1233
1234	INP_LOCK_ASSERT(tp->t_inpcb);
1235	bzero(ti, sizeof(*ti));
1236
1237	ti->tcpi_state = tp->t_state;
1238	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
1239		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1240	if (tp->t_flags & TF_SACK_PERMIT)
1241		ti->tcpi_options |= TCPI_OPT_SACK;
1242	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
1243		ti->tcpi_options |= TCPI_OPT_WSCALE;
1244		ti->tcpi_snd_wscale = tp->snd_scale;
1245		ti->tcpi_rcv_wscale = tp->rcv_scale;
1246	}
1247
1248	ti->tcpi_rtt = ((u_int64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
1249	ti->tcpi_rttvar = ((u_int64_t)tp->t_rttvar * tick) >> TCP_RTTVAR_SHIFT;
1250
1251	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1252	ti->tcpi_snd_cwnd = tp->snd_cwnd;
1253
1254	/*
1255	 * FreeBSD-specific extension fields for tcp_info.
1256	 */
1257	ti->tcpi_rcv_space = tp->rcv_wnd;
1258	ti->tcpi_snd_wnd = tp->snd_wnd;
1259	ti->tcpi_snd_bwnd = tp->snd_bwnd;
1260}
1261
1262/*
1263 * The new sockopt interface makes it possible for us to block in the
1264 * copyin/out step (if we take a page fault).  Taking a page fault at
1265 * splnet() is probably a Bad Thing.  (Since sockets and pcbs both now
1266 * use TSM, there probably isn't any need for this function to run at
1267 * splnet() any more.  This needs more examination.)
1268 *
1269 * XXXRW: The locking here is wrong; we may take a page fault while holding
1270 * the inpcb lock.
1271 */
1272int
1273tcp_ctloutput(struct socket *so, struct sockopt *sopt)
1274{
1275	int	error, opt, optval;
1276	struct	inpcb *inp;
1277	struct	tcpcb *tp;
1278	struct	tcp_info ti;
1279
1280	error = 0;
1281	inp = sotoinpcb(so);
1282	KASSERT(inp != NULL, ("tcp_ctloutput: inp == NULL"));
1283	INP_LOCK(inp);
1284	if (sopt->sopt_level != IPPROTO_TCP) {
1285		INP_UNLOCK(inp);
1286#ifdef INET6
1287		if (INP_CHECK_SOCKAF(so, AF_INET6))
1288			error = ip6_ctloutput(so, sopt);
1289		else
1290#endif /* INET6 */
1291		error = ip_ctloutput(so, sopt);
1292		return (error);
1293	}
1294	if (inp->inp_vflag & (INP_TIMEWAIT | INP_DROPPED)) {
1295		error = ECONNRESET;
1296		goto out;
1297	}
1298	tp = intotcpcb(inp);
1299
1300	switch (sopt->sopt_dir) {
1301	case SOPT_SET:
1302		switch (sopt->sopt_name) {
1303#ifdef TCP_SIGNATURE
1304		case TCP_MD5SIG:
1305			error = sooptcopyin(sopt, &optval, sizeof optval,
1306					    sizeof optval);
1307			if (error)
1308				break;
1309
1310			if (optval > 0)
1311				tp->t_flags |= TF_SIGNATURE;
1312			else
1313				tp->t_flags &= ~TF_SIGNATURE;
1314			break;
1315#endif /* TCP_SIGNATURE */
1316		case TCP_NODELAY:
1317		case TCP_NOOPT:
1318			error = sooptcopyin(sopt, &optval, sizeof optval,
1319					    sizeof optval);
1320			if (error)
1321				break;
1322
1323			switch (sopt->sopt_name) {
1324			case TCP_NODELAY:
1325				opt = TF_NODELAY;
1326				break;
1327			case TCP_NOOPT:
1328				opt = TF_NOOPT;
1329				break;
1330			default:
1331				opt = 0; /* dead code to fool gcc */
1332				break;
1333			}
1334
1335			if (optval)
1336				tp->t_flags |= opt;
1337			else
1338				tp->t_flags &= ~opt;
1339			break;
1340
1341		case TCP_NOPUSH:
1342			error = sooptcopyin(sopt, &optval, sizeof optval,
1343					    sizeof optval);
1344			if (error)
1345				break;
1346
1347			if (optval)
1348				tp->t_flags |= TF_NOPUSH;
1349			else {
1350				tp->t_flags &= ~TF_NOPUSH;
1351				error = tcp_output(tp);
1352			}
1353			break;
1354
1355		case TCP_MAXSEG:
1356			error = sooptcopyin(sopt, &optval, sizeof optval,
1357					    sizeof optval);
1358			if (error)
1359				break;
1360
1361			if (optval > 0 && optval <= tp->t_maxseg &&
1362			    optval + 40 >= tcp_minmss)
1363				tp->t_maxseg = optval;
1364			else
1365				error = EINVAL;
1366			break;
1367
1368		case TCP_INFO:
1369			error = EINVAL;
1370			break;
1371
1372		default:
1373			error = ENOPROTOOPT;
1374			break;
1375		}
1376		break;
1377
1378	case SOPT_GET:
1379		switch (sopt->sopt_name) {
1380#ifdef TCP_SIGNATURE
1381		case TCP_MD5SIG:
1382			optval = (tp->t_flags & TF_SIGNATURE) ? 1 : 0;
1383			error = sooptcopyout(sopt, &optval, sizeof optval);
1384			break;
1385#endif
1386		case TCP_NODELAY:
1387			optval = tp->t_flags & TF_NODELAY;
1388			error = sooptcopyout(sopt, &optval, sizeof optval);
1389			break;
1390		case TCP_MAXSEG:
1391			optval = tp->t_maxseg;
1392			error = sooptcopyout(sopt, &optval, sizeof optval);
1393			break;
1394		case TCP_NOOPT:
1395			optval = tp->t_flags & TF_NOOPT;
1396			error = sooptcopyout(sopt, &optval, sizeof optval);
1397			break;
1398		case TCP_NOPUSH:
1399			optval = tp->t_flags & TF_NOPUSH;
1400			error = sooptcopyout(sopt, &optval, sizeof optval);
1401			break;
1402		case TCP_INFO:
1403			tcp_fill_info(tp, &ti);
1404			error = sooptcopyout(sopt, &ti, sizeof ti);
1405			break;
1406		default:
1407			error = ENOPROTOOPT;
1408			break;
1409		}
1410		break;
1411	}
1412out:
1413	INP_UNLOCK(inp);
1414	return (error);
1415}
1416
1417/*
1418 * tcp_sendspace and tcp_recvspace are the default send and receive window
1419 * sizes, respectively.  These are obsolescent (this information should
1420 * be set by the route).
1421 */
1422u_long	tcp_sendspace = 1024*32;
1423SYSCTL_ULONG(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_RW,
1424    &tcp_sendspace , 0, "Maximum outgoing TCP datagram size");
1425u_long	tcp_recvspace = 1024*64;
1426SYSCTL_ULONG(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
1427    &tcp_recvspace , 0, "Maximum incoming TCP datagram size");
1428
1429/*
1430 * Attach TCP protocol to socket, allocating
1431 * internet protocol control block, tcp control block,
1432 * bufer space, and entering LISTEN state if to accept connections.
1433 */
1434static int
1435tcp_attach(struct socket *so)
1436{
1437	struct tcpcb *tp;
1438	struct inpcb *inp;
1439	int error;
1440#ifdef INET6
1441	int isipv6 = INP_CHECK_SOCKAF(so, AF_INET6) != 0;
1442#endif
1443
1444	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
1445		error = soreserve(so, tcp_sendspace, tcp_recvspace);
1446		if (error)
1447			return (error);
1448	}
1449	so->so_rcv.sb_flags |= SB_AUTOSIZE;
1450	so->so_snd.sb_flags |= SB_AUTOSIZE;
1451	INP_INFO_WLOCK(&tcbinfo);
1452	error = in_pcballoc(so, &tcbinfo);
1453	if (error) {
1454		INP_INFO_WUNLOCK(&tcbinfo);
1455		return (error);
1456	}
1457	inp = sotoinpcb(so);
1458#ifdef INET6
1459	if (isipv6) {
1460		inp->inp_vflag |= INP_IPV6;
1461		inp->in6p_hops = -1;	/* use kernel default */
1462	}
1463	else
1464#endif
1465	inp->inp_vflag |= INP_IPV4;
1466	tp = tcp_newtcpcb(inp);
1467	if (tp == NULL) {
1468#ifdef INET6
1469		if (isipv6) {
1470			in6_pcbdetach(inp);
1471			in6_pcbfree(inp);
1472		} else {
1473#endif
1474			in_pcbdetach(inp);
1475			in_pcbfree(inp);
1476#ifdef INET6
1477		}
1478#endif
1479		INP_INFO_WUNLOCK(&tcbinfo);
1480		return (ENOBUFS);
1481	}
1482	tp->t_state = TCPS_CLOSED;
1483	INP_UNLOCK(inp);
1484	INP_INFO_WUNLOCK(&tcbinfo);
1485	return (0);
1486}
1487
1488/*
1489 * Initiate (or continue) disconnect.
1490 * If embryonic state, just send reset (once).
1491 * If in ``let data drain'' option and linger null, just drop.
1492 * Otherwise (hard), mark socket disconnecting and drop
1493 * current input data; switch states based on user close, and
1494 * send segment to peer (with FIN).
1495 */
1496static void
1497tcp_disconnect(struct tcpcb *tp)
1498{
1499	struct inpcb *inp = tp->t_inpcb;
1500	struct socket *so = inp->inp_socket;
1501
1502	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1503	INP_LOCK_ASSERT(inp);
1504
1505	/*
1506	 * Neither tcp_close() nor tcp_drop() should return NULL, as the
1507	 * socket is still open.
1508	 */
1509	if (tp->t_state < TCPS_ESTABLISHED) {
1510		tp = tcp_close(tp);
1511		KASSERT(tp != NULL,
1512		    ("tcp_disconnect: tcp_close() returned NULL"));
1513	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
1514		tp = tcp_drop(tp, 0);
1515		KASSERT(tp != NULL,
1516		    ("tcp_disconnect: tcp_drop() returned NULL"));
1517	} else {
1518		soisdisconnecting(so);
1519		sbflush(&so->so_rcv);
1520		tcp_usrclosed(tp);
1521		if (!(inp->inp_vflag & INP_DROPPED))
1522			tcp_output(tp);
1523	}
1524}
1525
1526/*
1527 * User issued close, and wish to trail through shutdown states:
1528 * if never received SYN, just forget it.  If got a SYN from peer,
1529 * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
1530 * If already got a FIN from peer, then almost done; go to LAST_ACK
1531 * state.  In all other cases, have already sent FIN to peer (e.g.
1532 * after PRU_SHUTDOWN), and just have to play tedious game waiting
1533 * for peer to send FIN or not respond to keep-alives, etc.
1534 * We can let the user exit from the close as soon as the FIN is acked.
1535 */
1536static void
1537tcp_usrclosed(struct tcpcb *tp)
1538{
1539
1540	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1541	INP_LOCK_ASSERT(tp->t_inpcb);
1542
1543	switch (tp->t_state) {
1544
1545	case TCPS_CLOSED:
1546	case TCPS_LISTEN:
1547		tp->t_state = TCPS_CLOSED;
1548		tp = tcp_close(tp);
1549		/*
1550		 * tcp_close() should never return NULL here as the socket is
1551		 * still open.
1552		 */
1553		KASSERT(tp != NULL,
1554		    ("tcp_usrclosed: tcp_close() returned NULL"));
1555		break;
1556
1557	case TCPS_SYN_SENT:
1558	case TCPS_SYN_RECEIVED:
1559		tp->t_flags |= TF_NEEDFIN;
1560		break;
1561
1562	case TCPS_ESTABLISHED:
1563		tp->t_state = TCPS_FIN_WAIT_1;
1564		break;
1565
1566	case TCPS_CLOSE_WAIT:
1567		tp->t_state = TCPS_LAST_ACK;
1568		break;
1569	}
1570	if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
1571		soisdisconnected(tp->t_inpcb->inp_socket);
1572		/* To prevent the connection hanging in FIN_WAIT_2 forever. */
1573		if (tp->t_state == TCPS_FIN_WAIT_2) {
1574			int timeout;
1575
1576			timeout = (tcp_fast_finwait2_recycle) ?
1577				tcp_finwait2_timeout : tcp_maxidle;
1578			tcp_timer_activate(tp, TT_2MSL, timeout);
1579		}
1580	}
1581}
1582
1583#ifdef DDB
1584static void
1585db_print_indent(int indent)
1586{
1587	int i;
1588
1589	for (i = 0; i < indent; i++)
1590		db_printf(" ");
1591}
1592
1593static void
1594db_print_tstate(int t_state)
1595{
1596
1597	switch (t_state) {
1598	case TCPS_CLOSED:
1599		db_printf("TCPS_CLOSED");
1600		return;
1601
1602	case TCPS_LISTEN:
1603		db_printf("TCPS_LISTEN");
1604		return;
1605
1606	case TCPS_SYN_SENT:
1607		db_printf("TCPS_SYN_SENT");
1608		return;
1609
1610	case TCPS_SYN_RECEIVED:
1611		db_printf("TCPS_SYN_RECEIVED");
1612		return;
1613
1614	case TCPS_ESTABLISHED:
1615		db_printf("TCPS_ESTABLISHED");
1616		return;
1617
1618	case TCPS_CLOSE_WAIT:
1619		db_printf("TCPS_CLOSE_WAIT");
1620		return;
1621
1622	case TCPS_FIN_WAIT_1:
1623		db_printf("TCPS_FIN_WAIT_1");
1624		return;
1625
1626	case TCPS_CLOSING:
1627		db_printf("TCPS_CLOSING");
1628		return;
1629
1630	case TCPS_LAST_ACK:
1631		db_printf("TCPS_LAST_ACK");
1632		return;
1633
1634	case TCPS_FIN_WAIT_2:
1635		db_printf("TCPS_FIN_WAIT_2");
1636		return;
1637
1638	case TCPS_TIME_WAIT:
1639		db_printf("TCPS_TIME_WAIT");
1640		return;
1641
1642	default:
1643		db_printf("unknown");
1644		return;
1645	}
1646}
1647
1648static void
1649db_print_tflags(u_int t_flags)
1650{
1651	int comma;
1652
1653	comma = 0;
1654	if (t_flags & TF_ACKNOW) {
1655		db_printf("%sTF_ACKNOW", comma ? ", " : "");
1656		comma = 1;
1657	}
1658	if (t_flags & TF_DELACK) {
1659		db_printf("%sTF_DELACK", comma ? ", " : "");
1660		comma = 1;
1661	}
1662	if (t_flags & TF_NODELAY) {
1663		db_printf("%sTF_NODELAY", comma ? ", " : "");
1664		comma = 1;
1665	}
1666	if (t_flags & TF_NOOPT) {
1667		db_printf("%sTF_NOOPT", comma ? ", " : "");
1668		comma = 1;
1669	}
1670	if (t_flags & TF_SENTFIN) {
1671		db_printf("%sTF_SENTFIN", comma ? ", " : "");
1672		comma = 1;
1673	}
1674	if (t_flags & TF_REQ_SCALE) {
1675		db_printf("%sTF_REQ_SCALE", comma ? ", " : "");
1676		comma = 1;
1677	}
1678	if (t_flags & TF_RCVD_SCALE) {
1679		db_printf("%sTF_RECVD_SCALE", comma ? ", " : "");
1680		comma = 1;
1681	}
1682	if (t_flags & TF_REQ_TSTMP) {
1683		db_printf("%sTF_REQ_TSTMP", comma ? ", " : "");
1684		comma = 1;
1685	}
1686	if (t_flags & TF_RCVD_TSTMP) {
1687		db_printf("%sTF_RCVD_TSTMP", comma ? ", " : "");
1688		comma = 1;
1689	}
1690	if (t_flags & TF_SACK_PERMIT) {
1691		db_printf("%sTF_SACK_PERMIT", comma ? ", " : "");
1692		comma = 1;
1693	}
1694	if (t_flags & TF_NEEDSYN) {
1695		db_printf("%sTF_NEEDSYN", comma ? ", " : "");
1696		comma = 1;
1697	}
1698	if (t_flags & TF_NEEDFIN) {
1699		db_printf("%sTF_NEEDFIN", comma ? ", " : "");
1700		comma = 1;
1701	}
1702	if (t_flags & TF_NOPUSH) {
1703		db_printf("%sTF_NOPUSH", comma ? ", " : "");
1704		comma = 1;
1705	}
1706	if (t_flags & TF_NOPUSH) {
1707		db_printf("%sTF_NOPUSH", comma ? ", " : "");
1708		comma = 1;
1709	}
1710	if (t_flags & TF_MORETOCOME) {
1711		db_printf("%sTF_MORETOCOME", comma ? ", " : "");
1712		comma = 1;
1713	}
1714	if (t_flags & TF_LQ_OVERFLOW) {
1715		db_printf("%sTF_LQ_OVERFLOW", comma ? ", " : "");
1716		comma = 1;
1717	}
1718	if (t_flags & TF_LASTIDLE) {
1719		db_printf("%sTF_LASTIDLE", comma ? ", " : "");
1720		comma = 1;
1721	}
1722	if (t_flags & TF_RXWIN0SENT) {
1723		db_printf("%sTF_RXWIN0SENT", comma ? ", " : "");
1724		comma = 1;
1725	}
1726	if (t_flags & TF_FASTRECOVERY) {
1727		db_printf("%sTF_FASTRECOVERY", comma ? ", " : "");
1728		comma = 1;
1729	}
1730	if (t_flags & TF_WASFRECOVERY) {
1731		db_printf("%sTF_WASFRECOVERY", comma ? ", " : "");
1732		comma = 1;
1733	}
1734	if (t_flags & TF_SIGNATURE) {
1735		db_printf("%sTF_SIGNATURE", comma ? ", " : "");
1736		comma = 1;
1737	}
1738	if (t_flags & TF_FORCEDATA) {
1739		db_printf("%sTF_FORCEDATA", comma ? ", " : "");
1740		comma = 1;
1741	}
1742	if (t_flags & TF_TSO) {
1743		db_printf("%sTF_TSO", comma ? ", " : "");
1744		comma = 1;
1745	}
1746}
1747
1748static void
1749db_print_toobflags(char t_oobflags)
1750{
1751	int comma;
1752
1753	comma = 0;
1754	if (t_oobflags & TCPOOB_HAVEDATA) {
1755		db_printf("%sTCPOOB_HAVEDATA", comma ? ", " : "");
1756		comma = 1;
1757	}
1758	if (t_oobflags & TCPOOB_HADDATA) {
1759		db_printf("%sTCPOOB_HADDATA", comma ? ", " : "");
1760		comma = 1;
1761	}
1762}
1763
1764static void
1765db_print_tcpcb(struct tcpcb *tp, const char *name, int indent)
1766{
1767
1768	db_print_indent(indent);
1769	db_printf("%s at %p\n", name, tp);
1770
1771	indent += 2;
1772
1773	db_print_indent(indent);
1774	db_printf("t_segq first: %p   t_segqlen: %d   t_dupacks: %d\n",
1775	   LIST_FIRST(&tp->t_segq), tp->t_segqlen, tp->t_dupacks);
1776
1777	db_print_indent(indent);
1778	db_printf("t_inpcb: %p   t_timers: %p   tt_active: %x\n",
1779	    tp->t_inpcb, tp->t_timers, tp->t_timers->tt_active);
1780
1781	db_print_indent(indent);
1782	db_printf("tt_delack: %i   tt_rexmt: %i   tt_keep: %i   "
1783	    "tt_persist: %i   tt_2msl: %i\n",
1784	    tp->t_timers->tt_delack, tp->t_timers->tt_rexmt,
1785	    tp->t_timers->tt_keep, tp->t_timers->tt_persist,
1786	    tp->t_timers->tt_2msl);
1787
1788	db_print_indent(indent);
1789	db_printf("t_state: %d (", tp->t_state);
1790	db_print_tstate(tp->t_state);
1791	db_printf(")\n");
1792
1793	db_print_indent(indent);
1794	db_printf("t_flags: 0x%x (", tp->t_flags);
1795	db_print_tflags(tp->t_flags);
1796	db_printf(")\n");
1797
1798	db_print_indent(indent);
1799	db_printf("snd_una: 0x%08x   snd_max: 0x%08x   snd_nxt: x0%08x\n",
1800	    tp->snd_una, tp->snd_max, tp->snd_nxt);
1801
1802	db_print_indent(indent);
1803	db_printf("snd_up: 0x%08x   snd_wl1: 0x%08x   snd_wl2: 0x%08x\n",
1804	   tp->snd_up, tp->snd_wl1, tp->snd_wl2);
1805
1806	db_print_indent(indent);
1807	db_printf("iss: 0x%08x   irs: 0x%08x   rcv_nxt: 0x%08x\n",
1808	    tp->iss, tp->irs, tp->rcv_nxt);
1809
1810	db_print_indent(indent);
1811	db_printf("rcv_adv: 0x%08x   rcv_wnd: %lu   rcv_up: 0x%08x\n",
1812	    tp->rcv_adv, tp->rcv_wnd, tp->rcv_up);
1813
1814	db_print_indent(indent);
1815	db_printf("snd_wnd: %lu   snd_cwnd: %lu   snd_bwnd: %lu\n",
1816	   tp->snd_wnd, tp->snd_cwnd, tp->snd_bwnd);
1817
1818	db_print_indent(indent);
1819	db_printf("snd_ssthresh: %lu   snd_bandwidth: %lu   snd_recover: "
1820	    "0x%08x\n", tp->snd_ssthresh, tp->snd_bandwidth,
1821	    tp->snd_recover);
1822
1823	db_print_indent(indent);
1824	db_printf("t_maxopd: %u   t_rcvtime: %lu   t_startime: %lu\n",
1825	    tp->t_maxopd, tp->t_rcvtime, tp->t_starttime);
1826
1827	db_print_indent(indent);
1828	db_printf("t_rttime: %d   t_rtsq: 0x%08x   t_bw_rtttime: %d\n",
1829	    tp->t_rtttime, tp->t_rtseq, tp->t_bw_rtttime);
1830
1831	db_print_indent(indent);
1832	db_printf("t_bw_rtseq: 0x%08x   t_rxtcur: %d   t_maxseg: %u   "
1833	    "t_srtt: %d\n", tp->t_bw_rtseq, tp->t_rxtcur, tp->t_maxseg,
1834	    tp->t_srtt);
1835
1836	db_print_indent(indent);
1837	db_printf("t_rttvar: %d   t_rxtshift: %d   t_rttmin: %u   "
1838	    "t_rttbest: %u\n", tp->t_rttvar, tp->t_rxtshift, tp->t_rttmin,
1839	    tp->t_rttbest);
1840
1841	db_print_indent(indent);
1842	db_printf("t_rttupdated: %lu   max_sndwnd: %lu   t_softerror: %d\n",
1843	    tp->t_rttupdated, tp->max_sndwnd, tp->t_softerror);
1844
1845	db_print_indent(indent);
1846	db_printf("t_oobflags: 0x%x (", tp->t_oobflags);
1847	db_print_toobflags(tp->t_oobflags);
1848	db_printf(")   t_iobc: 0x%02x\n", tp->t_iobc);
1849
1850	db_print_indent(indent);
1851	db_printf("snd_scale: %u   rcv_scale: %u   request_r_scale: %u\n",
1852	    tp->snd_scale, tp->rcv_scale, tp->request_r_scale);
1853
1854	db_print_indent(indent);
1855	db_printf("ts_recent: %u   ts_recent_age: %lu\n",
1856	    tp->ts_recent, tp->ts_recent_age);
1857
1858	db_print_indent(indent);
1859	db_printf("ts_offset: %u   last_ack_sent: 0x%08x   snd_cwnd_prev: "
1860	    "%lu\n", tp->ts_offset, tp->last_ack_sent, tp->snd_cwnd_prev);
1861
1862	db_print_indent(indent);
1863	db_printf("snd_ssthresh_prev: %lu   snd_recover_prev: 0x%08x   "
1864	    "t_badrxtwin: %lu\n", tp->snd_ssthresh_prev,
1865	    tp->snd_recover_prev, tp->t_badrxtwin);
1866
1867	db_print_indent(indent);
1868	db_printf("snd_numholes: %d  snd_holes first: %p\n",
1869	    tp->snd_numholes, TAILQ_FIRST(&tp->snd_holes));
1870
1871	db_print_indent(indent);
1872	db_printf("snd_fack: 0x%08x   rcv_numsacks: %d   sack_newdata: "
1873	    "0x%08x\n", tp->snd_fack, tp->rcv_numsacks, tp->sack_newdata);
1874
1875	/* Skip sackblks, sackhint. */
1876
1877	db_print_indent(indent);
1878	db_printf("t_rttlow: %d   rfbuf_ts: %u   rfbuf_cnt: %d\n",
1879	    tp->t_rttlow, tp->rfbuf_ts, tp->rfbuf_cnt);
1880}
1881
1882DB_SHOW_COMMAND(tcpcb, db_show_tcpcb)
1883{
1884	struct tcpcb *tp;
1885
1886	if (!have_addr) {
1887		db_printf("usage: show tcpcb <addr>\n");
1888		return;
1889	}
1890	tp = (struct tcpcb *)addr;
1891
1892	db_print_tcpcb(tp, "tcpcb", 0);
1893}
1894#endif
1895