/*
 *               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"

/*
 * The network heap is divided by two parts: one used in static allocator
 * (StaticMalloc) and the other one used in dynamical allocator (IOS_Alloc).
 * During the initialization, the stack first reserves enough space for static
 * allocator specified by __staticAllocCounts. Then the left space will be
 * used to created a heap for dynamical allocation.
 *
 * The static area:
 *      4 * 0.5K, for ICMP sockets
 *     25 *   1K, for TCP/UDP info structure. The number = max sockets + 1 backlog
 *     25 *   4K, for default send buffer.    The number = max sockets + 1 backlog
 *     26 *   8K, for default recv buffer and default time-wait buffer.
 *                                            The number = max sockets + 1 backlog + 1 timewait
 *      6 *  16K, for 16K recv buffer, and larger time-wait buffer
 *      6 *  32K, for 32K recv buffer, and largest time-wait buffer, and default IPv6 reassembly buffer
 *
 * The dynamic area:
 *      1 *  64K, for default IPv4 reassembly buffer. This is allocated in SOiStartup()
 *      others. Currently, all are 32 bytes request and about 4K will be used.
 */

#ifndef _DEBUG
static u8 __heapArea[712 * 1024] ATTRIBUTE_ALIGN(32);
#else
static u8 __heapArea[616 * 1024] ATTRIBUTE_ALIGN(32);
#endif // _DEBUG
static IOSHeapId  __heapId;

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

#define ALLOC_SELECTOR_NUM          (sizeof(__selectorSizes) / sizeof(u32))
#define STATIC_SIZE_MIN             (__selectorSizes[0]/2 + 1)
#define STATIC_SIZE_MAX             (__selectorSizes[ALLOC_SELECTOR_NUM-1])

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];

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

static const FixedAllocCountEntry __staticAllocCounts[] ATTRIBUTE_ALIGN(32) =
{
    { ICMP_SOCKET_MAX,  512  },     /* for ICMP sockets */
    { SO_SOCKET_MAX+1,  1024 },     /* for TCP/UDP info, 1 backlog */
    { SO_SOCKET_MAX+1,  4096 },     /* for default send buffer, 1 backlog */
    { SO_SOCKET_MAX+2,  8192 },     /* for default recv buffer, 1 backlog, default time wait buffer */
#ifndef _DEBUG	
    { 6,               16384 },     /* for 16K recv buffer */
    { 6,               32768 },     /* for 32K recv buffer */
#else
    { 8,               16384 },     /* for 16K recv buffer */
    { 4,               32768 },     /* for 32K recv buffer */
#endif // _DEBUG
};

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) || (size > STATIC_SIZE_MAX)) {
        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 == NULL) {
        return;
    } else if (ptr >= __freeSpace) {
        IOS_Free(__heapId, ptr);
    } else {
        StaticFree(ptr);
    }
}
