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