2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include "opt_ipfw.h" /* for ipfw_fwd */
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
41 #include <sys/param.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
45 #include <sys/proc.h> /* for proc0 declaration */
46 #include <sys/protosw.h>
47 #include <sys/signalvar.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/systm.h>
54 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
59 #include <net/route.h>
62 #define TCPSTATES /* for logging */
64 #include <netinet/in.h>
65 #include <netinet/in_pcb.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/in_var.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
70 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
71 #include <netinet/ip_var.h>
72 #include <netinet/ip_options.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet6/in6_pcb.h>
76 #include <netinet6/ip6_var.h>
77 #include <netinet6/nd6.h>
78 #include <netinet/tcp.h>
79 #include <netinet/tcp_fsm.h>
80 #include <netinet/tcp_seq.h>
81 #include <netinet/tcp_timer.h>
82 #include <netinet/tcp_var.h>
83 #include <netinet6/tcp6_var.h>
84 #include <netinet/tcpip.h>
85 #include <netinet/tcp_syncache.h>
87 #include <netinet/tcp_debug.h>
91 #include <netipsec/ipsec.h>
92 #include <netipsec/ipsec6.h>
95 #include <machine/in_cksum.h>
97 #include <security/mac/mac_framework.h>
99 static const int tcprexmtthresh = 3;
101 VNET_DEFINE(struct tcpstat, tcpstat);
102 SYSCTL_VNET_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
103 &VNET_NAME(tcpstat), tcpstat,
104 "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
106 int tcp_log_in_vain = 0;
107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
109 "Log all incoming TCP segments to closed ports");
111 VNET_DEFINE(int, blackhole) = 0;
112 #define V_blackhole VNET(blackhole)
113 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
114 &VNET_NAME(blackhole), 0,
115 "Do not send RST on segments to closed ports");
117 VNET_DEFINE(int, tcp_delack_enabled) = 1;
118 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
119 &VNET_NAME(tcp_delack_enabled), 0,
120 "Delay ACK to try and piggyback it onto a data packet");
122 VNET_DEFINE(int, drop_synfin) = 0;
123 #define V_drop_synfin VNET(drop_synfin)
124 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
125 &VNET_NAME(drop_synfin), 0,
126 "Drop TCP packets with SYN+FIN set");
128 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
129 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
130 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
131 &VNET_NAME(tcp_do_rfc3042), 0,
132 "Enable RFC 3042 (Limited Transmit)");
134 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
135 #define V_tcp_do_rfc3390 VNET(tcp_do_rfc3390)
136 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
137 &VNET_NAME(tcp_do_rfc3390), 0,
138 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
140 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
141 #define V_tcp_do_rfc3465 VNET(tcp_do_rfc3465)
142 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
143 &VNET_NAME(tcp_do_rfc3465), 0,
144 "Enable RFC 3465 (Appropriate Byte Counting)");
146 VNET_DEFINE(int, tcp_abc_l_var) = 2;
147 #define V_tcp_abc_l_var VNET(tcp_abc_l_var)
148 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
149 &VNET_NAME(tcp_abc_l_var), 2,
150 "Cap the max cwnd increment during slow-start to this number of segments");
152 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
154 VNET_DEFINE(int, tcp_do_ecn) = 0;
155 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
156 &VNET_NAME(tcp_do_ecn), 0,
159 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
160 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
161 &VNET_NAME(tcp_ecn_maxretries), 0,
162 "Max retries before giving up on ECN");
164 VNET_DEFINE(int, tcp_insecure_rst) = 0;
165 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
166 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
167 &VNET_NAME(tcp_insecure_rst), 0,
168 "Follow the old (insecure) criteria for accepting RST packets");
170 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
171 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
172 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
173 &VNET_NAME(tcp_do_autorcvbuf), 0,
174 "Enable automatic receive buffer sizing");
176 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
177 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
178 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
179 &VNET_NAME(tcp_autorcvbuf_inc), 0,
180 "Incrementor step size of automatic receive buffer");
182 VNET_DEFINE(int, tcp_autorcvbuf_max) = 256*1024;
183 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
184 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
185 &VNET_NAME(tcp_autorcvbuf_max), 0,
186 "Max size of automatic receive buffer");
188 int tcp_read_locking = 1;
189 SYSCTL_INT(_net_inet_tcp, OID_AUTO, read_locking, CTLFLAG_RW,
190 &tcp_read_locking, 0, "Enable read locking strategy");
192 VNET_DEFINE(struct inpcbhead, tcb);
193 #define tcb6 tcb /* for KAME src sync over BSD*'s */
194 VNET_DEFINE(struct inpcbinfo, tcbinfo);
196 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
197 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
198 struct socket *, struct tcpcb *, int, int, uint8_t,
200 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
201 struct tcpcb *, int, int);
202 static void tcp_pulloutofband(struct socket *,
203 struct tcphdr *, struct mbuf *, int);
204 static void tcp_xmit_timer(struct tcpcb *, int);
205 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
207 tcp_congestion_exp(struct tcpcb *);
210 * Kernel module interface for updating tcpstat. The argument is an index
211 * into tcpstat treated as an array of u_long. While this encodes the
212 * general layout of tcpstat into the caller, it doesn't encode its location,
213 * so that future changes to add, for example, per-CPU stats support won't
214 * cause binary compatibility problems for kernel modules.
217 kmod_tcpstat_inc(int statnum)
220 (*((u_long *)&V_tcpstat + statnum))++;
224 tcp_congestion_exp(struct tcpcb *tp)
228 win = min(tp->snd_wnd, tp->snd_cwnd) /
232 tp->snd_ssthresh = win * tp->t_maxseg;
233 ENTER_FASTRECOVERY(tp);
234 tp->snd_recover = tp->snd_max;
235 if (tp->t_flags & TF_ECN_PERMIT)
236 tp->t_flags |= TF_ECN_SND_CWR;
239 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
241 #define ND6_HINT(tp) \
243 if ((tp) && (tp)->t_inpcb && \
244 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
245 nd6_nud_hint(NULL, NULL, 0); \
252 * Indicate whether this ack should be delayed. We can delay the ack if
253 * - there is no delayed ack timer in progress and
254 * - our last ack wasn't a 0-sized window. We never want to delay
255 * the ack that opens up a 0-sized window and
256 * - delayed acks are enabled or
257 * - this is a half-synchronized T/TCP connection.
259 #define DELAY_ACK(tp) \
260 ((!tcp_timer_active(tp, TT_DELACK) && \
261 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
262 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
265 * TCP input handling is split into multiple parts:
266 * tcp6_input is a thin wrapper around tcp_input for the extended
267 * ip6_protox[] call format in ip6_input
268 * tcp_input handles primary segment validation, inpcb lookup and
269 * SYN processing on listen sockets
270 * tcp_do_segment processes the ACK and text of the segment for
271 * establishing, established and closing connections
275 tcp6_input(struct mbuf **mp, int *offp, int proto)
277 struct mbuf *m = *mp;
278 struct in6_ifaddr *ia6;
280 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
283 * draft-itojun-ipv6-tcp-to-anycast
284 * better place to put this in?
286 ia6 = ip6_getdstifaddr(m);
287 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
290 ifa_free(&ia6->ia_ifa);
291 ip6 = mtod(m, struct ip6_hdr *);
292 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
293 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
303 tcp_input(struct mbuf *m, int off0)
306 struct ip *ip = NULL;
308 struct inpcb *inp = NULL;
309 struct tcpcb *tp = NULL;
310 struct socket *so = NULL;
316 int rstreason = 0; /* For badport_bandlim accounting purposes */
318 #ifdef IPFIREWALL_FORWARD
319 struct m_tag *fwd_tag;
322 struct ip6_hdr *ip6 = NULL;
325 const void *ip6 = NULL;
326 const int isipv6 = 0;
328 struct tcpopt to; /* options in this segment */
329 char *s = NULL; /* address and port logging */
331 #define TI_UNLOCKED 1
337 * The size of tcp_saveipgen must be the size of the max ip header,
340 u_char tcp_saveipgen[IP6_HDR_LEN];
341 struct tcphdr tcp_savetcp;
346 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
350 TCPSTAT_INC(tcps_rcvtotal);
354 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
355 ip6 = mtod(m, struct ip6_hdr *);
356 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
357 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
358 TCPSTAT_INC(tcps_rcvbadsum);
361 th = (struct tcphdr *)((caddr_t)ip6 + off0);
364 * Be proactive about unspecified IPv6 address in source.
365 * As we use all-zero to indicate unbounded/unconnected pcb,
366 * unspecified IPv6 address can be used to confuse us.
368 * Note that packets with unspecified IPv6 destination is
369 * already dropped in ip6_input.
371 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
376 th = NULL; /* XXX: Avoid compiler warning. */
380 * Get IP and TCP header together in first mbuf.
381 * Note: IP leaves IP header in first mbuf.
383 if (off0 > sizeof (struct ip)) {
384 ip_stripoptions(m, (struct mbuf *)0);
385 off0 = sizeof(struct ip);
387 if (m->m_len < sizeof (struct tcpiphdr)) {
388 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
390 TCPSTAT_INC(tcps_rcvshort);
394 ip = mtod(m, struct ip *);
395 ipov = (struct ipovly *)ip;
396 th = (struct tcphdr *)((caddr_t)ip + off0);
399 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
400 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
401 th->th_sum = m->m_pkthdr.csum_data;
403 th->th_sum = in_pseudo(ip->ip_src.s_addr,
405 htonl(m->m_pkthdr.csum_data +
408 th->th_sum ^= 0xffff;
410 ipov->ih_len = (u_short)tlen;
411 ipov->ih_len = htons(ipov->ih_len);
415 * Checksum extended TCP header and data.
417 len = sizeof (struct ip) + tlen;
418 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
419 ipov->ih_len = (u_short)tlen;
420 ipov->ih_len = htons(ipov->ih_len);
421 th->th_sum = in_cksum(m, len);
424 TCPSTAT_INC(tcps_rcvbadsum);
427 /* Re-initialization for later version check */
428 ip->ip_v = IPVERSION;
433 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
439 * Check that TCP offset makes sense,
440 * pull out TCP options and adjust length. XXX
442 off = th->th_off << 2;
443 if (off < sizeof (struct tcphdr) || off > tlen) {
444 TCPSTAT_INC(tcps_rcvbadoff);
447 tlen -= off; /* tlen is used instead of ti->ti_len */
448 if (off > sizeof (struct tcphdr)) {
451 IP6_EXTHDR_CHECK(m, off0, off, );
452 ip6 = mtod(m, struct ip6_hdr *);
453 th = (struct tcphdr *)((caddr_t)ip6 + off0);
456 if (m->m_len < sizeof(struct ip) + off) {
457 if ((m = m_pullup(m, sizeof (struct ip) + off))
459 TCPSTAT_INC(tcps_rcvshort);
462 ip = mtod(m, struct ip *);
463 ipov = (struct ipovly *)ip;
464 th = (struct tcphdr *)((caddr_t)ip + off0);
467 optlen = off - sizeof (struct tcphdr);
468 optp = (u_char *)(th + 1);
470 thflags = th->th_flags;
473 * Convert TCP protocol specific fields to host format.
475 th->th_seq = ntohl(th->th_seq);
476 th->th_ack = ntohl(th->th_ack);
477 th->th_win = ntohs(th->th_win);
478 th->th_urp = ntohs(th->th_urp);
481 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
483 drop_hdrlen = off0 + off;
486 * Locate pcb for segment, which requires a lock on tcbinfo.
487 * Optimisticaly acquire a global read lock rather than a write lock
488 * unless header flags necessarily imply a state change. There are
489 * two cases where we might discover later we need a write lock
490 * despite the flags: ACKs moving a connection out of the syncache,
491 * and ACKs for a connection in TIMEWAIT.
493 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
494 tcp_read_locking == 0) {
495 INP_INFO_WLOCK(&V_tcbinfo);
496 ti_locked = TI_WLOCKED;
498 INP_INFO_RLOCK(&V_tcbinfo);
499 ti_locked = TI_RLOCKED;
504 if (ti_locked == TI_RLOCKED)
505 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
506 else if (ti_locked == TI_WLOCKED)
507 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
509 panic("%s: findpcb ti_locked %d\n", __func__, ti_locked);
512 #ifdef IPFIREWALL_FORWARD
514 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
516 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
518 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
519 struct sockaddr_in *next_hop;
521 next_hop = (struct sockaddr_in *)(fwd_tag+1);
523 * Transparently forwarded. Pretend to be the destination.
524 * already got one like this?
526 inp = in_pcblookup_hash(&V_tcbinfo,
527 ip->ip_src, th->th_sport,
528 ip->ip_dst, th->th_dport,
529 0, m->m_pkthdr.rcvif);
531 /* It's new. Try to find the ambushing socket. */
532 inp = in_pcblookup_hash(&V_tcbinfo,
533 ip->ip_src, th->th_sport,
536 ntohs(next_hop->sin_port) :
541 /* Remove the tag from the packet. We don't need it anymore. */
542 m_tag_delete(m, fwd_tag);
544 #endif /* IPFIREWALL_FORWARD */
548 inp = in6_pcblookup_hash(&V_tcbinfo,
549 &ip6->ip6_src, th->th_sport,
550 &ip6->ip6_dst, th->th_dport,
555 inp = in_pcblookup_hash(&V_tcbinfo,
556 ip->ip_src, th->th_sport,
557 ip->ip_dst, th->th_dport,
563 * If the INPCB does not exist then all data in the incoming
564 * segment is discarded and an appropriate RST is sent back.
565 * XXX MRT Send RST using which routing table?
569 * Log communication attempts to ports that are not
572 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
573 tcp_log_in_vain == 2) {
574 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
575 log(LOG_INFO, "%s; %s: Connection attempt "
576 "to closed port\n", s, __func__);
579 * When blackholing do not respond with a RST but
580 * completely ignore the segment and drop it.
582 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
586 rstreason = BANDLIM_RST_CLOSEDPORT;
590 if (!(inp->inp_flags & INP_HW_FLOWID)
591 && (m->m_flags & M_FLOWID)
592 && ((inp->inp_socket == NULL)
593 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
594 inp->inp_flags |= INP_HW_FLOWID;
595 inp->inp_flags &= ~INP_SW_FLOWID;
596 inp->inp_flowid = m->m_pkthdr.flowid;
600 if (isipv6 && ipsec6_in_reject(m, inp)) {
601 V_ipsec6stat.in_polvio++;
605 if (ipsec4_in_reject(m, inp) != 0) {
606 V_ipsec4stat.in_polvio++;
612 * Check the minimum TTL for socket.
614 if (inp->inp_ip_minttl != 0) {
616 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
620 if (inp->inp_ip_minttl > ip->ip_ttl)
625 * A previous connection in TIMEWAIT state is supposed to catch stray
626 * or duplicate segments arriving late. If this segment was a
627 * legitimate new connection attempt the old INPCB gets removed and
628 * we can try again to find a listening socket.
630 * At this point, due to earlier optimism, we may hold a read lock on
631 * the inpcbinfo, rather than a write lock. If so, we need to
632 * upgrade, or if that fails, acquire a reference on the inpcb, drop
633 * all locks, acquire a global write lock, and then re-acquire the
634 * inpcb lock. We may at that point discover that another thread has
635 * tried to free the inpcb, in which case we need to loop back and
636 * try to find a new inpcb to deliver to.
639 if (inp->inp_flags & INP_TIMEWAIT) {
640 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
641 ("%s: INP_TIMEWAIT ti_locked %d", __func__, ti_locked));
643 if (ti_locked == TI_RLOCKED) {
644 if (INP_INFO_TRY_UPGRADE(&V_tcbinfo) == 0) {
647 INP_INFO_RUNLOCK(&V_tcbinfo);
648 INP_INFO_WLOCK(&V_tcbinfo);
649 ti_locked = TI_WLOCKED;
651 if (in_pcbrele(inp)) {
656 ti_locked = TI_WLOCKED;
658 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
660 if (thflags & TH_SYN)
661 tcp_dooptions(&to, optp, optlen, TO_SYN);
663 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
665 if (tcp_twcheck(inp, &to, th, m, tlen))
667 INP_INFO_WUNLOCK(&V_tcbinfo);
671 * The TCPCB may no longer exist if the connection is winding
672 * down or it is in the CLOSED state. Either way we drop the
673 * segment and send an appropriate response.
676 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
677 rstreason = BANDLIM_RST_CLOSEDPORT;
682 * We've identified a valid inpcb, but it could be that we need an
683 * inpcbinfo write lock and have only a read lock. In this case,
684 * attempt to upgrade/relock using the same strategy as the TIMEWAIT
685 * case above. If we relock, we have to jump back to 'relocked' as
686 * the connection might now be in TIMEWAIT.
688 if (tp->t_state != TCPS_ESTABLISHED ||
689 (thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
690 tcp_read_locking == 0) {
691 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
692 ("%s: upgrade check ti_locked %d", __func__, ti_locked));
694 if (ti_locked == TI_RLOCKED) {
695 if (INP_INFO_TRY_UPGRADE(&V_tcbinfo) == 0) {
698 INP_INFO_RUNLOCK(&V_tcbinfo);
699 INP_INFO_WLOCK(&V_tcbinfo);
700 ti_locked = TI_WLOCKED;
702 if (in_pcbrele(inp)) {
708 ti_locked = TI_WLOCKED;
710 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
714 INP_WLOCK_ASSERT(inp);
715 if (mac_inpcb_check_deliver(inp, m))
718 so = inp->inp_socket;
719 KASSERT(so != NULL, ("%s: so == NULL", __func__));
721 if (so->so_options & SO_DEBUG) {
722 ostate = tp->t_state;
725 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
728 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
733 * When the socket is accepting connections (the INPCB is in LISTEN
734 * state) we look into the SYN cache if this is a new connection
735 * attempt or the completion of a previous one.
737 if (so->so_options & SO_ACCEPTCONN) {
738 struct in_conninfo inc;
740 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
741 "tp not listening", __func__));
743 bzero(&inc, sizeof(inc));
746 inc.inc_flags |= INC_ISIPV6;
747 inc.inc6_faddr = ip6->ip6_src;
748 inc.inc6_laddr = ip6->ip6_dst;
752 inc.inc_faddr = ip->ip_src;
753 inc.inc_laddr = ip->ip_dst;
755 inc.inc_fport = th->th_sport;
756 inc.inc_lport = th->th_dport;
757 inc.inc_fibnum = so->so_fibnum;
760 * Check for an existing connection attempt in syncache if
761 * the flag is only ACK. A successful lookup creates a new
762 * socket appended to the listen queue in SYN_RECEIVED state.
764 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
766 * Parse the TCP options here because
767 * syncookies need access to the reflected
770 tcp_dooptions(&to, optp, optlen, 0);
772 * NB: syncache_expand() doesn't unlock
773 * inp and tcpinfo locks.
775 if (!syncache_expand(&inc, &to, th, &so, m)) {
777 * No syncache entry or ACK was not
778 * for our SYN/ACK. Send a RST.
779 * NB: syncache did its own logging
780 * of the failure cause.
782 rstreason = BANDLIM_RST_OPENPORT;
787 * We completed the 3-way handshake
788 * but could not allocate a socket
789 * either due to memory shortage,
790 * listen queue length limits or
791 * global socket limits. Send RST
792 * or wait and have the remote end
793 * retransmit the ACK for another
796 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
797 log(LOG_DEBUG, "%s; %s: Listen socket: "
798 "Socket allocation failed due to "
799 "limits or memory shortage, %s\n",
801 V_tcp_sc_rst_sock_fail ?
802 "sending RST" : "try again");
803 if (V_tcp_sc_rst_sock_fail) {
804 rstreason = BANDLIM_UNLIMITED;
810 * Socket is created in state SYN_RECEIVED.
811 * Unlock the listen socket, lock the newly
812 * created socket and update the tp variable.
814 INP_WUNLOCK(inp); /* listen socket */
816 INP_WLOCK(inp); /* new connection */
818 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
821 * Process the segment and the data it
822 * contains. tcp_do_segment() consumes
823 * the mbuf chain and unlocks the inpcb.
825 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
827 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
831 * Segment flag validation for new connection attempts:
833 * Our (SYN|ACK) response was rejected.
834 * Check with syncache and remove entry to prevent
837 * NB: syncache_chkrst does its own logging of failure
840 if (thflags & TH_RST) {
841 syncache_chkrst(&inc, th);
845 * We can't do anything without SYN.
847 if ((thflags & TH_SYN) == 0) {
848 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
849 log(LOG_DEBUG, "%s; %s: Listen socket: "
850 "SYN is missing, segment ignored\n",
852 TCPSTAT_INC(tcps_badsyn);
856 * (SYN|ACK) is bogus on a listen socket.
858 if (thflags & TH_ACK) {
859 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
860 log(LOG_DEBUG, "%s; %s: Listen socket: "
861 "SYN|ACK invalid, segment rejected\n",
863 syncache_badack(&inc); /* XXX: Not needed! */
864 TCPSTAT_INC(tcps_badsyn);
865 rstreason = BANDLIM_RST_OPENPORT;
869 * If the drop_synfin option is enabled, drop all
870 * segments with both the SYN and FIN bits set.
871 * This prevents e.g. nmap from identifying the
873 * XXX: Poor reasoning. nmap has other methods
874 * and is constantly refining its stack detection
876 * XXX: This is a violation of the TCP specification
877 * and was used by RFC1644.
879 if ((thflags & TH_FIN) && V_drop_synfin) {
880 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
881 log(LOG_DEBUG, "%s; %s: Listen socket: "
882 "SYN|FIN segment ignored (based on "
883 "sysctl setting)\n", s, __func__);
884 TCPSTAT_INC(tcps_badsyn);
888 * Segment's flags are (SYN) or (SYN|FIN).
890 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
891 * as they do not affect the state of the TCP FSM.
892 * The data pointed to by TH_URG and th_urp is ignored.
894 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
895 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
896 KASSERT(thflags & (TH_SYN),
897 ("%s: Listen socket: TH_SYN not set", __func__));
900 * If deprecated address is forbidden,
901 * we do not accept SYN to deprecated interface
902 * address to prevent any new inbound connection from
903 * getting established.
904 * When we do not accept SYN, we send a TCP RST,
905 * with deprecated source address (instead of dropping
906 * it). We compromise it as it is much better for peer
907 * to send a RST, and RST will be the final packet
910 * If we do not forbid deprecated addresses, we accept
911 * the SYN packet. RFC2462 does not suggest dropping
913 * If we decipher RFC2462 5.5.4, it says like this:
914 * 1. use of deprecated addr with existing
915 * communication is okay - "SHOULD continue to be
917 * 2. use of it with new communication:
918 * (2a) "SHOULD NOT be used if alternate address
919 * with sufficient scope is available"
920 * (2b) nothing mentioned otherwise.
921 * Here we fall into (2b) case as we have no choice in
922 * our source address selection - we must obey the peer.
924 * The wording in RFC2462 is confusing, and there are
925 * multiple description text for deprecated address
926 * handling - worse, they are not exactly the same.
927 * I believe 5.5.4 is the best one, so we follow 5.5.4.
929 if (isipv6 && !V_ip6_use_deprecated) {
930 struct in6_ifaddr *ia6;
932 ia6 = ip6_getdstifaddr(m);
934 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
935 ifa_free(&ia6->ia_ifa);
936 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
937 log(LOG_DEBUG, "%s; %s: Listen socket: "
938 "Connection attempt to deprecated "
939 "IPv6 address rejected\n",
941 rstreason = BANDLIM_RST_OPENPORT;
944 ifa_free(&ia6->ia_ifa);
948 * Basic sanity checks on incoming SYN requests:
949 * Don't respond if the destination is a link layer
950 * broadcast according to RFC1122 4.2.3.10, p. 104.
951 * If it is from this socket it must be forged.
952 * Don't respond if the source or destination is a
953 * global or subnet broad- or multicast address.
954 * Note that it is quite possible to receive unicast
955 * link-layer packets with a broadcast IP address. Use
956 * in_broadcast() to find them.
958 if (m->m_flags & (M_BCAST|M_MCAST)) {
959 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
960 log(LOG_DEBUG, "%s; %s: Listen socket: "
961 "Connection attempt from broad- or multicast "
962 "link layer address ignored\n", s, __func__);
967 if (th->th_dport == th->th_sport &&
968 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
969 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
970 log(LOG_DEBUG, "%s; %s: Listen socket: "
971 "Connection attempt to/from self "
972 "ignored\n", s, __func__);
975 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
976 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
977 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
978 log(LOG_DEBUG, "%s; %s: Listen socket: "
979 "Connection attempt from/to multicast "
980 "address ignored\n", s, __func__);
985 if (th->th_dport == th->th_sport &&
986 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
987 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
988 log(LOG_DEBUG, "%s; %s: Listen socket: "
989 "Connection attempt from/to self "
990 "ignored\n", s, __func__);
993 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
994 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
995 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
996 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
997 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
998 log(LOG_DEBUG, "%s; %s: Listen socket: "
999 "Connection attempt from/to broad- "
1000 "or multicast address ignored\n",
1006 * SYN appears to be valid. Create compressed TCP state
1010 if (so->so_options & SO_DEBUG)
1011 tcp_trace(TA_INPUT, ostate, tp,
1012 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1014 tcp_dooptions(&to, optp, optlen, TO_SYN);
1015 syncache_add(&inc, &to, th, inp, &so, m);
1017 * Entry added to syncache and mbuf consumed.
1018 * Everything already unlocked by syncache_add().
1020 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1025 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1026 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1027 * the inpcb, and unlocks pcbinfo.
1029 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1030 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1034 if (ti_locked == TI_RLOCKED)
1035 INP_INFO_RUNLOCK(&V_tcbinfo);
1036 else if (ti_locked == TI_WLOCKED)
1037 INP_INFO_WUNLOCK(&V_tcbinfo);
1039 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
1040 ti_locked = TI_UNLOCKED;
1043 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1046 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1047 m = NULL; /* mbuf chain got consumed. */
1051 if (ti_locked == TI_RLOCKED)
1052 INP_INFO_RUNLOCK(&V_tcbinfo);
1053 else if (ti_locked == TI_WLOCKED)
1054 INP_INFO_WUNLOCK(&V_tcbinfo);
1056 panic("%s: dropunlock ti_locked %d", __func__, ti_locked);
1057 ti_locked = TI_UNLOCKED;
1063 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1071 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1072 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1075 int thflags, acked, ourfinisacked, needoutput = 0;
1076 int rstreason, todrop, win;
1082 * The size of tcp_saveipgen must be the size of the max ip header,
1085 u_char tcp_saveipgen[IP6_HDR_LEN];
1086 struct tcphdr tcp_savetcp;
1089 thflags = th->th_flags;
1092 * If this is either a state-changing packet or current state isn't
1093 * established, we require a write lock on tcbinfo. Otherwise, we
1094 * allow either a read lock or a write lock, as we may have acquired
1095 * a write lock due to a race.
1097 * Require a global write lock for SYN/FIN/RST segments or
1098 * non-established connections; otherwise accept either a read or
1099 * write lock, as we may have conservatively acquired a write lock in
1100 * certain cases in tcp_input() (is this still true?). Currently we
1101 * will never enter with no lock, so we try to drop it quickly in the
1102 * common pure ack/pure data cases.
1104 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1105 tp->t_state != TCPS_ESTABLISHED) {
1106 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1107 "SYN/FIN/RST/!EST", __func__, ti_locked));
1108 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1111 if (ti_locked == TI_RLOCKED)
1112 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1113 else if (ti_locked == TI_WLOCKED)
1114 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1116 panic("%s: ti_locked %d for EST", __func__,
1120 INP_WLOCK_ASSERT(tp->t_inpcb);
1121 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1123 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1127 * Segment received on connection.
1128 * Reset idle time and keep-alive timer.
1129 * XXX: This should be done after segment
1130 * validation to ignore broken/spoofed segs.
1132 tp->t_rcvtime = ticks;
1133 if (TCPS_HAVEESTABLISHED(tp->t_state))
1134 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1137 * Unscale the window into a 32-bit value.
1138 * For the SYN_SENT state the scale is zero.
1140 tiwin = th->th_win << tp->snd_scale;
1143 * TCP ECN processing.
1145 if (tp->t_flags & TF_ECN_PERMIT) {
1146 if (thflags & TH_CWR)
1147 tp->t_flags &= ~TF_ECN_SND_ECE;
1148 switch (iptos & IPTOS_ECN_MASK) {
1150 tp->t_flags |= TF_ECN_SND_ECE;
1151 TCPSTAT_INC(tcps_ecn_ce);
1153 case IPTOS_ECN_ECT0:
1154 TCPSTAT_INC(tcps_ecn_ect0);
1156 case IPTOS_ECN_ECT1:
1157 TCPSTAT_INC(tcps_ecn_ect1);
1161 * Congestion experienced.
1162 * Ignore if we are already trying to recover.
1164 if ((thflags & TH_ECE) &&
1165 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
1166 TCPSTAT_INC(tcps_ecn_rcwnd);
1167 tcp_congestion_exp(tp);
1172 * Parse options on any incoming segment.
1174 tcp_dooptions(&to, (u_char *)(th + 1),
1175 (th->th_off << 2) - sizeof(struct tcphdr),
1176 (thflags & TH_SYN) ? TO_SYN : 0);
1179 * If echoed timestamp is later than the current time,
1180 * fall back to non RFC1323 RTT calculation. Normalize
1181 * timestamp if syncookies were used when this connection
1184 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1185 to.to_tsecr -= tp->ts_offset;
1186 if (TSTMP_GT(to.to_tsecr, ticks))
1191 * Process options only when we get SYN/ACK back. The SYN case
1192 * for incoming connections is handled in tcp_syncache.
1193 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1194 * or <SYN,ACK>) segment itself is never scaled.
1195 * XXX this is traditional behavior, may need to be cleaned up.
1197 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1198 if ((to.to_flags & TOF_SCALE) &&
1199 (tp->t_flags & TF_REQ_SCALE)) {
1200 tp->t_flags |= TF_RCVD_SCALE;
1201 tp->snd_scale = to.to_wscale;
1204 * Initial send window. It will be updated with
1205 * the next incoming segment to the scaled value.
1207 tp->snd_wnd = th->th_win;
1208 if (to.to_flags & TOF_TS) {
1209 tp->t_flags |= TF_RCVD_TSTMP;
1210 tp->ts_recent = to.to_tsval;
1211 tp->ts_recent_age = ticks;
1213 if (to.to_flags & TOF_MSS)
1214 tcp_mss(tp, to.to_mss);
1215 if ((tp->t_flags & TF_SACK_PERMIT) &&
1216 (to.to_flags & TOF_SACKPERM) == 0)
1217 tp->t_flags &= ~TF_SACK_PERMIT;
1221 * Header prediction: check for the two common cases
1222 * of a uni-directional data xfer. If the packet has
1223 * no control flags, is in-sequence, the window didn't
1224 * change and we're not retransmitting, it's a
1225 * candidate. If the length is zero and the ack moved
1226 * forward, we're the sender side of the xfer. Just
1227 * free the data acked & wake any higher level process
1228 * that was blocked waiting for space. If the length
1229 * is non-zero and the ack didn't move, we're the
1230 * receiver side. If we're getting packets in-order
1231 * (the reassembly queue is empty), add the data to
1232 * the socket buffer and note that we need a delayed ack.
1233 * Make sure that the hidden state-flags are also off.
1234 * Since we check for TCPS_ESTABLISHED first, it can only
1237 if (tp->t_state == TCPS_ESTABLISHED &&
1238 th->th_seq == tp->rcv_nxt &&
1239 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1240 tp->snd_nxt == tp->snd_max &&
1241 tiwin && tiwin == tp->snd_wnd &&
1242 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1243 LIST_EMPTY(&tp->t_segq) &&
1244 ((to.to_flags & TOF_TS) == 0 ||
1245 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1248 * If last ACK falls within this segment's sequence numbers,
1249 * record the timestamp.
1250 * NOTE that the test is modified according to the latest
1251 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1253 if ((to.to_flags & TOF_TS) != 0 &&
1254 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1255 tp->ts_recent_age = ticks;
1256 tp->ts_recent = to.to_tsval;
1260 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1261 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1262 tp->snd_cwnd >= tp->snd_wnd &&
1263 ((!V_tcp_do_newreno &&
1264 !(tp->t_flags & TF_SACK_PERMIT) &&
1265 tp->t_dupacks < tcprexmtthresh) ||
1266 ((V_tcp_do_newreno ||
1267 (tp->t_flags & TF_SACK_PERMIT)) &&
1268 !IN_FASTRECOVERY(tp) &&
1269 (to.to_flags & TOF_SACK) == 0 &&
1270 TAILQ_EMPTY(&tp->snd_holes)))) {
1272 * This is a pure ack for outstanding data.
1274 if (ti_locked == TI_RLOCKED)
1275 INP_INFO_RUNLOCK(&V_tcbinfo);
1276 else if (ti_locked == TI_WLOCKED)
1277 INP_INFO_WUNLOCK(&V_tcbinfo);
1279 panic("%s: ti_locked %d on pure ACK",
1280 __func__, ti_locked);
1281 ti_locked = TI_UNLOCKED;
1283 TCPSTAT_INC(tcps_predack);
1286 * "bad retransmit" recovery.
1288 if (tp->t_rxtshift == 1 &&
1289 (int)(ticks - tp->t_badrxtwin) < 0) {
1290 TCPSTAT_INC(tcps_sndrexmitbad);
1291 tp->snd_cwnd = tp->snd_cwnd_prev;
1293 tp->snd_ssthresh_prev;
1294 tp->snd_recover = tp->snd_recover_prev;
1295 if (tp->t_flags & TF_WASFRECOVERY)
1296 ENTER_FASTRECOVERY(tp);
1297 tp->snd_nxt = tp->snd_max;
1298 tp->t_badrxtwin = 0;
1302 * Recalculate the transmit timer / rtt.
1304 * Some boxes send broken timestamp replies
1305 * during the SYN+ACK phase, ignore
1306 * timestamps of 0 or we could calculate a
1307 * huge RTT and blow up the retransmit timer.
1309 if ((to.to_flags & TOF_TS) != 0 &&
1311 if (!tp->t_rttlow ||
1312 tp->t_rttlow > ticks - to.to_tsecr)
1313 tp->t_rttlow = ticks - to.to_tsecr;
1315 ticks - to.to_tsecr + 1);
1316 } else if (tp->t_rtttime &&
1317 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1318 if (!tp->t_rttlow ||
1319 tp->t_rttlow > ticks - tp->t_rtttime)
1320 tp->t_rttlow = ticks - tp->t_rtttime;
1322 ticks - tp->t_rtttime);
1324 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1325 acked = th->th_ack - tp->snd_una;
1326 TCPSTAT_INC(tcps_rcvackpack);
1327 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1328 sbdrop(&so->so_snd, acked);
1329 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1330 SEQ_LEQ(th->th_ack, tp->snd_recover))
1331 tp->snd_recover = th->th_ack - 1;
1332 tp->snd_una = th->th_ack;
1334 * Pull snd_wl2 up to prevent seq wrap relative
1337 tp->snd_wl2 = th->th_ack;
1340 ND6_HINT(tp); /* Some progress has been made. */
1343 * If all outstanding data are acked, stop
1344 * retransmit timer, otherwise restart timer
1345 * using current (possibly backed-off) value.
1346 * If process is waiting for space,
1347 * wakeup/selwakeup/signal. If data
1348 * are ready to send, let tcp_output
1349 * decide between more output or persist.
1352 if (so->so_options & SO_DEBUG)
1353 tcp_trace(TA_INPUT, ostate, tp,
1354 (void *)tcp_saveipgen,
1357 if (tp->snd_una == tp->snd_max)
1358 tcp_timer_activate(tp, TT_REXMT, 0);
1359 else if (!tcp_timer_active(tp, TT_PERSIST))
1360 tcp_timer_activate(tp, TT_REXMT,
1363 if (so->so_snd.sb_cc)
1364 (void) tcp_output(tp);
1367 } else if (th->th_ack == tp->snd_una &&
1368 tlen <= sbspace(&so->so_rcv)) {
1369 int newsize = 0; /* automatic sockbuf scaling */
1372 * This is a pure, in-sequence data packet with
1373 * nothing on the reassembly queue and we have enough
1374 * buffer space to take it.
1376 if (ti_locked == TI_RLOCKED)
1377 INP_INFO_RUNLOCK(&V_tcbinfo);
1378 else if (ti_locked == TI_WLOCKED)
1379 INP_INFO_WUNLOCK(&V_tcbinfo);
1381 panic("%s: ti_locked %d on pure data "
1382 "segment", __func__, ti_locked);
1383 ti_locked = TI_UNLOCKED;
1385 /* Clean receiver SACK report if present */
1386 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1387 tcp_clean_sackreport(tp);
1388 TCPSTAT_INC(tcps_preddat);
1389 tp->rcv_nxt += tlen;
1391 * Pull snd_wl1 up to prevent seq wrap relative to
1394 tp->snd_wl1 = th->th_seq;
1396 * Pull rcv_up up to prevent seq wrap relative to
1399 tp->rcv_up = tp->rcv_nxt;
1400 TCPSTAT_INC(tcps_rcvpack);
1401 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1402 ND6_HINT(tp); /* Some progress has been made */
1404 if (so->so_options & SO_DEBUG)
1405 tcp_trace(TA_INPUT, ostate, tp,
1406 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1409 * Automatic sizing of receive socket buffer. Often the send
1410 * buffer size is not optimally adjusted to the actual network
1411 * conditions at hand (delay bandwidth product). Setting the
1412 * buffer size too small limits throughput on links with high
1413 * bandwidth and high delay (eg. trans-continental/oceanic links).
1415 * On the receive side the socket buffer memory is only rarely
1416 * used to any significant extent. This allows us to be much
1417 * more aggressive in scaling the receive socket buffer. For
1418 * the case that the buffer space is actually used to a large
1419 * extent and we run out of kernel memory we can simply drop
1420 * the new segments; TCP on the sender will just retransmit it
1421 * later. Setting the buffer size too big may only consume too
1422 * much kernel memory if the application doesn't read() from
1423 * the socket or packet loss or reordering makes use of the
1426 * The criteria to step up the receive buffer one notch are:
1427 * 1. the number of bytes received during the time it takes
1428 * one timestamp to be reflected back to us (the RTT);
1429 * 2. received bytes per RTT is within seven eighth of the
1430 * current socket buffer size;
1431 * 3. receive buffer size has not hit maximal automatic size;
1433 * This algorithm does one step per RTT at most and only if
1434 * we receive a bulk stream w/o packet losses or reorderings.
1435 * Shrinking the buffer during idle times is not necessary as
1436 * it doesn't consume any memory when idle.
1438 * TODO: Only step up if the application is actually serving
1439 * the buffer to better manage the socket buffer resources.
1441 if (V_tcp_do_autorcvbuf &&
1443 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1444 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1445 to.to_tsecr - tp->rfbuf_ts < hz) {
1447 (so->so_rcv.sb_hiwat / 8 * 7) &&
1448 so->so_rcv.sb_hiwat <
1449 V_tcp_autorcvbuf_max) {
1451 min(so->so_rcv.sb_hiwat +
1452 V_tcp_autorcvbuf_inc,
1453 V_tcp_autorcvbuf_max);
1455 /* Start over with next RTT. */
1459 tp->rfbuf_cnt += tlen; /* add up */
1462 /* Add data to socket buffer. */
1463 SOCKBUF_LOCK(&so->so_rcv);
1464 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1468 * Set new socket buffer size.
1469 * Give up when limit is reached.
1472 if (!sbreserve_locked(&so->so_rcv,
1474 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1475 m_adj(m, drop_hdrlen); /* delayed header drop */
1476 sbappendstream_locked(&so->so_rcv, m);
1478 /* NB: sorwakeup_locked() does an implicit unlock. */
1479 sorwakeup_locked(so);
1480 if (DELAY_ACK(tp)) {
1481 tp->t_flags |= TF_DELACK;
1483 tp->t_flags |= TF_ACKNOW;
1491 * Calculate amount of space in receive window,
1492 * and then do TCP input processing.
1493 * Receive window is amount of space in rcv queue,
1494 * but not less than advertised window.
1496 win = sbspace(&so->so_rcv);
1499 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1501 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1505 switch (tp->t_state) {
1508 * If the state is SYN_RECEIVED:
1509 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1511 case TCPS_SYN_RECEIVED:
1512 if ((thflags & TH_ACK) &&
1513 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1514 SEQ_GT(th->th_ack, tp->snd_max))) {
1515 rstreason = BANDLIM_RST_OPENPORT;
1521 * If the state is SYN_SENT:
1522 * if seg contains an ACK, but not for our SYN, drop the input.
1523 * if seg contains a RST, then drop the connection.
1524 * if seg does not contain SYN, then drop it.
1525 * Otherwise this is an acceptable SYN segment
1526 * initialize tp->rcv_nxt and tp->irs
1527 * if seg contains ack then advance tp->snd_una
1528 * if seg contains an ECE and ECN support is enabled, the stream
1530 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1531 * arrange for segment to be acked (eventually)
1532 * continue processing rest of data/controls, beginning with URG
1535 if ((thflags & TH_ACK) &&
1536 (SEQ_LEQ(th->th_ack, tp->iss) ||
1537 SEQ_GT(th->th_ack, tp->snd_max))) {
1538 rstreason = BANDLIM_UNLIMITED;
1541 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1542 tp = tcp_drop(tp, ECONNREFUSED);
1543 if (thflags & TH_RST)
1545 if (!(thflags & TH_SYN))
1548 tp->irs = th->th_seq;
1550 if (thflags & TH_ACK) {
1551 TCPSTAT_INC(tcps_connects);
1554 mac_socketpeer_set_from_mbuf(m, so);
1556 /* Do window scaling on this connection? */
1557 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1558 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1559 tp->rcv_scale = tp->request_r_scale;
1561 tp->rcv_adv += tp->rcv_wnd;
1562 tp->snd_una++; /* SYN is acked */
1564 * If there's data, delay ACK; if there's also a FIN
1565 * ACKNOW will be turned on later.
1567 if (DELAY_ACK(tp) && tlen != 0)
1568 tcp_timer_activate(tp, TT_DELACK,
1571 tp->t_flags |= TF_ACKNOW;
1573 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1574 tp->t_flags |= TF_ECN_PERMIT;
1575 TCPSTAT_INC(tcps_ecn_shs);
1579 * Received <SYN,ACK> in SYN_SENT[*] state.
1581 * SYN_SENT --> ESTABLISHED
1582 * SYN_SENT* --> FIN_WAIT_1
1584 tp->t_starttime = ticks;
1585 if (tp->t_flags & TF_NEEDFIN) {
1586 tp->t_state = TCPS_FIN_WAIT_1;
1587 tp->t_flags &= ~TF_NEEDFIN;
1590 tp->t_state = TCPS_ESTABLISHED;
1591 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1595 * Received initial SYN in SYN-SENT[*] state =>
1596 * simultaneous open. If segment contains CC option
1597 * and there is a cached CC, apply TAO test.
1598 * If it succeeds, connection is * half-synchronized.
1599 * Otherwise, do 3-way handshake:
1600 * SYN-SENT -> SYN-RECEIVED
1601 * SYN-SENT* -> SYN-RECEIVED*
1602 * If there was no CC option, clear cached CC value.
1604 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1605 tcp_timer_activate(tp, TT_REXMT, 0);
1606 tp->t_state = TCPS_SYN_RECEIVED;
1609 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1610 "ti_locked %d", __func__, ti_locked));
1611 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1612 INP_WLOCK_ASSERT(tp->t_inpcb);
1615 * Advance th->th_seq to correspond to first data byte.
1616 * If data, trim to stay within window,
1617 * dropping FIN if necessary.
1620 if (tlen > tp->rcv_wnd) {
1621 todrop = tlen - tp->rcv_wnd;
1625 TCPSTAT_INC(tcps_rcvpackafterwin);
1626 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1628 tp->snd_wl1 = th->th_seq - 1;
1629 tp->rcv_up = th->th_seq;
1631 * Client side of transaction: already sent SYN and data.
1632 * If the remote host used T/TCP to validate the SYN,
1633 * our data will be ACK'd; if so, enter normal data segment
1634 * processing in the middle of step 5, ack processing.
1635 * Otherwise, goto step 6.
1637 if (thflags & TH_ACK)
1643 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1644 * do normal processing.
1646 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1650 break; /* continue normal processing */
1654 * States other than LISTEN or SYN_SENT.
1655 * First check the RST flag and sequence number since reset segments
1656 * are exempt from the timestamp and connection count tests. This
1657 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1658 * below which allowed reset segments in half the sequence space
1659 * to fall though and be processed (which gives forged reset
1660 * segments with a random sequence number a 50 percent chance of
1661 * killing a connection).
1662 * Then check timestamp, if present.
1663 * Then check the connection count, if present.
1664 * Then check that at least some bytes of segment are within
1665 * receive window. If segment begins before rcv_nxt,
1666 * drop leading data (and SYN); if nothing left, just ack.
1669 * If the RST bit is set, check the sequence number to see
1670 * if this is a valid reset segment.
1672 * In all states except SYN-SENT, all reset (RST) segments
1673 * are validated by checking their SEQ-fields. A reset is
1674 * valid if its sequence number is in the window.
1675 * Note: this does not take into account delayed ACKs, so
1676 * we should test against last_ack_sent instead of rcv_nxt.
1677 * The sequence number in the reset segment is normally an
1678 * echo of our outgoing acknowlegement numbers, but some hosts
1679 * send a reset with the sequence number at the rightmost edge
1680 * of our receive window, and we have to handle this case.
1681 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1682 * that brute force RST attacks are possible. To combat this,
1683 * we use a much stricter check while in the ESTABLISHED state,
1684 * only accepting RSTs where the sequence number is equal to
1685 * last_ack_sent. In all other states (the states in which a
1686 * RST is more likely), the more permissive check is used.
1687 * If we have multiple segments in flight, the initial reset
1688 * segment sequence numbers will be to the left of last_ack_sent,
1689 * but they will eventually catch up.
1690 * In any case, it never made sense to trim reset segments to
1691 * fit the receive window since RFC 1122 says:
1692 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1694 * A TCP SHOULD allow a received RST segment to include data.
1697 * It has been suggested that a RST segment could contain
1698 * ASCII text that encoded and explained the cause of the
1699 * RST. No standard has yet been established for such
1702 * If the reset segment passes the sequence number test examine
1704 * SYN_RECEIVED STATE:
1705 * If passive open, return to LISTEN state.
1706 * If active open, inform user that connection was refused.
1707 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1708 * Inform user that connection was reset, and close tcb.
1709 * CLOSING, LAST_ACK STATES:
1712 * Drop the segment - see Stevens, vol. 2, p. 964 and
1715 if (thflags & TH_RST) {
1716 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1717 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1718 switch (tp->t_state) {
1720 case TCPS_SYN_RECEIVED:
1721 so->so_error = ECONNREFUSED;
1724 case TCPS_ESTABLISHED:
1725 if (V_tcp_insecure_rst == 0 &&
1726 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1727 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1728 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1729 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1730 TCPSTAT_INC(tcps_badrst);
1734 case TCPS_FIN_WAIT_1:
1735 case TCPS_FIN_WAIT_2:
1736 case TCPS_CLOSE_WAIT:
1737 so->so_error = ECONNRESET;
1739 KASSERT(ti_locked == TI_WLOCKED,
1740 ("tcp_do_segment: TH_RST 1 ti_locked %d",
1742 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1744 tp->t_state = TCPS_CLOSED;
1745 TCPSTAT_INC(tcps_drops);
1751 KASSERT(ti_locked == TI_WLOCKED,
1752 ("tcp_do_segment: TH_RST 2 ti_locked %d",
1754 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1764 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1765 * and it's less than ts_recent, drop it.
1767 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1768 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1770 /* Check to see if ts_recent is over 24 days old. */
1771 if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
1773 * Invalidate ts_recent. If this segment updates
1774 * ts_recent, the age will be reset later and ts_recent
1775 * will get a valid value. If it does not, setting
1776 * ts_recent to zero will at least satisfy the
1777 * requirement that zero be placed in the timestamp
1778 * echo reply when ts_recent isn't valid. The
1779 * age isn't reset until we get a valid ts_recent
1780 * because we don't want out-of-order segments to be
1781 * dropped when ts_recent is old.
1785 TCPSTAT_INC(tcps_rcvduppack);
1786 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1787 TCPSTAT_INC(tcps_pawsdrop);
1795 * In the SYN-RECEIVED state, validate that the packet belongs to
1796 * this connection before trimming the data to fit the receive
1797 * window. Check the sequence number versus IRS since we know
1798 * the sequence numbers haven't wrapped. This is a partial fix
1799 * for the "LAND" DoS attack.
1801 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1802 rstreason = BANDLIM_RST_OPENPORT;
1806 todrop = tp->rcv_nxt - th->th_seq;
1809 * If this is a duplicate SYN for our current connection,
1810 * advance over it and pretend and it's not a SYN.
1812 if (thflags & TH_SYN && th->th_seq == tp->irs) {
1822 * Following if statement from Stevens, vol. 2, p. 960.
1825 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1827 * Any valid FIN must be to the left of the window.
1828 * At this point the FIN must be a duplicate or out
1829 * of sequence; drop it.
1834 * Send an ACK to resynchronize and drop any data.
1835 * But keep on processing for RST or ACK.
1837 tp->t_flags |= TF_ACKNOW;
1839 TCPSTAT_INC(tcps_rcvduppack);
1840 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1842 TCPSTAT_INC(tcps_rcvpartduppack);
1843 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1845 drop_hdrlen += todrop; /* drop from the top afterwards */
1846 th->th_seq += todrop;
1848 if (th->th_urp > todrop)
1849 th->th_urp -= todrop;
1857 * If new data are received on a connection after the
1858 * user processes are gone, then RST the other end.
1860 if ((so->so_state & SS_NOFDREF) &&
1861 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1864 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
1865 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
1866 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1868 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1869 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
1870 "was closed, sending RST and removing tcpcb\n",
1871 s, __func__, tcpstates[tp->t_state], tlen);
1875 TCPSTAT_INC(tcps_rcvafterclose);
1876 rstreason = BANDLIM_UNLIMITED;
1881 * If segment ends after window, drop trailing data
1882 * (and PUSH and FIN); if nothing left, just ACK.
1884 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1886 TCPSTAT_INC(tcps_rcvpackafterwin);
1887 if (todrop >= tlen) {
1888 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1890 * If window is closed can only take segments at
1891 * window edge, and have to drop data and PUSH from
1892 * incoming segments. Continue processing, but
1893 * remember to ack. Otherwise, drop segment
1896 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1897 tp->t_flags |= TF_ACKNOW;
1898 TCPSTAT_INC(tcps_rcvwinprobe);
1902 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1905 thflags &= ~(TH_PUSH|TH_FIN);
1909 * If last ACK falls within this segment's sequence numbers,
1910 * record its timestamp.
1912 * 1) That the test incorporates suggestions from the latest
1913 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1914 * 2) That updating only on newer timestamps interferes with
1915 * our earlier PAWS tests, so this check should be solely
1916 * predicated on the sequence space of this segment.
1917 * 3) That we modify the segment boundary check to be
1918 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1919 * instead of RFC1323's
1920 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1921 * This modified check allows us to overcome RFC1323's
1922 * limitations as described in Stevens TCP/IP Illustrated
1923 * Vol. 2 p.869. In such cases, we can still calculate the
1924 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1926 if ((to.to_flags & TOF_TS) != 0 &&
1927 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1928 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1929 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1930 tp->ts_recent_age = ticks;
1931 tp->ts_recent = to.to_tsval;
1935 * If a SYN is in the window, then this is an
1936 * error and we send an RST and drop the connection.
1938 if (thflags & TH_SYN) {
1939 KASSERT(ti_locked == TI_WLOCKED,
1940 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
1941 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1943 tp = tcp_drop(tp, ECONNRESET);
1944 rstreason = BANDLIM_UNLIMITED;
1949 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1950 * flag is on (half-synchronized state), then queue data for
1951 * later processing; else drop segment and return.
1953 if ((thflags & TH_ACK) == 0) {
1954 if (tp->t_state == TCPS_SYN_RECEIVED ||
1955 (tp->t_flags & TF_NEEDSYN))
1957 else if (tp->t_flags & TF_ACKNOW)
1966 switch (tp->t_state) {
1969 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1970 * ESTABLISHED state and continue processing.
1971 * The ACK was checked above.
1973 case TCPS_SYN_RECEIVED:
1975 TCPSTAT_INC(tcps_connects);
1977 /* Do window scaling? */
1978 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1979 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1980 tp->rcv_scale = tp->request_r_scale;
1981 tp->snd_wnd = tiwin;
1985 * SYN-RECEIVED -> ESTABLISHED
1986 * SYN-RECEIVED* -> FIN-WAIT-1
1988 tp->t_starttime = ticks;
1989 if (tp->t_flags & TF_NEEDFIN) {
1990 tp->t_state = TCPS_FIN_WAIT_1;
1991 tp->t_flags &= ~TF_NEEDFIN;
1993 tp->t_state = TCPS_ESTABLISHED;
1994 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1997 * If segment contains data or ACK, will call tcp_reass()
1998 * later; if not, do so now to pass queued data to user.
2000 if (tlen == 0 && (thflags & TH_FIN) == 0)
2001 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2003 tp->snd_wl1 = th->th_seq - 1;
2007 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2008 * ACKs. If the ack is in the range
2009 * tp->snd_una < th->th_ack <= tp->snd_max
2010 * then advance tp->snd_una to th->th_ack and drop
2011 * data from the retransmission queue. If this ACK reflects
2012 * more up to date window information we update our window information.
2014 case TCPS_ESTABLISHED:
2015 case TCPS_FIN_WAIT_1:
2016 case TCPS_FIN_WAIT_2:
2017 case TCPS_CLOSE_WAIT:
2020 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2021 TCPSTAT_INC(tcps_rcvacktoomuch);
2024 if ((tp->t_flags & TF_SACK_PERMIT) &&
2025 ((to.to_flags & TOF_SACK) ||
2026 !TAILQ_EMPTY(&tp->snd_holes)))
2027 tcp_sack_doack(tp, &to, th->th_ack);
2028 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2029 if (tlen == 0 && tiwin == tp->snd_wnd) {
2030 TCPSTAT_INC(tcps_rcvdupack);
2032 * If we have outstanding data (other than
2033 * a window probe), this is a completely
2034 * duplicate ack (ie, window info didn't
2035 * change), the ack is the biggest we've
2036 * seen and we've seen exactly our rexmt
2037 * threshhold of them, assume a packet
2038 * has been dropped and retransmit it.
2039 * Kludge snd_nxt & the congestion
2040 * window so we send only this one
2043 * We know we're losing at the current
2044 * window size so do congestion avoidance
2045 * (set ssthresh to half the current window
2046 * and pull our congestion window back to
2047 * the new ssthresh).
2049 * Dup acks mean that packets have left the
2050 * network (they're now cached at the receiver)
2051 * so bump cwnd by the amount in the receiver
2052 * to keep a constant cwnd packets in the
2055 * When using TCP ECN, notify the peer that
2056 * we reduced the cwnd.
2058 if (!tcp_timer_active(tp, TT_REXMT) ||
2059 th->th_ack != tp->snd_una)
2061 else if (++tp->t_dupacks > tcprexmtthresh ||
2062 ((V_tcp_do_newreno ||
2063 (tp->t_flags & TF_SACK_PERMIT)) &&
2064 IN_FASTRECOVERY(tp))) {
2065 if ((tp->t_flags & TF_SACK_PERMIT) &&
2066 IN_FASTRECOVERY(tp)) {
2070 * Compute the amount of data in flight first.
2071 * We can inject new data into the pipe iff
2072 * we have less than 1/2 the original window's
2073 * worth of data in flight.
2075 awnd = (tp->snd_nxt - tp->snd_fack) +
2076 tp->sackhint.sack_bytes_rexmit;
2077 if (awnd < tp->snd_ssthresh) {
2078 tp->snd_cwnd += tp->t_maxseg;
2079 if (tp->snd_cwnd > tp->snd_ssthresh)
2080 tp->snd_cwnd = tp->snd_ssthresh;
2083 tp->snd_cwnd += tp->t_maxseg;
2084 (void) tcp_output(tp);
2086 } else if (tp->t_dupacks == tcprexmtthresh) {
2087 tcp_seq onxt = tp->snd_nxt;
2090 * If we're doing sack, check to
2091 * see if we're already in sack
2092 * recovery. If we're not doing sack,
2093 * check to see if we're in newreno
2096 if (tp->t_flags & TF_SACK_PERMIT) {
2097 if (IN_FASTRECOVERY(tp)) {
2101 } else if (V_tcp_do_newreno ||
2103 if (SEQ_LEQ(th->th_ack,
2109 tcp_congestion_exp(tp);
2110 tcp_timer_activate(tp, TT_REXMT, 0);
2112 if (tp->t_flags & TF_SACK_PERMIT) {
2114 tcps_sack_recovery_episode);
2115 tp->sack_newdata = tp->snd_nxt;
2116 tp->snd_cwnd = tp->t_maxseg;
2117 (void) tcp_output(tp);
2120 tp->snd_nxt = th->th_ack;
2121 tp->snd_cwnd = tp->t_maxseg;
2122 (void) tcp_output(tp);
2123 KASSERT(tp->snd_limited <= 2,
2124 ("%s: tp->snd_limited too big",
2126 tp->snd_cwnd = tp->snd_ssthresh +
2128 (tp->t_dupacks - tp->snd_limited);
2129 if (SEQ_GT(onxt, tp->snd_nxt))
2132 } else if (V_tcp_do_rfc3042) {
2133 u_long oldcwnd = tp->snd_cwnd;
2134 tcp_seq oldsndmax = tp->snd_max;
2137 KASSERT(tp->t_dupacks == 1 ||
2139 ("%s: dupacks not 1 or 2",
2141 if (tp->t_dupacks == 1)
2142 tp->snd_limited = 0;
2144 (tp->snd_nxt - tp->snd_una) +
2145 (tp->t_dupacks - tp->snd_limited) *
2147 (void) tcp_output(tp);
2148 sent = tp->snd_max - oldsndmax;
2149 if (sent > tp->t_maxseg) {
2150 KASSERT((tp->t_dupacks == 2 &&
2151 tp->snd_limited == 0) ||
2152 (sent == tp->t_maxseg + 1 &&
2153 tp->t_flags & TF_SENTFIN),
2154 ("%s: sent too much",
2156 tp->snd_limited = 2;
2157 } else if (sent > 0)
2159 tp->snd_cwnd = oldcwnd;
2167 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2168 ("%s: th_ack <= snd_una", __func__));
2171 * If the congestion window was inflated to account
2172 * for the other side's cached packets, retract it.
2174 if (V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
2175 if (IN_FASTRECOVERY(tp)) {
2176 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2177 if (tp->t_flags & TF_SACK_PERMIT)
2178 tcp_sack_partialack(tp, th);
2180 tcp_newreno_partial_ack(tp, th);
2183 * Out of fast recovery.
2184 * Window inflation should have left us
2185 * with approximately snd_ssthresh
2187 * But in case we would be inclined to
2188 * send a burst, better to do it via
2189 * the slow start mechanism.
2191 if (SEQ_GT(th->th_ack +
2194 tp->snd_cwnd = tp->snd_max -
2198 tp->snd_cwnd = tp->snd_ssthresh;
2202 if (tp->t_dupacks >= tcprexmtthresh &&
2203 tp->snd_cwnd > tp->snd_ssthresh)
2204 tp->snd_cwnd = tp->snd_ssthresh;
2208 * If we reach this point, ACK is not a duplicate,
2209 * i.e., it ACKs something we sent.
2211 if (tp->t_flags & TF_NEEDSYN) {
2213 * T/TCP: Connection was half-synchronized, and our
2214 * SYN has been ACK'd (so connection is now fully
2215 * synchronized). Go to non-starred state,
2216 * increment snd_una for ACK of SYN, and check if
2217 * we can do window scaling.
2219 tp->t_flags &= ~TF_NEEDSYN;
2221 /* Do window scaling? */
2222 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2223 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2224 tp->rcv_scale = tp->request_r_scale;
2225 /* Send window already scaled. */
2230 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2231 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2232 ("tcp_input: process_ACK ti_locked %d", ti_locked));
2233 INP_WLOCK_ASSERT(tp->t_inpcb);
2235 acked = th->th_ack - tp->snd_una;
2236 TCPSTAT_INC(tcps_rcvackpack);
2237 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2240 * If we just performed our first retransmit, and the ACK
2241 * arrives within our recovery window, then it was a mistake
2242 * to do the retransmit in the first place. Recover our
2243 * original cwnd and ssthresh, and proceed to transmit where
2246 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0) {
2247 TCPSTAT_INC(tcps_sndrexmitbad);
2248 tp->snd_cwnd = tp->snd_cwnd_prev;
2249 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2250 tp->snd_recover = tp->snd_recover_prev;
2251 if (tp->t_flags & TF_WASFRECOVERY)
2252 ENTER_FASTRECOVERY(tp);
2253 tp->snd_nxt = tp->snd_max;
2254 tp->t_badrxtwin = 0; /* XXX probably not required */
2258 * If we have a timestamp reply, update smoothed
2259 * round trip time. If no timestamp is present but
2260 * transmit timer is running and timed sequence
2261 * number was acked, update smoothed round trip time.
2262 * Since we now have an rtt measurement, cancel the
2263 * timer backoff (cf., Phil Karn's retransmit alg.).
2264 * Recompute the initial retransmit timer.
2266 * Some boxes send broken timestamp replies
2267 * during the SYN+ACK phase, ignore
2268 * timestamps of 0 or we could calculate a
2269 * huge RTT and blow up the retransmit timer.
2271 if ((to.to_flags & TOF_TS) != 0 &&
2273 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2274 tp->t_rttlow = ticks - to.to_tsecr;
2275 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2276 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2277 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2278 tp->t_rttlow = ticks - tp->t_rtttime;
2279 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2281 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2284 * If all outstanding data is acked, stop retransmit
2285 * timer and remember to restart (more output or persist).
2286 * If there is more data to be acked, restart retransmit
2287 * timer, using current (possibly backed-off) value.
2289 if (th->th_ack == tp->snd_max) {
2290 tcp_timer_activate(tp, TT_REXMT, 0);
2292 } else if (!tcp_timer_active(tp, TT_PERSIST))
2293 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2296 * If no data (only SYN) was ACK'd,
2297 * skip rest of ACK processing.
2303 * When new data is acked, open the congestion window.
2304 * Method depends on which congestion control state we're
2305 * in (slow start or cong avoid) and if ABC (RFC 3465) is
2308 * slow start: cwnd <= ssthresh
2309 * cong avoid: cwnd > ssthresh
2311 * slow start and ABC (RFC 3465):
2312 * Grow cwnd exponentially by the amount of data
2313 * ACKed capping the max increment per ACK to
2314 * (abc_l_var * maxseg) bytes.
2316 * slow start without ABC (RFC 2581):
2317 * Grow cwnd exponentially by maxseg per ACK.
2319 * cong avoid and ABC (RFC 3465):
2320 * Grow cwnd linearly by maxseg per RTT for each
2321 * cwnd worth of ACKed data.
2323 * cong avoid without ABC (RFC 2581):
2324 * Grow cwnd linearly by approximately maxseg per RTT using
2325 * maxseg^2 / cwnd per ACK as the increment.
2326 * If cwnd > maxseg^2, fix the cwnd increment at 1 byte to
2327 * avoid capping cwnd.
2329 if ((!V_tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2330 !IN_FASTRECOVERY(tp)) {
2331 u_int cw = tp->snd_cwnd;
2332 u_int incr = tp->t_maxseg;
2333 /* In congestion avoidance? */
2334 if (cw > tp->snd_ssthresh) {
2335 if (V_tcp_do_rfc3465) {
2336 tp->t_bytes_acked += acked;
2337 if (tp->t_bytes_acked >= tp->snd_cwnd)
2338 tp->t_bytes_acked -= cw;
2343 incr = max((incr * incr / cw), 1);
2345 * In slow-start with ABC enabled and no RTO in sight?
2346 * (Must not use abc_l_var > 1 if slow starting after an
2347 * RTO. On RTO, snd_nxt = snd_una, so the snd_nxt ==
2348 * snd_max check is sufficient to handle this).
2350 } else if (V_tcp_do_rfc3465 &&
2351 tp->snd_nxt == tp->snd_max)
2353 V_tcp_abc_l_var * tp->t_maxseg);
2354 /* ABC is on by default, so (incr == 0) frequently. */
2356 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2358 SOCKBUF_LOCK(&so->so_snd);
2359 if (acked > so->so_snd.sb_cc) {
2360 tp->snd_wnd -= so->so_snd.sb_cc;
2361 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2364 sbdrop_locked(&so->so_snd, acked);
2365 tp->snd_wnd -= acked;
2368 /* NB: sowwakeup_locked() does an implicit unlock. */
2369 sowwakeup_locked(so);
2370 /* Detect una wraparound. */
2371 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2372 !IN_FASTRECOVERY(tp) &&
2373 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2374 SEQ_LEQ(th->th_ack, tp->snd_recover))
2375 tp->snd_recover = th->th_ack - 1;
2376 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2377 IN_FASTRECOVERY(tp) &&
2378 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2379 EXIT_FASTRECOVERY(tp);
2380 tp->t_bytes_acked = 0;
2382 tp->snd_una = th->th_ack;
2383 if (tp->t_flags & TF_SACK_PERMIT) {
2384 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2385 tp->snd_recover = tp->snd_una;
2387 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2388 tp->snd_nxt = tp->snd_una;
2390 switch (tp->t_state) {
2393 * In FIN_WAIT_1 STATE in addition to the processing
2394 * for the ESTABLISHED state if our FIN is now acknowledged
2395 * then enter FIN_WAIT_2.
2397 case TCPS_FIN_WAIT_1:
2398 if (ourfinisacked) {
2400 * If we can't receive any more
2401 * data, then closing user can proceed.
2402 * Starting the timer is contrary to the
2403 * specification, but if we don't get a FIN
2404 * we'll hang forever.
2407 * we should release the tp also, and use a
2410 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2413 soisdisconnected(so);
2414 timeout = (tcp_fast_finwait2_recycle) ?
2415 tcp_finwait2_timeout : tcp_maxidle;
2416 tcp_timer_activate(tp, TT_2MSL, timeout);
2418 tp->t_state = TCPS_FIN_WAIT_2;
2423 * In CLOSING STATE in addition to the processing for
2424 * the ESTABLISHED state if the ACK acknowledges our FIN
2425 * then enter the TIME-WAIT state, otherwise ignore
2429 if (ourfinisacked) {
2430 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2432 INP_INFO_WUNLOCK(&V_tcbinfo);
2439 * In LAST_ACK, we may still be waiting for data to drain
2440 * and/or to be acked, as well as for the ack of our FIN.
2441 * If our FIN is now acknowledged, delete the TCB,
2442 * enter the closed state and return.
2445 if (ourfinisacked) {
2446 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2455 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2456 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2457 ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2458 INP_WLOCK_ASSERT(tp->t_inpcb);
2461 * Update window information.
2462 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2464 if ((thflags & TH_ACK) &&
2465 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2466 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2467 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2468 /* keep track of pure window updates */
2470 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2471 TCPSTAT_INC(tcps_rcvwinupd);
2472 tp->snd_wnd = tiwin;
2473 tp->snd_wl1 = th->th_seq;
2474 tp->snd_wl2 = th->th_ack;
2475 if (tp->snd_wnd > tp->max_sndwnd)
2476 tp->max_sndwnd = tp->snd_wnd;
2481 * Process segments with URG.
2483 if ((thflags & TH_URG) && th->th_urp &&
2484 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2486 * This is a kludge, but if we receive and accept
2487 * random urgent pointers, we'll crash in
2488 * soreceive. It's hard to imagine someone
2489 * actually wanting to send this much urgent data.
2491 SOCKBUF_LOCK(&so->so_rcv);
2492 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2493 th->th_urp = 0; /* XXX */
2494 thflags &= ~TH_URG; /* XXX */
2495 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2496 goto dodata; /* XXX */
2499 * If this segment advances the known urgent pointer,
2500 * then mark the data stream. This should not happen
2501 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2502 * a FIN has been received from the remote side.
2503 * In these states we ignore the URG.
2505 * According to RFC961 (Assigned Protocols),
2506 * the urgent pointer points to the last octet
2507 * of urgent data. We continue, however,
2508 * to consider it to indicate the first octet
2509 * of data past the urgent section as the original
2510 * spec states (in one of two places).
2512 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2513 tp->rcv_up = th->th_seq + th->th_urp;
2514 so->so_oobmark = so->so_rcv.sb_cc +
2515 (tp->rcv_up - tp->rcv_nxt) - 1;
2516 if (so->so_oobmark == 0)
2517 so->so_rcv.sb_state |= SBS_RCVATMARK;
2519 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2521 SOCKBUF_UNLOCK(&so->so_rcv);
2523 * Remove out of band data so doesn't get presented to user.
2524 * This can happen independent of advancing the URG pointer,
2525 * but if two URG's are pending at once, some out-of-band
2526 * data may creep in... ick.
2528 if (th->th_urp <= (u_long)tlen &&
2529 !(so->so_options & SO_OOBINLINE)) {
2530 /* hdr drop is delayed */
2531 tcp_pulloutofband(so, th, m, drop_hdrlen);
2535 * If no out of band data is expected,
2536 * pull receive urgent pointer along
2537 * with the receive window.
2539 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2540 tp->rcv_up = tp->rcv_nxt;
2543 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2544 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2545 ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2546 INP_WLOCK_ASSERT(tp->t_inpcb);
2549 * Process the segment text, merging it into the TCP sequencing queue,
2550 * and arranging for acknowledgment of receipt if necessary.
2551 * This process logically involves adjusting tp->rcv_wnd as data
2552 * is presented to the user (this happens in tcp_usrreq.c,
2553 * case PRU_RCVD). If a FIN has already been received on this
2554 * connection then we just ignore the text.
2556 if ((tlen || (thflags & TH_FIN)) &&
2557 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2558 tcp_seq save_start = th->th_seq;
2559 m_adj(m, drop_hdrlen); /* delayed header drop */
2561 * Insert segment which includes th into TCP reassembly queue
2562 * with control block tp. Set thflags to whether reassembly now
2563 * includes a segment with FIN. This handles the common case
2564 * inline (segment is the next to be received on an established
2565 * connection, and the queue is empty), avoiding linkage into
2566 * and removal from the queue and repetition of various
2568 * Set DELACK for segments received in order, but ack
2569 * immediately when segments are out of order (so
2570 * fast retransmit can work).
2572 if (th->th_seq == tp->rcv_nxt &&
2573 LIST_EMPTY(&tp->t_segq) &&
2574 TCPS_HAVEESTABLISHED(tp->t_state)) {
2576 tp->t_flags |= TF_DELACK;
2578 tp->t_flags |= TF_ACKNOW;
2579 tp->rcv_nxt += tlen;
2580 thflags = th->th_flags & TH_FIN;
2581 TCPSTAT_INC(tcps_rcvpack);
2582 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2584 SOCKBUF_LOCK(&so->so_rcv);
2585 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2588 sbappendstream_locked(&so->so_rcv, m);
2589 /* NB: sorwakeup_locked() does an implicit unlock. */
2590 sorwakeup_locked(so);
2593 * XXX: Due to the header drop above "th" is
2594 * theoretically invalid by now. Fortunately
2595 * m_adj() doesn't actually frees any mbufs
2596 * when trimming from the head.
2598 thflags = tcp_reass(tp, th, &tlen, m);
2599 tp->t_flags |= TF_ACKNOW;
2601 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2602 tcp_update_sack_list(tp, save_start, save_start + tlen);
2605 * Note the amount of data that peer has sent into
2606 * our window, in order to estimate the sender's
2610 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2618 * If FIN is received ACK the FIN and let the user know
2619 * that the connection is closing.
2621 if (thflags & TH_FIN) {
2622 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2625 * If connection is half-synchronized
2626 * (ie NEEDSYN flag on) then delay ACK,
2627 * so it may be piggybacked when SYN is sent.
2628 * Otherwise, since we received a FIN then no
2629 * more input can be expected, send ACK now.
2631 if (tp->t_flags & TF_NEEDSYN)
2632 tp->t_flags |= TF_DELACK;
2634 tp->t_flags |= TF_ACKNOW;
2637 switch (tp->t_state) {
2640 * In SYN_RECEIVED and ESTABLISHED STATES
2641 * enter the CLOSE_WAIT state.
2643 case TCPS_SYN_RECEIVED:
2644 tp->t_starttime = ticks;
2646 case TCPS_ESTABLISHED:
2647 tp->t_state = TCPS_CLOSE_WAIT;
2651 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2652 * enter the CLOSING state.
2654 case TCPS_FIN_WAIT_1:
2655 tp->t_state = TCPS_CLOSING;
2659 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2660 * starting the time-wait timer, turning off the other
2663 case TCPS_FIN_WAIT_2:
2664 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2665 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2666 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2670 INP_INFO_WUNLOCK(&V_tcbinfo);
2674 if (ti_locked == TI_RLOCKED)
2675 INP_INFO_RUNLOCK(&V_tcbinfo);
2676 else if (ti_locked == TI_WLOCKED)
2677 INP_INFO_WUNLOCK(&V_tcbinfo);
2679 panic("%s: dodata epilogue ti_locked %d", __func__,
2681 ti_locked = TI_UNLOCKED;
2684 if (so->so_options & SO_DEBUG)
2685 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2690 * Return any desired output.
2692 if (needoutput || (tp->t_flags & TF_ACKNOW))
2693 (void) tcp_output(tp);
2696 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2697 __func__, ti_locked));
2698 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2699 INP_WLOCK_ASSERT(tp->t_inpcb);
2701 if (tp->t_flags & TF_DELACK) {
2702 tp->t_flags &= ~TF_DELACK;
2703 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2705 INP_WUNLOCK(tp->t_inpcb);
2709 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2710 ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2713 * Generate an ACK dropping incoming segment if it occupies
2714 * sequence space, where the ACK reflects our state.
2716 * We can now skip the test for the RST flag since all
2717 * paths to this code happen after packets containing
2718 * RST have been dropped.
2720 * In the SYN-RECEIVED state, don't send an ACK unless the
2721 * segment we received passes the SYN-RECEIVED ACK test.
2722 * If it fails send a RST. This breaks the loop in the
2723 * "LAND" DoS attack, and also prevents an ACK storm
2724 * between two listening ports that have been sent forged
2725 * SYN segments, each with the source address of the other.
2727 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2728 (SEQ_GT(tp->snd_una, th->th_ack) ||
2729 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2730 rstreason = BANDLIM_RST_OPENPORT;
2734 if (so->so_options & SO_DEBUG)
2735 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2738 if (ti_locked == TI_RLOCKED)
2739 INP_INFO_RUNLOCK(&V_tcbinfo);
2740 else if (ti_locked == TI_WLOCKED)
2741 INP_INFO_WUNLOCK(&V_tcbinfo);
2743 panic("%s: dropafterack epilogue ti_locked %d", __func__,
2745 ti_locked = TI_UNLOCKED;
2747 tp->t_flags |= TF_ACKNOW;
2748 (void) tcp_output(tp);
2749 INP_WUNLOCK(tp->t_inpcb);
2754 if (ti_locked == TI_RLOCKED)
2755 INP_INFO_RUNLOCK(&V_tcbinfo);
2756 else if (ti_locked == TI_WLOCKED)
2757 INP_INFO_WUNLOCK(&V_tcbinfo);
2759 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2760 ti_locked = TI_UNLOCKED;
2763 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2764 INP_WUNLOCK(tp->t_inpcb);
2766 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2770 if (ti_locked == TI_RLOCKED)
2771 INP_INFO_RUNLOCK(&V_tcbinfo);
2772 else if (ti_locked == TI_WLOCKED)
2773 INP_INFO_WUNLOCK(&V_tcbinfo);
2776 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2778 ti_locked = TI_UNLOCKED;
2781 * Drop space held by incoming segment and return.
2784 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2785 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2789 INP_WUNLOCK(tp->t_inpcb);
2794 * Issue RST and make ACK acceptable to originator of segment.
2795 * The mbuf must still include the original packet header.
2799 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2800 int tlen, int rstreason)
2804 struct ip6_hdr *ip6;
2808 INP_WLOCK_ASSERT(tp->t_inpcb);
2811 /* Don't bother if destination was broadcast/multicast. */
2812 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2815 if (mtod(m, struct ip *)->ip_v == 6) {
2816 ip6 = mtod(m, struct ip6_hdr *);
2817 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2818 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2820 /* IPv6 anycast check is done at tcp6_input() */
2824 ip = mtod(m, struct ip *);
2825 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2826 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2827 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2828 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2832 /* Perform bandwidth limiting. */
2833 if (badport_bandlim(rstreason) < 0)
2836 /* tcp_respond consumes the mbuf chain. */
2837 if (th->th_flags & TH_ACK) {
2838 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2839 th->th_ack, TH_RST);
2841 if (th->th_flags & TH_SYN)
2843 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2844 (tcp_seq)0, TH_RST|TH_ACK);
2852 * Parse TCP options and place in tcpopt.
2855 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2860 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2862 if (opt == TCPOPT_EOL)
2864 if (opt == TCPOPT_NOP)
2870 if (optlen < 2 || optlen > cnt)
2875 if (optlen != TCPOLEN_MAXSEG)
2877 if (!(flags & TO_SYN))
2879 to->to_flags |= TOF_MSS;
2880 bcopy((char *)cp + 2,
2881 (char *)&to->to_mss, sizeof(to->to_mss));
2882 to->to_mss = ntohs(to->to_mss);
2885 if (optlen != TCPOLEN_WINDOW)
2887 if (!(flags & TO_SYN))
2889 to->to_flags |= TOF_SCALE;
2890 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2892 case TCPOPT_TIMESTAMP:
2893 if (optlen != TCPOLEN_TIMESTAMP)
2895 to->to_flags |= TOF_TS;
2896 bcopy((char *)cp + 2,
2897 (char *)&to->to_tsval, sizeof(to->to_tsval));
2898 to->to_tsval = ntohl(to->to_tsval);
2899 bcopy((char *)cp + 6,
2900 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2901 to->to_tsecr = ntohl(to->to_tsecr);
2903 #ifdef TCP_SIGNATURE
2905 * XXX In order to reply to a host which has set the
2906 * TCP_SIGNATURE option in its initial SYN, we have to
2907 * record the fact that the option was observed here
2908 * for the syncache code to perform the correct response.
2910 case TCPOPT_SIGNATURE:
2911 if (optlen != TCPOLEN_SIGNATURE)
2913 to->to_flags |= TOF_SIGNATURE;
2914 to->to_signature = cp + 2;
2917 case TCPOPT_SACK_PERMITTED:
2918 if (optlen != TCPOLEN_SACK_PERMITTED)
2920 if (!(flags & TO_SYN))
2924 to->to_flags |= TOF_SACKPERM;
2927 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2931 to->to_flags |= TOF_SACK;
2932 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2933 to->to_sacks = cp + 2;
2934 TCPSTAT_INC(tcps_sack_rcv_blocks);
2943 * Pull out of band byte out of a segment so
2944 * it doesn't appear in the user's data queue.
2945 * It is still reflected in the segment length for
2946 * sequencing purposes.
2949 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2952 int cnt = off + th->th_urp - 1;
2955 if (m->m_len > cnt) {
2956 char *cp = mtod(m, caddr_t) + cnt;
2957 struct tcpcb *tp = sototcpcb(so);
2959 INP_WLOCK_ASSERT(tp->t_inpcb);
2962 tp->t_oobflags |= TCPOOB_HAVEDATA;
2963 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2965 if (m->m_flags & M_PKTHDR)
2974 panic("tcp_pulloutofband");
2978 * Collect new round-trip time estimate
2979 * and update averages and current timeout.
2982 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2986 INP_WLOCK_ASSERT(tp->t_inpcb);
2988 TCPSTAT_INC(tcps_rttupdated);
2990 if (tp->t_srtt != 0) {
2992 * srtt is stored as fixed point with 5 bits after the
2993 * binary point (i.e., scaled by 8). The following magic
2994 * is equivalent to the smoothing algorithm in rfc793 with
2995 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2996 * point). Adjust rtt to origin 0.
2998 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2999 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3001 if ((tp->t_srtt += delta) <= 0)
3005 * We accumulate a smoothed rtt variance (actually, a
3006 * smoothed mean difference), then set the retransmit
3007 * timer to smoothed rtt + 4 times the smoothed variance.
3008 * rttvar is stored as fixed point with 4 bits after the
3009 * binary point (scaled by 16). The following is
3010 * equivalent to rfc793 smoothing with an alpha of .75
3011 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3012 * rfc793's wired-in beta.
3016 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3017 if ((tp->t_rttvar += delta) <= 0)
3019 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3020 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3023 * No rtt measurement yet - use the unsmoothed rtt.
3024 * Set the variance to half the rtt (so our first
3025 * retransmit happens at 3*rtt).
3027 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3028 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3029 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3035 * the retransmit should happen at rtt + 4 * rttvar.
3036 * Because of the way we do the smoothing, srtt and rttvar
3037 * will each average +1/2 tick of bias. When we compute
3038 * the retransmit timer, we want 1/2 tick of rounding and
3039 * 1 extra tick because of +-1/2 tick uncertainty in the
3040 * firing of the timer. The bias will give us exactly the
3041 * 1.5 tick we need. But, because the bias is
3042 * statistical, we have to test that we don't drop below
3043 * the minimum feasible timer (which is 2 ticks).
3045 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3046 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3049 * We received an ack for a packet that wasn't retransmitted;
3050 * it is probably safe to discard any error indications we've
3051 * received recently. This isn't quite right, but close enough
3052 * for now (a route might have failed after we sent a segment,
3053 * and the return path might not be symmetrical).
3055 tp->t_softerror = 0;
3059 * Determine a reasonable value for maxseg size.
3060 * If the route is known, check route for mtu.
3061 * If none, use an mss that can be handled on the outgoing
3062 * interface without forcing IP to fragment; if bigger than
3063 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3064 * to utilize large mbufs. If no route is found, route has no mtu,
3065 * or the destination isn't local, use a default, hopefully conservative
3066 * size (usually 512 or the default IP max size, but no more than the mtu
3067 * of the interface), as we can't discover anything about intervening
3068 * gateways or networks. We also initialize the congestion/slow start
3069 * window to be a single segment if the destination isn't local.
3070 * While looking at the routing entry, we also initialize other path-dependent
3071 * parameters from pre-set or cached values in the routing entry.
3073 * Also take into account the space needed for options that we
3074 * send regularly. Make maxseg shorter by that amount to assure
3075 * that we can send maxseg amount of data even when the options
3076 * are present. Store the upper limit of the length of options plus
3079 * In case of T/TCP, we call this routine during implicit connection
3080 * setup as well (offer = -1), to initialize maxseg from the cached
3083 * NOTE that this routine is only called when we process an incoming
3084 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3087 tcp_mss_update(struct tcpcb *tp, int offer,
3088 struct hc_metrics_lite *metricptr, int *mtuflags)
3092 struct inpcb *inp = tp->t_inpcb;
3093 struct hc_metrics_lite metrics;
3094 int origoffer = offer;
3096 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3097 size_t min_protoh = isipv6 ?
3098 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3099 sizeof (struct tcpiphdr);
3101 const size_t min_protoh = sizeof(struct tcpiphdr);
3104 INP_WLOCK_ASSERT(tp->t_inpcb);
3109 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3110 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3114 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3115 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3119 * No route to sender, stay with default mss and return.
3123 * In case we return early we need to initialize metrics
3124 * to a defined state as tcp_hc_get() would do for us
3125 * if there was no cache hit.
3127 if (metricptr != NULL)
3128 bzero(metricptr, sizeof(struct hc_metrics_lite));
3132 /* What have we got? */
3136 * Offer == 0 means that there was no MSS on the SYN
3137 * segment, in this case we use tcp_mssdflt as
3138 * already assigned to t_maxopd above.
3140 offer = tp->t_maxopd;
3145 * Offer == -1 means that we didn't receive SYN yet.
3151 * Prevent DoS attack with too small MSS. Round up
3152 * to at least minmss.
3154 offer = max(offer, V_tcp_minmss);
3158 * rmx information is now retrieved from tcp_hostcache.
3160 tcp_hc_get(&inp->inp_inc, &metrics);
3161 if (metricptr != NULL)
3162 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3165 * If there's a discovered mtu int tcp hostcache, use it
3166 * else, use the link mtu.
3168 if (metrics.rmx_mtu)
3169 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3173 mss = maxmtu - min_protoh;
3174 if (!V_path_mtu_discovery &&
3175 !in6_localaddr(&inp->in6p_faddr))
3176 mss = min(mss, V_tcp_v6mssdflt);
3180 mss = maxmtu - min_protoh;
3181 if (!V_path_mtu_discovery &&
3182 !in_localaddr(inp->inp_faddr))
3183 mss = min(mss, V_tcp_mssdflt);
3186 * XXX - The above conditional (mss = maxmtu - min_protoh)
3187 * probably violates the TCP spec.
3188 * The problem is that, since we don't know the
3189 * other end's MSS, we are supposed to use a conservative
3190 * default. But, if we do that, then MTU discovery will
3191 * never actually take place, because the conservative
3192 * default is much less than the MTUs typically seen
3193 * on the Internet today. For the moment, we'll sweep
3194 * this under the carpet.
3196 * The conservative default might not actually be a problem
3197 * if the only case this occurs is when sending an initial
3198 * SYN with options and data to a host we've never talked
3199 * to before. Then, they will reply with an MSS value which
3200 * will get recorded and the new parameters should get
3201 * recomputed. For Further Study.
3204 mss = min(mss, offer);
3207 * Sanity check: make sure that maxopd will be large
3208 * enough to allow some data on segments even if the
3209 * all the option space is used (40bytes). Otherwise
3210 * funny things may happen in tcp_output.
3215 * maxopd stores the maximum length of data AND options
3216 * in a segment; maxseg is the amount of data in a normal
3217 * segment. We need to store this value (maxopd) apart
3218 * from maxseg, because now every segment carries options
3219 * and thus we normally have somewhat less data in segments.
3224 * origoffer==-1 indicates that no segments were received yet.
3225 * In this case we just guess.
3227 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3229 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3230 mss -= TCPOLEN_TSTAMP_APPA;
3232 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3234 mss &= ~(MCLBYTES-1);
3237 mss = mss / MCLBYTES * MCLBYTES;
3243 tcp_mss(struct tcpcb *tp, int offer)
3249 struct hc_metrics_lite metrics;
3254 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3256 tcp_mss_update(tp, offer, &metrics, &mtuflags);
3261 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3265 * If there's a pipesize, change the socket buffer to that size,
3266 * don't change if sb_hiwat is different than default (then it
3267 * has been changed on purpose with setsockopt).
3268 * Make the socket buffers an integral number of mss units;
3269 * if the mss is larger than the socket buffer, decrease the mss.
3271 so = inp->inp_socket;
3272 SOCKBUF_LOCK(&so->so_snd);
3273 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3274 bufsize = metrics.rmx_sendpipe;
3276 bufsize = so->so_snd.sb_hiwat;
3280 bufsize = roundup(bufsize, mss);
3281 if (bufsize > sb_max)
3283 if (bufsize > so->so_snd.sb_hiwat)
3284 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3286 SOCKBUF_UNLOCK(&so->so_snd);
3289 SOCKBUF_LOCK(&so->so_rcv);
3290 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3291 bufsize = metrics.rmx_recvpipe;
3293 bufsize = so->so_rcv.sb_hiwat;
3294 if (bufsize > mss) {
3295 bufsize = roundup(bufsize, mss);
3296 if (bufsize > sb_max)
3298 if (bufsize > so->so_rcv.sb_hiwat)
3299 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3301 SOCKBUF_UNLOCK(&so->so_rcv);
3303 * While we're here, check the others too.
3305 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3307 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3308 TCPSTAT_INC(tcps_usedrtt);
3309 if (metrics.rmx_rttvar) {
3310 tp->t_rttvar = metrics.rmx_rttvar;
3311 TCPSTAT_INC(tcps_usedrttvar);
3313 /* default variation is +- 1 rtt */
3315 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3317 TCPT_RANGESET(tp->t_rxtcur,
3318 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3319 tp->t_rttmin, TCPTV_REXMTMAX);
3321 if (metrics.rmx_ssthresh) {
3323 * There's some sort of gateway or interface
3324 * buffer limit on the path. Use this to set
3325 * the slow start threshhold, but set the
3326 * threshold to no less than 2*mss.
3328 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3329 TCPSTAT_INC(tcps_usedssthresh);
3331 if (metrics.rmx_bandwidth)
3332 tp->snd_bandwidth = metrics.rmx_bandwidth;
3335 * Set the slow-start flight size depending on whether this
3336 * is a local network or not.
3338 * Extend this so we cache the cwnd too and retrieve it here.
3339 * Make cwnd even bigger than RFC3390 suggests but only if we
3340 * have previous experience with the remote host. Be careful
3341 * not make cwnd bigger than remote receive window or our own
3342 * send socket buffer. Maybe put some additional upper bound
3343 * on the retrieved cwnd. Should do incremental updates to
3344 * hostcache when cwnd collapses so next connection doesn't
3345 * overloads the path again.
3347 * XXXAO: Initializing the CWND from the hostcache is broken
3348 * and in its current form not RFC conformant. It is disabled
3349 * until fixed or removed entirely.
3351 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3352 * We currently check only in syncache_socket for that.
3354 /* #define TCP_METRICS_CWND */
3355 #ifdef TCP_METRICS_CWND
3356 if (metrics.rmx_cwnd)
3357 tp->snd_cwnd = max(mss,
3358 min(metrics.rmx_cwnd / 2,
3359 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3362 if (V_tcp_do_rfc3390)
3363 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3365 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3366 (!isipv6 && in_localaddr(inp->inp_faddr)))
3368 else if (in_localaddr(inp->inp_faddr))
3370 tp->snd_cwnd = mss * V_ss_fltsz_local;
3372 tp->snd_cwnd = mss * V_ss_fltsz;
3374 /* Check the interface for TSO capabilities. */
3375 if (mtuflags & CSUM_TSO)
3376 tp->t_flags |= TF_TSO;
3380 * Determine the MSS option to send on an outgoing SYN.
3383 tcp_mssopt(struct in_conninfo *inc)
3390 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3393 if (inc->inc_flags & INC_ISIPV6) {
3394 mss = V_tcp_v6mssdflt;
3395 maxmtu = tcp_maxmtu6(inc, NULL);
3396 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3397 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3401 mss = V_tcp_mssdflt;
3402 maxmtu = tcp_maxmtu(inc, NULL);
3403 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3404 min_protoh = sizeof(struct tcpiphdr);
3406 if (maxmtu && thcmtu)
3407 mss = min(maxmtu, thcmtu) - min_protoh;
3408 else if (maxmtu || thcmtu)
3409 mss = max(maxmtu, thcmtu) - min_protoh;
3416 * On a partial ack arrives, force the retransmission of the
3417 * next unacknowledged segment. Do not clear tp->t_dupacks.
3418 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3422 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3424 tcp_seq onxt = tp->snd_nxt;
3425 u_long ocwnd = tp->snd_cwnd;
3427 INP_WLOCK_ASSERT(tp->t_inpcb);
3429 tcp_timer_activate(tp, TT_REXMT, 0);
3431 tp->snd_nxt = th->th_ack;
3433 * Set snd_cwnd to one segment beyond acknowledged offset.
3434 * (tp->snd_una has not yet been updated when this function is called.)
3436 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3437 tp->t_flags |= TF_ACKNOW;
3438 (void) tcp_output(tp);
3439 tp->snd_cwnd = ocwnd;
3440 if (SEQ_GT(onxt, tp->snd_nxt))
3443 * Partial window deflation. Relies on fact that tp->snd_una
3446 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3447 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3450 tp->snd_cwnd += tp->t_maxseg;