quiche/recovery/gcongestion/
mod.rs

1// Copyright (C) 2024, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27mod bbr;
28mod bbr2;
29pub mod pacer;
30mod recovery;
31
32use std::fmt::Debug;
33use std::str::FromStr;
34use std::time::Instant;
35
36pub use self::recovery::GRecovery;
37use crate::recovery::bandwidth::Bandwidth;
38
39use crate::recovery::rtt::RttStats;
40use crate::recovery::RecoveryStats;
41
42#[derive(Debug)]
43pub struct Lost {
44    pub(super) packet_number: u64,
45    pub(super) bytes_lost: usize,
46}
47
48#[derive(Debug)]
49pub struct Acked {
50    pub(super) pkt_num: u64,
51    pub(super) time_sent: Instant,
52}
53
54pub(super) trait CongestionControl: Debug {
55    /// Returns the name of the current state of the congestion control state
56    /// machine. Used to annotate qlogs after state transitions.
57    #[cfg(feature = "qlog")]
58    fn state_str(&self) -> &'static str;
59
60    /// Returns the size of the current congestion window in bytes. Note, this
61    /// is not the *available* window. Some send algorithms may not use a
62    /// congestion window and will return 0.
63    fn get_congestion_window(&self) -> usize;
64
65    /// Returns the size of the current congestion window in packets. Note, this
66    /// is not the *available* window. Some send algorithms may not use a
67    /// congestion window and will return 0.
68    fn get_congestion_window_in_packets(&self) -> usize;
69
70    /// Make decision on whether the sender can send right now.  Note that even
71    /// when this method returns true, the sending can be delayed due to pacing.
72    fn can_send(&self, bytes_in_flight: usize) -> bool;
73
74    /// Inform that we sent `bytes` to the wire, and if the packet is
75    /// retransmittable. `bytes_in_flight` is the number of bytes in flight
76    /// before the packet was sent. Note: this function must be called for
77    /// every packet sent to the wire.
78    fn on_packet_sent(
79        &mut self, sent_time: Instant, bytes_in_flight: usize,
80        packet_number: u64, bytes: usize, is_retransmissible: bool,
81        rtt_stats: &RttStats,
82    );
83
84    /// Inform that `packet_number` has been neutered.
85    fn on_packet_neutered(&mut self, _packet_number: u64) {}
86
87    /// Indicates an update to the congestion state, caused either by an
88    /// incoming ack or loss event timeout. `rtt_updated` indicates whether a
89    /// new `latest_rtt` sample has been taken, `prior_in_flight` the bytes in
90    /// flight prior to the congestion event. `acked_packets` and `lost_packets`
91    /// are any packets considered acked or lost as a result of the
92    /// congestion event.
93    #[allow(clippy::too_many_arguments)]
94    fn on_congestion_event(
95        &mut self, rtt_updated: bool, prior_in_flight: usize,
96        bytes_in_flight: usize, event_time: Instant, acked_packets: &[Acked],
97        lost_packets: &[Lost], least_unacked: u64, rtt_stats: &RttStats,
98        recovery_stats: &mut RecoveryStats,
99    );
100
101    /// Called when an RTO fires.  Resets the retransmission alarm if there are
102    /// remaining unacked packets.
103    fn on_retransmission_timeout(&mut self, packets_retransmitted: bool);
104
105    /// Called when connection migrates and cwnd needs to be reset.
106    #[allow(dead_code)]
107    fn on_connection_migration(&mut self);
108
109    /// Adjust the current cwnd to a new maximal size
110    fn limit_cwnd(&mut self, _max_cwnd: usize) {}
111
112    fn is_in_recovery(&self) -> bool;
113
114    #[allow(dead_code)]
115    fn is_cwnd_limited(&self, bytes_in_flight: usize) -> bool;
116
117    fn pacing_rate(
118        &self, bytes_in_flight: usize, rtt_stats: &RttStats,
119    ) -> Bandwidth;
120
121    fn bandwidth_estimate(&self, rtt_stats: &RttStats) -> Bandwidth;
122
123    fn max_bandwidth(&self) -> Bandwidth;
124
125    fn update_mss(&mut self, new_mss: usize);
126
127    fn on_app_limited(&mut self, _bytes_in_flight: usize) {}
128
129    #[cfg(feature = "qlog")]
130    fn ssthresh(&self) -> Option<u64> {
131        None
132    }
133}
134
135/// BBR settings used to customize the algorithm's behavior.
136///
137/// This functionality is experimental and will be removed in the future.
138///
139/// A congestion control algorithm has dual-responsibility of effective network
140/// utilization and avoiding congestion. Custom values should be choosen
141/// carefully since incorrect values can lead to network degradation for all
142/// connections on the shared network.
143#[derive(Debug, Default, Copy, Clone, PartialEq)]
144#[repr(C)]
145#[doc(hidden)]
146pub struct BbrParams {
147    /// Controls the BBR startup gain.
148    pub startup_cwnd_gain: Option<f32>,
149
150    /// Controls the BBR startup pacing gain.
151    pub startup_pacing_gain: Option<f32>,
152
153    /// Controls the BBR full bandwidth threshold.
154    pub full_bw_threshold: Option<f32>,
155
156    /// Controls the number of rounds to stay in STARTUP before
157    /// exiting due to bandwidth plateau.
158    pub startup_full_bw_rounds: Option<usize>,
159
160    /// Controls the BBR startup loss count necessary to exit startup.
161    pub startup_full_loss_count: Option<usize>,
162
163    /// Controls the BBR drain cwnd gain.
164    pub drain_cwnd_gain: Option<f32>,
165
166    /// Controls the BBR drain pacing gain.
167    pub drain_pacing_gain: Option<f32>,
168
169    /// Controls if BBR should respect Reno coexistence.
170    pub enable_reno_coexistence: Option<bool>,
171
172    /// Controls if BBR should enable code in Bandwidth Sampler that
173    /// attempts to avoid overestimating bandwidth on ack compression.
174    pub enable_overestimate_avoidance: Option<bool>,
175
176    /// Controls if BBR should enable a possible fix in Bandwidth
177    /// Sampler that attempts to bandwidth over estimation avoidance.
178    pub choose_a0_point_fix: Option<bool>,
179
180    /// Controls the BBR bandwidth probe up pacing gain.
181    pub probe_bw_probe_up_pacing_gain: Option<f32>,
182
183    /// Controls the BBR bandwidth probe down pacing gain.
184    pub probe_bw_probe_down_pacing_gain: Option<f32>,
185
186    /// Controls the BBR probe bandwidth DOWN/CRUISE/REFILL cwnd gain.
187    pub probe_bw_cwnd_gain: Option<f32>,
188
189    /// Controls the BBR probe bandwidth UP cwnd gain.
190    pub probe_bw_up_cwnd_gain: Option<f32>,
191
192    /// Controls the BBR probe RTT pacing gain.
193    pub probe_rtt_pacing_gain: Option<f32>,
194
195    /// Controls the BBR probe RTT cwnd gain.
196    pub probe_rtt_cwnd_gain: Option<f32>,
197
198    /// Controls the number of rounds BBR should stay in probe up if
199    /// bytes_in_flight doesn't drop below target.
200    pub max_probe_up_queue_rounds: Option<usize>,
201
202    /// Controls the BBR loss threshold.
203    pub loss_threshold: Option<f32>,
204
205    /// Controls if BBR should use bytes delievered as an estimate for
206    /// inflight_hi.
207    pub use_bytes_delivered_for_inflight_hi: Option<bool>,
208
209    /// Controls if BBR should adjust startup pacing at round end.
210    pub decrease_startup_pacing_at_end_of_round: Option<bool>,
211
212    /// Controls the BBR bandwidth lo reduction strategy.
213    pub bw_lo_reduction_strategy: Option<BbrBwLoReductionStrategy>,
214
215    /// Determines whether app limited rounds with no bandwidth growth count
216    /// towards the rounds threshold to exit startup.
217    pub ignore_app_limited_for_no_bandwidth_growth: Option<bool>,
218
219    /// Initial pacing rate for a new connection before an RTT
220    /// estimate is available.  This rate serves as an upper bound on
221    /// the initial pacing rate, which is calculated by dividing the
222    /// initial cwnd by the first RTT estimate.
223    pub initial_pacing_rate_bytes_per_second: Option<u64>,
224
225    /// If true, scale the pacing rate when updating mss when doing pmtud.
226    pub scale_pacing_rate_by_mss: Option<bool>,
227}
228
229/// Controls BBR's bandwidth reduction strategy on congestion event.
230///
231/// This functionality is experimental and will be removed in the future.
232#[derive(Debug, Copy, Clone, PartialEq, Eq)]
233#[repr(C)]
234#[doc(hidden)]
235pub enum BbrBwLoReductionStrategy {
236    /// Uses the default strategy based on `BBRBeta`.
237    Default           = 0,
238
239    /// Considers min-rtt to estimate bandwidth reduction.
240    MinRttReduction   = 1,
241
242    /// Considers inflight data to estimate bandwidth reduction.
243    InflightReduction = 2,
244
245    /// Considers cwnd to estimate bandwidth reduction.
246    CwndReduction     = 3,
247}
248
249#[doc(hidden)]
250impl FromStr for BbrBwLoReductionStrategy {
251    type Err = crate::Error;
252
253    /// Converts a string to `BbrBwLoReductionStrategy`.
254    ///
255    /// If `name` is not valid, `Error::CongestionControl` is returned.
256    fn from_str(name: &str) -> Result<Self, Self::Err> {
257        match name {
258            "default" => Ok(BbrBwLoReductionStrategy::Default),
259            "minrtt" => Ok(BbrBwLoReductionStrategy::MinRttReduction),
260            "inflight" => Ok(BbrBwLoReductionStrategy::InflightReduction),
261            "cwnd" => Ok(BbrBwLoReductionStrategy::CwndReduction),
262
263            _ => Err(crate::Error::CongestionControl),
264        }
265    }
266}