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