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

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

SpuLogClientInfo_t gLogClientInfo;

static inline SpuLogClientInfo_t* get_log_client_info(void)
{
    return (SpuLogClientInfo_t *)&gLogClientInfo;
}

void spu_log_client_init(void)
{
    int32_t core_id = get_core_id();
    SpuLogClientInfo_t* pLogClientInfo = get_log_client_info();
    pLogClientInfo->alloc = 0;
    pLogClientInfo->bufBase = SPU_LOG_CLIENT_BUF_BASE + (core_id * SPU_LOG_CLIENT_BUF_DEPTH * SPU_LOG_CLIENT_BUF_SIZE);
    pLogClientInfo->bufSize = SPU_LOG_CLIENT_BUF_SIZE;
    pLogClientInfo->ringSize = SPU_LOG_CLIENT_BUF_DEPTH;
    pLogClientInfo->ringMask = SPU_LOG_CLIENT_BUF_DEPTH - 1;

    return;
}

uint8_t* spu_log_client_mem_alloc(uint16_t* idx)
{
    int32_t core_id = get_core_id();
    PetSmLocalMgt_t* pPetSmLocalMgt = get_pet_sm_local_mgt();
    SpuLogCommonInfo_t* pLogCommonInfo = pPetSmLocalMgt->pLogCommonInfo;
    SpuLogClientInfo_t* pLogClientInfo = get_log_client_info();
    //pLogClientInfo->alloc = atomic_fetch_add(&pLogCommonInfo->alloc[core_id], 1);
    uint32_t alloc = atomic_fetch_add(&pLogCommonInfo->alloc[core_id], 1);
    uint32_t buf_idx = alloc & pLogClientInfo->ringMask;
    uint8_t* buf = (uint8_t *)(pLogClientInfo->bufBase + (buf_idx * pLogClientInfo->bufSize));
    idx[0] = buf_idx;

    return buf;
}

