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