// 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(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, (void*)0x4000000, 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 * startframe, int num_pages): queue_link(nullptr), isKernel(kernel), start(startframe), id(idCounter++), kill_flag(false){ StackPointer.isr = reinterpret_cast((uintptr_t)PageFrameAllocator::alloc(true)+STACK_SIZE);//(reserved_stack_space_isr + STACK_SIZE); StackPointer.user = (void*)(0x4100000+STACK_SIZE); subtable = (pagetable_t*) PageFrameAllocator::alloc(true); for(uint8_t i=0; ientries[i] = { .present = 1, .user = 1, .address = ((uintptr_t)startframe >> 12) + i }; } uintptr_t user_stackframe_p = ((uintptr_t)PageFrameAllocator::alloc(false)); subtable->entries[256] = { .present = 1, .write = 1, .user = 1, .address = user_stackframe_p >> 12 }; //map_pageframe(&paging_tree, (uintptr_t)StackPointer.user, 0x4001000); prepareContext(StackPointer.isr, context, kickoff, reinterpret_cast(this), 0, 0); } Thread::Thread() : Thread(false, 0) {} //Thread::Thread() : queue_link(nullptr), id(idCounter++), kill_flag(false) { // void *tos = reinterpret_cast(reserved_stack_space_isr + STACK_SIZE); // prepareContext(tos, context, kickoff, reinterpret_cast(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"); }