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