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