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