/* MARKUS MAIWALD (ARCHITECT) | VOXIS FORGE (AI)
   RUMPK HAL // CONTEXT SWITCH
   
   System V ABI (AArch64) requires we save:
   - x19..x28 (Callee-saved general purpose)
   - x29 (Frame Pointer)
   - x30 (Link Register / Return Address)
   
   Frame Size: 6 pairs * 16 bytes = 96 bytes (16-byte aligned!)
*/

.global cpu_switch_to
.type cpu_switch_to, @function

// void cpu_switch_to(uint64_t* prev_sp_ptr, uint64_t next_sp);
// x0 = pointer to storage for old stack pointer
// x1 = new stack pointer value

cpu_switch_to:
    // 1. Save Context (96 bytes = 16-byte aligned)
    sub sp, sp, #96
    
    stp x19, x20, [sp, #0]
    stp x21, x22, [sp, #16]
    stp x23, x24, [sp, #32]
    stp x25, x26, [sp, #48]
    stp x27, x28, [sp, #64]
    stp x29, x30, [sp, #80]
    
    // 2. Save Old SP
    mov x9, sp
    str x9, [x0]

    // 3. Load New SP
    mov sp, x1
    
    // 4. Restore Context
    ldp x19, x20, [sp, #0]
    ldp x21, x22, [sp, #16]
    ldp x23, x24, [sp, #32]
    ldp x25, x26, [sp, #48]
    ldp x27, x28, [sp, #64]
    ldp x29, x30, [sp, #80]
    
    add sp, sp, #96
    
    ret
