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 if ((to.to_flags & TOF_SCALE) &&
1615 (tp->t_flags & TF_REQ_SCALE)) {
1616 tp->t_flags |= TF_RCVD_SCALE;
1617 tp->snd_scale = to.to_wscale;
1620 * Initial send window. It will be updated with
1621 * the next incoming segment to the scaled value.
1623 tp->snd_wnd = th->th_win;
1624 if (to.to_flags & TOF_TS) {
1625 tp->t_flags |= TF_RCVD_TSTMP;
1626 tp->ts_recent = to.to_tsval;
1627 tp->ts_recent_age = tcp_ts_getticks();
1629 if (to.to_flags & TOF_MSS)
1630 tcp_mss(tp, to.to_mss);
1631 if ((tp->t_flags & TF_SACK_PERMIT) &&
1632 (to.to_flags & TOF_SACKPERM) == 0)
1633 tp->t_flags &= ~TF_SACK_PERMIT;
1634 if (IS_FASTOPEN(tp->t_flags)) {
1635 if (to.to_flags & TOF_FASTOPEN) {
1638 if (to.to_flags & TOF_MSS)
1641 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
1645 tcp_fastopen_update_cache(tp, mss,
1646 to.to_tfo_len, to.to_tfo_cookie);
1648 tcp_fastopen_disable_path(tp);
1653 * If timestamps were negotiated during SYN/ACK they should
1654 * appear on every segment during this session and vice versa.
1656 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1657 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1658 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1659 "no action\n", s, __func__);
1663 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1664 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1665 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1666 "no action\n", s, __func__);
1672 * Header prediction: check for the two common cases
1673 * of a uni-directional data xfer. If the packet has
1674 * no control flags, is in-sequence, the window didn't
1675 * change and we're not retransmitting, it's a
1676 * candidate. If the length is zero and the ack moved
1677 * forward, we're the sender side of the xfer. Just
1678 * free the data acked & wake any higher level process
1679 * that was blocked waiting for space. If the length
1680 * is non-zero and the ack didn't move, we're the
1681 * receiver side. If we're getting packets in-order
1682 * (the reassembly queue is empty), add the data to
1683 * the socket buffer and note that we need a delayed ack.
1684 * Make sure that the hidden state-flags are also off.
1685 * Since we check for TCPS_ESTABLISHED first, it can only
1688 if (tp->t_state == TCPS_ESTABLISHED &&
1689 th->th_seq == tp->rcv_nxt &&
1690 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1691 tp->snd_nxt == tp->snd_max &&
1692 tiwin && tiwin == tp->snd_wnd &&
1693 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1695 ((to.to_flags & TOF_TS) == 0 ||
1696 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1699 * If last ACK falls within this segment's sequence numbers,
1700 * record the timestamp.
1701 * NOTE that the test is modified according to the latest
1702 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1704 if ((to.to_flags & TOF_TS) != 0 &&
1705 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1706 tp->ts_recent_age = tcp_ts_getticks();
1707 tp->ts_recent = to.to_tsval;
1711 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1712 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1713 !IN_RECOVERY(tp->t_flags) &&
1714 (to.to_flags & TOF_SACK) == 0 &&
1715 TAILQ_EMPTY(&tp->snd_holes)) {
1717 * This is a pure ack for outstanding data.
1719 TCPSTAT_INC(tcps_predack);
1722 * "bad retransmit" recovery without timestamps.
1724 if ((to.to_flags & TOF_TS) == 0 &&
1725 tp->t_rxtshift == 1 &&
1726 tp->t_flags & TF_PREVVALID &&
1727 (int)(ticks - tp->t_badrxtwin) < 0) {
1728 cc_cong_signal(tp, th, CC_RTO_ERR);
1732 * Recalculate the transmit timer / rtt.
1734 * Some boxes send broken timestamp replies
1735 * during the SYN+ACK phase, ignore
1736 * timestamps of 0 or we could calculate a
1737 * huge RTT and blow up the retransmit timer.
1739 if ((to.to_flags & TOF_TS) != 0 &&
1743 t = tcp_ts_getticks() - to.to_tsecr;
1744 if (!tp->t_rttlow || tp->t_rttlow > t)
1747 TCP_TS_TO_TICKS(t) + 1);
1748 } else if (tp->t_rtttime &&
1749 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1750 if (!tp->t_rttlow ||
1751 tp->t_rttlow > ticks - tp->t_rtttime)
1752 tp->t_rttlow = ticks - tp->t_rtttime;
1754 ticks - tp->t_rtttime);
1756 acked = BYTES_THIS_ACK(tp, th);
1759 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1760 hhook_run_tcp_est_in(tp, th, &to);
1763 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
1764 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1765 sbdrop(&so->so_snd, acked);
1766 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1767 SEQ_LEQ(th->th_ack, tp->snd_recover))
1768 tp->snd_recover = th->th_ack - 1;
1771 * Let the congestion control algorithm update
1772 * congestion control related information. This
1773 * typically means increasing the congestion
1776 cc_ack_received(tp, th, nsegs, CC_ACK);
1778 tp->snd_una = th->th_ack;
1780 * Pull snd_wl2 up to prevent seq wrap relative
1783 tp->snd_wl2 = th->th_ack;
1788 * If all outstanding data are acked, stop
1789 * retransmit timer, otherwise restart timer
1790 * using current (possibly backed-off) value.
1791 * If process is waiting for space,
1792 * wakeup/selwakeup/signal. If data
1793 * are ready to send, let tcp_output
1794 * decide between more output or persist.
1797 if (so->so_options & SO_DEBUG)
1798 tcp_trace(TA_INPUT, ostate, tp,
1799 (void *)tcp_saveipgen,
1802 TCP_PROBE3(debug__input, tp, th, m);
1803 if (tp->snd_una == tp->snd_max)
1804 tcp_timer_activate(tp, TT_REXMT, 0);
1805 else if (!tcp_timer_active(tp, TT_PERSIST))
1806 tcp_timer_activate(tp, TT_REXMT,
1809 if (sbavail(&so->so_snd))
1810 (void) tp->t_fb->tfb_tcp_output(tp);
1813 } else if (th->th_ack == tp->snd_una &&
1814 tlen <= sbspace(&so->so_rcv)) {
1815 int newsize = 0; /* automatic sockbuf scaling */
1818 * This is a pure, in-sequence data packet with
1819 * nothing on the reassembly queue and we have enough
1820 * buffer space to take it.
1822 /* Clean receiver SACK report if present */
1823 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1824 tcp_clean_sackreport(tp);
1825 TCPSTAT_INC(tcps_preddat);
1826 tp->rcv_nxt += tlen;
1828 * Pull snd_wl1 up to prevent seq wrap relative to
1831 tp->snd_wl1 = th->th_seq;
1833 * Pull rcv_up up to prevent seq wrap relative to
1836 tp->rcv_up = tp->rcv_nxt;
1837 TCPSTAT_ADD(tcps_rcvpack, nsegs);
1838 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1840 if (so->so_options & SO_DEBUG)
1841 tcp_trace(TA_INPUT, ostate, tp,
1842 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1844 TCP_PROBE3(debug__input, tp, th, m);
1846 newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
1848 /* Add data to socket buffer. */
1849 SOCKBUF_LOCK(&so->so_rcv);
1850 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1854 * Set new socket buffer size.
1855 * Give up when limit is reached.
1858 if (!sbreserve_locked(&so->so_rcv,
1860 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1861 m_adj(m, drop_hdrlen); /* delayed header drop */
1862 sbappendstream_locked(&so->so_rcv, m, 0);
1864 /* NB: sorwakeup_locked() does an implicit unlock. */
1865 sorwakeup_locked(so);
1866 if (DELAY_ACK(tp, tlen)) {
1867 tp->t_flags |= TF_DELACK;
1869 tp->t_flags |= TF_ACKNOW;
1870 tp->t_fb->tfb_tcp_output(tp);
1877 * Calculate amount of space in receive window,
1878 * and then do TCP input processing.
1879 * Receive window is amount of space in rcv queue,
1880 * but not less than advertised window.
1882 win = sbspace(&so->so_rcv);
1885 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1887 switch (tp->t_state) {
1890 * If the state is SYN_RECEIVED:
1891 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1893 case TCPS_SYN_RECEIVED:
1894 if ((thflags & TH_ACK) &&
1895 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1896 SEQ_GT(th->th_ack, tp->snd_max))) {
1897 rstreason = BANDLIM_RST_OPENPORT;
1900 if (IS_FASTOPEN(tp->t_flags)) {
1902 * When a TFO connection is in SYN_RECEIVED, the
1903 * only valid packets are the initial SYN, a
1904 * retransmit/copy of the initial SYN (possibly with
1905 * a subset of the original data), a valid ACK, a
1908 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1909 rstreason = BANDLIM_RST_OPENPORT;
1911 } else if (thflags & TH_SYN) {
1912 /* non-initial SYN is ignored */
1913 if ((tcp_timer_active(tp, TT_DELACK) ||
1914 tcp_timer_active(tp, TT_REXMT)))
1916 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1923 * If the state is SYN_SENT:
1924 * if seg contains a RST with valid ACK (SEQ.ACK has already
1925 * been verified), then drop the connection.
1926 * if seg contains a RST without an ACK, drop the seg.
1927 * if seg does not contain SYN, then drop the seg.
1928 * Otherwise this is an acceptable SYN segment
1929 * initialize tp->rcv_nxt and tp->irs
1930 * if seg contains ack then advance tp->snd_una
1931 * if seg contains an ECE and ECN support is enabled, the stream
1933 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1934 * arrange for segment to be acked (eventually)
1935 * continue processing rest of data/controls, beginning with URG
1938 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1939 TCP_PROBE5(connect__refused, NULL, tp,
1941 tp = tcp_drop(tp, ECONNREFUSED);
1943 if (thflags & TH_RST)
1945 if (!(thflags & TH_SYN))
1948 tp->irs = th->th_seq;
1950 if (thflags & TH_ACK) {
1951 int tfo_partial_ack = 0;
1953 TCPSTAT_INC(tcps_connects);
1956 mac_socketpeer_set_from_mbuf(m, so);
1958 /* Do window scaling on this connection? */
1959 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1960 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1961 tp->rcv_scale = tp->request_r_scale;
1963 tp->rcv_adv += min(tp->rcv_wnd,
1964 TCP_MAXWIN << tp->rcv_scale);
1965 tp->snd_una++; /* SYN is acked */
1967 * If not all the data that was sent in the TFO SYN
1968 * has been acked, resend the remainder right away.
1970 if (IS_FASTOPEN(tp->t_flags) &&
1971 (tp->snd_una != tp->snd_max)) {
1972 tp->snd_nxt = th->th_ack;
1973 tfo_partial_ack = 1;
1976 * If there's data, delay ACK; if there's also a FIN
1977 * ACKNOW will be turned on later.
1979 if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial_ack)
1980 tcp_timer_activate(tp, TT_DELACK,
1983 tp->t_flags |= TF_ACKNOW;
1985 if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) &&
1986 (V_tcp_do_ecn == 1)) {
1987 tp->t_flags2 |= TF2_ECN_PERMIT;
1988 TCPSTAT_INC(tcps_ecn_shs);
1992 * Received <SYN,ACK> in SYN_SENT[*] state.
1994 * SYN_SENT --> ESTABLISHED
1995 * SYN_SENT* --> FIN_WAIT_1
1997 tp->t_starttime = ticks;
1998 if (tp->t_flags & TF_NEEDFIN) {
1999 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2000 tp->t_flags &= ~TF_NEEDFIN;
2003 tcp_state_change(tp, TCPS_ESTABLISHED);
2004 TCP_PROBE5(connect__established, NULL, tp,
2007 tcp_timer_activate(tp, TT_KEEP,
2012 * Received initial SYN in SYN-SENT[*] state =>
2013 * simultaneous open.
2014 * If it succeeds, connection is * half-synchronized.
2015 * Otherwise, do 3-way handshake:
2016 * SYN-SENT -> SYN-RECEIVED
2017 * SYN-SENT* -> SYN-RECEIVED*
2019 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2020 tcp_timer_activate(tp, TT_REXMT, 0);
2021 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2024 INP_WLOCK_ASSERT(tp->t_inpcb);
2027 * Advance th->th_seq to correspond to first data byte.
2028 * If data, trim to stay within window,
2029 * dropping FIN if necessary.
2032 if (tlen > tp->rcv_wnd) {
2033 todrop = tlen - tp->rcv_wnd;
2037 TCPSTAT_INC(tcps_rcvpackafterwin);
2038 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2040 tp->snd_wl1 = th->th_seq - 1;
2041 tp->rcv_up = th->th_seq;
2043 * Client side of transaction: already sent SYN and data.
2044 * If the remote host used T/TCP to validate the SYN,
2045 * our data will be ACK'd; if so, enter normal data segment
2046 * processing in the middle of step 5, ack processing.
2047 * Otherwise, goto step 6.
2049 if (thflags & TH_ACK)
2055 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2056 * do normal processing.
2058 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2062 break; /* continue normal processing */
2066 * States other than LISTEN or SYN_SENT.
2067 * First check the RST flag and sequence number since reset segments
2068 * are exempt from the timestamp and connection count tests. This
2069 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2070 * below which allowed reset segments in half the sequence space
2071 * to fall though and be processed (which gives forged reset
2072 * segments with a random sequence number a 50 percent chance of
2073 * killing a connection).
2074 * Then check timestamp, if present.
2075 * Then check the connection count, if present.
2076 * Then check that at least some bytes of segment are within
2077 * receive window. If segment begins before rcv_nxt,
2078 * drop leading data (and SYN); if nothing left, just ack.
2080 if (thflags & TH_RST) {
2082 * RFC5961 Section 3.2
2084 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2085 * - If RST is in window, we send challenge ACK.
2087 * Note: to take into account delayed ACKs, we should
2088 * test against last_ack_sent instead of rcv_nxt.
2089 * Note 2: we handle special case of closed window, not
2090 * covered by the RFC.
2092 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2093 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2094 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2096 KASSERT(tp->t_state != TCPS_SYN_SENT,
2097 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2100 if (V_tcp_insecure_rst ||
2101 tp->last_ack_sent == th->th_seq) {
2102 TCPSTAT_INC(tcps_drops);
2103 /* Drop the connection. */
2104 switch (tp->t_state) {
2105 case TCPS_SYN_RECEIVED:
2106 so->so_error = ECONNREFUSED;
2108 case TCPS_ESTABLISHED:
2109 case TCPS_FIN_WAIT_1:
2110 case TCPS_FIN_WAIT_2:
2111 case TCPS_CLOSE_WAIT:
2114 so->so_error = ECONNRESET;
2121 TCPSTAT_INC(tcps_badrst);
2122 /* Send challenge ACK. */
2123 tcp_respond(tp, mtod(m, void *), th, m,
2124 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2125 tp->last_ack_sent = tp->rcv_nxt;
2133 * RFC5961 Section 4.2
2134 * Send challenge ACK for any SYN in synchronized state.
2136 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2137 tp->t_state != TCPS_SYN_RECEIVED) {
2138 TCPSTAT_INC(tcps_badsyn);
2139 if (V_tcp_insecure_syn &&
2140 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2141 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2142 tp = tcp_drop(tp, ECONNRESET);
2143 rstreason = BANDLIM_UNLIMITED;
2145 /* Send challenge ACK. */
2146 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2147 tp->snd_nxt, TH_ACK);
2148 tp->last_ack_sent = tp->rcv_nxt;
2155 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2156 * and it's less than ts_recent, drop it.
2158 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2159 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2161 /* Check to see if ts_recent is over 24 days old. */
2162 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2164 * Invalidate ts_recent. If this segment updates
2165 * ts_recent, the age will be reset later and ts_recent
2166 * will get a valid value. If it does not, setting
2167 * ts_recent to zero will at least satisfy the
2168 * requirement that zero be placed in the timestamp
2169 * echo reply when ts_recent isn't valid. The
2170 * age isn't reset until we get a valid ts_recent
2171 * because we don't want out-of-order segments to be
2172 * dropped when ts_recent is old.
2176 TCPSTAT_INC(tcps_rcvduppack);
2177 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2178 TCPSTAT_INC(tcps_pawsdrop);
2186 * In the SYN-RECEIVED state, validate that the packet belongs to
2187 * this connection before trimming the data to fit the receive
2188 * window. Check the sequence number versus IRS since we know
2189 * the sequence numbers haven't wrapped. This is a partial fix
2190 * for the "LAND" DoS attack.
2192 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2193 rstreason = BANDLIM_RST_OPENPORT;
2197 todrop = tp->rcv_nxt - th->th_seq;
2199 if (thflags & TH_SYN) {
2209 * Following if statement from Stevens, vol. 2, p. 960.
2212 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2214 * Any valid FIN must be to the left of the window.
2215 * At this point the FIN must be a duplicate or out
2216 * of sequence; drop it.
2221 * Send an ACK to resynchronize and drop any data.
2222 * But keep on processing for RST or ACK.
2224 tp->t_flags |= TF_ACKNOW;
2226 TCPSTAT_INC(tcps_rcvduppack);
2227 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2229 TCPSTAT_INC(tcps_rcvpartduppack);
2230 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2233 * DSACK - add SACK block for dropped range
2235 if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
2236 tcp_update_sack_list(tp, th->th_seq,
2237 th->th_seq + todrop);
2239 * ACK now, as the next in-sequence segment
2240 * will clear the DSACK block again
2242 tp->t_flags |= TF_ACKNOW;
2244 drop_hdrlen += todrop; /* drop from the top afterwards */
2245 th->th_seq += todrop;
2247 if (th->th_urp > todrop)
2248 th->th_urp -= todrop;
2256 * If new data are received on a connection after the
2257 * user processes are gone, then RST the other end.
2259 if ((so->so_state & SS_NOFDREF) &&
2260 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2261 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2262 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2263 "after socket was closed, "
2264 "sending RST and removing tcpcb\n",
2265 s, __func__, tcpstates[tp->t_state], tlen);
2269 TCPSTAT_INC(tcps_rcvafterclose);
2270 rstreason = BANDLIM_UNLIMITED;
2275 * If segment ends after window, drop trailing data
2276 * (and PUSH and FIN); if nothing left, just ACK.
2278 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2280 TCPSTAT_INC(tcps_rcvpackafterwin);
2281 if (todrop >= tlen) {
2282 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2284 * If window is closed can only take segments at
2285 * window edge, and have to drop data and PUSH from
2286 * incoming segments. Continue processing, but
2287 * remember to ack. Otherwise, drop segment
2290 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2291 tp->t_flags |= TF_ACKNOW;
2292 TCPSTAT_INC(tcps_rcvwinprobe);
2296 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2299 thflags &= ~(TH_PUSH|TH_FIN);
2303 * If last ACK falls within this segment's sequence numbers,
2304 * record its timestamp.
2306 * 1) That the test incorporates suggestions from the latest
2307 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2308 * 2) That updating only on newer timestamps interferes with
2309 * our earlier PAWS tests, so this check should be solely
2310 * predicated on the sequence space of this segment.
2311 * 3) That we modify the segment boundary check to be
2312 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2313 * instead of RFC1323's
2314 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2315 * This modified check allows us to overcome RFC1323's
2316 * limitations as described in Stevens TCP/IP Illustrated
2317 * Vol. 2 p.869. In such cases, we can still calculate the
2318 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2320 if ((to.to_flags & TOF_TS) != 0 &&
2321 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2322 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2323 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2324 tp->ts_recent_age = tcp_ts_getticks();
2325 tp->ts_recent = to.to_tsval;
2329 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2330 * flag is on (half-synchronized state), then queue data for
2331 * later processing; else drop segment and return.
2333 if ((thflags & TH_ACK) == 0) {
2334 if (tp->t_state == TCPS_SYN_RECEIVED ||
2335 (tp->t_flags & TF_NEEDSYN)) {
2336 if (tp->t_state == TCPS_SYN_RECEIVED &&
2337 IS_FASTOPEN(tp->t_flags)) {
2338 tp->snd_wnd = tiwin;
2342 } else if (tp->t_flags & TF_ACKNOW)
2351 switch (tp->t_state) {
2354 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2355 * ESTABLISHED state and continue processing.
2356 * The ACK was checked above.
2358 case TCPS_SYN_RECEIVED:
2360 TCPSTAT_INC(tcps_connects);
2362 /* Do window scaling? */
2363 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2364 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2365 tp->rcv_scale = tp->request_r_scale;
2367 tp->snd_wnd = tiwin;
2370 * SYN-RECEIVED -> ESTABLISHED
2371 * SYN-RECEIVED* -> FIN-WAIT-1
2373 tp->t_starttime = ticks;
2374 if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
2375 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2376 tp->t_tfo_pending = NULL;
2378 if (tp->t_flags & TF_NEEDFIN) {
2379 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2380 tp->t_flags &= ~TF_NEEDFIN;
2382 tcp_state_change(tp, TCPS_ESTABLISHED);
2383 TCP_PROBE5(accept__established, NULL, tp,
2386 * TFO connections call cc_conn_init() during SYN
2387 * processing. Calling it again here for such
2388 * connections is not harmless as it would undo the
2389 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2392 if (!IS_FASTOPEN(tp->t_flags))
2394 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2397 * Account for the ACK of our SYN prior to
2398 * regular ACK processing below, except for
2399 * simultaneous SYN, which is handled later.
2401 if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
2404 * If segment contains data or ACK, will call tcp_reass()
2405 * later; if not, do so now to pass queued data to user.
2407 if (tlen == 0 && (thflags & TH_FIN) == 0)
2408 (void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
2410 tp->snd_wl1 = th->th_seq - 1;
2414 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2415 * ACKs. If the ack is in the range
2416 * tp->snd_una < th->th_ack <= tp->snd_max
2417 * then advance tp->snd_una to th->th_ack and drop
2418 * data from the retransmission queue. If this ACK reflects
2419 * more up to date window information we update our window information.
2421 case TCPS_ESTABLISHED:
2422 case TCPS_FIN_WAIT_1:
2423 case TCPS_FIN_WAIT_2:
2424 case TCPS_CLOSE_WAIT:
2427 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2428 TCPSTAT_INC(tcps_rcvacktoomuch);
2431 if ((tp->t_flags & TF_SACK_PERMIT) &&
2432 ((to.to_flags & TOF_SACK) ||
2433 !TAILQ_EMPTY(&tp->snd_holes)))
2434 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2437 * Reset the value so that previous (valid) value
2438 * from the last ack with SACK doesn't get used.
2440 tp->sackhint.sacked_bytes = 0;
2443 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2444 hhook_run_tcp_est_in(tp, th, &to);
2447 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2450 maxseg = tcp_maxseg(tp);
2452 (tiwin == tp->snd_wnd ||
2453 (tp->t_flags & TF_SACK_PERMIT))) {
2455 * If this is the first time we've seen a
2456 * FIN from the remote, this is not a
2457 * duplicate and it needs to be processed
2458 * normally. This happens during a
2459 * simultaneous close.
2461 if ((thflags & TH_FIN) &&
2462 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2466 TCPSTAT_INC(tcps_rcvdupack);
2468 * If we have outstanding data (other than
2469 * a window probe), this is a completely
2470 * duplicate ack (ie, window info didn't
2471 * change and FIN isn't set),
2472 * the ack is the biggest we've
2473 * seen and we've seen exactly our rexmt
2474 * threshold of them, assume a packet
2475 * has been dropped and retransmit it.
2476 * Kludge snd_nxt & the congestion
2477 * window so we send only this one
2480 * We know we're losing at the current
2481 * window size so do congestion avoidance
2482 * (set ssthresh to half the current window
2483 * and pull our congestion window back to
2484 * the new ssthresh).
2486 * Dup acks mean that packets have left the
2487 * network (they're now cached at the receiver)
2488 * so bump cwnd by the amount in the receiver
2489 * to keep a constant cwnd packets in the
2492 * When using TCP ECN, notify the peer that
2493 * we reduced the cwnd.
2496 * Following 2 kinds of acks should not affect
2499 * 2) Acks with SACK but without any new SACK
2500 * information in them. These could result from
2501 * any anomaly in the network like a switch
2502 * duplicating packets or a possible DoS attack.
2504 if (th->th_ack != tp->snd_una ||
2505 ((tp->t_flags & TF_SACK_PERMIT) &&
2508 else if (!tcp_timer_active(tp, TT_REXMT))
2510 else if (++tp->t_dupacks > tcprexmtthresh ||
2511 IN_FASTRECOVERY(tp->t_flags)) {
2512 cc_ack_received(tp, th, nsegs,
2514 if ((tp->t_flags & TF_SACK_PERMIT) &&
2515 IN_FASTRECOVERY(tp->t_flags)) {
2519 * Compute the amount of data in flight first.
2520 * We can inject new data into the pipe iff
2521 * we have less than 1/2 the original window's
2522 * worth of data in flight.
2524 if (V_tcp_do_rfc6675_pipe)
2525 awnd = tcp_compute_pipe(tp);
2527 awnd = (tp->snd_nxt - tp->snd_fack) +
2528 tp->sackhint.sack_bytes_rexmit;
2530 if (awnd < tp->snd_ssthresh) {
2531 tp->snd_cwnd += maxseg;
2532 if (tp->snd_cwnd > tp->snd_ssthresh)
2533 tp->snd_cwnd = tp->snd_ssthresh;
2536 tp->snd_cwnd += maxseg;
2537 (void) tp->t_fb->tfb_tcp_output(tp);
2539 } else if (tp->t_dupacks == tcprexmtthresh) {
2540 tcp_seq onxt = tp->snd_nxt;
2543 * If we're doing sack, check to
2544 * see if we're already in sack
2545 * recovery. If we're not doing sack,
2546 * check to see if we're in newreno
2549 if (tp->t_flags & TF_SACK_PERMIT) {
2550 if (IN_FASTRECOVERY(tp->t_flags)) {
2555 if (SEQ_LEQ(th->th_ack,
2561 /* Congestion signal before ack. */
2562 cc_cong_signal(tp, th, CC_NDUPACK);
2563 cc_ack_received(tp, th, nsegs,
2565 tcp_timer_activate(tp, TT_REXMT, 0);
2567 if (tp->t_flags & TF_SACK_PERMIT) {
2569 tcps_sack_recovery_episode);
2570 tp->snd_recover = tp->snd_nxt;
2571 tp->snd_cwnd = maxseg;
2572 (void) tp->t_fb->tfb_tcp_output(tp);
2575 tp->snd_nxt = th->th_ack;
2576 tp->snd_cwnd = maxseg;
2577 (void) tp->t_fb->tfb_tcp_output(tp);
2578 KASSERT(tp->snd_limited <= 2,
2579 ("%s: tp->snd_limited too big",
2581 tp->snd_cwnd = tp->snd_ssthresh +
2583 (tp->t_dupacks - tp->snd_limited);
2584 if (SEQ_GT(onxt, tp->snd_nxt))
2587 } else if (V_tcp_do_rfc3042) {
2589 * Process first and second duplicate
2590 * ACKs. Each indicates a segment
2591 * leaving the network, creating room
2592 * for more. Make sure we can send a
2593 * packet on reception of each duplicate
2594 * ACK by increasing snd_cwnd by one
2595 * segment. Restore the original
2596 * snd_cwnd after packet transmission.
2598 cc_ack_received(tp, th, nsegs,
2600 uint32_t oldcwnd = tp->snd_cwnd;
2601 tcp_seq oldsndmax = tp->snd_max;
2605 KASSERT(tp->t_dupacks == 1 ||
2607 ("%s: dupacks not 1 or 2",
2609 if (tp->t_dupacks == 1)
2610 tp->snd_limited = 0;
2612 (tp->snd_nxt - tp->snd_una) +
2613 (tp->t_dupacks - tp->snd_limited) *
2616 * Only call tcp_output when there
2617 * is new data available to be sent.
2618 * Otherwise we would send pure ACKs.
2620 SOCKBUF_LOCK(&so->so_snd);
2621 avail = sbavail(&so->so_snd) -
2622 (tp->snd_nxt - tp->snd_una);
2623 SOCKBUF_UNLOCK(&so->so_snd);
2625 (void) tp->t_fb->tfb_tcp_output(tp);
2626 sent = tp->snd_max - oldsndmax;
2627 if (sent > maxseg) {
2628 KASSERT((tp->t_dupacks == 2 &&
2629 tp->snd_limited == 0) ||
2630 (sent == maxseg + 1 &&
2631 tp->t_flags & TF_SENTFIN),
2632 ("%s: sent too much",
2634 tp->snd_limited = 2;
2635 } else if (sent > 0)
2637 tp->snd_cwnd = oldcwnd;
2644 * This ack is advancing the left edge, reset the
2649 * If this ack also has new SACK info, increment the
2650 * counter as per rfc6675.
2652 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2656 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2657 ("%s: th_ack <= snd_una", __func__));
2660 * If the congestion window was inflated to account
2661 * for the other side's cached packets, retract it.
2663 if (IN_FASTRECOVERY(tp->t_flags)) {
2664 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2665 if (tp->t_flags & TF_SACK_PERMIT)
2666 tcp_sack_partialack(tp, th);
2668 tcp_newreno_partial_ack(tp, th);
2670 cc_post_recovery(tp, th);
2673 * If we reach this point, ACK is not a duplicate,
2674 * i.e., it ACKs something we sent.
2676 if (tp->t_flags & TF_NEEDSYN) {
2678 * T/TCP: Connection was half-synchronized, and our
2679 * SYN has been ACK'd (so connection is now fully
2680 * synchronized). Go to non-starred state,
2681 * increment snd_una for ACK of SYN, and check if
2682 * we can do window scaling.
2684 tp->t_flags &= ~TF_NEEDSYN;
2686 /* Do window scaling? */
2687 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2688 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2689 tp->rcv_scale = tp->request_r_scale;
2690 /* Send window already scaled. */
2695 INP_WLOCK_ASSERT(tp->t_inpcb);
2698 * Adjust for the SYN bit in sequence space,
2699 * but don't account for it in cwnd calculations.
2700 * This is for the SYN_RECEIVED, non-simultaneous
2701 * SYN case. SYN_SENT and simultaneous SYN are
2702 * treated elsewhere.
2706 acked = BYTES_THIS_ACK(tp, th);
2707 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2708 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2709 tp->snd_una, th->th_ack, tp, m));
2710 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
2711 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2714 * If we just performed our first retransmit, and the ACK
2715 * arrives within our recovery window, then it was a mistake
2716 * to do the retransmit in the first place. Recover our
2717 * original cwnd and ssthresh, and proceed to transmit where
2720 if (tp->t_rxtshift == 1 &&
2721 tp->t_flags & TF_PREVVALID &&
2723 SEQ_LT(to.to_tsecr, tp->t_badrxtwin))
2724 cc_cong_signal(tp, th, CC_RTO_ERR);
2727 * If we have a timestamp reply, update smoothed
2728 * round trip time. If no timestamp is present but
2729 * transmit timer is running and timed sequence
2730 * number was acked, update smoothed round trip time.
2731 * Since we now have an rtt measurement, cancel the
2732 * timer backoff (cf., Phil Karn's retransmit alg.).
2733 * Recompute the initial retransmit timer.
2735 * Some boxes send broken timestamp replies
2736 * during the SYN+ACK phase, ignore
2737 * timestamps of 0 or we could calculate a
2738 * huge RTT and blow up the retransmit timer.
2740 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2743 t = tcp_ts_getticks() - to.to_tsecr;
2744 if (!tp->t_rttlow || tp->t_rttlow > t)
2746 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2747 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2748 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2749 tp->t_rttlow = ticks - tp->t_rtttime;
2750 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2754 * If all outstanding data is acked, stop retransmit
2755 * timer and remember to restart (more output or persist).
2756 * If there is more data to be acked, restart retransmit
2757 * timer, using current (possibly backed-off) value.
2759 if (th->th_ack == tp->snd_max) {
2760 tcp_timer_activate(tp, TT_REXMT, 0);
2762 } else if (!tcp_timer_active(tp, TT_PERSIST))
2763 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2766 * If no data (only SYN) was ACK'd,
2767 * skip rest of ACK processing.
2773 * Let the congestion control algorithm update congestion
2774 * control related information. This typically means increasing
2775 * the congestion window.
2777 cc_ack_received(tp, th, nsegs, CC_ACK);
2779 SOCKBUF_LOCK(&so->so_snd);
2780 if (acked > sbavail(&so->so_snd)) {
2781 if (tp->snd_wnd >= sbavail(&so->so_snd))
2782 tp->snd_wnd -= sbavail(&so->so_snd);
2785 mfree = sbcut_locked(&so->so_snd,
2786 (int)sbavail(&so->so_snd));
2789 mfree = sbcut_locked(&so->so_snd, acked);
2790 if (tp->snd_wnd >= (uint32_t) acked)
2791 tp->snd_wnd -= acked;
2796 /* NB: sowwakeup_locked() does an implicit unlock. */
2797 sowwakeup_locked(so);
2799 /* Detect una wraparound. */
2800 if (!IN_RECOVERY(tp->t_flags) &&
2801 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2802 SEQ_LEQ(th->th_ack, tp->snd_recover))
2803 tp->snd_recover = th->th_ack - 1;
2804 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2805 if (IN_RECOVERY(tp->t_flags) &&
2806 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2807 EXIT_RECOVERY(tp->t_flags);
2809 tp->snd_una = th->th_ack;
2810 if (tp->t_flags & TF_SACK_PERMIT) {
2811 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2812 tp->snd_recover = tp->snd_una;
2814 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2815 tp->snd_nxt = tp->snd_una;
2817 switch (tp->t_state) {
2820 * In FIN_WAIT_1 STATE in addition to the processing
2821 * for the ESTABLISHED state if our FIN is now acknowledged
2822 * then enter FIN_WAIT_2.
2824 case TCPS_FIN_WAIT_1:
2825 if (ourfinisacked) {
2827 * If we can't receive any more
2828 * data, then closing user can proceed.
2829 * Starting the timer is contrary to the
2830 * specification, but if we don't get a FIN
2831 * we'll hang forever.
2834 * we should release the tp also, and use a
2837 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2838 soisdisconnected(so);
2839 tcp_timer_activate(tp, TT_2MSL,
2840 (tcp_fast_finwait2_recycle ?
2841 tcp_finwait2_timeout :
2844 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2849 * In CLOSING STATE in addition to the processing for
2850 * the ESTABLISHED state if the ACK acknowledges our FIN
2851 * then enter the TIME-WAIT state, otherwise ignore
2855 if (ourfinisacked) {
2863 * In LAST_ACK, we may still be waiting for data to drain
2864 * and/or to be acked, as well as for the ack of our FIN.
2865 * If our FIN is now acknowledged, delete the TCB,
2866 * enter the closed state and return.
2869 if (ourfinisacked) {
2878 INP_WLOCK_ASSERT(tp->t_inpcb);
2881 * Update window information.
2882 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2884 if ((thflags & TH_ACK) &&
2885 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2886 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2887 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2888 /* keep track of pure window updates */
2890 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2891 TCPSTAT_INC(tcps_rcvwinupd);
2892 tp->snd_wnd = tiwin;
2893 tp->snd_wl1 = th->th_seq;
2894 tp->snd_wl2 = th->th_ack;
2895 if (tp->snd_wnd > tp->max_sndwnd)
2896 tp->max_sndwnd = tp->snd_wnd;
2901 * Process segments with URG.
2903 if ((thflags & TH_URG) && th->th_urp &&
2904 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2906 * This is a kludge, but if we receive and accept
2907 * random urgent pointers, we'll crash in
2908 * soreceive. It's hard to imagine someone
2909 * actually wanting to send this much urgent data.
2911 SOCKBUF_LOCK(&so->so_rcv);
2912 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2913 th->th_urp = 0; /* XXX */
2914 thflags &= ~TH_URG; /* XXX */
2915 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2916 goto dodata; /* XXX */
2919 * If this segment advances the known urgent pointer,
2920 * then mark the data stream. This should not happen
2921 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2922 * a FIN has been received from the remote side.
2923 * In these states we ignore the URG.
2925 * According to RFC961 (Assigned Protocols),
2926 * the urgent pointer points to the last octet
2927 * of urgent data. We continue, however,
2928 * to consider it to indicate the first octet
2929 * of data past the urgent section as the original
2930 * spec states (in one of two places).
2932 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2933 tp->rcv_up = th->th_seq + th->th_urp;
2934 so->so_oobmark = sbavail(&so->so_rcv) +
2935 (tp->rcv_up - tp->rcv_nxt) - 1;
2936 if (so->so_oobmark == 0)
2937 so->so_rcv.sb_state |= SBS_RCVATMARK;
2939 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2941 SOCKBUF_UNLOCK(&so->so_rcv);
2943 * Remove out of band data so doesn't get presented to user.
2944 * This can happen independent of advancing the URG pointer,
2945 * but if two URG's are pending at once, some out-of-band
2946 * data may creep in... ick.
2948 if (th->th_urp <= (uint32_t)tlen &&
2949 !(so->so_options & SO_OOBINLINE)) {
2950 /* hdr drop is delayed */
2951 tcp_pulloutofband(so, th, m, drop_hdrlen);
2955 * If no out of band data is expected,
2956 * pull receive urgent pointer along
2957 * with the receive window.
2959 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2960 tp->rcv_up = tp->rcv_nxt;
2963 INP_WLOCK_ASSERT(tp->t_inpcb);
2966 * Process the segment text, merging it into the TCP sequencing queue,
2967 * and arranging for acknowledgment of receipt if necessary.
2968 * This process logically involves adjusting tp->rcv_wnd as data
2969 * is presented to the user (this happens in tcp_usrreq.c,
2970 * case PRU_RCVD). If a FIN has already been received on this
2971 * connection then we just ignore the text.
2973 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
2974 IS_FASTOPEN(tp->t_flags));
2975 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
2976 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2977 tcp_seq save_start = th->th_seq;
2978 tcp_seq save_rnxt = tp->rcv_nxt;
2979 int save_tlen = tlen;
2980 m_adj(m, drop_hdrlen); /* delayed header drop */
2982 * Insert segment which includes th into TCP reassembly queue
2983 * with control block tp. Set thflags to whether reassembly now
2984 * includes a segment with FIN. This handles the common case
2985 * inline (segment is the next to be received on an established
2986 * connection, and the queue is empty), avoiding linkage into
2987 * and removal from the queue and repetition of various
2989 * Set DELACK for segments received in order, but ack
2990 * immediately when segments are out of order (so
2991 * fast retransmit can work).
2993 if (th->th_seq == tp->rcv_nxt &&
2995 (TCPS_HAVEESTABLISHED(tp->t_state) ||
2997 if (DELAY_ACK(tp, tlen) || tfo_syn)
2998 tp->t_flags |= TF_DELACK;
3000 tp->t_flags |= TF_ACKNOW;
3001 tp->rcv_nxt += tlen;
3002 thflags = th->th_flags & TH_FIN;
3003 TCPSTAT_INC(tcps_rcvpack);
3004 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3005 SOCKBUF_LOCK(&so->so_rcv);
3006 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3009 sbappendstream_locked(&so->so_rcv, m, 0);
3010 /* NB: sorwakeup_locked() does an implicit unlock. */
3011 sorwakeup_locked(so);
3014 * XXX: Due to the header drop above "th" is
3015 * theoretically invalid by now. Fortunately
3016 * m_adj() doesn't actually frees any mbufs
3017 * when trimming from the head.
3019 tcp_seq temp = save_start;
3020 thflags = tcp_reass(tp, th, &temp, &tlen, m);
3021 tp->t_flags |= TF_ACKNOW;
3023 if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) {
3024 if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
3026 * DSACK actually handled in the fastpath
3029 tcp_update_sack_list(tp, save_start,
3030 save_start + save_tlen);
3031 } else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
3032 if ((tp->rcv_numsacks >= 1) &&
3033 (tp->sackblks[0].end == save_start)) {
3035 * Partial overlap, recorded at todrop
3038 tcp_update_sack_list(tp,
3039 tp->sackblks[0].start,
3040 tp->sackblks[0].end);
3042 tcp_update_dsack_list(tp, save_start,
3043 save_start + save_tlen);
3045 } else if (tlen >= save_tlen) {
3046 /* Update of sackblks. */
3047 tcp_update_dsack_list(tp, save_start,
3048 save_start + save_tlen);
3049 } else if (tlen > 0) {
3050 tcp_update_dsack_list(tp, save_start,
3056 * Note the amount of data that peer has sent into
3057 * our window, in order to estimate the sender's
3061 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3062 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3064 len = so->so_rcv.sb_hiwat;
3072 * If FIN is received ACK the FIN and let the user know
3073 * that the connection is closing.
3075 if (thflags & TH_FIN) {
3076 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3079 * If connection is half-synchronized
3080 * (ie NEEDSYN flag on) then delay ACK,
3081 * so it may be piggybacked when SYN is sent.
3082 * Otherwise, since we received a FIN then no
3083 * more input can be expected, send ACK now.
3085 if (tp->t_flags & TF_NEEDSYN)
3086 tp->t_flags |= TF_DELACK;
3088 tp->t_flags |= TF_ACKNOW;
3091 switch (tp->t_state) {
3094 * In SYN_RECEIVED and ESTABLISHED STATES
3095 * enter the CLOSE_WAIT state.
3097 case TCPS_SYN_RECEIVED:
3098 tp->t_starttime = ticks;
3100 case TCPS_ESTABLISHED:
3101 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3105 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3106 * enter the CLOSING state.
3108 case TCPS_FIN_WAIT_1:
3109 tcp_state_change(tp, TCPS_CLOSING);
3113 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3114 * starting the time-wait timer, turning off the other
3117 case TCPS_FIN_WAIT_2:
3123 if (so->so_options & SO_DEBUG)
3124 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3127 TCP_PROBE3(debug__input, tp, th, m);
3130 * Return any desired output.
3132 if (needoutput || (tp->t_flags & TF_ACKNOW))
3133 (void) tp->t_fb->tfb_tcp_output(tp);
3136 INP_WLOCK_ASSERT(tp->t_inpcb);
3138 if (tp->t_flags & TF_DELACK) {
3139 tp->t_flags &= ~TF_DELACK;
3140 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3142 INP_WUNLOCK(tp->t_inpcb);
3147 * Generate an ACK dropping incoming segment if it occupies
3148 * sequence space, where the ACK reflects our state.
3150 * We can now skip the test for the RST flag since all
3151 * paths to this code happen after packets containing
3152 * RST have been dropped.
3154 * In the SYN-RECEIVED state, don't send an ACK unless the
3155 * segment we received passes the SYN-RECEIVED ACK test.
3156 * If it fails send a RST. This breaks the loop in the
3157 * "LAND" DoS attack, and also prevents an ACK storm
3158 * between two listening ports that have been sent forged
3159 * SYN segments, each with the source address of the other.
3161 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3162 (SEQ_GT(tp->snd_una, th->th_ack) ||
3163 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3164 rstreason = BANDLIM_RST_OPENPORT;
3168 if (so->so_options & SO_DEBUG)
3169 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3172 TCP_PROBE3(debug__input, tp, th, m);
3173 tp->t_flags |= TF_ACKNOW;
3174 (void) tp->t_fb->tfb_tcp_output(tp);
3175 INP_WUNLOCK(tp->t_inpcb);
3181 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3182 INP_WUNLOCK(tp->t_inpcb);
3184 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3189 * Drop space held by incoming segment and return.
3192 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3193 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3196 TCP_PROBE3(debug__input, tp, th, m);
3198 INP_WUNLOCK(tp->t_inpcb);
3203 * Issue RST and make ACK acceptable to originator of segment.
3204 * The mbuf must still include the original packet header.
3208 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3209 int tlen, int rstreason)
3215 struct ip6_hdr *ip6;
3219 INP_WLOCK_ASSERT(tp->t_inpcb);
3222 /* Don't bother if destination was broadcast/multicast. */
3223 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3226 if (mtod(m, struct ip *)->ip_v == 6) {
3227 ip6 = mtod(m, struct ip6_hdr *);
3228 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3229 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3231 /* IPv6 anycast check is done at tcp6_input() */
3234 #if defined(INET) && defined(INET6)
3239 ip = mtod(m, struct ip *);
3240 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3241 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3242 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3243 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3248 /* Perform bandwidth limiting. */
3249 if (badport_bandlim(rstreason) < 0)
3252 /* tcp_respond consumes the mbuf chain. */
3253 if (th->th_flags & TH_ACK) {
3254 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3255 th->th_ack, TH_RST);
3257 if (th->th_flags & TH_SYN)
3259 if (th->th_flags & TH_FIN)
3261 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3262 (tcp_seq)0, TH_RST|TH_ACK);
3270 * Parse TCP options and place in tcpopt.
3273 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3278 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3280 if (opt == TCPOPT_EOL)
3282 if (opt == TCPOPT_NOP)
3288 if (optlen < 2 || optlen > cnt)
3293 if (optlen != TCPOLEN_MAXSEG)
3295 if (!(flags & TO_SYN))
3297 to->to_flags |= TOF_MSS;
3298 bcopy((char *)cp + 2,
3299 (char *)&to->to_mss, sizeof(to->to_mss));
3300 to->to_mss = ntohs(to->to_mss);
3303 if (optlen != TCPOLEN_WINDOW)
3305 if (!(flags & TO_SYN))
3307 to->to_flags |= TOF_SCALE;
3308 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3310 case TCPOPT_TIMESTAMP:
3311 if (optlen != TCPOLEN_TIMESTAMP)
3313 to->to_flags |= TOF_TS;
3314 bcopy((char *)cp + 2,
3315 (char *)&to->to_tsval, sizeof(to->to_tsval));
3316 to->to_tsval = ntohl(to->to_tsval);
3317 bcopy((char *)cp + 6,
3318 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3319 to->to_tsecr = ntohl(to->to_tsecr);
3321 case TCPOPT_SIGNATURE:
3323 * In order to reply to a host which has set the
3324 * TCP_SIGNATURE option in its initial SYN, we have
3325 * to record the fact that the option was observed
3326 * here for the syncache code to perform the correct
3329 if (optlen != TCPOLEN_SIGNATURE)
3331 to->to_flags |= TOF_SIGNATURE;
3332 to->to_signature = cp + 2;
3334 case TCPOPT_SACK_PERMITTED:
3335 if (optlen != TCPOLEN_SACK_PERMITTED)
3337 if (!(flags & TO_SYN))
3341 to->to_flags |= TOF_SACKPERM;
3344 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3348 to->to_flags |= TOF_SACK;
3349 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3350 to->to_sacks = cp + 2;
3351 TCPSTAT_INC(tcps_sack_rcv_blocks);
3353 case TCPOPT_FAST_OPEN:
3355 * Cookie length validation is performed by the
3356 * server side cookie checking code or the client
3357 * side cookie cache update code.
3359 if (!(flags & TO_SYN))
3361 if (!V_tcp_fastopen_client_enable &&
3362 !V_tcp_fastopen_server_enable)
3364 to->to_flags |= TOF_FASTOPEN;
3365 to->to_tfo_len = optlen - 2;
3366 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3375 * Pull out of band byte out of a segment so
3376 * it doesn't appear in the user's data queue.
3377 * It is still reflected in the segment length for
3378 * sequencing purposes.
3381 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3384 int cnt = off + th->th_urp - 1;
3387 if (m->m_len > cnt) {
3388 char *cp = mtod(m, caddr_t) + cnt;
3389 struct tcpcb *tp = sototcpcb(so);
3391 INP_WLOCK_ASSERT(tp->t_inpcb);
3394 tp->t_oobflags |= TCPOOB_HAVEDATA;
3395 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3397 if (m->m_flags & M_PKTHDR)
3406 panic("tcp_pulloutofband");
3410 * Collect new round-trip time estimate
3411 * and update averages and current timeout.
3414 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3418 INP_WLOCK_ASSERT(tp->t_inpcb);
3420 TCPSTAT_INC(tcps_rttupdated);
3423 stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT,
3424 imax(0, rtt * 1000 / hz));
3426 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3428 * srtt is stored as fixed point with 5 bits after the
3429 * binary point (i.e., scaled by 8). The following magic
3430 * is equivalent to the smoothing algorithm in rfc793 with
3431 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3432 * point). Adjust rtt to origin 0.
3434 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3435 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3437 if ((tp->t_srtt += delta) <= 0)
3441 * We accumulate a smoothed rtt variance (actually, a
3442 * smoothed mean difference), then set the retransmit
3443 * timer to smoothed rtt + 4 times the smoothed variance.
3444 * rttvar is stored as fixed point with 4 bits after the
3445 * binary point (scaled by 16). The following is
3446 * equivalent to rfc793 smoothing with an alpha of .75
3447 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3448 * rfc793's wired-in beta.
3452 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3453 if ((tp->t_rttvar += delta) <= 0)
3455 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3456 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3459 * No rtt measurement yet - use the unsmoothed rtt.
3460 * Set the variance to half the rtt (so our first
3461 * retransmit happens at 3*rtt).
3463 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3464 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3465 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3471 * the retransmit should happen at rtt + 4 * rttvar.
3472 * Because of the way we do the smoothing, srtt and rttvar
3473 * will each average +1/2 tick of bias. When we compute
3474 * the retransmit timer, we want 1/2 tick of rounding and
3475 * 1 extra tick because of +-1/2 tick uncertainty in the
3476 * firing of the timer. The bias will give us exactly the
3477 * 1.5 tick we need. But, because the bias is
3478 * statistical, we have to test that we don't drop below
3479 * the minimum feasible timer (which is 2 ticks).
3481 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3482 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3485 * We received an ack for a packet that wasn't retransmitted;
3486 * it is probably safe to discard any error indications we've
3487 * received recently. This isn't quite right, but close enough
3488 * for now (a route might have failed after we sent a segment,
3489 * and the return path might not be symmetrical).
3491 tp->t_softerror = 0;
3495 * Determine a reasonable value for maxseg size.
3496 * If the route is known, check route for mtu.
3497 * If none, use an mss that can be handled on the outgoing interface
3498 * without forcing IP to fragment. If no route is found, route has no mtu,
3499 * or the destination isn't local, use a default, hopefully conservative
3500 * size (usually 512 or the default IP max size, but no more than the mtu
3501 * of the interface), as we can't discover anything about intervening
3502 * gateways or networks. We also initialize the congestion/slow start
3503 * window to be a single segment if the destination isn't local.
3504 * While looking at the routing entry, we also initialize other path-dependent
3505 * parameters from pre-set or cached values in the routing entry.
3507 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3508 * IP options, e.g. IPSEC data, since length of this data may vary, and
3509 * thus it is calculated for every segment separately in tcp_output().
3511 * NOTE that this routine is only called when we process an incoming
3512 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3513 * settings are handled in tcp_mssopt().
3516 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3517 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3520 uint32_t maxmtu = 0;
3521 struct inpcb *inp = tp->t_inpcb;
3522 struct hc_metrics_lite metrics;
3524 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3525 size_t min_protoh = isipv6 ?
3526 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3527 sizeof (struct tcpiphdr);
3529 const size_t min_protoh = sizeof(struct tcpiphdr);
3532 INP_WLOCK_ASSERT(tp->t_inpcb);
3534 if (mtuoffer != -1) {
3535 KASSERT(offer == -1, ("%s: conflict", __func__));
3536 offer = mtuoffer - min_protoh;
3542 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3543 tp->t_maxseg = V_tcp_v6mssdflt;
3546 #if defined(INET) && defined(INET6)
3551 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3552 tp->t_maxseg = V_tcp_mssdflt;
3557 * No route to sender, stay with default mss and return.
3561 * In case we return early we need to initialize metrics
3562 * to a defined state as tcp_hc_get() would do for us
3563 * if there was no cache hit.
3565 if (metricptr != NULL)
3566 bzero(metricptr, sizeof(struct hc_metrics_lite));
3570 /* What have we got? */
3574 * Offer == 0 means that there was no MSS on the SYN
3575 * segment, in this case we use tcp_mssdflt as
3576 * already assigned to t_maxseg above.
3578 offer = tp->t_maxseg;
3583 * Offer == -1 means that we didn't receive SYN yet.
3589 * Prevent DoS attack with too small MSS. Round up
3590 * to at least minmss.
3592 offer = max(offer, V_tcp_minmss);
3596 * rmx information is now retrieved from tcp_hostcache.
3598 tcp_hc_get(&inp->inp_inc, &metrics);
3599 if (metricptr != NULL)
3600 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3603 * If there's a discovered mtu in tcp hostcache, use it.
3604 * Else, use the link mtu.
3606 if (metrics.rmx_mtu)
3607 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3611 mss = maxmtu - min_protoh;
3612 if (!V_path_mtu_discovery &&
3613 !in6_localaddr(&inp->in6p_faddr))
3614 mss = min(mss, V_tcp_v6mssdflt);
3617 #if defined(INET) && defined(INET6)
3622 mss = maxmtu - min_protoh;
3623 if (!V_path_mtu_discovery &&
3624 !in_localaddr(inp->inp_faddr))
3625 mss = min(mss, V_tcp_mssdflt);
3629 * XXX - The above conditional (mss = maxmtu - min_protoh)
3630 * probably violates the TCP spec.
3631 * The problem is that, since we don't know the
3632 * other end's MSS, we are supposed to use a conservative
3633 * default. But, if we do that, then MTU discovery will
3634 * never actually take place, because the conservative
3635 * default is much less than the MTUs typically seen
3636 * on the Internet today. For the moment, we'll sweep
3637 * this under the carpet.
3639 * The conservative default might not actually be a problem
3640 * if the only case this occurs is when sending an initial
3641 * SYN with options and data to a host we've never talked
3642 * to before. Then, they will reply with an MSS value which
3643 * will get recorded and the new parameters should get
3644 * recomputed. For Further Study.
3647 mss = min(mss, offer);
3650 * Sanity check: make sure that maxseg will be large
3651 * enough to allow some data on segments even if the
3652 * all the option space is used (40bytes). Otherwise
3653 * funny things may happen in tcp_output.
3655 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3663 tcp_mss(struct tcpcb *tp, int offer)
3669 struct hc_metrics_lite metrics;
3670 struct tcp_ifcap cap;
3672 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3674 bzero(&cap, sizeof(cap));
3675 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3681 * If there's a pipesize, change the socket buffer to that size,
3682 * don't change if sb_hiwat is different than default (then it
3683 * has been changed on purpose with setsockopt).
3684 * Make the socket buffers an integral number of mss units;
3685 * if the mss is larger than the socket buffer, decrease the mss.
3687 so = inp->inp_socket;
3688 SOCKBUF_LOCK(&so->so_snd);
3689 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3690 bufsize = metrics.rmx_sendpipe;
3692 bufsize = so->so_snd.sb_hiwat;
3696 bufsize = roundup(bufsize, mss);
3697 if (bufsize > sb_max)
3699 if (bufsize > so->so_snd.sb_hiwat)
3700 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3702 SOCKBUF_UNLOCK(&so->so_snd);
3704 * Sanity check: make sure that maxseg will be large
3705 * enough to allow some data on segments even if the
3706 * all the option space is used (40bytes). Otherwise
3707 * funny things may happen in tcp_output.
3709 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3711 tp->t_maxseg = max(mss, 64);
3713 SOCKBUF_LOCK(&so->so_rcv);
3714 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3715 bufsize = metrics.rmx_recvpipe;
3717 bufsize = so->so_rcv.sb_hiwat;
3718 if (bufsize > mss) {
3719 bufsize = roundup(bufsize, mss);
3720 if (bufsize > sb_max)
3722 if (bufsize > so->so_rcv.sb_hiwat)
3723 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3725 SOCKBUF_UNLOCK(&so->so_rcv);
3727 /* Check the interface for TSO capabilities. */
3728 if (cap.ifcap & CSUM_TSO) {
3729 tp->t_flags |= TF_TSO;
3730 tp->t_tsomax = cap.tsomax;
3731 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3732 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3737 * Determine the MSS option to send on an outgoing SYN.
3740 tcp_mssopt(struct in_conninfo *inc)
3743 uint32_t thcmtu = 0;
3744 uint32_t maxmtu = 0;
3747 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3750 if (inc->inc_flags & INC_ISIPV6) {
3751 mss = V_tcp_v6mssdflt;
3752 maxmtu = tcp_maxmtu6(inc, NULL);
3753 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3756 #if defined(INET) && defined(INET6)
3761 mss = V_tcp_mssdflt;
3762 maxmtu = tcp_maxmtu(inc, NULL);
3763 min_protoh = sizeof(struct tcpiphdr);
3766 #if defined(INET6) || defined(INET)
3767 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3770 if (maxmtu && thcmtu)
3771 mss = min(maxmtu, thcmtu) - min_protoh;
3772 else if (maxmtu || thcmtu)
3773 mss = max(maxmtu, thcmtu) - min_protoh;
3780 * On a partial ack arrives, force the retransmission of the
3781 * next unacknowledged segment. Do not clear tp->t_dupacks.
3782 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3786 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3788 tcp_seq onxt = tp->snd_nxt;
3789 uint32_t ocwnd = tp->snd_cwnd;
3790 u_int maxseg = tcp_maxseg(tp);
3792 INP_WLOCK_ASSERT(tp->t_inpcb);
3794 tcp_timer_activate(tp, TT_REXMT, 0);
3796 tp->snd_nxt = th->th_ack;
3798 * Set snd_cwnd to one segment beyond acknowledged offset.
3799 * (tp->snd_una has not yet been updated when this function is called.)
3801 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3802 tp->t_flags |= TF_ACKNOW;
3803 (void) tp->t_fb->tfb_tcp_output(tp);
3804 tp->snd_cwnd = ocwnd;
3805 if (SEQ_GT(onxt, tp->snd_nxt))
3808 * Partial window deflation. Relies on fact that tp->snd_una
3811 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3812 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3815 tp->snd_cwnd += maxseg;
3819 tcp_compute_pipe(struct tcpcb *tp)
3821 return (tp->snd_max - tp->snd_una +
3822 tp->sackhint.sack_bytes_rexmit -
3823 tp->sackhint.sacked_bytes);
3827 tcp_compute_initwnd(uint32_t maxseg)
3830 * Calculate the Initial Window, also used as Restart Window
3832 * RFC5681 Section 3.1 specifies the default conservative values.
3833 * RFC3390 specifies slightly more aggressive values.
3834 * RFC6928 increases it to ten segments.
3835 * Support for user specified value for initial flight size.
3837 if (V_tcp_initcwnd_segments)
3838 return min(V_tcp_initcwnd_segments * maxseg,
3839 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
3840 else if (V_tcp_do_rfc3390)
3841 return min(4 * maxseg, max(2 * maxseg, 4380));
3843 /* Per RFC5681 Section 3.1 */
3845 return (2 * maxseg);
3846 else if (maxseg > 1095)
3847 return (3 * maxseg);
3849 return (4 * maxseg);