feat: make kernel architecture-agnostic; primitive work on arm port
This commit is contained in:
1 parent
dab7d5427b
commit
1bae77ec84
164 files changed
+3664
-1641
No files matched your search
+129
-188
@@ -18,12 +18,13 @@
|
||||
#include <Terminal/Terminal.hpp>
|
||||
#include <CppLib/Stream.hpp>
|
||||
#include <CppLib/Spinlock.hpp>
|
||||
#include <Hal/Apic/Apic.hpp>
|
||||
#include <Hal/Apic/Interrupts.hpp>
|
||||
#include <Hal/GDT.hpp>
|
||||
#include <Hal/SmpBoot.hpp>
|
||||
#include <Hal/CpuPower.hpp>
|
||||
#include <Timekeeping/ApicTimer.hpp>
|
||||
#include <Arch/Context.hpp>
|
||||
#include <Arch/Abi.hpp>
|
||||
#include <Arch/Cpu.hpp>
|
||||
#include <Arch/CpuPower.hpp>
|
||||
#include <Arch/Interrupts.hpp>
|
||||
#include <Arch/Smp.hpp>
|
||||
#include <Timekeeping/Timer.hpp>
|
||||
#include <Api/WinServer.hpp>
|
||||
#include <Api/Heap.hpp>
|
||||
#include <Api/LibSyscall.hpp>
|
||||
@@ -32,32 +33,6 @@
|
||||
#include <Ipc/Ipc.hpp>
|
||||
#include <Drivers/USB/UserUsb.hpp>
|
||||
|
||||
// Assembly: context switch with CR3 and FPU state parameters
|
||||
extern "C" void SchedContextSwitch(uint64_t* oldRsp, uint64_t newRsp, uint64_t newCR3,
|
||||
uint8_t* oldFpuArea, uint8_t* newFpuArea);
|
||||
|
||||
// Load a user thread's FS base (TLS thread pointer) before dispatching it.
|
||||
// Cached per CPU: the MSR write is skipped when unchanged, so TLS-free
|
||||
// processes (fsBase 0) cost one write per CPU ever. Userspace cannot move
|
||||
// FS base itself (CR4.FSGSBASE is off), so the cache cannot go stale.
|
||||
static inline void LoadUserFsBase(Smp::CpuData* cpu, uint64_t fsBase) {
|
||||
if (cpu->currentFsBase == fsBase) {
|
||||
return;
|
||||
}
|
||||
cpu->currentFsBase = fsBase;
|
||||
asm volatile("wrmsr"
|
||||
:
|
||||
: "c"(0xC0000100u), /* IA32_FS_BASE */
|
||||
"a"((uint32_t)fsBase),
|
||||
"d"((uint32_t)(fsBase >> 32)));
|
||||
}
|
||||
|
||||
// Assembly: jump to user mode via IRETQ.
|
||||
// `arg` is delivered as the user-mode RDI (SystemV first argument).
|
||||
// For freshly spawned processes this is 0; for SpawnThread it is the
|
||||
// user-supplied entry argument.
|
||||
extern "C" void JumpToUserMode(uint64_t rip, uint64_t rsp, uint64_t arg);
|
||||
|
||||
namespace Sched {
|
||||
|
||||
static Process processTable[MaxProcesses];
|
||||
@@ -74,7 +49,7 @@ namespace Sched {
|
||||
|
||||
// The scheduler lock MUST be a Spinlock (interrupt-disabling).
|
||||
// It is held ACROSS context switches to prevent the race where
|
||||
// another CPU picks up a process whose RSP hasn't been saved yet.
|
||||
// another CPU picks up a process whose stack pointer hasn't been saved yet.
|
||||
// The resumed process releases it.
|
||||
// schedLock is a baton: the context that acquires it switches stacks and
|
||||
// the context being resumed releases it. A Spinlock's ordinary shared
|
||||
@@ -99,7 +74,7 @@ namespace Sched {
|
||||
}
|
||||
|
||||
void Release() {
|
||||
uint64_t flags = 0; // Fresh startup remains IF=0 until JumpToUserMode's IRETQ.
|
||||
uint64_t flags = 0; // Fresh startup keeps interrupts off until EnterUserMode.
|
||||
auto* cpu = Smp::GetCurrentCpuData();
|
||||
if (cpu != nullptr && cpu->currentSlot >= 0 && cpu->currentSlot < MaxProcesses) {
|
||||
flags = processFlags[cpu->currentSlot];
|
||||
@@ -149,9 +124,9 @@ namespace Sched {
|
||||
return (uint32_t)(value >> 32);
|
||||
}
|
||||
|
||||
// The idle loop runs in the kernel PML4
|
||||
static uint64_t GetKernelCR3() {
|
||||
return (uint64_t)Memory::VMM::g_paging->PML4;
|
||||
// The idle loop runs in the kernel address space
|
||||
static uint64_t GetKernelRoot() {
|
||||
return Memory::VMM::g_paging->KernelRoot();
|
||||
}
|
||||
|
||||
static void RescheduleIpiHandler(uint8_t, bool interruptedUser) {
|
||||
@@ -192,8 +167,7 @@ namespace Sched {
|
||||
if (target->currentSlot >= 0) return false;
|
||||
if (target->reservedForKernelWork) return false;
|
||||
|
||||
return Hal::LocalApic::SendFixedIpi(target->lapicId,
|
||||
Hal::IRQ_VECTOR_BASE + Hal::IRQ_RESCHEDULE);
|
||||
return Arch::SendIpi(target->cpuIndex, Arch::IRQ_RESCHEDULE);
|
||||
};
|
||||
|
||||
if (tryKick(Smp::GetCpuData(0))) {
|
||||
@@ -230,30 +204,28 @@ namespace Sched {
|
||||
processTable[next].runningOnCpu = cpu->cpuIndex;
|
||||
processTable[next].sliceRemaining = TimeSliceMs;
|
||||
|
||||
cpu->kernelRsp = processTable[next].kernelStackTop;
|
||||
cpu->tss->rsp0 = processTable[next].kernelStackTop;
|
||||
|
||||
LoadUserFsBase(cpu, processTable[next].fsBase);
|
||||
SchedContextSwitch(&processTable[slot].savedRsp, processTable[next].savedRsp,
|
||||
processTable[next].pml4Phys,
|
||||
Arch::ActivateThread(cpu, processTable[next].kernelStackTop,
|
||||
processTable[next].threadPointer);
|
||||
Arch::SwitchContext(&processTable[slot].savedSp, processTable[next].savedSp,
|
||||
processTable[next].pageTableRoot,
|
||||
processTable[slot].fpuState, processTable[next].fpuState);
|
||||
schedLock.Release();
|
||||
return;
|
||||
}
|
||||
|
||||
cpu->currentSlot = -1;
|
||||
SchedContextSwitch(&processTable[slot].savedRsp, cpu->idleSavedRsp,
|
||||
GetKernelCR3(), processTable[slot].fpuState, nullptr);
|
||||
Arch::SwitchContext(&processTable[slot].savedSp, cpu->idleSavedSp,
|
||||
GetKernelRoot(), processTable[slot].fpuState, nullptr);
|
||||
schedLock.Release();
|
||||
}
|
||||
|
||||
// Startup function for newly spawned processes.
|
||||
// SchedContextSwitch "returns" here on first schedule.
|
||||
// Arch::SwitchContext "returns" here on first schedule.
|
||||
// The schedLock is held (acquired by the switching-from CPU's Schedule).
|
||||
static void ProcessStartup() {
|
||||
// Release the schedLock that the switching-from CPU held
|
||||
// without consulting this brand-new slot's (intentionally empty)
|
||||
// saved interrupt state. JumpToUserMode's IRETQ enables interrupts.
|
||||
// saved interrupt state. EnterUserMode enables interrupts.
|
||||
schedLock.ReleaseForStartup();
|
||||
|
||||
auto* cpu = Smp::GetCurrentCpuData();
|
||||
@@ -262,23 +234,18 @@ namespace Sched {
|
||||
if (slot >= 0) {
|
||||
Process& proc = processTable[slot];
|
||||
|
||||
// Set up per-CPU kernel RSP for SYSCALL entry
|
||||
cpu->kernelRsp = proc.kernelStackTop;
|
||||
|
||||
// Set up per-CPU TSS RSP0 for hardware interrupts from ring 3
|
||||
cpu->tss->rsp0 = proc.kernelStackTop;
|
||||
|
||||
LoadUserFsBase(cpu, proc.fsBase);
|
||||
// Kernel entry stack and TLS pointer for this thread
|
||||
Arch::ActivateThread(cpu, proc.kernelStackTop, proc.threadPointer);
|
||||
|
||||
// Jump to user mode (never returns).
|
||||
// For main threads threadArg is 0 (libc _start ignores RDI);
|
||||
// For main threads threadArg is 0 (libc _start ignores it);
|
||||
// for sibling threads it carries the user-supplied argument.
|
||||
JumpToUserMode(proc.entryPoint, proc.userStackTop, proc.threadArg);
|
||||
Arch::EnterUserMode(proc.entryPoint, proc.userStackTop, proc.threadArg);
|
||||
}
|
||||
|
||||
ExitProcess();
|
||||
for (;;) {
|
||||
asm volatile("hlt");
|
||||
Arch::Halt();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,12 +254,12 @@ namespace Sched {
|
||||
processTable[i].pid = i;
|
||||
processTable[i].state = ProcessState::Free;
|
||||
processTable[i].name[0] = '\0';
|
||||
processTable[i].savedRsp = 0;
|
||||
processTable[i].savedSp = 0;
|
||||
processTable[i].stackBase = 0;
|
||||
processTable[i].entryPoint = 0;
|
||||
processTable[i].sliceRemaining = 0;
|
||||
processTable[i].cpuTimeMs = 0;
|
||||
processTable[i].pml4Phys = 0;
|
||||
processTable[i].pageTableRoot = 0;
|
||||
processTable[i].kernelStackTop = 0;
|
||||
processTable[i].userStackTop = 0;
|
||||
processTable[i].heapNext = 0;
|
||||
@@ -344,7 +311,7 @@ namespace Sched {
|
||||
exitLedgerCode[i] = 0;
|
||||
}
|
||||
exitLedgerHead = 0;
|
||||
Hal::RegisterIrqHandler(Hal::IRQ_RESCHEDULE, RescheduleIpiHandler);
|
||||
Arch::RegisterIrqHandler(Arch::IRQ_RESCHEDULE, RescheduleIpiHandler);
|
||||
|
||||
Kt::KernelLogStream(Kt::OK, "Sched") << "Initialized (" << MaxProcesses
|
||||
<< " process slots, " << (uint64_t)TimeSliceMs << " ms time slice)";
|
||||
@@ -392,15 +359,15 @@ namespace Sched {
|
||||
processTable[slot].reapReady = false;
|
||||
schedLock.Release();
|
||||
|
||||
// Create per-process PML4 with kernel-half copied
|
||||
uint64_t pml4Phys = Memory::VMM::Paging::CreateUserPML4();
|
||||
// Create the process address space (kernel half shared)
|
||||
uint64_t pageTableRoot = Memory::VMM::Paging::CreateUserAddressSpace();
|
||||
|
||||
// Load ELF into the process's address space
|
||||
TlsInfo tls{};
|
||||
uint64_t entry = ElfLoad(vfsPath, pml4Phys, &tls);
|
||||
uint64_t entry = ElfLoad(vfsPath, pageTableRoot, &tls);
|
||||
if (entry == 0) {
|
||||
Memory::VMM::Paging::FreeUserHalf(pml4Phys);
|
||||
Memory::g_pfa->Free((void*)Memory::HHDM(pml4Phys));
|
||||
Memory::VMM::Paging::FreeUserHalf(pageTableRoot);
|
||||
Memory::g_pfa->Free((void*)Memory::HHDM(pageTableRoot));
|
||||
schedLock.Acquire();
|
||||
processTable[slot].state = ProcessState::Free;
|
||||
schedLock.Release();
|
||||
@@ -415,8 +382,8 @@ namespace Sched {
|
||||
void* stackMem = Memory::g_pfa->ReallocConsecutive(nullptr, StackPages);
|
||||
if (stackMem == nullptr) {
|
||||
Kt::KernelLogStream(Kt::ERROR, "Sched") << "Failed to allocate contiguous kernel stack";
|
||||
Memory::VMM::Paging::FreeUserHalf(pml4Phys);
|
||||
Memory::g_pfa->Free((void*)Memory::HHDM(pml4Phys));
|
||||
Memory::VMM::Paging::FreeUserHalf(pageTableRoot);
|
||||
Memory::g_pfa->Free((void*)Memory::HHDM(pageTableRoot));
|
||||
schedLock.Acquire();
|
||||
processTable[slot].state = ProcessState::Free;
|
||||
schedLock.Release();
|
||||
@@ -429,15 +396,15 @@ namespace Sched {
|
||||
|
||||
// Helper to clean up all resources allocated so far on failure
|
||||
auto cleanupOnFail = [&]() {
|
||||
Memory::VMM::Paging::FreeUserHalf(pml4Phys);
|
||||
Memory::g_pfa->Free((void*)Memory::HHDM(pml4Phys));
|
||||
Memory::VMM::Paging::FreeUserHalf(pageTableRoot);
|
||||
Memory::g_pfa->Free((void*)Memory::HHDM(pageTableRoot));
|
||||
Memory::g_pfa->Free(stackMem, StackPages);
|
||||
schedLock.Acquire();
|
||||
processTable[slot].state = ProcessState::Free;
|
||||
schedLock.Release();
|
||||
};
|
||||
|
||||
// Allocate user stack pages and map them in the process PML4
|
||||
// Allocate user stack pages and map them in the process address space
|
||||
uint64_t userStackBase = UserStackTop - UserStackSize;
|
||||
uint64_t topStackPagePhys = 0;
|
||||
for (uint64_t i = 0; i < UserStackPages; i++) {
|
||||
@@ -448,7 +415,7 @@ namespace Sched {
|
||||
return -1;
|
||||
}
|
||||
uint64_t physAddr = Memory::SubHHDM((uint64_t)page);
|
||||
if (!Memory::VMM::Paging::MapUserIn(pml4Phys, physAddr, userStackBase + i * 0x1000)) {
|
||||
if (!Memory::VMM::Paging::MapUserIn(pageTableRoot, physAddr, userStackBase + i * 0x1000)) {
|
||||
Kt::KernelLogStream(Kt::ERROR, "Sched") << "Failed to map user stack page";
|
||||
Memory::g_pfa->Free(page);
|
||||
cleanupOnFail();
|
||||
@@ -466,37 +433,24 @@ namespace Sched {
|
||||
return -1;
|
||||
}
|
||||
uint64_t stubPhys = Memory::SubHHDM((uint64_t)stubPage);
|
||||
if (!Memory::VMM::Paging::MapUserIn(pml4Phys, stubPhys, ExitStubAddr)) {
|
||||
if (!Memory::VMM::Paging::MapUserIn(pageTableRoot, stubPhys, ExitStubAddr)) {
|
||||
Kt::KernelLogStream(Kt::ERROR, "Sched") << "Failed to map exit stub";
|
||||
Memory::g_pfa->Free(stubPage);
|
||||
cleanupOnFail();
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Write: xor edi, edi; xor eax, eax; syscall
|
||||
uint8_t* stub = (uint8_t*)stubPage;
|
||||
stub[0] = 0x31; stub[1] = 0xFF; // xor edi, edi (exit code 0)
|
||||
stub[2] = 0x31; stub[3] = 0xC0; // xor eax, eax (SYS_EXIT = 0)
|
||||
stub[4] = 0x0F; stub[5] = 0x05; // syscall
|
||||
// User code that calls SYS_EXIT(0)
|
||||
Arch::WriteExitStub((uint8_t*)stubPage);
|
||||
}
|
||||
|
||||
// Push exit stub address as the return address on the user stack.
|
||||
{
|
||||
uint8_t* topPage = (uint8_t*)Memory::HHDM(topStackPagePhys);
|
||||
*(uint64_t*)(topPage + 0xFF8) = ExitStubAddr;
|
||||
}
|
||||
// Returning from the entry function lands in the exit stub.
|
||||
uint64_t initialUserSp = Arch::SetupUserEntryStack(
|
||||
(uint8_t*)Memory::HHDM(topStackPagePhys), UserStackTop, ExitStubAddr);
|
||||
|
||||
// Set up the initial kernel stack frame so that SchedContextSwitch
|
||||
// Set up the initial kernel stack frame so that Arch::SwitchContext
|
||||
// "returns" into ProcessStartup
|
||||
uint64_t* sp = (uint64_t*)kernelStackTop;
|
||||
|
||||
*(--sp) = (uint64_t)ProcessStartup; // return addr
|
||||
*(--sp) = 0; // rbp
|
||||
*(--sp) = 0; // rbx
|
||||
*(--sp) = 0; // r12
|
||||
*(--sp) = 0; // r13
|
||||
*(--sp) = 0; // r14
|
||||
*(--sp) = 0; // r15
|
||||
uint64_t initialKernelSp = Arch::PrepareThreadStack(kernelStackTop, ProcessStartup);
|
||||
|
||||
schedLock.Acquire();
|
||||
|
||||
@@ -516,18 +470,18 @@ namespace Sched {
|
||||
proc.joinable = false; // main thread is reaped by BSP, not joined
|
||||
proc.futexAddr = 0;
|
||||
proc.futexWoken = false;
|
||||
proc.savedRsp = (uint64_t)sp;
|
||||
proc.savedSp = initialKernelSp;
|
||||
proc.stackBase = (uint64_t)kernelStackBase;
|
||||
proc.entryPoint = entry;
|
||||
proc.sliceRemaining = TimeSliceMs;
|
||||
proc.cpuTimeMs = 0;
|
||||
proc.pml4Phys = pml4Phys;
|
||||
proc.pageTableRoot = pageTableRoot;
|
||||
proc.kernelStackTop = kernelStackTop;
|
||||
proc.userStackTop = UserStackTop - 8;
|
||||
proc.userStackTop = initialUserSp;
|
||||
proc.heapNext = UserHeapBase;
|
||||
for (uint64_t i = 0; i < UserHeapBitmapWords; i++)
|
||||
g_userHeapPageMap[slot][i] = 0;
|
||||
proc.fsBase = tls.fsBase;
|
||||
proc.threadPointer = tls.threadPointer;
|
||||
proc.tlsTemplateVaddr = tls.templateVaddr;
|
||||
proc.tlsFileSize = tls.fileSize;
|
||||
proc.tlsMemSize = tls.memSize;
|
||||
@@ -667,10 +621,7 @@ namespace Sched {
|
||||
proc.ioKeyHandle = -1;
|
||||
proc.ioWaitsetHandle = -1;
|
||||
|
||||
// Initialize FPU state: zero out, then set default FCW and MXCSR
|
||||
memset(proc.fpuState, 0, 512);
|
||||
*(uint16_t*)&proc.fpuState[0] = 0x037F; // FCW: default x87 control word
|
||||
*(uint32_t*)&proc.fpuState[24] = 0x1F80; // MXCSR: default SSE control/status
|
||||
Arch::InitFpuState(proc.fpuState);
|
||||
|
||||
Ipc::ProcessStartedInSlot(slot, proc.pid);
|
||||
|
||||
@@ -686,8 +637,8 @@ namespace Sched {
|
||||
// Threading
|
||||
//
|
||||
// Every thread is a slot in processTable. The main thread's primarySlot
|
||||
// points to itself and owns process-level state (PML4, IPC handles,
|
||||
// cwd/user/args, redirected I/O). A sibling thread copies pml4Phys from
|
||||
// points to itself and owns process-level state (page tables, IPC handles,
|
||||
// cwd/user/args, redirected I/O). A sibling thread copies pageTableRoot from
|
||||
// the primary so context-switch is cheap, but per-process getters use
|
||||
// primarySlot to reach the canonical state.
|
||||
//
|
||||
@@ -706,16 +657,16 @@ namespace Sched {
|
||||
int callerSlot = cpu->currentSlot;
|
||||
int primarySlot_ = processTable[callerSlot].primarySlot;
|
||||
if (primarySlot_ < 0) primarySlot_ = callerSlot;
|
||||
uint64_t sharedPml4 = processTable[primarySlot_].pml4Phys;
|
||||
uint64_t sharedRoot = processTable[primarySlot_].pageTableRoot;
|
||||
int processPid = processTable[primarySlot_].pid;
|
||||
if (sharedPml4 == 0) return -1;
|
||||
if (sharedRoot == 0) return -1;
|
||||
|
||||
// Give the new thread its own TLS block when the image has one.
|
||||
// We are executing inside the process's address space, so the
|
||||
// freshly mapped pages and the template are directly addressable.
|
||||
// The block uses process-heap virtual space. Its physical pages are
|
||||
// reclaimed when the sibling exits (or if creation fails).
|
||||
uint64_t threadFsBase = 0;
|
||||
uint64_t threadTp = 0;
|
||||
uint64_t threadTlsBase = 0;
|
||||
uint64_t threadTlsPages = 0;
|
||||
Process& primary = processTable[primarySlot_];
|
||||
@@ -739,7 +690,7 @@ namespace Sched {
|
||||
break;
|
||||
}
|
||||
uint64_t physAddr = Memory::SubHHDM((uint64_t)page);
|
||||
if (!Memory::VMM::Paging::MapUserIn(sharedPml4, physAddr,
|
||||
if (!Memory::VMM::Paging::MapUserIn(sharedRoot, physAddr,
|
||||
base + p * 0x1000)) {
|
||||
Memory::g_pfa->Free(page);
|
||||
ok = false;
|
||||
@@ -748,7 +699,7 @@ namespace Sched {
|
||||
mappedPages++;
|
||||
}
|
||||
if (!ok) {
|
||||
Memory::UnmapAndFreeUserRange(sharedPml4, base, mappedPages);
|
||||
Memory::UnmapAndFreeUserRange(sharedRoot, base, mappedPages);
|
||||
ReleaseUserHeapRange(primarySlot_, base, numPages * 0x1000ULL);
|
||||
Kt::KernelLogStream(Kt::ERROR, "Sched")
|
||||
<< "Thread TLS allocation failed";
|
||||
@@ -759,7 +710,7 @@ namespace Sched {
|
||||
memcpy((void*)(base + layout.templateOffset),
|
||||
(const void*)primary.tlsTemplateVaddr, primary.tlsFileSize);
|
||||
*(uint64_t*)tp = tp; /* ABI self-pointer */
|
||||
threadFsBase = tp;
|
||||
threadTp = tp;
|
||||
threadTlsBase = base;
|
||||
threadTlsPages = numPages;
|
||||
}
|
||||
@@ -768,14 +719,14 @@ namespace Sched {
|
||||
// require validating the user VA against the process page tables).
|
||||
// Userspace is responsible for ensuring the thread entry calls
|
||||
// SYS_THREAD_EXIT; the libc trampoline does this. The kernel only
|
||||
// enforces SystemV alignment by handing the entry RSP = 16n - 8.
|
||||
uint64_t userRsp = (userStackTop & ~0xFULL) - 8;
|
||||
// enforces the ABI's entry stack alignment.
|
||||
uint64_t userSp = Arch::ThreadEntryStackPointer(userStackTop);
|
||||
|
||||
// Allocate kernel stack.
|
||||
void* stackMem = Memory::g_pfa->ReallocConsecutive(nullptr, StackPages);
|
||||
if (stackMem == nullptr) {
|
||||
if (threadTlsPages != 0) {
|
||||
Memory::UnmapAndFreeUserRange(sharedPml4, threadTlsBase, threadTlsPages);
|
||||
Memory::UnmapAndFreeUserRange(sharedRoot, threadTlsBase, threadTlsPages);
|
||||
ReleaseUserHeapRange(primarySlot_, threadTlsBase,
|
||||
threadTlsPages * 0x1000ULL);
|
||||
}
|
||||
@@ -785,11 +736,8 @@ namespace Sched {
|
||||
uint8_t* kernelStackBase = (uint8_t*)stackMem;
|
||||
uint64_t kernelStackTop = (uint64_t)kernelStackBase + StackSize;
|
||||
|
||||
// Initial kernel frame -- SchedContextSwitch "returns" into ProcessStartup.
|
||||
uint64_t* sp = (uint64_t*)kernelStackTop;
|
||||
*(--sp) = (uint64_t)ProcessStartup;
|
||||
*(--sp) = 0; *(--sp) = 0; *(--sp) = 0;
|
||||
*(--sp) = 0; *(--sp) = 0; *(--sp) = 0;
|
||||
// Initial kernel frame -- Arch::SwitchContext "returns" into ProcessStartup.
|
||||
uint64_t initialKernelSp = Arch::PrepareThreadStack(kernelStackTop, ProcessStartup);
|
||||
|
||||
schedLock.Acquire();
|
||||
|
||||
@@ -801,7 +749,7 @@ namespace Sched {
|
||||
schedLock.Release();
|
||||
Memory::g_pfa->Free(stackMem, StackPages);
|
||||
if (threadTlsPages != 0) {
|
||||
Memory::UnmapAndFreeUserRange(sharedPml4, threadTlsBase, threadTlsPages);
|
||||
Memory::UnmapAndFreeUserRange(sharedRoot, threadTlsBase, threadTlsPages);
|
||||
ReleaseUserHeapRange(primarySlot_, threadTlsBase,
|
||||
threadTlsPages * 0x1000ULL);
|
||||
}
|
||||
@@ -826,12 +774,12 @@ namespace Sched {
|
||||
thr.threadArg = arg;
|
||||
thr.futexAddr = 0;
|
||||
thr.futexWoken = false;
|
||||
thr.savedRsp = (uint64_t)sp;
|
||||
thr.savedSp = initialKernelSp;
|
||||
thr.stackBase = (uint64_t)kernelStackBase;
|
||||
thr.entryPoint = entry;
|
||||
thr.userStackTop = userRsp;
|
||||
thr.userStackTop = userSp;
|
||||
thr.kernelStackTop = kernelStackTop;
|
||||
thr.pml4Phys = sharedPml4; // shared with primary, NOT owned
|
||||
thr.pageTableRoot = sharedRoot; // shared with primary, NOT owned
|
||||
thr.sliceRemaining = TimeSliceMs;
|
||||
thr.cpuTimeMs = 0;
|
||||
thr.heapNext = 0;
|
||||
@@ -846,7 +794,7 @@ namespace Sched {
|
||||
thr.ioOutHandle = -1; thr.ioInHandle = -1;
|
||||
thr.ioKeyHandle = -1; thr.ioWaitsetHandle = -1;
|
||||
thr.args[0] = '\0'; thr.user[0] = '\0'; thr.cwd[0] = '\0';
|
||||
thr.fsBase = threadFsBase;
|
||||
thr.threadPointer = threadTp;
|
||||
thr.tlsTemplateVaddr = 0;
|
||||
thr.tlsFileSize = 0;
|
||||
thr.tlsMemSize = 0;
|
||||
@@ -862,9 +810,7 @@ namespace Sched {
|
||||
thr.name[i] = '\0';
|
||||
}
|
||||
|
||||
memset(thr.fpuState, 0, 512);
|
||||
*(uint16_t*)&thr.fpuState[0] = 0x037F;
|
||||
*(uint32_t*)&thr.fpuState[24] = 0x1F80;
|
||||
Arch::InitFpuState(thr.fpuState);
|
||||
|
||||
int tid = thr.pid;
|
||||
schedLock.Release();
|
||||
@@ -933,25 +879,25 @@ namespace Sched {
|
||||
static void FreeSiblingThreadTls(Process& thr) {
|
||||
int primarySlot_ = thr.primarySlot;
|
||||
if (primarySlot_ < 0 || primarySlot_ >= MaxProcesses ||
|
||||
primarySlot_ == (int)(&thr - processTable) || thr.fsBase == 0) {
|
||||
primarySlot_ == (int)(&thr - processTable) || thr.threadPointer == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Process& primary = processTable[primarySlot_];
|
||||
if (primary.tlsMemSize == 0 || primary.pml4Phys == 0) {
|
||||
thr.fsBase = 0;
|
||||
if (primary.tlsMemSize == 0 || primary.pageTableRoot == 0) {
|
||||
thr.threadPointer = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
TlsLayout layout = ComputeTlsLayout(primary.tlsMemSize, primary.tlsAlign);
|
||||
if (layout.tpOffset > thr.fsBase || layout.totalSize < layout.tpOffset) {
|
||||
if (layout.tpOffset > thr.threadPointer || layout.totalSize < layout.tpOffset) {
|
||||
Panic("Invalid sibling TLS metadata during thread teardown", nullptr);
|
||||
}
|
||||
|
||||
uint64_t base = thr.fsBase - layout.tpOffset;
|
||||
uint64_t base = thr.threadPointer - layout.tpOffset;
|
||||
uint64_t pages = (layout.totalSize + 0xFFF) / 0x1000;
|
||||
thr.fsBase = 0;
|
||||
Memory::UnmapAndFreeUserRange(primary.pml4Phys, base, pages);
|
||||
thr.threadPointer = 0;
|
||||
Memory::UnmapAndFreeUserRange(primary.pageTableRoot, base, pages);
|
||||
ReleaseUserHeapRange(primarySlot_, base, pages * 0x1000ULL);
|
||||
}
|
||||
|
||||
@@ -971,19 +917,18 @@ namespace Sched {
|
||||
readyCount--;
|
||||
processTable[next].runningOnCpu = cpu->cpuIndex;
|
||||
processTable[next].sliceRemaining = TimeSliceMs;
|
||||
cpu->kernelRsp = processTable[next].kernelStackTop;
|
||||
cpu->tss->rsp0 = processTable[next].kernelStackTop;
|
||||
if (readyCount > 0) {
|
||||
KickOneIdleCpu(cpu->cpuIndex);
|
||||
}
|
||||
LoadUserFsBase(cpu, processTable[next].fsBase);
|
||||
SchedContextSwitch(&thr.savedRsp, processTable[next].savedRsp,
|
||||
processTable[next].pml4Phys,
|
||||
Arch::ActivateThread(cpu, processTable[next].kernelStackTop,
|
||||
processTable[next].threadPointer);
|
||||
Arch::SwitchContext(&thr.savedSp, processTable[next].savedSp,
|
||||
processTable[next].pageTableRoot,
|
||||
thr.fpuState, processTable[next].fpuState);
|
||||
} else {
|
||||
cpu->currentSlot = -1;
|
||||
SchedContextSwitch(&thr.savedRsp, cpu->idleSavedRsp,
|
||||
GetKernelCR3(),
|
||||
Arch::SwitchContext(&thr.savedSp, cpu->idleSavedSp,
|
||||
GetKernelRoot(),
|
||||
thr.fpuState, nullptr);
|
||||
}
|
||||
schedLock.Release();
|
||||
@@ -994,7 +939,7 @@ namespace Sched {
|
||||
auto* cpu = Smp::GetCurrentCpuData();
|
||||
int slot = cpu->currentSlot;
|
||||
if (slot < 0) {
|
||||
for (;;) asm volatile("hlt");
|
||||
for (;;) Arch::Halt();
|
||||
}
|
||||
|
||||
Process& thr = processTable[slot];
|
||||
@@ -1042,7 +987,7 @@ namespace Sched {
|
||||
|
||||
SwitchAwayFromExitingThreadLocked(slot, thr);
|
||||
// Unreachable: the slot is Terminated, nobody resumes us.
|
||||
for (;;) asm volatile("hlt");
|
||||
for (;;) Arch::Halt();
|
||||
}
|
||||
|
||||
int JoinThread(int tid, int* outExitCode) {
|
||||
@@ -1075,7 +1020,7 @@ namespace Sched {
|
||||
int code = processTable[target].exitCode;
|
||||
void* stackBase = (void*)processTable[target].stackBase;
|
||||
processTable[target].stackBase = 0;
|
||||
processTable[target].pml4Phys = 0;
|
||||
processTable[target].pageTableRoot = 0;
|
||||
processTable[target].joinerSlot = -1;
|
||||
processTable[target].primarySlot = -1;
|
||||
processTable[target].state = ProcessState::Free;
|
||||
@@ -1099,7 +1044,7 @@ namespace Sched {
|
||||
int code = processTable[target].exitCode;
|
||||
void* stackBase = (void*)processTable[target].stackBase;
|
||||
processTable[target].stackBase = 0;
|
||||
processTable[target].pml4Phys = 0;
|
||||
processTable[target].pageTableRoot = 0;
|
||||
processTable[target].joinerSlot = -1;
|
||||
processTable[target].primarySlot = -1;
|
||||
processTable[target].state = ProcessState::Free;
|
||||
@@ -1140,9 +1085,9 @@ namespace Sched {
|
||||
// Schedule -- core context switch logic
|
||||
//
|
||||
// The schedLock is held ACROSS the context switch. This is critical:
|
||||
// setting the old process to Ready and saving its RSP must be atomic
|
||||
// setting the old process to Ready and saving its stack pointer must be atomic
|
||||
// with respect to other CPUs. If we released the lock before saving
|
||||
// RSP, another CPU could pick up the process with a stale savedRsp.
|
||||
// the stack pointer, another CPU could pick up the process with a stale savedSp.
|
||||
//
|
||||
// The RESUMED process releases the lock (it was acquired by whatever
|
||||
// CPU called Schedule() and switched away from that process).
|
||||
@@ -1166,10 +1111,10 @@ namespace Sched {
|
||||
// Grab the pointers, mark Free, then free memory after releasing lock
|
||||
void* stackBase = (processTable[i].stackBase != 0)
|
||||
? (void*)processTable[i].stackBase : nullptr;
|
||||
void* pml4 = (processTable[i].pml4Phys != 0)
|
||||
? (void*)Memory::HHDM(processTable[i].pml4Phys) : nullptr;
|
||||
void* pageRoot = (processTable[i].pageTableRoot != 0)
|
||||
? (void*)Memory::HHDM(processTable[i].pageTableRoot) : nullptr;
|
||||
processTable[i].stackBase = 0;
|
||||
processTable[i].pml4Phys = 0;
|
||||
processTable[i].pageTableRoot = 0;
|
||||
processTable[i].reapReady = false;
|
||||
processTable[i].startPending = false;
|
||||
processTable[i].state = ProcessState::Free;
|
||||
@@ -1177,7 +1122,7 @@ namespace Sched {
|
||||
// Release lock during PFA::Free to minimize hold time
|
||||
schedLock.Release();
|
||||
if (stackBase) Memory::g_pfa->Free(stackBase, StackPages);
|
||||
if (pml4) Memory::g_pfa->Free(pml4);
|
||||
if (pageRoot) Memory::g_pfa->Free(pageRoot);
|
||||
schedLock.Acquire();
|
||||
}
|
||||
}
|
||||
@@ -1233,7 +1178,7 @@ namespace Sched {
|
||||
|
||||
// Thermal governor step (rate-limited internally to 500 ms).
|
||||
// The timer requests this idle-context pass even under full load.
|
||||
Hal::CpuPower::ThermalTick(Timekeeping::GetMilliseconds());
|
||||
Arch::CpuPower::ThermalTick(Timekeeping::GetMilliseconds());
|
||||
}
|
||||
|
||||
uint64_t GetNextDeadlineTick() {
|
||||
@@ -1304,10 +1249,10 @@ namespace Sched {
|
||||
// a process from idle will release it via the resumed
|
||||
// process path. But idle is special: we release here
|
||||
// because idle doesn't go through ProcessStartup.
|
||||
// The RSP save is safe because interrupts are disabled
|
||||
// The SP save is safe because interrupts are disabled
|
||||
// (Spinlock), so no timer can fire between Ready and save.
|
||||
SchedContextSwitch(&processTable[oldSlot].savedRsp, cpu->idleSavedRsp,
|
||||
GetKernelCR3(), processTable[oldSlot].fpuState, nullptr);
|
||||
Arch::SwitchContext(&processTable[oldSlot].savedSp, cpu->idleSavedSp,
|
||||
GetKernelRoot(), processTable[oldSlot].fpuState, nullptr);
|
||||
// Resumed from idle -- lock was held by whoever switched to us
|
||||
schedLock.Release();
|
||||
} else {
|
||||
@@ -1324,16 +1269,16 @@ namespace Sched {
|
||||
}
|
||||
|
||||
// Prepare the context switch
|
||||
uint64_t* oldRspPtr;
|
||||
uint64_t* oldSpPtr;
|
||||
int oldSlot = cpu->currentSlot;
|
||||
|
||||
if (oldSlot >= 0) {
|
||||
processTable[oldSlot].state = ProcessState::Ready;
|
||||
readyCount++;
|
||||
processTable[oldSlot].runningOnCpu = -1;
|
||||
oldRspPtr = &processTable[oldSlot].savedRsp;
|
||||
oldSpPtr = &processTable[oldSlot].savedSp;
|
||||
} else {
|
||||
oldRspPtr = &cpu->idleSavedRsp;
|
||||
oldSpPtr = &cpu->idleSavedSp;
|
||||
}
|
||||
|
||||
cpu->currentSlot = next;
|
||||
@@ -1342,11 +1287,7 @@ namespace Sched {
|
||||
processTable[next].runningOnCpu = cpu->cpuIndex;
|
||||
processTable[next].sliceRemaining = TimeSliceMs;
|
||||
|
||||
uint64_t newCR3 = processTable[next].pml4Phys;
|
||||
|
||||
// Update per-CPU kernel RSP and TSS RSP0
|
||||
cpu->kernelRsp = processTable[next].kernelStackTop;
|
||||
cpu->tss->rsp0 = processTable[next].kernelStackTop;
|
||||
uint64_t newRoot = processTable[next].pageTableRoot;
|
||||
|
||||
uint8_t* oldFpu = (oldSlot >= 0) ? processTable[oldSlot].fpuState : nullptr;
|
||||
uint8_t* newFpu = processTable[next].fpuState;
|
||||
@@ -1356,16 +1297,18 @@ namespace Sched {
|
||||
// dispatching user work so preemption resumes with the process.
|
||||
// Also pick up a thermal-governor policy epoch that may have
|
||||
// changed while this CPU remained asleep without timer ticks.
|
||||
Hal::CpuPower::ApplyPolicyIfChanged();
|
||||
Timekeeping::ApicTimerLeaveApIdle();
|
||||
Arch::CpuPower::ApplyPolicyIfChanged();
|
||||
Timekeeping::TimerLeaveApIdle();
|
||||
}
|
||||
|
||||
LoadUserFsBase(cpu, processTable[next].fsBase);
|
||||
// Kernel entry stack and TLS pointer for the incoming thread
|
||||
Arch::ActivateThread(cpu, processTable[next].kernelStackTop,
|
||||
processTable[next].threadPointer);
|
||||
|
||||
// DO NOT release schedLock here! It is held across the context
|
||||
// switch so that setting Ready + saving RSP is atomic. The
|
||||
// switch so that setting Ready + saving the SP is atomic. The
|
||||
// resumed process releases it.
|
||||
SchedContextSwitch(oldRspPtr, processTable[next].savedRsp, newCR3, oldFpu, newFpu);
|
||||
Arch::SwitchContext(oldSpPtr, processTable[next].savedSp, newRoot, oldFpu, newFpu);
|
||||
|
||||
// We reach here when this process is resumed by another CPU's
|
||||
// Schedule(). That CPU held the lock across its context switch.
|
||||
@@ -1379,7 +1322,7 @@ namespace Sched {
|
||||
// Pick up thermal-governor frequency changes (HWP requests are
|
||||
// per-core MSRs, so every CPU applies them itself). No-op unless
|
||||
// the governor bumped the policy epoch since our last tick.
|
||||
Hal::CpuPower::ApplyPolicyIfChanged();
|
||||
Arch::CpuPower::ApplyPolicyIfChanged();
|
||||
|
||||
// BSP: expire timed waits in the bounded IRQ-safe pass. Queue heavier
|
||||
// reclamation/policy work for the idle kernel context.
|
||||
@@ -1514,7 +1457,7 @@ namespace Sched {
|
||||
stackGrowLock.Acquire();
|
||||
|
||||
// Another thread may have mapped this page between the fault and here.
|
||||
if (Memory::VMM::Paging::IsUserRangeAccessible(proc->pml4Phys, pageVa, 0x1000, true)) {
|
||||
if (Memory::VMM::Paging::IsUserRangeAccessible(proc->pageTableRoot, pageVa, 0x1000, true)) {
|
||||
stackGrowLock.Release();
|
||||
return true;
|
||||
}
|
||||
@@ -1527,14 +1470,14 @@ namespace Sched {
|
||||
return false;
|
||||
}
|
||||
uint64_t physAddr = Memory::SubHHDM((uint64_t)page);
|
||||
if (!Memory::VMM::Paging::MapUserIn(proc->pml4Phys, physAddr, pageVa)) {
|
||||
if (!Memory::VMM::Paging::MapUserIn(proc->pageTableRoot, physAddr, pageVa)) {
|
||||
stackGrowLock.Release();
|
||||
Memory::g_pfa->Free(page);
|
||||
return false;
|
||||
}
|
||||
stackGrowLock.Release();
|
||||
|
||||
asm volatile("invlpg (%0)" :: "r"(pageVa) : "memory");
|
||||
Arch::FlushTlbPage(pageVa);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1562,7 +1505,7 @@ namespace Sched {
|
||||
int exitingPid = proc.pid;
|
||||
int primarySlot_ = slot;
|
||||
|
||||
// Drain sibling threads: any thread sharing our PML4 must stop using
|
||||
// Drain sibling threads: any thread sharing our address space must stop using
|
||||
// it before we call FreeUserHalf. Ready/Blocked siblings can be
|
||||
// terminated immediately; siblings running on other CPUs are tagged
|
||||
// killPending and we spin until their tick handler routes them
|
||||
@@ -1626,8 +1569,7 @@ namespace Sched {
|
||||
if (!targetCpus[i] || i == cpu->cpuIndex) continue;
|
||||
Smp::CpuData* target = Smp::GetCpuData(i);
|
||||
if (target != nullptr && target->started) {
|
||||
(void)Hal::LocalApic::SendFixedIpi(target->lapicId,
|
||||
Hal::IRQ_VECTOR_BASE + Hal::IRQ_RESCHEDULE);
|
||||
(void)Arch::SendIpi(target->cpuIndex, Arch::IRQ_RESCHEDULE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1644,7 +1586,7 @@ namespace Sched {
|
||||
// Wait for the sibling CPU(s) to observe killPending on their
|
||||
// next timer tick. Briefly busy-wait; this path is rare.
|
||||
for (int spin = 0; spin < 1024; spin++) {
|
||||
asm volatile("pause");
|
||||
Arch::Pause();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1656,11 +1598,11 @@ namespace Sched {
|
||||
if (processTable[i].state != ProcessState::Terminated) continue;
|
||||
// Ready/blocked siblings terminated inline above never ran their
|
||||
// ordinary ExitCurrentThread cleanup. Running siblings normally
|
||||
// arrive here with fsBase already cleared, making this a no-op.
|
||||
// arrive here with threadPointer already cleared, making this a no-op.
|
||||
FreeSiblingThreadTls(processTable[i]);
|
||||
void* stackBase = (void*)processTable[i].stackBase;
|
||||
processTable[i].stackBase = 0;
|
||||
processTable[i].pml4Phys = 0;
|
||||
processTable[i].pageTableRoot = 0;
|
||||
processTable[i].primarySlot = -1;
|
||||
processTable[i].joinerSlot = -1;
|
||||
processTable[i].state = ProcessState::Free;
|
||||
@@ -1689,8 +1631,8 @@ namespace Sched {
|
||||
Drivers::USB::UserUsb::ReleaseAllForPid(exitingPid);
|
||||
|
||||
// Release process-scoped IPC handles/mappings before tearing down the address space.
|
||||
Ipc::CleanupProcessSlot(slot, exitingPid, proc.pml4Phys);
|
||||
montauk::abi::CleanupHeapForSlot(slot, proc.pml4Phys);
|
||||
Ipc::CleanupProcessSlot(slot, exitingPid, proc.pageTableRoot);
|
||||
montauk::abi::CleanupHeapForSlot(slot, proc.pageTableRoot);
|
||||
montauk::abi::CleanupLibTable(slot);
|
||||
|
||||
proc.waitingForPid = -1;
|
||||
@@ -1718,7 +1660,7 @@ namespace Sched {
|
||||
Ipc::ProcessExitedInSlot(slot, exitingPid);
|
||||
|
||||
// Free all user-space physical pages and page table structures
|
||||
Memory::VMM::Paging::FreeUserHalf(proc.pml4Phys);
|
||||
Memory::VMM::Paging::FreeUserHalf(proc.pageTableRoot);
|
||||
|
||||
schedLock.Acquire();
|
||||
|
||||
@@ -1765,26 +1707,25 @@ namespace Sched {
|
||||
KickOneIdleCpu(cpu->cpuIndex);
|
||||
}
|
||||
|
||||
uint64_t newCR3 = processTable[next].pml4Phys;
|
||||
cpu->kernelRsp = processTable[next].kernelStackTop;
|
||||
cpu->tss->rsp0 = processTable[next].kernelStackTop;
|
||||
LoadUserFsBase(cpu, processTable[next].fsBase);
|
||||
uint64_t newRoot = processTable[next].pageTableRoot;
|
||||
Arch::ActivateThread(cpu, processTable[next].kernelStackTop,
|
||||
processTable[next].threadPointer);
|
||||
|
||||
// Lock held across context switch -- resumed process releases it
|
||||
SchedContextSwitch(&processTable[slot].savedRsp, processTable[next].savedRsp, newCR3,
|
||||
Arch::SwitchContext(&processTable[slot].savedSp, processTable[next].savedSp, newRoot,
|
||||
processTable[slot].fpuState, processTable[next].fpuState);
|
||||
schedLock.Release();
|
||||
} else {
|
||||
cpu->currentSlot = -1;
|
||||
|
||||
// Switch to idle -- release after resuming from idle
|
||||
SchedContextSwitch(&processTable[slot].savedRsp, cpu->idleSavedRsp, GetKernelCR3(),
|
||||
Arch::SwitchContext(&processTable[slot].savedSp, cpu->idleSavedSp, GetKernelRoot(),
|
||||
processTable[slot].fpuState, nullptr);
|
||||
schedLock.Release();
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
asm volatile("hlt");
|
||||
Arch::Halt();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2150,7 +2091,7 @@ namespace Sched {
|
||||
// it must not fault: the caller validated (and demand-committed) the
|
||||
// page, and the page walk below re-confirms it is still mapped. An
|
||||
// aligned 32-bit word never straddles a page.
|
||||
if (!Memory::VMM::Paging::IsUserRangeAccessible(self.pml4Phys, uaddr, 4, false)) {
|
||||
if (!Memory::VMM::Paging::IsUserRangeAccessible(self.pageTableRoot, uaddr, 4, false)) {
|
||||
schedLock.Release();
|
||||
return BadPointer;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user