1use std::time::{Duration, Instant};
2
3pub(crate) const ACK_INTERVAL: u64 = 200;
4const MAX_INIT_RETRANS: usize = 8;
5const PATH_MAX_RETRANS: usize = 5;
6const ASSOCIATION_MAX_RETRANS: usize = 10;
8const NO_MAX_RETRANS: usize = usize::MAX;
9const TIMER_COUNT: usize = 9;
10
11#[derive(Debug, Copy, Clone)]
12pub struct TimerConfig {
17 pub max_t1_init_retrans: usize,
19 pub max_t1_cookie_retrans: usize,
21 pub max_t2_shutdown_retrans: usize,
26 pub max_t3_rtx_retrans: usize,
36 pub max_reconfig_retrans: usize,
43 pub max_ack_retrans: usize,
45}
46
47impl Default for TimerConfig {
48 fn default() -> Self {
49 Self {
50 max_t1_init_retrans: MAX_INIT_RETRANS,
51 max_t1_cookie_retrans: MAX_INIT_RETRANS,
52 max_t2_shutdown_retrans: ASSOCIATION_MAX_RETRANS,
53 max_t3_rtx_retrans: ASSOCIATION_MAX_RETRANS,
54 max_reconfig_retrans: PATH_MAX_RETRANS,
55 max_ack_retrans: PATH_MAX_RETRANS,
56 }
57 }
58}
59
60#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
61pub(crate) enum Timer {
62 T1Init = 0,
63 T1Cookie = 1,
64 T2Shutdown = 2,
65 T3RTX = 3,
66 Reconfig = 4,
67 Ack = 5,
68 HalfOpen = 6,
71 T5ShutdownGuard = 7,
74 Heartbeat = 8,
77}
78
79impl Timer {
80 pub(crate) const VALUES: [Self; TIMER_COUNT] = [
81 Timer::T1Init,
82 Timer::T1Cookie,
83 Timer::T2Shutdown,
84 Timer::T3RTX,
85 Timer::Reconfig,
86 Timer::Ack,
87 Timer::HalfOpen,
88 Timer::T5ShutdownGuard,
89 Timer::Heartbeat,
90 ];
91}
92
93#[derive(Debug, Copy, Clone, Default)]
95pub(crate) struct TimerTable {
96 data: [Option<Instant>; TIMER_COUNT],
97 retrans: [usize; TIMER_COUNT],
98 max_retrans: [usize; TIMER_COUNT],
99 shutdown_interval: Option<u64>,
100 reconfig_interval: Option<u64>,
101 rto_max: Option<u64>,
104 t1_follows_rto: bool,
107}
108
109impl TimerTable {
110 pub fn new(time_config: TimerConfig) -> Self {
111 TimerTable {
112 max_retrans: [
113 time_config.max_t1_init_retrans, time_config.max_t1_cookie_retrans, time_config.max_t2_shutdown_retrans, time_config.max_t3_rtx_retrans, time_config.max_reconfig_retrans, time_config.max_ack_retrans, 0, 0, NO_MAX_RETRANS, ],
123 ..Default::default()
124 }
125 }
126
127 pub fn with_rto_config(mut self, config: RtoConfig) -> Self {
129 let max = u64::try_from(config.max.as_millis())
130 .unwrap_or(u64::MAX)
131 .max(1);
132 self.rto_max = Some(max);
133 self
134 }
135
136 pub fn with_t1_following_rto(mut self, value: bool) -> Self {
140 self.t1_follows_rto = value;
141 self
142 }
143
144 fn backoff(&self, interval: u64, n_rtos: usize) -> u64 {
145 calculate_next_timeout(interval, n_rtos, self.rto_max.unwrap_or(RTO_MAX))
146 }
147
148 pub fn set(&mut self, timer: Timer, time: Option<Instant>) {
149 self.data[timer as usize] = time;
150 }
151
152 pub fn get(&self, timer: Timer) -> Option<Instant> {
153 self.data[timer as usize]
154 }
155
156 pub fn next_timeout(&self) -> Option<Instant> {
157 self.data.iter().filter_map(|&x| x).min()
158 }
159
160 fn control_interval(&mut self, timer: Timer) -> Option<&mut Option<u64>> {
161 match timer {
162 Timer::T2Shutdown => Some(&mut self.shutdown_interval),
163 Timer::Reconfig => Some(&mut self.reconfig_interval),
164 _ => None,
165 }
166 }
167
168 pub fn start(&mut self, timer: Timer, now: Instant, interval: u64) {
169 let interval = if let Some(current) = self.control_interval(timer) {
172 *current.get_or_insert(interval)
177 } else if matches!(
178 timer,
179 Timer::Ack | Timer::T3RTX | Timer::HalfOpen | Timer::T5ShutdownGuard
180 ) || (self.t1_follows_rto && matches!(timer, Timer::T1Init | Timer::T1Cookie))
181 {
182 interval
185 } else {
186 self.backoff(interval, self.retrans[timer as usize])
187 };
188
189 let time = now + Duration::from_millis(interval);
190 self.data[timer as usize] = Some(time);
191 }
192
193 pub fn start_if_idle(&mut self, timer: Timer, now: Instant, interval: u64) {
198 if self.data[timer as usize].is_none() {
199 self.start(timer, now, interval);
200 }
201 }
202
203 pub fn stop(&mut self, timer: Timer) {
204 self.data[timer as usize] = None;
205 self.reset_retrans(timer);
206 if let Some(interval) = self.control_interval(timer) {
207 *interval = None;
208 }
209 }
210
211 pub fn count_error(&mut self, timer: Timer) -> bool {
215 self.retrans[timer as usize] = self.retrans[timer as usize].saturating_add(1);
216 self.retrans[timer as usize] > self.max_retrans[timer as usize]
217 }
218
219 pub fn max_retrans(&self, timer: Timer) -> usize {
221 self.max_retrans[timer as usize]
222 }
223
224 pub fn reset_retrans(&mut self, timer: Timer) {
225 self.retrans[timer as usize] = 0;
226 }
227
228 pub fn is_expired(&mut self, timer: Timer, after: Instant) -> (bool, bool, usize) {
229 let expired = self.data[timer as usize].is_some_and(|x| x <= after);
230 let mut failure = false;
231 let rto_max = self.rto_max.unwrap_or(RTO_MAX);
232 if expired && let Some(interval) = self.control_interval(timer) {
233 *interval = interval.map(|previous| calculate_next_timeout(previous, 1, rto_max));
234 }
235 if expired {
236 self.retrans[timer as usize] += 1;
237 if self.retrans[timer as usize] > self.max_retrans[timer as usize] {
238 failure = true;
239 }
240 }
241
242 (expired, failure, self.retrans[timer as usize])
243 }
244}
245
246const RTO_INITIAL: u64 = 1000; const RTO_MIN: u64 = 1000; const RTO_MAX: u64 = 60000; const CLOCK_GRANULARITY: f64 = 1.0;
253const RTO_ALPHA: u64 = 1;
254const RTO_BETA: u64 = 2;
255const RTO_BASE: u64 = 8;
256
257#[derive(Debug, Copy, Clone, PartialEq, Eq)]
260pub struct RtoConfig {
261 pub initial: Duration,
263 pub min: Duration,
265 pub max: Duration,
267}
268
269impl Default for RtoConfig {
270 fn default() -> Self {
271 Self {
272 initial: Duration::from_millis(RTO_INITIAL),
273 min: Duration::from_millis(RTO_MIN),
274 max: Duration::from_millis(RTO_MAX),
275 }
276 }
277}
278
279#[derive(Debug)]
282pub(crate) struct RtoManager {
283 pub(crate) srtt: u64,
284 pub(crate) rttvar: f64,
285 pub(crate) rto: u64,
286 pub(crate) no_update: bool,
287 initial: u64,
289 min: u64,
290 max: u64,
291}
292
293impl Default for RtoManager {
294 fn default() -> Self {
295 RtoManager {
296 srtt: 0,
297 rttvar: 0.0,
298 rto: 0,
299 no_update: false,
300 initial: RTO_INITIAL,
301 min: RTO_MIN,
302 max: RTO_MAX,
303 }
304 }
305}
306
307impl RtoManager {
308 pub(crate) fn new() -> Self {
310 Self::with_config(RtoConfig::default())
311 }
312
313 pub(crate) fn with_config(config: RtoConfig) -> Self {
316 let millis = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1);
317 let min = millis(config.min);
318 let max = millis(config.max).max(min);
319 let initial = millis(config.initial).clamp(min, max);
320 RtoManager {
321 rto: initial,
322 initial,
323 min,
324 max,
325 ..Default::default()
326 }
327 }
328
329 pub(crate) fn set_new_rtt(&mut self, rtt: u64) -> u64 {
331 if self.no_update {
332 return self.srtt;
333 }
334
335 if self.srtt == 0 {
336 self.srtt = rtt;
338 self.rttvar = rtt as f64 / 2.0;
339 } else {
340 self.rttvar = ((RTO_BASE - RTO_BETA) as f64 * self.rttvar
342 + RTO_BETA as f64 * (self.srtt as i64 - rtt as i64).abs() as f64)
343 / RTO_BASE as f64;
344 self.srtt = ((RTO_BASE - RTO_ALPHA) * self.srtt + RTO_ALPHA * rtt) / RTO_BASE;
345 }
346
347 if self.rttvar == 0.0 {
350 self.rttvar = CLOCK_GRANULARITY;
351 }
352
353 self.rto = (self.srtt + (4.0 * self.rttvar) as u64).clamp(self.min, self.max);
354
355 self.srtt
356 }
357
358 pub(crate) fn get_rto(&self) -> u64 {
360 self.rto
361 }
362
363 pub(crate) fn backoff(&mut self) {
365 if !self.no_update {
366 self.rto = self.rto.saturating_mul(2).min(self.max);
367 }
368 }
369
370 pub(crate) fn reset(&mut self) {
372 if self.no_update {
373 return;
374 }
375
376 self.srtt = 0;
377 self.rttvar = 0.0;
378 self.rto = self.initial;
379 }
380
381 pub(crate) fn set_rto(&mut self, rto: u64, no_update: bool) {
383 self.rto = rto;
384 self.no_update = no_update;
385 }
386}
387
388fn calculate_next_timeout(rto: u64, n_rtos: usize, rto_max: u64) -> u64 {
389 if n_rtos < 31 {
395 std::cmp::min(rto << n_rtos, rto_max)
396 } else {
397 rto_max
398 }
399}
400
401#[cfg(test)]
402#[path = "timer_test.rs"]
403mod timer_test;
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn rto_backoff_respects_pinned_rto() {
411 let mut rto = RtoManager::new();
412 rto.set_rto(1000, true);
413 rto.backoff();
414 assert_eq!(1000, rto.get_rto());
415 rto.set_rto(1000, false);
416 rto.backoff();
417 assert_eq!(2000, rto.get_rto());
418 rto.set_rto(RTO_MAX - 1, false);
419 rto.backoff();
420 assert_eq!(RTO_MAX, rto.get_rto());
421 }
422
423 #[test]
424 fn rto_manager_uses_rfc9260_initial_rto() {
425 assert_eq!(RTO_INITIAL, 1000);
426 assert_eq!(RtoManager::new().get_rto(), RTO_INITIAL);
427 }
428
429 #[test]
430 fn t1_init_starts_at_initial_rto_before_an_rtt_is_measured() {
431 let now = Instant::now();
432 let mut timers = TimerTable::new(TimerConfig::default());
433
434 timers.start(Timer::T1Init, now, RtoManager::new().get_rto());
435
436 assert_eq!(timers.next_timeout(), Some(now + Duration::from_secs(1)));
437 }
438
439 #[test]
440 fn control_backoff_uses_one_interval_until_stopped() {
441 for timer in [Timer::T2Shutdown, Timer::Reconfig] {
442 let mut timers = TimerTable::new(TimerConfig {
443 max_reconfig_retrans: usize::MAX,
444 ..TimerConfig::default()
445 });
446 let mut now = Instant::now();
447 timers.start(timer, now, 8000);
450 assert_eq!(Some(now + Duration::from_secs(8)), timers.get(timer));
451 for interval in [16, 32, 60, 60] {
452 now = timers.get(timer).unwrap();
453 assert_eq!((true, false), {
454 let (expired, failed, _) = timers.is_expired(timer, now);
455 (expired, failed)
456 });
457 timers.set(timer, None);
458 for data_rto in [60_000, 1000] {
459 timers.start(timer, now, data_rto);
460 assert_eq!(Some(now + Duration::from_secs(interval)), timers.get(timer));
461 }
462 }
463 timers.stop(timer);
464 timers.start(timer, now, 3000);
465 assert_eq!(Some(now + Duration::from_secs(3)), timers.get(timer));
466 assert_eq!((false, false, 0), timers.is_expired(timer, now));
467 }
468 }
469}