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