/*
 *               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[712 * 1024] ATTRIBUTE_ALIGN(32);
static IOSHeapId  __heapId;

#define ALLOC_SELECTOR_NUM          6
#define STATIC_SIZE_MIN             256

typedef struct NETAllocEntry
{
	void *freelist;
	u16 count;
	u16 size;
} NETAllocEntry;

static NETAllocEntry __allocTable[ALLOC_SELECTOR_NUM] ATTRIBUTE_ALIGN(4);
static void *__allocEnd[ALLOC_SELECTOR_NUM];

static const u32 __selectorSizes[ALLOC_SELECTOR_NUM] =
{
	512,
	1024,
	4096,
	8192,
	16384,
	32768
};

typedef struct FixedAllocCountEntry
{
	u16 maxCount;
	u16 size;
} FixedAllocCountEntry;

static const FixedAllocCountEntry __staticAllocCounts[ALLOC_SELECTOR_NUM] ATTRIBUTE_ALIGN(32) =
{
	{ ICMP_SOCKET_MAX,  512  },     /* for ICMP sockets */
	{ SO_SOCKET_MAX+1,  1024 },     /* for TCP/UDP info, 1 backlog */
	{ SO_SOCKET_MAX+3,  4096 },     /* for default send buffer, 1 backlog */
                                    /* default time wait buffer, default reassembly buffer */
	{ SO_SOCKET_MAX+1,  8192 },     /* for default recv buffer */
	{ 10,              16384 },     /* for 16K recv buffer */
	{ 6,               32768 },     /* for 32K recv buffer */
};

static void *__freeSpace;

void
NetInitHeap(void)
{
    u32 i, ptr, count;
    u32 size = 0;

    /* setup preallocated fixed length allocations */
	ptr = (u32) __heapArea;
    OSDbgReport(("__heapArea = %x\n", __heapArea));

	for (i=0; i<ALLOC_SELECTOR_NUM; ++i)
	{
        OSDbgReport(("size %d, free list\n", __staticAllocCounts[i].size));
        OSDbgReport(("    %x\n", ptr));
		__allocTable[i].freelist = (void *) ptr;
		__allocTable[i].size = __staticAllocCounts[i].size;
        size += (__allocTable[i].size * __staticAllocCounts[i].maxCount);

		for (count=0; count<(u32) __staticAllocCounts[i].maxCount-1; ++count)
		{
			*((u32 *) ptr) = ptr + __staticAllocCounts[i].size;
			ptr += __staticAllocCounts[i].size;
            OSDbgReport(("    %x\n", ptr));
		}
		*((u32 *) ptr) = 0;
		ptr += __staticAllocCounts[i].size;
		
		__allocEnd[i] = (void *) ptr;
        OSDbgReport(("    end = %x\n", ptr));
	}
	__freeSpace = (void *) ptr;
    OSDbgReport(("free space = %x\n", ptr));

    __heapId = IOS_CreateHeap(__freeSpace, sizeof(__heapArea) - size);
    OSDbgReport(("size = %d\n", sizeof(__heapArea) - size));
    ASSERT(__heapId >= 0);
}

void *
StaticMalloc(u32 size)
{
    u32 i;
	void *ptr = NULL;
    BOOL enabled;

    enabled = OSDisableInterrupts();

    for (i=0; i<ALLOC_SELECTOR_NUM; ++i)
    {
        if (size <= __selectorSizes[i]) {
            break;
        }
    }

    if (i == ALLOC_SELECTOR_NUM) {
        goto done;
    }

    /* if a block of this type is on the free list, unlink it and return it */
	if (__allocTable[i].freelist)
	{
		ptr = __allocTable[i].freelist;
		__allocTable[i].freelist = *((void **) ptr);

        /* check if free list is corrupted or not */
        ASSERT((((u32) ptr) & 3) == 0);
    }

done:
    OSRestoreInterrupts(enabled);
	return ptr;
}

static void 
StaticFree(void *ptr)
{
    BOOL enabled;
    u32 i;

    enabled = OSDisableInterrupts();

    for (i=0; i<ALLOC_SELECTOR_NUM; ++i)
    {
        if (ptr < __allocEnd[i])
        {
            *(void **) ptr = __allocTable[i].freelist;
            __allocTable[i].freelist = ptr;
            break;
        }
    }

    OSRestoreInterrupts(enabled);
}

void * 
OSAlloc(int size)
{
    void *ptr;

    if (size <= STATIC_SIZE_MIN) {
        ptr = IOS_Alloc(__heapId, size);
    } else {
        ptr = StaticMalloc(size);
    }

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

    return ptr;
}

void
OSFree(void *ptr)
{
    if (ptr >= __freeSpace) {
        IOS_Free(__heapId, ptr);
    } else {
        StaticFree(ptr);
    }
}
