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
49 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
56 #include "opt_inet6.h"
57 #include "opt_ipsec.h"
58 #include "opt_tcpdebug.h"
60 #include <sys/param.h>
62 #include <sys/kernel.h>
64 #include <sys/hhook.h>
66 #include <sys/malloc.h>
68 #include <sys/proc.h> /* for proc0 declaration */
69 #include <sys/protosw.h>
70 #include <sys/qmath.h>
72 #include <sys/signalvar.h>
73 #include <sys/socket.h>
74 #include <sys/socketvar.h>
75 #include <sys/sysctl.h>
76 #include <sys/syslog.h>
77 #include <sys/systm.h>
78 #include <sys/stats.h>
80 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
85 #include <net/if_var.h>
86 #include <net/route.h>
89 #define TCPSTATES /* for logging */
91 #include <netinet/in.h>
92 #include <netinet/in_kdtrace.h>
93 #include <netinet/in_pcb.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/ip.h>
96 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
97 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
98 #include <netinet/ip_var.h>
99 #include <netinet/ip_options.h>
100 #include <netinet/ip6.h>
101 #include <netinet/icmp6.h>
102 #include <netinet6/in6_pcb.h>
103 #include <netinet6/in6_var.h>
104 #include <netinet6/ip6_var.h>
105 #include <netinet6/nd6.h>
106 #include <netinet/tcp.h>
107 #include <netinet/tcp_fsm.h>
108 #include <netinet/tcp_log_buf.h>
109 #include <netinet/tcp_seq.h>
110 #include <netinet/tcp_timer.h>
111 #include <netinet/tcp_var.h>
112 #include <netinet6/tcp6_var.h>
113 #include <netinet/tcpip.h>
114 #include <netinet/cc/cc.h>
115 #include <netinet/tcp_fastopen.h>
117 #include <netinet/tcp_pcap.h>
119 #include <netinet/tcp_syncache.h>
121 #include <netinet/tcp_debug.h>
122 #endif /* TCPDEBUG */
124 #include <netinet/tcp_offload.h>
127 #include <netipsec/ipsec_support.h>
129 #include <machine/in_cksum.h>
131 #include <security/mac/mac_framework.h>
133 const int tcprexmtthresh = 3;
135 VNET_DEFINE(int, tcp_log_in_vain) = 0;
136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW,
137 &VNET_NAME(tcp_log_in_vain), 0,
138 "Log all incoming TCP segments to closed ports");
140 VNET_DEFINE(int, blackhole) = 0;
141 #define V_blackhole VNET(blackhole)
142 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
143 &VNET_NAME(blackhole), 0,
144 "Do not send RST on segments to closed ports");
146 VNET_DEFINE(int, tcp_delack_enabled) = 1;
147 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
148 &VNET_NAME(tcp_delack_enabled), 0,
149 "Delay ACK to try and piggyback it onto a data packet");
151 VNET_DEFINE(int, drop_synfin) = 0;
152 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
153 &VNET_NAME(drop_synfin), 0,
154 "Drop TCP packets with SYN+FIN set");
156 VNET_DEFINE(int, tcp_do_newcwv) = 0;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, newcwv, CTLFLAG_VNET | CTLFLAG_RW,
158 &VNET_NAME(tcp_do_newcwv), 0,
159 "Enable New Congestion Window Validation per RFC7661");
161 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
162 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
163 &VNET_NAME(tcp_do_rfc6675_pipe), 0,
164 "Use calculated pipe/in-flight bytes per RFC 6675");
166 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
167 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
168 &VNET_NAME(tcp_do_rfc3042), 0,
169 "Enable RFC 3042 (Limited Transmit)");
171 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
172 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
173 &VNET_NAME(tcp_do_rfc3390), 0,
174 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
176 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
177 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
178 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
179 "Slow-start flight size (initial congestion window) in number of segments");
181 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
183 &VNET_NAME(tcp_do_rfc3465), 0,
184 "Enable RFC 3465 (Appropriate Byte Counting)");
186 VNET_DEFINE(int, tcp_abc_l_var) = 2;
187 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
188 &VNET_NAME(tcp_abc_l_var), 2,
189 "Cap the max cwnd increment during slow-start to this number of segments");
191 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn,
192 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
195 VNET_DEFINE(int, tcp_do_ecn) = 2;
196 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
197 &VNET_NAME(tcp_do_ecn), 0,
200 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
201 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
202 &VNET_NAME(tcp_ecn_maxretries), 0,
203 "Max retries before giving up on ECN");
205 VNET_DEFINE(int, tcp_insecure_syn) = 0;
206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
207 &VNET_NAME(tcp_insecure_syn), 0,
208 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
210 VNET_DEFINE(int, tcp_insecure_rst) = 0;
211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
212 &VNET_NAME(tcp_insecure_rst), 0,
213 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
215 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
216 #define V_tcp_recvspace VNET(tcp_recvspace)
217 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
218 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
220 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
221 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
222 &VNET_NAME(tcp_do_autorcvbuf), 0,
223 "Enable automatic receive buffer sizing");
225 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
226 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
227 &VNET_NAME(tcp_autorcvbuf_max), 0,
228 "Max size of automatic receive buffer");
230 VNET_DEFINE(struct inpcbhead, tcb);
231 #define tcb6 tcb /* for KAME src sync over BSD*'s */
232 VNET_DEFINE(struct inpcbinfo, tcbinfo);
235 * TCP statistics are stored in an array of counter(9)s, which size matches
236 * size of struct tcpstat. TCP running connection count is a regular array.
238 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
239 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
240 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
241 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
242 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
243 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
244 "TCP connection counts by TCP state");
247 tcp_vnet_init(const void *unused)
250 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
251 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
253 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
254 tcp_vnet_init, NULL);
258 tcp_vnet_uninit(const void *unused)
261 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
262 VNET_PCPUSTAT_FREE(tcpstat);
264 VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
265 tcp_vnet_uninit, NULL);
269 * Kernel module interface for updating tcpstat. The first argument is an index
270 * into tcpstat treated as an array.
273 kmod_tcpstat_add(int statnum, int val)
276 counter_u64_add(VNET(tcpstat)[statnum], val);
281 * Wrapper for the TCP established input helper hook.
284 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
286 struct tcp_hhook_data hhook_data;
288 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
293 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
300 * CC wrapper hook functions
303 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
310 INP_WLOCK_ASSERT(tp->t_inpcb);
312 tp->ccv->nsegs = nsegs;
313 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
314 if ((!V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd)) ||
315 (V_tcp_do_newcwv && (tp->snd_cwnd <= tp->snd_wnd) &&
316 (tp->snd_cwnd < (tcp_compute_pipe(tp) * 2))))
317 tp->ccv->flags |= CCF_CWND_LIMITED;
319 tp->ccv->flags &= ~CCF_CWND_LIMITED;
321 if (type == CC_ACK) {
323 stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
324 ((int32_t)tp->snd_cwnd) - tp->snd_wnd);
325 if (!IN_RECOVERY(tp->t_flags))
326 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_ACKLEN,
327 tp->ccv->bytes_this_ack / (tcp_maxseg(tp) * nsegs));
328 if ((tp->t_flags & TF_GPUTINPROG) &&
329 SEQ_GEQ(th->th_ack, tp->gput_ack)) {
331 * Compute goodput in bits per millisecond.
333 gput = (((int64_t)(th->th_ack - tp->gput_seq)) << 3) /
334 max(1, tcp_ts_getticks() - tp->gput_ts);
335 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
338 * XXXLAS: This is a temporary hack, and should be
339 * chained off VOI_TCP_GPUT when stats(9) grows an API
340 * to deal with chained VOIs.
342 if (tp->t_stats_gput_prev > 0)
343 stats_voi_update_abs_s32(tp->t_stats,
345 ((gput - tp->t_stats_gput_prev) * 100) /
346 tp->t_stats_gput_prev);
347 tp->t_flags &= ~TF_GPUTINPROG;
348 tp->t_stats_gput_prev = gput;
351 if (tp->snd_cwnd > tp->snd_ssthresh) {
352 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
353 nsegs * V_tcp_abc_l_var * tcp_maxseg(tp));
354 if (tp->t_bytes_acked >= tp->snd_cwnd) {
355 tp->t_bytes_acked -= tp->snd_cwnd;
356 tp->ccv->flags |= CCF_ABC_SENTAWND;
359 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
360 tp->t_bytes_acked = 0;
364 if (CC_ALGO(tp)->ack_received != NULL) {
365 /* XXXLAS: Find a way to live without this */
366 tp->ccv->curack = th->th_ack;
367 CC_ALGO(tp)->ack_received(tp->ccv, type);
370 stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
375 cc_conn_init(struct tcpcb *tp)
377 struct hc_metrics_lite metrics;
378 struct inpcb *inp = tp->t_inpcb;
382 INP_WLOCK_ASSERT(tp->t_inpcb);
384 tcp_hc_get(&inp->inp_inc, &metrics);
385 maxseg = tcp_maxseg(tp);
387 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
389 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
390 TCPSTAT_INC(tcps_usedrtt);
391 if (metrics.rmx_rttvar) {
392 tp->t_rttvar = metrics.rmx_rttvar;
393 TCPSTAT_INC(tcps_usedrttvar);
395 /* default variation is +- 1 rtt */
397 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
399 TCPT_RANGESET(tp->t_rxtcur,
400 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
401 tp->t_rttmin, TCPTV_REXMTMAX);
403 if (metrics.rmx_ssthresh) {
405 * There's some sort of gateway or interface
406 * buffer limit on the path. Use this to set
407 * the slow start threshold, but set the
408 * threshold to no less than 2*mss.
410 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
411 TCPSTAT_INC(tcps_usedssthresh);
415 * Set the initial slow-start flight size.
417 * If a SYN or SYN/ACK was lost and retransmitted, we have to
418 * reduce the initial CWND to one segment as congestion is likely
419 * requiring us to be cautious.
421 if (tp->snd_cwnd == 1)
422 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
424 tp->snd_cwnd = tcp_compute_initwnd(maxseg);
426 if (CC_ALGO(tp)->conn_init != NULL)
427 CC_ALGO(tp)->conn_init(tp->ccv);
431 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
435 INP_WLOCK_ASSERT(tp->t_inpcb);
438 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
443 if (!IN_FASTRECOVERY(tp->t_flags)) {
444 tp->snd_recover = tp->snd_max;
445 if (tp->t_flags2 & TF2_ECN_PERMIT)
446 tp->t_flags2 |= TF2_ECN_SND_CWR;
450 if (!IN_CONGRECOVERY(tp->t_flags)) {
451 TCPSTAT_INC(tcps_ecn_rcwnd);
452 tp->snd_recover = tp->snd_max;
453 if (tp->t_flags2 & TF2_ECN_PERMIT)
454 tp->t_flags2 |= TF2_ECN_SND_CWR;
458 maxseg = tcp_maxseg(tp);
460 tp->t_bytes_acked = 0;
461 EXIT_RECOVERY(tp->t_flags);
462 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
464 tp->snd_cwnd = maxseg;
465 if (tp->t_flags2 & TF2_ECN_PERMIT)
466 tp->t_flags2 |= TF2_ECN_SND_CWR;
469 TCPSTAT_INC(tcps_sndrexmitbad);
470 /* RTO was unnecessary, so reset everything. */
471 tp->snd_cwnd = tp->snd_cwnd_prev;
472 tp->snd_ssthresh = tp->snd_ssthresh_prev;
473 tp->snd_recover = tp->snd_recover_prev;
474 if (tp->t_flags & TF_WASFRECOVERY)
475 ENTER_FASTRECOVERY(tp->t_flags);
476 if (tp->t_flags & TF_WASCRECOVERY)
477 ENTER_CONGRECOVERY(tp->t_flags);
478 tp->snd_nxt = tp->snd_max;
479 tp->t_flags &= ~TF_PREVVALID;
484 if (CC_ALGO(tp)->cong_signal != NULL) {
486 tp->ccv->curack = th->th_ack;
487 CC_ALGO(tp)->cong_signal(tp->ccv, type);
492 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
494 INP_WLOCK_ASSERT(tp->t_inpcb);
496 /* XXXLAS: KASSERT that we're in recovery? */
498 if (CC_ALGO(tp)->post_recovery != NULL) {
499 tp->ccv->curack = th->th_ack;
500 CC_ALGO(tp)->post_recovery(tp->ccv);
502 /* XXXLAS: EXIT_RECOVERY ? */
503 tp->t_bytes_acked = 0;
507 * Indicate whether this ack should be delayed. We can delay the ack if
508 * following conditions are met:
509 * - There is no delayed ack timer in progress.
510 * - Our last ack wasn't a 0-sized window. We never want to delay
511 * the ack that opens up a 0-sized window.
512 * - LRO wasn't used for this segment. We make sure by checking that the
513 * segment size is not larger than the MSS.
515 #define DELAY_ACK(tp, tlen) \
516 ((!tcp_timer_active(tp, TT_DELACK) && \
517 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
518 (tlen <= tp->t_maxseg) && \
519 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
522 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
524 INP_WLOCK_ASSERT(tp->t_inpcb);
526 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
527 switch (iptos & IPTOS_ECN_MASK) {
529 tp->ccv->flags |= CCF_IPHDR_CE;
535 case IPTOS_ECN_NOTECT:
536 tp->ccv->flags &= ~CCF_IPHDR_CE;
540 if (th->th_flags & TH_CWR)
541 tp->ccv->flags |= CCF_TCPHDR_CWR;
543 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
545 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
547 if (tp->ccv->flags & CCF_ACKNOW) {
548 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
549 tp->t_flags |= TF_ACKNOW;
555 * TCP input handling is split into multiple parts:
556 * tcp6_input is a thin wrapper around tcp_input for the extended
557 * ip6_protox[] call format in ip6_input
558 * tcp_input handles primary segment validation, inpcb lookup and
559 * SYN processing on listen sockets
560 * tcp_do_segment processes the ACK and text of the segment for
561 * establishing, established and closing connections
565 tcp6_input(struct mbuf **mp, int *offp, int proto)
568 struct in6_ifaddr *ia6;
572 if (m->m_len < *offp + sizeof(struct tcphdr)) {
573 m = m_pullup(m, *offp + sizeof(struct tcphdr));
576 TCPSTAT_INC(tcps_rcvshort);
577 return (IPPROTO_DONE);
582 * draft-itojun-ipv6-tcp-to-anycast
583 * better place to put this in?
585 ip6 = mtod(m, struct ip6_hdr *);
586 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
587 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
589 ifa_free(&ia6->ia_ifa);
590 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
591 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
593 return (IPPROTO_DONE);
596 ifa_free(&ia6->ia_ifa);
599 return (tcp_input(mp, offp, proto));
604 tcp_input(struct mbuf **mp, int *offp, int proto)
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 */
624 struct m_tag *fwd_tag = NULL;
626 struct ip6_hdr *ip6 = NULL;
629 const void *ip6 = NULL;
631 struct tcpopt to; /* options in this segment */
632 char *s = NULL; /* address and port logging */
635 * The size of tcp_saveipgen must be the size of the max ip header,
638 u_char tcp_saveipgen[IP6_HDR_LEN];
639 struct tcphdr tcp_savetcp;
646 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
653 TCPSTAT_INC(tcps_rcvtotal);
658 ip6 = mtod(m, struct ip6_hdr *);
659 th = (struct tcphdr *)((caddr_t)ip6 + off0);
660 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
661 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
662 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
663 th->th_sum = m->m_pkthdr.csum_data;
665 th->th_sum = in6_cksum_pseudo(ip6, tlen,
666 IPPROTO_TCP, m->m_pkthdr.csum_data);
667 th->th_sum ^= 0xffff;
669 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
671 TCPSTAT_INC(tcps_rcvbadsum);
676 * Be proactive about unspecified IPv6 address in source.
677 * As we use all-zero to indicate unbounded/unconnected pcb,
678 * unspecified IPv6 address can be used to confuse us.
680 * Note that packets with unspecified IPv6 destination is
681 * already dropped in ip6_input.
683 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
687 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
690 #if defined(INET) && defined(INET6)
696 * Get IP and TCP header together in first mbuf.
697 * Note: IP leaves IP header in first mbuf.
699 if (off0 > sizeof (struct ip)) {
701 off0 = sizeof(struct ip);
703 if (m->m_len < sizeof (struct tcpiphdr)) {
704 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
706 TCPSTAT_INC(tcps_rcvshort);
707 return (IPPROTO_DONE);
710 ip = mtod(m, struct ip *);
711 th = (struct tcphdr *)((caddr_t)ip + off0);
712 tlen = ntohs(ip->ip_len) - off0;
715 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
716 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
717 th->th_sum = m->m_pkthdr.csum_data;
719 th->th_sum = in_pseudo(ip->ip_src.s_addr,
721 htonl(m->m_pkthdr.csum_data + tlen +
723 th->th_sum ^= 0xffff;
725 struct ipovly *ipov = (struct ipovly *)ip;
728 * Checksum extended TCP header and data.
732 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
733 ipov->ih_len = htons(tlen);
734 th->th_sum = in_cksum(m, len);
735 /* Reset length for SDT probes. */
736 ip->ip_len = htons(len);
739 /* Re-initialization for later version check */
741 ip->ip_v = IPVERSION;
742 ip->ip_hl = off0 >> 2;
746 TCPSTAT_INC(tcps_rcvbadsum);
753 * Check that TCP offset makes sense,
754 * pull out TCP options and adjust length. XXX
756 off = th->th_off << 2;
757 if (off < sizeof (struct tcphdr) || off > tlen) {
758 TCPSTAT_INC(tcps_rcvbadoff);
761 tlen -= off; /* tlen is used instead of ti->ti_len */
762 if (off > sizeof (struct tcphdr)) {
765 if (m->m_len < off0 + off) {
766 m = m_pullup(m, off0 + off);
768 TCPSTAT_INC(tcps_rcvshort);
769 return (IPPROTO_DONE);
772 ip6 = mtod(m, struct ip6_hdr *);
773 th = (struct tcphdr *)((caddr_t)ip6 + off0);
776 #if defined(INET) && defined(INET6)
781 if (m->m_len < sizeof(struct ip) + off) {
782 if ((m = m_pullup(m, sizeof (struct ip) + off))
784 TCPSTAT_INC(tcps_rcvshort);
785 return (IPPROTO_DONE);
787 ip = mtod(m, struct ip *);
788 th = (struct tcphdr *)((caddr_t)ip + off0);
792 optlen = off - sizeof (struct tcphdr);
793 optp = (u_char *)(th + 1);
795 thflags = th->th_flags;
798 * Convert TCP protocol specific fields to host format.
800 tcp_fields_to_host(th);
803 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
805 drop_hdrlen = off0 + off;
808 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
812 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
814 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
817 #if defined(INET) && !defined(INET6)
818 (m->m_flags & M_IP_NEXTHOP)
821 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
825 if (isipv6 && fwd_tag != NULL) {
826 struct sockaddr_in6 *next_hop6;
828 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
830 * Transparently forwarded. Pretend to be the destination.
831 * Already got one like this?
833 inp = in6_pcblookup_mbuf(&V_tcbinfo,
834 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
835 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
838 * It's new. Try to find the ambushing socket.
839 * Because we've rewritten the destination address,
840 * any hardware-generated hash is ignored.
842 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
843 th->th_sport, &next_hop6->sin6_addr,
844 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
845 th->th_dport, INPLOOKUP_WILDCARD |
846 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
849 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
850 th->th_sport, &ip6->ip6_dst, th->th_dport,
851 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
852 m->m_pkthdr.rcvif, m);
855 #if defined(INET6) && defined(INET)
859 if (fwd_tag != NULL) {
860 struct sockaddr_in *next_hop;
862 next_hop = (struct sockaddr_in *)(fwd_tag+1);
864 * Transparently forwarded. Pretend to be the destination.
865 * already got one like this?
867 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
868 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
869 m->m_pkthdr.rcvif, m);
872 * It's new. Try to find the ambushing socket.
873 * Because we've rewritten the destination address,
874 * any hardware-generated hash is ignored.
876 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
877 th->th_sport, next_hop->sin_addr,
878 next_hop->sin_port ? ntohs(next_hop->sin_port) :
879 th->th_dport, INPLOOKUP_WILDCARD |
880 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
883 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
884 th->th_sport, ip->ip_dst, th->th_dport,
885 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
886 m->m_pkthdr.rcvif, m);
890 * If the INPCB does not exist then all data in the incoming
891 * segment is discarded and an appropriate RST is sent back.
892 * XXX MRT Send RST using which routing table?
896 * Log communication attempts to ports that are not
899 if ((V_tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
900 V_tcp_log_in_vain == 2) {
901 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
902 log(LOG_INFO, "%s; %s: Connection attempt "
903 "to closed port\n", s, __func__);
906 * When blackholing do not respond with a RST but
907 * completely ignore the segment and drop it.
909 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
913 rstreason = BANDLIM_RST_CLOSEDPORT;
916 INP_WLOCK_ASSERT(inp);
918 * While waiting for inp lock during the lookup, another thread
919 * can have dropped the inpcb, in which case we need to loop back
920 * and try to find a new inpcb to deliver to.
922 if (inp->inp_flags & INP_DROPPED) {
927 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
928 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
929 ((inp->inp_socket == NULL) ||
930 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
931 inp->inp_flowid = m->m_pkthdr.flowid;
932 inp->inp_flowtype = M_HASHTYPE_GET(m);
934 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
936 if (isipv6 && IPSEC_ENABLED(ipv6) &&
937 IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
945 if (IPSEC_ENABLED(ipv4) &&
946 IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
953 * Check the minimum TTL for socket.
955 if (inp->inp_ip_minttl != 0) {
958 if (inp->inp_ip_minttl > ip6->ip6_hlim)
962 if (inp->inp_ip_minttl > ip->ip_ttl)
967 * A previous connection in TIMEWAIT state is supposed to catch stray
968 * or duplicate segments arriving late. If this segment was a
969 * legitimate new connection attempt, the old INPCB gets removed and
970 * we can try again to find a listening socket.
972 * At this point, due to earlier optimism, we may hold only an inpcb
973 * lock, and not the inpcbinfo write lock. If so, we need to try to
974 * acquire it, or if that fails, acquire a reference on the inpcb,
975 * drop all locks, acquire a global write lock, and then re-acquire
976 * the inpcb lock. We may at that point discover that another thread
977 * has tried to free the inpcb, in which case we need to loop back
978 * and try to find a new inpcb to deliver to.
980 * XXXRW: It may be time to rethink timewait locking.
982 if (inp->inp_flags & INP_TIMEWAIT) {
983 if (thflags & TH_SYN)
984 tcp_dooptions(&to, optp, optlen, TO_SYN);
986 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
988 if (tcp_twcheck(inp, &to, th, m, tlen))
990 return (IPPROTO_DONE);
993 * The TCPCB may no longer exist if the connection is winding
994 * down or it is in the CLOSED state. Either way we drop the
995 * segment and send an appropriate response.
998 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
999 rstreason = BANDLIM_RST_CLOSEDPORT;
1004 if (tp->t_flags & TF_TOE) {
1005 tcp_offload_input(tp, m);
1006 m = NULL; /* consumed by the TOE driver */
1012 INP_WLOCK_ASSERT(inp);
1013 if (mac_inpcb_check_deliver(inp, m))
1016 so = inp->inp_socket;
1017 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1019 if (so->so_options & SO_DEBUG) {
1020 ostate = tp->t_state;
1023 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1026 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1029 #endif /* TCPDEBUG */
1031 * When the socket is accepting connections (the INPCB is in LISTEN
1032 * state) we look into the SYN cache if this is a new connection
1033 * attempt or the completion of a previous one.
1035 KASSERT(tp->t_state == TCPS_LISTEN || !(so->so_options & SO_ACCEPTCONN),
1036 ("%s: so accepting but tp %p not listening", __func__, tp));
1037 if (tp->t_state == TCPS_LISTEN && (so->so_options & SO_ACCEPTCONN)) {
1038 struct in_conninfo inc;
1040 bzero(&inc, sizeof(inc));
1043 inc.inc_flags |= INC_ISIPV6;
1044 if (inp->inp_inc.inc_flags & INC_IPV6MINMTU)
1045 inc.inc_flags |= INC_IPV6MINMTU;
1046 inc.inc6_faddr = ip6->ip6_src;
1047 inc.inc6_laddr = ip6->ip6_dst;
1051 inc.inc_faddr = ip->ip_src;
1052 inc.inc_laddr = ip->ip_dst;
1054 inc.inc_fport = th->th_sport;
1055 inc.inc_lport = th->th_dport;
1056 inc.inc_fibnum = so->so_fibnum;
1059 * Check for an existing connection attempt in syncache if
1060 * the flag is only ACK. A successful lookup creates a new
1061 * socket appended to the listen queue in SYN_RECEIVED state.
1063 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1066 * Parse the TCP options here because
1067 * syncookies need access to the reflected
1070 tcp_dooptions(&to, optp, optlen, 0);
1072 * NB: syncache_expand() doesn't unlock
1073 * inp and tcpinfo locks.
1075 rstreason = syncache_expand(&inc, &to, th, &so, m);
1076 if (rstreason < 0) {
1078 * A failing TCP MD5 signature comparison
1079 * must result in the segment being dropped
1080 * and must not produce any response back
1084 } else if (rstreason == 0) {
1086 * No syncache entry or ACK was not
1087 * for our SYN/ACK. Send a RST.
1088 * NB: syncache did its own logging
1089 * of the failure cause.
1091 rstreason = BANDLIM_RST_OPENPORT;
1097 * We completed the 3-way handshake
1098 * but could not allocate a socket
1099 * either due to memory shortage,
1100 * listen queue length limits or
1101 * global socket limits. Send RST
1102 * or wait and have the remote end
1103 * retransmit the ACK for another
1106 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1107 log(LOG_DEBUG, "%s; %s: Listen socket: "
1108 "Socket allocation failed due to "
1109 "limits or memory shortage, %s\n",
1111 V_tcp_sc_rst_sock_fail ?
1112 "sending RST" : "try again");
1113 if (V_tcp_sc_rst_sock_fail) {
1114 rstreason = BANDLIM_UNLIMITED;
1120 * Socket is created in state SYN_RECEIVED.
1121 * Unlock the listen socket, lock the newly
1122 * created socket and update the tp variable.
1124 INP_WUNLOCK(inp); /* listen socket */
1125 inp = sotoinpcb(so);
1127 * New connection inpcb is already locked by
1128 * syncache_expand().
1130 INP_WLOCK_ASSERT(inp);
1131 tp = intotcpcb(inp);
1132 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1133 ("%s: ", __func__));
1135 * Process the segment and the data it
1136 * contains. tcp_do_segment() consumes
1137 * the mbuf chain and unlocks the inpcb.
1139 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1140 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1142 return (IPPROTO_DONE);
1145 * Segment flag validation for new connection attempts:
1147 * Our (SYN|ACK) response was rejected.
1148 * Check with syncache and remove entry to prevent
1151 * NB: syncache_chkrst does its own logging of failure
1154 if (thflags & TH_RST) {
1155 syncache_chkrst(&inc, th, m);
1159 * We can't do anything without SYN.
1161 if ((thflags & TH_SYN) == 0) {
1162 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1163 log(LOG_DEBUG, "%s; %s: Listen socket: "
1164 "SYN is missing, segment ignored\n",
1166 TCPSTAT_INC(tcps_badsyn);
1170 * (SYN|ACK) is bogus on a listen socket.
1172 if (thflags & TH_ACK) {
1173 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1174 log(LOG_DEBUG, "%s; %s: Listen socket: "
1175 "SYN|ACK invalid, segment rejected\n",
1177 syncache_badack(&inc); /* XXX: Not needed! */
1178 TCPSTAT_INC(tcps_badsyn);
1179 rstreason = BANDLIM_RST_OPENPORT;
1183 * If the drop_synfin option is enabled, drop all
1184 * segments with both the SYN and FIN bits set.
1185 * This prevents e.g. nmap from identifying the
1187 * XXX: Poor reasoning. nmap has other methods
1188 * and is constantly refining its stack detection
1190 * XXX: This is a violation of the TCP specification
1191 * and was used by RFC1644.
1193 if ((thflags & TH_FIN) && V_drop_synfin) {
1194 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1195 log(LOG_DEBUG, "%s; %s: Listen socket: "
1196 "SYN|FIN segment ignored (based on "
1197 "sysctl setting)\n", s, __func__);
1198 TCPSTAT_INC(tcps_badsyn);
1202 * Segment's flags are (SYN) or (SYN|FIN).
1204 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1205 * as they do not affect the state of the TCP FSM.
1206 * The data pointed to by TH_URG and th_urp is ignored.
1208 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1209 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1210 KASSERT(thflags & (TH_SYN),
1211 ("%s: Listen socket: TH_SYN not set", __func__));
1214 * If deprecated address is forbidden,
1215 * we do not accept SYN to deprecated interface
1216 * address to prevent any new inbound connection from
1217 * getting established.
1218 * When we do not accept SYN, we send a TCP RST,
1219 * with deprecated source address (instead of dropping
1220 * it). We compromise it as it is much better for peer
1221 * to send a RST, and RST will be the final packet
1224 * If we do not forbid deprecated addresses, we accept
1225 * the SYN packet. RFC2462 does not suggest dropping
1227 * If we decipher RFC2462 5.5.4, it says like this:
1228 * 1. use of deprecated addr with existing
1229 * communication is okay - "SHOULD continue to be
1231 * 2. use of it with new communication:
1232 * (2a) "SHOULD NOT be used if alternate address
1233 * with sufficient scope is available"
1234 * (2b) nothing mentioned otherwise.
1235 * Here we fall into (2b) case as we have no choice in
1236 * our source address selection - we must obey the peer.
1238 * The wording in RFC2462 is confusing, and there are
1239 * multiple description text for deprecated address
1240 * handling - worse, they are not exactly the same.
1241 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1243 if (isipv6 && !V_ip6_use_deprecated) {
1244 struct in6_ifaddr *ia6;
1246 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1248 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1249 ifa_free(&ia6->ia_ifa);
1250 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1251 log(LOG_DEBUG, "%s; %s: Listen socket: "
1252 "Connection attempt to deprecated "
1253 "IPv6 address rejected\n",
1255 rstreason = BANDLIM_RST_OPENPORT;
1259 ifa_free(&ia6->ia_ifa);
1263 * Basic sanity checks on incoming SYN requests:
1264 * Don't respond if the destination is a link layer
1265 * broadcast according to RFC1122 4.2.3.10, p. 104.
1266 * If it is from this socket it must be forged.
1267 * Don't respond if the source or destination is a
1268 * global or subnet broad- or multicast address.
1269 * Note that it is quite possible to receive unicast
1270 * link-layer packets with a broadcast IP address. Use
1271 * in_broadcast() to find them.
1273 if (m->m_flags & (M_BCAST|M_MCAST)) {
1274 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1275 log(LOG_DEBUG, "%s; %s: Listen socket: "
1276 "Connection attempt from broad- or multicast "
1277 "link layer address ignored\n", s, __func__);
1282 if (th->th_dport == th->th_sport &&
1283 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1284 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1285 log(LOG_DEBUG, "%s; %s: Listen socket: "
1286 "Connection attempt to/from self "
1287 "ignored\n", s, __func__);
1290 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1291 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1292 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1293 log(LOG_DEBUG, "%s; %s: Listen socket: "
1294 "Connection attempt from/to multicast "
1295 "address ignored\n", s, __func__);
1300 #if defined(INET) && defined(INET6)
1305 if (th->th_dport == th->th_sport &&
1306 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1307 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1308 log(LOG_DEBUG, "%s; %s: Listen socket: "
1309 "Connection attempt from/to self "
1310 "ignored\n", s, __func__);
1313 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1314 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1315 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1316 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1317 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1318 log(LOG_DEBUG, "%s; %s: Listen socket: "
1319 "Connection attempt from/to broad- "
1320 "or multicast address ignored\n",
1327 * SYN appears to be valid. Create compressed TCP state
1331 if (so->so_options & SO_DEBUG)
1332 tcp_trace(TA_INPUT, ostate, tp,
1333 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1335 TCP_PROBE3(debug__input, tp, th, m);
1336 tcp_dooptions(&to, optp, optlen, TO_SYN);
1337 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL, iptos))
1338 goto tfo_socket_result;
1341 * Entry added to syncache and mbuf consumed.
1342 * Only the listen socket is unlocked by syncache_add().
1344 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1345 return (IPPROTO_DONE);
1346 } else if (tp->t_state == TCPS_LISTEN) {
1348 * When a listen socket is torn down the SO_ACCEPTCONN
1349 * flag is removed first while connections are drained
1350 * from the accept queue in a unlock/lock cycle of the
1351 * ACCEPT_LOCK, opening a race condition allowing a SYN
1352 * attempt go through unhandled.
1356 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1357 if (tp->t_flags & TF_SIGNATURE) {
1358 tcp_dooptions(&to, optp, optlen, thflags);
1359 if ((to.to_flags & TOF_SIGNATURE) == 0) {
1360 TCPSTAT_INC(tcps_sig_err_nosigopt);
1363 if (!TCPMD5_ENABLED() ||
1364 TCPMD5_INPUT(m, th, to.to_signature) != 0)
1368 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1371 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1372 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1373 * the inpcb, and unlocks pcbinfo.
1375 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos);
1376 return (IPPROTO_DONE);
1379 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1382 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1385 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1386 m = NULL; /* mbuf chain got consumed. */
1391 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1397 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
1402 return (IPPROTO_DONE);
1406 * Automatic sizing of receive socket buffer. Often the send
1407 * buffer size is not optimally adjusted to the actual network
1408 * conditions at hand (delay bandwidth product). Setting the
1409 * buffer size too small limits throughput on links with high
1410 * bandwidth and high delay (eg. trans-continental/oceanic links).
1412 * On the receive side the socket buffer memory is only rarely
1413 * used to any significant extent. This allows us to be much
1414 * more aggressive in scaling the receive socket buffer. For
1415 * the case that the buffer space is actually used to a large
1416 * extent and we run out of kernel memory we can simply drop
1417 * the new segments; TCP on the sender will just retransmit it
1418 * later. Setting the buffer size too big may only consume too
1419 * much kernel memory if the application doesn't read() from
1420 * the socket or packet loss or reordering makes use of the
1423 * The criteria to step up the receive buffer one notch are:
1424 * 1. Application has not set receive buffer size with
1425 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1426 * 2. the number of bytes received during 1/2 of an sRTT
1427 * is at least 3/8 of the current socket buffer size.
1428 * 3. receive buffer size has not hit maximal automatic size;
1430 * If all of the criteria are met we increaset the socket buffer
1431 * by a 1/2 (bounded by the max). This allows us to keep ahead
1432 * of slow-start but also makes it so our peer never gets limited
1433 * by our rwnd which we then open up causing a burst.
1435 * This algorithm does two steps per RTT at most and only if
1436 * we receive a bulk stream w/o packet losses or reorderings.
1437 * Shrinking the buffer during idle times is not necessary as
1438 * it doesn't consume any memory when idle.
1440 * TODO: Only step up if the application is actually serving
1441 * the buffer to better manage the socket buffer resources.
1444 tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1445 struct tcpcb *tp, int tlen)
1449 if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1450 tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1451 TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1452 ((tp->t_srtt >> TCP_RTT_SHIFT)/2)) {
1453 if (tp->rfbuf_cnt > ((so->so_rcv.sb_hiwat / 2)/ 4 * 3) &&
1454 so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1455 newsize = min((so->so_rcv.sb_hiwat + (so->so_rcv.sb_hiwat/2)), V_tcp_autorcvbuf_max);
1457 TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1459 /* Start over with next RTT. */
1463 tp->rfbuf_cnt += tlen; /* add up */
1469 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1470 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos)
1472 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1473 int rstreason, todrop, win, incforsyn = 0;
1477 struct in_conninfo *inc;
1484 * The size of tcp_saveipgen must be the size of the max ip header,
1487 u_char tcp_saveipgen[IP6_HDR_LEN];
1488 struct tcphdr tcp_savetcp;
1491 thflags = th->th_flags;
1492 inc = &tp->t_inpcb->inp_inc;
1493 tp->sackhint.last_sack_ack = 0;
1495 nsegs = max(1, m->m_pkthdr.lro_nsegs);
1498 INP_WLOCK_ASSERT(tp->t_inpcb);
1499 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1501 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1505 /* Save segment, if requested. */
1506 tcp_pcap_add(th, m, &(tp->t_inpkts));
1508 TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
1511 if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1512 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1513 log(LOG_DEBUG, "%s; %s: "
1514 "SYN|FIN segment ignored (based on "
1515 "sysctl setting)\n", s, __func__);
1522 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1523 * check SEQ.ACK first.
1525 if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1526 (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1527 rstreason = BANDLIM_UNLIMITED;
1532 * Segment received on connection.
1533 * Reset idle time and keep-alive timer.
1534 * XXX: This should be done after segment
1535 * validation to ignore broken/spoofed segs.
1537 tp->t_rcvtime = ticks;
1540 * Scale up the window into a 32-bit value.
1541 * For the SYN_SENT state the scale is zero.
1543 tiwin = th->th_win << tp->snd_scale;
1545 stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
1549 * TCP ECN processing.
1551 if (tp->t_flags2 & TF2_ECN_PERMIT) {
1552 if (thflags & TH_CWR) {
1553 tp->t_flags2 &= ~TF2_ECN_SND_ECE;
1554 tp->t_flags |= TF_ACKNOW;
1556 switch (iptos & IPTOS_ECN_MASK) {
1558 tp->t_flags2 |= TF2_ECN_SND_ECE;
1559 TCPSTAT_INC(tcps_ecn_ce);
1561 case IPTOS_ECN_ECT0:
1562 TCPSTAT_INC(tcps_ecn_ect0);
1564 case IPTOS_ECN_ECT1:
1565 TCPSTAT_INC(tcps_ecn_ect1);
1569 /* Process a packet differently from RFC3168. */
1570 cc_ecnpkt_handler(tp, th, iptos);
1572 /* Congestion experienced. */
1573 if (thflags & TH_ECE) {
1574 cc_cong_signal(tp, th, CC_ECN);
1579 * Parse options on any incoming segment.
1581 tcp_dooptions(&to, (u_char *)(th + 1),
1582 (th->th_off << 2) - sizeof(struct tcphdr),
1583 (thflags & TH_SYN) ? TO_SYN : 0);
1585 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1586 if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1587 (to.to_flags & TOF_SIGNATURE) == 0) {
1588 TCPSTAT_INC(tcps_sig_err_sigopt);
1589 /* XXX: should drop? */
1593 * If echoed timestamp is later than the current time,
1594 * fall back to non RFC1323 RTT calculation. Normalize
1595 * timestamp if syncookies were used when this connection
1598 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1599 to.to_tsecr -= tp->ts_offset;
1600 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1602 else if (tp->t_flags & TF_PREVVALID &&
1603 tp->t_badrxtwin != 0 && SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
1604 cc_cong_signal(tp, th, CC_RTO_ERR);
1607 * Process options only when we get SYN/ACK back. The SYN case
1608 * for incoming connections is handled in tcp_syncache.
1609 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1610 * or <SYN,ACK>) segment itself is never scaled.
1611 * XXX this is traditional behavior, may need to be cleaned up.
1613 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1614 /* Handle parallel SYN for ECN */
1615 if (!(thflags & TH_ACK) &&
1616 ((thflags & (TH_CWR | TH_ECE)) == (TH_CWR | TH_ECE)) &&
1617 ((V_tcp_do_ecn == 1) || (V_tcp_do_ecn == 2))) {
1618 tp->t_flags2 |= TF2_ECN_PERMIT;
1619 tp->t_flags2 |= TF2_ECN_SND_ECE;
1620 TCPSTAT_INC(tcps_ecn_shs);
1622 if ((to.to_flags & TOF_SCALE) &&
1623 (tp->t_flags & TF_REQ_SCALE)) {
1624 tp->t_flags |= TF_RCVD_SCALE;
1625 tp->snd_scale = to.to_wscale;
1628 * Initial send window. It will be updated with
1629 * the next incoming segment to the scaled value.
1631 tp->snd_wnd = th->th_win;
1632 if (to.to_flags & TOF_TS) {
1633 tp->t_flags |= TF_RCVD_TSTMP;
1634 tp->ts_recent = to.to_tsval;
1635 tp->ts_recent_age = tcp_ts_getticks();
1637 if (to.to_flags & TOF_MSS)
1638 tcp_mss(tp, to.to_mss);
1639 if ((tp->t_flags & TF_SACK_PERMIT) &&
1640 (to.to_flags & TOF_SACKPERM) == 0)
1641 tp->t_flags &= ~TF_SACK_PERMIT;
1642 if (IS_FASTOPEN(tp->t_flags)) {
1643 if (to.to_flags & TOF_FASTOPEN) {
1646 if (to.to_flags & TOF_MSS)
1649 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
1653 tcp_fastopen_update_cache(tp, mss,
1654 to.to_tfo_len, to.to_tfo_cookie);
1656 tcp_fastopen_disable_path(tp);
1661 * If timestamps were negotiated during SYN/ACK they should
1662 * appear on every segment during this session and vice versa.
1664 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1665 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1666 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1667 "no action\n", s, __func__);
1671 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1672 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1673 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1674 "no action\n", s, __func__);
1680 * Header prediction: check for the two common cases
1681 * of a uni-directional data xfer. If the packet has
1682 * no control flags, is in-sequence, the window didn't
1683 * change and we're not retransmitting, it's a
1684 * candidate. If the length is zero and the ack moved
1685 * forward, we're the sender side of the xfer. Just
1686 * free the data acked & wake any higher level process
1687 * that was blocked waiting for space. If the length
1688 * is non-zero and the ack didn't move, we're the
1689 * receiver side. If we're getting packets in-order
1690 * (the reassembly queue is empty), add the data to
1691 * the socket buffer and note that we need a delayed ack.
1692 * Make sure that the hidden state-flags are also off.
1693 * Since we check for TCPS_ESTABLISHED first, it can only
1696 if (tp->t_state == TCPS_ESTABLISHED &&
1697 th->th_seq == tp->rcv_nxt &&
1698 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1699 tp->snd_nxt == tp->snd_max &&
1700 tiwin && tiwin == tp->snd_wnd &&
1701 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1703 ((to.to_flags & TOF_TS) == 0 ||
1704 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1707 * If last ACK falls within this segment's sequence numbers,
1708 * record the timestamp.
1709 * NOTE that the test is modified according to the latest
1710 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1712 if ((to.to_flags & TOF_TS) != 0 &&
1713 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1714 tp->ts_recent_age = tcp_ts_getticks();
1715 tp->ts_recent = to.to_tsval;
1719 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1720 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1721 !IN_RECOVERY(tp->t_flags) &&
1722 (to.to_flags & TOF_SACK) == 0 &&
1723 TAILQ_EMPTY(&tp->snd_holes)) {
1725 * This is a pure ack for outstanding data.
1727 TCPSTAT_INC(tcps_predack);
1730 * "bad retransmit" recovery without timestamps.
1732 if ((to.to_flags & TOF_TS) == 0 &&
1733 tp->t_rxtshift == 1 &&
1734 tp->t_flags & TF_PREVVALID &&
1735 (int)(ticks - tp->t_badrxtwin) < 0) {
1736 cc_cong_signal(tp, th, CC_RTO_ERR);
1740 * Recalculate the transmit timer / rtt.
1742 * Some boxes send broken timestamp replies
1743 * during the SYN+ACK phase, ignore
1744 * timestamps of 0 or we could calculate a
1745 * huge RTT and blow up the retransmit timer.
1747 if ((to.to_flags & TOF_TS) != 0 &&
1751 t = tcp_ts_getticks() - to.to_tsecr;
1752 if (!tp->t_rttlow || tp->t_rttlow > t)
1755 TCP_TS_TO_TICKS(t) + 1);
1756 } else if (tp->t_rtttime &&
1757 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1758 if (!tp->t_rttlow ||
1759 tp->t_rttlow > ticks - tp->t_rtttime)
1760 tp->t_rttlow = ticks - tp->t_rtttime;
1762 ticks - tp->t_rtttime);
1764 acked = BYTES_THIS_ACK(tp, th);
1767 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1768 hhook_run_tcp_est_in(tp, th, &to);
1771 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
1772 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1773 sbdrop(&so->so_snd, acked);
1774 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1775 SEQ_LEQ(th->th_ack, tp->snd_recover))
1776 tp->snd_recover = th->th_ack - 1;
1779 * Let the congestion control algorithm update
1780 * congestion control related information. This
1781 * typically means increasing the congestion
1784 cc_ack_received(tp, th, nsegs, CC_ACK);
1786 tp->snd_una = th->th_ack;
1788 * Pull snd_wl2 up to prevent seq wrap relative
1791 tp->snd_wl2 = th->th_ack;
1796 * If all outstanding data are acked, stop
1797 * retransmit timer, otherwise restart timer
1798 * using current (possibly backed-off) value.
1799 * If process is waiting for space,
1800 * wakeup/selwakeup/signal. If data
1801 * are ready to send, let tcp_output
1802 * decide between more output or persist.
1805 if (so->so_options & SO_DEBUG)
1806 tcp_trace(TA_INPUT, ostate, tp,
1807 (void *)tcp_saveipgen,
1810 TCP_PROBE3(debug__input, tp, th, m);
1811 if (tp->snd_una == tp->snd_max)
1812 tcp_timer_activate(tp, TT_REXMT, 0);
1813 else if (!tcp_timer_active(tp, TT_PERSIST))
1814 tcp_timer_activate(tp, TT_REXMT,
1817 if (sbavail(&so->so_snd))
1818 (void) tp->t_fb->tfb_tcp_output(tp);
1821 } else if (th->th_ack == tp->snd_una &&
1822 tlen <= sbspace(&so->so_rcv)) {
1823 int newsize = 0; /* automatic sockbuf scaling */
1826 * This is a pure, in-sequence data packet with
1827 * nothing on the reassembly queue and we have enough
1828 * buffer space to take it.
1830 /* Clean receiver SACK report if present */
1831 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1832 tcp_clean_sackreport(tp);
1833 TCPSTAT_INC(tcps_preddat);
1834 tp->rcv_nxt += tlen;
1836 * Pull snd_wl1 up to prevent seq wrap relative to
1839 tp->snd_wl1 = th->th_seq;
1841 * Pull rcv_up up to prevent seq wrap relative to
1844 tp->rcv_up = tp->rcv_nxt;
1845 TCPSTAT_ADD(tcps_rcvpack, nsegs);
1846 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1848 if (so->so_options & SO_DEBUG)
1849 tcp_trace(TA_INPUT, ostate, tp,
1850 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1852 TCP_PROBE3(debug__input, tp, th, m);
1854 newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
1856 /* Add data to socket buffer. */
1857 SOCKBUF_LOCK(&so->so_rcv);
1858 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1862 * Set new socket buffer size.
1863 * Give up when limit is reached.
1866 if (!sbreserve_locked(&so->so_rcv,
1868 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1869 m_adj(m, drop_hdrlen); /* delayed header drop */
1870 sbappendstream_locked(&so->so_rcv, m, 0);
1872 /* NB: sorwakeup_locked() does an implicit unlock. */
1873 sorwakeup_locked(so);
1874 if (DELAY_ACK(tp, tlen)) {
1875 tp->t_flags |= TF_DELACK;
1877 tp->t_flags |= TF_ACKNOW;
1878 tp->t_fb->tfb_tcp_output(tp);
1885 * Calculate amount of space in receive window,
1886 * and then do TCP input processing.
1887 * Receive window is amount of space in rcv queue,
1888 * but not less than advertised window.
1890 win = sbspace(&so->so_rcv);
1893 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1895 switch (tp->t_state) {
1898 * If the state is SYN_RECEIVED:
1899 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1901 case TCPS_SYN_RECEIVED:
1902 if ((thflags & TH_ACK) &&
1903 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1904 SEQ_GT(th->th_ack, tp->snd_max))) {
1905 rstreason = BANDLIM_RST_OPENPORT;
1908 if (IS_FASTOPEN(tp->t_flags)) {
1910 * When a TFO connection is in SYN_RECEIVED, the
1911 * only valid packets are the initial SYN, a
1912 * retransmit/copy of the initial SYN (possibly with
1913 * a subset of the original data), a valid ACK, a
1916 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1917 rstreason = BANDLIM_RST_OPENPORT;
1919 } else if (thflags & TH_SYN) {
1920 /* non-initial SYN is ignored */
1921 if ((tcp_timer_active(tp, TT_DELACK) ||
1922 tcp_timer_active(tp, TT_REXMT)))
1924 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1931 * If the state is SYN_SENT:
1932 * if seg contains a RST with valid ACK (SEQ.ACK has already
1933 * been verified), then drop the connection.
1934 * if seg contains a RST without an ACK, drop the seg.
1935 * if seg does not contain SYN, then drop the seg.
1936 * Otherwise this is an acceptable SYN segment
1937 * initialize tp->rcv_nxt and tp->irs
1938 * if seg contains ack then advance tp->snd_una
1939 * if seg contains an ECE and ECN support is enabled, the stream
1941 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1942 * arrange for segment to be acked (eventually)
1943 * continue processing rest of data/controls, beginning with URG
1946 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1947 TCP_PROBE5(connect__refused, NULL, tp,
1949 tp = tcp_drop(tp, ECONNREFUSED);
1951 if (thflags & TH_RST)
1953 if (!(thflags & TH_SYN))
1956 tp->irs = th->th_seq;
1958 if (thflags & TH_ACK) {
1959 int tfo_partial_ack = 0;
1961 TCPSTAT_INC(tcps_connects);
1964 mac_socketpeer_set_from_mbuf(m, so);
1966 /* Do window scaling on this connection? */
1967 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1968 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1969 tp->rcv_scale = tp->request_r_scale;
1971 tp->rcv_adv += min(tp->rcv_wnd,
1972 TCP_MAXWIN << tp->rcv_scale);
1973 tp->snd_una++; /* SYN is acked */
1975 * If not all the data that was sent in the TFO SYN
1976 * has been acked, resend the remainder right away.
1978 if (IS_FASTOPEN(tp->t_flags) &&
1979 (tp->snd_una != tp->snd_max)) {
1980 tp->snd_nxt = th->th_ack;
1981 tfo_partial_ack = 1;
1984 * If there's data, delay ACK; if there's also a FIN
1985 * ACKNOW will be turned on later.
1987 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
1988 tcp_timer_activate(tp, TT_DELACK,
1991 tp->t_flags |= TF_ACKNOW;
1993 if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) &&
1994 (V_tcp_do_ecn == 1)) {
1995 tp->t_flags2 |= TF2_ECN_PERMIT;
1996 TCPSTAT_INC(tcps_ecn_shs);
2000 * Received <SYN,ACK> in SYN_SENT[*] state.
2002 * SYN_SENT --> ESTABLISHED
2003 * SYN_SENT* --> FIN_WAIT_1
2005 tp->t_starttime = ticks;
2006 if (tp->t_flags & TF_NEEDFIN) {
2007 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2008 tp->t_flags &= ~TF_NEEDFIN;
2011 tcp_state_change(tp, TCPS_ESTABLISHED);
2012 TCP_PROBE5(connect__established, NULL, tp,
2015 tcp_timer_activate(tp, TT_KEEP,
2020 * Received initial SYN in SYN-SENT[*] state =>
2021 * simultaneous open.
2022 * If it succeeds, connection is * half-synchronized.
2023 * Otherwise, do 3-way handshake:
2024 * SYN-SENT -> SYN-RECEIVED
2025 * SYN-SENT* -> SYN-RECEIVED*
2027 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2028 tcp_timer_activate(tp, TT_REXMT, 0);
2029 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2032 INP_WLOCK_ASSERT(tp->t_inpcb);
2035 * Advance th->th_seq to correspond to first data byte.
2036 * If data, trim to stay within window,
2037 * dropping FIN if necessary.
2040 if (tlen > tp->rcv_wnd) {
2041 todrop = tlen - tp->rcv_wnd;
2045 TCPSTAT_INC(tcps_rcvpackafterwin);
2046 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2048 tp->snd_wl1 = th->th_seq - 1;
2049 tp->rcv_up = th->th_seq;
2051 * Client side of transaction: already sent SYN and data.
2052 * If the remote host used T/TCP to validate the SYN,
2053 * our data will be ACK'd; if so, enter normal data segment
2054 * processing in the middle of step 5, ack processing.
2055 * Otherwise, goto step 6.
2057 if (thflags & TH_ACK)
2063 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2064 * do normal processing.
2066 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2070 break; /* continue normal processing */
2074 * States other than LISTEN or SYN_SENT.
2075 * First check the RST flag and sequence number since reset segments
2076 * are exempt from the timestamp and connection count tests. This
2077 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2078 * below which allowed reset segments in half the sequence space
2079 * to fall though and be processed (which gives forged reset
2080 * segments with a random sequence number a 50 percent chance of
2081 * killing a connection).
2082 * Then check timestamp, if present.
2083 * Then check the connection count, if present.
2084 * Then check that at least some bytes of segment are within
2085 * receive window. If segment begins before rcv_nxt,
2086 * drop leading data (and SYN); if nothing left, just ack.
2088 if (thflags & TH_RST) {
2090 * RFC5961 Section 3.2
2092 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2093 * - If RST is in window, we send challenge ACK.
2095 * Note: to take into account delayed ACKs, we should
2096 * test against last_ack_sent instead of rcv_nxt.
2097 * Note 2: we handle special case of closed window, not
2098 * covered by the RFC.
2100 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2101 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2102 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2104 KASSERT(tp->t_state != TCPS_SYN_SENT,
2105 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2108 if (V_tcp_insecure_rst ||
2109 tp->last_ack_sent == th->th_seq) {
2110 TCPSTAT_INC(tcps_drops);
2111 /* Drop the connection. */
2112 switch (tp->t_state) {
2113 case TCPS_SYN_RECEIVED:
2114 so->so_error = ECONNREFUSED;
2116 case TCPS_ESTABLISHED:
2117 case TCPS_FIN_WAIT_1:
2118 case TCPS_FIN_WAIT_2:
2119 case TCPS_CLOSE_WAIT:
2122 so->so_error = ECONNRESET;
2129 TCPSTAT_INC(tcps_badrst);
2130 /* Send challenge ACK. */
2131 tcp_respond(tp, mtod(m, void *), th, m,
2132 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2133 tp->last_ack_sent = tp->rcv_nxt;
2141 * RFC5961 Section 4.2
2142 * Send challenge ACK for any SYN in synchronized state.
2144 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2145 tp->t_state != TCPS_SYN_RECEIVED) {
2146 TCPSTAT_INC(tcps_badsyn);
2147 if (V_tcp_insecure_syn &&
2148 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2149 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2150 tp = tcp_drop(tp, ECONNRESET);
2151 rstreason = BANDLIM_UNLIMITED;
2153 /* Send challenge ACK. */
2154 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2155 tp->snd_nxt, TH_ACK);
2156 tp->last_ack_sent = tp->rcv_nxt;
2163 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2164 * and it's less than ts_recent, drop it.
2166 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2167 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2169 /* Check to see if ts_recent is over 24 days old. */
2170 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2172 * Invalidate ts_recent. If this segment updates
2173 * ts_recent, the age will be reset later and ts_recent
2174 * will get a valid value. If it does not, setting
2175 * ts_recent to zero will at least satisfy the
2176 * requirement that zero be placed in the timestamp
2177 * echo reply when ts_recent isn't valid. The
2178 * age isn't reset until we get a valid ts_recent
2179 * because we don't want out-of-order segments to be
2180 * dropped when ts_recent is old.
2184 TCPSTAT_INC(tcps_rcvduppack);
2185 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2186 TCPSTAT_INC(tcps_pawsdrop);
2194 * In the SYN-RECEIVED state, validate that the packet belongs to
2195 * this connection before trimming the data to fit the receive
2196 * window. Check the sequence number versus IRS since we know
2197 * the sequence numbers haven't wrapped. This is a partial fix
2198 * for the "LAND" DoS attack.
2200 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2201 rstreason = BANDLIM_RST_OPENPORT;
2205 todrop = tp->rcv_nxt - th->th_seq;
2207 if (thflags & TH_SYN) {
2217 * Following if statement from Stevens, vol. 2, p. 960.
2220 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2222 * Any valid FIN must be to the left of the window.
2223 * At this point the FIN must be a duplicate or out
2224 * of sequence; drop it.
2229 * Send an ACK to resynchronize and drop any data.
2230 * But keep on processing for RST or ACK.
2232 tp->t_flags |= TF_ACKNOW;
2234 TCPSTAT_INC(tcps_rcvduppack);
2235 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2237 TCPSTAT_INC(tcps_rcvpartduppack);
2238 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2241 * DSACK - add SACK block for dropped range
2243 if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2244 tcp_update_sack_list(tp, th->th_seq,
2245 th->th_seq + todrop);
2247 * ACK now, as the next in-sequence segment
2248 * will clear the DSACK block again
2250 tp->t_flags |= TF_ACKNOW;
2252 drop_hdrlen += todrop; /* drop from the top afterwards */
2253 th->th_seq += todrop;
2255 if (th->th_urp > todrop)
2256 th->th_urp -= todrop;
2264 * If new data are received on a connection after the
2265 * user processes are gone, then RST the other end.
2267 if ((so->so_state & SS_NOFDREF) &&
2268 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2269 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2270 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2271 "after socket was closed, "
2272 "sending RST and removing tcpcb\n",
2273 s, __func__, tcpstates[tp->t_state], tlen);
2277 TCPSTAT_INC(tcps_rcvafterclose);
2278 rstreason = BANDLIM_UNLIMITED;
2283 * If segment ends after window, drop trailing data
2284 * (and PUSH and FIN); if nothing left, just ACK.
2286 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2288 TCPSTAT_INC(tcps_rcvpackafterwin);
2289 if (todrop >= tlen) {
2290 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2292 * If window is closed can only take segments at
2293 * window edge, and have to drop data and PUSH from
2294 * incoming segments. Continue processing, but
2295 * remember to ack. Otherwise, drop segment
2298 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2299 tp->t_flags |= TF_ACKNOW;
2300 TCPSTAT_INC(tcps_rcvwinprobe);
2304 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2307 thflags &= ~(TH_PUSH|TH_FIN);
2311 * If last ACK falls within this segment's sequence numbers,
2312 * record its timestamp.
2314 * 1) That the test incorporates suggestions from the latest
2315 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2316 * 2) That updating only on newer timestamps interferes with
2317 * our earlier PAWS tests, so this check should be solely
2318 * predicated on the sequence space of this segment.
2319 * 3) That we modify the segment boundary check to be
2320 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2321 * instead of RFC1323's
2322 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2323 * This modified check allows us to overcome RFC1323's
2324 * limitations as described in Stevens TCP/IP Illustrated
2325 * Vol. 2 p.869. In such cases, we can still calculate the
2326 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2328 if ((to.to_flags & TOF_TS) != 0 &&
2329 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2330 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2331 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2332 tp->ts_recent_age = tcp_ts_getticks();
2333 tp->ts_recent = to.to_tsval;
2337 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2338 * flag is on (half-synchronized state), then queue data for
2339 * later processing; else drop segment and return.
2341 if ((thflags & TH_ACK) == 0) {
2342 if (tp->t_state == TCPS_SYN_RECEIVED ||
2343 (tp->t_flags & TF_NEEDSYN)) {
2344 if (tp->t_state == TCPS_SYN_RECEIVED &&
2345 IS_FASTOPEN(tp->t_flags)) {
2346 tp->snd_wnd = tiwin;
2350 } else if (tp->t_flags & TF_ACKNOW)
2359 switch (tp->t_state) {
2362 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2363 * ESTABLISHED state and continue processing.
2364 * The ACK was checked above.
2366 case TCPS_SYN_RECEIVED:
2368 TCPSTAT_INC(tcps_connects);
2370 /* Do window scaling? */
2371 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2372 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2373 tp->rcv_scale = tp->request_r_scale;
2375 tp->snd_wnd = tiwin;
2378 * SYN-RECEIVED -> ESTABLISHED
2379 * SYN-RECEIVED* -> FIN-WAIT-1
2381 tp->t_starttime = ticks;
2382 if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
2383 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2384 tp->t_tfo_pending = NULL;
2386 if (tp->t_flags & TF_NEEDFIN) {
2387 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2388 tp->t_flags &= ~TF_NEEDFIN;
2390 tcp_state_change(tp, TCPS_ESTABLISHED);
2391 TCP_PROBE5(accept__established, NULL, tp,
2394 * TFO connections call cc_conn_init() during SYN
2395 * processing. Calling it again here for such
2396 * connections is not harmless as it would undo the
2397 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2400 if (!IS_FASTOPEN(tp->t_flags))
2402 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2405 * Account for the ACK of our SYN prior to
2406 * regular ACK processing below, except for
2407 * simultaneous SYN, which is handled later.
2409 if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2412 * If segment contains data or ACK, will call tcp_reass()
2413 * later; if not, do so now to pass queued data to user.
2415 if (tlen == 0 && (thflags & TH_FIN) == 0)
2416 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2418 tp->snd_wl1 = th->th_seq - 1;
2422 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2423 * ACKs. If the ack is in the range
2424 * tp->snd_una < th->th_ack <= tp->snd_max
2425 * then advance tp->snd_una to th->th_ack and drop
2426 * data from the retransmission queue. If this ACK reflects
2427 * more up to date window information we update our window information.
2429 case TCPS_ESTABLISHED:
2430 case TCPS_FIN_WAIT_1:
2431 case TCPS_FIN_WAIT_2:
2432 case TCPS_CLOSE_WAIT:
2435 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2436 TCPSTAT_INC(tcps_rcvacktoomuch);
2439 if ((tp->t_flags & TF_SACK_PERMIT) &&
2440 ((to.to_flags & TOF_SACK) ||
2441 !TAILQ_EMPTY(&tp->snd_holes)))
2442 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2445 * Reset the value so that previous (valid) value
2446 * from the last ack with SACK doesn't get used.
2448 tp->sackhint.sacked_bytes = 0;
2451 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2452 hhook_run_tcp_est_in(tp, th, &to);
2455 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2458 maxseg = tcp_maxseg(tp);
2460 (tiwin == tp->snd_wnd ||
2461 (tp->t_flags & TF_SACK_PERMIT))) {
2463 * If this is the first time we've seen a
2464 * FIN from the remote, this is not a
2465 * duplicate and it needs to be processed
2466 * normally. This happens during a
2467 * simultaneous close.
2469 if ((thflags & TH_FIN) &&
2470 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2474 TCPSTAT_INC(tcps_rcvdupack);
2476 * If we have outstanding data (other than
2477 * a window probe), this is a completely
2478 * duplicate ack (ie, window info didn't
2479 * change and FIN isn't set),
2480 * the ack is the biggest we've
2481 * seen and we've seen exactly our rexmt
2482 * threshold of them, assume a packet
2483 * has been dropped and retransmit it.
2484 * Kludge snd_nxt & the congestion
2485 * window so we send only this one
2488 * We know we're losing at the current
2489 * window size so do congestion avoidance
2490 * (set ssthresh to half the current window
2491 * and pull our congestion window back to
2492 * the new ssthresh).
2494 * Dup acks mean that packets have left the
2495 * network (they're now cached at the receiver)
2496 * so bump cwnd by the amount in the receiver
2497 * to keep a constant cwnd packets in the
2500 * When using TCP ECN, notify the peer that
2501 * we reduced the cwnd.
2504 * Following 2 kinds of acks should not affect
2507 * 2) Acks with SACK but without any new SACK
2508 * information in them. These could result from
2509 * any anomaly in the network like a switch
2510 * duplicating packets or a possible DoS attack.
2512 if (th->th_ack != tp->snd_una ||
2513 ((tp->t_flags & TF_SACK_PERMIT) &&
2516 else if (!tcp_timer_active(tp, TT_REXMT))
2518 else if (++tp->t_dupacks > tcprexmtthresh ||
2519 IN_FASTRECOVERY(tp->t_flags)) {
2520 cc_ack_received(tp, th, nsegs,
2522 if ((tp->t_flags & TF_SACK_PERMIT) &&
2523 IN_FASTRECOVERY(tp->t_flags)) {
2527 * Compute the amount of data in flight first.
2528 * We can inject new data into the pipe iff
2529 * we have less than 1/2 the original window's
2530 * worth of data in flight.
2532 if (V_tcp_do_rfc6675_pipe)
2533 awnd = tcp_compute_pipe(tp);
2535 awnd = (tp->snd_nxt - tp->snd_fack) +
2536 tp->sackhint.sack_bytes_rexmit;
2538 if (awnd < tp->snd_ssthresh) {
2539 tp->snd_cwnd += maxseg;
2540 if (tp->snd_cwnd > tp->snd_ssthresh)
2541 tp->snd_cwnd = tp->snd_ssthresh;
2544 tp->snd_cwnd += maxseg;
2545 (void) tp->t_fb->tfb_tcp_output(tp);
2547 } else if (tp->t_dupacks == tcprexmtthresh) {
2548 tcp_seq onxt = tp->snd_nxt;
2551 * If we're doing sack, check to
2552 * see if we're already in sack
2553 * recovery. If we're not doing sack,
2554 * check to see if we're in newreno
2557 if (tp->t_flags & TF_SACK_PERMIT) {
2558 if (IN_FASTRECOVERY(tp->t_flags)) {
2563 if (SEQ_LEQ(th->th_ack,
2569 /* Congestion signal before ack. */
2570 cc_cong_signal(tp, th, CC_NDUPACK);
2571 cc_ack_received(tp, th, nsegs,
2573 tcp_timer_activate(tp, TT_REXMT, 0);
2575 if (tp->t_flags & TF_SACK_PERMIT) {
2577 tcps_sack_recovery_episode);
2578 tp->snd_recover = tp->snd_nxt;
2579 tp->snd_cwnd = maxseg;
2580 (void) tp->t_fb->tfb_tcp_output(tp);
2583 tp->snd_nxt = th->th_ack;
2584 tp->snd_cwnd = maxseg;
2585 (void) tp->t_fb->tfb_tcp_output(tp);
2586 KASSERT(tp->snd_limited <= 2,
2587 ("%s: tp->snd_limited too big",
2589 tp->snd_cwnd = tp->snd_ssthresh +
2591 (tp->t_dupacks - tp->snd_limited);
2592 if (SEQ_GT(onxt, tp->snd_nxt))
2595 } else if (V_tcp_do_rfc3042) {
2597 * Process first and second duplicate
2598 * ACKs. Each indicates a segment
2599 * leaving the network, creating room
2600 * for more. Make sure we can send a
2601 * packet on reception of each duplicate
2602 * ACK by increasing snd_cwnd by one
2603 * segment. Restore the original
2604 * snd_cwnd after packet transmission.
2606 cc_ack_received(tp, th, nsegs,
2608 uint32_t oldcwnd = tp->snd_cwnd;
2609 tcp_seq oldsndmax = tp->snd_max;
2613 KASSERT(tp->t_dupacks == 1 ||
2615 ("%s: dupacks not 1 or 2",
2617 if (tp->t_dupacks == 1)
2618 tp->snd_limited = 0;
2620 (tp->snd_nxt - tp->snd_una) +
2621 (tp->t_dupacks - tp->snd_limited) *
2624 * Only call tcp_output when there
2625 * is new data available to be sent.
2626 * Otherwise we would send pure ACKs.
2628 SOCKBUF_LOCK(&so->so_snd);
2629 avail = sbavail(&so->so_snd) -
2630 (tp->snd_nxt - tp->snd_una);
2631 SOCKBUF_UNLOCK(&so->so_snd);
2633 (void) tp->t_fb->tfb_tcp_output(tp);
2634 sent = tp->snd_max - oldsndmax;
2635 if (sent > maxseg) {
2636 KASSERT((tp->t_dupacks == 2 &&
2637 tp->snd_limited == 0) ||
2638 (sent == maxseg + 1 &&
2639 tp->t_flags & TF_SENTFIN),
2640 ("%s: sent too much",
2642 tp->snd_limited = 2;
2643 } else if (sent > 0)
2645 tp->snd_cwnd = oldcwnd;
2652 * This ack is advancing the left edge, reset the
2657 * If this ack also has new SACK info, increment the
2658 * counter as per rfc6675.
2660 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2664 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2665 ("%s: th_ack <= snd_una", __func__));
2668 * If the congestion window was inflated to account
2669 * for the other side's cached packets, retract it.
2671 if (IN_FASTRECOVERY(tp->t_flags)) {
2672 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2673 if (tp->t_flags & TF_SACK_PERMIT)
2674 tcp_sack_partialack(tp, th);
2676 tcp_newreno_partial_ack(tp, th);
2678 cc_post_recovery(tp, th);
2681 * If we reach this point, ACK is not a duplicate,
2682 * i.e., it ACKs something we sent.
2684 if (tp->t_flags & TF_NEEDSYN) {
2686 * T/TCP: Connection was half-synchronized, and our
2687 * SYN has been ACK'd (so connection is now fully
2688 * synchronized). Go to non-starred state,
2689 * increment snd_una for ACK of SYN, and check if
2690 * we can do window scaling.
2692 tp->t_flags &= ~TF_NEEDSYN;
2694 /* Do window scaling? */
2695 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2696 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2697 tp->rcv_scale = tp->request_r_scale;
2698 /* Send window already scaled. */
2703 INP_WLOCK_ASSERT(tp->t_inpcb);
2706 * Adjust for the SYN bit in sequence space,
2707 * but don't account for it in cwnd calculations.
2708 * This is for the SYN_RECEIVED, non-simultaneous
2709 * SYN case. SYN_SENT and simultaneous SYN are
2710 * treated elsewhere.
2714 acked = BYTES_THIS_ACK(tp, th);
2715 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2716 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2717 tp->snd_una, th->th_ack, tp, m));
2718 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
2719 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2722 * If we just performed our first retransmit, and the ACK
2723 * arrives within our recovery window, then it was a mistake
2724 * to do the retransmit in the first place. Recover our
2725 * original cwnd and ssthresh, and proceed to transmit where
2728 if (tp->t_rxtshift == 1 &&
2729 tp->t_flags & TF_PREVVALID &&
2731 SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
2732 cc_cong_signal(tp, th, CC_RTO_ERR);
2735 * If we have a timestamp reply, update smoothed
2736 * round trip time. If no timestamp is present but
2737 * transmit timer is running and timed sequence
2738 * number was acked, update smoothed round trip time.
2739 * Since we now have an rtt measurement, cancel the
2740 * timer backoff (cf., Phil Karn's retransmit alg.).
2741 * Recompute the initial retransmit timer.
2743 * Some boxes send broken timestamp replies
2744 * during the SYN+ACK phase, ignore
2745 * timestamps of 0 or we could calculate a
2746 * huge RTT and blow up the retransmit timer.
2748 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2751 t = tcp_ts_getticks() - to.to_tsecr;
2752 if (!tp->t_rttlow || tp->t_rttlow > t)
2754 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2755 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2756 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2757 tp->t_rttlow = ticks - tp->t_rtttime;
2758 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2762 * If all outstanding data is acked, stop retransmit
2763 * timer and remember to restart (more output or persist).
2764 * If there is more data to be acked, restart retransmit
2765 * timer, using current (possibly backed-off) value.
2767 if (th->th_ack == tp->snd_max) {
2768 tcp_timer_activate(tp, TT_REXMT, 0);
2770 } else if (!tcp_timer_active(tp, TT_PERSIST))
2771 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2774 * If no data (only SYN) was ACK'd,
2775 * skip rest of ACK processing.
2781 * Let the congestion control algorithm update congestion
2782 * control related information. This typically means increasing
2783 * the congestion window.
2785 cc_ack_received(tp, th, nsegs, CC_ACK);
2787 SOCKBUF_LOCK(&so->so_snd);
2788 if (acked > sbavail(&so->so_snd)) {
2789 if (tp->snd_wnd >= sbavail(&so->so_snd))
2790 tp->snd_wnd -= sbavail(&so->so_snd);
2793 mfree = sbcut_locked(&so->so_snd,
2794 (int)sbavail(&so->so_snd));
2797 mfree = sbcut_locked(&so->so_snd, acked);
2798 if (tp->snd_wnd >= (uint32_t) acked)
2799 tp->snd_wnd -= acked;
2804 /* NB: sowwakeup_locked() does an implicit unlock. */
2805 sowwakeup_locked(so);
2807 /* Detect una wraparound. */
2808 if (!IN_RECOVERY(tp->t_flags) &&
2809 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2810 SEQ_LEQ(th->th_ack, tp->snd_recover))
2811 tp->snd_recover = th->th_ack - 1;
2812 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2813 if (IN_RECOVERY(tp->t_flags) &&
2814 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2815 EXIT_RECOVERY(tp->t_flags);
2817 tp->snd_una = th->th_ack;
2818 if (tp->t_flags & TF_SACK_PERMIT) {
2819 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2820 tp->snd_recover = tp->snd_una;
2822 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2823 tp->snd_nxt = tp->snd_una;
2825 switch (tp->t_state) {
2828 * In FIN_WAIT_1 STATE in addition to the processing
2829 * for the ESTABLISHED state if our FIN is now acknowledged
2830 * then enter FIN_WAIT_2.
2832 case TCPS_FIN_WAIT_1:
2833 if (ourfinisacked) {
2835 * If we can't receive any more
2836 * data, then closing user can proceed.
2837 * Starting the timer is contrary to the
2838 * specification, but if we don't get a FIN
2839 * we'll hang forever.
2842 * we should release the tp also, and use a
2845 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2846 soisdisconnected(so);
2847 tcp_timer_activate(tp, TT_2MSL,
2848 (tcp_fast_finwait2_recycle ?
2849 tcp_finwait2_timeout :
2852 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2857 * In CLOSING STATE in addition to the processing for
2858 * the ESTABLISHED state if the ACK acknowledges our FIN
2859 * then enter the TIME-WAIT state, otherwise ignore
2863 if (ourfinisacked) {
2871 * In LAST_ACK, we may still be waiting for data to drain
2872 * and/or to be acked, as well as for the ack of our FIN.
2873 * If our FIN is now acknowledged, delete the TCB,
2874 * enter the closed state and return.
2877 if (ourfinisacked) {
2886 INP_WLOCK_ASSERT(tp->t_inpcb);
2889 * Update window information.
2890 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2892 if ((thflags & TH_ACK) &&
2893 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2894 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2895 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2896 /* keep track of pure window updates */
2898 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2899 TCPSTAT_INC(tcps_rcvwinupd);
2900 tp->snd_wnd = tiwin;
2901 tp->snd_wl1 = th->th_seq;
2902 tp->snd_wl2 = th->th_ack;
2903 if (tp->snd_wnd > tp->max_sndwnd)
2904 tp->max_sndwnd = tp->snd_wnd;
2909 * Process segments with URG.
2911 if ((thflags & TH_URG) && th->th_urp &&
2912 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2914 * This is a kludge, but if we receive and accept
2915 * random urgent pointers, we'll crash in
2916 * soreceive. It's hard to imagine someone
2917 * actually wanting to send this much urgent data.
2919 SOCKBUF_LOCK(&so->so_rcv);
2920 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2921 th->th_urp = 0; /* XXX */
2922 thflags &= ~TH_URG; /* XXX */
2923 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2924 goto dodata; /* XXX */
2927 * If this segment advances the known urgent pointer,
2928 * then mark the data stream. This should not happen
2929 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2930 * a FIN has been received from the remote side.
2931 * In these states we ignore the URG.
2933 * According to RFC961 (Assigned Protocols),
2934 * the urgent pointer points to the last octet
2935 * of urgent data. We continue, however,
2936 * to consider it to indicate the first octet
2937 * of data past the urgent section as the original
2938 * spec states (in one of two places).
2940 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2941 tp->rcv_up = th->th_seq + th->th_urp;
2942 so->so_oobmark = sbavail(&so->so_rcv) +
2943 (tp->rcv_up - tp->rcv_nxt) - 1;
2944 if (so->so_oobmark == 0)
2945 so->so_rcv.sb_state |= SBS_RCVATMARK;
2947 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2949 SOCKBUF_UNLOCK(&so->so_rcv);
2951 * Remove out of band data so doesn't get presented to user.
2952 * This can happen independent of advancing the URG pointer,
2953 * but if two URG's are pending at once, some out-of-band
2954 * data may creep in... ick.
2956 if (th->th_urp <= (uint32_t)tlen &&
2957 !(so->so_options & SO_OOBINLINE)) {
2958 /* hdr drop is delayed */
2959 tcp_pulloutofband(so, th, m, drop_hdrlen);
2963 * If no out of band data is expected,
2964 * pull receive urgent pointer along
2965 * with the receive window.
2967 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2968 tp->rcv_up = tp->rcv_nxt;
2971 INP_WLOCK_ASSERT(tp->t_inpcb);
2974 * Process the segment text, merging it into the TCP sequencing queue,
2975 * and arranging for acknowledgment of receipt if necessary.
2976 * This process logically involves adjusting tp->rcv_wnd as data
2977 * is presented to the user (this happens in tcp_usrreq.c,
2978 * case PRU_RCVD). If a FIN has already been received on this
2979 * connection then we just ignore the text.
2981 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
2982 IS_FASTOPEN(tp->t_flags));
2983 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
2984 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2985 tcp_seq save_start = th->th_seq;
2986 tcp_seq save_rnxt = tp->rcv_nxt;
2987 int save_tlen = tlen;
2988 m_adj(m, drop_hdrlen); /* delayed header drop */
2990 * Insert segment which includes th into TCP reassembly queue
2991 * with control block tp. Set thflags to whether reassembly now
2992 * includes a segment with FIN. This handles the common case
2993 * inline (segment is the next to be received on an established
2994 * connection, and the queue is empty), avoiding linkage into
2995 * and removal from the queue and repetition of various
2997 * Set DELACK for segments received in order, but ack
2998 * immediately when segments are out of order (so
2999 * fast retransmit can work).
3001 if (th->th_seq == tp->rcv_nxt &&
3003 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3005 if (DELAY_ACK(tp, tlen) || tfo_syn)
3006 tp->t_flags |= TF_DELACK;
3008 tp->t_flags |= TF_ACKNOW;
3009 tp->rcv_nxt += tlen;
3010 thflags = th->th_flags & TH_FIN;
3011 TCPSTAT_INC(tcps_rcvpack);
3012 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3013 SOCKBUF_LOCK(&so->so_rcv);
3014 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3017 sbappendstream_locked(&so->so_rcv, m, 0);
3018 /* NB: sorwakeup_locked() does an implicit unlock. */
3019 sorwakeup_locked(so);
3022 * XXX: Due to the header drop above "th" is
3023 * theoretically invalid by now. Fortunately
3024 * m_adj() doesn't actually frees any mbufs
3025 * when trimming from the head.
3027 tcp_seq temp = save_start;
3028 thflags = tcp_reass(tp, th, &temp, &tlen, m);
3029 tp->t_flags |= TF_ACKNOW;
3031 if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) {
3032 if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3034 * DSACK actually handled in the fastpath
3037 tcp_update_sack_list(tp, save_start,
3038 save_start + save_tlen);
3039 } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3040 if ((tp->rcv_numsacks >= 1) &&
3041 (tp->sackblks[0].end == save_start)) {
3043 * Partial overlap, recorded at todrop
3046 tcp_update_sack_list(tp,
3047 tp->sackblks[0].start,
3048 tp->sackblks[0].end);
3050 tcp_update_dsack_list(tp, save_start,
3051 save_start + save_tlen);
3053 } else if (tlen >= save_tlen) {
3054 /* Update of sackblks. */
3055 tcp_update_dsack_list(tp, save_start,
3056 save_start + save_tlen);
3057 } else if (tlen > 0) {
3058 tcp_update_dsack_list(tp, save_start,
3064 * Note the amount of data that peer has sent into
3065 * our window, in order to estimate the sender's
3069 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3070 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3072 len = so->so_rcv.sb_hiwat;
3080 * If FIN is received ACK the FIN and let the user know
3081 * that the connection is closing.
3083 if (thflags & TH_FIN) {
3084 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3087 * If connection is half-synchronized
3088 * (ie NEEDSYN flag on) then delay ACK,
3089 * so it may be piggybacked when SYN is sent.
3090 * Otherwise, since we received a FIN then no
3091 * more input can be expected, send ACK now.
3093 if (tp->t_flags & TF_NEEDSYN)
3094 tp->t_flags |= TF_DELACK;
3096 tp->t_flags |= TF_ACKNOW;
3099 switch (tp->t_state) {
3102 * In SYN_RECEIVED and ESTABLISHED STATES
3103 * enter the CLOSE_WAIT state.
3105 case TCPS_SYN_RECEIVED:
3106 tp->t_starttime = ticks;
3108 case TCPS_ESTABLISHED:
3109 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3113 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3114 * enter the CLOSING state.
3116 case TCPS_FIN_WAIT_1:
3117 tcp_state_change(tp, TCPS_CLOSING);
3121 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3122 * starting the time-wait timer, turning off the other
3125 case TCPS_FIN_WAIT_2:
3131 if (so->so_options & SO_DEBUG)
3132 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3135 TCP_PROBE3(debug__input, tp, th, m);
3138 * Return any desired output.
3140 if (needoutput || (tp->t_flags & TF_ACKNOW))
3141 (void) tp->t_fb->tfb_tcp_output(tp);
3144 INP_WLOCK_ASSERT(tp->t_inpcb);
3146 if (tp->t_flags & TF_DELACK) {
3147 tp->t_flags &= ~TF_DELACK;
3148 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3150 INP_WUNLOCK(tp->t_inpcb);
3155 * Generate an ACK dropping incoming segment if it occupies
3156 * sequence space, where the ACK reflects our state.
3158 * We can now skip the test for the RST flag since all
3159 * paths to this code happen after packets containing
3160 * RST have been dropped.
3162 * In the SYN-RECEIVED state, don't send an ACK unless the
3163 * segment we received passes the SYN-RECEIVED ACK test.
3164 * If it fails send a RST. This breaks the loop in the
3165 * "LAND" DoS attack, and also prevents an ACK storm
3166 * between two listening ports that have been sent forged
3167 * SYN segments, each with the source address of the other.
3169 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3170 (SEQ_GT(tp->snd_una, th->th_ack) ||
3171 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3172 rstreason = BANDLIM_RST_OPENPORT;
3176 if (so->so_options & SO_DEBUG)
3177 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3180 TCP_PROBE3(debug__input, tp, th, m);
3181 tp->t_flags |= TF_ACKNOW;
3182 (void) tp->t_fb->tfb_tcp_output(tp);
3183 INP_WUNLOCK(tp->t_inpcb);
3189 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3190 INP_WUNLOCK(tp->t_inpcb);
3192 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3197 * Drop space held by incoming segment and return.
3200 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3201 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3204 TCP_PROBE3(debug__input, tp, th, m);
3206 INP_WUNLOCK(tp->t_inpcb);
3211 * Issue RST and make ACK acceptable to originator of segment.
3212 * The mbuf must still include the original packet header.
3216 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3217 int tlen, int rstreason)
3223 struct ip6_hdr *ip6;
3227 INP_WLOCK_ASSERT(tp->t_inpcb);
3230 /* Don't bother if destination was broadcast/multicast. */
3231 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3234 if (mtod(m, struct ip *)->ip_v == 6) {
3235 ip6 = mtod(m, struct ip6_hdr *);
3236 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3237 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3239 /* IPv6 anycast check is done at tcp6_input() */
3242 #if defined(INET) && defined(INET6)
3247 ip = mtod(m, struct ip *);
3248 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3249 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3250 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3251 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3256 /* Perform bandwidth limiting. */
3257 if (badport_bandlim(rstreason) < 0)
3260 /* tcp_respond consumes the mbuf chain. */
3261 if (th->th_flags & TH_ACK) {
3262 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3263 th->th_ack, TH_RST);
3265 if (th->th_flags & TH_SYN)
3267 if (th->th_flags & TH_FIN)
3269 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3270 (tcp_seq)0, TH_RST|TH_ACK);
3278 * Parse TCP options and place in tcpopt.
3281 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3286 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3288 if (opt == TCPOPT_EOL)
3290 if (opt == TCPOPT_NOP)
3296 if (optlen < 2 || optlen > cnt)
3301 if (optlen != TCPOLEN_MAXSEG)
3303 if (!(flags & TO_SYN))
3305 to->to_flags |= TOF_MSS;
3306 bcopy((char *)cp + 2,
3307 (char *)&to->to_mss, sizeof(to->to_mss));
3308 to->to_mss = ntohs(to->to_mss);
3311 if (optlen != TCPOLEN_WINDOW)
3313 if (!(flags & TO_SYN))
3315 to->to_flags |= TOF_SCALE;
3316 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3318 case TCPOPT_TIMESTAMP:
3319 if (optlen != TCPOLEN_TIMESTAMP)
3321 to->to_flags |= TOF_TS;
3322 bcopy((char *)cp + 2,
3323 (char *)&to->to_tsval, sizeof(to->to_tsval));
3324 to->to_tsval = ntohl(to->to_tsval);
3325 bcopy((char *)cp + 6,
3326 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3327 to->to_tsecr = ntohl(to->to_tsecr);
3329 case TCPOPT_SIGNATURE:
3331 * In order to reply to a host which has set the
3332 * TCP_SIGNATURE option in its initial SYN, we have
3333 * to record the fact that the option was observed
3334 * here for the syncache code to perform the correct
3337 if (optlen != TCPOLEN_SIGNATURE)
3339 to->to_flags |= TOF_SIGNATURE;
3340 to->to_signature = cp + 2;
3342 case TCPOPT_SACK_PERMITTED:
3343 if (optlen != TCPOLEN_SACK_PERMITTED)
3345 if (!(flags & TO_SYN))
3349 to->to_flags |= TOF_SACKPERM;
3352 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3356 to->to_flags |= TOF_SACK;
3357 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3358 to->to_sacks = cp + 2;
3359 TCPSTAT_INC(tcps_sack_rcv_blocks);
3361 case TCPOPT_FAST_OPEN:
3363 * Cookie length validation is performed by the
3364 * server side cookie checking code or the client
3365 * side cookie cache update code.
3367 if (!(flags & TO_SYN))
3369 if (!V_tcp_fastopen_client_enable &&
3370 !V_tcp_fastopen_server_enable)
3372 to->to_flags |= TOF_FASTOPEN;
3373 to->to_tfo_len = optlen - 2;
3374 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3383 * Pull out of band byte out of a segment so
3384 * it doesn't appear in the user's data queue.
3385 * It is still reflected in the segment length for
3386 * sequencing purposes.
3389 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3392 int cnt = off + th->th_urp - 1;
3395 if (m->m_len > cnt) {
3396 char *cp = mtod(m, caddr_t) + cnt;
3397 struct tcpcb *tp = sototcpcb(so);
3399 INP_WLOCK_ASSERT(tp->t_inpcb);
3402 tp->t_oobflags |= TCPOOB_HAVEDATA;
3403 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3405 if (m->m_flags & M_PKTHDR)
3414 panic("tcp_pulloutofband");
3418 * Collect new round-trip time estimate
3419 * and update averages and current timeout.
3422 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3426 INP_WLOCK_ASSERT(tp->t_inpcb);
3428 TCPSTAT_INC(tcps_rttupdated);
3431 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT,
3432 imax(0, rtt * 1000 / hz));
3434 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3436 * srtt is stored as fixed point with 5 bits after the
3437 * binary point (i.e., scaled by 8). The following magic
3438 * is equivalent to the smoothing algorithm in rfc793 with
3439 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3440 * point). Adjust rtt to origin 0.
3442 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3443 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3445 if ((tp->t_srtt += delta) <= 0)
3449 * We accumulate a smoothed rtt variance (actually, a
3450 * smoothed mean difference), then set the retransmit
3451 * timer to smoothed rtt + 4 times the smoothed variance.
3452 * rttvar is stored as fixed point with 4 bits after the
3453 * binary point (scaled by 16). The following is
3454 * equivalent to rfc793 smoothing with an alpha of .75
3455 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3456 * rfc793's wired-in beta.
3460 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3461 if ((tp->t_rttvar += delta) <= 0)
3463 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3464 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3467 * No rtt measurement yet - use the unsmoothed rtt.
3468 * Set the variance to half the rtt (so our first
3469 * retransmit happens at 3*rtt).
3471 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3472 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3473 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3479 * the retransmit should happen at rtt + 4 * rttvar.
3480 * Because of the way we do the smoothing, srtt and rttvar
3481 * will each average +1/2 tick of bias. When we compute
3482 * the retransmit timer, we want 1/2 tick of rounding and
3483 * 1 extra tick because of +-1/2 tick uncertainty in the
3484 * firing of the timer. The bias will give us exactly the
3485 * 1.5 tick we need. But, because the bias is
3486 * statistical, we have to test that we don't drop below
3487 * the minimum feasible timer (which is 2 ticks).
3489 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3490 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3493 * We received an ack for a packet that wasn't retransmitted;
3494 * it is probably safe to discard any error indications we've
3495 * received recently. This isn't quite right, but close enough
3496 * for now (a route might have failed after we sent a segment,
3497 * and the return path might not be symmetrical).
3499 tp->t_softerror = 0;
3503 * Determine a reasonable value for maxseg size.
3504 * If the route is known, check route for mtu.
3505 * If none, use an mss that can be handled on the outgoing interface
3506 * without forcing IP to fragment. If no route is found, route has no mtu,
3507 * or the destination isn't local, use a default, hopefully conservative
3508 * size (usually 512 or the default IP max size, but no more than the mtu
3509 * of the interface), as we can't discover anything about intervening
3510 * gateways or networks. We also initialize the congestion/slow start
3511 * window to be a single segment if the destination isn't local.
3512 * While looking at the routing entry, we also initialize other path-dependent
3513 * parameters from pre-set or cached values in the routing entry.
3515 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3516 * IP options, e.g. IPSEC data, since length of this data may vary, and
3517 * thus it is calculated for every segment separately in tcp_output().
3519 * NOTE that this routine is only called when we process an incoming
3520 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3521 * settings are handled in tcp_mssopt().
3524 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3525 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3528 uint32_t maxmtu = 0;
3529 struct inpcb *inp = tp->t_inpcb;
3530 struct hc_metrics_lite metrics;
3532 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3533 size_t min_protoh = isipv6 ?
3534 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3535 sizeof (struct tcpiphdr);
3537 const size_t min_protoh = sizeof(struct tcpiphdr);
3540 INP_WLOCK_ASSERT(tp->t_inpcb);
3542 if (mtuoffer != -1) {
3543 KASSERT(offer == -1, ("%s: conflict", __func__));
3544 offer = mtuoffer - min_protoh;
3550 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3551 tp->t_maxseg = V_tcp_v6mssdflt;
3554 #if defined(INET) && defined(INET6)
3559 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3560 tp->t_maxseg = V_tcp_mssdflt;
3565 * No route to sender, stay with default mss and return.
3569 * In case we return early we need to initialize metrics
3570 * to a defined state as tcp_hc_get() would do for us
3571 * if there was no cache hit.
3573 if (metricptr != NULL)
3574 bzero(metricptr, sizeof(struct hc_metrics_lite));
3578 /* What have we got? */
3582 * Offer == 0 means that there was no MSS on the SYN
3583 * segment, in this case we use tcp_mssdflt as
3584 * already assigned to t_maxseg above.
3586 offer = tp->t_maxseg;
3591 * Offer == -1 means that we didn't receive SYN yet.
3597 * Prevent DoS attack with too small MSS. Round up
3598 * to at least minmss.
3600 offer = max(offer, V_tcp_minmss);
3604 * rmx information is now retrieved from tcp_hostcache.
3606 tcp_hc_get(&inp->inp_inc, &metrics);
3607 if (metricptr != NULL)
3608 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3611 * If there's a discovered mtu in tcp hostcache, use it.
3612 * Else, use the link mtu.
3614 if (metrics.rmx_mtu)
3615 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3619 mss = maxmtu - min_protoh;
3620 if (!V_path_mtu_discovery &&
3621 !in6_localaddr(&inp->in6p_faddr))
3622 mss = min(mss, V_tcp_v6mssdflt);
3625 #if defined(INET) && defined(INET6)
3630 mss = maxmtu - min_protoh;
3631 if (!V_path_mtu_discovery &&
3632 !in_localaddr(inp->inp_faddr))
3633 mss = min(mss, V_tcp_mssdflt);
3637 * XXX - The above conditional (mss = maxmtu - min_protoh)
3638 * probably violates the TCP spec.
3639 * The problem is that, since we don't know the
3640 * other end's MSS, we are supposed to use a conservative
3641 * default. But, if we do that, then MTU discovery will
3642 * never actually take place, because the conservative
3643 * default is much less than the MTUs typically seen
3644 * on the Internet today. For the moment, we'll sweep
3645 * this under the carpet.
3647 * The conservative default might not actually be a problem
3648 * if the only case this occurs is when sending an initial
3649 * SYN with options and data to a host we've never talked
3650 * to before. Then, they will reply with an MSS value which
3651 * will get recorded and the new parameters should get
3652 * recomputed. For Further Study.
3655 mss = min(mss, offer);
3658 * Sanity check: make sure that maxseg will be large
3659 * enough to allow some data on segments even if the
3660 * all the option space is used (40bytes). Otherwise
3661 * funny things may happen in tcp_output.
3663 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3671 tcp_mss(struct tcpcb *tp, int offer)
3677 struct hc_metrics_lite metrics;
3678 struct tcp_ifcap cap;
3680 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3682 bzero(&cap, sizeof(cap));
3683 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3689 * If there's a pipesize, change the socket buffer to that size,
3690 * don't change if sb_hiwat is different than default (then it
3691 * has been changed on purpose with setsockopt).
3692 * Make the socket buffers an integral number of mss units;
3693 * if the mss is larger than the socket buffer, decrease the mss.
3695 so = inp->inp_socket;
3696 SOCKBUF_LOCK(&so->so_snd);
3697 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3698 bufsize = metrics.rmx_sendpipe;
3700 bufsize = so->so_snd.sb_hiwat;
3704 bufsize = roundup(bufsize, mss);
3705 if (bufsize > sb_max)
3707 if (bufsize > so->so_snd.sb_hiwat)
3708 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3710 SOCKBUF_UNLOCK(&so->so_snd);
3712 * Sanity check: make sure that maxseg will be large
3713 * enough to allow some data on segments even if the
3714 * all the option space is used (40bytes). Otherwise
3715 * funny things may happen in tcp_output.
3717 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3719 tp->t_maxseg = max(mss, 64);
3721 SOCKBUF_LOCK(&so->so_rcv);
3722 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3723 bufsize = metrics.rmx_recvpipe;
3725 bufsize = so->so_rcv.sb_hiwat;
3726 if (bufsize > mss) {
3727 bufsize = roundup(bufsize, mss);
3728 if (bufsize > sb_max)
3730 if (bufsize > so->so_rcv.sb_hiwat)
3731 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3733 SOCKBUF_UNLOCK(&so->so_rcv);
3735 /* Check the interface for TSO capabilities. */
3736 if (cap.ifcap & CSUM_TSO) {
3737 tp->t_flags |= TF_TSO;
3738 tp->t_tsomax = cap.tsomax;
3739 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3740 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3745 * Determine the MSS option to send on an outgoing SYN.
3748 tcp_mssopt(struct in_conninfo *inc)
3751 uint32_t thcmtu = 0;
3752 uint32_t maxmtu = 0;
3755 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3758 if (inc->inc_flags & INC_ISIPV6) {
3759 mss = V_tcp_v6mssdflt;
3760 maxmtu = tcp_maxmtu6(inc, NULL);
3761 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3764 #if defined(INET) && defined(INET6)
3769 mss = V_tcp_mssdflt;
3770 maxmtu = tcp_maxmtu(inc, NULL);
3771 min_protoh = sizeof(struct tcpiphdr);
3774 #if defined(INET6) || defined(INET)
3775 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3778 if (maxmtu && thcmtu)
3779 mss = min(maxmtu, thcmtu) - min_protoh;
3780 else if (maxmtu || thcmtu)
3781 mss = max(maxmtu, thcmtu) - min_protoh;
3788 * On a partial ack arrives, force the retransmission of the
3789 * next unacknowledged segment. Do not clear tp->t_dupacks.
3790 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3794 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3796 tcp_seq onxt = tp->snd_nxt;
3797 uint32_t ocwnd = tp->snd_cwnd;
3798 u_int maxseg = tcp_maxseg(tp);
3800 INP_WLOCK_ASSERT(tp->t_inpcb);
3802 tcp_timer_activate(tp, TT_REXMT, 0);
3804 tp->snd_nxt = th->th_ack;
3806 * Set snd_cwnd to one segment beyond acknowledged offset.
3807 * (tp->snd_una has not yet been updated when this function is called.)
3809 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3810 tp->t_flags |= TF_ACKNOW;
3811 (void) tp->t_fb->tfb_tcp_output(tp);
3812 tp->snd_cwnd = ocwnd;
3813 if (SEQ_GT(onxt, tp->snd_nxt))
3816 * Partial window deflation. Relies on fact that tp->snd_una
3819 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3820 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3823 tp->snd_cwnd += maxseg;
3827 tcp_compute_pipe(struct tcpcb *tp)
3829 return (tp->snd_max - tp->snd_una +
3830 tp->sackhint.sack_bytes_rexmit -
3831 tp->sackhint.sacked_bytes);
3835 tcp_compute_initwnd(uint32_t maxseg)
3838 * Calculate the Initial Window, also used as Restart Window
3840 * RFC5681 Section 3.1 specifies the default conservative values.
3841 * RFC3390 specifies slightly more aggressive values.
3842 * RFC6928 increases it to ten segments.
3843 * Support for user specified value for initial flight size.
3845 if (V_tcp_initcwnd_segments)
3846 return min(V_tcp_initcwnd_segments * maxseg,
3847 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
3848 else if (V_tcp_do_rfc3390)
3849 return min(4 * maxseg, max(2 * maxseg, 4380));
3851 /* Per RFC5681 Section 3.1 */
3853 return (2 * maxseg);
3854 else if (maxseg > 1095)
3855 return (3 * maxseg);
3857 return (4 * maxseg);