// +FHDR------------------------------------------------------------
//                 Copyright (c) 2022 SmartLogic.
//                       ALL RIGHTS RESERVED
// -----------------------------------------------------------------
// Filename      : pet_rfm_spu1_top.s.c
// Author        : xianfeng.du
// Created On    : 2022-06-25
// Last Modified :
// -----------------------------------------------------------------
// Description:
//
//
// -FHDR------------------------------------------------------------
#include "ucp_port.h"
#include "ucp_handshake.h"
#include "ucp_utility.h"
#include "pet_sm_mgt.h"
#include "msg_transfer_mem.h"
#include "spu_hw_queue.h"
#include "app_interface.h"
#include "ape_csu.h"

void phy_init(void);//phy application function:msg_transfer_cfg

ALWAYS_INLINE int32_t get_core_id(void)
{
	return PET_RFM_SPU1_CORE_ID;
}

void pet_rfm_spu1_drv_init(void)
{
    int32_t core_id = get_core_id();
    //pet_rfm_dm_alloc();

    pet_sm_alloc();
    ape_csu_init();
    ecs_hw_que_init(core_id);
    ecs_hw_que_init_withirq(core_id, core_id);
    ecs_msg_que_init(core_id);
    ecs_hw_que_init_noirq(core_id, ECS_RFM_SPU0_HW_QUEUE);

    return;
}

void pet_rfm_spu1_msg_transfer_init(void)
{
    msg_transfer_mem_alloc();

    handshake_slave_with_master();

    msg_transfer_queue_init();

    phy_init();//phy application function

    return;
}

void msg_transfer_queue_polling(void)
{
	uint8_t port_id = get_ucp_port_id();
	HandleId_t handler;
	uint16_t cu_flag;
	uint32_t offset = 0;
	uint32_t len = 0;
	uint8_t* msg_ptr;

    for (uint32_t i = 0; i < MAX_INSTANCE_NUM; i++) {
		handler.port_id = port_id;
		handler.inst_id = i;
		handler.type_id = CU_SPLIT;
		cu_flag = C_PLANE;
		msg_transfer_receive(handler.value, cu_flag, offset, len, &msg_ptr);

		cu_flag = U_PLANE;
		msg_transfer_receive(handler.value, cu_flag, offset, len, &msg_ptr);

		handler.type_id = OAM;
		msg_transfer_receive(handler.value, cu_flag, offset, len, &msg_ptr);
    }

    return;
}

void msg_transfer_enqueue(void)
{
	uint32_t value;
	int32_t ret = ecs_hw_que_recv(ECS_RFM_SPU0_HW_QUEUE, &value);
	if (SUCCESS != ret) {
		return;
	}

	uint8_t inst_id = (value & 0xff000000) >> 24;
	uint8_t que_id = (value & 0x00ff0000) >> 16;
	uint16_t buf_id = value & 0x0000ffff;

	PetSmLocalMgt_t* pPetSmLocalMgt = get_pet_sm_local_mgt();
	MsgQueueCommonInfo_t* chCommon = pPetSmLocalMgt->pUlQueue[inst_id][que_id];

	MsgQueueLocalMgt_t* pMsgQueueLocalMgt = get_msg_queue_local_mgt();
	MsgQueueLocalInfo_t* ch = (MsgQueueLocalInfo_t*)&pMsgQueueLocalMgt->localUlQueue[inst_id][que_id];
	uint16_t* pIdxBase = (uint16_t *)ch->bufIdxBase;

    ch->in = do_read(&chCommon->in);
    uint16_t idx = ch->in & ch->ringMask;
    do_write_short(&pIdxBase[idx],buf_id);
    do_write(&chCommon->in, (ch->in+1));

	__ucps2_synch(0);
	return;
}



