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 VNET_DEFINE(struct inpcbhead, tcb);
184 VNET_DEFINE(struct inpcbinfo, tcbinfo);
185 #define tcb6 tcb /* for KAME src sync over BSD*'s */
187 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
188 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
189 struct socket *, struct tcpcb *, int, int, uint8_t,
191 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
192 struct tcpcb *, int, int);
193 static void tcp_pulloutofband(struct socket *,
194 struct tcphdr *, struct mbuf *, int);
195 static void tcp_xmit_timer(struct tcpcb *, int);
196 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
198 tcp_congestion_exp(struct tcpcb *);
201 * Kernel module interface for updating tcpstat. The argument is an index
202 * into tcpstat treated as an array of u_long. While this encodes the
203 * general layout of tcpstat into the caller, it doesn't encode its location,
204 * so that future changes to add, for example, per-CPU stats support won't
205 * cause binary compatibility problems for kernel modules.
208 kmod_tcpstat_inc(int statnum)
211 (*((u_long *)&V_tcpstat + statnum))++;
215 tcp_congestion_exp(struct tcpcb *tp)
219 win = min(tp->snd_wnd, tp->snd_cwnd) /
223 tp->snd_ssthresh = win * tp->t_maxseg;
224 ENTER_FASTRECOVERY(tp);
225 tp->snd_recover = tp->snd_max;
226 if (tp->t_flags & TF_ECN_PERMIT)
227 tp->t_flags |= TF_ECN_SND_CWR;
230 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
232 #define ND6_HINT(tp) \
234 if ((tp) && (tp)->t_inpcb && \
235 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
236 nd6_nud_hint(NULL, NULL, 0); \
243 * Indicate whether this ack should be delayed. We can delay the ack if
244 * - there is no delayed ack timer in progress and
245 * - our last ack wasn't a 0-sized window. We never want to delay
246 * the ack that opens up a 0-sized window and
247 * - delayed acks are enabled or
248 * - this is a half-synchronized T/TCP connection.
250 #define DELAY_ACK(tp) \
251 ((!tcp_timer_active(tp, TT_DELACK) && \
252 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
253 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
256 * TCP input handling is split into multiple parts:
257 * tcp6_input is a thin wrapper around tcp_input for the extended
258 * ip6_protox[] call format in ip6_input
259 * tcp_input handles primary segment validation, inpcb lookup and
260 * SYN processing on listen sockets
261 * tcp_do_segment processes the ACK and text of the segment for
262 * establishing, established and closing connections
266 tcp6_input(struct mbuf **mp, int *offp, int proto)
268 struct mbuf *m = *mp;
269 struct in6_ifaddr *ia6;
271 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
274 * draft-itojun-ipv6-tcp-to-anycast
275 * better place to put this in?
277 ia6 = ip6_getdstifaddr(m);
278 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
281 ifa_free(&ia6->ia_ifa);
282 ip6 = mtod(m, struct ip6_hdr *);
283 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
284 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
294 tcp_input(struct mbuf *m, int off0)
297 struct ip *ip = NULL;
299 struct inpcb *inp = NULL;
300 struct tcpcb *tp = NULL;
301 struct socket *so = NULL;
307 int rstreason = 0; /* For badport_bandlim accounting purposes */
309 #ifdef IPFIREWALL_FORWARD
310 struct m_tag *fwd_tag;
313 struct ip6_hdr *ip6 = NULL;
316 const void *ip6 = NULL;
317 const int isipv6 = 0;
319 struct tcpopt to; /* options in this segment */
320 char *s = NULL; /* address and port logging */
322 #define TI_UNLOCKED 1
328 * The size of tcp_saveipgen must be the size of the max ip header,
331 u_char tcp_saveipgen[IP6_HDR_LEN];
332 struct tcphdr tcp_savetcp;
337 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
341 TCPSTAT_INC(tcps_rcvtotal);
345 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
346 ip6 = mtod(m, struct ip6_hdr *);
347 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
348 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
349 TCPSTAT_INC(tcps_rcvbadsum);
352 th = (struct tcphdr *)((caddr_t)ip6 + off0);
355 * Be proactive about unspecified IPv6 address in source.
356 * As we use all-zero to indicate unbounded/unconnected pcb,
357 * unspecified IPv6 address can be used to confuse us.
359 * Note that packets with unspecified IPv6 destination is
360 * already dropped in ip6_input.
362 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
367 th = NULL; /* XXX: Avoid compiler warning. */
371 * Get IP and TCP header together in first mbuf.
372 * Note: IP leaves IP header in first mbuf.
374 if (off0 > sizeof (struct ip)) {
375 ip_stripoptions(m, (struct mbuf *)0);
376 off0 = sizeof(struct ip);
378 if (m->m_len < sizeof (struct tcpiphdr)) {
379 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
381 TCPSTAT_INC(tcps_rcvshort);
385 ip = mtod(m, struct ip *);
386 ipov = (struct ipovly *)ip;
387 th = (struct tcphdr *)((caddr_t)ip + off0);
390 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
391 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
392 th->th_sum = m->m_pkthdr.csum_data;
394 th->th_sum = in_pseudo(ip->ip_src.s_addr,
396 htonl(m->m_pkthdr.csum_data +
399 th->th_sum ^= 0xffff;
401 ipov->ih_len = (u_short)tlen;
402 ipov->ih_len = htons(ipov->ih_len);
406 * Checksum extended TCP header and data.
408 len = sizeof (struct ip) + tlen;
409 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
410 ipov->ih_len = (u_short)tlen;
411 ipov->ih_len = htons(ipov->ih_len);
412 th->th_sum = in_cksum(m, len);
415 TCPSTAT_INC(tcps_rcvbadsum);
418 /* Re-initialization for later version check */
419 ip->ip_v = IPVERSION;
424 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
430 * Check that TCP offset makes sense,
431 * pull out TCP options and adjust length. XXX
433 off = th->th_off << 2;
434 if (off < sizeof (struct tcphdr) || off > tlen) {
435 TCPSTAT_INC(tcps_rcvbadoff);
438 tlen -= off; /* tlen is used instead of ti->ti_len */
439 if (off > sizeof (struct tcphdr)) {
442 IP6_EXTHDR_CHECK(m, off0, off, );
443 ip6 = mtod(m, struct ip6_hdr *);
444 th = (struct tcphdr *)((caddr_t)ip6 + off0);
447 if (m->m_len < sizeof(struct ip) + off) {
448 if ((m = m_pullup(m, sizeof (struct ip) + off))
450 TCPSTAT_INC(tcps_rcvshort);
453 ip = mtod(m, struct ip *);
454 ipov = (struct ipovly *)ip;
455 th = (struct tcphdr *)((caddr_t)ip + off0);
458 optlen = off - sizeof (struct tcphdr);
459 optp = (u_char *)(th + 1);
461 thflags = th->th_flags;
464 * Convert TCP protocol specific fields to host format.
466 th->th_seq = ntohl(th->th_seq);
467 th->th_ack = ntohl(th->th_ack);
468 th->th_win = ntohs(th->th_win);
469 th->th_urp = ntohs(th->th_urp);
472 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
474 drop_hdrlen = off0 + off;
477 * Locate pcb for segment, which requires a lock on tcbinfo.
478 * Optimisticaly acquire a global read lock rather than a write lock
479 * unless header flags necessarily imply a state change. There are
480 * two cases where we might discover later we need a write lock
481 * despite the flags: ACKs moving a connection out of the syncache,
482 * and ACKs for a connection in TIMEWAIT.
484 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
485 tcp_read_locking == 0) {
486 INP_INFO_WLOCK(&V_tcbinfo);
487 ti_locked = TI_WLOCKED;
489 INP_INFO_RLOCK(&V_tcbinfo);
490 ti_locked = TI_RLOCKED;
495 if (ti_locked == TI_RLOCKED)
496 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
497 else if (ti_locked == TI_WLOCKED)
498 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
500 panic("%s: findpcb ti_locked %d\n", __func__, ti_locked);
503 #ifdef IPFIREWALL_FORWARD
505 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
507 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
509 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
510 struct sockaddr_in *next_hop;
512 next_hop = (struct sockaddr_in *)(fwd_tag+1);
514 * Transparently forwarded. Pretend to be the destination.
515 * already got one like this?
517 inp = in_pcblookup_hash(&V_tcbinfo,
518 ip->ip_src, th->th_sport,
519 ip->ip_dst, th->th_dport,
520 0, m->m_pkthdr.rcvif);
522 /* It's new. Try to find the ambushing socket. */
523 inp = in_pcblookup_hash(&V_tcbinfo,
524 ip->ip_src, th->th_sport,
527 ntohs(next_hop->sin_port) :
532 /* Remove the tag from the packet. We don't need it anymore. */
533 m_tag_delete(m, fwd_tag);
535 #endif /* IPFIREWALL_FORWARD */
539 inp = in6_pcblookup_hash(&V_tcbinfo,
540 &ip6->ip6_src, th->th_sport,
541 &ip6->ip6_dst, th->th_dport,
546 inp = in_pcblookup_hash(&V_tcbinfo,
547 ip->ip_src, th->th_sport,
548 ip->ip_dst, th->th_dport,
554 * If the INPCB does not exist then all data in the incoming
555 * segment is discarded and an appropriate RST is sent back.
556 * XXX MRT Send RST using which routing table?
560 * Log communication attempts to ports that are not
563 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
564 tcp_log_in_vain == 2) {
565 if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
566 log(LOG_INFO, "%s; %s: Connection attempt "
567 "to closed port\n", s, __func__);
570 * When blackholing do not respond with a RST but
571 * completely ignore the segment and drop it.
573 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
577 rstreason = BANDLIM_RST_CLOSEDPORT;
581 if (!(inp->inp_flags & INP_HW_FLOWID)
582 && (m->m_flags & M_FLOWID)
583 && ((inp->inp_socket == NULL)
584 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
585 inp->inp_flags |= INP_HW_FLOWID;
586 inp->inp_flags &= ~INP_SW_FLOWID;
587 inp->inp_flowid = m->m_pkthdr.flowid;
591 if (isipv6 && ipsec6_in_reject(m, inp)) {
592 V_ipsec6stat.in_polvio++;
596 if (ipsec4_in_reject(m, inp) != 0) {
597 V_ipsec4stat.in_polvio++;
603 * Check the minimum TTL for socket.
605 if (inp->inp_ip_minttl != 0) {
607 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
611 if (inp->inp_ip_minttl > ip->ip_ttl)
616 * A previous connection in TIMEWAIT state is supposed to catch stray
617 * or duplicate segments arriving late. If this segment was a
618 * legitimate new connection attempt the old INPCB gets removed and
619 * we can try again to find a listening socket.
621 * At this point, due to earlier optimism, we may hold a read lock on
622 * the inpcbinfo, rather than a write lock. If so, we need to
623 * upgrade, or if that fails, acquire a reference on the inpcb, drop
624 * all locks, acquire a global write lock, and then re-acquire the
625 * inpcb lock. We may at that point discover that another thread has
626 * tried to free the inpcb, in which case we need to loop back and
627 * try to find a new inpcb to deliver to.
630 if (inp->inp_flags & INP_TIMEWAIT) {
631 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
632 ("%s: INP_TIMEWAIT ti_locked %d", __func__, ti_locked));
634 if (ti_locked == TI_RLOCKED) {
635 if (rw_try_upgrade(&V_tcbinfo.ipi_lock) == 0) {
638 INP_INFO_RUNLOCK(&V_tcbinfo);
639 INP_INFO_WLOCK(&V_tcbinfo);
640 ti_locked = TI_WLOCKED;
642 if (in_pcbrele(inp)) {
647 ti_locked = TI_WLOCKED;
649 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
651 if (thflags & TH_SYN)
652 tcp_dooptions(&to, optp, optlen, TO_SYN);
654 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
656 if (tcp_twcheck(inp, &to, th, m, tlen))
658 INP_INFO_WUNLOCK(&V_tcbinfo);
662 * The TCPCB may no longer exist if the connection is winding
663 * down or it is in the CLOSED state. Either way we drop the
664 * segment and send an appropriate response.
667 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
668 rstreason = BANDLIM_RST_CLOSEDPORT;
673 * We've identified a valid inpcb, but it could be that we need an
674 * inpcbinfo write lock and have only a read lock. In this case,
675 * attempt to upgrade/relock using the same strategy as the TIMEWAIT
676 * case above. If we relock, we have to jump back to 'relocked' as
677 * the connection might now be in TIMEWAIT.
679 if (tp->t_state != TCPS_ESTABLISHED ||
680 (thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
681 tcp_read_locking == 0) {
682 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
683 ("%s: upgrade check ti_locked %d", __func__, ti_locked));
685 if (ti_locked == TI_RLOCKED) {
686 if (rw_try_upgrade(&V_tcbinfo.ipi_lock) == 0) {
689 INP_INFO_RUNLOCK(&V_tcbinfo);
690 INP_INFO_WLOCK(&V_tcbinfo);
691 ti_locked = TI_WLOCKED;
693 if (in_pcbrele(inp)) {
699 ti_locked = TI_WLOCKED;
701 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
705 INP_WLOCK_ASSERT(inp);
706 if (mac_inpcb_check_deliver(inp, m))
709 so = inp->inp_socket;
710 KASSERT(so != NULL, ("%s: so == NULL", __func__));
712 if (so->so_options & SO_DEBUG) {
713 ostate = tp->t_state;
716 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
719 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
724 * When the socket is accepting connections (the INPCB is in LISTEN
725 * state) we look into the SYN cache if this is a new connection
726 * attempt or the completion of a previous one.
728 if (so->so_options & SO_ACCEPTCONN) {
729 struct in_conninfo inc;
731 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
732 "tp not listening", __func__));
734 bzero(&inc, sizeof(inc));
737 inc.inc_flags |= INC_ISIPV6;
738 inc.inc6_faddr = ip6->ip6_src;
739 inc.inc6_laddr = ip6->ip6_dst;
743 inc.inc_faddr = ip->ip_src;
744 inc.inc_laddr = ip->ip_dst;
746 inc.inc_fport = th->th_sport;
747 inc.inc_lport = th->th_dport;
748 inc.inc_fibnum = so->so_fibnum;
751 * Check for an existing connection attempt in syncache if
752 * the flag is only ACK. A successful lookup creates a new
753 * socket appended to the listen queue in SYN_RECEIVED state.
755 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
757 * Parse the TCP options here because
758 * syncookies need access to the reflected
761 tcp_dooptions(&to, optp, optlen, 0);
763 * NB: syncache_expand() doesn't unlock
764 * inp and tcpinfo locks.
766 if (!syncache_expand(&inc, &to, th, &so, m)) {
768 * No syncache entry or ACK was not
769 * for our SYN/ACK. Send a RST.
770 * NB: syncache did its own logging
771 * of the failure cause.
773 rstreason = BANDLIM_RST_OPENPORT;
778 * We completed the 3-way handshake
779 * but could not allocate a socket
780 * either due to memory shortage,
781 * listen queue length limits or
782 * global socket limits. Send RST
783 * or wait and have the remote end
784 * retransmit the ACK for another
787 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
788 log(LOG_DEBUG, "%s; %s: Listen socket: "
789 "Socket allocation failed due to "
790 "limits or memory shortage, %s\n",
792 V_tcp_sc_rst_sock_fail ?
793 "sending RST" : "try again");
794 if (V_tcp_sc_rst_sock_fail) {
795 rstreason = BANDLIM_UNLIMITED;
801 * Socket is created in state SYN_RECEIVED.
802 * Unlock the listen socket, lock the newly
803 * created socket and update the tp variable.
805 INP_WUNLOCK(inp); /* listen socket */
807 INP_WLOCK(inp); /* new connection */
809 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
812 * Process the segment and the data it
813 * contains. tcp_do_segment() consumes
814 * the mbuf chain and unlocks the inpcb.
816 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
818 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
822 * Segment flag validation for new connection attempts:
824 * Our (SYN|ACK) response was rejected.
825 * Check with syncache and remove entry to prevent
828 * NB: syncache_chkrst does its own logging of failure
831 if (thflags & TH_RST) {
832 syncache_chkrst(&inc, th);
836 * We can't do anything without SYN.
838 if ((thflags & TH_SYN) == 0) {
839 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
840 log(LOG_DEBUG, "%s; %s: Listen socket: "
841 "SYN is missing, segment ignored\n",
843 TCPSTAT_INC(tcps_badsyn);
847 * (SYN|ACK) is bogus on a listen socket.
849 if (thflags & TH_ACK) {
850 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
851 log(LOG_DEBUG, "%s; %s: Listen socket: "
852 "SYN|ACK invalid, segment rejected\n",
854 syncache_badack(&inc); /* XXX: Not needed! */
855 TCPSTAT_INC(tcps_badsyn);
856 rstreason = BANDLIM_RST_OPENPORT;
860 * If the drop_synfin option is enabled, drop all
861 * segments with both the SYN and FIN bits set.
862 * This prevents e.g. nmap from identifying the
864 * XXX: Poor reasoning. nmap has other methods
865 * and is constantly refining its stack detection
867 * XXX: This is a violation of the TCP specification
868 * and was used by RFC1644.
870 if ((thflags & TH_FIN) && V_drop_synfin) {
871 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
872 log(LOG_DEBUG, "%s; %s: Listen socket: "
873 "SYN|FIN segment ignored (based on "
874 "sysctl setting)\n", s, __func__);
875 TCPSTAT_INC(tcps_badsyn);
879 * Segment's flags are (SYN) or (SYN|FIN).
881 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
882 * as they do not affect the state of the TCP FSM.
883 * The data pointed to by TH_URG and th_urp is ignored.
885 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
886 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
887 KASSERT(thflags & (TH_SYN),
888 ("%s: Listen socket: TH_SYN not set", __func__));
891 * If deprecated address is forbidden,
892 * we do not accept SYN to deprecated interface
893 * address to prevent any new inbound connection from
894 * getting established.
895 * When we do not accept SYN, we send a TCP RST,
896 * with deprecated source address (instead of dropping
897 * it). We compromise it as it is much better for peer
898 * to send a RST, and RST will be the final packet
901 * If we do not forbid deprecated addresses, we accept
902 * the SYN packet. RFC2462 does not suggest dropping
904 * If we decipher RFC2462 5.5.4, it says like this:
905 * 1. use of deprecated addr with existing
906 * communication is okay - "SHOULD continue to be
908 * 2. use of it with new communication:
909 * (2a) "SHOULD NOT be used if alternate address
910 * with sufficient scope is available"
911 * (2b) nothing mentioned otherwise.
912 * Here we fall into (2b) case as we have no choice in
913 * our source address selection - we must obey the peer.
915 * The wording in RFC2462 is confusing, and there are
916 * multiple description text for deprecated address
917 * handling - worse, they are not exactly the same.
918 * I believe 5.5.4 is the best one, so we follow 5.5.4.
920 if (isipv6 && !V_ip6_use_deprecated) {
921 struct in6_ifaddr *ia6;
923 ia6 = ip6_getdstifaddr(m);
925 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
926 ifa_free(&ia6->ia_ifa);
927 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
928 log(LOG_DEBUG, "%s; %s: Listen socket: "
929 "Connection attempt to deprecated "
930 "IPv6 address rejected\n",
932 rstreason = BANDLIM_RST_OPENPORT;
935 ifa_free(&ia6->ia_ifa);
939 * Basic sanity checks on incoming SYN requests:
940 * Don't respond if the destination is a link layer
941 * broadcast according to RFC1122 4.2.3.10, p. 104.
942 * If it is from this socket it must be forged.
943 * Don't respond if the source or destination is a
944 * global or subnet broad- or multicast address.
945 * Note that it is quite possible to receive unicast
946 * link-layer packets with a broadcast IP address. Use
947 * in_broadcast() to find them.
949 if (m->m_flags & (M_BCAST|M_MCAST)) {
950 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
951 log(LOG_DEBUG, "%s; %s: Listen socket: "
952 "Connection attempt from broad- or multicast "
953 "link layer address ignored\n", s, __func__);
958 if (th->th_dport == th->th_sport &&
959 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
960 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
961 log(LOG_DEBUG, "%s; %s: Listen socket: "
962 "Connection attempt to/from self "
963 "ignored\n", s, __func__);
966 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
967 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
968 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
969 log(LOG_DEBUG, "%s; %s: Listen socket: "
970 "Connection attempt from/to multicast "
971 "address ignored\n", s, __func__);
976 if (th->th_dport == th->th_sport &&
977 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
978 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
979 log(LOG_DEBUG, "%s; %s: Listen socket: "
980 "Connection attempt from/to self "
981 "ignored\n", s, __func__);
984 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
985 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
986 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
987 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
988 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
989 log(LOG_DEBUG, "%s; %s: Listen socket: "
990 "Connection attempt from/to broad- "
991 "or multicast address ignored\n",
997 * SYN appears to be valid. Create compressed TCP state
1001 if (so->so_options & SO_DEBUG)
1002 tcp_trace(TA_INPUT, ostate, tp,
1003 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1005 tcp_dooptions(&to, optp, optlen, TO_SYN);
1006 syncache_add(&inc, &to, th, inp, &so, m);
1008 * Entry added to syncache and mbuf consumed.
1009 * Everything already unlocked by syncache_add().
1011 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1016 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1017 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1018 * the inpcb, and unlocks pcbinfo.
1020 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1021 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1025 if (ti_locked == TI_RLOCKED)
1026 INP_INFO_RUNLOCK(&V_tcbinfo);
1027 else if (ti_locked == TI_WLOCKED)
1028 INP_INFO_WUNLOCK(&V_tcbinfo);
1030 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
1031 ti_locked = TI_UNLOCKED;
1034 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1037 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1038 m = NULL; /* mbuf chain got consumed. */
1042 if (ti_locked == TI_RLOCKED)
1043 INP_INFO_RUNLOCK(&V_tcbinfo);
1044 else if (ti_locked == TI_WLOCKED)
1045 INP_INFO_WUNLOCK(&V_tcbinfo);
1047 panic("%s: dropunlock ti_locked %d", __func__, ti_locked);
1048 ti_locked = TI_UNLOCKED;
1054 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1062 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1063 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1066 int thflags, acked, ourfinisacked, needoutput = 0;
1067 int rstreason, todrop, win;
1073 * The size of tcp_saveipgen must be the size of the max ip header,
1076 u_char tcp_saveipgen[IP6_HDR_LEN];
1077 struct tcphdr tcp_savetcp;
1080 thflags = th->th_flags;
1083 * If this is either a state-changing packet or current state isn't
1084 * established, we require a write lock on tcbinfo. Otherwise, we
1085 * allow either a read lock or a write lock, as we may have acquired
1086 * a write lock due to a race.
1088 * Require a global write lock for SYN/FIN/RST segments or
1089 * non-established connections; otherwise accept either a read or
1090 * write lock, as we may have conservatively acquired a write lock in
1091 * certain cases in tcp_input() (is this still true?). Currently we
1092 * will never enter with no lock, so we try to drop it quickly in the
1093 * common pure ack/pure data cases.
1095 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1096 tp->t_state != TCPS_ESTABLISHED) {
1097 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1098 "SYN/FIN/RST/!EST", __func__, ti_locked));
1099 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1102 if (ti_locked == TI_RLOCKED)
1103 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1104 else if (ti_locked == TI_WLOCKED)
1105 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1107 panic("%s: ti_locked %d for EST", __func__,
1111 INP_WLOCK_ASSERT(tp->t_inpcb);
1112 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1114 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1118 * Segment received on connection.
1119 * Reset idle time and keep-alive timer.
1120 * XXX: This should be done after segment
1121 * validation to ignore broken/spoofed segs.
1123 tp->t_rcvtime = ticks;
1124 if (TCPS_HAVEESTABLISHED(tp->t_state))
1125 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1128 * Unscale the window into a 32-bit value.
1129 * For the SYN_SENT state the scale is zero.
1131 tiwin = th->th_win << tp->snd_scale;
1134 * TCP ECN processing.
1136 if (tp->t_flags & TF_ECN_PERMIT) {
1137 switch (iptos & IPTOS_ECN_MASK) {
1139 tp->t_flags |= TF_ECN_SND_ECE;
1140 TCPSTAT_INC(tcps_ecn_ce);
1142 case IPTOS_ECN_ECT0:
1143 TCPSTAT_INC(tcps_ecn_ect0);
1145 case IPTOS_ECN_ECT1:
1146 TCPSTAT_INC(tcps_ecn_ect1);
1150 if (thflags & TH_CWR)
1151 tp->t_flags &= ~TF_ECN_SND_ECE;
1154 * Congestion experienced.
1155 * Ignore if we are already trying to recover.
1157 if ((thflags & TH_ECE) &&
1158 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
1159 TCPSTAT_INC(tcps_ecn_rcwnd);
1160 tcp_congestion_exp(tp);
1165 * Parse options on any incoming segment.
1167 tcp_dooptions(&to, (u_char *)(th + 1),
1168 (th->th_off << 2) - sizeof(struct tcphdr),
1169 (thflags & TH_SYN) ? TO_SYN : 0);
1172 * If echoed timestamp is later than the current time,
1173 * fall back to non RFC1323 RTT calculation. Normalize
1174 * timestamp if syncookies were used when this connection
1177 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1178 to.to_tsecr -= tp->ts_offset;
1179 if (TSTMP_GT(to.to_tsecr, ticks))
1184 * Process options only when we get SYN/ACK back. The SYN case
1185 * for incoming connections is handled in tcp_syncache.
1186 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1187 * or <SYN,ACK>) segment itself is never scaled.
1188 * XXX this is traditional behavior, may need to be cleaned up.
1190 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1191 if ((to.to_flags & TOF_SCALE) &&
1192 (tp->t_flags & TF_REQ_SCALE)) {
1193 tp->t_flags |= TF_RCVD_SCALE;
1194 tp->snd_scale = to.to_wscale;
1197 * Initial send window. It will be updated with
1198 * the next incoming segment to the scaled value.
1200 tp->snd_wnd = th->th_win;
1201 if (to.to_flags & TOF_TS) {
1202 tp->t_flags |= TF_RCVD_TSTMP;
1203 tp->ts_recent = to.to_tsval;
1204 tp->ts_recent_age = ticks;
1206 if (to.to_flags & TOF_MSS)
1207 tcp_mss(tp, to.to_mss);
1208 if ((tp->t_flags & TF_SACK_PERMIT) &&
1209 (to.to_flags & TOF_SACKPERM) == 0)
1210 tp->t_flags &= ~TF_SACK_PERMIT;
1214 * Header prediction: check for the two common cases
1215 * of a uni-directional data xfer. If the packet has
1216 * no control flags, is in-sequence, the window didn't
1217 * change and we're not retransmitting, it's a
1218 * candidate. If the length is zero and the ack moved
1219 * forward, we're the sender side of the xfer. Just
1220 * free the data acked & wake any higher level process
1221 * that was blocked waiting for space. If the length
1222 * is non-zero and the ack didn't move, we're the
1223 * receiver side. If we're getting packets in-order
1224 * (the reassembly queue is empty), add the data to
1225 * the socket buffer and note that we need a delayed ack.
1226 * Make sure that the hidden state-flags are also off.
1227 * Since we check for TCPS_ESTABLISHED first, it can only
1230 if (tp->t_state == TCPS_ESTABLISHED &&
1231 th->th_seq == tp->rcv_nxt &&
1232 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1233 tp->snd_nxt == tp->snd_max &&
1234 tiwin && tiwin == tp->snd_wnd &&
1235 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1236 LIST_EMPTY(&tp->t_segq) &&
1237 ((to.to_flags & TOF_TS) == 0 ||
1238 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1241 * If last ACK falls within this segment's sequence numbers,
1242 * record the timestamp.
1243 * NOTE that the test is modified according to the latest
1244 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1246 if ((to.to_flags & TOF_TS) != 0 &&
1247 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1248 tp->ts_recent_age = ticks;
1249 tp->ts_recent = to.to_tsval;
1253 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1254 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1255 tp->snd_cwnd >= tp->snd_wnd &&
1256 ((!V_tcp_do_newreno &&
1257 !(tp->t_flags & TF_SACK_PERMIT) &&
1258 tp->t_dupacks < tcprexmtthresh) ||
1259 ((V_tcp_do_newreno ||
1260 (tp->t_flags & TF_SACK_PERMIT)) &&
1261 !IN_FASTRECOVERY(tp) &&
1262 (to.to_flags & TOF_SACK) == 0 &&
1263 TAILQ_EMPTY(&tp->snd_holes)))) {
1265 * This is a pure ack for outstanding data.
1267 if (ti_locked == TI_RLOCKED)
1268 INP_INFO_RUNLOCK(&V_tcbinfo);
1269 else if (ti_locked == TI_WLOCKED)
1270 INP_INFO_WUNLOCK(&V_tcbinfo);
1272 panic("%s: ti_locked %d on pure ACK",
1273 __func__, ti_locked);
1274 ti_locked = TI_UNLOCKED;
1276 TCPSTAT_INC(tcps_predack);
1279 * "bad retransmit" recovery.
1281 if (tp->t_rxtshift == 1 &&
1282 (int)(ticks - tp->t_badrxtwin) < 0) {
1283 TCPSTAT_INC(tcps_sndrexmitbad);
1284 tp->snd_cwnd = tp->snd_cwnd_prev;
1286 tp->snd_ssthresh_prev;
1287 tp->snd_recover = tp->snd_recover_prev;
1288 if (tp->t_flags & TF_WASFRECOVERY)
1289 ENTER_FASTRECOVERY(tp);
1290 tp->snd_nxt = tp->snd_max;
1291 tp->t_badrxtwin = 0;
1295 * Recalculate the transmit timer / rtt.
1297 * Some boxes send broken timestamp replies
1298 * during the SYN+ACK phase, ignore
1299 * timestamps of 0 or we could calculate a
1300 * huge RTT and blow up the retransmit timer.
1302 if ((to.to_flags & TOF_TS) != 0 &&
1304 if (!tp->t_rttlow ||
1305 tp->t_rttlow > ticks - to.to_tsecr)
1306 tp->t_rttlow = ticks - to.to_tsecr;
1308 ticks - to.to_tsecr + 1);
1309 } else if (tp->t_rtttime &&
1310 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1311 if (!tp->t_rttlow ||
1312 tp->t_rttlow > ticks - tp->t_rtttime)
1313 tp->t_rttlow = ticks - tp->t_rtttime;
1315 ticks - tp->t_rtttime);
1317 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1318 acked = th->th_ack - tp->snd_una;
1319 TCPSTAT_INC(tcps_rcvackpack);
1320 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1321 sbdrop(&so->so_snd, acked);
1322 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1323 SEQ_LEQ(th->th_ack, tp->snd_recover))
1324 tp->snd_recover = th->th_ack - 1;
1325 tp->snd_una = th->th_ack;
1327 * Pull snd_wl2 up to prevent seq wrap relative
1330 tp->snd_wl2 = th->th_ack;
1333 ND6_HINT(tp); /* Some progress has been made. */
1336 * If all outstanding data are acked, stop
1337 * retransmit timer, otherwise restart timer
1338 * using current (possibly backed-off) value.
1339 * If process is waiting for space,
1340 * wakeup/selwakeup/signal. If data
1341 * are ready to send, let tcp_output
1342 * decide between more output or persist.
1345 if (so->so_options & SO_DEBUG)
1346 tcp_trace(TA_INPUT, ostate, tp,
1347 (void *)tcp_saveipgen,
1350 if (tp->snd_una == tp->snd_max)
1351 tcp_timer_activate(tp, TT_REXMT, 0);
1352 else if (!tcp_timer_active(tp, TT_PERSIST))
1353 tcp_timer_activate(tp, TT_REXMT,
1356 if (so->so_snd.sb_cc)
1357 (void) tcp_output(tp);
1360 } else if (th->th_ack == tp->snd_una &&
1361 tlen <= sbspace(&so->so_rcv)) {
1362 int newsize = 0; /* automatic sockbuf scaling */
1365 * This is a pure, in-sequence data packet with
1366 * nothing on the reassembly queue and we have enough
1367 * buffer space to take it.
1369 if (ti_locked == TI_RLOCKED)
1370 INP_INFO_RUNLOCK(&V_tcbinfo);
1371 else if (ti_locked == TI_WLOCKED)
1372 INP_INFO_WUNLOCK(&V_tcbinfo);
1374 panic("%s: ti_locked %d on pure data "
1375 "segment", __func__, ti_locked);
1376 ti_locked = TI_UNLOCKED;
1378 /* Clean receiver SACK report if present */
1379 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1380 tcp_clean_sackreport(tp);
1381 TCPSTAT_INC(tcps_preddat);
1382 tp->rcv_nxt += tlen;
1384 * Pull snd_wl1 up to prevent seq wrap relative to
1387 tp->snd_wl1 = th->th_seq;
1389 * Pull rcv_up up to prevent seq wrap relative to
1392 tp->rcv_up = tp->rcv_nxt;
1393 TCPSTAT_INC(tcps_rcvpack);
1394 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1395 ND6_HINT(tp); /* Some progress has been made */
1397 if (so->so_options & SO_DEBUG)
1398 tcp_trace(TA_INPUT, ostate, tp,
1399 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1402 * Automatic sizing of receive socket buffer. Often the send
1403 * buffer size is not optimally adjusted to the actual network
1404 * conditions at hand (delay bandwidth product). Setting the
1405 * buffer size too small limits throughput on links with high
1406 * bandwidth and high delay (eg. trans-continental/oceanic links).
1408 * On the receive side the socket buffer memory is only rarely
1409 * used to any significant extent. This allows us to be much
1410 * more aggressive in scaling the receive socket buffer. For
1411 * the case that the buffer space is actually used to a large
1412 * extent and we run out of kernel memory we can simply drop
1413 * the new segments; TCP on the sender will just retransmit it
1414 * later. Setting the buffer size too big may only consume too
1415 * much kernel memory if the application doesn't read() from
1416 * the socket or packet loss or reordering makes use of the
1419 * The criteria to step up the receive buffer one notch are:
1420 * 1. the number of bytes received during the time it takes
1421 * one timestamp to be reflected back to us (the RTT);
1422 * 2. received bytes per RTT is within seven eighth of the
1423 * current socket buffer size;
1424 * 3. receive buffer size has not hit maximal automatic size;
1426 * This algorithm does one step per RTT at most and only if
1427 * we receive a bulk stream w/o packet losses or reorderings.
1428 * Shrinking the buffer during idle times is not necessary as
1429 * it doesn't consume any memory when idle.
1431 * TODO: Only step up if the application is actually serving
1432 * the buffer to better manage the socket buffer resources.
1434 if (V_tcp_do_autorcvbuf &&
1436 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1437 if (to.to_tsecr > tp->rfbuf_ts &&
1438 to.to_tsecr - tp->rfbuf_ts < hz) {
1440 (so->so_rcv.sb_hiwat / 8 * 7) &&
1441 so->so_rcv.sb_hiwat <
1442 V_tcp_autorcvbuf_max) {
1444 min(so->so_rcv.sb_hiwat +
1445 V_tcp_autorcvbuf_inc,
1446 V_tcp_autorcvbuf_max);
1448 /* Start over with next RTT. */
1452 tp->rfbuf_cnt += tlen; /* add up */
1455 /* Add data to socket buffer. */
1456 SOCKBUF_LOCK(&so->so_rcv);
1457 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1461 * Set new socket buffer size.
1462 * Give up when limit is reached.
1465 if (!sbreserve_locked(&so->so_rcv,
1467 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1468 m_adj(m, drop_hdrlen); /* delayed header drop */
1469 sbappendstream_locked(&so->so_rcv, m);
1471 /* NB: sorwakeup_locked() does an implicit unlock. */
1472 sorwakeup_locked(so);
1473 if (DELAY_ACK(tp)) {
1474 tp->t_flags |= TF_DELACK;
1476 tp->t_flags |= TF_ACKNOW;
1484 * Calculate amount of space in receive window,
1485 * and then do TCP input processing.
1486 * Receive window is amount of space in rcv queue,
1487 * but not less than advertised window.
1489 win = sbspace(&so->so_rcv);
1492 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1494 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1498 switch (tp->t_state) {
1501 * If the state is SYN_RECEIVED:
1502 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1504 case TCPS_SYN_RECEIVED:
1505 if ((thflags & TH_ACK) &&
1506 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1507 SEQ_GT(th->th_ack, tp->snd_max))) {
1508 rstreason = BANDLIM_RST_OPENPORT;
1514 * If the state is SYN_SENT:
1515 * if seg contains an ACK, but not for our SYN, drop the input.
1516 * if seg contains a RST, then drop the connection.
1517 * if seg does not contain SYN, then drop it.
1518 * Otherwise this is an acceptable SYN segment
1519 * initialize tp->rcv_nxt and tp->irs
1520 * if seg contains ack then advance tp->snd_una
1521 * if seg contains an ECE and ECN support is enabled, the stream
1523 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1524 * arrange for segment to be acked (eventually)
1525 * continue processing rest of data/controls, beginning with URG
1528 if ((thflags & TH_ACK) &&
1529 (SEQ_LEQ(th->th_ack, tp->iss) ||
1530 SEQ_GT(th->th_ack, tp->snd_max))) {
1531 rstreason = BANDLIM_UNLIMITED;
1534 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1535 tp = tcp_drop(tp, ECONNREFUSED);
1536 if (thflags & TH_RST)
1538 if (!(thflags & TH_SYN))
1541 tp->irs = th->th_seq;
1543 if (thflags & TH_ACK) {
1544 TCPSTAT_INC(tcps_connects);
1547 mac_socketpeer_set_from_mbuf(m, so);
1549 /* Do window scaling on this connection? */
1550 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1551 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1552 tp->rcv_scale = tp->request_r_scale;
1554 tp->rcv_adv += tp->rcv_wnd;
1555 tp->snd_una++; /* SYN is acked */
1557 * If there's data, delay ACK; if there's also a FIN
1558 * ACKNOW will be turned on later.
1560 if (DELAY_ACK(tp) && tlen != 0)
1561 tcp_timer_activate(tp, TT_DELACK,
1564 tp->t_flags |= TF_ACKNOW;
1566 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1567 tp->t_flags |= TF_ECN_PERMIT;
1568 TCPSTAT_INC(tcps_ecn_shs);
1572 * Received <SYN,ACK> in SYN_SENT[*] state.
1574 * SYN_SENT --> ESTABLISHED
1575 * SYN_SENT* --> FIN_WAIT_1
1577 tp->t_starttime = ticks;
1578 if (tp->t_flags & TF_NEEDFIN) {
1579 tp->t_state = TCPS_FIN_WAIT_1;
1580 tp->t_flags &= ~TF_NEEDFIN;
1583 tp->t_state = TCPS_ESTABLISHED;
1584 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1588 * Received initial SYN in SYN-SENT[*] state =>
1589 * simultaneous open. If segment contains CC option
1590 * and there is a cached CC, apply TAO test.
1591 * If it succeeds, connection is * half-synchronized.
1592 * Otherwise, do 3-way handshake:
1593 * SYN-SENT -> SYN-RECEIVED
1594 * SYN-SENT* -> SYN-RECEIVED*
1595 * If there was no CC option, clear cached CC value.
1597 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1598 tcp_timer_activate(tp, TT_REXMT, 0);
1599 tp->t_state = TCPS_SYN_RECEIVED;
1602 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1603 "ti_locked %d", __func__, ti_locked));
1604 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1605 INP_WLOCK_ASSERT(tp->t_inpcb);
1608 * Advance th->th_seq to correspond to first data byte.
1609 * If data, trim to stay within window,
1610 * dropping FIN if necessary.
1613 if (tlen > tp->rcv_wnd) {
1614 todrop = tlen - tp->rcv_wnd;
1618 TCPSTAT_INC(tcps_rcvpackafterwin);
1619 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1621 tp->snd_wl1 = th->th_seq - 1;
1622 tp->rcv_up = th->th_seq;
1624 * Client side of transaction: already sent SYN and data.
1625 * If the remote host used T/TCP to validate the SYN,
1626 * our data will be ACK'd; if so, enter normal data segment
1627 * processing in the middle of step 5, ack processing.
1628 * Otherwise, goto step 6.
1630 if (thflags & TH_ACK)
1636 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1637 * do normal processing.
1639 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1643 break; /* continue normal processing */
1647 * States other than LISTEN or SYN_SENT.
1648 * First check the RST flag and sequence number since reset segments
1649 * are exempt from the timestamp and connection count tests. This
1650 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1651 * below which allowed reset segments in half the sequence space
1652 * to fall though and be processed (which gives forged reset
1653 * segments with a random sequence number a 50 percent chance of
1654 * killing a connection).
1655 * Then check timestamp, if present.
1656 * Then check the connection count, if present.
1657 * Then check that at least some bytes of segment are within
1658 * receive window. If segment begins before rcv_nxt,
1659 * drop leading data (and SYN); if nothing left, just ack.
1662 * If the RST bit is set, check the sequence number to see
1663 * if this is a valid reset segment.
1665 * In all states except SYN-SENT, all reset (RST) segments
1666 * are validated by checking their SEQ-fields. A reset is
1667 * valid if its sequence number is in the window.
1668 * Note: this does not take into account delayed ACKs, so
1669 * we should test against last_ack_sent instead of rcv_nxt.
1670 * The sequence number in the reset segment is normally an
1671 * echo of our outgoing acknowlegement numbers, but some hosts
1672 * send a reset with the sequence number at the rightmost edge
1673 * of our receive window, and we have to handle this case.
1674 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1675 * that brute force RST attacks are possible. To combat this,
1676 * we use a much stricter check while in the ESTABLISHED state,
1677 * only accepting RSTs where the sequence number is equal to
1678 * last_ack_sent. In all other states (the states in which a
1679 * RST is more likely), the more permissive check is used.
1680 * If we have multiple segments in flight, the initial reset
1681 * segment sequence numbers will be to the left of last_ack_sent,
1682 * but they will eventually catch up.
1683 * In any case, it never made sense to trim reset segments to
1684 * fit the receive window since RFC 1122 says:
1685 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1687 * A TCP SHOULD allow a received RST segment to include data.
1690 * It has been suggested that a RST segment could contain
1691 * ASCII text that encoded and explained the cause of the
1692 * RST. No standard has yet been established for such
1695 * If the reset segment passes the sequence number test examine
1697 * SYN_RECEIVED STATE:
1698 * If passive open, return to LISTEN state.
1699 * If active open, inform user that connection was refused.
1700 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1701 * Inform user that connection was reset, and close tcb.
1702 * CLOSING, LAST_ACK STATES:
1705 * Drop the segment - see Stevens, vol. 2, p. 964 and
1708 if (thflags & TH_RST) {
1709 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1710 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1711 switch (tp->t_state) {
1713 case TCPS_SYN_RECEIVED:
1714 so->so_error = ECONNREFUSED;
1717 case TCPS_ESTABLISHED:
1718 if (V_tcp_insecure_rst == 0 &&
1719 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1720 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1721 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1722 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1723 TCPSTAT_INC(tcps_badrst);
1727 case TCPS_FIN_WAIT_1:
1728 case TCPS_FIN_WAIT_2:
1729 case TCPS_CLOSE_WAIT:
1730 so->so_error = ECONNRESET;
1732 KASSERT(ti_locked == TI_WLOCKED,
1733 ("tcp_do_segment: TH_RST 1 ti_locked %d",
1735 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1737 tp->t_state = TCPS_CLOSED;
1738 TCPSTAT_INC(tcps_drops);
1744 KASSERT(ti_locked == TI_WLOCKED,
1745 ("tcp_do_segment: TH_RST 2 ti_locked %d",
1747 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1757 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1758 * and it's less than ts_recent, drop it.
1760 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1761 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1763 /* Check to see if ts_recent is over 24 days old. */
1764 if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
1766 * Invalidate ts_recent. If this segment updates
1767 * ts_recent, the age will be reset later and ts_recent
1768 * will get a valid value. If it does not, setting
1769 * ts_recent to zero will at least satisfy the
1770 * requirement that zero be placed in the timestamp
1771 * echo reply when ts_recent isn't valid. The
1772 * age isn't reset until we get a valid ts_recent
1773 * because we don't want out-of-order segments to be
1774 * dropped when ts_recent is old.
1778 TCPSTAT_INC(tcps_rcvduppack);
1779 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1780 TCPSTAT_INC(tcps_pawsdrop);
1788 * In the SYN-RECEIVED state, validate that the packet belongs to
1789 * this connection before trimming the data to fit the receive
1790 * window. Check the sequence number versus IRS since we know
1791 * the sequence numbers haven't wrapped. This is a partial fix
1792 * for the "LAND" DoS attack.
1794 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1795 rstreason = BANDLIM_RST_OPENPORT;
1799 todrop = tp->rcv_nxt - th->th_seq;
1802 * If this is a duplicate SYN for our current connection,
1803 * advance over it and pretend and it's not a SYN.
1805 if (thflags & TH_SYN && th->th_seq == tp->irs) {
1815 * Following if statement from Stevens, vol. 2, p. 960.
1818 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1820 * Any valid FIN must be to the left of the window.
1821 * At this point the FIN must be a duplicate or out
1822 * of sequence; drop it.
1827 * Send an ACK to resynchronize and drop any data.
1828 * But keep on processing for RST or ACK.
1830 tp->t_flags |= TF_ACKNOW;
1832 TCPSTAT_INC(tcps_rcvduppack);
1833 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1835 TCPSTAT_INC(tcps_rcvpartduppack);
1836 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1838 drop_hdrlen += todrop; /* drop from the top afterwards */
1839 th->th_seq += todrop;
1841 if (th->th_urp > todrop)
1842 th->th_urp -= todrop;
1850 * If new data are received on a connection after the
1851 * user processes are gone, then RST the other end.
1853 if ((so->so_state & SS_NOFDREF) &&
1854 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1857 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
1858 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
1859 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1861 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1862 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
1863 "was closed, sending RST and removing tcpcb\n",
1864 s, __func__, tcpstates[tp->t_state], tlen);
1868 TCPSTAT_INC(tcps_rcvafterclose);
1869 rstreason = BANDLIM_UNLIMITED;
1874 * If segment ends after window, drop trailing data
1875 * (and PUSH and FIN); if nothing left, just ACK.
1877 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1879 TCPSTAT_INC(tcps_rcvpackafterwin);
1880 if (todrop >= tlen) {
1881 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1883 * If window is closed can only take segments at
1884 * window edge, and have to drop data and PUSH from
1885 * incoming segments. Continue processing, but
1886 * remember to ack. Otherwise, drop segment
1889 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1890 tp->t_flags |= TF_ACKNOW;
1891 TCPSTAT_INC(tcps_rcvwinprobe);
1895 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1898 thflags &= ~(TH_PUSH|TH_FIN);
1902 * If last ACK falls within this segment's sequence numbers,
1903 * record its timestamp.
1905 * 1) That the test incorporates suggestions from the latest
1906 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1907 * 2) That updating only on newer timestamps interferes with
1908 * our earlier PAWS tests, so this check should be solely
1909 * predicated on the sequence space of this segment.
1910 * 3) That we modify the segment boundary check to be
1911 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1912 * instead of RFC1323's
1913 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1914 * This modified check allows us to overcome RFC1323's
1915 * limitations as described in Stevens TCP/IP Illustrated
1916 * Vol. 2 p.869. In such cases, we can still calculate the
1917 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1919 if ((to.to_flags & TOF_TS) != 0 &&
1920 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1921 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1922 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1923 tp->ts_recent_age = ticks;
1924 tp->ts_recent = to.to_tsval;
1928 * If a SYN is in the window, then this is an
1929 * error and we send an RST and drop the connection.
1931 if (thflags & TH_SYN) {
1932 KASSERT(ti_locked == TI_WLOCKED,
1933 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
1934 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1936 tp = tcp_drop(tp, ECONNRESET);
1937 rstreason = BANDLIM_UNLIMITED;
1942 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1943 * flag is on (half-synchronized state), then queue data for
1944 * later processing; else drop segment and return.
1946 if ((thflags & TH_ACK) == 0) {
1947 if (tp->t_state == TCPS_SYN_RECEIVED ||
1948 (tp->t_flags & TF_NEEDSYN))
1950 else if (tp->t_flags & TF_ACKNOW)
1959 switch (tp->t_state) {
1962 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1963 * ESTABLISHED state and continue processing.
1964 * The ACK was checked above.
1966 case TCPS_SYN_RECEIVED:
1968 TCPSTAT_INC(tcps_connects);
1970 /* Do window scaling? */
1971 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1972 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1973 tp->rcv_scale = tp->request_r_scale;
1974 tp->snd_wnd = tiwin;
1978 * SYN-RECEIVED -> ESTABLISHED
1979 * SYN-RECEIVED* -> FIN-WAIT-1
1981 tp->t_starttime = ticks;
1982 if (tp->t_flags & TF_NEEDFIN) {
1983 tp->t_state = TCPS_FIN_WAIT_1;
1984 tp->t_flags &= ~TF_NEEDFIN;
1986 tp->t_state = TCPS_ESTABLISHED;
1987 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1990 * If segment contains data or ACK, will call tcp_reass()
1991 * later; if not, do so now to pass queued data to user.
1993 if (tlen == 0 && (thflags & TH_FIN) == 0)
1994 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1996 tp->snd_wl1 = th->th_seq - 1;
2000 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2001 * ACKs. If the ack is in the range
2002 * tp->snd_una < th->th_ack <= tp->snd_max
2003 * then advance tp->snd_una to th->th_ack and drop
2004 * data from the retransmission queue. If this ACK reflects
2005 * more up to date window information we update our window information.
2007 case TCPS_ESTABLISHED:
2008 case TCPS_FIN_WAIT_1:
2009 case TCPS_FIN_WAIT_2:
2010 case TCPS_CLOSE_WAIT:
2013 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2014 TCPSTAT_INC(tcps_rcvacktoomuch);
2017 if ((tp->t_flags & TF_SACK_PERMIT) &&
2018 ((to.to_flags & TOF_SACK) ||
2019 !TAILQ_EMPTY(&tp->snd_holes)))
2020 tcp_sack_doack(tp, &to, th->th_ack);
2021 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2022 if (tlen == 0 && tiwin == tp->snd_wnd) {
2023 TCPSTAT_INC(tcps_rcvdupack);
2025 * If we have outstanding data (other than
2026 * a window probe), this is a completely
2027 * duplicate ack (ie, window info didn't
2028 * change), the ack is the biggest we've
2029 * seen and we've seen exactly our rexmt
2030 * threshhold of them, assume a packet
2031 * has been dropped and retransmit it.
2032 * Kludge snd_nxt & the congestion
2033 * window so we send only this one
2036 * We know we're losing at the current
2037 * window size so do congestion avoidance
2038 * (set ssthresh to half the current window
2039 * and pull our congestion window back to
2040 * the new ssthresh).
2042 * Dup acks mean that packets have left the
2043 * network (they're now cached at the receiver)
2044 * so bump cwnd by the amount in the receiver
2045 * to keep a constant cwnd packets in the
2048 * When using TCP ECN, notify the peer that
2049 * we reduced the cwnd.
2051 if (!tcp_timer_active(tp, TT_REXMT) ||
2052 th->th_ack != tp->snd_una)
2054 else if (++tp->t_dupacks > tcprexmtthresh ||
2055 ((V_tcp_do_newreno ||
2056 (tp->t_flags & TF_SACK_PERMIT)) &&
2057 IN_FASTRECOVERY(tp))) {
2058 if ((tp->t_flags & TF_SACK_PERMIT) &&
2059 IN_FASTRECOVERY(tp)) {
2063 * Compute the amount of data in flight first.
2064 * We can inject new data into the pipe iff
2065 * we have less than 1/2 the original window's
2066 * worth of data in flight.
2068 awnd = (tp->snd_nxt - tp->snd_fack) +
2069 tp->sackhint.sack_bytes_rexmit;
2070 if (awnd < tp->snd_ssthresh) {
2071 tp->snd_cwnd += tp->t_maxseg;
2072 if (tp->snd_cwnd > tp->snd_ssthresh)
2073 tp->snd_cwnd = tp->snd_ssthresh;
2076 tp->snd_cwnd += tp->t_maxseg;
2077 (void) tcp_output(tp);
2079 } else if (tp->t_dupacks == tcprexmtthresh) {
2080 tcp_seq onxt = tp->snd_nxt;
2083 * If we're doing sack, check to
2084 * see if we're already in sack
2085 * recovery. If we're not doing sack,
2086 * check to see if we're in newreno
2089 if (tp->t_flags & TF_SACK_PERMIT) {
2090 if (IN_FASTRECOVERY(tp)) {
2094 } else if (V_tcp_do_newreno ||
2096 if (SEQ_LEQ(th->th_ack,
2102 tcp_congestion_exp(tp);
2103 tcp_timer_activate(tp, TT_REXMT, 0);
2105 if (tp->t_flags & TF_SACK_PERMIT) {
2107 tcps_sack_recovery_episode);
2108 tp->sack_newdata = tp->snd_nxt;
2109 tp->snd_cwnd = tp->t_maxseg;
2110 (void) tcp_output(tp);
2113 tp->snd_nxt = th->th_ack;
2114 tp->snd_cwnd = tp->t_maxseg;
2115 (void) tcp_output(tp);
2116 KASSERT(tp->snd_limited <= 2,
2117 ("%s: tp->snd_limited too big",
2119 tp->snd_cwnd = tp->snd_ssthresh +
2121 (tp->t_dupacks - tp->snd_limited);
2122 if (SEQ_GT(onxt, tp->snd_nxt))
2125 } else if (V_tcp_do_rfc3042) {
2126 u_long oldcwnd = tp->snd_cwnd;
2127 tcp_seq oldsndmax = tp->snd_max;
2130 KASSERT(tp->t_dupacks == 1 ||
2132 ("%s: dupacks not 1 or 2",
2134 if (tp->t_dupacks == 1)
2135 tp->snd_limited = 0;
2137 (tp->snd_nxt - tp->snd_una) +
2138 (tp->t_dupacks - tp->snd_limited) *
2140 (void) tcp_output(tp);
2141 sent = tp->snd_max - oldsndmax;
2142 if (sent > tp->t_maxseg) {
2143 KASSERT((tp->t_dupacks == 2 &&
2144 tp->snd_limited == 0) ||
2145 (sent == tp->t_maxseg + 1 &&
2146 tp->t_flags & TF_SENTFIN),
2147 ("%s: sent too much",
2149 tp->snd_limited = 2;
2150 } else if (sent > 0)
2152 tp->snd_cwnd = oldcwnd;
2160 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2161 ("%s: th_ack <= snd_una", __func__));
2164 * If the congestion window was inflated to account
2165 * for the other side's cached packets, retract it.
2167 if (V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
2168 if (IN_FASTRECOVERY(tp)) {
2169 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2170 if (tp->t_flags & TF_SACK_PERMIT)
2171 tcp_sack_partialack(tp, th);
2173 tcp_newreno_partial_ack(tp, th);
2176 * Out of fast recovery.
2177 * Window inflation should have left us
2178 * with approximately snd_ssthresh
2180 * But in case we would be inclined to
2181 * send a burst, better to do it via
2182 * the slow start mechanism.
2184 if (SEQ_GT(th->th_ack +
2187 tp->snd_cwnd = tp->snd_max -
2191 tp->snd_cwnd = tp->snd_ssthresh;
2195 if (tp->t_dupacks >= tcprexmtthresh &&
2196 tp->snd_cwnd > tp->snd_ssthresh)
2197 tp->snd_cwnd = tp->snd_ssthresh;
2201 * If we reach this point, ACK is not a duplicate,
2202 * i.e., it ACKs something we sent.
2204 if (tp->t_flags & TF_NEEDSYN) {
2206 * T/TCP: Connection was half-synchronized, and our
2207 * SYN has been ACK'd (so connection is now fully
2208 * synchronized). Go to non-starred state,
2209 * increment snd_una for ACK of SYN, and check if
2210 * we can do window scaling.
2212 tp->t_flags &= ~TF_NEEDSYN;
2214 /* Do window scaling? */
2215 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2216 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2217 tp->rcv_scale = tp->request_r_scale;
2218 /* Send window already scaled. */
2223 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2224 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2225 ("tcp_input: process_ACK ti_locked %d", ti_locked));
2226 INP_WLOCK_ASSERT(tp->t_inpcb);
2228 acked = th->th_ack - tp->snd_una;
2229 TCPSTAT_INC(tcps_rcvackpack);
2230 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2233 * If we just performed our first retransmit, and the ACK
2234 * arrives within our recovery window, then it was a mistake
2235 * to do the retransmit in the first place. Recover our
2236 * original cwnd and ssthresh, and proceed to transmit where
2239 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0) {
2240 TCPSTAT_INC(tcps_sndrexmitbad);
2241 tp->snd_cwnd = tp->snd_cwnd_prev;
2242 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2243 tp->snd_recover = tp->snd_recover_prev;
2244 if (tp->t_flags & TF_WASFRECOVERY)
2245 ENTER_FASTRECOVERY(tp);
2246 tp->snd_nxt = tp->snd_max;
2247 tp->t_badrxtwin = 0; /* XXX probably not required */
2251 * If we have a timestamp reply, update smoothed
2252 * round trip time. If no timestamp is present but
2253 * transmit timer is running and timed sequence
2254 * number was acked, update smoothed round trip time.
2255 * Since we now have an rtt measurement, cancel the
2256 * timer backoff (cf., Phil Karn's retransmit alg.).
2257 * Recompute the initial retransmit timer.
2259 * Some boxes send broken timestamp replies
2260 * during the SYN+ACK phase, ignore
2261 * timestamps of 0 or we could calculate a
2262 * huge RTT and blow up the retransmit timer.
2264 if ((to.to_flags & TOF_TS) != 0 &&
2266 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2267 tp->t_rttlow = ticks - to.to_tsecr;
2268 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2269 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2270 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2271 tp->t_rttlow = ticks - tp->t_rtttime;
2272 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2274 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2277 * If all outstanding data is acked, stop retransmit
2278 * timer and remember to restart (more output or persist).
2279 * If there is more data to be acked, restart retransmit
2280 * timer, using current (possibly backed-off) value.
2282 if (th->th_ack == tp->snd_max) {
2283 tcp_timer_activate(tp, TT_REXMT, 0);
2285 } else if (!tcp_timer_active(tp, TT_PERSIST))
2286 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2289 * If no data (only SYN) was ACK'd,
2290 * skip rest of ACK processing.
2296 * When new data is acked, open the congestion window.
2297 * Method depends on which congestion control state we're
2298 * in (slow start or cong avoid) and if ABC (RFC 3465) is
2301 * slow start: cwnd <= ssthresh
2302 * cong avoid: cwnd > ssthresh
2304 * slow start and ABC (RFC 3465):
2305 * Grow cwnd exponentially by the amount of data
2306 * ACKed capping the max increment per ACK to
2307 * (abc_l_var * maxseg) bytes.
2309 * slow start without ABC (RFC 2581):
2310 * Grow cwnd exponentially by maxseg per ACK.
2312 * cong avoid and ABC (RFC 3465):
2313 * Grow cwnd linearly by maxseg per RTT for each
2314 * cwnd worth of ACKed data.
2316 * cong avoid without ABC (RFC 2581):
2317 * Grow cwnd linearly by approximately maxseg per RTT using
2318 * maxseg^2 / cwnd per ACK as the increment.
2319 * If cwnd > maxseg^2, fix the cwnd increment at 1 byte to
2320 * avoid capping cwnd.
2322 if ((!V_tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2323 !IN_FASTRECOVERY(tp)) {
2324 u_int cw = tp->snd_cwnd;
2325 u_int incr = tp->t_maxseg;
2326 /* In congestion avoidance? */
2327 if (cw > tp->snd_ssthresh) {
2328 if (V_tcp_do_rfc3465) {
2329 tp->t_bytes_acked += acked;
2330 if (tp->t_bytes_acked >= tp->snd_cwnd)
2331 tp->t_bytes_acked -= cw;
2336 incr = max((incr * incr / cw), 1);
2338 * In slow-start with ABC enabled and no RTO in sight?
2339 * (Must not use abc_l_var > 1 if slow starting after an
2340 * RTO. On RTO, snd_nxt = snd_una, so the snd_nxt ==
2341 * snd_max check is sufficient to handle this).
2343 } else if (V_tcp_do_rfc3465 &&
2344 tp->snd_nxt == tp->snd_max)
2346 V_tcp_abc_l_var * tp->t_maxseg);
2347 /* ABC is on by default, so (incr == 0) frequently. */
2349 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2351 SOCKBUF_LOCK(&so->so_snd);
2352 if (acked > so->so_snd.sb_cc) {
2353 tp->snd_wnd -= so->so_snd.sb_cc;
2354 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2357 sbdrop_locked(&so->so_snd, acked);
2358 tp->snd_wnd -= acked;
2361 /* NB: sowwakeup_locked() does an implicit unlock. */
2362 sowwakeup_locked(so);
2363 /* Detect una wraparound. */
2364 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2365 !IN_FASTRECOVERY(tp) &&
2366 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2367 SEQ_LEQ(th->th_ack, tp->snd_recover))
2368 tp->snd_recover = th->th_ack - 1;
2369 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2370 IN_FASTRECOVERY(tp) &&
2371 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2372 EXIT_FASTRECOVERY(tp);
2373 tp->t_bytes_acked = 0;
2375 tp->snd_una = th->th_ack;
2376 if (tp->t_flags & TF_SACK_PERMIT) {
2377 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2378 tp->snd_recover = tp->snd_una;
2380 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2381 tp->snd_nxt = tp->snd_una;
2383 switch (tp->t_state) {
2386 * In FIN_WAIT_1 STATE in addition to the processing
2387 * for the ESTABLISHED state if our FIN is now acknowledged
2388 * then enter FIN_WAIT_2.
2390 case TCPS_FIN_WAIT_1:
2391 if (ourfinisacked) {
2393 * If we can't receive any more
2394 * data, then closing user can proceed.
2395 * Starting the timer is contrary to the
2396 * specification, but if we don't get a FIN
2397 * we'll hang forever.
2400 * we should release the tp also, and use a
2403 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2406 soisdisconnected(so);
2407 timeout = (tcp_fast_finwait2_recycle) ?
2408 tcp_finwait2_timeout : tcp_maxidle;
2409 tcp_timer_activate(tp, TT_2MSL, timeout);
2411 tp->t_state = TCPS_FIN_WAIT_2;
2416 * In CLOSING STATE in addition to the processing for
2417 * the ESTABLISHED state if the ACK acknowledges our FIN
2418 * then enter the TIME-WAIT state, otherwise ignore
2422 if (ourfinisacked) {
2423 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2425 INP_INFO_WUNLOCK(&V_tcbinfo);
2432 * In LAST_ACK, we may still be waiting for data to drain
2433 * and/or to be acked, as well as for the ack of our FIN.
2434 * If our FIN is now acknowledged, delete the TCB,
2435 * enter the closed state and return.
2438 if (ourfinisacked) {
2439 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2448 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2449 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2450 ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2451 INP_WLOCK_ASSERT(tp->t_inpcb);
2454 * Update window information.
2455 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2457 if ((thflags & TH_ACK) &&
2458 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2459 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2460 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2461 /* keep track of pure window updates */
2463 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2464 TCPSTAT_INC(tcps_rcvwinupd);
2465 tp->snd_wnd = tiwin;
2466 tp->snd_wl1 = th->th_seq;
2467 tp->snd_wl2 = th->th_ack;
2468 if (tp->snd_wnd > tp->max_sndwnd)
2469 tp->max_sndwnd = tp->snd_wnd;
2474 * Process segments with URG.
2476 if ((thflags & TH_URG) && th->th_urp &&
2477 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2479 * This is a kludge, but if we receive and accept
2480 * random urgent pointers, we'll crash in
2481 * soreceive. It's hard to imagine someone
2482 * actually wanting to send this much urgent data.
2484 SOCKBUF_LOCK(&so->so_rcv);
2485 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2486 th->th_urp = 0; /* XXX */
2487 thflags &= ~TH_URG; /* XXX */
2488 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2489 goto dodata; /* XXX */
2492 * If this segment advances the known urgent pointer,
2493 * then mark the data stream. This should not happen
2494 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2495 * a FIN has been received from the remote side.
2496 * In these states we ignore the URG.
2498 * According to RFC961 (Assigned Protocols),
2499 * the urgent pointer points to the last octet
2500 * of urgent data. We continue, however,
2501 * to consider it to indicate the first octet
2502 * of data past the urgent section as the original
2503 * spec states (in one of two places).
2505 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2506 tp->rcv_up = th->th_seq + th->th_urp;
2507 so->so_oobmark = so->so_rcv.sb_cc +
2508 (tp->rcv_up - tp->rcv_nxt) - 1;
2509 if (so->so_oobmark == 0)
2510 so->so_rcv.sb_state |= SBS_RCVATMARK;
2512 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2514 SOCKBUF_UNLOCK(&so->so_rcv);
2516 * Remove out of band data so doesn't get presented to user.
2517 * This can happen independent of advancing the URG pointer,
2518 * but if two URG's are pending at once, some out-of-band
2519 * data may creep in... ick.
2521 if (th->th_urp <= (u_long)tlen &&
2522 !(so->so_options & SO_OOBINLINE)) {
2523 /* hdr drop is delayed */
2524 tcp_pulloutofband(so, th, m, drop_hdrlen);
2528 * If no out of band data is expected,
2529 * pull receive urgent pointer along
2530 * with the receive window.
2532 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2533 tp->rcv_up = tp->rcv_nxt;
2536 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2537 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2538 ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2539 INP_WLOCK_ASSERT(tp->t_inpcb);
2542 * Process the segment text, merging it into the TCP sequencing queue,
2543 * and arranging for acknowledgment of receipt if necessary.
2544 * This process logically involves adjusting tp->rcv_wnd as data
2545 * is presented to the user (this happens in tcp_usrreq.c,
2546 * case PRU_RCVD). If a FIN has already been received on this
2547 * connection then we just ignore the text.
2549 if ((tlen || (thflags & TH_FIN)) &&
2550 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2551 tcp_seq save_start = th->th_seq;
2552 m_adj(m, drop_hdrlen); /* delayed header drop */
2554 * Insert segment which includes th into TCP reassembly queue
2555 * with control block tp. Set thflags to whether reassembly now
2556 * includes a segment with FIN. This handles the common case
2557 * inline (segment is the next to be received on an established
2558 * connection, and the queue is empty), avoiding linkage into
2559 * and removal from the queue and repetition of various
2561 * Set DELACK for segments received in order, but ack
2562 * immediately when segments are out of order (so
2563 * fast retransmit can work).
2565 if (th->th_seq == tp->rcv_nxt &&
2566 LIST_EMPTY(&tp->t_segq) &&
2567 TCPS_HAVEESTABLISHED(tp->t_state)) {
2569 tp->t_flags |= TF_DELACK;
2571 tp->t_flags |= TF_ACKNOW;
2572 tp->rcv_nxt += tlen;
2573 thflags = th->th_flags & TH_FIN;
2574 TCPSTAT_INC(tcps_rcvpack);
2575 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2577 SOCKBUF_LOCK(&so->so_rcv);
2578 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2581 sbappendstream_locked(&so->so_rcv, m);
2582 /* NB: sorwakeup_locked() does an implicit unlock. */
2583 sorwakeup_locked(so);
2586 * XXX: Due to the header drop above "th" is
2587 * theoretically invalid by now. Fortunately
2588 * m_adj() doesn't actually frees any mbufs
2589 * when trimming from the head.
2591 thflags = tcp_reass(tp, th, &tlen, m);
2592 tp->t_flags |= TF_ACKNOW;
2594 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2595 tcp_update_sack_list(tp, save_start, save_start + tlen);
2598 * Note the amount of data that peer has sent into
2599 * our window, in order to estimate the sender's
2603 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2611 * If FIN is received ACK the FIN and let the user know
2612 * that the connection is closing.
2614 if (thflags & TH_FIN) {
2615 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2618 * If connection is half-synchronized
2619 * (ie NEEDSYN flag on) then delay ACK,
2620 * so it may be piggybacked when SYN is sent.
2621 * Otherwise, since we received a FIN then no
2622 * more input can be expected, send ACK now.
2624 if (tp->t_flags & TF_NEEDSYN)
2625 tp->t_flags |= TF_DELACK;
2627 tp->t_flags |= TF_ACKNOW;
2630 switch (tp->t_state) {
2633 * In SYN_RECEIVED and ESTABLISHED STATES
2634 * enter the CLOSE_WAIT state.
2636 case TCPS_SYN_RECEIVED:
2637 tp->t_starttime = ticks;
2639 case TCPS_ESTABLISHED:
2640 tp->t_state = TCPS_CLOSE_WAIT;
2644 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2645 * enter the CLOSING state.
2647 case TCPS_FIN_WAIT_1:
2648 tp->t_state = TCPS_CLOSING;
2652 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2653 * starting the time-wait timer, turning off the other
2656 case TCPS_FIN_WAIT_2:
2657 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2658 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2659 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2663 INP_INFO_WUNLOCK(&V_tcbinfo);
2667 if (ti_locked == TI_RLOCKED)
2668 INP_INFO_RUNLOCK(&V_tcbinfo);
2669 else if (ti_locked == TI_WLOCKED)
2670 INP_INFO_WUNLOCK(&V_tcbinfo);
2672 panic("%s: dodata epilogue ti_locked %d", __func__,
2674 ti_locked = TI_UNLOCKED;
2677 if (so->so_options & SO_DEBUG)
2678 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2683 * Return any desired output.
2685 if (needoutput || (tp->t_flags & TF_ACKNOW))
2686 (void) tcp_output(tp);
2689 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2690 __func__, ti_locked));
2691 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2692 INP_WLOCK_ASSERT(tp->t_inpcb);
2694 if (tp->t_flags & TF_DELACK) {
2695 tp->t_flags &= ~TF_DELACK;
2696 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2698 INP_WUNLOCK(tp->t_inpcb);
2702 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2703 ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2706 * Generate an ACK dropping incoming segment if it occupies
2707 * sequence space, where the ACK reflects our state.
2709 * We can now skip the test for the RST flag since all
2710 * paths to this code happen after packets containing
2711 * RST have been dropped.
2713 * In the SYN-RECEIVED state, don't send an ACK unless the
2714 * segment we received passes the SYN-RECEIVED ACK test.
2715 * If it fails send a RST. This breaks the loop in the
2716 * "LAND" DoS attack, and also prevents an ACK storm
2717 * between two listening ports that have been sent forged
2718 * SYN segments, each with the source address of the other.
2720 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2721 (SEQ_GT(tp->snd_una, th->th_ack) ||
2722 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2723 rstreason = BANDLIM_RST_OPENPORT;
2727 if (so->so_options & SO_DEBUG)
2728 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2731 if (ti_locked == TI_RLOCKED)
2732 INP_INFO_RUNLOCK(&V_tcbinfo);
2733 else if (ti_locked == TI_WLOCKED)
2734 INP_INFO_WUNLOCK(&V_tcbinfo);
2736 panic("%s: dropafterack epilogue ti_locked %d", __func__,
2738 ti_locked = TI_UNLOCKED;
2740 tp->t_flags |= TF_ACKNOW;
2741 (void) tcp_output(tp);
2742 INP_WUNLOCK(tp->t_inpcb);
2747 if (ti_locked == TI_RLOCKED)
2748 INP_INFO_RUNLOCK(&V_tcbinfo);
2749 else if (ti_locked == TI_WLOCKED)
2750 INP_INFO_WUNLOCK(&V_tcbinfo);
2752 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2753 ti_locked = TI_UNLOCKED;
2756 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2757 INP_WUNLOCK(tp->t_inpcb);
2759 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2763 if (ti_locked == TI_RLOCKED)
2764 INP_INFO_RUNLOCK(&V_tcbinfo);
2765 else if (ti_locked == TI_WLOCKED)
2766 INP_INFO_WUNLOCK(&V_tcbinfo);
2769 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2771 ti_locked = TI_UNLOCKED;
2774 * Drop space held by incoming segment and return.
2777 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2778 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2782 INP_WUNLOCK(tp->t_inpcb);
2787 * Issue RST and make ACK acceptable to originator of segment.
2788 * The mbuf must still include the original packet header.
2792 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2793 int tlen, int rstreason)
2797 struct ip6_hdr *ip6;
2801 INP_WLOCK_ASSERT(tp->t_inpcb);
2804 /* Don't bother if destination was broadcast/multicast. */
2805 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2808 if (mtod(m, struct ip *)->ip_v == 6) {
2809 ip6 = mtod(m, struct ip6_hdr *);
2810 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2811 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2813 /* IPv6 anycast check is done at tcp6_input() */
2817 ip = mtod(m, struct ip *);
2818 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2819 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2820 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2821 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2825 /* Perform bandwidth limiting. */
2826 if (badport_bandlim(rstreason) < 0)
2829 /* tcp_respond consumes the mbuf chain. */
2830 if (th->th_flags & TH_ACK) {
2831 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2832 th->th_ack, TH_RST);
2834 if (th->th_flags & TH_SYN)
2836 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2837 (tcp_seq)0, TH_RST|TH_ACK);
2845 * Parse TCP options and place in tcpopt.
2848 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2853 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2855 if (opt == TCPOPT_EOL)
2857 if (opt == TCPOPT_NOP)
2863 if (optlen < 2 || optlen > cnt)
2868 if (optlen != TCPOLEN_MAXSEG)
2870 if (!(flags & TO_SYN))
2872 to->to_flags |= TOF_MSS;
2873 bcopy((char *)cp + 2,
2874 (char *)&to->to_mss, sizeof(to->to_mss));
2875 to->to_mss = ntohs(to->to_mss);
2878 if (optlen != TCPOLEN_WINDOW)
2880 if (!(flags & TO_SYN))
2882 to->to_flags |= TOF_SCALE;
2883 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2885 case TCPOPT_TIMESTAMP:
2886 if (optlen != TCPOLEN_TIMESTAMP)
2888 to->to_flags |= TOF_TS;
2889 bcopy((char *)cp + 2,
2890 (char *)&to->to_tsval, sizeof(to->to_tsval));
2891 to->to_tsval = ntohl(to->to_tsval);
2892 bcopy((char *)cp + 6,
2893 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2894 to->to_tsecr = ntohl(to->to_tsecr);
2896 #ifdef TCP_SIGNATURE
2898 * XXX In order to reply to a host which has set the
2899 * TCP_SIGNATURE option in its initial SYN, we have to
2900 * record the fact that the option was observed here
2901 * for the syncache code to perform the correct response.
2903 case TCPOPT_SIGNATURE:
2904 if (optlen != TCPOLEN_SIGNATURE)
2906 to->to_flags |= TOF_SIGNATURE;
2907 to->to_signature = cp + 2;
2910 case TCPOPT_SACK_PERMITTED:
2911 if (optlen != TCPOLEN_SACK_PERMITTED)
2913 if (!(flags & TO_SYN))
2917 to->to_flags |= TOF_SACKPERM;
2920 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2924 to->to_flags |= TOF_SACK;
2925 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2926 to->to_sacks = cp + 2;
2927 TCPSTAT_INC(tcps_sack_rcv_blocks);
2936 * Pull out of band byte out of a segment so
2937 * it doesn't appear in the user's data queue.
2938 * It is still reflected in the segment length for
2939 * sequencing purposes.
2942 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2945 int cnt = off + th->th_urp - 1;
2948 if (m->m_len > cnt) {
2949 char *cp = mtod(m, caddr_t) + cnt;
2950 struct tcpcb *tp = sototcpcb(so);
2952 INP_WLOCK_ASSERT(tp->t_inpcb);
2955 tp->t_oobflags |= TCPOOB_HAVEDATA;
2956 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2958 if (m->m_flags & M_PKTHDR)
2967 panic("tcp_pulloutofband");
2971 * Collect new round-trip time estimate
2972 * and update averages and current timeout.
2975 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2979 INP_WLOCK_ASSERT(tp->t_inpcb);
2981 TCPSTAT_INC(tcps_rttupdated);
2983 if (tp->t_srtt != 0) {
2985 * srtt is stored as fixed point with 5 bits after the
2986 * binary point (i.e., scaled by 8). The following magic
2987 * is equivalent to the smoothing algorithm in rfc793 with
2988 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2989 * point). Adjust rtt to origin 0.
2991 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2992 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2994 if ((tp->t_srtt += delta) <= 0)
2998 * We accumulate a smoothed rtt variance (actually, a
2999 * smoothed mean difference), then set the retransmit
3000 * timer to smoothed rtt + 4 times the smoothed variance.
3001 * rttvar is stored as fixed point with 4 bits after the
3002 * binary point (scaled by 16). The following is
3003 * equivalent to rfc793 smoothing with an alpha of .75
3004 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3005 * rfc793's wired-in beta.
3009 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3010 if ((tp->t_rttvar += delta) <= 0)
3012 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3013 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3016 * No rtt measurement yet - use the unsmoothed rtt.
3017 * Set the variance to half the rtt (so our first
3018 * retransmit happens at 3*rtt).
3020 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3021 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3022 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3028 * the retransmit should happen at rtt + 4 * rttvar.
3029 * Because of the way we do the smoothing, srtt and rttvar
3030 * will each average +1/2 tick of bias. When we compute
3031 * the retransmit timer, we want 1/2 tick of rounding and
3032 * 1 extra tick because of +-1/2 tick uncertainty in the
3033 * firing of the timer. The bias will give us exactly the
3034 * 1.5 tick we need. But, because the bias is
3035 * statistical, we have to test that we don't drop below
3036 * the minimum feasible timer (which is 2 ticks).
3038 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3039 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3042 * We received an ack for a packet that wasn't retransmitted;
3043 * it is probably safe to discard any error indications we've
3044 * received recently. This isn't quite right, but close enough
3045 * for now (a route might have failed after we sent a segment,
3046 * and the return path might not be symmetrical).
3048 tp->t_softerror = 0;
3052 * Determine a reasonable value for maxseg size.
3053 * If the route is known, check route for mtu.
3054 * If none, use an mss that can be handled on the outgoing
3055 * interface without forcing IP to fragment; if bigger than
3056 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3057 * to utilize large mbufs. If no route is found, route has no mtu,
3058 * or the destination isn't local, use a default, hopefully conservative
3059 * size (usually 512 or the default IP max size, but no more than the mtu
3060 * of the interface), as we can't discover anything about intervening
3061 * gateways or networks. We also initialize the congestion/slow start
3062 * window to be a single segment if the destination isn't local.
3063 * While looking at the routing entry, we also initialize other path-dependent
3064 * parameters from pre-set or cached values in the routing entry.
3066 * Also take into account the space needed for options that we
3067 * send regularly. Make maxseg shorter by that amount to assure
3068 * that we can send maxseg amount of data even when the options
3069 * are present. Store the upper limit of the length of options plus
3072 * In case of T/TCP, we call this routine during implicit connection
3073 * setup as well (offer = -1), to initialize maxseg from the cached
3076 * NOTE that this routine is only called when we process an incoming
3077 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3080 tcp_mss_update(struct tcpcb *tp, int offer,
3081 struct hc_metrics_lite *metricptr, int *mtuflags)
3085 struct inpcb *inp = tp->t_inpcb;
3086 struct hc_metrics_lite metrics;
3087 int origoffer = offer;
3089 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3090 size_t min_protoh = isipv6 ?
3091 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3092 sizeof (struct tcpiphdr);
3094 const size_t min_protoh = sizeof(struct tcpiphdr);
3097 INP_WLOCK_ASSERT(tp->t_inpcb);
3102 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3103 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3107 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3108 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3112 * No route to sender, stay with default mss and return.
3116 * In case we return early we need to initialize metrics
3117 * to a defined state as tcp_hc_get() would do for us
3118 * if there was no cache hit.
3120 if (metricptr != NULL)
3121 bzero(metricptr, sizeof(struct hc_metrics_lite));
3125 /* What have we got? */
3129 * Offer == 0 means that there was no MSS on the SYN
3130 * segment, in this case we use tcp_mssdflt as
3131 * already assigned to t_maxopd above.
3133 offer = tp->t_maxopd;
3138 * Offer == -1 means that we didn't receive SYN yet.
3144 * Prevent DoS attack with too small MSS. Round up
3145 * to at least minmss.
3147 offer = max(offer, V_tcp_minmss);
3151 * rmx information is now retrieved from tcp_hostcache.
3153 tcp_hc_get(&inp->inp_inc, &metrics);
3154 if (metricptr != NULL)
3155 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3158 * If there's a discovered mtu int tcp hostcache, use it
3159 * else, use the link mtu.
3161 if (metrics.rmx_mtu)
3162 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3166 mss = maxmtu - min_protoh;
3167 if (!V_path_mtu_discovery &&
3168 !in6_localaddr(&inp->in6p_faddr))
3169 mss = min(mss, V_tcp_v6mssdflt);
3173 mss = maxmtu - min_protoh;
3174 if (!V_path_mtu_discovery &&
3175 !in_localaddr(inp->inp_faddr))
3176 mss = min(mss, V_tcp_mssdflt);
3179 * XXX - The above conditional (mss = maxmtu - min_protoh)
3180 * probably violates the TCP spec.
3181 * The problem is that, since we don't know the
3182 * other end's MSS, we are supposed to use a conservative
3183 * default. But, if we do that, then MTU discovery will
3184 * never actually take place, because the conservative
3185 * default is much less than the MTUs typically seen
3186 * on the Internet today. For the moment, we'll sweep
3187 * this under the carpet.
3189 * The conservative default might not actually be a problem
3190 * if the only case this occurs is when sending an initial
3191 * SYN with options and data to a host we've never talked
3192 * to before. Then, they will reply with an MSS value which
3193 * will get recorded and the new parameters should get
3194 * recomputed. For Further Study.
3197 mss = min(mss, offer);
3200 * Sanity check: make sure that maxopd will be large
3201 * enough to allow some data on segments even if the
3202 * all the option space is used (40bytes). Otherwise
3203 * funny things may happen in tcp_output.
3208 * maxopd stores the maximum length of data AND options
3209 * in a segment; maxseg is the amount of data in a normal
3210 * segment. We need to store this value (maxopd) apart
3211 * from maxseg, because now every segment carries options
3212 * and thus we normally have somewhat less data in segments.
3217 * origoffer==-1 indicates that no segments were received yet.
3218 * In this case we just guess.
3220 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3222 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3223 mss -= TCPOLEN_TSTAMP_APPA;
3225 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3227 mss &= ~(MCLBYTES-1);
3230 mss = mss / MCLBYTES * MCLBYTES;
3236 tcp_mss(struct tcpcb *tp, int offer)
3242 struct hc_metrics_lite metrics;
3247 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3249 tcp_mss_update(tp, offer, &metrics, &mtuflags);
3254 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3258 * If there's a pipesize, change the socket buffer to that size,
3259 * don't change if sb_hiwat is different than default (then it
3260 * has been changed on purpose with setsockopt).
3261 * Make the socket buffers an integral number of mss units;
3262 * if the mss is larger than the socket buffer, decrease the mss.
3264 so = inp->inp_socket;
3265 SOCKBUF_LOCK(&so->so_snd);
3266 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3267 bufsize = metrics.rmx_sendpipe;
3269 bufsize = so->so_snd.sb_hiwat;
3273 bufsize = roundup(bufsize, mss);
3274 if (bufsize > sb_max)
3276 if (bufsize > so->so_snd.sb_hiwat)
3277 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3279 SOCKBUF_UNLOCK(&so->so_snd);
3282 SOCKBUF_LOCK(&so->so_rcv);
3283 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3284 bufsize = metrics.rmx_recvpipe;
3286 bufsize = so->so_rcv.sb_hiwat;
3287 if (bufsize > mss) {
3288 bufsize = roundup(bufsize, mss);
3289 if (bufsize > sb_max)
3291 if (bufsize > so->so_rcv.sb_hiwat)
3292 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3294 SOCKBUF_UNLOCK(&so->so_rcv);
3296 * While we're here, check the others too.
3298 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3300 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3301 TCPSTAT_INC(tcps_usedrtt);
3302 if (metrics.rmx_rttvar) {
3303 tp->t_rttvar = metrics.rmx_rttvar;
3304 TCPSTAT_INC(tcps_usedrttvar);
3306 /* default variation is +- 1 rtt */
3308 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3310 TCPT_RANGESET(tp->t_rxtcur,
3311 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3312 tp->t_rttmin, TCPTV_REXMTMAX);
3314 if (metrics.rmx_ssthresh) {
3316 * There's some sort of gateway or interface
3317 * buffer limit on the path. Use this to set
3318 * the slow start threshhold, but set the
3319 * threshold to no less than 2*mss.
3321 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3322 TCPSTAT_INC(tcps_usedssthresh);
3324 if (metrics.rmx_bandwidth)
3325 tp->snd_bandwidth = metrics.rmx_bandwidth;
3328 * Set the slow-start flight size depending on whether this
3329 * is a local network or not.
3331 * Extend this so we cache the cwnd too and retrieve it here.
3332 * Make cwnd even bigger than RFC3390 suggests but only if we
3333 * have previous experience with the remote host. Be careful
3334 * not make cwnd bigger than remote receive window or our own
3335 * send socket buffer. Maybe put some additional upper bound
3336 * on the retrieved cwnd. Should do incremental updates to
3337 * hostcache when cwnd collapses so next connection doesn't
3338 * overloads the path again.
3340 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3341 * We currently check only in syncache_socket for that.
3343 #define TCP_METRICS_CWND
3344 #ifdef TCP_METRICS_CWND
3345 if (metrics.rmx_cwnd)
3346 tp->snd_cwnd = max(mss,
3347 min(metrics.rmx_cwnd / 2,
3348 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3351 if (V_tcp_do_rfc3390)
3352 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3354 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3355 (!isipv6 && in_localaddr(inp->inp_faddr)))
3357 else if (in_localaddr(inp->inp_faddr))
3359 tp->snd_cwnd = mss * V_ss_fltsz_local;
3361 tp->snd_cwnd = mss * V_ss_fltsz;
3363 /* Check the interface for TSO capabilities. */
3364 if (mtuflags & CSUM_TSO)
3365 tp->t_flags |= TF_TSO;
3369 * Determine the MSS option to send on an outgoing SYN.
3372 tcp_mssopt(struct in_conninfo *inc)
3379 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3382 if (inc->inc_flags & INC_ISIPV6) {
3383 mss = V_tcp_v6mssdflt;
3384 maxmtu = tcp_maxmtu6(inc, NULL);
3385 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3386 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3390 mss = V_tcp_mssdflt;
3391 maxmtu = tcp_maxmtu(inc, NULL);
3392 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3393 min_protoh = sizeof(struct tcpiphdr);
3395 if (maxmtu && thcmtu)
3396 mss = min(maxmtu, thcmtu) - min_protoh;
3397 else if (maxmtu || thcmtu)
3398 mss = max(maxmtu, thcmtu) - min_protoh;
3405 * On a partial ack arrives, force the retransmission of the
3406 * next unacknowledged segment. Do not clear tp->t_dupacks.
3407 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3411 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3413 tcp_seq onxt = tp->snd_nxt;
3414 u_long ocwnd = tp->snd_cwnd;
3416 INP_WLOCK_ASSERT(tp->t_inpcb);
3418 tcp_timer_activate(tp, TT_REXMT, 0);
3420 tp->snd_nxt = th->th_ack;
3422 * Set snd_cwnd to one segment beyond acknowledged offset.
3423 * (tp->snd_una has not yet been updated when this function is called.)
3425 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3426 tp->t_flags |= TF_ACKNOW;
3427 (void) tcp_output(tp);
3428 tp->snd_cwnd = ocwnd;
3429 if (SEQ_GT(onxt, tp->snd_nxt))
3432 * Partial window deflation. Relies on fact that tp->snd_una
3435 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3436 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3439 tp->snd_cwnd += tp->t_maxseg;