#include "ctc_intr.h"

#include "ucp_sfr_c.h"

#include "ucp_utility.h"
#include "ucp_printf.h"
#include "phy_para.h"

#ifdef APE_INT
#include "smartos.h"
#endif
#ifdef RFM_INT
#include "inter_vector.h"
#endif

extern stSfnPara 		gSfnPara;
extern stSfnPara		gCellSfnPara[2];
extern stPhyScsPara*	phyPara;

ddr_spinlock_t gSpinLockCtcInit;

int32_t ctc_cal_intr_init(void)
{
    int32_t apeId = get_core_id();
	//uint32_t errAddr = 0;
	int32_t ret = 0;

    if (11 == apeId)
    {
        do_write(CTC_INT_TYPE_ADDR, CTC_INT_TYPE_NULL);
    }
    else if (((0 <= apeId) && (7 >= apeId)) || (10 == apeId))
    {
#if 1
		gSpinLockCtcInit.lock_addr = 0xB7FD1480;
		gSpinLockCtcInit.flag_addr = 0xB7FD1484;
		smart_ddr_spinlock_init(&gSpinLockCtcInit);
#else
		gSpinLockCtcInit.lock_addr = DBG_DDR_SPIN_ADDR_BASE + LOCK_DDR_CTC*DBG_DDR_SPIN_LEN; // 0xB7FD1420;
		gSpinLockCtcInit.flag_addr = DBG_DDR_SPIN_ADDR_BASE + LOCK_DDR_CTC*DBG_DDR_SPIN_LEN + 0x4; // 0xB7FD1424;
		errAddr = DBG_DDR_SPIN_ADDR_BASE + LOCK_DDR_CTC*DBG_DDR_SPIN_LEN + 0x40 + (apeId<<2);
		ret = smart_ddr_spinlock_init(&gSpinLockCtcInit);
		if (0 != ret)
		{
			debug_write(errAddr, ret);
			return -1;
		}
#endif		
        int32_t ctcIntNum = CTC_CAL_INT_APE0 + apeId;
		smart_ddr_spinlock(&gSpinLockCtcInit);
        ret = smart_irq_request(ctcIntNum, isr_ctc_cal);
		smart_ddr_spinunlock(&gSpinLockCtcInit);
        if (0 != ret)
        {
            UCP_PRINT_EMPTY("attach int num: 0x%x error. errno = 0x%x. \r\n", ctcIntNum, ret);
            // debug write
            debug_write(DBG_DDR_ERR_IDX(apeId, 33), ret);
            return -1;
        }
    }

    return 0;
}

int32_t set_ctc_cal_int(int32_t dstCore)
{
	do_write(((uint32_t*)(&SYSC_CTC28_REG)+dstCore), 1);

	return 0;
}

int32_t gCtcCalIntCnt = 0;
void isr_ctc_cal(void)
{
	int32_t apeId = get_core_id();
	gCtcCalIntCnt++;
	debug_write((DBG_DDR_IDX_DRV_BASE+512+apeId), gCtcCalIntCnt);
	debug_write((DBG_DDR_IDX_DRV_BASE+524+apeId), GET_STC_CNT()); // 0x830
	
	int32_t type = do_read_volatile(CTC_INT_TYPE_ADDR);
	if ((CTC_INT_TYPE_CAL_SCS0 == type) || (CTC_INT_TYPE_CAL_SCS1 == type))
	{
		do_write(((uint32_t*)(&SYSC_CTC28_REG)+apeId), 0); // clear int
		gCellSfnPara[type-1].ctcIntFlag = 1;
	}
}

