2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2007-2008,2010
5 * Swinburne University of Technology, Melbourne, Australia.
6 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
7 * Copyright (c) 2010 The FreeBSD Foundation
8 * Copyright (c) 2010-2011 Juniper Networks, Inc.
11 * Portions of this software were developed at the Centre for Advanced Internet
12 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
13 * James Healy and David Hayes, made possible in part by a grant from the Cisco
14 * University Research Program Fund at Community Foundation Silicon Valley.
16 * Portions of this software were developed at the Centre for Advanced
17 * Internet Architectures, Swinburne University of Technology, Melbourne,
18 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
20 * Portions of this software were developed by Robert N. M. Watson under
21 * contract to Juniper Networks, Inc.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
53 #include "opt_ipfw.h" /* for ipfw_fwd */
55 #include "opt_inet6.h"
56 #include "opt_ipsec.h"
57 #include "opt_kdtrace.h"
58 #include "opt_tcpdebug.h"
60 #include <sys/param.h>
61 #include <sys/kernel.h>
62 #include <sys/hhook.h>
63 #include <sys/malloc.h>
65 #include <sys/proc.h> /* for proc0 declaration */
66 #include <sys/protosw.h>
68 #include <sys/signalvar.h>
69 #include <sys/socket.h>
70 #include <sys/socketvar.h>
71 #include <sys/sysctl.h>
72 #include <sys/syslog.h>
73 #include <sys/systm.h>
75 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
80 #include <net/route.h>
83 #define TCPSTATES /* for logging */
85 #include <netinet/cc.h>
86 #include <netinet/in.h>
87 #include <netinet/in_kdtrace.h>
88 #include <netinet/in_pcb.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/in_var.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
93 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
94 #include <netinet/ip_var.h>
95 #include <netinet/ip_options.h>
96 #include <netinet/ip6.h>
97 #include <netinet/icmp6.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
102 #include <netinet/tcp_fastopen.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
108 #include <netinet6/tcp6_var.h>
109 #include <netinet/tcpip.h>
110 #include <netinet/tcp_syncache.h>
112 #include <netinet/tcp_debug.h>
113 #endif /* TCPDEBUG */
115 #include <netinet/tcp_offload.h>
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
123 #include <machine/in_cksum.h>
125 #include <security/mac/mac_framework.h>
127 const int tcprexmtthresh = 3;
129 int tcp_log_in_vain = 0;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
132 "Log all incoming TCP segments to closed ports");
134 VNET_DEFINE(int, blackhole) = 0;
135 #define V_blackhole VNET(blackhole)
136 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
137 &VNET_NAME(blackhole), 0,
138 "Do not send RST on segments to closed ports");
140 VNET_DEFINE(int, tcp_delack_enabled) = 1;
141 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
142 &VNET_NAME(tcp_delack_enabled), 0,
143 "Delay ACK to try and piggyback it onto a data packet");
145 VNET_DEFINE(int, drop_synfin) = 0;
146 #define V_drop_synfin VNET(drop_synfin)
147 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
148 &VNET_NAME(drop_synfin), 0,
149 "Drop TCP packets with SYN+FIN set");
151 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
152 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_pipe, CTLFLAG_VNET | CTLFLAG_RW,
153 &VNET_NAME(tcp_do_rfc6675_pipe), 0,
154 "Use calculated pipe/in-flight bytes per RFC 6675");
156 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
157 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
158 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
159 &VNET_NAME(tcp_do_rfc3042), 0,
160 "Enable RFC 3042 (Limited Transmit)");
162 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
163 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
164 &VNET_NAME(tcp_do_rfc3390), 0,
165 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
167 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, experimental, CTLFLAG_RW, 0,
168 "Experimental TCP extensions");
170 VNET_DEFINE(int, tcp_do_initcwnd10) = 1;
171 SYSCTL_VNET_INT(_net_inet_tcp_experimental, OID_AUTO, initcwnd10, CTLFLAG_RW,
172 &VNET_NAME(tcp_do_initcwnd10), 0,
173 "Enable RFC 6928 (Increasing initial CWND to 10)");
175 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
176 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
177 &VNET_NAME(tcp_do_rfc3465), 0,
178 "Enable RFC 3465 (Appropriate Byte Counting)");
180 VNET_DEFINE(int, tcp_abc_l_var) = 2;
181 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
182 &VNET_NAME(tcp_abc_l_var), 2,
183 "Cap the max cwnd increment during slow-start to this number of segments");
185 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
187 VNET_DEFINE(int, tcp_do_ecn) = 2;
188 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
189 &VNET_NAME(tcp_do_ecn), 0,
192 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
193 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
194 &VNET_NAME(tcp_ecn_maxretries), 0,
195 "Max retries before giving up on ECN");
197 VNET_DEFINE(int, tcp_insecure_rst) = 0;
198 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
199 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
200 &VNET_NAME(tcp_insecure_rst), 0,
201 "Follow the old (insecure) criteria for accepting RST packets");
203 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
204 #define V_tcp_recvspace VNET(tcp_recvspace)
205 SYSCTL_VNET_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
206 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
208 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
209 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
210 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
211 &VNET_NAME(tcp_do_autorcvbuf), 0,
212 "Enable automatic receive buffer sizing");
214 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
215 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
216 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
217 &VNET_NAME(tcp_autorcvbuf_inc), 0,
218 "Incrementor step size of automatic receive buffer");
220 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
221 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
222 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
223 &VNET_NAME(tcp_autorcvbuf_max), 0,
224 "Max size of automatic receive buffer");
226 VNET_DEFINE(struct inpcbhead, tcb);
227 #define tcb6 tcb /* for KAME src sync over BSD*'s */
228 VNET_DEFINE(struct inpcbinfo, tcbinfo);
230 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
231 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
232 struct socket *, struct tcpcb *, int, int, uint8_t,
234 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
235 struct tcpcb *, int, int);
236 static void tcp_pulloutofband(struct socket *,
237 struct tcphdr *, struct mbuf *, int);
238 static void tcp_xmit_timer(struct tcpcb *, int);
239 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
240 static void inline cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
242 static void inline cc_conn_init(struct tcpcb *tp);
243 static void inline cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
244 static void inline hhook_run_tcp_est_in(struct tcpcb *tp,
245 struct tcphdr *th, struct tcpopt *to);
248 * TCP statistics are stored in an "array" of counter(9)s.
250 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
251 VNET_PCPUSTAT_SYSINIT(tcpstat);
252 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
253 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
256 VNET_PCPUSTAT_SYSUNINIT(tcpstat);
259 * Kernel module interface for updating tcpstat. The argument is an index
260 * into tcpstat treated as an array.
263 kmod_tcpstat_inc(int statnum)
266 counter_u64_add(VNET(tcpstat)[statnum], 1);
270 * Wrapper for the TCP established input helper hook.
273 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
275 struct tcp_hhook_data hhook_data;
277 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
282 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
288 * CC wrapper hook functions
291 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
293 INP_WLOCK_ASSERT(tp->t_inpcb);
295 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
296 if (tp->snd_cwnd <= tp->snd_wnd)
297 tp->ccv->flags |= CCF_CWND_LIMITED;
299 tp->ccv->flags &= ~CCF_CWND_LIMITED;
301 if (type == CC_ACK) {
302 if (tp->snd_cwnd > tp->snd_ssthresh) {
303 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
304 V_tcp_abc_l_var * tp->t_maxseg);
305 if (tp->t_bytes_acked >= tp->snd_cwnd) {
306 tp->t_bytes_acked -= tp->snd_cwnd;
307 tp->ccv->flags |= CCF_ABC_SENTAWND;
310 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
311 tp->t_bytes_acked = 0;
315 if (CC_ALGO(tp)->ack_received != NULL) {
316 /* XXXLAS: Find a way to live without this */
317 tp->ccv->curack = th->th_ack;
318 CC_ALGO(tp)->ack_received(tp->ccv, type);
323 cc_conn_init(struct tcpcb *tp)
325 struct hc_metrics_lite metrics;
326 struct inpcb *inp = tp->t_inpcb;
329 INP_WLOCK_ASSERT(tp->t_inpcb);
331 tcp_hc_get(&inp->inp_inc, &metrics);
333 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
335 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
336 TCPSTAT_INC(tcps_usedrtt);
337 if (metrics.rmx_rttvar) {
338 tp->t_rttvar = metrics.rmx_rttvar;
339 TCPSTAT_INC(tcps_usedrttvar);
341 /* default variation is +- 1 rtt */
343 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
345 TCPT_RANGESET(tp->t_rxtcur,
346 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
347 tp->t_rttmin, TCPTV_REXMTMAX);
349 if (metrics.rmx_ssthresh) {
351 * There's some sort of gateway or interface
352 * buffer limit on the path. Use this to set
353 * the slow start threshhold, but set the
354 * threshold to no less than 2*mss.
356 tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
357 TCPSTAT_INC(tcps_usedssthresh);
361 * Set the initial slow-start flight size.
363 * RFC5681 Section 3.1 specifies the default conservative values.
364 * RFC3390 specifies slightly more aggressive values.
365 * RFC6928 increases it to ten segments.
367 * If a SYN or SYN/ACK was lost and retransmitted, we have to
368 * reduce the initial CWND to one segment as congestion is likely
369 * requiring us to be cautious.
371 if (tp->snd_cwnd == 1)
372 tp->snd_cwnd = tp->t_maxseg; /* SYN(-ACK) lost */
373 else if (V_tcp_do_initcwnd10)
374 tp->snd_cwnd = min(10 * tp->t_maxseg,
375 max(2 * tp->t_maxseg, 14600));
376 else if (V_tcp_do_rfc3390)
377 tp->snd_cwnd = min(4 * tp->t_maxseg,
378 max(2 * tp->t_maxseg, 4380));
380 /* Per RFC5681 Section 3.1 */
381 if (tp->t_maxseg > 2190)
382 tp->snd_cwnd = 2 * tp->t_maxseg;
383 else if (tp->t_maxseg > 1095)
384 tp->snd_cwnd = 3 * tp->t_maxseg;
386 tp->snd_cwnd = 4 * tp->t_maxseg;
389 if (CC_ALGO(tp)->conn_init != NULL)
390 CC_ALGO(tp)->conn_init(tp->ccv);
394 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
396 INP_WLOCK_ASSERT(tp->t_inpcb);
400 if (!IN_FASTRECOVERY(tp->t_flags)) {
401 tp->snd_recover = tp->snd_max;
402 if (tp->t_flags & TF_ECN_PERMIT)
403 tp->t_flags |= TF_ECN_SND_CWR;
407 if (!IN_CONGRECOVERY(tp->t_flags)) {
408 TCPSTAT_INC(tcps_ecn_rcwnd);
409 tp->snd_recover = tp->snd_max;
410 if (tp->t_flags & TF_ECN_PERMIT)
411 tp->t_flags |= TF_ECN_SND_CWR;
416 tp->t_bytes_acked = 0;
417 EXIT_RECOVERY(tp->t_flags);
418 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
419 tp->t_maxseg) * tp->t_maxseg;
420 tp->snd_cwnd = tp->t_maxseg;
423 TCPSTAT_INC(tcps_sndrexmitbad);
424 /* RTO was unnecessary, so reset everything. */
425 tp->snd_cwnd = tp->snd_cwnd_prev;
426 tp->snd_ssthresh = tp->snd_ssthresh_prev;
427 tp->snd_recover = tp->snd_recover_prev;
428 if (tp->t_flags & TF_WASFRECOVERY)
429 ENTER_FASTRECOVERY(tp->t_flags);
430 if (tp->t_flags & TF_WASCRECOVERY)
431 ENTER_CONGRECOVERY(tp->t_flags);
432 tp->snd_nxt = tp->snd_max;
433 tp->t_flags &= ~TF_PREVVALID;
438 if (CC_ALGO(tp)->cong_signal != NULL) {
440 tp->ccv->curack = th->th_ack;
441 CC_ALGO(tp)->cong_signal(tp->ccv, type);
446 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
448 INP_WLOCK_ASSERT(tp->t_inpcb);
450 /* XXXLAS: KASSERT that we're in recovery? */
452 if (CC_ALGO(tp)->post_recovery != NULL) {
453 tp->ccv->curack = th->th_ack;
454 CC_ALGO(tp)->post_recovery(tp->ccv);
456 /* XXXLAS: EXIT_RECOVERY ? */
457 tp->t_bytes_acked = 0;
462 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
463 struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
467 tcp_fields_to_net(th);
468 ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
469 tcp_fields_to_host(th);
474 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
476 #define ND6_HINT(tp) \
478 if ((tp) && (tp)->t_inpcb && \
479 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
480 nd6_nud_hint(NULL, NULL, 0); \
487 * Indicate whether this ack should be delayed. We can delay the ack if
488 * - there is no delayed ack timer in progress and
489 * - our last ack wasn't a 0-sized window. We never want to delay
490 * the ack that opens up a 0-sized window and
491 * - delayed acks are enabled or
492 * - this is a half-synchronized T/TCP connection.
493 * - the segment size is not larger than the MSS and LRO wasn't used
496 #define DELAY_ACK(tp, tlen) \
497 ((!tcp_timer_active(tp, TT_DELACK) && \
498 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
499 (tlen <= tp->t_maxopd) && \
500 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
503 * TCP input handling is split into multiple parts:
504 * tcp6_input is a thin wrapper around tcp_input for the extended
505 * ip6_protox[] call format in ip6_input
506 * tcp_input handles primary segment validation, inpcb lookup and
507 * SYN processing on listen sockets
508 * tcp_do_segment processes the ACK and text of the segment for
509 * establishing, established and closing connections
513 tcp6_input(struct mbuf **mp, int *offp, int proto)
515 struct mbuf *m = *mp;
516 struct in6_ifaddr *ia6;
518 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
521 * draft-itojun-ipv6-tcp-to-anycast
522 * better place to put this in?
524 ia6 = ip6_getdstifaddr(m);
525 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
528 ifa_free(&ia6->ia_ifa);
529 ip6 = mtod(m, struct ip6_hdr *);
530 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
531 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
535 ifa_free(&ia6->ia_ifa);
543 tcp_input(struct mbuf *m, int off0)
545 struct tcphdr *th = NULL;
546 struct ip *ip = NULL;
547 struct inpcb *inp = NULL;
548 struct tcpcb *tp = NULL;
549 struct socket *so = NULL;
558 int rstreason = 0; /* For badport_bandlim accounting purposes */
560 uint8_t sig_checked = 0;
563 struct m_tag *fwd_tag = NULL;
565 struct ip6_hdr *ip6 = NULL;
568 const void *ip6 = NULL;
570 struct tcpopt to; /* options in this segment */
571 char *s = NULL; /* address and port logging */
573 #define TI_UNLOCKED 1
578 * The size of tcp_saveipgen must be the size of the max ip header,
581 u_char tcp_saveipgen[IP6_HDR_LEN];
582 struct tcphdr tcp_savetcp;
587 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
591 TCPSTAT_INC(tcps_rcvtotal);
595 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
597 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
598 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
600 TCPSTAT_INC(tcps_rcvshort);
605 ip6 = mtod(m, struct ip6_hdr *);
606 th = (struct tcphdr *)((caddr_t)ip6 + off0);
607 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
608 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
609 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
610 th->th_sum = m->m_pkthdr.csum_data;
612 th->th_sum = in6_cksum_pseudo(ip6, tlen,
613 IPPROTO_TCP, m->m_pkthdr.csum_data);
614 th->th_sum ^= 0xffff;
616 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
618 TCPSTAT_INC(tcps_rcvbadsum);
623 * Be proactive about unspecified IPv6 address in source.
624 * As we use all-zero to indicate unbounded/unconnected pcb,
625 * unspecified IPv6 address can be used to confuse us.
627 * Note that packets with unspecified IPv6 destination is
628 * already dropped in ip6_input.
630 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
636 #if defined(INET) && defined(INET6)
642 * Get IP and TCP header together in first mbuf.
643 * Note: IP leaves IP header in first mbuf.
645 if (off0 > sizeof (struct ip)) {
647 off0 = sizeof(struct ip);
649 if (m->m_len < sizeof (struct tcpiphdr)) {
650 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
652 TCPSTAT_INC(tcps_rcvshort);
656 ip = mtod(m, struct ip *);
657 th = (struct tcphdr *)((caddr_t)ip + off0);
658 tlen = ntohs(ip->ip_len) - off0;
660 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
661 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
662 th->th_sum = m->m_pkthdr.csum_data;
664 th->th_sum = in_pseudo(ip->ip_src.s_addr,
666 htonl(m->m_pkthdr.csum_data + tlen +
668 th->th_sum ^= 0xffff;
670 struct ipovly *ipov = (struct ipovly *)ip;
673 * Checksum extended TCP header and data.
676 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
677 ipov->ih_len = htons(tlen);
678 th->th_sum = in_cksum(m, len);
679 /* Reset length for SDT probes. */
680 ip->ip_len = htons(tlen + off0);
684 TCPSTAT_INC(tcps_rcvbadsum);
687 /* Re-initialization for later version check */
688 ip->ip_v = IPVERSION;
694 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
696 #if defined(INET) && defined(INET6)
704 * Check that TCP offset makes sense,
705 * pull out TCP options and adjust length. XXX
707 off = th->th_off << 2;
708 if (off < sizeof (struct tcphdr) || off > tlen) {
709 TCPSTAT_INC(tcps_rcvbadoff);
712 tlen -= off; /* tlen is used instead of ti->ti_len */
713 if (off > sizeof (struct tcphdr)) {
716 IP6_EXTHDR_CHECK(m, off0, off, );
717 ip6 = mtod(m, struct ip6_hdr *);
718 th = (struct tcphdr *)((caddr_t)ip6 + off0);
721 #if defined(INET) && defined(INET6)
726 if (m->m_len < sizeof(struct ip) + off) {
727 if ((m = m_pullup(m, sizeof (struct ip) + off))
729 TCPSTAT_INC(tcps_rcvshort);
732 ip = mtod(m, struct ip *);
733 th = (struct tcphdr *)((caddr_t)ip + off0);
737 optlen = off - sizeof (struct tcphdr);
738 optp = (u_char *)(th + 1);
740 thflags = th->th_flags;
743 * Convert TCP protocol specific fields to host format.
745 tcp_fields_to_host(th);
748 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
750 drop_hdrlen = off0 + off;
753 * Locate pcb for segment; if we're likely to add or remove a
754 * connection then first acquire pcbinfo lock. There are three cases
755 * where we might discover later we need a write lock despite the
756 * flags: ACKs moving a connection out of the syncache, ACKs for a
757 * connection in TIMEWAIT and SYNs not targeting a listening socket.
759 if ((thflags & (TH_FIN | TH_RST)) != 0) {
760 INP_INFO_RLOCK(&V_tcbinfo);
761 ti_locked = TI_RLOCKED;
763 ti_locked = TI_UNLOCKED;
766 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
770 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
772 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
775 #if defined(INET) && !defined(INET6)
776 (m->m_flags & M_IP_NEXTHOP)
779 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
783 if (ti_locked == TI_RLOCKED) {
784 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
786 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
790 if (isipv6 && fwd_tag != NULL) {
791 struct sockaddr_in6 *next_hop6;
793 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
795 * Transparently forwarded. Pretend to be the destination.
796 * Already got one like this?
798 inp = in6_pcblookup_mbuf(&V_tcbinfo,
799 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
800 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
803 * It's new. Try to find the ambushing socket.
804 * Because we've rewritten the destination address,
805 * any hardware-generated hash is ignored.
807 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
808 th->th_sport, &next_hop6->sin6_addr,
809 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
810 th->th_dport, INPLOOKUP_WILDCARD |
811 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
814 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
815 th->th_sport, &ip6->ip6_dst, th->th_dport,
816 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
817 m->m_pkthdr.rcvif, m);
820 #if defined(INET6) && defined(INET)
824 if (fwd_tag != NULL) {
825 struct sockaddr_in *next_hop;
827 next_hop = (struct sockaddr_in *)(fwd_tag+1);
829 * Transparently forwarded. Pretend to be the destination.
830 * already got one like this?
832 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
833 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
834 m->m_pkthdr.rcvif, m);
837 * It's new. Try to find the ambushing socket.
838 * Because we've rewritten the destination address,
839 * any hardware-generated hash is ignored.
841 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
842 th->th_sport, next_hop->sin_addr,
843 next_hop->sin_port ? ntohs(next_hop->sin_port) :
844 th->th_dport, INPLOOKUP_WILDCARD |
845 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
848 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
849 th->th_sport, ip->ip_dst, th->th_dport,
850 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
851 m->m_pkthdr.rcvif, m);
855 * If the INPCB does not exist then all data in the incoming
856 * segment is discarded and an appropriate RST is sent back.
857 * XXX MRT Send RST using which routing table?
861 * Log communication attempts to ports that are not
864 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
865 tcp_log_in_vain == 2) {
866 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
867 log(LOG_INFO, "%s; %s: Connection attempt "
868 "to closed port\n", s, __func__);
871 * When blackholing do not respond with a RST but
872 * completely ignore the segment and drop it.
874 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
878 rstreason = BANDLIM_RST_CLOSEDPORT;
881 INP_WLOCK_ASSERT(inp);
883 * While waiting for inp lock during the lookup, another thread
884 * can have dropped the inpcb, in which case we need to loop back
885 * and try to find a new inpcb to deliver to.
887 if (inp->inp_flags & INP_DROPPED) {
892 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
893 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
894 ((inp->inp_socket == NULL) ||
895 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
896 inp->inp_flowid = m->m_pkthdr.flowid;
897 inp->inp_flowtype = M_HASHTYPE_GET(m);
901 if (isipv6 && ipsec6_in_reject(m, inp)) {
902 IPSEC6STAT_INC(ips_in_polvio);
906 if (ipsec4_in_reject(m, inp) != 0) {
907 IPSECSTAT_INC(ips_in_polvio);
913 * Check the minimum TTL for socket.
915 if (inp->inp_ip_minttl != 0) {
917 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
921 if (inp->inp_ip_minttl > ip->ip_ttl)
926 * A previous connection in TIMEWAIT state is supposed to catch stray
927 * or duplicate segments arriving late. If this segment was a
928 * legitimate new connection attempt, the old INPCB gets removed and
929 * we can try again to find a listening socket.
931 * At this point, due to earlier optimism, we may hold only an inpcb
932 * lock, and not the inpcbinfo write lock. If so, we need to try to
933 * acquire it, or if that fails, acquire a reference on the inpcb,
934 * drop all locks, acquire a global write lock, and then re-acquire
935 * the inpcb lock. We may at that point discover that another thread
936 * has tried to free the inpcb, in which case we need to loop back
937 * and try to find a new inpcb to deliver to.
939 * XXXRW: It may be time to rethink timewait locking.
942 if (inp->inp_flags & INP_TIMEWAIT) {
943 if (ti_locked == TI_UNLOCKED) {
944 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
947 INP_INFO_RLOCK(&V_tcbinfo);
948 ti_locked = TI_RLOCKED;
950 if (in_pcbrele_wlocked(inp)) {
953 } else if (inp->inp_flags & INP_DROPPED) {
959 ti_locked = TI_RLOCKED;
961 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
963 if (thflags & TH_SYN)
964 tcp_dooptions(&to, optp, optlen, TO_SYN);
966 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
968 if (tcp_twcheck(inp, &to, th, m, tlen))
970 INP_INFO_RUNLOCK(&V_tcbinfo);
974 * The TCPCB may no longer exist if the connection is winding
975 * down or it is in the CLOSED state. Either way we drop the
976 * segment and send an appropriate response.
979 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
980 rstreason = BANDLIM_RST_CLOSEDPORT;
985 if (tp->t_flags & TF_TOE) {
986 tcp_offload_input(tp, m);
987 m = NULL; /* consumed by the TOE driver */
993 * We've identified a valid inpcb, but it could be that we need an
994 * inpcbinfo write lock but don't hold it. In this case, attempt to
995 * acquire using the same strategy as the TIMEWAIT case above. If we
996 * relock, we have to jump back to 'relocked' as the connection might
997 * now be in TIMEWAIT.
1000 if ((thflags & (TH_FIN | TH_RST)) != 0)
1001 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1003 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1004 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
1005 !(tp->t_flags & TF_FASTOPEN)))) {
1006 if (ti_locked == TI_UNLOCKED) {
1007 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
1010 INP_INFO_RLOCK(&V_tcbinfo);
1011 ti_locked = TI_RLOCKED;
1013 if (in_pcbrele_wlocked(inp)) {
1016 } else if (inp->inp_flags & INP_DROPPED) {
1023 ti_locked = TI_RLOCKED;
1025 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1029 INP_WLOCK_ASSERT(inp);
1030 if (mac_inpcb_check_deliver(inp, m))
1033 so = inp->inp_socket;
1034 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1036 if (so->so_options & SO_DEBUG) {
1037 ostate = tp->t_state;
1040 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1043 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1046 #endif /* TCPDEBUG */
1048 * When the socket is accepting connections (the INPCB is in LISTEN
1049 * state) we look into the SYN cache if this is a new connection
1050 * attempt or the completion of a previous one.
1052 if (so->so_options & SO_ACCEPTCONN) {
1053 struct in_conninfo inc;
1055 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
1056 "tp not listening", __func__));
1057 bzero(&inc, sizeof(inc));
1060 inc.inc_flags |= INC_ISIPV6;
1061 inc.inc6_faddr = ip6->ip6_src;
1062 inc.inc6_laddr = ip6->ip6_dst;
1066 inc.inc_faddr = ip->ip_src;
1067 inc.inc_laddr = ip->ip_dst;
1069 inc.inc_fport = th->th_sport;
1070 inc.inc_lport = th->th_dport;
1071 inc.inc_fibnum = so->so_fibnum;
1074 * Check for an existing connection attempt in syncache if
1075 * the flag is only ACK. A successful lookup creates a new
1076 * socket appended to the listen queue in SYN_RECEIVED state.
1078 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1080 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1082 * Parse the TCP options here because
1083 * syncookies need access to the reflected
1086 tcp_dooptions(&to, optp, optlen, 0);
1088 * NB: syncache_expand() doesn't unlock
1089 * inp and tcpinfo locks.
1091 if (!syncache_expand(&inc, &to, th, &so, m)) {
1093 * No syncache entry or ACK was not
1094 * for our SYN/ACK. Send a RST.
1095 * NB: syncache did its own logging
1096 * of the failure cause.
1098 rstreason = BANDLIM_RST_OPENPORT;
1106 * We completed the 3-way handshake
1107 * but could not allocate a socket
1108 * either due to memory shortage,
1109 * listen queue length limits or
1110 * global socket limits. Send RST
1111 * or wait and have the remote end
1112 * retransmit the ACK for another
1115 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1116 log(LOG_DEBUG, "%s; %s: Listen socket: "
1117 "Socket allocation failed due to "
1118 "limits or memory shortage, %s\n",
1120 V_tcp_sc_rst_sock_fail ?
1121 "sending RST" : "try again");
1122 if (V_tcp_sc_rst_sock_fail) {
1123 rstreason = BANDLIM_UNLIMITED;
1129 * Socket is created in state SYN_RECEIVED.
1130 * Unlock the listen socket, lock the newly
1131 * created socket and update the tp variable.
1133 INP_WUNLOCK(inp); /* listen socket */
1134 inp = sotoinpcb(so);
1136 * New connection inpcb is already locked by
1137 * syncache_expand().
1139 INP_WLOCK_ASSERT(inp);
1140 tp = intotcpcb(inp);
1141 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1142 ("%s: ", __func__));
1143 #ifdef TCP_SIGNATURE
1144 if (sig_checked == 0) {
1145 tcp_dooptions(&to, optp, optlen,
1146 (thflags & TH_SYN) ? TO_SYN : 0);
1147 if (!tcp_signature_verify_input(m, off0, tlen,
1148 optlen, &to, th, tp->t_flags)) {
1151 * In SYN_SENT state if it receives an
1152 * RST, it is allowed for further
1155 if ((thflags & TH_RST) == 0 ||
1156 (tp->t_state == TCPS_SYN_SENT) == 0)
1164 * Process the segment and the data it
1165 * contains. tcp_do_segment() consumes
1166 * the mbuf chain and unlocks the inpcb.
1168 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1170 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1174 * Segment flag validation for new connection attempts:
1176 * Our (SYN|ACK) response was rejected.
1177 * Check with syncache and remove entry to prevent
1180 * NB: syncache_chkrst does its own logging of failure
1183 if (thflags & TH_RST) {
1184 syncache_chkrst(&inc, th);
1188 * We can't do anything without SYN.
1190 if ((thflags & TH_SYN) == 0) {
1191 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1192 log(LOG_DEBUG, "%s; %s: Listen socket: "
1193 "SYN is missing, segment ignored\n",
1195 TCPSTAT_INC(tcps_badsyn);
1199 * (SYN|ACK) is bogus on a listen socket.
1201 if (thflags & TH_ACK) {
1202 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1203 log(LOG_DEBUG, "%s; %s: Listen socket: "
1204 "SYN|ACK invalid, segment rejected\n",
1206 syncache_badack(&inc); /* XXX: Not needed! */
1207 TCPSTAT_INC(tcps_badsyn);
1208 rstreason = BANDLIM_RST_OPENPORT;
1212 * If the drop_synfin option is enabled, drop all
1213 * segments with both the SYN and FIN bits set.
1214 * This prevents e.g. nmap from identifying the
1216 * XXX: Poor reasoning. nmap has other methods
1217 * and is constantly refining its stack detection
1219 * XXX: This is a violation of the TCP specification
1220 * and was used by RFC1644.
1222 if ((thflags & TH_FIN) && V_drop_synfin) {
1223 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1224 log(LOG_DEBUG, "%s; %s: Listen socket: "
1225 "SYN|FIN segment ignored (based on "
1226 "sysctl setting)\n", s, __func__);
1227 TCPSTAT_INC(tcps_badsyn);
1231 * Segment's flags are (SYN) or (SYN|FIN).
1233 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1234 * as they do not affect the state of the TCP FSM.
1235 * The data pointed to by TH_URG and th_urp is ignored.
1237 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1238 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1239 KASSERT(thflags & (TH_SYN),
1240 ("%s: Listen socket: TH_SYN not set", __func__));
1243 * If deprecated address is forbidden,
1244 * we do not accept SYN to deprecated interface
1245 * address to prevent any new inbound connection from
1246 * getting established.
1247 * When we do not accept SYN, we send a TCP RST,
1248 * with deprecated source address (instead of dropping
1249 * it). We compromise it as it is much better for peer
1250 * to send a RST, and RST will be the final packet
1253 * If we do not forbid deprecated addresses, we accept
1254 * the SYN packet. RFC2462 does not suggest dropping
1256 * If we decipher RFC2462 5.5.4, it says like this:
1257 * 1. use of deprecated addr with existing
1258 * communication is okay - "SHOULD continue to be
1260 * 2. use of it with new communication:
1261 * (2a) "SHOULD NOT be used if alternate address
1262 * with sufficient scope is available"
1263 * (2b) nothing mentioned otherwise.
1264 * Here we fall into (2b) case as we have no choice in
1265 * our source address selection - we must obey the peer.
1267 * The wording in RFC2462 is confusing, and there are
1268 * multiple description text for deprecated address
1269 * handling - worse, they are not exactly the same.
1270 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1272 if (isipv6 && !V_ip6_use_deprecated) {
1273 struct in6_ifaddr *ia6;
1275 ia6 = ip6_getdstifaddr(m);
1277 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1278 ifa_free(&ia6->ia_ifa);
1279 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1280 log(LOG_DEBUG, "%s; %s: Listen socket: "
1281 "Connection attempt to deprecated "
1282 "IPv6 address rejected\n",
1284 rstreason = BANDLIM_RST_OPENPORT;
1288 ifa_free(&ia6->ia_ifa);
1292 * Basic sanity checks on incoming SYN requests:
1293 * Don't respond if the destination is a link layer
1294 * broadcast according to RFC1122 4.2.3.10, p. 104.
1295 * If it is from this socket it must be forged.
1296 * Don't respond if the source or destination is a
1297 * global or subnet broad- or multicast address.
1298 * Note that it is quite possible to receive unicast
1299 * link-layer packets with a broadcast IP address. Use
1300 * in_broadcast() to find them.
1302 if (m->m_flags & (M_BCAST|M_MCAST)) {
1303 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1304 log(LOG_DEBUG, "%s; %s: Listen socket: "
1305 "Connection attempt from broad- or multicast "
1306 "link layer address ignored\n", s, __func__);
1311 if (th->th_dport == th->th_sport &&
1312 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1313 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1314 log(LOG_DEBUG, "%s; %s: Listen socket: "
1315 "Connection attempt to/from self "
1316 "ignored\n", s, __func__);
1319 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1320 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1321 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1322 log(LOG_DEBUG, "%s; %s: Listen socket: "
1323 "Connection attempt from/to multicast "
1324 "address ignored\n", s, __func__);
1329 #if defined(INET) && defined(INET6)
1334 if (th->th_dport == th->th_sport &&
1335 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1336 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1337 log(LOG_DEBUG, "%s; %s: Listen socket: "
1338 "Connection attempt from/to self "
1339 "ignored\n", s, __func__);
1342 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1343 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1344 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1345 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1346 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1347 log(LOG_DEBUG, "%s; %s: Listen socket: "
1348 "Connection attempt from/to broad- "
1349 "or multicast address ignored\n",
1356 * SYN appears to be valid. Create compressed TCP state
1360 if (so->so_options & SO_DEBUG)
1361 tcp_trace(TA_INPUT, ostate, tp,
1362 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1364 tcp_dooptions(&to, optp, optlen, TO_SYN);
1366 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
1367 goto new_tfo_socket;
1369 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1372 * Entry added to syncache and mbuf consumed.
1373 * Only the listen socket is unlocked by syncache_add().
1375 if (ti_locked == TI_RLOCKED) {
1376 INP_INFO_RUNLOCK(&V_tcbinfo);
1377 ti_locked = TI_UNLOCKED;
1379 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1381 } else if (tp->t_state == TCPS_LISTEN) {
1383 * When a listen socket is torn down the SO_ACCEPTCONN
1384 * flag is removed first while connections are drained
1385 * from the accept queue in a unlock/lock cycle of the
1386 * ACCEPT_LOCK, opening a race condition allowing a SYN
1387 * attempt go through unhandled.
1392 #ifdef TCP_SIGNATURE
1393 if (sig_checked == 0) {
1394 tcp_dooptions(&to, optp, optlen,
1395 (thflags & TH_SYN) ? TO_SYN : 0);
1396 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1400 * In SYN_SENT state if it receives an RST, it is
1401 * allowed for further processing.
1403 if ((thflags & TH_RST) == 0 ||
1404 (tp->t_state == TCPS_SYN_SENT) == 0)
1411 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1414 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1415 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1416 * the inpcb, and unlocks pcbinfo.
1418 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1419 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1423 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1425 if (ti_locked == TI_RLOCKED) {
1426 INP_INFO_RUNLOCK(&V_tcbinfo);
1427 ti_locked = TI_UNLOCKED;
1431 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1432 "ti_locked: %d", __func__, ti_locked));
1433 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1438 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1441 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1442 m = NULL; /* mbuf chain got consumed. */
1447 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1449 if (ti_locked == TI_RLOCKED) {
1450 INP_INFO_RUNLOCK(&V_tcbinfo);
1451 ti_locked = TI_UNLOCKED;
1455 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1456 "ti_locked: %d", __func__, ti_locked));
1457 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1465 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1473 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1474 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1477 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1478 int rstreason, todrop, win;
1481 struct in_conninfo *inc;
1488 * The size of tcp_saveipgen must be the size of the max ip header,
1491 u_char tcp_saveipgen[IP6_HDR_LEN];
1492 struct tcphdr tcp_savetcp;
1495 thflags = th->th_flags;
1496 inc = &tp->t_inpcb->inp_inc;
1497 tp->sackhint.last_sack_ack = 0;
1501 * If this is either a state-changing packet or current state isn't
1502 * established, we require a write lock on tcbinfo. Otherwise, we
1503 * allow the tcbinfo to be in either alocked or unlocked, as the
1504 * caller may have unnecessarily acquired a write lock due to a race.
1506 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1507 tp->t_state != TCPS_ESTABLISHED) {
1508 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1509 "SYN/FIN/RST/!EST", __func__, ti_locked));
1510 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1513 if (ti_locked == TI_RLOCKED)
1514 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1516 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1517 "ti_locked: %d", __func__, ti_locked));
1518 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1522 INP_WLOCK_ASSERT(tp->t_inpcb);
1523 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1525 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1529 * Segment received on connection.
1530 * Reset idle time and keep-alive timer.
1531 * XXX: This should be done after segment
1532 * validation to ignore broken/spoofed segs.
1534 tp->t_rcvtime = ticks;
1535 if (TCPS_HAVEESTABLISHED(tp->t_state))
1536 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1539 * Unscale the window into a 32-bit value.
1540 * For the SYN_SENT state the scale is zero.
1542 tiwin = th->th_win << tp->snd_scale;
1545 * TCP ECN processing.
1547 if (tp->t_flags & TF_ECN_PERMIT) {
1548 if (thflags & TH_CWR)
1549 tp->t_flags &= ~TF_ECN_SND_ECE;
1550 switch (iptos & IPTOS_ECN_MASK) {
1552 tp->t_flags |= TF_ECN_SND_ECE;
1553 TCPSTAT_INC(tcps_ecn_ce);
1555 case IPTOS_ECN_ECT0:
1556 TCPSTAT_INC(tcps_ecn_ect0);
1558 case IPTOS_ECN_ECT1:
1559 TCPSTAT_INC(tcps_ecn_ect1);
1562 /* Congestion experienced. */
1563 if (thflags & TH_ECE) {
1564 cc_cong_signal(tp, th, CC_ECN);
1569 * Parse options on any incoming segment.
1571 tcp_dooptions(&to, (u_char *)(th + 1),
1572 (th->th_off << 2) - sizeof(struct tcphdr),
1573 (thflags & TH_SYN) ? TO_SYN : 0);
1576 * If echoed timestamp is later than the current time,
1577 * fall back to non RFC1323 RTT calculation. Normalize
1578 * timestamp if syncookies were used when this connection
1581 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1582 to.to_tsecr -= tp->ts_offset;
1583 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1587 * If timestamps were negotiated during SYN/ACK they should
1588 * appear on every segment during this session and vice versa.
1590 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1591 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1592 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1593 "no action\n", s, __func__);
1597 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1598 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1599 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1600 "no action\n", s, __func__);
1606 * Process options only when we get SYN/ACK back. The SYN case
1607 * for incoming connections is handled in tcp_syncache.
1608 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1609 * or <SYN,ACK>) segment itself is never scaled.
1610 * XXX this is traditional behavior, may need to be cleaned up.
1612 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1613 if ((to.to_flags & TOF_SCALE) &&
1614 (tp->t_flags & TF_REQ_SCALE)) {
1615 tp->t_flags |= TF_RCVD_SCALE;
1616 tp->snd_scale = to.to_wscale;
1619 * Initial send window. It will be updated with
1620 * the next incoming segment to the scaled value.
1622 tp->snd_wnd = th->th_win;
1623 if (to.to_flags & TOF_TS) {
1624 tp->t_flags |= TF_RCVD_TSTMP;
1625 tp->ts_recent = to.to_tsval;
1626 tp->ts_recent_age = tcp_ts_getticks();
1628 if (to.to_flags & TOF_MSS)
1629 tcp_mss(tp, to.to_mss);
1630 if ((tp->t_flags & TF_SACK_PERMIT) &&
1631 (to.to_flags & TOF_SACKPERM) == 0)
1632 tp->t_flags &= ~TF_SACK_PERMIT;
1636 * Header prediction: check for the two common cases
1637 * of a uni-directional data xfer. If the packet has
1638 * no control flags, is in-sequence, the window didn't
1639 * change and we're not retransmitting, it's a
1640 * candidate. If the length is zero and the ack moved
1641 * forward, we're the sender side of the xfer. Just
1642 * free the data acked & wake any higher level process
1643 * that was blocked waiting for space. If the length
1644 * is non-zero and the ack didn't move, we're the
1645 * receiver side. If we're getting packets in-order
1646 * (the reassembly queue is empty), add the data to
1647 * the socket buffer and note that we need a delayed ack.
1648 * Make sure that the hidden state-flags are also off.
1649 * Since we check for TCPS_ESTABLISHED first, it can only
1652 if (tp->t_state == TCPS_ESTABLISHED &&
1653 th->th_seq == tp->rcv_nxt &&
1654 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1655 tp->snd_nxt == tp->snd_max &&
1656 tiwin && tiwin == tp->snd_wnd &&
1657 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1658 LIST_EMPTY(&tp->t_segq) &&
1659 ((to.to_flags & TOF_TS) == 0 ||
1660 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1663 * If last ACK falls within this segment's sequence numbers,
1664 * record the timestamp.
1665 * NOTE that the test is modified according to the latest
1666 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1668 if ((to.to_flags & TOF_TS) != 0 &&
1669 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1670 tp->ts_recent_age = tcp_ts_getticks();
1671 tp->ts_recent = to.to_tsval;
1675 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1676 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1677 !IN_RECOVERY(tp->t_flags) &&
1678 (to.to_flags & TOF_SACK) == 0 &&
1679 TAILQ_EMPTY(&tp->snd_holes)) {
1681 * This is a pure ack for outstanding data.
1683 if (ti_locked == TI_RLOCKED)
1684 INP_INFO_RUNLOCK(&V_tcbinfo);
1685 ti_locked = TI_UNLOCKED;
1687 TCPSTAT_INC(tcps_predack);
1690 * "bad retransmit" recovery.
1692 if (tp->t_rxtshift == 1 &&
1693 tp->t_flags & TF_PREVVALID &&
1694 (int)(ticks - tp->t_badrxtwin) < 0) {
1695 cc_cong_signal(tp, th, CC_RTO_ERR);
1699 * Recalculate the transmit timer / rtt.
1701 * Some boxes send broken timestamp replies
1702 * during the SYN+ACK phase, ignore
1703 * timestamps of 0 or we could calculate a
1704 * huge RTT and blow up the retransmit timer.
1706 if ((to.to_flags & TOF_TS) != 0 &&
1710 t = tcp_ts_getticks() - to.to_tsecr;
1711 if (!tp->t_rttlow || tp->t_rttlow > t)
1714 TCP_TS_TO_TICKS(t) + 1);
1715 } else if (tp->t_rtttime &&
1716 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1717 if (!tp->t_rttlow ||
1718 tp->t_rttlow > ticks - tp->t_rtttime)
1719 tp->t_rttlow = ticks - tp->t_rtttime;
1721 ticks - tp->t_rtttime);
1723 acked = BYTES_THIS_ACK(tp, th);
1725 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1726 hhook_run_tcp_est_in(tp, th, &to);
1728 TCPSTAT_INC(tcps_rcvackpack);
1729 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1730 sbdrop(&so->so_snd, acked);
1731 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1732 SEQ_LEQ(th->th_ack, tp->snd_recover))
1733 tp->snd_recover = th->th_ack - 1;
1736 * Let the congestion control algorithm update
1737 * congestion control related information. This
1738 * typically means increasing the congestion
1741 cc_ack_received(tp, th, CC_ACK);
1743 tp->snd_una = th->th_ack;
1745 * Pull snd_wl2 up to prevent seq wrap relative
1748 tp->snd_wl2 = th->th_ack;
1751 ND6_HINT(tp); /* Some progress has been made. */
1754 * If all outstanding data are acked, stop
1755 * retransmit timer, otherwise restart timer
1756 * using current (possibly backed-off) value.
1757 * If process is waiting for space,
1758 * wakeup/selwakeup/signal. If data
1759 * are ready to send, let tcp_output
1760 * decide between more output or persist.
1763 if (so->so_options & SO_DEBUG)
1764 tcp_trace(TA_INPUT, ostate, tp,
1765 (void *)tcp_saveipgen,
1768 if (tp->snd_una == tp->snd_max)
1769 tcp_timer_activate(tp, TT_REXMT, 0);
1770 else if (!tcp_timer_active(tp, TT_PERSIST))
1771 tcp_timer_activate(tp, TT_REXMT,
1774 if (so->so_snd.sb_cc)
1775 (void) tcp_output(tp);
1778 } else if (th->th_ack == tp->snd_una &&
1779 tlen <= sbspace(&so->so_rcv)) {
1780 int newsize = 0; /* automatic sockbuf scaling */
1783 * This is a pure, in-sequence data packet with
1784 * nothing on the reassembly queue and we have enough
1785 * buffer space to take it.
1787 if (ti_locked == TI_RLOCKED)
1788 INP_INFO_RUNLOCK(&V_tcbinfo);
1789 ti_locked = TI_UNLOCKED;
1791 /* Clean receiver SACK report if present */
1792 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1793 tcp_clean_sackreport(tp);
1794 TCPSTAT_INC(tcps_preddat);
1795 tp->rcv_nxt += tlen;
1797 * Pull snd_wl1 up to prevent seq wrap relative to
1800 tp->snd_wl1 = th->th_seq;
1802 * Pull rcv_up up to prevent seq wrap relative to
1805 tp->rcv_up = tp->rcv_nxt;
1806 TCPSTAT_INC(tcps_rcvpack);
1807 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1808 ND6_HINT(tp); /* Some progress has been made */
1810 if (so->so_options & SO_DEBUG)
1811 tcp_trace(TA_INPUT, ostate, tp,
1812 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1815 * Automatic sizing of receive socket buffer. Often the send
1816 * buffer size is not optimally adjusted to the actual network
1817 * conditions at hand (delay bandwidth product). Setting the
1818 * buffer size too small limits throughput on links with high
1819 * bandwidth and high delay (eg. trans-continental/oceanic links).
1821 * On the receive side the socket buffer memory is only rarely
1822 * used to any significant extent. This allows us to be much
1823 * more aggressive in scaling the receive socket buffer. For
1824 * the case that the buffer space is actually used to a large
1825 * extent and we run out of kernel memory we can simply drop
1826 * the new segments; TCP on the sender will just retransmit it
1827 * later. Setting the buffer size too big may only consume too
1828 * much kernel memory if the application doesn't read() from
1829 * the socket or packet loss or reordering makes use of the
1832 * The criteria to step up the receive buffer one notch are:
1833 * 1. the number of bytes received during the time it takes
1834 * one timestamp to be reflected back to us (the RTT);
1835 * 2. received bytes per RTT is within seven eighth of the
1836 * current socket buffer size;
1837 * 3. receive buffer size has not hit maximal automatic size;
1839 * This algorithm does one step per RTT at most and only if
1840 * we receive a bulk stream w/o packet losses or reorderings.
1841 * Shrinking the buffer during idle times is not necessary as
1842 * it doesn't consume any memory when idle.
1844 * TODO: Only step up if the application is actually serving
1845 * the buffer to better manage the socket buffer resources.
1847 if (V_tcp_do_autorcvbuf &&
1848 (to.to_flags & TOF_TS) &&
1850 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1851 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1852 to.to_tsecr - tp->rfbuf_ts < hz) {
1854 (so->so_rcv.sb_hiwat / 8 * 7) &&
1855 so->so_rcv.sb_hiwat <
1856 V_tcp_autorcvbuf_max) {
1858 min(so->so_rcv.sb_hiwat +
1859 V_tcp_autorcvbuf_inc,
1860 V_tcp_autorcvbuf_max);
1862 /* Start over with next RTT. */
1866 tp->rfbuf_cnt += tlen; /* add up */
1869 /* Add data to socket buffer. */
1870 SOCKBUF_LOCK(&so->so_rcv);
1871 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1875 * Set new socket buffer size.
1876 * Give up when limit is reached.
1879 if (!sbreserve_locked(&so->so_rcv,
1881 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1882 m_adj(m, drop_hdrlen); /* delayed header drop */
1883 sbappendstream_locked(&so->so_rcv, m);
1885 /* NB: sorwakeup_locked() does an implicit unlock. */
1886 sorwakeup_locked(so);
1887 if (DELAY_ACK(tp, tlen)) {
1888 tp->t_flags |= TF_DELACK;
1890 tp->t_flags |= TF_ACKNOW;
1898 * Calculate amount of space in receive window,
1899 * and then do TCP input processing.
1900 * Receive window is amount of space in rcv queue,
1901 * but not less than advertised window.
1903 win = sbspace(&so->so_rcv);
1906 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1908 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1912 switch (tp->t_state) {
1915 * If the state is SYN_RECEIVED:
1916 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1918 case TCPS_SYN_RECEIVED:
1919 if ((thflags & TH_ACK) &&
1920 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1921 SEQ_GT(th->th_ack, tp->snd_max))) {
1922 rstreason = BANDLIM_RST_OPENPORT;
1926 if (tp->t_flags & TF_FASTOPEN) {
1928 * When a TFO connection is in SYN_RECEIVED, the
1929 * only valid packets are the initial SYN, a
1930 * retransmit/copy of the initial SYN (possibly with
1931 * a subset of the original data), a valid ACK, a
1934 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1935 rstreason = BANDLIM_RST_OPENPORT;
1937 } else if (thflags & TH_SYN) {
1938 /* non-initial SYN is ignored */
1939 if ((tcp_timer_active(tp, TT_DELACK) ||
1940 tcp_timer_active(tp, TT_REXMT)))
1942 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1950 * If the state is SYN_SENT:
1951 * if seg contains an ACK, but not for our SYN, drop the input.
1952 * if seg contains a RST, then drop the connection.
1953 * if seg does not contain SYN, then drop it.
1954 * Otherwise this is an acceptable SYN segment
1955 * initialize tp->rcv_nxt and tp->irs
1956 * if seg contains ack then advance tp->snd_una
1957 * if seg contains an ECE and ECN support is enabled, the stream
1959 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1960 * arrange for segment to be acked (eventually)
1961 * continue processing rest of data/controls, beginning with URG
1964 if ((thflags & TH_ACK) &&
1965 (SEQ_LEQ(th->th_ack, tp->iss) ||
1966 SEQ_GT(th->th_ack, tp->snd_max))) {
1967 rstreason = BANDLIM_UNLIMITED;
1970 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1971 TCP_PROBE5(connect__refused, NULL, tp,
1972 mtod(m, const char *), tp, th);
1973 tp = tcp_drop(tp, ECONNREFUSED);
1975 if (thflags & TH_RST)
1977 if (!(thflags & TH_SYN))
1980 tp->irs = th->th_seq;
1982 if (thflags & TH_ACK) {
1983 TCPSTAT_INC(tcps_connects);
1986 mac_socketpeer_set_from_mbuf(m, so);
1988 /* Do window scaling on this connection? */
1989 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1990 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1991 tp->rcv_scale = tp->request_r_scale;
1993 tp->rcv_adv += imin(tp->rcv_wnd,
1994 TCP_MAXWIN << tp->rcv_scale);
1995 tp->snd_una++; /* SYN is acked */
1997 * If there's data, delay ACK; if there's also a FIN
1998 * ACKNOW will be turned on later.
2000 if (DELAY_ACK(tp, tlen) && tlen != 0)
2001 tcp_timer_activate(tp, TT_DELACK,
2004 tp->t_flags |= TF_ACKNOW;
2006 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
2007 tp->t_flags |= TF_ECN_PERMIT;
2008 TCPSTAT_INC(tcps_ecn_shs);
2012 * Received <SYN,ACK> in SYN_SENT[*] state.
2014 * SYN_SENT --> ESTABLISHED
2015 * SYN_SENT* --> FIN_WAIT_1
2017 tp->t_starttime = ticks;
2018 if (tp->t_flags & TF_NEEDFIN) {
2019 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2020 tp->t_flags &= ~TF_NEEDFIN;
2023 tcp_state_change(tp, TCPS_ESTABLISHED);
2024 TCP_PROBE5(connect__established, NULL, tp,
2025 mtod(m, const char *), tp, th);
2027 tcp_timer_activate(tp, TT_KEEP,
2032 * Received initial SYN in SYN-SENT[*] state =>
2033 * simultaneous open. If segment contains CC option
2034 * and there is a cached CC, apply TAO test.
2035 * If it succeeds, connection is * half-synchronized.
2036 * Otherwise, do 3-way handshake:
2037 * SYN-SENT -> SYN-RECEIVED
2038 * SYN-SENT* -> SYN-RECEIVED*
2039 * If there was no CC option, clear cached CC value.
2041 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2042 tcp_timer_activate(tp, TT_REXMT, 0);
2043 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2046 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
2047 "ti_locked %d", __func__, ti_locked));
2048 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2049 INP_WLOCK_ASSERT(tp->t_inpcb);
2052 * Advance th->th_seq to correspond to first data byte.
2053 * If data, trim to stay within window,
2054 * dropping FIN if necessary.
2057 if (tlen > tp->rcv_wnd) {
2058 todrop = tlen - tp->rcv_wnd;
2062 TCPSTAT_INC(tcps_rcvpackafterwin);
2063 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2065 tp->snd_wl1 = th->th_seq - 1;
2066 tp->rcv_up = th->th_seq;
2068 * Client side of transaction: already sent SYN and data.
2069 * If the remote host used T/TCP to validate the SYN,
2070 * our data will be ACK'd; if so, enter normal data segment
2071 * processing in the middle of step 5, ack processing.
2072 * Otherwise, goto step 6.
2074 if (thflags & TH_ACK)
2080 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2081 * do normal processing.
2083 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2087 break; /* continue normal processing */
2091 * States other than LISTEN or SYN_SENT.
2092 * First check the RST flag and sequence number since reset segments
2093 * are exempt from the timestamp and connection count tests. This
2094 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2095 * below which allowed reset segments in half the sequence space
2096 * to fall though and be processed (which gives forged reset
2097 * segments with a random sequence number a 50 percent chance of
2098 * killing a connection).
2099 * Then check timestamp, if present.
2100 * Then check the connection count, if present.
2101 * Then check that at least some bytes of segment are within
2102 * receive window. If segment begins before rcv_nxt,
2103 * drop leading data (and SYN); if nothing left, just ack.
2106 * If the RST bit is set, check the sequence number to see
2107 * if this is a valid reset segment.
2109 * In all states except SYN-SENT, all reset (RST) segments
2110 * are validated by checking their SEQ-fields. A reset is
2111 * valid if its sequence number is in the window.
2112 * Note: this does not take into account delayed ACKs, so
2113 * we should test against last_ack_sent instead of rcv_nxt.
2114 * The sequence number in the reset segment is normally an
2115 * echo of our outgoing acknowlegement numbers, but some hosts
2116 * send a reset with the sequence number at the rightmost edge
2117 * of our receive window, and we have to handle this case.
2118 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
2119 * that brute force RST attacks are possible. To combat this,
2120 * we use a much stricter check while in the ESTABLISHED state,
2121 * only accepting RSTs where the sequence number is equal to
2122 * last_ack_sent. In all other states (the states in which a
2123 * RST is more likely), the more permissive check is used.
2124 * If we have multiple segments in flight, the initial reset
2125 * segment sequence numbers will be to the left of last_ack_sent,
2126 * but they will eventually catch up.
2127 * In any case, it never made sense to trim reset segments to
2128 * fit the receive window since RFC 1122 says:
2129 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
2131 * A TCP SHOULD allow a received RST segment to include data.
2134 * It has been suggested that a RST segment could contain
2135 * ASCII text that encoded and explained the cause of the
2136 * RST. No standard has yet been established for such
2139 * If the reset segment passes the sequence number test examine
2141 * SYN_RECEIVED STATE:
2142 * If passive open, return to LISTEN state.
2143 * If active open, inform user that connection was refused.
2144 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
2145 * Inform user that connection was reset, and close tcb.
2146 * CLOSING, LAST_ACK STATES:
2149 * Drop the segment - see Stevens, vol. 2, p. 964 and
2152 if (thflags & TH_RST) {
2153 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2154 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2155 switch (tp->t_state) {
2157 case TCPS_SYN_RECEIVED:
2158 so->so_error = ECONNREFUSED;
2161 case TCPS_ESTABLISHED:
2162 if (V_tcp_insecure_rst == 0 &&
2163 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
2164 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
2165 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2166 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
2167 TCPSTAT_INC(tcps_badrst);
2171 case TCPS_FIN_WAIT_1:
2172 case TCPS_FIN_WAIT_2:
2173 case TCPS_CLOSE_WAIT:
2174 so->so_error = ECONNRESET;
2176 KASSERT(ti_locked == TI_RLOCKED,
2177 ("tcp_do_segment: TH_RST 1 ti_locked %d",
2179 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2181 tcp_state_change(tp, TCPS_CLOSED);
2182 TCPSTAT_INC(tcps_drops);
2188 KASSERT(ti_locked == TI_RLOCKED,
2189 ("tcp_do_segment: TH_RST 2 ti_locked %d",
2191 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2201 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2202 * and it's less than ts_recent, drop it.
2204 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2205 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2207 /* Check to see if ts_recent is over 24 days old. */
2208 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2210 * Invalidate ts_recent. If this segment updates
2211 * ts_recent, the age will be reset later and ts_recent
2212 * will get a valid value. If it does not, setting
2213 * ts_recent to zero will at least satisfy the
2214 * requirement that zero be placed in the timestamp
2215 * echo reply when ts_recent isn't valid. The
2216 * age isn't reset until we get a valid ts_recent
2217 * because we don't want out-of-order segments to be
2218 * dropped when ts_recent is old.
2222 TCPSTAT_INC(tcps_rcvduppack);
2223 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2224 TCPSTAT_INC(tcps_pawsdrop);
2232 * In the SYN-RECEIVED state, validate that the packet belongs to
2233 * this connection before trimming the data to fit the receive
2234 * window. Check the sequence number versus IRS since we know
2235 * the sequence numbers haven't wrapped. This is a partial fix
2236 * for the "LAND" DoS attack.
2238 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2239 rstreason = BANDLIM_RST_OPENPORT;
2243 todrop = tp->rcv_nxt - th->th_seq;
2245 if (thflags & TH_SYN) {
2255 * Following if statement from Stevens, vol. 2, p. 960.
2258 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2260 * Any valid FIN must be to the left of the window.
2261 * At this point the FIN must be a duplicate or out
2262 * of sequence; drop it.
2267 * Send an ACK to resynchronize and drop any data.
2268 * But keep on processing for RST or ACK.
2270 tp->t_flags |= TF_ACKNOW;
2272 TCPSTAT_INC(tcps_rcvduppack);
2273 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2275 TCPSTAT_INC(tcps_rcvpartduppack);
2276 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2278 drop_hdrlen += todrop; /* drop from the top afterwards */
2279 th->th_seq += todrop;
2281 if (th->th_urp > todrop)
2282 th->th_urp -= todrop;
2290 * If new data are received on a connection after the
2291 * user processes are gone, then RST the other end.
2293 if ((so->so_state & SS_NOFDREF) &&
2294 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2295 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
2296 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2297 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2299 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2300 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2301 "after socket was closed, "
2302 "sending RST and removing tcpcb\n",
2303 s, __func__, tcpstates[tp->t_state], tlen);
2307 TCPSTAT_INC(tcps_rcvafterclose);
2308 rstreason = BANDLIM_UNLIMITED;
2313 * If segment ends after window, drop trailing data
2314 * (and PUSH and FIN); if nothing left, just ACK.
2316 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2318 TCPSTAT_INC(tcps_rcvpackafterwin);
2319 if (todrop >= tlen) {
2320 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2322 * If window is closed can only take segments at
2323 * window edge, and have to drop data and PUSH from
2324 * incoming segments. Continue processing, but
2325 * remember to ack. Otherwise, drop segment
2328 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2329 tp->t_flags |= TF_ACKNOW;
2330 TCPSTAT_INC(tcps_rcvwinprobe);
2334 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2337 thflags &= ~(TH_PUSH|TH_FIN);
2341 * If last ACK falls within this segment's sequence numbers,
2342 * record its timestamp.
2344 * 1) That the test incorporates suggestions from the latest
2345 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2346 * 2) That updating only on newer timestamps interferes with
2347 * our earlier PAWS tests, so this check should be solely
2348 * predicated on the sequence space of this segment.
2349 * 3) That we modify the segment boundary check to be
2350 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2351 * instead of RFC1323's
2352 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2353 * This modified check allows us to overcome RFC1323's
2354 * limitations as described in Stevens TCP/IP Illustrated
2355 * Vol. 2 p.869. In such cases, we can still calculate the
2356 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2358 if ((to.to_flags & TOF_TS) != 0 &&
2359 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2360 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2361 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2362 tp->ts_recent_age = tcp_ts_getticks();
2363 tp->ts_recent = to.to_tsval;
2367 * If a SYN is in the window, then this is an
2368 * error and we send an RST and drop the connection.
2370 if (thflags & TH_SYN) {
2371 KASSERT(ti_locked == TI_RLOCKED,
2372 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2373 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2375 tp = tcp_drop(tp, ECONNRESET);
2376 rstreason = BANDLIM_UNLIMITED;
2381 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2382 * flag is on (half-synchronized state), then queue data for
2383 * later processing; else drop segment and return.
2385 if ((thflags & TH_ACK) == 0) {
2386 if (tp->t_state == TCPS_SYN_RECEIVED ||
2387 (tp->t_flags & TF_NEEDSYN)) {
2389 if (tp->t_state == TCPS_SYN_RECEIVED &&
2390 tp->t_flags & TF_FASTOPEN) {
2391 tp->snd_wnd = tiwin;
2396 } else if (tp->t_flags & TF_ACKNOW)
2405 switch (tp->t_state) {
2408 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2409 * ESTABLISHED state and continue processing.
2410 * The ACK was checked above.
2412 case TCPS_SYN_RECEIVED:
2414 TCPSTAT_INC(tcps_connects);
2416 /* Do window scaling? */
2417 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2418 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2419 tp->rcv_scale = tp->request_r_scale;
2420 tp->snd_wnd = tiwin;
2424 * SYN-RECEIVED -> ESTABLISHED
2425 * SYN-RECEIVED* -> FIN-WAIT-1
2427 tp->t_starttime = ticks;
2428 if (tp->t_flags & TF_NEEDFIN) {
2429 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2430 tp->t_flags &= ~TF_NEEDFIN;
2432 tcp_state_change(tp, TCPS_ESTABLISHED);
2433 TCP_PROBE5(accept__established, NULL, tp,
2434 mtod(m, const char *), tp, th);
2436 if (tp->t_tfo_pending) {
2437 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2438 tp->t_tfo_pending = NULL;
2441 * Account for the ACK of our SYN prior to
2442 * regular ACK processing below.
2447 * TFO connections call cc_conn_init() during SYN
2448 * processing. Calling it again here for such
2449 * connections is not harmless as it would undo the
2450 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2453 if (!(tp->t_flags & TF_FASTOPEN))
2456 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2459 * If segment contains data or ACK, will call tcp_reass()
2460 * later; if not, do so now to pass queued data to user.
2462 if (tlen == 0 && (thflags & TH_FIN) == 0)
2463 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2465 tp->snd_wl1 = th->th_seq - 1;
2469 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2470 * ACKs. If the ack is in the range
2471 * tp->snd_una < th->th_ack <= tp->snd_max
2472 * then advance tp->snd_una to th->th_ack and drop
2473 * data from the retransmission queue. If this ACK reflects
2474 * more up to date window information we update our window information.
2476 case TCPS_ESTABLISHED:
2477 case TCPS_FIN_WAIT_1:
2478 case TCPS_FIN_WAIT_2:
2479 case TCPS_CLOSE_WAIT:
2482 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2483 TCPSTAT_INC(tcps_rcvacktoomuch);
2486 if ((tp->t_flags & TF_SACK_PERMIT) &&
2487 ((to.to_flags & TOF_SACK) ||
2488 !TAILQ_EMPTY(&tp->snd_holes)))
2489 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2492 * Reset the value so that previous (valid) value
2493 * from the last ack with SACK doesn't get used.
2495 tp->sackhint.sacked_bytes = 0;
2497 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2498 hhook_run_tcp_est_in(tp, th, &to);
2500 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2502 (tiwin == tp->snd_wnd ||
2503 (tp->t_flags & TF_SACK_PERMIT))) {
2504 TCPSTAT_INC(tcps_rcvdupack);
2506 * If we have outstanding data (other than
2507 * a window probe), this is a completely
2508 * duplicate ack (ie, window info didn't
2509 * change), the ack is the biggest we've
2510 * seen and we've seen exactly our rexmt
2511 * threshhold of them, assume a packet
2512 * has been dropped and retransmit it.
2513 * Kludge snd_nxt & the congestion
2514 * window so we send only this one
2517 * We know we're losing at the current
2518 * window size so do congestion avoidance
2519 * (set ssthresh to half the current window
2520 * and pull our congestion window back to
2521 * the new ssthresh).
2523 * Dup acks mean that packets have left the
2524 * network (they're now cached at the receiver)
2525 * so bump cwnd by the amount in the receiver
2526 * to keep a constant cwnd packets in the
2529 * When using TCP ECN, notify the peer that
2530 * we reduced the cwnd.
2533 * Following 2 kinds of acks should not affect
2536 * 2) Acks with SACK but without any new SACK
2537 * information in them. These could result from
2538 * any anomaly in the network like a switch
2539 * duplicating packets or a possible DoS attack.
2541 if (th->th_ack != tp->snd_una ||
2542 ((tp->t_flags & TF_SACK_PERMIT) &&
2545 else if (!tcp_timer_active(tp, TT_REXMT))
2547 else if (++tp->t_dupacks > tcprexmtthresh ||
2548 IN_FASTRECOVERY(tp->t_flags)) {
2549 cc_ack_received(tp, th, CC_DUPACK);
2550 if ((tp->t_flags & TF_SACK_PERMIT) &&
2551 IN_FASTRECOVERY(tp->t_flags)) {
2555 * Compute the amount of data in flight first.
2556 * We can inject new data into the pipe iff
2557 * we have less than 1/2 the original window's
2558 * worth of data in flight.
2560 if (V_tcp_do_rfc6675_pipe)
2561 awnd = tcp_compute_pipe(tp);
2563 awnd = (tp->snd_nxt - tp->snd_fack) +
2564 tp->sackhint.sack_bytes_rexmit;
2566 if (awnd < tp->snd_ssthresh) {
2567 tp->snd_cwnd += tp->t_maxseg;
2568 if (tp->snd_cwnd > tp->snd_ssthresh)
2569 tp->snd_cwnd = tp->snd_ssthresh;
2572 tp->snd_cwnd += tp->t_maxseg;
2573 if ((thflags & TH_FIN) &&
2574 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2576 * If its a fin we need to process
2577 * it to avoid a race where both
2578 * sides enter FIN-WAIT and send FIN|ACK
2583 (void) tcp_output(tp);
2585 } else if (tp->t_dupacks == tcprexmtthresh) {
2586 tcp_seq onxt = tp->snd_nxt;
2589 * If we're doing sack, check to
2590 * see if we're already in sack
2591 * recovery. If we're not doing sack,
2592 * check to see if we're in newreno
2595 if (tp->t_flags & TF_SACK_PERMIT) {
2596 if (IN_FASTRECOVERY(tp->t_flags)) {
2601 if (SEQ_LEQ(th->th_ack,
2607 /* Congestion signal before ack. */
2608 cc_cong_signal(tp, th, CC_NDUPACK);
2609 cc_ack_received(tp, th, CC_DUPACK);
2610 tcp_timer_activate(tp, TT_REXMT, 0);
2612 if (tp->t_flags & TF_SACK_PERMIT) {
2614 tcps_sack_recovery_episode);
2615 tp->sack_newdata = tp->snd_nxt;
2616 tp->snd_cwnd = tp->t_maxseg;
2617 (void) tcp_output(tp);
2620 tp->snd_nxt = th->th_ack;
2621 tp->snd_cwnd = tp->t_maxseg;
2622 if ((thflags & TH_FIN) &&
2623 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2625 * If its a fin we need to process
2626 * it to avoid a race where both
2627 * sides enter FIN-WAIT and send FIN|ACK
2632 (void) tcp_output(tp);
2633 KASSERT(tp->snd_limited <= 2,
2634 ("%s: tp->snd_limited too big",
2636 tp->snd_cwnd = tp->snd_ssthresh +
2638 (tp->t_dupacks - tp->snd_limited);
2639 if (SEQ_GT(onxt, tp->snd_nxt))
2642 } else if (V_tcp_do_rfc3042) {
2644 * Process first and second duplicate
2645 * ACKs. Each indicates a segment
2646 * leaving the network, creating room
2647 * for more. Make sure we can send a
2648 * packet on reception of each duplicate
2649 * ACK by increasing snd_cwnd by one
2650 * segment. Restore the original
2651 * snd_cwnd after packet transmission.
2653 cc_ack_received(tp, th, CC_DUPACK);
2654 u_long oldcwnd = tp->snd_cwnd;
2655 tcp_seq oldsndmax = tp->snd_max;
2659 KASSERT(tp->t_dupacks == 1 ||
2661 ("%s: dupacks not 1 or 2",
2663 if (tp->t_dupacks == 1)
2664 tp->snd_limited = 0;
2666 (tp->snd_nxt - tp->snd_una) +
2667 (tp->t_dupacks - tp->snd_limited) *
2669 if ((thflags & TH_FIN) &&
2670 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2672 * If its a fin we need to process
2673 * it to avoid a race where both
2674 * sides enter FIN-WAIT and send FIN|ACK
2680 * Only call tcp_output when there
2681 * is new data available to be sent.
2682 * Otherwise we would send pure ACKs.
2684 SOCKBUF_LOCK(&so->so_snd);
2685 avail = so->so_snd.sb_cc -
2686 (tp->snd_nxt - tp->snd_una);
2687 SOCKBUF_UNLOCK(&so->so_snd);
2689 (void) tcp_output(tp);
2690 sent = tp->snd_max - oldsndmax;
2691 if (sent > tp->t_maxseg) {
2692 KASSERT((tp->t_dupacks == 2 &&
2693 tp->snd_limited == 0) ||
2694 (sent == tp->t_maxseg + 1 &&
2695 tp->t_flags & TF_SENTFIN),
2696 ("%s: sent too much",
2698 tp->snd_limited = 2;
2699 } else if (sent > 0)
2701 tp->snd_cwnd = oldcwnd;
2708 * This ack is advancing the left edge, reset the
2713 * If this ack also has new SACK info, increment the
2714 * counter as per rfc6675.
2716 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2720 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2721 ("%s: th_ack <= snd_una", __func__));
2724 * If the congestion window was inflated to account
2725 * for the other side's cached packets, retract it.
2727 if (IN_FASTRECOVERY(tp->t_flags)) {
2728 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2729 if (tp->t_flags & TF_SACK_PERMIT)
2730 tcp_sack_partialack(tp, th);
2732 tcp_newreno_partial_ack(tp, th);
2734 cc_post_recovery(tp, th);
2737 * If we reach this point, ACK is not a duplicate,
2738 * i.e., it ACKs something we sent.
2740 if (tp->t_flags & TF_NEEDSYN) {
2742 * T/TCP: Connection was half-synchronized, and our
2743 * SYN has been ACK'd (so connection is now fully
2744 * synchronized). Go to non-starred state,
2745 * increment snd_una for ACK of SYN, and check if
2746 * we can do window scaling.
2748 tp->t_flags &= ~TF_NEEDSYN;
2750 /* Do window scaling? */
2751 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2752 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2753 tp->rcv_scale = tp->request_r_scale;
2754 /* Send window already scaled. */
2759 INP_WLOCK_ASSERT(tp->t_inpcb);
2761 acked = BYTES_THIS_ACK(tp, th);
2762 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2763 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2764 tp->snd_una, th->th_ack, tp, m));
2765 TCPSTAT_INC(tcps_rcvackpack);
2766 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2769 * If we just performed our first retransmit, and the ACK
2770 * arrives within our recovery window, then it was a mistake
2771 * to do the retransmit in the first place. Recover our
2772 * original cwnd and ssthresh, and proceed to transmit where
2775 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2776 (int)(ticks - tp->t_badrxtwin) < 0)
2777 cc_cong_signal(tp, th, CC_RTO_ERR);
2780 * If we have a timestamp reply, update smoothed
2781 * round trip time. If no timestamp is present but
2782 * transmit timer is running and timed sequence
2783 * number was acked, update smoothed round trip time.
2784 * Since we now have an rtt measurement, cancel the
2785 * timer backoff (cf., Phil Karn's retransmit alg.).
2786 * Recompute the initial retransmit timer.
2788 * Some boxes send broken timestamp replies
2789 * during the SYN+ACK phase, ignore
2790 * timestamps of 0 or we could calculate a
2791 * huge RTT and blow up the retransmit timer.
2793 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2796 t = tcp_ts_getticks() - to.to_tsecr;
2797 if (!tp->t_rttlow || tp->t_rttlow > t)
2799 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2800 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2801 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2802 tp->t_rttlow = ticks - tp->t_rtttime;
2803 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2807 * If all outstanding data is acked, stop retransmit
2808 * timer and remember to restart (more output or persist).
2809 * If there is more data to be acked, restart retransmit
2810 * timer, using current (possibly backed-off) value.
2812 if (th->th_ack == tp->snd_max) {
2813 tcp_timer_activate(tp, TT_REXMT, 0);
2815 } else if (!tcp_timer_active(tp, TT_PERSIST))
2816 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2819 * If no data (only SYN) was ACK'd,
2820 * skip rest of ACK processing.
2826 * Let the congestion control algorithm update congestion
2827 * control related information. This typically means increasing
2828 * the congestion window.
2830 cc_ack_received(tp, th, CC_ACK);
2832 SOCKBUF_LOCK(&so->so_snd);
2833 if (acked > so->so_snd.sb_cc) {
2834 if (tp->snd_wnd >= so->so_snd.sb_cc)
2835 tp->snd_wnd -= so->so_snd.sb_cc;
2838 mfree = sbcut_locked(&so->so_snd,
2839 (int)so->so_snd.sb_cc);
2842 mfree = sbcut_locked(&so->so_snd, acked);
2843 if (tp->snd_wnd >= (u_long) acked)
2844 tp->snd_wnd -= acked;
2849 /* NB: sowwakeup_locked() does an implicit unlock. */
2850 sowwakeup_locked(so);
2852 /* Detect una wraparound. */
2853 if (!IN_RECOVERY(tp->t_flags) &&
2854 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2855 SEQ_LEQ(th->th_ack, tp->snd_recover))
2856 tp->snd_recover = th->th_ack - 1;
2857 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2858 if (IN_RECOVERY(tp->t_flags) &&
2859 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2860 EXIT_RECOVERY(tp->t_flags);
2862 tp->snd_una = th->th_ack;
2863 if (tp->t_flags & TF_SACK_PERMIT) {
2864 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2865 tp->snd_recover = tp->snd_una;
2867 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2868 tp->snd_nxt = tp->snd_una;
2870 switch (tp->t_state) {
2873 * In FIN_WAIT_1 STATE in addition to the processing
2874 * for the ESTABLISHED state if our FIN is now acknowledged
2875 * then enter FIN_WAIT_2.
2877 case TCPS_FIN_WAIT_1:
2878 if (ourfinisacked) {
2880 * If we can't receive any more
2881 * data, then closing user can proceed.
2882 * Starting the timer is contrary to the
2883 * specification, but if we don't get a FIN
2884 * we'll hang forever.
2887 * we should release the tp also, and use a
2890 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2891 soisdisconnected(so);
2892 tcp_timer_activate(tp, TT_2MSL,
2893 (tcp_fast_finwait2_recycle ?
2894 tcp_finwait2_timeout :
2897 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2902 * In CLOSING STATE in addition to the processing for
2903 * the ESTABLISHED state if the ACK acknowledges our FIN
2904 * then enter the TIME-WAIT state, otherwise ignore
2908 if (ourfinisacked) {
2909 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2911 INP_INFO_RUNLOCK(&V_tcbinfo);
2918 * In LAST_ACK, we may still be waiting for data to drain
2919 * and/or to be acked, as well as for the ack of our FIN.
2920 * If our FIN is now acknowledged, delete the TCB,
2921 * enter the closed state and return.
2924 if (ourfinisacked) {
2925 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2934 INP_WLOCK_ASSERT(tp->t_inpcb);
2937 * Update window information.
2938 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2940 if ((thflags & TH_ACK) &&
2941 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2942 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2943 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2944 /* keep track of pure window updates */
2946 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2947 TCPSTAT_INC(tcps_rcvwinupd);
2948 tp->snd_wnd = tiwin;
2949 tp->snd_wl1 = th->th_seq;
2950 tp->snd_wl2 = th->th_ack;
2951 if (tp->snd_wnd > tp->max_sndwnd)
2952 tp->max_sndwnd = tp->snd_wnd;
2957 * Process segments with URG.
2959 if ((thflags & TH_URG) && th->th_urp &&
2960 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2962 * This is a kludge, but if we receive and accept
2963 * random urgent pointers, we'll crash in
2964 * soreceive. It's hard to imagine someone
2965 * actually wanting to send this much urgent data.
2967 SOCKBUF_LOCK(&so->so_rcv);
2968 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2969 th->th_urp = 0; /* XXX */
2970 thflags &= ~TH_URG; /* XXX */
2971 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2972 goto dodata; /* XXX */
2975 * If this segment advances the known urgent pointer,
2976 * then mark the data stream. This should not happen
2977 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2978 * a FIN has been received from the remote side.
2979 * In these states we ignore the URG.
2981 * According to RFC961 (Assigned Protocols),
2982 * the urgent pointer points to the last octet
2983 * of urgent data. We continue, however,
2984 * to consider it to indicate the first octet
2985 * of data past the urgent section as the original
2986 * spec states (in one of two places).
2988 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2989 tp->rcv_up = th->th_seq + th->th_urp;
2990 so->so_oobmark = so->so_rcv.sb_cc +
2991 (tp->rcv_up - tp->rcv_nxt) - 1;
2992 if (so->so_oobmark == 0)
2993 so->so_rcv.sb_state |= SBS_RCVATMARK;
2995 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2997 SOCKBUF_UNLOCK(&so->so_rcv);
2999 * Remove out of band data so doesn't get presented to user.
3000 * This can happen independent of advancing the URG pointer,
3001 * but if two URG's are pending at once, some out-of-band
3002 * data may creep in... ick.
3004 if (th->th_urp <= (u_long)tlen &&
3005 !(so->so_options & SO_OOBINLINE)) {
3006 /* hdr drop is delayed */
3007 tcp_pulloutofband(so, th, m, drop_hdrlen);
3011 * If no out of band data is expected,
3012 * pull receive urgent pointer along
3013 * with the receive window.
3015 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3016 tp->rcv_up = tp->rcv_nxt;
3019 INP_WLOCK_ASSERT(tp->t_inpcb);
3022 * Process the segment text, merging it into the TCP sequencing queue,
3023 * and arranging for acknowledgment of receipt if necessary.
3024 * This process logically involves adjusting tp->rcv_wnd as data
3025 * is presented to the user (this happens in tcp_usrreq.c,
3026 * case PRU_RCVD). If a FIN has already been received on this
3027 * connection then we just ignore the text.
3029 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3030 (tp->t_flags & TF_FASTOPEN));
3031 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
3032 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3033 tcp_seq save_start = th->th_seq;
3035 m_adj(m, drop_hdrlen); /* delayed header drop */
3037 * Insert segment which includes th into TCP reassembly queue
3038 * with control block tp. Set thflags to whether reassembly now
3039 * includes a segment with FIN. This handles the common case
3040 * inline (segment is the next to be received on an established
3041 * connection, and the queue is empty), avoiding linkage into
3042 * and removal from the queue and repetition of various
3044 * Set DELACK for segments received in order, but ack
3045 * immediately when segments are out of order (so
3046 * fast retransmit can work).
3048 if (th->th_seq == tp->rcv_nxt &&
3049 LIST_EMPTY(&tp->t_segq) &&
3050 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3052 if (DELAY_ACK(tp, tlen) || tfo_syn)
3053 tp->t_flags |= TF_DELACK;
3055 tp->t_flags |= TF_ACKNOW;
3056 tp->rcv_nxt += tlen;
3057 thflags = th->th_flags & TH_FIN;
3058 TCPSTAT_INC(tcps_rcvpack);
3059 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3061 SOCKBUF_LOCK(&so->so_rcv);
3062 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3065 sbappendstream_locked(&so->so_rcv, m);
3066 /* NB: sorwakeup_locked() does an implicit unlock. */
3067 sorwakeup_locked(so);
3070 * XXX: Due to the header drop above "th" is
3071 * theoretically invalid by now. Fortunately
3072 * m_adj() doesn't actually frees any mbufs
3073 * when trimming from the head.
3075 thflags = tcp_reass(tp, th, &tlen, m);
3076 tp->t_flags |= TF_ACKNOW;
3078 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
3079 tcp_update_sack_list(tp, save_start, save_start + tlen);
3082 * Note the amount of data that peer has sent into
3083 * our window, in order to estimate the sender's
3087 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3088 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3090 len = so->so_rcv.sb_hiwat;
3098 * If FIN is received ACK the FIN and let the user know
3099 * that the connection is closing.
3101 if (thflags & TH_FIN) {
3102 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3105 * If connection is half-synchronized
3106 * (ie NEEDSYN flag on) then delay ACK,
3107 * so it may be piggybacked when SYN is sent.
3108 * Otherwise, since we received a FIN then no
3109 * more input can be expected, send ACK now.
3111 if (tp->t_flags & TF_NEEDSYN)
3112 tp->t_flags |= TF_DELACK;
3114 tp->t_flags |= TF_ACKNOW;
3117 switch (tp->t_state) {
3120 * In SYN_RECEIVED and ESTABLISHED STATES
3121 * enter the CLOSE_WAIT state.
3123 case TCPS_SYN_RECEIVED:
3124 tp->t_starttime = ticks;
3126 case TCPS_ESTABLISHED:
3127 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3131 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3132 * enter the CLOSING state.
3134 case TCPS_FIN_WAIT_1:
3135 tcp_state_change(tp, TCPS_CLOSING);
3139 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3140 * starting the time-wait timer, turning off the other
3143 case TCPS_FIN_WAIT_2:
3144 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3145 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
3146 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3150 INP_INFO_RUNLOCK(&V_tcbinfo);
3154 if (ti_locked == TI_RLOCKED)
3155 INP_INFO_RUNLOCK(&V_tcbinfo);
3156 ti_locked = TI_UNLOCKED;
3159 if (so->so_options & SO_DEBUG)
3160 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3165 * Return any desired output.
3167 if (needoutput || (tp->t_flags & TF_ACKNOW))
3168 (void) tcp_output(tp);
3171 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3172 __func__, ti_locked));
3173 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3174 INP_WLOCK_ASSERT(tp->t_inpcb);
3176 if (tp->t_flags & TF_DELACK) {
3177 tp->t_flags &= ~TF_DELACK;
3178 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3180 INP_WUNLOCK(tp->t_inpcb);
3185 * Generate an ACK dropping incoming segment if it occupies
3186 * sequence space, where the ACK reflects our state.
3188 * We can now skip the test for the RST flag since all
3189 * paths to this code happen after packets containing
3190 * RST have been dropped.
3192 * In the SYN-RECEIVED state, don't send an ACK unless the
3193 * segment we received passes the SYN-RECEIVED ACK test.
3194 * If it fails send a RST. This breaks the loop in the
3195 * "LAND" DoS attack, and also prevents an ACK storm
3196 * between two listening ports that have been sent forged
3197 * SYN segments, each with the source address of the other.
3199 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3200 (SEQ_GT(tp->snd_una, th->th_ack) ||
3201 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3202 rstreason = BANDLIM_RST_OPENPORT;
3206 if (so->so_options & SO_DEBUG)
3207 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3210 if (ti_locked == TI_RLOCKED)
3211 INP_INFO_RUNLOCK(&V_tcbinfo);
3212 ti_locked = TI_UNLOCKED;
3214 tp->t_flags |= TF_ACKNOW;
3215 (void) tcp_output(tp);
3216 INP_WUNLOCK(tp->t_inpcb);
3221 if (ti_locked == TI_RLOCKED)
3222 INP_INFO_RUNLOCK(&V_tcbinfo);
3223 ti_locked = TI_UNLOCKED;
3226 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3227 INP_WUNLOCK(tp->t_inpcb);
3229 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3233 if (ti_locked == TI_RLOCKED) {
3234 INP_INFO_RUNLOCK(&V_tcbinfo);
3235 ti_locked = TI_UNLOCKED;
3239 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3243 * Drop space held by incoming segment and return.
3246 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3247 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3251 INP_WUNLOCK(tp->t_inpcb);
3256 * Issue RST and make ACK acceptable to originator of segment.
3257 * The mbuf must still include the original packet header.
3261 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3262 int tlen, int rstreason)
3268 struct ip6_hdr *ip6;
3272 INP_WLOCK_ASSERT(tp->t_inpcb);
3275 /* Don't bother if destination was broadcast/multicast. */
3276 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3279 if (mtod(m, struct ip *)->ip_v == 6) {
3280 ip6 = mtod(m, struct ip6_hdr *);
3281 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3282 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3284 /* IPv6 anycast check is done at tcp6_input() */
3287 #if defined(INET) && defined(INET6)
3292 ip = mtod(m, struct ip *);
3293 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3294 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3295 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3296 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3301 /* Perform bandwidth limiting. */
3302 if (badport_bandlim(rstreason) < 0)
3305 /* tcp_respond consumes the mbuf chain. */
3306 if (th->th_flags & TH_ACK) {
3307 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3308 th->th_ack, TH_RST);
3310 if (th->th_flags & TH_SYN)
3312 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3313 (tcp_seq)0, TH_RST|TH_ACK);
3321 * Parse TCP options and place in tcpopt.
3324 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3329 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3331 if (opt == TCPOPT_EOL)
3333 if (opt == TCPOPT_NOP)
3339 if (optlen < 2 || optlen > cnt)
3344 if (optlen != TCPOLEN_MAXSEG)
3346 if (!(flags & TO_SYN))
3348 to->to_flags |= TOF_MSS;
3349 bcopy((char *)cp + 2,
3350 (char *)&to->to_mss, sizeof(to->to_mss));
3351 to->to_mss = ntohs(to->to_mss);
3354 if (optlen != TCPOLEN_WINDOW)
3356 if (!(flags & TO_SYN))
3358 to->to_flags |= TOF_SCALE;
3359 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3361 case TCPOPT_TIMESTAMP:
3362 if (optlen != TCPOLEN_TIMESTAMP)
3364 to->to_flags |= TOF_TS;
3365 bcopy((char *)cp + 2,
3366 (char *)&to->to_tsval, sizeof(to->to_tsval));
3367 to->to_tsval = ntohl(to->to_tsval);
3368 bcopy((char *)cp + 6,
3369 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3370 to->to_tsecr = ntohl(to->to_tsecr);
3372 #ifdef TCP_SIGNATURE
3374 * XXX In order to reply to a host which has set the
3375 * TCP_SIGNATURE option in its initial SYN, we have to
3376 * record the fact that the option was observed here
3377 * for the syncache code to perform the correct response.
3379 case TCPOPT_SIGNATURE:
3380 if (optlen != TCPOLEN_SIGNATURE)
3382 to->to_flags |= TOF_SIGNATURE;
3383 to->to_signature = cp + 2;
3386 case TCPOPT_SACK_PERMITTED:
3387 if (optlen != TCPOLEN_SACK_PERMITTED)
3389 if (!(flags & TO_SYN))
3393 to->to_flags |= TOF_SACKPERM;
3396 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3400 to->to_flags |= TOF_SACK;
3401 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3402 to->to_sacks = cp + 2;
3403 TCPSTAT_INC(tcps_sack_rcv_blocks);
3406 case TCPOPT_FAST_OPEN:
3407 if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
3408 (optlen < TCPOLEN_FAST_OPEN_MIN) &&
3409 (optlen > TCPOLEN_FAST_OPEN_MAX))
3411 if (!(flags & TO_SYN))
3413 if (!V_tcp_fastopen_enabled)
3415 to->to_flags |= TOF_FASTOPEN;
3416 to->to_tfo_len = optlen - 2;
3417 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3427 * Pull out of band byte out of a segment so
3428 * it doesn't appear in the user's data queue.
3429 * It is still reflected in the segment length for
3430 * sequencing purposes.
3433 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3436 int cnt = off + th->th_urp - 1;
3439 if (m->m_len > cnt) {
3440 char *cp = mtod(m, caddr_t) + cnt;
3441 struct tcpcb *tp = sototcpcb(so);
3443 INP_WLOCK_ASSERT(tp->t_inpcb);
3446 tp->t_oobflags |= TCPOOB_HAVEDATA;
3447 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3449 if (m->m_flags & M_PKTHDR)
3458 panic("tcp_pulloutofband");
3462 * Collect new round-trip time estimate
3463 * and update averages and current timeout.
3466 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3470 INP_WLOCK_ASSERT(tp->t_inpcb);
3472 TCPSTAT_INC(tcps_rttupdated);
3474 if (tp->t_srtt != 0) {
3476 * srtt is stored as fixed point with 5 bits after the
3477 * binary point (i.e., scaled by 8). The following magic
3478 * is equivalent to the smoothing algorithm in rfc793 with
3479 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3480 * point). Adjust rtt to origin 0.
3482 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3483 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3485 if ((tp->t_srtt += delta) <= 0)
3489 * We accumulate a smoothed rtt variance (actually, a
3490 * smoothed mean difference), then set the retransmit
3491 * timer to smoothed rtt + 4 times the smoothed variance.
3492 * rttvar is stored as fixed point with 4 bits after the
3493 * binary point (scaled by 16). The following is
3494 * equivalent to rfc793 smoothing with an alpha of .75
3495 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3496 * rfc793's wired-in beta.
3500 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3501 if ((tp->t_rttvar += delta) <= 0)
3503 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3504 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3507 * No rtt measurement yet - use the unsmoothed rtt.
3508 * Set the variance to half the rtt (so our first
3509 * retransmit happens at 3*rtt).
3511 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3512 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3513 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3519 * the retransmit should happen at rtt + 4 * rttvar.
3520 * Because of the way we do the smoothing, srtt and rttvar
3521 * will each average +1/2 tick of bias. When we compute
3522 * the retransmit timer, we want 1/2 tick of rounding and
3523 * 1 extra tick because of +-1/2 tick uncertainty in the
3524 * firing of the timer. The bias will give us exactly the
3525 * 1.5 tick we need. But, because the bias is
3526 * statistical, we have to test that we don't drop below
3527 * the minimum feasible timer (which is 2 ticks).
3529 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3530 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3533 * We received an ack for a packet that wasn't retransmitted;
3534 * it is probably safe to discard any error indications we've
3535 * received recently. This isn't quite right, but close enough
3536 * for now (a route might have failed after we sent a segment,
3537 * and the return path might not be symmetrical).
3539 tp->t_softerror = 0;
3543 * Determine a reasonable value for maxseg size.
3544 * If the route is known, check route for mtu.
3545 * If none, use an mss that can be handled on the outgoing interface
3546 * without forcing IP to fragment. If no route is found, route has no mtu,
3547 * or the destination isn't local, use a default, hopefully conservative
3548 * size (usually 512 or the default IP max size, but no more than the mtu
3549 * of the interface), as we can't discover anything about intervening
3550 * gateways or networks. We also initialize the congestion/slow start
3551 * window to be a single segment if the destination isn't local.
3552 * While looking at the routing entry, we also initialize other path-dependent
3553 * parameters from pre-set or cached values in the routing entry.
3555 * Also take into account the space needed for options that we
3556 * send regularly. Make maxseg shorter by that amount to assure
3557 * that we can send maxseg amount of data even when the options
3558 * are present. Store the upper limit of the length of options plus
3561 * NOTE that this routine is only called when we process an incoming
3562 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3563 * settings are handled in tcp_mssopt().
3566 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3567 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3571 struct inpcb *inp = tp->t_inpcb;
3572 struct hc_metrics_lite metrics;
3575 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3576 size_t min_protoh = isipv6 ?
3577 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3578 sizeof (struct tcpiphdr);
3580 const size_t min_protoh = sizeof(struct tcpiphdr);
3583 INP_WLOCK_ASSERT(tp->t_inpcb);
3585 if (mtuoffer != -1) {
3586 KASSERT(offer == -1, ("%s: conflict", __func__));
3587 offer = mtuoffer - min_protoh;
3594 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3595 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3598 #if defined(INET) && defined(INET6)
3603 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3604 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3609 * No route to sender, stay with default mss and return.
3613 * In case we return early we need to initialize metrics
3614 * to a defined state as tcp_hc_get() would do for us
3615 * if there was no cache hit.
3617 if (metricptr != NULL)
3618 bzero(metricptr, sizeof(struct hc_metrics_lite));
3622 /* What have we got? */
3626 * Offer == 0 means that there was no MSS on the SYN
3627 * segment, in this case we use tcp_mssdflt as
3628 * already assigned to t_maxopd above.
3630 offer = tp->t_maxopd;
3635 * Offer == -1 means that we didn't receive SYN yet.
3641 * Prevent DoS attack with too small MSS. Round up
3642 * to at least minmss.
3644 offer = max(offer, V_tcp_minmss);
3648 * rmx information is now retrieved from tcp_hostcache.
3650 tcp_hc_get(&inp->inp_inc, &metrics);
3651 if (metricptr != NULL)
3652 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3655 * If there's a discovered mtu int tcp hostcache, use it
3656 * else, use the link mtu.
3658 if (metrics.rmx_mtu)
3659 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3663 mss = maxmtu - min_protoh;
3664 if (!V_path_mtu_discovery &&
3665 !in6_localaddr(&inp->in6p_faddr))
3666 mss = min(mss, V_tcp_v6mssdflt);
3669 #if defined(INET) && defined(INET6)
3674 mss = maxmtu - min_protoh;
3675 if (!V_path_mtu_discovery &&
3676 !in_localaddr(inp->inp_faddr))
3677 mss = min(mss, V_tcp_mssdflt);
3681 * XXX - The above conditional (mss = maxmtu - min_protoh)
3682 * probably violates the TCP spec.
3683 * The problem is that, since we don't know the
3684 * other end's MSS, we are supposed to use a conservative
3685 * default. But, if we do that, then MTU discovery will
3686 * never actually take place, because the conservative
3687 * default is much less than the MTUs typically seen
3688 * on the Internet today. For the moment, we'll sweep
3689 * this under the carpet.
3691 * The conservative default might not actually be a problem
3692 * if the only case this occurs is when sending an initial
3693 * SYN with options and data to a host we've never talked
3694 * to before. Then, they will reply with an MSS value which
3695 * will get recorded and the new parameters should get
3696 * recomputed. For Further Study.
3699 mss = min(mss, offer);
3702 * Sanity check: make sure that maxopd will be large
3703 * enough to allow some data on segments even if the
3704 * all the option space is used (40bytes). Otherwise
3705 * funny things may happen in tcp_output.
3710 * maxopd stores the maximum length of data AND options
3711 * in a segment; maxseg is the amount of data in a normal
3712 * segment. We need to store this value (maxopd) apart
3713 * from maxseg, because now every segment carries options
3714 * and thus we normally have somewhat less data in segments.
3719 * origoffer==-1 indicates that no segments were received yet.
3720 * In this case we just guess.
3722 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3724 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3725 mss -= TCPOLEN_TSTAMP_APPA;
3731 tcp_mss(struct tcpcb *tp, int offer)
3737 struct hc_metrics_lite metrics;
3738 struct tcp_ifcap cap;
3740 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3742 bzero(&cap, sizeof(cap));
3743 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3749 * If there's a pipesize, change the socket buffer to that size,
3750 * don't change if sb_hiwat is different than default (then it
3751 * has been changed on purpose with setsockopt).
3752 * Make the socket buffers an integral number of mss units;
3753 * if the mss is larger than the socket buffer, decrease the mss.
3755 so = inp->inp_socket;
3756 SOCKBUF_LOCK(&so->so_snd);
3757 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3758 bufsize = metrics.rmx_sendpipe;
3760 bufsize = so->so_snd.sb_hiwat;
3764 bufsize = roundup(bufsize, mss);
3765 if (bufsize > sb_max)
3767 if (bufsize > so->so_snd.sb_hiwat)
3768 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3770 SOCKBUF_UNLOCK(&so->so_snd);
3773 SOCKBUF_LOCK(&so->so_rcv);
3774 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3775 bufsize = metrics.rmx_recvpipe;
3777 bufsize = so->so_rcv.sb_hiwat;
3778 if (bufsize > mss) {
3779 bufsize = roundup(bufsize, mss);
3780 if (bufsize > sb_max)
3782 if (bufsize > so->so_rcv.sb_hiwat)
3783 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3785 SOCKBUF_UNLOCK(&so->so_rcv);
3787 /* Check the interface for TSO capabilities. */
3788 if (cap.ifcap & CSUM_TSO) {
3789 tp->t_flags |= TF_TSO;
3790 tp->t_tsomax = cap.tsomax;
3791 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3792 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3797 * Determine the MSS option to send on an outgoing SYN.
3800 tcp_mssopt(struct in_conninfo *inc)
3807 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3810 if (inc->inc_flags & INC_ISIPV6) {
3811 mss = V_tcp_v6mssdflt;
3812 maxmtu = tcp_maxmtu6(inc, NULL);
3813 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3816 #if defined(INET) && defined(INET6)
3821 mss = V_tcp_mssdflt;
3822 maxmtu = tcp_maxmtu(inc, NULL);
3823 min_protoh = sizeof(struct tcpiphdr);
3826 #if defined(INET6) || defined(INET)
3827 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3830 if (maxmtu && thcmtu)
3831 mss = min(maxmtu, thcmtu) - min_protoh;
3832 else if (maxmtu || thcmtu)
3833 mss = max(maxmtu, thcmtu) - min_protoh;
3840 * On a partial ack arrives, force the retransmission of the
3841 * next unacknowledged segment. Do not clear tp->t_dupacks.
3842 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3846 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3848 tcp_seq onxt = tp->snd_nxt;
3849 u_long ocwnd = tp->snd_cwnd;
3851 INP_WLOCK_ASSERT(tp->t_inpcb);
3853 tcp_timer_activate(tp, TT_REXMT, 0);
3855 tp->snd_nxt = th->th_ack;
3857 * Set snd_cwnd to one segment beyond acknowledged offset.
3858 * (tp->snd_una has not yet been updated when this function is called.)
3860 tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3861 tp->t_flags |= TF_ACKNOW;
3862 (void) tcp_output(tp);
3863 tp->snd_cwnd = ocwnd;
3864 if (SEQ_GT(onxt, tp->snd_nxt))
3867 * Partial window deflation. Relies on fact that tp->snd_una
3870 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3871 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3874 tp->snd_cwnd += tp->t_maxseg;
3878 tcp_compute_pipe(struct tcpcb *tp)
3880 return (tp->snd_max - tp->snd_una +
3881 tp->sackhint.sack_bytes_rexmit -
3882 tp->sackhint.sacked_bytes);