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