From 8fe798de6d959c8ccc812a82b50b95a836d29a06 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Sun, 21 Jul 2024 18:56:41 +0300 Subject: [PATCH] Kernel: Make PIT counter atomic with spinlock --- kernel/include/kernel/Timer/PIT.h | 5 ++++- kernel/kernel/Timer/PIT.cpp | 17 +++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/kernel/include/kernel/Timer/PIT.h b/kernel/include/kernel/Timer/PIT.h index b8a57b5166..26b7f7329c 100644 --- a/kernel/include/kernel/Timer/PIT.h +++ b/kernel/include/kernel/Timer/PIT.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace Kernel @@ -19,9 +20,11 @@ namespace Kernel private: void initialize(); + uint64_t read_counter() const; private: - volatile uint64_t m_system_time { 0 }; + mutable SpinLock m_lock; + uint64_t m_system_time { 0 }; }; } diff --git a/kernel/kernel/Timer/PIT.cpp b/kernel/kernel/Timer/PIT.cpp index 182d0dcd0a..f4419c8840 100644 --- a/kernel/kernel/Timer/PIT.cpp +++ b/kernel/kernel/Timer/PIT.cpp @@ -54,23 +54,32 @@ namespace Kernel void PIT::handle_irq() { - m_system_time = m_system_time + 1; + { + SpinLockGuard _(m_lock); + m_system_time++; + } Kernel::Scheduler::get().timer_reschedule(); } + uint64_t PIT::read_counter() const + { + SpinLockGuard _(m_lock); + return m_system_time; + } + uint64_t PIT::ms_since_boot() const { - return m_system_time * (MS_PER_S / TICKS_PER_SECOND); + return read_counter() * (MS_PER_S / TICKS_PER_SECOND); } uint64_t PIT::ns_since_boot() const { - return m_system_time * (NS_PER_S / TICKS_PER_SECOND); + return read_counter() * (NS_PER_S / TICKS_PER_SECOND); } timespec PIT::time_since_boot() const { - uint64_t ticks = m_system_time; + uint64_t ticks = read_counter(); return timespec { .tv_sec = ticks / TICKS_PER_SECOND, .tv_nsec = (long)((ticks % TICKS_PER_SECOND) * (NS_PER_S / TICKS_PER_SECOND))