The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/tcp_input.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*
    2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
    3  *      The Regents of the University of California.  All rights reserved.
    4  *
    5  * Redistribution and use in source and binary forms, with or without
    6  * modification, are permitted provided that the following conditions
    7  * are met:
    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.
   16  *
   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
   27  * SUCH DAMAGE.
   28  *
   29  *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
   30  * $FreeBSD: releng/5.3/sys/netinet/tcp_input.c 147670 2005-06-29 21:46:15Z simon $
   31  */
   32 
   33 #include "opt_ipfw.h"           /* for ipfw_fwd         */
   34 #include "opt_inet.h"
   35 #include "opt_inet6.h"
   36 #include "opt_ipsec.h"
   37 #include "opt_mac.h"
   38 #include "opt_tcpdebug.h"
   39 #include "opt_tcp_input.h"
   40 #include "opt_tcp_sack.h"
   41 
   42 #include <sys/param.h>
   43 #include <sys/kernel.h>
   44 #include <sys/mac.h>
   45 #include <sys/malloc.h>
   46 #include <sys/mbuf.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>
   55 
   56 #include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
   57 
   58 #include <vm/uma.h>
   59 
   60 #include <net/if.h>
   61 #include <net/route.h>
   62 
   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>    /* for ICMP_BANDLIM             */
   69 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM             */
   70 #include <netinet/ip_var.h>
   71 #include <netinet/ip6.h>
   72 #include <netinet/icmp6.h>
   73 #include <netinet6/in6_pcb.h>
   74 #include <netinet6/ip6_var.h>
   75 #include <netinet6/nd6.h>
   76 #include <netinet/tcp.h>
   77 #include <netinet/tcp_fsm.h>
   78 #include <netinet/tcp_seq.h>
   79 #include <netinet/tcp_timer.h>
   80 #include <netinet/tcp_var.h>
   81 #include <netinet6/tcp6_var.h>
   82 #include <netinet/tcpip.h>
   83 #ifdef TCPDEBUG
   84 #include <netinet/tcp_debug.h>
   85 #endif /* TCPDEBUG */
   86 
   87 #ifdef FAST_IPSEC
   88 #include <netipsec/ipsec.h>
   89 #include <netipsec/ipsec6.h>
   90 #endif /*FAST_IPSEC*/
   91 
   92 #ifdef IPSEC
   93 #include <netinet6/ipsec.h>
   94 #include <netinet6/ipsec6.h>
   95 #include <netkey/key.h>
   96 #endif /*IPSEC*/
   97 
   98 #include <machine/in_cksum.h>
   99 
  100 static const int tcprexmtthresh = 3;
  101 tcp_cc  tcp_ccgen;
  102 
  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)");
  106 
  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");
  110 
  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");
  114 
  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");
  119 
  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");
  124 #endif
  125 
  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)");
  129 
  130 static int tcp_do_rfc3390 = 1;
  131 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
  132     &tcp_do_rfc3390, 0,
  133     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
  134 
  135 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
  136             "TCP Segment Reassembly Queue");
  137 
  138 static int tcp_reass_maxseg = 0;
  139 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
  140            &tcp_reass_maxseg, 0,
  141            "Global maximum number of TCP Segments in Reassembly Queue");
  142 
  143 int tcp_reass_qsize = 0;
  144 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
  145            &tcp_reass_qsize, 0,
  146            "Global number of TCP Segments currently in Reassembly Queue");
  147 
  148 static int tcp_reass_maxqlen = 48;
  149 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
  150            &tcp_reass_maxqlen, 0,
  151            "Maximum number of TCP Segments per individual Reassembly Queue");
  152 
  153 static int tcp_reass_overflows = 0;
  154 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
  155            &tcp_reass_overflows, 0,
  156            "Global number of TCP Segment Reassembly Queue Overflows");
  157 
  158 struct inpcbhead tcb;
  159 #define tcb6    tcb  /* for KAME src sync over BSD*'s */
  160 struct inpcbinfo tcbinfo;
  161 struct mtx      *tcbinfo_mtx;
  162 
  163 static void      tcp_dooptions(struct tcpcb *, struct tcpopt *, u_char *,
  164                      int, int, struct tcphdr *);
  165 
  166 static void      tcp_pulloutofband(struct socket *,
  167                      struct tcphdr *, struct mbuf *, int);
  168 static int       tcp_reass(struct tcpcb *, struct tcphdr *, int *,
  169                      struct mbuf *);
  170 static void      tcp_xmit_timer(struct tcpcb *, int);
  171 static void      tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
  172 static int       tcp_timewait(struct tcptw *, struct tcpopt *,
  173                      struct tcphdr *, struct mbuf *, int);
  174 
  175 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
  176 #ifdef INET6
  177 #define ND6_HINT(tp) \
  178 do { \
  179         if ((tp) && (tp)->t_inpcb && \
  180             ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
  181                 nd6_nud_hint(NULL, NULL, 0); \
  182 } while (0)
  183 #else
  184 #define ND6_HINT(tp)
  185 #endif
  186 
  187 /*
  188  * Indicate whether this ack should be delayed.  We can delay the ack if
  189  *      - there is no delayed ack timer in progress and
  190  *      - our last ack wasn't a 0-sized window.  We never want to delay
  191  *        the ack that opens up a 0-sized window and
  192  *              - delayed acks are enabled or
  193  *              - this is a half-synchronized T/TCP connection.
  194  */
  195 #define DELAY_ACK(tp)                                                   \
  196         ((!callout_active(tp->tt_delack) &&                             \
  197             (tp->t_flags & TF_RXWIN0SENT) == 0) &&                      \
  198             (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
  199 
  200 /* Initialize TCP reassembly queue */
  201 uma_zone_t      tcp_reass_zone;
  202 void
  203 tcp_reass_init()
  204 {
  205         tcp_reass_maxseg = nmbclusters / 16;
  206         TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
  207             &tcp_reass_maxseg);
  208         tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
  209             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  210         uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
  211 }
  212 
  213 static int
  214 tcp_reass(tp, th, tlenp, m)
  215         register struct tcpcb *tp;
  216         register struct tcphdr *th;
  217         int *tlenp;
  218         struct mbuf *m;
  219 {
  220         struct tseg_qent *q;
  221         struct tseg_qent *p = NULL;
  222         struct tseg_qent *nq;
  223         struct tseg_qent *te = NULL;
  224         struct socket *so = tp->t_inpcb->inp_socket;
  225         int flags;
  226 
  227         /*
  228          * XXX: tcp_reass() is rather inefficient with its data structures
  229          * and should be rewritten (see NetBSD for optimizations).  While
  230          * doing that it should move to its own file tcp_reass.c.
  231          */
  232 
  233         /*
  234          * Call with th==0 after become established to
  235          * force pre-ESTABLISHED data up to user socket.
  236          */
  237         if (th == 0)
  238                 goto present;
  239 
  240         /*
  241          * Limit the number of segments in the reassembly queue to prevent
  242          * holding on to too many segments (and thus running out of mbufs).
  243          * Make sure to let the missing segment through which caused this
  244          * queue.  Always keep one global queue entry spare to be able to
  245          * process the missing segment.
  246          */
  247         if (th->th_seq != tp->rcv_nxt &&
  248             (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
  249              tp->t_segqlen >= tcp_reass_maxqlen)) {
  250                 tcp_reass_overflows++;
  251                 tcpstat.tcps_rcvmemdrop++;
  252                 m_freem(m);
  253                 return (0);
  254         }
  255 
  256         /*
  257          * Allocate a new queue entry. If we can't, or hit the zone limit
  258          * just drop the pkt.
  259          */
  260         te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
  261         if (te == NULL) {
  262                 tcpstat.tcps_rcvmemdrop++;
  263                 m_freem(m);
  264                 return (0);
  265         }
  266         tp->t_segqlen++;
  267         tcp_reass_qsize++;
  268 
  269         /*
  270          * Find a segment which begins after this one does.
  271          */
  272         LIST_FOREACH(q, &tp->t_segq, tqe_q) {
  273                 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
  274                         break;
  275                 p = q;
  276         }
  277 
  278         /*
  279          * If there is a preceding segment, it may provide some of
  280          * our data already.  If so, drop the data from the incoming
  281          * segment.  If it provides all of our data, drop us.
  282          */
  283         if (p != NULL) {
  284                 register int i;
  285                 /* conversion to int (in i) handles seq wraparound */
  286                 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
  287                 if (i > 0) {
  288                         if (i >= *tlenp) {
  289                                 tcpstat.tcps_rcvduppack++;
  290                                 tcpstat.tcps_rcvdupbyte += *tlenp;
  291                                 m_freem(m);
  292                                 uma_zfree(tcp_reass_zone, te);
  293                                 tp->t_segqlen--;
  294                                 tcp_reass_qsize--;
  295                                 /*
  296                                  * Try to present any queued data
  297                                  * at the left window edge to the user.
  298                                  * This is needed after the 3-WHS
  299                                  * completes.
  300                                  */
  301                                 goto present;   /* ??? */
  302                         }
  303                         m_adj(m, i);
  304                         *tlenp -= i;
  305                         th->th_seq += i;
  306                 }
  307         }
  308         tcpstat.tcps_rcvoopack++;
  309         tcpstat.tcps_rcvoobyte += *tlenp;
  310 
  311         /*
  312          * While we overlap succeeding segments trim them or,
  313          * if they are completely covered, dequeue them.
  314          */
  315         while (q) {
  316                 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
  317                 if (i <= 0)
  318                         break;
  319                 if (i < q->tqe_len) {
  320                         q->tqe_th->th_seq += i;
  321                         q->tqe_len -= i;
  322                         m_adj(q->tqe_m, i);
  323                         break;
  324                 }
  325 
  326                 nq = LIST_NEXT(q, tqe_q);
  327                 LIST_REMOVE(q, tqe_q);
  328                 m_freem(q->tqe_m);
  329                 uma_zfree(tcp_reass_zone, q);
  330                 tp->t_segqlen--;
  331                 tcp_reass_qsize--;
  332                 q = nq;
  333         }
  334 
  335         /* Insert the new segment queue entry into place. */
  336         te->tqe_m = m;
  337         te->tqe_th = th;
  338         te->tqe_len = *tlenp;
  339 
  340         if (p == NULL) {
  341                 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
  342         } else {
  343                 LIST_INSERT_AFTER(p, te, tqe_q);
  344         }
  345 
  346 present:
  347         /*
  348          * Present data to user, advancing rcv_nxt through
  349          * completed sequence space.
  350          */
  351         if (!TCPS_HAVEESTABLISHED(tp->t_state))
  352                 return (0);
  353         q = LIST_FIRST(&tp->t_segq);
  354         if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
  355                 return (0);
  356         SOCKBUF_LOCK(&so->so_rcv);
  357         do {
  358                 tp->rcv_nxt += q->tqe_len;
  359                 flags = q->tqe_th->th_flags & TH_FIN;
  360                 nq = LIST_NEXT(q, tqe_q);
  361                 LIST_REMOVE(q, tqe_q);
  362                 /* Unlocked read. */
  363                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
  364                         m_freem(q->tqe_m);
  365                 else
  366                         sbappendstream_locked(&so->so_rcv, q->tqe_m);
  367                 uma_zfree(tcp_reass_zone, q);
  368                 tp->t_segqlen--;
  369                 tcp_reass_qsize--;
  370                 q = nq;
  371         } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
  372         ND6_HINT(tp);
  373         sorwakeup_locked(so);
  374         return (flags);
  375 }
  376 
  377 /*
  378  * TCP input routine, follows pages 65-76 of the
  379  * protocol specification dated September, 1981 very closely.
  380  */
  381 #ifdef INET6
  382 int
  383 tcp6_input(mp, offp, proto)
  384         struct mbuf **mp;
  385         int *offp, proto;
  386 {
  387         register struct mbuf *m = *mp;
  388         struct in6_ifaddr *ia6;
  389 
  390         IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
  391 
  392         /*
  393          * draft-itojun-ipv6-tcp-to-anycast
  394          * better place to put this in?
  395          */
  396         ia6 = ip6_getdstifaddr(m);
  397         if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
  398                 struct ip6_hdr *ip6;
  399 
  400                 ip6 = mtod(m, struct ip6_hdr *);
  401                 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
  402                             (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
  403                 return IPPROTO_DONE;
  404         }
  405 
  406         tcp_input(m, *offp);
  407         return IPPROTO_DONE;
  408 }
  409 #endif
  410 
  411 void
  412 tcp_input(m, off0)
  413         register struct mbuf *m;
  414         int off0;
  415 {
  416         register struct tcphdr *th;
  417         register struct ip *ip = NULL;
  418         register struct ipovly *ipov;
  419         register struct inpcb *inp = NULL;
  420         u_char *optp = NULL;
  421         int optlen = 0;
  422         int len, tlen, off;
  423         int drop_hdrlen;
  424         register struct tcpcb *tp = 0;
  425         register int thflags;
  426         struct socket *so = 0;
  427         int todrop, acked, ourfinisacked, needoutput = 0;
  428         u_long tiwin;
  429         struct tcpopt to;               /* options in this segment */
  430         struct rmxp_tao tao;            /* our TAO cache entry */
  431         int headlocked = 0;
  432 #ifdef IPFIREWALL_FORWARD
  433         struct m_tag *fwd_tag;
  434 #endif
  435         int rstreason; /* For badport_bandlim accounting purposes */
  436 
  437         struct ip6_hdr *ip6 = NULL;
  438 #ifdef INET6
  439         int isipv6;
  440 #else
  441         const int isipv6 = 0;
  442 #endif
  443 
  444 #ifdef TCPDEBUG
  445         /*
  446          * The size of tcp_saveipgen must be the size of the max ip header,
  447          * now IPv6.
  448          */
  449         u_char tcp_saveipgen[40];
  450         struct tcphdr tcp_savetcp;
  451         short ostate = 0;
  452 #endif
  453 
  454 #ifdef INET6
  455         isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
  456 #endif
  457         bzero(&tao, sizeof(tao));
  458         bzero((char *)&to, sizeof(to));
  459 
  460         tcpstat.tcps_rcvtotal++;
  461 
  462         if (isipv6) {
  463 #ifdef INET6
  464                 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
  465                 ip6 = mtod(m, struct ip6_hdr *);
  466                 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
  467                 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
  468                         tcpstat.tcps_rcvbadsum++;
  469                         goto drop;
  470                 }
  471                 th = (struct tcphdr *)((caddr_t)ip6 + off0);
  472 
  473                 /*
  474                  * Be proactive about unspecified IPv6 address in source.
  475                  * As we use all-zero to indicate unbounded/unconnected pcb,
  476                  * unspecified IPv6 address can be used to confuse us.
  477                  *
  478                  * Note that packets with unspecified IPv6 destination is
  479                  * already dropped in ip6_input.
  480                  */
  481                 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
  482                         /* XXX stat */
  483                         goto drop;
  484                 }
  485 #else
  486                 th = NULL;              /* XXX: avoid compiler warning */
  487 #endif
  488         } else {
  489                 /*
  490                  * Get IP and TCP header together in first mbuf.
  491                  * Note: IP leaves IP header in first mbuf.
  492                  */
  493                 if (off0 > sizeof (struct ip)) {
  494                         ip_stripoptions(m, (struct mbuf *)0);
  495                         off0 = sizeof(struct ip);
  496                 }
  497                 if (m->m_len < sizeof (struct tcpiphdr)) {
  498                         if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
  499                                 tcpstat.tcps_rcvshort++;
  500                                 return;
  501                         }
  502                 }
  503                 ip = mtod(m, struct ip *);
  504                 ipov = (struct ipovly *)ip;
  505                 th = (struct tcphdr *)((caddr_t)ip + off0);
  506                 tlen = ip->ip_len;
  507 
  508                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
  509                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
  510                                 th->th_sum = m->m_pkthdr.csum_data;
  511                         else
  512                                 th->th_sum = in_pseudo(ip->ip_src.s_addr,
  513                                                 ip->ip_dst.s_addr,
  514                                                 htonl(m->m_pkthdr.csum_data +
  515                                                         ip->ip_len +
  516                                                         IPPROTO_TCP));
  517                         th->th_sum ^= 0xffff;
  518 #ifdef TCPDEBUG
  519                         ipov->ih_len = (u_short)tlen;
  520                         ipov->ih_len = htons(ipov->ih_len);
  521 #endif
  522                 } else {
  523                         /*
  524                          * Checksum extended TCP header and data.
  525                          */
  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);
  531                 }
  532                 if (th->th_sum) {
  533                         tcpstat.tcps_rcvbadsum++;
  534                         goto drop;
  535                 }
  536 #ifdef INET6
  537                 /* Re-initialization for later version check */
  538                 ip->ip_v = IPVERSION;
  539 #endif
  540         }
  541 
  542         /*
  543          * Check that TCP offset makes sense,
  544          * pull out TCP options and adjust length.              XXX
  545          */
  546         off = th->th_off << 2;
  547         if (off < sizeof (struct tcphdr) || off > tlen) {
  548                 tcpstat.tcps_rcvbadoff++;
  549                 goto drop;
  550         }
  551         tlen -= off;    /* tlen is used instead of ti->ti_len */
  552         if (off > sizeof (struct tcphdr)) {
  553                 if (isipv6) {
  554 #ifdef INET6
  555                         IP6_EXTHDR_CHECK(m, off0, off, );
  556                         ip6 = mtod(m, struct ip6_hdr *);
  557                         th = (struct tcphdr *)((caddr_t)ip6 + off0);
  558 #endif
  559                 } else {
  560                         if (m->m_len < sizeof(struct ip) + off) {
  561                                 if ((m = m_pullup(m, sizeof (struct ip) + off))
  562                                                 == 0) {
  563                                         tcpstat.tcps_rcvshort++;
  564                                         return;
  565                                 }
  566                                 ip = mtod(m, struct ip *);
  567                                 ipov = (struct ipovly *)ip;
  568                                 th = (struct tcphdr *)((caddr_t)ip + off0);
  569                         }
  570                 }
  571                 optlen = off - sizeof (struct tcphdr);
  572                 optp = (u_char *)(th + 1);
  573         }
  574         thflags = th->th_flags;
  575 
  576 #ifdef TCP_DROP_SYNFIN
  577         /*
  578          * If the drop_synfin option is enabled, drop all packets with
  579          * both the SYN and FIN bits set. This prevents e.g. nmap from
  580          * identifying the TCP/IP stack.
  581          *
  582          * This is a violation of the TCP specification.
  583          */
  584         if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
  585                 goto drop;
  586 #endif
  587 
  588         /*
  589          * Convert TCP protocol specific fields to host format.
  590          */
  591         th->th_seq = ntohl(th->th_seq);
  592         th->th_ack = ntohl(th->th_ack);
  593         th->th_win = ntohs(th->th_win);
  594         th->th_urp = ntohs(th->th_urp);
  595 
  596         /*
  597          * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
  598          * until after ip6_savecontrol() is called and before other functions
  599          * which don't want those proto headers.
  600          * Because ip6_savecontrol() is going to parse the mbuf to
  601          * search for data to be passed up to user-land, it wants mbuf
  602          * parameters to be unchanged.
  603          * XXX: the call of ip6_savecontrol() has been obsoleted based on
  604          * latest version of the advanced API (20020110).
  605          */
  606         drop_hdrlen = off0 + off;
  607 
  608         /*
  609          * Locate pcb for segment.
  610          */
  611         INP_INFO_WLOCK(&tcbinfo);
  612         headlocked = 1;
  613 findpcb:
  614 #ifdef IPFIREWALL_FORWARD
  615         /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
  616         fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
  617 
  618         if (fwd_tag != NULL && isipv6 == 0) {   /* IPv6 support is not yet */
  619                 struct sockaddr_in *next_hop;
  620 
  621                 next_hop = (struct sockaddr_in *)(fwd_tag+1);
  622                 /*
  623                  * Transparently forwarded. Pretend to be the destination.
  624                  * already got one like this?
  625                  */
  626                 inp = in_pcblookup_hash(&tcbinfo,
  627                                         ip->ip_src, th->th_sport,
  628                                         ip->ip_dst, th->th_dport,
  629                                         0, m->m_pkthdr.rcvif);
  630                 if (!inp) {
  631                         /* It's new.  Try to find the ambushing socket. */
  632                         inp = in_pcblookup_hash(&tcbinfo,
  633                                                 ip->ip_src, th->th_sport,
  634                                                 next_hop->sin_addr,
  635                                                 next_hop->sin_port ?
  636                                                     ntohs(next_hop->sin_port) :
  637                                                     th->th_dport,
  638                                                 1, m->m_pkthdr.rcvif);
  639                 }
  640                 /* Remove the tag from the packet.  We don't need it anymore. */
  641                 m_tag_delete(m, fwd_tag);
  642         } else {
  643 #endif /* IPFIREWALL_FORWARD */
  644                 if (isipv6) {
  645 #ifdef INET6
  646                         inp = in6_pcblookup_hash(&tcbinfo,
  647                                                  &ip6->ip6_src, th->th_sport,
  648                                                  &ip6->ip6_dst, th->th_dport,
  649                                                  1, m->m_pkthdr.rcvif);
  650 #endif
  651                 } else
  652                         inp = in_pcblookup_hash(&tcbinfo,
  653                                                 ip->ip_src, th->th_sport,
  654                                                 ip->ip_dst, th->th_dport,
  655                                                 1, m->m_pkthdr.rcvif);
  656 #ifdef IPFIREWALL_FORWARD
  657         }
  658 #endif /* IPFIREWALL_FORWARD */
  659 
  660 #if defined(IPSEC) || defined(FAST_IPSEC)
  661 #ifdef INET6
  662         if (isipv6) {
  663                 if (inp != NULL && ipsec6_in_reject(m, inp)) {
  664 #ifdef IPSEC
  665                         ipsec6stat.in_polvio++;
  666 #endif
  667                         goto drop;
  668                 }
  669         } else
  670 #endif /* INET6 */
  671         if (inp != NULL && ipsec4_in_reject(m, inp)) {
  672 #ifdef IPSEC
  673                 ipsecstat.in_polvio++;
  674 #endif
  675                 goto drop;
  676         }
  677 #endif /*IPSEC || FAST_IPSEC*/
  678 
  679         /*
  680          * If the state is CLOSED (i.e., TCB does not exist) then
  681          * all data in the incoming segment is discarded.
  682          * If the TCB exists but is in CLOSED state, it is embryonic,
  683          * but should either do a listen or a connect soon.
  684          */
  685         if (inp == NULL) {
  686                 if (log_in_vain) {
  687 #ifdef INET6
  688                         char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
  689 #else
  690                         char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
  691 #endif
  692 
  693                         if (isipv6) {
  694 #ifdef INET6
  695                                 strcpy(dbuf, "[");
  696                                 strcpy(sbuf, "[");
  697                                 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
  698                                 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
  699                                 strcat(dbuf, "]");
  700                                 strcat(sbuf, "]");
  701 #endif
  702                         } else {
  703                                 strcpy(dbuf, inet_ntoa(ip->ip_dst));
  704                                 strcpy(sbuf, inet_ntoa(ip->ip_src));
  705                         }
  706                         switch (log_in_vain) {
  707                         case 1:
  708                                 if ((thflags & TH_SYN) == 0)
  709                                         break;
  710                                 /* FALLTHROUGH */
  711                         case 2:
  712                                 log(LOG_INFO,
  713                                     "Connection attempt to TCP %s:%d "
  714                                     "from %s:%d flags:0x%02x\n",
  715                                     dbuf, ntohs(th->th_dport), sbuf,
  716                                     ntohs(th->th_sport), thflags);
  717                                 break;
  718                         default:
  719                                 break;
  720                         }
  721                 }
  722                 if (blackhole) {
  723                         switch (blackhole) {
  724                         case 1:
  725                                 if (thflags & TH_SYN)
  726                                         goto drop;
  727                                 break;
  728                         case 2:
  729                                 goto drop;
  730                         default:
  731                                 goto drop;
  732                         }
  733                 }
  734                 rstreason = BANDLIM_RST_CLOSEDPORT;
  735                 goto dropwithreset;
  736         }
  737         INP_LOCK(inp);
  738         if (inp->inp_vflag & INP_TIMEWAIT) {
  739                 /*
  740                  * The only option of relevance is TOF_CC, and only if
  741                  * present in a SYN segment.  See tcp_timewait().
  742                  */
  743                 if (thflags & TH_SYN)
  744                         tcp_dooptions((struct tcpcb *)NULL, &to, optp, optlen, 1, th);
  745                 if (tcp_timewait((struct tcptw *)inp->inp_ppcb,
  746                     &to, th, m, tlen))
  747                         goto findpcb;
  748                 /*
  749                  * tcp_timewait unlocks inp.
  750                  */
  751                 INP_INFO_WUNLOCK(&tcbinfo);
  752                 return;
  753         }
  754         tp = intotcpcb(inp);
  755         if (tp == 0) {
  756                 INP_UNLOCK(inp);
  757                 rstreason = BANDLIM_RST_CLOSEDPORT;
  758                 goto dropwithreset;
  759         }
  760         if (tp->t_state == TCPS_CLOSED)
  761                 goto drop;
  762 
  763         /* Unscale the window into a 32-bit value. */
  764         if ((thflags & TH_SYN) == 0)
  765                 tiwin = th->th_win << tp->snd_scale;
  766         else
  767                 tiwin = th->th_win;
  768 
  769 #ifdef MAC
  770         INP_LOCK_ASSERT(inp);
  771         if (mac_check_inpcb_deliver(inp, m))
  772                 goto drop;
  773 #endif
  774         so = inp->inp_socket;
  775 #ifdef TCPDEBUG
  776         if (so->so_options & SO_DEBUG) {
  777                 ostate = tp->t_state;
  778                 if (isipv6)
  779                         bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
  780                 else
  781                         bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
  782                 tcp_savetcp = *th;
  783         }
  784 #endif
  785         if (so->so_options & SO_ACCEPTCONN) {
  786                 struct in_conninfo inc;
  787 
  788 #ifdef INET6
  789                 inc.inc_isipv6 = isipv6;
  790 #endif
  791                 if (isipv6) {
  792                         inc.inc6_faddr = ip6->ip6_src;
  793                         inc.inc6_laddr = ip6->ip6_dst;
  794                 } else {
  795                         inc.inc_faddr = ip->ip_src;
  796                         inc.inc_laddr = ip->ip_dst;
  797                 }
  798                 inc.inc_fport = th->th_sport;
  799                 inc.inc_lport = th->th_dport;
  800 
  801                 /*
  802                  * If the state is LISTEN then ignore segment if it contains
  803                  * a RST.  If the segment contains an ACK then it is bad and
  804                  * send a RST.  If it does not contain a SYN then it is not
  805                  * interesting; drop it.
  806                  *
  807                  * If the state is SYN_RECEIVED (syncache) and seg contains
  808                  * an ACK, but not for our SYN/ACK, send a RST.  If the seg
  809                  * contains a RST, check the sequence number to see if it
  810                  * is a valid reset segment.
  811                  */
  812                 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
  813                         if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
  814                                 if (!syncache_expand(&inc, th, &so, m)) {
  815                                         /*
  816                                          * No syncache entry, or ACK was not
  817                                          * for our SYN/ACK.  Send a RST.
  818                                          */
  819                                         tcpstat.tcps_badsyn++;
  820                                         rstreason = BANDLIM_RST_OPENPORT;
  821                                         goto dropwithreset;
  822                                 }
  823                                 if (so == NULL) {
  824                                         /*
  825                                          * Could not complete 3-way handshake,
  826                                          * connection is being closed down, and
  827                                          * syncache will free mbuf.
  828                                          */
  829                                         INP_UNLOCK(inp);
  830                                         INP_INFO_WUNLOCK(&tcbinfo);
  831                                         return;
  832                                 }
  833                                 /*
  834                                  * Socket is created in state SYN_RECEIVED.
  835                                  * Continue processing segment.
  836                                  */
  837                                 INP_UNLOCK(inp);
  838                                 inp = sotoinpcb(so);
  839                                 INP_LOCK(inp);
  840                                 tp = intotcpcb(inp);
  841                                 /*
  842                                  * This is what would have happened in
  843                                  * tcp_output() when the SYN,ACK was sent.
  844                                  */
  845                                 tp->snd_up = tp->snd_una;
  846                                 tp->snd_max = tp->snd_nxt = tp->iss + 1;
  847                                 tp->last_ack_sent = tp->rcv_nxt;
  848                                 /*
  849                                  * RFC1323: The window in SYN & SYN/ACK
  850                                  * segments is never scaled.
  851                                  */
  852                                 tp->snd_wnd = tiwin;    /* unscaled */
  853                                 goto after_listen;
  854                         }
  855                         if (thflags & TH_RST) {
  856                                 syncache_chkrst(&inc, th);
  857                                 goto drop;
  858                         }
  859                         if (thflags & TH_ACK) {
  860                                 syncache_badack(&inc);
  861                                 tcpstat.tcps_badsyn++;
  862                                 rstreason = BANDLIM_RST_OPENPORT;
  863                                 goto dropwithreset;
  864                         }
  865                         goto drop;
  866                 }
  867 
  868                 /*
  869                  * Segment's flags are (SYN) or (SYN|FIN).
  870                  */
  871 #ifdef INET6
  872                 /*
  873                  * If deprecated address is forbidden,
  874                  * we do not accept SYN to deprecated interface
  875                  * address to prevent any new inbound connection from
  876                  * getting established.
  877                  * When we do not accept SYN, we send a TCP RST,
  878                  * with deprecated source address (instead of dropping
  879                  * it).  We compromise it as it is much better for peer
  880                  * to send a RST, and RST will be the final packet
  881                  * for the exchange.
  882                  *
  883                  * If we do not forbid deprecated addresses, we accept
  884                  * the SYN packet.  RFC2462 does not suggest dropping
  885                  * SYN in this case.
  886                  * If we decipher RFC2462 5.5.4, it says like this:
  887                  * 1. use of deprecated addr with existing
  888                  *    communication is okay - "SHOULD continue to be
  889                  *    used"
  890                  * 2. use of it with new communication:
  891                  *   (2a) "SHOULD NOT be used if alternate address
  892                  *        with sufficient scope is available"
  893                  *   (2b) nothing mentioned otherwise.
  894                  * Here we fall into (2b) case as we have no choice in
  895                  * our source address selection - we must obey the peer.
  896                  *
  897                  * The wording in RFC2462 is confusing, and there are
  898                  * multiple description text for deprecated address
  899                  * handling - worse, they are not exactly the same.
  900                  * I believe 5.5.4 is the best one, so we follow 5.5.4.
  901                  */
  902                 if (isipv6 && !ip6_use_deprecated) {
  903                         struct in6_ifaddr *ia6;
  904 
  905                         if ((ia6 = ip6_getdstifaddr(m)) &&
  906                             (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
  907                                 INP_UNLOCK(inp);
  908                                 tp = NULL;
  909                                 rstreason = BANDLIM_RST_OPENPORT;
  910                                 goto dropwithreset;
  911                         }
  912                 }
  913 #endif
  914                 /*
  915                  * If it is from this socket, drop it, it must be forged.
  916                  * Don't bother responding if the destination was a broadcast.
  917                  */
  918                 if (th->th_dport == th->th_sport) {
  919                         if (isipv6) {
  920                                 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
  921                                                        &ip6->ip6_src))
  922                                         goto drop;
  923                         } else {
  924                                 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
  925                                         goto drop;
  926                         }
  927                 }
  928                 /*
  929                  * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
  930                  *
  931                  * Note that it is quite possible to receive unicast
  932                  * link-layer packets with a broadcast IP address. Use
  933                  * in_broadcast() to find them.
  934                  */
  935                 if (m->m_flags & (M_BCAST|M_MCAST))
  936                         goto drop;
  937                 if (isipv6) {
  938                         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
  939                             IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
  940                                 goto drop;
  941                 } else {
  942                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
  943                             IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
  944                             ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
  945                             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
  946                                 goto drop;
  947                 }
  948                 /*
  949                  * SYN appears to be valid; create compressed TCP state
  950                  * for syncache, or perform t/tcp connection.
  951                  */
  952                 if (so->so_qlen <= so->so_qlimit) {
  953 #ifdef TCPDEBUG
  954                         if (so->so_options & SO_DEBUG)
  955                                 tcp_trace(TA_INPUT, ostate, tp,
  956                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
  957 #endif
  958                         tcp_dooptions(tp, &to, optp, optlen, 1, th);
  959                         if (!syncache_add(&inc, &to, th, &so, m))
  960                                 goto drop;
  961                         if (so == NULL) {
  962                                 /*
  963                                  * Entry added to syncache, mbuf used to
  964                                  * send SYN,ACK packet.
  965                                  */
  966                                 KASSERT(headlocked, ("headlocked"));
  967                                 INP_UNLOCK(inp);
  968                                 INP_INFO_WUNLOCK(&tcbinfo);
  969                                 return;
  970                         }
  971                         /*
  972                          * Segment passed TAO tests.
  973                          */
  974                         INP_UNLOCK(inp);
  975                         inp = sotoinpcb(so);
  976                         INP_LOCK(inp);
  977                         tp = intotcpcb(inp);
  978                         tp->snd_wnd = tiwin;
  979                         tp->t_starttime = ticks;
  980                         tp->t_state = TCPS_ESTABLISHED;
  981 
  982                         /*
  983                          * T/TCP logic:
  984                          * If there is a FIN or if there is data, then
  985                          * delay SYN,ACK(SYN) in the hope of piggy-backing
  986                          * it on a response segment.  Otherwise must send
  987                          * ACK now in case the other side is slow starting.
  988                          */
  989                         if (thflags & TH_FIN || tlen != 0)
  990                                 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
  991                         else
  992                                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
  993                         tcpstat.tcps_connects++;
  994                         soisconnected(so);
  995                         goto trimthenstep6;
  996                 }
  997                 goto drop;
  998         }
  999 after_listen:
 1000         KASSERT(headlocked, ("tcp_input(): after_listen head is not locked"));
 1001         INP_LOCK_ASSERT(inp);
 1002 
 1003         /* XXX temp debugging */
 1004         /* should not happen - syncache should pick up these connections */
 1005         if (tp->t_state == TCPS_LISTEN)
 1006                 panic("tcp_input: TCPS_LISTEN");
 1007 
 1008         /*
 1009          * This is the second part of the MSS DoS prevention code (after
 1010          * minmss on the sending side) and it deals with too many too small
 1011          * tcp packets in a too short timeframe (1 second).
 1012          *
 1013          * For every full second we count the number of received packets
 1014          * and bytes. If we get a lot of packets per second for this connection
 1015          * (tcp_minmssoverload) we take a closer look at it and compute the
 1016          * average packet size for the past second. If that is less than
 1017          * tcp_minmss we get too many packets with very small payload which
 1018          * is not good and burdens our system (and every packet generates
 1019          * a wakeup to the process connected to our socket). We can reasonable
 1020          * expect this to be small packet DoS attack to exhaust our CPU
 1021          * cycles.
 1022          *
 1023          * Care has to be taken for the minimum packet overload value. This
 1024          * value defines the minimum number of packets per second before we
 1025          * start to worry. This must not be too low to avoid killing for
 1026          * example interactive connections with many small packets like
 1027          * telnet or SSH.
 1028          *
 1029          * Setting either tcp_minmssoverload or tcp_minmss to "" disables
 1030          * this check.
 1031          *
 1032          * Account for packet if payload packet, skip over ACK, etc.
 1033          */
 1034         if (tcp_minmss && tcp_minmssoverload &&
 1035             tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
 1036                 if (tp->rcv_second > ticks) {
 1037                         tp->rcv_pps++;
 1038                         tp->rcv_byps += tlen + off;
 1039                         if (tp->rcv_pps > tcp_minmssoverload) {
 1040                                 if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
 1041                                         printf("too many small tcp packets from "
 1042                                                "%s:%u, av. %lubyte/packet, "
 1043                                                "dropping connection\n",
 1044 #ifdef INET6
 1045                                                 isipv6 ?
 1046                                                 ip6_sprintf(&inp->inp_inc.inc6_faddr) :
 1047 #endif
 1048                                                 inet_ntoa(inp->inp_inc.inc_faddr),
 1049                                                 inp->inp_inc.inc_fport,
 1050                                                 tp->rcv_byps / tp->rcv_pps);
 1051                                         tp = tcp_drop(tp, ECONNRESET);
 1052                                         tcpstat.tcps_minmssdrops++;
 1053                                         goto drop;
 1054                                 }
 1055                         }
 1056                 } else {
 1057                         tp->rcv_second = ticks + hz;
 1058                         tp->rcv_pps = 1;
 1059                         tp->rcv_byps = tlen + off;
 1060                 }
 1061         }
 1062 
 1063         /*
 1064          * Segment received on connection.
 1065          * Reset idle time and keep-alive timer.
 1066          */
 1067         tp->t_rcvtime = ticks;
 1068         if (TCPS_HAVEESTABLISHED(tp->t_state))
 1069                 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
 1070 
 1071         /*
 1072          * Process options only when we get SYN/ACK back. The SYN case
 1073          * for incoming connections is handled in tcp_syncache.
 1074          * XXX this is traditional behavior, may need to be cleaned up.
 1075          */
 1076         tcp_dooptions(tp, &to, optp, optlen, thflags & TH_SYN, th);
 1077         if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
 1078                 if (to.to_flags & TOF_SCALE) {
 1079                         tp->t_flags |= TF_RCVD_SCALE;
 1080                         tp->requested_s_scale = to.to_requested_s_scale;
 1081                 }
 1082                 if (to.to_flags & TOF_TS) {
 1083                         tp->t_flags |= TF_RCVD_TSTMP;
 1084                         tp->ts_recent = to.to_tsval;
 1085                         tp->ts_recent_age = ticks;
 1086                 }
 1087                 if (to.to_flags & (TOF_CC|TOF_CCNEW))
 1088                         tp->t_flags |= TF_RCVD_CC;
 1089                 if (to.to_flags & TOF_MSS)
 1090                         tcp_mss(tp, to.to_mss);
 1091                 if (tp->sack_enable) {
 1092                         if (!(to.to_flags & TOF_SACK))
 1093                                 tp->sack_enable = 0;
 1094                         else
 1095                                 tp->t_flags |= TF_SACK_PERMIT;
 1096                 }
 1097 
 1098         }
 1099 
 1100         if (tp->sack_enable) {
 1101                 /* Delete stale (cumulatively acked) SACK holes */
 1102                 tcp_del_sackholes(tp, th);
 1103                 tp->rcv_laststart = th->th_seq; /* last recv'd segment*/
 1104                 tp->rcv_lastend = th->th_seq + tlen;
 1105         }
 1106 
 1107         /*
 1108          * Header prediction: check for the two common cases
 1109          * of a uni-directional data xfer.  If the packet has
 1110          * no control flags, is in-sequence, the window didn't
 1111          * change and we're not retransmitting, it's a
 1112          * candidate.  If the length is zero and the ack moved
 1113          * forward, we're the sender side of the xfer.  Just
 1114          * free the data acked & wake any higher level process
 1115          * that was blocked waiting for space.  If the length
 1116          * is non-zero and the ack didn't move, we're the
 1117          * receiver side.  If we're getting packets in-order
 1118          * (the reassembly queue is empty), add the data to
 1119          * the socket buffer and note that we need a delayed ack.
 1120          * Make sure that the hidden state-flags are also off.
 1121          * Since we check for TCPS_ESTABLISHED above, it can only
 1122          * be TH_NEEDSYN.
 1123          */
 1124         if (tp->t_state == TCPS_ESTABLISHED &&
 1125             (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
 1126             ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
 1127             ((to.to_flags & TOF_TS) == 0 ||
 1128              TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
 1129             /*
 1130              * Using the CC option is compulsory if once started:
 1131              *   the segment is OK if no T/TCP was negotiated or
 1132              *   if the segment has a CC option equal to CCrecv
 1133              */
 1134             ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
 1135              ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
 1136             th->th_seq == tp->rcv_nxt &&
 1137             tiwin && tiwin == tp->snd_wnd &&
 1138             tp->snd_nxt == tp->snd_max) {
 1139 
 1140                 /*
 1141                  * If last ACK falls within this segment's sequence numbers,
 1142                  * record the timestamp.
 1143                  * NOTE that the test is modified according to the latest
 1144                  * proposal of the tcplw@cray.com list (Braden 1993/04/26).
 1145                  */
 1146                 if ((to.to_flags & TOF_TS) != 0 &&
 1147                     SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
 1148                         tp->ts_recent_age = ticks;
 1149                         tp->ts_recent = to.to_tsval;
 1150                 }
 1151 
 1152                 if (tlen == 0) {
 1153                         if (SEQ_GT(th->th_ack, tp->snd_una) &&
 1154                             SEQ_LEQ(th->th_ack, tp->snd_max) &&
 1155                             tp->snd_cwnd >= tp->snd_wnd &&
 1156                             ((!tcp_do_newreno && !tp->sack_enable &&
 1157                               tp->t_dupacks < tcprexmtthresh) ||
 1158                              ((tcp_do_newreno || tp->sack_enable) &&
 1159                               !IN_FASTRECOVERY(tp)))) {
 1160                                 KASSERT(headlocked, ("headlocked"));
 1161                                 INP_INFO_WUNLOCK(&tcbinfo);
 1162                                 /*
 1163                                  * this is a pure ack for outstanding data.
 1164                                  */
 1165                                 ++tcpstat.tcps_predack;
 1166                                 /*
 1167                                  * "bad retransmit" recovery
 1168                                  */
 1169                                 if (tp->t_rxtshift == 1 &&
 1170                                     ticks < tp->t_badrxtwin) {
 1171                                         ++tcpstat.tcps_sndrexmitbad;
 1172                                         tp->snd_cwnd = tp->snd_cwnd_prev;
 1173                                         tp->snd_ssthresh =
 1174                                             tp->snd_ssthresh_prev;
 1175                                         tp->snd_recover = tp->snd_recover_prev;
 1176                                         if (tp->t_flags & TF_WASFRECOVERY)
 1177                                             ENTER_FASTRECOVERY(tp);
 1178                                         tp->snd_nxt = tp->snd_max;
 1179                                         tp->t_badrxtwin = 0;
 1180                                 }
 1181 
 1182                                 /*
 1183                                  * Recalculate the transmit timer / rtt.
 1184                                  *
 1185                                  * Some boxes send broken timestamp replies
 1186                                  * during the SYN+ACK phase, ignore
 1187                                  * timestamps of 0 or we could calculate a
 1188                                  * huge RTT and blow up the retransmit timer.
 1189                                  */
 1190                                 if ((to.to_flags & TOF_TS) != 0 &&
 1191                                     to.to_tsecr) {
 1192                                         tcp_xmit_timer(tp,
 1193                                             ticks - to.to_tsecr + 1);
 1194                                 } else if (tp->t_rtttime &&
 1195                                             SEQ_GT(th->th_ack, tp->t_rtseq)) {
 1196                                         tcp_xmit_timer(tp,
 1197                                                         ticks - tp->t_rtttime);
 1198                                 }
 1199                                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
 1200                                 acked = th->th_ack - tp->snd_una;
 1201                                 tcpstat.tcps_rcvackpack++;
 1202                                 tcpstat.tcps_rcvackbyte += acked;
 1203                                 sbdrop(&so->so_snd, acked);
 1204                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
 1205                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 1206                                         tp->snd_recover = th->th_ack - 1;
 1207                                 tp->snd_una = th->th_ack;
 1208                                 /*
 1209                                  * pull snd_wl2 up to prevent seq wrap relative
 1210                                  * to th_ack.
 1211                                  */
 1212                                 tp->snd_wl2 = th->th_ack;
 1213                                 tp->t_dupacks = 0;
 1214                                 m_freem(m);
 1215                                 ND6_HINT(tp); /* some progress has been done */
 1216 
 1217                                 /*
 1218                                  * If all outstanding data are acked, stop
 1219                                  * retransmit timer, otherwise restart timer
 1220                                  * using current (possibly backed-off) value.
 1221                                  * If process is waiting for space,
 1222                                  * wakeup/selwakeup/signal.  If data
 1223                                  * are ready to send, let tcp_output
 1224                                  * decide between more output or persist.
 1225 
 1226 #ifdef TCPDEBUG
 1227                                 if (so->so_options & SO_DEBUG)
 1228                                         tcp_trace(TA_INPUT, ostate, tp,
 1229                                             (void *)tcp_saveipgen,
 1230                                             &tcp_savetcp, 0);
 1231 #endif
 1232                                  */
 1233                                 if (tp->snd_una == tp->snd_max)
 1234                                         callout_stop(tp->tt_rexmt);
 1235                                 else if (!callout_active(tp->tt_persist))
 1236                                         callout_reset(tp->tt_rexmt,
 1237                                                       tp->t_rxtcur,
 1238                                                       tcp_timer_rexmt, tp);
 1239 
 1240                                 sowwakeup(so);
 1241                                 if (so->so_snd.sb_cc)
 1242                                         (void) tcp_output(tp);
 1243                                 goto check_delack;
 1244                         }
 1245                 } else if (th->th_ack == tp->snd_una &&
 1246                     LIST_EMPTY(&tp->t_segq) &&
 1247                     tlen <= sbspace(&so->so_rcv)) {
 1248                         KASSERT(headlocked, ("headlocked"));
 1249                         INP_INFO_WUNLOCK(&tcbinfo);
 1250                         /*
 1251                          * this is a pure, in-sequence data packet
 1252                          * with nothing on the reassembly queue and
 1253                          * we have enough buffer space to take it.
 1254                          */
 1255                         /* Clean receiver SACK report if present */
 1256                         if (tp->sack_enable && tp->rcv_numsacks)
 1257                                 tcp_clean_sackreport(tp);
 1258                         ++tcpstat.tcps_preddat;
 1259                         tp->rcv_nxt += tlen;
 1260                         /*
 1261                          * Pull snd_wl1 up to prevent seq wrap relative to
 1262                          * th_seq.
 1263                          */
 1264                         tp->snd_wl1 = th->th_seq;
 1265                         /*
 1266                          * Pull rcv_up up to prevent seq wrap relative to
 1267                          * rcv_nxt.
 1268                          */
 1269                         tp->rcv_up = tp->rcv_nxt;
 1270                         tcpstat.tcps_rcvpack++;
 1271                         tcpstat.tcps_rcvbyte += tlen;
 1272                         ND6_HINT(tp);   /* some progress has been done */
 1273                         /*
 1274 #ifdef TCPDEBUG
 1275                         if (so->so_options & SO_DEBUG)
 1276                                 tcp_trace(TA_INPUT, ostate, tp,
 1277                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
 1278 #endif
 1279                          * Add data to socket buffer.
 1280                          */
 1281                         /* Unlocked read. */
 1282                         SOCKBUF_LOCK(&so->so_rcv);
 1283                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 1284                                 m_freem(m);
 1285                         } else {
 1286                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 1287                                 sbappendstream_locked(&so->so_rcv, m);
 1288                         }
 1289                         sorwakeup_locked(so);
 1290                         if (DELAY_ACK(tp)) {
 1291                                 tp->t_flags |= TF_DELACK;
 1292                         } else {
 1293                                 tp->t_flags |= TF_ACKNOW;
 1294                                 tcp_output(tp);
 1295                         }
 1296                         goto check_delack;
 1297                 }
 1298         }
 1299 
 1300         /*
 1301          * Calculate amount of space in receive window,
 1302          * and then do TCP input processing.
 1303          * Receive window is amount of space in rcv queue,
 1304          * but not less than advertised window.
 1305          */
 1306         { int win;
 1307 
 1308         win = sbspace(&so->so_rcv);
 1309         if (win < 0)
 1310                 win = 0;
 1311         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
 1312         }
 1313 
 1314         switch (tp->t_state) {
 1315 
 1316         /*
 1317          * If the state is SYN_RECEIVED:
 1318          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
 1319          */
 1320         case TCPS_SYN_RECEIVED:
 1321                 if ((thflags & TH_ACK) &&
 1322                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
 1323                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1324                                 rstreason = BANDLIM_RST_OPENPORT;
 1325                                 goto dropwithreset;
 1326                 }
 1327                 break;
 1328 
 1329         /*
 1330          * If the state is SYN_SENT:
 1331          *      if seg contains an ACK, but not for our SYN, drop the input.
 1332          *      if seg contains a RST, then drop the connection.
 1333          *      if seg does not contain SYN, then drop it.
 1334          * Otherwise this is an acceptable SYN segment
 1335          *      initialize tp->rcv_nxt and tp->irs
 1336          *      if seg contains ack then advance tp->snd_una
 1337          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
 1338          *      arrange for segment to be acked (eventually)
 1339          *      continue processing rest of data/controls, beginning with URG
 1340          */
 1341         case TCPS_SYN_SENT:
 1342                 if (tcp_do_rfc1644)
 1343                         tcp_hc_gettao(&inp->inp_inc, &tao);
 1344 
 1345                 if ((thflags & TH_ACK) &&
 1346                     (SEQ_LEQ(th->th_ack, tp->iss) ||
 1347                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1348                         /*
 1349                          * If we have a cached CCsent for the remote host,
 1350                          * hence we haven't just crashed and restarted,
 1351                          * do not send a RST.  This may be a retransmission
 1352                          * from the other side after our earlier ACK was lost.
 1353                          * Our new SYN, when it arrives, will serve as the
 1354                          * needed ACK.
 1355                          */
 1356                         if (tao.tao_ccsent != 0)
 1357                                 goto drop;
 1358                         else {
 1359                                 rstreason = BANDLIM_UNLIMITED;
 1360                                 goto dropwithreset;
 1361                         }
 1362                 }
 1363                 if (thflags & TH_RST) {
 1364                         if (thflags & TH_ACK)
 1365                                 tp = tcp_drop(tp, ECONNREFUSED);
 1366                         goto drop;
 1367                 }
 1368                 if ((thflags & TH_SYN) == 0)
 1369                         goto drop;
 1370                 tp->snd_wnd = th->th_win;       /* initial send window */
 1371                 tp->cc_recv = to.to_cc;         /* foreign CC */
 1372 
 1373                 tp->irs = th->th_seq;
 1374                 tcp_rcvseqinit(tp);
 1375                 if (thflags & TH_ACK) {
 1376                         /*
 1377                          * Our SYN was acked.  If segment contains CC.ECHO
 1378                          * option, check it to make sure this segment really
 1379                          * matches our SYN.  If not, just drop it as old
 1380                          * duplicate, but send an RST if we're still playing
 1381                          * by the old rules.  If no CC.ECHO option, make sure
 1382                          * we don't get fooled into using T/TCP.
 1383                          */
 1384                         if (to.to_flags & TOF_CCECHO) {
 1385                                 if (tp->cc_send != to.to_ccecho) {
 1386                                         if (tao.tao_ccsent != 0)
 1387                                                 goto drop;
 1388                                         else {
 1389                                                 rstreason = BANDLIM_UNLIMITED;
 1390                                                 goto dropwithreset;
 1391                                         }
 1392                                 }
 1393                         } else
 1394                                 tp->t_flags &= ~TF_RCVD_CC;
 1395                         tcpstat.tcps_connects++;
 1396                         soisconnected(so);
 1397 #ifdef MAC
 1398                         SOCK_LOCK(so);
 1399                         mac_set_socket_peer_from_mbuf(m, so);
 1400                         SOCK_UNLOCK(so);
 1401 #endif
 1402                         /* Do window scaling on this connection? */
 1403                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1404                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1405                                 tp->snd_scale = tp->requested_s_scale;
 1406                                 tp->rcv_scale = tp->request_r_scale;
 1407                         }
 1408                         /* Segment is acceptable, update cache if undefined. */
 1409                         if (tao.tao_ccsent == 0 && tcp_do_rfc1644)
 1410                                 tcp_hc_updatetao(&inp->inp_inc, TCP_HC_TAO_CCSENT, to.to_ccecho, 0);
 1411 
 1412                         tp->rcv_adv += tp->rcv_wnd;
 1413                         tp->snd_una++;          /* SYN is acked */
 1414                         /*
 1415                          * If there's data, delay ACK; if there's also a FIN
 1416                          * ACKNOW will be turned on later.
 1417                          */
 1418                         if (DELAY_ACK(tp) && tlen != 0)
 1419                                 callout_reset(tp->tt_delack, tcp_delacktime,
 1420                                     tcp_timer_delack, tp);
 1421                         else
 1422                                 tp->t_flags |= TF_ACKNOW;
 1423                         /*
 1424                          * Received <SYN,ACK> in SYN_SENT[*] state.
 1425                          * Transitions:
 1426                          *      SYN_SENT  --> ESTABLISHED
 1427                          *      SYN_SENT* --> FIN_WAIT_1
 1428                          */
 1429                         tp->t_starttime = ticks;
 1430                         if (tp->t_flags & TF_NEEDFIN) {
 1431                                 tp->t_state = TCPS_FIN_WAIT_1;
 1432                                 tp->t_flags &= ~TF_NEEDFIN;
 1433                                 thflags &= ~TH_SYN;
 1434                         } else {
 1435                                 tp->t_state = TCPS_ESTABLISHED;
 1436                                 callout_reset(tp->tt_keep, tcp_keepidle,
 1437                                               tcp_timer_keep, tp);
 1438                         }
 1439                 } else {
 1440                         /*
 1441                          * Received initial SYN in SYN-SENT[*] state =>
 1442                          * simultaneous open.  If segment contains CC option
 1443                          * and there is a cached CC, apply TAO test.
 1444                          * If it succeeds, connection is * half-synchronized.
 1445                          * Otherwise, do 3-way handshake:
 1446                          *        SYN-SENT -> SYN-RECEIVED
 1447                          *        SYN-SENT* -> SYN-RECEIVED*
 1448                          * If there was no CC option, clear cached CC value.
 1449                          */
 1450                         tp->t_flags |= TF_ACKNOW;
 1451                         callout_stop(tp->tt_rexmt);
 1452                         if (to.to_flags & TOF_CC) {
 1453                                 if (tao.tao_cc != 0 &&
 1454                                     CC_GT(to.to_cc, tao.tao_cc)) {
 1455                                         /*
 1456                                          * update cache and make transition:
 1457                                          *        SYN-SENT -> ESTABLISHED*
 1458                                          *        SYN-SENT* -> FIN-WAIT-1*
 1459                                          */
 1460                                         tao.tao_cc = to.to_cc;
 1461                                         tcp_hc_updatetao(&inp->inp_inc,
 1462                                                 TCP_HC_TAO_CC, to.to_cc, 0);
 1463                                         tp->t_starttime = ticks;
 1464                                         if (tp->t_flags & TF_NEEDFIN) {
 1465                                                 tp->t_state = TCPS_FIN_WAIT_1;
 1466                                                 tp->t_flags &= ~TF_NEEDFIN;
 1467                                         } else {
 1468                                                 tp->t_state = TCPS_ESTABLISHED;
 1469                                                 callout_reset(tp->tt_keep,
 1470                                                               tcp_keepidle,
 1471                                                               tcp_timer_keep,
 1472                                                               tp);
 1473                                         }
 1474                                         tp->t_flags |= TF_NEEDSYN;
 1475                                 } else
 1476                                         tp->t_state = TCPS_SYN_RECEIVED;
 1477                         } else {
 1478                                 if (tcp_do_rfc1644) {
 1479                                         /* CC.NEW or no option => invalidate cache */
 1480                                         tao.tao_cc = 0;
 1481                                         tcp_hc_updatetao(&inp->inp_inc,
 1482                                                 TCP_HC_TAO_CC, to.to_cc, 0);
 1483                                 }
 1484                                 tp->t_state = TCPS_SYN_RECEIVED;
 1485                         }
 1486                 }
 1487 
 1488 trimthenstep6:
 1489                 KASSERT(headlocked,
 1490                     ("tcp_input(): trimthenstep6 head is not locked"));
 1491                 INP_LOCK_ASSERT(inp);
 1492 
 1493                 /*
 1494                  * Advance th->th_seq to correspond to first data byte.
 1495                  * If data, trim to stay within window,
 1496                  * dropping FIN if necessary.
 1497                  */
 1498                 th->th_seq++;
 1499                 if (tlen > tp->rcv_wnd) {
 1500                         todrop = tlen - tp->rcv_wnd;
 1501                         m_adj(m, -todrop);
 1502                         tlen = tp->rcv_wnd;
 1503                         thflags &= ~TH_FIN;
 1504                         tcpstat.tcps_rcvpackafterwin++;
 1505                         tcpstat.tcps_rcvbyteafterwin += todrop;
 1506                 }
 1507                 tp->snd_wl1 = th->th_seq - 1;
 1508                 tp->rcv_up = th->th_seq;
 1509                 /*
 1510                  * Client side of transaction: already sent SYN and data.
 1511                  * If the remote host used T/TCP to validate the SYN,
 1512                  * our data will be ACK'd; if so, enter normal data segment
 1513                  * processing in the middle of step 5, ack processing.
 1514                  * Otherwise, goto step 6.
 1515                  */
 1516                 if (thflags & TH_ACK)
 1517                         goto process_ACK;
 1518 
 1519                 goto step6;
 1520 
 1521         /*
 1522          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
 1523          *      if segment contains a SYN and CC [not CC.NEW] option:
 1524          *              if state == TIME_WAIT and connection duration > MSL,
 1525          *                  drop packet and send RST;
 1526          *
 1527          *              if SEG.CC > CCrecv then is new SYN, and can implicitly
 1528          *                  ack the FIN (and data) in retransmission queue.
 1529          *                  Complete close and delete TCPCB.  Then reprocess
 1530          *                  segment, hoping to find new TCPCB in LISTEN state;
 1531          *
 1532          *              else must be old SYN; drop it.
 1533          *      else do normal processing.
 1534          */
 1535         case TCPS_LAST_ACK:
 1536         case TCPS_CLOSING:
 1537         case TCPS_TIME_WAIT:
 1538                 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 1539                 if ((thflags & TH_SYN) &&
 1540                     (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
 1541                         if (tp->t_state == TCPS_TIME_WAIT &&
 1542                                         (ticks - tp->t_starttime) > tcp_msl) {
 1543                                 rstreason = BANDLIM_UNLIMITED;
 1544                                 goto dropwithreset;
 1545                         }
 1546                         if (CC_GT(to.to_cc, tp->cc_recv)) {
 1547                                 tp = tcp_close(tp);
 1548                                 goto findpcb;
 1549                         }
 1550                         else
 1551                                 goto drop;
 1552                 }
 1553                 break;  /* continue normal processing */
 1554         }
 1555 
 1556         /*
 1557          * States other than LISTEN or SYN_SENT.
 1558          * First check the RST flag and sequence number since reset segments
 1559          * are exempt from the timestamp and connection count tests.  This
 1560          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
 1561          * below which allowed reset segments in half the sequence space
 1562          * to fall though and be processed (which gives forged reset
 1563          * segments with a random sequence number a 50 percent chance of
 1564          * killing a connection).
 1565          * Then check timestamp, if present.
 1566          * Then check the connection count, if present.
 1567          * Then check that at least some bytes of segment are within
 1568          * receive window.  If segment begins before rcv_nxt,
 1569          * drop leading data (and SYN); if nothing left, just ack.
 1570          *
 1571          *
 1572          * If the RST bit is set, check the sequence number to see
 1573          * if this is a valid reset segment.
 1574          * RFC 793 page 37:
 1575          *   In all states except SYN-SENT, all reset (RST) segments
 1576          *   are validated by checking their SEQ-fields.  A reset is
 1577          *   valid if its sequence number is in the window.
 1578          * Note: this does not take into account delayed ACKs, so
 1579          *   we should test against last_ack_sent instead of rcv_nxt.
 1580          *   The sequence number in the reset segment is normally an
 1581          *   echo of our outgoing acknowlegement numbers, but some hosts
 1582          *   send a reset with the sequence number at the rightmost edge
 1583          *   of our receive window, and we have to handle this case.
 1584          * Note 2: Paul Watson's paper "Slipping in the Window" has shown
 1585          *   that brute force RST attacks are possible.  To combat this,
 1586          *   we use a much stricter check while in the ESTABLISHED state,
 1587          *   only accepting RSTs where the sequence number is equal to
 1588          *   last_ack_sent.  In all other states (the states in which a
 1589          *   RST is more likely), the more permissive check is used.
 1590          * If we have multiple segments in flight, the intial reset
 1591          * segment sequence numbers will be to the left of last_ack_sent,
 1592          * but they will eventually catch up.
 1593          * In any case, it never made sense to trim reset segments to
 1594          * fit the receive window since RFC 1122 says:
 1595          *   4.2.2.12  RST Segment: RFC-793 Section 3.4
 1596          *
 1597          *    A TCP SHOULD allow a received RST segment to include data.
 1598          *
 1599          *    DISCUSSION
 1600          *         It has been suggested that a RST segment could contain
 1601          *         ASCII text that encoded and explained the cause of the
 1602          *         RST.  No standard has yet been established for such
 1603          *         data.
 1604          *
 1605          * If the reset segment passes the sequence number test examine
 1606          * the state:
 1607          *    SYN_RECEIVED STATE:
 1608          *      If passive open, return to LISTEN state.
 1609          *      If active open, inform user that connection was refused.
 1610          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
 1611          *      Inform user that connection was reset, and close tcb.
 1612          *    CLOSING, LAST_ACK STATES:
 1613          *      Close the tcb.
 1614          *    TIME_WAIT STATE:
 1615          *      Drop the segment - see Stevens, vol. 2, p. 964 and
 1616          *      RFC 1337.
 1617          */
 1618         if (thflags & TH_RST) {
 1619                 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
 1620                     SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
 1621                         switch (tp->t_state) {
 1622 
 1623                         case TCPS_SYN_RECEIVED:
 1624                                 so->so_error = ECONNREFUSED;
 1625                                 goto close;
 1626 
 1627                         case TCPS_ESTABLISHED:
 1628                                 if (tp->last_ack_sent != th->th_seq) {
 1629                                         tcpstat.tcps_badrst++;
 1630                                         goto drop;
 1631                                 }
 1632                         case TCPS_FIN_WAIT_1:
 1633                         case TCPS_FIN_WAIT_2:
 1634                         case TCPS_CLOSE_WAIT:
 1635                                 so->so_error = ECONNRESET;
 1636                         close:
 1637                                 tp->t_state = TCPS_CLOSED;
 1638                                 tcpstat.tcps_drops++;
 1639                                 tp = tcp_close(tp);
 1640                                 break;
 1641 
 1642                         case TCPS_CLOSING:
 1643                         case TCPS_LAST_ACK:
 1644                                 tp = tcp_close(tp);
 1645                                 break;
 1646 
 1647                         case TCPS_TIME_WAIT:
 1648                                 KASSERT(tp->t_state != TCPS_TIME_WAIT,
 1649                                     ("timewait"));
 1650                                 break;
 1651                         }
 1652                 }
 1653                 goto drop;
 1654         }
 1655 
 1656         /*
 1657          * RFC 1323 PAWS: If we have a timestamp reply on this segment
 1658          * and it's less than ts_recent, drop it.
 1659          */
 1660         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
 1661             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
 1662 
 1663                 /* Check to see if ts_recent is over 24 days old.  */
 1664                 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
 1665                         /*
 1666                          * Invalidate ts_recent.  If this segment updates
 1667                          * ts_recent, the age will be reset later and ts_recent
 1668                          * will get a valid value.  If it does not, setting
 1669                          * ts_recent to zero will at least satisfy the
 1670                          * requirement that zero be placed in the timestamp
 1671                          * echo reply when ts_recent isn't valid.  The
 1672                          * age isn't reset until we get a valid ts_recent
 1673                          * because we don't want out-of-order segments to be
 1674                          * dropped when ts_recent is old.
 1675                          */
 1676                         tp->ts_recent = 0;
 1677                 } else {
 1678                         tcpstat.tcps_rcvduppack++;
 1679                         tcpstat.tcps_rcvdupbyte += tlen;
 1680                         tcpstat.tcps_pawsdrop++;
 1681                         if (tlen)
 1682                                 goto dropafterack;
 1683                         goto drop;
 1684                 }
 1685         }
 1686 
 1687         /*
 1688          * T/TCP mechanism
 1689          *   If T/TCP was negotiated and the segment doesn't have CC,
 1690          *   or if its CC is wrong then drop the segment.
 1691          *   RST segments do not have to comply with this.
 1692          */
 1693         if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
 1694             ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
 1695                 goto dropafterack;
 1696 
 1697         /*
 1698          * In the SYN-RECEIVED state, validate that the packet belongs to
 1699          * this connection before trimming the data to fit the receive
 1700          * window.  Check the sequence number versus IRS since we know
 1701          * the sequence numbers haven't wrapped.  This is a partial fix
 1702          * for the "LAND" DoS attack.
 1703          */
 1704         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
 1705                 rstreason = BANDLIM_RST_OPENPORT;
 1706                 goto dropwithreset;
 1707         }
 1708 
 1709         todrop = tp->rcv_nxt - th->th_seq;
 1710         if (todrop > 0) {
 1711                 if (thflags & TH_SYN) {
 1712                         thflags &= ~TH_SYN;
 1713                         th->th_seq++;
 1714                         if (th->th_urp > 1)
 1715                                 th->th_urp--;
 1716                         else
 1717                                 thflags &= ~TH_URG;
 1718                         todrop--;
 1719                 }
 1720                 /*
 1721                  * Following if statement from Stevens, vol. 2, p. 960.
 1722                  */
 1723                 if (todrop > tlen
 1724                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
 1725                         /*
 1726                          * Any valid FIN must be to the left of the window.
 1727                          * At this point the FIN must be a duplicate or out
 1728                          * of sequence; drop it.
 1729                          */
 1730                         thflags &= ~TH_FIN;
 1731 
 1732                         /*
 1733                          * Send an ACK to resynchronize and drop any data.
 1734                          * But keep on processing for RST or ACK.
 1735                          */
 1736                         tp->t_flags |= TF_ACKNOW;
 1737                         todrop = tlen;
 1738                         tcpstat.tcps_rcvduppack++;
 1739                         tcpstat.tcps_rcvdupbyte += todrop;
 1740                 } else {
 1741                         tcpstat.tcps_rcvpartduppack++;
 1742                         tcpstat.tcps_rcvpartdupbyte += todrop;
 1743                 }
 1744                 drop_hdrlen += todrop;  /* drop from the top afterwards */
 1745                 th->th_seq += todrop;
 1746                 tlen -= todrop;
 1747                 if (th->th_urp > todrop)
 1748                         th->th_urp -= todrop;
 1749                 else {
 1750                         thflags &= ~TH_URG;
 1751                         th->th_urp = 0;
 1752                 }
 1753         }
 1754 
 1755         /*
 1756          * If new data are received on a connection after the
 1757          * user processes are gone, then RST the other end.
 1758          */
 1759         if ((so->so_state & SS_NOFDREF) &&
 1760             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
 1761                 tp = tcp_close(tp);
 1762                 tcpstat.tcps_rcvafterclose++;
 1763                 rstreason = BANDLIM_UNLIMITED;
 1764                 goto dropwithreset;
 1765         }
 1766 
 1767         /*
 1768          * If segment ends after window, drop trailing data
 1769          * (and PUSH and FIN); if nothing left, just ACK.
 1770          */
 1771         todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
 1772         if (todrop > 0) {
 1773                 tcpstat.tcps_rcvpackafterwin++;
 1774                 if (todrop >= tlen) {
 1775                         tcpstat.tcps_rcvbyteafterwin += tlen;
 1776                         /*
 1777                          * If a new connection request is received
 1778                          * while in TIME_WAIT, drop the old connection
 1779                          * and start over if the sequence numbers
 1780                          * are above the previous ones.
 1781                          */
 1782                         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 1783                         if (thflags & TH_SYN &&
 1784                             tp->t_state == TCPS_TIME_WAIT &&
 1785                             SEQ_GT(th->th_seq, tp->rcv_nxt)) {
 1786                                 tp = tcp_close(tp);
 1787                                 goto findpcb;
 1788                         }
 1789                         /*
 1790                          * If window is closed can only take segments at
 1791                          * window edge, and have to drop data and PUSH from
 1792                          * incoming segments.  Continue processing, but
 1793                          * remember to ack.  Otherwise, drop segment
 1794                          * and ack.
 1795                          */
 1796                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
 1797                                 tp->t_flags |= TF_ACKNOW;
 1798                                 tcpstat.tcps_rcvwinprobe++;
 1799                         } else
 1800                                 goto dropafterack;
 1801                 } else
 1802                         tcpstat.tcps_rcvbyteafterwin += todrop;
 1803                 m_adj(m, -todrop);
 1804                 tlen -= todrop;
 1805                 thflags &= ~(TH_PUSH|TH_FIN);
 1806         }
 1807 
 1808         /*
 1809          * If last ACK falls within this segment's sequence numbers,
 1810          * record its timestamp.
 1811          * NOTE: 
 1812          * 1) That the test incorporates suggestions from the latest
 1813          *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
 1814          * 2) That updating only on newer timestamps interferes with
 1815          *    our earlier PAWS tests, so this check should be solely
 1816          *    predicated on the sequence space of this segment.
 1817          * 3) That we modify the segment boundary check to be 
 1818          *        Last.ACK.Sent <= SEG.SEQ + SEG.Len  
 1819          *    instead of RFC1323's
 1820          *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
 1821          *    This modified check allows us to overcome RFC1323's
 1822          *    limitations as described in Stevens TCP/IP Illustrated
 1823          *    Vol. 2 p.869. In such cases, we can still calculate the
 1824          *    RTT correctly when RCV.NXT == Last.ACK.Sent.
 1825          */
 1826         if ((to.to_flags & TOF_TS) != 0 &&
 1827             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
 1828             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
 1829                 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
 1830                 tp->ts_recent_age = ticks;
 1831                 tp->ts_recent = to.to_tsval;
 1832         }
 1833 
 1834         /*
 1835          * If a SYN is in the window, then this is an
 1836          * error and we send an RST and drop the connection.
 1837          */
 1838         if (thflags & TH_SYN) {
 1839                 tp = tcp_drop(tp, ECONNRESET);
 1840                 rstreason = BANDLIM_UNLIMITED;
 1841                 goto drop;
 1842         }
 1843 
 1844         /*
 1845          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
 1846          * flag is on (half-synchronized state), then queue data for
 1847          * later processing; else drop segment and return.
 1848          */
 1849         if ((thflags & TH_ACK) == 0) {
 1850                 if (tp->t_state == TCPS_SYN_RECEIVED ||
 1851                     (tp->t_flags & TF_NEEDSYN))
 1852                         goto step6;
 1853                 else
 1854                         goto drop;
 1855         }
 1856 
 1857         /*
 1858          * Ack processing.
 1859          */
 1860         switch (tp->t_state) {
 1861 
 1862         /*
 1863          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
 1864          * ESTABLISHED state and continue processing.
 1865          * The ACK was checked above.
 1866          */
 1867         case TCPS_SYN_RECEIVED:
 1868 
 1869                 tcpstat.tcps_connects++;
 1870                 soisconnected(so);
 1871                 /* Do window scaling? */
 1872                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1873                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1874                         tp->snd_scale = tp->requested_s_scale;
 1875                         tp->rcv_scale = tp->request_r_scale;
 1876                 }
 1877                 /*
 1878                  * Upon successful completion of 3-way handshake,
 1879                  * update cache.CC, pass any queued data to the user,
 1880                  * and advance state appropriately.
 1881                  */
 1882                 if (tcp_do_rfc1644) {
 1883                         tao.tao_cc = tp->cc_recv;
 1884                         tcp_hc_updatetao(&inp->inp_inc, TCP_HC_TAO_CC,
 1885                                          tp->cc_recv, 0);
 1886                 }
 1887                 /*
 1888                  * Make transitions:
 1889                  *      SYN-RECEIVED  -> ESTABLISHED
 1890                  *      SYN-RECEIVED* -> FIN-WAIT-1
 1891                  */
 1892                 tp->t_starttime = ticks;
 1893                 if (tp->t_flags & TF_NEEDFIN) {
 1894                         tp->t_state = TCPS_FIN_WAIT_1;
 1895                         tp->t_flags &= ~TF_NEEDFIN;
 1896                 } else {
 1897                         tp->t_state = TCPS_ESTABLISHED;
 1898                         callout_reset(tp->tt_keep, tcp_keepidle,
 1899                                       tcp_timer_keep, tp);
 1900                 }
 1901                 /*
 1902                  * If segment contains data or ACK, will call tcp_reass()
 1903                  * later; if not, do so now to pass queued data to user.
 1904                  */
 1905                 if (tlen == 0 && (thflags & TH_FIN) == 0)
 1906                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
 1907                             (struct mbuf *)0);
 1908                 tp->snd_wl1 = th->th_seq - 1;
 1909                 /* FALLTHROUGH */
 1910 
 1911         /*
 1912          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
 1913          * ACKs.  If the ack is in the range
 1914          *      tp->snd_una < th->th_ack <= tp->snd_max
 1915          * then advance tp->snd_una to th->th_ack and drop
 1916          * data from the retransmission queue.  If this ACK reflects
 1917          * more up to date window information we update our window information.
 1918          */
 1919         case TCPS_ESTABLISHED:
 1920         case TCPS_FIN_WAIT_1:
 1921         case TCPS_FIN_WAIT_2:
 1922         case TCPS_CLOSE_WAIT:
 1923         case TCPS_CLOSING:
 1924         case TCPS_LAST_ACK:
 1925         case TCPS_TIME_WAIT:
 1926                 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 1927                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
 1928                         if (tlen == 0 && tiwin == tp->snd_wnd) {
 1929                                 tcpstat.tcps_rcvdupack++;
 1930                                 /*
 1931                                  * If we have outstanding data (other than
 1932                                  * a window probe), this is a completely
 1933                                  * duplicate ack (ie, window info didn't
 1934                                  * change), the ack is the biggest we've
 1935                                  * seen and we've seen exactly our rexmt
 1936                                  * threshhold of them, assume a packet
 1937                                  * has been dropped and retransmit it.
 1938                                  * Kludge snd_nxt & the congestion
 1939                                  * window so we send only this one
 1940                                  * packet.
 1941                                  *
 1942                                  * We know we're losing at the current
 1943                                  * window size so do congestion avoidance
 1944                                  * (set ssthresh to half the current window
 1945                                  * and pull our congestion window back to
 1946                                  * the new ssthresh).
 1947                                  *
 1948                                  * Dup acks mean that packets have left the
 1949                                  * network (they're now cached at the receiver)
 1950                                  * so bump cwnd by the amount in the receiver
 1951                                  * to keep a constant cwnd packets in the
 1952                                  * network.
 1953                                  */
 1954                                 if (!callout_active(tp->tt_rexmt) ||
 1955                                     th->th_ack != tp->snd_una)
 1956                                         tp->t_dupacks = 0;
 1957                                 else if (++tp->t_dupacks > tcprexmtthresh ||
 1958                                          ((tcp_do_newreno || tp->sack_enable) &&
 1959                                           IN_FASTRECOVERY(tp))) {
 1960                                         tp->snd_cwnd += tp->t_maxseg;
 1961                                         (void) tcp_output(tp);
 1962                                         goto drop;
 1963                                 } else if (tp->t_dupacks == tcprexmtthresh) {
 1964                                         tcp_seq onxt = tp->snd_nxt;
 1965                                         u_int win;
 1966 
 1967                                         /*
 1968                                          * If we're doing sack, check to
 1969                                          * see if we're already in sack
 1970                                          * recovery. If we're not doing sack,
 1971                                          * check to see if we're in newreno
 1972                                          * recovery.
 1973                                          */
 1974                                         if (tp->sack_enable) {
 1975                                                 if (IN_FASTRECOVERY(tp)) {
 1976                                                         tp->t_dupacks = 0;
 1977                                                         break;
 1978                                                 }
 1979                                         } else if (tcp_do_newreno) {
 1980                                                 if (SEQ_LEQ(th->th_ack,
 1981                                                     tp->snd_recover)) {
 1982                                                         tp->t_dupacks = 0;
 1983                                                         break;
 1984                                                 }
 1985                                         }
 1986                                         win = min(tp->snd_wnd, tp->snd_cwnd) /
 1987                                             2 / tp->t_maxseg;
 1988                                         if (win < 2)
 1989                                                 win = 2;
 1990                                         tp->snd_ssthresh = win * tp->t_maxseg;
 1991                                         ENTER_FASTRECOVERY(tp);
 1992                                         tp->snd_recover = tp->snd_max;
 1993                                         callout_stop(tp->tt_rexmt);
 1994                                         tp->t_rtttime = 0;
 1995                                         if (tp->sack_enable) {
 1996                                                 tcpstat.tcps_sack_recovery_episode++;
 1997                                                 tp->snd_cwnd =
 1998                                                     tp->t_maxseg *
 1999                                                     tp->t_dupacks;
 2000                                                 (void) tcp_output(tp);
 2001                                                 tp->snd_cwnd +=
 2002                                                     tp->snd_ssthresh;
 2003                                                 goto drop;
 2004                                         }
 2005 
 2006                                         tp->snd_nxt = th->th_ack;
 2007                                         tp->snd_cwnd = tp->t_maxseg;
 2008                                         (void) tcp_output(tp);
 2009                                         KASSERT(tp->snd_limited <= 2,
 2010                                             ("tp->snd_limited too big"));
 2011                                         tp->snd_cwnd = tp->snd_ssthresh +
 2012                                              tp->t_maxseg *
 2013                                              (tp->t_dupacks - tp->snd_limited);
 2014                                         if (SEQ_GT(onxt, tp->snd_nxt))
 2015                                                 tp->snd_nxt = onxt;
 2016                                         goto drop;
 2017                                 } else if (tcp_do_rfc3042) {
 2018                                         u_long oldcwnd = tp->snd_cwnd;
 2019                                         tcp_seq oldsndmax = tp->snd_max;
 2020                                         u_int sent;
 2021 
 2022                                         KASSERT(tp->t_dupacks == 1 ||
 2023                                             tp->t_dupacks == 2,
 2024                                             ("dupacks not 1 or 2"));
 2025                                         if (tp->t_dupacks == 1)
 2026                                                 tp->snd_limited = 0;
 2027                                         tp->snd_cwnd =
 2028                                             (tp->snd_nxt - tp->snd_una) +
 2029                                             (tp->t_dupacks - tp->snd_limited) *
 2030                                             tp->t_maxseg;
 2031                                         (void) tcp_output(tp);
 2032                                         sent = tp->snd_max - oldsndmax;
 2033                                         if (sent > tp->t_maxseg) {
 2034                                                 KASSERT((tp->t_dupacks == 2 &&
 2035                                                     tp->snd_limited == 0) ||
 2036                                                    (sent == tp->t_maxseg + 1 &&
 2037                                                     tp->t_flags & TF_SENTFIN),
 2038                                                     ("sent too much"));
 2039                                                 tp->snd_limited = 2;
 2040                                         } else if (sent > 0)
 2041                                                 ++tp->snd_limited;
 2042                                         tp->snd_cwnd = oldcwnd;
 2043                                         goto drop;
 2044                                 }
 2045                         } else
 2046                                 tp->t_dupacks = 0;
 2047                         break;
 2048                 }
 2049 
 2050                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
 2051 
 2052                 /*
 2053                  * If the congestion window was inflated to account
 2054                  * for the other side's cached packets, retract it.
 2055                  */
 2056                 if (tcp_do_newreno || tp->sack_enable) {
 2057                         if (IN_FASTRECOVERY(tp)) {
 2058                                 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
 2059                                         if (tp->sack_enable)
 2060                                                 tcp_sack_partialack(tp, th);
 2061                                         else
 2062                                                 tcp_newreno_partial_ack(tp, th);
 2063                                 } else {
 2064                                         /*
 2065                                          * Out of fast recovery.
 2066                                          * Window inflation should have left us
 2067                                          * with approximately snd_ssthresh
 2068                                          * outstanding data.
 2069                                          * But in case we would be inclined to
 2070                                          * send a burst, better to do it via
 2071                                          * the slow start mechanism.
 2072                                          */
 2073                                         if (SEQ_GT(th->th_ack +
 2074                                                         tp->snd_ssthresh,
 2075                                                    tp->snd_max))
 2076                                                 tp->snd_cwnd = tp->snd_max -
 2077                                                                 th->th_ack +
 2078                                                                 tp->t_maxseg;
 2079                                         else
 2080                                                 tp->snd_cwnd = tp->snd_ssthresh;
 2081                                 }
 2082                         }
 2083                 } else {
 2084                         if (tp->t_dupacks >= tcprexmtthresh &&
 2085                             tp->snd_cwnd > tp->snd_ssthresh)
 2086                                 tp->snd_cwnd = tp->snd_ssthresh;
 2087                 }
 2088                 tp->t_dupacks = 0;
 2089                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
 2090                         tcpstat.tcps_rcvacktoomuch++;
 2091                         goto dropafterack;
 2092                 }
 2093                 /*
 2094                  * If we reach this point, ACK is not a duplicate,
 2095                  *     i.e., it ACKs something we sent.
 2096                  */
 2097                 if (tp->t_flags & TF_NEEDSYN) {
 2098                         /*
 2099                          * T/TCP: Connection was half-synchronized, and our
 2100                          * SYN has been ACK'd (so connection is now fully
 2101                          * synchronized).  Go to non-starred state,
 2102                          * increment snd_una for ACK of SYN, and check if
 2103                          * we can do window scaling.
 2104                          */
 2105                         tp->t_flags &= ~TF_NEEDSYN;
 2106                         tp->snd_una++;
 2107                         /* Do window scaling? */
 2108                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 2109                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 2110                                 tp->snd_scale = tp->requested_s_scale;
 2111                                 tp->rcv_scale = tp->request_r_scale;
 2112                         }
 2113                 }
 2114 
 2115 process_ACK:
 2116                 KASSERT(headlocked,
 2117                     ("tcp_input(): process_ACK head is not locked"));
 2118                 INP_LOCK_ASSERT(inp);
 2119 
 2120                 acked = th->th_ack - tp->snd_una;
 2121                 tcpstat.tcps_rcvackpack++;
 2122                 tcpstat.tcps_rcvackbyte += acked;
 2123 
 2124                 /*
 2125                  * If we just performed our first retransmit, and the ACK
 2126                  * arrives within our recovery window, then it was a mistake
 2127                  * to do the retransmit in the first place.  Recover our
 2128                  * original cwnd and ssthresh, and proceed to transmit where
 2129                  * we left off.
 2130                  */
 2131                 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
 2132                         ++tcpstat.tcps_sndrexmitbad;
 2133                         tp->snd_cwnd = tp->snd_cwnd_prev;
 2134                         tp->snd_ssthresh = tp->snd_ssthresh_prev;
 2135                         tp->snd_recover = tp->snd_recover_prev;
 2136                         if (tp->t_flags & TF_WASFRECOVERY)
 2137                                 ENTER_FASTRECOVERY(tp);
 2138                         tp->snd_nxt = tp->snd_max;
 2139                         tp->t_badrxtwin = 0;    /* XXX probably not required */
 2140                 }
 2141 
 2142                 /*
 2143                  * If we have a timestamp reply, update smoothed
 2144                  * round trip time.  If no timestamp is present but
 2145                  * transmit timer is running and timed sequence
 2146                  * number was acked, update smoothed round trip time.
 2147                  * Since we now have an rtt measurement, cancel the
 2148                  * timer backoff (cf., Phil Karn's retransmit alg.).
 2149                  * Recompute the initial retransmit timer.
 2150                  *
 2151                  * Some boxes send broken timestamp replies
 2152                  * during the SYN+ACK phase, ignore
 2153                  * timestamps of 0 or we could calculate a
 2154                  * huge RTT and blow up the retransmit timer.
 2155                  */
 2156                 if ((to.to_flags & TOF_TS) != 0 &&
 2157                     to.to_tsecr) {
 2158                         tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
 2159                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
 2160                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
 2161                 }
 2162                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
 2163 
 2164                 /*
 2165                  * If all outstanding data is acked, stop retransmit
 2166                  * timer and remember to restart (more output or persist).
 2167                  * If there is more data to be acked, restart retransmit
 2168                  * timer, using current (possibly backed-off) value.
 2169                  */
 2170                 if (th->th_ack == tp->snd_max) {
 2171                         callout_stop(tp->tt_rexmt);
 2172                         needoutput = 1;
 2173                 } else if (!callout_active(tp->tt_persist))
 2174                         callout_reset(tp->tt_rexmt, tp->t_rxtcur,
 2175                                       tcp_timer_rexmt, tp);
 2176 
 2177                 /*
 2178                  * If no data (only SYN) was ACK'd,
 2179                  *    skip rest of ACK processing.
 2180                  */
 2181                 if (acked == 0)
 2182                         goto step6;
 2183 
 2184                 /*
 2185                  * When new data is acked, open the congestion window.
 2186                  * If the window gives us less than ssthresh packets
 2187                  * in flight, open exponentially (maxseg per packet).
 2188                  * Otherwise open linearly: maxseg per window
 2189                  * (maxseg^2 / cwnd per packet).
 2190                  */
 2191                 if ((!tcp_do_newreno && !tp->sack_enable) ||
 2192                     !IN_FASTRECOVERY(tp)) {
 2193                         register u_int cw = tp->snd_cwnd;
 2194                         register u_int incr = tp->t_maxseg;
 2195                         if (cw > tp->snd_ssthresh)
 2196                                 incr = incr * incr / cw;
 2197                         tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
 2198                 }
 2199                 SOCKBUF_LOCK(&so->so_snd);
 2200                 if (acked > so->so_snd.sb_cc) {
 2201                         tp->snd_wnd -= so->so_snd.sb_cc;
 2202                         sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
 2203                         ourfinisacked = 1;
 2204                 } else {
 2205                         sbdrop_locked(&so->so_snd, acked);
 2206                         tp->snd_wnd -= acked;
 2207                         ourfinisacked = 0;
 2208                 }
 2209                 sowwakeup_locked(so);
 2210                 /* detect una wraparound */
 2211                 if ((tcp_do_newreno || tp->sack_enable) &&
 2212                     !IN_FASTRECOVERY(tp) &&
 2213                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
 2214                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 2215                         tp->snd_recover = th->th_ack - 1;
 2216                 if ((tcp_do_newreno || tp->sack_enable) &&
 2217                     IN_FASTRECOVERY(tp) &&
 2218                     SEQ_GEQ(th->th_ack, tp->snd_recover))
 2219                         EXIT_FASTRECOVERY(tp);
 2220                 tp->snd_una = th->th_ack;
 2221                 if (tp->sack_enable) {
 2222                         if (SEQ_GT(tp->snd_una, tp->snd_recover))
 2223                                 tp->snd_recover = tp->snd_una;
 2224                 }
 2225                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
 2226                         tp->snd_nxt = tp->snd_una;
 2227 
 2228                 switch (tp->t_state) {
 2229 
 2230                 /*
 2231                  * In FIN_WAIT_1 STATE in addition to the processing
 2232                  * for the ESTABLISHED state if our FIN is now acknowledged
 2233                  * then enter FIN_WAIT_2.
 2234                  */
 2235                 case TCPS_FIN_WAIT_1:
 2236                         if (ourfinisacked) {
 2237                                 /*
 2238                                  * If we can't receive any more
 2239                                  * data, then closing user can proceed.
 2240                                  * Starting the timer is contrary to the
 2241                                  * specification, but if we don't get a FIN
 2242                                  * we'll hang forever.
 2243                                  */
 2244                 /* XXXjl
 2245                  * we should release the tp also, and use a
 2246                  * compressed state.
 2247                  */
 2248                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 2249                                         soisdisconnected(so);
 2250                                         callout_reset(tp->tt_2msl, tcp_maxidle,
 2251                                                       tcp_timer_2msl, tp);
 2252                                 }
 2253                                 tp->t_state = TCPS_FIN_WAIT_2;
 2254                         }
 2255                         break;
 2256 
 2257                 /*
 2258                  * In CLOSING STATE in addition to the processing for
 2259                  * the ESTABLISHED state if the ACK acknowledges our FIN
 2260                  * then enter the TIME-WAIT state, otherwise ignore
 2261                  * the segment.
 2262                  */
 2263                 case TCPS_CLOSING:
 2264                         if (ourfinisacked) {
 2265                                 KASSERT(headlocked, ("headlocked"));
 2266                                 tcp_twstart(tp);
 2267                                 INP_INFO_WUNLOCK(&tcbinfo);
 2268                                 m_freem(m);
 2269                                 return;
 2270                         }
 2271                         break;
 2272 
 2273                 /*
 2274                  * In LAST_ACK, we may still be waiting for data to drain
 2275                  * and/or to be acked, as well as for the ack of our FIN.
 2276                  * If our FIN is now acknowledged, delete the TCB,
 2277                  * enter the closed state and return.
 2278                  */
 2279                 case TCPS_LAST_ACK:
 2280                         if (ourfinisacked) {
 2281                                 tp = tcp_close(tp);
 2282                                 goto drop;
 2283                         }
 2284                         break;
 2285 
 2286                 /*
 2287                  * In TIME_WAIT state the only thing that should arrive
 2288                  * is a retransmission of the remote FIN.  Acknowledge
 2289                  * it and restart the finack timer.
 2290                  */
 2291                 case TCPS_TIME_WAIT:
 2292                         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 2293                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
 2294                                       tcp_timer_2msl, tp);
 2295                         goto dropafterack;
 2296                 }
 2297         }
 2298 
 2299 step6:
 2300         KASSERT(headlocked, ("tcp_input(): step6 head is not locked"));
 2301         INP_LOCK_ASSERT(inp);
 2302 
 2303         /*
 2304          * Update window information.
 2305          * Don't look at window if no ACK: TAC's send garbage on first SYN.
 2306          */
 2307         if ((thflags & TH_ACK) &&
 2308             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
 2309             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
 2310              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
 2311                 /* keep track of pure window updates */
 2312                 if (tlen == 0 &&
 2313                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
 2314                         tcpstat.tcps_rcvwinupd++;
 2315                 tp->snd_wnd = tiwin;
 2316                 tp->snd_wl1 = th->th_seq;
 2317                 tp->snd_wl2 = th->th_ack;
 2318                 if (tp->snd_wnd > tp->max_sndwnd)
 2319                         tp->max_sndwnd = tp->snd_wnd;
 2320                 needoutput = 1;
 2321         }
 2322 
 2323         /*
 2324          * Process segments with URG.
 2325          */
 2326         if ((thflags & TH_URG) && th->th_urp &&
 2327             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2328                 /*
 2329                  * This is a kludge, but if we receive and accept
 2330                  * random urgent pointers, we'll crash in
 2331                  * soreceive.  It's hard to imagine someone
 2332                  * actually wanting to send this much urgent data.
 2333                  */
 2334                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
 2335                         th->th_urp = 0;                 /* XXX */
 2336                         thflags &= ~TH_URG;             /* XXX */
 2337                         goto dodata;                    /* XXX */
 2338                 }
 2339                 /*
 2340                  * If this segment advances the known urgent pointer,
 2341                  * then mark the data stream.  This should not happen
 2342                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
 2343                  * a FIN has been received from the remote side.
 2344                  * In these states we ignore the URG.
 2345                  *
 2346                  * According to RFC961 (Assigned Protocols),
 2347                  * the urgent pointer points to the last octet
 2348                  * of urgent data.  We continue, however,
 2349                  * to consider it to indicate the first octet
 2350                  * of data past the urgent section as the original
 2351                  * spec states (in one of two places).
 2352                  */
 2353                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
 2354                         tp->rcv_up = th->th_seq + th->th_urp;
 2355                         SOCKBUF_LOCK(&so->so_rcv);
 2356                         so->so_oobmark = so->so_rcv.sb_cc +
 2357                             (tp->rcv_up - tp->rcv_nxt) - 1;
 2358                         if (so->so_oobmark == 0)
 2359                                 so->so_rcv.sb_state |= SBS_RCVATMARK;
 2360                         SOCKBUF_UNLOCK(&so->so_rcv);
 2361                         sohasoutofband(so);
 2362                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
 2363                 }
 2364                 /*
 2365                  * Remove out of band data so doesn't get presented to user.
 2366                  * This can happen independent of advancing the URG pointer,
 2367                  * but if two URG's are pending at once, some out-of-band
 2368                  * data may creep in... ick.
 2369                  */
 2370                 if (th->th_urp <= (u_long)tlen &&
 2371                     !(so->so_options & SO_OOBINLINE)) {
 2372                         /* hdr drop is delayed */
 2373                         tcp_pulloutofband(so, th, m, drop_hdrlen);
 2374                 }
 2375         } else {
 2376                 /*
 2377                  * If no out of band data is expected,
 2378                  * pull receive urgent pointer along
 2379                  * with the receive window.
 2380                  */
 2381                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
 2382                         tp->rcv_up = tp->rcv_nxt;
 2383         }
 2384 dodata:                                                 /* XXX */
 2385         KASSERT(headlocked, ("tcp_input(): dodata head is not locked"));
 2386         INP_LOCK_ASSERT(inp);
 2387 
 2388         /*
 2389          * Process the segment text, merging it into the TCP sequencing queue,
 2390          * and arranging for acknowledgment of receipt if necessary.
 2391          * This process logically involves adjusting tp->rcv_wnd as data
 2392          * is presented to the user (this happens in tcp_usrreq.c,
 2393          * case PRU_RCVD).  If a FIN has already been received on this
 2394          * connection then we just ignore the text.
 2395          */
 2396         if ((tlen || (thflags & TH_FIN)) &&
 2397             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2398                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 2399                 /*
 2400                  * Insert segment which includes th into TCP reassembly queue
 2401                  * with control block tp.  Set thflags to whether reassembly now
 2402                  * includes a segment with FIN.  This handles the common case
 2403                  * inline (segment is the next to be received on an established
 2404                  * connection, and the queue is empty), avoiding linkage into
 2405                  * and removal from the queue and repetition of various
 2406                  * conversions.
 2407                  * Set DELACK for segments received in order, but ack
 2408                  * immediately when segments are out of order (so
 2409                  * fast retransmit can work).
 2410                  */
 2411                 if (th->th_seq == tp->rcv_nxt &&
 2412                     LIST_EMPTY(&tp->t_segq) &&
 2413                     TCPS_HAVEESTABLISHED(tp->t_state)) {
 2414                         if (DELAY_ACK(tp))
 2415                                 tp->t_flags |= TF_DELACK;
 2416                         else
 2417                                 tp->t_flags |= TF_ACKNOW;
 2418                         tp->rcv_nxt += tlen;
 2419                         thflags = th->th_flags & TH_FIN;
 2420                         tcpstat.tcps_rcvpack++;
 2421                         tcpstat.tcps_rcvbyte += tlen;
 2422                         ND6_HINT(tp);
 2423                         /* Unlocked read. */
 2424                         SOCKBUF_LOCK(&so->so_rcv);
 2425                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
 2426                                 m_freem(m);
 2427                         else
 2428                                 sbappendstream_locked(&so->so_rcv, m);
 2429                         sorwakeup_locked(so);
 2430                 } else {
 2431                         thflags = tcp_reass(tp, th, &tlen, m);
 2432                         tp->t_flags |= TF_ACKNOW;
 2433                 }
 2434                         if (tp->sack_enable)
 2435                                 tcp_update_sack_list(tp);
 2436                 /*
 2437                  * Note the amount of data that peer has sent into
 2438                  * our window, in order to estimate the sender's
 2439                  * buffer size.
 2440                  */
 2441                 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
 2442         } else {
 2443                 m_freem(m);
 2444                 thflags &= ~TH_FIN;
 2445         }
 2446 
 2447         /*
 2448          * If FIN is received ACK the FIN and let the user know
 2449          * that the connection is closing.
 2450          */
 2451         if (thflags & TH_FIN) {
 2452                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2453                         socantrcvmore(so);
 2454                         /*
 2455                          * If connection is half-synchronized
 2456                          * (ie NEEDSYN flag on) then delay ACK,
 2457                          * so it may be piggybacked when SYN is sent.
 2458                          * Otherwise, since we received a FIN then no
 2459                          * more input can be expected, send ACK now.
 2460                          */
 2461                         if (tp->t_flags & TF_NEEDSYN)
 2462                                 tp->t_flags |= TF_DELACK;
 2463                         else
 2464                                 tp->t_flags |= TF_ACKNOW;
 2465                         tp->rcv_nxt++;
 2466                 }
 2467                 switch (tp->t_state) {
 2468 
 2469                 /*
 2470                  * In SYN_RECEIVED and ESTABLISHED STATES
 2471                  * enter the CLOSE_WAIT state.
 2472                  */
 2473                 case TCPS_SYN_RECEIVED:
 2474                         tp->t_starttime = ticks;
 2475                         /*FALLTHROUGH*/
 2476                 case TCPS_ESTABLISHED:
 2477                         tp->t_state = TCPS_CLOSE_WAIT;
 2478                         break;
 2479 
 2480                 /*
 2481                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
 2482                  * enter the CLOSING state.
 2483                  */
 2484                 case TCPS_FIN_WAIT_1:
 2485                         tp->t_state = TCPS_CLOSING;
 2486                         break;
 2487 
 2488                 /*
 2489                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
 2490                  * starting the time-wait timer, turning off the other
 2491                  * standard timers.
 2492                  */
 2493                 case TCPS_FIN_WAIT_2:
 2494                         KASSERT(headlocked == 1, ("headlocked should be 1"));
 2495                         tcp_twstart(tp);
 2496                         INP_INFO_WUNLOCK(&tcbinfo);
 2497                         return;
 2498 
 2499                 /*
 2500                  * In TIME_WAIT state restart the 2 MSL time_wait timer.
 2501                  */
 2502                 case TCPS_TIME_WAIT:
 2503                         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
 2504                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
 2505                                       tcp_timer_2msl, tp);
 2506                         break;
 2507                 }
 2508         }
 2509         INP_INFO_WUNLOCK(&tcbinfo);
 2510 #ifdef TCPDEBUG
 2511         if (so->so_options & SO_DEBUG)
 2512                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
 2513                           &tcp_savetcp, 0);
 2514 #endif
 2515 
 2516         /*
 2517          * Return any desired output.
 2518          */
 2519         if (needoutput || (tp->t_flags & TF_ACKNOW))
 2520                 (void) tcp_output(tp);
 2521 
 2522 check_delack:
 2523         INP_LOCK_ASSERT(inp);
 2524         if (tp->t_flags & TF_DELACK) {
 2525                 tp->t_flags &= ~TF_DELACK;
 2526                 callout_reset(tp->tt_delack, tcp_delacktime,
 2527                     tcp_timer_delack, tp);
 2528         }
 2529         INP_UNLOCK(inp);
 2530         return;
 2531 
 2532 dropafterack:
 2533         /*
 2534          * Generate an ACK dropping incoming segment if it occupies
 2535          * sequence space, where the ACK reflects our state.
 2536          *
 2537          * We can now skip the test for the RST flag since all
 2538          * paths to this code happen after packets containing
 2539          * RST have been dropped.
 2540          *
 2541          * In the SYN-RECEIVED state, don't send an ACK unless the
 2542          * segment we received passes the SYN-RECEIVED ACK test.
 2543          * If it fails send a RST.  This breaks the loop in the
 2544          * "LAND" DoS attack, and also prevents an ACK storm
 2545          * between two listening ports that have been sent forged
 2546          * SYN segments, each with the source address of the other.
 2547          */
 2548         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
 2549             (SEQ_GT(tp->snd_una, th->th_ack) ||
 2550              SEQ_GT(th->th_ack, tp->snd_max)) ) {
 2551                 rstreason = BANDLIM_RST_OPENPORT;
 2552                 goto dropwithreset;
 2553         }
 2554 #ifdef TCPDEBUG
 2555         if (so->so_options & SO_DEBUG)
 2556                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2557                           &tcp_savetcp, 0);
 2558 #endif
 2559         KASSERT(headlocked, ("headlocked should be 1"));
 2560         INP_INFO_WUNLOCK(&tcbinfo);
 2561         m_freem(m);
 2562         tp->t_flags |= TF_ACKNOW;
 2563         (void) tcp_output(tp);
 2564         INP_UNLOCK(inp);
 2565         return;
 2566 
 2567 dropwithreset:
 2568         /*
 2569          * Generate a RST, dropping incoming segment.
 2570          * Make ACK acceptable to originator of segment.
 2571          * Don't bother to respond if destination was broadcast/multicast.
 2572          */
 2573         if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
 2574                 goto drop;
 2575         if (isipv6) {
 2576                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 2577                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
 2578                         goto drop;
 2579         } else {
 2580                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 2581                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 2582                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 2583                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
 2584                         goto drop;
 2585         }
 2586         /* IPv6 anycast check is done at tcp6_input() */
 2587 
 2588         /*
 2589          * Perform bandwidth limiting.
 2590          */
 2591         if (badport_bandlim(rstreason) < 0)
 2592                 goto drop;
 2593 
 2594 #ifdef TCPDEBUG
 2595         if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
 2596                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2597                           &tcp_savetcp, 0);
 2598 #endif
 2599 
 2600         if (thflags & TH_ACK)
 2601                 /* mtod() below is safe as long as hdr dropping is delayed */
 2602                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
 2603                             TH_RST);
 2604         else {
 2605                 if (thflags & TH_SYN)
 2606                         tlen++;
 2607                 /* mtod() below is safe as long as hdr dropping is delayed */
 2608                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
 2609                             (tcp_seq)0, TH_RST|TH_ACK);
 2610         }
 2611 
 2612         if (tp)
 2613                 INP_UNLOCK(inp);
 2614         if (headlocked)
 2615                 INP_INFO_WUNLOCK(&tcbinfo);
 2616         return;
 2617 
 2618 drop:
 2619         /*
 2620          * Drop space held by incoming segment and return.
 2621          */
 2622 #ifdef TCPDEBUG
 2623         if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
 2624                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2625                           &tcp_savetcp, 0);
 2626 #endif
 2627         if (tp)
 2628                 INP_UNLOCK(inp);
 2629         m_freem(m);
 2630         if (headlocked)
 2631                 INP_INFO_WUNLOCK(&tcbinfo);
 2632         return;
 2633 }
 2634 
 2635 /*
 2636  * Parse TCP options and place in tcpopt.
 2637  */
 2638 static void
 2639 tcp_dooptions(tp, to, cp, cnt, is_syn, th)
 2640         struct tcpcb *tp;
 2641         struct tcpopt *to;
 2642         u_char *cp;
 2643         int cnt;
 2644         int is_syn;
 2645         struct tcphdr *th;
 2646 {
 2647         int opt, optlen;
 2648 
 2649         to->to_flags = 0;
 2650         for (; cnt > 0; cnt -= optlen, cp += optlen) {
 2651                 opt = cp[0];
 2652                 if (opt == TCPOPT_EOL)
 2653                         break;
 2654                 if (opt == TCPOPT_NOP)
 2655                         optlen = 1;
 2656                 else {
 2657                         if (cnt < 2)
 2658                                 break;
 2659                         optlen = cp[1];
 2660                         if (optlen < 2 || optlen > cnt)
 2661                                 break;
 2662                 }
 2663                 switch (opt) {
 2664                 case TCPOPT_MAXSEG:
 2665                         if (optlen != TCPOLEN_MAXSEG)
 2666                                 continue;
 2667                         if (!is_syn)
 2668                                 continue;
 2669                         to->to_flags |= TOF_MSS;
 2670                         bcopy((char *)cp + 2,
 2671                             (char *)&to->to_mss, sizeof(to->to_mss));
 2672                         to->to_mss = ntohs(to->to_mss);
 2673                         break;
 2674                 case TCPOPT_WINDOW:
 2675                         if (optlen != TCPOLEN_WINDOW)
 2676                                 continue;
 2677                         if (! is_syn)
 2678                                 continue;
 2679                         to->to_flags |= TOF_SCALE;
 2680                         to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
 2681                         break;
 2682                 case TCPOPT_TIMESTAMP:
 2683                         if (optlen != TCPOLEN_TIMESTAMP)
 2684                                 continue;
 2685                         to->to_flags |= TOF_TS;
 2686                         bcopy((char *)cp + 2,
 2687                             (char *)&to->to_tsval, sizeof(to->to_tsval));
 2688                         to->to_tsval = ntohl(to->to_tsval);
 2689                         bcopy((char *)cp + 6,
 2690                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
 2691                         to->to_tsecr = ntohl(to->to_tsecr);
 2692                         /*
 2693                          * If echoed timestamp is later than the current time,
 2694                          * fall back to non RFC1323 RTT calculation.
 2695                          */
 2696                         if ((to->to_tsecr != 0) && TSTMP_GT(to->to_tsecr, ticks))
 2697                                 to->to_tsecr = 0;
 2698                         break;
 2699                 case TCPOPT_CC:
 2700                         if (optlen != TCPOLEN_CC)
 2701                                 continue;
 2702                         to->to_flags |= TOF_CC;
 2703                         bcopy((char *)cp + 2,
 2704                             (char *)&to->to_cc, sizeof(to->to_cc));
 2705                         to->to_cc = ntohl(to->to_cc);
 2706                         break;
 2707                 case TCPOPT_CCNEW:
 2708                         if (optlen != TCPOLEN_CC)
 2709                                 continue;
 2710                         if (!is_syn)
 2711                                 continue;
 2712                         to->to_flags |= TOF_CCNEW;
 2713                         bcopy((char *)cp + 2,
 2714                             (char *)&to->to_cc, sizeof(to->to_cc));
 2715                         to->to_cc = ntohl(to->to_cc);
 2716                         break;
 2717                 case TCPOPT_CCECHO:
 2718                         if (optlen != TCPOLEN_CC)
 2719                                 continue;
 2720                         if (!is_syn)
 2721                                 continue;
 2722                         to->to_flags |= TOF_CCECHO;
 2723                         bcopy((char *)cp + 2,
 2724                             (char *)&to->to_ccecho, sizeof(to->to_ccecho));
 2725                         to->to_ccecho = ntohl(to->to_ccecho);
 2726                         break;
 2727 #ifdef TCP_SIGNATURE
 2728                 /*
 2729                  * XXX In order to reply to a host which has set the
 2730                  * TCP_SIGNATURE option in its initial SYN, we have to
 2731                  * record the fact that the option was observed here
 2732                  * for the syncache code to perform the correct response.
 2733                  */
 2734                 case TCPOPT_SIGNATURE:
 2735                         if (optlen != TCPOLEN_SIGNATURE)
 2736                                 continue;
 2737                         to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
 2738                         break;
 2739 #endif
 2740                 case TCPOPT_SACK_PERMITTED:
 2741                         if (!tcp_do_sack ||
 2742                             optlen != TCPOLEN_SACK_PERMITTED)
 2743                                 continue;
 2744                         if (is_syn) {
 2745                                 /* MUST only be set on SYN */
 2746                                 to->to_flags |= TOF_SACK;
 2747                         }
 2748                         break;
 2749 
 2750                 case TCPOPT_SACK:
 2751                         if (!tp || tcp_sack_option(tp, th, cp, optlen))
 2752                                 continue;
 2753                         break;
 2754                 default:
 2755                         continue;
 2756                 }
 2757         }
 2758 }
 2759 
 2760 /*
 2761  * Pull out of band byte out of a segment so
 2762  * it doesn't appear in the user's data queue.
 2763  * It is still reflected in the segment length for
 2764  * sequencing purposes.
 2765  */
 2766 static void
 2767 tcp_pulloutofband(so, th, m, off)
 2768         struct socket *so;
 2769         struct tcphdr *th;
 2770         register struct mbuf *m;
 2771         int off;                /* delayed to be droped hdrlen */
 2772 {
 2773         int cnt = off + th->th_urp - 1;
 2774 
 2775         while (cnt >= 0) {
 2776                 if (m->m_len > cnt) {
 2777                         char *cp = mtod(m, caddr_t) + cnt;
 2778                         struct tcpcb *tp = sototcpcb(so);
 2779 
 2780                         tp->t_iobc = *cp;
 2781                         tp->t_oobflags |= TCPOOB_HAVEDATA;
 2782                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
 2783                         m->m_len--;
 2784                         if (m->m_flags & M_PKTHDR)
 2785                                 m->m_pkthdr.len--;
 2786                         return;
 2787                 }
 2788                 cnt -= m->m_len;
 2789                 m = m->m_next;
 2790                 if (m == 0)
 2791                         break;
 2792         }
 2793         panic("tcp_pulloutofband");
 2794 }
 2795 
 2796 /*
 2797  * Collect new round-trip time estimate
 2798  * and update averages and current timeout.
 2799  */
 2800 static void
 2801 tcp_xmit_timer(tp, rtt)
 2802         register struct tcpcb *tp;
 2803         int rtt;
 2804 {
 2805         register int delta;
 2806 
 2807         tcpstat.tcps_rttupdated++;
 2808         tp->t_rttupdated++;
 2809         if (tp->t_srtt != 0) {
 2810                 /*
 2811                  * srtt is stored as fixed point with 5 bits after the
 2812                  * binary point (i.e., scaled by 8).  The following magic
 2813                  * is equivalent to the smoothing algorithm in rfc793 with
 2814                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
 2815                  * point).  Adjust rtt to origin 0.
 2816                  */
 2817                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
 2818                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
 2819 
 2820                 if ((tp->t_srtt += delta) <= 0)
 2821                         tp->t_srtt = 1;
 2822 
 2823                 /*
 2824                  * We accumulate a smoothed rtt variance (actually, a
 2825                  * smoothed mean difference), then set the retransmit
 2826                  * timer to smoothed rtt + 4 times the smoothed variance.
 2827                  * rttvar is stored as fixed point with 4 bits after the
 2828                  * binary point (scaled by 16).  The following is
 2829                  * equivalent to rfc793 smoothing with an alpha of .75
 2830                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
 2831                  * rfc793's wired-in beta.
 2832                  */
 2833                 if (delta < 0)
 2834                         delta = -delta;
 2835                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
 2836                 if ((tp->t_rttvar += delta) <= 0)
 2837                         tp->t_rttvar = 1;
 2838                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
 2839                     tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 2840         } else {
 2841                 /*
 2842                  * No rtt measurement yet - use the unsmoothed rtt.
 2843                  * Set the variance to half the rtt (so our first
 2844                  * retransmit happens at 3*rtt).
 2845                  */
 2846                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
 2847                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
 2848                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 2849         }
 2850         tp->t_rtttime = 0;
 2851         tp->t_rxtshift = 0;
 2852 
 2853         /*
 2854          * the retransmit should happen at rtt + 4 * rttvar.
 2855          * Because of the way we do the smoothing, srtt and rttvar
 2856          * will each average +1/2 tick of bias.  When we compute
 2857          * the retransmit timer, we want 1/2 tick of rounding and
 2858          * 1 extra tick because of +-1/2 tick uncertainty in the
 2859          * firing of the timer.  The bias will give us exactly the
 2860          * 1.5 tick we need.  But, because the bias is
 2861          * statistical, we have to test that we don't drop below
 2862          * the minimum feasible timer (which is 2 ticks).
 2863          */
 2864         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
 2865                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
 2866 
 2867         /*
 2868          * We received an ack for a packet that wasn't retransmitted;
 2869          * it is probably safe to discard any error indications we've
 2870          * received recently.  This isn't quite right, but close enough
 2871          * for now (a route might have failed after we sent a segment,
 2872          * and the return path might not be symmetrical).
 2873          */
 2874         tp->t_softerror = 0;
 2875 }
 2876 
 2877 /*
 2878  * Determine a reasonable value for maxseg size.
 2879  * If the route is known, check route for mtu.
 2880  * If none, use an mss that can be handled on the outgoing
 2881  * interface without forcing IP to fragment; if bigger than
 2882  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
 2883  * to utilize large mbufs.  If no route is found, route has no mtu,
 2884  * or the destination isn't local, use a default, hopefully conservative
 2885  * size (usually 512 or the default IP max size, but no more than the mtu
 2886  * of the interface), as we can't discover anything about intervening
 2887  * gateways or networks.  We also initialize the congestion/slow start
 2888  * window to be a single segment if the destination isn't local.
 2889  * While looking at the routing entry, we also initialize other path-dependent
 2890  * parameters from pre-set or cached values in the routing entry.
 2891  *
 2892  * Also take into account the space needed for options that we
 2893  * send regularly.  Make maxseg shorter by that amount to assure
 2894  * that we can send maxseg amount of data even when the options
 2895  * are present.  Store the upper limit of the length of options plus
 2896  * data in maxopd.
 2897  *
 2898  *
 2899  * In case of T/TCP, we call this routine during implicit connection
 2900  * setup as well (offer = -1), to initialize maxseg from the cached
 2901  * MSS of our peer.
 2902  *
 2903  * NOTE that this routine is only called when we process an incoming
 2904  * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
 2905  */
 2906 void
 2907 tcp_mss(tp, offer)
 2908         struct tcpcb *tp;
 2909         int offer;
 2910 {
 2911         int rtt, mss;
 2912         u_long bufsize;
 2913         u_long maxmtu;
 2914         struct inpcb *inp = tp->t_inpcb;
 2915         struct socket *so;
 2916         struct hc_metrics_lite metrics;
 2917         struct rmxp_tao tao;
 2918         int origoffer = offer;
 2919 #ifdef INET6
 2920         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
 2921         size_t min_protoh = isipv6 ?
 2922                             sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
 2923                             sizeof (struct tcpiphdr);
 2924 #else
 2925         const size_t min_protoh = sizeof(struct tcpiphdr);
 2926 #endif
 2927         bzero(&tao, sizeof(tao));
 2928 
 2929         /* initialize */
 2930 #ifdef INET6
 2931         if (isipv6) {
 2932                 maxmtu = tcp_maxmtu6(&inp->inp_inc);
 2933                 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
 2934         } else
 2935 #endif
 2936         {
 2937                 maxmtu = tcp_maxmtu(&inp->inp_inc);
 2938                 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
 2939         }
 2940         so = inp->inp_socket;
 2941 
 2942         /*
 2943          * no route to sender, stay with default mss and return
 2944          */
 2945         if (maxmtu == 0)
 2946                 return;
 2947 
 2948         /* what have we got? */
 2949         switch (offer) {
 2950                 case 0:
 2951                         /*
 2952                          * Offer == 0 means that there was no MSS on the SYN
 2953                          * segment, in this case we use tcp_mssdflt.
 2954                          */
 2955                         offer =
 2956 #ifdef INET6
 2957                                 isipv6 ? tcp_v6mssdflt :
 2958 #endif
 2959                                 tcp_mssdflt;
 2960                         break;
 2961 
 2962                 case -1:
 2963                         /*
 2964                          * Offer == -1 means that we didn't receive SYN yet,
 2965                          * use cached value in that case;
 2966                          */
 2967                         if (tcp_do_rfc1644)
 2968                                 tcp_hc_gettao(&inp->inp_inc, &tao);
 2969                         if (tao.tao_mssopt != 0)
 2970                                 offer = tao.tao_mssopt;
 2971                         /* FALLTHROUGH */
 2972 
 2973                 default:
 2974                         /*
 2975                          * Prevent DoS attack with too small MSS. Round up
 2976                          * to at least minmss.
 2977                          */
 2978                         offer = max(offer, tcp_minmss);
 2979                         /*
 2980                          * Sanity check: make sure that maxopd will be large
 2981                          * enough to allow some data on segments even if the
 2982                          * all the option space is used (40bytes).  Otherwise
 2983                          * funny things may happen in tcp_output.
 2984                          */
 2985                         offer = max(offer, 64);
 2986                         if (tcp_do_rfc1644)
 2987                                 tcp_hc_updatetao(&inp->inp_inc,
 2988                                                  TCP_HC_TAO_MSSOPT, 0, offer);
 2989         }
 2990 
 2991         /*
 2992          * rmx information is now retrieved from tcp_hostcache
 2993          */
 2994         tcp_hc_get(&inp->inp_inc, &metrics);
 2995 
 2996         /*
 2997          * if there's a discovered mtu int tcp hostcache, use it
 2998          * else, use the link mtu.
 2999          */
 3000         if (metrics.rmx_mtu)
 3001                 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
 3002         else {
 3003 #ifdef INET6
 3004                 if (isipv6) {
 3005                         mss = maxmtu - min_protoh;
 3006                         if (!path_mtu_discovery &&
 3007                             !in6_localaddr(&inp->in6p_faddr))
 3008                                 mss = min(mss, tcp_v6mssdflt);
 3009                 } else
 3010 #endif
 3011                 {
 3012                         mss = maxmtu - min_protoh;
 3013                         if (!path_mtu_discovery &&
 3014                             !in_localaddr(inp->inp_faddr))
 3015                                 mss = min(mss, tcp_mssdflt);
 3016                 }
 3017         }
 3018         mss = min(mss, offer);
 3019 
 3020         /*
 3021          * maxopd stores the maximum length of data AND options
 3022          * in a segment; maxseg is the amount of data in a normal
 3023          * segment.  We need to store this value (maxopd) apart
 3024          * from maxseg, because now every segment carries options
 3025          * and thus we normally have somewhat less data in segments.
 3026          */
 3027         tp->t_maxopd = mss;
 3028 
 3029         /*
 3030          * In case of T/TCP, origoffer==-1 indicates, that no segments
 3031          * were received yet.  In this case we just guess, otherwise
 3032          * we do the same as before T/TCP.
 3033          */
 3034         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
 3035             (origoffer == -1 ||
 3036              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
 3037                 mss -= TCPOLEN_TSTAMP_APPA;
 3038         if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
 3039             (origoffer == -1 ||
 3040              (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
 3041                 mss -= TCPOLEN_CC_APPA;
 3042         tp->t_maxseg = mss;
 3043 
 3044 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
 3045                 if (mss > MCLBYTES)
 3046                         mss &= ~(MCLBYTES-1);
 3047 #else
 3048                 if (mss > MCLBYTES)
 3049                         mss = mss / MCLBYTES * MCLBYTES;
 3050 #endif
 3051         tp->t_maxseg = mss;
 3052 
 3053         /*
 3054          * If there's a pipesize, change the socket buffer to that size,
 3055          * don't change if sb_hiwat is different than default (then it
 3056          * has been changed on purpose with setsockopt).
 3057          * Make the socket buffers an integral number of mss units;
 3058          * if the mss is larger than the socket buffer, decrease the mss.
 3059          */
 3060         SOCKBUF_LOCK(&so->so_snd);
 3061         if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
 3062                 bufsize = metrics.rmx_sendpipe;
 3063         else
 3064                 bufsize = so->so_snd.sb_hiwat;
 3065         if (bufsize < mss)
 3066                 mss = bufsize;
 3067         else {
 3068                 bufsize = roundup(bufsize, mss);
 3069                 if (bufsize > sb_max)
 3070                         bufsize = sb_max;
 3071                 if (bufsize > so->so_snd.sb_hiwat)
 3072                         (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
 3073         }
 3074         SOCKBUF_UNLOCK(&so->so_snd);
 3075         tp->t_maxseg = mss;
 3076 
 3077         SOCKBUF_LOCK(&so->so_rcv);
 3078         if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
 3079                 bufsize = metrics.rmx_recvpipe;
 3080         else
 3081                 bufsize = so->so_rcv.sb_hiwat;
 3082         if (bufsize > mss) {
 3083                 bufsize = roundup(bufsize, mss);
 3084                 if (bufsize > sb_max)
 3085                         bufsize = sb_max;
 3086                 if (bufsize > so->so_rcv.sb_hiwat)
 3087                         (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
 3088         }
 3089         SOCKBUF_UNLOCK(&so->so_rcv);
 3090         /*
 3091          * While we're here, check the others too
 3092          */
 3093         if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
 3094                 tp->t_srtt = rtt;
 3095                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
 3096                 tcpstat.tcps_usedrtt++;
 3097                 if (metrics.rmx_rttvar) {
 3098                         tp->t_rttvar = metrics.rmx_rttvar;
 3099                         tcpstat.tcps_usedrttvar++;
 3100                 } else {
 3101                         /* default variation is +- 1 rtt */
 3102                         tp->t_rttvar =
 3103                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
 3104                 }
 3105                 TCPT_RANGESET(tp->t_rxtcur,
 3106                               ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
 3107                               tp->t_rttmin, TCPTV_REXMTMAX);
 3108         }
 3109         if (metrics.rmx_ssthresh) {
 3110                 /*
 3111                  * There's some sort of gateway or interface
 3112                  * buffer limit on the path.  Use this to set
 3113                  * the slow start threshhold, but set the
 3114                  * threshold to no less than 2*mss.
 3115                  */
 3116                 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
 3117                 tcpstat.tcps_usedssthresh++;
 3118         }
 3119         if (metrics.rmx_bandwidth)
 3120                 tp->snd_bandwidth = metrics.rmx_bandwidth;
 3121 
 3122         /*
 3123          * Set the slow-start flight size depending on whether this
 3124          * is a local network or not.
 3125          *
 3126          * Extend this so we cache the cwnd too and retrieve it here.
 3127          * Make cwnd even bigger than RFC3390 suggests but only if we
 3128          * have previous experience with the remote host. Be careful
 3129          * not make cwnd bigger than remote receive window or our own
 3130          * send socket buffer. Maybe put some additional upper bound
 3131          * on the retrieved cwnd. Should do incremental updates to
 3132          * hostcache when cwnd collapses so next connection doesn't
 3133          * overloads the path again.
 3134          *
 3135          * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
 3136          * We currently check only in syncache_socket for that.
 3137          */
 3138 #define TCP_METRICS_CWND
 3139 #ifdef TCP_METRICS_CWND
 3140         if (metrics.rmx_cwnd)
 3141                 tp->snd_cwnd = max(mss,
 3142                                 min(metrics.rmx_cwnd / 2,
 3143                                  min(tp->snd_wnd, so->so_snd.sb_hiwat)));
 3144         else
 3145 #endif
 3146         if (tcp_do_rfc3390)
 3147                 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
 3148 #ifdef INET6
 3149         else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
 3150                  (!isipv6 && in_localaddr(inp->inp_faddr)))
 3151 #else
 3152         else if (in_localaddr(inp->inp_faddr))
 3153 #endif
 3154                 tp->snd_cwnd = mss * ss_fltsz_local;
 3155         else
 3156                 tp->snd_cwnd = mss * ss_fltsz;
 3157 }
 3158 
 3159 /*
 3160  * Determine the MSS option to send on an outgoing SYN.
 3161  */
 3162 int
 3163 tcp_mssopt(inc)
 3164         struct in_conninfo *inc;
 3165 {
 3166         int mss = 0;
 3167         u_long maxmtu = 0;
 3168         u_long thcmtu = 0;
 3169         size_t min_protoh;
 3170 #ifdef INET6
 3171         int isipv6 = inc->inc_isipv6 ? 1 : 0;
 3172 #endif
 3173 
 3174         KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
 3175 
 3176 #ifdef INET6
 3177         if (isipv6) {
 3178                 mss = tcp_v6mssdflt;
 3179                 maxmtu = tcp_maxmtu6(inc);
 3180                 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3181                 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
 3182         } else
 3183 #endif
 3184         {
 3185                 mss = tcp_mssdflt;
 3186                 maxmtu = tcp_maxmtu(inc);
 3187                 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3188                 min_protoh = sizeof(struct tcpiphdr);
 3189         }
 3190         if (maxmtu && thcmtu)
 3191                 mss = min(maxmtu, thcmtu) - min_protoh;
 3192         else if (maxmtu || thcmtu)
 3193                 mss = max(maxmtu, thcmtu) - min_protoh;
 3194 
 3195         return (mss);
 3196 }
 3197 
 3198 
 3199 /*
 3200  * On a partial ack arrives, force the retransmission of the
 3201  * next unacknowledged segment.  Do not clear tp->t_dupacks.
 3202  * By setting snd_nxt to ti_ack, this forces retransmission timer to
 3203  * be started again.
 3204  */
 3205 static void
 3206 tcp_newreno_partial_ack(tp, th)
 3207         struct tcpcb *tp;
 3208         struct tcphdr *th;
 3209 {
 3210         tcp_seq onxt = tp->snd_nxt;
 3211         u_long  ocwnd = tp->snd_cwnd;
 3212 
 3213         callout_stop(tp->tt_rexmt);
 3214         tp->t_rtttime = 0;
 3215         tp->snd_nxt = th->th_ack;
 3216         /*
 3217          * Set snd_cwnd to one segment beyond acknowledged offset.
 3218          * (tp->snd_una has not yet been updated when this function is called.)
 3219          */
 3220         tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
 3221         tp->t_flags |= TF_ACKNOW;
 3222         (void) tcp_output(tp);
 3223         tp->snd_cwnd = ocwnd;
 3224         if (SEQ_GT(onxt, tp->snd_nxt))
 3225                 tp->snd_nxt = onxt;
 3226         /*
 3227          * Partial window deflation.  Relies on fact that tp->snd_una
 3228          * not updated yet.
 3229          */
 3230         tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
 3231 }
 3232 
 3233 /*
 3234  * Returns 1 if the TIME_WAIT state was killed and we should start over,
 3235  * looking for a pcb in the listen state.  Returns 0 otherwise.
 3236  */
 3237 static int
 3238 tcp_timewait(tw, to, th, m, tlen)
 3239         struct tcptw *tw;
 3240         struct tcpopt *to;
 3241         struct tcphdr *th;
 3242         struct mbuf *m;
 3243         int tlen;
 3244 {
 3245         int thflags;
 3246         tcp_seq seq;
 3247 #ifdef INET6
 3248         int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
 3249 #else
 3250         const int isipv6 = 0;
 3251 #endif
 3252 
 3253         thflags = th->th_flags;
 3254 
 3255         /*
 3256          * NOTE: for FIN_WAIT_2 (to be added later),
 3257          * must validate sequence number before accepting RST
 3258          */
 3259 
 3260         /*
 3261          * If the segment contains RST:
 3262          *      Drop the segment - see Stevens, vol. 2, p. 964 and
 3263          *      RFC 1337.
 3264          */
 3265         if (thflags & TH_RST)
 3266                 goto drop;
 3267 
 3268         /*
 3269          * If segment contains a SYN and CC [not CC.NEW] option:
 3270          *      if connection duration > MSL, drop packet and send RST;
 3271          *
 3272          *      if SEG.CC > CCrecv then is new SYN.
 3273          *          Complete close and delete TCPCB.  Then reprocess
 3274          *          segment, hoping to find new TCPCB in LISTEN state;
 3275          *
 3276          *      else must be old SYN; drop it.
 3277          * else do normal processing.
 3278          */
 3279         if ((thflags & TH_SYN) && (to->to_flags & TOF_CC) && tw->cc_recv != 0) {
 3280                 if ((ticks - tw->t_starttime) > tcp_msl)
 3281                         goto reset;
 3282                 if (CC_GT(to->to_cc, tw->cc_recv)) {
 3283                         (void) tcp_twclose(tw, 0);
 3284                         return (1);
 3285                 }
 3286                 goto drop;
 3287         }
 3288 
 3289 #if 0
 3290 /* PAWS not needed at the moment */
 3291         /*
 3292          * RFC 1323 PAWS: If we have a timestamp reply on this segment
 3293          * and it's less than ts_recent, drop it.
 3294          */
 3295         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
 3296             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
 3297                 if ((thflags & TH_ACK) == 0)
 3298                         goto drop;
 3299                 goto ack;
 3300         }
 3301         /*
 3302          * ts_recent is never updated because we never accept new segments.
 3303          */
 3304 #endif
 3305 
 3306         /*
 3307          * If a new connection request is received
 3308          * while in TIME_WAIT, drop the old connection
 3309          * and start over if the sequence numbers
 3310          * are above the previous ones.
 3311          */
 3312         if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
 3313                 (void) tcp_twclose(tw, 0);
 3314                 return (1);
 3315         }
 3316 
 3317         /*
 3318          * Drop the the segment if it does not contain an ACK.
 3319          */
 3320         if ((thflags & TH_ACK) == 0)
 3321                 goto drop;
 3322 
 3323         /*
 3324          * Reset the 2MSL timer if this is a duplicate FIN.
 3325          */
 3326         if (thflags & TH_FIN) {
 3327                 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
 3328                 if (seq + 1 == tw->rcv_nxt)
 3329                         tcp_timer_2msl_reset(tw, 2 * tcp_msl);
 3330         }
 3331 
 3332         /*
 3333          * Acknowledge the segment if it has data or is not a duplicate ACK.
 3334          */
 3335         if (thflags != TH_ACK || tlen != 0 ||
 3336             th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
 3337                 tcp_twrespond(tw, TH_ACK);
 3338         goto drop;
 3339 
 3340 reset:
 3341         /*
 3342          * Generate a RST, dropping incoming segment.
 3343          * Make ACK acceptable to originator of segment.
 3344          * Don't bother to respond if destination was broadcast/multicast.
 3345          */
 3346         if (m->m_flags & (M_BCAST|M_MCAST))
 3347                 goto drop;
 3348         if (isipv6) {
 3349                 struct ip6_hdr *ip6;
 3350 
 3351                 /* IPv6 anycast check is done at tcp6_input() */
 3352                 ip6 = mtod(m, struct ip6_hdr *);
 3353                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 3354                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
 3355                         goto drop;
 3356         } else {
 3357                 struct ip *ip;
 3358 
 3359                 ip = mtod(m, struct ip *);
 3360                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 3361                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 3362                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 3363                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
 3364                         goto drop;
 3365         }
 3366         if (thflags & TH_ACK) {
 3367                 tcp_respond(NULL,
 3368                     mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
 3369         } else {
 3370                 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
 3371                 tcp_respond(NULL,
 3372                     mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
 3373         }
 3374         INP_UNLOCK(tw->tw_inpcb);
 3375         return (0);
 3376 
 3377 drop:
 3378         INP_UNLOCK(tw->tw_inpcb);
 3379         m_freem(m);
 3380         return (0);
 3381 }

Cache object: 3d1f3e8d4757fc7b2c026e50ee367e51


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.