2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2007-2008,2010
5 * Swinburne University of Technology, Melbourne, Australia.
6 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
7 * Copyright (c) 2010 The FreeBSD Foundation
8 * Copyright (c) 2010-2011 Juniper Networks, Inc.
11 * Portions of this software were developed at the Centre for Advanced Internet
12 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
13 * James Healy and David Hayes, made possible in part by a grant from the Cisco
14 * University Research Program Fund at Community Foundation Silicon Valley.
16 * Portions of this software were developed at the Centre for Advanced
17 * Internet Architectures, Swinburne University of Technology, Melbourne,
18 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
20 * Portions of this software were developed by Robert N. M. Watson under
21 * contract to Juniper Networks, Inc.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
53 #include "opt_ipfw.h" /* for ipfw_fwd */
55 #include "opt_inet6.h"
56 #include "opt_ipsec.h"
57 #include "opt_tcpdebug.h"
59 #include <sys/param.h>
60 #include <sys/kernel.h>
61 #include <sys/hhook.h>
62 #include <sys/malloc.h>
64 #include <sys/proc.h> /* for proc0 declaration */
65 #include <sys/protosw.h>
67 #include <sys/signalvar.h>
68 #include <sys/socket.h>
69 #include <sys/socketvar.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/systm.h>
74 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
79 #include <net/if_var.h>
80 #include <net/route.h>
83 #define TCPSTATES /* for logging */
85 #include <netinet/in.h>
86 #include <netinet/in_kdtrace.h>
87 #include <netinet/in_pcb.h>
88 #include <netinet/in_systm.h>
89 #include <netinet/ip.h>
90 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
91 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
92 #include <netinet/ip_var.h>
93 #include <netinet/ip_options.h>
94 #include <netinet/ip6.h>
95 #include <netinet/icmp6.h>
96 #include <netinet6/in6_pcb.h>
97 #include <netinet6/in6_var.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/nd6.h>
101 #include <netinet/tcp_fastopen.h>
103 #include <netinet/tcp.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
108 #include <netinet6/tcp6_var.h>
109 #include <netinet/tcpip.h>
110 #include <netinet/cc/cc.h>
112 #include <netinet/tcp_pcap.h>
114 #include <netinet/tcp_syncache.h>
116 #include <netinet/tcp_debug.h>
117 #endif /* TCPDEBUG */
119 #include <netinet/tcp_offload.h>
123 #include <netipsec/ipsec.h>
124 #include <netipsec/ipsec6.h>
127 #include <machine/in_cksum.h>
129 #include <security/mac/mac_framework.h>
131 const int tcprexmtthresh = 3;
133 int tcp_log_in_vain = 0;
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
136 "Log all incoming TCP segments to closed ports");
138 VNET_DEFINE(int, blackhole) = 0;
139 #define V_blackhole VNET(blackhole)
140 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
141 &VNET_NAME(blackhole), 0,
142 "Do not send RST on segments to closed ports");
144 VNET_DEFINE(int, tcp_delack_enabled) = 1;
145 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
146 &VNET_NAME(tcp_delack_enabled), 0,
147 "Delay ACK to try and piggyback it onto a data packet");
149 VNET_DEFINE(int, drop_synfin) = 0;
150 #define V_drop_synfin VNET(drop_synfin)
151 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
152 &VNET_NAME(drop_synfin), 0,
153 "Drop TCP packets with SYN+FIN set");
155 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
157 &VNET_NAME(tcp_do_rfc6675_pipe), 0,
158 "Use calculated pipe/in-flight bytes per RFC 6675");
160 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
161 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
162 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
163 &VNET_NAME(tcp_do_rfc3042), 0,
164 "Enable RFC 3042 (Limited Transmit)");
166 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
167 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
168 &VNET_NAME(tcp_do_rfc3390), 0,
169 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
171 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
172 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
173 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
174 "Slow-start flight size (initial congestion window) in number of segments");
176 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
177 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
178 &VNET_NAME(tcp_do_rfc3465), 0,
179 "Enable RFC 3465 (Appropriate Byte Counting)");
181 VNET_DEFINE(int, tcp_abc_l_var) = 2;
182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
183 &VNET_NAME(tcp_abc_l_var), 2,
184 "Cap the max cwnd increment during slow-start to this number of segments");
186 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
188 VNET_DEFINE(int, tcp_do_ecn) = 0;
189 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
190 &VNET_NAME(tcp_do_ecn), 0,
193 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
194 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
195 &VNET_NAME(tcp_ecn_maxretries), 0,
196 "Max retries before giving up on ECN");
198 VNET_DEFINE(int, tcp_insecure_syn) = 0;
199 #define V_tcp_insecure_syn VNET(tcp_insecure_syn)
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
201 &VNET_NAME(tcp_insecure_syn), 0,
202 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
204 VNET_DEFINE(int, tcp_insecure_rst) = 0;
205 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
207 &VNET_NAME(tcp_insecure_rst), 0,
208 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
210 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
211 #define V_tcp_recvspace VNET(tcp_recvspace)
212 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
213 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
215 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
216 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
217 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
218 &VNET_NAME(tcp_do_autorcvbuf), 0,
219 "Enable automatic receive buffer sizing");
221 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
222 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
223 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
224 &VNET_NAME(tcp_autorcvbuf_inc), 0,
225 "Incrementor step size of automatic receive buffer");
227 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
228 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
229 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
230 &VNET_NAME(tcp_autorcvbuf_max), 0,
231 "Max size of automatic receive buffer");
233 VNET_DEFINE(struct inpcbhead, tcb);
234 #define tcb6 tcb /* for KAME src sync over BSD*'s */
235 VNET_DEFINE(struct inpcbinfo, tcbinfo);
238 * TCP statistics are stored in an "array" of counter(9)s.
240 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
241 VNET_PCPUSTAT_SYSINIT(tcpstat);
242 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
243 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
246 VNET_PCPUSTAT_SYSUNINIT(tcpstat);
249 * Kernel module interface for updating tcpstat. The argument is an index
250 * into tcpstat treated as an array.
253 kmod_tcpstat_inc(int statnum)
256 counter_u64_add(VNET(tcpstat)[statnum], 1);
260 * Wrapper for the TCP established input helper hook.
263 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
265 struct tcp_hhook_data hhook_data;
267 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
272 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
278 * CC wrapper hook functions
281 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
283 INP_WLOCK_ASSERT(tp->t_inpcb);
285 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
286 if (tp->snd_cwnd <= tp->snd_wnd)
287 tp->ccv->flags |= CCF_CWND_LIMITED;
289 tp->ccv->flags &= ~CCF_CWND_LIMITED;
291 if (type == CC_ACK) {
292 if (tp->snd_cwnd > tp->snd_ssthresh) {
293 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
294 V_tcp_abc_l_var * tcp_maxseg(tp));
295 if (tp->t_bytes_acked >= tp->snd_cwnd) {
296 tp->t_bytes_acked -= tp->snd_cwnd;
297 tp->ccv->flags |= CCF_ABC_SENTAWND;
300 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
301 tp->t_bytes_acked = 0;
305 if (CC_ALGO(tp)->ack_received != NULL) {
306 /* XXXLAS: Find a way to live without this */
307 tp->ccv->curack = th->th_ack;
308 CC_ALGO(tp)->ack_received(tp->ccv, type);
313 cc_conn_init(struct tcpcb *tp)
315 struct hc_metrics_lite metrics;
316 struct inpcb *inp = tp->t_inpcb;
320 INP_WLOCK_ASSERT(tp->t_inpcb);
322 tcp_hc_get(&inp->inp_inc, &metrics);
323 maxseg = tcp_maxseg(tp);
325 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
327 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
328 TCPSTAT_INC(tcps_usedrtt);
329 if (metrics.rmx_rttvar) {
330 tp->t_rttvar = metrics.rmx_rttvar;
331 TCPSTAT_INC(tcps_usedrttvar);
333 /* default variation is +- 1 rtt */
335 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
337 TCPT_RANGESET(tp->t_rxtcur,
338 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
339 tp->t_rttmin, TCPTV_REXMTMAX);
341 if (metrics.rmx_ssthresh) {
343 * There's some sort of gateway or interface
344 * buffer limit on the path. Use this to set
345 * the slow start threshhold, but set the
346 * threshold to no less than 2*mss.
348 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
349 TCPSTAT_INC(tcps_usedssthresh);
353 * Set the initial slow-start flight size.
355 * RFC5681 Section 3.1 specifies the default conservative values.
356 * RFC3390 specifies slightly more aggressive values.
357 * RFC6928 increases it to ten segments.
358 * Support for user specified value for initial flight size.
360 * If a SYN or SYN/ACK was lost and retransmitted, we have to
361 * reduce the initial CWND to one segment as congestion is likely
362 * requiring us to be cautious.
364 if (tp->snd_cwnd == 1)
365 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
366 else if (V_tcp_initcwnd_segments)
367 tp->snd_cwnd = min(V_tcp_initcwnd_segments * maxseg,
368 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
369 else if (V_tcp_do_rfc3390)
370 tp->snd_cwnd = min(4 * maxseg, max(2 * maxseg, 4380));
372 /* Per RFC5681 Section 3.1 */
374 tp->snd_cwnd = 2 * maxseg;
375 else if (maxseg > 1095)
376 tp->snd_cwnd = 3 * maxseg;
378 tp->snd_cwnd = 4 * maxseg;
381 if (CC_ALGO(tp)->conn_init != NULL)
382 CC_ALGO(tp)->conn_init(tp->ccv);
386 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
390 INP_WLOCK_ASSERT(tp->t_inpcb);
394 if (!IN_FASTRECOVERY(tp->t_flags)) {
395 tp->snd_recover = tp->snd_max;
396 if (tp->t_flags & TF_ECN_PERMIT)
397 tp->t_flags |= TF_ECN_SND_CWR;
401 if (!IN_CONGRECOVERY(tp->t_flags)) {
402 TCPSTAT_INC(tcps_ecn_rcwnd);
403 tp->snd_recover = tp->snd_max;
404 if (tp->t_flags & TF_ECN_PERMIT)
405 tp->t_flags |= TF_ECN_SND_CWR;
409 maxseg = tcp_maxseg(tp);
411 tp->t_bytes_acked = 0;
412 EXIT_RECOVERY(tp->t_flags);
413 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
415 tp->snd_cwnd = maxseg;
418 TCPSTAT_INC(tcps_sndrexmitbad);
419 /* RTO was unnecessary, so reset everything. */
420 tp->snd_cwnd = tp->snd_cwnd_prev;
421 tp->snd_ssthresh = tp->snd_ssthresh_prev;
422 tp->snd_recover = tp->snd_recover_prev;
423 if (tp->t_flags & TF_WASFRECOVERY)
424 ENTER_FASTRECOVERY(tp->t_flags);
425 if (tp->t_flags & TF_WASCRECOVERY)
426 ENTER_CONGRECOVERY(tp->t_flags);
427 tp->snd_nxt = tp->snd_max;
428 tp->t_flags &= ~TF_PREVVALID;
433 if (CC_ALGO(tp)->cong_signal != NULL) {
435 tp->ccv->curack = th->th_ack;
436 CC_ALGO(tp)->cong_signal(tp->ccv, type);
441 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
443 INP_WLOCK_ASSERT(tp->t_inpcb);
445 /* XXXLAS: KASSERT that we're in recovery? */
447 if (CC_ALGO(tp)->post_recovery != NULL) {
448 tp->ccv->curack = th->th_ack;
449 CC_ALGO(tp)->post_recovery(tp->ccv);
451 /* XXXLAS: EXIT_RECOVERY ? */
452 tp->t_bytes_acked = 0;
457 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
458 struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
462 tcp_fields_to_net(th);
463 ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
464 tcp_fields_to_host(th);
470 * Indicate whether this ack should be delayed. We can delay the ack if
471 * following conditions are met:
472 * - There is no delayed ack timer in progress.
473 * - Our last ack wasn't a 0-sized window. We never want to delay
474 * the ack that opens up a 0-sized window.
475 * - LRO wasn't used for this segment. We make sure by checking that the
476 * segment size is not larger than the MSS.
478 #define DELAY_ACK(tp, tlen) \
479 ((!tcp_timer_active(tp, TT_DELACK) && \
480 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
481 (tlen <= tp->t_maxseg) && \
482 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
485 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
487 INP_WLOCK_ASSERT(tp->t_inpcb);
489 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
490 switch (iptos & IPTOS_ECN_MASK) {
492 tp->ccv->flags |= CCF_IPHDR_CE;
495 tp->ccv->flags &= ~CCF_IPHDR_CE;
498 tp->ccv->flags &= ~CCF_IPHDR_CE;
502 if (th->th_flags & TH_CWR)
503 tp->ccv->flags |= CCF_TCPHDR_CWR;
505 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
507 if (tp->t_flags & TF_DELACK)
508 tp->ccv->flags |= CCF_DELACK;
510 tp->ccv->flags &= ~CCF_DELACK;
512 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
514 if (tp->ccv->flags & CCF_ACKNOW)
515 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
520 * TCP input handling is split into multiple parts:
521 * tcp6_input is a thin wrapper around tcp_input for the extended
522 * ip6_protox[] call format in ip6_input
523 * tcp_input handles primary segment validation, inpcb lookup and
524 * SYN processing on listen sockets
525 * tcp_do_segment processes the ACK and text of the segment for
526 * establishing, established and closing connections
530 tcp6_input(struct mbuf **mp, int *offp, int proto)
532 struct mbuf *m = *mp;
533 struct in6_ifaddr *ia6;
536 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
539 * draft-itojun-ipv6-tcp-to-anycast
540 * better place to put this in?
542 ip6 = mtod(m, struct ip6_hdr *);
543 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
544 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
547 ifa_free(&ia6->ia_ifa);
548 ip6 = mtod(m, struct ip6_hdr *);
549 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
550 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
551 return (IPPROTO_DONE);
554 ifa_free(&ia6->ia_ifa);
556 return (tcp_input(mp, offp, proto));
561 tcp_input(struct mbuf **mp, int *offp, int proto)
563 struct mbuf *m = *mp;
564 struct tcphdr *th = NULL;
565 struct ip *ip = NULL;
566 struct inpcb *inp = NULL;
567 struct tcpcb *tp = NULL;
568 struct socket *so = NULL;
578 int rstreason = 0; /* For badport_bandlim accounting purposes */
580 uint8_t sig_checked = 0;
583 struct m_tag *fwd_tag = NULL;
585 struct ip6_hdr *ip6 = NULL;
588 const void *ip6 = NULL;
590 struct tcpopt to; /* options in this segment */
591 char *s = NULL; /* address and port logging */
595 * The size of tcp_saveipgen must be the size of the max ip header,
598 u_char tcp_saveipgen[IP6_HDR_LEN];
599 struct tcphdr tcp_savetcp;
604 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
611 TCPSTAT_INC(tcps_rcvtotal);
615 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
617 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
618 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
620 TCPSTAT_INC(tcps_rcvshort);
621 return (IPPROTO_DONE);
625 ip6 = mtod(m, struct ip6_hdr *);
626 th = (struct tcphdr *)((caddr_t)ip6 + off0);
627 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
628 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
629 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
630 th->th_sum = m->m_pkthdr.csum_data;
632 th->th_sum = in6_cksum_pseudo(ip6, tlen,
633 IPPROTO_TCP, m->m_pkthdr.csum_data);
634 th->th_sum ^= 0xffff;
636 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
638 TCPSTAT_INC(tcps_rcvbadsum);
643 * Be proactive about unspecified IPv6 address in source.
644 * As we use all-zero to indicate unbounded/unconnected pcb,
645 * unspecified IPv6 address can be used to confuse us.
647 * Note that packets with unspecified IPv6 destination is
648 * already dropped in ip6_input.
650 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
656 #if defined(INET) && defined(INET6)
662 * Get IP and TCP header together in first mbuf.
663 * Note: IP leaves IP header in first mbuf.
665 if (off0 > sizeof (struct ip)) {
667 off0 = sizeof(struct ip);
669 if (m->m_len < sizeof (struct tcpiphdr)) {
670 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
672 TCPSTAT_INC(tcps_rcvshort);
673 return (IPPROTO_DONE);
676 ip = mtod(m, struct ip *);
677 th = (struct tcphdr *)((caddr_t)ip + off0);
678 tlen = ntohs(ip->ip_len) - off0;
680 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
681 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
682 th->th_sum = m->m_pkthdr.csum_data;
684 th->th_sum = in_pseudo(ip->ip_src.s_addr,
686 htonl(m->m_pkthdr.csum_data + tlen +
688 th->th_sum ^= 0xffff;
690 struct ipovly *ipov = (struct ipovly *)ip;
693 * Checksum extended TCP header and data.
696 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
697 ipov->ih_len = htons(tlen);
698 th->th_sum = in_cksum(m, len);
699 /* Reset length for SDT probes. */
700 ip->ip_len = htons(tlen + off0);
704 TCPSTAT_INC(tcps_rcvbadsum);
707 /* Re-initialization for later version check */
708 ip->ip_v = IPVERSION;
714 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
716 #if defined(INET) && defined(INET6)
724 * Check that TCP offset makes sense,
725 * pull out TCP options and adjust length. XXX
727 off = th->th_off << 2;
728 if (off < sizeof (struct tcphdr) || off > tlen) {
729 TCPSTAT_INC(tcps_rcvbadoff);
732 tlen -= off; /* tlen is used instead of ti->ti_len */
733 if (off > sizeof (struct tcphdr)) {
736 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
737 ip6 = mtod(m, struct ip6_hdr *);
738 th = (struct tcphdr *)((caddr_t)ip6 + off0);
741 #if defined(INET) && defined(INET6)
746 if (m->m_len < sizeof(struct ip) + off) {
747 if ((m = m_pullup(m, sizeof (struct ip) + off))
749 TCPSTAT_INC(tcps_rcvshort);
750 return (IPPROTO_DONE);
752 ip = mtod(m, struct ip *);
753 th = (struct tcphdr *)((caddr_t)ip + off0);
757 optlen = off - sizeof (struct tcphdr);
758 optp = (u_char *)(th + 1);
760 thflags = th->th_flags;
763 * Convert TCP protocol specific fields to host format.
765 tcp_fields_to_host(th);
768 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
770 drop_hdrlen = off0 + off;
773 * Locate pcb for segment; if we're likely to add or remove a
774 * connection then first acquire pcbinfo lock. There are three cases
775 * where we might discover later we need a write lock despite the
776 * flags: ACKs moving a connection out of the syncache, ACKs for a
777 * connection in TIMEWAIT and SYNs not targeting a listening socket.
779 if ((thflags & (TH_FIN | TH_RST)) != 0) {
780 INP_INFO_RLOCK(&V_tcbinfo);
781 ti_locked = TI_RLOCKED;
783 ti_locked = TI_UNLOCKED;
786 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
790 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
792 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
795 #if defined(INET) && !defined(INET6)
796 (m->m_flags & M_IP_NEXTHOP)
799 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
803 if (ti_locked == TI_RLOCKED) {
804 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
806 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
810 if (isipv6 && fwd_tag != NULL) {
811 struct sockaddr_in6 *next_hop6;
813 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
815 * Transparently forwarded. Pretend to be the destination.
816 * Already got one like this?
818 inp = in6_pcblookup_mbuf(&V_tcbinfo,
819 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
820 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
823 * It's new. Try to find the ambushing socket.
824 * Because we've rewritten the destination address,
825 * any hardware-generated hash is ignored.
827 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
828 th->th_sport, &next_hop6->sin6_addr,
829 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
830 th->th_dport, INPLOOKUP_WILDCARD |
831 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
834 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
835 th->th_sport, &ip6->ip6_dst, th->th_dport,
836 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
837 m->m_pkthdr.rcvif, m);
840 #if defined(INET6) && defined(INET)
844 if (fwd_tag != NULL) {
845 struct sockaddr_in *next_hop;
847 next_hop = (struct sockaddr_in *)(fwd_tag+1);
849 * Transparently forwarded. Pretend to be the destination.
850 * already got one like this?
852 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
853 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
854 m->m_pkthdr.rcvif, m);
857 * It's new. Try to find the ambushing socket.
858 * Because we've rewritten the destination address,
859 * any hardware-generated hash is ignored.
861 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
862 th->th_sport, next_hop->sin_addr,
863 next_hop->sin_port ? ntohs(next_hop->sin_port) :
864 th->th_dport, INPLOOKUP_WILDCARD |
865 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
868 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
869 th->th_sport, ip->ip_dst, th->th_dport,
870 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
871 m->m_pkthdr.rcvif, m);
875 * If the INPCB does not exist then all data in the incoming
876 * segment is discarded and an appropriate RST is sent back.
877 * XXX MRT Send RST using which routing table?
881 * Log communication attempts to ports that are not
884 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
885 tcp_log_in_vain == 2) {
886 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
887 log(LOG_INFO, "%s; %s: Connection attempt "
888 "to closed port\n", s, __func__);
891 * When blackholing do not respond with a RST but
892 * completely ignore the segment and drop it.
894 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
898 rstreason = BANDLIM_RST_CLOSEDPORT;
901 INP_WLOCK_ASSERT(inp);
902 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
903 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
904 ((inp->inp_socket == NULL) ||
905 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
906 inp->inp_flowid = m->m_pkthdr.flowid;
907 inp->inp_flowtype = M_HASHTYPE_GET(m);
911 if (isipv6 && ipsec6_in_reject(m, inp)) {
915 if (ipsec4_in_reject(m, inp) != 0) {
921 * Check the minimum TTL for socket.
923 if (inp->inp_ip_minttl != 0) {
926 if (inp->inp_ip_minttl > ip6->ip6_hlim)
930 if (inp->inp_ip_minttl > ip->ip_ttl)
935 * A previous connection in TIMEWAIT state is supposed to catch stray
936 * or duplicate segments arriving late. If this segment was a
937 * legitimate new connection attempt, the old INPCB gets removed and
938 * we can try again to find a listening socket.
940 * At this point, due to earlier optimism, we may hold only an inpcb
941 * lock, and not the inpcbinfo write lock. If so, we need to try to
942 * acquire it, or if that fails, acquire a reference on the inpcb,
943 * drop all locks, acquire a global write lock, and then re-acquire
944 * the inpcb lock. We may at that point discover that another thread
945 * has tried to free the inpcb, in which case we need to loop back
946 * and try to find a new inpcb to deliver to.
948 * XXXRW: It may be time to rethink timewait locking.
951 if (inp->inp_flags & INP_TIMEWAIT) {
952 if (ti_locked == TI_UNLOCKED) {
953 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
956 INP_INFO_RLOCK(&V_tcbinfo);
957 ti_locked = TI_RLOCKED;
959 if (in_pcbrele_wlocked(inp)) {
964 ti_locked = TI_RLOCKED;
966 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
968 if (thflags & TH_SYN)
969 tcp_dooptions(&to, optp, optlen, TO_SYN);
971 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
973 if (tcp_twcheck(inp, &to, th, m, tlen))
975 INP_INFO_RUNLOCK(&V_tcbinfo);
976 return (IPPROTO_DONE);
979 * The TCPCB may no longer exist if the connection is winding
980 * down or it is in the CLOSED state. Either way we drop the
981 * segment and send an appropriate response.
984 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
985 rstreason = BANDLIM_RST_CLOSEDPORT;
990 if (tp->t_flags & TF_TOE) {
991 tcp_offload_input(tp, m);
992 m = NULL; /* consumed by the TOE driver */
998 * We've identified a valid inpcb, but it could be that we need an
999 * inpcbinfo write lock but don't hold it. In this case, attempt to
1000 * acquire using the same strategy as the TIMEWAIT case above. If we
1001 * relock, we have to jump back to 'relocked' as the connection might
1002 * now be in TIMEWAIT.
1005 if ((thflags & (TH_FIN | TH_RST)) != 0)
1006 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1008 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1009 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
1010 !(tp->t_flags & TF_FASTOPEN)))) {
1011 if (ti_locked == TI_UNLOCKED) {
1012 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
1015 INP_INFO_RLOCK(&V_tcbinfo);
1016 ti_locked = TI_RLOCKED;
1018 if (in_pcbrele_wlocked(inp)) {
1024 ti_locked = TI_RLOCKED;
1026 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1030 INP_WLOCK_ASSERT(inp);
1031 if (mac_inpcb_check_deliver(inp, m))
1034 so = inp->inp_socket;
1035 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1037 if (so->so_options & SO_DEBUG) {
1038 ostate = tp->t_state;
1041 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1044 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1047 #endif /* TCPDEBUG */
1049 * When the socket is accepting connections (the INPCB is in LISTEN
1050 * state) we look into the SYN cache if this is a new connection
1051 * attempt or the completion of a previous one.
1053 if (so->so_options & SO_ACCEPTCONN) {
1054 struct in_conninfo inc;
1056 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
1057 "tp not listening", __func__));
1058 bzero(&inc, sizeof(inc));
1061 inc.inc_flags |= INC_ISIPV6;
1062 inc.inc6_faddr = ip6->ip6_src;
1063 inc.inc6_laddr = ip6->ip6_dst;
1067 inc.inc_faddr = ip->ip_src;
1068 inc.inc_laddr = ip->ip_dst;
1070 inc.inc_fport = th->th_sport;
1071 inc.inc_lport = th->th_dport;
1072 inc.inc_fibnum = so->so_fibnum;
1075 * Check for an existing connection attempt in syncache if
1076 * the flag is only ACK. A successful lookup creates a new
1077 * socket appended to the listen queue in SYN_RECEIVED state.
1079 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1081 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1083 * Parse the TCP options here because
1084 * syncookies need access to the reflected
1087 tcp_dooptions(&to, optp, optlen, 0);
1089 * NB: syncache_expand() doesn't unlock
1090 * inp and tcpinfo locks.
1092 if (!syncache_expand(&inc, &to, th, &so, m)) {
1094 * No syncache entry or ACK was not
1095 * for our SYN/ACK. Send a RST.
1096 * NB: syncache did its own logging
1097 * of the failure cause.
1099 rstreason = BANDLIM_RST_OPENPORT;
1107 * We completed the 3-way handshake
1108 * but could not allocate a socket
1109 * either due to memory shortage,
1110 * listen queue length limits or
1111 * global socket limits. Send RST
1112 * or wait and have the remote end
1113 * retransmit the ACK for another
1116 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1117 log(LOG_DEBUG, "%s; %s: Listen socket: "
1118 "Socket allocation failed due to "
1119 "limits or memory shortage, %s\n",
1121 V_tcp_sc_rst_sock_fail ?
1122 "sending RST" : "try again");
1123 if (V_tcp_sc_rst_sock_fail) {
1124 rstreason = BANDLIM_UNLIMITED;
1130 * Socket is created in state SYN_RECEIVED.
1131 * Unlock the listen socket, lock the newly
1132 * created socket and update the tp variable.
1134 INP_WUNLOCK(inp); /* listen socket */
1135 inp = sotoinpcb(so);
1137 * New connection inpcb is already locked by
1138 * syncache_expand().
1140 INP_WLOCK_ASSERT(inp);
1141 tp = intotcpcb(inp);
1142 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1143 ("%s: ", __func__));
1144 #ifdef TCP_SIGNATURE
1145 if (sig_checked == 0) {
1146 tcp_dooptions(&to, optp, optlen,
1147 (thflags & TH_SYN) ? TO_SYN : 0);
1148 if (!tcp_signature_verify_input(m, off0, tlen,
1149 optlen, &to, th, tp->t_flags)) {
1152 * In SYN_SENT state if it receives an
1153 * RST, it is allowed for further
1156 if ((thflags & TH_RST) == 0 ||
1157 (tp->t_state == TCPS_SYN_SENT) == 0)
1165 * Process the segment and the data it
1166 * contains. tcp_do_segment() consumes
1167 * the mbuf chain and unlocks the inpcb.
1169 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1171 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1172 return (IPPROTO_DONE);
1175 * Segment flag validation for new connection attempts:
1177 * Our (SYN|ACK) response was rejected.
1178 * Check with syncache and remove entry to prevent
1181 * NB: syncache_chkrst does its own logging of failure
1184 if (thflags & TH_RST) {
1185 syncache_chkrst(&inc, th);
1189 * We can't do anything without SYN.
1191 if ((thflags & TH_SYN) == 0) {
1192 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1193 log(LOG_DEBUG, "%s; %s: Listen socket: "
1194 "SYN is missing, segment ignored\n",
1196 TCPSTAT_INC(tcps_badsyn);
1200 * (SYN|ACK) is bogus on a listen socket.
1202 if (thflags & TH_ACK) {
1203 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1204 log(LOG_DEBUG, "%s; %s: Listen socket: "
1205 "SYN|ACK invalid, segment rejected\n",
1207 syncache_badack(&inc); /* XXX: Not needed! */
1208 TCPSTAT_INC(tcps_badsyn);
1209 rstreason = BANDLIM_RST_OPENPORT;
1213 * If the drop_synfin option is enabled, drop all
1214 * segments with both the SYN and FIN bits set.
1215 * This prevents e.g. nmap from identifying the
1217 * XXX: Poor reasoning. nmap has other methods
1218 * and is constantly refining its stack detection
1220 * XXX: This is a violation of the TCP specification
1221 * and was used by RFC1644.
1223 if ((thflags & TH_FIN) && V_drop_synfin) {
1224 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1225 log(LOG_DEBUG, "%s; %s: Listen socket: "
1226 "SYN|FIN segment ignored (based on "
1227 "sysctl setting)\n", s, __func__);
1228 TCPSTAT_INC(tcps_badsyn);
1232 * Segment's flags are (SYN) or (SYN|FIN).
1234 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1235 * as they do not affect the state of the TCP FSM.
1236 * The data pointed to by TH_URG and th_urp is ignored.
1238 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1239 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1240 KASSERT(thflags & (TH_SYN),
1241 ("%s: Listen socket: TH_SYN not set", __func__));
1244 * If deprecated address is forbidden,
1245 * we do not accept SYN to deprecated interface
1246 * address to prevent any new inbound connection from
1247 * getting established.
1248 * When we do not accept SYN, we send a TCP RST,
1249 * with deprecated source address (instead of dropping
1250 * it). We compromise it as it is much better for peer
1251 * to send a RST, and RST will be the final packet
1254 * If we do not forbid deprecated addresses, we accept
1255 * the SYN packet. RFC2462 does not suggest dropping
1257 * If we decipher RFC2462 5.5.4, it says like this:
1258 * 1. use of deprecated addr with existing
1259 * communication is okay - "SHOULD continue to be
1261 * 2. use of it with new communication:
1262 * (2a) "SHOULD NOT be used if alternate address
1263 * with sufficient scope is available"
1264 * (2b) nothing mentioned otherwise.
1265 * Here we fall into (2b) case as we have no choice in
1266 * our source address selection - we must obey the peer.
1268 * The wording in RFC2462 is confusing, and there are
1269 * multiple description text for deprecated address
1270 * handling - worse, they are not exactly the same.
1271 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1273 if (isipv6 && !V_ip6_use_deprecated) {
1274 struct in6_ifaddr *ia6;
1276 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1278 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1279 ifa_free(&ia6->ia_ifa);
1280 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1281 log(LOG_DEBUG, "%s; %s: Listen socket: "
1282 "Connection attempt to deprecated "
1283 "IPv6 address rejected\n",
1285 rstreason = BANDLIM_RST_OPENPORT;
1289 ifa_free(&ia6->ia_ifa);
1293 * Basic sanity checks on incoming SYN requests:
1294 * Don't respond if the destination is a link layer
1295 * broadcast according to RFC1122 4.2.3.10, p. 104.
1296 * If it is from this socket it must be forged.
1297 * Don't respond if the source or destination is a
1298 * global or subnet broad- or multicast address.
1299 * Note that it is quite possible to receive unicast
1300 * link-layer packets with a broadcast IP address. Use
1301 * in_broadcast() to find them.
1303 if (m->m_flags & (M_BCAST|M_MCAST)) {
1304 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1305 log(LOG_DEBUG, "%s; %s: Listen socket: "
1306 "Connection attempt from broad- or multicast "
1307 "link layer address ignored\n", s, __func__);
1312 if (th->th_dport == th->th_sport &&
1313 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1314 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1315 log(LOG_DEBUG, "%s; %s: Listen socket: "
1316 "Connection attempt to/from self "
1317 "ignored\n", s, __func__);
1320 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1321 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1322 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1323 log(LOG_DEBUG, "%s; %s: Listen socket: "
1324 "Connection attempt from/to multicast "
1325 "address ignored\n", s, __func__);
1330 #if defined(INET) && defined(INET6)
1335 if (th->th_dport == th->th_sport &&
1336 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1337 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1338 log(LOG_DEBUG, "%s; %s: Listen socket: "
1339 "Connection attempt from/to self "
1340 "ignored\n", s, __func__);
1343 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1344 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1345 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1346 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1347 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1348 log(LOG_DEBUG, "%s; %s: Listen socket: "
1349 "Connection attempt from/to broad- "
1350 "or multicast address ignored\n",
1357 * SYN appears to be valid. Create compressed TCP state
1361 if (so->so_options & SO_DEBUG)
1362 tcp_trace(TA_INPUT, ostate, tp,
1363 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1365 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1366 tcp_dooptions(&to, optp, optlen, TO_SYN);
1368 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
1369 goto new_tfo_socket;
1371 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1374 * Entry added to syncache and mbuf consumed.
1375 * Only the listen socket is unlocked by syncache_add().
1377 if (ti_locked == TI_RLOCKED) {
1378 INP_INFO_RUNLOCK(&V_tcbinfo);
1379 ti_locked = TI_UNLOCKED;
1381 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1382 return (IPPROTO_DONE);
1383 } else if (tp->t_state == TCPS_LISTEN) {
1385 * When a listen socket is torn down the SO_ACCEPTCONN
1386 * flag is removed first while connections are drained
1387 * from the accept queue in a unlock/lock cycle of the
1388 * ACCEPT_LOCK, opening a race condition allowing a SYN
1389 * attempt go through unhandled.
1394 #ifdef TCP_SIGNATURE
1395 if (sig_checked == 0) {
1396 tcp_dooptions(&to, optp, optlen,
1397 (thflags & TH_SYN) ? TO_SYN : 0);
1398 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1402 * In SYN_SENT state if it receives an RST, it is
1403 * allowed for further processing.
1405 if ((thflags & TH_RST) == 0 ||
1406 (tp->t_state == TCPS_SYN_SENT) == 0)
1413 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), 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, mtod(m, const char *), 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, mtod(m, const char *), 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 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1477 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1480 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1481 int rstreason, todrop, win;
1484 struct in_conninfo *inc;
1491 * The size of tcp_saveipgen must be the size of the max ip header,
1494 u_char tcp_saveipgen[IP6_HDR_LEN];
1495 struct tcphdr tcp_savetcp;
1498 thflags = th->th_flags;
1499 inc = &tp->t_inpcb->inp_inc;
1500 tp->sackhint.last_sack_ack = 0;
1504 * If this is either a state-changing packet or current state isn't
1505 * established, we require a write lock on tcbinfo. Otherwise, we
1506 * allow the tcbinfo to be in either alocked or unlocked, as the
1507 * caller may have unnecessarily acquired a write lock due to a race.
1509 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1510 tp->t_state != TCPS_ESTABLISHED) {
1511 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1512 "SYN/FIN/RST/!EST", __func__, ti_locked));
1513 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1516 if (ti_locked == TI_RLOCKED)
1517 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1519 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1520 "ti_locked: %d", __func__, ti_locked));
1521 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1525 INP_WLOCK_ASSERT(tp->t_inpcb);
1526 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1528 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1532 /* Save segment, if requested. */
1533 tcp_pcap_add(th, m, &(tp->t_inpkts));
1537 * Segment received on connection.
1538 * Reset idle time and keep-alive timer.
1539 * XXX: This should be done after segment
1540 * validation to ignore broken/spoofed segs.
1542 tp->t_rcvtime = ticks;
1543 if (TCPS_HAVEESTABLISHED(tp->t_state))
1544 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1547 * Scale up the window into a 32-bit value.
1548 * For the SYN_SENT state the scale is zero.
1550 tiwin = th->th_win << tp->snd_scale;
1553 * TCP ECN processing.
1555 if (tp->t_flags & TF_ECN_PERMIT) {
1556 if (thflags & TH_CWR)
1557 tp->t_flags &= ~TF_ECN_SND_ECE;
1558 switch (iptos & IPTOS_ECN_MASK) {
1560 tp->t_flags |= TF_ECN_SND_ECE;
1561 TCPSTAT_INC(tcps_ecn_ce);
1563 case IPTOS_ECN_ECT0:
1564 TCPSTAT_INC(tcps_ecn_ect0);
1566 case IPTOS_ECN_ECT1:
1567 TCPSTAT_INC(tcps_ecn_ect1);
1571 /* Process a packet differently from RFC3168. */
1572 cc_ecnpkt_handler(tp, th, iptos);
1574 /* Congestion experienced. */
1575 if (thflags & TH_ECE) {
1576 cc_cong_signal(tp, th, CC_ECN);
1581 * Parse options on any incoming segment.
1583 tcp_dooptions(&to, (u_char *)(th + 1),
1584 (th->th_off << 2) - sizeof(struct tcphdr),
1585 (thflags & TH_SYN) ? TO_SYN : 0);
1588 * If echoed timestamp is later than the current time,
1589 * fall back to non RFC1323 RTT calculation. Normalize
1590 * timestamp if syncookies were used when this connection
1593 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1594 to.to_tsecr -= tp->ts_offset;
1595 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1599 * If timestamps were negotiated during SYN/ACK they should
1600 * appear on every segment during this session and vice versa.
1602 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1603 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1604 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1605 "no action\n", s, __func__);
1609 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1610 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1611 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1612 "no action\n", s, __func__);
1618 * Process options only when we get SYN/ACK back. The SYN case
1619 * for incoming connections is handled in tcp_syncache.
1620 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1621 * or <SYN,ACK>) segment itself is never scaled.
1622 * XXX this is traditional behavior, may need to be cleaned up.
1624 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1625 if ((to.to_flags & TOF_SCALE) &&
1626 (tp->t_flags & TF_REQ_SCALE)) {
1627 tp->t_flags |= TF_RCVD_SCALE;
1628 tp->snd_scale = to.to_wscale;
1631 * Initial send window. It will be updated with
1632 * the next incoming segment to the scaled value.
1634 tp->snd_wnd = th->th_win;
1635 if (to.to_flags & TOF_TS) {
1636 tp->t_flags |= TF_RCVD_TSTMP;
1637 tp->ts_recent = to.to_tsval;
1638 tp->ts_recent_age = tcp_ts_getticks();
1640 if (to.to_flags & TOF_MSS)
1641 tcp_mss(tp, to.to_mss);
1642 if ((tp->t_flags & TF_SACK_PERMIT) &&
1643 (to.to_flags & TOF_SACKPERM) == 0)
1644 tp->t_flags &= ~TF_SACK_PERMIT;
1648 * Header prediction: check for the two common cases
1649 * of a uni-directional data xfer. If the packet has
1650 * no control flags, is in-sequence, the window didn't
1651 * change and we're not retransmitting, it's a
1652 * candidate. If the length is zero and the ack moved
1653 * forward, we're the sender side of the xfer. Just
1654 * free the data acked & wake any higher level process
1655 * that was blocked waiting for space. If the length
1656 * is non-zero and the ack didn't move, we're the
1657 * receiver side. If we're getting packets in-order
1658 * (the reassembly queue is empty), add the data to
1659 * the socket buffer and note that we need a delayed ack.
1660 * Make sure that the hidden state-flags are also off.
1661 * Since we check for TCPS_ESTABLISHED first, it can only
1664 if (tp->t_state == TCPS_ESTABLISHED &&
1665 th->th_seq == tp->rcv_nxt &&
1666 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1667 tp->snd_nxt == tp->snd_max &&
1668 tiwin && tiwin == tp->snd_wnd &&
1669 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1670 LIST_EMPTY(&tp->t_segq) &&
1671 ((to.to_flags & TOF_TS) == 0 ||
1672 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1675 * If last ACK falls within this segment's sequence numbers,
1676 * record the timestamp.
1677 * NOTE that the test is modified according to the latest
1678 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1680 if ((to.to_flags & TOF_TS) != 0 &&
1681 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1682 tp->ts_recent_age = tcp_ts_getticks();
1683 tp->ts_recent = to.to_tsval;
1687 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1688 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1689 !IN_RECOVERY(tp->t_flags) &&
1690 (to.to_flags & TOF_SACK) == 0 &&
1691 TAILQ_EMPTY(&tp->snd_holes)) {
1693 * This is a pure ack for outstanding data.
1695 if (ti_locked == TI_RLOCKED)
1696 INP_INFO_RUNLOCK(&V_tcbinfo);
1697 ti_locked = TI_UNLOCKED;
1699 TCPSTAT_INC(tcps_predack);
1702 * "bad retransmit" recovery.
1704 if (tp->t_rxtshift == 1 &&
1705 tp->t_flags & TF_PREVVALID &&
1706 (int)(ticks - tp->t_badrxtwin) < 0) {
1707 cc_cong_signal(tp, th, CC_RTO_ERR);
1711 * Recalculate the transmit timer / rtt.
1713 * Some boxes send broken timestamp replies
1714 * during the SYN+ACK phase, ignore
1715 * timestamps of 0 or we could calculate a
1716 * huge RTT and blow up the retransmit timer.
1718 if ((to.to_flags & TOF_TS) != 0 &&
1722 t = tcp_ts_getticks() - to.to_tsecr;
1723 if (!tp->t_rttlow || tp->t_rttlow > t)
1726 TCP_TS_TO_TICKS(t) + 1);
1727 } else if (tp->t_rtttime &&
1728 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1729 if (!tp->t_rttlow ||
1730 tp->t_rttlow > ticks - tp->t_rtttime)
1731 tp->t_rttlow = ticks - tp->t_rtttime;
1733 ticks - tp->t_rtttime);
1735 acked = BYTES_THIS_ACK(tp, th);
1737 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1738 hhook_run_tcp_est_in(tp, th, &to);
1740 TCPSTAT_INC(tcps_rcvackpack);
1741 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1742 sbdrop(&so->so_snd, acked);
1743 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1744 SEQ_LEQ(th->th_ack, tp->snd_recover))
1745 tp->snd_recover = th->th_ack - 1;
1748 * Let the congestion control algorithm update
1749 * congestion control related information. This
1750 * typically means increasing the congestion
1753 cc_ack_received(tp, th, CC_ACK);
1755 tp->snd_una = th->th_ack;
1757 * Pull snd_wl2 up to prevent seq wrap relative
1760 tp->snd_wl2 = th->th_ack;
1765 * If all outstanding data are acked, stop
1766 * retransmit timer, otherwise restart timer
1767 * using current (possibly backed-off) value.
1768 * If process is waiting for space,
1769 * wakeup/selwakeup/signal. If data
1770 * are ready to send, let tcp_output
1771 * decide between more output or persist.
1774 if (so->so_options & SO_DEBUG)
1775 tcp_trace(TA_INPUT, ostate, tp,
1776 (void *)tcp_saveipgen,
1779 TCP_PROBE3(debug__input, tp, th,
1780 mtod(m, const char *));
1781 if (tp->snd_una == tp->snd_max)
1782 tcp_timer_activate(tp, TT_REXMT, 0);
1783 else if (!tcp_timer_active(tp, TT_PERSIST))
1784 tcp_timer_activate(tp, TT_REXMT,
1787 if (sbavail(&so->so_snd))
1788 (void) tp->t_fb->tfb_tcp_output(tp);
1791 } else if (th->th_ack == tp->snd_una &&
1792 tlen <= sbspace(&so->so_rcv)) {
1793 int newsize = 0; /* automatic sockbuf scaling */
1796 * This is a pure, in-sequence data packet with
1797 * nothing on the reassembly queue and we have enough
1798 * buffer space to take it.
1800 if (ti_locked == TI_RLOCKED)
1801 INP_INFO_RUNLOCK(&V_tcbinfo);
1802 ti_locked = TI_UNLOCKED;
1804 /* Clean receiver SACK report if present */
1805 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1806 tcp_clean_sackreport(tp);
1807 TCPSTAT_INC(tcps_preddat);
1808 tp->rcv_nxt += tlen;
1810 * Pull snd_wl1 up to prevent seq wrap relative to
1813 tp->snd_wl1 = th->th_seq;
1815 * Pull rcv_up up to prevent seq wrap relative to
1818 tp->rcv_up = tp->rcv_nxt;
1819 TCPSTAT_INC(tcps_rcvpack);
1820 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1822 if (so->so_options & SO_DEBUG)
1823 tcp_trace(TA_INPUT, ostate, tp,
1824 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1826 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1829 * Automatic sizing of receive socket buffer. Often the send
1830 * buffer size is not optimally adjusted to the actual network
1831 * conditions at hand (delay bandwidth product). Setting the
1832 * buffer size too small limits throughput on links with high
1833 * bandwidth and high delay (eg. trans-continental/oceanic links).
1835 * On the receive side the socket buffer memory is only rarely
1836 * used to any significant extent. This allows us to be much
1837 * more aggressive in scaling the receive socket buffer. For
1838 * the case that the buffer space is actually used to a large
1839 * extent and we run out of kernel memory we can simply drop
1840 * the new segments; TCP on the sender will just retransmit it
1841 * later. Setting the buffer size too big may only consume too
1842 * much kernel memory if the application doesn't read() from
1843 * the socket or packet loss or reordering makes use of the
1846 * The criteria to step up the receive buffer one notch are:
1847 * 1. Application has not set receive buffer size with
1848 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1849 * 2. the number of bytes received during the time it takes
1850 * one timestamp to be reflected back to us (the RTT);
1851 * 3. received bytes per RTT is within seven eighth of the
1852 * current socket buffer size;
1853 * 4. receive buffer size has not hit maximal automatic size;
1855 * This algorithm does one step per RTT at most and only if
1856 * we receive a bulk stream w/o packet losses or reorderings.
1857 * Shrinking the buffer during idle times is not necessary as
1858 * it doesn't consume any memory when idle.
1860 * TODO: Only step up if the application is actually serving
1861 * the buffer to better manage the socket buffer resources.
1863 if (V_tcp_do_autorcvbuf &&
1864 (to.to_flags & TOF_TS) &&
1866 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1867 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1868 to.to_tsecr - tp->rfbuf_ts < hz) {
1870 (so->so_rcv.sb_hiwat / 8 * 7) &&
1871 so->so_rcv.sb_hiwat <
1872 V_tcp_autorcvbuf_max) {
1874 min(so->so_rcv.sb_hiwat +
1875 V_tcp_autorcvbuf_inc,
1876 V_tcp_autorcvbuf_max);
1878 /* Start over with next RTT. */
1882 tp->rfbuf_cnt += tlen; /* add up */
1885 /* Add data to socket buffer. */
1886 SOCKBUF_LOCK(&so->so_rcv);
1887 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1891 * Set new socket buffer size.
1892 * Give up when limit is reached.
1895 if (!sbreserve_locked(&so->so_rcv,
1897 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1898 m_adj(m, drop_hdrlen); /* delayed header drop */
1899 sbappendstream_locked(&so->so_rcv, m, 0);
1901 /* NB: sorwakeup_locked() does an implicit unlock. */
1902 sorwakeup_locked(so);
1903 if (DELAY_ACK(tp, tlen)) {
1904 tp->t_flags |= TF_DELACK;
1906 tp->t_flags |= TF_ACKNOW;
1907 tp->t_fb->tfb_tcp_output(tp);
1914 * Calculate amount of space in receive window,
1915 * and then do TCP input processing.
1916 * Receive window is amount of space in rcv queue,
1917 * but not less than advertised window.
1919 win = sbspace(&so->so_rcv);
1922 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1924 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1928 switch (tp->t_state) {
1931 * If the state is SYN_RECEIVED:
1932 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1934 case TCPS_SYN_RECEIVED:
1935 if ((thflags & TH_ACK) &&
1936 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1937 SEQ_GT(th->th_ack, tp->snd_max))) {
1938 rstreason = BANDLIM_RST_OPENPORT;
1942 if (tp->t_flags & TF_FASTOPEN) {
1944 * When a TFO connection is in SYN_RECEIVED, the
1945 * only valid packets are the initial SYN, a
1946 * retransmit/copy of the initial SYN (possibly with
1947 * a subset of the original data), a valid ACK, a
1950 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1951 rstreason = BANDLIM_RST_OPENPORT;
1953 } else if (thflags & TH_SYN) {
1954 /* non-initial SYN is ignored */
1955 if ((tcp_timer_active(tp, TT_DELACK) ||
1956 tcp_timer_active(tp, TT_REXMT)))
1958 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1966 * If the state is SYN_SENT:
1967 * if seg contains an ACK, but not for our SYN, drop the input.
1968 * if seg contains a RST, then drop the connection.
1969 * if seg does not contain SYN, then drop it.
1970 * Otherwise this is an acceptable SYN segment
1971 * initialize tp->rcv_nxt and tp->irs
1972 * if seg contains ack then advance tp->snd_una
1973 * if seg contains an ECE and ECN support is enabled, the stream
1975 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1976 * arrange for segment to be acked (eventually)
1977 * continue processing rest of data/controls, beginning with URG
1980 if ((thflags & TH_ACK) &&
1981 (SEQ_LEQ(th->th_ack, tp->iss) ||
1982 SEQ_GT(th->th_ack, tp->snd_max))) {
1983 rstreason = BANDLIM_UNLIMITED;
1986 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1987 TCP_PROBE5(connect__refused, NULL, tp,
1988 mtod(m, const char *), tp, th);
1989 tp = tcp_drop(tp, ECONNREFUSED);
1991 if (thflags & TH_RST)
1993 if (!(thflags & TH_SYN))
1996 tp->irs = th->th_seq;
1998 if (thflags & TH_ACK) {
1999 TCPSTAT_INC(tcps_connects);
2002 mac_socketpeer_set_from_mbuf(m, so);
2004 /* Do window scaling on this connection? */
2005 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2006 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2007 tp->rcv_scale = tp->request_r_scale;
2009 tp->rcv_adv += imin(tp->rcv_wnd,
2010 TCP_MAXWIN << tp->rcv_scale);
2011 tp->snd_una++; /* SYN is acked */
2013 * If there's data, delay ACK; if there's also a FIN
2014 * ACKNOW will be turned on later.
2016 if (DELAY_ACK(tp, tlen) && tlen != 0)
2017 tcp_timer_activate(tp, TT_DELACK,
2020 tp->t_flags |= TF_ACKNOW;
2022 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
2023 tp->t_flags |= TF_ECN_PERMIT;
2024 TCPSTAT_INC(tcps_ecn_shs);
2028 * Received <SYN,ACK> in SYN_SENT[*] state.
2030 * SYN_SENT --> ESTABLISHED
2031 * SYN_SENT* --> FIN_WAIT_1
2033 tp->t_starttime = ticks;
2034 if (tp->t_flags & TF_NEEDFIN) {
2035 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2036 tp->t_flags &= ~TF_NEEDFIN;
2039 tcp_state_change(tp, TCPS_ESTABLISHED);
2040 TCP_PROBE5(connect__established, NULL, tp,
2041 mtod(m, const char *), tp, th);
2043 tcp_timer_activate(tp, TT_KEEP,
2048 * Received initial SYN in SYN-SENT[*] state =>
2049 * simultaneous open.
2050 * If it succeeds, connection is * half-synchronized.
2051 * Otherwise, do 3-way handshake:
2052 * SYN-SENT -> SYN-RECEIVED
2053 * SYN-SENT* -> SYN-RECEIVED*
2055 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2056 tcp_timer_activate(tp, TT_REXMT, 0);
2057 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2060 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
2061 "ti_locked %d", __func__, ti_locked));
2062 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2063 INP_WLOCK_ASSERT(tp->t_inpcb);
2066 * Advance th->th_seq to correspond to first data byte.
2067 * If data, trim to stay within window,
2068 * dropping FIN if necessary.
2071 if (tlen > tp->rcv_wnd) {
2072 todrop = tlen - tp->rcv_wnd;
2076 TCPSTAT_INC(tcps_rcvpackafterwin);
2077 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2079 tp->snd_wl1 = th->th_seq - 1;
2080 tp->rcv_up = th->th_seq;
2082 * Client side of transaction: already sent SYN and data.
2083 * If the remote host used T/TCP to validate the SYN,
2084 * our data will be ACK'd; if so, enter normal data segment
2085 * processing in the middle of step 5, ack processing.
2086 * Otherwise, goto step 6.
2088 if (thflags & TH_ACK)
2094 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2095 * do normal processing.
2097 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2101 break; /* continue normal processing */
2105 * States other than LISTEN or SYN_SENT.
2106 * First check the RST flag and sequence number since reset segments
2107 * are exempt from the timestamp and connection count tests. This
2108 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2109 * below which allowed reset segments in half the sequence space
2110 * to fall though and be processed (which gives forged reset
2111 * segments with a random sequence number a 50 percent chance of
2112 * killing a connection).
2113 * Then check timestamp, if present.
2114 * Then check the connection count, if present.
2115 * Then check that at least some bytes of segment are within
2116 * receive window. If segment begins before rcv_nxt,
2117 * drop leading data (and SYN); if nothing left, just ack.
2119 if (thflags & TH_RST) {
2121 * RFC5961 Section 3.2
2123 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2124 * - If RST is in window, we send challenge ACK.
2126 * Note: to take into account delayed ACKs, we should
2127 * test against last_ack_sent instead of rcv_nxt.
2128 * Note 2: we handle special case of closed window, not
2129 * covered by the RFC.
2131 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2132 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2133 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2135 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2136 KASSERT(ti_locked == TI_RLOCKED,
2137 ("%s: TH_RST ti_locked %d, th %p tp %p",
2138 __func__, ti_locked, th, tp));
2139 KASSERT(tp->t_state != TCPS_SYN_SENT,
2140 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2143 if (V_tcp_insecure_rst ||
2144 tp->last_ack_sent == th->th_seq) {
2145 TCPSTAT_INC(tcps_drops);
2146 /* Drop the connection. */
2147 switch (tp->t_state) {
2148 case TCPS_SYN_RECEIVED:
2149 so->so_error = ECONNREFUSED;
2151 case TCPS_ESTABLISHED:
2152 case TCPS_FIN_WAIT_1:
2153 case TCPS_FIN_WAIT_2:
2154 case TCPS_CLOSE_WAIT:
2155 so->so_error = ECONNRESET;
2157 tcp_state_change(tp, TCPS_CLOSED);
2163 TCPSTAT_INC(tcps_badrst);
2164 /* Send challenge ACK. */
2165 tcp_respond(tp, mtod(m, void *), th, m,
2166 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2167 tp->last_ack_sent = tp->rcv_nxt;
2175 * RFC5961 Section 4.2
2176 * Send challenge ACK for any SYN in synchronized state.
2178 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2179 tp->t_state != TCPS_SYN_RECEIVED) {
2180 KASSERT(ti_locked == TI_RLOCKED,
2181 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2182 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2184 TCPSTAT_INC(tcps_badsyn);
2185 if (V_tcp_insecure_syn &&
2186 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2187 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2188 tp = tcp_drop(tp, ECONNRESET);
2189 rstreason = BANDLIM_UNLIMITED;
2191 /* Send challenge ACK. */
2192 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2193 tp->snd_nxt, TH_ACK);
2194 tp->last_ack_sent = tp->rcv_nxt;
2201 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2202 * and it's less than ts_recent, drop it.
2204 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2205 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2207 /* Check to see if ts_recent is over 24 days old. */
2208 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2210 * Invalidate ts_recent. If this segment updates
2211 * ts_recent, the age will be reset later and ts_recent
2212 * will get a valid value. If it does not, setting
2213 * ts_recent to zero will at least satisfy the
2214 * requirement that zero be placed in the timestamp
2215 * echo reply when ts_recent isn't valid. The
2216 * age isn't reset until we get a valid ts_recent
2217 * because we don't want out-of-order segments to be
2218 * dropped when ts_recent is old.
2222 TCPSTAT_INC(tcps_rcvduppack);
2223 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2224 TCPSTAT_INC(tcps_pawsdrop);
2232 * In the SYN-RECEIVED state, validate that the packet belongs to
2233 * this connection before trimming the data to fit the receive
2234 * window. Check the sequence number versus IRS since we know
2235 * the sequence numbers haven't wrapped. This is a partial fix
2236 * for the "LAND" DoS attack.
2238 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2239 rstreason = BANDLIM_RST_OPENPORT;
2243 todrop = tp->rcv_nxt - th->th_seq;
2245 if (thflags & TH_SYN) {
2255 * Following if statement from Stevens, vol. 2, p. 960.
2258 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2260 * Any valid FIN must be to the left of the window.
2261 * At this point the FIN must be a duplicate or out
2262 * of sequence; drop it.
2267 * Send an ACK to resynchronize and drop any data.
2268 * But keep on processing for RST or ACK.
2270 tp->t_flags |= TF_ACKNOW;
2272 TCPSTAT_INC(tcps_rcvduppack);
2273 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2275 TCPSTAT_INC(tcps_rcvpartduppack);
2276 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2278 drop_hdrlen += todrop; /* drop from the top afterwards */
2279 th->th_seq += todrop;
2281 if (th->th_urp > todrop)
2282 th->th_urp -= todrop;
2290 * If new data are received on a connection after the
2291 * user processes are gone, then RST the other end.
2293 if ((so->so_state & SS_NOFDREF) &&
2294 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2295 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
2296 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2297 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2299 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2300 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2301 "after socket was closed, "
2302 "sending RST and removing tcpcb\n",
2303 s, __func__, tcpstates[tp->t_state], tlen);
2307 TCPSTAT_INC(tcps_rcvafterclose);
2308 rstreason = BANDLIM_UNLIMITED;
2313 * If segment ends after window, drop trailing data
2314 * (and PUSH and FIN); if nothing left, just ACK.
2316 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2318 TCPSTAT_INC(tcps_rcvpackafterwin);
2319 if (todrop >= tlen) {
2320 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2322 * If window is closed can only take segments at
2323 * window edge, and have to drop data and PUSH from
2324 * incoming segments. Continue processing, but
2325 * remember to ack. Otherwise, drop segment
2328 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2329 tp->t_flags |= TF_ACKNOW;
2330 TCPSTAT_INC(tcps_rcvwinprobe);
2334 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2337 thflags &= ~(TH_PUSH|TH_FIN);
2341 * If last ACK falls within this segment's sequence numbers,
2342 * record its timestamp.
2344 * 1) That the test incorporates suggestions from the latest
2345 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2346 * 2) That updating only on newer timestamps interferes with
2347 * our earlier PAWS tests, so this check should be solely
2348 * predicated on the sequence space of this segment.
2349 * 3) That we modify the segment boundary check to be
2350 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2351 * instead of RFC1323's
2352 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2353 * This modified check allows us to overcome RFC1323's
2354 * limitations as described in Stevens TCP/IP Illustrated
2355 * Vol. 2 p.869. In such cases, we can still calculate the
2356 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2358 if ((to.to_flags & TOF_TS) != 0 &&
2359 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2360 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2361 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2362 tp->ts_recent_age = tcp_ts_getticks();
2363 tp->ts_recent = to.to_tsval;
2367 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2368 * flag is on (half-synchronized state), then queue data for
2369 * later processing; else drop segment and return.
2371 if ((thflags & TH_ACK) == 0) {
2372 if (tp->t_state == TCPS_SYN_RECEIVED ||
2373 (tp->t_flags & TF_NEEDSYN)) {
2375 if (tp->t_state == TCPS_SYN_RECEIVED &&
2376 tp->t_flags & TF_FASTOPEN) {
2377 tp->snd_wnd = tiwin;
2382 } else if (tp->t_flags & TF_ACKNOW)
2391 switch (tp->t_state) {
2394 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2395 * ESTABLISHED state and continue processing.
2396 * The ACK was checked above.
2398 case TCPS_SYN_RECEIVED:
2400 TCPSTAT_INC(tcps_connects);
2402 /* Do window scaling? */
2403 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2404 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2405 tp->rcv_scale = tp->request_r_scale;
2406 tp->snd_wnd = tiwin;
2410 * SYN-RECEIVED -> ESTABLISHED
2411 * SYN-RECEIVED* -> FIN-WAIT-1
2413 tp->t_starttime = ticks;
2414 if (tp->t_flags & TF_NEEDFIN) {
2415 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2416 tp->t_flags &= ~TF_NEEDFIN;
2418 tcp_state_change(tp, TCPS_ESTABLISHED);
2419 TCP_PROBE5(accept__established, NULL, tp,
2420 mtod(m, const char *), tp, th);
2422 if (tp->t_tfo_pending) {
2423 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2424 tp->t_tfo_pending = NULL;
2427 * Account for the ACK of our SYN prior to
2428 * regular ACK processing below.
2433 * TFO connections call cc_conn_init() during SYN
2434 * processing. Calling it again here for such
2435 * connections is not harmless as it would undo the
2436 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2439 if (!(tp->t_flags & TF_FASTOPEN))
2442 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2445 * If segment contains data or ACK, will call tcp_reass()
2446 * later; if not, do so now to pass queued data to user.
2448 if (tlen == 0 && (thflags & TH_FIN) == 0)
2449 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2451 tp->snd_wl1 = th->th_seq - 1;
2455 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2456 * ACKs. If the ack is in the range
2457 * tp->snd_una < th->th_ack <= tp->snd_max
2458 * then advance tp->snd_una to th->th_ack and drop
2459 * data from the retransmission queue. If this ACK reflects
2460 * more up to date window information we update our window information.
2462 case TCPS_ESTABLISHED:
2463 case TCPS_FIN_WAIT_1:
2464 case TCPS_FIN_WAIT_2:
2465 case TCPS_CLOSE_WAIT:
2468 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2469 TCPSTAT_INC(tcps_rcvacktoomuch);
2472 if ((tp->t_flags & TF_SACK_PERMIT) &&
2473 ((to.to_flags & TOF_SACK) ||
2474 !TAILQ_EMPTY(&tp->snd_holes)))
2475 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2478 * Reset the value so that previous (valid) value
2479 * from the last ack with SACK doesn't get used.
2481 tp->sackhint.sacked_bytes = 0;
2483 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2484 hhook_run_tcp_est_in(tp, th, &to);
2486 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2489 maxseg = tcp_maxseg(tp);
2491 (tiwin == tp->snd_wnd ||
2492 (tp->t_flags & TF_SACK_PERMIT))) {
2494 * If this is the first time we've seen a
2495 * FIN from the remote, this is not a
2496 * duplicate and it needs to be processed
2497 * normally. This happens during a
2498 * simultaneous close.
2500 if ((thflags & TH_FIN) &&
2501 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2505 TCPSTAT_INC(tcps_rcvdupack);
2507 * If we have outstanding data (other than
2508 * a window probe), this is a completely
2509 * duplicate ack (ie, window info didn't
2510 * change and FIN isn't set),
2511 * the ack is the biggest we've
2512 * seen and we've seen exactly our rexmt
2513 * threshhold of them, assume a packet
2514 * has been dropped and retransmit it.
2515 * Kludge snd_nxt & the congestion
2516 * window so we send only this one
2519 * We know we're losing at the current
2520 * window size so do congestion avoidance
2521 * (set ssthresh to half the current window
2522 * and pull our congestion window back to
2523 * the new ssthresh).
2525 * Dup acks mean that packets have left the
2526 * network (they're now cached at the receiver)
2527 * so bump cwnd by the amount in the receiver
2528 * to keep a constant cwnd packets in the
2531 * When using TCP ECN, notify the peer that
2532 * we reduced the cwnd.
2535 * Following 2 kinds of acks should not affect
2538 * 2) Acks with SACK but without any new SACK
2539 * information in them. These could result from
2540 * any anomaly in the network like a switch
2541 * duplicating packets or a possible DoS attack.
2543 if (th->th_ack != tp->snd_una ||
2544 ((tp->t_flags & TF_SACK_PERMIT) &&
2547 else if (!tcp_timer_active(tp, TT_REXMT))
2549 else if (++tp->t_dupacks > tcprexmtthresh ||
2550 IN_FASTRECOVERY(tp->t_flags)) {
2551 cc_ack_received(tp, th, CC_DUPACK);
2552 if ((tp->t_flags & TF_SACK_PERMIT) &&
2553 IN_FASTRECOVERY(tp->t_flags)) {
2557 * Compute the amount of data in flight first.
2558 * We can inject new data into the pipe iff
2559 * we have less than 1/2 the original window's
2560 * worth of data in flight.
2562 if (V_tcp_do_rfc6675_pipe)
2563 awnd = tcp_compute_pipe(tp);
2565 awnd = (tp->snd_nxt - tp->snd_fack) +
2566 tp->sackhint.sack_bytes_rexmit;
2568 if (awnd < tp->snd_ssthresh) {
2569 tp->snd_cwnd += maxseg;
2570 if (tp->snd_cwnd > tp->snd_ssthresh)
2571 tp->snd_cwnd = tp->snd_ssthresh;
2574 tp->snd_cwnd += maxseg;
2575 (void) tp->t_fb->tfb_tcp_output(tp);
2577 } else if (tp->t_dupacks == tcprexmtthresh) {
2578 tcp_seq onxt = tp->snd_nxt;
2581 * If we're doing sack, check to
2582 * see if we're already in sack
2583 * recovery. If we're not doing sack,
2584 * check to see if we're in newreno
2587 if (tp->t_flags & TF_SACK_PERMIT) {
2588 if (IN_FASTRECOVERY(tp->t_flags)) {
2593 if (SEQ_LEQ(th->th_ack,
2599 /* Congestion signal before ack. */
2600 cc_cong_signal(tp, th, CC_NDUPACK);
2601 cc_ack_received(tp, th, CC_DUPACK);
2602 tcp_timer_activate(tp, TT_REXMT, 0);
2604 if (tp->t_flags & TF_SACK_PERMIT) {
2606 tcps_sack_recovery_episode);
2607 tp->sack_newdata = tp->snd_nxt;
2608 tp->snd_cwnd = maxseg;
2609 (void) tp->t_fb->tfb_tcp_output(tp);
2612 tp->snd_nxt = th->th_ack;
2613 tp->snd_cwnd = maxseg;
2614 (void) tp->t_fb->tfb_tcp_output(tp);
2615 KASSERT(tp->snd_limited <= 2,
2616 ("%s: tp->snd_limited too big",
2618 tp->snd_cwnd = tp->snd_ssthresh +
2620 (tp->t_dupacks - tp->snd_limited);
2621 if (SEQ_GT(onxt, tp->snd_nxt))
2624 } else if (V_tcp_do_rfc3042) {
2626 * Process first and second duplicate
2627 * ACKs. Each indicates a segment
2628 * leaving the network, creating room
2629 * for more. Make sure we can send a
2630 * packet on reception of each duplicate
2631 * ACK by increasing snd_cwnd by one
2632 * segment. Restore the original
2633 * snd_cwnd after packet transmission.
2635 cc_ack_received(tp, th, CC_DUPACK);
2636 u_long oldcwnd = tp->snd_cwnd;
2637 tcp_seq oldsndmax = tp->snd_max;
2641 KASSERT(tp->t_dupacks == 1 ||
2643 ("%s: dupacks not 1 or 2",
2645 if (tp->t_dupacks == 1)
2646 tp->snd_limited = 0;
2648 (tp->snd_nxt - tp->snd_una) +
2649 (tp->t_dupacks - tp->snd_limited) *
2652 * Only call tcp_output when there
2653 * is new data available to be sent.
2654 * Otherwise we would send pure ACKs.
2656 SOCKBUF_LOCK(&so->so_snd);
2657 avail = sbavail(&so->so_snd) -
2658 (tp->snd_nxt - tp->snd_una);
2659 SOCKBUF_UNLOCK(&so->so_snd);
2661 (void) tp->t_fb->tfb_tcp_output(tp);
2662 sent = tp->snd_max - oldsndmax;
2663 if (sent > maxseg) {
2664 KASSERT((tp->t_dupacks == 2 &&
2665 tp->snd_limited == 0) ||
2666 (sent == maxseg + 1 &&
2667 tp->t_flags & TF_SENTFIN),
2668 ("%s: sent too much",
2670 tp->snd_limited = 2;
2671 } else if (sent > 0)
2673 tp->snd_cwnd = oldcwnd;
2680 * This ack is advancing the left edge, reset the
2685 * If this ack also has new SACK info, increment the
2686 * counter as per rfc6675.
2688 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2692 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2693 ("%s: th_ack <= snd_una", __func__));
2696 * If the congestion window was inflated to account
2697 * for the other side's cached packets, retract it.
2699 if (IN_FASTRECOVERY(tp->t_flags)) {
2700 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2701 if (tp->t_flags & TF_SACK_PERMIT)
2702 tcp_sack_partialack(tp, th);
2704 tcp_newreno_partial_ack(tp, th);
2706 cc_post_recovery(tp, th);
2709 * If we reach this point, ACK is not a duplicate,
2710 * i.e., it ACKs something we sent.
2712 if (tp->t_flags & TF_NEEDSYN) {
2714 * T/TCP: Connection was half-synchronized, and our
2715 * SYN has been ACK'd (so connection is now fully
2716 * synchronized). Go to non-starred state,
2717 * increment snd_una for ACK of SYN, and check if
2718 * we can do window scaling.
2720 tp->t_flags &= ~TF_NEEDSYN;
2722 /* Do window scaling? */
2723 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2724 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2725 tp->rcv_scale = tp->request_r_scale;
2726 /* Send window already scaled. */
2731 INP_WLOCK_ASSERT(tp->t_inpcb);
2733 acked = BYTES_THIS_ACK(tp, th);
2734 TCPSTAT_INC(tcps_rcvackpack);
2735 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2738 * If we just performed our first retransmit, and the ACK
2739 * arrives within our recovery window, then it was a mistake
2740 * to do the retransmit in the first place. Recover our
2741 * original cwnd and ssthresh, and proceed to transmit where
2744 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2745 (int)(ticks - tp->t_badrxtwin) < 0)
2746 cc_cong_signal(tp, th, CC_RTO_ERR);
2749 * If we have a timestamp reply, update smoothed
2750 * round trip time. If no timestamp is present but
2751 * transmit timer is running and timed sequence
2752 * number was acked, update smoothed round trip time.
2753 * Since we now have an rtt measurement, cancel the
2754 * timer backoff (cf., Phil Karn's retransmit alg.).
2755 * Recompute the initial retransmit timer.
2757 * Some boxes send broken timestamp replies
2758 * during the SYN+ACK phase, ignore
2759 * timestamps of 0 or we could calculate a
2760 * huge RTT and blow up the retransmit timer.
2762 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2765 t = tcp_ts_getticks() - to.to_tsecr;
2766 if (!tp->t_rttlow || tp->t_rttlow > t)
2768 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2769 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2770 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2771 tp->t_rttlow = ticks - tp->t_rtttime;
2772 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2776 * If all outstanding data is acked, stop retransmit
2777 * timer and remember to restart (more output or persist).
2778 * If there is more data to be acked, restart retransmit
2779 * timer, using current (possibly backed-off) value.
2781 if (th->th_ack == tp->snd_max) {
2782 tcp_timer_activate(tp, TT_REXMT, 0);
2784 } else if (!tcp_timer_active(tp, TT_PERSIST))
2785 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2788 * If no data (only SYN) was ACK'd,
2789 * skip rest of ACK processing.
2795 * Let the congestion control algorithm update congestion
2796 * control related information. This typically means increasing
2797 * the congestion window.
2799 cc_ack_received(tp, th, CC_ACK);
2801 SOCKBUF_LOCK(&so->so_snd);
2802 if (acked > sbavail(&so->so_snd)) {
2803 tp->snd_wnd -= sbavail(&so->so_snd);
2804 mfree = sbcut_locked(&so->so_snd,
2805 (int)sbavail(&so->so_snd));
2808 mfree = sbcut_locked(&so->so_snd, acked);
2809 tp->snd_wnd -= acked;
2812 /* NB: sowwakeup_locked() does an implicit unlock. */
2813 sowwakeup_locked(so);
2815 /* Detect una wraparound. */
2816 if (!IN_RECOVERY(tp->t_flags) &&
2817 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2818 SEQ_LEQ(th->th_ack, tp->snd_recover))
2819 tp->snd_recover = th->th_ack - 1;
2820 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2821 if (IN_RECOVERY(tp->t_flags) &&
2822 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2823 EXIT_RECOVERY(tp->t_flags);
2825 tp->snd_una = th->th_ack;
2826 if (tp->t_flags & TF_SACK_PERMIT) {
2827 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2828 tp->snd_recover = tp->snd_una;
2830 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2831 tp->snd_nxt = tp->snd_una;
2833 switch (tp->t_state) {
2836 * In FIN_WAIT_1 STATE in addition to the processing
2837 * for the ESTABLISHED state if our FIN is now acknowledged
2838 * then enter FIN_WAIT_2.
2840 case TCPS_FIN_WAIT_1:
2841 if (ourfinisacked) {
2843 * If we can't receive any more
2844 * data, then closing user can proceed.
2845 * Starting the timer is contrary to the
2846 * specification, but if we don't get a FIN
2847 * we'll hang forever.
2850 * we should release the tp also, and use a
2853 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2854 soisdisconnected(so);
2855 tcp_timer_activate(tp, TT_2MSL,
2856 (tcp_fast_finwait2_recycle ?
2857 tcp_finwait2_timeout :
2860 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2865 * In CLOSING STATE in addition to the processing for
2866 * the ESTABLISHED state if the ACK acknowledges our FIN
2867 * then enter the TIME-WAIT state, otherwise ignore
2871 if (ourfinisacked) {
2872 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2874 INP_INFO_RUNLOCK(&V_tcbinfo);
2881 * In LAST_ACK, we may still be waiting for data to drain
2882 * and/or to be acked, as well as for the ack of our FIN.
2883 * If our FIN is now acknowledged, delete the TCB,
2884 * enter the closed state and return.
2887 if (ourfinisacked) {
2888 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2897 INP_WLOCK_ASSERT(tp->t_inpcb);
2900 * Update window information.
2901 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2903 if ((thflags & TH_ACK) &&
2904 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2905 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2906 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2907 /* keep track of pure window updates */
2909 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2910 TCPSTAT_INC(tcps_rcvwinupd);
2911 tp->snd_wnd = tiwin;
2912 tp->snd_wl1 = th->th_seq;
2913 tp->snd_wl2 = th->th_ack;
2914 if (tp->snd_wnd > tp->max_sndwnd)
2915 tp->max_sndwnd = tp->snd_wnd;
2920 * Process segments with URG.
2922 if ((thflags & TH_URG) && th->th_urp &&
2923 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2925 * This is a kludge, but if we receive and accept
2926 * random urgent pointers, we'll crash in
2927 * soreceive. It's hard to imagine someone
2928 * actually wanting to send this much urgent data.
2930 SOCKBUF_LOCK(&so->so_rcv);
2931 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2932 th->th_urp = 0; /* XXX */
2933 thflags &= ~TH_URG; /* XXX */
2934 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2935 goto dodata; /* XXX */
2938 * If this segment advances the known urgent pointer,
2939 * then mark the data stream. This should not happen
2940 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2941 * a FIN has been received from the remote side.
2942 * In these states we ignore the URG.
2944 * According to RFC961 (Assigned Protocols),
2945 * the urgent pointer points to the last octet
2946 * of urgent data. We continue, however,
2947 * to consider it to indicate the first octet
2948 * of data past the urgent section as the original
2949 * spec states (in one of two places).
2951 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2952 tp->rcv_up = th->th_seq + th->th_urp;
2953 so->so_oobmark = sbavail(&so->so_rcv) +
2954 (tp->rcv_up - tp->rcv_nxt) - 1;
2955 if (so->so_oobmark == 0)
2956 so->so_rcv.sb_state |= SBS_RCVATMARK;
2958 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2960 SOCKBUF_UNLOCK(&so->so_rcv);
2962 * Remove out of band data so doesn't get presented to user.
2963 * This can happen independent of advancing the URG pointer,
2964 * but if two URG's are pending at once, some out-of-band
2965 * data may creep in... ick.
2967 if (th->th_urp <= (u_long)tlen &&
2968 !(so->so_options & SO_OOBINLINE)) {
2969 /* hdr drop is delayed */
2970 tcp_pulloutofband(so, th, m, drop_hdrlen);
2974 * If no out of band data is expected,
2975 * pull receive urgent pointer along
2976 * with the receive window.
2978 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2979 tp->rcv_up = tp->rcv_nxt;
2982 INP_WLOCK_ASSERT(tp->t_inpcb);
2985 * Process the segment text, merging it into the TCP sequencing queue,
2986 * and arranging for acknowledgment of receipt if necessary.
2987 * This process logically involves adjusting tp->rcv_wnd as data
2988 * is presented to the user (this happens in tcp_usrreq.c,
2989 * case PRU_RCVD). If a FIN has already been received on this
2990 * connection then we just ignore the text.
2992 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
2993 (tp->t_flags & TF_FASTOPEN));
2994 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
2995 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2996 tcp_seq save_start = th->th_seq;
2997 m_adj(m, drop_hdrlen); /* delayed header drop */
2999 * Insert segment which includes th into TCP reassembly queue
3000 * with control block tp. Set thflags to whether reassembly now
3001 * includes a segment with FIN. This handles the common case
3002 * inline (segment is the next to be received on an established
3003 * connection, and the queue is empty), avoiding linkage into
3004 * and removal from the queue and repetition of various
3006 * Set DELACK for segments received in order, but ack
3007 * immediately when segments are out of order (so
3008 * fast retransmit can work).
3010 if (th->th_seq == tp->rcv_nxt &&
3011 LIST_EMPTY(&tp->t_segq) &&
3012 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3014 if (DELAY_ACK(tp, tlen) || tfo_syn)
3015 tp->t_flags |= TF_DELACK;
3017 tp->t_flags |= TF_ACKNOW;
3018 tp->rcv_nxt += tlen;
3019 thflags = th->th_flags & TH_FIN;
3020 TCPSTAT_INC(tcps_rcvpack);
3021 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3022 SOCKBUF_LOCK(&so->so_rcv);
3023 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3026 sbappendstream_locked(&so->so_rcv, m, 0);
3027 /* NB: sorwakeup_locked() does an implicit unlock. */
3028 sorwakeup_locked(so);
3031 * XXX: Due to the header drop above "th" is
3032 * theoretically invalid by now. Fortunately
3033 * m_adj() doesn't actually frees any mbufs
3034 * when trimming from the head.
3036 thflags = tcp_reass(tp, th, &tlen, m);
3037 tp->t_flags |= TF_ACKNOW;
3039 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
3040 tcp_update_sack_list(tp, save_start, save_start + tlen);
3043 * Note the amount of data that peer has sent into
3044 * our window, in order to estimate the sender's
3048 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3049 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3051 len = so->so_rcv.sb_hiwat;
3059 * If FIN is received ACK the FIN and let the user know
3060 * that the connection is closing.
3062 if (thflags & TH_FIN) {
3063 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3066 * If connection is half-synchronized
3067 * (ie NEEDSYN flag on) then delay ACK,
3068 * so it may be piggybacked when SYN is sent.
3069 * Otherwise, since we received a FIN then no
3070 * more input can be expected, send ACK now.
3072 if (tp->t_flags & TF_NEEDSYN)
3073 tp->t_flags |= TF_DELACK;
3075 tp->t_flags |= TF_ACKNOW;
3078 switch (tp->t_state) {
3081 * In SYN_RECEIVED and ESTABLISHED STATES
3082 * enter the CLOSE_WAIT state.
3084 case TCPS_SYN_RECEIVED:
3085 tp->t_starttime = ticks;
3087 case TCPS_ESTABLISHED:
3088 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3092 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3093 * enter the CLOSING state.
3095 case TCPS_FIN_WAIT_1:
3096 tcp_state_change(tp, TCPS_CLOSING);
3100 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3101 * starting the time-wait timer, turning off the other
3104 case TCPS_FIN_WAIT_2:
3105 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3106 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
3107 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3111 INP_INFO_RUNLOCK(&V_tcbinfo);
3115 if (ti_locked == TI_RLOCKED)
3116 INP_INFO_RUNLOCK(&V_tcbinfo);
3117 ti_locked = TI_UNLOCKED;
3120 if (so->so_options & SO_DEBUG)
3121 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3124 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3127 * Return any desired output.
3129 if (needoutput || (tp->t_flags & TF_ACKNOW))
3130 (void) tp->t_fb->tfb_tcp_output(tp);
3133 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3134 __func__, ti_locked));
3135 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3136 INP_WLOCK_ASSERT(tp->t_inpcb);
3138 if (tp->t_flags & TF_DELACK) {
3139 tp->t_flags &= ~TF_DELACK;
3140 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3142 INP_WUNLOCK(tp->t_inpcb);
3147 * Generate an ACK dropping incoming segment if it occupies
3148 * sequence space, where the ACK reflects our state.
3150 * We can now skip the test for the RST flag since all
3151 * paths to this code happen after packets containing
3152 * RST have been dropped.
3154 * In the SYN-RECEIVED state, don't send an ACK unless the
3155 * segment we received passes the SYN-RECEIVED ACK test.
3156 * If it fails send a RST. This breaks the loop in the
3157 * "LAND" DoS attack, and also prevents an ACK storm
3158 * between two listening ports that have been sent forged
3159 * SYN segments, each with the source address of the other.
3161 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3162 (SEQ_GT(tp->snd_una, th->th_ack) ||
3163 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3164 rstreason = BANDLIM_RST_OPENPORT;
3168 if (so->so_options & SO_DEBUG)
3169 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3172 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3173 if (ti_locked == TI_RLOCKED)
3174 INP_INFO_RUNLOCK(&V_tcbinfo);
3175 ti_locked = TI_UNLOCKED;
3177 tp->t_flags |= TF_ACKNOW;
3178 (void) tp->t_fb->tfb_tcp_output(tp);
3179 INP_WUNLOCK(tp->t_inpcb);
3184 if (ti_locked == TI_RLOCKED)
3185 INP_INFO_RUNLOCK(&V_tcbinfo);
3186 ti_locked = TI_UNLOCKED;
3189 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3190 INP_WUNLOCK(tp->t_inpcb);
3192 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3196 if (ti_locked == TI_RLOCKED) {
3197 INP_INFO_RUNLOCK(&V_tcbinfo);
3198 ti_locked = TI_UNLOCKED;
3202 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3206 * Drop space held by incoming segment and return.
3209 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3210 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3213 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3215 INP_WUNLOCK(tp->t_inpcb);
3220 * Issue RST and make ACK acceptable to originator of segment.
3221 * The mbuf must still include the original packet header.
3225 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3226 int tlen, int rstreason)
3232 struct ip6_hdr *ip6;
3236 INP_WLOCK_ASSERT(tp->t_inpcb);
3239 /* Don't bother if destination was broadcast/multicast. */
3240 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3243 if (mtod(m, struct ip *)->ip_v == 6) {
3244 ip6 = mtod(m, struct ip6_hdr *);
3245 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3246 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3248 /* IPv6 anycast check is done at tcp6_input() */
3251 #if defined(INET) && defined(INET6)
3256 ip = mtod(m, struct ip *);
3257 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3258 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3259 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3260 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3265 /* Perform bandwidth limiting. */
3266 if (badport_bandlim(rstreason) < 0)
3269 /* tcp_respond consumes the mbuf chain. */
3270 if (th->th_flags & TH_ACK) {
3271 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3272 th->th_ack, TH_RST);
3274 if (th->th_flags & TH_SYN)
3276 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3277 (tcp_seq)0, TH_RST|TH_ACK);
3285 * Parse TCP options and place in tcpopt.
3288 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3293 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3295 if (opt == TCPOPT_EOL)
3297 if (opt == TCPOPT_NOP)
3303 if (optlen < 2 || optlen > cnt)
3308 if (optlen != TCPOLEN_MAXSEG)
3310 if (!(flags & TO_SYN))
3312 to->to_flags |= TOF_MSS;
3313 bcopy((char *)cp + 2,
3314 (char *)&to->to_mss, sizeof(to->to_mss));
3315 to->to_mss = ntohs(to->to_mss);
3318 if (optlen != TCPOLEN_WINDOW)
3320 if (!(flags & TO_SYN))
3322 to->to_flags |= TOF_SCALE;
3323 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3325 case TCPOPT_TIMESTAMP:
3326 if (optlen != TCPOLEN_TIMESTAMP)
3328 to->to_flags |= TOF_TS;
3329 bcopy((char *)cp + 2,
3330 (char *)&to->to_tsval, sizeof(to->to_tsval));
3331 to->to_tsval = ntohl(to->to_tsval);
3332 bcopy((char *)cp + 6,
3333 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3334 to->to_tsecr = ntohl(to->to_tsecr);
3336 #ifdef TCP_SIGNATURE
3338 * XXX In order to reply to a host which has set the
3339 * TCP_SIGNATURE option in its initial SYN, we have to
3340 * record the fact that the option was observed here
3341 * for the syncache code to perform the correct response.
3343 case TCPOPT_SIGNATURE:
3344 if (optlen != TCPOLEN_SIGNATURE)
3346 to->to_flags |= TOF_SIGNATURE;
3347 to->to_signature = cp + 2;
3350 case TCPOPT_SACK_PERMITTED:
3351 if (optlen != TCPOLEN_SACK_PERMITTED)
3353 if (!(flags & TO_SYN))
3357 to->to_flags |= TOF_SACKPERM;
3360 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3364 to->to_flags |= TOF_SACK;
3365 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3366 to->to_sacks = cp + 2;
3367 TCPSTAT_INC(tcps_sack_rcv_blocks);
3370 case TCPOPT_FAST_OPEN:
3371 if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
3372 (optlen < TCPOLEN_FAST_OPEN_MIN) &&
3373 (optlen > TCPOLEN_FAST_OPEN_MAX))
3375 if (!(flags & TO_SYN))
3377 if (!V_tcp_fastopen_enabled)
3379 to->to_flags |= TOF_FASTOPEN;
3380 to->to_tfo_len = optlen - 2;
3381 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3391 * Pull out of band byte out of a segment so
3392 * it doesn't appear in the user's data queue.
3393 * It is still reflected in the segment length for
3394 * sequencing purposes.
3397 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3400 int cnt = off + th->th_urp - 1;
3403 if (m->m_len > cnt) {
3404 char *cp = mtod(m, caddr_t) + cnt;
3405 struct tcpcb *tp = sototcpcb(so);
3407 INP_WLOCK_ASSERT(tp->t_inpcb);
3410 tp->t_oobflags |= TCPOOB_HAVEDATA;
3411 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3413 if (m->m_flags & M_PKTHDR)
3422 panic("tcp_pulloutofband");
3426 * Collect new round-trip time estimate
3427 * and update averages and current timeout.
3430 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3434 INP_WLOCK_ASSERT(tp->t_inpcb);
3436 TCPSTAT_INC(tcps_rttupdated);
3438 if (tp->t_srtt != 0) {
3440 * srtt is stored as fixed point with 5 bits after the
3441 * binary point (i.e., scaled by 8). The following magic
3442 * is equivalent to the smoothing algorithm in rfc793 with
3443 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3444 * point). Adjust rtt to origin 0.
3446 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3447 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3449 if ((tp->t_srtt += delta) <= 0)
3453 * We accumulate a smoothed rtt variance (actually, a
3454 * smoothed mean difference), then set the retransmit
3455 * timer to smoothed rtt + 4 times the smoothed variance.
3456 * rttvar is stored as fixed point with 4 bits after the
3457 * binary point (scaled by 16). The following is
3458 * equivalent to rfc793 smoothing with an alpha of .75
3459 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3460 * rfc793's wired-in beta.
3464 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3465 if ((tp->t_rttvar += delta) <= 0)
3467 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3468 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3471 * No rtt measurement yet - use the unsmoothed rtt.
3472 * Set the variance to half the rtt (so our first
3473 * retransmit happens at 3*rtt).
3475 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3476 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3477 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3483 * the retransmit should happen at rtt + 4 * rttvar.
3484 * Because of the way we do the smoothing, srtt and rttvar
3485 * will each average +1/2 tick of bias. When we compute
3486 * the retransmit timer, we want 1/2 tick of rounding and
3487 * 1 extra tick because of +-1/2 tick uncertainty in the
3488 * firing of the timer. The bias will give us exactly the
3489 * 1.5 tick we need. But, because the bias is
3490 * statistical, we have to test that we don't drop below
3491 * the minimum feasible timer (which is 2 ticks).
3493 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3494 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3497 * We received an ack for a packet that wasn't retransmitted;
3498 * it is probably safe to discard any error indications we've
3499 * received recently. This isn't quite right, but close enough
3500 * for now (a route might have failed after we sent a segment,
3501 * and the return path might not be symmetrical).
3503 tp->t_softerror = 0;
3507 * Determine a reasonable value for maxseg size.
3508 * If the route is known, check route for mtu.
3509 * If none, use an mss that can be handled on the outgoing interface
3510 * without forcing IP to fragment. If no route is found, route has no mtu,
3511 * or the destination isn't local, use a default, hopefully conservative
3512 * size (usually 512 or the default IP max size, but no more than the mtu
3513 * of the interface), as we can't discover anything about intervening
3514 * gateways or networks. We also initialize the congestion/slow start
3515 * window to be a single segment if the destination isn't local.
3516 * While looking at the routing entry, we also initialize other path-dependent
3517 * parameters from pre-set or cached values in the routing entry.
3519 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3520 * IP options, e.g. IPSEC data, since length of this data may vary, and
3521 * thus it is calculated for every segment separately in tcp_output().
3523 * NOTE that this routine is only called when we process an incoming
3524 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3525 * settings are handled in tcp_mssopt().
3528 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3529 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3533 struct inpcb *inp = tp->t_inpcb;
3534 struct hc_metrics_lite metrics;
3536 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3537 size_t min_protoh = isipv6 ?
3538 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3539 sizeof (struct tcpiphdr);
3541 const size_t min_protoh = sizeof(struct tcpiphdr);
3544 INP_WLOCK_ASSERT(tp->t_inpcb);
3546 if (mtuoffer != -1) {
3547 KASSERT(offer == -1, ("%s: conflict", __func__));
3548 offer = mtuoffer - min_protoh;
3554 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3555 tp->t_maxseg = V_tcp_v6mssdflt;
3558 #if defined(INET) && defined(INET6)
3563 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3564 tp->t_maxseg = V_tcp_mssdflt;
3569 * No route to sender, stay with default mss and return.
3573 * In case we return early we need to initialize metrics
3574 * to a defined state as tcp_hc_get() would do for us
3575 * if there was no cache hit.
3577 if (metricptr != NULL)
3578 bzero(metricptr, sizeof(struct hc_metrics_lite));
3582 /* What have we got? */
3586 * Offer == 0 means that there was no MSS on the SYN
3587 * segment, in this case we use tcp_mssdflt as
3588 * already assigned to t_maxseg above.
3590 offer = tp->t_maxseg;
3595 * Offer == -1 means that we didn't receive SYN yet.
3601 * Prevent DoS attack with too small MSS. Round up
3602 * to at least minmss.
3604 offer = max(offer, V_tcp_minmss);
3608 * rmx information is now retrieved from tcp_hostcache.
3610 tcp_hc_get(&inp->inp_inc, &metrics);
3611 if (metricptr != NULL)
3612 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3615 * If there's a discovered mtu in tcp hostcache, use it.
3616 * Else, use the link mtu.
3618 if (metrics.rmx_mtu)
3619 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3623 mss = maxmtu - min_protoh;
3624 if (!V_path_mtu_discovery &&
3625 !in6_localaddr(&inp->in6p_faddr))
3626 mss = min(mss, V_tcp_v6mssdflt);
3629 #if defined(INET) && defined(INET6)
3634 mss = maxmtu - min_protoh;
3635 if (!V_path_mtu_discovery &&
3636 !in_localaddr(inp->inp_faddr))
3637 mss = min(mss, V_tcp_mssdflt);
3641 * XXX - The above conditional (mss = maxmtu - min_protoh)
3642 * probably violates the TCP spec.
3643 * The problem is that, since we don't know the
3644 * other end's MSS, we are supposed to use a conservative
3645 * default. But, if we do that, then MTU discovery will
3646 * never actually take place, because the conservative
3647 * default is much less than the MTUs typically seen
3648 * on the Internet today. For the moment, we'll sweep
3649 * this under the carpet.
3651 * The conservative default might not actually be a problem
3652 * if the only case this occurs is when sending an initial
3653 * SYN with options and data to a host we've never talked
3654 * to before. Then, they will reply with an MSS value which
3655 * will get recorded and the new parameters should get
3656 * recomputed. For Further Study.
3659 mss = min(mss, offer);
3662 * Sanity check: make sure that maxseg will be large
3663 * enough to allow some data on segments even if the
3664 * all the option space is used (40bytes). Otherwise
3665 * funny things may happen in tcp_output.
3667 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3675 tcp_mss(struct tcpcb *tp, int offer)
3681 struct hc_metrics_lite metrics;
3682 struct tcp_ifcap cap;
3684 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3686 bzero(&cap, sizeof(cap));
3687 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3693 * If there's a pipesize, change the socket buffer to that size,
3694 * don't change if sb_hiwat is different than default (then it
3695 * has been changed on purpose with setsockopt).
3696 * Make the socket buffers an integral number of mss units;
3697 * if the mss is larger than the socket buffer, decrease the mss.
3699 so = inp->inp_socket;
3700 SOCKBUF_LOCK(&so->so_snd);
3701 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3702 bufsize = metrics.rmx_sendpipe;
3704 bufsize = so->so_snd.sb_hiwat;
3708 bufsize = roundup(bufsize, mss);
3709 if (bufsize > sb_max)
3711 if (bufsize > so->so_snd.sb_hiwat)
3712 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3714 SOCKBUF_UNLOCK(&so->so_snd);
3717 SOCKBUF_LOCK(&so->so_rcv);
3718 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3719 bufsize = metrics.rmx_recvpipe;
3721 bufsize = so->so_rcv.sb_hiwat;
3722 if (bufsize > mss) {
3723 bufsize = roundup(bufsize, mss);
3724 if (bufsize > sb_max)
3726 if (bufsize > so->so_rcv.sb_hiwat)
3727 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3729 SOCKBUF_UNLOCK(&so->so_rcv);
3731 /* Check the interface for TSO capabilities. */
3732 if (cap.ifcap & CSUM_TSO) {
3733 tp->t_flags |= TF_TSO;
3734 tp->t_tsomax = cap.tsomax;
3735 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3736 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3741 * Determine the MSS option to send on an outgoing SYN.
3744 tcp_mssopt(struct in_conninfo *inc)
3751 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3754 if (inc->inc_flags & INC_ISIPV6) {
3755 mss = V_tcp_v6mssdflt;
3756 maxmtu = tcp_maxmtu6(inc, NULL);
3757 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3760 #if defined(INET) && defined(INET6)
3765 mss = V_tcp_mssdflt;
3766 maxmtu = tcp_maxmtu(inc, NULL);
3767 min_protoh = sizeof(struct tcpiphdr);
3770 #if defined(INET6) || defined(INET)
3771 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3774 if (maxmtu && thcmtu)
3775 mss = min(maxmtu, thcmtu) - min_protoh;
3776 else if (maxmtu || thcmtu)
3777 mss = max(maxmtu, thcmtu) - min_protoh;
3784 * On a partial ack arrives, force the retransmission of the
3785 * next unacknowledged segment. Do not clear tp->t_dupacks.
3786 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3790 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3792 tcp_seq onxt = tp->snd_nxt;
3793 u_long ocwnd = tp->snd_cwnd;
3794 u_int maxseg = tcp_maxseg(tp);
3796 INP_WLOCK_ASSERT(tp->t_inpcb);
3798 tcp_timer_activate(tp, TT_REXMT, 0);
3800 tp->snd_nxt = th->th_ack;
3802 * Set snd_cwnd to one segment beyond acknowledged offset.
3803 * (tp->snd_una has not yet been updated when this function is called.)
3805 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3806 tp->t_flags |= TF_ACKNOW;
3807 (void) tp->t_fb->tfb_tcp_output(tp);
3808 tp->snd_cwnd = ocwnd;
3809 if (SEQ_GT(onxt, tp->snd_nxt))
3812 * Partial window deflation. Relies on fact that tp->snd_una
3815 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3816 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3819 tp->snd_cwnd += maxseg;
3823 tcp_compute_pipe(struct tcpcb *tp)
3825 return (tp->snd_max - tp->snd_una +
3826 tp->sackhint.sack_bytes_rexmit -
3827 tp->sackhint.sacked_bytes);