/**************************************************************************//**
 * @item     CosyOS-III Port
 * @file     port_cmx.h
 * @brief    CMSIS Cortex-M Core Port File
 * @author   迟凯峰
 * @version  v3.0.0
 * @date     2026.07.21
 ******************************************************************************/

#ifndef __PORT_CMX_H
#define __PORT_CMX_H

/* INCLUDE */
#include "port_x32.h"
#include "mcucfg_cm0.h"
#include "mcucfg_cm3.h"
#include SYSCFG_STANDARDHEAD
#include "os_cmsis.h"
#include "os_stack.h"


/* 互斥访问机制 */
#if (SYSCFG_PENDSVFIFO_DEPTH > 0) && (MCUCFG_PENDSVFIFO_MUTEX == 0xFF)
extern  void *mPendSV_FIFO_X;
#define mPendSV_FIFO_rx r6

/*
 * Arm Compiler 4/5
 */
#if defined ( __CC_ARM )
/* For Arm Compiler 4/5, CosyOS has already defined the register variable r6. */
register void **mPendSV_FIFO_REGx __ASM(sDefStr(mPendSV_FIFO_rx));

/*
 * Arm Compiler 6.6 LTM / above 6.10.1 (armclang)
 */
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
/* For Arm Compiler 6, please set -ffixed-r6, use Project > Options > C/C++ (AC6) > Misc Controls. */

/*
 * GNU Compiler
 */
#elif defined ( __GNUC__ )
/* For GNU Compiler, CosyOS has already defined the register variable r6. */
__extension__ register void **mPendSV_FIFO_REGx __ASM(sDefStr(mPendSV_FIFO_rx));

/*
 * IAR Compiler
 */
#elif defined ( __ICCARM__ )
/* For IAR Compiler, please set --lock_regs=r6, use Project > Options > C/C++ Compiler > Extra Options. */

/*
 * Other Compiler
 */
#else
/* For Other Compiler, please reset the option in mcucfg_cmx.h > 互斥访问方案. */
#endif
#endif


/* CONST & ATTRIBUTE */
#define MCUCFG_STACK_ALIGN        __ALIGNED(8)
#define MCUCFG_TASKSTACK_REALLOC  __DISABLED__
#if (MCUCFG_ASPEN_LSPEN == __ENABLED__)
#define MCUCFG_CALLER_PUSH_FPU    (18 * 4) /** \push   {s0-s15,FPSCR,UNKNOW} */
#define MCUCFG_CALLEE_PUSH_FPU    (16 * 4) /** \vstmdb {s16-s31} */
#else
#define MCUCFG_CALLER_PUSH_FPU     0
#define MCUCFG_CALLEE_PUSH_FPU     0
#endif
#define MCUCFG_CALLER_PUSH_REG    (8 * 4)  /** \push   {r0-r3,r12,r14(lr),r15(pc),xPSR} */
#define MCUCFG_CALLEE_PUSH_REG    (8 * 4)  /** \stmdb  {r4-r11} */
#define MCUCFG_CALLER_PUSH        (MCUCFG_CALLER_PUSH_FPU + MCUCFG_CALLER_PUSH_REG)
#define MCUCFG_CALLEE_PUSH        (MCUCFG_CALLEE_PUSH_FPU + MCUCFG_CALLEE_PUSH_REG)
#define MCUCFG_BASICSTACKSIZE     (MCUCFG_CALLER_PUSH + MCUCFG_CALLEE_PUSH)


/* TaskCtrl */
#define mTaskCtrl_Head_           m_sp_t psp;
#define mTaskCtrl_Tail_           m_sp_t psp_top;


/*
 * SysTick
 */
#if (MCUCFG_SYSTICK_AUTOCONFIG == __ENABLED__)
/* 自动配置 */
#define MCUCFG_SYSTICK_COUNTMODE   2             /*!< 计数方式，2：从重装载值向下计数至零溢出 */
#define MCUCFG_SYSTICK_LIMITVALUE (1UL << 24)    /*!< 极限值 */
#define MCUCFG_SYSTICK_CURRVALUE  (SysTick->VAL) /*!< 当前值寄存器 */
#define MCUCFG_SYSTICK_CLKDIV     (MCUCFG_SYSTICK_CLKSOURCE ? 1 : 8)
#define MCUCFG_SYSTICK_CLK        (MCUCFG_SYSCLK / MCUCFG_SYSTICK_CLKDIV)
#define MCUCFG_SYSTICK_COUNT1CYC  (SYSCFG_SYSTICK_CYCLE * MCUCFG_SYSTICK_CLK * 1UL)
#define MCUCFG_SYSTICK_LOADVALUE  (MCUCFG_SYSTICK_COUNT1CYC - 1)
#define MCUCFG_SYSTICK_MAXVALUE    MCUCFG_SYSTICK_LOADVALUE
#define MCUCFG_SYSTICK_MINVALUE    0
#if (MCUCFG_SYSCLK % MCUCFG_SYSTICK_CLKDIV)
#warning 系统滴答时钟不为整数。
#endif
#if (MCUCFG_SYSTICK_COUNT1CYC > MCUCFG_SYSTICK_LIMITVALUE)
#error 系统滴答定时器溢出。
#endif
#define mSysTick_SetLOAD()        SysTick->LOAD = MCUCFG_SYSTICK_LOADVALUE
#define mSysTick_SetCTRL()        SysTick->CTRL = ((MCUCFG_SYSTICK_CLKSOURCE ? 0x04 : 0x00) | 0x02 | 0x01)
#define mSysTick_INIT() \
do{ \
	mSysTick_SetPRI(); \
	mSysTick_SetLOAD(); \
	mSysTick_SetCTRL(); \
}while(false)

#else
/* 手动配置 */
  #if (MCUCFG_SYSTICK_COUNTMODE == 1 || MCUCFG_SYSTICK_COUNTMODE == 2)
#define MCUCFG_SYSTICK_MAXVALUE   (MCUCFG_SYSTICK_LOADVALUE)
#define MCUCFG_SYSTICK_MINVALUE    0
#define MCUCFG_SYSTICK_COUNT1CYC  (MCUCFG_SYSTICK_LOADVALUE + 1UL)

#elif (MCUCFG_SYSTICK_COUNTMODE == 3 || MCUCFG_SYSTICK_COUNTMODE == 4)
#define MCUCFG_SYSTICK_LIMITVALUE (1UL << MCUCFG_SYSTICK_BITS)
#define MCUCFG_SYSTICK_MAXVALUE   (MCUCFG_SYSTICK_LIMITVALUE)
#define MCUCFG_SYSTICK_MINVALUE   (MCUCFG_SYSTICK_LOADVALUE)
#define MCUCFG_SYSTICK_COUNT1CYC  (MCUCFG_SYSTICK_MAXVALUE - MCUCFG_SYSTICK_MINVALUE)
#endif

#define mSysTick_INIT()  mSysTick_SetPRI()
#endif


/*
 * SysTick_Handler + PendSV_Handler
 */
#if (MCUCFG_SYSINT == 3)
/* SysTick */
#define mSysTick_SetPRI() *(volatile s_u8_t  *)0xE000ED23 = 0xFF

/* PendSV */
#define mPendSV_SetPRI()  *(volatile s_u8_t  *)0xE000ED22 = 0xFF
#define mPendSV_Set()     *(volatile s_u32_t *)0xE000ED04 = 0x10000000
#define mPendSV_Clear()
#define mPendSV_INIT()    mPendSV_SetPRI()

/* 内核锁 */
__STATIC_FORCEINLINE void __mu_disable_sysirq(void)
{
	__set_BASEPRI(0xFF);
	__ASM("dsb");
	__ASM("isb");
}

__STATIC_FORCEINLINE void __mu_enable_sysirq(void)
{
	__ASM("dsb");
	__set_BASEPRI(0);
}


/*
 * TIMn_IRQHandler + XXXx_IRQHandler
 */
#elif (MCUCFG_SYSINT == 0)
/* SysTick */
#define mSysTick_SetPRI() \
	*(volatile s_u32_t *)(0xE000E400 + MCUCFG_TIMn_IRQn /  4 * 4)|= 0xFFUL << (MCUCFG_TIMn_IRQn %  4) * 8

/* PendSV */
#define mPendSV_SetPRI() \
	*(volatile s_u32_t *)(0xE000E400 + MCUCFG_XXXx_IRQn /  4 * 4)|= 0xFFUL << (MCUCFG_XXXx_IRQn %  4) * 8

#define mPendSV_Set() \
	*(volatile s_u32_t *)(0xE000E200 + MCUCFG_XXXx_IRQn / 32 * 4) = 0x01UL << (MCUCFG_XXXx_IRQn % 32)

#define mPendSV_Clear() \
	*(volatile s_u32_t *)(0xE000E280 + MCUCFG_XXXx_IRQn / 32 * 4) = 0x01UL << (MCUCFG_XXXx_IRQn % 32)

#define mPendSV_INIT()   mPendSV_SetPRI()

/* 内核锁 */
#define mSysINT_Disable() \
	*(volatile s_u32_t *)(0xE000E180 + MCUCFG_XXXx_IRQn / 32 * 4) = (0x01UL << (MCUCFG_XXXx_IRQn % 32)) \
                                                                  | (0x01UL << (MCUCFG_TIMn_IRQn % 32))
#define mSysINT_Enable() \
	*(volatile s_u32_t *)(0xE000E100 + MCUCFG_XXXx_IRQn / 32 * 4) = (0x01UL << (MCUCFG_XXXx_IRQn % 32)) \
                                                                  | (0x01UL << (MCUCFG_TIMn_IRQn % 32))
__STATIC_FORCEINLINE void __mu_disable_sysirq(void)
{
	mSysINT_Disable();
	__ASM("dsb");
	__ASM("isb");
}

__STATIC_FORCEINLINE void __mu_enable_sysirq(void)
{
	__ASM("dsb");
	mSysINT_Enable();
}

#endif


/* CCR：栈8字节对齐 */
#define mCCR_Set() \
do{ \
	*(volatile s_u32_t *)0xE000ED14 |= 0x0200; \
}while(false)


/*
 * FPU
 */

/* CPACR: CP11|CP10 */
#if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) \
 &&  (defined (__FPU_USED   ) && (__FPU_USED    == 1U)))
#define mCPACR_Set() \
do{ \
	*(volatile s_u32_t *)0xE000ED88 |= (0x0FUL << 20); \
}while(false)
#else
#define mCPACR_Set()
#endif

/* FPCCR: ASPEN|LSPEN */
#if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) \
 &&  (defined (__FPU_USED   ) && (__FPU_USED    == 1U)))
#if (MCUCFG_ASPEN_LSPEN == 1)
#define mFPCCR_Set() \
do{ \
	*(volatile s_u32_t *)0xE000EF34 |= (0x03UL << 30); \
}while(false)
#else
#define mFPCCR_Set() \
do{ \
	*(volatile s_u32_t *)0xE000EF34 &=~(0x03UL << 30); \
}while(false)
#endif
#else
#define mFPCCR_Set()
#endif

/* FPSCR */
#if ((MCUCFG_ASPEN_LSPEN == 1) \
 && ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) \
 &&  (defined (__FPU_USED   ) && (__FPU_USED    == 1U))))
#define mFPSCR_INIT() \
do{ \
	*(volatile s_u32_t *)(node_news->psp - 8) = __get_FPSCR(); \
}while(false)
#else
#define mFPSCR_INIT()
#endif


/* CosyOS初始化 */
#define mCosyOS_INIT() \
do{ \
	__ASM("cpsid i"); \
	mCCR_Set(); \
	mCPACR_Set(); \
	mFPCCR_Set(); \
	mPendSV_INIT(); \
	mSysTick_INIT(); \
	__set_PSP(__get_MSP() - 2 * MCUCFG_BASICSTACKSIZE); \
	__set_CONTROL(0x02); \
	__ASM("dsb"); \
	__ASM("isb"); \
	__ASM("cpsie i"); \
}while(false)


/* CosyOS低功耗 */
#define mCosyOS_IDLE()  __WFI()


/* 任务栈 */
#define MCUCFG_TASKSTACK_MODE __MSP_PSP__

#define mTaskStack_Init() \
do{ \
	node_news->psp_top = (m_sp_t)node_news->bsp + node_news->stacksize; \
	if(node_news->psp_top % 8){ \
		node_news->psp_top /= 8; \
		node_news->psp_top *= 8; \
		node_news->stacksize = node_news->psp_top - (m_sp_t)node_news->bsp; \
	} \
	mTaskStack_CheckInit(); \
	mTaskStack_Reset(); \
}while(false)

#define mTaskStack_Reset() \
do{ \
	node_news->psp = node_news->psp_top; \
	mFPSCR_INIT(); /* FPSCR */ \
	*(volatile s_u32_t *)(node_news->psp - MCUCFG_CALLER_PUSH_FPU - 4) = 0x01000000; /* xPSR */ \
	*(volatile s_u32_t *)(node_news->psp - MCUCFG_CALLER_PUSH_FPU - 8) = (s_u32_t)node_news->entry; /* r15(pc) */ \
	node_news->psp -= MCUCFG_BASICSTACKSIZE; \
}while(false)

/* 栈监控 */
#if (SYSCFG_DEBUGGING == __ENABLED__)

extern s_u32_t m_msp;
extern s_u32_t m_stacksize;
extern s_u32_t m_stacklen_max;

#if defined ( __ICCARM__ )
#define mMainStack_CheckInit() \
do{ \
	extern uint32_t CSTACK$$Base; \
	extern uint32_t CSTACK$$Limit; \
	m_msp = (uint32_t)&CSTACK$$Limit; \
	m_stacksize = (uint32_t)&CSTACK$$Limit - (uint32_t)&CSTACK$$Base; \
	s_stack_check_init((s_u8_t *)(m_msp - 64), m_stacksize - 64); \
}while(false)
#else
#define mMainStack_CheckInit(size) \
do{ \
	m_msp = __get_MSP(); \
	m_stacksize = size; \
	s_stack_check_init((s_u8_t *)(m_msp - 64), size - 64); \
}while(false)
#endif

#define mTaskStack_Check0()    s_task_current->psp_top - __get_PSP() + MCUCFG_CALLEE_PUSH
#define mMainStack_Check()     s_stack_check((s_u8_t *)m_msp, m_stacksize)
#define mTaskStack_Check()     s_stack_check((s_u8_t *)(s_task_current->psp_top), s_task_current->stacksize)
#define mTaskStack_CheckInit() s_stack_check_init((s_u8_t *)(node_news->psp_top), node_news->stacksize)

#else
#define mTaskStack_CheckInit()
#endif


/* 全局临界区 */
__STATIC_INLINE s_u32_t __mx_disable_irq(void)
{
	register s_u32_t oldirq = __get_PRIMASK();
	__ASM("cpsid i");
	__ASM("nop");
	return oldirq;
}
#define mxDisableIRQ()            __mx_disable_irq()
#define mxResumeIRQ(oldirq)       __set_PRIMASK(oldirq)

#if ((MCUCFG_SYSINT == 0) \
 && ((defined (__ARM_ARCH_7M__       ) && (__ARM_ARCH_7M__        == 1)) \
 ||  (defined (__ARM_ARCH_7EM__      ) && (__ARM_ARCH_7EM__       == 1)) \
 ||  (defined (__ARM_ARCH_8M_MAIN__  ) && (__ARM_ARCH_8M_MAIN__   == 1)) \
 ||  (defined (__ARM_ARCH_8_1M_MAIN__) && (__ARM_ARCH_8_1M_MAIN__ == 1))))
__STATIC_INLINE s_u32_t __mx_masking_pri(s_u32_t newpri)
{
	register s_u32_t oldpri = __get_BASEPRI();
	__set_BASEPRI_MAX(newpri << 4);
	__ASM("dsb");
	__ASM("isb");
	return oldpri;
}
#define mxMaskingPRI(newpri)      __mx_masking_pri(newpri)
#define mxResumePRI(oldpri)       __set_BASEPRI(oldpri)
#endif


/* 内存访问屏障 */
#define __mx_MMB()  __DMB()


#endif
