kernel/
time.rs

1//! Time utilities for the kernel
2//! 
3//! This module provides time-related functionality for the kernel,
4//! including current time access for filesystem operations.
5
6use crate::timer::get_kernel_timer;
7
8/// Get the current time in microseconds
9/// 
10/// This function returns the current system time in microseconds since boot.
11/// For filesystem operations, this provides a monotonic timestamp.
12pub fn current_time() -> u64 {
13    // For now, use CPU 0's timer. In a multi-core system, this might need
14    // to be more sophisticated to get a consistent global timestamp.
15    get_kernel_timer().get_time_us(0)
16}
17
18/// Get the current time in milliseconds
19pub fn current_time_ms() -> u64 {
20    current_time() / 1000
21}
22
23/// Get the current time in seconds
24pub fn current_time_s() -> u64 {
25    current_time() / 1_000_000
26}
27
28/// Convert microseconds to a human-readable format (for debugging)
29pub fn format_time_us(time_us: u64) -> (u64, u64, u64) {
30    let seconds = time_us / 1_000_000;
31    let minutes = seconds / 60;
32    let hours = minutes / 60;
33    
34    (hours, minutes % 60, seconds % 60)
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test_case]
42    fn test_time_functions() {
43        let time1 = current_time();
44        let time2 = current_time();
45        
46        // Time should be monotonic (non-decreasing)
47        assert!(time2 >= time1);
48        
49        // Test conversions
50        let time_ms = current_time_ms();
51        let time_s = current_time_s();
52        
53        assert!(time_ms <= time1 / 1000 + 1); // Allow for small timing differences
54        assert!(time_s <= time1 / 1_000_000 + 1);
55    }
56
57    #[test_case]
58    fn test_format_time() {
59        let (hours, minutes, seconds) = format_time_us(3_661_000_000); // 1 hour, 1 minute, 1 second
60        assert_eq!(hours, 1);
61        assert_eq!(minutes, 1);
62        assert_eq!(seconds, 1);
63        
64        let (hours, minutes, seconds) = format_time_us(123_000_000); // 2 minutes, 3 seconds
65        assert_eq!(hours, 0);
66        assert_eq!(minutes, 2);
67        assert_eq!(seconds, 3);
68    }
69}