xref: /freebsd/sys/netinet/tcp_input.c (revision f1ea4e412039cea00267b3a3b0eb937f5a756ab7)
1c398230bSWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4e79adb8eSGarrett Wollman  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
5df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
6dbc42409SLawrence Stewart  * Copyright (c) 2007-2008,2010
7dbc42409SLawrence Stewart  *	Swinburne University of Technology, Melbourne, Australia.
8dbc42409SLawrence Stewart  * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
9dbc42409SLawrence Stewart  * Copyright (c) 2010 The FreeBSD Foundation
10fa046d87SRobert Watson  * Copyright (c) 2010-2011 Juniper Networks, Inc.
11dbc42409SLawrence Stewart  * All rights reserved.
12dbc42409SLawrence Stewart  *
13dbc42409SLawrence Stewart  * Portions of this software were developed at the Centre for Advanced Internet
14891b8ed4SLawrence Stewart  * Architectures, Swinburne University of Technology, by Lawrence Stewart,
15891b8ed4SLawrence Stewart  * James Healy and David Hayes, made possible in part by a grant from the Cisco
16891b8ed4SLawrence Stewart  * University Research Program Fund at Community Foundation Silicon Valley.
17dbc42409SLawrence Stewart  *
18dbc42409SLawrence Stewart  * Portions of this software were developed at the Centre for Advanced
19dbc42409SLawrence Stewart  * Internet Architectures, Swinburne University of Technology, Melbourne,
20dbc42409SLawrence Stewart  * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
21df8bae1dSRodney W. Grimes  *
22fa046d87SRobert Watson  * Portions of this software were developed by Robert N. M. Watson under
23fa046d87SRobert Watson  * contract to Juniper Networks, Inc.
24fa046d87SRobert Watson  *
25df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
26df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
27df8bae1dSRodney W. Grimes  * are met:
28df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
29df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
30df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
31df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
32df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
33fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
34df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
35df8bae1dSRodney W. Grimes  *    without specific prior written permission.
36df8bae1dSRodney W. Grimes  *
37df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
48df8bae1dSRodney W. Grimes  *
49e79adb8eSGarrett Wollman  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
50df8bae1dSRodney W. Grimes  */
51df8bae1dSRodney W. Grimes 
524b421e2dSMike Silbersack #include <sys/cdefs.h>
534b421e2dSMike Silbersack __FBSDID("$FreeBSD$");
544b421e2dSMike Silbersack 
551cfd4b53SBruce M Simpson #include "opt_inet.h"
56fb59c426SYoshinobu Inoue #include "opt_inet6.h"
573a2a9f79SYoshinobu Inoue #include "opt_ipsec.h"
580cc12cc5SJoerg Wunsch #include "opt_tcpdebug.h"
590cc12cc5SJoerg Wunsch 
60df8bae1dSRodney W. Grimes #include <sys/param.h>
61adc56f5aSEdward Tomasz Napierala #include <sys/arb.h>
6298163b98SPoul-Henning Kamp #include <sys/kernel.h>
63bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
6439bc9de5SLawrence Stewart #include <sys/hhook.h>
65bd79708dSJonathan T. Looney #endif
66df8bae1dSRodney W. Grimes #include <sys/malloc.h>
67df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
68a29f300eSGarrett Wollman #include <sys/proc.h>		/* for proc0 declaration */
69df8bae1dSRodney W. Grimes #include <sys/protosw.h>
70adc56f5aSEdward Tomasz Napierala #include <sys/qmath.h>
7157f60867SMark Johnston #include <sys/sdt.h>
72960ed29cSSeigo Tanimura #include <sys/signalvar.h>
73df8bae1dSRodney W. Grimes #include <sys/socket.h>
74df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
75960ed29cSSeigo Tanimura #include <sys/sysctl.h>
76816a3d83SPoul-Henning Kamp #include <sys/syslog.h>
77960ed29cSSeigo Tanimura #include <sys/systm.h>
78adc56f5aSEdward Tomasz Napierala #include <sys/stats.h>
79df8bae1dSRodney W. Grimes 
80e79adb8eSGarrett Wollman #include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
81e79adb8eSGarrett Wollman 
8212e2e970SAndre Oppermann #include <vm/uma.h>
8312e2e970SAndre Oppermann 
84df8bae1dSRodney W. Grimes #include <net/if.h>
8576039bc8SGleb Smirnoff #include <net/if_var.h>
86df8bae1dSRodney W. Grimes #include <net/route.h>
87530c0060SRobert Watson #include <net/vnet.h>
88df8bae1dSRodney W. Grimes 
89773673c1SAndre Oppermann #define TCPSTATES		/* for logging */
90773673c1SAndre Oppermann 
91df8bae1dSRodney W. Grimes #include <netinet/in.h>
9257f60867SMark Johnston #include <netinet/in_kdtrace.h>
93960ed29cSSeigo Tanimura #include <netinet/in_pcb.h>
94df8bae1dSRodney W. Grimes #include <netinet/in_systm.h>
95df8bae1dSRodney W. Grimes #include <netinet/ip.h>
968e8aab7aSAndre Oppermann #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
97686cdd19SJun-ichiro itojun Hagino #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
98df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
99ef39adf0SAndre Oppermann #include <netinet/ip_options.h>
100686cdd19SJun-ichiro itojun Hagino #include <netinet/ip6.h>
101686cdd19SJun-ichiro itojun Hagino #include <netinet/icmp6.h>
102686cdd19SJun-ichiro itojun Hagino #include <netinet6/in6_pcb.h>
103b66d74c1SGleb Smirnoff #include <netinet6/in6_var.h>
104960ed29cSSeigo Tanimura #include <netinet6/ip6_var.h>
105960ed29cSSeigo Tanimura #include <netinet6/nd6.h>
1062de3e790SGleb Smirnoff #include <netinet/tcp.h>
107df8bae1dSRodney W. Grimes #include <netinet/tcp_fsm.h>
1082529f56eSJonathan T. Looney #include <netinet/tcp_log_buf.h>
109df8bae1dSRodney W. Grimes #include <netinet/tcp_seq.h>
110df8bae1dSRodney W. Grimes #include <netinet/tcp_timer.h>
111df8bae1dSRodney W. Grimes #include <netinet/tcp_var.h>
112fb59c426SYoshinobu Inoue #include <netinet6/tcp6_var.h>
113df8bae1dSRodney W. Grimes #include <netinet/tcpip.h>
1144644fda3SGleb Smirnoff #include <netinet/cc/cc.h>
115c560df6fSPatrick Kelsey #include <netinet/tcp_fastopen.h>
11686a996e6SHiren Panchasara #ifdef TCPPCAP
11786a996e6SHiren Panchasara #include <netinet/tcp_pcap.h>
11886a996e6SHiren Panchasara #endif
119c325962bSMike Silbersack #include <netinet/tcp_syncache.h>
120610ee2f9SDavid Greenman #ifdef TCPDEBUG
121df8bae1dSRodney W. Grimes #include <netinet/tcp_debug.h>
122fb59c426SYoshinobu Inoue #endif /* TCPDEBUG */
12309fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
12409fe6320SNavdeep Parhar #include <netinet/tcp_offload.h>
12509fe6320SNavdeep Parhar #endif
126fb59c426SYoshinobu Inoue 
127fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
128b9234fafSSam Leffler 
129db4f9cc7SJonathan Lemon #include <machine/in_cksum.h>
130db4f9cc7SJonathan Lemon 
131aed55708SRobert Watson #include <security/mac/mac_framework.h>
132aed55708SRobert Watson 
133dbc42409SLawrence Stewart const int tcprexmtthresh = 3;
1340312fbe9SPoul-Henning Kamp 
135334fc582SBjoern A. Zeeb VNET_DEFINE(int, tcp_log_in_vain) = 0;
136334fc582SBjoern A. Zeeb SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW,
137334fc582SBjoern A. Zeeb     &VNET_NAME(tcp_log_in_vain), 0,
138eddfbb76SRobert Watson     "Log all incoming TCP segments to closed ports");
139816a3d83SPoul-Henning Kamp 
14082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, blackhole) = 0;
14182cea7e6SBjoern A. Zeeb #define	V_blackhole		VNET(blackhole)
1426df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
143eddfbb76SRobert Watson     &VNET_NAME(blackhole), 0,
144eddfbb76SRobert Watson     "Do not send RST on segments to closed ports");
14516f7f31fSGeoff Rehmet 
14682cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_delack_enabled) = 1;
1476df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
148eddfbb76SRobert Watson     &VNET_NAME(tcp_delack_enabled), 0,
1493d177f46SBill Fumerola     "Delay ACK to try and piggyback it onto a data packet");
150f498eeeeSDavid Greenman 
15182cea7e6SBjoern A. Zeeb VNET_DEFINE(int, drop_synfin) = 0;
1526df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
153eddfbb76SRobert Watson     &VNET_NAME(drop_synfin), 0,
154eddfbb76SRobert Watson     "Drop TCP packets with SYN+FIN set");
155f8613305SDag-Erling Smørgrav 
156b72e56e7SMichael Tuexen VNET_DEFINE(int, tcp_do_newcwv) = 0;
157b72e56e7SMichael Tuexen SYSCTL_INT(_net_inet_tcp, OID_AUTO, newcwv, CTLFLAG_VNET | CTLFLAG_RW,
158b72e56e7SMichael Tuexen     &VNET_NAME(tcp_do_newcwv), 0,
159b72e56e7SMichael Tuexen     "Enable New Congestion Window Validation per RFC7661");
160b72e56e7SMichael Tuexen 
16112eeb81fSHiren Panchasara VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
162054d38e3SHiren Panchasara SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
16312eeb81fSHiren Panchasara     &VNET_NAME(tcp_do_rfc6675_pipe), 0,
16412eeb81fSHiren Panchasara     "Use calculated pipe/in-flight bytes per RFC 6675");
16512eeb81fSHiren Panchasara 
16682cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3042) = 1;
1676df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
168eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3042), 0,
169eddfbb76SRobert Watson     "Enable RFC 3042 (Limited Transmit)");
170582a954bSJeffrey Hsu 
17182cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3390) = 1;
1726df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
173eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3390), 0,
174da3a8a1aSJeffrey Hsu     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
175da3a8a1aSJeffrey Hsu 
176356c7958SHiren Panchasara VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
177356c7958SHiren Panchasara SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
178356c7958SHiren Panchasara     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
179356c7958SHiren Panchasara     "Slow-start flight size (initial congestion window) in number of segments");
18009440655SAndre Oppermann 
18182cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3465) = 1;
1826df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
183eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3465), 0,
18424cb0f22SLawrence Stewart     "Enable RFC 3465 (Appropriate Byte Counting)");
185eddfbb76SRobert Watson 
18682cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_abc_l_var) = 2;
1876df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
188eddfbb76SRobert Watson     &VNET_NAME(tcp_abc_l_var), 2,
18924cb0f22SLawrence Stewart     "Cap the max cwnd increment during slow-start to this number of segments");
19024cb0f22SLawrence Stewart 
1917029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn,
1927029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1937029da5cSPawel Biernacki     "TCP ECN");
194f2512ba1SRui Paulo 
195883054b4SDon Lewis VNET_DEFINE(int, tcp_do_ecn) = 2;
1966df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
197eddfbb76SRobert Watson     &VNET_NAME(tcp_do_ecn), 0,
198eddfbb76SRobert Watson     "TCP ECN support");
199eddfbb76SRobert Watson 
20082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
2016df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
202eddfbb76SRobert Watson     &VNET_NAME(tcp_ecn_maxretries), 0,
203eddfbb76SRobert Watson     "Max retries before giving up on ECN");
204eddfbb76SRobert Watson 
2053220a212SGleb Smirnoff VNET_DEFINE(int, tcp_insecure_syn) = 0;
2066df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
2073220a212SGleb Smirnoff     &VNET_NAME(tcp_insecure_syn), 0,
2083220a212SGleb Smirnoff     "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
2093220a212SGleb Smirnoff 
21082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_insecure_rst) = 0;
2116df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
212eddfbb76SRobert Watson     &VNET_NAME(tcp_insecure_rst), 0,
2133220a212SGleb Smirnoff     "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
214a69968eeSMike Silbersack 
215fba0cea1SBjoern A. Zeeb VNET_DEFINE(int, tcp_recvspace) = 1024*64;
216873789cbSAndre Oppermann #define	V_tcp_recvspace	VNET(tcp_recvspace)
2176df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
218873789cbSAndre Oppermann     &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
219873789cbSAndre Oppermann 
22082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
2216df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
222eddfbb76SRobert Watson     &VNET_NAME(tcp_do_autorcvbuf), 0,
2238b615593SMarko Zec     "Enable automatic receive buffer sizing");
2246741ecf5SAndre Oppermann 
225b233773bSBjoern A. Zeeb VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
2266df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
227eddfbb76SRobert Watson     &VNET_NAME(tcp_autorcvbuf_max), 0,
2288b615593SMarko Zec     "Max size of automatic receive buffer");
2296741ecf5SAndre Oppermann 
230eddfbb76SRobert Watson VNET_DEFINE(struct inpcbhead, tcb);
23144e33a07SMarko Zec #define	tcb6	tcb  /* for KAME src sync over BSD*'s */
23282cea7e6SBjoern A. Zeeb VNET_DEFINE(struct inpcbinfo, tcbinfo);
233df8bae1dSRodney W. Grimes 
234315e3e38SRobert Watson /*
235bf840a17SGleb Smirnoff  * TCP statistics are stored in an array of counter(9)s, which size matches
236bf840a17SGleb Smirnoff  * size of struct tcpstat.  TCP running connection count is a regular array.
2375923c293SGleb Smirnoff  */
2385da0521fSAndrey V. Elsukov VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
2395da0521fSAndrey V. Elsukov SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
2405da0521fSAndrey V. Elsukov     tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
241bf840a17SGleb Smirnoff VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
242bf840a17SGleb Smirnoff SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
243d4d32b9fSHans Petter Selasky     CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
244bf840a17SGleb Smirnoff     "TCP connection counts by TCP state");
245bf840a17SGleb Smirnoff 
246bf840a17SGleb Smirnoff static void
247bf840a17SGleb Smirnoff tcp_vnet_init(const void *unused)
248bf840a17SGleb Smirnoff {
249bf840a17SGleb Smirnoff 
250f59d975eSGleb Smirnoff 	COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
251bf840a17SGleb Smirnoff 	VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
252bf840a17SGleb Smirnoff }
253bf840a17SGleb Smirnoff VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
254bf840a17SGleb Smirnoff     tcp_vnet_init, NULL);
2555923c293SGleb Smirnoff 
2565923c293SGleb Smirnoff #ifdef VIMAGE
257bf840a17SGleb Smirnoff static void
258bf840a17SGleb Smirnoff tcp_vnet_uninit(const void *unused)
259bf840a17SGleb Smirnoff {
260bf840a17SGleb Smirnoff 
261f59d975eSGleb Smirnoff 	COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
262bf840a17SGleb Smirnoff 	VNET_PCPUSTAT_FREE(tcpstat);
263bf840a17SGleb Smirnoff }
264bf840a17SGleb Smirnoff VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
265bf840a17SGleb Smirnoff     tcp_vnet_uninit, NULL);
2665923c293SGleb Smirnoff #endif /* VIMAGE */
267bf840a17SGleb Smirnoff 
2685923c293SGleb Smirnoff /*
2697ca6e296SMichael Tuexen  * Kernel module interface for updating tcpstat.  The first argument is an index
2705923c293SGleb Smirnoff  * into tcpstat treated as an array.
271315e3e38SRobert Watson  */
272315e3e38SRobert Watson void
2737ca6e296SMichael Tuexen kmod_tcpstat_add(int statnum, int val)
274315e3e38SRobert Watson {
275315e3e38SRobert Watson 
2767ca6e296SMichael Tuexen 	counter_u64_add(VNET(tcpstat)[statnum], val);
277315e3e38SRobert Watson }
278315e3e38SRobert Watson 
279bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
280dbc42409SLawrence Stewart /*
28139bc9de5SLawrence Stewart  * Wrapper for the TCP established input helper hook.
28239bc9de5SLawrence Stewart  */
28355bceb1eSRandall Stewart void
28439bc9de5SLawrence Stewart hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
28539bc9de5SLawrence Stewart {
28639bc9de5SLawrence Stewart 	struct tcp_hhook_data hhook_data;
28739bc9de5SLawrence Stewart 
28839bc9de5SLawrence Stewart 	if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
28939bc9de5SLawrence Stewart 		hhook_data.tp = tp;
29039bc9de5SLawrence Stewart 		hhook_data.th = th;
29139bc9de5SLawrence Stewart 		hhook_data.to = to;
29239bc9de5SLawrence Stewart 
29339bc9de5SLawrence Stewart 		hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
29439bc9de5SLawrence Stewart 		    tp->osd);
29539bc9de5SLawrence Stewart 	}
29639bc9de5SLawrence Stewart }
297bd79708dSJonathan T. Looney #endif
29839bc9de5SLawrence Stewart 
29939bc9de5SLawrence Stewart /*
300dbc42409SLawrence Stewart  * CC wrapper hook functions
301dbc42409SLawrence Stewart  */
30255bceb1eSRandall Stewart void
3034b7b743cSLawrence Stewart cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
3044b7b743cSLawrence Stewart     uint16_t type)
305f2512ba1SRui Paulo {
306adc56f5aSEdward Tomasz Napierala #ifdef STATS
307adc56f5aSEdward Tomasz Napierala 	int32_t gput;
308adc56f5aSEdward Tomasz Napierala #endif
309adc56f5aSEdward Tomasz Napierala 
310dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
311f2512ba1SRui Paulo 
3124b7b743cSLawrence Stewart 	tp->ccv->nsegs = nsegs;
313dbc42409SLawrence Stewart 	tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
314b72e56e7SMichael Tuexen 	if ((!V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd)) ||
315b72e56e7SMichael Tuexen 	    (V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd) &&
316b72e56e7SMichael Tuexen 	     (tp->snd_cwnd < (tcp_compute_pipe(tp) * 2))))
317dbc42409SLawrence Stewart 		tp->ccv->flags |= CCF_CWND_LIMITED;
318dbc42409SLawrence Stewart 	else
319dbc42409SLawrence Stewart 		tp->ccv->flags &= ~CCF_CWND_LIMITED;
320dbc42409SLawrence Stewart 
321dbc42409SLawrence Stewart 	if (type == CC_ACK) {
322adc56f5aSEdward Tomasz Napierala #ifdef STATS
323adc56f5aSEdward Tomasz Napierala 		stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
324adc56f5aSEdward Tomasz Napierala 		    ((int32_t)tp->snd_cwnd) - tp->snd_wnd);
325adc56f5aSEdward Tomasz Napierala 		if (!IN_RECOVERY(tp->t_flags))
326adc56f5aSEdward Tomasz Napierala 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_ACKLEN,
327adc56f5aSEdward Tomasz Napierala 			   tp->ccv->bytes_this_ack / (tcp_maxseg(tp) * nsegs));
328adc56f5aSEdward Tomasz Napierala 		if ((tp->t_flags & TF_GPUTINPROG) &&
329adc56f5aSEdward Tomasz Napierala 		    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
330adc56f5aSEdward Tomasz Napierala 			/*
331adc56f5aSEdward Tomasz Napierala 			 * Compute goodput in bits per millisecond.
332adc56f5aSEdward Tomasz Napierala 			 */
333adc56f5aSEdward Tomasz Napierala 			gput = (((int64_t)(th->th_ack - tp->gput_seq)) << 3) /
334adc56f5aSEdward Tomasz Napierala 			    max(1, tcp_ts_getticks() - tp->gput_ts);
335adc56f5aSEdward Tomasz Napierala 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
336adc56f5aSEdward Tomasz Napierala 			    gput);
337adc56f5aSEdward Tomasz Napierala 			/*
338adc56f5aSEdward Tomasz Napierala 			 * XXXLAS: This is a temporary hack, and should be
339adc56f5aSEdward Tomasz Napierala 			 * chained off VOI_TCP_GPUT when stats(9) grows an API
340adc56f5aSEdward Tomasz Napierala 			 * to deal with chained VOIs.
341adc56f5aSEdward Tomasz Napierala 			 */
342adc56f5aSEdward Tomasz Napierala 			if (tp->t_stats_gput_prev > 0)
343adc56f5aSEdward Tomasz Napierala 				stats_voi_update_abs_s32(tp->t_stats,
344adc56f5aSEdward Tomasz Napierala 				    VOI_TCP_GPUT_ND,
345adc56f5aSEdward Tomasz Napierala 				    ((gput - tp->t_stats_gput_prev) * 100) /
346adc56f5aSEdward Tomasz Napierala 				    tp->t_stats_gput_prev);
347adc56f5aSEdward Tomasz Napierala 			tp->t_flags &= ~TF_GPUTINPROG;
348adc56f5aSEdward Tomasz Napierala 			tp->t_stats_gput_prev = gput;
349adc56f5aSEdward Tomasz Napierala 		}
350adc56f5aSEdward Tomasz Napierala #endif /* STATS */
351dbc42409SLawrence Stewart 		if (tp->snd_cwnd > tp->snd_ssthresh) {
352dbc42409SLawrence Stewart 			tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
3534b7b743cSLawrence Stewart 			     nsegs * V_tcp_abc_l_var * tcp_maxseg(tp));
354dbc42409SLawrence Stewart 			if (tp->t_bytes_acked >= tp->snd_cwnd) {
355dbc42409SLawrence Stewart 				tp->t_bytes_acked -= tp->snd_cwnd;
356dbc42409SLawrence Stewart 				tp->ccv->flags |= CCF_ABC_SENTAWND;
357dbc42409SLawrence Stewart 			}
358dbc42409SLawrence Stewart 		} else {
359dbc42409SLawrence Stewart 				tp->ccv->flags &= ~CCF_ABC_SENTAWND;
360dbc42409SLawrence Stewart 				tp->t_bytes_acked = 0;
361dbc42409SLawrence Stewart 		}
362dbc42409SLawrence Stewart 	}
363dbc42409SLawrence Stewart 
364dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->ack_received != NULL) {
365dbc42409SLawrence Stewart 		/* XXXLAS: Find a way to live without this */
366dbc42409SLawrence Stewart 		tp->ccv->curack = th->th_ack;
367dbc42409SLawrence Stewart 		CC_ALGO(tp)->ack_received(tp->ccv, type);
368dbc42409SLawrence Stewart 	}
369adc56f5aSEdward Tomasz Napierala #ifdef STATS
370adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
371adc56f5aSEdward Tomasz Napierala #endif
372dbc42409SLawrence Stewart }
373dbc42409SLawrence Stewart 
37455bceb1eSRandall Stewart void
375dbc42409SLawrence Stewart cc_conn_init(struct tcpcb *tp)
376dbc42409SLawrence Stewart {
377dbc42409SLawrence Stewart 	struct hc_metrics_lite metrics;
378dbc42409SLawrence Stewart 	struct inpcb *inp = tp->t_inpcb;
3790c39d38dSGleb Smirnoff 	u_int maxseg;
380dbc42409SLawrence Stewart 	int rtt;
381dbc42409SLawrence Stewart 
382dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
383dbc42409SLawrence Stewart 
384dbc42409SLawrence Stewart 	tcp_hc_get(&inp->inp_inc, &metrics);
3850c39d38dSGleb Smirnoff 	maxseg = tcp_maxseg(tp);
386dbc42409SLawrence Stewart 
387dbc42409SLawrence Stewart 	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
388dbc42409SLawrence Stewart 		tp->t_srtt = rtt;
389dbc42409SLawrence Stewart 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
390dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_usedrtt);
391dbc42409SLawrence Stewart 		if (metrics.rmx_rttvar) {
392dbc42409SLawrence Stewart 			tp->t_rttvar = metrics.rmx_rttvar;
393dbc42409SLawrence Stewart 			TCPSTAT_INC(tcps_usedrttvar);
394dbc42409SLawrence Stewart 		} else {
395dbc42409SLawrence Stewart 			/* default variation is +- 1 rtt */
396dbc42409SLawrence Stewart 			tp->t_rttvar =
397dbc42409SLawrence Stewart 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
398dbc42409SLawrence Stewart 		}
399dbc42409SLawrence Stewart 		TCPT_RANGESET(tp->t_rxtcur,
400dbc42409SLawrence Stewart 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
401dbc42409SLawrence Stewart 		    tp->t_rttmin, TCPTV_REXMTMAX);
402dbc42409SLawrence Stewart 	}
403dbc42409SLawrence Stewart 	if (metrics.rmx_ssthresh) {
404dbc42409SLawrence Stewart 		/*
405dbc42409SLawrence Stewart 		 * There's some sort of gateway or interface
406dbc42409SLawrence Stewart 		 * buffer limit on the path.  Use this to set
407a4641f4eSPedro F. Giffuni 		 * the slow start threshold, but set the
408dbc42409SLawrence Stewart 		 * threshold to no less than 2*mss.
409dbc42409SLawrence Stewart 		 */
4100c39d38dSGleb Smirnoff 		tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
411dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_usedssthresh);
412dbc42409SLawrence Stewart 	}
413dbc42409SLawrence Stewart 
414dbc42409SLawrence Stewart 	/*
4159ec4a4ccSAndre Oppermann 	 * Set the initial slow-start flight size.
416dbc42409SLawrence Stewart 	 *
417cf8f04f4SAndre Oppermann 	 * If a SYN or SYN/ACK was lost and retransmitted, we have to
418cf8f04f4SAndre Oppermann 	 * reduce the initial CWND to one segment as congestion is likely
419cf8f04f4SAndre Oppermann 	 * requiring us to be cautious.
420dbc42409SLawrence Stewart 	 */
421cf8f04f4SAndre Oppermann 	if (tp->snd_cwnd == 1)
4220c39d38dSGleb Smirnoff 		tp->snd_cwnd = maxseg;		/* SYN(-ACK) lost */
423dbc42409SLawrence Stewart 	else
4247dc90a1dSMichael Tuexen 		tp->snd_cwnd = tcp_compute_initwnd(maxseg);
425dbc42409SLawrence Stewart 
426dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->conn_init != NULL)
427dbc42409SLawrence Stewart 		CC_ALGO(tp)->conn_init(tp->ccv);
428dbc42409SLawrence Stewart }
429dbc42409SLawrence Stewart 
430dbc42409SLawrence Stewart void inline
431dbc42409SLawrence Stewart cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
432dbc42409SLawrence Stewart {
4330c39d38dSGleb Smirnoff 	u_int maxseg;
4340c39d38dSGleb Smirnoff 
435dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
436dbc42409SLawrence Stewart 
437adc56f5aSEdward Tomasz Napierala #ifdef STATS
438adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
439adc56f5aSEdward Tomasz Napierala #endif
440adc56f5aSEdward Tomasz Napierala 
441dbc42409SLawrence Stewart 	switch(type) {
442dbc42409SLawrence Stewart 	case CC_NDUPACK:
443dbc42409SLawrence Stewart 		if (!IN_FASTRECOVERY(tp->t_flags)) {
444f2512ba1SRui Paulo 			tp->snd_recover = tp->snd_max;
4453cf38784SMichael Tuexen 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4463cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_SND_CWR;
447f2512ba1SRui Paulo 		}
448dbc42409SLawrence Stewart 		break;
449dbc42409SLawrence Stewart 	case CC_ECN:
450af2fb894SRichard Scheffenegger 		if (!IN_CONGRECOVERY(tp->t_flags) ||
451af2fb894SRichard Scheffenegger 		    /*
452af2fb894SRichard Scheffenegger 		     * Allow ECN reaction on ACK to CWR, if
453af2fb894SRichard Scheffenegger 		     * that data segment was also CE marked.
454af2fb894SRichard Scheffenegger 		     */
455af2fb894SRichard Scheffenegger 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
456af2fb894SRichard Scheffenegger 			EXIT_CONGRECOVERY(tp->t_flags);
457dbc42409SLawrence Stewart 			TCPSTAT_INC(tcps_ecn_rcwnd);
458af2fb894SRichard Scheffenegger 			tp->snd_recover = tp->snd_max + 1;
4593cf38784SMichael Tuexen 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4603cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_SND_CWR;
461dbc42409SLawrence Stewart 		}
462dbc42409SLawrence Stewart 		break;
463dbc42409SLawrence Stewart 	case CC_RTO:
4640c39d38dSGleb Smirnoff 		maxseg = tcp_maxseg(tp);
465dbc42409SLawrence Stewart 		tp->t_dupacks = 0;
466dbc42409SLawrence Stewart 		tp->t_bytes_acked = 0;
467dbc42409SLawrence Stewart 		EXIT_RECOVERY(tp->t_flags);
46843053c12SSean Bruno 		tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
46943053c12SSean Bruno 		    maxseg) * maxseg;
4700c39d38dSGleb Smirnoff 		tp->snd_cwnd = maxseg;
4719cc711c9SMichael Tuexen 		if (tp->t_flags2 & TF2_ECN_PERMIT)
4729cc711c9SMichael Tuexen 			tp->t_flags2 |= TF2_ECN_SND_CWR;
473dbc42409SLawrence Stewart 		break;
474dbc42409SLawrence Stewart 	case CC_RTO_ERR:
475dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_sndrexmitbad);
476dbc42409SLawrence Stewart 		/* RTO was unnecessary, so reset everything. */
477dbc42409SLawrence Stewart 		tp->snd_cwnd = tp->snd_cwnd_prev;
478dbc42409SLawrence Stewart 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
479dbc42409SLawrence Stewart 		tp->snd_recover = tp->snd_recover_prev;
480dbc42409SLawrence Stewart 		if (tp->t_flags & TF_WASFRECOVERY)
481dbc42409SLawrence Stewart 			ENTER_FASTRECOVERY(tp->t_flags);
482dbc42409SLawrence Stewart 		if (tp->t_flags & TF_WASCRECOVERY)
483dbc42409SLawrence Stewart 			ENTER_CONGRECOVERY(tp->t_flags);
484dbc42409SLawrence Stewart 		tp->snd_nxt = tp->snd_max;
485672dc4aeSJohn Baldwin 		tp->t_flags &= ~TF_PREVVALID;
486dbc42409SLawrence Stewart 		tp->t_badrxtwin = 0;
487dbc42409SLawrence Stewart 		break;
488dbc42409SLawrence Stewart 	}
489dbc42409SLawrence Stewart 
490dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->cong_signal != NULL) {
491dbc42409SLawrence Stewart 		if (th != NULL)
492dbc42409SLawrence Stewart 			tp->ccv->curack = th->th_ack;
493dbc42409SLawrence Stewart 		CC_ALGO(tp)->cong_signal(tp->ccv, type);
494dbc42409SLawrence Stewart 	}
495dbc42409SLawrence Stewart }
496dbc42409SLawrence Stewart 
49755bceb1eSRandall Stewart void inline
498dbc42409SLawrence Stewart cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
499dbc42409SLawrence Stewart {
500dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
501dbc42409SLawrence Stewart 
502dbc42409SLawrence Stewart 	/* XXXLAS: KASSERT that we're in recovery? */
503dbc42409SLawrence Stewart 
504dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->post_recovery != NULL) {
505dbc42409SLawrence Stewart 		tp->ccv->curack = th->th_ack;
506dbc42409SLawrence Stewart 		CC_ALGO(tp)->post_recovery(tp->ccv);
507dbc42409SLawrence Stewart 	}
508dbc42409SLawrence Stewart 	/* XXXLAS: EXIT_RECOVERY ? */
509dbc42409SLawrence Stewart 	tp->t_bytes_acked = 0;
510dbc42409SLawrence Stewart }
5110312fbe9SPoul-Henning Kamp 
512df8bae1dSRodney W. Grimes /*
513262c1c1aSMatthew Dillon  * Indicate whether this ack should be delayed.  We can delay the ack if
51485536381SHiren Panchasara  * following conditions are met:
51585536381SHiren Panchasara  *	- There is no delayed ack timer in progress.
51685536381SHiren Panchasara  *	- Our last ack wasn't a 0-sized window. We never want to delay
51785536381SHiren Panchasara  *	  the ack that opens up a 0-sized window.
51885536381SHiren Panchasara  *	- LRO wasn't used for this segment. We make sure by checking that the
51985536381SHiren Panchasara  *	  segment size is not larger than the MSS.
520d8c85a26SJonathan Lemon  */
521c1e5a6e5SAndre Oppermann #define DELAY_ACK(tp, tlen)						\
522b8152ba7SAndre Oppermann 	((!tcp_timer_active(tp, TT_DELACK) &&				\
523a14c749fSJonathan Lemon 	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
5240c39d38dSGleb Smirnoff 	    (tlen <= tp->t_maxseg) &&					\
525603724d3SBjoern A. Zeeb 	    (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
526d8c85a26SJonathan Lemon 
5274ad24737SRandall Stewart void inline
52864807b30SHiren Panchasara cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
52964807b30SHiren Panchasara {
53064807b30SHiren Panchasara 	INP_WLOCK_ASSERT(tp->t_inpcb);
53164807b30SHiren Panchasara 
53264807b30SHiren Panchasara 	if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
53364807b30SHiren Panchasara 		switch (iptos & IPTOS_ECN_MASK) {
53464807b30SHiren Panchasara 		case IPTOS_ECN_CE:
53564807b30SHiren Panchasara 			tp->ccv->flags |= CCF_IPHDR_CE;
53664807b30SHiren Panchasara 			break;
53764807b30SHiren Panchasara 		case IPTOS_ECN_ECT0:
53883a2839fSMichael Tuexen 			/* FALLTHROUGH */
53964807b30SHiren Panchasara 		case IPTOS_ECN_ECT1:
54083a2839fSMichael Tuexen 			/* FALLTHROUGH */
54183a2839fSMichael Tuexen 		case IPTOS_ECN_NOTECT:
54264807b30SHiren Panchasara 			tp->ccv->flags &= ~CCF_IPHDR_CE;
54364807b30SHiren Panchasara 			break;
54464807b30SHiren Panchasara 		}
54564807b30SHiren Panchasara 
54664807b30SHiren Panchasara 		if (th->th_flags & TH_CWR)
54764807b30SHiren Panchasara 			tp->ccv->flags |= CCF_TCPHDR_CWR;
54864807b30SHiren Panchasara 		else
54964807b30SHiren Panchasara 			tp->ccv->flags &= ~CCF_TCPHDR_CWR;
55064807b30SHiren Panchasara 
55164807b30SHiren Panchasara 		CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
55264807b30SHiren Panchasara 
553e11c9783SMichael Tuexen 		if (tp->ccv->flags & CCF_ACKNOW) {
55464807b30SHiren Panchasara 			tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
555e11c9783SMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
556e11c9783SMichael Tuexen 		}
55764807b30SHiren Panchasara 	}
55864807b30SHiren Panchasara }
55964807b30SHiren Panchasara 
560df8bae1dSRodney W. Grimes /*
5618d573cc1SAndre Oppermann  * TCP input handling is split into multiple parts:
5628d573cc1SAndre Oppermann  *   tcp6_input is a thin wrapper around tcp_input for the extended
5638d573cc1SAndre Oppermann  *	ip6_protox[] call format in ip6_input
5648d573cc1SAndre Oppermann  *   tcp_input handles primary segment validation, inpcb lookup and
5658d573cc1SAndre Oppermann  *	SYN processing on listen sockets
5668d573cc1SAndre Oppermann  *   tcp_do_segment processes the ACK and text of the segment for
5678d573cc1SAndre Oppermann  *	establishing, established and closing connections
568df8bae1dSRodney W. Grimes  */
569fb59c426SYoshinobu Inoue #ifdef INET6
570fb59c426SYoshinobu Inoue int
571ad3f9ab3SAndre Oppermann tcp6_input(struct mbuf **mp, int *offp, int proto)
572fb59c426SYoshinobu Inoue {
573503f4e47SBjoern A. Zeeb 	struct mbuf *m;
57433841545SHajimu UMEMOTO 	struct in6_ifaddr *ia6;
5753e88eb90SAndrey V. Elsukov 	struct ip6_hdr *ip6;
576fb59c426SYoshinobu Inoue 
577503f4e47SBjoern A. Zeeb 	m = *mp;
578a4adf6ccSBjoern A. Zeeb 	if (m->m_len < *offp + sizeof(struct tcphdr)) {
5794e619b17SBjoern A. Zeeb 		m = m_pullup(m, *offp + sizeof(struct tcphdr));
5804e619b17SBjoern A. Zeeb 		if (m == NULL) {
5814e619b17SBjoern A. Zeeb 			*mp = m;
5824e619b17SBjoern A. Zeeb 			TCPSTAT_INC(tcps_rcvshort);
5834e619b17SBjoern A. Zeeb 			return (IPPROTO_DONE);
5844e619b17SBjoern A. Zeeb 		}
585a4adf6ccSBjoern A. Zeeb 	}
586fb59c426SYoshinobu Inoue 
587fb59c426SYoshinobu Inoue 	/*
588fb59c426SYoshinobu Inoue 	 * draft-itojun-ipv6-tcp-to-anycast
589fb59c426SYoshinobu Inoue 	 * better place to put this in?
590fb59c426SYoshinobu Inoue 	 */
5913e88eb90SAndrey V. Elsukov 	ip6 = mtod(m, struct ip6_hdr *);
5923e88eb90SAndrey V. Elsukov 	ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
59333841545SHajimu UMEMOTO 	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
594fb59c426SYoshinobu Inoue 
5958c0fec80SRobert Watson 		ifa_free(&ia6->ia_ifa);
596fb59c426SYoshinobu Inoue 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
597fb59c426SYoshinobu Inoue 			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
598a8fe77d8SBjoern A. Zeeb 		*mp = NULL;
5998f5a8818SKevin Lo 		return (IPPROTO_DONE);
600fb59c426SYoshinobu Inoue 	}
60177d396fdSMaksim Yevmenkin 	if (ia6)
60277d396fdSMaksim Yevmenkin 		ifa_free(&ia6->ia_ifa);
603fb59c426SYoshinobu Inoue 
604a8fe77d8SBjoern A. Zeeb 	*mp = m;
6058f5a8818SKevin Lo 	return (tcp_input(mp, offp, proto));
606fb59c426SYoshinobu Inoue }
607b287c6c7SBjoern A. Zeeb #endif /* INET6 */
608fb59c426SYoshinobu Inoue 
6098f5a8818SKevin Lo int
6108f5a8818SKevin Lo tcp_input(struct mbuf **mp, int *offp, int proto)
611df8bae1dSRodney W. Grimes {
6128f5a8818SKevin Lo 	struct mbuf *m = *mp;
613b287c6c7SBjoern A. Zeeb 	struct tcphdr *th = NULL;
614ad3f9ab3SAndre Oppermann 	struct ip *ip = NULL;
615ad3f9ab3SAndre Oppermann 	struct inpcb *inp = NULL;
616302ce8d6SAndre Oppermann 	struct tcpcb *tp = NULL;
617302ce8d6SAndre Oppermann 	struct socket *so = NULL;
618e79adb8eSGarrett Wollman 	u_char *optp = NULL;
6198f5a8818SKevin Lo 	int off0;
62026f9a767SRodney W. Grimes 	int optlen = 0;
621b287c6c7SBjoern A. Zeeb #ifdef INET
622b287c6c7SBjoern A. Zeeb 	int len;
623c4556b2fSAndrey V. Elsukov 	uint8_t ipttl;
624b287c6c7SBjoern A. Zeeb #endif
625b287c6c7SBjoern A. Zeeb 	int tlen = 0, off;
626fb59c426SYoshinobu Inoue 	int drop_hdrlen;
627ad3f9ab3SAndre Oppermann 	int thflags;
628302ce8d6SAndre Oppermann 	int rstreason = 0;	/* For badport_bandlim accounting purposes */
6291d7ee746SKurt Lidl 	uint8_t iptos;
630c1de64a4SAndrey V. Elsukov 	struct m_tag *fwd_tag = NULL;
631c068736aSJeffrey Hsu #ifdef INET6
632302ce8d6SAndre Oppermann 	struct ip6_hdr *ip6 = NULL;
633c068736aSJeffrey Hsu 	int isipv6;
634c068736aSJeffrey Hsu #else
635a160e630SAndre Oppermann 	const void *ip6 = NULL;
636b287c6c7SBjoern A. Zeeb #endif /* INET6 */
637302ce8d6SAndre Oppermann 	struct tcpopt to;		/* options in this segment */
638a160e630SAndre Oppermann 	char *s = NULL;			/* address and port logging */
639610ee2f9SDavid Greenman #ifdef TCPDEBUG
640c068736aSJeffrey Hsu 	/*
641c068736aSJeffrey Hsu 	 * The size of tcp_saveipgen must be the size of the max ip header,
642c068736aSJeffrey Hsu 	 * now IPv6.
643c068736aSJeffrey Hsu 	 */
64414739780SMaxim Konovalov 	u_char tcp_saveipgen[IP6_HDR_LEN];
645410bb1bfSLuigi Rizzo 	struct tcphdr tcp_savetcp;
646610ee2f9SDavid Greenman 	short ostate = 0;
647610ee2f9SDavid Greenman #endif
648c068736aSJeffrey Hsu 
649d40c0d47SGleb Smirnoff 	NET_EPOCH_ASSERT();
650d40c0d47SGleb Smirnoff 
651fb59c426SYoshinobu Inoue #ifdef INET6
652fb59c426SYoshinobu Inoue 	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
653fb59c426SYoshinobu Inoue #endif
654a0292f23SGarrett Wollman 
6558f5a8818SKevin Lo 	off0 = *offp;
6568f5a8818SKevin Lo 	m = *mp;
6578f5a8818SKevin Lo 	*mp = NULL;
658302ce8d6SAndre Oppermann 	to.to_flags = 0;
65978b50714SRobert Watson 	TCPSTAT_INC(tcps_rcvtotal);
660fb59c426SYoshinobu Inoue 
66104d3a452SHajimu UMEMOTO #ifdef INET6
662b287c6c7SBjoern A. Zeeb 	if (isipv6) {
66345747ba5SBjoern A. Zeeb 
664fb59c426SYoshinobu Inoue 		ip6 = mtod(m, struct ip6_hdr *);
66545747ba5SBjoern A. Zeeb 		th = (struct tcphdr *)((caddr_t)ip6 + off0);
666fb59c426SYoshinobu Inoue 		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
667356ab07eSBjoern A. Zeeb 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
66845747ba5SBjoern A. Zeeb 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
66945747ba5SBjoern A. Zeeb 				th->th_sum = m->m_pkthdr.csum_data;
67045747ba5SBjoern A. Zeeb 			else
67145747ba5SBjoern A. Zeeb 				th->th_sum = in6_cksum_pseudo(ip6, tlen,
67245747ba5SBjoern A. Zeeb 				    IPPROTO_TCP, m->m_pkthdr.csum_data);
67345747ba5SBjoern A. Zeeb 			th->th_sum ^= 0xffff;
67445747ba5SBjoern A. Zeeb 		} else
67545747ba5SBjoern A. Zeeb 			th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
67645747ba5SBjoern A. Zeeb 		if (th->th_sum) {
67778b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvbadsum);
678fb59c426SYoshinobu Inoue 			goto drop;
679fb59c426SYoshinobu Inoue 		}
68033841545SHajimu UMEMOTO 
68133841545SHajimu UMEMOTO 		/*
68233841545SHajimu UMEMOTO 		 * Be proactive about unspecified IPv6 address in source.
68333841545SHajimu UMEMOTO 		 * As we use all-zero to indicate unbounded/unconnected pcb,
68433841545SHajimu UMEMOTO 		 * unspecified IPv6 address can be used to confuse us.
68533841545SHajimu UMEMOTO 		 *
68633841545SHajimu UMEMOTO 		 * Note that packets with unspecified IPv6 destination is
68733841545SHajimu UMEMOTO 		 * already dropped in ip6_input.
68833841545SHajimu UMEMOTO 		 */
68933841545SHajimu UMEMOTO 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
69033841545SHajimu UMEMOTO 			/* XXX stat */
69133841545SHajimu UMEMOTO 			goto drop;
69233841545SHajimu UMEMOTO 		}
6931d7ee746SKurt Lidl 		iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
694b287c6c7SBjoern A. Zeeb 	}
69504d3a452SHajimu UMEMOTO #endif
696b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
697b287c6c7SBjoern A. Zeeb 	else
698b287c6c7SBjoern A. Zeeb #endif
699b287c6c7SBjoern A. Zeeb #ifdef INET
700b287c6c7SBjoern A. Zeeb 	{
701df8bae1dSRodney W. Grimes 		/*
702df8bae1dSRodney W. Grimes 		 * Get IP and TCP header together in first mbuf.
703df8bae1dSRodney W. Grimes 		 * Note: IP leaves IP header in first mbuf.
704df8bae1dSRodney W. Grimes 		 */
705fb59c426SYoshinobu Inoue 		if (off0 > sizeof (struct ip)) {
706105bd211SGleb Smirnoff 			ip_stripoptions(m);
707fb59c426SYoshinobu Inoue 			off0 = sizeof(struct ip);
708fb59c426SYoshinobu Inoue 		}
709df8bae1dSRodney W. Grimes 		if (m->m_len < sizeof (struct tcpiphdr)) {
7104dfdffe9SAndre Oppermann 			if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
7114dfdffe9SAndre Oppermann 			    == NULL) {
71278b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvshort);
7138f5a8818SKevin Lo 				return (IPPROTO_DONE);
714df8bae1dSRodney W. Grimes 			}
715df8bae1dSRodney W. Grimes 		}
716fb59c426SYoshinobu Inoue 		ip = mtod(m, struct ip *);
717db4f9cc7SJonathan Lemon 		th = (struct tcphdr *)((caddr_t)ip + off0);
7188ad458a4SGleb Smirnoff 		tlen = ntohs(ip->ip_len) - off0;
719df8bae1dSRodney W. Grimes 
7201d7ee746SKurt Lidl 		iptos = ip->ip_tos;
721db4f9cc7SJonathan Lemon 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
722db4f9cc7SJonathan Lemon 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
723db4f9cc7SJonathan Lemon 				th->th_sum = m->m_pkthdr.csum_data;
724db4f9cc7SJonathan Lemon 			else
725db4f9cc7SJonathan Lemon 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
726c068736aSJeffrey Hsu 				    ip->ip_dst.s_addr,
7278f134647SGleb Smirnoff 				    htonl(m->m_pkthdr.csum_data + tlen +
728c068736aSJeffrey Hsu 				    IPPROTO_TCP));
729db4f9cc7SJonathan Lemon 			th->th_sum ^= 0xffff;
730db4f9cc7SJonathan Lemon 		} else {
7318f134647SGleb Smirnoff 			struct ipovly *ipov = (struct ipovly *)ip;
7328f134647SGleb Smirnoff 
733df8bae1dSRodney W. Grimes 			/*
734df8bae1dSRodney W. Grimes 			 * Checksum extended TCP header and data.
735df8bae1dSRodney W. Grimes 			 */
7368f134647SGleb Smirnoff 			len = off0 + tlen;
737c4556b2fSAndrey V. Elsukov 			ipttl = ip->ip_ttl;
738fb59c426SYoshinobu Inoue 			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
7398f134647SGleb Smirnoff 			ipov->ih_len = htons(tlen);
740fb59c426SYoshinobu Inoue 			th->th_sum = in_cksum(m, len);
74157f60867SMark Johnston 			/* Reset length for SDT probes. */
7421d7ee746SKurt Lidl 			ip->ip_len = htons(len);
7431d7ee746SKurt Lidl 			/* Reset TOS bits */
7441d7ee746SKurt Lidl 			ip->ip_tos = iptos;
7451d7ee746SKurt Lidl 			/* Re-initialization for later version check */
746c4556b2fSAndrey V. Elsukov 			ip->ip_ttl = ipttl;
7471d7ee746SKurt Lidl 			ip->ip_v = IPVERSION;
748b2fe54bcSAndrey V. Elsukov 			ip->ip_hl = off0 >> 2;
749db4f9cc7SJonathan Lemon 		}
75057f60867SMark Johnston 
751fb59c426SYoshinobu Inoue 		if (th->th_sum) {
75278b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvbadsum);
753df8bae1dSRodney W. Grimes 			goto drop;
754df8bae1dSRodney W. Grimes 		}
755fb59c426SYoshinobu Inoue 	}
756b287c6c7SBjoern A. Zeeb #endif /* INET */
757df8bae1dSRodney W. Grimes 
758df8bae1dSRodney W. Grimes 	/*
759df8bae1dSRodney W. Grimes 	 * Check that TCP offset makes sense,
760df8bae1dSRodney W. Grimes 	 * pull out TCP options and adjust length.		XXX
761df8bae1dSRodney W. Grimes 	 */
762fb59c426SYoshinobu Inoue 	off = th->th_off << 2;
763df8bae1dSRodney W. Grimes 	if (off < sizeof (struct tcphdr) || off > tlen) {
76478b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvbadoff);
765df8bae1dSRodney W. Grimes 		goto drop;
766df8bae1dSRodney W. Grimes 	}
767fb59c426SYoshinobu Inoue 	tlen -= off;	/* tlen is used instead of ti->ti_len */
768df8bae1dSRodney W. Grimes 	if (off > sizeof (struct tcphdr)) {
76904d3a452SHajimu UMEMOTO #ifdef INET6
770b287c6c7SBjoern A. Zeeb 		if (isipv6) {
771a4adf6ccSBjoern A. Zeeb 			if (m->m_len < off0 + off) {
7724e619b17SBjoern A. Zeeb 				m = m_pullup(m, off0 + off);
7734e619b17SBjoern A. Zeeb 				if (m == NULL) {
7744e619b17SBjoern A. Zeeb 					TCPSTAT_INC(tcps_rcvshort);
7754e619b17SBjoern A. Zeeb 					return (IPPROTO_DONE);
7764e619b17SBjoern A. Zeeb 				}
777a4adf6ccSBjoern A. Zeeb 			}
778fb59c426SYoshinobu Inoue 			ip6 = mtod(m, struct ip6_hdr *);
779fb59c426SYoshinobu Inoue 			th = (struct tcphdr *)((caddr_t)ip6 + off0);
780b287c6c7SBjoern A. Zeeb 		}
78104d3a452SHajimu UMEMOTO #endif
782b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
783b287c6c7SBjoern A. Zeeb 		else
784b287c6c7SBjoern A. Zeeb #endif
785b287c6c7SBjoern A. Zeeb #ifdef INET
786b287c6c7SBjoern A. Zeeb 		{
787df8bae1dSRodney W. Grimes 			if (m->m_len < sizeof(struct ip) + off) {
788c068736aSJeffrey Hsu 				if ((m = m_pullup(m, sizeof (struct ip) + off))
7894dfdffe9SAndre Oppermann 				    == NULL) {
79078b50714SRobert Watson 					TCPSTAT_INC(tcps_rcvshort);
7918f5a8818SKevin Lo 					return (IPPROTO_DONE);
792df8bae1dSRodney W. Grimes 				}
793fb59c426SYoshinobu Inoue 				ip = mtod(m, struct ip *);
794fb59c426SYoshinobu Inoue 				th = (struct tcphdr *)((caddr_t)ip + off0);
795fb59c426SYoshinobu Inoue 			}
796df8bae1dSRodney W. Grimes 		}
797b287c6c7SBjoern A. Zeeb #endif
798df8bae1dSRodney W. Grimes 		optlen = off - sizeof (struct tcphdr);
799fb59c426SYoshinobu Inoue 		optp = (u_char *)(th + 1);
800df8bae1dSRodney W. Grimes 	}
801fb59c426SYoshinobu Inoue 	thflags = th->th_flags;
802df8bae1dSRodney W. Grimes 
803e46cd3d4SDag-Erling Smørgrav 	/*
804df8bae1dSRodney W. Grimes 	 * Convert TCP protocol specific fields to host format.
805df8bae1dSRodney W. Grimes 	 */
8062903309aSAttilio Rao 	tcp_fields_to_host(th);
807df8bae1dSRodney W. Grimes 
808df8bae1dSRodney W. Grimes 	/*
809794235b7SAndre Oppermann 	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
810755c1f07SAndras Olah 	 */
811fb59c426SYoshinobu Inoue 	drop_hdrlen = off0 + off;
812755c1f07SAndras Olah 
813755c1f07SAndras Olah 	/*
8148d573cc1SAndre Oppermann 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
8158d573cc1SAndre Oppermann 	 */
816b8056faeSGleb Smirnoff         if (
817b8056faeSGleb Smirnoff #ifdef INET6
818b8056faeSGleb Smirnoff 	    (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
819b8056faeSGleb Smirnoff #ifdef INET
820b8056faeSGleb Smirnoff 	    || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
821b8056faeSGleb Smirnoff #endif
822b8056faeSGleb Smirnoff #endif
823b8056faeSGleb Smirnoff #if defined(INET) && !defined(INET6)
824b8056faeSGleb Smirnoff 	    (m->m_flags & M_IP_NEXTHOP)
825b8056faeSGleb Smirnoff #endif
826b8056faeSGleb Smirnoff 	    )
8279b932e9eSAndre Oppermann 		fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
8289b932e9eSAndre Oppermann 
829ce7ad664SEd Maste findpcb:
8308a006adbSBjoern A. Zeeb #ifdef INET6
8318a006adbSBjoern A. Zeeb 	if (isipv6 && fwd_tag != NULL) {
8328a006adbSBjoern A. Zeeb 		struct sockaddr_in6 *next_hop6;
8338a006adbSBjoern A. Zeeb 
8348a006adbSBjoern A. Zeeb 		next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
8358a006adbSBjoern A. Zeeb 		/*
8368a006adbSBjoern A. Zeeb 		 * Transparently forwarded. Pretend to be the destination.
8378a006adbSBjoern A. Zeeb 		 * Already got one like this?
8388a006adbSBjoern A. Zeeb 		 */
8398a006adbSBjoern A. Zeeb 		inp = in6_pcblookup_mbuf(&V_tcbinfo,
8408a006adbSBjoern A. Zeeb 		    &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
8418a006adbSBjoern A. Zeeb 		    INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
8428a006adbSBjoern A. Zeeb 		if (!inp) {
8438a006adbSBjoern A. Zeeb 			/*
8448a006adbSBjoern A. Zeeb 			 * It's new.  Try to find the ambushing socket.
8458a006adbSBjoern A. Zeeb 			 * Because we've rewritten the destination address,
8468a006adbSBjoern A. Zeeb 			 * any hardware-generated hash is ignored.
8478a006adbSBjoern A. Zeeb 			 */
8488a006adbSBjoern A. Zeeb 			inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
8498a006adbSBjoern A. Zeeb 			    th->th_sport, &next_hop6->sin6_addr,
8508a006adbSBjoern A. Zeeb 			    next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
8518a006adbSBjoern A. Zeeb 			    th->th_dport, INPLOOKUP_WILDCARD |
8528a006adbSBjoern A. Zeeb 			    INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
8538a006adbSBjoern A. Zeeb 		}
854c1de64a4SAndrey V. Elsukov 	} else if (isipv6) {
8558a006adbSBjoern A. Zeeb 		inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
8568a006adbSBjoern A. Zeeb 		    th->th_sport, &ip6->ip6_dst, th->th_dport,
8578a006adbSBjoern A. Zeeb 		    INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
8588a006adbSBjoern A. Zeeb 		    m->m_pkthdr.rcvif, m);
8598a006adbSBjoern A. Zeeb 	}
8608a006adbSBjoern A. Zeeb #endif /* INET6 */
8618a006adbSBjoern A. Zeeb #if defined(INET6) && defined(INET)
8628a006adbSBjoern A. Zeeb 	else
8638a006adbSBjoern A. Zeeb #endif
8648a006adbSBjoern A. Zeeb #ifdef INET
8658a006adbSBjoern A. Zeeb 	if (fwd_tag != NULL) {
8669b932e9eSAndre Oppermann 		struct sockaddr_in *next_hop;
8679b932e9eSAndre Oppermann 
8689b932e9eSAndre Oppermann 		next_hop = (struct sockaddr_in *)(fwd_tag+1);
869f9e354dfSJulian Elischer 		/*
8702b25acc1SLuigi Rizzo 		 * Transparently forwarded. Pretend to be the destination.
871f9e354dfSJulian Elischer 		 * already got one like this?
872f9e354dfSJulian Elischer 		 */
873d3c1f003SRobert Watson 		inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
874fa046d87SRobert Watson 		    ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
875d3c1f003SRobert Watson 		    m->m_pkthdr.rcvif, m);
876fa046d87SRobert Watson 		if (!inp) {
877fa046d87SRobert Watson 			/*
878fa046d87SRobert Watson 			 * It's new.  Try to find the ambushing socket.
879d3c1f003SRobert Watson 			 * Because we've rewritten the destination address,
880d3c1f003SRobert Watson 			 * any hardware-generated hash is ignored.
881fa046d87SRobert Watson 			 */
882fa046d87SRobert Watson 			inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
883fa046d87SRobert Watson 			    th->th_sport, next_hop->sin_addr,
884fa046d87SRobert Watson 			    next_hop->sin_port ? ntohs(next_hop->sin_port) :
885fa046d87SRobert Watson 			    th->th_dport, INPLOOKUP_WILDCARD |
886fa046d87SRobert Watson 			    INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
887f9e354dfSJulian Elischer 		}
888b10fbdeaSAndre Oppermann 	} else
889d3c1f003SRobert Watson 		inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
890fa046d87SRobert Watson 		    th->th_sport, ip->ip_dst, th->th_dport,
891fa046d87SRobert Watson 		    INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
892d3c1f003SRobert Watson 		    m->m_pkthdr.rcvif, m);
8938a006adbSBjoern A. Zeeb #endif /* INET */
894f9e354dfSJulian Elischer 
895df8bae1dSRodney W. Grimes 	/*
896574b6964SAndre Oppermann 	 * If the INPCB does not exist then all data in the incoming
897574b6964SAndre Oppermann 	 * segment is discarded and an appropriate RST is sent back.
8988b07e49aSJulian Elischer 	 * XXX MRT Send RST using which routing table?
899df8bae1dSRodney W. Grimes 	 */
900816a3d83SPoul-Henning Kamp 	if (inp == NULL) {
901574b6964SAndre Oppermann 		/*
902574b6964SAndre Oppermann 		 * Log communication attempts to ports that are not
903574b6964SAndre Oppermann 		 * in use.
904574b6964SAndre Oppermann 		 */
905334fc582SBjoern A. Zeeb 		if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
906334fc582SBjoern A. Zeeb 		    V_tcp_log_in_vain == 2) {
907b7d747ecSAndre Oppermann 			if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
908df541e5fSAndre Oppermann 				log(LOG_INFO, "%s; %s: Connection attempt "
909df541e5fSAndre Oppermann 				    "to closed port\n", s, __func__);
9102e4e1b4cSGeoff Rehmet 		}
911574b6964SAndre Oppermann 		/*
912574b6964SAndre Oppermann 		 * When blackholing do not respond with a RST but
913574b6964SAndre Oppermann 		 * completely ignore the segment and drop it.
914574b6964SAndre Oppermann 		 */
915603724d3SBjoern A. Zeeb 		if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
916603724d3SBjoern A. Zeeb 		    V_blackhole == 2)
9171929eae1SAndre Oppermann 			goto dropunlock;
918574b6964SAndre Oppermann 
919a57815efSBosko Milekic 		rstreason = BANDLIM_RST_CLOSEDPORT;
920a57815efSBosko Milekic 		goto dropwithreset;
921816a3d83SPoul-Henning Kamp 	}
922fa046d87SRobert Watson 	INP_WLOCK_ASSERT(inp);
923f5cf1e5fSJulien Charbon 	/*
924f5cf1e5fSJulien Charbon 	 * While waiting for inp lock during the lookup, another thread
925f5cf1e5fSJulien Charbon 	 * can have dropped the inpcb, in which case we need to loop back
926f5cf1e5fSJulien Charbon 	 * and try to find a new inpcb to deliver to.
927f5cf1e5fSJulien Charbon 	 */
928f5cf1e5fSJulien Charbon 	if (inp->inp_flags & INP_DROPPED) {
929f5cf1e5fSJulien Charbon 		INP_WUNLOCK(inp);
930f5cf1e5fSJulien Charbon 		inp = NULL;
931f5cf1e5fSJulien Charbon 		goto findpcb;
932f5cf1e5fSJulien Charbon 	}
933c2529042SHans Petter Selasky 	if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
934c2529042SHans Petter Selasky 	    (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
935c2529042SHans Petter Selasky 	    ((inp->inp_socket == NULL) ||
936c2529042SHans Petter Selasky 	    (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
93780cb9f21SKip Macy 		inp->inp_flowid = m->m_pkthdr.flowid;
9382f719932SAdrian Chadd 		inp->inp_flowtype = M_HASHTYPE_GET(m);
93980cb9f21SKip Macy 	}
940fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
941a2589465SKen Smith #ifdef INET6
942fcf59617SAndrey V. Elsukov 	if (isipv6 && IPSEC_ENABLED(ipv6) &&
943fcf59617SAndrey V. Elsukov 	    IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
944a2589465SKen Smith 		goto dropunlock;
945a2589465SKen Smith 	}
946fcf59617SAndrey V. Elsukov #ifdef INET
947fcf59617SAndrey V. Elsukov 	else
948fcf59617SAndrey V. Elsukov #endif
949fcf59617SAndrey V. Elsukov #endif /* INET6 */
950fcf59617SAndrey V. Elsukov #ifdef INET
951fcf59617SAndrey V. Elsukov 	if (IPSEC_ENABLED(ipv4) &&
952fcf59617SAndrey V. Elsukov 	    IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
953fcf59617SAndrey V. Elsukov 		goto dropunlock;
954fcf59617SAndrey V. Elsukov 	}
955fcf59617SAndrey V. Elsukov #endif /* INET */
956a2589465SKen Smith #endif /* IPSEC */
957a2589465SKen Smith 
9588d573cc1SAndre Oppermann 	/*
9598d573cc1SAndre Oppermann 	 * Check the minimum TTL for socket.
9608d573cc1SAndre Oppermann 	 */
96134f83c52SGeorge V. Neville-Neil 	if (inp->inp_ip_minttl != 0) {
96234f83c52SGeorge V. Neville-Neil #ifdef INET6
9632d8868dbSJonathan T. Looney 		if (isipv6) {
9642d8868dbSJonathan T. Looney 			if (inp->inp_ip_minttl > ip6->ip6_hlim)
965302ce8d6SAndre Oppermann 				goto dropunlock;
9662d8868dbSJonathan T. Looney 		} else
96734f83c52SGeorge V. Neville-Neil #endif
96834f83c52SGeorge V. Neville-Neil 		if (inp->inp_ip_minttl > ip->ip_ttl)
969302ce8d6SAndre Oppermann 			goto dropunlock;
97034f83c52SGeorge V. Neville-Neil 	}
971936cd18dSAndre Oppermann 
972340c35deSJonathan Lemon 	/*
973252ca428SRobert Watson 	 * A previous connection in TIMEWAIT state is supposed to catch stray
974252ca428SRobert Watson 	 * or duplicate segments arriving late.  If this segment was a
9750989f56cSRobert Watson 	 * legitimate new connection attempt, the old INPCB gets removed and
976252ca428SRobert Watson 	 * we can try again to find a listening socket.
977252ca428SRobert Watson 	 *
978fa046d87SRobert Watson 	 * At this point, due to earlier optimism, we may hold only an inpcb
979fa046d87SRobert Watson 	 * lock, and not the inpcbinfo write lock.  If so, we need to try to
980fa046d87SRobert Watson 	 * acquire it, or if that fails, acquire a reference on the inpcb,
981fa046d87SRobert Watson 	 * drop all locks, acquire a global write lock, and then re-acquire
982fa046d87SRobert Watson 	 * the inpcb lock.  We may at that point discover that another thread
983fa046d87SRobert Watson 	 * has tried to free the inpcb, in which case we need to loop back
984fa046d87SRobert Watson 	 * and try to find a new inpcb to deliver to.
985fa046d87SRobert Watson 	 *
986fa046d87SRobert Watson 	 * XXXRW: It may be time to rethink timewait locking.
987340c35deSJonathan Lemon 	 */
988ad71fe3cSRobert Watson 	if (inp->inp_flags & INP_TIMEWAIT) {
989340c35deSJonathan Lemon 		if (thflags & TH_SYN)
990f72167f4SAndre Oppermann 			tcp_dooptions(&to, optp, optlen, TO_SYN);
9918d573cc1SAndre Oppermann 		/*
9928d573cc1SAndre Oppermann 		 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
9938d573cc1SAndre Oppermann 		 */
9942104448fSAndre Oppermann 		if (tcp_twcheck(inp, &to, th, m, tlen))
995340c35deSJonathan Lemon 			goto findpcb;
9968f5a8818SKevin Lo 		return (IPPROTO_DONE);
997340c35deSJonathan Lemon 	}
998794235b7SAndre Oppermann 	/*
999794235b7SAndre Oppermann 	 * The TCPCB may no longer exist if the connection is winding
1000794235b7SAndre Oppermann 	 * down or it is in the CLOSED state.  Either way we drop the
1001794235b7SAndre Oppermann 	 * segment and send an appropriate response.
1002794235b7SAndre Oppermann 	 */
1003df8bae1dSRodney W. Grimes 	tp = intotcpcb(inp);
1004a160e630SAndre Oppermann 	if (tp == NULL || tp->t_state == TCPS_CLOSED) {
1005a57815efSBosko Milekic 		rstreason = BANDLIM_RST_CLOSEDPORT;
1006a57815efSBosko Milekic 		goto dropwithreset;
100709f81a46SBosko Milekic 	}
1008df8bae1dSRodney W. Grimes 
100909fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
101009fe6320SNavdeep Parhar 	if (tp->t_flags & TF_TOE) {
101109fe6320SNavdeep Parhar 		tcp_offload_input(tp, m);
101209fe6320SNavdeep Parhar 		m = NULL;	/* consumed by the TOE driver */
101309fe6320SNavdeep Parhar 		goto dropunlock;
101409fe6320SNavdeep Parhar 	}
101509fe6320SNavdeep Parhar #endif
101609fe6320SNavdeep Parhar 
1017c488362eSRobert Watson #ifdef MAC
10188501a69cSRobert Watson 	INP_WLOCK_ASSERT(inp);
101930d239bcSRobert Watson 	if (mac_inpcb_check_deliver(inp, m))
1020302ce8d6SAndre Oppermann 		goto dropunlock;
1021c488362eSRobert Watson #endif
1022a557af22SRobert Watson 	so = inp->inp_socket;
1023302ce8d6SAndre Oppermann 	KASSERT(so != NULL, ("%s: so == NULL", __func__));
1024610ee2f9SDavid Greenman #ifdef TCPDEBUG
1025df8bae1dSRodney W. Grimes 	if (so->so_options & SO_DEBUG) {
1026df8bae1dSRodney W. Grimes 		ostate = tp->t_state;
102710fe523eSMaxim Konovalov #ifdef INET6
10286f697424SBjoern A. Zeeb 		if (isipv6) {
1029540e8b7eSJeffrey Hsu 			bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1030d30d90dcSMaxim Konovalov 		} else
10316f697424SBjoern A. Zeeb #endif
1032540e8b7eSJeffrey Hsu 			bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1033fb59c426SYoshinobu Inoue 		tcp_savetcp = *th;
1034df8bae1dSRodney W. Grimes 	}
1035b287c6c7SBjoern A. Zeeb #endif /* TCPDEBUG */
1036db33b3e6SAndre Oppermann 	/*
1037db33b3e6SAndre Oppermann 	 * When the socket is accepting connections (the INPCB is in LISTEN
1038db33b3e6SAndre Oppermann 	 * state) we look into the SYN cache if this is a new connection
1039a7c7f2a7SJohn Baldwin 	 * attempt or the completion of a previous one.
1040db33b3e6SAndre Oppermann 	 */
104145274760SJonathan T. Looney 	KASSERT(tp->t_state == TCPS_LISTEN || !(so->so_options & SO_ACCEPTCONN),
104245274760SJonathan T. Looney 	    ("%s: so accepting but tp %p not listening", __func__, tp));
104345274760SJonathan T. Looney 	if (tp->t_state == TCPS_LISTEN && (so->so_options & SO_ACCEPTCONN)) {
1044540e8b7eSJeffrey Hsu 		struct in_conninfo inc;
1045540e8b7eSJeffrey Hsu 
10468bfb1918SAndre Oppermann 		bzero(&inc, sizeof(inc));
1047302ce8d6SAndre Oppermann #ifdef INET6
1048be2ac88cSJonathan Lemon 		if (isipv6) {
1049dcdb4371SBjoern A. Zeeb 			inc.inc_flags |= INC_ISIPV6;
10505dff1c38SMichael Tuexen 			if (inp->inp_inc.inc_flags & INC_IPV6MINMTU)
10515dff1c38SMichael Tuexen 				inc.inc_flags |= INC_IPV6MINMTU;
1052be2ac88cSJonathan Lemon 			inc.inc6_faddr = ip6->ip6_src;
1053be2ac88cSJonathan Lemon 			inc.inc6_laddr = ip6->ip6_dst;
1054302ce8d6SAndre Oppermann 		} else
1055302ce8d6SAndre Oppermann #endif
1056302ce8d6SAndre Oppermann 		{
1057be2ac88cSJonathan Lemon 			inc.inc_faddr = ip->ip_src;
1058be2ac88cSJonathan Lemon 			inc.inc_laddr = ip->ip_dst;
1059be2ac88cSJonathan Lemon 		}
1060be2ac88cSJonathan Lemon 		inc.inc_fport = th->th_sport;
1061be2ac88cSJonathan Lemon 		inc.inc_lport = th->th_dport;
10627973fba3SJulian Elischer 		inc.inc_fibnum = so->so_fibnum;
1063be2ac88cSJonathan Lemon 
1064fb59c426SYoshinobu Inoue 		/*
10658d573cc1SAndre Oppermann 		 * Check for an existing connection attempt in syncache if
10668d573cc1SAndre Oppermann 		 * the flag is only ACK.  A successful lookup creates a new
10678d573cc1SAndre Oppermann 		 * socket appended to the listen queue in SYN_RECEIVED state.
1068fb59c426SYoshinobu Inoue 		 */
1069be2ac88cSJonathan Lemon 		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1070a7c7f2a7SJohn Baldwin 
1071bf6d304aSAndre Oppermann 			/*
1072bf6d304aSAndre Oppermann 			 * Parse the TCP options here because
1073bf6d304aSAndre Oppermann 			 * syncookies need access to the reflected
1074bf6d304aSAndre Oppermann 			 * timestamp.
1075bf6d304aSAndre Oppermann 			 */
1076bf6d304aSAndre Oppermann 			tcp_dooptions(&to, optp, optlen, 0);
10779fa198beSAndre Oppermann 			/*
10789fa198beSAndre Oppermann 			 * NB: syncache_expand() doesn't unlock
10799fa198beSAndre Oppermann 			 * inp and tcpinfo locks.
10809fa198beSAndre Oppermann 			 */
1081fcf59617SAndrey V. Elsukov 			rstreason = syncache_expand(&inc, &to, th, &so, m);
1082fcf59617SAndrey V. Elsukov 			if (rstreason < 0) {
1083fcf59617SAndrey V. Elsukov 				/*
1084fcf59617SAndrey V. Elsukov 				 * A failing TCP MD5 signature comparison
1085fcf59617SAndrey V. Elsukov 				 * must result in the segment being dropped
1086fcf59617SAndrey V. Elsukov 				 * and must not produce any response back
1087fcf59617SAndrey V. Elsukov 				 * to the sender.
1088fcf59617SAndrey V. Elsukov 				 */
1089fcf59617SAndrey V. Elsukov 				goto dropunlock;
1090fcf59617SAndrey V. Elsukov 			} else if (rstreason == 0) {
10914195b4afSPaul Traina 				/*
1092e207f800SAndre Oppermann 				 * No syncache entry or ACK was not
1093be2ac88cSJonathan Lemon 				 * for our SYN/ACK.  Send a RST.
10948d573cc1SAndre Oppermann 				 * NB: syncache did its own logging
10958d573cc1SAndre Oppermann 				 * of the failure cause.
10964195b4afSPaul Traina 				 */
1097be2ac88cSJonathan Lemon 				rstreason = BANDLIM_RST_OPENPORT;
1098be2ac88cSJonathan Lemon 				goto dropwithreset;
1099be2ac88cSJonathan Lemon 			}
110009c305ebSPatrick Kelsey tfo_socket_result:
1101f76fcf6dSJeffrey Hsu 			if (so == NULL) {
1102be2ac88cSJonathan Lemon 				/*
1103e207f800SAndre Oppermann 				 * We completed the 3-way handshake
1104e207f800SAndre Oppermann 				 * but could not allocate a socket
1105e207f800SAndre Oppermann 				 * either due to memory shortage,
1106e207f800SAndre Oppermann 				 * listen queue length limits or
1107a160e630SAndre Oppermann 				 * global socket limits.  Send RST
1108a160e630SAndre Oppermann 				 * or wait and have the remote end
1109a160e630SAndre Oppermann 				 * retransmit the ACK for another
1110a160e630SAndre Oppermann 				 * try.
1111be2ac88cSJonathan Lemon 				 */
1112a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1113a160e630SAndre Oppermann 					log(LOG_DEBUG, "%s; %s: Listen socket: "
11148d573cc1SAndre Oppermann 					    "Socket allocation failed due to "
11158d573cc1SAndre Oppermann 					    "limits or memory shortage, %s\n",
1116ac957cd2SJulian Elischer 					    s, __func__,
1117ac957cd2SJulian Elischer 					    V_tcp_sc_rst_sock_fail ?
1118ac957cd2SJulian Elischer 					    "sending RST" : "try again");
1119603724d3SBjoern A. Zeeb 				if (V_tcp_sc_rst_sock_fail) {
1120e207f800SAndre Oppermann 					rstreason = BANDLIM_UNLIMITED;
1121e207f800SAndre Oppermann 					goto dropwithreset;
1122a160e630SAndre Oppermann 				} else
1123a160e630SAndre Oppermann 					goto dropunlock;
1124f76fcf6dSJeffrey Hsu 			}
1125be2ac88cSJonathan Lemon 			/*
1126be2ac88cSJonathan Lemon 			 * Socket is created in state SYN_RECEIVED.
11278d573cc1SAndre Oppermann 			 * Unlock the listen socket, lock the newly
11288d573cc1SAndre Oppermann 			 * created socket and update the tp variable.
1129be2ac88cSJonathan Lemon 			 */
11308501a69cSRobert Watson 			INP_WUNLOCK(inp);	/* listen socket */
1131be2ac88cSJonathan Lemon 			inp = sotoinpcb(so);
1132ff9b006dSJulien Charbon 			/*
1133ff9b006dSJulien Charbon 			 * New connection inpcb is already locked by
1134ff9b006dSJulien Charbon 			 * syncache_expand().
1135ff9b006dSJulien Charbon 			 */
1136ff9b006dSJulien Charbon 			INP_WLOCK_ASSERT(inp);
1137be2ac88cSJonathan Lemon 			tp = intotcpcb(inp);
11388d573cc1SAndre Oppermann 			KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
11398d573cc1SAndre Oppermann 			    ("%s: ", __func__));
1140be2ac88cSJonathan Lemon 			/*
1141302ce8d6SAndre Oppermann 			 * Process the segment and the data it
1142302ce8d6SAndre Oppermann 			 * contains.  tcp_do_segment() consumes
1143302ce8d6SAndre Oppermann 			 * the mbuf chain and unlocks the inpcb.
1144302ce8d6SAndre Oppermann 			 */
11456138da62SMichael Tuexen 			TCP_PROBE5(receive, NULL, tp, m, tp, th);
114655bceb1eSRandall Stewart 			tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
11476573d758SMatt Macy 			    iptos);
11488f5a8818SKevin Lo 			return (IPPROTO_DONE);
1149be2ac88cSJonathan Lemon 		}
1150a160e630SAndre Oppermann 		/*
11518d573cc1SAndre Oppermann 		 * Segment flag validation for new connection attempts:
11528d573cc1SAndre Oppermann 		 *
1153a160e630SAndre Oppermann 		 * Our (SYN|ACK) response was rejected.
1154a160e630SAndre Oppermann 		 * Check with syncache and remove entry to prevent
1155a160e630SAndre Oppermann 		 * retransmits.
115619bc77c5SAndre Oppermann 		 *
115719bc77c5SAndre Oppermann 		 * NB: syncache_chkrst does its own logging of failure
115819bc77c5SAndre Oppermann 		 * causes.
1159a160e630SAndre Oppermann 		 */
1160a160e630SAndre Oppermann 		if (thflags & TH_RST) {
116193899d10SMichael Tuexen 			syncache_chkrst(&inc, th, m);
1162a160e630SAndre Oppermann 			goto dropunlock;
1163a160e630SAndre Oppermann 		}
1164a160e630SAndre Oppermann 		/*
1165a160e630SAndre Oppermann 		 * We can't do anything without SYN.
1166a160e630SAndre Oppermann 		 */
1167a160e630SAndre Oppermann 		if ((thflags & TH_SYN) == 0) {
1168a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1169a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
1170773673c1SAndre Oppermann 				    "SYN is missing, segment ignored\n",
11718d573cc1SAndre Oppermann 				    s, __func__);
117278b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1173a160e630SAndre Oppermann 			goto dropunlock;
1174a160e630SAndre Oppermann 		}
1175a160e630SAndre Oppermann 		/*
1176a160e630SAndre Oppermann 		 * (SYN|ACK) is bogus on a listen socket.
1177a160e630SAndre Oppermann 		 */
1178fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK) {
1179a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1180a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
11818d573cc1SAndre Oppermann 				    "SYN|ACK invalid, segment rejected\n",
11828d573cc1SAndre Oppermann 				    s, __func__);
1183a160e630SAndre Oppermann 			syncache_badack(&inc);	/* XXX: Not needed! */
118478b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1185a57815efSBosko Milekic 			rstreason = BANDLIM_RST_OPENPORT;
1186a57815efSBosko Milekic 			goto dropwithreset;
11874195b4afSPaul Traina 		}
1188a160e630SAndre Oppermann 		/*
1189a160e630SAndre Oppermann 		 * If the drop_synfin option is enabled, drop all
1190a160e630SAndre Oppermann 		 * segments with both the SYN and FIN bits set.
1191a160e630SAndre Oppermann 		 * This prevents e.g. nmap from identifying the
1192a160e630SAndre Oppermann 		 * TCP/IP stack.
1193a160e630SAndre Oppermann 		 * XXX: Poor reasoning.  nmap has other methods
1194a160e630SAndre Oppermann 		 * and is constantly refining its stack detection
1195a160e630SAndre Oppermann 		 * strategies.
11968d573cc1SAndre Oppermann 		 * XXX: This is a violation of the TCP specification
1197a160e630SAndre Oppermann 		 * and was used by RFC1644.
1198a160e630SAndre Oppermann 		 */
1199603724d3SBjoern A. Zeeb 		if ((thflags & TH_FIN) && V_drop_synfin) {
1200a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1201a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
1202773673c1SAndre Oppermann 				    "SYN|FIN segment ignored (based on "
12038d573cc1SAndre Oppermann 				    "sysctl setting)\n", s, __func__);
120478b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1205302ce8d6SAndre Oppermann 			goto dropunlock;
1206ebb0cbeaSPaul Traina 		}
1207be2ac88cSJonathan Lemon 		/*
1208be2ac88cSJonathan Lemon 		 * Segment's flags are (SYN) or (SYN|FIN).
1209a160e630SAndre Oppermann 		 *
1210a160e630SAndre Oppermann 		 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1211a160e630SAndre Oppermann 		 * as they do not affect the state of the TCP FSM.
1212a160e630SAndre Oppermann 		 * The data pointed to by TH_URG and th_urp is ignored.
1213be2ac88cSJonathan Lemon 		 */
1214a160e630SAndre Oppermann 		KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1215a160e630SAndre Oppermann 		    ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1216a160e630SAndre Oppermann 		KASSERT(thflags & (TH_SYN),
1217a160e630SAndre Oppermann 		    ("%s: Listen socket: TH_SYN not set", __func__));
121833841545SHajimu UMEMOTO #ifdef INET6
121933841545SHajimu UMEMOTO 		/*
122033841545SHajimu UMEMOTO 		 * If deprecated address is forbidden,
122133841545SHajimu UMEMOTO 		 * we do not accept SYN to deprecated interface
122233841545SHajimu UMEMOTO 		 * address to prevent any new inbound connection from
122333841545SHajimu UMEMOTO 		 * getting established.
122433841545SHajimu UMEMOTO 		 * When we do not accept SYN, we send a TCP RST,
122533841545SHajimu UMEMOTO 		 * with deprecated source address (instead of dropping
122633841545SHajimu UMEMOTO 		 * it).  We compromise it as it is much better for peer
122733841545SHajimu UMEMOTO 		 * to send a RST, and RST will be the final packet
122833841545SHajimu UMEMOTO 		 * for the exchange.
122933841545SHajimu UMEMOTO 		 *
123033841545SHajimu UMEMOTO 		 * If we do not forbid deprecated addresses, we accept
123133841545SHajimu UMEMOTO 		 * the SYN packet.  RFC2462 does not suggest dropping
123233841545SHajimu UMEMOTO 		 * SYN in this case.
123333841545SHajimu UMEMOTO 		 * If we decipher RFC2462 5.5.4, it says like this:
123433841545SHajimu UMEMOTO 		 * 1. use of deprecated addr with existing
123533841545SHajimu UMEMOTO 		 *    communication is okay - "SHOULD continue to be
123633841545SHajimu UMEMOTO 		 *    used"
123733841545SHajimu UMEMOTO 		 * 2. use of it with new communication:
123833841545SHajimu UMEMOTO 		 *   (2a) "SHOULD NOT be used if alternate address
123933841545SHajimu UMEMOTO 		 *        with sufficient scope is available"
124033841545SHajimu UMEMOTO 		 *   (2b) nothing mentioned otherwise.
124133841545SHajimu UMEMOTO 		 * Here we fall into (2b) case as we have no choice in
124233841545SHajimu UMEMOTO 		 * our source address selection - we must obey the peer.
124333841545SHajimu UMEMOTO 		 *
124433841545SHajimu UMEMOTO 		 * The wording in RFC2462 is confusing, and there are
124533841545SHajimu UMEMOTO 		 * multiple description text for deprecated address
124633841545SHajimu UMEMOTO 		 * handling - worse, they are not exactly the same.
124733841545SHajimu UMEMOTO 		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
124833841545SHajimu UMEMOTO 		 */
1249603724d3SBjoern A. Zeeb 		if (isipv6 && !V_ip6_use_deprecated) {
125033841545SHajimu UMEMOTO 			struct in6_ifaddr *ia6;
125133841545SHajimu UMEMOTO 
12523e88eb90SAndrey V. Elsukov 			ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
12538c0fec80SRobert Watson 			if (ia6 != NULL &&
125433841545SHajimu UMEMOTO 			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
12558c0fec80SRobert Watson 				ifa_free(&ia6->ia_ifa);
1256a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1257a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
12588d573cc1SAndre Oppermann 					"Connection attempt to deprecated "
12598d573cc1SAndre Oppermann 					"IPv6 address rejected\n",
1260a160e630SAndre Oppermann 					s, __func__);
126133841545SHajimu UMEMOTO 				rstreason = BANDLIM_RST_OPENPORT;
126233841545SHajimu UMEMOTO 				goto dropwithreset;
126333841545SHajimu UMEMOTO 			}
126477d396fdSMaksim Yevmenkin 			if (ia6)
12658c0fec80SRobert Watson 				ifa_free(&ia6->ia_ifa);
126633841545SHajimu UMEMOTO 		}
1267b287c6c7SBjoern A. Zeeb #endif /* INET6 */
126865f28919SJesper Skriver 		/*
1269db33b3e6SAndre Oppermann 		 * Basic sanity checks on incoming SYN requests:
12708d573cc1SAndre Oppermann 		 *   Don't respond if the destination is a link layer
1271db33b3e6SAndre Oppermann 		 *	broadcast according to RFC1122 4.2.3.10, p. 104.
12728d573cc1SAndre Oppermann 		 *   If it is from this socket it must be forged.
12738d573cc1SAndre Oppermann 		 *   Don't respond if the source or destination is a
12748d573cc1SAndre Oppermann 		 *	global or subnet broad- or multicast address.
127593ec91baSCrist J. Clark 		 *   Note that it is quite possible to receive unicast
127693ec91baSCrist J. Clark 		 *	link-layer packets with a broadcast IP address. Use
127793ec91baSCrist J. Clark 		 *	in_broadcast() to find them.
1278be2ac88cSJonathan Lemon 		 */
12798d573cc1SAndre Oppermann 		if (m->m_flags & (M_BCAST|M_MCAST)) {
12808d573cc1SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
12818d573cc1SAndre Oppermann 			    log(LOG_DEBUG, "%s; %s: Listen socket: "
12828d573cc1SAndre Oppermann 				"Connection attempt from broad- or multicast "
1283773673c1SAndre Oppermann 				"link layer address ignored\n", s, __func__);
1284302ce8d6SAndre Oppermann 			goto dropunlock;
12858d573cc1SAndre Oppermann 		}
1286db33b3e6SAndre Oppermann #ifdef INET6
1287b287c6c7SBjoern A. Zeeb 		if (isipv6) {
1288db33b3e6SAndre Oppermann 			if (th->th_dport == th->th_sport &&
1289a160e630SAndre Oppermann 			    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1290a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1291a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
12928d573cc1SAndre Oppermann 					"Connection attempt to/from self "
1293773673c1SAndre Oppermann 					"ignored\n", s, __func__);
1294302ce8d6SAndre Oppermann 				goto dropunlock;
1295a160e630SAndre Oppermann 			}
1296be2ac88cSJonathan Lemon 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1297a160e630SAndre Oppermann 			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1298a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1299a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13008d573cc1SAndre Oppermann 					"Connection attempt from/to multicast "
1301773673c1SAndre Oppermann 					"address ignored\n", s, __func__);
1302302ce8d6SAndre Oppermann 				goto dropunlock;
1303a160e630SAndre Oppermann 			}
1304b287c6c7SBjoern A. Zeeb 		}
1305db33b3e6SAndre Oppermann #endif
1306b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
1307b287c6c7SBjoern A. Zeeb 		else
1308b287c6c7SBjoern A. Zeeb #endif
1309b287c6c7SBjoern A. Zeeb #ifdef INET
1310b287c6c7SBjoern A. Zeeb 		{
1311db33b3e6SAndre Oppermann 			if (th->th_dport == th->th_sport &&
1312a160e630SAndre Oppermann 			    ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1313a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1314a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13158d573cc1SAndre Oppermann 					"Connection attempt from/to self "
1316773673c1SAndre Oppermann 					"ignored\n", s, __func__);
1317302ce8d6SAndre Oppermann 				goto dropunlock;
1318a160e630SAndre Oppermann 			}
1319be2ac88cSJonathan Lemon 			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1320be2ac88cSJonathan Lemon 			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
13212ca2159fSCrist J. Clark 			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1322a160e630SAndre Oppermann 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1323a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1324a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13258d573cc1SAndre Oppermann 					"Connection attempt from/to broad- "
1326773673c1SAndre Oppermann 					"or multicast address ignored\n",
1327a160e630SAndre Oppermann 					s, __func__);
1328302ce8d6SAndre Oppermann 				goto dropunlock;
1329c068736aSJeffrey Hsu 			}
1330a160e630SAndre Oppermann 		}
1331b287c6c7SBjoern A. Zeeb #endif
1332be2ac88cSJonathan Lemon 		/*
1333db33b3e6SAndre Oppermann 		 * SYN appears to be valid.  Create compressed TCP state
1334db33b3e6SAndre Oppermann 		 * for syncache.
1335be2ac88cSJonathan Lemon 		 */
13363c653157SHartmut Brandt #ifdef TCPDEBUG
13373c653157SHartmut Brandt 		if (so->so_options & SO_DEBUG)
13383c653157SHartmut Brandt 			tcp_trace(TA_INPUT, ostate, tp,
13393c653157SHartmut Brandt 			    (void *)tcp_saveipgen, &tcp_savetcp, 0);
13403c653157SHartmut Brandt #endif
13412b9c9984SGeorge V. Neville-Neil 		TCP_PROBE3(debug__input, tp, th, m);
1342f72167f4SAndre Oppermann 		tcp_dooptions(&to, optp, optlen, TO_SYN);
1343fa49a964SMichael Tuexen 		if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL, iptos))
134409c305ebSPatrick Kelsey 			goto tfo_socket_result;
134518a75309SPatrick Kelsey 
1346be2ac88cSJonathan Lemon 		/*
13474d6e7130SAndre Oppermann 		 * Entry added to syncache and mbuf consumed.
1348a7c7f2a7SJohn Baldwin 		 * Only the listen socket is unlocked by syncache_add().
1349be2ac88cSJonathan Lemon 		 */
1350384a5c3cSAndrey V. Elsukov 		INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
13518f5a8818SKevin Lo 		return (IPPROTO_DONE);
1352982c1675SAndre Oppermann 	} else if (tp->t_state == TCPS_LISTEN) {
1353982c1675SAndre Oppermann 		/*
1354982c1675SAndre Oppermann 		 * When a listen socket is torn down the SO_ACCEPTCONN
1355982c1675SAndre Oppermann 		 * flag is removed first while connections are drained
1356982c1675SAndre Oppermann 		 * from the accept queue in a unlock/lock cycle of the
1357982c1675SAndre Oppermann 		 * ACCEPT_LOCK, opening a race condition allowing a SYN
1358982c1675SAndre Oppermann 		 * attempt go through unhandled.
1359982c1675SAndre Oppermann 		 */
1360982c1675SAndre Oppermann 		goto dropunlock;
1361f76fcf6dSJeffrey Hsu 	}
1362fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1363fcf59617SAndrey V. Elsukov 	if (tp->t_flags & TF_SIGNATURE) {
1364fcf59617SAndrey V. Elsukov 		tcp_dooptions(&to, optp, optlen, thflags);
1365fcf59617SAndrey V. Elsukov 		if ((to.to_flags & TOF_SIGNATURE) == 0) {
1366fcf59617SAndrey V. Elsukov 			TCPSTAT_INC(tcps_sig_err_nosigopt);
13672903309aSAttilio Rao 			goto dropunlock;
13682903309aSAttilio Rao 		}
1369fcf59617SAndrey V. Elsukov 		if (!TCPMD5_ENABLED() ||
1370fcf59617SAndrey V. Elsukov 		    TCPMD5_INPUT(m, th, to.to_signature) != 0)
1371fcf59617SAndrey V. Elsukov 			goto dropunlock;
13722903309aSAttilio Rao 	}
13732903309aSAttilio Rao #endif
13742b9c9984SGeorge V. Neville-Neil 	TCP_PROBE5(receive, NULL, tp, m, tp, th);
137557f60867SMark Johnston 
1376302ce8d6SAndre Oppermann 	/*
13778d573cc1SAndre Oppermann 	 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
13788d573cc1SAndre Oppermann 	 * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
13798d573cc1SAndre Oppermann 	 * the inpcb, and unlocks pcbinfo.
1380302ce8d6SAndre Oppermann 	 */
13816573d758SMatt Macy 	tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos);
13828f5a8818SKevin Lo 	return (IPPROTO_DONE);
1383be2ac88cSJonathan Lemon 
1384302ce8d6SAndre Oppermann dropwithreset:
13852b9c9984SGeorge V. Neville-Neil 	TCP_PROBE5(receive, NULL, tp, m, tp, th);
138657f60867SMark Johnston 
1387014ea782SRobert Watson 	if (inp != NULL) {
1388302ce8d6SAndre Oppermann 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
1389014ea782SRobert Watson 		INP_WUNLOCK(inp);
1390dd8ac7f9SRobert Watson 	} else
1391014ea782SRobert Watson 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1392302ce8d6SAndre Oppermann 	m = NULL;	/* mbuf chain got consumed. */
1393014ea782SRobert Watson 	goto drop;
1394014ea782SRobert Watson 
1395302ce8d6SAndre Oppermann dropunlock:
139657f60867SMark Johnston 	if (m != NULL)
13972b9c9984SGeorge V. Neville-Neil 		TCP_PROBE5(receive, NULL, tp, m, tp, th);
139857f60867SMark Johnston 
13999fa198beSAndre Oppermann 	if (inp != NULL)
14008501a69cSRobert Watson 		INP_WUNLOCK(inp);
1401014ea782SRobert Watson 
1402302ce8d6SAndre Oppermann drop:
1403384a5c3cSAndrey V. Elsukov 	INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1404a160e630SAndre Oppermann 	if (s != NULL)
1405a160e630SAndre Oppermann 		free(s, M_TCPLOG);
1406302ce8d6SAndre Oppermann 	if (m != NULL)
1407302ce8d6SAndre Oppermann 		m_freem(m);
14088f5a8818SKevin Lo 	return (IPPROTO_DONE);
1409302ce8d6SAndre Oppermann }
1410302ce8d6SAndre Oppermann 
1411e44c1887SSteven Hartland /*
1412e44c1887SSteven Hartland  * Automatic sizing of receive socket buffer.  Often the send
1413e44c1887SSteven Hartland  * buffer size is not optimally adjusted to the actual network
1414e44c1887SSteven Hartland  * conditions at hand (delay bandwidth product).  Setting the
1415e44c1887SSteven Hartland  * buffer size too small limits throughput on links with high
1416e44c1887SSteven Hartland  * bandwidth and high delay (eg. trans-continental/oceanic links).
1417e44c1887SSteven Hartland  *
1418e44c1887SSteven Hartland  * On the receive side the socket buffer memory is only rarely
1419e44c1887SSteven Hartland  * used to any significant extent.  This allows us to be much
1420e44c1887SSteven Hartland  * more aggressive in scaling the receive socket buffer.  For
1421e44c1887SSteven Hartland  * the case that the buffer space is actually used to a large
1422e44c1887SSteven Hartland  * extent and we run out of kernel memory we can simply drop
1423e44c1887SSteven Hartland  * the new segments; TCP on the sender will just retransmit it
1424e44c1887SSteven Hartland  * later.  Setting the buffer size too big may only consume too
1425e44c1887SSteven Hartland  * much kernel memory if the application doesn't read() from
1426e44c1887SSteven Hartland  * the socket or packet loss or reordering makes use of the
1427e44c1887SSteven Hartland  * reassembly queue.
1428e44c1887SSteven Hartland  *
1429e44c1887SSteven Hartland  * The criteria to step up the receive buffer one notch are:
1430e44c1887SSteven Hartland  *  1. Application has not set receive buffer size with
1431e44c1887SSteven Hartland  *     SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1432560c0586SMichael Tuexen  *  2. the number of bytes received during 1/2 of an sRTT
1433560c0586SMichael Tuexen  *     is at least 3/8 of the current socket buffer size.
1434560c0586SMichael Tuexen  *  3. receive buffer size has not hit maximal automatic size;
1435e44c1887SSteven Hartland  *
1436560c0586SMichael Tuexen  * If all of the criteria are met we increaset the socket buffer
1437560c0586SMichael Tuexen  * by a 1/2 (bounded by the max). This allows us to keep ahead
1438560c0586SMichael Tuexen  * of slow-start but also makes it so our peer never gets limited
1439560c0586SMichael Tuexen  * by our rwnd which we then open up causing a burst.
1440560c0586SMichael Tuexen  *
1441560c0586SMichael Tuexen  * This algorithm does two steps per RTT at most and only if
1442e44c1887SSteven Hartland  * we receive a bulk stream w/o packet losses or reorderings.
1443e44c1887SSteven Hartland  * Shrinking the buffer during idle times is not necessary as
1444e44c1887SSteven Hartland  * it doesn't consume any memory when idle.
1445e44c1887SSteven Hartland  *
1446e44c1887SSteven Hartland  * TODO: Only step up if the application is actually serving
1447e44c1887SSteven Hartland  * the buffer to better manage the socket buffer resources.
1448e44c1887SSteven Hartland  */
1449e44c1887SSteven Hartland int
1450e44c1887SSteven Hartland tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1451e44c1887SSteven Hartland     struct tcpcb *tp, int tlen)
1452e44c1887SSteven Hartland {
1453e44c1887SSteven Hartland 	int newsize = 0;
1454e44c1887SSteven Hartland 
1455e44c1887SSteven Hartland 	if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1456e44c1887SSteven Hartland 	    tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1457e44c1887SSteven Hartland 	    TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1458560c0586SMichael Tuexen 	    ((tp->t_srtt >> TCP_RTT_SHIFT)/2)) {
1459560c0586SMichael Tuexen 		if (tp->rfbuf_cnt > ((so->so_rcv.sb_hiwat / 2)/ 4 * 3) &&
1460e44c1887SSteven Hartland 		    so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1461560c0586SMichael Tuexen 			newsize = min((so->so_rcv.sb_hiwat + (so->so_rcv.sb_hiwat/2)), V_tcp_autorcvbuf_max);
1462e44c1887SSteven Hartland 		}
1463e44c1887SSteven Hartland 		TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1464e44c1887SSteven Hartland 
1465e44c1887SSteven Hartland 		/* Start over with next RTT. */
1466e44c1887SSteven Hartland 		tp->rfbuf_ts = 0;
1467e44c1887SSteven Hartland 		tp->rfbuf_cnt = 0;
1468e44c1887SSteven Hartland 	} else {
1469e44c1887SSteven Hartland 		tp->rfbuf_cnt += tlen;	/* add up */
1470e44c1887SSteven Hartland 	}
1471e44c1887SSteven Hartland 	return (newsize);
1472e44c1887SSteven Hartland }
1473e44c1887SSteven Hartland 
147455bceb1eSRandall Stewart void
1475302ce8d6SAndre Oppermann tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
14766573d758SMatt Macy     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos)
1477302ce8d6SAndre Oppermann {
1478021eaf79SHiren Panchasara 	int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1479b2ade6b1SRichard Scheffenegger 	int rstreason, todrop, win, incforsyn = 0;
14803ac12506SJonathan T. Looney 	uint32_t tiwin;
14814b7b743cSLawrence Stewart 	uint16_t nsegs;
148207dacf03SAndre Oppermann 	char *s;
148307dacf03SAndre Oppermann 	struct in_conninfo *inc;
1484c11a15bfSGleb Smirnoff 	struct mbuf *mfree;
1485302ce8d6SAndre Oppermann 	struct tcpopt to;
1486281a0fd4SPatrick Kelsey 	int tfo_syn;
1487302ce8d6SAndre Oppermann 
148814739780SMaxim Konovalov #ifdef TCPDEBUG
148914739780SMaxim Konovalov 	/*
149014739780SMaxim Konovalov 	 * The size of tcp_saveipgen must be the size of the max ip header,
149114739780SMaxim Konovalov 	 * now IPv6.
149214739780SMaxim Konovalov 	 */
149314739780SMaxim Konovalov 	u_char tcp_saveipgen[IP6_HDR_LEN];
149414739780SMaxim Konovalov 	struct tcphdr tcp_savetcp;
149514739780SMaxim Konovalov 	short ostate = 0;
149614739780SMaxim Konovalov #endif
1497302ce8d6SAndre Oppermann 	thflags = th->th_flags;
149807dacf03SAndre Oppermann 	inc = &tp->t_inpcb->inp_inc;
1499d64a46eaSLawrence Stewart 	tp->sackhint.last_sack_ack = 0;
1500021eaf79SHiren Panchasara 	sack_changed = 0;
15014b7b743cSLawrence Stewart 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
1502d40c0d47SGleb Smirnoff 
1503d40c0d47SGleb Smirnoff 	NET_EPOCH_ASSERT();
15048501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
1505679d9708SAndre Oppermann 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1506679d9708SAndre Oppermann 	    __func__));
1507679d9708SAndre Oppermann 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1508679d9708SAndre Oppermann 	    __func__));
1509df8bae1dSRodney W. Grimes 
151086a996e6SHiren Panchasara #ifdef TCPPCAP
151186a996e6SHiren Panchasara 	/* Save segment, if requested. */
151286a996e6SHiren Panchasara 	tcp_pcap_add(th, m, &(tp->t_inpkts));
151386a996e6SHiren Panchasara #endif
15142529f56eSJonathan T. Looney 	TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
15152529f56eSJonathan T. Looney 	    tlen, NULL, true);
151686a996e6SHiren Panchasara 
1517013f4df6SMichael Tuexen 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1518013f4df6SMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1519013f4df6SMichael Tuexen 			log(LOG_DEBUG, "%s; %s: "
1520013f4df6SMichael Tuexen 			    "SYN|FIN segment ignored (based on "
1521013f4df6SMichael Tuexen 			    "sysctl setting)\n", s, __func__);
1522013f4df6SMichael Tuexen 			free(s, M_TCPLOG);
1523013f4df6SMichael Tuexen 		}
1524013f4df6SMichael Tuexen 		goto drop;
1525013f4df6SMichael Tuexen 	}
1526013f4df6SMichael Tuexen 
1527df8bae1dSRodney W. Grimes 	/*
1528ebfd7534SMichael Tuexen 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1529ebfd7534SMichael Tuexen 	 * check SEQ.ACK first.
1530ebfd7534SMichael Tuexen 	 */
1531ebfd7534SMichael Tuexen 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1532ebfd7534SMichael Tuexen 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1533ebfd7534SMichael Tuexen 		rstreason = BANDLIM_UNLIMITED;
1534ebfd7534SMichael Tuexen 		goto dropwithreset;
1535ebfd7534SMichael Tuexen 	}
1536ebfd7534SMichael Tuexen 
1537ebfd7534SMichael Tuexen 	/*
1538df8bae1dSRodney W. Grimes 	 * Segment received on connection.
1539df8bae1dSRodney W. Grimes 	 * Reset idle time and keep-alive timer.
1540e8949f74SAndre Oppermann 	 * XXX: This should be done after segment
1541e8949f74SAndre Oppermann 	 * validation to ignore broken/spoofed segs.
1542df8bae1dSRodney W. Grimes 	 */
15439b8b58e0SJonathan Lemon 	tp->t_rcvtime = ticks;
1544df8bae1dSRodney W. Grimes 
1545df8bae1dSRodney W. Grimes 	/*
1546c52102ddSHiren Panchasara 	 * Scale up the window into a 32-bit value.
1547e8949f74SAndre Oppermann 	 * For the SYN_SENT state the scale is zero.
1548464fcfbcSAndre Oppermann 	 */
1549464fcfbcSAndre Oppermann 	tiwin = th->th_win << tp->snd_scale;
1550adc56f5aSEdward Tomasz Napierala #ifdef STATS
1551adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
1552adc56f5aSEdward Tomasz Napierala #endif
1553464fcfbcSAndre Oppermann 
1554464fcfbcSAndre Oppermann 	/*
1555f2512ba1SRui Paulo 	 * TCP ECN processing.
1556f2512ba1SRui Paulo 	 */
15573cf38784SMichael Tuexen 	if (tp->t_flags2 & TF2_ECN_PERMIT) {
1558ee97681eSMichael Tuexen 		if (thflags & TH_CWR) {
15593cf38784SMichael Tuexen 			tp->t_flags2 &= ~TF2_ECN_SND_ECE;
1560ee97681eSMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
1561ee97681eSMichael Tuexen 		}
1562f2512ba1SRui Paulo 		switch (iptos & IPTOS_ECN_MASK) {
1563f2512ba1SRui Paulo 		case IPTOS_ECN_CE:
15643cf38784SMichael Tuexen 			tp->t_flags2 |= TF2_ECN_SND_ECE;
156578b50714SRobert Watson 			TCPSTAT_INC(tcps_ecn_ce);
1566f2512ba1SRui Paulo 			break;
1567f2512ba1SRui Paulo 		case IPTOS_ECN_ECT0:
156878b50714SRobert Watson 			TCPSTAT_INC(tcps_ecn_ect0);
1569f2512ba1SRui Paulo 			break;
1570f2512ba1SRui Paulo 		case IPTOS_ECN_ECT1:
157178b50714SRobert Watson 			TCPSTAT_INC(tcps_ecn_ect1);
1572f2512ba1SRui Paulo 			break;
1573f2512ba1SRui Paulo 		}
157464807b30SHiren Panchasara 
157564807b30SHiren Panchasara 		/* Process a packet differently from RFC3168. */
157664807b30SHiren Panchasara 		cc_ecnpkt_handler(tp, th, iptos);
157764807b30SHiren Panchasara 
1578dbc42409SLawrence Stewart 		/* Congestion experienced. */
1579dbc42409SLawrence Stewart 		if (thflags & TH_ECE) {
1580dbc42409SLawrence Stewart 			cc_cong_signal(tp, th, CC_ECN);
1581f2512ba1SRui Paulo 		}
1582f2512ba1SRui Paulo 	}
1583f2512ba1SRui Paulo 
1584f2512ba1SRui Paulo 	/*
1585f72167f4SAndre Oppermann 	 * Parse options on any incoming segment.
1586f72167f4SAndre Oppermann 	 */
1587302ce8d6SAndre Oppermann 	tcp_dooptions(&to, (u_char *)(th + 1),
1588302ce8d6SAndre Oppermann 	    (th->th_off << 2) - sizeof(struct tcphdr),
1589302ce8d6SAndre Oppermann 	    (thflags & TH_SYN) ? TO_SYN : 0);
1590f72167f4SAndre Oppermann 
1591fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1592fcf59617SAndrey V. Elsukov 	if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1593fcf59617SAndrey V. Elsukov 	    (to.to_flags & TOF_SIGNATURE) == 0) {
1594fcf59617SAndrey V. Elsukov 		TCPSTAT_INC(tcps_sig_err_sigopt);
1595fcf59617SAndrey V. Elsukov 		/* XXX: should drop? */
1596fcf59617SAndrey V. Elsukov 	}
1597fcf59617SAndrey V. Elsukov #endif
1598f72167f4SAndre Oppermann 	/*
1599f72167f4SAndre Oppermann 	 * If echoed timestamp is later than the current time,
1600bf6d304aSAndre Oppermann 	 * fall back to non RFC1323 RTT calculation.  Normalize
1601bf6d304aSAndre Oppermann 	 * timestamp if syncookies were used when this connection
1602bf6d304aSAndre Oppermann 	 * was established.
1603f72167f4SAndre Oppermann 	 */
1604bf6d304aSAndre Oppermann 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1605e16fa5caSJohn-Mark Gurney 		to.to_tsecr -= tp->ts_offset;
1606d8951c8aSBjoern A. Zeeb 		if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1607f72167f4SAndre Oppermann 			to.to_tsecr = 0;
160810d20c84SMatt Macy 		else if (tp->t_flags & TF_PREVVALID &&
160910d20c84SMatt Macy 			 tp->t_badrxtwin != 0 && SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
161010d20c84SMatt Macy 			cc_cong_signal(tp, th, CC_RTO_ERR);
1611bf6d304aSAndre Oppermann 	}
161207dacf03SAndre Oppermann 	/*
161397d8d152SAndre Oppermann 	 * Process options only when we get SYN/ACK back. The SYN case
161497d8d152SAndre Oppermann 	 * for incoming connections is handled in tcp_syncache.
16155396d0f8SAndre Oppermann 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
16165396d0f8SAndre Oppermann 	 * or <SYN,ACK>) segment itself is never scaled.
161797d8d152SAndre Oppermann 	 * XXX this is traditional behavior, may need to be cleaned up.
1618df8bae1dSRodney W. Grimes 	 */
16190a389eabSSimon L. B. Nielsen 	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
16206e16d877SRichard Scheffenegger 		/* Handle parallel SYN for ECN */
16216e16d877SRichard Scheffenegger 		if (!(thflags & TH_ACK) &&
16226e16d877SRichard Scheffenegger 		    ((thflags & (TH_CWR | TH_ECE)) == (TH_CWR | TH_ECE)) &&
16236e16d877SRichard Scheffenegger 		    ((V_tcp_do_ecn == 1) || (V_tcp_do_ecn == 2))) {
16246e16d877SRichard Scheffenegger 			tp->t_flags2 |= TF2_ECN_PERMIT;
16256e16d877SRichard Scheffenegger 			tp->t_flags2 |= TF2_ECN_SND_ECE;
16266e16d877SRichard Scheffenegger 			TCPSTAT_INC(tcps_ecn_shs);
16276e16d877SRichard Scheffenegger 		}
1628464fcfbcSAndre Oppermann 		if ((to.to_flags & TOF_SCALE) &&
1629464fcfbcSAndre Oppermann 		    (tp->t_flags & TF_REQ_SCALE)) {
1630be2ac88cSJonathan Lemon 			tp->t_flags |= TF_RCVD_SCALE;
163102a1a643SAndre Oppermann 			tp->snd_scale = to.to_wscale;
16328e051165SRichard Scheffenegger 		} else
16338e051165SRichard Scheffenegger 			tp->t_flags &= ~TF_REQ_SCALE;
16345396d0f8SAndre Oppermann 		/*
16355396d0f8SAndre Oppermann 		 * Initial send window.  It will be updated with
16365396d0f8SAndre Oppermann 		 * the next incoming segment to the scaled value.
16375396d0f8SAndre Oppermann 		 */
16385396d0f8SAndre Oppermann 		tp->snd_wnd = th->th_win;
16398e051165SRichard Scheffenegger 		if ((to.to_flags & TOF_TS) &&
16408e051165SRichard Scheffenegger 		    (tp->t_flags & TF_REQ_TSTMP)) {
1641be2ac88cSJonathan Lemon 			tp->t_flags |= TF_RCVD_TSTMP;
1642be2ac88cSJonathan Lemon 			tp->ts_recent = to.to_tsval;
1643d8951c8aSBjoern A. Zeeb 			tp->ts_recent_age = tcp_ts_getticks();
16448e051165SRichard Scheffenegger 		} else
16458e051165SRichard Scheffenegger 			tp->t_flags &= ~TF_REQ_TSTMP;
1646be2ac88cSJonathan Lemon 		if (to.to_flags & TOF_MSS)
1647be2ac88cSJonathan Lemon 			tcp_mss(tp, to.to_mss);
16483529149eSAndre Oppermann 		if ((tp->t_flags & TF_SACK_PERMIT) &&
16493529149eSAndre Oppermann 		    (to.to_flags & TOF_SACKPERM) == 0)
16503529149eSAndre Oppermann 			tp->t_flags &= ~TF_SACK_PERMIT;
1651c560df6fSPatrick Kelsey 		if (IS_FASTOPEN(tp->t_flags)) {
1652a026a53aSMichael Tuexen 			if (to.to_flags & TOF_FASTOPEN) {
1653a026a53aSMichael Tuexen 				uint16_t mss;
1654a026a53aSMichael Tuexen 
1655a026a53aSMichael Tuexen 				if (to.to_flags & TOF_MSS)
1656a026a53aSMichael Tuexen 					mss = to.to_mss;
1657c560df6fSPatrick Kelsey 				else
1658a026a53aSMichael Tuexen 					if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
1659a026a53aSMichael Tuexen 						mss = TCP6_MSS;
1660a026a53aSMichael Tuexen 					else
1661a026a53aSMichael Tuexen 						mss = TCP_MSS;
1662a026a53aSMichael Tuexen 				tcp_fastopen_update_cache(tp, mss,
1663a026a53aSMichael Tuexen 				    to.to_tfo_len, to.to_tfo_cookie);
1664a026a53aSMichael Tuexen 			} else
1665c560df6fSPatrick Kelsey 				tcp_fastopen_disable_path(tp);
1666c560df6fSPatrick Kelsey 		}
16676d90faf3SPaul Saab 	}
16686d90faf3SPaul Saab 
1669df8bae1dSRodney W. Grimes 	/*
16704da9052aSMichael Tuexen 	 * If timestamps were negotiated during SYN/ACK they should
16714da9052aSMichael Tuexen 	 * appear on every segment during this session and vice versa.
16724da9052aSMichael Tuexen 	 */
16734da9052aSMichael Tuexen 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
16744da9052aSMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
16754da9052aSMichael Tuexen 			log(LOG_DEBUG, "%s; %s: Timestamp missing, "
16764da9052aSMichael Tuexen 			    "no action\n", s, __func__);
16774da9052aSMichael Tuexen 			free(s, M_TCPLOG);
16784da9052aSMichael Tuexen 		}
16794da9052aSMichael Tuexen 	}
16804da9052aSMichael Tuexen 	if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
16814da9052aSMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
16824da9052aSMichael Tuexen 			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
16834da9052aSMichael Tuexen 			    "no action\n", s, __func__);
16844da9052aSMichael Tuexen 			free(s, M_TCPLOG);
16854da9052aSMichael Tuexen 		}
16864da9052aSMichael Tuexen 	}
16874da9052aSMichael Tuexen 
16884da9052aSMichael Tuexen 	/*
1689df8bae1dSRodney W. Grimes 	 * Header prediction: check for the two common cases
1690df8bae1dSRodney W. Grimes 	 * of a uni-directional data xfer.  If the packet has
1691df8bae1dSRodney W. Grimes 	 * no control flags, is in-sequence, the window didn't
1692df8bae1dSRodney W. Grimes 	 * change and we're not retransmitting, it's a
1693df8bae1dSRodney W. Grimes 	 * candidate.  If the length is zero and the ack moved
1694df8bae1dSRodney W. Grimes 	 * forward, we're the sender side of the xfer.  Just
1695df8bae1dSRodney W. Grimes 	 * free the data acked & wake any higher level process
1696df8bae1dSRodney W. Grimes 	 * that was blocked waiting for space.  If the length
1697df8bae1dSRodney W. Grimes 	 * is non-zero and the ack didn't move, we're the
1698df8bae1dSRodney W. Grimes 	 * receiver side.  If we're getting packets in-order
1699df8bae1dSRodney W. Grimes 	 * (the reassembly queue is empty), add the data to
1700df8bae1dSRodney W. Grimes 	 * the socket buffer and note that we need a delayed ack.
1701a0292f23SGarrett Wollman 	 * Make sure that the hidden state-flags are also off.
1702c5ad39b9SAndre Oppermann 	 * Since we check for TCPS_ESTABLISHED first, it can only
1703a0292f23SGarrett Wollman 	 * be TH_NEEDSYN.
1704df8bae1dSRodney W. Grimes 	 */
1705df8bae1dSRodney W. Grimes 	if (tp->t_state == TCPS_ESTABLISHED &&
1706c5ad39b9SAndre Oppermann 	    th->th_seq == tp->rcv_nxt &&
1707fb59c426SYoshinobu Inoue 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1708c5ad39b9SAndre Oppermann 	    tp->snd_nxt == tp->snd_max &&
1709c5ad39b9SAndre Oppermann 	    tiwin && tiwin == tp->snd_wnd &&
1710a0292f23SGarrett Wollman 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1711c28440dbSRandall Stewart 	    SEGQ_EMPTY(tp) &&
17124741bfcbSPatrick Kelsey 	    ((to.to_flags & TOF_TS) == 0 ||
1713c5ad39b9SAndre Oppermann 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1714df8bae1dSRodney W. Grimes 
1715df8bae1dSRodney W. Grimes 		/*
1716df8bae1dSRodney W. Grimes 		 * If last ACK falls within this segment's sequence numbers,
1717df8bae1dSRodney W. Grimes 		 * record the timestamp.
1718a0292f23SGarrett Wollman 		 * NOTE that the test is modified according to the latest
1719a0292f23SGarrett Wollman 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1720df8bae1dSRodney W. Grimes 		 */
1721be2ac88cSJonathan Lemon 		if ((to.to_flags & TOF_TS) != 0 &&
1722fb59c426SYoshinobu Inoue 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1723d8951c8aSBjoern A. Zeeb 			tp->ts_recent_age = tcp_ts_getticks();
1724a0292f23SGarrett Wollman 			tp->ts_recent = to.to_tsval;
1725df8bae1dSRodney W. Grimes 		}
1726df8bae1dSRodney W. Grimes 
1727fb59c426SYoshinobu Inoue 		if (tlen == 0) {
1728fb59c426SYoshinobu Inoue 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1729fb59c426SYoshinobu Inoue 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1730dbc42409SLawrence Stewart 			    !IN_RECOVERY(tp->t_flags) &&
1731fc30a251SAndre Oppermann 			    (to.to_flags & TOF_SACK) == 0 &&
1732dbc42409SLawrence Stewart 			    TAILQ_EMPTY(&tp->snd_holes)) {
1733df8bae1dSRodney W. Grimes 				/*
1734e8949f74SAndre Oppermann 				 * This is a pure ack for outstanding data.
1735df8bae1dSRodney W. Grimes 				 */
173678b50714SRobert Watson 				TCPSTAT_INC(tcps_predack);
1737252ca428SRobert Watson 
17389b8b58e0SJonathan Lemon 				/*
173910d20c84SMatt Macy 				 * "bad retransmit" recovery without timestamps.
17409b8b58e0SJonathan Lemon 				 */
174110d20c84SMatt Macy 				if ((to.to_flags & TOF_TS) == 0 &&
174210d20c84SMatt Macy 				    tp->t_rxtshift == 1 &&
1743672dc4aeSJohn Baldwin 				    tp->t_flags & TF_PREVVALID &&
17446dfb8b31SJohn Baldwin 				    (int)(ticks - tp->t_badrxtwin) < 0) {
1745dbc42409SLawrence Stewart 					cc_cong_signal(tp, th, CC_RTO_ERR);
17469b8b58e0SJonathan Lemon 				}
1747fa55172bSMatthew Dillon 
1748fa55172bSMatthew Dillon 				/*
1749fa55172bSMatthew Dillon 				 * Recalculate the transmit timer / rtt.
1750fa55172bSMatthew Dillon 				 *
1751fa55172bSMatthew Dillon 				 * Some boxes send broken timestamp replies
1752fa55172bSMatthew Dillon 				 * during the SYN+ACK phase, ignore
1753fa55172bSMatthew Dillon 				 * timestamps of 0 or we could calculate a
1754fa55172bSMatthew Dillon 				 * huge RTT and blow up the retransmit timer.
1755fa55172bSMatthew Dillon 				 */
1756fa55172bSMatthew Dillon 				if ((to.to_flags & TOF_TS) != 0 &&
1757fa55172bSMatthew Dillon 				    to.to_tsecr) {
17583ac12506SJonathan T. Looney 					uint32_t t;
1759d8951c8aSBjoern A. Zeeb 
1760d8951c8aSBjoern A. Zeeb 					t = tcp_ts_getticks() - to.to_tsecr;
1761d8951c8aSBjoern A. Zeeb 					if (!tp->t_rttlow || tp->t_rttlow > t)
1762d8951c8aSBjoern A. Zeeb 						tp->t_rttlow = t;
1763a0292f23SGarrett Wollman 					tcp_xmit_timer(tp,
1764d8951c8aSBjoern A. Zeeb 					    TCP_TS_TO_TICKS(t) + 1);
1765fa55172bSMatthew Dillon 				} else if (tp->t_rtttime &&
1766fa55172bSMatthew Dillon 				    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1767eaf80179SAndre Oppermann 					if (!tp->t_rttlow ||
1768eaf80179SAndre Oppermann 					    tp->t_rttlow > ticks - tp->t_rtttime)
1769eaf80179SAndre Oppermann 						tp->t_rttlow = ticks - tp->t_rtttime;
1770c068736aSJeffrey Hsu 					tcp_xmit_timer(tp,
1771c068736aSJeffrey Hsu 							ticks - tp->t_rtttime);
1772fa55172bSMatthew Dillon 				}
1773dbc42409SLawrence Stewart 				acked = BYTES_THIS_ACK(tp, th);
177439bc9de5SLawrence Stewart 
1775bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
177639bc9de5SLawrence Stewart 				/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
177739bc9de5SLawrence Stewart 				hhook_run_tcp_est_in(tp, th, &to);
1778bd79708dSJonathan T. Looney #endif
177939bc9de5SLawrence Stewart 
17804b7b743cSLawrence Stewart 				TCPSTAT_ADD(tcps_rcvackpack, nsegs);
178178b50714SRobert Watson 				TCPSTAT_ADD(tcps_rcvackbyte, acked);
1782df8bae1dSRodney W. Grimes 				sbdrop(&so->so_snd, acked);
17839d11646dSJeffrey Hsu 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
17849d11646dSJeffrey Hsu 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
17859d11646dSJeffrey Hsu 					tp->snd_recover = th->th_ack - 1;
1786dbc42409SLawrence Stewart 
1787dbc42409SLawrence Stewart 				/*
1788dbc42409SLawrence Stewart 				 * Let the congestion control algorithm update
1789dbc42409SLawrence Stewart 				 * congestion control related information. This
1790dbc42409SLawrence Stewart 				 * typically means increasing the congestion
1791dbc42409SLawrence Stewart 				 * window.
1792dbc42409SLawrence Stewart 				 */
17934b7b743cSLawrence Stewart 				cc_ack_received(tp, th, nsegs, CC_ACK);
1794dbc42409SLawrence Stewart 
17959d11646dSJeffrey Hsu 				tp->snd_una = th->th_ack;
17961645d090SJeff Roberson 				/*
1797e8949f74SAndre Oppermann 				 * Pull snd_wl2 up to prevent seq wrap relative
17981645d090SJeff Roberson 				 * to th_ack.
17991645d090SJeff Roberson 				 */
1800cb942153SJeffrey Hsu 				tp->snd_wl2 = th->th_ack;
1801b5addd85SJeffrey Hsu 				tp->t_dupacks = 0;
1802df8bae1dSRodney W. Grimes 				m_freem(m);
1803df8bae1dSRodney W. Grimes 
1804df8bae1dSRodney W. Grimes 				/*
1805df8bae1dSRodney W. Grimes 				 * If all outstanding data are acked, stop
1806df8bae1dSRodney W. Grimes 				 * retransmit timer, otherwise restart timer
1807df8bae1dSRodney W. Grimes 				 * using current (possibly backed-off) value.
1808df8bae1dSRodney W. Grimes 				 * If process is waiting for space,
1809df8bae1dSRodney W. Grimes 				 * wakeup/selwakeup/signal.  If data
1810df8bae1dSRodney W. Grimes 				 * are ready to send, let tcp_output
1811df8bae1dSRodney W. Grimes 				 * decide between more output or persist.
1812e8949f74SAndre Oppermann 				 */
18133c653157SHartmut Brandt #ifdef TCPDEBUG
18143c653157SHartmut Brandt 				if (so->so_options & SO_DEBUG)
18153c653157SHartmut Brandt 					tcp_trace(TA_INPUT, ostate, tp,
18163c653157SHartmut Brandt 					    (void *)tcp_saveipgen,
18173c653157SHartmut Brandt 					    &tcp_savetcp, 0);
18183c653157SHartmut Brandt #endif
18192b9c9984SGeorge V. Neville-Neil 				TCP_PROBE3(debug__input, tp, th, m);
1820df8bae1dSRodney W. Grimes 				if (tp->snd_una == tp->snd_max)
1821b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT, 0);
1822b8152ba7SAndre Oppermann 				else if (!tcp_timer_active(tp, TT_PERSIST))
1823b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT,
1824b8152ba7SAndre Oppermann 						      tp->t_rxtcur);
1825df8bae1dSRodney W. Grimes 				sowwakeup(so);
1826cfa6009eSGleb Smirnoff 				if (sbavail(&so->so_snd))
182755bceb1eSRandall Stewart 					(void) tp->t_fb->tfb_tcp_output(tp);
1828a14c749fSJonathan Lemon 				goto check_delack;
1829df8bae1dSRodney W. Grimes 			}
1830fb59c426SYoshinobu Inoue 		} else if (th->th_ack == tp->snd_una &&
1831fb59c426SYoshinobu Inoue 		    tlen <= sbspace(&so->so_rcv)) {
18326741ecf5SAndre Oppermann 			int newsize = 0;	/* automatic sockbuf scaling */
18336741ecf5SAndre Oppermann 
1834df8bae1dSRodney W. Grimes 			/*
1835252ca428SRobert Watson 			 * This is a pure, in-sequence data packet with
1836252ca428SRobert Watson 			 * nothing on the reassembly queue and we have enough
1837252ca428SRobert Watson 			 * buffer space to take it.
1838df8bae1dSRodney W. Grimes 			 */
18396d90faf3SPaul Saab 			/* Clean receiver SACK report if present */
18403529149eSAndre Oppermann 			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
18416d90faf3SPaul Saab 				tcp_clean_sackreport(tp);
184278b50714SRobert Watson 			TCPSTAT_INC(tcps_preddat);
1843fb59c426SYoshinobu Inoue 			tp->rcv_nxt += tlen;
18441645d090SJeff Roberson 			/*
18451645d090SJeff Roberson 			 * Pull snd_wl1 up to prevent seq wrap relative to
18461645d090SJeff Roberson 			 * th_seq.
18471645d090SJeff Roberson 			 */
184860ee3bb2SAndre Oppermann 			tp->snd_wl1 = th->th_seq;
18491645d090SJeff Roberson 			/*
18501645d090SJeff Roberson 			 * Pull rcv_up up to prevent seq wrap relative to
18511645d090SJeff Roberson 			 * rcv_nxt.
18521645d090SJeff Roberson 			 */
18531645d090SJeff Roberson 			tp->rcv_up = tp->rcv_nxt;
18544b7b743cSLawrence Stewart 			TCPSTAT_ADD(tcps_rcvpack, nsegs);
185578b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
18563c653157SHartmut Brandt #ifdef TCPDEBUG
18573c653157SHartmut Brandt 			if (so->so_options & SO_DEBUG)
18583c653157SHartmut Brandt 				tcp_trace(TA_INPUT, ostate, tp,
18593c653157SHartmut Brandt 				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
18603c653157SHartmut Brandt #endif
18612b9c9984SGeorge V. Neville-Neil 			TCP_PROBE3(debug__input, tp, th, m);
18625d06879aSGeorge V. Neville-Neil 
1863e44c1887SSteven Hartland 			newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
18646741ecf5SAndre Oppermann 
18656741ecf5SAndre Oppermann 			/* Add data to socket buffer. */
18661e4d7da7SRobert Watson 			SOCKBUF_LOCK(&so->so_rcv);
1867c0b99ffaSRobert Watson 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1868c1c36a2cSMike Silbersack 				m_freem(m);
1869c1c36a2cSMike Silbersack 			} else {
18706741ecf5SAndre Oppermann 				/*
18716741ecf5SAndre Oppermann 				 * Set new socket buffer size.
18726741ecf5SAndre Oppermann 				 * Give up when limit is reached.
18736741ecf5SAndre Oppermann 				 */
18746741ecf5SAndre Oppermann 				if (newsize)
18756741ecf5SAndre Oppermann 					if (!sbreserve_locked(&so->so_rcv,
18766c8286e4SRobert Watson 					    newsize, so, NULL))
18776741ecf5SAndre Oppermann 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1878fb59c426SYoshinobu Inoue 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1879651e4e6aSGleb Smirnoff 				sbappendstream_locked(&so->so_rcv, m, 0);
1880c1c36a2cSMike Silbersack 			}
1881e8949f74SAndre Oppermann 			/* NB: sorwakeup_locked() does an implicit unlock. */
18821e4d7da7SRobert Watson 			sorwakeup_locked(so);
1883c1e5a6e5SAndre Oppermann 			if (DELAY_ACK(tp, tlen)) {
18843bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
1885f498eeeeSDavid Greenman 			} else {
1886e612a582SDavid Greenman 				tp->t_flags |= TF_ACKNOW;
188755bceb1eSRandall Stewart 				tp->t_fb->tfb_tcp_output(tp);
1888e612a582SDavid Greenman 			}
1889a14c749fSJonathan Lemon 			goto check_delack;
1890df8bae1dSRodney W. Grimes 		}
1891df8bae1dSRodney W. Grimes 	}
1892df8bae1dSRodney W. Grimes 
1893df8bae1dSRodney W. Grimes 	/*
1894df8bae1dSRodney W. Grimes 	 * Calculate amount of space in receive window,
1895df8bae1dSRodney W. Grimes 	 * and then do TCP input processing.
1896df8bae1dSRodney W. Grimes 	 * Receive window is amount of space in rcv queue,
1897df8bae1dSRodney W. Grimes 	 * but not less than advertised window.
1898df8bae1dSRodney W. Grimes 	 */
1899df8bae1dSRodney W. Grimes 	win = sbspace(&so->so_rcv);
1900df8bae1dSRodney W. Grimes 	if (win < 0)
1901df8bae1dSRodney W. Grimes 		win = 0;
190266e39adcSJohn Polstra 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1903df8bae1dSRodney W. Grimes 
1904df8bae1dSRodney W. Grimes 	switch (tp->t_state) {
1905df8bae1dSRodney W. Grimes 
1906df8bae1dSRodney W. Grimes 	/*
1907764d8cefSBill Fenner 	 * If the state is SYN_RECEIVED:
1908764d8cefSBill Fenner 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1909764d8cefSBill Fenner 	 */
1910764d8cefSBill Fenner 	case TCPS_SYN_RECEIVED:
1911fb59c426SYoshinobu Inoue 		if ((thflags & TH_ACK) &&
1912fb59c426SYoshinobu Inoue 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1913a57815efSBosko Milekic 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1914a57815efSBosko Milekic 				rstreason = BANDLIM_RST_OPENPORT;
1915a57815efSBosko Milekic 				goto dropwithreset;
1916a57815efSBosko Milekic 		}
191768bd7ed1SJonathan T. Looney 		if (IS_FASTOPEN(tp->t_flags)) {
1918281a0fd4SPatrick Kelsey 			/*
1919281a0fd4SPatrick Kelsey 			 * When a TFO connection is in SYN_RECEIVED, the
1920281a0fd4SPatrick Kelsey 			 * only valid packets are the initial SYN, a
1921281a0fd4SPatrick Kelsey 			 * retransmit/copy of the initial SYN (possibly with
1922281a0fd4SPatrick Kelsey 			 * a subset of the original data), a valid ACK, a
1923281a0fd4SPatrick Kelsey 			 * FIN, or a RST.
1924281a0fd4SPatrick Kelsey 			 */
1925281a0fd4SPatrick Kelsey 			if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1926281a0fd4SPatrick Kelsey 				rstreason = BANDLIM_RST_OPENPORT;
1927281a0fd4SPatrick Kelsey 				goto dropwithreset;
1928281a0fd4SPatrick Kelsey 			} else if (thflags & TH_SYN) {
1929281a0fd4SPatrick Kelsey 				/* non-initial SYN is ignored */
1930281a0fd4SPatrick Kelsey 				if ((tcp_timer_active(tp, TT_DELACK) ||
1931281a0fd4SPatrick Kelsey 				     tcp_timer_active(tp, TT_REXMT)))
1932281a0fd4SPatrick Kelsey 					goto drop;
1933281a0fd4SPatrick Kelsey 			} else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1934281a0fd4SPatrick Kelsey 				goto drop;
1935281a0fd4SPatrick Kelsey 			}
1936281a0fd4SPatrick Kelsey 		}
1937764d8cefSBill Fenner 		break;
1938764d8cefSBill Fenner 
1939764d8cefSBill Fenner 	/*
1940df8bae1dSRodney W. Grimes 	 * If the state is SYN_SENT:
194198732609SMichael Tuexen 	 *	if seg contains a RST with valid ACK (SEQ.ACK has already
194298732609SMichael Tuexen 	 *	    been verified), then drop the connection.
194398732609SMichael Tuexen 	 *	if seg contains a RST without an ACK, drop the seg.
194498732609SMichael Tuexen 	 *	if seg does not contain SYN, then drop the seg.
1945df8bae1dSRodney W. Grimes 	 * Otherwise this is an acceptable SYN segment
1946df8bae1dSRodney W. Grimes 	 *	initialize tp->rcv_nxt and tp->irs
1947df8bae1dSRodney W. Grimes 	 *	if seg contains ack then advance tp->snd_una
1948f2512ba1SRui Paulo 	 *	if seg contains an ECE and ECN support is enabled, the stream
1949f2512ba1SRui Paulo 	 *	    is ECN capable.
1950df8bae1dSRodney W. Grimes 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1951df8bae1dSRodney W. Grimes 	 *	arrange for segment to be acked (eventually)
1952df8bae1dSRodney W. Grimes 	 *	continue processing rest of data/controls, beginning with URG
1953df8bae1dSRodney W. Grimes 	 */
1954df8bae1dSRodney W. Grimes 	case TCPS_SYN_SENT:
195557f60867SMark Johnston 		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1956d9fae5abSAndriy Gapon 			TCP_PROBE5(connect__refused, NULL, tp,
19572b9c9984SGeorge V. Neville-Neil 			    m, tp, th);
1958df8bae1dSRodney W. Grimes 			tp = tcp_drop(tp, ECONNREFUSED);
195957f60867SMark Johnston 		}
19600ca3f933SAndre Oppermann 		if (thflags & TH_RST)
1961df8bae1dSRodney W. Grimes 			goto drop;
19620ca3f933SAndre Oppermann 		if (!(thflags & TH_SYN))
1963df8bae1dSRodney W. Grimes 			goto drop;
1964464fcfbcSAndre Oppermann 
1965fb59c426SYoshinobu Inoue 		tp->irs = th->th_seq;
1966df8bae1dSRodney W. Grimes 		tcp_rcvseqinit(tp);
1967fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK) {
1968c560df6fSPatrick Kelsey 			int tfo_partial_ack = 0;
1969c560df6fSPatrick Kelsey 
197078b50714SRobert Watson 			TCPSTAT_INC(tcps_connects);
1971845799c1SAndras Olah 			soisconnected(so);
1972c488362eSRobert Watson #ifdef MAC
197330d239bcSRobert Watson 			mac_socketpeer_set_from_mbuf(m, so);
1974c488362eSRobert Watson #endif
1975845799c1SAndras Olah 			/* Do window scaling on this connection? */
1976845799c1SAndras Olah 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1977845799c1SAndras Olah 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1978845799c1SAndras Olah 				tp->rcv_scale = tp->request_r_scale;
1979845799c1SAndras Olah 			}
19803ac12506SJonathan T. Looney 			tp->rcv_adv += min(tp->rcv_wnd,
1981766282cbSJohn Baldwin 			    TCP_MAXWIN << tp->rcv_scale);
1982a0292f23SGarrett Wollman 			tp->snd_una++;		/* SYN is acked */
1983a0292f23SGarrett Wollman 			/*
1984c560df6fSPatrick Kelsey 			 * If not all the data that was sent in the TFO SYN
1985c560df6fSPatrick Kelsey 			 * has been acked, resend the remainder right away.
1986c560df6fSPatrick Kelsey 			 */
1987c560df6fSPatrick Kelsey 			if (IS_FASTOPEN(tp->t_flags) &&
1988c560df6fSPatrick Kelsey 			    (tp->snd_una != tp->snd_max)) {
1989c560df6fSPatrick Kelsey 				tp->snd_nxt = th->th_ack;
1990c560df6fSPatrick Kelsey 				tfo_partial_ack = 1;
1991c560df6fSPatrick Kelsey 			}
1992c560df6fSPatrick Kelsey 			/*
1993a0292f23SGarrett Wollman 			 * If there's data, delay ACK; if there's also a FIN
1994a0292f23SGarrett Wollman 			 * ACKNOW will be turned on later.
1995a0292f23SGarrett Wollman 			 */
1996c560df6fSPatrick Kelsey 			if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
1997b8152ba7SAndre Oppermann 				tcp_timer_activate(tp, TT_DELACK,
1998b8152ba7SAndre Oppermann 				    tcp_delacktime);
1999a0292f23SGarrett Wollman 			else
2000a0292f23SGarrett Wollman 				tp->t_flags |= TF_ACKNOW;
2001f2512ba1SRui Paulo 
2002bf7fcdb1SMichael Tuexen 			if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) &&
2003a2d59694SMichael Tuexen 			    (V_tcp_do_ecn == 1)) {
20043cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_PERMIT;
200578b50714SRobert Watson 				TCPSTAT_INC(tcps_ecn_shs);
2006f2512ba1SRui Paulo 			}
2007f2512ba1SRui Paulo 
2008a0292f23SGarrett Wollman 			/*
2009a0292f23SGarrett Wollman 			 * Received <SYN,ACK> in SYN_SENT[*] state.
2010a0292f23SGarrett Wollman 			 * Transitions:
2011a0292f23SGarrett Wollman 			 *	SYN_SENT  --> ESTABLISHED
2012a0292f23SGarrett Wollman 			 *	SYN_SENT* --> FIN_WAIT_1
2013a0292f23SGarrett Wollman 			 */
20149b8b58e0SJonathan Lemon 			tp->t_starttime = ticks;
2015a0292f23SGarrett Wollman 			if (tp->t_flags & TF_NEEDFIN) {
201657f60867SMark Johnston 				tcp_state_change(tp, TCPS_FIN_WAIT_1);
2017a0292f23SGarrett Wollman 				tp->t_flags &= ~TF_NEEDFIN;
2018fb59c426SYoshinobu Inoue 				thflags &= ~TH_SYN;
20197ff19458SPaul Traina 			} else {
202057f60867SMark Johnston 				tcp_state_change(tp, TCPS_ESTABLISHED);
2021d9fae5abSAndriy Gapon 				TCP_PROBE5(connect__established, NULL, tp,
20222b9c9984SGeorge V. Neville-Neil 				    m, tp, th);
2023dbc42409SLawrence Stewart 				cc_conn_init(tp);
20249077f387SGleb Smirnoff 				tcp_timer_activate(tp, TT_KEEP,
20259077f387SGleb Smirnoff 				    TP_KEEPIDLE(tp));
20267ff19458SPaul Traina 			}
2027a0292f23SGarrett Wollman 		} else {
2028a0292f23SGarrett Wollman 			/*
2029c068736aSJeffrey Hsu 			 * Received initial SYN in SYN-SENT[*] state =>
2030153edc50SHiren Panchasara 			 * simultaneous open.
2031c068736aSJeffrey Hsu 			 * If it succeeds, connection is * half-synchronized.
2032c068736aSJeffrey Hsu 			 * Otherwise, do 3-way handshake:
2033a0292f23SGarrett Wollman 			 *        SYN-SENT -> SYN-RECEIVED
2034a0292f23SGarrett Wollman 			 *        SYN-SENT* -> SYN-RECEIVED*
2035a0292f23SGarrett Wollman 			 */
20364b8e98d6SQing Li 			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2037b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
203857f60867SMark Johnston 			tcp_state_change(tp, TCPS_SYN_RECEIVED);
2039a0292f23SGarrett Wollman 		}
2040df8bae1dSRodney W. Grimes 
20418501a69cSRobert Watson 		INP_WLOCK_ASSERT(tp->t_inpcb);
20427cfc6904SRobert Watson 
2043df8bae1dSRodney W. Grimes 		/*
2044fb59c426SYoshinobu Inoue 		 * Advance th->th_seq to correspond to first data byte.
2045df8bae1dSRodney W. Grimes 		 * If data, trim to stay within window,
2046df8bae1dSRodney W. Grimes 		 * dropping FIN if necessary.
2047df8bae1dSRodney W. Grimes 		 */
2048fb59c426SYoshinobu Inoue 		th->th_seq++;
2049fb59c426SYoshinobu Inoue 		if (tlen > tp->rcv_wnd) {
2050fb59c426SYoshinobu Inoue 			todrop = tlen - tp->rcv_wnd;
2051df8bae1dSRodney W. Grimes 			m_adj(m, -todrop);
2052fb59c426SYoshinobu Inoue 			tlen = tp->rcv_wnd;
2053fb59c426SYoshinobu Inoue 			thflags &= ~TH_FIN;
205478b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpackafterwin);
205578b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2056df8bae1dSRodney W. Grimes 		}
2057fb59c426SYoshinobu Inoue 		tp->snd_wl1 = th->th_seq - 1;
2058fb59c426SYoshinobu Inoue 		tp->rcv_up = th->th_seq;
2059a0292f23SGarrett Wollman 		/*
2060a0292f23SGarrett Wollman 		 * Client side of transaction: already sent SYN and data.
2061a0292f23SGarrett Wollman 		 * If the remote host used T/TCP to validate the SYN,
2062a0292f23SGarrett Wollman 		 * our data will be ACK'd; if so, enter normal data segment
2063a0292f23SGarrett Wollman 		 * processing in the middle of step 5, ack processing.
2064a0292f23SGarrett Wollman 		 * Otherwise, goto step 6.
2065a0292f23SGarrett Wollman 		 */
2066fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK)
2067a0292f23SGarrett Wollman 			goto process_ACK;
2068c068736aSJeffrey Hsu 
2069df8bae1dSRodney W. Grimes 		goto step6;
2070c068736aSJeffrey Hsu 
2071a0292f23SGarrett Wollman 	/*
2072a0292f23SGarrett Wollman 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2073c94c54e4SAndre Oppermann 	 *      do normal processing.
2074a0292f23SGarrett Wollman 	 *
2075c94c54e4SAndre Oppermann 	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
2076a0292f23SGarrett Wollman 	 */
2077a0292f23SGarrett Wollman 	case TCPS_LAST_ACK:
2078a0292f23SGarrett Wollman 	case TCPS_CLOSING:
2079a0292f23SGarrett Wollman 		break;  /* continue normal processing */
2080df8bae1dSRodney W. Grimes 	}
2081df8bae1dSRodney W. Grimes 
2082df8bae1dSRodney W. Grimes 	/*
2083df8bae1dSRodney W. Grimes 	 * States other than LISTEN or SYN_SENT.
208480ab7c0eSGarrett Wollman 	 * First check the RST flag and sequence number since reset segments
208580ab7c0eSGarrett Wollman 	 * are exempt from the timestamp and connection count tests.  This
208680ab7c0eSGarrett Wollman 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
208780ab7c0eSGarrett Wollman 	 * below which allowed reset segments in half the sequence space
208880ab7c0eSGarrett Wollman 	 * to fall though and be processed (which gives forged reset
208980ab7c0eSGarrett Wollman 	 * segments with a random sequence number a 50 percent chance of
209080ab7c0eSGarrett Wollman 	 * killing a connection).
209180ab7c0eSGarrett Wollman 	 * Then check timestamp, if present.
2092a0292f23SGarrett Wollman 	 * Then check the connection count, if present.
2093df8bae1dSRodney W. Grimes 	 * Then check that at least some bytes of segment are within
2094df8bae1dSRodney W. Grimes 	 * receive window.  If segment begins before rcv_nxt,
2095df8bae1dSRodney W. Grimes 	 * drop leading data (and SYN); if nothing left, just ack.
209680ab7c0eSGarrett Wollman 	 */
2097fb59c426SYoshinobu Inoue 	if (thflags & TH_RST) {
20983220a212SGleb Smirnoff 		/*
20993220a212SGleb Smirnoff 		 * RFC5961 Section 3.2
21003220a212SGleb Smirnoff 		 *
21013220a212SGleb Smirnoff 		 * - RST drops connection only if SEG.SEQ == RCV.NXT.
21023220a212SGleb Smirnoff 		 * - If RST is in window, we send challenge ACK.
21033220a212SGleb Smirnoff 		 *
21043220a212SGleb Smirnoff 		 * Note: to take into account delayed ACKs, we should
21053220a212SGleb Smirnoff 		 *   test against last_ack_sent instead of rcv_nxt.
21063220a212SGleb Smirnoff 		 * Note 2: we handle special case of closed window, not
21073220a212SGleb Smirnoff 		 *   covered by the RFC.
21083220a212SGleb Smirnoff 		 */
21093220a212SGleb Smirnoff 		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
21103220a212SGleb Smirnoff 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
21113220a212SGleb Smirnoff 		    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
211280ab7c0eSGarrett Wollman 
21133220a212SGleb Smirnoff 			KASSERT(tp->t_state != TCPS_SYN_SENT,
21143220a212SGleb Smirnoff 			    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
21153220a212SGleb Smirnoff 			    __func__, th, tp));
21163220a212SGleb Smirnoff 
21173220a212SGleb Smirnoff 			if (V_tcp_insecure_rst ||
21183220a212SGleb Smirnoff 			    tp->last_ack_sent == th->th_seq) {
21193220a212SGleb Smirnoff 				TCPSTAT_INC(tcps_drops);
21203220a212SGleb Smirnoff 				/* Drop the connection. */
21213220a212SGleb Smirnoff 				switch (tp->t_state) {
212280ab7c0eSGarrett Wollman 				case TCPS_SYN_RECEIVED:
212380ab7c0eSGarrett Wollman 					so->so_error = ECONNREFUSED;
212480ab7c0eSGarrett Wollman 					goto close;
212580ab7c0eSGarrett Wollman 				case TCPS_ESTABLISHED:
212680ab7c0eSGarrett Wollman 				case TCPS_FIN_WAIT_1:
212780ab7c0eSGarrett Wollman 				case TCPS_FIN_WAIT_2:
212880ab7c0eSGarrett Wollman 				case TCPS_CLOSE_WAIT:
21296779a1a1SMichael Tuexen 				case TCPS_CLOSING:
21306779a1a1SMichael Tuexen 				case TCPS_LAST_ACK:
213180ab7c0eSGarrett Wollman 					so->so_error = ECONNRESET;
213280ab7c0eSGarrett Wollman 				close:
21333220a212SGleb Smirnoff 					/* FALLTHROUGH */
21343220a212SGleb Smirnoff 				default:
213580ab7c0eSGarrett Wollman 					tp = tcp_close(tp);
21363220a212SGleb Smirnoff 				}
21373220a212SGleb Smirnoff 			} else {
21383220a212SGleb Smirnoff 				TCPSTAT_INC(tcps_badrst);
21393220a212SGleb Smirnoff 				/* Send challenge ACK. */
21403220a212SGleb Smirnoff 				tcp_respond(tp, mtod(m, void *), th, m,
21413220a212SGleb Smirnoff 				    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
21423220a212SGleb Smirnoff 				tp->last_ack_sent = tp->rcv_nxt;
21433220a212SGleb Smirnoff 				m = NULL;
21443220a212SGleb Smirnoff 			}
21453220a212SGleb Smirnoff 		}
21463220a212SGleb Smirnoff 		goto drop;
21473220a212SGleb Smirnoff 	}
214880ab7c0eSGarrett Wollman 
21493220a212SGleb Smirnoff 	/*
21503220a212SGleb Smirnoff 	 * RFC5961 Section 4.2
21513220a212SGleb Smirnoff 	 * Send challenge ACK for any SYN in synchronized state.
21523220a212SGleb Smirnoff 	 */
2153281a0fd4SPatrick Kelsey 	if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2154281a0fd4SPatrick Kelsey 	    tp->t_state != TCPS_SYN_RECEIVED) {
21553220a212SGleb Smirnoff 		TCPSTAT_INC(tcps_badsyn);
21563220a212SGleb Smirnoff 		if (V_tcp_insecure_syn &&
21573220a212SGleb Smirnoff 		    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
21583220a212SGleb Smirnoff 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
21593220a212SGleb Smirnoff 			tp = tcp_drop(tp, ECONNRESET);
21603220a212SGleb Smirnoff 			rstreason = BANDLIM_UNLIMITED;
21613220a212SGleb Smirnoff 		} else {
21623220a212SGleb Smirnoff 			/* Send challenge ACK. */
21633220a212SGleb Smirnoff 			tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
21643220a212SGleb Smirnoff 			    tp->snd_nxt, TH_ACK);
21653220a212SGleb Smirnoff 			tp->last_ack_sent = tp->rcv_nxt;
21663220a212SGleb Smirnoff 			m = NULL;
216780ab7c0eSGarrett Wollman 		}
216880ab7c0eSGarrett Wollman 		goto drop;
216980ab7c0eSGarrett Wollman 	}
217080ab7c0eSGarrett Wollman 
217180ab7c0eSGarrett Wollman 	/*
2172df8bae1dSRodney W. Grimes 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2173df8bae1dSRodney W. Grimes 	 * and it's less than ts_recent, drop it.
2174df8bae1dSRodney W. Grimes 	 */
2175be2ac88cSJonathan Lemon 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
217680ab7c0eSGarrett Wollman 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2177df8bae1dSRodney W. Grimes 
2178df8bae1dSRodney W. Grimes 		/* Check to see if ts_recent is over 24 days old.  */
2179d8951c8aSBjoern A. Zeeb 		if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2180df8bae1dSRodney W. Grimes 			/*
2181df8bae1dSRodney W. Grimes 			 * Invalidate ts_recent.  If this segment updates
2182df8bae1dSRodney W. Grimes 			 * ts_recent, the age will be reset later and ts_recent
2183df8bae1dSRodney W. Grimes 			 * will get a valid value.  If it does not, setting
2184df8bae1dSRodney W. Grimes 			 * ts_recent to zero will at least satisfy the
2185df8bae1dSRodney W. Grimes 			 * requirement that zero be placed in the timestamp
2186df8bae1dSRodney W. Grimes 			 * echo reply when ts_recent isn't valid.  The
2187df8bae1dSRodney W. Grimes 			 * age isn't reset until we get a valid ts_recent
2188df8bae1dSRodney W. Grimes 			 * because we don't want out-of-order segments to be
2189df8bae1dSRodney W. Grimes 			 * dropped when ts_recent is old.
2190df8bae1dSRodney W. Grimes 			 */
2191df8bae1dSRodney W. Grimes 			tp->ts_recent = 0;
2192df8bae1dSRodney W. Grimes 		} else {
219378b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvduppack);
219478b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
219578b50714SRobert Watson 			TCPSTAT_INC(tcps_pawsdrop);
219607fd333dSMatthew Dillon 			if (tlen)
2197df8bae1dSRodney W. Grimes 				goto dropafterack;
21981ab4789dSMatthew Dillon 			goto drop;
21991ab4789dSMatthew Dillon 		}
2200df8bae1dSRodney W. Grimes 	}
2201df8bae1dSRodney W. Grimes 
2202a0292f23SGarrett Wollman 	/*
220380ab7c0eSGarrett Wollman 	 * In the SYN-RECEIVED state, validate that the packet belongs to
220480ab7c0eSGarrett Wollman 	 * this connection before trimming the data to fit the receive
220580ab7c0eSGarrett Wollman 	 * window.  Check the sequence number versus IRS since we know
220680ab7c0eSGarrett Wollman 	 * the sequence numbers haven't wrapped.  This is a partial fix
220780ab7c0eSGarrett Wollman 	 * for the "LAND" DoS attack.
220880ab7c0eSGarrett Wollman 	 */
2209a57815efSBosko Milekic 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2210a57815efSBosko Milekic 		rstreason = BANDLIM_RST_OPENPORT;
2211a57815efSBosko Milekic 		goto dropwithreset;
2212a57815efSBosko Milekic 	}
221380ab7c0eSGarrett Wollman 
2214fb59c426SYoshinobu Inoue 	todrop = tp->rcv_nxt - th->th_seq;
2215df8bae1dSRodney W. Grimes 	if (todrop > 0) {
2216831ad37eSXin LI 		if (thflags & TH_SYN) {
2217fb59c426SYoshinobu Inoue 			thflags &= ~TH_SYN;
2218fb59c426SYoshinobu Inoue 			th->th_seq++;
2219fb59c426SYoshinobu Inoue 			if (th->th_urp > 1)
2220fb59c426SYoshinobu Inoue 				th->th_urp--;
2221df8bae1dSRodney W. Grimes 			else
2222fb59c426SYoshinobu Inoue 				thflags &= ~TH_URG;
2223df8bae1dSRodney W. Grimes 			todrop--;
2224df8bae1dSRodney W. Grimes 		}
2225df8bae1dSRodney W. Grimes 		/*
2226dac20301SGarrett Wollman 		 * Following if statement from Stevens, vol. 2, p. 960.
2227df8bae1dSRodney W. Grimes 		 */
2228fb59c426SYoshinobu Inoue 		if (todrop > tlen
2229fb59c426SYoshinobu Inoue 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2230dac20301SGarrett Wollman 			/*
2231dac20301SGarrett Wollman 			 * Any valid FIN must be to the left of the window.
2232dac20301SGarrett Wollman 			 * At this point the FIN must be a duplicate or out
2233dac20301SGarrett Wollman 			 * of sequence; drop it.
2234dac20301SGarrett Wollman 			 */
2235fb59c426SYoshinobu Inoue 			thflags &= ~TH_FIN;
2236dac20301SGarrett Wollman 
2237df8bae1dSRodney W. Grimes 			/*
2238dac20301SGarrett Wollman 			 * Send an ACK to resynchronize and drop any data.
2239dac20301SGarrett Wollman 			 * But keep on processing for RST or ACK.
2240df8bae1dSRodney W. Grimes 			 */
2241dac20301SGarrett Wollman 			tp->t_flags |= TF_ACKNOW;
2242fb59c426SYoshinobu Inoue 			todrop = tlen;
224378b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvduppack);
224478b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2245df8bae1dSRodney W. Grimes 		} else {
224678b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpartduppack);
224778b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2248df8bae1dSRodney W. Grimes 		}
22495acfd95cSMichael Tuexen 		/*
22505acfd95cSMichael Tuexen 		 * DSACK - add SACK block for dropped range
22515acfd95cSMichael Tuexen 		 */
22528f63a52bSMichael Tuexen 		if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2253ecc5b1d1SMichael Tuexen 			tcp_update_sack_list(tp, th->th_seq,
2254ecc5b1d1SMichael Tuexen 			    th->th_seq + todrop);
22555acfd95cSMichael Tuexen 			/*
22565acfd95cSMichael Tuexen 			 * ACK now, as the next in-sequence segment
22575acfd95cSMichael Tuexen 			 * will clear the DSACK block again
22585acfd95cSMichael Tuexen 			 */
22595acfd95cSMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
22605acfd95cSMichael Tuexen 		}
2261fb59c426SYoshinobu Inoue 		drop_hdrlen += todrop;	/* drop from the top afterwards */
2262fb59c426SYoshinobu Inoue 		th->th_seq += todrop;
2263fb59c426SYoshinobu Inoue 		tlen -= todrop;
2264fb59c426SYoshinobu Inoue 		if (th->th_urp > todrop)
2265fb59c426SYoshinobu Inoue 			th->th_urp -= todrop;
2266df8bae1dSRodney W. Grimes 		else {
2267fb59c426SYoshinobu Inoue 			thflags &= ~TH_URG;
2268fb59c426SYoshinobu Inoue 			th->th_urp = 0;
2269df8bae1dSRodney W. Grimes 		}
2270df8bae1dSRodney W. Grimes 	}
2271df8bae1dSRodney W. Grimes 
2272df8bae1dSRodney W. Grimes 	/*
2273df8bae1dSRodney W. Grimes 	 * If new data are received on a connection after the
2274df8bae1dSRodney W. Grimes 	 * user processes are gone, then RST the other end.
2275df8bae1dSRodney W. Grimes 	 */
2276df8bae1dSRodney W. Grimes 	if ((so->so_state & SS_NOFDREF) &&
2277fb59c426SYoshinobu Inoue 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
227807dacf03SAndre Oppermann 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
227907dacf03SAndre Oppermann 			log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
228007dacf03SAndre Oppermann 			    "after socket was closed, "
228107dacf03SAndre Oppermann 			    "sending RST and removing tcpcb\n",
2282e31d8aa3SMike Silbersack 			    s, __func__, tcpstates[tp->t_state], tlen);
2283773673c1SAndre Oppermann 			free(s, M_TCPLOG);
2284773673c1SAndre Oppermann 		}
2285df8bae1dSRodney W. Grimes 		tp = tcp_close(tp);
228678b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvafterclose);
2287a57815efSBosko Milekic 		rstreason = BANDLIM_UNLIMITED;
2288df8bae1dSRodney W. Grimes 		goto dropwithreset;
2289df8bae1dSRodney W. Grimes 	}
2290df8bae1dSRodney W. Grimes 
2291df8bae1dSRodney W. Grimes 	/*
2292df8bae1dSRodney W. Grimes 	 * If segment ends after window, drop trailing data
2293df8bae1dSRodney W. Grimes 	 * (and PUSH and FIN); if nothing left, just ACK.
2294df8bae1dSRodney W. Grimes 	 */
2295fb59c426SYoshinobu Inoue 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2296df8bae1dSRodney W. Grimes 	if (todrop > 0) {
229778b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvpackafterwin);
2298fb59c426SYoshinobu Inoue 		if (todrop >= tlen) {
229978b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2300df8bae1dSRodney W. Grimes 			/*
2301df8bae1dSRodney W. Grimes 			 * If window is closed can only take segments at
2302df8bae1dSRodney W. Grimes 			 * window edge, and have to drop data and PUSH from
2303df8bae1dSRodney W. Grimes 			 * incoming segments.  Continue processing, but
2304df8bae1dSRodney W. Grimes 			 * remember to ack.  Otherwise, drop segment
2305df8bae1dSRodney W. Grimes 			 * and ack.
2306df8bae1dSRodney W. Grimes 			 */
2307fb59c426SYoshinobu Inoue 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2308df8bae1dSRodney W. Grimes 				tp->t_flags |= TF_ACKNOW;
230978b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvwinprobe);
2310df8bae1dSRodney W. Grimes 			} else
2311df8bae1dSRodney W. Grimes 				goto dropafterack;
2312df8bae1dSRodney W. Grimes 		} else
231378b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2314df8bae1dSRodney W. Grimes 		m_adj(m, -todrop);
2315fb59c426SYoshinobu Inoue 		tlen -= todrop;
2316fb59c426SYoshinobu Inoue 		thflags &= ~(TH_PUSH|TH_FIN);
2317df8bae1dSRodney W. Grimes 	}
2318df8bae1dSRodney W. Grimes 
2319df8bae1dSRodney W. Grimes 	/*
2320df8bae1dSRodney W. Grimes 	 * If last ACK falls within this segment's sequence numbers,
2321df8bae1dSRodney W. Grimes 	 * record its timestamp.
2322cf09195bSPaul Saab 	 * NOTE:
2323cf09195bSPaul Saab 	 * 1) That the test incorporates suggestions from the latest
2324a0292f23SGarrett Wollman 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
2325cf09195bSPaul Saab 	 * 2) That updating only on newer timestamps interferes with
2326cf09195bSPaul Saab 	 *    our earlier PAWS tests, so this check should be solely
2327cf09195bSPaul Saab 	 *    predicated on the sequence space of this segment.
2328cf09195bSPaul Saab 	 * 3) That we modify the segment boundary check to be
2329cf09195bSPaul Saab 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
2330cf09195bSPaul Saab 	 *    instead of RFC1323's
2331cf09195bSPaul Saab 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
2332cf09195bSPaul Saab 	 *    This modified check allows us to overcome RFC1323's
2333cf09195bSPaul Saab 	 *    limitations as described in Stevens TCP/IP Illustrated
2334cf09195bSPaul Saab 	 *    Vol. 2 p.869. In such cases, we can still calculate the
2335cf09195bSPaul Saab 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
2336df8bae1dSRodney W. Grimes 	 */
2337be2ac88cSJonathan Lemon 	if ((to.to_flags & TOF_TS) != 0 &&
2338cf09195bSPaul Saab 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2339cf09195bSPaul Saab 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2340cf09195bSPaul Saab 		((thflags & (TH_SYN|TH_FIN)) != 0))) {
2341d8951c8aSBjoern A. Zeeb 		tp->ts_recent_age = tcp_ts_getticks();
2342a0292f23SGarrett Wollman 		tp->ts_recent = to.to_tsval;
2343df8bae1dSRodney W. Grimes 	}
2344df8bae1dSRodney W. Grimes 
2345df8bae1dSRodney W. Grimes 	/*
2346a0292f23SGarrett Wollman 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
2347a0292f23SGarrett Wollman 	 * flag is on (half-synchronized state), then queue data for
2348a0292f23SGarrett Wollman 	 * later processing; else drop segment and return.
2349a0292f23SGarrett Wollman 	 */
2350fb59c426SYoshinobu Inoue 	if ((thflags & TH_ACK) == 0) {
2351a0292f23SGarrett Wollman 		if (tp->t_state == TCPS_SYN_RECEIVED ||
2352281a0fd4SPatrick Kelsey 		    (tp->t_flags & TF_NEEDSYN)) {
2353281a0fd4SPatrick Kelsey 			if (tp->t_state == TCPS_SYN_RECEIVED &&
235468bd7ed1SJonathan T. Looney 			    IS_FASTOPEN(tp->t_flags)) {
2355281a0fd4SPatrick Kelsey 				tp->snd_wnd = tiwin;
2356281a0fd4SPatrick Kelsey 				cc_conn_init(tp);
2357281a0fd4SPatrick Kelsey 			}
2358a0292f23SGarrett Wollman 			goto step6;
2359281a0fd4SPatrick Kelsey 		} else if (tp->t_flags & TF_ACKNOW)
23605e1aa279SDavid Malone 			goto dropafterack;
2361a0292f23SGarrett Wollman 		else
2362a0292f23SGarrett Wollman 			goto drop;
2363a0292f23SGarrett Wollman 	}
2364df8bae1dSRodney W. Grimes 
2365df8bae1dSRodney W. Grimes 	/*
2366df8bae1dSRodney W. Grimes 	 * Ack processing.
2367df8bae1dSRodney W. Grimes 	 */
2368df8bae1dSRodney W. Grimes 	switch (tp->t_state) {
2369df8bae1dSRodney W. Grimes 
2370df8bae1dSRodney W. Grimes 	/*
2371764d8cefSBill Fenner 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2372764d8cefSBill Fenner 	 * ESTABLISHED state and continue processing.
2373764d8cefSBill Fenner 	 * The ACK was checked above.
2374df8bae1dSRodney W. Grimes 	 */
2375df8bae1dSRodney W. Grimes 	case TCPS_SYN_RECEIVED:
2376a0292f23SGarrett Wollman 
237778b50714SRobert Watson 		TCPSTAT_INC(tcps_connects);
2378df8bae1dSRodney W. Grimes 		soisconnected(so);
2379df8bae1dSRodney W. Grimes 		/* Do window scaling? */
2380df8bae1dSRodney W. Grimes 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2381df8bae1dSRodney W. Grimes 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2382df8bae1dSRodney W. Grimes 			tp->rcv_scale = tp->request_r_scale;
2383df8bae1dSRodney W. Grimes 		}
2384116ef4d6SMichael Tuexen 		tp->snd_wnd = tiwin;
2385a0292f23SGarrett Wollman 		/*
2386a0292f23SGarrett Wollman 		 * Make transitions:
2387a0292f23SGarrett Wollman 		 *      SYN-RECEIVED  -> ESTABLISHED
2388a0292f23SGarrett Wollman 		 *      SYN-RECEIVED* -> FIN-WAIT-1
2389a0292f23SGarrett Wollman 		 */
23909b8b58e0SJonathan Lemon 		tp->t_starttime = ticks;
239118a75309SPatrick Kelsey 		if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
2392281a0fd4SPatrick Kelsey 			tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2393281a0fd4SPatrick Kelsey 			tp->t_tfo_pending = NULL;
2394281a0fd4SPatrick Kelsey 		}
23958db239dcSMichael Tuexen 		if (tp->t_flags & TF_NEEDFIN) {
23968db239dcSMichael Tuexen 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
23978db239dcSMichael Tuexen 			tp->t_flags &= ~TF_NEEDFIN;
23988db239dcSMichael Tuexen 		} else {
23998db239dcSMichael Tuexen 			tcp_state_change(tp, TCPS_ESTABLISHED);
24008db239dcSMichael Tuexen 			TCP_PROBE5(accept__established, NULL, tp,
24018db239dcSMichael Tuexen 			    m, tp, th);
2402281a0fd4SPatrick Kelsey 			/*
2403281a0fd4SPatrick Kelsey 			 * TFO connections call cc_conn_init() during SYN
2404281a0fd4SPatrick Kelsey 			 * processing.  Calling it again here for such
2405281a0fd4SPatrick Kelsey 			 * connections is not harmless as it would undo the
2406281a0fd4SPatrick Kelsey 			 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2407281a0fd4SPatrick Kelsey 			 * is retransmitted.
2408281a0fd4SPatrick Kelsey 			 */
240968bd7ed1SJonathan T. Looney 			if (!IS_FASTOPEN(tp->t_flags))
2410dbc42409SLawrence Stewart 				cc_conn_init(tp);
24119077f387SGleb Smirnoff 			tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
24127ff19458SPaul Traina 		}
2413a0292f23SGarrett Wollman 		/*
2414b2ade6b1SRichard Scheffenegger 		 * Account for the ACK of our SYN prior to
2415b2ade6b1SRichard Scheffenegger 		 * regular ACK processing below, except for
2416b2ade6b1SRichard Scheffenegger 		 * simultaneous SYN, which is handled later.
2417b2ade6b1SRichard Scheffenegger 		 */
2418b2ade6b1SRichard Scheffenegger 		if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2419b2ade6b1SRichard Scheffenegger 			incforsyn = 1;
2420b2ade6b1SRichard Scheffenegger 		/*
2421a0292f23SGarrett Wollman 		 * If segment contains data or ACK, will call tcp_reass()
2422a0292f23SGarrett Wollman 		 * later; if not, do so now to pass queued data to user.
2423a0292f23SGarrett Wollman 		 */
2424fb59c426SYoshinobu Inoue 		if (tlen == 0 && (thflags & TH_FIN) == 0)
2425c28440dbSRandall Stewart 			(void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2426a0292f23SGarrett Wollman 			    (struct mbuf *)0);
242760ee3bb2SAndre Oppermann 		tp->snd_wl1 = th->th_seq - 1;
242893b0017fSPhilippe Charnier 		/* FALLTHROUGH */
2429df8bae1dSRodney W. Grimes 
2430df8bae1dSRodney W. Grimes 	/*
2431df8bae1dSRodney W. Grimes 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2432df8bae1dSRodney W. Grimes 	 * ACKs.  If the ack is in the range
2433fb59c426SYoshinobu Inoue 	 *	tp->snd_una < th->th_ack <= tp->snd_max
2434fb59c426SYoshinobu Inoue 	 * then advance tp->snd_una to th->th_ack and drop
2435df8bae1dSRodney W. Grimes 	 * data from the retransmission queue.  If this ACK reflects
2436df8bae1dSRodney W. Grimes 	 * more up to date window information we update our window information.
2437df8bae1dSRodney W. Grimes 	 */
2438df8bae1dSRodney W. Grimes 	case TCPS_ESTABLISHED:
2439df8bae1dSRodney W. Grimes 	case TCPS_FIN_WAIT_1:
2440df8bae1dSRodney W. Grimes 	case TCPS_FIN_WAIT_2:
2441df8bae1dSRodney W. Grimes 	case TCPS_CLOSE_WAIT:
2442df8bae1dSRodney W. Grimes 	case TCPS_CLOSING:
2443df8bae1dSRodney W. Grimes 	case TCPS_LAST_ACK:
24445a53ca16SPaul Saab 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
244578b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvacktoomuch);
24465a53ca16SPaul Saab 			goto dropafterack;
24475a53ca16SPaul Saab 		}
24483529149eSAndre Oppermann 		if ((tp->t_flags & TF_SACK_PERMIT) &&
2449fc30a251SAndre Oppermann 		    ((to.to_flags & TOF_SACK) ||
2450fc30a251SAndre Oppermann 		     !TAILQ_EMPTY(&tp->snd_holes)))
2451021eaf79SHiren Panchasara 			sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
245212eeb81fSHiren Panchasara 		else
245312eeb81fSHiren Panchasara 			/*
245412eeb81fSHiren Panchasara 			 * Reset the value so that previous (valid) value
245512eeb81fSHiren Panchasara 			 * from the last ack with SACK doesn't get used.
245612eeb81fSHiren Panchasara 			 */
245712eeb81fSHiren Panchasara 			tp->sackhint.sacked_bytes = 0;
245839bc9de5SLawrence Stewart 
2459bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
246039bc9de5SLawrence Stewart 		/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
246139bc9de5SLawrence Stewart 		hhook_run_tcp_est_in(tp, th, &to);
2462bd79708dSJonathan T. Looney #endif
246339bc9de5SLawrence Stewart 
2464fb59c426SYoshinobu Inoue 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
24650c39d38dSGleb Smirnoff 			u_int maxseg;
24660c39d38dSGleb Smirnoff 
24670c39d38dSGleb Smirnoff 			maxseg = tcp_maxseg(tp);
2468021eaf79SHiren Panchasara 			if (tlen == 0 &&
2469021eaf79SHiren Panchasara 			    (tiwin == tp->snd_wnd ||
2470021eaf79SHiren Panchasara 			    (tp->t_flags & TF_SACK_PERMIT))) {
247162b90589SPeter Wemm 				/*
247262b90589SPeter Wemm 				 * If this is the first time we've seen a
247362b90589SPeter Wemm 				 * FIN from the remote, this is not a
247462b90589SPeter Wemm 				 * duplicate and it needs to be processed
247562b90589SPeter Wemm 				 * normally.  This happens during a
247662b90589SPeter Wemm 				 * simultaneous close.
247762b90589SPeter Wemm 				 */
247862b90589SPeter Wemm 				if ((thflags & TH_FIN) &&
247962b90589SPeter Wemm 				    (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
248062b90589SPeter Wemm 					tp->t_dupacks = 0;
248162b90589SPeter Wemm 					break;
248262b90589SPeter Wemm 				}
248378b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvdupack);
2484df8bae1dSRodney W. Grimes 				/*
2485df8bae1dSRodney W. Grimes 				 * If we have outstanding data (other than
2486df8bae1dSRodney W. Grimes 				 * a window probe), this is a completely
2487df8bae1dSRodney W. Grimes 				 * duplicate ack (ie, window info didn't
24885f30ec9bSEitan Adler 				 * change and FIN isn't set),
24895f30ec9bSEitan Adler 				 * the ack is the biggest we've
2490df8bae1dSRodney W. Grimes 				 * seen and we've seen exactly our rexmt
2491a4641f4eSPedro F. Giffuni 				 * threshold of them, assume a packet
2492df8bae1dSRodney W. Grimes 				 * has been dropped and retransmit it.
2493df8bae1dSRodney W. Grimes 				 * Kludge snd_nxt & the congestion
2494df8bae1dSRodney W. Grimes 				 * window so we send only this one
2495df8bae1dSRodney W. Grimes 				 * packet.
2496df8bae1dSRodney W. Grimes 				 *
2497df8bae1dSRodney W. Grimes 				 * We know we're losing at the current
2498df8bae1dSRodney W. Grimes 				 * window size so do congestion avoidance
2499df8bae1dSRodney W. Grimes 				 * (set ssthresh to half the current window
2500df8bae1dSRodney W. Grimes 				 * and pull our congestion window back to
2501df8bae1dSRodney W. Grimes 				 * the new ssthresh).
2502df8bae1dSRodney W. Grimes 				 *
2503df8bae1dSRodney W. Grimes 				 * Dup acks mean that packets have left the
2504df8bae1dSRodney W. Grimes 				 * network (they're now cached at the receiver)
2505df8bae1dSRodney W. Grimes 				 * so bump cwnd by the amount in the receiver
2506df8bae1dSRodney W. Grimes 				 * to keep a constant cwnd packets in the
2507df8bae1dSRodney W. Grimes 				 * network.
2508f2512ba1SRui Paulo 				 *
2509f2512ba1SRui Paulo 				 * When using TCP ECN, notify the peer that
2510f2512ba1SRui Paulo 				 * we reduced the cwnd.
2511df8bae1dSRodney W. Grimes 				 */
2512021eaf79SHiren Panchasara 				/*
2513021eaf79SHiren Panchasara 				 * Following 2 kinds of acks should not affect
2514021eaf79SHiren Panchasara 				 * dupack counting:
2515021eaf79SHiren Panchasara 				 * 1) Old acks
2516021eaf79SHiren Panchasara 				 * 2) Acks with SACK but without any new SACK
2517021eaf79SHiren Panchasara 				 * information in them. These could result from
2518021eaf79SHiren Panchasara 				 * any anomaly in the network like a switch
2519021eaf79SHiren Panchasara 				 * duplicating packets or a possible DoS attack.
2520021eaf79SHiren Panchasara 				 */
2521021eaf79SHiren Panchasara 				if (th->th_ack != tp->snd_una ||
2522021eaf79SHiren Panchasara 				    ((tp->t_flags & TF_SACK_PERMIT) &&
2523021eaf79SHiren Panchasara 				    !sack_changed))
2524021eaf79SHiren Panchasara 					break;
2525021eaf79SHiren Panchasara 				else if (!tcp_timer_active(tp, TT_REXMT))
2526df8bae1dSRodney W. Grimes 					tp->t_dupacks = 0;
2527cb942153SJeffrey Hsu 				else if (++tp->t_dupacks > tcprexmtthresh ||
2528dbc42409SLawrence Stewart 				     IN_FASTRECOVERY(tp->t_flags)) {
25294b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
25304b7b743cSLawrence Stewart 					    CC_DUPACK);
25313529149eSAndre Oppermann 					if ((tp->t_flags & TF_SACK_PERMIT) &&
2532dbc42409SLawrence Stewart 					    IN_FASTRECOVERY(tp->t_flags)) {
2533808f11b7SPaul Saab 						int awnd;
253425e6f9edSPaul Saab 
253525e6f9edSPaul Saab 						/*
253625e6f9edSPaul Saab 						 * Compute the amount of data in flight first.
25374c3972f0SHiren Panchasara 						 * We can inject new data into the pipe iff
253825e6f9edSPaul Saab 						 * we have less than 1/2 the original window's
253925e6f9edSPaul Saab 						 * worth of data in flight.
254025e6f9edSPaul Saab 						 */
254112eeb81fSHiren Panchasara 						if (V_tcp_do_rfc6675_pipe)
254212eeb81fSHiren Panchasara 							awnd = tcp_compute_pipe(tp);
254312eeb81fSHiren Panchasara 						else
2544808f11b7SPaul Saab 							awnd = (tp->snd_nxt - tp->snd_fack) +
25450077b016SPaul Saab 								tp->sackhint.sack_bytes_rexmit;
254612eeb81fSHiren Panchasara 
2547808f11b7SPaul Saab 						if (awnd < tp->snd_ssthresh) {
25480c39d38dSGleb Smirnoff 							tp->snd_cwnd += maxseg;
254925e6f9edSPaul Saab 							if (tp->snd_cwnd > tp->snd_ssthresh)
255025e6f9edSPaul Saab 								tp->snd_cwnd = tp->snd_ssthresh;
255125e6f9edSPaul Saab 						}
255225e6f9edSPaul Saab 					} else
25530c39d38dSGleb Smirnoff 						tp->snd_cwnd += maxseg;
255455bceb1eSRandall Stewart 					(void) tp->t_fb->tfb_tcp_output(tp);
255546f58482SJonathan Lemon 					goto drop;
2556cb942153SJeffrey Hsu 				} else if (tp->t_dupacks == tcprexmtthresh) {
2557cb942153SJeffrey Hsu 					tcp_seq onxt = tp->snd_nxt;
2558a0445c2eSJayanth Vijayaraghavan 
2559a0445c2eSJayanth Vijayaraghavan 					/*
2560a0445c2eSJayanth Vijayaraghavan 					 * If we're doing sack, check to
2561a0445c2eSJayanth Vijayaraghavan 					 * see if we're already in sack
2562a0445c2eSJayanth Vijayaraghavan 					 * recovery. If we're not doing sack,
2563a0445c2eSJayanth Vijayaraghavan 					 * check to see if we're in newreno
2564a0445c2eSJayanth Vijayaraghavan 					 * recovery.
2565a0445c2eSJayanth Vijayaraghavan 					 */
25663529149eSAndre Oppermann 					if (tp->t_flags & TF_SACK_PERMIT) {
2567dbc42409SLawrence Stewart 						if (IN_FASTRECOVERY(tp->t_flags)) {
2568a0445c2eSJayanth Vijayaraghavan 							tp->t_dupacks = 0;
2569a0445c2eSJayanth Vijayaraghavan 							break;
2570a0445c2eSJayanth Vijayaraghavan 						}
2571dbc42409SLawrence Stewart 					} else {
2572a0445c2eSJayanth Vijayaraghavan 						if (SEQ_LEQ(th->th_ack,
25739d11646dSJeffrey Hsu 						    tp->snd_recover)) {
2574cb942153SJeffrey Hsu 							tp->t_dupacks = 0;
2575cb942153SJeffrey Hsu 							break;
257646f58482SJonathan Lemon 						}
2577a0445c2eSJayanth Vijayaraghavan 					}
2578dbc42409SLawrence Stewart 					/* Congestion signal before ack. */
2579dbc42409SLawrence Stewart 					cc_cong_signal(tp, th, CC_NDUPACK);
25804b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
25814b7b743cSLawrence Stewart 					    CC_DUPACK);
2582b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT, 0);
25839b8b58e0SJonathan Lemon 					tp->t_rtttime = 0;
25843529149eSAndre Oppermann 					if (tp->t_flags & TF_SACK_PERMIT) {
258578b50714SRobert Watson 						TCPSTAT_INC(
258678b50714SRobert Watson 						    tcps_sack_recovery_episode);
2587a3574665SMichael Tuexen 						tp->snd_recover = tp->snd_nxt;
25880c39d38dSGleb Smirnoff 						tp->snd_cwnd = maxseg;
258955bceb1eSRandall Stewart 						(void) tp->t_fb->tfb_tcp_output(tp);
25906d90faf3SPaul Saab 						goto drop;
25916d90faf3SPaul Saab 					}
2592fb59c426SYoshinobu Inoue 					tp->snd_nxt = th->th_ack;
25930c39d38dSGleb Smirnoff 					tp->snd_cwnd = maxseg;
259455bceb1eSRandall Stewart 					(void) tp->t_fb->tfb_tcp_output(tp);
259548d2549cSJeffrey Hsu 					KASSERT(tp->snd_limited <= 2,
2596302ce8d6SAndre Oppermann 					    ("%s: tp->snd_limited too big",
2597302ce8d6SAndre Oppermann 					    __func__));
2598df8bae1dSRodney W. Grimes 					tp->snd_cwnd = tp->snd_ssthresh +
25990c39d38dSGleb Smirnoff 					     maxseg *
260048d2549cSJeffrey Hsu 					     (tp->t_dupacks - tp->snd_limited);
2601df8bae1dSRodney W. Grimes 					if (SEQ_GT(onxt, tp->snd_nxt))
2602df8bae1dSRodney W. Grimes 						tp->snd_nxt = onxt;
2603df8bae1dSRodney W. Grimes 					goto drop;
2604603724d3SBjoern A. Zeeb 				} else if (V_tcp_do_rfc3042) {
260562d4443fSHiren Panchasara 					/*
260662d4443fSHiren Panchasara 					 * Process first and second duplicate
260762d4443fSHiren Panchasara 					 * ACKs. Each indicates a segment
260862d4443fSHiren Panchasara 					 * leaving the network, creating room
260962d4443fSHiren Panchasara 					 * for more. Make sure we can send a
261062d4443fSHiren Panchasara 					 * packet on reception of each duplicate
261162d4443fSHiren Panchasara 					 * ACK by increasing snd_cwnd by one
261262d4443fSHiren Panchasara 					 * segment. Restore the original
261362d4443fSHiren Panchasara 					 * snd_cwnd after packet transmission.
261462d4443fSHiren Panchasara 					 */
26154b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
26164b7b743cSLawrence Stewart 					    CC_DUPACK);
26173ac12506SJonathan T. Looney 					uint32_t oldcwnd = tp->snd_cwnd;
261848d2549cSJeffrey Hsu 					tcp_seq oldsndmax = tp->snd_max;
261948d2549cSJeffrey Hsu 					u_int sent;
26205628dd08SAndre Oppermann 					int avail;
262189c02376SJeffrey Hsu 
2622582a954bSJeffrey Hsu 					KASSERT(tp->t_dupacks == 1 ||
2623582a954bSJeffrey Hsu 					    tp->t_dupacks == 2,
2624302ce8d6SAndre Oppermann 					    ("%s: dupacks not 1 or 2",
2625302ce8d6SAndre Oppermann 					    __func__));
262661a36e3dSJeffrey Hsu 					if (tp->t_dupacks == 1)
262748d2549cSJeffrey Hsu 						tp->snd_limited = 0;
262861a36e3dSJeffrey Hsu 					tp->snd_cwnd =
262961a36e3dSJeffrey Hsu 					    (tp->snd_nxt - tp->snd_una) +
263061a36e3dSJeffrey Hsu 					    (tp->t_dupacks - tp->snd_limited) *
26310c39d38dSGleb Smirnoff 					    maxseg;
26325628dd08SAndre Oppermann 					/*
26335628dd08SAndre Oppermann 					 * Only call tcp_output when there
26345628dd08SAndre Oppermann 					 * is new data available to be sent.
26355628dd08SAndre Oppermann 					 * Otherwise we would send pure ACKs.
26365628dd08SAndre Oppermann 					 */
26375628dd08SAndre Oppermann 					SOCKBUF_LOCK(&so->so_snd);
2638cfa6009eSGleb Smirnoff 					avail = sbavail(&so->so_snd) -
26395628dd08SAndre Oppermann 					    (tp->snd_nxt - tp->snd_una);
26405628dd08SAndre Oppermann 					SOCKBUF_UNLOCK(&so->so_snd);
26415628dd08SAndre Oppermann 					if (avail > 0)
264255bceb1eSRandall Stewart 						(void) tp->t_fb->tfb_tcp_output(tp);
264348d2549cSJeffrey Hsu 					sent = tp->snd_max - oldsndmax;
26440c39d38dSGleb Smirnoff 					if (sent > maxseg) {
264589c02376SJeffrey Hsu 						KASSERT((tp->t_dupacks == 2 &&
264689c02376SJeffrey Hsu 						    tp->snd_limited == 0) ||
26470c39d38dSGleb Smirnoff 						   (sent == maxseg + 1 &&
264889c02376SJeffrey Hsu 						    tp->t_flags & TF_SENTFIN),
2649302ce8d6SAndre Oppermann 						    ("%s: sent too much",
2650302ce8d6SAndre Oppermann 						    __func__));
265148d2549cSJeffrey Hsu 						tp->snd_limited = 2;
265248d2549cSJeffrey Hsu 					} else if (sent > 0)
265348d2549cSJeffrey Hsu 						++tp->snd_limited;
2654582a954bSJeffrey Hsu 					tp->snd_cwnd = oldcwnd;
2655582a954bSJeffrey Hsu 					goto drop;
2656df8bae1dSRodney W. Grimes 				}
2657021eaf79SHiren Panchasara 			}
2658df8bae1dSRodney W. Grimes 			break;
2659021eaf79SHiren Panchasara 		} else {
2660021eaf79SHiren Panchasara 			/*
2661021eaf79SHiren Panchasara 			 * This ack is advancing the left edge, reset the
2662021eaf79SHiren Panchasara 			 * counter.
2663021eaf79SHiren Panchasara 			 */
2664021eaf79SHiren Panchasara 			tp->t_dupacks = 0;
2665021eaf79SHiren Panchasara 			/*
2666021eaf79SHiren Panchasara 			 * If this ack also has new SACK info, increment the
2667021eaf79SHiren Panchasara 			 * counter as per rfc6675.
2668021eaf79SHiren Panchasara 			 */
2669021eaf79SHiren Panchasara 			if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2670021eaf79SHiren Panchasara 				tp->t_dupacks++;
2671df8bae1dSRodney W. Grimes 		}
2672cb942153SJeffrey Hsu 
2673302ce8d6SAndre Oppermann 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2674302ce8d6SAndre Oppermann 		    ("%s: th_ack <= snd_una", __func__));
2675cb942153SJeffrey Hsu 
2676df8bae1dSRodney W. Grimes 		/*
2677df8bae1dSRodney W. Grimes 		 * If the congestion window was inflated to account
2678df8bae1dSRodney W. Grimes 		 * for the other side's cached packets, retract it.
2679df8bae1dSRodney W. Grimes 		 */
2680dbc42409SLawrence Stewart 		if (IN_FASTRECOVERY(tp->t_flags)) {
2681cb942153SJeffrey Hsu 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
26823529149eSAndre Oppermann 				if (tp->t_flags & TF_SACK_PERMIT)
26836d90faf3SPaul Saab 					tcp_sack_partialack(tp, th);
26846d90faf3SPaul Saab 				else
2685c068736aSJeffrey Hsu 					tcp_newreno_partial_ack(tp, th);
2686dbc42409SLawrence Stewart 			} else
2687dbc42409SLawrence Stewart 				cc_post_recovery(tp, th);
268846f58482SJonathan Lemon 		}
2689a0292f23SGarrett Wollman 		/*
2690a0292f23SGarrett Wollman 		 * If we reach this point, ACK is not a duplicate,
2691a0292f23SGarrett Wollman 		 *     i.e., it ACKs something we sent.
2692a0292f23SGarrett Wollman 		 */
2693a0292f23SGarrett Wollman 		if (tp->t_flags & TF_NEEDSYN) {
2694a0292f23SGarrett Wollman 			/*
2695a0292f23SGarrett Wollman 			 * T/TCP: Connection was half-synchronized, and our
2696a0292f23SGarrett Wollman 			 * SYN has been ACK'd (so connection is now fully
269707e43e10SAndras Olah 			 * synchronized).  Go to non-starred state,
269807e43e10SAndras Olah 			 * increment snd_una for ACK of SYN, and check if
269907e43e10SAndras Olah 			 * we can do window scaling.
2700a0292f23SGarrett Wollman 			 */
2701a0292f23SGarrett Wollman 			tp->t_flags &= ~TF_NEEDSYN;
2702a0292f23SGarrett Wollman 			tp->snd_una++;
270307e43e10SAndras Olah 			/* Do window scaling? */
270407e43e10SAndras Olah 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
270507e43e10SAndras Olah 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
270607e43e10SAndras Olah 				tp->rcv_scale = tp->request_r_scale;
2707464fcfbcSAndre Oppermann 				/* Send window already scaled. */
270807e43e10SAndras Olah 			}
2709a0292f23SGarrett Wollman 		}
2710a0292f23SGarrett Wollman 
2711a0292f23SGarrett Wollman process_ACK:
27128501a69cSRobert Watson 		INP_WLOCK_ASSERT(tp->t_inpcb);
27137cfc6904SRobert Watson 
2714b2ade6b1SRichard Scheffenegger 		/*
2715b2ade6b1SRichard Scheffenegger 		 * Adjust for the SYN bit in sequence space,
2716b2ade6b1SRichard Scheffenegger 		 * but don't account for it in cwnd calculations.
2717b2ade6b1SRichard Scheffenegger 		 * This is for the SYN_RECEIVED, non-simultaneous
2718b2ade6b1SRichard Scheffenegger 		 * SYN case. SYN_SENT and simultaneous SYN are
2719b2ade6b1SRichard Scheffenegger 		 * treated elsewhere.
2720b2ade6b1SRichard Scheffenegger 		 */
2721b2ade6b1SRichard Scheffenegger 		if (incforsyn)
2722b2ade6b1SRichard Scheffenegger 			tp->snd_una++;
2723dbc42409SLawrence Stewart 		acked = BYTES_THIS_ACK(tp, th);
2724b8c2cd15SJonathan T. Looney 		KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2725b8c2cd15SJonathan T. Looney 		    "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2726b8c2cd15SJonathan T. Looney 		    tp->snd_una, th->th_ack, tp, m));
27274b7b743cSLawrence Stewart 		TCPSTAT_ADD(tcps_rcvackpack, nsegs);
272878b50714SRobert Watson 		TCPSTAT_ADD(tcps_rcvackbyte, acked);
2729df8bae1dSRodney W. Grimes 
2730df8bae1dSRodney W. Grimes 		/*
27319b8b58e0SJonathan Lemon 		 * If we just performed our first retransmit, and the ACK
27329b8b58e0SJonathan Lemon 		 * arrives within our recovery window, then it was a mistake
27339b8b58e0SJonathan Lemon 		 * to do the retransmit in the first place.  Recover our
27349b8b58e0SJonathan Lemon 		 * original cwnd and ssthresh, and proceed to transmit where
27359b8b58e0SJonathan Lemon 		 * we left off.
27369b8b58e0SJonathan Lemon 		 */
273710d20c84SMatt Macy 		if (tp->t_rxtshift == 1 &&
273810d20c84SMatt Macy 		    tp->t_flags & TF_PREVVALID &&
273910d20c84SMatt Macy 		    tp->t_badrxtwin &&
274010d20c84SMatt Macy 		    SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
2741dbc42409SLawrence Stewart 			cc_cong_signal(tp, th, CC_RTO_ERR);
27429b8b58e0SJonathan Lemon 
27439b8b58e0SJonathan Lemon 		/*
2744df8bae1dSRodney W. Grimes 		 * If we have a timestamp reply, update smoothed
2745df8bae1dSRodney W. Grimes 		 * round trip time.  If no timestamp is present but
2746df8bae1dSRodney W. Grimes 		 * transmit timer is running and timed sequence
2747df8bae1dSRodney W. Grimes 		 * number was acked, update smoothed round trip time.
2748df8bae1dSRodney W. Grimes 		 * Since we now have an rtt measurement, cancel the
2749df8bae1dSRodney W. Grimes 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2750df8bae1dSRodney W. Grimes 		 * Recompute the initial retransmit timer.
2751fa55172bSMatthew Dillon 		 *
2752fa55172bSMatthew Dillon 		 * Some boxes send broken timestamp replies
2753fa55172bSMatthew Dillon 		 * during the SYN+ACK phase, ignore
2754fa55172bSMatthew Dillon 		 * timestamps of 0 or we could calculate a
2755fa55172bSMatthew Dillon 		 * huge RTT and blow up the retransmit timer.
2756df8bae1dSRodney W. Grimes 		 */
2757d8951c8aSBjoern A. Zeeb 		if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
27583ac12506SJonathan T. Looney 			uint32_t t;
2759d8951c8aSBjoern A. Zeeb 
2760d8951c8aSBjoern A. Zeeb 			t = tcp_ts_getticks() - to.to_tsecr;
2761d8951c8aSBjoern A. Zeeb 			if (!tp->t_rttlow || tp->t_rttlow > t)
2762d8951c8aSBjoern A. Zeeb 				tp->t_rttlow = t;
2763d8951c8aSBjoern A. Zeeb 			tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2764fa55172bSMatthew Dillon 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2765eaf80179SAndre Oppermann 			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2766eaf80179SAndre Oppermann 				tp->t_rttlow = ticks - tp->t_rtttime;
27679b8b58e0SJonathan Lemon 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2768fa55172bSMatthew Dillon 		}
2769df8bae1dSRodney W. Grimes 
2770df8bae1dSRodney W. Grimes 		/*
2771df8bae1dSRodney W. Grimes 		 * If all outstanding data is acked, stop retransmit
2772df8bae1dSRodney W. Grimes 		 * timer and remember to restart (more output or persist).
2773df8bae1dSRodney W. Grimes 		 * If there is more data to be acked, restart retransmit
2774df8bae1dSRodney W. Grimes 		 * timer, using current (possibly backed-off) value.
2775df8bae1dSRodney W. Grimes 		 */
2776fb59c426SYoshinobu Inoue 		if (th->th_ack == tp->snd_max) {
2777b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
2778df8bae1dSRodney W. Grimes 			needoutput = 1;
2779b8152ba7SAndre Oppermann 		} else if (!tcp_timer_active(tp, TT_PERSIST))
2780b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2781a0292f23SGarrett Wollman 
2782a0292f23SGarrett Wollman 		/*
2783a0292f23SGarrett Wollman 		 * If no data (only SYN) was ACK'd,
2784a0292f23SGarrett Wollman 		 *    skip rest of ACK processing.
2785a0292f23SGarrett Wollman 		 */
2786a0292f23SGarrett Wollman 		if (acked == 0)
2787a0292f23SGarrett Wollman 			goto step6;
2788a0292f23SGarrett Wollman 
2789df8bae1dSRodney W. Grimes 		/*
2790dbc42409SLawrence Stewart 		 * Let the congestion control algorithm update congestion
2791dbc42409SLawrence Stewart 		 * control related information. This typically means increasing
2792dbc42409SLawrence Stewart 		 * the congestion window.
2793df8bae1dSRodney W. Grimes 		 */
27944b7b743cSLawrence Stewart 		cc_ack_received(tp, th, nsegs, CC_ACK);
2795dbc42409SLawrence Stewart 
27965905999bSRobert Watson 		SOCKBUF_LOCK(&so->so_snd);
2797cfa6009eSGleb Smirnoff 		if (acked > sbavail(&so->so_snd)) {
2798b8c2cd15SJonathan T. Looney 			if (tp->snd_wnd >= sbavail(&so->so_snd))
2799cfa6009eSGleb Smirnoff 				tp->snd_wnd -= sbavail(&so->so_snd);
2800b8c2cd15SJonathan T. Looney 			else
2801b8c2cd15SJonathan T. Looney 				tp->snd_wnd = 0;
2802c11a15bfSGleb Smirnoff 			mfree = sbcut_locked(&so->so_snd,
2803cfa6009eSGleb Smirnoff 			    (int)sbavail(&so->so_snd));
2804df8bae1dSRodney W. Grimes 			ourfinisacked = 1;
2805df8bae1dSRodney W. Grimes 		} else {
2806c11a15bfSGleb Smirnoff 			mfree = sbcut_locked(&so->so_snd, acked);
28073ac12506SJonathan T. Looney 			if (tp->snd_wnd >= (uint32_t) acked)
280860ee3bb2SAndre Oppermann 				tp->snd_wnd -= acked;
2809b8c2cd15SJonathan T. Looney 			else
2810b8c2cd15SJonathan T. Looney 				tp->snd_wnd = 0;
2811df8bae1dSRodney W. Grimes 			ourfinisacked = 0;
2812df8bae1dSRodney W. Grimes 		}
2813564aab1fSAndre Oppermann 		/* NB: sowwakeup_locked() does an implicit unlock. */
28141e4d7da7SRobert Watson 		sowwakeup_locked(so);
2815c11a15bfSGleb Smirnoff 		m_freem(mfree);
2816e8949f74SAndre Oppermann 		/* Detect una wraparound. */
2817dbc42409SLawrence Stewart 		if (!IN_RECOVERY(tp->t_flags) &&
28189d11646dSJeffrey Hsu 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
28199d11646dSJeffrey Hsu 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
28209d11646dSJeffrey Hsu 			tp->snd_recover = th->th_ack - 1;
2821dbc42409SLawrence Stewart 		/* XXXLAS: Can this be moved up into cc_post_recovery? */
2822dbc42409SLawrence Stewart 		if (IN_RECOVERY(tp->t_flags) &&
282324cb0f22SLawrence Stewart 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2824dbc42409SLawrence Stewart 			EXIT_RECOVERY(tp->t_flags);
282524cb0f22SLawrence Stewart 		}
2826fb59c426SYoshinobu Inoue 		tp->snd_una = th->th_ack;
28273529149eSAndre Oppermann 		if (tp->t_flags & TF_SACK_PERMIT) {
28286d90faf3SPaul Saab 			if (SEQ_GT(tp->snd_una, tp->snd_recover))
28296d90faf3SPaul Saab 				tp->snd_recover = tp->snd_una;
28306d90faf3SPaul Saab 		}
2831df8bae1dSRodney W. Grimes 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2832df8bae1dSRodney W. Grimes 			tp->snd_nxt = tp->snd_una;
2833df8bae1dSRodney W. Grimes 
2834df8bae1dSRodney W. Grimes 		switch (tp->t_state) {
2835df8bae1dSRodney W. Grimes 
2836df8bae1dSRodney W. Grimes 		/*
2837df8bae1dSRodney W. Grimes 		 * In FIN_WAIT_1 STATE in addition to the processing
2838df8bae1dSRodney W. Grimes 		 * for the ESTABLISHED state if our FIN is now acknowledged
2839df8bae1dSRodney W. Grimes 		 * then enter FIN_WAIT_2.
2840df8bae1dSRodney W. Grimes 		 */
2841df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_1:
2842df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
2843df8bae1dSRodney W. Grimes 				/*
2844df8bae1dSRodney W. Grimes 				 * If we can't receive any more
2845df8bae1dSRodney W. Grimes 				 * data, then closing user can proceed.
2846df8bae1dSRodney W. Grimes 				 * Starting the timer is contrary to the
2847df8bae1dSRodney W. Grimes 				 * specification, but if we don't get a FIN
2848df8bae1dSRodney W. Grimes 				 * we'll hang forever.
2849e8949f74SAndre Oppermann 				 *
2850e8949f74SAndre Oppermann 				 * XXXjl:
2851340c35deSJonathan Lemon 				 * we should release the tp also, and use a
2852340c35deSJonathan Lemon 				 * compressed state.
2853340c35deSJonathan Lemon 				 */
2854c0b99ffaSRobert Watson 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
285503e49181SSeigo Tanimura 					soisdisconnected(so);
28569077f387SGleb Smirnoff 					tcp_timer_activate(tp, TT_2MSL,
28579077f387SGleb Smirnoff 					    (tcp_fast_finwait2_recycle ?
28589077f387SGleb Smirnoff 					    tcp_finwait2_timeout :
28599077f387SGleb Smirnoff 					    TP_MAXIDLE(tp)));
28604cc20ab1SSeigo Tanimura 				}
286157f60867SMark Johnston 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
2862df8bae1dSRodney W. Grimes 			}
2863df8bae1dSRodney W. Grimes 			break;
2864df8bae1dSRodney W. Grimes 
2865df8bae1dSRodney W. Grimes 		/*
2866df8bae1dSRodney W. Grimes 		 * In CLOSING STATE in addition to the processing for
2867df8bae1dSRodney W. Grimes 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2868df8bae1dSRodney W. Grimes 		 * then enter the TIME-WAIT state, otherwise ignore
2869df8bae1dSRodney W. Grimes 		 * the segment.
2870df8bae1dSRodney W. Grimes 		 */
2871df8bae1dSRodney W. Grimes 		case TCPS_CLOSING:
2872df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
287311a20fb8SJeffrey Hsu 				tcp_twstart(tp);
2874340c35deSJonathan Lemon 				m_freem(m);
2875679d9708SAndre Oppermann 				return;
2876df8bae1dSRodney W. Grimes 			}
2877df8bae1dSRodney W. Grimes 			break;
2878df8bae1dSRodney W. Grimes 
2879df8bae1dSRodney W. Grimes 		/*
2880df8bae1dSRodney W. Grimes 		 * In LAST_ACK, we may still be waiting for data to drain
2881df8bae1dSRodney W. Grimes 		 * and/or to be acked, as well as for the ack of our FIN.
2882df8bae1dSRodney W. Grimes 		 * If our FIN is now acknowledged, delete the TCB,
2883df8bae1dSRodney W. Grimes 		 * enter the closed state and return.
2884df8bae1dSRodney W. Grimes 		 */
2885df8bae1dSRodney W. Grimes 		case TCPS_LAST_ACK:
2886df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
2887df8bae1dSRodney W. Grimes 				tp = tcp_close(tp);
2888df8bae1dSRodney W. Grimes 				goto drop;
2889df8bae1dSRodney W. Grimes 			}
2890df8bae1dSRodney W. Grimes 			break;
2891df8bae1dSRodney W. Grimes 		}
2892df8bae1dSRodney W. Grimes 	}
2893df8bae1dSRodney W. Grimes 
2894df8bae1dSRodney W. Grimes step6:
28958501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
28967cfc6904SRobert Watson 
2897df8bae1dSRodney W. Grimes 	/*
289860ee3bb2SAndre Oppermann 	 * Update window information.
289960ee3bb2SAndre Oppermann 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2900df8bae1dSRodney W. Grimes 	 */
290160ee3bb2SAndre Oppermann 	if ((thflags & TH_ACK) &&
290260ee3bb2SAndre Oppermann 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
290360ee3bb2SAndre Oppermann 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
290460ee3bb2SAndre Oppermann 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
290560ee3bb2SAndre Oppermann 		/* keep track of pure window updates */
290660ee3bb2SAndre Oppermann 		if (tlen == 0 &&
290760ee3bb2SAndre Oppermann 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
290878b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvwinupd);
2909df8bae1dSRodney W. Grimes 		tp->snd_wnd = tiwin;
291060ee3bb2SAndre Oppermann 		tp->snd_wl1 = th->th_seq;
291160ee3bb2SAndre Oppermann 		tp->snd_wl2 = th->th_ack;
2912df8bae1dSRodney W. Grimes 		if (tp->snd_wnd > tp->max_sndwnd)
2913df8bae1dSRodney W. Grimes 			tp->max_sndwnd = tp->snd_wnd;
291460ee3bb2SAndre Oppermann 		needoutput = 1;
2915df8bae1dSRodney W. Grimes 	}
2916df8bae1dSRodney W. Grimes 
2917df8bae1dSRodney W. Grimes 	/*
2918df8bae1dSRodney W. Grimes 	 * Process segments with URG.
2919df8bae1dSRodney W. Grimes 	 */
2920fb59c426SYoshinobu Inoue 	if ((thflags & TH_URG) && th->th_urp &&
2921df8bae1dSRodney W. Grimes 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2922df8bae1dSRodney W. Grimes 		/*
2923df8bae1dSRodney W. Grimes 		 * This is a kludge, but if we receive and accept
2924df8bae1dSRodney W. Grimes 		 * random urgent pointers, we'll crash in
2925df8bae1dSRodney W. Grimes 		 * soreceive.  It's hard to imagine someone
2926df8bae1dSRodney W. Grimes 		 * actually wanting to send this much urgent data.
2927df8bae1dSRodney W. Grimes 		 */
292818ad5842SRobert Watson 		SOCKBUF_LOCK(&so->so_rcv);
2929cfa6009eSGleb Smirnoff 		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2930fb59c426SYoshinobu Inoue 			th->th_urp = 0;			/* XXX */
2931fb59c426SYoshinobu Inoue 			thflags &= ~TH_URG;		/* XXX */
293218ad5842SRobert Watson 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
2933df8bae1dSRodney W. Grimes 			goto dodata;			/* XXX */
2934df8bae1dSRodney W. Grimes 		}
2935df8bae1dSRodney W. Grimes 		/*
2936df8bae1dSRodney W. Grimes 		 * If this segment advances the known urgent pointer,
2937df8bae1dSRodney W. Grimes 		 * then mark the data stream.  This should not happen
2938df8bae1dSRodney W. Grimes 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2939df8bae1dSRodney W. Grimes 		 * a FIN has been received from the remote side.
2940df8bae1dSRodney W. Grimes 		 * In these states we ignore the URG.
2941df8bae1dSRodney W. Grimes 		 *
2942df8bae1dSRodney W. Grimes 		 * According to RFC961 (Assigned Protocols),
2943df8bae1dSRodney W. Grimes 		 * the urgent pointer points to the last octet
2944df8bae1dSRodney W. Grimes 		 * of urgent data.  We continue, however,
2945df8bae1dSRodney W. Grimes 		 * to consider it to indicate the first octet
2946df8bae1dSRodney W. Grimes 		 * of data past the urgent section as the original
2947df8bae1dSRodney W. Grimes 		 * spec states (in one of two places).
2948df8bae1dSRodney W. Grimes 		 */
2949fb59c426SYoshinobu Inoue 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2950fb59c426SYoshinobu Inoue 			tp->rcv_up = th->th_seq + th->th_urp;
2951cfa6009eSGleb Smirnoff 			so->so_oobmark = sbavail(&so->so_rcv) +
2952df8bae1dSRodney W. Grimes 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2953927c5ceaSRobert Watson 			if (so->so_oobmark == 0)
2954c0b99ffaSRobert Watson 				so->so_rcv.sb_state |= SBS_RCVATMARK;
2955df8bae1dSRodney W. Grimes 			sohasoutofband(so);
2956df8bae1dSRodney W. Grimes 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2957df8bae1dSRodney W. Grimes 		}
295818ad5842SRobert Watson 		SOCKBUF_UNLOCK(&so->so_rcv);
2959df8bae1dSRodney W. Grimes 		/*
2960df8bae1dSRodney W. Grimes 		 * Remove out of band data so doesn't get presented to user.
2961df8bae1dSRodney W. Grimes 		 * This can happen independent of advancing the URG pointer,
2962df8bae1dSRodney W. Grimes 		 * but if two URG's are pending at once, some out-of-band
2963df8bae1dSRodney W. Grimes 		 * data may creep in... ick.
2964df8bae1dSRodney W. Grimes 		 */
29653ac12506SJonathan T. Looney 		if (th->th_urp <= (uint32_t)tlen &&
296630613f56SJeffrey Hsu 		    !(so->so_options & SO_OOBINLINE)) {
296730613f56SJeffrey Hsu 			/* hdr drop is delayed */
296830613f56SJeffrey Hsu 			tcp_pulloutofband(so, th, m, drop_hdrlen);
296930613f56SJeffrey Hsu 		}
2970c068736aSJeffrey Hsu 	} else {
2971df8bae1dSRodney W. Grimes 		/*
2972df8bae1dSRodney W. Grimes 		 * If no out of band data is expected,
2973df8bae1dSRodney W. Grimes 		 * pull receive urgent pointer along
2974df8bae1dSRodney W. Grimes 		 * with the receive window.
2975df8bae1dSRodney W. Grimes 		 */
2976df8bae1dSRodney W. Grimes 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2977df8bae1dSRodney W. Grimes 			tp->rcv_up = tp->rcv_nxt;
2978c068736aSJeffrey Hsu 	}
2979df8bae1dSRodney W. Grimes dodata:							/* XXX */
29808501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
29817cfc6904SRobert Watson 
2982df8bae1dSRodney W. Grimes 	/*
2983df8bae1dSRodney W. Grimes 	 * Process the segment text, merging it into the TCP sequencing queue,
2984df8bae1dSRodney W. Grimes 	 * and arranging for acknowledgment of receipt if necessary.
2985df8bae1dSRodney W. Grimes 	 * This process logically involves adjusting tp->rcv_wnd as data
2986df8bae1dSRodney W. Grimes 	 * is presented to the user (this happens in tcp_usrreq.c,
2987df8bae1dSRodney W. Grimes 	 * case PRU_RCVD).  If a FIN has already been received on this
2988df8bae1dSRodney W. Grimes 	 * connection then we just ignore the text.
2989df8bae1dSRodney W. Grimes 	 */
2990281a0fd4SPatrick Kelsey 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
299168bd7ed1SJonathan T. Looney 		   IS_FASTOPEN(tp->t_flags));
2992*f1ea4e41SRandall Stewart 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
2993df8bae1dSRodney W. Grimes 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
299469e03620SPaul Saab 		tcp_seq save_start = th->th_seq;
29955acfd95cSMichael Tuexen 		tcp_seq save_rnxt  = tp->rcv_nxt;
29965acfd95cSMichael Tuexen 		int     save_tlen  = tlen;
2997fb59c426SYoshinobu Inoue 		m_adj(m, drop_hdrlen);	/* delayed header drop */
2998e4b64281SJesper Skriver 		/*
2999c068736aSJeffrey Hsu 		 * Insert segment which includes th into TCP reassembly queue
3000c068736aSJeffrey Hsu 		 * with control block tp.  Set thflags to whether reassembly now
3001c068736aSJeffrey Hsu 		 * includes a segment with FIN.  This handles the common case
3002c068736aSJeffrey Hsu 		 * inline (segment is the next to be received on an established
3003c068736aSJeffrey Hsu 		 * connection, and the queue is empty), avoiding linkage into
3004c068736aSJeffrey Hsu 		 * and removal from the queue and repetition of various
3005c068736aSJeffrey Hsu 		 * conversions.
3006c068736aSJeffrey Hsu 		 * Set DELACK for segments received in order, but ack
3007c068736aSJeffrey Hsu 		 * immediately when segments are out of order (so
3008c068736aSJeffrey Hsu 		 * fast retransmit can work).
3009e4b64281SJesper Skriver 		 */
30104741bfcbSPatrick Kelsey 		if (th->th_seq == tp->rcv_nxt &&
3011c28440dbSRandall Stewart 		    SEGQ_EMPTY(tp) &&
3012281a0fd4SPatrick Kelsey 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
3013281a0fd4SPatrick Kelsey 		     tfo_syn)) {
3014281a0fd4SPatrick Kelsey 			if (DELAY_ACK(tp, tlen) || tfo_syn)
30153bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
3016e4b64281SJesper Skriver 			else
3017e4b64281SJesper Skriver 				tp->t_flags |= TF_ACKNOW;
3018e4b64281SJesper Skriver 			tp->rcv_nxt += tlen;
3019e4b64281SJesper Skriver 			thflags = th->th_flags & TH_FIN;
302078b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpack);
302178b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
30221e4d7da7SRobert Watson 			SOCKBUF_LOCK(&so->so_rcv);
3023c0b99ffaSRobert Watson 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3024c1c36a2cSMike Silbersack 				m_freem(m);
3025c1c36a2cSMike Silbersack 			else
3026651e4e6aSGleb Smirnoff 				sbappendstream_locked(&so->so_rcv, m, 0);
3027e8949f74SAndre Oppermann 			/* NB: sorwakeup_locked() does an implicit unlock. */
30281e4d7da7SRobert Watson 			sorwakeup_locked(so);
3029e4b64281SJesper Skriver 		} else {
3030e8949f74SAndre Oppermann 			/*
3031e8949f74SAndre Oppermann 			 * XXX: Due to the header drop above "th" is
3032e8949f74SAndre Oppermann 			 * theoretically invalid by now.  Fortunately
3033e8949f74SAndre Oppermann 			 * m_adj() doesn't actually frees any mbufs
3034e8949f74SAndre Oppermann 			 * when trimming from the head.
3035e8949f74SAndre Oppermann 			 */
30365acfd95cSMichael Tuexen 			tcp_seq temp = save_start;
30375acfd95cSMichael Tuexen 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
3038e4b64281SJesper Skriver 			tp->t_flags |= TF_ACKNOW;
3039e4b64281SJesper Skriver 		}
30406d261981SMichael Tuexen 		if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) {
30416d261981SMichael Tuexen 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3042b5a154d8SMichael Tuexen 				/*
3043b5a154d8SMichael Tuexen 				 * DSACK actually handled in the fastpath
3044b5a154d8SMichael Tuexen 				 * above.
3045b5a154d8SMichael Tuexen 				 */
3046ecc5b1d1SMichael Tuexen 				tcp_update_sack_list(tp, save_start,
3047ecc5b1d1SMichael Tuexen 				    save_start + save_tlen);
3048ecc5b1d1SMichael Tuexen 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3049ecc5b1d1SMichael Tuexen 				if ((tp->rcv_numsacks >= 1) &&
3050ecc5b1d1SMichael Tuexen 				    (tp->sackblks[0].end == save_start)) {
30516d261981SMichael Tuexen 					/*
30526d261981SMichael Tuexen 					 * Partial overlap, recorded at todrop
30536d261981SMichael Tuexen 					 * above.
30546d261981SMichael Tuexen 					 */
30556d261981SMichael Tuexen 					tcp_update_sack_list(tp,
30566d261981SMichael Tuexen 					    tp->sackblks[0].start,
3057ecc5b1d1SMichael Tuexen 					    tp->sackblks[0].end);
3058ecc5b1d1SMichael Tuexen 				} else {
3059ecc5b1d1SMichael Tuexen 					tcp_update_dsack_list(tp, save_start,
3060ecc5b1d1SMichael Tuexen 					    save_start + save_tlen);
3061ecc5b1d1SMichael Tuexen 				}
30626d261981SMichael Tuexen 			} else if (tlen >= save_tlen) {
3063b5a154d8SMichael Tuexen 				/* Update of sackblks. */
3064ecc5b1d1SMichael Tuexen 				tcp_update_dsack_list(tp, save_start,
3065ecc5b1d1SMichael Tuexen 				    save_start + save_tlen);
3066ecc5b1d1SMichael Tuexen 			} else if (tlen > 0) {
3067ecc5b1d1SMichael Tuexen 				tcp_update_dsack_list(tp, save_start,
3068ecc5b1d1SMichael Tuexen 				    save_start + tlen);
30695acfd95cSMichael Tuexen 			}
30705acfd95cSMichael Tuexen 		}
3071302ce8d6SAndre Oppermann #if 0
3072df8bae1dSRodney W. Grimes 		/*
3073df8bae1dSRodney W. Grimes 		 * Note the amount of data that peer has sent into
3074df8bae1dSRodney W. Grimes 		 * our window, in order to estimate the sender's
3075df8bae1dSRodney W. Grimes 		 * buffer size.
3076302ce8d6SAndre Oppermann 		 * XXX: Unused.
3077df8bae1dSRodney W. Grimes 		 */
3078f701e30dSJohn Baldwin 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3079df8bae1dSRodney W. Grimes 			len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3080f701e30dSJohn Baldwin 		else
3081f701e30dSJohn Baldwin 			len = so->so_rcv.sb_hiwat;
3082302ce8d6SAndre Oppermann #endif
3083df8bae1dSRodney W. Grimes 	} else {
3084df8bae1dSRodney W. Grimes 		m_freem(m);
3085fb59c426SYoshinobu Inoue 		thflags &= ~TH_FIN;
3086df8bae1dSRodney W. Grimes 	}
3087df8bae1dSRodney W. Grimes 
3088df8bae1dSRodney W. Grimes 	/*
3089df8bae1dSRodney W. Grimes 	 * If FIN is received ACK the FIN and let the user know
3090df8bae1dSRodney W. Grimes 	 * that the connection is closing.
3091df8bae1dSRodney W. Grimes 	 */
3092fb59c426SYoshinobu Inoue 	if (thflags & TH_FIN) {
3093df8bae1dSRodney W. Grimes 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3094df8bae1dSRodney W. Grimes 			socantrcvmore(so);
3095a0292f23SGarrett Wollman 			/*
3096a0292f23SGarrett Wollman 			 * If connection is half-synchronized
3097d3eede9dSAndras Olah 			 * (ie NEEDSYN flag on) then delay ACK,
3098a0292f23SGarrett Wollman 			 * so it may be piggybacked when SYN is sent.
3099a0292f23SGarrett Wollman 			 * Otherwise, since we received a FIN then no
3100a0292f23SGarrett Wollman 			 * more input can be expected, send ACK now.
3101a0292f23SGarrett Wollman 			 */
31023bfd6421SJonathan Lemon 			if (tp->t_flags & TF_NEEDSYN)
31033bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
3104a0292f23SGarrett Wollman 			else
3105df8bae1dSRodney W. Grimes 				tp->t_flags |= TF_ACKNOW;
3106df8bae1dSRodney W. Grimes 			tp->rcv_nxt++;
3107df8bae1dSRodney W. Grimes 		}
3108df8bae1dSRodney W. Grimes 		switch (tp->t_state) {
3109df8bae1dSRodney W. Grimes 
3110df8bae1dSRodney W. Grimes 		/*
3111df8bae1dSRodney W. Grimes 		 * In SYN_RECEIVED and ESTABLISHED STATES
3112df8bae1dSRodney W. Grimes 		 * enter the CLOSE_WAIT state.
3113df8bae1dSRodney W. Grimes 		 */
3114df8bae1dSRodney W. Grimes 		case TCPS_SYN_RECEIVED:
31159b8b58e0SJonathan Lemon 			tp->t_starttime = ticks;
31169b8b58e0SJonathan Lemon 			/* FALLTHROUGH */
3117df8bae1dSRodney W. Grimes 		case TCPS_ESTABLISHED:
311857f60867SMark Johnston 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
3119df8bae1dSRodney W. Grimes 			break;
3120df8bae1dSRodney W. Grimes 
3121df8bae1dSRodney W. Grimes 		/*
3122df8bae1dSRodney W. Grimes 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3123df8bae1dSRodney W. Grimes 		 * enter the CLOSING state.
3124df8bae1dSRodney W. Grimes 		 */
3125df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_1:
312657f60867SMark Johnston 			tcp_state_change(tp, TCPS_CLOSING);
3127df8bae1dSRodney W. Grimes 			break;
3128df8bae1dSRodney W. Grimes 
3129df8bae1dSRodney W. Grimes 		/*
3130df8bae1dSRodney W. Grimes 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3131df8bae1dSRodney W. Grimes 		 * starting the time-wait timer, turning off the other
3132df8bae1dSRodney W. Grimes 		 * standard timers.
3133df8bae1dSRodney W. Grimes 		 */
3134df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_2:
3135340c35deSJonathan Lemon 			tcp_twstart(tp);
3136679d9708SAndre Oppermann 			return;
3137df8bae1dSRodney W. Grimes 		}
3138df8bae1dSRodney W. Grimes 	}
3139610ee2f9SDavid Greenman #ifdef TCPDEBUG
31404cc20ab1SSeigo Tanimura 	if (so->so_options & SO_DEBUG)
3141fb59c426SYoshinobu Inoue 		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3142fb59c426SYoshinobu Inoue 			  &tcp_savetcp, 0);
3143610ee2f9SDavid Greenman #endif
31442b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
3145df8bae1dSRodney W. Grimes 
3146df8bae1dSRodney W. Grimes 	/*
3147df8bae1dSRodney W. Grimes 	 * Return any desired output.
3148df8bae1dSRodney W. Grimes 	 */
3149df8bae1dSRodney W. Grimes 	if (needoutput || (tp->t_flags & TF_ACKNOW))
315055bceb1eSRandall Stewart 		(void) tp->t_fb->tfb_tcp_output(tp);
31517792ea27SJeffrey Hsu 
3152a14c749fSJonathan Lemon check_delack:
31538501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
3154252ca428SRobert Watson 
3155a14c749fSJonathan Lemon 	if (tp->t_flags & TF_DELACK) {
31563bfd6421SJonathan Lemon 		tp->t_flags &= ~TF_DELACK;
3157b8152ba7SAndre Oppermann 		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
31583bfd6421SJonathan Lemon 	}
31598501a69cSRobert Watson 	INP_WUNLOCK(tp->t_inpcb);
3160679d9708SAndre Oppermann 	return;
3161df8bae1dSRodney W. Grimes 
3162df8bae1dSRodney W. Grimes dropafterack:
3163df8bae1dSRodney W. Grimes 	/*
3164df8bae1dSRodney W. Grimes 	 * Generate an ACK dropping incoming segment if it occupies
3165df8bae1dSRodney W. Grimes 	 * sequence space, where the ACK reflects our state.
316680ab7c0eSGarrett Wollman 	 *
316780ab7c0eSGarrett Wollman 	 * We can now skip the test for the RST flag since all
316880ab7c0eSGarrett Wollman 	 * paths to this code happen after packets containing
316980ab7c0eSGarrett Wollman 	 * RST have been dropped.
317080ab7c0eSGarrett Wollman 	 *
317180ab7c0eSGarrett Wollman 	 * In the SYN-RECEIVED state, don't send an ACK unless the
317280ab7c0eSGarrett Wollman 	 * segment we received passes the SYN-RECEIVED ACK test.
317380ab7c0eSGarrett Wollman 	 * If it fails send a RST.  This breaks the loop in the
317480ab7c0eSGarrett Wollman 	 * "LAND" DoS attack, and also prevents an ACK storm
317580ab7c0eSGarrett Wollman 	 * between two listening ports that have been sent forged
317680ab7c0eSGarrett Wollman 	 * SYN segments, each with the source address of the other.
3177df8bae1dSRodney W. Grimes 	 */
3178fb59c426SYoshinobu Inoue 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3179fb59c426SYoshinobu Inoue 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
3180a57815efSBosko Milekic 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
3181a57815efSBosko Milekic 		rstreason = BANDLIM_RST_OPENPORT;
3182a57815efSBosko Milekic 		goto dropwithreset;
3183a57815efSBosko Milekic 	}
3184a0292f23SGarrett Wollman #ifdef TCPDEBUG
31854cc20ab1SSeigo Tanimura 	if (so->so_options & SO_DEBUG)
3186fb59c426SYoshinobu Inoue 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3187fb59c426SYoshinobu Inoue 			  &tcp_savetcp, 0);
3188a0292f23SGarrett Wollman #endif
31892b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
3190df8bae1dSRodney W. Grimes 	tp->t_flags |= TF_ACKNOW;
319155bceb1eSRandall Stewart 	(void) tp->t_fb->tfb_tcp_output(tp);
31928501a69cSRobert Watson 	INP_WUNLOCK(tp->t_inpcb);
3193d6915262SRobert Watson 	m_freem(m);
3194679d9708SAndre Oppermann 	return;
3195df8bae1dSRodney W. Grimes 
3196df8bae1dSRodney W. Grimes dropwithreset:
3197a0ca0871SRobert Watson 	if (tp != NULL) {
3198302ce8d6SAndre Oppermann 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
31998501a69cSRobert Watson 		INP_WUNLOCK(tp->t_inpcb);
3200dd8ac7f9SRobert Watson 	} else
3201a0ca0871SRobert Watson 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3202679d9708SAndre Oppermann 	return;
3203df8bae1dSRodney W. Grimes 
3204df8bae1dSRodney W. Grimes drop:
3205df8bae1dSRodney W. Grimes 	/*
3206df8bae1dSRodney W. Grimes 	 * Drop space held by incoming segment and return.
3207df8bae1dSRodney W. Grimes 	 */
3208610ee2f9SDavid Greenman #ifdef TCPDEBUG
32091c53f806SRobert Watson 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3210fb59c426SYoshinobu Inoue 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3211fb59c426SYoshinobu Inoue 			  &tcp_savetcp, 0);
3212a0292f23SGarrett Wollman #endif
32132b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
32141c53f806SRobert Watson 	if (tp != NULL)
32158501a69cSRobert Watson 		INP_WUNLOCK(tp->t_inpcb);
3216d6915262SRobert Watson 	m_freem(m);
3217302ce8d6SAndre Oppermann }
3218302ce8d6SAndre Oppermann 
3219302ce8d6SAndre Oppermann /*
32200ca3f933SAndre Oppermann  * Issue RST and make ACK acceptable to originator of segment.
32210ca3f933SAndre Oppermann  * The mbuf must still include the original packet header.
32220ca3f933SAndre Oppermann  * tp may be NULL.
3223302ce8d6SAndre Oppermann  */
322455bceb1eSRandall Stewart void
3225302ce8d6SAndre Oppermann tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3226302ce8d6SAndre Oppermann     int tlen, int rstreason)
3227302ce8d6SAndre Oppermann {
3228b287c6c7SBjoern A. Zeeb #ifdef INET
3229302ce8d6SAndre Oppermann 	struct ip *ip;
3230b287c6c7SBjoern A. Zeeb #endif
3231302ce8d6SAndre Oppermann #ifdef INET6
3232302ce8d6SAndre Oppermann 	struct ip6_hdr *ip6;
3233302ce8d6SAndre Oppermann #endif
32347a3244ccSRobert Watson 
32357a3244ccSRobert Watson 	if (tp != NULL) {
32368501a69cSRobert Watson 		INP_WLOCK_ASSERT(tp->t_inpcb);
32377a3244ccSRobert Watson 	}
32387a3244ccSRobert Watson 
32390ca3f933SAndre Oppermann 	/* Don't bother if destination was broadcast/multicast. */
3240302ce8d6SAndre Oppermann 	if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3241302ce8d6SAndre Oppermann 		goto drop;
3242302ce8d6SAndre Oppermann #ifdef INET6
3243302ce8d6SAndre Oppermann 	if (mtod(m, struct ip *)->ip_v == 6) {
3244302ce8d6SAndre Oppermann 		ip6 = mtod(m, struct ip6_hdr *);
3245302ce8d6SAndre Oppermann 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3246302ce8d6SAndre Oppermann 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3247302ce8d6SAndre Oppermann 			goto drop;
3248302ce8d6SAndre Oppermann 		/* IPv6 anycast check is done at tcp6_input() */
3249b287c6c7SBjoern A. Zeeb 	}
3250302ce8d6SAndre Oppermann #endif
3251b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3252b287c6c7SBjoern A. Zeeb 	else
3253b287c6c7SBjoern A. Zeeb #endif
3254b287c6c7SBjoern A. Zeeb #ifdef INET
3255302ce8d6SAndre Oppermann 	{
3256302ce8d6SAndre Oppermann 		ip = mtod(m, struct ip *);
3257302ce8d6SAndre Oppermann 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3258302ce8d6SAndre Oppermann 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3259302ce8d6SAndre Oppermann 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3260302ce8d6SAndre Oppermann 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3261302ce8d6SAndre Oppermann 			goto drop;
3262302ce8d6SAndre Oppermann 	}
3263b287c6c7SBjoern A. Zeeb #endif
3264302ce8d6SAndre Oppermann 
3265302ce8d6SAndre Oppermann 	/* Perform bandwidth limiting. */
3266302ce8d6SAndre Oppermann 	if (badport_bandlim(rstreason) < 0)
3267302ce8d6SAndre Oppermann 		goto drop;
3268302ce8d6SAndre Oppermann 
3269302ce8d6SAndre Oppermann 	/* tcp_respond consumes the mbuf chain. */
3270302ce8d6SAndre Oppermann 	if (th->th_flags & TH_ACK) {
3271302ce8d6SAndre Oppermann 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3272302ce8d6SAndre Oppermann 		    th->th_ack, TH_RST);
3273302ce8d6SAndre Oppermann 	} else {
3274302ce8d6SAndre Oppermann 		if (th->th_flags & TH_SYN)
3275302ce8d6SAndre Oppermann 			tlen++;
32764ddd5aadSMichael Tuexen 		if (th->th_flags & TH_FIN)
32774ddd5aadSMichael Tuexen 			tlen++;
3278302ce8d6SAndre Oppermann 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3279302ce8d6SAndre Oppermann 		    (tcp_seq)0, TH_RST|TH_ACK);
3280302ce8d6SAndre Oppermann 	}
3281302ce8d6SAndre Oppermann 	return;
3282302ce8d6SAndre Oppermann drop:
3283302ce8d6SAndre Oppermann 	m_freem(m);
3284df8bae1dSRodney W. Grimes }
3285df8bae1dSRodney W. Grimes 
3286be2ac88cSJonathan Lemon /*
3287be2ac88cSJonathan Lemon  * Parse TCP options and place in tcpopt.
3288be2ac88cSJonathan Lemon  */
328955bceb1eSRandall Stewart void
3290ad3f9ab3SAndre Oppermann tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3291df8bae1dSRodney W. Grimes {
3292df8bae1dSRodney W. Grimes 	int opt, optlen;
3293df8bae1dSRodney W. Grimes 
3294be2ac88cSJonathan Lemon 	to->to_flags = 0;
3295df8bae1dSRodney W. Grimes 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
3296df8bae1dSRodney W. Grimes 		opt = cp[0];
3297df8bae1dSRodney W. Grimes 		if (opt == TCPOPT_EOL)
3298df8bae1dSRodney W. Grimes 			break;
3299df8bae1dSRodney W. Grimes 		if (opt == TCPOPT_NOP)
3300df8bae1dSRodney W. Grimes 			optlen = 1;
3301df8bae1dSRodney W. Grimes 		else {
3302b474779fSJun-ichiro itojun Hagino 			if (cnt < 2)
3303b474779fSJun-ichiro itojun Hagino 				break;
3304df8bae1dSRodney W. Grimes 			optlen = cp[1];
3305b474779fSJun-ichiro itojun Hagino 			if (optlen < 2 || optlen > cnt)
3306df8bae1dSRodney W. Grimes 				break;
3307df8bae1dSRodney W. Grimes 		}
3308df8bae1dSRodney W. Grimes 		switch (opt) {
3309df8bae1dSRodney W. Grimes 		case TCPOPT_MAXSEG:
3310df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_MAXSEG)
3311df8bae1dSRodney W. Grimes 				continue;
3312f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3313df8bae1dSRodney W. Grimes 				continue;
3314be2ac88cSJonathan Lemon 			to->to_flags |= TOF_MSS;
3315be2ac88cSJonathan Lemon 			bcopy((char *)cp + 2,
3316be2ac88cSJonathan Lemon 			    (char *)&to->to_mss, sizeof(to->to_mss));
3317fd8e4ebcSMike Barcroft 			to->to_mss = ntohs(to->to_mss);
3318df8bae1dSRodney W. Grimes 			break;
3319df8bae1dSRodney W. Grimes 		case TCPOPT_WINDOW:
3320df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_WINDOW)
3321df8bae1dSRodney W. Grimes 				continue;
3322f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3323df8bae1dSRodney W. Grimes 				continue;
3324be2ac88cSJonathan Lemon 			to->to_flags |= TOF_SCALE;
332502a1a643SAndre Oppermann 			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3326df8bae1dSRodney W. Grimes 			break;
3327df8bae1dSRodney W. Grimes 		case TCPOPT_TIMESTAMP:
3328df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_TIMESTAMP)
3329df8bae1dSRodney W. Grimes 				continue;
3330be2ac88cSJonathan Lemon 			to->to_flags |= TOF_TS;
3331a0292f23SGarrett Wollman 			bcopy((char *)cp + 2,
3332a0292f23SGarrett Wollman 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
3333fd8e4ebcSMike Barcroft 			to->to_tsval = ntohl(to->to_tsval);
3334a0292f23SGarrett Wollman 			bcopy((char *)cp + 6,
3335a0292f23SGarrett Wollman 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3336fd8e4ebcSMike Barcroft 			to->to_tsecr = ntohl(to->to_tsecr);
3337df8bae1dSRodney W. Grimes 			break;
33381cfd4b53SBruce M Simpson 		case TCPOPT_SIGNATURE:
3339fcf59617SAndrey V. Elsukov 			/*
3340fcf59617SAndrey V. Elsukov 			 * In order to reply to a host which has set the
3341fcf59617SAndrey V. Elsukov 			 * TCP_SIGNATURE option in its initial SYN, we have
3342fcf59617SAndrey V. Elsukov 			 * to record the fact that the option was observed
3343fcf59617SAndrey V. Elsukov 			 * here for the syncache code to perform the correct
3344fcf59617SAndrey V. Elsukov 			 * response.
3345fcf59617SAndrey V. Elsukov 			 */
33461cfd4b53SBruce M Simpson 			if (optlen != TCPOLEN_SIGNATURE)
33471cfd4b53SBruce M Simpson 				continue;
3348df47e437SAndre Oppermann 			to->to_flags |= TOF_SIGNATURE;
3349df47e437SAndre Oppermann 			to->to_signature = cp + 2;
33501cfd4b53SBruce M Simpson 			break;
33516d90faf3SPaul Saab 		case TCPOPT_SACK_PERMITTED:
3352f72167f4SAndre Oppermann 			if (optlen != TCPOLEN_SACK_PERMITTED)
33536d90faf3SPaul Saab 				continue;
3354f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3355f72167f4SAndre Oppermann 				continue;
3356603724d3SBjoern A. Zeeb 			if (!V_tcp_do_sack)
3357f72167f4SAndre Oppermann 				continue;
3358fc30a251SAndre Oppermann 			to->to_flags |= TOF_SACKPERM;
33596d90faf3SPaul Saab 			break;
33606d90faf3SPaul Saab 		case TCPOPT_SACK:
33615a53ca16SPaul Saab 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
33626d90faf3SPaul Saab 				continue;
3363b728e902SAndre Oppermann 			if (flags & TO_SYN)
3364b728e902SAndre Oppermann 				continue;
3365fc30a251SAndre Oppermann 			to->to_flags |= TOF_SACK;
33665a53ca16SPaul Saab 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
33675a53ca16SPaul Saab 			to->to_sacks = cp + 2;
336878b50714SRobert Watson 			TCPSTAT_INC(tcps_sack_rcv_blocks);
33696d90faf3SPaul Saab 			break;
3370281a0fd4SPatrick Kelsey 		case TCPOPT_FAST_OPEN:
3371c560df6fSPatrick Kelsey 			/*
3372c560df6fSPatrick Kelsey 			 * Cookie length validation is performed by the
3373c560df6fSPatrick Kelsey 			 * server side cookie checking code or the client
3374c560df6fSPatrick Kelsey 			 * side cookie cache update code.
3375c560df6fSPatrick Kelsey 			 */
3376281a0fd4SPatrick Kelsey 			if (!(flags & TO_SYN))
3377281a0fd4SPatrick Kelsey 				continue;
3378c560df6fSPatrick Kelsey 			if (!V_tcp_fastopen_client_enable &&
3379c560df6fSPatrick Kelsey 			    !V_tcp_fastopen_server_enable)
3380281a0fd4SPatrick Kelsey 				continue;
3381281a0fd4SPatrick Kelsey 			to->to_flags |= TOF_FASTOPEN;
3382281a0fd4SPatrick Kelsey 			to->to_tfo_len = optlen - 2;
3383281a0fd4SPatrick Kelsey 			to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3384281a0fd4SPatrick Kelsey 			break;
3385be2ac88cSJonathan Lemon 		default:
3386be2ac88cSJonathan Lemon 			continue;
3387df8bae1dSRodney W. Grimes 		}
3388df8bae1dSRodney W. Grimes 	}
3389df8bae1dSRodney W. Grimes }
3390df8bae1dSRodney W. Grimes 
3391df8bae1dSRodney W. Grimes /*
3392df8bae1dSRodney W. Grimes  * Pull out of band byte out of a segment so
3393df8bae1dSRodney W. Grimes  * it doesn't appear in the user's data queue.
3394df8bae1dSRodney W. Grimes  * It is still reflected in the segment length for
3395df8bae1dSRodney W. Grimes  * sequencing purposes.
3396df8bae1dSRodney W. Grimes  */
339755bceb1eSRandall Stewart void
3398ad3f9ab3SAndre Oppermann tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3399ad3f9ab3SAndre Oppermann     int off)
3400df8bae1dSRodney W. Grimes {
3401fb59c426SYoshinobu Inoue 	int cnt = off + th->th_urp - 1;
3402df8bae1dSRodney W. Grimes 
3403df8bae1dSRodney W. Grimes 	while (cnt >= 0) {
3404df8bae1dSRodney W. Grimes 		if (m->m_len > cnt) {
3405df8bae1dSRodney W. Grimes 			char *cp = mtod(m, caddr_t) + cnt;
3406df8bae1dSRodney W. Grimes 			struct tcpcb *tp = sototcpcb(so);
3407df8bae1dSRodney W. Grimes 
34088501a69cSRobert Watson 			INP_WLOCK_ASSERT(tp->t_inpcb);
34097a3244ccSRobert Watson 
3410df8bae1dSRodney W. Grimes 			tp->t_iobc = *cp;
3411df8bae1dSRodney W. Grimes 			tp->t_oobflags |= TCPOOB_HAVEDATA;
3412df8bae1dSRodney W. Grimes 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3413df8bae1dSRodney W. Grimes 			m->m_len--;
341469a34685SYoshinobu Inoue 			if (m->m_flags & M_PKTHDR)
341569a34685SYoshinobu Inoue 				m->m_pkthdr.len--;
3416df8bae1dSRodney W. Grimes 			return;
3417df8bae1dSRodney W. Grimes 		}
3418df8bae1dSRodney W. Grimes 		cnt -= m->m_len;
3419df8bae1dSRodney W. Grimes 		m = m->m_next;
34204dfdffe9SAndre Oppermann 		if (m == NULL)
3421df8bae1dSRodney W. Grimes 			break;
3422df8bae1dSRodney W. Grimes 	}
3423df8bae1dSRodney W. Grimes 	panic("tcp_pulloutofband");
3424df8bae1dSRodney W. Grimes }
3425df8bae1dSRodney W. Grimes 
3426df8bae1dSRodney W. Grimes /*
3427df8bae1dSRodney W. Grimes  * Collect new round-trip time estimate
3428df8bae1dSRodney W. Grimes  * and update averages and current timeout.
3429df8bae1dSRodney W. Grimes  */
343055bceb1eSRandall Stewart void
3431ad3f9ab3SAndre Oppermann tcp_xmit_timer(struct tcpcb *tp, int rtt)
3432df8bae1dSRodney W. Grimes {
3433ad3f9ab3SAndre Oppermann 	int delta;
3434233e8c18SGarrett Wollman 
34358501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
34362be3bf22SRobert Watson 
343778b50714SRobert Watson 	TCPSTAT_INC(tcps_rttupdated);
3438233e8c18SGarrett Wollman 	tp->t_rttupdated++;
3439adc56f5aSEdward Tomasz Napierala #ifdef STATS
3440adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT,
3441adc56f5aSEdward Tomasz Napierala 	    imax(0, rtt * 1000 / hz));
3442adc56f5aSEdward Tomasz Napierala #endif
34435ede40dcSRyan Stone 	if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3444233e8c18SGarrett Wollman 		/*
3445233e8c18SGarrett Wollman 		 * srtt is stored as fixed point with 5 bits after the
3446233e8c18SGarrett Wollman 		 * binary point (i.e., scaled by 8).  The following magic
3447233e8c18SGarrett Wollman 		 * is equivalent to the smoothing algorithm in rfc793 with
3448233e8c18SGarrett Wollman 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3449233e8c18SGarrett Wollman 		 * point).  Adjust rtt to origin 0.
3450233e8c18SGarrett Wollman 		 */
3451233e8c18SGarrett Wollman 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3452233e8c18SGarrett Wollman 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3453233e8c18SGarrett Wollman 
3454233e8c18SGarrett Wollman 		if ((tp->t_srtt += delta) <= 0)
3455233e8c18SGarrett Wollman 			tp->t_srtt = 1;
3456233e8c18SGarrett Wollman 
3457233e8c18SGarrett Wollman 		/*
3458233e8c18SGarrett Wollman 		 * We accumulate a smoothed rtt variance (actually, a
3459233e8c18SGarrett Wollman 		 * smoothed mean difference), then set the retransmit
3460233e8c18SGarrett Wollman 		 * timer to smoothed rtt + 4 times the smoothed variance.
3461233e8c18SGarrett Wollman 		 * rttvar is stored as fixed point with 4 bits after the
3462233e8c18SGarrett Wollman 		 * binary point (scaled by 16).  The following is
3463233e8c18SGarrett Wollman 		 * equivalent to rfc793 smoothing with an alpha of .75
3464233e8c18SGarrett Wollman 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
3465233e8c18SGarrett Wollman 		 * rfc793's wired-in beta.
3466233e8c18SGarrett Wollman 		 */
3467233e8c18SGarrett Wollman 		if (delta < 0)
3468233e8c18SGarrett Wollman 			delta = -delta;
3469233e8c18SGarrett Wollman 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3470233e8c18SGarrett Wollman 		if ((tp->t_rttvar += delta) <= 0)
3471233e8c18SGarrett Wollman 			tp->t_rttvar = 1;
34721fcc99b5SMatthew Dillon 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
34731fcc99b5SMatthew Dillon 		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3474233e8c18SGarrett Wollman 	} else {
3475233e8c18SGarrett Wollman 		/*
3476233e8c18SGarrett Wollman 		 * No rtt measurement yet - use the unsmoothed rtt.
3477233e8c18SGarrett Wollman 		 * Set the variance to half the rtt (so our first
3478233e8c18SGarrett Wollman 		 * retransmit happens at 3*rtt).
3479233e8c18SGarrett Wollman 		 */
3480233e8c18SGarrett Wollman 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
3481233e8c18SGarrett Wollman 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
34821fcc99b5SMatthew Dillon 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3483233e8c18SGarrett Wollman 	}
34849b8b58e0SJonathan Lemon 	tp->t_rtttime = 0;
3485df8bae1dSRodney W. Grimes 	tp->t_rxtshift = 0;
3486df8bae1dSRodney W. Grimes 
3487df8bae1dSRodney W. Grimes 	/*
3488df8bae1dSRodney W. Grimes 	 * the retransmit should happen at rtt + 4 * rttvar.
3489df8bae1dSRodney W. Grimes 	 * Because of the way we do the smoothing, srtt and rttvar
3490df8bae1dSRodney W. Grimes 	 * will each average +1/2 tick of bias.  When we compute
3491df8bae1dSRodney W. Grimes 	 * the retransmit timer, we want 1/2 tick of rounding and
3492df8bae1dSRodney W. Grimes 	 * 1 extra tick because of +-1/2 tick uncertainty in the
3493df8bae1dSRodney W. Grimes 	 * firing of the timer.  The bias will give us exactly the
3494df8bae1dSRodney W. Grimes 	 * 1.5 tick we need.  But, because the bias is
3495df8bae1dSRodney W. Grimes 	 * statistical, we have to test that we don't drop below
3496df8bae1dSRodney W. Grimes 	 * the minimum feasible timer (which is 2 ticks).
3497df8bae1dSRodney W. Grimes 	 */
3498233e8c18SGarrett Wollman 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
34999e2874b0SGarrett Wollman 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3500df8bae1dSRodney W. Grimes 
3501df8bae1dSRodney W. Grimes 	/*
3502df8bae1dSRodney W. Grimes 	 * We received an ack for a packet that wasn't retransmitted;
3503df8bae1dSRodney W. Grimes 	 * it is probably safe to discard any error indications we've
3504df8bae1dSRodney W. Grimes 	 * received recently.  This isn't quite right, but close enough
3505df8bae1dSRodney W. Grimes 	 * for now (a route might have failed after we sent a segment,
3506df8bae1dSRodney W. Grimes 	 * and the return path might not be symmetrical).
3507df8bae1dSRodney W. Grimes 	 */
3508df8bae1dSRodney W. Grimes 	tp->t_softerror = 0;
3509df8bae1dSRodney W. Grimes }
3510df8bae1dSRodney W. Grimes 
3511df8bae1dSRodney W. Grimes /*
3512df8bae1dSRodney W. Grimes  * Determine a reasonable value for maxseg size.
3513df8bae1dSRodney W. Grimes  * If the route is known, check route for mtu.
35144faaea55SAndre Oppermann  * If none, use an mss that can be handled on the outgoing interface
35154faaea55SAndre Oppermann  * without forcing IP to fragment.  If no route is found, route has no mtu,
3516df8bae1dSRodney W. Grimes  * or the destination isn't local, use a default, hopefully conservative
3517df8bae1dSRodney W. Grimes  * size (usually 512 or the default IP max size, but no more than the mtu
3518df8bae1dSRodney W. Grimes  * of the interface), as we can't discover anything about intervening
3519df8bae1dSRodney W. Grimes  * gateways or networks.  We also initialize the congestion/slow start
3520df8bae1dSRodney W. Grimes  * window to be a single segment if the destination isn't local.
3521df8bae1dSRodney W. Grimes  * While looking at the routing entry, we also initialize other path-dependent
3522df8bae1dSRodney W. Grimes  * parameters from pre-set or cached values in the routing entry.
3523a0292f23SGarrett Wollman  *
35240c39d38dSGleb Smirnoff  * NOTE that resulting t_maxseg doesn't include space for TCP options or
35250c39d38dSGleb Smirnoff  * IP options, e.g. IPSEC data, since length of this data may vary, and
35260c39d38dSGleb Smirnoff  * thus it is calculated for every segment separately in tcp_output().
3527a0292f23SGarrett Wollman  *
352897d8d152SAndre Oppermann  * NOTE that this routine is only called when we process an incoming
3529ef341ee1SGleb Smirnoff  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3530ef341ee1SGleb Smirnoff  * settings are handled in tcp_mssopt().
3531df8bae1dSRodney W. Grimes  */
3532a0292f23SGarrett Wollman void
3533ef341ee1SGleb Smirnoff tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
35343c914c54SAndre Oppermann     struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3535df8bae1dSRodney W. Grimes {
3536b287c6c7SBjoern A. Zeeb 	int mss = 0;
35373ac12506SJonathan T. Looney 	uint32_t maxmtu = 0;
3538c068736aSJeffrey Hsu 	struct inpcb *inp = tp->t_inpcb;
353997d8d152SAndre Oppermann 	struct hc_metrics_lite metrics;
3540fb59c426SYoshinobu Inoue #ifdef INET6
3541c068736aSJeffrey Hsu 	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3542c068736aSJeffrey Hsu 	size_t min_protoh = isipv6 ?
3543c068736aSJeffrey Hsu 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3544c068736aSJeffrey Hsu 			    sizeof (struct tcpiphdr);
3545c068736aSJeffrey Hsu #else
3546c068736aSJeffrey Hsu 	const size_t min_protoh = sizeof(struct tcpiphdr);
3547fb59c426SYoshinobu Inoue #endif
3548df8bae1dSRodney W. Grimes 
35498501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
35507a3244ccSRobert Watson 
3551ef341ee1SGleb Smirnoff 	if (mtuoffer != -1) {
3552ef341ee1SGleb Smirnoff 		KASSERT(offer == -1, ("%s: conflict", __func__));
3553ef341ee1SGleb Smirnoff 		offer = mtuoffer - min_protoh;
3554ef341ee1SGleb Smirnoff 	}
3555ef341ee1SGleb Smirnoff 
3556e8949f74SAndre Oppermann 	/* Initialize. */
355797d8d152SAndre Oppermann #ifdef INET6
355897d8d152SAndre Oppermann 	if (isipv6) {
35593c914c54SAndre Oppermann 		maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
35600c39d38dSGleb Smirnoff 		tp->t_maxseg = V_tcp_v6mssdflt;
3561b287c6c7SBjoern A. Zeeb 	}
356297d8d152SAndre Oppermann #endif
3563b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3564b287c6c7SBjoern A. Zeeb 	else
3565b287c6c7SBjoern A. Zeeb #endif
3566b287c6c7SBjoern A. Zeeb #ifdef INET
356797d8d152SAndre Oppermann 	{
35683c914c54SAndre Oppermann 		maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
35690c39d38dSGleb Smirnoff 		tp->t_maxseg = V_tcp_mssdflt;
3570df8bae1dSRodney W. Grimes 	}
3571b287c6c7SBjoern A. Zeeb #endif
3572df8bae1dSRodney W. Grimes 
357397d8d152SAndre Oppermann 	/*
3574e8949f74SAndre Oppermann 	 * No route to sender, stay with default mss and return.
357597d8d152SAndre Oppermann 	 */
35766f01cac6SBjoern A. Zeeb 	if (maxmtu == 0) {
35776f01cac6SBjoern A. Zeeb 		/*
35788e5c87f4SBjoern A. Zeeb 		 * In case we return early we need to initialize metrics
35796f01cac6SBjoern A. Zeeb 		 * to a defined state as tcp_hc_get() would do for us
35806f01cac6SBjoern A. Zeeb 		 * if there was no cache hit.
35816f01cac6SBjoern A. Zeeb 		 */
35826f01cac6SBjoern A. Zeeb 		if (metricptr != NULL)
35836f01cac6SBjoern A. Zeeb 			bzero(metricptr, sizeof(struct hc_metrics_lite));
358497d8d152SAndre Oppermann 		return;
35856f01cac6SBjoern A. Zeeb 	}
358697d8d152SAndre Oppermann 
3587e8949f74SAndre Oppermann 	/* What have we got? */
358897d8d152SAndre Oppermann 	switch (offer) {
358997d8d152SAndre Oppermann 		case 0:
359097d8d152SAndre Oppermann 			/*
359197d8d152SAndre Oppermann 			 * Offer == 0 means that there was no MSS on the SYN
3592c3b02504SBjoern A. Zeeb 			 * segment, in this case we use tcp_mssdflt as
35930c39d38dSGleb Smirnoff 			 * already assigned to t_maxseg above.
359497d8d152SAndre Oppermann 			 */
35950c39d38dSGleb Smirnoff 			offer = tp->t_maxseg;
359697d8d152SAndre Oppermann 			break;
359797d8d152SAndre Oppermann 
359897d8d152SAndre Oppermann 		case -1:
3599a0292f23SGarrett Wollman 			/*
3600c94c54e4SAndre Oppermann 			 * Offer == -1 means that we didn't receive SYN yet.
3601a0292f23SGarrett Wollman 			 */
360297d8d152SAndre Oppermann 			/* FALLTHROUGH */
360397d8d152SAndre Oppermann 
360497d8d152SAndre Oppermann 		default:
3605a0292f23SGarrett Wollman 			/*
360653369ac9SAndre Oppermann 			 * Prevent DoS attack with too small MSS. Round up
360753369ac9SAndre Oppermann 			 * to at least minmss.
360853369ac9SAndre Oppermann 			 */
3609603724d3SBjoern A. Zeeb 			offer = max(offer, V_tcp_minmss);
361097d8d152SAndre Oppermann 	}
3611a0292f23SGarrett Wollman 
3612df8bae1dSRodney W. Grimes 	/*
3613e8949f74SAndre Oppermann 	 * rmx information is now retrieved from tcp_hostcache.
3614df8bae1dSRodney W. Grimes 	 */
361597d8d152SAndre Oppermann 	tcp_hc_get(&inp->inp_inc, &metrics);
36163cee92e0SBjoern A. Zeeb 	if (metricptr != NULL)
36173cee92e0SBjoern A. Zeeb 		bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
361897d8d152SAndre Oppermann 
3619df8bae1dSRodney W. Grimes 	/*
3620cc412412SHiren Panchasara 	 * If there's a discovered mtu in tcp hostcache, use it.
3621cc412412SHiren Panchasara 	 * Else, use the link mtu.
3622df8bae1dSRodney W. Grimes 	 */
362397d8d152SAndre Oppermann 	if (metrics.rmx_mtu)
36242d166c02SAndre Oppermann 		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3625c068736aSJeffrey Hsu 	else {
362631b3783cSHajimu UMEMOTO #ifdef INET6
3627fb59c426SYoshinobu Inoue 		if (isipv6) {
362897d8d152SAndre Oppermann 			mss = maxmtu - min_protoh;
3629603724d3SBjoern A. Zeeb 			if (!V_path_mtu_discovery &&
363097d8d152SAndre Oppermann 			    !in6_localaddr(&inp->in6p_faddr))
3631603724d3SBjoern A. Zeeb 				mss = min(mss, V_tcp_v6mssdflt);
3632b287c6c7SBjoern A. Zeeb 		}
3633b3399803SHajimu UMEMOTO #endif
3634b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3635b287c6c7SBjoern A. Zeeb 		else
3636b287c6c7SBjoern A. Zeeb #endif
3637b287c6c7SBjoern A. Zeeb #ifdef INET
363897d8d152SAndre Oppermann 		{
363997d8d152SAndre Oppermann 			mss = maxmtu - min_protoh;
3640603724d3SBjoern A. Zeeb 			if (!V_path_mtu_discovery &&
364197d8d152SAndre Oppermann 			    !in_localaddr(inp->inp_faddr))
3642603724d3SBjoern A. Zeeb 				mss = min(mss, V_tcp_mssdflt);
3643a0292f23SGarrett Wollman 		}
3644b287c6c7SBjoern A. Zeeb #endif
36453cee92e0SBjoern A. Zeeb 		/*
36463cee92e0SBjoern A. Zeeb 		 * XXX - The above conditional (mss = maxmtu - min_protoh)
36473cee92e0SBjoern A. Zeeb 		 * probably violates the TCP spec.
36483cee92e0SBjoern A. Zeeb 		 * The problem is that, since we don't know the
36493cee92e0SBjoern A. Zeeb 		 * other end's MSS, we are supposed to use a conservative
36503cee92e0SBjoern A. Zeeb 		 * default.  But, if we do that, then MTU discovery will
36513cee92e0SBjoern A. Zeeb 		 * never actually take place, because the conservative
36523cee92e0SBjoern A. Zeeb 		 * default is much less than the MTUs typically seen
36533cee92e0SBjoern A. Zeeb 		 * on the Internet today.  For the moment, we'll sweep
36543cee92e0SBjoern A. Zeeb 		 * this under the carpet.
36553cee92e0SBjoern A. Zeeb 		 *
36563cee92e0SBjoern A. Zeeb 		 * The conservative default might not actually be a problem
36573cee92e0SBjoern A. Zeeb 		 * if the only case this occurs is when sending an initial
36583cee92e0SBjoern A. Zeeb 		 * SYN with options and data to a host we've never talked
36593cee92e0SBjoern A. Zeeb 		 * to before.  Then, they will reply with an MSS value which
36603cee92e0SBjoern A. Zeeb 		 * will get recorded and the new parameters should get
36613cee92e0SBjoern A. Zeeb 		 * recomputed.  For Further Study.
36623cee92e0SBjoern A. Zeeb 		 */
366397d8d152SAndre Oppermann 	}
3664a0292f23SGarrett Wollman 	mss = min(mss, offer);
366597d8d152SAndre Oppermann 
3666a0292f23SGarrett Wollman 	/*
36670c39d38dSGleb Smirnoff 	 * Sanity check: make sure that maxseg will be large
36683cee92e0SBjoern A. Zeeb 	 * enough to allow some data on segments even if the
36693cee92e0SBjoern A. Zeeb 	 * all the option space is used (40bytes).  Otherwise
36703cee92e0SBjoern A. Zeeb 	 * funny things may happen in tcp_output.
36710c39d38dSGleb Smirnoff 	 *
36720c39d38dSGleb Smirnoff 	 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
36733cee92e0SBjoern A. Zeeb 	 */
36743cee92e0SBjoern A. Zeeb 	mss = max(mss, 64);
36753cee92e0SBjoern A. Zeeb 
367697d8d152SAndre Oppermann 	tp->t_maxseg = mss;
36773cee92e0SBjoern A. Zeeb }
36783cee92e0SBjoern A. Zeeb 
36793cee92e0SBjoern A. Zeeb void
36803cee92e0SBjoern A. Zeeb tcp_mss(struct tcpcb *tp, int offer)
36813cee92e0SBjoern A. Zeeb {
3682dbc42409SLawrence Stewart 	int mss;
36833ac12506SJonathan T. Looney 	uint32_t bufsize;
36843cee92e0SBjoern A. Zeeb 	struct inpcb *inp;
36853cee92e0SBjoern A. Zeeb 	struct socket *so;
36863cee92e0SBjoern A. Zeeb 	struct hc_metrics_lite metrics;
36873c914c54SAndre Oppermann 	struct tcp_ifcap cap;
3688dbc42409SLawrence Stewart 
36893cee92e0SBjoern A. Zeeb 	KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
36903cee92e0SBjoern A. Zeeb 
36913c914c54SAndre Oppermann 	bzero(&cap, sizeof(cap));
36923c914c54SAndre Oppermann 	tcp_mss_update(tp, offer, -1, &metrics, &cap);
36933cee92e0SBjoern A. Zeeb 
36943cee92e0SBjoern A. Zeeb 	mss = tp->t_maxseg;
36953cee92e0SBjoern A. Zeeb 	inp = tp->t_inpcb;
369697d8d152SAndre Oppermann 
3697df8bae1dSRodney W. Grimes 	/*
369897d8d152SAndre Oppermann 	 * If there's a pipesize, change the socket buffer to that size,
369997d8d152SAndre Oppermann 	 * don't change if sb_hiwat is different than default (then it
370097d8d152SAndre Oppermann 	 * has been changed on purpose with setsockopt).
370197d8d152SAndre Oppermann 	 * Make the socket buffers an integral number of mss units;
370297d8d152SAndre Oppermann 	 * if the mss is larger than the socket buffer, decrease the mss.
3703df8bae1dSRodney W. Grimes 	 */
3704c3b02504SBjoern A. Zeeb 	so = inp->inp_socket;
37053f11a2f3SRobert Watson 	SOCKBUF_LOCK(&so->so_snd);
3706e233e2acSAndre Oppermann 	if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
370797d8d152SAndre Oppermann 		bufsize = metrics.rmx_sendpipe;
370897d8d152SAndre Oppermann 	else
3709df8bae1dSRodney W. Grimes 		bufsize = so->so_snd.sb_hiwat;
3710df8bae1dSRodney W. Grimes 	if (bufsize < mss)
3711df8bae1dSRodney W. Grimes 		mss = bufsize;
3712df8bae1dSRodney W. Grimes 	else {
3713df8bae1dSRodney W. Grimes 		bufsize = roundup(bufsize, mss);
3714df8bae1dSRodney W. Grimes 		if (bufsize > sb_max)
3715df8bae1dSRodney W. Grimes 			bufsize = sb_max;
371688c39af3SRuslan Ermilov 		if (bufsize > so->so_snd.sb_hiwat)
37173f11a2f3SRobert Watson 			(void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3718df8bae1dSRodney W. Grimes 	}
37193f11a2f3SRobert Watson 	SOCKBUF_UNLOCK(&so->so_snd);
3720784ce8faSHiren Panchasara 	/*
3721784ce8faSHiren Panchasara 	 * Sanity check: make sure that maxseg will be large
3722784ce8faSHiren Panchasara 	 * enough to allow some data on segments even if the
3723784ce8faSHiren Panchasara 	 * all the option space is used (40bytes).  Otherwise
3724784ce8faSHiren Panchasara 	 * funny things may happen in tcp_output.
3725784ce8faSHiren Panchasara 	 *
3726784ce8faSHiren Panchasara 	 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3727784ce8faSHiren Panchasara 	 */
3728784ce8faSHiren Panchasara 	tp->t_maxseg = max(mss, 64);
3729df8bae1dSRodney W. Grimes 
37303f11a2f3SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
3731e233e2acSAndre Oppermann 	if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
373297d8d152SAndre Oppermann 		bufsize = metrics.rmx_recvpipe;
373397d8d152SAndre Oppermann 	else
3734df8bae1dSRodney W. Grimes 		bufsize = so->so_rcv.sb_hiwat;
3735df8bae1dSRodney W. Grimes 	if (bufsize > mss) {
3736df8bae1dSRodney W. Grimes 		bufsize = roundup(bufsize, mss);
3737df8bae1dSRodney W. Grimes 		if (bufsize > sb_max)
3738df8bae1dSRodney W. Grimes 			bufsize = sb_max;
373988c39af3SRuslan Ermilov 		if (bufsize > so->so_rcv.sb_hiwat)
37403f11a2f3SRobert Watson 			(void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3741df8bae1dSRodney W. Grimes 	}
37423f11a2f3SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
374391d6cfa6SBjoern A. Zeeb 
374491d6cfa6SBjoern A. Zeeb 	/* Check the interface for TSO capabilities. */
37453c914c54SAndre Oppermann 	if (cap.ifcap & CSUM_TSO) {
374691d6cfa6SBjoern A. Zeeb 		tp->t_flags |= TF_TSO;
37473c914c54SAndre Oppermann 		tp->t_tsomax = cap.tsomax;
37489fd573c3SHans Petter Selasky 		tp->t_tsomaxsegcount = cap.tsomaxsegcount;
37499fd573c3SHans Petter Selasky 		tp->t_tsomaxsegsize = cap.tsomaxsegsize;
37503c914c54SAndre Oppermann 	}
3751a0292f23SGarrett Wollman }
3752a0292f23SGarrett Wollman 
3753a0292f23SGarrett Wollman /*
3754a0292f23SGarrett Wollman  * Determine the MSS option to send on an outgoing SYN.
3755a0292f23SGarrett Wollman  */
3756a0292f23SGarrett Wollman int
3757ad3f9ab3SAndre Oppermann tcp_mssopt(struct in_conninfo *inc)
3758a0292f23SGarrett Wollman {
375997d8d152SAndre Oppermann 	int mss = 0;
37603ac12506SJonathan T. Looney 	uint32_t thcmtu = 0;
37613ac12506SJonathan T. Looney 	uint32_t maxmtu = 0;
376297d8d152SAndre Oppermann 	size_t min_protoh;
3763a0292f23SGarrett Wollman 
376497d8d152SAndre Oppermann 	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3765a0292f23SGarrett Wollman 
376631b3783cSHajimu UMEMOTO #ifdef INET6
3767dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
3768603724d3SBjoern A. Zeeb 		mss = V_tcp_v6mssdflt;
3769233dcce1SAndre Oppermann 		maxmtu = tcp_maxmtu6(inc, NULL);
377097d8d152SAndre Oppermann 		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3771b287c6c7SBjoern A. Zeeb 	}
377231b3783cSHajimu UMEMOTO #endif
3773b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3774b287c6c7SBjoern A. Zeeb 	else
3775b287c6c7SBjoern A. Zeeb #endif
3776b287c6c7SBjoern A. Zeeb #ifdef INET
377797d8d152SAndre Oppermann 	{
3778603724d3SBjoern A. Zeeb 		mss = V_tcp_mssdflt;
3779233dcce1SAndre Oppermann 		maxmtu = tcp_maxmtu(inc, NULL);
378097d8d152SAndre Oppermann 		min_protoh = sizeof(struct tcpiphdr);
378197d8d152SAndre Oppermann 	}
3782b287c6c7SBjoern A. Zeeb #endif
37833a9391deSBjoern A. Zeeb #if defined(INET6) || defined(INET)
37843a9391deSBjoern A. Zeeb 	thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
37853a9391deSBjoern A. Zeeb #endif
37863a9391deSBjoern A. Zeeb 
378797d8d152SAndre Oppermann 	if (maxmtu && thcmtu)
378897d8d152SAndre Oppermann 		mss = min(maxmtu, thcmtu) - min_protoh;
378997d8d152SAndre Oppermann 	else if (maxmtu || thcmtu)
379097d8d152SAndre Oppermann 		mss = max(maxmtu, thcmtu) - min_protoh;
379197d8d152SAndre Oppermann 
379297d8d152SAndre Oppermann 	return (mss);
3793df8bae1dSRodney W. Grimes }
379446f58482SJonathan Lemon 
379546f58482SJonathan Lemon 
379646f58482SJonathan Lemon /*
3797c068736aSJeffrey Hsu  * On a partial ack arrives, force the retransmission of the
3798c068736aSJeffrey Hsu  * next unacknowledged segment.  Do not clear tp->t_dupacks.
3799c068736aSJeffrey Hsu  * By setting snd_nxt to ti_ack, this forces retransmission timer to
3800c068736aSJeffrey Hsu  * be started again.
380146f58482SJonathan Lemon  */
380255bceb1eSRandall Stewart void
3803ad3f9ab3SAndre Oppermann tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
380446f58482SJonathan Lemon {
380546f58482SJonathan Lemon 	tcp_seq onxt = tp->snd_nxt;
38063ac12506SJonathan T. Looney 	uint32_t ocwnd = tp->snd_cwnd;
38070c39d38dSGleb Smirnoff 	u_int maxseg = tcp_maxseg(tp);
380846f58482SJonathan Lemon 
38098501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
38107a3244ccSRobert Watson 
3811b8152ba7SAndre Oppermann 	tcp_timer_activate(tp, TT_REXMT, 0);
381246f58482SJonathan Lemon 	tp->t_rtttime = 0;
381346f58482SJonathan Lemon 	tp->snd_nxt = th->th_ack;
38146b2a5f92SJayanth Vijayaraghavan 	/*
3815c068736aSJeffrey Hsu 	 * Set snd_cwnd to one segment beyond acknowledged offset.
3816c068736aSJeffrey Hsu 	 * (tp->snd_una has not yet been updated when this function is called.)
38176b2a5f92SJayanth Vijayaraghavan 	 */
38180c39d38dSGleb Smirnoff 	tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3819a84db8f4SMatthew Dillon 	tp->t_flags |= TF_ACKNOW;
382055bceb1eSRandall Stewart 	(void) tp->t_fb->tfb_tcp_output(tp);
382146f58482SJonathan Lemon 	tp->snd_cwnd = ocwnd;
382246f58482SJonathan Lemon 	if (SEQ_GT(onxt, tp->snd_nxt))
382346f58482SJonathan Lemon 		tp->snd_nxt = onxt;
382446f58482SJonathan Lemon 	/*
382546f58482SJonathan Lemon 	 * Partial window deflation.  Relies on fact that tp->snd_una
382646f58482SJonathan Lemon 	 * not updated yet.
382746f58482SJonathan Lemon 	 */
3828dbc42409SLawrence Stewart 	if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3829dbc42409SLawrence Stewart 		tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3830d7587117SPaul Saab 	else
3831d7587117SPaul Saab 		tp->snd_cwnd = 0;
38320c39d38dSGleb Smirnoff 	tp->snd_cwnd += maxseg;
383346f58482SJonathan Lemon }
383412eeb81fSHiren Panchasara 
383512eeb81fSHiren Panchasara int
383612eeb81fSHiren Panchasara tcp_compute_pipe(struct tcpcb *tp)
383712eeb81fSHiren Panchasara {
383812eeb81fSHiren Panchasara 	return (tp->snd_max - tp->snd_una +
383912eeb81fSHiren Panchasara 		tp->sackhint.sack_bytes_rexmit -
384012eeb81fSHiren Panchasara 		tp->sackhint.sacked_bytes);
384112eeb81fSHiren Panchasara }
38427dc90a1dSMichael Tuexen 
38437dc90a1dSMichael Tuexen uint32_t
38447dc90a1dSMichael Tuexen tcp_compute_initwnd(uint32_t maxseg)
38457dc90a1dSMichael Tuexen {
38467dc90a1dSMichael Tuexen 	/*
38477dc90a1dSMichael Tuexen 	 * Calculate the Initial Window, also used as Restart Window
38487dc90a1dSMichael Tuexen 	 *
38497dc90a1dSMichael Tuexen 	 * RFC5681 Section 3.1 specifies the default conservative values.
38507dc90a1dSMichael Tuexen 	 * RFC3390 specifies slightly more aggressive values.
38517dc90a1dSMichael Tuexen 	 * RFC6928 increases it to ten segments.
38527dc90a1dSMichael Tuexen 	 * Support for user specified value for initial flight size.
38537dc90a1dSMichael Tuexen 	 */
38547dc90a1dSMichael Tuexen 	if (V_tcp_initcwnd_segments)
38557dc90a1dSMichael Tuexen 		return min(V_tcp_initcwnd_segments * maxseg,
38567dc90a1dSMichael Tuexen 		    max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
38577dc90a1dSMichael Tuexen 	else if (V_tcp_do_rfc3390)
38587dc90a1dSMichael Tuexen 		return min(4 * maxseg, max(2 * maxseg, 4380));
38597dc90a1dSMichael Tuexen 	else {
38607dc90a1dSMichael Tuexen 		/* Per RFC5681 Section 3.1 */
38617dc90a1dSMichael Tuexen 		if (maxseg > 2190)
38627dc90a1dSMichael Tuexen 			return (2 * maxseg);
38637dc90a1dSMichael Tuexen 		else if (maxseg > 1095)
38647dc90a1dSMichael Tuexen 			return (3 * maxseg);
38657dc90a1dSMichael Tuexen 		else
38667dc90a1dSMichael Tuexen 			return (4 * maxseg);
38677dc90a1dSMichael Tuexen 	}
38687dc90a1dSMichael Tuexen }
3869