2023-05-18 12:43:53 -07:00
|
|
|
#include "scheduler/thread.h"
|
|
|
|
|
2023-05-29 12:44:26 -07:00
|
|
|
#include "common/gdt.h"
|
2023-05-18 13:24:02 -07:00
|
|
|
#include "debug/debug.h"
|
2023-05-29 00:32:54 -07:00
|
|
|
#include "loader/elf_loader.h"
|
2023-05-29 12:44:26 -07:00
|
|
|
#include "memory/paging_util.h"
|
2023-05-18 12:43:53 -07:00
|
|
|
#include "scheduler/process.h"
|
2023-05-18 13:24:02 -07:00
|
|
|
#include "scheduler/scheduler.h"
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
2023-05-29 12:44:26 -07:00
|
|
|
extern "C" void jump_user_space(uint64_t rip, uint64_t rsp);
|
|
|
|
|
2023-05-18 13:24:02 -07:00
|
|
|
extern "C" void thread_init() {
|
|
|
|
asm("sti");
|
2023-05-18 13:56:54 -07:00
|
|
|
sched::CurrentThread().Init();
|
|
|
|
panic("Reached end of thread.");
|
2023-05-18 13:24:02 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace
|
|
|
|
|
2023-05-29 15:50:38 -07:00
|
|
|
SharedPtr<Thread> Thread::RootThread(Process* root_proc) {
|
|
|
|
return new Thread(root_proc);
|
|
|
|
}
|
2023-05-18 13:24:02 -07:00
|
|
|
|
2023-05-29 15:50:38 -07:00
|
|
|
Thread::Thread(const SharedPtr<Process>& proc, uint64_t tid, uint64_t elf_ptr)
|
2023-05-29 00:32:54 -07:00
|
|
|
: process_(proc), id_(tid), elf_ptr_(elf_ptr) {
|
2023-05-18 13:24:02 -07:00
|
|
|
uint64_t* stack = new uint64_t[512];
|
|
|
|
uint64_t* stack_ptr = stack + 511;
|
|
|
|
// 0: rip
|
|
|
|
*(stack_ptr) = reinterpret_cast<uint64_t>(thread_init);
|
|
|
|
// 1-4: rax, rcx, rdx, rbx
|
|
|
|
// 5: rbp
|
|
|
|
*(stack_ptr - 5) = reinterpret_cast<uint64_t>(stack_ptr + 1);
|
|
|
|
// 6-15: rsi, rdi, r8, r9, r10, r11, r12, r13, r14, r15
|
|
|
|
// 16: cr3
|
|
|
|
*(stack_ptr - 16) = proc->cr3();
|
|
|
|
rsp0_ = reinterpret_cast<uint64_t>(stack_ptr - 16);
|
2023-05-18 16:03:09 -07:00
|
|
|
rsp0_start_ = reinterpret_cast<uint64_t>(stack_ptr);
|
2023-05-18 13:24:02 -07:00
|
|
|
}
|
2023-05-18 12:43:53 -07:00
|
|
|
|
|
|
|
uint64_t Thread::pid() { return process_->id(); }
|
2023-05-18 13:56:54 -07:00
|
|
|
|
|
|
|
void Thread::Init() {
|
2023-05-29 12:44:26 -07:00
|
|
|
dbgln("[%u.%u]", pid(), id_);
|
|
|
|
uint64_t rip = LoadElfProgram(elf_ptr_, 0);
|
|
|
|
uint64_t rsp = 0x80000000;
|
|
|
|
EnsureResident(rsp - 1, 1);
|
|
|
|
SetRsp0(rsp0_start_);
|
|
|
|
jump_user_space(rip, rsp);
|
2023-05-18 13:56:54 -07:00
|
|
|
}
|
2023-05-29 13:51:00 -07:00
|
|
|
|
|
|
|
void Thread::Exit() {
|
|
|
|
dbgln("[%u.%u] Exiting", pid(), id_);
|
|
|
|
state_ = FINISHED;
|
|
|
|
process_->CheckState();
|
|
|
|
sched::Yield();
|
|
|
|
}
|