Back to home page

OSCL-LXR

 
 

    


0001 /* Bottleneck Bandwidth and RTT (BBR) congestion control
0002  *
0003  * BBR congestion control computes the sending rate based on the delivery
0004  * rate (throughput) estimated from ACKs. In a nutshell:
0005  *
0006  *   On each ACK, update our model of the network path:
0007  *      bottleneck_bandwidth = windowed_max(delivered / elapsed, 10 round trips)
0008  *      min_rtt = windowed_min(rtt, 10 seconds)
0009  *   pacing_rate = pacing_gain * bottleneck_bandwidth
0010  *   cwnd = max(cwnd_gain * bottleneck_bandwidth * min_rtt, 4)
0011  *
0012  * The core algorithm does not react directly to packet losses or delays,
0013  * although BBR may adjust the size of next send per ACK when loss is
0014  * observed, or adjust the sending rate if it estimates there is a
0015  * traffic policer, in order to keep the drop rate reasonable.
0016  *
0017  * Here is a state transition diagram for BBR:
0018  *
0019  *             |
0020  *             V
0021  *    +---> STARTUP  ----+
0022  *    |        |         |
0023  *    |        V         |
0024  *    |      DRAIN   ----+
0025  *    |        |         |
0026  *    |        V         |
0027  *    +---> PROBE_BW ----+
0028  *    |      ^    |      |
0029  *    |      |    |      |
0030  *    |      +----+      |
0031  *    |                  |
0032  *    +---- PROBE_RTT <--+
0033  *
0034  * A BBR flow starts in STARTUP, and ramps up its sending rate quickly.
0035  * When it estimates the pipe is full, it enters DRAIN to drain the queue.
0036  * In steady state a BBR flow only uses PROBE_BW and PROBE_RTT.
0037  * A long-lived BBR flow spends the vast majority of its time remaining
0038  * (repeatedly) in PROBE_BW, fully probing and utilizing the pipe's bandwidth
0039  * in a fair manner, with a small, bounded queue. *If* a flow has been
0040  * continuously sending for the entire min_rtt window, and hasn't seen an RTT
0041  * sample that matches or decreases its min_rtt estimate for 10 seconds, then
0042  * it briefly enters PROBE_RTT to cut inflight to a minimum value to re-probe
0043  * the path's two-way propagation delay (min_rtt). When exiting PROBE_RTT, if
0044  * we estimated that we reached the full bw of the pipe then we enter PROBE_BW;
0045  * otherwise we enter STARTUP to try to fill the pipe.
0046  *
0047  * BBR is described in detail in:
0048  *   "BBR: Congestion-Based Congestion Control",
0049  *   Neal Cardwell, Yuchung Cheng, C. Stephen Gunn, Soheil Hassas Yeganeh,
0050  *   Van Jacobson. ACM Queue, Vol. 14 No. 5, September-October 2016.
0051  *
0052  * There is a public e-mail list for discussing BBR development and testing:
0053  *   https://groups.google.com/forum/#!forum/bbr-dev
0054  *
0055  * NOTE: BBR might be used with the fq qdisc ("man tc-fq") with pacing enabled,
0056  * otherwise TCP stack falls back to an internal pacing using one high
0057  * resolution timer per TCP socket and may use more resources.
0058  */
0059 #include <linux/btf.h>
0060 #include <linux/btf_ids.h>
0061 #include <linux/module.h>
0062 #include <net/tcp.h>
0063 #include <linux/inet_diag.h>
0064 #include <linux/inet.h>
0065 #include <linux/random.h>
0066 #include <linux/win_minmax.h>
0067 
0068 /* Scale factor for rate in pkt/uSec unit to avoid truncation in bandwidth
0069  * estimation. The rate unit ~= (1500 bytes / 1 usec / 2^24) ~= 715 bps.
0070  * This handles bandwidths from 0.06pps (715bps) to 256Mpps (3Tbps) in a u32.
0071  * Since the minimum window is >=4 packets, the lower bound isn't
0072  * an issue. The upper bound isn't an issue with existing technologies.
0073  */
0074 #define BW_SCALE 24
0075 #define BW_UNIT (1 << BW_SCALE)
0076 
0077 #define BBR_SCALE 8 /* scaling factor for fractions in BBR (e.g. gains) */
0078 #define BBR_UNIT (1 << BBR_SCALE)
0079 
0080 /* BBR has the following modes for deciding how fast to send: */
0081 enum bbr_mode {
0082     BBR_STARTUP,    /* ramp up sending rate rapidly to fill pipe */
0083     BBR_DRAIN,  /* drain any queue created during startup */
0084     BBR_PROBE_BW,   /* discover, share bw: pace around estimated bw */
0085     BBR_PROBE_RTT,  /* cut inflight to min to probe min_rtt */
0086 };
0087 
0088 /* BBR congestion control block */
0089 struct bbr {
0090     u32 min_rtt_us;         /* min RTT in min_rtt_win_sec window */
0091     u32 min_rtt_stamp;          /* timestamp of min_rtt_us */
0092     u32 probe_rtt_done_stamp;   /* end time for BBR_PROBE_RTT mode */
0093     struct minmax bw;   /* Max recent delivery rate in pkts/uS << 24 */
0094     u32 rtt_cnt;        /* count of packet-timed rounds elapsed */
0095     u32     next_rtt_delivered; /* scb->tx.delivered at end of round */
0096     u64 cycle_mstamp;        /* time of this cycle phase start */
0097     u32     mode:3,          /* current bbr_mode in state machine */
0098         prev_ca_state:3,     /* CA state on previous ACK */
0099         packet_conservation:1,  /* use packet conservation? */
0100         round_start:1,       /* start of packet-timed tx->ack round? */
0101         idle_restart:1,      /* restarting after idle? */
0102         probe_rtt_round_done:1,  /* a BBR_PROBE_RTT round at 4 pkts? */
0103         unused:13,
0104         lt_is_sampling:1,    /* taking long-term ("LT") samples now? */
0105         lt_rtt_cnt:7,        /* round trips in long-term interval */
0106         lt_use_bw:1;         /* use lt_bw as our bw estimate? */
0107     u32 lt_bw;           /* LT est delivery rate in pkts/uS << 24 */
0108     u32 lt_last_delivered;   /* LT intvl start: tp->delivered */
0109     u32 lt_last_stamp;       /* LT intvl start: tp->delivered_mstamp */
0110     u32 lt_last_lost;        /* LT intvl start: tp->lost */
0111     u32 pacing_gain:10, /* current gain for setting pacing rate */
0112         cwnd_gain:10,   /* current gain for setting cwnd */
0113         full_bw_reached:1,   /* reached full bw in Startup? */
0114         full_bw_cnt:2,  /* number of rounds without large bw gains */
0115         cycle_idx:3,    /* current index in pacing_gain cycle array */
0116         has_seen_rtt:1, /* have we seen an RTT sample yet? */
0117         unused_b:5;
0118     u32 prior_cwnd; /* prior cwnd upon entering loss recovery */
0119     u32 full_bw;    /* recent bw, to estimate if pipe is full */
0120 
0121     /* For tracking ACK aggregation: */
0122     u64 ack_epoch_mstamp;   /* start of ACK sampling epoch */
0123     u16 extra_acked[2];     /* max excess data ACKed in epoch */
0124     u32 ack_epoch_acked:20, /* packets (S)ACKed in sampling epoch */
0125         extra_acked_win_rtts:5, /* age of extra_acked, in round trips */
0126         extra_acked_win_idx:1,  /* current index in extra_acked array */
0127         unused_c:6;
0128 };
0129 
0130 #define CYCLE_LEN   8   /* number of phases in a pacing gain cycle */
0131 
0132 /* Window length of bw filter (in rounds): */
0133 static const int bbr_bw_rtts = CYCLE_LEN + 2;
0134 /* Window length of min_rtt filter (in sec): */
0135 static const u32 bbr_min_rtt_win_sec = 10;
0136 /* Minimum time (in ms) spent at bbr_cwnd_min_target in BBR_PROBE_RTT mode: */
0137 static const u32 bbr_probe_rtt_mode_ms = 200;
0138 /* Skip TSO below the following bandwidth (bits/sec): */
0139 static const int bbr_min_tso_rate = 1200000;
0140 
0141 /* Pace at ~1% below estimated bw, on average, to reduce queue at bottleneck.
0142  * In order to help drive the network toward lower queues and low latency while
0143  * maintaining high utilization, the average pacing rate aims to be slightly
0144  * lower than the estimated bandwidth. This is an important aspect of the
0145  * design.
0146  */
0147 static const int bbr_pacing_margin_percent = 1;
0148 
0149 /* We use a high_gain value of 2/ln(2) because it's the smallest pacing gain
0150  * that will allow a smoothly increasing pacing rate that will double each RTT
0151  * and send the same number of packets per RTT that an un-paced, slow-starting
0152  * Reno or CUBIC flow would:
0153  */
0154 static const int bbr_high_gain  = BBR_UNIT * 2885 / 1000 + 1;
0155 /* The pacing gain of 1/high_gain in BBR_DRAIN is calculated to typically drain
0156  * the queue created in BBR_STARTUP in a single round:
0157  */
0158 static const int bbr_drain_gain = BBR_UNIT * 1000 / 2885;
0159 /* The gain for deriving steady-state cwnd tolerates delayed/stretched ACKs: */
0160 static const int bbr_cwnd_gain  = BBR_UNIT * 2;
0161 /* The pacing_gain values for the PROBE_BW gain cycle, to discover/share bw: */
0162 static const int bbr_pacing_gain[] = {
0163     BBR_UNIT * 5 / 4,   /* probe for more available bw */
0164     BBR_UNIT * 3 / 4,   /* drain queue and/or yield bw to other flows */
0165     BBR_UNIT, BBR_UNIT, BBR_UNIT,   /* cruise at 1.0*bw to utilize pipe, */
0166     BBR_UNIT, BBR_UNIT, BBR_UNIT    /* without creating excess queue... */
0167 };
0168 /* Randomize the starting gain cycling phase over N phases: */
0169 static const u32 bbr_cycle_rand = 7;
0170 
0171 /* Try to keep at least this many packets in flight, if things go smoothly. For
0172  * smooth functioning, a sliding window protocol ACKing every other packet
0173  * needs at least 4 packets in flight:
0174  */
0175 static const u32 bbr_cwnd_min_target = 4;
0176 
0177 /* To estimate if BBR_STARTUP mode (i.e. high_gain) has filled pipe... */
0178 /* If bw has increased significantly (1.25x), there may be more bw available: */
0179 static const u32 bbr_full_bw_thresh = BBR_UNIT * 5 / 4;
0180 /* But after 3 rounds w/o significant bw growth, estimate pipe is full: */
0181 static const u32 bbr_full_bw_cnt = 3;
0182 
0183 /* "long-term" ("LT") bandwidth estimator parameters... */
0184 /* The minimum number of rounds in an LT bw sampling interval: */
0185 static const u32 bbr_lt_intvl_min_rtts = 4;
0186 /* If lost/delivered ratio > 20%, interval is "lossy" and we may be policed: */
0187 static const u32 bbr_lt_loss_thresh = 50;
0188 /* If 2 intervals have a bw ratio <= 1/8, their bw is "consistent": */
0189 static const u32 bbr_lt_bw_ratio = BBR_UNIT / 8;
0190 /* If 2 intervals have a bw diff <= 4 Kbit/sec their bw is "consistent": */
0191 static const u32 bbr_lt_bw_diff = 4000 / 8;
0192 /* If we estimate we're policed, use lt_bw for this many round trips: */
0193 static const u32 bbr_lt_bw_max_rtts = 48;
0194 
0195 /* Gain factor for adding extra_acked to target cwnd: */
0196 static const int bbr_extra_acked_gain = BBR_UNIT;
0197 /* Window length of extra_acked window. */
0198 static const u32 bbr_extra_acked_win_rtts = 5;
0199 /* Max allowed val for ack_epoch_acked, after which sampling epoch is reset */
0200 static const u32 bbr_ack_epoch_acked_reset_thresh = 1U << 20;
0201 /* Time period for clamping cwnd increment due to ack aggregation */
0202 static const u32 bbr_extra_acked_max_us = 100 * 1000;
0203 
0204 static void bbr_check_probe_rtt_done(struct sock *sk);
0205 
0206 /* Do we estimate that STARTUP filled the pipe? */
0207 static bool bbr_full_bw_reached(const struct sock *sk)
0208 {
0209     const struct bbr *bbr = inet_csk_ca(sk);
0210 
0211     return bbr->full_bw_reached;
0212 }
0213 
0214 /* Return the windowed max recent bandwidth sample, in pkts/uS << BW_SCALE. */
0215 static u32 bbr_max_bw(const struct sock *sk)
0216 {
0217     struct bbr *bbr = inet_csk_ca(sk);
0218 
0219     return minmax_get(&bbr->bw);
0220 }
0221 
0222 /* Return the estimated bandwidth of the path, in pkts/uS << BW_SCALE. */
0223 static u32 bbr_bw(const struct sock *sk)
0224 {
0225     struct bbr *bbr = inet_csk_ca(sk);
0226 
0227     return bbr->lt_use_bw ? bbr->lt_bw : bbr_max_bw(sk);
0228 }
0229 
0230 /* Return maximum extra acked in past k-2k round trips,
0231  * where k = bbr_extra_acked_win_rtts.
0232  */
0233 static u16 bbr_extra_acked(const struct sock *sk)
0234 {
0235     struct bbr *bbr = inet_csk_ca(sk);
0236 
0237     return max(bbr->extra_acked[0], bbr->extra_acked[1]);
0238 }
0239 
0240 /* Return rate in bytes per second, optionally with a gain.
0241  * The order here is chosen carefully to avoid overflow of u64. This should
0242  * work for input rates of up to 2.9Tbit/sec and gain of 2.89x.
0243  */
0244 static u64 bbr_rate_bytes_per_sec(struct sock *sk, u64 rate, int gain)
0245 {
0246     unsigned int mss = tcp_sk(sk)->mss_cache;
0247 
0248     rate *= mss;
0249     rate *= gain;
0250     rate >>= BBR_SCALE;
0251     rate *= USEC_PER_SEC / 100 * (100 - bbr_pacing_margin_percent);
0252     return rate >> BW_SCALE;
0253 }
0254 
0255 /* Convert a BBR bw and gain factor to a pacing rate in bytes per second. */
0256 static unsigned long bbr_bw_to_pacing_rate(struct sock *sk, u32 bw, int gain)
0257 {
0258     u64 rate = bw;
0259 
0260     rate = bbr_rate_bytes_per_sec(sk, rate, gain);
0261     rate = min_t(u64, rate, sk->sk_max_pacing_rate);
0262     return rate;
0263 }
0264 
0265 /* Initialize pacing rate to: high_gain * init_cwnd / RTT. */
0266 static void bbr_init_pacing_rate_from_rtt(struct sock *sk)
0267 {
0268     struct tcp_sock *tp = tcp_sk(sk);
0269     struct bbr *bbr = inet_csk_ca(sk);
0270     u64 bw;
0271     u32 rtt_us;
0272 
0273     if (tp->srtt_us) {      /* any RTT sample yet? */
0274         rtt_us = max(tp->srtt_us >> 3, 1U);
0275         bbr->has_seen_rtt = 1;
0276     } else {             /* no RTT sample yet */
0277         rtt_us = USEC_PER_MSEC;  /* use nominal default RTT */
0278     }
0279     bw = (u64)tcp_snd_cwnd(tp) * BW_UNIT;
0280     do_div(bw, rtt_us);
0281     sk->sk_pacing_rate = bbr_bw_to_pacing_rate(sk, bw, bbr_high_gain);
0282 }
0283 
0284 /* Pace using current bw estimate and a gain factor. */
0285 static void bbr_set_pacing_rate(struct sock *sk, u32 bw, int gain)
0286 {
0287     struct tcp_sock *tp = tcp_sk(sk);
0288     struct bbr *bbr = inet_csk_ca(sk);
0289     unsigned long rate = bbr_bw_to_pacing_rate(sk, bw, gain);
0290 
0291     if (unlikely(!bbr->has_seen_rtt && tp->srtt_us))
0292         bbr_init_pacing_rate_from_rtt(sk);
0293     if (bbr_full_bw_reached(sk) || rate > sk->sk_pacing_rate)
0294         sk->sk_pacing_rate = rate;
0295 }
0296 
0297 /* override sysctl_tcp_min_tso_segs */
0298 static u32 bbr_min_tso_segs(struct sock *sk)
0299 {
0300     return sk->sk_pacing_rate < (bbr_min_tso_rate >> 3) ? 1 : 2;
0301 }
0302 
0303 static u32 bbr_tso_segs_goal(struct sock *sk)
0304 {
0305     struct tcp_sock *tp = tcp_sk(sk);
0306     u32 segs, bytes;
0307 
0308     /* Sort of tcp_tso_autosize() but ignoring
0309      * driver provided sk_gso_max_size.
0310      */
0311     bytes = min_t(unsigned long,
0312               sk->sk_pacing_rate >> READ_ONCE(sk->sk_pacing_shift),
0313               GSO_LEGACY_MAX_SIZE - 1 - MAX_TCP_HEADER);
0314     segs = max_t(u32, bytes / tp->mss_cache, bbr_min_tso_segs(sk));
0315 
0316     return min(segs, 0x7FU);
0317 }
0318 
0319 /* Save "last known good" cwnd so we can restore it after losses or PROBE_RTT */
0320 static void bbr_save_cwnd(struct sock *sk)
0321 {
0322     struct tcp_sock *tp = tcp_sk(sk);
0323     struct bbr *bbr = inet_csk_ca(sk);
0324 
0325     if (bbr->prev_ca_state < TCP_CA_Recovery && bbr->mode != BBR_PROBE_RTT)
0326         bbr->prior_cwnd = tcp_snd_cwnd(tp);  /* this cwnd is good enough */
0327     else  /* loss recovery or BBR_PROBE_RTT have temporarily cut cwnd */
0328         bbr->prior_cwnd = max(bbr->prior_cwnd, tcp_snd_cwnd(tp));
0329 }
0330 
0331 static void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event)
0332 {
0333     struct tcp_sock *tp = tcp_sk(sk);
0334     struct bbr *bbr = inet_csk_ca(sk);
0335 
0336     if (event == CA_EVENT_TX_START && tp->app_limited) {
0337         bbr->idle_restart = 1;
0338         bbr->ack_epoch_mstamp = tp->tcp_mstamp;
0339         bbr->ack_epoch_acked = 0;
0340         /* Avoid pointless buffer overflows: pace at est. bw if we don't
0341          * need more speed (we're restarting from idle and app-limited).
0342          */
0343         if (bbr->mode == BBR_PROBE_BW)
0344             bbr_set_pacing_rate(sk, bbr_bw(sk), BBR_UNIT);
0345         else if (bbr->mode == BBR_PROBE_RTT)
0346             bbr_check_probe_rtt_done(sk);
0347     }
0348 }
0349 
0350 /* Calculate bdp based on min RTT and the estimated bottleneck bandwidth:
0351  *
0352  * bdp = ceil(bw * min_rtt * gain)
0353  *
0354  * The key factor, gain, controls the amount of queue. While a small gain
0355  * builds a smaller queue, it becomes more vulnerable to noise in RTT
0356  * measurements (e.g., delayed ACKs or other ACK compression effects). This
0357  * noise may cause BBR to under-estimate the rate.
0358  */
0359 static u32 bbr_bdp(struct sock *sk, u32 bw, int gain)
0360 {
0361     struct bbr *bbr = inet_csk_ca(sk);
0362     u32 bdp;
0363     u64 w;
0364 
0365     /* If we've never had a valid RTT sample, cap cwnd at the initial
0366      * default. This should only happen when the connection is not using TCP
0367      * timestamps and has retransmitted all of the SYN/SYNACK/data packets
0368      * ACKed so far. In this case, an RTO can cut cwnd to 1, in which
0369      * case we need to slow-start up toward something safe: TCP_INIT_CWND.
0370      */
0371     if (unlikely(bbr->min_rtt_us == ~0U))    /* no valid RTT samples yet? */
0372         return TCP_INIT_CWND;  /* be safe: cap at default initial cwnd*/
0373 
0374     w = (u64)bw * bbr->min_rtt_us;
0375 
0376     /* Apply a gain to the given value, remove the BW_SCALE shift, and
0377      * round the value up to avoid a negative feedback loop.
0378      */
0379     bdp = (((w * gain) >> BBR_SCALE) + BW_UNIT - 1) / BW_UNIT;
0380 
0381     return bdp;
0382 }
0383 
0384 /* To achieve full performance in high-speed paths, we budget enough cwnd to
0385  * fit full-sized skbs in-flight on both end hosts to fully utilize the path:
0386  *   - one skb in sending host Qdisc,
0387  *   - one skb in sending host TSO/GSO engine
0388  *   - one skb being received by receiver host LRO/GRO/delayed-ACK engine
0389  * Don't worry, at low rates (bbr_min_tso_rate) this won't bloat cwnd because
0390  * in such cases tso_segs_goal is 1. The minimum cwnd is 4 packets,
0391  * which allows 2 outstanding 2-packet sequences, to try to keep pipe
0392  * full even with ACK-every-other-packet delayed ACKs.
0393  */
0394 static u32 bbr_quantization_budget(struct sock *sk, u32 cwnd)
0395 {
0396     struct bbr *bbr = inet_csk_ca(sk);
0397 
0398     /* Allow enough full-sized skbs in flight to utilize end systems. */
0399     cwnd += 3 * bbr_tso_segs_goal(sk);
0400 
0401     /* Reduce delayed ACKs by rounding up cwnd to the next even number. */
0402     cwnd = (cwnd + 1) & ~1U;
0403 
0404     /* Ensure gain cycling gets inflight above BDP even for small BDPs. */
0405     if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == 0)
0406         cwnd += 2;
0407 
0408     return cwnd;
0409 }
0410 
0411 /* Find inflight based on min RTT and the estimated bottleneck bandwidth. */
0412 static u32 bbr_inflight(struct sock *sk, u32 bw, int gain)
0413 {
0414     u32 inflight;
0415 
0416     inflight = bbr_bdp(sk, bw, gain);
0417     inflight = bbr_quantization_budget(sk, inflight);
0418 
0419     return inflight;
0420 }
0421 
0422 /* With pacing at lower layers, there's often less data "in the network" than
0423  * "in flight". With TSQ and departure time pacing at lower layers (e.g. fq),
0424  * we often have several skbs queued in the pacing layer with a pre-scheduled
0425  * earliest departure time (EDT). BBR adapts its pacing rate based on the
0426  * inflight level that it estimates has already been "baked in" by previous
0427  * departure time decisions. We calculate a rough estimate of the number of our
0428  * packets that might be in the network at the earliest departure time for the
0429  * next skb scheduled:
0430  *   in_network_at_edt = inflight_at_edt - (EDT - now) * bw
0431  * If we're increasing inflight, then we want to know if the transmit of the
0432  * EDT skb will push inflight above the target, so inflight_at_edt includes
0433  * bbr_tso_segs_goal() from the skb departing at EDT. If decreasing inflight,
0434  * then estimate if inflight will sink too low just before the EDT transmit.
0435  */
0436 static u32 bbr_packets_in_net_at_edt(struct sock *sk, u32 inflight_now)
0437 {
0438     struct tcp_sock *tp = tcp_sk(sk);
0439     struct bbr *bbr = inet_csk_ca(sk);
0440     u64 now_ns, edt_ns, interval_us;
0441     u32 interval_delivered, inflight_at_edt;
0442 
0443     now_ns = tp->tcp_clock_cache;
0444     edt_ns = max(tp->tcp_wstamp_ns, now_ns);
0445     interval_us = div_u64(edt_ns - now_ns, NSEC_PER_USEC);
0446     interval_delivered = (u64)bbr_bw(sk) * interval_us >> BW_SCALE;
0447     inflight_at_edt = inflight_now;
0448     if (bbr->pacing_gain > BBR_UNIT)              /* increasing inflight */
0449         inflight_at_edt += bbr_tso_segs_goal(sk);  /* include EDT skb */
0450     if (interval_delivered >= inflight_at_edt)
0451         return 0;
0452     return inflight_at_edt - interval_delivered;
0453 }
0454 
0455 /* Find the cwnd increment based on estimate of ack aggregation */
0456 static u32 bbr_ack_aggregation_cwnd(struct sock *sk)
0457 {
0458     u32 max_aggr_cwnd, aggr_cwnd = 0;
0459 
0460     if (bbr_extra_acked_gain && bbr_full_bw_reached(sk)) {
0461         max_aggr_cwnd = ((u64)bbr_bw(sk) * bbr_extra_acked_max_us)
0462                 / BW_UNIT;
0463         aggr_cwnd = (bbr_extra_acked_gain * bbr_extra_acked(sk))
0464                  >> BBR_SCALE;
0465         aggr_cwnd = min(aggr_cwnd, max_aggr_cwnd);
0466     }
0467 
0468     return aggr_cwnd;
0469 }
0470 
0471 /* An optimization in BBR to reduce losses: On the first round of recovery, we
0472  * follow the packet conservation principle: send P packets per P packets acked.
0473  * After that, we slow-start and send at most 2*P packets per P packets acked.
0474  * After recovery finishes, or upon undo, we restore the cwnd we had when
0475  * recovery started (capped by the target cwnd based on estimated BDP).
0476  *
0477  * TODO(ycheng/ncardwell): implement a rate-based approach.
0478  */
0479 static bool bbr_set_cwnd_to_recover_or_restore(
0480     struct sock *sk, const struct rate_sample *rs, u32 acked, u32 *new_cwnd)
0481 {
0482     struct tcp_sock *tp = tcp_sk(sk);
0483     struct bbr *bbr = inet_csk_ca(sk);
0484     u8 prev_state = bbr->prev_ca_state, state = inet_csk(sk)->icsk_ca_state;
0485     u32 cwnd = tcp_snd_cwnd(tp);
0486 
0487     /* An ACK for P pkts should release at most 2*P packets. We do this
0488      * in two steps. First, here we deduct the number of lost packets.
0489      * Then, in bbr_set_cwnd() we slow start up toward the target cwnd.
0490      */
0491     if (rs->losses > 0)
0492         cwnd = max_t(s32, cwnd - rs->losses, 1);
0493 
0494     if (state == TCP_CA_Recovery && prev_state != TCP_CA_Recovery) {
0495         /* Starting 1st round of Recovery, so do packet conservation. */
0496         bbr->packet_conservation = 1;
0497         bbr->next_rtt_delivered = tp->delivered;  /* start round now */
0498         /* Cut unused cwnd from app behavior, TSQ, or TSO deferral: */
0499         cwnd = tcp_packets_in_flight(tp) + acked;
0500     } else if (prev_state >= TCP_CA_Recovery && state < TCP_CA_Recovery) {
0501         /* Exiting loss recovery; restore cwnd saved before recovery. */
0502         cwnd = max(cwnd, bbr->prior_cwnd);
0503         bbr->packet_conservation = 0;
0504     }
0505     bbr->prev_ca_state = state;
0506 
0507     if (bbr->packet_conservation) {
0508         *new_cwnd = max(cwnd, tcp_packets_in_flight(tp) + acked);
0509         return true;    /* yes, using packet conservation */
0510     }
0511     *new_cwnd = cwnd;
0512     return false;
0513 }
0514 
0515 /* Slow-start up toward target cwnd (if bw estimate is growing, or packet loss
0516  * has drawn us down below target), or snap down to target if we're above it.
0517  */
0518 static void bbr_set_cwnd(struct sock *sk, const struct rate_sample *rs,
0519              u32 acked, u32 bw, int gain)
0520 {
0521     struct tcp_sock *tp = tcp_sk(sk);
0522     struct bbr *bbr = inet_csk_ca(sk);
0523     u32 cwnd = tcp_snd_cwnd(tp), target_cwnd = 0;
0524 
0525     if (!acked)
0526         goto done;  /* no packet fully ACKed; just apply caps */
0527 
0528     if (bbr_set_cwnd_to_recover_or_restore(sk, rs, acked, &cwnd))
0529         goto done;
0530 
0531     target_cwnd = bbr_bdp(sk, bw, gain);
0532 
0533     /* Increment the cwnd to account for excess ACKed data that seems
0534      * due to aggregation (of data and/or ACKs) visible in the ACK stream.
0535      */
0536     target_cwnd += bbr_ack_aggregation_cwnd(sk);
0537     target_cwnd = bbr_quantization_budget(sk, target_cwnd);
0538 
0539     /* If we're below target cwnd, slow start cwnd toward target cwnd. */
0540     if (bbr_full_bw_reached(sk))  /* only cut cwnd if we filled the pipe */
0541         cwnd = min(cwnd + acked, target_cwnd);
0542     else if (cwnd < target_cwnd || tp->delivered < TCP_INIT_CWND)
0543         cwnd = cwnd + acked;
0544     cwnd = max(cwnd, bbr_cwnd_min_target);
0545 
0546 done:
0547     tcp_snd_cwnd_set(tp, min(cwnd, tp->snd_cwnd_clamp));    /* apply global cap */
0548     if (bbr->mode == BBR_PROBE_RTT)  /* drain queue, refresh min_rtt */
0549         tcp_snd_cwnd_set(tp, min(tcp_snd_cwnd(tp), bbr_cwnd_min_target));
0550 }
0551 
0552 /* End cycle phase if it's time and/or we hit the phase's in-flight target. */
0553 static bool bbr_is_next_cycle_phase(struct sock *sk,
0554                     const struct rate_sample *rs)
0555 {
0556     struct tcp_sock *tp = tcp_sk(sk);
0557     struct bbr *bbr = inet_csk_ca(sk);
0558     bool is_full_length =
0559         tcp_stamp_us_delta(tp->delivered_mstamp, bbr->cycle_mstamp) >
0560         bbr->min_rtt_us;
0561     u32 inflight, bw;
0562 
0563     /* The pacing_gain of 1.0 paces at the estimated bw to try to fully
0564      * use the pipe without increasing the queue.
0565      */
0566     if (bbr->pacing_gain == BBR_UNIT)
0567         return is_full_length;      /* just use wall clock time */
0568 
0569     inflight = bbr_packets_in_net_at_edt(sk, rs->prior_in_flight);
0570     bw = bbr_max_bw(sk);
0571 
0572     /* A pacing_gain > 1.0 probes for bw by trying to raise inflight to at
0573      * least pacing_gain*BDP; this may take more than min_rtt if min_rtt is
0574      * small (e.g. on a LAN). We do not persist if packets are lost, since
0575      * a path with small buffers may not hold that much.
0576      */
0577     if (bbr->pacing_gain > BBR_UNIT)
0578         return is_full_length &&
0579             (rs->losses ||  /* perhaps pacing_gain*BDP won't fit */
0580              inflight >= bbr_inflight(sk, bw, bbr->pacing_gain));
0581 
0582     /* A pacing_gain < 1.0 tries to drain extra queue we added if bw
0583      * probing didn't find more bw. If inflight falls to match BDP then we
0584      * estimate queue is drained; persisting would underutilize the pipe.
0585      */
0586     return is_full_length ||
0587         inflight <= bbr_inflight(sk, bw, BBR_UNIT);
0588 }
0589 
0590 static void bbr_advance_cycle_phase(struct sock *sk)
0591 {
0592     struct tcp_sock *tp = tcp_sk(sk);
0593     struct bbr *bbr = inet_csk_ca(sk);
0594 
0595     bbr->cycle_idx = (bbr->cycle_idx + 1) & (CYCLE_LEN - 1);
0596     bbr->cycle_mstamp = tp->delivered_mstamp;
0597 }
0598 
0599 /* Gain cycling: cycle pacing gain to converge to fair share of available bw. */
0600 static void bbr_update_cycle_phase(struct sock *sk,
0601                    const struct rate_sample *rs)
0602 {
0603     struct bbr *bbr = inet_csk_ca(sk);
0604 
0605     if (bbr->mode == BBR_PROBE_BW && bbr_is_next_cycle_phase(sk, rs))
0606         bbr_advance_cycle_phase(sk);
0607 }
0608 
0609 static void bbr_reset_startup_mode(struct sock *sk)
0610 {
0611     struct bbr *bbr = inet_csk_ca(sk);
0612 
0613     bbr->mode = BBR_STARTUP;
0614 }
0615 
0616 static void bbr_reset_probe_bw_mode(struct sock *sk)
0617 {
0618     struct bbr *bbr = inet_csk_ca(sk);
0619 
0620     bbr->mode = BBR_PROBE_BW;
0621     bbr->cycle_idx = CYCLE_LEN - 1 - prandom_u32_max(bbr_cycle_rand);
0622     bbr_advance_cycle_phase(sk);    /* flip to next phase of gain cycle */
0623 }
0624 
0625 static void bbr_reset_mode(struct sock *sk)
0626 {
0627     if (!bbr_full_bw_reached(sk))
0628         bbr_reset_startup_mode(sk);
0629     else
0630         bbr_reset_probe_bw_mode(sk);
0631 }
0632 
0633 /* Start a new long-term sampling interval. */
0634 static void bbr_reset_lt_bw_sampling_interval(struct sock *sk)
0635 {
0636     struct tcp_sock *tp = tcp_sk(sk);
0637     struct bbr *bbr = inet_csk_ca(sk);
0638 
0639     bbr->lt_last_stamp = div_u64(tp->delivered_mstamp, USEC_PER_MSEC);
0640     bbr->lt_last_delivered = tp->delivered;
0641     bbr->lt_last_lost = tp->lost;
0642     bbr->lt_rtt_cnt = 0;
0643 }
0644 
0645 /* Completely reset long-term bandwidth sampling. */
0646 static void bbr_reset_lt_bw_sampling(struct sock *sk)
0647 {
0648     struct bbr *bbr = inet_csk_ca(sk);
0649 
0650     bbr->lt_bw = 0;
0651     bbr->lt_use_bw = 0;
0652     bbr->lt_is_sampling = false;
0653     bbr_reset_lt_bw_sampling_interval(sk);
0654 }
0655 
0656 /* Long-term bw sampling interval is done. Estimate whether we're policed. */
0657 static void bbr_lt_bw_interval_done(struct sock *sk, u32 bw)
0658 {
0659     struct bbr *bbr = inet_csk_ca(sk);
0660     u32 diff;
0661 
0662     if (bbr->lt_bw) {  /* do we have bw from a previous interval? */
0663         /* Is new bw close to the lt_bw from the previous interval? */
0664         diff = abs(bw - bbr->lt_bw);
0665         if ((diff * BBR_UNIT <= bbr_lt_bw_ratio * bbr->lt_bw) ||
0666             (bbr_rate_bytes_per_sec(sk, diff, BBR_UNIT) <=
0667              bbr_lt_bw_diff)) {
0668             /* All criteria are met; estimate we're policed. */
0669             bbr->lt_bw = (bw + bbr->lt_bw) >> 1;  /* avg 2 intvls */
0670             bbr->lt_use_bw = 1;
0671             bbr->pacing_gain = BBR_UNIT;  /* try to avoid drops */
0672             bbr->lt_rtt_cnt = 0;
0673             return;
0674         }
0675     }
0676     bbr->lt_bw = bw;
0677     bbr_reset_lt_bw_sampling_interval(sk);
0678 }
0679 
0680 /* Token-bucket traffic policers are common (see "An Internet-Wide Analysis of
0681  * Traffic Policing", SIGCOMM 2016). BBR detects token-bucket policers and
0682  * explicitly models their policed rate, to reduce unnecessary losses. We
0683  * estimate that we're policed if we see 2 consecutive sampling intervals with
0684  * consistent throughput and high packet loss. If we think we're being policed,
0685  * set lt_bw to the "long-term" average delivery rate from those 2 intervals.
0686  */
0687 static void bbr_lt_bw_sampling(struct sock *sk, const struct rate_sample *rs)
0688 {
0689     struct tcp_sock *tp = tcp_sk(sk);
0690     struct bbr *bbr = inet_csk_ca(sk);
0691     u32 lost, delivered;
0692     u64 bw;
0693     u32 t;
0694 
0695     if (bbr->lt_use_bw) {   /* already using long-term rate, lt_bw? */
0696         if (bbr->mode == BBR_PROBE_BW && bbr->round_start &&
0697             ++bbr->lt_rtt_cnt >= bbr_lt_bw_max_rtts) {
0698             bbr_reset_lt_bw_sampling(sk);    /* stop using lt_bw */
0699             bbr_reset_probe_bw_mode(sk);  /* restart gain cycling */
0700         }
0701         return;
0702     }
0703 
0704     /* Wait for the first loss before sampling, to let the policer exhaust
0705      * its tokens and estimate the steady-state rate allowed by the policer.
0706      * Starting samples earlier includes bursts that over-estimate the bw.
0707      */
0708     if (!bbr->lt_is_sampling) {
0709         if (!rs->losses)
0710             return;
0711         bbr_reset_lt_bw_sampling_interval(sk);
0712         bbr->lt_is_sampling = true;
0713     }
0714 
0715     /* To avoid underestimates, reset sampling if we run out of data. */
0716     if (rs->is_app_limited) {
0717         bbr_reset_lt_bw_sampling(sk);
0718         return;
0719     }
0720 
0721     if (bbr->round_start)
0722         bbr->lt_rtt_cnt++;  /* count round trips in this interval */
0723     if (bbr->lt_rtt_cnt < bbr_lt_intvl_min_rtts)
0724         return;     /* sampling interval needs to be longer */
0725     if (bbr->lt_rtt_cnt > 4 * bbr_lt_intvl_min_rtts) {
0726         bbr_reset_lt_bw_sampling(sk);  /* interval is too long */
0727         return;
0728     }
0729 
0730     /* End sampling interval when a packet is lost, so we estimate the
0731      * policer tokens were exhausted. Stopping the sampling before the
0732      * tokens are exhausted under-estimates the policed rate.
0733      */
0734     if (!rs->losses)
0735         return;
0736 
0737     /* Calculate packets lost and delivered in sampling interval. */
0738     lost = tp->lost - bbr->lt_last_lost;
0739     delivered = tp->delivered - bbr->lt_last_delivered;
0740     /* Is loss rate (lost/delivered) >= lt_loss_thresh? If not, wait. */
0741     if (!delivered || (lost << BBR_SCALE) < bbr_lt_loss_thresh * delivered)
0742         return;
0743 
0744     /* Find average delivery rate in this sampling interval. */
0745     t = div_u64(tp->delivered_mstamp, USEC_PER_MSEC) - bbr->lt_last_stamp;
0746     if ((s32)t < 1)
0747         return;     /* interval is less than one ms, so wait */
0748     /* Check if can multiply without overflow */
0749     if (t >= ~0U / USEC_PER_MSEC) {
0750         bbr_reset_lt_bw_sampling(sk);  /* interval too long; reset */
0751         return;
0752     }
0753     t *= USEC_PER_MSEC;
0754     bw = (u64)delivered * BW_UNIT;
0755     do_div(bw, t);
0756     bbr_lt_bw_interval_done(sk, bw);
0757 }
0758 
0759 /* Estimate the bandwidth based on how fast packets are delivered */
0760 static void bbr_update_bw(struct sock *sk, const struct rate_sample *rs)
0761 {
0762     struct tcp_sock *tp = tcp_sk(sk);
0763     struct bbr *bbr = inet_csk_ca(sk);
0764     u64 bw;
0765 
0766     bbr->round_start = 0;
0767     if (rs->delivered < 0 || rs->interval_us <= 0)
0768         return; /* Not a valid observation */
0769 
0770     /* See if we've reached the next RTT */
0771     if (!before(rs->prior_delivered, bbr->next_rtt_delivered)) {
0772         bbr->next_rtt_delivered = tp->delivered;
0773         bbr->rtt_cnt++;
0774         bbr->round_start = 1;
0775         bbr->packet_conservation = 0;
0776     }
0777 
0778     bbr_lt_bw_sampling(sk, rs);
0779 
0780     /* Divide delivered by the interval to find a (lower bound) bottleneck
0781      * bandwidth sample. Delivered is in packets and interval_us in uS and
0782      * ratio will be <<1 for most connections. So delivered is first scaled.
0783      */
0784     bw = div64_long((u64)rs->delivered * BW_UNIT, rs->interval_us);
0785 
0786     /* If this sample is application-limited, it is likely to have a very
0787      * low delivered count that represents application behavior rather than
0788      * the available network rate. Such a sample could drag down estimated
0789      * bw, causing needless slow-down. Thus, to continue to send at the
0790      * last measured network rate, we filter out app-limited samples unless
0791      * they describe the path bw at least as well as our bw model.
0792      *
0793      * So the goal during app-limited phase is to proceed with the best
0794      * network rate no matter how long. We automatically leave this
0795      * phase when app writes faster than the network can deliver :)
0796      */
0797     if (!rs->is_app_limited || bw >= bbr_max_bw(sk)) {
0798         /* Incorporate new sample into our max bw filter. */
0799         minmax_running_max(&bbr->bw, bbr_bw_rtts, bbr->rtt_cnt, bw);
0800     }
0801 }
0802 
0803 /* Estimates the windowed max degree of ack aggregation.
0804  * This is used to provision extra in-flight data to keep sending during
0805  * inter-ACK silences.
0806  *
0807  * Degree of ack aggregation is estimated as extra data acked beyond expected.
0808  *
0809  * max_extra_acked = "maximum recent excess data ACKed beyond max_bw * interval"
0810  * cwnd += max_extra_acked
0811  *
0812  * Max extra_acked is clamped by cwnd and bw * bbr_extra_acked_max_us (100 ms).
0813  * Max filter is an approximate sliding window of 5-10 (packet timed) round
0814  * trips.
0815  */
0816 static void bbr_update_ack_aggregation(struct sock *sk,
0817                        const struct rate_sample *rs)
0818 {
0819     u32 epoch_us, expected_acked, extra_acked;
0820     struct bbr *bbr = inet_csk_ca(sk);
0821     struct tcp_sock *tp = tcp_sk(sk);
0822 
0823     if (!bbr_extra_acked_gain || rs->acked_sacked <= 0 ||
0824         rs->delivered < 0 || rs->interval_us <= 0)
0825         return;
0826 
0827     if (bbr->round_start) {
0828         bbr->extra_acked_win_rtts = min(0x1F,
0829                         bbr->extra_acked_win_rtts + 1);
0830         if (bbr->extra_acked_win_rtts >= bbr_extra_acked_win_rtts) {
0831             bbr->extra_acked_win_rtts = 0;
0832             bbr->extra_acked_win_idx = bbr->extra_acked_win_idx ?
0833                            0 : 1;
0834             bbr->extra_acked[bbr->extra_acked_win_idx] = 0;
0835         }
0836     }
0837 
0838     /* Compute how many packets we expected to be delivered over epoch. */
0839     epoch_us = tcp_stamp_us_delta(tp->delivered_mstamp,
0840                       bbr->ack_epoch_mstamp);
0841     expected_acked = ((u64)bbr_bw(sk) * epoch_us) / BW_UNIT;
0842 
0843     /* Reset the aggregation epoch if ACK rate is below expected rate or
0844      * significantly large no. of ack received since epoch (potentially
0845      * quite old epoch).
0846      */
0847     if (bbr->ack_epoch_acked <= expected_acked ||
0848         (bbr->ack_epoch_acked + rs->acked_sacked >=
0849          bbr_ack_epoch_acked_reset_thresh)) {
0850         bbr->ack_epoch_acked = 0;
0851         bbr->ack_epoch_mstamp = tp->delivered_mstamp;
0852         expected_acked = 0;
0853     }
0854 
0855     /* Compute excess data delivered, beyond what was expected. */
0856     bbr->ack_epoch_acked = min_t(u32, 0xFFFFF,
0857                      bbr->ack_epoch_acked + rs->acked_sacked);
0858     extra_acked = bbr->ack_epoch_acked - expected_acked;
0859     extra_acked = min(extra_acked, tcp_snd_cwnd(tp));
0860     if (extra_acked > bbr->extra_acked[bbr->extra_acked_win_idx])
0861         bbr->extra_acked[bbr->extra_acked_win_idx] = extra_acked;
0862 }
0863 
0864 /* Estimate when the pipe is full, using the change in delivery rate: BBR
0865  * estimates that STARTUP filled the pipe if the estimated bw hasn't changed by
0866  * at least bbr_full_bw_thresh (25%) after bbr_full_bw_cnt (3) non-app-limited
0867  * rounds. Why 3 rounds: 1: rwin autotuning grows the rwin, 2: we fill the
0868  * higher rwin, 3: we get higher delivery rate samples. Or transient
0869  * cross-traffic or radio noise can go away. CUBIC Hystart shares a similar
0870  * design goal, but uses delay and inter-ACK spacing instead of bandwidth.
0871  */
0872 static void bbr_check_full_bw_reached(struct sock *sk,
0873                       const struct rate_sample *rs)
0874 {
0875     struct bbr *bbr = inet_csk_ca(sk);
0876     u32 bw_thresh;
0877 
0878     if (bbr_full_bw_reached(sk) || !bbr->round_start || rs->is_app_limited)
0879         return;
0880 
0881     bw_thresh = (u64)bbr->full_bw * bbr_full_bw_thresh >> BBR_SCALE;
0882     if (bbr_max_bw(sk) >= bw_thresh) {
0883         bbr->full_bw = bbr_max_bw(sk);
0884         bbr->full_bw_cnt = 0;
0885         return;
0886     }
0887     ++bbr->full_bw_cnt;
0888     bbr->full_bw_reached = bbr->full_bw_cnt >= bbr_full_bw_cnt;
0889 }
0890 
0891 /* If pipe is probably full, drain the queue and then enter steady-state. */
0892 static void bbr_check_drain(struct sock *sk, const struct rate_sample *rs)
0893 {
0894     struct bbr *bbr = inet_csk_ca(sk);
0895 
0896     if (bbr->mode == BBR_STARTUP && bbr_full_bw_reached(sk)) {
0897         bbr->mode = BBR_DRAIN;  /* drain queue we created */
0898         tcp_sk(sk)->snd_ssthresh =
0899                 bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT);
0900     }   /* fall through to check if in-flight is already small: */
0901     if (bbr->mode == BBR_DRAIN &&
0902         bbr_packets_in_net_at_edt(sk, tcp_packets_in_flight(tcp_sk(sk))) <=
0903         bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT))
0904         bbr_reset_probe_bw_mode(sk);  /* we estimate queue is drained */
0905 }
0906 
0907 static void bbr_check_probe_rtt_done(struct sock *sk)
0908 {
0909     struct tcp_sock *tp = tcp_sk(sk);
0910     struct bbr *bbr = inet_csk_ca(sk);
0911 
0912     if (!(bbr->probe_rtt_done_stamp &&
0913           after(tcp_jiffies32, bbr->probe_rtt_done_stamp)))
0914         return;
0915 
0916     bbr->min_rtt_stamp = tcp_jiffies32;  /* wait a while until PROBE_RTT */
0917     tcp_snd_cwnd_set(tp, max(tcp_snd_cwnd(tp), bbr->prior_cwnd));
0918     bbr_reset_mode(sk);
0919 }
0920 
0921 /* The goal of PROBE_RTT mode is to have BBR flows cooperatively and
0922  * periodically drain the bottleneck queue, to converge to measure the true
0923  * min_rtt (unloaded propagation delay). This allows the flows to keep queues
0924  * small (reducing queuing delay and packet loss) and achieve fairness among
0925  * BBR flows.
0926  *
0927  * The min_rtt filter window is 10 seconds. When the min_rtt estimate expires,
0928  * we enter PROBE_RTT mode and cap the cwnd at bbr_cwnd_min_target=4 packets.
0929  * After at least bbr_probe_rtt_mode_ms=200ms and at least one packet-timed
0930  * round trip elapsed with that flight size <= 4, we leave PROBE_RTT mode and
0931  * re-enter the previous mode. BBR uses 200ms to approximately bound the
0932  * performance penalty of PROBE_RTT's cwnd capping to roughly 2% (200ms/10s).
0933  *
0934  * Note that flows need only pay 2% if they are busy sending over the last 10
0935  * seconds. Interactive applications (e.g., Web, RPCs, video chunks) often have
0936  * natural silences or low-rate periods within 10 seconds where the rate is low
0937  * enough for long enough to drain its queue in the bottleneck. We pick up
0938  * these min RTT measurements opportunistically with our min_rtt filter. :-)
0939  */
0940 static void bbr_update_min_rtt(struct sock *sk, const struct rate_sample *rs)
0941 {
0942     struct tcp_sock *tp = tcp_sk(sk);
0943     struct bbr *bbr = inet_csk_ca(sk);
0944     bool filter_expired;
0945 
0946     /* Track min RTT seen in the min_rtt_win_sec filter window: */
0947     filter_expired = after(tcp_jiffies32,
0948                    bbr->min_rtt_stamp + bbr_min_rtt_win_sec * HZ);
0949     if (rs->rtt_us >= 0 &&
0950         (rs->rtt_us < bbr->min_rtt_us ||
0951          (filter_expired && !rs->is_ack_delayed))) {
0952         bbr->min_rtt_us = rs->rtt_us;
0953         bbr->min_rtt_stamp = tcp_jiffies32;
0954     }
0955 
0956     if (bbr_probe_rtt_mode_ms > 0 && filter_expired &&
0957         !bbr->idle_restart && bbr->mode != BBR_PROBE_RTT) {
0958         bbr->mode = BBR_PROBE_RTT;  /* dip, drain queue */
0959         bbr_save_cwnd(sk);  /* note cwnd so we can restore it */
0960         bbr->probe_rtt_done_stamp = 0;
0961     }
0962 
0963     if (bbr->mode == BBR_PROBE_RTT) {
0964         /* Ignore low rate samples during this mode. */
0965         tp->app_limited =
0966             (tp->delivered + tcp_packets_in_flight(tp)) ? : 1;
0967         /* Maintain min packets in flight for max(200 ms, 1 round). */
0968         if (!bbr->probe_rtt_done_stamp &&
0969             tcp_packets_in_flight(tp) <= bbr_cwnd_min_target) {
0970             bbr->probe_rtt_done_stamp = tcp_jiffies32 +
0971                 msecs_to_jiffies(bbr_probe_rtt_mode_ms);
0972             bbr->probe_rtt_round_done = 0;
0973             bbr->next_rtt_delivered = tp->delivered;
0974         } else if (bbr->probe_rtt_done_stamp) {
0975             if (bbr->round_start)
0976                 bbr->probe_rtt_round_done = 1;
0977             if (bbr->probe_rtt_round_done)
0978                 bbr_check_probe_rtt_done(sk);
0979         }
0980     }
0981     /* Restart after idle ends only once we process a new S/ACK for data */
0982     if (rs->delivered > 0)
0983         bbr->idle_restart = 0;
0984 }
0985 
0986 static void bbr_update_gains(struct sock *sk)
0987 {
0988     struct bbr *bbr = inet_csk_ca(sk);
0989 
0990     switch (bbr->mode) {
0991     case BBR_STARTUP:
0992         bbr->pacing_gain = bbr_high_gain;
0993         bbr->cwnd_gain   = bbr_high_gain;
0994         break;
0995     case BBR_DRAIN:
0996         bbr->pacing_gain = bbr_drain_gain;  /* slow, to drain */
0997         bbr->cwnd_gain   = bbr_high_gain;   /* keep cwnd */
0998         break;
0999     case BBR_PROBE_BW:
1000         bbr->pacing_gain = (bbr->lt_use_bw ?
1001                     BBR_UNIT :
1002                     bbr_pacing_gain[bbr->cycle_idx]);
1003         bbr->cwnd_gain   = bbr_cwnd_gain;
1004         break;
1005     case BBR_PROBE_RTT:
1006         bbr->pacing_gain = BBR_UNIT;
1007         bbr->cwnd_gain   = BBR_UNIT;
1008         break;
1009     default:
1010         WARN_ONCE(1, "BBR bad mode: %u\n", bbr->mode);
1011         break;
1012     }
1013 }
1014 
1015 static void bbr_update_model(struct sock *sk, const struct rate_sample *rs)
1016 {
1017     bbr_update_bw(sk, rs);
1018     bbr_update_ack_aggregation(sk, rs);
1019     bbr_update_cycle_phase(sk, rs);
1020     bbr_check_full_bw_reached(sk, rs);
1021     bbr_check_drain(sk, rs);
1022     bbr_update_min_rtt(sk, rs);
1023     bbr_update_gains(sk);
1024 }
1025 
1026 static void bbr_main(struct sock *sk, const struct rate_sample *rs)
1027 {
1028     struct bbr *bbr = inet_csk_ca(sk);
1029     u32 bw;
1030 
1031     bbr_update_model(sk, rs);
1032 
1033     bw = bbr_bw(sk);
1034     bbr_set_pacing_rate(sk, bw, bbr->pacing_gain);
1035     bbr_set_cwnd(sk, rs, rs->acked_sacked, bw, bbr->cwnd_gain);
1036 }
1037 
1038 static void bbr_init(struct sock *sk)
1039 {
1040     struct tcp_sock *tp = tcp_sk(sk);
1041     struct bbr *bbr = inet_csk_ca(sk);
1042 
1043     bbr->prior_cwnd = 0;
1044     tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
1045     bbr->rtt_cnt = 0;
1046     bbr->next_rtt_delivered = tp->delivered;
1047     bbr->prev_ca_state = TCP_CA_Open;
1048     bbr->packet_conservation = 0;
1049 
1050     bbr->probe_rtt_done_stamp = 0;
1051     bbr->probe_rtt_round_done = 0;
1052     bbr->min_rtt_us = tcp_min_rtt(tp);
1053     bbr->min_rtt_stamp = tcp_jiffies32;
1054 
1055     minmax_reset(&bbr->bw, bbr->rtt_cnt, 0);  /* init max bw to 0 */
1056 
1057     bbr->has_seen_rtt = 0;
1058     bbr_init_pacing_rate_from_rtt(sk);
1059 
1060     bbr->round_start = 0;
1061     bbr->idle_restart = 0;
1062     bbr->full_bw_reached = 0;
1063     bbr->full_bw = 0;
1064     bbr->full_bw_cnt = 0;
1065     bbr->cycle_mstamp = 0;
1066     bbr->cycle_idx = 0;
1067     bbr_reset_lt_bw_sampling(sk);
1068     bbr_reset_startup_mode(sk);
1069 
1070     bbr->ack_epoch_mstamp = tp->tcp_mstamp;
1071     bbr->ack_epoch_acked = 0;
1072     bbr->extra_acked_win_rtts = 0;
1073     bbr->extra_acked_win_idx = 0;
1074     bbr->extra_acked[0] = 0;
1075     bbr->extra_acked[1] = 0;
1076 
1077     cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED);
1078 }
1079 
1080 static u32 bbr_sndbuf_expand(struct sock *sk)
1081 {
1082     /* Provision 3 * cwnd since BBR may slow-start even during recovery. */
1083     return 3;
1084 }
1085 
1086 /* In theory BBR does not need to undo the cwnd since it does not
1087  * always reduce cwnd on losses (see bbr_main()). Keep it for now.
1088  */
1089 static u32 bbr_undo_cwnd(struct sock *sk)
1090 {
1091     struct bbr *bbr = inet_csk_ca(sk);
1092 
1093     bbr->full_bw = 0;   /* spurious slow-down; reset full pipe detection */
1094     bbr->full_bw_cnt = 0;
1095     bbr_reset_lt_bw_sampling(sk);
1096     return tcp_snd_cwnd(tcp_sk(sk));
1097 }
1098 
1099 /* Entering loss recovery, so save cwnd for when we exit or undo recovery. */
1100 static u32 bbr_ssthresh(struct sock *sk)
1101 {
1102     bbr_save_cwnd(sk);
1103     return tcp_sk(sk)->snd_ssthresh;
1104 }
1105 
1106 static size_t bbr_get_info(struct sock *sk, u32 ext, int *attr,
1107                union tcp_cc_info *info)
1108 {
1109     if (ext & (1 << (INET_DIAG_BBRINFO - 1)) ||
1110         ext & (1 << (INET_DIAG_VEGASINFO - 1))) {
1111         struct tcp_sock *tp = tcp_sk(sk);
1112         struct bbr *bbr = inet_csk_ca(sk);
1113         u64 bw = bbr_bw(sk);
1114 
1115         bw = bw * tp->mss_cache * USEC_PER_SEC >> BW_SCALE;
1116         memset(&info->bbr, 0, sizeof(info->bbr));
1117         info->bbr.bbr_bw_lo     = (u32)bw;
1118         info->bbr.bbr_bw_hi     = (u32)(bw >> 32);
1119         info->bbr.bbr_min_rtt       = bbr->min_rtt_us;
1120         info->bbr.bbr_pacing_gain   = bbr->pacing_gain;
1121         info->bbr.bbr_cwnd_gain     = bbr->cwnd_gain;
1122         *attr = INET_DIAG_BBRINFO;
1123         return sizeof(info->bbr);
1124     }
1125     return 0;
1126 }
1127 
1128 static void bbr_set_state(struct sock *sk, u8 new_state)
1129 {
1130     struct bbr *bbr = inet_csk_ca(sk);
1131 
1132     if (new_state == TCP_CA_Loss) {
1133         struct rate_sample rs = { .losses = 1 };
1134 
1135         bbr->prev_ca_state = TCP_CA_Loss;
1136         bbr->full_bw = 0;
1137         bbr->round_start = 1;   /* treat RTO like end of a round */
1138         bbr_lt_bw_sampling(sk, &rs);
1139     }
1140 }
1141 
1142 static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = {
1143     .flags      = TCP_CONG_NON_RESTRICTED,
1144     .name       = "bbr",
1145     .owner      = THIS_MODULE,
1146     .init       = bbr_init,
1147     .cong_control   = bbr_main,
1148     .sndbuf_expand  = bbr_sndbuf_expand,
1149     .undo_cwnd  = bbr_undo_cwnd,
1150     .cwnd_event = bbr_cwnd_event,
1151     .ssthresh   = bbr_ssthresh,
1152     .min_tso_segs   = bbr_min_tso_segs,
1153     .get_info   = bbr_get_info,
1154     .set_state  = bbr_set_state,
1155 };
1156 
1157 BTF_SET8_START(tcp_bbr_check_kfunc_ids)
1158 #ifdef CONFIG_X86
1159 #ifdef CONFIG_DYNAMIC_FTRACE
1160 BTF_ID_FLAGS(func, bbr_init)
1161 BTF_ID_FLAGS(func, bbr_main)
1162 BTF_ID_FLAGS(func, bbr_sndbuf_expand)
1163 BTF_ID_FLAGS(func, bbr_undo_cwnd)
1164 BTF_ID_FLAGS(func, bbr_cwnd_event)
1165 BTF_ID_FLAGS(func, bbr_ssthresh)
1166 BTF_ID_FLAGS(func, bbr_min_tso_segs)
1167 BTF_ID_FLAGS(func, bbr_set_state)
1168 #endif
1169 #endif
1170 BTF_SET8_END(tcp_bbr_check_kfunc_ids)
1171 
1172 static const struct btf_kfunc_id_set tcp_bbr_kfunc_set = {
1173     .owner = THIS_MODULE,
1174     .set   = &tcp_bbr_check_kfunc_ids,
1175 };
1176 
1177 static int __init bbr_register(void)
1178 {
1179     int ret;
1180 
1181     BUILD_BUG_ON(sizeof(struct bbr) > ICSK_CA_PRIV_SIZE);
1182 
1183     ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &tcp_bbr_kfunc_set);
1184     if (ret < 0)
1185         return ret;
1186     return tcp_register_congestion_control(&tcp_bbr_cong_ops);
1187 }
1188 
1189 static void __exit bbr_unregister(void)
1190 {
1191     tcp_unregister_congestion_control(&tcp_bbr_cong_ops);
1192 }
1193 
1194 module_init(bbr_register);
1195 module_exit(bbr_unregister);
1196 
1197 MODULE_AUTHOR("Van Jacobson <vanj@google.com>");
1198 MODULE_AUTHOR("Neal Cardwell <ncardwell@google.com>");
1199 MODULE_AUTHOR("Yuchung Cheng <ycheng@google.com>");
1200 MODULE_AUTHOR("Soheil Hassas Yeganeh <soheil@google.com>");
1201 MODULE_LICENSE("Dual BSD/GPL");
1202 MODULE_DESCRIPTION("TCP BBR (Bottleneck Bandwidth and RTT)");