/**************************************************************************//**
 * @item     CosyOS-III Port
 * @file     port_80251.c
 * @brief    80251 Core Port File
 * @author   迟凯峰
 * @version  v3.0.0
 * @date     2026.07.21
 ******************************************************************************/

#include "os_var.h"
#ifdef __PORT_80251_H

s_u16_t _SYS_MEM_ m_bsp_add = sizeof(s_taskload_ts);
static s_u8_t xdata mVOID _at_ 0;


/*
 * 栈监控（涵盖主栈和任务栈）
 */
#if (SYSCFG_DEBUGGING == __ENABLED__)
s_u16_t data m_taskstacklen;
#if (MCUCFG_TASKSTACK_MODE == __MSP__)
s_u16_t m_msp;
s_u16_t m_stacksize;
s_u16_t m_stacklen_max/**/sZeroInstall;
#endif
#endif


/*
 * 中断FIFO服务
 */
#if (SYSCFG_PENDSVFIFO_DEPTH > 0)

#if (MCUCFG_PENDSVFIFO_MUTEX < 0x80) \
 || (MCUCFG_PENDSVFIFO_MUTEX > 0xFF)
void _STATIC_MEM_ *mPendSV_FIFO_0[SYSCFG_PENDSVFIFO_DEPTH] _at_ 0x0100; // FIFO0
void _STATIC_MEM_ *mPendSV_FIFO_1[SYSCFG_PENDSVFIFO_DEPTH] _at_ 0x0200; // FIFO1
#else
void _STATIC_MEM_ *mPendSV_FIFO_0[SYSCFG_PENDSVFIFO_DEPTH] _at_ 0x0100/**/sZeroInstall_Group;
void _STATIC_MEM_ *mPendSV_FIFO_1[SYSCFG_PENDSVFIFO_DEPTH] _at_ 0x0200/**/sZeroInstall_Group;
#endif


/*
 * [INC]指令 和 关闭总中断
 */
#if (MCUCFG_PENDSVFIFO_MUTEX < 0x100)

/* FIFO计数器 */
s_u8_t data m_fifo_count[2]/**/sZeroInstall_Group;

/* 中断FIFO服务处理器 */
void mPendSV_FIFOHandler(void)
{
	register s_u8_t i;
	register s_u16_t j = 0;
	register bool lock = 1;
	register void _STATIC_MEM_ * _STATIC_MEM_ * p;
	         void _STATIC_MEM_ * _STATIC_MEM_ * const fifo[2] = {
	              mPendSV_FIFO_0 - 1,
	              mPendSV_FIFO_1 - 1
	         };
	
	while(true){
		lock = !lock;
		p = fifo[lock];
		m_fifo_lock = lock;
		__mx_MMB();
		
		if(m_fifo_count[lock]){
			i = m_fifo_count[lock];
			m_fifo_count[lock] = 0;
			#if (SYSCFG_PENDSVFIFO_MONITOR == __ENABLED__)
			if(i > mPendSV_FIFO_DepthMAX){
				mPendSV_FIFO_DepthMAX = i;
			}
			#endif
			if(i > SYSCFG_PENDSVFIFO_DEPTH){
				i = SYSCFG_PENDSVFIFO_DEPTH;
				#if (SYSCFG_PENDSVFIFO_MONITOR == __ENABLED__)
				s_fault.overflow_pendsvfifo = true;
				#endif
			}
			j += i;
			do{
				register void _STATIC_MEM_ *sv = *++p;
				#if (MCUCFG_PENDSVFIFO_MUTEX < 0x80)
				(*sPendSV_FIFOHandler[*(s_u8_t const *)sv])(sv);
				#else
				if(sv != OS_NULL){
					*p = OS_NULL;
					(*sPendSV_FIFOHandler[*(s_u8_t const *)sv])(sv);
				}
				#endif
			}while(--i);
		}
		
		if(lock){
			if(0 == m_fifo_count[0]) break;
			if(j >= SYSCFG_PENDSVFIFO_COUNT) break;
		}
	}
	
	#if (SYSCFG_PENDSVFIFO_MONITOR == __ENABLED__)
	if(mPendSV_FIFO_CountMAX < j) mPendSV_FIFO_CountMAX = j;
	#endif
}

#endif
#endif


#endif
