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

Cache object: 286152bd9de601da3ef0a16b80f42a10


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