/*
 * Copyright (C) 2017-2020 Alibaba Group Holding Limited
 */

 /****************************************************************************
 FILE_NAME           : arch_reg_save.S
 FUNCTION            : save the cpu context:
 ******************************************************************************/

#include <csi_config.h>

.global arch_do_cpu_save
.global arch_do_cpu_resume
.global arch_resume_context

#undef  CSKY_LPM_BASE
#define CSKY_LPM_BASE   0x40000000

arch_resume_context:
    mfcr    r0, cr<8, 3>
    bseti   r0, 1
    bseti   r0, 0
    mtcr    r0, cr<8, 3>

    lrw     r0, CSKY_LPM_BASE
    ldw     r1, (r0, 0x0)
    btsti   r1, 4
    bt      arch_sp_resume_from_standby

arch_sp_resume_from_stop:
    lrw     r0, g_arch_cpu_saved
    ldw     sp, (r0, 0x38)
    jbr     arch_do_cpu_resume

arch_sp_resume_from_standby:
    jbr     Reset_Handler

arch_do_cpu_save:
    subi    r14, 4
    stw     r0, (r14, 0x0)
    lrw     r0, g_arch_cpu_saved
    addi    r0, 4
    stm     r1-r31, (r0)
    subi    r0, 4
    addi    r0, 0x80
    fstms   vr0-vr15, (r0)
    subi    r0, 0x80
    mfcr    r2, psr
    stw     r2, (r0, 0xC0)
    mfcr    r2, vbr
    stw     r2, (r0, 0xC4)
    mfcr    r2, epsr
    stw     r2, (r0, 0xC8)
    mfcr    r2, epc
    stw     r2, (r0, 0xCC)
    /* save CCR */
    mfcr    r2, cr<18, 0>
    stw     r2, (r0, 0xD0)
    /* save CAPR */
    mfcr    r2, cr<19, 0>
    stw     r2, (r0, 0xD4)
    /* save PACR */
    mfcr    r2, cr<20, 0>
    stw     r2, (r0, 0xD8)
    /* save PRSR */
    mfcr    r2, cr<21, 0>
    stw     r2, (r0, 0xDC)
    /* save CHR */
    mfcr    r2, cr<31, 0>
    stw     r2, (r0, 0xE0)
    /* save User SP */
    mfcr    r2, cr<14, 1>
    stw     r2, (r0, 0xE4)
    /* save Int SP */
    mfcr    r2, cr<15, 1>
    stw     r2, (r0, 0xE8)
    /* save jtag */
    mfcr    r2, cr<8, 3>
    stw     r2, (r0, 0xEC)

    ldw     r2, (r14, 0x0)
    addi    r14, 4
    stw     r14, (r0, 0x38)
    stw     r2, (r0, 0x0)
    movi    r0, 0
    jmp     r15

arch_do_cpu_resume:
    lrw     r0, g_arch_cpu_saved
    ldw     r2, (r0, 0xEC)
    mtcr    r2, cr<8, 3>
    addi    r0, 4
    ldm     r1-r31, (r0)
    subi    r0, 4
    addi    r0, 0x80
    fldms   vr0-vr15, (r0)
    subi    r0, 0x80
    ldw     r2, (r0, 0xC0)
    mtcr    r2, psr
    ldw     r2, (r0, 0xC4)
    mtcr    r2, vbr
    ldw     r2, (r0, 0xC8)
    mtcr    r2, epsr
    ldw     r2, (r0, 0xCC)
    mtcr    r2, epc
    ldw     r2, (r0, 0xD0)
    mtcr    r2, cr<18, 0>
    ldw     r2, (r0, 0xD4)
    mtcr    r2, cr<19, 0>
    ldw     r2, (r0, 0xD8)
    mtcr    r2, cr<20, 0>
    ldw     r2, (r0, 0xDC)
    mtcr    r2, cr<21, 0>
    ldw     r2, (r0, 0xE0)
    mtcr    r2, cr<31, 0>
    ldw     r2, (r0, 0xE4)
    mtcr    r2, cr<14, 1>
    ldw     r2, (r0, 0xE8)
    mtcr    r2, cr<15, 1>
    ldw     r2, (r0, 0x8)
    ldw     r0, (r0, 0x0)
    movi    r0, 1
    jmp     r15
