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