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