2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include "opt_ipfw.h" /* for ipfw_fwd */
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
40 #include "opt_tcpdebug.h"
42 #include <sys/param.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
46 #include <sys/proc.h> /* for proc0 declaration */
47 #include <sys/protosw.h>
48 #include <sys/signalvar.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/systm.h>
54 #include <sys/vimage.h>
56 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
61 #include <net/route.h>
63 #define TCPSTATES /* for logging */
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/in_var.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
71 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
72 #include <netinet/ip_var.h>
73 #include <netinet/ip_options.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet6/in6_pcb.h>
77 #include <netinet6/ip6_var.h>
78 #include <netinet6/nd6.h>
79 #include <netinet/tcp.h>
80 #include <netinet/tcp_fsm.h>
81 #include <netinet/tcp_seq.h>
82 #include <netinet/tcp_timer.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet6/tcp6_var.h>
85 #include <netinet/tcpip.h>
86 #include <netinet/tcp_syncache.h>
88 #include <netinet/tcp_debug.h>
92 #include <netipsec/ipsec.h>
93 #include <netipsec/ipsec6.h>
96 #include <machine/in_cksum.h>
98 #include <security/mac/mac_framework.h>
100 static const int tcprexmtthresh = 3;
102 struct tcpstat tcpstat;
103 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
104 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
106 int tcp_log_in_vain = 0;
107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
108 &tcp_log_in_vain, 0, "Log all incoming TCP segments to closed ports");
110 static int blackhole = 0;
111 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
112 &blackhole, 0, "Do not send RST on segments to closed ports");
114 int tcp_delack_enabled = 1;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
116 &tcp_delack_enabled, 0,
117 "Delay ACK to try and piggyback it onto a data packet");
119 static int drop_synfin = 0;
120 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
121 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
123 static int tcp_do_rfc3042 = 1;
124 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
125 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
127 static int tcp_do_rfc3390 = 1;
128 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
130 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
133 int tcp_ecn_maxretries = 1;
134 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
135 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
136 &tcp_do_ecn, 0, "TCP ECN support");
137 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
138 &tcp_ecn_maxretries, 0, "Max retries before giving up on ECN");
140 static int tcp_insecure_rst = 0;
141 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
142 &tcp_insecure_rst, 0,
143 "Follow the old (insecure) criteria for accepting RST packets");
145 int tcp_do_autorcvbuf = 1;
146 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
147 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
149 int tcp_autorcvbuf_inc = 16*1024;
150 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
151 &tcp_autorcvbuf_inc, 0,
152 "Incrementor step size of automatic receive buffer");
154 int tcp_autorcvbuf_max = 256*1024;
155 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
156 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
158 struct inpcbhead tcb;
159 #define tcb6 tcb /* for KAME src sync over BSD*'s */
160 struct inpcbinfo tcbinfo;
162 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
163 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
164 struct socket *, struct tcpcb *, int, int, uint8_t);
165 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
166 struct tcpcb *, int, int);
167 static void tcp_pulloutofband(struct socket *,
168 struct tcphdr *, struct mbuf *, int);
169 static void tcp_xmit_timer(struct tcpcb *, int);
170 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
172 tcp_congestion_exp(struct tcpcb *);
175 tcp_congestion_exp(struct tcpcb *tp)
179 win = min(tp->snd_wnd, tp->snd_cwnd) /
183 tp->snd_ssthresh = win * tp->t_maxseg;
184 ENTER_FASTRECOVERY(tp);
185 tp->snd_recover = tp->snd_max;
186 if (tp->t_flags & TF_ECN_PERMIT)
187 tp->t_flags |= TF_ECN_SND_CWR;
190 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
192 #define ND6_HINT(tp) \
194 if ((tp) && (tp)->t_inpcb && \
195 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
196 nd6_nud_hint(NULL, NULL, 0); \
203 * Indicate whether this ack should be delayed. We can delay the ack if
204 * - there is no delayed ack timer in progress and
205 * - our last ack wasn't a 0-sized window. We never want to delay
206 * the ack that opens up a 0-sized window and
207 * - delayed acks are enabled or
208 * - this is a half-synchronized T/TCP connection.
210 #define DELAY_ACK(tp) \
211 ((!tcp_timer_active(tp, TT_DELACK) && \
212 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
213 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
216 * TCP input handling is split into multiple parts:
217 * tcp6_input is a thin wrapper around tcp_input for the extended
218 * ip6_protox[] call format in ip6_input
219 * tcp_input handles primary segment validation, inpcb lookup and
220 * SYN processing on listen sockets
221 * tcp_do_segment processes the ACK and text of the segment for
222 * establishing, established and closing connections
226 tcp6_input(struct mbuf **mp, int *offp, int proto)
228 struct mbuf *m = *mp;
229 struct in6_ifaddr *ia6;
231 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
234 * draft-itojun-ipv6-tcp-to-anycast
235 * better place to put this in?
237 ia6 = ip6_getdstifaddr(m);
238 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
241 ip6 = mtod(m, struct ip6_hdr *);
242 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
243 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
253 tcp_input(struct mbuf *m, int off0)
256 struct ip *ip = NULL;
258 struct inpcb *inp = NULL;
259 struct tcpcb *tp = NULL;
260 struct socket *so = NULL;
266 int rstreason = 0; /* For badport_bandlim accounting purposes */
268 #ifdef IPFIREWALL_FORWARD
269 struct m_tag *fwd_tag;
272 struct ip6_hdr *ip6 = NULL;
275 const void *ip6 = NULL;
276 const int isipv6 = 0;
278 struct tcpopt to; /* options in this segment */
279 char *s = NULL; /* address and port logging */
283 * The size of tcp_saveipgen must be the size of the max ip header,
286 u_char tcp_saveipgen[IP6_HDR_LEN];
287 struct tcphdr tcp_savetcp;
292 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
296 V_tcpstat.tcps_rcvtotal++;
300 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
301 ip6 = mtod(m, struct ip6_hdr *);
302 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
303 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
304 V_tcpstat.tcps_rcvbadsum++;
307 th = (struct tcphdr *)((caddr_t)ip6 + off0);
310 * Be proactive about unspecified IPv6 address in source.
311 * As we use all-zero to indicate unbounded/unconnected pcb,
312 * unspecified IPv6 address can be used to confuse us.
314 * Note that packets with unspecified IPv6 destination is
315 * already dropped in ip6_input.
317 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
322 th = NULL; /* XXX: Avoid compiler warning. */
326 * Get IP and TCP header together in first mbuf.
327 * Note: IP leaves IP header in first mbuf.
329 if (off0 > sizeof (struct ip)) {
330 ip_stripoptions(m, (struct mbuf *)0);
331 off0 = sizeof(struct ip);
333 if (m->m_len < sizeof (struct tcpiphdr)) {
334 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
336 V_tcpstat.tcps_rcvshort++;
340 ip = mtod(m, struct ip *);
341 ipov = (struct ipovly *)ip;
342 th = (struct tcphdr *)((caddr_t)ip + off0);
345 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
346 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
347 th->th_sum = m->m_pkthdr.csum_data;
349 th->th_sum = in_pseudo(ip->ip_src.s_addr,
351 htonl(m->m_pkthdr.csum_data +
354 th->th_sum ^= 0xffff;
356 ipov->ih_len = (u_short)tlen;
357 ipov->ih_len = htons(ipov->ih_len);
361 * Checksum extended TCP header and data.
363 len = sizeof (struct ip) + tlen;
364 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
365 ipov->ih_len = (u_short)tlen;
366 ipov->ih_len = htons(ipov->ih_len);
367 th->th_sum = in_cksum(m, len);
370 V_tcpstat.tcps_rcvbadsum++;
373 /* Re-initialization for later version check */
374 ip->ip_v = IPVERSION;
379 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
385 * Check that TCP offset makes sense,
386 * pull out TCP options and adjust length. XXX
388 off = th->th_off << 2;
389 if (off < sizeof (struct tcphdr) || off > tlen) {
390 V_tcpstat.tcps_rcvbadoff++;
393 tlen -= off; /* tlen is used instead of ti->ti_len */
394 if (off > sizeof (struct tcphdr)) {
397 IP6_EXTHDR_CHECK(m, off0, off, );
398 ip6 = mtod(m, struct ip6_hdr *);
399 th = (struct tcphdr *)((caddr_t)ip6 + off0);
402 if (m->m_len < sizeof(struct ip) + off) {
403 if ((m = m_pullup(m, sizeof (struct ip) + off))
405 V_tcpstat.tcps_rcvshort++;
408 ip = mtod(m, struct ip *);
409 ipov = (struct ipovly *)ip;
410 th = (struct tcphdr *)((caddr_t)ip + off0);
413 optlen = off - sizeof (struct tcphdr);
414 optp = (u_char *)(th + 1);
416 thflags = th->th_flags;
419 * Convert TCP protocol specific fields to host format.
421 th->th_seq = ntohl(th->th_seq);
422 th->th_ack = ntohl(th->th_ack);
423 th->th_win = ntohs(th->th_win);
424 th->th_urp = ntohs(th->th_urp);
427 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
429 drop_hdrlen = off0 + off;
432 * Locate pcb for segment.
434 INP_INFO_WLOCK(&V_tcbinfo);
436 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
437 #ifdef IPFIREWALL_FORWARD
439 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
441 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
443 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
444 struct sockaddr_in *next_hop;
446 next_hop = (struct sockaddr_in *)(fwd_tag+1);
448 * Transparently forwarded. Pretend to be the destination.
449 * already got one like this?
451 inp = in_pcblookup_hash(&V_tcbinfo,
452 ip->ip_src, th->th_sport,
453 ip->ip_dst, th->th_dport,
454 0, m->m_pkthdr.rcvif);
456 /* It's new. Try to find the ambushing socket. */
457 inp = in_pcblookup_hash(&V_tcbinfo,
458 ip->ip_src, th->th_sport,
461 ntohs(next_hop->sin_port) :
466 /* Remove the tag from the packet. We don't need it anymore. */
467 m_tag_delete(m, fwd_tag);
469 #endif /* IPFIREWALL_FORWARD */
473 inp = in6_pcblookup_hash(&V_tcbinfo,
474 &ip6->ip6_src, th->th_sport,
475 &ip6->ip6_dst, th->th_dport,
480 inp = in_pcblookup_hash(&V_tcbinfo,
481 ip->ip_src, th->th_sport,
482 ip->ip_dst, th->th_dport,
488 * If the INPCB does not exist then all data in the incoming
489 * segment is discarded and an appropriate RST is sent back.
490 * XXX MRT Send RST using which routing table?
494 * Log communication attempts to ports that are not
497 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
498 tcp_log_in_vain == 2) {
499 if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
500 log(LOG_INFO, "%s; %s: Connection attempt "
501 "to closed port\n", s, __func__);
504 * When blackholing do not respond with a RST but
505 * completely ignore the segment and drop it.
507 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
511 rstreason = BANDLIM_RST_CLOSEDPORT;
518 if (isipv6 && ipsec6_in_reject(m, inp)) {
519 V_ipsec6stat.in_polvio++;
523 if (ipsec4_in_reject(m, inp) != 0) {
524 V_ipsec4stat.in_polvio++;
530 * Check the minimum TTL for socket.
532 if (inp->inp_ip_minttl != 0) {
534 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
538 if (inp->inp_ip_minttl > ip->ip_ttl)
543 * A previous connection in TIMEWAIT state is supposed to catch
544 * stray or duplicate segments arriving late. If this segment
545 * was a legitimate new connection attempt the old INPCB gets
546 * removed and we can try again to find a listening socket.
548 if (inp->inp_vflag & INP_TIMEWAIT) {
549 if (thflags & TH_SYN)
550 tcp_dooptions(&to, optp, optlen, TO_SYN);
552 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
554 if (tcp_twcheck(inp, &to, th, m, tlen))
556 INP_INFO_WUNLOCK(&V_tcbinfo);
560 * The TCPCB may no longer exist if the connection is winding
561 * down or it is in the CLOSED state. Either way we drop the
562 * segment and send an appropriate response.
565 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
566 rstreason = BANDLIM_RST_CLOSEDPORT;
571 INP_WLOCK_ASSERT(inp);
572 if (mac_inpcb_check_deliver(inp, m))
575 so = inp->inp_socket;
576 KASSERT(so != NULL, ("%s: so == NULL", __func__));
578 if (so->so_options & SO_DEBUG) {
579 ostate = tp->t_state;
582 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
585 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
590 * When the socket is accepting connections (the INPCB is in LISTEN
591 * state) we look into the SYN cache if this is a new connection
592 * attempt or the completion of a previous one.
594 if (so->so_options & SO_ACCEPTCONN) {
595 struct in_conninfo inc;
597 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
598 "tp not listening", __func__));
600 bzero(&inc, sizeof(inc));
601 inc.inc_isipv6 = isipv6;
604 inc.inc6_faddr = ip6->ip6_src;
605 inc.inc6_laddr = ip6->ip6_dst;
609 inc.inc_faddr = ip->ip_src;
610 inc.inc_laddr = ip->ip_dst;
612 inc.inc_fport = th->th_sport;
613 inc.inc_lport = th->th_dport;
616 * Check for an existing connection attempt in syncache if
617 * the flag is only ACK. A successful lookup creates a new
618 * socket appended to the listen queue in SYN_RECEIVED state.
620 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
622 * Parse the TCP options here because
623 * syncookies need access to the reflected
626 tcp_dooptions(&to, optp, optlen, 0);
628 * NB: syncache_expand() doesn't unlock
629 * inp and tcpinfo locks.
631 if (!syncache_expand(&inc, &to, th, &so, m)) {
633 * No syncache entry or ACK was not
634 * for our SYN/ACK. Send a RST.
635 * NB: syncache did its own logging
636 * of the failure cause.
638 rstreason = BANDLIM_RST_OPENPORT;
643 * We completed the 3-way handshake
644 * but could not allocate a socket
645 * either due to memory shortage,
646 * listen queue length limits or
647 * global socket limits. Send RST
648 * or wait and have the remote end
649 * retransmit the ACK for another
652 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
653 log(LOG_DEBUG, "%s; %s: Listen socket: "
654 "Socket allocation failed due to "
655 "limits or memory shortage, %s\n",
657 V_tcp_sc_rst_sock_fail ?
658 "sending RST" : "try again");
659 if (V_tcp_sc_rst_sock_fail) {
660 rstreason = BANDLIM_UNLIMITED;
666 * Socket is created in state SYN_RECEIVED.
667 * Unlock the listen socket, lock the newly
668 * created socket and update the tp variable.
670 INP_WUNLOCK(inp); /* listen socket */
672 INP_WLOCK(inp); /* new connection */
674 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
677 * Process the segment and the data it
678 * contains. tcp_do_segment() consumes
679 * the mbuf chain and unlocks the inpcb.
681 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
683 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
687 * Segment flag validation for new connection attempts:
689 * Our (SYN|ACK) response was rejected.
690 * Check with syncache and remove entry to prevent
693 * NB: syncache_chkrst does its own logging of failure
696 if (thflags & TH_RST) {
697 syncache_chkrst(&inc, th);
701 * We can't do anything without SYN.
703 if ((thflags & TH_SYN) == 0) {
704 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
705 log(LOG_DEBUG, "%s; %s: Listen socket: "
706 "SYN is missing, segment ignored\n",
708 V_tcpstat.tcps_badsyn++;
712 * (SYN|ACK) is bogus on a listen socket.
714 if (thflags & TH_ACK) {
715 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
716 log(LOG_DEBUG, "%s; %s: Listen socket: "
717 "SYN|ACK invalid, segment rejected\n",
719 syncache_badack(&inc); /* XXX: Not needed! */
720 V_tcpstat.tcps_badsyn++;
721 rstreason = BANDLIM_RST_OPENPORT;
725 * If the drop_synfin option is enabled, drop all
726 * segments with both the SYN and FIN bits set.
727 * This prevents e.g. nmap from identifying the
729 * XXX: Poor reasoning. nmap has other methods
730 * and is constantly refining its stack detection
732 * XXX: This is a violation of the TCP specification
733 * and was used by RFC1644.
735 if ((thflags & TH_FIN) && V_drop_synfin) {
736 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
737 log(LOG_DEBUG, "%s; %s: Listen socket: "
738 "SYN|FIN segment ignored (based on "
739 "sysctl setting)\n", s, __func__);
740 V_tcpstat.tcps_badsyn++;
744 * Segment's flags are (SYN) or (SYN|FIN).
746 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
747 * as they do not affect the state of the TCP FSM.
748 * The data pointed to by TH_URG and th_urp is ignored.
750 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
751 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
752 KASSERT(thflags & (TH_SYN),
753 ("%s: Listen socket: TH_SYN not set", __func__));
756 * If deprecated address is forbidden,
757 * we do not accept SYN to deprecated interface
758 * address to prevent any new inbound connection from
759 * getting established.
760 * When we do not accept SYN, we send a TCP RST,
761 * with deprecated source address (instead of dropping
762 * it). We compromise it as it is much better for peer
763 * to send a RST, and RST will be the final packet
766 * If we do not forbid deprecated addresses, we accept
767 * the SYN packet. RFC2462 does not suggest dropping
769 * If we decipher RFC2462 5.5.4, it says like this:
770 * 1. use of deprecated addr with existing
771 * communication is okay - "SHOULD continue to be
773 * 2. use of it with new communication:
774 * (2a) "SHOULD NOT be used if alternate address
775 * with sufficient scope is available"
776 * (2b) nothing mentioned otherwise.
777 * Here we fall into (2b) case as we have no choice in
778 * our source address selection - we must obey the peer.
780 * The wording in RFC2462 is confusing, and there are
781 * multiple description text for deprecated address
782 * handling - worse, they are not exactly the same.
783 * I believe 5.5.4 is the best one, so we follow 5.5.4.
785 if (isipv6 && !V_ip6_use_deprecated) {
786 struct in6_ifaddr *ia6;
788 if ((ia6 = ip6_getdstifaddr(m)) &&
789 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
790 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
791 log(LOG_DEBUG, "%s; %s: Listen socket: "
792 "Connection attempt to deprecated "
793 "IPv6 address rejected\n",
795 rstreason = BANDLIM_RST_OPENPORT;
801 * Basic sanity checks on incoming SYN requests:
802 * Don't respond if the destination is a link layer
803 * broadcast according to RFC1122 4.2.3.10, p. 104.
804 * If it is from this socket it must be forged.
805 * Don't respond if the source or destination is a
806 * global or subnet broad- or multicast address.
807 * Note that it is quite possible to receive unicast
808 * link-layer packets with a broadcast IP address. Use
809 * in_broadcast() to find them.
811 if (m->m_flags & (M_BCAST|M_MCAST)) {
812 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
813 log(LOG_DEBUG, "%s; %s: Listen socket: "
814 "Connection attempt from broad- or multicast "
815 "link layer address ignored\n", s, __func__);
820 if (th->th_dport == th->th_sport &&
821 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
822 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
823 log(LOG_DEBUG, "%s; %s: Listen socket: "
824 "Connection attempt to/from self "
825 "ignored\n", s, __func__);
828 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
829 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
830 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
831 log(LOG_DEBUG, "%s; %s: Listen socket: "
832 "Connection attempt from/to multicast "
833 "address ignored\n", s, __func__);
838 if (th->th_dport == th->th_sport &&
839 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
840 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
841 log(LOG_DEBUG, "%s; %s: Listen socket: "
842 "Connection attempt from/to self "
843 "ignored\n", s, __func__);
846 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
847 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
848 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
849 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
850 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
851 log(LOG_DEBUG, "%s; %s: Listen socket: "
852 "Connection attempt from/to broad- "
853 "or multicast address ignored\n",
859 * SYN appears to be valid. Create compressed TCP state
863 if (so->so_options & SO_DEBUG)
864 tcp_trace(TA_INPUT, ostate, tp,
865 (void *)tcp_saveipgen, &tcp_savetcp, 0);
867 tcp_dooptions(&to, optp, optlen, TO_SYN);
868 syncache_add(&inc, &to, th, inp, &so, m);
870 * Entry added to syncache and mbuf consumed.
871 * Everything already unlocked by syncache_add().
873 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
878 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
879 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
880 * the inpcb, and unlocks pcbinfo.
882 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos);
883 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
887 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
888 tcp_dropwithreset(m, th, tp, tlen, rstreason);
889 m = NULL; /* mbuf chain got consumed. */
891 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
894 INP_INFO_WUNLOCK(&V_tcbinfo);
896 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
905 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
906 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos)
908 int thflags, acked, ourfinisacked, needoutput = 0;
910 int rstreason, todrop, win;
916 * The size of tcp_saveipgen must be the size of the max ip header,
919 u_char tcp_saveipgen[IP6_HDR_LEN];
920 struct tcphdr tcp_savetcp;
923 thflags = th->th_flags;
925 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
926 INP_WLOCK_ASSERT(tp->t_inpcb);
927 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
929 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
933 * Segment received on connection.
934 * Reset idle time and keep-alive timer.
935 * XXX: This should be done after segment
936 * validation to ignore broken/spoofed segs.
938 tp->t_rcvtime = ticks;
939 if (TCPS_HAVEESTABLISHED(tp->t_state))
940 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
943 * Unscale the window into a 32-bit value.
944 * For the SYN_SENT state the scale is zero.
946 tiwin = th->th_win << tp->snd_scale;
949 * TCP ECN processing.
951 if (tp->t_flags & TF_ECN_PERMIT) {
952 switch (iptos & IPTOS_ECN_MASK) {
954 tp->t_flags |= TF_ECN_SND_ECE;
955 V_tcpstat.tcps_ecn_ce++;
958 V_tcpstat.tcps_ecn_ect0++;
961 V_tcpstat.tcps_ecn_ect1++;
965 if (thflags & TH_CWR)
966 tp->t_flags &= ~TF_ECN_SND_ECE;
969 * Congestion experienced.
970 * Ignore if we are already trying to recover.
972 if ((thflags & TH_ECE) &&
973 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
974 V_tcpstat.tcps_ecn_rcwnd++;
975 tcp_congestion_exp(tp);
980 * Parse options on any incoming segment.
982 tcp_dooptions(&to, (u_char *)(th + 1),
983 (th->th_off << 2) - sizeof(struct tcphdr),
984 (thflags & TH_SYN) ? TO_SYN : 0);
987 * If echoed timestamp is later than the current time,
988 * fall back to non RFC1323 RTT calculation. Normalize
989 * timestamp if syncookies were used when this connection
992 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
993 to.to_tsecr -= tp->ts_offset;
994 if (TSTMP_GT(to.to_tsecr, ticks))
999 * Process options only when we get SYN/ACK back. The SYN case
1000 * for incoming connections is handled in tcp_syncache.
1001 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1002 * or <SYN,ACK>) segment itself is never scaled.
1003 * XXX this is traditional behavior, may need to be cleaned up.
1005 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1006 if ((to.to_flags & TOF_SCALE) &&
1007 (tp->t_flags & TF_REQ_SCALE)) {
1008 tp->t_flags |= TF_RCVD_SCALE;
1009 tp->snd_scale = to.to_wscale;
1012 * Initial send window. It will be updated with
1013 * the next incoming segment to the scaled value.
1015 tp->snd_wnd = th->th_win;
1016 if (to.to_flags & TOF_TS) {
1017 tp->t_flags |= TF_RCVD_TSTMP;
1018 tp->ts_recent = to.to_tsval;
1019 tp->ts_recent_age = ticks;
1021 if (to.to_flags & TOF_MSS)
1022 tcp_mss(tp, to.to_mss);
1023 if ((tp->t_flags & TF_SACK_PERMIT) &&
1024 (to.to_flags & TOF_SACKPERM) == 0)
1025 tp->t_flags &= ~TF_SACK_PERMIT;
1029 * Header prediction: check for the two common cases
1030 * of a uni-directional data xfer. If the packet has
1031 * no control flags, is in-sequence, the window didn't
1032 * change and we're not retransmitting, it's a
1033 * candidate. If the length is zero and the ack moved
1034 * forward, we're the sender side of the xfer. Just
1035 * free the data acked & wake any higher level process
1036 * that was blocked waiting for space. If the length
1037 * is non-zero and the ack didn't move, we're the
1038 * receiver side. If we're getting packets in-order
1039 * (the reassembly queue is empty), add the data to
1040 * the socket buffer and note that we need a delayed ack.
1041 * Make sure that the hidden state-flags are also off.
1042 * Since we check for TCPS_ESTABLISHED first, it can only
1045 if (tp->t_state == TCPS_ESTABLISHED &&
1046 th->th_seq == tp->rcv_nxt &&
1047 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1048 tp->snd_nxt == tp->snd_max &&
1049 tiwin && tiwin == tp->snd_wnd &&
1050 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1051 LIST_EMPTY(&tp->t_segq) &&
1052 ((to.to_flags & TOF_TS) == 0 ||
1053 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1056 * If last ACK falls within this segment's sequence numbers,
1057 * record the timestamp.
1058 * NOTE that the test is modified according to the latest
1059 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1061 if ((to.to_flags & TOF_TS) != 0 &&
1062 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1063 tp->ts_recent_age = ticks;
1064 tp->ts_recent = to.to_tsval;
1068 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1069 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1070 tp->snd_cwnd >= tp->snd_wnd &&
1071 ((!V_tcp_do_newreno &&
1072 !(tp->t_flags & TF_SACK_PERMIT) &&
1073 tp->t_dupacks < tcprexmtthresh) ||
1074 ((V_tcp_do_newreno ||
1075 (tp->t_flags & TF_SACK_PERMIT)) &&
1076 !IN_FASTRECOVERY(tp) &&
1077 (to.to_flags & TOF_SACK) == 0 &&
1078 TAILQ_EMPTY(&tp->snd_holes)))) {
1080 ("%s: headlocked", __func__));
1081 INP_INFO_WUNLOCK(&V_tcbinfo);
1084 * This is a pure ack for outstanding data.
1086 ++V_tcpstat.tcps_predack;
1088 * "bad retransmit" recovery.
1090 if (tp->t_rxtshift == 1 &&
1091 ticks < tp->t_badrxtwin) {
1092 ++V_tcpstat.tcps_sndrexmitbad;
1093 tp->snd_cwnd = tp->snd_cwnd_prev;
1095 tp->snd_ssthresh_prev;
1096 tp->snd_recover = tp->snd_recover_prev;
1097 if (tp->t_flags & TF_WASFRECOVERY)
1098 ENTER_FASTRECOVERY(tp);
1099 tp->snd_nxt = tp->snd_max;
1100 tp->t_badrxtwin = 0;
1104 * Recalculate the transmit timer / rtt.
1106 * Some boxes send broken timestamp replies
1107 * during the SYN+ACK phase, ignore
1108 * timestamps of 0 or we could calculate a
1109 * huge RTT and blow up the retransmit timer.
1111 if ((to.to_flags & TOF_TS) != 0 &&
1113 if (!tp->t_rttlow ||
1114 tp->t_rttlow > ticks - to.to_tsecr)
1115 tp->t_rttlow = ticks - to.to_tsecr;
1117 ticks - to.to_tsecr + 1);
1118 } else if (tp->t_rtttime &&
1119 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1120 if (!tp->t_rttlow ||
1121 tp->t_rttlow > ticks - tp->t_rtttime)
1122 tp->t_rttlow = ticks - tp->t_rtttime;
1124 ticks - tp->t_rtttime);
1126 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1127 acked = th->th_ack - tp->snd_una;
1128 V_tcpstat.tcps_rcvackpack++;
1129 V_tcpstat.tcps_rcvackbyte += acked;
1130 sbdrop(&so->so_snd, acked);
1131 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1132 SEQ_LEQ(th->th_ack, tp->snd_recover))
1133 tp->snd_recover = th->th_ack - 1;
1134 tp->snd_una = th->th_ack;
1136 * Pull snd_wl2 up to prevent seq wrap relative
1139 tp->snd_wl2 = th->th_ack;
1142 ND6_HINT(tp); /* Some progress has been made. */
1145 * If all outstanding data are acked, stop
1146 * retransmit timer, otherwise restart timer
1147 * using current (possibly backed-off) value.
1148 * If process is waiting for space,
1149 * wakeup/selwakeup/signal. If data
1150 * are ready to send, let tcp_output
1151 * decide between more output or persist.
1154 if (so->so_options & SO_DEBUG)
1155 tcp_trace(TA_INPUT, ostate, tp,
1156 (void *)tcp_saveipgen,
1159 if (tp->snd_una == tp->snd_max)
1160 tcp_timer_activate(tp, TT_REXMT, 0);
1161 else if (!tcp_timer_active(tp, TT_PERSIST))
1162 tcp_timer_activate(tp, TT_REXMT,
1165 if (so->so_snd.sb_cc)
1166 (void) tcp_output(tp);
1169 } else if (th->th_ack == tp->snd_una &&
1170 tlen <= sbspace(&so->so_rcv)) {
1171 int newsize = 0; /* automatic sockbuf scaling */
1173 KASSERT(headlocked, ("%s: headlocked", __func__));
1174 INP_INFO_WUNLOCK(&V_tcbinfo);
1177 * This is a pure, in-sequence data packet
1178 * with nothing on the reassembly queue and
1179 * we have enough buffer space to take it.
1181 /* Clean receiver SACK report if present */
1182 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1183 tcp_clean_sackreport(tp);
1184 ++V_tcpstat.tcps_preddat;
1185 tp->rcv_nxt += tlen;
1187 * Pull snd_wl1 up to prevent seq wrap relative to
1190 tp->snd_wl1 = th->th_seq;
1192 * Pull rcv_up up to prevent seq wrap relative to
1195 tp->rcv_up = tp->rcv_nxt;
1196 V_tcpstat.tcps_rcvpack++;
1197 V_tcpstat.tcps_rcvbyte += tlen;
1198 ND6_HINT(tp); /* Some progress has been made */
1200 if (so->so_options & SO_DEBUG)
1201 tcp_trace(TA_INPUT, ostate, tp,
1202 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1205 * Automatic sizing of receive socket buffer. Often the send
1206 * buffer size is not optimally adjusted to the actual network
1207 * conditions at hand (delay bandwidth product). Setting the
1208 * buffer size too small limits throughput on links with high
1209 * bandwidth and high delay (eg. trans-continental/oceanic links).
1211 * On the receive side the socket buffer memory is only rarely
1212 * used to any significant extent. This allows us to be much
1213 * more aggressive in scaling the receive socket buffer. For
1214 * the case that the buffer space is actually used to a large
1215 * extent and we run out of kernel memory we can simply drop
1216 * the new segments; TCP on the sender will just retransmit it
1217 * later. Setting the buffer size too big may only consume too
1218 * much kernel memory if the application doesn't read() from
1219 * the socket or packet loss or reordering makes use of the
1222 * The criteria to step up the receive buffer one notch are:
1223 * 1. the number of bytes received during the time it takes
1224 * one timestamp to be reflected back to us (the RTT);
1225 * 2. received bytes per RTT is within seven eighth of the
1226 * current socket buffer size;
1227 * 3. receive buffer size has not hit maximal automatic size;
1229 * This algorithm does one step per RTT at most and only if
1230 * we receive a bulk stream w/o packet losses or reorderings.
1231 * Shrinking the buffer during idle times is not necessary as
1232 * it doesn't consume any memory when idle.
1234 * TODO: Only step up if the application is actually serving
1235 * the buffer to better manage the socket buffer resources.
1237 if (V_tcp_do_autorcvbuf &&
1239 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1240 if (to.to_tsecr > tp->rfbuf_ts &&
1241 to.to_tsecr - tp->rfbuf_ts < hz) {
1243 (so->so_rcv.sb_hiwat / 8 * 7) &&
1244 so->so_rcv.sb_hiwat <
1245 V_tcp_autorcvbuf_max) {
1247 min(so->so_rcv.sb_hiwat +
1248 V_tcp_autorcvbuf_inc,
1249 V_tcp_autorcvbuf_max);
1251 /* Start over with next RTT. */
1255 tp->rfbuf_cnt += tlen; /* add up */
1258 /* Add data to socket buffer. */
1259 SOCKBUF_LOCK(&so->so_rcv);
1260 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1264 * Set new socket buffer size.
1265 * Give up when limit is reached.
1268 if (!sbreserve_locked(&so->so_rcv,
1269 newsize, so, curthread))
1270 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1271 m_adj(m, drop_hdrlen); /* delayed header drop */
1272 sbappendstream_locked(&so->so_rcv, m);
1274 /* NB: sorwakeup_locked() does an implicit unlock. */
1275 sorwakeup_locked(so);
1276 if (DELAY_ACK(tp)) {
1277 tp->t_flags |= TF_DELACK;
1279 tp->t_flags |= TF_ACKNOW;
1287 * Calculate amount of space in receive window,
1288 * and then do TCP input processing.
1289 * Receive window is amount of space in rcv queue,
1290 * but not less than advertised window.
1292 win = sbspace(&so->so_rcv);
1295 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1297 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1301 switch (tp->t_state) {
1304 * If the state is SYN_RECEIVED:
1305 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1307 case TCPS_SYN_RECEIVED:
1308 if ((thflags & TH_ACK) &&
1309 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1310 SEQ_GT(th->th_ack, tp->snd_max))) {
1311 rstreason = BANDLIM_RST_OPENPORT;
1317 * If the state is SYN_SENT:
1318 * if seg contains an ACK, but not for our SYN, drop the input.
1319 * if seg contains a RST, then drop the connection.
1320 * if seg does not contain SYN, then drop it.
1321 * Otherwise this is an acceptable SYN segment
1322 * initialize tp->rcv_nxt and tp->irs
1323 * if seg contains ack then advance tp->snd_una
1324 * if seg contains an ECE and ECN support is enabled, the stream
1326 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1327 * arrange for segment to be acked (eventually)
1328 * continue processing rest of data/controls, beginning with URG
1331 if ((thflags & TH_ACK) &&
1332 (SEQ_LEQ(th->th_ack, tp->iss) ||
1333 SEQ_GT(th->th_ack, tp->snd_max))) {
1334 rstreason = BANDLIM_UNLIMITED;
1337 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1338 tp = tcp_drop(tp, ECONNREFUSED);
1339 if (thflags & TH_RST)
1341 if (!(thflags & TH_SYN))
1344 tp->irs = th->th_seq;
1346 if (thflags & TH_ACK) {
1347 V_tcpstat.tcps_connects++;
1351 mac_socketpeer_set_from_mbuf(m, so);
1354 /* Do window scaling on this connection? */
1355 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1356 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1357 tp->rcv_scale = tp->request_r_scale;
1359 tp->rcv_adv += tp->rcv_wnd;
1360 tp->snd_una++; /* SYN is acked */
1362 * If there's data, delay ACK; if there's also a FIN
1363 * ACKNOW will be turned on later.
1365 if (DELAY_ACK(tp) && tlen != 0)
1366 tcp_timer_activate(tp, TT_DELACK,
1369 tp->t_flags |= TF_ACKNOW;
1371 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1372 tp->t_flags |= TF_ECN_PERMIT;
1373 V_tcpstat.tcps_ecn_shs++;
1377 * Received <SYN,ACK> in SYN_SENT[*] state.
1379 * SYN_SENT --> ESTABLISHED
1380 * SYN_SENT* --> FIN_WAIT_1
1382 tp->t_starttime = ticks;
1383 if (tp->t_flags & TF_NEEDFIN) {
1384 tp->t_state = TCPS_FIN_WAIT_1;
1385 tp->t_flags &= ~TF_NEEDFIN;
1388 tp->t_state = TCPS_ESTABLISHED;
1389 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1393 * Received initial SYN in SYN-SENT[*] state =>
1394 * simultaneous open. If segment contains CC option
1395 * and there is a cached CC, apply TAO test.
1396 * If it succeeds, connection is * half-synchronized.
1397 * Otherwise, do 3-way handshake:
1398 * SYN-SENT -> SYN-RECEIVED
1399 * SYN-SENT* -> SYN-RECEIVED*
1400 * If there was no CC option, clear cached CC value.
1402 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1403 tcp_timer_activate(tp, TT_REXMT, 0);
1404 tp->t_state = TCPS_SYN_RECEIVED;
1407 KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1409 INP_WLOCK_ASSERT(tp->t_inpcb);
1412 * Advance th->th_seq to correspond to first data byte.
1413 * If data, trim to stay within window,
1414 * dropping FIN if necessary.
1417 if (tlen > tp->rcv_wnd) {
1418 todrop = tlen - tp->rcv_wnd;
1422 V_tcpstat.tcps_rcvpackafterwin++;
1423 V_tcpstat.tcps_rcvbyteafterwin += todrop;
1425 tp->snd_wl1 = th->th_seq - 1;
1426 tp->rcv_up = th->th_seq;
1428 * Client side of transaction: already sent SYN and data.
1429 * If the remote host used T/TCP to validate the SYN,
1430 * our data will be ACK'd; if so, enter normal data segment
1431 * processing in the middle of step 5, ack processing.
1432 * Otherwise, goto step 6.
1434 if (thflags & TH_ACK)
1440 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1441 * do normal processing.
1443 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1447 break; /* continue normal processing */
1451 * States other than LISTEN or SYN_SENT.
1452 * First check the RST flag and sequence number since reset segments
1453 * are exempt from the timestamp and connection count tests. This
1454 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1455 * below which allowed reset segments in half the sequence space
1456 * to fall though and be processed (which gives forged reset
1457 * segments with a random sequence number a 50 percent chance of
1458 * killing a connection).
1459 * Then check timestamp, if present.
1460 * Then check the connection count, if present.
1461 * Then check that at least some bytes of segment are within
1462 * receive window. If segment begins before rcv_nxt,
1463 * drop leading data (and SYN); if nothing left, just ack.
1466 * If the RST bit is set, check the sequence number to see
1467 * if this is a valid reset segment.
1469 * In all states except SYN-SENT, all reset (RST) segments
1470 * are validated by checking their SEQ-fields. A reset is
1471 * valid if its sequence number is in the window.
1472 * Note: this does not take into account delayed ACKs, so
1473 * we should test against last_ack_sent instead of rcv_nxt.
1474 * The sequence number in the reset segment is normally an
1475 * echo of our outgoing acknowlegement numbers, but some hosts
1476 * send a reset with the sequence number at the rightmost edge
1477 * of our receive window, and we have to handle this case.
1478 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1479 * that brute force RST attacks are possible. To combat this,
1480 * we use a much stricter check while in the ESTABLISHED state,
1481 * only accepting RSTs where the sequence number is equal to
1482 * last_ack_sent. In all other states (the states in which a
1483 * RST is more likely), the more permissive check is used.
1484 * If we have multiple segments in flight, the intial reset
1485 * segment sequence numbers will be to the left of last_ack_sent,
1486 * but they will eventually catch up.
1487 * In any case, it never made sense to trim reset segments to
1488 * fit the receive window since RFC 1122 says:
1489 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1491 * A TCP SHOULD allow a received RST segment to include data.
1494 * It has been suggested that a RST segment could contain
1495 * ASCII text that encoded and explained the cause of the
1496 * RST. No standard has yet been established for such
1499 * If the reset segment passes the sequence number test examine
1501 * SYN_RECEIVED STATE:
1502 * If passive open, return to LISTEN state.
1503 * If active open, inform user that connection was refused.
1504 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1505 * Inform user that connection was reset, and close tcb.
1506 * CLOSING, LAST_ACK STATES:
1509 * Drop the segment - see Stevens, vol. 2, p. 964 and
1512 if (thflags & TH_RST) {
1513 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1514 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1515 switch (tp->t_state) {
1517 case TCPS_SYN_RECEIVED:
1518 so->so_error = ECONNREFUSED;
1521 case TCPS_ESTABLISHED:
1522 if (V_tcp_insecure_rst == 0 &&
1523 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1524 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1525 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1526 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1527 V_tcpstat.tcps_badrst++;
1531 case TCPS_FIN_WAIT_1:
1532 case TCPS_FIN_WAIT_2:
1533 case TCPS_CLOSE_WAIT:
1534 so->so_error = ECONNRESET;
1536 tp->t_state = TCPS_CLOSED;
1537 V_tcpstat.tcps_drops++;
1538 KASSERT(headlocked, ("%s: trimthenstep6: "
1539 "tcp_close: head not locked", __func__));
1545 KASSERT(headlocked, ("%s: trimthenstep6: "
1546 "tcp_close.2: head not locked", __func__));
1555 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1556 * and it's less than ts_recent, drop it.
1558 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1559 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1561 /* Check to see if ts_recent is over 24 days old. */
1562 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1564 * Invalidate ts_recent. If this segment updates
1565 * ts_recent, the age will be reset later and ts_recent
1566 * will get a valid value. If it does not, setting
1567 * ts_recent to zero will at least satisfy the
1568 * requirement that zero be placed in the timestamp
1569 * echo reply when ts_recent isn't valid. The
1570 * age isn't reset until we get a valid ts_recent
1571 * because we don't want out-of-order segments to be
1572 * dropped when ts_recent is old.
1576 V_tcpstat.tcps_rcvduppack++;
1577 V_tcpstat.tcps_rcvdupbyte += tlen;
1578 V_tcpstat.tcps_pawsdrop++;
1586 * In the SYN-RECEIVED state, validate that the packet belongs to
1587 * this connection before trimming the data to fit the receive
1588 * window. Check the sequence number versus IRS since we know
1589 * the sequence numbers haven't wrapped. This is a partial fix
1590 * for the "LAND" DoS attack.
1592 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1593 rstreason = BANDLIM_RST_OPENPORT;
1597 todrop = tp->rcv_nxt - th->th_seq;
1599 if (thflags & TH_SYN) {
1609 * Following if statement from Stevens, vol. 2, p. 960.
1612 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1614 * Any valid FIN must be to the left of the window.
1615 * At this point the FIN must be a duplicate or out
1616 * of sequence; drop it.
1621 * Send an ACK to resynchronize and drop any data.
1622 * But keep on processing for RST or ACK.
1624 tp->t_flags |= TF_ACKNOW;
1626 V_tcpstat.tcps_rcvduppack++;
1627 V_tcpstat.tcps_rcvdupbyte += todrop;
1629 V_tcpstat.tcps_rcvpartduppack++;
1630 V_tcpstat.tcps_rcvpartdupbyte += todrop;
1632 drop_hdrlen += todrop; /* drop from the top afterwards */
1633 th->th_seq += todrop;
1635 if (th->th_urp > todrop)
1636 th->th_urp -= todrop;
1644 * If new data are received on a connection after the
1645 * user processes are gone, then RST the other end.
1647 if ((so->so_state & SS_NOFDREF) &&
1648 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1651 KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1652 "not locked", __func__));
1653 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1654 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
1655 "was closed, sending RST and removing tcpcb\n",
1656 s, __func__, tcpstates[tp->t_state], tlen);
1660 V_tcpstat.tcps_rcvafterclose++;
1661 rstreason = BANDLIM_UNLIMITED;
1666 * If segment ends after window, drop trailing data
1667 * (and PUSH and FIN); if nothing left, just ACK.
1669 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1671 V_tcpstat.tcps_rcvpackafterwin++;
1672 if (todrop >= tlen) {
1673 V_tcpstat.tcps_rcvbyteafterwin += tlen;
1675 * If window is closed can only take segments at
1676 * window edge, and have to drop data and PUSH from
1677 * incoming segments. Continue processing, but
1678 * remember to ack. Otherwise, drop segment
1681 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1682 tp->t_flags |= TF_ACKNOW;
1683 V_tcpstat.tcps_rcvwinprobe++;
1687 V_tcpstat.tcps_rcvbyteafterwin += todrop;
1690 thflags &= ~(TH_PUSH|TH_FIN);
1694 * If last ACK falls within this segment's sequence numbers,
1695 * record its timestamp.
1697 * 1) That the test incorporates suggestions from the latest
1698 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1699 * 2) That updating only on newer timestamps interferes with
1700 * our earlier PAWS tests, so this check should be solely
1701 * predicated on the sequence space of this segment.
1702 * 3) That we modify the segment boundary check to be
1703 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1704 * instead of RFC1323's
1705 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1706 * This modified check allows us to overcome RFC1323's
1707 * limitations as described in Stevens TCP/IP Illustrated
1708 * Vol. 2 p.869. In such cases, we can still calculate the
1709 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1711 if ((to.to_flags & TOF_TS) != 0 &&
1712 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1713 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1714 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1715 tp->ts_recent_age = ticks;
1716 tp->ts_recent = to.to_tsval;
1720 * If a SYN is in the window, then this is an
1721 * error and we send an RST and drop the connection.
1723 if (thflags & TH_SYN) {
1724 KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1725 "head not locked", __func__));
1726 tp = tcp_drop(tp, ECONNRESET);
1727 rstreason = BANDLIM_UNLIMITED;
1732 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1733 * flag is on (half-synchronized state), then queue data for
1734 * later processing; else drop segment and return.
1736 if ((thflags & TH_ACK) == 0) {
1737 if (tp->t_state == TCPS_SYN_RECEIVED ||
1738 (tp->t_flags & TF_NEEDSYN))
1740 else if (tp->t_flags & TF_ACKNOW)
1749 switch (tp->t_state) {
1752 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1753 * ESTABLISHED state and continue processing.
1754 * The ACK was checked above.
1756 case TCPS_SYN_RECEIVED:
1758 V_tcpstat.tcps_connects++;
1760 /* Do window scaling? */
1761 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1762 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1763 tp->rcv_scale = tp->request_r_scale;
1764 tp->snd_wnd = tiwin;
1768 * SYN-RECEIVED -> ESTABLISHED
1769 * SYN-RECEIVED* -> FIN-WAIT-1
1771 tp->t_starttime = ticks;
1772 if (tp->t_flags & TF_NEEDFIN) {
1773 tp->t_state = TCPS_FIN_WAIT_1;
1774 tp->t_flags &= ~TF_NEEDFIN;
1776 tp->t_state = TCPS_ESTABLISHED;
1777 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1780 * If segment contains data or ACK, will call tcp_reass()
1781 * later; if not, do so now to pass queued data to user.
1783 if (tlen == 0 && (thflags & TH_FIN) == 0)
1784 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1786 tp->snd_wl1 = th->th_seq - 1;
1790 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1791 * ACKs. If the ack is in the range
1792 * tp->snd_una < th->th_ack <= tp->snd_max
1793 * then advance tp->snd_una to th->th_ack and drop
1794 * data from the retransmission queue. If this ACK reflects
1795 * more up to date window information we update our window information.
1797 case TCPS_ESTABLISHED:
1798 case TCPS_FIN_WAIT_1:
1799 case TCPS_FIN_WAIT_2:
1800 case TCPS_CLOSE_WAIT:
1803 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1804 V_tcpstat.tcps_rcvacktoomuch++;
1807 if ((tp->t_flags & TF_SACK_PERMIT) &&
1808 ((to.to_flags & TOF_SACK) ||
1809 !TAILQ_EMPTY(&tp->snd_holes)))
1810 tcp_sack_doack(tp, &to, th->th_ack);
1811 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1812 if (tlen == 0 && tiwin == tp->snd_wnd) {
1813 V_tcpstat.tcps_rcvdupack++;
1815 * If we have outstanding data (other than
1816 * a window probe), this is a completely
1817 * duplicate ack (ie, window info didn't
1818 * change), the ack is the biggest we've
1819 * seen and we've seen exactly our rexmt
1820 * threshhold of them, assume a packet
1821 * has been dropped and retransmit it.
1822 * Kludge snd_nxt & the congestion
1823 * window so we send only this one
1826 * We know we're losing at the current
1827 * window size so do congestion avoidance
1828 * (set ssthresh to half the current window
1829 * and pull our congestion window back to
1830 * the new ssthresh).
1832 * Dup acks mean that packets have left the
1833 * network (they're now cached at the receiver)
1834 * so bump cwnd by the amount in the receiver
1835 * to keep a constant cwnd packets in the
1838 * When using TCP ECN, notify the peer that
1839 * we reduced the cwnd.
1841 if (!tcp_timer_active(tp, TT_REXMT) ||
1842 th->th_ack != tp->snd_una)
1844 else if (++tp->t_dupacks > tcprexmtthresh ||
1845 ((V_tcp_do_newreno ||
1846 (tp->t_flags & TF_SACK_PERMIT)) &&
1847 IN_FASTRECOVERY(tp))) {
1848 if ((tp->t_flags & TF_SACK_PERMIT) &&
1849 IN_FASTRECOVERY(tp)) {
1853 * Compute the amount of data in flight first.
1854 * We can inject new data into the pipe iff
1855 * we have less than 1/2 the original window's
1856 * worth of data in flight.
1858 awnd = (tp->snd_nxt - tp->snd_fack) +
1859 tp->sackhint.sack_bytes_rexmit;
1860 if (awnd < tp->snd_ssthresh) {
1861 tp->snd_cwnd += tp->t_maxseg;
1862 if (tp->snd_cwnd > tp->snd_ssthresh)
1863 tp->snd_cwnd = tp->snd_ssthresh;
1866 tp->snd_cwnd += tp->t_maxseg;
1867 (void) tcp_output(tp);
1869 } else if (tp->t_dupacks == tcprexmtthresh) {
1870 tcp_seq onxt = tp->snd_nxt;
1873 * If we're doing sack, check to
1874 * see if we're already in sack
1875 * recovery. If we're not doing sack,
1876 * check to see if we're in newreno
1879 if (tp->t_flags & TF_SACK_PERMIT) {
1880 if (IN_FASTRECOVERY(tp)) {
1884 } else if (V_tcp_do_newreno ||
1886 if (SEQ_LEQ(th->th_ack,
1892 tcp_congestion_exp(tp);
1893 tcp_timer_activate(tp, TT_REXMT, 0);
1895 if (tp->t_flags & TF_SACK_PERMIT) {
1896 V_tcpstat.tcps_sack_recovery_episode++;
1897 tp->sack_newdata = tp->snd_nxt;
1898 tp->snd_cwnd = tp->t_maxseg;
1899 (void) tcp_output(tp);
1902 tp->snd_nxt = th->th_ack;
1903 tp->snd_cwnd = tp->t_maxseg;
1904 (void) tcp_output(tp);
1905 KASSERT(tp->snd_limited <= 2,
1906 ("%s: tp->snd_limited too big",
1908 tp->snd_cwnd = tp->snd_ssthresh +
1910 (tp->t_dupacks - tp->snd_limited);
1911 if (SEQ_GT(onxt, tp->snd_nxt))
1914 } else if (V_tcp_do_rfc3042) {
1915 u_long oldcwnd = tp->snd_cwnd;
1916 tcp_seq oldsndmax = tp->snd_max;
1919 KASSERT(tp->t_dupacks == 1 ||
1921 ("%s: dupacks not 1 or 2",
1923 if (tp->t_dupacks == 1)
1924 tp->snd_limited = 0;
1926 (tp->snd_nxt - tp->snd_una) +
1927 (tp->t_dupacks - tp->snd_limited) *
1929 (void) tcp_output(tp);
1930 sent = tp->snd_max - oldsndmax;
1931 if (sent > tp->t_maxseg) {
1932 KASSERT((tp->t_dupacks == 2 &&
1933 tp->snd_limited == 0) ||
1934 (sent == tp->t_maxseg + 1 &&
1935 tp->t_flags & TF_SENTFIN),
1936 ("%s: sent too much",
1938 tp->snd_limited = 2;
1939 } else if (sent > 0)
1941 tp->snd_cwnd = oldcwnd;
1949 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
1950 ("%s: th_ack <= snd_una", __func__));
1953 * If the congestion window was inflated to account
1954 * for the other side's cached packets, retract it.
1956 if (V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
1957 if (IN_FASTRECOVERY(tp)) {
1958 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1959 if (tp->t_flags & TF_SACK_PERMIT)
1960 tcp_sack_partialack(tp, th);
1962 tcp_newreno_partial_ack(tp, th);
1965 * Out of fast recovery.
1966 * Window inflation should have left us
1967 * with approximately snd_ssthresh
1969 * But in case we would be inclined to
1970 * send a burst, better to do it via
1971 * the slow start mechanism.
1973 if (SEQ_GT(th->th_ack +
1976 tp->snd_cwnd = tp->snd_max -
1980 tp->snd_cwnd = tp->snd_ssthresh;
1984 if (tp->t_dupacks >= tcprexmtthresh &&
1985 tp->snd_cwnd > tp->snd_ssthresh)
1986 tp->snd_cwnd = tp->snd_ssthresh;
1990 * If we reach this point, ACK is not a duplicate,
1991 * i.e., it ACKs something we sent.
1993 if (tp->t_flags & TF_NEEDSYN) {
1995 * T/TCP: Connection was half-synchronized, and our
1996 * SYN has been ACK'd (so connection is now fully
1997 * synchronized). Go to non-starred state,
1998 * increment snd_una for ACK of SYN, and check if
1999 * we can do window scaling.
2001 tp->t_flags &= ~TF_NEEDSYN;
2003 /* Do window scaling? */
2004 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2005 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2006 tp->rcv_scale = tp->request_r_scale;
2007 /* Send window already scaled. */
2012 KASSERT(headlocked, ("%s: process_ACK: head not locked",
2014 INP_WLOCK_ASSERT(tp->t_inpcb);
2016 acked = th->th_ack - tp->snd_una;
2017 V_tcpstat.tcps_rcvackpack++;
2018 V_tcpstat.tcps_rcvackbyte += acked;
2021 * If we just performed our first retransmit, and the ACK
2022 * arrives within our recovery window, then it was a mistake
2023 * to do the retransmit in the first place. Recover our
2024 * original cwnd and ssthresh, and proceed to transmit where
2027 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2028 ++V_tcpstat.tcps_sndrexmitbad;
2029 tp->snd_cwnd = tp->snd_cwnd_prev;
2030 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2031 tp->snd_recover = tp->snd_recover_prev;
2032 if (tp->t_flags & TF_WASFRECOVERY)
2033 ENTER_FASTRECOVERY(tp);
2034 tp->snd_nxt = tp->snd_max;
2035 tp->t_badrxtwin = 0; /* XXX probably not required */
2039 * If we have a timestamp reply, update smoothed
2040 * round trip time. If no timestamp is present but
2041 * transmit timer is running and timed sequence
2042 * number was acked, update smoothed round trip time.
2043 * Since we now have an rtt measurement, cancel the
2044 * timer backoff (cf., Phil Karn's retransmit alg.).
2045 * Recompute the initial retransmit timer.
2047 * Some boxes send broken timestamp replies
2048 * during the SYN+ACK phase, ignore
2049 * timestamps of 0 or we could calculate a
2050 * huge RTT and blow up the retransmit timer.
2052 if ((to.to_flags & TOF_TS) != 0 &&
2054 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2055 tp->t_rttlow = ticks - to.to_tsecr;
2056 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2057 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2058 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2059 tp->t_rttlow = ticks - tp->t_rtttime;
2060 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2062 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2065 * If all outstanding data is acked, stop retransmit
2066 * timer and remember to restart (more output or persist).
2067 * If there is more data to be acked, restart retransmit
2068 * timer, using current (possibly backed-off) value.
2070 if (th->th_ack == tp->snd_max) {
2071 tcp_timer_activate(tp, TT_REXMT, 0);
2073 } else if (!tcp_timer_active(tp, TT_PERSIST))
2074 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2077 * If no data (only SYN) was ACK'd,
2078 * skip rest of ACK processing.
2084 * When new data is acked, open the congestion window.
2085 * If the window gives us less than ssthresh packets
2086 * in flight, open exponentially (maxseg per packet).
2087 * Otherwise open linearly: maxseg per window
2088 * (maxseg^2 / cwnd per packet).
2090 if ((!V_tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2091 !IN_FASTRECOVERY(tp)) {
2092 u_int cw = tp->snd_cwnd;
2093 u_int incr = tp->t_maxseg;
2094 if (cw > tp->snd_ssthresh)
2095 incr = incr * incr / cw;
2096 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2098 SOCKBUF_LOCK(&so->so_snd);
2099 if (acked > so->so_snd.sb_cc) {
2100 tp->snd_wnd -= so->so_snd.sb_cc;
2101 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2104 sbdrop_locked(&so->so_snd, acked);
2105 tp->snd_wnd -= acked;
2108 /* NB: sowwakeup_locked() does an implicit unlock. */
2109 sowwakeup_locked(so);
2110 /* Detect una wraparound. */
2111 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2112 !IN_FASTRECOVERY(tp) &&
2113 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2114 SEQ_LEQ(th->th_ack, tp->snd_recover))
2115 tp->snd_recover = th->th_ack - 1;
2116 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2117 IN_FASTRECOVERY(tp) &&
2118 SEQ_GEQ(th->th_ack, tp->snd_recover))
2119 EXIT_FASTRECOVERY(tp);
2120 tp->snd_una = th->th_ack;
2121 if (tp->t_flags & TF_SACK_PERMIT) {
2122 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2123 tp->snd_recover = tp->snd_una;
2125 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2126 tp->snd_nxt = tp->snd_una;
2128 switch (tp->t_state) {
2131 * In FIN_WAIT_1 STATE in addition to the processing
2132 * for the ESTABLISHED state if our FIN is now acknowledged
2133 * then enter FIN_WAIT_2.
2135 case TCPS_FIN_WAIT_1:
2136 if (ourfinisacked) {
2138 * If we can't receive any more
2139 * data, then closing user can proceed.
2140 * Starting the timer is contrary to the
2141 * specification, but if we don't get a FIN
2142 * we'll hang forever.
2145 * we should release the tp also, and use a
2148 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2151 soisdisconnected(so);
2152 timeout = (tcp_fast_finwait2_recycle) ?
2153 tcp_finwait2_timeout : tcp_maxidle;
2154 tcp_timer_activate(tp, TT_2MSL, timeout);
2156 tp->t_state = TCPS_FIN_WAIT_2;
2161 * In CLOSING STATE in addition to the processing for
2162 * the ESTABLISHED state if the ACK acknowledges our FIN
2163 * then enter the TIME-WAIT state, otherwise ignore
2167 if (ourfinisacked) {
2168 KASSERT(headlocked, ("%s: process_ACK: "
2169 "head not locked", __func__));
2171 INP_INFO_WUNLOCK(&V_tcbinfo);
2179 * In LAST_ACK, we may still be waiting for data to drain
2180 * and/or to be acked, as well as for the ack of our FIN.
2181 * If our FIN is now acknowledged, delete the TCB,
2182 * enter the closed state and return.
2185 if (ourfinisacked) {
2186 KASSERT(headlocked, ("%s: process_ACK: "
2187 "tcp_close: head not locked", __func__));
2196 KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2197 INP_WLOCK_ASSERT(tp->t_inpcb);
2200 * Update window information.
2201 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2203 if ((thflags & TH_ACK) &&
2204 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2205 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2206 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2207 /* keep track of pure window updates */
2209 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2210 V_tcpstat.tcps_rcvwinupd++;
2211 tp->snd_wnd = tiwin;
2212 tp->snd_wl1 = th->th_seq;
2213 tp->snd_wl2 = th->th_ack;
2214 if (tp->snd_wnd > tp->max_sndwnd)
2215 tp->max_sndwnd = tp->snd_wnd;
2220 * Process segments with URG.
2222 if ((thflags & TH_URG) && th->th_urp &&
2223 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2225 * This is a kludge, but if we receive and accept
2226 * random urgent pointers, we'll crash in
2227 * soreceive. It's hard to imagine someone
2228 * actually wanting to send this much urgent data.
2230 SOCKBUF_LOCK(&so->so_rcv);
2231 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2232 th->th_urp = 0; /* XXX */
2233 thflags &= ~TH_URG; /* XXX */
2234 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2235 goto dodata; /* XXX */
2238 * If this segment advances the known urgent pointer,
2239 * then mark the data stream. This should not happen
2240 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2241 * a FIN has been received from the remote side.
2242 * In these states we ignore the URG.
2244 * According to RFC961 (Assigned Protocols),
2245 * the urgent pointer points to the last octet
2246 * of urgent data. We continue, however,
2247 * to consider it to indicate the first octet
2248 * of data past the urgent section as the original
2249 * spec states (in one of two places).
2251 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2252 tp->rcv_up = th->th_seq + th->th_urp;
2253 so->so_oobmark = so->so_rcv.sb_cc +
2254 (tp->rcv_up - tp->rcv_nxt) - 1;
2255 if (so->so_oobmark == 0)
2256 so->so_rcv.sb_state |= SBS_RCVATMARK;
2258 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2260 SOCKBUF_UNLOCK(&so->so_rcv);
2262 * Remove out of band data so doesn't get presented to user.
2263 * This can happen independent of advancing the URG pointer,
2264 * but if two URG's are pending at once, some out-of-band
2265 * data may creep in... ick.
2267 if (th->th_urp <= (u_long)tlen &&
2268 !(so->so_options & SO_OOBINLINE)) {
2269 /* hdr drop is delayed */
2270 tcp_pulloutofband(so, th, m, drop_hdrlen);
2274 * If no out of band data is expected,
2275 * pull receive urgent pointer along
2276 * with the receive window.
2278 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2279 tp->rcv_up = tp->rcv_nxt;
2282 KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2283 INP_WLOCK_ASSERT(tp->t_inpcb);
2286 * Process the segment text, merging it into the TCP sequencing queue,
2287 * and arranging for acknowledgment of receipt if necessary.
2288 * This process logically involves adjusting tp->rcv_wnd as data
2289 * is presented to the user (this happens in tcp_usrreq.c,
2290 * case PRU_RCVD). If a FIN has already been received on this
2291 * connection then we just ignore the text.
2293 if ((tlen || (thflags & TH_FIN)) &&
2294 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2295 tcp_seq save_start = th->th_seq;
2296 m_adj(m, drop_hdrlen); /* delayed header drop */
2298 * Insert segment which includes th into TCP reassembly queue
2299 * with control block tp. Set thflags to whether reassembly now
2300 * includes a segment with FIN. This handles the common case
2301 * inline (segment is the next to be received on an established
2302 * connection, and the queue is empty), avoiding linkage into
2303 * and removal from the queue and repetition of various
2305 * Set DELACK for segments received in order, but ack
2306 * immediately when segments are out of order (so
2307 * fast retransmit can work).
2309 if (th->th_seq == tp->rcv_nxt &&
2310 LIST_EMPTY(&tp->t_segq) &&
2311 TCPS_HAVEESTABLISHED(tp->t_state)) {
2313 tp->t_flags |= TF_DELACK;
2315 tp->t_flags |= TF_ACKNOW;
2316 tp->rcv_nxt += tlen;
2317 thflags = th->th_flags & TH_FIN;
2318 V_tcpstat.tcps_rcvpack++;
2319 V_tcpstat.tcps_rcvbyte += tlen;
2321 SOCKBUF_LOCK(&so->so_rcv);
2322 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2325 sbappendstream_locked(&so->so_rcv, m);
2326 /* NB: sorwakeup_locked() does an implicit unlock. */
2327 sorwakeup_locked(so);
2330 * XXX: Due to the header drop above "th" is
2331 * theoretically invalid by now. Fortunately
2332 * m_adj() doesn't actually frees any mbufs
2333 * when trimming from the head.
2335 thflags = tcp_reass(tp, th, &tlen, m);
2336 tp->t_flags |= TF_ACKNOW;
2338 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2339 tcp_update_sack_list(tp, save_start, save_start + tlen);
2342 * Note the amount of data that peer has sent into
2343 * our window, in order to estimate the sender's
2347 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2355 * If FIN is received ACK the FIN and let the user know
2356 * that the connection is closing.
2358 if (thflags & TH_FIN) {
2359 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2362 * If connection is half-synchronized
2363 * (ie NEEDSYN flag on) then delay ACK,
2364 * so it may be piggybacked when SYN is sent.
2365 * Otherwise, since we received a FIN then no
2366 * more input can be expected, send ACK now.
2368 if (tp->t_flags & TF_NEEDSYN)
2369 tp->t_flags |= TF_DELACK;
2371 tp->t_flags |= TF_ACKNOW;
2374 switch (tp->t_state) {
2377 * In SYN_RECEIVED and ESTABLISHED STATES
2378 * enter the CLOSE_WAIT state.
2380 case TCPS_SYN_RECEIVED:
2381 tp->t_starttime = ticks;
2383 case TCPS_ESTABLISHED:
2384 tp->t_state = TCPS_CLOSE_WAIT;
2388 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2389 * enter the CLOSING state.
2391 case TCPS_FIN_WAIT_1:
2392 tp->t_state = TCPS_CLOSING;
2396 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2397 * starting the time-wait timer, turning off the other
2400 case TCPS_FIN_WAIT_2:
2401 KASSERT(headlocked == 1, ("%s: dodata: "
2402 "TCP_FIN_WAIT_2: head not locked", __func__));
2404 INP_INFO_WUNLOCK(&V_tcbinfo);
2408 INP_INFO_WUNLOCK(&V_tcbinfo);
2411 if (so->so_options & SO_DEBUG)
2412 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2417 * Return any desired output.
2419 if (needoutput || (tp->t_flags & TF_ACKNOW))
2420 (void) tcp_output(tp);
2423 KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2425 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2426 INP_WLOCK_ASSERT(tp->t_inpcb);
2427 if (tp->t_flags & TF_DELACK) {
2428 tp->t_flags &= ~TF_DELACK;
2429 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2431 INP_WUNLOCK(tp->t_inpcb);
2435 KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2437 * Generate an ACK dropping incoming segment if it occupies
2438 * sequence space, where the ACK reflects our state.
2440 * We can now skip the test for the RST flag since all
2441 * paths to this code happen after packets containing
2442 * RST have been dropped.
2444 * In the SYN-RECEIVED state, don't send an ACK unless the
2445 * segment we received passes the SYN-RECEIVED ACK test.
2446 * If it fails send a RST. This breaks the loop in the
2447 * "LAND" DoS attack, and also prevents an ACK storm
2448 * between two listening ports that have been sent forged
2449 * SYN segments, each with the source address of the other.
2451 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2452 (SEQ_GT(tp->snd_una, th->th_ack) ||
2453 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2454 rstreason = BANDLIM_RST_OPENPORT;
2458 if (so->so_options & SO_DEBUG)
2459 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2462 KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2463 INP_INFO_WUNLOCK(&V_tcbinfo);
2464 tp->t_flags |= TF_ACKNOW;
2465 (void) tcp_output(tp);
2466 INP_WUNLOCK(tp->t_inpcb);
2471 KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2473 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2476 INP_WUNLOCK(tp->t_inpcb);
2478 INP_INFO_WUNLOCK(&V_tcbinfo);
2483 * Drop space held by incoming segment and return.
2486 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2487 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2491 INP_WUNLOCK(tp->t_inpcb);
2493 INP_INFO_WUNLOCK(&V_tcbinfo);
2499 * Issue RST and make ACK acceptable to originator of segment.
2500 * The mbuf must still include the original packet header.
2504 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2505 int tlen, int rstreason)
2509 struct ip6_hdr *ip6;
2513 INP_WLOCK_ASSERT(tp->t_inpcb);
2516 /* Don't bother if destination was broadcast/multicast. */
2517 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2520 if (mtod(m, struct ip *)->ip_v == 6) {
2521 ip6 = mtod(m, struct ip6_hdr *);
2522 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2523 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2525 /* IPv6 anycast check is done at tcp6_input() */
2529 ip = mtod(m, struct ip *);
2530 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2531 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2532 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2533 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2537 /* Perform bandwidth limiting. */
2538 if (badport_bandlim(rstreason) < 0)
2541 /* tcp_respond consumes the mbuf chain. */
2542 if (th->th_flags & TH_ACK) {
2543 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2544 th->th_ack, TH_RST);
2546 if (th->th_flags & TH_SYN)
2548 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2549 (tcp_seq)0, TH_RST|TH_ACK);
2558 * Parse TCP options and place in tcpopt.
2561 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2566 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2568 if (opt == TCPOPT_EOL)
2570 if (opt == TCPOPT_NOP)
2576 if (optlen < 2 || optlen > cnt)
2581 if (optlen != TCPOLEN_MAXSEG)
2583 if (!(flags & TO_SYN))
2585 to->to_flags |= TOF_MSS;
2586 bcopy((char *)cp + 2,
2587 (char *)&to->to_mss, sizeof(to->to_mss));
2588 to->to_mss = ntohs(to->to_mss);
2591 if (optlen != TCPOLEN_WINDOW)
2593 if (!(flags & TO_SYN))
2595 to->to_flags |= TOF_SCALE;
2596 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2598 case TCPOPT_TIMESTAMP:
2599 if (optlen != TCPOLEN_TIMESTAMP)
2601 to->to_flags |= TOF_TS;
2602 bcopy((char *)cp + 2,
2603 (char *)&to->to_tsval, sizeof(to->to_tsval));
2604 to->to_tsval = ntohl(to->to_tsval);
2605 bcopy((char *)cp + 6,
2606 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2607 to->to_tsecr = ntohl(to->to_tsecr);
2609 #ifdef TCP_SIGNATURE
2611 * XXX In order to reply to a host which has set the
2612 * TCP_SIGNATURE option in its initial SYN, we have to
2613 * record the fact that the option was observed here
2614 * for the syncache code to perform the correct response.
2616 case TCPOPT_SIGNATURE:
2617 if (optlen != TCPOLEN_SIGNATURE)
2619 to->to_flags |= TOF_SIGNATURE;
2620 to->to_signature = cp + 2;
2623 case TCPOPT_SACK_PERMITTED:
2624 if (optlen != TCPOLEN_SACK_PERMITTED)
2626 if (!(flags & TO_SYN))
2630 to->to_flags |= TOF_SACKPERM;
2633 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2637 to->to_flags |= TOF_SACK;
2638 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2639 to->to_sacks = cp + 2;
2640 V_tcpstat.tcps_sack_rcv_blocks++;
2649 * Pull out of band byte out of a segment so
2650 * it doesn't appear in the user's data queue.
2651 * It is still reflected in the segment length for
2652 * sequencing purposes.
2655 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2658 int cnt = off + th->th_urp - 1;
2661 if (m->m_len > cnt) {
2662 char *cp = mtod(m, caddr_t) + cnt;
2663 struct tcpcb *tp = sototcpcb(so);
2665 INP_WLOCK_ASSERT(tp->t_inpcb);
2668 tp->t_oobflags |= TCPOOB_HAVEDATA;
2669 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2671 if (m->m_flags & M_PKTHDR)
2680 panic("tcp_pulloutofband");
2684 * Collect new round-trip time estimate
2685 * and update averages and current timeout.
2688 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2692 INP_WLOCK_ASSERT(tp->t_inpcb);
2694 V_tcpstat.tcps_rttupdated++;
2696 if (tp->t_srtt != 0) {
2698 * srtt is stored as fixed point with 5 bits after the
2699 * binary point (i.e., scaled by 8). The following magic
2700 * is equivalent to the smoothing algorithm in rfc793 with
2701 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2702 * point). Adjust rtt to origin 0.
2704 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2705 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2707 if ((tp->t_srtt += delta) <= 0)
2711 * We accumulate a smoothed rtt variance (actually, a
2712 * smoothed mean difference), then set the retransmit
2713 * timer to smoothed rtt + 4 times the smoothed variance.
2714 * rttvar is stored as fixed point with 4 bits after the
2715 * binary point (scaled by 16). The following is
2716 * equivalent to rfc793 smoothing with an alpha of .75
2717 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2718 * rfc793's wired-in beta.
2722 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2723 if ((tp->t_rttvar += delta) <= 0)
2725 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2726 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2729 * No rtt measurement yet - use the unsmoothed rtt.
2730 * Set the variance to half the rtt (so our first
2731 * retransmit happens at 3*rtt).
2733 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2734 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2735 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2741 * the retransmit should happen at rtt + 4 * rttvar.
2742 * Because of the way we do the smoothing, srtt and rttvar
2743 * will each average +1/2 tick of bias. When we compute
2744 * the retransmit timer, we want 1/2 tick of rounding and
2745 * 1 extra tick because of +-1/2 tick uncertainty in the
2746 * firing of the timer. The bias will give us exactly the
2747 * 1.5 tick we need. But, because the bias is
2748 * statistical, we have to test that we don't drop below
2749 * the minimum feasible timer (which is 2 ticks).
2751 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2752 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2755 * We received an ack for a packet that wasn't retransmitted;
2756 * it is probably safe to discard any error indications we've
2757 * received recently. This isn't quite right, but close enough
2758 * for now (a route might have failed after we sent a segment,
2759 * and the return path might not be symmetrical).
2761 tp->t_softerror = 0;
2765 * Determine a reasonable value for maxseg size.
2766 * If the route is known, check route for mtu.
2767 * If none, use an mss that can be handled on the outgoing
2768 * interface without forcing IP to fragment; if bigger than
2769 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2770 * to utilize large mbufs. If no route is found, route has no mtu,
2771 * or the destination isn't local, use a default, hopefully conservative
2772 * size (usually 512 or the default IP max size, but no more than the mtu
2773 * of the interface), as we can't discover anything about intervening
2774 * gateways or networks. We also initialize the congestion/slow start
2775 * window to be a single segment if the destination isn't local.
2776 * While looking at the routing entry, we also initialize other path-dependent
2777 * parameters from pre-set or cached values in the routing entry.
2779 * Also take into account the space needed for options that we
2780 * send regularly. Make maxseg shorter by that amount to assure
2781 * that we can send maxseg amount of data even when the options
2782 * are present. Store the upper limit of the length of options plus
2785 * In case of T/TCP, we call this routine during implicit connection
2786 * setup as well (offer = -1), to initialize maxseg from the cached
2789 * NOTE that this routine is only called when we process an incoming
2790 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2793 tcp_mss(struct tcpcb *tp, int offer)
2798 struct inpcb *inp = tp->t_inpcb;
2800 struct hc_metrics_lite metrics;
2801 int origoffer = offer;
2804 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2805 size_t min_protoh = isipv6 ?
2806 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2807 sizeof (struct tcpiphdr);
2809 const size_t min_protoh = sizeof(struct tcpiphdr);
2812 INP_WLOCK_ASSERT(tp->t_inpcb);
2817 maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2818 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
2822 maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2823 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
2827 * No route to sender, stay with default mss and return.
2832 /* What have we got? */
2836 * Offer == 0 means that there was no MSS on the SYN
2837 * segment, in this case we use tcp_mssdflt as
2838 * already assigned to t_maxopd above.
2840 offer = tp->t_maxopd;
2845 * Offer == -1 means that we didn't receive SYN yet.
2851 * Prevent DoS attack with too small MSS. Round up
2852 * to at least minmss.
2854 offer = max(offer, V_tcp_minmss);
2856 * Sanity check: make sure that maxopd will be large
2857 * enough to allow some data on segments even if the
2858 * all the option space is used (40bytes). Otherwise
2859 * funny things may happen in tcp_output.
2861 offer = max(offer, 64);
2865 * rmx information is now retrieved from tcp_hostcache.
2867 tcp_hc_get(&inp->inp_inc, &metrics);
2870 * If there's a discovered mtu int tcp hostcache, use it
2871 * else, use the link mtu.
2873 if (metrics.rmx_mtu)
2874 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2878 mss = maxmtu - min_protoh;
2879 if (!V_path_mtu_discovery &&
2880 !in6_localaddr(&inp->in6p_faddr))
2881 mss = min(mss, V_tcp_v6mssdflt);
2885 mss = maxmtu - min_protoh;
2886 if (!V_path_mtu_discovery &&
2887 !in_localaddr(inp->inp_faddr))
2888 mss = min(mss, V_tcp_mssdflt);
2891 mss = min(mss, offer);
2894 * maxopd stores the maximum length of data AND options
2895 * in a segment; maxseg is the amount of data in a normal
2896 * segment. We need to store this value (maxopd) apart
2897 * from maxseg, because now every segment carries options
2898 * and thus we normally have somewhat less data in segments.
2903 * origoffer==-1 indicates that no segments were received yet.
2904 * In this case we just guess.
2906 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2908 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2909 mss -= TCPOLEN_TSTAMP_APPA;
2911 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2913 mss &= ~(MCLBYTES-1);
2916 mss = mss / MCLBYTES * MCLBYTES;
2921 * If there's a pipesize, change the socket buffer to that size,
2922 * don't change if sb_hiwat is different than default (then it
2923 * has been changed on purpose with setsockopt).
2924 * Make the socket buffers an integral number of mss units;
2925 * if the mss is larger than the socket buffer, decrease the mss.
2927 so = inp->inp_socket;
2928 SOCKBUF_LOCK(&so->so_snd);
2929 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2930 bufsize = metrics.rmx_sendpipe;
2932 bufsize = so->so_snd.sb_hiwat;
2936 bufsize = roundup(bufsize, mss);
2937 if (bufsize > sb_max)
2939 if (bufsize > so->so_snd.sb_hiwat)
2940 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2942 SOCKBUF_UNLOCK(&so->so_snd);
2945 SOCKBUF_LOCK(&so->so_rcv);
2946 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2947 bufsize = metrics.rmx_recvpipe;
2949 bufsize = so->so_rcv.sb_hiwat;
2950 if (bufsize > mss) {
2951 bufsize = roundup(bufsize, mss);
2952 if (bufsize > sb_max)
2954 if (bufsize > so->so_rcv.sb_hiwat)
2955 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
2957 SOCKBUF_UNLOCK(&so->so_rcv);
2959 * While we're here, check the others too.
2961 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
2963 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2964 V_tcpstat.tcps_usedrtt++;
2965 if (metrics.rmx_rttvar) {
2966 tp->t_rttvar = metrics.rmx_rttvar;
2967 V_tcpstat.tcps_usedrttvar++;
2969 /* default variation is +- 1 rtt */
2971 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2973 TCPT_RANGESET(tp->t_rxtcur,
2974 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2975 tp->t_rttmin, TCPTV_REXMTMAX);
2977 if (metrics.rmx_ssthresh) {
2979 * There's some sort of gateway or interface
2980 * buffer limit on the path. Use this to set
2981 * the slow start threshhold, but set the
2982 * threshold to no less than 2*mss.
2984 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
2985 V_tcpstat.tcps_usedssthresh++;
2987 if (metrics.rmx_bandwidth)
2988 tp->snd_bandwidth = metrics.rmx_bandwidth;
2991 * Set the slow-start flight size depending on whether this
2992 * is a local network or not.
2994 * Extend this so we cache the cwnd too and retrieve it here.
2995 * Make cwnd even bigger than RFC3390 suggests but only if we
2996 * have previous experience with the remote host. Be careful
2997 * not make cwnd bigger than remote receive window or our own
2998 * send socket buffer. Maybe put some additional upper bound
2999 * on the retrieved cwnd. Should do incremental updates to
3000 * hostcache when cwnd collapses so next connection doesn't
3001 * overloads the path again.
3003 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3004 * We currently check only in syncache_socket for that.
3006 #define TCP_METRICS_CWND
3007 #ifdef TCP_METRICS_CWND
3008 if (metrics.rmx_cwnd)
3009 tp->snd_cwnd = max(mss,
3010 min(metrics.rmx_cwnd / 2,
3011 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3014 if (V_tcp_do_rfc3390)
3015 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3017 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3018 (!isipv6 && in_localaddr(inp->inp_faddr)))
3020 else if (in_localaddr(inp->inp_faddr))
3022 tp->snd_cwnd = mss * V_ss_fltsz_local;
3024 tp->snd_cwnd = mss * V_ss_fltsz;
3026 /* Check the interface for TSO capabilities. */
3027 if (mtuflags & CSUM_TSO)
3028 tp->t_flags |= TF_TSO;
3032 * Determine the MSS option to send on an outgoing SYN.
3035 tcp_mssopt(struct in_conninfo *inc)
3042 int isipv6 = inc->inc_isipv6 ? 1 : 0;
3045 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3049 mss = V_tcp_v6mssdflt;
3050 maxmtu = tcp_maxmtu6(inc, NULL);
3051 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3052 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3056 mss = V_tcp_mssdflt;
3057 maxmtu = tcp_maxmtu(inc, NULL);
3058 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3059 min_protoh = sizeof(struct tcpiphdr);
3061 if (maxmtu && thcmtu)
3062 mss = min(maxmtu, thcmtu) - min_protoh;
3063 else if (maxmtu || thcmtu)
3064 mss = max(maxmtu, thcmtu) - min_protoh;
3071 * On a partial ack arrives, force the retransmission of the
3072 * next unacknowledged segment. Do not clear tp->t_dupacks.
3073 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3077 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3079 tcp_seq onxt = tp->snd_nxt;
3080 u_long ocwnd = tp->snd_cwnd;
3082 INP_WLOCK_ASSERT(tp->t_inpcb);
3084 tcp_timer_activate(tp, TT_REXMT, 0);
3086 tp->snd_nxt = th->th_ack;
3088 * Set snd_cwnd to one segment beyond acknowledged offset.
3089 * (tp->snd_una has not yet been updated when this function is called.)
3091 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3092 tp->t_flags |= TF_ACKNOW;
3093 (void) tcp_output(tp);
3094 tp->snd_cwnd = ocwnd;
3095 if (SEQ_GT(onxt, tp->snd_nxt))
3098 * Partial window deflation. Relies on fact that tp->snd_una
3101 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3102 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3105 tp->snd_cwnd += tp->t_maxseg;