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, which size matches
239 * size of struct tcpstat. TCP running connection count is a regular array.
241 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
242 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
243 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
244 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
245 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
246 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
247 "TCP connection counts by TCP state");
250 tcp_vnet_init(const void *unused)
253 COUNTER_ARRAY_ALLOC(VNET(tcps_states), TCP_NSTATES, M_WAITOK);
254 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
256 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
257 tcp_vnet_init, NULL);
261 tcp_vnet_uninit(const void *unused)
264 COUNTER_ARRAY_FREE(VNET(tcps_states), TCP_NSTATES);
265 VNET_PCPUSTAT_FREE(tcpstat);
267 VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
268 tcp_vnet_uninit, NULL);
272 * Kernel module interface for updating tcpstat. The argument is an index
273 * into tcpstat treated as an array.
276 kmod_tcpstat_inc(int statnum)
279 counter_u64_add(VNET(tcpstat)[statnum], 1);
283 * Wrapper for the TCP established input helper hook.
286 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
288 struct tcp_hhook_data hhook_data;
290 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
295 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
301 * CC wrapper hook functions
304 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
306 INP_WLOCK_ASSERT(tp->t_inpcb);
308 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
309 if (tp->snd_cwnd <= tp->snd_wnd)
310 tp->ccv->flags |= CCF_CWND_LIMITED;
312 tp->ccv->flags &= ~CCF_CWND_LIMITED;
314 if (type == CC_ACK) {
315 if (tp->snd_cwnd > tp->snd_ssthresh) {
316 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
317 V_tcp_abc_l_var * tcp_maxseg(tp));
318 if (tp->t_bytes_acked >= tp->snd_cwnd) {
319 tp->t_bytes_acked -= tp->snd_cwnd;
320 tp->ccv->flags |= CCF_ABC_SENTAWND;
323 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
324 tp->t_bytes_acked = 0;
328 if (CC_ALGO(tp)->ack_received != NULL) {
329 /* XXXLAS: Find a way to live without this */
330 tp->ccv->curack = th->th_ack;
331 CC_ALGO(tp)->ack_received(tp->ccv, type);
336 cc_conn_init(struct tcpcb *tp)
338 struct hc_metrics_lite metrics;
339 struct inpcb *inp = tp->t_inpcb;
343 INP_WLOCK_ASSERT(tp->t_inpcb);
345 tcp_hc_get(&inp->inp_inc, &metrics);
346 maxseg = tcp_maxseg(tp);
348 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
350 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
351 TCPSTAT_INC(tcps_usedrtt);
352 if (metrics.rmx_rttvar) {
353 tp->t_rttvar = metrics.rmx_rttvar;
354 TCPSTAT_INC(tcps_usedrttvar);
356 /* default variation is +- 1 rtt */
358 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
360 TCPT_RANGESET(tp->t_rxtcur,
361 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
362 tp->t_rttmin, TCPTV_REXMTMAX);
364 if (metrics.rmx_ssthresh) {
366 * There's some sort of gateway or interface
367 * buffer limit on the path. Use this to set
368 * the slow start threshold, but set the
369 * threshold to no less than 2*mss.
371 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
372 TCPSTAT_INC(tcps_usedssthresh);
376 * Set the initial slow-start flight size.
378 * RFC5681 Section 3.1 specifies the default conservative values.
379 * RFC3390 specifies slightly more aggressive values.
380 * RFC6928 increases it to ten segments.
381 * Support for user specified value for initial flight size.
383 * If a SYN or SYN/ACK was lost and retransmitted, we have to
384 * reduce the initial CWND to one segment as congestion is likely
385 * requiring us to be cautious.
387 if (tp->snd_cwnd == 1)
388 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
389 else if (V_tcp_initcwnd_segments)
390 tp->snd_cwnd = min(V_tcp_initcwnd_segments * maxseg,
391 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
392 else if (V_tcp_do_rfc3390)
393 tp->snd_cwnd = min(4 * maxseg, max(2 * maxseg, 4380));
395 /* Per RFC5681 Section 3.1 */
397 tp->snd_cwnd = 2 * maxseg;
398 else if (maxseg > 1095)
399 tp->snd_cwnd = 3 * maxseg;
401 tp->snd_cwnd = 4 * maxseg;
404 if (CC_ALGO(tp)->conn_init != NULL)
405 CC_ALGO(tp)->conn_init(tp->ccv);
409 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
413 INP_WLOCK_ASSERT(tp->t_inpcb);
417 if (!IN_FASTRECOVERY(tp->t_flags)) {
418 tp->snd_recover = tp->snd_max;
419 if (tp->t_flags & TF_ECN_PERMIT)
420 tp->t_flags |= TF_ECN_SND_CWR;
424 if (!IN_CONGRECOVERY(tp->t_flags)) {
425 TCPSTAT_INC(tcps_ecn_rcwnd);
426 tp->snd_recover = tp->snd_max;
427 if (tp->t_flags & TF_ECN_PERMIT)
428 tp->t_flags |= TF_ECN_SND_CWR;
432 maxseg = tcp_maxseg(tp);
434 tp->t_bytes_acked = 0;
435 EXIT_RECOVERY(tp->t_flags);
436 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
438 tp->snd_cwnd = maxseg;
441 TCPSTAT_INC(tcps_sndrexmitbad);
442 /* RTO was unnecessary, so reset everything. */
443 tp->snd_cwnd = tp->snd_cwnd_prev;
444 tp->snd_ssthresh = tp->snd_ssthresh_prev;
445 tp->snd_recover = tp->snd_recover_prev;
446 if (tp->t_flags & TF_WASFRECOVERY)
447 ENTER_FASTRECOVERY(tp->t_flags);
448 if (tp->t_flags & TF_WASCRECOVERY)
449 ENTER_CONGRECOVERY(tp->t_flags);
450 tp->snd_nxt = tp->snd_max;
451 tp->t_flags &= ~TF_PREVVALID;
456 if (CC_ALGO(tp)->cong_signal != NULL) {
458 tp->ccv->curack = th->th_ack;
459 CC_ALGO(tp)->cong_signal(tp->ccv, type);
464 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
466 INP_WLOCK_ASSERT(tp->t_inpcb);
468 /* XXXLAS: KASSERT that we're in recovery? */
470 if (CC_ALGO(tp)->post_recovery != NULL) {
471 tp->ccv->curack = th->th_ack;
472 CC_ALGO(tp)->post_recovery(tp->ccv);
474 /* XXXLAS: EXIT_RECOVERY ? */
475 tp->t_bytes_acked = 0;
480 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
481 struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
485 tcp_fields_to_net(th);
486 ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
487 tcp_fields_to_host(th);
493 * Indicate whether this ack should be delayed. We can delay the ack if
494 * following conditions are met:
495 * - There is no delayed ack timer in progress.
496 * - Our last ack wasn't a 0-sized window. We never want to delay
497 * the ack that opens up a 0-sized window.
498 * - LRO wasn't used for this segment. We make sure by checking that the
499 * segment size is not larger than the MSS.
501 #define DELAY_ACK(tp, tlen) \
502 ((!tcp_timer_active(tp, TT_DELACK) && \
503 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
504 (tlen <= tp->t_maxseg) && \
505 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
508 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
510 INP_WLOCK_ASSERT(tp->t_inpcb);
512 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
513 switch (iptos & IPTOS_ECN_MASK) {
515 tp->ccv->flags |= CCF_IPHDR_CE;
518 tp->ccv->flags &= ~CCF_IPHDR_CE;
521 tp->ccv->flags &= ~CCF_IPHDR_CE;
525 if (th->th_flags & TH_CWR)
526 tp->ccv->flags |= CCF_TCPHDR_CWR;
528 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
530 if (tp->t_flags & TF_DELACK)
531 tp->ccv->flags |= CCF_DELACK;
533 tp->ccv->flags &= ~CCF_DELACK;
535 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
537 if (tp->ccv->flags & CCF_ACKNOW)
538 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
543 * TCP input handling is split into multiple parts:
544 * tcp6_input is a thin wrapper around tcp_input for the extended
545 * ip6_protox[] call format in ip6_input
546 * tcp_input handles primary segment validation, inpcb lookup and
547 * SYN processing on listen sockets
548 * tcp_do_segment processes the ACK and text of the segment for
549 * establishing, established and closing connections
553 tcp6_input(struct mbuf **mp, int *offp, int proto)
555 struct mbuf *m = *mp;
556 struct in6_ifaddr *ia6;
559 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
562 * draft-itojun-ipv6-tcp-to-anycast
563 * better place to put this in?
565 ip6 = mtod(m, struct ip6_hdr *);
566 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
567 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
570 ifa_free(&ia6->ia_ifa);
571 ip6 = mtod(m, struct ip6_hdr *);
572 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
573 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
574 return (IPPROTO_DONE);
577 ifa_free(&ia6->ia_ifa);
579 return (tcp_input(mp, offp, proto));
584 tcp_input(struct mbuf **mp, int *offp, int proto)
586 struct mbuf *m = *mp;
587 struct tcphdr *th = NULL;
588 struct ip *ip = NULL;
589 struct inpcb *inp = NULL;
590 struct tcpcb *tp = NULL;
591 struct socket *so = NULL;
601 int rstreason = 0; /* For badport_bandlim accounting purposes */
603 uint8_t sig_checked = 0;
606 struct m_tag *fwd_tag = NULL;
608 struct ip6_hdr *ip6 = NULL;
611 const void *ip6 = NULL;
613 struct tcpopt to; /* options in this segment */
614 char *s = NULL; /* address and port logging */
618 * The size of tcp_saveipgen must be the size of the max ip header,
621 u_char tcp_saveipgen[IP6_HDR_LEN];
622 struct tcphdr tcp_savetcp;
627 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
634 TCPSTAT_INC(tcps_rcvtotal);
638 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
640 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
641 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
643 TCPSTAT_INC(tcps_rcvshort);
644 return (IPPROTO_DONE);
648 ip6 = mtod(m, struct ip6_hdr *);
649 th = (struct tcphdr *)((caddr_t)ip6 + off0);
650 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
651 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
652 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
653 th->th_sum = m->m_pkthdr.csum_data;
655 th->th_sum = in6_cksum_pseudo(ip6, tlen,
656 IPPROTO_TCP, m->m_pkthdr.csum_data);
657 th->th_sum ^= 0xffff;
659 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
661 TCPSTAT_INC(tcps_rcvbadsum);
666 * Be proactive about unspecified IPv6 address in source.
667 * As we use all-zero to indicate unbounded/unconnected pcb,
668 * unspecified IPv6 address can be used to confuse us.
670 * Note that packets with unspecified IPv6 destination is
671 * already dropped in ip6_input.
673 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
679 #if defined(INET) && defined(INET6)
685 * Get IP and TCP header together in first mbuf.
686 * Note: IP leaves IP header in first mbuf.
688 if (off0 > sizeof (struct ip)) {
690 off0 = sizeof(struct ip);
692 if (m->m_len < sizeof (struct tcpiphdr)) {
693 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
695 TCPSTAT_INC(tcps_rcvshort);
696 return (IPPROTO_DONE);
699 ip = mtod(m, struct ip *);
700 th = (struct tcphdr *)((caddr_t)ip + off0);
701 tlen = ntohs(ip->ip_len) - off0;
703 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
704 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
705 th->th_sum = m->m_pkthdr.csum_data;
707 th->th_sum = in_pseudo(ip->ip_src.s_addr,
709 htonl(m->m_pkthdr.csum_data + tlen +
711 th->th_sum ^= 0xffff;
713 struct ipovly *ipov = (struct ipovly *)ip;
716 * Checksum extended TCP header and data.
719 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
720 ipov->ih_len = htons(tlen);
721 th->th_sum = in_cksum(m, len);
722 /* Reset length for SDT probes. */
723 ip->ip_len = htons(tlen + off0);
727 TCPSTAT_INC(tcps_rcvbadsum);
730 /* Re-initialization for later version check */
731 ip->ip_v = IPVERSION;
737 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
739 #if defined(INET) && defined(INET6)
747 * Check that TCP offset makes sense,
748 * pull out TCP options and adjust length. XXX
750 off = th->th_off << 2;
751 if (off < sizeof (struct tcphdr) || off > tlen) {
752 TCPSTAT_INC(tcps_rcvbadoff);
755 tlen -= off; /* tlen is used instead of ti->ti_len */
756 if (off > sizeof (struct tcphdr)) {
759 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
760 ip6 = mtod(m, struct ip6_hdr *);
761 th = (struct tcphdr *)((caddr_t)ip6 + off0);
764 #if defined(INET) && defined(INET6)
769 if (m->m_len < sizeof(struct ip) + off) {
770 if ((m = m_pullup(m, sizeof (struct ip) + off))
772 TCPSTAT_INC(tcps_rcvshort);
773 return (IPPROTO_DONE);
775 ip = mtod(m, struct ip *);
776 th = (struct tcphdr *)((caddr_t)ip + off0);
780 optlen = off - sizeof (struct tcphdr);
781 optp = (u_char *)(th + 1);
783 thflags = th->th_flags;
786 * Convert TCP protocol specific fields to host format.
788 tcp_fields_to_host(th);
791 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
793 drop_hdrlen = off0 + off;
796 * Locate pcb for segment; if we're likely to add or remove a
797 * connection then first acquire pcbinfo lock. There are three cases
798 * where we might discover later we need a write lock despite the
799 * flags: ACKs moving a connection out of the syncache, ACKs for a
800 * connection in TIMEWAIT and SYNs not targeting a listening socket.
802 if ((thflags & (TH_FIN | TH_RST)) != 0) {
803 INP_INFO_RLOCK(&V_tcbinfo);
804 ti_locked = TI_RLOCKED;
806 ti_locked = TI_UNLOCKED;
809 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
813 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
815 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
818 #if defined(INET) && !defined(INET6)
819 (m->m_flags & M_IP_NEXTHOP)
822 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
826 if (ti_locked == TI_RLOCKED) {
827 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
829 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
833 if (isipv6 && fwd_tag != NULL) {
834 struct sockaddr_in6 *next_hop6;
836 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
838 * Transparently forwarded. Pretend to be the destination.
839 * Already got one like this?
841 inp = in6_pcblookup_mbuf(&V_tcbinfo,
842 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
843 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
846 * It's new. Try to find the ambushing socket.
847 * Because we've rewritten the destination address,
848 * any hardware-generated hash is ignored.
850 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
851 th->th_sport, &next_hop6->sin6_addr,
852 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
853 th->th_dport, INPLOOKUP_WILDCARD |
854 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
857 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
858 th->th_sport, &ip6->ip6_dst, th->th_dport,
859 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
860 m->m_pkthdr.rcvif, m);
863 #if defined(INET6) && defined(INET)
867 if (fwd_tag != NULL) {
868 struct sockaddr_in *next_hop;
870 next_hop = (struct sockaddr_in *)(fwd_tag+1);
872 * Transparently forwarded. Pretend to be the destination.
873 * already got one like this?
875 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
876 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
877 m->m_pkthdr.rcvif, m);
880 * It's new. Try to find the ambushing socket.
881 * Because we've rewritten the destination address,
882 * any hardware-generated hash is ignored.
884 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
885 th->th_sport, next_hop->sin_addr,
886 next_hop->sin_port ? ntohs(next_hop->sin_port) :
887 th->th_dport, INPLOOKUP_WILDCARD |
888 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
891 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
892 th->th_sport, ip->ip_dst, th->th_dport,
893 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
894 m->m_pkthdr.rcvif, m);
898 * If the INPCB does not exist then all data in the incoming
899 * segment is discarded and an appropriate RST is sent back.
900 * XXX MRT Send RST using which routing table?
904 * Log communication attempts to ports that are not
907 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
908 tcp_log_in_vain == 2) {
909 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
910 log(LOG_INFO, "%s; %s: Connection attempt "
911 "to closed port\n", s, __func__);
914 * When blackholing do not respond with a RST but
915 * completely ignore the segment and drop it.
917 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
921 rstreason = BANDLIM_RST_CLOSEDPORT;
924 INP_WLOCK_ASSERT(inp);
925 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
926 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
927 ((inp->inp_socket == NULL) ||
928 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
929 inp->inp_flowid = m->m_pkthdr.flowid;
930 inp->inp_flowtype = M_HASHTYPE_GET(m);
934 if (isipv6 && ipsec6_in_reject(m, inp)) {
938 if (ipsec4_in_reject(m, inp) != 0) {
944 * Check the minimum TTL for socket.
946 if (inp->inp_ip_minttl != 0) {
949 if (inp->inp_ip_minttl > ip6->ip6_hlim)
953 if (inp->inp_ip_minttl > ip->ip_ttl)
958 * A previous connection in TIMEWAIT state is supposed to catch stray
959 * or duplicate segments arriving late. If this segment was a
960 * legitimate new connection attempt, the old INPCB gets removed and
961 * we can try again to find a listening socket.
963 * At this point, due to earlier optimism, we may hold only an inpcb
964 * lock, and not the inpcbinfo write lock. If so, we need to try to
965 * acquire it, or if that fails, acquire a reference on the inpcb,
966 * drop all locks, acquire a global write lock, and then re-acquire
967 * the inpcb lock. We may at that point discover that another thread
968 * has tried to free the inpcb, in which case we need to loop back
969 * and try to find a new inpcb to deliver to.
971 * XXXRW: It may be time to rethink timewait locking.
974 if (inp->inp_flags & INP_TIMEWAIT) {
975 if (ti_locked == TI_UNLOCKED) {
976 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
979 INP_INFO_RLOCK(&V_tcbinfo);
980 ti_locked = TI_RLOCKED;
982 if (in_pcbrele_wlocked(inp)) {
987 ti_locked = TI_RLOCKED;
989 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
991 if (thflags & TH_SYN)
992 tcp_dooptions(&to, optp, optlen, TO_SYN);
994 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
996 if (tcp_twcheck(inp, &to, th, m, tlen))
998 INP_INFO_RUNLOCK(&V_tcbinfo);
999 return (IPPROTO_DONE);
1002 * The TCPCB may no longer exist if the connection is winding
1003 * down or it is in the CLOSED state. Either way we drop the
1004 * segment and send an appropriate response.
1006 tp = intotcpcb(inp);
1007 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
1008 rstreason = BANDLIM_RST_CLOSEDPORT;
1013 if (tp->t_flags & TF_TOE) {
1014 tcp_offload_input(tp, m);
1015 m = NULL; /* consumed by the TOE driver */
1021 * We've identified a valid inpcb, but it could be that we need an
1022 * inpcbinfo write lock but don't hold it. In this case, attempt to
1023 * acquire using the same strategy as the TIMEWAIT case above. If we
1024 * relock, we have to jump back to 'relocked' as the connection might
1025 * now be in TIMEWAIT.
1028 if ((thflags & (TH_FIN | TH_RST)) != 0)
1029 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1031 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1032 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
1033 !(tp->t_flags & TF_FASTOPEN)))) {
1034 if (ti_locked == TI_UNLOCKED) {
1035 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
1038 INP_INFO_RLOCK(&V_tcbinfo);
1039 ti_locked = TI_RLOCKED;
1041 if (in_pcbrele_wlocked(inp)) {
1047 ti_locked = TI_RLOCKED;
1049 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1053 INP_WLOCK_ASSERT(inp);
1054 if (mac_inpcb_check_deliver(inp, m))
1057 so = inp->inp_socket;
1058 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1060 if (so->so_options & SO_DEBUG) {
1061 ostate = tp->t_state;
1064 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1067 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1070 #endif /* TCPDEBUG */
1072 * When the socket is accepting connections (the INPCB is in LISTEN
1073 * state) we look into the SYN cache if this is a new connection
1074 * attempt or the completion of a previous one.
1076 if (so->so_options & SO_ACCEPTCONN) {
1077 struct in_conninfo inc;
1079 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
1080 "tp not listening", __func__));
1081 bzero(&inc, sizeof(inc));
1084 inc.inc_flags |= INC_ISIPV6;
1085 inc.inc6_faddr = ip6->ip6_src;
1086 inc.inc6_laddr = ip6->ip6_dst;
1090 inc.inc_faddr = ip->ip_src;
1091 inc.inc_laddr = ip->ip_dst;
1093 inc.inc_fport = th->th_sport;
1094 inc.inc_lport = th->th_dport;
1095 inc.inc_fibnum = so->so_fibnum;
1098 * Check for an existing connection attempt in syncache if
1099 * the flag is only ACK. A successful lookup creates a new
1100 * socket appended to the listen queue in SYN_RECEIVED state.
1102 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1104 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1106 * Parse the TCP options here because
1107 * syncookies need access to the reflected
1110 tcp_dooptions(&to, optp, optlen, 0);
1112 * NB: syncache_expand() doesn't unlock
1113 * inp and tcpinfo locks.
1115 if (!syncache_expand(&inc, &to, th, &so, m)) {
1117 * No syncache entry or ACK was not
1118 * for our SYN/ACK. Send a RST.
1119 * NB: syncache did its own logging
1120 * of the failure cause.
1122 rstreason = BANDLIM_RST_OPENPORT;
1130 * We completed the 3-way handshake
1131 * but could not allocate a socket
1132 * either due to memory shortage,
1133 * listen queue length limits or
1134 * global socket limits. Send RST
1135 * or wait and have the remote end
1136 * retransmit the ACK for another
1139 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1140 log(LOG_DEBUG, "%s; %s: Listen socket: "
1141 "Socket allocation failed due to "
1142 "limits or memory shortage, %s\n",
1144 V_tcp_sc_rst_sock_fail ?
1145 "sending RST" : "try again");
1146 if (V_tcp_sc_rst_sock_fail) {
1147 rstreason = BANDLIM_UNLIMITED;
1153 * Socket is created in state SYN_RECEIVED.
1154 * Unlock the listen socket, lock the newly
1155 * created socket and update the tp variable.
1157 INP_WUNLOCK(inp); /* listen socket */
1158 inp = sotoinpcb(so);
1160 * New connection inpcb is already locked by
1161 * syncache_expand().
1163 INP_WLOCK_ASSERT(inp);
1164 tp = intotcpcb(inp);
1165 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1166 ("%s: ", __func__));
1167 #ifdef TCP_SIGNATURE
1168 if (sig_checked == 0) {
1169 tcp_dooptions(&to, optp, optlen,
1170 (thflags & TH_SYN) ? TO_SYN : 0);
1171 if (!tcp_signature_verify_input(m, off0, tlen,
1172 optlen, &to, th, tp->t_flags)) {
1175 * In SYN_SENT state if it receives an
1176 * RST, it is allowed for further
1179 if ((thflags & TH_RST) == 0 ||
1180 (tp->t_state == TCPS_SYN_SENT) == 0)
1188 * Process the segment and the data it
1189 * contains. tcp_do_segment() consumes
1190 * the mbuf chain and unlocks the inpcb.
1192 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1194 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1195 return (IPPROTO_DONE);
1198 * Segment flag validation for new connection attempts:
1200 * Our (SYN|ACK) response was rejected.
1201 * Check with syncache and remove entry to prevent
1204 * NB: syncache_chkrst does its own logging of failure
1207 if (thflags & TH_RST) {
1208 syncache_chkrst(&inc, th);
1212 * We can't do anything without SYN.
1214 if ((thflags & TH_SYN) == 0) {
1215 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1216 log(LOG_DEBUG, "%s; %s: Listen socket: "
1217 "SYN is missing, segment ignored\n",
1219 TCPSTAT_INC(tcps_badsyn);
1223 * (SYN|ACK) is bogus on a listen socket.
1225 if (thflags & TH_ACK) {
1226 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1227 log(LOG_DEBUG, "%s; %s: Listen socket: "
1228 "SYN|ACK invalid, segment rejected\n",
1230 syncache_badack(&inc); /* XXX: Not needed! */
1231 TCPSTAT_INC(tcps_badsyn);
1232 rstreason = BANDLIM_RST_OPENPORT;
1236 * If the drop_synfin option is enabled, drop all
1237 * segments with both the SYN and FIN bits set.
1238 * This prevents e.g. nmap from identifying the
1240 * XXX: Poor reasoning. nmap has other methods
1241 * and is constantly refining its stack detection
1243 * XXX: This is a violation of the TCP specification
1244 * and was used by RFC1644.
1246 if ((thflags & TH_FIN) && V_drop_synfin) {
1247 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1248 log(LOG_DEBUG, "%s; %s: Listen socket: "
1249 "SYN|FIN segment ignored (based on "
1250 "sysctl setting)\n", s, __func__);
1251 TCPSTAT_INC(tcps_badsyn);
1255 * Segment's flags are (SYN) or (SYN|FIN).
1257 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1258 * as they do not affect the state of the TCP FSM.
1259 * The data pointed to by TH_URG and th_urp is ignored.
1261 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1262 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1263 KASSERT(thflags & (TH_SYN),
1264 ("%s: Listen socket: TH_SYN not set", __func__));
1267 * If deprecated address is forbidden,
1268 * we do not accept SYN to deprecated interface
1269 * address to prevent any new inbound connection from
1270 * getting established.
1271 * When we do not accept SYN, we send a TCP RST,
1272 * with deprecated source address (instead of dropping
1273 * it). We compromise it as it is much better for peer
1274 * to send a RST, and RST will be the final packet
1277 * If we do not forbid deprecated addresses, we accept
1278 * the SYN packet. RFC2462 does not suggest dropping
1280 * If we decipher RFC2462 5.5.4, it says like this:
1281 * 1. use of deprecated addr with existing
1282 * communication is okay - "SHOULD continue to be
1284 * 2. use of it with new communication:
1285 * (2a) "SHOULD NOT be used if alternate address
1286 * with sufficient scope is available"
1287 * (2b) nothing mentioned otherwise.
1288 * Here we fall into (2b) case as we have no choice in
1289 * our source address selection - we must obey the peer.
1291 * The wording in RFC2462 is confusing, and there are
1292 * multiple description text for deprecated address
1293 * handling - worse, they are not exactly the same.
1294 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1296 if (isipv6 && !V_ip6_use_deprecated) {
1297 struct in6_ifaddr *ia6;
1299 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1301 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1302 ifa_free(&ia6->ia_ifa);
1303 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1304 log(LOG_DEBUG, "%s; %s: Listen socket: "
1305 "Connection attempt to deprecated "
1306 "IPv6 address rejected\n",
1308 rstreason = BANDLIM_RST_OPENPORT;
1312 ifa_free(&ia6->ia_ifa);
1316 * Basic sanity checks on incoming SYN requests:
1317 * Don't respond if the destination is a link layer
1318 * broadcast according to RFC1122 4.2.3.10, p. 104.
1319 * If it is from this socket it must be forged.
1320 * Don't respond if the source or destination is a
1321 * global or subnet broad- or multicast address.
1322 * Note that it is quite possible to receive unicast
1323 * link-layer packets with a broadcast IP address. Use
1324 * in_broadcast() to find them.
1326 if (m->m_flags & (M_BCAST|M_MCAST)) {
1327 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1328 log(LOG_DEBUG, "%s; %s: Listen socket: "
1329 "Connection attempt from broad- or multicast "
1330 "link layer address ignored\n", s, __func__);
1335 if (th->th_dport == th->th_sport &&
1336 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1337 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1338 log(LOG_DEBUG, "%s; %s: Listen socket: "
1339 "Connection attempt to/from self "
1340 "ignored\n", s, __func__);
1343 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1344 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1345 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1346 log(LOG_DEBUG, "%s; %s: Listen socket: "
1347 "Connection attempt from/to multicast "
1348 "address ignored\n", s, __func__);
1353 #if defined(INET) && defined(INET6)
1358 if (th->th_dport == th->th_sport &&
1359 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1360 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1361 log(LOG_DEBUG, "%s; %s: Listen socket: "
1362 "Connection attempt from/to self "
1363 "ignored\n", s, __func__);
1366 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1367 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1368 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1369 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1370 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1371 log(LOG_DEBUG, "%s; %s: Listen socket: "
1372 "Connection attempt from/to broad- "
1373 "or multicast address ignored\n",
1380 * SYN appears to be valid. Create compressed TCP state
1384 if (so->so_options & SO_DEBUG)
1385 tcp_trace(TA_INPUT, ostate, tp,
1386 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1388 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1389 tcp_dooptions(&to, optp, optlen, TO_SYN);
1391 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
1392 goto new_tfo_socket;
1394 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1397 * Entry added to syncache and mbuf consumed.
1398 * Only the listen socket is unlocked by syncache_add().
1400 if (ti_locked == TI_RLOCKED) {
1401 INP_INFO_RUNLOCK(&V_tcbinfo);
1402 ti_locked = TI_UNLOCKED;
1404 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1405 return (IPPROTO_DONE);
1406 } else if (tp->t_state == TCPS_LISTEN) {
1408 * When a listen socket is torn down the SO_ACCEPTCONN
1409 * flag is removed first while connections are drained
1410 * from the accept queue in a unlock/lock cycle of the
1411 * ACCEPT_LOCK, opening a race condition allowing a SYN
1412 * attempt go through unhandled.
1417 #ifdef TCP_SIGNATURE
1418 if (sig_checked == 0) {
1419 tcp_dooptions(&to, optp, optlen,
1420 (thflags & TH_SYN) ? TO_SYN : 0);
1421 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1425 * In SYN_SENT state if it receives an RST, it is
1426 * allowed for further processing.
1428 if ((thflags & TH_RST) == 0 ||
1429 (tp->t_state == TCPS_SYN_SENT) == 0)
1436 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1439 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1440 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1441 * the inpcb, and unlocks pcbinfo.
1443 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1444 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1445 return (IPPROTO_DONE);
1448 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1450 if (ti_locked == TI_RLOCKED) {
1451 INP_INFO_RUNLOCK(&V_tcbinfo);
1452 ti_locked = TI_UNLOCKED;
1456 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1457 "ti_locked: %d", __func__, ti_locked));
1458 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1463 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1466 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1467 m = NULL; /* mbuf chain got consumed. */
1472 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1474 if (ti_locked == TI_RLOCKED) {
1475 INP_INFO_RUNLOCK(&V_tcbinfo);
1476 ti_locked = TI_UNLOCKED;
1480 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1481 "ti_locked: %d", __func__, ti_locked));
1482 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1490 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1495 return (IPPROTO_DONE);
1499 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1500 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1503 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1504 int rstreason, todrop, win;
1507 struct in_conninfo *inc;
1514 * The size of tcp_saveipgen must be the size of the max ip header,
1517 u_char tcp_saveipgen[IP6_HDR_LEN];
1518 struct tcphdr tcp_savetcp;
1521 thflags = th->th_flags;
1522 inc = &tp->t_inpcb->inp_inc;
1523 tp->sackhint.last_sack_ack = 0;
1527 * If this is either a state-changing packet or current state isn't
1528 * established, we require a write lock on tcbinfo. Otherwise, we
1529 * allow the tcbinfo to be in either alocked or unlocked, as the
1530 * caller may have unnecessarily acquired a write lock due to a race.
1532 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1533 tp->t_state != TCPS_ESTABLISHED) {
1534 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1535 "SYN/FIN/RST/!EST", __func__, ti_locked));
1536 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1539 if (ti_locked == TI_RLOCKED)
1540 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1542 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1543 "ti_locked: %d", __func__, ti_locked));
1544 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1548 INP_WLOCK_ASSERT(tp->t_inpcb);
1549 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1551 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1555 /* Save segment, if requested. */
1556 tcp_pcap_add(th, m, &(tp->t_inpkts));
1560 * Segment received on connection.
1561 * Reset idle time and keep-alive timer.
1562 * XXX: This should be done after segment
1563 * validation to ignore broken/spoofed segs.
1565 tp->t_rcvtime = ticks;
1566 if (TCPS_HAVEESTABLISHED(tp->t_state))
1567 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1570 * Scale up the window into a 32-bit value.
1571 * For the SYN_SENT state the scale is zero.
1573 tiwin = th->th_win << tp->snd_scale;
1576 * TCP ECN processing.
1578 if (tp->t_flags & TF_ECN_PERMIT) {
1579 if (thflags & TH_CWR)
1580 tp->t_flags &= ~TF_ECN_SND_ECE;
1581 switch (iptos & IPTOS_ECN_MASK) {
1583 tp->t_flags |= TF_ECN_SND_ECE;
1584 TCPSTAT_INC(tcps_ecn_ce);
1586 case IPTOS_ECN_ECT0:
1587 TCPSTAT_INC(tcps_ecn_ect0);
1589 case IPTOS_ECN_ECT1:
1590 TCPSTAT_INC(tcps_ecn_ect1);
1594 /* Process a packet differently from RFC3168. */
1595 cc_ecnpkt_handler(tp, th, iptos);
1597 /* Congestion experienced. */
1598 if (thflags & TH_ECE) {
1599 cc_cong_signal(tp, th, CC_ECN);
1604 * Parse options on any incoming segment.
1606 tcp_dooptions(&to, (u_char *)(th + 1),
1607 (th->th_off << 2) - sizeof(struct tcphdr),
1608 (thflags & TH_SYN) ? TO_SYN : 0);
1611 * If echoed timestamp is later than the current time,
1612 * fall back to non RFC1323 RTT calculation. Normalize
1613 * timestamp if syncookies were used when this connection
1616 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1617 to.to_tsecr -= tp->ts_offset;
1618 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1622 * If timestamps were negotiated during SYN/ACK they should
1623 * appear on every segment during this session and vice versa.
1625 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1626 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1627 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1628 "no action\n", s, __func__);
1632 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1633 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1634 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1635 "no action\n", s, __func__);
1641 * Process options only when we get SYN/ACK back. The SYN case
1642 * for incoming connections is handled in tcp_syncache.
1643 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1644 * or <SYN,ACK>) segment itself is never scaled.
1645 * XXX this is traditional behavior, may need to be cleaned up.
1647 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1648 if ((to.to_flags & TOF_SCALE) &&
1649 (tp->t_flags & TF_REQ_SCALE)) {
1650 tp->t_flags |= TF_RCVD_SCALE;
1651 tp->snd_scale = to.to_wscale;
1654 * Initial send window. It will be updated with
1655 * the next incoming segment to the scaled value.
1657 tp->snd_wnd = th->th_win;
1658 if (to.to_flags & TOF_TS) {
1659 tp->t_flags |= TF_RCVD_TSTMP;
1660 tp->ts_recent = to.to_tsval;
1661 tp->ts_recent_age = tcp_ts_getticks();
1663 if (to.to_flags & TOF_MSS)
1664 tcp_mss(tp, to.to_mss);
1665 if ((tp->t_flags & TF_SACK_PERMIT) &&
1666 (to.to_flags & TOF_SACKPERM) == 0)
1667 tp->t_flags &= ~TF_SACK_PERMIT;
1671 * Header prediction: check for the two common cases
1672 * of a uni-directional data xfer. If the packet has
1673 * no control flags, is in-sequence, the window didn't
1674 * change and we're not retransmitting, it's a
1675 * candidate. If the length is zero and the ack moved
1676 * forward, we're the sender side of the xfer. Just
1677 * free the data acked & wake any higher level process
1678 * that was blocked waiting for space. If the length
1679 * is non-zero and the ack didn't move, we're the
1680 * receiver side. If we're getting packets in-order
1681 * (the reassembly queue is empty), add the data to
1682 * the socket buffer and note that we need a delayed ack.
1683 * Make sure that the hidden state-flags are also off.
1684 * Since we check for TCPS_ESTABLISHED first, it can only
1687 if (tp->t_state == TCPS_ESTABLISHED &&
1688 th->th_seq == tp->rcv_nxt &&
1689 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1690 tp->snd_nxt == tp->snd_max &&
1691 tiwin && tiwin == tp->snd_wnd &&
1692 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1693 LIST_EMPTY(&tp->t_segq) &&
1694 ((to.to_flags & TOF_TS) == 0 ||
1695 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1698 * If last ACK falls within this segment's sequence numbers,
1699 * record the timestamp.
1700 * NOTE that the test is modified according to the latest
1701 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1703 if ((to.to_flags & TOF_TS) != 0 &&
1704 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1705 tp->ts_recent_age = tcp_ts_getticks();
1706 tp->ts_recent = to.to_tsval;
1710 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1711 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1712 !IN_RECOVERY(tp->t_flags) &&
1713 (to.to_flags & TOF_SACK) == 0 &&
1714 TAILQ_EMPTY(&tp->snd_holes)) {
1716 * This is a pure ack for outstanding data.
1718 if (ti_locked == TI_RLOCKED)
1719 INP_INFO_RUNLOCK(&V_tcbinfo);
1720 ti_locked = TI_UNLOCKED;
1722 TCPSTAT_INC(tcps_predack);
1725 * "bad retransmit" recovery.
1727 if (tp->t_rxtshift == 1 &&
1728 tp->t_flags & TF_PREVVALID &&
1729 (int)(ticks - tp->t_badrxtwin) < 0) {
1730 cc_cong_signal(tp, th, CC_RTO_ERR);
1734 * Recalculate the transmit timer / rtt.
1736 * Some boxes send broken timestamp replies
1737 * during the SYN+ACK phase, ignore
1738 * timestamps of 0 or we could calculate a
1739 * huge RTT and blow up the retransmit timer.
1741 if ((to.to_flags & TOF_TS) != 0 &&
1745 t = tcp_ts_getticks() - to.to_tsecr;
1746 if (!tp->t_rttlow || tp->t_rttlow > t)
1749 TCP_TS_TO_TICKS(t) + 1);
1750 } else if (tp->t_rtttime &&
1751 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1752 if (!tp->t_rttlow ||
1753 tp->t_rttlow > ticks - tp->t_rtttime)
1754 tp->t_rttlow = ticks - tp->t_rtttime;
1756 ticks - tp->t_rtttime);
1758 acked = BYTES_THIS_ACK(tp, th);
1760 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1761 hhook_run_tcp_est_in(tp, th, &to);
1763 TCPSTAT_INC(tcps_rcvackpack);
1764 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1765 sbdrop(&so->so_snd, acked);
1766 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1767 SEQ_LEQ(th->th_ack, tp->snd_recover))
1768 tp->snd_recover = th->th_ack - 1;
1771 * Let the congestion control algorithm update
1772 * congestion control related information. This
1773 * typically means increasing the congestion
1776 cc_ack_received(tp, th, CC_ACK);
1778 tp->snd_una = th->th_ack;
1780 * Pull snd_wl2 up to prevent seq wrap relative
1783 tp->snd_wl2 = th->th_ack;
1788 * If all outstanding data are acked, stop
1789 * retransmit timer, otherwise restart timer
1790 * using current (possibly backed-off) value.
1791 * If process is waiting for space,
1792 * wakeup/selwakeup/signal. If data
1793 * are ready to send, let tcp_output
1794 * decide between more output or persist.
1797 if (so->so_options & SO_DEBUG)
1798 tcp_trace(TA_INPUT, ostate, tp,
1799 (void *)tcp_saveipgen,
1802 TCP_PROBE3(debug__input, tp, th,
1803 mtod(m, const char *));
1804 if (tp->snd_una == tp->snd_max)
1805 tcp_timer_activate(tp, TT_REXMT, 0);
1806 else if (!tcp_timer_active(tp, TT_PERSIST))
1807 tcp_timer_activate(tp, TT_REXMT,
1810 if (sbavail(&so->so_snd))
1811 (void) tp->t_fb->tfb_tcp_output(tp);
1814 } else if (th->th_ack == tp->snd_una &&
1815 tlen <= sbspace(&so->so_rcv)) {
1816 int newsize = 0; /* automatic sockbuf scaling */
1819 * This is a pure, in-sequence data packet with
1820 * nothing on the reassembly queue and we have enough
1821 * buffer space to take it.
1823 if (ti_locked == TI_RLOCKED)
1824 INP_INFO_RUNLOCK(&V_tcbinfo);
1825 ti_locked = TI_UNLOCKED;
1827 /* Clean receiver SACK report if present */
1828 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1829 tcp_clean_sackreport(tp);
1830 TCPSTAT_INC(tcps_preddat);
1831 tp->rcv_nxt += tlen;
1833 * Pull snd_wl1 up to prevent seq wrap relative to
1836 tp->snd_wl1 = th->th_seq;
1838 * Pull rcv_up up to prevent seq wrap relative to
1841 tp->rcv_up = tp->rcv_nxt;
1842 TCPSTAT_INC(tcps_rcvpack);
1843 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1845 if (so->so_options & SO_DEBUG)
1846 tcp_trace(TA_INPUT, ostate, tp,
1847 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1849 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1852 * Automatic sizing of receive socket buffer. Often the send
1853 * buffer size is not optimally adjusted to the actual network
1854 * conditions at hand (delay bandwidth product). Setting the
1855 * buffer size too small limits throughput on links with high
1856 * bandwidth and high delay (eg. trans-continental/oceanic links).
1858 * On the receive side the socket buffer memory is only rarely
1859 * used to any significant extent. This allows us to be much
1860 * more aggressive in scaling the receive socket buffer. For
1861 * the case that the buffer space is actually used to a large
1862 * extent and we run out of kernel memory we can simply drop
1863 * the new segments; TCP on the sender will just retransmit it
1864 * later. Setting the buffer size too big may only consume too
1865 * much kernel memory if the application doesn't read() from
1866 * the socket or packet loss or reordering makes use of the
1869 * The criteria to step up the receive buffer one notch are:
1870 * 1. Application has not set receive buffer size with
1871 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1872 * 2. the number of bytes received during the time it takes
1873 * one timestamp to be reflected back to us (the RTT);
1874 * 3. received bytes per RTT is within seven eighth of the
1875 * current socket buffer size;
1876 * 4. receive buffer size has not hit maximal automatic size;
1878 * This algorithm does one step per RTT at most and only if
1879 * we receive a bulk stream w/o packet losses or reorderings.
1880 * Shrinking the buffer during idle times is not necessary as
1881 * it doesn't consume any memory when idle.
1883 * TODO: Only step up if the application is actually serving
1884 * the buffer to better manage the socket buffer resources.
1886 if (V_tcp_do_autorcvbuf &&
1887 (to.to_flags & TOF_TS) &&
1889 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1890 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1891 to.to_tsecr - tp->rfbuf_ts < hz) {
1893 (so->so_rcv.sb_hiwat / 8 * 7) &&
1894 so->so_rcv.sb_hiwat <
1895 V_tcp_autorcvbuf_max) {
1897 min(so->so_rcv.sb_hiwat +
1898 V_tcp_autorcvbuf_inc,
1899 V_tcp_autorcvbuf_max);
1901 /* Start over with next RTT. */
1905 tp->rfbuf_cnt += tlen; /* add up */
1908 /* Add data to socket buffer. */
1909 SOCKBUF_LOCK(&so->so_rcv);
1910 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1914 * Set new socket buffer size.
1915 * Give up when limit is reached.
1918 if (!sbreserve_locked(&so->so_rcv,
1920 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1921 m_adj(m, drop_hdrlen); /* delayed header drop */
1922 sbappendstream_locked(&so->so_rcv, m, 0);
1924 /* NB: sorwakeup_locked() does an implicit unlock. */
1925 sorwakeup_locked(so);
1926 if (DELAY_ACK(tp, tlen)) {
1927 tp->t_flags |= TF_DELACK;
1929 tp->t_flags |= TF_ACKNOW;
1930 tp->t_fb->tfb_tcp_output(tp);
1937 * Calculate amount of space in receive window,
1938 * and then do TCP input processing.
1939 * Receive window is amount of space in rcv queue,
1940 * but not less than advertised window.
1942 win = sbspace(&so->so_rcv);
1945 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1947 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1951 switch (tp->t_state) {
1954 * If the state is SYN_RECEIVED:
1955 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1957 case TCPS_SYN_RECEIVED:
1958 if ((thflags & TH_ACK) &&
1959 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1960 SEQ_GT(th->th_ack, tp->snd_max))) {
1961 rstreason = BANDLIM_RST_OPENPORT;
1965 if (tp->t_flags & TF_FASTOPEN) {
1967 * When a TFO connection is in SYN_RECEIVED, the
1968 * only valid packets are the initial SYN, a
1969 * retransmit/copy of the initial SYN (possibly with
1970 * a subset of the original data), a valid ACK, a
1973 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1974 rstreason = BANDLIM_RST_OPENPORT;
1976 } else if (thflags & TH_SYN) {
1977 /* non-initial SYN is ignored */
1978 if ((tcp_timer_active(tp, TT_DELACK) ||
1979 tcp_timer_active(tp, TT_REXMT)))
1981 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1989 * If the state is SYN_SENT:
1990 * if seg contains an ACK, but not for our SYN, drop the input.
1991 * if seg contains a RST, then drop the connection.
1992 * if seg does not contain SYN, then drop it.
1993 * Otherwise this is an acceptable SYN segment
1994 * initialize tp->rcv_nxt and tp->irs
1995 * if seg contains ack then advance tp->snd_una
1996 * if seg contains an ECE and ECN support is enabled, the stream
1998 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1999 * arrange for segment to be acked (eventually)
2000 * continue processing rest of data/controls, beginning with URG
2003 if ((thflags & TH_ACK) &&
2004 (SEQ_LEQ(th->th_ack, tp->iss) ||
2005 SEQ_GT(th->th_ack, tp->snd_max))) {
2006 rstreason = BANDLIM_UNLIMITED;
2009 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2010 TCP_PROBE5(connect__refused, NULL, tp,
2011 mtod(m, const char *), tp, th);
2012 tp = tcp_drop(tp, ECONNREFUSED);
2014 if (thflags & TH_RST)
2016 if (!(thflags & TH_SYN))
2019 tp->irs = th->th_seq;
2021 if (thflags & TH_ACK) {
2022 TCPSTAT_INC(tcps_connects);
2025 mac_socketpeer_set_from_mbuf(m, so);
2027 /* Do window scaling on this connection? */
2028 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2029 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2030 tp->rcv_scale = tp->request_r_scale;
2032 tp->rcv_adv += imin(tp->rcv_wnd,
2033 TCP_MAXWIN << tp->rcv_scale);
2034 tp->snd_una++; /* SYN is acked */
2036 * If there's data, delay ACK; if there's also a FIN
2037 * ACKNOW will be turned on later.
2039 if (DELAY_ACK(tp, tlen) && tlen != 0)
2040 tcp_timer_activate(tp, TT_DELACK,
2043 tp->t_flags |= TF_ACKNOW;
2045 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
2046 tp->t_flags |= TF_ECN_PERMIT;
2047 TCPSTAT_INC(tcps_ecn_shs);
2051 * Received <SYN,ACK> in SYN_SENT[*] state.
2053 * SYN_SENT --> ESTABLISHED
2054 * SYN_SENT* --> FIN_WAIT_1
2056 tp->t_starttime = ticks;
2057 if (tp->t_flags & TF_NEEDFIN) {
2058 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2059 tp->t_flags &= ~TF_NEEDFIN;
2062 tcp_state_change(tp, TCPS_ESTABLISHED);
2063 TCP_PROBE5(connect__established, NULL, tp,
2064 mtod(m, const char *), tp, th);
2066 tcp_timer_activate(tp, TT_KEEP,
2071 * Received initial SYN in SYN-SENT[*] state =>
2072 * simultaneous open.
2073 * If it succeeds, connection is * half-synchronized.
2074 * Otherwise, do 3-way handshake:
2075 * SYN-SENT -> SYN-RECEIVED
2076 * SYN-SENT* -> SYN-RECEIVED*
2078 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2079 tcp_timer_activate(tp, TT_REXMT, 0);
2080 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2083 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
2084 "ti_locked %d", __func__, ti_locked));
2085 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2086 INP_WLOCK_ASSERT(tp->t_inpcb);
2089 * Advance th->th_seq to correspond to first data byte.
2090 * If data, trim to stay within window,
2091 * dropping FIN if necessary.
2094 if (tlen > tp->rcv_wnd) {
2095 todrop = tlen - tp->rcv_wnd;
2099 TCPSTAT_INC(tcps_rcvpackafterwin);
2100 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2102 tp->snd_wl1 = th->th_seq - 1;
2103 tp->rcv_up = th->th_seq;
2105 * Client side of transaction: already sent SYN and data.
2106 * If the remote host used T/TCP to validate the SYN,
2107 * our data will be ACK'd; if so, enter normal data segment
2108 * processing in the middle of step 5, ack processing.
2109 * Otherwise, goto step 6.
2111 if (thflags & TH_ACK)
2117 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2118 * do normal processing.
2120 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2124 break; /* continue normal processing */
2128 * States other than LISTEN or SYN_SENT.
2129 * First check the RST flag and sequence number since reset segments
2130 * are exempt from the timestamp and connection count tests. This
2131 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2132 * below which allowed reset segments in half the sequence space
2133 * to fall though and be processed (which gives forged reset
2134 * segments with a random sequence number a 50 percent chance of
2135 * killing a connection).
2136 * Then check timestamp, if present.
2137 * Then check the connection count, if present.
2138 * Then check that at least some bytes of segment are within
2139 * receive window. If segment begins before rcv_nxt,
2140 * drop leading data (and SYN); if nothing left, just ack.
2142 if (thflags & TH_RST) {
2144 * RFC5961 Section 3.2
2146 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2147 * - If RST is in window, we send challenge ACK.
2149 * Note: to take into account delayed ACKs, we should
2150 * test against last_ack_sent instead of rcv_nxt.
2151 * Note 2: we handle special case of closed window, not
2152 * covered by the RFC.
2154 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2155 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2156 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2158 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2159 KASSERT(ti_locked == TI_RLOCKED,
2160 ("%s: TH_RST ti_locked %d, th %p tp %p",
2161 __func__, ti_locked, th, tp));
2162 KASSERT(tp->t_state != TCPS_SYN_SENT,
2163 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2166 if (V_tcp_insecure_rst ||
2167 tp->last_ack_sent == th->th_seq) {
2168 TCPSTAT_INC(tcps_drops);
2169 /* Drop the connection. */
2170 switch (tp->t_state) {
2171 case TCPS_SYN_RECEIVED:
2172 so->so_error = ECONNREFUSED;
2174 case TCPS_ESTABLISHED:
2175 case TCPS_FIN_WAIT_1:
2176 case TCPS_FIN_WAIT_2:
2177 case TCPS_CLOSE_WAIT:
2178 so->so_error = ECONNRESET;
2180 tcp_state_change(tp, TCPS_CLOSED);
2186 TCPSTAT_INC(tcps_badrst);
2187 /* Send challenge ACK. */
2188 tcp_respond(tp, mtod(m, void *), th, m,
2189 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2190 tp->last_ack_sent = tp->rcv_nxt;
2198 * RFC5961 Section 4.2
2199 * Send challenge ACK for any SYN in synchronized state.
2201 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2202 tp->t_state != TCPS_SYN_RECEIVED) {
2203 KASSERT(ti_locked == TI_RLOCKED,
2204 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2205 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2207 TCPSTAT_INC(tcps_badsyn);
2208 if (V_tcp_insecure_syn &&
2209 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2210 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2211 tp = tcp_drop(tp, ECONNRESET);
2212 rstreason = BANDLIM_UNLIMITED;
2214 /* Send challenge ACK. */
2215 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2216 tp->snd_nxt, TH_ACK);
2217 tp->last_ack_sent = tp->rcv_nxt;
2224 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2225 * and it's less than ts_recent, drop it.
2227 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2228 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2230 /* Check to see if ts_recent is over 24 days old. */
2231 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2233 * Invalidate ts_recent. If this segment updates
2234 * ts_recent, the age will be reset later and ts_recent
2235 * will get a valid value. If it does not, setting
2236 * ts_recent to zero will at least satisfy the
2237 * requirement that zero be placed in the timestamp
2238 * echo reply when ts_recent isn't valid. The
2239 * age isn't reset until we get a valid ts_recent
2240 * because we don't want out-of-order segments to be
2241 * dropped when ts_recent is old.
2245 TCPSTAT_INC(tcps_rcvduppack);
2246 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2247 TCPSTAT_INC(tcps_pawsdrop);
2255 * In the SYN-RECEIVED state, validate that the packet belongs to
2256 * this connection before trimming the data to fit the receive
2257 * window. Check the sequence number versus IRS since we know
2258 * the sequence numbers haven't wrapped. This is a partial fix
2259 * for the "LAND" DoS attack.
2261 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2262 rstreason = BANDLIM_RST_OPENPORT;
2266 todrop = tp->rcv_nxt - th->th_seq;
2268 if (thflags & TH_SYN) {
2278 * Following if statement from Stevens, vol. 2, p. 960.
2281 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2283 * Any valid FIN must be to the left of the window.
2284 * At this point the FIN must be a duplicate or out
2285 * of sequence; drop it.
2290 * Send an ACK to resynchronize and drop any data.
2291 * But keep on processing for RST or ACK.
2293 tp->t_flags |= TF_ACKNOW;
2295 TCPSTAT_INC(tcps_rcvduppack);
2296 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2298 TCPSTAT_INC(tcps_rcvpartduppack);
2299 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2301 drop_hdrlen += todrop; /* drop from the top afterwards */
2302 th->th_seq += todrop;
2304 if (th->th_urp > todrop)
2305 th->th_urp -= todrop;
2313 * If new data are received on a connection after the
2314 * user processes are gone, then RST the other end.
2316 if ((so->so_state & SS_NOFDREF) &&
2317 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2318 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
2319 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2320 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2322 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2323 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2324 "after socket was closed, "
2325 "sending RST and removing tcpcb\n",
2326 s, __func__, tcpstates[tp->t_state], tlen);
2330 TCPSTAT_INC(tcps_rcvafterclose);
2331 rstreason = BANDLIM_UNLIMITED;
2336 * If segment ends after window, drop trailing data
2337 * (and PUSH and FIN); if nothing left, just ACK.
2339 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2341 TCPSTAT_INC(tcps_rcvpackafterwin);
2342 if (todrop >= tlen) {
2343 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2345 * If window is closed can only take segments at
2346 * window edge, and have to drop data and PUSH from
2347 * incoming segments. Continue processing, but
2348 * remember to ack. Otherwise, drop segment
2351 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2352 tp->t_flags |= TF_ACKNOW;
2353 TCPSTAT_INC(tcps_rcvwinprobe);
2357 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2360 thflags &= ~(TH_PUSH|TH_FIN);
2364 * If last ACK falls within this segment's sequence numbers,
2365 * record its timestamp.
2367 * 1) That the test incorporates suggestions from the latest
2368 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2369 * 2) That updating only on newer timestamps interferes with
2370 * our earlier PAWS tests, so this check should be solely
2371 * predicated on the sequence space of this segment.
2372 * 3) That we modify the segment boundary check to be
2373 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2374 * instead of RFC1323's
2375 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2376 * This modified check allows us to overcome RFC1323's
2377 * limitations as described in Stevens TCP/IP Illustrated
2378 * Vol. 2 p.869. In such cases, we can still calculate the
2379 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2381 if ((to.to_flags & TOF_TS) != 0 &&
2382 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2383 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2384 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2385 tp->ts_recent_age = tcp_ts_getticks();
2386 tp->ts_recent = to.to_tsval;
2390 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2391 * flag is on (half-synchronized state), then queue data for
2392 * later processing; else drop segment and return.
2394 if ((thflags & TH_ACK) == 0) {
2395 if (tp->t_state == TCPS_SYN_RECEIVED ||
2396 (tp->t_flags & TF_NEEDSYN)) {
2398 if (tp->t_state == TCPS_SYN_RECEIVED &&
2399 tp->t_flags & TF_FASTOPEN) {
2400 tp->snd_wnd = tiwin;
2405 } else if (tp->t_flags & TF_ACKNOW)
2414 switch (tp->t_state) {
2417 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2418 * ESTABLISHED state and continue processing.
2419 * The ACK was checked above.
2421 case TCPS_SYN_RECEIVED:
2423 TCPSTAT_INC(tcps_connects);
2425 /* Do window scaling? */
2426 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2427 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2428 tp->rcv_scale = tp->request_r_scale;
2429 tp->snd_wnd = tiwin;
2433 * SYN-RECEIVED -> ESTABLISHED
2434 * SYN-RECEIVED* -> FIN-WAIT-1
2436 tp->t_starttime = ticks;
2437 if (tp->t_flags & TF_NEEDFIN) {
2438 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2439 tp->t_flags &= ~TF_NEEDFIN;
2441 tcp_state_change(tp, TCPS_ESTABLISHED);
2442 TCP_PROBE5(accept__established, NULL, tp,
2443 mtod(m, const char *), tp, th);
2445 if (tp->t_tfo_pending) {
2446 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2447 tp->t_tfo_pending = NULL;
2450 * Account for the ACK of our SYN prior to
2451 * regular ACK processing below.
2456 * TFO connections call cc_conn_init() during SYN
2457 * processing. Calling it again here for such
2458 * connections is not harmless as it would undo the
2459 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2462 if (!(tp->t_flags & TF_FASTOPEN))
2465 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2468 * If segment contains data or ACK, will call tcp_reass()
2469 * later; if not, do so now to pass queued data to user.
2471 if (tlen == 0 && (thflags & TH_FIN) == 0)
2472 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2474 tp->snd_wl1 = th->th_seq - 1;
2478 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2479 * ACKs. If the ack is in the range
2480 * tp->snd_una < th->th_ack <= tp->snd_max
2481 * then advance tp->snd_una to th->th_ack and drop
2482 * data from the retransmission queue. If this ACK reflects
2483 * more up to date window information we update our window information.
2485 case TCPS_ESTABLISHED:
2486 case TCPS_FIN_WAIT_1:
2487 case TCPS_FIN_WAIT_2:
2488 case TCPS_CLOSE_WAIT:
2491 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2492 TCPSTAT_INC(tcps_rcvacktoomuch);
2495 if ((tp->t_flags & TF_SACK_PERMIT) &&
2496 ((to.to_flags & TOF_SACK) ||
2497 !TAILQ_EMPTY(&tp->snd_holes)))
2498 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2501 * Reset the value so that previous (valid) value
2502 * from the last ack with SACK doesn't get used.
2504 tp->sackhint.sacked_bytes = 0;
2506 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2507 hhook_run_tcp_est_in(tp, th, &to);
2509 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2512 maxseg = tcp_maxseg(tp);
2514 (tiwin == tp->snd_wnd ||
2515 (tp->t_flags & TF_SACK_PERMIT))) {
2517 * If this is the first time we've seen a
2518 * FIN from the remote, this is not a
2519 * duplicate and it needs to be processed
2520 * normally. This happens during a
2521 * simultaneous close.
2523 if ((thflags & TH_FIN) &&
2524 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2528 TCPSTAT_INC(tcps_rcvdupack);
2530 * If we have outstanding data (other than
2531 * a window probe), this is a completely
2532 * duplicate ack (ie, window info didn't
2533 * change and FIN isn't set),
2534 * the ack is the biggest we've
2535 * seen and we've seen exactly our rexmt
2536 * threshold of them, assume a packet
2537 * has been dropped and retransmit it.
2538 * Kludge snd_nxt & the congestion
2539 * window so we send only this one
2542 * We know we're losing at the current
2543 * window size so do congestion avoidance
2544 * (set ssthresh to half the current window
2545 * and pull our congestion window back to
2546 * the new ssthresh).
2548 * Dup acks mean that packets have left the
2549 * network (they're now cached at the receiver)
2550 * so bump cwnd by the amount in the receiver
2551 * to keep a constant cwnd packets in the
2554 * When using TCP ECN, notify the peer that
2555 * we reduced the cwnd.
2558 * Following 2 kinds of acks should not affect
2561 * 2) Acks with SACK but without any new SACK
2562 * information in them. These could result from
2563 * any anomaly in the network like a switch
2564 * duplicating packets or a possible DoS attack.
2566 if (th->th_ack != tp->snd_una ||
2567 ((tp->t_flags & TF_SACK_PERMIT) &&
2570 else if (!tcp_timer_active(tp, TT_REXMT))
2572 else if (++tp->t_dupacks > tcprexmtthresh ||
2573 IN_FASTRECOVERY(tp->t_flags)) {
2574 cc_ack_received(tp, th, CC_DUPACK);
2575 if ((tp->t_flags & TF_SACK_PERMIT) &&
2576 IN_FASTRECOVERY(tp->t_flags)) {
2580 * Compute the amount of data in flight first.
2581 * We can inject new data into the pipe iff
2582 * we have less than 1/2 the original window's
2583 * worth of data in flight.
2585 if (V_tcp_do_rfc6675_pipe)
2586 awnd = tcp_compute_pipe(tp);
2588 awnd = (tp->snd_nxt - tp->snd_fack) +
2589 tp->sackhint.sack_bytes_rexmit;
2591 if (awnd < tp->snd_ssthresh) {
2592 tp->snd_cwnd += maxseg;
2593 if (tp->snd_cwnd > tp->snd_ssthresh)
2594 tp->snd_cwnd = tp->snd_ssthresh;
2597 tp->snd_cwnd += maxseg;
2598 (void) tp->t_fb->tfb_tcp_output(tp);
2600 } else if (tp->t_dupacks == tcprexmtthresh) {
2601 tcp_seq onxt = tp->snd_nxt;
2604 * If we're doing sack, check to
2605 * see if we're already in sack
2606 * recovery. If we're not doing sack,
2607 * check to see if we're in newreno
2610 if (tp->t_flags & TF_SACK_PERMIT) {
2611 if (IN_FASTRECOVERY(tp->t_flags)) {
2616 if (SEQ_LEQ(th->th_ack,
2622 /* Congestion signal before ack. */
2623 cc_cong_signal(tp, th, CC_NDUPACK);
2624 cc_ack_received(tp, th, CC_DUPACK);
2625 tcp_timer_activate(tp, TT_REXMT, 0);
2627 if (tp->t_flags & TF_SACK_PERMIT) {
2629 tcps_sack_recovery_episode);
2630 tp->sack_newdata = tp->snd_nxt;
2631 tp->snd_cwnd = maxseg;
2632 (void) tp->t_fb->tfb_tcp_output(tp);
2635 tp->snd_nxt = th->th_ack;
2636 tp->snd_cwnd = maxseg;
2637 (void) tp->t_fb->tfb_tcp_output(tp);
2638 KASSERT(tp->snd_limited <= 2,
2639 ("%s: tp->snd_limited too big",
2641 tp->snd_cwnd = tp->snd_ssthresh +
2643 (tp->t_dupacks - tp->snd_limited);
2644 if (SEQ_GT(onxt, tp->snd_nxt))
2647 } else if (V_tcp_do_rfc3042) {
2649 * Process first and second duplicate
2650 * ACKs. Each indicates a segment
2651 * leaving the network, creating room
2652 * for more. Make sure we can send a
2653 * packet on reception of each duplicate
2654 * ACK by increasing snd_cwnd by one
2655 * segment. Restore the original
2656 * snd_cwnd after packet transmission.
2658 cc_ack_received(tp, th, CC_DUPACK);
2659 u_long oldcwnd = tp->snd_cwnd;
2660 tcp_seq oldsndmax = tp->snd_max;
2664 KASSERT(tp->t_dupacks == 1 ||
2666 ("%s: dupacks not 1 or 2",
2668 if (tp->t_dupacks == 1)
2669 tp->snd_limited = 0;
2671 (tp->snd_nxt - tp->snd_una) +
2672 (tp->t_dupacks - tp->snd_limited) *
2675 * Only call tcp_output when there
2676 * is new data available to be sent.
2677 * Otherwise we would send pure ACKs.
2679 SOCKBUF_LOCK(&so->so_snd);
2680 avail = sbavail(&so->so_snd) -
2681 (tp->snd_nxt - tp->snd_una);
2682 SOCKBUF_UNLOCK(&so->so_snd);
2684 (void) tp->t_fb->tfb_tcp_output(tp);
2685 sent = tp->snd_max - oldsndmax;
2686 if (sent > maxseg) {
2687 KASSERT((tp->t_dupacks == 2 &&
2688 tp->snd_limited == 0) ||
2689 (sent == maxseg + 1 &&
2690 tp->t_flags & TF_SENTFIN),
2691 ("%s: sent too much",
2693 tp->snd_limited = 2;
2694 } else if (sent > 0)
2696 tp->snd_cwnd = oldcwnd;
2703 * This ack is advancing the left edge, reset the
2708 * If this ack also has new SACK info, increment the
2709 * counter as per rfc6675.
2711 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2715 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2716 ("%s: th_ack <= snd_una", __func__));
2719 * If the congestion window was inflated to account
2720 * for the other side's cached packets, retract it.
2722 if (IN_FASTRECOVERY(tp->t_flags)) {
2723 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2724 if (tp->t_flags & TF_SACK_PERMIT)
2725 tcp_sack_partialack(tp, th);
2727 tcp_newreno_partial_ack(tp, th);
2729 cc_post_recovery(tp, th);
2732 * If we reach this point, ACK is not a duplicate,
2733 * i.e., it ACKs something we sent.
2735 if (tp->t_flags & TF_NEEDSYN) {
2737 * T/TCP: Connection was half-synchronized, and our
2738 * SYN has been ACK'd (so connection is now fully
2739 * synchronized). Go to non-starred state,
2740 * increment snd_una for ACK of SYN, and check if
2741 * we can do window scaling.
2743 tp->t_flags &= ~TF_NEEDSYN;
2745 /* Do window scaling? */
2746 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2747 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2748 tp->rcv_scale = tp->request_r_scale;
2749 /* Send window already scaled. */
2754 INP_WLOCK_ASSERT(tp->t_inpcb);
2756 acked = BYTES_THIS_ACK(tp, th);
2757 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2758 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2759 tp->snd_una, th->th_ack, tp, m));
2760 TCPSTAT_INC(tcps_rcvackpack);
2761 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2764 * If we just performed our first retransmit, and the ACK
2765 * arrives within our recovery window, then it was a mistake
2766 * to do the retransmit in the first place. Recover our
2767 * original cwnd and ssthresh, and proceed to transmit where
2770 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2771 (int)(ticks - tp->t_badrxtwin) < 0)
2772 cc_cong_signal(tp, th, CC_RTO_ERR);
2775 * If we have a timestamp reply, update smoothed
2776 * round trip time. If no timestamp is present but
2777 * transmit timer is running and timed sequence
2778 * number was acked, update smoothed round trip time.
2779 * Since we now have an rtt measurement, cancel the
2780 * timer backoff (cf., Phil Karn's retransmit alg.).
2781 * Recompute the initial retransmit timer.
2783 * Some boxes send broken timestamp replies
2784 * during the SYN+ACK phase, ignore
2785 * timestamps of 0 or we could calculate a
2786 * huge RTT and blow up the retransmit timer.
2788 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2791 t = tcp_ts_getticks() - to.to_tsecr;
2792 if (!tp->t_rttlow || tp->t_rttlow > t)
2794 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2795 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2796 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2797 tp->t_rttlow = ticks - tp->t_rtttime;
2798 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2802 * If all outstanding data is acked, stop retransmit
2803 * timer and remember to restart (more output or persist).
2804 * If there is more data to be acked, restart retransmit
2805 * timer, using current (possibly backed-off) value.
2807 if (th->th_ack == tp->snd_max) {
2808 tcp_timer_activate(tp, TT_REXMT, 0);
2810 } else if (!tcp_timer_active(tp, TT_PERSIST))
2811 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2814 * If no data (only SYN) was ACK'd,
2815 * skip rest of ACK processing.
2821 * Let the congestion control algorithm update congestion
2822 * control related information. This typically means increasing
2823 * the congestion window.
2825 cc_ack_received(tp, th, CC_ACK);
2827 SOCKBUF_LOCK(&so->so_snd);
2828 if (acked > sbavail(&so->so_snd)) {
2829 if (tp->snd_wnd >= sbavail(&so->so_snd))
2830 tp->snd_wnd -= sbavail(&so->so_snd);
2833 mfree = sbcut_locked(&so->so_snd,
2834 (int)sbavail(&so->so_snd));
2837 mfree = sbcut_locked(&so->so_snd, acked);
2838 if (tp->snd_wnd >= (u_long) acked)
2839 tp->snd_wnd -= acked;
2844 /* NB: sowwakeup_locked() does an implicit unlock. */
2845 sowwakeup_locked(so);
2847 /* Detect una wraparound. */
2848 if (!IN_RECOVERY(tp->t_flags) &&
2849 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2850 SEQ_LEQ(th->th_ack, tp->snd_recover))
2851 tp->snd_recover = th->th_ack - 1;
2852 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2853 if (IN_RECOVERY(tp->t_flags) &&
2854 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2855 EXIT_RECOVERY(tp->t_flags);
2857 tp->snd_una = th->th_ack;
2858 if (tp->t_flags & TF_SACK_PERMIT) {
2859 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2860 tp->snd_recover = tp->snd_una;
2862 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2863 tp->snd_nxt = tp->snd_una;
2865 switch (tp->t_state) {
2868 * In FIN_WAIT_1 STATE in addition to the processing
2869 * for the ESTABLISHED state if our FIN is now acknowledged
2870 * then enter FIN_WAIT_2.
2872 case TCPS_FIN_WAIT_1:
2873 if (ourfinisacked) {
2875 * If we can't receive any more
2876 * data, then closing user can proceed.
2877 * Starting the timer is contrary to the
2878 * specification, but if we don't get a FIN
2879 * we'll hang forever.
2882 * we should release the tp also, and use a
2885 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2886 soisdisconnected(so);
2887 tcp_timer_activate(tp, TT_2MSL,
2888 (tcp_fast_finwait2_recycle ?
2889 tcp_finwait2_timeout :
2892 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2897 * In CLOSING STATE in addition to the processing for
2898 * the ESTABLISHED state if the ACK acknowledges our FIN
2899 * then enter the TIME-WAIT state, otherwise ignore
2903 if (ourfinisacked) {
2904 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2906 INP_INFO_RUNLOCK(&V_tcbinfo);
2913 * In LAST_ACK, we may still be waiting for data to drain
2914 * and/or to be acked, as well as for the ack of our FIN.
2915 * If our FIN is now acknowledged, delete the TCB,
2916 * enter the closed state and return.
2919 if (ourfinisacked) {
2920 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2929 INP_WLOCK_ASSERT(tp->t_inpcb);
2932 * Update window information.
2933 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2935 if ((thflags & TH_ACK) &&
2936 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2937 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2938 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2939 /* keep track of pure window updates */
2941 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2942 TCPSTAT_INC(tcps_rcvwinupd);
2943 tp->snd_wnd = tiwin;
2944 tp->snd_wl1 = th->th_seq;
2945 tp->snd_wl2 = th->th_ack;
2946 if (tp->snd_wnd > tp->max_sndwnd)
2947 tp->max_sndwnd = tp->snd_wnd;
2952 * Process segments with URG.
2954 if ((thflags & TH_URG) && th->th_urp &&
2955 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2957 * This is a kludge, but if we receive and accept
2958 * random urgent pointers, we'll crash in
2959 * soreceive. It's hard to imagine someone
2960 * actually wanting to send this much urgent data.
2962 SOCKBUF_LOCK(&so->so_rcv);
2963 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2964 th->th_urp = 0; /* XXX */
2965 thflags &= ~TH_URG; /* XXX */
2966 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2967 goto dodata; /* XXX */
2970 * If this segment advances the known urgent pointer,
2971 * then mark the data stream. This should not happen
2972 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2973 * a FIN has been received from the remote side.
2974 * In these states we ignore the URG.
2976 * According to RFC961 (Assigned Protocols),
2977 * the urgent pointer points to the last octet
2978 * of urgent data. We continue, however,
2979 * to consider it to indicate the first octet
2980 * of data past the urgent section as the original
2981 * spec states (in one of two places).
2983 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2984 tp->rcv_up = th->th_seq + th->th_urp;
2985 so->so_oobmark = sbavail(&so->so_rcv) +
2986 (tp->rcv_up - tp->rcv_nxt) - 1;
2987 if (so->so_oobmark == 0)
2988 so->so_rcv.sb_state |= SBS_RCVATMARK;
2990 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2992 SOCKBUF_UNLOCK(&so->so_rcv);
2994 * Remove out of band data so doesn't get presented to user.
2995 * This can happen independent of advancing the URG pointer,
2996 * but if two URG's are pending at once, some out-of-band
2997 * data may creep in... ick.
2999 if (th->th_urp <= (u_long)tlen &&
3000 !(so->so_options & SO_OOBINLINE)) {
3001 /* hdr drop is delayed */
3002 tcp_pulloutofband(so, th, m, drop_hdrlen);
3006 * If no out of band data is expected,
3007 * pull receive urgent pointer along
3008 * with the receive window.
3010 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3011 tp->rcv_up = tp->rcv_nxt;
3014 INP_WLOCK_ASSERT(tp->t_inpcb);
3017 * Process the segment text, merging it into the TCP sequencing queue,
3018 * and arranging for acknowledgment of receipt if necessary.
3019 * This process logically involves adjusting tp->rcv_wnd as data
3020 * is presented to the user (this happens in tcp_usrreq.c,
3021 * case PRU_RCVD). If a FIN has already been received on this
3022 * connection then we just ignore the text.
3024 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3025 (tp->t_flags & TF_FASTOPEN));
3026 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
3027 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3028 tcp_seq save_start = th->th_seq;
3029 m_adj(m, drop_hdrlen); /* delayed header drop */
3031 * Insert segment which includes th into TCP reassembly queue
3032 * with control block tp. Set thflags to whether reassembly now
3033 * includes a segment with FIN. This handles the common case
3034 * inline (segment is the next to be received on an established
3035 * connection, and the queue is empty), avoiding linkage into
3036 * and removal from the queue and repetition of various
3038 * Set DELACK for segments received in order, but ack
3039 * immediately when segments are out of order (so
3040 * fast retransmit can work).
3042 if (th->th_seq == tp->rcv_nxt &&
3043 LIST_EMPTY(&tp->t_segq) &&
3044 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3046 if (DELAY_ACK(tp, tlen) || tfo_syn)
3047 tp->t_flags |= TF_DELACK;
3049 tp->t_flags |= TF_ACKNOW;
3050 tp->rcv_nxt += tlen;
3051 thflags = th->th_flags & TH_FIN;
3052 TCPSTAT_INC(tcps_rcvpack);
3053 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3054 SOCKBUF_LOCK(&so->so_rcv);
3055 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3058 sbappendstream_locked(&so->so_rcv, m, 0);
3059 /* NB: sorwakeup_locked() does an implicit unlock. */
3060 sorwakeup_locked(so);
3063 * XXX: Due to the header drop above "th" is
3064 * theoretically invalid by now. Fortunately
3065 * m_adj() doesn't actually frees any mbufs
3066 * when trimming from the head.
3068 thflags = tcp_reass(tp, th, &tlen, m);
3069 tp->t_flags |= TF_ACKNOW;
3071 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
3072 tcp_update_sack_list(tp, save_start, save_start + tlen);
3075 * Note the amount of data that peer has sent into
3076 * our window, in order to estimate the sender's
3080 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3081 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3083 len = so->so_rcv.sb_hiwat;
3091 * If FIN is received ACK the FIN and let the user know
3092 * that the connection is closing.
3094 if (thflags & TH_FIN) {
3095 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3098 * If connection is half-synchronized
3099 * (ie NEEDSYN flag on) then delay ACK,
3100 * so it may be piggybacked when SYN is sent.
3101 * Otherwise, since we received a FIN then no
3102 * more input can be expected, send ACK now.
3104 if (tp->t_flags & TF_NEEDSYN)
3105 tp->t_flags |= TF_DELACK;
3107 tp->t_flags |= TF_ACKNOW;
3110 switch (tp->t_state) {
3113 * In SYN_RECEIVED and ESTABLISHED STATES
3114 * enter the CLOSE_WAIT state.
3116 case TCPS_SYN_RECEIVED:
3117 tp->t_starttime = ticks;
3119 case TCPS_ESTABLISHED:
3120 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3124 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3125 * enter the CLOSING state.
3127 case TCPS_FIN_WAIT_1:
3128 tcp_state_change(tp, TCPS_CLOSING);
3132 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3133 * starting the time-wait timer, turning off the other
3136 case TCPS_FIN_WAIT_2:
3137 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3138 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
3139 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3143 INP_INFO_RUNLOCK(&V_tcbinfo);
3147 if (ti_locked == TI_RLOCKED)
3148 INP_INFO_RUNLOCK(&V_tcbinfo);
3149 ti_locked = TI_UNLOCKED;
3152 if (so->so_options & SO_DEBUG)
3153 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3156 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3159 * Return any desired output.
3161 if (needoutput || (tp->t_flags & TF_ACKNOW))
3162 (void) tp->t_fb->tfb_tcp_output(tp);
3165 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3166 __func__, ti_locked));
3167 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3168 INP_WLOCK_ASSERT(tp->t_inpcb);
3170 if (tp->t_flags & TF_DELACK) {
3171 tp->t_flags &= ~TF_DELACK;
3172 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3174 INP_WUNLOCK(tp->t_inpcb);
3179 * Generate an ACK dropping incoming segment if it occupies
3180 * sequence space, where the ACK reflects our state.
3182 * We can now skip the test for the RST flag since all
3183 * paths to this code happen after packets containing
3184 * RST have been dropped.
3186 * In the SYN-RECEIVED state, don't send an ACK unless the
3187 * segment we received passes the SYN-RECEIVED ACK test.
3188 * If it fails send a RST. This breaks the loop in the
3189 * "LAND" DoS attack, and also prevents an ACK storm
3190 * between two listening ports that have been sent forged
3191 * SYN segments, each with the source address of the other.
3193 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3194 (SEQ_GT(tp->snd_una, th->th_ack) ||
3195 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3196 rstreason = BANDLIM_RST_OPENPORT;
3200 if (so->so_options & SO_DEBUG)
3201 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3204 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3205 if (ti_locked == TI_RLOCKED)
3206 INP_INFO_RUNLOCK(&V_tcbinfo);
3207 ti_locked = TI_UNLOCKED;
3209 tp->t_flags |= TF_ACKNOW;
3210 (void) tp->t_fb->tfb_tcp_output(tp);
3211 INP_WUNLOCK(tp->t_inpcb);
3216 if (ti_locked == TI_RLOCKED)
3217 INP_INFO_RUNLOCK(&V_tcbinfo);
3218 ti_locked = TI_UNLOCKED;
3221 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3222 INP_WUNLOCK(tp->t_inpcb);
3224 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3228 if (ti_locked == TI_RLOCKED) {
3229 INP_INFO_RUNLOCK(&V_tcbinfo);
3230 ti_locked = TI_UNLOCKED;
3234 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3238 * Drop space held by incoming segment and return.
3241 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3242 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3245 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3247 INP_WUNLOCK(tp->t_inpcb);
3252 * Issue RST and make ACK acceptable to originator of segment.
3253 * The mbuf must still include the original packet header.
3257 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3258 int tlen, int rstreason)
3264 struct ip6_hdr *ip6;
3268 INP_WLOCK_ASSERT(tp->t_inpcb);
3271 /* Don't bother if destination was broadcast/multicast. */
3272 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3275 if (mtod(m, struct ip *)->ip_v == 6) {
3276 ip6 = mtod(m, struct ip6_hdr *);
3277 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3278 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3280 /* IPv6 anycast check is done at tcp6_input() */
3283 #if defined(INET) && defined(INET6)
3288 ip = mtod(m, struct ip *);
3289 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3290 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3291 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3292 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3297 /* Perform bandwidth limiting. */
3298 if (badport_bandlim(rstreason) < 0)
3301 /* tcp_respond consumes the mbuf chain. */
3302 if (th->th_flags & TH_ACK) {
3303 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3304 th->th_ack, TH_RST);
3306 if (th->th_flags & TH_SYN)
3308 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3309 (tcp_seq)0, TH_RST|TH_ACK);
3317 * Parse TCP options and place in tcpopt.
3320 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3325 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3327 if (opt == TCPOPT_EOL)
3329 if (opt == TCPOPT_NOP)
3335 if (optlen < 2 || optlen > cnt)
3340 if (optlen != TCPOLEN_MAXSEG)
3342 if (!(flags & TO_SYN))
3344 to->to_flags |= TOF_MSS;
3345 bcopy((char *)cp + 2,
3346 (char *)&to->to_mss, sizeof(to->to_mss));
3347 to->to_mss = ntohs(to->to_mss);
3350 if (optlen != TCPOLEN_WINDOW)
3352 if (!(flags & TO_SYN))
3354 to->to_flags |= TOF_SCALE;
3355 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3357 case TCPOPT_TIMESTAMP:
3358 if (optlen != TCPOLEN_TIMESTAMP)
3360 to->to_flags |= TOF_TS;
3361 bcopy((char *)cp + 2,
3362 (char *)&to->to_tsval, sizeof(to->to_tsval));
3363 to->to_tsval = ntohl(to->to_tsval);
3364 bcopy((char *)cp + 6,
3365 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3366 to->to_tsecr = ntohl(to->to_tsecr);
3368 #ifdef TCP_SIGNATURE
3370 * XXX In order to reply to a host which has set the
3371 * TCP_SIGNATURE option in its initial SYN, we have to
3372 * record the fact that the option was observed here
3373 * for the syncache code to perform the correct response.
3375 case TCPOPT_SIGNATURE:
3376 if (optlen != TCPOLEN_SIGNATURE)
3378 to->to_flags |= TOF_SIGNATURE;
3379 to->to_signature = cp + 2;
3382 case TCPOPT_SACK_PERMITTED:
3383 if (optlen != TCPOLEN_SACK_PERMITTED)
3385 if (!(flags & TO_SYN))
3389 to->to_flags |= TOF_SACKPERM;
3392 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3396 to->to_flags |= TOF_SACK;
3397 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3398 to->to_sacks = cp + 2;
3399 TCPSTAT_INC(tcps_sack_rcv_blocks);
3402 case TCPOPT_FAST_OPEN:
3403 if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
3404 (optlen < TCPOLEN_FAST_OPEN_MIN) &&
3405 (optlen > TCPOLEN_FAST_OPEN_MAX))
3407 if (!(flags & TO_SYN))
3409 if (!V_tcp_fastopen_enabled)
3411 to->to_flags |= TOF_FASTOPEN;
3412 to->to_tfo_len = optlen - 2;
3413 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3423 * Pull out of band byte out of a segment so
3424 * it doesn't appear in the user's data queue.
3425 * It is still reflected in the segment length for
3426 * sequencing purposes.
3429 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3432 int cnt = off + th->th_urp - 1;
3435 if (m->m_len > cnt) {
3436 char *cp = mtod(m, caddr_t) + cnt;
3437 struct tcpcb *tp = sototcpcb(so);
3439 INP_WLOCK_ASSERT(tp->t_inpcb);
3442 tp->t_oobflags |= TCPOOB_HAVEDATA;
3443 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3445 if (m->m_flags & M_PKTHDR)
3454 panic("tcp_pulloutofband");
3458 * Collect new round-trip time estimate
3459 * and update averages and current timeout.
3462 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3466 INP_WLOCK_ASSERT(tp->t_inpcb);
3468 TCPSTAT_INC(tcps_rttupdated);
3470 if (tp->t_srtt != 0) {
3472 * srtt is stored as fixed point with 5 bits after the
3473 * binary point (i.e., scaled by 8). The following magic
3474 * is equivalent to the smoothing algorithm in rfc793 with
3475 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3476 * point). Adjust rtt to origin 0.
3478 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3479 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3481 if ((tp->t_srtt += delta) <= 0)
3485 * We accumulate a smoothed rtt variance (actually, a
3486 * smoothed mean difference), then set the retransmit
3487 * timer to smoothed rtt + 4 times the smoothed variance.
3488 * rttvar is stored as fixed point with 4 bits after the
3489 * binary point (scaled by 16). The following is
3490 * equivalent to rfc793 smoothing with an alpha of .75
3491 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3492 * rfc793's wired-in beta.
3496 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3497 if ((tp->t_rttvar += delta) <= 0)
3499 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3500 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3503 * No rtt measurement yet - use the unsmoothed rtt.
3504 * Set the variance to half the rtt (so our first
3505 * retransmit happens at 3*rtt).
3507 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3508 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3509 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3515 * the retransmit should happen at rtt + 4 * rttvar.
3516 * Because of the way we do the smoothing, srtt and rttvar
3517 * will each average +1/2 tick of bias. When we compute
3518 * the retransmit timer, we want 1/2 tick of rounding and
3519 * 1 extra tick because of +-1/2 tick uncertainty in the
3520 * firing of the timer. The bias will give us exactly the
3521 * 1.5 tick we need. But, because the bias is
3522 * statistical, we have to test that we don't drop below
3523 * the minimum feasible timer (which is 2 ticks).
3525 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3526 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3529 * We received an ack for a packet that wasn't retransmitted;
3530 * it is probably safe to discard any error indications we've
3531 * received recently. This isn't quite right, but close enough
3532 * for now (a route might have failed after we sent a segment,
3533 * and the return path might not be symmetrical).
3535 tp->t_softerror = 0;
3539 * Determine a reasonable value for maxseg size.
3540 * If the route is known, check route for mtu.
3541 * If none, use an mss that can be handled on the outgoing interface
3542 * without forcing IP to fragment. If no route is found, route has no mtu,
3543 * or the destination isn't local, use a default, hopefully conservative
3544 * size (usually 512 or the default IP max size, but no more than the mtu
3545 * of the interface), as we can't discover anything about intervening
3546 * gateways or networks. We also initialize the congestion/slow start
3547 * window to be a single segment if the destination isn't local.
3548 * While looking at the routing entry, we also initialize other path-dependent
3549 * parameters from pre-set or cached values in the routing entry.
3551 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3552 * IP options, e.g. IPSEC data, since length of this data may vary, and
3553 * thus it is calculated for every segment separately in tcp_output().
3555 * NOTE that this routine is only called when we process an incoming
3556 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3557 * settings are handled in tcp_mssopt().
3560 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3561 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3565 struct inpcb *inp = tp->t_inpcb;
3566 struct hc_metrics_lite metrics;
3568 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3569 size_t min_protoh = isipv6 ?
3570 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3571 sizeof (struct tcpiphdr);
3573 const size_t min_protoh = sizeof(struct tcpiphdr);
3576 INP_WLOCK_ASSERT(tp->t_inpcb);
3578 if (mtuoffer != -1) {
3579 KASSERT(offer == -1, ("%s: conflict", __func__));
3580 offer = mtuoffer - min_protoh;
3586 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3587 tp->t_maxseg = V_tcp_v6mssdflt;
3590 #if defined(INET) && defined(INET6)
3595 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3596 tp->t_maxseg = V_tcp_mssdflt;
3601 * No route to sender, stay with default mss and return.
3605 * In case we return early we need to initialize metrics
3606 * to a defined state as tcp_hc_get() would do for us
3607 * if there was no cache hit.
3609 if (metricptr != NULL)
3610 bzero(metricptr, sizeof(struct hc_metrics_lite));
3614 /* What have we got? */
3618 * Offer == 0 means that there was no MSS on the SYN
3619 * segment, in this case we use tcp_mssdflt as
3620 * already assigned to t_maxseg above.
3622 offer = tp->t_maxseg;
3627 * Offer == -1 means that we didn't receive SYN yet.
3633 * Prevent DoS attack with too small MSS. Round up
3634 * to at least minmss.
3636 offer = max(offer, V_tcp_minmss);
3640 * rmx information is now retrieved from tcp_hostcache.
3642 tcp_hc_get(&inp->inp_inc, &metrics);
3643 if (metricptr != NULL)
3644 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3647 * If there's a discovered mtu in tcp hostcache, use it.
3648 * Else, use the link mtu.
3650 if (metrics.rmx_mtu)
3651 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3655 mss = maxmtu - min_protoh;
3656 if (!V_path_mtu_discovery &&
3657 !in6_localaddr(&inp->in6p_faddr))
3658 mss = min(mss, V_tcp_v6mssdflt);
3661 #if defined(INET) && defined(INET6)
3666 mss = maxmtu - min_protoh;
3667 if (!V_path_mtu_discovery &&
3668 !in_localaddr(inp->inp_faddr))
3669 mss = min(mss, V_tcp_mssdflt);
3673 * XXX - The above conditional (mss = maxmtu - min_protoh)
3674 * probably violates the TCP spec.
3675 * The problem is that, since we don't know the
3676 * other end's MSS, we are supposed to use a conservative
3677 * default. But, if we do that, then MTU discovery will
3678 * never actually take place, because the conservative
3679 * default is much less than the MTUs typically seen
3680 * on the Internet today. For the moment, we'll sweep
3681 * this under the carpet.
3683 * The conservative default might not actually be a problem
3684 * if the only case this occurs is when sending an initial
3685 * SYN with options and data to a host we've never talked
3686 * to before. Then, they will reply with an MSS value which
3687 * will get recorded and the new parameters should get
3688 * recomputed. For Further Study.
3691 mss = min(mss, offer);
3694 * Sanity check: make sure that maxseg will be large
3695 * enough to allow some data on segments even if the
3696 * all the option space is used (40bytes). Otherwise
3697 * funny things may happen in tcp_output.
3699 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3707 tcp_mss(struct tcpcb *tp, int offer)
3713 struct hc_metrics_lite metrics;
3714 struct tcp_ifcap cap;
3716 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3718 bzero(&cap, sizeof(cap));
3719 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3725 * If there's a pipesize, change the socket buffer to that size,
3726 * don't change if sb_hiwat is different than default (then it
3727 * has been changed on purpose with setsockopt).
3728 * Make the socket buffers an integral number of mss units;
3729 * if the mss is larger than the socket buffer, decrease the mss.
3731 so = inp->inp_socket;
3732 SOCKBUF_LOCK(&so->so_snd);
3733 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3734 bufsize = metrics.rmx_sendpipe;
3736 bufsize = so->so_snd.sb_hiwat;
3740 bufsize = roundup(bufsize, mss);
3741 if (bufsize > sb_max)
3743 if (bufsize > so->so_snd.sb_hiwat)
3744 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3746 SOCKBUF_UNLOCK(&so->so_snd);
3749 SOCKBUF_LOCK(&so->so_rcv);
3750 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3751 bufsize = metrics.rmx_recvpipe;
3753 bufsize = so->so_rcv.sb_hiwat;
3754 if (bufsize > mss) {
3755 bufsize = roundup(bufsize, mss);
3756 if (bufsize > sb_max)
3758 if (bufsize > so->so_rcv.sb_hiwat)
3759 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3761 SOCKBUF_UNLOCK(&so->so_rcv);
3763 /* Check the interface for TSO capabilities. */
3764 if (cap.ifcap & CSUM_TSO) {
3765 tp->t_flags |= TF_TSO;
3766 tp->t_tsomax = cap.tsomax;
3767 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3768 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3773 * Determine the MSS option to send on an outgoing SYN.
3776 tcp_mssopt(struct in_conninfo *inc)
3783 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3786 if (inc->inc_flags & INC_ISIPV6) {
3787 mss = V_tcp_v6mssdflt;
3788 maxmtu = tcp_maxmtu6(inc, NULL);
3789 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3792 #if defined(INET) && defined(INET6)
3797 mss = V_tcp_mssdflt;
3798 maxmtu = tcp_maxmtu(inc, NULL);
3799 min_protoh = sizeof(struct tcpiphdr);
3802 #if defined(INET6) || defined(INET)
3803 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3806 if (maxmtu && thcmtu)
3807 mss = min(maxmtu, thcmtu) - min_protoh;
3808 else if (maxmtu || thcmtu)
3809 mss = max(maxmtu, thcmtu) - min_protoh;
3816 * On a partial ack arrives, force the retransmission of the
3817 * next unacknowledged segment. Do not clear tp->t_dupacks.
3818 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3822 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3824 tcp_seq onxt = tp->snd_nxt;
3825 u_long ocwnd = tp->snd_cwnd;
3826 u_int maxseg = tcp_maxseg(tp);
3828 INP_WLOCK_ASSERT(tp->t_inpcb);
3830 tcp_timer_activate(tp, TT_REXMT, 0);
3832 tp->snd_nxt = th->th_ack;
3834 * Set snd_cwnd to one segment beyond acknowledged offset.
3835 * (tp->snd_una has not yet been updated when this function is called.)
3837 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3838 tp->t_flags |= TF_ACKNOW;
3839 (void) tp->t_fb->tfb_tcp_output(tp);
3840 tp->snd_cwnd = ocwnd;
3841 if (SEQ_GT(onxt, tp->snd_nxt))
3844 * Partial window deflation. Relies on fact that tp->snd_una
3847 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3848 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3851 tp->snd_cwnd += maxseg;
3855 tcp_compute_pipe(struct tcpcb *tp)
3857 return (tp->snd_max - tp->snd_una +
3858 tp->sackhint.sack_bytes_rexmit -
3859 tp->sackhint.sacked_bytes);