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