; ============================================================================ ; src/zapp_smp.asm — Bare-Metal SMP AP Boot, Zero-Contention 64B Spin-Barrier ; & Menu-Only HLT/IPI Idle Sleep ; Zero-App Ephemeral OS (Stage 3) — Pure x86-64 NASM Assembly ; ; Architecture: ; - Boots Application Processors (APs) via Local APIC INIT + SIPI to 0x8000 ; using the relocatable 16->32->64 trampoline (src/ap_trampoline.asm). ; - Strictly isolates g_ctrl, g_job, g_job_gen, and each g_worker_done[tid] ; on separate 64-byte cache lines to eliminate cross-CCX false sharing. ; - Active inference fast path: pure lock-free spin-barrier with PAUSE ; (zero HLT, zero LAPIC IPI, zero LOCK XADD, zero #VMEXIT between layers). ; - Menu-idle / parked-core path: atomic `sti; hlt; cli` (0.0% host CPU) ; with single broadcast Fixed IPI wakeup on vector 0x30. ; ============================================================================ bits 64 default rel %include "constants.inc" ; --- SMP & Local APIC Constants --- %define ZAPP_MAX_CPUS 32 %define LAPIC_ICR_LO 0x300 %define LAPIC_ICR_HI 0x310 %define LAPIC_SVR_ENABLE 0x000001FF ; SW APIC enable | spurious vec 0xFF %define LAPIC_LVT_MASKED 0x00010000 ; Mask AP local timer interrupt %define LAPIC_ICR_BUSY (1 << 12) ; Delivery status pending bit %define LAPIC_ICR_INIT 0x00004500 ; INIT, Level=Assert %define LAPIC_ICR_SIPI_08 0x00004608 ; SIPI, start page 0x08 (0x8000) %define LAPIC_ICR_BCAST_IPI 0x000C4000 ; All-Excluding-Self, Assert, Fixed %define VEC_IPI_WAKE 0x30 %define AP_TRAMP_PA 0x00008000 ; 16-bit real-mode trampoline PA %define AP_CTRL_PA 0x00008F00 ; 64-byte AP boot control block PA %define AP_STACK_SIZE 0x00010000 ; 64 KiB kernel stack per AP %define AP_INIT_DELAY_TSC 5000000 ; ~2 ms post-INIT settle delay %define AP_BOOT_TIMEOUT_TSC 120000000 ; ~40 ms AP online timeout ; --- External Symbols --- extern pml4_table extern gdt64_ptr extern g_apic_base extern ap_trampoline_start extern ap_trampoline_end extern enable_avx2_cpu extern zapp_load_idt extern isr_ipi_wake extern idt_set_gate ; --- Exported System V x86-64 ABI Symbols --- global zapp_ap_c_entry global zapp_smp_init global zapp_smp_num_cpus global zapp_smp_active_cpus global zapp_smp_set_active_cpus global zapp_smp_wake global zapp_smp_sleep global zapp_smp_dispatch ; ============================================================================ ; Cache-Line-Isolated Shared State (64-byte aligned sections) ; ============================================================================ section .data align=64 ; SmpCtrlLine (64B isolated): control flags & online topology g_ctrl: g_ctrl_sleep_flag: dd 1 ; +0x00: 1 = idle HLT, 0 = active spin g_ctrl_active_cpus: dd 1 ; +0x04: active worker count (incl. BSP) g_ctrl_online_mask: dq 1 ; +0x08: bitmask of online CPUs (bit0=BSP) g_ctrl_num_cpus: dd 1 ; +0x10: total online CPUs times (64 - 20) db 0 section .bss align=64 ; SmpJobLine (64B isolated): current parallel work descriptor g_job: g_job_fn: resq 1 ; +0x00: ZappParallelFn fn g_job_ctx: resq 1 ; +0x08: void *ctx g_job_job_gen: resq 1 ; +0x10: uint64_t job_gen (0 when idle) g_job_nact: resd 1 ; +0x18: int32_t nact resb (64 - 28) align 64 ; SmpGenLine (64B isolated): monotonic dispatch generation counter g_job_gen: resq 1 ; +0x00: volatile uint64_t gen resb 56 align 64 ; SmpWorkerSlot[ZAPP_MAX_CPUS]: per-CPU 64B-isolated completion slots g_worker_done: resb (ZAPP_MAX_CPUS * 64) ; ============================================================================ ; Code Section ; ============================================================================ section .text ; ---------------------------------------------------------------------------- ; Internal: uint64_t lapic_get_base(void) ; Returns Local APIC MMIO base in RAX (defaults to 0xFEE00000 if unset). ; Clobbers: RAX only. ; ---------------------------------------------------------------------------- lapic_get_base: mov rax, [rel g_apic_base] test rax, rax jnz .have_base mov rax, APIC_DEFAULT_BASE .have_base: ret ; ---------------------------------------------------------------------------- ; Internal: void busy_delay_tsc(uint64_t ticks) ; RDI = TSC ticks to wait. Clobbers: RAX, RCX, RDX. ; ---------------------------------------------------------------------------- busy_delay_tsc: rdtsc shl rdx, 32 or rax, rdx mov rcx, rax ; rcx = t0 .spin: rdtsc shl rdx, 32 or rax, rdx sub rax, rcx cmp rax, rdi jae .done pause jmp .spin .done: ret ; ---------------------------------------------------------------------------- ; Internal: void smp_noop_fn(int tid, int nthreads, void *ctx) ; No-op parallel kernel used to synchronize APs into hot-spin state. ; ---------------------------------------------------------------------------- smp_noop_fn: ret ; ---------------------------------------------------------------------------- ; Internal: void broadcast_wake_ipi(void) ; Sends Fixed IPI (vector 0x30) to All Excluding Self. ; Clobbers: RAX. ; ---------------------------------------------------------------------------- broadcast_wake_ipi: call lapic_get_base ; rax = LAPIC MMIO base .wait_idle1: test dword [rax + LAPIC_ICR_LO], LAPIC_ICR_BUSY jz .send_ipi pause jmp .wait_idle1 .send_ipi: mov dword [rax + LAPIC_ICR_HI], 0 mov dword [rax + LAPIC_ICR_LO], (LAPIC_ICR_BCAST_IPI | VEC_IPI_WAKE) .wait_idle2: test dword [rax + LAPIC_ICR_LO], LAPIC_ICR_BUSY jz .done pause jmp .wait_idle2 .done: ret ; ---------------------------------------------------------------------------- ; Internal: int detect_logical_cpus(int max_cpus) ; Queries CPUID leaf 0x0B, leaf 0x01, and extended leaf 0x80000008. ; RDI = max_cpus, returns clamped logical CPU count in EAX. ; ---------------------------------------------------------------------------- detect_logical_cpus: push rbx mov r8d, edi ; r8d = max_cpus mov r9d, 1 ; r9d = n_det = 1 ; Leaf 0: max standard CPUID leaf xor eax, eax xor ecx, ecx cpuid cmp eax, 0x0B jb .try_leaf1 ; Leaf 0x0B: Extended Topology Enumeration (subleaves 0..3) xor r10d, r10d ; sub = 0 .leaf0b_loop: mov eax, 0x0B mov ecx, r10d cpuid shr ecx, 8 and ecx, 0xFF ; level_type = (ECX >> 8) & 0xFF jz .try_leaf1 ; level_type == 0 -> end of levels movzx ebx, bx ; cnt = EBX & 0xFFFF cmp ebx, r9d cmovg r9d, ebx inc r10d cmp r10d, 4 jb .leaf0b_loop .try_leaf1: cmp r9d, 1 jg .try_ext8 mov eax, 1 xor ecx, ecx cpuid shr ebx, 16 and ebx, 0xFF ; max addressable logical IDs cmp ebx, r9d cmovg r9d, ebx .try_ext8: mov eax, 0x80000000 xor ecx, ecx cpuid cmp eax, 0x80000008 jb .clamp mov eax, 0x80000008 xor ecx, ecx cpuid and ecx, 0xFF inc ecx ; (ECX & 0xFF) + 1 cmp ecx, r9d cmovg r9d, ecx .clamp: mov eax, 1 cmp r9d, eax cmovg eax, r9d cmp eax, r8d cmovg eax, r8d pop rbx ret ; ---------------------------------------------------------------------------- ; Internal: int wait_ap_online(int ap) ; Polls g_ctrl_online_mask bit `ap` up to AP_BOOT_TIMEOUT_TSC ticks. ; EDI = ap index (1..31). Returns EAX = 1 if online, 0 on timeout. ; Clobbers: RAX, RCX, RDX, R8, R9. ; ---------------------------------------------------------------------------- wait_ap_online: mov r8d, 1 mov ecx, edi shl r8, cl ; r8 = 1ULL << ap rdtsc shl rdx, 32 or rax, rdx mov r9, rax ; r9 = t0 .poll: test [rel g_ctrl_online_mask], r8 jnz .online rdtsc shl rdx, 32 or rax, rdx sub rax, r9 cmp rax, AP_BOOT_TIMEOUT_TSC jae .timeout pause jmp .poll .online: mov eax, 1 ret .timeout: xor eax, eax ret ; ============================================================================ ; void zapp_ap_c_entry(uint64_t tid) ; 64-bit AP entry point invoked from ap_trampoline.asm (RDI = tid). ; Enables AVX2 + IDT + Local APIC, publishes online bit, then loops between ; zero-contention spin-barrier (active) and atomic `sti; hlt; cli` (idle). ; ============================================================================ align 16 zapp_ap_c_entry: push rbx push r12 push r13 push r14 push r15 ; 5 pushes -> 16-byte stack aligned mov r12, rdi ; r12 = tid call enable_avx2_cpu call zapp_load_idt ; Enable AP Local APIC (spurious vec 0xFF) and mask AP local timer call lapic_get_base mov dword [rax + APIC_REG_SVR], LAPIC_SVR_ENABLE mov dword [rax + APIC_REG_LVT_TIMER], LAPIC_LVT_MASKED ; Atomically mark this AP online in g_ctrl_online_mask mov eax, 1 mov ecx, r12d shl rax, cl lock or [rel g_ctrl_online_mask], rax ; Precompute pointer to this AP's isolated 64B completion slot mov rax, r12 shl rax, 6 ; tid * 64 lea r14, [rel g_worker_done] add r14, rax ; r14 = &g_worker_done[tid].done_gen xor r13d, r13d ; r13 = my_gen = 0 .outer_loop: ; Enter active fast-path spin-barrier if awake and within active_cpus cmp dword [rel g_ctrl_sleep_flag], 0 jne .idle_path cmp r12d, dword [rel g_ctrl_active_cpus] jge .idle_path align 16 .spin_loop: ; Lock-free spin-barrier: zero HLT, zero IPI, zero LOCK, zero #VMEXIT mov r15, [rel g_job_gen] cmp r15, r13 jne .spin_got_job cmp dword [rel g_ctrl_sleep_flag], 0 jne .idle_path cmp r12d, dword [rel g_ctrl_active_cpus] jge .idle_path pause jmp .spin_loop .spin_got_job: mov r13, r15 ; my_gen = cur cmp [rel g_job_job_gen], r15 jne .spin_loop mov esi, [rel g_job_nact] ; arg2: nact cmp r12d, esi jge .spin_loop mov edi, r12d ; arg1: (int)tid mov rdx, [rel g_job_ctx] ; arg3: ctx mov rax, [rel g_job_fn] call rax mov [r14], r15 ; g_worker_done[tid].done_gen = cur jmp .spin_loop .idle_path: ; Menu-idle / parked-core path: race-free check + atomic `sti; hlt; cli` cli mov r15, [rel g_job_gen] cmp r15, r13 jne .idle_got_job cmp dword [rel g_ctrl_sleep_flag], 0 jne .do_hlt cmp r12d, dword [rel g_ctrl_active_cpus] jl .outer_loop ; woken & active -> return to spin .do_hlt: sti hlt cli jmp .outer_loop .idle_got_job: mov r13, r15 ; my_gen = cur cmp [rel g_job_job_gen], r15 jne .outer_loop mov esi, [rel g_job_nact] ; arg2: nact cmp r12d, esi jge .outer_loop mov edi, r12d ; arg1: (int)tid mov rdx, [rel g_job_ctx] ; arg3: ctx mov rax, [rel g_job_fn] call rax mov [r14], r15 ; g_worker_done[tid].done_gen = cur jmp .outer_loop ; ============================================================================ ; int zapp_smp_init(uint64_t ap_stacks_base, int max_cpus) ; RDI = ap_stacks_base, ESI = max_cpus. Returns total online CPUs in EAX. ; ============================================================================ zapp_smp_init: push rbx push r12 push r13 push r14 push r15 ; 5 pushes -> 16-byte stack aligned mov r12, rdi ; r12 = ap_stacks_base mov r13d, esi ; r13d = max_cpus ; Clamp max_cpus to [1, ZAPP_MAX_CPUS] cmp r13d, ZAPP_MAX_CPUS jle .max_hi_ok mov r13d, ZAPP_MAX_CPUS .max_hi_ok: cmp r13d, 1 jge .max_lo_ok mov r13d, 1 .max_lo_ok: ; Zero shared job, generation, and per-worker completion slots cld xor eax, eax lea rdi, [rel g_job] mov ecx, 64 / 8 rep stosq lea rdi, [rel g_job_gen] mov ecx, 64 / 8 rep stosq lea rdi, [rel g_worker_done] mov ecx, (ZAPP_MAX_CPUS * 64) / 8 rep stosq mov dword [rel g_ctrl_sleep_flag], 1 mov qword [rel g_ctrl_online_mask], 1 ; Install lightweight IPI wakeup handler on vector 0x30 before starting APs mov edi, VEC_IPI_WAKE lea rsi, [rel isr_ipi_wake] mov edx, 0x8E ; Present | DPL 0 | 64-bit Interrupt Gate xor ecx, ecx ; IST = 0 call idt_set_gate ; Detect logical CPUs via CPUID mov edi, r13d call detect_logical_cpus mov r14d, eax ; r14d = n_det cmp r14d, 1 jg .boot_aps mov dword [rel g_ctrl_num_cpus], 1 mov dword [rel g_ctrl_active_cpus], 1 mov eax, 1 jmp .ret .boot_aps: ; Copy relocatable 16->32->64 AP trampoline to physical 0x8000 cld lea rsi, [rel ap_trampoline_start] lea rcx, [rel ap_trampoline_end] sub rcx, rsi mov edi, AP_TRAMP_PA rep movsb ; Populate static fields of AP control block at 0x8F00 mov edx, AP_CTRL_PA lea rax, [rel pml4_table] mov [rdx + 0x00], rax ; ctrl[0] = pml4_table lea rax, [rel zapp_ap_c_entry] mov [rdx + 0x08], rax ; ctrl[1] = &zapp_ap_c_entry lea rsi, [rel gdt64_ptr] lea rdi, [rdx + 0x20] mov ecx, 10 ; 10-byte GDTR rep movsb mov r15d, 1 ; r15d = online = 1 (BSP) mov ebx, 1 ; ebx = ap = 1 .ap_loop: ; ctrl[2] = ap_stacks_base + (uint64_t)(ap + 1) * AP_STACK_SIZE - 16 mov eax, ebx inc eax ; ap + 1 shl rax, 16 ; * 0x10000 add rax, r12 sub rax, 16 mov edx, AP_CTRL_PA mov [rdx + 0x10], rax ; ctrl[2] = stack_top_pa mov eax, ebx ; zero-extend ap to uint64_t mov [rdx + 0x18], rax ; ctrl[3] = tid mfence ; Send INIT IPI to target APIC ID call lapic_get_base mov ecx, ebx shl ecx, 24 mov dword [rax + LAPIC_ICR_HI], ecx mov dword [rax + LAPIC_ICR_LO], LAPIC_ICR_INIT .wait_init: test dword [rax + LAPIC_ICR_LO], LAPIC_ICR_BUSY jz .init_sent pause jmp .wait_init .init_sent: mov edi, AP_INIT_DELAY_TSC call busy_delay_tsc ; Send 1st SIPI (vector 0x08 -> 0x8000) call lapic_get_base mov ecx, ebx shl ecx, 24 mov dword [rax + LAPIC_ICR_HI], ecx mov dword [rax + LAPIC_ICR_LO], LAPIC_ICR_SIPI_08 .wait_sipi1: test dword [rax + LAPIC_ICR_LO], LAPIC_ICR_BUSY jz .sipi1_sent pause jmp .wait_sipi1 .sipi1_sent: mov edi, ebx call wait_ap_online test eax, eax jnz .ap_booted ; Retry with 2nd SIPI if AP did not come online on 1st SIPI call lapic_get_base mov ecx, ebx shl ecx, 24 mov dword [rax + LAPIC_ICR_HI], ecx mov dword [rax + LAPIC_ICR_LO], LAPIC_ICR_SIPI_08 mov edi, ebx call wait_ap_online test eax, eax jz .ap_boot_done ; failed -> stop booting further APs .ap_booted: inc r15d ; online++ inc ebx ; ap++ cmp ebx, r14d jl .ap_loop .ap_boot_done: ; Wipe temporary real-mode trampoline page (4096 bytes at 0x8000) cld xor eax, eax mov edi, AP_TRAMP_PA mov ecx, 4096 / 8 rep stosq mov [rel g_ctrl_num_cpus], r15d ; Default active workers: cap at 20 (tunable live via `threads `) mov eax, r15d cmp eax, 20 jle .active_ok mov eax, 20 .active_ok: mov [rel g_ctrl_active_cpus], eax mov dword [rel g_ctrl_sleep_flag], 1 mov eax, r15d ; return online .ret: pop r15 pop r14 pop r13 pop r12 pop rbx ret ; ============================================================================ ; int zapp_smp_num_cpus(void) ; ============================================================================ zapp_smp_num_cpus: mov eax, [rel g_ctrl_num_cpus] ret ; ============================================================================ ; int zapp_smp_active_cpus(void) ; ============================================================================ zapp_smp_active_cpus: mov eax, [rel g_ctrl_active_cpus] ret ; ============================================================================ ; void zapp_smp_set_active_cpus(int n) ; EDI = desired active worker count (clamped to [1, num_cpus]). ; ============================================================================ zapp_smp_set_active_cpus: cmp edi, 1 jge .lo_ok mov edi, 1 .lo_ok: mov eax, [rel g_ctrl_num_cpus] cmp edi, eax jle .hi_ok mov edi, eax .hi_ok: mov [rel g_ctrl_active_cpus], edi cmp dword [rel g_ctrl_sleep_flag], 0 jne .done cmp edi, 1 jle .done sub rsp, 8 ; 16-byte stack alignment mfence call broadcast_wake_ipi lea rdi, [rel smp_noop_fn] xor esi, esi call zapp_smp_dispatch add rsp, 8 .done: ret ; ============================================================================ ; void zapp_smp_wake(void) ; Wakes all active APs out of menu HLT into pure spin-barrier mode via a single ; broadcast Fixed IPI, then synchronizes them with a no-op barrier dispatch. ; ============================================================================ zapp_smp_wake: cmp dword [rel g_ctrl_num_cpus], 1 jle .done sub rsp, 8 ; 16-byte stack alignment mov qword [rel g_job_job_gen], 0 mov dword [rel g_ctrl_sleep_flag], 0 mfence call broadcast_wake_ipi lea rdi, [rel smp_noop_fn] xor esi, esi call zapp_smp_dispatch add rsp, 8 .done: ret ; ============================================================================ ; void zapp_smp_sleep(void) ; Signals all APs to exit the spin-barrier and park in atomic `sti; hlt; cli`. ; ============================================================================ zapp_smp_sleep: cmp dword [rel g_ctrl_num_cpus], 1 jle .done mov qword [rel g_job_job_gen], 0 mov dword [rel g_ctrl_sleep_flag], 1 .done: ret ; ============================================================================ ; void zapp_smp_dispatch(ZappParallelFn fn, void *ctx) ; RDI = fn, RSI = ctx. ; Publishes job descriptor + monotonic generation, runs slice 0 on BSP, then ; waits on per-CPU 64B-isolated completion slots [1 .. nact-1]. ; ============================================================================ align 16 zapp_smp_dispatch: mov eax, [rel g_ctrl_active_cpus] cmp eax, 1 jg .parallel ; Single-core fast path: tail-call fn(0, 1, ctx) mov rax, rdi ; fn mov rdx, rsi ; arg3: ctx xor edi, edi ; arg1: tid = 0 mov esi, 1 ; arg2: nthreads = 1 jmp rax .parallel: push rbx push r12 push r13 ; 3 pushes -> 16-byte stack aligned mov rbx, rdi ; rbx = fn mov r12, rsi ; r12 = ctx mov r13d, eax ; r13d = nact cmp dword [rel g_ctrl_sleep_flag], 0 je .awake call zapp_smp_wake .awake: mov rax, [rel g_job_gen] inc rax ; rax = next_gen mov [rel g_job_fn], rbx mov [rel g_job_ctx], r12 mov [rel g_job_nact], r13d mov [rel g_job_job_gen], rax ; publish job metadata before gen mov [rel g_job_gen], rax ; release spinning AP workers ; BSP executes slice 0 directly; reuse r12 to hold next_gen across call mov rdx, r12 ; arg3: ctx mov r12, rax ; r12 = next_gen mov rax, rbx ; rax = fn xor edi, edi ; arg1: tid = 0 mov esi, r13d ; arg2: nact call rax ; Wait on per-CPU 64B-isolated completion slots [1 .. nact-1] lea rcx, [rel g_worker_done + 64] mov edx, r13d dec edx ; remaining AP count = nact - 1 .wait_worker: cmp [rcx], r12 je .worker_done pause jmp .wait_worker .worker_done: add rcx, 64 dec edx jnz .wait_worker mov qword [rel g_job_job_gen], 0 pop r13 pop r12 pop rbx ret