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