tcp_input.c revision 128019
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
30 * $FreeBSD: head/sys/netinet/tcp_input.c 128019 2004-04-07 20:46:16Z imp $
31 */
32
33#include "opt_ipfw.h"		/* for ipfw_fwd		*/
34#include "opt_inet.h"
35#include "opt_inet6.h"
36#include "opt_ipsec.h"
37#include "opt_mac.h"
38#include "opt_tcpdebug.h"
39#include "opt_tcp_input.h"
40
41#include <sys/param.h>
42#include <sys/kernel.h>
43#include <sys/mac.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/proc.h>		/* for proc0 declaration */
47#include <sys/protosw.h>
48#include <sys/signalvar.h>
49#include <sys/socket.h>
50#include <sys/socketvar.h>
51#include <sys/sysctl.h>
52#include <sys/syslog.h>
53#include <sys/systm.h>
54
55#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
56
57#include <vm/uma.h>
58
59#include <net/if.h>
60#include <net/route.h>
61
62#include <netinet/in.h>
63#include <netinet/in_pcb.h>
64#include <netinet/in_systm.h>
65#include <netinet/in_var.h>
66#include <netinet/ip.h>
67#include <netinet/ip_icmp.h>	/* for ICMP_BANDLIM		*/
68#include <netinet/icmp_var.h>	/* for ICMP_BANDLIM		*/
69#include <netinet/ip_var.h>
70#include <netinet/ip6.h>
71#include <netinet/icmp6.h>
72#include <netinet6/in6_pcb.h>
73#include <netinet6/ip6_var.h>
74#include <netinet6/nd6.h>
75#include <netinet/tcp.h>
76#include <netinet/tcp_fsm.h>
77#include <netinet/tcp_seq.h>
78#include <netinet/tcp_timer.h>
79#include <netinet/tcp_var.h>
80#include <netinet6/tcp6_var.h>
81#include <netinet/tcpip.h>
82#ifdef TCPDEBUG
83#include <netinet/tcp_debug.h>
84#endif /* TCPDEBUG */
85
86#ifdef FAST_IPSEC
87#include <netipsec/ipsec.h>
88#include <netipsec/ipsec6.h>
89#endif /*FAST_IPSEC*/
90
91#ifdef IPSEC
92#include <netinet6/ipsec.h>
93#include <netinet6/ipsec6.h>
94#include <netkey/key.h>
95#endif /*IPSEC*/
96
97#include <machine/in_cksum.h>
98
99static const int tcprexmtthresh = 3;
100tcp_cc	tcp_ccgen;
101
102struct	tcpstat tcpstat;
103SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
104    &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
105
106static int log_in_vain = 0;
107SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
108    &log_in_vain, 0, "Log all incoming TCP connections");
109
110static int blackhole = 0;
111SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
112	&blackhole, 0, "Do not send RST when dropping refused connections");
113
114int tcp_delack_enabled = 1;
115SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
116    &tcp_delack_enabled, 0,
117    "Delay ACK to try and piggyback it onto a data packet");
118
119#ifdef TCP_DROP_SYNFIN
120static int drop_synfin = 0;
121SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
122    &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
123#endif
124
125static int tcp_do_rfc3042 = 1;
126SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
127    &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
128
129static int tcp_do_rfc3390 = 1;
130SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
131    &tcp_do_rfc3390, 0,
132    "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
133
134SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
135	    "TCP Segment Reassembly Queue");
136
137static int tcp_reass_maxseg = 0;
138SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
139	   &tcp_reass_maxseg, 0,
140	   "Global maximum number of TCP Segments in Reassembly Queue");
141
142int tcp_reass_qsize = 0;
143SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
144	   &tcp_reass_qsize, 0,
145	   "Global number of TCP Segments currently in Reassembly Queue");
146
147static int tcp_reass_maxqlen = 48;
148SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
149	   &tcp_reass_maxqlen, 0,
150	   "Maximum number of TCP Segments per individual Reassembly Queue");
151
152static int tcp_reass_overflows = 0;
153SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
154	   &tcp_reass_overflows, 0,
155	   "Global number of TCP Segment Reassembly Queue Overflows");
156
157struct inpcbhead tcb;
158#define	tcb6	tcb  /* for KAME src sync over BSD*'s */
159struct inpcbinfo tcbinfo;
160struct mtx	*tcbinfo_mtx;
161
162static void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
163static void	 tcp_pulloutofband(struct socket *,
164		     struct tcphdr *, struct mbuf *, int);
165static int	 tcp_reass(struct tcpcb *, struct tcphdr *, int *,
166		     struct mbuf *);
167static void	 tcp_xmit_timer(struct tcpcb *, int);
168static void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
169static int	 tcp_timewait(struct tcptw *, struct tcpopt *,
170		     struct tcphdr *, struct mbuf *, int);
171
172/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
173#ifdef INET6
174#define ND6_HINT(tp) \
175do { \
176	if ((tp) && (tp)->t_inpcb && \
177	    ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
178		nd6_nud_hint(NULL, NULL, 0); \
179} while (0)
180#else
181#define ND6_HINT(tp)
182#endif
183
184/*
185 * Indicate whether this ack should be delayed.  We can delay the ack if
186 *	- there is no delayed ack timer in progress and
187 *	- our last ack wasn't a 0-sized window.  We never want to delay
188 *	  the ack that opens up a 0-sized window and
189 *		- delayed acks are enabled or
190 *		- this is a half-synchronized T/TCP connection.
191 */
192#define DELAY_ACK(tp)							\
193	((!callout_active(tp->tt_delack) &&				\
194	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
195	    (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
196
197/* Initialize TCP reassembly queue */
198uma_zone_t	tcp_reass_zone;
199void
200tcp_reass_init()
201{
202	tcp_reass_maxseg = nmbclusters / 16;
203	TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
204	    &tcp_reass_maxseg);
205	tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
206	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
207	uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
208}
209
210static int
211tcp_reass(tp, th, tlenp, m)
212	register struct tcpcb *tp;
213	register struct tcphdr *th;
214	int *tlenp;
215	struct mbuf *m;
216{
217	struct tseg_qent *q;
218	struct tseg_qent *p = NULL;
219	struct tseg_qent *nq;
220	struct tseg_qent *te = NULL;
221	struct socket *so = tp->t_inpcb->inp_socket;
222	int flags;
223
224	/*
225	 * XXX: tcp_reass() is rather inefficient with its data structures
226	 * and should be rewritten (see NetBSD for optimizations).  While
227	 * doing that it should move to its own file tcp_reass.c.
228	 */
229
230	/*
231	 * Call with th==0 after become established to
232	 * force pre-ESTABLISHED data up to user socket.
233	 */
234	if (th == 0)
235		goto present;
236
237	/*
238	 * Limit the number of segments in the reassembly queue to prevent
239	 * holding on to too many segments (and thus running out of mbufs).
240	 * Make sure to let the missing segment through which caused this
241	 * queue.  Always keep one global queue entry spare to be able to
242	 * process the missing segment.
243	 */
244	if (th->th_seq != tp->rcv_nxt &&
245	    (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
246	     tp->t_segqlen >= tcp_reass_maxqlen)) {
247		tcp_reass_overflows++;
248		tcpstat.tcps_rcvmemdrop++;
249		m_freem(m);
250		return (0);
251	}
252
253	/*
254	 * Allocate a new queue entry. If we can't, or hit the zone limit
255	 * just drop the pkt.
256	 */
257	te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
258	if (te == NULL) {
259		tcpstat.tcps_rcvmemdrop++;
260		m_freem(m);
261		return (0);
262	}
263	tp->t_segqlen++;
264	tcp_reass_qsize++;
265
266	/*
267	 * Find a segment which begins after this one does.
268	 */
269	LIST_FOREACH(q, &tp->t_segq, tqe_q) {
270		if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
271			break;
272		p = q;
273	}
274
275	/*
276	 * If there is a preceding segment, it may provide some of
277	 * our data already.  If so, drop the data from the incoming
278	 * segment.  If it provides all of our data, drop us.
279	 */
280	if (p != NULL) {
281		register int i;
282		/* conversion to int (in i) handles seq wraparound */
283		i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
284		if (i > 0) {
285			if (i >= *tlenp) {
286				tcpstat.tcps_rcvduppack++;
287				tcpstat.tcps_rcvdupbyte += *tlenp;
288				m_freem(m);
289				uma_zfree(tcp_reass_zone, te);
290				tp->t_segqlen--;
291				tcp_reass_qsize--;
292				/*
293				 * Try to present any queued data
294				 * at the left window edge to the user.
295				 * This is needed after the 3-WHS
296				 * completes.
297				 */
298				goto present;	/* ??? */
299			}
300			m_adj(m, i);
301			*tlenp -= i;
302			th->th_seq += i;
303		}
304	}
305	tcpstat.tcps_rcvoopack++;
306	tcpstat.tcps_rcvoobyte += *tlenp;
307
308	/*
309	 * While we overlap succeeding segments trim them or,
310	 * if they are completely covered, dequeue them.
311	 */
312	while (q) {
313		register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
314		if (i <= 0)
315			break;
316		if (i < q->tqe_len) {
317			q->tqe_th->th_seq += i;
318			q->tqe_len -= i;
319			m_adj(q->tqe_m, i);
320			break;
321		}
322
323		nq = LIST_NEXT(q, tqe_q);
324		LIST_REMOVE(q, tqe_q);
325		m_freem(q->tqe_m);
326		uma_zfree(tcp_reass_zone, q);
327		tp->t_segqlen--;
328		tcp_reass_qsize--;
329		q = nq;
330	}
331
332	/* Insert the new segment queue entry into place. */
333	te->tqe_m = m;
334	te->tqe_th = th;
335	te->tqe_len = *tlenp;
336
337	if (p == NULL) {
338		LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
339	} else {
340		LIST_INSERT_AFTER(p, te, tqe_q);
341	}
342
343present:
344	/*
345	 * Present data to user, advancing rcv_nxt through
346	 * completed sequence space.
347	 */
348	if (!TCPS_HAVEESTABLISHED(tp->t_state))
349		return (0);
350	q = LIST_FIRST(&tp->t_segq);
351	if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
352		return (0);
353	do {
354		tp->rcv_nxt += q->tqe_len;
355		flags = q->tqe_th->th_flags & TH_FIN;
356		nq = LIST_NEXT(q, tqe_q);
357		LIST_REMOVE(q, tqe_q);
358		if (so->so_state & SS_CANTRCVMORE)
359			m_freem(q->tqe_m);
360		else
361			sbappendstream(&so->so_rcv, q->tqe_m);
362		uma_zfree(tcp_reass_zone, q);
363		tp->t_segqlen--;
364		tcp_reass_qsize--;
365		q = nq;
366	} while (q && q->tqe_th->th_seq == tp->rcv_nxt);
367	ND6_HINT(tp);
368	sorwakeup(so);
369	return (flags);
370}
371
372/*
373 * TCP input routine, follows pages 65-76 of the
374 * protocol specification dated September, 1981 very closely.
375 */
376#ifdef INET6
377int
378tcp6_input(mp, offp, proto)
379	struct mbuf **mp;
380	int *offp, proto;
381{
382	register struct mbuf *m = *mp;
383	struct in6_ifaddr *ia6;
384
385	IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
386
387	/*
388	 * draft-itojun-ipv6-tcp-to-anycast
389	 * better place to put this in?
390	 */
391	ia6 = ip6_getdstifaddr(m);
392	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
393		struct ip6_hdr *ip6;
394
395		ip6 = mtod(m, struct ip6_hdr *);
396		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
397			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
398		return IPPROTO_DONE;
399	}
400
401	tcp_input(m, *offp);
402	return IPPROTO_DONE;
403}
404#endif
405
406void
407tcp_input(m, off0)
408	register struct mbuf *m;
409	int off0;
410{
411	register struct tcphdr *th;
412	register struct ip *ip = NULL;
413	register struct ipovly *ipov;
414	register struct inpcb *inp = NULL;
415	u_char *optp = NULL;
416	int optlen = 0;
417	int len, tlen, off;
418	int drop_hdrlen;
419	register struct tcpcb *tp = 0;
420	register int thflags;
421	struct socket *so = 0;
422	int todrop, acked, ourfinisacked, needoutput = 0;
423	u_long tiwin;
424	struct tcpopt to;		/* options in this segment */
425	struct rmxp_tao tao;		/* our TAO cache entry */
426	int headlocked = 0;
427	struct sockaddr_in *next_hop = NULL;
428	int rstreason; /* For badport_bandlim accounting purposes */
429
430	struct ip6_hdr *ip6 = NULL;
431#ifdef INET6
432	int isipv6;
433#else
434	const int isipv6 = 0;
435#endif
436
437#ifdef TCPDEBUG
438	/*
439	 * The size of tcp_saveipgen must be the size of the max ip header,
440	 * now IPv6.
441	 */
442	u_char tcp_saveipgen[40];
443	struct tcphdr tcp_savetcp;
444	short ostate = 0;
445#endif
446
447	/* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
448	next_hop = ip_claim_next_hop(m);
449#ifdef INET6
450	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
451#endif
452	bzero(&tao, sizeof(tao));
453	bzero((char *)&to, sizeof(to));
454
455	tcpstat.tcps_rcvtotal++;
456
457	if (isipv6) {
458#ifdef INET6
459		/* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
460		ip6 = mtod(m, struct ip6_hdr *);
461		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
462		if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
463			tcpstat.tcps_rcvbadsum++;
464			goto drop;
465		}
466		th = (struct tcphdr *)((caddr_t)ip6 + off0);
467
468		/*
469		 * Be proactive about unspecified IPv6 address in source.
470		 * As we use all-zero to indicate unbounded/unconnected pcb,
471		 * unspecified IPv6 address can be used to confuse us.
472		 *
473		 * Note that packets with unspecified IPv6 destination is
474		 * already dropped in ip6_input.
475		 */
476		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
477			/* XXX stat */
478			goto drop;
479		}
480#else
481		th = NULL;		/* XXX: avoid compiler warning */
482#endif
483	} else {
484		/*
485		 * Get IP and TCP header together in first mbuf.
486		 * Note: IP leaves IP header in first mbuf.
487		 */
488		if (off0 > sizeof (struct ip)) {
489			ip_stripoptions(m, (struct mbuf *)0);
490			off0 = sizeof(struct ip);
491		}
492		if (m->m_len < sizeof (struct tcpiphdr)) {
493			if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
494				tcpstat.tcps_rcvshort++;
495				return;
496			}
497		}
498		ip = mtod(m, struct ip *);
499		ipov = (struct ipovly *)ip;
500		th = (struct tcphdr *)((caddr_t)ip + off0);
501		tlen = ip->ip_len;
502
503		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
504			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
505				th->th_sum = m->m_pkthdr.csum_data;
506			else
507				th->th_sum = in_pseudo(ip->ip_src.s_addr,
508						ip->ip_dst.s_addr,
509						htonl(m->m_pkthdr.csum_data +
510							ip->ip_len +
511							IPPROTO_TCP));
512			th->th_sum ^= 0xffff;
513#ifdef TCPDEBUG
514			ipov->ih_len = (u_short)tlen;
515			ipov->ih_len = htons(ipov->ih_len);
516#endif
517		} else {
518			/*
519			 * Checksum extended TCP header and data.
520			 */
521			len = sizeof (struct ip) + tlen;
522			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
523			ipov->ih_len = (u_short)tlen;
524			ipov->ih_len = htons(ipov->ih_len);
525			th->th_sum = in_cksum(m, len);
526		}
527		if (th->th_sum) {
528			tcpstat.tcps_rcvbadsum++;
529			goto drop;
530		}
531#ifdef INET6
532		/* Re-initialization for later version check */
533		ip->ip_v = IPVERSION;
534#endif
535	}
536
537	/*
538	 * Check that TCP offset makes sense,
539	 * pull out TCP options and adjust length.		XXX
540	 */
541	off = th->th_off << 2;
542	if (off < sizeof (struct tcphdr) || off > tlen) {
543		tcpstat.tcps_rcvbadoff++;
544		goto drop;
545	}
546	tlen -= off;	/* tlen is used instead of ti->ti_len */
547	if (off > sizeof (struct tcphdr)) {
548		if (isipv6) {
549#ifdef INET6
550			IP6_EXTHDR_CHECK(m, off0, off, );
551			ip6 = mtod(m, struct ip6_hdr *);
552			th = (struct tcphdr *)((caddr_t)ip6 + off0);
553#endif
554		} else {
555			if (m->m_len < sizeof(struct ip) + off) {
556				if ((m = m_pullup(m, sizeof (struct ip) + off))
557						== 0) {
558					tcpstat.tcps_rcvshort++;
559					return;
560				}
561				ip = mtod(m, struct ip *);
562				ipov = (struct ipovly *)ip;
563				th = (struct tcphdr *)((caddr_t)ip + off0);
564			}
565		}
566		optlen = off - sizeof (struct tcphdr);
567		optp = (u_char *)(th + 1);
568	}
569	thflags = th->th_flags;
570
571#ifdef TCP_DROP_SYNFIN
572	/*
573	 * If the drop_synfin option is enabled, drop all packets with
574	 * both the SYN and FIN bits set. This prevents e.g. nmap from
575	 * identifying the TCP/IP stack.
576	 *
577	 * This is a violation of the TCP specification.
578	 */
579	if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
580		goto drop;
581#endif
582
583	/*
584	 * Convert TCP protocol specific fields to host format.
585	 */
586	th->th_seq = ntohl(th->th_seq);
587	th->th_ack = ntohl(th->th_ack);
588	th->th_win = ntohs(th->th_win);
589	th->th_urp = ntohs(th->th_urp);
590
591	/*
592	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
593	 * until after ip6_savecontrol() is called and before other functions
594	 * which don't want those proto headers.
595	 * Because ip6_savecontrol() is going to parse the mbuf to
596	 * search for data to be passed up to user-land, it wants mbuf
597	 * parameters to be unchanged.
598	 * XXX: the call of ip6_savecontrol() has been obsoleted based on
599	 * latest version of the advanced API (20020110).
600	 */
601	drop_hdrlen = off0 + off;
602
603	/*
604	 * Locate pcb for segment.
605	 */
606	INP_INFO_WLOCK(&tcbinfo);
607	headlocked = 1;
608findpcb:
609	/* IPFIREWALL_FORWARD section */
610	if (next_hop != NULL && isipv6 == 0) {	/* IPv6 support is not yet */
611		/*
612		 * Transparently forwarded. Pretend to be the destination.
613		 * already got one like this?
614		 */
615		inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
616					ip->ip_dst, th->th_dport,
617					0, m->m_pkthdr.rcvif);
618		if (!inp) {
619			/* It's new.  Try find the ambushing socket. */
620			inp = in_pcblookup_hash(&tcbinfo,
621						ip->ip_src, th->th_sport,
622						next_hop->sin_addr,
623						next_hop->sin_port ?
624						    ntohs(next_hop->sin_port) :
625						    th->th_dport,
626						1, m->m_pkthdr.rcvif);
627		}
628	} else {
629		if (isipv6) {
630#ifdef INET6
631			inp = in6_pcblookup_hash(&tcbinfo,
632						 &ip6->ip6_src, th->th_sport,
633						 &ip6->ip6_dst, th->th_dport,
634						 1, m->m_pkthdr.rcvif);
635#endif
636		} else
637			inp = in_pcblookup_hash(&tcbinfo,
638						ip->ip_src, th->th_sport,
639						ip->ip_dst, th->th_dport,
640						1, m->m_pkthdr.rcvif);
641      }
642
643#if defined(IPSEC) || defined(FAST_IPSEC)
644	if (isipv6) {
645		if (inp != NULL && ipsec6_in_reject(m, inp)) {
646#ifdef IPSEC
647			ipsec6stat.in_polvio++;
648#endif /*IPSEC*/
649			goto drop;
650		}
651	} else  if (inp != NULL && ipsec4_in_reject(m, inp)) {
652#ifdef IPSEC
653		ipsecstat.in_polvio++;
654#endif /*IPSEC*/
655		goto drop;
656	}
657#endif /*IPSEC || FAST_IPSEC*/
658
659	/*
660	 * If the state is CLOSED (i.e., TCB does not exist) then
661	 * all data in the incoming segment is discarded.
662	 * If the TCB exists but is in CLOSED state, it is embryonic,
663	 * but should either do a listen or a connect soon.
664	 */
665	if (inp == NULL) {
666		if (log_in_vain) {
667#ifdef INET6
668			char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
669#else
670			char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
671#endif
672
673			if (isipv6) {
674#ifdef INET6
675				strcpy(dbuf, "[");
676				strcpy(sbuf, "[");
677				strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
678				strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
679				strcat(dbuf, "]");
680				strcat(sbuf, "]");
681#endif
682			} else {
683				strcpy(dbuf, inet_ntoa(ip->ip_dst));
684				strcpy(sbuf, inet_ntoa(ip->ip_src));
685			}
686			switch (log_in_vain) {
687			case 1:
688				if ((thflags & TH_SYN) == 0)
689					break;
690				/* FALLTHROUGH */
691			case 2:
692				log(LOG_INFO,
693				    "Connection attempt to TCP %s:%d "
694				    "from %s:%d flags:0x%02x\n",
695				    dbuf, ntohs(th->th_dport), sbuf,
696				    ntohs(th->th_sport), thflags);
697				break;
698			default:
699				break;
700			}
701		}
702		if (blackhole) {
703			switch (blackhole) {
704			case 1:
705				if (thflags & TH_SYN)
706					goto drop;
707				break;
708			case 2:
709				goto drop;
710			default:
711				goto drop;
712			}
713		}
714		rstreason = BANDLIM_RST_CLOSEDPORT;
715		goto dropwithreset;
716	}
717	INP_LOCK(inp);
718	if (inp->inp_vflag & INP_TIMEWAIT) {
719		/*
720		 * The only option of relevance is TOF_CC, and only if
721		 * present in a SYN segment.  See tcp_timewait().
722		 */
723		if (thflags & TH_SYN)
724			tcp_dooptions(&to, optp, optlen, 1);
725		if (tcp_timewait((struct tcptw *)inp->inp_ppcb,
726		    &to, th, m, tlen))
727			goto findpcb;
728		/*
729		 * tcp_timewait unlocks inp.
730		 */
731		INP_INFO_WUNLOCK(&tcbinfo);
732		return;
733	}
734	tp = intotcpcb(inp);
735	if (tp == 0) {
736		INP_UNLOCK(inp);
737		rstreason = BANDLIM_RST_CLOSEDPORT;
738		goto dropwithreset;
739	}
740	if (tp->t_state == TCPS_CLOSED)
741		goto drop;
742
743	/* Unscale the window into a 32-bit value. */
744	if ((thflags & TH_SYN) == 0)
745		tiwin = th->th_win << tp->snd_scale;
746	else
747		tiwin = th->th_win;
748
749#ifdef MAC
750	if (mac_check_inpcb_deliver(inp, m))
751		goto drop;
752#endif
753	so = inp->inp_socket;
754#ifdef TCPDEBUG
755	if (so->so_options & SO_DEBUG) {
756		ostate = tp->t_state;
757		if (isipv6)
758			bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
759		else
760			bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
761		tcp_savetcp = *th;
762	}
763#endif
764	if (so->so_options & SO_ACCEPTCONN) {
765		struct in_conninfo inc;
766
767#ifdef INET6
768		inc.inc_isipv6 = isipv6;
769#endif
770		if (isipv6) {
771			inc.inc6_faddr = ip6->ip6_src;
772			inc.inc6_laddr = ip6->ip6_dst;
773		} else {
774			inc.inc_faddr = ip->ip_src;
775			inc.inc_laddr = ip->ip_dst;
776		}
777		inc.inc_fport = th->th_sport;
778		inc.inc_lport = th->th_dport;
779
780	        /*
781	         * If the state is LISTEN then ignore segment if it contains
782		 * a RST.  If the segment contains an ACK then it is bad and
783		 * send a RST.  If it does not contain a SYN then it is not
784		 * interesting; drop it.
785		 *
786		 * If the state is SYN_RECEIVED (syncache) and seg contains
787		 * an ACK, but not for our SYN/ACK, send a RST.  If the seg
788		 * contains a RST, check the sequence number to see if it
789		 * is a valid reset segment.
790		 */
791		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
792			if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
793				if (!syncache_expand(&inc, th, &so, m)) {
794					/*
795					 * No syncache entry, or ACK was not
796					 * for our SYN/ACK.  Send a RST.
797					 */
798					tcpstat.tcps_badsyn++;
799					rstreason = BANDLIM_RST_OPENPORT;
800					goto dropwithreset;
801				}
802				if (so == NULL) {
803					/*
804					 * Could not complete 3-way handshake,
805					 * connection is being closed down, and
806					 * syncache will free mbuf.
807					 */
808					INP_UNLOCK(inp);
809					INP_INFO_WUNLOCK(&tcbinfo);
810					return;
811				}
812				/*
813				 * Socket is created in state SYN_RECEIVED.
814				 * Continue processing segment.
815				 */
816				INP_UNLOCK(inp);
817				inp = sotoinpcb(so);
818				INP_LOCK(inp);
819				tp = intotcpcb(inp);
820				/*
821				 * This is what would have happened in
822				 * tcp_output() when the SYN,ACK was sent.
823				 */
824				tp->snd_up = tp->snd_una;
825				tp->snd_max = tp->snd_nxt = tp->iss + 1;
826				tp->last_ack_sent = tp->rcv_nxt;
827				/*
828				 * RFC1323: The window in SYN & SYN/ACK
829				 * segments is never scaled.
830				 */
831				tp->snd_wnd = tiwin;	/* unscaled */
832				goto after_listen;
833			}
834			if (thflags & TH_RST) {
835				syncache_chkrst(&inc, th);
836				goto drop;
837			}
838			if (thflags & TH_ACK) {
839				syncache_badack(&inc);
840				tcpstat.tcps_badsyn++;
841				rstreason = BANDLIM_RST_OPENPORT;
842				goto dropwithreset;
843			}
844			goto drop;
845		}
846
847		/*
848		 * Segment's flags are (SYN) or (SYN|FIN).
849		 */
850#ifdef INET6
851		/*
852		 * If deprecated address is forbidden,
853		 * we do not accept SYN to deprecated interface
854		 * address to prevent any new inbound connection from
855		 * getting established.
856		 * When we do not accept SYN, we send a TCP RST,
857		 * with deprecated source address (instead of dropping
858		 * it).  We compromise it as it is much better for peer
859		 * to send a RST, and RST will be the final packet
860		 * for the exchange.
861		 *
862		 * If we do not forbid deprecated addresses, we accept
863		 * the SYN packet.  RFC2462 does not suggest dropping
864		 * SYN in this case.
865		 * If we decipher RFC2462 5.5.4, it says like this:
866		 * 1. use of deprecated addr with existing
867		 *    communication is okay - "SHOULD continue to be
868		 *    used"
869		 * 2. use of it with new communication:
870		 *   (2a) "SHOULD NOT be used if alternate address
871		 *        with sufficient scope is available"
872		 *   (2b) nothing mentioned otherwise.
873		 * Here we fall into (2b) case as we have no choice in
874		 * our source address selection - we must obey the peer.
875		 *
876		 * The wording in RFC2462 is confusing, and there are
877		 * multiple description text for deprecated address
878		 * handling - worse, they are not exactly the same.
879		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
880		 */
881		if (isipv6 && !ip6_use_deprecated) {
882			struct in6_ifaddr *ia6;
883
884			if ((ia6 = ip6_getdstifaddr(m)) &&
885			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
886				INP_UNLOCK(inp);
887				tp = NULL;
888				rstreason = BANDLIM_RST_OPENPORT;
889				goto dropwithreset;
890			}
891		}
892#endif
893		/*
894		 * If it is from this socket, drop it, it must be forged.
895		 * Don't bother responding if the destination was a broadcast.
896		 */
897		if (th->th_dport == th->th_sport) {
898			if (isipv6) {
899				if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
900						       &ip6->ip6_src))
901					goto drop;
902			} else {
903				if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
904					goto drop;
905			}
906		}
907		/*
908		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
909		 *
910		 * Note that it is quite possible to receive unicast
911		 * link-layer packets with a broadcast IP address. Use
912		 * in_broadcast() to find them.
913		 */
914		if (m->m_flags & (M_BCAST|M_MCAST))
915			goto drop;
916		if (isipv6) {
917			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
918			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
919				goto drop;
920		} else {
921			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
922			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
923			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
924			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
925				goto drop;
926		}
927		/*
928		 * SYN appears to be valid; create compressed TCP state
929		 * for syncache, or perform t/tcp connection.
930		 */
931		if (so->so_qlen <= so->so_qlimit) {
932#ifdef TCPDEBUG
933			if (so->so_options & SO_DEBUG)
934				tcp_trace(TA_INPUT, ostate, tp,
935				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
936#endif
937			tcp_dooptions(&to, optp, optlen, 1);
938			if (!syncache_add(&inc, &to, th, &so, m))
939				goto drop;
940			if (so == NULL) {
941				/*
942				 * Entry added to syncache, mbuf used to
943				 * send SYN,ACK packet.
944				 */
945				KASSERT(headlocked, ("headlocked"));
946				INP_UNLOCK(inp);
947				INP_INFO_WUNLOCK(&tcbinfo);
948				return;
949			}
950			/*
951			 * Segment passed TAO tests.
952			 */
953			INP_UNLOCK(inp);
954			inp = sotoinpcb(so);
955			INP_LOCK(inp);
956			tp = intotcpcb(inp);
957			tp->snd_wnd = tiwin;
958			tp->t_starttime = ticks;
959			tp->t_state = TCPS_ESTABLISHED;
960
961			/*
962			 * T/TCP logic:
963			 * If there is a FIN or if there is data, then
964			 * delay SYN,ACK(SYN) in the hope of piggy-backing
965			 * it on a response segment.  Otherwise must send
966			 * ACK now in case the other side is slow starting.
967			 */
968			if (thflags & TH_FIN || tlen != 0)
969				tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
970			else
971				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
972			tcpstat.tcps_connects++;
973			soisconnected(so);
974			goto trimthenstep6;
975		}
976		goto drop;
977	}
978after_listen:
979
980	/* XXX temp debugging */
981	/* should not happen - syncache should pick up these connections */
982	if (tp->t_state == TCPS_LISTEN)
983		panic("tcp_input: TCPS_LISTEN");
984
985	/*
986	 * This is the second part of the MSS DoS prevention code (after
987	 * minmss on the sending side) and it deals with too many too small
988	 * tcp packets in a too short timeframe (1 second).
989	 *
990	 * For every full second we count the number of received packets
991	 * and bytes. If we get a lot of packets per second for this connection
992	 * (tcp_minmssoverload) we take a closer look at it and compute the
993	 * average packet size for the past second. If that is less than
994	 * tcp_minmss we get too many packets with very small payload which
995	 * is not good and burdens our system (and every packet generates
996	 * a wakeup to the process connected to our socket). We can reasonable
997	 * expect this to be small packet DoS attack to exhaust our CPU
998	 * cycles.
999	 *
1000	 * Care has to be taken for the minimum packet overload value. This
1001	 * value defines the minimum number of packets per second before we
1002	 * start to worry. This must not be too low to avoid killing for
1003	 * example interactive connections with many small packets like
1004	 * telnet or SSH.
1005	 *
1006	 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1007	 * this check.
1008	 *
1009	 * Account for packet if payload packet, skip over ACK, etc.
1010	 */
1011	if (tcp_minmss && tcp_minmssoverload &&
1012	    tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
1013		if (tp->rcv_second > ticks) {
1014			tp->rcv_pps++;
1015			tp->rcv_byps += tlen + off;
1016			if (tp->rcv_pps > tcp_minmssoverload) {
1017				if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
1018					printf("too many small tcp packets from "
1019					       "%s:%u, av. %lubyte/packet, "
1020					       "dropping connection\n",
1021#ifdef INET6
1022						isipv6 ?
1023						ip6_sprintf(&inp->inp_inc.inc6_faddr) :
1024#endif
1025						inet_ntoa(inp->inp_inc.inc_faddr),
1026						inp->inp_inc.inc_fport,
1027						tp->rcv_byps / tp->rcv_pps);
1028					tp = tcp_drop(tp, ECONNRESET);
1029					tcpstat.tcps_minmssdrops++;
1030					goto drop;
1031				}
1032			}
1033		} else {
1034			tp->rcv_second = ticks + hz;
1035			tp->rcv_pps = 1;
1036			tp->rcv_byps = tlen + off;
1037		}
1038	}
1039
1040	/*
1041	 * Segment received on connection.
1042	 * Reset idle time and keep-alive timer.
1043	 */
1044	tp->t_rcvtime = ticks;
1045	if (TCPS_HAVEESTABLISHED(tp->t_state))
1046		callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1047
1048	/*
1049	 * Process options only when we get SYN/ACK back. The SYN case
1050	 * for incoming connections is handled in tcp_syncache.
1051	 * XXX this is traditional behavior, may need to be cleaned up.
1052	 */
1053	tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
1054	if (thflags & TH_SYN) {
1055		if (to.to_flags & TOF_SCALE) {
1056			tp->t_flags |= TF_RCVD_SCALE;
1057			tp->requested_s_scale = to.to_requested_s_scale;
1058		}
1059		if (to.to_flags & TOF_TS) {
1060			tp->t_flags |= TF_RCVD_TSTMP;
1061			tp->ts_recent = to.to_tsval;
1062			tp->ts_recent_age = ticks;
1063		}
1064		if (to.to_flags & (TOF_CC|TOF_CCNEW))
1065			tp->t_flags |= TF_RCVD_CC;
1066		if (to.to_flags & TOF_MSS)
1067			tcp_mss(tp, to.to_mss);
1068	}
1069
1070	/*
1071	 * Header prediction: check for the two common cases
1072	 * of a uni-directional data xfer.  If the packet has
1073	 * no control flags, is in-sequence, the window didn't
1074	 * change and we're not retransmitting, it's a
1075	 * candidate.  If the length is zero and the ack moved
1076	 * forward, we're the sender side of the xfer.  Just
1077	 * free the data acked & wake any higher level process
1078	 * that was blocked waiting for space.  If the length
1079	 * is non-zero and the ack didn't move, we're the
1080	 * receiver side.  If we're getting packets in-order
1081	 * (the reassembly queue is empty), add the data to
1082	 * the socket buffer and note that we need a delayed ack.
1083	 * Make sure that the hidden state-flags are also off.
1084	 * Since we check for TCPS_ESTABLISHED above, it can only
1085	 * be TH_NEEDSYN.
1086	 */
1087	if (tp->t_state == TCPS_ESTABLISHED &&
1088	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1089	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1090	    ((to.to_flags & TOF_TS) == 0 ||
1091	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1092	    /*
1093	     * Using the CC option is compulsory if once started:
1094	     *   the segment is OK if no T/TCP was negotiated or
1095	     *   if the segment has a CC option equal to CCrecv
1096	     */
1097	    ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
1098	     ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
1099	    th->th_seq == tp->rcv_nxt &&
1100	    tiwin && tiwin == tp->snd_wnd &&
1101	    tp->snd_nxt == tp->snd_max) {
1102
1103		/*
1104		 * If last ACK falls within this segment's sequence numbers,
1105		 * record the timestamp.
1106		 * NOTE that the test is modified according to the latest
1107		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1108		 */
1109		if ((to.to_flags & TOF_TS) != 0 &&
1110		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1111			tp->ts_recent_age = ticks;
1112			tp->ts_recent = to.to_tsval;
1113		}
1114
1115		if (tlen == 0) {
1116			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1117			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1118			    tp->snd_cwnd >= tp->snd_wnd &&
1119			    ((!tcp_do_newreno &&
1120			      tp->t_dupacks < tcprexmtthresh) ||
1121			     (tcp_do_newreno && !IN_FASTRECOVERY(tp)))) {
1122				KASSERT(headlocked, ("headlocked"));
1123				INP_INFO_WUNLOCK(&tcbinfo);
1124				/*
1125				 * this is a pure ack for outstanding data.
1126				 */
1127				++tcpstat.tcps_predack;
1128				/*
1129				 * "bad retransmit" recovery
1130				 */
1131				if (tp->t_rxtshift == 1 &&
1132				    ticks < tp->t_badrxtwin) {
1133					++tcpstat.tcps_sndrexmitbad;
1134					tp->snd_cwnd = tp->snd_cwnd_prev;
1135					tp->snd_ssthresh =
1136					    tp->snd_ssthresh_prev;
1137					tp->snd_recover = tp->snd_recover_prev;
1138					if (tp->t_flags & TF_WASFRECOVERY)
1139					    ENTER_FASTRECOVERY(tp);
1140					tp->snd_nxt = tp->snd_max;
1141					tp->t_badrxtwin = 0;
1142				}
1143
1144				/*
1145				 * Recalculate the transmit timer / rtt.
1146				 *
1147				 * Some boxes send broken timestamp replies
1148				 * during the SYN+ACK phase, ignore
1149				 * timestamps of 0 or we could calculate a
1150				 * huge RTT and blow up the retransmit timer.
1151				 */
1152				if ((to.to_flags & TOF_TS) != 0 &&
1153				    to.to_tsecr) {
1154					tcp_xmit_timer(tp,
1155					    ticks - to.to_tsecr + 1);
1156				} else if (tp->t_rtttime &&
1157					    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1158					tcp_xmit_timer(tp,
1159							ticks - tp->t_rtttime);
1160				}
1161				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1162				acked = th->th_ack - tp->snd_una;
1163				tcpstat.tcps_rcvackpack++;
1164				tcpstat.tcps_rcvackbyte += acked;
1165				sbdrop(&so->so_snd, acked);
1166				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1167				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1168					tp->snd_recover = th->th_ack - 1;
1169				tp->snd_una = th->th_ack;
1170				/*
1171				 * pull snd_wl2 up to prevent seq wrap relative
1172				 * to th_ack.
1173				 */
1174				tp->snd_wl2 = th->th_ack;
1175				tp->t_dupacks = 0;
1176				m_freem(m);
1177				ND6_HINT(tp); /* some progress has been done */
1178
1179				/*
1180				 * If all outstanding data are acked, stop
1181				 * retransmit timer, otherwise restart timer
1182				 * using current (possibly backed-off) value.
1183				 * If process is waiting for space,
1184				 * wakeup/selwakeup/signal.  If data
1185				 * are ready to send, let tcp_output
1186				 * decide between more output or persist.
1187
1188#ifdef TCPDEBUG
1189				if (so->so_options & SO_DEBUG)
1190					tcp_trace(TA_INPUT, ostate, tp,
1191					    (void *)tcp_saveipgen,
1192					    &tcp_savetcp, 0);
1193#endif
1194				 */
1195				if (tp->snd_una == tp->snd_max)
1196					callout_stop(tp->tt_rexmt);
1197				else if (!callout_active(tp->tt_persist))
1198					callout_reset(tp->tt_rexmt,
1199						      tp->t_rxtcur,
1200						      tcp_timer_rexmt, tp);
1201
1202				sowwakeup(so);
1203				if (so->so_snd.sb_cc)
1204					(void) tcp_output(tp);
1205				goto check_delack;
1206			}
1207		} else if (th->th_ack == tp->snd_una &&
1208		    LIST_EMPTY(&tp->t_segq) &&
1209		    tlen <= sbspace(&so->so_rcv)) {
1210			KASSERT(headlocked, ("headlocked"));
1211			INP_INFO_WUNLOCK(&tcbinfo);
1212			/*
1213			 * this is a pure, in-sequence data packet
1214			 * with nothing on the reassembly queue and
1215			 * we have enough buffer space to take it.
1216			 */
1217			++tcpstat.tcps_preddat;
1218			tp->rcv_nxt += tlen;
1219			/*
1220			 * Pull snd_wl1 up to prevent seq wrap relative to
1221			 * th_seq.
1222			 */
1223			tp->snd_wl1 = th->th_seq;
1224			/*
1225			 * Pull rcv_up up to prevent seq wrap relative to
1226			 * rcv_nxt.
1227			 */
1228			tp->rcv_up = tp->rcv_nxt;
1229			tcpstat.tcps_rcvpack++;
1230			tcpstat.tcps_rcvbyte += tlen;
1231			ND6_HINT(tp);	/* some progress has been done */
1232			/*
1233#ifdef TCPDEBUG
1234			if (so->so_options & SO_DEBUG)
1235				tcp_trace(TA_INPUT, ostate, tp,
1236				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
1237#endif
1238			 * Add data to socket buffer.
1239			 */
1240			if (so->so_state & SS_CANTRCVMORE) {
1241				m_freem(m);
1242			} else {
1243				m_adj(m, drop_hdrlen);	/* delayed header drop */
1244				sbappendstream(&so->so_rcv, m);
1245			}
1246			sorwakeup(so);
1247			if (DELAY_ACK(tp)) {
1248				tp->t_flags |= TF_DELACK;
1249			} else {
1250				tp->t_flags |= TF_ACKNOW;
1251				tcp_output(tp);
1252			}
1253			goto check_delack;
1254		}
1255	}
1256
1257	/*
1258	 * Calculate amount of space in receive window,
1259	 * and then do TCP input processing.
1260	 * Receive window is amount of space in rcv queue,
1261	 * but not less than advertised window.
1262	 */
1263	{ int win;
1264
1265	win = sbspace(&so->so_rcv);
1266	if (win < 0)
1267		win = 0;
1268	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1269	}
1270
1271	switch (tp->t_state) {
1272
1273	/*
1274	 * If the state is SYN_RECEIVED:
1275	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1276	 */
1277	case TCPS_SYN_RECEIVED:
1278		if ((thflags & TH_ACK) &&
1279		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1280		     SEQ_GT(th->th_ack, tp->snd_max))) {
1281				rstreason = BANDLIM_RST_OPENPORT;
1282				goto dropwithreset;
1283		}
1284		break;
1285
1286	/*
1287	 * If the state is SYN_SENT:
1288	 *	if seg contains an ACK, but not for our SYN, drop the input.
1289	 *	if seg contains a RST, then drop the connection.
1290	 *	if seg does not contain SYN, then drop it.
1291	 * Otherwise this is an acceptable SYN segment
1292	 *	initialize tp->rcv_nxt and tp->irs
1293	 *	if seg contains ack then advance tp->snd_una
1294	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1295	 *	arrange for segment to be acked (eventually)
1296	 *	continue processing rest of data/controls, beginning with URG
1297	 */
1298	case TCPS_SYN_SENT:
1299		if (tcp_do_rfc1644)
1300			tcp_hc_gettao(&inp->inp_inc, &tao);
1301
1302		if ((thflags & TH_ACK) &&
1303		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1304		     SEQ_GT(th->th_ack, tp->snd_max))) {
1305			/*
1306			 * If we have a cached CCsent for the remote host,
1307			 * hence we haven't just crashed and restarted,
1308			 * do not send a RST.  This may be a retransmission
1309			 * from the other side after our earlier ACK was lost.
1310			 * Our new SYN, when it arrives, will serve as the
1311			 * needed ACK.
1312			 */
1313			if (tao.tao_ccsent != 0)
1314				goto drop;
1315			else {
1316				rstreason = BANDLIM_UNLIMITED;
1317				goto dropwithreset;
1318			}
1319		}
1320		if (thflags & TH_RST) {
1321			if (thflags & TH_ACK)
1322				tp = tcp_drop(tp, ECONNREFUSED);
1323			goto drop;
1324		}
1325		if ((thflags & TH_SYN) == 0)
1326			goto drop;
1327		tp->snd_wnd = th->th_win;	/* initial send window */
1328		tp->cc_recv = to.to_cc;		/* foreign CC */
1329
1330		tp->irs = th->th_seq;
1331		tcp_rcvseqinit(tp);
1332		if (thflags & TH_ACK) {
1333			/*
1334			 * Our SYN was acked.  If segment contains CC.ECHO
1335			 * option, check it to make sure this segment really
1336			 * matches our SYN.  If not, just drop it as old
1337			 * duplicate, but send an RST if we're still playing
1338			 * by the old rules.  If no CC.ECHO option, make sure
1339			 * we don't get fooled into using T/TCP.
1340			 */
1341			if (to.to_flags & TOF_CCECHO) {
1342				if (tp->cc_send != to.to_ccecho) {
1343					if (tao.tao_ccsent != 0)
1344						goto drop;
1345					else {
1346						rstreason = BANDLIM_UNLIMITED;
1347						goto dropwithreset;
1348					}
1349				}
1350			} else
1351				tp->t_flags &= ~TF_RCVD_CC;
1352			tcpstat.tcps_connects++;
1353			soisconnected(so);
1354#ifdef MAC
1355			mac_set_socket_peer_from_mbuf(m, so);
1356#endif
1357			/* Do window scaling on this connection? */
1358			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1359				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1360				tp->snd_scale = tp->requested_s_scale;
1361				tp->rcv_scale = tp->request_r_scale;
1362			}
1363			/* Segment is acceptable, update cache if undefined. */
1364			if (tao.tao_ccsent == 0 && tcp_do_rfc1644)
1365				tcp_hc_updatetao(&inp->inp_inc, TCP_HC_TAO_CCSENT, to.to_ccecho, 0);
1366
1367			tp->rcv_adv += tp->rcv_wnd;
1368			tp->snd_una++;		/* SYN is acked */
1369			/*
1370			 * If there's data, delay ACK; if there's also a FIN
1371			 * ACKNOW will be turned on later.
1372			 */
1373			if (DELAY_ACK(tp) && tlen != 0)
1374                                callout_reset(tp->tt_delack, tcp_delacktime,
1375                                    tcp_timer_delack, tp);
1376			else
1377				tp->t_flags |= TF_ACKNOW;
1378			/*
1379			 * Received <SYN,ACK> in SYN_SENT[*] state.
1380			 * Transitions:
1381			 *	SYN_SENT  --> ESTABLISHED
1382			 *	SYN_SENT* --> FIN_WAIT_1
1383			 */
1384			tp->t_starttime = ticks;
1385			if (tp->t_flags & TF_NEEDFIN) {
1386				tp->t_state = TCPS_FIN_WAIT_1;
1387				tp->t_flags &= ~TF_NEEDFIN;
1388				thflags &= ~TH_SYN;
1389			} else {
1390				tp->t_state = TCPS_ESTABLISHED;
1391				callout_reset(tp->tt_keep, tcp_keepidle,
1392					      tcp_timer_keep, tp);
1393			}
1394		} else {
1395			/*
1396		 	 * Received initial SYN in SYN-SENT[*] state =>
1397		 	 * simultaneous open.  If segment contains CC option
1398		 	 * and there is a cached CC, apply TAO test.
1399		 	 * If it succeeds, connection is * half-synchronized.
1400		 	 * Otherwise, do 3-way handshake:
1401		 	 *        SYN-SENT -> SYN-RECEIVED
1402		 	 *        SYN-SENT* -> SYN-RECEIVED*
1403		 	 * If there was no CC option, clear cached CC value.
1404		 	 */
1405			tp->t_flags |= TF_ACKNOW;
1406			callout_stop(tp->tt_rexmt);
1407			if (to.to_flags & TOF_CC) {
1408				if (tao.tao_cc != 0 &&
1409				    CC_GT(to.to_cc, tao.tao_cc)) {
1410					/*
1411					 * update cache and make transition:
1412					 *        SYN-SENT -> ESTABLISHED*
1413					 *        SYN-SENT* -> FIN-WAIT-1*
1414					 */
1415					tao.tao_cc = to.to_cc;
1416					tcp_hc_updatetao(&inp->inp_inc,
1417						TCP_HC_TAO_CC, to.to_cc, 0);
1418					tp->t_starttime = ticks;
1419					if (tp->t_flags & TF_NEEDFIN) {
1420						tp->t_state = TCPS_FIN_WAIT_1;
1421						tp->t_flags &= ~TF_NEEDFIN;
1422					} else {
1423						tp->t_state = TCPS_ESTABLISHED;
1424						callout_reset(tp->tt_keep,
1425							      tcp_keepidle,
1426							      tcp_timer_keep,
1427							      tp);
1428					}
1429					tp->t_flags |= TF_NEEDSYN;
1430				} else
1431					tp->t_state = TCPS_SYN_RECEIVED;
1432			} else {
1433				if (tcp_do_rfc1644) {
1434					/* CC.NEW or no option => invalidate cache */
1435					tao.tao_cc = 0;
1436					tcp_hc_updatetao(&inp->inp_inc,
1437						TCP_HC_TAO_CC, to.to_cc, 0);
1438				}
1439				tp->t_state = TCPS_SYN_RECEIVED;
1440			}
1441		}
1442
1443trimthenstep6:
1444		/*
1445		 * Advance th->th_seq to correspond to first data byte.
1446		 * If data, trim to stay within window,
1447		 * dropping FIN if necessary.
1448		 */
1449		th->th_seq++;
1450		if (tlen > tp->rcv_wnd) {
1451			todrop = tlen - tp->rcv_wnd;
1452			m_adj(m, -todrop);
1453			tlen = tp->rcv_wnd;
1454			thflags &= ~TH_FIN;
1455			tcpstat.tcps_rcvpackafterwin++;
1456			tcpstat.tcps_rcvbyteafterwin += todrop;
1457		}
1458		tp->snd_wl1 = th->th_seq - 1;
1459		tp->rcv_up = th->th_seq;
1460		/*
1461		 * Client side of transaction: already sent SYN and data.
1462		 * If the remote host used T/TCP to validate the SYN,
1463		 * our data will be ACK'd; if so, enter normal data segment
1464		 * processing in the middle of step 5, ack processing.
1465		 * Otherwise, goto step 6.
1466		 */
1467 		if (thflags & TH_ACK)
1468			goto process_ACK;
1469
1470		goto step6;
1471
1472	/*
1473	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1474	 *	if segment contains a SYN and CC [not CC.NEW] option:
1475	 *              if state == TIME_WAIT and connection duration > MSL,
1476	 *                  drop packet and send RST;
1477	 *
1478	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
1479	 *		    ack the FIN (and data) in retransmission queue.
1480	 *                  Complete close and delete TCPCB.  Then reprocess
1481	 *                  segment, hoping to find new TCPCB in LISTEN state;
1482	 *
1483	 *		else must be old SYN; drop it.
1484	 *      else do normal processing.
1485	 */
1486	case TCPS_LAST_ACK:
1487	case TCPS_CLOSING:
1488	case TCPS_TIME_WAIT:
1489		KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1490		if ((thflags & TH_SYN) &&
1491		    (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1492			if (tp->t_state == TCPS_TIME_WAIT &&
1493					(ticks - tp->t_starttime) > tcp_msl) {
1494				rstreason = BANDLIM_UNLIMITED;
1495				goto dropwithreset;
1496			}
1497			if (CC_GT(to.to_cc, tp->cc_recv)) {
1498				tp = tcp_close(tp);
1499				goto findpcb;
1500			}
1501			else
1502				goto drop;
1503		}
1504 		break;  /* continue normal processing */
1505	}
1506
1507	/*
1508	 * States other than LISTEN or SYN_SENT.
1509	 * First check the RST flag and sequence number since reset segments
1510	 * are exempt from the timestamp and connection count tests.  This
1511	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1512	 * below which allowed reset segments in half the sequence space
1513	 * to fall though and be processed (which gives forged reset
1514	 * segments with a random sequence number a 50 percent chance of
1515	 * killing a connection).
1516	 * Then check timestamp, if present.
1517	 * Then check the connection count, if present.
1518	 * Then check that at least some bytes of segment are within
1519	 * receive window.  If segment begins before rcv_nxt,
1520	 * drop leading data (and SYN); if nothing left, just ack.
1521	 *
1522	 *
1523	 * If the RST bit is set, check the sequence number to see
1524	 * if this is a valid reset segment.
1525	 * RFC 793 page 37:
1526	 *   In all states except SYN-SENT, all reset (RST) segments
1527	 *   are validated by checking their SEQ-fields.  A reset is
1528	 *   valid if its sequence number is in the window.
1529	 * Note: this does not take into account delayed ACKs, so
1530	 *   we should test against last_ack_sent instead of rcv_nxt.
1531	 *   The sequence number in the reset segment is normally an
1532	 *   echo of our outgoing acknowlegement numbers, but some hosts
1533	 *   send a reset with the sequence number at the rightmost edge
1534	 *   of our receive window, and we have to handle this case.
1535	 * If we have multiple segments in flight, the intial reset
1536	 * segment sequence numbers will be to the left of last_ack_sent,
1537	 * but they will eventually catch up.
1538	 * In any case, it never made sense to trim reset segments to
1539	 * fit the receive window since RFC 1122 says:
1540	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1541	 *
1542	 *    A TCP SHOULD allow a received RST segment to include data.
1543	 *
1544	 *    DISCUSSION
1545	 *         It has been suggested that a RST segment could contain
1546	 *         ASCII text that encoded and explained the cause of the
1547	 *         RST.  No standard has yet been established for such
1548	 *         data.
1549	 *
1550	 * If the reset segment passes the sequence number test examine
1551	 * the state:
1552	 *    SYN_RECEIVED STATE:
1553	 *	If passive open, return to LISTEN state.
1554	 *	If active open, inform user that connection was refused.
1555	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1556	 *	Inform user that connection was reset, and close tcb.
1557	 *    CLOSING, LAST_ACK STATES:
1558	 *	Close the tcb.
1559	 *    TIME_WAIT STATE:
1560	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1561	 *      RFC 1337.
1562	 */
1563	if (thflags & TH_RST) {
1564		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1565		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1566			switch (tp->t_state) {
1567
1568			case TCPS_SYN_RECEIVED:
1569				so->so_error = ECONNREFUSED;
1570				goto close;
1571
1572			case TCPS_ESTABLISHED:
1573			case TCPS_FIN_WAIT_1:
1574			case TCPS_FIN_WAIT_2:
1575			case TCPS_CLOSE_WAIT:
1576				so->so_error = ECONNRESET;
1577			close:
1578				tp->t_state = TCPS_CLOSED;
1579				tcpstat.tcps_drops++;
1580				tp = tcp_close(tp);
1581				break;
1582
1583			case TCPS_CLOSING:
1584			case TCPS_LAST_ACK:
1585				tp = tcp_close(tp);
1586				break;
1587
1588			case TCPS_TIME_WAIT:
1589				KASSERT(tp->t_state != TCPS_TIME_WAIT,
1590				    ("timewait"));
1591				break;
1592			}
1593		}
1594		goto drop;
1595	}
1596
1597	/*
1598	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1599	 * and it's less than ts_recent, drop it.
1600	 */
1601	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1602	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1603
1604		/* Check to see if ts_recent is over 24 days old.  */
1605		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1606			/*
1607			 * Invalidate ts_recent.  If this segment updates
1608			 * ts_recent, the age will be reset later and ts_recent
1609			 * will get a valid value.  If it does not, setting
1610			 * ts_recent to zero will at least satisfy the
1611			 * requirement that zero be placed in the timestamp
1612			 * echo reply when ts_recent isn't valid.  The
1613			 * age isn't reset until we get a valid ts_recent
1614			 * because we don't want out-of-order segments to be
1615			 * dropped when ts_recent is old.
1616			 */
1617			tp->ts_recent = 0;
1618		} else {
1619			tcpstat.tcps_rcvduppack++;
1620			tcpstat.tcps_rcvdupbyte += tlen;
1621			tcpstat.tcps_pawsdrop++;
1622			if (tlen)
1623				goto dropafterack;
1624			goto drop;
1625		}
1626	}
1627
1628	/*
1629	 * T/TCP mechanism
1630	 *   If T/TCP was negotiated and the segment doesn't have CC,
1631	 *   or if its CC is wrong then drop the segment.
1632	 *   RST segments do not have to comply with this.
1633	 */
1634	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1635	    ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1636 		goto dropafterack;
1637
1638	/*
1639	 * In the SYN-RECEIVED state, validate that the packet belongs to
1640	 * this connection before trimming the data to fit the receive
1641	 * window.  Check the sequence number versus IRS since we know
1642	 * the sequence numbers haven't wrapped.  This is a partial fix
1643	 * for the "LAND" DoS attack.
1644	 */
1645	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1646		rstreason = BANDLIM_RST_OPENPORT;
1647		goto dropwithreset;
1648	}
1649
1650	todrop = tp->rcv_nxt - th->th_seq;
1651	if (todrop > 0) {
1652		if (thflags & TH_SYN) {
1653			thflags &= ~TH_SYN;
1654			th->th_seq++;
1655			if (th->th_urp > 1)
1656				th->th_urp--;
1657			else
1658				thflags &= ~TH_URG;
1659			todrop--;
1660		}
1661		/*
1662		 * Following if statement from Stevens, vol. 2, p. 960.
1663		 */
1664		if (todrop > tlen
1665		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1666			/*
1667			 * Any valid FIN must be to the left of the window.
1668			 * At this point the FIN must be a duplicate or out
1669			 * of sequence; drop it.
1670			 */
1671			thflags &= ~TH_FIN;
1672
1673			/*
1674			 * Send an ACK to resynchronize and drop any data.
1675			 * But keep on processing for RST or ACK.
1676			 */
1677			tp->t_flags |= TF_ACKNOW;
1678			todrop = tlen;
1679			tcpstat.tcps_rcvduppack++;
1680			tcpstat.tcps_rcvdupbyte += todrop;
1681		} else {
1682			tcpstat.tcps_rcvpartduppack++;
1683			tcpstat.tcps_rcvpartdupbyte += todrop;
1684		}
1685		drop_hdrlen += todrop;	/* drop from the top afterwards */
1686		th->th_seq += todrop;
1687		tlen -= todrop;
1688		if (th->th_urp > todrop)
1689			th->th_urp -= todrop;
1690		else {
1691			thflags &= ~TH_URG;
1692			th->th_urp = 0;
1693		}
1694	}
1695
1696	/*
1697	 * If new data are received on a connection after the
1698	 * user processes are gone, then RST the other end.
1699	 */
1700	if ((so->so_state & SS_NOFDREF) &&
1701	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1702		tp = tcp_close(tp);
1703		tcpstat.tcps_rcvafterclose++;
1704		rstreason = BANDLIM_UNLIMITED;
1705		goto dropwithreset;
1706	}
1707
1708	/*
1709	 * If segment ends after window, drop trailing data
1710	 * (and PUSH and FIN); if nothing left, just ACK.
1711	 */
1712	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1713	if (todrop > 0) {
1714		tcpstat.tcps_rcvpackafterwin++;
1715		if (todrop >= tlen) {
1716			tcpstat.tcps_rcvbyteafterwin += tlen;
1717			/*
1718			 * If a new connection request is received
1719			 * while in TIME_WAIT, drop the old connection
1720			 * and start over if the sequence numbers
1721			 * are above the previous ones.
1722			 */
1723			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1724			if (thflags & TH_SYN &&
1725			    tp->t_state == TCPS_TIME_WAIT &&
1726			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1727				tp = tcp_close(tp);
1728				goto findpcb;
1729			}
1730			/*
1731			 * If window is closed can only take segments at
1732			 * window edge, and have to drop data and PUSH from
1733			 * incoming segments.  Continue processing, but
1734			 * remember to ack.  Otherwise, drop segment
1735			 * and ack.
1736			 */
1737			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1738				tp->t_flags |= TF_ACKNOW;
1739				tcpstat.tcps_rcvwinprobe++;
1740			} else
1741				goto dropafterack;
1742		} else
1743			tcpstat.tcps_rcvbyteafterwin += todrop;
1744		m_adj(m, -todrop);
1745		tlen -= todrop;
1746		thflags &= ~(TH_PUSH|TH_FIN);
1747	}
1748
1749	/*
1750	 * If last ACK falls within this segment's sequence numbers,
1751	 * record its timestamp.
1752	 * NOTE that the test is modified according to the latest
1753	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1754	 */
1755	if ((to.to_flags & TOF_TS) != 0 &&
1756	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1757		tp->ts_recent_age = ticks;
1758		tp->ts_recent = to.to_tsval;
1759	}
1760
1761	/*
1762	 * If a SYN is in the window, then this is an
1763	 * error and we send an RST and drop the connection.
1764	 */
1765	if (thflags & TH_SYN) {
1766		tp = tcp_drop(tp, ECONNRESET);
1767		rstreason = BANDLIM_UNLIMITED;
1768		goto drop;
1769	}
1770
1771	/*
1772	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1773	 * flag is on (half-synchronized state), then queue data for
1774	 * later processing; else drop segment and return.
1775	 */
1776	if ((thflags & TH_ACK) == 0) {
1777		if (tp->t_state == TCPS_SYN_RECEIVED ||
1778		    (tp->t_flags & TF_NEEDSYN))
1779			goto step6;
1780		else
1781			goto drop;
1782	}
1783
1784	/*
1785	 * Ack processing.
1786	 */
1787	switch (tp->t_state) {
1788
1789	/*
1790	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1791	 * ESTABLISHED state and continue processing.
1792	 * The ACK was checked above.
1793	 */
1794	case TCPS_SYN_RECEIVED:
1795
1796		tcpstat.tcps_connects++;
1797		soisconnected(so);
1798		/* Do window scaling? */
1799		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1800			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1801			tp->snd_scale = tp->requested_s_scale;
1802			tp->rcv_scale = tp->request_r_scale;
1803		}
1804		/*
1805		 * Upon successful completion of 3-way handshake,
1806		 * update cache.CC, pass any queued data to the user,
1807		 * and advance state appropriately.
1808		 */
1809		if (tcp_do_rfc1644) {
1810			tao.tao_cc = tp->cc_recv;
1811			tcp_hc_updatetao(&inp->inp_inc, TCP_HC_TAO_CC,
1812					 tp->cc_recv, 0);
1813		}
1814		/*
1815		 * Make transitions:
1816		 *      SYN-RECEIVED  -> ESTABLISHED
1817		 *      SYN-RECEIVED* -> FIN-WAIT-1
1818		 */
1819		tp->t_starttime = ticks;
1820		if (tp->t_flags & TF_NEEDFIN) {
1821			tp->t_state = TCPS_FIN_WAIT_1;
1822			tp->t_flags &= ~TF_NEEDFIN;
1823		} else {
1824			tp->t_state = TCPS_ESTABLISHED;
1825			callout_reset(tp->tt_keep, tcp_keepidle,
1826				      tcp_timer_keep, tp);
1827		}
1828		/*
1829		 * If segment contains data or ACK, will call tcp_reass()
1830		 * later; if not, do so now to pass queued data to user.
1831		 */
1832		if (tlen == 0 && (thflags & TH_FIN) == 0)
1833			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1834			    (struct mbuf *)0);
1835		tp->snd_wl1 = th->th_seq - 1;
1836		/* FALLTHROUGH */
1837
1838	/*
1839	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1840	 * ACKs.  If the ack is in the range
1841	 *	tp->snd_una < th->th_ack <= tp->snd_max
1842	 * then advance tp->snd_una to th->th_ack and drop
1843	 * data from the retransmission queue.  If this ACK reflects
1844	 * more up to date window information we update our window information.
1845	 */
1846	case TCPS_ESTABLISHED:
1847	case TCPS_FIN_WAIT_1:
1848	case TCPS_FIN_WAIT_2:
1849	case TCPS_CLOSE_WAIT:
1850	case TCPS_CLOSING:
1851	case TCPS_LAST_ACK:
1852	case TCPS_TIME_WAIT:
1853		KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1854		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1855			if (tlen == 0 && tiwin == tp->snd_wnd) {
1856				tcpstat.tcps_rcvdupack++;
1857				/*
1858				 * If we have outstanding data (other than
1859				 * a window probe), this is a completely
1860				 * duplicate ack (ie, window info didn't
1861				 * change), the ack is the biggest we've
1862				 * seen and we've seen exactly our rexmt
1863				 * threshhold of them, assume a packet
1864				 * has been dropped and retransmit it.
1865				 * Kludge snd_nxt & the congestion
1866				 * window so we send only this one
1867				 * packet.
1868				 *
1869				 * We know we're losing at the current
1870				 * window size so do congestion avoidance
1871				 * (set ssthresh to half the current window
1872				 * and pull our congestion window back to
1873				 * the new ssthresh).
1874				 *
1875				 * Dup acks mean that packets have left the
1876				 * network (they're now cached at the receiver)
1877				 * so bump cwnd by the amount in the receiver
1878				 * to keep a constant cwnd packets in the
1879				 * network.
1880				 */
1881				if (!callout_active(tp->tt_rexmt) ||
1882				    th->th_ack != tp->snd_una)
1883					tp->t_dupacks = 0;
1884				else if (++tp->t_dupacks > tcprexmtthresh ||
1885					 (tcp_do_newreno &&
1886					  IN_FASTRECOVERY(tp))) {
1887					tp->snd_cwnd += tp->t_maxseg;
1888					(void) tcp_output(tp);
1889					goto drop;
1890				} else if (tp->t_dupacks == tcprexmtthresh) {
1891					tcp_seq onxt = tp->snd_nxt;
1892					u_int win;
1893					if (tcp_do_newreno &&
1894					    SEQ_LEQ(th->th_ack,
1895					            tp->snd_recover)) {
1896						tp->t_dupacks = 0;
1897						break;
1898					}
1899					win = min(tp->snd_wnd, tp->snd_cwnd) /
1900					    2 / tp->t_maxseg;
1901					if (win < 2)
1902						win = 2;
1903					tp->snd_ssthresh = win * tp->t_maxseg;
1904					ENTER_FASTRECOVERY(tp);
1905					tp->snd_recover = tp->snd_max;
1906					callout_stop(tp->tt_rexmt);
1907					tp->t_rtttime = 0;
1908					tp->snd_nxt = th->th_ack;
1909					tp->snd_cwnd = tp->t_maxseg;
1910					(void) tcp_output(tp);
1911					KASSERT(tp->snd_limited <= 2,
1912					    ("tp->snd_limited too big"));
1913					tp->snd_cwnd = tp->snd_ssthresh +
1914					     tp->t_maxseg *
1915					     (tp->t_dupacks - tp->snd_limited);
1916					if (SEQ_GT(onxt, tp->snd_nxt))
1917						tp->snd_nxt = onxt;
1918					goto drop;
1919				} else if (tcp_do_rfc3042) {
1920					u_long oldcwnd = tp->snd_cwnd;
1921					tcp_seq oldsndmax = tp->snd_max;
1922					u_int sent;
1923
1924					KASSERT(tp->t_dupacks == 1 ||
1925					    tp->t_dupacks == 2,
1926					    ("dupacks not 1 or 2"));
1927					if (tp->t_dupacks == 1)
1928						tp->snd_limited = 0;
1929					tp->snd_cwnd =
1930					    (tp->snd_nxt - tp->snd_una) +
1931					    (tp->t_dupacks - tp->snd_limited) *
1932					    tp->t_maxseg;
1933					(void) tcp_output(tp);
1934					sent = tp->snd_max - oldsndmax;
1935					if (sent > tp->t_maxseg) {
1936						KASSERT((tp->t_dupacks == 2 &&
1937						    tp->snd_limited == 0) ||
1938						   (sent == tp->t_maxseg + 1 &&
1939						    tp->t_flags & TF_SENTFIN),
1940						    ("sent too much"));
1941						tp->snd_limited = 2;
1942					} else if (sent > 0)
1943						++tp->snd_limited;
1944					tp->snd_cwnd = oldcwnd;
1945					goto drop;
1946				}
1947			} else
1948				tp->t_dupacks = 0;
1949			break;
1950		}
1951
1952		KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1953
1954		/*
1955		 * If the congestion window was inflated to account
1956		 * for the other side's cached packets, retract it.
1957		 */
1958		if (tcp_do_newreno) {
1959			if (IN_FASTRECOVERY(tp)) {
1960				if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1961					tcp_newreno_partial_ack(tp, th);
1962				} else {
1963					/*
1964					 * Window inflation should have left us
1965					 * with approximately snd_ssthresh
1966					 * outstanding data.
1967					 * But in case we would be inclined to
1968					 * send a burst, better to do it via
1969					 * the slow start mechanism.
1970					 */
1971					if (SEQ_GT(th->th_ack +
1972							tp->snd_ssthresh,
1973						   tp->snd_max))
1974						tp->snd_cwnd = tp->snd_max -
1975								th->th_ack +
1976								tp->t_maxseg;
1977					else
1978						tp->snd_cwnd = tp->snd_ssthresh;
1979				}
1980			}
1981                } else {
1982                        if (tp->t_dupacks >= tcprexmtthresh &&
1983                            tp->snd_cwnd > tp->snd_ssthresh)
1984				tp->snd_cwnd = tp->snd_ssthresh;
1985                }
1986		tp->t_dupacks = 0;
1987		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1988			tcpstat.tcps_rcvacktoomuch++;
1989			goto dropafterack;
1990		}
1991		/*
1992		 * If we reach this point, ACK is not a duplicate,
1993		 *     i.e., it ACKs something we sent.
1994		 */
1995		if (tp->t_flags & TF_NEEDSYN) {
1996			/*
1997			 * T/TCP: Connection was half-synchronized, and our
1998			 * SYN has been ACK'd (so connection is now fully
1999			 * synchronized).  Go to non-starred state,
2000			 * increment snd_una for ACK of SYN, and check if
2001			 * we can do window scaling.
2002			 */
2003			tp->t_flags &= ~TF_NEEDSYN;
2004			tp->snd_una++;
2005			/* Do window scaling? */
2006			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2007				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2008				tp->snd_scale = tp->requested_s_scale;
2009				tp->rcv_scale = tp->request_r_scale;
2010			}
2011		}
2012
2013process_ACK:
2014		acked = th->th_ack - tp->snd_una;
2015		tcpstat.tcps_rcvackpack++;
2016		tcpstat.tcps_rcvackbyte += acked;
2017
2018		/*
2019		 * If we just performed our first retransmit, and the ACK
2020		 * arrives within our recovery window, then it was a mistake
2021		 * to do the retransmit in the first place.  Recover our
2022		 * original cwnd and ssthresh, and proceed to transmit where
2023		 * we left off.
2024		 */
2025		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2026			++tcpstat.tcps_sndrexmitbad;
2027			tp->snd_cwnd = tp->snd_cwnd_prev;
2028			tp->snd_ssthresh = tp->snd_ssthresh_prev;
2029			tp->snd_recover = tp->snd_recover_prev;
2030			if (tp->t_flags & TF_WASFRECOVERY)
2031				ENTER_FASTRECOVERY(tp);
2032			tp->snd_nxt = tp->snd_max;
2033			tp->t_badrxtwin = 0;	/* XXX probably not required */
2034		}
2035
2036		/*
2037		 * If we have a timestamp reply, update smoothed
2038		 * round trip time.  If no timestamp is present but
2039		 * transmit timer is running and timed sequence
2040		 * number was acked, update smoothed round trip time.
2041		 * Since we now have an rtt measurement, cancel the
2042		 * timer backoff (cf., Phil Karn's retransmit alg.).
2043		 * Recompute the initial retransmit timer.
2044		 *
2045		 * Some boxes send broken timestamp replies
2046		 * during the SYN+ACK phase, ignore
2047		 * timestamps of 0 or we could calculate a
2048		 * huge RTT and blow up the retransmit timer.
2049		 */
2050		if ((to.to_flags & TOF_TS) != 0 &&
2051		    to.to_tsecr) {
2052			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2053		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2054			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2055		}
2056		tcp_xmit_bandwidth_limit(tp, th->th_ack);
2057
2058		/*
2059		 * If all outstanding data is acked, stop retransmit
2060		 * timer and remember to restart (more output or persist).
2061		 * If there is more data to be acked, restart retransmit
2062		 * timer, using current (possibly backed-off) value.
2063		 */
2064		if (th->th_ack == tp->snd_max) {
2065			callout_stop(tp->tt_rexmt);
2066			needoutput = 1;
2067		} else if (!callout_active(tp->tt_persist))
2068			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2069				      tcp_timer_rexmt, tp);
2070
2071		/*
2072		 * If no data (only SYN) was ACK'd,
2073		 *    skip rest of ACK processing.
2074		 */
2075		if (acked == 0)
2076			goto step6;
2077
2078		/*
2079		 * When new data is acked, open the congestion window.
2080		 * If the window gives us less than ssthresh packets
2081		 * in flight, open exponentially (maxseg per packet).
2082		 * Otherwise open linearly: maxseg per window
2083		 * (maxseg^2 / cwnd per packet).
2084		 */
2085		if (!tcp_do_newreno || !IN_FASTRECOVERY(tp)) {
2086			register u_int cw = tp->snd_cwnd;
2087			register u_int incr = tp->t_maxseg;
2088			if (cw > tp->snd_ssthresh)
2089				incr = incr * incr / cw;
2090			tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2091		}
2092		if (acked > so->so_snd.sb_cc) {
2093			tp->snd_wnd -= so->so_snd.sb_cc;
2094			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2095			ourfinisacked = 1;
2096		} else {
2097			sbdrop(&so->so_snd, acked);
2098			tp->snd_wnd -= acked;
2099			ourfinisacked = 0;
2100		}
2101		sowwakeup(so);
2102		/* detect una wraparound */
2103		if (tcp_do_newreno && !IN_FASTRECOVERY(tp) &&
2104		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
2105		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2106			tp->snd_recover = th->th_ack - 1;
2107		if (tcp_do_newreno && IN_FASTRECOVERY(tp) &&
2108		    SEQ_GEQ(th->th_ack, tp->snd_recover))
2109			EXIT_FASTRECOVERY(tp);
2110		tp->snd_una = th->th_ack;
2111		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2112			tp->snd_nxt = tp->snd_una;
2113
2114		switch (tp->t_state) {
2115
2116		/*
2117		 * In FIN_WAIT_1 STATE in addition to the processing
2118		 * for the ESTABLISHED state if our FIN is now acknowledged
2119		 * then enter FIN_WAIT_2.
2120		 */
2121		case TCPS_FIN_WAIT_1:
2122			if (ourfinisacked) {
2123				/*
2124				 * If we can't receive any more
2125				 * data, then closing user can proceed.
2126				 * Starting the timer is contrary to the
2127				 * specification, but if we don't get a FIN
2128				 * we'll hang forever.
2129				 */
2130		/* XXXjl
2131		 * we should release the tp also, and use a
2132		 * compressed state.
2133		 */
2134				if (so->so_state & SS_CANTRCVMORE) {
2135					soisdisconnected(so);
2136					callout_reset(tp->tt_2msl, tcp_maxidle,
2137						      tcp_timer_2msl, tp);
2138				}
2139				tp->t_state = TCPS_FIN_WAIT_2;
2140			}
2141			break;
2142
2143	 	/*
2144		 * In CLOSING STATE in addition to the processing for
2145		 * the ESTABLISHED state if the ACK acknowledges our FIN
2146		 * then enter the TIME-WAIT state, otherwise ignore
2147		 * the segment.
2148		 */
2149		case TCPS_CLOSING:
2150			if (ourfinisacked) {
2151				KASSERT(headlocked, ("headlocked"));
2152				tcp_twstart(tp);
2153				INP_INFO_WUNLOCK(&tcbinfo);
2154				m_freem(m);
2155				return;
2156			}
2157			break;
2158
2159		/*
2160		 * In LAST_ACK, we may still be waiting for data to drain
2161		 * and/or to be acked, as well as for the ack of our FIN.
2162		 * If our FIN is now acknowledged, delete the TCB,
2163		 * enter the closed state and return.
2164		 */
2165		case TCPS_LAST_ACK:
2166			if (ourfinisacked) {
2167				tp = tcp_close(tp);
2168				goto drop;
2169			}
2170			break;
2171
2172		/*
2173		 * In TIME_WAIT state the only thing that should arrive
2174		 * is a retransmission of the remote FIN.  Acknowledge
2175		 * it and restart the finack timer.
2176		 */
2177		case TCPS_TIME_WAIT:
2178			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2179			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2180				      tcp_timer_2msl, tp);
2181			goto dropafterack;
2182		}
2183	}
2184
2185step6:
2186	/*
2187	 * Update window information.
2188	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2189	 */
2190	if ((thflags & TH_ACK) &&
2191	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2192	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2193	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2194		/* keep track of pure window updates */
2195		if (tlen == 0 &&
2196		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2197			tcpstat.tcps_rcvwinupd++;
2198		tp->snd_wnd = tiwin;
2199		tp->snd_wl1 = th->th_seq;
2200		tp->snd_wl2 = th->th_ack;
2201		if (tp->snd_wnd > tp->max_sndwnd)
2202			tp->max_sndwnd = tp->snd_wnd;
2203		needoutput = 1;
2204	}
2205
2206	/*
2207	 * Process segments with URG.
2208	 */
2209	if ((thflags & TH_URG) && th->th_urp &&
2210	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2211		/*
2212		 * This is a kludge, but if we receive and accept
2213		 * random urgent pointers, we'll crash in
2214		 * soreceive.  It's hard to imagine someone
2215		 * actually wanting to send this much urgent data.
2216		 */
2217		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2218			th->th_urp = 0;			/* XXX */
2219			thflags &= ~TH_URG;		/* XXX */
2220			goto dodata;			/* XXX */
2221		}
2222		/*
2223		 * If this segment advances the known urgent pointer,
2224		 * then mark the data stream.  This should not happen
2225		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2226		 * a FIN has been received from the remote side.
2227		 * In these states we ignore the URG.
2228		 *
2229		 * According to RFC961 (Assigned Protocols),
2230		 * the urgent pointer points to the last octet
2231		 * of urgent data.  We continue, however,
2232		 * to consider it to indicate the first octet
2233		 * of data past the urgent section as the original
2234		 * spec states (in one of two places).
2235		 */
2236		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2237			tp->rcv_up = th->th_seq + th->th_urp;
2238			so->so_oobmark = so->so_rcv.sb_cc +
2239			    (tp->rcv_up - tp->rcv_nxt) - 1;
2240			if (so->so_oobmark == 0)
2241				so->so_state |= SS_RCVATMARK;
2242			sohasoutofband(so);
2243			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2244		}
2245		/*
2246		 * Remove out of band data so doesn't get presented to user.
2247		 * This can happen independent of advancing the URG pointer,
2248		 * but if two URG's are pending at once, some out-of-band
2249		 * data may creep in... ick.
2250		 */
2251		if (th->th_urp <= (u_long)tlen &&
2252		    !(so->so_options & SO_OOBINLINE)) {
2253			/* hdr drop is delayed */
2254			tcp_pulloutofband(so, th, m, drop_hdrlen);
2255		}
2256	} else {
2257		/*
2258		 * If no out of band data is expected,
2259		 * pull receive urgent pointer along
2260		 * with the receive window.
2261		 */
2262		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2263			tp->rcv_up = tp->rcv_nxt;
2264	}
2265dodata:							/* XXX */
2266	KASSERT(headlocked, ("headlocked"));
2267	/*
2268	 * Process the segment text, merging it into the TCP sequencing queue,
2269	 * and arranging for acknowledgment of receipt if necessary.
2270	 * This process logically involves adjusting tp->rcv_wnd as data
2271	 * is presented to the user (this happens in tcp_usrreq.c,
2272	 * case PRU_RCVD).  If a FIN has already been received on this
2273	 * connection then we just ignore the text.
2274	 */
2275	if ((tlen || (thflags & TH_FIN)) &&
2276	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2277		m_adj(m, drop_hdrlen);	/* delayed header drop */
2278		/*
2279		 * Insert segment which includes th into TCP reassembly queue
2280		 * with control block tp.  Set thflags to whether reassembly now
2281		 * includes a segment with FIN.  This handles the common case
2282		 * inline (segment is the next to be received on an established
2283		 * connection, and the queue is empty), avoiding linkage into
2284		 * and removal from the queue and repetition of various
2285		 * conversions.
2286		 * Set DELACK for segments received in order, but ack
2287		 * immediately when segments are out of order (so
2288		 * fast retransmit can work).
2289		 */
2290		if (th->th_seq == tp->rcv_nxt &&
2291		    LIST_EMPTY(&tp->t_segq) &&
2292		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2293			if (DELAY_ACK(tp))
2294				tp->t_flags |= TF_DELACK;
2295			else
2296				tp->t_flags |= TF_ACKNOW;
2297			tp->rcv_nxt += tlen;
2298			thflags = th->th_flags & TH_FIN;
2299			tcpstat.tcps_rcvpack++;
2300			tcpstat.tcps_rcvbyte += tlen;
2301			ND6_HINT(tp);
2302			if (so->so_state & SS_CANTRCVMORE)
2303				m_freem(m);
2304			else
2305				sbappendstream(&so->so_rcv, m);
2306			sorwakeup(so);
2307		} else {
2308			thflags = tcp_reass(tp, th, &tlen, m);
2309			tp->t_flags |= TF_ACKNOW;
2310		}
2311
2312		/*
2313		 * Note the amount of data that peer has sent into
2314		 * our window, in order to estimate the sender's
2315		 * buffer size.
2316		 */
2317		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2318	} else {
2319		m_freem(m);
2320		thflags &= ~TH_FIN;
2321	}
2322
2323	/*
2324	 * If FIN is received ACK the FIN and let the user know
2325	 * that the connection is closing.
2326	 */
2327	if (thflags & TH_FIN) {
2328		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2329			socantrcvmore(so);
2330			/*
2331			 * If connection is half-synchronized
2332			 * (ie NEEDSYN flag on) then delay ACK,
2333			 * so it may be piggybacked when SYN is sent.
2334			 * Otherwise, since we received a FIN then no
2335			 * more input can be expected, send ACK now.
2336			 */
2337			if (tp->t_flags & TF_NEEDSYN)
2338				tp->t_flags |= TF_DELACK;
2339			else
2340				tp->t_flags |= TF_ACKNOW;
2341			tp->rcv_nxt++;
2342		}
2343		switch (tp->t_state) {
2344
2345	 	/*
2346		 * In SYN_RECEIVED and ESTABLISHED STATES
2347		 * enter the CLOSE_WAIT state.
2348		 */
2349		case TCPS_SYN_RECEIVED:
2350			tp->t_starttime = ticks;
2351			/*FALLTHROUGH*/
2352		case TCPS_ESTABLISHED:
2353			tp->t_state = TCPS_CLOSE_WAIT;
2354			break;
2355
2356	 	/*
2357		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2358		 * enter the CLOSING state.
2359		 */
2360		case TCPS_FIN_WAIT_1:
2361			tp->t_state = TCPS_CLOSING;
2362			break;
2363
2364	 	/*
2365		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2366		 * starting the time-wait timer, turning off the other
2367		 * standard timers.
2368		 */
2369		case TCPS_FIN_WAIT_2:
2370			KASSERT(headlocked == 1, ("headlocked should be 1"));
2371			tcp_twstart(tp);
2372			INP_INFO_WUNLOCK(&tcbinfo);
2373			return;
2374
2375		/*
2376		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2377		 */
2378		case TCPS_TIME_WAIT:
2379			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2380			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2381				      tcp_timer_2msl, tp);
2382			break;
2383		}
2384	}
2385	INP_INFO_WUNLOCK(&tcbinfo);
2386#ifdef TCPDEBUG
2387	if (so->so_options & SO_DEBUG)
2388		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2389			  &tcp_savetcp, 0);
2390#endif
2391
2392	/*
2393	 * Return any desired output.
2394	 */
2395	if (needoutput || (tp->t_flags & TF_ACKNOW))
2396		(void) tcp_output(tp);
2397
2398check_delack:
2399	if (tp->t_flags & TF_DELACK) {
2400		tp->t_flags &= ~TF_DELACK;
2401		callout_reset(tp->tt_delack, tcp_delacktime,
2402		    tcp_timer_delack, tp);
2403	}
2404	INP_UNLOCK(inp);
2405	return;
2406
2407dropafterack:
2408	/*
2409	 * Generate an ACK dropping incoming segment if it occupies
2410	 * sequence space, where the ACK reflects our state.
2411	 *
2412	 * We can now skip the test for the RST flag since all
2413	 * paths to this code happen after packets containing
2414	 * RST have been dropped.
2415	 *
2416	 * In the SYN-RECEIVED state, don't send an ACK unless the
2417	 * segment we received passes the SYN-RECEIVED ACK test.
2418	 * If it fails send a RST.  This breaks the loop in the
2419	 * "LAND" DoS attack, and also prevents an ACK storm
2420	 * between two listening ports that have been sent forged
2421	 * SYN segments, each with the source address of the other.
2422	 */
2423	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2424	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2425	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2426		rstreason = BANDLIM_RST_OPENPORT;
2427		goto dropwithreset;
2428	}
2429#ifdef TCPDEBUG
2430	if (so->so_options & SO_DEBUG)
2431		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2432			  &tcp_savetcp, 0);
2433#endif
2434	KASSERT(headlocked, ("headlocked should be 1"));
2435	INP_INFO_WUNLOCK(&tcbinfo);
2436	m_freem(m);
2437	tp->t_flags |= TF_ACKNOW;
2438	(void) tcp_output(tp);
2439	INP_UNLOCK(inp);
2440	return;
2441
2442dropwithreset:
2443	/*
2444	 * Generate a RST, dropping incoming segment.
2445	 * Make ACK acceptable to originator of segment.
2446	 * Don't bother to respond if destination was broadcast/multicast.
2447	 */
2448	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2449		goto drop;
2450	if (isipv6) {
2451		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2452		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2453			goto drop;
2454	} else {
2455		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2456		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2457	    	    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2458	    	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2459			goto drop;
2460	}
2461	/* IPv6 anycast check is done at tcp6_input() */
2462
2463	/*
2464	 * Perform bandwidth limiting.
2465	 */
2466	if (badport_bandlim(rstreason) < 0)
2467		goto drop;
2468
2469#ifdef TCPDEBUG
2470	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2471		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2472			  &tcp_savetcp, 0);
2473#endif
2474
2475	if (thflags & TH_ACK)
2476		/* mtod() below is safe as long as hdr dropping is delayed */
2477		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2478			    TH_RST);
2479	else {
2480		if (thflags & TH_SYN)
2481			tlen++;
2482		/* mtod() below is safe as long as hdr dropping is delayed */
2483		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2484			    (tcp_seq)0, TH_RST|TH_ACK);
2485	}
2486
2487	if (tp)
2488		INP_UNLOCK(inp);
2489	if (headlocked)
2490		INP_INFO_WUNLOCK(&tcbinfo);
2491	return;
2492
2493drop:
2494	/*
2495	 * Drop space held by incoming segment and return.
2496	 */
2497#ifdef TCPDEBUG
2498	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2499		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2500			  &tcp_savetcp, 0);
2501#endif
2502	if (tp)
2503		INP_UNLOCK(inp);
2504	m_freem(m);
2505	if (headlocked)
2506		INP_INFO_WUNLOCK(&tcbinfo);
2507	return;
2508}
2509
2510/*
2511 * Parse TCP options and place in tcpopt.
2512 */
2513static void
2514tcp_dooptions(to, cp, cnt, is_syn)
2515	struct tcpopt *to;
2516	u_char *cp;
2517	int cnt;
2518	int is_syn;
2519{
2520	int opt, optlen;
2521
2522	to->to_flags = 0;
2523	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2524		opt = cp[0];
2525		if (opt == TCPOPT_EOL)
2526			break;
2527		if (opt == TCPOPT_NOP)
2528			optlen = 1;
2529		else {
2530			if (cnt < 2)
2531				break;
2532			optlen = cp[1];
2533			if (optlen < 2 || optlen > cnt)
2534				break;
2535		}
2536		switch (opt) {
2537		case TCPOPT_MAXSEG:
2538			if (optlen != TCPOLEN_MAXSEG)
2539				continue;
2540			if (!is_syn)
2541				continue;
2542			to->to_flags |= TOF_MSS;
2543			bcopy((char *)cp + 2,
2544			    (char *)&to->to_mss, sizeof(to->to_mss));
2545			to->to_mss = ntohs(to->to_mss);
2546			break;
2547		case TCPOPT_WINDOW:
2548			if (optlen != TCPOLEN_WINDOW)
2549				continue;
2550			if (! is_syn)
2551				continue;
2552			to->to_flags |= TOF_SCALE;
2553			to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2554			break;
2555		case TCPOPT_TIMESTAMP:
2556			if (optlen != TCPOLEN_TIMESTAMP)
2557				continue;
2558			to->to_flags |= TOF_TS;
2559			bcopy((char *)cp + 2,
2560			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2561			to->to_tsval = ntohl(to->to_tsval);
2562			bcopy((char *)cp + 6,
2563			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2564			to->to_tsecr = ntohl(to->to_tsecr);
2565			break;
2566		case TCPOPT_CC:
2567			if (optlen != TCPOLEN_CC)
2568				continue;
2569			to->to_flags |= TOF_CC;
2570			bcopy((char *)cp + 2,
2571			    (char *)&to->to_cc, sizeof(to->to_cc));
2572			to->to_cc = ntohl(to->to_cc);
2573			break;
2574		case TCPOPT_CCNEW:
2575			if (optlen != TCPOLEN_CC)
2576				continue;
2577			if (!is_syn)
2578				continue;
2579			to->to_flags |= TOF_CCNEW;
2580			bcopy((char *)cp + 2,
2581			    (char *)&to->to_cc, sizeof(to->to_cc));
2582			to->to_cc = ntohl(to->to_cc);
2583			break;
2584		case TCPOPT_CCECHO:
2585			if (optlen != TCPOLEN_CC)
2586				continue;
2587			if (!is_syn)
2588				continue;
2589			to->to_flags |= TOF_CCECHO;
2590			bcopy((char *)cp + 2,
2591			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2592			to->to_ccecho = ntohl(to->to_ccecho);
2593			break;
2594#ifdef TCP_SIGNATURE
2595		/*
2596		 * XXX In order to reply to a host which has set the
2597		 * TCP_SIGNATURE option in its initial SYN, we have to
2598		 * record the fact that the option was observed here
2599		 * for the syncache code to perform the correct response.
2600		 */
2601		case TCPOPT_SIGNATURE:
2602			if (optlen != TCPOLEN_SIGNATURE)
2603				continue;
2604			to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2605			break;
2606#endif
2607		default:
2608			continue;
2609		}
2610	}
2611}
2612
2613/*
2614 * Pull out of band byte out of a segment so
2615 * it doesn't appear in the user's data queue.
2616 * It is still reflected in the segment length for
2617 * sequencing purposes.
2618 */
2619static void
2620tcp_pulloutofband(so, th, m, off)
2621	struct socket *so;
2622	struct tcphdr *th;
2623	register struct mbuf *m;
2624	int off;		/* delayed to be droped hdrlen */
2625{
2626	int cnt = off + th->th_urp - 1;
2627
2628	while (cnt >= 0) {
2629		if (m->m_len > cnt) {
2630			char *cp = mtod(m, caddr_t) + cnt;
2631			struct tcpcb *tp = sototcpcb(so);
2632
2633			tp->t_iobc = *cp;
2634			tp->t_oobflags |= TCPOOB_HAVEDATA;
2635			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2636			m->m_len--;
2637			if (m->m_flags & M_PKTHDR)
2638				m->m_pkthdr.len--;
2639			return;
2640		}
2641		cnt -= m->m_len;
2642		m = m->m_next;
2643		if (m == 0)
2644			break;
2645	}
2646	panic("tcp_pulloutofband");
2647}
2648
2649/*
2650 * Collect new round-trip time estimate
2651 * and update averages and current timeout.
2652 */
2653static void
2654tcp_xmit_timer(tp, rtt)
2655	register struct tcpcb *tp;
2656	int rtt;
2657{
2658	register int delta;
2659
2660	tcpstat.tcps_rttupdated++;
2661	tp->t_rttupdated++;
2662	if (tp->t_srtt != 0) {
2663		/*
2664		 * srtt is stored as fixed point with 5 bits after the
2665		 * binary point (i.e., scaled by 8).  The following magic
2666		 * is equivalent to the smoothing algorithm in rfc793 with
2667		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2668		 * point).  Adjust rtt to origin 0.
2669		 */
2670		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2671			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2672
2673		if ((tp->t_srtt += delta) <= 0)
2674			tp->t_srtt = 1;
2675
2676		/*
2677		 * We accumulate a smoothed rtt variance (actually, a
2678		 * smoothed mean difference), then set the retransmit
2679		 * timer to smoothed rtt + 4 times the smoothed variance.
2680		 * rttvar is stored as fixed point with 4 bits after the
2681		 * binary point (scaled by 16).  The following is
2682		 * equivalent to rfc793 smoothing with an alpha of .75
2683		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2684		 * rfc793's wired-in beta.
2685		 */
2686		if (delta < 0)
2687			delta = -delta;
2688		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2689		if ((tp->t_rttvar += delta) <= 0)
2690			tp->t_rttvar = 1;
2691		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2692		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2693	} else {
2694		/*
2695		 * No rtt measurement yet - use the unsmoothed rtt.
2696		 * Set the variance to half the rtt (so our first
2697		 * retransmit happens at 3*rtt).
2698		 */
2699		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2700		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2701		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2702	}
2703	tp->t_rtttime = 0;
2704	tp->t_rxtshift = 0;
2705
2706	/*
2707	 * the retransmit should happen at rtt + 4 * rttvar.
2708	 * Because of the way we do the smoothing, srtt and rttvar
2709	 * will each average +1/2 tick of bias.  When we compute
2710	 * the retransmit timer, we want 1/2 tick of rounding and
2711	 * 1 extra tick because of +-1/2 tick uncertainty in the
2712	 * firing of the timer.  The bias will give us exactly the
2713	 * 1.5 tick we need.  But, because the bias is
2714	 * statistical, we have to test that we don't drop below
2715	 * the minimum feasible timer (which is 2 ticks).
2716	 */
2717	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2718		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2719
2720	/*
2721	 * We received an ack for a packet that wasn't retransmitted;
2722	 * it is probably safe to discard any error indications we've
2723	 * received recently.  This isn't quite right, but close enough
2724	 * for now (a route might have failed after we sent a segment,
2725	 * and the return path might not be symmetrical).
2726	 */
2727	tp->t_softerror = 0;
2728}
2729
2730/*
2731 * Determine a reasonable value for maxseg size.
2732 * If the route is known, check route for mtu.
2733 * If none, use an mss that can be handled on the outgoing
2734 * interface without forcing IP to fragment; if bigger than
2735 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2736 * to utilize large mbufs.  If no route is found, route has no mtu,
2737 * or the destination isn't local, use a default, hopefully conservative
2738 * size (usually 512 or the default IP max size, but no more than the mtu
2739 * of the interface), as we can't discover anything about intervening
2740 * gateways or networks.  We also initialize the congestion/slow start
2741 * window to be a single segment if the destination isn't local.
2742 * While looking at the routing entry, we also initialize other path-dependent
2743 * parameters from pre-set or cached values in the routing entry.
2744 *
2745 * Also take into account the space needed for options that we
2746 * send regularly.  Make maxseg shorter by that amount to assure
2747 * that we can send maxseg amount of data even when the options
2748 * are present.  Store the upper limit of the length of options plus
2749 * data in maxopd.
2750 *
2751 *
2752 * In case of T/TCP, we call this routine during implicit connection
2753 * setup as well (offer = -1), to initialize maxseg from the cached
2754 * MSS of our peer.
2755 *
2756 * NOTE that this routine is only called when we process an incoming
2757 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2758 */
2759void
2760tcp_mss(tp, offer)
2761	struct tcpcb *tp;
2762	int offer;
2763{
2764	int rtt, mss;
2765	u_long bufsize;
2766	u_long maxmtu;
2767	struct inpcb *inp = tp->t_inpcb;
2768	struct socket *so;
2769	struct hc_metrics_lite metrics;
2770	struct rmxp_tao tao;
2771	int origoffer = offer;
2772#ifdef INET6
2773	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2774	size_t min_protoh = isipv6 ?
2775			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2776			    sizeof (struct tcpiphdr);
2777#else
2778	const size_t min_protoh = sizeof(struct tcpiphdr);
2779#endif
2780	bzero(&tao, sizeof(tao));
2781
2782	/* initialize */
2783#ifdef INET6
2784	if (isipv6) {
2785		maxmtu = tcp_maxmtu6(&inp->inp_inc);
2786		tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2787	} else
2788#endif
2789	{
2790		maxmtu = tcp_maxmtu(&inp->inp_inc);
2791		tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2792	}
2793	so = inp->inp_socket;
2794
2795	/*
2796	 * no route to sender, take default mss and return
2797	 */
2798	if (maxmtu == 0)
2799		return;
2800
2801	/* what have we got? */
2802	switch (offer) {
2803		case 0:
2804			/*
2805			 * Offer == 0 means that there was no MSS on the SYN
2806			 * segment, in this case we use tcp_mssdflt.
2807			 */
2808			offer =
2809#ifdef INET6
2810				isipv6 ? tcp_v6mssdflt :
2811#endif
2812				tcp_mssdflt;
2813			break;
2814
2815		case -1:
2816			/*
2817			 * Offer == -1 means that we didn't receive SYN yet,
2818			 * use cached value in that case;
2819			 */
2820			if (tcp_do_rfc1644)
2821				tcp_hc_gettao(&inp->inp_inc, &tao);
2822			if (tao.tao_mssopt != 0)
2823				offer = tao.tao_mssopt;
2824			/* FALLTHROUGH */
2825
2826		default:
2827			/*
2828			 * Prevent DoS attack with too small MSS. Round up
2829			 * to at least minmss.
2830			 */
2831			offer = max(offer, tcp_minmss);
2832			/*
2833			 * Sanity check: make sure that maxopd will be large
2834			 * enough to allow some data on segments even if the
2835			 * all the option space is used (40bytes).  Otherwise
2836			 * funny things may happen in tcp_output.
2837			 */
2838			offer = max(offer, 64);
2839			if (tcp_do_rfc1644)
2840				tcp_hc_updatetao(&inp->inp_inc,
2841						 TCP_HC_TAO_MSSOPT, 0, offer);
2842	}
2843
2844	/*
2845	 * rmx information is now retrieved from tcp_hostcache
2846	 */
2847	tcp_hc_get(&inp->inp_inc, &metrics);
2848
2849	/*
2850	 * if there's a discovered mtu int tcp hostcache, use it
2851	 * else, use the link mtu.
2852	 */
2853	if (metrics.rmx_mtu)
2854		mss = metrics.rmx_mtu - min_protoh;
2855	else {
2856#ifdef INET6
2857		if (isipv6) {
2858			mss = maxmtu - min_protoh;
2859			if (!path_mtu_discovery &&
2860			    !in6_localaddr(&inp->in6p_faddr))
2861				mss = min(mss, tcp_v6mssdflt);
2862		} else
2863#endif
2864		{
2865			mss = maxmtu - min_protoh;
2866			if (!path_mtu_discovery &&
2867			    !in_localaddr(inp->inp_faddr))
2868				mss = min(mss, tcp_mssdflt);
2869		}
2870	}
2871	mss = min(mss, offer);
2872
2873	/*
2874	 * maxopd stores the maximum length of data AND options
2875	 * in a segment; maxseg is the amount of data in a normal
2876	 * segment.  We need to store this value (maxopd) apart
2877	 * from maxseg, because now every segment carries options
2878	 * and thus we normally have somewhat less data in segments.
2879	 */
2880	tp->t_maxopd = mss;
2881
2882	/*
2883	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2884	 * were received yet.  In this case we just guess, otherwise
2885	 * we do the same as before T/TCP.
2886	 */
2887 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2888	    (origoffer == -1 ||
2889	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2890		mss -= TCPOLEN_TSTAMP_APPA;
2891 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2892	    (origoffer == -1 ||
2893	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2894		mss -= TCPOLEN_CC_APPA;
2895	tp->t_maxseg = mss;
2896
2897#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2898		if (mss > MCLBYTES)
2899			mss &= ~(MCLBYTES-1);
2900#else
2901		if (mss > MCLBYTES)
2902			mss = mss / MCLBYTES * MCLBYTES;
2903#endif
2904	tp->t_maxseg = mss;
2905
2906	/*
2907	 * If there's a pipesize, change the socket buffer to that size,
2908	 * don't change if sb_hiwat is different than default (then it
2909	 * has been changed on purpose with setsockopt).
2910	 * Make the socket buffers an integral number of mss units;
2911	 * if the mss is larger than the socket buffer, decrease the mss.
2912	 */
2913	if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2914		bufsize = metrics.rmx_sendpipe;
2915	else
2916		bufsize = so->so_snd.sb_hiwat;
2917	if (bufsize < mss)
2918		mss = bufsize;
2919	else {
2920		bufsize = roundup(bufsize, mss);
2921		if (bufsize > sb_max)
2922			bufsize = sb_max;
2923		if (bufsize > so->so_snd.sb_hiwat)
2924			(void)sbreserve(&so->so_snd, bufsize, so, NULL);
2925	}
2926	tp->t_maxseg = mss;
2927
2928	if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2929		bufsize = metrics.rmx_recvpipe;
2930	else
2931		bufsize = so->so_rcv.sb_hiwat;
2932	if (bufsize > mss) {
2933		bufsize = roundup(bufsize, mss);
2934		if (bufsize > sb_max)
2935			bufsize = sb_max;
2936		if (bufsize > so->so_rcv.sb_hiwat)
2937			(void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2938	}
2939	/*
2940	 * While we're here, check the others too
2941	 */
2942	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
2943		tp->t_srtt = rtt;
2944		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2945		tcpstat.tcps_usedrtt++;
2946		if (metrics.rmx_rttvar) {
2947			tp->t_rttvar = metrics.rmx_rttvar;
2948			tcpstat.tcps_usedrttvar++;
2949		} else {
2950			/* default variation is +- 1 rtt */
2951			tp->t_rttvar =
2952			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2953		}
2954		TCPT_RANGESET(tp->t_rxtcur,
2955			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2956			      tp->t_rttmin, TCPTV_REXMTMAX);
2957	}
2958	if (metrics.rmx_ssthresh) {
2959		/*
2960		 * There's some sort of gateway or interface
2961		 * buffer limit on the path.  Use this to set
2962		 * the slow start threshhold, but set the
2963		 * threshold to no less than 2*mss.
2964		 */
2965		tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
2966		tcpstat.tcps_usedssthresh++;
2967	}
2968	if (metrics.rmx_bandwidth)
2969		tp->snd_bandwidth = metrics.rmx_bandwidth;
2970
2971	/*
2972	 * Set the slow-start flight size depending on whether this
2973	 * is a local network or not.
2974	 *
2975	 * Extend this so we cache the cwnd too and retrieve it here.
2976	 * Make cwnd even bigger than RFC3390 suggests but only if we
2977	 * have previous experience with the remote host. Be careful
2978	 * not make cwnd bigger than remote receive window or our own
2979	 * send socket buffer. Maybe put some additional upper bound
2980	 * on the retrieved cwnd. Should do incremental updates to
2981	 * hostcache when cwnd collapses so next connection doesn't
2982	 * overloads the path again.
2983	 *
2984	 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
2985	 * We currently check only in syncache_socket for that.
2986	 */
2987#define TCP_METRICS_CWND
2988#ifdef TCP_METRICS_CWND
2989	if (metrics.rmx_cwnd)
2990		tp->snd_cwnd = max(mss,
2991				min(metrics.rmx_cwnd / 2,
2992				 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
2993	else
2994#endif
2995	if (tcp_do_rfc3390)
2996		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2997#ifdef INET6
2998	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2999		 (!isipv6 && in_localaddr(inp->inp_faddr)))
3000#else
3001	else if (in_localaddr(inp->inp_faddr))
3002#endif
3003		tp->snd_cwnd = mss * ss_fltsz_local;
3004	else
3005		tp->snd_cwnd = mss * ss_fltsz;
3006}
3007
3008/*
3009 * Determine the MSS option to send on an outgoing SYN.
3010 */
3011int
3012tcp_mssopt(inc)
3013	struct in_conninfo *inc;
3014{
3015	int mss = 0;
3016	u_long maxmtu = 0;
3017	u_long thcmtu = 0;
3018	size_t min_protoh;
3019#ifdef INET6
3020	int isipv6 = inc->inc_isipv6 ? 1 : 0;
3021#endif
3022
3023	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3024
3025#ifdef INET6
3026	if (isipv6) {
3027		mss = tcp_v6mssdflt;
3028		maxmtu = tcp_maxmtu6(inc);
3029		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3030		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3031	} else
3032#endif
3033	{
3034		mss = tcp_mssdflt;
3035		maxmtu = tcp_maxmtu(inc);
3036		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3037		min_protoh = sizeof(struct tcpiphdr);
3038	}
3039	if (maxmtu && thcmtu)
3040		mss = min(maxmtu, thcmtu) - min_protoh;
3041	else if (maxmtu || thcmtu)
3042		mss = max(maxmtu, thcmtu) - min_protoh;
3043
3044	return (mss);
3045}
3046
3047
3048/*
3049 * On a partial ack arrives, force the retransmission of the
3050 * next unacknowledged segment.  Do not clear tp->t_dupacks.
3051 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3052 * be started again.
3053 */
3054static void
3055tcp_newreno_partial_ack(tp, th)
3056	struct tcpcb *tp;
3057	struct tcphdr *th;
3058{
3059	tcp_seq onxt = tp->snd_nxt;
3060	u_long  ocwnd = tp->snd_cwnd;
3061
3062	callout_stop(tp->tt_rexmt);
3063	tp->t_rtttime = 0;
3064	tp->snd_nxt = th->th_ack;
3065	/*
3066	 * Set snd_cwnd to one segment beyond acknowledged offset.
3067	 * (tp->snd_una has not yet been updated when this function is called.)
3068	 */
3069	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3070	tp->t_flags |= TF_ACKNOW;
3071	(void) tcp_output(tp);
3072	tp->snd_cwnd = ocwnd;
3073	if (SEQ_GT(onxt, tp->snd_nxt))
3074		tp->snd_nxt = onxt;
3075	/*
3076	 * Partial window deflation.  Relies on fact that tp->snd_una
3077	 * not updated yet.
3078	 */
3079	tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
3080}
3081
3082/*
3083 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3084 * looking for a pcb in the listen state.  Returns 0 otherwise.
3085 */
3086static int
3087tcp_timewait(tw, to, th, m, tlen)
3088	struct tcptw *tw;
3089	struct tcpopt *to;
3090	struct tcphdr *th;
3091	struct mbuf *m;
3092	int tlen;
3093{
3094	int thflags;
3095	tcp_seq seq;
3096#ifdef INET6
3097	int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3098#else
3099	const int isipv6 = 0;
3100#endif
3101
3102	thflags = th->th_flags;
3103
3104	/*
3105	 * NOTE: for FIN_WAIT_2 (to be added later),
3106	 * must validate sequence number before accepting RST
3107	 */
3108
3109	/*
3110	 * If the segment contains RST:
3111	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
3112	 *      RFC 1337.
3113	 */
3114	if (thflags & TH_RST)
3115		goto drop;
3116
3117	/*
3118	 * If segment contains a SYN and CC [not CC.NEW] option:
3119	 * 	if connection duration > MSL, drop packet and send RST;
3120	 *
3121	 *	if SEG.CC > CCrecv then is new SYN.
3122	 *	    Complete close and delete TCPCB.  Then reprocess
3123	 *	    segment, hoping to find new TCPCB in LISTEN state;
3124	 *
3125	 *	else must be old SYN; drop it.
3126	 * else do normal processing.
3127	 */
3128	if ((thflags & TH_SYN) && (to->to_flags & TOF_CC) && tw->cc_recv != 0) {
3129		if ((ticks - tw->t_starttime) > tcp_msl)
3130			goto reset;
3131		if (CC_GT(to->to_cc, tw->cc_recv)) {
3132			(void) tcp_twclose(tw, 0);
3133			return (1);
3134		}
3135		goto drop;
3136	}
3137
3138#if 0
3139/* PAWS not needed at the moment */
3140	/*
3141	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3142	 * and it's less than ts_recent, drop it.
3143	 */
3144	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3145	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3146		if ((thflags & TH_ACK) == 0)
3147			goto drop;
3148		goto ack;
3149	}
3150	/*
3151	 * ts_recent is never updated because we never accept new segments.
3152	 */
3153#endif
3154
3155	/*
3156	 * If a new connection request is received
3157	 * while in TIME_WAIT, drop the old connection
3158	 * and start over if the sequence numbers
3159	 * are above the previous ones.
3160	 */
3161	if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3162		(void) tcp_twclose(tw, 0);
3163		return (1);
3164	}
3165
3166	/*
3167	 * Drop the the segment if it does not contain an ACK.
3168	 */
3169	if ((thflags & TH_ACK) == 0)
3170		goto drop;
3171
3172	/*
3173	 * Reset the 2MSL timer if this is a duplicate FIN.
3174	 */
3175	if (thflags & TH_FIN) {
3176		seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3177		if (seq + 1 == tw->rcv_nxt)
3178			tcp_timer_2msl_reset(tw, 2 * tcp_msl);
3179	}
3180
3181	/*
3182	 * Acknowledge the segment if it has data or is not a duplicate ACK.
3183	 */
3184	if (thflags != TH_ACK || tlen != 0 ||
3185	    th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3186		tcp_twrespond(tw, TH_ACK);
3187	goto drop;
3188
3189reset:
3190	/*
3191	 * Generate a RST, dropping incoming segment.
3192	 * Make ACK acceptable to originator of segment.
3193	 * Don't bother to respond if destination was broadcast/multicast.
3194	 */
3195	if (m->m_flags & (M_BCAST|M_MCAST))
3196		goto drop;
3197	if (isipv6) {
3198		struct ip6_hdr *ip6;
3199
3200		/* IPv6 anycast check is done at tcp6_input() */
3201		ip6 = mtod(m, struct ip6_hdr *);
3202		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3203		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3204			goto drop;
3205	} else {
3206		struct ip *ip;
3207
3208		ip = mtod(m, struct ip *);
3209		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3210		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3211		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3212		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3213			goto drop;
3214	}
3215	if (thflags & TH_ACK) {
3216		tcp_respond(NULL,
3217		    mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3218	} else {
3219		seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3220		tcp_respond(NULL,
3221		    mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
3222	}
3223	INP_UNLOCK(tw->tw_inpcb);
3224	return (0);
3225
3226drop:
3227	INP_UNLOCK(tw->tw_inpcb);
3228	m_freem(m);
3229	return (0);
3230}
3231