90 lines
2.6 KiB
C++
90 lines
2.6 KiB
C++
// vim: set noet ts=4 sw=4:
|
|
|
|
#include "thread.h"
|
|
#include "../arch/core_ring.h"
|
|
#include "../memory/pageframealloc.h"
|
|
#include "../memory/pagetable.h"
|
|
#include "../debug/kernelpanic.h"
|
|
#include "../interrupt/guard.h"
|
|
#include "debug/output.h"
|
|
|
|
static int idCounter = 1; // counter for task IDs
|
|
extern four_lvl_paging_t paging_tree;
|
|
|
|
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, thread->start, 0);
|
|
else
|
|
if(thread->start == nullptr)
|
|
thread->action();
|
|
else
|
|
((void(*)())thread->start)();
|
|
}
|
|
|
|
void Thread::load_paging(Thread* t){
|
|
paging_tree.l2.entries[32] = {
|
|
.present = 1,
|
|
.write = 1,
|
|
.user = 1,
|
|
.address = (uintptr_t)(t->subtable) >> 12
|
|
};
|
|
load_cr3((void*)&paging_tree.l4);
|
|
}
|
|
|
|
Thread::Thread (bool kernel, void * start): queue_link(nullptr), isKernel(kernel), start(start), id(idCounter++), kill_flag(false){
|
|
StackPointer.isr = reinterpret_cast<void *>((uintptr_t)PageFrameAllocator::alloc(true)+STACK_SIZE);//(reserved_stack_space_isr + STACK_SIZE);
|
|
StackPointer.user = reinterpret_cast<void *>((uintptr_t)PageFrameAllocator::alloc(false)+STACK_SIZE);
|
|
|
|
subtable = (pagetable_t*) PageFrameAllocator::alloc(true);
|
|
subtable->entries[0] = {
|
|
.present = 1,
|
|
.user = 1,
|
|
.address = (uintptr_t)start >> 12
|
|
};
|
|
subtable->entries[1] = {
|
|
.present = 1,
|
|
.write = 1,
|
|
.user = 1,
|
|
.address = (uintptr_t)StackPointer.user >> 12
|
|
};
|
|
|
|
//map_pageframe(&paging_tree, (uintptr_t)StackPointer.user, 0x4001000);
|
|
|
|
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) {
|
|
load_paging(next);
|
|
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() {
|
|
load_paging(this);
|
|
context_launch(&context);
|
|
}
|
|
|
|
void Thread::action() { kernelpanic("Wrong entry / missing action in Thread"); }
|