2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
5 * The Regents of the University of California. All rights reserved.
6 * Copyright (c) 2007-2008,2010
7 * Swinburne University of Technology, Melbourne, Australia.
8 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
9 * Copyright (c) 2010 The FreeBSD Foundation
10 * Copyright (c) 2010-2011 Juniper Networks, Inc.
11 * All rights reserved.
13 * Portions of this software were developed at the Centre for Advanced Internet
14 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
15 * James Healy and David Hayes, made possible in part by a grant from the Cisco
16 * University Research Program Fund at Community Foundation Silicon Valley.
18 * Portions of this software were developed at the Centre for Advanced
19 * Internet Architectures, Swinburne University of Technology, Melbourne,
20 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
22 * Portions of this software were developed by Robert N. M. Watson under
23 * contract to Juniper Networks, Inc.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the above copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
33 * 3. Neither the name of the University nor the names of its contributors
34 * may be used to endorse or promote products derived from this software
35 * without specific prior written permission.
37 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 #include <sys/cdefs.h>
52 #include "opt_inet6.h"
53 #include "opt_ipsec.h"
56 #include <sys/param.h>
58 #include <sys/kernel.h>
60 #include <sys/hhook.h>
62 #include <sys/malloc.h>
64 #include <sys/proc.h> /* for proc0 declaration */
65 #include <sys/protosw.h>
66 #include <sys/qmath.h>
68 #include <sys/signalvar.h>
69 #include <sys/socket.h>
70 #include <sys/socketvar.h>
71 #include <sys/sysctl.h>
72 #include <sys/syslog.h>
73 #include <sys/systm.h>
74 #include <sys/stats.h>
76 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
81 #include <net/if_var.h>
82 #include <net/route.h>
83 #include <net/rss_config.h>
86 #define TCPSTATES /* for logging */
88 #include <netinet/in.h>
89 #include <netinet/in_kdtrace.h>
90 #include <netinet/in_pcb.h>
91 #include <netinet/in_rss.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
95 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
96 #include <netinet/ip_var.h>
97 #include <netinet/ip_options.h>
98 #include <netinet/ip6.h>
99 #include <netinet/icmp6.h>
100 #include <netinet6/in6_pcb.h>
101 #include <netinet6/in6_rss.h>
102 #include <netinet6/in6_var.h>
103 #include <netinet6/ip6_var.h>
104 #include <netinet6/nd6.h>
105 #include <netinet/tcp.h>
106 #include <netinet/tcp_fsm.h>
107 #include <netinet/tcp_seq.h>
108 #include <netinet/tcp_timer.h>
109 #include <netinet/tcp_var.h>
110 #include <netinet/tcp_log_buf.h>
111 #include <netinet6/tcp6_var.h>
112 #include <netinet/tcpip.h>
113 #include <netinet/cc/cc.h>
114 #include <netinet/tcp_fastopen.h>
116 #include <netinet/tcp_pcap.h>
118 #include <netinet/tcp_syncache.h>
120 #include <netinet/tcp_offload.h>
122 #include <netinet/tcp_ecn.h>
123 #include <netinet/udp.h>
125 #include <netipsec/ipsec_support.h>
127 #include <machine/in_cksum.h>
129 #include <security/mac/mac_framework.h>
131 const int tcprexmtthresh = 3;
133 VNET_DEFINE(int, tcp_log_in_vain) = 0;
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW,
135 &VNET_NAME(tcp_log_in_vain), 0,
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(bool, blackhole_local) = false;
145 #define V_blackhole_local VNET(blackhole_local)
146 SYSCTL_BOOL(_net_inet_tcp, OID_AUTO, blackhole_local, CTLFLAG_VNET |
147 CTLFLAG_RW, &VNET_NAME(blackhole_local), false,
148 "Enforce net.inet.tcp.blackhole for locally originated packets");
150 VNET_DEFINE(int, tcp_delack_enabled) = 1;
151 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
152 &VNET_NAME(tcp_delack_enabled), 0,
153 "Delay ACK to try and piggyback it onto a data packet");
155 VNET_DEFINE(int, drop_synfin) = 0;
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
157 &VNET_NAME(drop_synfin), 0,
158 "Drop TCP packets with SYN+FIN set");
160 VNET_DEFINE(int, tcp_do_prr) = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_prr, CTLFLAG_VNET | CTLFLAG_RW,
162 &VNET_NAME(tcp_do_prr), 1,
163 "Enable Proportional Rate Reduction per RFC 6937");
165 VNET_DEFINE(int, tcp_do_newcwv) = 0;
166 SYSCTL_INT(_net_inet_tcp, OID_AUTO, newcwv, CTLFLAG_VNET | CTLFLAG_RW,
167 &VNET_NAME(tcp_do_newcwv), 0,
168 "Enable New Congestion Window Validation per RFC7661");
170 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
172 &VNET_NAME(tcp_do_rfc3042), 0,
173 "Enable RFC 3042 (Limited Transmit)");
175 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
176 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
177 &VNET_NAME(tcp_do_rfc3390), 0,
178 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
180 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
181 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
182 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
183 "Slow-start flight size (initial congestion window) in number of segments");
185 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
186 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
187 &VNET_NAME(tcp_do_rfc3465), 0,
188 "Enable RFC 3465 (Appropriate Byte Counting)");
190 VNET_DEFINE(int, tcp_abc_l_var) = 2;
191 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
192 &VNET_NAME(tcp_abc_l_var), 2,
193 "Cap the max cwnd increment during slow-start to this number of segments");
195 VNET_DEFINE(int, tcp_insecure_syn) = 0;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
197 &VNET_NAME(tcp_insecure_syn), 0,
198 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
200 VNET_DEFINE(int, tcp_insecure_rst) = 0;
201 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
202 &VNET_NAME(tcp_insecure_rst), 0,
203 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
205 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
206 #define V_tcp_recvspace VNET(tcp_recvspace)
207 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
208 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
210 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
212 &VNET_NAME(tcp_do_autorcvbuf), 0,
213 "Enable automatic receive buffer sizing");
215 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
216 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
217 &VNET_NAME(tcp_autorcvbuf_max), 0,
218 "Max size of automatic receive buffer");
220 VNET_DEFINE(struct inpcbinfo, tcbinfo);
223 * TCP statistics are stored in an array of counter(9)s, which size matches
224 * size of struct tcpstat. TCP running connection count is a regular array.
226 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
227 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
228 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
229 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
230 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
231 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
232 "TCP connection counts by TCP state");
235 * Kernel module interface for updating tcpstat. The first argument is an index
236 * into tcpstat treated as an array.
239 kmod_tcpstat_add(int statnum, int val)
242 counter_u64_add(VNET(tcpstat)[statnum], val);
246 * Make sure that we only start a SACK loss recovery when
247 * receiving a duplicate ACK with a SACK block, and also
248 * complete SACK loss recovery in case the other end
252 tcp_is_sack_recovery(struct tcpcb *tp, struct tcpopt *to)
254 return ((tp->t_flags & TF_SACK_PERMIT) &&
255 ((to->to_flags & TOF_SACK) ||
256 (!TAILQ_EMPTY(&tp->snd_holes))));
261 * Wrapper for the TCP established input helper hook.
264 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
266 struct tcp_hhook_data hhook_data;
268 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
273 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
280 * CC wrapper hook functions
283 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
290 INP_WLOCK_ASSERT(tptoinpcb(tp));
292 tp->t_ccv.nsegs = nsegs;
293 tp->t_ccv.bytes_this_ack = BYTES_THIS_ACK(tp, th);
294 if ((!V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd)) ||
295 (V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd) &&
296 (tp->snd_cwnd < (tcp_compute_pipe(tp) * 2))))
297 tp->t_ccv.flags |= CCF_CWND_LIMITED;
299 tp->t_ccv.flags &= ~CCF_CWND_LIMITED;
301 if (type == CC_ACK) {
303 stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
304 ((int32_t)tp->snd_cwnd) - tp->snd_wnd);
305 if (!IN_RECOVERY(tp->t_flags))
306 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_ACKLEN,
307 tp->t_ccv.bytes_this_ack / (tcp_maxseg(tp) * nsegs));
308 if ((tp->t_flags & TF_GPUTINPROG) &&
309 SEQ_GEQ(th->th_ack, tp->gput_ack)) {
311 * Compute goodput in bits per millisecond.
313 gput = (((int64_t)SEQ_SUB(th->th_ack, tp->gput_seq)) << 3) /
314 max(1, tcp_ts_getticks() - tp->gput_ts);
315 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
318 * XXXLAS: This is a temporary hack, and should be
319 * chained off VOI_TCP_GPUT when stats(9) grows an API
320 * to deal with chained VOIs.
322 if (tp->t_stats_gput_prev > 0)
323 stats_voi_update_abs_s32(tp->t_stats,
325 ((gput - tp->t_stats_gput_prev) * 100) /
326 tp->t_stats_gput_prev);
327 tp->t_flags &= ~TF_GPUTINPROG;
328 tp->t_stats_gput_prev = gput;
331 if (tp->snd_cwnd > tp->snd_ssthresh) {
332 tp->t_bytes_acked += tp->t_ccv.bytes_this_ack;
333 if (tp->t_bytes_acked >= tp->snd_cwnd) {
334 tp->t_bytes_acked -= tp->snd_cwnd;
335 tp->t_ccv.flags |= CCF_ABC_SENTAWND;
338 tp->t_ccv.flags &= ~CCF_ABC_SENTAWND;
339 tp->t_bytes_acked = 0;
343 if (CC_ALGO(tp)->ack_received != NULL) {
344 /* XXXLAS: Find a way to live without this */
345 tp->t_ccv.curack = th->th_ack;
346 CC_ALGO(tp)->ack_received(&tp->t_ccv, type);
349 stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
354 cc_conn_init(struct tcpcb *tp)
356 struct hc_metrics_lite metrics;
357 struct inpcb *inp = tptoinpcb(tp);
361 INP_WLOCK_ASSERT(inp);
363 tcp_hc_get(&inp->inp_inc, &metrics);
364 maxseg = tcp_maxseg(tp);
366 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
368 TCPSTAT_INC(tcps_usedrtt);
369 if (metrics.rmx_rttvar) {
370 tp->t_rttvar = metrics.rmx_rttvar;
371 TCPSTAT_INC(tcps_usedrttvar);
373 /* default variation is +- 1 rtt */
375 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
377 TCPT_RANGESET(tp->t_rxtcur,
378 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
379 tp->t_rttmin, TCPTV_REXMTMAX);
381 if (metrics.rmx_ssthresh) {
383 * There's some sort of gateway or interface
384 * buffer limit on the path. Use this to set
385 * the slow start threshold, but set the
386 * threshold to no less than 2*mss.
388 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
389 TCPSTAT_INC(tcps_usedssthresh);
393 * Set the initial slow-start flight size.
395 * If a SYN or SYN/ACK was lost and retransmitted, we have to
396 * reduce the initial CWND to one segment as congestion is likely
397 * requiring us to be cautious.
399 if (tp->snd_cwnd == 1)
400 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
402 tp->snd_cwnd = tcp_compute_initwnd(maxseg);
404 if (CC_ALGO(tp)->conn_init != NULL)
405 CC_ALGO(tp)->conn_init(&tp->t_ccv);
409 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
411 INP_WLOCK_ASSERT(tptoinpcb(tp));
414 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
419 if (!IN_FASTRECOVERY(tp->t_flags)) {
420 tp->snd_recover = tp->snd_max;
421 if (tp->t_flags2 & TF2_ECN_PERMIT)
422 tp->t_flags2 |= TF2_ECN_SND_CWR;
426 if (!IN_CONGRECOVERY(tp->t_flags) ||
428 * Allow ECN reaction on ACK to CWR, if
429 * that data segment was also CE marked.
431 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
432 EXIT_CONGRECOVERY(tp->t_flags);
433 TCPSTAT_INC(tcps_ecn_rcwnd);
434 tp->snd_recover = tp->snd_max + 1;
435 if (tp->t_flags2 & TF2_ECN_PERMIT)
436 tp->t_flags2 |= TF2_ECN_SND_CWR;
441 tp->t_bytes_acked = 0;
442 if ((tp->t_rxtshift > 1) ||
443 !((tp->t_flags & TF_SACK_PERMIT) &&
444 (!TAILQ_EMPTY(&tp->snd_holes))))
445 EXIT_RECOVERY(tp->t_flags);
446 if (tp->t_flags2 & TF2_ECN_PERMIT)
447 tp->t_flags2 |= TF2_ECN_SND_CWR;
450 TCPSTAT_INC(tcps_sndrexmitbad);
451 /* RTO was unnecessary, so reset everything. */
452 tp->snd_cwnd = tp->snd_cwnd_prev;
453 tp->snd_ssthresh = tp->snd_ssthresh_prev;
454 tp->snd_recover = tp->snd_recover_prev;
455 if (tp->t_flags & TF_WASFRECOVERY)
456 ENTER_FASTRECOVERY(tp->t_flags);
457 if (tp->t_flags & TF_WASCRECOVERY)
458 ENTER_CONGRECOVERY(tp->t_flags);
459 tp->snd_nxt = tp->snd_max;
460 tp->t_flags &= ~TF_PREVVALID;
464 if (SEQ_LT(tp->snd_fack, tp->snd_una) ||
465 SEQ_GT(tp->snd_fack, tp->snd_max)) {
466 tp->snd_fack = tp->snd_una;
469 if (CC_ALGO(tp)->cong_signal != NULL) {
471 tp->t_ccv.curack = th->th_ack;
472 CC_ALGO(tp)->cong_signal(&tp->t_ccv, type);
477 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
479 INP_WLOCK_ASSERT(tptoinpcb(tp));
481 if (CC_ALGO(tp)->post_recovery != NULL) {
482 if (SEQ_LT(tp->snd_fack, th->th_ack) ||
483 SEQ_GT(tp->snd_fack, tp->snd_max)) {
484 tp->snd_fack = th->th_ack;
486 tp->t_ccv.curack = th->th_ack;
487 CC_ALGO(tp)->post_recovery(&tp->t_ccv);
489 EXIT_RECOVERY(tp->t_flags);
491 tp->t_bytes_acked = 0;
492 tp->sackhint.delivered_data = 0;
493 tp->sackhint.prr_delivered = 0;
494 tp->sackhint.prr_out = 0;
498 * Indicate whether this ack should be delayed. We can delay the ack if
499 * following conditions are met:
500 * - There is no delayed ack timer in progress.
501 * - Our last ack wasn't a 0-sized window. We never want to delay
502 * the ack that opens up a 0-sized window.
503 * - LRO wasn't used for this segment. We make sure by checking that the
504 * segment size is not larger than the MSS.
506 #define DELAY_ACK(tp, tlen) \
507 ((!tcp_timer_active(tp, TT_DELACK) && \
508 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
509 (tlen <= tp->t_maxseg) && \
510 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
513 cc_ecnpkt_handler_flags(struct tcpcb *tp, uint16_t flags, uint8_t iptos)
515 INP_WLOCK_ASSERT(tptoinpcb(tp));
517 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
518 switch (iptos & IPTOS_ECN_MASK) {
520 tp->t_ccv.flags |= CCF_IPHDR_CE;
526 case IPTOS_ECN_NOTECT:
527 tp->t_ccv.flags &= ~CCF_IPHDR_CE;
532 tp->t_ccv.flags |= CCF_TCPHDR_CWR;
534 tp->t_ccv.flags &= ~CCF_TCPHDR_CWR;
536 CC_ALGO(tp)->ecnpkt_handler(&tp->t_ccv);
538 if (tp->t_ccv.flags & CCF_ACKNOW) {
539 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
540 tp->t_flags |= TF_ACKNOW;
546 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
548 cc_ecnpkt_handler_flags(tp, tcp_get_flags(th), iptos);
552 * TCP input handling is split into multiple parts:
553 * tcp6_input is a thin wrapper around tcp_input for the extended
554 * ip6_protox[] call format in ip6_input
555 * tcp_input handles primary segment validation, inpcb lookup and
556 * SYN processing on listen sockets
557 * tcp_do_segment processes the ACK and text of the segment for
558 * establishing, established and closing connections
562 tcp6_input_with_port(struct mbuf **mp, int *offp, int proto, uint16_t port)
565 struct in6_ifaddr *ia6;
569 if (m->m_len < *offp + sizeof(struct tcphdr)) {
570 m = m_pullup(m, *offp + sizeof(struct tcphdr));
573 TCPSTAT_INC(tcps_rcvshort);
574 return (IPPROTO_DONE);
579 * draft-itojun-ipv6-tcp-to-anycast
580 * better place to put this in?
582 ip6 = mtod(m, struct ip6_hdr *);
583 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
584 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
585 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
586 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
588 return (IPPROTO_DONE);
592 return (tcp_input_with_port(mp, offp, proto, port));
596 tcp6_input(struct mbuf **mp, int *offp, int proto)
599 return(tcp6_input_with_port(mp, offp, proto, 0));
604 tcp_input_with_port(struct mbuf **mp, int *offp, int proto, uint16_t port)
606 struct mbuf *m = *mp;
607 struct tcphdr *th = NULL;
608 struct ip *ip = NULL;
609 struct inpcb *inp = NULL;
610 struct tcpcb *tp = NULL;
611 struct socket *so = NULL;
622 int rstreason = 0; /* For badport_bandlim accounting purposes */
625 struct m_tag *fwd_tag = NULL;
627 struct ip6_hdr *ip6 = NULL;
630 const void *ip6 = NULL;
632 struct tcpopt to; /* options in this segment */
633 char *s = NULL; /* address and port logging */
638 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
645 TCPSTAT_INC(tcps_rcvtotal);
647 m->m_pkthdr.tcp_tun_port = port;
650 ip6 = mtod(m, struct ip6_hdr *);
651 th = (struct tcphdr *)((caddr_t)ip6 + off0);
652 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
655 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
656 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
657 th->th_sum = m->m_pkthdr.csum_data;
659 th->th_sum = in6_cksum_pseudo(ip6, tlen,
660 IPPROTO_TCP, m->m_pkthdr.csum_data);
661 th->th_sum ^= 0xffff;
663 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
665 TCPSTAT_INC(tcps_rcvbadsum);
670 * Be proactive about unspecified IPv6 address in source.
671 * As we use all-zero to indicate unbounded/unconnected pcb,
672 * unspecified IPv6 address can be used to confuse us.
674 * Note that packets with unspecified IPv6 destination is
675 * already dropped in ip6_input.
677 KASSERT(!IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst),
678 ("%s: unspecified destination v6 address", __func__));
679 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
680 IP6STAT_INC(ip6s_badscope); /* XXX */
683 iptos = IPV6_TRAFFIC_CLASS(ip6);
686 #if defined(INET) && defined(INET6)
692 * Get IP and TCP header together in first mbuf.
693 * Note: IP leaves IP header in first mbuf.
695 if (off0 > sizeof (struct ip)) {
697 off0 = sizeof(struct ip);
699 if (m->m_len < sizeof (struct tcpiphdr)) {
700 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
702 TCPSTAT_INC(tcps_rcvshort);
703 return (IPPROTO_DONE);
706 ip = mtod(m, struct ip *);
707 th = (struct tcphdr *)((caddr_t)ip + off0);
708 tlen = ntohs(ip->ip_len) - off0;
713 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
714 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
715 th->th_sum = m->m_pkthdr.csum_data;
717 th->th_sum = in_pseudo(ip->ip_src.s_addr,
719 htonl(m->m_pkthdr.csum_data + tlen +
721 th->th_sum ^= 0xffff;
723 struct ipovly *ipov = (struct ipovly *)ip;
726 * Checksum extended TCP header and data.
730 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
731 ipov->ih_len = htons(tlen);
732 th->th_sum = in_cksum(m, len);
733 /* Reset length for SDT probes. */
734 ip->ip_len = htons(len);
737 /* Re-initialization for later version check */
739 ip->ip_v = IPVERSION;
740 ip->ip_hl = off0 >> 2;
743 if (th->th_sum && (port == 0)) {
744 TCPSTAT_INC(tcps_rcvbadsum);
747 KASSERT(ip->ip_dst.s_addr != INADDR_ANY,
748 ("%s: unspecified destination v4 address", __func__));
749 if (__predict_false(ip->ip_src.s_addr == INADDR_ANY)) {
750 IPSTAT_INC(ips_badaddr);
757 * Check that TCP offset makes sense,
758 * pull out TCP options and adjust length. XXX
760 off = th->th_off << 2;
761 if (off < sizeof (struct tcphdr) || off > tlen) {
762 TCPSTAT_INC(tcps_rcvbadoff);
765 tlen -= off; /* tlen is used instead of ti->ti_len */
766 if (off > sizeof (struct tcphdr)) {
769 if (m->m_len < off0 + off) {
770 m = m_pullup(m, off0 + off);
772 TCPSTAT_INC(tcps_rcvshort);
773 return (IPPROTO_DONE);
776 ip6 = mtod(m, struct ip6_hdr *);
777 th = (struct tcphdr *)((caddr_t)ip6 + off0);
780 #if defined(INET) && defined(INET6)
785 if (m->m_len < sizeof(struct ip) + off) {
786 if ((m = m_pullup(m, sizeof (struct ip) + off))
788 TCPSTAT_INC(tcps_rcvshort);
789 return (IPPROTO_DONE);
791 ip = mtod(m, struct ip *);
792 th = (struct tcphdr *)((caddr_t)ip + off0);
796 optlen = off - sizeof (struct tcphdr);
797 optp = (u_char *)(th + 1);
799 thflags = tcp_get_flags(th);
802 * Convert TCP protocol specific fields to host format.
804 tcp_fields_to_host(th);
807 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
809 drop_hdrlen = off0 + off;
812 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
816 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
818 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
821 #if defined(INET) && !defined(INET6)
822 (m->m_flags & M_IP_NEXTHOP)
825 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
828 * For initial SYN packets we don't need write lock on matching
829 * PCB, be it a listening one or a synchronized one. The packet
830 * shall not modify its state.
832 lookupflag = INPLOOKUP_WILDCARD |
833 ((thflags & (TH_ACK|TH_SYN)) == TH_SYN ?
834 INPLOOKUP_RLOCKPCB : INPLOOKUP_WLOCKPCB);
837 if (isipv6 && fwd_tag != NULL) {
838 struct sockaddr_in6 *next_hop6;
840 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
842 * Transparently forwarded. Pretend to be the destination.
843 * Already got one like this?
845 inp = in6_pcblookup_mbuf(&V_tcbinfo,
846 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
847 lookupflag & ~INPLOOKUP_WILDCARD, m->m_pkthdr.rcvif, m);
850 * It's new. Try to find the ambushing socket.
851 * Because we've rewritten the destination address,
852 * any hardware-generated hash is ignored.
854 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
855 th->th_sport, &next_hop6->sin6_addr,
856 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
857 th->th_dport, lookupflag, m->m_pkthdr.rcvif);
860 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
861 th->th_sport, &ip6->ip6_dst, th->th_dport, lookupflag,
862 m->m_pkthdr.rcvif, m);
865 #if defined(INET6) && defined(INET)
869 if (fwd_tag != NULL) {
870 struct sockaddr_in *next_hop;
872 next_hop = (struct sockaddr_in *)(fwd_tag+1);
874 * Transparently forwarded. Pretend to be the destination.
875 * already got one like this?
877 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
878 ip->ip_dst, th->th_dport, lookupflag & ~INPLOOKUP_WILDCARD,
879 m->m_pkthdr.rcvif, m);
882 * It's new. Try to find the ambushing socket.
883 * Because we've rewritten the destination address,
884 * any hardware-generated hash is ignored.
886 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
887 th->th_sport, next_hop->sin_addr,
888 next_hop->sin_port ? ntohs(next_hop->sin_port) :
889 th->th_dport, lookupflag, m->m_pkthdr.rcvif);
892 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
893 th->th_sport, ip->ip_dst, th->th_dport, lookupflag,
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?
903 if (rstreason != 0) {
904 /* We came here after second (safety) lookup. */
905 MPASS((lookupflag & INPLOOKUP_WILDCARD) == 0);
909 * Log communication attempts to ports that are not
912 if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
913 V_tcp_log_in_vain == 2) {
914 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
915 log(LOG_INFO, "%s; %s: Connection attempt "
916 "to closed port\n", s, __func__);
919 * When blackholing do not respond with a RST but
920 * completely ignore the segment and drop it.
922 if (((V_blackhole == 1 && (thflags & TH_SYN)) ||
923 V_blackhole == 2) && (V_blackhole_local || (
925 isipv6 ? !in6_localaddr(&ip6->ip6_src) :
928 !in_localip(ip->ip_src)
935 rstreason = BANDLIM_RST_CLOSEDPORT;
938 INP_LOCK_ASSERT(inp);
940 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
941 !SOLISTENING(inp->inp_socket)) {
942 if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
943 inp->inp_flowid = m->m_pkthdr.flowid;
944 inp->inp_flowtype = M_HASHTYPE_GET(m);
947 /* assign flowid by software RSS hash */
950 rss_proto_software_hash_v6(&inp->in6p_faddr,
960 rss_proto_software_hash_v4(inp->inp_faddr,
971 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
973 if (isipv6 && IPSEC_ENABLED(ipv6) &&
974 IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
982 if (IPSEC_ENABLED(ipv4) &&
983 IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
990 * Check the minimum TTL for socket.
992 if (inp->inp_ip_minttl != 0) {
995 if (inp->inp_ip_minttl > ip6->ip6_hlim)
999 if (inp->inp_ip_minttl > ip->ip_ttl)
1003 tp = intotcpcb(inp);
1004 switch (tp->t_state) {
1005 case TCPS_TIME_WAIT:
1007 * A previous connection in TIMEWAIT state is supposed to catch
1008 * stray or duplicate segments arriving late. If this segment
1009 * was a legitimate new connection attempt, the old INPCB gets
1010 * removed and we can try again to find a listening socket.
1012 tcp_dooptions(&to, optp, optlen,
1013 (thflags & TH_SYN) ? TO_SYN : 0);
1015 * tcp_twcheck unlocks the inp always, and frees the m if fails.
1017 if (tcp_twcheck(inp, &to, th, m, tlen))
1019 return (IPPROTO_DONE);
1022 * The TCPCB may no longer exist if the connection is winding
1023 * down or it is in the CLOSED state. Either way we drop the
1024 * segment and send an appropriate response.
1026 rstreason = BANDLIM_RST_CLOSEDPORT;
1030 if ((tp->t_port != port) && (tp->t_state > TCPS_LISTEN)) {
1031 rstreason = BANDLIM_RST_CLOSEDPORT;
1036 if (tp->t_flags & TF_TOE) {
1037 tcp_offload_input(tp, m);
1038 m = NULL; /* consumed by the TOE driver */
1044 if (mac_inpcb_check_deliver(inp, m))
1047 so = inp->inp_socket;
1048 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1050 * When the socket is accepting connections (the INPCB is in LISTEN
1051 * state) we look into the SYN cache if this is a new connection
1052 * attempt or the completion of a previous one.
1054 KASSERT(tp->t_state == TCPS_LISTEN || !SOLISTENING(so),
1055 ("%s: so accepting but tp %p not listening", __func__, tp));
1056 if (tp->t_state == TCPS_LISTEN && SOLISTENING(so)) {
1057 struct in_conninfo inc;
1059 bzero(&inc, sizeof(inc));
1062 inc.inc_flags |= INC_ISIPV6;
1063 if (inp->inp_inc.inc_flags & INC_IPV6MINMTU)
1064 inc.inc_flags |= INC_IPV6MINMTU;
1065 inc.inc6_faddr = ip6->ip6_src;
1066 inc.inc6_laddr = ip6->ip6_dst;
1070 inc.inc_faddr = ip->ip_src;
1071 inc.inc_laddr = ip->ip_dst;
1073 inc.inc_fport = th->th_sport;
1074 inc.inc_lport = th->th_dport;
1075 inc.inc_fibnum = so->so_fibnum;
1078 * Check for an existing connection attempt in syncache if
1079 * the flag is only ACK. A successful lookup creates a new
1080 * socket appended to the listen queue in SYN_RECEIVED state.
1082 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1084 * Parse the TCP options here because
1085 * syncookies need access to the reflected
1088 tcp_dooptions(&to, optp, optlen, 0);
1090 * NB: syncache_expand() doesn't unlock inp.
1092 rstreason = syncache_expand(&inc, &to, th, &so, m, port);
1093 if (rstreason < 0) {
1095 * A failing TCP MD5 signature comparison
1096 * must result in the segment being dropped
1097 * and must not produce any response back
1101 } else if (rstreason == 0) {
1103 * No syncache entry, or ACK was not for our
1104 * SYN/ACK. Do our protection against double
1105 * ACK. If peer sent us 2 ACKs, then for the
1106 * first one syncache_expand() successfully
1107 * converted syncache entry into a socket,
1108 * while we were waiting on the inpcb lock. We
1109 * don't want to sent RST for the second ACK,
1110 * so we perform second lookup without wildcard
1111 * match, hoping to find the new socket. If
1112 * the ACK is stray indeed, rstreason would
1113 * hint the above code that the lookup was a
1116 * NB: syncache did its own logging
1117 * of the failure cause.
1120 rstreason = BANDLIM_RST_OPENPORT;
1121 lookupflag &= ~INPLOOKUP_WILDCARD;
1127 * We completed the 3-way handshake
1128 * but could not allocate a socket
1129 * either due to memory shortage,
1130 * listen queue length limits or
1131 * global socket limits. Send RST
1132 * or wait and have the remote end
1133 * retransmit the ACK for another
1136 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1137 log(LOG_DEBUG, "%s; %s: Listen socket: "
1138 "Socket allocation failed due to "
1139 "limits or memory shortage, %s\n",
1141 V_tcp_sc_rst_sock_fail ?
1142 "sending RST" : "try again");
1143 if (V_tcp_sc_rst_sock_fail) {
1144 rstreason = BANDLIM_UNLIMITED;
1150 * Socket is created in state SYN_RECEIVED.
1151 * Unlock the listen socket, lock the newly
1152 * created socket and update the tp variable.
1153 * If we came here via jump to tfo_socket_result,
1154 * then listening socket is read-locked.
1156 INP_UNLOCK(inp); /* listen socket */
1157 inp = sotoinpcb(so);
1159 * New connection inpcb is already locked by
1160 * syncache_expand().
1162 INP_WLOCK_ASSERT(inp);
1163 tp = intotcpcb(inp);
1164 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1165 ("%s: ", __func__));
1167 * Process the segment and the data it
1168 * contains. tcp_do_segment() consumes
1169 * the mbuf chain and unlocks the inpcb.
1171 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1172 tp->t_fb->tfb_tcp_do_segment(tp, m, th, drop_hdrlen,
1174 return (IPPROTO_DONE);
1177 * Segment flag validation for new connection attempts:
1179 * Our (SYN|ACK) response was rejected.
1180 * Check with syncache and remove entry to prevent
1183 * NB: syncache_chkrst does its own logging of failure
1186 if (thflags & TH_RST) {
1187 syncache_chkrst(&inc, th, m, port);
1191 * We can't do anything without SYN.
1193 if ((thflags & TH_SYN) == 0) {
1194 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1195 log(LOG_DEBUG, "%s; %s: Listen socket: "
1196 "SYN is missing, segment ignored\n",
1198 TCPSTAT_INC(tcps_badsyn);
1202 * (SYN|ACK) is bogus on a listen socket.
1204 if (thflags & TH_ACK) {
1205 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1206 log(LOG_DEBUG, "%s; %s: Listen socket: "
1207 "SYN|ACK invalid, segment rejected\n",
1209 syncache_badack(&inc, port); /* XXX: Not needed! */
1210 TCPSTAT_INC(tcps_badsyn);
1211 rstreason = BANDLIM_RST_OPENPORT;
1215 * If the drop_synfin option is enabled, drop all
1216 * segments with both the SYN and FIN bits set.
1217 * This prevents e.g. nmap from identifying the
1219 * XXX: Poor reasoning. nmap has other methods
1220 * and is constantly refining its stack detection
1222 * XXX: This is a violation of the TCP specification
1223 * and was used by RFC1644.
1225 if ((thflags & TH_FIN) && V_drop_synfin) {
1226 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1227 log(LOG_DEBUG, "%s; %s: Listen socket: "
1228 "SYN|FIN segment ignored (based on "
1229 "sysctl setting)\n", s, __func__);
1230 TCPSTAT_INC(tcps_badsyn);
1234 * Segment's flags are (SYN) or (SYN|FIN).
1236 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1237 * as they do not affect the state of the TCP FSM.
1238 * The data pointed to by TH_URG and th_urp is ignored.
1240 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1241 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1242 KASSERT(thflags & (TH_SYN),
1243 ("%s: Listen socket: TH_SYN not set", __func__));
1244 INP_RLOCK_ASSERT(inp);
1247 * If deprecated address is forbidden,
1248 * we do not accept SYN to deprecated interface
1249 * address to prevent any new inbound connection from
1250 * getting established.
1251 * When we do not accept SYN, we send a TCP RST,
1252 * with deprecated source address (instead of dropping
1253 * it). We compromise it as it is much better for peer
1254 * to send a RST, and RST will be the final packet
1257 * If we do not forbid deprecated addresses, we accept
1258 * the SYN packet. RFC2462 does not suggest dropping
1260 * If we decipher RFC2462 5.5.4, it says like this:
1261 * 1. use of deprecated addr with existing
1262 * communication is okay - "SHOULD continue to be
1264 * 2. use of it with new communication:
1265 * (2a) "SHOULD NOT be used if alternate address
1266 * with sufficient scope is available"
1267 * (2b) nothing mentioned otherwise.
1268 * Here we fall into (2b) case as we have no choice in
1269 * our source address selection - we must obey the peer.
1271 * The wording in RFC2462 is confusing, and there are
1272 * multiple description text for deprecated address
1273 * handling - worse, they are not exactly the same.
1274 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1276 if (isipv6 && !V_ip6_use_deprecated) {
1277 struct in6_ifaddr *ia6;
1279 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
1281 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1282 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1283 log(LOG_DEBUG, "%s; %s: Listen socket: "
1284 "Connection attempt to deprecated "
1285 "IPv6 address rejected\n",
1287 rstreason = BANDLIM_RST_OPENPORT;
1293 * Basic sanity checks on incoming SYN requests:
1294 * Don't respond if the destination is a link layer
1295 * broadcast according to RFC1122 4.2.3.10, p. 104.
1296 * If it is from this socket it must be forged.
1297 * Don't respond if the source or destination is a
1298 * global or subnet broad- or multicast address.
1299 * Note that it is quite possible to receive unicast
1300 * link-layer packets with a broadcast IP address. Use
1301 * in_broadcast() to find them.
1303 if (m->m_flags & (M_BCAST|M_MCAST)) {
1304 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1305 log(LOG_DEBUG, "%s; %s: Listen socket: "
1306 "Connection attempt from broad- or multicast "
1307 "link layer address ignored\n", s, __func__);
1312 if (th->th_dport == th->th_sport &&
1313 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1314 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1315 log(LOG_DEBUG, "%s; %s: Listen socket: "
1316 "Connection attempt to/from self "
1317 "ignored\n", s, __func__);
1320 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1321 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1322 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1323 log(LOG_DEBUG, "%s; %s: Listen socket: "
1324 "Connection attempt from/to multicast "
1325 "address ignored\n", s, __func__);
1330 #if defined(INET) && defined(INET6)
1335 if (th->th_dport == th->th_sport &&
1336 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1337 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1338 log(LOG_DEBUG, "%s; %s: Listen socket: "
1339 "Connection attempt from/to self "
1340 "ignored\n", s, __func__);
1343 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1344 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1345 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1346 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1347 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1348 log(LOG_DEBUG, "%s; %s: Listen socket: "
1349 "Connection attempt from/to broad- "
1350 "or multicast address ignored\n",
1357 * SYN appears to be valid. Create compressed TCP state
1360 TCP_PROBE3(debug__input, tp, th, m);
1361 tcp_dooptions(&to, optp, optlen, TO_SYN);
1362 if ((so = syncache_add(&inc, &to, th, inp, so, m, NULL, NULL,
1363 iptos, port)) != NULL)
1364 goto tfo_socket_result;
1367 * Entry added to syncache and mbuf consumed.
1368 * Only the listen socket is unlocked by syncache_add().
1370 return (IPPROTO_DONE);
1371 } else if (tp->t_state == TCPS_LISTEN) {
1373 * When a listen socket is torn down the SO_ACCEPTCONN
1374 * flag is removed first while connections are drained
1375 * from the accept queue in a unlock/lock cycle of the
1376 * ACCEPT_LOCK, opening a race condition allowing a SYN
1377 * attempt go through unhandled.
1381 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1382 if (tp->t_flags & TF_SIGNATURE) {
1383 tcp_dooptions(&to, optp, optlen, thflags);
1384 if ((to.to_flags & TOF_SIGNATURE) == 0) {
1385 TCPSTAT_INC(tcps_sig_err_nosigopt);
1388 if (!TCPMD5_ENABLED() ||
1389 TCPMD5_INPUT(m, th, to.to_signature) != 0)
1393 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1396 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1397 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1398 * the inpcb, and unlocks pcbinfo.
1400 * XXXGL: in case of a pure SYN arriving on existing connection
1401 * TCP stacks won't need to modify the PCB, they would either drop
1402 * the segment silently, or send a challenge ACK. However, we try
1403 * to upgrade the lock, because calling convention for stacks is
1404 * write-lock on PCB. If upgrade fails, drop the SYN.
1406 if ((lookupflag & INPLOOKUP_RLOCKPCB) && INP_TRY_UPGRADE(inp) == 0)
1409 tp->t_fb->tfb_tcp_do_segment(tp, m, th, drop_hdrlen, tlen, iptos);
1410 return (IPPROTO_DONE);
1413 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1416 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1419 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1420 m = NULL; /* mbuf chain got consumed. */
1425 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1435 return (IPPROTO_DONE);
1439 * Automatic sizing of receive socket buffer. Often the send
1440 * buffer size is not optimally adjusted to the actual network
1441 * conditions at hand (delay bandwidth product). Setting the
1442 * buffer size too small limits throughput on links with high
1443 * bandwidth and high delay (eg. trans-continental/oceanic links).
1445 * On the receive side the socket buffer memory is only rarely
1446 * used to any significant extent. This allows us to be much
1447 * more aggressive in scaling the receive socket buffer. For
1448 * the case that the buffer space is actually used to a large
1449 * extent and we run out of kernel memory we can simply drop
1450 * the new segments; TCP on the sender will just retransmit it
1451 * later. Setting the buffer size too big may only consume too
1452 * much kernel memory if the application doesn't read() from
1453 * the socket or packet loss or reordering makes use of the
1456 * The criteria to step up the receive buffer one notch are:
1457 * 1. Application has not set receive buffer size with
1458 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1459 * 2. the number of bytes received during 1/2 of an sRTT
1460 * is at least 3/8 of the current socket buffer size.
1461 * 3. receive buffer size has not hit maximal automatic size;
1463 * If all of the criteria are met we increaset the socket buffer
1464 * by a 1/2 (bounded by the max). This allows us to keep ahead
1465 * of slow-start but also makes it so our peer never gets limited
1466 * by our rwnd which we then open up causing a burst.
1468 * This algorithm does two steps per RTT at most and only if
1469 * we receive a bulk stream w/o packet losses or reorderings.
1470 * Shrinking the buffer during idle times is not necessary as
1471 * it doesn't consume any memory when idle.
1473 * TODO: Only step up if the application is actually serving
1474 * the buffer to better manage the socket buffer resources.
1477 tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1478 struct tcpcb *tp, int tlen)
1482 if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1483 tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1484 TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1485 ((tp->t_srtt >> TCP_RTT_SHIFT)/2)) {
1486 if (tp->rfbuf_cnt > ((so->so_rcv.sb_hiwat / 2)/ 4 * 3) &&
1487 so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1488 newsize = min((so->so_rcv.sb_hiwat + (so->so_rcv.sb_hiwat/2)), V_tcp_autorcvbuf_max);
1490 TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1492 /* Start over with next RTT. */
1496 tp->rfbuf_cnt += tlen; /* add up */
1502 tcp_input(struct mbuf **mp, int *offp, int proto)
1504 return(tcp_input_with_port(mp, offp, proto, 0));
1508 tcp_handle_wakeup(struct tcpcb *tp)
1511 INP_WLOCK_ASSERT(tptoinpcb(tp));
1513 if (tp->t_flags & TF_WAKESOR) {
1514 struct socket *so = tptosocket(tp);
1516 tp->t_flags &= ~TF_WAKESOR;
1517 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1518 sorwakeup_locked(so);
1523 tcp_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
1524 int drop_hdrlen, int tlen, uint8_t iptos)
1527 int acked, ourfinisacked, needoutput = 0;
1528 sackstatus_t sack_changed;
1529 int rstreason, todrop, win, incforsyn = 0;
1533 struct inpcb *inp = tptoinpcb(tp);
1534 struct socket *so = tptosocket(tp);
1535 struct in_conninfo *inc = &inp->inp_inc;
1541 thflags = tcp_get_flags(th);
1542 tp->sackhint.last_sack_ack = 0;
1543 sack_changed = SACK_NOCHANGE;
1544 nsegs = max(1, m->m_pkthdr.lro_nsegs);
1547 INP_WLOCK_ASSERT(inp);
1548 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1550 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1554 /* Save segment, if requested. */
1555 tcp_pcap_add(th, m, &(tp->t_inpkts));
1557 TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
1560 if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1561 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1562 log(LOG_DEBUG, "%s; %s: "
1563 "SYN|FIN segment ignored (based on "
1564 "sysctl setting)\n", s, __func__);
1571 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1572 * check SEQ.ACK first.
1574 if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1575 (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1576 rstreason = BANDLIM_UNLIMITED;
1577 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
1582 * Segment received on connection.
1583 * Reset idle time and keep-alive timer.
1584 * XXX: This should be done after segment
1585 * validation to ignore broken/spoofed segs.
1587 if (tp->t_idle_reduce &&
1588 (tp->snd_max == tp->snd_una) &&
1589 ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
1591 tp->t_rcvtime = ticks;
1593 if (thflags & TH_FIN)
1594 tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
1596 * Scale up the window into a 32-bit value.
1597 * For the SYN_SENT state the scale is zero.
1599 tiwin = th->th_win << tp->snd_scale;
1601 stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
1605 * TCP ECN processing.
1607 if (tcp_ecn_input_segment(tp, thflags, tlen,
1608 tcp_packets_this_ack(tp, th->th_ack),
1610 cc_cong_signal(tp, th, CC_ECN);
1613 * Parse options on any incoming segment.
1615 tcp_dooptions(&to, (u_char *)(th + 1),
1616 (th->th_off << 2) - sizeof(struct tcphdr),
1617 (thflags & TH_SYN) ? TO_SYN : 0);
1619 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1620 if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1621 (to.to_flags & TOF_SIGNATURE) == 0) {
1622 TCPSTAT_INC(tcps_sig_err_sigopt);
1623 /* XXX: should drop? */
1627 * If echoed timestamp is later than the current time,
1628 * fall back to non RFC1323 RTT calculation. Normalize
1629 * timestamp if syncookies were used when this connection
1632 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1633 to.to_tsecr -= tp->ts_offset;
1634 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks())) {
1636 } else if (tp->t_rxtshift == 1 &&
1637 tp->t_flags & TF_PREVVALID &&
1638 tp->t_badrxtwin != 0 &&
1639 TSTMP_LT(to.to_tsecr, tp->t_badrxtwin)) {
1640 cc_cong_signal(tp, th, CC_RTO_ERR);
1644 * Process options only when we get SYN/ACK back. The SYN case
1645 * for incoming connections is handled in tcp_syncache.
1646 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1647 * or <SYN,ACK>) segment itself is never scaled.
1648 * XXX this is traditional behavior, may need to be cleaned up.
1650 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1651 /* Handle parallel SYN for ECN */
1652 tcp_ecn_input_parallel_syn(tp, thflags, iptos);
1653 if ((to.to_flags & TOF_SCALE) &&
1654 (tp->t_flags & TF_REQ_SCALE) &&
1655 !(tp->t_flags & TF_NOOPT)) {
1656 tp->t_flags |= TF_RCVD_SCALE;
1657 tp->snd_scale = to.to_wscale;
1659 tp->t_flags &= ~TF_REQ_SCALE;
1662 * Initial send window. It will be updated with
1663 * the next incoming segment to the scaled value.
1665 tp->snd_wnd = th->th_win;
1666 if ((to.to_flags & TOF_TS) &&
1667 (tp->t_flags & TF_REQ_TSTMP) &&
1668 !(tp->t_flags & TF_NOOPT)) {
1669 tp->t_flags |= TF_RCVD_TSTMP;
1670 tp->ts_recent = to.to_tsval;
1671 tp->ts_recent_age = tcp_ts_getticks();
1673 tp->t_flags &= ~TF_REQ_TSTMP;
1675 if (to.to_flags & TOF_MSS) {
1676 tcp_mss(tp, to.to_mss);
1678 if ((tp->t_flags & TF_SACK_PERMIT) &&
1679 (!(to.to_flags & TOF_SACKPERM) ||
1680 (tp->t_flags & TF_NOOPT))) {
1681 tp->t_flags &= ~TF_SACK_PERMIT;
1683 if (tp->t_flags & TF_FASTOPEN) {
1684 if ((to.to_flags & TOF_FASTOPEN) &&
1685 !(tp->t_flags & TF_NOOPT)) {
1688 if (to.to_flags & TOF_MSS) {
1691 if ((inp->inp_vflag & INP_IPV6) != 0) {
1697 tcp_fastopen_update_cache(tp, mss,
1698 to.to_tfo_len, to.to_tfo_cookie);
1700 tcp_fastopen_disable_path(tp);
1706 * If timestamps were negotiated during SYN/ACK and a
1707 * segment without a timestamp is received, silently drop
1708 * the segment, unless it is a RST segment or missing timestamps are
1710 * See section 3.2 of RFC 7323.
1712 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1713 if (((thflags & TH_RST) != 0) || V_tcp_tolerate_missing_ts) {
1714 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1715 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1716 "segment processed normally\n",
1721 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1722 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1723 "segment silently dropped\n", s, __func__);
1730 * If timestamps were not negotiated during SYN/ACK and a
1731 * segment with a timestamp is received, ignore the
1732 * timestamp and process the packet normally.
1733 * See section 3.2 of RFC 7323.
1735 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1736 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1737 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1738 "segment processed normally\n", s, __func__);
1744 * Header prediction: check for the two common cases
1745 * of a uni-directional data xfer. If the packet has
1746 * no control flags, is in-sequence, the window didn't
1747 * change and we're not retransmitting, it's a
1748 * candidate. If the length is zero and the ack moved
1749 * forward, we're the sender side of the xfer. Just
1750 * free the data acked & wake any higher level process
1751 * that was blocked waiting for space. If the length
1752 * is non-zero and the ack didn't move, we're the
1753 * receiver side. If we're getting packets in-order
1754 * (the reassembly queue is empty), add the data to
1755 * the socket buffer and note that we need a delayed ack.
1756 * Make sure that the hidden state-flags are also off.
1757 * Since we check for TCPS_ESTABLISHED first, it can only
1760 if (tp->t_state == TCPS_ESTABLISHED &&
1761 th->th_seq == tp->rcv_nxt &&
1762 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1763 tp->snd_nxt == tp->snd_max &&
1764 tiwin && tiwin == tp->snd_wnd &&
1765 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1767 ((to.to_flags & TOF_TS) == 0 ||
1768 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1770 * If last ACK falls within this segment's sequence numbers,
1771 * record the timestamp.
1772 * NOTE that the test is modified according to the latest
1773 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1775 if ((to.to_flags & TOF_TS) != 0 &&
1776 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1777 tp->ts_recent_age = tcp_ts_getticks();
1778 tp->ts_recent = to.to_tsval;
1782 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1783 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1784 !IN_RECOVERY(tp->t_flags) &&
1785 (to.to_flags & TOF_SACK) == 0 &&
1786 TAILQ_EMPTY(&tp->snd_holes)) {
1788 * This is a pure ack for outstanding data.
1790 TCPSTAT_INC(tcps_predack);
1793 * "bad retransmit" recovery without timestamps.
1795 if ((to.to_flags & TOF_TS) == 0 &&
1796 tp->t_rxtshift == 1 &&
1797 tp->t_flags & TF_PREVVALID &&
1798 tp->t_badrxtwin != 0 &&
1799 TSTMP_LT(ticks, tp->t_badrxtwin)) {
1800 cc_cong_signal(tp, th, CC_RTO_ERR);
1804 * Recalculate the transmit timer / rtt.
1806 * Some boxes send broken timestamp replies
1807 * during the SYN+ACK phase, ignore
1808 * timestamps of 0 or we could calculate a
1809 * huge RTT and blow up the retransmit timer.
1811 if ((to.to_flags & TOF_TS) != 0 &&
1815 t = tcp_ts_getticks() - to.to_tsecr;
1816 if (!tp->t_rttlow || tp->t_rttlow > t)
1819 TCP_TS_TO_TICKS(t) + 1);
1820 } else if (tp->t_rtttime &&
1821 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1822 if (!tp->t_rttlow ||
1823 tp->t_rttlow > ticks - tp->t_rtttime)
1824 tp->t_rttlow = ticks - tp->t_rtttime;
1826 ticks - tp->t_rtttime);
1828 acked = BYTES_THIS_ACK(tp, th);
1831 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1832 hhook_run_tcp_est_in(tp, th, &to);
1835 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
1836 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1837 sbdrop(&so->so_snd, acked);
1838 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1839 SEQ_LEQ(th->th_ack, tp->snd_recover))
1840 tp->snd_recover = th->th_ack - 1;
1843 * Let the congestion control algorithm update
1844 * congestion control related information. This
1845 * typically means increasing the congestion
1848 cc_ack_received(tp, th, nsegs, CC_ACK);
1850 tp->snd_una = th->th_ack;
1852 * Pull snd_wl2 up to prevent seq wrap relative
1855 tp->snd_wl2 = th->th_ack;
1860 * If all outstanding data are acked, stop
1861 * retransmit timer, otherwise restart timer
1862 * using current (possibly backed-off) value.
1863 * If process is waiting for space,
1864 * wakeup/selwakeup/signal. If data
1865 * are ready to send, let tcp_output
1866 * decide between more output or persist.
1868 TCP_PROBE3(debug__input, tp, th, m);
1870 * Clear t_acktime if remote side has ACKd
1871 * all data in the socket buffer.
1872 * Otherwise, update t_acktime if we received
1873 * a sufficiently large ACK.
1875 if (sbavail(&so->so_snd) == 0)
1878 tp->t_acktime = ticks;
1879 if (tp->snd_una == tp->snd_max)
1880 tcp_timer_activate(tp, TT_REXMT, 0);
1881 else if (!tcp_timer_active(tp, TT_PERSIST))
1882 tcp_timer_activate(tp, TT_REXMT,
1886 * Only call tcp_output when there
1887 * is new data available to be sent
1888 * or we need to send an ACK.
1890 if ((tp->t_flags & TF_ACKNOW) ||
1891 (sbavail(&so->so_snd) >=
1892 SEQ_SUB(tp->snd_max, tp->snd_una))) {
1893 (void) tcp_output(tp);
1897 } else if (th->th_ack == tp->snd_una &&
1898 tlen <= sbspace(&so->so_rcv)) {
1899 int newsize = 0; /* automatic sockbuf scaling */
1902 * This is a pure, in-sequence data packet with
1903 * nothing on the reassembly queue and we have enough
1904 * buffer space to take it.
1906 /* Clean receiver SACK report if present */
1907 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1908 tcp_clean_sackreport(tp);
1909 TCPSTAT_INC(tcps_preddat);
1910 tp->rcv_nxt += tlen;
1912 ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
1913 (tp->t_fbyte_in == 0)) {
1914 tp->t_fbyte_in = ticks;
1915 if (tp->t_fbyte_in == 0)
1917 if (tp->t_fbyte_out && tp->t_fbyte_in)
1918 tp->t_flags2 |= TF2_FBYTES_COMPLETE;
1921 * Pull snd_wl1 up to prevent seq wrap relative to
1924 tp->snd_wl1 = th->th_seq;
1926 * Pull rcv_up up to prevent seq wrap relative to
1929 tp->rcv_up = tp->rcv_nxt;
1930 TCPSTAT_ADD(tcps_rcvpack, nsegs);
1931 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1932 TCP_PROBE3(debug__input, tp, th, m);
1934 newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
1936 /* Add data to socket buffer. */
1937 SOCKBUF_LOCK(&so->so_rcv);
1938 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1942 * Set new socket buffer size.
1943 * Give up when limit is reached.
1946 if (!sbreserve_locked(so, SO_RCV,
1948 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1949 m_adj(m, drop_hdrlen); /* delayed header drop */
1950 sbappendstream_locked(&so->so_rcv, m, 0);
1952 /* NB: sorwakeup_locked() does an implicit unlock. */
1953 sorwakeup_locked(so);
1954 if (DELAY_ACK(tp, tlen)) {
1955 tp->t_flags |= TF_DELACK;
1957 tp->t_flags |= TF_ACKNOW;
1965 * Calculate amount of space in receive window,
1966 * and then do TCP input processing.
1967 * Receive window is amount of space in rcv queue,
1968 * but not less than advertised window.
1970 win = sbspace(&so->so_rcv);
1973 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1975 switch (tp->t_state) {
1977 * If the state is SYN_RECEIVED:
1978 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1980 case TCPS_SYN_RECEIVED:
1981 if (thflags & TH_RST) {
1982 /* Handle RST segments later. */
1985 if ((thflags & TH_ACK) &&
1986 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1987 SEQ_GT(th->th_ack, tp->snd_max))) {
1988 rstreason = BANDLIM_RST_OPENPORT;
1989 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
1992 if (tp->t_flags & TF_FASTOPEN) {
1994 * When a TFO connection is in SYN_RECEIVED, the
1995 * only valid packets are the initial SYN, a
1996 * retransmit/copy of the initial SYN (possibly with
1997 * a subset of the original data), a valid ACK, a
2000 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
2001 rstreason = BANDLIM_RST_OPENPORT;
2002 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2004 } else if (thflags & TH_SYN) {
2005 /* non-initial SYN is ignored */
2006 if ((tcp_timer_active(tp, TT_DELACK) ||
2007 tcp_timer_active(tp, TT_REXMT)))
2009 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
2016 * If the state is SYN_SENT:
2017 * if seg contains a RST with valid ACK (SEQ.ACK has already
2018 * been verified), then drop the connection.
2019 * if seg contains a RST without an ACK, drop the seg.
2020 * if seg does not contain SYN, then drop the seg.
2021 * Otherwise this is an acceptable SYN segment
2022 * initialize tp->rcv_nxt and tp->irs
2023 * if seg contains ack then advance tp->snd_una
2024 * if seg contains an ECE and ECN support is enabled, the stream
2026 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2027 * arrange for segment to be acked (eventually)
2028 * continue processing rest of data/controls, beginning with URG
2031 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2032 TCP_PROBE5(connect__refused, NULL, tp,
2034 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2035 tp = tcp_drop(tp, ECONNREFUSED);
2037 if (thflags & TH_RST)
2039 if (!(thflags & TH_SYN))
2042 tp->irs = th->th_seq;
2044 if (thflags & TH_ACK) {
2045 int tfo_partial_ack = 0;
2047 TCPSTAT_INC(tcps_connects);
2050 mac_socketpeer_set_from_mbuf(m, so);
2052 /* Do window scaling on this connection? */
2053 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2054 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2055 tp->rcv_scale = tp->request_r_scale;
2057 tp->rcv_adv += min(tp->rcv_wnd,
2058 TCP_MAXWIN << tp->rcv_scale);
2059 tp->snd_una++; /* SYN is acked */
2060 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2061 tp->snd_nxt = tp->snd_una;
2063 * If not all the data that was sent in the TFO SYN
2064 * has been acked, resend the remainder right away.
2066 if ((tp->t_flags & TF_FASTOPEN) &&
2067 (tp->snd_una != tp->snd_max)) {
2068 tp->snd_nxt = th->th_ack;
2069 tfo_partial_ack = 1;
2072 * If there's data, delay ACK; if there's also a FIN
2073 * ACKNOW will be turned on later.
2075 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
2076 tcp_timer_activate(tp, TT_DELACK,
2079 tp->t_flags |= TF_ACKNOW;
2081 tcp_ecn_input_syn_sent(tp, thflags, iptos);
2084 * Received <SYN,ACK> in SYN_SENT[*] state.
2086 * SYN_SENT --> ESTABLISHED
2087 * SYN_SENT* --> FIN_WAIT_1
2089 tp->t_starttime = ticks;
2090 if (tp->t_flags & TF_NEEDFIN) {
2091 tp->t_acktime = ticks;
2092 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2093 tp->t_flags &= ~TF_NEEDFIN;
2096 tcp_state_change(tp, TCPS_ESTABLISHED);
2097 TCP_PROBE5(connect__established, NULL, tp,
2100 tcp_timer_activate(tp, TT_KEEP,
2105 * Received initial SYN in SYN-SENT[*] state =>
2106 * simultaneous open.
2107 * If it succeeds, connection is * half-synchronized.
2108 * Otherwise, do 3-way handshake:
2109 * SYN-SENT -> SYN-RECEIVED
2110 * SYN-SENT* -> SYN-RECEIVED*
2112 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
2113 tcp_timer_activate(tp, TT_REXMT, 0);
2114 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2118 * Advance th->th_seq to correspond to first data byte.
2119 * If data, trim to stay within window,
2120 * dropping FIN if necessary.
2123 if (tlen > tp->rcv_wnd) {
2124 todrop = tlen - tp->rcv_wnd;
2128 TCPSTAT_INC(tcps_rcvpackafterwin);
2129 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2131 tp->snd_wl1 = th->th_seq - 1;
2132 tp->rcv_up = th->th_seq;
2134 * Client side of transaction: already sent SYN and data.
2135 * If the remote host used T/TCP to validate the SYN,
2136 * our data will be ACK'd; if so, enter normal data segment
2137 * processing in the middle of step 5, ack processing.
2138 * Otherwise, goto step 6.
2140 if (thflags & TH_ACK)
2147 * States other than LISTEN or SYN_SENT.
2148 * First check the RST flag and sequence number since reset segments
2149 * are exempt from the timestamp and connection count tests. This
2150 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2151 * below which allowed reset segments in half the sequence space
2152 * to fall though and be processed (which gives forged reset
2153 * segments with a random sequence number a 50 percent chance of
2154 * killing a connection).
2155 * Then check timestamp, if present.
2156 * Then check the connection count, if present.
2157 * Then check that at least some bytes of segment are within
2158 * receive window. If segment begins before rcv_nxt,
2159 * drop leading data (and SYN); if nothing left, just ack.
2161 if (thflags & TH_RST) {
2163 * RFC5961 Section 3.2
2165 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2166 * - If RST is in window, we send challenge ACK.
2168 * Note: to take into account delayed ACKs, we should
2169 * test against last_ack_sent instead of rcv_nxt.
2170 * Note 2: we handle special case of closed window, not
2171 * covered by the RFC.
2173 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2174 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2175 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2176 KASSERT(tp->t_state != TCPS_SYN_SENT,
2177 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2180 if (V_tcp_insecure_rst ||
2181 tp->last_ack_sent == th->th_seq) {
2182 TCPSTAT_INC(tcps_drops);
2183 /* Drop the connection. */
2184 switch (tp->t_state) {
2185 case TCPS_SYN_RECEIVED:
2186 so->so_error = ECONNREFUSED;
2188 case TCPS_ESTABLISHED:
2189 case TCPS_FIN_WAIT_1:
2190 case TCPS_FIN_WAIT_2:
2191 case TCPS_CLOSE_WAIT:
2194 so->so_error = ECONNRESET;
2198 tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
2202 TCPSTAT_INC(tcps_badrst);
2203 /* Send challenge ACK. */
2204 tcp_respond(tp, mtod(m, void *), th, m,
2205 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2206 tp->last_ack_sent = tp->rcv_nxt;
2214 * RFC5961 Section 4.2
2215 * Send challenge ACK for any SYN in synchronized state.
2217 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2218 tp->t_state != TCPS_SYN_RECEIVED) {
2219 TCPSTAT_INC(tcps_badsyn);
2220 if (V_tcp_insecure_syn &&
2221 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2222 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2223 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2224 tp = tcp_drop(tp, ECONNRESET);
2225 rstreason = BANDLIM_UNLIMITED;
2227 tcp_ecn_input_syn_sent(tp, thflags, iptos);
2228 /* Send challenge ACK. */
2229 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2230 tp->snd_nxt, TH_ACK);
2231 tp->last_ack_sent = tp->rcv_nxt;
2238 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2239 * and it's less than ts_recent, drop it.
2241 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2242 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2243 /* Check to see if ts_recent is over 24 days old. */
2244 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2246 * Invalidate ts_recent. If this segment updates
2247 * ts_recent, the age will be reset later and ts_recent
2248 * will get a valid value. If it does not, setting
2249 * ts_recent to zero will at least satisfy the
2250 * requirement that zero be placed in the timestamp
2251 * echo reply when ts_recent isn't valid. The
2252 * age isn't reset until we get a valid ts_recent
2253 * because we don't want out-of-order segments to be
2254 * dropped when ts_recent is old.
2258 TCPSTAT_INC(tcps_rcvduppack);
2259 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2260 TCPSTAT_INC(tcps_pawsdrop);
2268 * In the SYN-RECEIVED state, validate that the packet belongs to
2269 * this connection before trimming the data to fit the receive
2270 * window. Check the sequence number versus IRS since we know
2271 * the sequence numbers haven't wrapped. This is a partial fix
2272 * for the "LAND" DoS attack.
2274 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2275 rstreason = BANDLIM_RST_OPENPORT;
2276 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
2280 todrop = tp->rcv_nxt - th->th_seq;
2282 if (thflags & TH_SYN) {
2292 * Following if statement from Stevens, vol. 2, p. 960.
2295 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2297 * Any valid FIN must be to the left of the window.
2298 * At this point the FIN must be a duplicate or out
2299 * of sequence; drop it.
2304 * Send an ACK to resynchronize and drop any data.
2305 * But keep on processing for RST or ACK.
2307 tp->t_flags |= TF_ACKNOW;
2309 TCPSTAT_INC(tcps_rcvduppack);
2310 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2312 TCPSTAT_INC(tcps_rcvpartduppack);
2313 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2316 * DSACK - add SACK block for dropped range
2318 if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2319 tcp_update_sack_list(tp, th->th_seq,
2320 th->th_seq + todrop);
2322 * ACK now, as the next in-sequence segment
2323 * will clear the DSACK block again
2325 tp->t_flags |= TF_ACKNOW;
2327 drop_hdrlen += todrop; /* drop from the top afterwards */
2328 th->th_seq += todrop;
2330 if (th->th_urp > todrop)
2331 th->th_urp -= todrop;
2339 * If new data are received on a connection after the
2340 * user processes are gone, then RST the other end.
2342 if ((tp->t_flags & TF_CLOSED) && tlen) {
2343 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2344 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2345 "after socket was closed, "
2346 "sending RST and removing tcpcb\n",
2347 s, __func__, tcpstates[tp->t_state], tlen);
2350 tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
2351 /* tcp_close will kill the inp pre-log the Reset */
2352 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
2354 TCPSTAT_INC(tcps_rcvafterclose);
2355 rstreason = BANDLIM_UNLIMITED;
2360 * If segment ends after window, drop trailing data
2361 * (and PUSH and FIN); if nothing left, just ACK.
2363 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2365 TCPSTAT_INC(tcps_rcvpackafterwin);
2366 if (todrop >= tlen) {
2367 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2369 * If window is closed can only take segments at
2370 * window edge, and have to drop data and PUSH from
2371 * incoming segments. Continue processing, but
2372 * remember to ack. Otherwise, drop segment
2375 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2376 tp->t_flags |= TF_ACKNOW;
2377 TCPSTAT_INC(tcps_rcvwinprobe);
2381 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2384 thflags &= ~(TH_PUSH|TH_FIN);
2388 * If last ACK falls within this segment's sequence numbers,
2389 * record its timestamp.
2391 * 1) That the test incorporates suggestions from the latest
2392 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2393 * 2) That updating only on newer timestamps interferes with
2394 * our earlier PAWS tests, so this check should be solely
2395 * predicated on the sequence space of this segment.
2396 * 3) That we modify the segment boundary check to be
2397 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2398 * instead of RFC1323's
2399 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2400 * This modified check allows us to overcome RFC1323's
2401 * limitations as described in Stevens TCP/IP Illustrated
2402 * Vol. 2 p.869. In such cases, we can still calculate the
2403 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2405 if ((to.to_flags & TOF_TS) != 0 &&
2406 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2407 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2408 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2409 tp->ts_recent_age = tcp_ts_getticks();
2410 tp->ts_recent = to.to_tsval;
2414 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2415 * flag is on (half-synchronized state), then queue data for
2416 * later processing; else drop segment and return.
2418 if ((thflags & TH_ACK) == 0) {
2419 if (tp->t_state == TCPS_SYN_RECEIVED ||
2420 (tp->t_flags & TF_NEEDSYN)) {
2421 if (tp->t_state == TCPS_SYN_RECEIVED &&
2422 (tp->t_flags & TF_FASTOPEN)) {
2423 tp->snd_wnd = tiwin;
2427 } else if (tp->t_flags & TF_ACKNOW)
2436 switch (tp->t_state) {
2438 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2439 * ESTABLISHED state and continue processing.
2440 * The ACK was checked above.
2442 case TCPS_SYN_RECEIVED:
2444 TCPSTAT_INC(tcps_connects);
2445 if (tp->t_flags & TF_SONOTCONN) {
2447 * Usually SYN_RECEIVED had been created from a LISTEN,
2448 * and solisten_enqueue() has already marked the socket
2449 * layer as connected. If it didn't, which can happen
2450 * only with an accept_filter(9), then the tp is marked
2451 * with TF_SONOTCONN. The other reason for this mark
2452 * to be set is a simultaneous open, a SYN_RECEIVED
2453 * that had been created from SYN_SENT.
2455 tp->t_flags &= ~TF_SONOTCONN;
2458 /* Do window scaling? */
2459 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2460 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2461 tp->rcv_scale = tp->request_r_scale;
2463 tp->snd_wnd = tiwin;
2466 * SYN-RECEIVED -> ESTABLISHED
2467 * SYN-RECEIVED* -> FIN-WAIT-1
2469 tp->t_starttime = ticks;
2470 if ((tp->t_flags & TF_FASTOPEN) && tp->t_tfo_pending) {
2471 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2472 tp->t_tfo_pending = NULL;
2474 if (tp->t_flags & TF_NEEDFIN) {
2475 tp->t_acktime = ticks;
2476 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2477 tp->t_flags &= ~TF_NEEDFIN;
2479 tcp_state_change(tp, TCPS_ESTABLISHED);
2480 TCP_PROBE5(accept__established, NULL, tp,
2483 * TFO connections call cc_conn_init() during SYN
2484 * processing. Calling it again here for such
2485 * connections is not harmless as it would undo the
2486 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2489 if (!(tp->t_flags & TF_FASTOPEN))
2491 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2494 * Account for the ACK of our SYN prior to
2495 * regular ACK processing below, except for
2496 * simultaneous SYN, which is handled later.
2498 if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2501 * If segment contains data or ACK, will call tcp_reass()
2502 * later; if not, do so now to pass queued data to user.
2504 if (tlen == 0 && (thflags & TH_FIN) == 0) {
2505 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2507 tcp_handle_wakeup(tp);
2509 tp->snd_wl1 = th->th_seq - 1;
2513 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2514 * ACKs. If the ack is in the range
2515 * tp->snd_una < th->th_ack <= tp->snd_max
2516 * then advance tp->snd_una to th->th_ack and drop
2517 * data from the retransmission queue. If this ACK reflects
2518 * more up to date window information we update our window information.
2520 case TCPS_ESTABLISHED:
2521 case TCPS_FIN_WAIT_1:
2522 case TCPS_FIN_WAIT_2:
2523 case TCPS_CLOSE_WAIT:
2526 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2527 TCPSTAT_INC(tcps_rcvacktoomuch);
2530 if (tcp_is_sack_recovery(tp, &to)) {
2531 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2532 if ((sack_changed != SACK_NOCHANGE) &&
2533 (tp->t_flags & TF_LRD)) {
2534 tcp_sack_lost_retransmission(tp, th);
2538 * Reset the value so that previous (valid) value
2539 * from the last ack with SACK doesn't get used.
2541 tp->sackhint.sacked_bytes = 0;
2544 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2545 hhook_run_tcp_est_in(tp, th, &to);
2548 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2549 maxseg = tcp_maxseg(tp);
2551 (tiwin == tp->snd_wnd ||
2552 (tp->t_flags & TF_SACK_PERMIT))) {
2554 * If this is the first time we've seen a
2555 * FIN from the remote, this is not a
2556 * duplicate and it needs to be processed
2557 * normally. This happens during a
2558 * simultaneous close.
2560 if ((thflags & TH_FIN) &&
2561 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2565 TCPSTAT_INC(tcps_rcvdupack);
2567 * If we have outstanding data (other than
2568 * a window probe), this is a completely
2569 * duplicate ack (ie, window info didn't
2570 * change and FIN isn't set),
2571 * the ack is the biggest we've
2572 * seen and we've seen exactly our rexmt
2573 * threshold of them, assume a packet
2574 * has been dropped and retransmit it.
2575 * Kludge snd_nxt & the congestion
2576 * window so we send only this one
2579 * We know we're losing at the current
2580 * window size so do congestion avoidance
2581 * (set ssthresh to half the current window
2582 * and pull our congestion window back to
2583 * the new ssthresh).
2585 * Dup acks mean that packets have left the
2586 * network (they're now cached at the receiver)
2587 * so bump cwnd by the amount in the receiver
2588 * to keep a constant cwnd packets in the
2591 * When using TCP ECN, notify the peer that
2592 * we reduced the cwnd.
2595 * Following 2 kinds of acks should not affect
2598 * 2) Acks with SACK but without any new SACK
2599 * information in them. These could result from
2600 * any anomaly in the network like a switch
2601 * duplicating packets or a possible DoS attack.
2603 if (th->th_ack != tp->snd_una ||
2604 (tcp_is_sack_recovery(tp, &to) &&
2605 (sack_changed == SACK_NOCHANGE))) {
2607 } else if (!tcp_timer_active(tp, TT_REXMT)) {
2609 } else if (++tp->t_dupacks > tcprexmtthresh ||
2610 IN_FASTRECOVERY(tp->t_flags)) {
2611 cc_ack_received(tp, th, nsegs,
2614 IN_FASTRECOVERY(tp->t_flags) &&
2615 (tp->t_flags & TF_SACK_PERMIT)) {
2616 tcp_do_prr_ack(tp, th, &to,
2617 sack_changed, &maxseg);
2618 } else if (tcp_is_sack_recovery(tp, &to) &&
2619 IN_FASTRECOVERY(tp->t_flags)) {
2623 * Compute the amount of data in flight first.
2624 * We can inject new data into the pipe iff
2625 * we have less than 1/2 the original window's
2626 * worth of data in flight.
2628 if (V_tcp_do_newsack) {
2629 awnd = tcp_compute_pipe(tp);
2631 awnd = (tp->snd_nxt - tp->snd_fack) +
2632 tp->sackhint.sack_bytes_rexmit;
2634 if (awnd < tp->snd_ssthresh) {
2635 tp->snd_cwnd += maxseg;
2636 if (tp->snd_cwnd > tp->snd_ssthresh)
2637 tp->snd_cwnd = tp->snd_ssthresh;
2640 tp->snd_cwnd += maxseg;
2642 (void) tcp_output(tp);
2644 } else if (tp->t_dupacks == tcprexmtthresh ||
2645 (tp->t_flags & TF_SACK_PERMIT &&
2647 tp->sackhint.sacked_bytes >
2648 (tcprexmtthresh - 1) * maxseg)) {
2651 * Above is the RFC6675 trigger condition of
2652 * more than (dupthresh-1)*maxseg sacked data.
2653 * If the count of holes in the
2654 * scoreboard is >= dupthresh, we could
2655 * also enter loss recovery, but don't
2656 * have that value readily available.
2658 tp->t_dupacks = tcprexmtthresh;
2659 tcp_seq onxt = tp->snd_nxt;
2662 * If we're doing sack, or prr, check
2663 * to see if we're already in sack
2664 * recovery. If we're not doing sack,
2665 * check to see if we're in newreno
2669 (tp->t_flags & TF_SACK_PERMIT)) {
2670 if (IN_FASTRECOVERY(tp->t_flags)) {
2675 if (SEQ_LEQ(th->th_ack,
2681 /* Congestion signal before ack. */
2682 cc_cong_signal(tp, th, CC_NDUPACK);
2683 cc_ack_received(tp, th, nsegs,
2685 tcp_timer_activate(tp, TT_REXMT, 0);
2689 * snd_ssthresh is already updated by
2692 if (tcp_is_sack_recovery(tp, &to)) {
2694 * Exclude Limited Transmit
2697 tp->sackhint.prr_delivered =
2700 tp->sackhint.prr_delivered =
2701 imin(tp->snd_max - tp->snd_una,
2702 imin(INT_MAX / 65536,
2703 tp->t_dupacks) * maxseg);
2705 tp->sackhint.recover_fs = max(1,
2706 tp->snd_nxt - tp->snd_una);
2708 if (tcp_is_sack_recovery(tp, &to)) {
2709 TCPSTAT_INC(tcps_sack_recovery_episode);
2710 tp->snd_recover = tp->snd_nxt;
2711 tp->snd_cwnd = maxseg;
2712 (void) tcp_output(tp);
2713 if (SEQ_GT(th->th_ack, tp->snd_una)) {
2714 goto resume_partialack;
2718 tp->snd_nxt = th->th_ack;
2719 tp->snd_cwnd = maxseg;
2720 (void) tcp_output(tp);
2721 KASSERT(tp->snd_limited <= 2,
2722 ("%s: tp->snd_limited too big",
2724 tp->snd_cwnd = tp->snd_ssthresh +
2726 (tp->t_dupacks - tp->snd_limited);
2727 if (SEQ_GT(onxt, tp->snd_nxt))
2730 } else if (V_tcp_do_rfc3042) {
2732 * Process first and second duplicate
2733 * ACKs. Each indicates a segment
2734 * leaving the network, creating room
2735 * for more. Make sure we can send a
2736 * packet on reception of each duplicate
2737 * ACK by increasing snd_cwnd by one
2738 * segment. Restore the original
2739 * snd_cwnd after packet transmission.
2741 cc_ack_received(tp, th, nsegs, CC_DUPACK);
2742 uint32_t oldcwnd = tp->snd_cwnd;
2743 tcp_seq oldsndmax = tp->snd_max;
2747 KASSERT(tp->t_dupacks == 1 ||
2749 ("%s: dupacks not 1 or 2",
2751 if (tp->t_dupacks == 1)
2752 tp->snd_limited = 0;
2754 (tp->snd_nxt - tp->snd_una) +
2755 (tp->t_dupacks - tp->snd_limited) *
2758 * Only call tcp_output when there
2759 * is new data available to be sent
2760 * or we need to send an ACK.
2762 SOCKBUF_LOCK(&so->so_snd);
2763 avail = sbavail(&so->so_snd);
2764 SOCKBUF_UNLOCK(&so->so_snd);
2765 if (tp->t_flags & TF_ACKNOW ||
2767 SEQ_SUB(tp->snd_nxt, tp->snd_una))) {
2768 (void) tcp_output(tp);
2770 sent = SEQ_SUB(tp->snd_max, oldsndmax);
2771 if (sent > maxseg) {
2772 KASSERT((tp->t_dupacks == 2 &&
2773 tp->snd_limited == 0) ||
2774 (sent == maxseg + 1 &&
2775 tp->t_flags & TF_SENTFIN),
2776 ("%s: sent too much",
2778 tp->snd_limited = 2;
2779 } else if (sent > 0) {
2782 tp->snd_cwnd = oldcwnd;
2789 * This ack is advancing the left edge, reset the
2794 * If this ack also has new SACK info, increment the
2795 * counter as per rfc6675. The variable
2796 * sack_changed tracks all changes to the SACK
2797 * scoreboard, including when partial ACKs without
2798 * SACK options are received, and clear the scoreboard
2799 * from the left side. Such partial ACKs should not be
2800 * counted as dupacks here.
2802 if (tcp_is_sack_recovery(tp, &to) &&
2803 (sack_changed != SACK_NOCHANGE)) {
2805 /* limit overhead by setting maxseg last */
2806 if (!IN_FASTRECOVERY(tp->t_flags) &&
2807 (tp->sackhint.sacked_bytes >
2808 ((tcprexmtthresh - 1) *
2809 (maxseg = tcp_maxseg(tp))))) {
2810 goto enter_recovery;
2816 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2817 ("%s: th_ack <= snd_una", __func__));
2820 * If the congestion window was inflated to account
2821 * for the other side's cached packets, retract it.
2823 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2824 if (IN_FASTRECOVERY(tp->t_flags)) {
2825 if (tp->t_flags & TF_SACK_PERMIT) {
2827 (to.to_flags & TOF_SACK)) {
2828 tcp_timer_activate(tp,
2831 tcp_do_prr_ack(tp, th, &to,
2832 sack_changed, &maxseg);
2833 tp->t_flags |= TF_ACKNOW;
2834 (void) tcp_output(tp);
2836 tcp_sack_partialack(tp, th,
2840 tcp_newreno_partial_ack(tp, th);
2842 } else if (IN_CONGRECOVERY(tp->t_flags) &&
2844 tp->sackhint.delivered_data =
2845 BYTES_THIS_ACK(tp, th);
2846 tp->snd_fack = th->th_ack;
2848 * During ECN cwnd reduction
2849 * always use PRR-SSRB
2851 tcp_do_prr_ack(tp, th, &to, SACK_CHANGE,
2853 (void) tcp_output(tp);
2857 * If we reach this point, ACK is not a duplicate,
2858 * i.e., it ACKs something we sent.
2860 if (tp->t_flags & TF_NEEDSYN) {
2862 * T/TCP: Connection was half-synchronized, and our
2863 * SYN has been ACK'd (so connection is now fully
2864 * synchronized). Go to non-starred state,
2865 * increment snd_una for ACK of SYN, and check if
2866 * we can do window scaling.
2868 tp->t_flags &= ~TF_NEEDSYN;
2870 /* Do window scaling? */
2871 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2872 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2873 tp->rcv_scale = tp->request_r_scale;
2874 /* Send window already scaled. */
2879 INP_WLOCK_ASSERT(inp);
2882 * Adjust for the SYN bit in sequence space,
2883 * but don't account for it in cwnd calculations.
2884 * This is for the SYN_RECEIVED, non-simultaneous
2885 * SYN case. SYN_SENT and simultaneous SYN are
2886 * treated elsewhere.
2890 acked = BYTES_THIS_ACK(tp, th);
2891 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2892 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2893 tp->snd_una, th->th_ack, tp, m));
2894 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
2895 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2898 * If we just performed our first retransmit, and the ACK
2899 * arrives within our recovery window, then it was a mistake
2900 * to do the retransmit in the first place. Recover our
2901 * original cwnd and ssthresh, and proceed to transmit where
2904 if (tp->t_rxtshift == 1 &&
2905 tp->t_flags & TF_PREVVALID &&
2906 tp->t_badrxtwin != 0 &&
2907 to.to_flags & TOF_TS &&
2909 TSTMP_LT(to.to_tsecr, tp->t_badrxtwin))
2910 cc_cong_signal(tp, th, CC_RTO_ERR);
2913 * If we have a timestamp reply, update smoothed
2914 * round trip time. If no timestamp is present but
2915 * transmit timer is running and timed sequence
2916 * number was acked, update smoothed round trip time.
2917 * Since we now have an rtt measurement, cancel the
2918 * timer backoff (cf., Phil Karn's retransmit alg.).
2919 * Recompute the initial retransmit timer.
2921 * Some boxes send broken timestamp replies
2922 * during the SYN+ACK phase, ignore
2923 * timestamps of 0 or we could calculate a
2924 * huge RTT and blow up the retransmit timer.
2926 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2929 t = tcp_ts_getticks() - to.to_tsecr;
2930 if (!tp->t_rttlow || tp->t_rttlow > t)
2932 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2933 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2934 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2935 tp->t_rttlow = ticks - tp->t_rtttime;
2936 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2939 SOCKBUF_LOCK(&so->so_snd);
2941 * Clear t_acktime if remote side has ACKd all data in the
2942 * socket buffer and FIN (if applicable).
2943 * Otherwise, update t_acktime if we received a sufficiently
2946 if ((tp->t_state <= TCPS_CLOSE_WAIT &&
2947 acked == sbavail(&so->so_snd)) ||
2948 acked > sbavail(&so->so_snd))
2951 tp->t_acktime = ticks;
2954 * If all outstanding data is acked, stop retransmit
2955 * timer and remember to restart (more output or persist).
2956 * If there is more data to be acked, restart retransmit
2957 * timer, using current (possibly backed-off) value.
2959 if (th->th_ack == tp->snd_max) {
2960 tcp_timer_activate(tp, TT_REXMT, 0);
2962 } else if (!tcp_timer_active(tp, TT_PERSIST))
2963 tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp));
2966 * If no data (only SYN) was ACK'd,
2967 * skip rest of ACK processing.
2970 SOCKBUF_UNLOCK(&so->so_snd);
2975 * Let the congestion control algorithm update congestion
2976 * control related information. This typically means increasing
2977 * the congestion window.
2979 cc_ack_received(tp, th, nsegs, CC_ACK);
2981 if (acked > sbavail(&so->so_snd)) {
2982 if (tp->snd_wnd >= sbavail(&so->so_snd))
2983 tp->snd_wnd -= sbavail(&so->so_snd);
2986 mfree = sbcut_locked(&so->so_snd,
2987 (int)sbavail(&so->so_snd));
2990 mfree = sbcut_locked(&so->so_snd, acked);
2991 if (tp->snd_wnd >= (uint32_t) acked)
2992 tp->snd_wnd -= acked;
2997 /* NB: sowwakeup_locked() does an implicit unlock. */
2998 sowwakeup_locked(so);
3000 /* Detect una wraparound. */
3001 if (!IN_RECOVERY(tp->t_flags) &&
3002 SEQ_GT(tp->snd_una, tp->snd_recover) &&
3003 SEQ_LEQ(th->th_ack, tp->snd_recover))
3004 tp->snd_recover = th->th_ack - 1;
3005 tp->snd_una = th->th_ack;
3006 if (IN_RECOVERY(tp->t_flags) &&
3007 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
3008 cc_post_recovery(tp, th);
3010 if (tp->t_flags & TF_SACK_PERMIT) {
3011 if (SEQ_GT(tp->snd_una, tp->snd_recover))
3012 tp->snd_recover = tp->snd_una;
3014 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
3015 tp->snd_nxt = tp->snd_una;
3017 switch (tp->t_state) {
3019 * In FIN_WAIT_1 STATE in addition to the processing
3020 * for the ESTABLISHED state if our FIN is now acknowledged
3021 * then enter FIN_WAIT_2.
3023 case TCPS_FIN_WAIT_1:
3024 if (ourfinisacked) {
3026 * If we can't receive any more
3027 * data, then closing user can proceed.
3028 * Starting the timer is contrary to the
3029 * specification, but if we don't get a FIN
3030 * we'll hang forever.
3032 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3033 tcp_free_sackholes(tp);
3034 soisdisconnected(so);
3035 tcp_timer_activate(tp, TT_2MSL,
3036 (tcp_fast_finwait2_recycle ?
3037 tcp_finwait2_timeout :
3040 tcp_state_change(tp, TCPS_FIN_WAIT_2);
3045 * In CLOSING STATE in addition to the processing for
3046 * the ESTABLISHED state if the ACK acknowledges our FIN
3047 * then enter the TIME-WAIT state, otherwise ignore
3051 if (ourfinisacked) {
3059 * In LAST_ACK, we may still be waiting for data to drain
3060 * and/or to be acked, as well as for the ack of our FIN.
3061 * If our FIN is now acknowledged, delete the TCB,
3062 * enter the closed state and return.
3065 if (ourfinisacked) {
3074 INP_WLOCK_ASSERT(inp);
3077 * Update window information.
3078 * Don't look at window if no ACK: TAC's send garbage on first SYN.
3080 if ((thflags & TH_ACK) &&
3081 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
3082 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
3083 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
3084 /* keep track of pure window updates */
3086 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
3087 TCPSTAT_INC(tcps_rcvwinupd);
3088 tp->snd_wnd = tiwin;
3089 tp->snd_wl1 = th->th_seq;
3090 tp->snd_wl2 = th->th_ack;
3091 if (tp->snd_wnd > tp->max_sndwnd)
3092 tp->max_sndwnd = tp->snd_wnd;
3097 * Process segments with URG.
3099 if ((thflags & TH_URG) && th->th_urp &&
3100 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3102 * This is a kludge, but if we receive and accept
3103 * random urgent pointers, we'll crash in
3104 * soreceive. It's hard to imagine someone
3105 * actually wanting to send this much urgent data.
3107 SOCKBUF_LOCK(&so->so_rcv);
3108 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
3109 th->th_urp = 0; /* XXX */
3110 thflags &= ~TH_URG; /* XXX */
3111 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
3112 goto dodata; /* XXX */
3115 * If this segment advances the known urgent pointer,
3116 * then mark the data stream. This should not happen
3117 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
3118 * a FIN has been received from the remote side.
3119 * In these states we ignore the URG.
3121 * According to RFC961 (Assigned Protocols),
3122 * the urgent pointer points to the last octet
3123 * of urgent data. We continue, however,
3124 * to consider it to indicate the first octet
3125 * of data past the urgent section as the original
3126 * spec states (in one of two places).
3128 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
3129 tp->rcv_up = th->th_seq + th->th_urp;
3130 so->so_oobmark = sbavail(&so->so_rcv) +
3131 (tp->rcv_up - tp->rcv_nxt) - 1;
3132 if (so->so_oobmark == 0)
3133 so->so_rcv.sb_state |= SBS_RCVATMARK;
3135 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
3137 SOCKBUF_UNLOCK(&so->so_rcv);
3139 * Remove out of band data so doesn't get presented to user.
3140 * This can happen independent of advancing the URG pointer,
3141 * but if two URG's are pending at once, some out-of-band
3142 * data may creep in... ick.
3144 if (th->th_urp <= (uint32_t)tlen &&
3145 !(so->so_options & SO_OOBINLINE)) {
3146 /* hdr drop is delayed */
3147 tcp_pulloutofband(so, th, m, drop_hdrlen);
3151 * If no out of band data is expected,
3152 * pull receive urgent pointer along
3153 * with the receive window.
3155 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3156 tp->rcv_up = tp->rcv_nxt;
3159 INP_WLOCK_ASSERT(inp);
3162 * Process the segment text, merging it into the TCP sequencing queue,
3163 * and arranging for acknowledgment of receipt if necessary.
3164 * This process logically involves adjusting tp->rcv_wnd as data
3165 * is presented to the user (this happens in tcp_usrreq.c,
3166 * case PRU_RCVD). If a FIN has already been received on this
3167 * connection then we just ignore the text.
3169 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3170 (tp->t_flags & TF_FASTOPEN));
3171 if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
3172 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3173 tcp_seq save_start = th->th_seq;
3174 tcp_seq save_rnxt = tp->rcv_nxt;
3175 int save_tlen = tlen;
3176 m_adj(m, drop_hdrlen); /* delayed header drop */
3178 * Insert segment which includes th into TCP reassembly queue
3179 * with control block tp. Set thflags to whether reassembly now
3180 * includes a segment with FIN. This handles the common case
3181 * inline (segment is the next to be received on an established
3182 * connection, and the queue is empty), avoiding linkage into
3183 * and removal from the queue and repetition of various
3185 * Set DELACK for segments received in order, but ack
3186 * immediately when segments are out of order (so
3187 * fast retransmit can work).
3189 if (th->th_seq == tp->rcv_nxt &&
3191 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3193 if (DELAY_ACK(tp, tlen) || tfo_syn)
3194 tp->t_flags |= TF_DELACK;
3196 tp->t_flags |= TF_ACKNOW;
3197 tp->rcv_nxt += tlen;
3199 ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
3200 (tp->t_fbyte_in == 0)) {
3201 tp->t_fbyte_in = ticks;
3202 if (tp->t_fbyte_in == 0)
3204 if (tp->t_fbyte_out && tp->t_fbyte_in)
3205 tp->t_flags2 |= TF2_FBYTES_COMPLETE;
3207 thflags = tcp_get_flags(th) & TH_FIN;
3208 TCPSTAT_INC(tcps_rcvpack);
3209 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3210 SOCKBUF_LOCK(&so->so_rcv);
3211 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3214 sbappendstream_locked(&so->so_rcv, m, 0);
3215 tp->t_flags |= TF_WAKESOR;
3218 * XXX: Due to the header drop above "th" is
3219 * theoretically invalid by now. Fortunately
3220 * m_adj() doesn't actually frees any mbufs
3221 * when trimming from the head.
3223 tcp_seq temp = save_start;
3225 thflags = tcp_reass(tp, th, &temp, &tlen, m);
3226 tp->t_flags |= TF_ACKNOW;
3228 if ((tp->t_flags & TF_SACK_PERMIT) &&
3230 TCPS_HAVEESTABLISHED(tp->t_state)) {
3231 if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3233 * DSACK actually handled in the fastpath
3236 tcp_update_sack_list(tp, save_start,
3237 save_start + save_tlen);
3238 } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3239 if ((tp->rcv_numsacks >= 1) &&
3240 (tp->sackblks[0].end == save_start)) {
3242 * Partial overlap, recorded at todrop
3245 tcp_update_sack_list(tp,
3246 tp->sackblks[0].start,
3247 tp->sackblks[0].end);
3249 tcp_update_dsack_list(tp, save_start,
3250 save_start + save_tlen);
3252 } else if (tlen >= save_tlen) {
3253 /* Update of sackblks. */
3254 tcp_update_dsack_list(tp, save_start,
3255 save_start + save_tlen);
3256 } else if (tlen > 0) {
3257 tcp_update_dsack_list(tp, save_start,
3261 tcp_handle_wakeup(tp);
3264 * Note the amount of data that peer has sent into
3265 * our window, in order to estimate the sender's
3269 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3270 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3272 len = so->so_rcv.sb_hiwat;
3280 * If FIN is received ACK the FIN and let the user know
3281 * that the connection is closing.
3283 if (thflags & TH_FIN) {
3284 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3285 /* The socket upcall is handled by socantrcvmore. */
3288 * If connection is half-synchronized
3289 * (ie NEEDSYN flag on) then delay ACK,
3290 * so it may be piggybacked when SYN is sent.
3291 * Otherwise, since we received a FIN then no
3292 * more input can be expected, send ACK now.
3294 if (tp->t_flags & TF_NEEDSYN)
3295 tp->t_flags |= TF_DELACK;
3297 tp->t_flags |= TF_ACKNOW;
3300 switch (tp->t_state) {
3302 * In SYN_RECEIVED and ESTABLISHED STATES
3303 * enter the CLOSE_WAIT state.
3305 case TCPS_SYN_RECEIVED:
3306 tp->t_starttime = ticks;
3308 case TCPS_ESTABLISHED:
3309 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3313 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3314 * enter the CLOSING state.
3316 case TCPS_FIN_WAIT_1:
3317 tcp_state_change(tp, TCPS_CLOSING);
3321 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3322 * starting the time-wait timer, turning off the other
3325 case TCPS_FIN_WAIT_2:
3330 TCP_PROBE3(debug__input, tp, th, m);
3333 * Return any desired output.
3335 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
3336 (void) tcp_output(tp);
3339 INP_WLOCK_ASSERT(inp);
3341 if (tp->t_flags & TF_DELACK) {
3342 tp->t_flags &= ~TF_DELACK;
3343 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3350 * Generate an ACK dropping incoming segment if it occupies
3351 * sequence space, where the ACK reflects our state.
3353 * We can now skip the test for the RST flag since all
3354 * paths to this code happen after packets containing
3355 * RST have been dropped.
3357 * In the SYN-RECEIVED state, don't send an ACK unless the
3358 * segment we received passes the SYN-RECEIVED ACK test.
3359 * If it fails send a RST. This breaks the loop in the
3360 * "LAND" DoS attack, and also prevents an ACK storm
3361 * between two listening ports that have been sent forged
3362 * SYN segments, each with the source address of the other.
3364 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3365 (SEQ_GT(tp->snd_una, th->th_ack) ||
3366 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3367 rstreason = BANDLIM_RST_OPENPORT;
3368 tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
3371 TCP_PROBE3(debug__input, tp, th, m);
3372 tp->t_flags |= TF_ACKNOW;
3373 (void) tcp_output(tp);
3380 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3383 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3388 * Drop space held by incoming segment and return.
3390 TCP_PROBE3(debug__input, tp, th, m);
3398 * Issue RST and make ACK acceptable to originator of segment.
3399 * The mbuf must still include the original packet header.
3403 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3404 int tlen, int rstreason)
3410 struct ip6_hdr *ip6;
3414 INP_LOCK_ASSERT(tptoinpcb(tp));
3417 /* Don't bother if destination was broadcast/multicast. */
3418 if ((tcp_get_flags(th) & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3421 if (mtod(m, struct ip *)->ip_v == 6) {
3422 ip6 = mtod(m, struct ip6_hdr *);
3423 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3424 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3426 /* IPv6 anycast check is done at tcp6_input() */
3429 #if defined(INET) && defined(INET6)
3434 ip = mtod(m, struct ip *);
3435 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3436 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3437 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3438 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3443 /* Perform bandwidth limiting. */
3444 if (badport_bandlim(rstreason) < 0)
3447 /* tcp_respond consumes the mbuf chain. */
3448 if (tcp_get_flags(th) & TH_ACK) {
3449 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3450 th->th_ack, TH_RST);
3452 if (tcp_get_flags(th) & TH_SYN)
3454 if (tcp_get_flags(th) & TH_FIN)
3456 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3457 (tcp_seq)0, TH_RST|TH_ACK);
3465 * Parse TCP options and place in tcpopt.
3468 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3473 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3475 if (opt == TCPOPT_EOL)
3477 if (opt == TCPOPT_NOP)
3483 if (optlen < 2 || optlen > cnt)
3488 if (optlen != TCPOLEN_MAXSEG)
3490 if (!(flags & TO_SYN))
3492 to->to_flags |= TOF_MSS;
3493 bcopy((char *)cp + 2,
3494 (char *)&to->to_mss, sizeof(to->to_mss));
3495 to->to_mss = ntohs(to->to_mss);
3498 if (optlen != TCPOLEN_WINDOW)
3500 if (!(flags & TO_SYN))
3502 to->to_flags |= TOF_SCALE;
3503 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3505 case TCPOPT_TIMESTAMP:
3506 if (optlen != TCPOLEN_TIMESTAMP)
3508 to->to_flags |= TOF_TS;
3509 bcopy((char *)cp + 2,
3510 (char *)&to->to_tsval, sizeof(to->to_tsval));
3511 to->to_tsval = ntohl(to->to_tsval);
3512 bcopy((char *)cp + 6,
3513 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3514 to->to_tsecr = ntohl(to->to_tsecr);
3516 case TCPOPT_SIGNATURE:
3518 * In order to reply to a host which has set the
3519 * TCP_SIGNATURE option in its initial SYN, we have
3520 * to record the fact that the option was observed
3521 * here for the syncache code to perform the correct
3524 if (optlen != TCPOLEN_SIGNATURE)
3526 to->to_flags |= TOF_SIGNATURE;
3527 to->to_signature = cp + 2;
3529 case TCPOPT_SACK_PERMITTED:
3530 if (optlen != TCPOLEN_SACK_PERMITTED)
3532 if (!(flags & TO_SYN))
3536 to->to_flags |= TOF_SACKPERM;
3539 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3543 to->to_flags |= TOF_SACK;
3544 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3545 to->to_sacks = cp + 2;
3546 TCPSTAT_INC(tcps_sack_rcv_blocks);
3548 case TCPOPT_FAST_OPEN:
3550 * Cookie length validation is performed by the
3551 * server side cookie checking code or the client
3552 * side cookie cache update code.
3554 if (!(flags & TO_SYN))
3556 if (!V_tcp_fastopen_client_enable &&
3557 !V_tcp_fastopen_server_enable)
3559 to->to_flags |= TOF_FASTOPEN;
3560 to->to_tfo_len = optlen - 2;
3561 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3570 * Pull out of band byte out of a segment so
3571 * it doesn't appear in the user's data queue.
3572 * It is still reflected in the segment length for
3573 * sequencing purposes.
3576 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3579 int cnt = off + th->th_urp - 1;
3582 if (m->m_len > cnt) {
3583 char *cp = mtod(m, caddr_t) + cnt;
3584 struct tcpcb *tp = sototcpcb(so);
3586 INP_WLOCK_ASSERT(tptoinpcb(tp));
3589 tp->t_oobflags |= TCPOOB_HAVEDATA;
3590 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3592 if (m->m_flags & M_PKTHDR)
3601 panic("tcp_pulloutofband");
3605 * Collect new round-trip time estimate
3606 * and update averages and current timeout.
3609 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3613 INP_WLOCK_ASSERT(tptoinpcb(tp));
3615 TCPSTAT_INC(tcps_rttupdated);
3616 if (tp->t_rttupdated < UCHAR_MAX)
3619 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT,
3620 imax(0, rtt * 1000 / hz));
3622 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3624 * srtt is stored as fixed point with 5 bits after the
3625 * binary point (i.e., scaled by 8). The following magic
3626 * is equivalent to the smoothing algorithm in rfc793 with
3627 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3628 * point). Adjust rtt to origin 0.
3630 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3631 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3633 if ((tp->t_srtt += delta) <= 0)
3637 * We accumulate a smoothed rtt variance (actually, a
3638 * smoothed mean difference), then set the retransmit
3639 * timer to smoothed rtt + 4 times the smoothed variance.
3640 * rttvar is stored as fixed point with 4 bits after the
3641 * binary point (scaled by 16). The following is
3642 * equivalent to rfc793 smoothing with an alpha of .75
3643 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3644 * rfc793's wired-in beta.
3648 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3649 if ((tp->t_rttvar += delta) <= 0)
3653 * No rtt measurement yet - use the unsmoothed rtt.
3654 * Set the variance to half the rtt (so our first
3655 * retransmit happens at 3*rtt).
3657 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3658 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3664 * the retransmit should happen at rtt + 4 * rttvar.
3665 * Because of the way we do the smoothing, srtt and rttvar
3666 * will each average +1/2 tick of bias. When we compute
3667 * the retransmit timer, we want 1/2 tick of rounding and
3668 * 1 extra tick because of +-1/2 tick uncertainty in the
3669 * firing of the timer. The bias will give us exactly the
3670 * 1.5 tick we need. But, because the bias is
3671 * statistical, we have to test that we don't drop below
3672 * the minimum feasible timer (which is 2 ticks).
3674 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3675 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3678 * We received an ack for a packet that wasn't retransmitted;
3679 * it is probably safe to discard any error indications we've
3680 * received recently. This isn't quite right, but close enough
3681 * for now (a route might have failed after we sent a segment,
3682 * and the return path might not be symmetrical).
3684 tp->t_softerror = 0;
3688 * Determine a reasonable value for maxseg size.
3689 * If the route is known, check route for mtu.
3690 * If none, use an mss that can be handled on the outgoing interface
3691 * without forcing IP to fragment. If no route is found, route has no mtu,
3692 * or the destination isn't local, use a default, hopefully conservative
3693 * size (usually 512 or the default IP max size, but no more than the mtu
3694 * of the interface), as we can't discover anything about intervening
3695 * gateways or networks. We also initialize the congestion/slow start
3696 * window to be a single segment if the destination isn't local.
3697 * While looking at the routing entry, we also initialize other path-dependent
3698 * parameters from pre-set or cached values in the routing entry.
3700 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3701 * IP options, e.g. IPSEC data, since length of this data may vary, and
3702 * thus it is calculated for every segment separately in tcp_output().
3704 * NOTE that this routine is only called when we process an incoming
3705 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3706 * settings are handled in tcp_mssopt().
3709 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3710 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3713 uint32_t maxmtu = 0;
3714 struct inpcb *inp = tptoinpcb(tp);
3715 struct hc_metrics_lite metrics;
3717 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3718 size_t min_protoh = isipv6 ?
3719 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3720 sizeof (struct tcpiphdr);
3722 size_t min_protoh = sizeof(struct tcpiphdr);
3725 INP_WLOCK_ASSERT(inp);
3728 min_protoh += V_tcp_udp_tunneling_overhead;
3729 if (mtuoffer != -1) {
3730 KASSERT(offer == -1, ("%s: conflict", __func__));
3731 offer = mtuoffer - min_protoh;
3737 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3738 tp->t_maxseg = V_tcp_v6mssdflt;
3741 #if defined(INET) && defined(INET6)
3746 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3747 tp->t_maxseg = V_tcp_mssdflt;
3752 * No route to sender, stay with default mss and return.
3756 * In case we return early we need to initialize metrics
3757 * to a defined state as tcp_hc_get() would do for us
3758 * if there was no cache hit.
3760 if (metricptr != NULL)
3761 bzero(metricptr, sizeof(struct hc_metrics_lite));
3765 /* What have we got? */
3769 * Offer == 0 means that there was no MSS on the SYN
3770 * segment, in this case we use tcp_mssdflt as
3771 * already assigned to t_maxseg above.
3773 offer = tp->t_maxseg;
3778 * Offer == -1 means that we didn't receive SYN yet.
3784 * Prevent DoS attack with too small MSS. Round up
3785 * to at least minmss.
3787 offer = max(offer, V_tcp_minmss);
3791 * rmx information is now retrieved from tcp_hostcache.
3793 tcp_hc_get(&inp->inp_inc, &metrics);
3794 if (metricptr != NULL)
3795 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3798 * If there's a discovered mtu in tcp hostcache, use it.
3799 * Else, use the link mtu.
3801 if (metrics.rmx_mtu)
3802 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3806 mss = maxmtu - min_protoh;
3807 if (!V_path_mtu_discovery &&
3808 !in6_localaddr(&inp->in6p_faddr))
3809 mss = min(mss, V_tcp_v6mssdflt);
3812 #if defined(INET) && defined(INET6)
3817 mss = maxmtu - min_protoh;
3818 if (!V_path_mtu_discovery &&
3819 !in_localaddr(inp->inp_faddr))
3820 mss = min(mss, V_tcp_mssdflt);
3824 * XXX - The above conditional (mss = maxmtu - min_protoh)
3825 * probably violates the TCP spec.
3826 * The problem is that, since we don't know the
3827 * other end's MSS, we are supposed to use a conservative
3828 * default. But, if we do that, then MTU discovery will
3829 * never actually take place, because the conservative
3830 * default is much less than the MTUs typically seen
3831 * on the Internet today. For the moment, we'll sweep
3832 * this under the carpet.
3834 * The conservative default might not actually be a problem
3835 * if the only case this occurs is when sending an initial
3836 * SYN with options and data to a host we've never talked
3837 * to before. Then, they will reply with an MSS value which
3838 * will get recorded and the new parameters should get
3839 * recomputed. For Further Study.
3842 mss = min(mss, offer);
3845 * Sanity check: make sure that maxseg will be large
3846 * enough to allow some data on segments even if the
3847 * all the option space is used (40bytes). Otherwise
3848 * funny things may happen in tcp_output.
3850 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3858 tcp_mss(struct tcpcb *tp, int offer)
3862 struct inpcb *inp = tptoinpcb(tp);
3864 struct hc_metrics_lite metrics;
3865 struct tcp_ifcap cap;
3867 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3869 bzero(&cap, sizeof(cap));
3870 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3875 * If there's a pipesize, change the socket buffer to that size,
3876 * don't change if sb_hiwat is different than default (then it
3877 * has been changed on purpose with setsockopt).
3878 * Make the socket buffers an integral number of mss units;
3879 * if the mss is larger than the socket buffer, decrease the mss.
3881 so = inp->inp_socket;
3882 SOCKBUF_LOCK(&so->so_snd);
3883 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3884 bufsize = metrics.rmx_sendpipe;
3886 bufsize = so->so_snd.sb_hiwat;
3890 bufsize = roundup(bufsize, mss);
3891 if (bufsize > sb_max)
3893 if (bufsize > so->so_snd.sb_hiwat)
3894 (void)sbreserve_locked(so, SO_SND, bufsize, NULL);
3896 SOCKBUF_UNLOCK(&so->so_snd);
3898 * Sanity check: make sure that maxseg will be large
3899 * enough to allow some data on segments even if the
3900 * all the option space is used (40bytes). Otherwise
3901 * funny things may happen in tcp_output.
3903 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3905 tp->t_maxseg = max(mss, 64);
3907 SOCKBUF_LOCK(&so->so_rcv);
3908 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3909 bufsize = metrics.rmx_recvpipe;
3911 bufsize = so->so_rcv.sb_hiwat;
3912 if (bufsize > mss) {
3913 bufsize = roundup(bufsize, mss);
3914 if (bufsize > sb_max)
3916 if (bufsize > so->so_rcv.sb_hiwat)
3917 (void)sbreserve_locked(so, SO_RCV, bufsize, NULL);
3919 SOCKBUF_UNLOCK(&so->so_rcv);
3921 /* Check the interface for TSO capabilities. */
3922 if (cap.ifcap & CSUM_TSO) {
3923 tp->t_flags |= TF_TSO;
3924 tp->t_tsomax = cap.tsomax;
3925 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3926 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3931 * Determine the MSS option to send on an outgoing SYN.
3934 tcp_mssopt(struct in_conninfo *inc)
3937 uint32_t thcmtu = 0;
3938 uint32_t maxmtu = 0;
3941 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3944 if (inc->inc_flags & INC_ISIPV6) {
3945 mss = V_tcp_v6mssdflt;
3946 maxmtu = tcp_maxmtu6(inc, NULL);
3947 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3950 #if defined(INET) && defined(INET6)
3955 mss = V_tcp_mssdflt;
3956 maxmtu = tcp_maxmtu(inc, NULL);
3957 min_protoh = sizeof(struct tcpiphdr);
3960 #if defined(INET6) || defined(INET)
3961 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3964 if (maxmtu && thcmtu)
3965 mss = min(maxmtu, thcmtu) - min_protoh;
3966 else if (maxmtu || thcmtu)
3967 mss = max(maxmtu, thcmtu) - min_protoh;
3973 tcp_do_prr_ack(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to,
3974 sackstatus_t sack_changed, u_int *maxsegp)
3976 int snd_cnt = 0, limit = 0, del_data = 0, pipe = 0;
3979 INP_WLOCK_ASSERT(tptoinpcb(tp));
3981 if (*maxsegp == 0) {
3982 *maxsegp = tcp_maxseg(tp);
3986 * Compute the amount of data that this ACK is indicating
3987 * (del_data) and an estimate of how many bytes are in the
3990 if (tcp_is_sack_recovery(tp, to) ||
3991 (IN_CONGRECOVERY(tp->t_flags) &&
3992 !IN_FASTRECOVERY(tp->t_flags))) {
3993 del_data = tp->sackhint.delivered_data;
3994 if (V_tcp_do_newsack)
3995 pipe = tcp_compute_pipe(tp);
3997 pipe = (tp->snd_nxt - tp->snd_fack) +
3998 tp->sackhint.sack_bytes_rexmit;
4000 if (tp->sackhint.prr_delivered < (tcprexmtthresh * maxseg +
4001 tp->snd_recover - tp->snd_una)) {
4004 pipe = imax(0, tp->snd_max - tp->snd_una -
4005 imin(INT_MAX / 65536, tp->t_dupacks) * maxseg);
4007 tp->sackhint.prr_delivered += del_data;
4009 * Proportional Rate Reduction
4011 if (pipe >= tp->snd_ssthresh) {
4012 if (tp->sackhint.recover_fs == 0)
4013 tp->sackhint.recover_fs =
4014 imax(1, tp->snd_nxt - tp->snd_una);
4015 snd_cnt = howmany((long)tp->sackhint.prr_delivered *
4016 tp->snd_ssthresh, tp->sackhint.recover_fs) -
4017 tp->sackhint.prr_out + maxseg - 1;
4020 * PRR 6937bis heuristic:
4021 * - A partial ack without SACK block beneath snd_recover
4022 * indicates further loss.
4023 * - An SACK scoreboard update adding a new hole indicates
4024 * further loss, so be conservative and send at most one
4026 * - Prevent ACK splitting attacks, by being conservative
4027 * when no new data is acked.
4029 if ((sack_changed == SACK_NEWLOSS) || (del_data == 0)) {
4030 limit = tp->sackhint.prr_delivered -
4031 tp->sackhint.prr_out;
4033 limit = imax(tp->sackhint.prr_delivered -
4034 tp->sackhint.prr_out, del_data) +
4037 snd_cnt = imin((tp->snd_ssthresh - pipe), limit);
4039 snd_cnt = imax(snd_cnt, 0) / maxseg;
4041 * Send snd_cnt new data into the network in response to this ack.
4042 * If there is going to be a SACK retransmission, adjust snd_cwnd
4045 if (IN_FASTRECOVERY(tp->t_flags)) {
4046 if (tcp_is_sack_recovery(tp, to)) {
4047 tp->snd_cwnd = tp->snd_nxt - tp->snd_recover +
4048 tp->sackhint.sack_bytes_rexmit +
4051 tp->snd_cwnd = (tp->snd_max - tp->snd_una) +
4054 } else if (IN_CONGRECOVERY(tp->t_flags)) {
4055 tp->snd_cwnd = pipe - del_data + (snd_cnt * maxseg);
4057 tp->snd_cwnd = imax(maxseg, tp->snd_cwnd);
4061 * On a partial ack arrives, force the retransmission of the
4062 * next unacknowledged segment. Do not clear tp->t_dupacks.
4063 * By setting snd_nxt to ti_ack, this forces retransmission timer to
4067 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
4069 tcp_seq onxt = tp->snd_nxt;
4070 uint32_t ocwnd = tp->snd_cwnd;
4071 u_int maxseg = tcp_maxseg(tp);
4073 INP_WLOCK_ASSERT(tptoinpcb(tp));
4075 tcp_timer_activate(tp, TT_REXMT, 0);
4077 tp->snd_nxt = th->th_ack;
4079 * Set snd_cwnd to one segment beyond acknowledged offset.
4080 * (tp->snd_una has not yet been updated when this function is called.)
4082 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
4083 tp->t_flags |= TF_ACKNOW;
4084 (void) tcp_output(tp);
4085 tp->snd_cwnd = ocwnd;
4086 if (SEQ_GT(onxt, tp->snd_nxt))
4089 * Partial window deflation. Relies on fact that tp->snd_una
4092 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
4093 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
4096 tp->snd_cwnd += maxseg;
4100 tcp_compute_pipe(struct tcpcb *tp)
4102 if (tp->t_fb->tfb_compute_pipe == NULL) {
4103 return (tp->snd_max - tp->snd_una +
4104 tp->sackhint.sack_bytes_rexmit -
4105 tp->sackhint.sacked_bytes -
4106 tp->sackhint.lost_bytes);
4108 return((*tp->t_fb->tfb_compute_pipe)(tp));
4113 tcp_compute_initwnd(uint32_t maxseg)
4116 * Calculate the Initial Window, also used as Restart Window
4118 * RFC5681 Section 3.1 specifies the default conservative values.
4119 * RFC3390 specifies slightly more aggressive values.
4120 * RFC6928 increases it to ten segments.
4121 * Support for user specified value for initial flight size.
4123 if (V_tcp_initcwnd_segments)
4124 return min(V_tcp_initcwnd_segments * maxseg,
4125 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
4126 else if (V_tcp_do_rfc3390)
4127 return min(4 * maxseg, max(2 * maxseg, 4380));
4129 /* Per RFC5681 Section 3.1 */
4131 return (2 * maxseg);
4132 else if (maxseg > 1095)
4133 return (3 * maxseg);
4135 return (4 * maxseg);