2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2007-2008,2010
5 * Swinburne University of Technology, Melbourne, Australia.
6 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
7 * Copyright (c) 2010 The FreeBSD Foundation
8 * Copyright (c) 2010-2011 Juniper Networks, Inc.
11 * Portions of this software were developed at the Centre for Advanced Internet
12 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
13 * James Healy and David Hayes, made possible in part by a grant from the Cisco
14 * University Research Program Fund at Community Foundation Silicon Valley.
16 * Portions of this software were developed at the Centre for Advanced
17 * Internet Architectures, Swinburne University of Technology, Melbourne,
18 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
20 * Portions of this software were developed by Robert N. M. Watson under
21 * contract to Juniper Networks, Inc.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
54 #include "opt_inet6.h"
55 #include "opt_ipsec.h"
56 #include "opt_tcpdebug.h"
58 #include <sys/param.h>
59 #include <sys/kernel.h>
61 #include <sys/hhook.h>
63 #include <sys/malloc.h>
65 #include <sys/proc.h> /* for proc0 declaration */
66 #include <sys/protosw.h>
68 #include <sys/signalvar.h>
69 #include <sys/socket.h>
70 #include <sys/socketvar.h>
71 #include <sys/sysctl.h>
72 #include <sys/syslog.h>
73 #include <sys/systm.h>
75 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
80 #include <net/if_var.h>
81 #include <net/route.h>
84 #define TCPSTATES /* for logging */
86 #include <netinet/in.h>
87 #include <netinet/in_kdtrace.h>
88 #include <netinet/in_pcb.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
92 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
93 #include <netinet/ip_var.h>
94 #include <netinet/ip_options.h>
95 #include <netinet/ip6.h>
96 #include <netinet/icmp6.h>
97 #include <netinet6/in6_pcb.h>
98 #include <netinet6/in6_var.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
102 #include <netinet/tcp_fastopen.h>
104 #include <netinet/tcp.h>
105 #include <netinet/tcp_fsm.h>
106 #include <netinet/tcp_seq.h>
107 #include <netinet/tcp_timer.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet6/tcp6_var.h>
110 #include <netinet/tcpip.h>
111 #include <netinet/cc/cc.h>
113 #include <netinet/tcp_pcap.h>
115 #include <netinet/tcp_syncache.h>
117 #include <netinet/tcp_debug.h>
118 #endif /* TCPDEBUG */
120 #include <netinet/tcp_offload.h>
123 #include <netipsec/ipsec_support.h>
125 #include <machine/in_cksum.h>
127 #include <security/mac/mac_framework.h>
129 const int tcprexmtthresh = 3;
131 int tcp_log_in_vain = 0;
132 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
134 "Log all incoming TCP segments to closed ports");
136 VNET_DEFINE(int, blackhole) = 0;
137 #define V_blackhole VNET(blackhole)
138 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
139 &VNET_NAME(blackhole), 0,
140 "Do not send RST on segments to closed ports");
142 VNET_DEFINE(int, tcp_delack_enabled) = 1;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
144 &VNET_NAME(tcp_delack_enabled), 0,
145 "Delay ACK to try and piggyback it onto a data packet");
147 VNET_DEFINE(int, drop_synfin) = 0;
148 #define V_drop_synfin VNET(drop_synfin)
149 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
150 &VNET_NAME(drop_synfin), 0,
151 "Drop TCP packets with SYN+FIN set");
153 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
154 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
155 &VNET_NAME(tcp_do_rfc6675_pipe), 0,
156 "Use calculated pipe/in-flight bytes per RFC 6675");
158 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
159 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
160 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
161 &VNET_NAME(tcp_do_rfc3042), 0,
162 "Enable RFC 3042 (Limited Transmit)");
164 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
166 &VNET_NAME(tcp_do_rfc3390), 0,
167 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
169 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
171 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
172 "Slow-start flight size (initial congestion window) in number of segments");
174 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
175 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
176 &VNET_NAME(tcp_do_rfc3465), 0,
177 "Enable RFC 3465 (Appropriate Byte Counting)");
179 VNET_DEFINE(int, tcp_abc_l_var) = 2;
180 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
181 &VNET_NAME(tcp_abc_l_var), 2,
182 "Cap the max cwnd increment during slow-start to this number of segments");
184 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
186 VNET_DEFINE(int, tcp_do_ecn) = 2;
187 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
188 &VNET_NAME(tcp_do_ecn), 0,
191 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
192 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
193 &VNET_NAME(tcp_ecn_maxretries), 0,
194 "Max retries before giving up on ECN");
196 VNET_DEFINE(int, tcp_insecure_syn) = 0;
197 #define V_tcp_insecure_syn VNET(tcp_insecure_syn)
198 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
199 &VNET_NAME(tcp_insecure_syn), 0,
200 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
202 VNET_DEFINE(int, tcp_insecure_rst) = 0;
203 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
204 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
205 &VNET_NAME(tcp_insecure_rst), 0,
206 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
208 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
209 #define V_tcp_recvspace VNET(tcp_recvspace)
210 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
211 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
213 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
214 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
215 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
216 &VNET_NAME(tcp_do_autorcvbuf), 0,
217 "Enable automatic receive buffer sizing");
219 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
220 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
221 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
222 &VNET_NAME(tcp_autorcvbuf_inc), 0,
223 "Incrementor step size of automatic receive buffer");
225 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
226 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
227 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
228 &VNET_NAME(tcp_autorcvbuf_max), 0,
229 "Max size of automatic receive buffer");
231 VNET_DEFINE(struct inpcbhead, tcb);
232 #define tcb6 tcb /* for KAME src sync over BSD*'s */
233 VNET_DEFINE(struct inpcbinfo, tcbinfo);
236 * TCP statistics are stored in an array of counter(9)s, which size matches
237 * size of struct tcpstat. TCP running connection count is a regular array.
239 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
240 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
241 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
242 VNET_DEFINE(counter_u64_t, tcps_states[TCP_NSTATES]);
243 SYSCTL_COUNTER_U64_ARRAY(_net_inet_tcp, TCPCTL_STATES, states, CTLFLAG_RD |
244 CTLFLAG_VNET, &VNET_NAME(tcps_states)[0], TCP_NSTATES,
245 "TCP connection counts by TCP state");
248 tcp_vnet_init(const void *unused)
251 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
252 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
254 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
255 tcp_vnet_init, NULL);
259 tcp_vnet_uninit(const void *unused)
262 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
263 VNET_PCPUSTAT_FREE(tcpstat);
265 VNET_SYSUNINIT(tcp_vnet_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
266 tcp_vnet_uninit, NULL);
270 * Kernel module interface for updating tcpstat. The argument is an index
271 * into tcpstat treated as an array.
274 kmod_tcpstat_inc(int statnum)
277 counter_u64_add(VNET(tcpstat)[statnum], 1);
282 * Wrapper for the TCP established input helper hook.
285 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
287 struct tcp_hhook_data hhook_data;
289 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
294 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
301 * CC wrapper hook functions
304 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t nsegs,
307 INP_WLOCK_ASSERT(tp->t_inpcb);
309 tp->ccv->nsegs = nsegs;
310 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
311 if (tp->snd_cwnd <= tp->snd_wnd)
312 tp->ccv->flags |= CCF_CWND_LIMITED;
314 tp->ccv->flags &= ~CCF_CWND_LIMITED;
316 if (type == CC_ACK) {
317 if (tp->snd_cwnd > tp->snd_ssthresh) {
318 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
319 nsegs * V_tcp_abc_l_var * tcp_maxseg(tp));
320 if (tp->t_bytes_acked >= tp->snd_cwnd) {
321 tp->t_bytes_acked -= tp->snd_cwnd;
322 tp->ccv->flags |= CCF_ABC_SENTAWND;
325 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
326 tp->t_bytes_acked = 0;
330 if (CC_ALGO(tp)->ack_received != NULL) {
331 /* XXXLAS: Find a way to live without this */
332 tp->ccv->curack = th->th_ack;
333 CC_ALGO(tp)->ack_received(tp->ccv, type);
338 cc_conn_init(struct tcpcb *tp)
340 struct hc_metrics_lite metrics;
341 struct inpcb *inp = tp->t_inpcb;
345 INP_WLOCK_ASSERT(tp->t_inpcb);
347 tcp_hc_get(&inp->inp_inc, &metrics);
348 maxseg = tcp_maxseg(tp);
350 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
352 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
353 TCPSTAT_INC(tcps_usedrtt);
354 if (metrics.rmx_rttvar) {
355 tp->t_rttvar = metrics.rmx_rttvar;
356 TCPSTAT_INC(tcps_usedrttvar);
358 /* default variation is +- 1 rtt */
360 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
362 TCPT_RANGESET(tp->t_rxtcur,
363 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
364 tp->t_rttmin, TCPTV_REXMTMAX);
366 if (metrics.rmx_ssthresh) {
368 * There's some sort of gateway or interface
369 * buffer limit on the path. Use this to set
370 * the slow start threshold, but set the
371 * threshold to no less than 2*mss.
373 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
374 TCPSTAT_INC(tcps_usedssthresh);
378 * Set the initial slow-start flight size.
380 * RFC5681 Section 3.1 specifies the default conservative values.
381 * RFC3390 specifies slightly more aggressive values.
382 * RFC6928 increases it to ten segments.
383 * Support for user specified value for initial flight size.
385 * If a SYN or SYN/ACK was lost and retransmitted, we have to
386 * reduce the initial CWND to one segment as congestion is likely
387 * requiring us to be cautious.
389 if (tp->snd_cwnd == 1)
390 tp->snd_cwnd = maxseg; /* SYN(-ACK) lost */
391 else if (V_tcp_initcwnd_segments)
392 tp->snd_cwnd = min(V_tcp_initcwnd_segments * maxseg,
393 max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
394 else if (V_tcp_do_rfc3390)
395 tp->snd_cwnd = min(4 * maxseg, max(2 * maxseg, 4380));
397 /* Per RFC5681 Section 3.1 */
399 tp->snd_cwnd = 2 * maxseg;
400 else if (maxseg > 1095)
401 tp->snd_cwnd = 3 * maxseg;
403 tp->snd_cwnd = 4 * maxseg;
406 if (CC_ALGO(tp)->conn_init != NULL)
407 CC_ALGO(tp)->conn_init(tp->ccv);
411 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
415 INP_WLOCK_ASSERT(tp->t_inpcb);
419 if (!IN_FASTRECOVERY(tp->t_flags)) {
420 tp->snd_recover = tp->snd_max;
421 if (tp->t_flags & TF_ECN_PERMIT)
422 tp->t_flags |= TF_ECN_SND_CWR;
426 if (!IN_CONGRECOVERY(tp->t_flags)) {
427 TCPSTAT_INC(tcps_ecn_rcwnd);
428 tp->snd_recover = tp->snd_max;
429 if (tp->t_flags & TF_ECN_PERMIT)
430 tp->t_flags |= TF_ECN_SND_CWR;
434 maxseg = tcp_maxseg(tp);
436 tp->t_bytes_acked = 0;
437 EXIT_RECOVERY(tp->t_flags);
438 if (CC_ALGO(tp)->cong_signal == NULL) {
440 * RFC5681 Section 3.1
441 * ssthresh = max (FlightSize / 2, 2*SMSS) eq (4)
444 max((tp->snd_max - tp->snd_una) / 2, 2 * maxseg);
445 tp->snd_cwnd = maxseg;
449 TCPSTAT_INC(tcps_sndrexmitbad);
450 /* RTO was unnecessary, so reset everything. */
451 tp->snd_cwnd = tp->snd_cwnd_prev;
452 tp->snd_ssthresh = tp->snd_ssthresh_prev;
453 tp->snd_recover = tp->snd_recover_prev;
454 if (tp->t_flags & TF_WASFRECOVERY)
455 ENTER_FASTRECOVERY(tp->t_flags);
456 if (tp->t_flags & TF_WASCRECOVERY)
457 ENTER_CONGRECOVERY(tp->t_flags);
458 tp->snd_nxt = tp->snd_max;
459 tp->t_flags &= ~TF_PREVVALID;
464 if (CC_ALGO(tp)->cong_signal != NULL) {
466 tp->ccv->curack = th->th_ack;
467 CC_ALGO(tp)->cong_signal(tp->ccv, type);
472 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
474 INP_WLOCK_ASSERT(tp->t_inpcb);
476 /* XXXLAS: KASSERT that we're in recovery? */
478 if (CC_ALGO(tp)->post_recovery != NULL) {
479 tp->ccv->curack = th->th_ack;
480 CC_ALGO(tp)->post_recovery(tp->ccv);
482 /* XXXLAS: EXIT_RECOVERY ? */
483 tp->t_bytes_acked = 0;
487 * Indicate whether this ack should be delayed. We can delay the ack if
488 * following conditions are met:
489 * - There is no delayed ack timer in progress.
490 * - Our last ack wasn't a 0-sized window. We never want to delay
491 * the ack that opens up a 0-sized window.
492 * - LRO wasn't used for this segment. We make sure by checking that the
493 * segment size is not larger than the MSS.
495 #define DELAY_ACK(tp, tlen) \
496 ((!tcp_timer_active(tp, TT_DELACK) && \
497 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
498 (tlen <= tp->t_maxseg) && \
499 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
502 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
504 INP_WLOCK_ASSERT(tp->t_inpcb);
506 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
507 switch (iptos & IPTOS_ECN_MASK) {
509 tp->ccv->flags |= CCF_IPHDR_CE;
512 tp->ccv->flags &= ~CCF_IPHDR_CE;
515 tp->ccv->flags &= ~CCF_IPHDR_CE;
519 if (th->th_flags & TH_CWR)
520 tp->ccv->flags |= CCF_TCPHDR_CWR;
522 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
524 if (tp->t_flags & TF_DELACK)
525 tp->ccv->flags |= CCF_DELACK;
527 tp->ccv->flags &= ~CCF_DELACK;
529 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
531 if (tp->ccv->flags & CCF_ACKNOW)
532 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
537 * TCP input handling is split into multiple parts:
538 * tcp6_input is a thin wrapper around tcp_input for the extended
539 * ip6_protox[] call format in ip6_input
540 * tcp_input handles primary segment validation, inpcb lookup and
541 * SYN processing on listen sockets
542 * tcp_do_segment processes the ACK and text of the segment for
543 * establishing, established and closing connections
547 tcp6_input(struct mbuf **mp, int *offp, int proto)
549 struct mbuf *m = *mp;
550 struct in6_ifaddr *ia6;
553 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
556 * draft-itojun-ipv6-tcp-to-anycast
557 * better place to put this in?
559 ip6 = mtod(m, struct ip6_hdr *);
560 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
561 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
564 ifa_free(&ia6->ia_ifa);
565 ip6 = mtod(m, struct ip6_hdr *);
566 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
567 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
568 return (IPPROTO_DONE);
571 ifa_free(&ia6->ia_ifa);
573 return (tcp_input(mp, offp, proto));
578 tcp_input(struct mbuf **mp, int *offp, int proto)
580 struct mbuf *m = *mp;
581 struct tcphdr *th = NULL;
582 struct ip *ip = NULL;
583 struct inpcb *inp = NULL;
584 struct tcpcb *tp = NULL;
585 struct socket *so = NULL;
595 int rstreason = 0; /* For badport_bandlim accounting purposes */
597 struct m_tag *fwd_tag = NULL;
599 struct ip6_hdr *ip6 = NULL;
602 const void *ip6 = NULL;
604 struct tcpopt to; /* options in this segment */
605 char *s = NULL; /* address and port logging */
609 * The size of tcp_saveipgen must be the size of the max ip header,
612 u_char tcp_saveipgen[IP6_HDR_LEN];
613 struct tcphdr tcp_savetcp;
618 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
625 TCPSTAT_INC(tcps_rcvtotal);
629 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
631 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
632 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
634 TCPSTAT_INC(tcps_rcvshort);
635 return (IPPROTO_DONE);
639 ip6 = mtod(m, struct ip6_hdr *);
640 th = (struct tcphdr *)((caddr_t)ip6 + off0);
641 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
642 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
643 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
644 th->th_sum = m->m_pkthdr.csum_data;
646 th->th_sum = in6_cksum_pseudo(ip6, tlen,
647 IPPROTO_TCP, m->m_pkthdr.csum_data);
648 th->th_sum ^= 0xffff;
650 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
652 TCPSTAT_INC(tcps_rcvbadsum);
657 * Be proactive about unspecified IPv6 address in source.
658 * As we use all-zero to indicate unbounded/unconnected pcb,
659 * unspecified IPv6 address can be used to confuse us.
661 * Note that packets with unspecified IPv6 destination is
662 * already dropped in ip6_input.
664 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
668 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
671 #if defined(INET) && defined(INET6)
677 * Get IP and TCP header together in first mbuf.
678 * Note: IP leaves IP header in first mbuf.
680 if (off0 > sizeof (struct ip)) {
682 off0 = sizeof(struct ip);
684 if (m->m_len < sizeof (struct tcpiphdr)) {
685 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
687 TCPSTAT_INC(tcps_rcvshort);
688 return (IPPROTO_DONE);
691 ip = mtod(m, struct ip *);
692 th = (struct tcphdr *)((caddr_t)ip + off0);
693 tlen = ntohs(ip->ip_len) - off0;
696 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
697 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
698 th->th_sum = m->m_pkthdr.csum_data;
700 th->th_sum = in_pseudo(ip->ip_src.s_addr,
702 htonl(m->m_pkthdr.csum_data + tlen +
704 th->th_sum ^= 0xffff;
706 struct ipovly *ipov = (struct ipovly *)ip;
709 * Checksum extended TCP header and data.
712 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
713 ipov->ih_len = htons(tlen);
714 th->th_sum = in_cksum(m, len);
715 /* Reset length for SDT probes. */
716 ip->ip_len = htons(len);
719 /* Re-initialization for later version check */
720 ip->ip_v = IPVERSION;
724 TCPSTAT_INC(tcps_rcvbadsum);
731 * Check that TCP offset makes sense,
732 * pull out TCP options and adjust length. XXX
734 off = th->th_off << 2;
735 if (off < sizeof (struct tcphdr) || off > tlen) {
736 TCPSTAT_INC(tcps_rcvbadoff);
739 tlen -= off; /* tlen is used instead of ti->ti_len */
740 if (off > sizeof (struct tcphdr)) {
743 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
744 ip6 = mtod(m, struct ip6_hdr *);
745 th = (struct tcphdr *)((caddr_t)ip6 + off0);
748 #if defined(INET) && defined(INET6)
753 if (m->m_len < sizeof(struct ip) + off) {
754 if ((m = m_pullup(m, sizeof (struct ip) + off))
756 TCPSTAT_INC(tcps_rcvshort);
757 return (IPPROTO_DONE);
759 ip = mtod(m, struct ip *);
760 th = (struct tcphdr *)((caddr_t)ip + off0);
764 optlen = off - sizeof (struct tcphdr);
765 optp = (u_char *)(th + 1);
767 thflags = th->th_flags;
770 * Convert TCP protocol specific fields to host format.
772 tcp_fields_to_host(th);
775 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
777 drop_hdrlen = off0 + off;
780 * Locate pcb for segment; if we're likely to add or remove a
781 * connection then first acquire pcbinfo lock. There are three cases
782 * where we might discover later we need a write lock despite the
783 * flags: ACKs moving a connection out of the syncache, ACKs for a
784 * connection in TIMEWAIT and SYNs not targeting a listening socket.
786 if ((thflags & (TH_FIN | TH_RST)) != 0) {
787 INP_INFO_RLOCK(&V_tcbinfo);
788 ti_locked = TI_RLOCKED;
790 ti_locked = TI_UNLOCKED;
793 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
797 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
799 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
802 #if defined(INET) && !defined(INET6)
803 (m->m_flags & M_IP_NEXTHOP)
806 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
810 if (ti_locked == TI_RLOCKED) {
811 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
813 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
817 if (isipv6 && fwd_tag != NULL) {
818 struct sockaddr_in6 *next_hop6;
820 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
822 * Transparently forwarded. Pretend to be the destination.
823 * Already got one like this?
825 inp = in6_pcblookup_mbuf(&V_tcbinfo,
826 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
827 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
830 * It's new. Try to find the ambushing socket.
831 * Because we've rewritten the destination address,
832 * any hardware-generated hash is ignored.
834 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
835 th->th_sport, &next_hop6->sin6_addr,
836 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
837 th->th_dport, INPLOOKUP_WILDCARD |
838 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
841 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
842 th->th_sport, &ip6->ip6_dst, th->th_dport,
843 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
844 m->m_pkthdr.rcvif, m);
847 #if defined(INET6) && defined(INET)
851 if (fwd_tag != NULL) {
852 struct sockaddr_in *next_hop;
854 next_hop = (struct sockaddr_in *)(fwd_tag+1);
856 * Transparently forwarded. Pretend to be the destination.
857 * already got one like this?
859 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
860 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
861 m->m_pkthdr.rcvif, m);
864 * It's new. Try to find the ambushing socket.
865 * Because we've rewritten the destination address,
866 * any hardware-generated hash is ignored.
868 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
869 th->th_sport, next_hop->sin_addr,
870 next_hop->sin_port ? ntohs(next_hop->sin_port) :
871 th->th_dport, INPLOOKUP_WILDCARD |
872 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
875 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
876 th->th_sport, ip->ip_dst, th->th_dport,
877 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
878 m->m_pkthdr.rcvif, m);
882 * If the INPCB does not exist then all data in the incoming
883 * segment is discarded and an appropriate RST is sent back.
884 * XXX MRT Send RST using which routing table?
888 * Log communication attempts to ports that are not
891 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
892 tcp_log_in_vain == 2) {
893 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
894 log(LOG_INFO, "%s; %s: Connection attempt "
895 "to closed port\n", s, __func__);
898 * When blackholing do not respond with a RST but
899 * completely ignore the segment and drop it.
901 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
905 rstreason = BANDLIM_RST_CLOSEDPORT;
908 INP_WLOCK_ASSERT(inp);
910 * While waiting for inp lock during the lookup, another thread
911 * can have dropped the inpcb, in which case we need to loop back
912 * and try to find a new inpcb to deliver to.
914 if (inp->inp_flags & INP_DROPPED) {
919 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
920 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
921 ((inp->inp_socket == NULL) ||
922 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
923 inp->inp_flowid = m->m_pkthdr.flowid;
924 inp->inp_flowtype = M_HASHTYPE_GET(m);
926 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
928 if (isipv6 && IPSEC_ENABLED(ipv6) &&
929 IPSEC_CHECK_POLICY(ipv6, m, inp) != 0) {
937 if (IPSEC_ENABLED(ipv4) &&
938 IPSEC_CHECK_POLICY(ipv4, m, inp) != 0) {
945 * Check the minimum TTL for socket.
947 if (inp->inp_ip_minttl != 0) {
950 if (inp->inp_ip_minttl > ip6->ip6_hlim)
954 if (inp->inp_ip_minttl > ip->ip_ttl)
959 * A previous connection in TIMEWAIT state is supposed to catch stray
960 * or duplicate segments arriving late. If this segment was a
961 * legitimate new connection attempt, the old INPCB gets removed and
962 * we can try again to find a listening socket.
964 * At this point, due to earlier optimism, we may hold only an inpcb
965 * lock, and not the inpcbinfo write lock. If so, we need to try to
966 * acquire it, or if that fails, acquire a reference on the inpcb,
967 * drop all locks, acquire a global write lock, and then re-acquire
968 * the inpcb lock. We may at that point discover that another thread
969 * has tried to free the inpcb, in which case we need to loop back
970 * and try to find a new inpcb to deliver to.
972 * XXXRW: It may be time to rethink timewait locking.
975 if (inp->inp_flags & INP_TIMEWAIT) {
976 if (ti_locked == TI_UNLOCKED) {
977 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
980 INP_INFO_RLOCK(&V_tcbinfo);
981 ti_locked = TI_RLOCKED;
983 if (in_pcbrele_wlocked(inp)) {
986 } else if (inp->inp_flags & INP_DROPPED) {
992 ti_locked = TI_RLOCKED;
994 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
996 if (thflags & TH_SYN)
997 tcp_dooptions(&to, optp, optlen, TO_SYN);
999 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
1001 if (tcp_twcheck(inp, &to, th, m, tlen))
1003 INP_INFO_RUNLOCK(&V_tcbinfo);
1004 return (IPPROTO_DONE);
1007 * The TCPCB may no longer exist if the connection is winding
1008 * down or it is in the CLOSED state. Either way we drop the
1009 * segment and send an appropriate response.
1011 tp = intotcpcb(inp);
1012 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
1013 rstreason = BANDLIM_RST_CLOSEDPORT;
1018 if (tp->t_flags & TF_TOE) {
1019 tcp_offload_input(tp, m);
1020 m = NULL; /* consumed by the TOE driver */
1026 * We've identified a valid inpcb, but it could be that we need an
1027 * inpcbinfo write lock but don't hold it. In this case, attempt to
1028 * acquire using the same strategy as the TIMEWAIT case above. If we
1029 * relock, we have to jump back to 'relocked' as the connection might
1030 * now be in TIMEWAIT.
1033 if ((thflags & (TH_FIN | TH_RST)) != 0)
1034 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1036 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1037 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
1038 !IS_FASTOPEN(tp->t_flags)))) {
1039 if (ti_locked == TI_UNLOCKED) {
1040 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
1043 INP_INFO_RLOCK(&V_tcbinfo);
1044 ti_locked = TI_RLOCKED;
1046 if (in_pcbrele_wlocked(inp)) {
1049 } else if (inp->inp_flags & INP_DROPPED) {
1056 ti_locked = TI_RLOCKED;
1058 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1062 INP_WLOCK_ASSERT(inp);
1063 if (mac_inpcb_check_deliver(inp, m))
1066 so = inp->inp_socket;
1067 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1069 if (so->so_options & SO_DEBUG) {
1070 ostate = tp->t_state;
1073 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1076 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1079 #endif /* TCPDEBUG */
1081 * When the socket is accepting connections (the INPCB is in LISTEN
1082 * state) we look into the SYN cache if this is a new connection
1083 * attempt or the completion of a previous one.
1085 KASSERT(tp->t_state == TCPS_LISTEN || !(so->so_options & SO_ACCEPTCONN),
1086 ("%s: so accepting but tp %p not listening", __func__, tp));
1087 if (tp->t_state == TCPS_LISTEN && (so->so_options & SO_ACCEPTCONN)) {
1088 struct in_conninfo inc;
1090 bzero(&inc, sizeof(inc));
1093 inc.inc_flags |= INC_ISIPV6;
1094 inc.inc6_faddr = ip6->ip6_src;
1095 inc.inc6_laddr = ip6->ip6_dst;
1099 inc.inc_faddr = ip->ip_src;
1100 inc.inc_laddr = ip->ip_dst;
1102 inc.inc_fport = th->th_sport;
1103 inc.inc_lport = th->th_dport;
1104 inc.inc_fibnum = so->so_fibnum;
1107 * Check for an existing connection attempt in syncache if
1108 * the flag is only ACK. A successful lookup creates a new
1109 * socket appended to the listen queue in SYN_RECEIVED state.
1111 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1113 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1115 * Parse the TCP options here because
1116 * syncookies need access to the reflected
1119 tcp_dooptions(&to, optp, optlen, 0);
1121 * NB: syncache_expand() doesn't unlock
1122 * inp and tcpinfo locks.
1124 rstreason = syncache_expand(&inc, &to, th, &so, m);
1125 if (rstreason < 0) {
1127 * A failing TCP MD5 signature comparison
1128 * must result in the segment being dropped
1129 * and must not produce any response back
1133 } else if (rstreason == 0) {
1135 * No syncache entry or ACK was not
1136 * for our SYN/ACK. Send a RST.
1137 * NB: syncache did its own logging
1138 * of the failure cause.
1140 rstreason = BANDLIM_RST_OPENPORT;
1148 * We completed the 3-way handshake
1149 * but could not allocate a socket
1150 * either due to memory shortage,
1151 * listen queue length limits or
1152 * global socket limits. Send RST
1153 * or wait and have the remote end
1154 * retransmit the ACK for another
1157 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1158 log(LOG_DEBUG, "%s; %s: Listen socket: "
1159 "Socket allocation failed due to "
1160 "limits or memory shortage, %s\n",
1162 V_tcp_sc_rst_sock_fail ?
1163 "sending RST" : "try again");
1164 if (V_tcp_sc_rst_sock_fail) {
1165 rstreason = BANDLIM_UNLIMITED;
1171 * Socket is created in state SYN_RECEIVED.
1172 * Unlock the listen socket, lock the newly
1173 * created socket and update the tp variable.
1175 INP_WUNLOCK(inp); /* listen socket */
1176 inp = sotoinpcb(so);
1178 * New connection inpcb is already locked by
1179 * syncache_expand().
1181 INP_WLOCK_ASSERT(inp);
1182 tp = intotcpcb(inp);
1183 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1184 ("%s: ", __func__));
1186 * Process the segment and the data it
1187 * contains. tcp_do_segment() consumes
1188 * the mbuf chain and unlocks the inpcb.
1190 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1192 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1193 return (IPPROTO_DONE);
1196 * Segment flag validation for new connection attempts:
1198 * Our (SYN|ACK) response was rejected.
1199 * Check with syncache and remove entry to prevent
1202 * NB: syncache_chkrst does its own logging of failure
1205 if (thflags & TH_RST) {
1206 syncache_chkrst(&inc, th);
1210 * We can't do anything without SYN.
1212 if ((thflags & TH_SYN) == 0) {
1213 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1214 log(LOG_DEBUG, "%s; %s: Listen socket: "
1215 "SYN is missing, segment ignored\n",
1217 TCPSTAT_INC(tcps_badsyn);
1221 * (SYN|ACK) is bogus on a listen socket.
1223 if (thflags & TH_ACK) {
1224 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1225 log(LOG_DEBUG, "%s; %s: Listen socket: "
1226 "SYN|ACK invalid, segment rejected\n",
1228 syncache_badack(&inc); /* XXX: Not needed! */
1229 TCPSTAT_INC(tcps_badsyn);
1230 rstreason = BANDLIM_RST_OPENPORT;
1234 * If the drop_synfin option is enabled, drop all
1235 * segments with both the SYN and FIN bits set.
1236 * This prevents e.g. nmap from identifying the
1238 * XXX: Poor reasoning. nmap has other methods
1239 * and is constantly refining its stack detection
1241 * XXX: This is a violation of the TCP specification
1242 * and was used by RFC1644.
1244 if ((thflags & TH_FIN) && V_drop_synfin) {
1245 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1246 log(LOG_DEBUG, "%s; %s: Listen socket: "
1247 "SYN|FIN segment ignored (based on "
1248 "sysctl setting)\n", s, __func__);
1249 TCPSTAT_INC(tcps_badsyn);
1253 * Segment's flags are (SYN) or (SYN|FIN).
1255 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1256 * as they do not affect the state of the TCP FSM.
1257 * The data pointed to by TH_URG and th_urp is ignored.
1259 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1260 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1261 KASSERT(thflags & (TH_SYN),
1262 ("%s: Listen socket: TH_SYN not set", __func__));
1265 * If deprecated address is forbidden,
1266 * we do not accept SYN to deprecated interface
1267 * address to prevent any new inbound connection from
1268 * getting established.
1269 * When we do not accept SYN, we send a TCP RST,
1270 * with deprecated source address (instead of dropping
1271 * it). We compromise it as it is much better for peer
1272 * to send a RST, and RST will be the final packet
1275 * If we do not forbid deprecated addresses, we accept
1276 * the SYN packet. RFC2462 does not suggest dropping
1278 * If we decipher RFC2462 5.5.4, it says like this:
1279 * 1. use of deprecated addr with existing
1280 * communication is okay - "SHOULD continue to be
1282 * 2. use of it with new communication:
1283 * (2a) "SHOULD NOT be used if alternate address
1284 * with sufficient scope is available"
1285 * (2b) nothing mentioned otherwise.
1286 * Here we fall into (2b) case as we have no choice in
1287 * our source address selection - we must obey the peer.
1289 * The wording in RFC2462 is confusing, and there are
1290 * multiple description text for deprecated address
1291 * handling - worse, they are not exactly the same.
1292 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1294 if (isipv6 && !V_ip6_use_deprecated) {
1295 struct in6_ifaddr *ia6;
1297 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1299 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1300 ifa_free(&ia6->ia_ifa);
1301 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1302 log(LOG_DEBUG, "%s; %s: Listen socket: "
1303 "Connection attempt to deprecated "
1304 "IPv6 address rejected\n",
1306 rstreason = BANDLIM_RST_OPENPORT;
1310 ifa_free(&ia6->ia_ifa);
1314 * Basic sanity checks on incoming SYN requests:
1315 * Don't respond if the destination is a link layer
1316 * broadcast according to RFC1122 4.2.3.10, p. 104.
1317 * If it is from this socket it must be forged.
1318 * Don't respond if the source or destination is a
1319 * global or subnet broad- or multicast address.
1320 * Note that it is quite possible to receive unicast
1321 * link-layer packets with a broadcast IP address. Use
1322 * in_broadcast() to find them.
1324 if (m->m_flags & (M_BCAST|M_MCAST)) {
1325 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1326 log(LOG_DEBUG, "%s; %s: Listen socket: "
1327 "Connection attempt from broad- or multicast "
1328 "link layer address ignored\n", s, __func__);
1333 if (th->th_dport == th->th_sport &&
1334 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1335 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1336 log(LOG_DEBUG, "%s; %s: Listen socket: "
1337 "Connection attempt to/from self "
1338 "ignored\n", s, __func__);
1341 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1342 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1343 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1344 log(LOG_DEBUG, "%s; %s: Listen socket: "
1345 "Connection attempt from/to multicast "
1346 "address ignored\n", s, __func__);
1351 #if defined(INET) && defined(INET6)
1356 if (th->th_dport == th->th_sport &&
1357 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1358 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1359 log(LOG_DEBUG, "%s; %s: Listen socket: "
1360 "Connection attempt from/to self "
1361 "ignored\n", s, __func__);
1364 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1365 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1366 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1367 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1368 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1369 log(LOG_DEBUG, "%s; %s: Listen socket: "
1370 "Connection attempt from/to broad- "
1371 "or multicast address ignored\n",
1378 * SYN appears to be valid. Create compressed TCP state
1382 if (so->so_options & SO_DEBUG)
1383 tcp_trace(TA_INPUT, ostate, tp,
1384 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1386 TCP_PROBE3(debug__input, tp, th, m);
1387 tcp_dooptions(&to, optp, optlen, TO_SYN);
1389 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
1390 goto tfo_socket_result;
1392 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1395 * Entry added to syncache and mbuf consumed.
1396 * Only the listen socket is unlocked by syncache_add().
1398 if (ti_locked == TI_RLOCKED) {
1399 INP_INFO_RUNLOCK(&V_tcbinfo);
1400 ti_locked = TI_UNLOCKED;
1402 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1403 return (IPPROTO_DONE);
1404 } else if (tp->t_state == TCPS_LISTEN) {
1406 * When a listen socket is torn down the SO_ACCEPTCONN
1407 * flag is removed first while connections are drained
1408 * from the accept queue in a unlock/lock cycle of the
1409 * ACCEPT_LOCK, opening a race condition allowing a SYN
1410 * attempt go through unhandled.
1414 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1415 if (tp->t_flags & TF_SIGNATURE) {
1416 tcp_dooptions(&to, optp, optlen, thflags);
1417 if ((to.to_flags & TOF_SIGNATURE) == 0) {
1418 TCPSTAT_INC(tcps_sig_err_nosigopt);
1421 if (!TCPMD5_ENABLED() ||
1422 TCPMD5_INPUT(m, th, to.to_signature) != 0)
1426 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1429 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1430 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1431 * the inpcb, and unlocks pcbinfo.
1433 tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1434 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1435 return (IPPROTO_DONE);
1438 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1440 if (ti_locked == TI_RLOCKED) {
1441 INP_INFO_RUNLOCK(&V_tcbinfo);
1442 ti_locked = TI_UNLOCKED;
1446 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1447 "ti_locked: %d", __func__, ti_locked));
1448 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1453 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1456 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1457 m = NULL; /* mbuf chain got consumed. */
1462 TCP_PROBE5(receive, NULL, tp, m, tp, th);
1464 if (ti_locked == TI_RLOCKED) {
1465 INP_INFO_RUNLOCK(&V_tcbinfo);
1466 ti_locked = TI_UNLOCKED;
1470 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1471 "ti_locked: %d", __func__, ti_locked));
1472 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1480 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1485 return (IPPROTO_DONE);
1489 * Automatic sizing of receive socket buffer. Often the send
1490 * buffer size is not optimally adjusted to the actual network
1491 * conditions at hand (delay bandwidth product). Setting the
1492 * buffer size too small limits throughput on links with high
1493 * bandwidth and high delay (eg. trans-continental/oceanic links).
1495 * On the receive side the socket buffer memory is only rarely
1496 * used to any significant extent. This allows us to be much
1497 * more aggressive in scaling the receive socket buffer. For
1498 * the case that the buffer space is actually used to a large
1499 * extent and we run out of kernel memory we can simply drop
1500 * the new segments; TCP on the sender will just retransmit it
1501 * later. Setting the buffer size too big may only consume too
1502 * much kernel memory if the application doesn't read() from
1503 * the socket or packet loss or reordering makes use of the
1506 * The criteria to step up the receive buffer one notch are:
1507 * 1. Application has not set receive buffer size with
1508 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1509 * 2. the number of bytes received during the time it takes
1510 * one timestamp to be reflected back to us (the RTT);
1511 * 3. received bytes per RTT is within seven eighth of the
1512 * current socket buffer size;
1513 * 4. receive buffer size has not hit maximal automatic size;
1515 * This algorithm does one step per RTT at most and only if
1516 * we receive a bulk stream w/o packet losses or reorderings.
1517 * Shrinking the buffer during idle times is not necessary as
1518 * it doesn't consume any memory when idle.
1520 * TODO: Only step up if the application is actually serving
1521 * the buffer to better manage the socket buffer resources.
1524 tcp_autorcvbuf(struct mbuf *m, struct tcphdr *th, struct socket *so,
1525 struct tcpcb *tp, int tlen)
1529 if (V_tcp_do_autorcvbuf && (so->so_rcv.sb_flags & SB_AUTOSIZE) &&
1530 tp->t_srtt != 0 && tp->rfbuf_ts != 0 &&
1531 TCP_TS_TO_TICKS(tcp_ts_getticks() - tp->rfbuf_ts) >
1532 (tp->t_srtt >> TCP_RTT_SHIFT)) {
1533 if (tp->rfbuf_cnt > (so->so_rcv.sb_hiwat / 8 * 7) &&
1534 so->so_rcv.sb_hiwat < V_tcp_autorcvbuf_max) {
1535 newsize = min(so->so_rcv.sb_hiwat +
1536 V_tcp_autorcvbuf_inc, V_tcp_autorcvbuf_max);
1538 TCP_PROBE6(receive__autoresize, NULL, tp, m, tp, th, newsize);
1540 /* Start over with next RTT. */
1544 tp->rfbuf_cnt += tlen; /* add up */
1551 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1552 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1555 int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1556 int rstreason, todrop, win;
1560 struct in_conninfo *inc;
1569 * The size of tcp_saveipgen must be the size of the max ip header,
1572 u_char tcp_saveipgen[IP6_HDR_LEN];
1573 struct tcphdr tcp_savetcp;
1576 thflags = th->th_flags;
1577 inc = &tp->t_inpcb->inp_inc;
1578 tp->sackhint.last_sack_ack = 0;
1580 nsegs = max(1, m->m_pkthdr.lro_nsegs);
1583 * If this is either a state-changing packet or current state isn't
1584 * established, we require a write lock on tcbinfo. Otherwise, we
1585 * allow the tcbinfo to be in either alocked or unlocked, as the
1586 * caller may have unnecessarily acquired a write lock due to a race.
1588 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1589 tp->t_state != TCPS_ESTABLISHED) {
1590 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1591 "SYN/FIN/RST/!EST", __func__, ti_locked));
1592 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1595 if (ti_locked == TI_RLOCKED)
1596 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1598 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1599 "ti_locked: %d", __func__, ti_locked));
1600 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1604 INP_WLOCK_ASSERT(tp->t_inpcb);
1605 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1607 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1611 /* Save segment, if requested. */
1612 tcp_pcap_add(th, m, &(tp->t_inpkts));
1615 if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
1616 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1617 log(LOG_DEBUG, "%s; %s: "
1618 "SYN|FIN segment ignored (based on "
1619 "sysctl setting)\n", s, __func__);
1626 * If a segment with the ACK-bit set arrives in the SYN-SENT state
1627 * check SEQ.ACK first.
1629 if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
1630 (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
1631 rstreason = BANDLIM_UNLIMITED;
1636 * Segment received on connection.
1637 * Reset idle time and keep-alive timer.
1638 * XXX: This should be done after segment
1639 * validation to ignore broken/spoofed segs.
1641 tp->t_rcvtime = ticks;
1644 * Scale up the window into a 32-bit value.
1645 * For the SYN_SENT state the scale is zero.
1647 tiwin = th->th_win << tp->snd_scale;
1650 * TCP ECN processing.
1652 if (tp->t_flags & TF_ECN_PERMIT) {
1653 if (thflags & TH_CWR)
1654 tp->t_flags &= ~TF_ECN_SND_ECE;
1655 switch (iptos & IPTOS_ECN_MASK) {
1657 tp->t_flags |= TF_ECN_SND_ECE;
1658 TCPSTAT_INC(tcps_ecn_ce);
1660 case IPTOS_ECN_ECT0:
1661 TCPSTAT_INC(tcps_ecn_ect0);
1663 case IPTOS_ECN_ECT1:
1664 TCPSTAT_INC(tcps_ecn_ect1);
1668 /* Process a packet differently from RFC3168. */
1669 cc_ecnpkt_handler(tp, th, iptos);
1671 /* Congestion experienced. */
1672 if (thflags & TH_ECE) {
1673 cc_cong_signal(tp, th, CC_ECN);
1678 * Parse options on any incoming segment.
1680 tcp_dooptions(&to, (u_char *)(th + 1),
1681 (th->th_off << 2) - sizeof(struct tcphdr),
1682 (thflags & TH_SYN) ? TO_SYN : 0);
1684 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1685 if ((tp->t_flags & TF_SIGNATURE) != 0 &&
1686 (to.to_flags & TOF_SIGNATURE) == 0) {
1687 TCPSTAT_INC(tcps_sig_err_sigopt);
1688 /* XXX: should drop? */
1692 * If echoed timestamp is later than the current time,
1693 * fall back to non RFC1323 RTT calculation. Normalize
1694 * timestamp if syncookies were used when this connection
1697 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1698 to.to_tsecr -= tp->ts_offset;
1699 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1703 * If timestamps were negotiated during SYN/ACK they should
1704 * appear on every segment during this session and vice versa.
1706 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1707 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1708 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1709 "no action\n", s, __func__);
1713 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1714 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1715 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1716 "no action\n", s, __func__);
1722 * Process options only when we get SYN/ACK back. The SYN case
1723 * for incoming connections is handled in tcp_syncache.
1724 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1725 * or <SYN,ACK>) segment itself is never scaled.
1726 * XXX this is traditional behavior, may need to be cleaned up.
1728 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1729 if ((to.to_flags & TOF_SCALE) &&
1730 (tp->t_flags & TF_REQ_SCALE)) {
1731 tp->t_flags |= TF_RCVD_SCALE;
1732 tp->snd_scale = to.to_wscale;
1735 * Initial send window. It will be updated with
1736 * the next incoming segment to the scaled value.
1738 tp->snd_wnd = th->th_win;
1739 if (to.to_flags & TOF_TS) {
1740 tp->t_flags |= TF_RCVD_TSTMP;
1741 tp->ts_recent = to.to_tsval;
1742 tp->ts_recent_age = tcp_ts_getticks();
1744 if (to.to_flags & TOF_MSS)
1745 tcp_mss(tp, to.to_mss);
1746 if ((tp->t_flags & TF_SACK_PERMIT) &&
1747 (to.to_flags & TOF_SACKPERM) == 0)
1748 tp->t_flags &= ~TF_SACK_PERMIT;
1752 * Header prediction: check for the two common cases
1753 * of a uni-directional data xfer. If the packet has
1754 * no control flags, is in-sequence, the window didn't
1755 * change and we're not retransmitting, it's a
1756 * candidate. If the length is zero and the ack moved
1757 * forward, we're the sender side of the xfer. Just
1758 * free the data acked & wake any higher level process
1759 * that was blocked waiting for space. If the length
1760 * is non-zero and the ack didn't move, we're the
1761 * receiver side. If we're getting packets in-order
1762 * (the reassembly queue is empty), add the data to
1763 * the socket buffer and note that we need a delayed ack.
1764 * Make sure that the hidden state-flags are also off.
1765 * Since we check for TCPS_ESTABLISHED first, it can only
1768 if (tp->t_state == TCPS_ESTABLISHED &&
1769 th->th_seq == tp->rcv_nxt &&
1770 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1771 tp->snd_nxt == tp->snd_max &&
1772 tiwin && tiwin == tp->snd_wnd &&
1773 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1774 LIST_EMPTY(&tp->t_segq) &&
1775 ((to.to_flags & TOF_TS) == 0 ||
1776 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1779 * If last ACK falls within this segment's sequence numbers,
1780 * record the timestamp.
1781 * NOTE that the test is modified according to the latest
1782 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1784 if ((to.to_flags & TOF_TS) != 0 &&
1785 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1786 tp->ts_recent_age = tcp_ts_getticks();
1787 tp->ts_recent = to.to_tsval;
1791 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1792 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1793 !IN_RECOVERY(tp->t_flags) &&
1794 (to.to_flags & TOF_SACK) == 0 &&
1795 TAILQ_EMPTY(&tp->snd_holes)) {
1797 * This is a pure ack for outstanding data.
1799 if (ti_locked == TI_RLOCKED)
1800 INP_INFO_RUNLOCK(&V_tcbinfo);
1801 ti_locked = TI_UNLOCKED;
1803 TCPSTAT_INC(tcps_predack);
1806 * "bad retransmit" recovery.
1808 if (tp->t_rxtshift == 1 &&
1809 tp->t_flags & TF_PREVVALID &&
1810 (int)(ticks - tp->t_badrxtwin) < 0) {
1811 cc_cong_signal(tp, th, CC_RTO_ERR);
1815 * Recalculate the transmit timer / rtt.
1817 * Some boxes send broken timestamp replies
1818 * during the SYN+ACK phase, ignore
1819 * timestamps of 0 or we could calculate a
1820 * huge RTT and blow up the retransmit timer.
1822 if ((to.to_flags & TOF_TS) != 0 &&
1826 t = tcp_ts_getticks() - to.to_tsecr;
1827 if (!tp->t_rttlow || tp->t_rttlow > t)
1830 TCP_TS_TO_TICKS(t) + 1);
1831 } else if (tp->t_rtttime &&
1832 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1833 if (!tp->t_rttlow ||
1834 tp->t_rttlow > ticks - tp->t_rtttime)
1835 tp->t_rttlow = ticks - tp->t_rtttime;
1837 ticks - tp->t_rtttime);
1839 acked = BYTES_THIS_ACK(tp, th);
1842 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1843 hhook_run_tcp_est_in(tp, th, &to);
1846 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
1847 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1848 sbdrop(&so->so_snd, acked);
1849 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1850 SEQ_LEQ(th->th_ack, tp->snd_recover))
1851 tp->snd_recover = th->th_ack - 1;
1854 * Let the congestion control algorithm update
1855 * congestion control related information. This
1856 * typically means increasing the congestion
1859 cc_ack_received(tp, th, nsegs, CC_ACK);
1861 tp->snd_una = th->th_ack;
1863 * Pull snd_wl2 up to prevent seq wrap relative
1866 tp->snd_wl2 = th->th_ack;
1871 * If all outstanding data are acked, stop
1872 * retransmit timer, otherwise restart timer
1873 * using current (possibly backed-off) value.
1874 * If process is waiting for space,
1875 * wakeup/selwakeup/signal. If data
1876 * are ready to send, let tcp_output
1877 * decide between more output or persist.
1880 if (so->so_options & SO_DEBUG)
1881 tcp_trace(TA_INPUT, ostate, tp,
1882 (void *)tcp_saveipgen,
1885 TCP_PROBE3(debug__input, tp, th, m);
1886 if (tp->snd_una == tp->snd_max)
1887 tcp_timer_activate(tp, TT_REXMT, 0);
1888 else if (!tcp_timer_active(tp, TT_PERSIST))
1889 tcp_timer_activate(tp, TT_REXMT,
1892 if (sbavail(&so->so_snd))
1893 (void) tp->t_fb->tfb_tcp_output(tp);
1896 } else if (th->th_ack == tp->snd_una &&
1897 tlen <= sbspace(&so->so_rcv)) {
1898 int newsize = 0; /* automatic sockbuf scaling */
1901 * This is a pure, in-sequence data packet with
1902 * nothing on the reassembly queue and we have enough
1903 * buffer space to take it.
1905 if (ti_locked == TI_RLOCKED)
1906 INP_INFO_RUNLOCK(&V_tcbinfo);
1907 ti_locked = TI_UNLOCKED;
1909 /* Clean receiver SACK report if present */
1910 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1911 tcp_clean_sackreport(tp);
1912 TCPSTAT_INC(tcps_preddat);
1913 tp->rcv_nxt += tlen;
1915 * Pull snd_wl1 up to prevent seq wrap relative to
1918 tp->snd_wl1 = th->th_seq;
1920 * Pull rcv_up up to prevent seq wrap relative to
1923 tp->rcv_up = tp->rcv_nxt;
1924 TCPSTAT_ADD(tcps_rcvpack, nsegs);
1925 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1927 if (so->so_options & SO_DEBUG)
1928 tcp_trace(TA_INPUT, ostate, tp,
1929 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1931 TCP_PROBE3(debug__input, tp, th, m);
1933 newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
1935 /* Add data to socket buffer. */
1936 SOCKBUF_LOCK(&so->so_rcv);
1937 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1941 * Set new socket buffer size.
1942 * Give up when limit is reached.
1945 if (!sbreserve_locked(&so->so_rcv,
1947 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1948 m_adj(m, drop_hdrlen); /* delayed header drop */
1949 sbappendstream_locked(&so->so_rcv, m, 0);
1951 /* NB: sorwakeup_locked() does an implicit unlock. */
1952 sorwakeup_locked(so);
1953 if (DELAY_ACK(tp, tlen)) {
1954 tp->t_flags |= TF_DELACK;
1956 tp->t_flags |= TF_ACKNOW;
1957 tp->t_fb->tfb_tcp_output(tp);
1964 * Calculate amount of space in receive window,
1965 * and then do TCP input processing.
1966 * Receive window is amount of space in rcv queue,
1967 * but not less than advertised window.
1969 win = sbspace(&so->so_rcv);
1972 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1974 switch (tp->t_state) {
1977 * If the state is SYN_RECEIVED:
1978 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1980 case TCPS_SYN_RECEIVED:
1981 if ((thflags & TH_ACK) &&
1982 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1983 SEQ_GT(th->th_ack, tp->snd_max))) {
1984 rstreason = BANDLIM_RST_OPENPORT;
1988 if (IS_FASTOPEN(tp->t_flags)) {
1990 * When a TFO connection is in SYN_RECEIVED, the
1991 * only valid packets are the initial SYN, a
1992 * retransmit/copy of the initial SYN (possibly with
1993 * a subset of the original data), a valid ACK, a
1996 if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1997 rstreason = BANDLIM_RST_OPENPORT;
1999 } else if (thflags & TH_SYN) {
2000 /* non-initial SYN is ignored */
2001 if ((tcp_timer_active(tp, TT_DELACK) ||
2002 tcp_timer_active(tp, TT_REXMT)))
2004 } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
2012 * If the state is SYN_SENT:
2013 * if seg contains a RST with valid ACK (SEQ.ACK has already
2014 * been verified), then drop the connection.
2015 * if seg contains a RST without an ACK, drop the seg.
2016 * if seg does not contain SYN, then drop the seg.
2017 * Otherwise this is an acceptable SYN segment
2018 * initialize tp->rcv_nxt and tp->irs
2019 * if seg contains ack then advance tp->snd_una
2020 * if seg contains an ECE and ECN support is enabled, the stream
2022 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2023 * arrange for segment to be acked (eventually)
2024 * continue processing rest of data/controls, beginning with URG
2027 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
2028 TCP_PROBE5(connect__refused, NULL, tp,
2030 tp = tcp_drop(tp, ECONNREFUSED);
2032 if (thflags & TH_RST)
2034 if (!(thflags & TH_SYN))
2037 tp->irs = th->th_seq;
2039 if (thflags & TH_ACK) {
2040 TCPSTAT_INC(tcps_connects);
2043 mac_socketpeer_set_from_mbuf(m, so);
2045 /* Do window scaling on this connection? */
2046 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2047 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2048 tp->rcv_scale = tp->request_r_scale;
2050 tp->rcv_adv += min(tp->rcv_wnd,
2051 TCP_MAXWIN << tp->rcv_scale);
2052 tp->snd_una++; /* SYN is acked */
2054 * If there's data, delay ACK; if there's also a FIN
2055 * ACKNOW will be turned on later.
2057 if (DELAY_ACK(tp, tlen) && tlen != 0)
2058 tcp_timer_activate(tp, TT_DELACK,
2061 tp->t_flags |= TF_ACKNOW;
2063 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
2064 tp->t_flags |= TF_ECN_PERMIT;
2065 TCPSTAT_INC(tcps_ecn_shs);
2069 * Received <SYN,ACK> in SYN_SENT[*] state.
2071 * SYN_SENT --> ESTABLISHED
2072 * SYN_SENT* --> FIN_WAIT_1
2074 tp->t_starttime = ticks;
2075 if (tp->t_flags & TF_NEEDFIN) {
2076 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2077 tp->t_flags &= ~TF_NEEDFIN;
2080 tcp_state_change(tp, TCPS_ESTABLISHED);
2081 TCP_PROBE5(connect__established, NULL, tp,
2084 tcp_timer_activate(tp, TT_KEEP,
2089 * Received initial SYN in SYN-SENT[*] state =>
2090 * simultaneous open.
2091 * If it succeeds, connection is * half-synchronized.
2092 * Otherwise, do 3-way handshake:
2093 * SYN-SENT -> SYN-RECEIVED
2094 * SYN-SENT* -> SYN-RECEIVED*
2096 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2097 tcp_timer_activate(tp, TT_REXMT, 0);
2098 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2101 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
2102 "ti_locked %d", __func__, ti_locked));
2103 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2104 INP_WLOCK_ASSERT(tp->t_inpcb);
2107 * Advance th->th_seq to correspond to first data byte.
2108 * If data, trim to stay within window,
2109 * dropping FIN if necessary.
2112 if (tlen > tp->rcv_wnd) {
2113 todrop = tlen - tp->rcv_wnd;
2117 TCPSTAT_INC(tcps_rcvpackafterwin);
2118 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2120 tp->snd_wl1 = th->th_seq - 1;
2121 tp->rcv_up = th->th_seq;
2123 * Client side of transaction: already sent SYN and data.
2124 * If the remote host used T/TCP to validate the SYN,
2125 * our data will be ACK'd; if so, enter normal data segment
2126 * processing in the middle of step 5, ack processing.
2127 * Otherwise, goto step 6.
2129 if (thflags & TH_ACK)
2135 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2136 * do normal processing.
2138 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2142 break; /* continue normal processing */
2146 * States other than LISTEN or SYN_SENT.
2147 * First check the RST flag and sequence number since reset segments
2148 * are exempt from the timestamp and connection count tests. This
2149 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2150 * below which allowed reset segments in half the sequence space
2151 * to fall though and be processed (which gives forged reset
2152 * segments with a random sequence number a 50 percent chance of
2153 * killing a connection).
2154 * Then check timestamp, if present.
2155 * Then check the connection count, if present.
2156 * Then check that at least some bytes of segment are within
2157 * receive window. If segment begins before rcv_nxt,
2158 * drop leading data (and SYN); if nothing left, just ack.
2160 if (thflags & TH_RST) {
2162 * RFC5961 Section 3.2
2164 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2165 * - If RST is in window, we send challenge ACK.
2167 * Note: to take into account delayed ACKs, we should
2168 * test against last_ack_sent instead of rcv_nxt.
2169 * Note 2: we handle special case of closed window, not
2170 * covered by the RFC.
2172 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2173 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2174 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2176 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2177 KASSERT(ti_locked == TI_RLOCKED,
2178 ("%s: TH_RST ti_locked %d, th %p tp %p",
2179 __func__, ti_locked, th, tp));
2180 KASSERT(tp->t_state != TCPS_SYN_SENT,
2181 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2184 if (V_tcp_insecure_rst ||
2185 tp->last_ack_sent == th->th_seq) {
2186 TCPSTAT_INC(tcps_drops);
2187 /* Drop the connection. */
2188 switch (tp->t_state) {
2189 case TCPS_SYN_RECEIVED:
2190 so->so_error = ECONNREFUSED;
2192 case TCPS_ESTABLISHED:
2193 case TCPS_FIN_WAIT_1:
2194 case TCPS_FIN_WAIT_2:
2195 case TCPS_CLOSE_WAIT:
2198 so->so_error = ECONNRESET;
2205 TCPSTAT_INC(tcps_badrst);
2206 /* Send challenge ACK. */
2207 tcp_respond(tp, mtod(m, void *), th, m,
2208 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2209 tp->last_ack_sent = tp->rcv_nxt;
2217 * RFC5961 Section 4.2
2218 * Send challenge ACK for any SYN in synchronized state.
2220 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
2221 tp->t_state != TCPS_SYN_RECEIVED) {
2222 KASSERT(ti_locked == TI_RLOCKED,
2223 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2224 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2226 TCPSTAT_INC(tcps_badsyn);
2227 if (V_tcp_insecure_syn &&
2228 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2229 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2230 tp = tcp_drop(tp, ECONNRESET);
2231 rstreason = BANDLIM_UNLIMITED;
2233 /* Send challenge ACK. */
2234 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2235 tp->snd_nxt, TH_ACK);
2236 tp->last_ack_sent = tp->rcv_nxt;
2243 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2244 * and it's less than ts_recent, drop it.
2246 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2247 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2249 /* Check to see if ts_recent is over 24 days old. */
2250 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2252 * Invalidate ts_recent. If this segment updates
2253 * ts_recent, the age will be reset later and ts_recent
2254 * will get a valid value. If it does not, setting
2255 * ts_recent to zero will at least satisfy the
2256 * requirement that zero be placed in the timestamp
2257 * echo reply when ts_recent isn't valid. The
2258 * age isn't reset until we get a valid ts_recent
2259 * because we don't want out-of-order segments to be
2260 * dropped when ts_recent is old.
2264 TCPSTAT_INC(tcps_rcvduppack);
2265 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2266 TCPSTAT_INC(tcps_pawsdrop);
2274 * In the SYN-RECEIVED state, validate that the packet belongs to
2275 * this connection before trimming the data to fit the receive
2276 * window. Check the sequence number versus IRS since we know
2277 * the sequence numbers haven't wrapped. This is a partial fix
2278 * for the "LAND" DoS attack.
2280 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2281 rstreason = BANDLIM_RST_OPENPORT;
2285 todrop = tp->rcv_nxt - th->th_seq;
2287 if (thflags & TH_SYN) {
2297 * Following if statement from Stevens, vol. 2, p. 960.
2300 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2302 * Any valid FIN must be to the left of the window.
2303 * At this point the FIN must be a duplicate or out
2304 * of sequence; drop it.
2309 * Send an ACK to resynchronize and drop any data.
2310 * But keep on processing for RST or ACK.
2312 tp->t_flags |= TF_ACKNOW;
2314 TCPSTAT_INC(tcps_rcvduppack);
2315 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2317 TCPSTAT_INC(tcps_rcvpartduppack);
2318 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2320 drop_hdrlen += todrop; /* drop from the top afterwards */
2321 th->th_seq += todrop;
2323 if (th->th_urp > todrop)
2324 th->th_urp -= todrop;
2332 * If new data are received on a connection after the
2333 * user processes are gone, then RST the other end.
2335 if ((so->so_state & SS_NOFDREF) &&
2336 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2337 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
2338 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2339 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2341 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2342 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2343 "after socket was closed, "
2344 "sending RST and removing tcpcb\n",
2345 s, __func__, tcpstates[tp->t_state], tlen);
2349 TCPSTAT_INC(tcps_rcvafterclose);
2350 rstreason = BANDLIM_UNLIMITED;
2355 * If segment ends after window, drop trailing data
2356 * (and PUSH and FIN); if nothing left, just ACK.
2358 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2360 TCPSTAT_INC(tcps_rcvpackafterwin);
2361 if (todrop >= tlen) {
2362 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2364 * If window is closed can only take segments at
2365 * window edge, and have to drop data and PUSH from
2366 * incoming segments. Continue processing, but
2367 * remember to ack. Otherwise, drop segment
2370 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2371 tp->t_flags |= TF_ACKNOW;
2372 TCPSTAT_INC(tcps_rcvwinprobe);
2376 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2379 thflags &= ~(TH_PUSH|TH_FIN);
2383 * If last ACK falls within this segment's sequence numbers,
2384 * record its timestamp.
2386 * 1) That the test incorporates suggestions from the latest
2387 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2388 * 2) That updating only on newer timestamps interferes with
2389 * our earlier PAWS tests, so this check should be solely
2390 * predicated on the sequence space of this segment.
2391 * 3) That we modify the segment boundary check to be
2392 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2393 * instead of RFC1323's
2394 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2395 * This modified check allows us to overcome RFC1323's
2396 * limitations as described in Stevens TCP/IP Illustrated
2397 * Vol. 2 p.869. In such cases, we can still calculate the
2398 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2400 if ((to.to_flags & TOF_TS) != 0 &&
2401 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2402 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2403 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2404 tp->ts_recent_age = tcp_ts_getticks();
2405 tp->ts_recent = to.to_tsval;
2409 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2410 * flag is on (half-synchronized state), then queue data for
2411 * later processing; else drop segment and return.
2413 if ((thflags & TH_ACK) == 0) {
2414 if (tp->t_state == TCPS_SYN_RECEIVED ||
2415 (tp->t_flags & TF_NEEDSYN)) {
2417 if (tp->t_state == TCPS_SYN_RECEIVED &&
2418 IS_FASTOPEN(tp->t_flags)) {
2419 tp->snd_wnd = tiwin;
2424 } else if (tp->t_flags & TF_ACKNOW)
2433 switch (tp->t_state) {
2436 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2437 * ESTABLISHED state and continue processing.
2438 * The ACK was checked above.
2440 case TCPS_SYN_RECEIVED:
2442 TCPSTAT_INC(tcps_connects);
2444 /* Do window scaling? */
2445 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2446 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2447 tp->rcv_scale = tp->request_r_scale;
2448 tp->snd_wnd = tiwin;
2452 * SYN-RECEIVED -> ESTABLISHED
2453 * SYN-RECEIVED* -> FIN-WAIT-1
2455 tp->t_starttime = ticks;
2456 if (tp->t_flags & TF_NEEDFIN) {
2457 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2458 tp->t_flags &= ~TF_NEEDFIN;
2460 tcp_state_change(tp, TCPS_ESTABLISHED);
2461 TCP_PROBE5(accept__established, NULL, tp,
2464 if (tp->t_tfo_pending) {
2465 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2466 tp->t_tfo_pending = NULL;
2469 * Account for the ACK of our SYN prior to
2470 * regular ACK processing below.
2475 * TFO connections call cc_conn_init() during SYN
2476 * processing. Calling it again here for such
2477 * connections is not harmless as it would undo the
2478 * snd_cwnd reduction that occurs when a TFO SYN|ACK
2481 if (!IS_FASTOPEN(tp->t_flags))
2484 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2487 * If segment contains data or ACK, will call tcp_reass()
2488 * later; if not, do so now to pass queued data to user.
2490 if (tlen == 0 && (thflags & TH_FIN) == 0)
2491 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2493 tp->snd_wl1 = th->th_seq - 1;
2497 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2498 * ACKs. If the ack is in the range
2499 * tp->snd_una < th->th_ack <= tp->snd_max
2500 * then advance tp->snd_una to th->th_ack and drop
2501 * data from the retransmission queue. If this ACK reflects
2502 * more up to date window information we update our window information.
2504 case TCPS_ESTABLISHED:
2505 case TCPS_FIN_WAIT_1:
2506 case TCPS_FIN_WAIT_2:
2507 case TCPS_CLOSE_WAIT:
2510 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2511 TCPSTAT_INC(tcps_rcvacktoomuch);
2514 if ((tp->t_flags & TF_SACK_PERMIT) &&
2515 ((to.to_flags & TOF_SACK) ||
2516 !TAILQ_EMPTY(&tp->snd_holes)))
2517 sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2520 * Reset the value so that previous (valid) value
2521 * from the last ack with SACK doesn't get used.
2523 tp->sackhint.sacked_bytes = 0;
2526 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2527 hhook_run_tcp_est_in(tp, th, &to);
2530 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2533 maxseg = tcp_maxseg(tp);
2535 (tiwin == tp->snd_wnd ||
2536 (tp->t_flags & TF_SACK_PERMIT))) {
2538 * If this is the first time we've seen a
2539 * FIN from the remote, this is not a
2540 * duplicate and it needs to be processed
2541 * normally. This happens during a
2542 * simultaneous close.
2544 if ((thflags & TH_FIN) &&
2545 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2549 TCPSTAT_INC(tcps_rcvdupack);
2551 * If we have outstanding data (other than
2552 * a window probe), this is a completely
2553 * duplicate ack (ie, window info didn't
2554 * change and FIN isn't set),
2555 * the ack is the biggest we've
2556 * seen and we've seen exactly our rexmt
2557 * threshold of them, assume a packet
2558 * has been dropped and retransmit it.
2559 * Kludge snd_nxt & the congestion
2560 * window so we send only this one
2563 * We know we're losing at the current
2564 * window size so do congestion avoidance
2565 * (set ssthresh to half the current window
2566 * and pull our congestion window back to
2567 * the new ssthresh).
2569 * Dup acks mean that packets have left the
2570 * network (they're now cached at the receiver)
2571 * so bump cwnd by the amount in the receiver
2572 * to keep a constant cwnd packets in the
2575 * When using TCP ECN, notify the peer that
2576 * we reduced the cwnd.
2579 * Following 2 kinds of acks should not affect
2582 * 2) Acks with SACK but without any new SACK
2583 * information in them. These could result from
2584 * any anomaly in the network like a switch
2585 * duplicating packets or a possible DoS attack.
2587 if (th->th_ack != tp->snd_una ||
2588 ((tp->t_flags & TF_SACK_PERMIT) &&
2591 else if (!tcp_timer_active(tp, TT_REXMT))
2593 else if (++tp->t_dupacks > tcprexmtthresh ||
2594 IN_FASTRECOVERY(tp->t_flags)) {
2595 cc_ack_received(tp, th, nsegs,
2597 if ((tp->t_flags & TF_SACK_PERMIT) &&
2598 IN_FASTRECOVERY(tp->t_flags)) {
2602 * Compute the amount of data in flight first.
2603 * We can inject new data into the pipe iff
2604 * we have less than 1/2 the original window's
2605 * worth of data in flight.
2607 if (V_tcp_do_rfc6675_pipe)
2608 awnd = tcp_compute_pipe(tp);
2610 awnd = (tp->snd_nxt - tp->snd_fack) +
2611 tp->sackhint.sack_bytes_rexmit;
2613 if (awnd < tp->snd_ssthresh) {
2614 tp->snd_cwnd += maxseg;
2616 * RFC5681 Section 3.2 talks about cwnd
2617 * inflation on additional dupacks and
2618 * deflation on recovering from loss.
2620 * We keep cwnd into check so that
2621 * we don't have to 'deflate' it when we
2622 * get out of recovery.
2624 if (tp->snd_cwnd > tp->snd_ssthresh)
2625 tp->snd_cwnd = tp->snd_ssthresh;
2628 tp->snd_cwnd += maxseg;
2629 (void) tp->t_fb->tfb_tcp_output(tp);
2631 } else if (tp->t_dupacks == tcprexmtthresh) {
2632 tcp_seq onxt = tp->snd_nxt;
2635 * If we're doing sack, check to
2636 * see if we're already in sack
2637 * recovery. If we're not doing sack,
2638 * check to see if we're in newreno
2641 if (tp->t_flags & TF_SACK_PERMIT) {
2642 if (IN_FASTRECOVERY(tp->t_flags)) {
2647 if (SEQ_LEQ(th->th_ack,
2653 /* Congestion signal before ack. */
2654 cc_cong_signal(tp, th, CC_NDUPACK);
2655 cc_ack_received(tp, th, nsegs,
2657 tcp_timer_activate(tp, TT_REXMT, 0);
2659 if (tp->t_flags & TF_SACK_PERMIT) {
2661 tcps_sack_recovery_episode);
2662 tp->sack_newdata = tp->snd_nxt;
2663 if (CC_ALGO(tp)->cong_signal == NULL)
2664 tp->snd_cwnd = maxseg;
2665 (void) tp->t_fb->tfb_tcp_output(tp);
2668 tp->snd_nxt = th->th_ack;
2669 if (CC_ALGO(tp)->cong_signal == NULL)
2670 tp->snd_cwnd = maxseg;
2671 (void) tp->t_fb->tfb_tcp_output(tp);
2672 KASSERT(tp->snd_limited <= 2,
2673 ("%s: tp->snd_limited too big",
2675 if (CC_ALGO(tp)->cong_signal == NULL)
2676 tp->snd_cwnd = tp->snd_ssthresh +
2678 (tp->t_dupacks - tp->snd_limited);
2679 if (SEQ_GT(onxt, tp->snd_nxt))
2682 } else if (V_tcp_do_rfc3042) {
2684 * Process first and second duplicate
2685 * ACKs. Each indicates a segment
2686 * leaving the network, creating room
2687 * for more. Make sure we can send a
2688 * packet on reception of each duplicate
2689 * ACK by increasing snd_cwnd by one
2690 * segment. Restore the original
2691 * snd_cwnd after packet transmission.
2693 cc_ack_received(tp, th, nsegs,
2695 uint32_t oldcwnd = tp->snd_cwnd;
2696 tcp_seq oldsndmax = tp->snd_max;
2700 KASSERT(tp->t_dupacks == 1 ||
2702 ("%s: dupacks not 1 or 2",
2704 if (tp->t_dupacks == 1)
2705 tp->snd_limited = 0;
2707 (tp->snd_nxt - tp->snd_una) +
2708 (tp->t_dupacks - tp->snd_limited) *
2711 * Only call tcp_output when there
2712 * is new data available to be sent.
2713 * Otherwise we would send pure ACKs.
2715 SOCKBUF_LOCK(&so->so_snd);
2716 avail = sbavail(&so->so_snd) -
2717 (tp->snd_nxt - tp->snd_una);
2718 SOCKBUF_UNLOCK(&so->so_snd);
2720 (void) tp->t_fb->tfb_tcp_output(tp);
2721 sent = tp->snd_max - oldsndmax;
2722 if (sent > maxseg) {
2723 KASSERT((tp->t_dupacks == 2 &&
2724 tp->snd_limited == 0) ||
2725 (sent == maxseg + 1 &&
2726 tp->t_flags & TF_SENTFIN),
2727 ("%s: sent too much",
2729 tp->snd_limited = 2;
2730 } else if (sent > 0)
2732 tp->snd_cwnd = oldcwnd;
2739 * This ack is advancing the left edge, reset the
2744 * If this ack also has new SACK info, increment the
2745 * counter as per rfc6675.
2747 if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2751 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2752 ("%s: th_ack <= snd_una", __func__));
2755 * If the congestion window was inflated to account
2756 * for the other side's cached packets, retract it.
2758 if (IN_FASTRECOVERY(tp->t_flags)) {
2759 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2760 if (tp->t_flags & TF_SACK_PERMIT)
2761 tcp_sack_partialack(tp, th);
2763 tcp_newreno_partial_ack(tp, th);
2765 cc_post_recovery(tp, th);
2768 * If we reach this point, ACK is not a duplicate,
2769 * i.e., it ACKs something we sent.
2771 if (tp->t_flags & TF_NEEDSYN) {
2773 * T/TCP: Connection was half-synchronized, and our
2774 * SYN has been ACK'd (so connection is now fully
2775 * synchronized). Go to non-starred state,
2776 * increment snd_una for ACK of SYN, and check if
2777 * we can do window scaling.
2779 tp->t_flags &= ~TF_NEEDSYN;
2781 /* Do window scaling? */
2782 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2783 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2784 tp->rcv_scale = tp->request_r_scale;
2785 /* Send window already scaled. */
2790 INP_WLOCK_ASSERT(tp->t_inpcb);
2792 acked = BYTES_THIS_ACK(tp, th);
2793 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2794 "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2795 tp->snd_una, th->th_ack, tp, m));
2796 TCPSTAT_ADD(tcps_rcvackpack, nsegs);
2797 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2800 * If we just performed our first retransmit, and the ACK
2801 * arrives within our recovery window, then it was a mistake
2802 * to do the retransmit in the first place. Recover our
2803 * original cwnd and ssthresh, and proceed to transmit where
2806 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2807 (int)(ticks - tp->t_badrxtwin) < 0)
2808 cc_cong_signal(tp, th, CC_RTO_ERR);
2811 * If we have a timestamp reply, update smoothed
2812 * round trip time. If no timestamp is present but
2813 * transmit timer is running and timed sequence
2814 * number was acked, update smoothed round trip time.
2815 * Since we now have an rtt measurement, cancel the
2816 * timer backoff (cf., Phil Karn's retransmit alg.).
2817 * Recompute the initial retransmit timer.
2819 * Some boxes send broken timestamp replies
2820 * during the SYN+ACK phase, ignore
2821 * timestamps of 0 or we could calculate a
2822 * huge RTT and blow up the retransmit timer.
2824 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2827 t = tcp_ts_getticks() - to.to_tsecr;
2828 if (!tp->t_rttlow || tp->t_rttlow > t)
2830 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2831 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2832 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2833 tp->t_rttlow = ticks - tp->t_rtttime;
2834 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2838 * If all outstanding data is acked, stop retransmit
2839 * timer and remember to restart (more output or persist).
2840 * If there is more data to be acked, restart retransmit
2841 * timer, using current (possibly backed-off) value.
2843 if (th->th_ack == tp->snd_max) {
2844 tcp_timer_activate(tp, TT_REXMT, 0);
2846 } else if (!tcp_timer_active(tp, TT_PERSIST))
2847 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2850 * If no data (only SYN) was ACK'd,
2851 * skip rest of ACK processing.
2857 * Let the congestion control algorithm update congestion
2858 * control related information. This typically means increasing
2859 * the congestion window.
2861 cc_ack_received(tp, th, nsegs, CC_ACK);
2863 SOCKBUF_LOCK(&so->so_snd);
2864 if (acked > sbavail(&so->so_snd)) {
2865 if (tp->snd_wnd >= sbavail(&so->so_snd))
2866 tp->snd_wnd -= sbavail(&so->so_snd);
2869 mfree = sbcut_locked(&so->so_snd,
2870 (int)sbavail(&so->so_snd));
2873 mfree = sbcut_locked(&so->so_snd, acked);
2874 if (tp->snd_wnd >= (uint32_t) acked)
2875 tp->snd_wnd -= acked;
2880 /* NB: sowwakeup_locked() does an implicit unlock. */
2881 sowwakeup_locked(so);
2883 /* Detect una wraparound. */
2884 if (!IN_RECOVERY(tp->t_flags) &&
2885 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2886 SEQ_LEQ(th->th_ack, tp->snd_recover))
2887 tp->snd_recover = th->th_ack - 1;
2888 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2889 if (IN_RECOVERY(tp->t_flags) &&
2890 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2891 EXIT_RECOVERY(tp->t_flags);
2893 tp->snd_una = th->th_ack;
2894 if (tp->t_flags & TF_SACK_PERMIT) {
2895 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2896 tp->snd_recover = tp->snd_una;
2898 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2899 tp->snd_nxt = tp->snd_una;
2901 switch (tp->t_state) {
2904 * In FIN_WAIT_1 STATE in addition to the processing
2905 * for the ESTABLISHED state if our FIN is now acknowledged
2906 * then enter FIN_WAIT_2.
2908 case TCPS_FIN_WAIT_1:
2909 if (ourfinisacked) {
2911 * If we can't receive any more
2912 * data, then closing user can proceed.
2913 * Starting the timer is contrary to the
2914 * specification, but if we don't get a FIN
2915 * we'll hang forever.
2918 * we should release the tp also, and use a
2921 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2922 soisdisconnected(so);
2923 tcp_timer_activate(tp, TT_2MSL,
2924 (tcp_fast_finwait2_recycle ?
2925 tcp_finwait2_timeout :
2928 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2933 * In CLOSING STATE in addition to the processing for
2934 * the ESTABLISHED state if the ACK acknowledges our FIN
2935 * then enter the TIME-WAIT state, otherwise ignore
2939 if (ourfinisacked) {
2940 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2942 INP_INFO_RUNLOCK(&V_tcbinfo);
2949 * In LAST_ACK, we may still be waiting for data to drain
2950 * and/or to be acked, as well as for the ack of our FIN.
2951 * If our FIN is now acknowledged, delete the TCB,
2952 * enter the closed state and return.
2955 if (ourfinisacked) {
2956 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2965 INP_WLOCK_ASSERT(tp->t_inpcb);
2968 * Update window information.
2969 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2971 if ((thflags & TH_ACK) &&
2972 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2973 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2974 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2975 /* keep track of pure window updates */
2977 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2978 TCPSTAT_INC(tcps_rcvwinupd);
2979 tp->snd_wnd = tiwin;
2980 tp->snd_wl1 = th->th_seq;
2981 tp->snd_wl2 = th->th_ack;
2982 if (tp->snd_wnd > tp->max_sndwnd)
2983 tp->max_sndwnd = tp->snd_wnd;
2988 * Process segments with URG.
2990 if ((thflags & TH_URG) && th->th_urp &&
2991 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2993 * This is a kludge, but if we receive and accept
2994 * random urgent pointers, we'll crash in
2995 * soreceive. It's hard to imagine someone
2996 * actually wanting to send this much urgent data.
2998 SOCKBUF_LOCK(&so->so_rcv);
2999 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
3000 th->th_urp = 0; /* XXX */
3001 thflags &= ~TH_URG; /* XXX */
3002 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
3003 goto dodata; /* XXX */
3006 * If this segment advances the known urgent pointer,
3007 * then mark the data stream. This should not happen
3008 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
3009 * a FIN has been received from the remote side.
3010 * In these states we ignore the URG.
3012 * According to RFC961 (Assigned Protocols),
3013 * the urgent pointer points to the last octet
3014 * of urgent data. We continue, however,
3015 * to consider it to indicate the first octet
3016 * of data past the urgent section as the original
3017 * spec states (in one of two places).
3019 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
3020 tp->rcv_up = th->th_seq + th->th_urp;
3021 so->so_oobmark = sbavail(&so->so_rcv) +
3022 (tp->rcv_up - tp->rcv_nxt) - 1;
3023 if (so->so_oobmark == 0)
3024 so->so_rcv.sb_state |= SBS_RCVATMARK;
3026 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
3028 SOCKBUF_UNLOCK(&so->so_rcv);
3030 * Remove out of band data so doesn't get presented to user.
3031 * This can happen independent of advancing the URG pointer,
3032 * but if two URG's are pending at once, some out-of-band
3033 * data may creep in... ick.
3035 if (th->th_urp <= (uint32_t)tlen &&
3036 !(so->so_options & SO_OOBINLINE)) {
3037 /* hdr drop is delayed */
3038 tcp_pulloutofband(so, th, m, drop_hdrlen);
3042 * If no out of band data is expected,
3043 * pull receive urgent pointer along
3044 * with the receive window.
3046 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
3047 tp->rcv_up = tp->rcv_nxt;
3050 INP_WLOCK_ASSERT(tp->t_inpcb);
3053 * Process the segment text, merging it into the TCP sequencing queue,
3054 * and arranging for acknowledgment of receipt if necessary.
3055 * This process logically involves adjusting tp->rcv_wnd as data
3056 * is presented to the user (this happens in tcp_usrreq.c,
3057 * case PRU_RCVD). If a FIN has already been received on this
3058 * connection then we just ignore the text.
3061 tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3062 IS_FASTOPEN(tp->t_flags));
3064 #define tfo_syn (false)
3066 if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
3067 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3068 tcp_seq save_start = th->th_seq;
3069 m_adj(m, drop_hdrlen); /* delayed header drop */
3071 * Insert segment which includes th into TCP reassembly queue
3072 * with control block tp. Set thflags to whether reassembly now
3073 * includes a segment with FIN. This handles the common case
3074 * inline (segment is the next to be received on an established
3075 * connection, and the queue is empty), avoiding linkage into
3076 * and removal from the queue and repetition of various
3078 * Set DELACK for segments received in order, but ack
3079 * immediately when segments are out of order (so
3080 * fast retransmit can work).
3082 if (th->th_seq == tp->rcv_nxt &&
3083 LIST_EMPTY(&tp->t_segq) &&
3084 (TCPS_HAVEESTABLISHED(tp->t_state) ||
3086 if (DELAY_ACK(tp, tlen) || tfo_syn)
3087 tp->t_flags |= TF_DELACK;
3089 tp->t_flags |= TF_ACKNOW;
3090 tp->rcv_nxt += tlen;
3091 thflags = th->th_flags & TH_FIN;
3092 TCPSTAT_INC(tcps_rcvpack);
3093 TCPSTAT_ADD(tcps_rcvbyte, tlen);
3094 SOCKBUF_LOCK(&so->so_rcv);
3095 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3098 sbappendstream_locked(&so->so_rcv, m, 0);
3099 /* NB: sorwakeup_locked() does an implicit unlock. */
3100 sorwakeup_locked(so);
3103 * XXX: Due to the header drop above "th" is
3104 * theoretically invalid by now. Fortunately
3105 * m_adj() doesn't actually frees any mbufs
3106 * when trimming from the head.
3108 thflags = tcp_reass(tp, th, &tlen, m);
3109 tp->t_flags |= TF_ACKNOW;
3111 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
3112 tcp_update_sack_list(tp, save_start, save_start + tlen);
3115 * Note the amount of data that peer has sent into
3116 * our window, in order to estimate the sender's
3120 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3121 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3123 len = so->so_rcv.sb_hiwat;
3131 * If FIN is received ACK the FIN and let the user know
3132 * that the connection is closing.
3134 if (thflags & TH_FIN) {
3135 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3138 * If connection is half-synchronized
3139 * (ie NEEDSYN flag on) then delay ACK,
3140 * so it may be piggybacked when SYN is sent.
3141 * Otherwise, since we received a FIN then no
3142 * more input can be expected, send ACK now.
3144 if (tp->t_flags & TF_NEEDSYN)
3145 tp->t_flags |= TF_DELACK;
3147 tp->t_flags |= TF_ACKNOW;
3150 switch (tp->t_state) {
3153 * In SYN_RECEIVED and ESTABLISHED STATES
3154 * enter the CLOSE_WAIT state.
3156 case TCPS_SYN_RECEIVED:
3157 tp->t_starttime = ticks;
3159 case TCPS_ESTABLISHED:
3160 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3164 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3165 * enter the CLOSING state.
3167 case TCPS_FIN_WAIT_1:
3168 tcp_state_change(tp, TCPS_CLOSING);
3172 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3173 * starting the time-wait timer, turning off the other
3176 case TCPS_FIN_WAIT_2:
3177 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3178 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
3179 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3183 INP_INFO_RUNLOCK(&V_tcbinfo);
3187 if (ti_locked == TI_RLOCKED)
3188 INP_INFO_RUNLOCK(&V_tcbinfo);
3189 ti_locked = TI_UNLOCKED;
3192 if (so->so_options & SO_DEBUG)
3193 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3196 TCP_PROBE3(debug__input, tp, th, m);
3199 * Return any desired output.
3201 if (needoutput || (tp->t_flags & TF_ACKNOW))
3202 (void) tp->t_fb->tfb_tcp_output(tp);
3205 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3206 __func__, ti_locked));
3207 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3208 INP_WLOCK_ASSERT(tp->t_inpcb);
3210 if (tp->t_flags & TF_DELACK) {
3211 tp->t_flags &= ~TF_DELACK;
3212 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3214 INP_WUNLOCK(tp->t_inpcb);
3219 * Generate an ACK dropping incoming segment if it occupies
3220 * sequence space, where the ACK reflects our state.
3222 * We can now skip the test for the RST flag since all
3223 * paths to this code happen after packets containing
3224 * RST have been dropped.
3226 * In the SYN-RECEIVED state, don't send an ACK unless the
3227 * segment we received passes the SYN-RECEIVED ACK test.
3228 * If it fails send a RST. This breaks the loop in the
3229 * "LAND" DoS attack, and also prevents an ACK storm
3230 * between two listening ports that have been sent forged
3231 * SYN segments, each with the source address of the other.
3233 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3234 (SEQ_GT(tp->snd_una, th->th_ack) ||
3235 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3236 rstreason = BANDLIM_RST_OPENPORT;
3240 if (so->so_options & SO_DEBUG)
3241 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3244 TCP_PROBE3(debug__input, tp, th, m);
3245 if (ti_locked == TI_RLOCKED)
3246 INP_INFO_RUNLOCK(&V_tcbinfo);
3247 ti_locked = TI_UNLOCKED;
3249 tp->t_flags |= TF_ACKNOW;
3250 (void) tp->t_fb->tfb_tcp_output(tp);
3251 INP_WUNLOCK(tp->t_inpcb);
3256 if (ti_locked == TI_RLOCKED)
3257 INP_INFO_RUNLOCK(&V_tcbinfo);
3258 ti_locked = TI_UNLOCKED;
3261 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3262 INP_WUNLOCK(tp->t_inpcb);
3264 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3268 if (ti_locked == TI_RLOCKED) {
3269 INP_INFO_RUNLOCK(&V_tcbinfo);
3270 ti_locked = TI_UNLOCKED;
3274 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3278 * Drop space held by incoming segment and return.
3281 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3282 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3285 TCP_PROBE3(debug__input, tp, th, m);
3287 INP_WUNLOCK(tp->t_inpcb);
3295 * Issue RST and make ACK acceptable to originator of segment.
3296 * The mbuf must still include the original packet header.
3300 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3301 int tlen, int rstreason)
3307 struct ip6_hdr *ip6;
3311 INP_WLOCK_ASSERT(tp->t_inpcb);
3314 /* Don't bother if destination was broadcast/multicast. */
3315 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3318 if (mtod(m, struct ip *)->ip_v == 6) {
3319 ip6 = mtod(m, struct ip6_hdr *);
3320 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3321 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3323 /* IPv6 anycast check is done at tcp6_input() */
3326 #if defined(INET) && defined(INET6)
3331 ip = mtod(m, struct ip *);
3332 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3333 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3334 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3335 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3340 /* Perform bandwidth limiting. */
3341 if (badport_bandlim(rstreason) < 0)
3344 /* tcp_respond consumes the mbuf chain. */
3345 if (th->th_flags & TH_ACK) {
3346 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3347 th->th_ack, TH_RST);
3349 if (th->th_flags & TH_SYN)
3351 if (th->th_flags & TH_FIN)
3353 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3354 (tcp_seq)0, TH_RST|TH_ACK);
3362 * Parse TCP options and place in tcpopt.
3365 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3370 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3372 if (opt == TCPOPT_EOL)
3374 if (opt == TCPOPT_NOP)
3380 if (optlen < 2 || optlen > cnt)
3385 if (optlen != TCPOLEN_MAXSEG)
3387 if (!(flags & TO_SYN))
3389 to->to_flags |= TOF_MSS;
3390 bcopy((char *)cp + 2,
3391 (char *)&to->to_mss, sizeof(to->to_mss));
3392 to->to_mss = ntohs(to->to_mss);
3395 if (optlen != TCPOLEN_WINDOW)
3397 if (!(flags & TO_SYN))
3399 to->to_flags |= TOF_SCALE;
3400 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3402 case TCPOPT_TIMESTAMP:
3403 if (optlen != TCPOLEN_TIMESTAMP)
3405 to->to_flags |= TOF_TS;
3406 bcopy((char *)cp + 2,
3407 (char *)&to->to_tsval, sizeof(to->to_tsval));
3408 to->to_tsval = ntohl(to->to_tsval);
3409 bcopy((char *)cp + 6,
3410 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3411 to->to_tsecr = ntohl(to->to_tsecr);
3413 case TCPOPT_SIGNATURE:
3415 * In order to reply to a host which has set the
3416 * TCP_SIGNATURE option in its initial SYN, we have
3417 * to record the fact that the option was observed
3418 * here for the syncache code to perform the correct
3421 if (optlen != TCPOLEN_SIGNATURE)
3423 to->to_flags |= TOF_SIGNATURE;
3424 to->to_signature = cp + 2;
3426 case TCPOPT_SACK_PERMITTED:
3427 if (optlen != TCPOLEN_SACK_PERMITTED)
3429 if (!(flags & TO_SYN))
3433 to->to_flags |= TOF_SACKPERM;
3436 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3440 to->to_flags |= TOF_SACK;
3441 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3442 to->to_sacks = cp + 2;
3443 TCPSTAT_INC(tcps_sack_rcv_blocks);
3446 case TCPOPT_FAST_OPEN:
3447 if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
3448 (optlen < TCPOLEN_FAST_OPEN_MIN) &&
3449 (optlen > TCPOLEN_FAST_OPEN_MAX))
3451 if (!(flags & TO_SYN))
3453 if (!V_tcp_fastopen_enabled)
3455 to->to_flags |= TOF_FASTOPEN;
3456 to->to_tfo_len = optlen - 2;
3457 to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3467 * Pull out of band byte out of a segment so
3468 * it doesn't appear in the user's data queue.
3469 * It is still reflected in the segment length for
3470 * sequencing purposes.
3473 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3476 int cnt = off + th->th_urp - 1;
3479 if (m->m_len > cnt) {
3480 char *cp = mtod(m, caddr_t) + cnt;
3481 struct tcpcb *tp = sototcpcb(so);
3483 INP_WLOCK_ASSERT(tp->t_inpcb);
3486 tp->t_oobflags |= TCPOOB_HAVEDATA;
3487 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3489 if (m->m_flags & M_PKTHDR)
3498 panic("tcp_pulloutofband");
3502 * Collect new round-trip time estimate
3503 * and update averages and current timeout.
3506 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3510 INP_WLOCK_ASSERT(tp->t_inpcb);
3512 TCPSTAT_INC(tcps_rttupdated);
3514 if ((tp->t_srtt != 0) && (tp->t_rxtshift <= TCP_RTT_INVALIDATE)) {
3516 * srtt is stored as fixed point with 5 bits after the
3517 * binary point (i.e., scaled by 8). The following magic
3518 * is equivalent to the smoothing algorithm in rfc793 with
3519 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3520 * point). Adjust rtt to origin 0.
3522 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3523 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3525 if ((tp->t_srtt += delta) <= 0)
3529 * We accumulate a smoothed rtt variance (actually, a
3530 * smoothed mean difference), then set the retransmit
3531 * timer to smoothed rtt + 4 times the smoothed variance.
3532 * rttvar is stored as fixed point with 4 bits after the
3533 * binary point (scaled by 16). The following is
3534 * equivalent to rfc793 smoothing with an alpha of .75
3535 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3536 * rfc793's wired-in beta.
3540 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3541 if ((tp->t_rttvar += delta) <= 0)
3543 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3544 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3547 * No rtt measurement yet - use the unsmoothed rtt.
3548 * Set the variance to half the rtt (so our first
3549 * retransmit happens at 3*rtt).
3551 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3552 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3553 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3559 * the retransmit should happen at rtt + 4 * rttvar.
3560 * Because of the way we do the smoothing, srtt and rttvar
3561 * will each average +1/2 tick of bias. When we compute
3562 * the retransmit timer, we want 1/2 tick of rounding and
3563 * 1 extra tick because of +-1/2 tick uncertainty in the
3564 * firing of the timer. The bias will give us exactly the
3565 * 1.5 tick we need. But, because the bias is
3566 * statistical, we have to test that we don't drop below
3567 * the minimum feasible timer (which is 2 ticks).
3569 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3570 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3573 * We received an ack for a packet that wasn't retransmitted;
3574 * it is probably safe to discard any error indications we've
3575 * received recently. This isn't quite right, but close enough
3576 * for now (a route might have failed after we sent a segment,
3577 * and the return path might not be symmetrical).
3579 tp->t_softerror = 0;
3583 * Determine a reasonable value for maxseg size.
3584 * If the route is known, check route for mtu.
3585 * If none, use an mss that can be handled on the outgoing interface
3586 * without forcing IP to fragment. If no route is found, route has no mtu,
3587 * or the destination isn't local, use a default, hopefully conservative
3588 * size (usually 512 or the default IP max size, but no more than the mtu
3589 * of the interface), as we can't discover anything about intervening
3590 * gateways or networks. We also initialize the congestion/slow start
3591 * window to be a single segment if the destination isn't local.
3592 * While looking at the routing entry, we also initialize other path-dependent
3593 * parameters from pre-set or cached values in the routing entry.
3595 * NOTE that resulting t_maxseg doesn't include space for TCP options or
3596 * IP options, e.g. IPSEC data, since length of this data may vary, and
3597 * thus it is calculated for every segment separately in tcp_output().
3599 * NOTE that this routine is only called when we process an incoming
3600 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3601 * settings are handled in tcp_mssopt().
3604 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3605 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3608 uint32_t maxmtu = 0;
3609 struct inpcb *inp = tp->t_inpcb;
3610 struct hc_metrics_lite metrics;
3612 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3613 size_t min_protoh = isipv6 ?
3614 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3615 sizeof (struct tcpiphdr);
3617 const size_t min_protoh = sizeof(struct tcpiphdr);
3620 INP_WLOCK_ASSERT(tp->t_inpcb);
3622 if (mtuoffer != -1) {
3623 KASSERT(offer == -1, ("%s: conflict", __func__));
3624 offer = mtuoffer - min_protoh;
3630 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3631 tp->t_maxseg = V_tcp_v6mssdflt;
3634 #if defined(INET) && defined(INET6)
3639 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3640 tp->t_maxseg = V_tcp_mssdflt;
3645 * No route to sender, stay with default mss and return.
3649 * In case we return early we need to initialize metrics
3650 * to a defined state as tcp_hc_get() would do for us
3651 * if there was no cache hit.
3653 if (metricptr != NULL)
3654 bzero(metricptr, sizeof(struct hc_metrics_lite));
3658 /* What have we got? */
3662 * Offer == 0 means that there was no MSS on the SYN
3663 * segment, in this case we use tcp_mssdflt as
3664 * already assigned to t_maxseg above.
3666 offer = tp->t_maxseg;
3671 * Offer == -1 means that we didn't receive SYN yet.
3677 * Prevent DoS attack with too small MSS. Round up
3678 * to at least minmss.
3680 offer = max(offer, V_tcp_minmss);
3684 * rmx information is now retrieved from tcp_hostcache.
3686 tcp_hc_get(&inp->inp_inc, &metrics);
3687 if (metricptr != NULL)
3688 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3691 * If there's a discovered mtu in tcp hostcache, use it.
3692 * Else, use the link mtu.
3694 if (metrics.rmx_mtu)
3695 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3699 mss = maxmtu - min_protoh;
3700 if (!V_path_mtu_discovery &&
3701 !in6_localaddr(&inp->in6p_faddr))
3702 mss = min(mss, V_tcp_v6mssdflt);
3705 #if defined(INET) && defined(INET6)
3710 mss = maxmtu - min_protoh;
3711 if (!V_path_mtu_discovery &&
3712 !in_localaddr(inp->inp_faddr))
3713 mss = min(mss, V_tcp_mssdflt);
3717 * XXX - The above conditional (mss = maxmtu - min_protoh)
3718 * probably violates the TCP spec.
3719 * The problem is that, since we don't know the
3720 * other end's MSS, we are supposed to use a conservative
3721 * default. But, if we do that, then MTU discovery will
3722 * never actually take place, because the conservative
3723 * default is much less than the MTUs typically seen
3724 * on the Internet today. For the moment, we'll sweep
3725 * this under the carpet.
3727 * The conservative default might not actually be a problem
3728 * if the only case this occurs is when sending an initial
3729 * SYN with options and data to a host we've never talked
3730 * to before. Then, they will reply with an MSS value which
3731 * will get recorded and the new parameters should get
3732 * recomputed. For Further Study.
3735 mss = min(mss, offer);
3738 * Sanity check: make sure that maxseg will be large
3739 * enough to allow some data on segments even if the
3740 * all the option space is used (40bytes). Otherwise
3741 * funny things may happen in tcp_output.
3743 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3751 tcp_mss(struct tcpcb *tp, int offer)
3757 struct hc_metrics_lite metrics;
3758 struct tcp_ifcap cap;
3760 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3762 bzero(&cap, sizeof(cap));
3763 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3769 * If there's a pipesize, change the socket buffer to that size,
3770 * don't change if sb_hiwat is different than default (then it
3771 * has been changed on purpose with setsockopt).
3772 * Make the socket buffers an integral number of mss units;
3773 * if the mss is larger than the socket buffer, decrease the mss.
3775 so = inp->inp_socket;
3776 SOCKBUF_LOCK(&so->so_snd);
3777 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3778 bufsize = metrics.rmx_sendpipe;
3780 bufsize = so->so_snd.sb_hiwat;
3784 bufsize = roundup(bufsize, mss);
3785 if (bufsize > sb_max)
3787 if (bufsize > so->so_snd.sb_hiwat)
3788 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3790 SOCKBUF_UNLOCK(&so->so_snd);
3792 * Sanity check: make sure that maxseg will be large
3793 * enough to allow some data on segments even if the
3794 * all the option space is used (40bytes). Otherwise
3795 * funny things may happen in tcp_output.
3797 * XXXGL: shouldn't we reserve space for IP/IPv6 options?
3799 tp->t_maxseg = max(mss, 64);
3801 SOCKBUF_LOCK(&so->so_rcv);
3802 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3803 bufsize = metrics.rmx_recvpipe;
3805 bufsize = so->so_rcv.sb_hiwat;
3806 if (bufsize > mss) {
3807 bufsize = roundup(bufsize, mss);
3808 if (bufsize > sb_max)
3810 if (bufsize > so->so_rcv.sb_hiwat)
3811 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3813 SOCKBUF_UNLOCK(&so->so_rcv);
3815 /* Check the interface for TSO capabilities. */
3816 if (cap.ifcap & CSUM_TSO) {
3817 tp->t_flags |= TF_TSO;
3818 tp->t_tsomax = cap.tsomax;
3819 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3820 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3825 * Determine the MSS option to send on an outgoing SYN.
3828 tcp_mssopt(struct in_conninfo *inc)
3831 uint32_t thcmtu = 0;
3832 uint32_t maxmtu = 0;
3835 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3838 if (inc->inc_flags & INC_ISIPV6) {
3839 mss = V_tcp_v6mssdflt;
3840 maxmtu = tcp_maxmtu6(inc, NULL);
3841 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3844 #if defined(INET) && defined(INET6)
3849 mss = V_tcp_mssdflt;
3850 maxmtu = tcp_maxmtu(inc, NULL);
3851 min_protoh = sizeof(struct tcpiphdr);
3854 #if defined(INET6) || defined(INET)
3855 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3858 if (maxmtu && thcmtu)
3859 mss = min(maxmtu, thcmtu) - min_protoh;
3860 else if (maxmtu || thcmtu)
3861 mss = max(maxmtu, thcmtu) - min_protoh;
3868 * On a partial ack arrives, force the retransmission of the
3869 * next unacknowledged segment. Do not clear tp->t_dupacks.
3870 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3874 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3876 tcp_seq onxt = tp->snd_nxt;
3877 uint32_t ocwnd = tp->snd_cwnd;
3878 u_int maxseg = tcp_maxseg(tp);
3880 INP_WLOCK_ASSERT(tp->t_inpcb);
3882 tcp_timer_activate(tp, TT_REXMT, 0);
3884 tp->snd_nxt = th->th_ack;
3886 * Set snd_cwnd to one segment beyond acknowledged offset.
3887 * (tp->snd_una has not yet been updated when this function is called.)
3889 tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
3890 tp->t_flags |= TF_ACKNOW;
3891 (void) tp->t_fb->tfb_tcp_output(tp);
3892 tp->snd_cwnd = ocwnd;
3893 if (SEQ_GT(onxt, tp->snd_nxt))
3896 * Partial window deflation. Relies on fact that tp->snd_una
3899 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3900 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3903 tp->snd_cwnd += maxseg;
3907 tcp_compute_pipe(struct tcpcb *tp)
3909 return (tp->snd_max - tp->snd_una +
3910 tp->sackhint.sack_bytes_rexmit -
3911 tp->sackhint.sacked_bytes);