/* MARKUS MAIWALD (ARCHITECT) | VOXIS FORGE (AI)
   RUMPK HAL // X86_64 CONTEXT SWITCH
   
   System V ABI (x86_64) Callee-Saved:
   - rbx, rbp, r12, r13, r14, r15
   - rip is saved by CALL instruction (on stack)
   
   Frame: 6 regs * 8 = 48 bytes + 8 (RIP) = 56, aligned to 64
*/

.global cpu_switch_to
.type cpu_switch_to, @function

// void cpu_switch_to(uint64_t* prev_sp_ptr, uint64_t next_sp);
// rdi = prev_sp_ptr
// rsi = next_sp

cpu_switch_to:
    // 1. Save Callee-Saved Registers (48 bytes)
    pushq %rbp
    pushq %rbx
    pushq %r12
    pushq %r13
    pushq %r14
    pushq %r15
    
    // 2. Save Old Stack Pointer to *rdi
    movq %rsp, (%rdi)
    
    // 3. Load New Stack Pointer from rsi
    movq %rsi, %rsp
    
    // 4. Restore Callee-Saved Registers
    popq %r15
    popq %r14
    popq %r13
    popq %r12
    popq %rbx
    popq %rbp
    
    // 5. Return (pops RIP from stack)
    ret
