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
10 * Portions of this software were developed at the Centre for Advanced Internet
11 * Architectures, Swinburne University, by Lawrence Stewart, James Healy and
12 * David Hayes, made possible in part by a grant from the Cisco University
13 * Research Program Fund at Community Foundation Silicon Valley.
15 * Portions of this software were developed at the Centre for Advanced
16 * Internet Architectures, Swinburne University of Technology, Melbourne,
17 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 4. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 #include "opt_ipfw.h" /* for ipfw_fwd */
51 #include "opt_inet6.h"
52 #include "opt_ipsec.h"
53 #include "opt_tcpdebug.h"
55 #include <sys/param.h>
56 #include <sys/kernel.h>
57 #include <sys/malloc.h>
59 #include <sys/proc.h> /* for proc0 declaration */
60 #include <sys/protosw.h>
61 #include <sys/signalvar.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/systm.h>
68 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
73 #include <net/route.h>
76 #define TCPSTATES /* for logging */
78 #include <netinet/cc.h>
79 #include <netinet/in.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/in_var.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
85 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip_options.h>
88 #include <netinet/ip6.h>
89 #include <netinet/icmp6.h>
90 #include <netinet6/in6_pcb.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet6/nd6.h>
93 #include <netinet/tcp_fsm.h>
94 #include <netinet/tcp_seq.h>
95 #include <netinet/tcp_timer.h>
96 #include <netinet/tcp_var.h>
97 #include <netinet6/tcp6_var.h>
98 #include <netinet/tcpip.h>
99 #include <netinet/tcp_syncache.h>
101 #include <netinet/tcp_debug.h>
102 #endif /* TCPDEBUG */
105 #include <netipsec/ipsec.h>
106 #include <netipsec/ipsec6.h>
109 #include <machine/in_cksum.h>
111 #include <security/mac/mac_framework.h>
113 const int tcprexmtthresh = 3;
115 VNET_DEFINE(struct tcpstat, tcpstat);
116 SYSCTL_VNET_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
117 &VNET_NAME(tcpstat), tcpstat,
118 "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
120 int tcp_log_in_vain = 0;
121 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
123 "Log all incoming TCP segments to closed ports");
125 VNET_DEFINE(int, blackhole) = 0;
126 #define V_blackhole VNET(blackhole)
127 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
128 &VNET_NAME(blackhole), 0,
129 "Do not send RST on segments to closed ports");
131 VNET_DEFINE(int, tcp_delack_enabled) = 1;
132 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
133 &VNET_NAME(tcp_delack_enabled), 0,
134 "Delay ACK to try and piggyback it onto a data packet");
136 VNET_DEFINE(int, drop_synfin) = 0;
137 #define V_drop_synfin VNET(drop_synfin)
138 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
139 &VNET_NAME(drop_synfin), 0,
140 "Drop TCP packets with SYN+FIN set");
142 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
143 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
144 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
145 &VNET_NAME(tcp_do_rfc3042), 0,
146 "Enable RFC 3042 (Limited Transmit)");
148 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
149 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
150 &VNET_NAME(tcp_do_rfc3390), 0,
151 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
153 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
154 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
155 &VNET_NAME(tcp_do_rfc3465), 0,
156 "Enable RFC 3465 (Appropriate Byte Counting)");
158 VNET_DEFINE(int, tcp_abc_l_var) = 2;
159 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
160 &VNET_NAME(tcp_abc_l_var), 2,
161 "Cap the max cwnd increment during slow-start to this number of segments");
163 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
165 VNET_DEFINE(int, tcp_do_ecn) = 0;
166 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
167 &VNET_NAME(tcp_do_ecn), 0,
170 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
171 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
172 &VNET_NAME(tcp_ecn_maxretries), 0,
173 "Max retries before giving up on ECN");
175 VNET_DEFINE(int, tcp_insecure_rst) = 0;
176 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
177 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
178 &VNET_NAME(tcp_insecure_rst), 0,
179 "Follow the old (insecure) criteria for accepting RST packets");
181 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
182 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
183 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
184 &VNET_NAME(tcp_do_autorcvbuf), 0,
185 "Enable automatic receive buffer sizing");
187 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
188 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
189 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
190 &VNET_NAME(tcp_autorcvbuf_inc), 0,
191 "Incrementor step size of automatic receive buffer");
193 VNET_DEFINE(int, tcp_autorcvbuf_max) = 256*1024;
194 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
195 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
196 &VNET_NAME(tcp_autorcvbuf_max), 0,
197 "Max size of automatic receive buffer");
199 int tcp_read_locking = 1;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, read_locking, CTLFLAG_RW,
201 &tcp_read_locking, 0, "Enable read locking strategy");
203 VNET_DEFINE(struct inpcbhead, tcb);
204 #define tcb6 tcb /* for KAME src sync over BSD*'s */
205 VNET_DEFINE(struct inpcbinfo, tcbinfo);
207 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
208 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
209 struct socket *, struct tcpcb *, int, int, uint8_t,
211 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
212 struct tcpcb *, int, int);
213 static void tcp_pulloutofband(struct socket *,
214 struct tcphdr *, struct mbuf *, int);
215 static void tcp_xmit_timer(struct tcpcb *, int);
216 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
217 static void inline cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
219 static void inline cc_conn_init(struct tcpcb *tp);
220 static void inline cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
223 * Kernel module interface for updating tcpstat. The argument is an index
224 * into tcpstat treated as an array of u_long. While this encodes the
225 * general layout of tcpstat into the caller, it doesn't encode its location,
226 * so that future changes to add, for example, per-CPU stats support won't
227 * cause binary compatibility problems for kernel modules.
230 kmod_tcpstat_inc(int statnum)
233 (*((u_long *)&V_tcpstat + statnum))++;
237 * CC wrapper hook functions
240 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
242 INP_WLOCK_ASSERT(tp->t_inpcb);
244 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
245 if (tp->snd_cwnd == min(tp->snd_cwnd, tp->snd_wnd))
246 tp->ccv->flags |= CCF_CWND_LIMITED;
248 tp->ccv->flags &= ~CCF_CWND_LIMITED;
250 if (type == CC_ACK) {
251 if (tp->snd_cwnd > tp->snd_ssthresh) {
252 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
253 V_tcp_abc_l_var * tp->t_maxseg);
254 if (tp->t_bytes_acked >= tp->snd_cwnd) {
255 tp->t_bytes_acked -= tp->snd_cwnd;
256 tp->ccv->flags |= CCF_ABC_SENTAWND;
259 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
260 tp->t_bytes_acked = 0;
264 if (CC_ALGO(tp)->ack_received != NULL) {
265 /* XXXLAS: Find a way to live without this */
266 tp->ccv->curack = th->th_ack;
267 CC_ALGO(tp)->ack_received(tp->ccv, type);
272 cc_conn_init(struct tcpcb *tp)
274 struct hc_metrics_lite metrics;
275 struct inpcb *inp = tp->t_inpcb;
278 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
281 INP_WLOCK_ASSERT(tp->t_inpcb);
283 tcp_hc_get(&inp->inp_inc, &metrics);
285 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
287 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
288 TCPSTAT_INC(tcps_usedrtt);
289 if (metrics.rmx_rttvar) {
290 tp->t_rttvar = metrics.rmx_rttvar;
291 TCPSTAT_INC(tcps_usedrttvar);
293 /* default variation is +- 1 rtt */
295 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
297 TCPT_RANGESET(tp->t_rxtcur,
298 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
299 tp->t_rttmin, TCPTV_REXMTMAX);
301 if (metrics.rmx_ssthresh) {
303 * There's some sort of gateway or interface
304 * buffer limit on the path. Use this to set
305 * the slow start threshhold, but set the
306 * threshold to no less than 2*mss.
308 tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
309 TCPSTAT_INC(tcps_usedssthresh);
313 * Set the slow-start flight size depending on whether this
314 * is a local network or not.
316 * Extend this so we cache the cwnd too and retrieve it here.
317 * Make cwnd even bigger than RFC3390 suggests but only if we
318 * have previous experience with the remote host. Be careful
319 * not make cwnd bigger than remote receive window or our own
320 * send socket buffer. Maybe put some additional upper bound
321 * on the retrieved cwnd. Should do incremental updates to
322 * hostcache when cwnd collapses so next connection doesn't
323 * overloads the path again.
325 * XXXAO: Initializing the CWND from the hostcache is broken
326 * and in its current form not RFC conformant. It is disabled
327 * until fixed or removed entirely.
329 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
330 * We currently check only in syncache_socket for that.
332 /* #define TCP_METRICS_CWND */
333 #ifdef TCP_METRICS_CWND
334 if (metrics.rmx_cwnd)
335 tp->snd_cwnd = max(tp->t_maxseg, min(metrics.rmx_cwnd / 2,
336 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
339 if (V_tcp_do_rfc3390)
340 tp->snd_cwnd = min(4 * tp->t_maxseg,
341 max(2 * tp->t_maxseg, 4380));
343 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
344 (!isipv6 && in_localaddr(inp->inp_faddr)))
346 else if (in_localaddr(inp->inp_faddr))
348 tp->snd_cwnd = tp->t_maxseg * V_ss_fltsz_local;
350 tp->snd_cwnd = tp->t_maxseg * V_ss_fltsz;
352 if (CC_ALGO(tp)->conn_init != NULL)
353 CC_ALGO(tp)->conn_init(tp->ccv);
357 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
359 INP_WLOCK_ASSERT(tp->t_inpcb);
363 if (!IN_FASTRECOVERY(tp->t_flags)) {
364 tp->snd_recover = tp->snd_max;
365 if (tp->t_flags & TF_ECN_PERMIT)
366 tp->t_flags |= TF_ECN_SND_CWR;
370 if (!IN_CONGRECOVERY(tp->t_flags)) {
371 TCPSTAT_INC(tcps_ecn_rcwnd);
372 tp->snd_recover = tp->snd_max;
373 if (tp->t_flags & TF_ECN_PERMIT)
374 tp->t_flags |= TF_ECN_SND_CWR;
379 tp->t_bytes_acked = 0;
380 EXIT_RECOVERY(tp->t_flags);
381 tp->snd_cwnd = tp->t_maxseg;
384 TCPSTAT_INC(tcps_sndrexmitbad);
385 /* RTO was unnecessary, so reset everything. */
386 tp->snd_cwnd = tp->snd_cwnd_prev;
387 tp->snd_ssthresh = tp->snd_ssthresh_prev;
388 tp->snd_recover = tp->snd_recover_prev;
389 if (tp->t_flags & TF_WASFRECOVERY)
390 ENTER_FASTRECOVERY(tp->t_flags);
391 if (tp->t_flags & TF_WASCRECOVERY)
392 ENTER_CONGRECOVERY(tp->t_flags);
393 tp->snd_nxt = tp->snd_max;
398 if (CC_ALGO(tp)->cong_signal != NULL) {
400 tp->ccv->curack = th->th_ack;
401 CC_ALGO(tp)->cong_signal(tp->ccv, type);
406 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
408 INP_WLOCK_ASSERT(tp->t_inpcb);
410 /* XXXLAS: KASSERT that we're in recovery? */
412 if (CC_ALGO(tp)->post_recovery != NULL) {
413 tp->ccv->curack = th->th_ack;
414 CC_ALGO(tp)->post_recovery(tp->ccv);
416 /* XXXLAS: EXIT_RECOVERY ? */
417 tp->t_bytes_acked = 0;
420 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
422 #define ND6_HINT(tp) \
424 if ((tp) && (tp)->t_inpcb && \
425 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
426 nd6_nud_hint(NULL, NULL, 0); \
433 * Indicate whether this ack should be delayed. We can delay the ack if
434 * - there is no delayed ack timer in progress and
435 * - our last ack wasn't a 0-sized window. We never want to delay
436 * the ack that opens up a 0-sized window and
437 * - delayed acks are enabled or
438 * - this is a half-synchronized T/TCP connection.
440 #define DELAY_ACK(tp) \
441 ((!tcp_timer_active(tp, TT_DELACK) && \
442 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
443 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
446 * TCP input handling is split into multiple parts:
447 * tcp6_input is a thin wrapper around tcp_input for the extended
448 * ip6_protox[] call format in ip6_input
449 * tcp_input handles primary segment validation, inpcb lookup and
450 * SYN processing on listen sockets
451 * tcp_do_segment processes the ACK and text of the segment for
452 * establishing, established and closing connections
456 tcp6_input(struct mbuf **mp, int *offp, int proto)
458 struct mbuf *m = *mp;
459 struct in6_ifaddr *ia6;
461 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
464 * draft-itojun-ipv6-tcp-to-anycast
465 * better place to put this in?
467 ia6 = ip6_getdstifaddr(m);
468 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
471 ifa_free(&ia6->ia_ifa);
472 ip6 = mtod(m, struct ip6_hdr *);
473 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
474 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
484 tcp_input(struct mbuf *m, int off0)
487 struct ip *ip = NULL;
489 struct inpcb *inp = NULL;
490 struct tcpcb *tp = NULL;
491 struct socket *so = NULL;
497 int rstreason = 0; /* For badport_bandlim accounting purposes */
499 #ifdef IPFIREWALL_FORWARD
500 struct m_tag *fwd_tag;
503 struct ip6_hdr *ip6 = NULL;
506 const void *ip6 = NULL;
507 const int isipv6 = 0;
509 struct tcpopt to; /* options in this segment */
510 char *s = NULL; /* address and port logging */
512 #define TI_UNLOCKED 1
518 * The size of tcp_saveipgen must be the size of the max ip header,
521 u_char tcp_saveipgen[IP6_HDR_LEN];
522 struct tcphdr tcp_savetcp;
527 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
531 TCPSTAT_INC(tcps_rcvtotal);
535 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
536 ip6 = mtod(m, struct ip6_hdr *);
537 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
538 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
539 TCPSTAT_INC(tcps_rcvbadsum);
542 th = (struct tcphdr *)((caddr_t)ip6 + off0);
545 * Be proactive about unspecified IPv6 address in source.
546 * As we use all-zero to indicate unbounded/unconnected pcb,
547 * unspecified IPv6 address can be used to confuse us.
549 * Note that packets with unspecified IPv6 destination is
550 * already dropped in ip6_input.
552 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
557 th = NULL; /* XXX: Avoid compiler warning. */
561 * Get IP and TCP header together in first mbuf.
562 * Note: IP leaves IP header in first mbuf.
564 if (off0 > sizeof (struct ip)) {
565 ip_stripoptions(m, (struct mbuf *)0);
566 off0 = sizeof(struct ip);
568 if (m->m_len < sizeof (struct tcpiphdr)) {
569 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
571 TCPSTAT_INC(tcps_rcvshort);
575 ip = mtod(m, struct ip *);
576 ipov = (struct ipovly *)ip;
577 th = (struct tcphdr *)((caddr_t)ip + off0);
580 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
581 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
582 th->th_sum = m->m_pkthdr.csum_data;
584 th->th_sum = in_pseudo(ip->ip_src.s_addr,
586 htonl(m->m_pkthdr.csum_data +
589 th->th_sum ^= 0xffff;
591 ipov->ih_len = (u_short)tlen;
592 ipov->ih_len = htons(ipov->ih_len);
596 * Checksum extended TCP header and data.
598 len = sizeof (struct ip) + tlen;
599 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
600 ipov->ih_len = (u_short)tlen;
601 ipov->ih_len = htons(ipov->ih_len);
602 th->th_sum = in_cksum(m, len);
605 TCPSTAT_INC(tcps_rcvbadsum);
608 /* Re-initialization for later version check */
609 ip->ip_v = IPVERSION;
614 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
620 * Check that TCP offset makes sense,
621 * pull out TCP options and adjust length. XXX
623 off = th->th_off << 2;
624 if (off < sizeof (struct tcphdr) || off > tlen) {
625 TCPSTAT_INC(tcps_rcvbadoff);
628 tlen -= off; /* tlen is used instead of ti->ti_len */
629 if (off > sizeof (struct tcphdr)) {
632 IP6_EXTHDR_CHECK(m, off0, off, );
633 ip6 = mtod(m, struct ip6_hdr *);
634 th = (struct tcphdr *)((caddr_t)ip6 + off0);
637 if (m->m_len < sizeof(struct ip) + off) {
638 if ((m = m_pullup(m, sizeof (struct ip) + off))
640 TCPSTAT_INC(tcps_rcvshort);
643 ip = mtod(m, struct ip *);
644 ipov = (struct ipovly *)ip;
645 th = (struct tcphdr *)((caddr_t)ip + off0);
648 optlen = off - sizeof (struct tcphdr);
649 optp = (u_char *)(th + 1);
651 thflags = th->th_flags;
654 * Convert TCP protocol specific fields to host format.
656 th->th_seq = ntohl(th->th_seq);
657 th->th_ack = ntohl(th->th_ack);
658 th->th_win = ntohs(th->th_win);
659 th->th_urp = ntohs(th->th_urp);
662 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
664 drop_hdrlen = off0 + off;
667 * Locate pcb for segment, which requires a lock on tcbinfo.
668 * Optimisticaly acquire a global read lock rather than a write lock
669 * unless header flags necessarily imply a state change. There are
670 * two cases where we might discover later we need a write lock
671 * despite the flags: ACKs moving a connection out of the syncache,
672 * and ACKs for a connection in TIMEWAIT.
674 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
675 tcp_read_locking == 0) {
676 INP_INFO_WLOCK(&V_tcbinfo);
677 ti_locked = TI_WLOCKED;
679 INP_INFO_RLOCK(&V_tcbinfo);
680 ti_locked = TI_RLOCKED;
685 if (ti_locked == TI_RLOCKED)
686 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
687 else if (ti_locked == TI_WLOCKED)
688 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
690 panic("%s: findpcb ti_locked %d\n", __func__, ti_locked);
693 #ifdef IPFIREWALL_FORWARD
695 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
697 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
699 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
700 struct sockaddr_in *next_hop;
702 next_hop = (struct sockaddr_in *)(fwd_tag+1);
704 * Transparently forwarded. Pretend to be the destination.
705 * already got one like this?
707 inp = in_pcblookup_hash(&V_tcbinfo,
708 ip->ip_src, th->th_sport,
709 ip->ip_dst, th->th_dport,
710 0, m->m_pkthdr.rcvif);
712 /* It's new. Try to find the ambushing socket. */
713 inp = in_pcblookup_hash(&V_tcbinfo,
714 ip->ip_src, th->th_sport,
717 ntohs(next_hop->sin_port) :
722 /* Remove the tag from the packet. We don't need it anymore. */
723 m_tag_delete(m, fwd_tag);
725 #endif /* IPFIREWALL_FORWARD */
729 inp = in6_pcblookup_hash(&V_tcbinfo,
730 &ip6->ip6_src, th->th_sport,
731 &ip6->ip6_dst, th->th_dport,
736 inp = in_pcblookup_hash(&V_tcbinfo,
737 ip->ip_src, th->th_sport,
738 ip->ip_dst, th->th_dport,
744 * If the INPCB does not exist then all data in the incoming
745 * segment is discarded and an appropriate RST is sent back.
746 * XXX MRT Send RST using which routing table?
750 * Log communication attempts to ports that are not
753 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
754 tcp_log_in_vain == 2) {
755 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
756 log(LOG_INFO, "%s; %s: Connection attempt "
757 "to closed port\n", s, __func__);
760 * When blackholing do not respond with a RST but
761 * completely ignore the segment and drop it.
763 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
767 rstreason = BANDLIM_RST_CLOSEDPORT;
771 if (!(inp->inp_flags & INP_HW_FLOWID)
772 && (m->m_flags & M_FLOWID)
773 && ((inp->inp_socket == NULL)
774 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
775 inp->inp_flags |= INP_HW_FLOWID;
776 inp->inp_flags &= ~INP_SW_FLOWID;
777 inp->inp_flowid = m->m_pkthdr.flowid;
781 if (isipv6 && ipsec6_in_reject(m, inp)) {
782 V_ipsec6stat.in_polvio++;
786 if (ipsec4_in_reject(m, inp) != 0) {
787 V_ipsec4stat.in_polvio++;
793 * Check the minimum TTL for socket.
795 if (inp->inp_ip_minttl != 0) {
797 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
801 if (inp->inp_ip_minttl > ip->ip_ttl)
806 * A previous connection in TIMEWAIT state is supposed to catch stray
807 * or duplicate segments arriving late. If this segment was a
808 * legitimate new connection attempt the old INPCB gets removed and
809 * we can try again to find a listening socket.
811 * At this point, due to earlier optimism, we may hold a read lock on
812 * the inpcbinfo, rather than a write lock. If so, we need to
813 * upgrade, or if that fails, acquire a reference on the inpcb, drop
814 * all locks, acquire a global write lock, and then re-acquire the
815 * inpcb lock. We may at that point discover that another thread has
816 * tried to free the inpcb, in which case we need to loop back and
817 * try to find a new inpcb to deliver to.
820 if (inp->inp_flags & INP_TIMEWAIT) {
821 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
822 ("%s: INP_TIMEWAIT ti_locked %d", __func__, ti_locked));
824 if (ti_locked == TI_RLOCKED) {
825 if (INP_INFO_TRY_UPGRADE(&V_tcbinfo) == 0) {
828 INP_INFO_RUNLOCK(&V_tcbinfo);
829 INP_INFO_WLOCK(&V_tcbinfo);
830 ti_locked = TI_WLOCKED;
832 if (in_pcbrele(inp)) {
837 ti_locked = TI_WLOCKED;
839 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
841 if (thflags & TH_SYN)
842 tcp_dooptions(&to, optp, optlen, TO_SYN);
844 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
846 if (tcp_twcheck(inp, &to, th, m, tlen))
848 INP_INFO_WUNLOCK(&V_tcbinfo);
852 * The TCPCB may no longer exist if the connection is winding
853 * down or it is in the CLOSED state. Either way we drop the
854 * segment and send an appropriate response.
857 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
858 rstreason = BANDLIM_RST_CLOSEDPORT;
863 * We've identified a valid inpcb, but it could be that we need an
864 * inpcbinfo write lock and have only a read lock. In this case,
865 * attempt to upgrade/relock using the same strategy as the TIMEWAIT
866 * case above. If we relock, we have to jump back to 'relocked' as
867 * the connection might now be in TIMEWAIT.
869 if (tp->t_state != TCPS_ESTABLISHED ||
870 (thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
871 tcp_read_locking == 0) {
872 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
873 ("%s: upgrade check ti_locked %d", __func__, ti_locked));
875 if (ti_locked == TI_RLOCKED) {
876 if (INP_INFO_TRY_UPGRADE(&V_tcbinfo) == 0) {
879 INP_INFO_RUNLOCK(&V_tcbinfo);
880 INP_INFO_WLOCK(&V_tcbinfo);
881 ti_locked = TI_WLOCKED;
883 if (in_pcbrele(inp)) {
889 ti_locked = TI_WLOCKED;
891 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
895 INP_WLOCK_ASSERT(inp);
896 if (mac_inpcb_check_deliver(inp, m))
899 so = inp->inp_socket;
900 KASSERT(so != NULL, ("%s: so == NULL", __func__));
902 if (so->so_options & SO_DEBUG) {
903 ostate = tp->t_state;
906 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
909 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
914 * When the socket is accepting connections (the INPCB is in LISTEN
915 * state) we look into the SYN cache if this is a new connection
916 * attempt or the completion of a previous one.
918 if (so->so_options & SO_ACCEPTCONN) {
919 struct in_conninfo inc;
921 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
922 "tp not listening", __func__));
924 bzero(&inc, sizeof(inc));
927 inc.inc_flags |= INC_ISIPV6;
928 inc.inc6_faddr = ip6->ip6_src;
929 inc.inc6_laddr = ip6->ip6_dst;
933 inc.inc_faddr = ip->ip_src;
934 inc.inc_laddr = ip->ip_dst;
936 inc.inc_fport = th->th_sport;
937 inc.inc_lport = th->th_dport;
938 inc.inc_fibnum = so->so_fibnum;
941 * Check for an existing connection attempt in syncache if
942 * the flag is only ACK. A successful lookup creates a new
943 * socket appended to the listen queue in SYN_RECEIVED state.
945 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
947 * Parse the TCP options here because
948 * syncookies need access to the reflected
951 tcp_dooptions(&to, optp, optlen, 0);
953 * NB: syncache_expand() doesn't unlock
954 * inp and tcpinfo locks.
956 if (!syncache_expand(&inc, &to, th, &so, m)) {
958 * No syncache entry or ACK was not
959 * for our SYN/ACK. Send a RST.
960 * NB: syncache did its own logging
961 * of the failure cause.
963 rstreason = BANDLIM_RST_OPENPORT;
968 * We completed the 3-way handshake
969 * but could not allocate a socket
970 * either due to memory shortage,
971 * listen queue length limits or
972 * global socket limits. Send RST
973 * or wait and have the remote end
974 * retransmit the ACK for another
977 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
978 log(LOG_DEBUG, "%s; %s: Listen socket: "
979 "Socket allocation failed due to "
980 "limits or memory shortage, %s\n",
982 V_tcp_sc_rst_sock_fail ?
983 "sending RST" : "try again");
984 if (V_tcp_sc_rst_sock_fail) {
985 rstreason = BANDLIM_UNLIMITED;
991 * Socket is created in state SYN_RECEIVED.
992 * Unlock the listen socket, lock the newly
993 * created socket and update the tp variable.
995 INP_WUNLOCK(inp); /* listen socket */
997 INP_WLOCK(inp); /* new connection */
999 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1000 ("%s: ", __func__));
1002 * Process the segment and the data it
1003 * contains. tcp_do_segment() consumes
1004 * the mbuf chain and unlocks the inpcb.
1006 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1008 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1012 * Segment flag validation for new connection attempts:
1014 * Our (SYN|ACK) response was rejected.
1015 * Check with syncache and remove entry to prevent
1018 * NB: syncache_chkrst does its own logging of failure
1021 if (thflags & TH_RST) {
1022 syncache_chkrst(&inc, th);
1026 * We can't do anything without SYN.
1028 if ((thflags & TH_SYN) == 0) {
1029 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1030 log(LOG_DEBUG, "%s; %s: Listen socket: "
1031 "SYN is missing, segment ignored\n",
1033 TCPSTAT_INC(tcps_badsyn);
1037 * (SYN|ACK) is bogus on a listen socket.
1039 if (thflags & TH_ACK) {
1040 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1041 log(LOG_DEBUG, "%s; %s: Listen socket: "
1042 "SYN|ACK invalid, segment rejected\n",
1044 syncache_badack(&inc); /* XXX: Not needed! */
1045 TCPSTAT_INC(tcps_badsyn);
1046 rstreason = BANDLIM_RST_OPENPORT;
1050 * If the drop_synfin option is enabled, drop all
1051 * segments with both the SYN and FIN bits set.
1052 * This prevents e.g. nmap from identifying the
1054 * XXX: Poor reasoning. nmap has other methods
1055 * and is constantly refining its stack detection
1057 * XXX: This is a violation of the TCP specification
1058 * and was used by RFC1644.
1060 if ((thflags & TH_FIN) && V_drop_synfin) {
1061 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1062 log(LOG_DEBUG, "%s; %s: Listen socket: "
1063 "SYN|FIN segment ignored (based on "
1064 "sysctl setting)\n", s, __func__);
1065 TCPSTAT_INC(tcps_badsyn);
1069 * Segment's flags are (SYN) or (SYN|FIN).
1071 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1072 * as they do not affect the state of the TCP FSM.
1073 * The data pointed to by TH_URG and th_urp is ignored.
1075 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1076 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1077 KASSERT(thflags & (TH_SYN),
1078 ("%s: Listen socket: TH_SYN not set", __func__));
1081 * If deprecated address is forbidden,
1082 * we do not accept SYN to deprecated interface
1083 * address to prevent any new inbound connection from
1084 * getting established.
1085 * When we do not accept SYN, we send a TCP RST,
1086 * with deprecated source address (instead of dropping
1087 * it). We compromise it as it is much better for peer
1088 * to send a RST, and RST will be the final packet
1091 * If we do not forbid deprecated addresses, we accept
1092 * the SYN packet. RFC2462 does not suggest dropping
1094 * If we decipher RFC2462 5.5.4, it says like this:
1095 * 1. use of deprecated addr with existing
1096 * communication is okay - "SHOULD continue to be
1098 * 2. use of it with new communication:
1099 * (2a) "SHOULD NOT be used if alternate address
1100 * with sufficient scope is available"
1101 * (2b) nothing mentioned otherwise.
1102 * Here we fall into (2b) case as we have no choice in
1103 * our source address selection - we must obey the peer.
1105 * The wording in RFC2462 is confusing, and there are
1106 * multiple description text for deprecated address
1107 * handling - worse, they are not exactly the same.
1108 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1110 if (isipv6 && !V_ip6_use_deprecated) {
1111 struct in6_ifaddr *ia6;
1113 ia6 = ip6_getdstifaddr(m);
1115 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1116 ifa_free(&ia6->ia_ifa);
1117 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1118 log(LOG_DEBUG, "%s; %s: Listen socket: "
1119 "Connection attempt to deprecated "
1120 "IPv6 address rejected\n",
1122 rstreason = BANDLIM_RST_OPENPORT;
1125 ifa_free(&ia6->ia_ifa);
1129 * Basic sanity checks on incoming SYN requests:
1130 * Don't respond if the destination is a link layer
1131 * broadcast according to RFC1122 4.2.3.10, p. 104.
1132 * If it is from this socket it must be forged.
1133 * Don't respond if the source or destination is a
1134 * global or subnet broad- or multicast address.
1135 * Note that it is quite possible to receive unicast
1136 * link-layer packets with a broadcast IP address. Use
1137 * in_broadcast() to find them.
1139 if (m->m_flags & (M_BCAST|M_MCAST)) {
1140 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1141 log(LOG_DEBUG, "%s; %s: Listen socket: "
1142 "Connection attempt from broad- or multicast "
1143 "link layer address ignored\n", s, __func__);
1148 if (th->th_dport == th->th_sport &&
1149 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1150 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1151 log(LOG_DEBUG, "%s; %s: Listen socket: "
1152 "Connection attempt to/from self "
1153 "ignored\n", s, __func__);
1156 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1157 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1158 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1159 log(LOG_DEBUG, "%s; %s: Listen socket: "
1160 "Connection attempt from/to multicast "
1161 "address ignored\n", s, __func__);
1166 if (th->th_dport == th->th_sport &&
1167 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1168 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1169 log(LOG_DEBUG, "%s; %s: Listen socket: "
1170 "Connection attempt from/to self "
1171 "ignored\n", s, __func__);
1174 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1175 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1176 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1177 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1178 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1179 log(LOG_DEBUG, "%s; %s: Listen socket: "
1180 "Connection attempt from/to broad- "
1181 "or multicast address ignored\n",
1187 * SYN appears to be valid. Create compressed TCP state
1191 if (so->so_options & SO_DEBUG)
1192 tcp_trace(TA_INPUT, ostate, tp,
1193 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1195 tcp_dooptions(&to, optp, optlen, TO_SYN);
1196 syncache_add(&inc, &to, th, inp, &so, m);
1198 * Entry added to syncache and mbuf consumed.
1199 * Everything already unlocked by syncache_add().
1201 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1206 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1207 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1208 * the inpcb, and unlocks pcbinfo.
1210 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1211 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1215 if (ti_locked == TI_RLOCKED)
1216 INP_INFO_RUNLOCK(&V_tcbinfo);
1217 else if (ti_locked == TI_WLOCKED)
1218 INP_INFO_WUNLOCK(&V_tcbinfo);
1220 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
1221 ti_locked = TI_UNLOCKED;
1224 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1227 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1228 m = NULL; /* mbuf chain got consumed. */
1232 if (ti_locked == TI_RLOCKED)
1233 INP_INFO_RUNLOCK(&V_tcbinfo);
1234 else if (ti_locked == TI_WLOCKED)
1235 INP_INFO_WUNLOCK(&V_tcbinfo);
1237 panic("%s: dropunlock ti_locked %d", __func__, ti_locked);
1238 ti_locked = TI_UNLOCKED;
1244 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1252 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1253 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1256 int thflags, acked, ourfinisacked, needoutput = 0;
1257 int rstreason, todrop, win;
1263 * The size of tcp_saveipgen must be the size of the max ip header,
1266 u_char tcp_saveipgen[IP6_HDR_LEN];
1267 struct tcphdr tcp_savetcp;
1270 thflags = th->th_flags;
1273 * If this is either a state-changing packet or current state isn't
1274 * established, we require a write lock on tcbinfo. Otherwise, we
1275 * allow either a read lock or a write lock, as we may have acquired
1276 * a write lock due to a race.
1278 * Require a global write lock for SYN/FIN/RST segments or
1279 * non-established connections; otherwise accept either a read or
1280 * write lock, as we may have conservatively acquired a write lock in
1281 * certain cases in tcp_input() (is this still true?). Currently we
1282 * will never enter with no lock, so we try to drop it quickly in the
1283 * common pure ack/pure data cases.
1285 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1286 tp->t_state != TCPS_ESTABLISHED) {
1287 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1288 "SYN/FIN/RST/!EST", __func__, ti_locked));
1289 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1292 if (ti_locked == TI_RLOCKED)
1293 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1294 else if (ti_locked == TI_WLOCKED)
1295 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1297 panic("%s: ti_locked %d for EST", __func__,
1301 INP_WLOCK_ASSERT(tp->t_inpcb);
1302 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1304 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1308 * Segment received on connection.
1309 * Reset idle time and keep-alive timer.
1310 * XXX: This should be done after segment
1311 * validation to ignore broken/spoofed segs.
1313 tp->t_rcvtime = ticks;
1314 if (TCPS_HAVEESTABLISHED(tp->t_state))
1315 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1318 * Unscale the window into a 32-bit value.
1319 * For the SYN_SENT state the scale is zero.
1321 tiwin = th->th_win << tp->snd_scale;
1324 * TCP ECN processing.
1326 if (tp->t_flags & TF_ECN_PERMIT) {
1327 if (thflags & TH_CWR)
1328 tp->t_flags &= ~TF_ECN_SND_ECE;
1329 switch (iptos & IPTOS_ECN_MASK) {
1331 tp->t_flags |= TF_ECN_SND_ECE;
1332 TCPSTAT_INC(tcps_ecn_ce);
1334 case IPTOS_ECN_ECT0:
1335 TCPSTAT_INC(tcps_ecn_ect0);
1337 case IPTOS_ECN_ECT1:
1338 TCPSTAT_INC(tcps_ecn_ect1);
1341 /* Congestion experienced. */
1342 if (thflags & TH_ECE) {
1343 cc_cong_signal(tp, th, CC_ECN);
1348 * Parse options on any incoming segment.
1350 tcp_dooptions(&to, (u_char *)(th + 1),
1351 (th->th_off << 2) - sizeof(struct tcphdr),
1352 (thflags & TH_SYN) ? TO_SYN : 0);
1355 * If echoed timestamp is later than the current time,
1356 * fall back to non RFC1323 RTT calculation. Normalize
1357 * timestamp if syncookies were used when this connection
1360 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1361 to.to_tsecr -= tp->ts_offset;
1362 if (TSTMP_GT(to.to_tsecr, ticks))
1367 * Process options only when we get SYN/ACK back. The SYN case
1368 * for incoming connections is handled in tcp_syncache.
1369 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1370 * or <SYN,ACK>) segment itself is never scaled.
1371 * XXX this is traditional behavior, may need to be cleaned up.
1373 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1374 if ((to.to_flags & TOF_SCALE) &&
1375 (tp->t_flags & TF_REQ_SCALE)) {
1376 tp->t_flags |= TF_RCVD_SCALE;
1377 tp->snd_scale = to.to_wscale;
1380 * Initial send window. It will be updated with
1381 * the next incoming segment to the scaled value.
1383 tp->snd_wnd = th->th_win;
1384 if (to.to_flags & TOF_TS) {
1385 tp->t_flags |= TF_RCVD_TSTMP;
1386 tp->ts_recent = to.to_tsval;
1387 tp->ts_recent_age = ticks;
1389 if (to.to_flags & TOF_MSS)
1390 tcp_mss(tp, to.to_mss);
1391 if ((tp->t_flags & TF_SACK_PERMIT) &&
1392 (to.to_flags & TOF_SACKPERM) == 0)
1393 tp->t_flags &= ~TF_SACK_PERMIT;
1397 * Header prediction: check for the two common cases
1398 * of a uni-directional data xfer. If the packet has
1399 * no control flags, is in-sequence, the window didn't
1400 * change and we're not retransmitting, it's a
1401 * candidate. If the length is zero and the ack moved
1402 * forward, we're the sender side of the xfer. Just
1403 * free the data acked & wake any higher level process
1404 * that was blocked waiting for space. If the length
1405 * is non-zero and the ack didn't move, we're the
1406 * receiver side. If we're getting packets in-order
1407 * (the reassembly queue is empty), add the data to
1408 * the socket buffer and note that we need a delayed ack.
1409 * Make sure that the hidden state-flags are also off.
1410 * Since we check for TCPS_ESTABLISHED first, it can only
1413 if (tp->t_state == TCPS_ESTABLISHED &&
1414 th->th_seq == tp->rcv_nxt &&
1415 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1416 tp->snd_nxt == tp->snd_max &&
1417 tiwin && tiwin == tp->snd_wnd &&
1418 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1419 LIST_EMPTY(&tp->t_segq) &&
1420 ((to.to_flags & TOF_TS) == 0 ||
1421 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1424 * If last ACK falls within this segment's sequence numbers,
1425 * record the timestamp.
1426 * NOTE that the test is modified according to the latest
1427 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1429 if ((to.to_flags & TOF_TS) != 0 &&
1430 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1431 tp->ts_recent_age = ticks;
1432 tp->ts_recent = to.to_tsval;
1436 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1437 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1438 !IN_RECOVERY(tp->t_flags) &&
1439 (to.to_flags & TOF_SACK) == 0 &&
1440 TAILQ_EMPTY(&tp->snd_holes)) {
1442 * This is a pure ack for outstanding data.
1444 if (ti_locked == TI_RLOCKED)
1445 INP_INFO_RUNLOCK(&V_tcbinfo);
1446 else if (ti_locked == TI_WLOCKED)
1447 INP_INFO_WUNLOCK(&V_tcbinfo);
1449 panic("%s: ti_locked %d on pure ACK",
1450 __func__, ti_locked);
1451 ti_locked = TI_UNLOCKED;
1453 TCPSTAT_INC(tcps_predack);
1456 * "bad retransmit" recovery.
1458 if (tp->t_rxtshift == 1 &&
1459 (int)(ticks - tp->t_badrxtwin) < 0) {
1460 cc_cong_signal(tp, th, CC_RTO_ERR);
1464 * Recalculate the transmit timer / rtt.
1466 * Some boxes send broken timestamp replies
1467 * during the SYN+ACK phase, ignore
1468 * timestamps of 0 or we could calculate a
1469 * huge RTT and blow up the retransmit timer.
1471 if ((to.to_flags & TOF_TS) != 0 &&
1473 if (!tp->t_rttlow ||
1474 tp->t_rttlow > ticks - to.to_tsecr)
1475 tp->t_rttlow = ticks - to.to_tsecr;
1477 ticks - to.to_tsecr + 1);
1478 } else if (tp->t_rtttime &&
1479 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1480 if (!tp->t_rttlow ||
1481 tp->t_rttlow > ticks - tp->t_rtttime)
1482 tp->t_rttlow = ticks - tp->t_rtttime;
1484 ticks - tp->t_rtttime);
1486 acked = BYTES_THIS_ACK(tp, th);
1487 TCPSTAT_INC(tcps_rcvackpack);
1488 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1489 sbdrop(&so->so_snd, acked);
1490 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1491 SEQ_LEQ(th->th_ack, tp->snd_recover))
1492 tp->snd_recover = th->th_ack - 1;
1495 * Let the congestion control algorithm update
1496 * congestion control related information. This
1497 * typically means increasing the congestion
1500 cc_ack_received(tp, th, CC_ACK);
1502 tp->snd_una = th->th_ack;
1504 * Pull snd_wl2 up to prevent seq wrap relative
1507 tp->snd_wl2 = th->th_ack;
1510 ND6_HINT(tp); /* Some progress has been made. */
1513 * If all outstanding data are acked, stop
1514 * retransmit timer, otherwise restart timer
1515 * using current (possibly backed-off) value.
1516 * If process is waiting for space,
1517 * wakeup/selwakeup/signal. If data
1518 * are ready to send, let tcp_output
1519 * decide between more output or persist.
1522 if (so->so_options & SO_DEBUG)
1523 tcp_trace(TA_INPUT, ostate, tp,
1524 (void *)tcp_saveipgen,
1527 if (tp->snd_una == tp->snd_max)
1528 tcp_timer_activate(tp, TT_REXMT, 0);
1529 else if (!tcp_timer_active(tp, TT_PERSIST))
1530 tcp_timer_activate(tp, TT_REXMT,
1533 if (so->so_snd.sb_cc)
1534 (void) tcp_output(tp);
1537 } else if (th->th_ack == tp->snd_una &&
1538 tlen <= sbspace(&so->so_rcv)) {
1539 int newsize = 0; /* automatic sockbuf scaling */
1542 * This is a pure, in-sequence data packet with
1543 * nothing on the reassembly queue and we have enough
1544 * buffer space to take it.
1546 if (ti_locked == TI_RLOCKED)
1547 INP_INFO_RUNLOCK(&V_tcbinfo);
1548 else if (ti_locked == TI_WLOCKED)
1549 INP_INFO_WUNLOCK(&V_tcbinfo);
1551 panic("%s: ti_locked %d on pure data "
1552 "segment", __func__, ti_locked);
1553 ti_locked = TI_UNLOCKED;
1555 /* Clean receiver SACK report if present */
1556 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1557 tcp_clean_sackreport(tp);
1558 TCPSTAT_INC(tcps_preddat);
1559 tp->rcv_nxt += tlen;
1561 * Pull snd_wl1 up to prevent seq wrap relative to
1564 tp->snd_wl1 = th->th_seq;
1566 * Pull rcv_up up to prevent seq wrap relative to
1569 tp->rcv_up = tp->rcv_nxt;
1570 TCPSTAT_INC(tcps_rcvpack);
1571 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1572 ND6_HINT(tp); /* Some progress has been made */
1574 if (so->so_options & SO_DEBUG)
1575 tcp_trace(TA_INPUT, ostate, tp,
1576 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1579 * Automatic sizing of receive socket buffer. Often the send
1580 * buffer size is not optimally adjusted to the actual network
1581 * conditions at hand (delay bandwidth product). Setting the
1582 * buffer size too small limits throughput on links with high
1583 * bandwidth and high delay (eg. trans-continental/oceanic links).
1585 * On the receive side the socket buffer memory is only rarely
1586 * used to any significant extent. This allows us to be much
1587 * more aggressive in scaling the receive socket buffer. For
1588 * the case that the buffer space is actually used to a large
1589 * extent and we run out of kernel memory we can simply drop
1590 * the new segments; TCP on the sender will just retransmit it
1591 * later. Setting the buffer size too big may only consume too
1592 * much kernel memory if the application doesn't read() from
1593 * the socket or packet loss or reordering makes use of the
1596 * The criteria to step up the receive buffer one notch are:
1597 * 1. the number of bytes received during the time it takes
1598 * one timestamp to be reflected back to us (the RTT);
1599 * 2. received bytes per RTT is within seven eighth of the
1600 * current socket buffer size;
1601 * 3. receive buffer size has not hit maximal automatic size;
1603 * This algorithm does one step per RTT at most and only if
1604 * we receive a bulk stream w/o packet losses or reorderings.
1605 * Shrinking the buffer during idle times is not necessary as
1606 * it doesn't consume any memory when idle.
1608 * TODO: Only step up if the application is actually serving
1609 * the buffer to better manage the socket buffer resources.
1611 if (V_tcp_do_autorcvbuf &&
1613 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1614 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1615 to.to_tsecr - tp->rfbuf_ts < hz) {
1617 (so->so_rcv.sb_hiwat / 8 * 7) &&
1618 so->so_rcv.sb_hiwat <
1619 V_tcp_autorcvbuf_max) {
1621 min(so->so_rcv.sb_hiwat +
1622 V_tcp_autorcvbuf_inc,
1623 V_tcp_autorcvbuf_max);
1625 /* Start over with next RTT. */
1629 tp->rfbuf_cnt += tlen; /* add up */
1632 /* Add data to socket buffer. */
1633 SOCKBUF_LOCK(&so->so_rcv);
1634 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1638 * Set new socket buffer size.
1639 * Give up when limit is reached.
1642 if (!sbreserve_locked(&so->so_rcv,
1644 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1645 m_adj(m, drop_hdrlen); /* delayed header drop */
1646 sbappendstream_locked(&so->so_rcv, m);
1648 /* NB: sorwakeup_locked() does an implicit unlock. */
1649 sorwakeup_locked(so);
1650 if (DELAY_ACK(tp)) {
1651 tp->t_flags |= TF_DELACK;
1653 tp->t_flags |= TF_ACKNOW;
1661 * Calculate amount of space in receive window,
1662 * and then do TCP input processing.
1663 * Receive window is amount of space in rcv queue,
1664 * but not less than advertised window.
1666 win = sbspace(&so->so_rcv);
1669 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1671 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1675 switch (tp->t_state) {
1678 * If the state is SYN_RECEIVED:
1679 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1681 case TCPS_SYN_RECEIVED:
1682 if ((thflags & TH_ACK) &&
1683 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1684 SEQ_GT(th->th_ack, tp->snd_max))) {
1685 rstreason = BANDLIM_RST_OPENPORT;
1691 * If the state is SYN_SENT:
1692 * if seg contains an ACK, but not for our SYN, drop the input.
1693 * if seg contains a RST, then drop the connection.
1694 * if seg does not contain SYN, then drop it.
1695 * Otherwise this is an acceptable SYN segment
1696 * initialize tp->rcv_nxt and tp->irs
1697 * if seg contains ack then advance tp->snd_una
1698 * if seg contains an ECE and ECN support is enabled, the stream
1700 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1701 * arrange for segment to be acked (eventually)
1702 * continue processing rest of data/controls, beginning with URG
1705 if ((thflags & TH_ACK) &&
1706 (SEQ_LEQ(th->th_ack, tp->iss) ||
1707 SEQ_GT(th->th_ack, tp->snd_max))) {
1708 rstreason = BANDLIM_UNLIMITED;
1711 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1712 tp = tcp_drop(tp, ECONNREFUSED);
1713 if (thflags & TH_RST)
1715 if (!(thflags & TH_SYN))
1718 tp->irs = th->th_seq;
1720 if (thflags & TH_ACK) {
1721 TCPSTAT_INC(tcps_connects);
1724 mac_socketpeer_set_from_mbuf(m, so);
1726 /* Do window scaling on this connection? */
1727 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1728 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1729 tp->rcv_scale = tp->request_r_scale;
1731 tp->rcv_adv += tp->rcv_wnd;
1732 tp->snd_una++; /* SYN is acked */
1734 * If there's data, delay ACK; if there's also a FIN
1735 * ACKNOW will be turned on later.
1737 if (DELAY_ACK(tp) && tlen != 0)
1738 tcp_timer_activate(tp, TT_DELACK,
1741 tp->t_flags |= TF_ACKNOW;
1743 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1744 tp->t_flags |= TF_ECN_PERMIT;
1745 TCPSTAT_INC(tcps_ecn_shs);
1749 * Received <SYN,ACK> in SYN_SENT[*] state.
1751 * SYN_SENT --> ESTABLISHED
1752 * SYN_SENT* --> FIN_WAIT_1
1754 tp->t_starttime = ticks;
1755 if (tp->t_flags & TF_NEEDFIN) {
1756 tp->t_state = TCPS_FIN_WAIT_1;
1757 tp->t_flags &= ~TF_NEEDFIN;
1760 tp->t_state = TCPS_ESTABLISHED;
1762 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1766 * Received initial SYN in SYN-SENT[*] state =>
1767 * simultaneous open. If segment contains CC option
1768 * and there is a cached CC, apply TAO test.
1769 * If it succeeds, connection is * half-synchronized.
1770 * Otherwise, do 3-way handshake:
1771 * SYN-SENT -> SYN-RECEIVED
1772 * SYN-SENT* -> SYN-RECEIVED*
1773 * If there was no CC option, clear cached CC value.
1775 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1776 tcp_timer_activate(tp, TT_REXMT, 0);
1777 tp->t_state = TCPS_SYN_RECEIVED;
1780 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1781 "ti_locked %d", __func__, ti_locked));
1782 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1783 INP_WLOCK_ASSERT(tp->t_inpcb);
1786 * Advance th->th_seq to correspond to first data byte.
1787 * If data, trim to stay within window,
1788 * dropping FIN if necessary.
1791 if (tlen > tp->rcv_wnd) {
1792 todrop = tlen - tp->rcv_wnd;
1796 TCPSTAT_INC(tcps_rcvpackafterwin);
1797 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1799 tp->snd_wl1 = th->th_seq - 1;
1800 tp->rcv_up = th->th_seq;
1802 * Client side of transaction: already sent SYN and data.
1803 * If the remote host used T/TCP to validate the SYN,
1804 * our data will be ACK'd; if so, enter normal data segment
1805 * processing in the middle of step 5, ack processing.
1806 * Otherwise, goto step 6.
1808 if (thflags & TH_ACK)
1814 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1815 * do normal processing.
1817 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1821 break; /* continue normal processing */
1825 * States other than LISTEN or SYN_SENT.
1826 * First check the RST flag and sequence number since reset segments
1827 * are exempt from the timestamp and connection count tests. This
1828 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1829 * below which allowed reset segments in half the sequence space
1830 * to fall though and be processed (which gives forged reset
1831 * segments with a random sequence number a 50 percent chance of
1832 * killing a connection).
1833 * Then check timestamp, if present.
1834 * Then check the connection count, if present.
1835 * Then check that at least some bytes of segment are within
1836 * receive window. If segment begins before rcv_nxt,
1837 * drop leading data (and SYN); if nothing left, just ack.
1840 * If the RST bit is set, check the sequence number to see
1841 * if this is a valid reset segment.
1843 * In all states except SYN-SENT, all reset (RST) segments
1844 * are validated by checking their SEQ-fields. A reset is
1845 * valid if its sequence number is in the window.
1846 * Note: this does not take into account delayed ACKs, so
1847 * we should test against last_ack_sent instead of rcv_nxt.
1848 * The sequence number in the reset segment is normally an
1849 * echo of our outgoing acknowlegement numbers, but some hosts
1850 * send a reset with the sequence number at the rightmost edge
1851 * of our receive window, and we have to handle this case.
1852 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1853 * that brute force RST attacks are possible. To combat this,
1854 * we use a much stricter check while in the ESTABLISHED state,
1855 * only accepting RSTs where the sequence number is equal to
1856 * last_ack_sent. In all other states (the states in which a
1857 * RST is more likely), the more permissive check is used.
1858 * If we have multiple segments in flight, the initial reset
1859 * segment sequence numbers will be to the left of last_ack_sent,
1860 * but they will eventually catch up.
1861 * In any case, it never made sense to trim reset segments to
1862 * fit the receive window since RFC 1122 says:
1863 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1865 * A TCP SHOULD allow a received RST segment to include data.
1868 * It has been suggested that a RST segment could contain
1869 * ASCII text that encoded and explained the cause of the
1870 * RST. No standard has yet been established for such
1873 * If the reset segment passes the sequence number test examine
1875 * SYN_RECEIVED STATE:
1876 * If passive open, return to LISTEN state.
1877 * If active open, inform user that connection was refused.
1878 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1879 * Inform user that connection was reset, and close tcb.
1880 * CLOSING, LAST_ACK STATES:
1883 * Drop the segment - see Stevens, vol. 2, p. 964 and
1886 if (thflags & TH_RST) {
1887 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1888 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1889 switch (tp->t_state) {
1891 case TCPS_SYN_RECEIVED:
1892 so->so_error = ECONNREFUSED;
1895 case TCPS_ESTABLISHED:
1896 if (V_tcp_insecure_rst == 0 &&
1897 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1898 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1899 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1900 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1901 TCPSTAT_INC(tcps_badrst);
1905 case TCPS_FIN_WAIT_1:
1906 case TCPS_FIN_WAIT_2:
1907 case TCPS_CLOSE_WAIT:
1908 so->so_error = ECONNRESET;
1910 KASSERT(ti_locked == TI_WLOCKED,
1911 ("tcp_do_segment: TH_RST 1 ti_locked %d",
1913 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1915 tp->t_state = TCPS_CLOSED;
1916 TCPSTAT_INC(tcps_drops);
1922 KASSERT(ti_locked == TI_WLOCKED,
1923 ("tcp_do_segment: TH_RST 2 ti_locked %d",
1925 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1935 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1936 * and it's less than ts_recent, drop it.
1938 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1939 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1941 /* Check to see if ts_recent is over 24 days old. */
1942 if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
1944 * Invalidate ts_recent. If this segment updates
1945 * ts_recent, the age will be reset later and ts_recent
1946 * will get a valid value. If it does not, setting
1947 * ts_recent to zero will at least satisfy the
1948 * requirement that zero be placed in the timestamp
1949 * echo reply when ts_recent isn't valid. The
1950 * age isn't reset until we get a valid ts_recent
1951 * because we don't want out-of-order segments to be
1952 * dropped when ts_recent is old.
1956 TCPSTAT_INC(tcps_rcvduppack);
1957 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1958 TCPSTAT_INC(tcps_pawsdrop);
1966 * In the SYN-RECEIVED state, validate that the packet belongs to
1967 * this connection before trimming the data to fit the receive
1968 * window. Check the sequence number versus IRS since we know
1969 * the sequence numbers haven't wrapped. This is a partial fix
1970 * for the "LAND" DoS attack.
1972 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1973 rstreason = BANDLIM_RST_OPENPORT;
1977 todrop = tp->rcv_nxt - th->th_seq;
1980 * If this is a duplicate SYN for our current connection,
1981 * advance over it and pretend and it's not a SYN.
1983 if (thflags & TH_SYN && th->th_seq == tp->irs) {
1993 * Following if statement from Stevens, vol. 2, p. 960.
1996 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1998 * Any valid FIN must be to the left of the window.
1999 * At this point the FIN must be a duplicate or out
2000 * of sequence; drop it.
2005 * Send an ACK to resynchronize and drop any data.
2006 * But keep on processing for RST or ACK.
2008 tp->t_flags |= TF_ACKNOW;
2010 TCPSTAT_INC(tcps_rcvduppack);
2011 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2013 TCPSTAT_INC(tcps_rcvpartduppack);
2014 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2016 drop_hdrlen += todrop; /* drop from the top afterwards */
2017 th->th_seq += todrop;
2019 if (th->th_urp > todrop)
2020 th->th_urp -= todrop;
2028 * If new data are received on a connection after the
2029 * user processes are gone, then RST the other end.
2031 if ((so->so_state & SS_NOFDREF) &&
2032 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2035 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
2036 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2037 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2039 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
2040 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
2041 "was closed, sending RST and removing tcpcb\n",
2042 s, __func__, tcpstates[tp->t_state], tlen);
2046 TCPSTAT_INC(tcps_rcvafterclose);
2047 rstreason = BANDLIM_UNLIMITED;
2052 * If segment ends after window, drop trailing data
2053 * (and PUSH and FIN); if nothing left, just ACK.
2055 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2057 TCPSTAT_INC(tcps_rcvpackafterwin);
2058 if (todrop >= tlen) {
2059 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2061 * If window is closed can only take segments at
2062 * window edge, and have to drop data and PUSH from
2063 * incoming segments. Continue processing, but
2064 * remember to ack. Otherwise, drop segment
2067 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2068 tp->t_flags |= TF_ACKNOW;
2069 TCPSTAT_INC(tcps_rcvwinprobe);
2073 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2076 thflags &= ~(TH_PUSH|TH_FIN);
2080 * If last ACK falls within this segment's sequence numbers,
2081 * record its timestamp.
2083 * 1) That the test incorporates suggestions from the latest
2084 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2085 * 2) That updating only on newer timestamps interferes with
2086 * our earlier PAWS tests, so this check should be solely
2087 * predicated on the sequence space of this segment.
2088 * 3) That we modify the segment boundary check to be
2089 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2090 * instead of RFC1323's
2091 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2092 * This modified check allows us to overcome RFC1323's
2093 * limitations as described in Stevens TCP/IP Illustrated
2094 * Vol. 2 p.869. In such cases, we can still calculate the
2095 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2097 if ((to.to_flags & TOF_TS) != 0 &&
2098 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2099 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2100 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2101 tp->ts_recent_age = ticks;
2102 tp->ts_recent = to.to_tsval;
2106 * If a SYN is in the window, then this is an
2107 * error and we send an RST and drop the connection.
2109 if (thflags & TH_SYN) {
2110 KASSERT(ti_locked == TI_WLOCKED,
2111 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2112 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2114 tp = tcp_drop(tp, ECONNRESET);
2115 rstreason = BANDLIM_UNLIMITED;
2120 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2121 * flag is on (half-synchronized state), then queue data for
2122 * later processing; else drop segment and return.
2124 if ((thflags & TH_ACK) == 0) {
2125 if (tp->t_state == TCPS_SYN_RECEIVED ||
2126 (tp->t_flags & TF_NEEDSYN))
2128 else if (tp->t_flags & TF_ACKNOW)
2137 switch (tp->t_state) {
2140 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2141 * ESTABLISHED state and continue processing.
2142 * The ACK was checked above.
2144 case TCPS_SYN_RECEIVED:
2146 TCPSTAT_INC(tcps_connects);
2148 /* Do window scaling? */
2149 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2150 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2151 tp->rcv_scale = tp->request_r_scale;
2152 tp->snd_wnd = tiwin;
2156 * SYN-RECEIVED -> ESTABLISHED
2157 * SYN-RECEIVED* -> FIN-WAIT-1
2159 tp->t_starttime = ticks;
2160 if (tp->t_flags & TF_NEEDFIN) {
2161 tp->t_state = TCPS_FIN_WAIT_1;
2162 tp->t_flags &= ~TF_NEEDFIN;
2164 tp->t_state = TCPS_ESTABLISHED;
2166 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
2169 * If segment contains data or ACK, will call tcp_reass()
2170 * later; if not, do so now to pass queued data to user.
2172 if (tlen == 0 && (thflags & TH_FIN) == 0)
2173 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2175 tp->snd_wl1 = th->th_seq - 1;
2179 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2180 * ACKs. If the ack is in the range
2181 * tp->snd_una < th->th_ack <= tp->snd_max
2182 * then advance tp->snd_una to th->th_ack and drop
2183 * data from the retransmission queue. If this ACK reflects
2184 * more up to date window information we update our window information.
2186 case TCPS_ESTABLISHED:
2187 case TCPS_FIN_WAIT_1:
2188 case TCPS_FIN_WAIT_2:
2189 case TCPS_CLOSE_WAIT:
2192 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2193 TCPSTAT_INC(tcps_rcvacktoomuch);
2196 if ((tp->t_flags & TF_SACK_PERMIT) &&
2197 ((to.to_flags & TOF_SACK) ||
2198 !TAILQ_EMPTY(&tp->snd_holes)))
2199 tcp_sack_doack(tp, &to, th->th_ack);
2200 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2201 if (tlen == 0 && tiwin == tp->snd_wnd) {
2202 TCPSTAT_INC(tcps_rcvdupack);
2204 * If we have outstanding data (other than
2205 * a window probe), this is a completely
2206 * duplicate ack (ie, window info didn't
2207 * change), the ack is the biggest we've
2208 * seen and we've seen exactly our rexmt
2209 * threshhold of them, assume a packet
2210 * has been dropped and retransmit it.
2211 * Kludge snd_nxt & the congestion
2212 * window so we send only this one
2215 * We know we're losing at the current
2216 * window size so do congestion avoidance
2217 * (set ssthresh to half the current window
2218 * and pull our congestion window back to
2219 * the new ssthresh).
2221 * Dup acks mean that packets have left the
2222 * network (they're now cached at the receiver)
2223 * so bump cwnd by the amount in the receiver
2224 * to keep a constant cwnd packets in the
2227 * When using TCP ECN, notify the peer that
2228 * we reduced the cwnd.
2230 if (!tcp_timer_active(tp, TT_REXMT) ||
2231 th->th_ack != tp->snd_una)
2233 else if (++tp->t_dupacks > tcprexmtthresh ||
2234 IN_FASTRECOVERY(tp->t_flags)) {
2235 cc_ack_received(tp, th, CC_DUPACK);
2236 if ((tp->t_flags & TF_SACK_PERMIT) &&
2237 IN_FASTRECOVERY(tp->t_flags)) {
2241 * Compute the amount of data in flight first.
2242 * We can inject new data into the pipe iff
2243 * we have less than 1/2 the original window's
2244 * worth of data in flight.
2246 awnd = (tp->snd_nxt - tp->snd_fack) +
2247 tp->sackhint.sack_bytes_rexmit;
2248 if (awnd < tp->snd_ssthresh) {
2249 tp->snd_cwnd += tp->t_maxseg;
2250 if (tp->snd_cwnd > tp->snd_ssthresh)
2251 tp->snd_cwnd = tp->snd_ssthresh;
2254 tp->snd_cwnd += tp->t_maxseg;
2255 (void) tcp_output(tp);
2257 } else if (tp->t_dupacks == tcprexmtthresh) {
2258 tcp_seq onxt = tp->snd_nxt;
2261 * If we're doing sack, check to
2262 * see if we're already in sack
2263 * recovery. If we're not doing sack,
2264 * check to see if we're in newreno
2267 if (tp->t_flags & TF_SACK_PERMIT) {
2268 if (IN_FASTRECOVERY(tp->t_flags)) {
2273 if (SEQ_LEQ(th->th_ack,
2279 /* Congestion signal before ack. */
2280 cc_cong_signal(tp, th, CC_NDUPACK);
2281 cc_ack_received(tp, th, CC_DUPACK);
2282 tcp_timer_activate(tp, TT_REXMT, 0);
2284 if (tp->t_flags & TF_SACK_PERMIT) {
2286 tcps_sack_recovery_episode);
2287 tp->sack_newdata = tp->snd_nxt;
2288 tp->snd_cwnd = tp->t_maxseg;
2289 (void) tcp_output(tp);
2292 tp->snd_nxt = th->th_ack;
2293 tp->snd_cwnd = tp->t_maxseg;
2294 (void) tcp_output(tp);
2295 KASSERT(tp->snd_limited <= 2,
2296 ("%s: tp->snd_limited too big",
2298 tp->snd_cwnd = tp->snd_ssthresh +
2300 (tp->t_dupacks - tp->snd_limited);
2301 if (SEQ_GT(onxt, tp->snd_nxt))
2304 } else if (V_tcp_do_rfc3042) {
2305 cc_ack_received(tp, th, CC_DUPACK);
2306 u_long oldcwnd = tp->snd_cwnd;
2307 tcp_seq oldsndmax = tp->snd_max;
2310 KASSERT(tp->t_dupacks == 1 ||
2312 ("%s: dupacks not 1 or 2",
2314 if (tp->t_dupacks == 1)
2315 tp->snd_limited = 0;
2317 (tp->snd_nxt - tp->snd_una) +
2318 (tp->t_dupacks - tp->snd_limited) *
2320 (void) tcp_output(tp);
2321 sent = tp->snd_max - oldsndmax;
2322 if (sent > tp->t_maxseg) {
2323 KASSERT((tp->t_dupacks == 2 &&
2324 tp->snd_limited == 0) ||
2325 (sent == tp->t_maxseg + 1 &&
2326 tp->t_flags & TF_SENTFIN),
2327 ("%s: sent too much",
2329 tp->snd_limited = 2;
2330 } else if (sent > 0)
2332 tp->snd_cwnd = oldcwnd;
2340 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2341 ("%s: th_ack <= snd_una", __func__));
2344 * If the congestion window was inflated to account
2345 * for the other side's cached packets, retract it.
2347 if (IN_FASTRECOVERY(tp->t_flags)) {
2348 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2349 if (tp->t_flags & TF_SACK_PERMIT)
2350 tcp_sack_partialack(tp, th);
2352 tcp_newreno_partial_ack(tp, th);
2354 cc_post_recovery(tp, th);
2358 * If we reach this point, ACK is not a duplicate,
2359 * i.e., it ACKs something we sent.
2361 if (tp->t_flags & TF_NEEDSYN) {
2363 * T/TCP: Connection was half-synchronized, and our
2364 * SYN has been ACK'd (so connection is now fully
2365 * synchronized). Go to non-starred state,
2366 * increment snd_una for ACK of SYN, and check if
2367 * we can do window scaling.
2369 tp->t_flags &= ~TF_NEEDSYN;
2371 /* Do window scaling? */
2372 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2373 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2374 tp->rcv_scale = tp->request_r_scale;
2375 /* Send window already scaled. */
2380 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2381 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2382 ("tcp_input: process_ACK ti_locked %d", ti_locked));
2383 INP_WLOCK_ASSERT(tp->t_inpcb);
2385 acked = BYTES_THIS_ACK(tp, th);
2386 TCPSTAT_INC(tcps_rcvackpack);
2387 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2390 * If we just performed our first retransmit, and the ACK
2391 * arrives within our recovery window, then it was a mistake
2392 * to do the retransmit in the first place. Recover our
2393 * original cwnd and ssthresh, and proceed to transmit where
2396 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0)
2397 cc_cong_signal(tp, th, CC_RTO_ERR);
2400 * If we have a timestamp reply, update smoothed
2401 * round trip time. If no timestamp is present but
2402 * transmit timer is running and timed sequence
2403 * number was acked, update smoothed round trip time.
2404 * Since we now have an rtt measurement, cancel the
2405 * timer backoff (cf., Phil Karn's retransmit alg.).
2406 * Recompute the initial retransmit timer.
2408 * Some boxes send broken timestamp replies
2409 * during the SYN+ACK phase, ignore
2410 * timestamps of 0 or we could calculate a
2411 * huge RTT and blow up the retransmit timer.
2413 if ((to.to_flags & TOF_TS) != 0 &&
2415 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2416 tp->t_rttlow = ticks - to.to_tsecr;
2417 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2418 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2419 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2420 tp->t_rttlow = ticks - tp->t_rtttime;
2421 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2425 * If all outstanding data is acked, stop retransmit
2426 * timer and remember to restart (more output or persist).
2427 * If there is more data to be acked, restart retransmit
2428 * timer, using current (possibly backed-off) value.
2430 if (th->th_ack == tp->snd_max) {
2431 tcp_timer_activate(tp, TT_REXMT, 0);
2433 } else if (!tcp_timer_active(tp, TT_PERSIST))
2434 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2437 * If no data (only SYN) was ACK'd,
2438 * skip rest of ACK processing.
2444 * Let the congestion control algorithm update congestion
2445 * control related information. This typically means increasing
2446 * the congestion window.
2448 cc_ack_received(tp, th, CC_ACK);
2450 SOCKBUF_LOCK(&so->so_snd);
2451 if (acked > so->so_snd.sb_cc) {
2452 tp->snd_wnd -= so->so_snd.sb_cc;
2453 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2456 sbdrop_locked(&so->so_snd, acked);
2457 tp->snd_wnd -= acked;
2460 /* NB: sowwakeup_locked() does an implicit unlock. */
2461 sowwakeup_locked(so);
2462 /* Detect una wraparound. */
2463 if (!IN_RECOVERY(tp->t_flags) &&
2464 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2465 SEQ_LEQ(th->th_ack, tp->snd_recover))
2466 tp->snd_recover = th->th_ack - 1;
2467 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2468 if (IN_RECOVERY(tp->t_flags) &&
2469 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2470 EXIT_RECOVERY(tp->t_flags);
2472 tp->snd_una = th->th_ack;
2473 if (tp->t_flags & TF_SACK_PERMIT) {
2474 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2475 tp->snd_recover = tp->snd_una;
2477 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2478 tp->snd_nxt = tp->snd_una;
2480 switch (tp->t_state) {
2483 * In FIN_WAIT_1 STATE in addition to the processing
2484 * for the ESTABLISHED state if our FIN is now acknowledged
2485 * then enter FIN_WAIT_2.
2487 case TCPS_FIN_WAIT_1:
2488 if (ourfinisacked) {
2490 * If we can't receive any more
2491 * data, then closing user can proceed.
2492 * Starting the timer is contrary to the
2493 * specification, but if we don't get a FIN
2494 * we'll hang forever.
2497 * we should release the tp also, and use a
2500 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2503 soisdisconnected(so);
2504 timeout = (tcp_fast_finwait2_recycle) ?
2505 tcp_finwait2_timeout : tcp_maxidle;
2506 tcp_timer_activate(tp, TT_2MSL, timeout);
2508 tp->t_state = TCPS_FIN_WAIT_2;
2513 * In CLOSING STATE in addition to the processing for
2514 * the ESTABLISHED state if the ACK acknowledges our FIN
2515 * then enter the TIME-WAIT state, otherwise ignore
2519 if (ourfinisacked) {
2520 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2522 INP_INFO_WUNLOCK(&V_tcbinfo);
2529 * In LAST_ACK, we may still be waiting for data to drain
2530 * and/or to be acked, as well as for the ack of our FIN.
2531 * If our FIN is now acknowledged, delete the TCB,
2532 * enter the closed state and return.
2535 if (ourfinisacked) {
2536 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2545 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2546 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2547 ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2548 INP_WLOCK_ASSERT(tp->t_inpcb);
2551 * Update window information.
2552 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2554 if ((thflags & TH_ACK) &&
2555 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2556 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2557 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2558 /* keep track of pure window updates */
2560 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2561 TCPSTAT_INC(tcps_rcvwinupd);
2562 tp->snd_wnd = tiwin;
2563 tp->snd_wl1 = th->th_seq;
2564 tp->snd_wl2 = th->th_ack;
2565 if (tp->snd_wnd > tp->max_sndwnd)
2566 tp->max_sndwnd = tp->snd_wnd;
2571 * Process segments with URG.
2573 if ((thflags & TH_URG) && th->th_urp &&
2574 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2576 * This is a kludge, but if we receive and accept
2577 * random urgent pointers, we'll crash in
2578 * soreceive. It's hard to imagine someone
2579 * actually wanting to send this much urgent data.
2581 SOCKBUF_LOCK(&so->so_rcv);
2582 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2583 th->th_urp = 0; /* XXX */
2584 thflags &= ~TH_URG; /* XXX */
2585 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2586 goto dodata; /* XXX */
2589 * If this segment advances the known urgent pointer,
2590 * then mark the data stream. This should not happen
2591 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2592 * a FIN has been received from the remote side.
2593 * In these states we ignore the URG.
2595 * According to RFC961 (Assigned Protocols),
2596 * the urgent pointer points to the last octet
2597 * of urgent data. We continue, however,
2598 * to consider it to indicate the first octet
2599 * of data past the urgent section as the original
2600 * spec states (in one of two places).
2602 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2603 tp->rcv_up = th->th_seq + th->th_urp;
2604 so->so_oobmark = so->so_rcv.sb_cc +
2605 (tp->rcv_up - tp->rcv_nxt) - 1;
2606 if (so->so_oobmark == 0)
2607 so->so_rcv.sb_state |= SBS_RCVATMARK;
2609 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2611 SOCKBUF_UNLOCK(&so->so_rcv);
2613 * Remove out of band data so doesn't get presented to user.
2614 * This can happen independent of advancing the URG pointer,
2615 * but if two URG's are pending at once, some out-of-band
2616 * data may creep in... ick.
2618 if (th->th_urp <= (u_long)tlen &&
2619 !(so->so_options & SO_OOBINLINE)) {
2620 /* hdr drop is delayed */
2621 tcp_pulloutofband(so, th, m, drop_hdrlen);
2625 * If no out of band data is expected,
2626 * pull receive urgent pointer along
2627 * with the receive window.
2629 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2630 tp->rcv_up = tp->rcv_nxt;
2633 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2634 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2635 ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2636 INP_WLOCK_ASSERT(tp->t_inpcb);
2639 * Process the segment text, merging it into the TCP sequencing queue,
2640 * and arranging for acknowledgment of receipt if necessary.
2641 * This process logically involves adjusting tp->rcv_wnd as data
2642 * is presented to the user (this happens in tcp_usrreq.c,
2643 * case PRU_RCVD). If a FIN has already been received on this
2644 * connection then we just ignore the text.
2646 if ((tlen || (thflags & TH_FIN)) &&
2647 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2648 tcp_seq save_start = th->th_seq;
2649 m_adj(m, drop_hdrlen); /* delayed header drop */
2651 * Insert segment which includes th into TCP reassembly queue
2652 * with control block tp. Set thflags to whether reassembly now
2653 * includes a segment with FIN. This handles the common case
2654 * inline (segment is the next to be received on an established
2655 * connection, and the queue is empty), avoiding linkage into
2656 * and removal from the queue and repetition of various
2658 * Set DELACK for segments received in order, but ack
2659 * immediately when segments are out of order (so
2660 * fast retransmit can work).
2662 if (th->th_seq == tp->rcv_nxt &&
2663 LIST_EMPTY(&tp->t_segq) &&
2664 TCPS_HAVEESTABLISHED(tp->t_state)) {
2666 tp->t_flags |= TF_DELACK;
2668 tp->t_flags |= TF_ACKNOW;
2669 tp->rcv_nxt += tlen;
2670 thflags = th->th_flags & TH_FIN;
2671 TCPSTAT_INC(tcps_rcvpack);
2672 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2674 SOCKBUF_LOCK(&so->so_rcv);
2675 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2678 sbappendstream_locked(&so->so_rcv, m);
2679 /* NB: sorwakeup_locked() does an implicit unlock. */
2680 sorwakeup_locked(so);
2683 * XXX: Due to the header drop above "th" is
2684 * theoretically invalid by now. Fortunately
2685 * m_adj() doesn't actually frees any mbufs
2686 * when trimming from the head.
2688 thflags = tcp_reass(tp, th, &tlen, m);
2689 tp->t_flags |= TF_ACKNOW;
2691 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2692 tcp_update_sack_list(tp, save_start, save_start + tlen);
2695 * Note the amount of data that peer has sent into
2696 * our window, in order to estimate the sender's
2700 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2708 * If FIN is received ACK the FIN and let the user know
2709 * that the connection is closing.
2711 if (thflags & TH_FIN) {
2712 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2715 * If connection is half-synchronized
2716 * (ie NEEDSYN flag on) then delay ACK,
2717 * so it may be piggybacked when SYN is sent.
2718 * Otherwise, since we received a FIN then no
2719 * more input can be expected, send ACK now.
2721 if (tp->t_flags & TF_NEEDSYN)
2722 tp->t_flags |= TF_DELACK;
2724 tp->t_flags |= TF_ACKNOW;
2727 switch (tp->t_state) {
2730 * In SYN_RECEIVED and ESTABLISHED STATES
2731 * enter the CLOSE_WAIT state.
2733 case TCPS_SYN_RECEIVED:
2734 tp->t_starttime = ticks;
2736 case TCPS_ESTABLISHED:
2737 tp->t_state = TCPS_CLOSE_WAIT;
2741 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2742 * enter the CLOSING state.
2744 case TCPS_FIN_WAIT_1:
2745 tp->t_state = TCPS_CLOSING;
2749 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2750 * starting the time-wait timer, turning off the other
2753 case TCPS_FIN_WAIT_2:
2754 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2755 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2756 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2760 INP_INFO_WUNLOCK(&V_tcbinfo);
2764 if (ti_locked == TI_RLOCKED)
2765 INP_INFO_RUNLOCK(&V_tcbinfo);
2766 else if (ti_locked == TI_WLOCKED)
2767 INP_INFO_WUNLOCK(&V_tcbinfo);
2769 panic("%s: dodata epilogue ti_locked %d", __func__,
2771 ti_locked = TI_UNLOCKED;
2774 if (so->so_options & SO_DEBUG)
2775 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2780 * Return any desired output.
2782 if (needoutput || (tp->t_flags & TF_ACKNOW))
2783 (void) tcp_output(tp);
2786 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2787 __func__, ti_locked));
2788 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2789 INP_WLOCK_ASSERT(tp->t_inpcb);
2791 if (tp->t_flags & TF_DELACK) {
2792 tp->t_flags &= ~TF_DELACK;
2793 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2795 INP_WUNLOCK(tp->t_inpcb);
2799 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2800 ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2803 * Generate an ACK dropping incoming segment if it occupies
2804 * sequence space, where the ACK reflects our state.
2806 * We can now skip the test for the RST flag since all
2807 * paths to this code happen after packets containing
2808 * RST have been dropped.
2810 * In the SYN-RECEIVED state, don't send an ACK unless the
2811 * segment we received passes the SYN-RECEIVED ACK test.
2812 * If it fails send a RST. This breaks the loop in the
2813 * "LAND" DoS attack, and also prevents an ACK storm
2814 * between two listening ports that have been sent forged
2815 * SYN segments, each with the source address of the other.
2817 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2818 (SEQ_GT(tp->snd_una, th->th_ack) ||
2819 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2820 rstreason = BANDLIM_RST_OPENPORT;
2824 if (so->so_options & SO_DEBUG)
2825 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2828 if (ti_locked == TI_RLOCKED)
2829 INP_INFO_RUNLOCK(&V_tcbinfo);
2830 else if (ti_locked == TI_WLOCKED)
2831 INP_INFO_WUNLOCK(&V_tcbinfo);
2833 panic("%s: dropafterack epilogue ti_locked %d", __func__,
2835 ti_locked = TI_UNLOCKED;
2837 tp->t_flags |= TF_ACKNOW;
2838 (void) tcp_output(tp);
2839 INP_WUNLOCK(tp->t_inpcb);
2844 if (ti_locked == TI_RLOCKED)
2845 INP_INFO_RUNLOCK(&V_tcbinfo);
2846 else if (ti_locked == TI_WLOCKED)
2847 INP_INFO_WUNLOCK(&V_tcbinfo);
2849 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2850 ti_locked = TI_UNLOCKED;
2853 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2854 INP_WUNLOCK(tp->t_inpcb);
2856 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2860 if (ti_locked == TI_RLOCKED)
2861 INP_INFO_RUNLOCK(&V_tcbinfo);
2862 else if (ti_locked == TI_WLOCKED)
2863 INP_INFO_WUNLOCK(&V_tcbinfo);
2866 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2868 ti_locked = TI_UNLOCKED;
2871 * Drop space held by incoming segment and return.
2874 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2875 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2879 INP_WUNLOCK(tp->t_inpcb);
2884 * Issue RST and make ACK acceptable to originator of segment.
2885 * The mbuf must still include the original packet header.
2889 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2890 int tlen, int rstreason)
2894 struct ip6_hdr *ip6;
2898 INP_WLOCK_ASSERT(tp->t_inpcb);
2901 /* Don't bother if destination was broadcast/multicast. */
2902 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2905 if (mtod(m, struct ip *)->ip_v == 6) {
2906 ip6 = mtod(m, struct ip6_hdr *);
2907 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2908 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2910 /* IPv6 anycast check is done at tcp6_input() */
2914 ip = mtod(m, struct ip *);
2915 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2916 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2917 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2918 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2922 /* Perform bandwidth limiting. */
2923 if (badport_bandlim(rstreason) < 0)
2926 /* tcp_respond consumes the mbuf chain. */
2927 if (th->th_flags & TH_ACK) {
2928 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2929 th->th_ack, TH_RST);
2931 if (th->th_flags & TH_SYN)
2933 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2934 (tcp_seq)0, TH_RST|TH_ACK);
2942 * Parse TCP options and place in tcpopt.
2945 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2950 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2952 if (opt == TCPOPT_EOL)
2954 if (opt == TCPOPT_NOP)
2960 if (optlen < 2 || optlen > cnt)
2965 if (optlen != TCPOLEN_MAXSEG)
2967 if (!(flags & TO_SYN))
2969 to->to_flags |= TOF_MSS;
2970 bcopy((char *)cp + 2,
2971 (char *)&to->to_mss, sizeof(to->to_mss));
2972 to->to_mss = ntohs(to->to_mss);
2975 if (optlen != TCPOLEN_WINDOW)
2977 if (!(flags & TO_SYN))
2979 to->to_flags |= TOF_SCALE;
2980 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2982 case TCPOPT_TIMESTAMP:
2983 if (optlen != TCPOLEN_TIMESTAMP)
2985 to->to_flags |= TOF_TS;
2986 bcopy((char *)cp + 2,
2987 (char *)&to->to_tsval, sizeof(to->to_tsval));
2988 to->to_tsval = ntohl(to->to_tsval);
2989 bcopy((char *)cp + 6,
2990 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2991 to->to_tsecr = ntohl(to->to_tsecr);
2993 #ifdef TCP_SIGNATURE
2995 * XXX In order to reply to a host which has set the
2996 * TCP_SIGNATURE option in its initial SYN, we have to
2997 * record the fact that the option was observed here
2998 * for the syncache code to perform the correct response.
3000 case TCPOPT_SIGNATURE:
3001 if (optlen != TCPOLEN_SIGNATURE)
3003 to->to_flags |= TOF_SIGNATURE;
3004 to->to_signature = cp + 2;
3007 case TCPOPT_SACK_PERMITTED:
3008 if (optlen != TCPOLEN_SACK_PERMITTED)
3010 if (!(flags & TO_SYN))
3014 to->to_flags |= TOF_SACKPERM;
3017 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3021 to->to_flags |= TOF_SACK;
3022 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3023 to->to_sacks = cp + 2;
3024 TCPSTAT_INC(tcps_sack_rcv_blocks);
3033 * Pull out of band byte out of a segment so
3034 * it doesn't appear in the user's data queue.
3035 * It is still reflected in the segment length for
3036 * sequencing purposes.
3039 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3042 int cnt = off + th->th_urp - 1;
3045 if (m->m_len > cnt) {
3046 char *cp = mtod(m, caddr_t) + cnt;
3047 struct tcpcb *tp = sototcpcb(so);
3049 INP_WLOCK_ASSERT(tp->t_inpcb);
3052 tp->t_oobflags |= TCPOOB_HAVEDATA;
3053 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3055 if (m->m_flags & M_PKTHDR)
3064 panic("tcp_pulloutofband");
3068 * Collect new round-trip time estimate
3069 * and update averages and current timeout.
3072 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3076 INP_WLOCK_ASSERT(tp->t_inpcb);
3078 TCPSTAT_INC(tcps_rttupdated);
3080 if (tp->t_srtt != 0) {
3082 * srtt is stored as fixed point with 5 bits after the
3083 * binary point (i.e., scaled by 8). The following magic
3084 * is equivalent to the smoothing algorithm in rfc793 with
3085 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3086 * point). Adjust rtt to origin 0.
3088 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3089 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3091 if ((tp->t_srtt += delta) <= 0)
3095 * We accumulate a smoothed rtt variance (actually, a
3096 * smoothed mean difference), then set the retransmit
3097 * timer to smoothed rtt + 4 times the smoothed variance.
3098 * rttvar is stored as fixed point with 4 bits after the
3099 * binary point (scaled by 16). The following is
3100 * equivalent to rfc793 smoothing with an alpha of .75
3101 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3102 * rfc793's wired-in beta.
3106 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3107 if ((tp->t_rttvar += delta) <= 0)
3109 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3110 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3113 * No rtt measurement yet - use the unsmoothed rtt.
3114 * Set the variance to half the rtt (so our first
3115 * retransmit happens at 3*rtt).
3117 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3118 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3119 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3125 * the retransmit should happen at rtt + 4 * rttvar.
3126 * Because of the way we do the smoothing, srtt and rttvar
3127 * will each average +1/2 tick of bias. When we compute
3128 * the retransmit timer, we want 1/2 tick of rounding and
3129 * 1 extra tick because of +-1/2 tick uncertainty in the
3130 * firing of the timer. The bias will give us exactly the
3131 * 1.5 tick we need. But, because the bias is
3132 * statistical, we have to test that we don't drop below
3133 * the minimum feasible timer (which is 2 ticks).
3135 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3136 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3139 * We received an ack for a packet that wasn't retransmitted;
3140 * it is probably safe to discard any error indications we've
3141 * received recently. This isn't quite right, but close enough
3142 * for now (a route might have failed after we sent a segment,
3143 * and the return path might not be symmetrical).
3145 tp->t_softerror = 0;
3149 * Determine a reasonable value for maxseg size.
3150 * If the route is known, check route for mtu.
3151 * If none, use an mss that can be handled on the outgoing
3152 * interface without forcing IP to fragment; if bigger than
3153 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3154 * to utilize large mbufs. If no route is found, route has no mtu,
3155 * or the destination isn't local, use a default, hopefully conservative
3156 * size (usually 512 or the default IP max size, but no more than the mtu
3157 * of the interface), as we can't discover anything about intervening
3158 * gateways or networks. We also initialize the congestion/slow start
3159 * window to be a single segment if the destination isn't local.
3160 * While looking at the routing entry, we also initialize other path-dependent
3161 * parameters from pre-set or cached values in the routing entry.
3163 * Also take into account the space needed for options that we
3164 * send regularly. Make maxseg shorter by that amount to assure
3165 * that we can send maxseg amount of data even when the options
3166 * are present. Store the upper limit of the length of options plus
3169 * In case of T/TCP, we call this routine during implicit connection
3170 * setup as well (offer = -1), to initialize maxseg from the cached
3173 * NOTE that this routine is only called when we process an incoming
3174 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3177 tcp_mss_update(struct tcpcb *tp, int offer,
3178 struct hc_metrics_lite *metricptr, int *mtuflags)
3182 struct inpcb *inp = tp->t_inpcb;
3183 struct hc_metrics_lite metrics;
3184 int origoffer = offer;
3186 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3187 size_t min_protoh = isipv6 ?
3188 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3189 sizeof (struct tcpiphdr);
3191 const size_t min_protoh = sizeof(struct tcpiphdr);
3194 INP_WLOCK_ASSERT(tp->t_inpcb);
3199 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3200 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3204 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3205 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3209 * No route to sender, stay with default mss and return.
3213 * In case we return early we need to initialize metrics
3214 * to a defined state as tcp_hc_get() would do for us
3215 * if there was no cache hit.
3217 if (metricptr != NULL)
3218 bzero(metricptr, sizeof(struct hc_metrics_lite));
3222 /* What have we got? */
3226 * Offer == 0 means that there was no MSS on the SYN
3227 * segment, in this case we use tcp_mssdflt as
3228 * already assigned to t_maxopd above.
3230 offer = tp->t_maxopd;
3235 * Offer == -1 means that we didn't receive SYN yet.
3241 * Prevent DoS attack with too small MSS. Round up
3242 * to at least minmss.
3244 offer = max(offer, V_tcp_minmss);
3248 * rmx information is now retrieved from tcp_hostcache.
3250 tcp_hc_get(&inp->inp_inc, &metrics);
3251 if (metricptr != NULL)
3252 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3255 * If there's a discovered mtu int tcp hostcache, use it
3256 * else, use the link mtu.
3258 if (metrics.rmx_mtu)
3259 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3263 mss = maxmtu - min_protoh;
3264 if (!V_path_mtu_discovery &&
3265 !in6_localaddr(&inp->in6p_faddr))
3266 mss = min(mss, V_tcp_v6mssdflt);
3270 mss = maxmtu - min_protoh;
3271 if (!V_path_mtu_discovery &&
3272 !in_localaddr(inp->inp_faddr))
3273 mss = min(mss, V_tcp_mssdflt);
3276 * XXX - The above conditional (mss = maxmtu - min_protoh)
3277 * probably violates the TCP spec.
3278 * The problem is that, since we don't know the
3279 * other end's MSS, we are supposed to use a conservative
3280 * default. But, if we do that, then MTU discovery will
3281 * never actually take place, because the conservative
3282 * default is much less than the MTUs typically seen
3283 * on the Internet today. For the moment, we'll sweep
3284 * this under the carpet.
3286 * The conservative default might not actually be a problem
3287 * if the only case this occurs is when sending an initial
3288 * SYN with options and data to a host we've never talked
3289 * to before. Then, they will reply with an MSS value which
3290 * will get recorded and the new parameters should get
3291 * recomputed. For Further Study.
3294 mss = min(mss, offer);
3297 * Sanity check: make sure that maxopd will be large
3298 * enough to allow some data on segments even if the
3299 * all the option space is used (40bytes). Otherwise
3300 * funny things may happen in tcp_output.
3305 * maxopd stores the maximum length of data AND options
3306 * in a segment; maxseg is the amount of data in a normal
3307 * segment. We need to store this value (maxopd) apart
3308 * from maxseg, because now every segment carries options
3309 * and thus we normally have somewhat less data in segments.
3314 * origoffer==-1 indicates that no segments were received yet.
3315 * In this case we just guess.
3317 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3319 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3320 mss -= TCPOLEN_TSTAMP_APPA;
3322 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3324 mss &= ~(MCLBYTES-1);
3327 mss = mss / MCLBYTES * MCLBYTES;
3333 tcp_mss(struct tcpcb *tp, int offer)
3339 struct hc_metrics_lite metrics;
3342 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3344 tcp_mss_update(tp, offer, &metrics, &mtuflags);
3350 * If there's a pipesize, change the socket buffer to that size,
3351 * don't change if sb_hiwat is different than default (then it
3352 * has been changed on purpose with setsockopt).
3353 * Make the socket buffers an integral number of mss units;
3354 * if the mss is larger than the socket buffer, decrease the mss.
3356 so = inp->inp_socket;
3357 SOCKBUF_LOCK(&so->so_snd);
3358 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3359 bufsize = metrics.rmx_sendpipe;
3361 bufsize = so->so_snd.sb_hiwat;
3365 bufsize = roundup(bufsize, mss);
3366 if (bufsize > sb_max)
3368 if (bufsize > so->so_snd.sb_hiwat)
3369 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3371 SOCKBUF_UNLOCK(&so->so_snd);
3374 SOCKBUF_LOCK(&so->so_rcv);
3375 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3376 bufsize = metrics.rmx_recvpipe;
3378 bufsize = so->so_rcv.sb_hiwat;
3379 if (bufsize > mss) {
3380 bufsize = roundup(bufsize, mss);
3381 if (bufsize > sb_max)
3383 if (bufsize > so->so_rcv.sb_hiwat)
3384 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3386 SOCKBUF_UNLOCK(&so->so_rcv);
3388 /* Check the interface for TSO capabilities. */
3389 if (mtuflags & CSUM_TSO)
3390 tp->t_flags |= TF_TSO;
3394 * Determine the MSS option to send on an outgoing SYN.
3397 tcp_mssopt(struct in_conninfo *inc)
3404 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3407 if (inc->inc_flags & INC_ISIPV6) {
3408 mss = V_tcp_v6mssdflt;
3409 maxmtu = tcp_maxmtu6(inc, NULL);
3410 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3411 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3415 mss = V_tcp_mssdflt;
3416 maxmtu = tcp_maxmtu(inc, NULL);
3417 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3418 min_protoh = sizeof(struct tcpiphdr);
3420 if (maxmtu && thcmtu)
3421 mss = min(maxmtu, thcmtu) - min_protoh;
3422 else if (maxmtu || thcmtu)
3423 mss = max(maxmtu, thcmtu) - min_protoh;
3430 * On a partial ack arrives, force the retransmission of the
3431 * next unacknowledged segment. Do not clear tp->t_dupacks.
3432 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3436 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3438 tcp_seq onxt = tp->snd_nxt;
3439 u_long ocwnd = tp->snd_cwnd;
3441 INP_WLOCK_ASSERT(tp->t_inpcb);
3443 tcp_timer_activate(tp, TT_REXMT, 0);
3445 tp->snd_nxt = th->th_ack;
3447 * Set snd_cwnd to one segment beyond acknowledged offset.
3448 * (tp->snd_una has not yet been updated when this function is called.)
3450 tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3451 tp->t_flags |= TF_ACKNOW;
3452 (void) tcp_output(tp);
3453 tp->snd_cwnd = ocwnd;
3454 if (SEQ_GT(onxt, tp->snd_nxt))
3457 * Partial window deflation. Relies on fact that tp->snd_una
3460 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3461 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3464 tp->snd_cwnd += tp->t_maxseg;