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