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 VNET_DEFINE(int, blackhole);
103 VNET_DEFINE(int, tcp_delack_enabled);
104 VNET_DEFINE(int, drop_synfin);
105 VNET_DEFINE(int, tcp_do_rfc3042);
106 VNET_DEFINE(int, tcp_do_rfc3390);
107 VNET_DEFINE(int, tcp_do_ecn);
108 VNET_DEFINE(int, tcp_ecn_maxretries);
109 VNET_DEFINE(int, tcp_insecure_rst);
110 VNET_DEFINE(int, tcp_do_autorcvbuf);
111 VNET_DEFINE(int, tcp_autorcvbuf_inc);
112 VNET_DEFINE(int, tcp_autorcvbuf_max);
113 VNET_DEFINE(int, tcp_do_rfc3465);
114 VNET_DEFINE(int, tcp_abc_l_var);
116 SYSCTL_VNET_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
117 &VNET_NAME(tcpstat), tcpstat,
118 "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
120 int tcp_log_in_vain = 0;
121 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
123 "Log all incoming TCP segments to closed ports");
125 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
126 &VNET_NAME(blackhole), 0,
127 "Do not send RST on segments to closed ports");
129 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
130 &VNET_NAME(tcp_delack_enabled), 0,
131 "Delay ACK to try and piggyback it onto a data packet");
133 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
134 &VNET_NAME(drop_synfin), 0,
135 "Drop TCP packets with SYN+FIN set");
137 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
138 &VNET_NAME(tcp_do_rfc3042), 0,
139 "Enable RFC 3042 (Limited Transmit)");
141 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
142 &VNET_NAME(tcp_do_rfc3390), 0,
143 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
145 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
146 &VNET_NAME(tcp_do_rfc3465), 0,
147 "Enable RFC 3465 (Appropriate Byte Counting)");
149 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
150 &VNET_NAME(tcp_abc_l_var), 2,
151 "Cap the max cwnd increment during slow-start to this number of segments");
153 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
155 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
156 &VNET_NAME(tcp_do_ecn), 0,
159 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
160 &VNET_NAME(tcp_ecn_maxretries), 0,
161 "Max retries before giving up on ECN");
163 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
164 &VNET_NAME(tcp_insecure_rst), 0,
165 "Follow the old (insecure) criteria for accepting RST packets");
167 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
168 &VNET_NAME(tcp_do_autorcvbuf), 0,
169 "Enable automatic receive buffer sizing");
171 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
172 &VNET_NAME(tcp_autorcvbuf_inc), 0,
173 "Incrementor step size of automatic receive buffer");
175 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
176 &VNET_NAME(tcp_autorcvbuf_max), 0,
177 "Max size of automatic receive buffer");
179 int tcp_read_locking = 1;
180 SYSCTL_INT(_net_inet_tcp, OID_AUTO, read_locking, CTLFLAG_RW,
181 &tcp_read_locking, 0, "Enable read locking strategy");
183 int tcp_rlock_atfirst;
184 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rlock_atfirst, CTLFLAG_RD,
185 &tcp_rlock_atfirst, 0, "");
187 int tcp_wlock_atfirst;
188 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_wlock_atfirst, CTLFLAG_RD,
189 &tcp_wlock_atfirst, 0, "");
191 int tcp_wlock_upgraded;
192 SYSCTL_INT(_net_inet_tcp, OID_AUTO, wlock_upgraded, CTLFLAG_RD,
193 &tcp_wlock_upgraded, 0, "");
195 int tcp_wlock_relocked;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, wlock_relocked, CTLFLAG_RD,
197 &tcp_wlock_relocked, 0, "");
199 int tcp_wlock_looped;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, wlock_looped, CTLFLAG_RD,
201 &tcp_wlock_looped, 0, "");
203 VNET_DEFINE(struct inpcbhead, tcb);
204 VNET_DEFINE(struct inpcbinfo, tcbinfo);
205 #define tcb6 tcb /* for KAME src sync over BSD*'s */
207 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
208 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
209 struct socket *, struct tcpcb *, int, int, uint8_t,
211 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
212 struct tcpcb *, int, int);
213 static void tcp_pulloutofband(struct socket *,
214 struct tcphdr *, struct mbuf *, int);
215 static void tcp_xmit_timer(struct tcpcb *, int);
216 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
218 tcp_congestion_exp(struct tcpcb *);
221 * Kernel module interface for updating tcpstat. The argument is an index
222 * into tcpstat treated as an array of u_long. While this encodes the
223 * general layout of tcpstat into the caller, it doesn't encode its location,
224 * so that future changes to add, for example, per-CPU stats support won't
225 * cause binary compatibility problems for kernel modules.
228 kmod_tcpstat_inc(int statnum)
231 (*((u_long *)&V_tcpstat + statnum))++;
235 tcp_congestion_exp(struct tcpcb *tp)
239 win = min(tp->snd_wnd, tp->snd_cwnd) /
243 tp->snd_ssthresh = win * tp->t_maxseg;
244 ENTER_FASTRECOVERY(tp);
245 tp->snd_recover = tp->snd_max;
246 if (tp->t_flags & TF_ECN_PERMIT)
247 tp->t_flags |= TF_ECN_SND_CWR;
250 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
252 #define ND6_HINT(tp) \
254 if ((tp) && (tp)->t_inpcb && \
255 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
256 nd6_nud_hint(NULL, NULL, 0); \
263 * Indicate whether this ack should be delayed. We can delay the ack if
264 * - there is no delayed ack timer in progress and
265 * - our last ack wasn't a 0-sized window. We never want to delay
266 * the ack that opens up a 0-sized window and
267 * - delayed acks are enabled or
268 * - this is a half-synchronized T/TCP connection.
270 #define DELAY_ACK(tp) \
271 ((!tcp_timer_active(tp, TT_DELACK) && \
272 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
273 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
276 * TCP input handling is split into multiple parts:
277 * tcp6_input is a thin wrapper around tcp_input for the extended
278 * ip6_protox[] call format in ip6_input
279 * tcp_input handles primary segment validation, inpcb lookup and
280 * SYN processing on listen sockets
281 * tcp_do_segment processes the ACK and text of the segment for
282 * establishing, established and closing connections
286 tcp6_input(struct mbuf **mp, int *offp, int proto)
288 struct mbuf *m = *mp;
289 struct in6_ifaddr *ia6;
291 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
294 * draft-itojun-ipv6-tcp-to-anycast
295 * better place to put this in?
297 ia6 = ip6_getdstifaddr(m);
298 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
301 ifa_free(&ia6->ia_ifa);
302 ip6 = mtod(m, struct ip6_hdr *);
303 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
304 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
314 tcp_input(struct mbuf *m, int off0)
317 struct ip *ip = NULL;
319 struct inpcb *inp = NULL;
320 struct tcpcb *tp = NULL;
321 struct socket *so = NULL;
327 int rstreason = 0; /* For badport_bandlim accounting purposes */
329 #ifdef IPFIREWALL_FORWARD
330 struct m_tag *fwd_tag;
333 struct ip6_hdr *ip6 = NULL;
336 const void *ip6 = NULL;
337 const int isipv6 = 0;
339 struct tcpopt to; /* options in this segment */
340 char *s = NULL; /* address and port logging */
342 #define TI_UNLOCKED 1
348 * The size of tcp_saveipgen must be the size of the max ip header,
351 u_char tcp_saveipgen[IP6_HDR_LEN];
352 struct tcphdr tcp_savetcp;
357 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
361 TCPSTAT_INC(tcps_rcvtotal);
365 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
366 ip6 = mtod(m, struct ip6_hdr *);
367 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
368 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
369 TCPSTAT_INC(tcps_rcvbadsum);
372 th = (struct tcphdr *)((caddr_t)ip6 + off0);
375 * Be proactive about unspecified IPv6 address in source.
376 * As we use all-zero to indicate unbounded/unconnected pcb,
377 * unspecified IPv6 address can be used to confuse us.
379 * Note that packets with unspecified IPv6 destination is
380 * already dropped in ip6_input.
382 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
387 th = NULL; /* XXX: Avoid compiler warning. */
391 * Get IP and TCP header together in first mbuf.
392 * Note: IP leaves IP header in first mbuf.
394 if (off0 > sizeof (struct ip)) {
395 ip_stripoptions(m, (struct mbuf *)0);
396 off0 = sizeof(struct ip);
398 if (m->m_len < sizeof (struct tcpiphdr)) {
399 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
401 TCPSTAT_INC(tcps_rcvshort);
405 ip = mtod(m, struct ip *);
406 ipov = (struct ipovly *)ip;
407 th = (struct tcphdr *)((caddr_t)ip + off0);
410 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
411 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
412 th->th_sum = m->m_pkthdr.csum_data;
414 th->th_sum = in_pseudo(ip->ip_src.s_addr,
416 htonl(m->m_pkthdr.csum_data +
419 th->th_sum ^= 0xffff;
421 ipov->ih_len = (u_short)tlen;
422 ipov->ih_len = htons(ipov->ih_len);
426 * Checksum extended TCP header and data.
428 len = sizeof (struct ip) + tlen;
429 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
430 ipov->ih_len = (u_short)tlen;
431 ipov->ih_len = htons(ipov->ih_len);
432 th->th_sum = in_cksum(m, len);
435 TCPSTAT_INC(tcps_rcvbadsum);
438 /* Re-initialization for later version check */
439 ip->ip_v = IPVERSION;
444 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
450 * Check that TCP offset makes sense,
451 * pull out TCP options and adjust length. XXX
453 off = th->th_off << 2;
454 if (off < sizeof (struct tcphdr) || off > tlen) {
455 TCPSTAT_INC(tcps_rcvbadoff);
458 tlen -= off; /* tlen is used instead of ti->ti_len */
459 if (off > sizeof (struct tcphdr)) {
462 IP6_EXTHDR_CHECK(m, off0, off, );
463 ip6 = mtod(m, struct ip6_hdr *);
464 th = (struct tcphdr *)((caddr_t)ip6 + off0);
467 if (m->m_len < sizeof(struct ip) + off) {
468 if ((m = m_pullup(m, sizeof (struct ip) + off))
470 TCPSTAT_INC(tcps_rcvshort);
473 ip = mtod(m, struct ip *);
474 ipov = (struct ipovly *)ip;
475 th = (struct tcphdr *)((caddr_t)ip + off0);
478 optlen = off - sizeof (struct tcphdr);
479 optp = (u_char *)(th + 1);
481 thflags = th->th_flags;
484 * Convert TCP protocol specific fields to host format.
486 th->th_seq = ntohl(th->th_seq);
487 th->th_ack = ntohl(th->th_ack);
488 th->th_win = ntohs(th->th_win);
489 th->th_urp = ntohs(th->th_urp);
492 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
494 drop_hdrlen = off0 + off;
497 * Locate pcb for segment, which requires a lock on tcbinfo.
498 * Optimisticaly acquire a global read lock rather than a write lock
499 * unless header flags necessarily imply a state change. There are
500 * two cases where we might discover later we need a write lock
501 * despite the flags: ACKs moving a connection out of the syncache,
502 * and ACKs for a connection in TIMEWAIT.
504 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
505 tcp_read_locking == 0) {
506 INP_INFO_WLOCK(&V_tcbinfo);
507 ti_locked = TI_WLOCKED;
510 INP_INFO_RLOCK(&V_tcbinfo);
511 ti_locked = TI_RLOCKED;
517 if (ti_locked == TI_RLOCKED)
518 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
519 else if (ti_locked == TI_WLOCKED)
520 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
522 panic("%s: findpcb ti_locked %d\n", __func__, ti_locked);
525 #ifdef IPFIREWALL_FORWARD
527 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
529 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
531 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
532 struct sockaddr_in *next_hop;
534 next_hop = (struct sockaddr_in *)(fwd_tag+1);
536 * Transparently forwarded. Pretend to be the destination.
537 * already got one like this?
539 inp = in_pcblookup_hash(&V_tcbinfo,
540 ip->ip_src, th->th_sport,
541 ip->ip_dst, th->th_dport,
542 0, m->m_pkthdr.rcvif);
544 /* It's new. Try to find the ambushing socket. */
545 inp = in_pcblookup_hash(&V_tcbinfo,
546 ip->ip_src, th->th_sport,
549 ntohs(next_hop->sin_port) :
554 /* Remove the tag from the packet. We don't need it anymore. */
555 m_tag_delete(m, fwd_tag);
557 #endif /* IPFIREWALL_FORWARD */
561 inp = in6_pcblookup_hash(&V_tcbinfo,
562 &ip6->ip6_src, th->th_sport,
563 &ip6->ip6_dst, th->th_dport,
568 inp = in_pcblookup_hash(&V_tcbinfo,
569 ip->ip_src, th->th_sport,
570 ip->ip_dst, th->th_dport,
576 * If the INPCB does not exist then all data in the incoming
577 * segment is discarded and an appropriate RST is sent back.
578 * XXX MRT Send RST using which routing table?
582 * Log communication attempts to ports that are not
585 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
586 tcp_log_in_vain == 2) {
587 if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
588 log(LOG_INFO, "%s; %s: Connection attempt "
589 "to closed port\n", s, __func__);
592 * When blackholing do not respond with a RST but
593 * completely ignore the segment and drop it.
595 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
599 rstreason = BANDLIM_RST_CLOSEDPORT;
603 if (!(inp->inp_flags & INP_HW_FLOWID)
604 && (m->m_flags & M_FLOWID)
605 && ((inp->inp_socket == NULL)
606 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
607 inp->inp_flags |= INP_HW_FLOWID;
608 inp->inp_flags &= ~INP_SW_FLOWID;
609 inp->inp_flowid = m->m_pkthdr.flowid;
613 if (isipv6 && ipsec6_in_reject(m, inp)) {
614 V_ipsec6stat.in_polvio++;
618 if (ipsec4_in_reject(m, inp) != 0) {
619 V_ipsec4stat.in_polvio++;
625 * Check the minimum TTL for socket.
627 if (inp->inp_ip_minttl != 0) {
629 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
633 if (inp->inp_ip_minttl > ip->ip_ttl)
638 * A previous connection in TIMEWAIT state is supposed to catch stray
639 * or duplicate segments arriving late. If this segment was a
640 * legitimate new connection attempt the old INPCB gets removed and
641 * we can try again to find a listening socket.
643 * At this point, due to earlier optimism, we may hold a read lock on
644 * the inpcbinfo, rather than a write lock. If so, we need to
645 * upgrade, or if that fails, acquire a reference on the inpcb, drop
646 * all locks, acquire a global write lock, and then re-acquire the
647 * inpcb lock. We may at that point discover that another thread has
648 * tried to free the inpcb, in which case we need to loop back and
649 * try to find a new inpcb to deliver to.
651 if (inp->inp_flags & INP_TIMEWAIT) {
652 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
653 ("%s: INP_TIMEWAIT ti_locked %d", __func__, ti_locked));
655 if (ti_locked == TI_RLOCKED) {
656 if (rw_try_upgrade(&V_tcbinfo.ipi_lock) == 0) {
659 INP_INFO_RUNLOCK(&V_tcbinfo);
660 INP_INFO_WLOCK(&V_tcbinfo);
661 ti_locked = TI_WLOCKED;
663 if (in_pcbrele(inp)) {
668 tcp_wlock_relocked++;
670 ti_locked = TI_WLOCKED;
671 tcp_wlock_upgraded++;
674 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
676 if (thflags & TH_SYN)
677 tcp_dooptions(&to, optp, optlen, TO_SYN);
679 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
681 if (tcp_twcheck(inp, &to, th, m, tlen))
683 INP_INFO_WUNLOCK(&V_tcbinfo);
687 * The TCPCB may no longer exist if the connection is winding
688 * down or it is in the CLOSED state. Either way we drop the
689 * segment and send an appropriate response.
692 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
693 rstreason = BANDLIM_RST_CLOSEDPORT;
698 * We've identified a valid inpcb, but it could be that we need an
699 * inpcbinfo write lock and have only a read lock. In this case,
700 * attempt to upgrade/relock using the same strategy as the TIMEWAIT
703 if (tp->t_state != TCPS_ESTABLISHED ||
704 (thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
705 tcp_read_locking == 0) {
706 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
707 ("%s: upgrade check ti_locked %d", __func__, ti_locked));
709 if (ti_locked == TI_RLOCKED) {
710 if (rw_try_upgrade(&V_tcbinfo.ipi_lock) == 0) {
713 INP_INFO_RUNLOCK(&V_tcbinfo);
714 INP_INFO_WLOCK(&V_tcbinfo);
715 ti_locked = TI_WLOCKED;
717 if (in_pcbrele(inp)) {
722 tcp_wlock_relocked++;
724 ti_locked = TI_WLOCKED;
725 tcp_wlock_upgraded++;
728 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
732 INP_WLOCK_ASSERT(inp);
733 if (mac_inpcb_check_deliver(inp, m))
736 so = inp->inp_socket;
737 KASSERT(so != NULL, ("%s: so == NULL", __func__));
739 if (so->so_options & SO_DEBUG) {
740 ostate = tp->t_state;
743 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
746 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
751 * When the socket is accepting connections (the INPCB is in LISTEN
752 * state) we look into the SYN cache if this is a new connection
753 * attempt or the completion of a previous one.
755 if (so->so_options & SO_ACCEPTCONN) {
756 struct in_conninfo inc;
758 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
759 "tp not listening", __func__));
761 bzero(&inc, sizeof(inc));
764 inc.inc_flags |= INC_ISIPV6;
765 inc.inc6_faddr = ip6->ip6_src;
766 inc.inc6_laddr = ip6->ip6_dst;
770 inc.inc_faddr = ip->ip_src;
771 inc.inc_laddr = ip->ip_dst;
773 inc.inc_fport = th->th_sport;
774 inc.inc_lport = th->th_dport;
775 inc.inc_fibnum = so->so_fibnum;
778 * Check for an existing connection attempt in syncache if
779 * the flag is only ACK. A successful lookup creates a new
780 * socket appended to the listen queue in SYN_RECEIVED state.
782 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
784 * Parse the TCP options here because
785 * syncookies need access to the reflected
788 tcp_dooptions(&to, optp, optlen, 0);
790 * NB: syncache_expand() doesn't unlock
791 * inp and tcpinfo locks.
793 if (!syncache_expand(&inc, &to, th, &so, m)) {
795 * No syncache entry or ACK was not
796 * for our SYN/ACK. Send a RST.
797 * NB: syncache did its own logging
798 * of the failure cause.
800 rstreason = BANDLIM_RST_OPENPORT;
805 * We completed the 3-way handshake
806 * but could not allocate a socket
807 * either due to memory shortage,
808 * listen queue length limits or
809 * global socket limits. Send RST
810 * or wait and have the remote end
811 * retransmit the ACK for another
814 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
815 log(LOG_DEBUG, "%s; %s: Listen socket: "
816 "Socket allocation failed due to "
817 "limits or memory shortage, %s\n",
819 V_tcp_sc_rst_sock_fail ?
820 "sending RST" : "try again");
821 if (V_tcp_sc_rst_sock_fail) {
822 rstreason = BANDLIM_UNLIMITED;
828 * Socket is created in state SYN_RECEIVED.
829 * Unlock the listen socket, lock the newly
830 * created socket and update the tp variable.
832 INP_WUNLOCK(inp); /* listen socket */
834 INP_WLOCK(inp); /* new connection */
836 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
839 * Process the segment and the data it
840 * contains. tcp_do_segment() consumes
841 * the mbuf chain and unlocks the inpcb.
843 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
845 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
849 * Segment flag validation for new connection attempts:
851 * Our (SYN|ACK) response was rejected.
852 * Check with syncache and remove entry to prevent
855 * NB: syncache_chkrst does its own logging of failure
858 if (thflags & TH_RST) {
859 syncache_chkrst(&inc, th);
863 * We can't do anything without SYN.
865 if ((thflags & TH_SYN) == 0) {
866 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
867 log(LOG_DEBUG, "%s; %s: Listen socket: "
868 "SYN is missing, segment ignored\n",
870 TCPSTAT_INC(tcps_badsyn);
874 * (SYN|ACK) is bogus on a listen socket.
876 if (thflags & TH_ACK) {
877 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
878 log(LOG_DEBUG, "%s; %s: Listen socket: "
879 "SYN|ACK invalid, segment rejected\n",
881 syncache_badack(&inc); /* XXX: Not needed! */
882 TCPSTAT_INC(tcps_badsyn);
883 rstreason = BANDLIM_RST_OPENPORT;
887 * If the drop_synfin option is enabled, drop all
888 * segments with both the SYN and FIN bits set.
889 * This prevents e.g. nmap from identifying the
891 * XXX: Poor reasoning. nmap has other methods
892 * and is constantly refining its stack detection
894 * XXX: This is a violation of the TCP specification
895 * and was used by RFC1644.
897 if ((thflags & TH_FIN) && V_drop_synfin) {
898 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
899 log(LOG_DEBUG, "%s; %s: Listen socket: "
900 "SYN|FIN segment ignored (based on "
901 "sysctl setting)\n", s, __func__);
902 TCPSTAT_INC(tcps_badsyn);
906 * Segment's flags are (SYN) or (SYN|FIN).
908 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
909 * as they do not affect the state of the TCP FSM.
910 * The data pointed to by TH_URG and th_urp is ignored.
912 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
913 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
914 KASSERT(thflags & (TH_SYN),
915 ("%s: Listen socket: TH_SYN not set", __func__));
918 * If deprecated address is forbidden,
919 * we do not accept SYN to deprecated interface
920 * address to prevent any new inbound connection from
921 * getting established.
922 * When we do not accept SYN, we send a TCP RST,
923 * with deprecated source address (instead of dropping
924 * it). We compromise it as it is much better for peer
925 * to send a RST, and RST will be the final packet
928 * If we do not forbid deprecated addresses, we accept
929 * the SYN packet. RFC2462 does not suggest dropping
931 * If we decipher RFC2462 5.5.4, it says like this:
932 * 1. use of deprecated addr with existing
933 * communication is okay - "SHOULD continue to be
935 * 2. use of it with new communication:
936 * (2a) "SHOULD NOT be used if alternate address
937 * with sufficient scope is available"
938 * (2b) nothing mentioned otherwise.
939 * Here we fall into (2b) case as we have no choice in
940 * our source address selection - we must obey the peer.
942 * The wording in RFC2462 is confusing, and there are
943 * multiple description text for deprecated address
944 * handling - worse, they are not exactly the same.
945 * I believe 5.5.4 is the best one, so we follow 5.5.4.
947 if (isipv6 && !V_ip6_use_deprecated) {
948 struct in6_ifaddr *ia6;
950 ia6 = ip6_getdstifaddr(m);
952 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
953 ifa_free(&ia6->ia_ifa);
954 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
955 log(LOG_DEBUG, "%s; %s: Listen socket: "
956 "Connection attempt to deprecated "
957 "IPv6 address rejected\n",
959 rstreason = BANDLIM_RST_OPENPORT;
962 ifa_free(&ia6->ia_ifa);
966 * Basic sanity checks on incoming SYN requests:
967 * Don't respond if the destination is a link layer
968 * broadcast according to RFC1122 4.2.3.10, p. 104.
969 * If it is from this socket it must be forged.
970 * Don't respond if the source or destination is a
971 * global or subnet broad- or multicast address.
972 * Note that it is quite possible to receive unicast
973 * link-layer packets with a broadcast IP address. Use
974 * in_broadcast() to find them.
976 if (m->m_flags & (M_BCAST|M_MCAST)) {
977 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
978 log(LOG_DEBUG, "%s; %s: Listen socket: "
979 "Connection attempt from broad- or multicast "
980 "link layer address ignored\n", s, __func__);
985 if (th->th_dport == th->th_sport &&
986 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
987 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
988 log(LOG_DEBUG, "%s; %s: Listen socket: "
989 "Connection attempt to/from self "
990 "ignored\n", s, __func__);
993 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
994 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
995 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
996 log(LOG_DEBUG, "%s; %s: Listen socket: "
997 "Connection attempt from/to multicast "
998 "address ignored\n", s, __func__);
1003 if (th->th_dport == th->th_sport &&
1004 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1005 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1006 log(LOG_DEBUG, "%s; %s: Listen socket: "
1007 "Connection attempt from/to self "
1008 "ignored\n", s, __func__);
1011 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1012 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1013 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1014 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1015 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1016 log(LOG_DEBUG, "%s; %s: Listen socket: "
1017 "Connection attempt from/to broad- "
1018 "or multicast address ignored\n",
1024 * SYN appears to be valid. Create compressed TCP state
1028 if (so->so_options & SO_DEBUG)
1029 tcp_trace(TA_INPUT, ostate, tp,
1030 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1032 tcp_dooptions(&to, optp, optlen, TO_SYN);
1033 syncache_add(&inc, &to, th, inp, &so, m);
1035 * Entry added to syncache and mbuf consumed.
1036 * Everything already unlocked by syncache_add().
1038 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1043 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1044 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1045 * the inpcb, and unlocks pcbinfo.
1047 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1048 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1052 if (ti_locked == TI_RLOCKED)
1053 INP_INFO_RUNLOCK(&V_tcbinfo);
1054 else if (ti_locked == TI_WLOCKED)
1055 INP_INFO_WUNLOCK(&V_tcbinfo);
1057 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
1058 ti_locked = TI_UNLOCKED;
1061 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1064 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1065 m = NULL; /* mbuf chain got consumed. */
1069 if (ti_locked == TI_RLOCKED)
1070 INP_INFO_RUNLOCK(&V_tcbinfo);
1071 else if (ti_locked == TI_WLOCKED)
1072 INP_INFO_WUNLOCK(&V_tcbinfo);
1074 panic("%s: dropunlock ti_locked %d", __func__, ti_locked);
1075 ti_locked = TI_UNLOCKED;
1081 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1089 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1090 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1093 int thflags, acked, ourfinisacked, needoutput = 0;
1094 int rstreason, todrop, win;
1100 * The size of tcp_saveipgen must be the size of the max ip header,
1103 u_char tcp_saveipgen[IP6_HDR_LEN];
1104 struct tcphdr tcp_savetcp;
1107 thflags = th->th_flags;
1110 * If this is either a state-changing packet or current state isn't
1111 * established, we require a write lock on tcbinfo. Otherwise, we
1112 * allow either a read lock or a write lock, as we may have acquired
1113 * a write lock due to a race.
1115 * Require a global write lock for SYN/FIN/RST segments or
1116 * non-established connections; otherwise accept either a read or
1117 * write lock, as we may have conservatively acquired a write lock in
1118 * certain cases in tcp_input() (is this still true?). Currently we
1119 * will never enter with no lock, so we try to drop it quickly in the
1120 * common pure ack/pure data cases.
1122 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1123 tp->t_state != TCPS_ESTABLISHED) {
1124 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1125 "SYN/FIN/RST/!EST", __func__, ti_locked));
1126 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1129 if (ti_locked == TI_RLOCKED)
1130 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1131 else if (ti_locked == TI_WLOCKED)
1132 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1134 panic("%s: ti_locked %d for EST", __func__,
1138 INP_WLOCK_ASSERT(tp->t_inpcb);
1139 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1141 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1145 * Segment received on connection.
1146 * Reset idle time and keep-alive timer.
1147 * XXX: This should be done after segment
1148 * validation to ignore broken/spoofed segs.
1150 tp->t_rcvtime = ticks;
1151 if (TCPS_HAVEESTABLISHED(tp->t_state))
1152 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1155 * Unscale the window into a 32-bit value.
1156 * For the SYN_SENT state the scale is zero.
1158 tiwin = th->th_win << tp->snd_scale;
1161 * TCP ECN processing.
1163 if (tp->t_flags & TF_ECN_PERMIT) {
1164 switch (iptos & IPTOS_ECN_MASK) {
1166 tp->t_flags |= TF_ECN_SND_ECE;
1167 TCPSTAT_INC(tcps_ecn_ce);
1169 case IPTOS_ECN_ECT0:
1170 TCPSTAT_INC(tcps_ecn_ect0);
1172 case IPTOS_ECN_ECT1:
1173 TCPSTAT_INC(tcps_ecn_ect1);
1177 if (thflags & TH_CWR)
1178 tp->t_flags &= ~TF_ECN_SND_ECE;
1181 * Congestion experienced.
1182 * Ignore if we are already trying to recover.
1184 if ((thflags & TH_ECE) &&
1185 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
1186 TCPSTAT_INC(tcps_ecn_rcwnd);
1187 tcp_congestion_exp(tp);
1192 * Parse options on any incoming segment.
1194 tcp_dooptions(&to, (u_char *)(th + 1),
1195 (th->th_off << 2) - sizeof(struct tcphdr),
1196 (thflags & TH_SYN) ? TO_SYN : 0);
1199 * If echoed timestamp is later than the current time,
1200 * fall back to non RFC1323 RTT calculation. Normalize
1201 * timestamp if syncookies were used when this connection
1204 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1205 to.to_tsecr -= tp->ts_offset;
1206 if (TSTMP_GT(to.to_tsecr, ticks))
1211 * Process options only when we get SYN/ACK back. The SYN case
1212 * for incoming connections is handled in tcp_syncache.
1213 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1214 * or <SYN,ACK>) segment itself is never scaled.
1215 * XXX this is traditional behavior, may need to be cleaned up.
1217 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1218 if ((to.to_flags & TOF_SCALE) &&
1219 (tp->t_flags & TF_REQ_SCALE)) {
1220 tp->t_flags |= TF_RCVD_SCALE;
1221 tp->snd_scale = to.to_wscale;
1224 * Initial send window. It will be updated with
1225 * the next incoming segment to the scaled value.
1227 tp->snd_wnd = th->th_win;
1228 if (to.to_flags & TOF_TS) {
1229 tp->t_flags |= TF_RCVD_TSTMP;
1230 tp->ts_recent = to.to_tsval;
1231 tp->ts_recent_age = ticks;
1233 if (to.to_flags & TOF_MSS)
1234 tcp_mss(tp, to.to_mss);
1235 if ((tp->t_flags & TF_SACK_PERMIT) &&
1236 (to.to_flags & TOF_SACKPERM) == 0)
1237 tp->t_flags &= ~TF_SACK_PERMIT;
1241 * Header prediction: check for the two common cases
1242 * of a uni-directional data xfer. If the packet has
1243 * no control flags, is in-sequence, the window didn't
1244 * change and we're not retransmitting, it's a
1245 * candidate. If the length is zero and the ack moved
1246 * forward, we're the sender side of the xfer. Just
1247 * free the data acked & wake any higher level process
1248 * that was blocked waiting for space. If the length
1249 * is non-zero and the ack didn't move, we're the
1250 * receiver side. If we're getting packets in-order
1251 * (the reassembly queue is empty), add the data to
1252 * the socket buffer and note that we need a delayed ack.
1253 * Make sure that the hidden state-flags are also off.
1254 * Since we check for TCPS_ESTABLISHED first, it can only
1257 if (tp->t_state == TCPS_ESTABLISHED &&
1258 th->th_seq == tp->rcv_nxt &&
1259 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1260 tp->snd_nxt == tp->snd_max &&
1261 tiwin && tiwin == tp->snd_wnd &&
1262 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1263 LIST_EMPTY(&tp->t_segq) &&
1264 ((to.to_flags & TOF_TS) == 0 ||
1265 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1268 * If last ACK falls within this segment's sequence numbers,
1269 * record the timestamp.
1270 * NOTE that the test is modified according to the latest
1271 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1273 if ((to.to_flags & TOF_TS) != 0 &&
1274 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1275 tp->ts_recent_age = ticks;
1276 tp->ts_recent = to.to_tsval;
1280 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1281 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1282 tp->snd_cwnd >= tp->snd_wnd &&
1283 ((!V_tcp_do_newreno &&
1284 !(tp->t_flags & TF_SACK_PERMIT) &&
1285 tp->t_dupacks < tcprexmtthresh) ||
1286 ((V_tcp_do_newreno ||
1287 (tp->t_flags & TF_SACK_PERMIT)) &&
1288 !IN_FASTRECOVERY(tp) &&
1289 (to.to_flags & TOF_SACK) == 0 &&
1290 TAILQ_EMPTY(&tp->snd_holes)))) {
1292 * This is a pure ack for outstanding data.
1294 if (ti_locked == TI_RLOCKED)
1295 INP_INFO_RUNLOCK(&V_tcbinfo);
1296 else if (ti_locked == TI_WLOCKED)
1297 INP_INFO_WUNLOCK(&V_tcbinfo);
1299 panic("%s: ti_locked %d on pure ACK",
1300 __func__, ti_locked);
1301 ti_locked = TI_UNLOCKED;
1303 TCPSTAT_INC(tcps_predack);
1306 * "bad retransmit" recovery.
1308 if (tp->t_rxtshift == 1 &&
1309 (int)(ticks - tp->t_badrxtwin) < 0) {
1310 TCPSTAT_INC(tcps_sndrexmitbad);
1311 tp->snd_cwnd = tp->snd_cwnd_prev;
1313 tp->snd_ssthresh_prev;
1314 tp->snd_recover = tp->snd_recover_prev;
1315 if (tp->t_flags & TF_WASFRECOVERY)
1316 ENTER_FASTRECOVERY(tp);
1317 tp->snd_nxt = tp->snd_max;
1318 tp->t_badrxtwin = 0;
1322 * Recalculate the transmit timer / rtt.
1324 * Some boxes send broken timestamp replies
1325 * during the SYN+ACK phase, ignore
1326 * timestamps of 0 or we could calculate a
1327 * huge RTT and blow up the retransmit timer.
1329 if ((to.to_flags & TOF_TS) != 0 &&
1331 if (!tp->t_rttlow ||
1332 tp->t_rttlow > ticks - to.to_tsecr)
1333 tp->t_rttlow = ticks - to.to_tsecr;
1335 ticks - to.to_tsecr + 1);
1336 } else if (tp->t_rtttime &&
1337 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1338 if (!tp->t_rttlow ||
1339 tp->t_rttlow > ticks - tp->t_rtttime)
1340 tp->t_rttlow = ticks - tp->t_rtttime;
1342 ticks - tp->t_rtttime);
1344 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1345 acked = th->th_ack - tp->snd_una;
1346 TCPSTAT_INC(tcps_rcvackpack);
1347 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1348 sbdrop(&so->so_snd, acked);
1349 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1350 SEQ_LEQ(th->th_ack, tp->snd_recover))
1351 tp->snd_recover = th->th_ack - 1;
1352 tp->snd_una = th->th_ack;
1354 * Pull snd_wl2 up to prevent seq wrap relative
1357 tp->snd_wl2 = th->th_ack;
1360 ND6_HINT(tp); /* Some progress has been made. */
1363 * If all outstanding data are acked, stop
1364 * retransmit timer, otherwise restart timer
1365 * using current (possibly backed-off) value.
1366 * If process is waiting for space,
1367 * wakeup/selwakeup/signal. If data
1368 * are ready to send, let tcp_output
1369 * decide between more output or persist.
1372 if (so->so_options & SO_DEBUG)
1373 tcp_trace(TA_INPUT, ostate, tp,
1374 (void *)tcp_saveipgen,
1377 if (tp->snd_una == tp->snd_max)
1378 tcp_timer_activate(tp, TT_REXMT, 0);
1379 else if (!tcp_timer_active(tp, TT_PERSIST))
1380 tcp_timer_activate(tp, TT_REXMT,
1383 if (so->so_snd.sb_cc)
1384 (void) tcp_output(tp);
1387 } else if (th->th_ack == tp->snd_una &&
1388 tlen <= sbspace(&so->so_rcv)) {
1389 int newsize = 0; /* automatic sockbuf scaling */
1392 * This is a pure, in-sequence data packet with
1393 * nothing on the reassembly queue and we have enough
1394 * buffer space to take it.
1396 if (ti_locked == TI_RLOCKED)
1397 INP_INFO_RUNLOCK(&V_tcbinfo);
1398 else if (ti_locked == TI_WLOCKED)
1399 INP_INFO_WUNLOCK(&V_tcbinfo);
1401 panic("%s: ti_locked %d on pure data "
1402 "segment", __func__, ti_locked);
1403 ti_locked = TI_UNLOCKED;
1405 /* Clean receiver SACK report if present */
1406 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1407 tcp_clean_sackreport(tp);
1408 TCPSTAT_INC(tcps_preddat);
1409 tp->rcv_nxt += tlen;
1411 * Pull snd_wl1 up to prevent seq wrap relative to
1414 tp->snd_wl1 = th->th_seq;
1416 * Pull rcv_up up to prevent seq wrap relative to
1419 tp->rcv_up = tp->rcv_nxt;
1420 TCPSTAT_INC(tcps_rcvpack);
1421 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1422 ND6_HINT(tp); /* Some progress has been made */
1424 if (so->so_options & SO_DEBUG)
1425 tcp_trace(TA_INPUT, ostate, tp,
1426 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1429 * Automatic sizing of receive socket buffer. Often the send
1430 * buffer size is not optimally adjusted to the actual network
1431 * conditions at hand (delay bandwidth product). Setting the
1432 * buffer size too small limits throughput on links with high
1433 * bandwidth and high delay (eg. trans-continental/oceanic links).
1435 * On the receive side the socket buffer memory is only rarely
1436 * used to any significant extent. This allows us to be much
1437 * more aggressive in scaling the receive socket buffer. For
1438 * the case that the buffer space is actually used to a large
1439 * extent and we run out of kernel memory we can simply drop
1440 * the new segments; TCP on the sender will just retransmit it
1441 * later. Setting the buffer size too big may only consume too
1442 * much kernel memory if the application doesn't read() from
1443 * the socket or packet loss or reordering makes use of the
1446 * The criteria to step up the receive buffer one notch are:
1447 * 1. the number of bytes received during the time it takes
1448 * one timestamp to be reflected back to us (the RTT);
1449 * 2. received bytes per RTT is within seven eighth of the
1450 * current socket buffer size;
1451 * 3. receive buffer size has not hit maximal automatic size;
1453 * This algorithm does one step per RTT at most and only if
1454 * we receive a bulk stream w/o packet losses or reorderings.
1455 * Shrinking the buffer during idle times is not necessary as
1456 * it doesn't consume any memory when idle.
1458 * TODO: Only step up if the application is actually serving
1459 * the buffer to better manage the socket buffer resources.
1461 if (V_tcp_do_autorcvbuf &&
1463 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1464 if (to.to_tsecr > tp->rfbuf_ts &&
1465 to.to_tsecr - tp->rfbuf_ts < hz) {
1467 (so->so_rcv.sb_hiwat / 8 * 7) &&
1468 so->so_rcv.sb_hiwat <
1469 V_tcp_autorcvbuf_max) {
1471 min(so->so_rcv.sb_hiwat +
1472 V_tcp_autorcvbuf_inc,
1473 V_tcp_autorcvbuf_max);
1475 /* Start over with next RTT. */
1479 tp->rfbuf_cnt += tlen; /* add up */
1482 /* Add data to socket buffer. */
1483 SOCKBUF_LOCK(&so->so_rcv);
1484 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1488 * Set new socket buffer size.
1489 * Give up when limit is reached.
1492 if (!sbreserve_locked(&so->so_rcv,
1494 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1495 m_adj(m, drop_hdrlen); /* delayed header drop */
1496 sbappendstream_locked(&so->so_rcv, m);
1498 /* NB: sorwakeup_locked() does an implicit unlock. */
1499 sorwakeup_locked(so);
1500 if (DELAY_ACK(tp)) {
1501 tp->t_flags |= TF_DELACK;
1503 tp->t_flags |= TF_ACKNOW;
1511 * Calculate amount of space in receive window,
1512 * and then do TCP input processing.
1513 * Receive window is amount of space in rcv queue,
1514 * but not less than advertised window.
1516 win = sbspace(&so->so_rcv);
1519 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1521 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1525 switch (tp->t_state) {
1528 * If the state is SYN_RECEIVED:
1529 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1531 case TCPS_SYN_RECEIVED:
1532 if ((thflags & TH_ACK) &&
1533 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1534 SEQ_GT(th->th_ack, tp->snd_max))) {
1535 rstreason = BANDLIM_RST_OPENPORT;
1541 * If the state is SYN_SENT:
1542 * if seg contains an ACK, but not for our SYN, drop the input.
1543 * if seg contains a RST, then drop the connection.
1544 * if seg does not contain SYN, then drop it.
1545 * Otherwise this is an acceptable SYN segment
1546 * initialize tp->rcv_nxt and tp->irs
1547 * if seg contains ack then advance tp->snd_una
1548 * if seg contains an ECE and ECN support is enabled, the stream
1550 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1551 * arrange for segment to be acked (eventually)
1552 * continue processing rest of data/controls, beginning with URG
1555 if ((thflags & TH_ACK) &&
1556 (SEQ_LEQ(th->th_ack, tp->iss) ||
1557 SEQ_GT(th->th_ack, tp->snd_max))) {
1558 rstreason = BANDLIM_UNLIMITED;
1561 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1562 tp = tcp_drop(tp, ECONNREFUSED);
1563 if (thflags & TH_RST)
1565 if (!(thflags & TH_SYN))
1568 tp->irs = th->th_seq;
1570 if (thflags & TH_ACK) {
1571 TCPSTAT_INC(tcps_connects);
1574 mac_socketpeer_set_from_mbuf(m, so);
1576 /* Do window scaling on this connection? */
1577 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1578 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1579 tp->rcv_scale = tp->request_r_scale;
1581 tp->rcv_adv += tp->rcv_wnd;
1582 tp->snd_una++; /* SYN is acked */
1584 * If there's data, delay ACK; if there's also a FIN
1585 * ACKNOW will be turned on later.
1587 if (DELAY_ACK(tp) && tlen != 0)
1588 tcp_timer_activate(tp, TT_DELACK,
1591 tp->t_flags |= TF_ACKNOW;
1593 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1594 tp->t_flags |= TF_ECN_PERMIT;
1595 TCPSTAT_INC(tcps_ecn_shs);
1599 * Received <SYN,ACK> in SYN_SENT[*] state.
1601 * SYN_SENT --> ESTABLISHED
1602 * SYN_SENT* --> FIN_WAIT_1
1604 tp->t_starttime = ticks;
1605 if (tp->t_flags & TF_NEEDFIN) {
1606 tp->t_state = TCPS_FIN_WAIT_1;
1607 tp->t_flags &= ~TF_NEEDFIN;
1610 tp->t_state = TCPS_ESTABLISHED;
1611 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1615 * Received initial SYN in SYN-SENT[*] state =>
1616 * simultaneous open. If segment contains CC option
1617 * and there is a cached CC, apply TAO test.
1618 * If it succeeds, connection is * half-synchronized.
1619 * Otherwise, do 3-way handshake:
1620 * SYN-SENT -> SYN-RECEIVED
1621 * SYN-SENT* -> SYN-RECEIVED*
1622 * If there was no CC option, clear cached CC value.
1624 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1625 tcp_timer_activate(tp, TT_REXMT, 0);
1626 tp->t_state = TCPS_SYN_RECEIVED;
1629 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1630 "ti_locked %d", __func__, ti_locked));
1631 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1632 INP_WLOCK_ASSERT(tp->t_inpcb);
1635 * Advance th->th_seq to correspond to first data byte.
1636 * If data, trim to stay within window,
1637 * dropping FIN if necessary.
1640 if (tlen > tp->rcv_wnd) {
1641 todrop = tlen - tp->rcv_wnd;
1645 TCPSTAT_INC(tcps_rcvpackafterwin);
1646 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1648 tp->snd_wl1 = th->th_seq - 1;
1649 tp->rcv_up = th->th_seq;
1651 * Client side of transaction: already sent SYN and data.
1652 * If the remote host used T/TCP to validate the SYN,
1653 * our data will be ACK'd; if so, enter normal data segment
1654 * processing in the middle of step 5, ack processing.
1655 * Otherwise, goto step 6.
1657 if (thflags & TH_ACK)
1663 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1664 * do normal processing.
1666 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1670 break; /* continue normal processing */
1674 * States other than LISTEN or SYN_SENT.
1675 * First check the RST flag and sequence number since reset segments
1676 * are exempt from the timestamp and connection count tests. This
1677 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1678 * below which allowed reset segments in half the sequence space
1679 * to fall though and be processed (which gives forged reset
1680 * segments with a random sequence number a 50 percent chance of
1681 * killing a connection).
1682 * Then check timestamp, if present.
1683 * Then check the connection count, if present.
1684 * Then check that at least some bytes of segment are within
1685 * receive window. If segment begins before rcv_nxt,
1686 * drop leading data (and SYN); if nothing left, just ack.
1689 * If the RST bit is set, check the sequence number to see
1690 * if this is a valid reset segment.
1692 * In all states except SYN-SENT, all reset (RST) segments
1693 * are validated by checking their SEQ-fields. A reset is
1694 * valid if its sequence number is in the window.
1695 * Note: this does not take into account delayed ACKs, so
1696 * we should test against last_ack_sent instead of rcv_nxt.
1697 * The sequence number in the reset segment is normally an
1698 * echo of our outgoing acknowlegement numbers, but some hosts
1699 * send a reset with the sequence number at the rightmost edge
1700 * of our receive window, and we have to handle this case.
1701 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1702 * that brute force RST attacks are possible. To combat this,
1703 * we use a much stricter check while in the ESTABLISHED state,
1704 * only accepting RSTs where the sequence number is equal to
1705 * last_ack_sent. In all other states (the states in which a
1706 * RST is more likely), the more permissive check is used.
1707 * If we have multiple segments in flight, the initial reset
1708 * segment sequence numbers will be to the left of last_ack_sent,
1709 * but they will eventually catch up.
1710 * In any case, it never made sense to trim reset segments to
1711 * fit the receive window since RFC 1122 says:
1712 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1714 * A TCP SHOULD allow a received RST segment to include data.
1717 * It has been suggested that a RST segment could contain
1718 * ASCII text that encoded and explained the cause of the
1719 * RST. No standard has yet been established for such
1722 * If the reset segment passes the sequence number test examine
1724 * SYN_RECEIVED STATE:
1725 * If passive open, return to LISTEN state.
1726 * If active open, inform user that connection was refused.
1727 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1728 * Inform user that connection was reset, and close tcb.
1729 * CLOSING, LAST_ACK STATES:
1732 * Drop the segment - see Stevens, vol. 2, p. 964 and
1735 if (thflags & TH_RST) {
1736 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1737 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1738 switch (tp->t_state) {
1740 case TCPS_SYN_RECEIVED:
1741 so->so_error = ECONNREFUSED;
1744 case TCPS_ESTABLISHED:
1745 if (V_tcp_insecure_rst == 0 &&
1746 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1747 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1748 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1749 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1750 TCPSTAT_INC(tcps_badrst);
1754 case TCPS_FIN_WAIT_1:
1755 case TCPS_FIN_WAIT_2:
1756 case TCPS_CLOSE_WAIT:
1757 so->so_error = ECONNRESET;
1759 KASSERT(ti_locked == TI_WLOCKED,
1760 ("tcp_do_segment: TH_RST 1 ti_locked %d",
1762 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1764 tp->t_state = TCPS_CLOSED;
1765 TCPSTAT_INC(tcps_drops);
1771 KASSERT(ti_locked == TI_WLOCKED,
1772 ("tcp_do_segment: TH_RST 2 ti_locked %d",
1774 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1784 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1785 * and it's less than ts_recent, drop it.
1787 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1788 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1790 /* Check to see if ts_recent is over 24 days old. */
1791 if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
1793 * Invalidate ts_recent. If this segment updates
1794 * ts_recent, the age will be reset later and ts_recent
1795 * will get a valid value. If it does not, setting
1796 * ts_recent to zero will at least satisfy the
1797 * requirement that zero be placed in the timestamp
1798 * echo reply when ts_recent isn't valid. The
1799 * age isn't reset until we get a valid ts_recent
1800 * because we don't want out-of-order segments to be
1801 * dropped when ts_recent is old.
1805 TCPSTAT_INC(tcps_rcvduppack);
1806 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1807 TCPSTAT_INC(tcps_pawsdrop);
1815 * In the SYN-RECEIVED state, validate that the packet belongs to
1816 * this connection before trimming the data to fit the receive
1817 * window. Check the sequence number versus IRS since we know
1818 * the sequence numbers haven't wrapped. This is a partial fix
1819 * for the "LAND" DoS attack.
1821 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1822 rstreason = BANDLIM_RST_OPENPORT;
1826 todrop = tp->rcv_nxt - th->th_seq;
1829 * If this is a duplicate SYN for our current connection,
1830 * advance over it and pretend and it's not a SYN.
1832 if (thflags & TH_SYN && th->th_seq == tp->irs) {
1842 * Following if statement from Stevens, vol. 2, p. 960.
1845 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1847 * Any valid FIN must be to the left of the window.
1848 * At this point the FIN must be a duplicate or out
1849 * of sequence; drop it.
1854 * Send an ACK to resynchronize and drop any data.
1855 * But keep on processing for RST or ACK.
1857 tp->t_flags |= TF_ACKNOW;
1859 TCPSTAT_INC(tcps_rcvduppack);
1860 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1862 TCPSTAT_INC(tcps_rcvpartduppack);
1863 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1865 drop_hdrlen += todrop; /* drop from the top afterwards */
1866 th->th_seq += todrop;
1868 if (th->th_urp > todrop)
1869 th->th_urp -= todrop;
1877 * If new data are received on a connection after the
1878 * user processes are gone, then RST the other end.
1880 if ((so->so_state & SS_NOFDREF) &&
1881 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1884 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
1885 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
1886 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1888 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1889 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
1890 "was closed, sending RST and removing tcpcb\n",
1891 s, __func__, tcpstates[tp->t_state], tlen);
1895 TCPSTAT_INC(tcps_rcvafterclose);
1896 rstreason = BANDLIM_UNLIMITED;
1901 * If segment ends after window, drop trailing data
1902 * (and PUSH and FIN); if nothing left, just ACK.
1904 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1906 TCPSTAT_INC(tcps_rcvpackafterwin);
1907 if (todrop >= tlen) {
1908 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1910 * If window is closed can only take segments at
1911 * window edge, and have to drop data and PUSH from
1912 * incoming segments. Continue processing, but
1913 * remember to ack. Otherwise, drop segment
1916 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1917 tp->t_flags |= TF_ACKNOW;
1918 TCPSTAT_INC(tcps_rcvwinprobe);
1922 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1925 thflags &= ~(TH_PUSH|TH_FIN);
1929 * If last ACK falls within this segment's sequence numbers,
1930 * record its timestamp.
1932 * 1) That the test incorporates suggestions from the latest
1933 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1934 * 2) That updating only on newer timestamps interferes with
1935 * our earlier PAWS tests, so this check should be solely
1936 * predicated on the sequence space of this segment.
1937 * 3) That we modify the segment boundary check to be
1938 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1939 * instead of RFC1323's
1940 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1941 * This modified check allows us to overcome RFC1323's
1942 * limitations as described in Stevens TCP/IP Illustrated
1943 * Vol. 2 p.869. In such cases, we can still calculate the
1944 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1946 if ((to.to_flags & TOF_TS) != 0 &&
1947 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1948 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1949 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1950 tp->ts_recent_age = ticks;
1951 tp->ts_recent = to.to_tsval;
1955 * If a SYN is in the window, then this is an
1956 * error and we send an RST and drop the connection.
1958 if (thflags & TH_SYN) {
1959 KASSERT(ti_locked == TI_WLOCKED,
1960 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
1961 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1963 tp = tcp_drop(tp, ECONNRESET);
1964 rstreason = BANDLIM_UNLIMITED;
1969 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1970 * flag is on (half-synchronized state), then queue data for
1971 * later processing; else drop segment and return.
1973 if ((thflags & TH_ACK) == 0) {
1974 if (tp->t_state == TCPS_SYN_RECEIVED ||
1975 (tp->t_flags & TF_NEEDSYN))
1977 else if (tp->t_flags & TF_ACKNOW)
1986 switch (tp->t_state) {
1989 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1990 * ESTABLISHED state and continue processing.
1991 * The ACK was checked above.
1993 case TCPS_SYN_RECEIVED:
1995 TCPSTAT_INC(tcps_connects);
1997 /* Do window scaling? */
1998 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1999 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2000 tp->rcv_scale = tp->request_r_scale;
2001 tp->snd_wnd = tiwin;
2005 * SYN-RECEIVED -> ESTABLISHED
2006 * SYN-RECEIVED* -> FIN-WAIT-1
2008 tp->t_starttime = ticks;
2009 if (tp->t_flags & TF_NEEDFIN) {
2010 tp->t_state = TCPS_FIN_WAIT_1;
2011 tp->t_flags &= ~TF_NEEDFIN;
2013 tp->t_state = TCPS_ESTABLISHED;
2014 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
2017 * If segment contains data or ACK, will call tcp_reass()
2018 * later; if not, do so now to pass queued data to user.
2020 if (tlen == 0 && (thflags & TH_FIN) == 0)
2021 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2023 tp->snd_wl1 = th->th_seq - 1;
2027 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2028 * ACKs. If the ack is in the range
2029 * tp->snd_una < th->th_ack <= tp->snd_max
2030 * then advance tp->snd_una to th->th_ack and drop
2031 * data from the retransmission queue. If this ACK reflects
2032 * more up to date window information we update our window information.
2034 case TCPS_ESTABLISHED:
2035 case TCPS_FIN_WAIT_1:
2036 case TCPS_FIN_WAIT_2:
2037 case TCPS_CLOSE_WAIT:
2040 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2041 TCPSTAT_INC(tcps_rcvacktoomuch);
2044 if ((tp->t_flags & TF_SACK_PERMIT) &&
2045 ((to.to_flags & TOF_SACK) ||
2046 !TAILQ_EMPTY(&tp->snd_holes)))
2047 tcp_sack_doack(tp, &to, th->th_ack);
2048 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2049 if (tlen == 0 && tiwin == tp->snd_wnd) {
2050 TCPSTAT_INC(tcps_rcvdupack);
2052 * If we have outstanding data (other than
2053 * a window probe), this is a completely
2054 * duplicate ack (ie, window info didn't
2055 * change), the ack is the biggest we've
2056 * seen and we've seen exactly our rexmt
2057 * threshhold of them, assume a packet
2058 * has been dropped and retransmit it.
2059 * Kludge snd_nxt & the congestion
2060 * window so we send only this one
2063 * We know we're losing at the current
2064 * window size so do congestion avoidance
2065 * (set ssthresh to half the current window
2066 * and pull our congestion window back to
2067 * the new ssthresh).
2069 * Dup acks mean that packets have left the
2070 * network (they're now cached at the receiver)
2071 * so bump cwnd by the amount in the receiver
2072 * to keep a constant cwnd packets in the
2075 * When using TCP ECN, notify the peer that
2076 * we reduced the cwnd.
2078 if (!tcp_timer_active(tp, TT_REXMT) ||
2079 th->th_ack != tp->snd_una)
2081 else if (++tp->t_dupacks > tcprexmtthresh ||
2082 ((V_tcp_do_newreno ||
2083 (tp->t_flags & TF_SACK_PERMIT)) &&
2084 IN_FASTRECOVERY(tp))) {
2085 if ((tp->t_flags & TF_SACK_PERMIT) &&
2086 IN_FASTRECOVERY(tp)) {
2090 * Compute the amount of data in flight first.
2091 * We can inject new data into the pipe iff
2092 * we have less than 1/2 the original window's
2093 * worth of data in flight.
2095 awnd = (tp->snd_nxt - tp->snd_fack) +
2096 tp->sackhint.sack_bytes_rexmit;
2097 if (awnd < tp->snd_ssthresh) {
2098 tp->snd_cwnd += tp->t_maxseg;
2099 if (tp->snd_cwnd > tp->snd_ssthresh)
2100 tp->snd_cwnd = tp->snd_ssthresh;
2103 tp->snd_cwnd += tp->t_maxseg;
2104 (void) tcp_output(tp);
2106 } else if (tp->t_dupacks == tcprexmtthresh) {
2107 tcp_seq onxt = tp->snd_nxt;
2110 * If we're doing sack, check to
2111 * see if we're already in sack
2112 * recovery. If we're not doing sack,
2113 * check to see if we're in newreno
2116 if (tp->t_flags & TF_SACK_PERMIT) {
2117 if (IN_FASTRECOVERY(tp)) {
2121 } else if (V_tcp_do_newreno ||
2123 if (SEQ_LEQ(th->th_ack,
2129 tcp_congestion_exp(tp);
2130 tcp_timer_activate(tp, TT_REXMT, 0);
2132 if (tp->t_flags & TF_SACK_PERMIT) {
2134 tcps_sack_recovery_episode);
2135 tp->sack_newdata = tp->snd_nxt;
2136 tp->snd_cwnd = tp->t_maxseg;
2137 (void) tcp_output(tp);
2140 tp->snd_nxt = th->th_ack;
2141 tp->snd_cwnd = tp->t_maxseg;
2142 (void) tcp_output(tp);
2143 KASSERT(tp->snd_limited <= 2,
2144 ("%s: tp->snd_limited too big",
2146 tp->snd_cwnd = tp->snd_ssthresh +
2148 (tp->t_dupacks - tp->snd_limited);
2149 if (SEQ_GT(onxt, tp->snd_nxt))
2152 } else if (V_tcp_do_rfc3042) {
2153 u_long oldcwnd = tp->snd_cwnd;
2154 tcp_seq oldsndmax = tp->snd_max;
2157 KASSERT(tp->t_dupacks == 1 ||
2159 ("%s: dupacks not 1 or 2",
2161 if (tp->t_dupacks == 1)
2162 tp->snd_limited = 0;
2164 (tp->snd_nxt - tp->snd_una) +
2165 (tp->t_dupacks - tp->snd_limited) *
2167 (void) tcp_output(tp);
2168 sent = tp->snd_max - oldsndmax;
2169 if (sent > tp->t_maxseg) {
2170 KASSERT((tp->t_dupacks == 2 &&
2171 tp->snd_limited == 0) ||
2172 (sent == tp->t_maxseg + 1 &&
2173 tp->t_flags & TF_SENTFIN),
2174 ("%s: sent too much",
2176 tp->snd_limited = 2;
2177 } else if (sent > 0)
2179 tp->snd_cwnd = oldcwnd;
2187 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2188 ("%s: th_ack <= snd_una", __func__));
2191 * If the congestion window was inflated to account
2192 * for the other side's cached packets, retract it.
2194 if (V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
2195 if (IN_FASTRECOVERY(tp)) {
2196 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2197 if (tp->t_flags & TF_SACK_PERMIT)
2198 tcp_sack_partialack(tp, th);
2200 tcp_newreno_partial_ack(tp, th);
2203 * Out of fast recovery.
2204 * Window inflation should have left us
2205 * with approximately snd_ssthresh
2207 * But in case we would be inclined to
2208 * send a burst, better to do it via
2209 * the slow start mechanism.
2211 if (SEQ_GT(th->th_ack +
2214 tp->snd_cwnd = tp->snd_max -
2218 tp->snd_cwnd = tp->snd_ssthresh;
2222 if (tp->t_dupacks >= tcprexmtthresh &&
2223 tp->snd_cwnd > tp->snd_ssthresh)
2224 tp->snd_cwnd = tp->snd_ssthresh;
2228 * If we reach this point, ACK is not a duplicate,
2229 * i.e., it ACKs something we sent.
2231 if (tp->t_flags & TF_NEEDSYN) {
2233 * T/TCP: Connection was half-synchronized, and our
2234 * SYN has been ACK'd (so connection is now fully
2235 * synchronized). Go to non-starred state,
2236 * increment snd_una for ACK of SYN, and check if
2237 * we can do window scaling.
2239 tp->t_flags &= ~TF_NEEDSYN;
2241 /* Do window scaling? */
2242 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2243 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2244 tp->rcv_scale = tp->request_r_scale;
2245 /* Send window already scaled. */
2250 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2251 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2252 ("tcp_input: process_ACK ti_locked %d", ti_locked));
2253 INP_WLOCK_ASSERT(tp->t_inpcb);
2255 acked = th->th_ack - tp->snd_una;
2256 TCPSTAT_INC(tcps_rcvackpack);
2257 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2260 * If we just performed our first retransmit, and the ACK
2261 * arrives within our recovery window, then it was a mistake
2262 * to do the retransmit in the first place. Recover our
2263 * original cwnd and ssthresh, and proceed to transmit where
2266 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0) {
2267 TCPSTAT_INC(tcps_sndrexmitbad);
2268 tp->snd_cwnd = tp->snd_cwnd_prev;
2269 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2270 tp->snd_recover = tp->snd_recover_prev;
2271 if (tp->t_flags & TF_WASFRECOVERY)
2272 ENTER_FASTRECOVERY(tp);
2273 tp->snd_nxt = tp->snd_max;
2274 tp->t_badrxtwin = 0; /* XXX probably not required */
2278 * If we have a timestamp reply, update smoothed
2279 * round trip time. If no timestamp is present but
2280 * transmit timer is running and timed sequence
2281 * number was acked, update smoothed round trip time.
2282 * Since we now have an rtt measurement, cancel the
2283 * timer backoff (cf., Phil Karn's retransmit alg.).
2284 * Recompute the initial retransmit timer.
2286 * Some boxes send broken timestamp replies
2287 * during the SYN+ACK phase, ignore
2288 * timestamps of 0 or we could calculate a
2289 * huge RTT and blow up the retransmit timer.
2291 if ((to.to_flags & TOF_TS) != 0 &&
2293 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2294 tp->t_rttlow = ticks - to.to_tsecr;
2295 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2296 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2297 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2298 tp->t_rttlow = ticks - tp->t_rtttime;
2299 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2301 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2304 * If all outstanding data is acked, stop retransmit
2305 * timer and remember to restart (more output or persist).
2306 * If there is more data to be acked, restart retransmit
2307 * timer, using current (possibly backed-off) value.
2309 if (th->th_ack == tp->snd_max) {
2310 tcp_timer_activate(tp, TT_REXMT, 0);
2312 } else if (!tcp_timer_active(tp, TT_PERSIST))
2313 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2316 * If no data (only SYN) was ACK'd,
2317 * skip rest of ACK processing.
2323 * When new data is acked, open the congestion window.
2324 * Method depends on which congestion control state we're
2325 * in (slow start or cong avoid) and if ABC (RFC 3465) is
2328 * slow start: cwnd <= ssthresh
2329 * cong avoid: cwnd > ssthresh
2331 * slow start and ABC (RFC 3465):
2332 * Grow cwnd exponentially by the amount of data
2333 * ACKed capping the max increment per ACK to
2334 * (abc_l_var * maxseg) bytes.
2336 * slow start without ABC (RFC 2581):
2337 * Grow cwnd exponentially by maxseg per ACK.
2339 * cong avoid and ABC (RFC 3465):
2340 * Grow cwnd linearly by maxseg per RTT for each
2341 * cwnd worth of ACKed data.
2343 * cong avoid without ABC (RFC 2581):
2344 * Grow cwnd linearly by approximately maxseg per RTT using
2345 * maxseg^2 / cwnd per ACK as the increment.
2346 * If cwnd > maxseg^2, fix the cwnd increment at 1 byte to
2347 * avoid capping cwnd.
2349 if ((!V_tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2350 !IN_FASTRECOVERY(tp)) {
2351 u_int cw = tp->snd_cwnd;
2352 u_int incr = tp->t_maxseg;
2353 /* In congestion avoidance? */
2354 if (cw > tp->snd_ssthresh) {
2355 if (V_tcp_do_rfc3465) {
2356 tp->t_bytes_acked += acked;
2357 if (tp->t_bytes_acked >= tp->snd_cwnd)
2358 tp->t_bytes_acked -= cw;
2363 incr = max((incr * incr / cw), 1);
2365 * In slow-start with ABC enabled and no RTO in sight?
2366 * (Must not use abc_l_var > 1 if slow starting after an
2367 * RTO. On RTO, snd_nxt = snd_una, so the snd_nxt ==
2368 * snd_max check is sufficient to handle this).
2370 } else if (V_tcp_do_rfc3465 &&
2371 tp->snd_nxt == tp->snd_max)
2373 V_tcp_abc_l_var * tp->t_maxseg);
2374 /* ABC is on by default, so (incr == 0) frequently. */
2376 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2378 SOCKBUF_LOCK(&so->so_snd);
2379 if (acked > so->so_snd.sb_cc) {
2380 tp->snd_wnd -= so->so_snd.sb_cc;
2381 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2384 sbdrop_locked(&so->so_snd, acked);
2385 tp->snd_wnd -= acked;
2388 /* NB: sowwakeup_locked() does an implicit unlock. */
2389 sowwakeup_locked(so);
2390 /* Detect una wraparound. */
2391 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2392 !IN_FASTRECOVERY(tp) &&
2393 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2394 SEQ_LEQ(th->th_ack, tp->snd_recover))
2395 tp->snd_recover = th->th_ack - 1;
2396 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2397 IN_FASTRECOVERY(tp) &&
2398 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2399 EXIT_FASTRECOVERY(tp);
2400 tp->t_bytes_acked = 0;
2402 tp->snd_una = th->th_ack;
2403 if (tp->t_flags & TF_SACK_PERMIT) {
2404 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2405 tp->snd_recover = tp->snd_una;
2407 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2408 tp->snd_nxt = tp->snd_una;
2410 switch (tp->t_state) {
2413 * In FIN_WAIT_1 STATE in addition to the processing
2414 * for the ESTABLISHED state if our FIN is now acknowledged
2415 * then enter FIN_WAIT_2.
2417 case TCPS_FIN_WAIT_1:
2418 if (ourfinisacked) {
2420 * If we can't receive any more
2421 * data, then closing user can proceed.
2422 * Starting the timer is contrary to the
2423 * specification, but if we don't get a FIN
2424 * we'll hang forever.
2427 * we should release the tp also, and use a
2430 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2433 soisdisconnected(so);
2434 timeout = (tcp_fast_finwait2_recycle) ?
2435 tcp_finwait2_timeout : tcp_maxidle;
2436 tcp_timer_activate(tp, TT_2MSL, timeout);
2438 tp->t_state = TCPS_FIN_WAIT_2;
2443 * In CLOSING STATE in addition to the processing for
2444 * the ESTABLISHED state if the ACK acknowledges our FIN
2445 * then enter the TIME-WAIT state, otherwise ignore
2449 if (ourfinisacked) {
2450 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2452 INP_INFO_WUNLOCK(&V_tcbinfo);
2459 * In LAST_ACK, we may still be waiting for data to drain
2460 * and/or to be acked, as well as for the ack of our FIN.
2461 * If our FIN is now acknowledged, delete the TCB,
2462 * enter the closed state and return.
2465 if (ourfinisacked) {
2466 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2475 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2476 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2477 ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2478 INP_WLOCK_ASSERT(tp->t_inpcb);
2481 * Update window information.
2482 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2484 if ((thflags & TH_ACK) &&
2485 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2486 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2487 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2488 /* keep track of pure window updates */
2490 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2491 TCPSTAT_INC(tcps_rcvwinupd);
2492 tp->snd_wnd = tiwin;
2493 tp->snd_wl1 = th->th_seq;
2494 tp->snd_wl2 = th->th_ack;
2495 if (tp->snd_wnd > tp->max_sndwnd)
2496 tp->max_sndwnd = tp->snd_wnd;
2501 * Process segments with URG.
2503 if ((thflags & TH_URG) && th->th_urp &&
2504 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2506 * This is a kludge, but if we receive and accept
2507 * random urgent pointers, we'll crash in
2508 * soreceive. It's hard to imagine someone
2509 * actually wanting to send this much urgent data.
2511 SOCKBUF_LOCK(&so->so_rcv);
2512 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2513 th->th_urp = 0; /* XXX */
2514 thflags &= ~TH_URG; /* XXX */
2515 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2516 goto dodata; /* XXX */
2519 * If this segment advances the known urgent pointer,
2520 * then mark the data stream. This should not happen
2521 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2522 * a FIN has been received from the remote side.
2523 * In these states we ignore the URG.
2525 * According to RFC961 (Assigned Protocols),
2526 * the urgent pointer points to the last octet
2527 * of urgent data. We continue, however,
2528 * to consider it to indicate the first octet
2529 * of data past the urgent section as the original
2530 * spec states (in one of two places).
2532 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2533 tp->rcv_up = th->th_seq + th->th_urp;
2534 so->so_oobmark = so->so_rcv.sb_cc +
2535 (tp->rcv_up - tp->rcv_nxt) - 1;
2536 if (so->so_oobmark == 0)
2537 so->so_rcv.sb_state |= SBS_RCVATMARK;
2539 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2541 SOCKBUF_UNLOCK(&so->so_rcv);
2543 * Remove out of band data so doesn't get presented to user.
2544 * This can happen independent of advancing the URG pointer,
2545 * but if two URG's are pending at once, some out-of-band
2546 * data may creep in... ick.
2548 if (th->th_urp <= (u_long)tlen &&
2549 !(so->so_options & SO_OOBINLINE)) {
2550 /* hdr drop is delayed */
2551 tcp_pulloutofband(so, th, m, drop_hdrlen);
2555 * If no out of band data is expected,
2556 * pull receive urgent pointer along
2557 * with the receive window.
2559 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2560 tp->rcv_up = tp->rcv_nxt;
2563 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2564 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2565 ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2566 INP_WLOCK_ASSERT(tp->t_inpcb);
2569 * Process the segment text, merging it into the TCP sequencing queue,
2570 * and arranging for acknowledgment of receipt if necessary.
2571 * This process logically involves adjusting tp->rcv_wnd as data
2572 * is presented to the user (this happens in tcp_usrreq.c,
2573 * case PRU_RCVD). If a FIN has already been received on this
2574 * connection then we just ignore the text.
2576 if ((tlen || (thflags & TH_FIN)) &&
2577 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2578 tcp_seq save_start = th->th_seq;
2579 m_adj(m, drop_hdrlen); /* delayed header drop */
2581 * Insert segment which includes th into TCP reassembly queue
2582 * with control block tp. Set thflags to whether reassembly now
2583 * includes a segment with FIN. This handles the common case
2584 * inline (segment is the next to be received on an established
2585 * connection, and the queue is empty), avoiding linkage into
2586 * and removal from the queue and repetition of various
2588 * Set DELACK for segments received in order, but ack
2589 * immediately when segments are out of order (so
2590 * fast retransmit can work).
2592 if (th->th_seq == tp->rcv_nxt &&
2593 LIST_EMPTY(&tp->t_segq) &&
2594 TCPS_HAVEESTABLISHED(tp->t_state)) {
2596 tp->t_flags |= TF_DELACK;
2598 tp->t_flags |= TF_ACKNOW;
2599 tp->rcv_nxt += tlen;
2600 thflags = th->th_flags & TH_FIN;
2601 TCPSTAT_INC(tcps_rcvpack);
2602 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2604 SOCKBUF_LOCK(&so->so_rcv);
2605 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2608 sbappendstream_locked(&so->so_rcv, m);
2609 /* NB: sorwakeup_locked() does an implicit unlock. */
2610 sorwakeup_locked(so);
2613 * XXX: Due to the header drop above "th" is
2614 * theoretically invalid by now. Fortunately
2615 * m_adj() doesn't actually frees any mbufs
2616 * when trimming from the head.
2618 thflags = tcp_reass(tp, th, &tlen, m);
2619 tp->t_flags |= TF_ACKNOW;
2621 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2622 tcp_update_sack_list(tp, save_start, save_start + tlen);
2625 * Note the amount of data that peer has sent into
2626 * our window, in order to estimate the sender's
2630 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2638 * If FIN is received ACK the FIN and let the user know
2639 * that the connection is closing.
2641 if (thflags & TH_FIN) {
2642 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2645 * If connection is half-synchronized
2646 * (ie NEEDSYN flag on) then delay ACK,
2647 * so it may be piggybacked when SYN is sent.
2648 * Otherwise, since we received a FIN then no
2649 * more input can be expected, send ACK now.
2651 if (tp->t_flags & TF_NEEDSYN)
2652 tp->t_flags |= TF_DELACK;
2654 tp->t_flags |= TF_ACKNOW;
2657 switch (tp->t_state) {
2660 * In SYN_RECEIVED and ESTABLISHED STATES
2661 * enter the CLOSE_WAIT state.
2663 case TCPS_SYN_RECEIVED:
2664 tp->t_starttime = ticks;
2666 case TCPS_ESTABLISHED:
2667 tp->t_state = TCPS_CLOSE_WAIT;
2671 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2672 * enter the CLOSING state.
2674 case TCPS_FIN_WAIT_1:
2675 tp->t_state = TCPS_CLOSING;
2679 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2680 * starting the time-wait timer, turning off the other
2683 case TCPS_FIN_WAIT_2:
2684 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2685 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2686 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2690 INP_INFO_WUNLOCK(&V_tcbinfo);
2694 if (ti_locked == TI_RLOCKED)
2695 INP_INFO_RUNLOCK(&V_tcbinfo);
2696 else if (ti_locked == TI_WLOCKED)
2697 INP_INFO_WUNLOCK(&V_tcbinfo);
2699 panic("%s: dodata epilogue ti_locked %d", __func__,
2701 ti_locked = TI_UNLOCKED;
2704 if (so->so_options & SO_DEBUG)
2705 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2710 * Return any desired output.
2712 if (needoutput || (tp->t_flags & TF_ACKNOW))
2713 (void) tcp_output(tp);
2716 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2717 __func__, ti_locked));
2718 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2719 INP_WLOCK_ASSERT(tp->t_inpcb);
2721 if (tp->t_flags & TF_DELACK) {
2722 tp->t_flags &= ~TF_DELACK;
2723 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2725 INP_WUNLOCK(tp->t_inpcb);
2729 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2730 ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2733 * Generate an ACK dropping incoming segment if it occupies
2734 * sequence space, where the ACK reflects our state.
2736 * We can now skip the test for the RST flag since all
2737 * paths to this code happen after packets containing
2738 * RST have been dropped.
2740 * In the SYN-RECEIVED state, don't send an ACK unless the
2741 * segment we received passes the SYN-RECEIVED ACK test.
2742 * If it fails send a RST. This breaks the loop in the
2743 * "LAND" DoS attack, and also prevents an ACK storm
2744 * between two listening ports that have been sent forged
2745 * SYN segments, each with the source address of the other.
2747 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2748 (SEQ_GT(tp->snd_una, th->th_ack) ||
2749 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2750 rstreason = BANDLIM_RST_OPENPORT;
2754 if (so->so_options & SO_DEBUG)
2755 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2758 if (ti_locked == TI_RLOCKED)
2759 INP_INFO_RUNLOCK(&V_tcbinfo);
2760 else if (ti_locked == TI_WLOCKED)
2761 INP_INFO_WUNLOCK(&V_tcbinfo);
2763 panic("%s: dropafterack epilogue ti_locked %d", __func__,
2765 ti_locked = TI_UNLOCKED;
2767 tp->t_flags |= TF_ACKNOW;
2768 (void) tcp_output(tp);
2769 INP_WUNLOCK(tp->t_inpcb);
2774 if (ti_locked == TI_RLOCKED)
2775 INP_INFO_RUNLOCK(&V_tcbinfo);
2776 else if (ti_locked == TI_WLOCKED)
2777 INP_INFO_WUNLOCK(&V_tcbinfo);
2779 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2780 ti_locked = TI_UNLOCKED;
2783 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2784 INP_WUNLOCK(tp->t_inpcb);
2786 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2790 if (ti_locked == TI_RLOCKED)
2791 INP_INFO_RUNLOCK(&V_tcbinfo);
2792 else if (ti_locked == TI_WLOCKED)
2793 INP_INFO_WUNLOCK(&V_tcbinfo);
2796 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2798 ti_locked = TI_UNLOCKED;
2801 * Drop space held by incoming segment and return.
2804 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2805 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2809 INP_WUNLOCK(tp->t_inpcb);
2814 * Issue RST and make ACK acceptable to originator of segment.
2815 * The mbuf must still include the original packet header.
2819 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2820 int tlen, int rstreason)
2824 struct ip6_hdr *ip6;
2828 INP_WLOCK_ASSERT(tp->t_inpcb);
2831 /* Don't bother if destination was broadcast/multicast. */
2832 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2835 if (mtod(m, struct ip *)->ip_v == 6) {
2836 ip6 = mtod(m, struct ip6_hdr *);
2837 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2838 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2840 /* IPv6 anycast check is done at tcp6_input() */
2844 ip = mtod(m, struct ip *);
2845 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2846 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2847 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2848 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2852 /* Perform bandwidth limiting. */
2853 if (badport_bandlim(rstreason) < 0)
2856 /* tcp_respond consumes the mbuf chain. */
2857 if (th->th_flags & TH_ACK) {
2858 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2859 th->th_ack, TH_RST);
2861 if (th->th_flags & TH_SYN)
2863 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2864 (tcp_seq)0, TH_RST|TH_ACK);
2872 * Parse TCP options and place in tcpopt.
2875 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2880 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2882 if (opt == TCPOPT_EOL)
2884 if (opt == TCPOPT_NOP)
2890 if (optlen < 2 || optlen > cnt)
2895 if (optlen != TCPOLEN_MAXSEG)
2897 if (!(flags & TO_SYN))
2899 to->to_flags |= TOF_MSS;
2900 bcopy((char *)cp + 2,
2901 (char *)&to->to_mss, sizeof(to->to_mss));
2902 to->to_mss = ntohs(to->to_mss);
2905 if (optlen != TCPOLEN_WINDOW)
2907 if (!(flags & TO_SYN))
2909 to->to_flags |= TOF_SCALE;
2910 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2912 case TCPOPT_TIMESTAMP:
2913 if (optlen != TCPOLEN_TIMESTAMP)
2915 to->to_flags |= TOF_TS;
2916 bcopy((char *)cp + 2,
2917 (char *)&to->to_tsval, sizeof(to->to_tsval));
2918 to->to_tsval = ntohl(to->to_tsval);
2919 bcopy((char *)cp + 6,
2920 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2921 to->to_tsecr = ntohl(to->to_tsecr);
2923 #ifdef TCP_SIGNATURE
2925 * XXX In order to reply to a host which has set the
2926 * TCP_SIGNATURE option in its initial SYN, we have to
2927 * record the fact that the option was observed here
2928 * for the syncache code to perform the correct response.
2930 case TCPOPT_SIGNATURE:
2931 if (optlen != TCPOLEN_SIGNATURE)
2933 to->to_flags |= TOF_SIGNATURE;
2934 to->to_signature = cp + 2;
2937 case TCPOPT_SACK_PERMITTED:
2938 if (optlen != TCPOLEN_SACK_PERMITTED)
2940 if (!(flags & TO_SYN))
2944 to->to_flags |= TOF_SACKPERM;
2947 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2951 to->to_flags |= TOF_SACK;
2952 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2953 to->to_sacks = cp + 2;
2954 TCPSTAT_INC(tcps_sack_rcv_blocks);
2963 * Pull out of band byte out of a segment so
2964 * it doesn't appear in the user's data queue.
2965 * It is still reflected in the segment length for
2966 * sequencing purposes.
2969 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2972 int cnt = off + th->th_urp - 1;
2975 if (m->m_len > cnt) {
2976 char *cp = mtod(m, caddr_t) + cnt;
2977 struct tcpcb *tp = sototcpcb(so);
2979 INP_WLOCK_ASSERT(tp->t_inpcb);
2982 tp->t_oobflags |= TCPOOB_HAVEDATA;
2983 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2985 if (m->m_flags & M_PKTHDR)
2994 panic("tcp_pulloutofband");
2998 * Collect new round-trip time estimate
2999 * and update averages and current timeout.
3002 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3006 INP_WLOCK_ASSERT(tp->t_inpcb);
3008 TCPSTAT_INC(tcps_rttupdated);
3010 if (tp->t_srtt != 0) {
3012 * srtt is stored as fixed point with 5 bits after the
3013 * binary point (i.e., scaled by 8). The following magic
3014 * is equivalent to the smoothing algorithm in rfc793 with
3015 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3016 * point). Adjust rtt to origin 0.
3018 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3019 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3021 if ((tp->t_srtt += delta) <= 0)
3025 * We accumulate a smoothed rtt variance (actually, a
3026 * smoothed mean difference), then set the retransmit
3027 * timer to smoothed rtt + 4 times the smoothed variance.
3028 * rttvar is stored as fixed point with 4 bits after the
3029 * binary point (scaled by 16). The following is
3030 * equivalent to rfc793 smoothing with an alpha of .75
3031 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3032 * rfc793's wired-in beta.
3036 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3037 if ((tp->t_rttvar += delta) <= 0)
3039 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3040 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3043 * No rtt measurement yet - use the unsmoothed rtt.
3044 * Set the variance to half the rtt (so our first
3045 * retransmit happens at 3*rtt).
3047 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3048 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3049 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3055 * the retransmit should happen at rtt + 4 * rttvar.
3056 * Because of the way we do the smoothing, srtt and rttvar
3057 * will each average +1/2 tick of bias. When we compute
3058 * the retransmit timer, we want 1/2 tick of rounding and
3059 * 1 extra tick because of +-1/2 tick uncertainty in the
3060 * firing of the timer. The bias will give us exactly the
3061 * 1.5 tick we need. But, because the bias is
3062 * statistical, we have to test that we don't drop below
3063 * the minimum feasible timer (which is 2 ticks).
3065 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3066 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3069 * We received an ack for a packet that wasn't retransmitted;
3070 * it is probably safe to discard any error indications we've
3071 * received recently. This isn't quite right, but close enough
3072 * for now (a route might have failed after we sent a segment,
3073 * and the return path might not be symmetrical).
3075 tp->t_softerror = 0;
3079 * Determine a reasonable value for maxseg size.
3080 * If the route is known, check route for mtu.
3081 * If none, use an mss that can be handled on the outgoing
3082 * interface without forcing IP to fragment; if bigger than
3083 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3084 * to utilize large mbufs. If no route is found, route has no mtu,
3085 * or the destination isn't local, use a default, hopefully conservative
3086 * size (usually 512 or the default IP max size, but no more than the mtu
3087 * of the interface), as we can't discover anything about intervening
3088 * gateways or networks. We also initialize the congestion/slow start
3089 * window to be a single segment if the destination isn't local.
3090 * While looking at the routing entry, we also initialize other path-dependent
3091 * parameters from pre-set or cached values in the routing entry.
3093 * Also take into account the space needed for options that we
3094 * send regularly. Make maxseg shorter by that amount to assure
3095 * that we can send maxseg amount of data even when the options
3096 * are present. Store the upper limit of the length of options plus
3099 * In case of T/TCP, we call this routine during implicit connection
3100 * setup as well (offer = -1), to initialize maxseg from the cached
3103 * NOTE that this routine is only called when we process an incoming
3104 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3107 tcp_mss_update(struct tcpcb *tp, int offer,
3108 struct hc_metrics_lite *metricptr, int *mtuflags)
3112 struct inpcb *inp = tp->t_inpcb;
3113 struct hc_metrics_lite metrics;
3114 int origoffer = offer;
3116 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3117 size_t min_protoh = isipv6 ?
3118 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3119 sizeof (struct tcpiphdr);
3121 const size_t min_protoh = sizeof(struct tcpiphdr);
3124 INP_WLOCK_ASSERT(tp->t_inpcb);
3129 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3130 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3134 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3135 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3139 * No route to sender, stay with default mss and return.
3143 * In case we return early we need to initialize metrics
3144 * to a defined state as tcp_hc_get() would do for us
3145 * if there was no cache hit.
3147 if (metricptr != NULL)
3148 bzero(metricptr, sizeof(struct hc_metrics_lite));
3152 /* What have we got? */
3156 * Offer == 0 means that there was no MSS on the SYN
3157 * segment, in this case we use tcp_mssdflt as
3158 * already assigned to t_maxopd above.
3160 offer = tp->t_maxopd;
3165 * Offer == -1 means that we didn't receive SYN yet.
3171 * Prevent DoS attack with too small MSS. Round up
3172 * to at least minmss.
3174 offer = max(offer, V_tcp_minmss);
3178 * rmx information is now retrieved from tcp_hostcache.
3180 tcp_hc_get(&inp->inp_inc, &metrics);
3181 if (metricptr != NULL)
3182 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3185 * If there's a discovered mtu int tcp hostcache, use it
3186 * else, use the link mtu.
3188 if (metrics.rmx_mtu)
3189 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3193 mss = maxmtu - min_protoh;
3194 if (!V_path_mtu_discovery &&
3195 !in6_localaddr(&inp->in6p_faddr))
3196 mss = min(mss, V_tcp_v6mssdflt);
3200 mss = maxmtu - min_protoh;
3201 if (!V_path_mtu_discovery &&
3202 !in_localaddr(inp->inp_faddr))
3203 mss = min(mss, V_tcp_mssdflt);
3206 * XXX - The above conditional (mss = maxmtu - min_protoh)
3207 * probably violates the TCP spec.
3208 * The problem is that, since we don't know the
3209 * other end's MSS, we are supposed to use a conservative
3210 * default. But, if we do that, then MTU discovery will
3211 * never actually take place, because the conservative
3212 * default is much less than the MTUs typically seen
3213 * on the Internet today. For the moment, we'll sweep
3214 * this under the carpet.
3216 * The conservative default might not actually be a problem
3217 * if the only case this occurs is when sending an initial
3218 * SYN with options and data to a host we've never talked
3219 * to before. Then, they will reply with an MSS value which
3220 * will get recorded and the new parameters should get
3221 * recomputed. For Further Study.
3224 mss = min(mss, offer);
3227 * Sanity check: make sure that maxopd will be large
3228 * enough to allow some data on segments even if the
3229 * all the option space is used (40bytes). Otherwise
3230 * funny things may happen in tcp_output.
3235 * maxopd stores the maximum length of data AND options
3236 * in a segment; maxseg is the amount of data in a normal
3237 * segment. We need to store this value (maxopd) apart
3238 * from maxseg, because now every segment carries options
3239 * and thus we normally have somewhat less data in segments.
3244 * origoffer==-1 indicates that no segments were received yet.
3245 * In this case we just guess.
3247 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3249 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3250 mss -= TCPOLEN_TSTAMP_APPA;
3252 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3254 mss &= ~(MCLBYTES-1);
3257 mss = mss / MCLBYTES * MCLBYTES;
3263 tcp_mss(struct tcpcb *tp, int offer)
3269 struct hc_metrics_lite metrics;
3274 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3276 tcp_mss_update(tp, offer, &metrics, &mtuflags);
3281 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3285 * If there's a pipesize, change the socket buffer to that size,
3286 * don't change if sb_hiwat is different than default (then it
3287 * has been changed on purpose with setsockopt).
3288 * Make the socket buffers an integral number of mss units;
3289 * if the mss is larger than the socket buffer, decrease the mss.
3291 so = inp->inp_socket;
3292 SOCKBUF_LOCK(&so->so_snd);
3293 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3294 bufsize = metrics.rmx_sendpipe;
3296 bufsize = so->so_snd.sb_hiwat;
3300 bufsize = roundup(bufsize, mss);
3301 if (bufsize > sb_max)
3303 if (bufsize > so->so_snd.sb_hiwat)
3304 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3306 SOCKBUF_UNLOCK(&so->so_snd);
3309 SOCKBUF_LOCK(&so->so_rcv);
3310 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3311 bufsize = metrics.rmx_recvpipe;
3313 bufsize = so->so_rcv.sb_hiwat;
3314 if (bufsize > mss) {
3315 bufsize = roundup(bufsize, mss);
3316 if (bufsize > sb_max)
3318 if (bufsize > so->so_rcv.sb_hiwat)
3319 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3321 SOCKBUF_UNLOCK(&so->so_rcv);
3323 * While we're here, check the others too.
3325 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3327 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3328 TCPSTAT_INC(tcps_usedrtt);
3329 if (metrics.rmx_rttvar) {
3330 tp->t_rttvar = metrics.rmx_rttvar;
3331 TCPSTAT_INC(tcps_usedrttvar);
3333 /* default variation is +- 1 rtt */
3335 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3337 TCPT_RANGESET(tp->t_rxtcur,
3338 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3339 tp->t_rttmin, TCPTV_REXMTMAX);
3341 if (metrics.rmx_ssthresh) {
3343 * There's some sort of gateway or interface
3344 * buffer limit on the path. Use this to set
3345 * the slow start threshhold, but set the
3346 * threshold to no less than 2*mss.
3348 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3349 TCPSTAT_INC(tcps_usedssthresh);
3351 if (metrics.rmx_bandwidth)
3352 tp->snd_bandwidth = metrics.rmx_bandwidth;
3355 * Set the slow-start flight size depending on whether this
3356 * is a local network or not.
3358 * Extend this so we cache the cwnd too and retrieve it here.
3359 * Make cwnd even bigger than RFC3390 suggests but only if we
3360 * have previous experience with the remote host. Be careful
3361 * not make cwnd bigger than remote receive window or our own
3362 * send socket buffer. Maybe put some additional upper bound
3363 * on the retrieved cwnd. Should do incremental updates to
3364 * hostcache when cwnd collapses so next connection doesn't
3365 * overloads the path again.
3367 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3368 * We currently check only in syncache_socket for that.
3370 #define TCP_METRICS_CWND
3371 #ifdef TCP_METRICS_CWND
3372 if (metrics.rmx_cwnd)
3373 tp->snd_cwnd = max(mss,
3374 min(metrics.rmx_cwnd / 2,
3375 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3378 if (V_tcp_do_rfc3390)
3379 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3381 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3382 (!isipv6 && in_localaddr(inp->inp_faddr)))
3384 else if (in_localaddr(inp->inp_faddr))
3386 tp->snd_cwnd = mss * V_ss_fltsz_local;
3388 tp->snd_cwnd = mss * V_ss_fltsz;
3390 /* Check the interface for TSO capabilities. */
3391 if (mtuflags & CSUM_TSO)
3392 tp->t_flags |= TF_TSO;
3396 * Determine the MSS option to send on an outgoing SYN.
3399 tcp_mssopt(struct in_conninfo *inc)
3406 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3409 if (inc->inc_flags & INC_ISIPV6) {
3410 mss = V_tcp_v6mssdflt;
3411 maxmtu = tcp_maxmtu6(inc, NULL);
3412 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3413 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3417 mss = V_tcp_mssdflt;
3418 maxmtu = tcp_maxmtu(inc, NULL);
3419 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3420 min_protoh = sizeof(struct tcpiphdr);
3422 if (maxmtu && thcmtu)
3423 mss = min(maxmtu, thcmtu) - min_protoh;
3424 else if (maxmtu || thcmtu)
3425 mss = max(maxmtu, thcmtu) - min_protoh;
3432 * On a partial ack arrives, force the retransmission of the
3433 * next unacknowledged segment. Do not clear tp->t_dupacks.
3434 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3438 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3440 tcp_seq onxt = tp->snd_nxt;
3441 u_long ocwnd = tp->snd_cwnd;
3443 INP_WLOCK_ASSERT(tp->t_inpcb);
3445 tcp_timer_activate(tp, TT_REXMT, 0);
3447 tp->snd_nxt = th->th_ack;
3449 * Set snd_cwnd to one segment beyond acknowledged offset.
3450 * (tp->snd_una has not yet been updated when this function is called.)
3452 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3453 tp->t_flags |= TF_ACKNOW;
3454 (void) tcp_output(tp);
3455 tp->snd_cwnd = ocwnd;
3456 if (SEQ_GT(onxt, tp->snd_nxt))
3459 * Partial window deflation. Relies on fact that tp->snd_una
3462 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3463 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3466 tp->snd_cwnd += tp->t_maxseg;