2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
37 * License terms: all terms for the DragonFly license above plus the following:
39 * 4. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
42 * This product includes software developed by Jeffrey M. Hsu
43 * for the DragonFly Project.
45 * This requirement may be waived with permission from Jeffrey Hsu.
46 * This requirement will sunset and may be removed on July 8 2005,
47 * after which the standard DragonFly license (as shown above) will
52 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
53 * The Regents of the University of California. All rights reserved.
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * 3. All advertising materials mentioning features or use of this software
64 * must display the following acknowledgement:
65 * This product includes software developed by the University of
66 * California, Berkeley and its contributors.
67 * 4. Neither the name of the University nor the names of its contributors
68 * may be used to endorse or promote products derived from this software
69 * without specific prior written permission.
71 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
83 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
84 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
85 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.34 2004/08/08 06:33:24 hsu Exp $
88 #include "opt_ipfw.h" /* for ipfw_fwd */
89 #include "opt_inet6.h"
90 #include "opt_ipsec.h"
91 #include "opt_tcpdebug.h"
92 #include "opt_tcp_input.h"
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/sysctl.h>
98 #include <sys/malloc.h>
100 #include <sys/proc.h> /* for proc0 declaration */
101 #include <sys/protosw.h>
102 #include <sys/socket.h>
103 #include <sys/socketvar.h>
104 #include <sys/syslog.h>
105 #include <sys/in_cksum.h>
107 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
108 #include <machine/stdarg.h>
111 #include <net/route.h>
113 #include <netinet/in.h>
114 #include <netinet/in_systm.h>
115 #include <netinet/ip.h>
116 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
117 #include <netinet/in_var.h>
118 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
119 #include <netinet/in_pcb.h>
120 #include <netinet/ip_var.h>
121 #include <netinet/ip6.h>
122 #include <netinet/icmp6.h>
123 #include <netinet6/nd6.h>
124 #include <netinet6/ip6_var.h>
125 #include <netinet6/in6_pcb.h>
126 #include <netinet/tcp.h>
127 #include <netinet/tcp_fsm.h>
128 #include <netinet/tcp_seq.h>
129 #include <netinet/tcp_timer.h>
130 #include <netinet/tcp_var.h>
131 #include <netinet6/tcp6_var.h>
132 #include <netinet/tcpip.h>
135 #include <netinet/tcp_debug.h>
137 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
138 struct tcphdr tcp_savetcp;
142 #include <netipsec/ipsec.h>
143 #include <netipsec/ipsec6.h>
147 #include <netinet6/ipsec.h>
148 #include <netinet6/ipsec6.h>
149 #include <netproto/key/key.h>
152 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
154 static const int tcprexmtthresh = 3;
156 static int log_in_vain = 0;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
158 &log_in_vain, 0, "Log all incoming TCP connections");
160 static int blackhole = 0;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
162 &blackhole, 0, "Do not send RST when dropping refused connections");
164 int tcp_delack_enabled = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
166 &tcp_delack_enabled, 0,
167 "Delay ACK to try and piggyback it onto a data packet");
169 #ifdef TCP_DROP_SYNFIN
170 static int drop_synfin = 0;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
172 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
175 static int tcp_do_limitedtransmit = 1;
176 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
177 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
179 static int tcp_do_early_retransmit = 0;
180 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
181 &tcp_do_early_retransmit, 0, "Early retransmit");
183 static int tcp_do_rfc3390 = 1;
184 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
186 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
188 static int tcp_do_eifel_detect = 1;
189 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
190 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
192 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
193 "TCP Segment Reassembly Queue");
195 int tcp_reass_maxseg = 0;
196 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
197 &tcp_reass_maxseg, 0,
198 "Global maximum number of TCP Segments in Reassembly Queue");
200 int tcp_reass_qsize = 0;
201 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
203 "Global number of TCP Segments currently in Reassembly Queue");
205 static int tcp_reass_overflows = 0;
206 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
207 &tcp_reass_overflows, 0,
208 "Global number of TCP Segment Reassembly Queue Overflows");
210 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
211 static void tcp_pulloutofband(struct socket *,
212 struct tcphdr *, struct mbuf *, int);
213 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
215 static void tcp_xmit_timer(struct tcpcb *, int);
216 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
218 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
220 #define ND6_HINT(tp) \
222 if ((tp) && (tp)->t_inpcb && \
223 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
224 (tp)->t_inpcb->in6p_route.ro_rt) \
225 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
232 * Indicate whether this ack should be delayed. We can delay the ack if
233 * - delayed acks are enabled and
234 * - there is no delayed ack timer in progress and
235 * - our last ack wasn't a 0-sized window. We never want to delay
236 * the ack that opens up a 0-sized window.
238 #define DELAY_ACK(tp) \
239 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
240 !(tp->t_flags & TF_RXWIN0SENT))
243 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
246 struct tseg_qent *p = NULL;
247 struct tseg_qent *nq;
248 struct tseg_qent *te;
249 struct socket *so = tp->t_inpcb->inp_socket;
253 * Call with th == NULL after become established to
254 * force pre-ESTABLISHED data up to user socket.
260 * Limit the number of segments in the reassembly queue to prevent
261 * holding on to too many segments (and thus running out of mbufs).
262 * Make sure to let the missing segment through which caused this
263 * queue. Always keep one global queue entry spare to be able to
264 * process the missing segment.
266 if (th->th_seq != tp->rcv_nxt &&
267 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
268 tcp_reass_overflows++;
269 tcpstat.tcps_rcvmemdrop++;
274 /* Allocate a new queue entry. */
275 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
276 M_INTWAIT | M_NULLOK);
278 tcpstat.tcps_rcvmemdrop++;
285 * Find a segment which begins after this one does.
287 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
288 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
294 * If there is a preceding segment, it may provide some of
295 * our data already. If so, drop the data from the incoming
296 * segment. If it provides all of our data, drop us.
300 /* conversion to int (in i) handles seq wraparound */
301 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
304 tcpstat.tcps_rcvduppack++;
305 tcpstat.tcps_rcvdupbyte += *tlenp;
310 * Try to present any queued data
311 * at the left window edge to the user.
312 * This is needed after the 3-WHS
315 goto present; /* ??? */
322 tcpstat.tcps_rcvoopack++;
323 tcpstat.tcps_rcvoobyte += *tlenp;
326 * While we overlap succeeding segments trim them or,
327 * if they are completely covered, dequeue them.
330 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
333 if (i < q->tqe_len) {
334 q->tqe_th->th_seq += i;
340 nq = LIST_NEXT(q, tqe_q);
341 LIST_REMOVE(q, tqe_q);
348 /* Insert the new segment queue entry into place. */
351 te->tqe_len = *tlenp;
354 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
356 LIST_INSERT_AFTER(p, te, tqe_q);
361 * Present data to user, advancing rcv_nxt through
362 * completed sequence space.
364 if (!TCPS_HAVEESTABLISHED(tp->t_state))
366 q = LIST_FIRST(&tp->t_segq);
367 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
370 tp->rcv_nxt += q->tqe_len;
371 flags = q->tqe_th->th_flags & TH_FIN;
372 nq = LIST_NEXT(q, tqe_q);
373 LIST_REMOVE(q, tqe_q);
374 if (so->so_state & SS_CANTRCVMORE)
377 sbappend(&so->so_rcv, q->tqe_m);
381 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
388 * TCP input routine, follows pages 65-76 of the
389 * protocol specification dated September, 1981 very closely.
393 tcp6_input(struct mbuf **mp, int *offp, int proto)
395 struct mbuf *m = *mp;
396 struct in6_ifaddr *ia6;
398 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
401 * draft-itojun-ipv6-tcp-to-anycast
402 * better place to put this in?
404 ia6 = ip6_getdstifaddr(m);
405 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
408 ip6 = mtod(m, struct ip6_hdr *);
409 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
410 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
411 return (IPPROTO_DONE);
414 tcp_input(m, *offp, proto);
415 return (IPPROTO_DONE);
420 tcp_input(struct mbuf *m, ...)
425 struct ip *ip = NULL;
427 struct inpcb *inp = NULL;
432 struct tcpcb *tp = NULL;
434 struct socket *so = 0;
436 boolean_t ourfinisacked, needoutput = FALSE;
439 struct tcpopt to; /* options in this segment */
440 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
441 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
442 struct sockaddr_in *next_hop = NULL;
443 int rstreason; /* For badport_bandlim accounting purposes */
445 struct ip6_hdr *ip6 = NULL;
449 const boolean_t isipv6 = FALSE;
456 off0 = __va_arg(ap, int);
457 proto = __va_arg(ap, int);
460 tcpstat.tcps_rcvtotal++;
462 /* Grab info from and strip MT_TAG mbufs prepended to the chain. */
463 while (m->m_type == MT_TAG) {
464 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
465 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
470 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
474 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
475 ip6 = mtod(m, struct ip6_hdr *);
476 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
477 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
478 tcpstat.tcps_rcvbadsum++;
481 th = (struct tcphdr *)((caddr_t)ip6 + off0);
484 * Be proactive about unspecified IPv6 address in source.
485 * As we use all-zero to indicate unbounded/unconnected pcb,
486 * unspecified IPv6 address can be used to confuse us.
488 * Note that packets with unspecified IPv6 destination is
489 * already dropped in ip6_input.
491 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
497 * Get IP and TCP header together in first mbuf.
498 * Note: IP leaves IP header in first mbuf.
500 if (off0 > sizeof(struct ip)) {
502 off0 = sizeof(struct ip);
504 /* already checked and pulled up in ip_demux() */
505 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
506 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
507 ip = mtod(m, struct ip *);
508 ipov = (struct ipovly *)ip;
509 th = (struct tcphdr *)((caddr_t)ip + off0);
512 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
513 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
514 th->th_sum = m->m_pkthdr.csum_data;
516 th->th_sum = in_pseudo(ip->ip_src.s_addr,
518 htonl(m->m_pkthdr.csum_data +
521 th->th_sum ^= 0xffff;
524 * Checksum extended TCP header and data.
526 len = sizeof(struct ip) + tlen;
527 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
528 ipov->ih_len = (u_short)tlen;
529 ipov->ih_len = htons(ipov->ih_len);
530 th->th_sum = in_cksum(m, len);
533 tcpstat.tcps_rcvbadsum++;
537 /* Re-initialization for later version check */
538 ip->ip_v = IPVERSION;
543 * Check that TCP offset makes sense,
544 * pull out TCP options and adjust length. XXX
546 off = th->th_off << 2;
547 /* already checked and pulled up in ip_demux() */
548 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
549 ("bad TCP data offset %d (tlen %d)", off, tlen));
550 tlen -= off; /* tlen is used instead of ti->ti_len */
551 if (off > sizeof(struct tcphdr)) {
553 IP6_EXTHDR_CHECK(m, off0, off, );
554 ip6 = mtod(m, struct ip6_hdr *);
555 th = (struct tcphdr *)((caddr_t)ip6 + off0);
557 /* already pulled up in ip_demux() */
558 KASSERT(m->m_len >= sizeof(struct ip) + off,
559 ("TCP header and options not in one mbuf: "
560 "m_len %d, off %d", m->m_len, off));
562 optlen = off - sizeof(struct tcphdr);
563 optp = (u_char *)(th + 1);
565 thflags = th->th_flags;
567 #ifdef TCP_DROP_SYNFIN
569 * If the drop_synfin option is enabled, drop all packets with
570 * both the SYN and FIN bits set. This prevents e.g. nmap from
571 * identifying the TCP/IP stack.
573 * This is a violation of the TCP specification.
575 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
580 * Convert TCP protocol specific fields to host format.
582 th->th_seq = ntohl(th->th_seq);
583 th->th_ack = ntohl(th->th_ack);
584 th->th_win = ntohs(th->th_win);
585 th->th_urp = ntohs(th->th_urp);
588 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
589 * until after ip6_savecontrol() is called and before other functions
590 * which don't want those proto headers.
591 * Because ip6_savecontrol() is going to parse the mbuf to
592 * search for data to be passed up to user-land, it wants mbuf
593 * parameters to be unchanged.
594 * XXX: the call of ip6_savecontrol() has been obsoleted based on
595 * latest version of the advanced API (20020110).
597 drop_hdrlen = off0 + off;
600 * Locate pcb for segment.
603 /* IPFIREWALL_FORWARD section */
604 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
606 * Transparently forwarded. Pretend to be the destination.
607 * already got one like this?
609 cpu = mycpu->gd_cpuid;
610 inp = in_pcblookup_hash(&tcbinfo[cpu],
611 ip->ip_src, th->th_sport,
612 ip->ip_dst, th->th_dport,
613 0, m->m_pkthdr.rcvif);
616 * It's new. Try to find the ambushing socket.
620 * The rest of the ipfw code stores the port in
622 * (The IP address is still in network order.)
624 in_port_t dport = next_hop->sin_port ?
625 htons(next_hop->sin_port) :
628 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
629 next_hop->sin_addr.s_addr, dport);
630 inp = in_pcblookup_hash(&tcbinfo[cpu],
631 ip->ip_src, th->th_sport,
632 next_hop->sin_addr, dport,
633 1, m->m_pkthdr.rcvif);
637 inp = in6_pcblookup_hash(&tcbinfo[0],
638 &ip6->ip6_src, th->th_sport,
639 &ip6->ip6_dst, th->th_dport,
640 1, m->m_pkthdr.rcvif);
642 cpu = mycpu->gd_cpuid;
643 inp = in_pcblookup_hash(&tcbinfo[cpu],
644 ip->ip_src, th->th_sport,
645 ip->ip_dst, th->th_dport,
646 1, m->m_pkthdr.rcvif);
651 * If the state is CLOSED (i.e., TCB does not exist) then
652 * all data in the incoming segment is discarded.
653 * If the TCB exists but is in CLOSED state, it is embryonic,
654 * but should either do a listen or a connect soon.
659 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
661 char dbuf[4 * sizeof "123"], sbuf[4 * sizeof "123"];
665 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
668 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
671 strcpy(dbuf, inet_ntoa(ip->ip_dst));
672 strcpy(sbuf, inet_ntoa(ip->ip_src));
674 switch (log_in_vain) {
676 if (!(thflags & TH_SYN))
680 "Connection attempt to TCP %s:%d "
681 "from %s:%d flags:0x%02x\n",
682 dbuf, ntohs(th->th_dport), sbuf,
683 ntohs(th->th_sport), thflags);
692 if (thflags & TH_SYN)
701 rstreason = BANDLIM_RST_CLOSEDPORT;
707 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
708 ipsec6stat.in_polvio++;
712 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
713 ipsecstat.in_polvio++;
720 if (ipsec6_in_reject(m, inp))
723 if (ipsec4_in_reject(m, inp))
730 rstreason = BANDLIM_RST_CLOSEDPORT;
733 if (tp->t_state == TCPS_CLOSED)
736 /* Unscale the window into a 32-bit value. */
737 if (!(thflags & TH_SYN))
738 tiwin = th->th_win << tp->snd_scale;
742 so = inp->inp_socket;
745 if (so->so_options & SO_DEBUG) {
746 ostate = tp->t_state;
748 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
750 bcopy(ip, tcp_saveipgen, sizeof(*ip));
755 bzero(&to, sizeof(to));
757 if (so->so_options & SO_ACCEPTCONN) {
758 struct in_conninfo inc;
761 inc.inc_isipv6 = (isipv6 == TRUE);
764 inc.inc6_faddr = ip6->ip6_src;
765 inc.inc6_laddr = ip6->ip6_dst;
766 inc.inc6_route.ro_rt = NULL; /* XXX */
768 inc.inc_faddr = ip->ip_src;
769 inc.inc_laddr = ip->ip_dst;
770 inc.inc_route.ro_rt = NULL; /* XXX */
772 inc.inc_fport = th->th_sport;
773 inc.inc_lport = th->th_dport;
776 * If the state is LISTEN then ignore segment if it contains
777 * a RST. If the segment contains an ACK then it is bad and
778 * send a RST. If it does not contain a SYN then it is not
779 * interesting; drop it.
781 * If the state is SYN_RECEIVED (syncache) and seg contains
782 * an ACK, but not for our SYN/ACK, send a RST. If the seg
783 * contains a RST, check the sequence number to see if it
784 * is a valid reset segment.
786 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
787 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
788 if (!syncache_expand(&inc, th, &so, m)) {
790 * No syncache entry, or ACK was not
791 * for our SYN/ACK. Send a RST.
793 tcpstat.tcps_badsyn++;
794 rstreason = BANDLIM_RST_OPENPORT;
799 * Could not complete 3-way handshake,
800 * connection is being closed down, and
801 * syncache will free mbuf.
805 * Socket is created in state SYN_RECEIVED.
806 * Continue processing segment.
811 * This is what would have happened in
812 * tcp_output() when the SYN,ACK was sent.
814 tp->snd_up = tp->snd_una;
815 tp->snd_max = tp->snd_nxt = tp->iss + 1;
816 tp->last_ack_sent = tp->rcv_nxt;
818 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
819 * until the _second_ ACK is received:
820 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
821 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
822 * move to ESTAB, set snd_wnd to tiwin.
824 tp->snd_wnd = tiwin; /* unscaled */
827 if (thflags & TH_RST) {
828 syncache_chkrst(&inc, th);
831 if (thflags & TH_ACK) {
832 syncache_badack(&inc);
833 tcpstat.tcps_badsyn++;
834 rstreason = BANDLIM_RST_OPENPORT;
841 * Segment's flags are (SYN) or (SYN | FIN).
845 * If deprecated address is forbidden,
846 * we do not accept SYN to deprecated interface
847 * address to prevent any new inbound connection from
848 * getting established.
849 * When we do not accept SYN, we send a TCP RST,
850 * with deprecated source address (instead of dropping
851 * it). We compromise it as it is much better for peer
852 * to send a RST, and RST will be the final packet
855 * If we do not forbid deprecated addresses, we accept
856 * the SYN packet. RFC2462 does not suggest dropping
858 * If we decipher RFC2462 5.5.4, it says like this:
859 * 1. use of deprecated addr with existing
860 * communication is okay - "SHOULD continue to be
862 * 2. use of it with new communication:
863 * (2a) "SHOULD NOT be used if alternate address
864 * with sufficient scope is available"
865 * (2b) nothing mentioned otherwise.
866 * Here we fall into (2b) case as we have no choice in
867 * our source address selection - we must obey the peer.
869 * The wording in RFC2462 is confusing, and there are
870 * multiple description text for deprecated address
871 * handling - worse, they are not exactly the same.
872 * I believe 5.5.4 is the best one, so we follow 5.5.4.
874 if (isipv6 && !ip6_use_deprecated) {
875 struct in6_ifaddr *ia6;
877 if ((ia6 = ip6_getdstifaddr(m)) &&
878 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
880 rstreason = BANDLIM_RST_OPENPORT;
886 * If it is from this socket, drop it, it must be forged.
887 * Don't bother responding if the destination was a broadcast.
889 if (th->th_dport == th->th_sport) {
891 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
895 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
900 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
902 * Note that it is quite possible to receive unicast
903 * link-layer packets with a broadcast IP address. Use
904 * in_broadcast() to find them.
906 if (m->m_flags & (M_BCAST | M_MCAST))
909 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
910 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
913 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
914 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
915 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
916 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
920 * SYN appears to be valid; create compressed TCP state
921 * for syncache, or perform t/tcp connection.
923 if (so->so_qlen <= so->so_qlimit) {
924 tcp_dooptions(&to, optp, optlen, TRUE);
925 if (!syncache_add(&inc, &to, th, &so, m))
929 * Entry added to syncache, mbuf used to
930 * send SYN,ACK packet.
934 * Segment passed TAO tests.
939 tp->t_starttime = ticks;
940 tp->t_state = TCPS_ESTABLISHED;
943 * If there is a FIN, or if there is data and the
944 * connection is local, then delay SYN,ACK(SYN) in
945 * the hope of piggy-backing it on a response
946 * segment. Otherwise must send ACK now in case
947 * the other side is slow starting.
950 ((thflags & TH_FIN) ||
952 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
953 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
954 callout_reset(tp->tt_delack, tcp_delacktime,
955 tcp_timer_delack, tp);
956 tp->t_flags |= TF_NEEDSYN;
958 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
960 tcpstat.tcps_connects++;
968 /* should not happen - syncache should pick up these connections */
969 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
972 * Segment received on connection.
973 * Reset idle time and keep-alive timer.
975 tp->t_rcvtime = ticks;
976 if (TCPS_HAVEESTABLISHED(tp->t_state))
977 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
981 * XXX this is tradtitional behavior, may need to be cleaned up.
983 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
984 if (thflags & TH_SYN) {
985 if (to.to_flags & TOF_SCALE) {
986 tp->t_flags |= TF_RCVD_SCALE;
987 tp->requested_s_scale = to.to_requested_s_scale;
989 if (to.to_flags & TOF_TS) {
990 tp->t_flags |= TF_RCVD_TSTMP;
991 tp->ts_recent = to.to_tsval;
992 tp->ts_recent_age = ticks;
994 if (to.to_flags & (TOF_CC | TOF_CCNEW))
995 tp->t_flags |= TF_RCVD_CC;
996 if (to.to_flags & TOF_MSS)
997 tcp_mss(tp, to.to_mss);
1001 * Header prediction: check for the two common cases
1002 * of a uni-directional data xfer. If the packet has
1003 * no control flags, is in-sequence, the window didn't
1004 * change and we're not retransmitting, it's a
1005 * candidate. If the length is zero and the ack moved
1006 * forward, we're the sender side of the xfer. Just
1007 * free the data acked & wake any higher level process
1008 * that was blocked waiting for space. If the length
1009 * is non-zero and the ack didn't move, we're the
1010 * receiver side. If we're getting packets in-order
1011 * (the reassembly queue is empty), add the data to
1012 * the socket buffer and note that we need a delayed ack.
1013 * Make sure that the hidden state-flags are also off.
1014 * Since we check for TCPS_ESTABLISHED above, it can only
1017 if (tp->t_state == TCPS_ESTABLISHED &&
1018 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1019 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1020 (!(to.to_flags & TOF_TS) ||
1021 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1023 * Using the CC option is compulsory if once started:
1024 * the segment is OK if no T/TCP was negotiated or
1025 * if the segment has a CC option equal to CCrecv
1027 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
1028 ((to.to_flags & TOF_CC) && to.to_cc == tp->cc_recv)) &&
1029 th->th_seq == tp->rcv_nxt &&
1030 tiwin && tiwin == tp->snd_wnd &&
1031 tp->snd_nxt == tp->snd_max) {
1034 * If last ACK falls within this segment's sequence numbers,
1035 * record the timestamp.
1036 * NOTE that the test is modified according to the latest
1037 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1039 if ((to.to_flags & TOF_TS) &&
1040 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1041 tp->ts_recent_age = ticks;
1042 tp->ts_recent = to.to_tsval;
1046 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1047 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1048 tp->snd_cwnd >= tp->snd_wnd &&
1049 !IN_FASTRECOVERY(tp)) {
1051 * this is a pure ack for outstanding data.
1053 ++tcpstat.tcps_predack;
1055 * "bad retransmit" recovery
1057 * If Eifel detection applies, then
1058 * it is deterministic, so use it
1059 * unconditionally over the old heuristic.
1060 * Otherwise, fall back to the old heuristic.
1062 if (tcp_do_eifel_detect &&
1063 (to.to_flags & TOF_TS) && to.to_tsecr &&
1064 (tp->t_flags & TF_FIRSTACCACK)) {
1065 /* Eifel detection applicable. */
1066 if (to.to_tsecr < tp->t_rexmtTS) {
1067 tcp_revert_congestion_state(tp);
1068 ++tcpstat.tcps_eifeldetected;
1070 } else if (tp->t_rxtshift == 1 &&
1071 ticks < tp->t_badrxtwin) {
1072 tcp_revert_congestion_state(tp);
1073 ++tcpstat.tcps_rttdetected;
1075 tp->t_flags &= ~(TF_FIRSTACCACK |
1076 TF_FASTREXMT | TF_EARLYREXMT);
1078 * Recalculate the retransmit timer / rtt.
1080 * Some machines (certain windows boxes)
1081 * send broken timestamp replies during the
1082 * SYN+ACK phase, ignore timestamps of 0.
1084 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1086 ticks - to.to_tsecr + 1);
1087 } else if (tp->t_rtttime &&
1088 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1090 ticks - tp->t_rtttime);
1092 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1093 acked = th->th_ack - tp->snd_una;
1094 tcpstat.tcps_rcvackpack++;
1095 tcpstat.tcps_rcvackbyte += acked;
1096 sbdrop(&so->so_snd, acked);
1097 tp->snd_recover = th->th_ack - 1;
1098 tp->snd_una = th->th_ack;
1101 ND6_HINT(tp); /* some progress has been done */
1104 * If all outstanding data are acked, stop
1105 * retransmit timer, otherwise restart timer
1106 * using current (possibly backed-off) value.
1107 * If process is waiting for space,
1108 * wakeup/selwakeup/signal. If data
1109 * are ready to send, let tcp_output
1110 * decide between more output or persist.
1112 if (tp->snd_una == tp->snd_max)
1113 callout_stop(tp->tt_rexmt);
1114 else if (!callout_active(tp->tt_persist))
1115 callout_reset(tp->tt_rexmt,
1117 tcp_timer_rexmt, tp);
1120 if (so->so_snd.sb_cc)
1121 (void) tcp_output(tp);
1124 } else if (th->th_ack == tp->snd_una &&
1125 LIST_EMPTY(&tp->t_segq) &&
1126 tlen <= sbspace(&so->so_rcv)) {
1128 * this is a pure, in-sequence data packet
1129 * with nothing on the reassembly queue and
1130 * we have enough buffer space to take it.
1132 ++tcpstat.tcps_preddat;
1133 tp->rcv_nxt += tlen;
1134 tcpstat.tcps_rcvpack++;
1135 tcpstat.tcps_rcvbyte += tlen;
1136 ND6_HINT(tp); /* some progress has been done */
1138 * Add data to socket buffer.
1140 if (so->so_state & SS_CANTRCVMORE) {
1143 m_adj(m, drop_hdrlen); /* delayed header drop */
1144 sbappend(&so->so_rcv, m);
1149 * This code is responsible for most of the ACKs
1150 * the TCP stack sends back after receiving a data
1151 * packet. Note that the DELAY_ACK check fails if
1152 * the delack timer is already running, which results
1153 * in an ack being sent every other packet (which is
1156 if (DELAY_ACK(tp)) {
1157 callout_reset(tp->tt_delack, tcp_delacktime,
1158 tcp_timer_delack, tp);
1160 tp->t_flags |= TF_ACKNOW;
1161 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1162 tp->t_flags |= TF_ONOUTPUTQ;
1163 tp->tt_cpu = mycpu->gd_cpuid;
1165 &tcpcbackq[tp->tt_cpu],
1174 * Calculate amount of space in receive window,
1175 * and then do TCP input processing.
1176 * Receive window is amount of space in rcv queue,
1177 * but not less than advertised window.
1179 recvwin = sbspace(&so->so_rcv);
1182 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1184 switch (tp->t_state) {
1187 * If the state is SYN_RECEIVED:
1188 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1190 case TCPS_SYN_RECEIVED:
1191 if ((thflags & TH_ACK) &&
1192 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1193 SEQ_GT(th->th_ack, tp->snd_max))) {
1194 rstreason = BANDLIM_RST_OPENPORT;
1200 * If the state is SYN_SENT:
1201 * if seg contains an ACK, but not for our SYN, drop the input.
1202 * if seg contains a RST, then drop the connection.
1203 * if seg does not contain SYN, then drop it.
1204 * Otherwise this is an acceptable SYN segment
1205 * initialize tp->rcv_nxt and tp->irs
1206 * if seg contains ack then advance tp->snd_una
1207 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1208 * arrange for segment to be acked (eventually)
1209 * continue processing rest of data/controls, beginning with URG
1212 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1213 taop = &tao_noncached;
1214 bzero(taop, sizeof(*taop));
1217 if ((thflags & TH_ACK) &&
1218 (SEQ_LEQ(th->th_ack, tp->iss) ||
1219 SEQ_GT(th->th_ack, tp->snd_max))) {
1221 * If we have a cached CCsent for the remote host,
1222 * hence we haven't just crashed and restarted,
1223 * do not send a RST. This may be a retransmission
1224 * from the other side after our earlier ACK was lost.
1225 * Our new SYN, when it arrives, will serve as the
1228 if (taop->tao_ccsent != 0)
1231 rstreason = BANDLIM_UNLIMITED;
1235 if (thflags & TH_RST) {
1236 if (thflags & TH_ACK)
1237 tp = tcp_drop(tp, ECONNREFUSED);
1240 if (!(thflags & TH_SYN))
1242 tp->snd_wnd = th->th_win; /* initial send window */
1243 tp->cc_recv = to.to_cc; /* foreign CC */
1245 tp->irs = th->th_seq;
1247 if (thflags & TH_ACK) {
1249 * Our SYN was acked. If segment contains CC.ECHO
1250 * option, check it to make sure this segment really
1251 * matches our SYN. If not, just drop it as old
1252 * duplicate, but send an RST if we're still playing
1253 * by the old rules. If no CC.ECHO option, make sure
1254 * we don't get fooled into using T/TCP.
1256 if (to.to_flags & TOF_CCECHO) {
1257 if (tp->cc_send != to.to_ccecho) {
1258 if (taop->tao_ccsent != 0)
1261 rstreason = BANDLIM_UNLIMITED;
1266 tp->t_flags &= ~TF_RCVD_CC;
1267 tcpstat.tcps_connects++;
1269 /* Do window scaling on this connection? */
1270 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1271 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1272 tp->snd_scale = tp->requested_s_scale;
1273 tp->rcv_scale = tp->request_r_scale;
1275 /* Segment is acceptable, update cache if undefined. */
1276 if (taop->tao_ccsent == 0)
1277 taop->tao_ccsent = to.to_ccecho;
1279 tp->rcv_adv += tp->rcv_wnd;
1280 tp->snd_una++; /* SYN is acked */
1282 * If there's data, delay ACK; if there's also a FIN
1283 * ACKNOW will be turned on later.
1285 if (DELAY_ACK(tp) && tlen != 0)
1286 callout_reset(tp->tt_delack, tcp_delacktime,
1287 tcp_timer_delack, tp);
1289 tp->t_flags |= TF_ACKNOW;
1291 * Received <SYN,ACK> in SYN_SENT[*] state.
1293 * SYN_SENT --> ESTABLISHED
1294 * SYN_SENT* --> FIN_WAIT_1
1296 tp->t_starttime = ticks;
1297 if (tp->t_flags & TF_NEEDFIN) {
1298 tp->t_state = TCPS_FIN_WAIT_1;
1299 tp->t_flags &= ~TF_NEEDFIN;
1302 tp->t_state = TCPS_ESTABLISHED;
1303 callout_reset(tp->tt_keep, tcp_keepidle,
1304 tcp_timer_keep, tp);
1308 * Received initial SYN in SYN-SENT[*] state =>
1309 * simultaneous open. If segment contains CC option
1310 * and there is a cached CC, apply TAO test.
1311 * If it succeeds, connection is * half-synchronized.
1312 * Otherwise, do 3-way handshake:
1313 * SYN-SENT -> SYN-RECEIVED
1314 * SYN-SENT* -> SYN-RECEIVED*
1315 * If there was no CC option, clear cached CC value.
1317 tp->t_flags |= TF_ACKNOW;
1318 callout_stop(tp->tt_rexmt);
1319 if (to.to_flags & TOF_CC) {
1320 if (taop->tao_cc != 0 &&
1321 CC_GT(to.to_cc, taop->tao_cc)) {
1323 * update cache and make transition:
1324 * SYN-SENT -> ESTABLISHED*
1325 * SYN-SENT* -> FIN-WAIT-1*
1327 taop->tao_cc = to.to_cc;
1328 tp->t_starttime = ticks;
1329 if (tp->t_flags & TF_NEEDFIN) {
1330 tp->t_state = TCPS_FIN_WAIT_1;
1331 tp->t_flags &= ~TF_NEEDFIN;
1333 tp->t_state = TCPS_ESTABLISHED;
1334 callout_reset(tp->tt_keep,
1339 tp->t_flags |= TF_NEEDSYN;
1341 tp->t_state = TCPS_SYN_RECEIVED;
1343 /* CC.NEW or no option => invalidate cache */
1345 tp->t_state = TCPS_SYN_RECEIVED;
1351 * Advance th->th_seq to correspond to first data byte.
1352 * If data, trim to stay within window,
1353 * dropping FIN if necessary.
1356 if (tlen > tp->rcv_wnd) {
1357 todrop = tlen - tp->rcv_wnd;
1361 tcpstat.tcps_rcvpackafterwin++;
1362 tcpstat.tcps_rcvbyteafterwin += todrop;
1364 tp->snd_wl1 = th->th_seq - 1;
1365 tp->rcv_up = th->th_seq;
1367 * Client side of transaction: already sent SYN and data.
1368 * If the remote host used T/TCP to validate the SYN,
1369 * our data will be ACK'd; if so, enter normal data segment
1370 * processing in the middle of step 5, ack processing.
1371 * Otherwise, goto step 6.
1373 if (thflags & TH_ACK)
1379 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1380 * if segment contains a SYN and CC [not CC.NEW] option:
1381 * if state == TIME_WAIT and connection duration > MSL,
1382 * drop packet and send RST;
1384 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1385 * ack the FIN (and data) in retransmission queue.
1386 * Complete close and delete TCPCB. Then reprocess
1387 * segment, hoping to find new TCPCB in LISTEN state;
1389 * else must be old SYN; drop it.
1390 * else do normal processing.
1394 case TCPS_TIME_WAIT:
1395 if ((thflags & TH_SYN) &&
1396 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1397 if (tp->t_state == TCPS_TIME_WAIT &&
1398 (ticks - tp->t_starttime) > tcp_msl) {
1399 rstreason = BANDLIM_UNLIMITED;
1402 if (CC_GT(to.to_cc, tp->cc_recv)) {
1409 break; /* continue normal processing */
1413 * States other than LISTEN or SYN_SENT.
1414 * First check the RST flag and sequence number since reset segments
1415 * are exempt from the timestamp and connection count tests. This
1416 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1417 * below which allowed reset segments in half the sequence space
1418 * to fall though and be processed (which gives forged reset
1419 * segments with a random sequence number a 50 percent chance of
1420 * killing a connection).
1421 * Then check timestamp, if present.
1422 * Then check the connection count, if present.
1423 * Then check that at least some bytes of segment are within
1424 * receive window. If segment begins before rcv_nxt,
1425 * drop leading data (and SYN); if nothing left, just ack.
1428 * If the RST bit is set, check the sequence number to see
1429 * if this is a valid reset segment.
1431 * In all states except SYN-SENT, all reset (RST) segments
1432 * are validated by checking their SEQ-fields. A reset is
1433 * valid if its sequence number is in the window.
1434 * Note: this does not take into account delayed ACKs, so
1435 * we should test against last_ack_sent instead of rcv_nxt.
1436 * The sequence number in the reset segment is normally an
1437 * echo of our outgoing acknowlegement numbers, but some hosts
1438 * send a reset with the sequence number at the rightmost edge
1439 * of our receive window, and we have to handle this case.
1440 * If we have multiple segments in flight, the intial reset
1441 * segment sequence numbers will be to the left of last_ack_sent,
1442 * but they will eventually catch up.
1443 * In any case, it never made sense to trim reset segments to
1444 * fit the receive window since RFC 1122 says:
1445 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1447 * A TCP SHOULD allow a received RST segment to include data.
1450 * It has been suggested that a RST segment could contain
1451 * ASCII text that encoded and explained the cause of the
1452 * RST. No standard has yet been established for such
1455 * If the reset segment passes the sequence number test examine
1457 * SYN_RECEIVED STATE:
1458 * If passive open, return to LISTEN state.
1459 * If active open, inform user that connection was refused.
1460 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1461 * Inform user that connection was reset, and close tcb.
1462 * CLOSING, LAST_ACK STATES:
1465 * Drop the segment - see Stevens, vol. 2, p. 964 and
1468 if (thflags & TH_RST) {
1469 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1470 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1471 switch (tp->t_state) {
1473 case TCPS_SYN_RECEIVED:
1474 so->so_error = ECONNREFUSED;
1477 case TCPS_ESTABLISHED:
1478 case TCPS_FIN_WAIT_1:
1479 case TCPS_FIN_WAIT_2:
1480 case TCPS_CLOSE_WAIT:
1481 so->so_error = ECONNRESET;
1483 tp->t_state = TCPS_CLOSED;
1484 tcpstat.tcps_drops++;
1493 case TCPS_TIME_WAIT:
1501 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1502 * and it's less than ts_recent, drop it.
1504 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1505 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1507 /* Check to see if ts_recent is over 24 days old. */
1508 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1510 * Invalidate ts_recent. If this segment updates
1511 * ts_recent, the age will be reset later and ts_recent
1512 * will get a valid value. If it does not, setting
1513 * ts_recent to zero will at least satisfy the
1514 * requirement that zero be placed in the timestamp
1515 * echo reply when ts_recent isn't valid. The
1516 * age isn't reset until we get a valid ts_recent
1517 * because we don't want out-of-order segments to be
1518 * dropped when ts_recent is old.
1522 tcpstat.tcps_rcvduppack++;
1523 tcpstat.tcps_rcvdupbyte += tlen;
1524 tcpstat.tcps_pawsdrop++;
1533 * If T/TCP was negotiated and the segment doesn't have CC,
1534 * or if its CC is wrong then drop the segment.
1535 * RST segments do not have to comply with this.
1537 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1538 (!(to.to_flags & TOF_CC) || tp->cc_recv != to.to_cc))
1542 * In the SYN-RECEIVED state, validate that the packet belongs to
1543 * this connection before trimming the data to fit the receive
1544 * window. Check the sequence number versus IRS since we know
1545 * the sequence numbers haven't wrapped. This is a partial fix
1546 * for the "LAND" DoS attack.
1548 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1549 rstreason = BANDLIM_RST_OPENPORT;
1553 todrop = tp->rcv_nxt - th->th_seq;
1555 if (thflags & TH_SYN) {
1565 * Following if statement from Stevens, vol. 2, p. 960.
1567 if (todrop > tlen ||
1568 (todrop == tlen && !(thflags & TH_FIN))) {
1570 * Any valid FIN must be to the left of the window.
1571 * At this point the FIN must be a duplicate or out
1572 * of sequence; drop it.
1577 * Send an ACK to resynchronize and drop any data.
1578 * But keep on processing for RST or ACK.
1580 tp->t_flags |= TF_ACKNOW;
1582 tcpstat.tcps_rcvduppack++;
1583 tcpstat.tcps_rcvdupbyte += todrop;
1585 tcpstat.tcps_rcvpartduppack++;
1586 tcpstat.tcps_rcvpartdupbyte += todrop;
1588 drop_hdrlen += todrop; /* drop from the top afterwards */
1589 th->th_seq += todrop;
1591 if (th->th_urp > todrop)
1592 th->th_urp -= todrop;
1600 * If new data are received on a connection after the
1601 * user processes are gone, then RST the other end.
1603 if ((so->so_state & SS_NOFDREF) &&
1604 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1606 tcpstat.tcps_rcvafterclose++;
1607 rstreason = BANDLIM_UNLIMITED;
1612 * If segment ends after window, drop trailing data
1613 * (and PUSH and FIN); if nothing left, just ACK.
1615 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1617 tcpstat.tcps_rcvpackafterwin++;
1618 if (todrop >= tlen) {
1619 tcpstat.tcps_rcvbyteafterwin += tlen;
1621 * If a new connection request is received
1622 * while in TIME_WAIT, drop the old connection
1623 * and start over if the sequence numbers
1624 * are above the previous ones.
1626 if (thflags & TH_SYN &&
1627 tp->t_state == TCPS_TIME_WAIT &&
1628 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1633 * If window is closed can only take segments at
1634 * window edge, and have to drop data and PUSH from
1635 * incoming segments. Continue processing, but
1636 * remember to ack. Otherwise, drop segment
1639 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1640 tp->t_flags |= TF_ACKNOW;
1641 tcpstat.tcps_rcvwinprobe++;
1645 tcpstat.tcps_rcvbyteafterwin += todrop;
1648 thflags &= ~(TH_PUSH | TH_FIN);
1652 * If last ACK falls within this segment's sequence numbers,
1653 * record its timestamp.
1654 * NOTE that the test is modified according to the latest
1655 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1657 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1658 tp->ts_recent_age = ticks;
1659 tp->ts_recent = to.to_tsval;
1663 * If a SYN is in the window, then this is an
1664 * error and we send an RST and drop the connection.
1666 if (thflags & TH_SYN) {
1667 tp = tcp_drop(tp, ECONNRESET);
1668 rstreason = BANDLIM_UNLIMITED;
1673 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1674 * flag is on (half-synchronized state), then queue data for
1675 * later processing; else drop segment and return.
1677 if (!(thflags & TH_ACK)) {
1678 if (tp->t_state == TCPS_SYN_RECEIVED ||
1679 (tp->t_flags & TF_NEEDSYN))
1688 switch (tp->t_state) {
1690 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1691 * ESTABLISHED state and continue processing.
1692 * The ACK was checked above.
1694 case TCPS_SYN_RECEIVED:
1696 tcpstat.tcps_connects++;
1698 /* Do window scaling? */
1699 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1700 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1701 tp->snd_scale = tp->requested_s_scale;
1702 tp->rcv_scale = tp->request_r_scale;
1705 * Upon successful completion of 3-way handshake,
1706 * update cache.CC if it was undefined, pass any queued
1707 * data to the user, and advance state appropriately.
1709 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1711 taop->tao_cc = tp->cc_recv;
1715 * SYN-RECEIVED -> ESTABLISHED
1716 * SYN-RECEIVED* -> FIN-WAIT-1
1718 tp->t_starttime = ticks;
1719 if (tp->t_flags & TF_NEEDFIN) {
1720 tp->t_state = TCPS_FIN_WAIT_1;
1721 tp->t_flags &= ~TF_NEEDFIN;
1723 tp->t_state = TCPS_ESTABLISHED;
1724 callout_reset(tp->tt_keep, tcp_keepidle,
1725 tcp_timer_keep, tp);
1728 * If segment contains data or ACK, will call tcp_reass()
1729 * later; if not, do so now to pass queued data to user.
1731 if (tlen == 0 && !(thflags & TH_FIN))
1732 (void) tcp_reass(tp, NULL, NULL, NULL);
1736 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1737 * ACKs. If the ack is in the range
1738 * tp->snd_una < th->th_ack <= tp->snd_max
1739 * then advance tp->snd_una to th->th_ack and drop
1740 * data from the retransmission queue. If this ACK reflects
1741 * more up to date window information we update our window information.
1743 case TCPS_ESTABLISHED:
1744 case TCPS_FIN_WAIT_1:
1745 case TCPS_FIN_WAIT_2:
1746 case TCPS_CLOSE_WAIT:
1749 case TCPS_TIME_WAIT:
1751 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1752 if (tlen != 0 || tiwin != tp->snd_wnd) {
1756 tcpstat.tcps_rcvdupack++;
1758 * If we have outstanding data (other than
1759 * a window probe), this is a completely
1760 * duplicate ack (ie, window info didn't
1761 * change), the ack is the biggest we've
1762 * seen and we've seen exactly our rexmt
1763 * threshhold of them, assume a packet
1764 * has been dropped and retransmit it.
1765 * Kludge snd_nxt & the congestion
1766 * window so we send only this one
1769 * We know we're losing at the current
1770 * window size so do congestion avoidance
1771 * (set ssthresh to half the current window
1772 * and pull our congestion window back to
1773 * the new ssthresh).
1775 * Dup acks mean that packets have left the
1776 * network (they're now cached at the receiver)
1777 * so bump cwnd by the amount in the receiver
1778 * to keep a constant cwnd packets in the
1781 if (!callout_active(tp->tt_rexmt) ||
1782 th->th_ack != tp->snd_una) {
1786 if (IN_FASTRECOVERY(tp)) {
1787 tp->snd_cwnd += tp->t_maxseg;
1788 (void) tcp_output(tp);
1789 } else if (++tp->t_dupacks == tcprexmtthresh) {
1793 if (SEQ_LEQ(th->th_ack, tp->snd_recover)) {
1798 if (tcp_do_eifel_detect &&
1799 (tp->t_flags & TF_RCVD_TSTMP)) {
1800 tcp_save_congestion_state(tp);
1801 tp->t_flags |= TF_FASTREXMT;
1803 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1807 tp->snd_ssthresh = win * tp->t_maxseg;
1808 ENTER_FASTRECOVERY(tp);
1809 tp->snd_recover = tp->snd_max;
1810 callout_stop(tp->tt_rexmt);
1813 tp->snd_nxt = th->th_ack;
1814 tp->snd_cwnd = tp->t_maxseg;
1815 (void) tcp_output(tp);
1816 ++tcpstat.tcps_sndfastrexmit;
1817 KASSERT(tp->snd_limited <= 2,
1818 ("tp->snd_limited too big"));
1819 tp->snd_cwnd = tp->snd_ssthresh +
1821 (tp->t_dupacks - tp->snd_limited));
1822 if (SEQ_GT(onxt, tp->snd_nxt))
1824 } else if (tcp_do_limitedtransmit) {
1825 u_long oldcwnd = tp->snd_cwnd;
1826 tcp_seq oldsndmax = tp->snd_max;
1827 /* outstanding data */
1828 uint32_t ownd = tp->snd_max - tp->snd_una;
1831 #define iceildiv(n, d) (((n)+(d)-1) / (d))
1833 KASSERT(tp->t_dupacks == 1 ||
1835 ("dupacks not 1 or 2"));
1836 if (tp->t_dupacks == 1)
1837 tp->snd_limited = 0;
1838 tp->snd_cwnd = ownd +
1839 (tp->t_dupacks - tp->snd_limited) *
1841 (void) tcp_output(tp);
1842 tp->snd_cwnd = oldcwnd;
1843 sent = tp->snd_max - oldsndmax;
1844 if (sent > tp->t_maxseg) {
1845 KASSERT((tp->t_dupacks == 2 &&
1846 tp->snd_limited == 0) ||
1847 (sent == tp->t_maxseg + 1 &&
1848 tp->t_flags & TF_SENTFIN),
1850 KASSERT(sent <= tp->t_maxseg * 2,
1851 ("sent too many segments"));
1852 tp->snd_limited = 2;
1853 tcpstat.tcps_sndlimited += 2;
1854 } else if (sent > 0) {
1856 ++tcpstat.tcps_sndlimited;
1857 } else if (tcp_do_early_retransmit &&
1858 (tcp_do_eifel_detect &&
1859 (tp->t_flags & TF_RCVD_TSTMP)) &&
1860 tp->t_dupacks + 1 >=
1861 iceildiv(ownd, tp->t_maxseg)) {
1862 ++tcpstat.tcps_sndearlyrexmit;
1863 tp->t_flags |= TF_EARLYREXMT;
1864 goto fastretransmit;
1870 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1873 * If the congestion window was inflated to account
1874 * for the other side's cached packets, retract it.
1876 if (IN_FASTRECOVERY(tp)) {
1877 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1878 tcp_newreno_partial_ack(tp, th);
1881 * Window inflation should have left us
1882 * with approximately snd_ssthresh
1884 * But in case we would be inclined to
1885 * send a burst, better to do it via
1886 * the slow start mechanism.
1888 if (SEQ_GT(th->th_ack + tp->snd_ssthresh,
1890 tp->snd_cwnd = tp->snd_max -
1891 th->th_ack + tp->t_maxseg;
1893 tp->snd_cwnd = tp->snd_ssthresh;
1897 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1899 * Detected optimistic ACK attack.
1900 * Force slow-start to de-synchronize attack.
1902 tp->snd_cwnd = tp->t_maxseg;
1904 tcpstat.tcps_rcvacktoomuch++;
1908 * If we reach this point, ACK is not a duplicate,
1909 * i.e., it ACKs something we sent.
1911 if (tp->t_flags & TF_NEEDSYN) {
1913 * T/TCP: Connection was half-synchronized, and our
1914 * SYN has been ACK'd (so connection is now fully
1915 * synchronized). Go to non-starred state,
1916 * increment snd_una for ACK of SYN, and check if
1917 * we can do window scaling.
1919 tp->t_flags &= ~TF_NEEDSYN;
1921 /* Do window scaling? */
1922 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1923 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1924 tp->snd_scale = tp->requested_s_scale;
1925 tp->rcv_scale = tp->request_r_scale;
1930 acked = th->th_ack - tp->snd_una;
1931 tcpstat.tcps_rcvackpack++;
1932 tcpstat.tcps_rcvackbyte += acked;
1935 * If we just performed our first retransmit, and the ACK
1936 * arrives within our recovery window, then it was a mistake
1937 * to do the retransmit in the first place. Recover our
1938 * original cwnd and ssthresh, and proceed to transmit where
1941 if (tcp_do_eifel_detect && acked &&
1942 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
1943 (tp->t_flags & TF_FIRSTACCACK)) {
1944 /* Eifel detection applicable. */
1945 if (to.to_tsecr < tp->t_rexmtTS) {
1946 ++tcpstat.tcps_eifeldetected;
1947 tcp_revert_congestion_state(tp);
1948 if (tp->t_rxtshift == 1 &&
1949 ticks >= tp->t_badrxtwin)
1950 ++tcpstat.tcps_rttcantdetect;
1952 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1953 tcp_revert_congestion_state(tp);
1954 ++tcpstat.tcps_rttdetected;
1958 * If we have a timestamp reply, update smoothed
1959 * round trip time. If no timestamp is present but
1960 * transmit timer is running and timed sequence
1961 * number was acked, update smoothed round trip time.
1962 * Since we now have an rtt measurement, cancel the
1963 * timer backoff (cf., Phil Karn's retransmit alg.).
1964 * Recompute the initial retransmit timer.
1966 * Some machines (certain windows boxes) send broken
1967 * timestamp replies during the SYN+ACK phase, ignore
1970 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
1971 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1972 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
1973 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1974 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1977 * If all outstanding data is acked, stop retransmit
1978 * timer and remember to restart (more output or persist).
1979 * If there is more data to be acked, restart retransmit
1980 * timer, using current (possibly backed-off) value.
1982 if (th->th_ack == tp->snd_max) {
1983 callout_stop(tp->tt_rexmt);
1985 } else if (!callout_active(tp->tt_persist))
1986 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1987 tcp_timer_rexmt, tp);
1990 * If no data (only SYN) was ACK'd,
1991 * skip rest of ACK processing.
1996 /* Stop looking for an acceptable ACK since one was received. */
1997 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2000 * When new data is acked, open the congestion window.
2001 * If the window gives us less than ssthresh packets
2002 * in flight, open exponentially (maxseg per packet).
2003 * Otherwise open linearly: maxseg per window
2004 * (maxseg^2 / cwnd per packet).
2006 if (!IN_FASTRECOVERY(tp)) {
2007 u_int cw = tp->snd_cwnd;
2008 u_int incr = tp->t_maxseg;
2010 if (cw > tp->snd_ssthresh)
2011 incr = incr * incr / cw;
2012 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2014 if (acked > so->so_snd.sb_cc) {
2015 tp->snd_wnd -= so->so_snd.sb_cc;
2016 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2017 ourfinisacked = TRUE;
2019 sbdrop(&so->so_snd, acked);
2020 tp->snd_wnd -= acked;
2021 ourfinisacked = FALSE;
2024 if (IN_FASTRECOVERY(tp)) {
2025 if (SEQ_GEQ(th->th_ack, tp->snd_recover))
2026 EXIT_FASTRECOVERY(tp);
2028 tp->snd_recover = th->th_ack - 1;
2030 tp->snd_una = th->th_ack;
2031 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2032 tp->snd_nxt = tp->snd_una;
2034 switch (tp->t_state) {
2037 * In FIN_WAIT_1 STATE in addition to the processing
2038 * for the ESTABLISHED state if our FIN is now acknowledged
2039 * then enter FIN_WAIT_2.
2041 case TCPS_FIN_WAIT_1:
2042 if (ourfinisacked) {
2044 * If we can't receive any more
2045 * data, then closing user can proceed.
2046 * Starting the timer is contrary to the
2047 * specification, but if we don't get a FIN
2048 * we'll hang forever.
2050 if (so->so_state & SS_CANTRCVMORE) {
2051 soisdisconnected(so);
2052 callout_reset(tp->tt_2msl, tcp_maxidle,
2053 tcp_timer_2msl, tp);
2055 tp->t_state = TCPS_FIN_WAIT_2;
2060 * In CLOSING STATE in addition to the processing for
2061 * the ESTABLISHED state if the ACK acknowledges our FIN
2062 * then enter the TIME-WAIT state, otherwise ignore
2066 if (ourfinisacked) {
2067 tp->t_state = TCPS_TIME_WAIT;
2068 tcp_canceltimers(tp);
2069 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2070 if (tp->cc_recv != 0 &&
2071 (ticks - tp->t_starttime) < tcp_msl)
2072 callout_reset(tp->tt_2msl,
2075 tcp_timer_2msl, tp);
2077 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2078 tcp_timer_2msl, tp);
2079 soisdisconnected(so);
2084 * In LAST_ACK, we may still be waiting for data to drain
2085 * and/or to be acked, as well as for the ack of our FIN.
2086 * If our FIN is now acknowledged, delete the TCB,
2087 * enter the closed state and return.
2090 if (ourfinisacked) {
2097 * In TIME_WAIT state the only thing that should arrive
2098 * is a retransmission of the remote FIN. Acknowledge
2099 * it and restart the finack timer.
2101 case TCPS_TIME_WAIT:
2102 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2103 tcp_timer_2msl, tp);
2110 * Update window information.
2111 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2113 if ((thflags & TH_ACK) &&
2114 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2115 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2116 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2117 /* keep track of pure window updates */
2119 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2120 tcpstat.tcps_rcvwinupd++;
2121 tp->snd_wnd = tiwin;
2122 tp->snd_wl1 = th->th_seq;
2123 tp->snd_wl2 = th->th_ack;
2124 if (tp->snd_wnd > tp->max_sndwnd)
2125 tp->max_sndwnd = tp->snd_wnd;
2130 * Process segments with URG.
2132 if ((thflags & TH_URG) && th->th_urp &&
2133 !TCPS_HAVERCVDFIN(tp->t_state)) {
2135 * This is a kludge, but if we receive and accept
2136 * random urgent pointers, we'll crash in
2137 * soreceive. It's hard to imagine someone
2138 * actually wanting to send this much urgent data.
2140 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2141 th->th_urp = 0; /* XXX */
2142 thflags &= ~TH_URG; /* XXX */
2143 goto dodata; /* XXX */
2146 * If this segment advances the known urgent pointer,
2147 * then mark the data stream. This should not happen
2148 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2149 * a FIN has been received from the remote side.
2150 * In these states we ignore the URG.
2152 * According to RFC961 (Assigned Protocols),
2153 * the urgent pointer points to the last octet
2154 * of urgent data. We continue, however,
2155 * to consider it to indicate the first octet
2156 * of data past the urgent section as the original
2157 * spec states (in one of two places).
2159 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2160 tp->rcv_up = th->th_seq + th->th_urp;
2161 so->so_oobmark = so->so_rcv.sb_cc +
2162 (tp->rcv_up - tp->rcv_nxt) - 1;
2163 if (so->so_oobmark == 0)
2164 so->so_state |= SS_RCVATMARK;
2166 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2169 * Remove out of band data so doesn't get presented to user.
2170 * This can happen independent of advancing the URG pointer,
2171 * but if two URG's are pending at once, some out-of-band
2172 * data may creep in... ick.
2174 if (th->th_urp <= (u_long)tlen &&
2175 !(so->so_options & SO_OOBINLINE)) {
2176 /* hdr drop is delayed */
2177 tcp_pulloutofband(so, th, m, drop_hdrlen);
2181 * If no out of band data is expected,
2182 * pull receive urgent pointer along
2183 * with the receive window.
2185 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2186 tp->rcv_up = tp->rcv_nxt;
2191 * Process the segment text, merging it into the TCP sequencing queue,
2192 * and arranging for acknowledgment of receipt if necessary.
2193 * This process logically involves adjusting tp->rcv_wnd as data
2194 * is presented to the user (this happens in tcp_usrreq.c,
2195 * case PRU_RCVD). If a FIN has already been received on this
2196 * connection then we just ignore the text.
2198 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2199 m_adj(m, drop_hdrlen); /* delayed header drop */
2201 * Insert segment which includes th into TCP reassembly queue
2202 * with control block tp. Set thflags to whether reassembly now
2203 * includes a segment with FIN. This handles the common case
2204 * inline (segment is the next to be received on an established
2205 * connection, and the queue is empty), avoiding linkage into
2206 * and removal from the queue and repetition of various
2208 * Set DELACK for segments received in order, but ack
2209 * immediately when segments are out of order (so
2210 * fast retransmit can work).
2212 if (th->th_seq == tp->rcv_nxt &&
2213 LIST_EMPTY(&tp->t_segq) &&
2214 TCPS_HAVEESTABLISHED(tp->t_state)) {
2216 callout_reset(tp->tt_delack, tcp_delacktime,
2217 tcp_timer_delack, tp);
2219 tp->t_flags |= TF_ACKNOW;
2220 tp->rcv_nxt += tlen;
2221 thflags = th->th_flags & TH_FIN;
2222 tcpstat.tcps_rcvpack++;
2223 tcpstat.tcps_rcvbyte += tlen;
2225 if (so->so_state & SS_CANTRCVMORE)
2228 sbappend(&so->so_rcv, m);
2231 thflags = tcp_reass(tp, th, &tlen, m);
2232 tp->t_flags |= TF_ACKNOW;
2236 * Note the amount of data that peer has sent into
2237 * our window, in order to estimate the sender's
2240 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2247 * If FIN is received ACK the FIN and let the user know
2248 * that the connection is closing.
2250 if (thflags & TH_FIN) {
2251 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2254 * If connection is half-synchronized
2255 * (ie NEEDSYN flag on) then delay ACK,
2256 * so it may be piggybacked when SYN is sent.
2257 * Otherwise, since we received a FIN then no
2258 * more input can be expected, send ACK now.
2260 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2261 callout_reset(tp->tt_delack, tcp_delacktime,
2262 tcp_timer_delack, tp);
2264 tp->t_flags |= TF_ACKNOW;
2268 switch (tp->t_state) {
2270 * In SYN_RECEIVED and ESTABLISHED STATES
2271 * enter the CLOSE_WAIT state.
2273 case TCPS_SYN_RECEIVED:
2274 tp->t_starttime = ticks;
2276 case TCPS_ESTABLISHED:
2277 tp->t_state = TCPS_CLOSE_WAIT;
2281 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2282 * enter the CLOSING state.
2284 case TCPS_FIN_WAIT_1:
2285 tp->t_state = TCPS_CLOSING;
2289 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2290 * starting the time-wait timer, turning off the other
2293 case TCPS_FIN_WAIT_2:
2294 tp->t_state = TCPS_TIME_WAIT;
2295 tcp_canceltimers(tp);
2296 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2297 if (tp->cc_recv != 0 &&
2298 (ticks - tp->t_starttime) < tcp_msl) {
2299 callout_reset(tp->tt_2msl,
2300 tp->t_rxtcur * TCPTV_TWTRUNC,
2301 tcp_timer_2msl, tp);
2302 /* For transaction client, force ACK now. */
2303 tp->t_flags |= TF_ACKNOW;
2306 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2307 tcp_timer_2msl, tp);
2308 soisdisconnected(so);
2312 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2314 case TCPS_TIME_WAIT:
2315 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2316 tcp_timer_2msl, tp);
2322 if (so->so_options & SO_DEBUG)
2323 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2328 * Return any desired output.
2330 if (needoutput || (tp->t_flags & TF_ACKNOW))
2331 (void) tcp_output(tp);
2336 * Generate an ACK dropping incoming segment if it occupies
2337 * sequence space, where the ACK reflects our state.
2339 * We can now skip the test for the RST flag since all
2340 * paths to this code happen after packets containing
2341 * RST have been dropped.
2343 * In the SYN-RECEIVED state, don't send an ACK unless the
2344 * segment we received passes the SYN-RECEIVED ACK test.
2345 * If it fails send a RST. This breaks the loop in the
2346 * "LAND" DoS attack, and also prevents an ACK storm
2347 * between two listening ports that have been sent forged
2348 * SYN segments, each with the source address of the other.
2350 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2351 (SEQ_GT(tp->snd_una, th->th_ack) ||
2352 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2353 rstreason = BANDLIM_RST_OPENPORT;
2357 if (so->so_options & SO_DEBUG)
2358 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2362 tp->t_flags |= TF_ACKNOW;
2363 (void) tcp_output(tp);
2368 * Generate a RST, dropping incoming segment.
2369 * Make ACK acceptable to originator of segment.
2370 * Don't bother to respond if destination was broadcast/multicast.
2372 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2375 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2376 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2379 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2380 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2381 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2382 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2385 /* IPv6 anycast check is done at tcp6_input() */
2388 * Perform bandwidth limiting.
2391 if (badport_bandlim(rstreason) < 0)
2396 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2397 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2400 if (thflags & TH_ACK)
2401 /* mtod() below is safe as long as hdr dropping is delayed */
2402 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2405 if (thflags & TH_SYN)
2407 /* mtod() below is safe as long as hdr dropping is delayed */
2408 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2409 (tcp_seq)0, TH_RST | TH_ACK);
2415 * Drop space held by incoming segment and return.
2418 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2419 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2427 * Parse TCP options and place in tcpopt.
2430 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2435 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2437 if (opt == TCPOPT_EOL)
2439 if (opt == TCPOPT_NOP)
2445 if (optlen < 2 || optlen > cnt)
2450 if (optlen != TCPOLEN_MAXSEG)
2454 to->to_flags |= TOF_MSS;
2455 bcopy(cp + 2, &to->to_mss, sizeof(to->to_mss));
2456 to->to_mss = ntohs(to->to_mss);
2459 if (optlen != TCPOLEN_WINDOW)
2463 to->to_flags |= TOF_SCALE;
2464 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2466 case TCPOPT_TIMESTAMP:
2467 if (optlen != TCPOLEN_TIMESTAMP)
2469 to->to_flags |= TOF_TS;
2470 bcopy(cp + 2, &to->to_tsval, sizeof(to->to_tsval));
2471 to->to_tsval = ntohl(to->to_tsval);
2472 bcopy(cp + 6, &to->to_tsecr, sizeof(to->to_tsecr));
2473 to->to_tsecr = ntohl(to->to_tsecr);
2476 if (optlen != TCPOLEN_CC)
2478 to->to_flags |= TOF_CC;
2479 bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
2480 to->to_cc = ntohl(to->to_cc);
2483 if (optlen != TCPOLEN_CC)
2487 to->to_flags |= TOF_CCNEW;
2488 bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
2489 to->to_cc = ntohl(to->to_cc);
2492 if (optlen != TCPOLEN_CC)
2496 to->to_flags |= TOF_CCECHO;
2497 bcopy(cp + 2, &to->to_ccecho, sizeof(to->to_ccecho));
2498 to->to_ccecho = ntohl(to->to_ccecho);
2507 * Pull out of band byte out of a segment so
2508 * it doesn't appear in the user's data queue.
2509 * It is still reflected in the segment length for
2510 * sequencing purposes.
2511 * "off" is the delayed to be dropped hdrlen.
2514 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2516 int cnt = off + th->th_urp - 1;
2519 if (m->m_len > cnt) {
2520 char *cp = mtod(m, caddr_t) + cnt;
2521 struct tcpcb *tp = sototcpcb(so);
2524 tp->t_oobflags |= TCPOOB_HAVEDATA;
2525 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2527 if (m->m_flags & M_PKTHDR)
2536 panic("tcp_pulloutofband");
2540 * Collect new round-trip time estimate
2541 * and update averages and current timeout.
2544 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2548 tcpstat.tcps_rttupdated++;
2550 if (tp->t_srtt != 0) {
2552 * srtt is stored as fixed point with 5 bits after the
2553 * binary point (i.e., scaled by 8). The following magic
2554 * is equivalent to the smoothing algorithm in rfc793 with
2555 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2556 * point). Adjust rtt to origin 0.
2558 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2559 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2561 if ((tp->t_srtt += delta) <= 0)
2565 * We accumulate a smoothed rtt variance (actually, a
2566 * smoothed mean difference), then set the retransmit
2567 * timer to smoothed rtt + 4 times the smoothed variance.
2568 * rttvar is stored as fixed point with 4 bits after the
2569 * binary point (scaled by 16). The following is
2570 * equivalent to rfc793 smoothing with an alpha of .75
2571 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2572 * rfc793's wired-in beta.
2576 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2577 if ((tp->t_rttvar += delta) <= 0)
2579 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2580 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2583 * No rtt measurement yet - use the unsmoothed rtt.
2584 * Set the variance to half the rtt (so our first
2585 * retransmit happens at 3*rtt).
2587 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2588 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2589 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2595 * the retransmit should happen at rtt + 4 * rttvar.
2596 * Because of the way we do the smoothing, srtt and rttvar
2597 * will each average +1/2 tick of bias. When we compute
2598 * the retransmit timer, we want 1/2 tick of rounding and
2599 * 1 extra tick because of +-1/2 tick uncertainty in the
2600 * firing of the timer. The bias will give us exactly the
2601 * 1.5 tick we need. But, because the bias is
2602 * statistical, we have to test that we don't drop below
2603 * the minimum feasible timer (which is 2 ticks).
2605 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2606 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2609 * We received an ack for a packet that wasn't retransmitted;
2610 * it is probably safe to discard any error indications we've
2611 * received recently. This isn't quite right, but close enough
2612 * for now (a route might have failed after we sent a segment,
2613 * and the return path might not be symmetrical).
2615 tp->t_softerror = 0;
2619 * Determine a reasonable value for maxseg size.
2620 * If the route is known, check route for mtu.
2621 * If none, use an mss that can be handled on the outgoing
2622 * interface without forcing IP to fragment; if bigger than
2623 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2624 * to utilize large mbufs. If no route is found, route has no mtu,
2625 * or the destination isn't local, use a default, hopefully conservative
2626 * size (usually 512 or the default IP max size, but no more than the mtu
2627 * of the interface), as we can't discover anything about intervening
2628 * gateways or networks. We also initialize the congestion/slow start
2629 * window to be a single segment if the destination isn't local.
2630 * While looking at the routing entry, we also initialize other path-dependent
2631 * parameters from pre-set or cached values in the routing entry.
2633 * Also take into account the space needed for options that we
2634 * send regularly. Make maxseg shorter by that amount to assure
2635 * that we can send maxseg amount of data even when the options
2636 * are present. Store the upper limit of the length of options plus
2639 * NOTE that this routine is only called when we process an incoming
2640 * segment, for outgoing segments only tcp_mssopt is called.
2642 * In case of T/TCP, we call this routine during implicit connection
2643 * setup as well (offer = -1), to initialize maxseg from the cached
2647 tcp_mss(struct tcpcb *tp, int offer)
2653 struct inpcb *inp = tp->t_inpcb;
2655 struct rmxp_tao *taop;
2656 int origoffer = offer;
2658 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2659 size_t min_protoh = isipv6 ?
2660 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2661 sizeof(struct tcpiphdr);
2663 const boolean_t isipv6 = FALSE;
2664 const size_t min_protoh = sizeof(struct tcpiphdr);
2668 rt = tcp_rtlookup6(&inp->inp_inc);
2670 rt = tcp_rtlookup(&inp->inp_inc);
2672 tp->t_maxopd = tp->t_maxseg =
2673 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2677 so = inp->inp_socket;
2679 taop = rmx_taop(rt->rt_rmx);
2681 * Offer == -1 means that we didn't receive SYN yet,
2682 * use cached value in that case;
2685 offer = taop->tao_mssopt;
2687 * Offer == 0 means that there was no MSS on the SYN segment,
2688 * in this case we use tcp_mssdflt.
2691 offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2694 * Sanity check: make sure that maxopd will be large
2695 * enough to allow some data on segments even is the
2696 * all the option space is used (40bytes). Otherwise
2697 * funny things may happen in tcp_output.
2699 offer = max(offer, 64);
2700 taop->tao_mssopt = offer;
2703 * While we're here, check if there's an initial rtt
2704 * or rttvar. Convert from the route-table units
2705 * to scaled multiples of the slow timeout timer.
2707 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2709 * XXX the lock bit for RTT indicates that the value
2710 * is also a minimum value; this is subject to time.
2712 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2713 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2714 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2715 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2716 tcpstat.tcps_usedrtt++;
2717 if (rt->rt_rmx.rmx_rttvar) {
2718 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2719 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2720 tcpstat.tcps_usedrttvar++;
2722 /* default variation is +- 1 rtt */
2724 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2726 TCPT_RANGESET(tp->t_rxtcur,
2727 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2728 tp->t_rttmin, TCPTV_REXMTMAX);
2731 * if there's an mtu associated with the route, use it
2732 * else, use the link mtu.
2734 if (rt->rt_rmx.rmx_mtu)
2735 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2738 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2740 if (!in6_localaddr(&inp->in6p_faddr))
2741 mss = min(mss, tcp_v6mssdflt);
2743 mss = ifp->if_mtu - min_protoh;
2744 if (!in_localaddr(inp->inp_faddr))
2745 mss = min(mss, tcp_mssdflt);
2748 mss = min(mss, offer);
2750 * maxopd stores the maximum length of data AND options
2751 * in a segment; maxseg is the amount of data in a normal
2752 * segment. We need to store this value (maxopd) apart
2753 * from maxseg, because now every segment carries options
2754 * and thus we normally have somewhat less data in segments.
2759 * In case of T/TCP, origoffer==-1 indicates, that no segments
2760 * were received yet. In this case we just guess, otherwise
2761 * we do the same as before T/TCP.
2763 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2765 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2766 mss -= TCPOLEN_TSTAMP_APPA;
2767 if ((tp->t_flags & (TF_REQ_CC | TF_NOOPT)) == TF_REQ_CC &&
2769 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2770 mss -= TCPOLEN_CC_APPA;
2772 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2774 mss &= ~(MCLBYTES-1);
2777 mss = mss / MCLBYTES * MCLBYTES;
2780 * If there's a pipesize, change the socket buffer
2781 * to that size. Make the socket buffers an integral
2782 * number of mss units; if the mss is larger than
2783 * the socket buffer, decrease the mss.
2786 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2788 bufsize = so->so_snd.sb_hiwat;
2792 bufsize = roundup(bufsize, mss);
2793 if (bufsize > sb_max)
2795 if (bufsize > so->so_snd.sb_hiwat)
2796 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2801 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2803 bufsize = so->so_rcv.sb_hiwat;
2804 if (bufsize > mss) {
2805 bufsize = roundup(bufsize, mss);
2806 if (bufsize > sb_max)
2808 if (bufsize > so->so_rcv.sb_hiwat)
2809 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2813 * Set the slow-start flight size depending on whether this
2814 * is a local network or not.
2817 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2818 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2819 (!isipv6 && in_localaddr(inp->inp_faddr)))
2820 tp->snd_cwnd = mss * ss_fltsz_local;
2822 tp->snd_cwnd = mss * ss_fltsz;
2824 if (rt->rt_rmx.rmx_ssthresh) {
2826 * There's some sort of gateway or interface
2827 * buffer limit on the path. Use this to set
2828 * the slow start threshhold, but set the
2829 * threshold to no less than 2*mss.
2831 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2832 tcpstat.tcps_usedssthresh++;
2837 * Determine the MSS option to send on an outgoing SYN.
2840 tcp_mssopt(struct tcpcb *tp)
2845 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2846 int min_protoh = isipv6 ?
2847 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2848 sizeof(struct tcpiphdr);
2850 const boolean_t isipv6 = FALSE;
2851 const size_t min_protoh = sizeof(struct tcpiphdr);
2855 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2857 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2859 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2861 return (rt->rt_ifp->if_mtu - min_protoh);
2865 * When a partial ack arrives, force the retransmission of the
2866 * next unacknowledged segment. Do not clear tp->t_dupacks.
2867 * By setting snd_nxt to th_ack, this forces retransmission timer to
2871 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
2873 tcp_seq onxt = tp->snd_nxt;
2874 u_long ocwnd = tp->snd_cwnd;
2876 callout_stop(tp->tt_rexmt);
2878 tp->snd_nxt = th->th_ack;
2880 * Set snd_cwnd to one segment beyond acknowledged offset
2881 * (tp->snd_una has not yet been updated when this function is called.)
2883 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2884 tp->t_flags |= TF_ACKNOW;
2885 (void) tcp_output(tp);
2886 tp->snd_cwnd = ocwnd;
2887 if (SEQ_GT(onxt, tp->snd_nxt))
2890 * Partial window deflation. Relies on fact that tp->snd_una
2893 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);