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