linux/net/ipv4/tcp_input.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * INET         An implementation of the TCP/IP protocol suite for the LINUX
   4 *              operating system.  INET is implemented using the  BSD Socket
   5 *              interface as the means of communication with the user level.
   6 *
   7 *              Implementation of the Transmission Control Protocol(TCP).
   8 *
   9 * Authors:     Ross Biro
  10 *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  11 *              Mark Evans, <evansmp@uhura.aston.ac.uk>
  12 *              Corey Minyard <wf-rch!minyard@relay.EU.net>
  13 *              Florian La Roche, <flla@stud.uni-sb.de>
  14 *              Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  15 *              Linus Torvalds, <torvalds@cs.helsinki.fi>
  16 *              Alan Cox, <gw4pts@gw4pts.ampr.org>
  17 *              Matthew Dillon, <dillon@apollo.west.oic.com>
  18 *              Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  19 *              Jorge Cwik, <jorge@laser.satlink.net>
  20 */
  21
  22/*
  23 * Changes:
  24 *              Pedro Roque     :       Fast Retransmit/Recovery.
  25 *                                      Two receive queues.
  26 *                                      Retransmit queue handled by TCP.
  27 *                                      Better retransmit timer handling.
  28 *                                      New congestion avoidance.
  29 *                                      Header prediction.
  30 *                                      Variable renaming.
  31 *
  32 *              Eric            :       Fast Retransmit.
  33 *              Randy Scott     :       MSS option defines.
  34 *              Eric Schenk     :       Fixes to slow start algorithm.
  35 *              Eric Schenk     :       Yet another double ACK bug.
  36 *              Eric Schenk     :       Delayed ACK bug fixes.
  37 *              Eric Schenk     :       Floyd style fast retrans war avoidance.
  38 *              David S. Miller :       Don't allow zero congestion window.
  39 *              Eric Schenk     :       Fix retransmitter so that it sends
  40 *                                      next packet on ack of previous packet.
  41 *              Andi Kleen      :       Moved open_request checking here
  42 *                                      and process RSTs for open_requests.
  43 *              Andi Kleen      :       Better prune_queue, and other fixes.
  44 *              Andrey Savochkin:       Fix RTT measurements in the presence of
  45 *                                      timestamps.
  46 *              Andrey Savochkin:       Check sequence numbers correctly when
  47 *                                      removing SACKs due to in sequence incoming
  48 *                                      data segments.
  49 *              Andi Kleen:             Make sure we never ack data there is not
  50 *                                      enough room for. Also make this condition
  51 *                                      a fatal error if it might still happen.
  52 *              Andi Kleen:             Add tcp_measure_rcv_mss to make
  53 *                                      connections with MSS<min(MTU,ann. MSS)
  54 *                                      work without delayed acks.
  55 *              Andi Kleen:             Process packets with PSH set in the
  56 *                                      fast path.
  57 *              J Hadi Salim:           ECN support
  58 *              Andrei Gurtov,
  59 *              Pasi Sarolahti,
  60 *              Panu Kuhlberg:          Experimental audit of TCP (re)transmission
  61 *                                      engine. Lots of bugs are found.
  62 *              Pasi Sarolahti:         F-RTO for dealing with spurious RTOs
  63 */
  64
  65#define pr_fmt(fmt) "TCP: " fmt
  66
  67#include <linux/mm.h>
  68#include <linux/slab.h>
  69#include <linux/module.h>
  70#include <linux/sysctl.h>
  71#include <linux/kernel.h>
  72#include <linux/prefetch.h>
  73#include <net/dst.h>
  74#include <net/tcp.h>
  75#include <net/inet_common.h>
  76#include <linux/ipsec.h>
  77#include <asm/unaligned.h>
  78#include <linux/errqueue.h>
  79#include <trace/events/tcp.h>
  80#include <linux/static_key.h>
  81
  82int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
  83
  84#define FLAG_DATA               0x01 /* Incoming frame contained data.          */
  85#define FLAG_WIN_UPDATE         0x02 /* Incoming ACK was a window update.       */
  86#define FLAG_DATA_ACKED         0x04 /* This ACK acknowledged new data.         */
  87#define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted.  */
  88#define FLAG_SYN_ACKED          0x10 /* This ACK acknowledged SYN.              */
  89#define FLAG_DATA_SACKED        0x20 /* New SACK.                               */
  90#define FLAG_ECE                0x40 /* ECE in this ACK                         */
  91#define FLAG_LOST_RETRANS       0x80 /* This ACK marks some retransmission lost */
  92#define FLAG_SLOWPATH           0x100 /* Do not skip RFC checks for window update.*/
  93#define FLAG_ORIG_SACK_ACKED    0x200 /* Never retransmitted data are (s)acked  */
  94#define FLAG_SND_UNA_ADVANCED   0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
  95#define FLAG_DSACKING_ACK       0x800 /* SACK blocks contained D-SACK info */
  96#define FLAG_SET_XMIT_TIMER     0x1000 /* Set TLP or RTO timer */
  97#define FLAG_SACK_RENEGING      0x2000 /* snd_una advanced to a sacked seq */
  98#define FLAG_UPDATE_TS_RECENT   0x4000 /* tcp_replace_ts_recent() */
  99#define FLAG_NO_CHALLENGE_ACK   0x8000 /* do not call tcp_send_challenge_ack()  */
 100
 101#define FLAG_ACKED              (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
 102#define FLAG_NOT_DUP            (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
 103#define FLAG_CA_ALERT           (FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK)
 104#define FLAG_FORWARD_PROGRESS   (FLAG_ACKED|FLAG_DATA_SACKED)
 105
 106#define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
 107#define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
 108
 109#define REXMIT_NONE     0 /* no loss recovery to do */
 110#define REXMIT_LOST     1 /* retransmit packets marked lost */
 111#define REXMIT_NEW      2 /* FRTO-style transmit of unsent/new packets */
 112
 113static void tcp_gro_dev_warn(struct sock *sk, const struct sk_buff *skb,
 114                             unsigned int len)
 115{
 116        static bool __once __read_mostly;
 117
 118        if (!__once) {
 119                struct net_device *dev;
 120
 121                __once = true;
 122
 123                rcu_read_lock();
 124                dev = dev_get_by_index_rcu(sock_net(sk), skb->skb_iif);
 125                if (!dev || len >= dev->mtu)
 126                        pr_warn("%s: Driver has suspect GRO implementation, TCP performance may be compromised.\n",
 127                                dev ? dev->name : "Unknown driver");
 128                rcu_read_unlock();
 129        }
 130}
 131
 132/* Adapt the MSS value used to make delayed ack decision to the
 133 * real world.
 134 */
 135static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
 136{
 137        struct inet_connection_sock *icsk = inet_csk(sk);
 138        const unsigned int lss = icsk->icsk_ack.last_seg_size;
 139        unsigned int len;
 140
 141        icsk->icsk_ack.last_seg_size = 0;
 142
 143        /* skb->len may jitter because of SACKs, even if peer
 144         * sends good full-sized frames.
 145         */
 146        len = skb_shinfo(skb)->gso_size ? : skb->len;
 147        if (len >= icsk->icsk_ack.rcv_mss) {
 148                icsk->icsk_ack.rcv_mss = min_t(unsigned int, len,
 149                                               tcp_sk(sk)->advmss);
 150                /* Account for possibly-removed options */
 151                if (unlikely(len > icsk->icsk_ack.rcv_mss +
 152                                   MAX_TCP_OPTION_SPACE))
 153                        tcp_gro_dev_warn(sk, skb, len);
 154        } else {
 155                /* Otherwise, we make more careful check taking into account,
 156                 * that SACKs block is variable.
 157                 *
 158                 * "len" is invariant segment length, including TCP header.
 159                 */
 160                len += skb->data - skb_transport_header(skb);
 161                if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
 162                    /* If PSH is not set, packet should be
 163                     * full sized, provided peer TCP is not badly broken.
 164                     * This observation (if it is correct 8)) allows
 165                     * to handle super-low mtu links fairly.
 166                     */
 167                    (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
 168                     !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
 169                        /* Subtract also invariant (if peer is RFC compliant),
 170                         * tcp header plus fixed timestamp option length.
 171                         * Resulting "len" is MSS free of SACK jitter.
 172                         */
 173                        len -= tcp_sk(sk)->tcp_header_len;
 174                        icsk->icsk_ack.last_seg_size = len;
 175                        if (len == lss) {
 176                                icsk->icsk_ack.rcv_mss = len;
 177                                return;
 178                        }
 179                }
 180                if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
 181                        icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
 182                icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
 183        }
 184}
 185
 186static void tcp_incr_quickack(struct sock *sk)
 187{
 188        struct inet_connection_sock *icsk = inet_csk(sk);
 189        unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
 190
 191        if (quickacks == 0)
 192                quickacks = 2;
 193        if (quickacks > icsk->icsk_ack.quick)
 194                icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
 195}
 196
 197static void tcp_enter_quickack_mode(struct sock *sk)
 198{
 199        struct inet_connection_sock *icsk = inet_csk(sk);
 200        tcp_incr_quickack(sk);
 201        icsk->icsk_ack.pingpong = 0;
 202        icsk->icsk_ack.ato = TCP_ATO_MIN;
 203}
 204
 205/* Send ACKs quickly, if "quick" count is not exhausted
 206 * and the session is not interactive.
 207 */
 208
 209static bool tcp_in_quickack_mode(struct sock *sk)
 210{
 211        const struct inet_connection_sock *icsk = inet_csk(sk);
 212        const struct dst_entry *dst = __sk_dst_get(sk);
 213
 214        return (dst && dst_metric(dst, RTAX_QUICKACK)) ||
 215                (icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong);
 216}
 217
 218static void tcp_ecn_queue_cwr(struct tcp_sock *tp)
 219{
 220        if (tp->ecn_flags & TCP_ECN_OK)
 221                tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
 222}
 223
 224static void tcp_ecn_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb)
 225{
 226        if (tcp_hdr(skb)->cwr)
 227                tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
 228}
 229
 230static void tcp_ecn_withdraw_cwr(struct tcp_sock *tp)
 231{
 232        tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
 233}
 234
 235static void __tcp_ecn_check_ce(struct tcp_sock *tp, const struct sk_buff *skb)
 236{
 237        switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
 238        case INET_ECN_NOT_ECT:
 239                /* Funny extension: if ECT is not set on a segment,
 240                 * and we already seen ECT on a previous segment,
 241                 * it is probably a retransmit.
 242                 */
 243                if (tp->ecn_flags & TCP_ECN_SEEN)
 244                        tcp_enter_quickack_mode((struct sock *)tp);
 245                break;
 246        case INET_ECN_CE:
 247                if (tcp_ca_needs_ecn((struct sock *)tp))
 248                        tcp_ca_event((struct sock *)tp, CA_EVENT_ECN_IS_CE);
 249
 250                if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) {
 251                        /* Better not delay acks, sender can have a very low cwnd */
 252                        tcp_enter_quickack_mode((struct sock *)tp);
 253                        tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
 254                }
 255                tp->ecn_flags |= TCP_ECN_SEEN;
 256                break;
 257        default:
 258                if (tcp_ca_needs_ecn((struct sock *)tp))
 259                        tcp_ca_event((struct sock *)tp, CA_EVENT_ECN_NO_CE);
 260                tp->ecn_flags |= TCP_ECN_SEEN;
 261                break;
 262        }
 263}
 264
 265static void tcp_ecn_check_ce(struct tcp_sock *tp, const struct sk_buff *skb)
 266{
 267        if (tp->ecn_flags & TCP_ECN_OK)
 268                __tcp_ecn_check_ce(tp, skb);
 269}
 270
 271static void tcp_ecn_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
 272{
 273        if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
 274                tp->ecn_flags &= ~TCP_ECN_OK;
 275}
 276
 277static void tcp_ecn_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
 278{
 279        if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
 280                tp->ecn_flags &= ~TCP_ECN_OK;
 281}
 282
 283static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
 284{
 285        if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
 286                return true;
 287        return false;
 288}
 289
 290/* Buffer size and advertised window tuning.
 291 *
 292 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
 293 */
 294
 295static void tcp_sndbuf_expand(struct sock *sk)
 296{
 297        const struct tcp_sock *tp = tcp_sk(sk);
 298        const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
 299        int sndmem, per_mss;
 300        u32 nr_segs;
 301
 302        /* Worst case is non GSO/TSO : each frame consumes one skb
 303         * and skb->head is kmalloced using power of two area of memory
 304         */
 305        per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
 306                  MAX_TCP_HEADER +
 307                  SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 308
 309        per_mss = roundup_pow_of_two(per_mss) +
 310                  SKB_DATA_ALIGN(sizeof(struct sk_buff));
 311
 312        nr_segs = max_t(u32, TCP_INIT_CWND, tp->snd_cwnd);
 313        nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
 314
 315        /* Fast Recovery (RFC 5681 3.2) :
 316         * Cubic needs 1.7 factor, rounded to 2 to include
 317         * extra cushion (application might react slowly to POLLOUT)
 318         */
 319        sndmem = ca_ops->sndbuf_expand ? ca_ops->sndbuf_expand(sk) : 2;
 320        sndmem *= nr_segs * per_mss;
 321
 322        if (sk->sk_sndbuf < sndmem)
 323                sk->sk_sndbuf = min(sndmem, sock_net(sk)->ipv4.sysctl_tcp_wmem[2]);
 324}
 325
 326/* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
 327 *
 328 * All tcp_full_space() is split to two parts: "network" buffer, allocated
 329 * forward and advertised in receiver window (tp->rcv_wnd) and
 330 * "application buffer", required to isolate scheduling/application
 331 * latencies from network.
 332 * window_clamp is maximal advertised window. It can be less than
 333 * tcp_full_space(), in this case tcp_full_space() - window_clamp
 334 * is reserved for "application" buffer. The less window_clamp is
 335 * the smoother our behaviour from viewpoint of network, but the lower
 336 * throughput and the higher sensitivity of the connection to losses. 8)
 337 *
 338 * rcv_ssthresh is more strict window_clamp used at "slow start"
 339 * phase to predict further behaviour of this connection.
 340 * It is used for two goals:
 341 * - to enforce header prediction at sender, even when application
 342 *   requires some significant "application buffer". It is check #1.
 343 * - to prevent pruning of receive queue because of misprediction
 344 *   of receiver window. Check #2.
 345 *
 346 * The scheme does not work when sender sends good segments opening
 347 * window and then starts to feed us spaghetti. But it should work
 348 * in common situations. Otherwise, we have to rely on queue collapsing.
 349 */
 350
 351/* Slow part of check#2. */
 352static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
 353{
 354        struct tcp_sock *tp = tcp_sk(sk);
 355        /* Optimize this! */
 356        int truesize = tcp_win_from_space(sk, skb->truesize) >> 1;
 357        int window = tcp_win_from_space(sk, sock_net(sk)->ipv4.sysctl_tcp_rmem[2]) >> 1;
 358
 359        while (tp->rcv_ssthresh <= window) {
 360                if (truesize <= skb->len)
 361                        return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
 362
 363                truesize >>= 1;
 364                window >>= 1;
 365        }
 366        return 0;
 367}
 368
 369static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb)
 370{
 371        struct tcp_sock *tp = tcp_sk(sk);
 372
 373        /* Check #1 */
 374        if (tp->rcv_ssthresh < tp->window_clamp &&
 375            (int)tp->rcv_ssthresh < tcp_space(sk) &&
 376            !tcp_under_memory_pressure(sk)) {
 377                int incr;
 378
 379                /* Check #2. Increase window, if skb with such overhead
 380                 * will fit to rcvbuf in future.
 381                 */
 382                if (tcp_win_from_space(sk, skb->truesize) <= skb->len)
 383                        incr = 2 * tp->advmss;
 384                else
 385                        incr = __tcp_grow_window(sk, skb);
 386
 387                if (incr) {
 388                        incr = max_t(int, incr, 2 * skb->len);
 389                        tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr,
 390                                               tp->window_clamp);
 391                        inet_csk(sk)->icsk_ack.quick |= 1;
 392                }
 393        }
 394}
 395
 396/* 3. Tuning rcvbuf, when connection enters established state. */
 397static void tcp_fixup_rcvbuf(struct sock *sk)
 398{
 399        u32 mss = tcp_sk(sk)->advmss;
 400        int rcvmem;
 401
 402        rcvmem = 2 * SKB_TRUESIZE(mss + MAX_TCP_HEADER) *
 403                 tcp_default_init_rwnd(mss);
 404
 405        /* Dynamic Right Sizing (DRS) has 2 to 3 RTT latency
 406         * Allow enough cushion so that sender is not limited by our window
 407         */
 408        if (sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf)
 409                rcvmem <<= 2;
 410
 411        if (sk->sk_rcvbuf < rcvmem)
 412                sk->sk_rcvbuf = min(rcvmem, sock_net(sk)->ipv4.sysctl_tcp_rmem[2]);
 413}
 414
 415/* 4. Try to fixup all. It is made immediately after connection enters
 416 *    established state.
 417 */
 418void tcp_init_buffer_space(struct sock *sk)
 419{
 420        int tcp_app_win = sock_net(sk)->ipv4.sysctl_tcp_app_win;
 421        struct tcp_sock *tp = tcp_sk(sk);
 422        int maxwin;
 423
 424        if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
 425                tcp_fixup_rcvbuf(sk);
 426        if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
 427                tcp_sndbuf_expand(sk);
 428
 429        tp->rcvq_space.space = tp->rcv_wnd;
 430        tcp_mstamp_refresh(tp);
 431        tp->rcvq_space.time = tp->tcp_mstamp;
 432        tp->rcvq_space.seq = tp->copied_seq;
 433
 434        maxwin = tcp_full_space(sk);
 435
 436        if (tp->window_clamp >= maxwin) {
 437                tp->window_clamp = maxwin;
 438
 439                if (tcp_app_win && maxwin > 4 * tp->advmss)
 440                        tp->window_clamp = max(maxwin -
 441                                               (maxwin >> tcp_app_win),
 442                                               4 * tp->advmss);
 443        }
 444
 445        /* Force reservation of one segment. */
 446        if (tcp_app_win &&
 447            tp->window_clamp > 2 * tp->advmss &&
 448            tp->window_clamp + tp->advmss > maxwin)
 449                tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
 450
 451        tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
 452        tp->snd_cwnd_stamp = tcp_jiffies32;
 453}
 454
 455/* 5. Recalculate window clamp after socket hit its memory bounds. */
 456static void tcp_clamp_window(struct sock *sk)
 457{
 458        struct tcp_sock *tp = tcp_sk(sk);
 459        struct inet_connection_sock *icsk = inet_csk(sk);
 460        struct net *net = sock_net(sk);
 461
 462        icsk->icsk_ack.quick = 0;
 463
 464        if (sk->sk_rcvbuf < net->ipv4.sysctl_tcp_rmem[2] &&
 465            !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
 466            !tcp_under_memory_pressure(sk) &&
 467            sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
 468                sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
 469                                    net->ipv4.sysctl_tcp_rmem[2]);
 470        }
 471        if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
 472                tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
 473}
 474
 475/* Initialize RCV_MSS value.
 476 * RCV_MSS is an our guess about MSS used by the peer.
 477 * We haven't any direct information about the MSS.
 478 * It's better to underestimate the RCV_MSS rather than overestimate.
 479 * Overestimations make us ACKing less frequently than needed.
 480 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
 481 */
 482void tcp_initialize_rcv_mss(struct sock *sk)
 483{
 484        const struct tcp_sock *tp = tcp_sk(sk);
 485        unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
 486
 487        hint = min(hint, tp->rcv_wnd / 2);
 488        hint = min(hint, TCP_MSS_DEFAULT);
 489        hint = max(hint, TCP_MIN_MSS);
 490
 491        inet_csk(sk)->icsk_ack.rcv_mss = hint;
 492}
 493EXPORT_SYMBOL(tcp_initialize_rcv_mss);
 494
 495/* Receiver "autotuning" code.
 496 *
 497 * The algorithm for RTT estimation w/o timestamps is based on
 498 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
 499 * <http://public.lanl.gov/radiant/pubs.html#DRS>
 500 *
 501 * More detail on this code can be found at
 502 * <http://staff.psc.edu/jheffner/>,
 503 * though this reference is out of date.  A new paper
 504 * is pending.
 505 */
 506static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
 507{
 508        u32 new_sample = tp->rcv_rtt_est.rtt_us;
 509        long m = sample;
 510
 511        if (new_sample != 0) {
 512                /* If we sample in larger samples in the non-timestamp
 513                 * case, we could grossly overestimate the RTT especially
 514                 * with chatty applications or bulk transfer apps which
 515                 * are stalled on filesystem I/O.
 516                 *
 517                 * Also, since we are only going for a minimum in the
 518                 * non-timestamp case, we do not smooth things out
 519                 * else with timestamps disabled convergence takes too
 520                 * long.
 521                 */
 522                if (!win_dep) {
 523                        m -= (new_sample >> 3);
 524                        new_sample += m;
 525                } else {
 526                        m <<= 3;
 527                        if (m < new_sample)
 528                                new_sample = m;
 529                }
 530        } else {
 531                /* No previous measure. */
 532                new_sample = m << 3;
 533        }
 534
 535        tp->rcv_rtt_est.rtt_us = new_sample;
 536}
 537
 538static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
 539{
 540        u32 delta_us;
 541
 542        if (tp->rcv_rtt_est.time == 0)
 543                goto new_measure;
 544        if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
 545                return;
 546        delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
 547        if (!delta_us)
 548                delta_us = 1;
 549        tcp_rcv_rtt_update(tp, delta_us, 1);
 550
 551new_measure:
 552        tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
 553        tp->rcv_rtt_est.time = tp->tcp_mstamp;
 554}
 555
 556static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
 557                                          const struct sk_buff *skb)
 558{
 559        struct tcp_sock *tp = tcp_sk(sk);
 560
 561        if (tp->rx_opt.rcv_tsecr &&
 562            (TCP_SKB_CB(skb)->end_seq -
 563             TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss)) {
 564                u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
 565                u32 delta_us;
 566
 567                if (!delta)
 568                        delta = 1;
 569                delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
 570                tcp_rcv_rtt_update(tp, delta_us, 0);
 571        }
 572}
 573
 574/*
 575 * This function should be called every time data is copied to user space.
 576 * It calculates the appropriate TCP receive buffer space.
 577 */
 578void tcp_rcv_space_adjust(struct sock *sk)
 579{
 580        struct tcp_sock *tp = tcp_sk(sk);
 581        int time;
 582        int copied;
 583
 584        tcp_mstamp_refresh(tp);
 585        time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
 586        if (time < (tp->rcv_rtt_est.rtt_us >> 3) || tp->rcv_rtt_est.rtt_us == 0)
 587                return;
 588
 589        /* Number of bytes copied to user in last RTT */
 590        copied = tp->copied_seq - tp->rcvq_space.seq;
 591        if (copied <= tp->rcvq_space.space)
 592                goto new_measure;
 593
 594        /* A bit of theory :
 595         * copied = bytes received in previous RTT, our base window
 596         * To cope with packet losses, we need a 2x factor
 597         * To cope with slow start, and sender growing its cwin by 100 %
 598         * every RTT, we need a 4x factor, because the ACK we are sending
 599         * now is for the next RTT, not the current one :
 600         * <prev RTT . ><current RTT .. ><next RTT .... >
 601         */
 602
 603        if (sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf &&
 604            !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
 605                int rcvwin, rcvmem, rcvbuf;
 606
 607                /* minimal window to cope with packet losses, assuming
 608                 * steady state. Add some cushion because of small variations.
 609                 */
 610                rcvwin = (copied << 1) + 16 * tp->advmss;
 611
 612                /* If rate increased by 25%,
 613                 *      assume slow start, rcvwin = 3 * copied
 614                 * If rate increased by 50%,
 615                 *      assume sender can use 2x growth, rcvwin = 4 * copied
 616                 */
 617                if (copied >=
 618                    tp->rcvq_space.space + (tp->rcvq_space.space >> 2)) {
 619                        if (copied >=
 620                            tp->rcvq_space.space + (tp->rcvq_space.space >> 1))
 621                                rcvwin <<= 1;
 622                        else
 623                                rcvwin += (rcvwin >> 1);
 624                }
 625
 626                rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
 627                while (tcp_win_from_space(sk, rcvmem) < tp->advmss)
 628                        rcvmem += 128;
 629
 630                rcvbuf = min(rcvwin / tp->advmss * rcvmem,
 631                             sock_net(sk)->ipv4.sysctl_tcp_rmem[2]);
 632                if (rcvbuf > sk->sk_rcvbuf) {
 633                        sk->sk_rcvbuf = rcvbuf;
 634
 635                        /* Make the window clamp follow along.  */
 636                        tp->window_clamp = rcvwin;
 637                }
 638        }
 639        tp->rcvq_space.space = copied;
 640
 641new_measure:
 642        tp->rcvq_space.seq = tp->copied_seq;
 643        tp->rcvq_space.time = tp->tcp_mstamp;
 644}
 645
 646/* There is something which you must keep in mind when you analyze the
 647 * behavior of the tp->ato delayed ack timeout interval.  When a
 648 * connection starts up, we want to ack as quickly as possible.  The
 649 * problem is that "good" TCP's do slow start at the beginning of data
 650 * transmission.  The means that until we send the first few ACK's the
 651 * sender will sit on his end and only queue most of his data, because
 652 * he can only send snd_cwnd unacked packets at any given time.  For
 653 * each ACK we send, he increments snd_cwnd and transmits more of his
 654 * queue.  -DaveM
 655 */
 656static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
 657{
 658        struct tcp_sock *tp = tcp_sk(sk);
 659        struct inet_connection_sock *icsk = inet_csk(sk);
 660        u32 now;
 661
 662        inet_csk_schedule_ack(sk);
 663
 664        tcp_measure_rcv_mss(sk, skb);
 665
 666        tcp_rcv_rtt_measure(tp);
 667
 668        now = tcp_jiffies32;
 669
 670        if (!icsk->icsk_ack.ato) {
 671                /* The _first_ data packet received, initialize
 672                 * delayed ACK engine.
 673                 */
 674                tcp_incr_quickack(sk);
 675                icsk->icsk_ack.ato = TCP_ATO_MIN;
 676        } else {
 677                int m = now - icsk->icsk_ack.lrcvtime;
 678
 679                if (m <= TCP_ATO_MIN / 2) {
 680                        /* The fastest case is the first. */
 681                        icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
 682                } else if (m < icsk->icsk_ack.ato) {
 683                        icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
 684                        if (icsk->icsk_ack.ato > icsk->icsk_rto)
 685                                icsk->icsk_ack.ato = icsk->icsk_rto;
 686                } else if (m > icsk->icsk_rto) {
 687                        /* Too long gap. Apparently sender failed to
 688                         * restart window, so that we send ACKs quickly.
 689                         */
 690                        tcp_incr_quickack(sk);
 691                        sk_mem_reclaim(sk);
 692                }
 693        }
 694        icsk->icsk_ack.lrcvtime = now;
 695
 696        tcp_ecn_check_ce(tp, skb);
 697
 698        if (skb->len >= 128)
 699                tcp_grow_window(sk, skb);
 700}
 701
 702/* Called to compute a smoothed rtt estimate. The data fed to this
 703 * routine either comes from timestamps, or from segments that were
 704 * known _not_ to have been retransmitted [see Karn/Partridge
 705 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
 706 * piece by Van Jacobson.
 707 * NOTE: the next three routines used to be one big routine.
 708 * To save cycles in the RFC 1323 implementation it was better to break
 709 * it up into three procedures. -- erics
 710 */
 711static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
 712{
 713        struct tcp_sock *tp = tcp_sk(sk);
 714        long m = mrtt_us; /* RTT */
 715        u32 srtt = tp->srtt_us;
 716
 717        /*      The following amusing code comes from Jacobson's
 718         *      article in SIGCOMM '88.  Note that rtt and mdev
 719         *      are scaled versions of rtt and mean deviation.
 720         *      This is designed to be as fast as possible
 721         *      m stands for "measurement".
 722         *
 723         *      On a 1990 paper the rto value is changed to:
 724         *      RTO = rtt + 4 * mdev
 725         *
 726         * Funny. This algorithm seems to be very broken.
 727         * These formulae increase RTO, when it should be decreased, increase
 728         * too slowly, when it should be increased quickly, decrease too quickly
 729         * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
 730         * does not matter how to _calculate_ it. Seems, it was trap
 731         * that VJ failed to avoid. 8)
 732         */
 733        if (srtt != 0) {
 734                m -= (srtt >> 3);       /* m is now error in rtt est */
 735                srtt += m;              /* rtt = 7/8 rtt + 1/8 new */
 736                if (m < 0) {
 737                        m = -m;         /* m is now abs(error) */
 738                        m -= (tp->mdev_us >> 2);   /* similar update on mdev */
 739                        /* This is similar to one of Eifel findings.
 740                         * Eifel blocks mdev updates when rtt decreases.
 741                         * This solution is a bit different: we use finer gain
 742                         * for mdev in this case (alpha*beta).
 743                         * Like Eifel it also prevents growth of rto,
 744                         * but also it limits too fast rto decreases,
 745                         * happening in pure Eifel.
 746                         */
 747                        if (m > 0)
 748                                m >>= 3;
 749                } else {
 750                        m -= (tp->mdev_us >> 2);   /* similar update on mdev */
 751                }
 752                tp->mdev_us += m;               /* mdev = 3/4 mdev + 1/4 new */
 753                if (tp->mdev_us > tp->mdev_max_us) {
 754                        tp->mdev_max_us = tp->mdev_us;
 755                        if (tp->mdev_max_us > tp->rttvar_us)
 756                                tp->rttvar_us = tp->mdev_max_us;
 757                }
 758                if (after(tp->snd_una, tp->rtt_seq)) {
 759                        if (tp->mdev_max_us < tp->rttvar_us)
 760                                tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
 761                        tp->rtt_seq = tp->snd_nxt;
 762                        tp->mdev_max_us = tcp_rto_min_us(sk);
 763                }
 764        } else {
 765                /* no previous measure. */
 766                srtt = m << 3;          /* take the measured time to be rtt */
 767                tp->mdev_us = m << 1;   /* make sure rto = 3*rtt */
 768                tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
 769                tp->mdev_max_us = tp->rttvar_us;
 770                tp->rtt_seq = tp->snd_nxt;
 771        }
 772        tp->srtt_us = max(1U, srtt);
 773}
 774
 775static void tcp_update_pacing_rate(struct sock *sk)
 776{
 777        const struct tcp_sock *tp = tcp_sk(sk);
 778        u64 rate;
 779
 780        /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
 781        rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
 782
 783        /* current rate is (cwnd * mss) / srtt
 784         * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
 785         * In Congestion Avoidance phase, set it to 120 % the current rate.
 786         *
 787         * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
 788         *       If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
 789         *       end of slow start and should slow down.
 790         */
 791        if (tp->snd_cwnd < tp->snd_ssthresh / 2)
 792                rate *= sock_net(sk)->ipv4.sysctl_tcp_pacing_ss_ratio;
 793        else
 794                rate *= sock_net(sk)->ipv4.sysctl_tcp_pacing_ca_ratio;
 795
 796        rate *= max(tp->snd_cwnd, tp->packets_out);
 797
 798        if (likely(tp->srtt_us))
 799                do_div(rate, tp->srtt_us);
 800
 801        /* WRITE_ONCE() is needed because sch_fq fetches sk_pacing_rate
 802         * without any lock. We want to make sure compiler wont store
 803         * intermediate values in this location.
 804         */
 805        WRITE_ONCE(sk->sk_pacing_rate, min_t(u64, rate,
 806                                             sk->sk_max_pacing_rate));
 807}
 808
 809/* Calculate rto without backoff.  This is the second half of Van Jacobson's
 810 * routine referred to above.
 811 */
 812static void tcp_set_rto(struct sock *sk)
 813{
 814        const struct tcp_sock *tp = tcp_sk(sk);
 815        /* Old crap is replaced with new one. 8)
 816         *
 817         * More seriously:
 818         * 1. If rtt variance happened to be less 50msec, it is hallucination.
 819         *    It cannot be less due to utterly erratic ACK generation made
 820         *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
 821         *    to do with delayed acks, because at cwnd>2 true delack timeout
 822         *    is invisible. Actually, Linux-2.4 also generates erratic
 823         *    ACKs in some circumstances.
 824         */
 825        inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
 826
 827        /* 2. Fixups made earlier cannot be right.
 828         *    If we do not estimate RTO correctly without them,
 829         *    all the algo is pure shit and should be replaced
 830         *    with correct one. It is exactly, which we pretend to do.
 831         */
 832
 833        /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
 834         * guarantees that rto is higher.
 835         */
 836        tcp_bound_rto(sk);
 837}
 838
 839__u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
 840{
 841        __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
 842
 843        if (!cwnd)
 844                cwnd = TCP_INIT_CWND;
 845        return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
 846}
 847
 848/* Take a notice that peer is sending D-SACKs */
 849static void tcp_dsack_seen(struct tcp_sock *tp)
 850{
 851        tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
 852        tp->rack.dsack_seen = 1;
 853}
 854
 855/* It's reordering when higher sequence was delivered (i.e. sacked) before
 856 * some lower never-retransmitted sequence ("low_seq"). The maximum reordering
 857 * distance is approximated in full-mss packet distance ("reordering").
 858 */
 859static void tcp_check_sack_reordering(struct sock *sk, const u32 low_seq,
 860                                      const int ts)
 861{
 862        struct tcp_sock *tp = tcp_sk(sk);
 863        const u32 mss = tp->mss_cache;
 864        u32 fack, metric;
 865
 866        fack = tcp_highest_sack_seq(tp);
 867        if (!before(low_seq, fack))
 868                return;
 869
 870        metric = fack - low_seq;
 871        if ((metric > tp->reordering * mss) && mss) {
 872#if FASTRETRANS_DEBUG > 1
 873                pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
 874                         tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
 875                         tp->reordering,
 876                         0,
 877                         tp->sacked_out,
 878                         tp->undo_marker ? tp->undo_retrans : 0);
 879#endif
 880                tp->reordering = min_t(u32, (metric + mss - 1) / mss,
 881                                       sock_net(sk)->ipv4.sysctl_tcp_max_reordering);
 882        }
 883
 884        tp->rack.reord = 1;
 885        /* This exciting event is worth to be remembered. 8) */
 886        NET_INC_STATS(sock_net(sk),
 887                      ts ? LINUX_MIB_TCPTSREORDER : LINUX_MIB_TCPSACKREORDER);
 888}
 889
 890/* This must be called before lost_out is incremented */
 891static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
 892{
 893        if (!tp->retransmit_skb_hint ||
 894            before(TCP_SKB_CB(skb)->seq,
 895                   TCP_SKB_CB(tp->retransmit_skb_hint)->seq))
 896                tp->retransmit_skb_hint = skb;
 897}
 898
 899/* Sum the number of packets on the wire we have marked as lost.
 900 * There are two cases we care about here:
 901 * a) Packet hasn't been marked lost (nor retransmitted),
 902 *    and this is the first loss.
 903 * b) Packet has been marked both lost and retransmitted,
 904 *    and this means we think it was lost again.
 905 */
 906static void tcp_sum_lost(struct tcp_sock *tp, struct sk_buff *skb)
 907{
 908        __u8 sacked = TCP_SKB_CB(skb)->sacked;
 909
 910        if (!(sacked & TCPCB_LOST) ||
 911            ((sacked & TCPCB_LOST) && (sacked & TCPCB_SACKED_RETRANS)))
 912                tp->lost += tcp_skb_pcount(skb);
 913}
 914
 915static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb)
 916{
 917        if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
 918                tcp_verify_retransmit_hint(tp, skb);
 919
 920                tp->lost_out += tcp_skb_pcount(skb);
 921                tcp_sum_lost(tp, skb);
 922                TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
 923        }
 924}
 925
 926void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp, struct sk_buff *skb)
 927{
 928        tcp_verify_retransmit_hint(tp, skb);
 929
 930        tcp_sum_lost(tp, skb);
 931        if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
 932                tp->lost_out += tcp_skb_pcount(skb);
 933                TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
 934        }
 935}
 936
 937/* This procedure tags the retransmission queue when SACKs arrive.
 938 *
 939 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
 940 * Packets in queue with these bits set are counted in variables
 941 * sacked_out, retrans_out and lost_out, correspondingly.
 942 *
 943 * Valid combinations are:
 944 * Tag  InFlight        Description
 945 * 0    1               - orig segment is in flight.
 946 * S    0               - nothing flies, orig reached receiver.
 947 * L    0               - nothing flies, orig lost by net.
 948 * R    2               - both orig and retransmit are in flight.
 949 * L|R  1               - orig is lost, retransmit is in flight.
 950 * S|R  1               - orig reached receiver, retrans is still in flight.
 951 * (L|S|R is logically valid, it could occur when L|R is sacked,
 952 *  but it is equivalent to plain S and code short-curcuits it to S.
 953 *  L|S is logically invalid, it would mean -1 packet in flight 8))
 954 *
 955 * These 6 states form finite state machine, controlled by the following events:
 956 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
 957 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
 958 * 3. Loss detection event of two flavors:
 959 *      A. Scoreboard estimator decided the packet is lost.
 960 *         A'. Reno "three dupacks" marks head of queue lost.
 961 *      B. SACK arrives sacking SND.NXT at the moment, when the
 962 *         segment was retransmitted.
 963 * 4. D-SACK added new rule: D-SACK changes any tag to S.
 964 *
 965 * It is pleasant to note, that state diagram turns out to be commutative,
 966 * so that we are allowed not to be bothered by order of our actions,
 967 * when multiple events arrive simultaneously. (see the function below).
 968 *
 969 * Reordering detection.
 970 * --------------------
 971 * Reordering metric is maximal distance, which a packet can be displaced
 972 * in packet stream. With SACKs we can estimate it:
 973 *
 974 * 1. SACK fills old hole and the corresponding segment was not
 975 *    ever retransmitted -> reordering. Alas, we cannot use it
 976 *    when segment was retransmitted.
 977 * 2. The last flaw is solved with D-SACK. D-SACK arrives
 978 *    for retransmitted and already SACKed segment -> reordering..
 979 * Both of these heuristics are not used in Loss state, when we cannot
 980 * account for retransmits accurately.
 981 *
 982 * SACK block validation.
 983 * ----------------------
 984 *
 985 * SACK block range validation checks that the received SACK block fits to
 986 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
 987 * Note that SND.UNA is not included to the range though being valid because
 988 * it means that the receiver is rather inconsistent with itself reporting
 989 * SACK reneging when it should advance SND.UNA. Such SACK block this is
 990 * perfectly valid, however, in light of RFC2018 which explicitly states
 991 * that "SACK block MUST reflect the newest segment.  Even if the newest
 992 * segment is going to be discarded ...", not that it looks very clever
 993 * in case of head skb. Due to potentional receiver driven attacks, we
 994 * choose to avoid immediate execution of a walk in write queue due to
 995 * reneging and defer head skb's loss recovery to standard loss recovery
 996 * procedure that will eventually trigger (nothing forbids us doing this).
 997 *
 998 * Implements also blockage to start_seq wrap-around. Problem lies in the
 999 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1000 * there's no guarantee that it will be before snd_nxt (n). The problem
1001 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1002 * wrap (s_w):
1003 *
1004 *         <- outs wnd ->                          <- wrapzone ->
1005 *         u     e      n                         u_w   e_w  s n_w
1006 *         |     |      |                          |     |   |  |
1007 * |<------------+------+----- TCP seqno space --------------+---------->|
1008 * ...-- <2^31 ->|                                           |<--------...
1009 * ...---- >2^31 ------>|                                    |<--------...
1010 *
1011 * Current code wouldn't be vulnerable but it's better still to discard such
1012 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1013 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1014 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1015 * equal to the ideal case (infinite seqno space without wrap caused issues).
1016 *
1017 * With D-SACK the lower bound is extended to cover sequence space below
1018 * SND.UNA down to undo_marker, which is the last point of interest. Yet
1019 * again, D-SACK block must not to go across snd_una (for the same reason as
1020 * for the normal SACK blocks, explained above). But there all simplicity
1021 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1022 * fully below undo_marker they do not affect behavior in anyway and can
1023 * therefore be safely ignored. In rare cases (which are more or less
1024 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1025 * fragmentation and packet reordering past skb's retransmission. To consider
1026 * them correctly, the acceptable range must be extended even more though
1027 * the exact amount is rather hard to quantify. However, tp->max_window can
1028 * be used as an exaggerated estimate.
1029 */
1030static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
1031                                   u32 start_seq, u32 end_seq)
1032{
1033        /* Too far in future, or reversed (interpretation is ambiguous) */
1034        if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1035                return false;
1036
1037        /* Nasty start_seq wrap-around check (see comments above) */
1038        if (!before(start_seq, tp->snd_nxt))
1039                return false;
1040
1041        /* In outstanding window? ...This is valid exit for D-SACKs too.
1042         * start_seq == snd_una is non-sensical (see comments above)
1043         */
1044        if (after(start_seq, tp->snd_una))
1045                return true;
1046
1047        if (!is_dsack || !tp->undo_marker)
1048                return false;
1049
1050        /* ...Then it's D-SACK, and must reside below snd_una completely */
1051        if (after(end_seq, tp->snd_una))
1052                return false;
1053
1054        if (!before(start_seq, tp->undo_marker))
1055                return true;
1056
1057        /* Too old */
1058        if (!after(end_seq, tp->undo_marker))
1059                return false;
1060
1061        /* Undo_marker boundary crossing (overestimates a lot). Known already:
1062         *   start_seq < undo_marker and end_seq >= undo_marker.
1063         */
1064        return !before(start_seq, end_seq - tp->max_window);
1065}
1066
1067static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1068                            struct tcp_sack_block_wire *sp, int num_sacks,
1069                            u32 prior_snd_una)
1070{
1071        struct tcp_sock *tp = tcp_sk(sk);
1072        u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1073        u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
1074        bool dup_sack = false;
1075
1076        if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1077                dup_sack = true;
1078                tcp_dsack_seen(tp);
1079                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
1080        } else if (num_sacks > 1) {
1081                u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1082                u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
1083
1084                if (!after(end_seq_0, end_seq_1) &&
1085                    !before(start_seq_0, start_seq_1)) {
1086                        dup_sack = true;
1087                        tcp_dsack_seen(tp);
1088                        NET_INC_STATS(sock_net(sk),
1089                                        LINUX_MIB_TCPDSACKOFORECV);
1090                }
1091        }
1092
1093        /* D-SACK for already forgotten data... Do dumb counting. */
1094        if (dup_sack && tp->undo_marker && tp->undo_retrans > 0 &&
1095            !after(end_seq_0, prior_snd_una) &&
1096            after(end_seq_0, tp->undo_marker))
1097                tp->undo_retrans--;
1098
1099        return dup_sack;
1100}
1101
1102struct tcp_sacktag_state {
1103        u32     reord;
1104        /* Timestamps for earliest and latest never-retransmitted segment
1105         * that was SACKed. RTO needs the earliest RTT to stay conservative,
1106         * but congestion control should still get an accurate delay signal.
1107         */
1108        u64     first_sackt;
1109        u64     last_sackt;
1110        struct rate_sample *rate;
1111        int     flag;
1112        unsigned int mss_now;
1113};
1114
1115/* Check if skb is fully within the SACK block. In presence of GSO skbs,
1116 * the incoming SACK may not exactly match but we can find smaller MSS
1117 * aligned portion of it that matches. Therefore we might need to fragment
1118 * which may fail and creates some hassle (caller must handle error case
1119 * returns).
1120 *
1121 * FIXME: this could be merged to shift decision code
1122 */
1123static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1124                                  u32 start_seq, u32 end_seq)
1125{
1126        int err;
1127        bool in_sack;
1128        unsigned int pkt_len;
1129        unsigned int mss;
1130
1131        in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1132                  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1133
1134        if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1135            after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1136                mss = tcp_skb_mss(skb);
1137                in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1138
1139                if (!in_sack) {
1140                        pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1141                        if (pkt_len < mss)
1142                                pkt_len = mss;
1143                } else {
1144                        pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1145                        if (pkt_len < mss)
1146                                return -EINVAL;
1147                }
1148
1149                /* Round if necessary so that SACKs cover only full MSSes
1150                 * and/or the remaining small portion (if present)
1151                 */
1152                if (pkt_len > mss) {
1153                        unsigned int new_len = (pkt_len / mss) * mss;
1154                        if (!in_sack && new_len < pkt_len)
1155                                new_len += mss;
1156                        pkt_len = new_len;
1157                }
1158
1159                if (pkt_len >= skb->len && !in_sack)
1160                        return 0;
1161
1162                err = tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
1163                                   pkt_len, mss, GFP_ATOMIC);
1164                if (err < 0)
1165                        return err;
1166        }
1167
1168        return in_sack;
1169}
1170
1171/* Mark the given newly-SACKed range as such, adjusting counters and hints. */
1172static u8 tcp_sacktag_one(struct sock *sk,
1173                          struct tcp_sacktag_state *state, u8 sacked,
1174                          u32 start_seq, u32 end_seq,
1175                          int dup_sack, int pcount,
1176                          u64 xmit_time)
1177{
1178        struct tcp_sock *tp = tcp_sk(sk);
1179
1180        /* Account D-SACK for retransmitted packet. */
1181        if (dup_sack && (sacked & TCPCB_RETRANS)) {
1182                if (tp->undo_marker && tp->undo_retrans > 0 &&
1183                    after(end_seq, tp->undo_marker))
1184                        tp->undo_retrans--;
1185                if ((sacked & TCPCB_SACKED_ACKED) &&
1186                    before(start_seq, state->reord))
1187                                state->reord = start_seq;
1188        }
1189
1190        /* Nothing to do; acked frame is about to be dropped (was ACKed). */
1191        if (!after(end_seq, tp->snd_una))
1192                return sacked;
1193
1194        if (!(sacked & TCPCB_SACKED_ACKED)) {
1195                tcp_rack_advance(tp, sacked, end_seq, xmit_time);
1196
1197                if (sacked & TCPCB_SACKED_RETRANS) {
1198                        /* If the segment is not tagged as lost,
1199                         * we do not clear RETRANS, believing
1200                         * that retransmission is still in flight.
1201                         */
1202                        if (sacked & TCPCB_LOST) {
1203                                sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1204                                tp->lost_out -= pcount;
1205                                tp->retrans_out -= pcount;
1206                        }
1207                } else {
1208                        if (!(sacked & TCPCB_RETRANS)) {
1209                                /* New sack for not retransmitted frame,
1210                                 * which was in hole. It is reordering.
1211                                 */
1212                                if (before(start_seq,
1213                                           tcp_highest_sack_seq(tp)) &&
1214                                    before(start_seq, state->reord))
1215                                        state->reord = start_seq;
1216
1217                                if (!after(end_seq, tp->high_seq))
1218                                        state->flag |= FLAG_ORIG_SACK_ACKED;
1219                                if (state->first_sackt == 0)
1220                                        state->first_sackt = xmit_time;
1221                                state->last_sackt = xmit_time;
1222                        }
1223
1224                        if (sacked & TCPCB_LOST) {
1225                                sacked &= ~TCPCB_LOST;
1226                                tp->lost_out -= pcount;
1227                        }
1228                }
1229
1230                sacked |= TCPCB_SACKED_ACKED;
1231                state->flag |= FLAG_DATA_SACKED;
1232                tp->sacked_out += pcount;
1233                tp->delivered += pcount;  /* Out-of-order packets delivered */
1234
1235                /* Lost marker hint past SACKed? Tweak RFC3517 cnt */
1236                if (tp->lost_skb_hint &&
1237                    before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
1238                        tp->lost_cnt_hint += pcount;
1239        }
1240
1241        /* D-SACK. We can detect redundant retransmission in S|R and plain R
1242         * frames and clear it. undo_retrans is decreased above, L|R frames
1243         * are accounted above as well.
1244         */
1245        if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1246                sacked &= ~TCPCB_SACKED_RETRANS;
1247                tp->retrans_out -= pcount;
1248        }
1249
1250        return sacked;
1251}
1252
1253/* Shift newly-SACKed bytes from this skb to the immediately previous
1254 * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1255 */
1256static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,
1257                            struct sk_buff *skb,
1258                            struct tcp_sacktag_state *state,
1259                            unsigned int pcount, int shifted, int mss,
1260                            bool dup_sack)
1261{
1262        struct tcp_sock *tp = tcp_sk(sk);
1263        u32 start_seq = TCP_SKB_CB(skb)->seq;   /* start of newly-SACKed */
1264        u32 end_seq = start_seq + shifted;      /* end of newly-SACKed */
1265
1266        BUG_ON(!pcount);
1267
1268        /* Adjust counters and hints for the newly sacked sequence
1269         * range but discard the return value since prev is already
1270         * marked. We must tag the range first because the seq
1271         * advancement below implicitly advances
1272         * tcp_highest_sack_seq() when skb is highest_sack.
1273         */
1274        tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
1275                        start_seq, end_seq, dup_sack, pcount,
1276                        skb->skb_mstamp);
1277        tcp_rate_skb_delivered(sk, skb, state->rate);
1278
1279        if (skb == tp->lost_skb_hint)
1280                tp->lost_cnt_hint += pcount;
1281
1282        TCP_SKB_CB(prev)->end_seq += shifted;
1283        TCP_SKB_CB(skb)->seq += shifted;
1284
1285        tcp_skb_pcount_add(prev, pcount);
1286        BUG_ON(tcp_skb_pcount(skb) < pcount);
1287        tcp_skb_pcount_add(skb, -pcount);
1288
1289        /* When we're adding to gso_segs == 1, gso_size will be zero,
1290         * in theory this shouldn't be necessary but as long as DSACK
1291         * code can come after this skb later on it's better to keep
1292         * setting gso_size to something.
1293         */
1294        if (!TCP_SKB_CB(prev)->tcp_gso_size)
1295                TCP_SKB_CB(prev)->tcp_gso_size = mss;
1296
1297        /* CHECKME: To clear or not to clear? Mimics normal skb currently */
1298        if (tcp_skb_pcount(skb) <= 1)
1299                TCP_SKB_CB(skb)->tcp_gso_size = 0;
1300
1301        /* Difference in this won't matter, both ACKed by the same cumul. ACK */
1302        TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1303
1304        if (skb->len > 0) {
1305                BUG_ON(!tcp_skb_pcount(skb));
1306                NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
1307                return false;
1308        }
1309
1310        /* Whole SKB was eaten :-) */
1311
1312        if (skb == tp->retransmit_skb_hint)
1313                tp->retransmit_skb_hint = prev;
1314        if (skb == tp->lost_skb_hint) {
1315                tp->lost_skb_hint = prev;
1316                tp->lost_cnt_hint -= tcp_skb_pcount(prev);
1317        }
1318
1319        TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
1320        TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
1321        if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
1322                TCP_SKB_CB(prev)->end_seq++;
1323
1324        if (skb == tcp_highest_sack(sk))
1325                tcp_advance_highest_sack(sk, skb);
1326
1327        tcp_skb_collapse_tstamp(prev, skb);
1328        if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
1329                TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
1330
1331        tcp_rtx_queue_unlink_and_free(skb, sk);
1332
1333        NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
1334
1335        return true;
1336}
1337
1338/* I wish gso_size would have a bit more sane initialization than
1339 * something-or-zero which complicates things
1340 */
1341static int tcp_skb_seglen(const struct sk_buff *skb)
1342{
1343        return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
1344}
1345
1346/* Shifting pages past head area doesn't work */
1347static int skb_can_shift(const struct sk_buff *skb)
1348{
1349        return !skb_headlen(skb) && skb_is_nonlinear(skb);
1350}
1351
1352/* Try collapsing SACK blocks spanning across multiple skbs to a single
1353 * skb.
1354 */
1355static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
1356                                          struct tcp_sacktag_state *state,
1357                                          u32 start_seq, u32 end_seq,
1358                                          bool dup_sack)
1359{
1360        struct tcp_sock *tp = tcp_sk(sk);
1361        struct sk_buff *prev;
1362        int mss;
1363        int pcount = 0;
1364        int len;
1365        int in_sack;
1366
1367        if (!sk_can_gso(sk))
1368                goto fallback;
1369
1370        /* Normally R but no L won't result in plain S */
1371        if (!dup_sack &&
1372            (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
1373                goto fallback;
1374        if (!skb_can_shift(skb))
1375                goto fallback;
1376        /* This frame is about to be dropped (was ACKed). */
1377        if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1378                goto fallback;
1379
1380        /* Can only happen with delayed DSACK + discard craziness */
1381        prev = skb_rb_prev(skb);
1382        if (!prev)
1383                goto fallback;
1384
1385        if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1386                goto fallback;
1387
1388        if (!tcp_skb_can_collapse_to(prev))
1389                goto fallback;
1390
1391        in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1392                  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1393
1394        if (in_sack) {
1395                len = skb->len;
1396                pcount = tcp_skb_pcount(skb);
1397                mss = tcp_skb_seglen(skb);
1398
1399                /* TODO: Fix DSACKs to not fragment already SACKed and we can
1400                 * drop this restriction as unnecessary
1401                 */
1402                if (mss != tcp_skb_seglen(prev))
1403                        goto fallback;
1404        } else {
1405                if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1406                        goto noop;
1407                /* CHECKME: This is non-MSS split case only?, this will
1408                 * cause skipped skbs due to advancing loop btw, original
1409                 * has that feature too
1410                 */
1411                if (tcp_skb_pcount(skb) <= 1)
1412                        goto noop;
1413
1414                in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1415                if (!in_sack) {
1416                        /* TODO: head merge to next could be attempted here
1417                         * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1418                         * though it might not be worth of the additional hassle
1419                         *
1420                         * ...we can probably just fallback to what was done
1421                         * previously. We could try merging non-SACKed ones
1422                         * as well but it probably isn't going to buy off
1423                         * because later SACKs might again split them, and
1424                         * it would make skb timestamp tracking considerably
1425                         * harder problem.
1426                         */
1427                        goto fallback;
1428                }
1429
1430                len = end_seq - TCP_SKB_CB(skb)->seq;
1431                BUG_ON(len < 0);
1432                BUG_ON(len > skb->len);
1433
1434                /* MSS boundaries should be honoured or else pcount will
1435                 * severely break even though it makes things bit trickier.
1436                 * Optimize common case to avoid most of the divides
1437                 */
1438                mss = tcp_skb_mss(skb);
1439
1440                /* TODO: Fix DSACKs to not fragment already SACKed and we can
1441                 * drop this restriction as unnecessary
1442                 */
1443                if (mss != tcp_skb_seglen(prev))
1444                        goto fallback;
1445
1446                if (len == mss) {
1447                        pcount = 1;
1448                } else if (len < mss) {
1449                        goto noop;
1450                } else {
1451                        pcount = len / mss;
1452                        len = pcount * mss;
1453                }
1454        }
1455
1456        /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
1457        if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
1458                goto fallback;
1459
1460        if (!skb_shift(prev, skb, len))
1461                goto fallback;
1462        if (!tcp_shifted_skb(sk, prev, skb, state, pcount, len, mss, dup_sack))
1463                goto out;
1464
1465        /* Hole filled allows collapsing with the next as well, this is very
1466         * useful when hole on every nth skb pattern happens
1467         */
1468        skb = skb_rb_next(prev);
1469        if (!skb)
1470                goto out;
1471
1472        if (!skb_can_shift(skb) ||
1473            ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
1474            (mss != tcp_skb_seglen(skb)))
1475                goto out;
1476
1477        len = skb->len;
1478        if (skb_shift(prev, skb, len)) {
1479                pcount += tcp_skb_pcount(skb);
1480                tcp_shifted_skb(sk, prev, skb, state, tcp_skb_pcount(skb),
1481                                len, mss, 0);
1482        }
1483
1484out:
1485        return prev;
1486
1487noop:
1488        return skb;
1489
1490fallback:
1491        NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
1492        return NULL;
1493}
1494
1495static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1496                                        struct tcp_sack_block *next_dup,
1497                                        struct tcp_sacktag_state *state,
1498                                        u32 start_seq, u32 end_seq,
1499                                        bool dup_sack_in)
1500{
1501        struct tcp_sock *tp = tcp_sk(sk);
1502        struct sk_buff *tmp;
1503
1504        skb_rbtree_walk_from(skb) {
1505                int in_sack = 0;
1506                bool dup_sack = dup_sack_in;
1507
1508                /* queue is in-order => we can short-circuit the walk early */
1509                if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1510                        break;
1511
1512                if (next_dup  &&
1513                    before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1514                        in_sack = tcp_match_skb_to_sack(sk, skb,
1515                                                        next_dup->start_seq,
1516                                                        next_dup->end_seq);
1517                        if (in_sack > 0)
1518                                dup_sack = true;
1519                }
1520
1521                /* skb reference here is a bit tricky to get right, since
1522                 * shifting can eat and free both this skb and the next,
1523                 * so not even _safe variant of the loop is enough.
1524                 */
1525                if (in_sack <= 0) {
1526                        tmp = tcp_shift_skb_data(sk, skb, state,
1527                                                 start_seq, end_seq, dup_sack);
1528                        if (tmp) {
1529                                if (tmp != skb) {
1530                                        skb = tmp;
1531                                        continue;
1532                                }
1533
1534                                in_sack = 0;
1535                        } else {
1536                                in_sack = tcp_match_skb_to_sack(sk, skb,
1537                                                                start_seq,
1538                                                                end_seq);
1539                        }
1540                }
1541
1542                if (unlikely(in_sack < 0))
1543                        break;
1544
1545                if (in_sack) {
1546                        TCP_SKB_CB(skb)->sacked =
1547                                tcp_sacktag_one(sk,
1548                                                state,
1549                                                TCP_SKB_CB(skb)->sacked,
1550                                                TCP_SKB_CB(skb)->seq,
1551                                                TCP_SKB_CB(skb)->end_seq,
1552                                                dup_sack,
1553                                                tcp_skb_pcount(skb),
1554                                                skb->skb_mstamp);
1555                        tcp_rate_skb_delivered(sk, skb, state->rate);
1556                        if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
1557                                list_del_init(&skb->tcp_tsorted_anchor);
1558
1559                        if (!before(TCP_SKB_CB(skb)->seq,
1560                                    tcp_highest_sack_seq(tp)))
1561                                tcp_advance_highest_sack(sk, skb);
1562                }
1563        }
1564        return skb;
1565}
1566
1567static struct sk_buff *tcp_sacktag_bsearch(struct sock *sk,
1568                                           struct tcp_sacktag_state *state,
1569                                           u32 seq)
1570{
1571        struct rb_node *parent, **p = &sk->tcp_rtx_queue.rb_node;
1572        struct sk_buff *skb;
1573
1574        while (*p) {
1575                parent = *p;
1576                skb = rb_to_skb(parent);
1577                if (before(seq, TCP_SKB_CB(skb)->seq)) {
1578                        p = &parent->rb_left;
1579                        continue;
1580                }
1581                if (!before(seq, TCP_SKB_CB(skb)->end_seq)) {
1582                        p = &parent->rb_right;
1583                        continue;
1584                }
1585                return skb;
1586        }
1587        return NULL;
1588}
1589
1590static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1591                                        struct tcp_sacktag_state *state,
1592                                        u32 skip_to_seq)
1593{
1594        if (skb && after(TCP_SKB_CB(skb)->seq, skip_to_seq))
1595                return skb;
1596
1597        return tcp_sacktag_bsearch(sk, state, skip_to_seq);
1598}
1599
1600static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1601                                                struct sock *sk,
1602                                                struct tcp_sack_block *next_dup,
1603                                                struct tcp_sacktag_state *state,
1604                                                u32 skip_to_seq)
1605{
1606        if (!next_dup)
1607                return skb;
1608
1609        if (before(next_dup->start_seq, skip_to_seq)) {
1610                skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq);
1611                skb = tcp_sacktag_walk(skb, sk, NULL, state,
1612                                       next_dup->start_seq, next_dup->end_seq,
1613                                       1);
1614        }
1615
1616        return skb;
1617}
1618
1619static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
1620{
1621        return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1622}
1623
1624static int
1625tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
1626                        u32 prior_snd_una, struct tcp_sacktag_state *state)
1627{
1628        struct tcp_sock *tp = tcp_sk(sk);
1629        const unsigned char *ptr = (skb_transport_header(ack_skb) +
1630                                    TCP_SKB_CB(ack_skb)->sacked);
1631        struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
1632        struct tcp_sack_block sp[TCP_NUM_SACKS];
1633        struct tcp_sack_block *cache;
1634        struct sk_buff *skb;
1635        int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
1636        int used_sacks;
1637        bool found_dup_sack = false;
1638        int i, j;
1639        int first_sack_index;
1640
1641        state->flag = 0;
1642        state->reord = tp->snd_nxt;
1643
1644        if (!tp->sacked_out)
1645                tcp_highest_sack_reset(sk);
1646
1647        found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
1648                                         num_sacks, prior_snd_una);
1649        if (found_dup_sack) {
1650                state->flag |= FLAG_DSACKING_ACK;
1651                tp->delivered++; /* A spurious retransmission is delivered */
1652        }
1653
1654        /* Eliminate too old ACKs, but take into
1655         * account more or less fresh ones, they can
1656         * contain valid SACK info.
1657         */
1658        if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1659                return 0;
1660
1661        if (!tp->packets_out)
1662                goto out;
1663
1664        used_sacks = 0;
1665        first_sack_index = 0;
1666        for (i = 0; i < num_sacks; i++) {
1667                bool dup_sack = !i && found_dup_sack;
1668
1669                sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
1670                sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
1671
1672                if (!tcp_is_sackblock_valid(tp, dup_sack,
1673                                            sp[used_sacks].start_seq,
1674                                            sp[used_sacks].end_seq)) {
1675                        int mib_idx;
1676
1677                        if (dup_sack) {
1678                                if (!tp->undo_marker)
1679                                        mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
1680                                else
1681                                        mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
1682                        } else {
1683                                /* Don't count olds caused by ACK reordering */
1684                                if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
1685                                    !after(sp[used_sacks].end_seq, tp->snd_una))
1686                                        continue;
1687                                mib_idx = LINUX_MIB_TCPSACKDISCARD;
1688                        }
1689
1690                        NET_INC_STATS(sock_net(sk), mib_idx);
1691                        if (i == 0)
1692                                first_sack_index = -1;
1693                        continue;
1694                }
1695
1696                /* Ignore very old stuff early */
1697                if (!after(sp[used_sacks].end_seq, prior_snd_una))
1698                        continue;
1699
1700                used_sacks++;
1701        }
1702
1703        /* order SACK blocks to allow in order walk of the retrans queue */
1704        for (i = used_sacks - 1; i > 0; i--) {
1705                for (j = 0; j < i; j++) {
1706                        if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
1707                                swap(sp[j], sp[j + 1]);
1708
1709                                /* Track where the first SACK block goes to */
1710                                if (j == first_sack_index)
1711                                        first_sack_index = j + 1;
1712                        }
1713                }
1714        }
1715
1716        state->mss_now = tcp_current_mss(sk);
1717        skb = NULL;
1718        i = 0;
1719
1720        if (!tp->sacked_out) {
1721                /* It's already past, so skip checking against it */
1722                cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1723        } else {
1724                cache = tp->recv_sack_cache;
1725                /* Skip empty blocks in at head of the cache */
1726                while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
1727                       !cache->end_seq)
1728                        cache++;
1729        }
1730
1731        while (i < used_sacks) {
1732                u32 start_seq = sp[i].start_seq;
1733                u32 end_seq = sp[i].end_seq;
1734                bool dup_sack = (found_dup_sack && (i == first_sack_index));
1735                struct tcp_sack_block *next_dup = NULL;
1736
1737                if (found_dup_sack && ((i + 1) == first_sack_index))
1738                        next_dup = &sp[i + 1];
1739
1740                /* Skip too early cached blocks */
1741                while (tcp_sack_cache_ok(tp, cache) &&
1742                       !before(start_seq, cache->end_seq))
1743                        cache++;
1744
1745                /* Can skip some work by looking recv_sack_cache? */
1746                if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
1747                    after(end_seq, cache->start_seq)) {
1748
1749                        /* Head todo? */
1750                        if (before(start_seq, cache->start_seq)) {
1751                                skb = tcp_sacktag_skip(skb, sk, state,
1752                                                       start_seq);
1753                                skb = tcp_sacktag_walk(skb, sk, next_dup,
1754                                                       state,
1755                                                       start_seq,
1756                                                       cache->start_seq,
1757                                                       dup_sack);
1758                        }
1759
1760                        /* Rest of the block already fully processed? */
1761                        if (!after(end_seq, cache->end_seq))
1762                                goto advance_sp;
1763
1764                        skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
1765                                                       state,
1766                                                       cache->end_seq);
1767
1768                        /* ...tail remains todo... */
1769                        if (tcp_highest_sack_seq(tp) == cache->end_seq) {
1770                                /* ...but better entrypoint exists! */
1771                                skb = tcp_highest_sack(sk);
1772                                if (!skb)
1773                                        break;
1774                                cache++;
1775                                goto walk;
1776                        }
1777
1778                        skb = tcp_sacktag_skip(skb, sk, state, cache->end_seq);
1779                        /* Check overlap against next cached too (past this one already) */
1780                        cache++;
1781                        continue;
1782                }
1783
1784                if (!before(start_seq, tcp_highest_sack_seq(tp))) {
1785                        skb = tcp_highest_sack(sk);
1786                        if (!skb)
1787                                break;
1788                }
1789                skb = tcp_sacktag_skip(skb, sk, state, start_seq);
1790
1791walk:
1792                skb = tcp_sacktag_walk(skb, sk, next_dup, state,
1793                                       start_seq, end_seq, dup_sack);
1794
1795advance_sp:
1796                i++;
1797        }
1798
1799        /* Clear the head of the cache sack blocks so we can skip it next time */
1800        for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
1801                tp->recv_sack_cache[i].start_seq = 0;
1802                tp->recv_sack_cache[i].end_seq = 0;
1803        }
1804        for (j = 0; j < used_sacks; j++)
1805                tp->recv_sack_cache[i++] = sp[j];
1806
1807        if (inet_csk(sk)->icsk_ca_state != TCP_CA_Loss || tp->undo_marker)
1808                tcp_check_sack_reordering(sk, state->reord, 0);
1809
1810        tcp_verify_left_out(tp);
1811out:
1812
1813#if FASTRETRANS_DEBUG > 0
1814        WARN_ON((int)tp->sacked_out < 0);
1815        WARN_ON((int)tp->lost_out < 0);
1816        WARN_ON((int)tp->retrans_out < 0);
1817        WARN_ON((int)tcp_packets_in_flight(tp) < 0);
1818#endif
1819        return state->flag;
1820}
1821
1822/* Limits sacked_out so that sum with lost_out isn't ever larger than
1823 * packets_out. Returns false if sacked_out adjustement wasn't necessary.
1824 */
1825static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
1826{
1827        u32 holes;
1828
1829        holes = max(tp->lost_out, 1U);
1830        holes = min(holes, tp->packets_out);
1831
1832        if ((tp->sacked_out + holes) > tp->packets_out) {
1833                tp->sacked_out = tp->packets_out - holes;
1834                return true;
1835        }
1836        return false;
1837}
1838
1839/* If we receive more dupacks than we expected counting segments
1840 * in assumption of absent reordering, interpret this as reordering.
1841 * The only another reason could be bug in receiver TCP.
1842 */
1843static void tcp_check_reno_reordering(struct sock *sk, const int addend)
1844{
1845        struct tcp_sock *tp = tcp_sk(sk);
1846
1847        if (!tcp_limit_reno_sacked(tp))
1848                return;
1849
1850        tp->reordering = min_t(u32, tp->packets_out + addend,
1851                               sock_net(sk)->ipv4.sysctl_tcp_max_reordering);
1852        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRENOREORDER);
1853}
1854
1855/* Emulate SACKs for SACKless connection: account for a new dupack. */
1856
1857static void tcp_add_reno_sack(struct sock *sk)
1858{
1859        struct tcp_sock *tp = tcp_sk(sk);
1860        u32 prior_sacked = tp->sacked_out;
1861
1862        tp->sacked_out++;
1863        tcp_check_reno_reordering(sk, 0);
1864        if (tp->sacked_out > prior_sacked)
1865                tp->delivered++; /* Some out-of-order packet is delivered */
1866        tcp_verify_left_out(tp);
1867}
1868
1869/* Account for ACK, ACKing some data in Reno Recovery phase. */
1870
1871static void tcp_remove_reno_sacks(struct sock *sk, int acked)
1872{
1873        struct tcp_sock *tp = tcp_sk(sk);
1874
1875        if (acked > 0) {
1876                /* One ACK acked hole. The rest eat duplicate ACKs. */
1877                tp->delivered += max_t(int, acked - tp->sacked_out, 1);
1878                if (acked - 1 >= tp->sacked_out)
1879                        tp->sacked_out = 0;
1880                else
1881                        tp->sacked_out -= acked - 1;
1882        }
1883        tcp_check_reno_reordering(sk, acked);
1884        tcp_verify_left_out(tp);
1885}
1886
1887static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
1888{
1889        tp->sacked_out = 0;
1890}
1891
1892void tcp_clear_retrans(struct tcp_sock *tp)
1893{
1894        tp->retrans_out = 0;
1895        tp->lost_out = 0;
1896        tp->undo_marker = 0;
1897        tp->undo_retrans = -1;
1898        tp->sacked_out = 0;
1899}
1900
1901static inline void tcp_init_undo(struct tcp_sock *tp)
1902{
1903        tp->undo_marker = tp->snd_una;
1904        /* Retransmission still in flight may cause DSACKs later. */
1905        tp->undo_retrans = tp->retrans_out ? : -1;
1906}
1907
1908/* Enter Loss state. If we detect SACK reneging, forget all SACK information
1909 * and reset tags completely, otherwise preserve SACKs. If receiver
1910 * dropped its ofo queue, we will know this due to reneging detection.
1911 */
1912void tcp_enter_loss(struct sock *sk)
1913{
1914        const struct inet_connection_sock *icsk = inet_csk(sk);
1915        struct tcp_sock *tp = tcp_sk(sk);
1916        struct net *net = sock_net(sk);
1917        struct sk_buff *skb;
1918        bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery;
1919        bool is_reneg;                  /* is receiver reneging on SACKs? */
1920        bool mark_lost;
1921
1922        /* Reduce ssthresh if it has not yet been made inside this window. */
1923        if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
1924            !after(tp->high_seq, tp->snd_una) ||
1925            (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
1926                tp->prior_ssthresh = tcp_current_ssthresh(sk);
1927                tp->prior_cwnd = tp->snd_cwnd;
1928                tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1929                tcp_ca_event(sk, CA_EVENT_LOSS);
1930                tcp_init_undo(tp);
1931        }
1932        tp->snd_cwnd       = 1;
1933        tp->snd_cwnd_cnt   = 0;
1934        tp->snd_cwnd_stamp = tcp_jiffies32;
1935
1936        tp->retrans_out = 0;
1937        tp->lost_out = 0;
1938
1939        if (tcp_is_reno(tp))
1940                tcp_reset_reno_sack(tp);
1941
1942        skb = tcp_rtx_queue_head(sk);
1943        is_reneg = skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED);
1944        if (is_reneg) {
1945                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
1946                tp->sacked_out = 0;
1947                /* Mark SACK reneging until we recover from this loss event. */
1948                tp->is_sack_reneg = 1;
1949        }
1950        tcp_clear_all_retrans_hints(tp);
1951
1952        skb_rbtree_walk_from(skb) {
1953                mark_lost = (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
1954                             is_reneg);
1955                if (mark_lost)
1956                        tcp_sum_lost(tp, skb);
1957                TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1958                if (mark_lost) {
1959                        TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1960                        TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1961                        tp->lost_out += tcp_skb_pcount(skb);
1962                }
1963        }
1964        tcp_verify_left_out(tp);
1965
1966        /* Timeout in disordered state after receiving substantial DUPACKs
1967         * suggests that the degree of reordering is over-estimated.
1968         */
1969        if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
1970            tp->sacked_out >= net->ipv4.sysctl_tcp_reordering)
1971                tp->reordering = min_t(unsigned int, tp->reordering,
1972                                       net->ipv4.sysctl_tcp_reordering);
1973        tcp_set_ca_state(sk, TCP_CA_Loss);
1974        tp->high_seq = tp->snd_nxt;
1975        tcp_ecn_queue_cwr(tp);
1976
1977        /* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
1978         * loss recovery is underway except recurring timeout(s) on
1979         * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
1980         */
1981        tp->frto = net->ipv4.sysctl_tcp_frto &&
1982                   (new_recovery || icsk->icsk_retransmits) &&
1983                   !inet_csk(sk)->icsk_mtup.probe_size;
1984}
1985
1986/* If ACK arrived pointing to a remembered SACK, it means that our
1987 * remembered SACKs do not reflect real state of receiver i.e.
1988 * receiver _host_ is heavily congested (or buggy).
1989 *
1990 * To avoid big spurious retransmission bursts due to transient SACK
1991 * scoreboard oddities that look like reneging, we give the receiver a
1992 * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
1993 * restore sanity to the SACK scoreboard. If the apparent reneging
1994 * persists until this RTO then we'll clear the SACK scoreboard.
1995 */
1996static bool tcp_check_sack_reneging(struct sock *sk, int flag)
1997{
1998        if (flag & FLAG_SACK_RENEGING) {
1999                struct tcp_sock *tp = tcp_sk(sk);
2000                unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
2001                                          msecs_to_jiffies(10));
2002
2003                inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
2004                                          delay, TCP_RTO_MAX);
2005                return true;
2006        }
2007        return false;
2008}
2009
2010/* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
2011 * counter when SACK is enabled (without SACK, sacked_out is used for
2012 * that purpose).
2013 *
2014 * With reordering, holes may still be in flight, so RFC3517 recovery
2015 * uses pure sacked_out (total number of SACKed segments) even though
2016 * it violates the RFC that uses duplicate ACKs, often these are equal
2017 * but when e.g. out-of-window ACKs or packet duplication occurs,
2018 * they differ. Since neither occurs due to loss, TCP should really
2019 * ignore them.
2020 */
2021static inline int tcp_dupack_heuristics(const struct tcp_sock *tp)
2022{
2023        return tp->sacked_out + 1;
2024}
2025
2026/* Linux NewReno/SACK/ECN state machine.
2027 * --------------------------------------
2028 *
2029 * "Open"       Normal state, no dubious events, fast path.
2030 * "Disorder"   In all the respects it is "Open",
2031 *              but requires a bit more attention. It is entered when
2032 *              we see some SACKs or dupacks. It is split of "Open"
2033 *              mainly to move some processing from fast path to slow one.
2034 * "CWR"        CWND was reduced due to some Congestion Notification event.
2035 *              It can be ECN, ICMP source quench, local device congestion.
2036 * "Recovery"   CWND was reduced, we are fast-retransmitting.
2037 * "Loss"       CWND was reduced due to RTO timeout or SACK reneging.
2038 *
2039 * tcp_fastretrans_alert() is entered:
2040 * - each incoming ACK, if state is not "Open"
2041 * - when arrived ACK is unusual, namely:
2042 *      * SACK
2043 *      * Duplicate ACK.
2044 *      * ECN ECE.
2045 *
2046 * Counting packets in flight is pretty simple.
2047 *
2048 *      in_flight = packets_out - left_out + retrans_out
2049 *
2050 *      packets_out is SND.NXT-SND.UNA counted in packets.
2051 *
2052 *      retrans_out is number of retransmitted segments.
2053 *
2054 *      left_out is number of segments left network, but not ACKed yet.
2055 *
2056 *              left_out = sacked_out + lost_out
2057 *
2058 *     sacked_out: Packets, which arrived to receiver out of order
2059 *                 and hence not ACKed. With SACKs this number is simply
2060 *                 amount of SACKed data. Even without SACKs
2061 *                 it is easy to give pretty reliable estimate of this number,
2062 *                 counting duplicate ACKs.
2063 *
2064 *       lost_out: Packets lost by network. TCP has no explicit
2065 *                 "loss notification" feedback from network (for now).
2066 *                 It means that this number can be only _guessed_.
2067 *                 Actually, it is the heuristics to predict lossage that
2068 *                 distinguishes different algorithms.
2069 *
2070 *      F.e. after RTO, when all the queue is considered as lost,
2071 *      lost_out = packets_out and in_flight = retrans_out.
2072 *
2073 *              Essentially, we have now a few algorithms detecting
2074 *              lost packets.
2075 *
2076 *              If the receiver supports SACK:
2077 *
2078 *              RFC6675/3517: It is the conventional algorithm. A packet is
2079 *              considered lost if the number of higher sequence packets
2080 *              SACKed is greater than or equal the DUPACK thoreshold
2081 *              (reordering). This is implemented in tcp_mark_head_lost and
2082 *              tcp_update_scoreboard.
2083 *
2084 *              RACK (draft-ietf-tcpm-rack-01): it is a newer algorithm
2085 *              (2017-) that checks timing instead of counting DUPACKs.
2086 *              Essentially a packet is considered lost if it's not S/ACKed
2087 *              after RTT + reordering_window, where both metrics are
2088 *              dynamically measured and adjusted. This is implemented in
2089 *              tcp_rack_mark_lost.
2090 *
2091 *              If the receiver does not support SACK:
2092 *
2093 *              NewReno (RFC6582): in Recovery we assume that one segment
2094 *              is lost (classic Reno). While we are in Recovery and
2095 *              a partial ACK arrives, we assume that one more packet
2096 *              is lost (NewReno). This heuristics are the same in NewReno
2097 *              and SACK.
2098 *
2099 * Really tricky (and requiring careful tuning) part of algorithm
2100 * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
2101 * The first determines the moment _when_ we should reduce CWND and,
2102 * hence, slow down forward transmission. In fact, it determines the moment
2103 * when we decide that hole is caused by loss, rather than by a reorder.
2104 *
2105 * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
2106 * holes, caused by lost packets.
2107 *
2108 * And the most logically complicated part of algorithm is undo
2109 * heuristics. We detect false retransmits due to both too early
2110 * fast retransmit (reordering) and underestimated RTO, analyzing
2111 * timestamps and D-SACKs. When we detect that some segments were
2112 * retransmitted by mistake and CWND reduction was wrong, we undo
2113 * window reduction and abort recovery phase. This logic is hidden
2114 * inside several functions named tcp_try_undo_<something>.
2115 */
2116
2117/* This function decides, when we should leave Disordered state
2118 * and enter Recovery phase, reducing congestion window.
2119 *
2120 * Main question: may we further continue forward transmission
2121 * with the same cwnd?
2122 */
2123static bool tcp_time_to_recover(struct sock *sk, int flag)
2124{
2125        struct tcp_sock *tp = tcp_sk(sk);
2126
2127        /* Trick#1: The loss is proven. */
2128        if (tp->lost_out)
2129                return true;
2130
2131        /* Not-A-Trick#2 : Classic rule... */
2132        if (tcp_dupack_heuristics(tp) > tp->reordering)
2133                return true;
2134
2135        return false;
2136}
2137
2138/* Detect loss in event "A" above by marking head of queue up as lost.
2139 * For non-SACK(Reno) senders, the first "packets" number of segments
2140 * are considered lost. For RFC3517 SACK, a segment is considered lost if it
2141 * has at least tp->reordering SACKed seqments above it; "packets" refers to
2142 * the maximum SACKed segments to pass before reaching this limit.
2143 */
2144static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head)
2145{
2146        struct tcp_sock *tp = tcp_sk(sk);
2147        struct sk_buff *skb;
2148        int cnt, oldcnt, lost;
2149        unsigned int mss;
2150        /* Use SACK to deduce losses of new sequences sent during recovery */
2151        const u32 loss_high = tcp_is_sack(tp) ?  tp->snd_nxt : tp->high_seq;
2152
2153        WARN_ON(packets > tp->packets_out);
2154        skb = tp->lost_skb_hint;
2155        if (skb) {
2156                /* Head already handled? */
2157                if (mark_head && after(TCP_SKB_CB(skb)->seq, tp->snd_una))
2158                        return;
2159                cnt = tp->lost_cnt_hint;
2160        } else {
2161                skb = tcp_rtx_queue_head(sk);
2162                cnt = 0;
2163        }
2164
2165        skb_rbtree_walk_from(skb) {
2166                /* TODO: do this better */
2167                /* this is not the most efficient way to do this... */
2168                tp->lost_skb_hint = skb;
2169                tp->lost_cnt_hint = cnt;
2170
2171                if (after(TCP_SKB_CB(skb)->end_seq, loss_high))
2172                        break;
2173
2174                oldcnt = cnt;
2175                if (tcp_is_reno(tp) ||
2176                    (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
2177                        cnt += tcp_skb_pcount(skb);
2178
2179                if (cnt > packets) {
2180                        if (tcp_is_sack(tp) ||
2181                            (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
2182                            (oldcnt >= packets))
2183                                break;
2184
2185                        mss = tcp_skb_mss(skb);
2186                        /* If needed, chop off the prefix to mark as lost. */
2187                        lost = (packets - oldcnt) * mss;
2188                        if (lost < skb->len &&
2189                            tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
2190                                         lost, mss, GFP_ATOMIC) < 0)
2191                                break;
2192                        cnt = packets;
2193                }
2194
2195                tcp_skb_mark_lost(tp, skb);
2196
2197                if (mark_head)
2198                        break;
2199        }
2200        tcp_verify_left_out(tp);
2201}
2202
2203/* Account newly detected lost packet(s) */
2204
2205static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
2206{
2207        struct tcp_sock *tp = tcp_sk(sk);
2208
2209        if (tcp_is_reno(tp)) {
2210                tcp_mark_head_lost(sk, 1, 1);
2211        } else {
2212                int sacked_upto = tp->sacked_out - tp->reordering;
2213                if (sacked_upto >= 0)
2214                        tcp_mark_head_lost(sk, sacked_upto, 0);
2215                else if (fast_rexmit)
2216                        tcp_mark_head_lost(sk, 1, 1);
2217        }
2218}
2219
2220static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when)
2221{
2222        return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2223               before(tp->rx_opt.rcv_tsecr, when);
2224}
2225
2226/* skb is spurious retransmitted if the returned timestamp echo
2227 * reply is prior to the skb transmission time
2228 */
2229static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp,
2230                                     const struct sk_buff *skb)
2231{
2232        return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) &&
2233               tcp_tsopt_ecr_before(tp, tcp_skb_timestamp(skb));
2234}
2235
2236/* Nothing was retransmitted or returned timestamp is less
2237 * than timestamp of the first retransmission.
2238 */
2239static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
2240{
2241        return !tp->retrans_stamp ||
2242               tcp_tsopt_ecr_before(tp, tp->retrans_stamp);
2243}
2244
2245/* Undo procedures. */
2246
2247/* We can clear retrans_stamp when there are no retransmissions in the
2248 * window. It would seem that it is trivially available for us in
2249 * tp->retrans_out, however, that kind of assumptions doesn't consider
2250 * what will happen if errors occur when sending retransmission for the
2251 * second time. ...It could the that such segment has only
2252 * TCPCB_EVER_RETRANS set at the present time. It seems that checking
2253 * the head skb is enough except for some reneging corner cases that
2254 * are not worth the effort.
2255 *
2256 * Main reason for all this complexity is the fact that connection dying
2257 * time now depends on the validity of the retrans_stamp, in particular,
2258 * that successive retransmissions of a segment must not advance
2259 * retrans_stamp under any conditions.
2260 */
2261static bool tcp_any_retrans_done(const struct sock *sk)
2262{
2263        const struct tcp_sock *tp = tcp_sk(sk);
2264        struct sk_buff *skb;
2265
2266        if (tp->retrans_out)
2267                return true;
2268
2269        skb = tcp_rtx_queue_head(sk);
2270        if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
2271                return true;
2272
2273        return false;
2274}
2275
2276static void DBGUNDO(struct sock *sk, const char *msg)
2277{
2278#if FASTRETRANS_DEBUG > 1
2279        struct tcp_sock *tp = tcp_sk(sk);
2280        struct inet_sock *inet = inet_sk(sk);
2281
2282        if (sk->sk_family == AF_INET) {
2283                pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
2284                         msg,
2285                         &inet->inet_daddr, ntohs(inet->inet_dport),
2286                         tp->snd_cwnd, tcp_left_out(tp),
2287                         tp->snd_ssthresh, tp->prior_ssthresh,
2288                         tp->packets_out);
2289        }
2290#if IS_ENABLED(CONFIG_IPV6)
2291        else if (sk->sk_family == AF_INET6) {
2292                pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
2293                         msg,
2294                         &sk->sk_v6_daddr, ntohs(inet->inet_dport),
2295                         tp->snd_cwnd, tcp_left_out(tp),
2296                         tp->snd_ssthresh, tp->prior_ssthresh,
2297                         tp->packets_out);
2298        }
2299#endif
2300#endif
2301}
2302
2303static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
2304{
2305        struct tcp_sock *tp = tcp_sk(sk);
2306
2307        if (unmark_loss) {
2308                struct sk_buff *skb;
2309
2310                skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
2311                        TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
2312                }
2313                tp->lost_out = 0;
2314                tcp_clear_all_retrans_hints(tp);
2315        }
2316
2317        if (tp->prior_ssthresh) {
2318                const struct inet_connection_sock *icsk = inet_csk(sk);
2319
2320                tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
2321
2322                if (tp->prior_ssthresh > tp->snd_ssthresh) {
2323                        tp->snd_ssthresh = tp->prior_ssthresh;
2324                        tcp_ecn_withdraw_cwr(tp);
2325                }
2326        }
2327        tp->snd_cwnd_stamp = tcp_jiffies32;
2328        tp->undo_marker = 0;
2329        tp->rack.advanced = 1; /* Force RACK to re-exam losses */
2330}
2331
2332static inline bool tcp_may_undo(const struct tcp_sock *tp)
2333{
2334        return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
2335}
2336
2337/* People celebrate: "We love our President!" */
2338static bool tcp_try_undo_recovery(struct sock *sk)
2339{
2340        struct tcp_sock *tp = tcp_sk(sk);
2341
2342        if (tcp_may_undo(tp)) {
2343                int mib_idx;
2344
2345                /* Happy end! We did not retransmit anything
2346                 * or our original transmission succeeded.
2347                 */
2348                DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
2349                tcp_undo_cwnd_reduction(sk, false);
2350                if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
2351                        mib_idx = LINUX_MIB_TCPLOSSUNDO;
2352                else
2353                        mib_idx = LINUX_MIB_TCPFULLUNDO;
2354
2355                NET_INC_STATS(sock_net(sk), mib_idx);
2356        } else if (tp->rack.reo_wnd_persist) {
2357                tp->rack.reo_wnd_persist--;
2358        }
2359        if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
2360                /* Hold old state until something *above* high_seq
2361                 * is ACKed. For Reno it is MUST to prevent false
2362                 * fast retransmits (RFC2582). SACK TCP is safe. */
2363                if (!tcp_any_retrans_done(sk))
2364                        tp->retrans_stamp = 0;
2365                return true;
2366        }
2367        tcp_set_ca_state(sk, TCP_CA_Open);
2368        tp->is_sack_reneg = 0;
2369        return false;
2370}
2371
2372/* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
2373static bool tcp_try_undo_dsack(struct sock *sk)
2374{
2375        struct tcp_sock *tp = tcp_sk(sk);
2376
2377        if (tp->undo_marker && !tp->undo_retrans) {
2378                tp->rack.reo_wnd_persist = min(TCP_RACK_RECOVERY_THRESH,
2379                                               tp->rack.reo_wnd_persist + 1);
2380                DBGUNDO(sk, "D-SACK");
2381                tcp_undo_cwnd_reduction(sk, false);
2382                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
2383                return true;
2384        }
2385        return false;
2386}
2387
2388/* Undo during loss recovery after partial ACK or using F-RTO. */
2389static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
2390{
2391        struct tcp_sock *tp = tcp_sk(sk);
2392
2393        if (frto_undo || tcp_may_undo(tp)) {
2394                tcp_undo_cwnd_reduction(sk, true);
2395
2396                DBGUNDO(sk, "partial loss");
2397                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
2398                if (frto_undo)
2399                        NET_INC_STATS(sock_net(sk),
2400                                        LINUX_MIB_TCPSPURIOUSRTOS);
2401                inet_csk(sk)->icsk_retransmits = 0;
2402                if (frto_undo || tcp_is_sack(tp)) {
2403                        tcp_set_ca_state(sk, TCP_CA_Open);
2404                        tp->is_sack_reneg = 0;
2405                }
2406                return true;
2407        }
2408        return false;
2409}
2410
2411/* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937.
2412 * It computes the number of packets to send (sndcnt) based on packets newly
2413 * delivered:
2414 *   1) If the packets in flight is larger than ssthresh, PRR spreads the
2415 *      cwnd reductions across a full RTT.
2416 *   2) Otherwise PRR uses packet conservation to send as much as delivered.
2417 *      But when the retransmits are acked without further losses, PRR
2418 *      slow starts cwnd up to ssthresh to speed up the recovery.
2419 */
2420static void tcp_init_cwnd_reduction(struct sock *sk)
2421{
2422        struct tcp_sock *tp = tcp_sk(sk);
2423
2424        tp->high_seq = tp->snd_nxt;
2425        tp->tlp_high_seq = 0;
2426        tp->snd_cwnd_cnt = 0;
2427        tp->prior_cwnd = tp->snd_cwnd;
2428        tp->prr_delivered = 0;
2429        tp->prr_out = 0;
2430        tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
2431        tcp_ecn_queue_cwr(tp);
2432}
2433
2434void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int flag)
2435{
2436        struct tcp_sock *tp = tcp_sk(sk);
2437        int sndcnt = 0;
2438        int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
2439
2440        if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
2441                return;
2442
2443        tp->prr_delivered += newly_acked_sacked;
2444        if (delta < 0) {
2445                u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
2446                               tp->prior_cwnd - 1;
2447                sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
2448        } else if ((flag & FLAG_RETRANS_DATA_ACKED) &&
2449                   !(flag & FLAG_LOST_RETRANS)) {
2450                sndcnt = min_t(int, delta,
2451                               max_t(int, tp->prr_delivered - tp->prr_out,
2452                                     newly_acked_sacked) + 1);
2453        } else {
2454                sndcnt = min(delta, newly_acked_sacked);
2455        }
2456        /* Force a fast retransmit upon entering fast recovery */
2457        sndcnt = max(sndcnt, (tp->prr_out ? 0 : 1));
2458        tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
2459}
2460
2461static inline void tcp_end_cwnd_reduction(struct sock *sk)
2462{
2463        struct tcp_sock *tp = tcp_sk(sk);
2464
2465        if (inet_csk(sk)->icsk_ca_ops->cong_control)
2466                return;
2467
2468        /* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
2469        if (tp->snd_ssthresh < TCP_INFINITE_SSTHRESH &&
2470            (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || tp->undo_marker)) {
2471                tp->snd_cwnd = tp->snd_ssthresh;
2472                tp->snd_cwnd_stamp = tcp_jiffies32;
2473        }
2474        tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
2475}
2476
2477/* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
2478void tcp_enter_cwr(struct sock *sk)
2479{
2480        struct tcp_sock *tp = tcp_sk(sk);
2481
2482        tp->prior_ssthresh = 0;
2483        if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
2484                tp->undo_marker = 0;
2485                tcp_init_cwnd_reduction(sk);
2486                tcp_set_ca_state(sk, TCP_CA_CWR);
2487        }
2488}
2489EXPORT_SYMBOL(tcp_enter_cwr);
2490
2491static void tcp_try_keep_open(struct sock *sk)
2492{
2493        struct tcp_sock *tp = tcp_sk(sk);
2494        int state = TCP_CA_Open;
2495
2496        if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
2497                state = TCP_CA_Disorder;
2498
2499        if (inet_csk(sk)->icsk_ca_state != state) {
2500                tcp_set_ca_state(sk, state);
2501                tp->high_seq = tp->snd_nxt;
2502        }
2503}
2504
2505static void tcp_try_to_open(struct sock *sk, int flag)
2506{
2507        struct tcp_sock *tp = tcp_sk(sk);
2508
2509        tcp_verify_left_out(tp);
2510
2511        if (!tcp_any_retrans_done(sk))
2512                tp->retrans_stamp = 0;
2513
2514        if (flag & FLAG_ECE)
2515                tcp_enter_cwr(sk);
2516
2517        if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
2518                tcp_try_keep_open(sk);
2519        }
2520}
2521
2522static void tcp_mtup_probe_failed(struct sock *sk)
2523{
2524        struct inet_connection_sock *icsk = inet_csk(sk);
2525
2526        icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
2527        icsk->icsk_mtup.probe_size = 0;
2528        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPFAIL);
2529}
2530
2531static void tcp_mtup_probe_success(struct sock *sk)
2532{
2533        struct tcp_sock *tp = tcp_sk(sk);
2534        struct inet_connection_sock *icsk = inet_csk(sk);
2535
2536        /* FIXME: breaks with very large cwnd */
2537        tp->prior_ssthresh = tcp_current_ssthresh(sk);
2538        tp->snd_cwnd = tp->snd_cwnd *
2539                       tcp_mss_to_mtu(sk, tp->mss_cache) /
2540                       icsk->icsk_mtup.probe_size;
2541        tp->snd_cwnd_cnt = 0;
2542        tp->snd_cwnd_stamp = tcp_jiffies32;
2543        tp->snd_ssthresh = tcp_current_ssthresh(sk);
2544
2545        icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
2546        icsk->icsk_mtup.probe_size = 0;
2547        tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2548        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
2549}
2550
2551/* Do a simple retransmit without using the backoff mechanisms in
2552 * tcp_timer. This is used for path mtu discovery.
2553 * The socket is already locked here.
2554 */
2555void tcp_simple_retransmit(struct sock *sk)
2556{
2557        const struct inet_connection_sock *icsk = inet_csk(sk);
2558        struct tcp_sock *tp = tcp_sk(sk);
2559        struct sk_buff *skb;
2560        unsigned int mss = tcp_current_mss(sk);
2561
2562        skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
2563                if (tcp_skb_seglen(skb) > mss &&
2564                    !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
2565                        if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
2566                                TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
2567                                tp->retrans_out -= tcp_skb_pcount(skb);
2568                        }
2569                        tcp_skb_mark_lost_uncond_verify(tp, skb);
2570                }
2571        }
2572
2573        tcp_clear_retrans_hints_partial(tp);
2574
2575        if (!tp->lost_out)
2576                return;
2577
2578        if (tcp_is_reno(tp))
2579                tcp_limit_reno_sacked(tp);
2580
2581        tcp_verify_left_out(tp);
2582
2583        /* Don't muck with the congestion window here.
2584         * Reason is that we do not increase amount of _data_
2585         * in network, but units changed and effective
2586         * cwnd/ssthresh really reduced now.
2587         */
2588        if (icsk->icsk_ca_state != TCP_CA_Loss) {
2589                tp->high_seq = tp->snd_nxt;
2590                tp->snd_ssthresh = tcp_current_ssthresh(sk);
2591                tp->prior_ssthresh = 0;
2592                tp->undo_marker = 0;
2593                tcp_set_ca_state(sk, TCP_CA_Loss);
2594        }
2595        tcp_xmit_retransmit_queue(sk);
2596}
2597EXPORT_SYMBOL(tcp_simple_retransmit);
2598
2599void tcp_enter_recovery(struct sock *sk, bool ece_ack)
2600{
2601        struct tcp_sock *tp = tcp_sk(sk);
2602        int mib_idx;
2603
2604        if (tcp_is_reno(tp))
2605                mib_idx = LINUX_MIB_TCPRENORECOVERY;
2606        else
2607                mib_idx = LINUX_MIB_TCPSACKRECOVERY;
2608
2609        NET_INC_STATS(sock_net(sk), mib_idx);
2610
2611        tp->prior_ssthresh = 0;
2612        tcp_init_undo(tp);
2613
2614        if (!tcp_in_cwnd_reduction(sk)) {
2615                if (!ece_ack)
2616                        tp->prior_ssthresh = tcp_current_ssthresh(sk);
2617                tcp_init_cwnd_reduction(sk);
2618        }
2619        tcp_set_ca_state(sk, TCP_CA_Recovery);
2620}
2621
2622/* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
2623 * recovered or spurious. Otherwise retransmits more on partial ACKs.
2624 */
2625static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack,
2626                             int *rexmit)
2627{
2628        struct tcp_sock *tp = tcp_sk(sk);
2629        bool recovered = !before(tp->snd_una, tp->high_seq);
2630
2631        if ((flag & FLAG_SND_UNA_ADVANCED) &&
2632            tcp_try_undo_loss(sk, false))
2633                return;
2634
2635        if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
2636                /* Step 3.b. A timeout is spurious if not all data are
2637                 * lost, i.e., never-retransmitted data are (s)acked.
2638                 */
2639                if ((flag & FLAG_ORIG_SACK_ACKED) &&
2640                    tcp_try_undo_loss(sk, true))
2641                        return;
2642
2643                if (after(tp->snd_nxt, tp->high_seq)) {
2644                        if (flag & FLAG_DATA_SACKED || is_dupack)
2645                                tp->frto = 0; /* Step 3.a. loss was real */
2646                } else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
2647                        tp->high_seq = tp->snd_nxt;
2648                        /* Step 2.b. Try send new data (but deferred until cwnd
2649                         * is updated in tcp_ack()). Otherwise fall back to
2650                         * the conventional recovery.
2651                         */
2652                        if (!tcp_write_queue_empty(sk) &&
2653                            after(tcp_wnd_end(tp), tp->snd_nxt)) {
2654                                *rexmit = REXMIT_NEW;
2655                                return;
2656                        }
2657                        tp->frto = 0;
2658                }
2659        }
2660
2661        if (recovered) {
2662                /* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
2663                tcp_try_undo_recovery(sk);
2664                return;
2665        }
2666        if (tcp_is_reno(tp)) {
2667                /* A Reno DUPACK means new data in F-RTO step 2.b above are
2668                 * delivered. Lower inflight to clock out (re)tranmissions.
2669                 */
2670                if (after(tp->snd_nxt, tp->high_seq) && is_dupack)
2671                        tcp_add_reno_sack(sk);
2672                else if (flag & FLAG_SND_UNA_ADVANCED)
2673                        tcp_reset_reno_sack(tp);
2674        }
2675        *rexmit = REXMIT_LOST;
2676}
2677
2678/* Undo during fast recovery after partial ACK. */
2679static bool tcp_try_undo_partial(struct sock *sk, u32 prior_snd_una)
2680{
2681        struct tcp_sock *tp = tcp_sk(sk);
2682
2683        if (tp->undo_marker && tcp_packet_delayed(tp)) {
2684                /* Plain luck! Hole if filled with delayed
2685                 * packet, rather than with a retransmit. Check reordering.
2686                 */
2687                tcp_check_sack_reordering(sk, prior_snd_una, 1);
2688
2689                /* We are getting evidence that the reordering degree is higher
2690                 * than we realized. If there are no retransmits out then we
2691                 * can undo. Otherwise we clock out new packets but do not
2692                 * mark more packets lost or retransmit more.
2693                 */
2694                if (tp->retrans_out)
2695                        return true;
2696
2697                if (!tcp_any_retrans_done(sk))
2698                        tp->retrans_stamp = 0;
2699
2700                DBGUNDO(sk, "partial recovery");
2701                tcp_undo_cwnd_reduction(sk, true);
2702                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
2703                tcp_try_keep_open(sk);
2704                return true;
2705        }
2706        return false;
2707}
2708
2709static void tcp_rack_identify_loss(struct sock *sk, int *ack_flag)
2710{
2711        struct tcp_sock *tp = tcp_sk(sk);
2712
2713        /* Use RACK to detect loss */
2714        if (sock_net(sk)->ipv4.sysctl_tcp_recovery & TCP_RACK_LOSS_DETECTION) {
2715                u32 prior_retrans = tp->retrans_out;
2716
2717                tcp_rack_mark_lost(sk);
2718                if (prior_retrans > tp->retrans_out)
2719                        *ack_flag |= FLAG_LOST_RETRANS;
2720        }
2721}
2722
2723static bool tcp_force_fast_retransmit(struct sock *sk)
2724{
2725        struct tcp_sock *tp = tcp_sk(sk);
2726
2727        return after(tcp_highest_sack_seq(tp),
2728                     tp->snd_una + tp->reordering * tp->mss_cache);
2729}
2730
2731/* Process an event, which can update packets-in-flight not trivially.
2732 * Main goal of this function is to calculate new estimate for left_out,
2733 * taking into account both packets sitting in receiver's buffer and
2734 * packets lost by network.
2735 *
2736 * Besides that it updates the congestion state when packet loss or ECN
2737 * is detected. But it does not reduce the cwnd, it is done by the
2738 * congestion control later.
2739 *
2740 * It does _not_ decide what to send, it is made in function
2741 * tcp_xmit_retransmit_queue().
2742 */
2743static void tcp_fastretrans_alert(struct sock *sk, const u32 prior_snd_una,
2744                                  bool is_dupack, int *ack_flag, int *rexmit)
2745{
2746        struct inet_connection_sock *icsk = inet_csk(sk);
2747        struct tcp_sock *tp = tcp_sk(sk);
2748        int fast_rexmit = 0, flag = *ack_flag;
2749        bool do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) &&
2750                                     tcp_force_fast_retransmit(sk));
2751
2752        if (!tp->packets_out && tp->sacked_out)
2753                tp->sacked_out = 0;
2754
2755        /* Now state machine starts.
2756         * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
2757        if (flag & FLAG_ECE)
2758                tp->prior_ssthresh = 0;
2759
2760        /* B. In all the states check for reneging SACKs. */
2761        if (tcp_check_sack_reneging(sk, flag))
2762                return;
2763
2764        /* C. Check consistency of the current state. */
2765        tcp_verify_left_out(tp);
2766
2767        /* D. Check state exit conditions. State can be terminated
2768         *    when high_seq is ACKed. */
2769        if (icsk->icsk_ca_state == TCP_CA_Open) {
2770                WARN_ON(tp->retrans_out != 0);
2771                tp->retrans_stamp = 0;
2772        } else if (!before(tp->snd_una, tp->high_seq)) {
2773                switch (icsk->icsk_ca_state) {
2774                case TCP_CA_CWR:
2775                        /* CWR is to be held something *above* high_seq
2776                         * is ACKed for CWR bit to reach receiver. */
2777                        if (tp->snd_una != tp->high_seq) {
2778                                tcp_end_cwnd_reduction(sk);
2779                                tcp_set_ca_state(sk, TCP_CA_Open);
2780                        }
2781                        break;
2782
2783                case TCP_CA_Recovery:
2784                        if (tcp_is_reno(tp))
2785                                tcp_reset_reno_sack(tp);
2786                        if (tcp_try_undo_recovery(sk))
2787                                return;
2788                        tcp_end_cwnd_reduction(sk);
2789                        break;
2790                }
2791        }
2792
2793        /* E. Process state. */
2794        switch (icsk->icsk_ca_state) {
2795        case TCP_CA_Recovery:
2796                if (!(flag & FLAG_SND_UNA_ADVANCED)) {
2797                        if (tcp_is_reno(tp) && is_dupack)
2798                                tcp_add_reno_sack(sk);
2799                } else {
2800                        if (tcp_try_undo_partial(sk, prior_snd_una))
2801                                return;
2802                        /* Partial ACK arrived. Force fast retransmit. */
2803                        do_lost = tcp_is_reno(tp) ||
2804                                  tcp_force_fast_retransmit(sk);
2805                }
2806                if (tcp_try_undo_dsack(sk)) {
2807                        tcp_try_keep_open(sk);
2808                        return;
2809                }
2810                tcp_rack_identify_loss(sk, ack_flag);
2811                break;
2812        case TCP_CA_Loss:
2813                tcp_process_loss(sk, flag, is_dupack, rexmit);
2814                tcp_rack_identify_loss(sk, ack_flag);
2815                if (!(icsk->icsk_ca_state == TCP_CA_Open ||
2816                      (*ack_flag & FLAG_LOST_RETRANS)))
2817                        return;
2818                /* Change state if cwnd is undone or retransmits are lost */
2819                /* fall through */
2820        default:
2821                if (tcp_is_reno(tp)) {
2822                        if (flag & FLAG_SND_UNA_ADVANCED)
2823                                tcp_reset_reno_sack(tp);
2824                        if (is_dupack)
2825                                tcp_add_reno_sack(sk);
2826                }
2827
2828                if (icsk->icsk_ca_state <= TCP_CA_Disorder)
2829                        tcp_try_undo_dsack(sk);
2830
2831                tcp_rack_identify_loss(sk, ack_flag);
2832                if (!tcp_time_to_recover(sk, flag)) {
2833                        tcp_try_to_open(sk, flag);
2834                        return;
2835                }
2836
2837                /* MTU probe failure: don't reduce cwnd */
2838                if (icsk->icsk_ca_state < TCP_CA_CWR &&
2839                    icsk->icsk_mtup.probe_size &&
2840                    tp->snd_una == tp->mtu_probe.probe_seq_start) {
2841                        tcp_mtup_probe_failed(sk);
2842                        /* Restores the reduction we did in tcp_mtup_probe() */
2843                        tp->snd_cwnd++;
2844                        tcp_simple_retransmit(sk);
2845                        return;
2846                }
2847
2848                /* Otherwise enter Recovery state */
2849                tcp_enter_recovery(sk, (flag & FLAG_ECE));
2850                fast_rexmit = 1;
2851        }
2852
2853        if (do_lost)
2854                tcp_update_scoreboard(sk, fast_rexmit);
2855        *rexmit = REXMIT_LOST;
2856}
2857
2858static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us)
2859{
2860        u32 wlen = sock_net(sk)->ipv4.sysctl_tcp_min_rtt_wlen * HZ;
2861        struct tcp_sock *tp = tcp_sk(sk);
2862
2863        minmax_running_min(&tp->rtt_min, wlen, tcp_jiffies32,
2864                           rtt_us ? : jiffies_to_usecs(1));
2865}
2866
2867static bool tcp_ack_update_rtt(struct sock *sk, const int flag,
2868                               long seq_rtt_us, long sack_rtt_us,
2869                               long ca_rtt_us, struct rate_sample *rs)
2870{
2871        const struct tcp_sock *tp = tcp_sk(sk);
2872
2873        /* Prefer RTT measured from ACK's timing to TS-ECR. This is because
2874         * broken middle-boxes or peers may corrupt TS-ECR fields. But
2875         * Karn's algorithm forbids taking RTT if some retransmitted data
2876         * is acked (RFC6298).
2877         */
2878        if (seq_rtt_us < 0)
2879                seq_rtt_us = sack_rtt_us;
2880
2881        /* RTTM Rule: A TSecr value received in a segment is used to
2882         * update the averaged RTT measurement only if the segment
2883         * acknowledges some new data, i.e., only if it advances the
2884         * left edge of the send window.
2885         * See draft-ietf-tcplw-high-performance-00, section 3.3.
2886         */
2887        if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2888            flag & FLAG_ACKED) {
2889                u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
2890                u32 delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
2891
2892                seq_rtt_us = ca_rtt_us = delta_us;
2893        }
2894        rs->rtt_us = ca_rtt_us; /* RTT of last (S)ACKed packet (or -1) */
2895        if (seq_rtt_us < 0)
2896                return false;
2897
2898        /* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is
2899         * always taken together with ACK, SACK, or TS-opts. Any negative
2900         * values will be skipped with the seq_rtt_us < 0 check above.
2901         */
2902        tcp_update_rtt_min(sk, ca_rtt_us);
2903        tcp_rtt_estimator(sk, seq_rtt_us);
2904        tcp_set_rto(sk);
2905
2906        /* RFC6298: only reset backoff on valid RTT measurement. */
2907        inet_csk(sk)->icsk_backoff = 0;
2908        return true;
2909}
2910
2911/* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */
2912void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req)
2913{
2914        struct rate_sample rs;
2915        long rtt_us = -1L;
2916
2917        if (req && !req->num_retrans && tcp_rsk(req)->snt_synack)
2918                rtt_us = tcp_stamp_us_delta(tcp_clock_us(), tcp_rsk(req)->snt_synack);
2919
2920        tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us, &rs);
2921}
2922
2923
2924static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked)
2925{
2926        const struct inet_connection_sock *icsk = inet_csk(sk);
2927
2928        icsk->icsk_ca_ops->cong_avoid(sk, ack, acked);
2929        tcp_sk(sk)->snd_cwnd_stamp = tcp_jiffies32;
2930}
2931
2932/* Restart timer after forward progress on connection.
2933 * RFC2988 recommends to restart timer to now+rto.
2934 */
2935void tcp_rearm_rto(struct sock *sk)
2936{
2937        const struct inet_connection_sock *icsk = inet_csk(sk);
2938        struct tcp_sock *tp = tcp_sk(sk);
2939
2940        /* If the retrans timer is currently being used by Fast Open
2941         * for SYN-ACK retrans purpose, stay put.
2942         */
2943        if (tp->fastopen_rsk)
2944                return;
2945
2946        if (!tp->packets_out) {
2947                inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
2948        } else {
2949                u32 rto = inet_csk(sk)->icsk_rto;
2950                /* Offset the time elapsed after installing regular RTO */
2951                if (icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
2952                    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
2953                        s64 delta_us = tcp_rto_delta_us(sk);
2954                        /* delta_us may not be positive if the socket is locked
2955                         * when the retrans timer fires and is rescheduled.
2956                         */
2957                        rto = usecs_to_jiffies(max_t(int, delta_us, 1));
2958                }
2959                inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto,
2960                                          TCP_RTO_MAX);
2961        }
2962}
2963
2964/* Try to schedule a loss probe; if that doesn't work, then schedule an RTO. */
2965static void tcp_set_xmit_timer(struct sock *sk)
2966{
2967        if (!tcp_schedule_loss_probe(sk, true))
2968                tcp_rearm_rto(sk);
2969}
2970
2971/* If we get here, the whole TSO packet has not been acked. */
2972static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
2973{
2974        struct tcp_sock *tp = tcp_sk(sk);
2975        u32 packets_acked;
2976
2977        BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
2978
2979        packets_acked = tcp_skb_pcount(skb);
2980        if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
2981                return 0;
2982        packets_acked -= tcp_skb_pcount(skb);
2983
2984        if (packets_acked) {
2985                BUG_ON(tcp_skb_pcount(skb) == 0);
2986                BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
2987        }
2988
2989        return packets_acked;
2990}
2991
2992static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb,
2993                           u32 prior_snd_una)
2994{
2995        const struct skb_shared_info *shinfo;
2996
2997        /* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */
2998        if (likely(!TCP_SKB_CB(skb)->txstamp_ack))
2999                return;
3000
3001        shinfo = skb_shinfo(skb);
3002        if (!before(shinfo->tskey, prior_snd_una) &&
3003            before(shinfo->tskey, tcp_sk(sk)->snd_una)) {
3004                tcp_skb_tsorted_save(skb) {
3005                        __skb_tstamp_tx(skb, NULL, sk, SCM_TSTAMP_ACK);
3006                } tcp_skb_tsorted_restore(skb);
3007        }
3008}
3009
3010/* Remove acknowledged frames from the retransmission queue. If our packet
3011 * is before the ack sequence we can discard it as it's confirmed to have
3012 * arrived at the other end.
3013 */
3014static int tcp_clean_rtx_queue(struct sock *sk, u32 prior_fack,
3015                               u32 prior_snd_una,
3016                               struct tcp_sacktag_state *sack)
3017{
3018        const struct inet_connection_sock *icsk = inet_csk(sk);
3019        u64 first_ackt, last_ackt;
3020        struct tcp_sock *tp = tcp_sk(sk);
3021        u32 prior_sacked = tp->sacked_out;
3022        u32 reord = tp->snd_nxt; /* lowest acked un-retx un-sacked seq */
3023        struct sk_buff *skb, *next;
3024        bool fully_acked = true;
3025        long sack_rtt_us = -1L;
3026        long seq_rtt_us = -1L;
3027        long ca_rtt_us = -1L;
3028        u32 pkts_acked = 0;
3029        u32 last_in_flight = 0;
3030        bool rtt_update;
3031        int flag = 0;
3032
3033        first_ackt = 0;
3034
3035        for (skb = skb_rb_first(&sk->tcp_rtx_queue); skb; skb = next) {
3036                struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
3037                const u32 start_seq = scb->seq;
3038                u8 sacked = scb->sacked;
3039                u32 acked_pcount;
3040
3041                tcp_ack_tstamp(sk, skb, prior_snd_una);
3042
3043                /* Determine how many packets and what bytes were acked, tso and else */
3044                if (after(scb->end_seq, tp->snd_una)) {
3045                        if (tcp_skb_pcount(skb) == 1 ||
3046                            !after(tp->snd_una, scb->seq))
3047                                break;
3048
3049                        acked_pcount = tcp_tso_acked(sk, skb);
3050                        if (!acked_pcount)
3051                                break;
3052                        fully_acked = false;
3053                } else {
3054                        acked_pcount = tcp_skb_pcount(skb);
3055                }
3056
3057                if (unlikely(sacked & TCPCB_RETRANS)) {
3058                        if (sacked & TCPCB_SACKED_RETRANS)
3059                                tp->retrans_out -= acked_pcount;
3060                        flag |= FLAG_RETRANS_DATA_ACKED;
3061                } else if (!(sacked & TCPCB_SACKED_ACKED)) {
3062                        last_ackt = skb->skb_mstamp;
3063                        WARN_ON_ONCE(last_ackt == 0);
3064                        if (!first_ackt)
3065                                first_ackt = last_ackt;
3066
3067                        last_in_flight = TCP_SKB_CB(skb)->tx.in_flight;
3068                        if (before(start_seq, reord))
3069                                reord = start_seq;
3070                        if (!after(scb->end_seq, tp->high_seq))
3071                                flag |= FLAG_ORIG_SACK_ACKED;
3072                }
3073
3074                if (sacked & TCPCB_SACKED_ACKED) {
3075                        tp->sacked_out -= acked_pcount;
3076                } else if (tcp_is_sack(tp)) {
3077                        tp->delivered += acked_pcount;
3078                        if (!tcp_skb_spurious_retrans(tp, skb))
3079                                tcp_rack_advance(tp, sacked, scb->end_seq,
3080                                                 skb->skb_mstamp);
3081                }
3082                if (sacked & TCPCB_LOST)
3083                        tp->lost_out -= acked_pcount;
3084
3085                tp->packets_out -= acked_pcount;
3086                pkts_acked += acked_pcount;
3087                tcp_rate_skb_delivered(sk, skb, sack->rate);
3088
3089                /* Initial outgoing SYN's get put onto the write_queue
3090                 * just like anything else we transmit.  It is not
3091                 * true data, and if we misinform our callers that
3092                 * this ACK acks real data, we will erroneously exit
3093                 * connection startup slow start one packet too
3094                 * quickly.  This is severely frowned upon behavior.
3095                 */
3096                if (likely(!(scb->tcp_flags & TCPHDR_SYN))) {
3097                        flag |= FLAG_DATA_ACKED;
3098                } else {
3099                        flag |= FLAG_SYN_ACKED;
3100                        tp->retrans_stamp = 0;
3101                }
3102
3103                if (!fully_acked)
3104                        break;
3105
3106                next = skb_rb_next(skb);
3107                if (unlikely(skb == tp->retransmit_skb_hint))
3108                        tp->retransmit_skb_hint = NULL;
3109                if (unlikely(skb == tp->lost_skb_hint))
3110                        tp->lost_skb_hint = NULL;
3111                tcp_rtx_queue_unlink_and_free(skb, sk);
3112        }
3113
3114        if (!skb)
3115                tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
3116
3117        if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
3118                tp->snd_up = tp->snd_una;
3119
3120        if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
3121                flag |= FLAG_SACK_RENEGING;
3122
3123        if (likely(first_ackt) && !(flag & FLAG_RETRANS_DATA_ACKED)) {
3124                seq_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, first_ackt);
3125                ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, last_ackt);
3126        }
3127        if (sack->first_sackt) {
3128                sack_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->first_sackt);
3129                ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->last_sackt);
3130        }
3131        rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us,
3132                                        ca_rtt_us, sack->rate);
3133
3134        if (flag & FLAG_ACKED) {
3135                flag |= FLAG_SET_XMIT_TIMER;  /* set TLP or RTO timer */
3136                if (unlikely(icsk->icsk_mtup.probe_size &&
3137                             !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
3138                        tcp_mtup_probe_success(sk);
3139                }
3140
3141                if (tcp_is_reno(tp)) {
3142                        tcp_remove_reno_sacks(sk, pkts_acked);
3143                } else {
3144                        int delta;
3145
3146                        /* Non-retransmitted hole got filled? That's reordering */
3147                        if (before(reord, prior_fack))
3148                                tcp_check_sack_reordering(sk, reord, 0);
3149
3150                        delta = prior_sacked - tp->sacked_out;
3151                        tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta);
3152                }
3153        } else if (skb && rtt_update && sack_rtt_us >= 0 &&
3154                   sack_rtt_us > tcp_stamp_us_delta(tp->tcp_mstamp, skb->skb_mstamp)) {
3155                /* Do not re-arm RTO if the sack RTT is measured from data sent
3156                 * after when the head was last (re)transmitted. Otherwise the
3157                 * timeout may continue to extend in loss recovery.
3158                 */
3159                flag |= FLAG_SET_XMIT_TIMER;  /* set TLP or RTO timer */
3160        }
3161
3162        if (icsk->icsk_ca_ops->pkts_acked) {
3163                struct ack_sample sample = { .pkts_acked = pkts_acked,
3164                                             .rtt_us = sack->rate->rtt_us,
3165                                             .in_flight = last_in_flight };
3166
3167                icsk->icsk_ca_ops->pkts_acked(sk, &sample);
3168        }
3169
3170#if FASTRETRANS_DEBUG > 0
3171        WARN_ON((int)tp->sacked_out < 0);
3172        WARN_ON((int)tp->lost_out < 0);
3173        WARN_ON((int)tp->retrans_out < 0);
3174        if (!tp->packets_out && tcp_is_sack(tp)) {
3175                icsk = inet_csk(sk);
3176                if (tp->lost_out) {
3177                        pr_debug("Leak l=%u %d\n",
3178                                 tp->lost_out, icsk->icsk_ca_state);
3179                        tp->lost_out = 0;
3180                }
3181                if (tp->sacked_out) {
3182                        pr_debug("Leak s=%u %d\n",
3183                                 tp->sacked_out, icsk->icsk_ca_state);
3184                        tp->sacked_out = 0;
3185                }
3186                if (tp->retrans_out) {
3187                        pr_debug("Leak r=%u %d\n",
3188                                 tp->retrans_out, icsk->icsk_ca_state);
3189                        tp->retrans_out = 0;
3190                }
3191        }
3192#endif
3193        return flag;
3194}
3195
3196static void tcp_ack_probe(struct sock *sk)
3197{
3198        struct inet_connection_sock *icsk = inet_csk(sk);
3199        struct sk_buff *head = tcp_send_head(sk);
3200        const struct tcp_sock *tp = tcp_sk(sk);
3201
3202        /* Was it a usable window open? */
3203        if (!head)
3204                return;
3205        if (!after(TCP_SKB_CB(head)->end_seq, tcp_wnd_end(tp))) {
3206                icsk->icsk_backoff = 0;
3207                inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
3208                /* Socket must be waked up by subsequent tcp_data_snd_check().
3209                 * This function is not for random using!
3210                 */
3211        } else {
3212                unsigned long when = tcp_probe0_when(sk, TCP_RTO_MAX);
3213
3214                inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
3215                                          when, TCP_RTO_MAX);
3216        }
3217}
3218
3219static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
3220{
3221        return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
3222                inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
3223}
3224
3225/* Decide wheather to run the increase function of congestion control. */
3226static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
3227{
3228        /* If reordering is high then always grow cwnd whenever data is
3229         * delivered regardless of its ordering. Otherwise stay conservative
3230         * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
3231         * new SACK or ECE mark may first advance cwnd here and later reduce
3232         * cwnd in tcp_fastretrans_alert() based on more states.
3233         */
3234        if (tcp_sk(sk)->reordering > sock_net(sk)->ipv4.sysctl_tcp_reordering)
3235                return flag & FLAG_FORWARD_PROGRESS;
3236
3237        return flag & FLAG_DATA_ACKED;
3238}
3239
3240/* The "ultimate" congestion control function that aims to replace the rigid
3241 * cwnd increase and decrease control (tcp_cong_avoid,tcp_*cwnd_reduction).
3242 * It's called toward the end of processing an ACK with precise rate
3243 * information. All transmission or retransmission are delayed afterwards.
3244 */
3245static void tcp_cong_control(struct sock *sk, u32 ack, u32 acked_sacked,
3246                             int flag, const struct rate_sample *rs)
3247{
3248        const struct inet_connection_sock *icsk = inet_csk(sk);
3249
3250        if (icsk->icsk_ca_ops->cong_control) {
3251                icsk->icsk_ca_ops->cong_control(sk, rs);
3252                return;
3253        }
3254
3255        if (tcp_in_cwnd_reduction(sk)) {
3256                /* Reduce cwnd if state mandates */
3257                tcp_cwnd_reduction(sk, acked_sacked, flag);
3258        } else if (tcp_may_raise_cwnd(sk, flag)) {
3259                /* Advance cwnd if state allows */
3260                tcp_cong_avoid(sk, ack, acked_sacked);
3261        }
3262        tcp_update_pacing_rate(sk);
3263}
3264
3265/* Check that window update is acceptable.
3266 * The function assumes that snd_una<=ack<=snd_next.
3267 */
3268static inline bool tcp_may_update_window(const struct tcp_sock *tp,
3269                                        const u32 ack, const u32 ack_seq,
3270                                        const u32 nwin)
3271{
3272        return  after(ack, tp->snd_una) ||
3273                after(ack_seq, tp->snd_wl1) ||
3274                (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd);
3275}
3276
3277/* If we update tp->snd_una, also update tp->bytes_acked */
3278static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack)
3279{
3280        u32 delta = ack - tp->snd_una;
3281
3282        sock_owned_by_me((struct sock *)tp);
3283        tp->bytes_acked += delta;
3284        tp->snd_una = ack;
3285}
3286
3287/* If we update tp->rcv_nxt, also update tp->bytes_received */
3288static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq)
3289{
3290        u32 delta = seq - tp->rcv_nxt;
3291
3292        sock_owned_by_me((struct sock *)tp);
3293        tp->bytes_received += delta;
3294        tp->rcv_nxt = seq;
3295}
3296
3297/* Update our send window.
3298 *
3299 * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
3300 * and in FreeBSD. NetBSD's one is even worse.) is wrong.
3301 */
3302static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
3303                                 u32 ack_seq)
3304{
3305        struct tcp_sock *tp = tcp_sk(sk);
3306        int flag = 0;
3307        u32 nwin = ntohs(tcp_hdr(skb)->window);
3308
3309        if (likely(!tcp_hdr(skb)->syn))
3310                nwin <<= tp->rx_opt.snd_wscale;
3311
3312        if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
3313                flag |= FLAG_WIN_UPDATE;
3314                tcp_update_wl(tp, ack_seq);
3315
3316                if (tp->snd_wnd != nwin) {
3317                        tp->snd_wnd = nwin;
3318
3319                        /* Note, it is the only place, where
3320                         * fast path is recovered for sending TCP.
3321                         */
3322                        tp->pred_flags = 0;
3323                        tcp_fast_path_check(sk);
3324
3325                        if (!tcp_write_queue_empty(sk))
3326                                tcp_slow_start_after_idle_check(sk);
3327
3328                        if (nwin > tp->max_window) {
3329                                tp->max_window = nwin;
3330                                tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
3331                        }
3332                }
3333        }
3334
3335        tcp_snd_una_update(tp, ack);
3336
3337        return flag;
3338}
3339
3340static bool __tcp_oow_rate_limited(struct net *net, int mib_idx,
3341                                   u32 *last_oow_ack_time)
3342{
3343        if (*last_oow_ack_time) {
3344                s32 elapsed = (s32)(tcp_jiffies32 - *last_oow_ack_time);
3345
3346                if (0 <= elapsed && elapsed < net->ipv4.sysctl_tcp_invalid_ratelimit) {
3347                        NET_INC_STATS(net, mib_idx);
3348                        return true;    /* rate-limited: don't send yet! */
3349                }
3350        }
3351
3352        *last_oow_ack_time = tcp_jiffies32;
3353
3354        return false;   /* not rate-limited: go ahead, send dupack now! */
3355}
3356
3357/* Return true if we're currently rate-limiting out-of-window ACKs and
3358 * thus shouldn't send a dupack right now. We rate-limit dupacks in
3359 * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS
3360 * attacks that send repeated SYNs or ACKs for the same connection. To
3361 * do this, we do not send a duplicate SYNACK or ACK if the remote
3362 * endpoint is sending out-of-window SYNs or pure ACKs at a high rate.
3363 */
3364bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb,
3365                          int mib_idx, u32 *last_oow_ack_time)
3366{
3367        /* Data packets without SYNs are not likely part of an ACK loop. */
3368        if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) &&
3369            !tcp_hdr(skb)->syn)
3370                return false;
3371
3372        return __tcp_oow_rate_limited(net, mib_idx, last_oow_ack_time);
3373}
3374
3375/* RFC 5961 7 [ACK Throttling] */
3376static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb)
3377{
3378        /* unprotected vars, we dont care of overwrites */
3379        static u32 challenge_timestamp;
3380        static unsigned int challenge_count;
3381        struct tcp_sock *tp = tcp_sk(sk);
3382        struct net *net = sock_net(sk);
3383        u32 count, now;
3384
3385        /* First check our per-socket dupack rate limit. */
3386        if (__tcp_oow_rate_limited(net,
3387                                   LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
3388                                   &tp->last_oow_ack_time))
3389                return;
3390
3391        /* Then check host-wide RFC 5961 rate limit. */
3392        now = jiffies / HZ;
3393        if (now != challenge_timestamp) {
3394                u32 ack_limit = net->ipv4.sysctl_tcp_challenge_ack_limit;
3395                u32 half = (ack_limit + 1) >> 1;
3396
3397                challenge_timestamp = now;
3398                WRITE_ONCE(challenge_count, half + prandom_u32_max(ack_limit));
3399        }
3400        count = READ_ONCE(challenge_count);
3401        if (count > 0) {
3402                WRITE_ONCE(challenge_count, count - 1);
3403                NET_INC_STATS(net, LINUX_MIB_TCPCHALLENGEACK);
3404                tcp_send_ack(sk);
3405        }
3406}
3407
3408static void tcp_store_ts_recent(struct tcp_sock *tp)
3409{
3410        tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
3411        tp->rx_opt.ts_recent_stamp = get_seconds();
3412}
3413
3414static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
3415{
3416        if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
3417                /* PAWS bug workaround wrt. ACK frames, the PAWS discard
3418                 * extra check below makes sure this can only happen
3419                 * for pure ACK frames.  -DaveM
3420                 *
3421                 * Not only, also it occurs for expired timestamps.
3422                 */
3423
3424                if (tcp_paws_check(&tp->rx_opt, 0))
3425                        tcp_store_ts_recent(tp);
3426        }
3427}
3428
3429/* This routine deals with acks during a TLP episode.
3430 * We mark the end of a TLP episode on receiving TLP dupack or when
3431 * ack is after tlp_high_seq.
3432 * Ref: loss detection algorithm in draft-dukkipati-tcpm-tcp-loss-probe.
3433 */
3434static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
3435{
3436        struct tcp_sock *tp = tcp_sk(sk);
3437
3438        if (before(ack, tp->tlp_high_seq))
3439                return;
3440
3441        if (flag & FLAG_DSACKING_ACK) {
3442                /* This DSACK means original and TLP probe arrived; no loss */
3443                tp->tlp_high_seq = 0;
3444        } else if (after(ack, tp->tlp_high_seq)) {
3445                /* ACK advances: there was a loss, so reduce cwnd. Reset
3446                 * tlp_high_seq in tcp_init_cwnd_reduction()
3447                 */
3448                tcp_init_cwnd_reduction(sk);
3449                tcp_set_ca_state(sk, TCP_CA_CWR);
3450                tcp_end_cwnd_reduction(sk);
3451                tcp_try_keep_open(sk);
3452                NET_INC_STATS(sock_net(sk),
3453                                LINUX_MIB_TCPLOSSPROBERECOVERY);
3454        } else if (!(flag & (FLAG_SND_UNA_ADVANCED |
3455                             FLAG_NOT_DUP | FLAG_DATA_SACKED))) {
3456                /* Pure dupack: original and TLP probe arrived; no loss */
3457                tp->tlp_high_seq = 0;
3458        }
3459}
3460
3461static inline void tcp_in_ack_event(struct sock *sk, u32 flags)
3462{
3463        const struct inet_connection_sock *icsk = inet_csk(sk);
3464
3465        if (icsk->icsk_ca_ops->in_ack_event)
3466                icsk->icsk_ca_ops->in_ack_event(sk, flags);
3467}
3468
3469/* Congestion control has updated the cwnd already. So if we're in
3470 * loss recovery then now we do any new sends (for FRTO) or
3471 * retransmits (for CA_Loss or CA_recovery) that make sense.
3472 */
3473static void tcp_xmit_recovery(struct sock *sk, int rexmit)
3474{
3475        struct tcp_sock *tp = tcp_sk(sk);
3476
3477        if (rexmit == REXMIT_NONE)
3478                return;
3479
3480        if (unlikely(rexmit == 2)) {
3481                __tcp_push_pending_frames(sk, tcp_current_mss(sk),
3482                                          TCP_NAGLE_OFF);
3483                if (after(tp->snd_nxt, tp->high_seq))
3484                        return;
3485                tp->frto = 0;
3486        }
3487        tcp_xmit_retransmit_queue(sk);
3488}
3489
3490/* This routine deals with incoming acks, but not outgoing ones. */
3491static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
3492{
3493        struct inet_connection_sock *icsk = inet_csk(sk);
3494        struct tcp_sock *tp = tcp_sk(sk);
3495        struct tcp_sacktag_state sack_state;
3496        struct rate_sample rs = { .prior_delivered = 0 };
3497        u32 prior_snd_una = tp->snd_una;
3498        bool is_sack_reneg = tp->is_sack_reneg;
3499        u32 ack_seq = TCP_SKB_CB(skb)->seq;
3500        u32 ack = TCP_SKB_CB(skb)->ack_seq;
3501        bool is_dupack = false;
3502        int prior_packets = tp->packets_out;
3503        u32 delivered = tp->delivered;
3504        u32 lost = tp->lost;
3505        int rexmit = REXMIT_NONE; /* Flag to (re)transmit to recover losses */
3506        u32 prior_fack;
3507
3508        sack_state.first_sackt = 0;
3509        sack_state.rate = &rs;
3510
3511        /* We very likely will need to access rtx queue. */
3512        prefetch(sk->tcp_rtx_queue.rb_node);
3513
3514        /* If the ack is older than previous acks
3515         * then we can probably ignore it.
3516         */
3517        if (before(ack, prior_snd_una)) {
3518                /* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
3519                if (before(ack, prior_snd_una - tp->max_window)) {
3520                        if (!(flag & FLAG_NO_CHALLENGE_ACK))
3521                                tcp_send_challenge_ack(sk, skb);
3522                        return -1;
3523                }
3524                goto old_ack;
3525        }
3526
3527        /* If the ack includes data we haven't sent yet, discard
3528         * this segment (RFC793 Section 3.9).
3529         */
3530        if (after(ack, tp->snd_nxt))
3531                goto invalid_ack;
3532
3533        if (after(ack, prior_snd_una)) {
3534                flag |= FLAG_SND_UNA_ADVANCED;
3535                icsk->icsk_retransmits = 0;
3536        }
3537
3538        prior_fack = tcp_is_sack(tp) ? tcp_highest_sack_seq(tp) : tp->snd_una;
3539        rs.prior_in_flight = tcp_packets_in_flight(tp);
3540
3541        /* ts_recent update must be made after we are sure that the packet
3542         * is in window.
3543         */
3544        if (flag & FLAG_UPDATE_TS_RECENT)
3545                tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
3546
3547        if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
3548                /* Window is constant, pure forward advance.
3549                 * No more checks are required.
3550                 * Note, we use the fact that SND.UNA>=SND.WL2.
3551                 */
3552                tcp_update_wl(tp, ack_seq);
3553                tcp_snd_una_update(tp, ack);
3554                flag |= FLAG_WIN_UPDATE;
3555
3556                tcp_in_ack_event(sk, CA_ACK_WIN_UPDATE);
3557
3558                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS);
3559        } else {
3560                u32 ack_ev_flags = CA_ACK_SLOWPATH;
3561
3562                if (ack_seq != TCP_SKB_CB(skb)->end_seq)
3563                        flag |= FLAG_DATA;
3564                else
3565                        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPUREACKS);
3566
3567                flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
3568
3569                if (TCP_SKB_CB(skb)->sacked)
3570                        flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3571                                                        &sack_state);
3572
3573                if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb))) {
3574                        flag |= FLAG_ECE;
3575                        ack_ev_flags |= CA_ACK_ECE;
3576                }
3577
3578                if (flag & FLAG_WIN_UPDATE)
3579                        ack_ev_flags |= CA_ACK_WIN_UPDATE;
3580
3581                tcp_in_ack_event(sk, ack_ev_flags);
3582        }
3583
3584        /* We passed data and got it acked, remove any soft error
3585         * log. Something worked...
3586         */
3587        sk->sk_err_soft = 0;
3588        icsk->icsk_probes_out = 0;
3589        tp->rcv_tstamp = tcp_jiffies32;
3590        if (!prior_packets)
3591                goto no_queue;
3592
3593        /* See if we can take anything off of the retransmit queue. */
3594        flag |= tcp_clean_rtx_queue(sk, prior_fack, prior_snd_una, &sack_state);
3595
3596        tcp_rack_update_reo_wnd(sk, &rs);
3597
3598        if (tp->tlp_high_seq)
3599                tcp_process_tlp_ack(sk, ack, flag);
3600        /* If needed, reset TLP/RTO timer; RACK may later override this. */
3601        if (flag & FLAG_SET_XMIT_TIMER)
3602                tcp_set_xmit_timer(sk);
3603
3604        if (tcp_ack_is_dubious(sk, flag)) {
3605                is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
3606                tcp_fastretrans_alert(sk, prior_snd_una, is_dupack, &flag,
3607                                      &rexmit);
3608        }
3609
3610        if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP))
3611                sk_dst_confirm(sk);
3612
3613        delivered = tp->delivered - delivered;  /* freshly ACKed or SACKed */
3614        lost = tp->lost - lost;                 /* freshly marked lost */
3615        tcp_rate_gen(sk, delivered, lost, is_sack_reneg, sack_state.rate);
3616        tcp_cong_control(sk, ack, delivered, flag, sack_state.rate);
3617        tcp_xmit_recovery(sk, rexmit);
3618        return 1;
3619
3620no_queue:
3621        /* If data was DSACKed, see if we can undo a cwnd reduction. */
3622        if (flag & FLAG_DSACKING_ACK)
3623                tcp_fastretrans_alert(sk, prior_snd_una, is_dupack, &flag,
3624                                      &rexmit);
3625        /* If this ack opens up a zero window, clear backoff.  It was
3626         * being used to time the probes, and is probably far higher than
3627         * it needs to be for normal retransmission.
3628         */
3629        tcp_ack_probe(sk);
3630
3631        if (tp->tlp_high_seq)
3632                tcp_process_tlp_ack(sk, ack, flag);
3633        return 1;
3634
3635invalid_ack:
3636        SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
3637        return -1;
3638
3639old_ack:
3640        /* If data was SACKed, tag it and see if we should send more data.
3641         * If data was DSACKed, see if we can undo a cwnd reduction.
3642         */
3643        if (TCP_SKB_CB(skb)->sacked) {
3644                flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3645                                                &sack_state);
3646                tcp_fastretrans_alert(sk, prior_snd_una, is_dupack, &flag,
3647                                      &rexmit);
3648                tcp_xmit_recovery(sk, rexmit);
3649        }
3650
3651        SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
3652        return 0;
3653}
3654
3655static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
3656                                      bool syn, struct tcp_fastopen_cookie *foc,
3657                                      bool exp_opt)
3658{
3659        /* Valid only in SYN or SYN-ACK with an even length.  */
3660        if (!foc || !syn || len < 0 || (len & 1))
3661                return;
3662
3663        if (len >= TCP_FASTOPEN_COOKIE_MIN &&
3664            len <= TCP_FASTOPEN_COOKIE_MAX)
3665                memcpy(foc->val, cookie, len);
3666        else if (len != 0)
3667                len = -1;
3668        foc->len = len;
3669        foc->exp = exp_opt;
3670}
3671
3672static void smc_parse_options(const struct tcphdr *th,
3673                              struct tcp_options_received *opt_rx,
3674                              const unsigned char *ptr,
3675                              int opsize)
3676{
3677#if IS_ENABLED(CONFIG_SMC)
3678        if (static_branch_unlikely(&tcp_have_smc)) {
3679                if (th->syn && !(opsize & 1) &&
3680                    opsize >= TCPOLEN_EXP_SMC_BASE &&
3681                    get_unaligned_be32(ptr) == TCPOPT_SMC_MAGIC)
3682                        opt_rx->smc_ok = 1;
3683        }
3684#endif
3685}
3686
3687/* Look for tcp options. Normally only called on SYN and SYNACK packets.
3688 * But, this can also be called on packets in the established flow when
3689 * the fast version below fails.
3690 */
3691void tcp_parse_options(const struct net *net,
3692                       const struct sk_buff *skb,
3693                       struct tcp_options_received *opt_rx, int estab,
3694                       struct tcp_fastopen_cookie *foc)
3695{
3696        const unsigned char *ptr;
3697        const struct tcphdr *th = tcp_hdr(skb);
3698        int length = (th->doff * 4) - sizeof(struct tcphdr);
3699
3700        ptr = (const unsigned char *)(th + 1);
3701        opt_rx->saw_tstamp = 0;
3702
3703        while (length > 0) {
3704                int opcode = *ptr++;
3705                int opsize;
3706
3707                switch (opcode) {
3708                case TCPOPT_EOL:
3709                        return;
3710                case TCPOPT_NOP:        /* Ref: RFC 793 section 3.1 */
3711                        length--;
3712                        continue;
3713                default:
3714                        opsize = *ptr++;
3715                        if (opsize < 2) /* "silly options" */
3716                                return;
3717                        if (opsize > length)
3718                                return; /* don't parse partial options */
3719                        switch (opcode) {
3720                        case TCPOPT_MSS:
3721                                if (opsize == TCPOLEN_MSS && th->syn && !estab) {
3722                                        u16 in_mss = get_unaligned_be16(ptr);
3723                                        if (in_mss) {
3724                                                if (opt_rx->user_mss &&
3725                                                    opt_rx->user_mss < in_mss)
3726                                                        in_mss = opt_rx->user_mss;
3727                                                opt_rx->mss_clamp = in_mss;
3728                                        }
3729                                }
3730                                break;
3731                        case TCPOPT_WINDOW:
3732                                if (opsize == TCPOLEN_WINDOW && th->syn &&
3733                                    !estab && net->ipv4.sysctl_tcp_window_scaling) {
3734                                        __u8 snd_wscale = *(__u8 *)ptr;
3735                                        opt_rx->wscale_ok = 1;
3736                                        if (snd_wscale > TCP_MAX_WSCALE) {
3737                                                net_info_ratelimited("%s: Illegal window scaling value %d > %u received\n",
3738                                                                     __func__,
3739                                                                     snd_wscale,
3740                                                                     TCP_MAX_WSCALE);
3741                                                snd_wscale = TCP_MAX_WSCALE;
3742                                        }
3743                                        opt_rx->snd_wscale = snd_wscale;
3744                                }
3745                                break;
3746                        case TCPOPT_TIMESTAMP:
3747                                if ((opsize == TCPOLEN_TIMESTAMP) &&
3748                                    ((estab && opt_rx->tstamp_ok) ||
3749                                     (!estab && net->ipv4.sysctl_tcp_timestamps))) {
3750                                        opt_rx->saw_tstamp = 1;
3751                                        opt_rx->rcv_tsval = get_unaligned_be32(ptr);
3752                                        opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
3753                                }
3754                                break;
3755                        case TCPOPT_SACK_PERM:
3756                                if (opsize == TCPOLEN_SACK_PERM && th->syn &&
3757                                    !estab && net->ipv4.sysctl_tcp_sack) {
3758                                        opt_rx->sack_ok = TCP_SACK_SEEN;
3759                                        tcp_sack_reset(opt_rx);
3760                                }
3761                                break;
3762
3763                        case TCPOPT_SACK:
3764                                if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
3765                                   !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
3766                                   opt_rx->sack_ok) {
3767                                        TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
3768                                }
3769                                break;
3770#ifdef CONFIG_TCP_MD5SIG
3771                        case TCPOPT_MD5SIG:
3772                                /*
3773                                 * The MD5 Hash has already been
3774                                 * checked (see tcp_v{4,6}_do_rcv()).
3775                                 */
3776                                break;
3777#endif
3778                        case TCPOPT_FASTOPEN:
3779                                tcp_parse_fastopen_option(
3780                                        opsize - TCPOLEN_FASTOPEN_BASE,
3781                                        ptr, th->syn, foc, false);
3782                                break;
3783
3784                        case TCPOPT_EXP:
3785                                /* Fast Open option shares code 254 using a
3786                                 * 16 bits magic number.
3787                                 */
3788                                if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE &&
3789                                    get_unaligned_be16(ptr) ==
3790                                    TCPOPT_FASTOPEN_MAGIC)
3791                                        tcp_parse_fastopen_option(opsize -
3792                                                TCPOLEN_EXP_FASTOPEN_BASE,
3793                                                ptr + 2, th->syn, foc, true);
3794                                else
3795                                        smc_parse_options(th, opt_rx, ptr,
3796                                                          opsize);
3797                                break;
3798
3799                        }
3800                        ptr += opsize-2;
3801                        length -= opsize;
3802                }
3803        }
3804}
3805EXPORT_SYMBOL(tcp_parse_options);
3806
3807static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
3808{
3809        const __be32 *ptr = (const __be32 *)(th + 1);
3810
3811        if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
3812                          | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
3813                tp->rx_opt.saw_tstamp = 1;
3814                ++ptr;
3815                tp->rx_opt.rcv_tsval = ntohl(*ptr);
3816                ++ptr;
3817                if (*ptr)
3818                        tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
3819                else
3820                        tp->rx_opt.rcv_tsecr = 0;
3821                return true;
3822        }
3823        return false;
3824}
3825
3826/* Fast parse options. This hopes to only see timestamps.
3827 * If it is wrong it falls back on tcp_parse_options().
3828 */
3829static bool tcp_fast_parse_options(const struct net *net,
3830                                   const struct sk_buff *skb,
3831                                   const struct tcphdr *th, struct tcp_sock *tp)
3832{
3833        /* In the spirit of fast parsing, compare doff directly to constant
3834         * values.  Because equality is used, short doff can be ignored here.
3835         */
3836        if (th->doff == (sizeof(*th) / 4)) {
3837                tp->rx_opt.saw_tstamp = 0;
3838                return false;
3839        } else if (tp->rx_opt.tstamp_ok &&
3840                   th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
3841                if (tcp_parse_aligned_timestamp(tp, th))
3842                        return true;
3843        }
3844
3845        tcp_parse_options(net, skb, &tp->rx_opt, 1, NULL);
3846        if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
3847                tp->rx_opt.rcv_tsecr -= tp->tsoffset;
3848
3849        return true;
3850}
3851
3852#ifdef CONFIG_TCP_MD5SIG
3853/*
3854 * Parse MD5 Signature option
3855 */
3856const u8 *tcp_parse_md5sig_option(const struct tcphdr *th)
3857{
3858        int length = (th->doff << 2) - sizeof(*th);
3859        const u8 *ptr = (const u8 *)(th + 1);
3860
3861        /* If the TCP option is too short, we can short cut */
3862        if (length < TCPOLEN_MD5SIG)
3863                return NULL;
3864
3865        while (length > 0) {
3866                int opcode = *ptr++;
3867                int opsize;
3868
3869                switch (opcode) {
3870                case TCPOPT_EOL:
3871                        return NULL;
3872                case TCPOPT_NOP:
3873                        length--;
3874                        continue;
3875                default:
3876                        opsize = *ptr++;
3877                        if (opsize < 2 || opsize > length)
3878                                return NULL;
3879                        if (opcode == TCPOPT_MD5SIG)
3880                                return opsize == TCPOLEN_MD5SIG ? ptr : NULL;
3881                }
3882                ptr += opsize - 2;
3883                length -= opsize;
3884        }
3885        return NULL;
3886}
3887EXPORT_SYMBOL(tcp_parse_md5sig_option);
3888#endif
3889
3890/* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
3891 *
3892 * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
3893 * it can pass through stack. So, the following predicate verifies that
3894 * this segment is not used for anything but congestion avoidance or
3895 * fast retransmit. Moreover, we even are able to eliminate most of such
3896 * second order effects, if we apply some small "replay" window (~RTO)
3897 * to timestamp space.
3898 *
3899 * All these measures still do not guarantee that we reject wrapped ACKs
3900 * on networks with high bandwidth, when sequence space is recycled fastly,
3901 * but it guarantees that such events will be very rare and do not affect
3902 * connection seriously. This doesn't look nice, but alas, PAWS is really
3903 * buggy extension.
3904 *
3905 * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
3906 * states that events when retransmit arrives after original data are rare.
3907 * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
3908 * the biggest problem on large power networks even with minor reordering.
3909 * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
3910 * up to bandwidth of 18Gigabit/sec. 8) ]
3911 */
3912
3913static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
3914{
3915        const struct tcp_sock *tp = tcp_sk(sk);
3916        const struct tcphdr *th = tcp_hdr(skb);
3917        u32 seq = TCP_SKB_CB(skb)->seq;
3918        u32 ack = TCP_SKB_CB(skb)->ack_seq;
3919
3920        return (/* 1. Pure ACK with correct sequence number. */
3921                (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
3922
3923                /* 2. ... and duplicate ACK. */
3924                ack == tp->snd_una &&
3925
3926                /* 3. ... and does not update window. */
3927                !tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
3928
3929                /* 4. ... and sits in replay window. */
3930                (s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
3931}
3932
3933static inline bool tcp_paws_discard(const struct sock *sk,
3934                                   const struct sk_buff *skb)
3935{
3936        const struct tcp_sock *tp = tcp_sk(sk);
3937
3938        return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) &&
3939               !tcp_disordered_ack(sk, skb);
3940}
3941
3942/* Check segment sequence number for validity.
3943 *
3944 * Segment controls are considered valid, if the segment
3945 * fits to the window after truncation to the window. Acceptability
3946 * of data (and SYN, FIN, of course) is checked separately.
3947 * See tcp_data_queue(), for example.
3948 *
3949 * Also, controls (RST is main one) are accepted using RCV.WUP instead
3950 * of RCV.NXT. Peer still did not advance his SND.UNA when we
3951 * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
3952 * (borrowed from freebsd)
3953 */
3954
3955static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq)
3956{
3957        return  !before(end_seq, tp->rcv_wup) &&
3958                !after(seq, tp->rcv_nxt + tcp_receive_window(tp));
3959}
3960
3961/* When we get a reset we do this. */
3962void tcp_reset(struct sock *sk)
3963{
3964        trace_tcp_receive_reset(sk);
3965
3966        /* We want the right error as BSD sees it (and indeed as we do). */
3967        switch (sk->sk_state) {
3968        case TCP_SYN_SENT:
3969                sk->sk_err = ECONNREFUSED;
3970                break;
3971        case TCP_CLOSE_WAIT:
3972                sk->sk_err = EPIPE;
3973                break;
3974        case TCP_CLOSE:
3975                return;
3976        default:
3977                sk->sk_err = ECONNRESET;
3978        }
3979        /* This barrier is coupled with smp_rmb() in tcp_poll() */
3980        smp_wmb();
3981
3982        tcp_write_queue_purge(sk);
3983        tcp_done(sk);
3984
3985        if (!sock_flag(sk, SOCK_DEAD))
3986                sk->sk_error_report(sk);
3987}
3988
3989/*
3990 *      Process the FIN bit. This now behaves as it is supposed to work
3991 *      and the FIN takes effect when it is validly part of sequence
3992 *      space. Not before when we get holes.
3993 *
3994 *      If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
3995 *      (and thence onto LAST-ACK and finally, CLOSE, we never enter
3996 *      TIME-WAIT)
3997 *
3998 *      If we are in FINWAIT-1, a received FIN indicates simultaneous
3999 *      close and we go into CLOSING (and later onto TIME-WAIT)
4000 *
4001 *      If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
4002 */
4003void tcp_fin(struct sock *sk)
4004{
4005        struct tcp_sock *tp = tcp_sk(sk);
4006
4007        inet_csk_schedule_ack(sk);
4008
4009        sk->sk_shutdown |= RCV_SHUTDOWN;
4010        sock_set_flag(sk, SOCK_DONE);
4011
4012        switch (sk->sk_state) {
4013        case TCP_SYN_RECV:
4014        case TCP_ESTABLISHED:
4015                /* Move to CLOSE_WAIT */
4016                tcp_set_state(sk, TCP_CLOSE_WAIT);
4017                inet_csk(sk)->icsk_ack.pingpong = 1;
4018                break;
4019
4020        case TCP_CLOSE_WAIT:
4021        case TCP_CLOSING:
4022                /* Received a retransmission of the FIN, do
4023                 * nothing.
4024                 */
4025                break;
4026        case TCP_LAST_ACK:
4027                /* RFC793: Remain in the LAST-ACK state. */
4028                break;
4029
4030        case TCP_FIN_WAIT1:
4031                /* This case occurs when a simultaneous close
4032                 * happens, we must ack the received FIN and
4033                 * enter the CLOSING state.
4034                 */
4035                tcp_send_ack(sk);
4036                tcp_set_state(sk, TCP_CLOSING);
4037                break;
4038        case TCP_FIN_WAIT2:
4039                /* Received a FIN -- send ACK and enter TIME_WAIT. */
4040                tcp_send_ack(sk);
4041                tcp_time_wait(sk, TCP_TIME_WAIT, 0);
4042                break;
4043        default:
4044                /* Only TCP_LISTEN and TCP_CLOSE are left, in these
4045                 * cases we should never reach this piece of code.
4046                 */
4047                pr_err("%s: Impossible, sk->sk_state=%d\n",
4048                       __func__, sk->sk_state);
4049                break;
4050        }
4051
4052        /* It _is_ possible, that we have something out-of-order _after_ FIN.
4053         * Probably, we should reset in this case. For now drop them.
4054         */
4055        skb_rbtree_purge(&tp->out_of_order_queue);
4056        if (tcp_is_sack(tp))
4057                tcp_sack_reset(&tp->rx_opt);
4058        sk_mem_reclaim(sk);
4059
4060        if (!sock_flag(sk, SOCK_DEAD)) {
4061                sk->sk_state_change(sk);
4062
4063                /* Do not send POLL_HUP for half duplex close. */
4064                if (sk->sk_shutdown == SHUTDOWN_MASK ||
4065                    sk->sk_state == TCP_CLOSE)
4066                        sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
4067                else
4068                        sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
4069        }
4070}
4071
4072static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
4073                                  u32 end_seq)
4074{
4075        if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
4076                if (before(seq, sp->start_seq))
4077                        sp->start_seq = seq;
4078                if (after(end_seq, sp->end_seq))
4079                        sp->end_seq = end_seq;
4080                return true;
4081        }
4082        return false;
4083}
4084
4085static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
4086{
4087        struct tcp_sock *tp = tcp_sk(sk);
4088
4089        if (tcp_is_sack(tp) && sock_net(sk)->ipv4.sysctl_tcp_dsack) {
4090                int mib_idx;
4091
4092                if (before(seq, tp->rcv_nxt))
4093                        mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
4094                else
4095                        mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
4096
4097                NET_INC_STATS(sock_net(sk), mib_idx);
4098
4099                tp->rx_opt.dsack = 1;
4100                tp->duplicate_sack[0].start_seq = seq;
4101                tp->duplicate_sack[0].end_seq = end_seq;
4102        }
4103}
4104
4105static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
4106{
4107        struct tcp_sock *tp = tcp_sk(sk);
4108
4109        if (!tp->rx_opt.dsack)
4110                tcp_dsack_set(sk, seq, end_seq);
4111        else
4112                tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
4113}
4114
4115static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
4116{
4117        struct tcp_sock *tp = tcp_sk(sk);
4118
4119        if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4120            before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4121                NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
4122                tcp_enter_quickack_mode(sk);
4123
4124                if (tcp_is_sack(tp) && sock_net(sk)->ipv4.sysctl_tcp_dsack) {
4125                        u32 end_seq = TCP_SKB_CB(skb)->end_seq;
4126
4127                        if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
4128                                end_seq = tp->rcv_nxt;
4129                        tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
4130                }
4131        }
4132
4133        tcp_send_ack(sk);
4134}
4135
4136/* These routines update the SACK block as out-of-order packets arrive or
4137 * in-order packets close up the sequence space.
4138 */
4139static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
4140{
4141        int this_sack;
4142        struct tcp_sack_block *sp = &tp->selective_acks[0];
4143        struct tcp_sack_block *swalk = sp + 1;
4144
4145        /* See if the recent change to the first SACK eats into
4146         * or hits the sequence space of other SACK blocks, if so coalesce.
4147         */
4148        for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
4149                if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
4150                        int i;
4151
4152                        /* Zap SWALK, by moving every further SACK up by one slot.
4153                         * Decrease num_sacks.
4154                         */
4155                        tp->rx_opt.num_sacks--;
4156                        for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
4157                                sp[i] = sp[i + 1];
4158                        continue;
4159                }
4160                this_sack++, swalk++;
4161        }
4162}
4163
4164static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
4165{
4166        struct tcp_sock *tp = tcp_sk(sk);
4167        struct tcp_sack_block *sp = &tp->selective_acks[0];
4168        int cur_sacks = tp->rx_opt.num_sacks;
4169        int this_sack;
4170
4171        if (!cur_sacks)
4172                goto new_sack;
4173
4174        for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
4175                if (tcp_sack_extend(sp, seq, end_seq)) {
4176                        /* Rotate this_sack to the first one. */
4177                        for (; this_sack > 0; this_sack--, sp--)
4178                                swap(*sp, *(sp - 1));
4179                        if (cur_sacks > 1)
4180                                tcp_sack_maybe_coalesce(tp);
4181                        return;
4182                }
4183        }
4184
4185        /* Could not find an adjacent existing SACK, build a new one,
4186         * put it at the front, and shift everyone else down.  We
4187         * always know there is at least one SACK present already here.
4188         *
4189         * If the sack array is full, forget about the last one.
4190         */
4191        if (this_sack >= TCP_NUM_SACKS) {
4192                this_sack--;
4193                tp->rx_opt.num_sacks--;
4194                sp--;
4195        }
4196        for (; this_sack > 0; this_sack--, sp--)
4197                *sp = *(sp - 1);
4198
4199new_sack:
4200        /* Build the new head SACK, and we're done. */
4201        sp->start_seq = seq;
4202        sp->end_seq = end_seq;
4203        tp->rx_opt.num_sacks++;
4204}
4205
4206/* RCV.NXT advances, some SACKs should be eaten. */
4207
4208static void tcp_sack_remove(struct tcp_sock *tp)
4209{
4210        struct tcp_sack_block *sp = &tp->selective_acks[0];
4211        int num_sacks = tp->rx_opt.num_sacks;
4212        int this_sack;
4213
4214        /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
4215        if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4216                tp->rx_opt.num_sacks = 0;
4217                return;
4218        }
4219
4220        for (this_sack = 0; this_sack < num_sacks;) {
4221                /* Check if the start of the sack is covered by RCV.NXT. */
4222                if (!before(tp->rcv_nxt, sp->start_seq)) {
4223                        int i;
4224
4225                        /* RCV.NXT must cover all the block! */
4226                        WARN_ON(before(tp->rcv_nxt, sp->end_seq));
4227
4228                        /* Zap this SACK, by moving forward any other SACKS. */
4229                        for (i = this_sack+1; i < num_sacks; i++)
4230                                tp->selective_acks[i-1] = tp->selective_acks[i];
4231                        num_sacks--;
4232                        continue;
4233                }
4234                this_sack++;
4235                sp++;
4236        }
4237        tp->rx_opt.num_sacks = num_sacks;
4238}
4239
4240/**
4241 * tcp_try_coalesce - try to merge skb to prior one
4242 * @sk: socket
4243 * @dest: destination queue
4244 * @to: prior buffer
4245 * @from: buffer to add in queue
4246 * @fragstolen: pointer to boolean
4247 *
4248 * Before queueing skb @from after @to, try to merge them
4249 * to reduce overall memory use and queue lengths, if cost is small.
4250 * Packets in ofo or receive queues can stay a long time.
4251 * Better try to coalesce them right now to avoid future collapses.
4252 * Returns true if caller should free @from instead of queueing it
4253 */
4254static bool tcp_try_coalesce(struct sock *sk,
4255                             struct sk_buff *to,
4256                             struct sk_buff *from,
4257                             bool *fragstolen)
4258{
4259        int delta;
4260
4261        *fragstolen = false;
4262
4263        /* Its possible this segment overlaps with prior segment in queue */
4264        if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
4265                return false;
4266
4267        if (!skb_try_coalesce(to, from, fragstolen, &delta))
4268                return false;
4269
4270        atomic_add(delta, &sk->sk_rmem_alloc);
4271        sk_mem_charge(sk, delta);
4272        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
4273        TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
4274        TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
4275        TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags;
4276
4277        if (TCP_SKB_CB(from)->has_rxtstamp) {
4278                TCP_SKB_CB(to)->has_rxtstamp = true;
4279                to->tstamp = from->tstamp;
4280        }
4281
4282        return true;
4283}
4284
4285static void tcp_drop(struct sock *sk, struct sk_buff *skb)
4286{
4287        sk_drops_add(sk, skb);
4288        __kfree_skb(skb);
4289}
4290
4291/* This one checks to see if we can put data from the
4292 * out_of_order queue into the receive_queue.
4293 */
4294static void tcp_ofo_queue(struct sock *sk)
4295{
4296        struct tcp_sock *tp = tcp_sk(sk);
4297        __u32 dsack_high = tp->rcv_nxt;
4298        bool fin, fragstolen, eaten;
4299        struct sk_buff *skb, *tail;
4300        struct rb_node *p;
4301
4302        p = rb_first(&tp->out_of_order_queue);
4303        while (p) {
4304                skb = rb_to_skb(p);
4305                if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
4306                        break;
4307
4308                if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
4309                        __u32 dsack = dsack_high;
4310                        if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
4311                                dsack_high = TCP_SKB_CB(skb)->end_seq;
4312                        tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
4313                }
4314                p = rb_next(p);
4315                rb_erase(&skb->rbnode, &tp->out_of_order_queue);
4316
4317                if (unlikely(!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))) {
4318                        SOCK_DEBUG(sk, "ofo packet was already received\n");
4319                        tcp_drop(sk, skb);
4320                        continue;
4321                }
4322                SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
4323                           tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
4324                           TCP_SKB_CB(skb)->end_seq);
4325
4326                tail = skb_peek_tail(&sk->sk_receive_queue);
4327                eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
4328                tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
4329                fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
4330                if (!eaten)
4331                        __skb_queue_tail(&sk->sk_receive_queue, skb);
4332                else
4333                        kfree_skb_partial(skb, fragstolen);
4334
4335                if (unlikely(fin)) {
4336                        tcp_fin(sk);
4337                        /* tcp_fin() purges tp->out_of_order_queue,
4338                         * so we must end this loop right now.
4339                         */
4340                        break;
4341                }
4342        }
4343}
4344
4345static bool tcp_prune_ofo_queue(struct sock *sk);
4346static int tcp_prune_queue(struct sock *sk);
4347
4348static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb,
4349                                 unsigned int size)
4350{
4351        if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
4352            !sk_rmem_schedule(sk, skb, size)) {
4353
4354                if (tcp_prune_queue(sk) < 0)
4355                        return -1;
4356
4357                while (!sk_rmem_schedule(sk, skb, size)) {
4358                        if (!tcp_prune_ofo_queue(sk))
4359                                return -1;
4360                }
4361        }
4362        return 0;
4363}
4364
4365static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
4366{
4367        struct tcp_sock *tp = tcp_sk(sk);
4368        struct rb_node **p, *parent;
4369        struct sk_buff *skb1;
4370        u32 seq, end_seq;
4371        bool fragstolen;
4372
4373        tcp_ecn_check_ce(tp, skb);
4374
4375        if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
4376                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP);
4377                tcp_drop(sk, skb);
4378                return;
4379        }
4380
4381        /* Disable header prediction. */
4382        tp->pred_flags = 0;
4383        inet_csk_schedule_ack(sk);
4384
4385        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
4386        seq = TCP_SKB_CB(skb)->seq;
4387        end_seq = TCP_SKB_CB(skb)->end_seq;
4388        SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
4389                   tp->rcv_nxt, seq, end_seq);
4390
4391        p = &tp->out_of_order_queue.rb_node;
4392        if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4393                /* Initial out of order segment, build 1 SACK. */
4394                if (tcp_is_sack(tp)) {
4395                        tp->rx_opt.num_sacks = 1;
4396                        tp->selective_acks[0].start_seq = seq;
4397                        tp->selective_acks[0].end_seq = end_seq;
4398                }
4399                rb_link_node(&skb->rbnode, NULL, p);
4400                rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
4401                tp->ooo_last_skb = skb;
4402                goto end;
4403        }
4404
4405        /* In the typical case, we are adding an skb to the end of the list.
4406         * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
4407         */
4408        if (tcp_try_coalesce(sk, tp->ooo_last_skb,
4409                             skb, &fragstolen)) {
4410coalesce_done:
4411                tcp_grow_window(sk, skb);
4412                kfree_skb_partial(skb, fragstolen);
4413                skb = NULL;
4414                goto add_sack;
4415        }
4416        /* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
4417        if (!before(seq, TCP_SKB_CB(tp->ooo_last_skb)->end_seq)) {
4418                parent = &tp->ooo_last_skb->rbnode;
4419                p = &parent->rb_right;
4420                goto insert;
4421        }
4422
4423        /* Find place to insert this segment. Handle overlaps on the way. */
4424        parent = NULL;
4425        while (*p) {
4426                parent = *p;
4427                skb1 = rb_to_skb(parent);
4428                if (before(seq, TCP_SKB_CB(skb1)->seq)) {
4429                        p = &parent->rb_left;
4430                        continue;
4431                }
4432                if (before(seq, TCP_SKB_CB(skb1)->end_seq)) {
4433                        if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4434                                /* All the bits are present. Drop. */
4435                                NET_INC_STATS(sock_net(sk),
4436                                              LINUX_MIB_TCPOFOMERGE);
4437                                __kfree_skb(skb);
4438                                skb = NULL;
4439                                tcp_dsack_set(sk, seq, end_seq);
4440                                goto add_sack;
4441                        }
4442                        if (after(seq, TCP_SKB_CB(skb1)->seq)) {
4443                                /* Partial overlap. */
4444                                tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq);
4445                        } else {
4446                                /* skb's seq == skb1's seq and skb covers skb1.
4447                                 * Replace skb1 with skb.
4448                                 */
4449                                rb_replace_node(&skb1->rbnode, &skb->rbnode,
4450                                                &tp->out_of_order_queue);
4451                                tcp_dsack_extend(sk,
4452                                                 TCP_SKB_CB(skb1)->seq,
4453                                                 TCP_SKB_CB(skb1)->end_seq);
4454                                NET_INC_STATS(sock_net(sk),
4455                                              LINUX_MIB_TCPOFOMERGE);
4456                                __kfree_skb(skb1);
4457                                goto merge_right;
4458                        }
4459                } else if (tcp_try_coalesce(sk, skb1,
4460                                            skb, &fragstolen)) {
4461                        goto coalesce_done;
4462                }
4463                p = &parent->rb_right;
4464        }
4465insert:
4466        /* Insert segment into RB tree. */
4467        rb_link_node(&skb->rbnode, parent, p);
4468        rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
4469
4470merge_right:
4471        /* Remove other segments covered by skb. */
4472        while ((skb1 = skb_rb_next(skb)) != NULL) {
4473                if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
4474                        break;
4475                if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4476                        tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
4477                                         end_seq);
4478                        break;
4479                }
4480                rb_erase(&skb1->rbnode, &tp->out_of_order_queue);
4481                tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
4482                                 TCP_SKB_CB(skb1)->end_seq);
4483                NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
4484                tcp_drop(sk, skb1);
4485        }
4486        /* If there is no skb after us, we are the last_skb ! */
4487        if (!skb1)
4488                tp->ooo_last_skb = skb;
4489
4490add_sack:
4491        if (tcp_is_sack(tp))
4492                tcp_sack_new_ofo_skb(sk, seq, end_seq);
4493end:
4494        if (skb) {
4495                tcp_grow_window(sk, skb);
4496                skb_condense(skb);
4497                skb_set_owner_r(skb, sk);
4498        }
4499}
4500
4501static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen,
4502                  bool *fragstolen)
4503{
4504        int eaten;
4505        struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
4506
4507        __skb_pull(skb, hdrlen);
4508        eaten = (tail &&
4509                 tcp_try_coalesce(sk, tail,
4510                                  skb, fragstolen)) ? 1 : 0;
4511        tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
4512        if (!eaten) {
4513                __skb_queue_tail(&sk->sk_receive_queue, skb);
4514                skb_set_owner_r(skb, sk);
4515        }
4516        return eaten;
4517}
4518
4519int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
4520{
4521        struct sk_buff *skb;
4522        int err = -ENOMEM;
4523        int data_len = 0;
4524        bool fragstolen;
4525
4526        if (size == 0)
4527                return 0;
4528
4529        if (size > PAGE_SIZE) {
4530                int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
4531
4532                data_len = npages << PAGE_SHIFT;
4533                size = data_len + (size & ~PAGE_MASK);
4534        }
4535        skb = alloc_skb_with_frags(size - data_len, data_len,
4536                                   PAGE_ALLOC_COSTLY_ORDER,
4537                                   &err, sk->sk_allocation);
4538        if (!skb)
4539                goto err;
4540
4541        skb_put(skb, size - data_len);
4542        skb->data_len = data_len;
4543        skb->len = size;
4544
4545        if (tcp_try_rmem_schedule(sk, skb, skb->truesize))
4546                goto err_free;
4547
4548        err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
4549        if (err)
4550                goto err_free;
4551
4552        TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
4553        TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
4554        TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
4555
4556        if (tcp_queue_rcv(sk, skb, 0, &fragstolen)) {
4557                WARN_ON_ONCE(fragstolen); /* should not happen */
4558                __kfree_skb(skb);
4559        }
4560        return size;
4561
4562err_free:
4563        kfree_skb(skb);
4564err:
4565        return err;
4566
4567}
4568
4569static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
4570{
4571        struct tcp_sock *tp = tcp_sk(sk);
4572        bool fragstolen;
4573        int eaten;
4574
4575        if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
4576                __kfree_skb(skb);
4577                return;
4578        }
4579        skb_dst_drop(skb);
4580        __skb_pull(skb, tcp_hdr(skb)->doff * 4);
4581
4582        tcp_ecn_accept_cwr(tp, skb);
4583
4584        tp->rx_opt.dsack = 0;
4585
4586        /*  Queue data for delivery to the user.
4587         *  Packets in sequence go to the receive queue.
4588         *  Out of sequence packets to the out_of_order_queue.
4589         */
4590        if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
4591                if (tcp_receive_window(tp) == 0)
4592                        goto out_of_window;
4593
4594                /* Ok. In sequence. In window. */
4595queue_and_out:
4596                if (skb_queue_len(&sk->sk_receive_queue) == 0)
4597                        sk_forced_mem_schedule(sk, skb->truesize);
4598                else if (tcp_try_rmem_schedule(sk, skb, skb->truesize))
4599                        goto drop;
4600
4601                eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen);
4602                tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
4603                if (skb->len)
4604                        tcp_event_data_recv(sk, skb);
4605                if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
4606                        tcp_fin(sk);
4607
4608                if (!RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4609                        tcp_ofo_queue(sk);
4610
4611                        /* RFC2581. 4.2. SHOULD send immediate ACK, when
4612                         * gap in queue is filled.
4613                         */
4614                        if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
4615                                inet_csk(sk)->icsk_ack.pingpong = 0;
4616                }
4617
4618                if (tp->rx_opt.num_sacks)
4619                        tcp_sack_remove(tp);
4620
4621                tcp_fast_path_check(sk);
4622
4623                if (eaten > 0)
4624                        kfree_skb_partial(skb, fragstolen);
4625                if (!sock_flag(sk, SOCK_DEAD))
4626                        sk->sk_data_ready(sk);
4627                return;
4628        }
4629
4630        if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
4631                /* A retransmit, 2nd most common case.  Force an immediate ack. */
4632                NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
4633                tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
4634
4635out_of_window:
4636                tcp_enter_quickack_mode(sk);
4637                inet_csk_schedule_ack(sk);
4638drop:
4639                tcp_drop(sk, skb);
4640                return;
4641        }
4642
4643        /* Out of window. F.e. zero window probe. */
4644        if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
4645                goto out_of_window;
4646
4647        tcp_enter_quickack_mode(sk);
4648
4649        if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4650                /* Partial packet, seq < rcv_next < end_seq */
4651                SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
4652                           tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
4653                           TCP_SKB_CB(skb)->end_seq);
4654
4655                tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
4656
4657                /* If window is closed, drop tail of packet. But after
4658                 * remembering D-SACK for its head made in previous line.
4659                 */
4660                if (!tcp_receive_window(tp))
4661                        goto out_of_window;
4662                goto queue_and_out;
4663        }
4664
4665        tcp_data_queue_ofo(sk, skb);
4666}
4667
4668static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *list)
4669{
4670        if (list)
4671                return !skb_queue_is_last(list, skb) ? skb->next : NULL;
4672
4673        return skb_rb_next(skb);
4674}
4675
4676static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
4677                                        struct sk_buff_head *list,
4678                                        struct rb_root *root)
4679{
4680        struct sk_buff *next = tcp_skb_next(skb, list);
4681
4682        if (list)
4683                __skb_unlink(skb, list);
4684        else
4685                rb_erase(&skb->rbnode, root);
4686
4687        __kfree_skb(skb);
4688        NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
4689
4690        return next;
4691}
4692
4693/* Insert skb into rb tree, ordered by TCP_SKB_CB(skb)->seq */
4694void tcp_rbtree_insert(struct rb_root *root, struct sk_buff *skb)
4695{
4696        struct rb_node **p = &root->rb_node;
4697        struct rb_node *parent = NULL;
4698        struct sk_buff *skb1;
4699
4700        while (*p) {
4701                parent = *p;
4702                skb1 = rb_to_skb(parent);
4703                if (before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb1)->seq))
4704                        p = &parent->rb_left;
4705                else
4706                        p = &parent->rb_right;
4707        }
4708        rb_link_node(&skb->rbnode, parent, p);
4709        rb_insert_color(&skb->rbnode, root);
4710}
4711
4712/* Collapse contiguous sequence of skbs head..tail with
4713 * sequence numbers start..end.
4714 *
4715 * If tail is NULL, this means until the end of the queue.
4716 *
4717 * Segments with FIN/SYN are not collapsed (only because this
4718 * simplifies code)
4719 */
4720static void
4721tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
4722             struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end)
4723{
4724        struct sk_buff *skb = head, *n;
4725        struct sk_buff_head tmp;
4726        bool end_of_skbs;
4727
4728        /* First, check that queue is collapsible and find
4729         * the point where collapsing can be useful.
4730         */
4731restart:
4732        for (end_of_skbs = true; skb != NULL && skb != tail; skb = n) {
4733                n = tcp_skb_next(skb, list);
4734
4735                /* No new bits? It is possible on ofo queue. */
4736                if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
4737                        skb = tcp_collapse_one(sk, skb, list, root);
4738                        if (!skb)
4739                                break;
4740                        goto restart;
4741                }
4742
4743                /* The first skb to collapse is:
4744                 * - not SYN/FIN and
4745                 * - bloated or contains data before "start" or
4746                 *   overlaps to the next one.
4747                 */
4748                if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) &&
4749                    (tcp_win_from_space(sk, skb->truesize) > skb->len ||
4750                     before(TCP_SKB_CB(skb)->seq, start))) {
4751                        end_of_skbs = false;
4752                        break;
4753                }
4754
4755                if (n && n != tail &&
4756                    TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(n)->seq) {
4757                        end_of_skbs = false;
4758                        break;
4759                }
4760
4761                /* Decided to skip this, advance start seq. */
4762                start = TCP_SKB_CB(skb)->end_seq;
4763        }
4764        if (end_of_skbs ||
4765            (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
4766                return;
4767
4768        __skb_queue_head_init(&tmp);
4769
4770        while (before(start, end)) {
4771                int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start);
4772                struct sk_buff *nskb;
4773
4774                nskb = alloc_skb(copy, GFP_ATOMIC);
4775                if (!nskb)
4776                        break;
4777
4778                memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
4779                TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
4780                if (list)
4781                        __skb_queue_before(list, skb, nskb);
4782                else
4783                        __skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
4784                skb_set_owner_r(nskb, sk);
4785
4786                /* Copy data, releasing collapsed skbs. */
4787                while (copy > 0) {
4788                        int offset = start - TCP_SKB_CB(skb)->seq;
4789                        int size = TCP_SKB_CB(skb)->end_seq - start;
4790
4791                        BUG_ON(offset < 0);
4792                        if (size > 0) {
4793                                size = min(copy, size);
4794                                if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
4795                                        BUG();
4796                                TCP_SKB_CB(nskb)->end_seq += size;
4797                                copy -= size;
4798                                start += size;
4799                        }
4800                        if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
4801                                skb = tcp_collapse_one(sk, skb, list, root);
4802                                if (!skb ||
4803                                    skb == tail ||
4804                                    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
4805                                        goto end;
4806                        }
4807                }
4808        }
4809end:
4810        skb_queue_walk_safe(&tmp, skb, n)
4811                tcp_rbtree_insert(root, skb);
4812}
4813
4814/* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
4815 * and tcp_collapse() them until all the queue is collapsed.
4816 */
4817static void tcp_collapse_ofo_queue(struct sock *sk)
4818{
4819        struct tcp_sock *tp = tcp_sk(sk);
4820        struct sk_buff *skb, *head;
4821        u32 start, end;
4822
4823        skb = skb_rb_first(&tp->out_of_order_queue);
4824new_range:
4825        if (!skb) {
4826                tp->ooo_last_skb = skb_rb_last(&tp->out_of_order_queue);
4827                return;
4828        }
4829        start = TCP_SKB_CB(skb)->seq;
4830        end = TCP_SKB_CB(skb)->end_seq;
4831
4832        for (head = skb;;) {
4833                skb = skb_rb_next(skb);
4834
4835                /* Range is terminated when we see a gap or when
4836                 * we are at the queue end.
4837                 */
4838                if (!skb ||
4839                    after(TCP_SKB_CB(skb)->seq, end) ||
4840                    before(TCP_SKB_CB(skb)->end_seq, start)) {
4841                        tcp_collapse(sk, NULL, &tp->out_of_order_queue,
4842                                     head, skb, start, end);
4843                        goto new_range;
4844                }
4845
4846                if (unlikely(before(TCP_SKB_CB(skb)->seq, start)))
4847                        start = TCP_SKB_CB(skb)->seq;
4848                if (after(TCP_SKB_CB(skb)->end_seq, end))
4849                        end = TCP_SKB_CB(skb)->end_seq;
4850        }
4851}
4852
4853/*
4854 * Clean the out-of-order queue to make room.
4855 * We drop high sequences packets to :
4856 * 1) Let a chance for holes to be filled.
4857 * 2) not add too big latencies if thousands of packets sit there.
4858 *    (But if application shrinks SO_RCVBUF, we could still end up
4859 *     freeing whole queue here)
4860 *
4861 * Return true if queue has shrunk.
4862 */
4863static bool tcp_prune_ofo_queue(struct sock *sk)
4864{
4865        struct tcp_sock *tp = tcp_sk(sk);
4866        struct rb_node *node, *prev;
4867
4868        if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
4869                return false;
4870
4871        NET_INC_STATS(sock_net(sk), LINUX_MIB_OFOPRUNED);
4872        node = &tp->ooo_last_skb->rbnode;
4873        do {
4874                prev = rb_prev(node);
4875                rb_erase(node, &tp->out_of_order_queue);
4876                tcp_drop(sk, rb_to_skb(node));
4877                sk_mem_reclaim(sk);
4878                if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
4879                    !tcp_under_memory_pressure(sk))
4880                        break;