/**************************************************************************//**
 * @item     CosyOS-III Port
 * @file     port_x32.c
 * @brief    32 bits Micro-Controller Public Port File
 * @author   迟凯峰
 * @version  v3.0.0
 * @date     2026.07.21
 ******************************************************************************/

#include "os_var.h"
#ifdef __PORT_X32_H


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

/**
 \brief    FIFO互斥访问锁
 \details  入FIFO与出FIFO之间的互斥
 \note     if(锁) { 中断FIFO服务装载器入FIFO0，中断FIFO服务处理器出FIFO1 } <br>
           else   { 中断FIFO服务装载器入FIFO1，中断FIFO服务处理器出FIFO0 }
 */
bool volatile m_fifo_lock = true;

void *mPendSV_FIFO_0[SYSCFG_PENDSVFIFO_DEPTH + 1]; // FIFO0
void *mPendSV_FIFO_1[SYSCFG_PENDSVFIFO_DEPTH + 1]; // FIFO1

#if (SYSCFG_PENDSVFIFO_MONITOR == __ENABLED__)
s_u32_t mPendSV_FIFO_DepthMAX/**/sZeroInstall;
s_u16_t mPendSV_FIFO_CountMAX/**/sZeroInstall;
#endif

/* 中断FIFO服务处理器 */
void mPendSV_FIFOHandler(void)
{
	register s_u32_t i;
	register s_u16_t j = 0;
	register bool lock = 1;
	register void ** p;
	         void ** const fifo[2] = {mPendSV_FIFO_0, mPendSV_FIFO_1};
	
	while(true){
		lock = !lock;
		p = fifo[lock];
		m_fifo_lock = lock;
		__mx_MMB();
		
		if(p[0]){
			i = (s_u32_t)p[0];
			p[0] = 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 *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 == mPendSV_FIFO_0[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
