aboutsummaryrefslogtreecommitdiffstats
path: root/src/protocol/timer.rs
blob: d2bcfcb3cf84527459d9808a8ee41f3fcab849d8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright 2017 Sopium

// This file is part of WireGuard.rs.

// WireGuard.rs is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.

// WireGuard.rs is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with WireGuard.rs.  If not, see <https://www.gnu.org/licenses/>.

use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
use std::time::{Duration, Instant};

type Action = Box<Fn() + Send + Sync>;

struct Timer {
    activated: AtomicBool,
    // Actually, this is not used outside the big whole wheel mutex.
    // But how to tell the compiler that???
    rounds: AtomicUsize,
    action: Action,
}

pub struct TimerHandle {
    controller: Arc<Mutex<Wheel>>,
    pos: AtomicUsize,
    timer: ArcTimer,
}

// A single round will be ~ 16 seconds.
// WireGuard timers are mostly in this range.
const WHEEL_SLOTS: usize = 128;
const TICK_MS: usize = 128;

// This is hashed timing wheel.
pub struct TimerController(Arc<Mutex<Wheel>>);

struct Wheel {
    // Usually a linked list is used in each slot.
    // Use hash table for now, for implementation simplicity.
    // It's slower but should still have same complexity.
    wheel: Vec<HashSet<ArcTimer>>,
    cur: usize,
}

impl TimerController {
    pub fn new() -> Self {
        let con = Arc::new(Mutex::new(Wheel {
            wheel: ::std::iter::repeat(HashSet::new()).take(WHEEL_SLOTS).collect(),
            cur: 0,
        }));
        let con1 = con.clone();

        thread::Builder::new().name("timer".to_string()).spawn(move || {
            loop {
                let tick_start = Instant::now();

                let mut to_run = Vec::new();
                let mut wheel = con.lock().unwrap();
                let cur = wheel.cur;
                wheel.cur = (wheel.cur + 1) % WHEEL_SLOTS;
                {
                    let slot = &mut wheel.wheel[cur];

                    slot.retain(|t| {
                        Arc::strong_count(&t.0) > 1
                    });

                    for t in slot.iter() {
                        // `fetch_sub` always wraps, doesn't it?
                        let rounds = t.rounds.fetch_sub(1, Ordering::Relaxed);
                        if t.activated.load(Ordering::Relaxed) && rounds == 0 {
                            to_run.push(t.clone());
                            t.activated.store(false, Ordering::Relaxed);
                        }
                    }
                }
                drop(wheel);

                for t in to_run {
                    (t.action)();
                }

                let spent = tick_start.elapsed();
                #[allow(non_snake_case)]
                let TICK = Duration::from_millis(TICK_MS as u64);

                if spent >= TICK {
                    warn!("timer tick processing time exceeds TICK!");
                } else {
                    thread::sleep(TICK - spent);
                }
            }
        }).unwrap();

        TimerController(con1)
    }

    pub fn register_delay(&self, delay: Duration, action: Action) -> TimerHandle {
        let (offset, rounds) = calc_offset_and_rounds(delay);

        let mut wheel = self.0.lock().unwrap();
        let pos = (wheel.cur + offset) % WHEEL_SLOTS;

        let timer = Arc::new(Timer {
            activated: AtomicBool::new(false),
            rounds: AtomicUsize::new(rounds),
            action: action,
        });

        wheel.wheel[pos].insert(ArcTimer(timer.clone()));

        TimerHandle {
            controller: self.0.clone(),
            pos: AtomicUsize::new(pos),
            timer: ArcTimer(timer),
        }
    }
}

impl TimerHandle {
    pub fn activate(&self) {
        self.timer.activated.store(true, Ordering::Relaxed);
    }

    pub fn de_activate(&self) {
        self.timer.activated.store(false, Ordering::Relaxed);
    }

    pub fn adjust_and_activate(&self, secs: u64) {
        let (offset, rounds) = calc_offset_and_rounds(Duration::from_secs(secs));

        let mut wheel = self.controller.lock().unwrap();
        let old_pos = self.pos.load(Ordering::Relaxed);
        let new_pos = (wheel.cur + offset) % WHEEL_SLOTS;
        self.pos.store(new_pos, Ordering::Relaxed);
        self.timer.rounds.store(rounds, Ordering::Relaxed);

        let t = wheel.wheel[old_pos].take(&self.timer).unwrap();
        wheel.wheel[new_pos].insert(t);

        self.timer.activated.store(true, Ordering::Release);
    }

    pub fn adjust_and_activate_if_not_activated(&self, secs: u64) {
        if !self.timer.activated.load(Ordering::Relaxed) {
            self.adjust_and_activate(secs);
        }
    }
}

fn calc_offset_and_rounds(delay: Duration) -> (usize, usize) {
    let delay_ms = delay.as_secs() * 1000 + delay.subsec_nanos() as u64 / 1000000;
    let ticks = ::std::cmp::max(delay_ms as usize / TICK_MS, 1);
    let offset = ticks % WHEEL_SLOTS;
    let rounds = ticks / WHEEL_SLOTS;
    (offset, rounds)
}

/// Hash and Eq by pointer address.
#[derive(Clone)]
struct ArcTimer(Arc<Timer>);

impl Deref for ArcTimer {
    type Target = Timer;

    fn deref(&self) -> &Timer {
        self.0.deref()
    }
}

impl Hash for ArcTimer {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (self.0.deref() as *const Timer).hash(state);
    }
}

impl PartialEq for ArcTimer {
    fn eq(&self, other: &ArcTimer) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for ArcTimer {
}