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