/**************************************************************************//**
 * @item     CosyOS-III Port
 * @file     port_x51.h
 * @brief    80x51 Core Port File
 * @author   迟凯峰
 * @version  v3.0.0
 * @date     2026.07.21
 ******************************************************************************/

#ifndef __PORT_X51_H
#define __PORT_X51_H

/* INCLUDE */
#include "syscfg.h"
#include "os_def.h"
#include <intrins.h>


/* Typedef */
typedef char  s_s8_t;
typedef short s_s16_t;
typedef long  s_s32_t;
typedef unsigned char  s_u8_t;
typedef unsigned short s_u16_t;
typedef unsigned long  s_u32_t;
typedef s_u8_t   bool;
typedef bit      m_bit_t;
typedef s_u32_t  m_group_t;
#if (SYSCFG_SYSTICK_CYCLE > 1000000UL / 65536)
typedef s_u16_t  m_rtccount_t;
#else
typedef s_u32_t  m_rtccount_t;
#endif


/* Extern */
extern  void     mx_disable_irq(void);
extern  void     mx_resume_irq (void);
#if (SYSCFG_PENDSVFIFO_DEPTH > 0)
extern  bit      m_sign_fifo_0_0;
extern  bit           m_fifo_lock;
extern  s_u8_t   data m_fifo_count[2];
extern  s_u8_t   mPendSV_FIFO_DepthMAX;
extern  s_u16_t  mPendSV_FIFO_CountMAX;
extern  void     mPendSV_FIFOHandler(void);
#endif


/* CONST & ATTRIBUTE */
#define MCUCFG_STACK_ALIGN


/* SysTick */
#define MCUCFG_SYSTICK_COUNTMODE    3                /*!< 计数方式，3：从重装载值向上计数至零溢出 */
#define MCUCFG_SYSTICK_LIMITVALUE  (1UL << 16)       /*!< 极限值 */
#define MCUCFG_SYSTICK_CLKDIV     ((MCUCFG_SYSCLKHZ / 1000UL * SYSCFG_SYSTICK_CYCLE <= MCUCFG_SYSTICK_MAXVALUE * 1000UL) ? 1 : 12)
#define MCUCFG_SYSTICK_COUNT1CYC  ((MCUCFG_SYSCLKHZ / 1000UL * SYSCFG_SYSTICK_CYCLE) / MCUCFG_SYSTICK_CLKDIV   / 1000UL)
#define MCUCFG_SYSTICK_LOADVALUE   (MCUCFG_SYSTICK_LIMITVALUE - MCUCFG_SYSTICK_COUNT1CYC)
#define MCUCFG_SYSTICK_MAXVALUE     MCUCFG_SYSTICK_LIMITVALUE
#define MCUCFG_SYSTICK_MINVALUE     MCUCFG_SYSTICK_LOADVALUE


/* 内核锁 */
#define mSysIRQ_Disable() \
do{ \
	mPendSV_Disable(); \
	mSysTick_Disable(); \
}while(false)

#define mSysIRQ_Enable() \
do{ \
	mSysTick_Enable(); \
	mPendSV_Enable(); \
}while(false)


/* CosyOS初始化 */
#define mCosyOS_INIT() \
do{ \
	s_init_mempool((void _MALLOC_MEM_ *)MCUCFG_MALLOCMEMBPTR, MCUCFG_MALLOCMEMSIZE); \
	OS_NOP(1); \
	mSysTick_INIT(); \
	EA = 1; \
}while(false)


/* CosyOS低功耗 */
#define mCosyOS_IDLE() \
do{ \
	PCON |= 0x01; \
	OS_NOP(4); \
}while(false)


/* 全局临界区 */
#define mxDisableIRQ()  mx_disable_irq()
#define mxResumeIRQ()   mx_resume_irq()


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


#endif
