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  -  FREEBSD10  -  FREEBSD9  -  FREEBSD92  -  FREEBSD91  -  FREEBSD90  -  FREEBSD8  -  FREEBSD82  -  FREEBSD81  -  FREEBSD80  -  FREEBSD7  -  FREEBSD74  -  FREEBSD73  -  FREEBSD72  -  FREEBSD71  -  FREEBSD70  -  FREEBSD6  -  FREEBSD64  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
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  * Copyright (c) 2007-2008,2010
    5  *      Swinburne University of Technology, Melbourne, Australia.
    6  * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
    7  * Copyright (c) 2010 The FreeBSD Foundation
    8  * Copyright (c) 2010-2011 Juniper Networks, Inc.
    9  * All rights reserved.
   10  *
   11  * Portions of this software were developed at the Centre for Advanced Internet
   12  * Architectures, Swinburne University of Technology, by Lawrence Stewart,
   13  * James Healy and David Hayes, made possible in part by a grant from the Cisco
   14  * University Research Program Fund at Community Foundation Silicon Valley.
   15  *
   16  * Portions of this software were developed at the Centre for Advanced
   17  * Internet Architectures, Swinburne University of Technology, Melbourne,
   18  * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
   19  *
   20  * Portions of this software were developed by Robert N. M. Watson under
   21  * contract to Juniper Networks, Inc.
   22  *
   23  * Redistribution and use in source and binary forms, with or without
   24  * modification, are permitted provided that the following conditions
   25  * are met:
   26  * 1. Redistributions of source code must retain the above copyright
   27  *    notice, this list of conditions and the following disclaimer.
   28  * 2. Redistributions in binary form must reproduce the above copyright
   29  *    notice, this list of conditions and the following disclaimer in the
   30  *    documentation and/or other materials provided with the distribution.
   31  * 4. Neither the name of the University nor the names of its contributors
   32  *    may be used to endorse or promote products derived from this software
   33  *    without specific prior written permission.
   34  *
   35  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   36  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   38  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   39  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   40  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   41  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   43  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   44  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   45  * SUCH DAMAGE.
   46  *
   47  *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
   48  */
   49 
   50 #include <sys/cdefs.h>
   51 __FBSDID("$FreeBSD: head/sys/netinet/tcp_input.c 294931 2016-01-27 17:59:39Z glebius $");
   52 
   53 #include "opt_ipfw.h"           /* for ipfw_fwd */
   54 #include "opt_inet.h"
   55 #include "opt_inet6.h"
   56 #include "opt_ipsec.h"
   57 #include "opt_tcpdebug.h"
   58 
   59 #include <sys/param.h>
   60 #include <sys/kernel.h>
   61 #include <sys/hhook.h>
   62 #include <sys/malloc.h>
   63 #include <sys/mbuf.h>
   64 #include <sys/proc.h>           /* for proc0 declaration */
   65 #include <sys/protosw.h>
   66 #include <sys/sdt.h>
   67 #include <sys/signalvar.h>
   68 #include <sys/socket.h>
   69 #include <sys/socketvar.h>
   70 #include <sys/sysctl.h>
   71 #include <sys/syslog.h>
   72 #include <sys/systm.h>
   73 
   74 #include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
   75 
   76 #include <vm/uma.h>
   77 
   78 #include <net/if.h>
   79 #include <net/if_var.h>
   80 #include <net/route.h>
   81 #include <net/vnet.h>
   82 
   83 #define TCPSTATES               /* for logging */
   84 
   85 #include <netinet/in.h>
   86 #include <netinet/in_kdtrace.h>
   87 #include <netinet/in_pcb.h>
   88 #include <netinet/in_systm.h>
   89 #include <netinet/ip.h>
   90 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
   91 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
   92 #include <netinet/ip_var.h>
   93 #include <netinet/ip_options.h>
   94 #include <netinet/ip6.h>
   95 #include <netinet/icmp6.h>
   96 #include <netinet6/in6_pcb.h>
   97 #include <netinet6/in6_var.h>
   98 #include <netinet6/ip6_var.h>
   99 #include <netinet6/nd6.h>
  100 #ifdef TCP_RFC7413
  101 #include <netinet/tcp_fastopen.h>
  102 #endif
  103 #include <netinet/tcp.h>
  104 #include <netinet/tcp_fsm.h>
  105 #include <netinet/tcp_seq.h>
  106 #include <netinet/tcp_timer.h>
  107 #include <netinet/tcp_var.h>
  108 #include <netinet6/tcp6_var.h>
  109 #include <netinet/tcpip.h>
  110 #include <netinet/cc/cc.h>
  111 #ifdef TCPPCAP
  112 #include <netinet/tcp_pcap.h>
  113 #endif
  114 #include <netinet/tcp_syncache.h>
  115 #ifdef TCPDEBUG
  116 #include <netinet/tcp_debug.h>
  117 #endif /* TCPDEBUG */
  118 #ifdef TCP_OFFLOAD
  119 #include <netinet/tcp_offload.h>
  120 #endif
  121 
  122 #ifdef IPSEC
  123 #include <netipsec/ipsec.h>
  124 #include <netipsec/ipsec6.h>
  125 #endif /*IPSEC*/
  126 
  127 #include <machine/in_cksum.h>
  128 
  129 #include <security/mac/mac_framework.h>
  130 
  131 const int tcprexmtthresh = 3;
  132 
  133 int tcp_log_in_vain = 0;
  134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
  135     &tcp_log_in_vain, 0,
  136     "Log all incoming TCP segments to closed ports");
  137 
  138 VNET_DEFINE(int, blackhole) = 0;
  139 #define V_blackhole             VNET(blackhole)
  140 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
  141     &VNET_NAME(blackhole), 0,
  142     "Do not send RST on segments to closed ports");
  143 
  144 VNET_DEFINE(int, tcp_delack_enabled) = 1;
  145 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
  146     &VNET_NAME(tcp_delack_enabled), 0,
  147     "Delay ACK to try and piggyback it onto a data packet");
  148 
  149 VNET_DEFINE(int, drop_synfin) = 0;
  150 #define V_drop_synfin           VNET(drop_synfin)
  151 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
  152     &VNET_NAME(drop_synfin), 0,
  153     "Drop TCP packets with SYN+FIN set");
  154 
  155 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
  156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_pipe, CTLFLAG_VNET | CTLFLAG_RW,
  157     &VNET_NAME(tcp_do_rfc6675_pipe), 0,
  158     "Use calculated pipe/in-flight bytes per RFC 6675");
  159 
  160 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
  161 #define V_tcp_do_rfc3042        VNET(tcp_do_rfc3042)
  162 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
  163     &VNET_NAME(tcp_do_rfc3042), 0,
  164     "Enable RFC 3042 (Limited Transmit)");
  165 
  166 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
  167 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
  168     &VNET_NAME(tcp_do_rfc3390), 0,
  169     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
  170 
  171 VNET_DEFINE(int, tcp_initcwnd_segments) = 10;
  172 SYSCTL_INT(_net_inet_tcp, OID_AUTO, initcwnd_segments,
  173     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_initcwnd_segments), 0,
  174     "Slow-start flight size (initial congestion window) in number of segments");
  175 
  176 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
  177 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
  178     &VNET_NAME(tcp_do_rfc3465), 0,
  179     "Enable RFC 3465 (Appropriate Byte Counting)");
  180 
  181 VNET_DEFINE(int, tcp_abc_l_var) = 2;
  182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
  183     &VNET_NAME(tcp_abc_l_var), 2,
  184     "Cap the max cwnd increment during slow-start to this number of segments");
  185 
  186 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
  187 
  188 VNET_DEFINE(int, tcp_do_ecn) = 0;
  189 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
  190     &VNET_NAME(tcp_do_ecn), 0,
  191     "TCP ECN support");
  192 
  193 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
  194 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
  195     &VNET_NAME(tcp_ecn_maxretries), 0,
  196     "Max retries before giving up on ECN");
  197 
  198 VNET_DEFINE(int, tcp_insecure_syn) = 0;
  199 #define V_tcp_insecure_syn      VNET(tcp_insecure_syn)
  200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
  201     &VNET_NAME(tcp_insecure_syn), 0,
  202     "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
  203 
  204 VNET_DEFINE(int, tcp_insecure_rst) = 0;
  205 #define V_tcp_insecure_rst      VNET(tcp_insecure_rst)
  206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
  207     &VNET_NAME(tcp_insecure_rst), 0,
  208     "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
  209 
  210 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
  211 #define V_tcp_recvspace VNET(tcp_recvspace)
  212 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
  213     &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
  214 
  215 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
  216 #define V_tcp_do_autorcvbuf     VNET(tcp_do_autorcvbuf)
  217 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
  218     &VNET_NAME(tcp_do_autorcvbuf), 0,
  219     "Enable automatic receive buffer sizing");
  220 
  221 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
  222 #define V_tcp_autorcvbuf_inc    VNET(tcp_autorcvbuf_inc)
  223 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
  224     &VNET_NAME(tcp_autorcvbuf_inc), 0,
  225     "Incrementor step size of automatic receive buffer");
  226 
  227 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
  228 #define V_tcp_autorcvbuf_max    VNET(tcp_autorcvbuf_max)
  229 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
  230     &VNET_NAME(tcp_autorcvbuf_max), 0,
  231     "Max size of automatic receive buffer");
  232 
  233 VNET_DEFINE(struct inpcbhead, tcb);
  234 #define tcb6    tcb  /* for KAME src sync over BSD*'s */
  235 VNET_DEFINE(struct inpcbinfo, tcbinfo);
  236 
  237 /*
  238  * TCP statistics are stored in an "array" of counter(9)s.
  239  */
  240 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
  241 VNET_PCPUSTAT_SYSINIT(tcpstat);
  242 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
  243     tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
  244 
  245 #ifdef VIMAGE
  246 VNET_PCPUSTAT_SYSUNINIT(tcpstat);
  247 #endif /* VIMAGE */
  248 /*
  249  * Kernel module interface for updating tcpstat.  The argument is an index
  250  * into tcpstat treated as an array.
  251  */
  252 void
  253 kmod_tcpstat_inc(int statnum)
  254 {
  255 
  256         counter_u64_add(VNET(tcpstat)[statnum], 1);
  257 }
  258 
  259 /*
  260  * Wrapper for the TCP established input helper hook.
  261  */
  262 void
  263 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
  264 {
  265         struct tcp_hhook_data hhook_data;
  266 
  267         if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
  268                 hhook_data.tp = tp;
  269                 hhook_data.th = th;
  270                 hhook_data.to = to;
  271 
  272                 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
  273                     tp->osd);
  274         }
  275 }
  276 
  277 /*
  278  * CC wrapper hook functions
  279  */
  280 void
  281 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
  282 {
  283         INP_WLOCK_ASSERT(tp->t_inpcb);
  284 
  285         tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
  286         if (tp->snd_cwnd <= tp->snd_wnd)
  287                 tp->ccv->flags |= CCF_CWND_LIMITED;
  288         else
  289                 tp->ccv->flags &= ~CCF_CWND_LIMITED;
  290 
  291         if (type == CC_ACK) {
  292                 if (tp->snd_cwnd > tp->snd_ssthresh) {
  293                         tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
  294                              V_tcp_abc_l_var * tcp_maxseg(tp));
  295                         if (tp->t_bytes_acked >= tp->snd_cwnd) {
  296                                 tp->t_bytes_acked -= tp->snd_cwnd;
  297                                 tp->ccv->flags |= CCF_ABC_SENTAWND;
  298                         }
  299                 } else {
  300                                 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
  301                                 tp->t_bytes_acked = 0;
  302                 }
  303         }
  304 
  305         if (CC_ALGO(tp)->ack_received != NULL) {
  306                 /* XXXLAS: Find a way to live without this */
  307                 tp->ccv->curack = th->th_ack;
  308                 CC_ALGO(tp)->ack_received(tp->ccv, type);
  309         }
  310 }
  311 
  312 void 
  313 cc_conn_init(struct tcpcb *tp)
  314 {
  315         struct hc_metrics_lite metrics;
  316         struct inpcb *inp = tp->t_inpcb;
  317         u_int maxseg;
  318         int rtt;
  319 
  320         INP_WLOCK_ASSERT(tp->t_inpcb);
  321 
  322         tcp_hc_get(&inp->inp_inc, &metrics);
  323         maxseg = tcp_maxseg(tp);
  324 
  325         if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
  326                 tp->t_srtt = rtt;
  327                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
  328                 TCPSTAT_INC(tcps_usedrtt);
  329                 if (metrics.rmx_rttvar) {
  330                         tp->t_rttvar = metrics.rmx_rttvar;
  331                         TCPSTAT_INC(tcps_usedrttvar);
  332                 } else {
  333                         /* default variation is +- 1 rtt */
  334                         tp->t_rttvar =
  335                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
  336                 }
  337                 TCPT_RANGESET(tp->t_rxtcur,
  338                     ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
  339                     tp->t_rttmin, TCPTV_REXMTMAX);
  340         }
  341         if (metrics.rmx_ssthresh) {
  342                 /*
  343                  * There's some sort of gateway or interface
  344                  * buffer limit on the path.  Use this to set
  345                  * the slow start threshhold, but set the
  346                  * threshold to no less than 2*mss.
  347                  */
  348                 tp->snd_ssthresh = max(2 * maxseg, metrics.rmx_ssthresh);
  349                 TCPSTAT_INC(tcps_usedssthresh);
  350         }
  351 
  352         /*
  353          * Set the initial slow-start flight size.
  354          *
  355          * RFC5681 Section 3.1 specifies the default conservative values.
  356          * RFC3390 specifies slightly more aggressive values.
  357          * RFC6928 increases it to ten segments.
  358          * Support for user specified value for initial flight size.
  359          *
  360          * If a SYN or SYN/ACK was lost and retransmitted, we have to
  361          * reduce the initial CWND to one segment as congestion is likely
  362          * requiring us to be cautious.
  363          */
  364         if (tp->snd_cwnd == 1)
  365                 tp->snd_cwnd = maxseg;          /* SYN(-ACK) lost */
  366         else if (V_tcp_initcwnd_segments)
  367                 tp->snd_cwnd = min(V_tcp_initcwnd_segments * maxseg,
  368                     max(2 * maxseg, V_tcp_initcwnd_segments * 1460));
  369         else if (V_tcp_do_rfc3390)
  370                 tp->snd_cwnd = min(4 * maxseg, max(2 * maxseg, 4380));
  371         else {
  372                 /* Per RFC5681 Section 3.1 */
  373                 if (maxseg > 2190)
  374                         tp->snd_cwnd = 2 * maxseg;
  375                 else if (maxseg > 1095)
  376                         tp->snd_cwnd = 3 * maxseg;
  377                 else
  378                         tp->snd_cwnd = 4 * maxseg;
  379         }
  380 
  381         if (CC_ALGO(tp)->conn_init != NULL)
  382                 CC_ALGO(tp)->conn_init(tp->ccv);
  383 }
  384 
  385 void inline
  386 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
  387 {
  388         u_int maxseg;
  389 
  390         INP_WLOCK_ASSERT(tp->t_inpcb);
  391 
  392         switch(type) {
  393         case CC_NDUPACK:
  394                 if (!IN_FASTRECOVERY(tp->t_flags)) {
  395                         tp->snd_recover = tp->snd_max;
  396                         if (tp->t_flags & TF_ECN_PERMIT)
  397                                 tp->t_flags |= TF_ECN_SND_CWR;
  398                 }
  399                 break;
  400         case CC_ECN:
  401                 if (!IN_CONGRECOVERY(tp->t_flags)) {
  402                         TCPSTAT_INC(tcps_ecn_rcwnd);
  403                         tp->snd_recover = tp->snd_max;
  404                         if (tp->t_flags & TF_ECN_PERMIT)
  405                                 tp->t_flags |= TF_ECN_SND_CWR;
  406                 }
  407                 break;
  408         case CC_RTO:
  409                 maxseg = tcp_maxseg(tp);
  410                 tp->t_dupacks = 0;
  411                 tp->t_bytes_acked = 0;
  412                 EXIT_RECOVERY(tp->t_flags);
  413                 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
  414                     maxseg) * maxseg;
  415                 tp->snd_cwnd = maxseg;
  416                 break;
  417         case CC_RTO_ERR:
  418                 TCPSTAT_INC(tcps_sndrexmitbad);
  419                 /* RTO was unnecessary, so reset everything. */
  420                 tp->snd_cwnd = tp->snd_cwnd_prev;
  421                 tp->snd_ssthresh = tp->snd_ssthresh_prev;
  422                 tp->snd_recover = tp->snd_recover_prev;
  423                 if (tp->t_flags & TF_WASFRECOVERY)
  424                         ENTER_FASTRECOVERY(tp->t_flags);
  425                 if (tp->t_flags & TF_WASCRECOVERY)
  426                         ENTER_CONGRECOVERY(tp->t_flags);
  427                 tp->snd_nxt = tp->snd_max;
  428                 tp->t_flags &= ~TF_PREVVALID;
  429                 tp->t_badrxtwin = 0;
  430                 break;
  431         }
  432 
  433         if (CC_ALGO(tp)->cong_signal != NULL) {
  434                 if (th != NULL)
  435                         tp->ccv->curack = th->th_ack;
  436                 CC_ALGO(tp)->cong_signal(tp->ccv, type);
  437         }
  438 }
  439 
  440 void inline
  441 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
  442 {
  443         INP_WLOCK_ASSERT(tp->t_inpcb);
  444 
  445         /* XXXLAS: KASSERT that we're in recovery? */
  446 
  447         if (CC_ALGO(tp)->post_recovery != NULL) {
  448                 tp->ccv->curack = th->th_ack;
  449                 CC_ALGO(tp)->post_recovery(tp->ccv);
  450         }
  451         /* XXXLAS: EXIT_RECOVERY ? */
  452         tp->t_bytes_acked = 0;
  453 }
  454 
  455 #ifdef TCP_SIGNATURE
  456 static inline int
  457 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
  458     struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
  459 {
  460         int ret;
  461 
  462         tcp_fields_to_net(th);
  463         ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
  464         tcp_fields_to_host(th);
  465         return (ret);
  466 }
  467 #endif
  468 
  469 /*
  470  * Indicate whether this ack should be delayed.  We can delay the ack if
  471  * following conditions are met:
  472  *      - There is no delayed ack timer in progress.
  473  *      - Our last ack wasn't a 0-sized window. We never want to delay
  474  *        the ack that opens up a 0-sized window.
  475  *      - LRO wasn't used for this segment. We make sure by checking that the
  476  *        segment size is not larger than the MSS.
  477  */
  478 #define DELAY_ACK(tp, tlen)                                             \
  479         ((!tcp_timer_active(tp, TT_DELACK) &&                           \
  480             (tp->t_flags & TF_RXWIN0SENT) == 0) &&                      \
  481             (tlen <= tp->t_maxseg) &&                                   \
  482             (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
  483 
  484 static void inline
  485 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
  486 {
  487         INP_WLOCK_ASSERT(tp->t_inpcb);
  488 
  489         if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
  490                 switch (iptos & IPTOS_ECN_MASK) {
  491                 case IPTOS_ECN_CE:
  492                     tp->ccv->flags |= CCF_IPHDR_CE;
  493                     break;
  494                 case IPTOS_ECN_ECT0:
  495                     tp->ccv->flags &= ~CCF_IPHDR_CE;
  496                     break;
  497                 case IPTOS_ECN_ECT1:
  498                     tp->ccv->flags &= ~CCF_IPHDR_CE;
  499                     break;
  500                 }
  501 
  502                 if (th->th_flags & TH_CWR)
  503                         tp->ccv->flags |= CCF_TCPHDR_CWR;
  504                 else
  505                         tp->ccv->flags &= ~CCF_TCPHDR_CWR;
  506 
  507                 if (tp->t_flags & TF_DELACK)
  508                         tp->ccv->flags |= CCF_DELACK;
  509                 else
  510                         tp->ccv->flags &= ~CCF_DELACK;
  511 
  512                 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
  513 
  514                 if (tp->ccv->flags & CCF_ACKNOW)
  515                         tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
  516         }
  517 }
  518 
  519 /*
  520  * TCP input handling is split into multiple parts:
  521  *   tcp6_input is a thin wrapper around tcp_input for the extended
  522  *      ip6_protox[] call format in ip6_input
  523  *   tcp_input handles primary segment validation, inpcb lookup and
  524  *      SYN processing on listen sockets
  525  *   tcp_do_segment processes the ACK and text of the segment for
  526  *      establishing, established and closing connections
  527  */
  528 #ifdef INET6
  529 int
  530 tcp6_input(struct mbuf **mp, int *offp, int proto)
  531 {
  532         struct mbuf *m = *mp;
  533         struct in6_ifaddr *ia6;
  534         struct ip6_hdr *ip6;
  535 
  536         IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
  537 
  538         /*
  539          * draft-itojun-ipv6-tcp-to-anycast
  540          * better place to put this in?
  541          */
  542         ip6 = mtod(m, struct ip6_hdr *);
  543         ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
  544         if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
  545                 struct ip6_hdr *ip6;
  546 
  547                 ifa_free(&ia6->ia_ifa);
  548                 ip6 = mtod(m, struct ip6_hdr *);
  549                 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
  550                             (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
  551                 return (IPPROTO_DONE);
  552         }
  553         if (ia6)
  554                 ifa_free(&ia6->ia_ifa);
  555 
  556         return (tcp_input(mp, offp, proto));
  557 }
  558 #endif /* INET6 */
  559 
  560 int
  561 tcp_input(struct mbuf **mp, int *offp, int proto)
  562 {
  563         struct mbuf *m = *mp;
  564         struct tcphdr *th = NULL;
  565         struct ip *ip = NULL;
  566         struct inpcb *inp = NULL;
  567         struct tcpcb *tp = NULL;
  568         struct socket *so = NULL;
  569         u_char *optp = NULL;
  570         int off0;
  571         int optlen = 0;
  572 #ifdef INET
  573         int len;
  574 #endif
  575         int tlen = 0, off;
  576         int drop_hdrlen;
  577         int thflags;
  578         int rstreason = 0;      /* For badport_bandlim accounting purposes */
  579 #ifdef TCP_SIGNATURE
  580         uint8_t sig_checked = 0;
  581 #endif
  582         uint8_t iptos = 0;
  583         struct m_tag *fwd_tag = NULL;
  584 #ifdef INET6
  585         struct ip6_hdr *ip6 = NULL;
  586         int isipv6;
  587 #else
  588         const void *ip6 = NULL;
  589 #endif /* INET6 */
  590         struct tcpopt to;               /* options in this segment */
  591         char *s = NULL;                 /* address and port logging */
  592         int ti_locked;
  593 #ifdef TCPDEBUG
  594         /*
  595          * The size of tcp_saveipgen must be the size of the max ip header,
  596          * now IPv6.
  597          */
  598         u_char tcp_saveipgen[IP6_HDR_LEN];
  599         struct tcphdr tcp_savetcp;
  600         short ostate = 0;
  601 #endif
  602 
  603 #ifdef INET6
  604         isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
  605 #endif
  606 
  607         off0 = *offp;
  608         m = *mp;
  609         *mp = NULL;
  610         to.to_flags = 0;
  611         TCPSTAT_INC(tcps_rcvtotal);
  612 
  613 #ifdef INET6
  614         if (isipv6) {
  615                 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
  616 
  617                 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
  618                         m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
  619                         if (m == NULL) {
  620                                 TCPSTAT_INC(tcps_rcvshort);
  621                                 return (IPPROTO_DONE);
  622                         }
  623                 }
  624 
  625                 ip6 = mtod(m, struct ip6_hdr *);
  626                 th = (struct tcphdr *)((caddr_t)ip6 + off0);
  627                 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
  628                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
  629                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
  630                                 th->th_sum = m->m_pkthdr.csum_data;
  631                         else
  632                                 th->th_sum = in6_cksum_pseudo(ip6, tlen,
  633                                     IPPROTO_TCP, m->m_pkthdr.csum_data);
  634                         th->th_sum ^= 0xffff;
  635                 } else
  636                         th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
  637                 if (th->th_sum) {
  638                         TCPSTAT_INC(tcps_rcvbadsum);
  639                         goto drop;
  640                 }
  641 
  642                 /*
  643                  * Be proactive about unspecified IPv6 address in source.
  644                  * As we use all-zero to indicate unbounded/unconnected pcb,
  645                  * unspecified IPv6 address can be used to confuse us.
  646                  *
  647                  * Note that packets with unspecified IPv6 destination is
  648                  * already dropped in ip6_input.
  649                  */
  650                 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
  651                         /* XXX stat */
  652                         goto drop;
  653                 }
  654         }
  655 #endif
  656 #if defined(INET) && defined(INET6)
  657         else
  658 #endif
  659 #ifdef INET
  660         {
  661                 /*
  662                  * Get IP and TCP header together in first mbuf.
  663                  * Note: IP leaves IP header in first mbuf.
  664                  */
  665                 if (off0 > sizeof (struct ip)) {
  666                         ip_stripoptions(m);
  667                         off0 = sizeof(struct ip);
  668                 }
  669                 if (m->m_len < sizeof (struct tcpiphdr)) {
  670                         if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
  671                             == NULL) {
  672                                 TCPSTAT_INC(tcps_rcvshort);
  673                                 return (IPPROTO_DONE);
  674                         }
  675                 }
  676                 ip = mtod(m, struct ip *);
  677                 th = (struct tcphdr *)((caddr_t)ip + off0);
  678                 tlen = ntohs(ip->ip_len) - off0;
  679 
  680                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
  681                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
  682                                 th->th_sum = m->m_pkthdr.csum_data;
  683                         else
  684                                 th->th_sum = in_pseudo(ip->ip_src.s_addr,
  685                                     ip->ip_dst.s_addr,
  686                                     htonl(m->m_pkthdr.csum_data + tlen +
  687                                     IPPROTO_TCP));
  688                         th->th_sum ^= 0xffff;
  689                 } else {
  690                         struct ipovly *ipov = (struct ipovly *)ip;
  691 
  692                         /*
  693                          * Checksum extended TCP header and data.
  694                          */
  695                         len = off0 + tlen;
  696                         bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
  697                         ipov->ih_len = htons(tlen);
  698                         th->th_sum = in_cksum(m, len);
  699                         /* Reset length for SDT probes. */
  700                         ip->ip_len = htons(tlen + off0);
  701                 }
  702 
  703                 if (th->th_sum) {
  704                         TCPSTAT_INC(tcps_rcvbadsum);
  705                         goto drop;
  706                 }
  707                 /* Re-initialization for later version check */
  708                 ip->ip_v = IPVERSION;
  709         }
  710 #endif /* INET */
  711 
  712 #ifdef INET6
  713         if (isipv6)
  714                 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
  715 #endif
  716 #if defined(INET) && defined(INET6)
  717         else
  718 #endif
  719 #ifdef INET
  720                 iptos = ip->ip_tos;
  721 #endif
  722 
  723         /*
  724          * Check that TCP offset makes sense,
  725          * pull out TCP options and adjust length.              XXX
  726          */
  727         off = th->th_off << 2;
  728         if (off < sizeof (struct tcphdr) || off > tlen) {
  729                 TCPSTAT_INC(tcps_rcvbadoff);
  730                 goto drop;
  731         }
  732         tlen -= off;    /* tlen is used instead of ti->ti_len */
  733         if (off > sizeof (struct tcphdr)) {
  734 #ifdef INET6
  735                 if (isipv6) {
  736                         IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
  737                         ip6 = mtod(m, struct ip6_hdr *);
  738                         th = (struct tcphdr *)((caddr_t)ip6 + off0);
  739                 }
  740 #endif
  741 #if defined(INET) && defined(INET6)
  742                 else
  743 #endif
  744 #ifdef INET
  745                 {
  746                         if (m->m_len < sizeof(struct ip) + off) {
  747                                 if ((m = m_pullup(m, sizeof (struct ip) + off))
  748                                     == NULL) {
  749                                         TCPSTAT_INC(tcps_rcvshort);
  750                                         return (IPPROTO_DONE);
  751                                 }
  752                                 ip = mtod(m, struct ip *);
  753                                 th = (struct tcphdr *)((caddr_t)ip + off0);
  754                         }
  755                 }
  756 #endif
  757                 optlen = off - sizeof (struct tcphdr);
  758                 optp = (u_char *)(th + 1);
  759         }
  760         thflags = th->th_flags;
  761 
  762         /*
  763          * Convert TCP protocol specific fields to host format.
  764          */
  765         tcp_fields_to_host(th);
  766 
  767         /*
  768          * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
  769          */
  770         drop_hdrlen = off0 + off;
  771 
  772         /*
  773          * Locate pcb for segment; if we're likely to add or remove a
  774          * connection then first acquire pcbinfo lock.  There are three cases
  775          * where we might discover later we need a write lock despite the
  776          * flags: ACKs moving a connection out of the syncache, ACKs for a
  777          * connection in TIMEWAIT and SYNs not targeting a listening socket.
  778          */
  779         if ((thflags & (TH_FIN | TH_RST)) != 0) {
  780                 INP_INFO_RLOCK(&V_tcbinfo);
  781                 ti_locked = TI_RLOCKED;
  782         } else
  783                 ti_locked = TI_UNLOCKED;
  784 
  785         /*
  786          * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
  787          */
  788         if (
  789 #ifdef INET6
  790             (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
  791 #ifdef INET
  792             || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
  793 #endif
  794 #endif
  795 #if defined(INET) && !defined(INET6)
  796             (m->m_flags & M_IP_NEXTHOP)
  797 #endif
  798             )
  799                 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
  800 
  801 findpcb:
  802 #ifdef INVARIANTS
  803         if (ti_locked == TI_RLOCKED) {
  804                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
  805         } else {
  806                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
  807         }
  808 #endif
  809 #ifdef INET6
  810         if (isipv6 && fwd_tag != NULL) {
  811                 struct sockaddr_in6 *next_hop6;
  812 
  813                 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
  814                 /*
  815                  * Transparently forwarded. Pretend to be the destination.
  816                  * Already got one like this?
  817                  */
  818                 inp = in6_pcblookup_mbuf(&V_tcbinfo,
  819                     &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
  820                     INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
  821                 if (!inp) {
  822                         /*
  823                          * It's new.  Try to find the ambushing socket.
  824                          * Because we've rewritten the destination address,
  825                          * any hardware-generated hash is ignored.
  826                          */
  827                         inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
  828                             th->th_sport, &next_hop6->sin6_addr,
  829                             next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
  830                             th->th_dport, INPLOOKUP_WILDCARD |
  831                             INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
  832                 }
  833         } else if (isipv6) {
  834                 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
  835                     th->th_sport, &ip6->ip6_dst, th->th_dport,
  836                     INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
  837                     m->m_pkthdr.rcvif, m);
  838         }
  839 #endif /* INET6 */
  840 #if defined(INET6) && defined(INET)
  841         else
  842 #endif
  843 #ifdef INET
  844         if (fwd_tag != NULL) {
  845                 struct sockaddr_in *next_hop;
  846 
  847                 next_hop = (struct sockaddr_in *)(fwd_tag+1);
  848                 /*
  849                  * Transparently forwarded. Pretend to be the destination.
  850                  * already got one like this?
  851                  */
  852                 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
  853                     ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
  854                     m->m_pkthdr.rcvif, m);
  855                 if (!inp) {
  856                         /*
  857                          * It's new.  Try to find the ambushing socket.
  858                          * Because we've rewritten the destination address,
  859                          * any hardware-generated hash is ignored.
  860                          */
  861                         inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
  862                             th->th_sport, next_hop->sin_addr,
  863                             next_hop->sin_port ? ntohs(next_hop->sin_port) :
  864                             th->th_dport, INPLOOKUP_WILDCARD |
  865                             INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
  866                 }
  867         } else
  868                 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
  869                     th->th_sport, ip->ip_dst, th->th_dport,
  870                     INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
  871                     m->m_pkthdr.rcvif, m);
  872 #endif /* INET */
  873 
  874         /*
  875          * If the INPCB does not exist then all data in the incoming
  876          * segment is discarded and an appropriate RST is sent back.
  877          * XXX MRT Send RST using which routing table?
  878          */
  879         if (inp == NULL) {
  880                 /*
  881                  * Log communication attempts to ports that are not
  882                  * in use.
  883                  */
  884                 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
  885                     tcp_log_in_vain == 2) {
  886                         if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
  887                                 log(LOG_INFO, "%s; %s: Connection attempt "
  888                                     "to closed port\n", s, __func__);
  889                 }
  890                 /*
  891                  * When blackholing do not respond with a RST but
  892                  * completely ignore the segment and drop it.
  893                  */
  894                 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
  895                     V_blackhole == 2)
  896                         goto dropunlock;
  897 
  898                 rstreason = BANDLIM_RST_CLOSEDPORT;
  899                 goto dropwithreset;
  900         }
  901         INP_WLOCK_ASSERT(inp);
  902         if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
  903             (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
  904             ((inp->inp_socket == NULL) ||
  905             (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
  906                 inp->inp_flowid = m->m_pkthdr.flowid;
  907                 inp->inp_flowtype = M_HASHTYPE_GET(m);
  908         }
  909 #ifdef IPSEC
  910 #ifdef INET6
  911         if (isipv6 && ipsec6_in_reject(m, inp)) {
  912                 goto dropunlock;
  913         } else
  914 #endif /* INET6 */
  915         if (ipsec4_in_reject(m, inp) != 0) {
  916                 goto dropunlock;
  917         }
  918 #endif /* IPSEC */
  919 
  920         /*
  921          * Check the minimum TTL for socket.
  922          */
  923         if (inp->inp_ip_minttl != 0) {
  924 #ifdef INET6
  925                 if (isipv6) {
  926                         if (inp->inp_ip_minttl > ip6->ip6_hlim)
  927                                 goto dropunlock;
  928                 } else
  929 #endif
  930                 if (inp->inp_ip_minttl > ip->ip_ttl)
  931                         goto dropunlock;
  932         }
  933 
  934         /*
  935          * A previous connection in TIMEWAIT state is supposed to catch stray
  936          * or duplicate segments arriving late.  If this segment was a
  937          * legitimate new connection attempt, the old INPCB gets removed and
  938          * we can try again to find a listening socket.
  939          *
  940          * At this point, due to earlier optimism, we may hold only an inpcb
  941          * lock, and not the inpcbinfo write lock.  If so, we need to try to
  942          * acquire it, or if that fails, acquire a reference on the inpcb,
  943          * drop all locks, acquire a global write lock, and then re-acquire
  944          * the inpcb lock.  We may at that point discover that another thread
  945          * has tried to free the inpcb, in which case we need to loop back
  946          * and try to find a new inpcb to deliver to.
  947          *
  948          * XXXRW: It may be time to rethink timewait locking.
  949          */
  950 relocked:
  951         if (inp->inp_flags & INP_TIMEWAIT) {
  952                 if (ti_locked == TI_UNLOCKED) {
  953                         if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
  954                                 in_pcbref(inp);
  955                                 INP_WUNLOCK(inp);
  956                                 INP_INFO_RLOCK(&V_tcbinfo);
  957                                 ti_locked = TI_RLOCKED;
  958                                 INP_WLOCK(inp);
  959                                 if (in_pcbrele_wlocked(inp)) {
  960                                         inp = NULL;
  961                                         goto findpcb;
  962                                 }
  963                         } else
  964                                 ti_locked = TI_RLOCKED;
  965                 }
  966                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
  967 
  968                 if (thflags & TH_SYN)
  969                         tcp_dooptions(&to, optp, optlen, TO_SYN);
  970                 /*
  971                  * NB: tcp_twcheck unlocks the INP and frees the mbuf.
  972                  */
  973                 if (tcp_twcheck(inp, &to, th, m, tlen))
  974                         goto findpcb;
  975                 INP_INFO_RUNLOCK(&V_tcbinfo);
  976                 return (IPPROTO_DONE);
  977         }
  978         /*
  979          * The TCPCB may no longer exist if the connection is winding
  980          * down or it is in the CLOSED state.  Either way we drop the
  981          * segment and send an appropriate response.
  982          */
  983         tp = intotcpcb(inp);
  984         if (tp == NULL || tp->t_state == TCPS_CLOSED) {
  985                 rstreason = BANDLIM_RST_CLOSEDPORT;
  986                 goto dropwithreset;
  987         }
  988 
  989 #ifdef TCP_OFFLOAD
  990         if (tp->t_flags & TF_TOE) {
  991                 tcp_offload_input(tp, m);
  992                 m = NULL;       /* consumed by the TOE driver */
  993                 goto dropunlock;
  994         }
  995 #endif
  996 
  997         /*
  998          * We've identified a valid inpcb, but it could be that we need an
  999          * inpcbinfo write lock but don't hold it.  In this case, attempt to
 1000          * acquire using the same strategy as the TIMEWAIT case above.  If we
 1001          * relock, we have to jump back to 'relocked' as the connection might
 1002          * now be in TIMEWAIT.
 1003          */
 1004 #ifdef INVARIANTS
 1005         if ((thflags & (TH_FIN | TH_RST)) != 0)
 1006                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 1007 #endif
 1008         if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
 1009               (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
 1010                !(tp->t_flags & TF_FASTOPEN)))) {
 1011                 if (ti_locked == TI_UNLOCKED) {
 1012                         if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
 1013                                 in_pcbref(inp);
 1014                                 INP_WUNLOCK(inp);
 1015                                 INP_INFO_RLOCK(&V_tcbinfo);
 1016                                 ti_locked = TI_RLOCKED;
 1017                                 INP_WLOCK(inp);
 1018                                 if (in_pcbrele_wlocked(inp)) {
 1019                                         inp = NULL;
 1020                                         goto findpcb;
 1021                                 }
 1022                                 goto relocked;
 1023                         } else
 1024                                 ti_locked = TI_RLOCKED;
 1025                 }
 1026                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 1027         }
 1028 
 1029 #ifdef MAC
 1030         INP_WLOCK_ASSERT(inp);
 1031         if (mac_inpcb_check_deliver(inp, m))
 1032                 goto dropunlock;
 1033 #endif
 1034         so = inp->inp_socket;
 1035         KASSERT(so != NULL, ("%s: so == NULL", __func__));
 1036 #ifdef TCPDEBUG
 1037         if (so->so_options & SO_DEBUG) {
 1038                 ostate = tp->t_state;
 1039 #ifdef INET6
 1040                 if (isipv6) {
 1041                         bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
 1042                 } else
 1043 #endif
 1044                         bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
 1045                 tcp_savetcp = *th;
 1046         }
 1047 #endif /* TCPDEBUG */
 1048         /*
 1049          * When the socket is accepting connections (the INPCB is in LISTEN
 1050          * state) we look into the SYN cache if this is a new connection
 1051          * attempt or the completion of a previous one.
 1052          */
 1053         if (so->so_options & SO_ACCEPTCONN) {
 1054                 struct in_conninfo inc;
 1055 
 1056                 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
 1057                     "tp not listening", __func__));
 1058                 bzero(&inc, sizeof(inc));
 1059 #ifdef INET6
 1060                 if (isipv6) {
 1061                         inc.inc_flags |= INC_ISIPV6;
 1062                         inc.inc6_faddr = ip6->ip6_src;
 1063                         inc.inc6_laddr = ip6->ip6_dst;
 1064                 } else
 1065 #endif
 1066                 {
 1067                         inc.inc_faddr = ip->ip_src;
 1068                         inc.inc_laddr = ip->ip_dst;
 1069                 }
 1070                 inc.inc_fport = th->th_sport;
 1071                 inc.inc_lport = th->th_dport;
 1072                 inc.inc_fibnum = so->so_fibnum;
 1073 
 1074                 /*
 1075                  * Check for an existing connection attempt in syncache if
 1076                  * the flag is only ACK.  A successful lookup creates a new
 1077                  * socket appended to the listen queue in SYN_RECEIVED state.
 1078                  */
 1079                 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
 1080 
 1081                         INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 1082                         /*
 1083                          * Parse the TCP options here because
 1084                          * syncookies need access to the reflected
 1085                          * timestamp.
 1086                          */
 1087                         tcp_dooptions(&to, optp, optlen, 0);
 1088                         /*
 1089                          * NB: syncache_expand() doesn't unlock
 1090                          * inp and tcpinfo locks.
 1091                          */
 1092                         if (!syncache_expand(&inc, &to, th, &so, m)) {
 1093                                 /*
 1094                                  * No syncache entry or ACK was not
 1095                                  * for our SYN/ACK.  Send a RST.
 1096                                  * NB: syncache did its own logging
 1097                                  * of the failure cause.
 1098                                  */
 1099                                 rstreason = BANDLIM_RST_OPENPORT;
 1100                                 goto dropwithreset;
 1101                         }
 1102 #ifdef TCP_RFC7413
 1103 new_tfo_socket:
 1104 #endif
 1105                         if (so == NULL) {
 1106                                 /*
 1107                                  * We completed the 3-way handshake
 1108                                  * but could not allocate a socket
 1109                                  * either due to memory shortage,
 1110                                  * listen queue length limits or
 1111                                  * global socket limits.  Send RST
 1112                                  * or wait and have the remote end
 1113                                  * retransmit the ACK for another
 1114                                  * try.
 1115                                  */
 1116                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1117                                         log(LOG_DEBUG, "%s; %s: Listen socket: "
 1118                                             "Socket allocation failed due to "
 1119                                             "limits or memory shortage, %s\n",
 1120                                             s, __func__,
 1121                                             V_tcp_sc_rst_sock_fail ?
 1122                                             "sending RST" : "try again");
 1123                                 if (V_tcp_sc_rst_sock_fail) {
 1124                                         rstreason = BANDLIM_UNLIMITED;
 1125                                         goto dropwithreset;
 1126                                 } else
 1127                                         goto dropunlock;
 1128                         }
 1129                         /*
 1130                          * Socket is created in state SYN_RECEIVED.
 1131                          * Unlock the listen socket, lock the newly
 1132                          * created socket and update the tp variable.
 1133                          */
 1134                         INP_WUNLOCK(inp);       /* listen socket */
 1135                         inp = sotoinpcb(so);
 1136                         /*
 1137                          * New connection inpcb is already locked by
 1138                          * syncache_expand().
 1139                          */
 1140                         INP_WLOCK_ASSERT(inp);
 1141                         tp = intotcpcb(inp);
 1142                         KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
 1143                             ("%s: ", __func__));
 1144 #ifdef TCP_SIGNATURE
 1145                         if (sig_checked == 0)  {
 1146                                 tcp_dooptions(&to, optp, optlen,
 1147                                     (thflags & TH_SYN) ? TO_SYN : 0);
 1148                                 if (!tcp_signature_verify_input(m, off0, tlen,
 1149                                     optlen, &to, th, tp->t_flags)) {
 1150 
 1151                                         /*
 1152                                          * In SYN_SENT state if it receives an
 1153                                          * RST, it is allowed for further
 1154                                          * processing.
 1155                                          */
 1156                                         if ((thflags & TH_RST) == 0 ||
 1157                                             (tp->t_state == TCPS_SYN_SENT) == 0)
 1158                                                 goto dropunlock;
 1159                                 }
 1160                                 sig_checked = 1;
 1161                         }
 1162 #endif
 1163 
 1164                         /*
 1165                          * Process the segment and the data it
 1166                          * contains.  tcp_do_segment() consumes
 1167                          * the mbuf chain and unlocks the inpcb.
 1168                          */
 1169                         tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
 1170                             iptos, ti_locked);
 1171                         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1172                         return (IPPROTO_DONE);
 1173                 }
 1174                 /*
 1175                  * Segment flag validation for new connection attempts:
 1176                  *
 1177                  * Our (SYN|ACK) response was rejected.
 1178                  * Check with syncache and remove entry to prevent
 1179                  * retransmits.
 1180                  *
 1181                  * NB: syncache_chkrst does its own logging of failure
 1182                  * causes.
 1183                  */
 1184                 if (thflags & TH_RST) {
 1185                         syncache_chkrst(&inc, th);
 1186                         goto dropunlock;
 1187                 }
 1188                 /*
 1189                  * We can't do anything without SYN.
 1190                  */
 1191                 if ((thflags & TH_SYN) == 0) {
 1192                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1193                                 log(LOG_DEBUG, "%s; %s: Listen socket: "
 1194                                     "SYN is missing, segment ignored\n",
 1195                                     s, __func__);
 1196                         TCPSTAT_INC(tcps_badsyn);
 1197                         goto dropunlock;
 1198                 }
 1199                 /*
 1200                  * (SYN|ACK) is bogus on a listen socket.
 1201                  */
 1202                 if (thflags & TH_ACK) {
 1203                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1204                                 log(LOG_DEBUG, "%s; %s: Listen socket: "
 1205                                     "SYN|ACK invalid, segment rejected\n",
 1206                                     s, __func__);
 1207                         syncache_badack(&inc);  /* XXX: Not needed! */
 1208                         TCPSTAT_INC(tcps_badsyn);
 1209                         rstreason = BANDLIM_RST_OPENPORT;
 1210                         goto dropwithreset;
 1211                 }
 1212                 /*
 1213                  * If the drop_synfin option is enabled, drop all
 1214                  * segments with both the SYN and FIN bits set.
 1215                  * This prevents e.g. nmap from identifying the
 1216                  * TCP/IP stack.
 1217                  * XXX: Poor reasoning.  nmap has other methods
 1218                  * and is constantly refining its stack detection
 1219                  * strategies.
 1220                  * XXX: This is a violation of the TCP specification
 1221                  * and was used by RFC1644.
 1222                  */
 1223                 if ((thflags & TH_FIN) && V_drop_synfin) {
 1224                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1225                                 log(LOG_DEBUG, "%s; %s: Listen socket: "
 1226                                     "SYN|FIN segment ignored (based on "
 1227                                     "sysctl setting)\n", s, __func__);
 1228                         TCPSTAT_INC(tcps_badsyn);
 1229                         goto dropunlock;
 1230                 }
 1231                 /*
 1232                  * Segment's flags are (SYN) or (SYN|FIN).
 1233                  *
 1234                  * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
 1235                  * as they do not affect the state of the TCP FSM.
 1236                  * The data pointed to by TH_URG and th_urp is ignored.
 1237                  */
 1238                 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
 1239                     ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
 1240                 KASSERT(thflags & (TH_SYN),
 1241                     ("%s: Listen socket: TH_SYN not set", __func__));
 1242 #ifdef INET6
 1243                 /*
 1244                  * If deprecated address is forbidden,
 1245                  * we do not accept SYN to deprecated interface
 1246                  * address to prevent any new inbound connection from
 1247                  * getting established.
 1248                  * When we do not accept SYN, we send a TCP RST,
 1249                  * with deprecated source address (instead of dropping
 1250                  * it).  We compromise it as it is much better for peer
 1251                  * to send a RST, and RST will be the final packet
 1252                  * for the exchange.
 1253                  *
 1254                  * If we do not forbid deprecated addresses, we accept
 1255                  * the SYN packet.  RFC2462 does not suggest dropping
 1256                  * SYN in this case.
 1257                  * If we decipher RFC2462 5.5.4, it says like this:
 1258                  * 1. use of deprecated addr with existing
 1259                  *    communication is okay - "SHOULD continue to be
 1260                  *    used"
 1261                  * 2. use of it with new communication:
 1262                  *   (2a) "SHOULD NOT be used if alternate address
 1263                  *        with sufficient scope is available"
 1264                  *   (2b) nothing mentioned otherwise.
 1265                  * Here we fall into (2b) case as we have no choice in
 1266                  * our source address selection - we must obey the peer.
 1267                  *
 1268                  * The wording in RFC2462 is confusing, and there are
 1269                  * multiple description text for deprecated address
 1270                  * handling - worse, they are not exactly the same.
 1271                  * I believe 5.5.4 is the best one, so we follow 5.5.4.
 1272                  */
 1273                 if (isipv6 && !V_ip6_use_deprecated) {
 1274                         struct in6_ifaddr *ia6;
 1275 
 1276                         ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
 1277                         if (ia6 != NULL &&
 1278                             (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
 1279                                 ifa_free(&ia6->ia_ifa);
 1280                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1281                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
 1282                                         "Connection attempt to deprecated "
 1283                                         "IPv6 address rejected\n",
 1284                                         s, __func__);
 1285                                 rstreason = BANDLIM_RST_OPENPORT;
 1286                                 goto dropwithreset;
 1287                         }
 1288                         if (ia6)
 1289                                 ifa_free(&ia6->ia_ifa);
 1290                 }
 1291 #endif /* INET6 */
 1292                 /*
 1293                  * Basic sanity checks on incoming SYN requests:
 1294                  *   Don't respond if the destination is a link layer
 1295                  *      broadcast according to RFC1122 4.2.3.10, p. 104.
 1296                  *   If it is from this socket it must be forged.
 1297                  *   Don't respond if the source or destination is a
 1298                  *      global or subnet broad- or multicast address.
 1299                  *   Note that it is quite possible to receive unicast
 1300                  *      link-layer packets with a broadcast IP address. Use
 1301                  *      in_broadcast() to find them.
 1302                  */
 1303                 if (m->m_flags & (M_BCAST|M_MCAST)) {
 1304                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1305                             log(LOG_DEBUG, "%s; %s: Listen socket: "
 1306                                 "Connection attempt from broad- or multicast "
 1307                                 "link layer address ignored\n", s, __func__);
 1308                         goto dropunlock;
 1309                 }
 1310 #ifdef INET6
 1311                 if (isipv6) {
 1312                         if (th->th_dport == th->th_sport &&
 1313                             IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
 1314                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1315                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
 1316                                         "Connection attempt to/from self "
 1317                                         "ignored\n", s, __func__);
 1318                                 goto dropunlock;
 1319                         }
 1320                         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 1321                             IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
 1322                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1323                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
 1324                                         "Connection attempt from/to multicast "
 1325                                         "address ignored\n", s, __func__);
 1326                                 goto dropunlock;
 1327                         }
 1328                 }
 1329 #endif
 1330 #if defined(INET) && defined(INET6)
 1331                 else
 1332 #endif
 1333 #ifdef INET
 1334                 {
 1335                         if (th->th_dport == th->th_sport &&
 1336                             ip->ip_dst.s_addr == ip->ip_src.s_addr) {
 1337                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1338                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
 1339                                         "Connection attempt from/to self "
 1340                                         "ignored\n", s, __func__);
 1341                                 goto dropunlock;
 1342                         }
 1343                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 1344                             IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 1345                             ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 1346                             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
 1347                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
 1348                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
 1349                                         "Connection attempt from/to broad- "
 1350                                         "or multicast address ignored\n",
 1351                                         s, __func__);
 1352                                 goto dropunlock;
 1353                         }
 1354                 }
 1355 #endif
 1356                 /*
 1357                  * SYN appears to be valid.  Create compressed TCP state
 1358                  * for syncache.
 1359                  */
 1360 #ifdef TCPDEBUG
 1361                 if (so->so_options & SO_DEBUG)
 1362                         tcp_trace(TA_INPUT, ostate, tp,
 1363                             (void *)tcp_saveipgen, &tcp_savetcp, 0);
 1364 #endif
 1365                 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
 1366                 tcp_dooptions(&to, optp, optlen, TO_SYN);
 1367 #ifdef TCP_RFC7413
 1368                 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
 1369                         goto new_tfo_socket;
 1370 #else
 1371                 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
 1372 #endif
 1373                 /*
 1374                  * Entry added to syncache and mbuf consumed.
 1375                  * Only the listen socket is unlocked by syncache_add().
 1376                  */
 1377                 if (ti_locked == TI_RLOCKED) {
 1378                         INP_INFO_RUNLOCK(&V_tcbinfo);
 1379                         ti_locked = TI_UNLOCKED;
 1380                 }
 1381                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1382                 return (IPPROTO_DONE);
 1383         } else if (tp->t_state == TCPS_LISTEN) {
 1384                 /*
 1385                  * When a listen socket is torn down the SO_ACCEPTCONN
 1386                  * flag is removed first while connections are drained
 1387                  * from the accept queue in a unlock/lock cycle of the
 1388                  * ACCEPT_LOCK, opening a race condition allowing a SYN
 1389                  * attempt go through unhandled.
 1390                  */
 1391                 goto dropunlock;
 1392         }
 1393 
 1394 #ifdef TCP_SIGNATURE
 1395         if (sig_checked == 0)  {
 1396                 tcp_dooptions(&to, optp, optlen,
 1397                     (thflags & TH_SYN) ? TO_SYN : 0);
 1398                 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
 1399                     th, tp->t_flags)) {
 1400 
 1401                         /*
 1402                          * In SYN_SENT state if it receives an RST, it is
 1403                          * allowed for further processing.
 1404                          */
 1405                         if ((thflags & TH_RST) == 0 ||
 1406                             (tp->t_state == TCPS_SYN_SENT) == 0)
 1407                                 goto dropunlock;
 1408                 }
 1409                 sig_checked = 1;
 1410         }
 1411 #endif
 1412 
 1413         TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
 1414 
 1415         /*
 1416          * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
 1417          * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
 1418          * the inpcb, and unlocks pcbinfo.
 1419          */
 1420         tp->t_fb->tfb_tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
 1421         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1422         return (IPPROTO_DONE);
 1423 
 1424 dropwithreset:
 1425         TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
 1426 
 1427         if (ti_locked == TI_RLOCKED) {
 1428                 INP_INFO_RUNLOCK(&V_tcbinfo);
 1429                 ti_locked = TI_UNLOCKED;
 1430         }
 1431 #ifdef INVARIANTS
 1432         else {
 1433                 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
 1434                     "ti_locked: %d", __func__, ti_locked));
 1435                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1436         }
 1437 #endif
 1438 
 1439         if (inp != NULL) {
 1440                 tcp_dropwithreset(m, th, tp, tlen, rstreason);
 1441                 INP_WUNLOCK(inp);
 1442         } else
 1443                 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
 1444         m = NULL;       /* mbuf chain got consumed. */
 1445         goto drop;
 1446 
 1447 dropunlock:
 1448         if (m != NULL)
 1449                 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
 1450 
 1451         if (ti_locked == TI_RLOCKED) {
 1452                 INP_INFO_RUNLOCK(&V_tcbinfo);
 1453                 ti_locked = TI_UNLOCKED;
 1454         }
 1455 #ifdef INVARIANTS
 1456         else {
 1457                 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
 1458                     "ti_locked: %d", __func__, ti_locked));
 1459                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1460         }
 1461 #endif
 1462 
 1463         if (inp != NULL)
 1464                 INP_WUNLOCK(inp);
 1465 
 1466 drop:
 1467         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1468         if (s != NULL)
 1469                 free(s, M_TCPLOG);
 1470         if (m != NULL)
 1471                 m_freem(m);
 1472         return (IPPROTO_DONE);
 1473 }
 1474 
 1475 void
 1476 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
 1477     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
 1478     int ti_locked)
 1479 {
 1480         int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
 1481         int rstreason, todrop, win;
 1482         u_long tiwin;
 1483         char *s;
 1484         struct in_conninfo *inc;
 1485         struct mbuf *mfree;
 1486         struct tcpopt to;
 1487         int tfo_syn;
 1488         
 1489 #ifdef TCPDEBUG
 1490         /*
 1491          * The size of tcp_saveipgen must be the size of the max ip header,
 1492          * now IPv6.
 1493          */
 1494         u_char tcp_saveipgen[IP6_HDR_LEN];
 1495         struct tcphdr tcp_savetcp;
 1496         short ostate = 0;
 1497 #endif
 1498         thflags = th->th_flags;
 1499         inc = &tp->t_inpcb->inp_inc;
 1500         tp->sackhint.last_sack_ack = 0;
 1501         sack_changed = 0;
 1502 
 1503         /*
 1504          * If this is either a state-changing packet or current state isn't
 1505          * established, we require a write lock on tcbinfo.  Otherwise, we
 1506          * allow the tcbinfo to be in either alocked or unlocked, as the
 1507          * caller may have unnecessarily acquired a write lock due to a race.
 1508          */
 1509         if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
 1510             tp->t_state != TCPS_ESTABLISHED) {
 1511                 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
 1512                     "SYN/FIN/RST/!EST", __func__, ti_locked));
 1513                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 1514         } else {
 1515 #ifdef INVARIANTS
 1516                 if (ti_locked == TI_RLOCKED)
 1517                         INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 1518                 else {
 1519                         KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
 1520                             "ti_locked: %d", __func__, ti_locked));
 1521                         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 1522                 }
 1523 #endif
 1524         }
 1525         INP_WLOCK_ASSERT(tp->t_inpcb);
 1526         KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
 1527             __func__));
 1528         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
 1529             __func__));
 1530 
 1531 #ifdef TCPPCAP
 1532         /* Save segment, if requested. */
 1533         tcp_pcap_add(th, m, &(tp->t_inpkts));
 1534 #endif
 1535 
 1536         /*
 1537          * Segment received on connection.
 1538          * Reset idle time and keep-alive timer.
 1539          * XXX: This should be done after segment
 1540          * validation to ignore broken/spoofed segs.
 1541          */
 1542         tp->t_rcvtime = ticks;
 1543         if (TCPS_HAVEESTABLISHED(tp->t_state))
 1544                 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
 1545 
 1546         /*
 1547          * Scale up the window into a 32-bit value.
 1548          * For the SYN_SENT state the scale is zero.
 1549          */
 1550         tiwin = th->th_win << tp->snd_scale;
 1551 
 1552         /*
 1553          * TCP ECN processing.
 1554          */
 1555         if (tp->t_flags & TF_ECN_PERMIT) {
 1556                 if (thflags & TH_CWR)
 1557                         tp->t_flags &= ~TF_ECN_SND_ECE;
 1558                 switch (iptos & IPTOS_ECN_MASK) {
 1559                 case IPTOS_ECN_CE:
 1560                         tp->t_flags |= TF_ECN_SND_ECE;
 1561                         TCPSTAT_INC(tcps_ecn_ce);
 1562                         break;
 1563                 case IPTOS_ECN_ECT0:
 1564                         TCPSTAT_INC(tcps_ecn_ect0);
 1565                         break;
 1566                 case IPTOS_ECN_ECT1:
 1567                         TCPSTAT_INC(tcps_ecn_ect1);
 1568                         break;
 1569                 }
 1570 
 1571                 /* Process a packet differently from RFC3168. */
 1572                 cc_ecnpkt_handler(tp, th, iptos);
 1573 
 1574                 /* Congestion experienced. */
 1575                 if (thflags & TH_ECE) {
 1576                         cc_cong_signal(tp, th, CC_ECN);
 1577                 }
 1578         }
 1579 
 1580         /*
 1581          * Parse options on any incoming segment.
 1582          */
 1583         tcp_dooptions(&to, (u_char *)(th + 1),
 1584             (th->th_off << 2) - sizeof(struct tcphdr),
 1585             (thflags & TH_SYN) ? TO_SYN : 0);
 1586 
 1587         /*
 1588          * If echoed timestamp is later than the current time,
 1589          * fall back to non RFC1323 RTT calculation.  Normalize
 1590          * timestamp if syncookies were used when this connection
 1591          * was established.
 1592          */
 1593         if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
 1594                 to.to_tsecr -= tp->ts_offset;
 1595                 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
 1596                         to.to_tsecr = 0;
 1597         }
 1598         /*
 1599          * If timestamps were negotiated during SYN/ACK they should
 1600          * appear on every segment during this session and vice versa.
 1601          */
 1602         if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
 1603                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
 1604                         log(LOG_DEBUG, "%s; %s: Timestamp missing, "
 1605                             "no action\n", s, __func__);
 1606                         free(s, M_TCPLOG);
 1607                 }
 1608         }
 1609         if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
 1610                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
 1611                         log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
 1612                             "no action\n", s, __func__);
 1613                         free(s, M_TCPLOG);
 1614                 }
 1615         }
 1616 
 1617         /*
 1618          * Process options only when we get SYN/ACK back. The SYN case
 1619          * for incoming connections is handled in tcp_syncache.
 1620          * According to RFC1323 the window field in a SYN (i.e., a <SYN>
 1621          * or <SYN,ACK>) segment itself is never scaled.
 1622          * XXX this is traditional behavior, may need to be cleaned up.
 1623          */
 1624         if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
 1625                 if ((to.to_flags & TOF_SCALE) &&
 1626                     (tp->t_flags & TF_REQ_SCALE)) {
 1627                         tp->t_flags |= TF_RCVD_SCALE;
 1628                         tp->snd_scale = to.to_wscale;
 1629                 }
 1630                 /*
 1631                  * Initial send window.  It will be updated with
 1632                  * the next incoming segment to the scaled value.
 1633                  */
 1634                 tp->snd_wnd = th->th_win;
 1635                 if (to.to_flags & TOF_TS) {
 1636                         tp->t_flags |= TF_RCVD_TSTMP;
 1637                         tp->ts_recent = to.to_tsval;
 1638                         tp->ts_recent_age = tcp_ts_getticks();
 1639                 }
 1640                 if (to.to_flags & TOF_MSS)
 1641                         tcp_mss(tp, to.to_mss);
 1642                 if ((tp->t_flags & TF_SACK_PERMIT) &&
 1643                     (to.to_flags & TOF_SACKPERM) == 0)
 1644                         tp->t_flags &= ~TF_SACK_PERMIT;
 1645         }
 1646 
 1647         /*
 1648          * Header prediction: check for the two common cases
 1649          * of a uni-directional data xfer.  If the packet has
 1650          * no control flags, is in-sequence, the window didn't
 1651          * change and we're not retransmitting, it's a
 1652          * candidate.  If the length is zero and the ack moved
 1653          * forward, we're the sender side of the xfer.  Just
 1654          * free the data acked & wake any higher level process
 1655          * that was blocked waiting for space.  If the length
 1656          * is non-zero and the ack didn't move, we're the
 1657          * receiver side.  If we're getting packets in-order
 1658          * (the reassembly queue is empty), add the data to
 1659          * the socket buffer and note that we need a delayed ack.
 1660          * Make sure that the hidden state-flags are also off.
 1661          * Since we check for TCPS_ESTABLISHED first, it can only
 1662          * be TH_NEEDSYN.
 1663          */
 1664         if (tp->t_state == TCPS_ESTABLISHED &&
 1665             th->th_seq == tp->rcv_nxt &&
 1666             (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
 1667             tp->snd_nxt == tp->snd_max &&
 1668             tiwin && tiwin == tp->snd_wnd && 
 1669             ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
 1670             LIST_EMPTY(&tp->t_segq) &&
 1671             ((to.to_flags & TOF_TS) == 0 ||
 1672              TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
 1673 
 1674                 /*
 1675                  * If last ACK falls within this segment's sequence numbers,
 1676                  * record the timestamp.
 1677                  * NOTE that the test is modified according to the latest
 1678                  * proposal of the tcplw@cray.com list (Braden 1993/04/26).
 1679                  */
 1680                 if ((to.to_flags & TOF_TS) != 0 &&
 1681                     SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
 1682                         tp->ts_recent_age = tcp_ts_getticks();
 1683                         tp->ts_recent = to.to_tsval;
 1684                 }
 1685 
 1686                 if (tlen == 0) {
 1687                         if (SEQ_GT(th->th_ack, tp->snd_una) &&
 1688                             SEQ_LEQ(th->th_ack, tp->snd_max) &&
 1689                             !IN_RECOVERY(tp->t_flags) &&
 1690                             (to.to_flags & TOF_SACK) == 0 &&
 1691                             TAILQ_EMPTY(&tp->snd_holes)) {
 1692                                 /*
 1693                                  * This is a pure ack for outstanding data.
 1694                                  */
 1695                                 if (ti_locked == TI_RLOCKED)
 1696                                         INP_INFO_RUNLOCK(&V_tcbinfo);
 1697                                 ti_locked = TI_UNLOCKED;
 1698 
 1699                                 TCPSTAT_INC(tcps_predack);
 1700 
 1701                                 /*
 1702                                  * "bad retransmit" recovery.
 1703                                  */
 1704                                 if (tp->t_rxtshift == 1 &&
 1705                                     tp->t_flags & TF_PREVVALID &&
 1706                                     (int)(ticks - tp->t_badrxtwin) < 0) {
 1707                                         cc_cong_signal(tp, th, CC_RTO_ERR);
 1708                                 }
 1709 
 1710                                 /*
 1711                                  * Recalculate the transmit timer / rtt.
 1712                                  *
 1713                                  * Some boxes send broken timestamp replies
 1714                                  * during the SYN+ACK phase, ignore
 1715                                  * timestamps of 0 or we could calculate a
 1716                                  * huge RTT and blow up the retransmit timer.
 1717                                  */
 1718                                 if ((to.to_flags & TOF_TS) != 0 &&
 1719                                     to.to_tsecr) {
 1720                                         u_int t;
 1721 
 1722                                         t = tcp_ts_getticks() - to.to_tsecr;
 1723                                         if (!tp->t_rttlow || tp->t_rttlow > t)
 1724                                                 tp->t_rttlow = t;
 1725                                         tcp_xmit_timer(tp,
 1726                                             TCP_TS_TO_TICKS(t) + 1);
 1727                                 } else if (tp->t_rtttime &&
 1728                                     SEQ_GT(th->th_ack, tp->t_rtseq)) {
 1729                                         if (!tp->t_rttlow ||
 1730                                             tp->t_rttlow > ticks - tp->t_rtttime)
 1731                                                 tp->t_rttlow = ticks - tp->t_rtttime;
 1732                                         tcp_xmit_timer(tp,
 1733                                                         ticks - tp->t_rtttime);
 1734                                 }
 1735                                 acked = BYTES_THIS_ACK(tp, th);
 1736 
 1737                                 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
 1738                                 hhook_run_tcp_est_in(tp, th, &to);
 1739 
 1740                                 TCPSTAT_INC(tcps_rcvackpack);
 1741                                 TCPSTAT_ADD(tcps_rcvackbyte, acked);
 1742                                 sbdrop(&so->so_snd, acked);
 1743                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
 1744                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 1745                                         tp->snd_recover = th->th_ack - 1;
 1746                                 
 1747                                 /*
 1748                                  * Let the congestion control algorithm update
 1749                                  * congestion control related information. This
 1750                                  * typically means increasing the congestion
 1751                                  * window.
 1752                                  */
 1753                                 cc_ack_received(tp, th, CC_ACK);
 1754 
 1755                                 tp->snd_una = th->th_ack;
 1756                                 /*
 1757                                  * Pull snd_wl2 up to prevent seq wrap relative
 1758                                  * to th_ack.
 1759                                  */
 1760                                 tp->snd_wl2 = th->th_ack;
 1761                                 tp->t_dupacks = 0;
 1762                                 m_freem(m);
 1763 
 1764                                 /*
 1765                                  * If all outstanding data are acked, stop
 1766                                  * retransmit timer, otherwise restart timer
 1767                                  * using current (possibly backed-off) value.
 1768                                  * If process is waiting for space,
 1769                                  * wakeup/selwakeup/signal.  If data
 1770                                  * are ready to send, let tcp_output
 1771                                  * decide between more output or persist.
 1772                                  */
 1773 #ifdef TCPDEBUG
 1774                                 if (so->so_options & SO_DEBUG)
 1775                                         tcp_trace(TA_INPUT, ostate, tp,
 1776                                             (void *)tcp_saveipgen,
 1777                                             &tcp_savetcp, 0);
 1778 #endif
 1779                                 TCP_PROBE3(debug__input, tp, th,
 1780                                         mtod(m, const char *));
 1781                                 if (tp->snd_una == tp->snd_max)
 1782                                         tcp_timer_activate(tp, TT_REXMT, 0);
 1783                                 else if (!tcp_timer_active(tp, TT_PERSIST))
 1784                                         tcp_timer_activate(tp, TT_REXMT,
 1785                                                       tp->t_rxtcur);
 1786                                 sowwakeup(so);
 1787                                 if (sbavail(&so->so_snd))
 1788                                         (void) tp->t_fb->tfb_tcp_output(tp);
 1789                                 goto check_delack;
 1790                         }
 1791                 } else if (th->th_ack == tp->snd_una &&
 1792                     tlen <= sbspace(&so->so_rcv)) {
 1793                         int newsize = 0;        /* automatic sockbuf scaling */
 1794 
 1795                         /*
 1796                          * This is a pure, in-sequence data packet with
 1797                          * nothing on the reassembly queue and we have enough
 1798                          * buffer space to take it.
 1799                          */
 1800                         if (ti_locked == TI_RLOCKED)
 1801                                 INP_INFO_RUNLOCK(&V_tcbinfo);
 1802                         ti_locked = TI_UNLOCKED;
 1803 
 1804                         /* Clean receiver SACK report if present */
 1805                         if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
 1806                                 tcp_clean_sackreport(tp);
 1807                         TCPSTAT_INC(tcps_preddat);
 1808                         tp->rcv_nxt += tlen;
 1809                         /*
 1810                          * Pull snd_wl1 up to prevent seq wrap relative to
 1811                          * th_seq.
 1812                          */
 1813                         tp->snd_wl1 = th->th_seq;
 1814                         /*
 1815                          * Pull rcv_up up to prevent seq wrap relative to
 1816                          * rcv_nxt.
 1817                          */
 1818                         tp->rcv_up = tp->rcv_nxt;
 1819                         TCPSTAT_INC(tcps_rcvpack);
 1820                         TCPSTAT_ADD(tcps_rcvbyte, tlen);
 1821 #ifdef TCPDEBUG
 1822                         if (so->so_options & SO_DEBUG)
 1823                                 tcp_trace(TA_INPUT, ostate, tp,
 1824                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
 1825 #endif
 1826                         TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
 1827 
 1828                 /*
 1829                  * Automatic sizing of receive socket buffer.  Often the send
 1830                  * buffer size is not optimally adjusted to the actual network
 1831                  * conditions at hand (delay bandwidth product).  Setting the
 1832                  * buffer size too small limits throughput on links with high
 1833                  * bandwidth and high delay (eg. trans-continental/oceanic links).
 1834                  *
 1835                  * On the receive side the socket buffer memory is only rarely
 1836                  * used to any significant extent.  This allows us to be much
 1837                  * more aggressive in scaling the receive socket buffer.  For
 1838                  * the case that the buffer space is actually used to a large
 1839                  * extent and we run out of kernel memory we can simply drop
 1840                  * the new segments; TCP on the sender will just retransmit it
 1841                  * later.  Setting the buffer size too big may only consume too
 1842                  * much kernel memory if the application doesn't read() from
 1843                  * the socket or packet loss or reordering makes use of the
 1844                  * reassembly queue.
 1845                  *
 1846                  * The criteria to step up the receive buffer one notch are:
 1847                  *  1. Application has not set receive buffer size with
 1848                  *     SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
 1849                  *  2. the number of bytes received during the time it takes
 1850                  *     one timestamp to be reflected back to us (the RTT);
 1851                  *  3. received bytes per RTT is within seven eighth of the
 1852                  *     current socket buffer size;
 1853                  *  4. receive buffer size has not hit maximal automatic size;
 1854                  *
 1855                  * This algorithm does one step per RTT at most and only if
 1856                  * we receive a bulk stream w/o packet losses or reorderings.
 1857                  * Shrinking the buffer during idle times is not necessary as
 1858                  * it doesn't consume any memory when idle.
 1859                  *
 1860                  * TODO: Only step up if the application is actually serving
 1861                  * the buffer to better manage the socket buffer resources.
 1862                  */
 1863                         if (V_tcp_do_autorcvbuf &&
 1864                             (to.to_flags & TOF_TS) &&
 1865                             to.to_tsecr &&
 1866                             (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
 1867                                 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
 1868                                     to.to_tsecr - tp->rfbuf_ts < hz) {
 1869                                         if (tp->rfbuf_cnt >
 1870                                             (so->so_rcv.sb_hiwat / 8 * 7) &&
 1871                                             so->so_rcv.sb_hiwat <
 1872                                             V_tcp_autorcvbuf_max) {
 1873                                                 newsize =
 1874                                                     min(so->so_rcv.sb_hiwat +
 1875                                                     V_tcp_autorcvbuf_inc,
 1876                                                     V_tcp_autorcvbuf_max);
 1877                                         }
 1878                                         /* Start over with next RTT. */
 1879                                         tp->rfbuf_ts = 0;
 1880                                         tp->rfbuf_cnt = 0;
 1881                                 } else
 1882                                         tp->rfbuf_cnt += tlen;  /* add up */
 1883                         }
 1884 
 1885                         /* Add data to socket buffer. */
 1886                         SOCKBUF_LOCK(&so->so_rcv);
 1887                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 1888                                 m_freem(m);
 1889                         } else {
 1890                                 /*
 1891                                  * Set new socket buffer size.
 1892                                  * Give up when limit is reached.
 1893                                  */
 1894                                 if (newsize)
 1895                                         if (!sbreserve_locked(&so->so_rcv,
 1896                                             newsize, so, NULL))
 1897                                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
 1898                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 1899                                 sbappendstream_locked(&so->so_rcv, m, 0);
 1900                         }
 1901                         /* NB: sorwakeup_locked() does an implicit unlock. */
 1902                         sorwakeup_locked(so);
 1903                         if (DELAY_ACK(tp, tlen)) {
 1904                                 tp->t_flags |= TF_DELACK;
 1905                         } else {
 1906                                 tp->t_flags |= TF_ACKNOW;
 1907                                 tp->t_fb->tfb_tcp_output(tp);
 1908                         }
 1909                         goto check_delack;
 1910                 }
 1911         }
 1912 
 1913         /*
 1914          * Calculate amount of space in receive window,
 1915          * and then do TCP input processing.
 1916          * Receive window is amount of space in rcv queue,
 1917          * but not less than advertised window.
 1918          */
 1919         win = sbspace(&so->so_rcv);
 1920         if (win < 0)
 1921                 win = 0;
 1922         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
 1923 
 1924         /* Reset receive buffer auto scaling when not in bulk receive mode. */
 1925         tp->rfbuf_ts = 0;
 1926         tp->rfbuf_cnt = 0;
 1927 
 1928         switch (tp->t_state) {
 1929 
 1930         /*
 1931          * If the state is SYN_RECEIVED:
 1932          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
 1933          */
 1934         case TCPS_SYN_RECEIVED:
 1935                 if ((thflags & TH_ACK) &&
 1936                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
 1937                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1938                                 rstreason = BANDLIM_RST_OPENPORT;
 1939                                 goto dropwithreset;
 1940                 }
 1941 #ifdef TCP_RFC7413
 1942                 if (tp->t_flags & TF_FASTOPEN) {
 1943                         /*
 1944                          * When a TFO connection is in SYN_RECEIVED, the
 1945                          * only valid packets are the initial SYN, a
 1946                          * retransmit/copy of the initial SYN (possibly with
 1947                          * a subset of the original data), a valid ACK, a
 1948                          * FIN, or a RST.
 1949                          */
 1950                         if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
 1951                                 rstreason = BANDLIM_RST_OPENPORT;
 1952                                 goto dropwithreset;
 1953                         } else if (thflags & TH_SYN) {
 1954                                 /* non-initial SYN is ignored */
 1955                                 if ((tcp_timer_active(tp, TT_DELACK) || 
 1956                                      tcp_timer_active(tp, TT_REXMT)))
 1957                                         goto drop;
 1958                         } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
 1959                                 goto drop;
 1960                         }
 1961                 }
 1962 #endif
 1963                 break;
 1964 
 1965         /*
 1966          * If the state is SYN_SENT:
 1967          *      if seg contains an ACK, but not for our SYN, drop the input.
 1968          *      if seg contains a RST, then drop the connection.
 1969          *      if seg does not contain SYN, then drop it.
 1970          * Otherwise this is an acceptable SYN segment
 1971          *      initialize tp->rcv_nxt and tp->irs
 1972          *      if seg contains ack then advance tp->snd_una
 1973          *      if seg contains an ECE and ECN support is enabled, the stream
 1974          *          is ECN capable.
 1975          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
 1976          *      arrange for segment to be acked (eventually)
 1977          *      continue processing rest of data/controls, beginning with URG
 1978          */
 1979         case TCPS_SYN_SENT:
 1980                 if ((thflags & TH_ACK) &&
 1981                     (SEQ_LEQ(th->th_ack, tp->iss) ||
 1982                      SEQ_GT(th->th_ack, tp->snd_max))) {
 1983                         rstreason = BANDLIM_UNLIMITED;
 1984                         goto dropwithreset;
 1985                 }
 1986                 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
 1987                         TCP_PROBE5(connect__refused, NULL, tp,
 1988                             mtod(m, const char *), tp, th);
 1989                         tp = tcp_drop(tp, ECONNREFUSED);
 1990                 }
 1991                 if (thflags & TH_RST)
 1992                         goto drop;
 1993                 if (!(thflags & TH_SYN))
 1994                         goto drop;
 1995 
 1996                 tp->irs = th->th_seq;
 1997                 tcp_rcvseqinit(tp);
 1998                 if (thflags & TH_ACK) {
 1999                         TCPSTAT_INC(tcps_connects);
 2000                         soisconnected(so);
 2001 #ifdef MAC
 2002                         mac_socketpeer_set_from_mbuf(m, so);
 2003 #endif
 2004                         /* Do window scaling on this connection? */
 2005                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 2006                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 2007                                 tp->rcv_scale = tp->request_r_scale;
 2008                         }
 2009                         tp->rcv_adv += imin(tp->rcv_wnd,
 2010                             TCP_MAXWIN << tp->rcv_scale);
 2011                         tp->snd_una++;          /* SYN is acked */
 2012                         /*
 2013                          * If there's data, delay ACK; if there's also a FIN
 2014                          * ACKNOW will be turned on later.
 2015                          */
 2016                         if (DELAY_ACK(tp, tlen) && tlen != 0)
 2017                                 tcp_timer_activate(tp, TT_DELACK,
 2018                                     tcp_delacktime);
 2019                         else
 2020                                 tp->t_flags |= TF_ACKNOW;
 2021 
 2022                         if ((thflags & TH_ECE) && V_tcp_do_ecn) {
 2023                                 tp->t_flags |= TF_ECN_PERMIT;
 2024                                 TCPSTAT_INC(tcps_ecn_shs);
 2025                         }
 2026                         
 2027                         /*
 2028                          * Received <SYN,ACK> in SYN_SENT[*] state.
 2029                          * Transitions:
 2030                          *      SYN_SENT  --> ESTABLISHED
 2031                          *      SYN_SENT* --> FIN_WAIT_1
 2032                          */
 2033                         tp->t_starttime = ticks;
 2034                         if (tp->t_flags & TF_NEEDFIN) {
 2035                                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
 2036                                 tp->t_flags &= ~TF_NEEDFIN;
 2037                                 thflags &= ~TH_SYN;
 2038                         } else {
 2039                                 tcp_state_change(tp, TCPS_ESTABLISHED);
 2040                                 TCP_PROBE5(connect__established, NULL, tp,
 2041                                     mtod(m, const char *), tp, th);
 2042                                 cc_conn_init(tp);
 2043                                 tcp_timer_activate(tp, TT_KEEP,
 2044                                     TP_KEEPIDLE(tp));
 2045                         }
 2046                 } else {
 2047                         /*
 2048                          * Received initial SYN in SYN-SENT[*] state =>
 2049                          * simultaneous open.
 2050                          * If it succeeds, connection is * half-synchronized.
 2051                          * Otherwise, do 3-way handshake:
 2052                          *        SYN-SENT -> SYN-RECEIVED
 2053                          *        SYN-SENT* -> SYN-RECEIVED*
 2054                          */
 2055                         tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
 2056                         tcp_timer_activate(tp, TT_REXMT, 0);
 2057                         tcp_state_change(tp, TCPS_SYN_RECEIVED);
 2058                 }
 2059 
 2060                 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
 2061                     "ti_locked %d", __func__, ti_locked));
 2062                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 2063                 INP_WLOCK_ASSERT(tp->t_inpcb);
 2064 
 2065                 /*
 2066                  * Advance th->th_seq to correspond to first data byte.
 2067                  * If data, trim to stay within window,
 2068                  * dropping FIN if necessary.
 2069                  */
 2070                 th->th_seq++;
 2071                 if (tlen > tp->rcv_wnd) {
 2072                         todrop = tlen - tp->rcv_wnd;
 2073                         m_adj(m, -todrop);
 2074                         tlen = tp->rcv_wnd;
 2075                         thflags &= ~TH_FIN;
 2076                         TCPSTAT_INC(tcps_rcvpackafterwin);
 2077                         TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
 2078                 }
 2079                 tp->snd_wl1 = th->th_seq - 1;
 2080                 tp->rcv_up = th->th_seq;
 2081                 /*
 2082                  * Client side of transaction: already sent SYN and data.
 2083                  * If the remote host used T/TCP to validate the SYN,
 2084                  * our data will be ACK'd; if so, enter normal data segment
 2085                  * processing in the middle of step 5, ack processing.
 2086                  * Otherwise, goto step 6.
 2087                  */
 2088                 if (thflags & TH_ACK)
 2089                         goto process_ACK;
 2090 
 2091                 goto step6;
 2092 
 2093         /*
 2094          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
 2095          *      do normal processing.
 2096          *
 2097          * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
 2098          */
 2099         case TCPS_LAST_ACK:
 2100         case TCPS_CLOSING:
 2101                 break;  /* continue normal processing */
 2102         }
 2103 
 2104         /*
 2105          * States other than LISTEN or SYN_SENT.
 2106          * First check the RST flag and sequence number since reset segments
 2107          * are exempt from the timestamp and connection count tests.  This
 2108          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
 2109          * below which allowed reset segments in half the sequence space
 2110          * to fall though and be processed (which gives forged reset
 2111          * segments with a random sequence number a 50 percent chance of
 2112          * killing a connection).
 2113          * Then check timestamp, if present.
 2114          * Then check the connection count, if present.
 2115          * Then check that at least some bytes of segment are within
 2116          * receive window.  If segment begins before rcv_nxt,
 2117          * drop leading data (and SYN); if nothing left, just ack.
 2118          */
 2119         if (thflags & TH_RST) {
 2120                 /*
 2121                  * RFC5961 Section 3.2
 2122                  *
 2123                  * - RST drops connection only if SEG.SEQ == RCV.NXT.
 2124                  * - If RST is in window, we send challenge ACK.
 2125                  *
 2126                  * Note: to take into account delayed ACKs, we should
 2127                  *   test against last_ack_sent instead of rcv_nxt.
 2128                  * Note 2: we handle special case of closed window, not
 2129                  *   covered by the RFC.
 2130                  */
 2131                 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
 2132                     SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
 2133                     (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
 2134 
 2135                         INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 2136                         KASSERT(ti_locked == TI_RLOCKED,
 2137                             ("%s: TH_RST ti_locked %d, th %p tp %p",
 2138                             __func__, ti_locked, th, tp));
 2139                         KASSERT(tp->t_state != TCPS_SYN_SENT,
 2140                             ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
 2141                             __func__, th, tp));
 2142 
 2143                         if (V_tcp_insecure_rst ||
 2144                             tp->last_ack_sent == th->th_seq) {
 2145                                 TCPSTAT_INC(tcps_drops);
 2146                                 /* Drop the connection. */
 2147                                 switch (tp->t_state) {
 2148                                 case TCPS_SYN_RECEIVED:
 2149                                         so->so_error = ECONNREFUSED;
 2150                                         goto close;
 2151                                 case TCPS_ESTABLISHED:
 2152                                 case TCPS_FIN_WAIT_1:
 2153                                 case TCPS_FIN_WAIT_2:
 2154                                 case TCPS_CLOSE_WAIT:
 2155                                         so->so_error = ECONNRESET;
 2156                                 close:
 2157                                         tcp_state_change(tp, TCPS_CLOSED);
 2158                                         /* FALLTHROUGH */
 2159                                 default:
 2160                                         tp = tcp_close(tp);
 2161                                 }
 2162                         } else {
 2163                                 TCPSTAT_INC(tcps_badrst);
 2164                                 /* Send challenge ACK. */
 2165                                 tcp_respond(tp, mtod(m, void *), th, m,
 2166                                     tp->rcv_nxt, tp->snd_nxt, TH_ACK);
 2167                                 tp->last_ack_sent = tp->rcv_nxt;
 2168                                 m = NULL;
 2169                         }
 2170                 }
 2171                 goto drop;
 2172         }
 2173 
 2174         /*
 2175          * RFC5961 Section 4.2
 2176          * Send challenge ACK for any SYN in synchronized state.
 2177          */
 2178         if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT &&
 2179             tp->t_state != TCPS_SYN_RECEIVED) {
 2180                 KASSERT(ti_locked == TI_RLOCKED,
 2181                     ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
 2182                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 2183 
 2184                 TCPSTAT_INC(tcps_badsyn);
 2185                 if (V_tcp_insecure_syn &&
 2186                     SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
 2187                     SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
 2188                         tp = tcp_drop(tp, ECONNRESET);
 2189                         rstreason = BANDLIM_UNLIMITED;
 2190                 } else {
 2191                         /* Send challenge ACK. */
 2192                         tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
 2193                             tp->snd_nxt, TH_ACK);
 2194                         tp->last_ack_sent = tp->rcv_nxt;
 2195                         m = NULL;
 2196                 }
 2197                 goto drop;
 2198         }
 2199 
 2200         /*
 2201          * RFC 1323 PAWS: If we have a timestamp reply on this segment
 2202          * and it's less than ts_recent, drop it.
 2203          */
 2204         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
 2205             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
 2206 
 2207                 /* Check to see if ts_recent is over 24 days old.  */
 2208                 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
 2209                         /*
 2210                          * Invalidate ts_recent.  If this segment updates
 2211                          * ts_recent, the age will be reset later and ts_recent
 2212                          * will get a valid value.  If it does not, setting
 2213                          * ts_recent to zero will at least satisfy the
 2214                          * requirement that zero be placed in the timestamp
 2215                          * echo reply when ts_recent isn't valid.  The
 2216                          * age isn't reset until we get a valid ts_recent
 2217                          * because we don't want out-of-order segments to be
 2218                          * dropped when ts_recent is old.
 2219                          */
 2220                         tp->ts_recent = 0;
 2221                 } else {
 2222                         TCPSTAT_INC(tcps_rcvduppack);
 2223                         TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
 2224                         TCPSTAT_INC(tcps_pawsdrop);
 2225                         if (tlen)
 2226                                 goto dropafterack;
 2227                         goto drop;
 2228                 }
 2229         }
 2230 
 2231         /*
 2232          * In the SYN-RECEIVED state, validate that the packet belongs to
 2233          * this connection before trimming the data to fit the receive
 2234          * window.  Check the sequence number versus IRS since we know
 2235          * the sequence numbers haven't wrapped.  This is a partial fix
 2236          * for the "LAND" DoS attack.
 2237          */
 2238         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
 2239                 rstreason = BANDLIM_RST_OPENPORT;
 2240                 goto dropwithreset;
 2241         }
 2242 
 2243         todrop = tp->rcv_nxt - th->th_seq;
 2244         if (todrop > 0) {
 2245                 if (thflags & TH_SYN) {
 2246                         thflags &= ~TH_SYN;
 2247                         th->th_seq++;
 2248                         if (th->th_urp > 1)
 2249                                 th->th_urp--;
 2250                         else
 2251                                 thflags &= ~TH_URG;
 2252                         todrop--;
 2253                 }
 2254                 /*
 2255                  * Following if statement from Stevens, vol. 2, p. 960.
 2256                  */
 2257                 if (todrop > tlen
 2258                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
 2259                         /*
 2260                          * Any valid FIN must be to the left of the window.
 2261                          * At this point the FIN must be a duplicate or out
 2262                          * of sequence; drop it.
 2263                          */
 2264                         thflags &= ~TH_FIN;
 2265 
 2266                         /*
 2267                          * Send an ACK to resynchronize and drop any data.
 2268                          * But keep on processing for RST or ACK.
 2269                          */
 2270                         tp->t_flags |= TF_ACKNOW;
 2271                         todrop = tlen;
 2272                         TCPSTAT_INC(tcps_rcvduppack);
 2273                         TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
 2274                 } else {
 2275                         TCPSTAT_INC(tcps_rcvpartduppack);
 2276                         TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
 2277                 }
 2278                 drop_hdrlen += todrop;  /* drop from the top afterwards */
 2279                 th->th_seq += todrop;
 2280                 tlen -= todrop;
 2281                 if (th->th_urp > todrop)
 2282                         th->th_urp -= todrop;
 2283                 else {
 2284                         thflags &= ~TH_URG;
 2285                         th->th_urp = 0;
 2286                 }
 2287         }
 2288 
 2289         /*
 2290          * If new data are received on a connection after the
 2291          * user processes are gone, then RST the other end.
 2292          */
 2293         if ((so->so_state & SS_NOFDREF) &&
 2294             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
 2295                 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
 2296                     "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
 2297                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 2298 
 2299                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
 2300                         log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
 2301                             "after socket was closed, "
 2302                             "sending RST and removing tcpcb\n",
 2303                             s, __func__, tcpstates[tp->t_state], tlen);
 2304                         free(s, M_TCPLOG);
 2305                 }
 2306                 tp = tcp_close(tp);
 2307                 TCPSTAT_INC(tcps_rcvafterclose);
 2308                 rstreason = BANDLIM_UNLIMITED;
 2309                 goto dropwithreset;
 2310         }
 2311 
 2312         /*
 2313          * If segment ends after window, drop trailing data
 2314          * (and PUSH and FIN); if nothing left, just ACK.
 2315          */
 2316         todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
 2317         if (todrop > 0) {
 2318                 TCPSTAT_INC(tcps_rcvpackafterwin);
 2319                 if (todrop >= tlen) {
 2320                         TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
 2321                         /*
 2322                          * If window is closed can only take segments at
 2323                          * window edge, and have to drop data and PUSH from
 2324                          * incoming segments.  Continue processing, but
 2325                          * remember to ack.  Otherwise, drop segment
 2326                          * and ack.
 2327                          */
 2328                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
 2329                                 tp->t_flags |= TF_ACKNOW;
 2330                                 TCPSTAT_INC(tcps_rcvwinprobe);
 2331                         } else
 2332                                 goto dropafterack;
 2333                 } else
 2334                         TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
 2335                 m_adj(m, -todrop);
 2336                 tlen -= todrop;
 2337                 thflags &= ~(TH_PUSH|TH_FIN);
 2338         }
 2339 
 2340         /*
 2341          * If last ACK falls within this segment's sequence numbers,
 2342          * record its timestamp.
 2343          * NOTE: 
 2344          * 1) That the test incorporates suggestions from the latest
 2345          *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
 2346          * 2) That updating only on newer timestamps interferes with
 2347          *    our earlier PAWS tests, so this check should be solely
 2348          *    predicated on the sequence space of this segment.
 2349          * 3) That we modify the segment boundary check to be 
 2350          *        Last.ACK.Sent <= SEG.SEQ + SEG.Len  
 2351          *    instead of RFC1323's
 2352          *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
 2353          *    This modified check allows us to overcome RFC1323's
 2354          *    limitations as described in Stevens TCP/IP Illustrated
 2355          *    Vol. 2 p.869. In such cases, we can still calculate the
 2356          *    RTT correctly when RCV.NXT == Last.ACK.Sent.
 2357          */
 2358         if ((to.to_flags & TOF_TS) != 0 &&
 2359             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
 2360             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
 2361                 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
 2362                 tp->ts_recent_age = tcp_ts_getticks();
 2363                 tp->ts_recent = to.to_tsval;
 2364         }
 2365 
 2366         /*
 2367          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
 2368          * flag is on (half-synchronized state), then queue data for
 2369          * later processing; else drop segment and return.
 2370          */
 2371         if ((thflags & TH_ACK) == 0) {
 2372                 if (tp->t_state == TCPS_SYN_RECEIVED ||
 2373                     (tp->t_flags & TF_NEEDSYN)) {
 2374 #ifdef TCP_RFC7413
 2375                         if (tp->t_state == TCPS_SYN_RECEIVED &&
 2376                             tp->t_flags & TF_FASTOPEN) {
 2377                                 tp->snd_wnd = tiwin;
 2378                                 cc_conn_init(tp);
 2379                         }
 2380 #endif
 2381                         goto step6;
 2382                 } else if (tp->t_flags & TF_ACKNOW)
 2383                         goto dropafterack;
 2384                 else
 2385                         goto drop;
 2386         }
 2387 
 2388         /*
 2389          * Ack processing.
 2390          */
 2391         switch (tp->t_state) {
 2392 
 2393         /*
 2394          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
 2395          * ESTABLISHED state and continue processing.
 2396          * The ACK was checked above.
 2397          */
 2398         case TCPS_SYN_RECEIVED:
 2399 
 2400                 TCPSTAT_INC(tcps_connects);
 2401                 soisconnected(so);
 2402                 /* Do window scaling? */
 2403                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 2404                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 2405                         tp->rcv_scale = tp->request_r_scale;
 2406                         tp->snd_wnd = tiwin;
 2407                 }
 2408                 /*
 2409                  * Make transitions:
 2410                  *      SYN-RECEIVED  -> ESTABLISHED
 2411                  *      SYN-RECEIVED* -> FIN-WAIT-1
 2412                  */
 2413                 tp->t_starttime = ticks;
 2414                 if (tp->t_flags & TF_NEEDFIN) {
 2415                         tcp_state_change(tp, TCPS_FIN_WAIT_1);
 2416                         tp->t_flags &= ~TF_NEEDFIN;
 2417                 } else {
 2418                         tcp_state_change(tp, TCPS_ESTABLISHED);
 2419                         TCP_PROBE5(accept__established, NULL, tp,
 2420                             mtod(m, const char *), tp, th);
 2421 #ifdef TCP_RFC7413
 2422                         if (tp->t_tfo_pending) {
 2423                                 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
 2424                                 tp->t_tfo_pending = NULL;
 2425 
 2426                                 /*
 2427                                  * Account for the ACK of our SYN prior to
 2428                                  * regular ACK processing below.
 2429                                  */ 
 2430                                 tp->snd_una++;
 2431                         }
 2432                         /*
 2433                          * TFO connections call cc_conn_init() during SYN
 2434                          * processing.  Calling it again here for such
 2435                          * connections is not harmless as it would undo the
 2436                          * snd_cwnd reduction that occurs when a TFO SYN|ACK
 2437                          * is retransmitted.
 2438                          */
 2439                         if (!(tp->t_flags & TF_FASTOPEN))
 2440 #endif
 2441                                 cc_conn_init(tp);
 2442                         tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
 2443                 }
 2444                 /*
 2445                  * If segment contains data or ACK, will call tcp_reass()
 2446                  * later; if not, do so now to pass queued data to user.
 2447                  */
 2448                 if (tlen == 0 && (thflags & TH_FIN) == 0)
 2449                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
 2450                             (struct mbuf *)0);
 2451                 tp->snd_wl1 = th->th_seq - 1;
 2452                 /* FALLTHROUGH */
 2453 
 2454         /*
 2455          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
 2456          * ACKs.  If the ack is in the range
 2457          *      tp->snd_una < th->th_ack <= tp->snd_max
 2458          * then advance tp->snd_una to th->th_ack and drop
 2459          * data from the retransmission queue.  If this ACK reflects
 2460          * more up to date window information we update our window information.
 2461          */
 2462         case TCPS_ESTABLISHED:
 2463         case TCPS_FIN_WAIT_1:
 2464         case TCPS_FIN_WAIT_2:
 2465         case TCPS_CLOSE_WAIT:
 2466         case TCPS_CLOSING:
 2467         case TCPS_LAST_ACK:
 2468                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
 2469                         TCPSTAT_INC(tcps_rcvacktoomuch);
 2470                         goto dropafterack;
 2471                 }
 2472                 if ((tp->t_flags & TF_SACK_PERMIT) &&
 2473                     ((to.to_flags & TOF_SACK) ||
 2474                      !TAILQ_EMPTY(&tp->snd_holes)))
 2475                         sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
 2476                 else
 2477                         /*
 2478                          * Reset the value so that previous (valid) value
 2479                          * from the last ack with SACK doesn't get used.
 2480                          */
 2481                         tp->sackhint.sacked_bytes = 0;
 2482 
 2483                 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
 2484                 hhook_run_tcp_est_in(tp, th, &to);
 2485 
 2486                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
 2487                         u_int maxseg;
 2488 
 2489                         maxseg = tcp_maxseg(tp);
 2490                         if (tlen == 0 &&
 2491                             (tiwin == tp->snd_wnd ||
 2492                             (tp->t_flags & TF_SACK_PERMIT))) {
 2493                                 /*
 2494                                  * If this is the first time we've seen a
 2495                                  * FIN from the remote, this is not a
 2496                                  * duplicate and it needs to be processed
 2497                                  * normally.  This happens during a
 2498                                  * simultaneous close.
 2499                                  */
 2500                                 if ((thflags & TH_FIN) &&
 2501                                     (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
 2502                                         tp->t_dupacks = 0;
 2503                                         break;
 2504                                 }
 2505                                 TCPSTAT_INC(tcps_rcvdupack);
 2506                                 /*
 2507                                  * If we have outstanding data (other than
 2508                                  * a window probe), this is a completely
 2509                                  * duplicate ack (ie, window info didn't
 2510                                  * change and FIN isn't set),
 2511                                  * the ack is the biggest we've
 2512                                  * seen and we've seen exactly our rexmt
 2513                                  * threshhold of them, assume a packet
 2514                                  * has been dropped and retransmit it.
 2515                                  * Kludge snd_nxt & the congestion
 2516                                  * window so we send only this one
 2517                                  * packet.
 2518                                  *
 2519                                  * We know we're losing at the current
 2520                                  * window size so do congestion avoidance
 2521                                  * (set ssthresh to half the current window
 2522                                  * and pull our congestion window back to
 2523                                  * the new ssthresh).
 2524                                  *
 2525                                  * Dup acks mean that packets have left the
 2526                                  * network (they're now cached at the receiver)
 2527                                  * so bump cwnd by the amount in the receiver
 2528                                  * to keep a constant cwnd packets in the
 2529                                  * network.
 2530                                  *
 2531                                  * When using TCP ECN, notify the peer that
 2532                                  * we reduced the cwnd.
 2533                                  */
 2534                                 /*
 2535                                  * Following 2 kinds of acks should not affect
 2536                                  * dupack counting:
 2537                                  * 1) Old acks
 2538                                  * 2) Acks with SACK but without any new SACK
 2539                                  * information in them. These could result from
 2540                                  * any anomaly in the network like a switch
 2541                                  * duplicating packets or a possible DoS attack.
 2542                                  */
 2543                                 if (th->th_ack != tp->snd_una ||
 2544                                     ((tp->t_flags & TF_SACK_PERMIT) &&
 2545                                     !sack_changed))
 2546                                         break;
 2547                                 else if (!tcp_timer_active(tp, TT_REXMT))
 2548                                         tp->t_dupacks = 0;
 2549                                 else if (++tp->t_dupacks > tcprexmtthresh ||
 2550                                      IN_FASTRECOVERY(tp->t_flags)) {
 2551                                         cc_ack_received(tp, th, CC_DUPACK);
 2552                                         if ((tp->t_flags & TF_SACK_PERMIT) &&
 2553                                             IN_FASTRECOVERY(tp->t_flags)) {
 2554                                                 int awnd;
 2555                                                 
 2556                                                 /*
 2557                                                  * Compute the amount of data in flight first.
 2558                                                  * We can inject new data into the pipe iff 
 2559                                                  * we have less than 1/2 the original window's
 2560                                                  * worth of data in flight.
 2561                                                  */
 2562                                                 if (V_tcp_do_rfc6675_pipe)
 2563                                                         awnd = tcp_compute_pipe(tp);
 2564                                                 else
 2565                                                         awnd = (tp->snd_nxt - tp->snd_fack) +
 2566                                                                 tp->sackhint.sack_bytes_rexmit;
 2567 
 2568                                                 if (awnd < tp->snd_ssthresh) {
 2569                                                         tp->snd_cwnd += maxseg;
 2570                                                         if (tp->snd_cwnd > tp->snd_ssthresh)
 2571                                                                 tp->snd_cwnd = tp->snd_ssthresh;
 2572                                                 }
 2573                                         } else
 2574                                                 tp->snd_cwnd += maxseg;
 2575                                         (void) tp->t_fb->tfb_tcp_output(tp);
 2576                                         goto drop;
 2577                                 } else if (tp->t_dupacks == tcprexmtthresh) {
 2578                                         tcp_seq onxt = tp->snd_nxt;
 2579 
 2580                                         /*
 2581                                          * If we're doing sack, check to
 2582                                          * see if we're already in sack
 2583                                          * recovery. If we're not doing sack,
 2584                                          * check to see if we're in newreno
 2585                                          * recovery.
 2586                                          */
 2587                                         if (tp->t_flags & TF_SACK_PERMIT) {
 2588                                                 if (IN_FASTRECOVERY(tp->t_flags)) {
 2589                                                         tp->t_dupacks = 0;
 2590                                                         break;
 2591                                                 }
 2592                                         } else {
 2593                                                 if (SEQ_LEQ(th->th_ack,
 2594                                                     tp->snd_recover)) {
 2595                                                         tp->t_dupacks = 0;
 2596                                                         break;
 2597                                                 }
 2598                                         }
 2599                                         /* Congestion signal before ack. */
 2600                                         cc_cong_signal(tp, th, CC_NDUPACK);
 2601                                         cc_ack_received(tp, th, CC_DUPACK);
 2602                                         tcp_timer_activate(tp, TT_REXMT, 0);
 2603                                         tp->t_rtttime = 0;
 2604                                         if (tp->t_flags & TF_SACK_PERMIT) {
 2605                                                 TCPSTAT_INC(
 2606                                                     tcps_sack_recovery_episode);
 2607                                                 tp->sack_newdata = tp->snd_nxt;
 2608                                                 tp->snd_cwnd = maxseg;
 2609                                                 (void) tp->t_fb->tfb_tcp_output(tp);
 2610                                                 goto drop;
 2611                                         }
 2612                                         tp->snd_nxt = th->th_ack;
 2613                                         tp->snd_cwnd = maxseg;
 2614                                         (void) tp->t_fb->tfb_tcp_output(tp);
 2615                                         KASSERT(tp->snd_limited <= 2,
 2616                                             ("%s: tp->snd_limited too big",
 2617                                             __func__));
 2618                                         tp->snd_cwnd = tp->snd_ssthresh +
 2619                                              maxseg *
 2620                                              (tp->t_dupacks - tp->snd_limited);
 2621                                         if (SEQ_GT(onxt, tp->snd_nxt))
 2622                                                 tp->snd_nxt = onxt;
 2623                                         goto drop;
 2624                                 } else if (V_tcp_do_rfc3042) {
 2625                                         /*
 2626                                          * Process first and second duplicate
 2627                                          * ACKs. Each indicates a segment
 2628                                          * leaving the network, creating room
 2629                                          * for more. Make sure we can send a
 2630                                          * packet on reception of each duplicate
 2631                                          * ACK by increasing snd_cwnd by one
 2632                                          * segment. Restore the original
 2633                                          * snd_cwnd after packet transmission.
 2634                                          */
 2635                                         cc_ack_received(tp, th, CC_DUPACK);
 2636                                         u_long oldcwnd = tp->snd_cwnd;
 2637                                         tcp_seq oldsndmax = tp->snd_max;
 2638                                         u_int sent;
 2639                                         int avail;
 2640 
 2641                                         KASSERT(tp->t_dupacks == 1 ||
 2642                                             tp->t_dupacks == 2,
 2643                                             ("%s: dupacks not 1 or 2",
 2644                                             __func__));
 2645                                         if (tp->t_dupacks == 1)
 2646                                                 tp->snd_limited = 0;
 2647                                         tp->snd_cwnd =
 2648                                             (tp->snd_nxt - tp->snd_una) +
 2649                                             (tp->t_dupacks - tp->snd_limited) *
 2650                                             maxseg;
 2651                                         /*
 2652                                          * Only call tcp_output when there
 2653                                          * is new data available to be sent.
 2654                                          * Otherwise we would send pure ACKs.
 2655                                          */
 2656                                         SOCKBUF_LOCK(&so->so_snd);
 2657                                         avail = sbavail(&so->so_snd) -
 2658                                             (tp->snd_nxt - tp->snd_una);
 2659                                         SOCKBUF_UNLOCK(&so->so_snd);
 2660                                         if (avail > 0)
 2661                                                 (void) tp->t_fb->tfb_tcp_output(tp);
 2662                                         sent = tp->snd_max - oldsndmax;
 2663                                         if (sent > maxseg) {
 2664                                                 KASSERT((tp->t_dupacks == 2 &&
 2665                                                     tp->snd_limited == 0) ||
 2666                                                    (sent == maxseg + 1 &&
 2667                                                     tp->t_flags & TF_SENTFIN),
 2668                                                     ("%s: sent too much",
 2669                                                     __func__));
 2670                                                 tp->snd_limited = 2;
 2671                                         } else if (sent > 0)
 2672                                                 ++tp->snd_limited;
 2673                                         tp->snd_cwnd = oldcwnd;
 2674                                         goto drop;
 2675                                 }
 2676                         }
 2677                         break;
 2678                 } else {
 2679                         /*
 2680                          * This ack is advancing the left edge, reset the
 2681                          * counter.
 2682                          */
 2683                         tp->t_dupacks = 0;
 2684                         /*
 2685                          * If this ack also has new SACK info, increment the
 2686                          * counter as per rfc6675.
 2687                          */
 2688                         if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
 2689                                 tp->t_dupacks++;
 2690                 }
 2691 
 2692                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
 2693                     ("%s: th_ack <= snd_una", __func__));
 2694 
 2695                 /*
 2696                  * If the congestion window was inflated to account
 2697                  * for the other side's cached packets, retract it.
 2698                  */
 2699                 if (IN_FASTRECOVERY(tp->t_flags)) {
 2700                         if (SEQ_LT(th->th_ack, tp->snd_recover)) {
 2701                                 if (tp->t_flags & TF_SACK_PERMIT)
 2702                                         tcp_sack_partialack(tp, th);
 2703                                 else
 2704                                         tcp_newreno_partial_ack(tp, th);
 2705                         } else
 2706                                 cc_post_recovery(tp, th);
 2707                 }
 2708                 /*
 2709                  * If we reach this point, ACK is not a duplicate,
 2710                  *     i.e., it ACKs something we sent.
 2711                  */
 2712                 if (tp->t_flags & TF_NEEDSYN) {
 2713                         /*
 2714                          * T/TCP: Connection was half-synchronized, and our
 2715                          * SYN has been ACK'd (so connection is now fully
 2716                          * synchronized).  Go to non-starred state,
 2717                          * increment snd_una for ACK of SYN, and check if
 2718                          * we can do window scaling.
 2719                          */
 2720                         tp->t_flags &= ~TF_NEEDSYN;
 2721                         tp->snd_una++;
 2722                         /* Do window scaling? */
 2723                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
 2724                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
 2725                                 tp->rcv_scale = tp->request_r_scale;
 2726                                 /* Send window already scaled. */
 2727                         }
 2728                 }
 2729 
 2730 process_ACK:
 2731                 INP_WLOCK_ASSERT(tp->t_inpcb);
 2732 
 2733                 acked = BYTES_THIS_ACK(tp, th);
 2734                 TCPSTAT_INC(tcps_rcvackpack);
 2735                 TCPSTAT_ADD(tcps_rcvackbyte, acked);
 2736 
 2737                 /*
 2738                  * If we just performed our first retransmit, and the ACK
 2739                  * arrives within our recovery window, then it was a mistake
 2740                  * to do the retransmit in the first place.  Recover our
 2741                  * original cwnd and ssthresh, and proceed to transmit where
 2742                  * we left off.
 2743                  */
 2744                 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
 2745                     (int)(ticks - tp->t_badrxtwin) < 0)
 2746                         cc_cong_signal(tp, th, CC_RTO_ERR);
 2747 
 2748                 /*
 2749                  * If we have a timestamp reply, update smoothed
 2750                  * round trip time.  If no timestamp is present but
 2751                  * transmit timer is running and timed sequence
 2752                  * number was acked, update smoothed round trip time.
 2753                  * Since we now have an rtt measurement, cancel the
 2754                  * timer backoff (cf., Phil Karn's retransmit alg.).
 2755                  * Recompute the initial retransmit timer.
 2756                  *
 2757                  * Some boxes send broken timestamp replies
 2758                  * during the SYN+ACK phase, ignore
 2759                  * timestamps of 0 or we could calculate a
 2760                  * huge RTT and blow up the retransmit timer.
 2761                  */
 2762                 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
 2763                         u_int t;
 2764 
 2765                         t = tcp_ts_getticks() - to.to_tsecr;
 2766                         if (!tp->t_rttlow || tp->t_rttlow > t)
 2767                                 tp->t_rttlow = t;
 2768                         tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
 2769                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
 2770                         if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
 2771                                 tp->t_rttlow = ticks - tp->t_rtttime;
 2772                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
 2773                 }
 2774 
 2775                 /*
 2776                  * If all outstanding data is acked, stop retransmit
 2777                  * timer and remember to restart (more output or persist).
 2778                  * If there is more data to be acked, restart retransmit
 2779                  * timer, using current (possibly backed-off) value.
 2780                  */
 2781                 if (th->th_ack == tp->snd_max) {
 2782                         tcp_timer_activate(tp, TT_REXMT, 0);
 2783                         needoutput = 1;
 2784                 } else if (!tcp_timer_active(tp, TT_PERSIST))
 2785                         tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
 2786 
 2787                 /*
 2788                  * If no data (only SYN) was ACK'd,
 2789                  *    skip rest of ACK processing.
 2790                  */
 2791                 if (acked == 0)
 2792                         goto step6;
 2793 
 2794                 /*
 2795                  * Let the congestion control algorithm update congestion
 2796                  * control related information. This typically means increasing
 2797                  * the congestion window.
 2798                  */
 2799                 cc_ack_received(tp, th, CC_ACK);
 2800 
 2801                 SOCKBUF_LOCK(&so->so_snd);
 2802                 if (acked > sbavail(&so->so_snd)) {
 2803                         tp->snd_wnd -= sbavail(&so->so_snd);
 2804                         mfree = sbcut_locked(&so->so_snd,
 2805                             (int)sbavail(&so->so_snd));
 2806                         ourfinisacked = 1;
 2807                 } else {
 2808                         mfree = sbcut_locked(&so->so_snd, acked);
 2809                         tp->snd_wnd -= acked;
 2810                         ourfinisacked = 0;
 2811                 }
 2812                 /* NB: sowwakeup_locked() does an implicit unlock. */
 2813                 sowwakeup_locked(so);
 2814                 m_freem(mfree);
 2815                 /* Detect una wraparound. */
 2816                 if (!IN_RECOVERY(tp->t_flags) &&
 2817                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
 2818                     SEQ_LEQ(th->th_ack, tp->snd_recover))
 2819                         tp->snd_recover = th->th_ack - 1;
 2820                 /* XXXLAS: Can this be moved up into cc_post_recovery? */
 2821                 if (IN_RECOVERY(tp->t_flags) &&
 2822                     SEQ_GEQ(th->th_ack, tp->snd_recover)) {
 2823                         EXIT_RECOVERY(tp->t_flags);
 2824                 }
 2825                 tp->snd_una = th->th_ack;
 2826                 if (tp->t_flags & TF_SACK_PERMIT) {
 2827                         if (SEQ_GT(tp->snd_una, tp->snd_recover))
 2828                                 tp->snd_recover = tp->snd_una;
 2829                 }
 2830                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
 2831                         tp->snd_nxt = tp->snd_una;
 2832 
 2833                 switch (tp->t_state) {
 2834 
 2835                 /*
 2836                  * In FIN_WAIT_1 STATE in addition to the processing
 2837                  * for the ESTABLISHED state if our FIN is now acknowledged
 2838                  * then enter FIN_WAIT_2.
 2839                  */
 2840                 case TCPS_FIN_WAIT_1:
 2841                         if (ourfinisacked) {
 2842                                 /*
 2843                                  * If we can't receive any more
 2844                                  * data, then closing user can proceed.
 2845                                  * Starting the timer is contrary to the
 2846                                  * specification, but if we don't get a FIN
 2847                                  * we'll hang forever.
 2848                                  *
 2849                                  * XXXjl:
 2850                                  * we should release the tp also, and use a
 2851                                  * compressed state.
 2852                                  */
 2853                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
 2854                                         soisdisconnected(so);
 2855                                         tcp_timer_activate(tp, TT_2MSL,
 2856                                             (tcp_fast_finwait2_recycle ?
 2857                                             tcp_finwait2_timeout :
 2858                                             TP_MAXIDLE(tp)));
 2859                                 }
 2860                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
 2861                         }
 2862                         break;
 2863 
 2864                 /*
 2865                  * In CLOSING STATE in addition to the processing for
 2866                  * the ESTABLISHED state if the ACK acknowledges our FIN
 2867                  * then enter the TIME-WAIT state, otherwise ignore
 2868                  * the segment.
 2869                  */
 2870                 case TCPS_CLOSING:
 2871                         if (ourfinisacked) {
 2872                                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 2873                                 tcp_twstart(tp);
 2874                                 INP_INFO_RUNLOCK(&V_tcbinfo);
 2875                                 m_freem(m);
 2876                                 return;
 2877                         }
 2878                         break;
 2879 
 2880                 /*
 2881                  * In LAST_ACK, we may still be waiting for data to drain
 2882                  * and/or to be acked, as well as for the ack of our FIN.
 2883                  * If our FIN is now acknowledged, delete the TCB,
 2884                  * enter the closed state and return.
 2885                  */
 2886                 case TCPS_LAST_ACK:
 2887                         if (ourfinisacked) {
 2888                                 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 2889                                 tp = tcp_close(tp);
 2890                                 goto drop;
 2891                         }
 2892                         break;
 2893                 }
 2894         }
 2895 
 2896 step6:
 2897         INP_WLOCK_ASSERT(tp->t_inpcb);
 2898 
 2899         /*
 2900          * Update window information.
 2901          * Don't look at window if no ACK: TAC's send garbage on first SYN.
 2902          */
 2903         if ((thflags & TH_ACK) &&
 2904             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
 2905             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
 2906              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
 2907                 /* keep track of pure window updates */
 2908                 if (tlen == 0 &&
 2909                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
 2910                         TCPSTAT_INC(tcps_rcvwinupd);
 2911                 tp->snd_wnd = tiwin;
 2912                 tp->snd_wl1 = th->th_seq;
 2913                 tp->snd_wl2 = th->th_ack;
 2914                 if (tp->snd_wnd > tp->max_sndwnd)
 2915                         tp->max_sndwnd = tp->snd_wnd;
 2916                 needoutput = 1;
 2917         }
 2918 
 2919         /*
 2920          * Process segments with URG.
 2921          */
 2922         if ((thflags & TH_URG) && th->th_urp &&
 2923             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2924                 /*
 2925                  * This is a kludge, but if we receive and accept
 2926                  * random urgent pointers, we'll crash in
 2927                  * soreceive.  It's hard to imagine someone
 2928                  * actually wanting to send this much urgent data.
 2929                  */
 2930                 SOCKBUF_LOCK(&so->so_rcv);
 2931                 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
 2932                         th->th_urp = 0;                 /* XXX */
 2933                         thflags &= ~TH_URG;             /* XXX */
 2934                         SOCKBUF_UNLOCK(&so->so_rcv);    /* XXX */
 2935                         goto dodata;                    /* XXX */
 2936                 }
 2937                 /*
 2938                  * If this segment advances the known urgent pointer,
 2939                  * then mark the data stream.  This should not happen
 2940                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
 2941                  * a FIN has been received from the remote side.
 2942                  * In these states we ignore the URG.
 2943                  *
 2944                  * According to RFC961 (Assigned Protocols),
 2945                  * the urgent pointer points to the last octet
 2946                  * of urgent data.  We continue, however,
 2947                  * to consider it to indicate the first octet
 2948                  * of data past the urgent section as the original
 2949                  * spec states (in one of two places).
 2950                  */
 2951                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
 2952                         tp->rcv_up = th->th_seq + th->th_urp;
 2953                         so->so_oobmark = sbavail(&so->so_rcv) +
 2954                             (tp->rcv_up - tp->rcv_nxt) - 1;
 2955                         if (so->so_oobmark == 0)
 2956                                 so->so_rcv.sb_state |= SBS_RCVATMARK;
 2957                         sohasoutofband(so);
 2958                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
 2959                 }
 2960                 SOCKBUF_UNLOCK(&so->so_rcv);
 2961                 /*
 2962                  * Remove out of band data so doesn't get presented to user.
 2963                  * This can happen independent of advancing the URG pointer,
 2964                  * but if two URG's are pending at once, some out-of-band
 2965                  * data may creep in... ick.
 2966                  */
 2967                 if (th->th_urp <= (u_long)tlen &&
 2968                     !(so->so_options & SO_OOBINLINE)) {
 2969                         /* hdr drop is delayed */
 2970                         tcp_pulloutofband(so, th, m, drop_hdrlen);
 2971                 }
 2972         } else {
 2973                 /*
 2974                  * If no out of band data is expected,
 2975                  * pull receive urgent pointer along
 2976                  * with the receive window.
 2977                  */
 2978                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
 2979                         tp->rcv_up = tp->rcv_nxt;
 2980         }
 2981 dodata:                                                 /* XXX */
 2982         INP_WLOCK_ASSERT(tp->t_inpcb);
 2983 
 2984         /*
 2985          * Process the segment text, merging it into the TCP sequencing queue,
 2986          * and arranging for acknowledgment of receipt if necessary.
 2987          * This process logically involves adjusting tp->rcv_wnd as data
 2988          * is presented to the user (this happens in tcp_usrreq.c,
 2989          * case PRU_RCVD).  If a FIN has already been received on this
 2990          * connection then we just ignore the text.
 2991          */
 2992         tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
 2993                    (tp->t_flags & TF_FASTOPEN));
 2994         if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
 2995             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 2996                 tcp_seq save_start = th->th_seq;
 2997                 m_adj(m, drop_hdrlen);  /* delayed header drop */
 2998                 /*
 2999                  * Insert segment which includes th into TCP reassembly queue
 3000                  * with control block tp.  Set thflags to whether reassembly now
 3001                  * includes a segment with FIN.  This handles the common case
 3002                  * inline (segment is the next to be received on an established
 3003                  * connection, and the queue is empty), avoiding linkage into
 3004                  * and removal from the queue and repetition of various
 3005                  * conversions.
 3006                  * Set DELACK for segments received in order, but ack
 3007                  * immediately when segments are out of order (so
 3008                  * fast retransmit can work).
 3009                  */
 3010                 if (th->th_seq == tp->rcv_nxt &&
 3011                     LIST_EMPTY(&tp->t_segq) &&
 3012                     (TCPS_HAVEESTABLISHED(tp->t_state) ||
 3013                      tfo_syn)) {
 3014                         if (DELAY_ACK(tp, tlen) || tfo_syn)
 3015                                 tp->t_flags |= TF_DELACK;
 3016                         else
 3017                                 tp->t_flags |= TF_ACKNOW;
 3018                         tp->rcv_nxt += tlen;
 3019                         thflags = th->th_flags & TH_FIN;
 3020                         TCPSTAT_INC(tcps_rcvpack);
 3021                         TCPSTAT_ADD(tcps_rcvbyte, tlen);
 3022                         SOCKBUF_LOCK(&so->so_rcv);
 3023                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
 3024                                 m_freem(m);
 3025                         else
 3026                                 sbappendstream_locked(&so->so_rcv, m, 0);
 3027                         /* NB: sorwakeup_locked() does an implicit unlock. */
 3028                         sorwakeup_locked(so);
 3029                 } else {
 3030                         /*
 3031                          * XXX: Due to the header drop above "th" is
 3032                          * theoretically invalid by now.  Fortunately
 3033                          * m_adj() doesn't actually frees any mbufs
 3034                          * when trimming from the head.
 3035                          */
 3036                         thflags = tcp_reass(tp, th, &tlen, m);
 3037                         tp->t_flags |= TF_ACKNOW;
 3038                 }
 3039                 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
 3040                         tcp_update_sack_list(tp, save_start, save_start + tlen);
 3041 #if 0
 3042                 /*
 3043                  * Note the amount of data that peer has sent into
 3044                  * our window, in order to estimate the sender's
 3045                  * buffer size.
 3046                  * XXX: Unused.
 3047                  */
 3048                 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
 3049                         len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
 3050                 else
 3051                         len = so->so_rcv.sb_hiwat;
 3052 #endif
 3053         } else {
 3054                 m_freem(m);
 3055                 thflags &= ~TH_FIN;
 3056         }
 3057 
 3058         /*
 3059          * If FIN is received ACK the FIN and let the user know
 3060          * that the connection is closing.
 3061          */
 3062         if (thflags & TH_FIN) {
 3063                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
 3064                         socantrcvmore(so);
 3065                         /*
 3066                          * If connection is half-synchronized
 3067                          * (ie NEEDSYN flag on) then delay ACK,
 3068                          * so it may be piggybacked when SYN is sent.
 3069                          * Otherwise, since we received a FIN then no
 3070                          * more input can be expected, send ACK now.
 3071                          */
 3072                         if (tp->t_flags & TF_NEEDSYN)
 3073                                 tp->t_flags |= TF_DELACK;
 3074                         else
 3075                                 tp->t_flags |= TF_ACKNOW;
 3076                         tp->rcv_nxt++;
 3077                 }
 3078                 switch (tp->t_state) {
 3079 
 3080                 /*
 3081                  * In SYN_RECEIVED and ESTABLISHED STATES
 3082                  * enter the CLOSE_WAIT state.
 3083                  */
 3084                 case TCPS_SYN_RECEIVED:
 3085                         tp->t_starttime = ticks;
 3086                         /* FALLTHROUGH */
 3087                 case TCPS_ESTABLISHED:
 3088                         tcp_state_change(tp, TCPS_CLOSE_WAIT);
 3089                         break;
 3090 
 3091                 /*
 3092                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
 3093                  * enter the CLOSING state.
 3094                  */
 3095                 case TCPS_FIN_WAIT_1:
 3096                         tcp_state_change(tp, TCPS_CLOSING);
 3097                         break;
 3098 
 3099                 /*
 3100                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
 3101                  * starting the time-wait timer, turning off the other
 3102                  * standard timers.
 3103                  */
 3104                 case TCPS_FIN_WAIT_2:
 3105                         INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
 3106                         KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
 3107                             "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
 3108                             ti_locked));
 3109 
 3110                         tcp_twstart(tp);
 3111                         INP_INFO_RUNLOCK(&V_tcbinfo);
 3112                         return;
 3113                 }
 3114         }
 3115         if (ti_locked == TI_RLOCKED)
 3116                 INP_INFO_RUNLOCK(&V_tcbinfo);
 3117         ti_locked = TI_UNLOCKED;
 3118 
 3119 #ifdef TCPDEBUG
 3120         if (so->so_options & SO_DEBUG)
 3121                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
 3122                           &tcp_savetcp, 0);
 3123 #endif
 3124         TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
 3125 
 3126         /*
 3127          * Return any desired output.
 3128          */
 3129         if (needoutput || (tp->t_flags & TF_ACKNOW))
 3130                 (void) tp->t_fb->tfb_tcp_output(tp);
 3131 
 3132 check_delack:
 3133         KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
 3134             __func__, ti_locked));
 3135         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 3136         INP_WLOCK_ASSERT(tp->t_inpcb);
 3137 
 3138         if (tp->t_flags & TF_DELACK) {
 3139                 tp->t_flags &= ~TF_DELACK;
 3140                 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
 3141         }
 3142         INP_WUNLOCK(tp->t_inpcb);
 3143         return;
 3144 
 3145 dropafterack:
 3146         /*
 3147          * Generate an ACK dropping incoming segment if it occupies
 3148          * sequence space, where the ACK reflects our state.
 3149          *
 3150          * We can now skip the test for the RST flag since all
 3151          * paths to this code happen after packets containing
 3152          * RST have been dropped.
 3153          *
 3154          * In the SYN-RECEIVED state, don't send an ACK unless the
 3155          * segment we received passes the SYN-RECEIVED ACK test.
 3156          * If it fails send a RST.  This breaks the loop in the
 3157          * "LAND" DoS attack, and also prevents an ACK storm
 3158          * between two listening ports that have been sent forged
 3159          * SYN segments, each with the source address of the other.
 3160          */
 3161         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
 3162             (SEQ_GT(tp->snd_una, th->th_ack) ||
 3163              SEQ_GT(th->th_ack, tp->snd_max)) ) {
 3164                 rstreason = BANDLIM_RST_OPENPORT;
 3165                 goto dropwithreset;
 3166         }
 3167 #ifdef TCPDEBUG
 3168         if (so->so_options & SO_DEBUG)
 3169                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 3170                           &tcp_savetcp, 0);
 3171 #endif
 3172         TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
 3173         if (ti_locked == TI_RLOCKED)
 3174                 INP_INFO_RUNLOCK(&V_tcbinfo);
 3175         ti_locked = TI_UNLOCKED;
 3176 
 3177         tp->t_flags |= TF_ACKNOW;
 3178         (void) tp->t_fb->tfb_tcp_output(tp);
 3179         INP_WUNLOCK(tp->t_inpcb);
 3180         m_freem(m);
 3181         return;
 3182 
 3183 dropwithreset:
 3184         if (ti_locked == TI_RLOCKED)
 3185                 INP_INFO_RUNLOCK(&V_tcbinfo);
 3186         ti_locked = TI_UNLOCKED;
 3187 
 3188         if (tp != NULL) {
 3189                 tcp_dropwithreset(m, th, tp, tlen, rstreason);
 3190                 INP_WUNLOCK(tp->t_inpcb);
 3191         } else
 3192                 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
 3193         return;
 3194 
 3195 drop:
 3196         if (ti_locked == TI_RLOCKED) {
 3197                 INP_INFO_RUNLOCK(&V_tcbinfo);
 3198                 ti_locked = TI_UNLOCKED;
 3199         }
 3200 #ifdef INVARIANTS
 3201         else
 3202                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
 3203 #endif
 3204 
 3205         /*
 3206          * Drop space held by incoming segment and return.
 3207          */
 3208 #ifdef TCPDEBUG
 3209         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
 3210                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
 3211                           &tcp_savetcp, 0);
 3212 #endif
 3213         TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
 3214         if (tp != NULL)
 3215                 INP_WUNLOCK(tp->t_inpcb);
 3216         m_freem(m);
 3217 }
 3218 
 3219 /*
 3220  * Issue RST and make ACK acceptable to originator of segment.
 3221  * The mbuf must still include the original packet header.
 3222  * tp may be NULL.
 3223  */
 3224 void
 3225 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
 3226     int tlen, int rstreason)
 3227 {
 3228 #ifdef INET
 3229         struct ip *ip;
 3230 #endif
 3231 #ifdef INET6
 3232         struct ip6_hdr *ip6;
 3233 #endif
 3234 
 3235         if (tp != NULL) {
 3236                 INP_WLOCK_ASSERT(tp->t_inpcb);
 3237         }
 3238 
 3239         /* Don't bother if destination was broadcast/multicast. */
 3240         if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
 3241                 goto drop;
 3242 #ifdef INET6
 3243         if (mtod(m, struct ip *)->ip_v == 6) {
 3244                 ip6 = mtod(m, struct ip6_hdr *);
 3245                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
 3246                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
 3247                         goto drop;
 3248                 /* IPv6 anycast check is done at tcp6_input() */
 3249         }
 3250 #endif
 3251 #if defined(INET) && defined(INET6)
 3252         else
 3253 #endif
 3254 #ifdef INET
 3255         {
 3256                 ip = mtod(m, struct ip *);
 3257                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
 3258                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
 3259                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
 3260                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
 3261                         goto drop;
 3262         }
 3263 #endif
 3264 
 3265         /* Perform bandwidth limiting. */
 3266         if (badport_bandlim(rstreason) < 0)
 3267                 goto drop;
 3268 
 3269         /* tcp_respond consumes the mbuf chain. */
 3270         if (th->th_flags & TH_ACK) {
 3271                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
 3272                     th->th_ack, TH_RST);
 3273         } else {
 3274                 if (th->th_flags & TH_SYN)
 3275                         tlen++;
 3276                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
 3277                     (tcp_seq)0, TH_RST|TH_ACK);
 3278         }
 3279         return;
 3280 drop:
 3281         m_freem(m);
 3282 }
 3283 
 3284 /*
 3285  * Parse TCP options and place in tcpopt.
 3286  */
 3287 void
 3288 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
 3289 {
 3290         int opt, optlen;
 3291 
 3292         to->to_flags = 0;
 3293         for (; cnt > 0; cnt -= optlen, cp += optlen) {
 3294                 opt = cp[0];
 3295                 if (opt == TCPOPT_EOL)
 3296                         break;
 3297                 if (opt == TCPOPT_NOP)
 3298                         optlen = 1;
 3299                 else {
 3300                         if (cnt < 2)
 3301                                 break;
 3302                         optlen = cp[1];
 3303                         if (optlen < 2 || optlen > cnt)
 3304                                 break;
 3305                 }
 3306                 switch (opt) {
 3307                 case TCPOPT_MAXSEG:
 3308                         if (optlen != TCPOLEN_MAXSEG)
 3309                                 continue;
 3310                         if (!(flags & TO_SYN))
 3311                                 continue;
 3312                         to->to_flags |= TOF_MSS;
 3313                         bcopy((char *)cp + 2,
 3314                             (char *)&to->to_mss, sizeof(to->to_mss));
 3315                         to->to_mss = ntohs(to->to_mss);
 3316                         break;
 3317                 case TCPOPT_WINDOW:
 3318                         if (optlen != TCPOLEN_WINDOW)
 3319                                 continue;
 3320                         if (!(flags & TO_SYN))
 3321                                 continue;
 3322                         to->to_flags |= TOF_SCALE;
 3323                         to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
 3324                         break;
 3325                 case TCPOPT_TIMESTAMP:
 3326                         if (optlen != TCPOLEN_TIMESTAMP)
 3327                                 continue;
 3328                         to->to_flags |= TOF_TS;
 3329                         bcopy((char *)cp + 2,
 3330                             (char *)&to->to_tsval, sizeof(to->to_tsval));
 3331                         to->to_tsval = ntohl(to->to_tsval);
 3332                         bcopy((char *)cp + 6,
 3333                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
 3334                         to->to_tsecr = ntohl(to->to_tsecr);
 3335                         break;
 3336 #ifdef TCP_SIGNATURE
 3337                 /*
 3338                  * XXX In order to reply to a host which has set the
 3339                  * TCP_SIGNATURE option in its initial SYN, we have to
 3340                  * record the fact that the option was observed here
 3341                  * for the syncache code to perform the correct response.
 3342                  */
 3343                 case TCPOPT_SIGNATURE:
 3344                         if (optlen != TCPOLEN_SIGNATURE)
 3345                                 continue;
 3346                         to->to_flags |= TOF_SIGNATURE;
 3347                         to->to_signature = cp + 2;
 3348                         break;
 3349 #endif
 3350                 case TCPOPT_SACK_PERMITTED:
 3351                         if (optlen != TCPOLEN_SACK_PERMITTED)
 3352                                 continue;
 3353                         if (!(flags & TO_SYN))
 3354                                 continue;
 3355                         if (!V_tcp_do_sack)
 3356                                 continue;
 3357                         to->to_flags |= TOF_SACKPERM;
 3358                         break;
 3359                 case TCPOPT_SACK:
 3360                         if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
 3361                                 continue;
 3362                         if (flags & TO_SYN)
 3363                                 continue;
 3364                         to->to_flags |= TOF_SACK;
 3365                         to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
 3366                         to->to_sacks = cp + 2;
 3367                         TCPSTAT_INC(tcps_sack_rcv_blocks);
 3368                         break;
 3369 #ifdef TCP_RFC7413
 3370                 case TCPOPT_FAST_OPEN:
 3371                         if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
 3372                             (optlen < TCPOLEN_FAST_OPEN_MIN) &&
 3373                             (optlen > TCPOLEN_FAST_OPEN_MAX))
 3374                                 continue;
 3375                         if (!(flags & TO_SYN))
 3376                                 continue;
 3377                         if (!V_tcp_fastopen_enabled)
 3378                                 continue;
 3379                         to->to_flags |= TOF_FASTOPEN;
 3380                         to->to_tfo_len = optlen - 2;
 3381                         to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
 3382                         break;
 3383 #endif
 3384                 default:
 3385                         continue;
 3386                 }
 3387         }
 3388 }
 3389 
 3390 /*
 3391  * Pull out of band byte out of a segment so
 3392  * it doesn't appear in the user's data queue.
 3393  * It is still reflected in the segment length for
 3394  * sequencing purposes.
 3395  */
 3396 void
 3397 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
 3398     int off)
 3399 {
 3400         int cnt = off + th->th_urp - 1;
 3401 
 3402         while (cnt >= 0) {
 3403                 if (m->m_len > cnt) {
 3404                         char *cp = mtod(m, caddr_t) + cnt;
 3405                         struct tcpcb *tp = sototcpcb(so);
 3406 
 3407                         INP_WLOCK_ASSERT(tp->t_inpcb);
 3408 
 3409                         tp->t_iobc = *cp;
 3410                         tp->t_oobflags |= TCPOOB_HAVEDATA;
 3411                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
 3412                         m->m_len--;
 3413                         if (m->m_flags & M_PKTHDR)
 3414                                 m->m_pkthdr.len--;
 3415                         return;
 3416                 }
 3417                 cnt -= m->m_len;
 3418                 m = m->m_next;
 3419                 if (m == NULL)
 3420                         break;
 3421         }
 3422         panic("tcp_pulloutofband");
 3423 }
 3424 
 3425 /*
 3426  * Collect new round-trip time estimate
 3427  * and update averages and current timeout.
 3428  */
 3429 void
 3430 tcp_xmit_timer(struct tcpcb *tp, int rtt)
 3431 {
 3432         int delta;
 3433 
 3434         INP_WLOCK_ASSERT(tp->t_inpcb);
 3435 
 3436         TCPSTAT_INC(tcps_rttupdated);
 3437         tp->t_rttupdated++;
 3438         if (tp->t_srtt != 0) {
 3439                 /*
 3440                  * srtt is stored as fixed point with 5 bits after the
 3441                  * binary point (i.e., scaled by 8).  The following magic
 3442                  * is equivalent to the smoothing algorithm in rfc793 with
 3443                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
 3444                  * point).  Adjust rtt to origin 0.
 3445                  */
 3446                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
 3447                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
 3448 
 3449                 if ((tp->t_srtt += delta) <= 0)
 3450                         tp->t_srtt = 1;
 3451 
 3452                 /*
 3453                  * We accumulate a smoothed rtt variance (actually, a
 3454                  * smoothed mean difference), then set the retransmit
 3455                  * timer to smoothed rtt + 4 times the smoothed variance.
 3456                  * rttvar is stored as fixed point with 4 bits after the
 3457                  * binary point (scaled by 16).  The following is
 3458                  * equivalent to rfc793 smoothing with an alpha of .75
 3459                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
 3460                  * rfc793's wired-in beta.
 3461                  */
 3462                 if (delta < 0)
 3463                         delta = -delta;
 3464                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
 3465                 if ((tp->t_rttvar += delta) <= 0)
 3466                         tp->t_rttvar = 1;
 3467                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
 3468                     tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 3469         } else {
 3470                 /*
 3471                  * No rtt measurement yet - use the unsmoothed rtt.
 3472                  * Set the variance to half the rtt (so our first
 3473                  * retransmit happens at 3*rtt).
 3474                  */
 3475                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
 3476                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
 3477                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
 3478         }
 3479         tp->t_rtttime = 0;
 3480         tp->t_rxtshift = 0;
 3481 
 3482         /*
 3483          * the retransmit should happen at rtt + 4 * rttvar.
 3484          * Because of the way we do the smoothing, srtt and rttvar
 3485          * will each average +1/2 tick of bias.  When we compute
 3486          * the retransmit timer, we want 1/2 tick of rounding and
 3487          * 1 extra tick because of +-1/2 tick uncertainty in the
 3488          * firing of the timer.  The bias will give us exactly the
 3489          * 1.5 tick we need.  But, because the bias is
 3490          * statistical, we have to test that we don't drop below
 3491          * the minimum feasible timer (which is 2 ticks).
 3492          */
 3493         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
 3494                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
 3495 
 3496         /*
 3497          * We received an ack for a packet that wasn't retransmitted;
 3498          * it is probably safe to discard any error indications we've
 3499          * received recently.  This isn't quite right, but close enough
 3500          * for now (a route might have failed after we sent a segment,
 3501          * and the return path might not be symmetrical).
 3502          */
 3503         tp->t_softerror = 0;
 3504 }
 3505 
 3506 /*
 3507  * Determine a reasonable value for maxseg size.
 3508  * If the route is known, check route for mtu.
 3509  * If none, use an mss that can be handled on the outgoing interface
 3510  * without forcing IP to fragment.  If no route is found, route has no mtu,
 3511  * or the destination isn't local, use a default, hopefully conservative
 3512  * size (usually 512 or the default IP max size, but no more than the mtu
 3513  * of the interface), as we can't discover anything about intervening
 3514  * gateways or networks.  We also initialize the congestion/slow start
 3515  * window to be a single segment if the destination isn't local.
 3516  * While looking at the routing entry, we also initialize other path-dependent
 3517  * parameters from pre-set or cached values in the routing entry.
 3518  *
 3519  * NOTE that resulting t_maxseg doesn't include space for TCP options or
 3520  * IP options, e.g. IPSEC data, since length of this data may vary, and
 3521  * thus it is calculated for every segment separately in tcp_output().
 3522  *
 3523  * NOTE that this routine is only called when we process an incoming
 3524  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
 3525  * settings are handled in tcp_mssopt().
 3526  */
 3527 void
 3528 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
 3529     struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
 3530 {
 3531         int mss = 0;
 3532         u_long maxmtu = 0;
 3533         struct inpcb *inp = tp->t_inpcb;
 3534         struct hc_metrics_lite metrics;
 3535 #ifdef INET6
 3536         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
 3537         size_t min_protoh = isipv6 ?
 3538                             sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
 3539                             sizeof (struct tcpiphdr);
 3540 #else
 3541         const size_t min_protoh = sizeof(struct tcpiphdr);
 3542 #endif
 3543 
 3544         INP_WLOCK_ASSERT(tp->t_inpcb);
 3545 
 3546         if (mtuoffer != -1) {
 3547                 KASSERT(offer == -1, ("%s: conflict", __func__));
 3548                 offer = mtuoffer - min_protoh;
 3549         }
 3550 
 3551         /* Initialize. */
 3552 #ifdef INET6
 3553         if (isipv6) {
 3554                 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
 3555                 tp->t_maxseg = V_tcp_v6mssdflt;
 3556         }
 3557 #endif
 3558 #if defined(INET) && defined(INET6)
 3559         else
 3560 #endif
 3561 #ifdef INET
 3562         {
 3563                 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
 3564                 tp->t_maxseg = V_tcp_mssdflt;
 3565         }
 3566 #endif
 3567 
 3568         /*
 3569          * No route to sender, stay with default mss and return.
 3570          */
 3571         if (maxmtu == 0) {
 3572                 /*
 3573                  * In case we return early we need to initialize metrics
 3574                  * to a defined state as tcp_hc_get() would do for us
 3575                  * if there was no cache hit.
 3576                  */
 3577                 if (metricptr != NULL)
 3578                         bzero(metricptr, sizeof(struct hc_metrics_lite));
 3579                 return;
 3580         }
 3581 
 3582         /* What have we got? */
 3583         switch (offer) {
 3584                 case 0:
 3585                         /*
 3586                          * Offer == 0 means that there was no MSS on the SYN
 3587                          * segment, in this case we use tcp_mssdflt as
 3588                          * already assigned to t_maxseg above.
 3589                          */
 3590                         offer = tp->t_maxseg;
 3591                         break;
 3592 
 3593                 case -1:
 3594                         /*
 3595                          * Offer == -1 means that we didn't receive SYN yet.
 3596                          */
 3597                         /* FALLTHROUGH */
 3598 
 3599                 default:
 3600                         /*
 3601                          * Prevent DoS attack with too small MSS. Round up
 3602                          * to at least minmss.
 3603                          */
 3604                         offer = max(offer, V_tcp_minmss);
 3605         }
 3606 
 3607         /*
 3608          * rmx information is now retrieved from tcp_hostcache.
 3609          */
 3610         tcp_hc_get(&inp->inp_inc, &metrics);
 3611         if (metricptr != NULL)
 3612                 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
 3613 
 3614         /*
 3615          * If there's a discovered mtu in tcp hostcache, use it.
 3616          * Else, use the link mtu.
 3617          */
 3618         if (metrics.rmx_mtu)
 3619                 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
 3620         else {
 3621 #ifdef INET6
 3622                 if (isipv6) {
 3623                         mss = maxmtu - min_protoh;
 3624                         if (!V_path_mtu_discovery &&
 3625                             !in6_localaddr(&inp->in6p_faddr))
 3626                                 mss = min(mss, V_tcp_v6mssdflt);
 3627                 }
 3628 #endif
 3629 #if defined(INET) && defined(INET6)
 3630                 else
 3631 #endif
 3632 #ifdef INET
 3633                 {
 3634                         mss = maxmtu - min_protoh;
 3635                         if (!V_path_mtu_discovery &&
 3636                             !in_localaddr(inp->inp_faddr))
 3637                                 mss = min(mss, V_tcp_mssdflt);
 3638                 }
 3639 #endif
 3640                 /*
 3641                  * XXX - The above conditional (mss = maxmtu - min_protoh)
 3642                  * probably violates the TCP spec.
 3643                  * The problem is that, since we don't know the
 3644                  * other end's MSS, we are supposed to use a conservative
 3645                  * default.  But, if we do that, then MTU discovery will
 3646                  * never actually take place, because the conservative
 3647                  * default is much less than the MTUs typically seen
 3648                  * on the Internet today.  For the moment, we'll sweep
 3649                  * this under the carpet.
 3650                  *
 3651                  * The conservative default might not actually be a problem
 3652                  * if the only case this occurs is when sending an initial
 3653                  * SYN with options and data to a host we've never talked
 3654                  * to before.  Then, they will reply with an MSS value which
 3655                  * will get recorded and the new parameters should get
 3656                  * recomputed.  For Further Study.
 3657                  */
 3658         }
 3659         mss = min(mss, offer);
 3660 
 3661         /*
 3662          * Sanity check: make sure that maxseg will be large
 3663          * enough to allow some data on segments even if the
 3664          * all the option space is used (40bytes).  Otherwise
 3665          * funny things may happen in tcp_output.
 3666          *
 3667          * XXXGL: shouldn't we reserve space for IP/IPv6 options?
 3668          */
 3669         mss = max(mss, 64);
 3670 
 3671         tp->t_maxseg = mss;
 3672 }
 3673 
 3674 void
 3675 tcp_mss(struct tcpcb *tp, int offer)
 3676 {
 3677         int mss;
 3678         u_long bufsize;
 3679         struct inpcb *inp;
 3680         struct socket *so;
 3681         struct hc_metrics_lite metrics;
 3682         struct tcp_ifcap cap;
 3683 
 3684         KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
 3685 
 3686         bzero(&cap, sizeof(cap));
 3687         tcp_mss_update(tp, offer, -1, &metrics, &cap);
 3688 
 3689         mss = tp->t_maxseg;
 3690         inp = tp->t_inpcb;
 3691 
 3692         /*
 3693          * If there's a pipesize, change the socket buffer to that size,
 3694          * don't change if sb_hiwat is different than default (then it
 3695          * has been changed on purpose with setsockopt).
 3696          * Make the socket buffers an integral number of mss units;
 3697          * if the mss is larger than the socket buffer, decrease the mss.
 3698          */
 3699         so = inp->inp_socket;
 3700         SOCKBUF_LOCK(&so->so_snd);
 3701         if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
 3702                 bufsize = metrics.rmx_sendpipe;
 3703         else
 3704                 bufsize = so->so_snd.sb_hiwat;
 3705         if (bufsize < mss)
 3706                 mss = bufsize;
 3707         else {
 3708                 bufsize = roundup(bufsize, mss);
 3709                 if (bufsize > sb_max)
 3710                         bufsize = sb_max;
 3711                 if (bufsize > so->so_snd.sb_hiwat)
 3712                         (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
 3713         }
 3714         SOCKBUF_UNLOCK(&so->so_snd);
 3715         tp->t_maxseg = mss;
 3716 
 3717         SOCKBUF_LOCK(&so->so_rcv);
 3718         if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
 3719                 bufsize = metrics.rmx_recvpipe;
 3720         else
 3721                 bufsize = so->so_rcv.sb_hiwat;
 3722         if (bufsize > mss) {
 3723                 bufsize = roundup(bufsize, mss);
 3724                 if (bufsize > sb_max)
 3725                         bufsize = sb_max;
 3726                 if (bufsize > so->so_rcv.sb_hiwat)
 3727                         (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
 3728         }
 3729         SOCKBUF_UNLOCK(&so->so_rcv);
 3730 
 3731         /* Check the interface for TSO capabilities. */
 3732         if (cap.ifcap & CSUM_TSO) {
 3733                 tp->t_flags |= TF_TSO;
 3734                 tp->t_tsomax = cap.tsomax;
 3735                 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
 3736                 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
 3737         }
 3738 }
 3739 
 3740 /*
 3741  * Determine the MSS option to send on an outgoing SYN.
 3742  */
 3743 int
 3744 tcp_mssopt(struct in_conninfo *inc)
 3745 {
 3746         int mss = 0;
 3747         u_long maxmtu = 0;
 3748         u_long thcmtu = 0;
 3749         size_t min_protoh;
 3750 
 3751         KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
 3752 
 3753 #ifdef INET6
 3754         if (inc->inc_flags & INC_ISIPV6) {
 3755                 mss = V_tcp_v6mssdflt;
 3756                 maxmtu = tcp_maxmtu6(inc, NULL);
 3757                 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
 3758         }
 3759 #endif
 3760 #if defined(INET) && defined(INET6)
 3761         else
 3762 #endif
 3763 #ifdef INET
 3764         {
 3765                 mss = V_tcp_mssdflt;
 3766                 maxmtu = tcp_maxmtu(inc, NULL);
 3767                 min_protoh = sizeof(struct tcpiphdr);
 3768         }
 3769 #endif
 3770 #if defined(INET6) || defined(INET)
 3771         thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
 3772 #endif
 3773 
 3774         if (maxmtu && thcmtu)
 3775                 mss = min(maxmtu, thcmtu) - min_protoh;
 3776         else if (maxmtu || thcmtu)
 3777                 mss = max(maxmtu, thcmtu) - min_protoh;
 3778 
 3779         return (mss);
 3780 }
 3781 
 3782 
 3783 /*
 3784  * On a partial ack arrives, force the retransmission of the
 3785  * next unacknowledged segment.  Do not clear tp->t_dupacks.
 3786  * By setting snd_nxt to ti_ack, this forces retransmission timer to
 3787  * be started again.
 3788  */
 3789 void
 3790 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
 3791 {
 3792         tcp_seq onxt = tp->snd_nxt;
 3793         u_long ocwnd = tp->snd_cwnd;
 3794         u_int maxseg = tcp_maxseg(tp);
 3795 
 3796         INP_WLOCK_ASSERT(tp->t_inpcb);
 3797 
 3798         tcp_timer_activate(tp, TT_REXMT, 0);
 3799         tp->t_rtttime = 0;
 3800         tp->snd_nxt = th->th_ack;
 3801         /*
 3802          * Set snd_cwnd to one segment beyond acknowledged offset.
 3803          * (tp->snd_una has not yet been updated when this function is called.)
 3804          */
 3805         tp->snd_cwnd = maxseg + BYTES_THIS_ACK(tp, th);
 3806         tp->t_flags |= TF_ACKNOW;
 3807         (void) tp->t_fb->tfb_tcp_output(tp);
 3808         tp->snd_cwnd = ocwnd;
 3809         if (SEQ_GT(onxt, tp->snd_nxt))
 3810                 tp->snd_nxt = onxt;
 3811         /*
 3812          * Partial window deflation.  Relies on fact that tp->snd_una
 3813          * not updated yet.
 3814          */
 3815         if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
 3816                 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
 3817         else
 3818                 tp->snd_cwnd = 0;
 3819         tp->snd_cwnd += maxseg;
 3820 }
 3821 
 3822 int
 3823 tcp_compute_pipe(struct tcpcb *tp)
 3824 {
 3825         return (tp->snd_max - tp->snd_una +
 3826                 tp->sackhint.sack_bytes_rexmit -
 3827                 tp->sackhint.sacked_bytes);
 3828 }

Cache object: ba32a0a0af587b917cdb87102e1e7267


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