Files
bsb2/kernel/thread/thread.cc
2026-02-03 20:15:35 +01:00

68 lines
2.1 KiB
C++

// vim: set noet ts=4 sw=4:
#include "thread.h"
#include "../arch/core_ring.h"
#include "../memory/pageframealloc.h"
#include "../debug/kernelpanic.h"
#include "../interrupt/guard.h"
#include "debug/output.h"
// counter for ID
static size_t idCounter = 1;
void Thread::kickoff(uintptr_t param1, uintptr_t param2, uintptr_t param3) {
Thread *thread = reinterpret_cast<Thread *>(param1);
assert(thread != nullptr && "Kickoff got nullptr pointer to Thread");
(void)param2; // will be used later
(void)param3; // will be used later
// The core must have entered level 1/2 to cause a thread to be scheduled.
Guard::leave();
if(!thread->isKernel)
Core::Ring::switchToUsermode(thread->StackPointer.user, reinterpret_cast<void*>(kickoffUsermode), thread);
else
if(thread->start == nullptr)
thread->action();
else
((void(*)())thread->start)();
}
void Thread::kickoffUsermode (Thread *object){
if(object->start == nullptr)
object->action();
else
((void(*)())object->start)();
}
Thread::Thread (bool kernel, void * start): queue_link(nullptr), isKernel(kernel), start(start), id(idCounter++), kill_flag(false){
StackPointer.isr = reinterpret_cast<void *>(reserved_stack_space_isr + STACK_SIZE);
StackPointer.user = reinterpret_cast<void *>(PageFrameAllocator::alloc(false) + STACK_SIZE);
prepareContext(StackPointer.isr, context, kickoff, reinterpret_cast<uintptr_t>(this), 0, 0);
}
Thread::Thread() : Thread(false, 0) {}
//Thread::Thread() : queue_link(nullptr), id(idCounter++), kill_flag(false) {
// void *tos = reinterpret_cast<void *>(reserved_stack_space_isr + STACK_SIZE);
// prepareContext(tos, context, kickoff, reinterpret_cast<uintptr_t>(this), 0, 0);
//}
void Thread::resume(Thread *next) {
assert(next != nullptr && "Pointer to next Thread must not be nullptr!");
context_switch(&next->context, &context);
}
void* Thread::operator new(size_t sz) noexcept
{
if (sz == 0)
++sz; // avoid std::malloc(0) which may return nullptr on success
void *ptr = PageFrameAllocator::alloc(true);
return ptr;
}
void Thread::go() { context_launch(&context); }
void Thread::action() { kernelpanic("Wrong entry / missing action in Thread"); }