xref: /freebsd/sys/netinet/tcp_input.c (revision 0d7445193abc7c68703fd9b6de39f3f6cf6b55c9)
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>
120df8bae1dSRodney W. Grimes #include <netinet/tcp_debug.h>
12109fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
12209fe6320SNavdeep Parhar #include <netinet/tcp_offload.h>
12309fe6320SNavdeep Parhar #endif
124f7220c48SRichard Scheffenegger #include <netinet/tcp_ecn.h>
1259e644c23SMichael Tuexen #include <netinet/udp.h>
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 
1463ea9a7cfSGleb Smirnoff VNET_DEFINE(bool, blackhole_local) = false;
1473ea9a7cfSGleb Smirnoff #define	V_blackhole_local	VNET(blackhole_local)
1483ea9a7cfSGleb Smirnoff SYSCTL_BOOL(_net_inet_tcp, OID_AUTO, blackhole_local, CTLFLAG_VNET |
1493ea9a7cfSGleb Smirnoff     CTLFLAG_RW, &VNET_NAME(blackhole_local), false,
1503ea9a7cfSGleb Smirnoff     "Enforce net.inet.tcp.blackhole for locally originated packets");
1513ea9a7cfSGleb Smirnoff 
15282cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_delack_enabled) = 1;
1536df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
154eddfbb76SRobert Watson     &VNET_NAME(tcp_delack_enabled), 0,
1553d177f46SBill Fumerola     "Delay ACK to try and piggyback it onto a data packet");
156f498eeeeSDavid Greenman 
15782cea7e6SBjoern A. Zeeb VNET_DEFINE(int, drop_synfin) = 0;
1586df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
159eddfbb76SRobert Watson     &VNET_NAME(drop_synfin), 0,
160eddfbb76SRobert Watson     "Drop TCP packets with SYN+FIN set");
161f8613305SDag-Erling Smørgrav 
1620e1d7c25SRichard Scheffenegger VNET_DEFINE(int, tcp_do_prr_conservative) = 0;
1630e1d7c25SRichard Scheffenegger SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_prr_conservative, CTLFLAG_VNET | CTLFLAG_RW,
1640e1d7c25SRichard Scheffenegger     &VNET_NAME(tcp_do_prr_conservative), 0,
1650e1d7c25SRichard Scheffenegger     "Do conservative Proportional Rate Reduction");
1660e1d7c25SRichard Scheffenegger 
1670e1d7c25SRichard Scheffenegger VNET_DEFINE(int, tcp_do_prr) = 1;
1680e1d7c25SRichard Scheffenegger SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_prr, CTLFLAG_VNET | CTLFLAG_RW,
1690e1d7c25SRichard Scheffenegger     &VNET_NAME(tcp_do_prr), 1,
1700e1d7c25SRichard Scheffenegger     "Enable Proportional Rate Reduction per RFC 6937");
1710e1d7c25SRichard Scheffenegger 
1720471a8c7SRichard Scheffenegger VNET_DEFINE(int, tcp_do_lrd) = 0;
1730471a8c7SRichard Scheffenegger SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_lrd, CTLFLAG_VNET | CTLFLAG_RW,
1740471a8c7SRichard Scheffenegger     &VNET_NAME(tcp_do_lrd), 1,
1750471a8c7SRichard Scheffenegger     "Perform Lost Retransmission Detection");
1760471a8c7SRichard Scheffenegger 
177b72e56e7SMichael Tuexen VNET_DEFINE(int, tcp_do_newcwv) = 0;
178b72e56e7SMichael Tuexen SYSCTL_INT(_net_inet_tcp, OID_AUTO, newcwv, CTLFLAG_VNET | CTLFLAG_RW,
179b72e56e7SMichael Tuexen     &VNET_NAME(tcp_do_newcwv), 0,
180b72e56e7SMichael Tuexen     "Enable New Congestion Window Validation per RFC7661");
181b72e56e7SMichael Tuexen 
18282cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3042) = 1;
1836df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
184eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3042), 0,
185eddfbb76SRobert Watson     "Enable RFC 3042 (Limited Transmit)");
186582a954bSJeffrey Hsu 
18782cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3390) = 1;
1886df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
189eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3390), 0,
190da3a8a1aSJeffrey Hsu     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
191da3a8a1aSJeffrey Hsu 
192356c7958SHiren Panchasara VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
193356c7958SHiren Panchasara SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
194356c7958SHiren Panchasara     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
195356c7958SHiren Panchasara     "Slow-start flight size (initial congestion window) in number of segments");
19609440655SAndre Oppermann 
19782cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3465) = 1;
1986df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
199eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3465), 0,
20024cb0f22SLawrence Stewart     "Enable RFC 3465 (Appropriate Byte Counting)");
201eddfbb76SRobert Watson 
20282cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_abc_l_var) = 2;
2036df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
204eddfbb76SRobert Watson     &VNET_NAME(tcp_abc_l_var), 2,
20524cb0f22SLawrence Stewart     "Cap the max cwnd increment during slow-start to this number of segments");
20624cb0f22SLawrence Stewart 
2077029da5cSPawel Biernacki static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn,
2087029da5cSPawel Biernacki     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
2097029da5cSPawel Biernacki     "TCP ECN");
210f2512ba1SRui Paulo 
211883054b4SDon Lewis VNET_DEFINE(int, tcp_do_ecn) = 2;
2126df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
213eddfbb76SRobert Watson     &VNET_NAME(tcp_do_ecn), 0,
214eddfbb76SRobert Watson     "TCP ECN support");
215eddfbb76SRobert Watson 
21682cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
2176df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
218eddfbb76SRobert Watson     &VNET_NAME(tcp_ecn_maxretries), 0,
219eddfbb76SRobert Watson     "Max retries before giving up on ECN");
220eddfbb76SRobert Watson 
2213220a212SGleb Smirnoff VNET_DEFINE(int, tcp_insecure_syn) = 0;
2226df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
2233220a212SGleb Smirnoff     &VNET_NAME(tcp_insecure_syn), 0,
2243220a212SGleb Smirnoff     "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
2253220a212SGleb Smirnoff 
22682cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_insecure_rst) = 0;
2276df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
228eddfbb76SRobert Watson     &VNET_NAME(tcp_insecure_rst), 0,
2293220a212SGleb Smirnoff     "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
230a69968eeSMike Silbersack 
231fba0cea1SBjoern A. Zeeb VNET_DEFINE(int, tcp_recvspace) = 1024*64;
232873789cbSAndre Oppermann #define	V_tcp_recvspace	VNET(tcp_recvspace)
2336df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
234873789cbSAndre Oppermann     &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
235873789cbSAndre Oppermann 
23682cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
2376df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
238eddfbb76SRobert Watson     &VNET_NAME(tcp_do_autorcvbuf), 0,
2398b615593SMarko Zec     "Enable automatic receive buffer sizing");
2406741ecf5SAndre Oppermann 
241b233773bSBjoern A. Zeeb VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
2426df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
243eddfbb76SRobert Watson     &VNET_NAME(tcp_autorcvbuf_max), 0,
2448b615593SMarko Zec     "Max size of automatic receive buffer");
2456741ecf5SAndre Oppermann 
24682cea7e6SBjoern A. Zeeb VNET_DEFINE(struct inpcbinfo, tcbinfo);
247df8bae1dSRodney W. Grimes 
248315e3e38SRobert Watson /*
249bf840a17SGleb Smirnoff  * TCP statistics are stored in an array of counter(9)s, which size matches
250bf840a17SGleb Smirnoff  * size of struct tcpstat.  TCP running connection count is a regular array.
2515923c293SGleb Smirnoff  */
2525da0521fSAndrey V. Elsukov VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
2535da0521fSAndrey V. Elsukov SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
2545da0521fSAndrey V. Elsukov     tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
255bf840a17SGleb Smirnoff VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
256bf840a17SGleb Smirnoff SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
257d4d32b9fSHans Petter Selasky     CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
258bf840a17SGleb Smirnoff     "TCP connection counts by TCP state");
259bf840a17SGleb Smirnoff 
2605923c293SGleb Smirnoff /*
2617ca6e296SMichael Tuexen  * Kernel module interface for updating tcpstat.  The first argument is an index
2625923c293SGleb Smirnoff  * into tcpstat treated as an array.
263315e3e38SRobert Watson  */
264315e3e38SRobert Watson void
2657ca6e296SMichael Tuexen kmod_tcpstat_add(int statnum, int val)
266315e3e38SRobert Watson {
267315e3e38SRobert Watson 
2687ca6e296SMichael Tuexen 	counter_u64_add(VNET(tcpstat)[statnum], val);
269315e3e38SRobert Watson }
270315e3e38SRobert Watson 
271c21b7b55SRichard Scheffenegger /*
272c21b7b55SRichard Scheffenegger  * Make sure that we only start a SACK loss recovery when
273c21b7b55SRichard Scheffenegger  * receiving a duplicate ACK with a SACK block, and also
274c21b7b55SRichard Scheffenegger  * complete SACK loss recovery in case the other end
275c21b7b55SRichard Scheffenegger  * reneges.
276c21b7b55SRichard Scheffenegger  */
277c21b7b55SRichard Scheffenegger static bool inline
278c21b7b55SRichard Scheffenegger tcp_is_sack_recovery(struct tcpcb *tp, struct tcpopt *to)
279c21b7b55SRichard Scheffenegger {
280c21b7b55SRichard Scheffenegger 	return ((tp->t_flags & TF_SACK_PERMIT) &&
281c21b7b55SRichard Scheffenegger 		((to->to_flags & TOF_SACK) ||
282c21b7b55SRichard Scheffenegger 		(!TAILQ_EMPTY(&tp->snd_holes))));
283c21b7b55SRichard Scheffenegger }
284c21b7b55SRichard Scheffenegger 
285bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
286dbc42409SLawrence Stewart /*
28739bc9de5SLawrence Stewart  * Wrapper for the TCP established input helper hook.
28839bc9de5SLawrence Stewart  */
28955bceb1eSRandall Stewart void
29039bc9de5SLawrence Stewart hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
29139bc9de5SLawrence Stewart {
29239bc9de5SLawrence Stewart 	struct tcp_hhook_data hhook_data;
29339bc9de5SLawrence Stewart 
29439bc9de5SLawrence Stewart 	if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
29539bc9de5SLawrence Stewart 		hhook_data.tp = tp;
29639bc9de5SLawrence Stewart 		hhook_data.th = th;
29739bc9de5SLawrence Stewart 		hhook_data.to = to;
29839bc9de5SLawrence Stewart 
29939bc9de5SLawrence Stewart 		hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
30039bc9de5SLawrence Stewart 		    tp->osd);
30139bc9de5SLawrence Stewart 	}
30239bc9de5SLawrence Stewart }
303bd79708dSJonathan T. Looney #endif
30439bc9de5SLawrence Stewart 
30539bc9de5SLawrence Stewart /*
306dbc42409SLawrence Stewart  * CC wrapper hook functions
307dbc42409SLawrence Stewart  */
30855bceb1eSRandall Stewart void
3094b7b743cSLawrence Stewart cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
3104b7b743cSLawrence Stewart     uint16_t type)
311f2512ba1SRui Paulo {
312adc56f5aSEdward Tomasz Napierala #ifdef STATS
313adc56f5aSEdward Tomasz Napierala 	int32_t gput;
314adc56f5aSEdward Tomasz Napierala #endif
315adc56f5aSEdward Tomasz Napierala 
316dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
317f2512ba1SRui Paulo 
3184b7b743cSLawrence Stewart 	tp->ccv->nsegs = nsegs;
319dbc42409SLawrence Stewart 	tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
320b72e56e7SMichael Tuexen 	if ((!V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd)) ||
321b72e56e7SMichael Tuexen 	    (V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd) &&
322b72e56e7SMichael Tuexen 	     (tp->snd_cwnd < (tcp_compute_pipe(tp) * 2))))
323dbc42409SLawrence Stewart 		tp->ccv->flags |= CCF_CWND_LIMITED;
324dbc42409SLawrence Stewart 	else
325dbc42409SLawrence Stewart 		tp->ccv->flags &= ~CCF_CWND_LIMITED;
326dbc42409SLawrence Stewart 
327dbc42409SLawrence Stewart 	if (type == CC_ACK) {
328adc56f5aSEdward Tomasz Napierala #ifdef STATS
329adc56f5aSEdward Tomasz Napierala 		stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
330adc56f5aSEdward Tomasz Napierala 		    ((int32_t)tp->snd_cwnd) - tp->snd_wnd);
331adc56f5aSEdward Tomasz Napierala 		if (!IN_RECOVERY(tp->t_flags))
332adc56f5aSEdward Tomasz Napierala 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_ACKLEN,
333adc56f5aSEdward Tomasz Napierala 			   tp->ccv->bytes_this_ack / (tcp_maxseg(tp) * nsegs));
334adc56f5aSEdward Tomasz Napierala 		if ((tp->t_flags & TF_GPUTINPROG) &&
335adc56f5aSEdward Tomasz Napierala 		    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
336adc56f5aSEdward Tomasz Napierala 			/*
337adc56f5aSEdward Tomasz Napierala 			 * Compute goodput in bits per millisecond.
338adc56f5aSEdward Tomasz Napierala 			 */
339f5766992SHans Petter Selasky 			gput = (((int64_t)SEQ_SUB(th->th_ack, tp->gput_seq)) << 3) /
340adc56f5aSEdward Tomasz Napierala 			    max(1, tcp_ts_getticks() - tp->gput_ts);
341adc56f5aSEdward Tomasz Napierala 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
342adc56f5aSEdward Tomasz Napierala 			    gput);
343adc56f5aSEdward Tomasz Napierala 			/*
344adc56f5aSEdward Tomasz Napierala 			 * XXXLAS: This is a temporary hack, and should be
345adc56f5aSEdward Tomasz Napierala 			 * chained off VOI_TCP_GPUT when stats(9) grows an API
346adc56f5aSEdward Tomasz Napierala 			 * to deal with chained VOIs.
347adc56f5aSEdward Tomasz Napierala 			 */
348adc56f5aSEdward Tomasz Napierala 			if (tp->t_stats_gput_prev > 0)
349adc56f5aSEdward Tomasz Napierala 				stats_voi_update_abs_s32(tp->t_stats,
350adc56f5aSEdward Tomasz Napierala 				    VOI_TCP_GPUT_ND,
351adc56f5aSEdward Tomasz Napierala 				    ((gput - tp->t_stats_gput_prev) * 100) /
352adc56f5aSEdward Tomasz Napierala 				    tp->t_stats_gput_prev);
353adc56f5aSEdward Tomasz Napierala 			tp->t_flags &= ~TF_GPUTINPROG;
354adc56f5aSEdward Tomasz Napierala 			tp->t_stats_gput_prev = gput;
355adc56f5aSEdward Tomasz Napierala 		}
356adc56f5aSEdward Tomasz Napierala #endif /* STATS */
357dbc42409SLawrence Stewart 		if (tp->snd_cwnd > tp->snd_ssthresh) {
3581951fa79SMichael Tuexen 			tp->t_bytes_acked += tp->ccv->bytes_this_ack;
359dbc42409SLawrence Stewart 			if (tp->t_bytes_acked >= tp->snd_cwnd) {
360dbc42409SLawrence Stewart 				tp->t_bytes_acked -= tp->snd_cwnd;
361dbc42409SLawrence Stewart 				tp->ccv->flags |= CCF_ABC_SENTAWND;
362dbc42409SLawrence Stewart 			}
363dbc42409SLawrence Stewart 		} else {
364dbc42409SLawrence Stewart 				tp->ccv->flags &= ~CCF_ABC_SENTAWND;
365dbc42409SLawrence Stewart 				tp->t_bytes_acked = 0;
366dbc42409SLawrence Stewart 		}
367dbc42409SLawrence Stewart 	}
368dbc42409SLawrence Stewart 
369dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->ack_received != NULL) {
370dbc42409SLawrence Stewart 		/* XXXLAS: Find a way to live without this */
371dbc42409SLawrence Stewart 		tp->ccv->curack = th->th_ack;
372dbc42409SLawrence Stewart 		CC_ALGO(tp)->ack_received(tp->ccv, type);
373dbc42409SLawrence Stewart 	}
374adc56f5aSEdward Tomasz Napierala #ifdef STATS
375adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
376adc56f5aSEdward Tomasz Napierala #endif
377dbc42409SLawrence Stewart }
378dbc42409SLawrence Stewart 
37955bceb1eSRandall Stewart void
380dbc42409SLawrence Stewart cc_conn_init(struct tcpcb *tp)
381dbc42409SLawrence Stewart {
382dbc42409SLawrence Stewart 	struct hc_metrics_lite metrics;
383dbc42409SLawrence Stewart 	struct inpcb *inp = tp->t_inpcb;
3840c39d38dSGleb Smirnoff 	u_int maxseg;
385dbc42409SLawrence Stewart 	int rtt;
386dbc42409SLawrence Stewart 
387dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
388dbc42409SLawrence Stewart 
389dbc42409SLawrence Stewart 	tcp_hc_get(&inp->inp_inc, &metrics);
3900c39d38dSGleb Smirnoff 	maxseg = tcp_maxseg(tp);
391dbc42409SLawrence Stewart 
392dbc42409SLawrence Stewart 	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
393dbc42409SLawrence Stewart 		tp->t_srtt = rtt;
394dbc42409SLawrence Stewart 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
395dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_usedrtt);
396dbc42409SLawrence Stewart 		if (metrics.rmx_rttvar) {
397dbc42409SLawrence Stewart 			tp->t_rttvar = metrics.rmx_rttvar;
398dbc42409SLawrence Stewart 			TCPSTAT_INC(tcps_usedrttvar);
399dbc42409SLawrence Stewart 		} else {
400dbc42409SLawrence Stewart 			/* default variation is +- 1 rtt */
401dbc42409SLawrence Stewart 			tp->t_rttvar =
402dbc42409SLawrence Stewart 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
403dbc42409SLawrence Stewart 		}
404dbc42409SLawrence Stewart 		TCPT_RANGESET(tp->t_rxtcur,
405dbc42409SLawrence Stewart 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
406dbc42409SLawrence Stewart 		    tp->t_rttmin, TCPTV_REXMTMAX);
407dbc42409SLawrence Stewart 	}
408dbc42409SLawrence Stewart 	if (metrics.rmx_ssthresh) {
409dbc42409SLawrence Stewart 		/*
410dbc42409SLawrence Stewart 		 * There's some sort of gateway or interface
411dbc42409SLawrence Stewart 		 * buffer limit on the path.  Use this to set
412a4641f4eSPedro F. Giffuni 		 * the slow start threshold, but set the
413dbc42409SLawrence Stewart 		 * threshold to no less than 2*mss.
414dbc42409SLawrence Stewart 		 */
4150c39d38dSGleb Smirnoff 		tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
416dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_usedssthresh);
417dbc42409SLawrence Stewart 	}
418dbc42409SLawrence Stewart 
419dbc42409SLawrence Stewart 	/*
4209ec4a4ccSAndre Oppermann 	 * Set the initial slow-start flight size.
421dbc42409SLawrence Stewart 	 *
422cf8f04f4SAndre Oppermann 	 * If a SYN or SYN/ACK was lost and retransmitted, we have to
423cf8f04f4SAndre Oppermann 	 * reduce the initial CWND to one segment as congestion is likely
424cf8f04f4SAndre Oppermann 	 * requiring us to be cautious.
425dbc42409SLawrence Stewart 	 */
426cf8f04f4SAndre Oppermann 	if (tp->snd_cwnd == 1)
4270c39d38dSGleb Smirnoff 		tp->snd_cwnd = maxseg;		/* SYN(-ACK) lost */
428dbc42409SLawrence Stewart 	else
4297dc90a1dSMichael Tuexen 		tp->snd_cwnd = tcp_compute_initwnd(maxseg);
430dbc42409SLawrence Stewart 
431dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->conn_init != NULL)
432dbc42409SLawrence Stewart 		CC_ALGO(tp)->conn_init(tp->ccv);
433dbc42409SLawrence Stewart }
434dbc42409SLawrence Stewart 
435dbc42409SLawrence Stewart void inline
436dbc42409SLawrence Stewart cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
437dbc42409SLawrence Stewart {
438dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
439dbc42409SLawrence Stewart 
440adc56f5aSEdward Tomasz Napierala #ifdef STATS
441adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
442adc56f5aSEdward Tomasz Napierala #endif
443adc56f5aSEdward Tomasz Napierala 
444dbc42409SLawrence Stewart 	switch(type) {
445dbc42409SLawrence Stewart 	case CC_NDUPACK:
446dbc42409SLawrence Stewart 		if (!IN_FASTRECOVERY(tp->t_flags)) {
447f2512ba1SRui Paulo 			tp->snd_recover = tp->snd_max;
4483cf38784SMichael Tuexen 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4493cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_SND_CWR;
450f2512ba1SRui Paulo 		}
451dbc42409SLawrence Stewart 		break;
452dbc42409SLawrence Stewart 	case CC_ECN:
453af2fb894SRichard Scheffenegger 		if (!IN_CONGRECOVERY(tp->t_flags) ||
454af2fb894SRichard Scheffenegger 		    /*
455af2fb894SRichard Scheffenegger 		     * Allow ECN reaction on ACK to CWR, if
456af2fb894SRichard Scheffenegger 		     * that data segment was also CE marked.
457af2fb894SRichard Scheffenegger 		     */
458af2fb894SRichard Scheffenegger 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
459af2fb894SRichard Scheffenegger 			EXIT_CONGRECOVERY(tp->t_flags);
460dbc42409SLawrence Stewart 			TCPSTAT_INC(tcps_ecn_rcwnd);
461af2fb894SRichard Scheffenegger 			tp->snd_recover = tp->snd_max + 1;
4623cf38784SMichael Tuexen 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4633cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_SND_CWR;
464dbc42409SLawrence Stewart 		}
465dbc42409SLawrence Stewart 		break;
466dbc42409SLawrence Stewart 	case CC_RTO:
467dbc42409SLawrence Stewart 		tp->t_dupacks = 0;
468dbc42409SLawrence Stewart 		tp->t_bytes_acked = 0;
469dbc42409SLawrence Stewart 		EXIT_RECOVERY(tp->t_flags);
4709cc711c9SMichael Tuexen 		if (tp->t_flags2 & TF2_ECN_PERMIT)
4719cc711c9SMichael Tuexen 			tp->t_flags2 |= TF2_ECN_SND_CWR;
472dbc42409SLawrence Stewart 		break;
473dbc42409SLawrence Stewart 	case CC_RTO_ERR:
474dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_sndrexmitbad);
475dbc42409SLawrence Stewart 		/* RTO was unnecessary, so reset everything. */
476dbc42409SLawrence Stewart 		tp->snd_cwnd = tp->snd_cwnd_prev;
477dbc42409SLawrence Stewart 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
478dbc42409SLawrence Stewart 		tp->snd_recover = tp->snd_recover_prev;
479dbc42409SLawrence Stewart 		if (tp->t_flags & TF_WASFRECOVERY)
480dbc42409SLawrence Stewart 			ENTER_FASTRECOVERY(tp->t_flags);
481dbc42409SLawrence Stewart 		if (tp->t_flags & TF_WASCRECOVERY)
482dbc42409SLawrence Stewart 			ENTER_CONGRECOVERY(tp->t_flags);
483dbc42409SLawrence Stewart 		tp->snd_nxt = tp->snd_max;
484672dc4aeSJohn Baldwin 		tp->t_flags &= ~TF_PREVVALID;
485dbc42409SLawrence Stewart 		tp->t_badrxtwin = 0;
486dbc42409SLawrence Stewart 		break;
487dbc42409SLawrence Stewart 	}
488dbc42409SLawrence Stewart 
489dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->cong_signal != NULL) {
490dbc42409SLawrence Stewart 		if (th != NULL)
491dbc42409SLawrence Stewart 			tp->ccv->curack = th->th_ack;
492dbc42409SLawrence Stewart 		CC_ALGO(tp)->cong_signal(tp->ccv, type);
493dbc42409SLawrence Stewart 	}
494dbc42409SLawrence Stewart }
495dbc42409SLawrence Stewart 
49655bceb1eSRandall Stewart void inline
497dbc42409SLawrence Stewart cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
498dbc42409SLawrence Stewart {
499dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
500dbc42409SLawrence Stewart 
501dbc42409SLawrence Stewart 	/* XXXLAS: KASSERT that we're in recovery? */
502dbc42409SLawrence Stewart 
503dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->post_recovery != NULL) {
504dbc42409SLawrence Stewart 		tp->ccv->curack = th->th_ack;
505dbc42409SLawrence Stewart 		CC_ALGO(tp)->post_recovery(tp->ccv);
506dbc42409SLawrence Stewart 	}
507dbc42409SLawrence Stewart 	/* XXXLAS: EXIT_RECOVERY ? */
508dbc42409SLawrence Stewart 	tp->t_bytes_acked = 0;
50948be5b97SRichard Scheffenegger 	tp->sackhint.delivered_data = 0;
510e5313869SRichard Scheffenegger 	tp->sackhint.prr_out = 0;
511dbc42409SLawrence Stewart }
5120312fbe9SPoul-Henning Kamp 
513df8bae1dSRodney W. Grimes /*
514262c1c1aSMatthew Dillon  * Indicate whether this ack should be delayed.  We can delay the ack if
51585536381SHiren Panchasara  * following conditions are met:
51685536381SHiren Panchasara  *	- There is no delayed ack timer in progress.
51785536381SHiren Panchasara  *	- Our last ack wasn't a 0-sized window. We never want to delay
51885536381SHiren Panchasara  *	  the ack that opens up a 0-sized window.
51985536381SHiren Panchasara  *	- LRO wasn't used for this segment. We make sure by checking that the
52085536381SHiren Panchasara  *	  segment size is not larger than the MSS.
521d8c85a26SJonathan Lemon  */
522c1e5a6e5SAndre Oppermann #define DELAY_ACK(tp, tlen)						\
523b8152ba7SAndre Oppermann 	((!tcp_timer_active(tp, TT_DELACK) &&				\
524a14c749fSJonathan Lemon 	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
5250c39d38dSGleb Smirnoff 	    (tlen <= tp->t_maxseg) &&					\
526603724d3SBjoern A. Zeeb 	    (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
527d8c85a26SJonathan Lemon 
5284ad24737SRandall Stewart void inline
5295d8fd932SRandall Stewart cc_ecnpkt_handler_flags(struct tcpcb *tp, uint16_t flags, uint8_t iptos)
53064807b30SHiren Panchasara {
53164807b30SHiren Panchasara 	INP_WLOCK_ASSERT(tp->t_inpcb);
53264807b30SHiren Panchasara 
53364807b30SHiren Panchasara 	if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
53464807b30SHiren Panchasara 		switch (iptos & IPTOS_ECN_MASK) {
53564807b30SHiren Panchasara 		case IPTOS_ECN_CE:
53664807b30SHiren Panchasara 			tp->ccv->flags |= CCF_IPHDR_CE;
53764807b30SHiren Panchasara 			break;
53864807b30SHiren Panchasara 		case IPTOS_ECN_ECT0:
53983a2839fSMichael Tuexen 			/* FALLTHROUGH */
54064807b30SHiren Panchasara 		case IPTOS_ECN_ECT1:
54183a2839fSMichael Tuexen 			/* FALLTHROUGH */
54283a2839fSMichael Tuexen 		case IPTOS_ECN_NOTECT:
54364807b30SHiren Panchasara 			tp->ccv->flags &= ~CCF_IPHDR_CE;
54464807b30SHiren Panchasara 			break;
54564807b30SHiren Panchasara 		}
54664807b30SHiren Panchasara 
5475d8fd932SRandall Stewart 		if (flags & TH_CWR)
54864807b30SHiren Panchasara 			tp->ccv->flags |= CCF_TCPHDR_CWR;
54964807b30SHiren Panchasara 		else
55064807b30SHiren Panchasara 			tp->ccv->flags &= ~CCF_TCPHDR_CWR;
55164807b30SHiren Panchasara 
55264807b30SHiren Panchasara 		CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
55364807b30SHiren Panchasara 
554e11c9783SMichael Tuexen 		if (tp->ccv->flags & CCF_ACKNOW) {
55564807b30SHiren Panchasara 			tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
556e11c9783SMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
557e11c9783SMichael Tuexen 		}
55864807b30SHiren Panchasara 	}
55964807b30SHiren Panchasara }
56064807b30SHiren Panchasara 
5615d8fd932SRandall Stewart void inline
5625d8fd932SRandall Stewart cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
5635d8fd932SRandall Stewart {
5641ebf4607SRichard Scheffenegger 	cc_ecnpkt_handler_flags(tp, tcp_get_flags(th), iptos);
5655d8fd932SRandall Stewart }
5665d8fd932SRandall Stewart 
567df8bae1dSRodney W. Grimes /*
5688d573cc1SAndre Oppermann  * TCP input handling is split into multiple parts:
5698d573cc1SAndre Oppermann  *   tcp6_input is a thin wrapper around tcp_input for the extended
5708d573cc1SAndre Oppermann  *	ip6_protox[] call format in ip6_input
5718d573cc1SAndre Oppermann  *   tcp_input handles primary segment validation, inpcb lookup and
5728d573cc1SAndre Oppermann  *	SYN processing on listen sockets
5738d573cc1SAndre Oppermann  *   tcp_do_segment processes the ACK and text of the segment for
5748d573cc1SAndre Oppermann  *	establishing, established and closing connections
575df8bae1dSRodney W. Grimes  */
576fb59c426SYoshinobu Inoue #ifdef INET6
577fb59c426SYoshinobu Inoue int
5789e644c23SMichael Tuexen tcp6_input_with_port(struct mbuf **mp, int *offp, int proto, uint16_t port)
579fb59c426SYoshinobu Inoue {
580503f4e47SBjoern A. Zeeb 	struct mbuf *m;
58133841545SHajimu UMEMOTO 	struct in6_ifaddr *ia6;
5823e88eb90SAndrey V. Elsukov 	struct ip6_hdr *ip6;
583fb59c426SYoshinobu Inoue 
584503f4e47SBjoern A. Zeeb 	m = *mp;
585a4adf6ccSBjoern A. Zeeb 	if (m->m_len < *offp + sizeof(struct tcphdr)) {
5864e619b17SBjoern A. Zeeb 		m = m_pullup(m, *offp + sizeof(struct tcphdr));
5874e619b17SBjoern A. Zeeb 		if (m == NULL) {
5884e619b17SBjoern A. Zeeb 			*mp = m;
5894e619b17SBjoern A. Zeeb 			TCPSTAT_INC(tcps_rcvshort);
5904e619b17SBjoern A. Zeeb 			return (IPPROTO_DONE);
5914e619b17SBjoern A. Zeeb 		}
592a4adf6ccSBjoern A. Zeeb 	}
593fb59c426SYoshinobu Inoue 
594fb59c426SYoshinobu Inoue 	/*
595fb59c426SYoshinobu Inoue 	 * draft-itojun-ipv6-tcp-to-anycast
596fb59c426SYoshinobu Inoue 	 * better place to put this in?
597fb59c426SYoshinobu Inoue 	 */
5983e88eb90SAndrey V. Elsukov 	ip6 = mtod(m, struct ip6_hdr *);
5998268d82cSAlexander V. Chernikov 	ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
60033841545SHajimu UMEMOTO 	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
601fb59c426SYoshinobu Inoue 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
602fb59c426SYoshinobu Inoue 			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
603a8fe77d8SBjoern A. Zeeb 		*mp = NULL;
6048f5a8818SKevin Lo 		return (IPPROTO_DONE);
605fb59c426SYoshinobu Inoue 	}
606fb59c426SYoshinobu Inoue 
607a8fe77d8SBjoern A. Zeeb 	*mp = m;
6089e644c23SMichael Tuexen 	return (tcp_input_with_port(mp, offp, proto, port));
6099e644c23SMichael Tuexen }
6109e644c23SMichael Tuexen 
6119e644c23SMichael Tuexen int
6129e644c23SMichael Tuexen tcp6_input(struct mbuf **mp, int *offp, int proto)
6139e644c23SMichael Tuexen {
6149e644c23SMichael Tuexen 
6159e644c23SMichael Tuexen 	return(tcp6_input_with_port(mp, offp, proto, 0));
616fb59c426SYoshinobu Inoue }
617b287c6c7SBjoern A. Zeeb #endif /* INET6 */
618fb59c426SYoshinobu Inoue 
6198f5a8818SKevin Lo int
6209e644c23SMichael Tuexen tcp_input_with_port(struct mbuf **mp, int *offp, int proto, uint16_t port)
621df8bae1dSRodney W. Grimes {
6228f5a8818SKevin Lo 	struct mbuf *m = *mp;
623b287c6c7SBjoern A. Zeeb 	struct tcphdr *th = NULL;
624ad3f9ab3SAndre Oppermann 	struct ip *ip = NULL;
625ad3f9ab3SAndre Oppermann 	struct inpcb *inp = NULL;
626302ce8d6SAndre Oppermann 	struct tcpcb *tp = NULL;
627302ce8d6SAndre Oppermann 	struct socket *so = NULL;
628e79adb8eSGarrett Wollman 	u_char *optp = NULL;
6298f5a8818SKevin Lo 	int off0;
63026f9a767SRodney W. Grimes 	int optlen = 0;
631b287c6c7SBjoern A. Zeeb #ifdef INET
632b287c6c7SBjoern A. Zeeb 	int len;
633c4556b2fSAndrey V. Elsukov 	uint8_t ipttl;
634b287c6c7SBjoern A. Zeeb #endif
635b287c6c7SBjoern A. Zeeb 	int tlen = 0, off;
636fb59c426SYoshinobu Inoue 	int drop_hdrlen;
637ad3f9ab3SAndre Oppermann 	int thflags;
638302ce8d6SAndre Oppermann 	int rstreason = 0;	/* For badport_bandlim accounting purposes */
63908d9c920SGleb Smirnoff 	int lookupflag;
6401d7ee746SKurt Lidl 	uint8_t iptos;
641c1de64a4SAndrey V. Elsukov 	struct m_tag *fwd_tag = NULL;
642c068736aSJeffrey Hsu #ifdef INET6
643302ce8d6SAndre Oppermann 	struct ip6_hdr *ip6 = NULL;
644c068736aSJeffrey Hsu 	int isipv6;
645c068736aSJeffrey Hsu #else
646a160e630SAndre Oppermann 	const void *ip6 = NULL;
647b287c6c7SBjoern A. Zeeb #endif /* INET6 */
648302ce8d6SAndre Oppermann 	struct tcpopt to;		/* options in this segment */
649a160e630SAndre Oppermann 	char *s = NULL;			/* address and port logging */
650610ee2f9SDavid Greenman #ifdef TCPDEBUG
651c068736aSJeffrey Hsu 	/*
652c068736aSJeffrey Hsu 	 * The size of tcp_saveipgen must be the size of the max ip header,
653c068736aSJeffrey Hsu 	 * now IPv6.
654c068736aSJeffrey Hsu 	 */
65514739780SMaxim Konovalov 	u_char tcp_saveipgen[IP6_HDR_LEN];
656410bb1bfSLuigi Rizzo 	struct tcphdr tcp_savetcp;
657610ee2f9SDavid Greenman 	short ostate = 0;
658610ee2f9SDavid Greenman #endif
659c068736aSJeffrey Hsu 
660d40c0d47SGleb Smirnoff 	NET_EPOCH_ASSERT();
661d40c0d47SGleb Smirnoff 
662fb59c426SYoshinobu Inoue #ifdef INET6
663fb59c426SYoshinobu Inoue 	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
664fb59c426SYoshinobu Inoue #endif
665a0292f23SGarrett Wollman 
6668f5a8818SKevin Lo 	off0 = *offp;
6678f5a8818SKevin Lo 	m = *mp;
6688f5a8818SKevin Lo 	*mp = NULL;
669302ce8d6SAndre Oppermann 	to.to_flags = 0;
67078b50714SRobert Watson 	TCPSTAT_INC(tcps_rcvtotal);
671fb59c426SYoshinobu Inoue 
67204d3a452SHajimu UMEMOTO #ifdef INET6
673b287c6c7SBjoern A. Zeeb 	if (isipv6) {
674fb59c426SYoshinobu Inoue 		ip6 = mtod(m, struct ip6_hdr *);
67545747ba5SBjoern A. Zeeb 		th = (struct tcphdr *)((caddr_t)ip6 + off0);
676fb59c426SYoshinobu Inoue 		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
6779e644c23SMichael Tuexen 		if (port)
6789e644c23SMichael Tuexen 			goto skip6_csum;
679356ab07eSBjoern A. Zeeb 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
68045747ba5SBjoern A. Zeeb 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
68145747ba5SBjoern A. Zeeb 				th->th_sum = m->m_pkthdr.csum_data;
68245747ba5SBjoern A. Zeeb 			else
68345747ba5SBjoern A. Zeeb 				th->th_sum = in6_cksum_pseudo(ip6, tlen,
68445747ba5SBjoern A. Zeeb 				    IPPROTO_TCP, m->m_pkthdr.csum_data);
68545747ba5SBjoern A. Zeeb 			th->th_sum ^= 0xffff;
68645747ba5SBjoern A. Zeeb 		} else
68745747ba5SBjoern A. Zeeb 			th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
68845747ba5SBjoern A. Zeeb 		if (th->th_sum) {
68978b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvbadsum);
690fb59c426SYoshinobu Inoue 			goto drop;
691fb59c426SYoshinobu Inoue 		}
6929e644c23SMichael Tuexen 	skip6_csum:
69333841545SHajimu UMEMOTO 		/*
69433841545SHajimu UMEMOTO 		 * Be proactive about unspecified IPv6 address in source.
69533841545SHajimu UMEMOTO 		 * As we use all-zero to indicate unbounded/unconnected pcb,
69633841545SHajimu UMEMOTO 		 * unspecified IPv6 address can be used to confuse us.
69733841545SHajimu UMEMOTO 		 *
69833841545SHajimu UMEMOTO 		 * Note that packets with unspecified IPv6 destination is
69933841545SHajimu UMEMOTO 		 * already dropped in ip6_input.
70033841545SHajimu UMEMOTO 		 */
70133841545SHajimu UMEMOTO 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
70233841545SHajimu UMEMOTO 			/* XXX stat */
70333841545SHajimu UMEMOTO 			goto drop;
70433841545SHajimu UMEMOTO 		}
705bb4a7d94SKristof Provost 		iptos = IPV6_TRAFFIC_CLASS(ip6);
706b287c6c7SBjoern A. Zeeb 	}
70704d3a452SHajimu UMEMOTO #endif
708b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
709b287c6c7SBjoern A. Zeeb 	else
710b287c6c7SBjoern A. Zeeb #endif
711b287c6c7SBjoern A. Zeeb #ifdef INET
712b287c6c7SBjoern A. Zeeb 	{
713df8bae1dSRodney W. Grimes 		/*
714df8bae1dSRodney W. Grimes 		 * Get IP and TCP header together in first mbuf.
715df8bae1dSRodney W. Grimes 		 * Note: IP leaves IP header in first mbuf.
716df8bae1dSRodney W. Grimes 		 */
717fb59c426SYoshinobu Inoue 		if (off0 > sizeof (struct ip)) {
718105bd211SGleb Smirnoff 			ip_stripoptions(m);
719fb59c426SYoshinobu Inoue 			off0 = sizeof(struct ip);
720fb59c426SYoshinobu Inoue 		}
721df8bae1dSRodney W. Grimes 		if (m->m_len < sizeof (struct tcpiphdr)) {
7224dfdffe9SAndre Oppermann 			if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
7234dfdffe9SAndre Oppermann 			    == NULL) {
72478b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvshort);
7258f5a8818SKevin Lo 				return (IPPROTO_DONE);
726df8bae1dSRodney W. Grimes 			}
727df8bae1dSRodney W. Grimes 		}
728fb59c426SYoshinobu Inoue 		ip = mtod(m, struct ip *);
729db4f9cc7SJonathan Lemon 		th = (struct tcphdr *)((caddr_t)ip + off0);
7308ad458a4SGleb Smirnoff 		tlen = ntohs(ip->ip_len) - off0;
731df8bae1dSRodney W. Grimes 
7321d7ee746SKurt Lidl 		iptos = ip->ip_tos;
7339e644c23SMichael Tuexen 		if (port)
7349e644c23SMichael Tuexen 			goto skip_csum;
735db4f9cc7SJonathan Lemon 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
736db4f9cc7SJonathan Lemon 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
737db4f9cc7SJonathan Lemon 				th->th_sum = m->m_pkthdr.csum_data;
738db4f9cc7SJonathan Lemon 			else
739db4f9cc7SJonathan Lemon 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
740c068736aSJeffrey Hsu 				    ip->ip_dst.s_addr,
7418f134647SGleb Smirnoff 				    htonl(m->m_pkthdr.csum_data + tlen +
742c068736aSJeffrey Hsu 				    IPPROTO_TCP));
743db4f9cc7SJonathan Lemon 			th->th_sum ^= 0xffff;
744db4f9cc7SJonathan Lemon 		} else {
7458f134647SGleb Smirnoff 			struct ipovly *ipov = (struct ipovly *)ip;
7468f134647SGleb Smirnoff 
747df8bae1dSRodney W. Grimes 			/*
748df8bae1dSRodney W. Grimes 			 * Checksum extended TCP header and data.
749df8bae1dSRodney W. Grimes 			 */
7508f134647SGleb Smirnoff 			len = off0 + tlen;
751c4556b2fSAndrey V. Elsukov 			ipttl = ip->ip_ttl;
752fb59c426SYoshinobu Inoue 			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
7538f134647SGleb Smirnoff 			ipov->ih_len = htons(tlen);
754fb59c426SYoshinobu Inoue 			th->th_sum = in_cksum(m, len);
75557f60867SMark Johnston 			/* Reset length for SDT probes. */
7561d7ee746SKurt Lidl 			ip->ip_len = htons(len);
7571d7ee746SKurt Lidl 			/* Reset TOS bits */
7581d7ee746SKurt Lidl 			ip->ip_tos = iptos;
7591d7ee746SKurt Lidl 			/* Re-initialization for later version check */
760c4556b2fSAndrey V. Elsukov 			ip->ip_ttl = ipttl;
7611d7ee746SKurt Lidl 			ip->ip_v = IPVERSION;
762b2fe54bcSAndrey V. Elsukov 			ip->ip_hl = off0 >> 2;
763db4f9cc7SJonathan Lemon 		}
7649e644c23SMichael Tuexen 	skip_csum:
7659e644c23SMichael Tuexen 		if (th->th_sum && (port == 0)) {
76678b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvbadsum);
767df8bae1dSRodney W. Grimes 			goto drop;
768df8bae1dSRodney W. Grimes 		}
769fb59c426SYoshinobu Inoue 	}
770b287c6c7SBjoern A. Zeeb #endif /* INET */
771df8bae1dSRodney W. Grimes 
772df8bae1dSRodney W. Grimes 	/*
773df8bae1dSRodney W. Grimes 	 * Check that TCP offset makes sense,
774df8bae1dSRodney W. Grimes 	 * pull out TCP options and adjust length.		XXX
775df8bae1dSRodney W. Grimes 	 */
776fb59c426SYoshinobu Inoue 	off = th->th_off << 2;
777df8bae1dSRodney W. Grimes 	if (off < sizeof (struct tcphdr) || off > tlen) {
77878b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvbadoff);
779df8bae1dSRodney W. Grimes 		goto drop;
780df8bae1dSRodney W. Grimes 	}
781fb59c426SYoshinobu Inoue 	tlen -= off;	/* tlen is used instead of ti->ti_len */
782df8bae1dSRodney W. Grimes 	if (off > sizeof (struct tcphdr)) {
78304d3a452SHajimu UMEMOTO #ifdef INET6
784b287c6c7SBjoern A. Zeeb 		if (isipv6) {
785a4adf6ccSBjoern A. Zeeb 			if (m->m_len < off0 + off) {
7864e619b17SBjoern A. Zeeb 				m = m_pullup(m, off0 + off);
7874e619b17SBjoern A. Zeeb 				if (m == NULL) {
7884e619b17SBjoern A. Zeeb 					TCPSTAT_INC(tcps_rcvshort);
7894e619b17SBjoern A. Zeeb 					return (IPPROTO_DONE);
7904e619b17SBjoern A. Zeeb 				}
791a4adf6ccSBjoern A. Zeeb 			}
792fb59c426SYoshinobu Inoue 			ip6 = mtod(m, struct ip6_hdr *);
793fb59c426SYoshinobu Inoue 			th = (struct tcphdr *)((caddr_t)ip6 + off0);
794b287c6c7SBjoern A. Zeeb 		}
79504d3a452SHajimu UMEMOTO #endif
796b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
797b287c6c7SBjoern A. Zeeb 		else
798b287c6c7SBjoern A. Zeeb #endif
799b287c6c7SBjoern A. Zeeb #ifdef INET
800b287c6c7SBjoern A. Zeeb 		{
801df8bae1dSRodney W. Grimes 			if (m->m_len < sizeof(struct ip) + off) {
802c068736aSJeffrey Hsu 				if ((m = m_pullup(m, sizeof (struct ip) + off))
8034dfdffe9SAndre Oppermann 				    == NULL) {
80478b50714SRobert Watson 					TCPSTAT_INC(tcps_rcvshort);
8058f5a8818SKevin Lo 					return (IPPROTO_DONE);
806df8bae1dSRodney W. Grimes 				}
807fb59c426SYoshinobu Inoue 				ip = mtod(m, struct ip *);
808fb59c426SYoshinobu Inoue 				th = (struct tcphdr *)((caddr_t)ip + off0);
809fb59c426SYoshinobu Inoue 			}
810df8bae1dSRodney W. Grimes 		}
811b287c6c7SBjoern A. Zeeb #endif
812df8bae1dSRodney W. Grimes 		optlen = off - sizeof (struct tcphdr);
813fb59c426SYoshinobu Inoue 		optp = (u_char *)(th + 1);
814df8bae1dSRodney W. Grimes 	}
8151ebf4607SRichard Scheffenegger 	thflags = tcp_get_flags(th);
816df8bae1dSRodney W. Grimes 
817e46cd3d4SDag-Erling Smørgrav 	/*
818df8bae1dSRodney W. Grimes 	 * Convert TCP protocol specific fields to host format.
819df8bae1dSRodney W. Grimes 	 */
8202903309aSAttilio Rao 	tcp_fields_to_host(th);
821df8bae1dSRodney W. Grimes 
822df8bae1dSRodney W. Grimes 	/*
823794235b7SAndre Oppermann 	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
824755c1f07SAndras Olah 	 */
825fb59c426SYoshinobu Inoue 	drop_hdrlen = off0 + off;
826755c1f07SAndras Olah 
827755c1f07SAndras Olah 	/*
8288d573cc1SAndre Oppermann 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
8298d573cc1SAndre Oppermann 	 */
830b8056faeSGleb Smirnoff         if (
831b8056faeSGleb Smirnoff #ifdef INET6
832b8056faeSGleb Smirnoff 	    (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
833b8056faeSGleb Smirnoff #ifdef INET
834b8056faeSGleb Smirnoff 	    || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
835b8056faeSGleb Smirnoff #endif
836b8056faeSGleb Smirnoff #endif
837b8056faeSGleb Smirnoff #if defined(INET) && !defined(INET6)
838b8056faeSGleb Smirnoff 	    (m->m_flags & M_IP_NEXTHOP)
839b8056faeSGleb Smirnoff #endif
840b8056faeSGleb Smirnoff 	    )
8419b932e9eSAndre Oppermann 		fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
8429b932e9eSAndre Oppermann 
84308d9c920SGleb Smirnoff 	/*
8441db08fbeSGleb Smirnoff 	 * For initial SYN packets we don't need write lock on matching
8451db08fbeSGleb Smirnoff 	 * PCB, be it a listening one or a synchronized one.  The packet
8461db08fbeSGleb Smirnoff 	 * shall not modify its state.
84708d9c920SGleb Smirnoff 	 */
848d88eb465SGleb Smirnoff 	lookupflag = INPLOOKUP_WILDCARD |
849d88eb465SGleb Smirnoff 	    ((thflags & (TH_ACK|TH_SYN)) == TH_SYN ?
850d88eb465SGleb Smirnoff 	    INPLOOKUP_RLOCKPCB : INPLOOKUP_WLOCKPCB);
851ce7ad664SEd Maste findpcb:
8528a006adbSBjoern A. Zeeb #ifdef INET6
8538a006adbSBjoern A. Zeeb 	if (isipv6 && fwd_tag != NULL) {
8548a006adbSBjoern A. Zeeb 		struct sockaddr_in6 *next_hop6;
8558a006adbSBjoern A. Zeeb 
8568a006adbSBjoern A. Zeeb 		next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
8578a006adbSBjoern A. Zeeb 		/*
8588a006adbSBjoern A. Zeeb 		 * Transparently forwarded. Pretend to be the destination.
8598a006adbSBjoern A. Zeeb 		 * Already got one like this?
8608a006adbSBjoern A. Zeeb 		 */
8618a006adbSBjoern A. Zeeb 		inp = in6_pcblookup_mbuf(&V_tcbinfo,
8628a006adbSBjoern A. Zeeb 		    &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
86308d9c920SGleb Smirnoff 		    lookupflag, m->m_pkthdr.rcvif, m);
8648a006adbSBjoern A. Zeeb 		if (!inp) {
8658a006adbSBjoern A. Zeeb 			/*
8668a006adbSBjoern A. Zeeb 			 * It's new.  Try to find the ambushing socket.
8678a006adbSBjoern A. Zeeb 			 * Because we've rewritten the destination address,
8688a006adbSBjoern A. Zeeb 			 * any hardware-generated hash is ignored.
8698a006adbSBjoern A. Zeeb 			 */
8708a006adbSBjoern A. Zeeb 			inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
8718a006adbSBjoern A. Zeeb 			    th->th_sport, &next_hop6->sin6_addr,
8728a006adbSBjoern A. Zeeb 			    next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
873d88eb465SGleb Smirnoff 			    th->th_dport, lookupflag, m->m_pkthdr.rcvif);
8748a006adbSBjoern A. Zeeb 		}
875c1de64a4SAndrey V. Elsukov 	} else if (isipv6) {
8768a006adbSBjoern A. Zeeb 		inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
877d88eb465SGleb Smirnoff 		    th->th_sport, &ip6->ip6_dst, th->th_dport, lookupflag,
878d88eb465SGleb Smirnoff 		    m->m_pkthdr.rcvif, m);
8798a006adbSBjoern A. Zeeb 	}
8808a006adbSBjoern A. Zeeb #endif /* INET6 */
8818a006adbSBjoern A. Zeeb #if defined(INET6) && defined(INET)
8828a006adbSBjoern A. Zeeb 	else
8838a006adbSBjoern A. Zeeb #endif
8848a006adbSBjoern A. Zeeb #ifdef INET
8858a006adbSBjoern A. Zeeb 	if (fwd_tag != NULL) {
8869b932e9eSAndre Oppermann 		struct sockaddr_in *next_hop;
8879b932e9eSAndre Oppermann 
8889b932e9eSAndre Oppermann 		next_hop = (struct sockaddr_in *)(fwd_tag+1);
889f9e354dfSJulian Elischer 		/*
8902b25acc1SLuigi Rizzo 		 * Transparently forwarded. Pretend to be the destination.
891f9e354dfSJulian Elischer 		 * already got one like this?
892f9e354dfSJulian Elischer 		 */
893d3c1f003SRobert Watson 		inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
89408d9c920SGleb Smirnoff 		    ip->ip_dst, th->th_dport, lookupflag, m->m_pkthdr.rcvif, m);
895fa046d87SRobert Watson 		if (!inp) {
896fa046d87SRobert Watson 			/*
897fa046d87SRobert Watson 			 * It's new.  Try to find the ambushing socket.
898d3c1f003SRobert Watson 			 * Because we've rewritten the destination address,
899d3c1f003SRobert Watson 			 * any hardware-generated hash is ignored.
900fa046d87SRobert Watson 			 */
901fa046d87SRobert Watson 			inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
902fa046d87SRobert Watson 			    th->th_sport, next_hop->sin_addr,
903fa046d87SRobert Watson 			    next_hop->sin_port ? ntohs(next_hop->sin_port) :
904d88eb465SGleb Smirnoff 			    th->th_dport, lookupflag, m->m_pkthdr.rcvif);
905f9e354dfSJulian Elischer 		}
906b10fbdeaSAndre Oppermann 	} else
907d3c1f003SRobert Watson 		inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
908d88eb465SGleb Smirnoff 		    th->th_sport, ip->ip_dst, th->th_dport, lookupflag,
909d88eb465SGleb Smirnoff 		    m->m_pkthdr.rcvif, m);
9108a006adbSBjoern A. Zeeb #endif /* INET */
911f9e354dfSJulian Elischer 
912df8bae1dSRodney W. Grimes 	/*
913574b6964SAndre Oppermann 	 * If the INPCB does not exist then all data in the incoming
914574b6964SAndre Oppermann 	 * segment is discarded and an appropriate RST is sent back.
9158b07e49aSJulian Elischer 	 * XXX MRT Send RST using which routing table?
916df8bae1dSRodney W. Grimes 	 */
917816a3d83SPoul-Henning Kamp 	if (inp == NULL) {
918d88eb465SGleb Smirnoff 		if (rstreason != 0) {
919d88eb465SGleb Smirnoff 			/* We came here after second (safety) lookup. */
920d88eb465SGleb Smirnoff 			MPASS((lookupflag & INPLOOKUP_WILDCARD) == 0);
921d88eb465SGleb Smirnoff 			goto dropwithreset;
922d88eb465SGleb Smirnoff 		}
923574b6964SAndre Oppermann 		/*
924574b6964SAndre Oppermann 		 * Log communication attempts to ports that are not
925574b6964SAndre Oppermann 		 * in use.
926574b6964SAndre Oppermann 		 */
927334fc582SBjoern A. Zeeb 		if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
928334fc582SBjoern A. Zeeb 		    V_tcp_log_in_vain == 2) {
929b7d747ecSAndre Oppermann 			if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
930df541e5fSAndre Oppermann 				log(LOG_INFO, "%s; %s: Connection attempt "
931df541e5fSAndre Oppermann 				    "to closed port\n", s, __func__);
9322e4e1b4cSGeoff Rehmet 		}
933574b6964SAndre Oppermann 		/*
934574b6964SAndre Oppermann 		 * When blackholing do not respond with a RST but
935574b6964SAndre Oppermann 		 * completely ignore the segment and drop it.
936574b6964SAndre Oppermann 		 */
9373ea9a7cfSGleb Smirnoff 		if (((V_blackhole == 1 && (thflags & TH_SYN)) ||
938ad3ad064SGleb Smirnoff 		    V_blackhole == 2) && (V_blackhole_local || (
9393ea9a7cfSGleb Smirnoff #ifdef INET6
9403ea9a7cfSGleb Smirnoff 		    isipv6 ? !in6_localaddr(&ip6->ip6_src) :
9413ea9a7cfSGleb Smirnoff #endif
9423ea9a7cfSGleb Smirnoff #ifdef INET
9433ea9a7cfSGleb Smirnoff 		    !in_localip(ip->ip_src)
9443ea9a7cfSGleb Smirnoff #else
9453ea9a7cfSGleb Smirnoff 		    true
9463ea9a7cfSGleb Smirnoff #endif
947ad3ad064SGleb Smirnoff 		    )))
9481929eae1SAndre Oppermann 			goto dropunlock;
949574b6964SAndre Oppermann 
950a57815efSBosko Milekic 		rstreason = BANDLIM_RST_CLOSEDPORT;
951a57815efSBosko Milekic 		goto dropwithreset;
952816a3d83SPoul-Henning Kamp 	}
95308d9c920SGleb Smirnoff 	INP_LOCK_ASSERT(inp);
954f5cf1e5fSJulien Charbon 	/*
955f5cf1e5fSJulien Charbon 	 * While waiting for inp lock during the lookup, another thread
956f5cf1e5fSJulien Charbon 	 * can have dropped the inpcb, in which case we need to loop back
957f5cf1e5fSJulien Charbon 	 * and try to find a new inpcb to deliver to.
958f5cf1e5fSJulien Charbon 	 */
959f5cf1e5fSJulien Charbon 	if (inp->inp_flags & INP_DROPPED) {
96008d9c920SGleb Smirnoff 		INP_UNLOCK(inp);
961f5cf1e5fSJulien Charbon 		inp = NULL;
962f5cf1e5fSJulien Charbon 		goto findpcb;
963f5cf1e5fSJulien Charbon 	}
964c2529042SHans Petter Selasky 	if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
965c2529042SHans Petter Selasky 	    (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
966f4bb1869SMark Johnston 	    ((inp->inp_socket == NULL) || !SOLISTENING(inp->inp_socket))) {
96780cb9f21SKip Macy 		inp->inp_flowid = m->m_pkthdr.flowid;
9682f719932SAdrian Chadd 		inp->inp_flowtype = M_HASHTYPE_GET(m);
96980cb9f21SKip Macy 	}
970fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
971a2589465SKen Smith #ifdef INET6
972fcf59617SAndrey V. Elsukov 	if (isipv6 && IPSEC_ENABLED(ipv6) &&
973fcf59617SAndrey V. Elsukov 	    IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
974a2589465SKen Smith 		goto dropunlock;
975a2589465SKen Smith 	}
976fcf59617SAndrey V. Elsukov #ifdef INET
977fcf59617SAndrey V. Elsukov 	else
978fcf59617SAndrey V. Elsukov #endif
979fcf59617SAndrey V. Elsukov #endif /* INET6 */
980fcf59617SAndrey V. Elsukov #ifdef INET
981fcf59617SAndrey V. Elsukov 	if (IPSEC_ENABLED(ipv4) &&
982fcf59617SAndrey V. Elsukov 	    IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
983fcf59617SAndrey V. Elsukov 		goto dropunlock;
984fcf59617SAndrey V. Elsukov 	}
985fcf59617SAndrey V. Elsukov #endif /* INET */
986a2589465SKen Smith #endif /* IPSEC */
987a2589465SKen Smith 
9888d573cc1SAndre Oppermann 	/*
9898d573cc1SAndre Oppermann 	 * Check the minimum TTL for socket.
9908d573cc1SAndre Oppermann 	 */
99134f83c52SGeorge V. Neville-Neil 	if (inp->inp_ip_minttl != 0) {
99234f83c52SGeorge V. Neville-Neil #ifdef INET6
9932d8868dbSJonathan T. Looney 		if (isipv6) {
9942d8868dbSJonathan T. Looney 			if (inp->inp_ip_minttl > ip6->ip6_hlim)
995302ce8d6SAndre Oppermann 				goto dropunlock;
9962d8868dbSJonathan T. Looney 		} else
99734f83c52SGeorge V. Neville-Neil #endif
99834f83c52SGeorge V. Neville-Neil 		if (inp->inp_ip_minttl > ip->ip_ttl)
999302ce8d6SAndre Oppermann 			goto dropunlock;
100034f83c52SGeorge V. Neville-Neil 	}
1001936cd18dSAndre Oppermann 
1002*0d744519SGleb Smirnoff 	tp = intotcpcb(inp);
1003*0d744519SGleb Smirnoff 	switch (tp->t_state) {
1004*0d744519SGleb Smirnoff 	case TCPS_TIME_WAIT:
1005340c35deSJonathan Lemon 		/*
1006*0d744519SGleb Smirnoff 		 * A previous connection in TIMEWAIT state is supposed to catch
1007*0d744519SGleb Smirnoff 		 * stray or duplicate segments arriving late.  If this segment
1008*0d744519SGleb Smirnoff 		 * was a legitimate new connection attempt, the old INPCB gets
1009*0d744519SGleb Smirnoff 		 * removed and we can try again to find a listening socket.
1010340c35deSJonathan Lemon 		 */
1011283c76c7SMichael Tuexen 		tcp_dooptions(&to, optp, optlen,
1012283c76c7SMichael Tuexen 		    (thflags & TH_SYN) ? TO_SYN : 0);
10138d573cc1SAndre Oppermann 		/*
1014*0d744519SGleb Smirnoff 		 * tcp_twcheck unlocks the inp always, and frees the m if fails.
10158d573cc1SAndre Oppermann 		 */
10162104448fSAndre Oppermann 		if (tcp_twcheck(inp, &to, th, m, tlen))
1017340c35deSJonathan Lemon 			goto findpcb;
10188f5a8818SKevin Lo 		return (IPPROTO_DONE);
1019*0d744519SGleb Smirnoff 	case TCPS_CLOSED:
1020794235b7SAndre Oppermann 		/*
1021794235b7SAndre Oppermann 		 * The TCPCB may no longer exist if the connection is winding
1022794235b7SAndre Oppermann 		 * down or it is in the CLOSED state.  Either way we drop the
1023794235b7SAndre Oppermann 		 * segment and send an appropriate response.
1024794235b7SAndre Oppermann 		 */
1025a57815efSBosko Milekic 		rstreason = BANDLIM_RST_CLOSEDPORT;
1026a57815efSBosko Milekic 		goto dropwithreset;
102709f81a46SBosko Milekic 	}
1028df8bae1dSRodney W. Grimes 
10299e644c23SMichael Tuexen 	if ((tp->t_port != port) && (tp->t_state > TCPS_LISTEN)) {
10309e644c23SMichael Tuexen 		rstreason = BANDLIM_RST_CLOSEDPORT;
10319e644c23SMichael Tuexen 		goto dropwithreset;
10329e644c23SMichael Tuexen 	}
10339e644c23SMichael Tuexen 
103409fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
103509fe6320SNavdeep Parhar 	if (tp->t_flags & TF_TOE) {
103609fe6320SNavdeep Parhar 		tcp_offload_input(tp, m);
103709fe6320SNavdeep Parhar 		m = NULL;	/* consumed by the TOE driver */
103809fe6320SNavdeep Parhar 		goto dropunlock;
103909fe6320SNavdeep Parhar 	}
104009fe6320SNavdeep Parhar #endif
104109fe6320SNavdeep Parhar 
1042c488362eSRobert Watson #ifdef MAC
104330d239bcSRobert Watson 	if (mac_inpcb_check_deliver(inp, m))
1044302ce8d6SAndre Oppermann 		goto dropunlock;
1045c488362eSRobert Watson #endif
1046a557af22SRobert Watson 	so = inp->inp_socket;
1047302ce8d6SAndre Oppermann 	KASSERT(so != NULL, ("%s: so == NULL", __func__));
1048610ee2f9SDavid Greenman #ifdef TCPDEBUG
1049df8bae1dSRodney W. Grimes 	if (so->so_options & SO_DEBUG) {
1050df8bae1dSRodney W. Grimes 		ostate = tp->t_state;
105110fe523eSMaxim Konovalov #ifdef INET6
10526f697424SBjoern A. Zeeb 		if (isipv6) {
1053540e8b7eSJeffrey Hsu 			bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1054d30d90dcSMaxim Konovalov 		} else
10556f697424SBjoern A. Zeeb #endif
1056540e8b7eSJeffrey Hsu 			bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1057fb59c426SYoshinobu Inoue 		tcp_savetcp = *th;
1058df8bae1dSRodney W. Grimes 	}
1059b287c6c7SBjoern A. Zeeb #endif /* TCPDEBUG */
1060db33b3e6SAndre Oppermann 	/*
1061db33b3e6SAndre Oppermann 	 * When the socket is accepting connections (the INPCB is in LISTEN
1062db33b3e6SAndre Oppermann 	 * state) we look into the SYN cache if this is a new connection
1063a7c7f2a7SJohn Baldwin 	 * attempt or the completion of a previous one.
1064db33b3e6SAndre Oppermann 	 */
1065f4bb1869SMark Johnston 	KASSERT(tp->t_state == TCPS_LISTEN || !SOLISTENING(so),
106645274760SJonathan T. Looney 	    ("%s: so accepting but tp %p not listening", __func__, tp));
1067f4bb1869SMark Johnston 	if (tp->t_state == TCPS_LISTEN && SOLISTENING(so)) {
1068540e8b7eSJeffrey Hsu 		struct in_conninfo inc;
1069540e8b7eSJeffrey Hsu 
10708bfb1918SAndre Oppermann 		bzero(&inc, sizeof(inc));
1071302ce8d6SAndre Oppermann #ifdef INET6
1072be2ac88cSJonathan Lemon 		if (isipv6) {
1073dcdb4371SBjoern A. Zeeb 			inc.inc_flags |= INC_ISIPV6;
10745dff1c38SMichael Tuexen 			if (inp->inp_inc.inc_flags & INC_IPV6MINMTU)
10755dff1c38SMichael Tuexen 				inc.inc_flags |= INC_IPV6MINMTU;
1076be2ac88cSJonathan Lemon 			inc.inc6_faddr = ip6->ip6_src;
1077be2ac88cSJonathan Lemon 			inc.inc6_laddr = ip6->ip6_dst;
1078302ce8d6SAndre Oppermann 		} else
1079302ce8d6SAndre Oppermann #endif
1080302ce8d6SAndre Oppermann 		{
1081be2ac88cSJonathan Lemon 			inc.inc_faddr = ip->ip_src;
1082be2ac88cSJonathan Lemon 			inc.inc_laddr = ip->ip_dst;
1083be2ac88cSJonathan Lemon 		}
1084be2ac88cSJonathan Lemon 		inc.inc_fport = th->th_sport;
1085be2ac88cSJonathan Lemon 		inc.inc_lport = th->th_dport;
10867973fba3SJulian Elischer 		inc.inc_fibnum = so->so_fibnum;
1087be2ac88cSJonathan Lemon 
1088fb59c426SYoshinobu Inoue 		/*
10898d573cc1SAndre Oppermann 		 * Check for an existing connection attempt in syncache if
10908d573cc1SAndre Oppermann 		 * the flag is only ACK.  A successful lookup creates a new
10918d573cc1SAndre Oppermann 		 * socket appended to the listen queue in SYN_RECEIVED state.
1092fb59c426SYoshinobu Inoue 		 */
1093be2ac88cSJonathan Lemon 		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1094bf6d304aSAndre Oppermann 			/*
1095bf6d304aSAndre Oppermann 			 * Parse the TCP options here because
1096bf6d304aSAndre Oppermann 			 * syncookies need access to the reflected
1097bf6d304aSAndre Oppermann 			 * timestamp.
1098bf6d304aSAndre Oppermann 			 */
1099bf6d304aSAndre Oppermann 			tcp_dooptions(&to, optp, optlen, 0);
11009fa198beSAndre Oppermann 			/*
1101e7231d07SGleb Smirnoff 			 * NB: syncache_expand() doesn't unlock inp.
11029fa198beSAndre Oppermann 			 */
11039e644c23SMichael Tuexen 			rstreason = syncache_expand(&inc, &to, th, &so, m, port);
1104fcf59617SAndrey V. Elsukov 			if (rstreason < 0) {
1105fcf59617SAndrey V. Elsukov 				/*
1106fcf59617SAndrey V. Elsukov 				 * A failing TCP MD5 signature comparison
1107fcf59617SAndrey V. Elsukov 				 * must result in the segment being dropped
1108fcf59617SAndrey V. Elsukov 				 * and must not produce any response back
1109fcf59617SAndrey V. Elsukov 				 * to the sender.
1110fcf59617SAndrey V. Elsukov 				 */
1111fcf59617SAndrey V. Elsukov 				goto dropunlock;
1112fcf59617SAndrey V. Elsukov 			} else if (rstreason == 0) {
11134195b4afSPaul Traina 				/*
1114d88eb465SGleb Smirnoff 				 * No syncache entry, or ACK was not for our
1115d88eb465SGleb Smirnoff 				 * SYN/ACK.  Do our protection against double
1116d88eb465SGleb Smirnoff 				 * ACK.  If peer sent us 2 ACKs, then for the
1117d88eb465SGleb Smirnoff 				 * first one syncache_expand() successfully
1118d88eb465SGleb Smirnoff 				 * converted syncache entry into a socket,
1119d88eb465SGleb Smirnoff 				 * while we were waiting on the inpcb lock.  We
1120d88eb465SGleb Smirnoff 				 * don't want to sent RST for the second ACK,
1121d88eb465SGleb Smirnoff 				 * so we perform second lookup without wildcard
1122d88eb465SGleb Smirnoff 				 * match, hoping to find the new socket.  If
1123d88eb465SGleb Smirnoff 				 * the ACK is stray indeed, rstreason would
1124d88eb465SGleb Smirnoff 				 * hint the above code that the lookup was a
1125d88eb465SGleb Smirnoff 				 * second attempt.
1126d88eb465SGleb Smirnoff 				 *
11278d573cc1SAndre Oppermann 				 * NB: syncache did its own logging
11288d573cc1SAndre Oppermann 				 * of the failure cause.
11294195b4afSPaul Traina 				 */
1130d88eb465SGleb Smirnoff 				INP_WUNLOCK(inp);
1131be2ac88cSJonathan Lemon 				rstreason = BANDLIM_RST_OPENPORT;
1132d88eb465SGleb Smirnoff 				lookupflag &= ~INPLOOKUP_WILDCARD;
1133d88eb465SGleb Smirnoff 				goto findpcb;
1134be2ac88cSJonathan Lemon 			}
113509c305ebSPatrick Kelsey tfo_socket_result:
1136f76fcf6dSJeffrey Hsu 			if (so == NULL) {
1137be2ac88cSJonathan Lemon 				/*
1138e207f800SAndre Oppermann 				 * We completed the 3-way handshake
1139e207f800SAndre Oppermann 				 * but could not allocate a socket
1140e207f800SAndre Oppermann 				 * either due to memory shortage,
1141e207f800SAndre Oppermann 				 * listen queue length limits or
1142a160e630SAndre Oppermann 				 * global socket limits.  Send RST
1143a160e630SAndre Oppermann 				 * or wait and have the remote end
1144a160e630SAndre Oppermann 				 * retransmit the ACK for another
1145a160e630SAndre Oppermann 				 * try.
1146be2ac88cSJonathan Lemon 				 */
1147a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1148a160e630SAndre Oppermann 					log(LOG_DEBUG, "%s; %s: Listen socket: "
11498d573cc1SAndre Oppermann 					    "Socket allocation failed due to "
11508d573cc1SAndre Oppermann 					    "limits or memory shortage, %s\n",
1151ac957cd2SJulian Elischer 					    s, __func__,
1152ac957cd2SJulian Elischer 					    V_tcp_sc_rst_sock_fail ?
1153ac957cd2SJulian Elischer 					    "sending RST" : "try again");
1154603724d3SBjoern A. Zeeb 				if (V_tcp_sc_rst_sock_fail) {
1155e207f800SAndre Oppermann 					rstreason = BANDLIM_UNLIMITED;
1156e207f800SAndre Oppermann 					goto dropwithreset;
1157a160e630SAndre Oppermann 				} else
1158a160e630SAndre Oppermann 					goto dropunlock;
1159f76fcf6dSJeffrey Hsu 			}
1160be2ac88cSJonathan Lemon 			/*
1161be2ac88cSJonathan Lemon 			 * Socket is created in state SYN_RECEIVED.
11628d573cc1SAndre Oppermann 			 * Unlock the listen socket, lock the newly
11638d573cc1SAndre Oppermann 			 * created socket and update the tp variable.
116408d9c920SGleb Smirnoff 			 * If we came here via jump to tfo_socket_result,
116508d9c920SGleb Smirnoff 			 * then listening socket is read-locked.
1166be2ac88cSJonathan Lemon 			 */
116708d9c920SGleb Smirnoff 			INP_UNLOCK(inp);	/* listen socket */
1168be2ac88cSJonathan Lemon 			inp = sotoinpcb(so);
1169ff9b006dSJulien Charbon 			/*
1170ff9b006dSJulien Charbon 			 * New connection inpcb is already locked by
1171ff9b006dSJulien Charbon 			 * syncache_expand().
1172ff9b006dSJulien Charbon 			 */
1173ff9b006dSJulien Charbon 			INP_WLOCK_ASSERT(inp);
1174be2ac88cSJonathan Lemon 			tp = intotcpcb(inp);
11758d573cc1SAndre Oppermann 			KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
11768d573cc1SAndre Oppermann 			    ("%s: ", __func__));
1177be2ac88cSJonathan Lemon 			/*
1178302ce8d6SAndre Oppermann 			 * Process the segment and the data it
1179302ce8d6SAndre Oppermann 			 * contains.  tcp_do_segment() consumes
1180302ce8d6SAndre Oppermann 			 * the mbuf chain and unlocks the inpcb.
1181302ce8d6SAndre Oppermann 			 */
11826138da62SMichael Tuexen 			TCP_PROBE5(receive, NULL, tp, m, tp, th);
118355bceb1eSRandall Stewart 			tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
11846573d758SMatt Macy 			    iptos);
11858f5a8818SKevin Lo 			return (IPPROTO_DONE);
1186be2ac88cSJonathan Lemon 		}
1187a160e630SAndre Oppermann 		/*
11888d573cc1SAndre Oppermann 		 * Segment flag validation for new connection attempts:
11898d573cc1SAndre Oppermann 		 *
1190a160e630SAndre Oppermann 		 * Our (SYN|ACK) response was rejected.
1191a160e630SAndre Oppermann 		 * Check with syncache and remove entry to prevent
1192a160e630SAndre Oppermann 		 * retransmits.
119319bc77c5SAndre Oppermann 		 *
119419bc77c5SAndre Oppermann 		 * NB: syncache_chkrst does its own logging of failure
119519bc77c5SAndre Oppermann 		 * causes.
1196a160e630SAndre Oppermann 		 */
1197a160e630SAndre Oppermann 		if (thflags & TH_RST) {
11989e644c23SMichael Tuexen 			syncache_chkrst(&inc, th, m, port);
1199a160e630SAndre Oppermann 			goto dropunlock;
1200a160e630SAndre Oppermann 		}
1201a160e630SAndre Oppermann 		/*
1202a160e630SAndre Oppermann 		 * We can't do anything without SYN.
1203a160e630SAndre Oppermann 		 */
1204a160e630SAndre Oppermann 		if ((thflags & TH_SYN) == 0) {
1205a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1206a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
1207773673c1SAndre Oppermann 				    "SYN is missing, segment ignored\n",
12088d573cc1SAndre Oppermann 				    s, __func__);
120978b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1210a160e630SAndre Oppermann 			goto dropunlock;
1211a160e630SAndre Oppermann 		}
1212a160e630SAndre Oppermann 		/*
1213a160e630SAndre Oppermann 		 * (SYN|ACK) is bogus on a listen socket.
1214a160e630SAndre Oppermann 		 */
1215fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK) {
1216a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1217a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
12188d573cc1SAndre Oppermann 				    "SYN|ACK invalid, segment rejected\n",
12198d573cc1SAndre Oppermann 				    s, __func__);
12209e644c23SMichael Tuexen 			syncache_badack(&inc, port);	/* XXX: Not needed! */
122178b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1222a57815efSBosko Milekic 			rstreason = BANDLIM_RST_OPENPORT;
1223a57815efSBosko Milekic 			goto dropwithreset;
12244195b4afSPaul Traina 		}
1225a160e630SAndre Oppermann 		/*
1226a160e630SAndre Oppermann 		 * If the drop_synfin option is enabled, drop all
1227a160e630SAndre Oppermann 		 * segments with both the SYN and FIN bits set.
1228a160e630SAndre Oppermann 		 * This prevents e.g. nmap from identifying the
1229a160e630SAndre Oppermann 		 * TCP/IP stack.
1230a160e630SAndre Oppermann 		 * XXX: Poor reasoning.  nmap has other methods
1231a160e630SAndre Oppermann 		 * and is constantly refining its stack detection
1232a160e630SAndre Oppermann 		 * strategies.
12338d573cc1SAndre Oppermann 		 * XXX: This is a violation of the TCP specification
1234a160e630SAndre Oppermann 		 * and was used by RFC1644.
1235a160e630SAndre Oppermann 		 */
1236603724d3SBjoern A. Zeeb 		if ((thflags & TH_FIN) && V_drop_synfin) {
1237a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1238a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
1239773673c1SAndre Oppermann 				    "SYN|FIN segment ignored (based on "
12408d573cc1SAndre Oppermann 				    "sysctl setting)\n", s, __func__);
124178b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1242302ce8d6SAndre Oppermann 			goto dropunlock;
1243ebb0cbeaSPaul Traina 		}
1244be2ac88cSJonathan Lemon 		/*
1245be2ac88cSJonathan Lemon 		 * Segment's flags are (SYN) or (SYN|FIN).
1246a160e630SAndre Oppermann 		 *
1247a160e630SAndre Oppermann 		 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1248a160e630SAndre Oppermann 		 * as they do not affect the state of the TCP FSM.
1249a160e630SAndre Oppermann 		 * The data pointed to by TH_URG and th_urp is ignored.
1250be2ac88cSJonathan Lemon 		 */
1251a160e630SAndre Oppermann 		KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1252a160e630SAndre Oppermann 		    ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1253a160e630SAndre Oppermann 		KASSERT(thflags & (TH_SYN),
1254a160e630SAndre Oppermann 		    ("%s: Listen socket: TH_SYN not set", __func__));
125508d9c920SGleb Smirnoff 		INP_RLOCK_ASSERT(inp);
125633841545SHajimu UMEMOTO #ifdef INET6
125733841545SHajimu UMEMOTO 		/*
125833841545SHajimu UMEMOTO 		 * If deprecated address is forbidden,
125933841545SHajimu UMEMOTO 		 * we do not accept SYN to deprecated interface
126033841545SHajimu UMEMOTO 		 * address to prevent any new inbound connection from
126133841545SHajimu UMEMOTO 		 * getting established.
126233841545SHajimu UMEMOTO 		 * When we do not accept SYN, we send a TCP RST,
126333841545SHajimu UMEMOTO 		 * with deprecated source address (instead of dropping
126433841545SHajimu UMEMOTO 		 * it).  We compromise it as it is much better for peer
126533841545SHajimu UMEMOTO 		 * to send a RST, and RST will be the final packet
126633841545SHajimu UMEMOTO 		 * for the exchange.
126733841545SHajimu UMEMOTO 		 *
126833841545SHajimu UMEMOTO 		 * If we do not forbid deprecated addresses, we accept
126933841545SHajimu UMEMOTO 		 * the SYN packet.  RFC2462 does not suggest dropping
127033841545SHajimu UMEMOTO 		 * SYN in this case.
127133841545SHajimu UMEMOTO 		 * If we decipher RFC2462 5.5.4, it says like this:
127233841545SHajimu UMEMOTO 		 * 1. use of deprecated addr with existing
127333841545SHajimu UMEMOTO 		 *    communication is okay - "SHOULD continue to be
127433841545SHajimu UMEMOTO 		 *    used"
127533841545SHajimu UMEMOTO 		 * 2. use of it with new communication:
127633841545SHajimu UMEMOTO 		 *   (2a) "SHOULD NOT be used if alternate address
127733841545SHajimu UMEMOTO 		 *        with sufficient scope is available"
127833841545SHajimu UMEMOTO 		 *   (2b) nothing mentioned otherwise.
127933841545SHajimu UMEMOTO 		 * Here we fall into (2b) case as we have no choice in
128033841545SHajimu UMEMOTO 		 * our source address selection - we must obey the peer.
128133841545SHajimu UMEMOTO 		 *
128233841545SHajimu UMEMOTO 		 * The wording in RFC2462 is confusing, and there are
128333841545SHajimu UMEMOTO 		 * multiple description text for deprecated address
128433841545SHajimu UMEMOTO 		 * handling - worse, they are not exactly the same.
128533841545SHajimu UMEMOTO 		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
128633841545SHajimu UMEMOTO 		 */
1287603724d3SBjoern A. Zeeb 		if (isipv6 && !V_ip6_use_deprecated) {
128833841545SHajimu UMEMOTO 			struct in6_ifaddr *ia6;
128933841545SHajimu UMEMOTO 
12908268d82cSAlexander V. Chernikov 			ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
12918c0fec80SRobert Watson 			if (ia6 != NULL &&
129233841545SHajimu UMEMOTO 			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1293a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1294a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
12958d573cc1SAndre Oppermann 					"Connection attempt to deprecated "
12968d573cc1SAndre Oppermann 					"IPv6 address rejected\n",
1297a160e630SAndre Oppermann 					s, __func__);
129833841545SHajimu UMEMOTO 				rstreason = BANDLIM_RST_OPENPORT;
129933841545SHajimu UMEMOTO 				goto dropwithreset;
130033841545SHajimu UMEMOTO 			}
130133841545SHajimu UMEMOTO 		}
1302b287c6c7SBjoern A. Zeeb #endif /* INET6 */
130365f28919SJesper Skriver 		/*
1304db33b3e6SAndre Oppermann 		 * Basic sanity checks on incoming SYN requests:
13058d573cc1SAndre Oppermann 		 *   Don't respond if the destination is a link layer
1306db33b3e6SAndre Oppermann 		 *	broadcast according to RFC1122 4.2.3.10, p. 104.
13078d573cc1SAndre Oppermann 		 *   If it is from this socket it must be forged.
13088d573cc1SAndre Oppermann 		 *   Don't respond if the source or destination is a
13098d573cc1SAndre Oppermann 		 *	global or subnet broad- or multicast address.
131093ec91baSCrist J. Clark 		 *   Note that it is quite possible to receive unicast
131193ec91baSCrist J. Clark 		 *	link-layer packets with a broadcast IP address. Use
131293ec91baSCrist J. Clark 		 *	in_broadcast() to find them.
1313be2ac88cSJonathan Lemon 		 */
13148d573cc1SAndre Oppermann 		if (m->m_flags & (M_BCAST|M_MCAST)) {
13158d573cc1SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
13168d573cc1SAndre Oppermann 			    log(LOG_DEBUG, "%s; %s: Listen socket: "
13178d573cc1SAndre Oppermann 				"Connection attempt from broad- or multicast "
1318773673c1SAndre Oppermann 				"link layer address ignored\n", s, __func__);
1319302ce8d6SAndre Oppermann 			goto dropunlock;
13208d573cc1SAndre Oppermann 		}
1321db33b3e6SAndre Oppermann #ifdef INET6
1322b287c6c7SBjoern A. Zeeb 		if (isipv6) {
1323db33b3e6SAndre Oppermann 			if (th->th_dport == th->th_sport &&
1324a160e630SAndre Oppermann 			    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1325a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1326a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13278d573cc1SAndre Oppermann 					"Connection attempt to/from self "
1328773673c1SAndre Oppermann 					"ignored\n", s, __func__);
1329302ce8d6SAndre Oppermann 				goto dropunlock;
1330a160e630SAndre Oppermann 			}
1331be2ac88cSJonathan Lemon 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1332a160e630SAndre Oppermann 			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1333a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1334a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13358d573cc1SAndre Oppermann 					"Connection attempt from/to multicast "
1336773673c1SAndre Oppermann 					"address ignored\n", s, __func__);
1337302ce8d6SAndre Oppermann 				goto dropunlock;
1338a160e630SAndre Oppermann 			}
1339b287c6c7SBjoern A. Zeeb 		}
1340db33b3e6SAndre Oppermann #endif
1341b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
1342b287c6c7SBjoern A. Zeeb 		else
1343b287c6c7SBjoern A. Zeeb #endif
1344b287c6c7SBjoern A. Zeeb #ifdef INET
1345b287c6c7SBjoern A. Zeeb 		{
1346db33b3e6SAndre Oppermann 			if (th->th_dport == th->th_sport &&
1347a160e630SAndre Oppermann 			    ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1348a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1349a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13508d573cc1SAndre Oppermann 					"Connection attempt from/to self "
1351773673c1SAndre Oppermann 					"ignored\n", s, __func__);
1352302ce8d6SAndre Oppermann 				goto dropunlock;
1353a160e630SAndre Oppermann 			}
1354be2ac88cSJonathan Lemon 			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1355be2ac88cSJonathan Lemon 			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
13562ca2159fSCrist J. Clark 			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1357a160e630SAndre Oppermann 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1358a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1359a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13608d573cc1SAndre Oppermann 					"Connection attempt from/to broad- "
1361773673c1SAndre Oppermann 					"or multicast address ignored\n",
1362a160e630SAndre Oppermann 					s, __func__);
1363302ce8d6SAndre Oppermann 				goto dropunlock;
1364c068736aSJeffrey Hsu 			}
1365a160e630SAndre Oppermann 		}
1366b287c6c7SBjoern A. Zeeb #endif
1367be2ac88cSJonathan Lemon 		/*
1368db33b3e6SAndre Oppermann 		 * SYN appears to be valid.  Create compressed TCP state
1369db33b3e6SAndre Oppermann 		 * for syncache.
1370be2ac88cSJonathan Lemon 		 */
13713c653157SHartmut Brandt #ifdef TCPDEBUG
13723c653157SHartmut Brandt 		if (so->so_options & SO_DEBUG)
13733c653157SHartmut Brandt 			tcp_trace(TA_INPUT, ostate, tp,
13743c653157SHartmut Brandt 			    (void *)tcp_saveipgen, &tcp_savetcp, 0);
13753c653157SHartmut Brandt #endif
13762b9c9984SGeorge V. Neville-Neil 		TCP_PROBE3(debug__input, tp, th, m);
1377f72167f4SAndre Oppermann 		tcp_dooptions(&to, optp, optlen, TO_SYN);
13788d5719aaSGleb Smirnoff 		if ((so = syncache_add(&inc, &to, th, inp, so, m, NULL, NULL,
13799e644c23SMichael Tuexen 		    iptos, port)) != NULL)
138009c305ebSPatrick Kelsey 			goto tfo_socket_result;
138118a75309SPatrick Kelsey 
1382be2ac88cSJonathan Lemon 		/*
13834d6e7130SAndre Oppermann 		 * Entry added to syncache and mbuf consumed.
1384a7c7f2a7SJohn Baldwin 		 * Only the listen socket is unlocked by syncache_add().
1385be2ac88cSJonathan Lemon 		 */
13868f5a8818SKevin Lo 		return (IPPROTO_DONE);
1387982c1675SAndre Oppermann 	} else if (tp->t_state == TCPS_LISTEN) {
1388982c1675SAndre Oppermann 		/*
1389982c1675SAndre Oppermann 		 * When a listen socket is torn down the SO_ACCEPTCONN
1390982c1675SAndre Oppermann 		 * flag is removed first while connections are drained
1391982c1675SAndre Oppermann 		 * from the accept queue in a unlock/lock cycle of the
1392982c1675SAndre Oppermann 		 * ACCEPT_LOCK, opening a race condition allowing a SYN
1393982c1675SAndre Oppermann 		 * attempt go through unhandled.
1394982c1675SAndre Oppermann 		 */
1395982c1675SAndre Oppermann 		goto dropunlock;
1396f76fcf6dSJeffrey Hsu 	}
1397fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1398fcf59617SAndrey V. Elsukov 	if (tp->t_flags & TF_SIGNATURE) {
1399fcf59617SAndrey V. Elsukov 		tcp_dooptions(&to, optp, optlen, thflags);
1400fcf59617SAndrey V. Elsukov 		if ((to.to_flags & TOF_SIGNATURE) == 0) {
1401fcf59617SAndrey V. Elsukov 			TCPSTAT_INC(tcps_sig_err_nosigopt);
14022903309aSAttilio Rao 			goto dropunlock;
14032903309aSAttilio Rao 		}
1404fcf59617SAndrey V. Elsukov 		if (!TCPMD5_ENABLED() ||
1405fcf59617SAndrey V. Elsukov 		    TCPMD5_INPUT(m, th, to.to_signature) != 0)
1406fcf59617SAndrey V. Elsukov 			goto dropunlock;
14072903309aSAttilio Rao 	}
14082903309aSAttilio Rao #endif
14092b9c9984SGeorge V. Neville-Neil 	TCP_PROBE5(receive, NULL, tp, m, tp, th);
141057f60867SMark Johnston 
1411302ce8d6SAndre Oppermann 	/*
14128d573cc1SAndre Oppermann 	 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
14138d573cc1SAndre Oppermann 	 * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
14148d573cc1SAndre Oppermann 	 * the inpcb, and unlocks pcbinfo.
14151db08fbeSGleb Smirnoff 	 *
14161db08fbeSGleb Smirnoff 	 * XXXGL: in case of a pure SYN arriving on existing connection
14171db08fbeSGleb Smirnoff 	 * TCP stacks won't need to modify the PCB, they would either drop
14181db08fbeSGleb Smirnoff 	 * the segment silently, or send a challenge ACK.  However, we try
14191db08fbeSGleb Smirnoff 	 * to upgrade the lock, because calling convention for stacks is
14201db08fbeSGleb Smirnoff 	 * write-lock on PCB.  If upgrade fails, drop the SYN.
1421302ce8d6SAndre Oppermann 	 */
1422d88eb465SGleb Smirnoff 	if ((lookupflag & INPLOOKUP_RLOCKPCB) && INP_TRY_UPGRADE(inp) == 0)
14231db08fbeSGleb Smirnoff 		goto dropunlock;
14241db08fbeSGleb Smirnoff 
14256573d758SMatt Macy 	tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos);
14268f5a8818SKevin Lo 	return (IPPROTO_DONE);
1427be2ac88cSJonathan Lemon 
1428302ce8d6SAndre Oppermann dropwithreset:
14292b9c9984SGeorge V. Neville-Neil 	TCP_PROBE5(receive, NULL, tp, m, tp, th);
143057f60867SMark Johnston 
1431014ea782SRobert Watson 	if (inp != NULL) {
1432302ce8d6SAndre Oppermann 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
143308d9c920SGleb Smirnoff 		INP_UNLOCK(inp);
1434dd8ac7f9SRobert Watson 	} else
1435014ea782SRobert Watson 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1436302ce8d6SAndre Oppermann 	m = NULL;	/* mbuf chain got consumed. */
1437014ea782SRobert Watson 	goto drop;
1438014ea782SRobert Watson 
1439302ce8d6SAndre Oppermann dropunlock:
144057f60867SMark Johnston 	if (m != NULL)
14412b9c9984SGeorge V. Neville-Neil 		TCP_PROBE5(receive, NULL, tp, m, tp, th);
144257f60867SMark Johnston 
14439fa198beSAndre Oppermann 	if (inp != NULL)
144408d9c920SGleb Smirnoff 		INP_UNLOCK(inp);
1445014ea782SRobert Watson 
1446302ce8d6SAndre Oppermann drop:
1447a160e630SAndre Oppermann 	if (s != NULL)
1448a160e630SAndre Oppermann 		free(s, M_TCPLOG);
1449302ce8d6SAndre Oppermann 	if (m != NULL)
1450302ce8d6SAndre Oppermann 		m_freem(m);
14518f5a8818SKevin Lo 	return (IPPROTO_DONE);
1452302ce8d6SAndre Oppermann }
1453302ce8d6SAndre Oppermann 
1454e44c1887SSteven Hartland /*
1455e44c1887SSteven Hartland  * Automatic sizing of receive socket buffer.  Often the send
1456e44c1887SSteven Hartland  * buffer size is not optimally adjusted to the actual network
1457e44c1887SSteven Hartland  * conditions at hand (delay bandwidth product).  Setting the
1458e44c1887SSteven Hartland  * buffer size too small limits throughput on links with high
1459e44c1887SSteven Hartland  * bandwidth and high delay (eg. trans-continental/oceanic links).
1460e44c1887SSteven Hartland  *
1461e44c1887SSteven Hartland  * On the receive side the socket buffer memory is only rarely
1462e44c1887SSteven Hartland  * used to any significant extent.  This allows us to be much
1463e44c1887SSteven Hartland  * more aggressive in scaling the receive socket buffer.  For
1464e44c1887SSteven Hartland  * the case that the buffer space is actually used to a large
1465e44c1887SSteven Hartland  * extent and we run out of kernel memory we can simply drop
1466e44c1887SSteven Hartland  * the new segments; TCP on the sender will just retransmit it
1467e44c1887SSteven Hartland  * later.  Setting the buffer size too big may only consume too
1468e44c1887SSteven Hartland  * much kernel memory if the application doesn't read() from
1469e44c1887SSteven Hartland  * the socket or packet loss or reordering makes use of the
1470e44c1887SSteven Hartland  * reassembly queue.
1471e44c1887SSteven Hartland  *
1472e44c1887SSteven Hartland  * The criteria to step up the receive buffer one notch are:
1473e44c1887SSteven Hartland  *  1. Application has not set receive buffer size with
1474e44c1887SSteven Hartland  *     SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1475560c0586SMichael Tuexen  *  2. the number of bytes received during 1/2 of an sRTT
1476560c0586SMichael Tuexen  *     is at least 3/8 of the current socket buffer size.
1477560c0586SMichael Tuexen  *  3. receive buffer size has not hit maximal automatic size;
1478e44c1887SSteven Hartland  *
1479560c0586SMichael Tuexen  * If all of the criteria are met we increaset the socket buffer
1480560c0586SMichael Tuexen  * by a 1/2 (bounded by the max). This allows us to keep ahead
1481560c0586SMichael Tuexen  * of slow-start but also makes it so our peer never gets limited
1482560c0586SMichael Tuexen  * by our rwnd which we then open up causing a burst.
1483560c0586SMichael Tuexen  *
1484560c0586SMichael Tuexen  * This algorithm does two steps per RTT at most and only if
1485e44c1887SSteven Hartland  * we receive a bulk stream w/o packet losses or reorderings.
1486e44c1887SSteven Hartland  * Shrinking the buffer during idle times is not necessary as
1487e44c1887SSteven Hartland  * it doesn't consume any memory when idle.
1488e44c1887SSteven Hartland  *
1489e44c1887SSteven Hartland  * TODO: Only step up if the application is actually serving
1490e44c1887SSteven Hartland  * the buffer to better manage the socket buffer resources.
1491e44c1887SSteven Hartland  */
1492e44c1887SSteven Hartland int
1493e44c1887SSteven Hartland tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1494e44c1887SSteven Hartland     struct tcpcb *tp, int tlen)
1495e44c1887SSteven Hartland {
1496e44c1887SSteven Hartland 	int newsize = 0;
1497e44c1887SSteven Hartland 
1498e44c1887SSteven Hartland 	if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1499e44c1887SSteven Hartland 	    tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1500e44c1887SSteven Hartland 	    TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1501560c0586SMichael Tuexen 	    ((tp->t_srtt >> TCP_RTT_SHIFT)/2)) {
1502560c0586SMichael Tuexen 		if (tp->rfbuf_cnt > ((so->so_rcv.sb_hiwat / 2)/ 4 * 3) &&
1503e44c1887SSteven Hartland 		    so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1504560c0586SMichael Tuexen 			newsize = min((so->so_rcv.sb_hiwat + (so->so_rcv.sb_hiwat/2)), V_tcp_autorcvbuf_max);
1505e44c1887SSteven Hartland 		}
1506e44c1887SSteven Hartland 		TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1507e44c1887SSteven Hartland 
1508e44c1887SSteven Hartland 		/* Start over with next RTT. */
1509e44c1887SSteven Hartland 		tp->rfbuf_ts = 0;
1510e44c1887SSteven Hartland 		tp->rfbuf_cnt = 0;
1511e44c1887SSteven Hartland 	} else {
1512e44c1887SSteven Hartland 		tp->rfbuf_cnt += tlen;	/* add up */
1513e44c1887SSteven Hartland 	}
1514e44c1887SSteven Hartland 	return (newsize);
1515e44c1887SSteven Hartland }
1516e44c1887SSteven Hartland 
15179e644c23SMichael Tuexen int
15189e644c23SMichael Tuexen tcp_input(struct mbuf **mp, int *offp, int proto)
15199e644c23SMichael Tuexen {
15209e644c23SMichael Tuexen 	return(tcp_input_with_port(mp, offp, proto, 0));
15219e644c23SMichael Tuexen }
15229e644c23SMichael Tuexen 
152355bceb1eSRandall Stewart void
15244d0770f1SRichard Scheffenegger tcp_handle_wakeup(struct tcpcb *tp, struct socket *so)
15254d0770f1SRichard Scheffenegger {
15264d0770f1SRichard Scheffenegger 	/*
15274d0770f1SRichard Scheffenegger 	 * Since tp might be gone if the session entered
15284d0770f1SRichard Scheffenegger 	 * the TIME_WAIT state before coming here, we need
15294d0770f1SRichard Scheffenegger 	 * to check if the socket is still connected.
15304d0770f1SRichard Scheffenegger 	 */
1531032bf749SRichard Scheffenegger 	if (tp == NULL) {
15324d0770f1SRichard Scheffenegger 		return;
1533032bf749SRichard Scheffenegger 	}
1534032bf749SRichard Scheffenegger 	if (so == NULL) {
1535032bf749SRichard Scheffenegger 		return;
1536032bf749SRichard Scheffenegger 	}
15374d0770f1SRichard Scheffenegger 	INP_LOCK_ASSERT(tp->t_inpcb);
15384d0770f1SRichard Scheffenegger 	if (tp->t_flags & TF_WAKESOR) {
15394d0770f1SRichard Scheffenegger 		tp->t_flags &= ~TF_WAKESOR;
1540032bf749SRichard Scheffenegger 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1541032bf749SRichard Scheffenegger 		sorwakeup_locked(so);
15424d0770f1SRichard Scheffenegger 	}
15434d0770f1SRichard Scheffenegger }
15444d0770f1SRichard Scheffenegger 
15454d0770f1SRichard Scheffenegger void
1546302ce8d6SAndre Oppermann tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
15476573d758SMatt Macy     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos)
1548302ce8d6SAndre Oppermann {
1549f7220c48SRichard Scheffenegger 	uint16_t thflags;
1550f7220c48SRichard Scheffenegger 	int acked, ourfinisacked, needoutput = 0, sack_changed;
1551b2ade6b1SRichard Scheffenegger 	int rstreason, todrop, win, incforsyn = 0;
15523ac12506SJonathan T. Looney 	uint32_t tiwin;
15534b7b743cSLawrence Stewart 	uint16_t nsegs;
155407dacf03SAndre Oppermann 	char *s;
155507dacf03SAndre Oppermann 	struct in_conninfo *inc;
1556c11a15bfSGleb Smirnoff 	struct mbuf *mfree;
1557302ce8d6SAndre Oppermann 	struct tcpopt to;
1558281a0fd4SPatrick Kelsey 	int tfo_syn;
15593c40e1d5SRichard Scheffenegger 	u_int maxseg;
1560302ce8d6SAndre Oppermann 
156114739780SMaxim Konovalov #ifdef TCPDEBUG
156214739780SMaxim Konovalov 	/*
156314739780SMaxim Konovalov 	 * The size of tcp_saveipgen must be the size of the max ip header,
156414739780SMaxim Konovalov 	 * now IPv6.
156514739780SMaxim Konovalov 	 */
156614739780SMaxim Konovalov 	u_char tcp_saveipgen[IP6_HDR_LEN];
156714739780SMaxim Konovalov 	struct tcphdr tcp_savetcp;
156814739780SMaxim Konovalov 	short ostate = 0;
156914739780SMaxim Konovalov #endif
15701ebf4607SRichard Scheffenegger 	thflags = tcp_get_flags(th);
157107dacf03SAndre Oppermann 	inc = &tp->t_inpcb->inp_inc;
1572d64a46eaSLawrence Stewart 	tp->sackhint.last_sack_ack = 0;
1573021eaf79SHiren Panchasara 	sack_changed = 0;
15744b7b743cSLawrence Stewart 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
1575d40c0d47SGleb Smirnoff 
1576d40c0d47SGleb Smirnoff 	NET_EPOCH_ASSERT();
15778501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
1578679d9708SAndre Oppermann 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1579679d9708SAndre Oppermann 	    __func__));
1580679d9708SAndre Oppermann 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1581679d9708SAndre Oppermann 	    __func__));
1582df8bae1dSRodney W. Grimes 
158386a996e6SHiren Panchasara #ifdef TCPPCAP
158486a996e6SHiren Panchasara 	/* Save segment, if requested. */
158586a996e6SHiren Panchasara 	tcp_pcap_add(th, m, &(tp->t_inpkts));
158686a996e6SHiren Panchasara #endif
15872529f56eSJonathan T. Looney 	TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
15882529f56eSJonathan T. Looney 	    tlen, NULL, true);
158986a996e6SHiren Panchasara 
1590013f4df6SMichael Tuexen 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1591013f4df6SMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1592013f4df6SMichael Tuexen 			log(LOG_DEBUG, "%s; %s: "
1593013f4df6SMichael Tuexen 			    "SYN|FIN segment ignored (based on "
1594013f4df6SMichael Tuexen 			    "sysctl setting)\n", s, __func__);
1595013f4df6SMichael Tuexen 			free(s, M_TCPLOG);
1596013f4df6SMichael Tuexen 		}
1597013f4df6SMichael Tuexen 		goto drop;
1598013f4df6SMichael Tuexen 	}
1599013f4df6SMichael Tuexen 
1600df8bae1dSRodney W. Grimes 	/*
1601ebfd7534SMichael Tuexen 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1602ebfd7534SMichael Tuexen 	 * check SEQ.ACK first.
1603ebfd7534SMichael Tuexen 	 */
1604ebfd7534SMichael Tuexen 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1605ebfd7534SMichael Tuexen 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1606ebfd7534SMichael Tuexen 		rstreason = BANDLIM_UNLIMITED;
1607d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
1608ebfd7534SMichael Tuexen 		goto dropwithreset;
1609ebfd7534SMichael Tuexen 	}
1610ebfd7534SMichael Tuexen 
1611ebfd7534SMichael Tuexen 	/*
1612df8bae1dSRodney W. Grimes 	 * Segment received on connection.
1613df8bae1dSRodney W. Grimes 	 * Reset idle time and keep-alive timer.
1614e8949f74SAndre Oppermann 	 * XXX: This should be done after segment
1615e8949f74SAndre Oppermann 	 * validation to ignore broken/spoofed segs.
1616df8bae1dSRodney W. Grimes 	 */
1617cd84e78fSRandall Stewart 	if  (tp->t_idle_reduce &&
1618cd84e78fSRandall Stewart 	     (tp->snd_max == tp->snd_una) &&
1619cd84e78fSRandall Stewart 	     ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
1620cd84e78fSRandall Stewart 		cc_after_idle(tp);
16219b8b58e0SJonathan Lemon 	tp->t_rcvtime = ticks;
1622df8bae1dSRodney W. Grimes 
1623d1b07f36SRandall Stewart 	if (thflags & TH_FIN)
1624d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
1625df8bae1dSRodney W. Grimes 	/*
1626c52102ddSHiren Panchasara 	 * Scale up the window into a 32-bit value.
1627e8949f74SAndre Oppermann 	 * For the SYN_SENT state the scale is zero.
1628464fcfbcSAndre Oppermann 	 */
1629464fcfbcSAndre Oppermann 	tiwin = th->th_win << tp->snd_scale;
1630adc56f5aSEdward Tomasz Napierala #ifdef STATS
1631adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
1632adc56f5aSEdward Tomasz Napierala #endif
1633464fcfbcSAndre Oppermann 
1634464fcfbcSAndre Oppermann 	/*
1635f2512ba1SRui Paulo 	 * TCP ECN processing.
1636f2512ba1SRui Paulo 	 */
1637f7220c48SRichard Scheffenegger 	if (tcp_ecn_input_segment(tp, thflags, iptos))
1638dbc42409SLawrence Stewart 		cc_cong_signal(tp, th, CC_ECN);
1639f2512ba1SRui Paulo 
1640f2512ba1SRui Paulo 	/*
1641f72167f4SAndre Oppermann 	 * Parse options on any incoming segment.
1642f72167f4SAndre Oppermann 	 */
1643302ce8d6SAndre Oppermann 	tcp_dooptions(&to, (u_char *)(th + 1),
1644302ce8d6SAndre Oppermann 	    (th->th_off << 2) - sizeof(struct tcphdr),
1645302ce8d6SAndre Oppermann 	    (thflags & TH_SYN) ? TO_SYN : 0);
1646f72167f4SAndre Oppermann 
1647fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1648fcf59617SAndrey V. Elsukov 	if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1649fcf59617SAndrey V. Elsukov 	    (to.to_flags & TOF_SIGNATURE) == 0) {
1650fcf59617SAndrey V. Elsukov 		TCPSTAT_INC(tcps_sig_err_sigopt);
1651fcf59617SAndrey V. Elsukov 		/* XXX: should drop? */
1652fcf59617SAndrey V. Elsukov 	}
1653fcf59617SAndrey V. Elsukov #endif
1654f72167f4SAndre Oppermann 	/*
1655f72167f4SAndre Oppermann 	 * If echoed timestamp is later than the current time,
1656bf6d304aSAndre Oppermann 	 * fall back to non RFC1323 RTT calculation.  Normalize
1657bf6d304aSAndre Oppermann 	 * timestamp if syncookies were used when this connection
1658bf6d304aSAndre Oppermann 	 * was established.
1659f72167f4SAndre Oppermann 	 */
1660bf6d304aSAndre Oppermann 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1661e16fa5caSJohn-Mark Gurney 		to.to_tsecr -= tp->ts_offset;
1662d8951c8aSBjoern A. Zeeb 		if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1663f72167f4SAndre Oppermann 			to.to_tsecr = 0;
16644531b345SRichard Scheffenegger 		else if (tp->t_rxtshift == 1 &&
16654531b345SRichard Scheffenegger 			 tp->t_flags & TF_PREVVALID &&
16664531b345SRichard Scheffenegger 			 tp->t_badrxtwin != 0 &&
16674531b345SRichard Scheffenegger 			 TSTMP_LT(to.to_tsecr, tp->t_badrxtwin))
166810d20c84SMatt Macy 			cc_cong_signal(tp, th, CC_RTO_ERR);
1669bf6d304aSAndre Oppermann 	}
167007dacf03SAndre Oppermann 	/*
167197d8d152SAndre Oppermann 	 * Process options only when we get SYN/ACK back. The SYN case
167297d8d152SAndre Oppermann 	 * for incoming connections is handled in tcp_syncache.
16735396d0f8SAndre Oppermann 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
16745396d0f8SAndre Oppermann 	 * or <SYN,ACK>) segment itself is never scaled.
167597d8d152SAndre Oppermann 	 * XXX this is traditional behavior, may need to be cleaned up.
1676df8bae1dSRodney W. Grimes 	 */
16770a389eabSSimon L. B. Nielsen 	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
16786e16d877SRichard Scheffenegger 		/* Handle parallel SYN for ECN */
1679f7220c48SRichard Scheffenegger 		tcp_ecn_input_parallel_syn(tp, thflags, iptos);
1680464fcfbcSAndre Oppermann 		if ((to.to_flags & TOF_SCALE) &&
16812593f858SRichard Scheffenegger 		    (tp->t_flags & TF_REQ_SCALE) &&
16822593f858SRichard Scheffenegger 		    !(tp->t_flags & TF_NOOPT)) {
1683be2ac88cSJonathan Lemon 			tp->t_flags |= TF_RCVD_SCALE;
168402a1a643SAndre Oppermann 			tp->snd_scale = to.to_wscale;
16858e051165SRichard Scheffenegger 		} else
16868e051165SRichard Scheffenegger 			tp->t_flags &= ~TF_REQ_SCALE;
16875396d0f8SAndre Oppermann 		/*
16885396d0f8SAndre Oppermann 		 * Initial send window.  It will be updated with
16895396d0f8SAndre Oppermann 		 * the next incoming segment to the scaled value.
16905396d0f8SAndre Oppermann 		 */
16915396d0f8SAndre Oppermann 		tp->snd_wnd = th->th_win;
16928e051165SRichard Scheffenegger 		if ((to.to_flags & TOF_TS) &&
16932593f858SRichard Scheffenegger 		    (tp->t_flags & TF_REQ_TSTMP) &&
16942593f858SRichard Scheffenegger 		    !(tp->t_flags & TF_NOOPT)) {
1695be2ac88cSJonathan Lemon 			tp->t_flags |= TF_RCVD_TSTMP;
1696be2ac88cSJonathan Lemon 			tp->ts_recent = to.to_tsval;
1697d8951c8aSBjoern A. Zeeb 			tp->ts_recent_age = tcp_ts_getticks();
16988e051165SRichard Scheffenegger 		} else
16998e051165SRichard Scheffenegger 			tp->t_flags &= ~TF_REQ_TSTMP;
1700be2ac88cSJonathan Lemon 		if (to.to_flags & TOF_MSS)
1701be2ac88cSJonathan Lemon 			tcp_mss(tp, to.to_mss);
17023529149eSAndre Oppermann 		if ((tp->t_flags & TF_SACK_PERMIT) &&
17032593f858SRichard Scheffenegger 		    (!(to.to_flags & TOF_SACKPERM) ||
17042593f858SRichard Scheffenegger 		    (tp->t_flags & TF_NOOPT)))
17053529149eSAndre Oppermann 			tp->t_flags &= ~TF_SACK_PERMIT;
1706c560df6fSPatrick Kelsey 		if (IS_FASTOPEN(tp->t_flags)) {
17072593f858SRichard Scheffenegger 			if ((to.to_flags & TOF_FASTOPEN) &&
17082593f858SRichard Scheffenegger 			    !(tp->t_flags & TF_NOOPT)) {
1709a026a53aSMichael Tuexen 				uint16_t mss;
1710a026a53aSMichael Tuexen 
1711a026a53aSMichael Tuexen 				if (to.to_flags & TOF_MSS)
1712a026a53aSMichael Tuexen 					mss = to.to_mss;
1713c560df6fSPatrick Kelsey 				else
1714a026a53aSMichael Tuexen 					if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
1715a026a53aSMichael Tuexen 						mss = TCP6_MSS;
1716a026a53aSMichael Tuexen 					else
1717a026a53aSMichael Tuexen 						mss = TCP_MSS;
1718a026a53aSMichael Tuexen 				tcp_fastopen_update_cache(tp, mss,
1719a026a53aSMichael Tuexen 				    to.to_tfo_len, to.to_tfo_cookie);
1720a026a53aSMichael Tuexen 			} else
1721c560df6fSPatrick Kelsey 				tcp_fastopen_disable_path(tp);
1722c560df6fSPatrick Kelsey 		}
17236d90faf3SPaul Saab 	}
17246d90faf3SPaul Saab 
1725df8bae1dSRodney W. Grimes 	/*
1726283c76c7SMichael Tuexen 	 * If timestamps were negotiated during SYN/ACK and a
1727283c76c7SMichael Tuexen 	 * segment without a timestamp is received, silently drop
1728d2b3ceddSMichael Tuexen 	 * the segment, unless it is a RST segment or missing timestamps are
1729d2b3ceddSMichael Tuexen 	 * tolerated.
1730283c76c7SMichael Tuexen 	 * See section 3.2 of RFC 7323.
17314da9052aSMichael Tuexen 	 */
17324da9052aSMichael Tuexen 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1733d2b3ceddSMichael Tuexen 		if (((thflags & TH_RST) != 0) || V_tcp_tolerate_missing_ts) {
1734cc3c3485SMichael Tuexen 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1735cc3c3485SMichael Tuexen 				log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1736cc3c3485SMichael Tuexen 				    "segment processed normally\n",
1737cc3c3485SMichael Tuexen 				    s, __func__);
1738cc3c3485SMichael Tuexen 				free(s, M_TCPLOG);
1739cc3c3485SMichael Tuexen 			}
1740cc3c3485SMichael Tuexen 		} else {
17414da9052aSMichael Tuexen 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
17424da9052aSMichael Tuexen 				log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1743283c76c7SMichael Tuexen 				    "segment silently dropped\n", s, __func__);
17444da9052aSMichael Tuexen 				free(s, M_TCPLOG);
17454da9052aSMichael Tuexen 			}
1746283c76c7SMichael Tuexen 			goto drop;
17474da9052aSMichael Tuexen 		}
1748cc3c3485SMichael Tuexen 	}
1749283c76c7SMichael Tuexen 	/*
1750283c76c7SMichael Tuexen 	 * If timestamps were not negotiated during SYN/ACK and a
175175fcd27aSMichael Tuexen 	 * segment with a timestamp is received, ignore the
1752283c76c7SMichael Tuexen 	 * timestamp and process the packet normally.
1753283c76c7SMichael Tuexen 	 * See section 3.2 of RFC 7323.
1754283c76c7SMichael Tuexen 	 */
17554da9052aSMichael Tuexen 	if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
17564da9052aSMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
17574da9052aSMichael Tuexen 			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1758283c76c7SMichael Tuexen 			    "segment processed normally\n", s, __func__);
17594da9052aSMichael Tuexen 			free(s, M_TCPLOG);
17604da9052aSMichael Tuexen 		}
17614da9052aSMichael Tuexen 	}
17624da9052aSMichael Tuexen 
17634da9052aSMichael Tuexen 	/*
1764df8bae1dSRodney W. Grimes 	 * Header prediction: check for the two common cases
1765df8bae1dSRodney W. Grimes 	 * of a uni-directional data xfer.  If the packet has
1766df8bae1dSRodney W. Grimes 	 * no control flags, is in-sequence, the window didn't
1767df8bae1dSRodney W. Grimes 	 * change and we're not retransmitting, it's a
1768df8bae1dSRodney W. Grimes 	 * candidate.  If the length is zero and the ack moved
1769df8bae1dSRodney W. Grimes 	 * forward, we're the sender side of the xfer.  Just
1770df8bae1dSRodney W. Grimes 	 * free the data acked & wake any higher level process
1771df8bae1dSRodney W. Grimes 	 * that was blocked waiting for space.  If the length
1772df8bae1dSRodney W. Grimes 	 * is non-zero and the ack didn't move, we're the
1773df8bae1dSRodney W. Grimes 	 * receiver side.  If we're getting packets in-order
1774df8bae1dSRodney W. Grimes 	 * (the reassembly queue is empty), add the data to
1775df8bae1dSRodney W. Grimes 	 * the socket buffer and note that we need a delayed ack.
1776a0292f23SGarrett Wollman 	 * Make sure that the hidden state-flags are also off.
1777c5ad39b9SAndre Oppermann 	 * Since we check for TCPS_ESTABLISHED first, it can only
1778a0292f23SGarrett Wollman 	 * be TH_NEEDSYN.
1779df8bae1dSRodney W. Grimes 	 */
1780df8bae1dSRodney W. Grimes 	if (tp->t_state == TCPS_ESTABLISHED &&
1781c5ad39b9SAndre Oppermann 	    th->th_seq == tp->rcv_nxt &&
1782fb59c426SYoshinobu Inoue 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1783c5ad39b9SAndre Oppermann 	    tp->snd_nxt == tp->snd_max &&
1784c5ad39b9SAndre Oppermann 	    tiwin && tiwin == tp->snd_wnd &&
1785a0292f23SGarrett Wollman 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1786c28440dbSRandall Stewart 	    SEGQ_EMPTY(tp) &&
17874741bfcbSPatrick Kelsey 	    ((to.to_flags & TOF_TS) == 0 ||
1788c5ad39b9SAndre Oppermann 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1789df8bae1dSRodney W. Grimes 		/*
1790df8bae1dSRodney W. Grimes 		 * If last ACK falls within this segment's sequence numbers,
1791df8bae1dSRodney W. Grimes 		 * record the timestamp.
1792a0292f23SGarrett Wollman 		 * NOTE that the test is modified according to the latest
1793a0292f23SGarrett Wollman 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1794df8bae1dSRodney W. Grimes 		 */
1795be2ac88cSJonathan Lemon 		if ((to.to_flags & TOF_TS) != 0 &&
1796fb59c426SYoshinobu Inoue 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1797d8951c8aSBjoern A. Zeeb 			tp->ts_recent_age = tcp_ts_getticks();
1798a0292f23SGarrett Wollman 			tp->ts_recent = to.to_tsval;
1799df8bae1dSRodney W. Grimes 		}
1800df8bae1dSRodney W. Grimes 
1801fb59c426SYoshinobu Inoue 		if (tlen == 0) {
1802fb59c426SYoshinobu Inoue 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1803fb59c426SYoshinobu Inoue 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1804dbc42409SLawrence Stewart 			    !IN_RECOVERY(tp->t_flags) &&
1805fc30a251SAndre Oppermann 			    (to.to_flags & TOF_SACK) == 0 &&
1806dbc42409SLawrence Stewart 			    TAILQ_EMPTY(&tp->snd_holes)) {
1807df8bae1dSRodney W. Grimes 				/*
1808e8949f74SAndre Oppermann 				 * This is a pure ack for outstanding data.
1809df8bae1dSRodney W. Grimes 				 */
181078b50714SRobert Watson 				TCPSTAT_INC(tcps_predack);
1811252ca428SRobert Watson 
18129b8b58e0SJonathan Lemon 				/*
181310d20c84SMatt Macy 				 * "bad retransmit" recovery without timestamps.
18149b8b58e0SJonathan Lemon 				 */
181510d20c84SMatt Macy 				if ((to.to_flags & TOF_TS) == 0 &&
181610d20c84SMatt Macy 				    tp->t_rxtshift == 1 &&
1817672dc4aeSJohn Baldwin 				    tp->t_flags & TF_PREVVALID &&
18184531b345SRichard Scheffenegger 				    tp->t_badrxtwin != 0 &&
18194531b345SRichard Scheffenegger 				    TSTMP_LT(ticks, tp->t_badrxtwin)) {
1820dbc42409SLawrence Stewart 					cc_cong_signal(tp, th, CC_RTO_ERR);
18219b8b58e0SJonathan Lemon 				}
1822fa55172bSMatthew Dillon 
1823fa55172bSMatthew Dillon 				/*
1824fa55172bSMatthew Dillon 				 * Recalculate the transmit timer / rtt.
1825fa55172bSMatthew Dillon 				 *
1826fa55172bSMatthew Dillon 				 * Some boxes send broken timestamp replies
1827fa55172bSMatthew Dillon 				 * during the SYN+ACK phase, ignore
1828fa55172bSMatthew Dillon 				 * timestamps of 0 or we could calculate a
1829fa55172bSMatthew Dillon 				 * huge RTT and blow up the retransmit timer.
1830fa55172bSMatthew Dillon 				 */
1831fa55172bSMatthew Dillon 				if ((to.to_flags & TOF_TS) != 0 &&
1832fa55172bSMatthew Dillon 				    to.to_tsecr) {
18333ac12506SJonathan T. Looney 					uint32_t t;
1834d8951c8aSBjoern A. Zeeb 
1835d8951c8aSBjoern A. Zeeb 					t = tcp_ts_getticks() - to.to_tsecr;
1836d8951c8aSBjoern A. Zeeb 					if (!tp->t_rttlow || tp->t_rttlow > t)
1837d8951c8aSBjoern A. Zeeb 						tp->t_rttlow = t;
1838a0292f23SGarrett Wollman 					tcp_xmit_timer(tp,
1839d8951c8aSBjoern A. Zeeb 					    TCP_TS_TO_TICKS(t) + 1);
1840fa55172bSMatthew Dillon 				} else if (tp->t_rtttime &&
1841fa55172bSMatthew Dillon 				    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1842eaf80179SAndre Oppermann 					if (!tp->t_rttlow ||
1843eaf80179SAndre Oppermann 					    tp->t_rttlow > ticks - tp->t_rtttime)
1844eaf80179SAndre Oppermann 						tp->t_rttlow = ticks - tp->t_rtttime;
1845c068736aSJeffrey Hsu 					tcp_xmit_timer(tp,
1846c068736aSJeffrey Hsu 							ticks - tp->t_rtttime);
1847fa55172bSMatthew Dillon 				}
1848dbc42409SLawrence Stewart 				acked = BYTES_THIS_ACK(tp, th);
184939bc9de5SLawrence Stewart 
1850bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
185139bc9de5SLawrence Stewart 				/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
185239bc9de5SLawrence Stewart 				hhook_run_tcp_est_in(tp, th, &to);
1853bd79708dSJonathan T. Looney #endif
185439bc9de5SLawrence Stewart 
18554b7b743cSLawrence Stewart 				TCPSTAT_ADD(tcps_rcvackpack, nsegs);
185678b50714SRobert Watson 				TCPSTAT_ADD(tcps_rcvackbyte, acked);
1857df8bae1dSRodney W. Grimes 				sbdrop(&so->so_snd, acked);
18589d11646dSJeffrey Hsu 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
18599d11646dSJeffrey Hsu 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
18609d11646dSJeffrey Hsu 					tp->snd_recover = th->th_ack - 1;
1861dbc42409SLawrence Stewart 
1862dbc42409SLawrence Stewart 				/*
1863dbc42409SLawrence Stewart 				 * Let the congestion control algorithm update
1864dbc42409SLawrence Stewart 				 * congestion control related information. This
1865dbc42409SLawrence Stewart 				 * typically means increasing the congestion
1866dbc42409SLawrence Stewart 				 * window.
1867dbc42409SLawrence Stewart 				 */
18684b7b743cSLawrence Stewart 				cc_ack_received(tp, th, nsegs, CC_ACK);
1869dbc42409SLawrence Stewart 
18709d11646dSJeffrey Hsu 				tp->snd_una = th->th_ack;
18711645d090SJeff Roberson 				/*
1872e8949f74SAndre Oppermann 				 * Pull snd_wl2 up to prevent seq wrap relative
18731645d090SJeff Roberson 				 * to th_ack.
18741645d090SJeff Roberson 				 */
1875cb942153SJeffrey Hsu 				tp->snd_wl2 = th->th_ack;
1876b5addd85SJeffrey Hsu 				tp->t_dupacks = 0;
1877df8bae1dSRodney W. Grimes 				m_freem(m);
1878df8bae1dSRodney W. Grimes 
1879df8bae1dSRodney W. Grimes 				/*
1880df8bae1dSRodney W. Grimes 				 * If all outstanding data are acked, stop
1881df8bae1dSRodney W. Grimes 				 * retransmit timer, otherwise restart timer
1882df8bae1dSRodney W. Grimes 				 * using current (possibly backed-off) value.
1883df8bae1dSRodney W. Grimes 				 * If process is waiting for space,
1884df8bae1dSRodney W. Grimes 				 * wakeup/selwakeup/signal.  If data
1885df8bae1dSRodney W. Grimes 				 * are ready to send, let tcp_output
1886df8bae1dSRodney W. Grimes 				 * decide between more output or persist.
1887e8949f74SAndre Oppermann 				 */
18883c653157SHartmut Brandt #ifdef TCPDEBUG
18893c653157SHartmut Brandt 				if (so->so_options & SO_DEBUG)
18903c653157SHartmut Brandt 					tcp_trace(TA_INPUT, ostate, tp,
18913c653157SHartmut Brandt 					    (void *)tcp_saveipgen,
18923c653157SHartmut Brandt 					    &tcp_savetcp, 0);
18933c653157SHartmut Brandt #endif
18942b9c9984SGeorge V. Neville-Neil 				TCP_PROBE3(debug__input, tp, th, m);
189508af8aacSRandall Stewart 				/*
189608af8aacSRandall Stewart 				 * Clear t_acktime if remote side has ACKd
189708af8aacSRandall Stewart 				 * all data in the socket buffer.
189808af8aacSRandall Stewart 				 * Otherwise, update t_acktime if we received
189908af8aacSRandall Stewart 				 * a sufficiently large ACK.
190008af8aacSRandall Stewart 				 */
190108af8aacSRandall Stewart 				if (sbavail(&so->so_snd) == 0)
190208af8aacSRandall Stewart 					tp->t_acktime = 0;
190308af8aacSRandall Stewart 				else if (acked > 1)
190408af8aacSRandall Stewart 					tp->t_acktime = ticks;
1905df8bae1dSRodney W. Grimes 				if (tp->snd_una == tp->snd_max)
1906b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT, 0);
1907b8152ba7SAndre Oppermann 				else if (!tcp_timer_active(tp, TT_PERSIST))
1908b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT,
190908af8aacSRandall Stewart 					    TP_RXTCUR(tp));
1910032bf749SRichard Scheffenegger 				sowwakeup(so);
1911cfa6009eSGleb Smirnoff 				if (sbavail(&so->so_snd))
191240fa3e40SGleb Smirnoff 					(void) tcp_output(tp);
1913a14c749fSJonathan Lemon 				goto check_delack;
1914df8bae1dSRodney W. Grimes 			}
1915fb59c426SYoshinobu Inoue 		} else if (th->th_ack == tp->snd_una &&
1916fb59c426SYoshinobu Inoue 		    tlen <= sbspace(&so->so_rcv)) {
19176741ecf5SAndre Oppermann 			int newsize = 0;	/* automatic sockbuf scaling */
19186741ecf5SAndre Oppermann 
1919df8bae1dSRodney W. Grimes 			/*
1920252ca428SRobert Watson 			 * This is a pure, in-sequence data packet with
1921252ca428SRobert Watson 			 * nothing on the reassembly queue and we have enough
1922252ca428SRobert Watson 			 * buffer space to take it.
1923df8bae1dSRodney W. Grimes 			 */
19246d90faf3SPaul Saab 			/* Clean receiver SACK report if present */
19253529149eSAndre Oppermann 			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
19266d90faf3SPaul Saab 				tcp_clean_sackreport(tp);
192778b50714SRobert Watson 			TCPSTAT_INC(tcps_preddat);
1928fb59c426SYoshinobu Inoue 			tp->rcv_nxt += tlen;
1929e854dd38SRandall Stewart 			if (tlen &&
1930e854dd38SRandall Stewart 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
1931e854dd38SRandall Stewart 			    (tp->t_fbyte_in == 0)) {
1932e854dd38SRandall Stewart 				tp->t_fbyte_in = ticks;
1933e854dd38SRandall Stewart 				if (tp->t_fbyte_in == 0)
1934e854dd38SRandall Stewart 					tp->t_fbyte_in = 1;
1935e854dd38SRandall Stewart 				if (tp->t_fbyte_out && tp->t_fbyte_in)
1936e854dd38SRandall Stewart 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
1937e854dd38SRandall Stewart 			}
19381645d090SJeff Roberson 			/*
19391645d090SJeff Roberson 			 * Pull snd_wl1 up to prevent seq wrap relative to
19401645d090SJeff Roberson 			 * th_seq.
19411645d090SJeff Roberson 			 */
194260ee3bb2SAndre Oppermann 			tp->snd_wl1 = th->th_seq;
19431645d090SJeff Roberson 			/*
19441645d090SJeff Roberson 			 * Pull rcv_up up to prevent seq wrap relative to
19451645d090SJeff Roberson 			 * rcv_nxt.
19461645d090SJeff Roberson 			 */
19471645d090SJeff Roberson 			tp->rcv_up = tp->rcv_nxt;
19484b7b743cSLawrence Stewart 			TCPSTAT_ADD(tcps_rcvpack, nsegs);
194978b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
19503c653157SHartmut Brandt #ifdef TCPDEBUG
19513c653157SHartmut Brandt 			if (so->so_options & SO_DEBUG)
19523c653157SHartmut Brandt 				tcp_trace(TA_INPUT, ostate, tp,
19533c653157SHartmut Brandt 				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
19543c653157SHartmut Brandt #endif
19552b9c9984SGeorge V. Neville-Neil 			TCP_PROBE3(debug__input, tp, th, m);
19565d06879aSGeorge V. Neville-Neil 
1957e44c1887SSteven Hartland 			newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
19586741ecf5SAndre Oppermann 
19596741ecf5SAndre Oppermann 			/* Add data to socket buffer. */
19601e4d7da7SRobert Watson 			SOCKBUF_LOCK(&so->so_rcv);
1961c0b99ffaSRobert Watson 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1962c1c36a2cSMike Silbersack 				m_freem(m);
1963c1c36a2cSMike Silbersack 			} else {
19646741ecf5SAndre Oppermann 				/*
19656741ecf5SAndre Oppermann 				 * Set new socket buffer size.
19666741ecf5SAndre Oppermann 				 * Give up when limit is reached.
19676741ecf5SAndre Oppermann 				 */
19686741ecf5SAndre Oppermann 				if (newsize)
196943283184SGleb Smirnoff 					if (!sbreserve_locked(so, SO_RCV,
197043283184SGleb Smirnoff 					    newsize, NULL))
19716741ecf5SAndre Oppermann 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1972fb59c426SYoshinobu Inoue 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1973651e4e6aSGleb Smirnoff 				sbappendstream_locked(&so->so_rcv, m, 0);
1974c1c36a2cSMike Silbersack 			}
1975032bf749SRichard Scheffenegger 			/* NB: sorwakeup_locked() does an implicit unlock. */
1976032bf749SRichard Scheffenegger 			sorwakeup_locked(so);
1977c1e5a6e5SAndre Oppermann 			if (DELAY_ACK(tp, tlen)) {
19783bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
1979f498eeeeSDavid Greenman 			} else {
1980e612a582SDavid Greenman 				tp->t_flags |= TF_ACKNOW;
198140fa3e40SGleb Smirnoff 				tcp_output(tp);
1982e612a582SDavid Greenman 			}
1983a14c749fSJonathan Lemon 			goto check_delack;
1984df8bae1dSRodney W. Grimes 		}
1985df8bae1dSRodney W. Grimes 	}
1986df8bae1dSRodney W. Grimes 
1987df8bae1dSRodney W. Grimes 	/*
1988df8bae1dSRodney W. Grimes 	 * Calculate amount of space in receive window,
1989df8bae1dSRodney W. Grimes 	 * and then do TCP input processing.
1990df8bae1dSRodney W. Grimes 	 * Receive window is amount of space in rcv queue,
1991df8bae1dSRodney W. Grimes 	 * but not less than advertised window.
1992df8bae1dSRodney W. Grimes 	 */
1993df8bae1dSRodney W. Grimes 	win = sbspace(&so->so_rcv);
1994df8bae1dSRodney W. Grimes 	if (win < 0)
1995df8bae1dSRodney W. Grimes 		win = 0;
199666e39adcSJohn Polstra 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1997df8bae1dSRodney W. Grimes 
1998df8bae1dSRodney W. Grimes 	switch (tp->t_state) {
1999df8bae1dSRodney W. Grimes 	/*
2000764d8cefSBill Fenner 	 * If the state is SYN_RECEIVED:
2001764d8cefSBill Fenner 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
2002764d8cefSBill Fenner 	 */
2003764d8cefSBill Fenner 	case TCPS_SYN_RECEIVED:
2004fb59c426SYoshinobu Inoue 		if ((thflags & TH_ACK) &&
2005fb59c426SYoshinobu Inoue 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
2006a57815efSBosko Milekic 		     SEQ_GT(th->th_ack, tp->snd_max))) {
2007a57815efSBosko Milekic 				rstreason = BANDLIM_RST_OPENPORT;
2008d1b07f36SRandall Stewart 				tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2009a57815efSBosko Milekic 				goto dropwithreset;
2010a57815efSBosko Milekic 		}
201168bd7ed1SJonathan T. Looney 		if (IS_FASTOPEN(tp->t_flags)) {
2012281a0fd4SPatrick Kelsey 			/*
2013281a0fd4SPatrick Kelsey 			 * When a TFO connection is in SYN_RECEIVED, the
2014281a0fd4SPatrick Kelsey 			 * only valid packets are the initial SYN, a
2015281a0fd4SPatrick Kelsey 			 * retransmit/copy of the initial SYN (possibly with
2016281a0fd4SPatrick Kelsey 			 * a subset of the original data), a valid ACK, a
2017281a0fd4SPatrick Kelsey 			 * FIN, or a RST.
2018281a0fd4SPatrick Kelsey 			 */
2019281a0fd4SPatrick Kelsey 			if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
2020281a0fd4SPatrick Kelsey 				rstreason = BANDLIM_RST_OPENPORT;
2021d1b07f36SRandall Stewart 				tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2022281a0fd4SPatrick Kelsey 				goto dropwithreset;
2023281a0fd4SPatrick Kelsey 			} else if (thflags & TH_SYN) {
2024281a0fd4SPatrick Kelsey 				/* non-initial SYN is ignored */
2025281a0fd4SPatrick Kelsey 				if ((tcp_timer_active(tp, TT_DELACK) ||
2026281a0fd4SPatrick Kelsey 				     tcp_timer_active(tp, TT_REXMT)))
2027281a0fd4SPatrick Kelsey 					goto drop;
2028281a0fd4SPatrick Kelsey 			} else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
2029281a0fd4SPatrick Kelsey 				goto drop;
2030281a0fd4SPatrick Kelsey 			}
2031281a0fd4SPatrick Kelsey 		}
2032764d8cefSBill Fenner 		break;
2033764d8cefSBill Fenner 
2034764d8cefSBill Fenner 	/*
2035df8bae1dSRodney W. Grimes 	 * If the state is SYN_SENT:
203698732609SMichael Tuexen 	 *	if seg contains a RST with valid ACK (SEQ.ACK has already
203798732609SMichael Tuexen 	 *	    been verified), then drop the connection.
203898732609SMichael Tuexen 	 *	if seg contains a RST without an ACK, drop the seg.
203998732609SMichael Tuexen 	 *	if seg does not contain SYN, then drop the seg.
2040df8bae1dSRodney W. Grimes 	 * Otherwise this is an acceptable SYN segment
2041df8bae1dSRodney W. Grimes 	 *	initialize tp->rcv_nxt and tp->irs
2042df8bae1dSRodney W. Grimes 	 *	if seg contains ack then advance tp->snd_una
2043f2512ba1SRui Paulo 	 *	if seg contains an ECE and ECN support is enabled, the stream
2044f2512ba1SRui Paulo 	 *	    is ECN capable.
2045df8bae1dSRodney W. Grimes 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2046df8bae1dSRodney W. Grimes 	 *	arrange for segment to be acked (eventually)
2047df8bae1dSRodney W. Grimes 	 *	continue processing rest of data/controls, beginning with URG
2048df8bae1dSRodney W. Grimes 	 */
2049df8bae1dSRodney W. Grimes 	case TCPS_SYN_SENT:
205057f60867SMark Johnston 		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2051d9fae5abSAndriy Gapon 			TCP_PROBE5(connect__refused, NULL, tp,
20522b9c9984SGeorge V. Neville-Neil 			    m, tp, th);
2053d1b07f36SRandall Stewart 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2054df8bae1dSRodney W. Grimes 			tp = tcp_drop(tp, ECONNREFUSED);
205557f60867SMark Johnston 		}
20560ca3f933SAndre Oppermann 		if (thflags & TH_RST)
2057df8bae1dSRodney W. Grimes 			goto drop;
20580ca3f933SAndre Oppermann 		if (!(thflags & TH_SYN))
2059df8bae1dSRodney W. Grimes 			goto drop;
2060464fcfbcSAndre Oppermann 
2061fb59c426SYoshinobu Inoue 		tp->irs = th->th_seq;
2062df8bae1dSRodney W. Grimes 		tcp_rcvseqinit(tp);
2063fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK) {
2064c560df6fSPatrick Kelsey 			int tfo_partial_ack = 0;
2065c560df6fSPatrick Kelsey 
206678b50714SRobert Watson 			TCPSTAT_INC(tcps_connects);
2067845799c1SAndras Olah 			soisconnected(so);
2068c488362eSRobert Watson #ifdef MAC
206930d239bcSRobert Watson 			mac_socketpeer_set_from_mbuf(m, so);
2070c488362eSRobert Watson #endif
2071845799c1SAndras Olah 			/* Do window scaling on this connection? */
2072845799c1SAndras Olah 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2073845799c1SAndras Olah 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2074845799c1SAndras Olah 				tp->rcv_scale = tp->request_r_scale;
2075845799c1SAndras Olah 			}
20763ac12506SJonathan T. Looney 			tp->rcv_adv += min(tp->rcv_wnd,
2077766282cbSJohn Baldwin 			    TCP_MAXWIN << tp->rcv_scale);
2078a0292f23SGarrett Wollman 			tp->snd_una++;		/* SYN is acked */
2079a0292f23SGarrett Wollman 			/*
2080c560df6fSPatrick Kelsey 			 * If not all the data that was sent in the TFO SYN
2081c560df6fSPatrick Kelsey 			 * has been acked, resend the remainder right away.
2082c560df6fSPatrick Kelsey 			 */
2083c560df6fSPatrick Kelsey 			if (IS_FASTOPEN(tp->t_flags) &&
2084c560df6fSPatrick Kelsey 			    (tp->snd_una != tp->snd_max)) {
2085c560df6fSPatrick Kelsey 				tp->snd_nxt = th->th_ack;
2086c560df6fSPatrick Kelsey 				tfo_partial_ack = 1;
2087c560df6fSPatrick Kelsey 			}
2088c560df6fSPatrick Kelsey 			/*
2089a0292f23SGarrett Wollman 			 * If there's data, delay ACK; if there's also a FIN
2090a0292f23SGarrett Wollman 			 * ACKNOW will be turned on later.
2091a0292f23SGarrett Wollman 			 */
2092c560df6fSPatrick Kelsey 			if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
2093b8152ba7SAndre Oppermann 				tcp_timer_activate(tp, TT_DELACK,
2094b8152ba7SAndre Oppermann 				    tcp_delacktime);
2095a0292f23SGarrett Wollman 			else
2096a0292f23SGarrett Wollman 				tp->t_flags |= TF_ACKNOW;
2097f2512ba1SRui Paulo 
2098f7220c48SRichard Scheffenegger 			tcp_ecn_input_syn_sent(tp, thflags, iptos);
2099f2512ba1SRui Paulo 
2100a0292f23SGarrett Wollman 			/*
2101a0292f23SGarrett Wollman 			 * Received <SYN,ACK> in SYN_SENT[*] state.
2102a0292f23SGarrett Wollman 			 * Transitions:
2103a0292f23SGarrett Wollman 			 *	SYN_SENT  --> ESTABLISHED
2104a0292f23SGarrett Wollman 			 *	SYN_SENT* --> FIN_WAIT_1
2105a0292f23SGarrett Wollman 			 */
21069b8b58e0SJonathan Lemon 			tp->t_starttime = ticks;
2107a0292f23SGarrett Wollman 			if (tp->t_flags & TF_NEEDFIN) {
210808af8aacSRandall Stewart 				tp->t_acktime = ticks;
210957f60867SMark Johnston 				tcp_state_change(tp, TCPS_FIN_WAIT_1);
2110a0292f23SGarrett Wollman 				tp->t_flags &= ~TF_NEEDFIN;
2111fb59c426SYoshinobu Inoue 				thflags &= ~TH_SYN;
21127ff19458SPaul Traina 			} else {
211357f60867SMark Johnston 				tcp_state_change(tp, TCPS_ESTABLISHED);
2114d9fae5abSAndriy Gapon 				TCP_PROBE5(connect__established, NULL, tp,
21152b9c9984SGeorge V. Neville-Neil 				    m, tp, th);
2116dbc42409SLawrence Stewart 				cc_conn_init(tp);
21179077f387SGleb Smirnoff 				tcp_timer_activate(tp, TT_KEEP,
21189077f387SGleb Smirnoff 				    TP_KEEPIDLE(tp));
21197ff19458SPaul Traina 			}
2120a0292f23SGarrett Wollman 		} else {
2121a0292f23SGarrett Wollman 			/*
2122c068736aSJeffrey Hsu 			 * Received initial SYN in SYN-SENT[*] state =>
2123153edc50SHiren Panchasara 			 * simultaneous open.
2124c068736aSJeffrey Hsu 			 * If it succeeds, connection is * half-synchronized.
2125c068736aSJeffrey Hsu 			 * Otherwise, do 3-way handshake:
2126a0292f23SGarrett Wollman 			 *        SYN-SENT -> SYN-RECEIVED
2127a0292f23SGarrett Wollman 			 *        SYN-SENT* -> SYN-RECEIVED*
2128a0292f23SGarrett Wollman 			 */
2129493105c2SGleb Smirnoff 			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
2130b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
213157f60867SMark Johnston 			tcp_state_change(tp, TCPS_SYN_RECEIVED);
2132a0292f23SGarrett Wollman 		}
2133df8bae1dSRodney W. Grimes 
21348501a69cSRobert Watson 		INP_WLOCK_ASSERT(tp->t_inpcb);
21357cfc6904SRobert Watson 
2136df8bae1dSRodney W. Grimes 		/*
2137fb59c426SYoshinobu Inoue 		 * Advance th->th_seq to correspond to first data byte.
2138df8bae1dSRodney W. Grimes 		 * If data, trim to stay within window,
2139df8bae1dSRodney W. Grimes 		 * dropping FIN if necessary.
2140df8bae1dSRodney W. Grimes 		 */
2141fb59c426SYoshinobu Inoue 		th->th_seq++;
2142fb59c426SYoshinobu Inoue 		if (tlen > tp->rcv_wnd) {
2143fb59c426SYoshinobu Inoue 			todrop = tlen - tp->rcv_wnd;
2144df8bae1dSRodney W. Grimes 			m_adj(m, -todrop);
2145fb59c426SYoshinobu Inoue 			tlen = tp->rcv_wnd;
2146fb59c426SYoshinobu Inoue 			thflags &= ~TH_FIN;
214778b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpackafterwin);
214878b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2149df8bae1dSRodney W. Grimes 		}
2150fb59c426SYoshinobu Inoue 		tp->snd_wl1 = th->th_seq - 1;
2151fb59c426SYoshinobu Inoue 		tp->rcv_up = th->th_seq;
2152a0292f23SGarrett Wollman 		/*
2153a0292f23SGarrett Wollman 		 * Client side of transaction: already sent SYN and data.
2154a0292f23SGarrett Wollman 		 * If the remote host used T/TCP to validate the SYN,
2155a0292f23SGarrett Wollman 		 * our data will be ACK'd; if so, enter normal data segment
2156a0292f23SGarrett Wollman 		 * processing in the middle of step 5, ack processing.
2157a0292f23SGarrett Wollman 		 * Otherwise, goto step 6.
2158a0292f23SGarrett Wollman 		 */
2159fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK)
2160a0292f23SGarrett Wollman 			goto process_ACK;
2161c068736aSJeffrey Hsu 
2162df8bae1dSRodney W. Grimes 		goto step6;
2163df8bae1dSRodney W. Grimes 	}
2164df8bae1dSRodney W. Grimes 
2165df8bae1dSRodney W. Grimes 	/*
2166df8bae1dSRodney W. Grimes 	 * States other than LISTEN or SYN_SENT.
216780ab7c0eSGarrett Wollman 	 * First check the RST flag and sequence number since reset segments
216880ab7c0eSGarrett Wollman 	 * are exempt from the timestamp and connection count tests.  This
216980ab7c0eSGarrett Wollman 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
217080ab7c0eSGarrett Wollman 	 * below which allowed reset segments in half the sequence space
217180ab7c0eSGarrett Wollman 	 * to fall though and be processed (which gives forged reset
217280ab7c0eSGarrett Wollman 	 * segments with a random sequence number a 50 percent chance of
217380ab7c0eSGarrett Wollman 	 * killing a connection).
217480ab7c0eSGarrett Wollman 	 * Then check timestamp, if present.
2175a0292f23SGarrett Wollman 	 * Then check the connection count, if present.
2176df8bae1dSRodney W. Grimes 	 * Then check that at least some bytes of segment are within
2177df8bae1dSRodney W. Grimes 	 * receive window.  If segment begins before rcv_nxt,
2178df8bae1dSRodney W. Grimes 	 * drop leading data (and SYN); if nothing left, just ack.
217980ab7c0eSGarrett Wollman 	 */
2180fb59c426SYoshinobu Inoue 	if (thflags & TH_RST) {
21813220a212SGleb Smirnoff 		/*
21823220a212SGleb Smirnoff 		 * RFC5961 Section 3.2
21833220a212SGleb Smirnoff 		 *
21843220a212SGleb Smirnoff 		 * - RST drops connection only if SEG.SEQ == RCV.NXT.
21853220a212SGleb Smirnoff 		 * - If RST is in window, we send challenge ACK.
21863220a212SGleb Smirnoff 		 *
21873220a212SGleb Smirnoff 		 * Note: to take into account delayed ACKs, we should
21883220a212SGleb Smirnoff 		 *   test against last_ack_sent instead of rcv_nxt.
21893220a212SGleb Smirnoff 		 * Note 2: we handle special case of closed window, not
21903220a212SGleb Smirnoff 		 *   covered by the RFC.
21913220a212SGleb Smirnoff 		 */
21923220a212SGleb Smirnoff 		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
21933220a212SGleb Smirnoff 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
21943220a212SGleb Smirnoff 		    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
21953220a212SGleb Smirnoff 			KASSERT(tp->t_state != TCPS_SYN_SENT,
21963220a212SGleb Smirnoff 			    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
21973220a212SGleb Smirnoff 			    __func__, th, tp));
21983220a212SGleb Smirnoff 
21993220a212SGleb Smirnoff 			if (V_tcp_insecure_rst ||
22003220a212SGleb Smirnoff 			    tp->last_ack_sent == th->th_seq) {
22013220a212SGleb Smirnoff 				TCPSTAT_INC(tcps_drops);
22023220a212SGleb Smirnoff 				/* Drop the connection. */
22033220a212SGleb Smirnoff 				switch (tp->t_state) {
220480ab7c0eSGarrett Wollman 				case TCPS_SYN_RECEIVED:
220580ab7c0eSGarrett Wollman 					so->so_error = ECONNREFUSED;
220680ab7c0eSGarrett Wollman 					goto close;
220780ab7c0eSGarrett Wollman 				case TCPS_ESTABLISHED:
220880ab7c0eSGarrett Wollman 				case TCPS_FIN_WAIT_1:
220980ab7c0eSGarrett Wollman 				case TCPS_FIN_WAIT_2:
221080ab7c0eSGarrett Wollman 				case TCPS_CLOSE_WAIT:
22116779a1a1SMichael Tuexen 				case TCPS_CLOSING:
22126779a1a1SMichael Tuexen 				case TCPS_LAST_ACK:
221380ab7c0eSGarrett Wollman 					so->so_error = ECONNRESET;
221480ab7c0eSGarrett Wollman 				close:
22153220a212SGleb Smirnoff 					/* FALLTHROUGH */
22163220a212SGleb Smirnoff 				default:
2217d1b07f36SRandall Stewart 					tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
221880ab7c0eSGarrett Wollman 					tp = tcp_close(tp);
22193220a212SGleb Smirnoff 				}
22203220a212SGleb Smirnoff 			} else {
22213220a212SGleb Smirnoff 				TCPSTAT_INC(tcps_badrst);
22223220a212SGleb Smirnoff 				/* Send challenge ACK. */
22233220a212SGleb Smirnoff 				tcp_respond(tp, mtod(m, void *), th, m,
22243220a212SGleb Smirnoff 				    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
22253220a212SGleb Smirnoff 				tp->last_ack_sent = tp->rcv_nxt;
22263220a212SGleb Smirnoff 				m = NULL;
22273220a212SGleb Smirnoff 			}
22283220a212SGleb Smirnoff 		}
22293220a212SGleb Smirnoff 		goto drop;
22303220a212SGleb Smirnoff 	}
223180ab7c0eSGarrett Wollman 
22323220a212SGleb Smirnoff 	/*
22333220a212SGleb Smirnoff 	 * RFC5961 Section 4.2
22343220a212SGleb Smirnoff 	 * Send challenge ACK for any SYN in synchronized state.
22353220a212SGleb Smirnoff 	 */
2236281a0fd4SPatrick Kelsey 	if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2237281a0fd4SPatrick Kelsey 	    tp->t_state != TCPS_SYN_RECEIVED) {
22383220a212SGleb Smirnoff 		TCPSTAT_INC(tcps_badsyn);
22393220a212SGleb Smirnoff 		if (V_tcp_insecure_syn &&
22403220a212SGleb Smirnoff 		    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
22413220a212SGleb Smirnoff 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2242d1b07f36SRandall Stewart 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
22433220a212SGleb Smirnoff 			tp = tcp_drop(tp, ECONNRESET);
22443220a212SGleb Smirnoff 			rstreason = BANDLIM_UNLIMITED;
22453220a212SGleb Smirnoff 		} else {
22463220a212SGleb Smirnoff 			/* Send challenge ACK. */
22473220a212SGleb Smirnoff 			tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
22483220a212SGleb Smirnoff 			    tp->snd_nxt, TH_ACK);
22493220a212SGleb Smirnoff 			tp->last_ack_sent = tp->rcv_nxt;
22503220a212SGleb Smirnoff 			m = NULL;
225180ab7c0eSGarrett Wollman 		}
225280ab7c0eSGarrett Wollman 		goto drop;
225380ab7c0eSGarrett Wollman 	}
225480ab7c0eSGarrett Wollman 
225580ab7c0eSGarrett Wollman 	/*
2256df8bae1dSRodney W. Grimes 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2257df8bae1dSRodney W. Grimes 	 * and it's less than ts_recent, drop it.
2258df8bae1dSRodney W. Grimes 	 */
2259be2ac88cSJonathan Lemon 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
226080ab7c0eSGarrett Wollman 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2261df8bae1dSRodney W. Grimes 		/* Check to see if ts_recent is over 24 days old.  */
2262d8951c8aSBjoern A. Zeeb 		if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2263df8bae1dSRodney W. Grimes 			/*
2264df8bae1dSRodney W. Grimes 			 * Invalidate ts_recent.  If this segment updates
2265df8bae1dSRodney W. Grimes 			 * ts_recent, the age will be reset later and ts_recent
2266df8bae1dSRodney W. Grimes 			 * will get a valid value.  If it does not, setting
2267df8bae1dSRodney W. Grimes 			 * ts_recent to zero will at least satisfy the
2268df8bae1dSRodney W. Grimes 			 * requirement that zero be placed in the timestamp
2269df8bae1dSRodney W. Grimes 			 * echo reply when ts_recent isn't valid.  The
2270df8bae1dSRodney W. Grimes 			 * age isn't reset until we get a valid ts_recent
2271df8bae1dSRodney W. Grimes 			 * because we don't want out-of-order segments to be
2272df8bae1dSRodney W. Grimes 			 * dropped when ts_recent is old.
2273df8bae1dSRodney W. Grimes 			 */
2274df8bae1dSRodney W. Grimes 			tp->ts_recent = 0;
2275df8bae1dSRodney W. Grimes 		} else {
227678b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvduppack);
227778b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
227878b50714SRobert Watson 			TCPSTAT_INC(tcps_pawsdrop);
227907fd333dSMatthew Dillon 			if (tlen)
2280df8bae1dSRodney W. Grimes 				goto dropafterack;
22811ab4789dSMatthew Dillon 			goto drop;
22821ab4789dSMatthew Dillon 		}
2283df8bae1dSRodney W. Grimes 	}
2284df8bae1dSRodney W. Grimes 
2285a0292f23SGarrett Wollman 	/*
228680ab7c0eSGarrett Wollman 	 * In the SYN-RECEIVED state, validate that the packet belongs to
228780ab7c0eSGarrett Wollman 	 * this connection before trimming the data to fit the receive
228880ab7c0eSGarrett Wollman 	 * window.  Check the sequence number versus IRS since we know
228980ab7c0eSGarrett Wollman 	 * the sequence numbers haven't wrapped.  This is a partial fix
229080ab7c0eSGarrett Wollman 	 * for the "LAND" DoS attack.
229180ab7c0eSGarrett Wollman 	 */
2292a57815efSBosko Milekic 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2293a57815efSBosko Milekic 		rstreason = BANDLIM_RST_OPENPORT;
2294d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2295a57815efSBosko Milekic 		goto dropwithreset;
2296a57815efSBosko Milekic 	}
229780ab7c0eSGarrett Wollman 
2298fb59c426SYoshinobu Inoue 	todrop = tp->rcv_nxt - th->th_seq;
2299df8bae1dSRodney W. Grimes 	if (todrop > 0) {
2300831ad37eSXin LI 		if (thflags & TH_SYN) {
2301fb59c426SYoshinobu Inoue 			thflags &= ~TH_SYN;
2302fb59c426SYoshinobu Inoue 			th->th_seq++;
2303fb59c426SYoshinobu Inoue 			if (th->th_urp > 1)
2304fb59c426SYoshinobu Inoue 				th->th_urp--;
2305df8bae1dSRodney W. Grimes 			else
2306fb59c426SYoshinobu Inoue 				thflags &= ~TH_URG;
2307df8bae1dSRodney W. Grimes 			todrop--;
2308df8bae1dSRodney W. Grimes 		}
2309df8bae1dSRodney W. Grimes 		/*
2310dac20301SGarrett Wollman 		 * Following if statement from Stevens, vol. 2, p. 960.
2311df8bae1dSRodney W. Grimes 		 */
2312fb59c426SYoshinobu Inoue 		if (todrop > tlen
2313fb59c426SYoshinobu Inoue 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2314dac20301SGarrett Wollman 			/*
2315dac20301SGarrett Wollman 			 * Any valid FIN must be to the left of the window.
2316dac20301SGarrett Wollman 			 * At this point the FIN must be a duplicate or out
2317dac20301SGarrett Wollman 			 * of sequence; drop it.
2318dac20301SGarrett Wollman 			 */
2319fb59c426SYoshinobu Inoue 			thflags &= ~TH_FIN;
2320dac20301SGarrett Wollman 
2321df8bae1dSRodney W. Grimes 			/*
2322dac20301SGarrett Wollman 			 * Send an ACK to resynchronize and drop any data.
2323dac20301SGarrett Wollman 			 * But keep on processing for RST or ACK.
2324df8bae1dSRodney W. Grimes 			 */
2325dac20301SGarrett Wollman 			tp->t_flags |= TF_ACKNOW;
2326fb59c426SYoshinobu Inoue 			todrop = tlen;
232778b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvduppack);
232878b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2329df8bae1dSRodney W. Grimes 		} else {
233078b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpartduppack);
233178b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2332df8bae1dSRodney W. Grimes 		}
23335acfd95cSMichael Tuexen 		/*
23345acfd95cSMichael Tuexen 		 * DSACK - add SACK block for dropped range
23355acfd95cSMichael Tuexen 		 */
23368f63a52bSMichael Tuexen 		if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2337ecc5b1d1SMichael Tuexen 			tcp_update_sack_list(tp, th->th_seq,
2338ecc5b1d1SMichael Tuexen 			    th->th_seq + todrop);
23395acfd95cSMichael Tuexen 			/*
23405acfd95cSMichael Tuexen 			 * ACK now, as the next in-sequence segment
23415acfd95cSMichael Tuexen 			 * will clear the DSACK block again
23425acfd95cSMichael Tuexen 			 */
23435acfd95cSMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
23445acfd95cSMichael Tuexen 		}
2345fb59c426SYoshinobu Inoue 		drop_hdrlen += todrop;	/* drop from the top afterwards */
2346fb59c426SYoshinobu Inoue 		th->th_seq += todrop;
2347fb59c426SYoshinobu Inoue 		tlen -= todrop;
2348fb59c426SYoshinobu Inoue 		if (th->th_urp > todrop)
2349fb59c426SYoshinobu Inoue 			th->th_urp -= todrop;
2350df8bae1dSRodney W. Grimes 		else {
2351fb59c426SYoshinobu Inoue 			thflags &= ~TH_URG;
2352fb59c426SYoshinobu Inoue 			th->th_urp = 0;
2353df8bae1dSRodney W. Grimes 		}
2354df8bae1dSRodney W. Grimes 	}
2355df8bae1dSRodney W. Grimes 
2356df8bae1dSRodney W. Grimes 	/*
2357df8bae1dSRodney W. Grimes 	 * If new data are received on a connection after the
2358df8bae1dSRodney W. Grimes 	 * user processes are gone, then RST the other end.
2359df8bae1dSRodney W. Grimes 	 */
236074703901SGleb Smirnoff 	if ((tp->t_flags & TF_CLOSED) && tlen) {
236107dacf03SAndre Oppermann 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
236207dacf03SAndre Oppermann 			log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
236307dacf03SAndre Oppermann 			    "after socket was closed, "
236407dacf03SAndre Oppermann 			    "sending RST and removing tcpcb\n",
2365e31d8aa3SMike Silbersack 			    s, __func__, tcpstates[tp->t_state], tlen);
2366773673c1SAndre Oppermann 			free(s, M_TCPLOG);
2367773673c1SAndre Oppermann 		}
2368d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
2369d1b07f36SRandall Stewart 		/* tcp_close will kill the inp pre-log the Reset */
2370d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
2371df8bae1dSRodney W. Grimes 		tp = tcp_close(tp);
237278b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvafterclose);
2373a57815efSBosko Milekic 		rstreason = BANDLIM_UNLIMITED;
2374df8bae1dSRodney W. Grimes 		goto dropwithreset;
2375df8bae1dSRodney W. Grimes 	}
2376df8bae1dSRodney W. Grimes 
2377df8bae1dSRodney W. Grimes 	/*
2378df8bae1dSRodney W. Grimes 	 * If segment ends after window, drop trailing data
2379df8bae1dSRodney W. Grimes 	 * (and PUSH and FIN); if nothing left, just ACK.
2380df8bae1dSRodney W. Grimes 	 */
2381fb59c426SYoshinobu Inoue 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2382df8bae1dSRodney W. Grimes 	if (todrop > 0) {
238378b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvpackafterwin);
2384fb59c426SYoshinobu Inoue 		if (todrop >= tlen) {
238578b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2386df8bae1dSRodney W. Grimes 			/*
2387df8bae1dSRodney W. Grimes 			 * If window is closed can only take segments at
2388df8bae1dSRodney W. Grimes 			 * window edge, and have to drop data and PUSH from
2389df8bae1dSRodney W. Grimes 			 * incoming segments.  Continue processing, but
2390df8bae1dSRodney W. Grimes 			 * remember to ack.  Otherwise, drop segment
2391df8bae1dSRodney W. Grimes 			 * and ack.
2392df8bae1dSRodney W. Grimes 			 */
2393fb59c426SYoshinobu Inoue 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2394df8bae1dSRodney W. Grimes 				tp->t_flags |= TF_ACKNOW;
239578b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvwinprobe);
2396df8bae1dSRodney W. Grimes 			} else
2397df8bae1dSRodney W. Grimes 				goto dropafterack;
2398df8bae1dSRodney W. Grimes 		} else
239978b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2400df8bae1dSRodney W. Grimes 		m_adj(m, -todrop);
2401fb59c426SYoshinobu Inoue 		tlen -= todrop;
2402fb59c426SYoshinobu Inoue 		thflags &= ~(TH_PUSH|TH_FIN);
2403df8bae1dSRodney W. Grimes 	}
2404df8bae1dSRodney W. Grimes 
2405df8bae1dSRodney W. Grimes 	/*
2406df8bae1dSRodney W. Grimes 	 * If last ACK falls within this segment's sequence numbers,
2407df8bae1dSRodney W. Grimes 	 * record its timestamp.
2408cf09195bSPaul Saab 	 * NOTE:
2409cf09195bSPaul Saab 	 * 1) That the test incorporates suggestions from the latest
2410a0292f23SGarrett Wollman 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
2411cf09195bSPaul Saab 	 * 2) That updating only on newer timestamps interferes with
2412cf09195bSPaul Saab 	 *    our earlier PAWS tests, so this check should be solely
2413cf09195bSPaul Saab 	 *    predicated on the sequence space of this segment.
2414cf09195bSPaul Saab 	 * 3) That we modify the segment boundary check to be
2415cf09195bSPaul Saab 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
2416cf09195bSPaul Saab 	 *    instead of RFC1323's
2417cf09195bSPaul Saab 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
2418cf09195bSPaul Saab 	 *    This modified check allows us to overcome RFC1323's
2419cf09195bSPaul Saab 	 *    limitations as described in Stevens TCP/IP Illustrated
2420cf09195bSPaul Saab 	 *    Vol. 2 p.869. In such cases, we can still calculate the
2421cf09195bSPaul Saab 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
2422df8bae1dSRodney W. Grimes 	 */
2423be2ac88cSJonathan Lemon 	if ((to.to_flags & TOF_TS) != 0 &&
2424cf09195bSPaul Saab 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2425cf09195bSPaul Saab 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2426cf09195bSPaul Saab 		((thflags & (TH_SYN|TH_FIN)) != 0))) {
2427d8951c8aSBjoern A. Zeeb 		tp->ts_recent_age = tcp_ts_getticks();
2428a0292f23SGarrett Wollman 		tp->ts_recent = to.to_tsval;
2429df8bae1dSRodney W. Grimes 	}
2430df8bae1dSRodney W. Grimes 
2431df8bae1dSRodney W. Grimes 	/*
2432a0292f23SGarrett Wollman 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
2433a0292f23SGarrett Wollman 	 * flag is on (half-synchronized state), then queue data for
2434a0292f23SGarrett Wollman 	 * later processing; else drop segment and return.
2435a0292f23SGarrett Wollman 	 */
2436fb59c426SYoshinobu Inoue 	if ((thflags & TH_ACK) == 0) {
2437a0292f23SGarrett Wollman 		if (tp->t_state == TCPS_SYN_RECEIVED ||
2438281a0fd4SPatrick Kelsey 		    (tp->t_flags & TF_NEEDSYN)) {
2439281a0fd4SPatrick Kelsey 			if (tp->t_state == TCPS_SYN_RECEIVED &&
244068bd7ed1SJonathan T. Looney 			    IS_FASTOPEN(tp->t_flags)) {
2441281a0fd4SPatrick Kelsey 				tp->snd_wnd = tiwin;
2442281a0fd4SPatrick Kelsey 				cc_conn_init(tp);
2443281a0fd4SPatrick Kelsey 			}
2444a0292f23SGarrett Wollman 			goto step6;
2445281a0fd4SPatrick Kelsey 		} else if (tp->t_flags & TF_ACKNOW)
24465e1aa279SDavid Malone 			goto dropafterack;
2447a0292f23SGarrett Wollman 		else
2448a0292f23SGarrett Wollman 			goto drop;
2449a0292f23SGarrett Wollman 	}
2450df8bae1dSRodney W. Grimes 
2451df8bae1dSRodney W. Grimes 	/*
2452df8bae1dSRodney W. Grimes 	 * Ack processing.
2453df8bae1dSRodney W. Grimes 	 */
2454df8bae1dSRodney W. Grimes 	switch (tp->t_state) {
2455df8bae1dSRodney W. Grimes 	/*
2456764d8cefSBill Fenner 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2457764d8cefSBill Fenner 	 * ESTABLISHED state and continue processing.
2458764d8cefSBill Fenner 	 * The ACK was checked above.
2459df8bae1dSRodney W. Grimes 	 */
2460df8bae1dSRodney W. Grimes 	case TCPS_SYN_RECEIVED:
2461a0292f23SGarrett Wollman 
246278b50714SRobert Watson 		TCPSTAT_INC(tcps_connects);
2463493105c2SGleb Smirnoff 		if (tp->t_flags & TF_SONOTCONN) {
2464493105c2SGleb Smirnoff 			/*
2465493105c2SGleb Smirnoff 			 * Usually SYN_RECEIVED had been created from a LISTEN,
2466493105c2SGleb Smirnoff 			 * and solisten_enqueue() has already marked the socket
2467493105c2SGleb Smirnoff 			 * layer as connected.  If it didn't, which can happen
2468493105c2SGleb Smirnoff 			 * only with an accept_filter(9), then the tp is marked
2469493105c2SGleb Smirnoff 			 * with TF_SONOTCONN.  The other reason for this mark
2470493105c2SGleb Smirnoff 			 * to be set is a simultaneous open, a SYN_RECEIVED
2471493105c2SGleb Smirnoff 			 * that had been created from SYN_SENT.
2472493105c2SGleb Smirnoff 			 */
2473493105c2SGleb Smirnoff 			tp->t_flags &= ~TF_SONOTCONN;
2474df8bae1dSRodney W. Grimes 			soisconnected(so);
2475e80062a2SGleb Smirnoff 		}
2476df8bae1dSRodney W. Grimes 		/* Do window scaling? */
2477df8bae1dSRodney W. Grimes 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2478df8bae1dSRodney W. Grimes 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2479df8bae1dSRodney W. Grimes 			tp->rcv_scale = tp->request_r_scale;
2480df8bae1dSRodney W. Grimes 		}
2481116ef4d6SMichael Tuexen 		tp->snd_wnd = tiwin;
2482a0292f23SGarrett Wollman 		/*
2483a0292f23SGarrett Wollman 		 * Make transitions:
2484a0292f23SGarrett Wollman 		 *      SYN-RECEIVED  -> ESTABLISHED
2485a0292f23SGarrett Wollman 		 *      SYN-RECEIVED* -> FIN-WAIT-1
2486a0292f23SGarrett Wollman 		 */
24879b8b58e0SJonathan Lemon 		tp->t_starttime = ticks;
248818a75309SPatrick Kelsey 		if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
2489281a0fd4SPatrick Kelsey 			tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2490281a0fd4SPatrick Kelsey 			tp->t_tfo_pending = NULL;
2491281a0fd4SPatrick Kelsey 		}
24928db239dcSMichael Tuexen 		if (tp->t_flags & TF_NEEDFIN) {
249308af8aacSRandall Stewart 			tp->t_acktime = ticks;
24948db239dcSMichael Tuexen 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
24958db239dcSMichael Tuexen 			tp->t_flags &= ~TF_NEEDFIN;
24968db239dcSMichael Tuexen 		} else {
24978db239dcSMichael Tuexen 			tcp_state_change(tp, TCPS_ESTABLISHED);
24988db239dcSMichael Tuexen 			TCP_PROBE5(accept__established, NULL, tp,
24998db239dcSMichael Tuexen 			    m, tp, th);
2500281a0fd4SPatrick Kelsey 			/*
2501281a0fd4SPatrick Kelsey 			 * TFO connections call cc_conn_init() during SYN
2502281a0fd4SPatrick Kelsey 			 * processing.  Calling it again here for such
2503281a0fd4SPatrick Kelsey 			 * connections is not harmless as it would undo the
2504281a0fd4SPatrick Kelsey 			 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2505281a0fd4SPatrick Kelsey 			 * is retransmitted.
2506281a0fd4SPatrick Kelsey 			 */
250768bd7ed1SJonathan T. Looney 			if (!IS_FASTOPEN(tp->t_flags))
2508dbc42409SLawrence Stewart 				cc_conn_init(tp);
25099077f387SGleb Smirnoff 			tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
25107ff19458SPaul Traina 		}
2511a0292f23SGarrett Wollman 		/*
2512b2ade6b1SRichard Scheffenegger 		 * Account for the ACK of our SYN prior to
2513b2ade6b1SRichard Scheffenegger 		 * regular ACK processing below, except for
2514b2ade6b1SRichard Scheffenegger 		 * simultaneous SYN, which is handled later.
2515b2ade6b1SRichard Scheffenegger 		 */
2516b2ade6b1SRichard Scheffenegger 		if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2517b2ade6b1SRichard Scheffenegger 			incforsyn = 1;
2518b2ade6b1SRichard Scheffenegger 		/*
2519a0292f23SGarrett Wollman 		 * If segment contains data or ACK, will call tcp_reass()
2520a0292f23SGarrett Wollman 		 * later; if not, do so now to pass queued data to user.
2521a0292f23SGarrett Wollman 		 */
2522032bf749SRichard Scheffenegger 		if (tlen == 0 && (thflags & TH_FIN) == 0) {
2523c28440dbSRandall Stewart 			(void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2524a0292f23SGarrett Wollman 			    (struct mbuf *)0);
2525032bf749SRichard Scheffenegger 			tcp_handle_wakeup(tp, so);
2526032bf749SRichard Scheffenegger 		}
252760ee3bb2SAndre Oppermann 		tp->snd_wl1 = th->th_seq - 1;
252893b0017fSPhilippe Charnier 		/* FALLTHROUGH */
2529df8bae1dSRodney W. Grimes 
2530df8bae1dSRodney W. Grimes 	/*
2531df8bae1dSRodney W. Grimes 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2532df8bae1dSRodney W. Grimes 	 * ACKs.  If the ack is in the range
2533fb59c426SYoshinobu Inoue 	 *	tp->snd_una < th->th_ack <= tp->snd_max
2534fb59c426SYoshinobu Inoue 	 * then advance tp->snd_una to th->th_ack and drop
2535df8bae1dSRodney W. Grimes 	 * data from the retransmission queue.  If this ACK reflects
2536df8bae1dSRodney W. Grimes 	 * more up to date window information we update our window information.
2537df8bae1dSRodney W. Grimes 	 */
2538df8bae1dSRodney W. Grimes 	case TCPS_ESTABLISHED:
2539df8bae1dSRodney W. Grimes 	case TCPS_FIN_WAIT_1:
2540df8bae1dSRodney W. Grimes 	case TCPS_FIN_WAIT_2:
2541df8bae1dSRodney W. Grimes 	case TCPS_CLOSE_WAIT:
2542df8bae1dSRodney W. Grimes 	case TCPS_CLOSING:
2543df8bae1dSRodney W. Grimes 	case TCPS_LAST_ACK:
25445a53ca16SPaul Saab 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
254578b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvacktoomuch);
25465a53ca16SPaul Saab 			goto dropafterack;
25475a53ca16SPaul Saab 		}
2548c21b7b55SRichard Scheffenegger 		if (tcp_is_sack_recovery(tp, &to)) {
25490471a8c7SRichard Scheffenegger 			if (((sack_changed = tcp_sack_doack(tp, &to, th->th_ack)) != 0) &&
25500471a8c7SRichard Scheffenegger 			    (tp->t_flags & TF_LRD)) {
25510471a8c7SRichard Scheffenegger 				tcp_sack_lost_retransmission(tp, th);
25520471a8c7SRichard Scheffenegger 			}
25530471a8c7SRichard Scheffenegger 		} else
255412eeb81fSHiren Panchasara 			/*
255512eeb81fSHiren Panchasara 			 * Reset the value so that previous (valid) value
255612eeb81fSHiren Panchasara 			 * from the last ack with SACK doesn't get used.
255712eeb81fSHiren Panchasara 			 */
255812eeb81fSHiren Panchasara 			tp->sackhint.sacked_bytes = 0;
255939bc9de5SLawrence Stewart 
2560bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
256139bc9de5SLawrence Stewart 		/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
256239bc9de5SLawrence Stewart 		hhook_run_tcp_est_in(tp, th, &to);
2563bd79708dSJonathan T. Looney #endif
256439bc9de5SLawrence Stewart 
2565fb59c426SYoshinobu Inoue 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
25660c39d38dSGleb Smirnoff 			maxseg = tcp_maxseg(tp);
2567021eaf79SHiren Panchasara 			if (tlen == 0 &&
2568021eaf79SHiren Panchasara 			    (tiwin == tp->snd_wnd ||
2569021eaf79SHiren Panchasara 			    (tp->t_flags & TF_SACK_PERMIT))) {
257062b90589SPeter Wemm 				/*
257162b90589SPeter Wemm 				 * If this is the first time we've seen a
257262b90589SPeter Wemm 				 * FIN from the remote, this is not a
257362b90589SPeter Wemm 				 * duplicate and it needs to be processed
257462b90589SPeter Wemm 				 * normally.  This happens during a
257562b90589SPeter Wemm 				 * simultaneous close.
257662b90589SPeter Wemm 				 */
257762b90589SPeter Wemm 				if ((thflags & TH_FIN) &&
257862b90589SPeter Wemm 				    (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
257962b90589SPeter Wemm 					tp->t_dupacks = 0;
258062b90589SPeter Wemm 					break;
258162b90589SPeter Wemm 				}
258278b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvdupack);
2583df8bae1dSRodney W. Grimes 				/*
2584df8bae1dSRodney W. Grimes 				 * If we have outstanding data (other than
2585df8bae1dSRodney W. Grimes 				 * a window probe), this is a completely
2586df8bae1dSRodney W. Grimes 				 * duplicate ack (ie, window info didn't
25875f30ec9bSEitan Adler 				 * change and FIN isn't set),
25885f30ec9bSEitan Adler 				 * the ack is the biggest we've
2589df8bae1dSRodney W. Grimes 				 * seen and we've seen exactly our rexmt
2590a4641f4eSPedro F. Giffuni 				 * threshold of them, assume a packet
2591df8bae1dSRodney W. Grimes 				 * has been dropped and retransmit it.
2592df8bae1dSRodney W. Grimes 				 * Kludge snd_nxt & the congestion
2593df8bae1dSRodney W. Grimes 				 * window so we send only this one
2594df8bae1dSRodney W. Grimes 				 * packet.
2595df8bae1dSRodney W. Grimes 				 *
2596df8bae1dSRodney W. Grimes 				 * We know we're losing at the current
2597df8bae1dSRodney W. Grimes 				 * window size so do congestion avoidance
2598df8bae1dSRodney W. Grimes 				 * (set ssthresh to half the current window
2599df8bae1dSRodney W. Grimes 				 * and pull our congestion window back to
2600df8bae1dSRodney W. Grimes 				 * the new ssthresh).
2601df8bae1dSRodney W. Grimes 				 *
2602df8bae1dSRodney W. Grimes 				 * Dup acks mean that packets have left the
2603df8bae1dSRodney W. Grimes 				 * network (they're now cached at the receiver)
2604df8bae1dSRodney W. Grimes 				 * so bump cwnd by the amount in the receiver
2605df8bae1dSRodney W. Grimes 				 * to keep a constant cwnd packets in the
2606df8bae1dSRodney W. Grimes 				 * network.
2607f2512ba1SRui Paulo 				 *
2608f2512ba1SRui Paulo 				 * When using TCP ECN, notify the peer that
2609f2512ba1SRui Paulo 				 * we reduced the cwnd.
2610df8bae1dSRodney W. Grimes 				 */
2611021eaf79SHiren Panchasara 				/*
2612021eaf79SHiren Panchasara 				 * Following 2 kinds of acks should not affect
2613021eaf79SHiren Panchasara 				 * dupack counting:
2614021eaf79SHiren Panchasara 				 * 1) Old acks
2615021eaf79SHiren Panchasara 				 * 2) Acks with SACK but without any new SACK
2616021eaf79SHiren Panchasara 				 * information in them. These could result from
2617021eaf79SHiren Panchasara 				 * any anomaly in the network like a switch
2618021eaf79SHiren Panchasara 				 * duplicating packets or a possible DoS attack.
2619021eaf79SHiren Panchasara 				 */
2620021eaf79SHiren Panchasara 				if (th->th_ack != tp->snd_una ||
2621c21b7b55SRichard Scheffenegger 				    (tcp_is_sack_recovery(tp, &to) &&
2622021eaf79SHiren Panchasara 				    !sack_changed))
2623021eaf79SHiren Panchasara 					break;
2624021eaf79SHiren Panchasara 				else if (!tcp_timer_active(tp, TT_REXMT))
2625df8bae1dSRodney W. Grimes 					tp->t_dupacks = 0;
2626cb942153SJeffrey Hsu 				else if (++tp->t_dupacks > tcprexmtthresh ||
2627dbc42409SLawrence Stewart 				     IN_FASTRECOVERY(tp->t_flags)) {
26284b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
26294b7b743cSLawrence Stewart 					    CC_DUPACK);
26300e1d7c25SRichard Scheffenegger 					if (V_tcp_do_prr &&
263174d7fc87SRichard Scheffenegger 					    IN_FASTRECOVERY(tp->t_flags)) {
263290cca08eSRichard Scheffenegger 						tcp_do_prr_ack(tp, th, &to);
2633c21b7b55SRichard Scheffenegger 					} else if (tcp_is_sack_recovery(tp, &to) &&
2634dbc42409SLawrence Stewart 					    IN_FASTRECOVERY(tp->t_flags)) {
2635808f11b7SPaul Saab 						int awnd;
263625e6f9edSPaul Saab 
263725e6f9edSPaul Saab 						/*
263825e6f9edSPaul Saab 						 * Compute the amount of data in flight first.
26394c3972f0SHiren Panchasara 						 * We can inject new data into the pipe iff
264025e6f9edSPaul Saab 						 * we have less than 1/2 the original window's
264125e6f9edSPaul Saab 						 * worth of data in flight.
264225e6f9edSPaul Saab 						 */
2643d1de2b05SRichard Scheffenegger 						if (V_tcp_do_newsack)
264412eeb81fSHiren Panchasara 							awnd = tcp_compute_pipe(tp);
264512eeb81fSHiren Panchasara 						else
2646808f11b7SPaul Saab 							awnd = (tp->snd_nxt - tp->snd_fack) +
26470077b016SPaul Saab 								tp->sackhint.sack_bytes_rexmit;
264812eeb81fSHiren Panchasara 
2649808f11b7SPaul Saab 						if (awnd < tp->snd_ssthresh) {
26500c39d38dSGleb Smirnoff 							tp->snd_cwnd += maxseg;
265125e6f9edSPaul Saab 							if (tp->snd_cwnd > tp->snd_ssthresh)
265225e6f9edSPaul Saab 								tp->snd_cwnd = tp->snd_ssthresh;
265325e6f9edSPaul Saab 						}
265425e6f9edSPaul Saab 					} else
26550c39d38dSGleb Smirnoff 						tp->snd_cwnd += maxseg;
265640fa3e40SGleb Smirnoff 					(void) tcp_output(tp);
265746f58482SJonathan Lemon 					goto drop;
26583c40e1d5SRichard Scheffenegger 				} else if (tp->t_dupacks == tcprexmtthresh ||
26593c40e1d5SRichard Scheffenegger 					    (tp->t_flags & TF_SACK_PERMIT &&
2660d1de2b05SRichard Scheffenegger 					     V_tcp_do_newsack &&
26613c40e1d5SRichard Scheffenegger 					     tp->sackhint.sacked_bytes >
26623c40e1d5SRichard Scheffenegger 					     (tcprexmtthresh - 1) * maxseg)) {
26633c40e1d5SRichard Scheffenegger enter_recovery:
26643c40e1d5SRichard Scheffenegger 					/*
26653c40e1d5SRichard Scheffenegger 					 * Above is the RFC6675 trigger condition of
26663c40e1d5SRichard Scheffenegger 					 * more than (dupthresh-1)*maxseg sacked data.
26673c40e1d5SRichard Scheffenegger 					 * If the count of holes in the
26683c40e1d5SRichard Scheffenegger 					 * scoreboard is >= dupthresh, we could
26693c40e1d5SRichard Scheffenegger 					 * also enter loss recovery, but don't
26703c40e1d5SRichard Scheffenegger 					 * have that value readily available.
26713c40e1d5SRichard Scheffenegger 					 */
26723c40e1d5SRichard Scheffenegger 					tp->t_dupacks = tcprexmtthresh;
2673cb942153SJeffrey Hsu 					tcp_seq onxt = tp->snd_nxt;
2674a0445c2eSJayanth Vijayaraghavan 
2675a0445c2eSJayanth Vijayaraghavan 					/*
26760e1d7c25SRichard Scheffenegger 					 * If we're doing sack, or prr, check
26770e1d7c25SRichard Scheffenegger 					 * to see if we're already in sack
2678a0445c2eSJayanth Vijayaraghavan 					 * recovery. If we're not doing sack,
2679a0445c2eSJayanth Vijayaraghavan 					 * check to see if we're in newreno
2680a0445c2eSJayanth Vijayaraghavan 					 * recovery.
2681a0445c2eSJayanth Vijayaraghavan 					 */
26820e1d7c25SRichard Scheffenegger 					if (V_tcp_do_prr ||
26830e1d7c25SRichard Scheffenegger 					    (tp->t_flags & TF_SACK_PERMIT)) {
2684dbc42409SLawrence Stewart 						if (IN_FASTRECOVERY(tp->t_flags)) {
2685a0445c2eSJayanth Vijayaraghavan 							tp->t_dupacks = 0;
2686a0445c2eSJayanth Vijayaraghavan 							break;
2687a0445c2eSJayanth Vijayaraghavan 						}
2688dbc42409SLawrence Stewart 					} else {
2689a0445c2eSJayanth Vijayaraghavan 						if (SEQ_LEQ(th->th_ack,
26909d11646dSJeffrey Hsu 						    tp->snd_recover)) {
2691cb942153SJeffrey Hsu 							tp->t_dupacks = 0;
2692cb942153SJeffrey Hsu 							break;
269346f58482SJonathan Lemon 						}
2694a0445c2eSJayanth Vijayaraghavan 					}
2695dbc42409SLawrence Stewart 					/* Congestion signal before ack. */
2696dbc42409SLawrence Stewart 					cc_cong_signal(tp, th, CC_NDUPACK);
26974b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
26984b7b743cSLawrence Stewart 					    CC_DUPACK);
2699b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT, 0);
27009b8b58e0SJonathan Lemon 					tp->t_rtttime = 0;
27010e1d7c25SRichard Scheffenegger 					if (V_tcp_do_prr) {
27020e1d7c25SRichard Scheffenegger 						/*
27030e1d7c25SRichard Scheffenegger 						 * snd_ssthresh is already updated by
27040e1d7c25SRichard Scheffenegger 						 * cc_cong_signal.
27050e1d7c25SRichard Scheffenegger 						 */
2706c21b7b55SRichard Scheffenegger 						if (tcp_is_sack_recovery(tp, &to)) {
2707e9071000SRichard Scheffenegger 							tp->sackhint.prr_delivered =
2708e9071000SRichard Scheffenegger 							    tp->sackhint.sacked_bytes;
270974d7fc87SRichard Scheffenegger 						} else {
271074d7fc87SRichard Scheffenegger 							tp->sackhint.prr_delivered =
271174d7fc87SRichard Scheffenegger 							    imin(tp->snd_max - tp->snd_una,
271274d7fc87SRichard Scheffenegger 							    imin(INT_MAX / 65536,
271374d7fc87SRichard Scheffenegger 								tp->t_dupacks) * maxseg);
271474d7fc87SRichard Scheffenegger 						}
2715bc7ee8e5SRichard Scheffenegger 						tp->sackhint.recover_fs = max(1,
2716bc7ee8e5SRichard Scheffenegger 						    tp->snd_nxt - tp->snd_una);
27170e1d7c25SRichard Scheffenegger 					}
2718c21b7b55SRichard Scheffenegger 					if (tcp_is_sack_recovery(tp, &to)) {
271978b50714SRobert Watson 						TCPSTAT_INC(
272078b50714SRobert Watson 						    tcps_sack_recovery_episode);
2721a3574665SMichael Tuexen 						tp->snd_recover = tp->snd_nxt;
27220c39d38dSGleb Smirnoff 						tp->snd_cwnd = maxseg;
272340fa3e40SGleb Smirnoff 						(void) tcp_output(tp);
27243c40e1d5SRichard Scheffenegger 						if (SEQ_GT(th->th_ack, tp->snd_una))
27253c40e1d5SRichard Scheffenegger 							goto resume_partialack;
27266d90faf3SPaul Saab 						goto drop;
27276d90faf3SPaul Saab 					}
2728fb59c426SYoshinobu Inoue 					tp->snd_nxt = th->th_ack;
27290c39d38dSGleb Smirnoff 					tp->snd_cwnd = maxseg;
273040fa3e40SGleb Smirnoff 					(void) tcp_output(tp);
273148d2549cSJeffrey Hsu 					KASSERT(tp->snd_limited <= 2,
2732302ce8d6SAndre Oppermann 					    ("%s: tp->snd_limited too big",
2733302ce8d6SAndre Oppermann 					    __func__));
2734df8bae1dSRodney W. Grimes 					tp->snd_cwnd = tp->snd_ssthresh +
27350c39d38dSGleb Smirnoff 					     maxseg *
273648d2549cSJeffrey Hsu 					     (tp->t_dupacks - tp->snd_limited);
2737df8bae1dSRodney W. Grimes 					if (SEQ_GT(onxt, tp->snd_nxt))
2738df8bae1dSRodney W. Grimes 						tp->snd_nxt = onxt;
2739df8bae1dSRodney W. Grimes 					goto drop;
2740603724d3SBjoern A. Zeeb 				} else if (V_tcp_do_rfc3042) {
274162d4443fSHiren Panchasara 					/*
274262d4443fSHiren Panchasara 					 * Process first and second duplicate
274362d4443fSHiren Panchasara 					 * ACKs. Each indicates a segment
274462d4443fSHiren Panchasara 					 * leaving the network, creating room
274562d4443fSHiren Panchasara 					 * for more. Make sure we can send a
274662d4443fSHiren Panchasara 					 * packet on reception of each duplicate
274762d4443fSHiren Panchasara 					 * ACK by increasing snd_cwnd by one
274862d4443fSHiren Panchasara 					 * segment. Restore the original
274962d4443fSHiren Panchasara 					 * snd_cwnd after packet transmission.
275062d4443fSHiren Panchasara 					 */
27514b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
27524b7b743cSLawrence Stewart 					    CC_DUPACK);
27533ac12506SJonathan T. Looney 					uint32_t oldcwnd = tp->snd_cwnd;
275448d2549cSJeffrey Hsu 					tcp_seq oldsndmax = tp->snd_max;
275548d2549cSJeffrey Hsu 					u_int sent;
27565628dd08SAndre Oppermann 					int avail;
275789c02376SJeffrey Hsu 
2758582a954bSJeffrey Hsu 					KASSERT(tp->t_dupacks == 1 ||
2759582a954bSJeffrey Hsu 					    tp->t_dupacks == 2,
2760302ce8d6SAndre Oppermann 					    ("%s: dupacks not 1 or 2",
2761302ce8d6SAndre Oppermann 					    __func__));
276261a36e3dSJeffrey Hsu 					if (tp->t_dupacks == 1)
276348d2549cSJeffrey Hsu 						tp->snd_limited = 0;
276461a36e3dSJeffrey Hsu 					tp->snd_cwnd =
276561a36e3dSJeffrey Hsu 					    (tp->snd_nxt - tp->snd_una) +
276661a36e3dSJeffrey Hsu 					    (tp->t_dupacks - tp->snd_limited) *
27670c39d38dSGleb Smirnoff 					    maxseg;
27685628dd08SAndre Oppermann 					/*
27695628dd08SAndre Oppermann 					 * Only call tcp_output when there
27705ae83e0dSMichael Tuexen 					 * is new data available to be sent
27715ae83e0dSMichael Tuexen 					 * or we need to send an ACK.
27725628dd08SAndre Oppermann 					 */
27735628dd08SAndre Oppermann 					SOCKBUF_LOCK(&so->so_snd);
2774cfa6009eSGleb Smirnoff 					avail = sbavail(&so->so_snd) -
27755628dd08SAndre Oppermann 					    (tp->snd_nxt - tp->snd_una);
27765628dd08SAndre Oppermann 					SOCKBUF_UNLOCK(&so->so_snd);
27775ae83e0dSMichael Tuexen 					if (avail > 0 || tp->t_flags & TF_ACKNOW)
277840fa3e40SGleb Smirnoff 						(void) tcp_output(tp);
277948d2549cSJeffrey Hsu 					sent = tp->snd_max - oldsndmax;
27800c39d38dSGleb Smirnoff 					if (sent > maxseg) {
278189c02376SJeffrey Hsu 						KASSERT((tp->t_dupacks == 2 &&
278289c02376SJeffrey Hsu 						    tp->snd_limited == 0) ||
27830c39d38dSGleb Smirnoff 						   (sent == maxseg + 1 &&
278489c02376SJeffrey Hsu 						    tp->t_flags & TF_SENTFIN),
2785302ce8d6SAndre Oppermann 						    ("%s: sent too much",
2786302ce8d6SAndre Oppermann 						    __func__));
278748d2549cSJeffrey Hsu 						tp->snd_limited = 2;
278848d2549cSJeffrey Hsu 					} else if (sent > 0)
278948d2549cSJeffrey Hsu 						++tp->snd_limited;
2790582a954bSJeffrey Hsu 					tp->snd_cwnd = oldcwnd;
2791582a954bSJeffrey Hsu 					goto drop;
2792df8bae1dSRodney W. Grimes 				}
2793021eaf79SHiren Panchasara 			}
2794df8bae1dSRodney W. Grimes 			break;
2795021eaf79SHiren Panchasara 		} else {
2796021eaf79SHiren Panchasara 			/*
2797021eaf79SHiren Panchasara 			 * This ack is advancing the left edge, reset the
2798021eaf79SHiren Panchasara 			 * counter.
2799021eaf79SHiren Panchasara 			 */
2800021eaf79SHiren Panchasara 			tp->t_dupacks = 0;
2801021eaf79SHiren Panchasara 			/*
2802021eaf79SHiren Panchasara 			 * If this ack also has new SACK info, increment the
2803f359d6ebSRichard Scheffenegger 			 * counter as per rfc6675. The variable
2804f359d6ebSRichard Scheffenegger 			 * sack_changed tracks all changes to the SACK
2805f359d6ebSRichard Scheffenegger 			 * scoreboard, including when partial ACKs without
2806f359d6ebSRichard Scheffenegger 			 * SACK options are received, and clear the scoreboard
2807f359d6ebSRichard Scheffenegger 			 * from the left side. Such partial ACKs should not be
2808f359d6ebSRichard Scheffenegger 			 * counted as dupacks here.
2809021eaf79SHiren Panchasara 			 */
2810c21b7b55SRichard Scheffenegger 			if (tcp_is_sack_recovery(tp, &to) &&
28113c40e1d5SRichard Scheffenegger 			    sack_changed) {
2812021eaf79SHiren Panchasara 				tp->t_dupacks++;
28133c40e1d5SRichard Scheffenegger 				/* limit overhead by setting maxseg last */
28143c40e1d5SRichard Scheffenegger 				if (!IN_FASTRECOVERY(tp->t_flags) &&
28153c40e1d5SRichard Scheffenegger 				    (tp->sackhint.sacked_bytes >
28163c40e1d5SRichard Scheffenegger 				    ((tcprexmtthresh - 1) *
28173c40e1d5SRichard Scheffenegger 				    (maxseg = tcp_maxseg(tp))))) {
28183c40e1d5SRichard Scheffenegger 					goto enter_recovery;
28193c40e1d5SRichard Scheffenegger 				}
28203c40e1d5SRichard Scheffenegger 			}
2821df8bae1dSRodney W. Grimes 		}
2822cb942153SJeffrey Hsu 
28233c40e1d5SRichard Scheffenegger resume_partialack:
2824302ce8d6SAndre Oppermann 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2825302ce8d6SAndre Oppermann 		    ("%s: th_ack <= snd_una", __func__));
2826cb942153SJeffrey Hsu 
2827df8bae1dSRodney W. Grimes 		/*
2828df8bae1dSRodney W. Grimes 		 * If the congestion window was inflated to account
2829df8bae1dSRodney W. Grimes 		 * for the other side's cached packets, retract it.
2830df8bae1dSRodney W. Grimes 		 */
2831dbc42409SLawrence Stewart 		if (IN_FASTRECOVERY(tp->t_flags)) {
2832cb942153SJeffrey Hsu 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
28333529149eSAndre Oppermann 				if (tp->t_flags & TF_SACK_PERMIT)
2834eb3a59a8SRichard Scheffenegger 					if (V_tcp_do_prr && to.to_flags & TOF_SACK) {
2835eb3a59a8SRichard Scheffenegger 						tcp_timer_activate(tp, TT_REXMT, 0);
2836eb3a59a8SRichard Scheffenegger 						tp->t_rtttime = 0;
283790cca08eSRichard Scheffenegger 						tcp_do_prr_ack(tp, th, &to);
2838eb3a59a8SRichard Scheffenegger 						tp->t_flags |= TF_ACKNOW;
2839eb3a59a8SRichard Scheffenegger 						(void) tcp_output(tp);
2840eb3a59a8SRichard Scheffenegger 					} else
28416d90faf3SPaul Saab 						tcp_sack_partialack(tp, th);
28426d90faf3SPaul Saab 				else
2843c068736aSJeffrey Hsu 					tcp_newreno_partial_ack(tp, th);
2844dbc42409SLawrence Stewart 			} else
2845dbc42409SLawrence Stewart 				cc_post_recovery(tp, th);
2846b9f803b7SRichard Scheffenegger 		} else if (IN_CONGRECOVERY(tp->t_flags)) {
2847b9f803b7SRichard Scheffenegger 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2848b9f803b7SRichard Scheffenegger 				if (V_tcp_do_prr) {
2849b9f803b7SRichard Scheffenegger 					tp->sackhint.delivered_data = BYTES_THIS_ACK(tp, th);
2850b9f803b7SRichard Scheffenegger 					tp->snd_fack = th->th_ack;
285190cca08eSRichard Scheffenegger 					tcp_do_prr_ack(tp, th, &to);
2852b9f803b7SRichard Scheffenegger 					(void) tcp_output(tp);
2853b9f803b7SRichard Scheffenegger 				}
2854b9f803b7SRichard Scheffenegger 			} else
2855b9f803b7SRichard Scheffenegger 				cc_post_recovery(tp, th);
285646f58482SJonathan Lemon 		}
2857a0292f23SGarrett Wollman 		/*
2858a0292f23SGarrett Wollman 		 * If we reach this point, ACK is not a duplicate,
2859a0292f23SGarrett Wollman 		 *     i.e., it ACKs something we sent.
2860a0292f23SGarrett Wollman 		 */
2861a0292f23SGarrett Wollman 		if (tp->t_flags & TF_NEEDSYN) {
2862a0292f23SGarrett Wollman 			/*
2863a0292f23SGarrett Wollman 			 * T/TCP: Connection was half-synchronized, and our
2864a0292f23SGarrett Wollman 			 * SYN has been ACK'd (so connection is now fully
286507e43e10SAndras Olah 			 * synchronized).  Go to non-starred state,
286607e43e10SAndras Olah 			 * increment snd_una for ACK of SYN, and check if
286707e43e10SAndras Olah 			 * we can do window scaling.
2868a0292f23SGarrett Wollman 			 */
2869a0292f23SGarrett Wollman 			tp->t_flags &= ~TF_NEEDSYN;
2870a0292f23SGarrett Wollman 			tp->snd_una++;
287107e43e10SAndras Olah 			/* Do window scaling? */
287207e43e10SAndras Olah 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
287307e43e10SAndras Olah 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
287407e43e10SAndras Olah 				tp->rcv_scale = tp->request_r_scale;
2875464fcfbcSAndre Oppermann 				/* Send window already scaled. */
287607e43e10SAndras Olah 			}
2877a0292f23SGarrett Wollman 		}
2878a0292f23SGarrett Wollman 
2879a0292f23SGarrett Wollman process_ACK:
28808501a69cSRobert Watson 		INP_WLOCK_ASSERT(tp->t_inpcb);
28817cfc6904SRobert Watson 
2882b2ade6b1SRichard Scheffenegger 		/*
2883b2ade6b1SRichard Scheffenegger 		 * Adjust for the SYN bit in sequence space,
2884b2ade6b1SRichard Scheffenegger 		 * but don't account for it in cwnd calculations.
2885b2ade6b1SRichard Scheffenegger 		 * This is for the SYN_RECEIVED, non-simultaneous
2886b2ade6b1SRichard Scheffenegger 		 * SYN case. SYN_SENT and simultaneous SYN are
2887b2ade6b1SRichard Scheffenegger 		 * treated elsewhere.
2888b2ade6b1SRichard Scheffenegger 		 */
2889b2ade6b1SRichard Scheffenegger 		if (incforsyn)
2890b2ade6b1SRichard Scheffenegger 			tp->snd_una++;
2891dbc42409SLawrence Stewart 		acked = BYTES_THIS_ACK(tp, th);
2892b8c2cd15SJonathan T. Looney 		KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2893b8c2cd15SJonathan T. Looney 		    "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2894b8c2cd15SJonathan T. Looney 		    tp->snd_una, th->th_ack, tp, m));
28954b7b743cSLawrence Stewart 		TCPSTAT_ADD(tcps_rcvackpack, nsegs);
289678b50714SRobert Watson 		TCPSTAT_ADD(tcps_rcvackbyte, acked);
2897df8bae1dSRodney W. Grimes 
2898df8bae1dSRodney W. Grimes 		/*
28999b8b58e0SJonathan Lemon 		 * If we just performed our first retransmit, and the ACK
29009b8b58e0SJonathan Lemon 		 * arrives within our recovery window, then it was a mistake
29019b8b58e0SJonathan Lemon 		 * to do the retransmit in the first place.  Recover our
29029b8b58e0SJonathan Lemon 		 * original cwnd and ssthresh, and proceed to transmit where
29039b8b58e0SJonathan Lemon 		 * we left off.
29049b8b58e0SJonathan Lemon 		 */
290510d20c84SMatt Macy 		if (tp->t_rxtshift == 1 &&
290610d20c84SMatt Macy 		    tp->t_flags & TF_PREVVALID &&
29074531b345SRichard Scheffenegger 		    tp->t_badrxtwin != 0 &&
29084531b345SRichard Scheffenegger 		    to.to_flags & TOF_TS &&
29094531b345SRichard Scheffenegger 		    to.to_tsecr != 0 &&
29104531b345SRichard Scheffenegger 		    TSTMP_LT(to.to_tsecr, tp->t_badrxtwin))
2911dbc42409SLawrence Stewart 			cc_cong_signal(tp, th, CC_RTO_ERR);
29129b8b58e0SJonathan Lemon 
29139b8b58e0SJonathan Lemon 		/*
2914df8bae1dSRodney W. Grimes 		 * If we have a timestamp reply, update smoothed
2915df8bae1dSRodney W. Grimes 		 * round trip time.  If no timestamp is present but
2916df8bae1dSRodney W. Grimes 		 * transmit timer is running and timed sequence
2917df8bae1dSRodney W. Grimes 		 * number was acked, update smoothed round trip time.
2918df8bae1dSRodney W. Grimes 		 * Since we now have an rtt measurement, cancel the
2919df8bae1dSRodney W. Grimes 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2920df8bae1dSRodney W. Grimes 		 * Recompute the initial retransmit timer.
2921fa55172bSMatthew Dillon 		 *
2922fa55172bSMatthew Dillon 		 * Some boxes send broken timestamp replies
2923fa55172bSMatthew Dillon 		 * during the SYN+ACK phase, ignore
2924fa55172bSMatthew Dillon 		 * timestamps of 0 or we could calculate a
2925fa55172bSMatthew Dillon 		 * huge RTT and blow up the retransmit timer.
2926df8bae1dSRodney W. Grimes 		 */
2927d8951c8aSBjoern A. Zeeb 		if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
29283ac12506SJonathan T. Looney 			uint32_t t;
2929d8951c8aSBjoern A. Zeeb 
2930d8951c8aSBjoern A. Zeeb 			t = tcp_ts_getticks() - to.to_tsecr;
2931d8951c8aSBjoern A. Zeeb 			if (!tp->t_rttlow || tp->t_rttlow > t)
2932d8951c8aSBjoern A. Zeeb 				tp->t_rttlow = t;
2933d8951c8aSBjoern A. Zeeb 			tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2934fa55172bSMatthew Dillon 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2935eaf80179SAndre Oppermann 			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2936eaf80179SAndre Oppermann 				tp->t_rttlow = ticks - tp->t_rtttime;
29379b8b58e0SJonathan Lemon 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2938fa55172bSMatthew Dillon 		}
2939df8bae1dSRodney W. Grimes 
294008af8aacSRandall Stewart 		SOCKBUF_LOCK(&so->so_snd);
294108af8aacSRandall Stewart 		/*
294208af8aacSRandall Stewart 		 * Clear t_acktime if remote side has ACKd all data in the
294308af8aacSRandall Stewart 		 * socket buffer and FIN (if applicable).
294408af8aacSRandall Stewart 		 * Otherwise, update t_acktime if we received a sufficiently
294508af8aacSRandall Stewart 		 * large ACK.
294608af8aacSRandall Stewart 		 */
294708af8aacSRandall Stewart 		if ((tp->t_state <= TCPS_CLOSE_WAIT &&
294808af8aacSRandall Stewart 		    acked == sbavail(&so->so_snd)) ||
294908af8aacSRandall Stewart 		    acked > sbavail(&so->so_snd))
295008af8aacSRandall Stewart 			tp->t_acktime = 0;
295108af8aacSRandall Stewart 		else if (acked > 1)
295208af8aacSRandall Stewart 			tp->t_acktime = ticks;
295308af8aacSRandall Stewart 
2954df8bae1dSRodney W. Grimes 		/*
2955df8bae1dSRodney W. Grimes 		 * If all outstanding data is acked, stop retransmit
2956df8bae1dSRodney W. Grimes 		 * timer and remember to restart (more output or persist).
2957df8bae1dSRodney W. Grimes 		 * If there is more data to be acked, restart retransmit
2958df8bae1dSRodney W. Grimes 		 * timer, using current (possibly backed-off) value.
2959df8bae1dSRodney W. Grimes 		 */
2960fb59c426SYoshinobu Inoue 		if (th->th_ack == tp->snd_max) {
2961b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
2962df8bae1dSRodney W. Grimes 			needoutput = 1;
2963b8152ba7SAndre Oppermann 		} else if (!tcp_timer_active(tp, TT_PERSIST))
296408af8aacSRandall Stewart 			tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp));
2965a0292f23SGarrett Wollman 
2966a0292f23SGarrett Wollman 		/*
2967a0292f23SGarrett Wollman 		 * If no data (only SYN) was ACK'd,
2968a0292f23SGarrett Wollman 		 *    skip rest of ACK processing.
2969a0292f23SGarrett Wollman 		 */
297008af8aacSRandall Stewart 		if (acked == 0) {
297108af8aacSRandall Stewart 			SOCKBUF_UNLOCK(&so->so_snd);
2972a0292f23SGarrett Wollman 			goto step6;
297308af8aacSRandall Stewart 		}
2974a0292f23SGarrett Wollman 
2975df8bae1dSRodney W. Grimes 		/*
2976dbc42409SLawrence Stewart 		 * Let the congestion control algorithm update congestion
2977dbc42409SLawrence Stewart 		 * control related information. This typically means increasing
2978dbc42409SLawrence Stewart 		 * the congestion window.
2979df8bae1dSRodney W. Grimes 		 */
29804b7b743cSLawrence Stewart 		cc_ack_received(tp, th, nsegs, CC_ACK);
2981dbc42409SLawrence Stewart 
2982cfa6009eSGleb Smirnoff 		if (acked > sbavail(&so->so_snd)) {
2983b8c2cd15SJonathan T. Looney 			if (tp->snd_wnd >= sbavail(&so->so_snd))
2984cfa6009eSGleb Smirnoff 				tp->snd_wnd -= sbavail(&so->so_snd);
2985b8c2cd15SJonathan T. Looney 			else
2986b8c2cd15SJonathan T. Looney 				tp->snd_wnd = 0;
2987c11a15bfSGleb Smirnoff 			mfree = sbcut_locked(&so->so_snd,
2988cfa6009eSGleb Smirnoff 			    (int)sbavail(&so->so_snd));
2989df8bae1dSRodney W. Grimes 			ourfinisacked = 1;
2990df8bae1dSRodney W. Grimes 		} else {
2991c11a15bfSGleb Smirnoff 			mfree = sbcut_locked(&so->so_snd, acked);
29923ac12506SJonathan T. Looney 			if (tp->snd_wnd >= (uint32_t) acked)
299360ee3bb2SAndre Oppermann 				tp->snd_wnd -= acked;
2994b8c2cd15SJonathan T. Looney 			else
2995b8c2cd15SJonathan T. Looney 				tp->snd_wnd = 0;
2996df8bae1dSRodney W. Grimes 			ourfinisacked = 0;
2997df8bae1dSRodney W. Grimes 		}
2998032bf749SRichard Scheffenegger 		/* NB: sowwakeup_locked() does an implicit unlock. */
2999032bf749SRichard Scheffenegger 		sowwakeup_locked(so);
3000c11a15bfSGleb Smirnoff 		m_freem(mfree);
3001e8949f74SAndre Oppermann 		/* Detect una wraparound. */
3002dbc42409SLawrence Stewart 		if (!IN_RECOVERY(tp->t_flags) &&
30039d11646dSJeffrey Hsu 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
30049d11646dSJeffrey Hsu 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
30059d11646dSJeffrey Hsu 			tp->snd_recover = th->th_ack - 1;
3006dbc42409SLawrence Stewart 		/* XXXLAS: Can this be moved up into cc_post_recovery? */
3007dbc42409SLawrence Stewart 		if (IN_RECOVERY(tp->t_flags) &&
300824cb0f22SLawrence Stewart 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
3009dbc42409SLawrence Stewart 			EXIT_RECOVERY(tp->t_flags);
301024cb0f22SLawrence Stewart 		}
3011fb59c426SYoshinobu Inoue 		tp->snd_una = th->th_ack;
30123529149eSAndre Oppermann 		if (tp->t_flags & TF_SACK_PERMIT) {
30136d90faf3SPaul Saab 			if (SEQ_GT(tp->snd_una, tp->snd_recover))
30146d90faf3SPaul Saab 				tp->snd_recover = tp->snd_una;
30156d90faf3SPaul Saab 		}
3016df8bae1dSRodney W. Grimes 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
3017df8bae1dSRodney W. Grimes 			tp->snd_nxt = tp->snd_una;
3018df8bae1dSRodney W. Grimes 
3019df8bae1dSRodney W. Grimes 		switch (tp->t_state) {
3020df8bae1dSRodney W. Grimes 		/*
3021df8bae1dSRodney W. Grimes 		 * In FIN_WAIT_1 STATE in addition to the processing
3022df8bae1dSRodney W. Grimes 		 * for the ESTABLISHED state if our FIN is now acknowledged
3023df8bae1dSRodney W. Grimes 		 * then enter FIN_WAIT_2.
3024df8bae1dSRodney W. Grimes 		 */
3025df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_1:
3026df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
3027df8bae1dSRodney W. Grimes 				/*
3028df8bae1dSRodney W. Grimes 				 * If we can't receive any more
3029df8bae1dSRodney W. Grimes 				 * data, then closing user can proceed.
3030df8bae1dSRodney W. Grimes 				 * Starting the timer is contrary to the
3031df8bae1dSRodney W. Grimes 				 * specification, but if we don't get a FIN
3032df8bae1dSRodney W. Grimes 				 * we'll hang forever.
3033340c35deSJonathan Lemon 				 */
3034c0b99ffaSRobert Watson 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
303503e49181SSeigo Tanimura 					soisdisconnected(so);
30369077f387SGleb Smirnoff 					tcp_timer_activate(tp, TT_2MSL,
30379077f387SGleb Smirnoff 					    (tcp_fast_finwait2_recycle ?
30389077f387SGleb Smirnoff 					    tcp_finwait2_timeout :
30399077f387SGleb Smirnoff 					    TP_MAXIDLE(tp)));
30404cc20ab1SSeigo Tanimura 				}
304157f60867SMark Johnston 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
3042df8bae1dSRodney W. Grimes 			}
3043df8bae1dSRodney W. Grimes 			break;
3044df8bae1dSRodney W. Grimes 
3045df8bae1dSRodney W. Grimes 		/*
3046df8bae1dSRodney W. Grimes 		 * In CLOSING STATE in addition to the processing for
3047df8bae1dSRodney W. Grimes 		 * the ESTABLISHED state if the ACK acknowledges our FIN
3048df8bae1dSRodney W. Grimes 		 * then enter the TIME-WAIT state, otherwise ignore
3049df8bae1dSRodney W. Grimes 		 * the segment.
3050df8bae1dSRodney W. Grimes 		 */
3051df8bae1dSRodney W. Grimes 		case TCPS_CLOSING:
3052df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
305311a20fb8SJeffrey Hsu 				tcp_twstart(tp);
3054340c35deSJonathan Lemon 				m_freem(m);
3055679d9708SAndre Oppermann 				return;
3056df8bae1dSRodney W. Grimes 			}
3057df8bae1dSRodney W. Grimes 			break;
3058df8bae1dSRodney W. Grimes 
3059df8bae1dSRodney W. Grimes 		/*
3060df8bae1dSRodney W. Grimes 		 * In LAST_ACK, we may still be waiting for data to drain
3061df8bae1dSRodney W. Grimes 		 * and/or to be acked, as well as for the ack of our FIN.
3062df8bae1dSRodney W. Grimes 		 * If our FIN is now acknowledged, delete the TCB,
3063df8bae1dSRodney W. Grimes 		 * enter the closed state and return.
3064df8bae1dSRodney W. Grimes 		 */
3065df8bae1dSRodney W. Grimes 		case TCPS_LAST_ACK:
3066df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
3067df8bae1dSRodney W. Grimes 				tp = tcp_close(tp);
3068df8bae1dSRodney W. Grimes 				goto drop;
3069df8bae1dSRodney W. Grimes 			}
3070df8bae1dSRodney W. Grimes 			break;
3071df8bae1dSRodney W. Grimes 		}
3072df8bae1dSRodney W. Grimes 	}
3073df8bae1dSRodney W. Grimes 
3074df8bae1dSRodney W. Grimes step6:
30758501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
30767cfc6904SRobert Watson 
3077df8bae1dSRodney W. Grimes 	/*
307860ee3bb2SAndre Oppermann 	 * Update window information.
307960ee3bb2SAndre Oppermann 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
3080df8bae1dSRodney W. Grimes 	 */
308160ee3bb2SAndre Oppermann 	if ((thflags & TH_ACK) &&
308260ee3bb2SAndre Oppermann 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
308360ee3bb2SAndre Oppermann 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
308460ee3bb2SAndre Oppermann 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
308560ee3bb2SAndre Oppermann 		/* keep track of pure window updates */
308660ee3bb2SAndre Oppermann 		if (tlen == 0 &&
308760ee3bb2SAndre Oppermann 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
308878b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvwinupd);
3089df8bae1dSRodney W. Grimes 		tp->snd_wnd = tiwin;
309060ee3bb2SAndre Oppermann 		tp->snd_wl1 = th->th_seq;
309160ee3bb2SAndre Oppermann 		tp->snd_wl2 = th->th_ack;
3092df8bae1dSRodney W. Grimes 		if (tp->snd_wnd > tp->max_sndwnd)
3093df8bae1dSRodney W. Grimes 			tp->max_sndwnd = tp->snd_wnd;
309460ee3bb2SAndre Oppermann 		needoutput = 1;
3095df8bae1dSRodney W. Grimes 	}
3096df8bae1dSRodney W. Grimes 
3097df8bae1dSRodney W. Grimes 	/*
3098df8bae1dSRodney W. Grimes 	 * Process segments with URG.
3099df8bae1dSRodney W. Grimes 	 */
3100fb59c426SYoshinobu Inoue 	if ((thflags & TH_URG) && th->th_urp &&
3101df8bae1dSRodney W. Grimes 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3102df8bae1dSRodney W. Grimes 		/*
3103df8bae1dSRodney W. Grimes 		 * This is a kludge, but if we receive and accept
3104df8bae1dSRodney W. Grimes 		 * random urgent pointers, we'll crash in
3105df8bae1dSRodney W. Grimes 		 * soreceive.  It's hard to imagine someone
3106df8bae1dSRodney W. Grimes 		 * actually wanting to send this much urgent data.
3107df8bae1dSRodney W. Grimes 		 */
310818ad5842SRobert Watson 		SOCKBUF_LOCK(&so->so_rcv);
3109cfa6009eSGleb Smirnoff 		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
3110fb59c426SYoshinobu Inoue 			th->th_urp = 0;			/* XXX */
3111fb59c426SYoshinobu Inoue 			thflags &= ~TH_URG;		/* XXX */
311218ad5842SRobert Watson 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
3113df8bae1dSRodney W. Grimes 			goto dodata;			/* XXX */
3114df8bae1dSRodney W. Grimes 		}
3115df8bae1dSRodney W. Grimes 		/*
3116df8bae1dSRodney W. Grimes 		 * If this segment advances the known urgent pointer,
3117df8bae1dSRodney W. Grimes 		 * then mark the data stream.  This should not happen
3118df8bae1dSRodney W. Grimes 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
3119df8bae1dSRodney W. Grimes 		 * a FIN has been received from the remote side.
3120df8bae1dSRodney W. Grimes 		 * In these states we ignore the URG.
3121df8bae1dSRodney W. Grimes 		 *
3122df8bae1dSRodney W. Grimes 		 * According to RFC961 (Assigned Protocols),
3123df8bae1dSRodney W. Grimes 		 * the urgent pointer points to the last octet
3124df8bae1dSRodney W. Grimes 		 * of urgent data.  We continue, however,
3125df8bae1dSRodney W. Grimes 		 * to consider it to indicate the first octet
3126df8bae1dSRodney W. Grimes 		 * of data past the urgent section as the original
3127df8bae1dSRodney W. Grimes 		 * spec states (in one of two places).
3128df8bae1dSRodney W. Grimes 		 */
3129fb59c426SYoshinobu Inoue 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
3130fb59c426SYoshinobu Inoue 			tp->rcv_up = th->th_seq + th->th_urp;
3131cfa6009eSGleb Smirnoff 			so->so_oobmark = sbavail(&so->so_rcv) +
3132df8bae1dSRodney W. Grimes 			    (tp->rcv_up - tp->rcv_nxt) - 1;
3133927c5ceaSRobert Watson 			if (so->so_oobmark == 0)
3134c0b99ffaSRobert Watson 				so->so_rcv.sb_state |= SBS_RCVATMARK;
3135df8bae1dSRodney W. Grimes 			sohasoutofband(so);
3136df8bae1dSRodney W. Grimes 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
3137df8bae1dSRodney W. Grimes 		}
313818ad5842SRobert Watson 		SOCKBUF_UNLOCK(&so->so_rcv);
3139df8bae1dSRodney W. Grimes 		/*
3140df8bae1dSRodney W. Grimes 		 * Remove out of band data so doesn't get presented to user.
3141df8bae1dSRodney W. Grimes 		 * This can happen independent of advancing the URG pointer,
3142df8bae1dSRodney W. Grimes 		 * but if two URG's are pending at once, some out-of-band
3143df8bae1dSRodney W. Grimes 		 * data may creep in... ick.
3144df8bae1dSRodney W. Grimes 		 */
31453ac12506SJonathan T. Looney 		if (th->th_urp <= (uint32_t)tlen &&
314630613f56SJeffrey Hsu 		    !(so->so_options & SO_OOBINLINE)) {
314730613f56SJeffrey Hsu 			/* hdr drop is delayed */
314830613f56SJeffrey Hsu 			tcp_pulloutofband(so, th, m, drop_hdrlen);
314930613f56SJeffrey Hsu 		}
3150c068736aSJeffrey Hsu 	} else {
3151df8bae1dSRodney W. Grimes 		/*
3152df8bae1dSRodney W. Grimes 		 * If no out of band data is expected,
3153df8bae1dSRodney W. Grimes 		 * pull receive urgent pointer along
3154df8bae1dSRodney W. Grimes 		 * with the receive window.
3155df8bae1dSRodney W. Grimes 		 */
3156df8bae1dSRodney W. Grimes 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3157df8bae1dSRodney W. Grimes 			tp->rcv_up = tp->rcv_nxt;
3158c068736aSJeffrey Hsu 	}
3159df8bae1dSRodney W. Grimes dodata:							/* XXX */
31608501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
31617cfc6904SRobert Watson 
3162df8bae1dSRodney W. Grimes 	/*
3163df8bae1dSRodney W. Grimes 	 * Process the segment text, merging it into the TCP sequencing queue,
3164df8bae1dSRodney W. Grimes 	 * and arranging for acknowledgment of receipt if necessary.
3165df8bae1dSRodney W. Grimes 	 * This process logically involves adjusting tp->rcv_wnd as data
3166df8bae1dSRodney W. Grimes 	 * is presented to the user (this happens in tcp_usrreq.c,
3167df8bae1dSRodney W. Grimes 	 * case PRU_RCVD).  If a FIN has already been received on this
3168df8bae1dSRodney W. Grimes 	 * connection then we just ignore the text.
3169df8bae1dSRodney W. Grimes 	 */
3170281a0fd4SPatrick Kelsey 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
317168bd7ed1SJonathan T. Looney 		   IS_FASTOPEN(tp->t_flags));
3172f1ea4e41SRandall Stewart 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
3173df8bae1dSRodney W. Grimes 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
317469e03620SPaul Saab 		tcp_seq save_start = th->th_seq;
31755acfd95cSMichael Tuexen 		tcp_seq save_rnxt  = tp->rcv_nxt;
31765acfd95cSMichael Tuexen 		int     save_tlen  = tlen;
3177fb59c426SYoshinobu Inoue 		m_adj(m, drop_hdrlen);	/* delayed header drop */
3178e4b64281SJesper Skriver 		/*
3179c068736aSJeffrey Hsu 		 * Insert segment which includes th into TCP reassembly queue
3180c068736aSJeffrey Hsu 		 * with control block tp.  Set thflags to whether reassembly now
3181c068736aSJeffrey Hsu 		 * includes a segment with FIN.  This handles the common case
3182c068736aSJeffrey Hsu 		 * inline (segment is the next to be received on an established
3183c068736aSJeffrey Hsu 		 * connection, and the queue is empty), avoiding linkage into
3184c068736aSJeffrey Hsu 		 * and removal from the queue and repetition of various
3185c068736aSJeffrey Hsu 		 * conversions.
3186c068736aSJeffrey Hsu 		 * Set DELACK for segments received in order, but ack
3187c068736aSJeffrey Hsu 		 * immediately when segments are out of order (so
3188c068736aSJeffrey Hsu 		 * fast retransmit can work).
3189e4b64281SJesper Skriver 		 */
31904741bfcbSPatrick Kelsey 		if (th->th_seq == tp->rcv_nxt &&
3191c28440dbSRandall Stewart 		    SEGQ_EMPTY(tp) &&
3192281a0fd4SPatrick Kelsey 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
3193281a0fd4SPatrick Kelsey 		     tfo_syn)) {
3194281a0fd4SPatrick Kelsey 			if (DELAY_ACK(tp, tlen) || tfo_syn)
31953bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
3196e4b64281SJesper Skriver 			else
3197e4b64281SJesper Skriver 				tp->t_flags |= TF_ACKNOW;
3198e4b64281SJesper Skriver 			tp->rcv_nxt += tlen;
3199e854dd38SRandall Stewart 			if (tlen &&
3200e854dd38SRandall Stewart 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
3201e854dd38SRandall Stewart 			    (tp->t_fbyte_in == 0)) {
3202e854dd38SRandall Stewart 				tp->t_fbyte_in = ticks;
3203e854dd38SRandall Stewart 				if (tp->t_fbyte_in == 0)
3204e854dd38SRandall Stewart 					tp->t_fbyte_in = 1;
3205e854dd38SRandall Stewart 				if (tp->t_fbyte_out && tp->t_fbyte_in)
3206e854dd38SRandall Stewart 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
3207e854dd38SRandall Stewart 			}
32081ebf4607SRichard Scheffenegger 			thflags = tcp_get_flags(th) & TH_FIN;
320978b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpack);
321078b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
32111e4d7da7SRobert Watson 			SOCKBUF_LOCK(&so->so_rcv);
3212c0b99ffaSRobert Watson 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3213c1c36a2cSMike Silbersack 				m_freem(m);
3214c1c36a2cSMike Silbersack 			else
3215651e4e6aSGleb Smirnoff 				sbappendstream_locked(&so->so_rcv, m, 0);
32164d0770f1SRichard Scheffenegger 			tp->t_flags |= TF_WAKESOR;
3217e4b64281SJesper Skriver 		} else {
3218e8949f74SAndre Oppermann 			/*
3219e8949f74SAndre Oppermann 			 * XXX: Due to the header drop above "th" is
3220e8949f74SAndre Oppermann 			 * theoretically invalid by now.  Fortunately
3221e8949f74SAndre Oppermann 			 * m_adj() doesn't actually frees any mbufs
3222e8949f74SAndre Oppermann 			 * when trimming from the head.
3223e8949f74SAndre Oppermann 			 */
32245acfd95cSMichael Tuexen 			tcp_seq temp = save_start;
32254747500dSRandall Stewart 
32265acfd95cSMichael Tuexen 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
3227e4b64281SJesper Skriver 			tp->t_flags |= TF_ACKNOW;
3228e4b64281SJesper Skriver 		}
322940f41eceSMichael Tuexen 		if ((tp->t_flags & TF_SACK_PERMIT) &&
323040f41eceSMichael Tuexen 		    (save_tlen > 0) &&
323140f41eceSMichael Tuexen 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
32326d261981SMichael Tuexen 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3233b5a154d8SMichael Tuexen 				/*
3234b5a154d8SMichael Tuexen 				 * DSACK actually handled in the fastpath
3235b5a154d8SMichael Tuexen 				 * above.
3236b5a154d8SMichael Tuexen 				 */
3237ecc5b1d1SMichael Tuexen 				tcp_update_sack_list(tp, save_start,
3238ecc5b1d1SMichael Tuexen 				    save_start + save_tlen);
3239ecc5b1d1SMichael Tuexen 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3240ecc5b1d1SMichael Tuexen 				if ((tp->rcv_numsacks >= 1) &&
3241ecc5b1d1SMichael Tuexen 				    (tp->sackblks[0].end == save_start)) {
32426d261981SMichael Tuexen 					/*
32436d261981SMichael Tuexen 					 * Partial overlap, recorded at todrop
32446d261981SMichael Tuexen 					 * above.
32456d261981SMichael Tuexen 					 */
32466d261981SMichael Tuexen 					tcp_update_sack_list(tp,
32476d261981SMichael Tuexen 					    tp->sackblks[0].start,
3248ecc5b1d1SMichael Tuexen 					    tp->sackblks[0].end);
3249ecc5b1d1SMichael Tuexen 				} else {
3250ecc5b1d1SMichael Tuexen 					tcp_update_dsack_list(tp, save_start,
3251ecc5b1d1SMichael Tuexen 					    save_start + save_tlen);
3252ecc5b1d1SMichael Tuexen 				}
32536d261981SMichael Tuexen 			} else if (tlen >= save_tlen) {
3254b5a154d8SMichael Tuexen 				/* Update of sackblks. */
3255ecc5b1d1SMichael Tuexen 				tcp_update_dsack_list(tp, save_start,
3256ecc5b1d1SMichael Tuexen 				    save_start + save_tlen);
3257ecc5b1d1SMichael Tuexen 			} else if (tlen > 0) {
3258ecc5b1d1SMichael Tuexen 				tcp_update_dsack_list(tp, save_start,
3259ecc5b1d1SMichael Tuexen 				    save_start + tlen);
32605acfd95cSMichael Tuexen 			}
32615acfd95cSMichael Tuexen 		}
3262032bf749SRichard Scheffenegger 		tcp_handle_wakeup(tp, so);
3263302ce8d6SAndre Oppermann #if 0
3264df8bae1dSRodney W. Grimes 		/*
3265df8bae1dSRodney W. Grimes 		 * Note the amount of data that peer has sent into
3266df8bae1dSRodney W. Grimes 		 * our window, in order to estimate the sender's
3267df8bae1dSRodney W. Grimes 		 * buffer size.
3268302ce8d6SAndre Oppermann 		 * XXX: Unused.
3269df8bae1dSRodney W. Grimes 		 */
3270f701e30dSJohn Baldwin 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3271df8bae1dSRodney W. Grimes 			len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3272f701e30dSJohn Baldwin 		else
3273f701e30dSJohn Baldwin 			len = so->so_rcv.sb_hiwat;
3274302ce8d6SAndre Oppermann #endif
3275df8bae1dSRodney W. Grimes 	} else {
3276df8bae1dSRodney W. Grimes 		m_freem(m);
3277fb59c426SYoshinobu Inoue 		thflags &= ~TH_FIN;
3278df8bae1dSRodney W. Grimes 	}
3279df8bae1dSRodney W. Grimes 
3280df8bae1dSRodney W. Grimes 	/*
3281df8bae1dSRodney W. Grimes 	 * If FIN is received ACK the FIN and let the user know
3282df8bae1dSRodney W. Grimes 	 * that the connection is closing.
3283df8bae1dSRodney W. Grimes 	 */
3284fb59c426SYoshinobu Inoue 	if (thflags & TH_FIN) {
3285df8bae1dSRodney W. Grimes 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
32864d0770f1SRichard Scheffenegger 			/* The socket upcall is handled by socantrcvmore. */
3287032bf749SRichard Scheffenegger 			socantrcvmore(so);
3288a0292f23SGarrett Wollman 			/*
3289a0292f23SGarrett Wollman 			 * If connection is half-synchronized
3290d3eede9dSAndras Olah 			 * (ie NEEDSYN flag on) then delay ACK,
3291a0292f23SGarrett Wollman 			 * so it may be piggybacked when SYN is sent.
3292a0292f23SGarrett Wollman 			 * Otherwise, since we received a FIN then no
3293a0292f23SGarrett Wollman 			 * more input can be expected, send ACK now.
3294a0292f23SGarrett Wollman 			 */
32953bfd6421SJonathan Lemon 			if (tp->t_flags & TF_NEEDSYN)
32963bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
3297a0292f23SGarrett Wollman 			else
3298df8bae1dSRodney W. Grimes 				tp->t_flags |= TF_ACKNOW;
3299df8bae1dSRodney W. Grimes 			tp->rcv_nxt++;
3300df8bae1dSRodney W. Grimes 		}
3301df8bae1dSRodney W. Grimes 		switch (tp->t_state) {
3302df8bae1dSRodney W. Grimes 		/*
3303df8bae1dSRodney W. Grimes 		 * In SYN_RECEIVED and ESTABLISHED STATES
3304df8bae1dSRodney W. Grimes 		 * enter the CLOSE_WAIT state.
3305df8bae1dSRodney W. Grimes 		 */
3306df8bae1dSRodney W. Grimes 		case TCPS_SYN_RECEIVED:
33079b8b58e0SJonathan Lemon 			tp->t_starttime = ticks;
33089b8b58e0SJonathan Lemon 			/* FALLTHROUGH */
3309df8bae1dSRodney W. Grimes 		case TCPS_ESTABLISHED:
331057f60867SMark Johnston 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
3311df8bae1dSRodney W. Grimes 			break;
3312df8bae1dSRodney W. Grimes 
3313df8bae1dSRodney W. Grimes 		/*
3314df8bae1dSRodney W. Grimes 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3315df8bae1dSRodney W. Grimes 		 * enter the CLOSING state.
3316df8bae1dSRodney W. Grimes 		 */
3317df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_1:
331857f60867SMark Johnston 			tcp_state_change(tp, TCPS_CLOSING);
3319df8bae1dSRodney W. Grimes 			break;
3320df8bae1dSRodney W. Grimes 
3321df8bae1dSRodney W. Grimes 		/*
3322df8bae1dSRodney W. Grimes 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3323df8bae1dSRodney W. Grimes 		 * starting the time-wait timer, turning off the other
3324df8bae1dSRodney W. Grimes 		 * standard timers.
3325df8bae1dSRodney W. Grimes 		 */
3326df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_2:
3327340c35deSJonathan Lemon 			tcp_twstart(tp);
3328679d9708SAndre Oppermann 			return;
3329df8bae1dSRodney W. Grimes 		}
3330df8bae1dSRodney W. Grimes 	}
3331610ee2f9SDavid Greenman #ifdef TCPDEBUG
33324cc20ab1SSeigo Tanimura 	if (so->so_options & SO_DEBUG)
3333fb59c426SYoshinobu Inoue 		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3334fb59c426SYoshinobu Inoue 			  &tcp_savetcp, 0);
3335610ee2f9SDavid Greenman #endif
33362b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
3337df8bae1dSRodney W. Grimes 
3338df8bae1dSRodney W. Grimes 	/*
3339df8bae1dSRodney W. Grimes 	 * Return any desired output.
3340df8bae1dSRodney W. Grimes 	 */
3341df8bae1dSRodney W. Grimes 	if (needoutput || (tp->t_flags & TF_ACKNOW))
334240fa3e40SGleb Smirnoff 		(void) tcp_output(tp);
33437792ea27SJeffrey Hsu 
3344a14c749fSJonathan Lemon check_delack:
33458501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
3346252ca428SRobert Watson 
3347a14c749fSJonathan Lemon 	if (tp->t_flags & TF_DELACK) {
33483bfd6421SJonathan Lemon 		tp->t_flags &= ~TF_DELACK;
3349b8152ba7SAndre Oppermann 		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
33503bfd6421SJonathan Lemon 	}
33518501a69cSRobert Watson 	INP_WUNLOCK(tp->t_inpcb);
3352679d9708SAndre Oppermann 	return;
3353df8bae1dSRodney W. Grimes 
3354df8bae1dSRodney W. Grimes dropafterack:
3355df8bae1dSRodney W. Grimes 	/*
3356df8bae1dSRodney W. Grimes 	 * Generate an ACK dropping incoming segment if it occupies
3357df8bae1dSRodney W. Grimes 	 * sequence space, where the ACK reflects our state.
335880ab7c0eSGarrett Wollman 	 *
335980ab7c0eSGarrett Wollman 	 * We can now skip the test for the RST flag since all
336080ab7c0eSGarrett Wollman 	 * paths to this code happen after packets containing
336180ab7c0eSGarrett Wollman 	 * RST have been dropped.
336280ab7c0eSGarrett Wollman 	 *
336380ab7c0eSGarrett Wollman 	 * In the SYN-RECEIVED state, don't send an ACK unless the
336480ab7c0eSGarrett Wollman 	 * segment we received passes the SYN-RECEIVED ACK test.
336580ab7c0eSGarrett Wollman 	 * If it fails send a RST.  This breaks the loop in the
336680ab7c0eSGarrett Wollman 	 * "LAND" DoS attack, and also prevents an ACK storm
336780ab7c0eSGarrett Wollman 	 * between two listening ports that have been sent forged
336880ab7c0eSGarrett Wollman 	 * SYN segments, each with the source address of the other.
3369df8bae1dSRodney W. Grimes 	 */
3370fb59c426SYoshinobu Inoue 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3371fb59c426SYoshinobu Inoue 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
3372a57815efSBosko Milekic 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
3373a57815efSBosko Milekic 		rstreason = BANDLIM_RST_OPENPORT;
3374d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
3375a57815efSBosko Milekic 		goto dropwithreset;
3376a57815efSBosko Milekic 	}
3377a0292f23SGarrett Wollman #ifdef TCPDEBUG
33784cc20ab1SSeigo Tanimura 	if (so->so_options & SO_DEBUG)
3379fb59c426SYoshinobu Inoue 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3380fb59c426SYoshinobu Inoue 			  &tcp_savetcp, 0);
3381a0292f23SGarrett Wollman #endif
33822b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
3383df8bae1dSRodney W. Grimes 	tp->t_flags |= TF_ACKNOW;
338440fa3e40SGleb Smirnoff 	(void) tcp_output(tp);
33858501a69cSRobert Watson 	INP_WUNLOCK(tp->t_inpcb);
3386d6915262SRobert Watson 	m_freem(m);
3387679d9708SAndre Oppermann 	return;
3388df8bae1dSRodney W. Grimes 
3389df8bae1dSRodney W. Grimes dropwithreset:
3390a0ca0871SRobert Watson 	if (tp != NULL) {
3391302ce8d6SAndre Oppermann 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
33928501a69cSRobert Watson 		INP_WUNLOCK(tp->t_inpcb);
3393dd8ac7f9SRobert Watson 	} else
3394a0ca0871SRobert Watson 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3395679d9708SAndre Oppermann 	return;
3396df8bae1dSRodney W. Grimes 
3397df8bae1dSRodney W. Grimes drop:
3398df8bae1dSRodney W. Grimes 	/*
3399df8bae1dSRodney W. Grimes 	 * Drop space held by incoming segment and return.
3400df8bae1dSRodney W. Grimes 	 */
3401610ee2f9SDavid Greenman #ifdef TCPDEBUG
34021c53f806SRobert Watson 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3403fb59c426SYoshinobu Inoue 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3404fb59c426SYoshinobu Inoue 			  &tcp_savetcp, 0);
3405a0292f23SGarrett Wollman #endif
34062b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
34074d0770f1SRichard Scheffenegger 	if (tp != NULL) {
34088501a69cSRobert Watson 		INP_WUNLOCK(tp->t_inpcb);
34094d0770f1SRichard Scheffenegger 	}
3410d6915262SRobert Watson 	m_freem(m);
3411302ce8d6SAndre Oppermann }
3412302ce8d6SAndre Oppermann 
3413302ce8d6SAndre Oppermann /*
34140ca3f933SAndre Oppermann  * Issue RST and make ACK acceptable to originator of segment.
34150ca3f933SAndre Oppermann  * The mbuf must still include the original packet header.
34160ca3f933SAndre Oppermann  * tp may be NULL.
3417302ce8d6SAndre Oppermann  */
341855bceb1eSRandall Stewart void
3419302ce8d6SAndre Oppermann tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3420302ce8d6SAndre Oppermann     int tlen, int rstreason)
3421302ce8d6SAndre Oppermann {
3422b287c6c7SBjoern A. Zeeb #ifdef INET
3423302ce8d6SAndre Oppermann 	struct ip *ip;
3424b287c6c7SBjoern A. Zeeb #endif
3425302ce8d6SAndre Oppermann #ifdef INET6
3426302ce8d6SAndre Oppermann 	struct ip6_hdr *ip6;
3427302ce8d6SAndre Oppermann #endif
34287a3244ccSRobert Watson 
34297a3244ccSRobert Watson 	if (tp != NULL) {
343008d9c920SGleb Smirnoff 		INP_LOCK_ASSERT(tp->t_inpcb);
34317a3244ccSRobert Watson 	}
34327a3244ccSRobert Watson 
34330ca3f933SAndre Oppermann 	/* Don't bother if destination was broadcast/multicast. */
34341ebf4607SRichard Scheffenegger 	if ((tcp_get_flags(th) & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3435302ce8d6SAndre Oppermann 		goto drop;
3436302ce8d6SAndre Oppermann #ifdef INET6
3437302ce8d6SAndre Oppermann 	if (mtod(m, struct ip *)->ip_v == 6) {
3438302ce8d6SAndre Oppermann 		ip6 = mtod(m, struct ip6_hdr *);
3439302ce8d6SAndre Oppermann 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3440302ce8d6SAndre Oppermann 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3441302ce8d6SAndre Oppermann 			goto drop;
3442302ce8d6SAndre Oppermann 		/* IPv6 anycast check is done at tcp6_input() */
3443b287c6c7SBjoern A. Zeeb 	}
3444302ce8d6SAndre Oppermann #endif
3445b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3446b287c6c7SBjoern A. Zeeb 	else
3447b287c6c7SBjoern A. Zeeb #endif
3448b287c6c7SBjoern A. Zeeb #ifdef INET
3449302ce8d6SAndre Oppermann 	{
3450302ce8d6SAndre Oppermann 		ip = mtod(m, struct ip *);
3451302ce8d6SAndre Oppermann 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3452302ce8d6SAndre Oppermann 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3453302ce8d6SAndre Oppermann 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3454302ce8d6SAndre Oppermann 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3455302ce8d6SAndre Oppermann 			goto drop;
3456302ce8d6SAndre Oppermann 	}
3457b287c6c7SBjoern A. Zeeb #endif
3458302ce8d6SAndre Oppermann 
3459302ce8d6SAndre Oppermann 	/* Perform bandwidth limiting. */
3460302ce8d6SAndre Oppermann 	if (badport_bandlim(rstreason) < 0)
3461302ce8d6SAndre Oppermann 		goto drop;
3462302ce8d6SAndre Oppermann 
3463302ce8d6SAndre Oppermann 	/* tcp_respond consumes the mbuf chain. */
34641ebf4607SRichard Scheffenegger 	if (tcp_get_flags(th) & TH_ACK) {
3465302ce8d6SAndre Oppermann 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3466302ce8d6SAndre Oppermann 		    th->th_ack, TH_RST);
3467302ce8d6SAndre Oppermann 	} else {
34681ebf4607SRichard Scheffenegger 		if (tcp_get_flags(th) & TH_SYN)
3469302ce8d6SAndre Oppermann 			tlen++;
34701ebf4607SRichard Scheffenegger 		if (tcp_get_flags(th) & TH_FIN)
34714ddd5aadSMichael Tuexen 			tlen++;
3472302ce8d6SAndre Oppermann 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3473302ce8d6SAndre Oppermann 		    (tcp_seq)0, TH_RST|TH_ACK);
3474302ce8d6SAndre Oppermann 	}
3475302ce8d6SAndre Oppermann 	return;
3476302ce8d6SAndre Oppermann drop:
3477302ce8d6SAndre Oppermann 	m_freem(m);
3478df8bae1dSRodney W. Grimes }
3479df8bae1dSRodney W. Grimes 
3480be2ac88cSJonathan Lemon /*
3481be2ac88cSJonathan Lemon  * Parse TCP options and place in tcpopt.
3482be2ac88cSJonathan Lemon  */
348355bceb1eSRandall Stewart void
3484ad3f9ab3SAndre Oppermann tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3485df8bae1dSRodney W. Grimes {
3486df8bae1dSRodney W. Grimes 	int opt, optlen;
3487df8bae1dSRodney W. Grimes 
3488be2ac88cSJonathan Lemon 	to->to_flags = 0;
3489df8bae1dSRodney W. Grimes 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
3490df8bae1dSRodney W. Grimes 		opt = cp[0];
3491df8bae1dSRodney W. Grimes 		if (opt == TCPOPT_EOL)
3492df8bae1dSRodney W. Grimes 			break;
3493df8bae1dSRodney W. Grimes 		if (opt == TCPOPT_NOP)
3494df8bae1dSRodney W. Grimes 			optlen = 1;
3495df8bae1dSRodney W. Grimes 		else {
3496b474779fSJun-ichiro itojun Hagino 			if (cnt < 2)
3497b474779fSJun-ichiro itojun Hagino 				break;
3498df8bae1dSRodney W. Grimes 			optlen = cp[1];
3499b474779fSJun-ichiro itojun Hagino 			if (optlen < 2 || optlen > cnt)
3500df8bae1dSRodney W. Grimes 				break;
3501df8bae1dSRodney W. Grimes 		}
3502df8bae1dSRodney W. Grimes 		switch (opt) {
3503df8bae1dSRodney W. Grimes 		case TCPOPT_MAXSEG:
3504df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_MAXSEG)
3505df8bae1dSRodney W. Grimes 				continue;
3506f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3507df8bae1dSRodney W. Grimes 				continue;
3508be2ac88cSJonathan Lemon 			to->to_flags |= TOF_MSS;
3509be2ac88cSJonathan Lemon 			bcopy((char *)cp + 2,
3510be2ac88cSJonathan Lemon 			    (char *)&to->to_mss, sizeof(to->to_mss));
3511fd8e4ebcSMike Barcroft 			to->to_mss = ntohs(to->to_mss);
3512df8bae1dSRodney W. Grimes 			break;
3513df8bae1dSRodney W. Grimes 		case TCPOPT_WINDOW:
3514df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_WINDOW)
3515df8bae1dSRodney W. Grimes 				continue;
3516f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3517df8bae1dSRodney W. Grimes 				continue;
3518be2ac88cSJonathan Lemon 			to->to_flags |= TOF_SCALE;
351902a1a643SAndre Oppermann 			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3520df8bae1dSRodney W. Grimes 			break;
3521df8bae1dSRodney W. Grimes 		case TCPOPT_TIMESTAMP:
3522df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_TIMESTAMP)
3523df8bae1dSRodney W. Grimes 				continue;
3524be2ac88cSJonathan Lemon 			to->to_flags |= TOF_TS;
3525a0292f23SGarrett Wollman 			bcopy((char *)cp + 2,
3526a0292f23SGarrett Wollman 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
3527fd8e4ebcSMike Barcroft 			to->to_tsval = ntohl(to->to_tsval);
3528a0292f23SGarrett Wollman 			bcopy((char *)cp + 6,
3529a0292f23SGarrett Wollman 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3530fd8e4ebcSMike Barcroft 			to->to_tsecr = ntohl(to->to_tsecr);
3531df8bae1dSRodney W. Grimes 			break;
35321cfd4b53SBruce M Simpson 		case TCPOPT_SIGNATURE:
3533fcf59617SAndrey V. Elsukov 			/*
3534fcf59617SAndrey V. Elsukov 			 * In order to reply to a host which has set the
3535fcf59617SAndrey V. Elsukov 			 * TCP_SIGNATURE option in its initial SYN, we have
3536fcf59617SAndrey V. Elsukov 			 * to record the fact that the option was observed
3537fcf59617SAndrey V. Elsukov 			 * here for the syncache code to perform the correct
3538fcf59617SAndrey V. Elsukov 			 * response.
3539fcf59617SAndrey V. Elsukov 			 */
35401cfd4b53SBruce M Simpson 			if (optlen != TCPOLEN_SIGNATURE)
35411cfd4b53SBruce M Simpson 				continue;
3542df47e437SAndre Oppermann 			to->to_flags |= TOF_SIGNATURE;
3543df47e437SAndre Oppermann 			to->to_signature = cp + 2;
35441cfd4b53SBruce M Simpson 			break;
35456d90faf3SPaul Saab 		case TCPOPT_SACK_PERMITTED:
3546f72167f4SAndre Oppermann 			if (optlen != TCPOLEN_SACK_PERMITTED)
35476d90faf3SPaul Saab 				continue;
3548f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3549f72167f4SAndre Oppermann 				continue;
3550603724d3SBjoern A. Zeeb 			if (!V_tcp_do_sack)
3551f72167f4SAndre Oppermann 				continue;
3552fc30a251SAndre Oppermann 			to->to_flags |= TOF_SACKPERM;
35536d90faf3SPaul Saab 			break;
35546d90faf3SPaul Saab 		case TCPOPT_SACK:
35555a53ca16SPaul Saab 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
35566d90faf3SPaul Saab 				continue;
3557b728e902SAndre Oppermann 			if (flags & TO_SYN)
3558b728e902SAndre Oppermann 				continue;
3559fc30a251SAndre Oppermann 			to->to_flags |= TOF_SACK;
35605a53ca16SPaul Saab 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
35615a53ca16SPaul Saab 			to->to_sacks = cp + 2;
356278b50714SRobert Watson 			TCPSTAT_INC(tcps_sack_rcv_blocks);
35636d90faf3SPaul Saab 			break;
3564281a0fd4SPatrick Kelsey 		case TCPOPT_FAST_OPEN:
3565c560df6fSPatrick Kelsey 			/*
3566c560df6fSPatrick Kelsey 			 * Cookie length validation is performed by the
3567c560df6fSPatrick Kelsey 			 * server side cookie checking code or the client
3568c560df6fSPatrick Kelsey 			 * side cookie cache update code.
3569c560df6fSPatrick Kelsey 			 */
3570281a0fd4SPatrick Kelsey 			if (!(flags & TO_SYN))
3571281a0fd4SPatrick Kelsey 				continue;
3572c560df6fSPatrick Kelsey 			if (!V_tcp_fastopen_client_enable &&
3573c560df6fSPatrick Kelsey 			    !V_tcp_fastopen_server_enable)
3574281a0fd4SPatrick Kelsey 				continue;
3575281a0fd4SPatrick Kelsey 			to->to_flags |= TOF_FASTOPEN;
3576281a0fd4SPatrick Kelsey 			to->to_tfo_len = optlen - 2;
3577281a0fd4SPatrick Kelsey 			to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3578281a0fd4SPatrick Kelsey 			break;
3579be2ac88cSJonathan Lemon 		default:
3580be2ac88cSJonathan Lemon 			continue;
3581df8bae1dSRodney W. Grimes 		}
3582df8bae1dSRodney W. Grimes 	}
3583df8bae1dSRodney W. Grimes }
3584df8bae1dSRodney W. Grimes 
3585df8bae1dSRodney W. Grimes /*
3586df8bae1dSRodney W. Grimes  * Pull out of band byte out of a segment so
3587df8bae1dSRodney W. Grimes  * it doesn't appear in the user's data queue.
3588df8bae1dSRodney W. Grimes  * It is still reflected in the segment length for
3589df8bae1dSRodney W. Grimes  * sequencing purposes.
3590df8bae1dSRodney W. Grimes  */
359155bceb1eSRandall Stewart void
3592ad3f9ab3SAndre Oppermann tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3593ad3f9ab3SAndre Oppermann     int off)
3594df8bae1dSRodney W. Grimes {
3595fb59c426SYoshinobu Inoue 	int cnt = off + th->th_urp - 1;
3596df8bae1dSRodney W. Grimes 
3597df8bae1dSRodney W. Grimes 	while (cnt >= 0) {
3598df8bae1dSRodney W. Grimes 		if (m->m_len > cnt) {
3599df8bae1dSRodney W. Grimes 			char *cp = mtod(m, caddr_t) + cnt;
3600df8bae1dSRodney W. Grimes 			struct tcpcb *tp = sototcpcb(so);
3601df8bae1dSRodney W. Grimes 
36028501a69cSRobert Watson 			INP_WLOCK_ASSERT(tp->t_inpcb);
36037a3244ccSRobert Watson 
3604df8bae1dSRodney W. Grimes 			tp->t_iobc = *cp;
3605df8bae1dSRodney W. Grimes 			tp->t_oobflags |= TCPOOB_HAVEDATA;
3606df8bae1dSRodney W. Grimes 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3607df8bae1dSRodney W. Grimes 			m->m_len--;
360869a34685SYoshinobu Inoue 			if (m->m_flags & M_PKTHDR)
360969a34685SYoshinobu Inoue 				m->m_pkthdr.len--;
3610df8bae1dSRodney W. Grimes 			return;
3611df8bae1dSRodney W. Grimes 		}
3612df8bae1dSRodney W. Grimes 		cnt -= m->m_len;
3613df8bae1dSRodney W. Grimes 		m = m->m_next;
36144dfdffe9SAndre Oppermann 		if (m == NULL)
3615df8bae1dSRodney W. Grimes 			break;
3616df8bae1dSRodney W. Grimes 	}
3617df8bae1dSRodney W. Grimes 	panic("tcp_pulloutofband");
3618df8bae1dSRodney W. Grimes }
3619df8bae1dSRodney W. Grimes 
3620df8bae1dSRodney W. Grimes /*
3621df8bae1dSRodney W. Grimes  * Collect new round-trip time estimate
3622df8bae1dSRodney W. Grimes  * and update averages and current timeout.
3623df8bae1dSRodney W. Grimes  */
362455bceb1eSRandall Stewart void
3625ad3f9ab3SAndre Oppermann tcp_xmit_timer(struct tcpcb *tp, int rtt)
3626df8bae1dSRodney W. Grimes {
3627ad3f9ab3SAndre Oppermann 	int delta;
3628233e8c18SGarrett Wollman 
36298501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
36302be3bf22SRobert Watson 
363178b50714SRobert Watson 	TCPSTAT_INC(tcps_rttupdated);
3632233e8c18SGarrett Wollman 	tp->t_rttupdated++;
3633adc56f5aSEdward Tomasz Napierala #ifdef STATS
3634adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT,
3635adc56f5aSEdward Tomasz Napierala 	    imax(0, rtt * 1000 / hz));
3636adc56f5aSEdward Tomasz Napierala #endif
36375ede40dcSRyan Stone 	if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3638233e8c18SGarrett Wollman 		/*
3639233e8c18SGarrett Wollman 		 * srtt is stored as fixed point with 5 bits after the
3640233e8c18SGarrett Wollman 		 * binary point (i.e., scaled by 8).  The following magic
3641233e8c18SGarrett Wollman 		 * is equivalent to the smoothing algorithm in rfc793 with
3642233e8c18SGarrett Wollman 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3643233e8c18SGarrett Wollman 		 * point).  Adjust rtt to origin 0.
3644233e8c18SGarrett Wollman 		 */
3645233e8c18SGarrett Wollman 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3646233e8c18SGarrett Wollman 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3647233e8c18SGarrett Wollman 
3648233e8c18SGarrett Wollman 		if ((tp->t_srtt += delta) <= 0)
3649233e8c18SGarrett Wollman 			tp->t_srtt = 1;
3650233e8c18SGarrett Wollman 
3651233e8c18SGarrett Wollman 		/*
3652233e8c18SGarrett Wollman 		 * We accumulate a smoothed rtt variance (actually, a
3653233e8c18SGarrett Wollman 		 * smoothed mean difference), then set the retransmit
3654233e8c18SGarrett Wollman 		 * timer to smoothed rtt + 4 times the smoothed variance.
3655233e8c18SGarrett Wollman 		 * rttvar is stored as fixed point with 4 bits after the
3656233e8c18SGarrett Wollman 		 * binary point (scaled by 16).  The following is
3657233e8c18SGarrett Wollman 		 * equivalent to rfc793 smoothing with an alpha of .75
3658233e8c18SGarrett Wollman 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
3659233e8c18SGarrett Wollman 		 * rfc793's wired-in beta.
3660233e8c18SGarrett Wollman 		 */
3661233e8c18SGarrett Wollman 		if (delta < 0)
3662233e8c18SGarrett Wollman 			delta = -delta;
3663233e8c18SGarrett Wollman 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3664233e8c18SGarrett Wollman 		if ((tp->t_rttvar += delta) <= 0)
3665233e8c18SGarrett Wollman 			tp->t_rttvar = 1;
36661fcc99b5SMatthew Dillon 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
36671fcc99b5SMatthew Dillon 		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3668233e8c18SGarrett Wollman 	} else {
3669233e8c18SGarrett Wollman 		/*
3670233e8c18SGarrett Wollman 		 * No rtt measurement yet - use the unsmoothed rtt.
3671233e8c18SGarrett Wollman 		 * Set the variance to half the rtt (so our first
3672233e8c18SGarrett Wollman 		 * retransmit happens at 3*rtt).
3673233e8c18SGarrett Wollman 		 */
3674233e8c18SGarrett Wollman 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
3675233e8c18SGarrett Wollman 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
36761fcc99b5SMatthew Dillon 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3677233e8c18SGarrett Wollman 	}
36789b8b58e0SJonathan Lemon 	tp->t_rtttime = 0;
3679df8bae1dSRodney W. Grimes 	tp->t_rxtshift = 0;
3680df8bae1dSRodney W. Grimes 
3681df8bae1dSRodney W. Grimes 	/*
3682df8bae1dSRodney W. Grimes 	 * the retransmit should happen at rtt + 4 * rttvar.
3683df8bae1dSRodney W. Grimes 	 * Because of the way we do the smoothing, srtt and rttvar
3684df8bae1dSRodney W. Grimes 	 * will each average +1/2 tick of bias.  When we compute
3685df8bae1dSRodney W. Grimes 	 * the retransmit timer, we want 1/2 tick of rounding and
3686df8bae1dSRodney W. Grimes 	 * 1 extra tick because of +-1/2 tick uncertainty in the
3687df8bae1dSRodney W. Grimes 	 * firing of the timer.  The bias will give us exactly the
3688df8bae1dSRodney W. Grimes 	 * 1.5 tick we need.  But, because the bias is
3689df8bae1dSRodney W. Grimes 	 * statistical, we have to test that we don't drop below
3690df8bae1dSRodney W. Grimes 	 * the minimum feasible timer (which is 2 ticks).
3691df8bae1dSRodney W. Grimes 	 */
3692233e8c18SGarrett Wollman 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
36939e2874b0SGarrett Wollman 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3694df8bae1dSRodney W. Grimes 
3695df8bae1dSRodney W. Grimes 	/*
3696df8bae1dSRodney W. Grimes 	 * We received an ack for a packet that wasn't retransmitted;
3697df8bae1dSRodney W. Grimes 	 * it is probably safe to discard any error indications we've
3698df8bae1dSRodney W. Grimes 	 * received recently.  This isn't quite right, but close enough
3699df8bae1dSRodney W. Grimes 	 * for now (a route might have failed after we sent a segment,
3700df8bae1dSRodney W. Grimes 	 * and the return path might not be symmetrical).
3701df8bae1dSRodney W. Grimes 	 */
3702df8bae1dSRodney W. Grimes 	tp->t_softerror = 0;
3703df8bae1dSRodney W. Grimes }
3704df8bae1dSRodney W. Grimes 
3705df8bae1dSRodney W. Grimes /*
3706df8bae1dSRodney W. Grimes  * Determine a reasonable value for maxseg size.
3707df8bae1dSRodney W. Grimes  * If the route is known, check route for mtu.
37084faaea55SAndre Oppermann  * If none, use an mss that can be handled on the outgoing interface
37094faaea55SAndre Oppermann  * without forcing IP to fragment.  If no route is found, route has no mtu,
3710df8bae1dSRodney W. Grimes  * or the destination isn't local, use a default, hopefully conservative
3711df8bae1dSRodney W. Grimes  * size (usually 512 or the default IP max size, but no more than the mtu
3712df8bae1dSRodney W. Grimes  * of the interface), as we can't discover anything about intervening
3713df8bae1dSRodney W. Grimes  * gateways or networks.  We also initialize the congestion/slow start
3714df8bae1dSRodney W. Grimes  * window to be a single segment if the destination isn't local.
3715df8bae1dSRodney W. Grimes  * While looking at the routing entry, we also initialize other path-dependent
3716df8bae1dSRodney W. Grimes  * parameters from pre-set or cached values in the routing entry.
3717a0292f23SGarrett Wollman  *
37180c39d38dSGleb Smirnoff  * NOTE that resulting t_maxseg doesn't include space for TCP options or
37190c39d38dSGleb Smirnoff  * IP options, e.g. IPSEC data, since length of this data may vary, and
37200c39d38dSGleb Smirnoff  * thus it is calculated for every segment separately in tcp_output().
3721a0292f23SGarrett Wollman  *
372297d8d152SAndre Oppermann  * NOTE that this routine is only called when we process an incoming
3723ef341ee1SGleb Smirnoff  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3724ef341ee1SGleb Smirnoff  * settings are handled in tcp_mssopt().
3725df8bae1dSRodney W. Grimes  */
3726a0292f23SGarrett Wollman void
3727ef341ee1SGleb Smirnoff tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
37283c914c54SAndre Oppermann     struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3729df8bae1dSRodney W. Grimes {
3730b287c6c7SBjoern A. Zeeb 	int mss = 0;
37313ac12506SJonathan T. Looney 	uint32_t maxmtu = 0;
3732c068736aSJeffrey Hsu 	struct inpcb *inp = tp->t_inpcb;
373397d8d152SAndre Oppermann 	struct hc_metrics_lite metrics;
3734fb59c426SYoshinobu Inoue #ifdef INET6
3735c068736aSJeffrey Hsu 	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3736c068736aSJeffrey Hsu 	size_t min_protoh = isipv6 ?
3737c068736aSJeffrey Hsu 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3738c068736aSJeffrey Hsu 			    sizeof (struct tcpiphdr);
3739c068736aSJeffrey Hsu #else
37409e644c23SMichael Tuexen 	 size_t min_protoh = sizeof(struct tcpiphdr);
3741fb59c426SYoshinobu Inoue #endif
3742df8bae1dSRodney W. Grimes 
37438501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
37447a3244ccSRobert Watson 
37459e644c23SMichael Tuexen 	if (tp->t_port)
37469e644c23SMichael Tuexen 		min_protoh += V_tcp_udp_tunneling_overhead;
3747ef341ee1SGleb Smirnoff 	if (mtuoffer != -1) {
3748ef341ee1SGleb Smirnoff 		KASSERT(offer == -1, ("%s: conflict", __func__));
3749ef341ee1SGleb Smirnoff 		offer = mtuoffer - min_protoh;
3750ef341ee1SGleb Smirnoff 	}
3751ef341ee1SGleb Smirnoff 
3752e8949f74SAndre Oppermann 	/* Initialize. */
375397d8d152SAndre Oppermann #ifdef INET6
375497d8d152SAndre Oppermann 	if (isipv6) {
37553c914c54SAndre Oppermann 		maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
37560c39d38dSGleb Smirnoff 		tp->t_maxseg = V_tcp_v6mssdflt;
3757b287c6c7SBjoern A. Zeeb 	}
375897d8d152SAndre Oppermann #endif
3759b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3760b287c6c7SBjoern A. Zeeb 	else
3761b287c6c7SBjoern A. Zeeb #endif
3762b287c6c7SBjoern A. Zeeb #ifdef INET
376397d8d152SAndre Oppermann 	{
37643c914c54SAndre Oppermann 		maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
37650c39d38dSGleb Smirnoff 		tp->t_maxseg = V_tcp_mssdflt;
3766df8bae1dSRodney W. Grimes 	}
3767b287c6c7SBjoern A. Zeeb #endif
3768df8bae1dSRodney W. Grimes 
376997d8d152SAndre Oppermann 	/*
3770e8949f74SAndre Oppermann 	 * No route to sender, stay with default mss and return.
377197d8d152SAndre Oppermann 	 */
37726f01cac6SBjoern A. Zeeb 	if (maxmtu == 0) {
37736f01cac6SBjoern A. Zeeb 		/*
37748e5c87f4SBjoern A. Zeeb 		 * In case we return early we need to initialize metrics
37756f01cac6SBjoern A. Zeeb 		 * to a defined state as tcp_hc_get() would do for us
37766f01cac6SBjoern A. Zeeb 		 * if there was no cache hit.
37776f01cac6SBjoern A. Zeeb 		 */
37786f01cac6SBjoern A. Zeeb 		if (metricptr != NULL)
37796f01cac6SBjoern A. Zeeb 			bzero(metricptr, sizeof(struct hc_metrics_lite));
378097d8d152SAndre Oppermann 		return;
37816f01cac6SBjoern A. Zeeb 	}
378297d8d152SAndre Oppermann 
3783e8949f74SAndre Oppermann 	/* What have we got? */
378497d8d152SAndre Oppermann 	switch (offer) {
378597d8d152SAndre Oppermann 		case 0:
378697d8d152SAndre Oppermann 			/*
378797d8d152SAndre Oppermann 			 * Offer == 0 means that there was no MSS on the SYN
3788c3b02504SBjoern A. Zeeb 			 * segment, in this case we use tcp_mssdflt as
37890c39d38dSGleb Smirnoff 			 * already assigned to t_maxseg above.
379097d8d152SAndre Oppermann 			 */
37910c39d38dSGleb Smirnoff 			offer = tp->t_maxseg;
379297d8d152SAndre Oppermann 			break;
379397d8d152SAndre Oppermann 
379497d8d152SAndre Oppermann 		case -1:
3795a0292f23SGarrett Wollman 			/*
3796c94c54e4SAndre Oppermann 			 * Offer == -1 means that we didn't receive SYN yet.
3797a0292f23SGarrett Wollman 			 */
379897d8d152SAndre Oppermann 			/* FALLTHROUGH */
379997d8d152SAndre Oppermann 
380097d8d152SAndre Oppermann 		default:
3801a0292f23SGarrett Wollman 			/*
380253369ac9SAndre Oppermann 			 * Prevent DoS attack with too small MSS. Round up
380353369ac9SAndre Oppermann 			 * to at least minmss.
380453369ac9SAndre Oppermann 			 */
3805603724d3SBjoern A. Zeeb 			offer = max(offer, V_tcp_minmss);
380697d8d152SAndre Oppermann 	}
3807a0292f23SGarrett Wollman 
3808df8bae1dSRodney W. Grimes 	/*
3809e8949f74SAndre Oppermann 	 * rmx information is now retrieved from tcp_hostcache.
3810df8bae1dSRodney W. Grimes 	 */
381197d8d152SAndre Oppermann 	tcp_hc_get(&inp->inp_inc, &metrics);
38123cee92e0SBjoern A. Zeeb 	if (metricptr != NULL)
38133cee92e0SBjoern A. Zeeb 		bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
381497d8d152SAndre Oppermann 
3815df8bae1dSRodney W. Grimes 	/*
3816cc412412SHiren Panchasara 	 * If there's a discovered mtu in tcp hostcache, use it.
3817cc412412SHiren Panchasara 	 * Else, use the link mtu.
3818df8bae1dSRodney W. Grimes 	 */
381997d8d152SAndre Oppermann 	if (metrics.rmx_mtu)
38202d166c02SAndre Oppermann 		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3821c068736aSJeffrey Hsu 	else {
382231b3783cSHajimu UMEMOTO #ifdef INET6
3823fb59c426SYoshinobu Inoue 		if (isipv6) {
382497d8d152SAndre Oppermann 			mss = maxmtu - min_protoh;
3825603724d3SBjoern A. Zeeb 			if (!V_path_mtu_discovery &&
382697d8d152SAndre Oppermann 			    !in6_localaddr(&inp->in6p_faddr))
3827603724d3SBjoern A. Zeeb 				mss = min(mss, V_tcp_v6mssdflt);
3828b287c6c7SBjoern A. Zeeb 		}
3829b3399803SHajimu UMEMOTO #endif
3830b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3831b287c6c7SBjoern A. Zeeb 		else
3832b287c6c7SBjoern A. Zeeb #endif
3833b287c6c7SBjoern A. Zeeb #ifdef INET
383497d8d152SAndre Oppermann 		{
383597d8d152SAndre Oppermann 			mss = maxmtu - min_protoh;
3836603724d3SBjoern A. Zeeb 			if (!V_path_mtu_discovery &&
383797d8d152SAndre Oppermann 			    !in_localaddr(inp->inp_faddr))
3838603724d3SBjoern A. Zeeb 				mss = min(mss, V_tcp_mssdflt);
3839a0292f23SGarrett Wollman 		}
3840b287c6c7SBjoern A. Zeeb #endif
38413cee92e0SBjoern A. Zeeb 		/*
38423cee92e0SBjoern A. Zeeb 		 * XXX - The above conditional (mss = maxmtu - min_protoh)
38433cee92e0SBjoern A. Zeeb 		 * probably violates the TCP spec.
38443cee92e0SBjoern A. Zeeb 		 * The problem is that, since we don't know the
38453cee92e0SBjoern A. Zeeb 		 * other end's MSS, we are supposed to use a conservative
38463cee92e0SBjoern A. Zeeb 		 * default.  But, if we do that, then MTU discovery will
38473cee92e0SBjoern A. Zeeb 		 * never actually take place, because the conservative
38483cee92e0SBjoern A. Zeeb 		 * default is much less than the MTUs typically seen
38493cee92e0SBjoern A. Zeeb 		 * on the Internet today.  For the moment, we'll sweep
38503cee92e0SBjoern A. Zeeb 		 * this under the carpet.
38513cee92e0SBjoern A. Zeeb 		 *
38523cee92e0SBjoern A. Zeeb 		 * The conservative default might not actually be a problem
38533cee92e0SBjoern A. Zeeb 		 * if the only case this occurs is when sending an initial
38543cee92e0SBjoern A. Zeeb 		 * SYN with options and data to a host we've never talked
38553cee92e0SBjoern A. Zeeb 		 * to before.  Then, they will reply with an MSS value which
38563cee92e0SBjoern A. Zeeb 		 * will get recorded and the new parameters should get
38573cee92e0SBjoern A. Zeeb 		 * recomputed.  For Further Study.
38583cee92e0SBjoern A. Zeeb 		 */
385997d8d152SAndre Oppermann 	}
3860a0292f23SGarrett Wollman 	mss = min(mss, offer);
386197d8d152SAndre Oppermann 
3862a0292f23SGarrett Wollman 	/*
38630c39d38dSGleb Smirnoff 	 * Sanity check: make sure that maxseg will be large
38643cee92e0SBjoern A. Zeeb 	 * enough to allow some data on segments even if the
38653cee92e0SBjoern A. Zeeb 	 * all the option space is used (40bytes).  Otherwise
38663cee92e0SBjoern A. Zeeb 	 * funny things may happen in tcp_output.
38670c39d38dSGleb Smirnoff 	 *
38680c39d38dSGleb Smirnoff 	 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
38693cee92e0SBjoern A. Zeeb 	 */
38703cee92e0SBjoern A. Zeeb 	mss = max(mss, 64);
38713cee92e0SBjoern A. Zeeb 
387297d8d152SAndre Oppermann 	tp->t_maxseg = mss;
38733cee92e0SBjoern A. Zeeb }
38743cee92e0SBjoern A. Zeeb 
38753cee92e0SBjoern A. Zeeb void
38763cee92e0SBjoern A. Zeeb tcp_mss(struct tcpcb *tp, int offer)
38773cee92e0SBjoern A. Zeeb {
3878dbc42409SLawrence Stewart 	int mss;
38793ac12506SJonathan T. Looney 	uint32_t bufsize;
38803cee92e0SBjoern A. Zeeb 	struct inpcb *inp;
38813cee92e0SBjoern A. Zeeb 	struct socket *so;
38823cee92e0SBjoern A. Zeeb 	struct hc_metrics_lite metrics;
38833c914c54SAndre Oppermann 	struct tcp_ifcap cap;
3884dbc42409SLawrence Stewart 
38853cee92e0SBjoern A. Zeeb 	KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
38863cee92e0SBjoern A. Zeeb 
38873c914c54SAndre Oppermann 	bzero(&cap, sizeof(cap));
38883c914c54SAndre Oppermann 	tcp_mss_update(tp, offer, -1, &metrics, &cap);
38893cee92e0SBjoern A. Zeeb 
38903cee92e0SBjoern A. Zeeb 	mss = tp->t_maxseg;
38913cee92e0SBjoern A. Zeeb 	inp = tp->t_inpcb;
389297d8d152SAndre Oppermann 
3893df8bae1dSRodney W. Grimes 	/*
389497d8d152SAndre Oppermann 	 * If there's a pipesize, change the socket buffer to that size,
389597d8d152SAndre Oppermann 	 * don't change if sb_hiwat is different than default (then it
389697d8d152SAndre Oppermann 	 * has been changed on purpose with setsockopt).
389797d8d152SAndre Oppermann 	 * Make the socket buffers an integral number of mss units;
389897d8d152SAndre Oppermann 	 * if the mss is larger than the socket buffer, decrease the mss.
3899df8bae1dSRodney W. Grimes 	 */
3900c3b02504SBjoern A. Zeeb 	so = inp->inp_socket;
39013f11a2f3SRobert Watson 	SOCKBUF_LOCK(&so->so_snd);
3902e233e2acSAndre Oppermann 	if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
390397d8d152SAndre Oppermann 		bufsize = metrics.rmx_sendpipe;
390497d8d152SAndre Oppermann 	else
3905df8bae1dSRodney W. Grimes 		bufsize = so->so_snd.sb_hiwat;
3906df8bae1dSRodney W. Grimes 	if (bufsize < mss)
3907df8bae1dSRodney W. Grimes 		mss = bufsize;
3908df8bae1dSRodney W. Grimes 	else {
3909df8bae1dSRodney W. Grimes 		bufsize = roundup(bufsize, mss);
3910df8bae1dSRodney W. Grimes 		if (bufsize > sb_max)
3911df8bae1dSRodney W. Grimes 			bufsize = sb_max;
391288c39af3SRuslan Ermilov 		if (bufsize > so->so_snd.sb_hiwat)
391343283184SGleb Smirnoff 			(void)sbreserve_locked(so, SO_SND, bufsize, NULL);
3914df8bae1dSRodney W. Grimes 	}
39153f11a2f3SRobert Watson 	SOCKBUF_UNLOCK(&so->so_snd);
3916784ce8faSHiren Panchasara 	/*
3917784ce8faSHiren Panchasara 	 * Sanity check: make sure that maxseg will be large
3918784ce8faSHiren Panchasara 	 * enough to allow some data on segments even if the
3919784ce8faSHiren Panchasara 	 * all the option space is used (40bytes).  Otherwise
3920784ce8faSHiren Panchasara 	 * funny things may happen in tcp_output.
3921784ce8faSHiren Panchasara 	 *
3922784ce8faSHiren Panchasara 	 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3923784ce8faSHiren Panchasara 	 */
3924784ce8faSHiren Panchasara 	tp->t_maxseg = max(mss, 64);
3925df8bae1dSRodney W. Grimes 
39263f11a2f3SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
3927e233e2acSAndre Oppermann 	if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
392897d8d152SAndre Oppermann 		bufsize = metrics.rmx_recvpipe;
392997d8d152SAndre Oppermann 	else
3930df8bae1dSRodney W. Grimes 		bufsize = so->so_rcv.sb_hiwat;
3931df8bae1dSRodney W. Grimes 	if (bufsize > mss) {
3932df8bae1dSRodney W. Grimes 		bufsize = roundup(bufsize, mss);
3933df8bae1dSRodney W. Grimes 		if (bufsize > sb_max)
3934df8bae1dSRodney W. Grimes 			bufsize = sb_max;
393588c39af3SRuslan Ermilov 		if (bufsize > so->so_rcv.sb_hiwat)
393643283184SGleb Smirnoff 			(void)sbreserve_locked(so, SO_RCV, bufsize, NULL);
3937df8bae1dSRodney W. Grimes 	}
39383f11a2f3SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
393991d6cfa6SBjoern A. Zeeb 
394091d6cfa6SBjoern A. Zeeb 	/* Check the interface for TSO capabilities. */
39413c914c54SAndre Oppermann 	if (cap.ifcap & CSUM_TSO) {
394291d6cfa6SBjoern A. Zeeb 		tp->t_flags |= TF_TSO;
39433c914c54SAndre Oppermann 		tp->t_tsomax = cap.tsomax;
39449fd573c3SHans Petter Selasky 		tp->t_tsomaxsegcount = cap.tsomaxsegcount;
39459fd573c3SHans Petter Selasky 		tp->t_tsomaxsegsize = cap.tsomaxsegsize;
39463c914c54SAndre Oppermann 	}
3947a0292f23SGarrett Wollman }
3948a0292f23SGarrett Wollman 
3949a0292f23SGarrett Wollman /*
3950a0292f23SGarrett Wollman  * Determine the MSS option to send on an outgoing SYN.
3951a0292f23SGarrett Wollman  */
3952a0292f23SGarrett Wollman int
3953ad3f9ab3SAndre Oppermann tcp_mssopt(struct in_conninfo *inc)
3954a0292f23SGarrett Wollman {
395597d8d152SAndre Oppermann 	int mss = 0;
39563ac12506SJonathan T. Looney 	uint32_t thcmtu = 0;
39573ac12506SJonathan T. Looney 	uint32_t maxmtu = 0;
395897d8d152SAndre Oppermann 	size_t min_protoh;
3959a0292f23SGarrett Wollman 
396097d8d152SAndre Oppermann 	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3961a0292f23SGarrett Wollman 
396231b3783cSHajimu UMEMOTO #ifdef INET6
3963dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
3964603724d3SBjoern A. Zeeb 		mss = V_tcp_v6mssdflt;
3965233dcce1SAndre Oppermann 		maxmtu = tcp_maxmtu6(inc, NULL);
396697d8d152SAndre Oppermann 		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3967b287c6c7SBjoern A. Zeeb 	}
396831b3783cSHajimu UMEMOTO #endif
3969b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3970b287c6c7SBjoern A. Zeeb 	else
3971b287c6c7SBjoern A. Zeeb #endif
3972b287c6c7SBjoern A. Zeeb #ifdef INET
397397d8d152SAndre Oppermann 	{
3974603724d3SBjoern A. Zeeb 		mss = V_tcp_mssdflt;
3975233dcce1SAndre Oppermann 		maxmtu = tcp_maxmtu(inc, NULL);
397697d8d152SAndre Oppermann 		min_protoh = sizeof(struct tcpiphdr);
397797d8d152SAndre Oppermann 	}
3978b287c6c7SBjoern A. Zeeb #endif
39793a9391deSBjoern A. Zeeb #if defined(INET6) || defined(INET)
39803a9391deSBjoern A. Zeeb 	thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
39813a9391deSBjoern A. Zeeb #endif
39823a9391deSBjoern A. Zeeb 
398397d8d152SAndre Oppermann 	if (maxmtu && thcmtu)
398497d8d152SAndre Oppermann 		mss = min(maxmtu, thcmtu) - min_protoh;
398597d8d152SAndre Oppermann 	else if (maxmtu || thcmtu)
398697d8d152SAndre Oppermann 		mss = max(maxmtu, thcmtu) - min_protoh;
398797d8d152SAndre Oppermann 
398897d8d152SAndre Oppermann 	return (mss);
3989df8bae1dSRodney W. Grimes }
399046f58482SJonathan Lemon 
39910e1d7c25SRichard Scheffenegger void
399290cca08eSRichard Scheffenegger tcp_do_prr_ack(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
39930e1d7c25SRichard Scheffenegger {
399448396dc7SRichard Scheffenegger 	int snd_cnt = 0, limit = 0, del_data = 0, pipe = 0;
39950e1d7c25SRichard Scheffenegger 	int maxseg = tcp_maxseg(tp);
39960e1d7c25SRichard Scheffenegger 
39970e1d7c25SRichard Scheffenegger 	INP_WLOCK_ASSERT(tp->t_inpcb);
39980e1d7c25SRichard Scheffenegger 
39990e1d7c25SRichard Scheffenegger 	/*
40000e1d7c25SRichard Scheffenegger 	 * Compute the amount of data that this ACK is indicating
40010e1d7c25SRichard Scheffenegger 	 * (del_data) and an estimate of how many bytes are in the
40020e1d7c25SRichard Scheffenegger 	 * network.
40030e1d7c25SRichard Scheffenegger 	 */
4004c21b7b55SRichard Scheffenegger 	if (tcp_is_sack_recovery(tp, to) ||
400574d7fc87SRichard Scheffenegger 	    (IN_CONGRECOVERY(tp->t_flags) &&
400674d7fc87SRichard Scheffenegger 	     !IN_FASTRECOVERY(tp->t_flags))) {
400731d7a27cSRichard Scheffenegger 		del_data = tp->sackhint.delivered_data;
4008d1de2b05SRichard Scheffenegger 		if (V_tcp_do_newsack)
4009a8e431e1SRichard Scheffenegger 			pipe = tcp_compute_pipe(tp);
4010a8e431e1SRichard Scheffenegger 		else
401174d7fc87SRichard Scheffenegger 			pipe = (tp->snd_nxt - tp->snd_fack) +
401274d7fc87SRichard Scheffenegger 				tp->sackhint.sack_bytes_rexmit;
401374d7fc87SRichard Scheffenegger 	} else {
401474d7fc87SRichard Scheffenegger 		if (tp->sackhint.prr_delivered < (tcprexmtthresh * maxseg +
401574d7fc87SRichard Scheffenegger 					     tp->snd_recover - tp->snd_una))
401674d7fc87SRichard Scheffenegger 			del_data = maxseg;
401774d7fc87SRichard Scheffenegger 		pipe = imax(0, tp->snd_max - tp->snd_una -
401874d7fc87SRichard Scheffenegger 			    imin(INT_MAX / 65536, tp->t_dupacks) * maxseg);
401974d7fc87SRichard Scheffenegger 	}
40200e1d7c25SRichard Scheffenegger 	tp->sackhint.prr_delivered += del_data;
40210e1d7c25SRichard Scheffenegger 	/*
40220e1d7c25SRichard Scheffenegger 	 * Proportional Rate Reduction
40230e1d7c25SRichard Scheffenegger 	 */
4024e9071000SRichard Scheffenegger 	if (pipe >= tp->snd_ssthresh) {
40256a376af0SRichard Scheffenegger 		if (tp->sackhint.recover_fs == 0)
40266a376af0SRichard Scheffenegger 			tp->sackhint.recover_fs =
402748396dc7SRichard Scheffenegger 			    imax(1, tp->snd_nxt - tp->snd_una);
402848396dc7SRichard Scheffenegger 		snd_cnt = howmany((long)tp->sackhint.prr_delivered *
402948396dc7SRichard Scheffenegger 			    tp->snd_ssthresh, tp->sackhint.recover_fs) -
4030e5313869SRichard Scheffenegger 			    tp->sackhint.prr_out;
40316a376af0SRichard Scheffenegger 	} else {
403274d7fc87SRichard Scheffenegger 		if (V_tcp_do_prr_conservative || (del_data == 0))
403384761f3dSRichard Scheffenegger 			limit = tp->sackhint.prr_delivered -
4034e5313869SRichard Scheffenegger 				tp->sackhint.prr_out;
40350e1d7c25SRichard Scheffenegger 		else
403648396dc7SRichard Scheffenegger 			limit = imax(tp->sackhint.prr_delivered -
4037e5313869SRichard Scheffenegger 				    tp->sackhint.prr_out, del_data) +
4038e5313869SRichard Scheffenegger 				    maxseg;
403948396dc7SRichard Scheffenegger 		snd_cnt = imin((tp->snd_ssthresh - pipe), limit);
40400e1d7c25SRichard Scheffenegger 	}
404148396dc7SRichard Scheffenegger 	snd_cnt = imax(snd_cnt, 0) / maxseg;
40420e1d7c25SRichard Scheffenegger 	/*
40430e1d7c25SRichard Scheffenegger 	 * Send snd_cnt new data into the network in response to this ack.
40440e1d7c25SRichard Scheffenegger 	 * If there is going to be a SACK retransmission, adjust snd_cwnd
40450e1d7c25SRichard Scheffenegger 	 * accordingly.
40460e1d7c25SRichard Scheffenegger 	 */
4047b9f803b7SRichard Scheffenegger 	if (IN_FASTRECOVERY(tp->t_flags)) {
4048c21b7b55SRichard Scheffenegger 		if (tcp_is_sack_recovery(tp, to)) {
404974d7fc87SRichard Scheffenegger 			tp->snd_cwnd = tp->snd_nxt - tp->snd_recover +
405074d7fc87SRichard Scheffenegger 					    tp->sackhint.sack_bytes_rexmit +
405174d7fc87SRichard Scheffenegger 					    (snd_cnt * maxseg);
405274d7fc87SRichard Scheffenegger 		} else {
405374d7fc87SRichard Scheffenegger 			tp->snd_cwnd = (tp->snd_max - tp->snd_una) +
405474d7fc87SRichard Scheffenegger 					    (snd_cnt * maxseg);
405574d7fc87SRichard Scheffenegger 		}
4056b9f803b7SRichard Scheffenegger 	} else if (IN_CONGRECOVERY(tp->t_flags))
405774d7fc87SRichard Scheffenegger 		tp->snd_cwnd = pipe - del_data + (snd_cnt * maxseg);
405874d7fc87SRichard Scheffenegger 	tp->snd_cwnd = imax(maxseg, tp->snd_cwnd);
40590e1d7c25SRichard Scheffenegger }
40600e1d7c25SRichard Scheffenegger 
406146f58482SJonathan Lemon /*
4062c068736aSJeffrey Hsu  * On a partial ack arrives, force the retransmission of the
4063c068736aSJeffrey Hsu  * next unacknowledged segment.  Do not clear tp->t_dupacks.
4064c068736aSJeffrey Hsu  * By setting snd_nxt to ti_ack, this forces retransmission timer to
4065c068736aSJeffrey Hsu  * be started again.
406646f58482SJonathan Lemon  */
406755bceb1eSRandall Stewart void
4068ad3f9ab3SAndre Oppermann tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
406946f58482SJonathan Lemon {
407046f58482SJonathan Lemon 	tcp_seq onxt = tp->snd_nxt;
40713ac12506SJonathan T. Looney 	uint32_t ocwnd = tp->snd_cwnd;
40720c39d38dSGleb Smirnoff 	u_int maxseg = tcp_maxseg(tp);
407346f58482SJonathan Lemon 
40748501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
40757a3244ccSRobert Watson 
4076b8152ba7SAndre Oppermann 	tcp_timer_activate(tp, TT_REXMT, 0);
407746f58482SJonathan Lemon 	tp->t_rtttime = 0;
407846f58482SJonathan Lemon 	tp->snd_nxt = th->th_ack;
40796b2a5f92SJayanth Vijayaraghavan 	/*
4080c068736aSJeffrey Hsu 	 * Set snd_cwnd to one segment beyond acknowledged offset.
4081c068736aSJeffrey Hsu 	 * (tp->snd_una has not yet been updated when this function is called.)
40826b2a5f92SJayanth Vijayaraghavan 	 */
40830c39d38dSGleb Smirnoff 	tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
4084a84db8f4SMatthew Dillon 	tp->t_flags |= TF_ACKNOW;
408540fa3e40SGleb Smirnoff 	(void) tcp_output(tp);
408646f58482SJonathan Lemon 	tp->snd_cwnd = ocwnd;
408746f58482SJonathan Lemon 	if (SEQ_GT(onxt, tp->snd_nxt))
408846f58482SJonathan Lemon 		tp->snd_nxt = onxt;
408946f58482SJonathan Lemon 	/*
409046f58482SJonathan Lemon 	 * Partial window deflation.  Relies on fact that tp->snd_una
409146f58482SJonathan Lemon 	 * not updated yet.
409246f58482SJonathan Lemon 	 */
4093dbc42409SLawrence Stewart 	if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
4094dbc42409SLawrence Stewart 		tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
4095d7587117SPaul Saab 	else
4096d7587117SPaul Saab 		tp->snd_cwnd = 0;
40970c39d38dSGleb Smirnoff 	tp->snd_cwnd += maxseg;
409846f58482SJonathan Lemon }
409912eeb81fSHiren Panchasara 
410012eeb81fSHiren Panchasara int
410112eeb81fSHiren Panchasara tcp_compute_pipe(struct tcpcb *tp)
410212eeb81fSHiren Panchasara {
4103e5049a17SRandall Stewart 	if (tp->t_fb->tfb_compute_pipe == NULL) {
410412eeb81fSHiren Panchasara 		return (tp->snd_max - tp->snd_una +
410512eeb81fSHiren Panchasara 			tp->sackhint.sack_bytes_rexmit -
410612eeb81fSHiren Panchasara 			tp->sackhint.sacked_bytes);
4107e5049a17SRandall Stewart 	} else {
4108e5049a17SRandall Stewart 		return((*tp->t_fb->tfb_compute_pipe)(tp));
4109e5049a17SRandall Stewart 	}
411012eeb81fSHiren Panchasara }
41117dc90a1dSMichael Tuexen 
41127dc90a1dSMichael Tuexen uint32_t
41137dc90a1dSMichael Tuexen tcp_compute_initwnd(uint32_t maxseg)
41147dc90a1dSMichael Tuexen {
41157dc90a1dSMichael Tuexen 	/*
41167dc90a1dSMichael Tuexen 	 * Calculate the Initial Window, also used as Restart Window
41177dc90a1dSMichael Tuexen 	 *
41187dc90a1dSMichael Tuexen 	 * RFC5681 Section 3.1 specifies the default conservative values.
41197dc90a1dSMichael Tuexen 	 * RFC3390 specifies slightly more aggressive values.
41207dc90a1dSMichael Tuexen 	 * RFC6928 increases it to ten segments.
41217dc90a1dSMichael Tuexen 	 * Support for user specified value for initial flight size.
41227dc90a1dSMichael Tuexen 	 */
41237dc90a1dSMichael Tuexen 	if (V_tcp_initcwnd_segments)
41247dc90a1dSMichael Tuexen 		return min(V_tcp_initcwnd_segments * maxseg,
41257dc90a1dSMichael Tuexen 		    max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
41267dc90a1dSMichael Tuexen 	else if (V_tcp_do_rfc3390)
41277dc90a1dSMichael Tuexen 		return min(4 * maxseg, max(2 * maxseg, 4380));
41287dc90a1dSMichael Tuexen 	else {
41297dc90a1dSMichael Tuexen 		/* Per RFC5681 Section 3.1 */
41307dc90a1dSMichael Tuexen 		if (maxseg > 2190)
41317dc90a1dSMichael Tuexen 			return (2 * maxseg);
41327dc90a1dSMichael Tuexen 		else if (maxseg > 1095)
41337dc90a1dSMichael Tuexen 			return (3 * maxseg);
41347dc90a1dSMichael Tuexen 		else
41357dc90a1dSMichael Tuexen 			return (4 * maxseg);
41367dc90a1dSMichael Tuexen 	}
41377dc90a1dSMichael Tuexen }
4138