
#define CTX_SAVE_SP_BYTE_SIZE  80

.section .context_switch
.global CS_contextSave
.type CS_contextSave, %function
CS_contextSave:
    addi sp,  sp, -CTX_SAVE_SP_BYTE_SIZE
    sw   x1,  0(sp)
    sw   x2,  4(sp)
    sw   x3,  8(sp)
    sw   x4,  12(sp)
    sw   x5,  16(sp)
    sw   x6,  20(sp)
    sw   x7,  24(sp)
    sw   x8,  28(sp)
    sw   x9,  32(sp)
    sw   x10, 36(sp)
    sw   x11, 40(sp)
    sw   x12, 44(sp)
    sw   x13, 48(sp)
    sw   x14, 52(sp)
    sw   x15, 56(sp)
    //csrr x8,  mie
    csrr x9,  mtvt
    csrr x10, mtvec
    //csrr x11, mstatus
    //sw   x8,  60(sp)
    sw   x9,  64(sp)
    sw   x10, 68(sp)
    //sw   x11, 72(sp)

    // start sleep process
    //save sp to 0x40080024
    li   a0,  0x40080024 // AON_CTRL->SOFT_RECORD1
    sw   sp,  0(a0)

    // start sleep
    li   a0,  0x40080048 /* setup the  AON_CTRL->GOSLEEP = 1 */
    li   a1,  1
    sw   a1,  0(a0)

    wfi

.global CS_contextRestore
.type CS_contextRestore, %function
CS_contextRestore:
/*
    li a0, 0x40000104
    sw x0, 0(a0)
*/
    li    a0, 0x40080080
    lw    a0, 0(a0)
    li    a1, 8
    and   a0, a0, a1
    beqz  a0, __normal /* is not watch dog reset */
    li    a0, 0x40080020
    sw    x0, 0(a0)   /* set PC to 0 */
    li    a0, 0x40080084
    li    a1, 0xA
    sw    a1, 0(a0)   /* clr wdg/deep sleep reset flag */
    li    a0, 0x40000008
    li    a1, 1
    sw    a1, 0(a0)   /* reset system */
    wfi
__normal:
    // restore sp from 0x40080024
    li   a0,  0x40080024 // AON_CTRL->SOFT_RECORD1
    lw   a1,  0(a0)
    mv   sp,  a1

    //lw   x8,   60(sp)
    lw   x9,   64(sp)
    lw   x10,  68(sp)
    //lw   x11,  72(sp)
    //csrw mie,     x8
    csrw mtvt,    x9
    csrw mtvec,   x10
    //csrw mstatus, x11

    lw   x1,  0(sp)
    lw   x2,  4(sp)
    lw   x3,  8(sp)
    lw   x4,  12(sp)
    lw   x5,  16(sp)
    lw   x6,  20(sp)
    lw   x7,  24(sp)
    lw   x8,  28(sp)
    lw   x9,  32(sp)
    lw   x10, 36(sp)
    lw   x11, 40(sp)
    lw   x12, 44(sp)
    lw   x13, 48(sp)
    lw   x14, 52(sp)
    lw   x15, 56(sp)
    addi sp,  sp, CTX_SAVE_SP_BYTE_SIZE

    ret
