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