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