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