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 #include <netinet/in.h>
61 #include <netinet/in_pcb.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
66 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
67 #include <netinet/ip_var.h>
68 #include <netinet/ip_options.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <netinet6/in6_pcb.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/nd6.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_fsm.h>
76 #include <netinet/tcp_seq.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #include <netinet6/tcp6_var.h>
80 #include <netinet/tcpip.h>
81 #include <netinet/tcp_syncache.h>
83 #include <netinet/tcp_debug.h>
87 #include <netipsec/ipsec.h>
88 #include <netipsec/ipsec6.h>
91 #include <machine/in_cksum.h>
93 #include <security/mac/mac_framework.h>
95 static const int tcprexmtthresh = 3;
97 struct tcpstat tcpstat;
98 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
99 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
101 static int tcp_log_in_vain = 0;
102 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
103 &tcp_log_in_vain, 0, "Log all incoming TCP segments to closed ports");
105 static int blackhole = 0;
106 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
107 &blackhole, 0, "Do not send RST on segments to closed ports");
109 int tcp_delack_enabled = 1;
110 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
111 &tcp_delack_enabled, 0,
112 "Delay ACK to try and piggyback it onto a data packet");
114 static int drop_synfin = 0;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
116 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
118 static int tcp_do_rfc3042 = 1;
119 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
120 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
122 static int tcp_do_rfc3390 = 1;
123 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
125 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
127 static int tcp_insecure_rst = 0;
128 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
129 &tcp_insecure_rst, 0,
130 "Follow the old (insecure) criteria for accepting RST packets");
132 int tcp_do_autorcvbuf = 1;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
134 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
136 int tcp_autorcvbuf_inc = 16*1024;
137 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
138 &tcp_autorcvbuf_inc, 0,
139 "Incrementor step size of automatic receive buffer");
141 int tcp_autorcvbuf_max = 256*1024;
142 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
143 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
145 struct inpcbhead tcb;
146 #define tcb6 tcb /* for KAME src sync over BSD*'s */
147 struct inpcbinfo tcbinfo;
149 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
150 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
151 struct socket *, struct tcpcb *, int, int);
152 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
153 struct tcpcb *, int, int);
154 static void tcp_pulloutofband(struct socket *,
155 struct tcphdr *, struct mbuf *, int);
156 static void tcp_xmit_timer(struct tcpcb *, int);
157 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
159 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
161 #define ND6_HINT(tp) \
163 if ((tp) && (tp)->t_inpcb && \
164 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
165 nd6_nud_hint(NULL, NULL, 0); \
172 * Indicate whether this ack should be delayed. We can delay the ack if
173 * - there is no delayed ack timer in progress and
174 * - our last ack wasn't a 0-sized window. We never want to delay
175 * the ack that opens up a 0-sized window and
176 * - delayed acks are enabled or
177 * - this is a half-synchronized T/TCP connection.
179 #define DELAY_ACK(tp) \
180 ((!tcp_timer_active(tp, TT_DELACK) && \
181 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
182 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
186 * TCP input handling is split into multiple parts:
187 * tcp6_input is a thin wrapper around tcp_input for the extended
188 * ip6_protox[] call format in ip6_input
189 * tcp_input handles primary segment validation, inpcb lookup and
190 * SYN processing on listen sockets
191 * tcp_do_segment processes the ACK and text of the segment for
192 * establishing, established and closing connections
196 tcp6_input(struct mbuf **mp, int *offp, int proto)
198 struct mbuf *m = *mp;
199 struct in6_ifaddr *ia6;
201 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
204 * draft-itojun-ipv6-tcp-to-anycast
205 * better place to put this in?
207 ia6 = ip6_getdstifaddr(m);
208 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
211 ip6 = mtod(m, struct ip6_hdr *);
212 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
213 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
223 tcp_input(struct mbuf *m, int off0)
226 struct ip *ip = NULL;
228 struct inpcb *inp = NULL;
229 struct tcpcb *tp = NULL;
230 struct socket *so = NULL;
236 int rstreason = 0; /* For badport_bandlim accounting purposes */
237 #ifdef IPFIREWALL_FORWARD
238 struct m_tag *fwd_tag;
241 struct ip6_hdr *ip6 = NULL;
244 const void *ip6 = NULL;
245 const int isipv6 = 0;
247 struct tcpopt to; /* options in this segment */
248 char *s = NULL; /* address and port logging */
252 * The size of tcp_saveipgen must be the size of the max ip header,
255 u_char tcp_saveipgen[IP6_HDR_LEN];
256 struct tcphdr tcp_savetcp;
261 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
265 tcpstat.tcps_rcvtotal++;
269 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
270 ip6 = mtod(m, struct ip6_hdr *);
271 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
272 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
273 tcpstat.tcps_rcvbadsum++;
276 th = (struct tcphdr *)((caddr_t)ip6 + off0);
279 * Be proactive about unspecified IPv6 address in source.
280 * As we use all-zero to indicate unbounded/unconnected pcb,
281 * unspecified IPv6 address can be used to confuse us.
283 * Note that packets with unspecified IPv6 destination is
284 * already dropped in ip6_input.
286 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
291 th = NULL; /* XXX: Avoid compiler warning. */
295 * Get IP and TCP header together in first mbuf.
296 * Note: IP leaves IP header in first mbuf.
298 if (off0 > sizeof (struct ip)) {
299 ip_stripoptions(m, (struct mbuf *)0);
300 off0 = sizeof(struct ip);
302 if (m->m_len < sizeof (struct tcpiphdr)) {
303 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
305 tcpstat.tcps_rcvshort++;
309 ip = mtod(m, struct ip *);
310 ipov = (struct ipovly *)ip;
311 th = (struct tcphdr *)((caddr_t)ip + off0);
314 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
315 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
316 th->th_sum = m->m_pkthdr.csum_data;
318 th->th_sum = in_pseudo(ip->ip_src.s_addr,
320 htonl(m->m_pkthdr.csum_data +
323 th->th_sum ^= 0xffff;
325 ipov->ih_len = (u_short)tlen;
326 ipov->ih_len = htons(ipov->ih_len);
330 * Checksum extended TCP header and data.
332 len = sizeof (struct ip) + tlen;
333 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
334 ipov->ih_len = (u_short)tlen;
335 ipov->ih_len = htons(ipov->ih_len);
336 th->th_sum = in_cksum(m, len);
339 tcpstat.tcps_rcvbadsum++;
342 /* Re-initialization for later version check */
343 ip->ip_v = IPVERSION;
347 * Check that TCP offset makes sense,
348 * pull out TCP options and adjust length. XXX
350 off = th->th_off << 2;
351 if (off < sizeof (struct tcphdr) || off > tlen) {
352 tcpstat.tcps_rcvbadoff++;
355 tlen -= off; /* tlen is used instead of ti->ti_len */
356 if (off > sizeof (struct tcphdr)) {
359 IP6_EXTHDR_CHECK(m, off0, off, );
360 ip6 = mtod(m, struct ip6_hdr *);
361 th = (struct tcphdr *)((caddr_t)ip6 + off0);
364 if (m->m_len < sizeof(struct ip) + off) {
365 if ((m = m_pullup(m, sizeof (struct ip) + off))
367 tcpstat.tcps_rcvshort++;
370 ip = mtod(m, struct ip *);
371 ipov = (struct ipovly *)ip;
372 th = (struct tcphdr *)((caddr_t)ip + off0);
375 optlen = off - sizeof (struct tcphdr);
376 optp = (u_char *)(th + 1);
378 thflags = th->th_flags;
381 * Convert TCP protocol specific fields to host format.
383 th->th_seq = ntohl(th->th_seq);
384 th->th_ack = ntohl(th->th_ack);
385 th->th_win = ntohs(th->th_win);
386 th->th_urp = ntohs(th->th_urp);
389 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
391 drop_hdrlen = off0 + off;
394 * Locate pcb for segment.
396 INP_INFO_WLOCK(&tcbinfo);
398 INP_INFO_WLOCK_ASSERT(&tcbinfo);
399 #ifdef IPFIREWALL_FORWARD
401 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
403 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
405 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
406 struct sockaddr_in *next_hop;
408 next_hop = (struct sockaddr_in *)(fwd_tag+1);
410 * Transparently forwarded. Pretend to be the destination.
411 * already got one like this?
413 inp = in_pcblookup_hash(&tcbinfo,
414 ip->ip_src, th->th_sport,
415 ip->ip_dst, th->th_dport,
416 0, m->m_pkthdr.rcvif);
418 /* It's new. Try to find the ambushing socket. */
419 inp = in_pcblookup_hash(&tcbinfo,
420 ip->ip_src, th->th_sport,
423 ntohs(next_hop->sin_port) :
428 /* Remove the tag from the packet. We don't need it anymore. */
429 m_tag_delete(m, fwd_tag);
431 #endif /* IPFIREWALL_FORWARD */
435 inp = in6_pcblookup_hash(&tcbinfo,
436 &ip6->ip6_src, th->th_sport,
437 &ip6->ip6_dst, th->th_dport,
442 inp = in_pcblookup_hash(&tcbinfo,
443 ip->ip_src, th->th_sport,
444 ip->ip_dst, th->th_dport,
451 if (isipv6 && inp != NULL && ipsec6_in_reject(m, inp)) {
452 ipsec6stat.in_polvio++;
456 if (inp != NULL && ipsec4_in_reject(m, inp)) {
457 ipsec4stat.in_polvio++;
463 * If the INPCB does not exist then all data in the incoming
464 * segment is discarded and an appropriate RST is sent back.
468 * Log communication attempts to ports that are not
471 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
472 tcp_log_in_vain == 2) {
473 if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
474 log(LOG_INFO, "%s; %s: Connection attempt "
475 "to closed port\n", s, __func__);
478 * When blackholing do not respond with a RST but
479 * completely ignore the segment and drop it.
481 if ((blackhole == 1 && (thflags & TH_SYN)) ||
485 rstreason = BANDLIM_RST_CLOSEDPORT;
491 * Check the minimum TTL for socket.
493 if (inp->inp_ip_minttl != 0) {
495 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
499 if (inp->inp_ip_minttl > ip->ip_ttl)
504 * A previous connection in TIMEWAIT state is supposed to catch
505 * stray or duplicate segments arriving late. If this segment
506 * was a legitimate new connection attempt the old INPCB gets
507 * removed and we can try again to find a listening socket.
509 if (inp->inp_vflag & INP_TIMEWAIT) {
510 if (thflags & TH_SYN)
511 tcp_dooptions(&to, optp, optlen, TO_SYN);
513 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
515 if (tcp_twcheck(inp, &to, th, m, tlen))
517 INP_INFO_WUNLOCK(&tcbinfo);
521 * The TCPCB may no longer exist if the connection is winding
522 * down or it is in the CLOSED state. Either way we drop the
523 * segment and send an appropriate response.
526 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
527 rstreason = BANDLIM_RST_CLOSEDPORT;
532 INP_LOCK_ASSERT(inp);
533 if (mac_check_inpcb_deliver(inp, m))
536 so = inp->inp_socket;
537 KASSERT(so != NULL, ("%s: so == NULL", __func__));
539 if (so->so_options & SO_DEBUG) {
540 ostate = tp->t_state;
543 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
546 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
551 * When the socket is accepting connections (the INPCB is in LISTEN
552 * state) we look into the SYN cache if this is a new connection
553 * attempt or the completion of a previous one.
555 if (so->so_options & SO_ACCEPTCONN) {
556 struct in_conninfo inc;
558 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
559 "tp not listening", __func__));
561 bzero(&inc, sizeof(inc));
562 inc.inc_isipv6 = isipv6;
565 inc.inc6_faddr = ip6->ip6_src;
566 inc.inc6_laddr = ip6->ip6_dst;
570 inc.inc_faddr = ip->ip_src;
571 inc.inc_laddr = ip->ip_dst;
573 inc.inc_fport = th->th_sport;
574 inc.inc_lport = th->th_dport;
577 * Check for an existing connection attempt in syncache if
578 * the flag is only ACK. A successful lookup creates a new
579 * socket appended to the listen queue in SYN_RECEIVED state.
581 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
583 * Parse the TCP options here because
584 * syncookies need access to the reflected
587 tcp_dooptions(&to, optp, optlen, 0);
589 * NB: syncache_expand() doesn't unlock
590 * inp and tcpinfo locks.
592 if (!syncache_expand(&inc, &to, th, &so, m)) {
594 * No syncache entry or ACK was not
595 * for our SYN/ACK. Send a RST.
596 * NB: syncache did its own logging
597 * of the failure cause.
599 rstreason = BANDLIM_RST_OPENPORT;
604 * We completed the 3-way handshake
605 * but could not allocate a socket
606 * either due to memory shortage,
607 * listen queue length limits or
608 * global socket limits. Send RST
609 * or wait and have the remote end
610 * retransmit the ACK for another
613 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
614 log(LOG_DEBUG, "%s; %s: Listen socket: "
615 "Socket allocation failed due to "
616 "limits or memory shortage, %s\n",
617 s, __func__, (tcp_sc_rst_sock_fail ?
618 "sending RST" : "try again"));
619 if (tcp_sc_rst_sock_fail) {
620 rstreason = BANDLIM_UNLIMITED;
626 * Socket is created in state SYN_RECEIVED.
627 * Unlock the listen socket, lock the newly
628 * created socket and update the tp variable.
630 INP_UNLOCK(inp); /* listen socket */
632 INP_LOCK(inp); /* new connection */
634 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
637 * Process the segment and the data it
638 * contains. tcp_do_segment() consumes
639 * the mbuf chain and unlocks the inpcb.
641 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
642 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
646 * Segment flag validation for new connection attempts:
648 * Our (SYN|ACK) response was rejected.
649 * Check with syncache and remove entry to prevent
652 * NB: syncache_chkrst does its own logging of failure
655 if (thflags & TH_RST) {
656 syncache_chkrst(&inc, th);
660 * We can't do anything without SYN.
662 if ((thflags & TH_SYN) == 0) {
663 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
664 log(LOG_DEBUG, "%s; %s: Listen socket: "
665 "SYN is missing, segment rejected\n",
667 tcpstat.tcps_badsyn++;
671 * (SYN|ACK) is bogus on a listen socket.
673 if (thflags & TH_ACK) {
674 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
675 log(LOG_DEBUG, "%s; %s: Listen socket: "
676 "SYN|ACK invalid, segment rejected\n",
678 syncache_badack(&inc); /* XXX: Not needed! */
679 tcpstat.tcps_badsyn++;
680 rstreason = BANDLIM_RST_OPENPORT;
684 * If the drop_synfin option is enabled, drop all
685 * segments with both the SYN and FIN bits set.
686 * This prevents e.g. nmap from identifying the
688 * XXX: Poor reasoning. nmap has other methods
689 * and is constantly refining its stack detection
691 * XXX: This is a violation of the TCP specification
692 * and was used by RFC1644.
694 if ((thflags & TH_FIN) && drop_synfin) {
695 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
696 log(LOG_DEBUG, "%s; %s: Listen socket: "
697 "SYN|FIN segment rejected (based on "
698 "sysctl setting)\n", s, __func__);
699 tcpstat.tcps_badsyn++;
703 * Segment's flags are (SYN) or (SYN|FIN).
705 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
706 * as they do not affect the state of the TCP FSM.
707 * The data pointed to by TH_URG and th_urp is ignored.
709 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
710 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
711 KASSERT(thflags & (TH_SYN),
712 ("%s: Listen socket: TH_SYN not set", __func__));
715 * If deprecated address is forbidden,
716 * we do not accept SYN to deprecated interface
717 * address to prevent any new inbound connection from
718 * getting established.
719 * When we do not accept SYN, we send a TCP RST,
720 * with deprecated source address (instead of dropping
721 * it). We compromise it as it is much better for peer
722 * to send a RST, and RST will be the final packet
725 * If we do not forbid deprecated addresses, we accept
726 * the SYN packet. RFC2462 does not suggest dropping
728 * If we decipher RFC2462 5.5.4, it says like this:
729 * 1. use of deprecated addr with existing
730 * communication is okay - "SHOULD continue to be
732 * 2. use of it with new communication:
733 * (2a) "SHOULD NOT be used if alternate address
734 * with sufficient scope is available"
735 * (2b) nothing mentioned otherwise.
736 * Here we fall into (2b) case as we have no choice in
737 * our source address selection - we must obey the peer.
739 * The wording in RFC2462 is confusing, and there are
740 * multiple description text for deprecated address
741 * handling - worse, they are not exactly the same.
742 * I believe 5.5.4 is the best one, so we follow 5.5.4.
744 if (isipv6 && !ip6_use_deprecated) {
745 struct in6_ifaddr *ia6;
747 if ((ia6 = ip6_getdstifaddr(m)) &&
748 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
749 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
750 log(LOG_DEBUG, "%s; %s: Listen socket: "
751 "Connection attempt to deprecated "
752 "IPv6 address rejected\n",
754 rstreason = BANDLIM_RST_OPENPORT;
760 * Basic sanity checks on incoming SYN requests:
761 * Don't respond if the destination is a link layer
762 * broadcast according to RFC1122 4.2.3.10, p. 104.
763 * If it is from this socket it must be forged.
764 * Don't respond if the source or destination is a
765 * global or subnet broad- or multicast address.
766 * Note that it is quite possible to receive unicast
767 * link-layer packets with a broadcast IP address. Use
768 * in_broadcast() to find them.
770 if (m->m_flags & (M_BCAST|M_MCAST)) {
771 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
772 log(LOG_DEBUG, "%s; %s: Listen socket: "
773 "Connection attempt from broad- or multicast "
774 "link layer address rejected\n", s, __func__);
779 if (th->th_dport == th->th_sport &&
780 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
781 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
782 log(LOG_DEBUG, "%s; %s: Listen socket: "
783 "Connection attempt to/from self "
784 "rejected\n", s, __func__);
787 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
788 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
789 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
790 log(LOG_DEBUG, "%s; %s: Listen socket: "
791 "Connection attempt from/to multicast "
792 "address rejected\n", s, __func__);
797 if (th->th_dport == th->th_sport &&
798 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
799 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
800 log(LOG_DEBUG, "%s; %s: Listen socket: "
801 "Connection attempt from/to self "
802 "rejected\n", s, __func__);
805 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
806 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
807 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
808 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
809 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
810 log(LOG_DEBUG, "%s; %s: Listen socket: "
811 "Connection attempt from/to broad- "
812 "or multicast address rejected\n",
818 * SYN appears to be valid. Create compressed TCP state
822 if (so->so_options & SO_DEBUG)
823 tcp_trace(TA_INPUT, ostate, tp,
824 (void *)tcp_saveipgen, &tcp_savetcp, 0);
826 tcp_dooptions(&to, optp, optlen, TO_SYN);
827 syncache_add(&inc, &to, th, inp, &so, m);
829 * Entry added to syncache and mbuf consumed.
830 * Everything already unlocked by syncache_add().
832 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
837 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
838 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
839 * the inpcb, and unlocks pcbinfo.
841 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
842 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
846 INP_INFO_WLOCK_ASSERT(&tcbinfo);
847 tcp_dropwithreset(m, th, tp, tlen, rstreason);
848 m = NULL; /* mbuf chain got consumed. */
850 INP_INFO_WLOCK_ASSERT(&tcbinfo);
853 INP_INFO_WUNLOCK(&tcbinfo);
855 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
864 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
865 struct tcpcb *tp, int drop_hdrlen, int tlen)
867 int thflags, acked, ourfinisacked, needoutput = 0;
869 int rstreason, todrop, win;
875 * The size of tcp_saveipgen must be the size of the max ip header,
878 u_char tcp_saveipgen[IP6_HDR_LEN];
879 struct tcphdr tcp_savetcp;
882 thflags = th->th_flags;
884 INP_INFO_WLOCK_ASSERT(&tcbinfo);
885 INP_LOCK_ASSERT(tp->t_inpcb);
886 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
888 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
892 * Segment received on connection.
893 * Reset idle time and keep-alive timer.
894 * XXX: This should be done after segment
895 * validation to ignore broken/spoofed segs.
897 tp->t_rcvtime = ticks;
898 if (TCPS_HAVEESTABLISHED(tp->t_state))
899 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
902 * Unscale the window into a 32-bit value.
903 * For the SYN_SENT state the scale is zero.
905 tiwin = th->th_win << tp->snd_scale;
908 * Parse options on any incoming segment.
910 tcp_dooptions(&to, (u_char *)(th + 1),
911 (th->th_off << 2) - sizeof(struct tcphdr),
912 (thflags & TH_SYN) ? TO_SYN : 0);
915 * If echoed timestamp is later than the current time,
916 * fall back to non RFC1323 RTT calculation. Normalize
917 * timestamp if syncookies were used when this connection
920 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
921 to.to_tsecr -= tp->ts_offset;
922 if (TSTMP_GT(to.to_tsecr, ticks))
927 * Process options only when we get SYN/ACK back. The SYN case
928 * for incoming connections is handled in tcp_syncache.
929 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
930 * or <SYN,ACK>) segment itself is never scaled.
931 * XXX this is traditional behavior, may need to be cleaned up.
933 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
934 if ((to.to_flags & TOF_SCALE) &&
935 (tp->t_flags & TF_REQ_SCALE)) {
936 tp->t_flags |= TF_RCVD_SCALE;
937 tp->snd_scale = to.to_wscale;
940 * Initial send window. It will be updated with
941 * the next incoming segment to the scaled value.
943 tp->snd_wnd = th->th_win;
944 if (to.to_flags & TOF_TS) {
945 tp->t_flags |= TF_RCVD_TSTMP;
946 tp->ts_recent = to.to_tsval;
947 tp->ts_recent_age = ticks;
949 if (to.to_flags & TOF_MSS)
950 tcp_mss(tp, to.to_mss);
951 if ((tp->t_flags & TF_SACK_PERMIT) &&
952 (to.to_flags & TOF_SACKPERM) == 0)
953 tp->t_flags &= ~TF_SACK_PERMIT;
957 * Header prediction: check for the two common cases
958 * of a uni-directional data xfer. If the packet has
959 * no control flags, is in-sequence, the window didn't
960 * change and we're not retransmitting, it's a
961 * candidate. If the length is zero and the ack moved
962 * forward, we're the sender side of the xfer. Just
963 * free the data acked & wake any higher level process
964 * that was blocked waiting for space. If the length
965 * is non-zero and the ack didn't move, we're the
966 * receiver side. If we're getting packets in-order
967 * (the reassembly queue is empty), add the data to
968 * the socket buffer and note that we need a delayed ack.
969 * Make sure that the hidden state-flags are also off.
970 * Since we check for TCPS_ESTABLISHED first, it can only
973 if (tp->t_state == TCPS_ESTABLISHED &&
974 th->th_seq == tp->rcv_nxt &&
975 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
976 tp->snd_nxt == tp->snd_max &&
977 tiwin && tiwin == tp->snd_wnd &&
978 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
979 LIST_EMPTY(&tp->t_segq) &&
980 ((to.to_flags & TOF_TS) == 0 ||
981 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
984 * If last ACK falls within this segment's sequence numbers,
985 * record the timestamp.
986 * NOTE that the test is modified according to the latest
987 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
989 if ((to.to_flags & TOF_TS) != 0 &&
990 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
991 tp->ts_recent_age = ticks;
992 tp->ts_recent = to.to_tsval;
996 if (SEQ_GT(th->th_ack, tp->snd_una) &&
997 SEQ_LEQ(th->th_ack, tp->snd_max) &&
998 tp->snd_cwnd >= tp->snd_wnd &&
1000 !(tp->t_flags & TF_SACK_PERMIT) &&
1001 tp->t_dupacks < tcprexmtthresh) ||
1003 (tp->t_flags & TF_SACK_PERMIT)) &&
1004 !IN_FASTRECOVERY(tp) &&
1005 (to.to_flags & TOF_SACK) == 0 &&
1006 TAILQ_EMPTY(&tp->snd_holes)))) {
1008 ("%s: headlocked", __func__));
1009 INP_INFO_WUNLOCK(&tcbinfo);
1012 * This is a pure ack for outstanding data.
1014 ++tcpstat.tcps_predack;
1016 * "bad retransmit" recovery.
1018 if (tp->t_rxtshift == 1 &&
1019 ticks < tp->t_badrxtwin) {
1020 ++tcpstat.tcps_sndrexmitbad;
1021 tp->snd_cwnd = tp->snd_cwnd_prev;
1023 tp->snd_ssthresh_prev;
1024 tp->snd_recover = tp->snd_recover_prev;
1025 if (tp->t_flags & TF_WASFRECOVERY)
1026 ENTER_FASTRECOVERY(tp);
1027 tp->snd_nxt = tp->snd_max;
1028 tp->t_badrxtwin = 0;
1032 * Recalculate the transmit timer / rtt.
1034 * Some boxes send broken timestamp replies
1035 * during the SYN+ACK phase, ignore
1036 * timestamps of 0 or we could calculate a
1037 * huge RTT and blow up the retransmit timer.
1039 if ((to.to_flags & TOF_TS) != 0 &&
1041 if (!tp->t_rttlow ||
1042 tp->t_rttlow > ticks - to.to_tsecr)
1043 tp->t_rttlow = ticks - to.to_tsecr;
1045 ticks - to.to_tsecr + 1);
1046 } else if (tp->t_rtttime &&
1047 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1048 if (!tp->t_rttlow ||
1049 tp->t_rttlow > ticks - tp->t_rtttime)
1050 tp->t_rttlow = ticks - tp->t_rtttime;
1052 ticks - tp->t_rtttime);
1054 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1055 acked = th->th_ack - tp->snd_una;
1056 tcpstat.tcps_rcvackpack++;
1057 tcpstat.tcps_rcvackbyte += acked;
1058 sbdrop(&so->so_snd, acked);
1059 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1060 SEQ_LEQ(th->th_ack, tp->snd_recover))
1061 tp->snd_recover = th->th_ack - 1;
1062 tp->snd_una = th->th_ack;
1064 * Pull snd_wl2 up to prevent seq wrap relative
1067 tp->snd_wl2 = th->th_ack;
1070 ND6_HINT(tp); /* Some progress has been made. */
1073 * If all outstanding data are acked, stop
1074 * retransmit timer, otherwise restart timer
1075 * using current (possibly backed-off) value.
1076 * If process is waiting for space,
1077 * wakeup/selwakeup/signal. If data
1078 * are ready to send, let tcp_output
1079 * decide between more output or persist.
1082 if (so->so_options & SO_DEBUG)
1083 tcp_trace(TA_INPUT, ostate, tp,
1084 (void *)tcp_saveipgen,
1087 if (tp->snd_una == tp->snd_max)
1088 tcp_timer_activate(tp, TT_REXMT, 0);
1089 else if (!tcp_timer_active(tp, TT_PERSIST))
1090 tcp_timer_activate(tp, TT_REXMT,
1093 if (so->so_snd.sb_cc)
1094 (void) tcp_output(tp);
1097 } else if (th->th_ack == tp->snd_una &&
1098 tlen <= sbspace(&so->so_rcv)) {
1099 int newsize = 0; /* automatic sockbuf scaling */
1101 KASSERT(headlocked, ("%s: headlocked", __func__));
1102 INP_INFO_WUNLOCK(&tcbinfo);
1105 * This is a pure, in-sequence data packet
1106 * with nothing on the reassembly queue and
1107 * we have enough buffer space to take it.
1109 /* Clean receiver SACK report if present */
1110 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1111 tcp_clean_sackreport(tp);
1112 ++tcpstat.tcps_preddat;
1113 tp->rcv_nxt += tlen;
1115 * Pull snd_wl1 up to prevent seq wrap relative to
1118 tp->snd_wl1 = th->th_seq;
1120 * Pull rcv_up up to prevent seq wrap relative to
1123 tp->rcv_up = tp->rcv_nxt;
1124 tcpstat.tcps_rcvpack++;
1125 tcpstat.tcps_rcvbyte += tlen;
1126 ND6_HINT(tp); /* Some progress has been made */
1128 if (so->so_options & SO_DEBUG)
1129 tcp_trace(TA_INPUT, ostate, tp,
1130 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1133 * Automatic sizing of receive socket buffer. Often the send
1134 * buffer size is not optimally adjusted to the actual network
1135 * conditions at hand (delay bandwidth product). Setting the
1136 * buffer size too small limits throughput on links with high
1137 * bandwidth and high delay (eg. trans-continental/oceanic links).
1139 * On the receive side the socket buffer memory is only rarely
1140 * used to any significant extent. This allows us to be much
1141 * more aggressive in scaling the receive socket buffer. For
1142 * the case that the buffer space is actually used to a large
1143 * extent and we run out of kernel memory we can simply drop
1144 * the new segments; TCP on the sender will just retransmit it
1145 * later. Setting the buffer size too big may only consume too
1146 * much kernel memory if the application doesn't read() from
1147 * the socket or packet loss or reordering makes use of the
1150 * The criteria to step up the receive buffer one notch are:
1151 * 1. the number of bytes received during the time it takes
1152 * one timestamp to be reflected back to us (the RTT);
1153 * 2. received bytes per RTT is within seven eighth of the
1154 * current socket buffer size;
1155 * 3. receive buffer size has not hit maximal automatic size;
1157 * This algorithm does one step per RTT at most and only if
1158 * we receive a bulk stream w/o packet losses or reorderings.
1159 * Shrinking the buffer during idle times is not necessary as
1160 * it doesn't consume any memory when idle.
1162 * TODO: Only step up if the application is actually serving
1163 * the buffer to better manage the socket buffer resources.
1165 if (tcp_do_autorcvbuf &&
1167 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1168 if (to.to_tsecr > tp->rfbuf_ts &&
1169 to.to_tsecr - tp->rfbuf_ts < hz) {
1171 (so->so_rcv.sb_hiwat / 8 * 7) &&
1172 so->so_rcv.sb_hiwat <
1173 tcp_autorcvbuf_max) {
1175 min(so->so_rcv.sb_hiwat +
1177 tcp_autorcvbuf_max);
1179 /* Start over with next RTT. */
1183 tp->rfbuf_cnt += tlen; /* add up */
1186 /* Add data to socket buffer. */
1187 SOCKBUF_LOCK(&so->so_rcv);
1188 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1192 * Set new socket buffer size.
1193 * Give up when limit is reached.
1196 if (!sbreserve_locked(&so->so_rcv,
1197 newsize, so, curthread))
1198 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1199 m_adj(m, drop_hdrlen); /* delayed header drop */
1200 sbappendstream_locked(&so->so_rcv, m);
1202 /* NB: sorwakeup_locked() does an implicit unlock. */
1203 sorwakeup_locked(so);
1204 if (DELAY_ACK(tp)) {
1205 tp->t_flags |= TF_DELACK;
1207 tp->t_flags |= TF_ACKNOW;
1215 * Calculate amount of space in receive window,
1216 * and then do TCP input processing.
1217 * Receive window is amount of space in rcv queue,
1218 * but not less than advertised window.
1220 win = sbspace(&so->so_rcv);
1223 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1225 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1229 switch (tp->t_state) {
1232 * If the state is SYN_RECEIVED:
1233 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1235 case TCPS_SYN_RECEIVED:
1236 if ((thflags & TH_ACK) &&
1237 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1238 SEQ_GT(th->th_ack, tp->snd_max))) {
1239 rstreason = BANDLIM_RST_OPENPORT;
1245 * If the state is SYN_SENT:
1246 * if seg contains an ACK, but not for our SYN, drop the input.
1247 * if seg contains a RST, then drop the connection.
1248 * if seg does not contain SYN, then drop it.
1249 * Otherwise this is an acceptable SYN segment
1250 * initialize tp->rcv_nxt and tp->irs
1251 * if seg contains ack then advance tp->snd_una
1252 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1253 * arrange for segment to be acked (eventually)
1254 * continue processing rest of data/controls, beginning with URG
1257 if ((thflags & TH_ACK) &&
1258 (SEQ_LEQ(th->th_ack, tp->iss) ||
1259 SEQ_GT(th->th_ack, tp->snd_max))) {
1260 rstreason = BANDLIM_UNLIMITED;
1263 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1264 tp = tcp_drop(tp, ECONNREFUSED);
1265 if (thflags & TH_RST)
1267 if (!(thflags & TH_SYN))
1270 tp->irs = th->th_seq;
1272 if (thflags & TH_ACK) {
1273 tcpstat.tcps_connects++;
1277 mac_set_socket_peer_from_mbuf(m, so);
1280 /* Do window scaling on this connection? */
1281 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1282 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1283 tp->rcv_scale = tp->request_r_scale;
1285 tp->rcv_adv += tp->rcv_wnd;
1286 tp->snd_una++; /* SYN is acked */
1288 * If there's data, delay ACK; if there's also a FIN
1289 * ACKNOW will be turned on later.
1291 if (DELAY_ACK(tp) && tlen != 0)
1292 tcp_timer_activate(tp, TT_DELACK,
1295 tp->t_flags |= TF_ACKNOW;
1297 * Received <SYN,ACK> in SYN_SENT[*] state.
1299 * SYN_SENT --> ESTABLISHED
1300 * SYN_SENT* --> FIN_WAIT_1
1302 tp->t_starttime = ticks;
1303 if (tp->t_flags & TF_NEEDFIN) {
1304 tp->t_state = TCPS_FIN_WAIT_1;
1305 tp->t_flags &= ~TF_NEEDFIN;
1308 tp->t_state = TCPS_ESTABLISHED;
1309 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1313 * Received initial SYN in SYN-SENT[*] state =>
1314 * simultaneous open. If segment contains CC option
1315 * and there is a cached CC, apply TAO test.
1316 * If it succeeds, connection is * half-synchronized.
1317 * Otherwise, do 3-way handshake:
1318 * SYN-SENT -> SYN-RECEIVED
1319 * SYN-SENT* -> SYN-RECEIVED*
1320 * If there was no CC option, clear cached CC value.
1322 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1323 tcp_timer_activate(tp, TT_REXMT, 0);
1324 tp->t_state = TCPS_SYN_RECEIVED;
1327 KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1329 INP_LOCK_ASSERT(tp->t_inpcb);
1332 * Advance th->th_seq to correspond to first data byte.
1333 * If data, trim to stay within window,
1334 * dropping FIN if necessary.
1337 if (tlen > tp->rcv_wnd) {
1338 todrop = tlen - tp->rcv_wnd;
1342 tcpstat.tcps_rcvpackafterwin++;
1343 tcpstat.tcps_rcvbyteafterwin += todrop;
1345 tp->snd_wl1 = th->th_seq - 1;
1346 tp->rcv_up = th->th_seq;
1348 * Client side of transaction: already sent SYN and data.
1349 * If the remote host used T/TCP to validate the SYN,
1350 * our data will be ACK'd; if so, enter normal data segment
1351 * processing in the middle of step 5, ack processing.
1352 * Otherwise, goto step 6.
1354 if (thflags & TH_ACK)
1360 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1361 * do normal processing.
1363 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1367 break; /* continue normal processing */
1371 * States other than LISTEN or SYN_SENT.
1372 * First check the RST flag and sequence number since reset segments
1373 * are exempt from the timestamp and connection count tests. This
1374 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1375 * below which allowed reset segments in half the sequence space
1376 * to fall though and be processed (which gives forged reset
1377 * segments with a random sequence number a 50 percent chance of
1378 * killing a connection).
1379 * Then check timestamp, if present.
1380 * Then check the connection count, if present.
1381 * Then check that at least some bytes of segment are within
1382 * receive window. If segment begins before rcv_nxt,
1383 * drop leading data (and SYN); if nothing left, just ack.
1386 * If the RST bit is set, check the sequence number to see
1387 * if this is a valid reset segment.
1389 * In all states except SYN-SENT, all reset (RST) segments
1390 * are validated by checking their SEQ-fields. A reset is
1391 * valid if its sequence number is in the window.
1392 * Note: this does not take into account delayed ACKs, so
1393 * we should test against last_ack_sent instead of rcv_nxt.
1394 * The sequence number in the reset segment is normally an
1395 * echo of our outgoing acknowlegement numbers, but some hosts
1396 * send a reset with the sequence number at the rightmost edge
1397 * of our receive window, and we have to handle this case.
1398 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1399 * that brute force RST attacks are possible. To combat this,
1400 * we use a much stricter check while in the ESTABLISHED state,
1401 * only accepting RSTs where the sequence number is equal to
1402 * last_ack_sent. In all other states (the states in which a
1403 * RST is more likely), the more permissive check is used.
1404 * If we have multiple segments in flight, the intial reset
1405 * segment sequence numbers will be to the left of last_ack_sent,
1406 * but they will eventually catch up.
1407 * In any case, it never made sense to trim reset segments to
1408 * fit the receive window since RFC 1122 says:
1409 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1411 * A TCP SHOULD allow a received RST segment to include data.
1414 * It has been suggested that a RST segment could contain
1415 * ASCII text that encoded and explained the cause of the
1416 * RST. No standard has yet been established for such
1419 * If the reset segment passes the sequence number test examine
1421 * SYN_RECEIVED STATE:
1422 * If passive open, return to LISTEN state.
1423 * If active open, inform user that connection was refused.
1424 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1425 * Inform user that connection was reset, and close tcb.
1426 * CLOSING, LAST_ACK STATES:
1429 * Drop the segment - see Stevens, vol. 2, p. 964 and
1432 if (thflags & TH_RST) {
1433 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1434 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1435 switch (tp->t_state) {
1437 case TCPS_SYN_RECEIVED:
1438 so->so_error = ECONNREFUSED;
1441 case TCPS_ESTABLISHED:
1442 if (tcp_insecure_rst == 0 &&
1443 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1444 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1445 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1446 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1447 tcpstat.tcps_badrst++;
1451 case TCPS_FIN_WAIT_1:
1452 case TCPS_FIN_WAIT_2:
1453 case TCPS_CLOSE_WAIT:
1454 so->so_error = ECONNRESET;
1456 tp->t_state = TCPS_CLOSED;
1457 tcpstat.tcps_drops++;
1458 KASSERT(headlocked, ("%s: trimthenstep6: "
1459 "tcp_close: head not locked", __func__));
1465 KASSERT(headlocked, ("%s: trimthenstep6: "
1466 "tcp_close.2: head not locked", __func__));
1475 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1476 * and it's less than ts_recent, drop it.
1478 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1479 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1481 /* Check to see if ts_recent is over 24 days old. */
1482 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1484 * Invalidate ts_recent. If this segment updates
1485 * ts_recent, the age will be reset later and ts_recent
1486 * will get a valid value. If it does not, setting
1487 * ts_recent to zero will at least satisfy the
1488 * requirement that zero be placed in the timestamp
1489 * echo reply when ts_recent isn't valid. The
1490 * age isn't reset until we get a valid ts_recent
1491 * because we don't want out-of-order segments to be
1492 * dropped when ts_recent is old.
1496 tcpstat.tcps_rcvduppack++;
1497 tcpstat.tcps_rcvdupbyte += tlen;
1498 tcpstat.tcps_pawsdrop++;
1506 * In the SYN-RECEIVED state, validate that the packet belongs to
1507 * this connection before trimming the data to fit the receive
1508 * window. Check the sequence number versus IRS since we know
1509 * the sequence numbers haven't wrapped. This is a partial fix
1510 * for the "LAND" DoS attack.
1512 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1513 rstreason = BANDLIM_RST_OPENPORT;
1517 todrop = tp->rcv_nxt - th->th_seq;
1519 if (thflags & TH_SYN) {
1529 * Following if statement from Stevens, vol. 2, p. 960.
1532 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1534 * Any valid FIN must be to the left of the window.
1535 * At this point the FIN must be a duplicate or out
1536 * of sequence; drop it.
1541 * Send an ACK to resynchronize and drop any data.
1542 * But keep on processing for RST or ACK.
1544 tp->t_flags |= TF_ACKNOW;
1546 tcpstat.tcps_rcvduppack++;
1547 tcpstat.tcps_rcvdupbyte += todrop;
1549 tcpstat.tcps_rcvpartduppack++;
1550 tcpstat.tcps_rcvpartdupbyte += todrop;
1552 drop_hdrlen += todrop; /* drop from the top afterwards */
1553 th->th_seq += todrop;
1555 if (th->th_urp > todrop)
1556 th->th_urp -= todrop;
1564 * If new data are received on a connection after the
1565 * user processes are gone, then RST the other end.
1567 if ((so->so_state & SS_NOFDREF) &&
1568 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1569 KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1570 "not locked", __func__));
1572 tcpstat.tcps_rcvafterclose++;
1573 rstreason = BANDLIM_UNLIMITED;
1578 * If segment ends after window, drop trailing data
1579 * (and PUSH and FIN); if nothing left, just ACK.
1581 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1583 tcpstat.tcps_rcvpackafterwin++;
1584 if (todrop >= tlen) {
1585 tcpstat.tcps_rcvbyteafterwin += tlen;
1587 * If window is closed can only take segments at
1588 * window edge, and have to drop data and PUSH from
1589 * incoming segments. Continue processing, but
1590 * remember to ack. Otherwise, drop segment
1593 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1594 tp->t_flags |= TF_ACKNOW;
1595 tcpstat.tcps_rcvwinprobe++;
1599 tcpstat.tcps_rcvbyteafterwin += todrop;
1602 thflags &= ~(TH_PUSH|TH_FIN);
1606 * If last ACK falls within this segment's sequence numbers,
1607 * record its timestamp.
1609 * 1) That the test incorporates suggestions from the latest
1610 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1611 * 2) That updating only on newer timestamps interferes with
1612 * our earlier PAWS tests, so this check should be solely
1613 * predicated on the sequence space of this segment.
1614 * 3) That we modify the segment boundary check to be
1615 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1616 * instead of RFC1323's
1617 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1618 * This modified check allows us to overcome RFC1323's
1619 * limitations as described in Stevens TCP/IP Illustrated
1620 * Vol. 2 p.869. In such cases, we can still calculate the
1621 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1623 if ((to.to_flags & TOF_TS) != 0 &&
1624 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1625 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1626 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1627 tp->ts_recent_age = ticks;
1628 tp->ts_recent = to.to_tsval;
1632 * If a SYN is in the window, then this is an
1633 * error and we send an RST and drop the connection.
1635 if (thflags & TH_SYN) {
1636 KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1637 "head not locked", __func__));
1638 tp = tcp_drop(tp, ECONNRESET);
1639 rstreason = BANDLIM_UNLIMITED;
1644 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1645 * flag is on (half-synchronized state), then queue data for
1646 * later processing; else drop segment and return.
1648 if ((thflags & TH_ACK) == 0) {
1649 if (tp->t_state == TCPS_SYN_RECEIVED ||
1650 (tp->t_flags & TF_NEEDSYN))
1652 else if (tp->t_flags & TF_ACKNOW)
1661 switch (tp->t_state) {
1664 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1665 * ESTABLISHED state and continue processing.
1666 * The ACK was checked above.
1668 case TCPS_SYN_RECEIVED:
1670 tcpstat.tcps_connects++;
1672 /* Do window scaling? */
1673 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1674 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1675 tp->rcv_scale = tp->request_r_scale;
1676 tp->snd_wnd = tiwin;
1680 * SYN-RECEIVED -> ESTABLISHED
1681 * SYN-RECEIVED* -> FIN-WAIT-1
1683 tp->t_starttime = ticks;
1684 if (tp->t_flags & TF_NEEDFIN) {
1685 tp->t_state = TCPS_FIN_WAIT_1;
1686 tp->t_flags &= ~TF_NEEDFIN;
1688 tp->t_state = TCPS_ESTABLISHED;
1689 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1692 * If segment contains data or ACK, will call tcp_reass()
1693 * later; if not, do so now to pass queued data to user.
1695 if (tlen == 0 && (thflags & TH_FIN) == 0)
1696 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1698 tp->snd_wl1 = th->th_seq - 1;
1702 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1703 * ACKs. If the ack is in the range
1704 * tp->snd_una < th->th_ack <= tp->snd_max
1705 * then advance tp->snd_una to th->th_ack and drop
1706 * data from the retransmission queue. If this ACK reflects
1707 * more up to date window information we update our window information.
1709 case TCPS_ESTABLISHED:
1710 case TCPS_FIN_WAIT_1:
1711 case TCPS_FIN_WAIT_2:
1712 case TCPS_CLOSE_WAIT:
1715 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1716 tcpstat.tcps_rcvacktoomuch++;
1719 if ((tp->t_flags & TF_SACK_PERMIT) &&
1720 ((to.to_flags & TOF_SACK) ||
1721 !TAILQ_EMPTY(&tp->snd_holes)))
1722 tcp_sack_doack(tp, &to, th->th_ack);
1723 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1724 if (tlen == 0 && tiwin == tp->snd_wnd) {
1725 tcpstat.tcps_rcvdupack++;
1727 * If we have outstanding data (other than
1728 * a window probe), this is a completely
1729 * duplicate ack (ie, window info didn't
1730 * change), the ack is the biggest we've
1731 * seen and we've seen exactly our rexmt
1732 * threshhold of them, assume a packet
1733 * has been dropped and retransmit it.
1734 * Kludge snd_nxt & the congestion
1735 * window so we send only this one
1738 * We know we're losing at the current
1739 * window size so do congestion avoidance
1740 * (set ssthresh to half the current window
1741 * and pull our congestion window back to
1742 * the new ssthresh).
1744 * Dup acks mean that packets have left the
1745 * network (they're now cached at the receiver)
1746 * so bump cwnd by the amount in the receiver
1747 * to keep a constant cwnd packets in the
1750 if (!tcp_timer_active(tp, TT_REXMT) ||
1751 th->th_ack != tp->snd_una)
1753 else if (++tp->t_dupacks > tcprexmtthresh ||
1755 (tp->t_flags & TF_SACK_PERMIT)) &&
1756 IN_FASTRECOVERY(tp))) {
1757 if ((tp->t_flags & TF_SACK_PERMIT) &&
1758 IN_FASTRECOVERY(tp)) {
1762 * Compute the amount of data in flight first.
1763 * We can inject new data into the pipe iff
1764 * we have less than 1/2 the original window's
1765 * worth of data in flight.
1767 awnd = (tp->snd_nxt - tp->snd_fack) +
1768 tp->sackhint.sack_bytes_rexmit;
1769 if (awnd < tp->snd_ssthresh) {
1770 tp->snd_cwnd += tp->t_maxseg;
1771 if (tp->snd_cwnd > tp->snd_ssthresh)
1772 tp->snd_cwnd = tp->snd_ssthresh;
1775 tp->snd_cwnd += tp->t_maxseg;
1776 (void) tcp_output(tp);
1778 } else if (tp->t_dupacks == tcprexmtthresh) {
1779 tcp_seq onxt = tp->snd_nxt;
1783 * If we're doing sack, check to
1784 * see if we're already in sack
1785 * recovery. If we're not doing sack,
1786 * check to see if we're in newreno
1789 if (tp->t_flags & TF_SACK_PERMIT) {
1790 if (IN_FASTRECOVERY(tp)) {
1794 } else if (tcp_do_newreno) {
1795 if (SEQ_LEQ(th->th_ack,
1801 win = min(tp->snd_wnd, tp->snd_cwnd) /
1805 tp->snd_ssthresh = win * tp->t_maxseg;
1806 ENTER_FASTRECOVERY(tp);
1807 tp->snd_recover = tp->snd_max;
1808 tcp_timer_activate(tp, TT_REXMT, 0);
1810 if (tp->t_flags & TF_SACK_PERMIT) {
1811 tcpstat.tcps_sack_recovery_episode++;
1812 tp->sack_newdata = tp->snd_nxt;
1813 tp->snd_cwnd = tp->t_maxseg;
1814 (void) tcp_output(tp);
1817 tp->snd_nxt = th->th_ack;
1818 tp->snd_cwnd = tp->t_maxseg;
1819 (void) tcp_output(tp);
1820 KASSERT(tp->snd_limited <= 2,
1821 ("%s: tp->snd_limited too big",
1823 tp->snd_cwnd = tp->snd_ssthresh +
1825 (tp->t_dupacks - tp->snd_limited);
1826 if (SEQ_GT(onxt, tp->snd_nxt))
1829 } else if (tcp_do_rfc3042) {
1830 u_long oldcwnd = tp->snd_cwnd;
1831 tcp_seq oldsndmax = tp->snd_max;
1834 KASSERT(tp->t_dupacks == 1 ||
1836 ("%s: dupacks not 1 or 2",
1838 if (tp->t_dupacks == 1)
1839 tp->snd_limited = 0;
1841 (tp->snd_nxt - tp->snd_una) +
1842 (tp->t_dupacks - tp->snd_limited) *
1844 (void) tcp_output(tp);
1845 sent = tp->snd_max - oldsndmax;
1846 if (sent > tp->t_maxseg) {
1847 KASSERT((tp->t_dupacks == 2 &&
1848 tp->snd_limited == 0) ||
1849 (sent == tp->t_maxseg + 1 &&
1850 tp->t_flags & TF_SENTFIN),
1851 ("%s: sent too much",
1853 tp->snd_limited = 2;
1854 } else if (sent > 0)
1856 tp->snd_cwnd = oldcwnd;
1864 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
1865 ("%s: th_ack <= snd_una", __func__));
1868 * If the congestion window was inflated to account
1869 * for the other side's cached packets, retract it.
1871 if (tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
1872 if (IN_FASTRECOVERY(tp)) {
1873 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1874 if (tp->t_flags & TF_SACK_PERMIT)
1875 tcp_sack_partialack(tp, th);
1877 tcp_newreno_partial_ack(tp, th);
1880 * Out of fast recovery.
1881 * Window inflation should have left us
1882 * with approximately snd_ssthresh
1884 * But in case we would be inclined to
1885 * send a burst, better to do it via
1886 * the slow start mechanism.
1888 if (SEQ_GT(th->th_ack +
1891 tp->snd_cwnd = tp->snd_max -
1895 tp->snd_cwnd = tp->snd_ssthresh;
1899 if (tp->t_dupacks >= tcprexmtthresh &&
1900 tp->snd_cwnd > tp->snd_ssthresh)
1901 tp->snd_cwnd = tp->snd_ssthresh;
1905 * If we reach this point, ACK is not a duplicate,
1906 * i.e., it ACKs something we sent.
1908 if (tp->t_flags & TF_NEEDSYN) {
1910 * T/TCP: Connection was half-synchronized, and our
1911 * SYN has been ACK'd (so connection is now fully
1912 * synchronized). Go to non-starred state,
1913 * increment snd_una for ACK of SYN, and check if
1914 * we can do window scaling.
1916 tp->t_flags &= ~TF_NEEDSYN;
1918 /* Do window scaling? */
1919 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1920 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1921 tp->rcv_scale = tp->request_r_scale;
1922 /* Send window already scaled. */
1927 KASSERT(headlocked, ("%s: process_ACK: head not locked",
1929 INP_LOCK_ASSERT(tp->t_inpcb);
1931 acked = th->th_ack - tp->snd_una;
1932 tcpstat.tcps_rcvackpack++;
1933 tcpstat.tcps_rcvackbyte += acked;
1936 * If we just performed our first retransmit, and the ACK
1937 * arrives within our recovery window, then it was a mistake
1938 * to do the retransmit in the first place. Recover our
1939 * original cwnd and ssthresh, and proceed to transmit where
1942 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1943 ++tcpstat.tcps_sndrexmitbad;
1944 tp->snd_cwnd = tp->snd_cwnd_prev;
1945 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1946 tp->snd_recover = tp->snd_recover_prev;
1947 if (tp->t_flags & TF_WASFRECOVERY)
1948 ENTER_FASTRECOVERY(tp);
1949 tp->snd_nxt = tp->snd_max;
1950 tp->t_badrxtwin = 0; /* XXX probably not required */
1954 * If we have a timestamp reply, update smoothed
1955 * round trip time. If no timestamp is present but
1956 * transmit timer is running and timed sequence
1957 * number was acked, update smoothed round trip time.
1958 * Since we now have an rtt measurement, cancel the
1959 * timer backoff (cf., Phil Karn's retransmit alg.).
1960 * Recompute the initial retransmit timer.
1962 * Some boxes send broken timestamp replies
1963 * during the SYN+ACK phase, ignore
1964 * timestamps of 0 or we could calculate a
1965 * huge RTT and blow up the retransmit timer.
1967 if ((to.to_flags & TOF_TS) != 0 &&
1969 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
1970 tp->t_rttlow = ticks - to.to_tsecr;
1971 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1972 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1973 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
1974 tp->t_rttlow = ticks - tp->t_rtttime;
1975 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1977 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1980 * If all outstanding data is acked, stop retransmit
1981 * timer and remember to restart (more output or persist).
1982 * If there is more data to be acked, restart retransmit
1983 * timer, using current (possibly backed-off) value.
1985 if (th->th_ack == tp->snd_max) {
1986 tcp_timer_activate(tp, TT_REXMT, 0);
1988 } else if (!tcp_timer_active(tp, TT_PERSIST))
1989 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1992 * If no data (only SYN) was ACK'd,
1993 * skip rest of ACK processing.
1999 * When new data is acked, open the congestion window.
2000 * If the window gives us less than ssthresh packets
2001 * in flight, open exponentially (maxseg per packet).
2002 * Otherwise open linearly: maxseg per window
2003 * (maxseg^2 / cwnd per packet).
2005 if ((!tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2006 !IN_FASTRECOVERY(tp)) {
2007 u_int cw = tp->snd_cwnd;
2008 u_int incr = tp->t_maxseg;
2009 if (cw > tp->snd_ssthresh)
2010 incr = incr * incr / cw;
2011 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2013 SOCKBUF_LOCK(&so->so_snd);
2014 if (acked > so->so_snd.sb_cc) {
2015 tp->snd_wnd -= so->so_snd.sb_cc;
2016 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2019 sbdrop_locked(&so->so_snd, acked);
2020 tp->snd_wnd -= acked;
2023 /* NB: sowwakeup_locked() does an implicit unlock. */
2024 sowwakeup_locked(so);
2025 /* Detect una wraparound. */
2026 if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2027 !IN_FASTRECOVERY(tp) &&
2028 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2029 SEQ_LEQ(th->th_ack, tp->snd_recover))
2030 tp->snd_recover = th->th_ack - 1;
2031 if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2032 IN_FASTRECOVERY(tp) &&
2033 SEQ_GEQ(th->th_ack, tp->snd_recover))
2034 EXIT_FASTRECOVERY(tp);
2035 tp->snd_una = th->th_ack;
2036 if (tp->t_flags & TF_SACK_PERMIT) {
2037 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2038 tp->snd_recover = tp->snd_una;
2040 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2041 tp->snd_nxt = tp->snd_una;
2043 switch (tp->t_state) {
2046 * In FIN_WAIT_1 STATE in addition to the processing
2047 * for the ESTABLISHED state if our FIN is now acknowledged
2048 * then enter FIN_WAIT_2.
2050 case TCPS_FIN_WAIT_1:
2051 if (ourfinisacked) {
2053 * If we can't receive any more
2054 * data, then closing user can proceed.
2055 * Starting the timer is contrary to the
2056 * specification, but if we don't get a FIN
2057 * we'll hang forever.
2060 * we should release the tp also, and use a
2063 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2066 soisdisconnected(so);
2067 timeout = (tcp_fast_finwait2_recycle) ?
2068 tcp_finwait2_timeout : tcp_maxidle;
2069 tcp_timer_activate(tp, TT_2MSL, timeout);
2071 tp->t_state = TCPS_FIN_WAIT_2;
2076 * In CLOSING STATE in addition to the processing for
2077 * the ESTABLISHED state if the ACK acknowledges our FIN
2078 * then enter the TIME-WAIT state, otherwise ignore
2082 if (ourfinisacked) {
2083 KASSERT(headlocked, ("%s: process_ACK: "
2084 "head not locked", __func__));
2086 INP_INFO_WUNLOCK(&tcbinfo);
2094 * In LAST_ACK, we may still be waiting for data to drain
2095 * and/or to be acked, as well as for the ack of our FIN.
2096 * If our FIN is now acknowledged, delete the TCB,
2097 * enter the closed state and return.
2100 if (ourfinisacked) {
2101 KASSERT(headlocked, ("%s: process_ACK: "
2102 "tcp_close: head not locked", __func__));
2111 KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2112 INP_LOCK_ASSERT(tp->t_inpcb);
2115 * Update window information.
2116 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2118 if ((thflags & TH_ACK) &&
2119 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2120 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2121 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2122 /* keep track of pure window updates */
2124 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2125 tcpstat.tcps_rcvwinupd++;
2126 tp->snd_wnd = tiwin;
2127 tp->snd_wl1 = th->th_seq;
2128 tp->snd_wl2 = th->th_ack;
2129 if (tp->snd_wnd > tp->max_sndwnd)
2130 tp->max_sndwnd = tp->snd_wnd;
2135 * Process segments with URG.
2137 if ((thflags & TH_URG) && th->th_urp &&
2138 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2140 * This is a kludge, but if we receive and accept
2141 * random urgent pointers, we'll crash in
2142 * soreceive. It's hard to imagine someone
2143 * actually wanting to send this much urgent data.
2145 SOCKBUF_LOCK(&so->so_rcv);
2146 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2147 th->th_urp = 0; /* XXX */
2148 thflags &= ~TH_URG; /* XXX */
2149 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2150 goto dodata; /* XXX */
2153 * If this segment advances the known urgent pointer,
2154 * then mark the data stream. This should not happen
2155 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2156 * a FIN has been received from the remote side.
2157 * In these states we ignore the URG.
2159 * According to RFC961 (Assigned Protocols),
2160 * the urgent pointer points to the last octet
2161 * of urgent data. We continue, however,
2162 * to consider it to indicate the first octet
2163 * of data past the urgent section as the original
2164 * spec states (in one of two places).
2166 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2167 tp->rcv_up = th->th_seq + th->th_urp;
2168 so->so_oobmark = so->so_rcv.sb_cc +
2169 (tp->rcv_up - tp->rcv_nxt) - 1;
2170 if (so->so_oobmark == 0)
2171 so->so_rcv.sb_state |= SBS_RCVATMARK;
2173 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2175 SOCKBUF_UNLOCK(&so->so_rcv);
2177 * Remove out of band data so doesn't get presented to user.
2178 * This can happen independent of advancing the URG pointer,
2179 * but if two URG's are pending at once, some out-of-band
2180 * data may creep in... ick.
2182 if (th->th_urp <= (u_long)tlen &&
2183 !(so->so_options & SO_OOBINLINE)) {
2184 /* hdr drop is delayed */
2185 tcp_pulloutofband(so, th, m, drop_hdrlen);
2189 * If no out of band data is expected,
2190 * pull receive urgent pointer along
2191 * with the receive window.
2193 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2194 tp->rcv_up = tp->rcv_nxt;
2197 KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2198 INP_LOCK_ASSERT(tp->t_inpcb);
2201 * Process the segment text, merging it into the TCP sequencing queue,
2202 * and arranging for acknowledgment of receipt if necessary.
2203 * This process logically involves adjusting tp->rcv_wnd as data
2204 * is presented to the user (this happens in tcp_usrreq.c,
2205 * case PRU_RCVD). If a FIN has already been received on this
2206 * connection then we just ignore the text.
2208 if ((tlen || (thflags & TH_FIN)) &&
2209 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2210 tcp_seq save_start = th->th_seq;
2211 m_adj(m, drop_hdrlen); /* delayed header drop */
2213 * Insert segment which includes th into TCP reassembly queue
2214 * with control block tp. Set thflags to whether reassembly now
2215 * includes a segment with FIN. This handles the common case
2216 * inline (segment is the next to be received on an established
2217 * connection, and the queue is empty), avoiding linkage into
2218 * and removal from the queue and repetition of various
2220 * Set DELACK for segments received in order, but ack
2221 * immediately when segments are out of order (so
2222 * fast retransmit can work).
2224 if (th->th_seq == tp->rcv_nxt &&
2225 LIST_EMPTY(&tp->t_segq) &&
2226 TCPS_HAVEESTABLISHED(tp->t_state)) {
2228 tp->t_flags |= TF_DELACK;
2230 tp->t_flags |= TF_ACKNOW;
2231 tp->rcv_nxt += tlen;
2232 thflags = th->th_flags & TH_FIN;
2233 tcpstat.tcps_rcvpack++;
2234 tcpstat.tcps_rcvbyte += tlen;
2236 SOCKBUF_LOCK(&so->so_rcv);
2237 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2240 sbappendstream_locked(&so->so_rcv, m);
2241 /* NB: sorwakeup_locked() does an implicit unlock. */
2242 sorwakeup_locked(so);
2245 * XXX: Due to the header drop above "th" is
2246 * theoretically invalid by now. Fortunately
2247 * m_adj() doesn't actually frees any mbufs
2248 * when trimming from the head.
2250 thflags = tcp_reass(tp, th, &tlen, m);
2251 tp->t_flags |= TF_ACKNOW;
2253 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2254 tcp_update_sack_list(tp, save_start, save_start + tlen);
2257 * Note the amount of data that peer has sent into
2258 * our window, in order to estimate the sender's
2262 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2270 * If FIN is received ACK the FIN and let the user know
2271 * that the connection is closing.
2273 if (thflags & TH_FIN) {
2274 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2277 * If connection is half-synchronized
2278 * (ie NEEDSYN flag on) then delay ACK,
2279 * so it may be piggybacked when SYN is sent.
2280 * Otherwise, since we received a FIN then no
2281 * more input can be expected, send ACK now.
2283 if (tp->t_flags & TF_NEEDSYN)
2284 tp->t_flags |= TF_DELACK;
2286 tp->t_flags |= TF_ACKNOW;
2289 switch (tp->t_state) {
2292 * In SYN_RECEIVED and ESTABLISHED STATES
2293 * enter the CLOSE_WAIT state.
2295 case TCPS_SYN_RECEIVED:
2296 tp->t_starttime = ticks;
2298 case TCPS_ESTABLISHED:
2299 tp->t_state = TCPS_CLOSE_WAIT;
2303 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2304 * enter the CLOSING state.
2306 case TCPS_FIN_WAIT_1:
2307 tp->t_state = TCPS_CLOSING;
2311 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2312 * starting the time-wait timer, turning off the other
2315 case TCPS_FIN_WAIT_2:
2316 KASSERT(headlocked == 1, ("%s: dodata: "
2317 "TCP_FIN_WAIT_2: head not locked", __func__));
2319 INP_INFO_WUNLOCK(&tcbinfo);
2323 INP_INFO_WUNLOCK(&tcbinfo);
2326 if (so->so_options & SO_DEBUG)
2327 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2332 * Return any desired output.
2334 if (needoutput || (tp->t_flags & TF_ACKNOW))
2335 (void) tcp_output(tp);
2338 KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2340 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
2341 INP_LOCK_ASSERT(tp->t_inpcb);
2342 if (tp->t_flags & TF_DELACK) {
2343 tp->t_flags &= ~TF_DELACK;
2344 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2346 INP_UNLOCK(tp->t_inpcb);
2350 KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2352 * Generate an ACK dropping incoming segment if it occupies
2353 * sequence space, where the ACK reflects our state.
2355 * We can now skip the test for the RST flag since all
2356 * paths to this code happen after packets containing
2357 * RST have been dropped.
2359 * In the SYN-RECEIVED state, don't send an ACK unless the
2360 * segment we received passes the SYN-RECEIVED ACK test.
2361 * If it fails send a RST. This breaks the loop in the
2362 * "LAND" DoS attack, and also prevents an ACK storm
2363 * between two listening ports that have been sent forged
2364 * SYN segments, each with the source address of the other.
2366 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2367 (SEQ_GT(tp->snd_una, th->th_ack) ||
2368 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2369 rstreason = BANDLIM_RST_OPENPORT;
2373 if (so->so_options & SO_DEBUG)
2374 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2377 KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2378 INP_INFO_WUNLOCK(&tcbinfo);
2379 tp->t_flags |= TF_ACKNOW;
2380 (void) tcp_output(tp);
2381 INP_UNLOCK(tp->t_inpcb);
2386 KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2388 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2391 INP_UNLOCK(tp->t_inpcb);
2393 INP_INFO_WUNLOCK(&tcbinfo);
2398 * Drop space held by incoming segment and return.
2401 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2402 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2406 INP_UNLOCK(tp->t_inpcb);
2408 INP_INFO_WUNLOCK(&tcbinfo);
2414 * Issue RST and make ACK acceptable to originator of segment.
2415 * The mbuf must still include the original packet header.
2419 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2420 int tlen, int rstreason)
2424 struct ip6_hdr *ip6;
2426 /* Don't bother if destination was broadcast/multicast. */
2427 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2430 if (mtod(m, struct ip *)->ip_v == 6) {
2431 ip6 = mtod(m, struct ip6_hdr *);
2432 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2433 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2435 /* IPv6 anycast check is done at tcp6_input() */
2439 ip = mtod(m, struct ip *);
2440 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2441 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2442 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2443 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2447 /* Perform bandwidth limiting. */
2448 if (badport_bandlim(rstreason) < 0)
2451 /* tcp_respond consumes the mbuf chain. */
2452 if (th->th_flags & TH_ACK) {
2453 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2454 th->th_ack, TH_RST);
2456 if (th->th_flags & TH_SYN)
2458 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2459 (tcp_seq)0, TH_RST|TH_ACK);
2468 * Parse TCP options and place in tcpopt.
2471 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2476 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2478 if (opt == TCPOPT_EOL)
2480 if (opt == TCPOPT_NOP)
2486 if (optlen < 2 || optlen > cnt)
2491 if (optlen != TCPOLEN_MAXSEG)
2493 if (!(flags & TO_SYN))
2495 to->to_flags |= TOF_MSS;
2496 bcopy((char *)cp + 2,
2497 (char *)&to->to_mss, sizeof(to->to_mss));
2498 to->to_mss = ntohs(to->to_mss);
2501 if (optlen != TCPOLEN_WINDOW)
2503 if (!(flags & TO_SYN))
2505 to->to_flags |= TOF_SCALE;
2506 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2508 case TCPOPT_TIMESTAMP:
2509 if (optlen != TCPOLEN_TIMESTAMP)
2511 to->to_flags |= TOF_TS;
2512 bcopy((char *)cp + 2,
2513 (char *)&to->to_tsval, sizeof(to->to_tsval));
2514 to->to_tsval = ntohl(to->to_tsval);
2515 bcopy((char *)cp + 6,
2516 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2517 to->to_tsecr = ntohl(to->to_tsecr);
2519 #ifdef TCP_SIGNATURE
2521 * XXX In order to reply to a host which has set the
2522 * TCP_SIGNATURE option in its initial SYN, we have to
2523 * record the fact that the option was observed here
2524 * for the syncache code to perform the correct response.
2526 case TCPOPT_SIGNATURE:
2527 if (optlen != TCPOLEN_SIGNATURE)
2529 to->to_flags |= TOF_SIGNATURE;
2530 to->to_signature = cp + 2;
2533 case TCPOPT_SACK_PERMITTED:
2534 if (optlen != TCPOLEN_SACK_PERMITTED)
2536 if (!(flags & TO_SYN))
2540 to->to_flags |= TOF_SACKPERM;
2543 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2547 to->to_flags |= TOF_SACK;
2548 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2549 to->to_sacks = cp + 2;
2550 tcpstat.tcps_sack_rcv_blocks++;
2559 * Pull out of band byte out of a segment so
2560 * it doesn't appear in the user's data queue.
2561 * It is still reflected in the segment length for
2562 * sequencing purposes.
2565 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2568 int cnt = off + th->th_urp - 1;
2571 if (m->m_len > cnt) {
2572 char *cp = mtod(m, caddr_t) + cnt;
2573 struct tcpcb *tp = sototcpcb(so);
2576 tp->t_oobflags |= TCPOOB_HAVEDATA;
2577 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2579 if (m->m_flags & M_PKTHDR)
2588 panic("tcp_pulloutofband");
2592 * Collect new round-trip time estimate
2593 * and update averages and current timeout.
2596 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2600 INP_LOCK_ASSERT(tp->t_inpcb);
2602 tcpstat.tcps_rttupdated++;
2604 if (tp->t_srtt != 0) {
2606 * srtt is stored as fixed point with 5 bits after the
2607 * binary point (i.e., scaled by 8). The following magic
2608 * is equivalent to the smoothing algorithm in rfc793 with
2609 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2610 * point). Adjust rtt to origin 0.
2612 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2613 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2615 if ((tp->t_srtt += delta) <= 0)
2619 * We accumulate a smoothed rtt variance (actually, a
2620 * smoothed mean difference), then set the retransmit
2621 * timer to smoothed rtt + 4 times the smoothed variance.
2622 * rttvar is stored as fixed point with 4 bits after the
2623 * binary point (scaled by 16). The following is
2624 * equivalent to rfc793 smoothing with an alpha of .75
2625 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2626 * rfc793's wired-in beta.
2630 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2631 if ((tp->t_rttvar += delta) <= 0)
2633 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2634 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2637 * No rtt measurement yet - use the unsmoothed rtt.
2638 * Set the variance to half the rtt (so our first
2639 * retransmit happens at 3*rtt).
2641 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2642 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2643 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2649 * the retransmit should happen at rtt + 4 * rttvar.
2650 * Because of the way we do the smoothing, srtt and rttvar
2651 * will each average +1/2 tick of bias. When we compute
2652 * the retransmit timer, we want 1/2 tick of rounding and
2653 * 1 extra tick because of +-1/2 tick uncertainty in the
2654 * firing of the timer. The bias will give us exactly the
2655 * 1.5 tick we need. But, because the bias is
2656 * statistical, we have to test that we don't drop below
2657 * the minimum feasible timer (which is 2 ticks).
2659 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2660 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2663 * We received an ack for a packet that wasn't retransmitted;
2664 * it is probably safe to discard any error indications we've
2665 * received recently. This isn't quite right, but close enough
2666 * for now (a route might have failed after we sent a segment,
2667 * and the return path might not be symmetrical).
2669 tp->t_softerror = 0;
2673 * Determine a reasonable value for maxseg size.
2674 * If the route is known, check route for mtu.
2675 * If none, use an mss that can be handled on the outgoing
2676 * interface without forcing IP to fragment; if bigger than
2677 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2678 * to utilize large mbufs. If no route is found, route has no mtu,
2679 * or the destination isn't local, use a default, hopefully conservative
2680 * size (usually 512 or the default IP max size, but no more than the mtu
2681 * of the interface), as we can't discover anything about intervening
2682 * gateways or networks. We also initialize the congestion/slow start
2683 * window to be a single segment if the destination isn't local.
2684 * While looking at the routing entry, we also initialize other path-dependent
2685 * parameters from pre-set or cached values in the routing entry.
2687 * Also take into account the space needed for options that we
2688 * send regularly. Make maxseg shorter by that amount to assure
2689 * that we can send maxseg amount of data even when the options
2690 * are present. Store the upper limit of the length of options plus
2693 * In case of T/TCP, we call this routine during implicit connection
2694 * setup as well (offer = -1), to initialize maxseg from the cached
2697 * NOTE that this routine is only called when we process an incoming
2698 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2701 tcp_mss(struct tcpcb *tp, int offer)
2706 struct inpcb *inp = tp->t_inpcb;
2708 struct hc_metrics_lite metrics;
2709 int origoffer = offer;
2712 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2713 size_t min_protoh = isipv6 ?
2714 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2715 sizeof (struct tcpiphdr);
2717 const size_t min_protoh = sizeof(struct tcpiphdr);
2723 maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2724 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2728 maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2729 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2731 so = inp->inp_socket;
2734 * No route to sender, stay with default mss and return.
2739 /* What have we got? */
2743 * Offer == 0 means that there was no MSS on the SYN
2744 * segment, in this case we use tcp_mssdflt.
2748 isipv6 ? tcp_v6mssdflt :
2755 * Offer == -1 means that we didn't receive SYN yet.
2761 * Prevent DoS attack with too small MSS. Round up
2762 * to at least minmss.
2764 offer = max(offer, tcp_minmss);
2766 * Sanity check: make sure that maxopd will be large
2767 * enough to allow some data on segments even if the
2768 * all the option space is used (40bytes). Otherwise
2769 * funny things may happen in tcp_output.
2771 offer = max(offer, 64);
2775 * rmx information is now retrieved from tcp_hostcache.
2777 tcp_hc_get(&inp->inp_inc, &metrics);
2780 * If there's a discovered mtu int tcp hostcache, use it
2781 * else, use the link mtu.
2783 if (metrics.rmx_mtu)
2784 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2788 mss = maxmtu - min_protoh;
2789 if (!path_mtu_discovery &&
2790 !in6_localaddr(&inp->in6p_faddr))
2791 mss = min(mss, tcp_v6mssdflt);
2795 mss = maxmtu - min_protoh;
2796 if (!path_mtu_discovery &&
2797 !in_localaddr(inp->inp_faddr))
2798 mss = min(mss, tcp_mssdflt);
2801 mss = min(mss, offer);
2804 * maxopd stores the maximum length of data AND options
2805 * in a segment; maxseg is the amount of data in a normal
2806 * segment. We need to store this value (maxopd) apart
2807 * from maxseg, because now every segment carries options
2808 * and thus we normally have somewhat less data in segments.
2813 * origoffer==-1 indicates that no segments were received yet.
2814 * In this case we just guess.
2816 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2818 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2819 mss -= TCPOLEN_TSTAMP_APPA;
2822 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2824 mss &= ~(MCLBYTES-1);
2827 mss = mss / MCLBYTES * MCLBYTES;
2832 * If there's a pipesize, change the socket buffer to that size,
2833 * don't change if sb_hiwat is different than default (then it
2834 * has been changed on purpose with setsockopt).
2835 * Make the socket buffers an integral number of mss units;
2836 * if the mss is larger than the socket buffer, decrease the mss.
2838 SOCKBUF_LOCK(&so->so_snd);
2839 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2840 bufsize = metrics.rmx_sendpipe;
2842 bufsize = so->so_snd.sb_hiwat;
2846 bufsize = roundup(bufsize, mss);
2847 if (bufsize > sb_max)
2849 if (bufsize > so->so_snd.sb_hiwat)
2850 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2852 SOCKBUF_UNLOCK(&so->so_snd);
2855 SOCKBUF_LOCK(&so->so_rcv);
2856 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2857 bufsize = metrics.rmx_recvpipe;
2859 bufsize = so->so_rcv.sb_hiwat;
2860 if (bufsize > mss) {
2861 bufsize = roundup(bufsize, mss);
2862 if (bufsize > sb_max)
2864 if (bufsize > so->so_rcv.sb_hiwat)
2865 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
2867 SOCKBUF_UNLOCK(&so->so_rcv);
2869 * While we're here, check the others too.
2871 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
2873 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2874 tcpstat.tcps_usedrtt++;
2875 if (metrics.rmx_rttvar) {
2876 tp->t_rttvar = metrics.rmx_rttvar;
2877 tcpstat.tcps_usedrttvar++;
2879 /* default variation is +- 1 rtt */
2881 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2883 TCPT_RANGESET(tp->t_rxtcur,
2884 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2885 tp->t_rttmin, TCPTV_REXMTMAX);
2887 if (metrics.rmx_ssthresh) {
2889 * There's some sort of gateway or interface
2890 * buffer limit on the path. Use this to set
2891 * the slow start threshhold, but set the
2892 * threshold to no less than 2*mss.
2894 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
2895 tcpstat.tcps_usedssthresh++;
2897 if (metrics.rmx_bandwidth)
2898 tp->snd_bandwidth = metrics.rmx_bandwidth;
2901 * Set the slow-start flight size depending on whether this
2902 * is a local network or not.
2904 * Extend this so we cache the cwnd too and retrieve it here.
2905 * Make cwnd even bigger than RFC3390 suggests but only if we
2906 * have previous experience with the remote host. Be careful
2907 * not make cwnd bigger than remote receive window or our own
2908 * send socket buffer. Maybe put some additional upper bound
2909 * on the retrieved cwnd. Should do incremental updates to
2910 * hostcache when cwnd collapses so next connection doesn't
2911 * overloads the path again.
2913 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
2914 * We currently check only in syncache_socket for that.
2916 #define TCP_METRICS_CWND
2917 #ifdef TCP_METRICS_CWND
2918 if (metrics.rmx_cwnd)
2919 tp->snd_cwnd = max(mss,
2920 min(metrics.rmx_cwnd / 2,
2921 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
2925 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2927 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2928 (!isipv6 && in_localaddr(inp->inp_faddr)))
2930 else if (in_localaddr(inp->inp_faddr))
2932 tp->snd_cwnd = mss * ss_fltsz_local;
2934 tp->snd_cwnd = mss * ss_fltsz;
2936 /* Check the interface for TSO capabilities. */
2937 if (mtuflags & CSUM_TSO)
2938 tp->t_flags |= TF_TSO;
2942 * Determine the MSS option to send on an outgoing SYN.
2945 tcp_mssopt(struct in_conninfo *inc)
2952 int isipv6 = inc->inc_isipv6 ? 1 : 0;
2955 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
2959 mss = tcp_v6mssdflt;
2960 maxmtu = tcp_maxmtu6(inc, NULL);
2961 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
2962 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
2967 maxmtu = tcp_maxmtu(inc, NULL);
2968 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
2969 min_protoh = sizeof(struct tcpiphdr);
2971 if (maxmtu && thcmtu)
2972 mss = min(maxmtu, thcmtu) - min_protoh;
2973 else if (maxmtu || thcmtu)
2974 mss = max(maxmtu, thcmtu) - min_protoh;
2981 * On a partial ack arrives, force the retransmission of the
2982 * next unacknowledged segment. Do not clear tp->t_dupacks.
2983 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2987 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
2989 tcp_seq onxt = tp->snd_nxt;
2990 u_long ocwnd = tp->snd_cwnd;
2992 tcp_timer_activate(tp, TT_REXMT, 0);
2994 tp->snd_nxt = th->th_ack;
2996 * Set snd_cwnd to one segment beyond acknowledged offset.
2997 * (tp->snd_una has not yet been updated when this function is called.)
2999 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3000 tp->t_flags |= TF_ACKNOW;
3001 (void) tcp_output(tp);
3002 tp->snd_cwnd = ocwnd;
3003 if (SEQ_GT(onxt, tp->snd_nxt))
3006 * Partial window deflation. Relies on fact that tp->snd_una
3009 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3010 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3013 tp->snd_cwnd += tp->t_maxseg;