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