1
//! Round Trip Time measurement (ยง 2.1)
2

            
3
use std::cmp::{max, min};
4
use std::collections::VecDeque;
5
use std::sync::atomic::{AtomicBool, Ordering};
6
use std::time::{Duration, Instant};
7

            
8
use super::params::RoundTripEstimatorParams;
9
use super::{CongestionWindow, State};
10

            
11
use thiserror::Error;
12
use tor_error::{ErrorKind, HasKind};
13

            
14
/// An error originating from the tor-congestion crate.
15
#[derive(Error, Debug, Clone)]
16
#[non_exhaustive]
17
pub(crate) enum Error {
18
    /// A call to `RoundtripTimeEstimator::sendme_received` was made without calling
19
    /// `RoundtripTimeEstimator::expect_sendme` first.
20
    #[error("Informed of a SENDME we weren't expecting")]
21
    MismatchedEstimationCall,
22
}
23

            
24
impl HasKind for Error {
25
    fn kind(&self) -> ErrorKind {
26
        use Error as E;
27
        match self {
28
            E::MismatchedEstimationCall => ErrorKind::TorProtocolViolation,
29
        }
30
    }
31
}
32

            
33
/// Provides an estimate of the round-trip time (RTT) of a Tor circuit.
34
#[derive(Debug)]
35
#[allow(dead_code)]
36
pub(crate) struct RoundtripTimeEstimator {
37
    /// A queue of times we sent a cell that we'd expect a SENDME for.
38
    ///
39
    /// When a data cell is sent and for which we expect a SENDME next, the timestamp at the send
40
    /// is kept in this queue so we can use it to measure the RTT when the SENDME is received.
41
    ///
42
    /// A queue is used here because the protocol allows to send all pending SENDMEs at once as
43
    /// long as it is within one congestion window.
44
    sendme_expected_from: VecDeque<Instant>,
45
    /// The last *measured* round-trip time.
46
    ///
47
    /// This is `None` iff we have not managed to get any estimate yet.
48
    last_rtt: Option<Duration>,
49
    /// The current smoothed *estimate* of what the round-trip time is.
50
    ///
51
    /// This is `None` iff we have not managed to get any estimate yet.
52
    ewma_rtt: Option<Duration>,
53
    /// The minimum observed value of `last_rtt`.
54
    ///
55
    /// This is `None` iff we have not managed to get any estimate yet.
56
    min_rtt: Option<Duration>,
57
    /// The maximum observed value of `last_rtt`.
58
    ///
59
    /// This is `None` iff we have not managed to get any estimate yet.
60
    max_rtt: Option<Duration>,
61
    /// The network parameters we're using.
62
    params: RoundTripEstimatorParams,
63
    /// A reference to a shared boolean for storing if the clock is stalled or not.
64
    /// Spec: CLOCK_HEURISTICS from prop324. See is_clock_stalled() for the implementation.
65
    clock_stalled: AtomicBool,
66
}
67

            
68
#[allow(dead_code)]
69
impl RoundtripTimeEstimator {
70
    /// Create a new `RoundtripTimeEstimator`, using a set of `NetParameters` and a shared boolean
71
    /// to cache clock stalled state in.
72
754
    pub(crate) fn new(params: &RoundTripEstimatorParams) -> Self {
73
754
        Self {
74
754
            sendme_expected_from: Default::default(),
75
754
            last_rtt: None,
76
754
            ewma_rtt: None,
77
754
            min_rtt: None,
78
754
            max_rtt: None,
79
754
            params: params.clone(),
80
754
            clock_stalled: AtomicBool::default(),
81
754
        }
82
754
    }
83

            
84
    /// Return true iff the estimator is ready to be used or read.
85
312
    pub(crate) fn is_ready(&self) -> bool {
86
312
        !self.clock_stalled() && self.last_rtt.is_some()
87
312
    }
88

            
89
    /// Return the state of the clock stalled indicator.
90
468
    pub(crate) fn clock_stalled(&self) -> bool {
91
468
        self.clock_stalled.load(Ordering::SeqCst)
92
468
    }
93

            
94
    /// Return the EWMA RTT in usec or `None` if we don't have an estimate yet.
95
2676
    pub(crate) fn ewma_rtt_usec(&self) -> Option<u32> {
96
2676
        self.ewma_rtt
97
3270
            .map(|rtt| u32::try_from(rtt.as_micros()).ok().unwrap_or(u32::MAX))
98
2676
    }
99

            
100
    /// Return the Minimum RTT in usec or `None` if we don't have an estimate yet.
101
276
    pub(crate) fn min_rtt_usec(&self) -> Option<u32> {
102
276
        self.min_rtt
103
414
            .map(|rtt| u32::try_from(rtt.as_micros()).ok().unwrap_or(u32::MAX))
104
276
    }
105

            
106
    /// Inform the estimator that we did (at time `now`) something that we'll expect a SENDME to
107
    /// be received for.
108
174
    pub(crate) fn expect_sendme(&mut self, now: Instant) {
109
174
        self.sendme_expected_from.push_back(now);
110
174
    }
111

            
112
    /// Return whether we can use heuristics to sanity-check RTT values against our EWMA value.
113
    /// Spec: 2.1.1. Clock Jump Heuristics CLOCK_HEURISTICS
114
    ///
115
    /// Used in [`is_clock_stalled`](RoundtripTimeEstimator::is_clock_stalled), to check the sanity of
116
    /// a newly measured RTT value.
117
174
    fn can_crosscheck_with_current_estimate(&self, in_slow_start: bool) -> bool {
118
174
        // If we're in slow start, we don't perform any sanity checks, as per spec. If we don't
119
174
        // have a current estimate, we can't use it for sanity checking, because it doesn't
120
174
        // exist.
121
174
        !in_slow_start && self.ewma_rtt.is_some()
122
174
    }
123

            
124
    /// Given a raw RTT value we just observed, compute whether or not we think the clock has
125
    /// stalled or jumped, and we should throw it out as a result.
126
174
    fn is_clock_stalled(&self, raw_rtt: Duration, in_slow_start: bool) -> bool {
127
174
        if raw_rtt.is_zero() {
128
            // Clock is stalled.
129
            self.clock_stalled.store(true, Ordering::SeqCst);
130
            true
131
174
        } else if self.can_crosscheck_with_current_estimate(in_slow_start) {
132
62
            let ewma_rtt = self
133
62
                .ewma_rtt
134
62
                .expect("ewma_rtt was not checked by can_crosscheck_with_current_estimate?!");
135

            
136
            /// Discrepancy ratio of a new RTT value that we allow against the current RTT in order
137
            /// to declare if the clock has stalled or not. This value is taken from proposal 324
138
            /// section 2.1.1 CLOCK_HEURISTICS and has the same name as in C-tor.
139
            const DELTA_DISCREPANCY_RATIO_MAX: u32 = 5000;
140
            // If we have enough data, check the sanity of our measurement against our EWMA value.
141
62
            if raw_rtt > ewma_rtt * DELTA_DISCREPANCY_RATIO_MAX {
142
                // The clock significantly jumped forward.
143
                //
144
                // Don't update the global cache, though, since this is triggerable over the
145
                // network.
146
                //
147
                // FIXME(eta): We should probably log something here?
148
                true
149
62
            } else if ewma_rtt > raw_rtt * DELTA_DISCREPANCY_RATIO_MAX {
150
                // The clock might have stalled. We can't really make a decision just off this
151
                // one measurement, though, so we'll use the stored stall value.
152
                self.clock_stalled.load(Ordering::SeqCst)
153
            } else {
154
                // If we got here, we're not stalled.
155
62
                self.clock_stalled.store(false, Ordering::SeqCst);
156
62
                false
157
            }
158
        } else {
159
            // If we don't have enough measurements to sanity check, assume it's okay.
160
112
            false
161
        }
162
174
    }
163

            
164
    /// Update the estimator on time `now` and at the congestion window `cwnd`.
165
    ///
166
    /// # Errors
167
    ///
168
    /// Each call to this function removes an entry from `sendme_expected_from` (the entries are
169
    /// added using [`sendme_expected_from`](Self::sendme_expected_from)).
170
    ///
171
    /// Returns an error if are not expecting any SENDMEs at this time (if `expect_sendme` was
172
    /// never called, or if we have exhausted all `sendme_expected_from` added by previous
173
    /// `expect_sendme` calls).
174
    ///
175
    /// Spec: prop324 section 2.1 C-tor: congestion_control_update_circuit_rtt() in
176
    /// congestion_control_common.c
177
174
    pub(crate) fn update(
178
174
        &mut self,
179
174
        now: Instant,
180
174
        state: &State,
181
174
        cwnd: &CongestionWindow,
182
174
    ) -> Result<(), Error> {
183
174
        let data_sent_at = self
184
174
            .sendme_expected_from
185
174
            .pop_front()
186
174
            .ok_or(Error::MismatchedEstimationCall)?;
187
174
        let raw_rtt = now.saturating_duration_since(data_sent_at);
188
174

            
189
174
        if self.is_clock_stalled(raw_rtt, state.in_slow_start()) {
190
            return Ok(());
191
174
        }
192
174

            
193
174
        self.max_rtt = self.max_rtt.max(Some(raw_rtt));
194
174
        self.last_rtt = Some(raw_rtt);
195

            
196
        // This is the "N" for N-EWMA.
197
174
        let ewma_n = u64::from(if state.in_slow_start() {
198
112
            self.params.ewma_ss_max()
199
        } else {
200
62
            min(
201
62
                (cwnd.update_rate(state) * (self.params.ewma_cwnd_pct().as_percent())) / 100,
202
62
                self.params.ewma_max(),
203
62
            )
204
        });
205
174
        let ewma_n = max(ewma_n, 2);
206
174

            
207
174
        // Get the USEC values.
208
174
        let raw_rtt_usec = raw_rtt.as_micros() as u64;
209
252
        let prev_ewma_rtt_usec = self.ewma_rtt.map(|rtt| rtt.as_micros() as u64);
210

            
211
        // This is the actual EWMA calculation.
212
        // C-tor simplifies this as follows for rounding error reasons:
213
        //
214
        // EWMA = value*2/(N+1) + EMA_prev*(N-1)/(N+1)
215
        //      = (value*2 + EWMA_prev*(N-1))/(N+1)
216
        //
217
        // Spec: prop324 section 2.1.2 (N_EWMA_SMOOTHING)
218
174
        let new_ewma_rtt_usec = match prev_ewma_rtt_usec {
219
18
            None => raw_rtt_usec,
220
156
            Some(prev_ewma_rtt_usec) => {
221
156
                ((raw_rtt_usec * 2) + ((ewma_n - 1) * prev_ewma_rtt_usec)) / (ewma_n + 1)
222
            }
223
        };
224
174
        let ewma_rtt = Duration::from_micros(new_ewma_rtt_usec);
225
174
        self.ewma_rtt = Some(ewma_rtt);
226

            
227
174
        let Some(min_rtt) = self.min_rtt else {
228
18
            self.min_rtt = self.ewma_rtt;
229
18
            return Ok(());
230
        };
231

            
232
156
        if cwnd.get() == cwnd.min() && !state.in_slow_start() {
233
4
            // The cast is OK even if lossy, we only care about the usec level.
234
4
            let max = max(ewma_rtt, min_rtt).as_micros() as u64;
235
4
            let min = min(ewma_rtt, min_rtt).as_micros() as u64;
236
4
            let rtt_reset_pct = u64::from(self.params.rtt_reset_pct().as_percent());
237
4
            let min_rtt = Duration::from_micros(
238
4
                (rtt_reset_pct * max / 100) + (100 - rtt_reset_pct) * min / 100,
239
4
            );
240
4

            
241
4
            self.min_rtt = Some(min_rtt);
242
152
        } else if self.ewma_rtt < self.min_rtt {
243
34
            self.min_rtt = self.ewma_rtt;
244
118
        }
245

            
246
156
        Ok(())
247
174
    }
248
}
249

            
250
#[cfg(test)]
251
#[allow(clippy::print_stderr)]
252
mod test {
253
    // @@ begin test lint list maintained by maint/add_warning @@
254
    #![allow(clippy::bool_assert_comparison)]
255
    #![allow(clippy::clone_on_copy)]
256
    #![allow(clippy::dbg_macro)]
257
    #![allow(clippy::mixed_attributes_style)]
258
    #![allow(clippy::print_stderr)]
259
    #![allow(clippy::print_stdout)]
260
    #![allow(clippy::single_char_pattern)]
261
    #![allow(clippy::unwrap_used)]
262
    #![allow(clippy::unchecked_duration_subtraction)]
263
    #![allow(clippy::useless_vec)]
264
    #![allow(clippy::needless_pass_by_value)]
265
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
266

            
267
    use std::time::{Duration, Instant};
268

            
269
    use crate::congestion::test_utils::{new_cwnd, new_rtt_estimator};
270

            
271
    use super::*;
272

            
273
    #[derive(Debug)]
274
    struct RttTestSample {
275
        sent_usec_in: u64,
276
        sendme_received_usec_in: u64,
277
        cwnd_in: u32,
278
        ss_in: bool,
279
        last_rtt_usec_out: u64,
280
        ewma_rtt_usec_out: u64,
281
        min_rtt_usec_out: u64,
282
    }
283

            
284
    impl From<[u64; 7]> for RttTestSample {
285
        fn from(arr: [u64; 7]) -> Self {
286
            Self {
287
                sent_usec_in: arr[0],
288
                sendme_received_usec_in: arr[1],
289
                cwnd_in: arr[2] as u32,
290
                ss_in: arr[3] == 1,
291
                last_rtt_usec_out: arr[4],
292
                ewma_rtt_usec_out: arr[5],
293
                min_rtt_usec_out: arr[6],
294
            }
295
        }
296
    }
297
    impl RttTestSample {
298
        fn test(&self, estimator: &mut RoundtripTimeEstimator, start: Instant) {
299
            let state = if self.ss_in {
300
                State::SlowStart
301
            } else {
302
                State::Steady
303
            };
304
            let mut cwnd = new_cwnd();
305
            cwnd.set(self.cwnd_in);
306
            let sent = start + Duration::from_micros(self.sent_usec_in);
307
            let sendme_received = start + Duration::from_micros(self.sendme_received_usec_in);
308

            
309
            estimator.expect_sendme(sent);
310
            estimator
311
                .update(sendme_received, &state, &cwnd)
312
                .expect("Error on RTT update");
313
            assert_eq!(
314
                estimator.last_rtt,
315
                Some(Duration::from_micros(self.last_rtt_usec_out))
316
            );
317
            assert_eq!(
318
                estimator.ewma_rtt,
319
                Some(Duration::from_micros(self.ewma_rtt_usec_out))
320
            );
321
            assert_eq!(
322
                estimator.min_rtt,
323
                Some(Duration::from_micros(self.min_rtt_usec_out))
324
            );
325
        }
326
    }
327

            
328
    #[test]
329
    fn test_vectors() {
330
        let mut rtt = new_rtt_estimator();
331
        let now = Instant::now();
332
        // from C-tor src/test/test_congestion_control.c
333
        let vectors = [
334
            [100000, 200000, 124, 1, 100000, 100000, 100000],
335
            [200000, 300000, 124, 1, 100000, 100000, 100000],
336
            [350000, 500000, 124, 1, 150000, 133333, 100000],
337
            [500000, 550000, 124, 1, 50000, 77777, 77777],
338
            [600000, 700000, 124, 1, 100000, 92592, 77777],
339
            [700000, 750000, 124, 1, 50000, 64197, 64197],
340
            [750000, 875000, 124, 0, 125000, 104732, 104732],
341
            [875000, 900000, 124, 0, 25000, 51577, 104732],
342
            [900000, 950000, 200, 0, 50000, 50525, 50525],
343
        ];
344
        for vect in vectors {
345
            let vect = RttTestSample::from(vect);
346
            eprintln!("Testing vector: {:?}", vect);
347
            vect.test(&mut rtt, now);
348
        }
349
    }
350
}