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