/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/*---------------------------------------------------------------------------*
 * 
 * Memory allocater for the tcp/ip stack
 * 
 *---------------------------------------------------------------------------*/

#include <types.h>
#include <iostypes.h>
#include <ios.h>
#include <ioslibc.h>

#include "dolphin/os.h"

static u8 __heapArea[128 * 1024] ATTRIBUTE_ALIGN(32);
static IOSHeapId  __heapId;

#ifdef _DEBUG
static s32 allocated = 0;
#endif // _DEBUG

BOOL
initNetMem(void)
{
    __heapId = IOS_CreateHeap(__heapArea, sizeof(__heapArea));
    if (__heapId < 0) {
        OSReport("%s: cant create heap\n", __FUNCTION__);
        return FALSE;
    }
    return TRUE;
}

void
cleanupNetMem(void)
{
    IOSError ret = IOS_DestroyHeap(__heapId);
    if (ret < 0)
        OSReport("%s: cant cleanup heap\n", __FUNCTION__);        
}

void * 
OSAlloc(int size)
{
#ifndef _DEBUG
    void *ptr = IOS_Alloc(__heapId, size);

    if (!ptr) {
        OSReport("%s: mem allocation fails! size = %d\n", __FUNCTION__, size);
    }

    return ptr;
#else
    // in debug version, we built a resource tracker. we use the first 4 bytes
    // to record the size of pointer
    u32 *ptr = (u32 *) IOS_Alloc(__heapId, size+4);

    if (ptr)
    {
        allocated += size;
        *ptr = size;
        ptr++;
    }
    else
    {
        OSReport("%s: mem allocation fails! total allocated = %d, asking = %d\n", 
            __FUNCTION__, allocated, size);
        IOS_GetUsage(IOS_USAGE_HEAPS);
    }

    return (void *) ptr;
#endif // _DEBUG
}

void
OSFree(void *ptr)
{
#ifdef _DEBUG
    u32 *realPtr = ptr;
    if (ptr)
    {
        realPtr--;
        allocated -= *realPtr;
        IOS_Free(__heapId, realPtr);
    }
#else
    IOS_Free(__heapId, ptr);
#endif // _DEBUG
}

#ifdef _DEBUG
s32
OSGetAllocatedSize(void)
{
    return allocated;
}
#endif // _DEBUG
