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