xref: /freebsd/sys/netinet/tcp_input.c (revision fce03f85c5bfc0d73fb5c43ac1affad73efab11a)
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  */
49df8bae1dSRodney W. Grimes 
504b421e2dSMike Silbersack #include <sys/cdefs.h>
511cfd4b53SBruce M Simpson #include "opt_inet.h"
52fb59c426SYoshinobu Inoue #include "opt_inet6.h"
533a2a9f79SYoshinobu Inoue #include "opt_ipsec.h"
54e5738ee0SCheng Cui #include "opt_rss.h"
550cc12cc5SJoerg Wunsch 
56df8bae1dSRodney W. Grimes #include <sys/param.h>
57adc56f5aSEdward Tomasz Napierala #include <sys/arb.h>
5898163b98SPoul-Henning Kamp #include <sys/kernel.h>
59bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
6039bc9de5SLawrence Stewart #include <sys/hhook.h>
61bd79708dSJonathan T. Looney #endif
62df8bae1dSRodney W. Grimes #include <sys/malloc.h>
63df8bae1dSRodney W. Grimes #include <sys/mbuf.h>
64a29f300eSGarrett Wollman #include <sys/proc.h>		/* for proc0 declaration */
65df8bae1dSRodney W. Grimes #include <sys/protosw.h>
66adc56f5aSEdward Tomasz Napierala #include <sys/qmath.h>
6757f60867SMark Johnston #include <sys/sdt.h>
68960ed29cSSeigo Tanimura #include <sys/signalvar.h>
69df8bae1dSRodney W. Grimes #include <sys/socket.h>
70df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
71960ed29cSSeigo Tanimura #include <sys/sysctl.h>
72816a3d83SPoul-Henning Kamp #include <sys/syslog.h>
73960ed29cSSeigo Tanimura #include <sys/systm.h>
74adc56f5aSEdward Tomasz Napierala #include <sys/stats.h>
75df8bae1dSRodney W. Grimes 
76e79adb8eSGarrett Wollman #include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
77e79adb8eSGarrett Wollman 
7812e2e970SAndre Oppermann #include <vm/uma.h>
7912e2e970SAndre Oppermann 
80df8bae1dSRodney W. Grimes #include <net/if.h>
8176039bc8SGleb Smirnoff #include <net/if_var.h>
82df8bae1dSRodney W. Grimes #include <net/route.h>
83e5738ee0SCheng Cui #include <net/rss_config.h>
84530c0060SRobert Watson #include <net/vnet.h>
85df8bae1dSRodney W. Grimes 
86773673c1SAndre Oppermann #define TCPSTATES		/* for logging */
87773673c1SAndre Oppermann 
88df8bae1dSRodney W. Grimes #include <netinet/in.h>
8957f60867SMark Johnston #include <netinet/in_kdtrace.h>
90960ed29cSSeigo Tanimura #include <netinet/in_pcb.h>
91e5738ee0SCheng Cui #include <netinet/in_rss.h>
92df8bae1dSRodney W. Grimes #include <netinet/in_systm.h>
93df8bae1dSRodney W. Grimes #include <netinet/ip.h>
948e8aab7aSAndre Oppermann #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
95686cdd19SJun-ichiro itojun Hagino #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
96df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
97ef39adf0SAndre Oppermann #include <netinet/ip_options.h>
98686cdd19SJun-ichiro itojun Hagino #include <netinet/ip6.h>
99686cdd19SJun-ichiro itojun Hagino #include <netinet/icmp6.h>
100686cdd19SJun-ichiro itojun Hagino #include <netinet6/in6_pcb.h>
101e5738ee0SCheng Cui #include <netinet6/in6_rss.h>
102b66d74c1SGleb Smirnoff #include <netinet6/in6_var.h>
103960ed29cSSeigo Tanimura #include <netinet6/ip6_var.h>
104960ed29cSSeigo Tanimura #include <netinet6/nd6.h>
1052de3e790SGleb Smirnoff #include <netinet/tcp.h>
106df8bae1dSRodney W. Grimes #include <netinet/tcp_fsm.h>
107df8bae1dSRodney W. Grimes #include <netinet/tcp_seq.h>
108df8bae1dSRodney W. Grimes #include <netinet/tcp_timer.h>
109df8bae1dSRodney W. Grimes #include <netinet/tcp_var.h>
11069c7c811SRandall Stewart #include <netinet/tcp_log_buf.h>
111fb59c426SYoshinobu Inoue #include <netinet6/tcp6_var.h>
112df8bae1dSRodney W. Grimes #include <netinet/tcpip.h>
1134644fda3SGleb Smirnoff #include <netinet/cc/cc.h>
114c560df6fSPatrick Kelsey #include <netinet/tcp_fastopen.h>
11586a996e6SHiren Panchasara #ifdef TCPPCAP
11686a996e6SHiren Panchasara #include <netinet/tcp_pcap.h>
11786a996e6SHiren Panchasara #endif
118c325962bSMike Silbersack #include <netinet/tcp_syncache.h>
11909fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
12009fe6320SNavdeep Parhar #include <netinet/tcp_offload.h>
12109fe6320SNavdeep Parhar #endif
122f7220c48SRichard Scheffenegger #include <netinet/tcp_ecn.h>
1239e644c23SMichael Tuexen #include <netinet/udp.h>
124fb59c426SYoshinobu Inoue 
125fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
126b9234fafSSam Leffler 
127db4f9cc7SJonathan Lemon #include <machine/in_cksum.h>
128db4f9cc7SJonathan Lemon 
129aed55708SRobert Watson #include <security/mac/mac_framework.h>
130aed55708SRobert Watson 
131dbc42409SLawrence Stewart const int tcprexmtthresh = 3;
1320312fbe9SPoul-Henning Kamp 
133334fc582SBjoern A. Zeeb VNET_DEFINE(int, tcp_log_in_vain) = 0;
134334fc582SBjoern A. Zeeb SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW,
135334fc582SBjoern A. Zeeb     &VNET_NAME(tcp_log_in_vain), 0,
136eddfbb76SRobert Watson     "Log all incoming TCP segments to closed ports");
137816a3d83SPoul-Henning Kamp 
13882cea7e6SBjoern A. Zeeb VNET_DEFINE(int, blackhole) = 0;
13982cea7e6SBjoern A. Zeeb #define	V_blackhole		VNET(blackhole)
1406df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
141eddfbb76SRobert Watson     &VNET_NAME(blackhole), 0,
142eddfbb76SRobert Watson     "Do not send RST on segments to closed ports");
14316f7f31fSGeoff Rehmet 
1443ea9a7cfSGleb Smirnoff VNET_DEFINE(bool, blackhole_local) = false;
1453ea9a7cfSGleb Smirnoff #define	V_blackhole_local	VNET(blackhole_local)
1463ea9a7cfSGleb Smirnoff SYSCTL_BOOL(_net_inet_tcp, OID_AUTO, blackhole_local, CTLFLAG_VNET |
1473ea9a7cfSGleb Smirnoff     CTLFLAG_RW, &VNET_NAME(blackhole_local), false,
1483ea9a7cfSGleb Smirnoff     "Enforce net.inet.tcp.blackhole for locally originated packets");
1493ea9a7cfSGleb Smirnoff 
15082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_delack_enabled) = 1;
1516df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
152eddfbb76SRobert Watson     &VNET_NAME(tcp_delack_enabled), 0,
1533d177f46SBill Fumerola     "Delay ACK to try and piggyback it onto a data packet");
154f498eeeeSDavid Greenman 
15582cea7e6SBjoern A. Zeeb VNET_DEFINE(int, drop_synfin) = 0;
1566df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
157eddfbb76SRobert Watson     &VNET_NAME(drop_synfin), 0,
158eddfbb76SRobert Watson     "Drop TCP packets with SYN+FIN set");
159f8613305SDag-Erling Smørgrav 
1600e1d7c25SRichard Scheffenegger VNET_DEFINE(int, tcp_do_prr) = 1;
1610e1d7c25SRichard Scheffenegger SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_prr, CTLFLAG_VNET | CTLFLAG_RW,
1620e1d7c25SRichard Scheffenegger     &VNET_NAME(tcp_do_prr), 1,
1630e1d7c25SRichard Scheffenegger     "Enable Proportional Rate Reduction per RFC 6937");
1640e1d7c25SRichard Scheffenegger 
165b72e56e7SMichael Tuexen VNET_DEFINE(int, tcp_do_newcwv) = 0;
166b72e56e7SMichael Tuexen SYSCTL_INT(_net_inet_tcp, OID_AUTO, newcwv, CTLFLAG_VNET | CTLFLAG_RW,
167b72e56e7SMichael Tuexen     &VNET_NAME(tcp_do_newcwv), 0,
168b72e56e7SMichael Tuexen     "Enable New Congestion Window Validation per RFC7661");
169b72e56e7SMichael Tuexen 
17082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3042) = 1;
1716df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
172eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3042), 0,
173eddfbb76SRobert Watson     "Enable RFC 3042 (Limited Transmit)");
174582a954bSJeffrey Hsu 
17582cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3390) = 1;
1766df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
177eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3390), 0,
178da3a8a1aSJeffrey Hsu     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
179da3a8a1aSJeffrey Hsu 
180356c7958SHiren Panchasara VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
181356c7958SHiren Panchasara SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
182356c7958SHiren Panchasara     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
183356c7958SHiren Panchasara     "Slow-start flight size (initial congestion window) in number of segments");
18409440655SAndre Oppermann 
18582cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_rfc3465) = 1;
1866df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
187eddfbb76SRobert Watson     &VNET_NAME(tcp_do_rfc3465), 0,
18824cb0f22SLawrence Stewart     "Enable RFC 3465 (Appropriate Byte Counting)");
189eddfbb76SRobert Watson 
19082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_abc_l_var) = 2;
1916df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
192eddfbb76SRobert Watson     &VNET_NAME(tcp_abc_l_var), 2,
19324cb0f22SLawrence Stewart     "Cap the max cwnd increment during slow-start to this number of segments");
19424cb0f22SLawrence Stewart 
1953220a212SGleb Smirnoff VNET_DEFINE(int, tcp_insecure_syn) = 0;
1966df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
1973220a212SGleb Smirnoff     &VNET_NAME(tcp_insecure_syn), 0,
1983220a212SGleb Smirnoff     "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
1993220a212SGleb Smirnoff 
20082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_insecure_rst) = 0;
2016df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
202eddfbb76SRobert Watson     &VNET_NAME(tcp_insecure_rst), 0,
2033220a212SGleb Smirnoff     "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
204a69968eeSMike Silbersack 
205fba0cea1SBjoern A. Zeeb VNET_DEFINE(int, tcp_recvspace) = 1024*64;
206873789cbSAndre Oppermann #define	V_tcp_recvspace	VNET(tcp_recvspace)
2076df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
208873789cbSAndre Oppermann     &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
209873789cbSAndre Oppermann 
21082cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
2116df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
212eddfbb76SRobert Watson     &VNET_NAME(tcp_do_autorcvbuf), 0,
2138b615593SMarko Zec     "Enable automatic receive buffer sizing");
2146741ecf5SAndre Oppermann 
215b233773bSBjoern A. Zeeb VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
2166df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
217eddfbb76SRobert Watson     &VNET_NAME(tcp_autorcvbuf_max), 0,
2188b615593SMarko Zec     "Max size of automatic receive buffer");
2196741ecf5SAndre Oppermann 
22082cea7e6SBjoern A. Zeeb VNET_DEFINE(struct inpcbinfo, tcbinfo);
221df8bae1dSRodney W. Grimes 
222315e3e38SRobert Watson /*
223bf840a17SGleb Smirnoff  * TCP statistics are stored in an array of counter(9)s, which size matches
224bf840a17SGleb Smirnoff  * size of struct tcpstat.  TCP running connection count is a regular array.
2255923c293SGleb Smirnoff  */
2265da0521fSAndrey V. Elsukov VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
2275da0521fSAndrey V. Elsukov SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
2285da0521fSAndrey V. Elsukov     tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
229bf840a17SGleb Smirnoff VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
230bf840a17SGleb Smirnoff SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
231d4d32b9fSHans Petter Selasky     CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
232bf840a17SGleb Smirnoff     "TCP connection counts by TCP state");
233bf840a17SGleb Smirnoff 
2345923c293SGleb Smirnoff /*
2357ca6e296SMichael Tuexen  * Kernel module interface for updating tcpstat.  The first argument is an index
2365923c293SGleb Smirnoff  * into tcpstat treated as an array.
237315e3e38SRobert Watson  */
238315e3e38SRobert Watson void
2397ca6e296SMichael Tuexen kmod_tcpstat_add(int statnum, int val)
240315e3e38SRobert Watson {
241315e3e38SRobert Watson 
2427ca6e296SMichael Tuexen 	counter_u64_add(VNET(tcpstat)[statnum], val);
243315e3e38SRobert Watson }
244315e3e38SRobert Watson 
245c21b7b55SRichard Scheffenegger /*
246c21b7b55SRichard Scheffenegger  * Make sure that we only start a SACK loss recovery when
247c21b7b55SRichard Scheffenegger  * receiving a duplicate ACK with a SACK block, and also
248c21b7b55SRichard Scheffenegger  * complete SACK loss recovery in case the other end
249c21b7b55SRichard Scheffenegger  * reneges.
250c21b7b55SRichard Scheffenegger  */
251c21b7b55SRichard Scheffenegger static bool inline
252c21b7b55SRichard Scheffenegger tcp_is_sack_recovery(struct tcpcb *tp, struct tcpopt *to)
253c21b7b55SRichard Scheffenegger {
254c21b7b55SRichard Scheffenegger 	return ((tp->t_flags & TF_SACK_PERMIT) &&
255c21b7b55SRichard Scheffenegger 		((to->to_flags & TOF_SACK) ||
256c21b7b55SRichard Scheffenegger 		(!TAILQ_EMPTY(&tp->snd_holes))));
257c21b7b55SRichard Scheffenegger }
258c21b7b55SRichard Scheffenegger 
259bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
260dbc42409SLawrence Stewart /*
26139bc9de5SLawrence Stewart  * Wrapper for the TCP established input helper hook.
26239bc9de5SLawrence Stewart  */
26355bceb1eSRandall Stewart void
26439bc9de5SLawrence Stewart hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
26539bc9de5SLawrence Stewart {
26639bc9de5SLawrence Stewart 	struct tcp_hhook_data hhook_data;
26739bc9de5SLawrence Stewart 
26839bc9de5SLawrence Stewart 	if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
26939bc9de5SLawrence Stewart 		hhook_data.tp = tp;
27039bc9de5SLawrence Stewart 		hhook_data.th = th;
27139bc9de5SLawrence Stewart 		hhook_data.to = to;
27239bc9de5SLawrence Stewart 
27339bc9de5SLawrence Stewart 		hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
274e68b3792SGleb Smirnoff 		    &tp->t_osd);
27539bc9de5SLawrence Stewart 	}
27639bc9de5SLawrence Stewart }
277bd79708dSJonathan T. Looney #endif
27839bc9de5SLawrence Stewart 
27939bc9de5SLawrence Stewart /*
280dbc42409SLawrence Stewart  * CC wrapper hook functions
281dbc42409SLawrence Stewart  */
28255bceb1eSRandall Stewart void
2834b7b743cSLawrence Stewart cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
2844b7b743cSLawrence Stewart     uint16_t type)
285f2512ba1SRui Paulo {
286adc56f5aSEdward Tomasz Napierala #ifdef STATS
287adc56f5aSEdward Tomasz Napierala 	int32_t gput;
288adc56f5aSEdward Tomasz Napierala #endif
289adc56f5aSEdward Tomasz Napierala 
2909eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
291f2512ba1SRui Paulo 
292e68b3792SGleb Smirnoff 	tp->t_ccv.nsegs = nsegs;
293e68b3792SGleb Smirnoff 	tp->t_ccv.bytes_this_ack = BYTES_THIS_ACK(tp, th);
294b72e56e7SMichael Tuexen 	if ((!V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd)) ||
295b72e56e7SMichael Tuexen 	    (V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd) &&
296b72e56e7SMichael Tuexen 	     (tp->snd_cwnd < (tcp_compute_pipe(tp) * 2))))
297e68b3792SGleb Smirnoff 		tp->t_ccv.flags |= CCF_CWND_LIMITED;
298dbc42409SLawrence Stewart 	else
299e68b3792SGleb Smirnoff 		tp->t_ccv.flags &= ~CCF_CWND_LIMITED;
300dbc42409SLawrence Stewart 
301dbc42409SLawrence Stewart 	if (type == CC_ACK) {
302adc56f5aSEdward Tomasz Napierala #ifdef STATS
303adc56f5aSEdward Tomasz Napierala 		stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
304adc56f5aSEdward Tomasz Napierala 		    ((int32_t)tp->snd_cwnd) - tp->snd_wnd);
305adc56f5aSEdward Tomasz Napierala 		if (!IN_RECOVERY(tp->t_flags))
306adc56f5aSEdward Tomasz Napierala 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_ACKLEN,
307e68b3792SGleb Smirnoff 			   tp->t_ccv.bytes_this_ack / (tcp_maxseg(tp) * nsegs));
308adc56f5aSEdward Tomasz Napierala 		if ((tp->t_flags & TF_GPUTINPROG) &&
309adc56f5aSEdward Tomasz Napierala 		    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
310adc56f5aSEdward Tomasz Napierala 			/*
311adc56f5aSEdward Tomasz Napierala 			 * Compute goodput in bits per millisecond.
312adc56f5aSEdward Tomasz Napierala 			 */
313f5766992SHans Petter Selasky 			gput = (((int64_t)SEQ_SUB(th->th_ack, tp->gput_seq)) << 3) /
314adc56f5aSEdward Tomasz Napierala 			    max(1, tcp_ts_getticks() - tp->gput_ts);
315adc56f5aSEdward Tomasz Napierala 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
316adc56f5aSEdward Tomasz Napierala 			    gput);
317adc56f5aSEdward Tomasz Napierala 			/*
318adc56f5aSEdward Tomasz Napierala 			 * XXXLAS: This is a temporary hack, and should be
319adc56f5aSEdward Tomasz Napierala 			 * chained off VOI_TCP_GPUT when stats(9) grows an API
320adc56f5aSEdward Tomasz Napierala 			 * to deal with chained VOIs.
321adc56f5aSEdward Tomasz Napierala 			 */
322adc56f5aSEdward Tomasz Napierala 			if (tp->t_stats_gput_prev > 0)
323adc56f5aSEdward Tomasz Napierala 				stats_voi_update_abs_s32(tp->t_stats,
324adc56f5aSEdward Tomasz Napierala 				    VOI_TCP_GPUT_ND,
325adc56f5aSEdward Tomasz Napierala 				    ((gput - tp->t_stats_gput_prev) * 100) /
326adc56f5aSEdward Tomasz Napierala 				    tp->t_stats_gput_prev);
327adc56f5aSEdward Tomasz Napierala 			tp->t_flags &= ~TF_GPUTINPROG;
328adc56f5aSEdward Tomasz Napierala 			tp->t_stats_gput_prev = gput;
329adc56f5aSEdward Tomasz Napierala 		}
330adc56f5aSEdward Tomasz Napierala #endif /* STATS */
331dbc42409SLawrence Stewart 		if (tp->snd_cwnd > tp->snd_ssthresh) {
332e68b3792SGleb Smirnoff 			tp->t_bytes_acked += tp->t_ccv.bytes_this_ack;
333dbc42409SLawrence Stewart 			if (tp->t_bytes_acked >= tp->snd_cwnd) {
334dbc42409SLawrence Stewart 				tp->t_bytes_acked -= tp->snd_cwnd;
335e68b3792SGleb Smirnoff 				tp->t_ccv.flags |= CCF_ABC_SENTAWND;
336dbc42409SLawrence Stewart 			}
337dbc42409SLawrence Stewart 		} else {
338e68b3792SGleb Smirnoff 				tp->t_ccv.flags &= ~CCF_ABC_SENTAWND;
339dbc42409SLawrence Stewart 				tp->t_bytes_acked = 0;
340dbc42409SLawrence Stewart 		}
341dbc42409SLawrence Stewart 	}
342dbc42409SLawrence Stewart 
343dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->ack_received != NULL) {
344dbc42409SLawrence Stewart 		/* XXXLAS: Find a way to live without this */
345e68b3792SGleb Smirnoff 		tp->t_ccv.curack = th->th_ack;
346e68b3792SGleb Smirnoff 		CC_ALGO(tp)->ack_received(&tp->t_ccv, type);
347dbc42409SLawrence Stewart 	}
348adc56f5aSEdward Tomasz Napierala #ifdef STATS
349adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
350adc56f5aSEdward Tomasz Napierala #endif
351dbc42409SLawrence Stewart }
352dbc42409SLawrence Stewart 
35355bceb1eSRandall Stewart void
354dbc42409SLawrence Stewart cc_conn_init(struct tcpcb *tp)
355dbc42409SLawrence Stewart {
356dbc42409SLawrence Stewart 	struct hc_metrics_lite metrics;
3579eb0e832SGleb Smirnoff 	struct inpcb *inp = tptoinpcb(tp);
3580c39d38dSGleb Smirnoff 	u_int maxseg;
359dbc42409SLawrence Stewart 	int rtt;
360dbc42409SLawrence Stewart 
3619eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
362dbc42409SLawrence Stewart 
363dbc42409SLawrence Stewart 	tcp_hc_get(&inp->inp_inc, &metrics);
3640c39d38dSGleb Smirnoff 	maxseg = tcp_maxseg(tp);
365dbc42409SLawrence Stewart 
366dbc42409SLawrence Stewart 	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
367dbc42409SLawrence Stewart 		tp->t_srtt = rtt;
368dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_usedrtt);
369dbc42409SLawrence Stewart 		if (metrics.rmx_rttvar) {
370dbc42409SLawrence Stewart 			tp->t_rttvar = metrics.rmx_rttvar;
371dbc42409SLawrence Stewart 			TCPSTAT_INC(tcps_usedrttvar);
372dbc42409SLawrence Stewart 		} else {
373dbc42409SLawrence Stewart 			/* default variation is +- 1 rtt */
374dbc42409SLawrence Stewart 			tp->t_rttvar =
375dbc42409SLawrence Stewart 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
376dbc42409SLawrence Stewart 		}
377dbc42409SLawrence Stewart 		TCPT_RANGESET(tp->t_rxtcur,
378dbc42409SLawrence Stewart 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
379dbc42409SLawrence Stewart 		    tp->t_rttmin, TCPTV_REXMTMAX);
380dbc42409SLawrence Stewart 	}
381dbc42409SLawrence Stewart 	if (metrics.rmx_ssthresh) {
382dbc42409SLawrence Stewart 		/*
383dbc42409SLawrence Stewart 		 * There's some sort of gateway or interface
384dbc42409SLawrence Stewart 		 * buffer limit on the path.  Use this to set
385a4641f4eSPedro F. Giffuni 		 * the slow start threshold, but set the
386dbc42409SLawrence Stewart 		 * threshold to no less than 2*mss.
387dbc42409SLawrence Stewart 		 */
3880c39d38dSGleb Smirnoff 		tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
389dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_usedssthresh);
390dbc42409SLawrence Stewart 	}
391dbc42409SLawrence Stewart 
392dbc42409SLawrence Stewart 	/*
3939ec4a4ccSAndre Oppermann 	 * Set the initial slow-start flight size.
394dbc42409SLawrence Stewart 	 *
395cf8f04f4SAndre Oppermann 	 * If a SYN or SYN/ACK was lost and retransmitted, we have to
396cf8f04f4SAndre Oppermann 	 * reduce the initial CWND to one segment as congestion is likely
397cf8f04f4SAndre Oppermann 	 * requiring us to be cautious.
398dbc42409SLawrence Stewart 	 */
399cf8f04f4SAndre Oppermann 	if (tp->snd_cwnd == 1)
4000c39d38dSGleb Smirnoff 		tp->snd_cwnd = maxseg;		/* SYN(-ACK) lost */
401dbc42409SLawrence Stewart 	else
4027dc90a1dSMichael Tuexen 		tp->snd_cwnd = tcp_compute_initwnd(maxseg);
403dbc42409SLawrence Stewart 
404dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->conn_init != NULL)
405e68b3792SGleb Smirnoff 		CC_ALGO(tp)->conn_init(&tp->t_ccv);
406dbc42409SLawrence Stewart }
407dbc42409SLawrence Stewart 
408dbc42409SLawrence Stewart void inline
409dbc42409SLawrence Stewart cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
410dbc42409SLawrence Stewart {
4119eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
412dbc42409SLawrence Stewart 
413adc56f5aSEdward Tomasz Napierala #ifdef STATS
414adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
415adc56f5aSEdward Tomasz Napierala #endif
416adc56f5aSEdward Tomasz Napierala 
417dbc42409SLawrence Stewart 	switch(type) {
418dbc42409SLawrence Stewart 	case CC_NDUPACK:
419dbc42409SLawrence Stewart 		if (!IN_FASTRECOVERY(tp->t_flags)) {
420f2512ba1SRui Paulo 			tp->snd_recover = tp->snd_max;
4213cf38784SMichael Tuexen 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4223cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_SND_CWR;
423f2512ba1SRui Paulo 		}
424dbc42409SLawrence Stewart 		break;
425dbc42409SLawrence Stewart 	case CC_ECN:
426af2fb894SRichard Scheffenegger 		if (!IN_CONGRECOVERY(tp->t_flags) ||
427af2fb894SRichard Scheffenegger 		    /*
428af2fb894SRichard Scheffenegger 		     * Allow ECN reaction on ACK to CWR, if
429af2fb894SRichard Scheffenegger 		     * that data segment was also CE marked.
430af2fb894SRichard Scheffenegger 		     */
431af2fb894SRichard Scheffenegger 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
432af2fb894SRichard Scheffenegger 			EXIT_CONGRECOVERY(tp->t_flags);
433dbc42409SLawrence Stewart 			TCPSTAT_INC(tcps_ecn_rcwnd);
434af2fb894SRichard Scheffenegger 			tp->snd_recover = tp->snd_max + 1;
4353cf38784SMichael Tuexen 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4363cf38784SMichael Tuexen 				tp->t_flags2 |= TF2_ECN_SND_CWR;
437dbc42409SLawrence Stewart 		}
438dbc42409SLawrence Stewart 		break;
439dbc42409SLawrence Stewart 	case CC_RTO:
440dbc42409SLawrence Stewart 		tp->t_dupacks = 0;
441dbc42409SLawrence Stewart 		tp->t_bytes_acked = 0;
44230409ecdSRichard Scheffenegger 		if ((tp->t_rxtshift > 1) ||
44330409ecdSRichard Scheffenegger 		    !((tp->t_flags & TF_SACK_PERMIT) &&
44430409ecdSRichard Scheffenegger 		      (!TAILQ_EMPTY(&tp->snd_holes))))
445dbc42409SLawrence Stewart 			EXIT_RECOVERY(tp->t_flags);
4469cc711c9SMichael Tuexen 		if (tp->t_flags2 & TF2_ECN_PERMIT)
4479cc711c9SMichael Tuexen 			tp->t_flags2 |= TF2_ECN_SND_CWR;
448dbc42409SLawrence Stewart 		break;
449dbc42409SLawrence Stewart 	case CC_RTO_ERR:
450dbc42409SLawrence Stewart 		TCPSTAT_INC(tcps_sndrexmitbad);
451dbc42409SLawrence Stewart 		/* RTO was unnecessary, so reset everything. */
452dbc42409SLawrence Stewart 		tp->snd_cwnd = tp->snd_cwnd_prev;
453dbc42409SLawrence Stewart 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
454dbc42409SLawrence Stewart 		tp->snd_recover = tp->snd_recover_prev;
455dbc42409SLawrence Stewart 		if (tp->t_flags & TF_WASFRECOVERY)
456dbc42409SLawrence Stewart 			ENTER_FASTRECOVERY(tp->t_flags);
457dbc42409SLawrence Stewart 		if (tp->t_flags & TF_WASCRECOVERY)
458dbc42409SLawrence Stewart 			ENTER_CONGRECOVERY(tp->t_flags);
459dbc42409SLawrence Stewart 		tp->snd_nxt = tp->snd_max;
460672dc4aeSJohn Baldwin 		tp->t_flags &= ~TF_PREVVALID;
461dbc42409SLawrence Stewart 		tp->t_badrxtwin = 0;
462dbc42409SLawrence Stewart 		break;
463dbc42409SLawrence Stewart 	}
464fcea1cc9SRichard Scheffenegger 	if (SEQ_LT(tp->snd_fack, tp->snd_una) ||
465fcea1cc9SRichard Scheffenegger 	    SEQ_GT(tp->snd_fack, tp->snd_max)) {
466fcea1cc9SRichard Scheffenegger 		tp->snd_fack = tp->snd_una;
467fcea1cc9SRichard Scheffenegger 	}
468dbc42409SLawrence Stewart 
469dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->cong_signal != NULL) {
470dbc42409SLawrence Stewart 		if (th != NULL)
471e68b3792SGleb Smirnoff 			tp->t_ccv.curack = th->th_ack;
472e68b3792SGleb Smirnoff 		CC_ALGO(tp)->cong_signal(&tp->t_ccv, type);
473dbc42409SLawrence Stewart 	}
474dbc42409SLawrence Stewart }
475dbc42409SLawrence Stewart 
47655bceb1eSRandall Stewart void inline
477dbc42409SLawrence Stewart cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
478dbc42409SLawrence Stewart {
4799eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
480dbc42409SLawrence Stewart 
481dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->post_recovery != NULL) {
48240fdc6d2SRichard Scheffenegger 		if (SEQ_LT(tp->snd_fack, th->th_ack) ||
48340fdc6d2SRichard Scheffenegger 		    SEQ_GT(tp->snd_fack, tp->snd_max)) {
48440fdc6d2SRichard Scheffenegger 			tp->snd_fack = th->th_ack;
48540fdc6d2SRichard Scheffenegger 		}
486e68b3792SGleb Smirnoff 		tp->t_ccv.curack = th->th_ack;
487e68b3792SGleb Smirnoff 		CC_ALGO(tp)->post_recovery(&tp->t_ccv);
488dbc42409SLawrence Stewart 	}
4890b3f9e43SRichard Scheffenegger 	EXIT_RECOVERY(tp->t_flags);
4900b3f9e43SRichard Scheffenegger 
491dbc42409SLawrence Stewart 	tp->t_bytes_acked = 0;
49248be5b97SRichard Scheffenegger 	tp->sackhint.delivered_data = 0;
493429f14f8SRichard Scheffenegger 	tp->sackhint.prr_delivered = 0;
494e5313869SRichard Scheffenegger 	tp->sackhint.prr_out = 0;
495dbc42409SLawrence Stewart }
4960312fbe9SPoul-Henning Kamp 
497df8bae1dSRodney W. Grimes /*
498262c1c1aSMatthew Dillon  * Indicate whether this ack should be delayed.  We can delay the ack if
49985536381SHiren Panchasara  * following conditions are met:
50085536381SHiren Panchasara  *	- There is no delayed ack timer in progress.
50185536381SHiren Panchasara  *	- Our last ack wasn't a 0-sized window. We never want to delay
50285536381SHiren Panchasara  *	  the ack that opens up a 0-sized window.
50385536381SHiren Panchasara  *	- LRO wasn't used for this segment. We make sure by checking that the
50485536381SHiren Panchasara  *	  segment size is not larger than the MSS.
505d8c85a26SJonathan Lemon  */
506c1e5a6e5SAndre Oppermann #define DELAY_ACK(tp, tlen)						\
507b8152ba7SAndre Oppermann 	((!tcp_timer_active(tp, TT_DELACK) &&				\
508a14c749fSJonathan Lemon 	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
5090c39d38dSGleb Smirnoff 	    (tlen <= tp->t_maxseg) &&					\
510603724d3SBjoern A. Zeeb 	    (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
511d8c85a26SJonathan Lemon 
5124ad24737SRandall Stewart void inline
5135d8fd932SRandall Stewart cc_ecnpkt_handler_flags(struct tcpcb *tp, uint16_t flags, uint8_t iptos)
51464807b30SHiren Panchasara {
5159eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
51664807b30SHiren Panchasara 
51764807b30SHiren Panchasara 	if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
51864807b30SHiren Panchasara 		switch (iptos & IPTOS_ECN_MASK) {
51964807b30SHiren Panchasara 		case IPTOS_ECN_CE:
520e68b3792SGleb Smirnoff 			tp->t_ccv.flags |= CCF_IPHDR_CE;
52164807b30SHiren Panchasara 			break;
52264807b30SHiren Panchasara 		case IPTOS_ECN_ECT0:
52383a2839fSMichael Tuexen 			/* FALLTHROUGH */
52464807b30SHiren Panchasara 		case IPTOS_ECN_ECT1:
52583a2839fSMichael Tuexen 			/* FALLTHROUGH */
52683a2839fSMichael Tuexen 		case IPTOS_ECN_NOTECT:
527e68b3792SGleb Smirnoff 			tp->t_ccv.flags &= ~CCF_IPHDR_CE;
52864807b30SHiren Panchasara 			break;
52964807b30SHiren Panchasara 		}
53064807b30SHiren Panchasara 
5315d8fd932SRandall Stewart 		if (flags & TH_CWR)
532e68b3792SGleb Smirnoff 			tp->t_ccv.flags |= CCF_TCPHDR_CWR;
53364807b30SHiren Panchasara 		else
534e68b3792SGleb Smirnoff 			tp->t_ccv.flags &= ~CCF_TCPHDR_CWR;
53564807b30SHiren Panchasara 
536e68b3792SGleb Smirnoff 		CC_ALGO(tp)->ecnpkt_handler(&tp->t_ccv);
53764807b30SHiren Panchasara 
538e68b3792SGleb Smirnoff 		if (tp->t_ccv.flags & CCF_ACKNOW) {
53964807b30SHiren Panchasara 			tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
540e11c9783SMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
541e11c9783SMichael Tuexen 		}
54264807b30SHiren Panchasara 	}
54364807b30SHiren Panchasara }
54464807b30SHiren Panchasara 
5455d8fd932SRandall Stewart void inline
5465d8fd932SRandall Stewart cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
5475d8fd932SRandall Stewart {
5481ebf4607SRichard Scheffenegger 	cc_ecnpkt_handler_flags(tp, tcp_get_flags(th), iptos);
5495d8fd932SRandall Stewart }
5505d8fd932SRandall Stewart 
551df8bae1dSRodney W. Grimes /*
5528d573cc1SAndre Oppermann  * TCP input handling is split into multiple parts:
5538d573cc1SAndre Oppermann  *   tcp6_input is a thin wrapper around tcp_input for the extended
5548d573cc1SAndre Oppermann  *	ip6_protox[] call format in ip6_input
5558d573cc1SAndre Oppermann  *   tcp_input handles primary segment validation, inpcb lookup and
5568d573cc1SAndre Oppermann  *	SYN processing on listen sockets
5578d573cc1SAndre Oppermann  *   tcp_do_segment processes the ACK and text of the segment for
5588d573cc1SAndre Oppermann  *	establishing, established and closing connections
559df8bae1dSRodney W. Grimes  */
560fb59c426SYoshinobu Inoue #ifdef INET6
561fb59c426SYoshinobu Inoue int
5629e644c23SMichael Tuexen tcp6_input_with_port(struct mbuf **mp, int *offp, int proto, uint16_t port)
563fb59c426SYoshinobu Inoue {
564503f4e47SBjoern A. Zeeb 	struct mbuf *m;
56533841545SHajimu UMEMOTO 	struct in6_ifaddr *ia6;
5663e88eb90SAndrey V. Elsukov 	struct ip6_hdr *ip6;
567fb59c426SYoshinobu Inoue 
568503f4e47SBjoern A. Zeeb 	m = *mp;
569a4adf6ccSBjoern A. Zeeb 	if (m->m_len < *offp + sizeof(struct tcphdr)) {
5704e619b17SBjoern A. Zeeb 		m = m_pullup(m, *offp + sizeof(struct tcphdr));
5714e619b17SBjoern A. Zeeb 		if (m == NULL) {
5724e619b17SBjoern A. Zeeb 			*mp = m;
5734e619b17SBjoern A. Zeeb 			TCPSTAT_INC(tcps_rcvshort);
5744e619b17SBjoern A. Zeeb 			return (IPPROTO_DONE);
5754e619b17SBjoern A. Zeeb 		}
576a4adf6ccSBjoern A. Zeeb 	}
577fb59c426SYoshinobu Inoue 
578fb59c426SYoshinobu Inoue 	/*
579fb59c426SYoshinobu Inoue 	 * draft-itojun-ipv6-tcp-to-anycast
580fb59c426SYoshinobu Inoue 	 * better place to put this in?
581fb59c426SYoshinobu Inoue 	 */
5823e88eb90SAndrey V. Elsukov 	ip6 = mtod(m, struct ip6_hdr *);
5838268d82cSAlexander V. Chernikov 	ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
58433841545SHajimu UMEMOTO 	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
585fb59c426SYoshinobu Inoue 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
586fb59c426SYoshinobu Inoue 			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
587a8fe77d8SBjoern A. Zeeb 		*mp = NULL;
5888f5a8818SKevin Lo 		return (IPPROTO_DONE);
589fb59c426SYoshinobu Inoue 	}
590fb59c426SYoshinobu Inoue 
591a8fe77d8SBjoern A. Zeeb 	*mp = m;
5929e644c23SMichael Tuexen 	return (tcp_input_with_port(mp, offp, proto, port));
5939e644c23SMichael Tuexen }
5949e644c23SMichael Tuexen 
5959e644c23SMichael Tuexen int
5969e644c23SMichael Tuexen tcp6_input(struct mbuf **mp, int *offp, int proto)
5979e644c23SMichael Tuexen {
5989e644c23SMichael Tuexen 
5999e644c23SMichael Tuexen 	return(tcp6_input_with_port(mp, offp, proto, 0));
600fb59c426SYoshinobu Inoue }
601b287c6c7SBjoern A. Zeeb #endif /* INET6 */
602fb59c426SYoshinobu Inoue 
6038f5a8818SKevin Lo int
6049e644c23SMichael Tuexen tcp_input_with_port(struct mbuf **mp, int *offp, int proto, uint16_t port)
605df8bae1dSRodney W. Grimes {
6068f5a8818SKevin Lo 	struct mbuf *m = *mp;
607b287c6c7SBjoern A. Zeeb 	struct tcphdr *th = NULL;
608ad3f9ab3SAndre Oppermann 	struct ip *ip = NULL;
609ad3f9ab3SAndre Oppermann 	struct inpcb *inp = NULL;
610302ce8d6SAndre Oppermann 	struct tcpcb *tp = NULL;
611302ce8d6SAndre Oppermann 	struct socket *so = NULL;
612e79adb8eSGarrett Wollman 	u_char *optp = NULL;
6138f5a8818SKevin Lo 	int off0;
61426f9a767SRodney W. Grimes 	int optlen = 0;
615b287c6c7SBjoern A. Zeeb #ifdef INET
616b287c6c7SBjoern A. Zeeb 	int len;
617c4556b2fSAndrey V. Elsukov 	uint8_t ipttl;
618b287c6c7SBjoern A. Zeeb #endif
619b287c6c7SBjoern A. Zeeb 	int tlen = 0, off;
620fb59c426SYoshinobu Inoue 	int drop_hdrlen;
621ad3f9ab3SAndre Oppermann 	int thflags;
622302ce8d6SAndre Oppermann 	int rstreason = 0;	/* For badport_bandlim accounting purposes */
62308d9c920SGleb Smirnoff 	int lookupflag;
6241d7ee746SKurt Lidl 	uint8_t iptos;
625c1de64a4SAndrey V. Elsukov 	struct m_tag *fwd_tag = NULL;
626c068736aSJeffrey Hsu #ifdef INET6
627302ce8d6SAndre Oppermann 	struct ip6_hdr *ip6 = NULL;
628c068736aSJeffrey Hsu 	int isipv6;
629c068736aSJeffrey Hsu #else
630a160e630SAndre Oppermann 	const void *ip6 = NULL;
631b287c6c7SBjoern A. Zeeb #endif /* INET6 */
632302ce8d6SAndre Oppermann 	struct tcpopt to;		/* options in this segment */
633a160e630SAndre Oppermann 	char *s = NULL;			/* address and port logging */
634c068736aSJeffrey Hsu 
635d40c0d47SGleb Smirnoff 	NET_EPOCH_ASSERT();
636d40c0d47SGleb Smirnoff 
637fb59c426SYoshinobu Inoue #ifdef INET6
638fb59c426SYoshinobu Inoue 	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
639fb59c426SYoshinobu Inoue #endif
640a0292f23SGarrett Wollman 
6418f5a8818SKevin Lo 	off0 = *offp;
6428f5a8818SKevin Lo 	m = *mp;
6438f5a8818SKevin Lo 	*mp = NULL;
644302ce8d6SAndre Oppermann 	to.to_flags = 0;
64578b50714SRobert Watson 	TCPSTAT_INC(tcps_rcvtotal);
646fb59c426SYoshinobu Inoue 
647513f2e2eSGleb Smirnoff 	m->m_pkthdr.tcp_tun_port = port;
64804d3a452SHajimu UMEMOTO #ifdef INET6
649b287c6c7SBjoern A. Zeeb 	if (isipv6) {
650fb59c426SYoshinobu Inoue 		ip6 = mtod(m, struct ip6_hdr *);
65145747ba5SBjoern A. Zeeb 		th = (struct tcphdr *)((caddr_t)ip6 + off0);
652fb59c426SYoshinobu Inoue 		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
6539e644c23SMichael Tuexen 		if (port)
6549e644c23SMichael Tuexen 			goto skip6_csum;
655356ab07eSBjoern A. Zeeb 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
65645747ba5SBjoern A. Zeeb 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
65745747ba5SBjoern A. Zeeb 				th->th_sum = m->m_pkthdr.csum_data;
65845747ba5SBjoern A. Zeeb 			else
65945747ba5SBjoern A. Zeeb 				th->th_sum = in6_cksum_pseudo(ip6, tlen,
66045747ba5SBjoern A. Zeeb 				    IPPROTO_TCP, m->m_pkthdr.csum_data);
66145747ba5SBjoern A. Zeeb 			th->th_sum ^= 0xffff;
66245747ba5SBjoern A. Zeeb 		} else
66345747ba5SBjoern A. Zeeb 			th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
66445747ba5SBjoern A. Zeeb 		if (th->th_sum) {
66578b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvbadsum);
666fb59c426SYoshinobu Inoue 			goto drop;
667fb59c426SYoshinobu Inoue 		}
6689e644c23SMichael Tuexen 	skip6_csum:
66933841545SHajimu UMEMOTO 		/*
67033841545SHajimu UMEMOTO 		 * Be proactive about unspecified IPv6 address in source.
67133841545SHajimu UMEMOTO 		 * As we use all-zero to indicate unbounded/unconnected pcb,
67233841545SHajimu UMEMOTO 		 * unspecified IPv6 address can be used to confuse us.
67333841545SHajimu UMEMOTO 		 *
67433841545SHajimu UMEMOTO 		 * Note that packets with unspecified IPv6 destination is
67533841545SHajimu UMEMOTO 		 * already dropped in ip6_input.
67633841545SHajimu UMEMOTO 		 */
677713264f6SMark Johnston 		KASSERT(!IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst),
678713264f6SMark Johnston 		    ("%s: unspecified destination v6 address", __func__));
67933841545SHajimu UMEMOTO 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
68078e6c3aaSGleb Smirnoff 			IP6STAT_INC(ip6s_badscope); /* XXX */
68133841545SHajimu UMEMOTO 			goto drop;
68233841545SHajimu UMEMOTO 		}
683bb4a7d94SKristof Provost 		iptos = IPV6_TRAFFIC_CLASS(ip6);
684b287c6c7SBjoern A. Zeeb 	}
68504d3a452SHajimu UMEMOTO #endif
686b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
687b287c6c7SBjoern A. Zeeb 	else
688b287c6c7SBjoern A. Zeeb #endif
689b287c6c7SBjoern A. Zeeb #ifdef INET
690b287c6c7SBjoern A. Zeeb 	{
691df8bae1dSRodney W. Grimes 		/*
692df8bae1dSRodney W. Grimes 		 * Get IP and TCP header together in first mbuf.
693df8bae1dSRodney W. Grimes 		 * Note: IP leaves IP header in first mbuf.
694df8bae1dSRodney W. Grimes 		 */
695fb59c426SYoshinobu Inoue 		if (off0 > sizeof (struct ip)) {
696105bd211SGleb Smirnoff 			ip_stripoptions(m);
697fb59c426SYoshinobu Inoue 			off0 = sizeof(struct ip);
698fb59c426SYoshinobu Inoue 		}
699df8bae1dSRodney W. Grimes 		if (m->m_len < sizeof (struct tcpiphdr)) {
7004dfdffe9SAndre Oppermann 			if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
7014dfdffe9SAndre Oppermann 			    == NULL) {
70278b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvshort);
7038f5a8818SKevin Lo 				return (IPPROTO_DONE);
704df8bae1dSRodney W. Grimes 			}
705df8bae1dSRodney W. Grimes 		}
706fb59c426SYoshinobu Inoue 		ip = mtod(m, struct ip *);
707db4f9cc7SJonathan Lemon 		th = (struct tcphdr *)((caddr_t)ip + off0);
7088ad458a4SGleb Smirnoff 		tlen = ntohs(ip->ip_len) - off0;
709df8bae1dSRodney W. Grimes 
7101d7ee746SKurt Lidl 		iptos = ip->ip_tos;
7119e644c23SMichael Tuexen 		if (port)
7129e644c23SMichael Tuexen 			goto skip_csum;
713db4f9cc7SJonathan Lemon 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
714db4f9cc7SJonathan Lemon 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
715db4f9cc7SJonathan Lemon 				th->th_sum = m->m_pkthdr.csum_data;
716db4f9cc7SJonathan Lemon 			else
717db4f9cc7SJonathan Lemon 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
718c068736aSJeffrey Hsu 				    ip->ip_dst.s_addr,
7198f134647SGleb Smirnoff 				    htonl(m->m_pkthdr.csum_data + tlen +
720c068736aSJeffrey Hsu 				    IPPROTO_TCP));
721db4f9cc7SJonathan Lemon 			th->th_sum ^= 0xffff;
722db4f9cc7SJonathan Lemon 		} else {
7238f134647SGleb Smirnoff 			struct ipovly *ipov = (struct ipovly *)ip;
7248f134647SGleb Smirnoff 
725df8bae1dSRodney W. Grimes 			/*
726df8bae1dSRodney W. Grimes 			 * Checksum extended TCP header and data.
727df8bae1dSRodney W. Grimes 			 */
7288f134647SGleb Smirnoff 			len = off0 + tlen;
729c4556b2fSAndrey V. Elsukov 			ipttl = ip->ip_ttl;
730fb59c426SYoshinobu Inoue 			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
7318f134647SGleb Smirnoff 			ipov->ih_len = htons(tlen);
732fb59c426SYoshinobu Inoue 			th->th_sum = in_cksum(m, len);
73357f60867SMark Johnston 			/* Reset length for SDT probes. */
7341d7ee746SKurt Lidl 			ip->ip_len = htons(len);
7351d7ee746SKurt Lidl 			/* Reset TOS bits */
7361d7ee746SKurt Lidl 			ip->ip_tos = iptos;
7371d7ee746SKurt Lidl 			/* Re-initialization for later version check */
738c4556b2fSAndrey V. Elsukov 			ip->ip_ttl = ipttl;
7391d7ee746SKurt Lidl 			ip->ip_v = IPVERSION;
740b2fe54bcSAndrey V. Elsukov 			ip->ip_hl = off0 >> 2;
741db4f9cc7SJonathan Lemon 		}
7429e644c23SMichael Tuexen 	skip_csum:
7439e644c23SMichael Tuexen 		if (th->th_sum && (port == 0)) {
74478b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvbadsum);
745df8bae1dSRodney W. Grimes 			goto drop;
746df8bae1dSRodney W. Grimes 		}
747713264f6SMark Johnston 		KASSERT(ip->ip_dst.s_addr != INADDR_ANY,
748713264f6SMark Johnston 		    ("%s: unspecified destination v4 address", __func__));
749713264f6SMark Johnston 		if (__predict_false(ip->ip_src.s_addr == INADDR_ANY)) {
75078e6c3aaSGleb Smirnoff 			IPSTAT_INC(ips_badaddr);
751713264f6SMark Johnston 			goto drop;
752713264f6SMark Johnston 		}
753fb59c426SYoshinobu Inoue 	}
754b287c6c7SBjoern A. Zeeb #endif /* INET */
755df8bae1dSRodney W. Grimes 
756df8bae1dSRodney W. Grimes 	/*
757df8bae1dSRodney W. Grimes 	 * Check that TCP offset makes sense,
758df8bae1dSRodney W. Grimes 	 * pull out TCP options and adjust length.		XXX
759df8bae1dSRodney W. Grimes 	 */
760fb59c426SYoshinobu Inoue 	off = th->th_off << 2;
761df8bae1dSRodney W. Grimes 	if (off < sizeof (struct tcphdr) || off > tlen) {
76278b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvbadoff);
763df8bae1dSRodney W. Grimes 		goto drop;
764df8bae1dSRodney W. Grimes 	}
765fb59c426SYoshinobu Inoue 	tlen -= off;	/* tlen is used instead of ti->ti_len */
766df8bae1dSRodney W. Grimes 	if (off > sizeof (struct tcphdr)) {
76704d3a452SHajimu UMEMOTO #ifdef INET6
768b287c6c7SBjoern A. Zeeb 		if (isipv6) {
769a4adf6ccSBjoern A. Zeeb 			if (m->m_len < off0 + off) {
7704e619b17SBjoern A. Zeeb 				m = m_pullup(m, off0 + off);
7714e619b17SBjoern A. Zeeb 				if (m == NULL) {
7724e619b17SBjoern A. Zeeb 					TCPSTAT_INC(tcps_rcvshort);
7734e619b17SBjoern A. Zeeb 					return (IPPROTO_DONE);
7744e619b17SBjoern A. Zeeb 				}
775a4adf6ccSBjoern A. Zeeb 			}
776fb59c426SYoshinobu Inoue 			ip6 = mtod(m, struct ip6_hdr *);
777fb59c426SYoshinobu Inoue 			th = (struct tcphdr *)((caddr_t)ip6 + off0);
778b287c6c7SBjoern A. Zeeb 		}
77904d3a452SHajimu UMEMOTO #endif
780b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
781b287c6c7SBjoern A. Zeeb 		else
782b287c6c7SBjoern A. Zeeb #endif
783b287c6c7SBjoern A. Zeeb #ifdef INET
784b287c6c7SBjoern A. Zeeb 		{
785df8bae1dSRodney W. Grimes 			if (m->m_len < sizeof(struct ip) + off) {
786c068736aSJeffrey Hsu 				if ((m = m_pullup(m, sizeof (struct ip) + off))
7874dfdffe9SAndre Oppermann 				    == NULL) {
78878b50714SRobert Watson 					TCPSTAT_INC(tcps_rcvshort);
7898f5a8818SKevin Lo 					return (IPPROTO_DONE);
790df8bae1dSRodney W. Grimes 				}
791fb59c426SYoshinobu Inoue 				ip = mtod(m, struct ip *);
792fb59c426SYoshinobu Inoue 				th = (struct tcphdr *)((caddr_t)ip + off0);
793fb59c426SYoshinobu Inoue 			}
794df8bae1dSRodney W. Grimes 		}
795b287c6c7SBjoern A. Zeeb #endif
796df8bae1dSRodney W. Grimes 		optlen = off - sizeof (struct tcphdr);
797fb59c426SYoshinobu Inoue 		optp = (u_char *)(th + 1);
798df8bae1dSRodney W. Grimes 	}
7991ebf4607SRichard Scheffenegger 	thflags = tcp_get_flags(th);
800df8bae1dSRodney W. Grimes 
801e46cd3d4SDag-Erling Smørgrav 	/*
802df8bae1dSRodney W. Grimes 	 * Convert TCP protocol specific fields to host format.
803df8bae1dSRodney W. Grimes 	 */
8042903309aSAttilio Rao 	tcp_fields_to_host(th);
805df8bae1dSRodney W. Grimes 
806df8bae1dSRodney W. Grimes 	/*
807794235b7SAndre Oppermann 	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
808755c1f07SAndras Olah 	 */
809fb59c426SYoshinobu Inoue 	drop_hdrlen = off0 + off;
810755c1f07SAndras Olah 
811755c1f07SAndras Olah 	/*
8128d573cc1SAndre Oppermann 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
8138d573cc1SAndre Oppermann 	 */
814b8056faeSGleb Smirnoff         if (
815b8056faeSGleb Smirnoff #ifdef INET6
816b8056faeSGleb Smirnoff 	    (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
817b8056faeSGleb Smirnoff #ifdef INET
818b8056faeSGleb Smirnoff 	    || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
819b8056faeSGleb Smirnoff #endif
820b8056faeSGleb Smirnoff #endif
821b8056faeSGleb Smirnoff #if defined(INET) && !defined(INET6)
822b8056faeSGleb Smirnoff 	    (m->m_flags & M_IP_NEXTHOP)
823b8056faeSGleb Smirnoff #endif
824b8056faeSGleb Smirnoff 	    )
8259b932e9eSAndre Oppermann 		fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
8269b932e9eSAndre Oppermann 
82708d9c920SGleb Smirnoff 	/*
8281db08fbeSGleb Smirnoff 	 * For initial SYN packets we don't need write lock on matching
8291db08fbeSGleb Smirnoff 	 * PCB, be it a listening one or a synchronized one.  The packet
8301db08fbeSGleb Smirnoff 	 * shall not modify its state.
83108d9c920SGleb Smirnoff 	 */
832d88eb465SGleb Smirnoff 	lookupflag = INPLOOKUP_WILDCARD |
833d88eb465SGleb Smirnoff 	    ((thflags & (TH_ACK|TH_SYN)) == TH_SYN ?
834d88eb465SGleb Smirnoff 	    INPLOOKUP_RLOCKPCB : INPLOOKUP_WLOCKPCB);
835ce7ad664SEd Maste findpcb:
8368a006adbSBjoern A. Zeeb #ifdef INET6
8378a006adbSBjoern A. Zeeb 	if (isipv6 && fwd_tag != NULL) {
8388a006adbSBjoern A. Zeeb 		struct sockaddr_in6 *next_hop6;
8398a006adbSBjoern A. Zeeb 
8408a006adbSBjoern A. Zeeb 		next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
8418a006adbSBjoern A. Zeeb 		/*
8428a006adbSBjoern A. Zeeb 		 * Transparently forwarded. Pretend to be the destination.
8438a006adbSBjoern A. Zeeb 		 * Already got one like this?
8448a006adbSBjoern A. Zeeb 		 */
8458a006adbSBjoern A. Zeeb 		inp = in6_pcblookup_mbuf(&V_tcbinfo,
8468a006adbSBjoern A. Zeeb 		    &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
847aab8c844SGleb Smirnoff 		    lookupflag & ~INPLOOKUP_WILDCARD, m->m_pkthdr.rcvif, m);
8488a006adbSBjoern A. Zeeb 		if (!inp) {
8498a006adbSBjoern A. Zeeb 			/*
8508a006adbSBjoern A. Zeeb 			 * It's new.  Try to find the ambushing socket.
8518a006adbSBjoern A. Zeeb 			 * Because we've rewritten the destination address,
8528a006adbSBjoern A. Zeeb 			 * any hardware-generated hash is ignored.
8538a006adbSBjoern A. Zeeb 			 */
8548a006adbSBjoern A. Zeeb 			inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
8558a006adbSBjoern A. Zeeb 			    th->th_sport, &next_hop6->sin6_addr,
8568a006adbSBjoern A. Zeeb 			    next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
857d88eb465SGleb Smirnoff 			    th->th_dport, lookupflag, m->m_pkthdr.rcvif);
8588a006adbSBjoern A. Zeeb 		}
859c1de64a4SAndrey V. Elsukov 	} else if (isipv6) {
8608a006adbSBjoern A. Zeeb 		inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
861d88eb465SGleb Smirnoff 		    th->th_sport, &ip6->ip6_dst, th->th_dport, lookupflag,
862d88eb465SGleb Smirnoff 		    m->m_pkthdr.rcvif, m);
8638a006adbSBjoern A. Zeeb 	}
8648a006adbSBjoern A. Zeeb #endif /* INET6 */
8658a006adbSBjoern A. Zeeb #if defined(INET6) && defined(INET)
8668a006adbSBjoern A. Zeeb 	else
8678a006adbSBjoern A. Zeeb #endif
8688a006adbSBjoern A. Zeeb #ifdef INET
8698a006adbSBjoern A. Zeeb 	if (fwd_tag != NULL) {
8709b932e9eSAndre Oppermann 		struct sockaddr_in *next_hop;
8719b932e9eSAndre Oppermann 
8729b932e9eSAndre Oppermann 		next_hop = (struct sockaddr_in *)(fwd_tag+1);
873f9e354dfSJulian Elischer 		/*
8742b25acc1SLuigi Rizzo 		 * Transparently forwarded. Pretend to be the destination.
875f9e354dfSJulian Elischer 		 * already got one like this?
876f9e354dfSJulian Elischer 		 */
877d3c1f003SRobert Watson 		inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
878aab8c844SGleb Smirnoff 		    ip->ip_dst, th->th_dport, lookupflag & ~INPLOOKUP_WILDCARD,
879aab8c844SGleb Smirnoff 		    m->m_pkthdr.rcvif, m);
880fa046d87SRobert Watson 		if (!inp) {
881fa046d87SRobert Watson 			/*
882fa046d87SRobert Watson 			 * It's new.  Try to find the ambushing socket.
883d3c1f003SRobert Watson 			 * Because we've rewritten the destination address,
884d3c1f003SRobert Watson 			 * any hardware-generated hash is ignored.
885fa046d87SRobert Watson 			 */
886fa046d87SRobert Watson 			inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
887fa046d87SRobert Watson 			    th->th_sport, next_hop->sin_addr,
888fa046d87SRobert Watson 			    next_hop->sin_port ? ntohs(next_hop->sin_port) :
889d88eb465SGleb Smirnoff 			    th->th_dport, lookupflag, m->m_pkthdr.rcvif);
890f9e354dfSJulian Elischer 		}
891b10fbdeaSAndre Oppermann 	} else
892d3c1f003SRobert Watson 		inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
893d88eb465SGleb Smirnoff 		    th->th_sport, ip->ip_dst, th->th_dport, lookupflag,
894d88eb465SGleb Smirnoff 		    m->m_pkthdr.rcvif, m);
8958a006adbSBjoern A. Zeeb #endif /* INET */
896f9e354dfSJulian Elischer 
897df8bae1dSRodney W. Grimes 	/*
898574b6964SAndre Oppermann 	 * If the INPCB does not exist then all data in the incoming
899574b6964SAndre Oppermann 	 * segment is discarded and an appropriate RST is sent back.
9008b07e49aSJulian Elischer 	 * XXX MRT Send RST using which routing table?
901df8bae1dSRodney W. Grimes 	 */
902816a3d83SPoul-Henning Kamp 	if (inp == NULL) {
903d88eb465SGleb Smirnoff 		if (rstreason != 0) {
904d88eb465SGleb Smirnoff 			/* We came here after second (safety) lookup. */
905d88eb465SGleb Smirnoff 			MPASS((lookupflag & INPLOOKUP_WILDCARD) == 0);
906d88eb465SGleb Smirnoff 			goto dropwithreset;
907d88eb465SGleb Smirnoff 		}
908574b6964SAndre Oppermann 		/*
909574b6964SAndre Oppermann 		 * Log communication attempts to ports that are not
910574b6964SAndre Oppermann 		 * in use.
911574b6964SAndre Oppermann 		 */
912334fc582SBjoern A. Zeeb 		if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
913334fc582SBjoern A. Zeeb 		    V_tcp_log_in_vain == 2) {
914b7d747ecSAndre Oppermann 			if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
915df541e5fSAndre Oppermann 				log(LOG_INFO, "%s; %s: Connection attempt "
916df541e5fSAndre Oppermann 				    "to closed port\n", s, __func__);
9172e4e1b4cSGeoff Rehmet 		}
918574b6964SAndre Oppermann 		/*
919574b6964SAndre Oppermann 		 * When blackholing do not respond with a RST but
920574b6964SAndre Oppermann 		 * completely ignore the segment and drop it.
921574b6964SAndre Oppermann 		 */
9223ea9a7cfSGleb Smirnoff 		if (((V_blackhole == 1 && (thflags & TH_SYN)) ||
923ad3ad064SGleb Smirnoff 		    V_blackhole == 2) && (V_blackhole_local || (
9243ea9a7cfSGleb Smirnoff #ifdef INET6
9253ea9a7cfSGleb Smirnoff 		    isipv6 ? !in6_localaddr(&ip6->ip6_src) :
9263ea9a7cfSGleb Smirnoff #endif
9273ea9a7cfSGleb Smirnoff #ifdef INET
9283ea9a7cfSGleb Smirnoff 		    !in_localip(ip->ip_src)
9293ea9a7cfSGleb Smirnoff #else
9303ea9a7cfSGleb Smirnoff 		    true
9313ea9a7cfSGleb Smirnoff #endif
932ad3ad064SGleb Smirnoff 		    )))
9331929eae1SAndre Oppermann 			goto dropunlock;
934574b6964SAndre Oppermann 
935a57815efSBosko Milekic 		rstreason = BANDLIM_RST_CLOSEDPORT;
936a57815efSBosko Milekic 		goto dropwithreset;
937816a3d83SPoul-Henning Kamp 	}
93808d9c920SGleb Smirnoff 	INP_LOCK_ASSERT(inp);
939f567d55fSGleb Smirnoff 
940c2529042SHans Petter Selasky 	if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
941f71cb9f7SGleb Smirnoff 	    !SOLISTENING(inp->inp_socket)) {
942e5738ee0SCheng Cui 		if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
94380cb9f21SKip Macy 			inp->inp_flowid = m->m_pkthdr.flowid;
9442f719932SAdrian Chadd 			inp->inp_flowtype = M_HASHTYPE_GET(m);
945e5738ee0SCheng Cui #ifdef	RSS
946e5738ee0SCheng Cui 		} else {
947e5738ee0SCheng Cui 			  /* assign flowid by software RSS hash */
948e5738ee0SCheng Cui #ifdef INET6
949e5738ee0SCheng Cui 			  if (isipv6) {
950e5738ee0SCheng Cui 				rss_proto_software_hash_v6(&inp->in6p_faddr,
951e5738ee0SCheng Cui 							   &inp->in6p_laddr,
952e5738ee0SCheng Cui 							   inp->inp_fport,
953e5738ee0SCheng Cui 							   inp->inp_lport,
954e5738ee0SCheng Cui 							   IPPROTO_TCP,
955e5738ee0SCheng Cui 							   &inp->inp_flowid,
956e5738ee0SCheng Cui 							   &inp->inp_flowtype);
957e5738ee0SCheng Cui 			  } else
958e5738ee0SCheng Cui #endif	/* INET6 */
959e5738ee0SCheng Cui 			  {
960e5738ee0SCheng Cui 				rss_proto_software_hash_v4(inp->inp_faddr,
961e5738ee0SCheng Cui 							   inp->inp_laddr,
962e5738ee0SCheng Cui 							   inp->inp_fport,
963e5738ee0SCheng Cui 							   inp->inp_lport,
964e5738ee0SCheng Cui 							   IPPROTO_TCP,
965e5738ee0SCheng Cui 							   &inp->inp_flowid,
966e5738ee0SCheng Cui 							   &inp->inp_flowtype);
967e5738ee0SCheng Cui 			  }
968e5738ee0SCheng Cui #endif	/* RSS */
969e5738ee0SCheng Cui 		}
97080cb9f21SKip Macy 	}
971fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
972a2589465SKen Smith #ifdef INET6
973fcf59617SAndrey V. Elsukov 	if (isipv6 && IPSEC_ENABLED(ipv6) &&
974fcf59617SAndrey V. Elsukov 	    IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
975a2589465SKen Smith 		goto dropunlock;
976a2589465SKen Smith 	}
977fcf59617SAndrey V. Elsukov #ifdef INET
978fcf59617SAndrey V. Elsukov 	else
979fcf59617SAndrey V. Elsukov #endif
980fcf59617SAndrey V. Elsukov #endif /* INET6 */
981fcf59617SAndrey V. Elsukov #ifdef INET
982fcf59617SAndrey V. Elsukov 	if (IPSEC_ENABLED(ipv4) &&
983fcf59617SAndrey V. Elsukov 	    IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
984fcf59617SAndrey V. Elsukov 		goto dropunlock;
985fcf59617SAndrey V. Elsukov 	}
986fcf59617SAndrey V. Elsukov #endif /* INET */
987a2589465SKen Smith #endif /* IPSEC */
988a2589465SKen Smith 
9898d573cc1SAndre Oppermann 	/*
9908d573cc1SAndre Oppermann 	 * Check the minimum TTL for socket.
9918d573cc1SAndre Oppermann 	 */
99234f83c52SGeorge V. Neville-Neil 	if (inp->inp_ip_minttl != 0) {
99334f83c52SGeorge V. Neville-Neil #ifdef INET6
9942d8868dbSJonathan T. Looney 		if (isipv6) {
9952d8868dbSJonathan T. Looney 			if (inp->inp_ip_minttl > ip6->ip6_hlim)
996302ce8d6SAndre Oppermann 				goto dropunlock;
9972d8868dbSJonathan T. Looney 		} else
99834f83c52SGeorge V. Neville-Neil #endif
99934f83c52SGeorge V. Neville-Neil 		if (inp->inp_ip_minttl > ip->ip_ttl)
1000302ce8d6SAndre Oppermann 			goto dropunlock;
100134f83c52SGeorge V. Neville-Neil 	}
1002936cd18dSAndre Oppermann 
10030d744519SGleb Smirnoff 	tp = intotcpcb(inp);
10040d744519SGleb Smirnoff 	switch (tp->t_state) {
10050d744519SGleb Smirnoff 	case TCPS_TIME_WAIT:
1006340c35deSJonathan Lemon 		/*
10070d744519SGleb Smirnoff 		 * A previous connection in TIMEWAIT state is supposed to catch
10080d744519SGleb Smirnoff 		 * stray or duplicate segments arriving late.  If this segment
10090d744519SGleb Smirnoff 		 * was a legitimate new connection attempt, the old INPCB gets
10100d744519SGleb Smirnoff 		 * removed and we can try again to find a listening socket.
1011340c35deSJonathan Lemon 		 */
1012283c76c7SMichael Tuexen 		tcp_dooptions(&to, optp, optlen,
1013283c76c7SMichael Tuexen 		    (thflags & TH_SYN) ? TO_SYN : 0);
10148d573cc1SAndre Oppermann 		/*
10150d744519SGleb Smirnoff 		 * tcp_twcheck unlocks the inp always, and frees the m if fails.
10168d573cc1SAndre Oppermann 		 */
10172104448fSAndre Oppermann 		if (tcp_twcheck(inp, &to, th, m, tlen))
1018340c35deSJonathan Lemon 			goto findpcb;
10198f5a8818SKevin Lo 		return (IPPROTO_DONE);
10200d744519SGleb Smirnoff 	case TCPS_CLOSED:
1021794235b7SAndre Oppermann 		/*
1022794235b7SAndre Oppermann 		 * The TCPCB may no longer exist if the connection is winding
1023794235b7SAndre Oppermann 		 * down or it is in the CLOSED state.  Either way we drop the
1024794235b7SAndre Oppermann 		 * segment and send an appropriate response.
1025794235b7SAndre Oppermann 		 */
1026a57815efSBosko Milekic 		rstreason = BANDLIM_RST_CLOSEDPORT;
1027a57815efSBosko Milekic 		goto dropwithreset;
102809f81a46SBosko Milekic 	}
1029df8bae1dSRodney W. Grimes 
10309e644c23SMichael Tuexen 	if ((tp->t_port != port) && (tp->t_state > TCPS_LISTEN)) {
10319e644c23SMichael Tuexen 		rstreason = BANDLIM_RST_CLOSEDPORT;
10329e644c23SMichael Tuexen 		goto dropwithreset;
10339e644c23SMichael Tuexen 	}
10349e644c23SMichael Tuexen 
103509fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
103609fe6320SNavdeep Parhar 	if (tp->t_flags & TF_TOE) {
103709fe6320SNavdeep Parhar 		tcp_offload_input(tp, m);
103809fe6320SNavdeep Parhar 		m = NULL;	/* consumed by the TOE driver */
103909fe6320SNavdeep Parhar 		goto dropunlock;
104009fe6320SNavdeep Parhar 	}
104109fe6320SNavdeep Parhar #endif
104209fe6320SNavdeep Parhar 
1043c488362eSRobert Watson #ifdef MAC
104430d239bcSRobert Watson 	if (mac_inpcb_check_deliver(inp, m))
1045302ce8d6SAndre Oppermann 		goto dropunlock;
1046c488362eSRobert Watson #endif
1047a557af22SRobert Watson 	so = inp->inp_socket;
1048302ce8d6SAndre Oppermann 	KASSERT(so != NULL, ("%s: so == NULL", __func__));
1049db33b3e6SAndre Oppermann 	/*
1050db33b3e6SAndre Oppermann 	 * When the socket is accepting connections (the INPCB is in LISTEN
1051db33b3e6SAndre Oppermann 	 * state) we look into the SYN cache if this is a new connection
1052a7c7f2a7SJohn Baldwin 	 * attempt or the completion of a previous one.
1053db33b3e6SAndre Oppermann 	 */
1054f4bb1869SMark Johnston 	KASSERT(tp->t_state == TCPS_LISTEN || !SOLISTENING(so),
105545274760SJonathan T. Looney 	    ("%s: so accepting but tp %p not listening", __func__, tp));
1056f4bb1869SMark Johnston 	if (tp->t_state == TCPS_LISTEN && SOLISTENING(so)) {
1057540e8b7eSJeffrey Hsu 		struct in_conninfo inc;
1058540e8b7eSJeffrey Hsu 
10598bfb1918SAndre Oppermann 		bzero(&inc, sizeof(inc));
1060302ce8d6SAndre Oppermann #ifdef INET6
1061be2ac88cSJonathan Lemon 		if (isipv6) {
1062dcdb4371SBjoern A. Zeeb 			inc.inc_flags |= INC_ISIPV6;
10635dff1c38SMichael Tuexen 			if (inp->inp_inc.inc_flags & INC_IPV6MINMTU)
10645dff1c38SMichael Tuexen 				inc.inc_flags |= INC_IPV6MINMTU;
1065be2ac88cSJonathan Lemon 			inc.inc6_faddr = ip6->ip6_src;
1066be2ac88cSJonathan Lemon 			inc.inc6_laddr = ip6->ip6_dst;
1067302ce8d6SAndre Oppermann 		} else
1068302ce8d6SAndre Oppermann #endif
1069302ce8d6SAndre Oppermann 		{
1070be2ac88cSJonathan Lemon 			inc.inc_faddr = ip->ip_src;
1071be2ac88cSJonathan Lemon 			inc.inc_laddr = ip->ip_dst;
1072be2ac88cSJonathan Lemon 		}
1073be2ac88cSJonathan Lemon 		inc.inc_fport = th->th_sport;
1074be2ac88cSJonathan Lemon 		inc.inc_lport = th->th_dport;
10757973fba3SJulian Elischer 		inc.inc_fibnum = so->so_fibnum;
1076be2ac88cSJonathan Lemon 
1077fb59c426SYoshinobu Inoue 		/*
10788d573cc1SAndre Oppermann 		 * Check for an existing connection attempt in syncache if
10798d573cc1SAndre Oppermann 		 * the flag is only ACK.  A successful lookup creates a new
10808d573cc1SAndre Oppermann 		 * socket appended to the listen queue in SYN_RECEIVED state.
1081fb59c426SYoshinobu Inoue 		 */
1082be2ac88cSJonathan Lemon 		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1083bf6d304aSAndre Oppermann 			/*
1084bf6d304aSAndre Oppermann 			 * Parse the TCP options here because
1085bf6d304aSAndre Oppermann 			 * syncookies need access to the reflected
1086bf6d304aSAndre Oppermann 			 * timestamp.
1087bf6d304aSAndre Oppermann 			 */
1088bf6d304aSAndre Oppermann 			tcp_dooptions(&to, optp, optlen, 0);
10899fa198beSAndre Oppermann 			/*
1090e7231d07SGleb Smirnoff 			 * NB: syncache_expand() doesn't unlock inp.
10919fa198beSAndre Oppermann 			 */
10929e644c23SMichael Tuexen 			rstreason = syncache_expand(&inc, &to, th, &so, m, port);
1093fcf59617SAndrey V. Elsukov 			if (rstreason < 0) {
1094fcf59617SAndrey V. Elsukov 				/*
1095fcf59617SAndrey V. Elsukov 				 * A failing TCP MD5 signature comparison
1096fcf59617SAndrey V. Elsukov 				 * must result in the segment being dropped
1097fcf59617SAndrey V. Elsukov 				 * and must not produce any response back
1098fcf59617SAndrey V. Elsukov 				 * to the sender.
1099fcf59617SAndrey V. Elsukov 				 */
1100fcf59617SAndrey V. Elsukov 				goto dropunlock;
1101fcf59617SAndrey V. Elsukov 			} else if (rstreason == 0) {
11024195b4afSPaul Traina 				/*
1103d88eb465SGleb Smirnoff 				 * No syncache entry, or ACK was not for our
1104d88eb465SGleb Smirnoff 				 * SYN/ACK.  Do our protection against double
1105d88eb465SGleb Smirnoff 				 * ACK.  If peer sent us 2 ACKs, then for the
1106d88eb465SGleb Smirnoff 				 * first one syncache_expand() successfully
1107d88eb465SGleb Smirnoff 				 * converted syncache entry into a socket,
1108d88eb465SGleb Smirnoff 				 * while we were waiting on the inpcb lock.  We
1109d88eb465SGleb Smirnoff 				 * don't want to sent RST for the second ACK,
1110d88eb465SGleb Smirnoff 				 * so we perform second lookup without wildcard
1111d88eb465SGleb Smirnoff 				 * match, hoping to find the new socket.  If
1112d88eb465SGleb Smirnoff 				 * the ACK is stray indeed, rstreason would
1113d88eb465SGleb Smirnoff 				 * hint the above code that the lookup was a
1114d88eb465SGleb Smirnoff 				 * second attempt.
1115d88eb465SGleb Smirnoff 				 *
11168d573cc1SAndre Oppermann 				 * NB: syncache did its own logging
11178d573cc1SAndre Oppermann 				 * of the failure cause.
11184195b4afSPaul Traina 				 */
1119d88eb465SGleb Smirnoff 				INP_WUNLOCK(inp);
1120be2ac88cSJonathan Lemon 				rstreason = BANDLIM_RST_OPENPORT;
1121d88eb465SGleb Smirnoff 				lookupflag &= ~INPLOOKUP_WILDCARD;
1122d88eb465SGleb Smirnoff 				goto findpcb;
1123be2ac88cSJonathan Lemon 			}
112409c305ebSPatrick Kelsey tfo_socket_result:
1125f76fcf6dSJeffrey Hsu 			if (so == NULL) {
1126be2ac88cSJonathan Lemon 				/*
1127e207f800SAndre Oppermann 				 * We completed the 3-way handshake
1128e207f800SAndre Oppermann 				 * but could not allocate a socket
1129e207f800SAndre Oppermann 				 * either due to memory shortage,
1130e207f800SAndre Oppermann 				 * listen queue length limits or
1131a160e630SAndre Oppermann 				 * global socket limits.  Send RST
1132a160e630SAndre Oppermann 				 * or wait and have the remote end
1133a160e630SAndre Oppermann 				 * retransmit the ACK for another
1134a160e630SAndre Oppermann 				 * try.
1135be2ac88cSJonathan Lemon 				 */
1136a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1137a160e630SAndre Oppermann 					log(LOG_DEBUG, "%s; %s: Listen socket: "
11388d573cc1SAndre Oppermann 					    "Socket allocation failed due to "
11398d573cc1SAndre Oppermann 					    "limits or memory shortage, %s\n",
1140ac957cd2SJulian Elischer 					    s, __func__,
1141ac957cd2SJulian Elischer 					    V_tcp_sc_rst_sock_fail ?
1142ac957cd2SJulian Elischer 					    "sending RST" : "try again");
1143603724d3SBjoern A. Zeeb 				if (V_tcp_sc_rst_sock_fail) {
1144e207f800SAndre Oppermann 					rstreason = BANDLIM_UNLIMITED;
1145e207f800SAndre Oppermann 					goto dropwithreset;
1146a160e630SAndre Oppermann 				} else
1147a160e630SAndre Oppermann 					goto dropunlock;
1148f76fcf6dSJeffrey Hsu 			}
1149be2ac88cSJonathan Lemon 			/*
1150be2ac88cSJonathan Lemon 			 * Socket is created in state SYN_RECEIVED.
11518d573cc1SAndre Oppermann 			 * Unlock the listen socket, lock the newly
11528d573cc1SAndre Oppermann 			 * created socket and update the tp variable.
115308d9c920SGleb Smirnoff 			 * If we came here via jump to tfo_socket_result,
115408d9c920SGleb Smirnoff 			 * then listening socket is read-locked.
1155be2ac88cSJonathan Lemon 			 */
115608d9c920SGleb Smirnoff 			INP_UNLOCK(inp);	/* listen socket */
1157be2ac88cSJonathan Lemon 			inp = sotoinpcb(so);
1158ff9b006dSJulien Charbon 			/*
1159ff9b006dSJulien Charbon 			 * New connection inpcb is already locked by
1160ff9b006dSJulien Charbon 			 * syncache_expand().
1161ff9b006dSJulien Charbon 			 */
1162ff9b006dSJulien Charbon 			INP_WLOCK_ASSERT(inp);
1163be2ac88cSJonathan Lemon 			tp = intotcpcb(inp);
11648d573cc1SAndre Oppermann 			KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
11658d573cc1SAndre Oppermann 			    ("%s: ", __func__));
1166be2ac88cSJonathan Lemon 			/*
1167302ce8d6SAndre Oppermann 			 * Process the segment and the data it
1168302ce8d6SAndre Oppermann 			 * contains.  tcp_do_segment() consumes
1169302ce8d6SAndre Oppermann 			 * the mbuf chain and unlocks the inpcb.
1170302ce8d6SAndre Oppermann 			 */
11716138da62SMichael Tuexen 			TCP_PROBE5(receive, NULL, tp, m, tp, th);
117235bc0bccSGleb Smirnoff 			tp->t_fb->tfb_tcp_do_segment(tp, m, th, drop_hdrlen,
117335bc0bccSGleb Smirnoff 			    tlen, iptos);
11748f5a8818SKevin Lo 			return (IPPROTO_DONE);
1175be2ac88cSJonathan Lemon 		}
1176a160e630SAndre Oppermann 		/*
11778d573cc1SAndre Oppermann 		 * Segment flag validation for new connection attempts:
11788d573cc1SAndre Oppermann 		 *
1179a160e630SAndre Oppermann 		 * Our (SYN|ACK) response was rejected.
1180a160e630SAndre Oppermann 		 * Check with syncache and remove entry to prevent
1181a160e630SAndre Oppermann 		 * retransmits.
118219bc77c5SAndre Oppermann 		 *
118319bc77c5SAndre Oppermann 		 * NB: syncache_chkrst does its own logging of failure
118419bc77c5SAndre Oppermann 		 * causes.
1185a160e630SAndre Oppermann 		 */
1186a160e630SAndre Oppermann 		if (thflags & TH_RST) {
11879e644c23SMichael Tuexen 			syncache_chkrst(&inc, th, m, port);
1188a160e630SAndre Oppermann 			goto dropunlock;
1189a160e630SAndre Oppermann 		}
1190a160e630SAndre Oppermann 		/*
1191a160e630SAndre Oppermann 		 * We can't do anything without SYN.
1192a160e630SAndre Oppermann 		 */
1193a160e630SAndre Oppermann 		if ((thflags & TH_SYN) == 0) {
1194a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1195a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
1196773673c1SAndre Oppermann 				    "SYN is missing, segment ignored\n",
11978d573cc1SAndre Oppermann 				    s, __func__);
119878b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1199a160e630SAndre Oppermann 			goto dropunlock;
1200a160e630SAndre Oppermann 		}
1201a160e630SAndre Oppermann 		/*
1202a160e630SAndre Oppermann 		 * (SYN|ACK) is bogus on a listen socket.
1203a160e630SAndre Oppermann 		 */
1204fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK) {
1205a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1206a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
12078d573cc1SAndre Oppermann 				    "SYN|ACK invalid, segment rejected\n",
12088d573cc1SAndre Oppermann 				    s, __func__);
12099e644c23SMichael Tuexen 			syncache_badack(&inc, port);	/* XXX: Not needed! */
121078b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1211a57815efSBosko Milekic 			rstreason = BANDLIM_RST_OPENPORT;
1212a57815efSBosko Milekic 			goto dropwithreset;
12134195b4afSPaul Traina 		}
1214a160e630SAndre Oppermann 		/*
1215a160e630SAndre Oppermann 		 * If the drop_synfin option is enabled, drop all
1216a160e630SAndre Oppermann 		 * segments with both the SYN and FIN bits set.
1217a160e630SAndre Oppermann 		 * This prevents e.g. nmap from identifying the
1218a160e630SAndre Oppermann 		 * TCP/IP stack.
1219a160e630SAndre Oppermann 		 * XXX: Poor reasoning.  nmap has other methods
1220a160e630SAndre Oppermann 		 * and is constantly refining its stack detection
1221a160e630SAndre Oppermann 		 * strategies.
12228d573cc1SAndre Oppermann 		 * XXX: This is a violation of the TCP specification
1223a160e630SAndre Oppermann 		 * and was used by RFC1644.
1224a160e630SAndre Oppermann 		 */
1225603724d3SBjoern A. Zeeb 		if ((thflags & TH_FIN) && V_drop_synfin) {
1226a160e630SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1227a160e630SAndre Oppermann 				log(LOG_DEBUG, "%s; %s: Listen socket: "
1228773673c1SAndre Oppermann 				    "SYN|FIN segment ignored (based on "
12298d573cc1SAndre Oppermann 				    "sysctl setting)\n", s, __func__);
123078b50714SRobert Watson 			TCPSTAT_INC(tcps_badsyn);
1231302ce8d6SAndre Oppermann 			goto dropunlock;
1232ebb0cbeaSPaul Traina 		}
1233be2ac88cSJonathan Lemon 		/*
1234be2ac88cSJonathan Lemon 		 * Segment's flags are (SYN) or (SYN|FIN).
1235a160e630SAndre Oppermann 		 *
1236a160e630SAndre Oppermann 		 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1237a160e630SAndre Oppermann 		 * as they do not affect the state of the TCP FSM.
1238a160e630SAndre Oppermann 		 * The data pointed to by TH_URG and th_urp is ignored.
1239be2ac88cSJonathan Lemon 		 */
1240a160e630SAndre Oppermann 		KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1241a160e630SAndre Oppermann 		    ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1242a160e630SAndre Oppermann 		KASSERT(thflags & (TH_SYN),
1243a160e630SAndre Oppermann 		    ("%s: Listen socket: TH_SYN not set", __func__));
124408d9c920SGleb Smirnoff 		INP_RLOCK_ASSERT(inp);
124533841545SHajimu UMEMOTO #ifdef INET6
124633841545SHajimu UMEMOTO 		/*
124733841545SHajimu UMEMOTO 		 * If deprecated address is forbidden,
124833841545SHajimu UMEMOTO 		 * we do not accept SYN to deprecated interface
124933841545SHajimu UMEMOTO 		 * address to prevent any new inbound connection from
125033841545SHajimu UMEMOTO 		 * getting established.
125133841545SHajimu UMEMOTO 		 * When we do not accept SYN, we send a TCP RST,
125233841545SHajimu UMEMOTO 		 * with deprecated source address (instead of dropping
125333841545SHajimu UMEMOTO 		 * it).  We compromise it as it is much better for peer
125433841545SHajimu UMEMOTO 		 * to send a RST, and RST will be the final packet
125533841545SHajimu UMEMOTO 		 * for the exchange.
125633841545SHajimu UMEMOTO 		 *
125733841545SHajimu UMEMOTO 		 * If we do not forbid deprecated addresses, we accept
125833841545SHajimu UMEMOTO 		 * the SYN packet.  RFC2462 does not suggest dropping
125933841545SHajimu UMEMOTO 		 * SYN in this case.
126033841545SHajimu UMEMOTO 		 * If we decipher RFC2462 5.5.4, it says like this:
126133841545SHajimu UMEMOTO 		 * 1. use of deprecated addr with existing
126233841545SHajimu UMEMOTO 		 *    communication is okay - "SHOULD continue to be
126333841545SHajimu UMEMOTO 		 *    used"
126433841545SHajimu UMEMOTO 		 * 2. use of it with new communication:
126533841545SHajimu UMEMOTO 		 *   (2a) "SHOULD NOT be used if alternate address
126633841545SHajimu UMEMOTO 		 *        with sufficient scope is available"
126733841545SHajimu UMEMOTO 		 *   (2b) nothing mentioned otherwise.
126833841545SHajimu UMEMOTO 		 * Here we fall into (2b) case as we have no choice in
126933841545SHajimu UMEMOTO 		 * our source address selection - we must obey the peer.
127033841545SHajimu UMEMOTO 		 *
127133841545SHajimu UMEMOTO 		 * The wording in RFC2462 is confusing, and there are
127233841545SHajimu UMEMOTO 		 * multiple description text for deprecated address
127333841545SHajimu UMEMOTO 		 * handling - worse, they are not exactly the same.
127433841545SHajimu UMEMOTO 		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
127533841545SHajimu UMEMOTO 		 */
1276603724d3SBjoern A. Zeeb 		if (isipv6 && !V_ip6_use_deprecated) {
127733841545SHajimu UMEMOTO 			struct in6_ifaddr *ia6;
127833841545SHajimu UMEMOTO 
12798268d82cSAlexander V. Chernikov 			ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
12808c0fec80SRobert Watson 			if (ia6 != NULL &&
128133841545SHajimu UMEMOTO 			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1282a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1283a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
12848d573cc1SAndre Oppermann 					"Connection attempt to deprecated "
12858d573cc1SAndre Oppermann 					"IPv6 address rejected\n",
1286a160e630SAndre Oppermann 					s, __func__);
128733841545SHajimu UMEMOTO 				rstreason = BANDLIM_RST_OPENPORT;
128833841545SHajimu UMEMOTO 				goto dropwithreset;
128933841545SHajimu UMEMOTO 			}
129033841545SHajimu UMEMOTO 		}
1291b287c6c7SBjoern A. Zeeb #endif /* INET6 */
129265f28919SJesper Skriver 		/*
1293db33b3e6SAndre Oppermann 		 * Basic sanity checks on incoming SYN requests:
12948d573cc1SAndre Oppermann 		 *   Don't respond if the destination is a link layer
1295db33b3e6SAndre Oppermann 		 *	broadcast according to RFC1122 4.2.3.10, p. 104.
12968d573cc1SAndre Oppermann 		 *   If it is from this socket it must be forged.
12978d573cc1SAndre Oppermann 		 *   Don't respond if the source or destination is a
12988d573cc1SAndre Oppermann 		 *	global or subnet broad- or multicast address.
129993ec91baSCrist J. Clark 		 *   Note that it is quite possible to receive unicast
130093ec91baSCrist J. Clark 		 *	link-layer packets with a broadcast IP address. Use
130193ec91baSCrist J. Clark 		 *	in_broadcast() to find them.
1302be2ac88cSJonathan Lemon 		 */
13038d573cc1SAndre Oppermann 		if (m->m_flags & (M_BCAST|M_MCAST)) {
13048d573cc1SAndre Oppermann 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
13058d573cc1SAndre Oppermann 			    log(LOG_DEBUG, "%s; %s: Listen socket: "
13068d573cc1SAndre Oppermann 				"Connection attempt from broad- or multicast "
1307773673c1SAndre Oppermann 				"link layer address ignored\n", s, __func__);
1308302ce8d6SAndre Oppermann 			goto dropunlock;
13098d573cc1SAndre Oppermann 		}
1310db33b3e6SAndre Oppermann #ifdef INET6
1311b287c6c7SBjoern A. Zeeb 		if (isipv6) {
1312db33b3e6SAndre Oppermann 			if (th->th_dport == th->th_sport &&
1313a160e630SAndre Oppermann 			    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1314a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1315a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13168d573cc1SAndre Oppermann 					"Connection attempt to/from self "
1317773673c1SAndre Oppermann 					"ignored\n", s, __func__);
1318302ce8d6SAndre Oppermann 				goto dropunlock;
1319a160e630SAndre Oppermann 			}
1320be2ac88cSJonathan Lemon 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1321a160e630SAndre Oppermann 			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1322a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1323a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13248d573cc1SAndre Oppermann 					"Connection attempt from/to multicast "
1325773673c1SAndre Oppermann 					"address ignored\n", s, __func__);
1326302ce8d6SAndre Oppermann 				goto dropunlock;
1327a160e630SAndre Oppermann 			}
1328b287c6c7SBjoern A. Zeeb 		}
1329db33b3e6SAndre Oppermann #endif
1330b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
1331b287c6c7SBjoern A. Zeeb 		else
1332b287c6c7SBjoern A. Zeeb #endif
1333b287c6c7SBjoern A. Zeeb #ifdef INET
1334b287c6c7SBjoern A. Zeeb 		{
1335db33b3e6SAndre Oppermann 			if (th->th_dport == th->th_sport &&
1336a160e630SAndre Oppermann 			    ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1337a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1338a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13398d573cc1SAndre Oppermann 					"Connection attempt from/to self "
1340773673c1SAndre Oppermann 					"ignored\n", s, __func__);
1341302ce8d6SAndre Oppermann 				goto dropunlock;
1342a160e630SAndre Oppermann 			}
1343be2ac88cSJonathan Lemon 			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1344be2ac88cSJonathan Lemon 			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
13452ca2159fSCrist J. Clark 			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1346a160e630SAndre Oppermann 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1347a160e630SAndre Oppermann 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1348a160e630SAndre Oppermann 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
13498d573cc1SAndre Oppermann 					"Connection attempt from/to broad- "
1350773673c1SAndre Oppermann 					"or multicast address ignored\n",
1351a160e630SAndre Oppermann 					s, __func__);
1352302ce8d6SAndre Oppermann 				goto dropunlock;
1353c068736aSJeffrey Hsu 			}
1354a160e630SAndre Oppermann 		}
1355b287c6c7SBjoern A. Zeeb #endif
1356be2ac88cSJonathan Lemon 		/*
1357db33b3e6SAndre Oppermann 		 * SYN appears to be valid.  Create compressed TCP state
1358db33b3e6SAndre Oppermann 		 * for syncache.
1359be2ac88cSJonathan Lemon 		 */
13602b9c9984SGeorge V. Neville-Neil 		TCP_PROBE3(debug__input, tp, th, m);
1361f72167f4SAndre Oppermann 		tcp_dooptions(&to, optp, optlen, TO_SYN);
13628d5719aaSGleb Smirnoff 		if ((so = syncache_add(&inc, &to, th, inp, so, m, NULL, NULL,
13639e644c23SMichael Tuexen 		    iptos, port)) != NULL)
136409c305ebSPatrick Kelsey 			goto tfo_socket_result;
136518a75309SPatrick Kelsey 
1366be2ac88cSJonathan Lemon 		/*
13674d6e7130SAndre Oppermann 		 * Entry added to syncache and mbuf consumed.
1368a7c7f2a7SJohn Baldwin 		 * Only the listen socket is unlocked by syncache_add().
1369be2ac88cSJonathan Lemon 		 */
13708f5a8818SKevin Lo 		return (IPPROTO_DONE);
1371982c1675SAndre Oppermann 	} else if (tp->t_state == TCPS_LISTEN) {
1372982c1675SAndre Oppermann 		/*
1373982c1675SAndre Oppermann 		 * When a listen socket is torn down the SO_ACCEPTCONN
1374982c1675SAndre Oppermann 		 * flag is removed first while connections are drained
1375982c1675SAndre Oppermann 		 * from the accept queue in a unlock/lock cycle of the
1376982c1675SAndre Oppermann 		 * ACCEPT_LOCK, opening a race condition allowing a SYN
1377982c1675SAndre Oppermann 		 * attempt go through unhandled.
1378982c1675SAndre Oppermann 		 */
1379982c1675SAndre Oppermann 		goto dropunlock;
1380f76fcf6dSJeffrey Hsu 	}
1381fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1382fcf59617SAndrey V. Elsukov 	if (tp->t_flags & TF_SIGNATURE) {
1383fcf59617SAndrey V. Elsukov 		tcp_dooptions(&to, optp, optlen, thflags);
1384fcf59617SAndrey V. Elsukov 		if ((to.to_flags & TOF_SIGNATURE) == 0) {
1385fcf59617SAndrey V. Elsukov 			TCPSTAT_INC(tcps_sig_err_nosigopt);
13862903309aSAttilio Rao 			goto dropunlock;
13872903309aSAttilio Rao 		}
1388fcf59617SAndrey V. Elsukov 		if (!TCPMD5_ENABLED() ||
1389fcf59617SAndrey V. Elsukov 		    TCPMD5_INPUT(m, th, to.to_signature) != 0)
1390fcf59617SAndrey V. Elsukov 			goto dropunlock;
13912903309aSAttilio Rao 	}
13922903309aSAttilio Rao #endif
13932b9c9984SGeorge V. Neville-Neil 	TCP_PROBE5(receive, NULL, tp, m, tp, th);
139457f60867SMark Johnston 
1395302ce8d6SAndre Oppermann 	/*
13968d573cc1SAndre Oppermann 	 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
13978d573cc1SAndre Oppermann 	 * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
13988d573cc1SAndre Oppermann 	 * the inpcb, and unlocks pcbinfo.
13991db08fbeSGleb Smirnoff 	 *
14001db08fbeSGleb Smirnoff 	 * XXXGL: in case of a pure SYN arriving on existing connection
14011db08fbeSGleb Smirnoff 	 * TCP stacks won't need to modify the PCB, they would either drop
14021db08fbeSGleb Smirnoff 	 * the segment silently, or send a challenge ACK.  However, we try
14031db08fbeSGleb Smirnoff 	 * to upgrade the lock, because calling convention for stacks is
14041db08fbeSGleb Smirnoff 	 * write-lock on PCB.  If upgrade fails, drop the SYN.
1405302ce8d6SAndre Oppermann 	 */
1406d88eb465SGleb Smirnoff 	if ((lookupflag & INPLOOKUP_RLOCKPCB) && INP_TRY_UPGRADE(inp) == 0)
14071db08fbeSGleb Smirnoff 		goto dropunlock;
14081db08fbeSGleb Smirnoff 
140935bc0bccSGleb Smirnoff 	tp->t_fb->tfb_tcp_do_segment(tp, m, th, drop_hdrlen, tlen, iptos);
14108f5a8818SKevin Lo 	return (IPPROTO_DONE);
1411be2ac88cSJonathan Lemon 
1412302ce8d6SAndre Oppermann dropwithreset:
14132b9c9984SGeorge V. Neville-Neil 	TCP_PROBE5(receive, NULL, tp, m, tp, th);
141457f60867SMark Johnston 
1415014ea782SRobert Watson 	if (inp != NULL) {
1416302ce8d6SAndre Oppermann 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
141708d9c920SGleb Smirnoff 		INP_UNLOCK(inp);
1418dd8ac7f9SRobert Watson 	} else
1419014ea782SRobert Watson 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1420302ce8d6SAndre Oppermann 	m = NULL;	/* mbuf chain got consumed. */
1421014ea782SRobert Watson 	goto drop;
1422014ea782SRobert Watson 
1423302ce8d6SAndre Oppermann dropunlock:
142457f60867SMark Johnston 	if (m != NULL)
14252b9c9984SGeorge V. Neville-Neil 		TCP_PROBE5(receive, NULL, tp, m, tp, th);
142657f60867SMark Johnston 
14279fa198beSAndre Oppermann 	if (inp != NULL)
142808d9c920SGleb Smirnoff 		INP_UNLOCK(inp);
1429014ea782SRobert Watson 
1430302ce8d6SAndre Oppermann drop:
1431a160e630SAndre Oppermann 	if (s != NULL)
1432a160e630SAndre Oppermann 		free(s, M_TCPLOG);
1433302ce8d6SAndre Oppermann 	if (m != NULL)
1434302ce8d6SAndre Oppermann 		m_freem(m);
14358f5a8818SKevin Lo 	return (IPPROTO_DONE);
1436302ce8d6SAndre Oppermann }
1437302ce8d6SAndre Oppermann 
1438e44c1887SSteven Hartland /*
1439e44c1887SSteven Hartland  * Automatic sizing of receive socket buffer.  Often the send
1440e44c1887SSteven Hartland  * buffer size is not optimally adjusted to the actual network
1441e44c1887SSteven Hartland  * conditions at hand (delay bandwidth product).  Setting the
1442e44c1887SSteven Hartland  * buffer size too small limits throughput on links with high
1443e44c1887SSteven Hartland  * bandwidth and high delay (eg. trans-continental/oceanic links).
1444e44c1887SSteven Hartland  *
1445e44c1887SSteven Hartland  * On the receive side the socket buffer memory is only rarely
1446e44c1887SSteven Hartland  * used to any significant extent.  This allows us to be much
1447e44c1887SSteven Hartland  * more aggressive in scaling the receive socket buffer.  For
1448e44c1887SSteven Hartland  * the case that the buffer space is actually used to a large
1449e44c1887SSteven Hartland  * extent and we run out of kernel memory we can simply drop
1450e44c1887SSteven Hartland  * the new segments; TCP on the sender will just retransmit it
1451e44c1887SSteven Hartland  * later.  Setting the buffer size too big may only consume too
1452e44c1887SSteven Hartland  * much kernel memory if the application doesn't read() from
1453e44c1887SSteven Hartland  * the socket or packet loss or reordering makes use of the
1454e44c1887SSteven Hartland  * reassembly queue.
1455e44c1887SSteven Hartland  *
1456e44c1887SSteven Hartland  * The criteria to step up the receive buffer one notch are:
1457e44c1887SSteven Hartland  *  1. Application has not set receive buffer size with
1458e44c1887SSteven Hartland  *     SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1459560c0586SMichael Tuexen  *  2. the number of bytes received during 1/2 of an sRTT
1460560c0586SMichael Tuexen  *     is at least 3/8 of the current socket buffer size.
1461560c0586SMichael Tuexen  *  3. receive buffer size has not hit maximal automatic size;
1462e44c1887SSteven Hartland  *
1463560c0586SMichael Tuexen  * If all of the criteria are met we increaset the socket buffer
1464560c0586SMichael Tuexen  * by a 1/2 (bounded by the max). This allows us to keep ahead
1465560c0586SMichael Tuexen  * of slow-start but also makes it so our peer never gets limited
1466560c0586SMichael Tuexen  * by our rwnd which we then open up causing a burst.
1467560c0586SMichael Tuexen  *
1468560c0586SMichael Tuexen  * This algorithm does two steps per RTT at most and only if
1469e44c1887SSteven Hartland  * we receive a bulk stream w/o packet losses or reorderings.
1470e44c1887SSteven Hartland  * Shrinking the buffer during idle times is not necessary as
1471e44c1887SSteven Hartland  * it doesn't consume any memory when idle.
1472e44c1887SSteven Hartland  *
1473e44c1887SSteven Hartland  * TODO: Only step up if the application is actually serving
1474e44c1887SSteven Hartland  * the buffer to better manage the socket buffer resources.
1475e44c1887SSteven Hartland  */
1476e44c1887SSteven Hartland int
1477e44c1887SSteven Hartland tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1478e44c1887SSteven Hartland     struct tcpcb *tp, int tlen)
1479e44c1887SSteven Hartland {
1480e44c1887SSteven Hartland 	int newsize = 0;
1481e44c1887SSteven Hartland 
1482e44c1887SSteven Hartland 	if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1483e44c1887SSteven Hartland 	    tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1484e44c1887SSteven Hartland 	    TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1485560c0586SMichael Tuexen 	    ((tp->t_srtt >> TCP_RTT_SHIFT)/2)) {
1486560c0586SMichael Tuexen 		if (tp->rfbuf_cnt > ((so->so_rcv.sb_hiwat / 2)/ 4 * 3) &&
1487e44c1887SSteven Hartland 		    so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1488560c0586SMichael Tuexen 			newsize = min((so->so_rcv.sb_hiwat + (so->so_rcv.sb_hiwat/2)), V_tcp_autorcvbuf_max);
1489e44c1887SSteven Hartland 		}
1490e44c1887SSteven Hartland 		TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1491e44c1887SSteven Hartland 
1492e44c1887SSteven Hartland 		/* Start over with next RTT. */
1493e44c1887SSteven Hartland 		tp->rfbuf_ts = 0;
1494e44c1887SSteven Hartland 		tp->rfbuf_cnt = 0;
1495e44c1887SSteven Hartland 	} else {
1496e44c1887SSteven Hartland 		tp->rfbuf_cnt += tlen;	/* add up */
1497e44c1887SSteven Hartland 	}
1498e44c1887SSteven Hartland 	return (newsize);
1499e44c1887SSteven Hartland }
1500e44c1887SSteven Hartland 
15019e644c23SMichael Tuexen int
15029e644c23SMichael Tuexen tcp_input(struct mbuf **mp, int *offp, int proto)
15039e644c23SMichael Tuexen {
15049e644c23SMichael Tuexen 	return(tcp_input_with_port(mp, offp, proto, 0));
15059e644c23SMichael Tuexen }
15069e644c23SMichael Tuexen 
1507c348e880SGleb Smirnoff static void
1508c348e880SGleb Smirnoff tcp_handle_wakeup(struct tcpcb *tp)
15094d0770f1SRichard Scheffenegger {
1510c348e880SGleb Smirnoff 
15119eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
1512c348e880SGleb Smirnoff 
15134d0770f1SRichard Scheffenegger 	if (tp->t_flags & TF_WAKESOR) {
15149eb0e832SGleb Smirnoff 		struct socket *so = tptosocket(tp);
1515c348e880SGleb Smirnoff 
15164d0770f1SRichard Scheffenegger 		tp->t_flags &= ~TF_WAKESOR;
1517032bf749SRichard Scheffenegger 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1518032bf749SRichard Scheffenegger 		sorwakeup_locked(so);
15194d0770f1SRichard Scheffenegger 	}
15204d0770f1SRichard Scheffenegger }
15214d0770f1SRichard Scheffenegger 
15224d0770f1SRichard Scheffenegger void
152335bc0bccSGleb Smirnoff tcp_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
152435bc0bccSGleb Smirnoff     int drop_hdrlen, int tlen, uint8_t iptos)
1525302ce8d6SAndre Oppermann {
1526f7220c48SRichard Scheffenegger 	uint16_t thflags;
152749a6fbe3SRichard Scheffenegger 	int acked, ourfinisacked, needoutput = 0;
152849a6fbe3SRichard Scheffenegger 	sackstatus_t sack_changed;
1529b2ade6b1SRichard Scheffenegger 	int rstreason, todrop, win, incforsyn = 0;
15303ac12506SJonathan T. Looney 	uint32_t tiwin;
15314b7b743cSLawrence Stewart 	uint16_t nsegs;
153207dacf03SAndre Oppermann 	char *s;
15339eb0e832SGleb Smirnoff 	struct inpcb *inp = tptoinpcb(tp);
153435bc0bccSGleb Smirnoff 	struct socket *so = tptosocket(tp);
15359eb0e832SGleb Smirnoff 	struct in_conninfo *inc = &inp->inp_inc;
1536c11a15bfSGleb Smirnoff 	struct mbuf *mfree;
1537302ce8d6SAndre Oppermann 	struct tcpopt to;
1538281a0fd4SPatrick Kelsey 	int tfo_syn;
1539c7c325d0SRichard Scheffenegger 	u_int maxseg = 0;
1540302ce8d6SAndre Oppermann 
15411ebf4607SRichard Scheffenegger 	thflags = tcp_get_flags(th);
1542d64a46eaSLawrence Stewart 	tp->sackhint.last_sack_ack = 0;
154349a6fbe3SRichard Scheffenegger 	sack_changed = SACK_NOCHANGE;
15444b7b743cSLawrence Stewart 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
1545d40c0d47SGleb Smirnoff 
1546d40c0d47SGleb Smirnoff 	NET_EPOCH_ASSERT();
15479eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
1548679d9708SAndre Oppermann 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1549679d9708SAndre Oppermann 	    __func__));
1550679d9708SAndre Oppermann 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1551679d9708SAndre Oppermann 	    __func__));
1552df8bae1dSRodney W. Grimes 
155386a996e6SHiren Panchasara #ifdef TCPPCAP
155486a996e6SHiren Panchasara 	/* Save segment, if requested. */
155586a996e6SHiren Panchasara 	tcp_pcap_add(th, m, &(tp->t_inpkts));
155686a996e6SHiren Panchasara #endif
15572529f56eSJonathan T. Looney 	TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
15582529f56eSJonathan T. Looney 	    tlen, NULL, true);
155986a996e6SHiren Panchasara 
1560013f4df6SMichael Tuexen 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1561013f4df6SMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1562013f4df6SMichael Tuexen 			log(LOG_DEBUG, "%s; %s: "
1563013f4df6SMichael Tuexen 			    "SYN|FIN segment ignored (based on "
1564013f4df6SMichael Tuexen 			    "sysctl setting)\n", s, __func__);
1565013f4df6SMichael Tuexen 			free(s, M_TCPLOG);
1566013f4df6SMichael Tuexen 		}
1567013f4df6SMichael Tuexen 		goto drop;
1568013f4df6SMichael Tuexen 	}
1569013f4df6SMichael Tuexen 
1570df8bae1dSRodney W. Grimes 	/*
1571ebfd7534SMichael Tuexen 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1572ebfd7534SMichael Tuexen 	 * check SEQ.ACK first.
1573ebfd7534SMichael Tuexen 	 */
1574ebfd7534SMichael Tuexen 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1575ebfd7534SMichael Tuexen 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1576ebfd7534SMichael Tuexen 		rstreason = BANDLIM_UNLIMITED;
1577d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
1578ebfd7534SMichael Tuexen 		goto dropwithreset;
1579ebfd7534SMichael Tuexen 	}
1580ebfd7534SMichael Tuexen 
1581ebfd7534SMichael Tuexen 	/*
1582df8bae1dSRodney W. Grimes 	 * Segment received on connection.
1583df8bae1dSRodney W. Grimes 	 * Reset idle time and keep-alive timer.
1584e8949f74SAndre Oppermann 	 * XXX: This should be done after segment
1585e8949f74SAndre Oppermann 	 * validation to ignore broken/spoofed segs.
1586df8bae1dSRodney W. Grimes 	 */
1587cd84e78fSRandall Stewart 	if  (tp->t_idle_reduce &&
1588cd84e78fSRandall Stewart 	     (tp->snd_max == tp->snd_una) &&
1589cd84e78fSRandall Stewart 	     ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
1590cd84e78fSRandall Stewart 		cc_after_idle(tp);
15919b8b58e0SJonathan Lemon 	tp->t_rcvtime = ticks;
1592df8bae1dSRodney W. Grimes 
1593d1b07f36SRandall Stewart 	if (thflags & TH_FIN)
1594d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
1595df8bae1dSRodney W. Grimes 	/*
1596c52102ddSHiren Panchasara 	 * Scale up the window into a 32-bit value.
1597e8949f74SAndre Oppermann 	 * For the SYN_SENT state the scale is zero.
1598464fcfbcSAndre Oppermann 	 */
1599464fcfbcSAndre Oppermann 	tiwin = th->th_win << tp->snd_scale;
1600adc56f5aSEdward Tomasz Napierala #ifdef STATS
1601adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
1602adc56f5aSEdward Tomasz Napierala #endif
1603464fcfbcSAndre Oppermann 
1604464fcfbcSAndre Oppermann 	/*
1605f2512ba1SRui Paulo 	 * TCP ECN processing.
1606f2512ba1SRui Paulo 	 */
1607b1258b76SRichard Scheffenegger 	if (tcp_ecn_input_segment(tp, thflags, tlen,
1608b1258b76SRichard Scheffenegger 	    tcp_packets_this_ack(tp, th->th_ack),
1609b1258b76SRichard Scheffenegger 	    iptos))
1610dbc42409SLawrence Stewart 		cc_cong_signal(tp, th, CC_ECN);
1611f2512ba1SRui Paulo 
1612f2512ba1SRui Paulo 	/*
1613f72167f4SAndre Oppermann 	 * Parse options on any incoming segment.
1614f72167f4SAndre Oppermann 	 */
1615302ce8d6SAndre Oppermann 	tcp_dooptions(&to, (u_char *)(th + 1),
1616302ce8d6SAndre Oppermann 	    (th->th_off << 2) - sizeof(struct tcphdr),
1617302ce8d6SAndre Oppermann 	    (thflags & TH_SYN) ? TO_SYN : 0);
1618*fce03f85SRandall Stewart 	if (tp->t_flags2 & TF2_PROC_SACK_PROHIBIT) {
1619*fce03f85SRandall Stewart 		/*
1620*fce03f85SRandall Stewart 		 * We don't look at sack's from the
1621*fce03f85SRandall Stewart 		 * peer because the MSS is too small which
1622*fce03f85SRandall Stewart 		 * can subject us to an attack.
1623*fce03f85SRandall Stewart 		 */
1624*fce03f85SRandall Stewart 		to.to_flags &= ~TOF_SACK;
1625*fce03f85SRandall Stewart 	}
1626fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1627fcf59617SAndrey V. Elsukov 	if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1628fcf59617SAndrey V. Elsukov 	    (to.to_flags & TOF_SIGNATURE) == 0) {
1629fcf59617SAndrey V. Elsukov 		TCPSTAT_INC(tcps_sig_err_sigopt);
1630fcf59617SAndrey V. Elsukov 		/* XXX: should drop? */
1631fcf59617SAndrey V. Elsukov 	}
1632fcf59617SAndrey V. Elsukov #endif
1633f72167f4SAndre Oppermann 	/*
1634f72167f4SAndre Oppermann 	 * If echoed timestamp is later than the current time,
1635bf6d304aSAndre Oppermann 	 * fall back to non RFC1323 RTT calculation.  Normalize
1636bf6d304aSAndre Oppermann 	 * timestamp if syncookies were used when this connection
1637bf6d304aSAndre Oppermann 	 * was established.
1638f72167f4SAndre Oppermann 	 */
1639bf6d304aSAndre Oppermann 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1640e16fa5caSJohn-Mark Gurney 		to.to_tsecr -= tp->ts_offset;
16412d05a1c8SRichard Scheffenegger 		if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks())) {
1642f72167f4SAndre Oppermann 			to.to_tsecr = 0;
16432d05a1c8SRichard Scheffenegger 		} else if (tp->t_rxtshift == 1 &&
16444531b345SRichard Scheffenegger 			 tp->t_flags & TF_PREVVALID &&
16454531b345SRichard Scheffenegger 			 tp->t_badrxtwin != 0 &&
16462d05a1c8SRichard Scheffenegger 			 TSTMP_LT(to.to_tsecr, tp->t_badrxtwin)) {
164710d20c84SMatt Macy 			cc_cong_signal(tp, th, CC_RTO_ERR);
1648bf6d304aSAndre Oppermann 		}
16492d05a1c8SRichard Scheffenegger 	}
165007dacf03SAndre Oppermann 	/*
165197d8d152SAndre Oppermann 	 * Process options only when we get SYN/ACK back. The SYN case
165297d8d152SAndre Oppermann 	 * for incoming connections is handled in tcp_syncache.
16535396d0f8SAndre Oppermann 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
16545396d0f8SAndre Oppermann 	 * or <SYN,ACK>) segment itself is never scaled.
165597d8d152SAndre Oppermann 	 * XXX this is traditional behavior, may need to be cleaned up.
1656df8bae1dSRodney W. Grimes 	 */
16570a389eabSSimon L. B. Nielsen 	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
16586e16d877SRichard Scheffenegger 		/* Handle parallel SYN for ECN */
1659f7220c48SRichard Scheffenegger 		tcp_ecn_input_parallel_syn(tp, thflags, iptos);
1660464fcfbcSAndre Oppermann 		if ((to.to_flags & TOF_SCALE) &&
16612593f858SRichard Scheffenegger 		    (tp->t_flags & TF_REQ_SCALE) &&
16622593f858SRichard Scheffenegger 		    !(tp->t_flags & TF_NOOPT)) {
1663be2ac88cSJonathan Lemon 			tp->t_flags |= TF_RCVD_SCALE;
166402a1a643SAndre Oppermann 			tp->snd_scale = to.to_wscale;
16652d05a1c8SRichard Scheffenegger 		} else {
16668e051165SRichard Scheffenegger 			tp->t_flags &= ~TF_REQ_SCALE;
16672d05a1c8SRichard Scheffenegger 		}
16685396d0f8SAndre Oppermann 		/*
16695396d0f8SAndre Oppermann 		 * Initial send window.  It will be updated with
16705396d0f8SAndre Oppermann 		 * the next incoming segment to the scaled value.
16715396d0f8SAndre Oppermann 		 */
16725396d0f8SAndre Oppermann 		tp->snd_wnd = th->th_win;
16738e051165SRichard Scheffenegger 		if ((to.to_flags & TOF_TS) &&
16742593f858SRichard Scheffenegger 		    (tp->t_flags & TF_REQ_TSTMP) &&
16752593f858SRichard Scheffenegger 		    !(tp->t_flags & TF_NOOPT)) {
1676be2ac88cSJonathan Lemon 			tp->t_flags |= TF_RCVD_TSTMP;
1677be2ac88cSJonathan Lemon 			tp->ts_recent = to.to_tsval;
1678d8951c8aSBjoern A. Zeeb 			tp->ts_recent_age = tcp_ts_getticks();
16792d05a1c8SRichard Scheffenegger 		} else {
16808e051165SRichard Scheffenegger 			tp->t_flags &= ~TF_REQ_TSTMP;
16812d05a1c8SRichard Scheffenegger 		}
16822d05a1c8SRichard Scheffenegger 		if (to.to_flags & TOF_MSS) {
1683be2ac88cSJonathan Lemon 			tcp_mss(tp, to.to_mss);
16842d05a1c8SRichard Scheffenegger 		}
16853529149eSAndre Oppermann 		if ((tp->t_flags & TF_SACK_PERMIT) &&
16862593f858SRichard Scheffenegger 		    (!(to.to_flags & TOF_SACKPERM) ||
16872d05a1c8SRichard Scheffenegger 		    (tp->t_flags & TF_NOOPT))) {
16883529149eSAndre Oppermann 			tp->t_flags &= ~TF_SACK_PERMIT;
16892d05a1c8SRichard Scheffenegger 		}
1690dd7b86e2SGleb Smirnoff 		if (tp->t_flags & TF_FASTOPEN) {
16912593f858SRichard Scheffenegger 			if ((to.to_flags & TOF_FASTOPEN) &&
16922593f858SRichard Scheffenegger 			    !(tp->t_flags & TF_NOOPT)) {
1693a026a53aSMichael Tuexen 				uint16_t mss;
1694a026a53aSMichael Tuexen 
16952d05a1c8SRichard Scheffenegger 				if (to.to_flags & TOF_MSS) {
1696a026a53aSMichael Tuexen 					mss = to.to_mss;
16972d05a1c8SRichard Scheffenegger 				} else {
16982d05a1c8SRichard Scheffenegger 					if ((inp->inp_vflag & INP_IPV6) != 0) {
1699a026a53aSMichael Tuexen 						mss = TCP6_MSS;
17002d05a1c8SRichard Scheffenegger 					} else {
1701a026a53aSMichael Tuexen 						mss = TCP_MSS;
17022d05a1c8SRichard Scheffenegger 					}
17032d05a1c8SRichard Scheffenegger 				}
1704a026a53aSMichael Tuexen 				tcp_fastopen_update_cache(tp, mss,
1705a026a53aSMichael Tuexen 				    to.to_tfo_len, to.to_tfo_cookie);
17062d05a1c8SRichard Scheffenegger 			} else {
1707c560df6fSPatrick Kelsey 				tcp_fastopen_disable_path(tp);
1708c560df6fSPatrick Kelsey 			}
17096d90faf3SPaul Saab 		}
17102d05a1c8SRichard Scheffenegger 	}
17116d90faf3SPaul Saab 
1712df8bae1dSRodney W. Grimes 	/*
1713283c76c7SMichael Tuexen 	 * If timestamps were negotiated during SYN/ACK and a
1714283c76c7SMichael Tuexen 	 * segment without a timestamp is received, silently drop
1715d2b3ceddSMichael Tuexen 	 * the segment, unless it is a RST segment or missing timestamps are
1716d2b3ceddSMichael Tuexen 	 * tolerated.
1717283c76c7SMichael Tuexen 	 * See section 3.2 of RFC 7323.
17184da9052aSMichael Tuexen 	 */
17194da9052aSMichael Tuexen 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1720d2b3ceddSMichael Tuexen 		if (((thflags & TH_RST) != 0) || V_tcp_tolerate_missing_ts) {
1721cc3c3485SMichael Tuexen 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1722cc3c3485SMichael Tuexen 				log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1723cc3c3485SMichael Tuexen 				    "segment processed normally\n",
1724cc3c3485SMichael Tuexen 				    s, __func__);
1725cc3c3485SMichael Tuexen 				free(s, M_TCPLOG);
1726cc3c3485SMichael Tuexen 			}
1727cc3c3485SMichael Tuexen 		} else {
17284da9052aSMichael Tuexen 			if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
17294da9052aSMichael Tuexen 				log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1730283c76c7SMichael Tuexen 				    "segment silently dropped\n", s, __func__);
17314da9052aSMichael Tuexen 				free(s, M_TCPLOG);
17324da9052aSMichael Tuexen 			}
1733283c76c7SMichael Tuexen 			goto drop;
17344da9052aSMichael Tuexen 		}
1735cc3c3485SMichael Tuexen 	}
1736283c76c7SMichael Tuexen 	/*
1737283c76c7SMichael Tuexen 	 * If timestamps were not negotiated during SYN/ACK and a
173875fcd27aSMichael Tuexen 	 * segment with a timestamp is received, ignore the
1739283c76c7SMichael Tuexen 	 * timestamp and process the packet normally.
1740283c76c7SMichael Tuexen 	 * See section 3.2 of RFC 7323.
1741283c76c7SMichael Tuexen 	 */
17424da9052aSMichael Tuexen 	if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
17434da9052aSMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
17444da9052aSMichael Tuexen 			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1745283c76c7SMichael Tuexen 			    "segment processed normally\n", s, __func__);
17464da9052aSMichael Tuexen 			free(s, M_TCPLOG);
17474da9052aSMichael Tuexen 		}
17484da9052aSMichael Tuexen 	}
17494da9052aSMichael Tuexen 
17504da9052aSMichael Tuexen 	/*
1751df8bae1dSRodney W. Grimes 	 * Header prediction: check for the two common cases
1752df8bae1dSRodney W. Grimes 	 * of a uni-directional data xfer.  If the packet has
1753df8bae1dSRodney W. Grimes 	 * no control flags, is in-sequence, the window didn't
1754df8bae1dSRodney W. Grimes 	 * change and we're not retransmitting, it's a
1755df8bae1dSRodney W. Grimes 	 * candidate.  If the length is zero and the ack moved
1756df8bae1dSRodney W. Grimes 	 * forward, we're the sender side of the xfer.  Just
1757df8bae1dSRodney W. Grimes 	 * free the data acked & wake any higher level process
1758df8bae1dSRodney W. Grimes 	 * that was blocked waiting for space.  If the length
1759df8bae1dSRodney W. Grimes 	 * is non-zero and the ack didn't move, we're the
1760df8bae1dSRodney W. Grimes 	 * receiver side.  If we're getting packets in-order
1761df8bae1dSRodney W. Grimes 	 * (the reassembly queue is empty), add the data to
1762df8bae1dSRodney W. Grimes 	 * the socket buffer and note that we need a delayed ack.
1763a0292f23SGarrett Wollman 	 * Make sure that the hidden state-flags are also off.
1764c5ad39b9SAndre Oppermann 	 * Since we check for TCPS_ESTABLISHED first, it can only
1765a0292f23SGarrett Wollman 	 * be TH_NEEDSYN.
1766df8bae1dSRodney W. Grimes 	 */
1767df8bae1dSRodney W. Grimes 	if (tp->t_state == TCPS_ESTABLISHED &&
1768c5ad39b9SAndre Oppermann 	    th->th_seq == tp->rcv_nxt &&
1769fb59c426SYoshinobu Inoue 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1770c5ad39b9SAndre Oppermann 	    tp->snd_nxt == tp->snd_max &&
1771c5ad39b9SAndre Oppermann 	    tiwin && tiwin == tp->snd_wnd &&
1772a0292f23SGarrett Wollman 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1773c28440dbSRandall Stewart 	    SEGQ_EMPTY(tp) &&
17744741bfcbSPatrick Kelsey 	    ((to.to_flags & TOF_TS) == 0 ||
1775c5ad39b9SAndre Oppermann 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1776df8bae1dSRodney W. Grimes 		/*
1777df8bae1dSRodney W. Grimes 		 * If last ACK falls within this segment's sequence numbers,
1778df8bae1dSRodney W. Grimes 		 * record the timestamp.
1779a0292f23SGarrett Wollman 		 * NOTE that the test is modified according to the latest
1780a0292f23SGarrett Wollman 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1781df8bae1dSRodney W. Grimes 		 */
1782be2ac88cSJonathan Lemon 		if ((to.to_flags & TOF_TS) != 0 &&
1783fb59c426SYoshinobu Inoue 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1784d8951c8aSBjoern A. Zeeb 			tp->ts_recent_age = tcp_ts_getticks();
1785a0292f23SGarrett Wollman 			tp->ts_recent = to.to_tsval;
1786df8bae1dSRodney W. Grimes 		}
1787df8bae1dSRodney W. Grimes 
1788fb59c426SYoshinobu Inoue 		if (tlen == 0) {
1789fb59c426SYoshinobu Inoue 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1790fb59c426SYoshinobu Inoue 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1791dbc42409SLawrence Stewart 			    !IN_RECOVERY(tp->t_flags) &&
1792fc30a251SAndre Oppermann 			    (to.to_flags & TOF_SACK) == 0 &&
1793dbc42409SLawrence Stewart 			    TAILQ_EMPTY(&tp->snd_holes)) {
1794df8bae1dSRodney W. Grimes 				/*
1795e8949f74SAndre Oppermann 				 * This is a pure ack for outstanding data.
1796df8bae1dSRodney W. Grimes 				 */
179778b50714SRobert Watson 				TCPSTAT_INC(tcps_predack);
1798252ca428SRobert Watson 
17999b8b58e0SJonathan Lemon 				/*
180010d20c84SMatt Macy 				 * "bad retransmit" recovery without timestamps.
18019b8b58e0SJonathan Lemon 				 */
180210d20c84SMatt Macy 				if ((to.to_flags & TOF_TS) == 0 &&
180310d20c84SMatt Macy 				    tp->t_rxtshift == 1 &&
1804672dc4aeSJohn Baldwin 				    tp->t_flags & TF_PREVVALID &&
18054531b345SRichard Scheffenegger 				    tp->t_badrxtwin != 0 &&
18064531b345SRichard Scheffenegger 				    TSTMP_LT(ticks, tp->t_badrxtwin)) {
1807dbc42409SLawrence Stewart 					cc_cong_signal(tp, th, CC_RTO_ERR);
18089b8b58e0SJonathan Lemon 				}
1809fa55172bSMatthew Dillon 
1810fa55172bSMatthew Dillon 				/*
1811fa55172bSMatthew Dillon 				 * Recalculate the transmit timer / rtt.
1812fa55172bSMatthew Dillon 				 *
1813fa55172bSMatthew Dillon 				 * Some boxes send broken timestamp replies
1814fa55172bSMatthew Dillon 				 * during the SYN+ACK phase, ignore
1815fa55172bSMatthew Dillon 				 * timestamps of 0 or we could calculate a
1816fa55172bSMatthew Dillon 				 * huge RTT and blow up the retransmit timer.
1817fa55172bSMatthew Dillon 				 */
1818fa55172bSMatthew Dillon 				if ((to.to_flags & TOF_TS) != 0 &&
1819fa55172bSMatthew Dillon 				    to.to_tsecr) {
18203ac12506SJonathan T. Looney 					uint32_t t;
1821d8951c8aSBjoern A. Zeeb 
1822d8951c8aSBjoern A. Zeeb 					t = tcp_ts_getticks() - to.to_tsecr;
1823d8951c8aSBjoern A. Zeeb 					if (!tp->t_rttlow || tp->t_rttlow > t)
1824d8951c8aSBjoern A. Zeeb 						tp->t_rttlow = t;
1825a0292f23SGarrett Wollman 					tcp_xmit_timer(tp,
1826d8951c8aSBjoern A. Zeeb 					    TCP_TS_TO_TICKS(t) + 1);
1827fa55172bSMatthew Dillon 				} else if (tp->t_rtttime &&
1828fa55172bSMatthew Dillon 				    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1829eaf80179SAndre Oppermann 					if (!tp->t_rttlow ||
1830eaf80179SAndre Oppermann 					    tp->t_rttlow > ticks - tp->t_rtttime)
1831eaf80179SAndre Oppermann 						tp->t_rttlow = ticks - tp->t_rtttime;
1832c068736aSJeffrey Hsu 					tcp_xmit_timer(tp,
1833c068736aSJeffrey Hsu 							ticks - tp->t_rtttime);
1834fa55172bSMatthew Dillon 				}
1835dbc42409SLawrence Stewart 				acked = BYTES_THIS_ACK(tp, th);
183639bc9de5SLawrence Stewart 
1837bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
183839bc9de5SLawrence Stewart 				/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
183939bc9de5SLawrence Stewart 				hhook_run_tcp_est_in(tp, th, &to);
1840bd79708dSJonathan T. Looney #endif
184139bc9de5SLawrence Stewart 
18424b7b743cSLawrence Stewart 				TCPSTAT_ADD(tcps_rcvackpack, nsegs);
184378b50714SRobert Watson 				TCPSTAT_ADD(tcps_rcvackbyte, acked);
1844df8bae1dSRodney W. Grimes 				sbdrop(&so->so_snd, acked);
18459d11646dSJeffrey Hsu 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
18469d11646dSJeffrey Hsu 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
18479d11646dSJeffrey Hsu 					tp->snd_recover = th->th_ack - 1;
1848dbc42409SLawrence Stewart 
1849dbc42409SLawrence Stewart 				/*
1850dbc42409SLawrence Stewart 				 * Let the congestion control algorithm update
1851dbc42409SLawrence Stewart 				 * congestion control related information. This
1852dbc42409SLawrence Stewart 				 * typically means increasing the congestion
1853dbc42409SLawrence Stewart 				 * window.
1854dbc42409SLawrence Stewart 				 */
18554b7b743cSLawrence Stewart 				cc_ack_received(tp, th, nsegs, CC_ACK);
1856dbc42409SLawrence Stewart 
18579d11646dSJeffrey Hsu 				tp->snd_una = th->th_ack;
18581645d090SJeff Roberson 				/*
1859e8949f74SAndre Oppermann 				 * Pull snd_wl2 up to prevent seq wrap relative
18601645d090SJeff Roberson 				 * to th_ack.
18611645d090SJeff Roberson 				 */
1862cb942153SJeffrey Hsu 				tp->snd_wl2 = th->th_ack;
1863b5addd85SJeffrey Hsu 				tp->t_dupacks = 0;
1864df8bae1dSRodney W. Grimes 				m_freem(m);
1865df8bae1dSRodney W. Grimes 
1866df8bae1dSRodney W. Grimes 				/*
1867df8bae1dSRodney W. Grimes 				 * If all outstanding data are acked, stop
1868df8bae1dSRodney W. Grimes 				 * retransmit timer, otherwise restart timer
1869df8bae1dSRodney W. Grimes 				 * using current (possibly backed-off) value.
1870df8bae1dSRodney W. Grimes 				 * If process is waiting for space,
1871df8bae1dSRodney W. Grimes 				 * wakeup/selwakeup/signal.  If data
1872df8bae1dSRodney W. Grimes 				 * are ready to send, let tcp_output
1873df8bae1dSRodney W. Grimes 				 * decide between more output or persist.
1874e8949f74SAndre Oppermann 				 */
18752b9c9984SGeorge V. Neville-Neil 				TCP_PROBE3(debug__input, tp, th, m);
187608af8aacSRandall Stewart 				/*
187708af8aacSRandall Stewart 				 * Clear t_acktime if remote side has ACKd
187808af8aacSRandall Stewart 				 * all data in the socket buffer.
187908af8aacSRandall Stewart 				 * Otherwise, update t_acktime if we received
188008af8aacSRandall Stewart 				 * a sufficiently large ACK.
188108af8aacSRandall Stewart 				 */
188208af8aacSRandall Stewart 				if (sbavail(&so->so_snd) == 0)
188308af8aacSRandall Stewart 					tp->t_acktime = 0;
188408af8aacSRandall Stewart 				else if (acked > 1)
188508af8aacSRandall Stewart 					tp->t_acktime = ticks;
1886df8bae1dSRodney W. Grimes 				if (tp->snd_una == tp->snd_max)
1887b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT, 0);
1888b8152ba7SAndre Oppermann 				else if (!tcp_timer_active(tp, TT_PERSIST))
1889b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT,
189008af8aacSRandall Stewart 					    TP_RXTCUR(tp));
1891032bf749SRichard Scheffenegger 				sowwakeup(so);
1892f4574e2dSRichard Scheffenegger 				/*
1893f4574e2dSRichard Scheffenegger 				 * Only call tcp_output when there
1894f4574e2dSRichard Scheffenegger 				 * is new data available to be sent
1895f4574e2dSRichard Scheffenegger 				 * or we need to send an ACK.
1896f4574e2dSRichard Scheffenegger 				 */
18972d05a1c8SRichard Scheffenegger 				if ((tp->t_flags & TF_ACKNOW) ||
18982d05a1c8SRichard Scheffenegger 				    (sbavail(&so->so_snd) >=
18992d05a1c8SRichard Scheffenegger 				     SEQ_SUB(tp->snd_max, tp->snd_una))) {
190040fa3e40SGleb Smirnoff 					(void) tcp_output(tp);
19012d05a1c8SRichard Scheffenegger 				}
1902a14c749fSJonathan Lemon 				goto check_delack;
1903df8bae1dSRodney W. Grimes 			}
1904fb59c426SYoshinobu Inoue 		} else if (th->th_ack == tp->snd_una &&
1905fb59c426SYoshinobu Inoue 		    tlen <= sbspace(&so->so_rcv)) {
19066741ecf5SAndre Oppermann 			int newsize = 0;	/* automatic sockbuf scaling */
19076741ecf5SAndre Oppermann 
1908df8bae1dSRodney W. Grimes 			/*
1909252ca428SRobert Watson 			 * This is a pure, in-sequence data packet with
1910252ca428SRobert Watson 			 * nothing on the reassembly queue and we have enough
1911252ca428SRobert Watson 			 * buffer space to take it.
1912df8bae1dSRodney W. Grimes 			 */
19136d90faf3SPaul Saab 			/* Clean receiver SACK report if present */
19143529149eSAndre Oppermann 			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
19156d90faf3SPaul Saab 				tcp_clean_sackreport(tp);
191678b50714SRobert Watson 			TCPSTAT_INC(tcps_preddat);
1917fb59c426SYoshinobu Inoue 			tp->rcv_nxt += tlen;
1918e854dd38SRandall Stewart 			if (tlen &&
1919e854dd38SRandall Stewart 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
1920e854dd38SRandall Stewart 			    (tp->t_fbyte_in == 0)) {
1921e854dd38SRandall Stewart 				tp->t_fbyte_in = ticks;
1922e854dd38SRandall Stewart 				if (tp->t_fbyte_in == 0)
1923e854dd38SRandall Stewart 					tp->t_fbyte_in = 1;
1924e854dd38SRandall Stewart 				if (tp->t_fbyte_out && tp->t_fbyte_in)
1925e854dd38SRandall Stewart 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
1926e854dd38SRandall Stewart 			}
19271645d090SJeff Roberson 			/*
19281645d090SJeff Roberson 			 * Pull snd_wl1 up to prevent seq wrap relative to
19291645d090SJeff Roberson 			 * th_seq.
19301645d090SJeff Roberson 			 */
193160ee3bb2SAndre Oppermann 			tp->snd_wl1 = th->th_seq;
19321645d090SJeff Roberson 			/*
19331645d090SJeff Roberson 			 * Pull rcv_up up to prevent seq wrap relative to
19341645d090SJeff Roberson 			 * rcv_nxt.
19351645d090SJeff Roberson 			 */
19361645d090SJeff Roberson 			tp->rcv_up = tp->rcv_nxt;
19374b7b743cSLawrence Stewart 			TCPSTAT_ADD(tcps_rcvpack, nsegs);
193878b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
19392b9c9984SGeorge V. Neville-Neil 			TCP_PROBE3(debug__input, tp, th, m);
19405d06879aSGeorge V. Neville-Neil 
1941e44c1887SSteven Hartland 			newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
19426741ecf5SAndre Oppermann 
19436741ecf5SAndre Oppermann 			/* Add data to socket buffer. */
19441e4d7da7SRobert Watson 			SOCKBUF_LOCK(&so->so_rcv);
1945c0b99ffaSRobert Watson 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1946c1c36a2cSMike Silbersack 				m_freem(m);
1947c1c36a2cSMike Silbersack 			} else {
19486741ecf5SAndre Oppermann 				/*
19496741ecf5SAndre Oppermann 				 * Set new socket buffer size.
19506741ecf5SAndre Oppermann 				 * Give up when limit is reached.
19516741ecf5SAndre Oppermann 				 */
19526741ecf5SAndre Oppermann 				if (newsize)
195343283184SGleb Smirnoff 					if (!sbreserve_locked(so, SO_RCV,
195443283184SGleb Smirnoff 					    newsize, NULL))
19556741ecf5SAndre Oppermann 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1956fb59c426SYoshinobu Inoue 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1957651e4e6aSGleb Smirnoff 				sbappendstream_locked(&so->so_rcv, m, 0);
1958c1c36a2cSMike Silbersack 			}
1959032bf749SRichard Scheffenegger 			/* NB: sorwakeup_locked() does an implicit unlock. */
1960032bf749SRichard Scheffenegger 			sorwakeup_locked(so);
1961c1e5a6e5SAndre Oppermann 			if (DELAY_ACK(tp, tlen)) {
19623bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
1963f498eeeeSDavid Greenman 			} else {
1964e612a582SDavid Greenman 				tp->t_flags |= TF_ACKNOW;
19653e1c8a35SMichael Tuexen 				(void) tcp_output(tp);
1966e612a582SDavid Greenman 			}
1967a14c749fSJonathan Lemon 			goto check_delack;
1968df8bae1dSRodney W. Grimes 		}
1969df8bae1dSRodney W. Grimes 	}
1970df8bae1dSRodney W. Grimes 
1971df8bae1dSRodney W. Grimes 	/*
1972df8bae1dSRodney W. Grimes 	 * Calculate amount of space in receive window,
1973df8bae1dSRodney W. Grimes 	 * and then do TCP input processing.
1974df8bae1dSRodney W. Grimes 	 * Receive window is amount of space in rcv queue,
1975df8bae1dSRodney W. Grimes 	 * but not less than advertised window.
1976df8bae1dSRodney W. Grimes 	 */
1977df8bae1dSRodney W. Grimes 	win = sbspace(&so->so_rcv);
1978df8bae1dSRodney W. Grimes 	if (win < 0)
1979df8bae1dSRodney W. Grimes 		win = 0;
198066e39adcSJohn Polstra 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1981df8bae1dSRodney W. Grimes 
1982df8bae1dSRodney W. Grimes 	switch (tp->t_state) {
1983df8bae1dSRodney W. Grimes 	/*
1984764d8cefSBill Fenner 	 * If the state is SYN_RECEIVED:
1985764d8cefSBill Fenner 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1986764d8cefSBill Fenner 	 */
1987764d8cefSBill Fenner 	case TCPS_SYN_RECEIVED:
1988b352ef58SRichard Scheffenegger 		if (thflags & TH_RST) {
1989b352ef58SRichard Scheffenegger 			/* Handle RST segments later. */
1990b352ef58SRichard Scheffenegger 			break;
1991b352ef58SRichard Scheffenegger 		}
1992fb59c426SYoshinobu Inoue 		if ((thflags & TH_ACK) &&
1993fb59c426SYoshinobu Inoue 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1994a57815efSBosko Milekic 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1995a57815efSBosko Milekic 				rstreason = BANDLIM_RST_OPENPORT;
1996d1b07f36SRandall Stewart 				tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
1997a57815efSBosko Milekic 				goto dropwithreset;
1998a57815efSBosko Milekic 		}
1999dd7b86e2SGleb Smirnoff 		if (tp->t_flags & TF_FASTOPEN) {
2000281a0fd4SPatrick Kelsey 			/*
2001281a0fd4SPatrick Kelsey 			 * When a TFO connection is in SYN_RECEIVED, the
2002281a0fd4SPatrick Kelsey 			 * only valid packets are the initial SYN, a
2003281a0fd4SPatrick Kelsey 			 * retransmit/copy of the initial SYN (possibly with
2004281a0fd4SPatrick Kelsey 			 * a subset of the original data), a valid ACK, a
2005281a0fd4SPatrick Kelsey 			 * FIN, or a RST.
2006281a0fd4SPatrick Kelsey 			 */
2007281a0fd4SPatrick Kelsey 			if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
2008281a0fd4SPatrick Kelsey 				rstreason = BANDLIM_RST_OPENPORT;
2009d1b07f36SRandall Stewart 				tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2010281a0fd4SPatrick Kelsey 				goto dropwithreset;
2011281a0fd4SPatrick Kelsey 			} else if (thflags & TH_SYN) {
2012281a0fd4SPatrick Kelsey 				/* non-initial SYN is ignored */
2013281a0fd4SPatrick Kelsey 				if ((tcp_timer_active(tp, TT_DELACK) ||
2014281a0fd4SPatrick Kelsey 				     tcp_timer_active(tp, TT_REXMT)))
2015281a0fd4SPatrick Kelsey 					goto drop;
2016281a0fd4SPatrick Kelsey 			} else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
2017281a0fd4SPatrick Kelsey 				goto drop;
2018281a0fd4SPatrick Kelsey 			}
2019281a0fd4SPatrick Kelsey 		}
2020764d8cefSBill Fenner 		break;
2021764d8cefSBill Fenner 
2022764d8cefSBill Fenner 	/*
2023df8bae1dSRodney W. Grimes 	 * If the state is SYN_SENT:
202498732609SMichael Tuexen 	 *	if seg contains a RST with valid ACK (SEQ.ACK has already
202598732609SMichael Tuexen 	 *	    been verified), then drop the connection.
202698732609SMichael Tuexen 	 *	if seg contains a RST without an ACK, drop the seg.
202798732609SMichael Tuexen 	 *	if seg does not contain SYN, then drop the seg.
2028df8bae1dSRodney W. Grimes 	 * Otherwise this is an acceptable SYN segment
2029df8bae1dSRodney W. Grimes 	 *	initialize tp->rcv_nxt and tp->irs
2030df8bae1dSRodney W. Grimes 	 *	if seg contains ack then advance tp->snd_una
2031f2512ba1SRui Paulo 	 *	if seg contains an ECE and ECN support is enabled, the stream
2032f2512ba1SRui Paulo 	 *	    is ECN capable.
2033df8bae1dSRodney W. Grimes 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2034df8bae1dSRodney W. Grimes 	 *	arrange for segment to be acked (eventually)
2035df8bae1dSRodney W. Grimes 	 *	continue processing rest of data/controls, beginning with URG
2036df8bae1dSRodney W. Grimes 	 */
2037df8bae1dSRodney W. Grimes 	case TCPS_SYN_SENT:
203857f60867SMark Johnston 		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2039d9fae5abSAndriy Gapon 			TCP_PROBE5(connect__refused, NULL, tp,
20402b9c9984SGeorge V. Neville-Neil 			    m, tp, th);
2041d1b07f36SRandall Stewart 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2042df8bae1dSRodney W. Grimes 			tp = tcp_drop(tp, ECONNREFUSED);
204357f60867SMark Johnston 		}
20440ca3f933SAndre Oppermann 		if (thflags & TH_RST)
2045df8bae1dSRodney W. Grimes 			goto drop;
20460ca3f933SAndre Oppermann 		if (!(thflags & TH_SYN))
2047df8bae1dSRodney W. Grimes 			goto drop;
2048464fcfbcSAndre Oppermann 
2049fb59c426SYoshinobu Inoue 		tp->irs = th->th_seq;
2050df8bae1dSRodney W. Grimes 		tcp_rcvseqinit(tp);
2051fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK) {
2052c560df6fSPatrick Kelsey 			int tfo_partial_ack = 0;
2053c560df6fSPatrick Kelsey 
205478b50714SRobert Watson 			TCPSTAT_INC(tcps_connects);
2055845799c1SAndras Olah 			soisconnected(so);
2056c488362eSRobert Watson #ifdef MAC
205730d239bcSRobert Watson 			mac_socketpeer_set_from_mbuf(m, so);
2058c488362eSRobert Watson #endif
2059845799c1SAndras Olah 			/* Do window scaling on this connection? */
2060845799c1SAndras Olah 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2061845799c1SAndras Olah 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2062845799c1SAndras Olah 				tp->rcv_scale = tp->request_r_scale;
2063845799c1SAndras Olah 			}
20643ac12506SJonathan T. Looney 			tp->rcv_adv += min(tp->rcv_wnd,
2065766282cbSJohn Baldwin 			    TCP_MAXWIN << tp->rcv_scale);
2066a0292f23SGarrett Wollman 			tp->snd_una++;		/* SYN is acked */
2067f4574e2dSRichard Scheffenegger 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2068f4574e2dSRichard Scheffenegger 				tp->snd_nxt = tp->snd_una;
2069a0292f23SGarrett Wollman 			/*
2070c560df6fSPatrick Kelsey 			 * If not all the data that was sent in the TFO SYN
2071c560df6fSPatrick Kelsey 			 * has been acked, resend the remainder right away.
2072c560df6fSPatrick Kelsey 			 */
2073dd7b86e2SGleb Smirnoff 			if ((tp->t_flags & TF_FASTOPEN) &&
2074c560df6fSPatrick Kelsey 			    (tp->snd_una != tp->snd_max)) {
2075c560df6fSPatrick Kelsey 				tp->snd_nxt = th->th_ack;
2076c560df6fSPatrick Kelsey 				tfo_partial_ack = 1;
2077c560df6fSPatrick Kelsey 			}
2078c560df6fSPatrick Kelsey 			/*
2079a0292f23SGarrett Wollman 			 * If there's data, delay ACK; if there's also a FIN
2080a0292f23SGarrett Wollman 			 * ACKNOW will be turned on later.
2081a0292f23SGarrett Wollman 			 */
2082c560df6fSPatrick Kelsey 			if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
2083b8152ba7SAndre Oppermann 				tcp_timer_activate(tp, TT_DELACK,
2084b8152ba7SAndre Oppermann 				    tcp_delacktime);
2085a0292f23SGarrett Wollman 			else
2086a0292f23SGarrett Wollman 				tp->t_flags |= TF_ACKNOW;
2087f2512ba1SRui Paulo 
2088f7220c48SRichard Scheffenegger 			tcp_ecn_input_syn_sent(tp, thflags, iptos);
2089f2512ba1SRui Paulo 
2090a0292f23SGarrett Wollman 			/*
2091a0292f23SGarrett Wollman 			 * Received <SYN,ACK> in SYN_SENT[*] state.
2092a0292f23SGarrett Wollman 			 * Transitions:
2093a0292f23SGarrett Wollman 			 *	SYN_SENT  --> ESTABLISHED
2094a0292f23SGarrett Wollman 			 *	SYN_SENT* --> FIN_WAIT_1
2095a0292f23SGarrett Wollman 			 */
20969b8b58e0SJonathan Lemon 			tp->t_starttime = ticks;
2097a0292f23SGarrett Wollman 			if (tp->t_flags & TF_NEEDFIN) {
209808af8aacSRandall Stewart 				tp->t_acktime = ticks;
209957f60867SMark Johnston 				tcp_state_change(tp, TCPS_FIN_WAIT_1);
2100a0292f23SGarrett Wollman 				tp->t_flags &= ~TF_NEEDFIN;
2101fb59c426SYoshinobu Inoue 				thflags &= ~TH_SYN;
21027ff19458SPaul Traina 			} else {
210357f60867SMark Johnston 				tcp_state_change(tp, TCPS_ESTABLISHED);
2104d9fae5abSAndriy Gapon 				TCP_PROBE5(connect__established, NULL, tp,
21052b9c9984SGeorge V. Neville-Neil 				    m, tp, th);
2106dbc42409SLawrence Stewart 				cc_conn_init(tp);
21079077f387SGleb Smirnoff 				tcp_timer_activate(tp, TT_KEEP,
21089077f387SGleb Smirnoff 				    TP_KEEPIDLE(tp));
21097ff19458SPaul Traina 			}
2110a0292f23SGarrett Wollman 		} else {
2111a0292f23SGarrett Wollman 			/*
2112c068736aSJeffrey Hsu 			 * Received initial SYN in SYN-SENT[*] state =>
2113153edc50SHiren Panchasara 			 * simultaneous open.
2114c068736aSJeffrey Hsu 			 * If it succeeds, connection is * half-synchronized.
2115c068736aSJeffrey Hsu 			 * Otherwise, do 3-way handshake:
2116a0292f23SGarrett Wollman 			 *        SYN-SENT -> SYN-RECEIVED
2117a0292f23SGarrett Wollman 			 *        SYN-SENT* -> SYN-RECEIVED*
2118a0292f23SGarrett Wollman 			 */
2119493105c2SGleb Smirnoff 			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
2120b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
212157f60867SMark Johnston 			tcp_state_change(tp, TCPS_SYN_RECEIVED);
2122a0292f23SGarrett Wollman 		}
2123df8bae1dSRodney W. Grimes 
2124df8bae1dSRodney W. Grimes 		/*
2125fb59c426SYoshinobu Inoue 		 * Advance th->th_seq to correspond to first data byte.
2126df8bae1dSRodney W. Grimes 		 * If data, trim to stay within window,
2127df8bae1dSRodney W. Grimes 		 * dropping FIN if necessary.
2128df8bae1dSRodney W. Grimes 		 */
2129fb59c426SYoshinobu Inoue 		th->th_seq++;
2130fb59c426SYoshinobu Inoue 		if (tlen > tp->rcv_wnd) {
2131fb59c426SYoshinobu Inoue 			todrop = tlen - tp->rcv_wnd;
2132df8bae1dSRodney W. Grimes 			m_adj(m, -todrop);
2133fb59c426SYoshinobu Inoue 			tlen = tp->rcv_wnd;
2134fb59c426SYoshinobu Inoue 			thflags &= ~TH_FIN;
213578b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpackafterwin);
213678b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2137df8bae1dSRodney W. Grimes 		}
2138fb59c426SYoshinobu Inoue 		tp->snd_wl1 = th->th_seq - 1;
2139fb59c426SYoshinobu Inoue 		tp->rcv_up = th->th_seq;
2140a0292f23SGarrett Wollman 		/*
2141a0292f23SGarrett Wollman 		 * Client side of transaction: already sent SYN and data.
2142a0292f23SGarrett Wollman 		 * If the remote host used T/TCP to validate the SYN,
2143a0292f23SGarrett Wollman 		 * our data will be ACK'd; if so, enter normal data segment
2144a0292f23SGarrett Wollman 		 * processing in the middle of step 5, ack processing.
2145a0292f23SGarrett Wollman 		 * Otherwise, goto step 6.
2146a0292f23SGarrett Wollman 		 */
2147fb59c426SYoshinobu Inoue 		if (thflags & TH_ACK)
2148a0292f23SGarrett Wollman 			goto process_ACK;
2149c068736aSJeffrey Hsu 
2150df8bae1dSRodney W. Grimes 		goto step6;
2151df8bae1dSRodney W. Grimes 	}
2152df8bae1dSRodney W. Grimes 
2153df8bae1dSRodney W. Grimes 	/*
2154df8bae1dSRodney W. Grimes 	 * States other than LISTEN or SYN_SENT.
215580ab7c0eSGarrett Wollman 	 * First check the RST flag and sequence number since reset segments
215680ab7c0eSGarrett Wollman 	 * are exempt from the timestamp and connection count tests.  This
215780ab7c0eSGarrett Wollman 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
215880ab7c0eSGarrett Wollman 	 * below which allowed reset segments in half the sequence space
215980ab7c0eSGarrett Wollman 	 * to fall though and be processed (which gives forged reset
216080ab7c0eSGarrett Wollman 	 * segments with a random sequence number a 50 percent chance of
216180ab7c0eSGarrett Wollman 	 * killing a connection).
216280ab7c0eSGarrett Wollman 	 * Then check timestamp, if present.
2163a0292f23SGarrett Wollman 	 * Then check the connection count, if present.
2164df8bae1dSRodney W. Grimes 	 * Then check that at least some bytes of segment are within
2165df8bae1dSRodney W. Grimes 	 * receive window.  If segment begins before rcv_nxt,
2166df8bae1dSRodney W. Grimes 	 * drop leading data (and SYN); if nothing left, just ack.
216780ab7c0eSGarrett Wollman 	 */
2168fb59c426SYoshinobu Inoue 	if (thflags & TH_RST) {
21693220a212SGleb Smirnoff 		/*
21703220a212SGleb Smirnoff 		 * RFC5961 Section 3.2
21713220a212SGleb Smirnoff 		 *
21723220a212SGleb Smirnoff 		 * - RST drops connection only if SEG.SEQ == RCV.NXT.
21733220a212SGleb Smirnoff 		 * - If RST is in window, we send challenge ACK.
21743220a212SGleb Smirnoff 		 *
21753220a212SGleb Smirnoff 		 * Note: to take into account delayed ACKs, we should
21763220a212SGleb Smirnoff 		 *   test against last_ack_sent instead of rcv_nxt.
21773220a212SGleb Smirnoff 		 * Note 2: we handle special case of closed window, not
21783220a212SGleb Smirnoff 		 *   covered by the RFC.
21793220a212SGleb Smirnoff 		 */
21803220a212SGleb Smirnoff 		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
21813220a212SGleb Smirnoff 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
21823220a212SGleb Smirnoff 		    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
21833220a212SGleb Smirnoff 			KASSERT(tp->t_state != TCPS_SYN_SENT,
21843220a212SGleb Smirnoff 			    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
21853220a212SGleb Smirnoff 			    __func__, th, tp));
21863220a212SGleb Smirnoff 
21873220a212SGleb Smirnoff 			if (V_tcp_insecure_rst ||
21883220a212SGleb Smirnoff 			    tp->last_ack_sent == th->th_seq) {
21893220a212SGleb Smirnoff 				TCPSTAT_INC(tcps_drops);
21903220a212SGleb Smirnoff 				/* Drop the connection. */
21913220a212SGleb Smirnoff 				switch (tp->t_state) {
219280ab7c0eSGarrett Wollman 				case TCPS_SYN_RECEIVED:
219380ab7c0eSGarrett Wollman 					so->so_error = ECONNREFUSED;
219480ab7c0eSGarrett Wollman 					goto close;
219580ab7c0eSGarrett Wollman 				case TCPS_ESTABLISHED:
219680ab7c0eSGarrett Wollman 				case TCPS_FIN_WAIT_1:
219780ab7c0eSGarrett Wollman 				case TCPS_FIN_WAIT_2:
219880ab7c0eSGarrett Wollman 				case TCPS_CLOSE_WAIT:
21996779a1a1SMichael Tuexen 				case TCPS_CLOSING:
22006779a1a1SMichael Tuexen 				case TCPS_LAST_ACK:
220180ab7c0eSGarrett Wollman 					so->so_error = ECONNRESET;
220280ab7c0eSGarrett Wollman 				close:
22033220a212SGleb Smirnoff 					/* FALLTHROUGH */
22043220a212SGleb Smirnoff 				default:
2205d1b07f36SRandall Stewart 					tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
220680ab7c0eSGarrett Wollman 					tp = tcp_close(tp);
22073220a212SGleb Smirnoff 				}
22083220a212SGleb Smirnoff 			} else {
22093220a212SGleb Smirnoff 				TCPSTAT_INC(tcps_badrst);
22103220a212SGleb Smirnoff 				/* Send challenge ACK. */
22113220a212SGleb Smirnoff 				tcp_respond(tp, mtod(m, void *), th, m,
22123220a212SGleb Smirnoff 				    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
22133220a212SGleb Smirnoff 				tp->last_ack_sent = tp->rcv_nxt;
22143220a212SGleb Smirnoff 				m = NULL;
22153220a212SGleb Smirnoff 			}
22163220a212SGleb Smirnoff 		}
22173220a212SGleb Smirnoff 		goto drop;
22183220a212SGleb Smirnoff 	}
221980ab7c0eSGarrett Wollman 
22203220a212SGleb Smirnoff 	/*
22213220a212SGleb Smirnoff 	 * RFC5961 Section 4.2
22223220a212SGleb Smirnoff 	 * Send challenge ACK for any SYN in synchronized state.
22233220a212SGleb Smirnoff 	 */
2224281a0fd4SPatrick Kelsey 	if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2225281a0fd4SPatrick Kelsey 	    tp->t_state != TCPS_SYN_RECEIVED) {
22263220a212SGleb Smirnoff 		TCPSTAT_INC(tcps_badsyn);
22273220a212SGleb Smirnoff 		if (V_tcp_insecure_syn &&
22283220a212SGleb Smirnoff 		    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
22293220a212SGleb Smirnoff 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2230d1b07f36SRandall Stewart 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
22313220a212SGleb Smirnoff 			tp = tcp_drop(tp, ECONNRESET);
22323220a212SGleb Smirnoff 			rstreason = BANDLIM_UNLIMITED;
22333220a212SGleb Smirnoff 		} else {
223483c1ec92SRichard Scheffenegger 			tcp_ecn_input_syn_sent(tp, thflags, iptos);
22353220a212SGleb Smirnoff 			/* Send challenge ACK. */
22363220a212SGleb Smirnoff 			tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
22373220a212SGleb Smirnoff 			    tp->snd_nxt, TH_ACK);
22383220a212SGleb Smirnoff 			tp->last_ack_sent = tp->rcv_nxt;
22393220a212SGleb Smirnoff 			m = NULL;
224080ab7c0eSGarrett Wollman 		}
224180ab7c0eSGarrett Wollman 		goto drop;
224280ab7c0eSGarrett Wollman 	}
224380ab7c0eSGarrett Wollman 
224480ab7c0eSGarrett Wollman 	/*
2245df8bae1dSRodney W. Grimes 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2246df8bae1dSRodney W. Grimes 	 * and it's less than ts_recent, drop it.
2247df8bae1dSRodney W. Grimes 	 */
2248be2ac88cSJonathan Lemon 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
224980ab7c0eSGarrett Wollman 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2250df8bae1dSRodney W. Grimes 		/* Check to see if ts_recent is over 24 days old.  */
2251d8951c8aSBjoern A. Zeeb 		if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2252df8bae1dSRodney W. Grimes 			/*
2253df8bae1dSRodney W. Grimes 			 * Invalidate ts_recent.  If this segment updates
2254df8bae1dSRodney W. Grimes 			 * ts_recent, the age will be reset later and ts_recent
2255df8bae1dSRodney W. Grimes 			 * will get a valid value.  If it does not, setting
2256df8bae1dSRodney W. Grimes 			 * ts_recent to zero will at least satisfy the
2257df8bae1dSRodney W. Grimes 			 * requirement that zero be placed in the timestamp
2258df8bae1dSRodney W. Grimes 			 * echo reply when ts_recent isn't valid.  The
2259df8bae1dSRodney W. Grimes 			 * age isn't reset until we get a valid ts_recent
2260df8bae1dSRodney W. Grimes 			 * because we don't want out-of-order segments to be
2261df8bae1dSRodney W. Grimes 			 * dropped when ts_recent is old.
2262df8bae1dSRodney W. Grimes 			 */
2263df8bae1dSRodney W. Grimes 			tp->ts_recent = 0;
2264df8bae1dSRodney W. Grimes 		} else {
226578b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvduppack);
226678b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
226778b50714SRobert Watson 			TCPSTAT_INC(tcps_pawsdrop);
226807fd333dSMatthew Dillon 			if (tlen)
2269df8bae1dSRodney W. Grimes 				goto dropafterack;
22701ab4789dSMatthew Dillon 			goto drop;
22711ab4789dSMatthew Dillon 		}
2272df8bae1dSRodney W. Grimes 	}
2273df8bae1dSRodney W. Grimes 
2274a0292f23SGarrett Wollman 	/*
227580ab7c0eSGarrett Wollman 	 * In the SYN-RECEIVED state, validate that the packet belongs to
227680ab7c0eSGarrett Wollman 	 * this connection before trimming the data to fit the receive
227780ab7c0eSGarrett Wollman 	 * window.  Check the sequence number versus IRS since we know
227880ab7c0eSGarrett Wollman 	 * the sequence numbers haven't wrapped.  This is a partial fix
227980ab7c0eSGarrett Wollman 	 * for the "LAND" DoS attack.
228080ab7c0eSGarrett Wollman 	 */
2281a57815efSBosko Milekic 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2282a57815efSBosko Milekic 		rstreason = BANDLIM_RST_OPENPORT;
2283d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2284a57815efSBosko Milekic 		goto dropwithreset;
2285a57815efSBosko Milekic 	}
228680ab7c0eSGarrett Wollman 
2287fb59c426SYoshinobu Inoue 	todrop = tp->rcv_nxt - th->th_seq;
2288df8bae1dSRodney W. Grimes 	if (todrop > 0) {
2289831ad37eSXin LI 		if (thflags & TH_SYN) {
2290fb59c426SYoshinobu Inoue 			thflags &= ~TH_SYN;
2291fb59c426SYoshinobu Inoue 			th->th_seq++;
2292fb59c426SYoshinobu Inoue 			if (th->th_urp > 1)
2293fb59c426SYoshinobu Inoue 				th->th_urp--;
2294df8bae1dSRodney W. Grimes 			else
2295fb59c426SYoshinobu Inoue 				thflags &= ~TH_URG;
2296df8bae1dSRodney W. Grimes 			todrop--;
2297df8bae1dSRodney W. Grimes 		}
2298df8bae1dSRodney W. Grimes 		/*
2299dac20301SGarrett Wollman 		 * Following if statement from Stevens, vol. 2, p. 960.
2300df8bae1dSRodney W. Grimes 		 */
2301fb59c426SYoshinobu Inoue 		if (todrop > tlen
2302fb59c426SYoshinobu Inoue 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2303dac20301SGarrett Wollman 			/*
2304dac20301SGarrett Wollman 			 * Any valid FIN must be to the left of the window.
2305dac20301SGarrett Wollman 			 * At this point the FIN must be a duplicate or out
2306dac20301SGarrett Wollman 			 * of sequence; drop it.
2307dac20301SGarrett Wollman 			 */
2308fb59c426SYoshinobu Inoue 			thflags &= ~TH_FIN;
2309dac20301SGarrett Wollman 
2310df8bae1dSRodney W. Grimes 			/*
2311dac20301SGarrett Wollman 			 * Send an ACK to resynchronize and drop any data.
2312dac20301SGarrett Wollman 			 * But keep on processing for RST or ACK.
2313df8bae1dSRodney W. Grimes 			 */
2314dac20301SGarrett Wollman 			tp->t_flags |= TF_ACKNOW;
2315fb59c426SYoshinobu Inoue 			todrop = tlen;
231678b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvduppack);
231778b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2318df8bae1dSRodney W. Grimes 		} else {
231978b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpartduppack);
232078b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2321df8bae1dSRodney W. Grimes 		}
23225acfd95cSMichael Tuexen 		/*
23235acfd95cSMichael Tuexen 		 * DSACK - add SACK block for dropped range
23245acfd95cSMichael Tuexen 		 */
23258f63a52bSMichael Tuexen 		if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2326ecc5b1d1SMichael Tuexen 			tcp_update_sack_list(tp, th->th_seq,
2327ecc5b1d1SMichael Tuexen 			    th->th_seq + todrop);
23285acfd95cSMichael Tuexen 			/*
23295acfd95cSMichael Tuexen 			 * ACK now, as the next in-sequence segment
23305acfd95cSMichael Tuexen 			 * will clear the DSACK block again
23315acfd95cSMichael Tuexen 			 */
23325acfd95cSMichael Tuexen 			tp->t_flags |= TF_ACKNOW;
23335acfd95cSMichael Tuexen 		}
2334fb59c426SYoshinobu Inoue 		drop_hdrlen += todrop;	/* drop from the top afterwards */
2335fb59c426SYoshinobu Inoue 		th->th_seq += todrop;
2336fb59c426SYoshinobu Inoue 		tlen -= todrop;
2337fb59c426SYoshinobu Inoue 		if (th->th_urp > todrop)
2338fb59c426SYoshinobu Inoue 			th->th_urp -= todrop;
2339df8bae1dSRodney W. Grimes 		else {
2340fb59c426SYoshinobu Inoue 			thflags &= ~TH_URG;
2341fb59c426SYoshinobu Inoue 			th->th_urp = 0;
2342df8bae1dSRodney W. Grimes 		}
2343df8bae1dSRodney W. Grimes 	}
2344df8bae1dSRodney W. Grimes 
2345df8bae1dSRodney W. Grimes 	/*
2346df8bae1dSRodney W. Grimes 	 * If new data are received on a connection after the
2347c9cd686bSMichael Tuexen 	 * user processes are gone, then RST the other end if
2348c9cd686bSMichael Tuexen 	 * no FIN has been processed.
2349df8bae1dSRodney W. Grimes 	 */
2350c9cd686bSMichael Tuexen 	if ((tp->t_flags & TF_CLOSED) && tlen > 0 &&
2351c9cd686bSMichael Tuexen 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
235207dacf03SAndre Oppermann 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
235307dacf03SAndre Oppermann 			log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
235407dacf03SAndre Oppermann 			    "after socket was closed, "
235507dacf03SAndre Oppermann 			    "sending RST and removing tcpcb\n",
2356e31d8aa3SMike Silbersack 			    s, __func__, tcpstates[tp->t_state], tlen);
2357773673c1SAndre Oppermann 			free(s, M_TCPLOG);
2358773673c1SAndre Oppermann 		}
2359d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
2360d1b07f36SRandall Stewart 		/* tcp_close will kill the inp pre-log the Reset */
2361d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
2362df8bae1dSRodney W. Grimes 		tp = tcp_close(tp);
236378b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvafterclose);
2364a57815efSBosko Milekic 		rstreason = BANDLIM_UNLIMITED;
2365df8bae1dSRodney W. Grimes 		goto dropwithreset;
2366df8bae1dSRodney W. Grimes 	}
2367df8bae1dSRodney W. Grimes 
2368df8bae1dSRodney W. Grimes 	/*
2369df8bae1dSRodney W. Grimes 	 * If segment ends after window, drop trailing data
2370df8bae1dSRodney W. Grimes 	 * (and PUSH and FIN); if nothing left, just ACK.
2371df8bae1dSRodney W. Grimes 	 */
2372fb59c426SYoshinobu Inoue 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2373df8bae1dSRodney W. Grimes 	if (todrop > 0) {
237478b50714SRobert Watson 		TCPSTAT_INC(tcps_rcvpackafterwin);
2375fb59c426SYoshinobu Inoue 		if (todrop >= tlen) {
237678b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2377df8bae1dSRodney W. Grimes 			/*
2378df8bae1dSRodney W. Grimes 			 * If window is closed can only take segments at
2379df8bae1dSRodney W. Grimes 			 * window edge, and have to drop data and PUSH from
2380df8bae1dSRodney W. Grimes 			 * incoming segments.  Continue processing, but
2381df8bae1dSRodney W. Grimes 			 * remember to ack.  Otherwise, drop segment
2382df8bae1dSRodney W. Grimes 			 * and ack.
2383df8bae1dSRodney W. Grimes 			 */
2384fb59c426SYoshinobu Inoue 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2385df8bae1dSRodney W. Grimes 				tp->t_flags |= TF_ACKNOW;
238678b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvwinprobe);
2387df8bae1dSRodney W. Grimes 			} else
2388df8bae1dSRodney W. Grimes 				goto dropafterack;
2389df8bae1dSRodney W. Grimes 		} else
239078b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2391df8bae1dSRodney W. Grimes 		m_adj(m, -todrop);
2392fb59c426SYoshinobu Inoue 		tlen -= todrop;
2393fb59c426SYoshinobu Inoue 		thflags &= ~(TH_PUSH|TH_FIN);
2394df8bae1dSRodney W. Grimes 	}
2395df8bae1dSRodney W. Grimes 
2396df8bae1dSRodney W. Grimes 	/*
2397df8bae1dSRodney W. Grimes 	 * If last ACK falls within this segment's sequence numbers,
2398df8bae1dSRodney W. Grimes 	 * record its timestamp.
2399cf09195bSPaul Saab 	 * NOTE:
2400cf09195bSPaul Saab 	 * 1) That the test incorporates suggestions from the latest
2401a0292f23SGarrett Wollman 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
2402cf09195bSPaul Saab 	 * 2) That updating only on newer timestamps interferes with
2403cf09195bSPaul Saab 	 *    our earlier PAWS tests, so this check should be solely
2404cf09195bSPaul Saab 	 *    predicated on the sequence space of this segment.
2405cf09195bSPaul Saab 	 * 3) That we modify the segment boundary check to be
2406cf09195bSPaul Saab 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
2407cf09195bSPaul Saab 	 *    instead of RFC1323's
2408cf09195bSPaul Saab 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
2409cf09195bSPaul Saab 	 *    This modified check allows us to overcome RFC1323's
2410cf09195bSPaul Saab 	 *    limitations as described in Stevens TCP/IP Illustrated
2411cf09195bSPaul Saab 	 *    Vol. 2 p.869. In such cases, we can still calculate the
2412cf09195bSPaul Saab 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
2413df8bae1dSRodney W. Grimes 	 */
2414be2ac88cSJonathan Lemon 	if ((to.to_flags & TOF_TS) != 0 &&
2415cf09195bSPaul Saab 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2416cf09195bSPaul Saab 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2417cf09195bSPaul Saab 		((thflags & (TH_SYN|TH_FIN)) != 0))) {
2418d8951c8aSBjoern A. Zeeb 		tp->ts_recent_age = tcp_ts_getticks();
2419a0292f23SGarrett Wollman 		tp->ts_recent = to.to_tsval;
2420df8bae1dSRodney W. Grimes 	}
2421df8bae1dSRodney W. Grimes 
2422df8bae1dSRodney W. Grimes 	/*
2423a0292f23SGarrett Wollman 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
2424a0292f23SGarrett Wollman 	 * flag is on (half-synchronized state), then queue data for
2425a0292f23SGarrett Wollman 	 * later processing; else drop segment and return.
2426a0292f23SGarrett Wollman 	 */
2427fb59c426SYoshinobu Inoue 	if ((thflags & TH_ACK) == 0) {
2428a0292f23SGarrett Wollman 		if (tp->t_state == TCPS_SYN_RECEIVED ||
2429281a0fd4SPatrick Kelsey 		    (tp->t_flags & TF_NEEDSYN)) {
2430281a0fd4SPatrick Kelsey 			if (tp->t_state == TCPS_SYN_RECEIVED &&
2431dd7b86e2SGleb Smirnoff 			    (tp->t_flags & TF_FASTOPEN)) {
2432281a0fd4SPatrick Kelsey 				tp->snd_wnd = tiwin;
2433281a0fd4SPatrick Kelsey 				cc_conn_init(tp);
2434281a0fd4SPatrick Kelsey 			}
2435a0292f23SGarrett Wollman 			goto step6;
2436281a0fd4SPatrick Kelsey 		} else if (tp->t_flags & TF_ACKNOW)
24375e1aa279SDavid Malone 			goto dropafterack;
2438a0292f23SGarrett Wollman 		else
2439a0292f23SGarrett Wollman 			goto drop;
2440a0292f23SGarrett Wollman 	}
2441df8bae1dSRodney W. Grimes 
2442df8bae1dSRodney W. Grimes 	/*
2443df8bae1dSRodney W. Grimes 	 * Ack processing.
2444df8bae1dSRodney W. Grimes 	 */
2445df8bae1dSRodney W. Grimes 	switch (tp->t_state) {
2446df8bae1dSRodney W. Grimes 	/*
2447764d8cefSBill Fenner 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2448764d8cefSBill Fenner 	 * ESTABLISHED state and continue processing.
2449764d8cefSBill Fenner 	 * The ACK was checked above.
2450df8bae1dSRodney W. Grimes 	 */
2451df8bae1dSRodney W. Grimes 	case TCPS_SYN_RECEIVED:
2452a0292f23SGarrett Wollman 
245378b50714SRobert Watson 		TCPSTAT_INC(tcps_connects);
2454493105c2SGleb Smirnoff 		if (tp->t_flags & TF_SONOTCONN) {
2455493105c2SGleb Smirnoff 			/*
2456493105c2SGleb Smirnoff 			 * Usually SYN_RECEIVED had been created from a LISTEN,
2457493105c2SGleb Smirnoff 			 * and solisten_enqueue() has already marked the socket
2458493105c2SGleb Smirnoff 			 * layer as connected.  If it didn't, which can happen
2459493105c2SGleb Smirnoff 			 * only with an accept_filter(9), then the tp is marked
2460493105c2SGleb Smirnoff 			 * with TF_SONOTCONN.  The other reason for this mark
2461493105c2SGleb Smirnoff 			 * to be set is a simultaneous open, a SYN_RECEIVED
2462493105c2SGleb Smirnoff 			 * that had been created from SYN_SENT.
2463493105c2SGleb Smirnoff 			 */
2464493105c2SGleb Smirnoff 			tp->t_flags &= ~TF_SONOTCONN;
2465df8bae1dSRodney W. Grimes 			soisconnected(so);
2466e80062a2SGleb Smirnoff 		}
2467df8bae1dSRodney W. Grimes 		/* Do window scaling? */
2468df8bae1dSRodney W. Grimes 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2469df8bae1dSRodney W. Grimes 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2470df8bae1dSRodney W. Grimes 			tp->rcv_scale = tp->request_r_scale;
2471df8bae1dSRodney W. Grimes 		}
2472116ef4d6SMichael Tuexen 		tp->snd_wnd = tiwin;
2473a0292f23SGarrett Wollman 		/*
2474a0292f23SGarrett Wollman 		 * Make transitions:
2475a0292f23SGarrett Wollman 		 *      SYN-RECEIVED  -> ESTABLISHED
2476a0292f23SGarrett Wollman 		 *      SYN-RECEIVED* -> FIN-WAIT-1
2477a0292f23SGarrett Wollman 		 */
24789b8b58e0SJonathan Lemon 		tp->t_starttime = ticks;
2479dd7b86e2SGleb Smirnoff 		if ((tp->t_flags & TF_FASTOPEN) && tp->t_tfo_pending) {
2480281a0fd4SPatrick Kelsey 			tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2481281a0fd4SPatrick Kelsey 			tp->t_tfo_pending = NULL;
2482281a0fd4SPatrick Kelsey 		}
24838db239dcSMichael Tuexen 		if (tp->t_flags & TF_NEEDFIN) {
248408af8aacSRandall Stewart 			tp->t_acktime = ticks;
24858db239dcSMichael Tuexen 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
24868db239dcSMichael Tuexen 			tp->t_flags &= ~TF_NEEDFIN;
24878db239dcSMichael Tuexen 		} else {
24888db239dcSMichael Tuexen 			tcp_state_change(tp, TCPS_ESTABLISHED);
24898db239dcSMichael Tuexen 			TCP_PROBE5(accept__established, NULL, tp,
24908db239dcSMichael Tuexen 			    m, tp, th);
2491281a0fd4SPatrick Kelsey 			/*
2492281a0fd4SPatrick Kelsey 			 * TFO connections call cc_conn_init() during SYN
2493281a0fd4SPatrick Kelsey 			 * processing.  Calling it again here for such
2494281a0fd4SPatrick Kelsey 			 * connections is not harmless as it would undo the
2495281a0fd4SPatrick Kelsey 			 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2496281a0fd4SPatrick Kelsey 			 * is retransmitted.
2497281a0fd4SPatrick Kelsey 			 */
2498dd7b86e2SGleb Smirnoff 			if (!(tp->t_flags & TF_FASTOPEN))
2499dbc42409SLawrence Stewart 				cc_conn_init(tp);
25009077f387SGleb Smirnoff 			tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
25017ff19458SPaul Traina 		}
2502a0292f23SGarrett Wollman 		/*
2503b2ade6b1SRichard Scheffenegger 		 * Account for the ACK of our SYN prior to
2504b2ade6b1SRichard Scheffenegger 		 * regular ACK processing below, except for
2505b2ade6b1SRichard Scheffenegger 		 * simultaneous SYN, which is handled later.
2506b2ade6b1SRichard Scheffenegger 		 */
2507b2ade6b1SRichard Scheffenegger 		if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2508b2ade6b1SRichard Scheffenegger 			incforsyn = 1;
2509b2ade6b1SRichard Scheffenegger 		/*
2510a0292f23SGarrett Wollman 		 * If segment contains data or ACK, will call tcp_reass()
2511a0292f23SGarrett Wollman 		 * later; if not, do so now to pass queued data to user.
2512a0292f23SGarrett Wollman 		 */
2513032bf749SRichard Scheffenegger 		if (tlen == 0 && (thflags & TH_FIN) == 0) {
2514c28440dbSRandall Stewart 			(void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2515a0292f23SGarrett Wollman 			    (struct mbuf *)0);
2516c348e880SGleb Smirnoff 			tcp_handle_wakeup(tp);
2517032bf749SRichard Scheffenegger 		}
251860ee3bb2SAndre Oppermann 		tp->snd_wl1 = th->th_seq - 1;
251993b0017fSPhilippe Charnier 		/* FALLTHROUGH */
2520df8bae1dSRodney W. Grimes 
2521df8bae1dSRodney W. Grimes 	/*
2522df8bae1dSRodney W. Grimes 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2523df8bae1dSRodney W. Grimes 	 * ACKs.  If the ack is in the range
2524fb59c426SYoshinobu Inoue 	 *	tp->snd_una < th->th_ack <= tp->snd_max
2525fb59c426SYoshinobu Inoue 	 * then advance tp->snd_una to th->th_ack and drop
2526df8bae1dSRodney W. Grimes 	 * data from the retransmission queue.  If this ACK reflects
2527df8bae1dSRodney W. Grimes 	 * more up to date window information we update our window information.
2528df8bae1dSRodney W. Grimes 	 */
2529df8bae1dSRodney W. Grimes 	case TCPS_ESTABLISHED:
2530df8bae1dSRodney W. Grimes 	case TCPS_FIN_WAIT_1:
2531df8bae1dSRodney W. Grimes 	case TCPS_FIN_WAIT_2:
2532df8bae1dSRodney W. Grimes 	case TCPS_CLOSE_WAIT:
2533df8bae1dSRodney W. Grimes 	case TCPS_CLOSING:
2534df8bae1dSRodney W. Grimes 	case TCPS_LAST_ACK:
25355a53ca16SPaul Saab 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
253678b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvacktoomuch);
25375a53ca16SPaul Saab 			goto dropafterack;
25385a53ca16SPaul Saab 		}
2539c21b7b55SRichard Scheffenegger 		if (tcp_is_sack_recovery(tp, &to)) {
2540893ed42eSRichard Scheffenegger 			sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2541893ed42eSRichard Scheffenegger 			if ((sack_changed != SACK_NOCHANGE) &&
25420471a8c7SRichard Scheffenegger 			    (tp->t_flags & TF_LRD)) {
25430471a8c7SRichard Scheffenegger 				tcp_sack_lost_retransmission(tp, th);
25440471a8c7SRichard Scheffenegger 			}
25450471a8c7SRichard Scheffenegger 		} else
254612eeb81fSHiren Panchasara 			/*
254712eeb81fSHiren Panchasara 			 * Reset the value so that previous (valid) value
254812eeb81fSHiren Panchasara 			 * from the last ack with SACK doesn't get used.
254912eeb81fSHiren Panchasara 			 */
255012eeb81fSHiren Panchasara 			tp->sackhint.sacked_bytes = 0;
255139bc9de5SLawrence Stewart 
2552bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
255339bc9de5SLawrence Stewart 		/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
255439bc9de5SLawrence Stewart 		hhook_run_tcp_est_in(tp, th, &to);
2555bd79708dSJonathan T. Looney #endif
255639bc9de5SLawrence Stewart 
2557fb59c426SYoshinobu Inoue 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
25580c39d38dSGleb Smirnoff 			maxseg = tcp_maxseg(tp);
2559021eaf79SHiren Panchasara 			if (tlen == 0 &&
2560021eaf79SHiren Panchasara 			    (tiwin == tp->snd_wnd ||
2561021eaf79SHiren Panchasara 			    (tp->t_flags & TF_SACK_PERMIT))) {
256262b90589SPeter Wemm 				/*
256362b90589SPeter Wemm 				 * If this is the first time we've seen a
256462b90589SPeter Wemm 				 * FIN from the remote, this is not a
256562b90589SPeter Wemm 				 * duplicate and it needs to be processed
256662b90589SPeter Wemm 				 * normally.  This happens during a
256762b90589SPeter Wemm 				 * simultaneous close.
256862b90589SPeter Wemm 				 */
256962b90589SPeter Wemm 				if ((thflags & TH_FIN) &&
257062b90589SPeter Wemm 				    (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
257162b90589SPeter Wemm 					tp->t_dupacks = 0;
257262b90589SPeter Wemm 					break;
257362b90589SPeter Wemm 				}
257478b50714SRobert Watson 				TCPSTAT_INC(tcps_rcvdupack);
2575df8bae1dSRodney W. Grimes 				/*
2576df8bae1dSRodney W. Grimes 				 * If we have outstanding data (other than
2577df8bae1dSRodney W. Grimes 				 * a window probe), this is a completely
2578df8bae1dSRodney W. Grimes 				 * duplicate ack (ie, window info didn't
25795f30ec9bSEitan Adler 				 * change and FIN isn't set),
25805f30ec9bSEitan Adler 				 * the ack is the biggest we've
2581df8bae1dSRodney W. Grimes 				 * seen and we've seen exactly our rexmt
2582a4641f4eSPedro F. Giffuni 				 * threshold of them, assume a packet
2583df8bae1dSRodney W. Grimes 				 * has been dropped and retransmit it.
2584df8bae1dSRodney W. Grimes 				 * Kludge snd_nxt & the congestion
2585df8bae1dSRodney W. Grimes 				 * window so we send only this one
2586df8bae1dSRodney W. Grimes 				 * packet.
2587df8bae1dSRodney W. Grimes 				 *
2588df8bae1dSRodney W. Grimes 				 * We know we're losing at the current
2589df8bae1dSRodney W. Grimes 				 * window size so do congestion avoidance
2590df8bae1dSRodney W. Grimes 				 * (set ssthresh to half the current window
2591df8bae1dSRodney W. Grimes 				 * and pull our congestion window back to
2592df8bae1dSRodney W. Grimes 				 * the new ssthresh).
2593df8bae1dSRodney W. Grimes 				 *
2594df8bae1dSRodney W. Grimes 				 * Dup acks mean that packets have left the
2595df8bae1dSRodney W. Grimes 				 * network (they're now cached at the receiver)
2596df8bae1dSRodney W. Grimes 				 * so bump cwnd by the amount in the receiver
2597df8bae1dSRodney W. Grimes 				 * to keep a constant cwnd packets in the
2598df8bae1dSRodney W. Grimes 				 * network.
2599f2512ba1SRui Paulo 				 *
2600f2512ba1SRui Paulo 				 * When using TCP ECN, notify the peer that
2601f2512ba1SRui Paulo 				 * we reduced the cwnd.
2602df8bae1dSRodney W. Grimes 				 */
2603021eaf79SHiren Panchasara 				/*
2604021eaf79SHiren Panchasara 				 * Following 2 kinds of acks should not affect
2605021eaf79SHiren Panchasara 				 * dupack counting:
2606021eaf79SHiren Panchasara 				 * 1) Old acks
2607021eaf79SHiren Panchasara 				 * 2) Acks with SACK but without any new SACK
2608021eaf79SHiren Panchasara 				 * information in them. These could result from
2609021eaf79SHiren Panchasara 				 * any anomaly in the network like a switch
2610021eaf79SHiren Panchasara 				 * duplicating packets or a possible DoS attack.
2611021eaf79SHiren Panchasara 				 */
2612021eaf79SHiren Panchasara 				if (th->th_ack != tp->snd_una ||
2613c21b7b55SRichard Scheffenegger 				    (tcp_is_sack_recovery(tp, &to) &&
26142d05a1c8SRichard Scheffenegger 				    (sack_changed == SACK_NOCHANGE))) {
2615021eaf79SHiren Panchasara 					break;
26162d05a1c8SRichard Scheffenegger 				} else if (!tcp_timer_active(tp, TT_REXMT)) {
2617df8bae1dSRodney W. Grimes 					tp->t_dupacks = 0;
26182d05a1c8SRichard Scheffenegger 				} else if (++tp->t_dupacks > tcprexmtthresh ||
2619dbc42409SLawrence Stewart 					    IN_FASTRECOVERY(tp->t_flags)) {
26204b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
26214b7b743cSLawrence Stewart 					    CC_DUPACK);
26220e1d7c25SRichard Scheffenegger 					if (V_tcp_do_prr &&
262349a6fbe3SRichard Scheffenegger 					    IN_FASTRECOVERY(tp->t_flags) &&
262449a6fbe3SRichard Scheffenegger 					    (tp->t_flags & TF_SACK_PERMIT)) {
2625c7c325d0SRichard Scheffenegger 						tcp_do_prr_ack(tp, th, &to,
2626c7c325d0SRichard Scheffenegger 						    sack_changed, &maxseg);
2627c21b7b55SRichard Scheffenegger 					} else if (tcp_is_sack_recovery(tp, &to) &&
2628dbc42409SLawrence Stewart 						    IN_FASTRECOVERY(tp->t_flags)) {
2629808f11b7SPaul Saab 						int awnd;
263025e6f9edSPaul Saab 
263125e6f9edSPaul Saab 						/*
263225e6f9edSPaul Saab 						 * Compute the amount of data in flight first.
26334c3972f0SHiren Panchasara 						 * We can inject new data into the pipe iff
263425e6f9edSPaul Saab 						 * we have less than 1/2 the original window's
263525e6f9edSPaul Saab 						 * worth of data in flight.
263625e6f9edSPaul Saab 						 */
26372d05a1c8SRichard Scheffenegger 						if (V_tcp_do_newsack) {
263812eeb81fSHiren Panchasara 							awnd = tcp_compute_pipe(tp);
26392d05a1c8SRichard Scheffenegger 						} else {
2640808f11b7SPaul Saab 							awnd = (tp->snd_nxt - tp->snd_fack) +
26410077b016SPaul Saab 								tp->sackhint.sack_bytes_rexmit;
26422d05a1c8SRichard Scheffenegger 						}
2643808f11b7SPaul Saab 						if (awnd < tp->snd_ssthresh) {
26440c39d38dSGleb Smirnoff 							tp->snd_cwnd += maxseg;
264525e6f9edSPaul Saab 							if (tp->snd_cwnd > tp->snd_ssthresh)
264625e6f9edSPaul Saab 								tp->snd_cwnd = tp->snd_ssthresh;
264725e6f9edSPaul Saab 						}
26482d05a1c8SRichard Scheffenegger 					} else {
26490c39d38dSGleb Smirnoff 						tp->snd_cwnd += maxseg;
26502d05a1c8SRichard Scheffenegger 					}
265140fa3e40SGleb Smirnoff 					(void) tcp_output(tp);
265246f58482SJonathan Lemon 					goto drop;
26533c40e1d5SRichard Scheffenegger 				} else if (tp->t_dupacks == tcprexmtthresh ||
26543c40e1d5SRichard Scheffenegger 					    (tp->t_flags & TF_SACK_PERMIT &&
2655d1de2b05SRichard Scheffenegger 					     V_tcp_do_newsack &&
26563c40e1d5SRichard Scheffenegger 					     tp->sackhint.sacked_bytes >
26573c40e1d5SRichard Scheffenegger 					     (tcprexmtthresh - 1) * maxseg)) {
26583c40e1d5SRichard Scheffenegger enter_recovery:
26593c40e1d5SRichard Scheffenegger 					/*
26603c40e1d5SRichard Scheffenegger 					 * Above is the RFC6675 trigger condition of
26613c40e1d5SRichard Scheffenegger 					 * more than (dupthresh-1)*maxseg sacked data.
26623c40e1d5SRichard Scheffenegger 					 * If the count of holes in the
26633c40e1d5SRichard Scheffenegger 					 * scoreboard is >= dupthresh, we could
26643c40e1d5SRichard Scheffenegger 					 * also enter loss recovery, but don't
26653c40e1d5SRichard Scheffenegger 					 * have that value readily available.
26663c40e1d5SRichard Scheffenegger 					 */
26673c40e1d5SRichard Scheffenegger 					tp->t_dupacks = tcprexmtthresh;
2668cb942153SJeffrey Hsu 					tcp_seq onxt = tp->snd_nxt;
2669a0445c2eSJayanth Vijayaraghavan 
2670a0445c2eSJayanth Vijayaraghavan 					/*
26710e1d7c25SRichard Scheffenegger 					 * If we're doing sack, or prr, check
26720e1d7c25SRichard Scheffenegger 					 * to see if we're already in sack
2673a0445c2eSJayanth Vijayaraghavan 					 * recovery. If we're not doing sack,
2674a0445c2eSJayanth Vijayaraghavan 					 * check to see if we're in newreno
2675a0445c2eSJayanth Vijayaraghavan 					 * recovery.
2676a0445c2eSJayanth Vijayaraghavan 					 */
26770e1d7c25SRichard Scheffenegger 					if (V_tcp_do_prr ||
26780e1d7c25SRichard Scheffenegger 					    (tp->t_flags & TF_SACK_PERMIT)) {
2679dbc42409SLawrence Stewart 						if (IN_FASTRECOVERY(tp->t_flags)) {
2680a0445c2eSJayanth Vijayaraghavan 							tp->t_dupacks = 0;
2681a0445c2eSJayanth Vijayaraghavan 							break;
2682a0445c2eSJayanth Vijayaraghavan 						}
2683dbc42409SLawrence Stewart 					} else {
2684a0445c2eSJayanth Vijayaraghavan 						if (SEQ_LEQ(th->th_ack,
26859d11646dSJeffrey Hsu 						    tp->snd_recover)) {
2686cb942153SJeffrey Hsu 							tp->t_dupacks = 0;
2687cb942153SJeffrey Hsu 							break;
268846f58482SJonathan Lemon 						}
2689a0445c2eSJayanth Vijayaraghavan 					}
2690dbc42409SLawrence Stewart 					/* Congestion signal before ack. */
2691dbc42409SLawrence Stewart 					cc_cong_signal(tp, th, CC_NDUPACK);
26924b7b743cSLawrence Stewart 					cc_ack_received(tp, th, nsegs,
26934b7b743cSLawrence Stewart 					    CC_DUPACK);
2694b8152ba7SAndre Oppermann 					tcp_timer_activate(tp, TT_REXMT, 0);
26959b8b58e0SJonathan Lemon 					tp->t_rtttime = 0;
26960e1d7c25SRichard Scheffenegger 					if (V_tcp_do_prr) {
26970e1d7c25SRichard Scheffenegger 						/*
26980e1d7c25SRichard Scheffenegger 						 * snd_ssthresh is already updated by
26990e1d7c25SRichard Scheffenegger 						 * cc_cong_signal.
27000e1d7c25SRichard Scheffenegger 						 */
2701c21b7b55SRichard Scheffenegger 						if (tcp_is_sack_recovery(tp, &to)) {
270249a6fbe3SRichard Scheffenegger 							/*
270349a6fbe3SRichard Scheffenegger 							 * Exclude Limited Transmit
270449a6fbe3SRichard Scheffenegger 							 * segments here
270549a6fbe3SRichard Scheffenegger 							 */
2706e9071000SRichard Scheffenegger 							tp->sackhint.prr_delivered =
270749a6fbe3SRichard Scheffenegger 							    maxseg;
270874d7fc87SRichard Scheffenegger 						} else {
270974d7fc87SRichard Scheffenegger 							tp->sackhint.prr_delivered =
271074d7fc87SRichard Scheffenegger 							    imin(tp->snd_max - tp->snd_una,
271174d7fc87SRichard Scheffenegger 							    imin(INT_MAX / 65536,
271274d7fc87SRichard Scheffenegger 								tp->t_dupacks) * maxseg);
271374d7fc87SRichard Scheffenegger 						}
2714bc7ee8e5SRichard Scheffenegger 						tp->sackhint.recover_fs = max(1,
2715bc7ee8e5SRichard Scheffenegger 						    tp->snd_nxt - tp->snd_una);
27160e1d7c25SRichard Scheffenegger 					}
2717c21b7b55SRichard Scheffenegger 					if (tcp_is_sack_recovery(tp, &to)) {
27182d05a1c8SRichard Scheffenegger 						TCPSTAT_INC(tcps_sack_recovery_episode);
2719a3574665SMichael Tuexen 						tp->snd_recover = tp->snd_nxt;
27200c39d38dSGleb Smirnoff 						tp->snd_cwnd = maxseg;
272140fa3e40SGleb Smirnoff 						(void) tcp_output(tp);
27222d05a1c8SRichard Scheffenegger 						if (SEQ_GT(th->th_ack, tp->snd_una)) {
27233c40e1d5SRichard Scheffenegger 							goto resume_partialack;
27242d05a1c8SRichard Scheffenegger 						}
27256d90faf3SPaul Saab 						goto drop;
27266d90faf3SPaul Saab 					}
2727fb59c426SYoshinobu Inoue 					tp->snd_nxt = th->th_ack;
27280c39d38dSGleb Smirnoff 					tp->snd_cwnd = maxseg;
272940fa3e40SGleb Smirnoff 					(void) tcp_output(tp);
273048d2549cSJeffrey Hsu 					KASSERT(tp->snd_limited <= 2,
2731302ce8d6SAndre Oppermann 					    ("%s: tp->snd_limited too big",
2732302ce8d6SAndre Oppermann 					    __func__));
2733df8bae1dSRodney W. Grimes 					tp->snd_cwnd = tp->snd_ssthresh +
27340c39d38dSGleb Smirnoff 					     maxseg *
273548d2549cSJeffrey Hsu 					     (tp->t_dupacks - tp->snd_limited);
2736df8bae1dSRodney W. Grimes 					if (SEQ_GT(onxt, tp->snd_nxt))
2737df8bae1dSRodney W. Grimes 						tp->snd_nxt = onxt;
2738df8bae1dSRodney W. Grimes 					goto drop;
2739603724d3SBjoern A. Zeeb 				} else if (V_tcp_do_rfc3042) {
274062d4443fSHiren Panchasara 					/*
274162d4443fSHiren Panchasara 					 * Process first and second duplicate
274262d4443fSHiren Panchasara 					 * ACKs. Each indicates a segment
274362d4443fSHiren Panchasara 					 * leaving the network, creating room
274462d4443fSHiren Panchasara 					 * for more. Make sure we can send a
274562d4443fSHiren Panchasara 					 * packet on reception of each duplicate
274662d4443fSHiren Panchasara 					 * ACK by increasing snd_cwnd by one
274762d4443fSHiren Panchasara 					 * segment. Restore the original
274862d4443fSHiren Panchasara 					 * snd_cwnd after packet transmission.
274962d4443fSHiren Panchasara 					 */
27502d05a1c8SRichard Scheffenegger 					cc_ack_received(tp, th, nsegs, CC_DUPACK);
27513ac12506SJonathan T. Looney 					uint32_t oldcwnd = tp->snd_cwnd;
275248d2549cSJeffrey Hsu 					tcp_seq oldsndmax = tp->snd_max;
275348d2549cSJeffrey Hsu 					u_int sent;
27545628dd08SAndre Oppermann 					int avail;
275589c02376SJeffrey Hsu 
2756582a954bSJeffrey Hsu 					KASSERT(tp->t_dupacks == 1 ||
2757582a954bSJeffrey Hsu 					    tp->t_dupacks == 2,
2758302ce8d6SAndre Oppermann 					    ("%s: dupacks not 1 or 2",
2759302ce8d6SAndre Oppermann 					    __func__));
276061a36e3dSJeffrey Hsu 					if (tp->t_dupacks == 1)
276148d2549cSJeffrey Hsu 						tp->snd_limited = 0;
276261a36e3dSJeffrey Hsu 					tp->snd_cwnd =
276361a36e3dSJeffrey Hsu 					    (tp->snd_nxt - tp->snd_una) +
276461a36e3dSJeffrey Hsu 					    (tp->t_dupacks - tp->snd_limited) *
27650c39d38dSGleb Smirnoff 					    maxseg;
27665628dd08SAndre Oppermann 					/*
27675628dd08SAndre Oppermann 					 * Only call tcp_output when there
27685ae83e0dSMichael Tuexen 					 * is new data available to be sent
27695ae83e0dSMichael Tuexen 					 * or we need to send an ACK.
27705628dd08SAndre Oppermann 					 */
27715628dd08SAndre Oppermann 					SOCKBUF_LOCK(&so->so_snd);
27722d05a1c8SRichard Scheffenegger 					avail = sbavail(&so->so_snd);
27735628dd08SAndre Oppermann 					SOCKBUF_UNLOCK(&so->so_snd);
27742d05a1c8SRichard Scheffenegger 					if (tp->t_flags & TF_ACKNOW ||
27752d05a1c8SRichard Scheffenegger 					    (avail >=
27762d05a1c8SRichard Scheffenegger 					     SEQ_SUB(tp->snd_nxt, tp->snd_una))) {
277740fa3e40SGleb Smirnoff 						(void) tcp_output(tp);
27782d05a1c8SRichard Scheffenegger 					}
27792d05a1c8SRichard Scheffenegger 					sent = SEQ_SUB(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;
27882d05a1c8SRichard Scheffenegger 					} else if (sent > 0) {
278948d2549cSJeffrey Hsu 						++tp->snd_limited;
27902d05a1c8SRichard Scheffenegger 					}
2791582a954bSJeffrey Hsu 					tp->snd_cwnd = oldcwnd;
2792582a954bSJeffrey Hsu 					goto drop;
2793df8bae1dSRodney W. Grimes 				}
2794021eaf79SHiren Panchasara 			}
2795df8bae1dSRodney W. Grimes 			break;
2796021eaf79SHiren Panchasara 		} else {
2797021eaf79SHiren Panchasara 			/*
2798021eaf79SHiren Panchasara 			 * This ack is advancing the left edge, reset the
2799021eaf79SHiren Panchasara 			 * counter.
2800021eaf79SHiren Panchasara 			 */
2801021eaf79SHiren Panchasara 			tp->t_dupacks = 0;
2802021eaf79SHiren Panchasara 			/*
2803021eaf79SHiren Panchasara 			 * If this ack also has new SACK info, increment the
2804f359d6ebSRichard Scheffenegger 			 * counter as per rfc6675. The variable
2805f359d6ebSRichard Scheffenegger 			 * sack_changed tracks all changes to the SACK
2806f359d6ebSRichard Scheffenegger 			 * scoreboard, including when partial ACKs without
2807f359d6ebSRichard Scheffenegger 			 * SACK options are received, and clear the scoreboard
2808f359d6ebSRichard Scheffenegger 			 * from the left side. Such partial ACKs should not be
2809f359d6ebSRichard Scheffenegger 			 * counted as dupacks here.
2810021eaf79SHiren Panchasara 			 */
2811c21b7b55SRichard Scheffenegger 			if (tcp_is_sack_recovery(tp, &to) &&
281249a6fbe3SRichard Scheffenegger 			    (sack_changed != SACK_NOCHANGE)) {
2813021eaf79SHiren Panchasara 				tp->t_dupacks++;
28143c40e1d5SRichard Scheffenegger 				/* limit overhead by setting maxseg last */
28153c40e1d5SRichard Scheffenegger 				if (!IN_FASTRECOVERY(tp->t_flags) &&
28163c40e1d5SRichard Scheffenegger 				    (tp->sackhint.sacked_bytes >
28173c40e1d5SRichard Scheffenegger 				    ((tcprexmtthresh - 1) *
28183c40e1d5SRichard Scheffenegger 				    (maxseg = tcp_maxseg(tp))))) {
28193c40e1d5SRichard Scheffenegger 					goto enter_recovery;
28203c40e1d5SRichard Scheffenegger 				}
28213c40e1d5SRichard Scheffenegger 			}
2822df8bae1dSRodney W. Grimes 		}
2823cb942153SJeffrey Hsu 
28243c40e1d5SRichard Scheffenegger resume_partialack:
2825302ce8d6SAndre Oppermann 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2826302ce8d6SAndre Oppermann 		    ("%s: th_ack <= snd_una", __func__));
2827cb942153SJeffrey Hsu 
2828df8bae1dSRodney W. Grimes 		/*
2829df8bae1dSRodney W. Grimes 		 * If the congestion window was inflated to account
2830df8bae1dSRodney W. Grimes 		 * for the other side's cached packets, retract it.
2831df8bae1dSRodney W. Grimes 		 */
2832cb942153SJeffrey Hsu 		if (SEQ_LT(th->th_ack, tp->snd_recover)) {
28330b3f9e43SRichard Scheffenegger 			if (IN_FASTRECOVERY(tp->t_flags)) {
2834c7c325d0SRichard Scheffenegger 				if (tp->t_flags & TF_SACK_PERMIT) {
28350b3f9e43SRichard Scheffenegger 					if (V_tcp_do_prr &&
28360b3f9e43SRichard Scheffenegger 					    (to.to_flags & TOF_SACK)) {
28370b3f9e43SRichard Scheffenegger 						tcp_timer_activate(tp,
28380b3f9e43SRichard Scheffenegger 						    TT_REXMT, 0);
2839eb3a59a8SRichard Scheffenegger 						tp->t_rtttime = 0;
2840c7c325d0SRichard Scheffenegger 						tcp_do_prr_ack(tp, th, &to,
2841c7c325d0SRichard Scheffenegger 						    sack_changed, &maxseg);
2842eb3a59a8SRichard Scheffenegger 						tp->t_flags |= TF_ACKNOW;
2843eb3a59a8SRichard Scheffenegger 						(void) tcp_output(tp);
2844c7c325d0SRichard Scheffenegger 					} else {
2845c7c325d0SRichard Scheffenegger 						tcp_sack_partialack(tp, th,
2846c7c325d0SRichard Scheffenegger 						    &maxseg);
2847c7c325d0SRichard Scheffenegger 					}
2848c7c325d0SRichard Scheffenegger 				} else {
2849c068736aSJeffrey Hsu 					tcp_newreno_partial_ack(tp, th);
2850c7c325d0SRichard Scheffenegger 				}
28510b3f9e43SRichard Scheffenegger 			} else if (IN_CONGRECOVERY(tp->t_flags) &&
28520b3f9e43SRichard Scheffenegger 				    (V_tcp_do_prr)) {
28530b3f9e43SRichard Scheffenegger 				tp->sackhint.delivered_data =
28540b3f9e43SRichard Scheffenegger 				    BYTES_THIS_ACK(tp, th);
2855b9f803b7SRichard Scheffenegger 				tp->snd_fack = th->th_ack;
285649a6fbe3SRichard Scheffenegger 				/*
285749a6fbe3SRichard Scheffenegger 				 * During ECN cwnd reduction
285849a6fbe3SRichard Scheffenegger 				 * always use PRR-SSRB
285949a6fbe3SRichard Scheffenegger 				 */
2860c7c325d0SRichard Scheffenegger 				tcp_do_prr_ack(tp, th, &to, SACK_CHANGE,
2861c7c325d0SRichard Scheffenegger 				    &maxseg);
2862b9f803b7SRichard Scheffenegger 				(void) tcp_output(tp);
2863b9f803b7SRichard Scheffenegger 			}
2864c7c325d0SRichard Scheffenegger 		}
2865a0292f23SGarrett Wollman 		/*
2866a0292f23SGarrett Wollman 		 * If we reach this point, ACK is not a duplicate,
2867a0292f23SGarrett Wollman 		 *     i.e., it ACKs something we sent.
2868a0292f23SGarrett Wollman 		 */
2869a0292f23SGarrett Wollman 		if (tp->t_flags & TF_NEEDSYN) {
2870a0292f23SGarrett Wollman 			/*
2871a0292f23SGarrett Wollman 			 * T/TCP: Connection was half-synchronized, and our
2872a0292f23SGarrett Wollman 			 * SYN has been ACK'd (so connection is now fully
287307e43e10SAndras Olah 			 * synchronized).  Go to non-starred state,
287407e43e10SAndras Olah 			 * increment snd_una for ACK of SYN, and check if
287507e43e10SAndras Olah 			 * we can do window scaling.
2876a0292f23SGarrett Wollman 			 */
2877a0292f23SGarrett Wollman 			tp->t_flags &= ~TF_NEEDSYN;
2878a0292f23SGarrett Wollman 			tp->snd_una++;
287907e43e10SAndras Olah 			/* Do window scaling? */
288007e43e10SAndras Olah 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
288107e43e10SAndras Olah 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
288207e43e10SAndras Olah 				tp->rcv_scale = tp->request_r_scale;
2883464fcfbcSAndre Oppermann 				/* Send window already scaled. */
288407e43e10SAndras Olah 			}
2885a0292f23SGarrett Wollman 		}
2886a0292f23SGarrett Wollman 
2887a0292f23SGarrett Wollman process_ACK:
28889eb0e832SGleb Smirnoff 		INP_WLOCK_ASSERT(inp);
28897cfc6904SRobert Watson 
2890b2ade6b1SRichard Scheffenegger 		/*
2891b2ade6b1SRichard Scheffenegger 		 * Adjust for the SYN bit in sequence space,
2892b2ade6b1SRichard Scheffenegger 		 * but don't account for it in cwnd calculations.
2893b2ade6b1SRichard Scheffenegger 		 * This is for the SYN_RECEIVED, non-simultaneous
2894b2ade6b1SRichard Scheffenegger 		 * SYN case. SYN_SENT and simultaneous SYN are
2895b2ade6b1SRichard Scheffenegger 		 * treated elsewhere.
2896b2ade6b1SRichard Scheffenegger 		 */
2897b2ade6b1SRichard Scheffenegger 		if (incforsyn)
2898b2ade6b1SRichard Scheffenegger 			tp->snd_una++;
2899dbc42409SLawrence Stewart 		acked = BYTES_THIS_ACK(tp, th);
2900b8c2cd15SJonathan T. Looney 		KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2901b8c2cd15SJonathan T. Looney 		    "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2902b8c2cd15SJonathan T. Looney 		    tp->snd_una, th->th_ack, tp, m));
29034b7b743cSLawrence Stewart 		TCPSTAT_ADD(tcps_rcvackpack, nsegs);
290478b50714SRobert Watson 		TCPSTAT_ADD(tcps_rcvackbyte, acked);
2905df8bae1dSRodney W. Grimes 
2906df8bae1dSRodney W. Grimes 		/*
29079b8b58e0SJonathan Lemon 		 * If we just performed our first retransmit, and the ACK
29089b8b58e0SJonathan Lemon 		 * arrives within our recovery window, then it was a mistake
29099b8b58e0SJonathan Lemon 		 * to do the retransmit in the first place.  Recover our
29109b8b58e0SJonathan Lemon 		 * original cwnd and ssthresh, and proceed to transmit where
29119b8b58e0SJonathan Lemon 		 * we left off.
29129b8b58e0SJonathan Lemon 		 */
291310d20c84SMatt Macy 		if (tp->t_rxtshift == 1 &&
291410d20c84SMatt Macy 		    tp->t_flags & TF_PREVVALID &&
29154531b345SRichard Scheffenegger 		    tp->t_badrxtwin != 0 &&
29164531b345SRichard Scheffenegger 		    to.to_flags & TOF_TS &&
29174531b345SRichard Scheffenegger 		    to.to_tsecr != 0 &&
29184531b345SRichard Scheffenegger 		    TSTMP_LT(to.to_tsecr, tp->t_badrxtwin))
2919dbc42409SLawrence Stewart 			cc_cong_signal(tp, th, CC_RTO_ERR);
29209b8b58e0SJonathan Lemon 
29219b8b58e0SJonathan Lemon 		/*
2922df8bae1dSRodney W. Grimes 		 * If we have a timestamp reply, update smoothed
2923df8bae1dSRodney W. Grimes 		 * round trip time.  If no timestamp is present but
2924df8bae1dSRodney W. Grimes 		 * transmit timer is running and timed sequence
2925df8bae1dSRodney W. Grimes 		 * number was acked, update smoothed round trip time.
2926df8bae1dSRodney W. Grimes 		 * Since we now have an rtt measurement, cancel the
2927df8bae1dSRodney W. Grimes 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2928df8bae1dSRodney W. Grimes 		 * Recompute the initial retransmit timer.
2929fa55172bSMatthew Dillon 		 *
2930fa55172bSMatthew Dillon 		 * Some boxes send broken timestamp replies
2931fa55172bSMatthew Dillon 		 * during the SYN+ACK phase, ignore
2932fa55172bSMatthew Dillon 		 * timestamps of 0 or we could calculate a
2933fa55172bSMatthew Dillon 		 * huge RTT and blow up the retransmit timer.
2934df8bae1dSRodney W. Grimes 		 */
2935d8951c8aSBjoern A. Zeeb 		if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
29363ac12506SJonathan T. Looney 			uint32_t t;
2937d8951c8aSBjoern A. Zeeb 
2938d8951c8aSBjoern A. Zeeb 			t = tcp_ts_getticks() - to.to_tsecr;
2939d8951c8aSBjoern A. Zeeb 			if (!tp->t_rttlow || tp->t_rttlow > t)
2940d8951c8aSBjoern A. Zeeb 				tp->t_rttlow = t;
2941d8951c8aSBjoern A. Zeeb 			tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2942fa55172bSMatthew Dillon 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2943eaf80179SAndre Oppermann 			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2944eaf80179SAndre Oppermann 				tp->t_rttlow = ticks - tp->t_rtttime;
29459b8b58e0SJonathan Lemon 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2946fa55172bSMatthew Dillon 		}
2947df8bae1dSRodney W. Grimes 
294808af8aacSRandall Stewart 		SOCKBUF_LOCK(&so->so_snd);
294908af8aacSRandall Stewart 		/*
295008af8aacSRandall Stewart 		 * Clear t_acktime if remote side has ACKd all data in the
295108af8aacSRandall Stewart 		 * socket buffer and FIN (if applicable).
295208af8aacSRandall Stewart 		 * Otherwise, update t_acktime if we received a sufficiently
295308af8aacSRandall Stewart 		 * large ACK.
295408af8aacSRandall Stewart 		 */
295508af8aacSRandall Stewart 		if ((tp->t_state <= TCPS_CLOSE_WAIT &&
295608af8aacSRandall Stewart 		    acked == sbavail(&so->so_snd)) ||
295708af8aacSRandall Stewart 		    acked > sbavail(&so->so_snd))
295808af8aacSRandall Stewart 			tp->t_acktime = 0;
295908af8aacSRandall Stewart 		else if (acked > 1)
296008af8aacSRandall Stewart 			tp->t_acktime = ticks;
296108af8aacSRandall Stewart 
2962df8bae1dSRodney W. Grimes 		/*
2963df8bae1dSRodney W. Grimes 		 * If all outstanding data is acked, stop retransmit
2964df8bae1dSRodney W. Grimes 		 * timer and remember to restart (more output or persist).
2965df8bae1dSRodney W. Grimes 		 * If there is more data to be acked, restart retransmit
2966df8bae1dSRodney W. Grimes 		 * timer, using current (possibly backed-off) value.
2967df8bae1dSRodney W. Grimes 		 */
2968fb59c426SYoshinobu Inoue 		if (th->th_ack == tp->snd_max) {
2969b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
2970df8bae1dSRodney W. Grimes 			needoutput = 1;
2971b8152ba7SAndre Oppermann 		} else if (!tcp_timer_active(tp, TT_PERSIST))
297208af8aacSRandall Stewart 			tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp));
2973a0292f23SGarrett Wollman 
2974a0292f23SGarrett Wollman 		/*
2975a0292f23SGarrett Wollman 		 * If no data (only SYN) was ACK'd,
2976a0292f23SGarrett Wollman 		 *    skip rest of ACK processing.
2977a0292f23SGarrett Wollman 		 */
297808af8aacSRandall Stewart 		if (acked == 0) {
297908af8aacSRandall Stewart 			SOCKBUF_UNLOCK(&so->so_snd);
2980a0292f23SGarrett Wollman 			goto step6;
298108af8aacSRandall Stewart 		}
2982a0292f23SGarrett Wollman 
2983df8bae1dSRodney W. Grimes 		/*
2984dbc42409SLawrence Stewart 		 * Let the congestion control algorithm update congestion
2985dbc42409SLawrence Stewart 		 * control related information. This typically means increasing
2986dbc42409SLawrence Stewart 		 * the congestion window.
2987df8bae1dSRodney W. Grimes 		 */
29884b7b743cSLawrence Stewart 		cc_ack_received(tp, th, nsegs, CC_ACK);
2989dbc42409SLawrence Stewart 
2990cfa6009eSGleb Smirnoff 		if (acked > sbavail(&so->so_snd)) {
2991b8c2cd15SJonathan T. Looney 			if (tp->snd_wnd >= sbavail(&so->so_snd))
2992cfa6009eSGleb Smirnoff 				tp->snd_wnd -= sbavail(&so->so_snd);
2993b8c2cd15SJonathan T. Looney 			else
2994b8c2cd15SJonathan T. Looney 				tp->snd_wnd = 0;
2995c11a15bfSGleb Smirnoff 			mfree = sbcut_locked(&so->so_snd,
2996cfa6009eSGleb Smirnoff 			    (int)sbavail(&so->so_snd));
2997df8bae1dSRodney W. Grimes 			ourfinisacked = 1;
2998df8bae1dSRodney W. Grimes 		} else {
2999c11a15bfSGleb Smirnoff 			mfree = sbcut_locked(&so->so_snd, acked);
30003ac12506SJonathan T. Looney 			if (tp->snd_wnd >= (uint32_t) acked)
300160ee3bb2SAndre Oppermann 				tp->snd_wnd -= acked;
3002b8c2cd15SJonathan T. Looney 			else
3003b8c2cd15SJonathan T. Looney 				tp->snd_wnd = 0;
3004df8bae1dSRodney W. Grimes 			ourfinisacked = 0;
3005df8bae1dSRodney W. Grimes 		}
3006032bf749SRichard Scheffenegger 		/* NB: sowwakeup_locked() does an implicit unlock. */
3007032bf749SRichard Scheffenegger 		sowwakeup_locked(so);
3008c11a15bfSGleb Smirnoff 		m_freem(mfree);
3009e8949f74SAndre Oppermann 		/* Detect una wraparound. */
3010dbc42409SLawrence Stewart 		if (!IN_RECOVERY(tp->t_flags) &&
30119d11646dSJeffrey Hsu 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
30129d11646dSJeffrey Hsu 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
30139d11646dSJeffrey Hsu 			tp->snd_recover = th->th_ack - 1;
30140b3f9e43SRichard Scheffenegger 		tp->snd_una = th->th_ack;
3015dbc42409SLawrence Stewart 		if (IN_RECOVERY(tp->t_flags) &&
301624cb0f22SLawrence Stewart 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
30170b3f9e43SRichard Scheffenegger 			cc_post_recovery(tp, th);
301824cb0f22SLawrence Stewart 		}
30193529149eSAndre Oppermann 		if (tp->t_flags & TF_SACK_PERMIT) {
30206d90faf3SPaul Saab 			if (SEQ_GT(tp->snd_una, tp->snd_recover))
30216d90faf3SPaul Saab 				tp->snd_recover = tp->snd_una;
30226d90faf3SPaul Saab 		}
3023df8bae1dSRodney W. Grimes 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
3024df8bae1dSRodney W. Grimes 			tp->snd_nxt = tp->snd_una;
3025df8bae1dSRodney W. Grimes 
3026df8bae1dSRodney W. Grimes 		switch (tp->t_state) {
3027df8bae1dSRodney W. Grimes 		/*
3028df8bae1dSRodney W. Grimes 		 * In FIN_WAIT_1 STATE in addition to the processing
3029df8bae1dSRodney W. Grimes 		 * for the ESTABLISHED state if our FIN is now acknowledged
3030df8bae1dSRodney W. Grimes 		 * then enter FIN_WAIT_2.
3031df8bae1dSRodney W. Grimes 		 */
3032df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_1:
3033df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
3034df8bae1dSRodney W. Grimes 				/*
3035df8bae1dSRodney W. Grimes 				 * If we can't receive any more
3036df8bae1dSRodney W. Grimes 				 * data, then closing user can proceed.
3037df8bae1dSRodney W. Grimes 				 * Starting the timer is contrary to the
3038df8bae1dSRodney W. Grimes 				 * specification, but if we don't get a FIN
3039df8bae1dSRodney W. Grimes 				 * we'll hang forever.
3040340c35deSJonathan Lemon 				 */
3041c0b99ffaSRobert Watson 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
30423eeb22cbSRichard Scheffenegger 					tcp_free_sackholes(tp);
304303e49181SSeigo Tanimura 					soisdisconnected(so);
30449077f387SGleb Smirnoff 					tcp_timer_activate(tp, TT_2MSL,
30459077f387SGleb Smirnoff 					    (tcp_fast_finwait2_recycle ?
30469077f387SGleb Smirnoff 					    tcp_finwait2_timeout :
30479077f387SGleb Smirnoff 					    TP_MAXIDLE(tp)));
30484cc20ab1SSeigo Tanimura 				}
304957f60867SMark Johnston 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
3050df8bae1dSRodney W. Grimes 			}
3051df8bae1dSRodney W. Grimes 			break;
3052df8bae1dSRodney W. Grimes 
3053df8bae1dSRodney W. Grimes 		/*
3054df8bae1dSRodney W. Grimes 		 * In CLOSING STATE in addition to the processing for
3055df8bae1dSRodney W. Grimes 		 * the ESTABLISHED state if the ACK acknowledges our FIN
3056df8bae1dSRodney W. Grimes 		 * then enter the TIME-WAIT state, otherwise ignore
3057df8bae1dSRodney W. Grimes 		 * the segment.
3058df8bae1dSRodney W. Grimes 		 */
3059df8bae1dSRodney W. Grimes 		case TCPS_CLOSING:
3060df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
306111a20fb8SJeffrey Hsu 				tcp_twstart(tp);
3062340c35deSJonathan Lemon 				m_freem(m);
3063679d9708SAndre Oppermann 				return;
3064df8bae1dSRodney W. Grimes 			}
3065df8bae1dSRodney W. Grimes 			break;
3066df8bae1dSRodney W. Grimes 
3067df8bae1dSRodney W. Grimes 		/*
3068df8bae1dSRodney W. Grimes 		 * In LAST_ACK, we may still be waiting for data to drain
3069df8bae1dSRodney W. Grimes 		 * and/or to be acked, as well as for the ack of our FIN.
3070df8bae1dSRodney W. Grimes 		 * If our FIN is now acknowledged, delete the TCB,
3071df8bae1dSRodney W. Grimes 		 * enter the closed state and return.
3072df8bae1dSRodney W. Grimes 		 */
3073df8bae1dSRodney W. Grimes 		case TCPS_LAST_ACK:
3074df8bae1dSRodney W. Grimes 			if (ourfinisacked) {
3075df8bae1dSRodney W. Grimes 				tp = tcp_close(tp);
3076df8bae1dSRodney W. Grimes 				goto drop;
3077df8bae1dSRodney W. Grimes 			}
3078df8bae1dSRodney W. Grimes 			break;
3079df8bae1dSRodney W. Grimes 		}
3080df8bae1dSRodney W. Grimes 	}
3081df8bae1dSRodney W. Grimes 
3082df8bae1dSRodney W. Grimes step6:
30839eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
30847cfc6904SRobert Watson 
3085df8bae1dSRodney W. Grimes 	/*
308660ee3bb2SAndre Oppermann 	 * Update window information.
308760ee3bb2SAndre Oppermann 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
3088df8bae1dSRodney W. Grimes 	 */
308960ee3bb2SAndre Oppermann 	if ((thflags & TH_ACK) &&
309060ee3bb2SAndre Oppermann 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
309160ee3bb2SAndre Oppermann 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
309260ee3bb2SAndre Oppermann 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
309360ee3bb2SAndre Oppermann 		/* keep track of pure window updates */
309460ee3bb2SAndre Oppermann 		if (tlen == 0 &&
309560ee3bb2SAndre Oppermann 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
309678b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvwinupd);
3097df8bae1dSRodney W. Grimes 		tp->snd_wnd = tiwin;
309860ee3bb2SAndre Oppermann 		tp->snd_wl1 = th->th_seq;
309960ee3bb2SAndre Oppermann 		tp->snd_wl2 = th->th_ack;
3100df8bae1dSRodney W. Grimes 		if (tp->snd_wnd > tp->max_sndwnd)
3101df8bae1dSRodney W. Grimes 			tp->max_sndwnd = tp->snd_wnd;
310260ee3bb2SAndre Oppermann 		needoutput = 1;
3103df8bae1dSRodney W. Grimes 	}
3104df8bae1dSRodney W. Grimes 
3105df8bae1dSRodney W. Grimes 	/*
3106df8bae1dSRodney W. Grimes 	 * Process segments with URG.
3107df8bae1dSRodney W. Grimes 	 */
3108fb59c426SYoshinobu Inoue 	if ((thflags & TH_URG) && th->th_urp &&
3109df8bae1dSRodney W. Grimes 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3110df8bae1dSRodney W. Grimes 		/*
3111df8bae1dSRodney W. Grimes 		 * This is a kludge, but if we receive and accept
3112df8bae1dSRodney W. Grimes 		 * random urgent pointers, we'll crash in
3113df8bae1dSRodney W. Grimes 		 * soreceive.  It's hard to imagine someone
3114df8bae1dSRodney W. Grimes 		 * actually wanting to send this much urgent data.
3115df8bae1dSRodney W. Grimes 		 */
311618ad5842SRobert Watson 		SOCKBUF_LOCK(&so->so_rcv);
3117cfa6009eSGleb Smirnoff 		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
3118fb59c426SYoshinobu Inoue 			th->th_urp = 0;			/* XXX */
3119fb59c426SYoshinobu Inoue 			thflags &= ~TH_URG;		/* XXX */
312018ad5842SRobert Watson 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
3121df8bae1dSRodney W. Grimes 			goto dodata;			/* XXX */
3122df8bae1dSRodney W. Grimes 		}
3123df8bae1dSRodney W. Grimes 		/*
3124df8bae1dSRodney W. Grimes 		 * If this segment advances the known urgent pointer,
3125df8bae1dSRodney W. Grimes 		 * then mark the data stream.  This should not happen
3126df8bae1dSRodney W. Grimes 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
3127df8bae1dSRodney W. Grimes 		 * a FIN has been received from the remote side.
3128df8bae1dSRodney W. Grimes 		 * In these states we ignore the URG.
3129df8bae1dSRodney W. Grimes 		 *
3130df8bae1dSRodney W. Grimes 		 * According to RFC961 (Assigned Protocols),
3131df8bae1dSRodney W. Grimes 		 * the urgent pointer points to the last octet
3132df8bae1dSRodney W. Grimes 		 * of urgent data.  We continue, however,
3133df8bae1dSRodney W. Grimes 		 * to consider it to indicate the first octet
3134df8bae1dSRodney W. Grimes 		 * of data past the urgent section as the original
3135df8bae1dSRodney W. Grimes 		 * spec states (in one of two places).
3136df8bae1dSRodney W. Grimes 		 */
3137fb59c426SYoshinobu Inoue 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
3138fb59c426SYoshinobu Inoue 			tp->rcv_up = th->th_seq + th->th_urp;
3139cfa6009eSGleb Smirnoff 			so->so_oobmark = sbavail(&so->so_rcv) +
3140df8bae1dSRodney W. Grimes 			    (tp->rcv_up - tp->rcv_nxt) - 1;
3141927c5ceaSRobert Watson 			if (so->so_oobmark == 0)
3142c0b99ffaSRobert Watson 				so->so_rcv.sb_state |= SBS_RCVATMARK;
3143df8bae1dSRodney W. Grimes 			sohasoutofband(so);
3144df8bae1dSRodney W. Grimes 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
3145df8bae1dSRodney W. Grimes 		}
314618ad5842SRobert Watson 		SOCKBUF_UNLOCK(&so->so_rcv);
3147df8bae1dSRodney W. Grimes 		/*
3148df8bae1dSRodney W. Grimes 		 * Remove out of band data so doesn't get presented to user.
3149df8bae1dSRodney W. Grimes 		 * This can happen independent of advancing the URG pointer,
3150df8bae1dSRodney W. Grimes 		 * but if two URG's are pending at once, some out-of-band
3151df8bae1dSRodney W. Grimes 		 * data may creep in... ick.
3152df8bae1dSRodney W. Grimes 		 */
31533ac12506SJonathan T. Looney 		if (th->th_urp <= (uint32_t)tlen &&
315430613f56SJeffrey Hsu 		    !(so->so_options & SO_OOBINLINE)) {
315530613f56SJeffrey Hsu 			/* hdr drop is delayed */
315630613f56SJeffrey Hsu 			tcp_pulloutofband(so, th, m, drop_hdrlen);
315730613f56SJeffrey Hsu 		}
3158c068736aSJeffrey Hsu 	} else {
3159df8bae1dSRodney W. Grimes 		/*
3160df8bae1dSRodney W. Grimes 		 * If no out of band data is expected,
3161df8bae1dSRodney W. Grimes 		 * pull receive urgent pointer along
3162df8bae1dSRodney W. Grimes 		 * with the receive window.
3163df8bae1dSRodney W. Grimes 		 */
3164df8bae1dSRodney W. Grimes 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3165df8bae1dSRodney W. Grimes 			tp->rcv_up = tp->rcv_nxt;
3166c068736aSJeffrey Hsu 	}
3167df8bae1dSRodney W. Grimes dodata:							/* XXX */
31689eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
31697cfc6904SRobert Watson 
3170df8bae1dSRodney W. Grimes 	/*
3171df8bae1dSRodney W. Grimes 	 * Process the segment text, merging it into the TCP sequencing queue,
3172df8bae1dSRodney W. Grimes 	 * and arranging for acknowledgment of receipt if necessary.
3173df8bae1dSRodney W. Grimes 	 * This process logically involves adjusting tp->rcv_wnd as data
3174df8bae1dSRodney W. Grimes 	 * is presented to the user (this happens in tcp_usrreq.c,
3175df8bae1dSRodney W. Grimes 	 * case PRU_RCVD).  If a FIN has already been received on this
3176df8bae1dSRodney W. Grimes 	 * connection then we just ignore the text.
3177df8bae1dSRodney W. Grimes 	 */
3178281a0fd4SPatrick Kelsey 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3179dd7b86e2SGleb Smirnoff 	    (tp->t_flags & TF_FASTOPEN));
3180f1ea4e41SRandall Stewart 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
3181df8bae1dSRodney W. Grimes 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
318269e03620SPaul Saab 		tcp_seq save_start = th->th_seq;
31835acfd95cSMichael Tuexen 		tcp_seq save_rnxt  = tp->rcv_nxt;
31845acfd95cSMichael Tuexen 		int     save_tlen  = tlen;
3185fb59c426SYoshinobu Inoue 		m_adj(m, drop_hdrlen);	/* delayed header drop */
3186e4b64281SJesper Skriver 		/*
3187c068736aSJeffrey Hsu 		 * Insert segment which includes th into TCP reassembly queue
3188c068736aSJeffrey Hsu 		 * with control block tp.  Set thflags to whether reassembly now
3189c068736aSJeffrey Hsu 		 * includes a segment with FIN.  This handles the common case
3190c068736aSJeffrey Hsu 		 * inline (segment is the next to be received on an established
3191c068736aSJeffrey Hsu 		 * connection, and the queue is empty), avoiding linkage into
3192c068736aSJeffrey Hsu 		 * and removal from the queue and repetition of various
3193c068736aSJeffrey Hsu 		 * conversions.
3194c068736aSJeffrey Hsu 		 * Set DELACK for segments received in order, but ack
3195c068736aSJeffrey Hsu 		 * immediately when segments are out of order (so
3196c068736aSJeffrey Hsu 		 * fast retransmit can work).
3197e4b64281SJesper Skriver 		 */
31984741bfcbSPatrick Kelsey 		if (th->th_seq == tp->rcv_nxt &&
3199c28440dbSRandall Stewart 		    SEGQ_EMPTY(tp) &&
3200281a0fd4SPatrick Kelsey 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
3201281a0fd4SPatrick Kelsey 		     tfo_syn)) {
3202281a0fd4SPatrick Kelsey 			if (DELAY_ACK(tp, tlen) || tfo_syn)
32033bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
3204e4b64281SJesper Skriver 			else
3205e4b64281SJesper Skriver 				tp->t_flags |= TF_ACKNOW;
3206e4b64281SJesper Skriver 			tp->rcv_nxt += tlen;
3207e854dd38SRandall Stewart 			if (tlen &&
3208e854dd38SRandall Stewart 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
3209e854dd38SRandall Stewart 			    (tp->t_fbyte_in == 0)) {
3210e854dd38SRandall Stewart 				tp->t_fbyte_in = ticks;
3211e854dd38SRandall Stewart 				if (tp->t_fbyte_in == 0)
3212e854dd38SRandall Stewart 					tp->t_fbyte_in = 1;
3213e854dd38SRandall Stewart 				if (tp->t_fbyte_out && tp->t_fbyte_in)
3214e854dd38SRandall Stewart 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
3215e854dd38SRandall Stewart 			}
32161ebf4607SRichard Scheffenegger 			thflags = tcp_get_flags(th) & TH_FIN;
321778b50714SRobert Watson 			TCPSTAT_INC(tcps_rcvpack);
321878b50714SRobert Watson 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
32191e4d7da7SRobert Watson 			SOCKBUF_LOCK(&so->so_rcv);
3220c0b99ffaSRobert Watson 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3221c1c36a2cSMike Silbersack 				m_freem(m);
3222c1c36a2cSMike Silbersack 			else
3223651e4e6aSGleb Smirnoff 				sbappendstream_locked(&so->so_rcv, m, 0);
32244d0770f1SRichard Scheffenegger 			tp->t_flags |= TF_WAKESOR;
3225e4b64281SJesper Skriver 		} else {
3226e8949f74SAndre Oppermann 			/*
3227e8949f74SAndre Oppermann 			 * XXX: Due to the header drop above "th" is
3228e8949f74SAndre Oppermann 			 * theoretically invalid by now.  Fortunately
3229e8949f74SAndre Oppermann 			 * m_adj() doesn't actually frees any mbufs
3230e8949f74SAndre Oppermann 			 * when trimming from the head.
3231e8949f74SAndre Oppermann 			 */
32325acfd95cSMichael Tuexen 			tcp_seq temp = save_start;
32334747500dSRandall Stewart 
32345acfd95cSMichael Tuexen 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
3235e4b64281SJesper Skriver 			tp->t_flags |= TF_ACKNOW;
3236e4b64281SJesper Skriver 		}
323740f41eceSMichael Tuexen 		if ((tp->t_flags & TF_SACK_PERMIT) &&
323840f41eceSMichael Tuexen 		    (save_tlen > 0) &&
323940f41eceSMichael Tuexen 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
32406d261981SMichael Tuexen 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3241b5a154d8SMichael Tuexen 				/*
3242b5a154d8SMichael Tuexen 				 * DSACK actually handled in the fastpath
3243b5a154d8SMichael Tuexen 				 * above.
3244b5a154d8SMichael Tuexen 				 */
3245ecc5b1d1SMichael Tuexen 				tcp_update_sack_list(tp, save_start,
3246ecc5b1d1SMichael Tuexen 				    save_start + save_tlen);
3247ecc5b1d1SMichael Tuexen 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3248ecc5b1d1SMichael Tuexen 				if ((tp->rcv_numsacks >= 1) &&
3249ecc5b1d1SMichael Tuexen 				    (tp->sackblks[0].end == save_start)) {
32506d261981SMichael Tuexen 					/*
32516d261981SMichael Tuexen 					 * Partial overlap, recorded at todrop
32526d261981SMichael Tuexen 					 * above.
32536d261981SMichael Tuexen 					 */
32546d261981SMichael Tuexen 					tcp_update_sack_list(tp,
32556d261981SMichael Tuexen 					    tp->sackblks[0].start,
3256ecc5b1d1SMichael Tuexen 					    tp->sackblks[0].end);
3257ecc5b1d1SMichael Tuexen 				} else {
3258ecc5b1d1SMichael Tuexen 					tcp_update_dsack_list(tp, save_start,
3259ecc5b1d1SMichael Tuexen 					    save_start + save_tlen);
3260ecc5b1d1SMichael Tuexen 				}
32616d261981SMichael Tuexen 			} else if (tlen >= save_tlen) {
3262b5a154d8SMichael Tuexen 				/* Update of sackblks. */
3263ecc5b1d1SMichael Tuexen 				tcp_update_dsack_list(tp, save_start,
3264ecc5b1d1SMichael Tuexen 				    save_start + save_tlen);
3265ecc5b1d1SMichael Tuexen 			} else if (tlen > 0) {
3266ecc5b1d1SMichael Tuexen 				tcp_update_dsack_list(tp, save_start,
3267ecc5b1d1SMichael Tuexen 				    save_start + tlen);
32685acfd95cSMichael Tuexen 			}
32695acfd95cSMichael Tuexen 		}
3270c348e880SGleb Smirnoff 		tcp_handle_wakeup(tp);
3271302ce8d6SAndre Oppermann #if 0
3272df8bae1dSRodney W. Grimes 		/*
3273df8bae1dSRodney W. Grimes 		 * Note the amount of data that peer has sent into
3274df8bae1dSRodney W. Grimes 		 * our window, in order to estimate the sender's
3275df8bae1dSRodney W. Grimes 		 * buffer size.
3276302ce8d6SAndre Oppermann 		 * XXX: Unused.
3277df8bae1dSRodney W. Grimes 		 */
3278f701e30dSJohn Baldwin 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3279df8bae1dSRodney W. Grimes 			len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3280f701e30dSJohn Baldwin 		else
3281f701e30dSJohn Baldwin 			len = so->so_rcv.sb_hiwat;
3282302ce8d6SAndre Oppermann #endif
3283df8bae1dSRodney W. Grimes 	} else {
3284e8c149abSMichael Tuexen 		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
3285e8c149abSMichael Tuexen 			if (tlen > 0) {
3286e8c149abSMichael Tuexen 				if ((thflags & TH_FIN) != 0) {
3287e8c149abSMichael Tuexen 					log(LOG_DEBUG, "%s; %s: %s: "
3288e8c149abSMichael Tuexen 					    "Received %d bytes of data and FIN "
3289e8c149abSMichael Tuexen 					    "after having received a FIN, "
3290e8c149abSMichael Tuexen 					    "just dropping both\n",
3291e8c149abSMichael Tuexen 					    s, __func__,
3292e8c149abSMichael Tuexen 					    tcpstates[tp->t_state], tlen);
3293e8c149abSMichael Tuexen 				} else {
3294e8c149abSMichael Tuexen 					log(LOG_DEBUG, "%s; %s: %s: "
3295e8c149abSMichael Tuexen 					    "Received %d bytes of data "
3296e8c149abSMichael Tuexen 					    "after having received a FIN, "
3297e8c149abSMichael Tuexen 					    "just dropping it\n",
3298e8c149abSMichael Tuexen 					    s, __func__,
3299e8c149abSMichael Tuexen 					    tcpstates[tp->t_state], tlen);
3300e8c149abSMichael Tuexen 				}
3301e8c149abSMichael Tuexen 			} else {
3302e8c149abSMichael Tuexen 				if ((thflags & TH_FIN) != 0) {
3303e8c149abSMichael Tuexen 					log(LOG_DEBUG, "%s; %s: %s: "
3304e8c149abSMichael Tuexen 					    "Received FIN "
3305e8c149abSMichael Tuexen 					    "after having received a FIN, "
3306e8c149abSMichael Tuexen 					    "just dropping it\n",
3307e8c149abSMichael Tuexen 					    s, __func__,
3308e8c149abSMichael Tuexen 					    tcpstates[tp->t_state]);
3309e8c149abSMichael Tuexen 				}
3310e8c149abSMichael Tuexen 			}
3311e8c149abSMichael Tuexen 			free(s, M_TCPLOG);
3312e8c149abSMichael Tuexen 		}
3313df8bae1dSRodney W. Grimes 		m_freem(m);
3314fb59c426SYoshinobu Inoue 		thflags &= ~TH_FIN;
3315df8bae1dSRodney W. Grimes 	}
3316df8bae1dSRodney W. Grimes 
3317df8bae1dSRodney W. Grimes 	/*
3318df8bae1dSRodney W. Grimes 	 * If FIN is received ACK the FIN and let the user know
3319df8bae1dSRodney W. Grimes 	 * that the connection is closing.
3320df8bae1dSRodney W. Grimes 	 */
3321fb59c426SYoshinobu Inoue 	if (thflags & TH_FIN) {
3322df8bae1dSRodney W. Grimes 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
33234d0770f1SRichard Scheffenegger 			/* The socket upcall is handled by socantrcvmore. */
3324032bf749SRichard Scheffenegger 			socantrcvmore(so);
3325a0292f23SGarrett Wollman 			/*
3326a0292f23SGarrett Wollman 			 * If connection is half-synchronized
3327d3eede9dSAndras Olah 			 * (ie NEEDSYN flag on) then delay ACK,
3328a0292f23SGarrett Wollman 			 * so it may be piggybacked when SYN is sent.
3329a0292f23SGarrett Wollman 			 * Otherwise, since we received a FIN then no
3330a0292f23SGarrett Wollman 			 * more input can be expected, send ACK now.
3331a0292f23SGarrett Wollman 			 */
33323bfd6421SJonathan Lemon 			if (tp->t_flags & TF_NEEDSYN)
33333bfd6421SJonathan Lemon 				tp->t_flags |= TF_DELACK;
3334a0292f23SGarrett Wollman 			else
3335df8bae1dSRodney W. Grimes 				tp->t_flags |= TF_ACKNOW;
3336df8bae1dSRodney W. Grimes 			tp->rcv_nxt++;
3337df8bae1dSRodney W. Grimes 		}
3338df8bae1dSRodney W. Grimes 		switch (tp->t_state) {
3339df8bae1dSRodney W. Grimes 		/*
3340df8bae1dSRodney W. Grimes 		 * In SYN_RECEIVED and ESTABLISHED STATES
3341df8bae1dSRodney W. Grimes 		 * enter the CLOSE_WAIT state.
3342df8bae1dSRodney W. Grimes 		 */
3343df8bae1dSRodney W. Grimes 		case TCPS_SYN_RECEIVED:
33449b8b58e0SJonathan Lemon 			tp->t_starttime = ticks;
33459b8b58e0SJonathan Lemon 			/* FALLTHROUGH */
3346df8bae1dSRodney W. Grimes 		case TCPS_ESTABLISHED:
334757f60867SMark Johnston 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
3348df8bae1dSRodney W. Grimes 			break;
3349df8bae1dSRodney W. Grimes 
3350df8bae1dSRodney W. Grimes 		/*
3351df8bae1dSRodney W. Grimes 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3352df8bae1dSRodney W. Grimes 		 * enter the CLOSING state.
3353df8bae1dSRodney W. Grimes 		 */
3354df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_1:
335557f60867SMark Johnston 			tcp_state_change(tp, TCPS_CLOSING);
3356df8bae1dSRodney W. Grimes 			break;
3357df8bae1dSRodney W. Grimes 
3358df8bae1dSRodney W. Grimes 		/*
3359df8bae1dSRodney W. Grimes 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3360df8bae1dSRodney W. Grimes 		 * starting the time-wait timer, turning off the other
3361df8bae1dSRodney W. Grimes 		 * standard timers.
3362df8bae1dSRodney W. Grimes 		 */
3363df8bae1dSRodney W. Grimes 		case TCPS_FIN_WAIT_2:
3364340c35deSJonathan Lemon 			tcp_twstart(tp);
3365679d9708SAndre Oppermann 			return;
3366df8bae1dSRodney W. Grimes 		}
3367df8bae1dSRodney W. Grimes 	}
33682b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
3369df8bae1dSRodney W. Grimes 
3370df8bae1dSRodney W. Grimes 	/*
3371df8bae1dSRodney W. Grimes 	 * Return any desired output.
3372df8bae1dSRodney W. Grimes 	 */
33732d05a1c8SRichard Scheffenegger 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
337440fa3e40SGleb Smirnoff 		(void) tcp_output(tp);
33752d05a1c8SRichard Scheffenegger 	}
3376a14c749fSJonathan Lemon check_delack:
33779eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
3378252ca428SRobert Watson 
3379a14c749fSJonathan Lemon 	if (tp->t_flags & TF_DELACK) {
33803bfd6421SJonathan Lemon 		tp->t_flags &= ~TF_DELACK;
3381b8152ba7SAndre Oppermann 		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
33823bfd6421SJonathan Lemon 	}
33839eb0e832SGleb Smirnoff 	INP_WUNLOCK(inp);
3384679d9708SAndre Oppermann 	return;
3385df8bae1dSRodney W. Grimes 
3386df8bae1dSRodney W. Grimes dropafterack:
3387df8bae1dSRodney W. Grimes 	/*
3388df8bae1dSRodney W. Grimes 	 * Generate an ACK dropping incoming segment if it occupies
3389df8bae1dSRodney W. Grimes 	 * sequence space, where the ACK reflects our state.
339080ab7c0eSGarrett Wollman 	 *
339180ab7c0eSGarrett Wollman 	 * We can now skip the test for the RST flag since all
339280ab7c0eSGarrett Wollman 	 * paths to this code happen after packets containing
339380ab7c0eSGarrett Wollman 	 * RST have been dropped.
339480ab7c0eSGarrett Wollman 	 *
339580ab7c0eSGarrett Wollman 	 * In the SYN-RECEIVED state, don't send an ACK unless the
339680ab7c0eSGarrett Wollman 	 * segment we received passes the SYN-RECEIVED ACK test.
339780ab7c0eSGarrett Wollman 	 * If it fails send a RST.  This breaks the loop in the
339880ab7c0eSGarrett Wollman 	 * "LAND" DoS attack, and also prevents an ACK storm
339980ab7c0eSGarrett Wollman 	 * between two listening ports that have been sent forged
340080ab7c0eSGarrett Wollman 	 * SYN segments, each with the source address of the other.
3401df8bae1dSRodney W. Grimes 	 */
3402fb59c426SYoshinobu Inoue 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3403fb59c426SYoshinobu Inoue 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
3404a57815efSBosko Milekic 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
3405a57815efSBosko Milekic 		rstreason = BANDLIM_RST_OPENPORT;
3406d1b07f36SRandall Stewart 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
3407a57815efSBosko Milekic 		goto dropwithreset;
3408a57815efSBosko Milekic 	}
34092b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
3410df8bae1dSRodney W. Grimes 	tp->t_flags |= TF_ACKNOW;
341140fa3e40SGleb Smirnoff 	(void) tcp_output(tp);
34129eb0e832SGleb Smirnoff 	INP_WUNLOCK(inp);
3413d6915262SRobert Watson 	m_freem(m);
3414679d9708SAndre Oppermann 	return;
3415df8bae1dSRodney W. Grimes 
3416df8bae1dSRodney W. Grimes dropwithreset:
3417a0ca0871SRobert Watson 	if (tp != NULL) {
3418302ce8d6SAndre Oppermann 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
34199eb0e832SGleb Smirnoff 		INP_WUNLOCK(inp);
3420dd8ac7f9SRobert Watson 	} else
3421a0ca0871SRobert Watson 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3422679d9708SAndre Oppermann 	return;
3423df8bae1dSRodney W. Grimes 
3424df8bae1dSRodney W. Grimes drop:
3425df8bae1dSRodney W. Grimes 	/*
3426df8bae1dSRodney W. Grimes 	 * Drop space held by incoming segment and return.
3427df8bae1dSRodney W. Grimes 	 */
34282b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__input, tp, th, m);
34294d0770f1SRichard Scheffenegger 	if (tp != NULL) {
34309eb0e832SGleb Smirnoff 		INP_WUNLOCK(inp);
34314d0770f1SRichard Scheffenegger 	}
3432d6915262SRobert Watson 	m_freem(m);
3433302ce8d6SAndre Oppermann }
3434302ce8d6SAndre Oppermann 
3435302ce8d6SAndre Oppermann /*
34360ca3f933SAndre Oppermann  * Issue RST and make ACK acceptable to originator of segment.
34370ca3f933SAndre Oppermann  * The mbuf must still include the original packet header.
34380ca3f933SAndre Oppermann  * tp may be NULL.
3439302ce8d6SAndre Oppermann  */
344055bceb1eSRandall Stewart void
3441302ce8d6SAndre Oppermann tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3442302ce8d6SAndre Oppermann     int tlen, int rstreason)
3443302ce8d6SAndre Oppermann {
3444b287c6c7SBjoern A. Zeeb #ifdef INET
3445302ce8d6SAndre Oppermann 	struct ip *ip;
3446b287c6c7SBjoern A. Zeeb #endif
3447302ce8d6SAndre Oppermann #ifdef INET6
3448302ce8d6SAndre Oppermann 	struct ip6_hdr *ip6;
3449302ce8d6SAndre Oppermann #endif
34507a3244ccSRobert Watson 
34517a3244ccSRobert Watson 	if (tp != NULL) {
34529eb0e832SGleb Smirnoff 		INP_LOCK_ASSERT(tptoinpcb(tp));
34537a3244ccSRobert Watson 	}
34547a3244ccSRobert Watson 
34550ca3f933SAndre Oppermann 	/* Don't bother if destination was broadcast/multicast. */
34561ebf4607SRichard Scheffenegger 	if ((tcp_get_flags(th) & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3457302ce8d6SAndre Oppermann 		goto drop;
3458302ce8d6SAndre Oppermann #ifdef INET6
3459302ce8d6SAndre Oppermann 	if (mtod(m, struct ip *)->ip_v == 6) {
3460302ce8d6SAndre Oppermann 		ip6 = mtod(m, struct ip6_hdr *);
3461302ce8d6SAndre Oppermann 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3462302ce8d6SAndre Oppermann 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3463302ce8d6SAndre Oppermann 			goto drop;
3464302ce8d6SAndre Oppermann 		/* IPv6 anycast check is done at tcp6_input() */
3465b287c6c7SBjoern A. Zeeb 	}
3466302ce8d6SAndre Oppermann #endif
3467b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3468b287c6c7SBjoern A. Zeeb 	else
3469b287c6c7SBjoern A. Zeeb #endif
3470b287c6c7SBjoern A. Zeeb #ifdef INET
3471302ce8d6SAndre Oppermann 	{
3472302ce8d6SAndre Oppermann 		ip = mtod(m, struct ip *);
3473302ce8d6SAndre Oppermann 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3474302ce8d6SAndre Oppermann 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3475302ce8d6SAndre Oppermann 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3476302ce8d6SAndre Oppermann 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3477302ce8d6SAndre Oppermann 			goto drop;
3478302ce8d6SAndre Oppermann 	}
3479b287c6c7SBjoern A. Zeeb #endif
3480302ce8d6SAndre Oppermann 
3481302ce8d6SAndre Oppermann 	/* Perform bandwidth limiting. */
3482302ce8d6SAndre Oppermann 	if (badport_bandlim(rstreason) < 0)
3483302ce8d6SAndre Oppermann 		goto drop;
3484302ce8d6SAndre Oppermann 
3485302ce8d6SAndre Oppermann 	/* tcp_respond consumes the mbuf chain. */
34861ebf4607SRichard Scheffenegger 	if (tcp_get_flags(th) & TH_ACK) {
3487302ce8d6SAndre Oppermann 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3488302ce8d6SAndre Oppermann 		    th->th_ack, TH_RST);
3489302ce8d6SAndre Oppermann 	} else {
34901ebf4607SRichard Scheffenegger 		if (tcp_get_flags(th) & TH_SYN)
3491302ce8d6SAndre Oppermann 			tlen++;
34921ebf4607SRichard Scheffenegger 		if (tcp_get_flags(th) & TH_FIN)
34934ddd5aadSMichael Tuexen 			tlen++;
3494302ce8d6SAndre Oppermann 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3495302ce8d6SAndre Oppermann 		    (tcp_seq)0, TH_RST|TH_ACK);
3496302ce8d6SAndre Oppermann 	}
3497302ce8d6SAndre Oppermann 	return;
3498302ce8d6SAndre Oppermann drop:
3499302ce8d6SAndre Oppermann 	m_freem(m);
3500df8bae1dSRodney W. Grimes }
3501df8bae1dSRodney W. Grimes 
3502be2ac88cSJonathan Lemon /*
3503be2ac88cSJonathan Lemon  * Parse TCP options and place in tcpopt.
3504be2ac88cSJonathan Lemon  */
350555bceb1eSRandall Stewart void
3506ad3f9ab3SAndre Oppermann tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3507df8bae1dSRodney W. Grimes {
3508df8bae1dSRodney W. Grimes 	int opt, optlen;
3509df8bae1dSRodney W. Grimes 
3510be2ac88cSJonathan Lemon 	to->to_flags = 0;
3511df8bae1dSRodney W. Grimes 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
3512df8bae1dSRodney W. Grimes 		opt = cp[0];
3513df8bae1dSRodney W. Grimes 		if (opt == TCPOPT_EOL)
3514df8bae1dSRodney W. Grimes 			break;
3515df8bae1dSRodney W. Grimes 		if (opt == TCPOPT_NOP)
3516df8bae1dSRodney W. Grimes 			optlen = 1;
3517df8bae1dSRodney W. Grimes 		else {
3518b474779fSJun-ichiro itojun Hagino 			if (cnt < 2)
3519b474779fSJun-ichiro itojun Hagino 				break;
3520df8bae1dSRodney W. Grimes 			optlen = cp[1];
3521b474779fSJun-ichiro itojun Hagino 			if (optlen < 2 || optlen > cnt)
3522df8bae1dSRodney W. Grimes 				break;
3523df8bae1dSRodney W. Grimes 		}
3524df8bae1dSRodney W. Grimes 		switch (opt) {
3525df8bae1dSRodney W. Grimes 		case TCPOPT_MAXSEG:
3526df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_MAXSEG)
3527df8bae1dSRodney W. Grimes 				continue;
3528f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3529df8bae1dSRodney W. Grimes 				continue;
3530be2ac88cSJonathan Lemon 			to->to_flags |= TOF_MSS;
3531be2ac88cSJonathan Lemon 			bcopy((char *)cp + 2,
3532be2ac88cSJonathan Lemon 			    (char *)&to->to_mss, sizeof(to->to_mss));
3533fd8e4ebcSMike Barcroft 			to->to_mss = ntohs(to->to_mss);
3534df8bae1dSRodney W. Grimes 			break;
3535df8bae1dSRodney W. Grimes 		case TCPOPT_WINDOW:
3536df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_WINDOW)
3537df8bae1dSRodney W. Grimes 				continue;
3538f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3539df8bae1dSRodney W. Grimes 				continue;
3540be2ac88cSJonathan Lemon 			to->to_flags |= TOF_SCALE;
354102a1a643SAndre Oppermann 			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3542df8bae1dSRodney W. Grimes 			break;
3543df8bae1dSRodney W. Grimes 		case TCPOPT_TIMESTAMP:
3544df8bae1dSRodney W. Grimes 			if (optlen != TCPOLEN_TIMESTAMP)
3545df8bae1dSRodney W. Grimes 				continue;
3546be2ac88cSJonathan Lemon 			to->to_flags |= TOF_TS;
3547a0292f23SGarrett Wollman 			bcopy((char *)cp + 2,
3548a0292f23SGarrett Wollman 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
3549fd8e4ebcSMike Barcroft 			to->to_tsval = ntohl(to->to_tsval);
3550a0292f23SGarrett Wollman 			bcopy((char *)cp + 6,
3551a0292f23SGarrett Wollman 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3552fd8e4ebcSMike Barcroft 			to->to_tsecr = ntohl(to->to_tsecr);
3553df8bae1dSRodney W. Grimes 			break;
35541cfd4b53SBruce M Simpson 		case TCPOPT_SIGNATURE:
3555fcf59617SAndrey V. Elsukov 			/*
3556fcf59617SAndrey V. Elsukov 			 * In order to reply to a host which has set the
3557fcf59617SAndrey V. Elsukov 			 * TCP_SIGNATURE option in its initial SYN, we have
3558fcf59617SAndrey V. Elsukov 			 * to record the fact that the option was observed
3559fcf59617SAndrey V. Elsukov 			 * here for the syncache code to perform the correct
3560fcf59617SAndrey V. Elsukov 			 * response.
3561fcf59617SAndrey V. Elsukov 			 */
35621cfd4b53SBruce M Simpson 			if (optlen != TCPOLEN_SIGNATURE)
35631cfd4b53SBruce M Simpson 				continue;
3564df47e437SAndre Oppermann 			to->to_flags |= TOF_SIGNATURE;
3565df47e437SAndre Oppermann 			to->to_signature = cp + 2;
35661cfd4b53SBruce M Simpson 			break;
35676d90faf3SPaul Saab 		case TCPOPT_SACK_PERMITTED:
3568f72167f4SAndre Oppermann 			if (optlen != TCPOLEN_SACK_PERMITTED)
35696d90faf3SPaul Saab 				continue;
3570f72167f4SAndre Oppermann 			if (!(flags & TO_SYN))
3571f72167f4SAndre Oppermann 				continue;
3572603724d3SBjoern A. Zeeb 			if (!V_tcp_do_sack)
3573f72167f4SAndre Oppermann 				continue;
3574fc30a251SAndre Oppermann 			to->to_flags |= TOF_SACKPERM;
35756d90faf3SPaul Saab 			break;
35766d90faf3SPaul Saab 		case TCPOPT_SACK:
35775a53ca16SPaul Saab 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
35786d90faf3SPaul Saab 				continue;
3579b728e902SAndre Oppermann 			if (flags & TO_SYN)
3580b728e902SAndre Oppermann 				continue;
3581fc30a251SAndre Oppermann 			to->to_flags |= TOF_SACK;
35825a53ca16SPaul Saab 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
35835a53ca16SPaul Saab 			to->to_sacks = cp + 2;
358478b50714SRobert Watson 			TCPSTAT_INC(tcps_sack_rcv_blocks);
35856d90faf3SPaul Saab 			break;
3586281a0fd4SPatrick Kelsey 		case TCPOPT_FAST_OPEN:
3587c560df6fSPatrick Kelsey 			/*
3588c560df6fSPatrick Kelsey 			 * Cookie length validation is performed by the
3589c560df6fSPatrick Kelsey 			 * server side cookie checking code or the client
3590c560df6fSPatrick Kelsey 			 * side cookie cache update code.
3591c560df6fSPatrick Kelsey 			 */
3592281a0fd4SPatrick Kelsey 			if (!(flags & TO_SYN))
3593281a0fd4SPatrick Kelsey 				continue;
3594c560df6fSPatrick Kelsey 			if (!V_tcp_fastopen_client_enable &&
3595c560df6fSPatrick Kelsey 			    !V_tcp_fastopen_server_enable)
3596281a0fd4SPatrick Kelsey 				continue;
3597281a0fd4SPatrick Kelsey 			to->to_flags |= TOF_FASTOPEN;
3598281a0fd4SPatrick Kelsey 			to->to_tfo_len = optlen - 2;
3599281a0fd4SPatrick Kelsey 			to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3600281a0fd4SPatrick Kelsey 			break;
3601be2ac88cSJonathan Lemon 		default:
3602be2ac88cSJonathan Lemon 			continue;
3603df8bae1dSRodney W. Grimes 		}
3604df8bae1dSRodney W. Grimes 	}
3605df8bae1dSRodney W. Grimes }
3606df8bae1dSRodney W. Grimes 
3607df8bae1dSRodney W. Grimes /*
3608df8bae1dSRodney W. Grimes  * Pull out of band byte out of a segment so
3609df8bae1dSRodney W. Grimes  * it doesn't appear in the user's data queue.
3610df8bae1dSRodney W. Grimes  * It is still reflected in the segment length for
3611df8bae1dSRodney W. Grimes  * sequencing purposes.
3612df8bae1dSRodney W. Grimes  */
361355bceb1eSRandall Stewart void
3614ad3f9ab3SAndre Oppermann tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3615ad3f9ab3SAndre Oppermann     int off)
3616df8bae1dSRodney W. Grimes {
3617fb59c426SYoshinobu Inoue 	int cnt = off + th->th_urp - 1;
3618df8bae1dSRodney W. Grimes 
3619df8bae1dSRodney W. Grimes 	while (cnt >= 0) {
3620df8bae1dSRodney W. Grimes 		if (m->m_len > cnt) {
3621df8bae1dSRodney W. Grimes 			char *cp = mtod(m, caddr_t) + cnt;
3622df8bae1dSRodney W. Grimes 			struct tcpcb *tp = sototcpcb(so);
3623df8bae1dSRodney W. Grimes 
36249eb0e832SGleb Smirnoff 			INP_WLOCK_ASSERT(tptoinpcb(tp));
36257a3244ccSRobert Watson 
3626df8bae1dSRodney W. Grimes 			tp->t_iobc = *cp;
3627df8bae1dSRodney W. Grimes 			tp->t_oobflags |= TCPOOB_HAVEDATA;
3628df8bae1dSRodney W. Grimes 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3629df8bae1dSRodney W. Grimes 			m->m_len--;
363069a34685SYoshinobu Inoue 			if (m->m_flags & M_PKTHDR)
363169a34685SYoshinobu Inoue 				m->m_pkthdr.len--;
3632df8bae1dSRodney W. Grimes 			return;
3633df8bae1dSRodney W. Grimes 		}
3634df8bae1dSRodney W. Grimes 		cnt -= m->m_len;
3635df8bae1dSRodney W. Grimes 		m = m->m_next;
36364dfdffe9SAndre Oppermann 		if (m == NULL)
3637df8bae1dSRodney W. Grimes 			break;
3638df8bae1dSRodney W. Grimes 	}
3639df8bae1dSRodney W. Grimes 	panic("tcp_pulloutofband");
3640df8bae1dSRodney W. Grimes }
3641df8bae1dSRodney W. Grimes 
3642df8bae1dSRodney W. Grimes /*
3643df8bae1dSRodney W. Grimes  * Collect new round-trip time estimate
3644df8bae1dSRodney W. Grimes  * and update averages and current timeout.
3645df8bae1dSRodney W. Grimes  */
364655bceb1eSRandall Stewart void
3647ad3f9ab3SAndre Oppermann tcp_xmit_timer(struct tcpcb *tp, int rtt)
3648df8bae1dSRodney W. Grimes {
3649ad3f9ab3SAndre Oppermann 	int delta;
3650233e8c18SGarrett Wollman 
36519eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
36522be3bf22SRobert Watson 
365378b50714SRobert Watson 	TCPSTAT_INC(tcps_rttupdated);
365418b83b62SRichard Scheffenegger 	if (tp->t_rttupdated < UCHAR_MAX)
3655233e8c18SGarrett Wollman 		tp->t_rttupdated++;
3656adc56f5aSEdward Tomasz Napierala #ifdef STATS
3657adc56f5aSEdward Tomasz Napierala 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT,
3658adc56f5aSEdward Tomasz Napierala 	    imax(0, rtt * 1000 / hz));
3659adc56f5aSEdward Tomasz Napierala #endif
36605ede40dcSRyan Stone 	if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3661233e8c18SGarrett Wollman 		/*
3662233e8c18SGarrett Wollman 		 * srtt is stored as fixed point with 5 bits after the
3663233e8c18SGarrett Wollman 		 * binary point (i.e., scaled by 8).  The following magic
3664233e8c18SGarrett Wollman 		 * is equivalent to the smoothing algorithm in rfc793 with
3665233e8c18SGarrett Wollman 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3666233e8c18SGarrett Wollman 		 * point).  Adjust rtt to origin 0.
3667233e8c18SGarrett Wollman 		 */
3668233e8c18SGarrett Wollman 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3669233e8c18SGarrett Wollman 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3670233e8c18SGarrett Wollman 
3671233e8c18SGarrett Wollman 		if ((tp->t_srtt += delta) <= 0)
3672233e8c18SGarrett Wollman 			tp->t_srtt = 1;
3673233e8c18SGarrett Wollman 
3674233e8c18SGarrett Wollman 		/*
3675233e8c18SGarrett Wollman 		 * We accumulate a smoothed rtt variance (actually, a
3676233e8c18SGarrett Wollman 		 * smoothed mean difference), then set the retransmit
3677233e8c18SGarrett Wollman 		 * timer to smoothed rtt + 4 times the smoothed variance.
3678233e8c18SGarrett Wollman 		 * rttvar is stored as fixed point with 4 bits after the
3679233e8c18SGarrett Wollman 		 * binary point (scaled by 16).  The following is
3680233e8c18SGarrett Wollman 		 * equivalent to rfc793 smoothing with an alpha of .75
3681233e8c18SGarrett Wollman 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
3682233e8c18SGarrett Wollman 		 * rfc793's wired-in beta.
3683233e8c18SGarrett Wollman 		 */
3684233e8c18SGarrett Wollman 		if (delta < 0)
3685233e8c18SGarrett Wollman 			delta = -delta;
3686233e8c18SGarrett Wollman 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3687233e8c18SGarrett Wollman 		if ((tp->t_rttvar += delta) <= 0)
3688233e8c18SGarrett Wollman 			tp->t_rttvar = 1;
3689233e8c18SGarrett Wollman 	} else {
3690233e8c18SGarrett Wollman 		/*
3691233e8c18SGarrett Wollman 		 * No rtt measurement yet - use the unsmoothed rtt.
3692233e8c18SGarrett Wollman 		 * Set the variance to half the rtt (so our first
3693233e8c18SGarrett Wollman 		 * retransmit happens at 3*rtt).
3694233e8c18SGarrett Wollman 		 */
3695233e8c18SGarrett Wollman 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
3696233e8c18SGarrett Wollman 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3697233e8c18SGarrett Wollman 	}
36989b8b58e0SJonathan Lemon 	tp->t_rtttime = 0;
3699df8bae1dSRodney W. Grimes 	tp->t_rxtshift = 0;
3700df8bae1dSRodney W. Grimes 
3701df8bae1dSRodney W. Grimes 	/*
3702df8bae1dSRodney W. Grimes 	 * the retransmit should happen at rtt + 4 * rttvar.
3703df8bae1dSRodney W. Grimes 	 * Because of the way we do the smoothing, srtt and rttvar
3704df8bae1dSRodney W. Grimes 	 * will each average +1/2 tick of bias.  When we compute
3705df8bae1dSRodney W. Grimes 	 * the retransmit timer, we want 1/2 tick of rounding and
3706df8bae1dSRodney W. Grimes 	 * 1 extra tick because of +-1/2 tick uncertainty in the
3707df8bae1dSRodney W. Grimes 	 * firing of the timer.  The bias will give us exactly the
3708df8bae1dSRodney W. Grimes 	 * 1.5 tick we need.  But, because the bias is
3709df8bae1dSRodney W. Grimes 	 * statistical, we have to test that we don't drop below
3710df8bae1dSRodney W. Grimes 	 * the minimum feasible timer (which is 2 ticks).
3711df8bae1dSRodney W. Grimes 	 */
3712233e8c18SGarrett Wollman 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
37139e2874b0SGarrett Wollman 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3714df8bae1dSRodney W. Grimes 
3715df8bae1dSRodney W. Grimes 	/*
3716df8bae1dSRodney W. Grimes 	 * We received an ack for a packet that wasn't retransmitted;
3717df8bae1dSRodney W. Grimes 	 * it is probably safe to discard any error indications we've
3718df8bae1dSRodney W. Grimes 	 * received recently.  This isn't quite right, but close enough
3719df8bae1dSRodney W. Grimes 	 * for now (a route might have failed after we sent a segment,
3720df8bae1dSRodney W. Grimes 	 * and the return path might not be symmetrical).
3721df8bae1dSRodney W. Grimes 	 */
3722df8bae1dSRodney W. Grimes 	tp->t_softerror = 0;
3723df8bae1dSRodney W. Grimes }
3724df8bae1dSRodney W. Grimes 
3725df8bae1dSRodney W. Grimes /*
3726df8bae1dSRodney W. Grimes  * Determine a reasonable value for maxseg size.
3727df8bae1dSRodney W. Grimes  * If the route is known, check route for mtu.
37284faaea55SAndre Oppermann  * If none, use an mss that can be handled on the outgoing interface
37294faaea55SAndre Oppermann  * without forcing IP to fragment.  If no route is found, route has no mtu,
3730df8bae1dSRodney W. Grimes  * or the destination isn't local, use a default, hopefully conservative
3731df8bae1dSRodney W. Grimes  * size (usually 512 or the default IP max size, but no more than the mtu
3732df8bae1dSRodney W. Grimes  * of the interface), as we can't discover anything about intervening
3733df8bae1dSRodney W. Grimes  * gateways or networks.  We also initialize the congestion/slow start
3734df8bae1dSRodney W. Grimes  * window to be a single segment if the destination isn't local.
3735df8bae1dSRodney W. Grimes  * While looking at the routing entry, we also initialize other path-dependent
3736df8bae1dSRodney W. Grimes  * parameters from pre-set or cached values in the routing entry.
3737a0292f23SGarrett Wollman  *
37380c39d38dSGleb Smirnoff  * NOTE that resulting t_maxseg doesn't include space for TCP options or
37390c39d38dSGleb Smirnoff  * IP options, e.g. IPSEC data, since length of this data may vary, and
37400c39d38dSGleb Smirnoff  * thus it is calculated for every segment separately in tcp_output().
3741a0292f23SGarrett Wollman  *
374297d8d152SAndre Oppermann  * NOTE that this routine is only called when we process an incoming
3743ef341ee1SGleb Smirnoff  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3744ef341ee1SGleb Smirnoff  * settings are handled in tcp_mssopt().
3745df8bae1dSRodney W. Grimes  */
3746a0292f23SGarrett Wollman void
3747ef341ee1SGleb Smirnoff tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
37483c914c54SAndre Oppermann     struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3749df8bae1dSRodney W. Grimes {
3750b287c6c7SBjoern A. Zeeb 	int mss = 0;
37513ac12506SJonathan T. Looney 	uint32_t maxmtu = 0;
37529eb0e832SGleb Smirnoff 	struct inpcb *inp = tptoinpcb(tp);
375397d8d152SAndre Oppermann 	struct hc_metrics_lite metrics;
3754fb59c426SYoshinobu Inoue #ifdef INET6
3755c068736aSJeffrey Hsu 	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3756c068736aSJeffrey Hsu 	size_t min_protoh = isipv6 ?
3757c068736aSJeffrey Hsu 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3758c068736aSJeffrey Hsu 			    sizeof (struct tcpiphdr);
3759c068736aSJeffrey Hsu #else
37609e644c23SMichael Tuexen 	 size_t min_protoh = sizeof(struct tcpiphdr);
3761fb59c426SYoshinobu Inoue #endif
3762df8bae1dSRodney W. Grimes 
37639eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(inp);
37647a3244ccSRobert Watson 
37659e644c23SMichael Tuexen 	if (tp->t_port)
37669e644c23SMichael Tuexen 		min_protoh += V_tcp_udp_tunneling_overhead;
3767ef341ee1SGleb Smirnoff 	if (mtuoffer != -1) {
3768ef341ee1SGleb Smirnoff 		KASSERT(offer == -1, ("%s: conflict", __func__));
3769ef341ee1SGleb Smirnoff 		offer = mtuoffer - min_protoh;
3770ef341ee1SGleb Smirnoff 	}
3771ef341ee1SGleb Smirnoff 
3772e8949f74SAndre Oppermann 	/* Initialize. */
377397d8d152SAndre Oppermann #ifdef INET6
377497d8d152SAndre Oppermann 	if (isipv6) {
37753c914c54SAndre Oppermann 		maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
37760c39d38dSGleb Smirnoff 		tp->t_maxseg = V_tcp_v6mssdflt;
3777b287c6c7SBjoern A. Zeeb 	}
377897d8d152SAndre Oppermann #endif
3779b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3780b287c6c7SBjoern A. Zeeb 	else
3781b287c6c7SBjoern A. Zeeb #endif
3782b287c6c7SBjoern A. Zeeb #ifdef INET
378397d8d152SAndre Oppermann 	{
37843c914c54SAndre Oppermann 		maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
37850c39d38dSGleb Smirnoff 		tp->t_maxseg = V_tcp_mssdflt;
3786df8bae1dSRodney W. Grimes 	}
3787b287c6c7SBjoern A. Zeeb #endif
3788df8bae1dSRodney W. Grimes 
378997d8d152SAndre Oppermann 	/*
3790e8949f74SAndre Oppermann 	 * No route to sender, stay with default mss and return.
379197d8d152SAndre Oppermann 	 */
37926f01cac6SBjoern A. Zeeb 	if (maxmtu == 0) {
37936f01cac6SBjoern A. Zeeb 		/*
37948e5c87f4SBjoern A. Zeeb 		 * In case we return early we need to initialize metrics
37956f01cac6SBjoern A. Zeeb 		 * to a defined state as tcp_hc_get() would do for us
37966f01cac6SBjoern A. Zeeb 		 * if there was no cache hit.
37976f01cac6SBjoern A. Zeeb 		 */
37986f01cac6SBjoern A. Zeeb 		if (metricptr != NULL)
37996f01cac6SBjoern A. Zeeb 			bzero(metricptr, sizeof(struct hc_metrics_lite));
380097d8d152SAndre Oppermann 		return;
38016f01cac6SBjoern A. Zeeb 	}
380297d8d152SAndre Oppermann 
3803e8949f74SAndre Oppermann 	/* What have we got? */
380497d8d152SAndre Oppermann 	switch (offer) {
380597d8d152SAndre Oppermann 		case 0:
380697d8d152SAndre Oppermann 			/*
380797d8d152SAndre Oppermann 			 * Offer == 0 means that there was no MSS on the SYN
3808c3b02504SBjoern A. Zeeb 			 * segment, in this case we use tcp_mssdflt as
38090c39d38dSGleb Smirnoff 			 * already assigned to t_maxseg above.
381097d8d152SAndre Oppermann 			 */
38110c39d38dSGleb Smirnoff 			offer = tp->t_maxseg;
381297d8d152SAndre Oppermann 			break;
381397d8d152SAndre Oppermann 
381497d8d152SAndre Oppermann 		case -1:
3815a0292f23SGarrett Wollman 			/*
3816c94c54e4SAndre Oppermann 			 * Offer == -1 means that we didn't receive SYN yet.
3817a0292f23SGarrett Wollman 			 */
381897d8d152SAndre Oppermann 			/* FALLTHROUGH */
381997d8d152SAndre Oppermann 
382097d8d152SAndre Oppermann 		default:
3821a0292f23SGarrett Wollman 			/*
382253369ac9SAndre Oppermann 			 * Prevent DoS attack with too small MSS. Round up
382353369ac9SAndre Oppermann 			 * to at least minmss.
382453369ac9SAndre Oppermann 			 */
3825603724d3SBjoern A. Zeeb 			offer = max(offer, V_tcp_minmss);
382697d8d152SAndre Oppermann 	}
3827a0292f23SGarrett Wollman 
3828df8bae1dSRodney W. Grimes 	/*
3829e8949f74SAndre Oppermann 	 * rmx information is now retrieved from tcp_hostcache.
3830df8bae1dSRodney W. Grimes 	 */
383197d8d152SAndre Oppermann 	tcp_hc_get(&inp->inp_inc, &metrics);
38323cee92e0SBjoern A. Zeeb 	if (metricptr != NULL)
38333cee92e0SBjoern A. Zeeb 		bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
383497d8d152SAndre Oppermann 
3835df8bae1dSRodney W. Grimes 	/*
3836cc412412SHiren Panchasara 	 * If there's a discovered mtu in tcp hostcache, use it.
3837cc412412SHiren Panchasara 	 * Else, use the link mtu.
3838df8bae1dSRodney W. Grimes 	 */
383997d8d152SAndre Oppermann 	if (metrics.rmx_mtu)
38402d166c02SAndre Oppermann 		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3841c068736aSJeffrey Hsu 	else {
384231b3783cSHajimu UMEMOTO #ifdef INET6
3843fb59c426SYoshinobu Inoue 		if (isipv6) {
384497d8d152SAndre Oppermann 			mss = maxmtu - min_protoh;
3845603724d3SBjoern A. Zeeb 			if (!V_path_mtu_discovery &&
384697d8d152SAndre Oppermann 			    !in6_localaddr(&inp->in6p_faddr))
3847603724d3SBjoern A. Zeeb 				mss = min(mss, V_tcp_v6mssdflt);
3848b287c6c7SBjoern A. Zeeb 		}
3849b3399803SHajimu UMEMOTO #endif
3850b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
3851b287c6c7SBjoern A. Zeeb 		else
3852b287c6c7SBjoern A. Zeeb #endif
3853b287c6c7SBjoern A. Zeeb #ifdef INET
385497d8d152SAndre Oppermann 		{
385597d8d152SAndre Oppermann 			mss = maxmtu - min_protoh;
3856603724d3SBjoern A. Zeeb 			if (!V_path_mtu_discovery &&
385797d8d152SAndre Oppermann 			    !in_localaddr(inp->inp_faddr))
3858603724d3SBjoern A. Zeeb 				mss = min(mss, V_tcp_mssdflt);
3859a0292f23SGarrett Wollman 		}
3860b287c6c7SBjoern A. Zeeb #endif
38613cee92e0SBjoern A. Zeeb 		/*
38623cee92e0SBjoern A. Zeeb 		 * XXX - The above conditional (mss = maxmtu - min_protoh)
38633cee92e0SBjoern A. Zeeb 		 * probably violates the TCP spec.
38643cee92e0SBjoern A. Zeeb 		 * The problem is that, since we don't know the
38653cee92e0SBjoern A. Zeeb 		 * other end's MSS, we are supposed to use a conservative
38663cee92e0SBjoern A. Zeeb 		 * default.  But, if we do that, then MTU discovery will
38673cee92e0SBjoern A. Zeeb 		 * never actually take place, because the conservative
38683cee92e0SBjoern A. Zeeb 		 * default is much less than the MTUs typically seen
38693cee92e0SBjoern A. Zeeb 		 * on the Internet today.  For the moment, we'll sweep
38703cee92e0SBjoern A. Zeeb 		 * this under the carpet.
38713cee92e0SBjoern A. Zeeb 		 *
38723cee92e0SBjoern A. Zeeb 		 * The conservative default might not actually be a problem
38733cee92e0SBjoern A. Zeeb 		 * if the only case this occurs is when sending an initial
38743cee92e0SBjoern A. Zeeb 		 * SYN with options and data to a host we've never talked
38753cee92e0SBjoern A. Zeeb 		 * to before.  Then, they will reply with an MSS value which
38763cee92e0SBjoern A. Zeeb 		 * will get recorded and the new parameters should get
38773cee92e0SBjoern A. Zeeb 		 * recomputed.  For Further Study.
38783cee92e0SBjoern A. Zeeb 		 */
387997d8d152SAndre Oppermann 	}
3880a0292f23SGarrett Wollman 	mss = min(mss, offer);
388197d8d152SAndre Oppermann 
3882a0292f23SGarrett Wollman 	/*
38830c39d38dSGleb Smirnoff 	 * Sanity check: make sure that maxseg will be large
38843cee92e0SBjoern A. Zeeb 	 * enough to allow some data on segments even if the
38853cee92e0SBjoern A. Zeeb 	 * all the option space is used (40bytes).  Otherwise
38863cee92e0SBjoern A. Zeeb 	 * funny things may happen in tcp_output.
38870c39d38dSGleb Smirnoff 	 *
38880c39d38dSGleb Smirnoff 	 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
38893cee92e0SBjoern A. Zeeb 	 */
38903cee92e0SBjoern A. Zeeb 	mss = max(mss, 64);
38913cee92e0SBjoern A. Zeeb 
389297d8d152SAndre Oppermann 	tp->t_maxseg = mss;
3893*fce03f85SRandall Stewart 	if (tp->t_maxseg < V_tcp_mssdflt) {
3894*fce03f85SRandall Stewart 		/*
3895*fce03f85SRandall Stewart 		 * The MSS is so small we should not process incoming
3896*fce03f85SRandall Stewart 		 * SACK's since we are subject to attack in such a
3897*fce03f85SRandall Stewart 		 * case.
3898*fce03f85SRandall Stewart 		 */
3899*fce03f85SRandall Stewart 		tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
3900*fce03f85SRandall Stewart 	} else {
3901*fce03f85SRandall Stewart 		tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
3902*fce03f85SRandall Stewart 	}
3903*fce03f85SRandall Stewart 
39043cee92e0SBjoern A. Zeeb }
39053cee92e0SBjoern A. Zeeb 
39063cee92e0SBjoern A. Zeeb void
39073cee92e0SBjoern A. Zeeb tcp_mss(struct tcpcb *tp, int offer)
39083cee92e0SBjoern A. Zeeb {
3909dbc42409SLawrence Stewart 	int mss;
39103ac12506SJonathan T. Looney 	uint32_t bufsize;
39119eb0e832SGleb Smirnoff 	struct inpcb *inp = tptoinpcb(tp);
39123cee92e0SBjoern A. Zeeb 	struct socket *so;
39133cee92e0SBjoern A. Zeeb 	struct hc_metrics_lite metrics;
39143c914c54SAndre Oppermann 	struct tcp_ifcap cap;
3915dbc42409SLawrence Stewart 
39163cee92e0SBjoern A. Zeeb 	KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
39173cee92e0SBjoern A. Zeeb 
39183c914c54SAndre Oppermann 	bzero(&cap, sizeof(cap));
39193c914c54SAndre Oppermann 	tcp_mss_update(tp, offer, -1, &metrics, &cap);
39203cee92e0SBjoern A. Zeeb 
39213cee92e0SBjoern A. Zeeb 	mss = tp->t_maxseg;
392297d8d152SAndre Oppermann 
3923df8bae1dSRodney W. Grimes 	/*
392497d8d152SAndre Oppermann 	 * If there's a pipesize, change the socket buffer to that size,
392597d8d152SAndre Oppermann 	 * don't change if sb_hiwat is different than default (then it
392697d8d152SAndre Oppermann 	 * has been changed on purpose with setsockopt).
392797d8d152SAndre Oppermann 	 * Make the socket buffers an integral number of mss units;
392897d8d152SAndre Oppermann 	 * if the mss is larger than the socket buffer, decrease the mss.
3929df8bae1dSRodney W. Grimes 	 */
3930c3b02504SBjoern A. Zeeb 	so = inp->inp_socket;
39313f11a2f3SRobert Watson 	SOCKBUF_LOCK(&so->so_snd);
3932e233e2acSAndre Oppermann 	if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
393397d8d152SAndre Oppermann 		bufsize = metrics.rmx_sendpipe;
393497d8d152SAndre Oppermann 	else
3935df8bae1dSRodney W. Grimes 		bufsize = so->so_snd.sb_hiwat;
3936df8bae1dSRodney W. Grimes 	if (bufsize < mss)
3937df8bae1dSRodney W. Grimes 		mss = bufsize;
3938df8bae1dSRodney W. Grimes 	else {
3939df8bae1dSRodney W. Grimes 		bufsize = roundup(bufsize, mss);
3940df8bae1dSRodney W. Grimes 		if (bufsize > sb_max)
3941df8bae1dSRodney W. Grimes 			bufsize = sb_max;
394288c39af3SRuslan Ermilov 		if (bufsize > so->so_snd.sb_hiwat)
394343283184SGleb Smirnoff 			(void)sbreserve_locked(so, SO_SND, bufsize, NULL);
3944df8bae1dSRodney W. Grimes 	}
39453f11a2f3SRobert Watson 	SOCKBUF_UNLOCK(&so->so_snd);
3946784ce8faSHiren Panchasara 	/*
3947784ce8faSHiren Panchasara 	 * Sanity check: make sure that maxseg will be large
3948784ce8faSHiren Panchasara 	 * enough to allow some data on segments even if the
3949784ce8faSHiren Panchasara 	 * all the option space is used (40bytes).  Otherwise
3950784ce8faSHiren Panchasara 	 * funny things may happen in tcp_output.
3951784ce8faSHiren Panchasara 	 *
3952784ce8faSHiren Panchasara 	 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3953784ce8faSHiren Panchasara 	 */
3954784ce8faSHiren Panchasara 	tp->t_maxseg = max(mss, 64);
3955*fce03f85SRandall Stewart 	if (tp->t_maxseg < V_tcp_mssdflt) {
3956*fce03f85SRandall Stewart 		/*
3957*fce03f85SRandall Stewart 		 * The MSS is so small we should not process incoming
3958*fce03f85SRandall Stewart 		 * SACK's since we are subject to attack in such a
3959*fce03f85SRandall Stewart 		 * case.
3960*fce03f85SRandall Stewart 		 */
3961*fce03f85SRandall Stewart 		tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
3962*fce03f85SRandall Stewart 	} else {
3963*fce03f85SRandall Stewart 		tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
3964*fce03f85SRandall Stewart 	}
3965df8bae1dSRodney W. Grimes 
39663f11a2f3SRobert Watson 	SOCKBUF_LOCK(&so->so_rcv);
3967e233e2acSAndre Oppermann 	if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
396897d8d152SAndre Oppermann 		bufsize = metrics.rmx_recvpipe;
396997d8d152SAndre Oppermann 	else
3970df8bae1dSRodney W. Grimes 		bufsize = so->so_rcv.sb_hiwat;
3971df8bae1dSRodney W. Grimes 	if (bufsize > mss) {
3972df8bae1dSRodney W. Grimes 		bufsize = roundup(bufsize, mss);
3973df8bae1dSRodney W. Grimes 		if (bufsize > sb_max)
3974df8bae1dSRodney W. Grimes 			bufsize = sb_max;
397588c39af3SRuslan Ermilov 		if (bufsize > so->so_rcv.sb_hiwat)
397643283184SGleb Smirnoff 			(void)sbreserve_locked(so, SO_RCV, bufsize, NULL);
3977df8bae1dSRodney W. Grimes 	}
39783f11a2f3SRobert Watson 	SOCKBUF_UNLOCK(&so->so_rcv);
397991d6cfa6SBjoern A. Zeeb 
398091d6cfa6SBjoern A. Zeeb 	/* Check the interface for TSO capabilities. */
39813c914c54SAndre Oppermann 	if (cap.ifcap & CSUM_TSO) {
398291d6cfa6SBjoern A. Zeeb 		tp->t_flags |= TF_TSO;
39833c914c54SAndre Oppermann 		tp->t_tsomax = cap.tsomax;
39849fd573c3SHans Petter Selasky 		tp->t_tsomaxsegcount = cap.tsomaxsegcount;
39859fd573c3SHans Petter Selasky 		tp->t_tsomaxsegsize = cap.tsomaxsegsize;
39863c914c54SAndre Oppermann 	}
3987a0292f23SGarrett Wollman }
3988a0292f23SGarrett Wollman 
3989a0292f23SGarrett Wollman /*
3990a0292f23SGarrett Wollman  * Determine the MSS option to send on an outgoing SYN.
3991a0292f23SGarrett Wollman  */
3992a0292f23SGarrett Wollman int
3993ad3f9ab3SAndre Oppermann tcp_mssopt(struct in_conninfo *inc)
3994a0292f23SGarrett Wollman {
399597d8d152SAndre Oppermann 	int mss = 0;
39963ac12506SJonathan T. Looney 	uint32_t thcmtu = 0;
39973ac12506SJonathan T. Looney 	uint32_t maxmtu = 0;
399897d8d152SAndre Oppermann 	size_t min_protoh;
3999a0292f23SGarrett Wollman 
400097d8d152SAndre Oppermann 	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
4001a0292f23SGarrett Wollman 
400231b3783cSHajimu UMEMOTO #ifdef INET6
4003dcdb4371SBjoern A. Zeeb 	if (inc->inc_flags & INC_ISIPV6) {
4004603724d3SBjoern A. Zeeb 		mss = V_tcp_v6mssdflt;
4005233dcce1SAndre Oppermann 		maxmtu = tcp_maxmtu6(inc, NULL);
400697d8d152SAndre Oppermann 		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
4007b287c6c7SBjoern A. Zeeb 	}
400831b3783cSHajimu UMEMOTO #endif
4009b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
4010b287c6c7SBjoern A. Zeeb 	else
4011b287c6c7SBjoern A. Zeeb #endif
4012b287c6c7SBjoern A. Zeeb #ifdef INET
401397d8d152SAndre Oppermann 	{
4014603724d3SBjoern A. Zeeb 		mss = V_tcp_mssdflt;
4015233dcce1SAndre Oppermann 		maxmtu = tcp_maxmtu(inc, NULL);
401697d8d152SAndre Oppermann 		min_protoh = sizeof(struct tcpiphdr);
401797d8d152SAndre Oppermann 	}
4018b287c6c7SBjoern A. Zeeb #endif
40193a9391deSBjoern A. Zeeb #if defined(INET6) || defined(INET)
40203a9391deSBjoern A. Zeeb 	thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
40213a9391deSBjoern A. Zeeb #endif
40223a9391deSBjoern A. Zeeb 
402397d8d152SAndre Oppermann 	if (maxmtu && thcmtu)
402497d8d152SAndre Oppermann 		mss = min(maxmtu, thcmtu) - min_protoh;
402597d8d152SAndre Oppermann 	else if (maxmtu || thcmtu)
402697d8d152SAndre Oppermann 		mss = max(maxmtu, thcmtu) - min_protoh;
402797d8d152SAndre Oppermann 
402897d8d152SAndre Oppermann 	return (mss);
4029df8bae1dSRodney W. Grimes }
403046f58482SJonathan Lemon 
40310e1d7c25SRichard Scheffenegger void
4032c7c325d0SRichard Scheffenegger tcp_do_prr_ack(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to,
4033c7c325d0SRichard Scheffenegger     sackstatus_t sack_changed, u_int *maxsegp)
40340e1d7c25SRichard Scheffenegger {
403548396dc7SRichard Scheffenegger 	int snd_cnt = 0, limit = 0, del_data = 0, pipe = 0;
4036c7c325d0SRichard Scheffenegger 	u_int maxseg;
40370e1d7c25SRichard Scheffenegger 
40389eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
40390e1d7c25SRichard Scheffenegger 
4040c7c325d0SRichard Scheffenegger 	if (*maxsegp == 0) {
4041c7c325d0SRichard Scheffenegger 		*maxsegp = tcp_maxseg(tp);
4042c7c325d0SRichard Scheffenegger 	}
4043c7c325d0SRichard Scheffenegger 	maxseg = *maxsegp;
40440e1d7c25SRichard Scheffenegger 	/*
40450e1d7c25SRichard Scheffenegger 	 * Compute the amount of data that this ACK is indicating
40460e1d7c25SRichard Scheffenegger 	 * (del_data) and an estimate of how many bytes are in the
40470e1d7c25SRichard Scheffenegger 	 * network.
40480e1d7c25SRichard Scheffenegger 	 */
4049c21b7b55SRichard Scheffenegger 	if (tcp_is_sack_recovery(tp, to) ||
405074d7fc87SRichard Scheffenegger 	    (IN_CONGRECOVERY(tp->t_flags) &&
405174d7fc87SRichard Scheffenegger 	     !IN_FASTRECOVERY(tp->t_flags))) {
405231d7a27cSRichard Scheffenegger 		del_data = tp->sackhint.delivered_data;
4053d1de2b05SRichard Scheffenegger 		if (V_tcp_do_newsack)
4054a8e431e1SRichard Scheffenegger 			pipe = tcp_compute_pipe(tp);
4055a8e431e1SRichard Scheffenegger 		else
405674d7fc87SRichard Scheffenegger 			pipe = (tp->snd_nxt - tp->snd_fack) +
405774d7fc87SRichard Scheffenegger 				tp->sackhint.sack_bytes_rexmit;
405874d7fc87SRichard Scheffenegger 	} else {
405974d7fc87SRichard Scheffenegger 		if (tp->sackhint.prr_delivered < (tcprexmtthresh * maxseg +
40602d05a1c8SRichard Scheffenegger 					     tp->snd_recover - tp->snd_una)) {
406174d7fc87SRichard Scheffenegger 			del_data = maxseg;
40622d05a1c8SRichard Scheffenegger 		}
406374d7fc87SRichard Scheffenegger 		pipe = imax(0, tp->snd_max - tp->snd_una -
406474d7fc87SRichard Scheffenegger 			    imin(INT_MAX / 65536, tp->t_dupacks) * maxseg);
406574d7fc87SRichard Scheffenegger 	}
40660e1d7c25SRichard Scheffenegger 	tp->sackhint.prr_delivered += del_data;
40670e1d7c25SRichard Scheffenegger 	/*
40680e1d7c25SRichard Scheffenegger 	 * Proportional Rate Reduction
40690e1d7c25SRichard Scheffenegger 	 */
4070e9071000SRichard Scheffenegger 	if (pipe >= tp->snd_ssthresh) {
40716a376af0SRichard Scheffenegger 		if (tp->sackhint.recover_fs == 0)
40726a376af0SRichard Scheffenegger 			tp->sackhint.recover_fs =
407348396dc7SRichard Scheffenegger 			    imax(1, tp->snd_nxt - tp->snd_una);
407448396dc7SRichard Scheffenegger 		snd_cnt = howmany((long)tp->sackhint.prr_delivered *
407548396dc7SRichard Scheffenegger 			    tp->snd_ssthresh, tp->sackhint.recover_fs) -
40769276ad23SRichard Scheffenegger 			    tp->sackhint.prr_out + maxseg - 1;
40776a376af0SRichard Scheffenegger 	} else {
407849a6fbe3SRichard Scheffenegger 		/*
407949a6fbe3SRichard Scheffenegger 		 * PRR 6937bis heuristic:
408049a6fbe3SRichard Scheffenegger 		 * - A partial ack without SACK block beneath snd_recover
408149a6fbe3SRichard Scheffenegger 		 * indicates further loss.
408249a6fbe3SRichard Scheffenegger 		 * - An SACK scoreboard update adding a new hole indicates
408349a6fbe3SRichard Scheffenegger 		 * further loss, so be conservative and send at most one
408449a6fbe3SRichard Scheffenegger 		 * segment.
408549a6fbe3SRichard Scheffenegger 		 * - Prevent ACK splitting attacks, by being conservative
408649a6fbe3SRichard Scheffenegger 		 * when no new data is acked.
408749a6fbe3SRichard Scheffenegger 		 */
40882d05a1c8SRichard Scheffenegger 		if ((sack_changed == SACK_NEWLOSS) || (del_data == 0)) {
408984761f3dSRichard Scheffenegger 			limit = tp->sackhint.prr_delivered -
4090e5313869SRichard Scheffenegger 				tp->sackhint.prr_out;
40912d05a1c8SRichard Scheffenegger 		} else {
409248396dc7SRichard Scheffenegger 			limit = imax(tp->sackhint.prr_delivered -
4093e5313869SRichard Scheffenegger 				    tp->sackhint.prr_out, del_data) +
4094e5313869SRichard Scheffenegger 				    maxseg;
40952d05a1c8SRichard Scheffenegger 		}
409648396dc7SRichard Scheffenegger 		snd_cnt = imin((tp->snd_ssthresh - pipe), limit);
40970e1d7c25SRichard Scheffenegger 	}
409848396dc7SRichard Scheffenegger 	snd_cnt = imax(snd_cnt, 0) / maxseg;
40990e1d7c25SRichard Scheffenegger 	/*
41000e1d7c25SRichard Scheffenegger 	 * Send snd_cnt new data into the network in response to this ack.
41010e1d7c25SRichard Scheffenegger 	 * If there is going to be a SACK retransmission, adjust snd_cwnd
41020e1d7c25SRichard Scheffenegger 	 * accordingly.
41030e1d7c25SRichard Scheffenegger 	 */
4104b9f803b7SRichard Scheffenegger 	if (IN_FASTRECOVERY(tp->t_flags)) {
4105c21b7b55SRichard Scheffenegger 		if (tcp_is_sack_recovery(tp, to)) {
410674d7fc87SRichard Scheffenegger 			tp->snd_cwnd = tp->snd_nxt - tp->snd_recover +
410774d7fc87SRichard Scheffenegger 					    tp->sackhint.sack_bytes_rexmit +
410874d7fc87SRichard Scheffenegger 					    (snd_cnt * maxseg);
410974d7fc87SRichard Scheffenegger 		} else {
411074d7fc87SRichard Scheffenegger 			tp->snd_cwnd = (tp->snd_max - tp->snd_una) +
411174d7fc87SRichard Scheffenegger 					    (snd_cnt * maxseg);
411274d7fc87SRichard Scheffenegger 		}
41132d05a1c8SRichard Scheffenegger 	} else if (IN_CONGRECOVERY(tp->t_flags)) {
411474d7fc87SRichard Scheffenegger 		tp->snd_cwnd = pipe - del_data + (snd_cnt * maxseg);
41152d05a1c8SRichard Scheffenegger 	}
411674d7fc87SRichard Scheffenegger 	tp->snd_cwnd = imax(maxseg, tp->snd_cwnd);
41170e1d7c25SRichard Scheffenegger }
41180e1d7c25SRichard Scheffenegger 
411946f58482SJonathan Lemon /*
4120c068736aSJeffrey Hsu  * On a partial ack arrives, force the retransmission of the
4121c068736aSJeffrey Hsu  * next unacknowledged segment.  Do not clear tp->t_dupacks.
4122c068736aSJeffrey Hsu  * By setting snd_nxt to ti_ack, this forces retransmission timer to
4123c068736aSJeffrey Hsu  * be started again.
412446f58482SJonathan Lemon  */
412555bceb1eSRandall Stewart void
4126ad3f9ab3SAndre Oppermann tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
412746f58482SJonathan Lemon {
412846f58482SJonathan Lemon 	tcp_seq onxt = tp->snd_nxt;
41293ac12506SJonathan T. Looney 	uint32_t ocwnd = tp->snd_cwnd;
41300c39d38dSGleb Smirnoff 	u_int maxseg = tcp_maxseg(tp);
413146f58482SJonathan Lemon 
41329eb0e832SGleb Smirnoff 	INP_WLOCK_ASSERT(tptoinpcb(tp));
41337a3244ccSRobert Watson 
4134b8152ba7SAndre Oppermann 	tcp_timer_activate(tp, TT_REXMT, 0);
413546f58482SJonathan Lemon 	tp->t_rtttime = 0;
413646f58482SJonathan Lemon 	tp->snd_nxt = th->th_ack;
41376b2a5f92SJayanth Vijayaraghavan 	/*
4138c068736aSJeffrey Hsu 	 * Set snd_cwnd to one segment beyond acknowledged offset.
4139c068736aSJeffrey Hsu 	 * (tp->snd_una has not yet been updated when this function is called.)
41406b2a5f92SJayanth Vijayaraghavan 	 */
41410c39d38dSGleb Smirnoff 	tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
4142a84db8f4SMatthew Dillon 	tp->t_flags |= TF_ACKNOW;
414340fa3e40SGleb Smirnoff 	(void) tcp_output(tp);
414446f58482SJonathan Lemon 	tp->snd_cwnd = ocwnd;
414546f58482SJonathan Lemon 	if (SEQ_GT(onxt, tp->snd_nxt))
414646f58482SJonathan Lemon 		tp->snd_nxt = onxt;
414746f58482SJonathan Lemon 	/*
414846f58482SJonathan Lemon 	 * Partial window deflation.  Relies on fact that tp->snd_una
414946f58482SJonathan Lemon 	 * not updated yet.
415046f58482SJonathan Lemon 	 */
4151dbc42409SLawrence Stewart 	if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
4152dbc42409SLawrence Stewart 		tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
4153d7587117SPaul Saab 	else
4154d7587117SPaul Saab 		tp->snd_cwnd = 0;
41550c39d38dSGleb Smirnoff 	tp->snd_cwnd += maxseg;
415646f58482SJonathan Lemon }
415712eeb81fSHiren Panchasara 
415812eeb81fSHiren Panchasara int
415912eeb81fSHiren Panchasara tcp_compute_pipe(struct tcpcb *tp)
416012eeb81fSHiren Panchasara {
4161e5049a17SRandall Stewart 	if (tp->t_fb->tfb_compute_pipe == NULL) {
416212eeb81fSHiren Panchasara 		return (tp->snd_max - tp->snd_una +
416312eeb81fSHiren Panchasara 			tp->sackhint.sack_bytes_rexmit -
4164e2c6a6d2SRichard Scheffenegger 			tp->sackhint.sacked_bytes -
4165e2c6a6d2SRichard Scheffenegger 			tp->sackhint.lost_bytes);
4166e5049a17SRandall Stewart 	} else {
4167e5049a17SRandall Stewart 		return((*tp->t_fb->tfb_compute_pipe)(tp));
4168e5049a17SRandall Stewart 	}
416912eeb81fSHiren Panchasara }
41707dc90a1dSMichael Tuexen 
41717dc90a1dSMichael Tuexen uint32_t
41727dc90a1dSMichael Tuexen tcp_compute_initwnd(uint32_t maxseg)
41737dc90a1dSMichael Tuexen {
41747dc90a1dSMichael Tuexen 	/*
41757dc90a1dSMichael Tuexen 	 * Calculate the Initial Window, also used as Restart Window
41767dc90a1dSMichael Tuexen 	 *
41777dc90a1dSMichael Tuexen 	 * RFC5681 Section 3.1 specifies the default conservative values.
41787dc90a1dSMichael Tuexen 	 * RFC3390 specifies slightly more aggressive values.
41797dc90a1dSMichael Tuexen 	 * RFC6928 increases it to ten segments.
41807dc90a1dSMichael Tuexen 	 * Support for user specified value for initial flight size.
41817dc90a1dSMichael Tuexen 	 */
41827dc90a1dSMichael Tuexen 	if (V_tcp_initcwnd_segments)
41837dc90a1dSMichael Tuexen 		return min(V_tcp_initcwnd_segments * maxseg,
41847dc90a1dSMichael Tuexen 		    max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
41857dc90a1dSMichael Tuexen 	else if (V_tcp_do_rfc3390)
41867dc90a1dSMichael Tuexen 		return min(4 * maxseg, max(2 * maxseg, 4380));
41877dc90a1dSMichael Tuexen 	else {
41887dc90a1dSMichael Tuexen 		/* Per RFC5681 Section 3.1 */
41897dc90a1dSMichael Tuexen 		if (maxseg > 2190)
41907dc90a1dSMichael Tuexen 			return (2 * maxseg);
41917dc90a1dSMichael Tuexen 		else if (maxseg > 1095)
41927dc90a1dSMichael Tuexen 			return (3 * maxseg);
41937dc90a1dSMichael Tuexen 		else
41947dc90a1dSMichael Tuexen 			return (4 * maxseg);
41957dc90a1dSMichael Tuexen 	}
41967dc90a1dSMichael Tuexen }
4197