| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::{ |
| 8 |
cell::RefCell, |
| 9 |
rc::{Rc, Weak}, |
| 10 |
time::Duration, |
| 11 |
}; |
| 12 |
|
| 13 |
#[cfg(windows)] |
| 14 |
use windows::Win32::Media::{timeBeginPeriod, timeEndPeriod}; |
| 15 |
|
| 16 |
/// A quantized `Duration`. This currently just produces 16 discrete values |
| 17 |
/// corresponding to whole milliseconds. Future implementations might choose |
| 18 |
/// a different allocation, such as a logarithmic scale. |
| 19 |
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 20 |
struct Period(u8); |
| 21 |
|
| 22 |
impl Period { |
| 23 |
const MAX: Self = Self(16); |
| 24 |
const MIN: Self = Self(1); |
| 25 |
|
| 26 |
#[cfg(windows)] |
| 27 |
fn as_u32(self) -> u32 { |
| 28 |
u32::from(self.0) |
| 29 |
} |
| 30 |
|
| 31 |
#[cfg(target_os = "macos")] |
| 32 |
fn scaled(self, scale: f64) -> f64 { |
| 33 |
scale * f64::from(self.0) |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
impl From<Duration> for Period { |
| 38 |
fn from(p: Duration) -> Self { |
| 39 |
let rounded = u8::try_from(p.as_millis()).unwrap_or(Self::MAX.0); |
| 40 |
Self(rounded.clamp(Self::MIN.0, Self::MAX.0)) |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
/// This counts instances of `Period`, except those of `Period::MAX`. |
| 45 |
#[derive(Default)] |
| 46 |
struct PeriodSet { |
| 47 |
counts: [usize; (Period::MAX.0 - Period::MIN.0) as usize], |
| 48 |
} |
| 49 |
|
| 50 |
impl PeriodSet { |
| 51 |
fn idx(&mut self, p: Period) -> &mut usize { |
| 52 |
debug_assert!(p >= Period::MIN); |
| 53 |
&mut self.counts[usize::from(p.0 - Period::MIN.0)] |
| 54 |
} |
| 55 |
|
| 56 |
fn add(&mut self, p: Period) { |
| 57 |
if p != Period::MAX { |
| 58 |
*self.idx(p) += 1; |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
fn remove(&mut self, p: Period) { |
| 63 |
if p != Period::MAX { |
| 64 |
let p = self.idx(p); |
| 65 |
debug_assert_ne!(*p, 0); |
| 66 |
*p -= 1; |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
fn min(&self) -> Option<Period> { |
| 71 |
for (i, v) in self.counts.iter().enumerate() { |
| 72 |
if *v > 0 { |
| 73 |
return Some(Period(u8::try_from(i).ok()? + Period::MIN.0)); |
| 74 |
} |
| 75 |
} |
| 76 |
None |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
#[cfg(target_os = "macos")] |
| 81 |
#[expect(non_camel_case_types, reason = "These are C types.")] |
| 82 |
mod mac { |
| 83 |
use std::ptr::addr_of_mut; |
| 84 |
|
| 85 |
// These are manually extracted from the many bindings generated |
| 86 |
// by bindgen when provided with the simple header: |
| 87 |
// #include <mach/mach_init.h> |
| 88 |
// #include <mach/mach_time.h> |
| 89 |
// #include <mach/thread_policy.h> |
| 90 |
// #include <pthread.h> |
| 91 |
|
| 92 |
type __darwin_natural_t = ::std::os::raw::c_uint; |
| 93 |
type __darwin_mach_port_name_t = __darwin_natural_t; |
| 94 |
type __darwin_mach_port_t = __darwin_mach_port_name_t; |
| 95 |
type mach_port_t = __darwin_mach_port_t; |
| 96 |
type thread_t = mach_port_t; |
| 97 |
type natural_t = __darwin_natural_t; |
| 98 |
type thread_policy_flavor_t = natural_t; |
| 99 |
type integer_t = ::std::os::raw::c_int; |
| 100 |
type thread_policy_t = *mut integer_t; |
| 101 |
type mach_msg_type_number_t = natural_t; |
| 102 |
type boolean_t = ::std::os::raw::c_uint; |
| 103 |
type kern_return_t = ::std::os::raw::c_int; |
| 104 |
|
| 105 |
#[repr(C)] |
| 106 |
#[derive(Debug, Copy, Clone, Default)] |
| 107 |
struct mach_timebase_info { |
| 108 |
numer: u32, |
| 109 |
denom: u32, |
| 110 |
} |
| 111 |
type mach_timebase_info_t = *mut mach_timebase_info; |
| 112 |
type mach_timebase_info_data_t = mach_timebase_info; |
| 113 |
extern "C" { |
| 114 |
fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t; |
| 115 |
} |
| 116 |
|
| 117 |
#[repr(C)] |
| 118 |
#[derive(Debug, Copy, Clone, Default)] |
| 119 |
pub struct thread_time_constraint_policy { |
| 120 |
period: u32, |
| 121 |
computation: u32, |
| 122 |
constraint: u32, |
| 123 |
preemptible: boolean_t, |
| 124 |
} |
| 125 |
|
| 126 |
const THREAD_TIME_CONSTRAINT_POLICY: thread_policy_flavor_t = 2; |
| 127 |
#[expect(clippy::cast_possible_truncation, reason = "These are C types.")] |
| 128 |
const THREAD_TIME_CONSTRAINT_POLICY_COUNT: mach_msg_type_number_t = |
| 129 |
(size_of::<thread_time_constraint_policy>() / size_of::<integer_t>()) |
| 130 |
as mach_msg_type_number_t; |
| 131 |
|
| 132 |
// These function definitions are taken from a comment in <thread_policy.h>. |
| 133 |
// Why they are inaccessible is unknown, but they work as declared. |
| 134 |
extern "C" { |
| 135 |
fn thread_policy_set( |
| 136 |
thread: thread_t, |
| 137 |
flavor: thread_policy_flavor_t, |
| 138 |
policy_info: thread_policy_t, |
| 139 |
count: mach_msg_type_number_t, |
| 140 |
) -> kern_return_t; |
| 141 |
fn thread_policy_get( |
| 142 |
thread: thread_t, |
| 143 |
flavor: thread_policy_flavor_t, |
| 144 |
policy_info: thread_policy_t, |
| 145 |
count: *mut mach_msg_type_number_t, |
| 146 |
get_default: *mut boolean_t, |
| 147 |
) -> kern_return_t; |
| 148 |
} |
| 149 |
|
| 150 |
enum _opaque_pthread_t {} // An opaque type is fine here. |
| 151 |
type __darwin_pthread_t = *mut _opaque_pthread_t; |
| 152 |
type pthread_t = __darwin_pthread_t; |
| 153 |
|
| 154 |
extern "C" { |
| 155 |
fn pthread_self() -> pthread_t; |
| 156 |
fn pthread_mach_thread_np(thread: pthread_t) -> mach_port_t; |
| 157 |
} |
| 158 |
|
| 159 |
/// Set a thread time policy. |
| 160 |
pub fn set_thread_policy(mut policy: thread_time_constraint_policy) { |
| 161 |
_ = unsafe { |
| 162 |
thread_policy_set( |
| 163 |
pthread_mach_thread_np(pthread_self()), |
| 164 |
THREAD_TIME_CONSTRAINT_POLICY, |
| 165 |
addr_of_mut!(policy).cast(), // horror! |
| 166 |
THREAD_TIME_CONSTRAINT_POLICY_COUNT, |
| 167 |
) |
| 168 |
}; |
| 169 |
} |
| 170 |
|
| 171 |
pub fn get_scale() -> f64 { |
| 172 |
const NANOS_PER_MSEC: f64 = 1_000_000.0; |
| 173 |
let mut timebase_info = mach_timebase_info_data_t::default(); |
| 174 |
unsafe { |
| 175 |
mach_timebase_info(&mut timebase_info); |
| 176 |
} |
| 177 |
f64::from(timebase_info.denom) * NANOS_PER_MSEC / f64::from(timebase_info.numer) |
| 178 |
} |
| 179 |
|
| 180 |
/// Create a realtime policy and set it. |
| 181 |
pub fn set_realtime(base: f64) { |
| 182 |
#[expect( |
| 183 |
clippy::cast_possible_truncation, |
| 184 |
clippy::cast_sign_loss, |
| 185 |
reason = "These are C types." |
| 186 |
)] |
| 187 |
let policy = thread_time_constraint_policy { |
| 188 |
period: base as u32, // Base interval |
| 189 |
computation: (base * 0.5) as u32, |
| 190 |
constraint: (base * 1.0) as u32, |
| 191 |
preemptible: 1, |
| 192 |
}; |
| 193 |
set_thread_policy(policy); |
| 194 |
} |
| 195 |
|
| 196 |
/// Get the default policy. |
| 197 |
pub fn get_default_policy() -> thread_time_constraint_policy { |
| 198 |
let mut policy = thread_time_constraint_policy::default(); |
| 199 |
let mut count = THREAD_TIME_CONSTRAINT_POLICY_COUNT; |
| 200 |
let mut get_default = 0; |
| 201 |
_ = unsafe { |
| 202 |
thread_policy_get( |
| 203 |
pthread_mach_thread_np(pthread_self()), |
| 204 |
THREAD_TIME_CONSTRAINT_POLICY, |
| 205 |
addr_of_mut!(policy).cast(), // horror! |
| 206 |
&mut count, |
| 207 |
&mut get_default, |
| 208 |
) |
| 209 |
}; |
| 210 |
policy |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
/// A handle for a high-resolution timer of a specific period. |
| 215 |
pub struct Handle { |
| 216 |
hrt: Rc<RefCell<Time>>, |
| 217 |
active: Period, |
| 218 |
hysteresis: [Period; Self::HISTORY], |
| 219 |
hysteresis_index: usize, |
| 220 |
} |
| 221 |
|
| 222 |
impl Handle { |
| 223 |
const HISTORY: usize = 8; |
| 224 |
|
| 225 |
const fn new(hrt: Rc<RefCell<Time>>, active: Period) -> Self { |
| 226 |
Self { |
| 227 |
hrt, |
| 228 |
active, |
| 229 |
hysteresis: [Period::MAX; Self::HISTORY], |
| 230 |
hysteresis_index: 0, |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
/// Update shortcut. Equivalent to dropping the current reference and |
| 235 |
/// calling `HrTime::get` again with the new period, except that this applies |
| 236 |
/// a little hysteresis that smoothes out fluctuations. |
| 237 |
pub fn update(&mut self, period: Duration) { |
| 238 |
self.hysteresis[self.hysteresis_index] = Period::from(period); |
| 239 |
self.hysteresis_index += 1; |
| 240 |
self.hysteresis_index %= self.hysteresis.len(); |
| 241 |
|
| 242 |
let mut first = Period::MAX; |
| 243 |
let mut second = Period::MAX; |
| 244 |
for i in &self.hysteresis { |
| 245 |
if *i < first { |
| 246 |
second = first; |
| 247 |
first = *i; |
| 248 |
} else if *i < second { |
| 249 |
second = *i; |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
if second != self.active { |
| 254 |
let mut b = self.hrt.borrow_mut(); |
| 255 |
b.periods.remove(self.active); |
| 256 |
self.active = second; |
| 257 |
b.periods.add(self.active); |
| 258 |
b.update(); |
| 259 |
} |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
impl Drop for Handle { |
| 264 |
fn drop(&mut self) { |
| 265 |
self.hrt.borrow_mut().remove(self.active); |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
/// Holding an instance of this indicates that high resolution timers are enabled. |
| 270 |
pub struct Time { |
| 271 |
periods: PeriodSet, |
| 272 |
active: Option<Period>, |
| 273 |
|
| 274 |
#[cfg(target_os = "macos")] |
| 275 |
scale: f64, |
| 276 |
#[cfg(target_os = "macos")] |
| 277 |
deflt: mac::thread_time_constraint_policy, |
| 278 |
} |
| 279 |
impl Time { |
| 280 |
fn new() -> Self { |
| 281 |
Self { |
| 282 |
periods: PeriodSet::default(), |
| 283 |
active: None, |
| 284 |
|
| 285 |
#[cfg(target_os = "macos")] |
| 286 |
scale: mac::get_scale(), |
| 287 |
#[cfg(target_os = "macos")] |
| 288 |
deflt: mac::get_default_policy(), |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
#[cfg(target_os = "macos")] |
| 293 |
fn start(&self) { |
| 294 |
if let Some(p) = self.active { |
| 295 |
mac::set_realtime(p.scaled(self.scale)); |
| 296 |
} else { |
| 297 |
mac::set_thread_policy(self.deflt); |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
#[cfg(target_os = "windows")] |
| 302 |
fn start(&self) { |
| 303 |
if let Some(p) = self.active { |
| 304 |
_ = unsafe { timeBeginPeriod(p.as_u32()) }; |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))] |
| 309 |
#[expect( |
| 310 |
clippy::unused_self, |
| 311 |
reason = "Not used on platforms other than macOS and Windows." |
| 312 |
)] |
| 313 |
const fn start(&self) {} |
| 314 |
|
| 315 |
#[cfg(windows)] |
| 316 |
fn stop(&self) { |
| 317 |
if let Some(p) = self.active { |
| 318 |
_ = unsafe { timeEndPeriod(p.as_u32()) }; |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
#[cfg(not(target_os = "windows"))] |
| 323 |
#[expect( |
| 324 |
clippy::unused_self, |
| 325 |
reason = "Not used on platforms other than Windows." |
| 326 |
)] |
| 327 |
const fn stop(&self) {} |
| 328 |
|
| 329 |
fn update(&mut self) { |
| 330 |
let next = self.periods.min(); |
| 331 |
if next != self.active { |
| 332 |
self.stop(); |
| 333 |
self.active = next; |
| 334 |
self.start(); |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
fn add(&mut self, p: Period) { |
| 339 |
self.periods.add(p); |
| 340 |
self.update(); |
| 341 |
} |
| 342 |
|
| 343 |
fn remove(&mut self, p: Period) { |
| 344 |
self.periods.remove(p); |
| 345 |
self.update(); |
| 346 |
} |
| 347 |
|
| 348 |
/// Enable high resolution time. Returns a thread-bound handle that |
| 349 |
/// needs to be held until the high resolution time is no longer needed. |
| 350 |
/// The handle can also be used to update the resolution. |
| 351 |
#[must_use] |
| 352 |
pub fn get(period: Duration) -> Handle { |
| 353 |
thread_local!(static HR_TIME: RefCell<Weak<RefCell<Time>>> = RefCell::default()); |
| 354 |
|
| 355 |
HR_TIME.with(|r| { |
| 356 |
let mut b = r.borrow_mut(); |
| 357 |
let hrt = b.upgrade().unwrap_or_else(|| { |
| 358 |
let hrt = Rc::new(RefCell::new(Self::new())); |
| 359 |
*b = Rc::downgrade(&hrt); |
| 360 |
hrt |
| 361 |
}); |
| 362 |
|
| 363 |
let p = Period::from(period); |
| 364 |
hrt.borrow_mut().add(p); |
| 365 |
Handle::new(hrt, p) |
| 366 |
}) |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
impl Drop for Time { |
| 371 |
fn drop(&mut self) { |
| 372 |
self.stop(); |
| 373 |
|
| 374 |
#[cfg(target_os = "macos")] |
| 375 |
{ |
| 376 |
if self.active.is_some() { |
| 377 |
mac::set_thread_policy(self.deflt); |
| 378 |
} |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
// Only run these tests in CI on Linux, where the timer accuracies are OK enough to pass the tests, |
| 384 |
// but only when not running sanitizers. |
| 385 |
#[cfg(all(target_os = "linux", not(neqo_sanitize)))] |
| 386 |
#[cfg(test)] |
| 387 |
mod test { |
| 388 |
use std::{ |
| 389 |
thread::{sleep, spawn}, |
| 390 |
time::{Duration, Instant}, |
| 391 |
}; |
| 392 |
|
| 393 |
use super::Time; |
| 394 |
|
| 395 |
const ONE_MS: Duration = Duration::from_millis(1); |
| 396 |
const FIVE_MS: Duration = Duration::from_millis(5); |
| 397 |
const ONE_MS_AND_A_BIT: Duration = Duration::from_micros(1500); |
| 398 |
/// A limit for when high resolution timers are disabled. |
| 399 |
const GENEROUS: Duration = Duration::from_millis(30); |
| 400 |
|
| 401 |
fn validate_delays(max_lag: Duration) -> Result<(), ()> { |
| 402 |
const DELAYS: &[u64] = &[1, 2, 3, 5, 8, 10, 12, 15, 20, 25, 30]; |
| 403 |
let durations = DELAYS.iter().map(|&d| Duration::from_millis(d)); |
| 404 |
|
| 405 |
let mut s = Instant::now(); |
| 406 |
for d in durations { |
| 407 |
sleep(d); |
| 408 |
let e = Instant::now(); |
| 409 |
let actual = e.saturating_duration_since(s); |
| 410 |
let lag = actual.saturating_sub(d); |
| 411 |
println!("sleep({d:>4?}) \u{2192} {actual:>11.6?} \u{394}{lag:>10?}"); |
| 412 |
if lag > max_lag { |
| 413 |
return Err(()); |
| 414 |
} |
| 415 |
s = Instant::now(); |
| 416 |
} |
| 417 |
Ok(()) |
| 418 |
} |
| 419 |
|
| 420 |
/// Validate the delays multiple times. Sometimes a run can stall. |
| 421 |
/// Reliability in CI is more important than reliable timers. |
| 422 |
/// Any failure results in enqueing two additional checks, |
| 423 |
/// up to a limit that is determined based on how small `max_lag` is. |
| 424 |
/// If the count exceeds that limit, fail the test. |
| 425 |
fn check_delays(max_lag: Duration) { |
| 426 |
let max_loops = if max_lag < FIVE_MS { |
| 427 |
5 |
| 428 |
} else if max_lag < GENEROUS { |
| 429 |
3 |
| 430 |
} else { |
| 431 |
1 |
| 432 |
}; |
| 433 |
|
| 434 |
let mut count = 1; |
| 435 |
while count <= max_loops { |
| 436 |
if validate_delays(max_lag).is_ok() { |
| 437 |
count -= 1; |
| 438 |
} else { |
| 439 |
count += 1; |
| 440 |
} |
| 441 |
if count == 0 { |
| 442 |
return; |
| 443 |
} |
| 444 |
sleep(Duration::from_millis(50)); |
| 445 |
} |
| 446 |
panic!("timers slipped too often"); |
| 447 |
} |
| 448 |
|
| 449 |
/// Note that you have to run this test alone or other tests will |
| 450 |
/// grab the high resolution timer and this will run faster. |
| 451 |
#[test] |
| 452 |
fn baseline() { |
| 453 |
check_delays(GENEROUS); |
| 454 |
} |
| 455 |
|
| 456 |
#[test] |
| 457 |
fn one_ms() { |
| 458 |
let _hrt = Time::get(ONE_MS); |
| 459 |
check_delays(ONE_MS_AND_A_BIT); |
| 460 |
} |
| 461 |
|
| 462 |
#[test] |
| 463 |
fn multithread_baseline() { |
| 464 |
let thr = spawn(move || { |
| 465 |
baseline(); |
| 466 |
}); |
| 467 |
baseline(); |
| 468 |
thr.join().unwrap(); |
| 469 |
} |
| 470 |
|
| 471 |
#[test] |
| 472 |
fn one_ms_multi() { |
| 473 |
let thr = spawn(move || { |
| 474 |
one_ms(); |
| 475 |
}); |
| 476 |
one_ms(); |
| 477 |
thr.join().unwrap(); |
| 478 |
} |
| 479 |
|
| 480 |
#[test] |
| 481 |
fn mixed_multi() { |
| 482 |
let thr = spawn(move || { |
| 483 |
one_ms(); |
| 484 |
}); |
| 485 |
let _hrt = Time::get(Duration::from_millis(4)); |
| 486 |
check_delays(FIVE_MS); |
| 487 |
thr.join().unwrap(); |
| 488 |
} |
| 489 |
|
| 490 |
#[test] |
| 491 |
fn update() { |
| 492 |
let mut hrt = Time::get(Duration::from_millis(4)); |
| 493 |
check_delays(FIVE_MS); |
| 494 |
hrt.update(ONE_MS); |
| 495 |
check_delays(ONE_MS_AND_A_BIT); |
| 496 |
} |
| 497 |
|
| 498 |
#[cfg(not(target_arch = "arm"))] // This test is flaky on linux/arm. |
| 499 |
#[test] |
| 500 |
fn update_multi() { |
| 501 |
let thr = spawn(move || { |
| 502 |
update(); |
| 503 |
}); |
| 504 |
update(); |
| 505 |
thr.join().unwrap(); |
| 506 |
} |
| 507 |
|
| 508 |
#[test] |
| 509 |
fn max() { |
| 510 |
let _hrt = Time::get(Duration::from_secs(1)); |
| 511 |
check_delays(GENEROUS); |
| 512 |
} |
| 513 |
|
| 514 |
#[test] |
| 515 |
#[should_panic(expected = "timers slipped too often")] |
| 516 |
fn slip() { |
| 517 |
// This amount of timer resolution should be unachievable. |
| 518 |
check_delays(Duration::from_nanos(1)); |
| 519 |
} |
| 520 |
} |