#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 uint32_t 			gMtimerId;
extern stPhyScsPara*	phyPara;

ddr_spinlock_t gSpinLockCtcInit;

int32_t ctc_cal_intr_init(void)
{
    int32_t apeId = get_core_id();

    if (11 == apeId)
    {
        do_write(CTC_INT_TYPE_ADDR, CTC_INT_TYPE_NULL);
    }
    else if (((0 <= apeId) && (7 >= apeId)) || (10 == apeId))
    {
		gSpinLockCtcInit.lock_addr = 0xB7FD1420;
		gSpinLockCtcInit.flag_addr = 0xB7FD1424;
		//gSpinLockCtcInit.spin_lock_addr = 0xB7FD1428;
		//gSpinLockCtcInit.lock_w_addr = 0xB7FD142C;
		//gSpinLockCtcInit.lock_loop_addr = 0xB7FD1430;
		//gSpinLockCtcInit.unlock_loop_addr = 0xB7FD1434;
		//gSpinLockCtcInit.unlock_addr = 0xB7FD1438;
		smart_ddr_spin_lock_init(&gSpinLockCtcInit);
		
        int32_t ctcIntNum = CTC_CAL_INT_APE0 + apeId;
		smart_ddr_spinlock(&gSpinLockCtcInit);
        int32_t 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;
#if 0
		int32_t scsId = gCellSfnPara[gMtimerId].scsId;
		gCellSfnPara[gMtimerId].txSfnNum = do_read_volatile(&(phyPara[scsId].txSfnNum));
		gCellSfnPara[gMtimerId].rxSfnNum = do_read_volatile(&(phyPara[scsId].rxSfnNum));
		gCellSfnPara[gMtimerId].txSlotNum = do_read_volatile(&(phyPara[scsId].txSlotNum));
		gCellSfnPara[gMtimerId].rxSlotNum = do_read_volatile(&(phyPara[scsId].rxSlotNum));
#endif
	}
}

