Extract shared code from timer

This commit is contained in:
YanWQ-monad
2024-09-24 21:01:34 +08:00
committed by Tate, Hongliang Tian
parent c4cb0f1aef
commit 839c2a6689
12 changed files with 47 additions and 38 deletions

45
ostd/src/timer/jiffies.rs Normal file
View File

@ -0,0 +1,45 @@
// SPDX-License-Identifier: MPL-2.0
use core::{
sync::atomic::{AtomicU64, Ordering},
time::Duration,
};
use crate::arch::timer::TIMER_FREQ;
/// Jiffies is a term used to denote the units of time measurement by the kernel.
///
/// A jiffy represents one tick of the system timer interrupt,
/// whose frequency is equal to [`TIMER_FREQ`] Hz.
#[derive(Copy, Clone, Debug)]
pub struct Jiffies(u64);
pub(crate) static ELAPSED: AtomicU64 = AtomicU64::new(0);
impl Jiffies {
/// Creates a new instance.
pub fn new(value: u64) -> Self {
Self(value)
}
/// Returns the elapsed time since the system boots up.
pub fn elapsed() -> Self {
Self::new(ELAPSED.load(Ordering::Relaxed))
}
/// Gets the number of jiffies.
pub fn as_u64(self) -> u64 {
self.0
}
/// Gets the [`Duration`] calculated from the jiffies counts.
pub fn as_duration(self) -> Duration {
Duration::from_millis(self.0 * 1000 / TIMER_FREQ)
}
}
impl From<Jiffies> for Duration {
fn from(value: Jiffies) -> Self {
value.as_duration()
}
}

30
ostd/src/timer/mod.rs Normal file
View File

@ -0,0 +1,30 @@
// SPDX-License-Identifier: MPL-2.0
//! The timer support.
pub(crate) mod jiffies;
use alloc::{boxed::Box, vec::Vec};
use core::cell::RefCell;
pub use jiffies::Jiffies;
use crate::{cpu_local, trap};
type InterruptCallback = Box<dyn Fn() + Sync + Send>;
cpu_local! {
pub(crate) static INTERRUPT_CALLBACKS: RefCell<Vec<InterruptCallback>> = RefCell::new(Vec::new());
}
/// Register a function that will be executed during the system timer interruption.
pub fn register_callback<F>(func: F)
where
F: Fn() + Sync + Send + 'static,
{
let irq_guard = trap::disable_local();
INTERRUPT_CALLBACKS
.get_with(&irq_guard)
.borrow_mut()
.push(Box::new(func));
}