menios icon indicating copy to clipboard operation
menios copied to clipboard

Centralized timekeeper abstraction

Open pbalduino opened this issue 3 months ago • 0 comments

Goal

Create a dedicated timekeeper structure to centralize time management logic.

Context

The TSC helper currently acts as the "timekeeper", but time logic is scattered across tsc.c and syscall code. Issue #226 expects a proper timekeeper abstraction.

Current State

  • Time tracking is fragmented across multiple files
  • No clear distinction between monotonic time (uptime) and wall-clock time
  • Timekeeper logic embedded in TSC-specific code

What's Needed

Implement the timekeeper structure from #226:

// Kernel timekeeping structure
struct timekeeper {
    time_t boot_time;           // System boot time (seconds since epoch)
    uint64_t ticks_since_boot;  // Timer ticks since boot
    uint32_t tick_frequency;    // Ticks per second (usually 100 Hz)
    time_t current_time;        // Current time (seconds since epoch)
    uint64_t current_nsec;      // Nanoseconds component
    spinlock_t lock;            // Protect time updates
};

// Time conversion and management
void time_init(void);
void time_update_from_rtc(void);
void time_tick(void);  // Called on each timer interrupt
time_t get_current_time(void);
int get_current_timespec(struct timespec *ts);
int get_current_timeval(struct timeval *tv);
void set_system_time(time_t seconds);
uint64_t get_uptime_ticks(void);
uint64_t get_uptime_seconds(void);

Benefits

  • Clear separation of concerns
  • Easy to support multiple time sources (TSC, HPET, APIC)
  • Unified interface for all time queries
  • Better lock granularity
  • Easier testing and debugging

Implementation Strategy

  1. Create src/kernel/time/timekeeper.c
  2. Define global timekeeper instance
  3. Migrate time logic from tsc.c and syscall handlers
  4. Update all time syscalls to use timekeeper API
  5. Add proper locking for concurrent access

Files to Create/Modify

  • src/kernel/time/timekeeper.c (new)
  • include/kernel/time.h (new header)
  • src/kernel/timer/tsc.c (refactor)
  • src/kernel/syscall/syscall.c (use timekeeper API)
  • src/kernel/init/main.c (initialize timekeeper)

Testing

  • Unit tests for timekeeper operations
  • Concurrent time query stress test
  • Verify monotonic time never goes backwards
  • Check nanosecond precision accuracy

Dependencies

  • #286 - Kernel RTC driver (✅ complete)
  • #325 - RTC boot-time synchronization (new)

Parent Issue

  • #226 - RTC and time management

pbalduino avatar Oct 20 '25 15:10 pbalduino