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"
39 #include "opt_tcp_input.h"
40 #include "opt_tcp_sack.h"
42 #include <sys/param.h>
43 #include <sys/kernel.h>
45 #include <sys/malloc.h>
47 #include <sys/proc.h> /* for proc0 declaration */
48 #include <sys/protosw.h>
49 #include <sys/signalvar.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/syslog.h>
54 #include <sys/systm.h>
56 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
61 #include <net/route.h>
63 #include <netinet/in.h>
64 #include <netinet/in_pcb.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
69 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
70 #include <netinet/ip_var.h>
71 #include <netinet/ip_options.h>
72 #include <netinet/ip6.h>
73 #include <netinet/icmp6.h>
74 #include <netinet6/in6_pcb.h>
75 #include <netinet6/ip6_var.h>
76 #include <netinet6/nd6.h>
77 #include <netinet/tcp.h>
78 #include <netinet/tcp_fsm.h>
79 #include <netinet/tcp_seq.h>
80 #include <netinet/tcp_timer.h>
81 #include <netinet/tcp_var.h>
82 #include <netinet6/tcp6_var.h>
83 #include <netinet/tcpip.h>
85 #include <netinet/tcp_debug.h>
89 #include <netipsec/ipsec.h>
90 #include <netipsec/ipsec6.h>
94 #include <netinet6/ipsec.h>
95 #include <netinet6/ipsec6.h>
96 #include <netkey/key.h>
99 #include <machine/in_cksum.h>
101 static const int tcprexmtthresh = 3;
103 struct tcpstat tcpstat;
104 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
105 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
107 static int log_in_vain = 0;
108 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
109 &log_in_vain, 0, "Log all incoming TCP connections");
111 static int blackhole = 0;
112 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
113 &blackhole, 0, "Do not send RST when dropping refused connections");
115 int tcp_delack_enabled = 1;
116 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
117 &tcp_delack_enabled, 0,
118 "Delay ACK to try and piggyback it onto a data packet");
120 #ifdef TCP_DROP_SYNFIN
121 static int drop_synfin = 0;
122 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
123 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
126 static int tcp_do_rfc3042 = 1;
127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
128 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
130 static int tcp_do_rfc3390 = 1;
131 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
133 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
135 static int tcp_insecure_rst = 0;
136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
137 &tcp_insecure_rst, 0,
138 "Follow the old (insecure) criteria for accepting RST packets.");
140 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
141 "TCP Segment Reassembly Queue");
143 static int tcp_reass_maxseg = 0;
144 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
145 &tcp_reass_maxseg, 0,
146 "Global maximum number of TCP Segments in Reassembly Queue");
148 int tcp_reass_qsize = 0;
149 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
151 "Global number of TCP Segments currently in Reassembly Queue");
153 static int tcp_reass_maxqlen = 48;
154 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
155 &tcp_reass_maxqlen, 0,
156 "Maximum number of TCP Segments per individual Reassembly Queue");
158 static int tcp_reass_overflows = 0;
159 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
160 &tcp_reass_overflows, 0,
161 "Global number of TCP Segment Reassembly Queue Overflows");
163 struct inpcbhead tcb;
164 #define tcb6 tcb /* for KAME src sync over BSD*'s */
165 struct inpcbinfo tcbinfo;
166 struct mtx *tcbinfo_mtx;
168 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
170 static void tcp_pulloutofband(struct socket *,
171 struct tcphdr *, struct mbuf *, int);
172 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
174 static void tcp_xmit_timer(struct tcpcb *, int);
175 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
176 static int tcp_timewait(struct inpcb *, struct tcpopt *,
177 struct tcphdr *, struct mbuf *, int);
179 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
181 #define ND6_HINT(tp) \
183 if ((tp) && (tp)->t_inpcb && \
184 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
185 nd6_nud_hint(NULL, NULL, 0); \
192 * Indicate whether this ack should be delayed. We can delay the ack if
193 * - there is no delayed ack timer in progress and
194 * - our last ack wasn't a 0-sized window. We never want to delay
195 * the ack that opens up a 0-sized window and
196 * - delayed acks are enabled or
197 * - this is a half-synchronized T/TCP connection.
199 #define DELAY_ACK(tp) \
200 ((!callout_active(tp->tt_delack) && \
201 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
202 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
204 /* Initialize TCP reassembly queue */
206 tcp_reass_zone_change(void *tag)
209 tcp_reass_maxseg = nmbclusters / 16;
210 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
213 uma_zone_t tcp_reass_zone;
217 tcp_reass_maxseg = nmbclusters / 16;
218 TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
220 tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
221 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
222 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
223 EVENTHANDLER_REGISTER(nmbclusters_change,
224 tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
228 tcp_reass(tp, th, tlenp, m)
229 register struct tcpcb *tp;
230 register struct tcphdr *th;
235 struct tseg_qent *p = NULL;
236 struct tseg_qent *nq;
237 struct tseg_qent *te = NULL;
238 struct socket *so = tp->t_inpcb->inp_socket;
241 INP_LOCK_ASSERT(tp->t_inpcb);
244 * XXX: tcp_reass() is rather inefficient with its data structures
245 * and should be rewritten (see NetBSD for optimizations). While
246 * doing that it should move to its own file tcp_reass.c.
250 * Call with th==NULL after become established to
251 * force pre-ESTABLISHED data up to user socket.
257 * Limit the number of segments in the reassembly queue to prevent
258 * holding on to too many segments (and thus running out of mbufs).
259 * Make sure to let the missing segment through which caused this
260 * queue. Always keep one global queue entry spare to be able to
261 * process the missing segment.
263 if (th->th_seq != tp->rcv_nxt &&
264 (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
265 tp->t_segqlen >= tcp_reass_maxqlen)) {
266 tcp_reass_overflows++;
267 tcpstat.tcps_rcvmemdrop++;
274 * Allocate a new queue entry. If we can't, or hit the zone limit
277 te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
279 tcpstat.tcps_rcvmemdrop++;
288 * Find a segment which begins after this one does.
290 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
291 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
297 * If there is a preceding segment, it may provide some of
298 * our data already. If so, drop the data from the incoming
299 * segment. If it provides all of our data, drop us.
303 /* conversion to int (in i) handles seq wraparound */
304 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
307 tcpstat.tcps_rcvduppack++;
308 tcpstat.tcps_rcvdupbyte += *tlenp;
310 uma_zfree(tcp_reass_zone, te);
314 * Try to present any queued data
315 * at the left window edge to the user.
316 * This is needed after the 3-WHS
319 goto present; /* ??? */
326 tcpstat.tcps_rcvoopack++;
327 tcpstat.tcps_rcvoobyte += *tlenp;
330 * While we overlap succeeding segments trim them or,
331 * if they are completely covered, dequeue them.
334 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
337 if (i < q->tqe_len) {
338 q->tqe_th->th_seq += i;
344 nq = LIST_NEXT(q, tqe_q);
345 LIST_REMOVE(q, tqe_q);
347 uma_zfree(tcp_reass_zone, q);
353 /* Insert the new segment queue entry into place. */
356 te->tqe_len = *tlenp;
359 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
361 LIST_INSERT_AFTER(p, te, tqe_q);
366 * Present data to user, advancing rcv_nxt through
367 * completed sequence space.
369 if (!TCPS_HAVEESTABLISHED(tp->t_state))
371 q = LIST_FIRST(&tp->t_segq);
372 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
374 SOCKBUF_LOCK(&so->so_rcv);
376 tp->rcv_nxt += q->tqe_len;
377 flags = q->tqe_th->th_flags & TH_FIN;
378 nq = LIST_NEXT(q, tqe_q);
379 LIST_REMOVE(q, tqe_q);
380 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
383 sbappendstream_locked(&so->so_rcv, q->tqe_m);
384 uma_zfree(tcp_reass_zone, q);
388 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
390 sorwakeup_locked(so);
395 * TCP input routine, follows pages 65-76 of the
396 * protocol specification dated September, 1981 very closely.
400 tcp6_input(mp, offp, proto)
404 register struct mbuf *m = *mp;
405 struct in6_ifaddr *ia6;
407 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
410 * draft-itojun-ipv6-tcp-to-anycast
411 * better place to put this in?
413 ia6 = ip6_getdstifaddr(m);
414 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
417 ip6 = mtod(m, struct ip6_hdr *);
418 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
419 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
430 register struct mbuf *m;
433 register struct tcphdr *th;
434 register struct ip *ip = NULL;
435 register struct ipovly *ipov;
436 register struct inpcb *inp = NULL;
441 register struct tcpcb *tp = 0;
442 register int thflags;
443 struct socket *so = 0;
444 int todrop, acked, ourfinisacked, needoutput = 0;
446 struct tcpopt to; /* options in this segment */
448 #ifdef IPFIREWALL_FORWARD
449 struct m_tag *fwd_tag;
451 int rstreason; /* For badport_bandlim accounting purposes */
453 struct ip6_hdr *ip6 = NULL;
457 const int isipv6 = 0;
462 * The size of tcp_saveipgen must be the size of the max ip header,
465 u_char tcp_saveipgen[40];
466 struct tcphdr tcp_savetcp;
471 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
473 bzero((char *)&to, sizeof(to));
475 tcpstat.tcps_rcvtotal++;
479 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
480 ip6 = mtod(m, struct ip6_hdr *);
481 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
482 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
483 tcpstat.tcps_rcvbadsum++;
486 th = (struct tcphdr *)((caddr_t)ip6 + off0);
489 * Be proactive about unspecified IPv6 address in source.
490 * As we use all-zero to indicate unbounded/unconnected pcb,
491 * unspecified IPv6 address can be used to confuse us.
493 * Note that packets with unspecified IPv6 destination is
494 * already dropped in ip6_input.
496 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
501 th = NULL; /* XXX: avoid compiler warning */
505 * Get IP and TCP header together in first mbuf.
506 * Note: IP leaves IP header in first mbuf.
508 if (off0 > sizeof (struct ip)) {
509 ip_stripoptions(m, (struct mbuf *)0);
510 off0 = sizeof(struct ip);
512 if (m->m_len < sizeof (struct tcpiphdr)) {
513 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
514 tcpstat.tcps_rcvshort++;
518 ip = mtod(m, struct ip *);
519 ipov = (struct ipovly *)ip;
520 th = (struct tcphdr *)((caddr_t)ip + off0);
523 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
524 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
525 th->th_sum = m->m_pkthdr.csum_data;
527 th->th_sum = in_pseudo(ip->ip_src.s_addr,
529 htonl(m->m_pkthdr.csum_data +
532 th->th_sum ^= 0xffff;
534 ipov->ih_len = (u_short)tlen;
535 ipov->ih_len = htons(ipov->ih_len);
539 * Checksum extended TCP header and data.
541 len = sizeof (struct ip) + tlen;
542 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
543 ipov->ih_len = (u_short)tlen;
544 ipov->ih_len = htons(ipov->ih_len);
545 th->th_sum = in_cksum(m, len);
548 tcpstat.tcps_rcvbadsum++;
552 /* Re-initialization for later version check */
553 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;
591 #ifdef TCP_DROP_SYNFIN
593 * If the drop_synfin option is enabled, drop all packets with
594 * both the SYN and FIN bits set. This prevents e.g. nmap from
595 * identifying the TCP/IP stack.
597 * This is a violation of the TCP specification.
599 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
604 * Convert TCP protocol specific fields to host format.
606 th->th_seq = ntohl(th->th_seq);
607 th->th_ack = ntohl(th->th_ack);
608 th->th_win = ntohs(th->th_win);
609 th->th_urp = ntohs(th->th_urp);
612 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
613 * until after ip6_savecontrol() is called and before other functions
614 * which don't want those proto headers.
615 * Because ip6_savecontrol() is going to parse the mbuf to
616 * search for data to be passed up to user-land, it wants mbuf
617 * parameters to be unchanged.
618 * XXX: the call of ip6_savecontrol() has been obsoleted based on
619 * latest version of the advanced API (20020110).
621 drop_hdrlen = off0 + off;
624 * Locate pcb for segment.
626 INP_INFO_WLOCK(&tcbinfo);
629 KASSERT(headlocked, ("tcp_input: findpcb: head not locked"));
630 #ifdef IPFIREWALL_FORWARD
631 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
632 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
634 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
635 struct sockaddr_in *next_hop;
637 next_hop = (struct sockaddr_in *)(fwd_tag+1);
639 * Transparently forwarded. Pretend to be the destination.
640 * already got one like this?
642 inp = in_pcblookup_hash(&tcbinfo,
643 ip->ip_src, th->th_sport,
644 ip->ip_dst, th->th_dport,
645 0, m->m_pkthdr.rcvif);
647 /* It's new. Try to find the ambushing socket. */
648 inp = in_pcblookup_hash(&tcbinfo,
649 ip->ip_src, th->th_sport,
652 ntohs(next_hop->sin_port) :
657 /* Remove the tag from the packet. We don't need it anymore. */
658 m_tag_delete(m, fwd_tag);
660 #endif /* IPFIREWALL_FORWARD */
663 inp = in6_pcblookup_hash(&tcbinfo,
664 &ip6->ip6_src, th->th_sport,
665 &ip6->ip6_dst, th->th_dport,
670 inp = in_pcblookup_hash(&tcbinfo,
671 ip->ip_src, th->th_sport,
672 ip->ip_dst, th->th_dport,
675 #ifdef IPFIREWALL_FORWARD
677 #endif /* IPFIREWALL_FORWARD */
679 #if defined(IPSEC) || defined(FAST_IPSEC)
682 if (inp != NULL && ipsec6_in_reject(m, inp)) {
684 ipsec6stat.in_polvio++;
690 if (inp != NULL && ipsec4_in_reject(m, inp)) {
692 ipsecstat.in_polvio++;
696 #endif /*IPSEC || FAST_IPSEC*/
699 * If the state is CLOSED (i.e., TCB does not exist) then
700 * all data in the incoming segment is discarded.
701 * If the TCB exists but is in CLOSED state, it is embryonic,
702 * but should either do a listen or a connect soon.
707 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
709 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
716 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
717 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
722 strcpy(dbuf, inet_ntoa(ip->ip_dst));
723 strcpy(sbuf, inet_ntoa(ip->ip_src));
725 switch (log_in_vain) {
727 if ((thflags & TH_SYN) == 0)
732 "Connection attempt to TCP %s:%d "
733 "from %s:%d flags:0x%02x\n",
734 dbuf, ntohs(th->th_dport), sbuf,
735 ntohs(th->th_sport), thflags);
744 if (thflags & TH_SYN)
753 rstreason = BANDLIM_RST_CLOSEDPORT;
758 /* Check the minimum TTL for socket. */
759 if (inp->inp_ip_minttl != 0) {
761 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
765 if (inp->inp_ip_minttl > ip->ip_ttl)
769 if (inp->inp_vflag & INP_TIMEWAIT) {
771 * The only option of relevance is TOF_CC, and only if
772 * present in a SYN segment. See tcp_timewait().
774 if (thflags & TH_SYN)
775 tcp_dooptions(&to, optp, optlen, TO_SYN);
776 if (tcp_timewait(inp, &to, th, m, tlen))
779 * tcp_timewait unlocks inp.
781 INP_INFO_WUNLOCK(&tcbinfo);
787 rstreason = BANDLIM_RST_CLOSEDPORT;
790 if (tp->t_state == TCPS_CLOSED)
794 INP_LOCK_ASSERT(inp);
795 if (mac_check_inpcb_deliver(inp, m))
798 so = inp->inp_socket;
799 KASSERT(so != NULL, ("tcp_input: so == NULL"));
801 if (so->so_options & SO_DEBUG) {
802 ostate = tp->t_state;
804 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
806 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
810 if (so->so_options & SO_ACCEPTCONN) {
811 struct in_conninfo inc;
813 bzero(&inc, sizeof(inc));
815 inc.inc_isipv6 = isipv6;
818 inc.inc6_faddr = ip6->ip6_src;
819 inc.inc6_laddr = ip6->ip6_dst;
821 inc.inc_faddr = ip->ip_src;
822 inc.inc_laddr = ip->ip_dst;
824 inc.inc_fport = th->th_sport;
825 inc.inc_lport = th->th_dport;
828 * If the state is LISTEN then ignore segment if it contains
829 * a RST. If the segment contains an ACK then it is bad and
830 * send a RST. If it does not contain a SYN then it is not
831 * interesting; drop it.
833 * If the state is SYN_RECEIVED (syncache) and seg contains
834 * an ACK, but not for our SYN/ACK, send a RST. If the seg
835 * contains a RST, check the sequence number to see if it
836 * is a valid reset segment.
838 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
839 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
840 if (!syncache_expand(&inc, th, &so, m)) {
842 * No syncache entry, or ACK was not
843 * for our SYN/ACK. Send a RST.
845 tcpstat.tcps_badsyn++;
846 rstreason = BANDLIM_RST_OPENPORT;
851 * Could not complete 3-way handshake,
852 * connection is being closed down, and
853 * syncache has free'd mbuf.
856 INP_INFO_WUNLOCK(&tcbinfo);
860 * Socket is created in state SYN_RECEIVED.
861 * Continue processing segment.
868 * This is what would have happened in
869 * tcp_output() when the SYN,ACK was sent.
871 tp->snd_up = tp->snd_una;
872 tp->snd_max = tp->snd_nxt = tp->iss + 1;
873 tp->last_ack_sent = tp->rcv_nxt;
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)) {
930 rstreason = BANDLIM_RST_OPENPORT;
936 * If it is from this socket, drop it, it must be forged.
937 * Don't bother responding if the destination was a broadcast.
939 if (th->th_dport == th->th_sport) {
941 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
945 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
950 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
952 * Note that it is quite possible to receive unicast
953 * link-layer packets with a broadcast IP address. Use
954 * in_broadcast() to find them.
956 if (m->m_flags & (M_BCAST|M_MCAST))
959 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
960 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
963 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
964 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
965 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
966 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
970 * SYN appears to be valid; create compressed TCP state
971 * for syncache, or perform t/tcp connection.
973 if (so->so_qlen <= so->so_qlimit) {
975 if (so->so_options & SO_DEBUG)
976 tcp_trace(TA_INPUT, ostate, tp,
977 (void *)tcp_saveipgen, &tcp_savetcp, 0);
979 tcp_dooptions(&to, optp, optlen, TO_SYN);
980 if (!syncache_add(&inc, &to, th, inp, &so, m))
981 goto drop; /* XXX: does not happen */
984 * Entry added to syncache, mbuf used to
985 * send SYN,ACK packet. Everything unlocked
990 panic("T/TCP not supported at the moment");
993 * Segment passed TAO tests.
994 * XXX: Can't happen at the moment.
1000 tp->t_starttime = ticks;
1001 tp->t_state = TCPS_ESTABLISHED;
1005 * If there is a FIN or if there is data, then
1006 * delay SYN,ACK(SYN) in the hope of piggy-backing
1007 * it on a response segment. Otherwise must send
1008 * ACK now in case the other side is slow starting.
1010 if (thflags & TH_FIN || tlen != 0)
1011 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
1013 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1014 tiwin = th->th_win << tp->snd_scale;
1015 tcpstat.tcps_connects++;
1023 KASSERT(headlocked, ("tcp_input: after_listen: head not locked"));
1024 INP_LOCK_ASSERT(inp);
1026 /* Syncache takes care of sockets in the listen state. */
1027 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN"));
1030 * This is the second part of the MSS DoS prevention code (after
1031 * minmss on the sending side) and it deals with too many too small
1032 * tcp packets in a too short timeframe (1 second).
1034 * For every full second we count the number of received packets
1035 * and bytes. If we get a lot of packets per second for this connection
1036 * (tcp_minmssoverload) we take a closer look at it and compute the
1037 * average packet size for the past second. If that is less than
1038 * tcp_minmss we get too many packets with very small payload which
1039 * is not good and burdens our system (and every packet generates
1040 * a wakeup to the process connected to our socket). We can reasonable
1041 * expect this to be small packet DoS attack to exhaust our CPU
1044 * Care has to be taken for the minimum packet overload value. This
1045 * value defines the minimum number of packets per second before we
1046 * start to worry. This must not be too low to avoid killing for
1047 * example interactive connections with many small packets like
1050 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1053 * Account for packet if payload packet, skip over ACK, etc.
1055 if (tcp_minmss && tcp_minmssoverload &&
1056 tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
1057 if ((unsigned int)(tp->rcv_second - ticks) < hz) {
1059 tp->rcv_byps += tlen + off;
1060 if (tp->rcv_pps > tcp_minmssoverload) {
1061 if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
1062 printf("too many small tcp packets from "
1063 "%s:%u, av. %lubyte/packet, "
1064 "dropping connection\n",
1067 ip6_sprintf(&inp->inp_inc.inc6_faddr) :
1069 inet_ntoa(inp->inp_inc.inc_faddr),
1070 inp->inp_inc.inc_fport,
1071 tp->rcv_byps / tp->rcv_pps);
1072 KASSERT(headlocked, ("tcp_input: "
1073 "after_listen: tcp_drop: head "
1075 tp = tcp_drop(tp, ECONNRESET);
1076 tcpstat.tcps_minmssdrops++;
1081 tp->rcv_second = ticks + hz;
1083 tp->rcv_byps = tlen + off;
1088 * Segment received on connection.
1089 * Reset idle time and keep-alive timer.
1091 tp->t_rcvtime = ticks;
1092 if (TCPS_HAVEESTABLISHED(tp->t_state))
1093 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1096 * Unscale the window into a 32-bit value.
1097 * This value is bogus for the TCPS_SYN_SENT state
1098 * and is overwritten later.
1100 tiwin = th->th_win << tp->snd_scale;
1103 * Parse options on any incoming segment.
1105 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) ? TO_SYN : 0);
1108 * If echoed timestamp is later than the current time,
1109 * fall back to non RFC1323 RTT calculation.
1111 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
1112 TSTMP_GT(to.to_tsecr, ticks))
1116 * Process options only when we get SYN/ACK back. The SYN case
1117 * for incoming connections is handled in tcp_syncache.
1118 * XXX this is traditional behavior, may need to be cleaned up.
1120 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1121 if ((to.to_flags & TOF_SCALE) &&
1122 (tp->t_flags & TF_REQ_SCALE)) {
1123 tp->t_flags |= TF_RCVD_SCALE;
1124 tp->snd_scale = to.to_requested_s_scale;
1125 tp->snd_wnd = th->th_win << tp->snd_scale;
1126 tiwin = tp->snd_wnd;
1128 if (to.to_flags & TOF_TS) {
1129 tp->t_flags |= TF_RCVD_TSTMP;
1130 tp->ts_recent = to.to_tsval;
1131 tp->ts_recent_age = ticks;
1133 if (to.to_flags & TOF_MSS)
1134 tcp_mss(tp, to.to_mss);
1135 if (tp->sack_enable) {
1136 if (!(to.to_flags & TOF_SACK))
1137 tp->sack_enable = 0;
1139 tp->t_flags |= TF_SACK_PERMIT;
1145 * Header prediction: check for the two common cases
1146 * of a uni-directional data xfer. If the packet has
1147 * no control flags, is in-sequence, the window didn't
1148 * change and we're not retransmitting, it's a
1149 * candidate. If the length is zero and the ack moved
1150 * forward, we're the sender side of the xfer. Just
1151 * free the data acked & wake any higher level process
1152 * that was blocked waiting for space. If the length
1153 * is non-zero and the ack didn't move, we're the
1154 * receiver side. If we're getting packets in-order
1155 * (the reassembly queue is empty), add the data to
1156 * the socket buffer and note that we need a delayed ack.
1157 * Make sure that the hidden state-flags are also off.
1158 * Since we check for TCPS_ESTABLISHED above, it can only
1161 if (tp->t_state == TCPS_ESTABLISHED &&
1162 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1163 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1164 ((to.to_flags & TOF_TS) == 0 ||
1165 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1166 th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd &&
1167 tp->snd_nxt == tp->snd_max) {
1170 * If last ACK falls within this segment's sequence numbers,
1171 * record the timestamp.
1172 * NOTE that the test is modified according to the latest
1173 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1175 if ((to.to_flags & TOF_TS) != 0 &&
1176 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1177 tp->ts_recent_age = ticks;
1178 tp->ts_recent = to.to_tsval;
1182 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1183 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1184 tp->snd_cwnd >= tp->snd_wnd &&
1185 ((!tcp_do_newreno && !tp->sack_enable &&
1186 tp->t_dupacks < tcprexmtthresh) ||
1187 ((tcp_do_newreno || tp->sack_enable) &&
1188 !IN_FASTRECOVERY(tp) && to.to_nsacks == 0 &&
1189 TAILQ_EMPTY(&tp->snd_holes)))) {
1190 KASSERT(headlocked, ("headlocked"));
1191 INP_INFO_WUNLOCK(&tcbinfo);
1194 * this is a pure ack for outstanding data.
1196 ++tcpstat.tcps_predack;
1198 * "bad retransmit" recovery
1200 if (tp->t_rxtshift == 1 &&
1201 ticks < tp->t_badrxtwin) {
1202 ++tcpstat.tcps_sndrexmitbad;
1203 tp->snd_cwnd = tp->snd_cwnd_prev;
1205 tp->snd_ssthresh_prev;
1206 tp->snd_recover = tp->snd_recover_prev;
1207 if (tp->t_flags & TF_WASFRECOVERY)
1208 ENTER_FASTRECOVERY(tp);
1209 tp->snd_nxt = tp->snd_max;
1210 tp->t_badrxtwin = 0;
1214 * Recalculate the transmit timer / rtt.
1216 * Some boxes send broken timestamp replies
1217 * during the SYN+ACK phase, ignore
1218 * timestamps of 0 or we could calculate a
1219 * huge RTT and blow up the retransmit timer.
1221 if ((to.to_flags & TOF_TS) != 0 &&
1223 if (!tp->t_rttlow ||
1224 tp->t_rttlow > ticks - to.to_tsecr)
1225 tp->t_rttlow = ticks - to.to_tsecr;
1227 ticks - to.to_tsecr + 1);
1228 } else if (tp->t_rtttime &&
1229 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1230 if (!tp->t_rttlow ||
1231 tp->t_rttlow > ticks - tp->t_rtttime)
1232 tp->t_rttlow = ticks - tp->t_rtttime;
1234 ticks - tp->t_rtttime);
1236 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1237 acked = th->th_ack - tp->snd_una;
1238 tcpstat.tcps_rcvackpack++;
1239 tcpstat.tcps_rcvackbyte += acked;
1240 sbdrop(&so->so_snd, acked);
1241 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1242 SEQ_LEQ(th->th_ack, tp->snd_recover))
1243 tp->snd_recover = th->th_ack - 1;
1244 tp->snd_una = th->th_ack;
1246 * pull snd_wl2 up to prevent seq wrap relative
1249 tp->snd_wl2 = th->th_ack;
1252 ND6_HINT(tp); /* some progress has been done */
1255 * If all outstanding data are acked, stop
1256 * retransmit timer, otherwise restart timer
1257 * using current (possibly backed-off) value.
1258 * If process is waiting for space,
1259 * wakeup/selwakeup/signal. If data
1260 * are ready to send, let tcp_output
1261 * decide between more output or persist.
1264 if (so->so_options & SO_DEBUG)
1265 tcp_trace(TA_INPUT, ostate, tp,
1266 (void *)tcp_saveipgen,
1270 if (tp->snd_una == tp->snd_max)
1271 callout_stop(tp->tt_rexmt);
1272 else if (!callout_active(tp->tt_persist))
1273 callout_reset(tp->tt_rexmt,
1275 tcp_timer_rexmt, tp);
1278 if (so->so_snd.sb_cc)
1279 (void) tcp_output(tp);
1282 } else if (th->th_ack == tp->snd_una &&
1283 LIST_EMPTY(&tp->t_segq) &&
1284 tlen <= sbspace(&so->so_rcv)) {
1285 KASSERT(headlocked, ("headlocked"));
1286 INP_INFO_WUNLOCK(&tcbinfo);
1289 * this is a pure, in-sequence data packet
1290 * with nothing on the reassembly queue and
1291 * we have enough buffer space to take it.
1293 /* Clean receiver SACK report if present */
1294 if (tp->sack_enable && tp->rcv_numsacks)
1295 tcp_clean_sackreport(tp);
1296 ++tcpstat.tcps_preddat;
1297 tp->rcv_nxt += tlen;
1299 * Pull snd_wl1 up to prevent seq wrap relative to
1302 tp->snd_wl1 = th->th_seq;
1304 * Pull rcv_up up to prevent seq wrap relative to
1307 tp->rcv_up = tp->rcv_nxt;
1308 tcpstat.tcps_rcvpack++;
1309 tcpstat.tcps_rcvbyte += tlen;
1310 ND6_HINT(tp); /* some progress has been done */
1313 if (so->so_options & SO_DEBUG)
1314 tcp_trace(TA_INPUT, ostate, tp,
1315 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1317 * Add data to socket buffer.
1319 SOCKBUF_LOCK(&so->so_rcv);
1320 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1323 m_adj(m, drop_hdrlen); /* delayed header drop */
1324 sbappendstream_locked(&so->so_rcv, m);
1326 sorwakeup_locked(so);
1327 if (DELAY_ACK(tp)) {
1328 tp->t_flags |= TF_DELACK;
1330 tp->t_flags |= TF_ACKNOW;
1338 * Calculate amount of space in receive window,
1339 * and then do TCP input processing.
1340 * Receive window is amount of space in rcv queue,
1341 * but not less than advertised window.
1345 win = sbspace(&so->so_rcv);
1348 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1351 switch (tp->t_state) {
1354 * If the state is SYN_RECEIVED:
1355 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1357 case TCPS_SYN_RECEIVED:
1358 if ((thflags & TH_ACK) &&
1359 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1360 SEQ_GT(th->th_ack, tp->snd_max))) {
1361 rstreason = BANDLIM_RST_OPENPORT;
1367 * If the state is SYN_SENT:
1368 * if seg contains an ACK, but not for our SYN, drop the input.
1369 * if seg contains a RST, then drop the connection.
1370 * if seg does not contain SYN, then drop it.
1371 * Otherwise this is an acceptable SYN segment
1372 * initialize tp->rcv_nxt and tp->irs
1373 * if seg contains ack then advance tp->snd_una
1374 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1375 * arrange for segment to be acked (eventually)
1376 * continue processing rest of data/controls, beginning with URG
1379 if ((thflags & TH_ACK) &&
1380 (SEQ_LEQ(th->th_ack, tp->iss) ||
1381 SEQ_GT(th->th_ack, tp->snd_max))) {
1382 rstreason = BANDLIM_UNLIMITED;
1385 if (thflags & TH_RST) {
1386 if (thflags & TH_ACK) {
1387 KASSERT(headlocked, ("tcp_input: after_listen"
1388 ": tcp_drop.2: head not locked"));
1389 tp = tcp_drop(tp, ECONNREFUSED);
1393 if ((thflags & TH_SYN) == 0)
1396 /* Initial send window, already scaled. */
1397 tp->snd_wnd = th->th_win;
1399 tp->irs = th->th_seq;
1401 if (thflags & TH_ACK) {
1402 tcpstat.tcps_connects++;
1406 mac_set_socket_peer_from_mbuf(m, so);
1409 /* Do window scaling on this connection? */
1410 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1411 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1412 tp->rcv_scale = tp->request_r_scale;
1414 tp->rcv_adv += tp->rcv_wnd;
1415 tp->snd_una++; /* SYN is acked */
1417 * If there's data, delay ACK; if there's also a FIN
1418 * ACKNOW will be turned on later.
1420 if (DELAY_ACK(tp) && tlen != 0)
1421 callout_reset(tp->tt_delack, tcp_delacktime,
1422 tcp_timer_delack, tp);
1424 tp->t_flags |= TF_ACKNOW;
1426 * Received <SYN,ACK> in SYN_SENT[*] state.
1428 * SYN_SENT --> ESTABLISHED
1429 * SYN_SENT* --> FIN_WAIT_1
1431 tp->t_starttime = ticks;
1432 if (tp->t_flags & TF_NEEDFIN) {
1433 tp->t_state = TCPS_FIN_WAIT_1;
1434 tp->t_flags &= ~TF_NEEDFIN;
1437 tp->t_state = TCPS_ESTABLISHED;
1438 callout_reset(tp->tt_keep, tcp_keepidle,
1439 tcp_timer_keep, tp);
1443 * Received initial SYN in SYN-SENT[*] state =>
1444 * simultaneous open. If segment contains CC option
1445 * and there is a cached CC, apply TAO test.
1446 * If it succeeds, connection is * half-synchronized.
1447 * Otherwise, do 3-way handshake:
1448 * SYN-SENT -> SYN-RECEIVED
1449 * SYN-SENT* -> SYN-RECEIVED*
1450 * If there was no CC option, clear cached CC value.
1452 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1453 callout_stop(tp->tt_rexmt);
1454 tp->t_state = TCPS_SYN_RECEIVED;
1460 KASSERT(headlocked, ("tcp_input: trimthenstep6: head not "
1462 INP_LOCK_ASSERT(inp);
1465 * Advance th->th_seq to correspond to first data byte.
1466 * If data, trim to stay within window,
1467 * dropping FIN if necessary.
1470 if (tlen > tp->rcv_wnd) {
1471 todrop = tlen - tp->rcv_wnd;
1475 tcpstat.tcps_rcvpackafterwin++;
1476 tcpstat.tcps_rcvbyteafterwin += todrop;
1478 tp->snd_wl1 = th->th_seq - 1;
1479 tp->rcv_up = th->th_seq;
1481 * Client side of transaction: already sent SYN and data.
1482 * If the remote host used T/TCP to validate the SYN,
1483 * our data will be ACK'd; if so, enter normal data segment
1484 * processing in the middle of step 5, ack processing.
1485 * Otherwise, goto step 6.
1487 if (thflags & TH_ACK)
1493 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1494 * do normal processing.
1496 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1500 case TCPS_TIME_WAIT:
1501 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1502 break; /* continue normal processing */
1506 * States other than LISTEN or SYN_SENT.
1507 * First check the RST flag and sequence number since reset segments
1508 * are exempt from the timestamp and connection count tests. This
1509 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1510 * below which allowed reset segments in half the sequence space
1511 * to fall though and be processed (which gives forged reset
1512 * segments with a random sequence number a 50 percent chance of
1513 * killing a connection).
1514 * Then check timestamp, if present.
1515 * Then check the connection count, if present.
1516 * Then check that at least some bytes of segment are within
1517 * receive window. If segment begins before rcv_nxt,
1518 * drop leading data (and SYN); if nothing left, just ack.
1521 * If the RST bit is set, check the sequence number to see
1522 * if this is a valid reset segment.
1524 * In all states except SYN-SENT, all reset (RST) segments
1525 * are validated by checking their SEQ-fields. A reset is
1526 * valid if its sequence number is in the window.
1527 * Note: this does not take into account delayed ACKs, so
1528 * we should test against last_ack_sent instead of rcv_nxt.
1529 * The sequence number in the reset segment is normally an
1530 * echo of our outgoing acknowlegement numbers, but some hosts
1531 * send a reset with the sequence number at the rightmost edge
1532 * of our receive window, and we have to handle this case.
1533 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1534 * that brute force RST attacks are possible. To combat this,
1535 * we use a much stricter check while in the ESTABLISHED state,
1536 * only accepting RSTs where the sequence number is equal to
1537 * last_ack_sent. In all other states (the states in which a
1538 * RST is more likely), the more permissive check is used.
1539 * If we have multiple segments in flight, the intial reset
1540 * segment sequence numbers will be to the left of last_ack_sent,
1541 * but they will eventually catch up.
1542 * In any case, it never made sense to trim reset segments to
1543 * fit the receive window since RFC 1122 says:
1544 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1546 * A TCP SHOULD allow a received RST segment to include data.
1549 * It has been suggested that a RST segment could contain
1550 * ASCII text that encoded and explained the cause of the
1551 * RST. No standard has yet been established for such
1554 * If the reset segment passes the sequence number test examine
1556 * SYN_RECEIVED STATE:
1557 * If passive open, return to LISTEN state.
1558 * If active open, inform user that connection was refused.
1559 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1560 * Inform user that connection was reset, and close tcb.
1561 * CLOSING, LAST_ACK STATES:
1564 * Drop the segment - see Stevens, vol. 2, p. 964 and
1567 if (thflags & TH_RST) {
1568 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1569 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
1570 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
1571 switch (tp->t_state) {
1573 case TCPS_SYN_RECEIVED:
1574 so->so_error = ECONNREFUSED;
1577 case TCPS_ESTABLISHED:
1578 if (tp->last_ack_sent != th->th_seq &&
1579 tcp_insecure_rst == 0) {
1580 tcpstat.tcps_badrst++;
1583 case TCPS_FIN_WAIT_1:
1584 case TCPS_FIN_WAIT_2:
1585 case TCPS_CLOSE_WAIT:
1586 so->so_error = ECONNRESET;
1588 tp->t_state = TCPS_CLOSED;
1589 tcpstat.tcps_drops++;
1590 KASSERT(headlocked, ("tcp_input: "
1591 "trimthenstep6: tcp_close: head not "
1598 KASSERT(headlocked, ("trimthenstep6: "
1599 "tcp_close.2: head not locked"));
1603 case TCPS_TIME_WAIT:
1604 KASSERT(tp->t_state != TCPS_TIME_WAIT,
1613 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1614 * and it's less than ts_recent, drop it.
1616 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1617 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1619 /* Check to see if ts_recent is over 24 days old. */
1620 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1622 * Invalidate ts_recent. If this segment updates
1623 * ts_recent, the age will be reset later and ts_recent
1624 * will get a valid value. If it does not, setting
1625 * ts_recent to zero will at least satisfy the
1626 * requirement that zero be placed in the timestamp
1627 * echo reply when ts_recent isn't valid. The
1628 * age isn't reset until we get a valid ts_recent
1629 * because we don't want out-of-order segments to be
1630 * dropped when ts_recent is old.
1634 tcpstat.tcps_rcvduppack++;
1635 tcpstat.tcps_rcvdupbyte += tlen;
1636 tcpstat.tcps_pawsdrop++;
1644 * In the SYN-RECEIVED state, validate that the packet belongs to
1645 * this connection before trimming the data to fit the receive
1646 * window. Check the sequence number versus IRS since we know
1647 * the sequence numbers haven't wrapped. This is a partial fix
1648 * for the "LAND" DoS attack.
1650 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1651 rstreason = BANDLIM_RST_OPENPORT;
1655 todrop = tp->rcv_nxt - th->th_seq;
1657 if (thflags & TH_SYN) {
1667 * Following if statement from Stevens, vol. 2, p. 960.
1670 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1672 * Any valid FIN must be to the left of the window.
1673 * At this point the FIN must be a duplicate or out
1674 * of sequence; drop it.
1679 * Send an ACK to resynchronize and drop any data.
1680 * But keep on processing for RST or ACK.
1682 tp->t_flags |= TF_ACKNOW;
1684 tcpstat.tcps_rcvduppack++;
1685 tcpstat.tcps_rcvdupbyte += todrop;
1687 tcpstat.tcps_rcvpartduppack++;
1688 tcpstat.tcps_rcvpartdupbyte += todrop;
1690 drop_hdrlen += todrop; /* drop from the top afterwards */
1691 th->th_seq += todrop;
1693 if (th->th_urp > todrop)
1694 th->th_urp -= todrop;
1702 * If new data are received on a connection after the
1703 * user processes are gone, then RST the other end.
1705 if ((so->so_state & SS_NOFDREF) &&
1706 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1707 KASSERT(headlocked, ("trimthenstep6: tcp_close.3: head not "
1710 tcpstat.tcps_rcvafterclose++;
1711 rstreason = BANDLIM_UNLIMITED;
1716 * If segment ends after window, drop trailing data
1717 * (and PUSH and FIN); if nothing left, just ACK.
1719 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1721 tcpstat.tcps_rcvpackafterwin++;
1722 if (todrop >= tlen) {
1723 tcpstat.tcps_rcvbyteafterwin += tlen;
1725 * If a new connection request is received
1726 * while in TIME_WAIT, drop the old connection
1727 * and start over if the sequence numbers
1728 * are above the previous ones.
1730 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1731 if (thflags & TH_SYN &&
1732 tp->t_state == TCPS_TIME_WAIT &&
1733 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1734 KASSERT(headlocked, ("trimthenstep6: "
1735 "tcp_close.4: head not locked"));
1740 * If window is closed can only take segments at
1741 * window edge, and have to drop data and PUSH from
1742 * incoming segments. Continue processing, but
1743 * remember to ack. Otherwise, drop segment
1746 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1747 tp->t_flags |= TF_ACKNOW;
1748 tcpstat.tcps_rcvwinprobe++;
1752 tcpstat.tcps_rcvbyteafterwin += todrop;
1755 thflags &= ~(TH_PUSH|TH_FIN);
1759 * If last ACK falls within this segment's sequence numbers,
1760 * record its timestamp.
1762 * 1) That the test incorporates suggestions from the latest
1763 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1764 * 2) That updating only on newer timestamps interferes with
1765 * our earlier PAWS tests, so this check should be solely
1766 * predicated on the sequence space of this segment.
1767 * 3) That we modify the segment boundary check to be
1768 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1769 * instead of RFC1323's
1770 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1771 * This modified check allows us to overcome RFC1323's
1772 * limitations as described in Stevens TCP/IP Illustrated
1773 * Vol. 2 p.869. In such cases, we can still calculate the
1774 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1776 if ((to.to_flags & TOF_TS) != 0 &&
1777 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1778 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1779 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1780 tp->ts_recent_age = ticks;
1781 tp->ts_recent = to.to_tsval;
1785 * If a SYN is in the window, then this is an
1786 * error and we send an RST and drop the connection.
1788 if (thflags & TH_SYN) {
1789 KASSERT(headlocked, ("tcp_input: tcp_drop: trimthenstep6: "
1790 "head not locked"));
1791 tp = tcp_drop(tp, ECONNRESET);
1792 rstreason = BANDLIM_UNLIMITED;
1797 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1798 * flag is on (half-synchronized state), then queue data for
1799 * later processing; else drop segment and return.
1801 if ((thflags & TH_ACK) == 0) {
1802 if (tp->t_state == TCPS_SYN_RECEIVED ||
1803 (tp->t_flags & TF_NEEDSYN))
1805 else if (tp->t_flags & TF_ACKNOW)
1814 switch (tp->t_state) {
1817 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1818 * ESTABLISHED state and continue processing.
1819 * The ACK was checked above.
1821 case TCPS_SYN_RECEIVED:
1823 tcpstat.tcps_connects++;
1825 /* Do window scaling? */
1826 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1827 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1828 tp->rcv_scale = tp->request_r_scale;
1829 tp->snd_wnd = tiwin;
1833 * SYN-RECEIVED -> ESTABLISHED
1834 * SYN-RECEIVED* -> FIN-WAIT-1
1836 tp->t_starttime = ticks;
1837 if (tp->t_flags & TF_NEEDFIN) {
1838 tp->t_state = TCPS_FIN_WAIT_1;
1839 tp->t_flags &= ~TF_NEEDFIN;
1841 tp->t_state = TCPS_ESTABLISHED;
1842 callout_reset(tp->tt_keep, tcp_keepidle,
1843 tcp_timer_keep, tp);
1846 * If segment contains data or ACK, will call tcp_reass()
1847 * later; if not, do so now to pass queued data to user.
1849 if (tlen == 0 && (thflags & TH_FIN) == 0)
1850 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1852 tp->snd_wl1 = th->th_seq - 1;
1856 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1857 * ACKs. If the ack is in the range
1858 * tp->snd_una < th->th_ack <= tp->snd_max
1859 * then advance tp->snd_una to th->th_ack and drop
1860 * data from the retransmission queue. If this ACK reflects
1861 * more up to date window information we update our window information.
1863 case TCPS_ESTABLISHED:
1864 case TCPS_FIN_WAIT_1:
1865 case TCPS_FIN_WAIT_2:
1866 case TCPS_CLOSE_WAIT:
1869 case TCPS_TIME_WAIT:
1870 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1871 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1872 tcpstat.tcps_rcvacktoomuch++;
1875 if (tp->sack_enable &&
1876 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes)))
1877 tcp_sack_doack(tp, &to, th->th_ack);
1878 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1879 if (tlen == 0 && tiwin == tp->snd_wnd) {
1880 tcpstat.tcps_rcvdupack++;
1882 * If we have outstanding data (other than
1883 * a window probe), this is a completely
1884 * duplicate ack (ie, window info didn't
1885 * change), the ack is the biggest we've
1886 * seen and we've seen exactly our rexmt
1887 * threshhold of them, assume a packet
1888 * has been dropped and retransmit it.
1889 * Kludge snd_nxt & the congestion
1890 * window so we send only this one
1893 * We know we're losing at the current
1894 * window size so do congestion avoidance
1895 * (set ssthresh to half the current window
1896 * and pull our congestion window back to
1897 * the new ssthresh).
1899 * Dup acks mean that packets have left the
1900 * network (they're now cached at the receiver)
1901 * so bump cwnd by the amount in the receiver
1902 * to keep a constant cwnd packets in the
1905 if (!callout_active(tp->tt_rexmt) ||
1906 th->th_ack != tp->snd_una)
1908 else if (++tp->t_dupacks > tcprexmtthresh ||
1909 ((tcp_do_newreno || tp->sack_enable) &&
1910 IN_FASTRECOVERY(tp))) {
1911 if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
1915 * Compute the amount of data in flight first.
1916 * We can inject new data into the pipe iff
1917 * we have less than 1/2 the original window's
1918 * worth of data in flight.
1920 awnd = (tp->snd_nxt - tp->snd_fack) +
1921 tp->sackhint.sack_bytes_rexmit;
1922 if (awnd < tp->snd_ssthresh) {
1923 tp->snd_cwnd += tp->t_maxseg;
1924 if (tp->snd_cwnd > tp->snd_ssthresh)
1925 tp->snd_cwnd = tp->snd_ssthresh;
1928 tp->snd_cwnd += tp->t_maxseg;
1929 (void) tcp_output(tp);
1931 } else if (tp->t_dupacks == tcprexmtthresh) {
1932 tcp_seq onxt = tp->snd_nxt;
1936 * If we're doing sack, check to
1937 * see if we're already in sack
1938 * recovery. If we're not doing sack,
1939 * check to see if we're in newreno
1942 if (tp->sack_enable) {
1943 if (IN_FASTRECOVERY(tp)) {
1947 } else if (tcp_do_newreno) {
1948 if (SEQ_LEQ(th->th_ack,
1954 win = min(tp->snd_wnd, tp->snd_cwnd) /
1958 tp->snd_ssthresh = win * tp->t_maxseg;
1959 ENTER_FASTRECOVERY(tp);
1960 tp->snd_recover = tp->snd_max;
1961 callout_stop(tp->tt_rexmt);
1963 if (tp->sack_enable) {
1964 tcpstat.tcps_sack_recovery_episode++;
1965 tp->sack_newdata = tp->snd_nxt;
1966 tp->snd_cwnd = tp->t_maxseg;
1967 (void) tcp_output(tp);
1970 tp->snd_nxt = th->th_ack;
1971 tp->snd_cwnd = tp->t_maxseg;
1972 (void) tcp_output(tp);
1973 KASSERT(tp->snd_limited <= 2,
1974 ("tp->snd_limited too big"));
1975 tp->snd_cwnd = tp->snd_ssthresh +
1977 (tp->t_dupacks - tp->snd_limited);
1978 if (SEQ_GT(onxt, tp->snd_nxt))
1981 } else if (tcp_do_rfc3042) {
1982 u_long oldcwnd = tp->snd_cwnd;
1983 tcp_seq oldsndmax = tp->snd_max;
1986 KASSERT(tp->t_dupacks == 1 ||
1988 ("dupacks not 1 or 2"));
1989 if (tp->t_dupacks == 1)
1990 tp->snd_limited = 0;
1992 (tp->snd_nxt - tp->snd_una) +
1993 (tp->t_dupacks - tp->snd_limited) *
1995 (void) tcp_output(tp);
1996 sent = tp->snd_max - oldsndmax;
1997 if (sent > tp->t_maxseg) {
1998 KASSERT((tp->t_dupacks == 2 &&
1999 tp->snd_limited == 0) ||
2000 (sent == tp->t_maxseg + 1 &&
2001 tp->t_flags & TF_SENTFIN),
2003 tp->snd_limited = 2;
2004 } else if (sent > 0)
2006 tp->snd_cwnd = oldcwnd;
2014 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2017 * If the congestion window was inflated to account
2018 * for the other side's cached packets, retract it.
2020 if (tcp_do_newreno || tp->sack_enable) {
2021 if (IN_FASTRECOVERY(tp)) {
2022 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2023 if (tp->sack_enable)
2024 tcp_sack_partialack(tp, th);
2026 tcp_newreno_partial_ack(tp, th);
2029 * Out of fast recovery.
2030 * Window inflation should have left us
2031 * with approximately snd_ssthresh
2033 * But in case we would be inclined to
2034 * send a burst, better to do it via
2035 * the slow start mechanism.
2037 if (SEQ_GT(th->th_ack +
2040 tp->snd_cwnd = tp->snd_max -
2044 tp->snd_cwnd = tp->snd_ssthresh;
2048 if (tp->t_dupacks >= tcprexmtthresh &&
2049 tp->snd_cwnd > tp->snd_ssthresh)
2050 tp->snd_cwnd = tp->snd_ssthresh;
2054 * If we reach this point, ACK is not a duplicate,
2055 * i.e., it ACKs something we sent.
2057 if (tp->t_flags & TF_NEEDSYN) {
2059 * T/TCP: Connection was half-synchronized, and our
2060 * SYN has been ACK'd (so connection is now fully
2061 * synchronized). Go to non-starred state,
2062 * increment snd_una for ACK of SYN, and check if
2063 * we can do window scaling.
2065 tp->t_flags &= ~TF_NEEDSYN;
2067 /* Do window scaling? */
2068 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2069 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2070 tp->rcv_scale = tp->request_r_scale;
2071 /* Send window already scaled. */
2076 KASSERT(headlocked, ("tcp_input: process_ACK: head not "
2078 INP_LOCK_ASSERT(inp);
2080 acked = th->th_ack - tp->snd_una;
2081 tcpstat.tcps_rcvackpack++;
2082 tcpstat.tcps_rcvackbyte += acked;
2085 * If we just performed our first retransmit, and the ACK
2086 * arrives within our recovery window, then it was a mistake
2087 * to do the retransmit in the first place. Recover our
2088 * original cwnd and ssthresh, and proceed to transmit where
2091 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2092 ++tcpstat.tcps_sndrexmitbad;
2093 tp->snd_cwnd = tp->snd_cwnd_prev;
2094 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2095 tp->snd_recover = tp->snd_recover_prev;
2096 if (tp->t_flags & TF_WASFRECOVERY)
2097 ENTER_FASTRECOVERY(tp);
2098 tp->snd_nxt = tp->snd_max;
2099 tp->t_badrxtwin = 0; /* XXX probably not required */
2103 * If we have a timestamp reply, update smoothed
2104 * round trip time. If no timestamp is present but
2105 * transmit timer is running and timed sequence
2106 * number was acked, update smoothed round trip time.
2107 * Since we now have an rtt measurement, cancel the
2108 * timer backoff (cf., Phil Karn's retransmit alg.).
2109 * Recompute the initial retransmit timer.
2111 * Some boxes send broken timestamp replies
2112 * during the SYN+ACK phase, ignore
2113 * timestamps of 0 or we could calculate a
2114 * huge RTT and blow up the retransmit timer.
2116 if ((to.to_flags & TOF_TS) != 0 &&
2118 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2119 tp->t_rttlow = ticks - to.to_tsecr;
2120 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2121 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2122 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2123 tp->t_rttlow = ticks - tp->t_rtttime;
2124 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2126 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2129 * If all outstanding data is acked, stop retransmit
2130 * timer and remember to restart (more output or persist).
2131 * If there is more data to be acked, restart retransmit
2132 * timer, using current (possibly backed-off) value.
2134 if (th->th_ack == tp->snd_max) {
2135 callout_stop(tp->tt_rexmt);
2137 } else if (!callout_active(tp->tt_persist))
2138 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2139 tcp_timer_rexmt, tp);
2142 * If no data (only SYN) was ACK'd,
2143 * skip rest of ACK processing.
2149 * When new data is acked, open the congestion window.
2150 * If the window gives us less than ssthresh packets
2151 * in flight, open exponentially (maxseg per packet).
2152 * Otherwise open linearly: maxseg per window
2153 * (maxseg^2 / cwnd per packet).
2155 if ((!tcp_do_newreno && !tp->sack_enable) ||
2156 !IN_FASTRECOVERY(tp)) {
2157 register u_int cw = tp->snd_cwnd;
2158 register u_int incr = tp->t_maxseg;
2159 if (cw > tp->snd_ssthresh)
2160 incr = incr * incr / cw;
2161 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2163 SOCKBUF_LOCK(&so->so_snd);
2164 if (acked > so->so_snd.sb_cc) {
2165 tp->snd_wnd -= so->so_snd.sb_cc;
2166 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2169 sbdrop_locked(&so->so_snd, acked);
2170 tp->snd_wnd -= acked;
2173 sowwakeup_locked(so);
2174 /* detect una wraparound */
2175 if ((tcp_do_newreno || tp->sack_enable) &&
2176 !IN_FASTRECOVERY(tp) &&
2177 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2178 SEQ_LEQ(th->th_ack, tp->snd_recover))
2179 tp->snd_recover = th->th_ack - 1;
2180 if ((tcp_do_newreno || tp->sack_enable) &&
2181 IN_FASTRECOVERY(tp) &&
2182 SEQ_GEQ(th->th_ack, tp->snd_recover))
2183 EXIT_FASTRECOVERY(tp);
2184 tp->snd_una = th->th_ack;
2185 if (tp->sack_enable) {
2186 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2187 tp->snd_recover = tp->snd_una;
2189 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2190 tp->snd_nxt = tp->snd_una;
2192 switch (tp->t_state) {
2195 * In FIN_WAIT_1 STATE in addition to the processing
2196 * for the ESTABLISHED state if our FIN is now acknowledged
2197 * then enter FIN_WAIT_2.
2199 case TCPS_FIN_WAIT_1:
2200 if (ourfinisacked) {
2202 * If we can't receive any more
2203 * data, then closing user can proceed.
2204 * Starting the timer is contrary to the
2205 * specification, but if we don't get a FIN
2206 * we'll hang forever.
2209 * we should release the tp also, and use a
2212 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2213 soisdisconnected(so);
2214 callout_reset(tp->tt_2msl, tcp_maxidle,
2215 tcp_timer_2msl, tp);
2217 tp->t_state = TCPS_FIN_WAIT_2;
2222 * In CLOSING STATE in addition to the processing for
2223 * the ESTABLISHED state if the ACK acknowledges our FIN
2224 * then enter the TIME-WAIT state, otherwise ignore
2228 if (ourfinisacked) {
2229 KASSERT(headlocked, ("tcp_input: process_ACK: "
2230 "head not locked"));
2232 INP_INFO_WUNLOCK(&tcbinfo);
2239 * In LAST_ACK, we may still be waiting for data to drain
2240 * and/or to be acked, as well as for the ack of our FIN.
2241 * If our FIN is now acknowledged, delete the TCB,
2242 * enter the closed state and return.
2245 if (ourfinisacked) {
2246 KASSERT(headlocked, ("tcp_input: process_ACK:"
2247 " tcp_close: head not locked"));
2254 * In TIME_WAIT state the only thing that should arrive
2255 * is a retransmission of the remote FIN. Acknowledge
2256 * it and restart the finack timer.
2258 case TCPS_TIME_WAIT:
2259 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2260 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2261 tcp_timer_2msl, tp);
2267 KASSERT(headlocked, ("tcp_input: step6: head not locked"));
2268 INP_LOCK_ASSERT(inp);
2271 * Update window information.
2272 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2274 if ((thflags & TH_ACK) &&
2275 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2276 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2277 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2278 /* keep track of pure window updates */
2280 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2281 tcpstat.tcps_rcvwinupd++;
2282 tp->snd_wnd = tiwin;
2283 tp->snd_wl1 = th->th_seq;
2284 tp->snd_wl2 = th->th_ack;
2285 if (tp->snd_wnd > tp->max_sndwnd)
2286 tp->max_sndwnd = tp->snd_wnd;
2291 * Process segments with URG.
2293 if ((thflags & TH_URG) && th->th_urp &&
2294 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2296 * This is a kludge, but if we receive and accept
2297 * random urgent pointers, we'll crash in
2298 * soreceive. It's hard to imagine someone
2299 * actually wanting to send this much urgent data.
2301 SOCKBUF_LOCK(&so->so_rcv);
2302 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2303 th->th_urp = 0; /* XXX */
2304 thflags &= ~TH_URG; /* XXX */
2305 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2306 goto dodata; /* XXX */
2309 * If this segment advances the known urgent pointer,
2310 * then mark the data stream. This should not happen
2311 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2312 * a FIN has been received from the remote side.
2313 * In these states we ignore the URG.
2315 * According to RFC961 (Assigned Protocols),
2316 * the urgent pointer points to the last octet
2317 * of urgent data. We continue, however,
2318 * to consider it to indicate the first octet
2319 * of data past the urgent section as the original
2320 * spec states (in one of two places).
2322 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2323 tp->rcv_up = th->th_seq + th->th_urp;
2324 so->so_oobmark = so->so_rcv.sb_cc +
2325 (tp->rcv_up - tp->rcv_nxt) - 1;
2326 if (so->so_oobmark == 0)
2327 so->so_rcv.sb_state |= SBS_RCVATMARK;
2329 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2331 SOCKBUF_UNLOCK(&so->so_rcv);
2333 * Remove out of band data so doesn't get presented to user.
2334 * This can happen independent of advancing the URG pointer,
2335 * but if two URG's are pending at once, some out-of-band
2336 * data may creep in... ick.
2338 if (th->th_urp <= (u_long)tlen &&
2339 !(so->so_options & SO_OOBINLINE)) {
2340 /* hdr drop is delayed */
2341 tcp_pulloutofband(so, th, m, drop_hdrlen);
2345 * If no out of band data is expected,
2346 * pull receive urgent pointer along
2347 * with the receive window.
2349 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2350 tp->rcv_up = tp->rcv_nxt;
2353 KASSERT(headlocked, ("tcp_input: dodata: head not locked"));
2354 INP_LOCK_ASSERT(inp);
2357 * Process the segment text, merging it into the TCP sequencing queue,
2358 * and arranging for acknowledgment of receipt if necessary.
2359 * This process logically involves adjusting tp->rcv_wnd as data
2360 * is presented to the user (this happens in tcp_usrreq.c,
2361 * case PRU_RCVD). If a FIN has already been received on this
2362 * connection then we just ignore the text.
2364 if ((tlen || (thflags & TH_FIN)) &&
2365 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2366 tcp_seq save_start = th->th_seq;
2367 tcp_seq save_end = th->th_seq + tlen;
2368 m_adj(m, drop_hdrlen); /* delayed header drop */
2370 * Insert segment which includes th into TCP reassembly queue
2371 * with control block tp. Set thflags to whether reassembly now
2372 * includes a segment with FIN. This handles the common case
2373 * inline (segment is the next to be received on an established
2374 * connection, and the queue is empty), avoiding linkage into
2375 * and removal from the queue and repetition of various
2377 * Set DELACK for segments received in order, but ack
2378 * immediately when segments are out of order (so
2379 * fast retransmit can work).
2381 if (th->th_seq == tp->rcv_nxt &&
2382 LIST_EMPTY(&tp->t_segq) &&
2383 TCPS_HAVEESTABLISHED(tp->t_state)) {
2385 tp->t_flags |= TF_DELACK;
2387 tp->t_flags |= TF_ACKNOW;
2388 tp->rcv_nxt += tlen;
2389 thflags = th->th_flags & TH_FIN;
2390 tcpstat.tcps_rcvpack++;
2391 tcpstat.tcps_rcvbyte += tlen;
2393 SOCKBUF_LOCK(&so->so_rcv);
2394 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2397 sbappendstream_locked(&so->so_rcv, m);
2398 sorwakeup_locked(so);
2400 thflags = tcp_reass(tp, th, &tlen, m);
2401 tp->t_flags |= TF_ACKNOW;
2403 if (tlen > 0 && tp->sack_enable)
2404 tcp_update_sack_list(tp, save_start, save_end);
2406 * Note the amount of data that peer has sent into
2407 * our window, in order to estimate the sender's
2410 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2417 * If FIN is received ACK the FIN and let the user know
2418 * that the connection is closing.
2420 if (thflags & TH_FIN) {
2421 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2424 * If connection is half-synchronized
2425 * (ie NEEDSYN flag on) then delay ACK,
2426 * so it may be piggybacked when SYN is sent.
2427 * Otherwise, since we received a FIN then no
2428 * more input can be expected, send ACK now.
2430 if (tp->t_flags & TF_NEEDSYN)
2431 tp->t_flags |= TF_DELACK;
2433 tp->t_flags |= TF_ACKNOW;
2436 switch (tp->t_state) {
2439 * In SYN_RECEIVED and ESTABLISHED STATES
2440 * enter the CLOSE_WAIT state.
2442 case TCPS_SYN_RECEIVED:
2443 tp->t_starttime = ticks;
2445 case TCPS_ESTABLISHED:
2446 tp->t_state = TCPS_CLOSE_WAIT;
2450 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2451 * enter the CLOSING state.
2453 case TCPS_FIN_WAIT_1:
2454 tp->t_state = TCPS_CLOSING;
2458 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2459 * starting the time-wait timer, turning off the other
2462 case TCPS_FIN_WAIT_2:
2463 KASSERT(headlocked == 1, ("tcp_input: dodata: "
2464 "TCP_FIN_WAIT_2: head not locked"));
2466 INP_INFO_WUNLOCK(&tcbinfo);
2470 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2472 case TCPS_TIME_WAIT:
2473 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2474 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2475 tcp_timer_2msl, tp);
2479 INP_INFO_WUNLOCK(&tcbinfo);
2482 if (so->so_options & SO_DEBUG)
2483 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2488 * Return any desired output.
2490 if (needoutput || (tp->t_flags & TF_ACKNOW))
2491 (void) tcp_output(tp);
2494 KASSERT(headlocked == 0, ("tcp_input: check_delack: head locked"));
2495 INP_LOCK_ASSERT(inp);
2496 if (tp->t_flags & TF_DELACK) {
2497 tp->t_flags &= ~TF_DELACK;
2498 callout_reset(tp->tt_delack, tcp_delacktime,
2499 tcp_timer_delack, tp);
2505 KASSERT(headlocked, ("tcp_input: dropafterack: head not locked"));
2507 * Generate an ACK dropping incoming segment if it occupies
2508 * sequence space, where the ACK reflects our state.
2510 * We can now skip the test for the RST flag since all
2511 * paths to this code happen after packets containing
2512 * RST have been dropped.
2514 * In the SYN-RECEIVED state, don't send an ACK unless the
2515 * segment we received passes the SYN-RECEIVED ACK test.
2516 * If it fails send a RST. This breaks the loop in the
2517 * "LAND" DoS attack, and also prevents an ACK storm
2518 * between two listening ports that have been sent forged
2519 * SYN segments, each with the source address of the other.
2521 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2522 (SEQ_GT(tp->snd_una, th->th_ack) ||
2523 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2524 rstreason = BANDLIM_RST_OPENPORT;
2528 if (so->so_options & SO_DEBUG)
2529 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2532 KASSERT(headlocked, ("headlocked should be 1"));
2533 INP_INFO_WUNLOCK(&tcbinfo);
2534 tp->t_flags |= TF_ACKNOW;
2535 (void) tcp_output(tp);
2541 KASSERT(headlocked, ("tcp_input: dropwithreset: head not locked"));
2543 * Generate a RST, dropping incoming segment.
2544 * Make ACK acceptable to originator of segment.
2545 * Don't bother to respond if destination was broadcast/multicast.
2547 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2550 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2551 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2554 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2555 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2556 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2557 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2560 /* IPv6 anycast check is done at tcp6_input() */
2563 * Perform bandwidth limiting.
2565 if (badport_bandlim(rstreason) < 0)
2569 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2570 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2574 if (thflags & TH_ACK)
2575 /* mtod() below is safe as long as hdr dropping is delayed */
2576 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2579 if (thflags & TH_SYN)
2581 /* mtod() below is safe as long as hdr dropping is delayed */
2582 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2583 (tcp_seq)0, TH_RST|TH_ACK);
2589 INP_INFO_WUNLOCK(&tcbinfo);
2594 * Drop space held by incoming segment and return.
2597 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2598 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2604 INP_INFO_WUNLOCK(&tcbinfo);
2610 * Parse TCP options and place in tcpopt.
2613 tcp_dooptions(to, cp, cnt, flags)
2622 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2624 if (opt == TCPOPT_EOL)
2626 if (opt == TCPOPT_NOP)
2632 if (optlen < 2 || optlen > cnt)
2637 if (optlen != TCPOLEN_MAXSEG)
2639 if (!(flags & TO_SYN))
2641 to->to_flags |= TOF_MSS;
2642 bcopy((char *)cp + 2,
2643 (char *)&to->to_mss, sizeof(to->to_mss));
2644 to->to_mss = ntohs(to->to_mss);
2647 if (optlen != TCPOLEN_WINDOW)
2649 if (!(flags & TO_SYN))
2651 to->to_flags |= TOF_SCALE;
2652 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2654 case TCPOPT_TIMESTAMP:
2655 if (optlen != TCPOLEN_TIMESTAMP)
2657 to->to_flags |= TOF_TS;
2658 bcopy((char *)cp + 2,
2659 (char *)&to->to_tsval, sizeof(to->to_tsval));
2660 to->to_tsval = ntohl(to->to_tsval);
2661 bcopy((char *)cp + 6,
2662 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2663 to->to_tsecr = ntohl(to->to_tsecr);
2665 #ifdef TCP_SIGNATURE
2667 * XXX In order to reply to a host which has set the
2668 * TCP_SIGNATURE option in its initial SYN, we have to
2669 * record the fact that the option was observed here
2670 * for the syncache code to perform the correct response.
2672 case TCPOPT_SIGNATURE:
2673 if (optlen != TCPOLEN_SIGNATURE)
2675 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2678 case TCPOPT_SACK_PERMITTED:
2679 if (optlen != TCPOLEN_SACK_PERMITTED)
2681 if (!(flags & TO_SYN))
2685 to->to_flags |= TOF_SACK;
2688 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2690 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2691 to->to_sacks = cp + 2;
2692 tcpstat.tcps_sack_rcv_blocks++;
2701 * Pull out of band byte out of a segment so
2702 * it doesn't appear in the user's data queue.
2703 * It is still reflected in the segment length for
2704 * sequencing purposes.
2707 tcp_pulloutofband(so, th, m, off)
2710 register struct mbuf *m;
2711 int off; /* delayed to be droped hdrlen */
2713 int cnt = off + th->th_urp - 1;
2716 if (m->m_len > cnt) {
2717 char *cp = mtod(m, caddr_t) + cnt;
2718 struct tcpcb *tp = sototcpcb(so);
2721 tp->t_oobflags |= TCPOOB_HAVEDATA;
2722 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2724 if (m->m_flags & M_PKTHDR)
2733 panic("tcp_pulloutofband");
2737 * Collect new round-trip time estimate
2738 * and update averages and current timeout.
2741 tcp_xmit_timer(tp, rtt)
2742 register struct tcpcb *tp;
2747 INP_LOCK_ASSERT(tp->t_inpcb);
2749 tcpstat.tcps_rttupdated++;
2751 if (tp->t_srtt != 0) {
2753 * srtt is stored as fixed point with 5 bits after the
2754 * binary point (i.e., scaled by 8). The following magic
2755 * is equivalent to the smoothing algorithm in rfc793 with
2756 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2757 * point). Adjust rtt to origin 0.
2759 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2760 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2762 if ((tp->t_srtt += delta) <= 0)
2766 * We accumulate a smoothed rtt variance (actually, a
2767 * smoothed mean difference), then set the retransmit
2768 * timer to smoothed rtt + 4 times the smoothed variance.
2769 * rttvar is stored as fixed point with 4 bits after the
2770 * binary point (scaled by 16). The following is
2771 * equivalent to rfc793 smoothing with an alpha of .75
2772 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2773 * rfc793's wired-in beta.
2777 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2778 if ((tp->t_rttvar += delta) <= 0)
2780 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2781 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2784 * No rtt measurement yet - use the unsmoothed rtt.
2785 * Set the variance to half the rtt (so our first
2786 * retransmit happens at 3*rtt).
2788 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2789 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2790 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2796 * the retransmit should happen at rtt + 4 * rttvar.
2797 * Because of the way we do the smoothing, srtt and rttvar
2798 * will each average +1/2 tick of bias. When we compute
2799 * the retransmit timer, we want 1/2 tick of rounding and
2800 * 1 extra tick because of +-1/2 tick uncertainty in the
2801 * firing of the timer. The bias will give us exactly the
2802 * 1.5 tick we need. But, because the bias is
2803 * statistical, we have to test that we don't drop below
2804 * the minimum feasible timer (which is 2 ticks).
2806 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2807 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2810 * We received an ack for a packet that wasn't retransmitted;
2811 * it is probably safe to discard any error indications we've
2812 * received recently. This isn't quite right, but close enough
2813 * for now (a route might have failed after we sent a segment,
2814 * and the return path might not be symmetrical).
2816 tp->t_softerror = 0;
2820 * Determine a reasonable value for maxseg size.
2821 * If the route is known, check route for mtu.
2822 * If none, use an mss that can be handled on the outgoing
2823 * interface without forcing IP to fragment; if bigger than
2824 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2825 * to utilize large mbufs. If no route is found, route has no mtu,
2826 * or the destination isn't local, use a default, hopefully conservative
2827 * size (usually 512 or the default IP max size, but no more than the mtu
2828 * of the interface), as we can't discover anything about intervening
2829 * gateways or networks. We also initialize the congestion/slow start
2830 * window to be a single segment if the destination isn't local.
2831 * While looking at the routing entry, we also initialize other path-dependent
2832 * parameters from pre-set or cached values in the routing entry.
2834 * Also take into account the space needed for options that we
2835 * send regularly. Make maxseg shorter by that amount to assure
2836 * that we can send maxseg amount of data even when the options
2837 * are present. Store the upper limit of the length of options plus
2841 * In case of T/TCP, we call this routine during implicit connection
2842 * setup as well (offer = -1), to initialize maxseg from the cached
2845 * NOTE that this routine is only called when we process an incoming
2846 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2856 struct inpcb *inp = tp->t_inpcb;
2858 struct hc_metrics_lite metrics;
2859 int origoffer = offer;
2861 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2862 size_t min_protoh = isipv6 ?
2863 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2864 sizeof (struct tcpiphdr);
2866 const size_t min_protoh = sizeof(struct tcpiphdr);
2872 maxmtu = tcp_maxmtu6(&inp->inp_inc);
2873 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2877 maxmtu = tcp_maxmtu(&inp->inp_inc);
2878 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2880 so = inp->inp_socket;
2883 * no route to sender, stay with default mss and return
2888 /* what have we got? */
2892 * Offer == 0 means that there was no MSS on the SYN
2893 * segment, in this case we use tcp_mssdflt.
2897 isipv6 ? tcp_v6mssdflt :
2904 * Offer == -1 means that we didn't receive SYN yet.
2910 * Prevent DoS attack with too small MSS. Round up
2911 * to at least minmss.
2913 offer = max(offer, tcp_minmss);
2915 * Sanity check: make sure that maxopd will be large
2916 * enough to allow some data on segments even if the
2917 * all the option space is used (40bytes). Otherwise
2918 * funny things may happen in tcp_output.
2920 offer = max(offer, 64);
2924 * rmx information is now retrieved from tcp_hostcache
2926 tcp_hc_get(&inp->inp_inc, &metrics);
2929 * if there's a discovered mtu int tcp hostcache, use it
2930 * else, use the link mtu.
2932 if (metrics.rmx_mtu)
2933 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2937 mss = maxmtu - min_protoh;
2938 if (!path_mtu_discovery &&
2939 !in6_localaddr(&inp->in6p_faddr))
2940 mss = min(mss, tcp_v6mssdflt);
2944 mss = maxmtu - min_protoh;
2945 if (!path_mtu_discovery &&
2946 !in_localaddr(inp->inp_faddr))
2947 mss = min(mss, tcp_mssdflt);
2950 mss = min(mss, offer);
2953 * maxopd stores the maximum length of data AND options
2954 * in a segment; maxseg is the amount of data in a normal
2955 * segment. We need to store this value (maxopd) apart
2956 * from maxseg, because now every segment carries options
2957 * and thus we normally have somewhat less data in segments.
2962 * origoffer==-1 indicates, that no segments were received yet.
2963 * In this case we just guess.
2965 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2967 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2968 mss -= TCPOLEN_TSTAMP_APPA;
2971 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2973 mss &= ~(MCLBYTES-1);
2976 mss = mss / MCLBYTES * MCLBYTES;
2981 * If there's a pipesize, change the socket buffer to that size,
2982 * don't change if sb_hiwat is different than default (then it
2983 * has been changed on purpose with setsockopt).
2984 * Make the socket buffers an integral number of mss units;
2985 * if the mss is larger than the socket buffer, decrease the mss.
2987 SOCKBUF_LOCK(&so->so_snd);
2988 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2989 bufsize = metrics.rmx_sendpipe;
2991 bufsize = so->so_snd.sb_hiwat;
2995 bufsize = roundup(bufsize, mss);
2996 if (bufsize > sb_max)
2998 if (bufsize > so->so_snd.sb_hiwat)
2999 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3001 SOCKBUF_UNLOCK(&so->so_snd);
3004 SOCKBUF_LOCK(&so->so_rcv);
3005 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3006 bufsize = metrics.rmx_recvpipe;
3008 bufsize = so->so_rcv.sb_hiwat;
3009 if (bufsize > mss) {
3010 bufsize = roundup(bufsize, mss);
3011 if (bufsize > sb_max)
3013 if (bufsize > so->so_rcv.sb_hiwat)
3014 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3016 SOCKBUF_UNLOCK(&so->so_rcv);
3018 * While we're here, check the others too
3020 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3022 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3023 tcpstat.tcps_usedrtt++;
3024 if (metrics.rmx_rttvar) {
3025 tp->t_rttvar = metrics.rmx_rttvar;
3026 tcpstat.tcps_usedrttvar++;
3028 /* default variation is +- 1 rtt */
3030 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3032 TCPT_RANGESET(tp->t_rxtcur,
3033 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3034 tp->t_rttmin, TCPTV_REXMTMAX);
3036 if (metrics.rmx_ssthresh) {
3038 * There's some sort of gateway or interface
3039 * buffer limit on the path. Use this to set
3040 * the slow start threshhold, but set the
3041 * threshold to no less than 2*mss.
3043 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3044 tcpstat.tcps_usedssthresh++;
3046 if (metrics.rmx_bandwidth)
3047 tp->snd_bandwidth = metrics.rmx_bandwidth;
3050 * Set the slow-start flight size depending on whether this
3051 * is a local network or not.
3053 * Extend this so we cache the cwnd too and retrieve it here.
3054 * Make cwnd even bigger than RFC3390 suggests but only if we
3055 * have previous experience with the remote host. Be careful
3056 * not make cwnd bigger than remote receive window or our own
3057 * send socket buffer. Maybe put some additional upper bound
3058 * on the retrieved cwnd. Should do incremental updates to
3059 * hostcache when cwnd collapses so next connection doesn't
3060 * overloads the path again.
3062 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3063 * We currently check only in syncache_socket for that.
3065 #define TCP_METRICS_CWND
3066 #ifdef TCP_METRICS_CWND
3067 if (metrics.rmx_cwnd)
3068 tp->snd_cwnd = max(mss,
3069 min(metrics.rmx_cwnd / 2,
3070 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3074 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3076 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3077 (!isipv6 && in_localaddr(inp->inp_faddr)))
3079 else if (in_localaddr(inp->inp_faddr))
3081 tp->snd_cwnd = mss * ss_fltsz_local;
3083 tp->snd_cwnd = mss * ss_fltsz;
3087 * Determine the MSS option to send on an outgoing SYN.
3091 struct in_conninfo *inc;
3098 int isipv6 = inc->inc_isipv6 ? 1 : 0;
3101 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3105 mss = tcp_v6mssdflt;
3106 maxmtu = tcp_maxmtu6(inc);
3107 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3108 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3113 maxmtu = tcp_maxmtu(inc);
3114 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3115 min_protoh = sizeof(struct tcpiphdr);
3117 if (maxmtu && thcmtu)
3118 mss = min(maxmtu, thcmtu) - min_protoh;
3119 else if (maxmtu || thcmtu)
3120 mss = max(maxmtu, thcmtu) - min_protoh;
3127 * On a partial ack arrives, force the retransmission of the
3128 * next unacknowledged segment. Do not clear tp->t_dupacks.
3129 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3133 tcp_newreno_partial_ack(tp, th)
3137 tcp_seq onxt = tp->snd_nxt;
3138 u_long ocwnd = tp->snd_cwnd;
3140 callout_stop(tp->tt_rexmt);
3142 tp->snd_nxt = th->th_ack;
3144 * Set snd_cwnd to one segment beyond acknowledged offset.
3145 * (tp->snd_una has not yet been updated when this function is called.)
3147 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3148 tp->t_flags |= TF_ACKNOW;
3149 (void) tcp_output(tp);
3150 tp->snd_cwnd = ocwnd;
3151 if (SEQ_GT(onxt, tp->snd_nxt))
3154 * Partial window deflation. Relies on fact that tp->snd_una
3157 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3158 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3161 tp->snd_cwnd += tp->t_maxseg;
3165 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3166 * looking for a pcb in the listen state. Returns 0 otherwise.
3169 tcp_timewait(inp, to, th, m, tlen)
3180 int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3182 const int isipv6 = 0;
3185 /* tcbinfo lock required for tcp_twclose(), tcp_2msl_reset. */
3186 INP_INFO_WLOCK_ASSERT(&tcbinfo);
3187 INP_LOCK_ASSERT(inp);
3190 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
3191 * still present. This is undesirable, but temporarily necessary
3192 * until we work out how to handle inpcb's who's timewait state has
3199 thflags = th->th_flags;
3202 * NOTE: for FIN_WAIT_2 (to be added later),
3203 * must validate sequence number before accepting RST
3207 * If the segment contains RST:
3208 * Drop the segment - see Stevens, vol. 2, p. 964 and
3211 if (thflags & TH_RST)
3215 /* PAWS not needed at the moment */
3217 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3218 * and it's less than ts_recent, drop it.
3220 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3221 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3222 if ((thflags & TH_ACK) == 0)
3227 * ts_recent is never updated because we never accept new segments.
3232 * If a new connection request is received
3233 * while in TIME_WAIT, drop the old connection
3234 * and start over if the sequence numbers
3235 * are above the previous ones.
3237 if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3243 * Drop the the segment if it does not contain an ACK.
3245 if ((thflags & TH_ACK) == 0)
3249 * Reset the 2MSL timer if this is a duplicate FIN.
3251 if (thflags & TH_FIN) {
3252 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3253 if (seq + 1 == tw->rcv_nxt)
3254 tcp_timer_2msl_reset(tw, 2 * tcp_msl, 1);
3258 * Acknowledge the segment if it has data or is not a duplicate ACK.
3260 if (thflags != TH_ACK || tlen != 0 ||
3261 th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3262 tcp_twrespond(tw, TH_ACK);
3266 * Generate a RST, dropping incoming segment.
3267 * Make ACK acceptable to originator of segment.
3268 * Don't bother to respond if destination was broadcast/multicast.
3270 if (m->m_flags & (M_BCAST|M_MCAST))
3273 struct ip6_hdr *ip6;
3275 /* IPv6 anycast check is done at tcp6_input() */
3276 ip6 = mtod(m, struct ip6_hdr *);
3277 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3278 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3283 ip = mtod(m, struct ip *);
3284 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3285 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3286 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3287 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3290 if (thflags & TH_ACK) {
3292 mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3294 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3296 mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);