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