/**
******************************************************************************************************************************************************************************************
*@file                       cpu_deepsleep_enter.c
*@author         
*@data                       
*@version                    v1.0
*@par Copyright(c):
*
*@par History:
*     version:author,date,desc
*     v1.0   :create this file
*
*******************************************************************************************************************************************************************************************
*/
#include "cpu.h"


__ASM void deep_sleep_enter(void)
{
	
FLAG_NEED_RECOVER		EQU		0x234
ADDR_FLAG_NEED_RECOVER	EQU		0x20000008
ADDR_PC					EQU		0x20000004	
ADDR_SP					EQU		0x20000010	
ADDR_PSR				EQU		0x2000000C

CACHE_ADDR_BD				EQU 	0x40005040
QSPI_ADDR_DEVICE_PARA		EQU 	0x40009014
QSPI_ADDR_CACHE_INIT_CMD	EQU 	0x40009038
QSPI_ADDR_IO_CTRL			EQU 	0x40009044

BK_CACHE_ADDR_BD				EQU 	0x20000014
BK_QSPI_ADDR_DEVICE_PARA		EQU 	0x20000018
BK_QSPI_ADDR_CACHE_INIT_CMD 	EQU 	0x2000001C
BK_QSPI_ADDR_IO_CTRL			EQU 	0x20000020

			//push r0-r12,r14,xpsr
			push {r0-r12,r14}
			MRS		R0,xPSR
			LDR		R1,=ADDR_PSR
			STR		R0,[R1]
			//load addr
			LDR		R0,=ADDR_FLAG_NEED_RECOVER
			LDR		R1,=ADDR_SP
			LDR		R2,=ADDR_PC

			//save pc,sp
			LDR R3,=START_RECOVER
			STR R3,[R2] //pc
			STR SP,[R1] //sp

			LDR	R8,=BK_CACHE_ADDR_BD
			LDR	R9,=CACHE_ADDR_BD
			LDR	R9,[R9]
			STR	R9,[R8]
			LDR	R8,=BK_QSPI_ADDR_DEVICE_PARA
			LDR	R9,=QSPI_ADDR_DEVICE_PARA
			LDR	R9,[R9]
			STR	R9,[R8]
			LDR	R8,=BK_QSPI_ADDR_CACHE_INIT_CMD
			LDR	R9,=QSPI_ADDR_CACHE_INIT_CMD
			LDR	R9,[R9]
			STR	R9,[R8]
			LDR	R8,=BK_QSPI_ADDR_IO_CTRL
			LDR	R9,=QSPI_ADDR_IO_CTRL
			LDR	R9,[R9]
			STR	R9,[R8]
				
			//write have saved flag
			MOV R4,#FLAG_NEED_RECOVER
			STR R4,[R0] 
			
			//save nvic
		
			// deepsleep
			WFI
			
START_RECOVER
			//RECOVER load Flag addr
			LDR		R0,=ADDR_FLAG_NEED_RECOVER
			
			//
			MOV R1,#0
			STR R1,[R0] //CANCLE FLAG
			
			LDR		R0,=ADDR_PSR
			LDR		R1,[R0]			
			MSR	xPSR,R1
			pop {r0-r12,r14}
			
			BX LR
			
}


