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