12#include "stk_config.h"
14#ifdef _STK_ARCH_X86_WIN32
21#define WIN32_LEAN_AND_MEAN
32#define WINAPI __stdcall
36typedef MMRESULT (WINAPI * timeBeginPeriodF)(UINT uPeriod);
37static timeBeginPeriodF timeBeginPeriod =
nullptr;
39#define STK_X86_WIN32_CRITICAL_SECTION CRITICAL_SECTION
40#define STK_X86_WIN32_CRITICAL_SECTION_INIT(SES) ::InitializeCriticalSection(SES)
41#define STK_X86_WIN32_CRITICAL_SECTION_START(SES) ::EnterCriticalSection(SES)
42#define STK_X86_WIN32_CRITICAL_SECTION_END(SES) ::LeaveCriticalSection(SES)
43#define STK_X86_WIN32_MIN_RESOLUTION (1000)
44#define STK_X86_WIN32_GET_SP(STACK) (STACK + 2)
45#define SLK_UNLOCKED hw::SpinLock::UNLOCKED
46#define SLK_LOCKED hw::SpinLock::LOCKED
52 return (InterlockedCompareExchange(
53 reinterpret_cast<volatile LONG *
>(&lock), SLK_LOCKED, SLK_UNLOCKED) == SLK_UNLOCKED);
60 uint8_t sleep_time = 0;
61 uint32_t timeout = 0xFFFFFF;
64 while (!HW_SpinLockTryLock(lock))
72 for (
volatile int32_t spin = 100; (spin != 0); spin--)
77 if (lock == SLK_UNLOCKED)
91 InterlockedExchange(
reinterpret_cast<volatile LONG *
>(&lock), SLK_UNLOCKED);
94struct Win32ScopedCriticalSection
96 STK_X86_WIN32_CRITICAL_SECTION &m_sec;
98 explicit Win32ScopedCriticalSection(STK_X86_WIN32_CRITICAL_SECTION &sec) : m_sec(sec)
100 STK_X86_WIN32_CRITICAL_SECTION_START(&sec);
102 ~Win32ScopedCriticalSection()
104 STK_X86_WIN32_CRITICAL_SECTION_END(&m_sec);
110 LARGE_INTEGER m_freq;
111 LARGE_INTEGER m_start;
114 explicit HiResClockQPC()
116 QueryPerformanceFrequency(&m_freq);
117 QueryPerformanceCounter(&m_start);
120 static HiResClockQPC *GetInstance()
124 static HiResClockQPC clock;
130 LARGE_INTEGER current;
131 QueryPerformanceCounter(¤t);
134 return static_cast<Cycles>(current.QuadPart - m_start.QuadPart);
137 uint32_t GetFrequency()
139 return static_cast<uint32_t
>(m_freq.QuadPart);
147 : m_overrider(nullptr),
148 m_sleep_trap(nullptr),
149 m_exit_trap(nullptr),
150 m_winmm_dll(nullptr),
151 m_timer_thread(nullptr),
152 m_tls(TLS_OUT_OF_INDEXES),
156 #if STK_TICKLESS_IDLE
165 void Initialize(IPlatform::IEventHandler *handler, IKernelService *service, Stack *exit_trap,
166 uint32_t resolution_us)
override
168 PlatformContext::Initialize(handler, service, exit_trap, resolution_us);
170 m_sleep_trap =
nullptr;
171 m_exit_trap =
nullptr;
172 m_winmm_dll =
nullptr;
173 m_timer_thread =
nullptr;
175 m_stop_signal =
false;
178 #if STK_TICKLESS_IDLE
183 if ((m_tls = TlsAlloc()) == TLS_OUT_OF_INDEXES)
190 STK_X86_WIN32_CRITICAL_SECTION_INIT(&m_cs);
198 if (m_tls != TLS_OUT_OF_INDEXES)
205 void LoadWindowsAPI()
207 HMODULE winmm = GetModuleHandleA(
"Winmm");
208 if (winmm ==
nullptr)
209 m_winmm_dll = winmm = LoadLibraryA(
"Winmm.dll");
210 assert(winmm !=
nullptr);
212 timeBeginPeriod = (timeBeginPeriodF)GetProcAddress(winmm,
"timeBeginPeriod");
213 assert(timeBeginPeriod !=
nullptr);
218 void UnloadWindowsAPI()
220 if (m_winmm_dll !=
nullptr)
222 FreeLibrary(m_winmm_dll);
223 m_winmm_dll =
nullptr;
229 TaskContext() : m_task(nullptr), m_stack(nullptr), m_thread(nullptr), m_thread_id(0)
232 void Initialize(ITask *task, Stack *stack)
245 const size_t stack_size = m_task->GetStackSize() *
sizeof(
Word);
247 m_thread = CreateThread(
nullptr, stack_size, &OnTaskRun,
this, CREATE_SUSPENDED, &m_thread_id);
250 static DWORD WINAPI OnTaskRun(LPVOID param)
252 ((TaskContext *)param)->m_task->Run();
262 void InitStack(EStackType stack_type, Stack *stack, IStackMemory *stack_memory, ITask *user_task);
263 void ConfigureTime();
264 void StartActiveTask();
265 void CreateTimerThreadAndJoin();
268 void SwitchContext();
270 void Sleep(Timeout ticks);
271 bool SleepUntil(Ticks timestamp);
272 EWaitResult Wait(ISyncObject *sync_obj, IMutex *mutex, Timeout timeout);
274 Word GetCallerSP()
const;
280 return hw::PtrToWord(TlsGetValue(m_tls));
285 TlsSetValue(m_tls, hw::WordToPtr<void>(tp));
291 STK_X86_WIN32_CRITICAL_SECTION_START(&m_cs);
293 if (m_csu_nesting == 0)
296 if (GetCurrentThreadId() != m_timer_tid)
298 SuspendThread(m_timer_thread);
306 STK_KERNEL_PANIC(KERNEL_PANIC_CS_NESTING_OVERFLOW);
316 if (m_csu_nesting == 0)
319 if (GetCurrentThreadId() != m_timer_tid)
321 ResumeThread(m_timer_thread);
325 STK_X86_WIN32_CRITICAL_SECTION_END(&m_cs);
328 IPlatform::IEventOverrider *m_overrider;
332 HANDLE m_timer_thread;
334 std::list<TaskContext *> m_tasks;
335 std::vector<HANDLE> m_task_threads;
340 STK_X86_WIN32_CRITICAL_SECTION m_cs;
341 uint8_t m_csu_nesting;
343 volatile bool m_stop_signal;
345s_StkPlatformContext[1];
365 return static_cast<DWORD
>((ticks *
GetContext().m_tick_resolution) / 1000U);
368static DWORD WINAPI TimerThread(LPVOID param)
372 DWORD wait_ms = TicksToMs(1U);
373 GetContext().m_timer_tid = GetCurrentThreadId();
375 while (WaitForSingleObject(
GetContext().m_timer_thread, wait_ms) == WAIT_TIMEOUT)
384 #if STK_TICKLESS_IDLE
385 wait_ms = TicksToMs(
GetContext().m_sleep_ticks);
392void Context::ConfigureTime()
395 if (m_tick_resolution < STK_X86_WIN32_MIN_RESOLUTION)
397 m_tick_resolution = STK_X86_WIN32_MIN_RESOLUTION;
404void Context::StartActiveTask()
410 ResumeThread(active_task->m_thread);
413void Context::CreateTimerThreadAndJoin()
421 m_handler->OnStart(m_stack_active);
426 m_timer_thread = CreateThread(
nullptr, 0, &TimerThread,
nullptr, 0,
nullptr);
428 SetThreadPriority(m_timer_thread, THREAD_PRIORITY_TIME_CRITICAL);
430 while (!m_task_threads.empty())
432 DWORD result = WaitForMultipleObjects((DWORD)m_task_threads.size(), m_task_threads.data(), FALSE, INFINITE);
437 Win32ScopedCriticalSection __cs(m_cs);
440 for (std::vector<HANDLE>::iterator itr = m_task_threads.begin(); itr != m_task_threads.end(); ++itr)
442 if (result == (WAIT_OBJECT_0 + i))
444 TaskContext *exiting_task =
nullptr;
445 for (std::list<TaskContext *>::iterator titr = m_tasks.begin(); titr != m_tasks.end(); ++titr)
447 if ((*titr)->m_thread == (*itr))
449 exiting_task = (*titr);
455 if (exiting_task !=
nullptr)
457 m_handler->OnTaskExit(exiting_task->m_stack);
460 m_task_threads.erase(itr);
470 if (m_timer_thread !=
nullptr)
472 WaitForSingleObject(m_timer_thread, INFINITE);
476void Context::Cleanup()
479 for (std::list<TaskContext *>::iterator itr = m_tasks.begin(); itr != m_tasks.end(); ++itr)
481 if ((*itr)->m_thread !=
nullptr)
483 CloseHandle((*itr)->m_thread);
484 (*itr)->m_thread =
nullptr;
490 if (m_timer_thread !=
nullptr)
492 CloseHandle(m_timer_thread);
493 m_timer_thread =
nullptr;
497 m_stop_signal =
false;
503void Context::ProcessTick()
505 Win32ScopedCriticalSection __cs(m_cs);
511 if (m_handler->OnTick(m_stack_idle, m_stack_active
512 #
if STK_TICKLESS_IDLE
521 m_sleep_ticks = ticks;
525void Context::SwitchContext()
528 if ((m_stack_idle != m_sleep_trap) && (m_stack_idle != m_exit_trap))
533 SuspendThread(idle_task->m_thread);
537 if (m_stack_active == m_sleep_trap)
539 #if STK_TICKLESS_IDLE
540 const Timeout sleep_ticks = m_sleep_ticks;
545 if ((m_overrider ==
nullptr) || !m_overrider->OnSleep(sleep_ticks))
551 if (m_stack_active ==
GetContext().m_exit_trap)
560 ResumeThread(active_task->m_thread);
564Word Context::GetCallerSP()
const
567 DWORD calling_tid = GetCurrentThreadId();
569 Win32ScopedCriticalSection __cs(
const_cast<STK_X86_WIN32_CRITICAL_SECTION &
>(m_cs));
571 for (std::list<TaskContext *>::const_iterator itr = m_tasks.begin(), end = m_tasks.end(); itr != end; ++itr)
573 if ((*itr)->m_thread_id == calling_tid)
575 caller_sp =
hw::PtrToWord(STK_X86_WIN32_GET_SP((*itr)->m_task->GetStack()));
586TId Context::GetTid()
const
588 return m_handler->OnGetTid(GetCallerSP());
591void Context::SwitchToNext()
593 m_handler->OnTaskSwitch(GetCallerSP());
596void Context::Sleep(
Timeout ticks)
598 m_handler->OnTaskSleep(GetCallerSP(), ticks);
601bool Context::SleepUntil(
Ticks timestamp)
603 return m_handler->OnTaskSleepUntil(GetCallerSP(), timestamp);
608 return m_handler->OnTaskWait(GetCallerSP(), sync_obj, mutex, timeout);
613 m_stop_signal =
true;
619 InitStackMemory(stack_memory);
622 TaskContext *
const ctx =
reinterpret_cast<TaskContext *
>(STK_X86_WIN32_GET_SP(stack_mem));
627 ctx->Initialize(user_task, stack);
629 m_tasks.push_back(ctx);
630 m_task_threads.push_back(ctx->m_thread);
652 GetContext().Initialize(event_handler, service, exit_trap, resolution_us);
680 GetContext().InitStack(stack_type, stack, stack_memory, user_task);
690 return HiResClockQPC::GetInstance()->GetCycles();
695 return HiResClockQPC::GetInstance()->GetFrequency();
715 return GetContext().Wait(sync_obj, mutex, timeout);
748Word stk::hw::GetTls()
753void stk::hw::SetTls(
Word tp)
779 HW_SpinLockLock(m_lock);
784 HW_SpinLockUnlock(m_lock);
789 return HW_SpinLockTryLock(m_lock);
804 return HiResClockQPC::GetInstance()->GetCycles();
809 return HiResClockQPC::GetInstance()->GetFrequency();
Contains common inventory for platform implementation.
#define GetContext()
Get platform's context.
Hardware Abstraction Layer (HAL) declarations for the stk::hw namespace.
void STK_PANIC_HANDLER_DEFAULT(stk::EKernelPanicId id)
Default panic handler: disable interrupts, record the id, and spin in a tight loop — a defined,...
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
#define __stk_forceinline
Forces compiler to always inline the decorated function, regardless of optimisation level.
#define STK_CS_NESTINGS_MAX
Maximum allowable recursion depth for critical section entry (default: 16).
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
#define __stk_attr_noinline
Prevents compiler from inlining the decorated function (function prefix).
#define __stk_attr_noreturn
Declares that function never returns to its caller (function prefix).
Namespace of STK package.
uintptr_t Word
Native processor word type.
static void Sleep(Timeout tick_count)
Put calling process into a sleep state.
EWaitResult
Wait result (see IKernelService::Wait).
int64_t Ticks
Ticks value.
int32_t Timeout
Timeout time (ticks).
static __stk_forceinline void STK_KERNEL_PANIC(stk::EKernelPanicId id)
Called when the kernel detects an unrecoverable internal fault.
@ STACK_SLEEP_TRAP
Stack of the Sleep trap.
@ STACK_USER_TASK
Stack of the user task.
@ STACK_EXIT_TRAP
Stack of the Exit trap.
uint64_t Cycles
Cycles value.
Word TId
Task (thread) id.
EKernelPanicId
Identifies the source of a kernel panic.
@ KERNEL_PANIC_HRT_HARD_FAULT
Kernel running in KERNEL_HRT mode reported deadline failure of the task.
@ KERNEL_PANIC_NONE
Panic is absent (no fault).
@ KERNEL_PANIC_SPINLOCK_DEADLOCK
Spin-lock timeout expired: lock owner never released.
bool IsPrivilegedContext()
Check if caller context is Privileged.
static constexpr T * WordToPtr(Word value) noexcept
Cast a CPU register-width integer back to a pointer.
static constexpr Word PtrToWord(T *const ptr) noexcept
Cast a pointer to a CPU register-width integer.
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
Base platform context for all platform implementations.
EWaitResult Wait(ISyncObject *sync_obj, IMutex *mutex, Timeout timeout) override
Put calling process into a waiting state until synchronization object is signaled or timeout occurs.
void Sleep(Timeout ticks) override
Put calling process into a sleep state.
void Resume(Timeout elapsed_ticks) override
Resume scheduling after a prior Suspend() call.
void Stop() override
Stop scheduling.
void Initialize(IEventHandler *event_handler, IKernelService *service, uint32_t resolution_us, Stack *exit_trap) override
Initialize scheduler's context.
Word GetCallerSP() const override
Get caller's Stack Pointer (SP).
void Start() override
Start scheduling.
uint32_t GetSysTimerFrequency() const override
Get system timer frequency.
uint32_t GetTickResolution() const override
Get resolution of the system tick timer in microseconds. Resolution means a number of microseconds be...
void InitStack(EStackType stack_type, Stack *stack, IStackMemory *stack_memory, ITask *user_task) override
Initialize stack memory of the user task.
void ProcessHardFault() override
Cause a hard fault of the system.
void SetEventOverrider(IEventOverrider *overrider) override
Set platform event overrider.
void ProcessTick() override
Process one tick.
Cycles GetSysTimerCount() const override
Get system timer count value.
bool SleepUntil(Ticks timestamp) override
Put calling process into a sleep state until the specified timestamp.
TId GetTid() const override
Get thread Id.
void SwitchToNext() override
Switch to a next task.
Timeout Suspend() override
Suspend scheduling.
static constexpr Session DEFAULT_SESSION
Default session value passed to Enter()/Exit() when the caller does not need to force a specific hand...
static Session Enter(const Session ses=DEFAULT_SESSION)
Enter a critical section.
uint8_t Session
Opaque session token returned by Enter() and consumed by Exit().
static void Exit(const Session ses=DEFAULT_SESSION)
Exit a critical section.
bool TryLock()
Attempt to acquire SpinLock in a single non-blocking attempt.
void Lock()
Acquire SpinLock, blocking until it is available.
void Unlock()
Release SpinLock, allowing another thread or core to acquire it.
static uint32_t GetFrequency()
Get clock frequency.
static Cycles GetCycles()
Get number of clock cycles elapsed.
Word SP
Offset 0: Stack Pointer (SP) register.
Interface for a stack memory region.
virtual const Word * GetStack() const =0
Get pointer to the stack memory.
Synchronization object interface.
Interface for mutex synchronization primitive.
Interface for a user task.
Interface for the kernel services exposed to the user processes during run-time when Kernel started s...
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
RISC-V specific event handler.