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