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