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