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