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