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