#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "drv_init.h"
#include "arm_csu.h"
#include "ucp_printf.h"

int32_t g_drv_mem_fd = -1;
uint32_t *g_stc_regs_ptr = NULL;  //0x08568000

uint64_t get_arm_cycle()
{
    uint64_t cycle;

    asm volatile("mrs %0, pmccntr_el0" : "=r" (cycle));

    return cycle;
}

uint32_t read_stc_local_timer()
{
    return *(g_stc_regs_ptr + STC_LTBG_REG_OFFSET);
}

int32_t init_stc()
{
    if(g_drv_mem_fd < 0)
    {
        g_drv_mem_fd = open("/dev/mem", O_RDWR|O_SYNC);
        if(g_drv_mem_fd < 0)
        {
            UCP_PRINT_ERROR("open /dev/mem error");
            return -1;
        }
    }
    
    if(g_stc_regs_ptr == NULL)
    {
        g_stc_regs_ptr = mmap(NULL, STC_REG_LEN, PROT_READ|PROT_WRITE, MAP_SHARED,
                            g_drv_mem_fd, STC_REG_BASE_ADDR);
        if(-1 == (int64_t)g_stc_regs_ptr)
        {
            UCP_PRINT_ERROR("mmap stc regs error!! return = %ld\n",(uint64_t)g_stc_regs_ptr);
            return -2;
        }
    }
    
    return 0;
}

int32_t drv_init(void)
{

    if(0 != arm_csu_init())
    {
        UCP_PRINT_ERROR("Init arm csu error!!");
        return -1;
    }

    if(0 != init_stc())
    {
        UCP_PRINT_ERROR("Init stc error!!");
        return -3;
    }

    return 0;
}

