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>
82 #include <netinet/tcp_debug.h>
86 #include <netipsec/ipsec.h>
87 #include <netipsec/ipsec6.h>
91 #include <netinet6/ipsec.h>
92 #include <netinet6/ipsec6.h>
93 #include <netkey/key.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 static 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)");
132 static int tcp_insecure_rst = 0;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
134 &tcp_insecure_rst, 0,
135 "Follow the old (insecure) criteria for accepting RST packets");
137 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
138 "TCP Segment Reassembly Queue");
140 static int tcp_reass_maxseg = 0;
141 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
142 &tcp_reass_maxseg, 0,
143 "Global maximum number of TCP Segments in Reassembly Queue");
145 int tcp_reass_qsize = 0;
146 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
148 "Global number of TCP Segments currently in Reassembly Queue");
150 static int tcp_reass_maxqlen = 48;
151 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
152 &tcp_reass_maxqlen, 0,
153 "Maximum number of TCP Segments per individual Reassembly Queue");
155 static int tcp_reass_overflows = 0;
156 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
157 &tcp_reass_overflows, 0,
158 "Global number of TCP Segment Reassembly Queue Overflows");
160 int tcp_do_autorcvbuf = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
162 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
164 int tcp_autorcvbuf_inc = 16*1024;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
166 &tcp_autorcvbuf_inc, 0,
167 "Incrementor step size of automatic receive buffer");
169 int tcp_autorcvbuf_max = 256*1024;
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
171 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
173 struct inpcbhead tcb;
174 #define tcb6 tcb /* for KAME src sync over BSD*'s */
175 struct inpcbinfo tcbinfo;
177 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
178 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
179 struct socket *, struct tcpcb *, int, int);
180 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
181 struct tcpcb *, int, int);
182 static void tcp_pulloutofband(struct socket *,
183 struct tcphdr *, struct mbuf *, int);
184 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
186 static void tcp_xmit_timer(struct tcpcb *, int);
187 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
188 static int tcp_timewait(struct inpcb *, struct tcpopt *,
189 struct tcphdr *, struct mbuf *, int);
191 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
193 #define ND6_HINT(tp) \
195 if ((tp) && (tp)->t_inpcb && \
196 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
197 nd6_nud_hint(NULL, NULL, 0); \
204 * Indicate whether this ack should be delayed. We can delay the ack if
205 * - there is no delayed ack timer in progress and
206 * - our last ack wasn't a 0-sized window. We never want to delay
207 * the ack that opens up a 0-sized window and
208 * - delayed acks are enabled or
209 * - this is a half-synchronized T/TCP connection.
211 #define DELAY_ACK(tp) \
212 ((!tcp_timer_active(tp, TT_DELACK) && \
213 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
214 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
216 /* Initialize TCP reassembly queue */
218 tcp_reass_zone_change(void *tag)
221 tcp_reass_maxseg = nmbclusters / 16;
222 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
225 uma_zone_t tcp_reass_zone;
229 tcp_reass_maxseg = nmbclusters / 16;
230 TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
232 tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
233 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
234 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
235 EVENTHANDLER_REGISTER(nmbclusters_change,
236 tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
240 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
243 struct tseg_qent *p = NULL;
244 struct tseg_qent *nq;
245 struct tseg_qent *te = NULL;
246 struct socket *so = tp->t_inpcb->inp_socket;
249 INP_LOCK_ASSERT(tp->t_inpcb);
252 * XXX: tcp_reass() is rather inefficient with its data structures
253 * and should be rewritten (see NetBSD for optimizations). While
254 * doing that it should move to its own file tcp_reass.c.
258 * Call with th==NULL after become established to
259 * force pre-ESTABLISHED data up to user socket.
265 * Limit the number of segments in the reassembly queue to prevent
266 * holding on to too many segments (and thus running out of mbufs).
267 * Make sure to let the missing segment through which caused this
268 * queue. Always keep one global queue entry spare to be able to
269 * process the missing segment.
271 if (th->th_seq != tp->rcv_nxt &&
272 (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
273 tp->t_segqlen >= tcp_reass_maxqlen)) {
274 tcp_reass_overflows++;
275 tcpstat.tcps_rcvmemdrop++;
282 * Allocate a new queue entry. If we can't, or hit the zone limit
285 te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
287 tcpstat.tcps_rcvmemdrop++;
296 * Find a segment which begins after this one does.
298 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
299 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
305 * If there is a preceding segment, it may provide some of
306 * our data already. If so, drop the data from the incoming
307 * segment. If it provides all of our data, drop us.
311 /* conversion to int (in i) handles seq wraparound */
312 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
315 tcpstat.tcps_rcvduppack++;
316 tcpstat.tcps_rcvdupbyte += *tlenp;
318 uma_zfree(tcp_reass_zone, te);
322 * Try to present any queued data
323 * at the left window edge to the user.
324 * This is needed after the 3-WHS
327 goto present; /* ??? */
334 tcpstat.tcps_rcvoopack++;
335 tcpstat.tcps_rcvoobyte += *tlenp;
338 * While we overlap succeeding segments trim them or,
339 * if they are completely covered, dequeue them.
342 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
345 if (i < q->tqe_len) {
346 q->tqe_th->th_seq += i;
352 nq = LIST_NEXT(q, tqe_q);
353 LIST_REMOVE(q, tqe_q);
355 uma_zfree(tcp_reass_zone, q);
361 /* Insert the new segment queue entry into place. */
364 te->tqe_len = *tlenp;
367 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
369 LIST_INSERT_AFTER(p, te, tqe_q);
374 * Present data to user, advancing rcv_nxt through
375 * completed sequence space.
377 if (!TCPS_HAVEESTABLISHED(tp->t_state))
379 q = LIST_FIRST(&tp->t_segq);
380 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
382 SOCKBUF_LOCK(&so->so_rcv);
384 tp->rcv_nxt += q->tqe_len;
385 flags = q->tqe_th->th_flags & TH_FIN;
386 nq = LIST_NEXT(q, tqe_q);
387 LIST_REMOVE(q, tqe_q);
388 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
391 sbappendstream_locked(&so->so_rcv, q->tqe_m);
392 uma_zfree(tcp_reass_zone, q);
396 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
398 sorwakeup_locked(so);
403 * TCP input routine, follows pages 65-76 of the
404 * protocol specification dated September, 1981 very closely.
408 tcp6_input(struct mbuf **mp, int *offp, int proto)
410 struct mbuf *m = *mp;
411 struct in6_ifaddr *ia6;
413 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
416 * draft-itojun-ipv6-tcp-to-anycast
417 * better place to put this in?
419 ia6 = ip6_getdstifaddr(m);
420 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
423 ip6 = mtod(m, struct ip6_hdr *);
424 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
425 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
435 tcp_input(struct mbuf *m, int off0)
438 struct ip *ip = NULL;
440 struct inpcb *inp = NULL;
441 struct tcpcb *tp = NULL;
442 struct socket *so = NULL;
448 int rstreason = 0; /* For badport_bandlim accounting purposes */
449 #ifdef IPFIREWALL_FORWARD
450 struct m_tag *fwd_tag;
453 struct ip6_hdr *ip6 = NULL;
455 char ip6buf[INET6_ADDRSTRLEN];
457 const int isipv6 = 0;
459 struct tcpopt to; /* options in this segment */
463 * The size of tcp_saveipgen must be the size of the max ip header,
466 u_char tcp_saveipgen[IP6_HDR_LEN];
467 struct tcphdr tcp_savetcp;
472 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
476 tcpstat.tcps_rcvtotal++;
480 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
481 ip6 = mtod(m, struct ip6_hdr *);
482 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
483 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
484 tcpstat.tcps_rcvbadsum++;
487 th = (struct tcphdr *)((caddr_t)ip6 + off0);
490 * Be proactive about unspecified IPv6 address in source.
491 * As we use all-zero to indicate unbounded/unconnected pcb,
492 * unspecified IPv6 address can be used to confuse us.
494 * Note that packets with unspecified IPv6 destination is
495 * already dropped in ip6_input.
497 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
502 th = NULL; /* XXX: avoid compiler warning */
506 * Get IP and TCP header together in first mbuf.
507 * Note: IP leaves IP header in first mbuf.
509 if (off0 > sizeof (struct ip)) {
510 ip_stripoptions(m, (struct mbuf *)0);
511 off0 = sizeof(struct ip);
513 if (m->m_len < sizeof (struct tcpiphdr)) {
514 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
516 tcpstat.tcps_rcvshort++;
520 ip = mtod(m, struct ip *);
521 ipov = (struct ipovly *)ip;
522 th = (struct tcphdr *)((caddr_t)ip + off0);
525 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
526 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
527 th->th_sum = m->m_pkthdr.csum_data;
529 th->th_sum = in_pseudo(ip->ip_src.s_addr,
531 htonl(m->m_pkthdr.csum_data +
534 th->th_sum ^= 0xffff;
536 ipov->ih_len = (u_short)tlen;
537 ipov->ih_len = htons(ipov->ih_len);
541 * Checksum extended TCP header and data.
543 len = sizeof (struct ip) + tlen;
544 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
545 ipov->ih_len = (u_short)tlen;
546 ipov->ih_len = htons(ipov->ih_len);
547 th->th_sum = in_cksum(m, len);
550 tcpstat.tcps_rcvbadsum++;
553 /* Re-initialization for later version check */
554 ip->ip_v = IPVERSION;
558 * Check that TCP offset makes sense,
559 * pull out TCP options and adjust length. XXX
561 off = th->th_off << 2;
562 if (off < sizeof (struct tcphdr) || off > tlen) {
563 tcpstat.tcps_rcvbadoff++;
566 tlen -= off; /* tlen is used instead of ti->ti_len */
567 if (off > sizeof (struct tcphdr)) {
570 IP6_EXTHDR_CHECK(m, off0, off, );
571 ip6 = mtod(m, struct ip6_hdr *);
572 th = (struct tcphdr *)((caddr_t)ip6 + off0);
575 if (m->m_len < sizeof(struct ip) + off) {
576 if ((m = m_pullup(m, sizeof (struct ip) + off))
578 tcpstat.tcps_rcvshort++;
581 ip = mtod(m, struct ip *);
582 ipov = (struct ipovly *)ip;
583 th = (struct tcphdr *)((caddr_t)ip + off0);
586 optlen = off - sizeof (struct tcphdr);
587 optp = (u_char *)(th + 1);
589 thflags = th->th_flags;
592 * If the drop_synfin option is enabled, drop all packets with
593 * both the SYN and FIN bits set. This prevents e.g. nmap from
594 * identifying the TCP/IP stack.
596 * This is a violation of the TCP specification.
598 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
602 * Convert TCP protocol specific fields to host format.
604 th->th_seq = ntohl(th->th_seq);
605 th->th_ack = ntohl(th->th_ack);
606 th->th_win = ntohs(th->th_win);
607 th->th_urp = ntohs(th->th_urp);
610 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
612 drop_hdrlen = off0 + off;
615 * Locate pcb for segment.
617 INP_INFO_WLOCK(&tcbinfo);
619 INP_INFO_WLOCK_ASSERT(&tcbinfo);
620 #ifdef IPFIREWALL_FORWARD
621 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
622 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
624 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
625 struct sockaddr_in *next_hop;
627 next_hop = (struct sockaddr_in *)(fwd_tag+1);
629 * Transparently forwarded. Pretend to be the destination.
630 * already got one like this?
632 inp = in_pcblookup_hash(&tcbinfo,
633 ip->ip_src, th->th_sport,
634 ip->ip_dst, th->th_dport,
635 0, m->m_pkthdr.rcvif);
637 /* It's new. Try to find the ambushing socket. */
638 inp = in_pcblookup_hash(&tcbinfo,
639 ip->ip_src, th->th_sport,
642 ntohs(next_hop->sin_port) :
647 /* Remove the tag from the packet. We don't need it anymore. */
648 m_tag_delete(m, fwd_tag);
650 #endif /* IPFIREWALL_FORWARD */
654 inp = in6_pcblookup_hash(&tcbinfo,
655 &ip6->ip6_src, th->th_sport,
656 &ip6->ip6_dst, th->th_dport,
661 inp = in_pcblookup_hash(&tcbinfo,
662 ip->ip_src, th->th_sport,
663 ip->ip_dst, th->th_dport,
668 #if defined(IPSEC) || defined(FAST_IPSEC)
670 if (isipv6 && inp != NULL && ipsec6_in_reject(m, inp)) {
672 ipsec6stat.in_polvio++;
677 if (inp != NULL && ipsec4_in_reject(m, inp)) {
679 ipsecstat.in_polvio++;
683 #endif /*IPSEC || FAST_IPSEC*/
686 * If the INPCB does not exist then all data in the incoming
687 * segment is discarded and an appropriate RST is sent back.
691 * Log communication attempts to ports that are not
694 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
695 tcp_log_in_vain == 2) {
697 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
699 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
703 ip6_sprintf(ip6buf, &ip6->ip6_dst));
707 ip6_sprintf(ip6buf, &ip6->ip6_src));
712 strcpy(dbuf, inet_ntoa(ip->ip_dst));
713 strcpy(sbuf, inet_ntoa(ip->ip_src));
716 "Connection attempt to TCP %s:%d "
717 "from %s:%d flags:0x%02x\n",
718 dbuf, ntohs(th->th_dport), sbuf,
719 ntohs(th->th_sport), thflags);
722 * When blackholing do not respond with a RST but
723 * completely ignore the segment and drop it.
725 if ((blackhole == 1 && (thflags & TH_SYN)) ||
729 rstreason = BANDLIM_RST_CLOSEDPORT;
734 /* Check the minimum TTL for socket. */
735 if (inp->inp_ip_minttl != 0) {
737 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
741 if (inp->inp_ip_minttl > ip->ip_ttl)
746 * A previous connection in TIMEWAIT state is supposed to catch
747 * stray or duplicate segments arriving late. If this segment
748 * was a legitimate new connection attempt the old INPCB gets
749 * removed and we can try again to find a listening socket.
751 if (inp->inp_vflag & INP_TIMEWAIT) {
752 if (thflags & TH_SYN)
753 tcp_dooptions(&to, optp, optlen, TO_SYN);
754 /* NB: tcp_timewait unlocks the INP and frees the mbuf. */
755 if (tcp_timewait(inp, &to, th, m, tlen))
757 INP_INFO_WUNLOCK(&tcbinfo);
761 * The TCPCB may no longer exist if the connection is winding
762 * down or it is in the CLOSED state. Either way we drop the
763 * segment and send an appropriate response.
767 rstreason = BANDLIM_RST_CLOSEDPORT;
770 if (tp->t_state == TCPS_CLOSED)
771 goto dropunlock; /* XXX: dropwithreset??? */
774 INP_LOCK_ASSERT(inp);
775 if (mac_check_inpcb_deliver(inp, m))
778 so = inp->inp_socket;
779 KASSERT(so != NULL, ("%s: so == NULL", __func__));
781 if (so->so_options & SO_DEBUG) {
782 ostate = tp->t_state;
784 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
786 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
791 * When the socket is accepting connections (the INPCB is in LISTEN
792 * state) we look into the SYN cache if this is a new connection
793 * attempt or the completion of a previous one.
795 if (so->so_options & SO_ACCEPTCONN) {
796 struct in_conninfo inc;
798 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
799 "tp not listening", __func__));
801 bzero(&inc, sizeof(inc));
802 inc.inc_isipv6 = isipv6;
805 inc.inc6_faddr = ip6->ip6_src;
806 inc.inc6_laddr = ip6->ip6_dst;
810 inc.inc_faddr = ip->ip_src;
811 inc.inc_laddr = ip->ip_dst;
813 inc.inc_fport = th->th_sport;
814 inc.inc_lport = th->th_dport;
817 * If the state is LISTEN then ignore segment if it contains
818 * a RST. If the segment contains an ACK then it is bad and
819 * send a RST. If it does not contain a SYN then it is not
820 * interesting; drop it.
822 * If the state is SYN_RECEIVED (syncache) and seg contains
823 * an ACK, but not for our SYN/ACK, send a RST. If the seg
824 * contains a RST, check the sequence number to see if it
825 * is a valid reset segment.
827 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
828 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
830 * Parse the TCP options here because
831 * syncookies need access to the reflected
834 tcp_dooptions(&to, optp, optlen, 0);
836 * NB: syncache_expand() doesn't unlock
837 * inp and tcpinfo locks.
839 if (!syncache_expand(&inc, &to, th, &so, m)) {
841 * No syncache entry or ACK was not
842 * for our SYN/ACK. Send a RST.
844 rstreason = BANDLIM_RST_OPENPORT;
849 * We completed the 3-way handshake
850 * but could not allocate a socket
851 * either due to memory shortage,
852 * listen queue length limits or
853 * global socket limits.
855 rstreason = BANDLIM_UNLIMITED;
859 * Socket is created in state SYN_RECEIVED.
860 * Continue processing segment.
862 INP_UNLOCK(inp); /* listen socket */
864 INP_LOCK(inp); /* new connection */
867 * Process the segment and the data it
868 * contains. tcp_do_segment() consumes
869 * the mbuf chain and unlocks the inpcb.
871 tcp_do_segment(m, th, so, tp, drop_hdrlen,
873 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
876 if (thflags & TH_RST) {
877 syncache_chkrst(&inc, th);
880 if (thflags & TH_ACK) {
881 syncache_badack(&inc);
882 tcpstat.tcps_badsyn++;
883 rstreason = BANDLIM_RST_OPENPORT;
890 * Segment's flags are (SYN) or (SYN|FIN).
894 * If deprecated address is forbidden,
895 * we do not accept SYN to deprecated interface
896 * address to prevent any new inbound connection from
897 * getting established.
898 * When we do not accept SYN, we send a TCP RST,
899 * with deprecated source address (instead of dropping
900 * it). We compromise it as it is much better for peer
901 * to send a RST, and RST will be the final packet
904 * If we do not forbid deprecated addresses, we accept
905 * the SYN packet. RFC2462 does not suggest dropping
907 * If we decipher RFC2462 5.5.4, it says like this:
908 * 1. use of deprecated addr with existing
909 * communication is okay - "SHOULD continue to be
911 * 2. use of it with new communication:
912 * (2a) "SHOULD NOT be used if alternate address
913 * with sufficient scope is available"
914 * (2b) nothing mentioned otherwise.
915 * Here we fall into (2b) case as we have no choice in
916 * our source address selection - we must obey the peer.
918 * The wording in RFC2462 is confusing, and there are
919 * multiple description text for deprecated address
920 * handling - worse, they are not exactly the same.
921 * I believe 5.5.4 is the best one, so we follow 5.5.4.
923 if (isipv6 && !ip6_use_deprecated) {
924 struct in6_ifaddr *ia6;
926 if ((ia6 = ip6_getdstifaddr(m)) &&
927 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
928 rstreason = BANDLIM_RST_OPENPORT;
934 * Basic sanity checks on incoming SYN requests:
936 * Don't bother responding if the destination was a
937 * broadcast according to RFC1122 4.2.3.10, p. 104.
939 * If it is from this socket, drop it, it must be forged.
941 * Note that it is quite possible to receive unicast
942 * link-layer packets with a broadcast IP address. Use
943 * in_broadcast() to find them.
945 if (m->m_flags & (M_BCAST|M_MCAST))
949 if (th->th_dport == th->th_sport &&
950 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src))
952 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
953 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
957 if (th->th_dport == th->th_sport &&
958 ip->ip_dst.s_addr == ip->ip_src.s_addr)
960 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
961 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
962 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
963 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
967 * SYN appears to be valid. Create compressed TCP state
971 if (so->so_options & SO_DEBUG)
972 tcp_trace(TA_INPUT, ostate, tp,
973 (void *)tcp_saveipgen, &tcp_savetcp, 0);
975 tcp_dooptions(&to, optp, optlen, TO_SYN);
976 syncache_add(&inc, &to, th, inp, &so, m);
978 * Entry added to syncache and mbuf consumed.
979 * Everything unlocked already by syncache_add().
985 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or late
986 * state. tcp_do_segment() always consumes the mbuf chain, unlocks the
987 * inpcb, and unlocks the pcbinfo.
989 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
990 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
994 INP_INFO_WLOCK_ASSERT(&tcbinfo);
995 tcp_dropwithreset(m, th, tp, tlen, rstreason);
996 m = NULL; /* mbuf chain got consumed. */
998 INP_INFO_WLOCK_ASSERT(&tcbinfo);
1001 INP_INFO_WUNLOCK(&tcbinfo);
1003 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
1010 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1011 struct tcpcb *tp, int drop_hdrlen, int tlen)
1013 int thflags, acked, ourfinisacked, needoutput = 0;
1015 int rstreason, todrop, win;
1021 * The size of tcp_saveipgen must be the size of the max ip header,
1024 u_char tcp_saveipgen[IP6_HDR_LEN];
1025 struct tcphdr tcp_savetcp;
1028 thflags = th->th_flags;
1030 INP_INFO_WLOCK_ASSERT(&tcbinfo);
1031 INP_LOCK_ASSERT(tp->t_inpcb);
1032 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1034 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1038 * Segment received on connection.
1039 * Reset idle time and keep-alive timer.
1041 tp->t_rcvtime = ticks;
1042 if (TCPS_HAVEESTABLISHED(tp->t_state))
1043 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1046 * Unscale the window into a 32-bit value.
1047 * This value is bogus for the TCPS_SYN_SENT state
1048 * and is overwritten later.
1050 tiwin = th->th_win << tp->snd_scale;
1053 * Parse options on any incoming segment.
1055 tcp_dooptions(&to, (u_char *)(th + 1),
1056 (th->th_off << 2) - sizeof(struct tcphdr),
1057 (thflags & TH_SYN) ? TO_SYN : 0);
1060 * If echoed timestamp is later than the current time,
1061 * fall back to non RFC1323 RTT calculation. Normalize
1062 * timestamp if syncookies were used when this connection
1065 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1066 to.to_tsecr -= tp->ts_offset;
1067 if (TSTMP_GT(to.to_tsecr, ticks))
1072 * Process options only when we get SYN/ACK back. The SYN case
1073 * for incoming connections is handled in tcp_syncache.
1074 * XXX this is traditional behavior, may need to be cleaned up.
1076 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1077 if ((to.to_flags & TOF_SCALE) &&
1078 (tp->t_flags & TF_REQ_SCALE)) {
1079 tp->t_flags |= TF_RCVD_SCALE;
1080 tp->snd_scale = to.to_wscale;
1081 tp->snd_wnd = th->th_win << tp->snd_scale;
1082 tiwin = tp->snd_wnd;
1084 if (to.to_flags & TOF_TS) {
1085 tp->t_flags |= TF_RCVD_TSTMP;
1086 tp->ts_recent = to.to_tsval;
1087 tp->ts_recent_age = ticks;
1089 /* Initial send window, already scaled. */
1090 tp->snd_wnd = th->th_win;
1091 if (to.to_flags & TOF_MSS)
1092 tcp_mss(tp, to.to_mss);
1093 if (tp->sack_enable) {
1094 if (!(to.to_flags & TOF_SACKPERM))
1095 tp->sack_enable = 0;
1097 tp->t_flags |= TF_SACK_PERMIT;
1103 * Header prediction: check for the two common cases
1104 * of a uni-directional data xfer. If the packet has
1105 * no control flags, is in-sequence, the window didn't
1106 * change and we're not retransmitting, it's a
1107 * candidate. If the length is zero and the ack moved
1108 * forward, we're the sender side of the xfer. Just
1109 * free the data acked & wake any higher level process
1110 * that was blocked waiting for space. If the length
1111 * is non-zero and the ack didn't move, we're the
1112 * receiver side. If we're getting packets in-order
1113 * (the reassembly queue is empty), add the data to
1114 * the socket buffer and note that we need a delayed ack.
1115 * Make sure that the hidden state-flags are also off.
1116 * Since we check for TCPS_ESTABLISHED above, it can only
1119 if (tp->t_state == TCPS_ESTABLISHED &&
1120 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1121 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1122 ((to.to_flags & TOF_TS) == 0 ||
1123 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1124 th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd &&
1125 tp->snd_nxt == tp->snd_max) {
1128 * If last ACK falls within this segment's sequence numbers,
1129 * record the timestamp.
1130 * NOTE that the test is modified according to the latest
1131 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1133 if ((to.to_flags & TOF_TS) != 0 &&
1134 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1135 tp->ts_recent_age = ticks;
1136 tp->ts_recent = to.to_tsval;
1140 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1141 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1142 tp->snd_cwnd >= tp->snd_wnd &&
1143 ((!tcp_do_newreno && !tp->sack_enable &&
1144 tp->t_dupacks < tcprexmtthresh) ||
1145 ((tcp_do_newreno || tp->sack_enable) &&
1146 !IN_FASTRECOVERY(tp) &&
1147 (to.to_flags & TOF_SACK) == 0 &&
1148 TAILQ_EMPTY(&tp->snd_holes)))) {
1150 ("%s: headlocked", __func__));
1151 INP_INFO_WUNLOCK(&tcbinfo);
1154 * this is a pure ack for outstanding data.
1156 ++tcpstat.tcps_predack;
1158 * "bad retransmit" recovery
1160 if (tp->t_rxtshift == 1 &&
1161 ticks < tp->t_badrxtwin) {
1162 ++tcpstat.tcps_sndrexmitbad;
1163 tp->snd_cwnd = tp->snd_cwnd_prev;
1165 tp->snd_ssthresh_prev;
1166 tp->snd_recover = tp->snd_recover_prev;
1167 if (tp->t_flags & TF_WASFRECOVERY)
1168 ENTER_FASTRECOVERY(tp);
1169 tp->snd_nxt = tp->snd_max;
1170 tp->t_badrxtwin = 0;
1174 * Recalculate the transmit timer / rtt.
1176 * Some boxes send broken timestamp replies
1177 * during the SYN+ACK phase, ignore
1178 * timestamps of 0 or we could calculate a
1179 * huge RTT and blow up the retransmit timer.
1181 if ((to.to_flags & TOF_TS) != 0 &&
1183 if (!tp->t_rttlow ||
1184 tp->t_rttlow > ticks - to.to_tsecr)
1185 tp->t_rttlow = ticks - to.to_tsecr;
1187 ticks - to.to_tsecr + 1);
1188 } else if (tp->t_rtttime &&
1189 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1190 if (!tp->t_rttlow ||
1191 tp->t_rttlow > ticks - tp->t_rtttime)
1192 tp->t_rttlow = ticks - tp->t_rtttime;
1194 ticks - tp->t_rtttime);
1196 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1197 acked = th->th_ack - tp->snd_una;
1198 tcpstat.tcps_rcvackpack++;
1199 tcpstat.tcps_rcvackbyte += acked;
1200 sbdrop(&so->so_snd, acked);
1201 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1202 SEQ_LEQ(th->th_ack, tp->snd_recover))
1203 tp->snd_recover = th->th_ack - 1;
1204 tp->snd_una = th->th_ack;
1206 * pull snd_wl2 up to prevent seq wrap relative
1209 tp->snd_wl2 = th->th_ack;
1212 ND6_HINT(tp); /* some progress has been done */
1215 * If all outstanding data are acked, stop
1216 * retransmit timer, otherwise restart timer
1217 * using current (possibly backed-off) value.
1218 * If process is waiting for space,
1219 * wakeup/selwakeup/signal. If data
1220 * are ready to send, let tcp_output
1221 * decide between more output or persist.
1224 if (so->so_options & SO_DEBUG)
1225 tcp_trace(TA_INPUT, ostate, tp,
1226 (void *)tcp_saveipgen,
1230 if (tp->snd_una == tp->snd_max)
1231 tcp_timer_activate(tp, TT_REXMT, 0);
1232 else if (!tcp_timer_active(tp, TT_PERSIST))
1233 tcp_timer_activate(tp, TT_REXMT,
1237 if (so->so_snd.sb_cc)
1238 (void) tcp_output(tp);
1241 } else if (th->th_ack == tp->snd_una &&
1242 LIST_EMPTY(&tp->t_segq) &&
1243 tlen <= sbspace(&so->so_rcv)) {
1244 int newsize = 0; /* automatic sockbuf scaling */
1246 KASSERT(headlocked, ("%s: headlocked", __func__));
1247 INP_INFO_WUNLOCK(&tcbinfo);
1250 * this is a pure, in-sequence data packet
1251 * with nothing on the reassembly queue and
1252 * we have enough buffer space to take it.
1254 /* Clean receiver SACK report if present */
1255 if (tp->sack_enable && tp->rcv_numsacks)
1256 tcp_clean_sackreport(tp);
1257 ++tcpstat.tcps_preddat;
1258 tp->rcv_nxt += tlen;
1260 * Pull snd_wl1 up to prevent seq wrap relative to
1263 tp->snd_wl1 = th->th_seq;
1265 * Pull rcv_up up to prevent seq wrap relative to
1268 tp->rcv_up = tp->rcv_nxt;
1269 tcpstat.tcps_rcvpack++;
1270 tcpstat.tcps_rcvbyte += tlen;
1271 ND6_HINT(tp); /* some progress has been done */
1273 if (so->so_options & SO_DEBUG)
1274 tcp_trace(TA_INPUT, ostate, tp,
1275 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1278 * Automatic sizing of receive socket buffer. Often the send
1279 * buffer size is not optimally adjusted to the actual network
1280 * conditions at hand (delay bandwidth product). Setting the
1281 * buffer size too small limits throughput on links with high
1282 * bandwidth and high delay (eg. trans-continental/oceanic links).
1284 * On the receive side the socket buffer memory is only rarely
1285 * used to any significant extent. This allows us to be much
1286 * more aggressive in scaling the receive socket buffer. For
1287 * the case that the buffer space is actually used to a large
1288 * extent and we run out of kernel memory we can simply drop
1289 * the new segments; TCP on the sender will just retransmit it
1290 * later. Setting the buffer size too big may only consume too
1291 * much kernel memory if the application doesn't read() from
1292 * the socket or packet loss or reordering makes use of the
1295 * The criteria to step up the receive buffer one notch are:
1296 * 1. the number of bytes received during the time it takes
1297 * one timestamp to be reflected back to us (the RTT);
1298 * 2. received bytes per RTT is within seven eighth of the
1299 * current socket buffer size;
1300 * 3. receive buffer size has not hit maximal automatic size;
1302 * This algorithm does one step per RTT at most and only if
1303 * we receive a bulk stream w/o packet losses or reorderings.
1304 * Shrinking the buffer during idle times is not necessary as
1305 * it doesn't consume any memory when idle.
1307 * TODO: Only step up if the application is actually serving
1308 * the buffer to better manage the socket buffer resources.
1310 if (tcp_do_autorcvbuf &&
1312 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1313 if (to.to_tsecr > tp->rfbuf_ts &&
1314 to.to_tsecr - tp->rfbuf_ts < hz) {
1316 (so->so_rcv.sb_hiwat / 8 * 7) &&
1317 so->so_rcv.sb_hiwat <
1318 tcp_autorcvbuf_max) {
1320 min(so->so_rcv.sb_hiwat +
1322 tcp_autorcvbuf_max);
1324 /* Start over with next RTT. */
1328 tp->rfbuf_cnt += tlen; /* add up */
1331 /* Add data to socket buffer. */
1332 SOCKBUF_LOCK(&so->so_rcv);
1333 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1337 * Set new socket buffer size.
1338 * Give up when limit is reached.
1341 if (!sbreserve_locked(&so->so_rcv,
1342 newsize, so, curthread))
1343 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1344 m_adj(m, drop_hdrlen); /* delayed header drop */
1345 sbappendstream_locked(&so->so_rcv, m);
1347 sorwakeup_locked(so);
1348 if (DELAY_ACK(tp)) {
1349 tp->t_flags |= TF_DELACK;
1351 tp->t_flags |= TF_ACKNOW;
1359 * Calculate amount of space in receive window,
1360 * and then do TCP input processing.
1361 * Receive window is amount of space in rcv queue,
1362 * but not less than advertised window.
1364 win = sbspace(&so->so_rcv);
1367 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1369 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1373 switch (tp->t_state) {
1376 * If the state is SYN_RECEIVED:
1377 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1379 case TCPS_SYN_RECEIVED:
1380 if ((thflags & TH_ACK) &&
1381 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1382 SEQ_GT(th->th_ack, tp->snd_max))) {
1383 rstreason = BANDLIM_RST_OPENPORT;
1389 * If the state is SYN_SENT:
1390 * if seg contains an ACK, but not for our SYN, drop the input.
1391 * if seg contains a RST, then drop the connection.
1392 * if seg does not contain SYN, then drop it.
1393 * Otherwise this is an acceptable SYN segment
1394 * initialize tp->rcv_nxt and tp->irs
1395 * if seg contains ack then advance tp->snd_una
1396 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1397 * arrange for segment to be acked (eventually)
1398 * continue processing rest of data/controls, beginning with URG
1401 if ((thflags & TH_ACK) &&
1402 (SEQ_LEQ(th->th_ack, tp->iss) ||
1403 SEQ_GT(th->th_ack, tp->snd_max))) {
1404 rstreason = BANDLIM_UNLIMITED;
1407 if (thflags & TH_RST) {
1408 if (thflags & TH_ACK) {
1409 KASSERT(headlocked, ("%s: after_listen: "
1410 "tcp_drop.2: head not locked", __func__));
1411 tp = tcp_drop(tp, ECONNREFUSED);
1415 if ((thflags & TH_SYN) == 0)
1418 tp->irs = th->th_seq;
1420 if (thflags & TH_ACK) {
1421 tcpstat.tcps_connects++;
1425 mac_set_socket_peer_from_mbuf(m, so);
1428 /* Do window scaling on this connection? */
1429 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1430 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1431 tp->rcv_scale = tp->request_r_scale;
1433 tp->rcv_adv += tp->rcv_wnd;
1434 tp->snd_una++; /* SYN is acked */
1436 * If there's data, delay ACK; if there's also a FIN
1437 * ACKNOW will be turned on later.
1439 if (DELAY_ACK(tp) && tlen != 0)
1440 tcp_timer_activate(tp, TT_DELACK,
1443 tp->t_flags |= TF_ACKNOW;
1445 * Received <SYN,ACK> in SYN_SENT[*] state.
1447 * SYN_SENT --> ESTABLISHED
1448 * SYN_SENT* --> FIN_WAIT_1
1450 tp->t_starttime = ticks;
1451 if (tp->t_flags & TF_NEEDFIN) {
1452 tp->t_state = TCPS_FIN_WAIT_1;
1453 tp->t_flags &= ~TF_NEEDFIN;
1456 tp->t_state = TCPS_ESTABLISHED;
1457 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1461 * Received initial SYN in SYN-SENT[*] state =>
1462 * simultaneous open. If segment contains CC option
1463 * and there is a cached CC, apply TAO test.
1464 * If it succeeds, connection is * half-synchronized.
1465 * Otherwise, do 3-way handshake:
1466 * SYN-SENT -> SYN-RECEIVED
1467 * SYN-SENT* -> SYN-RECEIVED*
1468 * If there was no CC option, clear cached CC value.
1470 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1471 tcp_timer_activate(tp, TT_REXMT, 0);
1472 tp->t_state = TCPS_SYN_RECEIVED;
1475 KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1477 INP_LOCK_ASSERT(tp->t_inpcb);
1480 * Advance th->th_seq to correspond to first data byte.
1481 * If data, trim to stay within window,
1482 * dropping FIN if necessary.
1485 if (tlen > tp->rcv_wnd) {
1486 todrop = tlen - tp->rcv_wnd;
1490 tcpstat.tcps_rcvpackafterwin++;
1491 tcpstat.tcps_rcvbyteafterwin += todrop;
1493 tp->snd_wl1 = th->th_seq - 1;
1494 tp->rcv_up = th->th_seq;
1496 * Client side of transaction: already sent SYN and data.
1497 * If the remote host used T/TCP to validate the SYN,
1498 * our data will be ACK'd; if so, enter normal data segment
1499 * processing in the middle of step 5, ack processing.
1500 * Otherwise, goto step 6.
1502 if (thflags & TH_ACK)
1508 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1509 * do normal processing.
1511 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1515 break; /* continue normal processing */
1519 * States other than LISTEN or SYN_SENT.
1520 * First check the RST flag and sequence number since reset segments
1521 * are exempt from the timestamp and connection count tests. This
1522 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1523 * below which allowed reset segments in half the sequence space
1524 * to fall though and be processed (which gives forged reset
1525 * segments with a random sequence number a 50 percent chance of
1526 * killing a connection).
1527 * Then check timestamp, if present.
1528 * Then check the connection count, if present.
1529 * Then check that at least some bytes of segment are within
1530 * receive window. If segment begins before rcv_nxt,
1531 * drop leading data (and SYN); if nothing left, just ack.
1534 * If the RST bit is set, check the sequence number to see
1535 * if this is a valid reset segment.
1537 * In all states except SYN-SENT, all reset (RST) segments
1538 * are validated by checking their SEQ-fields. A reset is
1539 * valid if its sequence number is in the window.
1540 * Note: this does not take into account delayed ACKs, so
1541 * we should test against last_ack_sent instead of rcv_nxt.
1542 * The sequence number in the reset segment is normally an
1543 * echo of our outgoing acknowlegement numbers, but some hosts
1544 * send a reset with the sequence number at the rightmost edge
1545 * of our receive window, and we have to handle this case.
1546 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1547 * that brute force RST attacks are possible. To combat this,
1548 * we use a much stricter check while in the ESTABLISHED state,
1549 * only accepting RSTs where the sequence number is equal to
1550 * last_ack_sent. In all other states (the states in which a
1551 * RST is more likely), the more permissive check is used.
1552 * If we have multiple segments in flight, the intial reset
1553 * segment sequence numbers will be to the left of last_ack_sent,
1554 * but they will eventually catch up.
1555 * In any case, it never made sense to trim reset segments to
1556 * fit the receive window since RFC 1122 says:
1557 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1559 * A TCP SHOULD allow a received RST segment to include data.
1562 * It has been suggested that a RST segment could contain
1563 * ASCII text that encoded and explained the cause of the
1564 * RST. No standard has yet been established for such
1567 * If the reset segment passes the sequence number test examine
1569 * SYN_RECEIVED STATE:
1570 * If passive open, return to LISTEN state.
1571 * If active open, inform user that connection was refused.
1572 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1573 * Inform user that connection was reset, and close tcb.
1574 * CLOSING, LAST_ACK STATES:
1577 * Drop the segment - see Stevens, vol. 2, p. 964 and
1580 if (thflags & TH_RST) {
1581 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1582 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1583 switch (tp->t_state) {
1585 case TCPS_SYN_RECEIVED:
1586 so->so_error = ECONNREFUSED;
1589 case TCPS_ESTABLISHED:
1590 if (tcp_insecure_rst == 0 &&
1591 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1592 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1593 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1594 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1595 tcpstat.tcps_badrst++;
1598 case TCPS_FIN_WAIT_1:
1599 case TCPS_FIN_WAIT_2:
1600 case TCPS_CLOSE_WAIT:
1601 so->so_error = ECONNRESET;
1603 tp->t_state = TCPS_CLOSED;
1604 tcpstat.tcps_drops++;
1605 KASSERT(headlocked, ("%s: trimthenstep6: "
1606 "tcp_close: head not locked", __func__));
1612 KASSERT(headlocked, ("%s: trimthenstep6: "
1613 "tcp_close.2: head not locked", __func__));
1622 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1623 * and it's less than ts_recent, drop it.
1625 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1626 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1628 /* Check to see if ts_recent is over 24 days old. */
1629 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1631 * Invalidate ts_recent. If this segment updates
1632 * ts_recent, the age will be reset later and ts_recent
1633 * will get a valid value. If it does not, setting
1634 * ts_recent to zero will at least satisfy the
1635 * requirement that zero be placed in the timestamp
1636 * echo reply when ts_recent isn't valid. The
1637 * age isn't reset until we get a valid ts_recent
1638 * because we don't want out-of-order segments to be
1639 * dropped when ts_recent is old.
1643 tcpstat.tcps_rcvduppack++;
1644 tcpstat.tcps_rcvdupbyte += tlen;
1645 tcpstat.tcps_pawsdrop++;
1653 * In the SYN-RECEIVED state, validate that the packet belongs to
1654 * this connection before trimming the data to fit the receive
1655 * window. Check the sequence number versus IRS since we know
1656 * the sequence numbers haven't wrapped. This is a partial fix
1657 * for the "LAND" DoS attack.
1659 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1660 rstreason = BANDLIM_RST_OPENPORT;
1664 todrop = tp->rcv_nxt - th->th_seq;
1666 if (thflags & TH_SYN) {
1676 * Following if statement from Stevens, vol. 2, p. 960.
1679 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1681 * Any valid FIN must be to the left of the window.
1682 * At this point the FIN must be a duplicate or out
1683 * of sequence; drop it.
1688 * Send an ACK to resynchronize and drop any data.
1689 * But keep on processing for RST or ACK.
1691 tp->t_flags |= TF_ACKNOW;
1693 tcpstat.tcps_rcvduppack++;
1694 tcpstat.tcps_rcvdupbyte += todrop;
1696 tcpstat.tcps_rcvpartduppack++;
1697 tcpstat.tcps_rcvpartdupbyte += todrop;
1699 drop_hdrlen += todrop; /* drop from the top afterwards */
1700 th->th_seq += todrop;
1702 if (th->th_urp > todrop)
1703 th->th_urp -= todrop;
1711 * If new data are received on a connection after the
1712 * user processes are gone, then RST the other end.
1714 if ((so->so_state & SS_NOFDREF) &&
1715 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1716 KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1717 "not locked", __func__));
1719 tcpstat.tcps_rcvafterclose++;
1720 rstreason = BANDLIM_UNLIMITED;
1725 * If segment ends after window, drop trailing data
1726 * (and PUSH and FIN); if nothing left, just ACK.
1728 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1730 tcpstat.tcps_rcvpackafterwin++;
1731 if (todrop >= tlen) {
1732 tcpstat.tcps_rcvbyteafterwin += tlen;
1734 * If window is closed can only take segments at
1735 * window edge, and have to drop data and PUSH from
1736 * incoming segments. Continue processing, but
1737 * remember to ack. Otherwise, drop segment
1740 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1741 tp->t_flags |= TF_ACKNOW;
1742 tcpstat.tcps_rcvwinprobe++;
1746 tcpstat.tcps_rcvbyteafterwin += todrop;
1749 thflags &= ~(TH_PUSH|TH_FIN);
1753 * If last ACK falls within this segment's sequence numbers,
1754 * record its timestamp.
1756 * 1) That the test incorporates suggestions from the latest
1757 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1758 * 2) That updating only on newer timestamps interferes with
1759 * our earlier PAWS tests, so this check should be solely
1760 * predicated on the sequence space of this segment.
1761 * 3) That we modify the segment boundary check to be
1762 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1763 * instead of RFC1323's
1764 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1765 * This modified check allows us to overcome RFC1323's
1766 * limitations as described in Stevens TCP/IP Illustrated
1767 * Vol. 2 p.869. In such cases, we can still calculate the
1768 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1770 if ((to.to_flags & TOF_TS) != 0 &&
1771 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1772 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1773 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1774 tp->ts_recent_age = ticks;
1775 tp->ts_recent = to.to_tsval;
1779 * If a SYN is in the window, then this is an
1780 * error and we send an RST and drop the connection.
1782 if (thflags & TH_SYN) {
1783 KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1784 "head not locked", __func__));
1785 tp = tcp_drop(tp, ECONNRESET);
1786 rstreason = BANDLIM_UNLIMITED;
1791 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1792 * flag is on (half-synchronized state), then queue data for
1793 * later processing; else drop segment and return.
1795 if ((thflags & TH_ACK) == 0) {
1796 if (tp->t_state == TCPS_SYN_RECEIVED ||
1797 (tp->t_flags & TF_NEEDSYN))
1799 else if (tp->t_flags & TF_ACKNOW)
1808 switch (tp->t_state) {
1811 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1812 * ESTABLISHED state and continue processing.
1813 * The ACK was checked above.
1815 case TCPS_SYN_RECEIVED:
1817 tcpstat.tcps_connects++;
1819 /* Do window scaling? */
1820 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1821 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1822 tp->rcv_scale = tp->request_r_scale;
1823 tp->snd_wnd = tiwin;
1827 * SYN-RECEIVED -> ESTABLISHED
1828 * SYN-RECEIVED* -> FIN-WAIT-1
1830 tp->t_starttime = ticks;
1831 if (tp->t_flags & TF_NEEDFIN) {
1832 tp->t_state = TCPS_FIN_WAIT_1;
1833 tp->t_flags &= ~TF_NEEDFIN;
1835 tp->t_state = TCPS_ESTABLISHED;
1836 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1839 * If segment contains data or ACK, will call tcp_reass()
1840 * later; if not, do so now to pass queued data to user.
1842 if (tlen == 0 && (thflags & TH_FIN) == 0)
1843 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1845 tp->snd_wl1 = th->th_seq - 1;
1849 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1850 * ACKs. If the ack is in the range
1851 * tp->snd_una < th->th_ack <= tp->snd_max
1852 * then advance tp->snd_una to th->th_ack and drop
1853 * data from the retransmission queue. If this ACK reflects
1854 * more up to date window information we update our window information.
1856 case TCPS_ESTABLISHED:
1857 case TCPS_FIN_WAIT_1:
1858 case TCPS_FIN_WAIT_2:
1859 case TCPS_CLOSE_WAIT:
1862 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1863 tcpstat.tcps_rcvacktoomuch++;
1866 if (tp->sack_enable &&
1867 ((to.to_flags & TOF_SACK) ||
1868 !TAILQ_EMPTY(&tp->snd_holes)))
1869 tcp_sack_doack(tp, &to, th->th_ack);
1870 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1871 if (tlen == 0 && tiwin == tp->snd_wnd) {
1872 tcpstat.tcps_rcvdupack++;
1874 * If we have outstanding data (other than
1875 * a window probe), this is a completely
1876 * duplicate ack (ie, window info didn't
1877 * change), the ack is the biggest we've
1878 * seen and we've seen exactly our rexmt
1879 * threshhold of them, assume a packet
1880 * has been dropped and retransmit it.
1881 * Kludge snd_nxt & the congestion
1882 * window so we send only this one
1885 * We know we're losing at the current
1886 * window size so do congestion avoidance
1887 * (set ssthresh to half the current window
1888 * and pull our congestion window back to
1889 * the new ssthresh).
1891 * Dup acks mean that packets have left the
1892 * network (they're now cached at the receiver)
1893 * so bump cwnd by the amount in the receiver
1894 * to keep a constant cwnd packets in the
1897 if (!tcp_timer_active(tp, TT_REXMT) ||
1898 th->th_ack != tp->snd_una)
1900 else if (++tp->t_dupacks > tcprexmtthresh ||
1901 ((tcp_do_newreno || tp->sack_enable) &&
1902 IN_FASTRECOVERY(tp))) {
1903 if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
1907 * Compute the amount of data in flight first.
1908 * We can inject new data into the pipe iff
1909 * we have less than 1/2 the original window's
1910 * worth of data in flight.
1912 awnd = (tp->snd_nxt - tp->snd_fack) +
1913 tp->sackhint.sack_bytes_rexmit;
1914 if (awnd < tp->snd_ssthresh) {
1915 tp->snd_cwnd += tp->t_maxseg;
1916 if (tp->snd_cwnd > tp->snd_ssthresh)
1917 tp->snd_cwnd = tp->snd_ssthresh;
1920 tp->snd_cwnd += tp->t_maxseg;
1921 (void) tcp_output(tp);
1923 } else if (tp->t_dupacks == tcprexmtthresh) {
1924 tcp_seq onxt = tp->snd_nxt;
1928 * If we're doing sack, check to
1929 * see if we're already in sack
1930 * recovery. If we're not doing sack,
1931 * check to see if we're in newreno
1934 if (tp->sack_enable) {
1935 if (IN_FASTRECOVERY(tp)) {
1939 } else if (tcp_do_newreno) {
1940 if (SEQ_LEQ(th->th_ack,
1946 win = min(tp->snd_wnd, tp->snd_cwnd) /
1950 tp->snd_ssthresh = win * tp->t_maxseg;
1951 ENTER_FASTRECOVERY(tp);
1952 tp->snd_recover = tp->snd_max;
1953 tcp_timer_activate(tp, TT_REXMT, 0);
1955 if (tp->sack_enable) {
1956 tcpstat.tcps_sack_recovery_episode++;
1957 tp->sack_newdata = tp->snd_nxt;
1958 tp->snd_cwnd = tp->t_maxseg;
1959 (void) tcp_output(tp);
1962 tp->snd_nxt = th->th_ack;
1963 tp->snd_cwnd = tp->t_maxseg;
1964 (void) tcp_output(tp);
1965 KASSERT(tp->snd_limited <= 2,
1966 ("%s: tp->snd_limited too big",
1968 tp->snd_cwnd = tp->snd_ssthresh +
1970 (tp->t_dupacks - tp->snd_limited);
1971 if (SEQ_GT(onxt, tp->snd_nxt))
1974 } else if (tcp_do_rfc3042) {
1975 u_long oldcwnd = tp->snd_cwnd;
1976 tcp_seq oldsndmax = tp->snd_max;
1979 KASSERT(tp->t_dupacks == 1 ||
1981 ("%s: dupacks not 1 or 2",
1983 if (tp->t_dupacks == 1)
1984 tp->snd_limited = 0;
1986 (tp->snd_nxt - tp->snd_una) +
1987 (tp->t_dupacks - tp->snd_limited) *
1989 (void) tcp_output(tp);
1990 sent = tp->snd_max - oldsndmax;
1991 if (sent > tp->t_maxseg) {
1992 KASSERT((tp->t_dupacks == 2 &&
1993 tp->snd_limited == 0) ||
1994 (sent == tp->t_maxseg + 1 &&
1995 tp->t_flags & TF_SENTFIN),
1996 ("%s: sent too much",
1998 tp->snd_limited = 2;
1999 } else if (sent > 0)
2001 tp->snd_cwnd = oldcwnd;
2009 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2010 ("%s: th_ack <= snd_una", __func__));
2013 * If the congestion window was inflated to account
2014 * for the other side's cached packets, retract it.
2016 if (tcp_do_newreno || tp->sack_enable) {
2017 if (IN_FASTRECOVERY(tp)) {
2018 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2019 if (tp->sack_enable)
2020 tcp_sack_partialack(tp, th);
2022 tcp_newreno_partial_ack(tp, th);
2025 * Out of fast recovery.
2026 * Window inflation should have left us
2027 * with approximately snd_ssthresh
2029 * But in case we would be inclined to
2030 * send a burst, better to do it via
2031 * the slow start mechanism.
2033 if (SEQ_GT(th->th_ack +
2036 tp->snd_cwnd = tp->snd_max -
2040 tp->snd_cwnd = tp->snd_ssthresh;
2044 if (tp->t_dupacks >= tcprexmtthresh &&
2045 tp->snd_cwnd > tp->snd_ssthresh)
2046 tp->snd_cwnd = tp->snd_ssthresh;
2050 * If we reach this point, ACK is not a duplicate,
2051 * i.e., it ACKs something we sent.
2053 if (tp->t_flags & TF_NEEDSYN) {
2055 * T/TCP: Connection was half-synchronized, and our
2056 * SYN has been ACK'd (so connection is now fully
2057 * synchronized). Go to non-starred state,
2058 * increment snd_una for ACK of SYN, and check if
2059 * we can do window scaling.
2061 tp->t_flags &= ~TF_NEEDSYN;
2063 /* Do window scaling? */
2064 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2065 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2066 tp->rcv_scale = tp->request_r_scale;
2067 /* Send window already scaled. */
2072 KASSERT(headlocked, ("%s: process_ACK: head not locked",
2074 INP_LOCK_ASSERT(tp->t_inpcb);
2076 acked = th->th_ack - tp->snd_una;
2077 tcpstat.tcps_rcvackpack++;
2078 tcpstat.tcps_rcvackbyte += acked;
2081 * If we just performed our first retransmit, and the ACK
2082 * arrives within our recovery window, then it was a mistake
2083 * to do the retransmit in the first place. Recover our
2084 * original cwnd and ssthresh, and proceed to transmit where
2087 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2088 ++tcpstat.tcps_sndrexmitbad;
2089 tp->snd_cwnd = tp->snd_cwnd_prev;
2090 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2091 tp->snd_recover = tp->snd_recover_prev;
2092 if (tp->t_flags & TF_WASFRECOVERY)
2093 ENTER_FASTRECOVERY(tp);
2094 tp->snd_nxt = tp->snd_max;
2095 tp->t_badrxtwin = 0; /* XXX probably not required */
2099 * If we have a timestamp reply, update smoothed
2100 * round trip time. If no timestamp is present but
2101 * transmit timer is running and timed sequence
2102 * number was acked, update smoothed round trip time.
2103 * Since we now have an rtt measurement, cancel the
2104 * timer backoff (cf., Phil Karn's retransmit alg.).
2105 * Recompute the initial retransmit timer.
2107 * Some boxes send broken timestamp replies
2108 * during the SYN+ACK phase, ignore
2109 * timestamps of 0 or we could calculate a
2110 * huge RTT and blow up the retransmit timer.
2112 if ((to.to_flags & TOF_TS) != 0 &&
2114 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2115 tp->t_rttlow = ticks - to.to_tsecr;
2116 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2117 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2118 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2119 tp->t_rttlow = ticks - tp->t_rtttime;
2120 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2122 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2125 * If all outstanding data is acked, stop retransmit
2126 * timer and remember to restart (more output or persist).
2127 * If there is more data to be acked, restart retransmit
2128 * timer, using current (possibly backed-off) value.
2130 if (th->th_ack == tp->snd_max) {
2131 tcp_timer_activate(tp, TT_REXMT, 0);
2133 } else if (!tcp_timer_active(tp, TT_PERSIST))
2134 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2137 * If no data (only SYN) was ACK'd,
2138 * skip rest of ACK processing.
2144 * When new data is acked, open the congestion window.
2145 * If the window gives us less than ssthresh packets
2146 * in flight, open exponentially (maxseg per packet).
2147 * Otherwise open linearly: maxseg per window
2148 * (maxseg^2 / cwnd per packet).
2150 if ((!tcp_do_newreno && !tp->sack_enable) ||
2151 !IN_FASTRECOVERY(tp)) {
2152 u_int cw = tp->snd_cwnd;
2153 u_int incr = tp->t_maxseg;
2154 if (cw > tp->snd_ssthresh)
2155 incr = incr * incr / cw;
2156 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2158 SOCKBUF_LOCK(&so->so_snd);
2159 if (acked > so->so_snd.sb_cc) {
2160 tp->snd_wnd -= so->so_snd.sb_cc;
2161 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2164 sbdrop_locked(&so->so_snd, acked);
2165 tp->snd_wnd -= acked;
2168 sowwakeup_locked(so);
2169 /* detect una wraparound */
2170 if ((tcp_do_newreno || tp->sack_enable) &&
2171 !IN_FASTRECOVERY(tp) &&
2172 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2173 SEQ_LEQ(th->th_ack, tp->snd_recover))
2174 tp->snd_recover = th->th_ack - 1;
2175 if ((tcp_do_newreno || tp->sack_enable) &&
2176 IN_FASTRECOVERY(tp) &&
2177 SEQ_GEQ(th->th_ack, tp->snd_recover))
2178 EXIT_FASTRECOVERY(tp);
2179 tp->snd_una = th->th_ack;
2180 if (tp->sack_enable) {
2181 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2182 tp->snd_recover = tp->snd_una;
2184 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2185 tp->snd_nxt = tp->snd_una;
2187 switch (tp->t_state) {
2190 * In FIN_WAIT_1 STATE in addition to the processing
2191 * for the ESTABLISHED state if our FIN is now acknowledged
2192 * then enter FIN_WAIT_2.
2194 case TCPS_FIN_WAIT_1:
2195 if (ourfinisacked) {
2197 * If we can't receive any more
2198 * data, then closing user can proceed.
2199 * Starting the timer is contrary to the
2200 * specification, but if we don't get a FIN
2201 * we'll hang forever.
2204 * we should release the tp also, and use a
2207 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2210 soisdisconnected(so);
2211 timeout = (tcp_fast_finwait2_recycle) ?
2212 tcp_finwait2_timeout : tcp_maxidle;
2213 tcp_timer_activate(tp, TT_2MSL, timeout);
2215 tp->t_state = TCPS_FIN_WAIT_2;
2220 * In CLOSING STATE in addition to the processing for
2221 * the ESTABLISHED state if the ACK acknowledges our FIN
2222 * then enter the TIME-WAIT state, otherwise ignore
2226 if (ourfinisacked) {
2227 KASSERT(headlocked, ("%s: process_ACK: "
2228 "head not locked", __func__));
2230 INP_INFO_WUNLOCK(&tcbinfo);
2238 * In LAST_ACK, we may still be waiting for data to drain
2239 * and/or to be acked, as well as for the ack of our FIN.
2240 * If our FIN is now acknowledged, delete the TCB,
2241 * enter the closed state and return.
2244 if (ourfinisacked) {
2245 KASSERT(headlocked, ("%s: process_ACK: "
2246 "tcp_close: head not locked", __func__));
2255 KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2256 INP_LOCK_ASSERT(tp->t_inpcb);
2259 * Update window information.
2260 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2262 if ((thflags & TH_ACK) &&
2263 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2264 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2265 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2266 /* keep track of pure window updates */
2268 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2269 tcpstat.tcps_rcvwinupd++;
2270 tp->snd_wnd = tiwin;
2271 tp->snd_wl1 = th->th_seq;
2272 tp->snd_wl2 = th->th_ack;
2273 if (tp->snd_wnd > tp->max_sndwnd)
2274 tp->max_sndwnd = tp->snd_wnd;
2279 * Process segments with URG.
2281 if ((thflags & TH_URG) && th->th_urp &&
2282 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2284 * This is a kludge, but if we receive and accept
2285 * random urgent pointers, we'll crash in
2286 * soreceive. It's hard to imagine someone
2287 * actually wanting to send this much urgent data.
2289 SOCKBUF_LOCK(&so->so_rcv);
2290 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2291 th->th_urp = 0; /* XXX */
2292 thflags &= ~TH_URG; /* XXX */
2293 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2294 goto dodata; /* XXX */
2297 * If this segment advances the known urgent pointer,
2298 * then mark the data stream. This should not happen
2299 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2300 * a FIN has been received from the remote side.
2301 * In these states we ignore the URG.
2303 * According to RFC961 (Assigned Protocols),
2304 * the urgent pointer points to the last octet
2305 * of urgent data. We continue, however,
2306 * to consider it to indicate the first octet
2307 * of data past the urgent section as the original
2308 * spec states (in one of two places).
2310 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2311 tp->rcv_up = th->th_seq + th->th_urp;
2312 so->so_oobmark = so->so_rcv.sb_cc +
2313 (tp->rcv_up - tp->rcv_nxt) - 1;
2314 if (so->so_oobmark == 0)
2315 so->so_rcv.sb_state |= SBS_RCVATMARK;
2317 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2319 SOCKBUF_UNLOCK(&so->so_rcv);
2321 * Remove out of band data so doesn't get presented to user.
2322 * This can happen independent of advancing the URG pointer,
2323 * but if two URG's are pending at once, some out-of-band
2324 * data may creep in... ick.
2326 if (th->th_urp <= (u_long)tlen &&
2327 !(so->so_options & SO_OOBINLINE)) {
2328 /* hdr drop is delayed */
2329 tcp_pulloutofband(so, th, m, drop_hdrlen);
2333 * If no out of band data is expected,
2334 * pull receive urgent pointer along
2335 * with the receive window.
2337 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2338 tp->rcv_up = tp->rcv_nxt;
2341 KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2342 INP_LOCK_ASSERT(tp->t_inpcb);
2345 * Process the segment text, merging it into the TCP sequencing queue,
2346 * and arranging for acknowledgment of receipt if necessary.
2347 * This process logically involves adjusting tp->rcv_wnd as data
2348 * is presented to the user (this happens in tcp_usrreq.c,
2349 * case PRU_RCVD). If a FIN has already been received on this
2350 * connection then we just ignore the text.
2352 if ((tlen || (thflags & TH_FIN)) &&
2353 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2354 tcp_seq save_start = th->th_seq;
2355 tcp_seq save_end = th->th_seq + tlen;
2356 m_adj(m, drop_hdrlen); /* delayed header drop */
2358 * Insert segment which includes th into TCP reassembly queue
2359 * with control block tp. Set thflags to whether reassembly now
2360 * includes a segment with FIN. This handles the common case
2361 * inline (segment is the next to be received on an established
2362 * connection, and the queue is empty), avoiding linkage into
2363 * and removal from the queue and repetition of various
2365 * Set DELACK for segments received in order, but ack
2366 * immediately when segments are out of order (so
2367 * fast retransmit can work).
2369 if (th->th_seq == tp->rcv_nxt &&
2370 LIST_EMPTY(&tp->t_segq) &&
2371 TCPS_HAVEESTABLISHED(tp->t_state)) {
2373 tp->t_flags |= TF_DELACK;
2375 tp->t_flags |= TF_ACKNOW;
2376 tp->rcv_nxt += tlen;
2377 thflags = th->th_flags & TH_FIN;
2378 tcpstat.tcps_rcvpack++;
2379 tcpstat.tcps_rcvbyte += tlen;
2381 SOCKBUF_LOCK(&so->so_rcv);
2382 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2385 sbappendstream_locked(&so->so_rcv, m);
2386 sorwakeup_locked(so);
2388 thflags = tcp_reass(tp, th, &tlen, m);
2389 tp->t_flags |= TF_ACKNOW;
2391 if (tlen > 0 && tp->sack_enable)
2392 tcp_update_sack_list(tp, save_start, save_end);
2395 * Note the amount of data that peer has sent into
2396 * our window, in order to estimate the sender's
2400 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2408 * If FIN is received ACK the FIN and let the user know
2409 * that the connection is closing.
2411 if (thflags & TH_FIN) {
2412 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2415 * If connection is half-synchronized
2416 * (ie NEEDSYN flag on) then delay ACK,
2417 * so it may be piggybacked when SYN is sent.
2418 * Otherwise, since we received a FIN then no
2419 * more input can be expected, send ACK now.
2421 if (tp->t_flags & TF_NEEDSYN)
2422 tp->t_flags |= TF_DELACK;
2424 tp->t_flags |= TF_ACKNOW;
2427 switch (tp->t_state) {
2430 * In SYN_RECEIVED and ESTABLISHED STATES
2431 * enter the CLOSE_WAIT state.
2433 case TCPS_SYN_RECEIVED:
2434 tp->t_starttime = ticks;
2436 case TCPS_ESTABLISHED:
2437 tp->t_state = TCPS_CLOSE_WAIT;
2441 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2442 * enter the CLOSING state.
2444 case TCPS_FIN_WAIT_1:
2445 tp->t_state = TCPS_CLOSING;
2449 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2450 * starting the time-wait timer, turning off the other
2453 case TCPS_FIN_WAIT_2:
2454 KASSERT(headlocked == 1, ("%s: dodata: "
2455 "TCP_FIN_WAIT_2: head not locked", __func__));
2457 INP_INFO_WUNLOCK(&tcbinfo);
2461 INP_INFO_WUNLOCK(&tcbinfo);
2464 if (so->so_options & SO_DEBUG)
2465 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2470 * Return any desired output.
2472 if (needoutput || (tp->t_flags & TF_ACKNOW))
2473 (void) tcp_output(tp);
2476 KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2478 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
2479 INP_LOCK_ASSERT(tp->t_inpcb);
2480 if (tp->t_flags & TF_DELACK) {
2481 tp->t_flags &= ~TF_DELACK;
2482 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2484 INP_UNLOCK(tp->t_inpcb);
2488 KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2490 * Generate an ACK dropping incoming segment if it occupies
2491 * sequence space, where the ACK reflects our state.
2493 * We can now skip the test for the RST flag since all
2494 * paths to this code happen after packets containing
2495 * RST have been dropped.
2497 * In the SYN-RECEIVED state, don't send an ACK unless the
2498 * segment we received passes the SYN-RECEIVED ACK test.
2499 * If it fails send a RST. This breaks the loop in the
2500 * "LAND" DoS attack, and also prevents an ACK storm
2501 * between two listening ports that have been sent forged
2502 * SYN segments, each with the source address of the other.
2504 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2505 (SEQ_GT(tp->snd_una, th->th_ack) ||
2506 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2507 rstreason = BANDLIM_RST_OPENPORT;
2511 if (so->so_options & SO_DEBUG)
2512 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2515 KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2516 INP_INFO_WUNLOCK(&tcbinfo);
2517 tp->t_flags |= TF_ACKNOW;
2518 (void) tcp_output(tp);
2519 INP_UNLOCK(tp->t_inpcb);
2524 KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2526 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2529 INP_UNLOCK(tp->t_inpcb);
2531 INP_INFO_WUNLOCK(&tcbinfo);
2536 * Drop space held by incoming segment and return.
2539 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2540 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2544 INP_UNLOCK(tp->t_inpcb);
2546 INP_INFO_WUNLOCK(&tcbinfo);
2553 * Issue RST on TCP segment. The mbuf must still include the original
2557 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2558 int tlen, int rstreason)
2562 struct ip6_hdr *ip6;
2565 * Generate a RST, dropping incoming segment.
2566 * Make ACK acceptable to originator of segment.
2567 * Don't bother to respond if destination was broadcast/multicast.
2570 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2573 if (mtod(m, struct ip *)->ip_v == 6) {
2574 ip6 = mtod(m, struct ip6_hdr *);
2575 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2576 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2578 /* IPv6 anycast check is done at tcp6_input() */
2582 ip = mtod(m, struct ip *);
2583 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2584 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2585 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2586 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2590 /* Perform bandwidth limiting. */
2591 if (badport_bandlim(rstreason) < 0)
2594 /* tcp_respond consumes the mbuf chain. */
2595 if (th->th_flags & TH_ACK) {
2596 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2597 th->th_ack, TH_RST);
2599 if (th->th_flags & TH_SYN)
2601 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2602 (tcp_seq)0, TH_RST|TH_ACK);
2611 * Parse TCP options and place in tcpopt.
2614 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2619 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2621 if (opt == TCPOPT_EOL)
2623 if (opt == TCPOPT_NOP)
2629 if (optlen < 2 || optlen > cnt)
2634 if (optlen != TCPOLEN_MAXSEG)
2636 if (!(flags & TO_SYN))
2638 to->to_flags |= TOF_MSS;
2639 bcopy((char *)cp + 2,
2640 (char *)&to->to_mss, sizeof(to->to_mss));
2641 to->to_mss = ntohs(to->to_mss);
2644 if (optlen != TCPOLEN_WINDOW)
2646 if (!(flags & TO_SYN))
2648 to->to_flags |= TOF_SCALE;
2649 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2651 case TCPOPT_TIMESTAMP:
2652 if (optlen != TCPOLEN_TIMESTAMP)
2654 to->to_flags |= TOF_TS;
2655 bcopy((char *)cp + 2,
2656 (char *)&to->to_tsval, sizeof(to->to_tsval));
2657 to->to_tsval = ntohl(to->to_tsval);
2658 bcopy((char *)cp + 6,
2659 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2660 to->to_tsecr = ntohl(to->to_tsecr);
2662 #ifdef TCP_SIGNATURE
2664 * XXX In order to reply to a host which has set the
2665 * TCP_SIGNATURE option in its initial SYN, we have to
2666 * record the fact that the option was observed here
2667 * for the syncache code to perform the correct response.
2669 case TCPOPT_SIGNATURE:
2670 if (optlen != TCPOLEN_SIGNATURE)
2672 to->to_flags |= TOF_SIGNATURE;
2673 to->to_signature = cp + 2;
2676 case TCPOPT_SACK_PERMITTED:
2677 if (optlen != TCPOLEN_SACK_PERMITTED)
2679 if (!(flags & TO_SYN))
2683 to->to_flags |= TOF_SACKPERM;
2686 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2690 to->to_flags |= TOF_SACK;
2691 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2692 to->to_sacks = cp + 2;
2693 tcpstat.tcps_sack_rcv_blocks++;
2702 * Pull out of band byte out of a segment so
2703 * it doesn't appear in the user's data queue.
2704 * It is still reflected in the segment length for
2705 * sequencing purposes.
2708 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2711 int cnt = off + th->th_urp - 1;
2714 if (m->m_len > cnt) {
2715 char *cp = mtod(m, caddr_t) + cnt;
2716 struct tcpcb *tp = sototcpcb(so);
2719 tp->t_oobflags |= TCPOOB_HAVEDATA;
2720 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2722 if (m->m_flags & M_PKTHDR)
2731 panic("tcp_pulloutofband");
2735 * Collect new round-trip time estimate
2736 * and update averages and current timeout.
2739 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2743 INP_LOCK_ASSERT(tp->t_inpcb);
2745 tcpstat.tcps_rttupdated++;
2747 if (tp->t_srtt != 0) {
2749 * srtt is stored as fixed point with 5 bits after the
2750 * binary point (i.e., scaled by 8). The following magic
2751 * is equivalent to the smoothing algorithm in rfc793 with
2752 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2753 * point). Adjust rtt to origin 0.
2755 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2756 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2758 if ((tp->t_srtt += delta) <= 0)
2762 * We accumulate a smoothed rtt variance (actually, a
2763 * smoothed mean difference), then set the retransmit
2764 * timer to smoothed rtt + 4 times the smoothed variance.
2765 * rttvar is stored as fixed point with 4 bits after the
2766 * binary point (scaled by 16). The following is
2767 * equivalent to rfc793 smoothing with an alpha of .75
2768 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2769 * rfc793's wired-in beta.
2773 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2774 if ((tp->t_rttvar += delta) <= 0)
2776 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2777 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2780 * No rtt measurement yet - use the unsmoothed rtt.
2781 * Set the variance to half the rtt (so our first
2782 * retransmit happens at 3*rtt).
2784 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2785 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2786 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2792 * the retransmit should happen at rtt + 4 * rttvar.
2793 * Because of the way we do the smoothing, srtt and rttvar
2794 * will each average +1/2 tick of bias. When we compute
2795 * the retransmit timer, we want 1/2 tick of rounding and
2796 * 1 extra tick because of +-1/2 tick uncertainty in the
2797 * firing of the timer. The bias will give us exactly the
2798 * 1.5 tick we need. But, because the bias is
2799 * statistical, we have to test that we don't drop below
2800 * the minimum feasible timer (which is 2 ticks).
2802 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2803 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2806 * We received an ack for a packet that wasn't retransmitted;
2807 * it is probably safe to discard any error indications we've
2808 * received recently. This isn't quite right, but close enough
2809 * for now (a route might have failed after we sent a segment,
2810 * and the return path might not be symmetrical).
2812 tp->t_softerror = 0;
2816 * Determine a reasonable value for maxseg size.
2817 * If the route is known, check route for mtu.
2818 * If none, use an mss that can be handled on the outgoing
2819 * interface without forcing IP to fragment; if bigger than
2820 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2821 * to utilize large mbufs. If no route is found, route has no mtu,
2822 * or the destination isn't local, use a default, hopefully conservative
2823 * size (usually 512 or the default IP max size, but no more than the mtu
2824 * of the interface), as we can't discover anything about intervening
2825 * gateways or networks. We also initialize the congestion/slow start
2826 * window to be a single segment if the destination isn't local.
2827 * While looking at the routing entry, we also initialize other path-dependent
2828 * parameters from pre-set or cached values in the routing entry.
2830 * Also take into account the space needed for options that we
2831 * send regularly. Make maxseg shorter by that amount to assure
2832 * that we can send maxseg amount of data even when the options
2833 * are present. Store the upper limit of the length of options plus
2837 * In case of T/TCP, we call this routine during implicit connection
2838 * setup as well (offer = -1), to initialize maxseg from the cached
2841 * NOTE that this routine is only called when we process an incoming
2842 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2845 tcp_mss(struct tcpcb *tp, int offer)
2850 struct inpcb *inp = tp->t_inpcb;
2852 struct hc_metrics_lite metrics;
2853 int origoffer = offer;
2856 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2857 size_t min_protoh = isipv6 ?
2858 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2859 sizeof (struct tcpiphdr);
2861 const size_t min_protoh = sizeof(struct tcpiphdr);
2867 maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2868 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2872 maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2873 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2875 so = inp->inp_socket;
2878 * no route to sender, stay with default mss and return
2883 /* what have we got? */
2887 * Offer == 0 means that there was no MSS on the SYN
2888 * segment, in this case we use tcp_mssdflt.
2892 isipv6 ? tcp_v6mssdflt :
2899 * Offer == -1 means that we didn't receive SYN yet.
2905 * Prevent DoS attack with too small MSS. Round up
2906 * to at least minmss.
2908 offer = max(offer, tcp_minmss);
2910 * Sanity check: make sure that maxopd will be large
2911 * enough to allow some data on segments even if the
2912 * all the option space is used (40bytes). Otherwise
2913 * funny things may happen in tcp_output.
2915 offer = max(offer, 64);
2919 * rmx information is now retrieved from tcp_hostcache
2921 tcp_hc_get(&inp->inp_inc, &metrics);
2924 * if there's a discovered mtu int tcp hostcache, use it
2925 * else, use the link mtu.
2927 if (metrics.rmx_mtu)
2928 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2932 mss = maxmtu - min_protoh;
2933 if (!path_mtu_discovery &&
2934 !in6_localaddr(&inp->in6p_faddr))
2935 mss = min(mss, tcp_v6mssdflt);
2939 mss = maxmtu - min_protoh;
2940 if (!path_mtu_discovery &&
2941 !in_localaddr(inp->inp_faddr))
2942 mss = min(mss, tcp_mssdflt);
2945 mss = min(mss, offer);
2948 * maxopd stores the maximum length of data AND options
2949 * in a segment; maxseg is the amount of data in a normal
2950 * segment. We need to store this value (maxopd) apart
2951 * from maxseg, because now every segment carries options
2952 * and thus we normally have somewhat less data in segments.
2957 * origoffer==-1 indicates, that no segments were received yet.
2958 * In this case we just guess.
2960 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2962 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2963 mss -= TCPOLEN_TSTAMP_APPA;
2966 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2968 mss &= ~(MCLBYTES-1);
2971 mss = mss / MCLBYTES * MCLBYTES;
2976 * If there's a pipesize, change the socket buffer to that size,
2977 * don't change if sb_hiwat is different than default (then it
2978 * has been changed on purpose with setsockopt).
2979 * Make the socket buffers an integral number of mss units;
2980 * if the mss is larger than the socket buffer, decrease the mss.
2982 SOCKBUF_LOCK(&so->so_snd);
2983 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2984 bufsize = metrics.rmx_sendpipe;
2986 bufsize = so->so_snd.sb_hiwat;
2990 bufsize = roundup(bufsize, mss);
2991 if (bufsize > sb_max)
2993 if (bufsize > so->so_snd.sb_hiwat)
2994 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2996 SOCKBUF_UNLOCK(&so->so_snd);
2999 SOCKBUF_LOCK(&so->so_rcv);
3000 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3001 bufsize = metrics.rmx_recvpipe;
3003 bufsize = so->so_rcv.sb_hiwat;
3004 if (bufsize > mss) {
3005 bufsize = roundup(bufsize, mss);
3006 if (bufsize > sb_max)
3008 if (bufsize > so->so_rcv.sb_hiwat)
3009 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3011 SOCKBUF_UNLOCK(&so->so_rcv);
3013 * While we're here, check the others too
3015 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3017 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3018 tcpstat.tcps_usedrtt++;
3019 if (metrics.rmx_rttvar) {
3020 tp->t_rttvar = metrics.rmx_rttvar;
3021 tcpstat.tcps_usedrttvar++;
3023 /* default variation is +- 1 rtt */
3025 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3027 TCPT_RANGESET(tp->t_rxtcur,
3028 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3029 tp->t_rttmin, TCPTV_REXMTMAX);
3031 if (metrics.rmx_ssthresh) {
3033 * There's some sort of gateway or interface
3034 * buffer limit on the path. Use this to set
3035 * the slow start threshhold, but set the
3036 * threshold to no less than 2*mss.
3038 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3039 tcpstat.tcps_usedssthresh++;
3041 if (metrics.rmx_bandwidth)
3042 tp->snd_bandwidth = metrics.rmx_bandwidth;
3045 * Set the slow-start flight size depending on whether this
3046 * is a local network or not.
3048 * Extend this so we cache the cwnd too and retrieve it here.
3049 * Make cwnd even bigger than RFC3390 suggests but only if we
3050 * have previous experience with the remote host. Be careful
3051 * not make cwnd bigger than remote receive window or our own
3052 * send socket buffer. Maybe put some additional upper bound
3053 * on the retrieved cwnd. Should do incremental updates to
3054 * hostcache when cwnd collapses so next connection doesn't
3055 * overloads the path again.
3057 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3058 * We currently check only in syncache_socket for that.
3060 #define TCP_METRICS_CWND
3061 #ifdef TCP_METRICS_CWND
3062 if (metrics.rmx_cwnd)
3063 tp->snd_cwnd = max(mss,
3064 min(metrics.rmx_cwnd / 2,
3065 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3069 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3071 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3072 (!isipv6 && in_localaddr(inp->inp_faddr)))
3074 else if (in_localaddr(inp->inp_faddr))
3076 tp->snd_cwnd = mss * ss_fltsz_local;
3078 tp->snd_cwnd = mss * ss_fltsz;
3080 /* Check the interface for TSO capabilities. */
3081 if (mtuflags & CSUM_TSO)
3082 tp->t_flags |= TF_TSO;
3086 * Determine the MSS option to send on an outgoing SYN.
3089 tcp_mssopt(struct in_conninfo *inc)
3096 int isipv6 = inc->inc_isipv6 ? 1 : 0;
3099 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3103 mss = tcp_v6mssdflt;
3104 maxmtu = tcp_maxmtu6(inc, NULL);
3105 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3106 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3111 maxmtu = tcp_maxmtu(inc, NULL);
3112 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3113 min_protoh = sizeof(struct tcpiphdr);
3115 if (maxmtu && thcmtu)
3116 mss = min(maxmtu, thcmtu) - min_protoh;
3117 else if (maxmtu || thcmtu)
3118 mss = max(maxmtu, thcmtu) - min_protoh;
3125 * On a partial ack arrives, force the retransmission of the
3126 * next unacknowledged segment. Do not clear tp->t_dupacks.
3127 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3131 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3133 tcp_seq onxt = tp->snd_nxt;
3134 u_long ocwnd = tp->snd_cwnd;
3136 tcp_timer_activate(tp, TT_REXMT, 0);
3138 tp->snd_nxt = th->th_ack;
3140 * Set snd_cwnd to one segment beyond acknowledged offset.
3141 * (tp->snd_una has not yet been updated when this function is called.)
3143 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3144 tp->t_flags |= TF_ACKNOW;
3145 (void) tcp_output(tp);
3146 tp->snd_cwnd = ocwnd;
3147 if (SEQ_GT(onxt, tp->snd_nxt))
3150 * Partial window deflation. Relies on fact that tp->snd_una
3153 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3154 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3157 tp->snd_cwnd += tp->t_maxseg;
3161 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3162 * looking for a pcb in the listen state. Returns 0 otherwise.
3165 tcp_timewait(struct inpcb *inp, struct tcpopt *to, struct tcphdr *th,
3166 struct mbuf *m, int tlen)
3172 int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3174 const int isipv6 = 0;
3177 /* tcbinfo lock required for tcp_twclose(), tcp_timer_2msl_reset(). */
3178 INP_INFO_WLOCK_ASSERT(&tcbinfo);
3179 INP_LOCK_ASSERT(inp);
3182 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
3183 * still present. This is undesirable, but temporarily necessary
3184 * until we work out how to handle inpcb's who's timewait state has
3191 thflags = th->th_flags;
3194 * NOTE: for FIN_WAIT_2 (to be added later),
3195 * must validate sequence number before accepting RST
3199 * If the segment contains RST:
3200 * Drop the segment - see Stevens, vol. 2, p. 964 and
3203 if (thflags & TH_RST)
3207 /* PAWS not needed at the moment */
3209 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3210 * and it's less than ts_recent, drop it.
3212 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3213 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3214 if ((thflags & TH_ACK) == 0)
3219 * ts_recent is never updated because we never accept new segments.
3224 * If a new connection request is received
3225 * while in TIME_WAIT, drop the old connection
3226 * and start over if the sequence numbers
3227 * are above the previous ones.
3229 if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3235 * Drop the the segment if it does not contain an ACK.
3237 if ((thflags & TH_ACK) == 0)
3241 * Reset the 2MSL timer if this is a duplicate FIN.
3243 if (thflags & TH_FIN) {
3244 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3245 if (seq + 1 == tw->rcv_nxt)
3246 tcp_timer_2msl_reset(tw, 1);
3250 * Acknowledge the segment if it has data or is not a duplicate ACK.
3252 if (thflags != TH_ACK || tlen != 0 ||
3253 th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3254 tcp_twrespond(tw, TH_ACK);
3258 * Generate a RST, dropping incoming segment.
3259 * Make ACK acceptable to originator of segment.
3260 * Don't bother to respond if destination was broadcast/multicast.
3262 if (m->m_flags & (M_BCAST|M_MCAST))
3265 struct ip6_hdr *ip6;
3267 /* IPv6 anycast check is done at tcp6_input() */
3268 ip6 = mtod(m, struct ip6_hdr *);
3269 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3270 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3275 ip = mtod(m, struct ip *);
3276 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3277 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3278 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3279 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3282 if (thflags & TH_ACK) {
3284 mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3286 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3288 mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);