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