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