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