xref: /freebsd/sys/netinet/tcp_reass.c (revision e0c27215058b5786c78fcfb3963eebe61a989511)
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 && !IN_FASTRECOVERY(tp)))) {
996 				KASSERT(headlocked, ("headlocked"));
997 				INP_INFO_WUNLOCK(&tcbinfo);
998 				/*
999 				 * this is a pure ack for outstanding data.
1000 				 */
1001 				++tcpstat.tcps_predack;
1002 				/*
1003 				 * "bad retransmit" recovery
1004 				 */
1005 				if (tp->t_rxtshift == 1 &&
1006 				    ticks < tp->t_badrxtwin) {
1007 					++tcpstat.tcps_sndrexmitbad;
1008 					tp->snd_cwnd = tp->snd_cwnd_prev;
1009 					tp->snd_ssthresh =
1010 					    tp->snd_ssthresh_prev;
1011 					tp->snd_recover = tp->snd_recover_prev;
1012 					if (tp->t_flags & TF_WASFRECOVERY)
1013 					    ENTER_FASTRECOVERY(tp);
1014 					tp->snd_nxt = tp->snd_max;
1015 					tp->t_badrxtwin = 0;
1016 				}
1017 
1018 				/*
1019 				 * Recalculate the transmit timer / rtt.
1020 				 *
1021 				 * Some boxes send broken timestamp replies
1022 				 * during the SYN+ACK phase, ignore
1023 				 * timestamps of 0 or we could calculate a
1024 				 * huge RTT and blow up the retransmit timer.
1025 				 */
1026 				if ((to.to_flags & TOF_TS) != 0 &&
1027 				    to.to_tsecr) {
1028 					tcp_xmit_timer(tp,
1029 					    ticks - to.to_tsecr + 1);
1030 				} else if (tp->t_rtttime &&
1031 					    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1032 					tcp_xmit_timer(tp,
1033 							ticks - tp->t_rtttime);
1034 				}
1035 				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1036 				acked = th->th_ack - tp->snd_una;
1037 				tcpstat.tcps_rcvackpack++;
1038 				tcpstat.tcps_rcvackbyte += acked;
1039 				sbdrop(&so->so_snd, acked);
1040 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1041 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1042 					tp->snd_recover = th->th_ack - 1;
1043 				tp->snd_una = th->th_ack;
1044 				/*
1045 				 * pull snd_wl2 up to prevent seq wrap relative
1046 				 * to th_ack.
1047 				 */
1048 				tp->snd_wl2 = th->th_ack;
1049 				tp->t_dupacks = 0;
1050 				m_freem(m);
1051 				ND6_HINT(tp); /* some progress has been done */
1052 
1053 				/*
1054 				 * If all outstanding data are acked, stop
1055 				 * retransmit timer, otherwise restart timer
1056 				 * using current (possibly backed-off) value.
1057 				 * If process is waiting for space,
1058 				 * wakeup/selwakeup/signal.  If data
1059 				 * are ready to send, let tcp_output
1060 				 * decide between more output or persist.
1061 				 */
1062 				if (tp->snd_una == tp->snd_max)
1063 					callout_stop(tp->tt_rexmt);
1064 				else if (!callout_active(tp->tt_persist))
1065 					callout_reset(tp->tt_rexmt,
1066 						      tp->t_rxtcur,
1067 						      tcp_timer_rexmt, tp);
1068 
1069 				sowwakeup(so);
1070 				if (so->so_snd.sb_cc)
1071 					(void) tcp_output(tp);
1072 				goto check_delack;
1073 			}
1074 		} else if (th->th_ack == tp->snd_una &&
1075 		    LIST_EMPTY(&tp->t_segq) &&
1076 		    tlen <= sbspace(&so->so_rcv)) {
1077 			KASSERT(headlocked, ("headlocked"));
1078 			INP_INFO_WUNLOCK(&tcbinfo);
1079 			/*
1080 			 * this is a pure, in-sequence data packet
1081 			 * with nothing on the reassembly queue and
1082 			 * we have enough buffer space to take it.
1083 			 */
1084 			++tcpstat.tcps_preddat;
1085 			tp->rcv_nxt += tlen;
1086 			/*
1087 			 * Pull snd_wl1 up to prevent seq wrap relative to
1088 			 * th_seq.
1089 			 */
1090 			tp->snd_wl1 = th->th_seq;
1091 			/*
1092 			 * Pull rcv_up up to prevent seq wrap relative to
1093 			 * rcv_nxt.
1094 			 */
1095 			tp->rcv_up = tp->rcv_nxt;
1096 			tcpstat.tcps_rcvpack++;
1097 			tcpstat.tcps_rcvbyte += tlen;
1098 			ND6_HINT(tp);	/* some progress has been done */
1099 			/*
1100 			 * Add data to socket buffer.
1101 			 */
1102 			if (so->so_state & SS_CANTRCVMORE) {
1103 				m_freem(m);
1104 			} else {
1105 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1106 				sbappend(&so->so_rcv, m);
1107 			}
1108 			sorwakeup(so);
1109 			if (DELAY_ACK(tp)) {
1110 				tp->t_flags |= TF_DELACK;
1111 			} else {
1112 				tp->t_flags |= TF_ACKNOW;
1113 				tcp_output(tp);
1114 			}
1115 			goto check_delack;
1116 		}
1117 	}
1118 
1119 	/*
1120 	 * Calculate amount of space in receive window,
1121 	 * and then do TCP input processing.
1122 	 * Receive window is amount of space in rcv queue,
1123 	 * but not less than advertised window.
1124 	 */
1125 	{ int win;
1126 
1127 	win = sbspace(&so->so_rcv);
1128 	if (win < 0)
1129 		win = 0;
1130 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1131 	}
1132 
1133 	switch (tp->t_state) {
1134 
1135 	/*
1136 	 * If the state is SYN_RECEIVED:
1137 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1138 	 */
1139 	case TCPS_SYN_RECEIVED:
1140 		if ((thflags & TH_ACK) &&
1141 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1142 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1143 				rstreason = BANDLIM_RST_OPENPORT;
1144 				goto dropwithreset;
1145 		}
1146 		break;
1147 
1148 	/*
1149 	 * If the state is SYN_SENT:
1150 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1151 	 *	if seg contains a RST, then drop the connection.
1152 	 *	if seg does not contain SYN, then drop it.
1153 	 * Otherwise this is an acceptable SYN segment
1154 	 *	initialize tp->rcv_nxt and tp->irs
1155 	 *	if seg contains ack then advance tp->snd_una
1156 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1157 	 *	arrange for segment to be acked (eventually)
1158 	 *	continue processing rest of data/controls, beginning with URG
1159 	 */
1160 	case TCPS_SYN_SENT:
1161 		if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1162 			taop = &tao_noncached;
1163 			bzero(taop, sizeof(*taop));
1164 		}
1165 
1166 		if ((thflags & TH_ACK) &&
1167 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1168 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1169 			/*
1170 			 * If we have a cached CCsent for the remote host,
1171 			 * hence we haven't just crashed and restarted,
1172 			 * do not send a RST.  This may be a retransmission
1173 			 * from the other side after our earlier ACK was lost.
1174 			 * Our new SYN, when it arrives, will serve as the
1175 			 * needed ACK.
1176 			 */
1177 			if (taop->tao_ccsent != 0)
1178 				goto drop;
1179 			else {
1180 				rstreason = BANDLIM_UNLIMITED;
1181 				goto dropwithreset;
1182 			}
1183 		}
1184 		if (thflags & TH_RST) {
1185 			if (thflags & TH_ACK)
1186 				tp = tcp_drop(tp, ECONNREFUSED);
1187 			goto drop;
1188 		}
1189 		if ((thflags & TH_SYN) == 0)
1190 			goto drop;
1191 		tp->snd_wnd = th->th_win;	/* initial send window */
1192 		tp->cc_recv = to.to_cc;		/* foreign CC */
1193 
1194 		tp->irs = th->th_seq;
1195 		tcp_rcvseqinit(tp);
1196 		if (thflags & TH_ACK) {
1197 			/*
1198 			 * Our SYN was acked.  If segment contains CC.ECHO
1199 			 * option, check it to make sure this segment really
1200 			 * matches our SYN.  If not, just drop it as old
1201 			 * duplicate, but send an RST if we're still playing
1202 			 * by the old rules.  If no CC.ECHO option, make sure
1203 			 * we don't get fooled into using T/TCP.
1204 			 */
1205 			if (to.to_flags & TOF_CCECHO) {
1206 				if (tp->cc_send != to.to_ccecho) {
1207 					if (taop->tao_ccsent != 0)
1208 						goto drop;
1209 					else {
1210 						rstreason = BANDLIM_UNLIMITED;
1211 						goto dropwithreset;
1212 					}
1213 				}
1214 			} else
1215 				tp->t_flags &= ~TF_RCVD_CC;
1216 			tcpstat.tcps_connects++;
1217 			soisconnected(so);
1218 #ifdef MAC
1219 			mac_set_socket_peer_from_mbuf(m, so);
1220 #endif
1221 			/* Do window scaling on this connection? */
1222 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1223 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1224 				tp->snd_scale = tp->requested_s_scale;
1225 				tp->rcv_scale = tp->request_r_scale;
1226 			}
1227 			/* Segment is acceptable, update cache if undefined. */
1228 			if (taop->tao_ccsent == 0)
1229 				taop->tao_ccsent = to.to_ccecho;
1230 
1231 			tp->rcv_adv += tp->rcv_wnd;
1232 			tp->snd_una++;		/* SYN is acked */
1233 			/*
1234 			 * If there's data, delay ACK; if there's also a FIN
1235 			 * ACKNOW will be turned on later.
1236 			 */
1237 			if (DELAY_ACK(tp) && tlen != 0)
1238                                 callout_reset(tp->tt_delack, tcp_delacktime,
1239                                     tcp_timer_delack, tp);
1240 			else
1241 				tp->t_flags |= TF_ACKNOW;
1242 			/*
1243 			 * Received <SYN,ACK> in SYN_SENT[*] state.
1244 			 * Transitions:
1245 			 *	SYN_SENT  --> ESTABLISHED
1246 			 *	SYN_SENT* --> FIN_WAIT_1
1247 			 */
1248 			tp->t_starttime = ticks;
1249 			if (tp->t_flags & TF_NEEDFIN) {
1250 				tp->t_state = TCPS_FIN_WAIT_1;
1251 				tp->t_flags &= ~TF_NEEDFIN;
1252 				thflags &= ~TH_SYN;
1253 			} else {
1254 				tp->t_state = TCPS_ESTABLISHED;
1255 				callout_reset(tp->tt_keep, tcp_keepidle,
1256 					      tcp_timer_keep, tp);
1257 			}
1258 		} else {
1259 			/*
1260 		 	 * Received initial SYN in SYN-SENT[*] state =>
1261 		 	 * simultaneous open.  If segment contains CC option
1262 		 	 * and there is a cached CC, apply TAO test.
1263 		 	 * If it succeeds, connection is * half-synchronized.
1264 		 	 * Otherwise, do 3-way handshake:
1265 		 	 *        SYN-SENT -> SYN-RECEIVED
1266 		 	 *        SYN-SENT* -> SYN-RECEIVED*
1267 		 	 * If there was no CC option, clear cached CC value.
1268 		 	 */
1269 			tp->t_flags |= TF_ACKNOW;
1270 			callout_stop(tp->tt_rexmt);
1271 			if (to.to_flags & TOF_CC) {
1272 				if (taop->tao_cc != 0 &&
1273 				    CC_GT(to.to_cc, taop->tao_cc)) {
1274 					/*
1275 					 * update cache and make transition:
1276 					 *        SYN-SENT -> ESTABLISHED*
1277 					 *        SYN-SENT* -> FIN-WAIT-1*
1278 					 */
1279 					taop->tao_cc = to.to_cc;
1280 					tp->t_starttime = ticks;
1281 					if (tp->t_flags & TF_NEEDFIN) {
1282 						tp->t_state = TCPS_FIN_WAIT_1;
1283 						tp->t_flags &= ~TF_NEEDFIN;
1284 					} else {
1285 						tp->t_state = TCPS_ESTABLISHED;
1286 						callout_reset(tp->tt_keep,
1287 							      tcp_keepidle,
1288 							      tcp_timer_keep,
1289 							      tp);
1290 					}
1291 					tp->t_flags |= TF_NEEDSYN;
1292 				} else
1293 					tp->t_state = TCPS_SYN_RECEIVED;
1294 			} else {
1295 				/* CC.NEW or no option => invalidate cache */
1296 				taop->tao_cc = 0;
1297 				tp->t_state = TCPS_SYN_RECEIVED;
1298 			}
1299 		}
1300 
1301 trimthenstep6:
1302 		/*
1303 		 * Advance th->th_seq to correspond to first data byte.
1304 		 * If data, trim to stay within window,
1305 		 * dropping FIN if necessary.
1306 		 */
1307 		th->th_seq++;
1308 		if (tlen > tp->rcv_wnd) {
1309 			todrop = tlen - tp->rcv_wnd;
1310 			m_adj(m, -todrop);
1311 			tlen = tp->rcv_wnd;
1312 			thflags &= ~TH_FIN;
1313 			tcpstat.tcps_rcvpackafterwin++;
1314 			tcpstat.tcps_rcvbyteafterwin += todrop;
1315 		}
1316 		tp->snd_wl1 = th->th_seq - 1;
1317 		tp->rcv_up = th->th_seq;
1318 		/*
1319 		 * Client side of transaction: already sent SYN and data.
1320 		 * If the remote host used T/TCP to validate the SYN,
1321 		 * our data will be ACK'd; if so, enter normal data segment
1322 		 * processing in the middle of step 5, ack processing.
1323 		 * Otherwise, goto step 6.
1324 		 */
1325  		if (thflags & TH_ACK)
1326 			goto process_ACK;
1327 
1328 		goto step6;
1329 
1330 	/*
1331 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1332 	 *	if segment contains a SYN and CC [not CC.NEW] option:
1333 	 *              if state == TIME_WAIT and connection duration > MSL,
1334 	 *                  drop packet and send RST;
1335 	 *
1336 	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
1337 	 *		    ack the FIN (and data) in retransmission queue.
1338 	 *                  Complete close and delete TCPCB.  Then reprocess
1339 	 *                  segment, hoping to find new TCPCB in LISTEN state;
1340 	 *
1341 	 *		else must be old SYN; drop it.
1342 	 *      else do normal processing.
1343 	 */
1344 	case TCPS_LAST_ACK:
1345 	case TCPS_CLOSING:
1346 	case TCPS_TIME_WAIT:
1347 		KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1348 		if ((thflags & TH_SYN) &&
1349 		    (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1350 			if (tp->t_state == TCPS_TIME_WAIT &&
1351 					(ticks - tp->t_starttime) > tcp_msl) {
1352 				rstreason = BANDLIM_UNLIMITED;
1353 				goto dropwithreset;
1354 			}
1355 			if (CC_GT(to.to_cc, tp->cc_recv)) {
1356 				tp = tcp_close(tp);
1357 				goto findpcb;
1358 			}
1359 			else
1360 				goto drop;
1361 		}
1362  		break;  /* continue normal processing */
1363 	}
1364 
1365 	/*
1366 	 * States other than LISTEN or SYN_SENT.
1367 	 * First check the RST flag and sequence number since reset segments
1368 	 * are exempt from the timestamp and connection count tests.  This
1369 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1370 	 * below which allowed reset segments in half the sequence space
1371 	 * to fall though and be processed (which gives forged reset
1372 	 * segments with a random sequence number a 50 percent chance of
1373 	 * killing a connection).
1374 	 * Then check timestamp, if present.
1375 	 * Then check the connection count, if present.
1376 	 * Then check that at least some bytes of segment are within
1377 	 * receive window.  If segment begins before rcv_nxt,
1378 	 * drop leading data (and SYN); if nothing left, just ack.
1379 	 *
1380 	 *
1381 	 * If the RST bit is set, check the sequence number to see
1382 	 * if this is a valid reset segment.
1383 	 * RFC 793 page 37:
1384 	 *   In all states except SYN-SENT, all reset (RST) segments
1385 	 *   are validated by checking their SEQ-fields.  A reset is
1386 	 *   valid if its sequence number is in the window.
1387 	 * Note: this does not take into account delayed ACKs, so
1388 	 *   we should test against last_ack_sent instead of rcv_nxt.
1389 	 *   The sequence number in the reset segment is normally an
1390 	 *   echo of our outgoing acknowlegement numbers, but some hosts
1391 	 *   send a reset with the sequence number at the rightmost edge
1392 	 *   of our receive window, and we have to handle this case.
1393 	 * If we have multiple segments in flight, the intial reset
1394 	 * segment sequence numbers will be to the left of last_ack_sent,
1395 	 * but they will eventually catch up.
1396 	 * In any case, it never made sense to trim reset segments to
1397 	 * fit the receive window since RFC 1122 says:
1398 	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1399 	 *
1400 	 *    A TCP SHOULD allow a received RST segment to include data.
1401 	 *
1402 	 *    DISCUSSION
1403 	 *         It has been suggested that a RST segment could contain
1404 	 *         ASCII text that encoded and explained the cause of the
1405 	 *         RST.  No standard has yet been established for such
1406 	 *         data.
1407 	 *
1408 	 * If the reset segment passes the sequence number test examine
1409 	 * the state:
1410 	 *    SYN_RECEIVED STATE:
1411 	 *	If passive open, return to LISTEN state.
1412 	 *	If active open, inform user that connection was refused.
1413 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1414 	 *	Inform user that connection was reset, and close tcb.
1415 	 *    CLOSING, LAST_ACK STATES:
1416 	 *	Close the tcb.
1417 	 *    TIME_WAIT STATE:
1418 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1419 	 *      RFC 1337.
1420 	 */
1421 	if (thflags & TH_RST) {
1422 		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1423 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1424 			switch (tp->t_state) {
1425 
1426 			case TCPS_SYN_RECEIVED:
1427 				so->so_error = ECONNREFUSED;
1428 				goto close;
1429 
1430 			case TCPS_ESTABLISHED:
1431 			case TCPS_FIN_WAIT_1:
1432 			case TCPS_FIN_WAIT_2:
1433 			case TCPS_CLOSE_WAIT:
1434 				so->so_error = ECONNRESET;
1435 			close:
1436 				tp->t_state = TCPS_CLOSED;
1437 				tcpstat.tcps_drops++;
1438 				tp = tcp_close(tp);
1439 				break;
1440 
1441 			case TCPS_CLOSING:
1442 			case TCPS_LAST_ACK:
1443 				tp = tcp_close(tp);
1444 				break;
1445 
1446 			case TCPS_TIME_WAIT:
1447 				KASSERT(tp->t_state != TCPS_TIME_WAIT,
1448 				    ("timewait"));
1449 				break;
1450 			}
1451 		}
1452 		goto drop;
1453 	}
1454 
1455 	/*
1456 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1457 	 * and it's less than ts_recent, drop it.
1458 	 */
1459 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1460 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1461 
1462 		/* Check to see if ts_recent is over 24 days old.  */
1463 		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1464 			/*
1465 			 * Invalidate ts_recent.  If this segment updates
1466 			 * ts_recent, the age will be reset later and ts_recent
1467 			 * will get a valid value.  If it does not, setting
1468 			 * ts_recent to zero will at least satisfy the
1469 			 * requirement that zero be placed in the timestamp
1470 			 * echo reply when ts_recent isn't valid.  The
1471 			 * age isn't reset until we get a valid ts_recent
1472 			 * because we don't want out-of-order segments to be
1473 			 * dropped when ts_recent is old.
1474 			 */
1475 			tp->ts_recent = 0;
1476 		} else {
1477 			tcpstat.tcps_rcvduppack++;
1478 			tcpstat.tcps_rcvdupbyte += tlen;
1479 			tcpstat.tcps_pawsdrop++;
1480 			if (tlen)
1481 				goto dropafterack;
1482 			goto drop;
1483 		}
1484 	}
1485 
1486 	/*
1487 	 * T/TCP mechanism
1488 	 *   If T/TCP was negotiated and the segment doesn't have CC,
1489 	 *   or if its CC is wrong then drop the segment.
1490 	 *   RST segments do not have to comply with this.
1491 	 */
1492 	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1493 	    ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1494  		goto dropafterack;
1495 
1496 	/*
1497 	 * In the SYN-RECEIVED state, validate that the packet belongs to
1498 	 * this connection before trimming the data to fit the receive
1499 	 * window.  Check the sequence number versus IRS since we know
1500 	 * the sequence numbers haven't wrapped.  This is a partial fix
1501 	 * for the "LAND" DoS attack.
1502 	 */
1503 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1504 		rstreason = BANDLIM_RST_OPENPORT;
1505 		goto dropwithreset;
1506 	}
1507 
1508 	todrop = tp->rcv_nxt - th->th_seq;
1509 	if (todrop > 0) {
1510 		if (thflags & TH_SYN) {
1511 			thflags &= ~TH_SYN;
1512 			th->th_seq++;
1513 			if (th->th_urp > 1)
1514 				th->th_urp--;
1515 			else
1516 				thflags &= ~TH_URG;
1517 			todrop--;
1518 		}
1519 		/*
1520 		 * Following if statement from Stevens, vol. 2, p. 960.
1521 		 */
1522 		if (todrop > tlen
1523 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1524 			/*
1525 			 * Any valid FIN must be to the left of the window.
1526 			 * At this point the FIN must be a duplicate or out
1527 			 * of sequence; drop it.
1528 			 */
1529 			thflags &= ~TH_FIN;
1530 
1531 			/*
1532 			 * Send an ACK to resynchronize and drop any data.
1533 			 * But keep on processing for RST or ACK.
1534 			 */
1535 			tp->t_flags |= TF_ACKNOW;
1536 			todrop = tlen;
1537 			tcpstat.tcps_rcvduppack++;
1538 			tcpstat.tcps_rcvdupbyte += todrop;
1539 		} else {
1540 			tcpstat.tcps_rcvpartduppack++;
1541 			tcpstat.tcps_rcvpartdupbyte += todrop;
1542 		}
1543 		drop_hdrlen += todrop;	/* drop from the top afterwards */
1544 		th->th_seq += todrop;
1545 		tlen -= todrop;
1546 		if (th->th_urp > todrop)
1547 			th->th_urp -= todrop;
1548 		else {
1549 			thflags &= ~TH_URG;
1550 			th->th_urp = 0;
1551 		}
1552 	}
1553 
1554 	/*
1555 	 * If new data are received on a connection after the
1556 	 * user processes are gone, then RST the other end.
1557 	 */
1558 	if ((so->so_state & SS_NOFDREF) &&
1559 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1560 		tp = tcp_close(tp);
1561 		tcpstat.tcps_rcvafterclose++;
1562 		rstreason = BANDLIM_UNLIMITED;
1563 		goto dropwithreset;
1564 	}
1565 
1566 	/*
1567 	 * If segment ends after window, drop trailing data
1568 	 * (and PUSH and FIN); if nothing left, just ACK.
1569 	 */
1570 	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1571 	if (todrop > 0) {
1572 		tcpstat.tcps_rcvpackafterwin++;
1573 		if (todrop >= tlen) {
1574 			tcpstat.tcps_rcvbyteafterwin += tlen;
1575 			/*
1576 			 * If a new connection request is received
1577 			 * while in TIME_WAIT, drop the old connection
1578 			 * and start over if the sequence numbers
1579 			 * are above the previous ones.
1580 			 */
1581 			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1582 			if (thflags & TH_SYN &&
1583 			    tp->t_state == TCPS_TIME_WAIT &&
1584 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1585 				tp = tcp_close(tp);
1586 				goto findpcb;
1587 			}
1588 			/*
1589 			 * If window is closed can only take segments at
1590 			 * window edge, and have to drop data and PUSH from
1591 			 * incoming segments.  Continue processing, but
1592 			 * remember to ack.  Otherwise, drop segment
1593 			 * and ack.
1594 			 */
1595 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1596 				tp->t_flags |= TF_ACKNOW;
1597 				tcpstat.tcps_rcvwinprobe++;
1598 			} else
1599 				goto dropafterack;
1600 		} else
1601 			tcpstat.tcps_rcvbyteafterwin += todrop;
1602 		m_adj(m, -todrop);
1603 		tlen -= todrop;
1604 		thflags &= ~(TH_PUSH|TH_FIN);
1605 	}
1606 
1607 	/*
1608 	 * If last ACK falls within this segment's sequence numbers,
1609 	 * record its timestamp.
1610 	 * NOTE that the test is modified according to the latest
1611 	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1612 	 */
1613 	if ((to.to_flags & TOF_TS) != 0 &&
1614 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1615 		tp->ts_recent_age = ticks;
1616 		tp->ts_recent = to.to_tsval;
1617 	}
1618 
1619 	/*
1620 	 * If a SYN is in the window, then this is an
1621 	 * error and we send an RST and drop the connection.
1622 	 */
1623 	if (thflags & TH_SYN) {
1624 		tp = tcp_drop(tp, ECONNRESET);
1625 		rstreason = BANDLIM_UNLIMITED;
1626 		goto dropwithreset;
1627 	}
1628 
1629 	/*
1630 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1631 	 * flag is on (half-synchronized state), then queue data for
1632 	 * later processing; else drop segment and return.
1633 	 */
1634 	if ((thflags & TH_ACK) == 0) {
1635 		if (tp->t_state == TCPS_SYN_RECEIVED ||
1636 		    (tp->t_flags & TF_NEEDSYN))
1637 			goto step6;
1638 		else
1639 			goto drop;
1640 	}
1641 
1642 	/*
1643 	 * Ack processing.
1644 	 */
1645 	switch (tp->t_state) {
1646 
1647 	/*
1648 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1649 	 * ESTABLISHED state and continue processing.
1650 	 * The ACK was checked above.
1651 	 */
1652 	case TCPS_SYN_RECEIVED:
1653 
1654 		tcpstat.tcps_connects++;
1655 		soisconnected(so);
1656 		/* Do window scaling? */
1657 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1658 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1659 			tp->snd_scale = tp->requested_s_scale;
1660 			tp->rcv_scale = tp->request_r_scale;
1661 		}
1662 		/*
1663 		 * Upon successful completion of 3-way handshake,
1664 		 * update cache.CC if it was undefined, pass any queued
1665 		 * data to the user, and advance state appropriately.
1666 		 */
1667 		if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1668 		    taop->tao_cc == 0)
1669 			taop->tao_cc = tp->cc_recv;
1670 
1671 		/*
1672 		 * Make transitions:
1673 		 *      SYN-RECEIVED  -> ESTABLISHED
1674 		 *      SYN-RECEIVED* -> FIN-WAIT-1
1675 		 */
1676 		tp->t_starttime = ticks;
1677 		if (tp->t_flags & TF_NEEDFIN) {
1678 			tp->t_state = TCPS_FIN_WAIT_1;
1679 			tp->t_flags &= ~TF_NEEDFIN;
1680 		} else {
1681 			tp->t_state = TCPS_ESTABLISHED;
1682 			callout_reset(tp->tt_keep, tcp_keepidle,
1683 				      tcp_timer_keep, tp);
1684 		}
1685 		/*
1686 		 * If segment contains data or ACK, will call tcp_reass()
1687 		 * later; if not, do so now to pass queued data to user.
1688 		 */
1689 		if (tlen == 0 && (thflags & TH_FIN) == 0)
1690 			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1691 			    (struct mbuf *)0);
1692 		tp->snd_wl1 = th->th_seq - 1;
1693 		/* FALLTHROUGH */
1694 
1695 	/*
1696 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1697 	 * ACKs.  If the ack is in the range
1698 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1699 	 * then advance tp->snd_una to th->th_ack and drop
1700 	 * data from the retransmission queue.  If this ACK reflects
1701 	 * more up to date window information we update our window information.
1702 	 */
1703 	case TCPS_ESTABLISHED:
1704 	case TCPS_FIN_WAIT_1:
1705 	case TCPS_FIN_WAIT_2:
1706 	case TCPS_CLOSE_WAIT:
1707 	case TCPS_CLOSING:
1708 	case TCPS_LAST_ACK:
1709 	case TCPS_TIME_WAIT:
1710 		KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1711 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1712 			if (tlen == 0 && tiwin == tp->snd_wnd) {
1713 				tcpstat.tcps_rcvdupack++;
1714 				/*
1715 				 * If we have outstanding data (other than
1716 				 * a window probe), this is a completely
1717 				 * duplicate ack (ie, window info didn't
1718 				 * change), the ack is the biggest we've
1719 				 * seen and we've seen exactly our rexmt
1720 				 * threshhold of them, assume a packet
1721 				 * has been dropped and retransmit it.
1722 				 * Kludge snd_nxt & the congestion
1723 				 * window so we send only this one
1724 				 * packet.
1725 				 *
1726 				 * We know we're losing at the current
1727 				 * window size so do congestion avoidance
1728 				 * (set ssthresh to half the current window
1729 				 * and pull our congestion window back to
1730 				 * the new ssthresh).
1731 				 *
1732 				 * Dup acks mean that packets have left the
1733 				 * network (they're now cached at the receiver)
1734 				 * so bump cwnd by the amount in the receiver
1735 				 * to keep a constant cwnd packets in the
1736 				 * network.
1737 				 */
1738 				if (!callout_active(tp->tt_rexmt) ||
1739 				    th->th_ack != tp->snd_una)
1740 					tp->t_dupacks = 0;
1741 				else if (++tp->t_dupacks > tcprexmtthresh ||
1742 					 (tcp_do_newreno &&
1743 					  IN_FASTRECOVERY(tp))) {
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,
1752 					            tp->snd_recover)) {
1753 						tp->t_dupacks = 0;
1754 						break;
1755 					}
1756 					win = min(tp->snd_wnd, tp->snd_cwnd) /
1757 					    2 / tp->t_maxseg;
1758 					if (win < 2)
1759 						win = 2;
1760 					tp->snd_ssthresh = win * tp->t_maxseg;
1761 					ENTER_FASTRECOVERY(tp);
1762 					tp->snd_recover = tp->snd_max;
1763 					callout_stop(tp->tt_rexmt);
1764 					tp->t_rtttime = 0;
1765 					tp->snd_nxt = th->th_ack;
1766 					tp->snd_cwnd = tp->t_maxseg;
1767 					(void) tcp_output(tp);
1768 					KASSERT(tp->snd_limited <= 2,
1769 					    ("tp->snd_limited too big"));
1770 					tp->snd_cwnd = tp->snd_ssthresh +
1771 					     tp->t_maxseg *
1772 					     (tp->t_dupacks - tp->snd_limited);
1773 					if (SEQ_GT(onxt, tp->snd_nxt))
1774 						tp->snd_nxt = onxt;
1775 					goto drop;
1776 				} else if (tcp_do_rfc3042) {
1777 					u_long oldcwnd = tp->snd_cwnd;
1778 					tcp_seq oldsndmax = tp->snd_max;
1779 					u_int sent;
1780 					KASSERT(tp->t_dupacks == 1 ||
1781 					    tp->t_dupacks == 2,
1782 					    ("dupacks not 1 or 2"));
1783 					if (tp->t_dupacks == 1) {
1784 						tp->snd_limited = 0;
1785 						tp->snd_cwnd += tp->t_maxseg;
1786 					} else {
1787 						tp->snd_cwnd +=
1788 						    tp->t_maxseg * 2;
1789 					}
1790 					(void) tcp_output(tp);
1791 					sent = tp->snd_max - oldsndmax;
1792 					if (sent > tp->t_maxseg) {
1793 						KASSERT(tp->snd_limited == 0 &&
1794 						    tp->t_dupacks == 2,
1795 						    ("sent too much"));
1796 						tp->snd_limited = 2;
1797 					} else if (sent > 0)
1798 						++tp->snd_limited;
1799 					tp->snd_cwnd = oldcwnd;
1800 					goto drop;
1801 				}
1802 			} else
1803 				tp->t_dupacks = 0;
1804 			break;
1805 		}
1806 
1807 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1808 
1809 		/*
1810 		 * If the congestion window was inflated to account
1811 		 * for the other side's cached packets, retract it.
1812 		 */
1813 		if (tcp_do_newreno) {
1814 			if (IN_FASTRECOVERY(tp)) {
1815 				if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1816 					tcp_newreno_partial_ack(tp, th);
1817 				} else {
1818 					/*
1819 					 * Window inflation should have left us
1820 					 * with approximately snd_ssthresh
1821 					 * outstanding data.
1822 					 * But in case we would be inclined to
1823 					 * send a burst, better to do it via
1824 					 * the slow start mechanism.
1825 					 */
1826 					if (SEQ_GT(th->th_ack +
1827 							tp->snd_ssthresh,
1828 						   tp->snd_max))
1829 						tp->snd_cwnd = tp->snd_max -
1830 								th->th_ack +
1831 								tp->t_maxseg;
1832 					else
1833 						tp->snd_cwnd = tp->snd_ssthresh;
1834 				}
1835 			}
1836                 } else {
1837                         if (tp->t_dupacks >= tcprexmtthresh &&
1838                             tp->snd_cwnd > tp->snd_ssthresh)
1839 				tp->snd_cwnd = tp->snd_ssthresh;
1840                 }
1841 		tp->t_dupacks = 0;
1842 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1843 			tcpstat.tcps_rcvacktoomuch++;
1844 			goto dropafterack;
1845 		}
1846 		/*
1847 		 * If we reach this point, ACK is not a duplicate,
1848 		 *     i.e., it ACKs something we sent.
1849 		 */
1850 		if (tp->t_flags & TF_NEEDSYN) {
1851 			/*
1852 			 * T/TCP: Connection was half-synchronized, and our
1853 			 * SYN has been ACK'd (so connection is now fully
1854 			 * synchronized).  Go to non-starred state,
1855 			 * increment snd_una for ACK of SYN, and check if
1856 			 * we can do window scaling.
1857 			 */
1858 			tp->t_flags &= ~TF_NEEDSYN;
1859 			tp->snd_una++;
1860 			/* Do window scaling? */
1861 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1862 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1863 				tp->snd_scale = tp->requested_s_scale;
1864 				tp->rcv_scale = tp->request_r_scale;
1865 			}
1866 		}
1867 
1868 process_ACK:
1869 		acked = th->th_ack - tp->snd_una;
1870 		tcpstat.tcps_rcvackpack++;
1871 		tcpstat.tcps_rcvackbyte += acked;
1872 
1873 		/*
1874 		 * If we just performed our first retransmit, and the ACK
1875 		 * arrives within our recovery window, then it was a mistake
1876 		 * to do the retransmit in the first place.  Recover our
1877 		 * original cwnd and ssthresh, and proceed to transmit where
1878 		 * we left off.
1879 		 */
1880 		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1881 			++tcpstat.tcps_sndrexmitbad;
1882 			tp->snd_cwnd = tp->snd_cwnd_prev;
1883 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
1884 			tp->snd_recover = tp->snd_recover_prev;
1885 			if (tp->t_flags & TF_WASFRECOVERY)
1886 				ENTER_FASTRECOVERY(tp);
1887 			tp->snd_nxt = tp->snd_max;
1888 			tp->t_badrxtwin = 0;	/* XXX probably not required */
1889 		}
1890 
1891 		/*
1892 		 * If we have a timestamp reply, update smoothed
1893 		 * round trip time.  If no timestamp is present but
1894 		 * transmit timer is running and timed sequence
1895 		 * number was acked, update smoothed round trip time.
1896 		 * Since we now have an rtt measurement, cancel the
1897 		 * timer backoff (cf., Phil Karn's retransmit alg.).
1898 		 * Recompute the initial retransmit timer.
1899 		 *
1900 		 * Some boxes send broken timestamp replies
1901 		 * during the SYN+ACK phase, ignore
1902 		 * timestamps of 0 or we could calculate a
1903 		 * huge RTT and blow up the retransmit timer.
1904 		 */
1905 		if ((to.to_flags & TOF_TS) != 0 &&
1906 		    to.to_tsecr) {
1907 			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1908 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1909 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1910 		}
1911 		tcp_xmit_bandwidth_limit(tp, th->th_ack);
1912 
1913 		/*
1914 		 * If all outstanding data is acked, stop retransmit
1915 		 * timer and remember to restart (more output or persist).
1916 		 * If there is more data to be acked, restart retransmit
1917 		 * timer, using current (possibly backed-off) value.
1918 		 */
1919 		if (th->th_ack == tp->snd_max) {
1920 			callout_stop(tp->tt_rexmt);
1921 			needoutput = 1;
1922 		} else if (!callout_active(tp->tt_persist))
1923 			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1924 				      tcp_timer_rexmt, tp);
1925 
1926 		/*
1927 		 * If no data (only SYN) was ACK'd,
1928 		 *    skip rest of ACK processing.
1929 		 */
1930 		if (acked == 0)
1931 			goto step6;
1932 
1933 		/*
1934 		 * When new data is acked, open the congestion window.
1935 		 * If the window gives us less than ssthresh packets
1936 		 * in flight, open exponentially (maxseg per packet).
1937 		 * Otherwise open linearly: maxseg per window
1938 		 * (maxseg^2 / cwnd per packet).
1939 		 */
1940 		if (!tcp_do_newreno || !IN_FASTRECOVERY(tp)) {
1941 			register u_int cw = tp->snd_cwnd;
1942 			register u_int incr = tp->t_maxseg;
1943 			if (cw > tp->snd_ssthresh)
1944 				incr = incr * incr / cw;
1945 			tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1946 		}
1947 		if (acked > so->so_snd.sb_cc) {
1948 			tp->snd_wnd -= so->so_snd.sb_cc;
1949 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1950 			ourfinisacked = 1;
1951 		} else {
1952 			sbdrop(&so->so_snd, acked);
1953 			tp->snd_wnd -= acked;
1954 			ourfinisacked = 0;
1955 		}
1956 		sowwakeup(so);
1957 		/* detect una wraparound */
1958 		if (tcp_do_newreno && !IN_FASTRECOVERY(tp) &&
1959 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
1960 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
1961 			tp->snd_recover = th->th_ack - 1;
1962 		if (tcp_do_newreno && IN_FASTRECOVERY(tp) &&
1963 		    SEQ_GEQ(th->th_ack, tp->snd_recover))
1964 			EXIT_FASTRECOVERY(tp);
1965 		tp->snd_una = th->th_ack;
1966 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1967 			tp->snd_nxt = tp->snd_una;
1968 
1969 		switch (tp->t_state) {
1970 
1971 		/*
1972 		 * In FIN_WAIT_1 STATE in addition to the processing
1973 		 * for the ESTABLISHED state if our FIN is now acknowledged
1974 		 * then enter FIN_WAIT_2.
1975 		 */
1976 		case TCPS_FIN_WAIT_1:
1977 			if (ourfinisacked) {
1978 				/*
1979 				 * If we can't receive any more
1980 				 * data, then closing user can proceed.
1981 				 * Starting the timer is contrary to the
1982 				 * specification, but if we don't get a FIN
1983 				 * we'll hang forever.
1984 				 */
1985 		/* XXXjl
1986 		 * we should release the tp also, and use a
1987 		 * compressed state.
1988 		 */
1989 				if (so->so_state & SS_CANTRCVMORE) {
1990 					soisdisconnected(so);
1991 					callout_reset(tp->tt_2msl, tcp_maxidle,
1992 						      tcp_timer_2msl, tp);
1993 				}
1994 				tp->t_state = TCPS_FIN_WAIT_2;
1995 			}
1996 			break;
1997 
1998 	 	/*
1999 		 * In CLOSING STATE in addition to the processing for
2000 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2001 		 * then enter the TIME-WAIT state, otherwise ignore
2002 		 * the segment.
2003 		 */
2004 		case TCPS_CLOSING:
2005 			if (ourfinisacked) {
2006 				KASSERT(headlocked, ("headlocked"));
2007 				tcp_twstart(tp);
2008 				INP_INFO_WUNLOCK(&tcbinfo);
2009 				m_freem(m);
2010 				return;
2011 			}
2012 			break;
2013 
2014 		/*
2015 		 * In LAST_ACK, we may still be waiting for data to drain
2016 		 * and/or to be acked, as well as for the ack of our FIN.
2017 		 * If our FIN is now acknowledged, delete the TCB,
2018 		 * enter the closed state and return.
2019 		 */
2020 		case TCPS_LAST_ACK:
2021 			if (ourfinisacked) {
2022 				tp = tcp_close(tp);
2023 				goto drop;
2024 			}
2025 			break;
2026 
2027 		/*
2028 		 * In TIME_WAIT state the only thing that should arrive
2029 		 * is a retransmission of the remote FIN.  Acknowledge
2030 		 * it and restart the finack timer.
2031 		 */
2032 		case TCPS_TIME_WAIT:
2033 			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2034 			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2035 				      tcp_timer_2msl, tp);
2036 			goto dropafterack;
2037 		}
2038 	}
2039 
2040 step6:
2041 	/*
2042 	 * Update window information.
2043 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2044 	 */
2045 	if ((thflags & TH_ACK) &&
2046 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2047 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2048 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2049 		/* keep track of pure window updates */
2050 		if (tlen == 0 &&
2051 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2052 			tcpstat.tcps_rcvwinupd++;
2053 		tp->snd_wnd = tiwin;
2054 		tp->snd_wl1 = th->th_seq;
2055 		tp->snd_wl2 = th->th_ack;
2056 		if (tp->snd_wnd > tp->max_sndwnd)
2057 			tp->max_sndwnd = tp->snd_wnd;
2058 		needoutput = 1;
2059 	}
2060 
2061 	/*
2062 	 * Process segments with URG.
2063 	 */
2064 	if ((thflags & TH_URG) && th->th_urp &&
2065 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2066 		/*
2067 		 * This is a kludge, but if we receive and accept
2068 		 * random urgent pointers, we'll crash in
2069 		 * soreceive.  It's hard to imagine someone
2070 		 * actually wanting to send this much urgent data.
2071 		 */
2072 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2073 			th->th_urp = 0;			/* XXX */
2074 			thflags &= ~TH_URG;		/* XXX */
2075 			goto dodata;			/* XXX */
2076 		}
2077 		/*
2078 		 * If this segment advances the known urgent pointer,
2079 		 * then mark the data stream.  This should not happen
2080 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2081 		 * a FIN has been received from the remote side.
2082 		 * In these states we ignore the URG.
2083 		 *
2084 		 * According to RFC961 (Assigned Protocols),
2085 		 * the urgent pointer points to the last octet
2086 		 * of urgent data.  We continue, however,
2087 		 * to consider it to indicate the first octet
2088 		 * of data past the urgent section as the original
2089 		 * spec states (in one of two places).
2090 		 */
2091 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2092 			tp->rcv_up = th->th_seq + th->th_urp;
2093 			so->so_oobmark = so->so_rcv.sb_cc +
2094 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2095 			if (so->so_oobmark == 0)
2096 				so->so_state |= SS_RCVATMARK;
2097 			sohasoutofband(so);
2098 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2099 		}
2100 		/*
2101 		 * Remove out of band data so doesn't get presented to user.
2102 		 * This can happen independent of advancing the URG pointer,
2103 		 * but if two URG's are pending at once, some out-of-band
2104 		 * data may creep in... ick.
2105 		 */
2106 		if (th->th_urp <= (u_long)tlen &&
2107 		    !(so->so_options & SO_OOBINLINE)) {
2108 			/* hdr drop is delayed */
2109 			tcp_pulloutofband(so, th, m, drop_hdrlen);
2110 		}
2111 	} else {
2112 		/*
2113 		 * If no out of band data is expected,
2114 		 * pull receive urgent pointer along
2115 		 * with the receive window.
2116 		 */
2117 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2118 			tp->rcv_up = tp->rcv_nxt;
2119 	}
2120 dodata:							/* XXX */
2121 	KASSERT(headlocked, ("headlocked"));
2122 	/*
2123 	 * Process the segment text, merging it into the TCP sequencing queue,
2124 	 * and arranging for acknowledgment of receipt if necessary.
2125 	 * This process logically involves adjusting tp->rcv_wnd as data
2126 	 * is presented to the user (this happens in tcp_usrreq.c,
2127 	 * case PRU_RCVD).  If a FIN has already been received on this
2128 	 * connection then we just ignore the text.
2129 	 */
2130 	if ((tlen || (thflags & TH_FIN)) &&
2131 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2132 		m_adj(m, drop_hdrlen);	/* delayed header drop */
2133 		/*
2134 		 * Insert segment which includes th into TCP reassembly queue
2135 		 * with control block tp.  Set thflags to whether reassembly now
2136 		 * includes a segment with FIN.  This handles the common case
2137 		 * inline (segment is the next to be received on an established
2138 		 * connection, and the queue is empty), avoiding linkage into
2139 		 * and removal from the queue and repetition of various
2140 		 * conversions.
2141 		 * Set DELACK for segments received in order, but ack
2142 		 * immediately when segments are out of order (so
2143 		 * fast retransmit can work).
2144 		 */
2145 		if (th->th_seq == tp->rcv_nxt &&
2146 		    LIST_EMPTY(&tp->t_segq) &&
2147 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2148 			if (DELAY_ACK(tp))
2149 				tp->t_flags |= TF_DELACK;
2150 			else
2151 				tp->t_flags |= TF_ACKNOW;
2152 			tp->rcv_nxt += tlen;
2153 			thflags = th->th_flags & TH_FIN;
2154 			tcpstat.tcps_rcvpack++;
2155 			tcpstat.tcps_rcvbyte += tlen;
2156 			ND6_HINT(tp);
2157 			if (so->so_state & SS_CANTRCVMORE)
2158 				m_freem(m);
2159 			else
2160 				sbappend(&so->so_rcv, m);
2161 			sorwakeup(so);
2162 		} else {
2163 			thflags = tcp_reass(tp, th, &tlen, m);
2164 			tp->t_flags |= TF_ACKNOW;
2165 		}
2166 
2167 		/*
2168 		 * Note the amount of data that peer has sent into
2169 		 * our window, in order to estimate the sender's
2170 		 * buffer size.
2171 		 */
2172 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2173 	} else {
2174 		m_freem(m);
2175 		thflags &= ~TH_FIN;
2176 	}
2177 
2178 	/*
2179 	 * If FIN is received ACK the FIN and let the user know
2180 	 * that the connection is closing.
2181 	 */
2182 	if (thflags & TH_FIN) {
2183 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2184 			socantrcvmore(so);
2185 			/*
2186 			 * If connection is half-synchronized
2187 			 * (ie NEEDSYN flag on) then delay ACK,
2188 			 * so it may be piggybacked when SYN is sent.
2189 			 * Otherwise, since we received a FIN then no
2190 			 * more input can be expected, send ACK now.
2191 			 */
2192 			if (tp->t_flags & TF_NEEDSYN)
2193 				tp->t_flags |= TF_DELACK;
2194 			else
2195 				tp->t_flags |= TF_ACKNOW;
2196 			tp->rcv_nxt++;
2197 		}
2198 		switch (tp->t_state) {
2199 
2200 	 	/*
2201 		 * In SYN_RECEIVED and ESTABLISHED STATES
2202 		 * enter the CLOSE_WAIT state.
2203 		 */
2204 		case TCPS_SYN_RECEIVED:
2205 			tp->t_starttime = ticks;
2206 			/*FALLTHROUGH*/
2207 		case TCPS_ESTABLISHED:
2208 			tp->t_state = TCPS_CLOSE_WAIT;
2209 			break;
2210 
2211 	 	/*
2212 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2213 		 * enter the CLOSING state.
2214 		 */
2215 		case TCPS_FIN_WAIT_1:
2216 			tp->t_state = TCPS_CLOSING;
2217 			break;
2218 
2219 	 	/*
2220 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2221 		 * starting the time-wait timer, turning off the other
2222 		 * standard timers.
2223 		 */
2224 		case TCPS_FIN_WAIT_2:
2225 			KASSERT(headlocked == 1, ("headlocked should be 1"));
2226 			tcp_twstart(tp);
2227 			INP_INFO_WUNLOCK(&tcbinfo);
2228 			return;
2229 
2230 		/*
2231 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2232 		 */
2233 		case TCPS_TIME_WAIT:
2234 			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2235 			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2236 				      tcp_timer_2msl, tp);
2237 			break;
2238 		}
2239 	}
2240 	INP_INFO_WUNLOCK(&tcbinfo);
2241 #ifdef TCPDEBUG
2242 	if (so->so_options & SO_DEBUG)
2243 		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2244 			  &tcp_savetcp, 0);
2245 #endif
2246 
2247 	/*
2248 	 * Return any desired output.
2249 	 */
2250 	if (needoutput || (tp->t_flags & TF_ACKNOW))
2251 		(void) tcp_output(tp);
2252 
2253 check_delack:
2254 	if (tp->t_flags & TF_DELACK) {
2255 		tp->t_flags &= ~TF_DELACK;
2256 		callout_reset(tp->tt_delack, tcp_delacktime,
2257 		    tcp_timer_delack, tp);
2258 	}
2259 	INP_UNLOCK(inp);
2260 	return;
2261 
2262 dropafterack:
2263 	/*
2264 	 * Generate an ACK dropping incoming segment if it occupies
2265 	 * sequence space, where the ACK reflects our state.
2266 	 *
2267 	 * We can now skip the test for the RST flag since all
2268 	 * paths to this code happen after packets containing
2269 	 * RST have been dropped.
2270 	 *
2271 	 * In the SYN-RECEIVED state, don't send an ACK unless the
2272 	 * segment we received passes the SYN-RECEIVED ACK test.
2273 	 * If it fails send a RST.  This breaks the loop in the
2274 	 * "LAND" DoS attack, and also prevents an ACK storm
2275 	 * between two listening ports that have been sent forged
2276 	 * SYN segments, each with the source address of the other.
2277 	 */
2278 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2279 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2280 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2281 		rstreason = BANDLIM_RST_OPENPORT;
2282 		goto dropwithreset;
2283 	}
2284 #ifdef TCPDEBUG
2285 	if (so->so_options & SO_DEBUG)
2286 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2287 			  &tcp_savetcp, 0);
2288 #endif
2289 	KASSERT(headlocked, ("headlocked should be 1"));
2290 	INP_INFO_WUNLOCK(&tcbinfo);
2291 	m_freem(m);
2292 	tp->t_flags |= TF_ACKNOW;
2293 	(void) tcp_output(tp);
2294 	INP_UNLOCK(inp);
2295 	return;
2296 
2297 dropwithreset:
2298 	/*
2299 	 * Generate a RST, dropping incoming segment.
2300 	 * Make ACK acceptable to originator of segment.
2301 	 * Don't bother to respond if destination was broadcast/multicast.
2302 	 */
2303 	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2304 		goto drop;
2305 	if (isipv6) {
2306 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2307 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2308 			goto drop;
2309 	} else {
2310 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2311 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2312 	    	    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2313 	    	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2314 			goto drop;
2315 	}
2316 	/* IPv6 anycast check is done at tcp6_input() */
2317 
2318 	/*
2319 	 * Perform bandwidth limiting.
2320 	 */
2321 	if (badport_bandlim(rstreason) < 0)
2322 		goto drop;
2323 
2324 #ifdef TCPDEBUG
2325 	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2326 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2327 			  &tcp_savetcp, 0);
2328 #endif
2329 
2330 	if (tp)
2331 		INP_UNLOCK(inp);
2332 
2333 	if (thflags & TH_ACK)
2334 		/* mtod() below is safe as long as hdr dropping is delayed */
2335 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2336 			    TH_RST);
2337 	else {
2338 		if (thflags & TH_SYN)
2339 			tlen++;
2340 		/* mtod() below is safe as long as hdr dropping is delayed */
2341 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2342 			    (tcp_seq)0, TH_RST|TH_ACK);
2343 	}
2344 	if (headlocked)
2345 		INP_INFO_WUNLOCK(&tcbinfo);
2346 	return;
2347 
2348 drop:
2349 	/*
2350 	 * Drop space held by incoming segment and return.
2351 	 */
2352 #ifdef TCPDEBUG
2353 	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2354 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2355 			  &tcp_savetcp, 0);
2356 #endif
2357 	if (tp)
2358 		INP_UNLOCK(inp);
2359 	m_freem(m);
2360 	if (headlocked)
2361 		INP_INFO_WUNLOCK(&tcbinfo);
2362 	return;
2363 }
2364 
2365 /*
2366  * Parse TCP options and place in tcpopt.
2367  */
2368 static void
2369 tcp_dooptions(to, cp, cnt, is_syn)
2370 	struct tcpopt *to;
2371 	u_char *cp;
2372 	int cnt;
2373 	int is_syn;
2374 {
2375 	int opt, optlen;
2376 
2377 	to->to_flags = 0;
2378 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2379 		opt = cp[0];
2380 		if (opt == TCPOPT_EOL)
2381 			break;
2382 		if (opt == TCPOPT_NOP)
2383 			optlen = 1;
2384 		else {
2385 			if (cnt < 2)
2386 				break;
2387 			optlen = cp[1];
2388 			if (optlen < 2 || optlen > cnt)
2389 				break;
2390 		}
2391 		switch (opt) {
2392 		case TCPOPT_MAXSEG:
2393 			if (optlen != TCPOLEN_MAXSEG)
2394 				continue;
2395 			if (!is_syn)
2396 				continue;
2397 			to->to_flags |= TOF_MSS;
2398 			bcopy((char *)cp + 2,
2399 			    (char *)&to->to_mss, sizeof(to->to_mss));
2400 			to->to_mss = ntohs(to->to_mss);
2401 			break;
2402 		case TCPOPT_WINDOW:
2403 			if (optlen != TCPOLEN_WINDOW)
2404 				continue;
2405 			if (! is_syn)
2406 				continue;
2407 			to->to_flags |= TOF_SCALE;
2408 			to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2409 			break;
2410 		case TCPOPT_TIMESTAMP:
2411 			if (optlen != TCPOLEN_TIMESTAMP)
2412 				continue;
2413 			to->to_flags |= TOF_TS;
2414 			bcopy((char *)cp + 2,
2415 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2416 			to->to_tsval = ntohl(to->to_tsval);
2417 			bcopy((char *)cp + 6,
2418 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2419 			to->to_tsecr = ntohl(to->to_tsecr);
2420 			break;
2421 		case TCPOPT_CC:
2422 			if (optlen != TCPOLEN_CC)
2423 				continue;
2424 			to->to_flags |= TOF_CC;
2425 			bcopy((char *)cp + 2,
2426 			    (char *)&to->to_cc, sizeof(to->to_cc));
2427 			to->to_cc = ntohl(to->to_cc);
2428 			break;
2429 		case TCPOPT_CCNEW:
2430 			if (optlen != TCPOLEN_CC)
2431 				continue;
2432 			if (!is_syn)
2433 				continue;
2434 			to->to_flags |= TOF_CCNEW;
2435 			bcopy((char *)cp + 2,
2436 			    (char *)&to->to_cc, sizeof(to->to_cc));
2437 			to->to_cc = ntohl(to->to_cc);
2438 			break;
2439 		case TCPOPT_CCECHO:
2440 			if (optlen != TCPOLEN_CC)
2441 				continue;
2442 			if (!is_syn)
2443 				continue;
2444 			to->to_flags |= TOF_CCECHO;
2445 			bcopy((char *)cp + 2,
2446 			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2447 			to->to_ccecho = ntohl(to->to_ccecho);
2448 			break;
2449 		default:
2450 			continue;
2451 		}
2452 	}
2453 }
2454 
2455 /*
2456  * Pull out of band byte out of a segment so
2457  * it doesn't appear in the user's data queue.
2458  * It is still reflected in the segment length for
2459  * sequencing purposes.
2460  */
2461 static void
2462 tcp_pulloutofband(so, th, m, off)
2463 	struct socket *so;
2464 	struct tcphdr *th;
2465 	register struct mbuf *m;
2466 	int off;		/* delayed to be droped hdrlen */
2467 {
2468 	int cnt = off + th->th_urp - 1;
2469 
2470 	while (cnt >= 0) {
2471 		if (m->m_len > cnt) {
2472 			char *cp = mtod(m, caddr_t) + cnt;
2473 			struct tcpcb *tp = sototcpcb(so);
2474 
2475 			tp->t_iobc = *cp;
2476 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2477 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2478 			m->m_len--;
2479 			if (m->m_flags & M_PKTHDR)
2480 				m->m_pkthdr.len--;
2481 			return;
2482 		}
2483 		cnt -= m->m_len;
2484 		m = m->m_next;
2485 		if (m == 0)
2486 			break;
2487 	}
2488 	panic("tcp_pulloutofband");
2489 }
2490 
2491 /*
2492  * Collect new round-trip time estimate
2493  * and update averages and current timeout.
2494  */
2495 static void
2496 tcp_xmit_timer(tp, rtt)
2497 	register struct tcpcb *tp;
2498 	int rtt;
2499 {
2500 	register int delta;
2501 
2502 	tcpstat.tcps_rttupdated++;
2503 	tp->t_rttupdated++;
2504 	if (tp->t_srtt != 0) {
2505 		/*
2506 		 * srtt is stored as fixed point with 5 bits after the
2507 		 * binary point (i.e., scaled by 8).  The following magic
2508 		 * is equivalent to the smoothing algorithm in rfc793 with
2509 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2510 		 * point).  Adjust rtt to origin 0.
2511 		 */
2512 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2513 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2514 
2515 		if ((tp->t_srtt += delta) <= 0)
2516 			tp->t_srtt = 1;
2517 
2518 		/*
2519 		 * We accumulate a smoothed rtt variance (actually, a
2520 		 * smoothed mean difference), then set the retransmit
2521 		 * timer to smoothed rtt + 4 times the smoothed variance.
2522 		 * rttvar is stored as fixed point with 4 bits after the
2523 		 * binary point (scaled by 16).  The following is
2524 		 * equivalent to rfc793 smoothing with an alpha of .75
2525 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2526 		 * rfc793's wired-in beta.
2527 		 */
2528 		if (delta < 0)
2529 			delta = -delta;
2530 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2531 		if ((tp->t_rttvar += delta) <= 0)
2532 			tp->t_rttvar = 1;
2533 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2534 		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2535 	} else {
2536 		/*
2537 		 * No rtt measurement yet - use the unsmoothed rtt.
2538 		 * Set the variance to half the rtt (so our first
2539 		 * retransmit happens at 3*rtt).
2540 		 */
2541 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2542 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2543 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2544 	}
2545 	tp->t_rtttime = 0;
2546 	tp->t_rxtshift = 0;
2547 
2548 	/*
2549 	 * the retransmit should happen at rtt + 4 * rttvar.
2550 	 * Because of the way we do the smoothing, srtt and rttvar
2551 	 * will each average +1/2 tick of bias.  When we compute
2552 	 * the retransmit timer, we want 1/2 tick of rounding and
2553 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2554 	 * firing of the timer.  The bias will give us exactly the
2555 	 * 1.5 tick we need.  But, because the bias is
2556 	 * statistical, we have to test that we don't drop below
2557 	 * the minimum feasible timer (which is 2 ticks).
2558 	 */
2559 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2560 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2561 
2562 	/*
2563 	 * We received an ack for a packet that wasn't retransmitted;
2564 	 * it is probably safe to discard any error indications we've
2565 	 * received recently.  This isn't quite right, but close enough
2566 	 * for now (a route might have failed after we sent a segment,
2567 	 * and the return path might not be symmetrical).
2568 	 */
2569 	tp->t_softerror = 0;
2570 }
2571 
2572 /*
2573  * Determine a reasonable value for maxseg size.
2574  * If the route is known, check route for mtu.
2575  * If none, use an mss that can be handled on the outgoing
2576  * interface without forcing IP to fragment; if bigger than
2577  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2578  * to utilize large mbufs.  If no route is found, route has no mtu,
2579  * or the destination isn't local, use a default, hopefully conservative
2580  * size (usually 512 or the default IP max size, but no more than the mtu
2581  * of the interface), as we can't discover anything about intervening
2582  * gateways or networks.  We also initialize the congestion/slow start
2583  * window to be a single segment if the destination isn't local.
2584  * While looking at the routing entry, we also initialize other path-dependent
2585  * parameters from pre-set or cached values in the routing entry.
2586  *
2587  * Also take into account the space needed for options that we
2588  * send regularly.  Make maxseg shorter by that amount to assure
2589  * that we can send maxseg amount of data even when the options
2590  * are present.  Store the upper limit of the length of options plus
2591  * data in maxopd.
2592  *
2593  * NOTE that this routine is only called when we process an incoming
2594  * segment, for outgoing segments only tcp_mssopt is called.
2595  *
2596  * In case of T/TCP, we call this routine during implicit connection
2597  * setup as well (offer = -1), to initialize maxseg from the cached
2598  * MSS of our peer.
2599  */
2600 void
2601 tcp_mss(tp, offer)
2602 	struct tcpcb *tp;
2603 	int offer;
2604 {
2605 	register struct rtentry *rt;
2606 	struct ifnet *ifp;
2607 	register int rtt, mss;
2608 	u_long bufsize;
2609 	struct inpcb *inp = tp->t_inpcb;
2610 	struct socket *so;
2611 	struct rmxp_tao *taop;
2612 	int origoffer = offer;
2613 #ifdef INET6
2614 	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2615 	size_t min_protoh = isipv6 ?
2616 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2617 			    sizeof (struct tcpiphdr);
2618 #else
2619 	const int isipv6 = 0;
2620 	const size_t min_protoh = sizeof (struct tcpiphdr);
2621 #endif
2622 
2623 	if (isipv6)
2624 		rt = tcp_rtlookup6(&inp->inp_inc);
2625 	else
2626 		rt = tcp_rtlookup(&inp->inp_inc);
2627 	if (rt == NULL) {
2628 		tp->t_maxopd = tp->t_maxseg =
2629 				isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2630 		return;
2631 	}
2632 	ifp = rt->rt_ifp;
2633 	so = inp->inp_socket;
2634 
2635 	taop = rmx_taop(rt->rt_rmx);
2636 	/*
2637 	 * Offer == -1 means that we didn't receive SYN yet,
2638 	 * use cached value in that case;
2639 	 */
2640 	if (offer == -1)
2641 		offer = taop->tao_mssopt;
2642 	/*
2643 	 * Offer == 0 means that there was no MSS on the SYN segment,
2644 	 * in this case we use tcp_mssdflt.
2645 	 */
2646 	if (offer == 0)
2647 		offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2648 	else
2649 		/*
2650 		 * Sanity check: make sure that maxopd will be large
2651 		 * enough to allow some data on segments even is the
2652 		 * all the option space is used (40bytes).  Otherwise
2653 		 * funny things may happen in tcp_output.
2654 		 */
2655 		offer = max(offer, 64);
2656 	taop->tao_mssopt = offer;
2657 
2658 	/*
2659 	 * While we're here, check if there's an initial rtt
2660 	 * or rttvar.  Convert from the route-table units
2661 	 * to scaled multiples of the slow timeout timer.
2662 	 */
2663 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2664 		/*
2665 		 * XXX the lock bit for RTT indicates that the value
2666 		 * is also a minimum value; this is subject to time.
2667 		 */
2668 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2669 			tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2670 		tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2671 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2672 		tcpstat.tcps_usedrtt++;
2673 		if (rt->rt_rmx.rmx_rttvar) {
2674 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2675 			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2676 			tcpstat.tcps_usedrttvar++;
2677 		} else {
2678 			/* default variation is +- 1 rtt */
2679 			tp->t_rttvar =
2680 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2681 		}
2682 		TCPT_RANGESET(tp->t_rxtcur,
2683 			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2684 			      tp->t_rttmin, TCPTV_REXMTMAX);
2685 	}
2686 	/*
2687 	 * if there's an mtu associated with the route, use it
2688 	 * else, use the link mtu.
2689 	 */
2690 	if (rt->rt_rmx.rmx_mtu)
2691 		mss = rt->rt_rmx.rmx_mtu - min_protoh;
2692 	else {
2693 		if (isipv6) {
2694 			mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2695 				min_protoh;
2696 			if (!in6_localaddr(&inp->in6p_faddr))
2697 				mss = min(mss, tcp_v6mssdflt);
2698 		} else {
2699 			mss = ifp->if_mtu - min_protoh;
2700 			if (!in_localaddr(inp->inp_faddr))
2701 				mss = min(mss, tcp_mssdflt);
2702 		}
2703 	}
2704 	mss = min(mss, offer);
2705 	/*
2706 	 * maxopd stores the maximum length of data AND options
2707 	 * in a segment; maxseg is the amount of data in a normal
2708 	 * segment.  We need to store this value (maxopd) apart
2709 	 * from maxseg, because now every segment carries options
2710 	 * and thus we normally have somewhat less data in segments.
2711 	 */
2712 	tp->t_maxopd = mss;
2713 
2714 	/*
2715 	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2716 	 * were received yet.  In this case we just guess, otherwise
2717 	 * we do the same as before T/TCP.
2718 	 */
2719  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2720 	    (origoffer == -1 ||
2721 	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2722 		mss -= TCPOLEN_TSTAMP_APPA;
2723  	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2724 	    (origoffer == -1 ||
2725 	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2726 		mss -= TCPOLEN_CC_APPA;
2727 
2728 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
2729 		if (mss > MCLBYTES)
2730 			mss &= ~(MCLBYTES-1);
2731 #else
2732 		if (mss > MCLBYTES)
2733 			mss = mss / MCLBYTES * MCLBYTES;
2734 #endif
2735 	/*
2736 	 * If there's a pipesize, change the socket buffer
2737 	 * to that size.  Make the socket buffers an integral
2738 	 * number of mss units; if the mss is larger than
2739 	 * the socket buffer, decrease the mss.
2740 	 */
2741 #ifdef RTV_SPIPE
2742 	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2743 #endif
2744 		bufsize = so->so_snd.sb_hiwat;
2745 	if (bufsize < mss)
2746 		mss = bufsize;
2747 	else {
2748 		bufsize = roundup(bufsize, mss);
2749 		if (bufsize > sb_max)
2750 			bufsize = sb_max;
2751 		if (bufsize > so->so_snd.sb_hiwat)
2752 			(void)sbreserve(&so->so_snd, bufsize, so, NULL);
2753 	}
2754 	tp->t_maxseg = mss;
2755 
2756 #ifdef RTV_RPIPE
2757 	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2758 #endif
2759 		bufsize = so->so_rcv.sb_hiwat;
2760 	if (bufsize > mss) {
2761 		bufsize = roundup(bufsize, mss);
2762 		if (bufsize > sb_max)
2763 			bufsize = sb_max;
2764 		if (bufsize > so->so_rcv.sb_hiwat)
2765 			(void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2766 	}
2767 
2768 	/*
2769 	 * Set the slow-start flight size depending on whether this
2770 	 * is a local network or not.
2771 	 */
2772 	if (tcp_do_rfc3390)
2773 		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2774 	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2775 	    (!isipv6 && in_localaddr(inp->inp_faddr)))
2776 		tp->snd_cwnd = mss * ss_fltsz_local;
2777 	else
2778 		tp->snd_cwnd = mss * ss_fltsz;
2779 
2780 	if (rt->rt_rmx.rmx_ssthresh) {
2781 		/*
2782 		 * There's some sort of gateway or interface
2783 		 * buffer limit on the path.  Use this to set
2784 		 * the slow start threshhold, but set the
2785 		 * threshold to no less than 2*mss.
2786 		 */
2787 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2788 		tcpstat.tcps_usedssthresh++;
2789 	}
2790 }
2791 
2792 /*
2793  * Determine the MSS option to send on an outgoing SYN.
2794  */
2795 int
2796 tcp_mssopt(tp)
2797 	struct tcpcb *tp;
2798 {
2799 	struct rtentry *rt;
2800 #ifdef INET6
2801 	int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2802 	size_t min_protoh = isipv6 ?
2803 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2804 			    sizeof (struct tcpiphdr);
2805 #else
2806 	const int isipv6 = 0;
2807 	const size_t min_protoh = sizeof (struct tcpiphdr);
2808 #endif
2809 
2810 	if (isipv6)
2811 		rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2812 	else
2813 		rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2814 	if (rt == NULL)
2815 		return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2816 
2817 	return (rt->rt_ifp->if_mtu - min_protoh);
2818 }
2819 
2820 
2821 /*
2822  * On a partial ack arrives, force the retransmission of the
2823  * next unacknowledged segment.  Do not clear tp->t_dupacks.
2824  * By setting snd_nxt to ti_ack, this forces retransmission timer to
2825  * be started again.
2826  */
2827 static void
2828 tcp_newreno_partial_ack(tp, th)
2829 	struct tcpcb *tp;
2830 	struct tcphdr *th;
2831 {
2832 	tcp_seq onxt = tp->snd_nxt;
2833 	u_long  ocwnd = tp->snd_cwnd;
2834 
2835 	callout_stop(tp->tt_rexmt);
2836 	tp->t_rtttime = 0;
2837 	tp->snd_nxt = th->th_ack;
2838 	/*
2839 	 * Set snd_cwnd to one segment beyond acknowledged offset.
2840 	 * (tp->snd_una has not yet been updated when this function is called.)
2841 	 */
2842 	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2843 	tp->t_flags |= TF_ACKNOW;
2844 	(void) tcp_output(tp);
2845 	tp->snd_cwnd = ocwnd;
2846 	if (SEQ_GT(onxt, tp->snd_nxt))
2847 		tp->snd_nxt = onxt;
2848 	/*
2849 	 * Partial window deflation.  Relies on fact that tp->snd_una
2850 	 * not updated yet.
2851 	 */
2852 	tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2853 }
2854 
2855 /*
2856  * Returns 1 if the TIME_WAIT state was killed and we should start over,
2857  * looking for a pcb in the listen state.  Returns 0 otherwise.
2858  */
2859 static int
2860 tcp_timewait(tw, to, th, m, tlen)
2861 	struct tcptw *tw;
2862 	struct tcpopt *to;
2863 	struct tcphdr *th;
2864 	struct mbuf *m;
2865 	int tlen;
2866 {
2867 	int thflags;
2868 	tcp_seq seq;
2869 #ifdef INET6
2870 	int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
2871 #else
2872 	const int isipv6 = 0;
2873 #endif
2874 
2875 	thflags = th->th_flags;
2876 
2877 	/*
2878 	 * NOTE: for FIN_WAIT_2 (to be added later),
2879 	 * must validate sequence number before accepting RST
2880 	 */
2881 
2882 	/*
2883 	 * If the segment contains RST:
2884 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
2885 	 *      RFC 1337.
2886 	 */
2887 	if (thflags & TH_RST)
2888 		goto drop;
2889 
2890 	/*
2891 	 * If segment contains a SYN and CC [not CC.NEW] option:
2892 	 * 	if connection duration > MSL, drop packet and send RST;
2893 	 *
2894 	 *	if SEG.CC > CCrecv then is new SYN.
2895 	 *	    Complete close and delete TCPCB.  Then reprocess
2896 	 *	    segment, hoping to find new TCPCB in LISTEN state;
2897 	 *
2898 	 *	else must be old SYN; drop it.
2899 	 * else do normal processing.
2900 	 */
2901 	if ((thflags & TH_SYN) && (to->to_flags & TOF_CC) && tw->cc_recv != 0) {
2902 		if ((ticks - tw->t_starttime) > tcp_msl)
2903 			goto reset;
2904 		if (CC_GT(to->to_cc, tw->cc_recv)) {
2905 			(void) tcp_twclose(tw, 0);
2906 			return (1);
2907 		}
2908 		goto drop;
2909 	}
2910 
2911 #if 0
2912 /* PAWS not needed at the moment */
2913 	/*
2914 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2915 	 * and it's less than ts_recent, drop it.
2916 	 */
2917 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2918 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2919 		if ((thflags & TH_ACK) == 0)
2920 			goto drop;
2921 		goto ack;
2922 	}
2923 	/*
2924 	 * ts_recent is never updated because we never accept new segments.
2925 	 */
2926 #endif
2927 
2928 	/*
2929 	 * If a new connection request is received
2930 	 * while in TIME_WAIT, drop the old connection
2931 	 * and start over if the sequence numbers
2932 	 * are above the previous ones.
2933 	 */
2934 	if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
2935 		(void) tcp_twclose(tw, 0);
2936 		return (1);
2937 	}
2938 
2939 	/*
2940 	 * Drop the the segment if it does not contain an ACK.
2941 	 */
2942 	if ((thflags & TH_ACK) == 0)
2943 		goto drop;
2944 
2945 	/*
2946 	 * Reset the 2MSL timer if this is a duplicate FIN.
2947 	 */
2948 	if (thflags & TH_FIN) {
2949 		seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
2950 		if (seq + 1 == tw->rcv_nxt)
2951 			tcp_timer_2msl_reset(tw, 2 * tcp_msl);
2952 	}
2953 
2954 	/*
2955 	 * Acknowledge the segment if it has data or is not a duplicate ACK.
2956 	 */
2957 	if (thflags != TH_ACK || tlen != 0 ||
2958 	    th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
2959 		tcp_twrespond(tw, NULL, m, TH_ACK);
2960 	goto drop;
2961 
2962 reset:
2963 	/*
2964 	 * Generate a RST, dropping incoming segment.
2965 	 * Make ACK acceptable to originator of segment.
2966 	 * Don't bother to respond if destination was broadcast/multicast.
2967 	 */
2968 	if (m->m_flags & (M_BCAST|M_MCAST))
2969 		goto drop;
2970 	if (isipv6) {
2971 		struct ip6_hdr *ip6;
2972 
2973 		/* IPv6 anycast check is done at tcp6_input() */
2974 		ip6 = mtod(m, struct ip6_hdr *);
2975 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2976 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2977 			goto drop;
2978 	} else {
2979 		struct ip *ip;
2980 
2981 		ip = mtod(m, struct ip *);
2982 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2983 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2984 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2985 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2986 			goto drop;
2987 	}
2988 	if (thflags & TH_ACK) {
2989 		tcp_respond(NULL,
2990 		    mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
2991 	} else {
2992 		seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
2993 		tcp_respond(NULL,
2994 		    mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
2995 	}
2996 	INP_UNLOCK(tw->tw_inpcb);
2997 	return (0);
2998 
2999 drop:
3000 	INP_UNLOCK(tw->tw_inpcb);
3001 	m_freem(m);
3002 	return (0);
3003 }
3004