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

Cache object: 5513d11e845fa595b9be55ab5d95ba15


[ 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.