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