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

#include "typedef.h"
#include "ucp_handshake.h"
#include "ucp_utility.h"
#include "ucp_heartbeat.h"
//#include "ucp_printf.h"

#define HEART_BEAT_CNT_THRESHOLD    (500000)

static uint32_t gLocalHeartBeatCounter = 0;

static inline void init_heart_beat_cnt_local(void)
{
    gLocalHeartBeatCounter = 0;
    return;
}

static inline void inc_heart_beat_cnt_local(void)
{
    gLocalHeartBeatCounter += 1;
    return;
}

static inline uint32_t get_heart_beat_cnt_local(void)
{
    return gLocalHeartBeatCounter;
}

static inline void inc_heart_beat_cnt_sm(uint32_t core_id)
{
#ifdef HEARTBEAT_ENABLE
    UcpHandshake_t* pHandshake = (UcpHandshake_t *)get_handshake_info();
    //uint32_t core_id = get_core_id();
    uint32_t heartBeatShareMem = do_read_volatile(&pHandshake->heartbeat[core_id]);
    heartBeatShareMem++;
    do_write(&pHandshake->heartbeat[core_id], heartBeatShareMem);
#endif
    return;
}

void heart_beat_write(void)
{
    uint32_t heartBeatLocal = 0;
    uint32_t core_id = get_core_id();

    if (core_id >= PET_RFM_SPU0_CORE_ID) {//RFM
        inc_heart_beat_cnt_local();
        heartBeatLocal = get_heart_beat_cnt_local();
        if (heartBeatLocal >= HEART_BEAT_CNT_THRESHOLD) {
            inc_heart_beat_cnt_sm(core_id);
            init_heart_beat_cnt_local();
        }
    } else{//APE
        inc_heart_beat_cnt_sm(core_id);
    }

    return;
}

