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 * 3. 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$");
54 #include "opt_inet6.h"
55 #include "opt_ipsec.h"
56 #include "opt_tcpdebug.h"
58 #include <sys/param.h>
59 #include <sys/kernel.h>
61 #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/if_var.h>
81 #include <net/route.h>
84 #define TCPSTATES /* for logging */
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/ip.h>
91 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
92 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
93 #include <netinet/ip_var.h>
94 #include <netinet/ip_options.h>
95 #include <netinet/ip6.h>
96 #include <netinet/icmp6.h>
97 #include <netinet6/in6_pcb.h>
98 #include <netinet6/in6_var.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
102 #include <netinet/tcp_fastopen.h>
104 #include <netinet/tcp.h>
105 #include <netinet/tcp_fsm.h>
106 #include <netinet/tcp_seq.h>
107 #include <netinet/tcp_timer.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet6/tcp6_var.h>
110 #include <netinet/tcpip.h>
111 #include <netinet/cc/cc.h>
113 #include <netinet/tcp_pcap.h>
115 #include <netinet/tcp_syncache.h>
117 #include <netinet/tcp_debug.h>
118 #endif /* TCPDEBUG */
120 #include <netinet/tcp_offload.h>
123 #include <netipsec/ipsec_support.h>
125 #include <machine/in_cksum.h>
127 #include <security/mac/mac_framework.h>
129 const int tcprexmtthresh = 3;
131 int tcp_log_in_vain = 0;
132 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
134 "Log all incoming TCP segments to closed ports");
136 VNET_DEFINE(int, blackhole) = 0;
137 #define V_blackhole VNET(blackhole)
138 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
139 &VNET_NAME(blackhole), 0,
140 "Do not send RST on segments to closed ports");
142 VNET_DEFINE(int, tcp_delack_enabled) = 1;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
144 &VNET_NAME(tcp_delack_enabled), 0,
145 "Delay ACK to try and piggyback it onto a data packet");
147 VNET_DEFINE(int, drop_synfin) = 0;
148 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
149 &VNET_NAME(drop_synfin), 0,
150 "Drop TCP packets with SYN+FIN set");
152 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
154 &VNET_NAME(tcp_do_rfc6675_pipe), 0,
155 "Use calculated pipe/in-flight bytes per RFC 6675");
157 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
158 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | 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_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
164 &VNET_NAME(tcp_do_rfc3390), 0,
165 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
167 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
168 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
169 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
170 "Slow-start flight size (initial congestion window) in number of segments");
172 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
173 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
174 &VNET_NAME(tcp_do_rfc3465), 0,
175 "Enable RFC 3465 (Appropriate Byte Counting)");
177 VNET_DEFINE(int, tcp_abc_l_var) = 2;
178 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
179 &VNET_NAME(tcp_abc_l_var), 2,
180 "Cap the max cwnd increment during slow-start to this number of segments");
182 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
184 VNET_DEFINE(int, tcp_do_ecn) = 2;
185 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
186 &VNET_NAME(tcp_do_ecn), 0,
189 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
190 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
191 &VNET_NAME(tcp_ecn_maxretries), 0,
192 "Max retries before giving up on ECN");
194 VNET_DEFINE(int, tcp_insecure_syn) = 0;
195 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
196 &VNET_NAME(tcp_insecure_syn), 0,
197 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
199 VNET_DEFINE(int, tcp_insecure_rst) = 0;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
201 &VNET_NAME(tcp_insecure_rst), 0,
202 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
204 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
205 #define V_tcp_recvspace VNET(tcp_recvspace)
206 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
207 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
209 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
210 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | 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 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
216 &VNET_NAME(tcp_autorcvbuf_inc), 0,
217 "Incrementor step size of automatic receive buffer");
219 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
220 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
221 &VNET_NAME(tcp_autorcvbuf_max), 0,
222 "Max size of automatic receive buffer");
224 VNET_DEFINE(struct inpcbhead, tcb);
225 #define tcb6 tcb /* for KAME src sync over BSD*'s */
226 VNET_DEFINE(struct inpcbinfo, tcbinfo);
229 * TCP statistics are stored in an array of counter(9)s, which size matches
230 * size of struct tcpstat. TCP running connection count is a regular array.
232 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
233 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
234 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
235 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
236 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
237 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
238 "TCP connection counts by TCP state");
241 tcp_vnet_init(const void *unused)
244 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
245 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
247 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
248 tcp_vnet_init, NULL);
252 tcp_vnet_uninit(const void *unused)
255 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
256 VNET_PCPUSTAT_FREE(tcpstat);
258 VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
259 tcp_vnet_uninit, NULL);
263 * Kernel module interface for updating tcpstat. The argument is an index
264 * into tcpstat treated as an array.
267 kmod_tcpstat_inc(int statnum)
270 counter_u64_add(VNET(tcpstat)[statnum], 1);
275 * Wrapper for the TCP established input helper hook.
278 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
280 struct tcp_hhook_data hhook_data;
282 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
287 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
294 * CC wrapper hook functions
297 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
300 INP_WLOCK_ASSERT(tp->t_inpcb);
302 tp->ccv->nsegs = nsegs;
303 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
304 if (tp->snd_cwnd <= tp->snd_wnd)
305 tp->ccv->flags |= CCF_CWND_LIMITED;
307 tp->ccv->flags &= ~CCF_CWND_LIMITED;
309 if (type == CC_ACK) {
310 if (tp->snd_cwnd > tp->snd_ssthresh) {
311 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
312 nsegs * V_tcp_abc_l_var * tcp_maxseg(tp));
313 if (tp->t_bytes_acked >= tp->snd_cwnd) {
314 tp->t_bytes_acked -= tp->snd_cwnd;
315 tp->ccv->flags |= CCF_ABC_SENTAWND;
318 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
319 tp->t_bytes_acked = 0;
323 if (CC_ALGO(tp)->ack_received != NULL) {
324 /* XXXLAS: Find a way to live without this */
325 tp->ccv->curack = th->th_ack;
326 CC_ALGO(tp)->ack_received(tp->ccv, type);
331 cc_conn_init(struct tcpcb *tp)
333 struct hc_metrics_lite metrics;
334 struct inpcb *inp = tp->t_inpcb;
338 INP_WLOCK_ASSERT(tp->t_inpcb);
340 tcp_hc_get(&inp->inp_inc, &metrics);
341 maxseg = tcp_maxseg(tp);
343 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
345 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
346 TCPSTAT_INC(tcps_usedrtt);
347 if (metrics.rmx_rttvar) {
348 tp->t_rttvar = metrics.rmx_rttvar;
349 TCPSTAT_INC(tcps_usedrttvar);
351 /* default variation is +- 1 rtt */
353 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
355 TCPT_RANGESET(tp->t_rxtcur,
356 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
357 tp->t_rttmin, TCPTV_REXMTMAX);
359 if (metrics.rmx_ssthresh) {
361 * There's some sort of gateway or interface
362 * buffer limit on the path. Use this to set
363 * the slow start threshold, but set the
364 * threshold to no less than 2*mss.
366 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
367 TCPSTAT_INC(tcps_usedssthresh);
371 * Set the initial slow-start flight size.
373 * RFC5681 Section 3.1 specifies the default conservative values.
374 * RFC3390 specifies slightly more aggressive values.
375 * RFC6928 increases it to ten segments.
376 * Support for user specified value for initial flight size.
378 * If a SYN or SYN/ACK was lost and retransmitted, we have to
379 * reduce the initial CWND to one segment as congestion is likely
380 * requiring us to be cautious.
382 if (tp->snd_cwnd == 1)
383 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
384 else if (V_tcp_initcwnd_segments)
385 tp->snd_cwnd = min(V_tcp_initcwnd_segments * maxseg,
386 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
387 else if (V_tcp_do_rfc3390)
388 tp->snd_cwnd = min(4 * maxseg, max(2 * maxseg, 4380));
390 /* Per RFC5681 Section 3.1 */
392 tp->snd_cwnd = 2 * maxseg;
393 else if (maxseg > 1095)
394 tp->snd_cwnd = 3 * maxseg;
396 tp->snd_cwnd = 4 * maxseg;
399 if (CC_ALGO(tp)->conn_init != NULL)
400 CC_ALGO(tp)->conn_init(tp->ccv);
404 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
408 INP_WLOCK_ASSERT(tp->t_inpcb);
412 if (!IN_FASTRECOVERY(tp->t_flags)) {
413 tp->snd_recover = tp->snd_max;
414 if (tp->t_flags & TF_ECN_PERMIT)
415 tp->t_flags |= TF_ECN_SND_CWR;
419 if (!IN_CONGRECOVERY(tp->t_flags)) {
420 TCPSTAT_INC(tcps_ecn_rcwnd);
421 tp->snd_recover = tp->snd_max;
422 if (tp->t_flags & TF_ECN_PERMIT)
423 tp->t_flags |= TF_ECN_SND_CWR;
427 maxseg = tcp_maxseg(tp);
429 tp->t_bytes_acked = 0;
430 EXIT_RECOVERY(tp->t_flags);
431 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
433 tp->snd_cwnd = maxseg;
436 TCPSTAT_INC(tcps_sndrexmitbad);
437 /* RTO was unnecessary, so reset everything. */
438 tp->snd_cwnd = tp->snd_cwnd_prev;
439 tp->snd_ssthresh = tp->snd_ssthresh_prev;
440 tp->snd_recover = tp->snd_recover_prev;
441 if (tp->t_flags & TF_WASFRECOVERY)
442 ENTER_FASTRECOVERY(tp->t_flags);
443 if (tp->t_flags & TF_WASCRECOVERY)
444 ENTER_CONGRECOVERY(tp->t_flags);
445 tp->snd_nxt = tp->snd_max;
446 tp->t_flags &= ~TF_PREVVALID;
451 if (CC_ALGO(tp)->cong_signal != NULL) {
453 tp->ccv->curack = th->th_ack;
454 CC_ALGO(tp)->cong_signal(tp->ccv, type);
459 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
461 INP_WLOCK_ASSERT(tp->t_inpcb);
463 /* XXXLAS: KASSERT that we're in recovery? */
465 if (CC_ALGO(tp)->post_recovery != NULL) {
466 tp->ccv->curack = th->th_ack;
467 CC_ALGO(tp)->post_recovery(tp->ccv);
469 /* XXXLAS: EXIT_RECOVERY ? */
470 tp->t_bytes_acked = 0;
474 * Indicate whether this ack should be delayed. We can delay the ack if
475 * following conditions are met:
476 * - There is no delayed ack timer in progress.
477 * - Our last ack wasn't a 0-sized window. We never want to delay
478 * the ack that opens up a 0-sized window.
479 * - LRO wasn't used for this segment. We make sure by checking that the
480 * segment size is not larger than the MSS.
482 #define DELAY_ACK(tp, tlen) \
483 ((!tcp_timer_active(tp, TT_DELACK) && \
484 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
485 (tlen <= tp->t_maxseg) && \
486 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
489 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
491 INP_WLOCK_ASSERT(tp->t_inpcb);
493 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
494 switch (iptos & IPTOS_ECN_MASK) {
496 tp->ccv->flags |= CCF_IPHDR_CE;
499 tp->ccv->flags &= ~CCF_IPHDR_CE;
502 tp->ccv->flags &= ~CCF_IPHDR_CE;
506 if (th->th_flags & TH_CWR)
507 tp->ccv->flags |= CCF_TCPHDR_CWR;
509 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
511 if (tp->t_flags & TF_DELACK)
512 tp->ccv->flags |= CCF_DELACK;
514 tp->ccv->flags &= ~CCF_DELACK;
516 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
518 if (tp->ccv->flags & CCF_ACKNOW)
519 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
524 * TCP input handling is split into multiple parts:
525 * tcp6_input is a thin wrapper around tcp_input for the extended
526 * ip6_protox[] call format in ip6_input
527 * tcp_input handles primary segment validation, inpcb lookup and
528 * SYN processing on listen sockets
529 * tcp_do_segment processes the ACK and text of the segment for
530 * establishing, established and closing connections
534 tcp6_input(struct mbuf **mp, int *offp, int proto)
536 struct mbuf *m = *mp;
537 struct in6_ifaddr *ia6;
540 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
543 * draft-itojun-ipv6-tcp-to-anycast
544 * better place to put this in?
546 ip6 = mtod(m, struct ip6_hdr *);
547 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
548 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
551 ifa_free(&ia6->ia_ifa);
552 ip6 = mtod(m, struct ip6_hdr *);
553 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
554 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
555 return (IPPROTO_DONE);
558 ifa_free(&ia6->ia_ifa);
560 return (tcp_input(mp, offp, proto));
565 tcp_input(struct mbuf **mp, int *offp, int proto)
567 struct mbuf *m = *mp;
568 struct tcphdr *th = NULL;
569 struct ip *ip = NULL;
570 struct inpcb *inp = NULL;
571 struct tcpcb *tp = NULL;
572 struct socket *so = NULL;
582 int rstreason = 0; /* For badport_bandlim accounting purposes */
584 struct m_tag *fwd_tag = NULL;
586 struct ip6_hdr *ip6 = NULL;
589 const void *ip6 = NULL;
591 struct tcpopt to; /* options in this segment */
592 char *s = NULL; /* address and port logging */
596 * The size of tcp_saveipgen must be the size of the max ip header,
599 u_char tcp_saveipgen[IP6_HDR_LEN];
600 struct tcphdr tcp_savetcp;
605 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
612 TCPSTAT_INC(tcps_rcvtotal);
616 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
618 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
619 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
621 TCPSTAT_INC(tcps_rcvshort);
622 return (IPPROTO_DONE);
626 ip6 = mtod(m, struct ip6_hdr *);
627 th = (struct tcphdr *)((caddr_t)ip6 + off0);
628 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
629 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
630 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
631 th->th_sum = m->m_pkthdr.csum_data;
633 th->th_sum = in6_cksum_pseudo(ip6, tlen,
634 IPPROTO_TCP, m->m_pkthdr.csum_data);
635 th->th_sum ^= 0xffff;
637 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
639 TCPSTAT_INC(tcps_rcvbadsum);
644 * Be proactive about unspecified IPv6 address in source.
645 * As we use all-zero to indicate unbounded/unconnected pcb,
646 * unspecified IPv6 address can be used to confuse us.
648 * Note that packets with unspecified IPv6 destination is
649 * already dropped in ip6_input.
651 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
655 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
658 #if defined(INET) && defined(INET6)
664 * Get IP and TCP header together in first mbuf.
665 * Note: IP leaves IP header in first mbuf.
667 if (off0 > sizeof (struct ip)) {
669 off0 = sizeof(struct ip);
671 if (m->m_len < sizeof (struct tcpiphdr)) {
672 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
674 TCPSTAT_INC(tcps_rcvshort);
675 return (IPPROTO_DONE);
678 ip = mtod(m, struct ip *);
679 th = (struct tcphdr *)((caddr_t)ip + off0);
680 tlen = ntohs(ip->ip_len) - off0;
683 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
684 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
685 th->th_sum = m->m_pkthdr.csum_data;
687 th->th_sum = in_pseudo(ip->ip_src.s_addr,
689 htonl(m->m_pkthdr.csum_data + tlen +
691 th->th_sum ^= 0xffff;
693 struct ipovly *ipov = (struct ipovly *)ip;
696 * Checksum extended TCP header and data.
699 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
700 ipov->ih_len = htons(tlen);
701 th->th_sum = in_cksum(m, len);
702 /* Reset length for SDT probes. */
703 ip->ip_len = htons(len);
706 /* Re-initialization for later version check */
707 ip->ip_v = IPVERSION;
711 TCPSTAT_INC(tcps_rcvbadsum);
718 * Check that TCP offset makes sense,
719 * pull out TCP options and adjust length. XXX
721 off = th->th_off << 2;
722 if (off < sizeof (struct tcphdr) || off > tlen) {
723 TCPSTAT_INC(tcps_rcvbadoff);
726 tlen -= off; /* tlen is used instead of ti->ti_len */
727 if (off > sizeof (struct tcphdr)) {
730 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
731 ip6 = mtod(m, struct ip6_hdr *);
732 th = (struct tcphdr *)((caddr_t)ip6 + off0);
735 #if defined(INET) && defined(INET6)
740 if (m->m_len < sizeof(struct ip) + off) {
741 if ((m = m_pullup(m, sizeof (struct ip) + off))
743 TCPSTAT_INC(tcps_rcvshort);
744 return (IPPROTO_DONE);
746 ip = mtod(m, struct ip *);
747 th = (struct tcphdr *)((caddr_t)ip + off0);
751 optlen = off - sizeof (struct tcphdr);
752 optp = (u_char *)(th + 1);
754 thflags = th->th_flags;
757 * Convert TCP protocol specific fields to host format.
759 tcp_fields_to_host(th);
762 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
764 drop_hdrlen = off0 + off;
767 * Locate pcb for segment; if we're likely to add or remove a
768 * connection then first acquire pcbinfo lock. There are three cases
769 * where we might discover later we need a write lock despite the
770 * flags: ACKs moving a connection out of the syncache, ACKs for a
771 * connection in TIMEWAIT and SYNs not targeting a listening socket.
773 if ((thflags & (TH_FIN | TH_RST)) != 0) {
774 INP_INFO_RLOCK(&V_tcbinfo);
775 ti_locked = TI_RLOCKED;
777 ti_locked = TI_UNLOCKED;
780 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
784 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
786 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
789 #if defined(INET) && !defined(INET6)
790 (m->m_flags & M_IP_NEXTHOP)
793 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
797 if (ti_locked == TI_RLOCKED) {
798 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
800 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
804 if (isipv6 && fwd_tag != NULL) {
805 struct sockaddr_in6 *next_hop6;
807 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
809 * Transparently forwarded. Pretend to be the destination.
810 * Already got one like this?
812 inp = in6_pcblookup_mbuf(&V_tcbinfo,
813 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
814 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
817 * It's new. Try to find the ambushing socket.
818 * Because we've rewritten the destination address,
819 * any hardware-generated hash is ignored.
821 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
822 th->th_sport, &next_hop6->sin6_addr,
823 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
824 th->th_dport, INPLOOKUP_WILDCARD |
825 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
828 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
829 th->th_sport, &ip6->ip6_dst, th->th_dport,
830 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
831 m->m_pkthdr.rcvif, m);
834 #if defined(INET6) && defined(INET)
838 if (fwd_tag != NULL) {
839 struct sockaddr_in *next_hop;
841 next_hop = (struct sockaddr_in *)(fwd_tag+1);
843 * Transparently forwarded. Pretend to be the destination.
844 * already got one like this?
846 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
847 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
848 m->m_pkthdr.rcvif, m);
851 * It's new. Try to find the ambushing socket.
852 * Because we've rewritten the destination address,
853 * any hardware-generated hash is ignored.
855 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
856 th->th_sport, next_hop->sin_addr,
857 next_hop->sin_port ? ntohs(next_hop->sin_port) :
858 th->th_dport, INPLOOKUP_WILDCARD |
859 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
862 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
863 th->th_sport, ip->ip_dst, th->th_dport,
864 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
865 m->m_pkthdr.rcvif, m);
869 * If the INPCB does not exist then all data in the incoming
870 * segment is discarded and an appropriate RST is sent back.
871 * XXX MRT Send RST using which routing table?
875 * Log communication attempts to ports that are not
878 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
879 tcp_log_in_vain == 2) {
880 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
881 log(LOG_INFO, "%s; %s: Connection attempt "
882 "to closed port\n", s, __func__);
885 * When blackholing do not respond with a RST but
886 * completely ignore the segment and drop it.
888 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
892 rstreason = BANDLIM_RST_CLOSEDPORT;
895 INP_WLOCK_ASSERT(inp);
897 * While waiting for inp lock during the lookup, another thread
898 * can have dropped the inpcb, in which case we need to loop back
899 * and try to find a new inpcb to deliver to.
901 if (inp->inp_flags & INP_DROPPED) {
906 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
907 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
908 ((inp->inp_socket == NULL) ||
909 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
910 inp->inp_flowid = m->m_pkthdr.flowid;
911 inp->inp_flowtype = M_HASHTYPE_GET(m);
913 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
915 if (isipv6 && IPSEC_ENABLED(ipv6) &&
916 IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
924 if (IPSEC_ENABLED(ipv4) &&
925 IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
932 * Check the minimum TTL for socket.
934 if (inp->inp_ip_minttl != 0) {
937 if (inp->inp_ip_minttl > ip6->ip6_hlim)
941 if (inp->inp_ip_minttl > ip->ip_ttl)
946 * A previous connection in TIMEWAIT state is supposed to catch stray
947 * or duplicate segments arriving late. If this segment was a
948 * legitimate new connection attempt, the old INPCB gets removed and
949 * we can try again to find a listening socket.
951 * At this point, due to earlier optimism, we may hold only an inpcb
952 * lock, and not the inpcbinfo write lock. If so, we need to try to
953 * acquire it, or if that fails, acquire a reference on the inpcb,
954 * drop all locks, acquire a global write lock, and then re-acquire
955 * the inpcb lock. We may at that point discover that another thread
956 * has tried to free the inpcb, in which case we need to loop back
957 * and try to find a new inpcb to deliver to.
959 * XXXRW: It may be time to rethink timewait locking.
962 if (inp->inp_flags & INP_TIMEWAIT) {
963 if (ti_locked == TI_UNLOCKED) {
964 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
967 INP_INFO_RLOCK(&V_tcbinfo);
968 ti_locked = TI_RLOCKED;
970 if (in_pcbrele_wlocked(inp)) {
973 } else if (inp->inp_flags & INP_DROPPED) {
979 ti_locked = TI_RLOCKED;
981 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
983 if (thflags & TH_SYN)
984 tcp_dooptions(&to, optp, optlen, TO_SYN);
986 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
988 if (tcp_twcheck(inp, &to, th, m, tlen))
990 INP_INFO_RUNLOCK(&V_tcbinfo);
991 return (IPPROTO_DONE);
994 * The TCPCB may no longer exist if the connection is winding
995 * down or it is in the CLOSED state. Either way we drop the
996 * segment and send an appropriate response.
999 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
1000 rstreason = BANDLIM_RST_CLOSEDPORT;
1005 if (tp->t_flags & TF_TOE) {
1006 tcp_offload_input(tp, m);
1007 m = NULL; /* consumed by the TOE driver */
1013 * We've identified a valid inpcb, but it could be that we need an
1014 * inpcbinfo write lock but don't hold it. In this case, attempt to
1015 * acquire using the same strategy as the TIMEWAIT case above. If we
1016 * relock, we have to jump back to 'relocked' as the connection might
1017 * now be in TIMEWAIT.
1020 if ((thflags & (TH_FIN | TH_RST)) != 0)
1021 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1023 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1024 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
1025 !IS_FASTOPEN(tp->t_flags)))) {
1026 if (ti_locked == TI_UNLOCKED) {
1027 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
1030 INP_INFO_RLOCK(&V_tcbinfo);
1031 ti_locked = TI_RLOCKED;
1033 if (in_pcbrele_wlocked(inp)) {
1036 } else if (inp->inp_flags & INP_DROPPED) {
1043 ti_locked = TI_RLOCKED;
1045 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1049 INP_WLOCK_ASSERT(inp);
1050 if (mac_inpcb_check_deliver(inp, m))
1053 so = inp->inp_socket;
1054 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1056 if (so->so_options & SO_DEBUG) {
1057 ostate = tp->t_state;
1060 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1063 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1066 #endif /* TCPDEBUG */
1068 * When the socket is accepting connections (the INPCB is in LISTEN
1069 * state) we look into the SYN cache if this is a new connection
1070 * attempt or the completion of a previous one.
1072 KASSERT(tp->t_state == TCPS_LISTEN || !(so->so_options & SO_ACCEPTCONN),
1073 ("%s: so accepting but tp %p not listening", __func__, tp));
1074 if (tp->t_state == TCPS_LISTEN && (so->so_options & SO_ACCEPTCONN)) {
1075 struct in_conninfo inc;
1077 bzero(&inc, sizeof(inc));
1080 inc.inc_flags |= INC_ISIPV6;
1081 inc.inc6_faddr = ip6->ip6_src;
1082 inc.inc6_laddr = ip6->ip6_dst;
1086 inc.inc_faddr = ip->ip_src;
1087 inc.inc_laddr = ip->ip_dst;
1089 inc.inc_fport = th->th_sport;
1090 inc.inc_lport = th->th_dport;
1091 inc.inc_fibnum = so->so_fibnum;
1094 * Check for an existing connection attempt in syncache if
1095 * the flag is only ACK. A successful lookup creates a new
1096 * socket appended to the listen queue in SYN_RECEIVED state.
1098 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1100 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1102 * Parse the TCP options here because
1103 * syncookies need access to the reflected
1106 tcp_dooptions(&to, optp, optlen, 0);
1108 * NB: syncache_expand() doesn't unlock
1109 * inp and tcpinfo locks.
1111 rstreason = syncache_expand(&inc, &to, th, &so, m);
1112 if (rstreason < 0) {
1114 * A failing TCP MD5 signature comparison
1115 * must result in the segment being dropped
1116 * and must not produce any response back
1120 } else if (rstreason == 0) {
1122 * No syncache entry or ACK was not
1123 * for our SYN/ACK. Send a RST.
1124 * NB: syncache did its own logging
1125 * of the failure cause.
1127 rstreason = BANDLIM_RST_OPENPORT;
1135 * We completed the 3-way handshake
1136 * but could not allocate a socket
1137 * either due to memory shortage,
1138 * listen queue length limits or
1139 * global socket limits. Send RST
1140 * or wait and have the remote end
1141 * retransmit the ACK for another
1144 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1145 log(LOG_DEBUG, "%s; %s: Listen socket: "
1146 "Socket allocation failed due to "
1147 "limits or memory shortage, %s\n",
1149 V_tcp_sc_rst_sock_fail ?
1150 "sending RST" : "try again");
1151 if (V_tcp_sc_rst_sock_fail) {
1152 rstreason = BANDLIM_UNLIMITED;
1158 * Socket is created in state SYN_RECEIVED.
1159 * Unlock the listen socket, lock the newly
1160 * created socket and update the tp variable.
1162 INP_WUNLOCK(inp); /* listen socket */
1163 inp = sotoinpcb(so);
1165 * New connection inpcb is already locked by
1166 * syncache_expand().
1168 INP_WLOCK_ASSERT(inp);
1169 tp = intotcpcb(inp);
1170 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1171 ("%s: ", __func__));
1173 * Process the segment and the data it
1174 * contains. tcp_do_segment() consumes
1175 * the mbuf chain and unlocks the inpcb.
1177 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1179 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1180 return (IPPROTO_DONE);
1183 * Segment flag validation for new connection attempts:
1185 * Our (SYN|ACK) response was rejected.
1186 * Check with syncache and remove entry to prevent
1189 * NB: syncache_chkrst does its own logging of failure
1192 if (thflags & TH_RST) {
1193 syncache_chkrst(&inc, th);
1197 * We can't do anything without SYN.
1199 if ((thflags & TH_SYN) == 0) {
1200 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1201 log(LOG_DEBUG, "%s; %s: Listen socket: "
1202 "SYN is missing, segment ignored\n",
1204 TCPSTAT_INC(tcps_badsyn);
1208 * (SYN|ACK) is bogus on a listen socket.
1210 if (thflags & TH_ACK) {
1211 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1212 log(LOG_DEBUG, "%s; %s: Listen socket: "
1213 "SYN|ACK invalid, segment rejected\n",
1215 syncache_badack(&inc); /* XXX: Not needed! */
1216 TCPSTAT_INC(tcps_badsyn);
1217 rstreason = BANDLIM_RST_OPENPORT;
1221 * If the drop_synfin option is enabled, drop all
1222 * segments with both the SYN and FIN bits set.
1223 * This prevents e.g. nmap from identifying the
1225 * XXX: Poor reasoning. nmap has other methods
1226 * and is constantly refining its stack detection
1228 * XXX: This is a violation of the TCP specification
1229 * and was used by RFC1644.
1231 if ((thflags & TH_FIN) && V_drop_synfin) {
1232 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1233 log(LOG_DEBUG, "%s; %s: Listen socket: "
1234 "SYN|FIN segment ignored (based on "
1235 "sysctl setting)\n", s, __func__);
1236 TCPSTAT_INC(tcps_badsyn);
1240 * Segment's flags are (SYN) or (SYN|FIN).
1242 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1243 * as they do not affect the state of the TCP FSM.
1244 * The data pointed to by TH_URG and th_urp is ignored.
1246 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1247 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1248 KASSERT(thflags & (TH_SYN),
1249 ("%s: Listen socket: TH_SYN not set", __func__));
1252 * If deprecated address is forbidden,
1253 * we do not accept SYN to deprecated interface
1254 * address to prevent any new inbound connection from
1255 * getting established.
1256 * When we do not accept SYN, we send a TCP RST,
1257 * with deprecated source address (instead of dropping
1258 * it). We compromise it as it is much better for peer
1259 * to send a RST, and RST will be the final packet
1262 * If we do not forbid deprecated addresses, we accept
1263 * the SYN packet. RFC2462 does not suggest dropping
1265 * If we decipher RFC2462 5.5.4, it says like this:
1266 * 1. use of deprecated addr with existing
1267 * communication is okay - "SHOULD continue to be
1269 * 2. use of it with new communication:
1270 * (2a) "SHOULD NOT be used if alternate address
1271 * with sufficient scope is available"
1272 * (2b) nothing mentioned otherwise.
1273 * Here we fall into (2b) case as we have no choice in
1274 * our source address selection - we must obey the peer.
1276 * The wording in RFC2462 is confusing, and there are
1277 * multiple description text for deprecated address
1278 * handling - worse, they are not exactly the same.
1279 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1281 if (isipv6 && !V_ip6_use_deprecated) {
1282 struct in6_ifaddr *ia6;
1284 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1286 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1287 ifa_free(&ia6->ia_ifa);
1288 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1289 log(LOG_DEBUG, "%s; %s: Listen socket: "
1290 "Connection attempt to deprecated "
1291 "IPv6 address rejected\n",
1293 rstreason = BANDLIM_RST_OPENPORT;
1297 ifa_free(&ia6->ia_ifa);
1301 * Basic sanity checks on incoming SYN requests:
1302 * Don't respond if the destination is a link layer
1303 * broadcast according to RFC1122 4.2.3.10, p. 104.
1304 * If it is from this socket it must be forged.
1305 * Don't respond if the source or destination is a
1306 * global or subnet broad- or multicast address.
1307 * Note that it is quite possible to receive unicast
1308 * link-layer packets with a broadcast IP address. Use
1309 * in_broadcast() to find them.
1311 if (m->m_flags & (M_BCAST|M_MCAST)) {
1312 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1313 log(LOG_DEBUG, "%s; %s: Listen socket: "
1314 "Connection attempt from broad- or multicast "
1315 "link layer address ignored\n", s, __func__);
1320 if (th->th_dport == th->th_sport &&
1321 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1322 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1323 log(LOG_DEBUG, "%s; %s: Listen socket: "
1324 "Connection attempt to/from self "
1325 "ignored\n", s, __func__);
1328 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1329 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1330 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1331 log(LOG_DEBUG, "%s; %s: Listen socket: "
1332 "Connection attempt from/to multicast "
1333 "address ignored\n", s, __func__);
1338 #if defined(INET) && defined(INET6)
1343 if (th->th_dport == th->th_sport &&
1344 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1345 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1346 log(LOG_DEBUG, "%s; %s: Listen socket: "
1347 "Connection attempt from/to self "
1348 "ignored\n", s, __func__);
1351 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1352 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1353 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1354 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1355 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1356 log(LOG_DEBUG, "%s; %s: Listen socket: "
1357 "Connection attempt from/to broad- "
1358 "or multicast address ignored\n",
1365 * SYN appears to be valid. Create compressed TCP state
1369 if (so->so_options & SO_DEBUG)
1370 tcp_trace(TA_INPUT, ostate, tp,
1371 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1373 TCP_PROBE3(debug__input, tp, th, m);
1374 tcp_dooptions(&to, optp, optlen, TO_SYN);
1376 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
1377 goto tfo_socket_result;
1379 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1382 * Entry added to syncache and mbuf consumed.
1383 * Only the listen socket is unlocked by syncache_add().
1385 if (ti_locked == TI_RLOCKED) {
1386 INP_INFO_RUNLOCK(&V_tcbinfo);
1387 ti_locked = TI_UNLOCKED;
1389 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1390 return (IPPROTO_DONE);
1391 } else if (tp->t_state == TCPS_LISTEN) {
1393 * When a listen socket is torn down the SO_ACCEPTCONN
1394 * flag is removed first while connections are drained
1395 * from the accept queue in a unlock/lock cycle of the
1396 * ACCEPT_LOCK, opening a race condition allowing a SYN
1397 * attempt go through unhandled.
1401 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1402 if (tp->t_flags & TF_SIGNATURE) {
1403 tcp_dooptions(&to, optp, optlen, thflags);
1404 if ((to.to_flags & TOF_SIGNATURE) == 0) {
1405 TCPSTAT_INC(tcps_sig_err_nosigopt);
1408 if (!TCPMD5_ENABLED() ||
1409 TCPMD5_INPUT(m, th, to.to_signature) != 0)
1413 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1416 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1417 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1418 * the inpcb, and unlocks pcbinfo.
1420 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1421 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1422 return (IPPROTO_DONE);
1425 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1427 if (ti_locked == TI_RLOCKED) {
1428 INP_INFO_RUNLOCK(&V_tcbinfo);
1429 ti_locked = TI_UNLOCKED;
1433 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1434 "ti_locked: %d", __func__, ti_locked));
1435 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1440 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1443 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1444 m = NULL; /* mbuf chain got consumed. */
1449 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1451 if (ti_locked == TI_RLOCKED) {
1452 INP_INFO_RUNLOCK(&V_tcbinfo);
1453 ti_locked = TI_UNLOCKED;
1457 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1458 "ti_locked: %d", __func__, ti_locked));
1459 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1467 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1472 return (IPPROTO_DONE);
1476 * Automatic sizing of receive socket buffer. Often the send
1477 * buffer size is not optimally adjusted to the actual network
1478 * conditions at hand (delay bandwidth product). Setting the
1479 * buffer size too small limits throughput on links with high
1480 * bandwidth and high delay (eg. trans-continental/oceanic links).
1482 * On the receive side the socket buffer memory is only rarely
1483 * used to any significant extent. This allows us to be much
1484 * more aggressive in scaling the receive socket buffer. For
1485 * the case that the buffer space is actually used to a large
1486 * extent and we run out of kernel memory we can simply drop
1487 * the new segments; TCP on the sender will just retransmit it
1488 * later. Setting the buffer size too big may only consume too
1489 * much kernel memory if the application doesn't read() from
1490 * the socket or packet loss or reordering makes use of the
1493 * The criteria to step up the receive buffer one notch are:
1494 * 1. Application has not set receive buffer size with
1495 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1496 * 2. the number of bytes received during the time it takes
1497 * one timestamp to be reflected back to us (the RTT);
1498 * 3. received bytes per RTT is within seven eighth of the
1499 * current socket buffer size;
1500 * 4. receive buffer size has not hit maximal automatic size;
1502 * This algorithm does one step per RTT at most and only if
1503 * we receive a bulk stream w/o packet losses or reorderings.
1504 * Shrinking the buffer during idle times is not necessary as
1505 * it doesn't consume any memory when idle.
1507 * TODO: Only step up if the application is actually serving
1508 * the buffer to better manage the socket buffer resources.
1511 tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1512 struct tcpcb *tp, int tlen)
1516 if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1517 tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1518 TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1519 (tp->t_srtt >> TCP_RTT_SHIFT)) {
1520 if (tp->rfbuf_cnt > (so->so_rcv.sb_hiwat / 8 * 7) &&
1521 so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1522 newsize = min(so->so_rcv.sb_hiwat +
1523 V_tcp_autorcvbuf_inc, V_tcp_autorcvbuf_max);
1525 TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1527 /* Start over with next RTT. */
1531 tp->rfbuf_cnt += tlen; /* add up */
1538 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1539 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1542 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1543 int rstreason, todrop, win;
1547 struct in_conninfo *inc;
1556 * The size of tcp_saveipgen must be the size of the max ip header,
1559 u_char tcp_saveipgen[IP6_HDR_LEN];
1560 struct tcphdr tcp_savetcp;
1563 thflags = th->th_flags;
1564 inc = &tp->t_inpcb->inp_inc;
1565 tp->sackhint.last_sack_ack = 0;
1567 nsegs = max(1, m->m_pkthdr.lro_nsegs);
1570 * If this is either a state-changing packet or current state isn't
1571 * established, we require a write lock on tcbinfo. Otherwise, we
1572 * allow the tcbinfo to be in either alocked or unlocked, as the
1573 * caller may have unnecessarily acquired a write lock due to a race.
1575 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1576 tp->t_state != TCPS_ESTABLISHED) {
1577 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1578 "SYN/FIN/RST/!EST", __func__, ti_locked));
1579 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1582 if (ti_locked == TI_RLOCKED)
1583 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1585 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1586 "ti_locked: %d", __func__, ti_locked));
1587 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1591 INP_WLOCK_ASSERT(tp->t_inpcb);
1592 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1594 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1598 /* Save segment, if requested. */
1599 tcp_pcap_add(th, m, &(tp->t_inpkts));
1602 if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1603 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1604 log(LOG_DEBUG, "%s; %s: "
1605 "SYN|FIN segment ignored (based on "
1606 "sysctl setting)\n", s, __func__);
1613 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1614 * check SEQ.ACK first.
1616 if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1617 (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1618 rstreason = BANDLIM_UNLIMITED;
1623 * Segment received on connection.
1624 * Reset idle time and keep-alive timer.
1625 * XXX: This should be done after segment
1626 * validation to ignore broken/spoofed segs.
1628 tp->t_rcvtime = ticks;
1631 * Scale up the window into a 32-bit value.
1632 * For the SYN_SENT state the scale is zero.
1634 tiwin = th->th_win << tp->snd_scale;
1637 * TCP ECN processing.
1639 if (tp->t_flags & TF_ECN_PERMIT) {
1640 if (thflags & TH_CWR)
1641 tp->t_flags &= ~TF_ECN_SND_ECE;
1642 switch (iptos & IPTOS_ECN_MASK) {
1644 tp->t_flags |= TF_ECN_SND_ECE;
1645 TCPSTAT_INC(tcps_ecn_ce);
1647 case IPTOS_ECN_ECT0:
1648 TCPSTAT_INC(tcps_ecn_ect0);
1650 case IPTOS_ECN_ECT1:
1651 TCPSTAT_INC(tcps_ecn_ect1);
1655 /* Process a packet differently from RFC3168. */
1656 cc_ecnpkt_handler(tp, th, iptos);
1658 /* Congestion experienced. */
1659 if (thflags & TH_ECE) {
1660 cc_cong_signal(tp, th, CC_ECN);
1665 * Parse options on any incoming segment.
1667 tcp_dooptions(&to, (u_char *)(th + 1),
1668 (th->th_off << 2) - sizeof(struct tcphdr),
1669 (thflags & TH_SYN) ? TO_SYN : 0);
1671 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1672 if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1673 (to.to_flags & TOF_SIGNATURE) == 0) {
1674 TCPSTAT_INC(tcps_sig_err_sigopt);
1675 /* XXX: should drop? */
1679 * If echoed timestamp is later than the current time,
1680 * fall back to non RFC1323 RTT calculation. Normalize
1681 * timestamp if syncookies were used when this connection
1684 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1685 to.to_tsecr -= tp->ts_offset;
1686 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1690 * Process options only when we get SYN/ACK back. The SYN case
1691 * for incoming connections is handled in tcp_syncache.
1692 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1693 * or <SYN,ACK>) segment itself is never scaled.
1694 * XXX this is traditional behavior, may need to be cleaned up.
1696 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1697 if ((to.to_flags & TOF_SCALE) &&
1698 (tp->t_flags & TF_REQ_SCALE)) {
1699 tp->t_flags |= TF_RCVD_SCALE;
1700 tp->snd_scale = to.to_wscale;
1703 * Initial send window. It will be updated with
1704 * the next incoming segment to the scaled value.
1706 tp->snd_wnd = th->th_win;
1707 if (to.to_flags & TOF_TS) {
1708 tp->t_flags |= TF_RCVD_TSTMP;
1709 tp->ts_recent = to.to_tsval;
1710 tp->ts_recent_age = tcp_ts_getticks();
1712 if (to.to_flags & TOF_MSS)
1713 tcp_mss(tp, to.to_mss);
1714 if ((tp->t_flags & TF_SACK_PERMIT) &&
1715 (to.to_flags & TOF_SACKPERM) == 0)
1716 tp->t_flags &= ~TF_SACK_PERMIT;
1720 * If timestamps were negotiated during SYN/ACK they should
1721 * appear on every segment during this session and vice versa.
1723 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1724 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1725 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1726 "no action\n", s, __func__);
1730 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1731 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1732 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1733 "no action\n", s, __func__);
1739 * Header prediction: check for the two common cases
1740 * of a uni-directional data xfer. If the packet has
1741 * no control flags, is in-sequence, the window didn't
1742 * change and we're not retransmitting, it's a
1743 * candidate. If the length is zero and the ack moved
1744 * forward, we're the sender side of the xfer. Just
1745 * free the data acked & wake any higher level process
1746 * that was blocked waiting for space. If the length
1747 * is non-zero and the ack didn't move, we're the
1748 * receiver side. If we're getting packets in-order
1749 * (the reassembly queue is empty), add the data to
1750 * the socket buffer and note that we need a delayed ack.
1751 * Make sure that the hidden state-flags are also off.
1752 * Since we check for TCPS_ESTABLISHED first, it can only
1755 if (tp->t_state == TCPS_ESTABLISHED &&
1756 th->th_seq == tp->rcv_nxt &&
1757 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1758 tp->snd_nxt == tp->snd_max &&
1759 tiwin && tiwin == tp->snd_wnd &&
1760 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1761 LIST_EMPTY(&tp->t_segq) &&
1762 ((to.to_flags & TOF_TS) == 0 ||
1763 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1766 * If last ACK falls within this segment's sequence numbers,
1767 * record the timestamp.
1768 * NOTE that the test is modified according to the latest
1769 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1771 if ((to.to_flags & TOF_TS) != 0 &&
1772 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1773 tp->ts_recent_age = tcp_ts_getticks();
1774 tp->ts_recent = to.to_tsval;
1778 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1779 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1780 !IN_RECOVERY(tp->t_flags) &&
1781 (to.to_flags & TOF_SACK) == 0 &&
1782 TAILQ_EMPTY(&tp->snd_holes)) {
1784 * This is a pure ack for outstanding data.
1786 if (ti_locked == TI_RLOCKED)
1787 INP_INFO_RUNLOCK(&V_tcbinfo);
1788 ti_locked = TI_UNLOCKED;
1790 TCPSTAT_INC(tcps_predack);
1793 * "bad retransmit" recovery.
1795 if (tp->t_rxtshift == 1 &&
1796 tp->t_flags & TF_PREVVALID &&
1797 (int)(ticks - tp->t_badrxtwin) < 0) {
1798 cc_cong_signal(tp, th, CC_RTO_ERR);
1802 * Recalculate the transmit timer / rtt.
1804 * Some boxes send broken timestamp replies
1805 * during the SYN+ACK phase, ignore
1806 * timestamps of 0 or we could calculate a
1807 * huge RTT and blow up the retransmit timer.
1809 if ((to.to_flags & TOF_TS) != 0 &&
1813 t = tcp_ts_getticks() - to.to_tsecr;
1814 if (!tp->t_rttlow || tp->t_rttlow > t)
1817 TCP_TS_TO_TICKS(t) + 1);
1818 } else if (tp->t_rtttime &&
1819 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1820 if (!tp->t_rttlow ||
1821 tp->t_rttlow > ticks - tp->t_rtttime)
1822 tp->t_rttlow = ticks - tp->t_rtttime;
1824 ticks - tp->t_rtttime);
1826 acked = BYTES_THIS_ACK(tp, th);
1829 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1830 hhook_run_tcp_est_in(tp, th, &to);
1833 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
1834 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1835 sbdrop(&so->so_snd, acked);
1836 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1837 SEQ_LEQ(th->th_ack, tp->snd_recover))
1838 tp->snd_recover = th->th_ack - 1;
1841 * Let the congestion control algorithm update
1842 * congestion control related information. This
1843 * typically means increasing the congestion
1846 cc_ack_received(tp, th, nsegs, CC_ACK);
1848 tp->snd_una = th->th_ack;
1850 * Pull snd_wl2 up to prevent seq wrap relative
1853 tp->snd_wl2 = th->th_ack;
1858 * If all outstanding data are acked, stop
1859 * retransmit timer, otherwise restart timer
1860 * using current (possibly backed-off) value.
1861 * If process is waiting for space,
1862 * wakeup/selwakeup/signal. If data
1863 * are ready to send, let tcp_output
1864 * decide between more output or persist.
1867 if (so->so_options & SO_DEBUG)
1868 tcp_trace(TA_INPUT, ostate, tp,
1869 (void *)tcp_saveipgen,
1872 TCP_PROBE3(debug__input, tp, th, m);
1873 if (tp->snd_una == tp->snd_max)
1874 tcp_timer_activate(tp, TT_REXMT, 0);
1875 else if (!tcp_timer_active(tp, TT_PERSIST))
1876 tcp_timer_activate(tp, TT_REXMT,
1879 if (sbavail(&so->so_snd))
1880 (void) tp->t_fb->tfb_tcp_output(tp);
1883 } else if (th->th_ack == tp->snd_una &&
1884 tlen <= sbspace(&so->so_rcv)) {
1885 int newsize = 0; /* automatic sockbuf scaling */
1888 * This is a pure, in-sequence data packet with
1889 * nothing on the reassembly queue and we have enough
1890 * buffer space to take it.
1892 if (ti_locked == TI_RLOCKED)
1893 INP_INFO_RUNLOCK(&V_tcbinfo);
1894 ti_locked = TI_UNLOCKED;
1896 /* Clean receiver SACK report if present */
1897 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1898 tcp_clean_sackreport(tp);
1899 TCPSTAT_INC(tcps_preddat);
1900 tp->rcv_nxt += tlen;
1902 * Pull snd_wl1 up to prevent seq wrap relative to
1905 tp->snd_wl1 = th->th_seq;
1907 * Pull rcv_up up to prevent seq wrap relative to
1910 tp->rcv_up = tp->rcv_nxt;
1911 TCPSTAT_ADD(tcps_rcvpack, nsegs);
1912 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1914 if (so->so_options & SO_DEBUG)
1915 tcp_trace(TA_INPUT, ostate, tp,
1916 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1918 TCP_PROBE3(debug__input, tp, th, m);
1920 newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
1922 /* Add data to socket buffer. */
1923 SOCKBUF_LOCK(&so->so_rcv);
1924 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1928 * Set new socket buffer size.
1929 * Give up when limit is reached.
1932 if (!sbreserve_locked(&so->so_rcv,
1934 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1935 m_adj(m, drop_hdrlen); /* delayed header drop */
1936 sbappendstream_locked(&so->so_rcv, m, 0);
1938 /* NB: sorwakeup_locked() does an implicit unlock. */
1939 sorwakeup_locked(so);
1940 if (DELAY_ACK(tp, tlen)) {
1941 tp->t_flags |= TF_DELACK;
1943 tp->t_flags |= TF_ACKNOW;
1944 tp->t_fb->tfb_tcp_output(tp);
1951 * Calculate amount of space in receive window,
1952 * and then do TCP input processing.
1953 * Receive window is amount of space in rcv queue,
1954 * but not less than advertised window.
1956 win = sbspace(&so->so_rcv);
1959 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1961 switch (tp->t_state) {
1964 * If the state is SYN_RECEIVED:
1965 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1967 case TCPS_SYN_RECEIVED:
1968 if ((thflags & TH_ACK) &&
1969 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1970 SEQ_GT(th->th_ack, tp->snd_max))) {
1971 rstreason = BANDLIM_RST_OPENPORT;
1975 if (IS_FASTOPEN(tp->t_flags)) {
1977 * When a TFO connection is in SYN_RECEIVED, the
1978 * only valid packets are the initial SYN, a
1979 * retransmit/copy of the initial SYN (possibly with
1980 * a subset of the original data), a valid ACK, a
1983 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1984 rstreason = BANDLIM_RST_OPENPORT;
1986 } else if (thflags & TH_SYN) {
1987 /* non-initial SYN is ignored */
1988 if ((tcp_timer_active(tp, TT_DELACK) ||
1989 tcp_timer_active(tp, TT_REXMT)))
1991 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1999 * If the state is SYN_SENT:
2000 * if seg contains a RST with valid ACK (SEQ.ACK has already
2001 * been verified), then drop the connection.
2002 * if seg contains a RST without an ACK, drop the seg.
2003 * if seg does not contain SYN, then drop the seg.
2004 * Otherwise this is an acceptable SYN segment
2005 * initialize tp->rcv_nxt and tp->irs
2006 * if seg contains ack then advance tp->snd_una
2007 * if seg contains an ECE and ECN support is enabled, the stream
2009 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2010 * arrange for segment to be acked (eventually)
2011 * continue processing rest of data/controls, beginning with URG
2014 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2015 TCP_PROBE5(connect__refused, NULL, tp,
2017 tp = tcp_drop(tp, ECONNREFUSED);
2019 if (thflags & TH_RST)
2021 if (!(thflags & TH_SYN))
2024 tp->irs = th->th_seq;
2026 if (thflags & TH_ACK) {
2027 TCPSTAT_INC(tcps_connects);
2030 mac_socketpeer_set_from_mbuf(m, so);
2032 /* Do window scaling on this connection? */
2033 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2034 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2035 tp->rcv_scale = tp->request_r_scale;
2037 tp->rcv_adv += min(tp->rcv_wnd,
2038 TCP_MAXWIN << tp->rcv_scale);
2039 tp->snd_una++; /* SYN is acked */
2041 * If there's data, delay ACK; if there's also a FIN
2042 * ACKNOW will be turned on later.
2044 if (DELAY_ACK(tp, tlen) && tlen != 0)
2045 tcp_timer_activate(tp, TT_DELACK,
2048 tp->t_flags |= TF_ACKNOW;
2050 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
2051 tp->t_flags |= TF_ECN_PERMIT;
2052 TCPSTAT_INC(tcps_ecn_shs);
2056 * Received <SYN,ACK> in SYN_SENT[*] state.
2058 * SYN_SENT --> ESTABLISHED
2059 * SYN_SENT* --> FIN_WAIT_1
2061 tp->t_starttime = ticks;
2062 if (tp->t_flags & TF_NEEDFIN) {
2063 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2064 tp->t_flags &= ~TF_NEEDFIN;
2067 tcp_state_change(tp, TCPS_ESTABLISHED);
2068 TCP_PROBE5(connect__established, NULL, tp,
2071 tcp_timer_activate(tp, TT_KEEP,
2076 * Received initial SYN in SYN-SENT[*] state =>
2077 * simultaneous open.
2078 * If it succeeds, connection is * half-synchronized.
2079 * Otherwise, do 3-way handshake:
2080 * SYN-SENT -> SYN-RECEIVED
2081 * SYN-SENT* -> SYN-RECEIVED*
2083 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2084 tcp_timer_activate(tp, TT_REXMT, 0);
2085 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2088 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
2089 "ti_locked %d", __func__, ti_locked));
2090 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2091 INP_WLOCK_ASSERT(tp->t_inpcb);
2094 * Advance th->th_seq to correspond to first data byte.
2095 * If data, trim to stay within window,
2096 * dropping FIN if necessary.
2099 if (tlen > tp->rcv_wnd) {
2100 todrop = tlen - tp->rcv_wnd;
2104 TCPSTAT_INC(tcps_rcvpackafterwin);
2105 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2107 tp->snd_wl1 = th->th_seq - 1;
2108 tp->rcv_up = th->th_seq;
2110 * Client side of transaction: already sent SYN and data.
2111 * If the remote host used T/TCP to validate the SYN,
2112 * our data will be ACK'd; if so, enter normal data segment
2113 * processing in the middle of step 5, ack processing.
2114 * Otherwise, goto step 6.
2116 if (thflags & TH_ACK)
2122 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2123 * do normal processing.
2125 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2129 break; /* continue normal processing */
2133 * States other than LISTEN or SYN_SENT.
2134 * First check the RST flag and sequence number since reset segments
2135 * are exempt from the timestamp and connection count tests. This
2136 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2137 * below which allowed reset segments in half the sequence space
2138 * to fall though and be processed (which gives forged reset
2139 * segments with a random sequence number a 50 percent chance of
2140 * killing a connection).
2141 * Then check timestamp, if present.
2142 * Then check the connection count, if present.
2143 * Then check that at least some bytes of segment are within
2144 * receive window. If segment begins before rcv_nxt,
2145 * drop leading data (and SYN); if nothing left, just ack.
2147 if (thflags & TH_RST) {
2149 * RFC5961 Section 3.2
2151 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2152 * - If RST is in window, we send challenge ACK.
2154 * Note: to take into account delayed ACKs, we should
2155 * test against last_ack_sent instead of rcv_nxt.
2156 * Note 2: we handle special case of closed window, not
2157 * covered by the RFC.
2159 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2160 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2161 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2163 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2164 KASSERT(ti_locked == TI_RLOCKED,
2165 ("%s: TH_RST ti_locked %d, th %p tp %p",
2166 __func__, ti_locked, th, tp));
2167 KASSERT(tp->t_state != TCPS_SYN_SENT,
2168 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2171 if (V_tcp_insecure_rst ||
2172 tp->last_ack_sent == th->th_seq) {
2173 TCPSTAT_INC(tcps_drops);
2174 /* Drop the connection. */
2175 switch (tp->t_state) {
2176 case TCPS_SYN_RECEIVED:
2177 so->so_error = ECONNREFUSED;
2179 case TCPS_ESTABLISHED:
2180 case TCPS_FIN_WAIT_1:
2181 case TCPS_FIN_WAIT_2:
2182 case TCPS_CLOSE_WAIT:
2185 so->so_error = ECONNRESET;
2192 TCPSTAT_INC(tcps_badrst);
2193 /* Send challenge ACK. */
2194 tcp_respond(tp, mtod(m, void *), th, m,
2195 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2196 tp->last_ack_sent = tp->rcv_nxt;
2204 * RFC5961 Section 4.2
2205 * Send challenge ACK for any SYN in synchronized state.
2207 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2208 tp->t_state != TCPS_SYN_RECEIVED) {
2209 KASSERT(ti_locked == TI_RLOCKED,
2210 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2211 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2213 TCPSTAT_INC(tcps_badsyn);
2214 if (V_tcp_insecure_syn &&
2215 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2216 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2217 tp = tcp_drop(tp, ECONNRESET);
2218 rstreason = BANDLIM_UNLIMITED;
2220 /* Send challenge ACK. */
2221 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2222 tp->snd_nxt, TH_ACK);
2223 tp->last_ack_sent = tp->rcv_nxt;
2230 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2231 * and it's less than ts_recent, drop it.
2233 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2234 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2236 /* Check to see if ts_recent is over 24 days old. */
2237 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2239 * Invalidate ts_recent. If this segment updates
2240 * ts_recent, the age will be reset later and ts_recent
2241 * will get a valid value. If it does not, setting
2242 * ts_recent to zero will at least satisfy the
2243 * requirement that zero be placed in the timestamp
2244 * echo reply when ts_recent isn't valid. The
2245 * age isn't reset until we get a valid ts_recent
2246 * because we don't want out-of-order segments to be
2247 * dropped when ts_recent is old.
2251 TCPSTAT_INC(tcps_rcvduppack);
2252 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2253 TCPSTAT_INC(tcps_pawsdrop);
2261 * In the SYN-RECEIVED state, validate that the packet belongs to
2262 * this connection before trimming the data to fit the receive
2263 * window. Check the sequence number versus IRS since we know
2264 * the sequence numbers haven't wrapped. This is a partial fix
2265 * for the "LAND" DoS attack.
2267 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2268 rstreason = BANDLIM_RST_OPENPORT;
2272 todrop = tp->rcv_nxt - th->th_seq;
2274 if (thflags & TH_SYN) {
2284 * Following if statement from Stevens, vol. 2, p. 960.
2287 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2289 * Any valid FIN must be to the left of the window.
2290 * At this point the FIN must be a duplicate or out
2291 * of sequence; drop it.
2296 * Send an ACK to resynchronize and drop any data.
2297 * But keep on processing for RST or ACK.
2299 tp->t_flags |= TF_ACKNOW;
2301 TCPSTAT_INC(tcps_rcvduppack);
2302 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2304 TCPSTAT_INC(tcps_rcvpartduppack);
2305 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2307 drop_hdrlen += todrop; /* drop from the top afterwards */
2308 th->th_seq += todrop;
2310 if (th->th_urp > todrop)
2311 th->th_urp -= todrop;
2319 * If new data are received on a connection after the
2320 * user processes are gone, then RST the other end.
2322 if ((so->so_state & SS_NOFDREF) &&
2323 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2324 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
2325 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2326 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2328 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2329 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2330 "after socket was closed, "
2331 "sending RST and removing tcpcb\n",
2332 s, __func__, tcpstates[tp->t_state], tlen);
2336 TCPSTAT_INC(tcps_rcvafterclose);
2337 rstreason = BANDLIM_UNLIMITED;
2342 * If segment ends after window, drop trailing data
2343 * (and PUSH and FIN); if nothing left, just ACK.
2345 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2347 TCPSTAT_INC(tcps_rcvpackafterwin);
2348 if (todrop >= tlen) {
2349 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2351 * If window is closed can only take segments at
2352 * window edge, and have to drop data and PUSH from
2353 * incoming segments. Continue processing, but
2354 * remember to ack. Otherwise, drop segment
2357 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2358 tp->t_flags |= TF_ACKNOW;
2359 TCPSTAT_INC(tcps_rcvwinprobe);
2363 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2366 thflags &= ~(TH_PUSH|TH_FIN);
2370 * If last ACK falls within this segment's sequence numbers,
2371 * record its timestamp.
2373 * 1) That the test incorporates suggestions from the latest
2374 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2375 * 2) That updating only on newer timestamps interferes with
2376 * our earlier PAWS tests, so this check should be solely
2377 * predicated on the sequence space of this segment.
2378 * 3) That we modify the segment boundary check to be
2379 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2380 * instead of RFC1323's
2381 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2382 * This modified check allows us to overcome RFC1323's
2383 * limitations as described in Stevens TCP/IP Illustrated
2384 * Vol. 2 p.869. In such cases, we can still calculate the
2385 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2387 if ((to.to_flags & TOF_TS) != 0 &&
2388 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2389 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2390 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2391 tp->ts_recent_age = tcp_ts_getticks();
2392 tp->ts_recent = to.to_tsval;
2396 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2397 * flag is on (half-synchronized state), then queue data for
2398 * later processing; else drop segment and return.
2400 if ((thflags & TH_ACK) == 0) {
2401 if (tp->t_state == TCPS_SYN_RECEIVED ||
2402 (tp->t_flags & TF_NEEDSYN)) {
2404 if (tp->t_state == TCPS_SYN_RECEIVED &&
2405 IS_FASTOPEN(tp->t_flags)) {
2406 tp->snd_wnd = tiwin;
2411 } else if (tp->t_flags & TF_ACKNOW)
2420 switch (tp->t_state) {
2423 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2424 * ESTABLISHED state and continue processing.
2425 * The ACK was checked above.
2427 case TCPS_SYN_RECEIVED:
2429 TCPSTAT_INC(tcps_connects);
2431 /* Do window scaling? */
2432 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2433 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2434 tp->rcv_scale = tp->request_r_scale;
2435 tp->snd_wnd = tiwin;
2439 * SYN-RECEIVED -> ESTABLISHED
2440 * SYN-RECEIVED* -> FIN-WAIT-1
2442 tp->t_starttime = ticks;
2443 if (tp->t_flags & TF_NEEDFIN) {
2444 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2445 tp->t_flags &= ~TF_NEEDFIN;
2447 tcp_state_change(tp, TCPS_ESTABLISHED);
2448 TCP_PROBE5(accept__established, NULL, tp,
2451 if (tp->t_tfo_pending) {
2452 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2453 tp->t_tfo_pending = NULL;
2456 * Account for the ACK of our SYN prior to
2457 * regular ACK processing below.
2462 * TFO connections call cc_conn_init() during SYN
2463 * processing. Calling it again here for such
2464 * connections is not harmless as it would undo the
2465 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2468 if (!IS_FASTOPEN(tp->t_flags))
2471 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2474 * If segment contains data or ACK, will call tcp_reass()
2475 * later; if not, do so now to pass queued data to user.
2477 if (tlen == 0 && (thflags & TH_FIN) == 0)
2478 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2480 tp->snd_wl1 = th->th_seq - 1;
2484 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2485 * ACKs. If the ack is in the range
2486 * tp->snd_una < th->th_ack <= tp->snd_max
2487 * then advance tp->snd_una to th->th_ack and drop
2488 * data from the retransmission queue. If this ACK reflects
2489 * more up to date window information we update our window information.
2491 case TCPS_ESTABLISHED:
2492 case TCPS_FIN_WAIT_1:
2493 case TCPS_FIN_WAIT_2:
2494 case TCPS_CLOSE_WAIT:
2497 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2498 TCPSTAT_INC(tcps_rcvacktoomuch);
2501 if ((tp->t_flags & TF_SACK_PERMIT) &&
2502 ((to.to_flags & TOF_SACK) ||
2503 !TAILQ_EMPTY(&tp->snd_holes)))
2504 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2507 * Reset the value so that previous (valid) value
2508 * from the last ack with SACK doesn't get used.
2510 tp->sackhint.sacked_bytes = 0;
2513 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2514 hhook_run_tcp_est_in(tp, th, &to);
2517 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2520 maxseg = tcp_maxseg(tp);
2522 (tiwin == tp->snd_wnd ||
2523 (tp->t_flags & TF_SACK_PERMIT))) {
2525 * If this is the first time we've seen a
2526 * FIN from the remote, this is not a
2527 * duplicate and it needs to be processed
2528 * normally. This happens during a
2529 * simultaneous close.
2531 if ((thflags & TH_FIN) &&
2532 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2536 TCPSTAT_INC(tcps_rcvdupack);
2538 * If we have outstanding data (other than
2539 * a window probe), this is a completely
2540 * duplicate ack (ie, window info didn't
2541 * change and FIN isn't set),
2542 * the ack is the biggest we've
2543 * seen and we've seen exactly our rexmt
2544 * threshold of them, assume a packet
2545 * has been dropped and retransmit it.
2546 * Kludge snd_nxt & the congestion
2547 * window so we send only this one
2550 * We know we're losing at the current
2551 * window size so do congestion avoidance
2552 * (set ssthresh to half the current window
2553 * and pull our congestion window back to
2554 * the new ssthresh).
2556 * Dup acks mean that packets have left the
2557 * network (they're now cached at the receiver)
2558 * so bump cwnd by the amount in the receiver
2559 * to keep a constant cwnd packets in the
2562 * When using TCP ECN, notify the peer that
2563 * we reduced the cwnd.
2566 * Following 2 kinds of acks should not affect
2569 * 2) Acks with SACK but without any new SACK
2570 * information in them. These could result from
2571 * any anomaly in the network like a switch
2572 * duplicating packets or a possible DoS attack.
2574 if (th->th_ack != tp->snd_una ||
2575 ((tp->t_flags & TF_SACK_PERMIT) &&
2578 else if (!tcp_timer_active(tp, TT_REXMT))
2580 else if (++tp->t_dupacks > tcprexmtthresh ||
2581 IN_FASTRECOVERY(tp->t_flags)) {
2582 cc_ack_received(tp, th, nsegs,
2584 if ((tp->t_flags & TF_SACK_PERMIT) &&
2585 IN_FASTRECOVERY(tp->t_flags)) {
2589 * Compute the amount of data in flight first.
2590 * We can inject new data into the pipe iff
2591 * we have less than 1/2 the original window's
2592 * worth of data in flight.
2594 if (V_tcp_do_rfc6675_pipe)
2595 awnd = tcp_compute_pipe(tp);
2597 awnd = (tp->snd_nxt - tp->snd_fack) +
2598 tp->sackhint.sack_bytes_rexmit;
2600 if (awnd < tp->snd_ssthresh) {
2601 tp->snd_cwnd += maxseg;
2602 if (tp->snd_cwnd > tp->snd_ssthresh)
2603 tp->snd_cwnd = tp->snd_ssthresh;
2606 tp->snd_cwnd += maxseg;
2607 (void) tp->t_fb->tfb_tcp_output(tp);
2609 } else if (tp->t_dupacks == tcprexmtthresh) {
2610 tcp_seq onxt = tp->snd_nxt;
2613 * If we're doing sack, check to
2614 * see if we're already in sack
2615 * recovery. If we're not doing sack,
2616 * check to see if we're in newreno
2619 if (tp->t_flags & TF_SACK_PERMIT) {
2620 if (IN_FASTRECOVERY(tp->t_flags)) {
2625 if (SEQ_LEQ(th->th_ack,
2631 /* Congestion signal before ack. */
2632 cc_cong_signal(tp, th, CC_NDUPACK);
2633 cc_ack_received(tp, th, nsegs,
2635 tcp_timer_activate(tp, TT_REXMT, 0);
2637 if (tp->t_flags & TF_SACK_PERMIT) {
2639 tcps_sack_recovery_episode);
2640 tp->sack_newdata = tp->snd_nxt;
2641 tp->snd_cwnd = maxseg;
2642 (void) tp->t_fb->tfb_tcp_output(tp);
2645 tp->snd_nxt = th->th_ack;
2646 tp->snd_cwnd = maxseg;
2647 (void) tp->t_fb->tfb_tcp_output(tp);
2648 KASSERT(tp->snd_limited <= 2,
2649 ("%s: tp->snd_limited too big",
2651 tp->snd_cwnd = tp->snd_ssthresh +
2653 (tp->t_dupacks - tp->snd_limited);
2654 if (SEQ_GT(onxt, tp->snd_nxt))
2657 } else if (V_tcp_do_rfc3042) {
2659 * Process first and second duplicate
2660 * ACKs. Each indicates a segment
2661 * leaving the network, creating room
2662 * for more. Make sure we can send a
2663 * packet on reception of each duplicate
2664 * ACK by increasing snd_cwnd by one
2665 * segment. Restore the original
2666 * snd_cwnd after packet transmission.
2668 cc_ack_received(tp, th, nsegs,
2670 uint32_t oldcwnd = tp->snd_cwnd;
2671 tcp_seq oldsndmax = tp->snd_max;
2675 KASSERT(tp->t_dupacks == 1 ||
2677 ("%s: dupacks not 1 or 2",
2679 if (tp->t_dupacks == 1)
2680 tp->snd_limited = 0;
2682 (tp->snd_nxt - tp->snd_una) +
2683 (tp->t_dupacks - tp->snd_limited) *
2686 * Only call tcp_output when there
2687 * is new data available to be sent.
2688 * Otherwise we would send pure ACKs.
2690 SOCKBUF_LOCK(&so->so_snd);
2691 avail = sbavail(&so->so_snd) -
2692 (tp->snd_nxt - tp->snd_una);
2693 SOCKBUF_UNLOCK(&so->so_snd);
2695 (void) tp->t_fb->tfb_tcp_output(tp);
2696 sent = tp->snd_max - oldsndmax;
2697 if (sent > maxseg) {
2698 KASSERT((tp->t_dupacks == 2 &&
2699 tp->snd_limited == 0) ||
2700 (sent == maxseg + 1 &&
2701 tp->t_flags & TF_SENTFIN),
2702 ("%s: sent too much",
2704 tp->snd_limited = 2;
2705 } else if (sent > 0)
2707 tp->snd_cwnd = oldcwnd;
2714 * This ack is advancing the left edge, reset the
2719 * If this ack also has new SACK info, increment the
2720 * counter as per rfc6675.
2722 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2726 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2727 ("%s: th_ack <= snd_una", __func__));
2730 * If the congestion window was inflated to account
2731 * for the other side's cached packets, retract it.
2733 if (IN_FASTRECOVERY(tp->t_flags)) {
2734 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2735 if (tp->t_flags & TF_SACK_PERMIT)
2736 tcp_sack_partialack(tp, th);
2738 tcp_newreno_partial_ack(tp, th);
2740 cc_post_recovery(tp, th);
2743 * If we reach this point, ACK is not a duplicate,
2744 * i.e., it ACKs something we sent.
2746 if (tp->t_flags & TF_NEEDSYN) {
2748 * T/TCP: Connection was half-synchronized, and our
2749 * SYN has been ACK'd (so connection is now fully
2750 * synchronized). Go to non-starred state,
2751 * increment snd_una for ACK of SYN, and check if
2752 * we can do window scaling.
2754 tp->t_flags &= ~TF_NEEDSYN;
2756 /* Do window scaling? */
2757 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2758 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2759 tp->rcv_scale = tp->request_r_scale;
2760 /* Send window already scaled. */
2765 INP_WLOCK_ASSERT(tp->t_inpcb);
2767 acked = BYTES_THIS_ACK(tp, th);
2768 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2769 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2770 tp->snd_una, th->th_ack, tp, m));
2771 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
2772 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2775 * If we just performed our first retransmit, and the ACK
2776 * arrives within our recovery window, then it was a mistake
2777 * to do the retransmit in the first place. Recover our
2778 * original cwnd and ssthresh, and proceed to transmit where
2781 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2782 (int)(ticks - tp->t_badrxtwin) < 0)
2783 cc_cong_signal(tp, th, CC_RTO_ERR);
2786 * If we have a timestamp reply, update smoothed
2787 * round trip time. If no timestamp is present but
2788 * transmit timer is running and timed sequence
2789 * number was acked, update smoothed round trip time.
2790 * Since we now have an rtt measurement, cancel the
2791 * timer backoff (cf., Phil Karn's retransmit alg.).
2792 * Recompute the initial retransmit timer.
2794 * Some boxes send broken timestamp replies
2795 * during the SYN+ACK phase, ignore
2796 * timestamps of 0 or we could calculate a
2797 * huge RTT and blow up the retransmit timer.
2799 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2802 t = tcp_ts_getticks() - to.to_tsecr;
2803 if (!tp->t_rttlow || tp->t_rttlow > t)
2805 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2806 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2807 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2808 tp->t_rttlow = ticks - tp->t_rtttime;
2809 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2813 * If all outstanding data is acked, stop retransmit
2814 * timer and remember to restart (more output or persist).
2815 * If there is more data to be acked, restart retransmit
2816 * timer, using current (possibly backed-off) value.
2818 if (th->th_ack == tp->snd_max) {
2819 tcp_timer_activate(tp, TT_REXMT, 0);
2821 } else if (!tcp_timer_active(tp, TT_PERSIST))
2822 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2825 * If no data (only SYN) was ACK'd,
2826 * skip rest of ACK processing.
2832 * Let the congestion control algorithm update congestion
2833 * control related information. This typically means increasing
2834 * the congestion window.
2836 cc_ack_received(tp, th, nsegs, CC_ACK);
2838 SOCKBUF_LOCK(&so->so_snd);
2839 if (acked > sbavail(&so->so_snd)) {
2840 if (tp->snd_wnd >= sbavail(&so->so_snd))
2841 tp->snd_wnd -= sbavail(&so->so_snd);
2844 mfree = sbcut_locked(&so->so_snd,
2845 (int)sbavail(&so->so_snd));
2848 mfree = sbcut_locked(&so->so_snd, acked);
2849 if (tp->snd_wnd >= (uint32_t) acked)
2850 tp->snd_wnd -= acked;
2855 /* NB: sowwakeup_locked() does an implicit unlock. */
2856 sowwakeup_locked(so);
2858 /* Detect una wraparound. */
2859 if (!IN_RECOVERY(tp->t_flags) &&
2860 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2861 SEQ_LEQ(th->th_ack, tp->snd_recover))
2862 tp->snd_recover = th->th_ack - 1;
2863 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2864 if (IN_RECOVERY(tp->t_flags) &&
2865 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2866 EXIT_RECOVERY(tp->t_flags);
2868 tp->snd_una = th->th_ack;
2869 if (tp->t_flags & TF_SACK_PERMIT) {
2870 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2871 tp->snd_recover = tp->snd_una;
2873 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2874 tp->snd_nxt = tp->snd_una;
2876 switch (tp->t_state) {
2879 * In FIN_WAIT_1 STATE in addition to the processing
2880 * for the ESTABLISHED state if our FIN is now acknowledged
2881 * then enter FIN_WAIT_2.
2883 case TCPS_FIN_WAIT_1:
2884 if (ourfinisacked) {
2886 * If we can't receive any more
2887 * data, then closing user can proceed.
2888 * Starting the timer is contrary to the
2889 * specification, but if we don't get a FIN
2890 * we'll hang forever.
2893 * we should release the tp also, and use a
2896 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2897 soisdisconnected(so);
2898 tcp_timer_activate(tp, TT_2MSL,
2899 (tcp_fast_finwait2_recycle ?
2900 tcp_finwait2_timeout :
2903 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2908 * In CLOSING STATE in addition to the processing for
2909 * the ESTABLISHED state if the ACK acknowledges our FIN
2910 * then enter the TIME-WAIT state, otherwise ignore
2914 if (ourfinisacked) {
2915 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2917 INP_INFO_RUNLOCK(&V_tcbinfo);
2924 * In LAST_ACK, we may still be waiting for data to drain
2925 * and/or to be acked, as well as for the ack of our FIN.
2926 * If our FIN is now acknowledged, delete the TCB,
2927 * enter the closed state and return.
2930 if (ourfinisacked) {
2931 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2940 INP_WLOCK_ASSERT(tp->t_inpcb);
2943 * Update window information.
2944 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2946 if ((thflags & TH_ACK) &&
2947 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2948 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2949 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2950 /* keep track of pure window updates */
2952 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2953 TCPSTAT_INC(tcps_rcvwinupd);
2954 tp->snd_wnd = tiwin;
2955 tp->snd_wl1 = th->th_seq;
2956 tp->snd_wl2 = th->th_ack;
2957 if (tp->snd_wnd > tp->max_sndwnd)
2958 tp->max_sndwnd = tp->snd_wnd;
2963 * Process segments with URG.
2965 if ((thflags & TH_URG) && th->th_urp &&
2966 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2968 * This is a kludge, but if we receive and accept
2969 * random urgent pointers, we'll crash in
2970 * soreceive. It's hard to imagine someone
2971 * actually wanting to send this much urgent data.
2973 SOCKBUF_LOCK(&so->so_rcv);
2974 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2975 th->th_urp = 0; /* XXX */
2976 thflags &= ~TH_URG; /* XXX */
2977 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2978 goto dodata; /* XXX */
2981 * If this segment advances the known urgent pointer,
2982 * then mark the data stream. This should not happen
2983 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2984 * a FIN has been received from the remote side.
2985 * In these states we ignore the URG.
2987 * According to RFC961 (Assigned Protocols),
2988 * the urgent pointer points to the last octet
2989 * of urgent data. We continue, however,
2990 * to consider it to indicate the first octet
2991 * of data past the urgent section as the original
2992 * spec states (in one of two places).
2994 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2995 tp->rcv_up = th->th_seq + th->th_urp;
2996 so->so_oobmark = sbavail(&so->so_rcv) +
2997 (tp->rcv_up - tp->rcv_nxt) - 1;
2998 if (so->so_oobmark == 0)
2999 so->so_rcv.sb_state |= SBS_RCVATMARK;
3001 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
3003 SOCKBUF_UNLOCK(&so->so_rcv);
3005 * Remove out of band data so doesn't get presented to user.
3006 * This can happen independent of advancing the URG pointer,
3007 * but if two URG's are pending at once, some out-of-band
3008 * data may creep in... ick.
3010 if (th->th_urp <= (uint32_t)tlen &&
3011 !(so->so_options & SO_OOBINLINE)) {
3012 /* hdr drop is delayed */
3013 tcp_pulloutofband(so, th, m, drop_hdrlen);
3017 * If no out of band data is expected,
3018 * pull receive urgent pointer along
3019 * with the receive window.
3021 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3022 tp->rcv_up = tp->rcv_nxt;
3025 INP_WLOCK_ASSERT(tp->t_inpcb);
3028 * Process the segment text, merging it into the TCP sequencing queue,
3029 * and arranging for acknowledgment of receipt if necessary.
3030 * This process logically involves adjusting tp->rcv_wnd as data
3031 * is presented to the user (this happens in tcp_usrreq.c,
3032 * case PRU_RCVD). If a FIN has already been received on this
3033 * connection then we just ignore the text.
3036 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3037 IS_FASTOPEN(tp->t_flags));
3039 #define tfo_syn (false)
3041 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
3042 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3043 tcp_seq save_start = th->th_seq;
3044 m_adj(m, drop_hdrlen); /* delayed header drop */
3046 * Insert segment which includes th into TCP reassembly queue
3047 * with control block tp. Set thflags to whether reassembly now
3048 * includes a segment with FIN. This handles the common case
3049 * inline (segment is the next to be received on an established
3050 * connection, and the queue is empty), avoiding linkage into
3051 * and removal from the queue and repetition of various
3053 * Set DELACK for segments received in order, but ack
3054 * immediately when segments are out of order (so
3055 * fast retransmit can work).
3057 if (th->th_seq == tp->rcv_nxt &&
3058 LIST_EMPTY(&tp->t_segq) &&
3059 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3061 if (DELAY_ACK(tp, tlen) || tfo_syn)
3062 tp->t_flags |= TF_DELACK;
3064 tp->t_flags |= TF_ACKNOW;
3065 tp->rcv_nxt += tlen;
3066 thflags = th->th_flags & TH_FIN;
3067 TCPSTAT_INC(tcps_rcvpack);
3068 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3069 SOCKBUF_LOCK(&so->so_rcv);
3070 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3073 sbappendstream_locked(&so->so_rcv, m, 0);
3074 /* NB: sorwakeup_locked() does an implicit unlock. */
3075 sorwakeup_locked(so);
3078 * XXX: Due to the header drop above "th" is
3079 * theoretically invalid by now. Fortunately
3080 * m_adj() doesn't actually frees any mbufs
3081 * when trimming from the head.
3083 thflags = tcp_reass(tp, th, &tlen, m);
3084 tp->t_flags |= TF_ACKNOW;
3086 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
3087 tcp_update_sack_list(tp, save_start, save_start + tlen);
3090 * Note the amount of data that peer has sent into
3091 * our window, in order to estimate the sender's
3095 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3096 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3098 len = so->so_rcv.sb_hiwat;
3106 * If FIN is received ACK the FIN and let the user know
3107 * that the connection is closing.
3109 if (thflags & TH_FIN) {
3110 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3113 * If connection is half-synchronized
3114 * (ie NEEDSYN flag on) then delay ACK,
3115 * so it may be piggybacked when SYN is sent.
3116 * Otherwise, since we received a FIN then no
3117 * more input can be expected, send ACK now.
3119 if (tp->t_flags & TF_NEEDSYN)
3120 tp->t_flags |= TF_DELACK;
3122 tp->t_flags |= TF_ACKNOW;
3125 switch (tp->t_state) {
3128 * In SYN_RECEIVED and ESTABLISHED STATES
3129 * enter the CLOSE_WAIT state.
3131 case TCPS_SYN_RECEIVED:
3132 tp->t_starttime = ticks;
3134 case TCPS_ESTABLISHED:
3135 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3139 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3140 * enter the CLOSING state.
3142 case TCPS_FIN_WAIT_1:
3143 tcp_state_change(tp, TCPS_CLOSING);
3147 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3148 * starting the time-wait timer, turning off the other
3151 case TCPS_FIN_WAIT_2:
3152 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3153 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
3154 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3158 INP_INFO_RUNLOCK(&V_tcbinfo);
3162 if (ti_locked == TI_RLOCKED)
3163 INP_INFO_RUNLOCK(&V_tcbinfo);
3164 ti_locked = TI_UNLOCKED;
3167 if (so->so_options & SO_DEBUG)
3168 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3171 TCP_PROBE3(debug__input, tp, th, m);
3174 * Return any desired output.
3176 if (needoutput || (tp->t_flags & TF_ACKNOW))
3177 (void) tp->t_fb->tfb_tcp_output(tp);
3180 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3181 __func__, ti_locked));
3182 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3183 INP_WLOCK_ASSERT(tp->t_inpcb);
3185 if (tp->t_flags & TF_DELACK) {
3186 tp->t_flags &= ~TF_DELACK;
3187 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3189 INP_WUNLOCK(tp->t_inpcb);
3194 * Generate an ACK dropping incoming segment if it occupies
3195 * sequence space, where the ACK reflects our state.
3197 * We can now skip the test for the RST flag since all
3198 * paths to this code happen after packets containing
3199 * RST have been dropped.
3201 * In the SYN-RECEIVED state, don't send an ACK unless the
3202 * segment we received passes the SYN-RECEIVED ACK test.
3203 * If it fails send a RST. This breaks the loop in the
3204 * "LAND" DoS attack, and also prevents an ACK storm
3205 * between two listening ports that have been sent forged
3206 * SYN segments, each with the source address of the other.
3208 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3209 (SEQ_GT(tp->snd_una, th->th_ack) ||
3210 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3211 rstreason = BANDLIM_RST_OPENPORT;
3215 if (so->so_options & SO_DEBUG)
3216 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3219 TCP_PROBE3(debug__input, tp, th, m);
3220 if (ti_locked == TI_RLOCKED)
3221 INP_INFO_RUNLOCK(&V_tcbinfo);
3222 ti_locked = TI_UNLOCKED;
3224 tp->t_flags |= TF_ACKNOW;
3225 (void) tp->t_fb->tfb_tcp_output(tp);
3226 INP_WUNLOCK(tp->t_inpcb);
3231 if (ti_locked == TI_RLOCKED)
3232 INP_INFO_RUNLOCK(&V_tcbinfo);
3233 ti_locked = TI_UNLOCKED;
3236 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3237 INP_WUNLOCK(tp->t_inpcb);
3239 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3243 if (ti_locked == TI_RLOCKED) {
3244 INP_INFO_RUNLOCK(&V_tcbinfo);
3245 ti_locked = TI_UNLOCKED;
3249 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3253 * Drop space held by incoming segment and return.
3256 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3257 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3260 TCP_PROBE3(debug__input, tp, th, m);
3262 INP_WUNLOCK(tp->t_inpcb);
3270 * Issue RST and make ACK acceptable to originator of segment.
3271 * The mbuf must still include the original packet header.
3275 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3276 int tlen, int rstreason)
3282 struct ip6_hdr *ip6;
3286 INP_WLOCK_ASSERT(tp->t_inpcb);
3289 /* Don't bother if destination was broadcast/multicast. */
3290 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3293 if (mtod(m, struct ip *)->ip_v == 6) {
3294 ip6 = mtod(m, struct ip6_hdr *);
3295 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3296 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3298 /* IPv6 anycast check is done at tcp6_input() */
3301 #if defined(INET) && defined(INET6)
3306 ip = mtod(m, struct ip *);
3307 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3308 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3309 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3310 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3315 /* Perform bandwidth limiting. */
3316 if (badport_bandlim(rstreason) < 0)
3319 /* tcp_respond consumes the mbuf chain. */
3320 if (th->th_flags & TH_ACK) {
3321 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3322 th->th_ack, TH_RST);
3324 if (th->th_flags & TH_SYN)
3326 if (th->th_flags & TH_FIN)
3328 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3329 (tcp_seq)0, TH_RST|TH_ACK);
3337 * Parse TCP options and place in tcpopt.
3340 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3345 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3347 if (opt == TCPOPT_EOL)
3349 if (opt == TCPOPT_NOP)
3355 if (optlen < 2 || optlen > cnt)
3360 if (optlen != TCPOLEN_MAXSEG)
3362 if (!(flags & TO_SYN))
3364 to->to_flags |= TOF_MSS;
3365 bcopy((char *)cp + 2,
3366 (char *)&to->to_mss, sizeof(to->to_mss));
3367 to->to_mss = ntohs(to->to_mss);
3370 if (optlen != TCPOLEN_WINDOW)
3372 if (!(flags & TO_SYN))
3374 to->to_flags |= TOF_SCALE;
3375 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3377 case TCPOPT_TIMESTAMP:
3378 if (optlen != TCPOLEN_TIMESTAMP)
3380 to->to_flags |= TOF_TS;
3381 bcopy((char *)cp + 2,
3382 (char *)&to->to_tsval, sizeof(to->to_tsval));
3383 to->to_tsval = ntohl(to->to_tsval);
3384 bcopy((char *)cp + 6,
3385 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3386 to->to_tsecr = ntohl(to->to_tsecr);
3388 case TCPOPT_SIGNATURE:
3390 * In order to reply to a host which has set the
3391 * TCP_SIGNATURE option in its initial SYN, we have
3392 * to record the fact that the option was observed
3393 * here for the syncache code to perform the correct
3396 if (optlen != TCPOLEN_SIGNATURE)
3398 to->to_flags |= TOF_SIGNATURE;
3399 to->to_signature = cp + 2;
3401 case TCPOPT_SACK_PERMITTED:
3402 if (optlen != TCPOLEN_SACK_PERMITTED)
3404 if (!(flags & TO_SYN))
3408 to->to_flags |= TOF_SACKPERM;
3411 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3415 to->to_flags |= TOF_SACK;
3416 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3417 to->to_sacks = cp + 2;
3418 TCPSTAT_INC(tcps_sack_rcv_blocks);
3421 case TCPOPT_FAST_OPEN:
3422 if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
3423 (optlen < TCPOLEN_FAST_OPEN_MIN) &&
3424 (optlen > TCPOLEN_FAST_OPEN_MAX))
3426 if (!(flags & TO_SYN))
3428 if (!V_tcp_fastopen_enabled)
3430 to->to_flags |= TOF_FASTOPEN;
3431 to->to_tfo_len = optlen - 2;
3432 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3442 * Pull out of band byte out of a segment so
3443 * it doesn't appear in the user's data queue.
3444 * It is still reflected in the segment length for
3445 * sequencing purposes.
3448 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3451 int cnt = off + th->th_urp - 1;
3454 if (m->m_len > cnt) {
3455 char *cp = mtod(m, caddr_t) + cnt;
3456 struct tcpcb *tp = sototcpcb(so);
3458 INP_WLOCK_ASSERT(tp->t_inpcb);
3461 tp->t_oobflags |= TCPOOB_HAVEDATA;
3462 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3464 if (m->m_flags & M_PKTHDR)
3473 panic("tcp_pulloutofband");
3477 * Collect new round-trip time estimate
3478 * and update averages and current timeout.
3481 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3485 INP_WLOCK_ASSERT(tp->t_inpcb);
3487 TCPSTAT_INC(tcps_rttupdated);
3489 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3491 * srtt is stored as fixed point with 5 bits after the
3492 * binary point (i.e., scaled by 8). The following magic
3493 * is equivalent to the smoothing algorithm in rfc793 with
3494 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3495 * point). Adjust rtt to origin 0.
3497 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3498 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3500 if ((tp->t_srtt += delta) <= 0)
3504 * We accumulate a smoothed rtt variance (actually, a
3505 * smoothed mean difference), then set the retransmit
3506 * timer to smoothed rtt + 4 times the smoothed variance.
3507 * rttvar is stored as fixed point with 4 bits after the
3508 * binary point (scaled by 16). The following is
3509 * equivalent to rfc793 smoothing with an alpha of .75
3510 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3511 * rfc793's wired-in beta.
3515 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3516 if ((tp->t_rttvar += delta) <= 0)
3518 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3519 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3522 * No rtt measurement yet - use the unsmoothed rtt.
3523 * Set the variance to half the rtt (so our first
3524 * retransmit happens at 3*rtt).
3526 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3527 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3528 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3534 * the retransmit should happen at rtt + 4 * rttvar.
3535 * Because of the way we do the smoothing, srtt and rttvar
3536 * will each average +1/2 tick of bias. When we compute
3537 * the retransmit timer, we want 1/2 tick of rounding and
3538 * 1 extra tick because of +-1/2 tick uncertainty in the
3539 * firing of the timer. The bias will give us exactly the
3540 * 1.5 tick we need. But, because the bias is
3541 * statistical, we have to test that we don't drop below
3542 * the minimum feasible timer (which is 2 ticks).
3544 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3545 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3548 * We received an ack for a packet that wasn't retransmitted;
3549 * it is probably safe to discard any error indications we've
3550 * received recently. This isn't quite right, but close enough
3551 * for now (a route might have failed after we sent a segment,
3552 * and the return path might not be symmetrical).
3554 tp->t_softerror = 0;
3558 * Determine a reasonable value for maxseg size.
3559 * If the route is known, check route for mtu.
3560 * If none, use an mss that can be handled on the outgoing interface
3561 * without forcing IP to fragment. If no route is found, route has no mtu,
3562 * or the destination isn't local, use a default, hopefully conservative
3563 * size (usually 512 or the default IP max size, but no more than the mtu
3564 * of the interface), as we can't discover anything about intervening
3565 * gateways or networks. We also initialize the congestion/slow start
3566 * window to be a single segment if the destination isn't local.
3567 * While looking at the routing entry, we also initialize other path-dependent
3568 * parameters from pre-set or cached values in the routing entry.
3570 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3571 * IP options, e.g. IPSEC data, since length of this data may vary, and
3572 * thus it is calculated for every segment separately in tcp_output().
3574 * NOTE that this routine is only called when we process an incoming
3575 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3576 * settings are handled in tcp_mssopt().
3579 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3580 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3583 uint32_t maxmtu = 0;
3584 struct inpcb *inp = tp->t_inpcb;
3585 struct hc_metrics_lite metrics;
3587 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3588 size_t min_protoh = isipv6 ?
3589 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3590 sizeof (struct tcpiphdr);
3592 const size_t min_protoh = sizeof(struct tcpiphdr);
3595 INP_WLOCK_ASSERT(tp->t_inpcb);
3597 if (mtuoffer != -1) {
3598 KASSERT(offer == -1, ("%s: conflict", __func__));
3599 offer = mtuoffer - min_protoh;
3605 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3606 tp->t_maxseg = V_tcp_v6mssdflt;
3609 #if defined(INET) && defined(INET6)
3614 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3615 tp->t_maxseg = V_tcp_mssdflt;
3620 * No route to sender, stay with default mss and return.
3624 * In case we return early we need to initialize metrics
3625 * to a defined state as tcp_hc_get() would do for us
3626 * if there was no cache hit.
3628 if (metricptr != NULL)
3629 bzero(metricptr, sizeof(struct hc_metrics_lite));
3633 /* What have we got? */
3637 * Offer == 0 means that there was no MSS on the SYN
3638 * segment, in this case we use tcp_mssdflt as
3639 * already assigned to t_maxseg above.
3641 offer = tp->t_maxseg;
3646 * Offer == -1 means that we didn't receive SYN yet.
3652 * Prevent DoS attack with too small MSS. Round up
3653 * to at least minmss.
3655 offer = max(offer, V_tcp_minmss);
3659 * rmx information is now retrieved from tcp_hostcache.
3661 tcp_hc_get(&inp->inp_inc, &metrics);
3662 if (metricptr != NULL)
3663 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3666 * If there's a discovered mtu in tcp hostcache, use it.
3667 * Else, use the link mtu.
3669 if (metrics.rmx_mtu)
3670 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3674 mss = maxmtu - min_protoh;
3675 if (!V_path_mtu_discovery &&
3676 !in6_localaddr(&inp->in6p_faddr))
3677 mss = min(mss, V_tcp_v6mssdflt);
3680 #if defined(INET) && defined(INET6)
3685 mss = maxmtu - min_protoh;
3686 if (!V_path_mtu_discovery &&
3687 !in_localaddr(inp->inp_faddr))
3688 mss = min(mss, V_tcp_mssdflt);
3692 * XXX - The above conditional (mss = maxmtu - min_protoh)
3693 * probably violates the TCP spec.
3694 * The problem is that, since we don't know the
3695 * other end's MSS, we are supposed to use a conservative
3696 * default. But, if we do that, then MTU discovery will
3697 * never actually take place, because the conservative
3698 * default is much less than the MTUs typically seen
3699 * on the Internet today. For the moment, we'll sweep
3700 * this under the carpet.
3702 * The conservative default might not actually be a problem
3703 * if the only case this occurs is when sending an initial
3704 * SYN with options and data to a host we've never talked
3705 * to before. Then, they will reply with an MSS value which
3706 * will get recorded and the new parameters should get
3707 * recomputed. For Further Study.
3710 mss = min(mss, offer);
3713 * Sanity check: make sure that maxseg will be large
3714 * enough to allow some data on segments even if the
3715 * all the option space is used (40bytes). Otherwise
3716 * funny things may happen in tcp_output.
3718 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3726 tcp_mss(struct tcpcb *tp, int offer)
3732 struct hc_metrics_lite metrics;
3733 struct tcp_ifcap cap;
3735 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3737 bzero(&cap, sizeof(cap));
3738 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3744 * If there's a pipesize, change the socket buffer to that size,
3745 * don't change if sb_hiwat is different than default (then it
3746 * has been changed on purpose with setsockopt).
3747 * Make the socket buffers an integral number of mss units;
3748 * if the mss is larger than the socket buffer, decrease the mss.
3750 so = inp->inp_socket;
3751 SOCKBUF_LOCK(&so->so_snd);
3752 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3753 bufsize = metrics.rmx_sendpipe;
3755 bufsize = so->so_snd.sb_hiwat;
3759 bufsize = roundup(bufsize, mss);
3760 if (bufsize > sb_max)
3762 if (bufsize > so->so_snd.sb_hiwat)
3763 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3765 SOCKBUF_UNLOCK(&so->so_snd);
3767 * Sanity check: make sure that maxseg will be large
3768 * enough to allow some data on segments even if the
3769 * all the option space is used (40bytes). Otherwise
3770 * funny things may happen in tcp_output.
3772 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3774 tp->t_maxseg = max(mss, 64);
3776 SOCKBUF_LOCK(&so->so_rcv);
3777 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3778 bufsize = metrics.rmx_recvpipe;
3780 bufsize = so->so_rcv.sb_hiwat;
3781 if (bufsize > mss) {
3782 bufsize = roundup(bufsize, mss);
3783 if (bufsize > sb_max)
3785 if (bufsize > so->so_rcv.sb_hiwat)
3786 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3788 SOCKBUF_UNLOCK(&so->so_rcv);
3790 /* Check the interface for TSO capabilities. */
3791 if (cap.ifcap & CSUM_TSO) {
3792 tp->t_flags |= TF_TSO;
3793 tp->t_tsomax = cap.tsomax;
3794 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3795 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3800 * Determine the MSS option to send on an outgoing SYN.
3803 tcp_mssopt(struct in_conninfo *inc)
3806 uint32_t thcmtu = 0;
3807 uint32_t maxmtu = 0;
3810 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3813 if (inc->inc_flags & INC_ISIPV6) {
3814 mss = V_tcp_v6mssdflt;
3815 maxmtu = tcp_maxmtu6(inc, NULL);
3816 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3819 #if defined(INET) && defined(INET6)
3824 mss = V_tcp_mssdflt;
3825 maxmtu = tcp_maxmtu(inc, NULL);
3826 min_protoh = sizeof(struct tcpiphdr);
3829 #if defined(INET6) || defined(INET)
3830 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3833 if (maxmtu && thcmtu)
3834 mss = min(maxmtu, thcmtu) - min_protoh;
3835 else if (maxmtu || thcmtu)
3836 mss = max(maxmtu, thcmtu) - min_protoh;
3843 * On a partial ack arrives, force the retransmission of the
3844 * next unacknowledged segment. Do not clear tp->t_dupacks.
3845 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3849 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3851 tcp_seq onxt = tp->snd_nxt;
3852 uint32_t ocwnd = tp->snd_cwnd;
3853 u_int maxseg = tcp_maxseg(tp);
3855 INP_WLOCK_ASSERT(tp->t_inpcb);
3857 tcp_timer_activate(tp, TT_REXMT, 0);
3859 tp->snd_nxt = th->th_ack;
3861 * Set snd_cwnd to one segment beyond acknowledged offset.
3862 * (tp->snd_una has not yet been updated when this function is called.)
3864 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3865 tp->t_flags |= TF_ACKNOW;
3866 (void) tp->t_fb->tfb_tcp_output(tp);
3867 tp->snd_cwnd = ocwnd;
3868 if (SEQ_GT(onxt, tp->snd_nxt))
3871 * Partial window deflation. Relies on fact that tp->snd_una
3874 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3875 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3878 tp->snd_cwnd += maxseg;
3882 tcp_compute_pipe(struct tcpcb *tp)
3884 return (tp->snd_max - tp->snd_una +
3885 tp->sackhint.sack_bytes_rexmit -
3886 tp->sackhint.sacked_bytes);