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