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