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