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


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

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

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

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

Cache object: a7e78000489779d6f25ce5ae65946266


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