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