// vim: set noet ts=4 sw=4: #include "thread.h" #include "../arch/core_ring.h" #include "../memory/pageframealloc.h" #include "../memory/pagetable.h" #include "../memory/page.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; extern pagetable_t identity_table; 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)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, (void*)param2); else if(thread->start == nullptr) thread->action(); else ((void(*)())thread->start)(); } void Thread::load_paging(Thread* t){ load_cr3((void*)(t->paging_tree->l4)); } void Thread::map_app(void* code_paddr, uint16_t code_page_num, void* stack_vaddr, uint16_t stack_page_num){ paging_tree = (four_lvl_paging_t*)PageFrameAllocator::alloc(true); memset(paging_tree, 0, 4096); create_basic_page_table(paging_tree, &identity_table); // app code pages at 0x4000000 for(uintptr_t i=0; i<(code_page_num*4096); i+=4096){ copy_page(paging_tree->l4, (uintptr_t)code_paddr+i, (void*)(0x4000000+i)); } for(uintptr_t i=0; i<(stack_page_num*4096); i+=4096){ uintptr_t user_stackframe_p = ((uintptr_t)PageFrameAllocator::alloc(false)); setMapping((uintptr_t)(stack_vaddr)+i, (void*)((uintptr_t)user_stackframe_p), paging_tree->l4); } } Thread::Thread (bool kernel, void* start_addr, void * codeframe, int code_frame_num): queue_link(nullptr), isKernel(kernel), start(start_addr), code_paddr(codeframe), code_pagenum(code_frame_num), id(idCounter++), kill_flag(false){ StackPointer.isr = reinterpret_cast((uintptr_t)PageFrameAllocator::alloc(true)+STACK_SIZE);// mapped due to identity mapping StackPointer.user = (void*)(0x6000000+STACK_SIZE); map_app(codeframe, code_frame_num, (void*)((uintptr_t)StackPointer.user-STACK_SIZE), 1); 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"); }