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