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