/*
 *               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 management: Allocate, free EDs, TDs, etc. */
#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include "ohci.h"
#include "ohci_regs.h"
#include "ohci_core.h"

#ifdef OHCI_MEM_ENABLE_DBG
static u32 __edCnt = 0;
static u32 __tdCnt = 0;
#define OHCI_MEM_DBG(format, ...) printf(format, ##__VA_ARGS__)
#else
#define OHCI_MEM_DBG(format, ...)
#endif /* OHCI_ENABLE_DBG */
/* Memory management for transfer descriptors,
 * endpoint descriptors and buffers for driver use.
 */
IOSHeapId __ohcdHeapId = -1;

IOSError 
freeTD(ohci_td *td)
{
    if (NULL != td) {
        OHCI_MEM_DBG("freeTD: %p; td count: %u\n", td, --__tdCnt);
        return IOS_Free(__ohcdHeapId, td);
    } else {
        return IOS_ERROR_INVALID;
    }
}

ohci_td *
allocTD(void)
{
    ohci_td *td = IOS_AllocAligned(__ohcdHeapId, sizeof(ohci_td), OHCI_TD_ALIGN);
    if (NULL != td) {
        memset(td, 0, sizeof(ohci_td));
        OHCI_MEM_DBG("allocTD: %p; td count: %u\n", td, ++__tdCnt);
    }
    return td;
}

/* 0 if invalid
 * 1 if valid
 */
u8 
isValidTD(ohci_td *td)
{
    u8 rv = 0;

    if (NULL == td) {
        OHCI_DBG("invalid TD: NULL\n");
        goto done;
    }
    if (0 != ((u32)td % OHCI_TD_ALIGN)) {
        OHCI_DBG("invalid TD: %p alignment\n", td);
        goto done;
    }
    if (((u32)td <  OH0_BUF_START) || (u32)td >= (OH0_BUF_START + OH0_BUF_SPACE_SIZE )) {
        OHCI_DBG("invalid TD: %p address \n", td);
        goto done;
    }
    OHCI_DBG("TD %p valid\n", td);
    rv = 1;

done:
    return rv;
}

ohci_ed *
allocED(void)
{
    ohci_ed *ed = IOS_AllocAligned(__ohcdHeapId, sizeof(ohci_ed), OHCI_ED_ALIGN);
    if (NULL != ed) {
        memset(ed, 0, sizeof(ohci_ed));
        OHCI_MEM_DBG("allocED: %p; ed count: %u\n", ed, ++__edCnt);
    }
    return ed;
}

IOSError
freeED(ohci_ed *ed)
{
    if (NULL != ed) {
        OHCI_MEM_DBG("freeED: %p; ed count: %u\n", ed, --__edCnt);
        return IOS_Free(__ohcdHeapId, ed);
    } else {
        return IOS_ERROR_INVALID;
    }
}

IOSError
initOHCDHeap(void)
{ 
    memset((u8 *)OH0_BUF_START, 0, OH0_BUF_SPACE_SIZE);
    __ohcdHeapId = IOS_CreateHeap((u8 *) OH0_BUF_START, OH0_BUF_SPACE_SIZE);
    if (__ohcdHeapId < 0) 
        OHCI_DBG("Failed to create buf heap: %d\n", __ohcdHeapId);
    return __ohcdHeapId;
}

IOSError
initOHCDMem(void)
{
    IOSError rv;
    if ((rv = initOHCDHeap()) < 0)
        goto err;
     rv = IOS_ERROR_OK;
     goto done;
err:
   if (__ohcdHeapId > 0)  IOS_DestroyHeap(__ohcdHeapId); 
   rv = IOS_ERROR_INVALID;

done:
    return rv;
}
