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: releng/7.4/sys/netinet/tcp_input.c 215926 2010-11-27 03:12:39Z lstewart $");
   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, ticks))
  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 = ticks;
  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 = ticks;
 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                                     (int)(ticks - tp->t_badrxtwin) < 0) {
 1034                                         ++tcpstat.tcps_sndrexmitbad;
 1035                                         tp->snd_cwnd = tp->snd_cwnd_prev;
 1036                                         tp->snd_ssthresh =
 1037                                             tp->snd_ssthresh_prev;
 1038                                         tp->snd_recover = tp->snd_recover_prev;
 1039                                         if (tp->t_flags & TF_WASFRECOVERY)
 1040                                             ENTER_FASTRECOVERY(tp);
 1041                                         tp->snd_nxt = tp->snd_max;
 1042                                         tp->t_badrxtwin = 0;
 1043                                 }
 1044 
 1045                                 /*
 1046                                  * Recalculate the transmit timer / rtt.
 1047                                  *
 1048                                  * Some boxes send broken timestamp replies
 1049                                  * during the SYN+ACK phase, ignore
 1050                                  * timestamps of 0 or we could calculate a
 1051                                  * huge RTT and blow up the retransmit timer.
 1052                                  */
 1053                                 if ((to.to_flags & TOF_TS) != 0 &&
 1054                                     to.to_tsecr) {
 1055                                         if (!tp->t_rttlow ||
 1056                                             tp->t_rttlow > ticks - to.to_tsecr)
 1057                                                 tp->t_rttlow = ticks - to.to_tsecr;
 1058                                         tcp_xmit_timer(tp,
 1059                                             ticks - to.to_tsecr + 1);
 1060                                 } else if (tp->t_rtttime &&
 1061                                     SEQ_GT(th->th_ack, tp->t_rtseq)) {
 1062                                         if (!tp->t_rttlow ||
 1063                                             tp->t_rttlow > ticks - tp->t_rtttime)
 1064                                                 tp->t_rttlow = ticks - tp->t_rtttime;
 1065                                         tcp_xmit_timer(tp,
 1066                                                         ticks - tp->t_rtttime);
 1067                                 }
 1068                                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
 1069                                 acked = th->th_ack - tp->snd_una;
 1070                                 tcpstat.tcps_rcvackpack++;
 1071                                 tcpstat.tcps_rcvackbyte += acked;
 1072                                 sbdrop(&so->so_snd, acked);
 1073                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
 1074                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 1075                                         tp->snd_recover = th->th_ack - 1;
 1076                                 tp->snd_una = th->th_ack;
 1077                                 /*
 1078                                  * Pull snd_wl2 up to prevent seq wrap relative
 1079                                  * to th_ack.
 1080                                  */
 1081                                 tp->snd_wl2 = th->th_ack;
 1082                                 tp->t_dupacks = 0;
 1083                                 m_freem(m);
 1084                                 ND6_HINT(tp); /* Some progress has been made. */
 1085 
 1086                                 /*
 1087                                  * If all outstanding data are acked, stop
 1088                                  * retransmit timer, otherwise restart timer
 1089                                  * using current (possibly backed-off) value.
 1090                                  * If process is waiting for space,
 1091                                  * wakeup/selwakeup/signal.  If data
 1092                                  * are ready to send, let tcp_output
 1093                                  * decide between more output or persist.
 1094                                  */
 1095 #ifdef TCPDEBUG
 1096                                 if (so->so_options & SO_DEBUG)
 1097                                         tcp_trace(TA_INPUT, ostate, tp,
 1098                                             (void *)tcp_saveipgen,
 1099                                             &tcp_savetcp, 0);
 1100 #endif
 1101                                 if (tp->snd_una == tp->snd_max)
 1102                                         tcp_timer_activate(tp, TT_REXMT, 0);
 1103                                 else if (!tcp_timer_active(tp, TT_PERSIST))
 1104                                         tcp_timer_activate(tp, TT_REXMT,
 1105                                                       tp->t_rxtcur);
 1106                                 sowwakeup(so);
 1107                                 if (so->so_snd.sb_cc)
 1108                                         (void) tcp_output(tp);
 1109                                 goto check_delack;
 1110                         }
 1111                 } else if (th->th_ack == tp->snd_una &&
 1112                     tlen <= sbspace(&so->so_rcv)) {
 1113                         int newsize = 0;        /* automatic sockbuf scaling */
 1114 
 1115                         KASSERT(headlocked, ("%s: headlocked", __func__));
 1116                         INP_INFO_WUNLOCK(&tcbinfo);
 1117                         headlocked = 0;
 1118                         /*
 1119                          * This is a pure, in-sequence data packet
 1120                          * with nothing on the reassembly queue and
 1121                          * we have enough buffer space to take it.
 1122                          */
 1123                         /* Clean receiver SACK report if present */
 1124                         if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
 1125                                 tcp_clean_sackreport(tp);
 1126                         ++tcpstat.tcps_preddat;
 1127                         tp->rcv_nxt += tlen;
 1128                         /*
 1129                          * Pull snd_wl1 up to prevent seq wrap relative to
 1130                          * th_seq.
 1131                          */
 1132                         tp->snd_wl1 = th->th_seq;
 1133                         /*
 1134                          * Pull rcv_up up to prevent seq wrap relative to
 1135                          * rcv_nxt.
 1136                          */
 1137                         tp->rcv_up = tp->rcv_nxt;
 1138                         tcpstat.tcps_rcvpack++;
 1139                         tcpstat.tcps_rcvbyte += tlen;
 1140                         ND6_HINT(tp);   /* Some progress has been made */
 1141 #ifdef TCPDEBUG
 1142                         if (so->so_options & SO_DEBUG)
 1143                                 tcp_trace(TA_INPUT, ostate, tp,
 1144                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
 1145 #endif
 1146                 /*
 1147                  * Automatic sizing of receive socket buffer.  Often the send
 1148                  * buffer size is not optimally adjusted to the actual network
 1149                  * conditions at hand (delay bandwidth product).  Setting the
 1150                  * buffer size too small limits throughput on links with high
 1151                  * bandwidth and high delay (eg. trans-continental/oceanic links).
 1152                  *
 1153                  * On the receive side the socket buffer memory is only rarely
 1154                  * used to any significant extent.  This allows us to be much
 1155                  * more aggressive in scaling the receive socket buffer.  For
 1156                  * the case that the buffer space is actually used to a large
 1157                  * extent and we run out of kernel memory we can simply drop
 1158                  * the new segments; TCP on the sender will just retransmit it
 1159                  * later.  Setting the buffer size too big may only consume too
 1160                  * much kernel memory if the application doesn't read() from
 1161                  * the socket or packet loss or reordering makes use of the
 1162                  * reassembly queue.
 1163                  *
 1164                  * The criteria to step up the receive buffer one notch are:
 1165                  *  1. the number of bytes received during the time it takes
 1166                  *     one timestamp to be reflected back to us (the RTT);
 1167                  *  2. received bytes per RTT is within seven eighth of the
 1168                  *     current socket buffer size;
 1169                  *  3. receive buffer size has not hit maximal automatic size;
 1170                  *
 1171                  * This algorithm does one step per RTT at most and only if
 1172                  * we receive a bulk stream w/o packet losses or reorderings.
 1173                  * Shrinking the buffer during idle times is not necessary as
 1174                  * it doesn't consume any memory when idle.
 1175                  *
 1176                  * TODO: Only step up if the application is actually serving
 1177                  * the buffer to better manage the socket buffer resources.
 1178                  */
 1179                         if (tcp_do_autorcvbuf &&
 1180                             to.to_tsecr &&
 1181                             (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
 1182                                 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
 1183                                     to.to_tsecr - tp->rfbuf_ts < hz) {
 1184                                         if (tp->rfbuf_cnt >
 1185                                             (so->so_rcv.sb_hiwat / 8 * 7) &&
 1186                                             so->so_rcv.sb_hiwat <
 1187                                             tcp_autorcvbuf_max) {
 1188                                                 newsize =
 1189                                                     min(so->so_rcv.sb_hiwat +
 1190                                                     tcp_autorcvbuf_inc,
 1191                                                     tcp_autorcvbuf_max);
 1192                                         }
 1193                                         /* Start over with next RTT. */
 1194                                         tp->rfbuf_ts = 0;
 1195                                         tp->rfbuf_cnt = 0;
 1196                                 } else
 1197                                         tp->rfbuf_cnt += tlen;  /* add up */
 1198                         }
 1199 
 1200                         /* Add data to socket buffer. */
 1201                         SOCKBUF_LOCK(&so->so_rcv);
 1202                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 1203                                 m_freem(m);
 1204                         } else {
 1205                                 /*
 1206                                  * Set new socket buffer size.
 1207                                  * Give up when limit is reached.
 1208                                  */
 1209                                 if (newsize)
 1210                                         if (!sbreserve_locked(&so->so_rcv,
 1211                                             newsize, so, NULL))
 1212                                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
 1213                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 1214                                 sbappendstream_locked(&so->so_rcv, m);
 1215                         }
 1216                         /* NB: sorwakeup_locked() does an implicit unlock. */
 1217                         sorwakeup_locked(so);
 1218                         if (DELAY_ACK(tp)) {
 1219                                 tp->t_flags |= TF_DELACK;
 1220                         } else {
 1221                                 tp->t_flags |= TF_ACKNOW;
 1222                                 tcp_output(tp);
 1223                         }
 1224                         goto check_delack;
 1225                 }
 1226         }
 1227 
 1228         /*
 1229          * Calculate amount of space in receive window,
 1230          * and then do TCP input processing.
 1231          * Receive window is amount of space in rcv queue,
 1232          * but not less than advertised window.
 1233          */
 1234         win = sbspace(&so->so_rcv);
 1235         if (win < 0)
 1236                 win = 0;
 1237         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
 1238 
 1239         /* Reset receive buffer auto scaling when not in bulk receive mode. */
 1240         tp->rfbuf_ts = 0;
 1241         tp->rfbuf_cnt = 0;
 1242 
 1243         switch (tp->t_state) {
 1244 
 1245         /*
 1246          * If the state is SYN_RECEIVED:
 1247          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
 1248          */
 1249         case TCPS_SYN_RECEIVED:
 1250                 if ((thflags & TH_ACK) &&
 1251                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
 1252                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1253                                 rstreason = BANDLIM_RST_OPENPORT;
 1254                                 goto dropwithreset;
 1255                 }
 1256                 break;
 1257 
 1258         /*
 1259          * If the state is SYN_SENT:
 1260          *      if seg contains an ACK, but not for our SYN, drop the input.
 1261          *      if seg contains a RST, then drop the connection.
 1262          *      if seg does not contain SYN, then drop it.
 1263          * Otherwise this is an acceptable SYN segment
 1264          *      initialize tp->rcv_nxt and tp->irs
 1265          *      if seg contains ack then advance tp->snd_una
 1266          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
 1267          *      arrange for segment to be acked (eventually)
 1268          *      continue processing rest of data/controls, beginning with URG
 1269          */
 1270         case TCPS_SYN_SENT:
 1271                 if ((thflags & TH_ACK) &&
 1272                     (SEQ_LEQ(th->th_ack, tp->iss) ||
 1273                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1274                         rstreason = BANDLIM_UNLIMITED;
 1275                         goto dropwithreset;
 1276                 }
 1277                 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
 1278                         tp = tcp_drop(tp, ECONNREFUSED);
 1279                 if (thflags & TH_RST)
 1280                         goto drop;
 1281                 if (!(thflags & TH_SYN))
 1282                         goto drop;
 1283 
 1284                 tp->irs = th->th_seq;
 1285                 tcp_rcvseqinit(tp);
 1286                 if (thflags & TH_ACK) {
 1287                         tcpstat.tcps_connects++;
 1288                         soisconnected(so);
 1289 #ifdef MAC
 1290                         SOCK_LOCK(so);
 1291                         mac_set_socket_peer_from_mbuf(m, so);
 1292                         SOCK_UNLOCK(so);
 1293 #endif
 1294                         /* Do window scaling on this connection? */
 1295                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1296                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1297                                 tp->rcv_scale = tp->request_r_scale;
 1298                         }
 1299                         tp->rcv_adv += tp->rcv_wnd;
 1300                         tp->snd_una++;          /* SYN is acked */
 1301                         /*
 1302                          * If there's data, delay ACK; if there's also a FIN
 1303                          * ACKNOW will be turned on later.
 1304                          */
 1305                         if (DELAY_ACK(tp) && tlen != 0)
 1306                                 tcp_timer_activate(tp, TT_DELACK,
 1307                                     tcp_delacktime);
 1308                         else
 1309                                 tp->t_flags |= TF_ACKNOW;
 1310                         /*
 1311                          * Received <SYN,ACK> in SYN_SENT[*] state.
 1312                          * Transitions:
 1313                          *      SYN_SENT  --> ESTABLISHED
 1314                          *      SYN_SENT* --> FIN_WAIT_1
 1315                          */
 1316                         tp->t_starttime = ticks;
 1317                         if (tp->t_flags & TF_NEEDFIN) {
 1318                                 tp->t_state = TCPS_FIN_WAIT_1;
 1319                                 tp->t_flags &= ~TF_NEEDFIN;
 1320                                 thflags &= ~TH_SYN;
 1321                         } else {
 1322                                 tp->t_state = TCPS_ESTABLISHED;
 1323                                 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
 1324                         }
 1325                 } else {
 1326                         /*
 1327                          * Received initial SYN in SYN-SENT[*] state =>
 1328                          * simultaneous open.  If segment contains CC option
 1329                          * and there is a cached CC, apply TAO test.
 1330                          * If it succeeds, connection is * half-synchronized.
 1331                          * Otherwise, do 3-way handshake:
 1332                          *        SYN-SENT -> SYN-RECEIVED
 1333                          *        SYN-SENT* -> SYN-RECEIVED*
 1334                          * If there was no CC option, clear cached CC value.
 1335                          */
 1336                         tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
 1337                         tcp_timer_activate(tp, TT_REXMT, 0);
 1338                         tp->t_state = TCPS_SYN_RECEIVED;
 1339                 }
 1340 
 1341                 KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
 1342                     __func__));
 1343                 INP_WLOCK_ASSERT(tp->t_inpcb);
 1344 
 1345                 /*
 1346                  * Advance th->th_seq to correspond to first data byte.
 1347                  * If data, trim to stay within window,
 1348                  * dropping FIN if necessary.
 1349                  */
 1350                 th->th_seq++;
 1351                 if (tlen > tp->rcv_wnd) {
 1352                         todrop = tlen - tp->rcv_wnd;
 1353                         m_adj(m, -todrop);
 1354                         tlen = tp->rcv_wnd;
 1355                         thflags &= ~TH_FIN;
 1356                         tcpstat.tcps_rcvpackafterwin++;
 1357                         tcpstat.tcps_rcvbyteafterwin += todrop;
 1358                 }
 1359                 tp->snd_wl1 = th->th_seq - 1;
 1360                 tp->rcv_up = th->th_seq;
 1361                 /*
 1362                  * Client side of transaction: already sent SYN and data.
 1363                  * If the remote host used T/TCP to validate the SYN,
 1364                  * our data will be ACK'd; if so, enter normal data segment
 1365                  * processing in the middle of step 5, ack processing.
 1366                  * Otherwise, goto step 6.
 1367                  */
 1368                 if (thflags & TH_ACK)
 1369                         goto process_ACK;
 1370 
 1371                 goto step6;
 1372 
 1373         /*
 1374          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
 1375          *      do normal processing.
 1376          *
 1377          * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
 1378          */
 1379         case TCPS_LAST_ACK:
 1380         case TCPS_CLOSING:
 1381                 break;  /* continue normal processing */
 1382         }
 1383 
 1384         /*
 1385          * States other than LISTEN or SYN_SENT.
 1386          * First check the RST flag and sequence number since reset segments
 1387          * are exempt from the timestamp and connection count tests.  This
 1388          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
 1389          * below which allowed reset segments in half the sequence space
 1390          * to fall though and be processed (which gives forged reset
 1391          * segments with a random sequence number a 50 percent chance of
 1392          * killing a connection).
 1393          * Then check timestamp, if present.
 1394          * Then check the connection count, if present.
 1395          * Then check that at least some bytes of segment are within
 1396          * receive window.  If segment begins before rcv_nxt,
 1397          * drop leading data (and SYN); if nothing left, just ack.
 1398          *
 1399          *
 1400          * If the RST bit is set, check the sequence number to see
 1401          * if this is a valid reset segment.
 1402          * RFC 793 page 37:
 1403          *   In all states except SYN-SENT, all reset (RST) segments
 1404          *   are validated by checking their SEQ-fields.  A reset is
 1405          *   valid if its sequence number is in the window.
 1406          * Note: this does not take into account delayed ACKs, so
 1407          *   we should test against last_ack_sent instead of rcv_nxt.
 1408          *   The sequence number in the reset segment is normally an
 1409          *   echo of our outgoing acknowlegement numbers, but some hosts
 1410          *   send a reset with the sequence number at the rightmost edge
 1411          *   of our receive window, and we have to handle this case.
 1412          * Note 2: Paul Watson's paper "Slipping in the Window" has shown
 1413          *   that brute force RST attacks are possible.  To combat this,
 1414          *   we use a much stricter check while in the ESTABLISHED state,
 1415          *   only accepting RSTs where the sequence number is equal to
 1416          *   last_ack_sent.  In all other states (the states in which a
 1417          *   RST is more likely), the more permissive check is used.
 1418          * If we have multiple segments in flight, the initial reset
 1419          * segment sequence numbers will be to the left of last_ack_sent,
 1420          * but they will eventually catch up.
 1421          * In any case, it never made sense to trim reset segments to
 1422          * fit the receive window since RFC 1122 says:
 1423          *   4.2.2.12  RST Segment: RFC-793 Section 3.4
 1424          *
 1425          *    A TCP SHOULD allow a received RST segment to include data.
 1426          *
 1427          *    DISCUSSION
 1428          *         It has been suggested that a RST segment could contain
 1429          *         ASCII text that encoded and explained the cause of the
 1430          *         RST.  No standard has yet been established for such
 1431          *         data.
 1432          *
 1433          * If the reset segment passes the sequence number test examine
 1434          * the state:
 1435          *    SYN_RECEIVED STATE:
 1436          *      If passive open, return to LISTEN state.
 1437          *      If active open, inform user that connection was refused.
 1438          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
 1439          *      Inform user that connection was reset, and close tcb.
 1440          *    CLOSING, LAST_ACK STATES:
 1441          *      Close the tcb.
 1442          *    TIME_WAIT STATE:
 1443          *      Drop the segment - see Stevens, vol. 2, p. 964 and
 1444          *      RFC 1337.
 1445          */
 1446         if (thflags & TH_RST) {
 1447                 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
 1448                     SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
 1449                         switch (tp->t_state) {
 1450 
 1451                         case TCPS_SYN_RECEIVED:
 1452                                 so->so_error = ECONNREFUSED;
 1453                                 goto close;
 1454 
 1455                         case TCPS_ESTABLISHED:
 1456                                 if (tcp_insecure_rst == 0 &&
 1457                                     !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
 1458                                     SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
 1459                                     !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
 1460                                     SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
 1461                                         tcpstat.tcps_badrst++;
 1462                                         goto drop;
 1463                                 }
 1464                                 /* FALLTHROUGH */
 1465                         case TCPS_FIN_WAIT_1:
 1466                         case TCPS_FIN_WAIT_2:
 1467                         case TCPS_CLOSE_WAIT:
 1468                                 so->so_error = ECONNRESET;
 1469                         close:
 1470                                 tp->t_state = TCPS_CLOSED;
 1471                                 tcpstat.tcps_drops++;
 1472                                 KASSERT(headlocked, ("%s: trimthenstep6: "
 1473                                     "tcp_close: head not locked", __func__));
 1474                                 tp = tcp_close(tp);
 1475                                 break;
 1476 
 1477                         case TCPS_CLOSING:
 1478                         case TCPS_LAST_ACK:
 1479                                 KASSERT(headlocked, ("%s: trimthenstep6: "
 1480                                     "tcp_close.2: head not locked", __func__));
 1481                                 tp = tcp_close(tp);
 1482                                 break;
 1483                         }
 1484                 }
 1485                 goto drop;
 1486         }
 1487 
 1488         /*
 1489          * RFC 1323 PAWS: If we have a timestamp reply on this segment
 1490          * and it's less than ts_recent, drop it.
 1491          */
 1492         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
 1493             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
 1494 
 1495                 /* Check to see if ts_recent is over 24 days old.  */
 1496                 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
 1497                         /*
 1498                          * Invalidate ts_recent.  If this segment updates
 1499                          * ts_recent, the age will be reset later and ts_recent
 1500                          * will get a valid value.  If it does not, setting
 1501                          * ts_recent to zero will at least satisfy the
 1502                          * requirement that zero be placed in the timestamp
 1503                          * echo reply when ts_recent isn't valid.  The
 1504                          * age isn't reset until we get a valid ts_recent
 1505                          * because we don't want out-of-order segments to be
 1506                          * dropped when ts_recent is old.
 1507                          */
 1508                         tp->ts_recent = 0;
 1509                 } else {
 1510                         tcpstat.tcps_rcvduppack++;
 1511                         tcpstat.tcps_rcvdupbyte += tlen;
 1512                         tcpstat.tcps_pawsdrop++;
 1513                         if (tlen)
 1514                                 goto dropafterack;
 1515                         goto drop;
 1516                 }
 1517         }
 1518 
 1519         /*
 1520          * In the SYN-RECEIVED state, validate that the packet belongs to
 1521          * this connection before trimming the data to fit the receive
 1522          * window.  Check the sequence number versus IRS since we know
 1523          * the sequence numbers haven't wrapped.  This is a partial fix
 1524          * for the "LAND" DoS attack.
 1525          */
 1526         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
 1527                 rstreason = BANDLIM_RST_OPENPORT;
 1528                 goto dropwithreset;
 1529         }
 1530 
 1531         todrop = tp->rcv_nxt - th->th_seq;
 1532         if (todrop > 0) {
 1533                 if (thflags & TH_SYN) {
 1534                         thflags &= ~TH_SYN;
 1535                         th->th_seq++;
 1536                         if (th->th_urp > 1)
 1537                                 th->th_urp--;
 1538                         else
 1539                                 thflags &= ~TH_URG;
 1540                         todrop--;
 1541                 }
 1542                 /*
 1543                  * Following if statement from Stevens, vol. 2, p. 960.
 1544                  */
 1545                 if (todrop > tlen
 1546                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
 1547                         /*
 1548                          * Any valid FIN must be to the left of the window.
 1549                          * At this point the FIN must be a duplicate or out
 1550                          * of sequence; drop it.
 1551                          */
 1552                         thflags &= ~TH_FIN;
 1553 
 1554                         /*
 1555                          * Send an ACK to resynchronize and drop any data.
 1556                          * But keep on processing for RST or ACK.
 1557                          */
 1558                         tp->t_flags |= TF_ACKNOW;
 1559                         todrop = tlen;
 1560                         tcpstat.tcps_rcvduppack++;
 1561                         tcpstat.tcps_rcvdupbyte += todrop;
 1562                 } else {
 1563                         tcpstat.tcps_rcvpartduppack++;
 1564                         tcpstat.tcps_rcvpartdupbyte += todrop;
 1565                 }
 1566                 drop_hdrlen += todrop;  /* drop from the top afterwards */
 1567                 th->th_seq += todrop;
 1568                 tlen -= todrop;
 1569                 if (th->th_urp > todrop)
 1570                         th->th_urp -= todrop;
 1571                 else {
 1572                         thflags &= ~TH_URG;
 1573                         th->th_urp = 0;
 1574                 }
 1575         }
 1576 
 1577         /*
 1578          * If new data are received on a connection after the
 1579          * user processes are gone, then RST the other end.
 1580          */
 1581         if ((so->so_state & SS_NOFDREF) &&
 1582             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
 1583                 char *s;
 1584 
 1585                 KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
 1586                     "not locked", __func__));
 1587                 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
 1588                         log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
 1589                             "was closed, sending RST and removing tcpcb\n",
 1590                             s, __func__, tcpstates[tp->t_state], tlen);
 1591                         free(s, M_TCPLOG);
 1592                 }
 1593                 tp = tcp_close(tp);
 1594                 tcpstat.tcps_rcvafterclose++;
 1595                 rstreason = BANDLIM_UNLIMITED;
 1596                 goto dropwithreset;
 1597         }
 1598 
 1599         /*
 1600          * If segment ends after window, drop trailing data
 1601          * (and PUSH and FIN); if nothing left, just ACK.
 1602          */
 1603         todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
 1604         if (todrop > 0) {
 1605                 tcpstat.tcps_rcvpackafterwin++;
 1606                 if (todrop >= tlen) {
 1607                         tcpstat.tcps_rcvbyteafterwin += tlen;
 1608                         /*
 1609                          * If window is closed can only take segments at
 1610                          * window edge, and have to drop data and PUSH from
 1611                          * incoming segments.  Continue processing, but
 1612                          * remember to ack.  Otherwise, drop segment
 1613                          * and ack.
 1614                          */
 1615                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
 1616                                 tp->t_flags |= TF_ACKNOW;
 1617                                 tcpstat.tcps_rcvwinprobe++;
 1618                         } else
 1619                                 goto dropafterack;
 1620                 } else
 1621                         tcpstat.tcps_rcvbyteafterwin += todrop;
 1622                 m_adj(m, -todrop);
 1623                 tlen -= todrop;
 1624                 thflags &= ~(TH_PUSH|TH_FIN);
 1625         }
 1626 
 1627         /*
 1628          * If last ACK falls within this segment's sequence numbers,
 1629          * record its timestamp.
 1630          * NOTE: 
 1631          * 1) That the test incorporates suggestions from the latest
 1632          *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
 1633          * 2) That updating only on newer timestamps interferes with
 1634          *    our earlier PAWS tests, so this check should be solely
 1635          *    predicated on the sequence space of this segment.
 1636          * 3) That we modify the segment boundary check to be 
 1637          *        Last.ACK.Sent <= SEG.SEQ + SEG.Len  
 1638          *    instead of RFC1323's
 1639          *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
 1640          *    This modified check allows us to overcome RFC1323's
 1641          *    limitations as described in Stevens TCP/IP Illustrated
 1642          *    Vol. 2 p.869. In such cases, we can still calculate the
 1643          *    RTT correctly when RCV.NXT == Last.ACK.Sent.
 1644          */
 1645         if ((to.to_flags & TOF_TS) != 0 &&
 1646             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
 1647             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
 1648                 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
 1649                 tp->ts_recent_age = ticks;
 1650                 tp->ts_recent = to.to_tsval;
 1651         }
 1652 
 1653         /*
 1654          * If a SYN is in the window, then this is an
 1655          * error and we send an RST and drop the connection.
 1656          */
 1657         if (thflags & TH_SYN) {
 1658                 KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
 1659                     "head not locked", __func__));
 1660                 tp = tcp_drop(tp, ECONNRESET);
 1661                 rstreason = BANDLIM_UNLIMITED;
 1662                 goto drop;
 1663         }
 1664 
 1665         /*
 1666          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
 1667          * flag is on (half-synchronized state), then queue data for
 1668          * later processing; else drop segment and return.
 1669          */
 1670         if ((thflags & TH_ACK) == 0) {
 1671                 if (tp->t_state == TCPS_SYN_RECEIVED ||
 1672                     (tp->t_flags & TF_NEEDSYN))
 1673                         goto step6;
 1674                 else if (tp->t_flags & TF_ACKNOW)
 1675                         goto dropafterack;
 1676                 else
 1677                         goto drop;
 1678         }
 1679 
 1680         /*
 1681          * Ack processing.
 1682          */
 1683         switch (tp->t_state) {
 1684 
 1685         /*
 1686          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
 1687          * ESTABLISHED state and continue processing.
 1688          * The ACK was checked above.
 1689          */
 1690         case TCPS_SYN_RECEIVED:
 1691 
 1692                 tcpstat.tcps_connects++;
 1693                 soisconnected(so);
 1694                 /* Do window scaling? */
 1695                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1696                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1697                         tp->rcv_scale = tp->request_r_scale;
 1698                         tp->snd_wnd = tiwin;
 1699                 }
 1700                 /*
 1701                  * Make transitions:
 1702                  *      SYN-RECEIVED  -> ESTABLISHED
 1703                  *      SYN-RECEIVED* -> FIN-WAIT-1
 1704                  */
 1705                 tp->t_starttime = ticks;
 1706                 if (tp->t_flags & TF_NEEDFIN) {
 1707                         tp->t_state = TCPS_FIN_WAIT_1;
 1708                         tp->t_flags &= ~TF_NEEDFIN;
 1709                 } else {
 1710                         tp->t_state = TCPS_ESTABLISHED;
 1711                         tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
 1712                 }
 1713                 /*
 1714                  * If segment contains data or ACK, will call tcp_reass()
 1715                  * later; if not, do so now to pass queued data to user.
 1716                  */
 1717                 if (tlen == 0 && (thflags & TH_FIN) == 0)
 1718                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
 1719                             (struct mbuf *)0);
 1720                 tp->snd_wl1 = th->th_seq - 1;
 1721                 /* FALLTHROUGH */
 1722 
 1723         /*
 1724          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
 1725          * ACKs.  If the ack is in the range
 1726          *      tp->snd_una < th->th_ack <= tp->snd_max
 1727          * then advance tp->snd_una to th->th_ack and drop
 1728          * data from the retransmission queue.  If this ACK reflects
 1729          * more up to date window information we update our window information.
 1730          */
 1731         case TCPS_ESTABLISHED:
 1732         case TCPS_FIN_WAIT_1:
 1733         case TCPS_FIN_WAIT_2:
 1734         case TCPS_CLOSE_WAIT:
 1735         case TCPS_CLOSING:
 1736         case TCPS_LAST_ACK:
 1737                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
 1738                         tcpstat.tcps_rcvacktoomuch++;
 1739                         goto dropafterack;
 1740                 }
 1741                 if ((tp->t_flags & TF_SACK_PERMIT) &&
 1742                     ((to.to_flags & TOF_SACK) ||
 1743                      !TAILQ_EMPTY(&tp->snd_holes)))
 1744                         tcp_sack_doack(tp, &to, th->th_ack);
 1745                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
 1746                         if (tlen == 0 && tiwin == tp->snd_wnd) {
 1747                                 tcpstat.tcps_rcvdupack++;
 1748                                 /*
 1749                                  * If we have outstanding data (other than
 1750                                  * a window probe), this is a completely
 1751                                  * duplicate ack (ie, window info didn't
 1752                                  * change), the ack is the biggest we've
 1753                                  * seen and we've seen exactly our rexmt
 1754                                  * threshhold of them, assume a packet
 1755                                  * has been dropped and retransmit it.
 1756                                  * Kludge snd_nxt & the congestion
 1757                                  * window so we send only this one
 1758                                  * packet.
 1759                                  *
 1760                                  * We know we're losing at the current
 1761                                  * window size so do congestion avoidance
 1762                                  * (set ssthresh to half the current window
 1763                                  * and pull our congestion window back to
 1764                                  * the new ssthresh).
 1765                                  *
 1766                                  * Dup acks mean that packets have left the
 1767                                  * network (they're now cached at the receiver)
 1768                                  * so bump cwnd by the amount in the receiver
 1769                                  * to keep a constant cwnd packets in the
 1770                                  * network.
 1771                                  */
 1772                                 if (!tcp_timer_active(tp, TT_REXMT) ||
 1773                                     th->th_ack != tp->snd_una)
 1774                                         tp->t_dupacks = 0;
 1775                                 else if (++tp->t_dupacks > tcprexmtthresh ||
 1776                                     ((tcp_do_newreno ||
 1777                                       (tp->t_flags & TF_SACK_PERMIT)) &&
 1778                                      IN_FASTRECOVERY(tp))) {
 1779                                         if ((tp->t_flags & TF_SACK_PERMIT) &&
 1780                                             IN_FASTRECOVERY(tp)) {
 1781                                                 int awnd;
 1782                                                 
 1783                                                 /*
 1784                                                  * Compute the amount of data in flight first.
 1785                                                  * We can inject new data into the pipe iff 
 1786                                                  * we have less than 1/2 the original window's  
 1787                                                  * worth of data in flight.
 1788                                                  */
 1789                                                 awnd = (tp->snd_nxt - tp->snd_fack) +
 1790                                                         tp->sackhint.sack_bytes_rexmit;
 1791                                                 if (awnd < tp->snd_ssthresh) {
 1792                                                         tp->snd_cwnd += tp->t_maxseg;
 1793                                                         if (tp->snd_cwnd > tp->snd_ssthresh)
 1794                                                                 tp->snd_cwnd = tp->snd_ssthresh;
 1795                                                 }
 1796                                         } else
 1797                                                 tp->snd_cwnd += tp->t_maxseg;
 1798                                         (void) tcp_output(tp);
 1799                                         goto drop;
 1800                                 } else if (tp->t_dupacks == tcprexmtthresh) {
 1801                                         tcp_seq onxt = tp->snd_nxt;
 1802                                         u_int win;
 1803 
 1804                                         /*
 1805                                          * If we're doing sack, check to
 1806                                          * see if we're already in sack
 1807                                          * recovery. If we're not doing sack,
 1808                                          * check to see if we're in newreno
 1809                                          * recovery.
 1810                                          */
 1811                                         if (tp->t_flags & TF_SACK_PERMIT) {
 1812                                                 if (IN_FASTRECOVERY(tp)) {
 1813                                                         tp->t_dupacks = 0;
 1814                                                         break;
 1815                                                 }
 1816                                         } else if (tcp_do_newreno) {
 1817                                                 if (SEQ_LEQ(th->th_ack,
 1818                                                     tp->snd_recover)) {
 1819                                                         tp->t_dupacks = 0;
 1820                                                         break;
 1821                                                 }
 1822                                         }
 1823                                         win = min(tp->snd_wnd, tp->snd_cwnd) /
 1824                                             2 / tp->t_maxseg;
 1825                                         if (win < 2)
 1826                                                 win = 2;
 1827                                         tp->snd_ssthresh = win * tp->t_maxseg;
 1828                                         ENTER_FASTRECOVERY(tp);
 1829                                         tp->snd_recover = tp->snd_max;
 1830                                         tcp_timer_activate(tp, TT_REXMT, 0);
 1831                                         tp->t_rtttime = 0;
 1832                                         if (tp->t_flags & TF_SACK_PERMIT) {
 1833                                                 tcpstat.tcps_sack_recovery_episode++;
 1834                                                 tp->sack_newdata = tp->snd_nxt;
 1835                                                 tp->snd_cwnd = tp->t_maxseg;
 1836                                                 (void) tcp_output(tp);
 1837                                                 goto drop;
 1838                                         }
 1839                                         tp->snd_nxt = th->th_ack;
 1840                                         tp->snd_cwnd = tp->t_maxseg;
 1841                                         (void) tcp_output(tp);
 1842                                         KASSERT(tp->snd_limited <= 2,
 1843                                             ("%s: tp->snd_limited too big",
 1844                                             __func__));
 1845                                         tp->snd_cwnd = tp->snd_ssthresh +
 1846                                              tp->t_maxseg *
 1847                                              (tp->t_dupacks - tp->snd_limited);
 1848                                         if (SEQ_GT(onxt, tp->snd_nxt))
 1849                                                 tp->snd_nxt = onxt;
 1850                                         goto drop;
 1851                                 } else if (tcp_do_rfc3042) {
 1852                                         u_long oldcwnd = tp->snd_cwnd;
 1853                                         tcp_seq oldsndmax = tp->snd_max;
 1854                                         u_int sent;
 1855 
 1856                                         KASSERT(tp->t_dupacks == 1 ||
 1857                                             tp->t_dupacks == 2,
 1858                                             ("%s: dupacks not 1 or 2",
 1859                                             __func__));
 1860                                         if (tp->t_dupacks == 1)
 1861                                                 tp->snd_limited = 0;
 1862                                         tp->snd_cwnd =
 1863                                             (tp->snd_nxt - tp->snd_una) +
 1864                                             (tp->t_dupacks - tp->snd_limited) *
 1865                                             tp->t_maxseg;
 1866                                         (void) tcp_output(tp);
 1867                                         sent = tp->snd_max - oldsndmax;
 1868                                         if (sent > tp->t_maxseg) {
 1869                                                 KASSERT((tp->t_dupacks == 2 &&
 1870                                                     tp->snd_limited == 0) ||
 1871                                                    (sent == tp->t_maxseg + 1 &&
 1872                                                     tp->t_flags & TF_SENTFIN),
 1873                                                     ("%s: sent too much",
 1874                                                     __func__));
 1875                                                 tp->snd_limited = 2;
 1876                                         } else if (sent > 0)
 1877                                                 ++tp->snd_limited;
 1878                                         tp->snd_cwnd = oldcwnd;
 1879                                         goto drop;
 1880                                 }
 1881                         } else
 1882                                 tp->t_dupacks = 0;
 1883                         break;
 1884                 }
 1885 
 1886                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
 1887                     ("%s: th_ack <= snd_una", __func__));
 1888 
 1889                 /*
 1890                  * If the congestion window was inflated to account
 1891                  * for the other side's cached packets, retract it.
 1892                  */
 1893                 if (tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
 1894                         if (IN_FASTRECOVERY(tp)) {
 1895                                 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
 1896                                         if (tp->t_flags & TF_SACK_PERMIT)
 1897                                                 tcp_sack_partialack(tp, th);
 1898                                         else
 1899                                                 tcp_newreno_partial_ack(tp, th);
 1900                                 } else {
 1901                                         /*
 1902                                          * Out of fast recovery.
 1903                                          * Window inflation should have left us
 1904                                          * with approximately snd_ssthresh
 1905                                          * outstanding data.
 1906                                          * But in case we would be inclined to
 1907                                          * send a burst, better to do it via
 1908                                          * the slow start mechanism.
 1909                                          */
 1910                                         if (SEQ_GT(th->th_ack +
 1911                                                         tp->snd_ssthresh,
 1912                                                    tp->snd_max))
 1913                                                 tp->snd_cwnd = tp->snd_max -
 1914                                                                 th->th_ack +
 1915                                                                 tp->t_maxseg;
 1916                                         else
 1917                                                 tp->snd_cwnd = tp->snd_ssthresh;
 1918                                 }
 1919                         }
 1920                 } else {
 1921                         if (tp->t_dupacks >= tcprexmtthresh &&
 1922                             tp->snd_cwnd > tp->snd_ssthresh)
 1923                                 tp->snd_cwnd = tp->snd_ssthresh;
 1924                 }
 1925                 tp->t_dupacks = 0;
 1926                 /*
 1927                  * If we reach this point, ACK is not a duplicate,
 1928                  *     i.e., it ACKs something we sent.
 1929                  */
 1930                 if (tp->t_flags & TF_NEEDSYN) {
 1931                         /*
 1932                          * T/TCP: Connection was half-synchronized, and our
 1933                          * SYN has been ACK'd (so connection is now fully
 1934                          * synchronized).  Go to non-starred state,
 1935                          * increment snd_una for ACK of SYN, and check if
 1936                          * we can do window scaling.
 1937                          */
 1938                         tp->t_flags &= ~TF_NEEDSYN;
 1939                         tp->snd_una++;
 1940                         /* Do window scaling? */
 1941                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 1942                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 1943                                 tp->rcv_scale = tp->request_r_scale;
 1944                                 /* Send window already scaled. */
 1945                         }
 1946                 }
 1947 
 1948 process_ACK:
 1949                 KASSERT(headlocked, ("%s: process_ACK: head not locked",
 1950                     __func__));
 1951                 INP_WLOCK_ASSERT(tp->t_inpcb);
 1952 
 1953                 acked = th->th_ack - tp->snd_una;
 1954                 tcpstat.tcps_rcvackpack++;
 1955                 tcpstat.tcps_rcvackbyte += acked;
 1956 
 1957                 /*
 1958                  * If we just performed our first retransmit, and the ACK
 1959                  * arrives within our recovery window, then it was a mistake
 1960                  * to do the retransmit in the first place.  Recover our
 1961                  * original cwnd and ssthresh, and proceed to transmit where
 1962                  * we left off.
 1963                  */
 1964                 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0) {
 1965                         ++tcpstat.tcps_sndrexmitbad;
 1966                         tp->snd_cwnd = tp->snd_cwnd_prev;
 1967                         tp->snd_ssthresh = tp->snd_ssthresh_prev;
 1968                         tp->snd_recover = tp->snd_recover_prev;
 1969                         if (tp->t_flags & TF_WASFRECOVERY)
 1970                                 ENTER_FASTRECOVERY(tp);
 1971                         tp->snd_nxt = tp->snd_max;
 1972                         tp->t_badrxtwin = 0;    /* XXX probably not required */
 1973                 }
 1974 
 1975                 /*
 1976                  * If we have a timestamp reply, update smoothed
 1977                  * round trip time.  If no timestamp is present but
 1978                  * transmit timer is running and timed sequence
 1979                  * number was acked, update smoothed round trip time.
 1980                  * Since we now have an rtt measurement, cancel the
 1981                  * timer backoff (cf., Phil Karn's retransmit alg.).
 1982                  * Recompute the initial retransmit timer.
 1983                  *
 1984                  * Some boxes send broken timestamp replies
 1985                  * during the SYN+ACK phase, ignore
 1986                  * timestamps of 0 or we could calculate a
 1987                  * huge RTT and blow up the retransmit timer.
 1988                  */
 1989                 if ((to.to_flags & TOF_TS) != 0 &&
 1990                     to.to_tsecr) {
 1991                         if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
 1992                                 tp->t_rttlow = ticks - to.to_tsecr;
 1993                         tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
 1994                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
 1995                         if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
 1996                                 tp->t_rttlow = ticks - tp->t_rtttime;
 1997                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
 1998                 }
 1999                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
 2000 
 2001                 /*
 2002                  * If all outstanding data is acked, stop retransmit
 2003                  * timer and remember to restart (more output or persist).
 2004                  * If there is more data to be acked, restart retransmit
 2005                  * timer, using current (possibly backed-off) value.
 2006                  */
 2007                 if (th->th_ack == tp->snd_max) {
 2008                         tcp_timer_activate(tp, TT_REXMT, 0);
 2009                         needoutput = 1;
 2010                 } else if (!tcp_timer_active(tp, TT_PERSIST))
 2011                         tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
 2012 
 2013                 /*
 2014                  * If no data (only SYN) was ACK'd,
 2015                  *    skip rest of ACK processing.
 2016                  */
 2017                 if (acked == 0)
 2018                         goto step6;
 2019 
 2020                 /*
 2021                  * When new data is acked, open the congestion window.
 2022                  * If the window gives us less than ssthresh packets
 2023                  * in flight, open exponentially (maxseg per packet).
 2024                  * Otherwise open linearly: maxseg per window
 2025                  * (maxseg^2 / cwnd per packet).
 2026                  * If cwnd > maxseg^2, fix the cwnd increment at 1 byte
 2027                  * to avoid capping cwnd (as suggested in RFC2581).
 2028                  */
 2029                 if ((!tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
 2030                     !IN_FASTRECOVERY(tp)) {
 2031                         u_int cw = tp->snd_cwnd;
 2032                         u_int incr = tp->t_maxseg;
 2033                         if (cw > tp->snd_ssthresh)
 2034                                 incr = max((incr * incr / cw), 1);
 2035                         tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
 2036                 }
 2037                 SOCKBUF_LOCK(&so->so_snd);
 2038                 if (acked > so->so_snd.sb_cc) {
 2039                         tp->snd_wnd -= so->so_snd.sb_cc;
 2040                         sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
 2041                         ourfinisacked = 1;
 2042                 } else {
 2043                         sbdrop_locked(&so->so_snd, acked);
 2044                         tp->snd_wnd -= acked;
 2045                         ourfinisacked = 0;
 2046                 }
 2047                 /* NB: sowwakeup_locked() does an implicit unlock. */
 2048                 sowwakeup_locked(so);
 2049                 /* Detect una wraparound. */
 2050                 if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
 2051                     !IN_FASTRECOVERY(tp) &&
 2052                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
 2053                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 2054                         tp->snd_recover = th->th_ack - 1;
 2055                 if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
 2056                     IN_FASTRECOVERY(tp) &&
 2057                     SEQ_GEQ(th->th_ack, tp->snd_recover))
 2058                         EXIT_FASTRECOVERY(tp);
 2059                 tp->snd_una = th->th_ack;
 2060                 if (tp->t_flags & TF_SACK_PERMIT) {
 2061                         if (SEQ_GT(tp->snd_una, tp->snd_recover))
 2062                                 tp->snd_recover = tp->snd_una;
 2063                 }
 2064                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
 2065                         tp->snd_nxt = tp->snd_una;
 2066 
 2067                 switch (tp->t_state) {
 2068 
 2069                 /*
 2070                  * In FIN_WAIT_1 STATE in addition to the processing
 2071                  * for the ESTABLISHED state if our FIN is now acknowledged
 2072                  * then enter FIN_WAIT_2.
 2073                  */
 2074                 case TCPS_FIN_WAIT_1:
 2075                         if (ourfinisacked) {
 2076                                 /*
 2077                                  * If we can't receive any more
 2078                                  * data, then closing user can proceed.
 2079                                  * Starting the timer is contrary to the
 2080                                  * specification, but if we don't get a FIN
 2081                                  * we'll hang forever.
 2082                                  *
 2083                                  * XXXjl:
 2084                                  * we should release the tp also, and use a
 2085                                  * compressed state.
 2086                                  */
 2087                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 2088                                         int timeout;
 2089 
 2090                                         soisdisconnected(so);
 2091                                         timeout = (tcp_fast_finwait2_recycle) ? 
 2092                                                 tcp_finwait2_timeout : tcp_maxidle;
 2093                                         tcp_timer_activate(tp, TT_2MSL, timeout);
 2094                                 }
 2095                                 tp->t_state = TCPS_FIN_WAIT_2;
 2096                         }
 2097                         break;
 2098 
 2099                 /*
 2100                  * In CLOSING STATE in addition to the processing for
 2101                  * the ESTABLISHED state if the ACK acknowledges our FIN
 2102                  * then enter the TIME-WAIT state, otherwise ignore
 2103                  * the segment.
 2104                  */
 2105                 case TCPS_CLOSING:
 2106                         if (ourfinisacked) {
 2107                                 KASSERT(headlocked, ("%s: process_ACK: "
 2108                                     "head not locked", __func__));
 2109                                 tcp_twstart(tp);
 2110                                 INP_INFO_WUNLOCK(&tcbinfo);
 2111                                 headlocked = 0;
 2112                                 m_freem(m);
 2113                                 return;
 2114                         }
 2115                         break;
 2116 
 2117                 /*
 2118                  * In LAST_ACK, we may still be waiting for data to drain
 2119                  * and/or to be acked, as well as for the ack of our FIN.
 2120                  * If our FIN is now acknowledged, delete the TCB,
 2121                  * enter the closed state and return.
 2122                  */
 2123                 case TCPS_LAST_ACK:
 2124                         if (ourfinisacked) {
 2125                                 KASSERT(headlocked, ("%s: process_ACK: "
 2126                                     "tcp_close: head not locked", __func__));
 2127                                 tp = tcp_close(tp);
 2128                                 goto drop;
 2129                         }
 2130                         break;
 2131                 }
 2132         }
 2133 
 2134 step6:
 2135         KASSERT(headlocked, ("%s: step6: head not locked", __func__));
 2136         INP_WLOCK_ASSERT(tp->t_inpcb);
 2137 
 2138         /*
 2139          * Update window information.
 2140          * Don't look at window if no ACK: TAC's send garbage on first SYN.
 2141          */
 2142         if ((thflags & TH_ACK) &&
 2143             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
 2144             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
 2145              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
 2146                 /* keep track of pure window updates */
 2147                 if (tlen == 0 &&
 2148                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
 2149                         tcpstat.tcps_rcvwinupd++;
 2150                 tp->snd_wnd = tiwin;
 2151                 tp->snd_wl1 = th->th_seq;
 2152                 tp->snd_wl2 = th->th_ack;
 2153                 if (tp->snd_wnd > tp->max_sndwnd)
 2154                         tp->max_sndwnd = tp->snd_wnd;
 2155                 needoutput = 1;
 2156         }
 2157 
 2158         /*
 2159          * Process segments with URG.
 2160          */
 2161         if ((thflags & TH_URG) && th->th_urp &&
 2162             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2163                 /*
 2164                  * This is a kludge, but if we receive and accept
 2165                  * random urgent pointers, we'll crash in
 2166                  * soreceive.  It's hard to imagine someone
 2167                  * actually wanting to send this much urgent data.
 2168                  */
 2169                 SOCKBUF_LOCK(&so->so_rcv);
 2170                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
 2171                         th->th_urp = 0;                 /* XXX */
 2172                         thflags &= ~TH_URG;             /* XXX */
 2173                         SOCKBUF_UNLOCK(&so->so_rcv);    /* XXX */
 2174                         goto dodata;                    /* XXX */
 2175                 }
 2176                 /*
 2177                  * If this segment advances the known urgent pointer,
 2178                  * then mark the data stream.  This should not happen
 2179                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
 2180                  * a FIN has been received from the remote side.
 2181                  * In these states we ignore the URG.
 2182                  *
 2183                  * According to RFC961 (Assigned Protocols),
 2184                  * the urgent pointer points to the last octet
 2185                  * of urgent data.  We continue, however,
 2186                  * to consider it to indicate the first octet
 2187                  * of data past the urgent section as the original
 2188                  * spec states (in one of two places).
 2189                  */
 2190                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
 2191                         tp->rcv_up = th->th_seq + th->th_urp;
 2192                         so->so_oobmark = so->so_rcv.sb_cc +
 2193                             (tp->rcv_up - tp->rcv_nxt) - 1;
 2194                         if (so->so_oobmark == 0)
 2195                                 so->so_rcv.sb_state |= SBS_RCVATMARK;
 2196                         sohasoutofband(so);
 2197                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
 2198                 }
 2199                 SOCKBUF_UNLOCK(&so->so_rcv);
 2200                 /*
 2201                  * Remove out of band data so doesn't get presented to user.
 2202                  * This can happen independent of advancing the URG pointer,
 2203                  * but if two URG's are pending at once, some out-of-band
 2204                  * data may creep in... ick.
 2205                  */
 2206                 if (th->th_urp <= (u_long)tlen &&
 2207                     !(so->so_options & SO_OOBINLINE)) {
 2208                         /* hdr drop is delayed */
 2209                         tcp_pulloutofband(so, th, m, drop_hdrlen);
 2210                 }
 2211         } else {
 2212                 /*
 2213                  * If no out of band data is expected,
 2214                  * pull receive urgent pointer along
 2215                  * with the receive window.
 2216                  */
 2217                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
 2218                         tp->rcv_up = tp->rcv_nxt;
 2219         }
 2220 dodata:                                                 /* XXX */
 2221         KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
 2222         INP_WLOCK_ASSERT(tp->t_inpcb);
 2223 
 2224         /*
 2225          * Process the segment text, merging it into the TCP sequencing queue,
 2226          * and arranging for acknowledgment of receipt if necessary.
 2227          * This process logically involves adjusting tp->rcv_wnd as data
 2228          * is presented to the user (this happens in tcp_usrreq.c,
 2229          * case PRU_RCVD).  If a FIN has already been received on this
 2230          * connection then we just ignore the text.
 2231          */
 2232         if ((tlen || (thflags & TH_FIN)) &&
 2233             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2234                 tcp_seq save_start = th->th_seq;
 2235                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 2236                 /*
 2237                  * Insert segment which includes th into TCP reassembly queue
 2238                  * with control block tp.  Set thflags to whether reassembly now
 2239                  * includes a segment with FIN.  This handles the common case
 2240                  * inline (segment is the next to be received on an established
 2241                  * connection, and the queue is empty), avoiding linkage into
 2242                  * and removal from the queue and repetition of various
 2243                  * conversions.
 2244                  * Set DELACK for segments received in order, but ack
 2245                  * immediately when segments are out of order (so
 2246                  * fast retransmit can work).
 2247                  */
 2248                 if (th->th_seq == tp->rcv_nxt &&
 2249                     LIST_EMPTY(&tp->t_segq) &&
 2250                     TCPS_HAVEESTABLISHED(tp->t_state)) {
 2251                         if (DELAY_ACK(tp))
 2252                                 tp->t_flags |= TF_DELACK;
 2253                         else
 2254                                 tp->t_flags |= TF_ACKNOW;
 2255                         tp->rcv_nxt += tlen;
 2256                         thflags = th->th_flags & TH_FIN;
 2257                         tcpstat.tcps_rcvpack++;
 2258                         tcpstat.tcps_rcvbyte += tlen;
 2259                         ND6_HINT(tp);
 2260                         SOCKBUF_LOCK(&so->so_rcv);
 2261                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
 2262                                 m_freem(m);
 2263                         else
 2264                                 sbappendstream_locked(&so->so_rcv, m);
 2265                         /* NB: sorwakeup_locked() does an implicit unlock. */
 2266                         sorwakeup_locked(so);
 2267                 } else {
 2268                         /*
 2269                          * XXX: Due to the header drop above "th" is
 2270                          * theoretically invalid by now.  Fortunately
 2271                          * m_adj() doesn't actually frees any mbufs
 2272                          * when trimming from the head.
 2273                          */
 2274                         thflags = tcp_reass(tp, th, &tlen, m);
 2275                         tp->t_flags |= TF_ACKNOW;
 2276                 }
 2277                 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
 2278                         tcp_update_sack_list(tp, save_start, save_start + tlen);
 2279 #if 0
 2280                 /*
 2281                  * Note the amount of data that peer has sent into
 2282                  * our window, in order to estimate the sender's
 2283                  * buffer size.
 2284                  * XXX: Unused.
 2285                  */
 2286                 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
 2287 #endif
 2288         } else {
 2289                 m_freem(m);
 2290                 thflags &= ~TH_FIN;
 2291         }
 2292 
 2293         /*
 2294          * If FIN is received ACK the FIN and let the user know
 2295          * that the connection is closing.
 2296          */
 2297         if (thflags & TH_FIN) {
 2298                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2299                         socantrcvmore(so);
 2300                         /*
 2301                          * If connection is half-synchronized
 2302                          * (ie NEEDSYN flag on) then delay ACK,
 2303                          * so it may be piggybacked when SYN is sent.
 2304                          * Otherwise, since we received a FIN then no
 2305                          * more input can be expected, send ACK now.
 2306                          */
 2307                         if (tp->t_flags & TF_NEEDSYN)
 2308                                 tp->t_flags |= TF_DELACK;
 2309                         else
 2310                                 tp->t_flags |= TF_ACKNOW;
 2311                         tp->rcv_nxt++;
 2312                 }
 2313                 switch (tp->t_state) {
 2314 
 2315                 /*
 2316                  * In SYN_RECEIVED and ESTABLISHED STATES
 2317                  * enter the CLOSE_WAIT state.
 2318                  */
 2319                 case TCPS_SYN_RECEIVED:
 2320                         tp->t_starttime = ticks;
 2321                         /* FALLTHROUGH */
 2322                 case TCPS_ESTABLISHED:
 2323                         tp->t_state = TCPS_CLOSE_WAIT;
 2324                         break;
 2325 
 2326                 /*
 2327                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
 2328                  * enter the CLOSING state.
 2329                  */
 2330                 case TCPS_FIN_WAIT_1:
 2331                         tp->t_state = TCPS_CLOSING;
 2332                         break;
 2333 
 2334                 /*
 2335                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
 2336                  * starting the time-wait timer, turning off the other
 2337                  * standard timers.
 2338                  */
 2339                 case TCPS_FIN_WAIT_2:
 2340                         KASSERT(headlocked == 1, ("%s: dodata: "
 2341                             "TCP_FIN_WAIT_2: head not locked", __func__));
 2342                         tcp_twstart(tp);
 2343                         INP_INFO_WUNLOCK(&tcbinfo);
 2344                         return;
 2345                 }
 2346         }
 2347         INP_INFO_WUNLOCK(&tcbinfo);
 2348         headlocked = 0;
 2349 #ifdef TCPDEBUG
 2350         if (so->so_options & SO_DEBUG)
 2351                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
 2352                           &tcp_savetcp, 0);
 2353 #endif
 2354 
 2355         /*
 2356          * Return any desired output.
 2357          */
 2358         if (needoutput || (tp->t_flags & TF_ACKNOW))
 2359                 (void) tcp_output(tp);
 2360 
 2361 check_delack:
 2362         KASSERT(headlocked == 0, ("%s: check_delack: head locked",
 2363             __func__));
 2364         INP_INFO_UNLOCK_ASSERT(&tcbinfo);
 2365         INP_WLOCK_ASSERT(tp->t_inpcb);
 2366         if (tp->t_flags & TF_DELACK) {
 2367                 tp->t_flags &= ~TF_DELACK;
 2368                 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
 2369         }
 2370         INP_WUNLOCK(tp->t_inpcb);
 2371         return;
 2372 
 2373 dropafterack:
 2374         KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
 2375         /*
 2376          * Generate an ACK dropping incoming segment if it occupies
 2377          * sequence space, where the ACK reflects our state.
 2378          *
 2379          * We can now skip the test for the RST flag since all
 2380          * paths to this code happen after packets containing
 2381          * RST have been dropped.
 2382          *
 2383          * In the SYN-RECEIVED state, don't send an ACK unless the
 2384          * segment we received passes the SYN-RECEIVED ACK test.
 2385          * If it fails send a RST.  This breaks the loop in the
 2386          * "LAND" DoS attack, and also prevents an ACK storm
 2387          * between two listening ports that have been sent forged
 2388          * SYN segments, each with the source address of the other.
 2389          */
 2390         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
 2391             (SEQ_GT(tp->snd_una, th->th_ack) ||
 2392              SEQ_GT(th->th_ack, tp->snd_max)) ) {
 2393                 rstreason = BANDLIM_RST_OPENPORT;
 2394                 goto dropwithreset;
 2395         }
 2396 #ifdef TCPDEBUG
 2397         if (so->so_options & SO_DEBUG)
 2398                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2399                           &tcp_savetcp, 0);
 2400 #endif
 2401         KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
 2402         INP_INFO_WUNLOCK(&tcbinfo);
 2403         tp->t_flags |= TF_ACKNOW;
 2404         (void) tcp_output(tp);
 2405         INP_WUNLOCK(tp->t_inpcb);
 2406         m_freem(m);
 2407         return;
 2408 
 2409 dropwithreset:
 2410         KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
 2411         INP_INFO_WUNLOCK(&tcbinfo);
 2412 
 2413         if (tp != NULL) {
 2414                 tcp_dropwithreset(m, th, tp, tlen, rstreason);
 2415                 INP_WUNLOCK(tp->t_inpcb);
 2416         } else
 2417                 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
 2418         return;
 2419 
 2420 drop:
 2421         /*
 2422          * Drop space held by incoming segment and return.
 2423          */
 2424 #ifdef TCPDEBUG
 2425         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
 2426                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 2427                           &tcp_savetcp, 0);
 2428 #endif
 2429         if (tp != NULL)
 2430                 INP_WUNLOCK(tp->t_inpcb);
 2431         if (headlocked)
 2432                 INP_INFO_WUNLOCK(&tcbinfo);
 2433         m_freem(m);
 2434 }
 2435 
 2436 /*
 2437  * Issue RST and make ACK acceptable to originator of segment.
 2438  * The mbuf must still include the original packet header.
 2439  * tp may be NULL.
 2440  */
 2441 static void
 2442 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
 2443     int tlen, int rstreason)
 2444 {
 2445         struct ip *ip;
 2446 #ifdef INET6
 2447         struct ip6_hdr *ip6;
 2448 #endif
 2449 
 2450         if (tp != NULL) {
 2451                 INP_WLOCK_ASSERT(tp->t_inpcb);
 2452         }
 2453 
 2454         /* Don't bother if destination was broadcast/multicast. */
 2455         if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
 2456                 goto drop;
 2457 #ifdef INET6
 2458         if (mtod(m, struct ip *)->ip_v == 6) {
 2459                 ip6 = mtod(m, struct ip6_hdr *);
 2460                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 2461                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
 2462                         goto drop;
 2463                 /* IPv6 anycast check is done at tcp6_input() */
 2464         } else
 2465 #endif
 2466         {
 2467                 ip = mtod(m, struct ip *);
 2468                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 2469                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 2470                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 2471                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
 2472                         goto drop;
 2473         }
 2474 
 2475         /* Perform bandwidth limiting. */
 2476         if (badport_bandlim(rstreason) < 0)
 2477                 goto drop;
 2478 
 2479         /* tcp_respond consumes the mbuf chain. */
 2480         if (th->th_flags & TH_ACK) {
 2481                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
 2482                     th->th_ack, TH_RST);
 2483         } else {
 2484                 if (th->th_flags & TH_SYN)
 2485                         tlen++;
 2486                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
 2487                     (tcp_seq)0, TH_RST|TH_ACK);
 2488         }
 2489         return;
 2490 drop:
 2491         m_freem(m);
 2492 }
 2493 
 2494 /*
 2495  * Parse TCP options and place in tcpopt.
 2496  */
 2497 static void
 2498 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
 2499 {
 2500         int opt, optlen;
 2501 
 2502         to->to_flags = 0;
 2503         for (; cnt > 0; cnt -= optlen, cp += optlen) {
 2504                 opt = cp[0];
 2505                 if (opt == TCPOPT_EOL)
 2506                         break;
 2507                 if (opt == TCPOPT_NOP)
 2508                         optlen = 1;
 2509                 else {
 2510                         if (cnt < 2)
 2511                                 break;
 2512                         optlen = cp[1];
 2513                         if (optlen < 2 || optlen > cnt)
 2514                                 break;
 2515                 }
 2516                 switch (opt) {
 2517                 case TCPOPT_MAXSEG:
 2518                         if (optlen != TCPOLEN_MAXSEG)
 2519                                 continue;
 2520                         if (!(flags & TO_SYN))
 2521                                 continue;
 2522                         to->to_flags |= TOF_MSS;
 2523                         bcopy((char *)cp + 2,
 2524                             (char *)&to->to_mss, sizeof(to->to_mss));
 2525                         to->to_mss = ntohs(to->to_mss);
 2526                         break;
 2527                 case TCPOPT_WINDOW:
 2528                         if (optlen != TCPOLEN_WINDOW)
 2529                                 continue;
 2530                         if (!(flags & TO_SYN))
 2531                                 continue;
 2532                         to->to_flags |= TOF_SCALE;
 2533                         to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
 2534                         break;
 2535                 case TCPOPT_TIMESTAMP:
 2536                         if (optlen != TCPOLEN_TIMESTAMP)
 2537                                 continue;
 2538                         to->to_flags |= TOF_TS;
 2539                         bcopy((char *)cp + 2,
 2540                             (char *)&to->to_tsval, sizeof(to->to_tsval));
 2541                         to->to_tsval = ntohl(to->to_tsval);
 2542                         bcopy((char *)cp + 6,
 2543                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
 2544                         to->to_tsecr = ntohl(to->to_tsecr);
 2545                         break;
 2546 #ifdef TCP_SIGNATURE
 2547                 /*
 2548                  * XXX In order to reply to a host which has set the
 2549                  * TCP_SIGNATURE option in its initial SYN, we have to
 2550                  * record the fact that the option was observed here
 2551                  * for the syncache code to perform the correct response.
 2552                  */
 2553                 case TCPOPT_SIGNATURE:
 2554                         if (optlen != TCPOLEN_SIGNATURE)
 2555                                 continue;
 2556                         to->to_flags |= TOF_SIGNATURE;
 2557                         to->to_signature = cp + 2;
 2558                         break;
 2559 #endif
 2560                 case TCPOPT_SACK_PERMITTED:
 2561                         if (optlen != TCPOLEN_SACK_PERMITTED)
 2562                                 continue;
 2563                         if (!(flags & TO_SYN))
 2564                                 continue;
 2565                         if (!tcp_do_sack)
 2566                                 continue;
 2567                         to->to_flags |= TOF_SACKPERM;
 2568                         break;
 2569                 case TCPOPT_SACK:
 2570                         if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
 2571                                 continue;
 2572                         if (flags & TO_SYN)
 2573                                 continue;
 2574                         to->to_flags |= TOF_SACK;
 2575                         to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
 2576                         to->to_sacks = cp + 2;
 2577                         tcpstat.tcps_sack_rcv_blocks++;
 2578                         break;
 2579                 default:
 2580                         continue;
 2581                 }
 2582         }
 2583 }
 2584 
 2585 /*
 2586  * Pull out of band byte out of a segment so
 2587  * it doesn't appear in the user's data queue.
 2588  * It is still reflected in the segment length for
 2589  * sequencing purposes.
 2590  */
 2591 static void
 2592 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
 2593     int off)
 2594 {
 2595         int cnt = off + th->th_urp - 1;
 2596 
 2597         while (cnt >= 0) {
 2598                 if (m->m_len > cnt) {
 2599                         char *cp = mtod(m, caddr_t) + cnt;
 2600                         struct tcpcb *tp = sototcpcb(so);
 2601 
 2602                         INP_WLOCK_ASSERT(tp->t_inpcb);
 2603 
 2604                         tp->t_iobc = *cp;
 2605                         tp->t_oobflags |= TCPOOB_HAVEDATA;
 2606                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
 2607                         m->m_len--;
 2608                         if (m->m_flags & M_PKTHDR)
 2609                                 m->m_pkthdr.len--;
 2610                         return;
 2611                 }
 2612                 cnt -= m->m_len;
 2613                 m = m->m_next;
 2614                 if (m == NULL)
 2615                         break;
 2616         }
 2617         panic("tcp_pulloutofband");
 2618 }
 2619 
 2620 /*
 2621  * Collect new round-trip time estimate
 2622  * and update averages and current timeout.
 2623  */
 2624 static void
 2625 tcp_xmit_timer(struct tcpcb *tp, int rtt)
 2626 {
 2627         int delta;
 2628 
 2629         INP_WLOCK_ASSERT(tp->t_inpcb);
 2630 
 2631         tcpstat.tcps_rttupdated++;
 2632         tp->t_rttupdated++;
 2633         if (tp->t_srtt != 0) {
 2634                 /*
 2635                  * srtt is stored as fixed point with 5 bits after the
 2636                  * binary point (i.e., scaled by 8).  The following magic
 2637                  * is equivalent to the smoothing algorithm in rfc793 with
 2638                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
 2639                  * point).  Adjust rtt to origin 0.
 2640                  */
 2641                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
 2642                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
 2643 
 2644                 if ((tp->t_srtt += delta) <= 0)
 2645                         tp->t_srtt = 1;
 2646 
 2647                 /*
 2648                  * We accumulate a smoothed rtt variance (actually, a
 2649                  * smoothed mean difference), then set the retransmit
 2650                  * timer to smoothed rtt + 4 times the smoothed variance.
 2651                  * rttvar is stored as fixed point with 4 bits after the
 2652                  * binary point (scaled by 16).  The following is
 2653                  * equivalent to rfc793 smoothing with an alpha of .75
 2654                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
 2655                  * rfc793's wired-in beta.
 2656                  */
 2657                 if (delta < 0)
 2658                         delta = -delta;
 2659                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
 2660                 if ((tp->t_rttvar += delta) <= 0)
 2661                         tp->t_rttvar = 1;
 2662                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
 2663                     tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 2664         } else {
 2665                 /*
 2666                  * No rtt measurement yet - use the unsmoothed rtt.
 2667                  * Set the variance to half the rtt (so our first
 2668                  * retransmit happens at 3*rtt).
 2669                  */
 2670                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
 2671                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
 2672                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 2673         }
 2674         tp->t_rtttime = 0;
 2675         tp->t_rxtshift = 0;
 2676 
 2677         /*
 2678          * the retransmit should happen at rtt + 4 * rttvar.
 2679          * Because of the way we do the smoothing, srtt and rttvar
 2680          * will each average +1/2 tick of bias.  When we compute
 2681          * the retransmit timer, we want 1/2 tick of rounding and
 2682          * 1 extra tick because of +-1/2 tick uncertainty in the
 2683          * firing of the timer.  The bias will give us exactly the
 2684          * 1.5 tick we need.  But, because the bias is
 2685          * statistical, we have to test that we don't drop below
 2686          * the minimum feasible timer (which is 2 ticks).
 2687          */
 2688         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
 2689                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
 2690 
 2691         /*
 2692          * We received an ack for a packet that wasn't retransmitted;
 2693          * it is probably safe to discard any error indications we've
 2694          * received recently.  This isn't quite right, but close enough
 2695          * for now (a route might have failed after we sent a segment,
 2696          * and the return path might not be symmetrical).
 2697          */
 2698         tp->t_softerror = 0;
 2699 }
 2700 
 2701 /*
 2702  * Determine a reasonable value for maxseg size.
 2703  * If the route is known, check route for mtu.
 2704  * If none, use an mss that can be handled on the outgoing
 2705  * interface without forcing IP to fragment; if bigger than
 2706  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
 2707  * to utilize large mbufs.  If no route is found, route has no mtu,
 2708  * or the destination isn't local, use a default, hopefully conservative
 2709  * size (usually 512 or the default IP max size, but no more than the mtu
 2710  * of the interface), as we can't discover anything about intervening
 2711  * gateways or networks.  We also initialize the congestion/slow start
 2712  * window to be a single segment if the destination isn't local.
 2713  * While looking at the routing entry, we also initialize other path-dependent
 2714  * parameters from pre-set or cached values in the routing entry.
 2715  *
 2716  * Also take into account the space needed for options that we
 2717  * send regularly.  Make maxseg shorter by that amount to assure
 2718  * that we can send maxseg amount of data even when the options
 2719  * are present.  Store the upper limit of the length of options plus
 2720  * data in maxopd.
 2721  *
 2722  * In case of T/TCP, we call this routine during implicit connection
 2723  * setup as well (offer = -1), to initialize maxseg from the cached
 2724  * MSS of our peer.
 2725  *
 2726  * NOTE that this routine is only called when we process an incoming
 2727  * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
 2728  */
 2729 void
 2730 tcp_mss_update(struct tcpcb *tp, int offer,
 2731     struct hc_metrics_lite *metricptr, int *mtuflags)
 2732 {
 2733         int mss;
 2734         u_long maxmtu;
 2735         struct inpcb *inp = tp->t_inpcb;
 2736         struct hc_metrics_lite metrics;
 2737         int origoffer = offer;
 2738 #ifdef INET6
 2739         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
 2740         size_t min_protoh = isipv6 ?
 2741                             sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
 2742                             sizeof (struct tcpiphdr);
 2743 #else
 2744         const size_t min_protoh = sizeof(struct tcpiphdr);
 2745 #endif
 2746 
 2747         INP_WLOCK_ASSERT(tp->t_inpcb);
 2748 
 2749         /* Initialize. */
 2750 #ifdef INET6
 2751         if (isipv6) {
 2752                 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
 2753                 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
 2754         } else
 2755 #endif
 2756         {
 2757                 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
 2758                 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
 2759         }
 2760 
 2761         /*
 2762          * No route to sender, stay with default mss and return.
 2763          */
 2764         if (maxmtu == 0) {
 2765                 /*
 2766                  * In case we return early we need to initialize metrics
 2767                  * to a defined state as tcp_hc_get() would do for us
 2768                  * if there was no cache hit.
 2769                  */
 2770                 if (metricptr != NULL)
 2771                         bzero(metricptr, sizeof(struct hc_metrics_lite));
 2772                 return;
 2773         }
 2774 
 2775         /* What have we got? */
 2776         switch (offer) {
 2777                 case 0:
 2778                         /*
 2779                          * Offer == 0 means that there was no MSS on the SYN
 2780                          * segment, in this case we use tcp_mssdflt as
 2781                          * already assigned to t_maxopd above.
 2782                          */
 2783                         offer = tp->t_maxopd;
 2784                         break;
 2785 
 2786                 case -1:
 2787                         /*
 2788                          * Offer == -1 means that we didn't receive SYN yet.
 2789                          */
 2790                         /* FALLTHROUGH */
 2791 
 2792                 default:
 2793                         /*
 2794                          * Prevent DoS attack with too small MSS. Round up
 2795                          * to at least minmss.
 2796                          */
 2797                         offer = max(offer, tcp_minmss);
 2798         }
 2799 
 2800         /*
 2801          * rmx information is now retrieved from tcp_hostcache.
 2802          */
 2803         tcp_hc_get(&inp->inp_inc, &metrics);
 2804         if (metricptr != NULL)
 2805                 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
 2806 
 2807         /*
 2808          * If there's a discovered mtu int tcp hostcache, use it
 2809          * else, use the link mtu.
 2810          */
 2811         if (metrics.rmx_mtu)
 2812                 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
 2813         else {
 2814 #ifdef INET6
 2815                 if (isipv6) {
 2816                         mss = maxmtu - min_protoh;
 2817                         if (!path_mtu_discovery &&
 2818                             !in6_localaddr(&inp->in6p_faddr))
 2819                                 mss = min(mss, tcp_v6mssdflt);
 2820                 } else
 2821 #endif
 2822                 {
 2823                         mss = maxmtu - min_protoh;
 2824                         if (!path_mtu_discovery &&
 2825                             !in_localaddr(inp->inp_faddr))
 2826                                 mss = min(mss, tcp_mssdflt);
 2827                 }
 2828                 /*
 2829                  * XXX - The above conditional (mss = maxmtu - min_protoh)
 2830                  * probably violates the TCP spec.
 2831                  * The problem is that, since we don't know the
 2832                  * other end's MSS, we are supposed to use a conservative
 2833                  * default.  But, if we do that, then MTU discovery will
 2834                  * never actually take place, because the conservative
 2835                  * default is much less than the MTUs typically seen
 2836                  * on the Internet today.  For the moment, we'll sweep
 2837                  * this under the carpet.
 2838                  *
 2839                  * The conservative default might not actually be a problem
 2840                  * if the only case this occurs is when sending an initial
 2841                  * SYN with options and data to a host we've never talked
 2842                  * to before.  Then, they will reply with an MSS value which
 2843                  * will get recorded and the new parameters should get
 2844                  * recomputed.  For Further Study.
 2845                  */
 2846         }
 2847         mss = min(mss, offer);
 2848 
 2849         /*
 2850          * Sanity check: make sure that maxopd will be large
 2851          * enough to allow some data on segments even if the
 2852          * all the option space is used (40bytes).  Otherwise
 2853          * funny things may happen in tcp_output.
 2854          */
 2855         mss = max(mss, 64);
 2856 
 2857         /*
 2858          * maxopd stores the maximum length of data AND options
 2859          * in a segment; maxseg is the amount of data in a normal
 2860          * segment.  We need to store this value (maxopd) apart
 2861          * from maxseg, because now every segment carries options
 2862          * and thus we normally have somewhat less data in segments.
 2863          */
 2864         tp->t_maxopd = mss;
 2865 
 2866         /*
 2867          * origoffer==-1 indicates that no segments were received yet.
 2868          * In this case we just guess.
 2869          */
 2870         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
 2871             (origoffer == -1 ||
 2872              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
 2873                 mss -= TCPOLEN_TSTAMP_APPA;
 2874 
 2875 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
 2876         if (mss > MCLBYTES)
 2877                 mss &= ~(MCLBYTES-1);
 2878 #else
 2879         if (mss > MCLBYTES)
 2880                 mss = mss / MCLBYTES * MCLBYTES;
 2881 #endif
 2882         tp->t_maxseg = mss;
 2883 }
 2884 
 2885 void
 2886 tcp_mss(struct tcpcb *tp, int offer)
 2887 {
 2888         int rtt, mss;
 2889         u_long bufsize;
 2890         struct inpcb *inp;
 2891         struct socket *so;
 2892         struct hc_metrics_lite metrics;
 2893         int mtuflags = 0;
 2894 #ifdef INET6
 2895         int isipv6;
 2896 #endif
 2897         KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
 2898         
 2899         tcp_mss_update(tp, offer, &metrics, &mtuflags);
 2900 
 2901         mss = tp->t_maxseg;
 2902         inp = tp->t_inpcb;
 2903 #ifdef INET6
 2904         isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
 2905 #endif
 2906 
 2907         /*
 2908          * If there's a pipesize, change the socket buffer to that size,
 2909          * don't change if sb_hiwat is different than default (then it
 2910          * has been changed on purpose with setsockopt).
 2911          * Make the socket buffers an integral number of mss units;
 2912          * if the mss is larger than the socket buffer, decrease the mss.
 2913          */
 2914         so = inp->inp_socket;
 2915         SOCKBUF_LOCK(&so->so_snd);
 2916         if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
 2917                 bufsize = metrics.rmx_sendpipe;
 2918         else
 2919                 bufsize = so->so_snd.sb_hiwat;
 2920         if (bufsize < mss)
 2921                 mss = bufsize;
 2922         else {
 2923                 bufsize = roundup(bufsize, mss);
 2924                 if (bufsize > sb_max)
 2925                         bufsize = sb_max;
 2926                 if (bufsize > so->so_snd.sb_hiwat)
 2927                         (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
 2928         }
 2929         SOCKBUF_UNLOCK(&so->so_snd);
 2930         tp->t_maxseg = mss;
 2931 
 2932         SOCKBUF_LOCK(&so->so_rcv);
 2933         if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
 2934                 bufsize = metrics.rmx_recvpipe;
 2935         else
 2936                 bufsize = so->so_rcv.sb_hiwat;
 2937         if (bufsize > mss) {
 2938                 bufsize = roundup(bufsize, mss);
 2939                 if (bufsize > sb_max)
 2940                         bufsize = sb_max;
 2941                 if (bufsize > so->so_rcv.sb_hiwat)
 2942                         (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
 2943         }
 2944         SOCKBUF_UNLOCK(&so->so_rcv);
 2945         /*
 2946          * While we're here, check the others too.
 2947          */
 2948         if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
 2949                 tp->t_srtt = rtt;
 2950                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
 2951                 tcpstat.tcps_usedrtt++;
 2952                 if (metrics.rmx_rttvar) {
 2953                         tp->t_rttvar = metrics.rmx_rttvar;
 2954                         tcpstat.tcps_usedrttvar++;
 2955                 } else {
 2956                         /* default variation is +- 1 rtt */
 2957                         tp->t_rttvar =
 2958                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
 2959                 }
 2960                 TCPT_RANGESET(tp->t_rxtcur,
 2961                               ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
 2962                               tp->t_rttmin, TCPTV_REXMTMAX);
 2963         }
 2964         if (metrics.rmx_ssthresh) {
 2965                 /*
 2966                  * There's some sort of gateway or interface
 2967                  * buffer limit on the path.  Use this to set
 2968                  * the slow start threshhold, but set the
 2969                  * threshold to no less than 2*mss.
 2970                  */
 2971                 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
 2972                 tcpstat.tcps_usedssthresh++;
 2973         }
 2974         if (metrics.rmx_bandwidth)
 2975                 tp->snd_bandwidth = metrics.rmx_bandwidth;
 2976 
 2977         /*
 2978          * Set the slow-start flight size depending on whether this
 2979          * is a local network or not.
 2980          *
 2981          * Extend this so we cache the cwnd too and retrieve it here.
 2982          * Make cwnd even bigger than RFC3390 suggests but only if we
 2983          * have previous experience with the remote host. Be careful
 2984          * not make cwnd bigger than remote receive window or our own
 2985          * send socket buffer. Maybe put some additional upper bound
 2986          * on the retrieved cwnd. Should do incremental updates to
 2987          * hostcache when cwnd collapses so next connection doesn't
 2988          * overloads the path again.
 2989          *
 2990          * XXXAO: Initializing the CWND from the hostcache is broken
 2991          * and in its current form not RFC conformant.  It is disabled
 2992          * until fixed or removed entirely.
 2993          *
 2994          * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
 2995          * We currently check only in syncache_socket for that.
 2996          */
 2997 /* #define TCP_METRICS_CWND */
 2998 #ifdef TCP_METRICS_CWND
 2999         if (metrics.rmx_cwnd)
 3000                 tp->snd_cwnd = max(mss,
 3001                                 min(metrics.rmx_cwnd / 2,
 3002                                  min(tp->snd_wnd, so->so_snd.sb_hiwat)));
 3003         else
 3004 #endif
 3005         if (tcp_do_rfc3390)
 3006                 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
 3007 #ifdef INET6
 3008         else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
 3009                  (!isipv6 && in_localaddr(inp->inp_faddr)))
 3010 #else
 3011         else if (in_localaddr(inp->inp_faddr))
 3012 #endif
 3013                 tp->snd_cwnd = mss * ss_fltsz_local;
 3014         else
 3015                 tp->snd_cwnd = mss * ss_fltsz;
 3016 
 3017         /* Check the interface for TSO capabilities. */
 3018         if (mtuflags & CSUM_TSO)
 3019                 tp->t_flags |= TF_TSO;
 3020 }
 3021 
 3022 /*
 3023  * Determine the MSS option to send on an outgoing SYN.
 3024  */
 3025 int
 3026 tcp_mssopt(struct in_conninfo *inc)
 3027 {
 3028         int mss = 0;
 3029         u_long maxmtu = 0;
 3030         u_long thcmtu = 0;
 3031         size_t min_protoh;
 3032 
 3033         KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
 3034 
 3035 #ifdef INET6
 3036         if (inc->inc_flags & INC_ISIPV6) {
 3037                 mss = tcp_v6mssdflt;
 3038                 maxmtu = tcp_maxmtu6(inc, NULL);
 3039                 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3040                 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
 3041         } else
 3042 #endif
 3043         {
 3044                 mss = tcp_mssdflt;
 3045                 maxmtu = tcp_maxmtu(inc, NULL);
 3046                 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3047                 min_protoh = sizeof(struct tcpiphdr);
 3048         }
 3049         if (maxmtu && thcmtu)
 3050                 mss = min(maxmtu, thcmtu) - min_protoh;
 3051         else if (maxmtu || thcmtu)
 3052                 mss = max(maxmtu, thcmtu) - min_protoh;
 3053 
 3054         return (mss);
 3055 }
 3056 
 3057 
 3058 /*
 3059  * On a partial ack arrives, force the retransmission of the
 3060  * next unacknowledged segment.  Do not clear tp->t_dupacks.
 3061  * By setting snd_nxt to ti_ack, this forces retransmission timer to
 3062  * be started again.
 3063  */
 3064 static void
 3065 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
 3066 {
 3067         tcp_seq onxt = tp->snd_nxt;
 3068         u_long  ocwnd = tp->snd_cwnd;
 3069 
 3070         INP_WLOCK_ASSERT(tp->t_inpcb);
 3071 
 3072         tcp_timer_activate(tp, TT_REXMT, 0);
 3073         tp->t_rtttime = 0;
 3074         tp->snd_nxt = th->th_ack;
 3075         /*
 3076          * Set snd_cwnd to one segment beyond acknowledged offset.
 3077          * (tp->snd_una has not yet been updated when this function is called.)
 3078          */
 3079         tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
 3080         tp->t_flags |= TF_ACKNOW;
 3081         (void) tcp_output(tp);
 3082         tp->snd_cwnd = ocwnd;
 3083         if (SEQ_GT(onxt, tp->snd_nxt))
 3084                 tp->snd_nxt = onxt;
 3085         /*
 3086          * Partial window deflation.  Relies on fact that tp->snd_una
 3087          * not updated yet.
 3088          */
 3089         if (tp->snd_cwnd > th->th_ack - tp->snd_una)
 3090                 tp->snd_cwnd -= th->th_ack - tp->snd_una;
 3091         else
 3092                 tp->snd_cwnd = 0;
 3093         tp->snd_cwnd += tp->t_maxseg;
 3094 }

Cache object: 43d65bb88d06f53ad25543f99d666b31


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