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