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