/*
 * @file tl_heap.c
 * @brief interfaces for malloc / free
 * Copyright (c) 2016, Samsung Electronics Corporation. All rights reserved.
 */

/*#include <comdef.h>*/
#include "target.h"
#include "x509v3.h"
#include "tl_heap.h"
#include "tl_utils.h"
#include "tl_log.h"
#include "target.h"

struct mem_node {
    void *ptr;
    size_t size;
    struct mem_node *next;
};
#define MAX_ALIGNMENT 8
#define MEM_POOL_SIZE 256*1024
struct mem_pool {
    /*char data[MEM_POOL_SIZE];*/
    char *data;
    int pos;
}__attribute__ ((aligned (MAX_ALIGNMENT)));

static struct mem_pool _softsim_pool;
static struct mem_pool * const softsim_pool = &_softsim_pool;

int init_mem_pool() {
    /*SOFTSIM_LOGD(" file: %s, func: %s",__FILE_NAME__, __func__);*/

    softsim_pool->data = target_malloc(MEM_POOL_SIZE);
    if (NULL == softsim_pool->data) {
        return -1;
    }
    softsim_pool->pos = 0;
    SOFTSIM_LOGD("start heap = 0x%08x, end heap = 0x%08x", softsim_pool->data, softsim_pool->data + MEM_POOL_SIZE);
    return 0;
}

void cleanup_mem_pool() {
    /*SOFTSIM_LOGD(" file: %s, func: %s",__FILE_NAME__, __func__);*/
    /*SOFTSIM_LOGD(" memory pool size %d ", softsim_pool->pos);*/
    target_free(softsim_pool->data);
    softsim_pool->pos = 0;
    /*SOFTSIM_LOGD(" +++MEMORY CLEAN UP DONE...+++");*/
}

void* tl_malloc(size_t size) {
    /*SOFTSIM_LOGD(" file: %s, func: %s",__FILE_NAME__, __func__);*/
    /*SOFTSIM_LOGD(" malloc size = %d", size);*/
    softsim_pool->pos = (softsim_pool->pos + MAX_ALIGNMENT - 1) / MAX_ALIGNMENT * MAX_ALIGNMENT;
    if (softsim_pool->pos + size > MEM_POOL_SIZE) {
        SOFTSIM_LOGE("exceed memory pool limit, current pos = %d", softsim_pool->pos);
        return NULL;
    }

    char *p = &softsim_pool->data[softsim_pool->pos];
    softsim_pool->pos += size;
    return p;
}

void tl_free(void *ptr) {
    //--- we will free all allocated mem at the end of request processing
}
