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