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