#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>


#include "osp.h"

char *OspMemBaseOrg;
char *OspMemBase;
OSP_STATUS osp_mem_init(void)
{
//    int fd;
//    fd=open("./ospmem",O_CREAT|O_RDWR, 0777);
//    ftruncate(fd,OSP_MEM_SIZE);
//    OspMemBase=mmap(0,OSP_MEM_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

    OspMemBase = malloc(OSP_MEM_SIZE);
    if (NULL == OspMemBase)
    {
        return OSP_ERROR;
    }

    OspMemBaseOrg = OspMemBase;
    OspMemBase = (char *)(OSP_ROUND_UP(OspMemBase, 32));

    return OSP_OK;
}

void osp_print_tatal_mem(void)
{
    osp_debug_out_with_time(RUN_DEBUG_LEVEL, "OspMemBase = %#lx,Osp Use Total Mem is %dKB\n", (uint64_t)OspMemBase,(OspMemBase - OspMemBaseOrg) >> 10);
}

char *osp_alloc_mem(uint32_t Len)
{
    char *p = osp_get_buffer(Len, BUF_FOR_MEMORY, BUFFER_NORMAL_LEVEL);
    if (NULL == p)
    {
        return NULL;
    }
    osp_atomic_inc((int32_t *)&TASK_MEM_ALLOCCNT(CURRENT_TASKID));
    return p;

}

void osp_free_mem(char *pbuf)
{
    osp_atomic_inc((int32_t *)&TASK_MEM_FREECNT(CURRENT_TASKID));
    osp_free_buffer(pbuf);
}

char *osp_get_init_mem(int32_t len)
{
    char *p;

    p = OspMemBase;
    OspMemBase += len;
    OspMemBase = (char *)OSP_ROUND_UP(OspMemBase, 32);
    
    osp_assert((OspMemBase - OspMemBaseOrg) < OSP_MEM_SIZE);
    
    return p;
}



