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
33 #include "opt_ipfw.h" /* for ipfw_fwd */
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
38 #include "opt_tcpdebug.h"
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
44 #include <sys/proc.h> /* for proc0 declaration */
45 #include <sys/protosw.h>
46 #include <sys/signalvar.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/systm.h>
53 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
58 #include <net/route.h>
60 #define TCPSTATES /* for logging */
62 #include <netinet/in.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/in_var.h>
66 #include <netinet/ip.h>
67 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
68 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
69 #include <netinet/ip_var.h>
70 #include <netinet/ip_options.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <netinet6/in6_pcb.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/nd6.h>
76 #include <netinet/tcp.h>
77 #include <netinet/tcp_fsm.h>
78 #include <netinet/tcp_seq.h>
79 #include <netinet/tcp_timer.h>
80 #include <netinet/tcp_var.h>
81 #include <netinet6/tcp6_var.h>
82 #include <netinet/tcpip.h>
83 #include <netinet/tcp_syncache.h>
85 #include <netinet/tcp_debug.h>
89 #include <netipsec/ipsec.h>
90 #include <netipsec/ipsec6.h>
93 #include <machine/in_cksum.h>
95 #include <security/mac/mac_framework.h>
97 static const int tcprexmtthresh = 3;
99 struct tcpstat tcpstat;
100 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
101 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
103 int tcp_log_in_vain = 0;
104 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
105 &tcp_log_in_vain, 0, "Log all incoming TCP segments to closed ports");
107 static int blackhole = 0;
108 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
109 &blackhole, 0, "Do not send RST on segments to closed ports");
111 int tcp_delack_enabled = 1;
112 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
113 &tcp_delack_enabled, 0,
114 "Delay ACK to try and piggyback it onto a data packet");
116 static int drop_synfin = 0;
117 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
118 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
120 static int tcp_do_rfc3042 = 1;
121 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
122 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
124 static int tcp_do_rfc3390 = 1;
125 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
127 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
129 static int tcp_insecure_rst = 0;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
131 &tcp_insecure_rst, 0,
132 "Follow the old (insecure) criteria for accepting RST packets");
134 int tcp_do_autorcvbuf = 1;
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
136 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
138 int tcp_autorcvbuf_inc = 16*1024;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
140 &tcp_autorcvbuf_inc, 0,
141 "Incrementor step size of automatic receive buffer");
143 int tcp_autorcvbuf_max = 256*1024;
144 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
145 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
147 struct inpcbhead tcb;
148 #define tcb6 tcb /* for KAME src sync over BSD*'s */
149 struct inpcbinfo tcbinfo;
151 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
152 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
153 struct socket *, struct tcpcb *, int, int);
154 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
155 struct tcpcb *, int, int);
156 static void tcp_pulloutofband(struct socket *,
157 struct tcphdr *, struct mbuf *, int);
158 static void tcp_xmit_timer(struct tcpcb *, int);
159 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
161 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
163 #define ND6_HINT(tp) \
165 if ((tp) && (tp)->t_inpcb && \
166 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
167 nd6_nud_hint(NULL, NULL, 0); \
174 * Indicate whether this ack should be delayed. We can delay the ack if
175 * - there is no delayed ack timer in progress and
176 * - our last ack wasn't a 0-sized window. We never want to delay
177 * the ack that opens up a 0-sized window and
178 * - delayed acks are enabled or
179 * - this is a half-synchronized T/TCP connection.
181 #define DELAY_ACK(tp) \
182 ((!tcp_timer_active(tp, TT_DELACK) && \
183 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
184 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
188 * TCP input handling is split into multiple parts:
189 * tcp6_input is a thin wrapper around tcp_input for the extended
190 * ip6_protox[] call format in ip6_input
191 * tcp_input handles primary segment validation, inpcb lookup and
192 * SYN processing on listen sockets
193 * tcp_do_segment processes the ACK and text of the segment for
194 * establishing, established and closing connections
198 tcp6_input(struct mbuf **mp, int *offp, int proto)
200 struct mbuf *m = *mp;
201 struct in6_ifaddr *ia6;
203 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
206 * draft-itojun-ipv6-tcp-to-anycast
207 * better place to put this in?
209 ia6 = ip6_getdstifaddr(m);
210 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
213 ip6 = mtod(m, struct ip6_hdr *);
214 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
215 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
225 tcp_input(struct mbuf *m, int off0)
228 struct ip *ip = NULL;
230 struct inpcb *inp = NULL;
231 struct tcpcb *tp = NULL;
232 struct socket *so = NULL;
238 int rstreason = 0; /* For badport_bandlim accounting purposes */
239 #ifdef IPFIREWALL_FORWARD
240 struct m_tag *fwd_tag;
243 struct ip6_hdr *ip6 = NULL;
246 const void *ip6 = NULL;
247 const int isipv6 = 0;
249 struct tcpopt to; /* options in this segment */
250 char *s = NULL; /* address and port logging */
254 * The size of tcp_saveipgen must be the size of the max ip header,
257 u_char tcp_saveipgen[IP6_HDR_LEN];
258 struct tcphdr tcp_savetcp;
263 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
267 tcpstat.tcps_rcvtotal++;
271 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
272 ip6 = mtod(m, struct ip6_hdr *);
273 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
274 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
275 tcpstat.tcps_rcvbadsum++;
278 th = (struct tcphdr *)((caddr_t)ip6 + off0);
281 * Be proactive about unspecified IPv6 address in source.
282 * As we use all-zero to indicate unbounded/unconnected pcb,
283 * unspecified IPv6 address can be used to confuse us.
285 * Note that packets with unspecified IPv6 destination is
286 * already dropped in ip6_input.
288 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
293 th = NULL; /* XXX: Avoid compiler warning. */
297 * Get IP and TCP header together in first mbuf.
298 * Note: IP leaves IP header in first mbuf.
300 if (off0 > sizeof (struct ip)) {
301 ip_stripoptions(m, (struct mbuf *)0);
302 off0 = sizeof(struct ip);
304 if (m->m_len < sizeof (struct tcpiphdr)) {
305 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
307 tcpstat.tcps_rcvshort++;
311 ip = mtod(m, struct ip *);
312 ipov = (struct ipovly *)ip;
313 th = (struct tcphdr *)((caddr_t)ip + off0);
316 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
317 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
318 th->th_sum = m->m_pkthdr.csum_data;
320 th->th_sum = in_pseudo(ip->ip_src.s_addr,
322 htonl(m->m_pkthdr.csum_data +
325 th->th_sum ^= 0xffff;
327 ipov->ih_len = (u_short)tlen;
328 ipov->ih_len = htons(ipov->ih_len);
332 * Checksum extended TCP header and data.
334 len = sizeof (struct ip) + tlen;
335 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
336 ipov->ih_len = (u_short)tlen;
337 ipov->ih_len = htons(ipov->ih_len);
338 th->th_sum = in_cksum(m, len);
341 tcpstat.tcps_rcvbadsum++;
344 /* Re-initialization for later version check */
345 ip->ip_v = IPVERSION;
349 * Check that TCP offset makes sense,
350 * pull out TCP options and adjust length. XXX
352 off = th->th_off << 2;
353 if (off < sizeof (struct tcphdr) || off > tlen) {
354 tcpstat.tcps_rcvbadoff++;
357 tlen -= off; /* tlen is used instead of ti->ti_len */
358 if (off > sizeof (struct tcphdr)) {
361 IP6_EXTHDR_CHECK(m, off0, off, );
362 ip6 = mtod(m, struct ip6_hdr *);
363 th = (struct tcphdr *)((caddr_t)ip6 + off0);
366 if (m->m_len < sizeof(struct ip) + off) {
367 if ((m = m_pullup(m, sizeof (struct ip) + off))
369 tcpstat.tcps_rcvshort++;
372 ip = mtod(m, struct ip *);
373 ipov = (struct ipovly *)ip;
374 th = (struct tcphdr *)((caddr_t)ip + off0);
377 optlen = off - sizeof (struct tcphdr);
378 optp = (u_char *)(th + 1);
380 thflags = th->th_flags;
383 * Convert TCP protocol specific fields to host format.
385 th->th_seq = ntohl(th->th_seq);
386 th->th_ack = ntohl(th->th_ack);
387 th->th_win = ntohs(th->th_win);
388 th->th_urp = ntohs(th->th_urp);
391 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
393 drop_hdrlen = off0 + off;
396 * Locate pcb for segment.
398 INP_INFO_WLOCK(&tcbinfo);
400 INP_INFO_WLOCK_ASSERT(&tcbinfo);
401 #ifdef IPFIREWALL_FORWARD
403 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
405 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
407 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
408 struct sockaddr_in *next_hop;
410 next_hop = (struct sockaddr_in *)(fwd_tag+1);
412 * Transparently forwarded. Pretend to be the destination.
413 * already got one like this?
415 inp = in_pcblookup_hash(&tcbinfo,
416 ip->ip_src, th->th_sport,
417 ip->ip_dst, th->th_dport,
418 0, m->m_pkthdr.rcvif);
420 /* It's new. Try to find the ambushing socket. */
421 inp = in_pcblookup_hash(&tcbinfo,
422 ip->ip_src, th->th_sport,
425 ntohs(next_hop->sin_port) :
430 /* Remove the tag from the packet. We don't need it anymore. */
431 m_tag_delete(m, fwd_tag);
433 #endif /* IPFIREWALL_FORWARD */
437 inp = in6_pcblookup_hash(&tcbinfo,
438 &ip6->ip6_src, th->th_sport,
439 &ip6->ip6_dst, th->th_dport,
444 inp = in_pcblookup_hash(&tcbinfo,
445 ip->ip_src, th->th_sport,
446 ip->ip_dst, th->th_dport,
453 if (isipv6 && inp != NULL && ipsec6_in_reject(m, inp)) {
454 ipsec6stat.in_polvio++;
458 if (inp != NULL && ipsec4_in_reject(m, inp)) {
459 ipsec4stat.in_polvio++;
465 * If the INPCB does not exist then all data in the incoming
466 * segment is discarded and an appropriate RST is sent back.
470 * Log communication attempts to ports that are not
473 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
474 tcp_log_in_vain == 2) {
475 if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
476 log(LOG_INFO, "%s; %s: Connection attempt "
477 "to closed port\n", s, __func__);
480 * When blackholing do not respond with a RST but
481 * completely ignore the segment and drop it.
483 if ((blackhole == 1 && (thflags & TH_SYN)) ||
487 rstreason = BANDLIM_RST_CLOSEDPORT;
493 * Check the minimum TTL for socket.
495 if (inp->inp_ip_minttl != 0) {
497 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
501 if (inp->inp_ip_minttl > ip->ip_ttl)
506 * A previous connection in TIMEWAIT state is supposed to catch
507 * stray or duplicate segments arriving late. If this segment
508 * was a legitimate new connection attempt the old INPCB gets
509 * removed and we can try again to find a listening socket.
511 if (inp->inp_vflag & INP_TIMEWAIT) {
512 if (thflags & TH_SYN)
513 tcp_dooptions(&to, optp, optlen, TO_SYN);
515 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
517 if (tcp_twcheck(inp, &to, th, m, tlen))
519 INP_INFO_WUNLOCK(&tcbinfo);
523 * The TCPCB may no longer exist if the connection is winding
524 * down or it is in the CLOSED state. Either way we drop the
525 * segment and send an appropriate response.
528 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
529 rstreason = BANDLIM_RST_CLOSEDPORT;
534 INP_LOCK_ASSERT(inp);
535 if (mac_check_inpcb_deliver(inp, m))
538 so = inp->inp_socket;
539 KASSERT(so != NULL, ("%s: so == NULL", __func__));
541 if (so->so_options & SO_DEBUG) {
542 ostate = tp->t_state;
545 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
548 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
553 * When the socket is accepting connections (the INPCB is in LISTEN
554 * state) we look into the SYN cache if this is a new connection
555 * attempt or the completion of a previous one.
557 if (so->so_options & SO_ACCEPTCONN) {
558 struct in_conninfo inc;
560 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
561 "tp not listening", __func__));
563 bzero(&inc, sizeof(inc));
564 inc.inc_isipv6 = isipv6;
567 inc.inc6_faddr = ip6->ip6_src;
568 inc.inc6_laddr = ip6->ip6_dst;
572 inc.inc_faddr = ip->ip_src;
573 inc.inc_laddr = ip->ip_dst;
575 inc.inc_fport = th->th_sport;
576 inc.inc_lport = th->th_dport;
579 * Check for an existing connection attempt in syncache if
580 * the flag is only ACK. A successful lookup creates a new
581 * socket appended to the listen queue in SYN_RECEIVED state.
583 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
585 * Parse the TCP options here because
586 * syncookies need access to the reflected
589 tcp_dooptions(&to, optp, optlen, 0);
591 * NB: syncache_expand() doesn't unlock
592 * inp and tcpinfo locks.
594 if (!syncache_expand(&inc, &to, th, &so, m)) {
596 * No syncache entry or ACK was not
597 * for our SYN/ACK. Send a RST.
598 * NB: syncache did its own logging
599 * of the failure cause.
601 rstreason = BANDLIM_RST_OPENPORT;
606 * We completed the 3-way handshake
607 * but could not allocate a socket
608 * either due to memory shortage,
609 * listen queue length limits or
610 * global socket limits. Send RST
611 * or wait and have the remote end
612 * retransmit the ACK for another
615 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
616 log(LOG_DEBUG, "%s; %s: Listen socket: "
617 "Socket allocation failed due to "
618 "limits or memory shortage, %s\n",
619 s, __func__, (tcp_sc_rst_sock_fail ?
620 "sending RST" : "try again"));
621 if (tcp_sc_rst_sock_fail) {
622 rstreason = BANDLIM_UNLIMITED;
628 * Socket is created in state SYN_RECEIVED.
629 * Unlock the listen socket, lock the newly
630 * created socket and update the tp variable.
632 INP_UNLOCK(inp); /* listen socket */
634 INP_LOCK(inp); /* new connection */
636 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
639 * Process the segment and the data it
640 * contains. tcp_do_segment() consumes
641 * the mbuf chain and unlocks the inpcb.
643 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
644 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
648 * Segment flag validation for new connection attempts:
650 * Our (SYN|ACK) response was rejected.
651 * Check with syncache and remove entry to prevent
654 * NB: syncache_chkrst does its own logging of failure
657 if (thflags & TH_RST) {
658 syncache_chkrst(&inc, th);
662 * We can't do anything without SYN.
664 if ((thflags & TH_SYN) == 0) {
665 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
666 log(LOG_DEBUG, "%s; %s: Listen socket: "
667 "SYN is missing, segment ignored\n",
669 tcpstat.tcps_badsyn++;
673 * (SYN|ACK) is bogus on a listen socket.
675 if (thflags & TH_ACK) {
676 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
677 log(LOG_DEBUG, "%s; %s: Listen socket: "
678 "SYN|ACK invalid, segment rejected\n",
680 syncache_badack(&inc); /* XXX: Not needed! */
681 tcpstat.tcps_badsyn++;
682 rstreason = BANDLIM_RST_OPENPORT;
686 * If the drop_synfin option is enabled, drop all
687 * segments with both the SYN and FIN bits set.
688 * This prevents e.g. nmap from identifying the
690 * XXX: Poor reasoning. nmap has other methods
691 * and is constantly refining its stack detection
693 * XXX: This is a violation of the TCP specification
694 * and was used by RFC1644.
696 if ((thflags & TH_FIN) && drop_synfin) {
697 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
698 log(LOG_DEBUG, "%s; %s: Listen socket: "
699 "SYN|FIN segment ignored (based on "
700 "sysctl setting)\n", s, __func__);
701 tcpstat.tcps_badsyn++;
705 * Segment's flags are (SYN) or (SYN|FIN).
707 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
708 * as they do not affect the state of the TCP FSM.
709 * The data pointed to by TH_URG and th_urp is ignored.
711 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
712 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
713 KASSERT(thflags & (TH_SYN),
714 ("%s: Listen socket: TH_SYN not set", __func__));
717 * If deprecated address is forbidden,
718 * we do not accept SYN to deprecated interface
719 * address to prevent any new inbound connection from
720 * getting established.
721 * When we do not accept SYN, we send a TCP RST,
722 * with deprecated source address (instead of dropping
723 * it). We compromise it as it is much better for peer
724 * to send a RST, and RST will be the final packet
727 * If we do not forbid deprecated addresses, we accept
728 * the SYN packet. RFC2462 does not suggest dropping
730 * If we decipher RFC2462 5.5.4, it says like this:
731 * 1. use of deprecated addr with existing
732 * communication is okay - "SHOULD continue to be
734 * 2. use of it with new communication:
735 * (2a) "SHOULD NOT be used if alternate address
736 * with sufficient scope is available"
737 * (2b) nothing mentioned otherwise.
738 * Here we fall into (2b) case as we have no choice in
739 * our source address selection - we must obey the peer.
741 * The wording in RFC2462 is confusing, and there are
742 * multiple description text for deprecated address
743 * handling - worse, they are not exactly the same.
744 * I believe 5.5.4 is the best one, so we follow 5.5.4.
746 if (isipv6 && !ip6_use_deprecated) {
747 struct in6_ifaddr *ia6;
749 if ((ia6 = ip6_getdstifaddr(m)) &&
750 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
751 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
752 log(LOG_DEBUG, "%s; %s: Listen socket: "
753 "Connection attempt to deprecated "
754 "IPv6 address rejected\n",
756 rstreason = BANDLIM_RST_OPENPORT;
762 * Basic sanity checks on incoming SYN requests:
763 * Don't respond if the destination is a link layer
764 * broadcast according to RFC1122 4.2.3.10, p. 104.
765 * If it is from this socket it must be forged.
766 * Don't respond if the source or destination is a
767 * global or subnet broad- or multicast address.
768 * Note that it is quite possible to receive unicast
769 * link-layer packets with a broadcast IP address. Use
770 * in_broadcast() to find them.
772 if (m->m_flags & (M_BCAST|M_MCAST)) {
773 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
774 log(LOG_DEBUG, "%s; %s: Listen socket: "
775 "Connection attempt from broad- or multicast "
776 "link layer address ignored\n", s, __func__);
781 if (th->th_dport == th->th_sport &&
782 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
783 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
784 log(LOG_DEBUG, "%s; %s: Listen socket: "
785 "Connection attempt to/from self "
786 "ignored\n", s, __func__);
789 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
790 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
791 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
792 log(LOG_DEBUG, "%s; %s: Listen socket: "
793 "Connection attempt from/to multicast "
794 "address ignored\n", s, __func__);
799 if (th->th_dport == th->th_sport &&
800 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
801 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
802 log(LOG_DEBUG, "%s; %s: Listen socket: "
803 "Connection attempt from/to self "
804 "ignored\n", s, __func__);
807 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
808 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
809 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
810 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
811 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
812 log(LOG_DEBUG, "%s; %s: Listen socket: "
813 "Connection attempt from/to broad- "
814 "or multicast address ignored\n",
820 * SYN appears to be valid. Create compressed TCP state
824 if (so->so_options & SO_DEBUG)
825 tcp_trace(TA_INPUT, ostate, tp,
826 (void *)tcp_saveipgen, &tcp_savetcp, 0);
828 tcp_dooptions(&to, optp, optlen, TO_SYN);
829 syncache_add(&inc, &to, th, inp, &so, m);
831 * Entry added to syncache and mbuf consumed.
832 * Everything already unlocked by syncache_add().
834 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
839 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
840 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
841 * the inpcb, and unlocks pcbinfo.
843 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
844 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
848 INP_INFO_WLOCK_ASSERT(&tcbinfo);
849 tcp_dropwithreset(m, th, tp, tlen, rstreason);
850 m = NULL; /* mbuf chain got consumed. */
852 INP_INFO_WLOCK_ASSERT(&tcbinfo);
855 INP_INFO_WUNLOCK(&tcbinfo);
857 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
866 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
867 struct tcpcb *tp, int drop_hdrlen, int tlen)
869 int thflags, acked, ourfinisacked, needoutput = 0;
871 int rstreason, todrop, win;
877 * The size of tcp_saveipgen must be the size of the max ip header,
880 u_char tcp_saveipgen[IP6_HDR_LEN];
881 struct tcphdr tcp_savetcp;
884 thflags = th->th_flags;
886 INP_INFO_WLOCK_ASSERT(&tcbinfo);
887 INP_LOCK_ASSERT(tp->t_inpcb);
888 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
890 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
894 * Segment received on connection.
895 * Reset idle time and keep-alive timer.
896 * XXX: This should be done after segment
897 * validation to ignore broken/spoofed segs.
899 tp->t_rcvtime = ticks;
900 if (TCPS_HAVEESTABLISHED(tp->t_state))
901 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
904 * Unscale the window into a 32-bit value.
905 * For the SYN_SENT state the scale is zero.
907 tiwin = th->th_win << tp->snd_scale;
910 * Parse options on any incoming segment.
912 tcp_dooptions(&to, (u_char *)(th + 1),
913 (th->th_off << 2) - sizeof(struct tcphdr),
914 (thflags & TH_SYN) ? TO_SYN : 0);
917 * If echoed timestamp is later than the current time,
918 * fall back to non RFC1323 RTT calculation. Normalize
919 * timestamp if syncookies were used when this connection
922 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
923 to.to_tsecr -= tp->ts_offset;
924 if (TSTMP_GT(to.to_tsecr, ticks))
929 * Process options only when we get SYN/ACK back. The SYN case
930 * for incoming connections is handled in tcp_syncache.
931 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
932 * or <SYN,ACK>) segment itself is never scaled.
933 * XXX this is traditional behavior, may need to be cleaned up.
935 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
936 if ((to.to_flags & TOF_SCALE) &&
937 (tp->t_flags & TF_REQ_SCALE)) {
938 tp->t_flags |= TF_RCVD_SCALE;
939 tp->snd_scale = to.to_wscale;
942 * Initial send window. It will be updated with
943 * the next incoming segment to the scaled value.
945 tp->snd_wnd = th->th_win;
946 if (to.to_flags & TOF_TS) {
947 tp->t_flags |= TF_RCVD_TSTMP;
948 tp->ts_recent = to.to_tsval;
949 tp->ts_recent_age = ticks;
951 if (to.to_flags & TOF_MSS)
952 tcp_mss(tp, to.to_mss);
953 if ((tp->t_flags & TF_SACK_PERMIT) &&
954 (to.to_flags & TOF_SACKPERM) == 0)
955 tp->t_flags &= ~TF_SACK_PERMIT;
959 * Header prediction: check for the two common cases
960 * of a uni-directional data xfer. If the packet has
961 * no control flags, is in-sequence, the window didn't
962 * change and we're not retransmitting, it's a
963 * candidate. If the length is zero and the ack moved
964 * forward, we're the sender side of the xfer. Just
965 * free the data acked & wake any higher level process
966 * that was blocked waiting for space. If the length
967 * is non-zero and the ack didn't move, we're the
968 * receiver side. If we're getting packets in-order
969 * (the reassembly queue is empty), add the data to
970 * the socket buffer and note that we need a delayed ack.
971 * Make sure that the hidden state-flags are also off.
972 * Since we check for TCPS_ESTABLISHED first, it can only
975 if (tp->t_state == TCPS_ESTABLISHED &&
976 th->th_seq == tp->rcv_nxt &&
977 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
978 tp->snd_nxt == tp->snd_max &&
979 tiwin && tiwin == tp->snd_wnd &&
980 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
981 LIST_EMPTY(&tp->t_segq) &&
982 ((to.to_flags & TOF_TS) == 0 ||
983 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
986 * If last ACK falls within this segment's sequence numbers,
987 * record the timestamp.
988 * NOTE that the test is modified according to the latest
989 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
991 if ((to.to_flags & TOF_TS) != 0 &&
992 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
993 tp->ts_recent_age = ticks;
994 tp->ts_recent = to.to_tsval;
998 if (SEQ_GT(th->th_ack, tp->snd_una) &&
999 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1000 tp->snd_cwnd >= tp->snd_wnd &&
1001 ((!tcp_do_newreno &&
1002 !(tp->t_flags & TF_SACK_PERMIT) &&
1003 tp->t_dupacks < tcprexmtthresh) ||
1005 (tp->t_flags & TF_SACK_PERMIT)) &&
1006 !IN_FASTRECOVERY(tp) &&
1007 (to.to_flags & TOF_SACK) == 0 &&
1008 TAILQ_EMPTY(&tp->snd_holes)))) {
1010 ("%s: headlocked", __func__));
1011 INP_INFO_WUNLOCK(&tcbinfo);
1014 * This is a pure ack for outstanding data.
1016 ++tcpstat.tcps_predack;
1018 * "bad retransmit" recovery.
1020 if (tp->t_rxtshift == 1 &&
1021 ticks < tp->t_badrxtwin) {
1022 ++tcpstat.tcps_sndrexmitbad;
1023 tp->snd_cwnd = tp->snd_cwnd_prev;
1025 tp->snd_ssthresh_prev;
1026 tp->snd_recover = tp->snd_recover_prev;
1027 if (tp->t_flags & TF_WASFRECOVERY)
1028 ENTER_FASTRECOVERY(tp);
1029 tp->snd_nxt = tp->snd_max;
1030 tp->t_badrxtwin = 0;
1034 * Recalculate the transmit timer / rtt.
1036 * Some boxes send broken timestamp replies
1037 * during the SYN+ACK phase, ignore
1038 * timestamps of 0 or we could calculate a
1039 * huge RTT and blow up the retransmit timer.
1041 if ((to.to_flags & TOF_TS) != 0 &&
1043 if (!tp->t_rttlow ||
1044 tp->t_rttlow > ticks - to.to_tsecr)
1045 tp->t_rttlow = ticks - to.to_tsecr;
1047 ticks - to.to_tsecr + 1);
1048 } else if (tp->t_rtttime &&
1049 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1050 if (!tp->t_rttlow ||
1051 tp->t_rttlow > ticks - tp->t_rtttime)
1052 tp->t_rttlow = ticks - tp->t_rtttime;
1054 ticks - tp->t_rtttime);
1056 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1057 acked = th->th_ack - tp->snd_una;
1058 tcpstat.tcps_rcvackpack++;
1059 tcpstat.tcps_rcvackbyte += acked;
1060 sbdrop(&so->so_snd, acked);
1061 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1062 SEQ_LEQ(th->th_ack, tp->snd_recover))
1063 tp->snd_recover = th->th_ack - 1;
1064 tp->snd_una = th->th_ack;
1066 * Pull snd_wl2 up to prevent seq wrap relative
1069 tp->snd_wl2 = th->th_ack;
1072 ND6_HINT(tp); /* Some progress has been made. */
1075 * If all outstanding data are acked, stop
1076 * retransmit timer, otherwise restart timer
1077 * using current (possibly backed-off) value.
1078 * If process is waiting for space,
1079 * wakeup/selwakeup/signal. If data
1080 * are ready to send, let tcp_output
1081 * decide between more output or persist.
1084 if (so->so_options & SO_DEBUG)
1085 tcp_trace(TA_INPUT, ostate, tp,
1086 (void *)tcp_saveipgen,
1089 if (tp->snd_una == tp->snd_max)
1090 tcp_timer_activate(tp, TT_REXMT, 0);
1091 else if (!tcp_timer_active(tp, TT_PERSIST))
1092 tcp_timer_activate(tp, TT_REXMT,
1095 if (so->so_snd.sb_cc)
1096 (void) tcp_output(tp);
1099 } else if (th->th_ack == tp->snd_una &&
1100 tlen <= sbspace(&so->so_rcv)) {
1101 int newsize = 0; /* automatic sockbuf scaling */
1103 KASSERT(headlocked, ("%s: headlocked", __func__));
1104 INP_INFO_WUNLOCK(&tcbinfo);
1107 * This is a pure, in-sequence data packet
1108 * with nothing on the reassembly queue and
1109 * we have enough buffer space to take it.
1111 /* Clean receiver SACK report if present */
1112 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1113 tcp_clean_sackreport(tp);
1114 ++tcpstat.tcps_preddat;
1115 tp->rcv_nxt += tlen;
1117 * Pull snd_wl1 up to prevent seq wrap relative to
1120 tp->snd_wl1 = th->th_seq;
1122 * Pull rcv_up up to prevent seq wrap relative to
1125 tp->rcv_up = tp->rcv_nxt;
1126 tcpstat.tcps_rcvpack++;
1127 tcpstat.tcps_rcvbyte += tlen;
1128 ND6_HINT(tp); /* Some progress has been made */
1130 if (so->so_options & SO_DEBUG)
1131 tcp_trace(TA_INPUT, ostate, tp,
1132 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1135 * Automatic sizing of receive socket buffer. Often the send
1136 * buffer size is not optimally adjusted to the actual network
1137 * conditions at hand (delay bandwidth product). Setting the
1138 * buffer size too small limits throughput on links with high
1139 * bandwidth and high delay (eg. trans-continental/oceanic links).
1141 * On the receive side the socket buffer memory is only rarely
1142 * used to any significant extent. This allows us to be much
1143 * more aggressive in scaling the receive socket buffer. For
1144 * the case that the buffer space is actually used to a large
1145 * extent and we run out of kernel memory we can simply drop
1146 * the new segments; TCP on the sender will just retransmit it
1147 * later. Setting the buffer size too big may only consume too
1148 * much kernel memory if the application doesn't read() from
1149 * the socket or packet loss or reordering makes use of the
1152 * The criteria to step up the receive buffer one notch are:
1153 * 1. the number of bytes received during the time it takes
1154 * one timestamp to be reflected back to us (the RTT);
1155 * 2. received bytes per RTT is within seven eighth of the
1156 * current socket buffer size;
1157 * 3. receive buffer size has not hit maximal automatic size;
1159 * This algorithm does one step per RTT at most and only if
1160 * we receive a bulk stream w/o packet losses or reorderings.
1161 * Shrinking the buffer during idle times is not necessary as
1162 * it doesn't consume any memory when idle.
1164 * TODO: Only step up if the application is actually serving
1165 * the buffer to better manage the socket buffer resources.
1167 if (tcp_do_autorcvbuf &&
1169 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1170 if (to.to_tsecr > tp->rfbuf_ts &&
1171 to.to_tsecr - tp->rfbuf_ts < hz) {
1173 (so->so_rcv.sb_hiwat / 8 * 7) &&
1174 so->so_rcv.sb_hiwat <
1175 tcp_autorcvbuf_max) {
1177 min(so->so_rcv.sb_hiwat +
1179 tcp_autorcvbuf_max);
1181 /* Start over with next RTT. */
1185 tp->rfbuf_cnt += tlen; /* add up */
1188 /* Add data to socket buffer. */
1189 SOCKBUF_LOCK(&so->so_rcv);
1190 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1194 * Set new socket buffer size.
1195 * Give up when limit is reached.
1198 if (!sbreserve_locked(&so->so_rcv,
1199 newsize, so, curthread))
1200 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1201 m_adj(m, drop_hdrlen); /* delayed header drop */
1202 sbappendstream_locked(&so->so_rcv, m);
1204 /* NB: sorwakeup_locked() does an implicit unlock. */
1205 sorwakeup_locked(so);
1206 if (DELAY_ACK(tp)) {
1207 tp->t_flags |= TF_DELACK;
1209 tp->t_flags |= TF_ACKNOW;
1217 * Calculate amount of space in receive window,
1218 * and then do TCP input processing.
1219 * Receive window is amount of space in rcv queue,
1220 * but not less than advertised window.
1222 win = sbspace(&so->so_rcv);
1225 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1227 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1231 switch (tp->t_state) {
1234 * If the state is SYN_RECEIVED:
1235 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1237 case TCPS_SYN_RECEIVED:
1238 if ((thflags & TH_ACK) &&
1239 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1240 SEQ_GT(th->th_ack, tp->snd_max))) {
1241 rstreason = BANDLIM_RST_OPENPORT;
1247 * If the state is SYN_SENT:
1248 * if seg contains an ACK, but not for our SYN, drop the input.
1249 * if seg contains a RST, then drop the connection.
1250 * if seg does not contain SYN, then drop it.
1251 * Otherwise this is an acceptable SYN segment
1252 * initialize tp->rcv_nxt and tp->irs
1253 * if seg contains ack then advance tp->snd_una
1254 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1255 * arrange for segment to be acked (eventually)
1256 * continue processing rest of data/controls, beginning with URG
1259 if ((thflags & TH_ACK) &&
1260 (SEQ_LEQ(th->th_ack, tp->iss) ||
1261 SEQ_GT(th->th_ack, tp->snd_max))) {
1262 rstreason = BANDLIM_UNLIMITED;
1265 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1266 tp = tcp_drop(tp, ECONNREFUSED);
1267 if (thflags & TH_RST)
1269 if (!(thflags & TH_SYN))
1272 tp->irs = th->th_seq;
1274 if (thflags & TH_ACK) {
1275 tcpstat.tcps_connects++;
1279 mac_set_socket_peer_from_mbuf(m, so);
1282 /* Do window scaling on this connection? */
1283 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1284 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1285 tp->rcv_scale = tp->request_r_scale;
1287 tp->rcv_adv += tp->rcv_wnd;
1288 tp->snd_una++; /* SYN is acked */
1290 * If there's data, delay ACK; if there's also a FIN
1291 * ACKNOW will be turned on later.
1293 if (DELAY_ACK(tp) && tlen != 0)
1294 tcp_timer_activate(tp, TT_DELACK,
1297 tp->t_flags |= TF_ACKNOW;
1299 * Received <SYN,ACK> in SYN_SENT[*] state.
1301 * SYN_SENT --> ESTABLISHED
1302 * SYN_SENT* --> FIN_WAIT_1
1304 tp->t_starttime = ticks;
1305 if (tp->t_flags & TF_NEEDFIN) {
1306 tp->t_state = TCPS_FIN_WAIT_1;
1307 tp->t_flags &= ~TF_NEEDFIN;
1310 tp->t_state = TCPS_ESTABLISHED;
1311 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1315 * Received initial SYN in SYN-SENT[*] state =>
1316 * simultaneous open. If segment contains CC option
1317 * and there is a cached CC, apply TAO test.
1318 * If it succeeds, connection is * half-synchronized.
1319 * Otherwise, do 3-way handshake:
1320 * SYN-SENT -> SYN-RECEIVED
1321 * SYN-SENT* -> SYN-RECEIVED*
1322 * If there was no CC option, clear cached CC value.
1324 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1325 tcp_timer_activate(tp, TT_REXMT, 0);
1326 tp->t_state = TCPS_SYN_RECEIVED;
1329 KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1331 INP_LOCK_ASSERT(tp->t_inpcb);
1334 * Advance th->th_seq to correspond to first data byte.
1335 * If data, trim to stay within window,
1336 * dropping FIN if necessary.
1339 if (tlen > tp->rcv_wnd) {
1340 todrop = tlen - tp->rcv_wnd;
1344 tcpstat.tcps_rcvpackafterwin++;
1345 tcpstat.tcps_rcvbyteafterwin += todrop;
1347 tp->snd_wl1 = th->th_seq - 1;
1348 tp->rcv_up = th->th_seq;
1350 * Client side of transaction: already sent SYN and data.
1351 * If the remote host used T/TCP to validate the SYN,
1352 * our data will be ACK'd; if so, enter normal data segment
1353 * processing in the middle of step 5, ack processing.
1354 * Otherwise, goto step 6.
1356 if (thflags & TH_ACK)
1362 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1363 * do normal processing.
1365 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1369 break; /* continue normal processing */
1373 * States other than LISTEN or SYN_SENT.
1374 * First check the RST flag and sequence number since reset segments
1375 * are exempt from the timestamp and connection count tests. This
1376 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1377 * below which allowed reset segments in half the sequence space
1378 * to fall though and be processed (which gives forged reset
1379 * segments with a random sequence number a 50 percent chance of
1380 * killing a connection).
1381 * Then check timestamp, if present.
1382 * Then check the connection count, if present.
1383 * Then check that at least some bytes of segment are within
1384 * receive window. If segment begins before rcv_nxt,
1385 * drop leading data (and SYN); if nothing left, just ack.
1388 * If the RST bit is set, check the sequence number to see
1389 * if this is a valid reset segment.
1391 * In all states except SYN-SENT, all reset (RST) segments
1392 * are validated by checking their SEQ-fields. A reset is
1393 * valid if its sequence number is in the window.
1394 * Note: this does not take into account delayed ACKs, so
1395 * we should test against last_ack_sent instead of rcv_nxt.
1396 * The sequence number in the reset segment is normally an
1397 * echo of our outgoing acknowlegement numbers, but some hosts
1398 * send a reset with the sequence number at the rightmost edge
1399 * of our receive window, and we have to handle this case.
1400 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1401 * that brute force RST attacks are possible. To combat this,
1402 * we use a much stricter check while in the ESTABLISHED state,
1403 * only accepting RSTs where the sequence number is equal to
1404 * last_ack_sent. In all other states (the states in which a
1405 * RST is more likely), the more permissive check is used.
1406 * If we have multiple segments in flight, the intial reset
1407 * segment sequence numbers will be to the left of last_ack_sent,
1408 * but they will eventually catch up.
1409 * In any case, it never made sense to trim reset segments to
1410 * fit the receive window since RFC 1122 says:
1411 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1413 * A TCP SHOULD allow a received RST segment to include data.
1416 * It has been suggested that a RST segment could contain
1417 * ASCII text that encoded and explained the cause of the
1418 * RST. No standard has yet been established for such
1421 * If the reset segment passes the sequence number test examine
1423 * SYN_RECEIVED STATE:
1424 * If passive open, return to LISTEN state.
1425 * If active open, inform user that connection was refused.
1426 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1427 * Inform user that connection was reset, and close tcb.
1428 * CLOSING, LAST_ACK STATES:
1431 * Drop the segment - see Stevens, vol. 2, p. 964 and
1434 if (thflags & TH_RST) {
1435 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1436 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1437 switch (tp->t_state) {
1439 case TCPS_SYN_RECEIVED:
1440 so->so_error = ECONNREFUSED;
1443 case TCPS_ESTABLISHED:
1444 if (tcp_insecure_rst == 0 &&
1445 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1446 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1447 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1448 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1449 tcpstat.tcps_badrst++;
1453 case TCPS_FIN_WAIT_1:
1454 case TCPS_FIN_WAIT_2:
1455 case TCPS_CLOSE_WAIT:
1456 so->so_error = ECONNRESET;
1458 tp->t_state = TCPS_CLOSED;
1459 tcpstat.tcps_drops++;
1460 KASSERT(headlocked, ("%s: trimthenstep6: "
1461 "tcp_close: head not locked", __func__));
1467 KASSERT(headlocked, ("%s: trimthenstep6: "
1468 "tcp_close.2: head not locked", __func__));
1477 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1478 * and it's less than ts_recent, drop it.
1480 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1481 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1483 /* Check to see if ts_recent is over 24 days old. */
1484 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1486 * Invalidate ts_recent. If this segment updates
1487 * ts_recent, the age will be reset later and ts_recent
1488 * will get a valid value. If it does not, setting
1489 * ts_recent to zero will at least satisfy the
1490 * requirement that zero be placed in the timestamp
1491 * echo reply when ts_recent isn't valid. The
1492 * age isn't reset until we get a valid ts_recent
1493 * because we don't want out-of-order segments to be
1494 * dropped when ts_recent is old.
1498 tcpstat.tcps_rcvduppack++;
1499 tcpstat.tcps_rcvdupbyte += tlen;
1500 tcpstat.tcps_pawsdrop++;
1508 * In the SYN-RECEIVED state, validate that the packet belongs to
1509 * this connection before trimming the data to fit the receive
1510 * window. Check the sequence number versus IRS since we know
1511 * the sequence numbers haven't wrapped. This is a partial fix
1512 * for the "LAND" DoS attack.
1514 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1515 rstreason = BANDLIM_RST_OPENPORT;
1519 todrop = tp->rcv_nxt - th->th_seq;
1521 if (thflags & TH_SYN) {
1531 * Following if statement from Stevens, vol. 2, p. 960.
1534 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1536 * Any valid FIN must be to the left of the window.
1537 * At this point the FIN must be a duplicate or out
1538 * of sequence; drop it.
1543 * Send an ACK to resynchronize and drop any data.
1544 * But keep on processing for RST or ACK.
1546 tp->t_flags |= TF_ACKNOW;
1548 tcpstat.tcps_rcvduppack++;
1549 tcpstat.tcps_rcvdupbyte += todrop;
1551 tcpstat.tcps_rcvpartduppack++;
1552 tcpstat.tcps_rcvpartdupbyte += todrop;
1554 drop_hdrlen += todrop; /* drop from the top afterwards */
1555 th->th_seq += todrop;
1557 if (th->th_urp > todrop)
1558 th->th_urp -= todrop;
1566 * If new data are received on a connection after the
1567 * user processes are gone, then RST the other end.
1569 if ((so->so_state & SS_NOFDREF) &&
1570 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1573 KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1574 "not locked", __func__));
1575 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1576 log(LOG_DEBUG, "%s; %s: %s: Received data after socket "
1577 "was closed, sending RST and removing tcpcb\n",
1578 s, __func__, tcpstates[tp->t_state]);
1582 tcpstat.tcps_rcvafterclose++;
1583 rstreason = BANDLIM_UNLIMITED;
1588 * If segment ends after window, drop trailing data
1589 * (and PUSH and FIN); if nothing left, just ACK.
1591 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1593 tcpstat.tcps_rcvpackafterwin++;
1594 if (todrop >= tlen) {
1595 tcpstat.tcps_rcvbyteafterwin += tlen;
1597 * If window is closed can only take segments at
1598 * window edge, and have to drop data and PUSH from
1599 * incoming segments. Continue processing, but
1600 * remember to ack. Otherwise, drop segment
1603 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1604 tp->t_flags |= TF_ACKNOW;
1605 tcpstat.tcps_rcvwinprobe++;
1609 tcpstat.tcps_rcvbyteafterwin += todrop;
1612 thflags &= ~(TH_PUSH|TH_FIN);
1616 * If last ACK falls within this segment's sequence numbers,
1617 * record its timestamp.
1619 * 1) That the test incorporates suggestions from the latest
1620 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1621 * 2) That updating only on newer timestamps interferes with
1622 * our earlier PAWS tests, so this check should be solely
1623 * predicated on the sequence space of this segment.
1624 * 3) That we modify the segment boundary check to be
1625 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1626 * instead of RFC1323's
1627 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1628 * This modified check allows us to overcome RFC1323's
1629 * limitations as described in Stevens TCP/IP Illustrated
1630 * Vol. 2 p.869. In such cases, we can still calculate the
1631 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1633 if ((to.to_flags & TOF_TS) != 0 &&
1634 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1635 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1636 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1637 tp->ts_recent_age = ticks;
1638 tp->ts_recent = to.to_tsval;
1642 * If a SYN is in the window, then this is an
1643 * error and we send an RST and drop the connection.
1645 if (thflags & TH_SYN) {
1646 KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1647 "head not locked", __func__));
1648 tp = tcp_drop(tp, ECONNRESET);
1649 rstreason = BANDLIM_UNLIMITED;
1654 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1655 * flag is on (half-synchronized state), then queue data for
1656 * later processing; else drop segment and return.
1658 if ((thflags & TH_ACK) == 0) {
1659 if (tp->t_state == TCPS_SYN_RECEIVED ||
1660 (tp->t_flags & TF_NEEDSYN))
1662 else if (tp->t_flags & TF_ACKNOW)
1671 switch (tp->t_state) {
1674 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1675 * ESTABLISHED state and continue processing.
1676 * The ACK was checked above.
1678 case TCPS_SYN_RECEIVED:
1680 tcpstat.tcps_connects++;
1682 /* Do window scaling? */
1683 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1684 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1685 tp->rcv_scale = tp->request_r_scale;
1686 tp->snd_wnd = tiwin;
1690 * SYN-RECEIVED -> ESTABLISHED
1691 * SYN-RECEIVED* -> FIN-WAIT-1
1693 tp->t_starttime = ticks;
1694 if (tp->t_flags & TF_NEEDFIN) {
1695 tp->t_state = TCPS_FIN_WAIT_1;
1696 tp->t_flags &= ~TF_NEEDFIN;
1698 tp->t_state = TCPS_ESTABLISHED;
1699 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1702 * If segment contains data or ACK, will call tcp_reass()
1703 * later; if not, do so now to pass queued data to user.
1705 if (tlen == 0 && (thflags & TH_FIN) == 0)
1706 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1708 tp->snd_wl1 = th->th_seq - 1;
1712 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1713 * ACKs. If the ack is in the range
1714 * tp->snd_una < th->th_ack <= tp->snd_max
1715 * then advance tp->snd_una to th->th_ack and drop
1716 * data from the retransmission queue. If this ACK reflects
1717 * more up to date window information we update our window information.
1719 case TCPS_ESTABLISHED:
1720 case TCPS_FIN_WAIT_1:
1721 case TCPS_FIN_WAIT_2:
1722 case TCPS_CLOSE_WAIT:
1725 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1726 tcpstat.tcps_rcvacktoomuch++;
1729 if ((tp->t_flags & TF_SACK_PERMIT) &&
1730 ((to.to_flags & TOF_SACK) ||
1731 !TAILQ_EMPTY(&tp->snd_holes)))
1732 tcp_sack_doack(tp, &to, th->th_ack);
1733 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1734 if (tlen == 0 && tiwin == tp->snd_wnd) {
1735 tcpstat.tcps_rcvdupack++;
1737 * If we have outstanding data (other than
1738 * a window probe), this is a completely
1739 * duplicate ack (ie, window info didn't
1740 * change), the ack is the biggest we've
1741 * seen and we've seen exactly our rexmt
1742 * threshhold of them, assume a packet
1743 * has been dropped and retransmit it.
1744 * Kludge snd_nxt & the congestion
1745 * window so we send only this one
1748 * We know we're losing at the current
1749 * window size so do congestion avoidance
1750 * (set ssthresh to half the current window
1751 * and pull our congestion window back to
1752 * the new ssthresh).
1754 * Dup acks mean that packets have left the
1755 * network (they're now cached at the receiver)
1756 * so bump cwnd by the amount in the receiver
1757 * to keep a constant cwnd packets in the
1760 if (!tcp_timer_active(tp, TT_REXMT) ||
1761 th->th_ack != tp->snd_una)
1763 else if (++tp->t_dupacks > tcprexmtthresh ||
1765 (tp->t_flags & TF_SACK_PERMIT)) &&
1766 IN_FASTRECOVERY(tp))) {
1767 if ((tp->t_flags & TF_SACK_PERMIT) &&
1768 IN_FASTRECOVERY(tp)) {
1772 * Compute the amount of data in flight first.
1773 * We can inject new data into the pipe iff
1774 * we have less than 1/2 the original window's
1775 * worth of data in flight.
1777 awnd = (tp->snd_nxt - tp->snd_fack) +
1778 tp->sackhint.sack_bytes_rexmit;
1779 if (awnd < tp->snd_ssthresh) {
1780 tp->snd_cwnd += tp->t_maxseg;
1781 if (tp->snd_cwnd > tp->snd_ssthresh)
1782 tp->snd_cwnd = tp->snd_ssthresh;
1785 tp->snd_cwnd += tp->t_maxseg;
1786 (void) tcp_output(tp);
1788 } else if (tp->t_dupacks == tcprexmtthresh) {
1789 tcp_seq onxt = tp->snd_nxt;
1793 * If we're doing sack, check to
1794 * see if we're already in sack
1795 * recovery. If we're not doing sack,
1796 * check to see if we're in newreno
1799 if (tp->t_flags & TF_SACK_PERMIT) {
1800 if (IN_FASTRECOVERY(tp)) {
1804 } else if (tcp_do_newreno) {
1805 if (SEQ_LEQ(th->th_ack,
1811 win = min(tp->snd_wnd, tp->snd_cwnd) /
1815 tp->snd_ssthresh = win * tp->t_maxseg;
1816 ENTER_FASTRECOVERY(tp);
1817 tp->snd_recover = tp->snd_max;
1818 tcp_timer_activate(tp, TT_REXMT, 0);
1820 if (tp->t_flags & TF_SACK_PERMIT) {
1821 tcpstat.tcps_sack_recovery_episode++;
1822 tp->sack_newdata = tp->snd_nxt;
1823 tp->snd_cwnd = tp->t_maxseg;
1824 (void) tcp_output(tp);
1827 tp->snd_nxt = th->th_ack;
1828 tp->snd_cwnd = tp->t_maxseg;
1829 (void) tcp_output(tp);
1830 KASSERT(tp->snd_limited <= 2,
1831 ("%s: tp->snd_limited too big",
1833 tp->snd_cwnd = tp->snd_ssthresh +
1835 (tp->t_dupacks - tp->snd_limited);
1836 if (SEQ_GT(onxt, tp->snd_nxt))
1839 } else if (tcp_do_rfc3042) {
1840 u_long oldcwnd = tp->snd_cwnd;
1841 tcp_seq oldsndmax = tp->snd_max;
1844 KASSERT(tp->t_dupacks == 1 ||
1846 ("%s: dupacks not 1 or 2",
1848 if (tp->t_dupacks == 1)
1849 tp->snd_limited = 0;
1851 (tp->snd_nxt - tp->snd_una) +
1852 (tp->t_dupacks - tp->snd_limited) *
1854 (void) tcp_output(tp);
1855 sent = tp->snd_max - oldsndmax;
1856 if (sent > tp->t_maxseg) {
1857 KASSERT((tp->t_dupacks == 2 &&
1858 tp->snd_limited == 0) ||
1859 (sent == tp->t_maxseg + 1 &&
1860 tp->t_flags & TF_SENTFIN),
1861 ("%s: sent too much",
1863 tp->snd_limited = 2;
1864 } else if (sent > 0)
1866 tp->snd_cwnd = oldcwnd;
1874 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
1875 ("%s: th_ack <= snd_una", __func__));
1878 * If the congestion window was inflated to account
1879 * for the other side's cached packets, retract it.
1881 if (tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
1882 if (IN_FASTRECOVERY(tp)) {
1883 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1884 if (tp->t_flags & TF_SACK_PERMIT)
1885 tcp_sack_partialack(tp, th);
1887 tcp_newreno_partial_ack(tp, th);
1890 * Out of fast recovery.
1891 * Window inflation should have left us
1892 * with approximately snd_ssthresh
1894 * But in case we would be inclined to
1895 * send a burst, better to do it via
1896 * the slow start mechanism.
1898 if (SEQ_GT(th->th_ack +
1901 tp->snd_cwnd = tp->snd_max -
1905 tp->snd_cwnd = tp->snd_ssthresh;
1909 if (tp->t_dupacks >= tcprexmtthresh &&
1910 tp->snd_cwnd > tp->snd_ssthresh)
1911 tp->snd_cwnd = tp->snd_ssthresh;
1915 * If we reach this point, ACK is not a duplicate,
1916 * i.e., it ACKs something we sent.
1918 if (tp->t_flags & TF_NEEDSYN) {
1920 * T/TCP: Connection was half-synchronized, and our
1921 * SYN has been ACK'd (so connection is now fully
1922 * synchronized). Go to non-starred state,
1923 * increment snd_una for ACK of SYN, and check if
1924 * we can do window scaling.
1926 tp->t_flags &= ~TF_NEEDSYN;
1928 /* Do window scaling? */
1929 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1930 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1931 tp->rcv_scale = tp->request_r_scale;
1932 /* Send window already scaled. */
1937 KASSERT(headlocked, ("%s: process_ACK: head not locked",
1939 INP_LOCK_ASSERT(tp->t_inpcb);
1941 acked = th->th_ack - tp->snd_una;
1942 tcpstat.tcps_rcvackpack++;
1943 tcpstat.tcps_rcvackbyte += acked;
1946 * If we just performed our first retransmit, and the ACK
1947 * arrives within our recovery window, then it was a mistake
1948 * to do the retransmit in the first place. Recover our
1949 * original cwnd and ssthresh, and proceed to transmit where
1952 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1953 ++tcpstat.tcps_sndrexmitbad;
1954 tp->snd_cwnd = tp->snd_cwnd_prev;
1955 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1956 tp->snd_recover = tp->snd_recover_prev;
1957 if (tp->t_flags & TF_WASFRECOVERY)
1958 ENTER_FASTRECOVERY(tp);
1959 tp->snd_nxt = tp->snd_max;
1960 tp->t_badrxtwin = 0; /* XXX probably not required */
1964 * If we have a timestamp reply, update smoothed
1965 * round trip time. If no timestamp is present but
1966 * transmit timer is running and timed sequence
1967 * number was acked, update smoothed round trip time.
1968 * Since we now have an rtt measurement, cancel the
1969 * timer backoff (cf., Phil Karn's retransmit alg.).
1970 * Recompute the initial retransmit timer.
1972 * Some boxes send broken timestamp replies
1973 * during the SYN+ACK phase, ignore
1974 * timestamps of 0 or we could calculate a
1975 * huge RTT and blow up the retransmit timer.
1977 if ((to.to_flags & TOF_TS) != 0 &&
1979 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
1980 tp->t_rttlow = ticks - to.to_tsecr;
1981 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1982 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1983 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
1984 tp->t_rttlow = ticks - tp->t_rtttime;
1985 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1987 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1990 * If all outstanding data is acked, stop retransmit
1991 * timer and remember to restart (more output or persist).
1992 * If there is more data to be acked, restart retransmit
1993 * timer, using current (possibly backed-off) value.
1995 if (th->th_ack == tp->snd_max) {
1996 tcp_timer_activate(tp, TT_REXMT, 0);
1998 } else if (!tcp_timer_active(tp, TT_PERSIST))
1999 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2002 * If no data (only SYN) was ACK'd,
2003 * skip rest of ACK processing.
2009 * When new data is acked, open the congestion window.
2010 * If the window gives us less than ssthresh packets
2011 * in flight, open exponentially (maxseg per packet).
2012 * Otherwise open linearly: maxseg per window
2013 * (maxseg^2 / cwnd per packet).
2015 if ((!tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2016 !IN_FASTRECOVERY(tp)) {
2017 u_int cw = tp->snd_cwnd;
2018 u_int incr = tp->t_maxseg;
2019 if (cw > tp->snd_ssthresh)
2020 incr = incr * incr / cw;
2021 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2023 SOCKBUF_LOCK(&so->so_snd);
2024 if (acked > so->so_snd.sb_cc) {
2025 tp->snd_wnd -= so->so_snd.sb_cc;
2026 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2029 sbdrop_locked(&so->so_snd, acked);
2030 tp->snd_wnd -= acked;
2033 /* NB: sowwakeup_locked() does an implicit unlock. */
2034 sowwakeup_locked(so);
2035 /* Detect una wraparound. */
2036 if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2037 !IN_FASTRECOVERY(tp) &&
2038 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2039 SEQ_LEQ(th->th_ack, tp->snd_recover))
2040 tp->snd_recover = th->th_ack - 1;
2041 if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2042 IN_FASTRECOVERY(tp) &&
2043 SEQ_GEQ(th->th_ack, tp->snd_recover))
2044 EXIT_FASTRECOVERY(tp);
2045 tp->snd_una = th->th_ack;
2046 if (tp->t_flags & TF_SACK_PERMIT) {
2047 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2048 tp->snd_recover = tp->snd_una;
2050 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2051 tp->snd_nxt = tp->snd_una;
2053 switch (tp->t_state) {
2056 * In FIN_WAIT_1 STATE in addition to the processing
2057 * for the ESTABLISHED state if our FIN is now acknowledged
2058 * then enter FIN_WAIT_2.
2060 case TCPS_FIN_WAIT_1:
2061 if (ourfinisacked) {
2063 * If we can't receive any more
2064 * data, then closing user can proceed.
2065 * Starting the timer is contrary to the
2066 * specification, but if we don't get a FIN
2067 * we'll hang forever.
2070 * we should release the tp also, and use a
2073 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2076 soisdisconnected(so);
2077 timeout = (tcp_fast_finwait2_recycle) ?
2078 tcp_finwait2_timeout : tcp_maxidle;
2079 tcp_timer_activate(tp, TT_2MSL, timeout);
2081 tp->t_state = TCPS_FIN_WAIT_2;
2086 * In CLOSING STATE in addition to the processing for
2087 * the ESTABLISHED state if the ACK acknowledges our FIN
2088 * then enter the TIME-WAIT state, otherwise ignore
2092 if (ourfinisacked) {
2093 KASSERT(headlocked, ("%s: process_ACK: "
2094 "head not locked", __func__));
2096 INP_INFO_WUNLOCK(&tcbinfo);
2104 * In LAST_ACK, we may still be waiting for data to drain
2105 * and/or to be acked, as well as for the ack of our FIN.
2106 * If our FIN is now acknowledged, delete the TCB,
2107 * enter the closed state and return.
2110 if (ourfinisacked) {
2111 KASSERT(headlocked, ("%s: process_ACK: "
2112 "tcp_close: head not locked", __func__));
2121 KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2122 INP_LOCK_ASSERT(tp->t_inpcb);
2125 * Update window information.
2126 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2128 if ((thflags & TH_ACK) &&
2129 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2130 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2131 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2132 /* keep track of pure window updates */
2134 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2135 tcpstat.tcps_rcvwinupd++;
2136 tp->snd_wnd = tiwin;
2137 tp->snd_wl1 = th->th_seq;
2138 tp->snd_wl2 = th->th_ack;
2139 if (tp->snd_wnd > tp->max_sndwnd)
2140 tp->max_sndwnd = tp->snd_wnd;
2145 * Process segments with URG.
2147 if ((thflags & TH_URG) && th->th_urp &&
2148 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2150 * This is a kludge, but if we receive and accept
2151 * random urgent pointers, we'll crash in
2152 * soreceive. It's hard to imagine someone
2153 * actually wanting to send this much urgent data.
2155 SOCKBUF_LOCK(&so->so_rcv);
2156 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2157 th->th_urp = 0; /* XXX */
2158 thflags &= ~TH_URG; /* XXX */
2159 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2160 goto dodata; /* XXX */
2163 * If this segment advances the known urgent pointer,
2164 * then mark the data stream. This should not happen
2165 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2166 * a FIN has been received from the remote side.
2167 * In these states we ignore the URG.
2169 * According to RFC961 (Assigned Protocols),
2170 * the urgent pointer points to the last octet
2171 * of urgent data. We continue, however,
2172 * to consider it to indicate the first octet
2173 * of data past the urgent section as the original
2174 * spec states (in one of two places).
2176 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2177 tp->rcv_up = th->th_seq + th->th_urp;
2178 so->so_oobmark = so->so_rcv.sb_cc +
2179 (tp->rcv_up - tp->rcv_nxt) - 1;
2180 if (so->so_oobmark == 0)
2181 so->so_rcv.sb_state |= SBS_RCVATMARK;
2183 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2185 SOCKBUF_UNLOCK(&so->so_rcv);
2187 * Remove out of band data so doesn't get presented to user.
2188 * This can happen independent of advancing the URG pointer,
2189 * but if two URG's are pending at once, some out-of-band
2190 * data may creep in... ick.
2192 if (th->th_urp <= (u_long)tlen &&
2193 !(so->so_options & SO_OOBINLINE)) {
2194 /* hdr drop is delayed */
2195 tcp_pulloutofband(so, th, m, drop_hdrlen);
2199 * If no out of band data is expected,
2200 * pull receive urgent pointer along
2201 * with the receive window.
2203 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2204 tp->rcv_up = tp->rcv_nxt;
2207 KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2208 INP_LOCK_ASSERT(tp->t_inpcb);
2211 * Process the segment text, merging it into the TCP sequencing queue,
2212 * and arranging for acknowledgment of receipt if necessary.
2213 * This process logically involves adjusting tp->rcv_wnd as data
2214 * is presented to the user (this happens in tcp_usrreq.c,
2215 * case PRU_RCVD). If a FIN has already been received on this
2216 * connection then we just ignore the text.
2218 if ((tlen || (thflags & TH_FIN)) &&
2219 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2220 tcp_seq save_start = th->th_seq;
2221 m_adj(m, drop_hdrlen); /* delayed header drop */
2223 * Insert segment which includes th into TCP reassembly queue
2224 * with control block tp. Set thflags to whether reassembly now
2225 * includes a segment with FIN. This handles the common case
2226 * inline (segment is the next to be received on an established
2227 * connection, and the queue is empty), avoiding linkage into
2228 * and removal from the queue and repetition of various
2230 * Set DELACK for segments received in order, but ack
2231 * immediately when segments are out of order (so
2232 * fast retransmit can work).
2234 if (th->th_seq == tp->rcv_nxt &&
2235 LIST_EMPTY(&tp->t_segq) &&
2236 TCPS_HAVEESTABLISHED(tp->t_state)) {
2238 tp->t_flags |= TF_DELACK;
2240 tp->t_flags |= TF_ACKNOW;
2241 tp->rcv_nxt += tlen;
2242 thflags = th->th_flags & TH_FIN;
2243 tcpstat.tcps_rcvpack++;
2244 tcpstat.tcps_rcvbyte += tlen;
2246 SOCKBUF_LOCK(&so->so_rcv);
2247 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2250 sbappendstream_locked(&so->so_rcv, m);
2251 /* NB: sorwakeup_locked() does an implicit unlock. */
2252 sorwakeup_locked(so);
2255 * XXX: Due to the header drop above "th" is
2256 * theoretically invalid by now. Fortunately
2257 * m_adj() doesn't actually frees any mbufs
2258 * when trimming from the head.
2260 thflags = tcp_reass(tp, th, &tlen, m);
2261 tp->t_flags |= TF_ACKNOW;
2263 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2264 tcp_update_sack_list(tp, save_start, save_start + tlen);
2267 * Note the amount of data that peer has sent into
2268 * our window, in order to estimate the sender's
2272 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2280 * If FIN is received ACK the FIN and let the user know
2281 * that the connection is closing.
2283 if (thflags & TH_FIN) {
2284 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2287 * If connection is half-synchronized
2288 * (ie NEEDSYN flag on) then delay ACK,
2289 * so it may be piggybacked when SYN is sent.
2290 * Otherwise, since we received a FIN then no
2291 * more input can be expected, send ACK now.
2293 if (tp->t_flags & TF_NEEDSYN)
2294 tp->t_flags |= TF_DELACK;
2296 tp->t_flags |= TF_ACKNOW;
2299 switch (tp->t_state) {
2302 * In SYN_RECEIVED and ESTABLISHED STATES
2303 * enter the CLOSE_WAIT state.
2305 case TCPS_SYN_RECEIVED:
2306 tp->t_starttime = ticks;
2308 case TCPS_ESTABLISHED:
2309 tp->t_state = TCPS_CLOSE_WAIT;
2313 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2314 * enter the CLOSING state.
2316 case TCPS_FIN_WAIT_1:
2317 tp->t_state = TCPS_CLOSING;
2321 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2322 * starting the time-wait timer, turning off the other
2325 case TCPS_FIN_WAIT_2:
2326 KASSERT(headlocked == 1, ("%s: dodata: "
2327 "TCP_FIN_WAIT_2: head not locked", __func__));
2329 INP_INFO_WUNLOCK(&tcbinfo);
2333 INP_INFO_WUNLOCK(&tcbinfo);
2336 if (so->so_options & SO_DEBUG)
2337 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2342 * Return any desired output.
2344 if (needoutput || (tp->t_flags & TF_ACKNOW))
2345 (void) tcp_output(tp);
2348 KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2350 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
2351 INP_LOCK_ASSERT(tp->t_inpcb);
2352 if (tp->t_flags & TF_DELACK) {
2353 tp->t_flags &= ~TF_DELACK;
2354 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2356 INP_UNLOCK(tp->t_inpcb);
2360 KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2362 * Generate an ACK dropping incoming segment if it occupies
2363 * sequence space, where the ACK reflects our state.
2365 * We can now skip the test for the RST flag since all
2366 * paths to this code happen after packets containing
2367 * RST have been dropped.
2369 * In the SYN-RECEIVED state, don't send an ACK unless the
2370 * segment we received passes the SYN-RECEIVED ACK test.
2371 * If it fails send a RST. This breaks the loop in the
2372 * "LAND" DoS attack, and also prevents an ACK storm
2373 * between two listening ports that have been sent forged
2374 * SYN segments, each with the source address of the other.
2376 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2377 (SEQ_GT(tp->snd_una, th->th_ack) ||
2378 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2379 rstreason = BANDLIM_RST_OPENPORT;
2383 if (so->so_options & SO_DEBUG)
2384 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2387 KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2388 INP_INFO_WUNLOCK(&tcbinfo);
2389 tp->t_flags |= TF_ACKNOW;
2390 (void) tcp_output(tp);
2391 INP_UNLOCK(tp->t_inpcb);
2396 KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2398 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2401 INP_UNLOCK(tp->t_inpcb);
2403 INP_INFO_WUNLOCK(&tcbinfo);
2408 * Drop space held by incoming segment and return.
2411 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2412 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2416 INP_UNLOCK(tp->t_inpcb);
2418 INP_INFO_WUNLOCK(&tcbinfo);
2424 * Issue RST and make ACK acceptable to originator of segment.
2425 * The mbuf must still include the original packet header.
2429 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2430 int tlen, int rstreason)
2434 struct ip6_hdr *ip6;
2436 /* Don't bother if destination was broadcast/multicast. */
2437 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2440 if (mtod(m, struct ip *)->ip_v == 6) {
2441 ip6 = mtod(m, struct ip6_hdr *);
2442 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2443 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2445 /* IPv6 anycast check is done at tcp6_input() */
2449 ip = mtod(m, struct ip *);
2450 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2451 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2452 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2453 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2457 /* Perform bandwidth limiting. */
2458 if (badport_bandlim(rstreason) < 0)
2461 /* tcp_respond consumes the mbuf chain. */
2462 if (th->th_flags & TH_ACK) {
2463 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2464 th->th_ack, TH_RST);
2466 if (th->th_flags & TH_SYN)
2468 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2469 (tcp_seq)0, TH_RST|TH_ACK);
2478 * Parse TCP options and place in tcpopt.
2481 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2486 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2488 if (opt == TCPOPT_EOL)
2490 if (opt == TCPOPT_NOP)
2496 if (optlen < 2 || optlen > cnt)
2501 if (optlen != TCPOLEN_MAXSEG)
2503 if (!(flags & TO_SYN))
2505 to->to_flags |= TOF_MSS;
2506 bcopy((char *)cp + 2,
2507 (char *)&to->to_mss, sizeof(to->to_mss));
2508 to->to_mss = ntohs(to->to_mss);
2511 if (optlen != TCPOLEN_WINDOW)
2513 if (!(flags & TO_SYN))
2515 to->to_flags |= TOF_SCALE;
2516 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2518 case TCPOPT_TIMESTAMP:
2519 if (optlen != TCPOLEN_TIMESTAMP)
2521 to->to_flags |= TOF_TS;
2522 bcopy((char *)cp + 2,
2523 (char *)&to->to_tsval, sizeof(to->to_tsval));
2524 to->to_tsval = ntohl(to->to_tsval);
2525 bcopy((char *)cp + 6,
2526 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2527 to->to_tsecr = ntohl(to->to_tsecr);
2529 #ifdef TCP_SIGNATURE
2531 * XXX In order to reply to a host which has set the
2532 * TCP_SIGNATURE option in its initial SYN, we have to
2533 * record the fact that the option was observed here
2534 * for the syncache code to perform the correct response.
2536 case TCPOPT_SIGNATURE:
2537 if (optlen != TCPOLEN_SIGNATURE)
2539 to->to_flags |= TOF_SIGNATURE;
2540 to->to_signature = cp + 2;
2543 case TCPOPT_SACK_PERMITTED:
2544 if (optlen != TCPOLEN_SACK_PERMITTED)
2546 if (!(flags & TO_SYN))
2550 to->to_flags |= TOF_SACKPERM;
2553 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2557 to->to_flags |= TOF_SACK;
2558 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2559 to->to_sacks = cp + 2;
2560 tcpstat.tcps_sack_rcv_blocks++;
2569 * Pull out of band byte out of a segment so
2570 * it doesn't appear in the user's data queue.
2571 * It is still reflected in the segment length for
2572 * sequencing purposes.
2575 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2578 int cnt = off + th->th_urp - 1;
2581 if (m->m_len > cnt) {
2582 char *cp = mtod(m, caddr_t) + cnt;
2583 struct tcpcb *tp = sototcpcb(so);
2586 tp->t_oobflags |= TCPOOB_HAVEDATA;
2587 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2589 if (m->m_flags & M_PKTHDR)
2598 panic("tcp_pulloutofband");
2602 * Collect new round-trip time estimate
2603 * and update averages and current timeout.
2606 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2610 INP_LOCK_ASSERT(tp->t_inpcb);
2612 tcpstat.tcps_rttupdated++;
2614 if (tp->t_srtt != 0) {
2616 * srtt is stored as fixed point with 5 bits after the
2617 * binary point (i.e., scaled by 8). The following magic
2618 * is equivalent to the smoothing algorithm in rfc793 with
2619 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2620 * point). Adjust rtt to origin 0.
2622 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2623 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2625 if ((tp->t_srtt += delta) <= 0)
2629 * We accumulate a smoothed rtt variance (actually, a
2630 * smoothed mean difference), then set the retransmit
2631 * timer to smoothed rtt + 4 times the smoothed variance.
2632 * rttvar is stored as fixed point with 4 bits after the
2633 * binary point (scaled by 16). The following is
2634 * equivalent to rfc793 smoothing with an alpha of .75
2635 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2636 * rfc793's wired-in beta.
2640 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2641 if ((tp->t_rttvar += delta) <= 0)
2643 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2644 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2647 * No rtt measurement yet - use the unsmoothed rtt.
2648 * Set the variance to half the rtt (so our first
2649 * retransmit happens at 3*rtt).
2651 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2652 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2653 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2659 * the retransmit should happen at rtt + 4 * rttvar.
2660 * Because of the way we do the smoothing, srtt and rttvar
2661 * will each average +1/2 tick of bias. When we compute
2662 * the retransmit timer, we want 1/2 tick of rounding and
2663 * 1 extra tick because of +-1/2 tick uncertainty in the
2664 * firing of the timer. The bias will give us exactly the
2665 * 1.5 tick we need. But, because the bias is
2666 * statistical, we have to test that we don't drop below
2667 * the minimum feasible timer (which is 2 ticks).
2669 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2670 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2673 * We received an ack for a packet that wasn't retransmitted;
2674 * it is probably safe to discard any error indications we've
2675 * received recently. This isn't quite right, but close enough
2676 * for now (a route might have failed after we sent a segment,
2677 * and the return path might not be symmetrical).
2679 tp->t_softerror = 0;
2683 * Determine a reasonable value for maxseg size.
2684 * If the route is known, check route for mtu.
2685 * If none, use an mss that can be handled on the outgoing
2686 * interface without forcing IP to fragment; if bigger than
2687 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2688 * to utilize large mbufs. If no route is found, route has no mtu,
2689 * or the destination isn't local, use a default, hopefully conservative
2690 * size (usually 512 or the default IP max size, but no more than the mtu
2691 * of the interface), as we can't discover anything about intervening
2692 * gateways or networks. We also initialize the congestion/slow start
2693 * window to be a single segment if the destination isn't local.
2694 * While looking at the routing entry, we also initialize other path-dependent
2695 * parameters from pre-set or cached values in the routing entry.
2697 * Also take into account the space needed for options that we
2698 * send regularly. Make maxseg shorter by that amount to assure
2699 * that we can send maxseg amount of data even when the options
2700 * are present. Store the upper limit of the length of options plus
2703 * In case of T/TCP, we call this routine during implicit connection
2704 * setup as well (offer = -1), to initialize maxseg from the cached
2707 * NOTE that this routine is only called when we process an incoming
2708 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2711 tcp_mss(struct tcpcb *tp, int offer)
2716 struct inpcb *inp = tp->t_inpcb;
2718 struct hc_metrics_lite metrics;
2719 int origoffer = offer;
2722 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2723 size_t min_protoh = isipv6 ?
2724 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2725 sizeof (struct tcpiphdr);
2727 const size_t min_protoh = sizeof(struct tcpiphdr);
2733 maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2734 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2738 maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2739 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2741 so = inp->inp_socket;
2744 * No route to sender, stay with default mss and return.
2749 /* What have we got? */
2753 * Offer == 0 means that there was no MSS on the SYN
2754 * segment, in this case we use tcp_mssdflt.
2758 isipv6 ? tcp_v6mssdflt :
2765 * Offer == -1 means that we didn't receive SYN yet.
2771 * Prevent DoS attack with too small MSS. Round up
2772 * to at least minmss.
2774 offer = max(offer, tcp_minmss);
2776 * Sanity check: make sure that maxopd will be large
2777 * enough to allow some data on segments even if the
2778 * all the option space is used (40bytes). Otherwise
2779 * funny things may happen in tcp_output.
2781 offer = max(offer, 64);
2785 * rmx information is now retrieved from tcp_hostcache.
2787 tcp_hc_get(&inp->inp_inc, &metrics);
2790 * If there's a discovered mtu int tcp hostcache, use it
2791 * else, use the link mtu.
2793 if (metrics.rmx_mtu)
2794 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2798 mss = maxmtu - min_protoh;
2799 if (!path_mtu_discovery &&
2800 !in6_localaddr(&inp->in6p_faddr))
2801 mss = min(mss, tcp_v6mssdflt);
2805 mss = maxmtu - min_protoh;
2806 if (!path_mtu_discovery &&
2807 !in_localaddr(inp->inp_faddr))
2808 mss = min(mss, tcp_mssdflt);
2811 mss = min(mss, offer);
2814 * maxopd stores the maximum length of data AND options
2815 * in a segment; maxseg is the amount of data in a normal
2816 * segment. We need to store this value (maxopd) apart
2817 * from maxseg, because now every segment carries options
2818 * and thus we normally have somewhat less data in segments.
2823 * origoffer==-1 indicates that no segments were received yet.
2824 * In this case we just guess.
2826 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2828 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2829 mss -= TCPOLEN_TSTAMP_APPA;
2832 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2834 mss &= ~(MCLBYTES-1);
2837 mss = mss / MCLBYTES * MCLBYTES;
2842 * If there's a pipesize, change the socket buffer to that size,
2843 * don't change if sb_hiwat is different than default (then it
2844 * has been changed on purpose with setsockopt).
2845 * Make the socket buffers an integral number of mss units;
2846 * if the mss is larger than the socket buffer, decrease the mss.
2848 SOCKBUF_LOCK(&so->so_snd);
2849 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2850 bufsize = metrics.rmx_sendpipe;
2852 bufsize = so->so_snd.sb_hiwat;
2856 bufsize = roundup(bufsize, mss);
2857 if (bufsize > sb_max)
2859 if (bufsize > so->so_snd.sb_hiwat)
2860 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2862 SOCKBUF_UNLOCK(&so->so_snd);
2865 SOCKBUF_LOCK(&so->so_rcv);
2866 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2867 bufsize = metrics.rmx_recvpipe;
2869 bufsize = so->so_rcv.sb_hiwat;
2870 if (bufsize > mss) {
2871 bufsize = roundup(bufsize, mss);
2872 if (bufsize > sb_max)
2874 if (bufsize > so->so_rcv.sb_hiwat)
2875 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
2877 SOCKBUF_UNLOCK(&so->so_rcv);
2879 * While we're here, check the others too.
2881 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
2883 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2884 tcpstat.tcps_usedrtt++;
2885 if (metrics.rmx_rttvar) {
2886 tp->t_rttvar = metrics.rmx_rttvar;
2887 tcpstat.tcps_usedrttvar++;
2889 /* default variation is +- 1 rtt */
2891 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2893 TCPT_RANGESET(tp->t_rxtcur,
2894 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2895 tp->t_rttmin, TCPTV_REXMTMAX);
2897 if (metrics.rmx_ssthresh) {
2899 * There's some sort of gateway or interface
2900 * buffer limit on the path. Use this to set
2901 * the slow start threshhold, but set the
2902 * threshold to no less than 2*mss.
2904 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
2905 tcpstat.tcps_usedssthresh++;
2907 if (metrics.rmx_bandwidth)
2908 tp->snd_bandwidth = metrics.rmx_bandwidth;
2911 * Set the slow-start flight size depending on whether this
2912 * is a local network or not.
2914 * Extend this so we cache the cwnd too and retrieve it here.
2915 * Make cwnd even bigger than RFC3390 suggests but only if we
2916 * have previous experience with the remote host. Be careful
2917 * not make cwnd bigger than remote receive window or our own
2918 * send socket buffer. Maybe put some additional upper bound
2919 * on the retrieved cwnd. Should do incremental updates to
2920 * hostcache when cwnd collapses so next connection doesn't
2921 * overloads the path again.
2923 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
2924 * We currently check only in syncache_socket for that.
2926 #define TCP_METRICS_CWND
2927 #ifdef TCP_METRICS_CWND
2928 if (metrics.rmx_cwnd)
2929 tp->snd_cwnd = max(mss,
2930 min(metrics.rmx_cwnd / 2,
2931 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
2935 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2937 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2938 (!isipv6 && in_localaddr(inp->inp_faddr)))
2940 else if (in_localaddr(inp->inp_faddr))
2942 tp->snd_cwnd = mss * ss_fltsz_local;
2944 tp->snd_cwnd = mss * ss_fltsz;
2946 /* Check the interface for TSO capabilities. */
2947 if (mtuflags & CSUM_TSO)
2948 tp->t_flags |= TF_TSO;
2952 * Determine the MSS option to send on an outgoing SYN.
2955 tcp_mssopt(struct in_conninfo *inc)
2962 int isipv6 = inc->inc_isipv6 ? 1 : 0;
2965 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
2969 mss = tcp_v6mssdflt;
2970 maxmtu = tcp_maxmtu6(inc, NULL);
2971 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
2972 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
2977 maxmtu = tcp_maxmtu(inc, NULL);
2978 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
2979 min_protoh = sizeof(struct tcpiphdr);
2981 if (maxmtu && thcmtu)
2982 mss = min(maxmtu, thcmtu) - min_protoh;
2983 else if (maxmtu || thcmtu)
2984 mss = max(maxmtu, thcmtu) - min_protoh;
2991 * On a partial ack arrives, force the retransmission of the
2992 * next unacknowledged segment. Do not clear tp->t_dupacks.
2993 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2997 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
2999 tcp_seq onxt = tp->snd_nxt;
3000 u_long ocwnd = tp->snd_cwnd;
3002 tcp_timer_activate(tp, TT_REXMT, 0);
3004 tp->snd_nxt = th->th_ack;
3006 * Set snd_cwnd to one segment beyond acknowledged offset.
3007 * (tp->snd_una has not yet been updated when this function is called.)
3009 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3010 tp->t_flags |= TF_ACKNOW;
3011 (void) tcp_output(tp);
3012 tp->snd_cwnd = ocwnd;
3013 if (SEQ_GT(onxt, tp->snd_nxt))
3016 * Partial window deflation. Relies on fact that tp->snd_una
3019 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3020 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3023 tp->snd_cwnd += tp->t_maxseg;