using System.Runtime.InteropServices; namespace XFESystem.NativeKernel; [StructLayout(LayoutKind.Sequential, Size = 128)] public unsafe struct CpuWorker { public ulong Online, ExpectedApicId, Generation, Completed, Kind, Source, Target; public ulong SourcePitch, TargetPitch, Width, Rows, Swap, ActualApicId, CoreKey, Started, Finished; } // Real AP execution for bounded, allocation-free kernel jobs. The Microsoft // managed scheduler/GC still executes on the BSP. APs never allocate, attach to // that runtime, mutate page tables, or borrow another CPU's FS/TSS/IRQ stack. public static unsafe class Multiprocessor { public const uint MaximumCpus = 32; static CpuWorker* _workers; // Native storage: busy, generation, rendezvous arrivals/release, copy jobs. static ulong* _control; public static uint OnlineCount = 1; public static ulong ReportedCount = 1; public static bool Ready; static uint _preferredCpus = 1; static ulong _minimumPixels = 262144, _pixelsPerCpu = 262144; static bool Expired(ulong deadline) => MonotonicClock.Nanoseconds() >= deadline; static void CheckWorker(uint cpu) { if (Native.AtomicLoad(&_workers[cpu].Online) == 1) return; Serial.Write("XFE_AP_FAULT|Index|"); Serial.Number(cpu); Serial.Write("|Vector|"); Serial.Number(_workers[cpu].Kind); Serial.Write("|Rip|"); Serial.Hex(_workers[cpu].Source); Serial.Write("|Cr2|"); Serial.Hex(_workers[cpu].Target); Serial.Line(""); Kernel.Fail("AP_WORKER_FAULT"); } public static bool Initialize(NativeBootInfo* boot) { if (Ready || sizeof(CpuWorker) != 128) return false; _workers = (CpuWorker*)Native.Storage(16); _control = (ulong*)Native.Storage(18); if (_workers == null || _control == null) return false; Native.SetCpuIndex(0); _workers[0].Online = 1; _workers[0].ActualApicId = Cpu.CurrentApicId(); _workers[0].CoreKey = Cpu.CurrentCoreKey(); LimineMpResponse* response = boot == null ? null : boot->Multiprocessors; if (response == null) { Ready = true; Serial.Line("XFE_MULTIPROCESSOR|Reported|1|Online|1|Backend|NoMpResponse|ManagedSchedulerCpus|1"); return true; } if (response->Count == 0 || response->Count > 4096 || response->Cpus == null || response->BspApicId != _workers[0].ActualApicId) return false; // Validate the complete topology before releasing any AP. Reserved fields // belong to Limine and are never repurposed as stacks or CPU indices. uint bspEntries = 0; for (ulong i = 0; i < response->Count; i++) { LimineMpInfo* current = response->Cpus[i]; if (current == null || current->GotoAddress != 0) return false; if (current->ApicId == response->BspApicId) bspEntries++; for (ulong j = 0; j < i; j++) if (response->Cpus[j]->ApicId == current->ApicId) return false; } if (bspEntries != 1) return false; ReportedCount = response->Count; for (ulong i = 0; i < response->Count && OnlineCount < MaximumCpus; i++) { LimineMpInfo* current = response->Cpus[i]; if (current->ApicId == response->BspApicId) continue; uint slot = OnlineCount; _workers[slot].ExpectedApicId = current->ApicId; if (Native.StartCpu(current, slot) != 1) return false; ulong deadline = MonotonicClock.Nanoseconds() + 3000000000; while (Native.AtomicLoad(&_workers[slot].Online) == 0 && !Expired(deadline)) Native.Pause(); // A released AP cannot safely be ignored and its memory reused. if (Native.AtomicLoad(&_workers[slot].Online) != 1 || _workers[slot].ActualApicId != current->ApicId) return false; Serial.Write("XFE_AP_ONLINE|Index|"); Serial.Number(slot); Serial.Write("|ApicId|"); Serial.Number(_workers[slot].ActualApicId); Serial.Write("|CoreKey|"); Serial.Number(_workers[slot].CoreKey); Serial.Line("|PrivateDescriptors|1"); OnlineCount++; } Ready = true; Serial.Write("XFE_MULTIPROCESSOR|Reported|"); Serial.Number(ReportedCount); Serial.Write("|Online|"); Serial.Number(OnlineCount); Serial.Line("|Backend|LimineApKernelJobs|ManagedSchedulerCpus|1"); return true; } [UnmanagedCallersOnly(EntryPoint = "XfeKernelApMain")] public static void Run(LimineMpInfo* info) { if (info == null || info->ExtraArgument == 0 || info->ExtraArgument >= MaximumCpus) for (;;) Native.Halt(); uint cpu = (uint)info->ExtraArgument; Native.SetCpuIndex(cpu); CpuWorker* worker = (CpuWorker*)Native.Storage(16) + cpu; worker->ActualApicId = Cpu.CurrentApicId(); worker->CoreKey = Cpu.CurrentCoreKey(); if (worker->ExpectedApicId != worker->ActualApicId || !Cpu.InstallWorkerDescriptors(cpu) || !LocalApicTimer.InitializeWorker()) { Native.AtomicStore(&worker->Online, 2); for (;;) Native.Halt(); } Native.AtomicStore(&worker->Online, 1); ulong completed = 0; for (;;) { ulong generation = Native.AtomicLoad(&worker->Generation); if (generation == completed) { Native.Idle(); continue; } // APs touch dynamic mappings only inside a joined job. Flush stale // non-global translations before the next pinned source is read. Native.ReloadPageTables(); worker->Started = Native.ReadTsc(); if (worker->Kind == 1) Native.CopyRgb32Rows((uint*)worker->Source, (byte*)worker->Target, (uint)worker->SourcePitch, (uint)worker->TargetPitch, (uint)worker->Width, (uint)worker->Rows, (uint)worker->Swap); else if (worker->Kind == 2) { ulong* control = (ulong*)Native.Storage(18); Native.AtomicAdd(control + 2, 1); while (Native.AtomicLoad(control + 3) != generation) Native.Pause(); } else { Native.AtomicStore(&worker->Online, 3); for (;;) Native.Halt(); } worker->Finished = Native.ReadTsc(); Native.MemoryBarrier(); // WC completion belongs to this AP, not the BSP's fence. completed = generation; Native.AtomicStore(&worker->Completed, generation); } } public static void Fault(InterruptFrame* frame) { uint cpu = Native.CurrentCpuIndex(); if (_workers != null && cpu > 0 && cpu < MaximumCpus) { _workers[cpu].Kind = frame == null ? ~0UL : frame->Vector; _workers[cpu].Source = frame == null ? 0 : frame->Rip; _workers[cpu].Target = Native.ReadCr2(); Native.AtomicStore(&_workers[cpu].Online, 3); } for (;;) Native.Halt(); } static void Submit(uint cpu, ulong generation) { Native.AtomicStore(&_workers[cpu].Generation, generation); if (!LocalApicTimer.WakeWorker((uint)_workers[cpu].ActualApicId)) Kernel.Fail("AP_WAKE_IPI"); } static void Join(uint cpu, ulong generation, ulong deadline) { while (Native.AtomicLoad(&_workers[cpu].Completed) != generation) { CheckWorker(cpu); // Never return and unpin the source while a worker can still read it. if (Expired(deadline)) Kernel.Fail("AP_JOB_JOIN_TIMEOUT"); Native.Pause(); } } // Caller keeps both extents alive until this synchronous call returns. Only // BSP code submits; contention falls back before publishing any descriptor. public static bool TryCopy(uint* source, byte* target, uint sourcePitch, uint targetPitch, uint width, uint rows, uint swap, bool force = false, uint cpuLimit = 0) { if (!Ready || OnlineCount < 2 || Native.CurrentCpuIndex() != 0 || source == null || target == null || width == 0 || rows < 2 || sourcePitch < (ulong)width * 4 || targetPitch < (ulong)width * 4 || swap > 1 || (!force && ((ulong)width * rows < _minimumPixels || _preferredCpus < 2)) || Native.AtomicCompare(_control, 0, 1) != 0) return false; if (cpuLimit == 0) cpuLimit = force ? 8u : _preferredCpus; uint count = OnlineCount < cpuLimit ? OnlineCount : cpuLimit; if (count > 8) count = 8; if (count < 2) { Native.AtomicStore(_control, 0); return false; } if (count > rows) count = rows; if (!force) { uint useful = (uint)((ulong)width * rows / _pixelsPerCpu); if (useful < 2) useful = 2; if (count > useful) count = useful; } uint* selected = stackalloc uint[8]; selected[0] = 0; uint used = 1; // Prefer separate physical cores before selecting an SMT sibling. for (uint pass = 0; pass < 2 && used < count; pass++) for (uint cpu = 1; cpu < OnlineCount && used < count; cpu++) { bool duplicate = false, sibling = false; for (uint j = 0; j < used; j++) { if (selected[j] == cpu) duplicate = true; if (_workers[selected[j]].CoreKey == _workers[cpu].CoreKey) sibling = true; } if (!duplicate && (pass != 0 || !sibling)) selected[used++] = cpu; } ulong generation = ++_control[1]; if (generation == 0) Kernel.Fail("AP_JOB_GENERATION_EXHAUSTED"); for (uint part = 1; part < count; part++) { uint cpu = selected[part], first = (uint)((ulong)rows * part / count), last = (uint)((ulong)rows * (part + 1) / count); CheckWorker(cpu); CpuWorker* worker = _workers + cpu; worker->Kind = 1; worker->Source = (ulong)source + (ulong)first * sourcePitch; worker->Target = (ulong)target + (ulong)first * targetPitch; worker->SourcePitch = sourcePitch; worker->TargetPitch = targetPitch; worker->Width = width; worker->Rows = last - first; worker->Swap = swap; Submit(cpu, generation); } Native.CopyRgb32Rows(source, target, sourcePitch, targetPitch, width, rows / count, swap); ulong deadline = MonotonicClock.Nanoseconds() + 5000000000; for (uint part = 1; part < count; part++) Join(selected[part], generation, deadline); _control[4]++; Native.AtomicStore(_control, 0); return true; } public static bool SelfTest() { if (!Ready) return false; if (OnlineCount > 1) { ulong generation = ++_control[1]; Native.AtomicStore(_control + 2, 0); Native.AtomicStore(_control + 3, 0); for (uint cpu = 1; cpu < OnlineCount; cpu++) { _workers[cpu].Kind = 2; Submit(cpu, generation); } ulong deadline = MonotonicClock.Nanoseconds() + 5000000000; while (Native.AtomicLoad(_control + 2) != OnlineCount - 1) { for (uint cpu = 1; cpu < OnlineCount; cpu++) CheckWorker(cpu); if (Expired(deadline)) return false; Native.Pause(); } // Every AP is waiting simultaneously, without a yield, timer or BSP // scheduler context switch. A fabricated CPU count cannot pass this. Native.AtomicStore(_control + 3, generation); for (uint cpu = 1; cpu < OnlineCount; cpu++) Join(cpu, generation, deadline); } ulong page = PhysicalMemory.Allocate(2); if (page == 0) return false; byte* memory = (byte*)PhysicalMemory.ToVirtual(page); uint* source = (uint*)memory; byte* target = memory + 4096 + 3; for (uint i = 0; i < 512; i++) source[i] = 0xf0000000u | (i * 0x12731u); bool result = true; for (uint round = 0; round < 32; round++) { for (uint i = 4096; i < 8192; i++) memory[i] = 0xa7; const uint width = 17, rows = 13, sourcePitch = 92, targetPitch = 83; uint swap = round & 1; bool copied = TryCopy(source, target, sourcePitch, targetPitch, width, rows, swap, true); if (OnlineCount > 1 && !copied) result = false; if (!copied) Native.CopyRgb32Rows(source, target, sourcePitch, targetPitch, width, rows, swap); for (uint i = 4096; i < 8192; i++) { uint relative = i - 4096; bool pixel = relative >= 3 && (relative - 3) / targetPitch < rows && (relative - 3) % targetPitch < width * 4; byte expected = 0xa7; if (pixel) { uint row = (relative - 3) / targetPitch, x = ((relative - 3) % targetPitch) / 4, b = ((relative - 3) % targetPitch) % 4; uint rgb = *(uint*)(memory + row * sourcePitch + x * 4); uint packed = swap == 0 ? rgb & 0xffffff : ((rgb & 255) << 16) | (rgb & 0xff00) | ((rgb >> 16) & 255); expected = (byte)(packed >> (int)(b * 8)); } if (memory[i] != expected) result = false; } } if (!PhysicalMemory.Release(page, 2)) result = false; Serial.Write("XFE_AP_JOBS_PROOF|Online|"); Serial.Number(OnlineCount); Serial.Write("|Rendezvous|"); Serial.Number(OnlineCount - 1); Serial.Write("|CopyCases|32|Passed|"); Serial.Number(result ? 1UL : 0UL); Serial.Line("|ManagedSmp|0|Physical240Hz|0"); return result; } // Measure the actual firmware scanout mapping while it is still black, // before the branded splash starts. More cores can lose on a shared memory // bus or virtual APIC; enable parallel presentation only after it wins here. // These CPU copy timings are never reported as panel FPS or Windows parity. public static void TuneFramebufferCopy() { _preferredCpus = 1; if (OnlineCount < 2 || !Framebuffer.Ready) return; ulong pixels = (ulong)Framebuffer.Width * Framebuffer.Height; if (pixels < 262144 || pixels > 33554432) return; uint pages = (uint)((pixels * 4 + 4095) / 4096); ulong allocation = PhysicalMemory.Allocate(pages); if (allocation == 0) return; uint* source = (uint*)PhysicalMemory.ToVirtual(allocation); // Allocator returns zeroed RAM. ulong baseline = 0, best = ~0UL; for (uint cpus = 1; cpus <= 8 && cpus <= OnlineCount; cpus *= 2) { ulong* samples = stackalloc ulong[5]; for (uint sample = 0; sample < 7; sample++) { ulong start = MonotonicClock.Nanoseconds(); if (cpus == 1) Native.CopyRgb32Rows(source, Framebuffer.Address, Framebuffer.Width * 4, Framebuffer.Pitch, Framebuffer.Width, Framebuffer.Height, 0); else if (!TryCopy(source, Framebuffer.Address, Framebuffer.Width * 4, Framebuffer.Pitch, Framebuffer.Width, Framebuffer.Height, 0, true, cpus)) Kernel.Fail("AP_COPY_TUNING"); ulong elapsed = MonotonicClock.Nanoseconds() - start; if (sample >= 2) samples[sample - 2] = elapsed; } for (uint i = 1; i < 5; i++) { ulong value = samples[i]; uint j = i; while (j > 0 && samples[j - 1] > value) { samples[j] = samples[j - 1]; j--; } samples[j] = value; } Serial.Write("XFE_AP_COPY_TUNING|Pixels|"); Serial.Number(pixels); Serial.Write("|Cpus|"); Serial.Number(cpus); Serial.Write("|MedianNs|"); Serial.Number(samples[2]); Serial.Write("|WorstNs|"); Serial.Number(samples[4]); Serial.Line("|Samples|5|PanelFps|0"); if (cpus == 1) baseline = best = samples[4]; else if (samples[4] < best && samples[4] * 10 < baseline * 9) { best = samples[4]; _preferredCpus = cpus; } } if (!PhysicalMemory.Release(allocation, pages)) Kernel.Fail("AP_TUNING_RELEASE"); if (_preferredCpus > 1) { _pixelsPerCpu = pixels / _preferredCpus; _minimumPixels = _pixelsPerCpu * 2; if (_minimumPixels < 262144) _minimumPixels = 262144; } Serial.Write("XFE_AP_COPY_POLICY|MaximumCpus|"); Serial.Number(_preferredCpus); Serial.Write("|MinimumPixels|"); Serial.Number(_minimumPixels); Serial.Line("|RequiresMeasuredWin|1|ManagedSmp|0|Physical240Hz|0"); } [UnmanagedCallersOnly(EntryPoint = "xfe_runtime_native_cpu_count")] public static uint ReadCount() => Ready ? OnlineCount : 1; [UnmanagedCallersOnly(EntryPoint = "xfe_runtime_native_copy_cpu_limit")] public static uint ReadCopyCpuLimit() => _preferredCpus; [UnmanagedCallersOnly(EntryPoint = "xfe_runtime_native_copy_count")] public static ulong ReadCopyCount() => _control == null ? 0 : Native.AtomicLoad(_control + 4); [UnmanagedCallersOnly(EntryPoint = "xfe_runtime_native_copy_busy")] public static uint ReadBusy() => _control == null ? 0 : (uint)Native.AtomicLoad(_control); // Trusted native buffer ABI for runtime/offscreen consumers. Both mappings // must remain pinned/reserved through this joined call, just like scanout. [UnmanagedCallersOnly(EntryPoint = "xfe_runtime_parallel_copy32")] public static int Copy32(uint* source, ulong sourceBytes, byte* target, ulong targetBytes, uint sourcePitch, uint targetPitch, uint width, uint rows, uint swap) { if (source == null || target == null || width == 0 || rows == 0 || width > 16384 || rows > 16384 || (ulong)width * rows > 33554432 || sourcePitch < (ulong)width * 4 || targetPitch < (ulong)width * 4 || swap > 1) return -1; ulong inputExtent = (ulong)(rows - 1) * sourcePitch + (ulong)width * 4; ulong outputExtent = (ulong)(rows - 1) * targetPitch + (ulong)width * 4; if (inputExtent > sourceBytes || outputExtent > targetBytes || (ulong)source > ~0UL - inputExtent || (ulong)target > ~0UL - outputExtent || ((ulong)source < (ulong)target + outputExtent && (ulong)target < (ulong)source + inputExtent)) return -1; if (!TryCopy(source, target, sourcePitch, targetPitch, width, rows, swap, true)) Native.CopyRgb32Rows(source, target, sourcePitch, targetPitch, width, rows, swap); return 1; } }