// +FHDR------------------------------------------------------------
//                 Copyright (c) 2022 SmartLogic.
//                       ALL RIGHTS RESERVED
// -----------------------------------------------------------------
// Filename      : ucp_handshake.c
// Author        : xianfeng.du
// Created On    : 2022-06-25
// Last Modified :
// -----------------------------------------------------------------
// Description:
//
//
// -FHDR------------------------------------------------------------

#include "ucp_printf.h"
#include "ucp_utility.h"
#include "ucp_handshake.h"
#include "msg_transfer_mem.h"
#include "pet_sm_mgt.h"

//master is the core which controlled the handshake flow
void ucp_handshake(void)
{
	uint32_t core_id = NPU_CORE_ID;
	uint32_t request= (core_id + HANDSHKAE_REQ_VALUE);
	volatile uint32_t response;

	PetSmLocalMgt_t* pPetSmLocalMgt = get_pet_sm_local_mgt();
	UcpHandshake_t*	pHandshake = pPetSmLocalMgt->pHandshake;

	pHandshake->request[core_id] = request;
	UCP_PRINT_DEBUG("core[0x%08x] send handshake request message,value[0x%08x].",core_id,request);

	while(1) {
		response = pHandshake->response[core_id];
		if (response == (core_id + HANDSHKAE_RESP_VALUE)) {
			UCP_PRINT_DEBUG("core[0x%08x] recieved handshake response message,value[0x%08x].",core_id,response);
			break;
		}
	}

	return;
}

void send_handshake_request(void)
{
	uint32_t core_id = NPU_CORE_ID;
	uint32_t request= (core_id + HANDSHKAE_REQ_VALUE);
	//volatile uint32_t response;

	PetSmLocalMgt_t* pPetSmLocalMgt = get_pet_sm_local_mgt();
	UcpHandshake_t*	pHandshake = pPetSmLocalMgt->pHandshake;

	pHandshake->request[core_id] = request;
	UCP_PRINT_DEBUG("core[0x%08x] send handshake request message,value[0x%08x].",core_id,request);

	return;
}

uint32_t get_handshake_status(void)
{
	volatile uint32_t response;
	uint32_t core_id = NPU_CORE_ID;
    uint32_t coreReadyBitMap = SUCCESS;//0:ready, 1:not ready
	uint32_t handshake_coremask = 0x6FF;

	PetSmLocalMgt_t* pPetSmLocalMgt = get_pet_sm_local_mgt();
	UcpHandshake_t*	pHandshake = pPetSmLocalMgt->pHandshake;

	response = pHandshake->response[core_id];
	if (response == (core_id + HANDSHKAE_RESP_VALUE)) {
		return coreReadyBitMap;
	} else {
		for(uint32_t i = 0; i < MAX_NUM_SPU; i++) {
			response = pHandshake->response[i];
			if (response != (i + HANDSHKAE_RESP_VALUE)) {
				coreReadyBitMap |= (1 << i);
			}
		}
		coreReadyBitMap &= handshake_coremask;
		return coreReadyBitMap;
	}

	//return;
}

void receive_handshake_response(void)
{
	uint32_t stauts = SUCCESS;
	do {
		stauts = get_handshake_status();
	} while(SUCCESS != stauts);

	return;
}

