Beispiel #1
0
IpcResource_Handle IpcResource_connect(UInt timeout)
{
    UInt16 dstProc;
    UInt16 len;
    IpcResource_Handle handle;
    IpcResource_Ack ack;
    Int status;

    handle = Memory_alloc(NULL, sizeof(*handle), 0, NULL);
    if (!handle) {
        System_printf("IpcResource_connect: No memory");
        return NULL;
    }

    handle->timeout = (!timeout) ? DEFAULT_TIMEOUT :
                      (timeout == IpcResource_FOREVER) ? MessageQCopy_FOREVER :
                      timeout;

    dstProc = MultiProc_getId("HOST");
    handle->sem = Semaphore_create(1, NULL, NULL);

    MessageQCopy_init(dstProc);
    handle->msgq= MessageQCopy_create(MessageQCopy_ASSIGN_ANY,
                                      &handle->endPoint);
    if (!handle->msgq) {
        System_printf("IpcResource_connect: MessageQCopy_create failed\n");
        goto err;
    }

    NameMap_register("rpmsg-resmgr", handle->endPoint);

    /* Wait for the connection ack from the host */
    status = MessageQCopy_recv(handle->msgq, &ack, &len, &handle->remote,
                               handle->timeout);
    if (status) {
        System_printf("IpcResource_connect: MessageQCopy_recv "
                      "failed status %d\n", status);
        goto err_disc;
    }

    if (len < sizeof(ack)) {
        System_printf("IpcResource_connect: Bad ack message len = %d\n", len);
        goto err_disc;
    }

    status = _IpcResource_translateError(ack.status);
    if (status) {
        System_printf("IpcResource_connect: A9 Resource Manager "
                      "failed status %d\n", status);
        goto err_disc;
    }

    return handle;

err_disc:
    NameMap_unregister("rpmsg-resmgr", handle->endPoint);
    MessageQCopy_delete(&handle->msgq);
err:
    Memory_free(NULL, handle, sizeof(*handle));
    return NULL;
}
Beispiel #2
0
/*
 *  ======== modifyDefaultLinkCfgObjectBasedOnUserCfgData ========
 */
static Void modifyDefaultLinkCfgObjectBasedOnUserCfgData( String serverName )
{
    LINKCFG_MemEntry *  linkcfgMemTable;
    LINKCFG_MemEntry *  e;
    static LINKCFG_MemEntry * linkcfgMemTables[] = { NULL /* to be set */ };
    Global_ArmDspLinkConfig * armDspLinkConfig = NULL;
    Global_ArmDspLinkConfigMemTableEntry *mte;
    DSP_BootMode    staticCfgDspCtl;
    DSP_BootMode    newCfgDspCtl;
    Int    serverNameIndex;
    UInt32 cmemPhysBase;
    size_t cmemSize;
    Int    status;

    /* MODIFY MEMORY CONFIGURATION */
    CMEM_BlockAttrs   blockAttrs;
    Int    numMemTableEntries, i = 0;
    Int    numMemEntries = 0;
    Int    memEntryIdx;
    Int    numCmemBlocks = 0;
    Bool   addCmemBlocks = FALSE;

    /* first locate our server in the list of server names */
    for (serverNameIndex = 0;;serverNameIndex++) {
        if (!strcmp(ti_sdo_ce_ipc_armDspLinkConfigServerNames[serverNameIndex],
            serverName)) {
                break;
        }
        if (ti_sdo_ce_ipc_armDspLinkConfigServerNames[serverNameIndex] ==
            NULL ) {
            GT_1trace(curTrace, GT_7CLASS, "Processor_create_d> "
                "ERROR: Cannot find DspLink configuration data for the server "
                "named '%s' -- verify that the name was specified correctly in "
                "the application configuration file.\n", serverName);
            return;
        }
    }

    GT_2trace(curTrace, GT_2CLASS, "Processor_create_d> "
        "Using DspLink config data for entry #%d [server '%s']\n",
        serverNameIndex, serverName );

    armDspLinkConfig = ti_sdo_ce_ipc_armDspLinkConfigs[ serverNameIndex ];

    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->memTables = linkcfgMemTables;
    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->memTables[0] = NULL;

    /*
     *  Count the number of CMEM blocks, so we can add entries for these,
     *  if needed.
     */
    status = CMEM_getNumBlocks(&numCmemBlocks);
    if (status != 0) {
        /* TODO: Is this always an error? */
        GT_0trace(curTrace, GT_6CLASS, "Processor_create_d> "
                "CMEM_getNumBlocks() failed!");
        numCmemBlocks = 0;
    }
    else {
        GT_1trace(curTrace, GT_2CLASS, "Processor_create_d> Number of CMEM "
                "blocks: %d\n", numCmemBlocks);
    }

    for (;armDspLinkConfig->memTable[i].segmentName != NULL; i++);

    /*
     *  Add a few extra entries in case we need to map CMEM blocks. The
     *  app's config will have at most one CMEM entry with base and length
     *  set to 0. We'll use CMEM_getBlockAttrs to get the base and length
     *  of all CMEM blocks. (Note: We will allocate at least one more entry
     *  then is actually needed, but this is easier than checking the
     *  memTable for "CMEM", and subtracting '1' from the nuber to allocate
     *  if "CMEM" is found.)
     */
    numMemEntries = i;
    numMemTableEntries = numMemEntries + numCmemBlocks;

    /* anything allocated here must be deallocated in procDelete */
    linkcfgMemTable = (LINKCFG_MemEntry *) Memory_alloc(
            sizeof(LINKCFG_MemEntry) * numMemTableEntries, NULL);

    if (linkcfgMemTable == NULL) {
        GT_0trace(curTrace, GT_7CLASS, "Processor_create_d> "
            "ERROR: Memory_alloc failed\n");
        return;
    }

    /* point link config memTables only entry to our list of memTable entries */
    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->memTables[0] = linkcfgMemTable;

    for (i = 0, memEntryIdx = 0; i < numMemEntries; i++) {
        e   = &linkcfgMemTable[memEntryIdx];
        mte = &armDspLinkConfig->memTable[i];
        GT_4trace(curTrace, GT_2CLASS, "Processor_create_d> Adding memTable "
                "entry for %s, physAddr = 0x%x, dspAddr = 0x%x, size = 0x%x\n",
                mte->segmentName, mte->gppAddress, mte->startAddress,
                mte->sizeInBytes);

        if (!strcmp("CMEM", mte->segmentName)) {
            /* Skip CMEM entry, we'll add CMEM blocks later */
            addCmemBlocks = TRUE;
            continue;
        }

        e->entry        = memEntryIdx; //i;
        strncpy( e->name, mte->segmentName, DSP_MAX_STRLEN );
        e->physAddr     = mte->gppAddress; // gpp physical address
        e->dspVirtAddr  = mte->startAddress; // dsp view (physical or virtual)
        e->gppVirtAddr  = (UInt32)-1;
        e->size         = mte->sizeInBytes;
        e->shared       = mte->shared;
        e->syncd        = mte->syncd;

        memEntryIdx++;

        GT_6trace(curTrace, GT_2CLASS, "Processor_create_d> "
            "Adding DSP segment #%d to Link configuration: "
            "name='%s', startAddress=0x%x, sizeInBytes=0x%x, shared=%d, "
            "syncd=%d\n",
            i, e->name, e->physAddr, e->size, e->shared, e->syncd);
    }

    /* Now add the CMEM blocks if needed */
    if (addCmemBlocks) {
        for (i = 0; i < numCmemBlocks; i++) {
            e = &linkcfgMemTable[memEntryIdx];
            status = CMEM_getBlockAttrs(i, &blockAttrs);
            if (status != 0) {
                GT_1trace(curTrace, GT_7CLASS, "Processor_create_d> "
                        "ERROR: failed to get CMEM attrs of block %d\n", i);
                break;
            }
            sprintf(e->name, "CMEM_BLOCK%d", i);
            e->physAddr = blockAttrs.phys_base;
            e->dspVirtAddr = blockAttrs.phys_base;
            e->size = blockAttrs.size;
            memEntryIdx++;
        }
    }

    /* set number of memTable entries */
    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->dspObject[0].memEntries =
        memEntryIdx; //numMemTableEntries;

    /* RESET vector is always #3 in the list (that's how Global.xdt arranges it;
     * read its start address and size and adjust some other params in the
     * dsplink config object. (Note: third in the list is index [2].
     */
    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->dspObject[0].resumeAddr =
        armDspLinkConfig->memTable[2].startAddress + 0x20;
    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->dspObject[0].resetVector =
        armDspLinkConfig->memTable[2].startAddress;
    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->dspObject[0].resetCodeSize =
        armDspLinkConfig->memTable[2].sizeInBytes;

    /* SET DOPOWERCONTROL PER CE CONFIGURATION */
    staticCfgDspCtl =
        ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->dspObject[0].doDspCtrl;

    if (armDspLinkConfig->doDspCtrl == BootNoPwr) {
        newCfgDspCtl = DSP_BootMode_Boot_NoPwr;
    }
    else if (armDspLinkConfig->doDspCtrl == BootPwr) {
        newCfgDspCtl = DSP_BootMode_Boot_Pwr;
    }
    else if (armDspLinkConfig->doDspCtrl == NoLoadNoPwr) {
        newCfgDspCtl = DSP_BootMode_NoLoad_NoPwr;
    }
    else if (armDspLinkConfig->doDspCtrl == NoLoadPwr) {
        newCfgDspCtl = DSP_BootMode_NoLoad_Pwr;
    }
    else { /* NoBoot */
        newCfgDspCtl = DSP_BootMode_NoBoot;
    }

    ti_sdo_ce_ipc_Processor_linkcfg.dspConfigs[0]->dspObject[0].doDspCtrl =
        newCfgDspCtl;
    GT_2trace(curTrace, GT_2CLASS, "Processor_create_d> "
            "DODSPCTRL was=%d; now=%d\n", staticCfgDspCtl, newCfgDspCtl);
}
Beispiel #3
0
/*
 *  ======== Notify_registerEvent ========
 */
Int Notify_registerEvent(UInt16                 procId,
                         UInt16                 lineId,
                         UInt32                 eventId,
                         Notify_FnNotifyCbck    fnNotifyCbck,
                         UArg                   cbckArg)
{
    UInt32               strippedEventId = (eventId & 0xFFFF);
    UInt16 clusterId =   ti_sdo_utils_MultiProc_getClusterId(procId);
    Int                  status;
    ti_sdo_ipc_Notify_Object        *obj;
    UInt                 modKey;
    List_Handle          eventList;
    ti_sdo_ipc_Notify_EventListener *listener;
    Bool                 listWasEmpty;
    Error_Block          eb;

    Assert_isTrue(procId < ti_sdo_utils_MultiProc_numProcessors &&
                  lineId < ti_sdo_ipc_Notify_numLines, ti_sdo_ipc_Notify_A_invArgument);
    Assert_isTrue(strippedEventId < ti_sdo_ipc_Notify_numEvents,
                  ti_sdo_ipc_Notify_A_invArgument);
    Assert_isTrue(ISRESERVED(eventId), ti_sdo_ipc_Notify_A_reservedEvent);

    Error_init(&eb);

    modKey = Gate_enterModule();

    obj = (ti_sdo_ipc_Notify_Object *)
          Notify_module->notifyHandles[clusterId][lineId];

    Assert_isTrue(obj != NULL, ti_sdo_ipc_Notify_A_notRegistered);

    /* Allocate a new EventListener */
    listener = Memory_alloc(ti_sdo_ipc_Notify_Object_heap(),
                            sizeof(ti_sdo_ipc_Notify_EventListener), 0, &eb);
    if (listener == NULL) {
        /* Listener memory allocation failed.  Leave module gate & return */
        Gate_leaveModule(modKey);

        return (Notify_E_MEMORY);
    }

    listener->callback.fnNotifyCbck = (Fxn)fnNotifyCbck;
    listener->callback.cbckArg = cbckArg;

    eventList = List_Object_get(obj->eventList, strippedEventId);

    /*
     *  Store whether the list was empty so we know whether to register the
     *  callback
     */
    listWasEmpty = List_empty(eventList);

    /*
     *  Need to atomically add to the list using the system gate because
     *  Notify_exec might preempt List_remove.  List_put is atomic.
     */
    List_put(eventList, (List_Elem *)listener);

    if (listWasEmpty) {
        /*
         *  Registering this event for the first time.  Need to register the
         *  callback function.
         */
        status = Notify_registerEventSingle(procId, lineId, eventId,
                                            Notify_execMany, (UArg)obj);

        /* Notify_registerEventSingle should always succeed */
        Assert_isTrue(status == Notify_S_SUCCESS,
                      ti_sdo_ipc_Notify_A_internal);
    }

    status = Notify_S_SUCCESS;

    Gate_leaveModule(modKey);

    return (status);
}
/*
 *  ======== ipcSetup ========
 */
Int ipcSetup (Int testCase)
{
    Int                             status          = 0;
    Char *                          procName;
    UInt16                          procId;
    ProcMgr_AttachParams            attachParams;
    ProcMgr_State                   state;
#if !defined(SYSLINK_USE_DAEMON)
    UInt32                          entryPoint      = 0;
    ProcMgr_StartParams             startParams;
    Char                            uProcId;
    HeapBufMP_Params                heapbufmpParams;
#if defined(SYSLINK_USE_LOADER)
    Char                          * imageName;
    UInt32                          fileId;
#endif
#endif
    Ipc_Config                      config;
    Int                             i;
    UInt32                          srCount;
    SharedRegion_Entry              srEntry;

    Osal_printf ("ipcSetup: Setup IPC componnets \n");

    switch(testCase) {
    case 0:
        Osal_printf ("ipcSetup: Local RCM test\n");
        remoteServerName = RCMSERVER_NAME;
        procName = MPU_PROC_NAME;
        break;
    case 1:
        Osal_printf ("ipcSetup: RCM test with RCM client and server on "
                     "Sys M3\n\n");
        remoteServerName = SYSM3_SERVER_NAME;
        procName = SYSM3_PROC_NAME;
        break;
    case 2:
        Osal_printf ("ipcSetup: RCM test with RCM client and server on "
                     "App M3\n\n");
        remoteServerName = APPM3_SERVER_NAME;
        procName = APPM3_PROC_NAME;
        break;
    case 3:
        Osal_printf ("ipcSetup: RCM test with RCM client and server on "
                     "Tesla\n\n");
        remoteServerName = DSP_SERVER_NAME;
        procName = DSP_PROC_NAME;
        break;
    default:
        Osal_printf ("ipcSetup: Please pass valid arg "
                     "(0-local, 1-Sys M3, 2-App M3, 3-Tesla) \n");
        goto exit;
        break;
    }

    Ipc_getConfig (&config);
    status = Ipc_setup (&config);
    if (status < 0) {
        Osal_printf ("ipcSetup: Error in Ipc_setup [0x%x]\n", status);
        goto exit;
    }
    Osal_printf("Ipc_setup status [0x%x]\n", status);

    procId = ((testCase == 3) ? MultiProc_getId (DSP_PROC_NAME) : \
                                MultiProc_getId (SYSM3_PROC_NAME));
    remoteIdClient = MultiProc_getId (procName);

    /* Open a handle to the ProcMgr instance. */
    status = ProcMgr_open (&procMgrHandleClient, procId);
    if (status < 0) {
        Osal_printf ("ipcSetup: Error in ProcMgr_open [0x%x]\n", status);
        goto exit;
    }
    if (status >= 0) {
        Osal_printf ("ipcSetup: ProcMgr_open Status [0x%x]\n", status);
        ProcMgr_getAttachParams (NULL, &attachParams);
        /* Default params will be used if NULL is passed. */
        status = ProcMgr_attach (procMgrHandleClient, &attachParams);
        if (status < 0) {
            Osal_printf ("ipcSetup: ProcMgr_attach failed [0x%x]\n", status);
        }
        else {
            Osal_printf ("ipcSetup: ProcMgr_attach status: [0x%x]\n", status);
            state = ProcMgr_getState (procMgrHandleClient);
            Osal_printf ("ipcSetup: After attach: ProcMgr_getState\n"
                         "    state [0x%x]\n", state);
        }
    }

    if ((status >= 0) && (testCase == 2)) {
        status = ProcMgr_open (&procMgrHandleClient1, remoteIdClient);
        if (status < 0) {
            Osal_printf ("ipcSetup: Error in ProcMgr_open [0x%x]\n", status);
            goto exit;
        }
        if (status >= 0) {
            Osal_printf ("ipcSetup: ProcMgr_open Status [0x%x]\n", status);
            ProcMgr_getAttachParams (NULL, &attachParams);
            /* Default params will be used if NULL is passed. */
            status = ProcMgr_attach (procMgrHandleClient1, &attachParams);
            if (status < 0) {
                Osal_printf ("ipcSetup: ProcMgr_attach failed [0x%x]\n",
                                status);
            }
            else {
                Osal_printf ("ipcSetup: ProcMgr_attach status: [0x%x]\n",
                                status);
                state = ProcMgr_getState (procMgrHandleClient1);
                Osal_printf ("ipcSetup: After attach: ProcMgr_getState\n"
                             "    state [0x%x]\n", state);
            }
        }
    }

#if !defined(SYSLINK_USE_DAEMON) /* Daemon sets this up */
#if defined(SYSLINK_USE_LOADER)
    if (testCase == 1)
        imageName = RCM_MPUCLIENT_SYSM3ONLY_IMAGE;
    else if (testCase == 2)
        imageName = RCM_MPUCLIENT_SYSM3_IMAGE;
    else if (testCase == 3)
        imageName = RCM_MPUCLIENT_DSP_IMAGE;

    if (testCase != 0) {
        status = ProcMgr_load (procMgrHandleClient, imageName, 2, &imageName,
                                &entryPoint, &fileId, procId);
        if (status < 0) {
            Osal_printf ("ipcSetup: Error in ProcMgr_load %s image [0x%x]\n",
                            procName, status);
            goto exit;
        }
        Osal_printf ("ipcSetup: ProcMgr_load %s image Status [0x%x]\n",
                        procName, status);
    }
#endif /* defined(SYSLINK_USE_LOADER) */
    if (testCase != 0) {
        startParams.proc_id = procId;
        status = ProcMgr_start (procMgrHandleClient, entryPoint, &startParams);
        if (status < 0) {
            Osal_printf ("ipcSetup: Error in ProcMgr_start %s [0x%x]\n",
                            procName, status);
            goto exit;
        }
        Osal_printf ("ipcSetup: ProcMgr_start %s Status [0x%x]\n", procName,
                        status);
    }

    if (testCase == 2) {
#if defined(SYSLINK_USE_LOADER)
        imageName = RCM_MPUCLIENT_APPM3_IMAGE;
        uProcId = MultiProc_getId (APPM3_PROC_NAME);
        status = ProcMgr_load (procMgrHandleClient1, imageName, 2, &imageName,
                                &entryPoint, &fileId, uProcId);
        if (status < 0) {
            Osal_printf ("ipcSetup: Error in ProcMgr_load AppM3 image: "
                "[0x%x]\n", status);
            goto exit;
        }
        Osal_printf ("ipcSetup: AppM3: ProcMgr_load Status [0x%x]\n", status);
#endif /* defined(SYSLINK_USE_LOADER) */
        startParams.proc_id = MultiProc_getId (APPM3_PROC_NAME);
        status = ProcMgr_start (procMgrHandleClient1, entryPoint, &startParams);
        if (status < 0) {
            Osal_printf ("ipcSetup: Error in ProcMgr_start AppM3 [0x%x]\n",
                        status);
            goto exit;
        }
        Osal_printf ("ipcSetup: ProcMgr_start AppM3 Status [0x%x]\n", status);
    }
#endif /* defined(SYSLINK_USE_DAEMON) */

    srCount = SharedRegion_getNumRegions();
    Osal_printf ("SharedRegion_getNumRegions = %d\n", srCount);
    for (i = 0; i < srCount; i++) {
        status = SharedRegion_getEntry (i, &srEntry);
        Osal_printf ("SharedRegion_entry #%d: base = 0x%x len = 0x%x "
                        "ownerProcId = %d isValid = %d cacheEnable = %d "
                        "cacheLineSize = 0x%x createHeap = %d name = %s\n",
                        i, srEntry.base, srEntry.len, srEntry.ownerProcId,
                        (Int)srEntry.isValid, (Int)srEntry.cacheEnable,
                        srEntry.cacheLineSize, (Int)srEntry.createHeap,
                        srEntry.name);
    }

#if !defined(SYSLINK_USE_DAEMON) /* Daemon sets this up */
    /* Create Heap and register it with MessageQ */
    if (status >= 0) {
        HeapBufMP_Params_init (&heapbufmpParams);
        heapbufmpParams.sharedAddr = NULL;
        heapbufmpParams.align      = 128;
        heapbufmpParams.numBlocks  = 4;
        heapbufmpParams.blockSize  = MSGSIZE;
        heapSize = HeapBufMP_sharedMemReq (&heapbufmpParams);
        Osal_printf ("ipcSetup: heapSize = 0x%x\n", heapSize);

        srHeap = SharedRegion_getHeap (RCM_HEAP_SR);
        if (srHeap == NULL) {
            status = MEMORYOS_E_FAIL;
            Osal_printf ("ipcSetup: SharedRegion_getHeap failed for srHeap:"
                         " [0x%x]\n", srHeap);
        }
        else {
            Osal_printf ("ipcSetup: Before Memory_alloc = 0x%x\n", srHeap);
            heapBufPtr = Memory_alloc (srHeap, heapSize, 0);
            if (heapBufPtr == NULL) {
                status = MEMORYOS_E_MEMORY;
                Osal_printf ("ipcSetup: Memory_alloc failed for ptr: [0x%x]\n",
                             heapBufPtr);
            }
            else {
                heapbufmpParams.name           = RCM_MSGQ_HEAPNAME;
                heapbufmpParams.sharedAddr     = heapBufPtr;
                Osal_printf ("ipcSetup: Before HeapBufMP_Create: [0x%x]\n",
                                heapBufPtr);
                heapHandle = HeapBufMP_create (&heapbufmpParams);
                if (heapHandle == NULL) {
                    status = HeapBufMP_E_FAIL;
                    Osal_printf ("ipcSetup: HeapBufMP_create failed for Handle:"
                                 "[0x%x]\n", heapHandle);
                }
                else {
                    /* Register this heap with MessageQ */
                    status = MessageQ_registerHeap (heapHandle,
                                                    RCM_MSGQ_HEAPID);
                    if (status < 0) {
                        Osal_printf ("ipcSetup: MessageQ_registerHeap "
                                     "failed!\n");
                    }
                }
            }
        }
    }
#endif /* defined(SYSLINK_USE_DAEMON) */

exit:
    Osal_printf ("ipcSetup: Leaving ipcSetup()\n");
    return status;
}
Beispiel #5
0
/*
 *  ======== Loader_loadLibrary ========
 */
Loader_Handle Loader_loadLibrary(String name)
{
    Loader_Object *lib = NULL;
    Char           seps[] = ";";
    Char          *dir = NULL;
    String         errString = NULL;
    String         fullPath = NULL;
    Int            bufLen;

    Log_print1(Diags_ENTRY, "[+E] Loader_loadLibrary(%s)", (IArg)name);

    if ((lib = Memory_alloc(NULL, sizeof(Loader_Object), 0, NULL)) == NULL) {
        Log_print0(Diags_USER7,
                   "[+7] Loader_loadLibrary> Memory_alloc failed");
        return (NULL);
    }

    /*
     *  Load the library. dlopen() will return the same handle if the library
     *  is already loaded. dlclose() must be called the same number of times
     *  as dlopen() for the library to be unloaded.
     *
     *  RTLD_LAZY: Perform lazy binding of function references (only resolve
     *  symbols when executed).
     *  RTLD_NOW: Resolve all symbols before dlopen() returns.
     *
     *  First try loading the library name as is. If this fails, try searching
     *  along the path.
     */
    lib->handle = dlopen(name, RTLD_NOW);
    if (lib->handle == NULL) {
        if (libPath == NULL) {
            Log_print0(Diags_USER7,
                       "[+7] Loader_loadLibrary> dlopen() failed");

            /* Get the last dlerror */
            errString = (String)dlerror();
            if (errString != NULL) {
                Log_print1(Diags_USER7,
                           "[+7] Loader_loadLibrary> dlopen() error: %s",
                           (IArg)errString);
            }
            Memory_free(NULL, lib, sizeof(Loader_Object));
            return (NULL);
        }

        /* strtok will mess up the path, so copy it first. */
        Assert_isTrue(tmpPath != NULL, (Assert_Id)NULL);
        strcpy(tmpPath, libPath);

        /* Allocate a big enough buffer for storing the full path name */
        bufLen = strlen(libPath) + strlen(name) + 2;
        fullPath = Memory_alloc(NULL, bufLen, 0, NULL);

        if (fullPath == NULL) {
            Log_print0(Diags_USER7, "[+7] Loader_loadLibrary> "
                       "Memory_alloc full path buffer failed");
            Memory_free(NULL, lib, sizeof(Loader_Object));
            return (NULL);
        }

        dir = strtok(tmpPath, seps);

        while (dir != NULL) {
            strcpy(fullPath, dir);
            strcat(fullPath, "/");
            strcat(fullPath, name);

            lib->handle = dlopen(fullPath, RTLD_NOW);

            if (lib->handle != NULL) {
                Log_print1(Diags_USER2, "[+2] Loader_loadLibrary> "
                           "dlopen(%s) succeeded!", (IArg)fullPath);
                break;
            }

            /*
             *  Get the last dlerror in case library was found but there was
             *  some other problem (eg, wrong format).
             */
            errString = (String)dlerror();
            if (errString != NULL) {
                Log_print2(Diags_USER2, "[+2] Loader_loadLibrary> "
                           "dlopen(%s) failed, error returned:\n     %s",
                           (IArg)fullPath, (IArg)errString);
            }

            dir = strtok(NULL, seps);
        }

        if (fullPath) {
            Memory_free(NULL, fullPath, bufLen);
        }

        if (dir == NULL) {
            Log_print2(Diags_USER7, "[+7] Loader_loadLibrary> "
                       "Failed to load library: %s with search path %s",
                       (IArg)name, (IArg)libPath);
        }
    }

    if (lib && (lib->handle == NULL)) {
        Memory_free(NULL, lib, sizeof(Loader_Object));
        lib = NULL;
    }

    Log_print1(Diags_EXIT, "[+X] Loader_loadLibrary> Exit, returning 0x%x",
               (IArg)lib);

    return (lib);
}
Beispiel #6
0
int32_t XdmServer_create (
    Rpe_ServerObj              *server,
    Rpe_Attributes             *instAttr,
    void                       *createParams)
{
    XdmServer_ServerObj        *xdmServer = (XdmServer_ServerObj *) server;
    XDM_Fxns                   *xdmFxns;
    IALG_Fxns                  *ialgFxns;
    IALG_MemRec                *memTab = NULL;
    Int                         numRecs;
    uint16_t                    memTabSize;
    IALG_Handle                 alg;
    IALG_Fxns                  *fxnsPtr;
    XdmServer_ServerConfig     *xdmServerCfg;
    uint8_t                     algAllocDone = FALSE;
    int32_t                     status, i;
    uint8_t                    *ptr;
    Error_Block                 eb;

#ifdef DEBUG
    fprintf (stderr, "XdmServer_createServer: Enter\n");
#endif
    xdmServer->alg = NULL;

    xdmServerCfg = (XdmServer_ServerConfig *) (server->serverConfig);

    /* Check that all fields in the config. structure are initialized */
    if ((xdmFxns = xdmServerCfg->xdmFxns) == NULL) {
        status = RPE_E_XDM_NULL_XDMFXNS;
        goto Error;
    }

    ialgFxns = &(xdmFxns->ialgFxns);

    if (NULL == ialgFxns->algAlloc) {
        status = RPE_E_XDM_NULL_ALGALLOC_FXN;
        goto Error;
    }
    if (NULL == ialgFxns->algFree) {
        status = RPE_E_XDM_NULL_ALGFREE_FXN;
        goto Error;
    }
    if (NULL == ialgFxns->algInit) {
        status = RPE_E_XDM_NULL_ALGINIT_FXN;
        goto Error;
    }
    if (NULL == xdmFxns->algControlFxn) {
        status = RPE_E_XDM_NULL_CONTROL;
        goto Error;
    }
    if (NULL == xdmFxns->algProcessFxn) {
        status = RPE_E_XDM_NULL_PROCESS;
        goto Error;
    }
    
    /* Get number of XDAIS alg memtab entries */
    xdmServer->numRecs = numRecs = (ialgFxns->algNumAlloc != NULL)
        ? ialgFxns->algNumAlloc () : IALG_DEFMEMRECS;

    /* Allocate memtab entries */
    memTabSize = numRecs * sizeof(IALG_MemRec);      
    
    if ((memTab = (IALG_MemRec *) Memory_alloc ((IHeap_Handle) RPE_dspAlgHeapHandle,
                                                memTabSize,
                                                RPE_MEM_ALLOC_ALIGNMENT,
                                                &eb)) == NULL) {
        status = RPE_E_SERVER_NO_MEMORY;
        goto Error;
    }
    
    /* Clear the memTab memory */
    ptr = (uint8_t *) memTab;
    for (i = 0; i < memTabSize; i++)
    {
      ptr[i] = 0;
    }
    
    /* Save memTab in the server record */
    xdmServer->memTab = memTab;

    /* Fill up memtab entries */
    if ((numRecs = ialgFxns->algAlloc (createParams, &fxnsPtr, memTab)) <= 0) {
        status = RPE_E_XDM_INVALID_CREAT_PARAMS;
        goto Error;
    }

    /* Allocated algorithm memory using memtab entries */
    if ((status = _XdmServer_allocXdaisAlgMemory (memTab, numRecs))
                                                            != RPE_S_SUCCESS) {
        goto Error;
    }
    algAllocDone = TRUE;

    /* Initialize alg handle */
    alg = (IALG_Handle) memTab[0].base;
    alg->fxns = ialgFxns;

    /* 
     * Call alg initialize function with the memory it requested.
     * If algInit successful return the alg object's handle 
     */
    if (ialgFxns->algInit (alg, memTab, NULL, createParams) != IALG_EOK) {
        status = RPE_E_XDM_ALGINIT;
        goto Error;
    }

    /* Put algHandle in the server handle */
    xdmServer->alg = alg;

    status = RPE_S_SUCCESS;
    goto Exit;

Error:
    /* Free all memory resources */

    /* Call algFree to free all instance memory, saved memTab recs. */
    if (TRUE == algAllocDone) {
        ialgFxns->algFree (alg, memTab);
        _XdmServer_freeXdaisAlgMemory (memTab, numRecs);
    }

    if (NULL != memTab)
        Memory_free ((IHeap_Handle) RPE_dspAlgHeapHandle, memTab, memTabSize);

Exit:
    return (status);
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    IMGDEC1_Handle dec = NULL;
    IMGENC1_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;

    if (argc <= 1) {
        inFile = "./in.dat";
        outFile = "./out.dat";
        createInFileIfMissing(inFile);
    }
    else if (argc >= 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    if ((argc == 4) && (argv[3][0] == '1')) {
        appPause = 1;
    }


    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    encodedBuf = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

    if ((inBuf == NULL) || (encodedBuf == NULL) || (outBuf == NULL) ||
        (versionBuf == NULL)) {

        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = IMGDEC1_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = IMGENC1_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

#ifdef USE_POWER_MANAGEMENT
    /* open local power manager */
    if (Global_usePowerManagement) {
       LPM_Status  lpmStat = LPM_SOK;
       lpmStat = LPM_open("/dev/lpm0", &lpmHandle);

       if (lpmStat != LPM_SOK) {
            fprintf(stderr, "%s: error: LPM_open() failed\n", progName);
            goto end;
       }
    }
#endif

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
#ifdef USE_POWER_MANAGEMENT
    /* close local power manager */
    if (lpmHandle != NULL) {
       LPM_close(lpmHandle);
    }
#endif

    /* teardown the codecs */
    if (enc) {
        IMGENC1_delete(enc);
    }
    if (dec) {
        IMGDEC1_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (encodedBuf) {
        Memory_free(encodedBuf, EFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    VIDDEC_Handle dec = NULL;
    VIDENC_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;


    
#if 0
    if (argc <= 1) {
        inFile = "./in.dat";
        outFile = "./out.dat";
        createInFileIfMissing(inFile);
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }
 #endif   


        /*init uart*/
        uart_init(fd.uart1);
		uart_init(fd.uart2);
 
         /*thread*/
         pthread_t thread1 , thread2; 
         pthread_create(&thread1, NULL , &read_uart1_task, NULL);
         pthread_create(&thread2, NULL , &read_uart2_task, NULL);



    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate input, encoded, and output buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    encodedBuf = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);

    if ((inBuf == NULL) || (encodedBuf == NULL) || (outBuf == NULL)) {
        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = VIDDEC_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = VIDENC_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
    /* teardown the codecs */
    if (enc) {
        VIDENC_delete(enc);
    }
    if (dec) {
        VIDDEC_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (encodedBuf) {
        Memory_free(encodedBuf, EFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Void ListTest(Void)
{
    List_Params listParams;
    List_Handle listHandle;
    List_Elem *elem;
    ListNode *node;
    UInt32 i, value;
    Bool failed = FALSE;

    IGateProvider_Handle gateHandle;

    List_Params_init(&listParams);

    gateHandle = (IGateProvider_Handle) GateMutex_create();
    if(gateHandle == NULL) {
        Osal_printf("ListTest: GateMutex_create failed.\n");
        goto exit;
    }

    listParams.gateHandle = gateHandle;
    listHandle = List_create(&listParams);
    if(listHandle == NULL) {
        Osal_printf("ListTest: List_create failed.\n");
        goto gateExit;
    }

    node = Memory_alloc(NULL, LIST_SIZE * sizeof(ListNode), 0);
    if(node == NULL) {
        Osal_printf("ListTest: Memory_alloc failed.\n");
        goto listExit;
    }

    // Put some nodes into the list
    for(i = 0; i < LIST_SIZE; i++) {
        node[i].value = i;
        List_put(listHandle, (List_Elem *)&node[i]);
    }

    // Traverse the list
    for(i = 0, elem = List_next(listHandle, NULL);
        elem != NULL && !failed;
        i++, elem = List_next(listHandle, elem)) {
        value = ((ListNode *)elem)->value;

        // Check against expected value
        if(value != i) {
            Osal_printf("ListTest: data mismatch, expected "
                "0x%x, actual 0x%x\n", i, i, value);
            failed = TRUE;
        }
    }

    // Remove nodes
    for(i = 0; i < LIST_SIZE && !List_empty(listHandle); i++) {
        // Get first element and put it back to test List_get and List_putHead
        elem = List_get(listHandle);
        List_putHead(listHandle, elem);

        // Now remove it permanently to test List_remove
        if(elem != NULL) {
            List_remove(listHandle, elem);
        }
    }
    // Did we remove the expected number of nodes?
    if(i != LIST_SIZE)
    {
        Osal_printf("ListTest: removed %d node(s), expected %d\n",
            i, LIST_SIZE);
        failed = TRUE;
    }

    if(!List_empty(listHandle))
    {
        Osal_printf("ListTest: list not empty!\n");
        failed = TRUE;
    }

    if(failed)
        Osal_printf("ListTest: FAILED!\n");
    else
        Osal_printf("ListTest: PASSED!\n");

listExit:
    List_delete(&listHandle);
gateExit:
    GateMutex_delete((GateMutex_Handle *)&gateHandle);
exit:
    return;
}
Beispiel #10
0
Datei: ce.c Projekt: guyz/dsp
 int cont_alloc_frames(struct frame_format *ff, unsigned bufsize,
                  struct frame **fr, unsigned *nf) {
    int buf_w = ff->width, buf_h = ff->height;
    
    uint8_t *p = NULL;
    uint8_t *pp = NULL;
    unsigned y_offset;
    int i, clear_count;

    mem_params.type = Memory_CONTIGHEAP;
    mem_params.flags = Memory_NONCACHED;
    mem_params.align = 16; 

    input_buf = Memory_alloc(INPUT_BUFFER_SIZE, &mem_params);
    if (!input_buf) {
        fprintf(stderr, "Error allocating input buffer\n");
	return -1;  
    }

    ce_frame_size = buf_w * buf_h * 2;

    num_frames = bufsize / ce_frame_size;
    y_offset = buf_w * buf_h;

    fprintf(stderr, "MAIN CE Memory Manager: using %d CMEM HEAP allocated frame buffers, with size: %u\n", num_frames, ce_frame_size);

    frames = malloc(num_frames * sizeof(*frames));

    for (i = 0; i < num_frames; i++) {
	p = Memory_alloc(ce_frame_size, &mem_params);
    	if (!p) {
            fprintf(stderr, "Error allocating frame buffer %d on CMEM\n", i);
	    goto err;    
        }

	pp = (uint8_t *)Memory_getBufferPhysicalAddress(p, ce_frame_size, NULL);

        frames[i].virt[0] = p;
        frames[i].virt[1] = p + y_offset;
        frames[i].virt[2] = p + y_offset + buf_w / 2;
        frames[i].phys[0] = pp;
        frames[i].phys[1] = pp + y_offset;
        frames[i].phys[2] = pp + y_offset + buf_w / 2;
        frames[i].linesize[0] = ff->width;
        frames[i].linesize[1] = ff->width;
        frames[i].linesize[2] = ff->width;
    }

    ff->y_stride  = ff->width;
    ff->uv_stride = ff->width;

    *fr = frames;
    *nf = num_frames;

    return 0;

err:
    clear_count = i;
    for (i=0; i<clear_count; i++) {
	if (!frames) break;
	Memory_free(frames[i].virt[0], ce_frame_size, &mem_params);
    }

    Memory_free(input_buf, INPUT_BUFFER_SIZE, &mem_params);
    if (frames) free(frames);
    return -1;
}
Beispiel #11
0
/*
 * ======== OsalKfile_open ========
 */
Int
OsalKfile_open (String             fileName,
                Char *             fileMode,
                OsalKfile_Handle * fileHandle)
{
    Int                 status      = OSALKFILE_SUCCESS;
    struct file *       fileDesc    = NULL;
    OsalKfile_Object *  fileObject  = NULL;
    mm_segment_t        fs;

    GT_3trace (curTrace, GT_ENTER, "OsalKfile_open",
               fileName, fileMode, fileHandle);

    GT_assert (curTrace, (fileName != NULL));
    GT_assert (curTrace, (fileMode != NULL));
    GT_assert (curTrace, (fileHandle != NULL));

#if !defined(SYSLINK_BUILD_OPTIMIZE)
    if (fileName == NULL) {
        /*! @retval OSALKFILE_E_INVALIDARG NULL provided for argument
                                           fileName. */
        status = OSALKFILE_E_INVALIDARG;
        GT_setFailureReason (curTrace,
                             GT_4CLASS,
                             "OsalKfile_open",
                             status,
                             "NULL provided for argument fileName");
    }
    else if (fileMode == NULL) {
        /*! @retval OSALKFILE_E_INVALIDARG NULL provided for argument
                                           fileMode. */
        status = OSALKFILE_E_INVALIDARG;
        GT_setFailureReason (curTrace,
                             GT_4CLASS,
                             "OsalKfile_open",
                             status,
                             "NULL provided for argument fileMode");
    }
    else if (fileMode [0] != 'r') {
        /*! @retval OSALKFILE_E_INVALIDARG Only read 'r' mode is supported. */
        status = OSALKFILE_E_INVALIDARG;
        GT_setFailureReason (curTrace,
                             GT_4CLASS,
                             "OsalKfile_open",
                             status,
                             "Only read 'r' mode is supported.");
    }
    else if (fileHandle == NULL) {
        /*! @retval OSALKFILE_E_INVALIDARG NULL provided for argument
                                           fileHandle. */
        status = OSALKFILE_E_INVALIDARG;
        GT_setFailureReason (curTrace,
                             GT_4CLASS,
                             "OsalKfile_open",
                             status,
                             "NULL provided for argument fileHandle");
    }
    else {
#endif /* #if !defined(SYSLINK_BUILD_OPTIMIZE) */
        *fileHandle = NULL;
        fileObject = Memory_alloc (NULL, sizeof (OsalKfile_Object), 0, NULL);
#if !defined(SYSLINK_BUILD_OPTIMIZE)
        if (fileObject == NULL) {
            /*! @retval OSALKFILE_E_MEMORY Failed to allocate memory for
                                           OsalKfile object. */
            status = OSALKFILE_E_MEMORY;
            GT_setFailureReason (curTrace,
                             GT_4CLASS,
                             "OsalKfile_open",
                             status,
                             "Failed to allocate memory for OsalKfile object.");
        }
        else {
#endif /* #if !defined(SYSLINK_BUILD_OPTIMIZE) */
            fs = get_fs ();
            set_fs (KERNEL_DS);

            fileDesc = filp_open (fileName, O_RDONLY, 0) ;
#if !defined(SYSLINK_BUILD_OPTIMIZE)
            if (   (IS_ERR (fileDesc))
                || (fileDesc == NULL)
                || (fileDesc->f_op == NULL)
                || (fileDesc->f_op->read == NULL)) {
                /*! @retval OSALKFILE_E_FILEOPEN Failed to open file. */
                status = OSALKFILE_E_FILEOPEN;
                GT_setFailureReason (curTrace,
                                     GT_4CLASS,
                                     "Kfile_Open",
                                     status,
                                     "Failed to open file.");
            }
            else {
#endif /* #if !defined(SYSLINK_BUILD_OPTIMIZE) */
                fileObject->fileDesc = fileDesc;
                fileObject->fileName = fileName;
                fileObject->curPos = 0;

                *fileHandle = (OsalKfile_Handle) fileObject;

                /* Get the file size  */
                fileDesc->f_pos = 0u;

                if (fileDesc->f_op->llseek != NULL) {
                    fileObject->size =
                                fileDesc->f_op->llseek (fileDesc, 0, SEEK_END);
                    fileDesc->f_op->llseek (fileDesc, 0, SEEK_SET);
                }
                else {
                    fileObject->size = default_llseek (fileDesc,0,SEEK_END);
                    default_llseek (fileDesc, 0, SEEK_SET);
                }
#if !defined(SYSLINK_BUILD_OPTIMIZE)
            }
#endif /* #if !defined(SYSLINK_BUILD_OPTIMIZE) */

            /* If the function call failed then free the object allocated
             * earlier.
             */
            if (status < 0) {
                Memory_free (NULL, fileObject, sizeof (OsalKfile_Object));
                *fileHandle = NULL;
            }
            set_fs (fs);
#if !defined(SYSLINK_BUILD_OPTIMIZE)
        }
    }
#endif /* #if !defined(SYSLINK_BUILD_OPTIMIZE) */

    GT_1trace (curTrace, GT_LEAVE, "OsalKfile_open", status);

    /*! @retval OSALKFILE_SUCCESS Operation successfully completed. */
    return status;
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    SCALE_Handle codec = NULL;
    SCALE_Params params;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;

    unsigned char color_table_temp[1024]={0}; 

   //opencv var
    IplImage * frame;
    IplImage * gray_frame = NULL;
    IplImage * BinaryImage =NULL;
    CvCapture *cap=cvCreateCameraCapture(0);
    cvSetCaptureProperty(cap,CV_CAP_PROP_FRAME_WIDTH,320);
    cvSetCaptureProperty(cap,CV_CAP_PROP_FRAME_HEIGHT,240);
    cvSetCaptureProperty(cap,CV_CAP_PROP_FPS,30);



   /*YC added the bmp struct*/
#pragma pack(1)                       //採用1byte為單位對齊(需要讀檔頭)  
    static struct BMP_file_header {   //Total 54 bytes
           unsigned char Identifier[2];                     
           unsigned long  File_Size;            
           unsigned long  Reserved;          
           unsigned long  Bitmap_Data_Offset;  
           unsigned long   Bitmap_Header_Size;   
           unsigned long   Width;
           unsigned long   Height;       
           unsigned short  Planes;        
           unsigned short  Bits_Per_Pixel;      
           unsigned long   Compression;      
           unsigned long   Bitmap_Data_Size;  
           unsigned long   H_Resolution;        
           unsigned long   V_Resolution;         
           unsigned long   Used_Colors;           
           unsigned long   Important_Colors;  
    } BMP_header;  
    #pragma pack()

   static struct BMP_file_header *header_temp; 

    if (argc <= 1) {
        inFile = "./test2_8bit_gray.bmp";
        outFile = "./test2_8bit_sobel.bmp";
        createInFileIfMissing(inFile);
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    printf("App-> Application started.\n");

    /* allocate input, encoded, and output buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = Memory_DEFAULTALIGNMENT;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    

    if ((inBuf == NULL) || (outBuf == NULL)) {
        goto end;
    }



    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }


    //copy the Bmp_header
    header_temp=&BMP_header;                                                                    
    fread(header_temp,54,sizeof(unsigned char),in);                        
    fwrite(header_temp,54,sizeof(unsigned char),out);
 
    //copy the color table BGRA total 256*4=1024 bytes                                                                       
    fread(color_table_temp,1024,sizeof(unsigned char),in);
    fwrite(color_table_temp,1024,sizeof(unsigned char),out);  





   //capture video's frame
    frame = cvQueryFrame(cap);
   


    /* initialize scale factor */
    params.size = sizeof(SCALE_Params);
    params.initialScaleFactor = APP_SCALEFACTOR;

    /* allocate and initialize scale algo on the engine */
    codec = SCALE_create(ce, scaleName, &params);
    if (codec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", scaleName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    scale(codec, in, out);




end:
    /* teardown the codec */
    if (codec) {
        SCALE_delete(codec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }

    printf("app done.\n");
    return (0);
}
Beispiel #13
0
/*!
 * ======== VirtQueue_create ========
 */
VirtQueue_Object *VirtQueue_create(VirtQueue_callback callback,
        UInt16 remoteProcId)
{
    VirtQueue_Object *vq;
    void *vring_phys;
    Error_Block eb;

    Error_init(&eb);

    vq = Memory_alloc(NULL, sizeof(VirtQueue_Object), 0, &eb);
    if (!vq) {
        return (NULL);
    }

    vq->callback = callback;
    vq->id = numQueues++;
    vq->procId = remoteProcId;
    vq->last_avail_idx = 0;

    if (MultiProc_self() == appm3ProcId) {
        vq->id += 2;
    }

    switch (vq->id) {
        case ID_A9_TO_SYSM3:
            /* A9 -> SYSM3 */
            vring_phys = (struct vring *)((UInt)buf_addr + RP_MSG_BUFS_SPACE);
            break;
        case ID_SYSM3_TO_A9:
            /* SYSM3 */
            vring_phys = (struct vring *)((UInt)buf_addr +
                    RP_MSG_RING_SIZE + RP_MSG_BUFS_SPACE);
            break;
        case ID_A9_TO_APPM3:
            /* A9 -> APPM3 */
            vring_phys = (struct vring *)((UInt)buf_addr + RP_MSG_BUFS_SPACE +
                    RPMSG_IPC_MEM);
            break;
        case ID_APPM3_TO_A9:
            /* APPM3 */
            vring_phys = (struct vring *)((UInt)buf_addr +
                    RP_MSG_RING_SIZE + RP_MSG_BUFS_SPACE + RPMSG_IPC_MEM);
            break;
    }

    Log_print3(Diags_USER1,
            "vring: %d 0x%x (0x%x)\n", vq->id, (IArg)vring_phys,
            RP_MSG_RING_SIZE);

    vring_init(&(vq->vring), RP_MSG_NUM_BUFS, vring_phys, RP_MSG_VRING_ALIGN);

    /*
     *  Don't trigger a mailbox message every time A8 makes another buffer
     *  available
     */
    if (vq->procId == hostProcId || vq->procId == dspProcId) {
        vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
    }

    queueRegistry[vq->id] = vq;

    return (vq);
}
/*
 *  ======== Task_Instance_init ========
 */
Int Task_Instance_init(Task_Object *tsk, Task_FuncPtr fxn,
                const Task_Params *params, Error_Block *eb)
{
    Int align;
    Int status;
    SizeT stackSize;

    Assert_isTrue((BIOS_taskEnabled == TRUE), Task_A_taskDisabled);

    Assert_isTrue(((BIOS_getThreadType() != BIOS_ThreadType_Hwi) &&
                   (BIOS_getThreadType() != BIOS_ThreadType_Swi)), Task_A_badThreadType);

    Assert_isTrue((((params->priority == -1) || (params->priority > 0)) &&
                   (params->priority < (Int)Task_numPriorities)),
                   Task_A_badPriority);

    tsk->priority = params->priority;

    /* deal with undefined Task_Params defaults */
    if (params->stackHeap == NULL) {
        tsk->stackHeap = Task_defaultStackHeap;
    }
    else {
        tsk->stackHeap = params->stackHeap;
    }

    if (params->stackSize == 0) {
        stackSize = Task_defaultStackSize;
    }
    else {
        stackSize = params->stackSize;
    }

    align = Task_SupportProxy_getStackAlignment();

    if (params->stack != NULL) {
        if (align != 0) {
            UArg stackTemp;
            /* align low address to stackAlignment */
            stackTemp = (UArg)params->stack;
            stackTemp += align - 1;
            stackTemp &= -align;
            tsk->stack = (Ptr)xdc_uargToPtr(stackTemp);

            /* subtract what we removed from the low address from stackSize */
            tsk->stackSize = stackSize - (stackTemp - (UArg)params->stack);

            /* lower the high address as necessary */
            tsk->stackSize &= -align;
        }
        else {
            tsk->stack = params->stack;
            tsk->stackSize = stackSize;
        }
        /* tell Task_delete that stack was provided */
        tsk->stackHeap = (xdc_runtime_IHeap_Handle)(-1);
    }
    else {
        if (BIOS_runtimeCreatesEnabled) {
            if (align != 0) {
                /*
                 * round stackSize up to the nearest multiple of the alignment.
                 */
                tsk->stackSize = (stackSize + align - 1) & -align;
            }
            else {
                tsk->stackSize = stackSize;
            }

            tsk->stack = Memory_alloc(tsk->stackHeap, tsk->stackSize,
                                      align, eb);

            if (tsk->stack == NULL) {
                return (1);
            }
        }
    }

    tsk->fxn = fxn;
    tsk->arg0 = params->arg0;
    tsk->arg1 = params->arg1;

    tsk->env = params->env;

    tsk->vitalTaskFlag = params->vitalTaskFlag;
    if (tsk->vitalTaskFlag == TRUE) {
        Task_module->vitalTasks += 1;
    }

#ifndef ti_sysbios_knl_Task_DISABLE_ALL_HOOKS
    if (Task_hooks.length > 0) {
        tsk->hookEnv = Memory_calloc(Task_Object_heap(),
                Task_hooks.length * sizeof (Ptr), 0, eb);

        if (tsk->hookEnv == NULL) {
            return (2);
        }
    }
#endif

    status = Task_postInit(tsk, eb);

    if (Error_check(eb)) {
        return (3 + status);
    }

    return (0);   /* no failure states */
}
Beispiel #15
0
/*
 *  ======== tsk0_func ========
 *  Allocates a message and ping-pongs the message around the processors.
 *  A local message queue is created and a remote message queue is opened.
 *  Messages are sent to the remote message queue and retrieved from the
 *  local MessageQ.
 */
Void tsk0_func(UArg arg0, UArg arg1)
{
    MessageQ_Msg     msg;    
    MessageQ_Handle  messageQ;
    MessageQ_QueueId remoteQueueId;    
    Int              status;
    UInt16           msgId = 0;
    Ptr              buf;
    HeapBuf_Handle   heapHandle;
    HeapBuf_Params   hbparams;
    SizeT            blockSize;
    UInt             numBlocks;

    /* Compute the blockSize & numBlocks for the HeapBuf */
    numBlocks = 2;
    blockSize = sizeof(MessageQ_MsgHeader);

    /* Alloc a buffer from the default heap */
    buf = Memory_alloc(0, numBlocks * blockSize, 0, NULL);
    
    /* 
     *  Create the heap that is used for allocating MessageQ messages.
     */     
    HeapBuf_Params_init(&hbparams);
    hbparams.align          = 0;
    hbparams.numBlocks      = numBlocks;
    hbparams.blockSize      = blockSize;
    hbparams.bufSize        = numBlocks * blockSize;
    hbparams.buf            = buf;
    heapHandle = HeapBuf_create(&hbparams, NULL);
    if (heapHandle == NULL) {
        System_abort("HeapBuf_create failed\n" );
    }
        
    /* Register default system heap with MessageQ */
    MessageQ_registerHeap((IHeap_Handle)(heapHandle), HEAPID);

    /* Create the local message queue */
    messageQ = MessageQ_create(localQueueName, NULL);    
    if (messageQ == NULL) {
        System_abort("MessageQ_create failed\n" );
    }
    
    /* Open the remote message queue. Spin until it is ready. */
    do {
        status = MessageQ_open(remoteQueueName, &remoteQueueId); 
        /* 
         *  Sleep for 1 clock tick to avoid inundating remote processor
         *  with interrupts if open failed
         */
        if (status < 0) { 
            Task_sleep(1);
        }
    } while (status < 0);
    
    if (MultiProc_self() == 0) {
        /* Allocate a message to be ping-ponged around the processors */
        msg = MessageQ_alloc(HEAPID, sizeof(MessageQ_MsgHeader));
        if (msg == NULL) {
           System_abort("MessageQ_alloc failed\n" );
        }
        
        /* 
         *  Send the message to the remote processor and wait for a message
         *  from the previous processor.
         */
        System_printf("Start the main loop\n");
        while (msgId < NUMLOOPS) {
            /* Increment...the remote side will check this */
            msgId++;
            MessageQ_setMsgId(msg, msgId);
            
            System_printf("Sending a message #%d to %s\n", msgId, remoteQueueName);
            
            /* send the message to the remote processor */
            status = MessageQ_put(remoteQueueId, msg);
            if (status < 0) {
               System_abort("MessageQ_put had a failure/error\n");        
            }
            
            /* Get a message */
            status = MessageQ_get(messageQ, &msg, MessageQ_FOREVER);
            if (status < 0) {
               System_abort("This should not happen since timeout is forever\n");
            }
        }
    }
    else {
        /*
         *  Wait for a message from the previous processor and
         *  send it to the remote processor
         */
        System_printf("Start the main loop\n");
        while (TRUE) {
            /* Get a message */
            status = MessageQ_get(messageQ, &msg, MessageQ_FOREVER);
            if (status < 0) {
               System_abort("This should not happen since timeout is forever\n");
            }

            System_printf("Sending a message #%d to %s\n", MessageQ_getMsgId(msg),
                remoteQueueName);

            /* Get the message id */
            msgId = MessageQ_getMsgId(msg);

            /* send the message to the remote processor */
            status = MessageQ_put(remoteQueueId, msg);
            if (status < 0) {
               System_abort("MessageQ_put had a failure/error\n");
            }
            
            /* test done */
            if (msgId >= NUMLOOPS) {
                break;
            }
        }
    }
    
    System_printf("The test is complete\n");

    BIOS_exit(0);
}
/*
 *  ======== Algorithm_create ========
 */
Algorithm_Handle Algorithm_create(IALG_Fxns *fxns, Void *idma3FxnsVoid,
        Void *iresFxnsVoid, IALG_Params *params, Algorithm_Attrs *attrs)
{
    Algorithm_Obj *pObject = NULL;
    Int         groupId;
    IDMA3_Fxns *idma3Fxns = (IDMA3_Fxns *)idma3FxnsVoid;
    IRES_Fxns  *iresFxns = (IRES_Fxns *)iresFxnsVoid;
    IRES_Status iresStatus;
    UInt32      useCachedMem;

    Log_print5(Diags_ENTRY, "[+E] Algorithm_create> Enter("
            "fxns=0x%x, idma3Fxns=0x%x, iresFxns=0x%x, params=0x%x, "
            "attrs=0x%x)",
            (IArg)fxns, (IArg)idma3Fxns, (IArg)iresFxns, (IArg)params,
            (IArg)attrs);

    groupId = (attrs != NULL) ? attrs->groupId : -1;
    useCachedMem = (attrs != NULL) ? attrs->useCachedMem :
            Algorithm_USECACHEDMEM_DEFAULT;

    Log_print1(Diags_USER2, "Algorithm_create> useCachedMem = %d",
            (IArg)useCachedMem);

    /* if (attrs == NULL) use default groupId */
    if ((pObject = (Algorithm_Obj *)Memory_alloc(sizeof(Algorithm_Obj),
                 NULL)) == NULL) {
        Log_print0(Diags_USER7, "[+7] Algorithm_create> "
                "Alloc for a small object FAILED -- out of memory?");
        goto Algorithm_create_return;
    }

    pObject->alg = ALG_create(groupId, fxns, NULL, params, useCachedMem);
    pObject->idma3Fxns = NULL;
    pObject->iresFxns = NULL;
    pObject->groupId = groupId;

    if (pObject->alg == NULL) {
        Log_print0(Diags_USER7, "[+7] Algorithm_create> "
                "Algorithm creation FAILED; make sure that 1) alg params are "
                "correct/appropriate, 2) there is enough internal and external "
                "algorithm memory available -- check DSKT2 settings for heap "
                "assignments and scratch allocation");
        Algorithm_delete(pObject);
        pObject = NULL;
        goto Algorithm_create_return;
    }

    /* if the alg implements IDMA3, we need to negotiate DMA resources */
    if (idma3Fxns != NULL) {
        Int status;
        status = DMAN3_grantDmaChannels(pObject->groupId, &pObject->alg,
                &idma3Fxns, 1);

        if (status != DMAN3_SOK) {
            Log_print1(Diags_USER7, "[+7] Algorithm_create> "
                    "Granting DMA channels to algorithm through DMAN3 FAILED"
                    " (0x%x)", (IArg)status);
            Algorithm_delete(pObject);
            pObject = NULL;
            goto Algorithm_create_return;
        }

        pObject->idma3Fxns = idma3Fxns;  /* tell Algorithm_delete to release */
    }

    /* If alg implements IRES, allocate resources */
    if (iresFxns != NULL) {
        iresStatus = RMAN_assignResources(pObject->alg, iresFxns,
                pObject->groupId);

        if (iresStatus != IRES_OK) {
            Log_print1(Diags_USER7, "[+7] Algorithm_create> Assignment of "
                    "alg resources through RMAN FAILED (0x%x)",
                    (IArg)iresStatus);

            /* Free DMAN3 channels, if allocated */
            if (idma3Fxns != NULL) {
                DMAN3_releaseDmaChannels(&(pObject->alg),
                        &(pObject->idma3Fxns), 1);
            }

            Algorithm_delete(pObject);
            pObject = NULL;
            goto Algorithm_create_return;
        }
        pObject->iresFxns = iresFxns;
    }

Algorithm_create_return:

    Log_print1(Diags_EXIT, "[+X] Algorithm_create> return (0x%x)",
            (IArg)pObject);

    return (pObject);
}
Beispiel #17
0
/*
 *  ======== smain ========
 */
Int smain(String progName, String procId, String engineName,
          String inFile, String outFile)
{
    Engine_Handle ce = NULL;
    Engine_Attrs attrs;
    UNIVERSAL_Handle hUniversal = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    Memory_AllocParams allocParams;
    XDAS_Int8 *inBuf;
    XDAS_Int8 *outBuf;
    XDAS_Int8 *versionBuf;   /* acquire optional version from codecs */

    /* create the input file if it doesn't already exist */
    createInFileIfMissing(inFile);

    Log_print4(Diags_USER1, "[+1] App-> Application started, procId %s "
               "engineName %s input-file %s output-file %s.",
               (IArg)procId, (IArg)engineName, (IArg)inFile, (IArg)outFile);

    /*
     * Allocate buffers.
     * Note that the .flags field (cache) is ignored on BIOS-based systems.
     */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

    if ((inBuf == NULL) || (outBuf == NULL) || (versionBuf == NULL)) {
        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* Initialize attrs fields to default values, and set the procId */
    Engine_initAttrs(&attrs);
    attrs.procId = procId;

    /* Open the Engine */
    if ((ce = Engine_open(engineName, &attrs, NULL)) == NULL) {
        printf("App-> ERROR: can't open engine %s\n", engineName);
        goto end;
    }

    /* allocate and initialize universal alg on the engine */
    hUniversal = UNIVERSAL_create(ce, universalName, NULL);
    if (hUniversal == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", universalName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    processLoop(hUniversal, in, out, inBuf, outBuf, versionBuf);

end:
    /* teardown the codec */
    if (hUniversal) {
        UNIVERSAL_delete(hUniversal);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    Log_print0(Diags_USER1, "[+1] app done.");
    return (0);
}
/*
 *  ======== ffcio_open ========
 */
int ffcio_open(const char *path, unsigned flags, int llv_fd)
{
    int         dev_fd;
    FRESULT     result;
    BYTE        fflags;
    Error_Block eb;

    (void)llv_fd;
    
    if (!init) {
        for (dev_fd = 0; dev_fd < _NSTREAM; dev_fd++) {
            filTable[dev_fd] = NULL;
        }
        init = 1;
    }

    for (dev_fd = 0; dev_fd < _NSTREAM && filTable[dev_fd] != NULL; dev_fd++) {
    }

    if (dev_fd == _NSTREAM) {
        /* no available file handles */
        return (-1);
    }

    Error_init(&eb);

    filTable[dev_fd] = Memory_alloc(NULL, sizeof(FIL), 0, &eb);

    if (filTable[dev_fd] == NULL) {
        /* allocation failed */
        return (-1);
    }

    switch (flags & 0x3) {
        case O_RDONLY:
            fflags = FA_READ;
            break;

        case O_WRONLY:
            fflags = FA_WRITE;
            break;

        case O_RDWR:
            fflags = FA_READ | FA_WRITE;
            break;

        default:
            return (-1);
    }
    
    if (flags & O_TRUNC) {
        fflags |= FA_CREATE_ALWAYS;
    }

    if (flags & O_CREAT) {
        fflags |= FA_OPEN_ALWAYS;
    }

    if (flags & O_APPEND) {
            ;
    }

    if ((result = f_open(filTable[dev_fd], path, fflags)) != FR_OK) {
        Memory_free(NULL, filTable[dev_fd], sizeof(FIL));

        filTable[dev_fd] = NULL;

        dev_fd = -1;

        /* TODO: map result to errno */
        (void)result;
    }

    return (dev_fd);
}
Beispiel #19
0
/*!
 * ======== VirtQueue_create ========
 */
VirtQueue_Handle VirtQueue_create(UInt16 remoteProcId, VirtQueue_Params *params,
                                  Error_Block *eb)
{
    VirtQueue_Object *vq;
    Void *vringAddr;

    /* Perform initialization we can't do in Instance_init (being non-XDC): */
    _VirtQueue_init();

    vq = Memory_alloc(NULL, sizeof(VirtQueue_Object), 0, eb);
    if (NULL == vq) {
        return (NULL);
    }

    /* Create the thread protection gate */
    vq->gateH = GateHwi_create(NULL, eb);
    if (Error_check(eb)) {
        Log_error0("VirtQueue_create: could not create gate object");
        Memory_free(NULL, vq, sizeof(VirtQueue_Object));
        return (NULL);
    }

    vq->callback = params->callback;
    vq->id = params->vqId;
    vq->procId = remoteProcId;
    vq->last_avail_idx = 0;

#ifndef SMP
    if (MultiProc_self() == appm3ProcId) {
        /* vqindices that belong to AppM3 should be big so they don't
         * collide with SysM3's virtqueues */
         vq->id += 2;
    }
#endif

    switch (vq->id) {
        /* IPC transport vrings */
        case ID_SELF_TO_A9:
            /* IPU/DSP -> A9 */
            vringAddr = (struct vring *) IPC_MEM_VRING0;
            break;
        case ID_A9_TO_SELF:
            /* A9 -> IPU/DSP */
            vringAddr = (struct vring *) IPC_MEM_VRING1;
            break;
#ifndef SMP
        case ID_APPM3_TO_A9:
            /* APPM3 -> A9 */
            vringAddr = (struct vring *) IPC_MEM_VRING2;
            break;
        case ID_A9_TO_APPM3:
            /* A9 -> APPM3 */
            vringAddr = (struct vring *) IPC_MEM_VRING3;
            break;
#endif
        default:
            GateHwi_delete(&vq->gateH);
            Memory_free(NULL, vq, sizeof(VirtQueue_Object));
            return (NULL);
    }

    Log_print3(Diags_USER1,
            "vring: %d 0x%x (0x%x)\n", vq->id, (IArg)vringAddr,
            RP_MSG_RING_SIZE);

    /* See coverity related comment in vring_init() */
    /* coverity[overrun-call] */
    vring_init(&(vq->vring), RP_MSG_NUM_BUFS, vringAddr, RP_MSG_VRING_ALIGN);

    /*
     *  Don't trigger a mailbox message every time MPU makes another buffer
     *  available
     */
    if (vq->procId == hostProcId) {
        vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
    }

    queueRegistry[vq->id] = vq;

    return (vq);
}
Beispiel #20
0
/*
 *  ======== SemaphoreMP_pend ========
 */
Bool SemaphoreMP_pend(SemaphoreMP_Object *obj)
{
    UInt tskKey;
    SemaphoreMP_PendElem *elem;
    IArg gateMPKey;

    /* Check for correct calling context */
    Assert_isTrue((BIOS_getThreadType() == BIOS_ThreadType_Task),
                    SemaphoreMP_A_badContext);

    elem = ThreadLocal_getspecific(SemaphoreMP_pendElemKey);
    if (elem == NULL) {
        /* 
         * Choose region zero (instead of the region that contains the 
         * SemaphoreMP) since region zero is always accessible by all cores
         */
        elem = Memory_alloc(SharedRegion_getHeap(0), 
                sizeof(SemaphoreMP_PendElem), 0, NULL);
        ThreadLocal_setspecific(SemaphoreMP_pendElemKey, elem);
    }
    
    /* Enter the gate */
    gateMPKey = GateMP_enter((GateMP_Handle)obj->gate);

    if (obj->cacheEnabled) {
        Cache_inv(obj->attrs, sizeof(SemaphoreMP_Attrs), Cache_Type_ALL, TRUE);
    }
    
    /* check semaphore count */
    if (obj->attrs->count == 0) {
        /* lock task scheduler */
        tskKey = Task_disable();

        /* get task handle and block tsk */
        elem->task = (Bits32)Task_self();
        elem->procId = MultiProc_self();
        
        Task_block((Task_Handle)elem->task);
        
        if (obj->cacheEnabled) {
            Cache_wbInv(elem, sizeof(SemaphoreMP_PendElem), Cache_Type_ALL, TRUE);
        }

        /* add it to pendQ */
        ListMP_putTail((ListMP_Handle)obj->pendQ, (ListMP_Elem *)elem);

        /* Leave the gate */
        GateMP_leave((GateMP_Handle)obj->gate, gateMPKey);

        Task_restore(tskKey);/* the calling task will switch out here */

        return (TRUE);
    }
    else {
        obj->attrs->count--;
        if (obj->cacheEnabled) {
            Cache_wbInv(obj->attrs, sizeof(SemaphoreMP_Attrs), Cache_Type_ALL, 
                    TRUE);
        }

        /* Leave the gate */
        GateMP_leave((GateMP_Handle)obj->gate, gateMPKey);

        return (TRUE);
    }
}
Beispiel #21
0
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    AUDDEC1_Handle dec = NULL;
    AUDENC1_Handle enc = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Int i;
    Memory_AllocParams allocParams;

    if (argc <= 1) {
        inFile = "./in.dat";
        outFile = "./out.dat";
        createInFileIfMissing(inFile);
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    for (i = 0; i < NBUFFERS; i++) {
        inBuf[i] = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
        encodedBuf[i] = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE, &allocParams);
        outBuf[i] = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
#if USE_ANCDATA
        ancBuf[i] = (XDAS_Int8 *)Memory_alloc(ENCANCBUFSIZE, &allocParams);
        if (ancBuf[i] == NULL) {
            goto end;
        }
#endif

        if ((inBuf[i] == NULL) || (encodedBuf[i] == NULL) ||
            (outBuf[i] == NULL)) {

            goto end;
        }
    }
    /* we need one more encoded buffer than the others */
    encodedBuf[NBUFFERS] = (XDAS_Int8 *)Memory_alloc(EFRAMESIZE,
            &allocParams);
    if (encodedBuf[NBUFFERS] == NULL) {
        goto end;
    }

    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);
    if (versionBuf == NULL) {
        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video decoder on the engine */
    dec = AUDDEC1_create(ce, decoderName, NULL);
    if (dec == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", decoderName);
        goto end;
    }

    /* allocate and initialize video encoder on the engine */
    enc = AUDENC1_create(ce, encoderName, NULL);
    if (enc == NULL) {
        fprintf(stderr, "%s: error: can't open codec %s\n",
            progName, encoderName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    encode_decode(enc, dec, in, out);

end:
    /* teardown the codecs */
    if (enc) {
        AUDENC1_delete(enc);
    }
    if (dec) {
        AUDDEC1_delete(dec);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    for (i = 0; i < NBUFFERS; i++) {
        if (inBuf[i]) {
            Memory_free(inBuf[i], IFRAMESIZE, &allocParams);
        }
        if (encodedBuf[i]) {
            Memory_free(encodedBuf[i], EFRAMESIZE, &allocParams);
        }
        if (outBuf[i]) {
            Memory_free(outBuf[i], OFRAMESIZE, &allocParams);
        }
#if USE_ANCDATA
        if (ancBuf[i]) {
            Memory_free(ancBuf[i], ENCANCBUFSIZE, &allocParams);
        }
#endif
    }
    if (encodedBuf[NBUFFERS]) {
        Memory_free(encodedBuf[NBUFFERS], EFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Beispiel #22
0
/*
 *  ======== SemaphoreMP_Instance_init ========
 */
Int SemaphoreMP_Instance_init(SemaphoreMP_Object *obj, Int count,
        const SemaphoreMP_Params *params, Error_Block *eb)
{
    Ptr localAddr;
    Int status;
    IHeap_Handle regionHeap;
    ListMP_Params listMPParams;
    SharedRegion_SRPtr sharedShmBase;
    
    if (params->openFlag) {
        /* Open by sharedAddr */
        obj->objType = ti_sdo_ipc_Ipc_ObjType_OPENDYNAMIC;
        obj->attrs = (SemaphoreMP_Attrs *)params->sharedAddr;
        obj->regionId = SharedRegion_getId(obj->attrs);
        obj->cacheEnabled = SharedRegion_isCacheEnabled(obj->regionId);
    
        obj->mode = (SemaphoreMP_Mode)obj->attrs->mode;
    
        regionHeap = SharedRegion_getHeap(obj->regionId);
        Assert_isTrue(regionHeap != NULL, ti_sdo_ipc_SharedRegion_A_noHeap);
    
        /* get the local address of the SRPtr */
        localAddr = SharedRegion_getPtr(obj->attrs->gateMPAddr);
        status = GateMP_openByAddr(localAddr, (GateMP_Handle *)&(obj->gate));
        if (status < 0) {
            return (1);
        }
        
        /* Open the ListMP */
        localAddr = (Ptr)_Ipc_roundup(
            (UInt32)obj->attrs + sizeof(SemaphoreMP_Attrs), 
            SharedRegion_getCacheLineSize(obj->regionId));
        status = ListMP_openByAddr(localAddr, (ListMP_Handle *)&(obj->pendQ));
        if (status < 0) {
            /* obj->freeList set to NULL */
            return (4);
        }

        return (0);
    }

    /* init the gate */
    if (params->gate != NULL) {
        obj->gate = params->gate;
    }
    else {
        obj->gate = (ti_sdo_ipc_GateMP_Handle)GateMP_getDefaultRemote();
    }
    obj->mode = params->mode;
    
    if (params->sharedAddr == NULL) {
        /* Creating using a shared region ID */                
        obj->objType = ti_sdo_ipc_Ipc_ObjType_CREATEDYNAMIC_REGION;
        obj->regionId = params->regionId;
        obj->cacheEnabled = SharedRegion_isCacheEnabled(obj->regionId);
                
        /* Need to allocate from the heap */
        obj->allocSize = SemaphoreMP_sharedMemReq(params);
            
        regionHeap = SharedRegion_getHeap(obj->regionId);
        Assert_isTrue(regionHeap != NULL, ti_sdo_ipc_SharedRegion_A_noHeap);

        /* The region heap will take care of the alignment */
        obj->attrs = Memory_alloc(regionHeap, obj->allocSize, 0, eb);
        if (obj->attrs == NULL) {
            return (2);
        }
    }
    else {
        /* Creating using sharedAddr */
        obj->regionId = SharedRegion_getId(params->sharedAddr);
                    
        /* Assert that the buffer is in a valid shared region */
        Assert_isTrue(obj->regionId != SharedRegion_INVALIDREGIONID, 
                      ti_sdo_ipc_Ipc_A_addrNotInSharedRegion);
        
        /* Assert that sharedAddr is cache aligned */
        Assert_isTrue(((UInt32)params->sharedAddr % 
                      SharedRegion_getCacheLineSize(obj->regionId) == 0),
                      ti_sdo_ipc_Ipc_A_addrNotCacheAligned);
                
        /* set object's cacheEnabled, objType, and attrs  */
        obj->cacheEnabled = SharedRegion_isCacheEnabled(obj->regionId);
        obj->objType = ti_sdo_ipc_Ipc_ObjType_CREATEDYNAMIC;
        obj->attrs = (SemaphoreMP_Attrs *)params->sharedAddr;
    }
    
    /* Store the GateMP sharedAddr in the SemaphoreMP Attrs */
    obj->attrs->gateMPAddr = ti_sdo_ipc_GateMP_getSharedAddr(obj->gate);
    obj->attrs->mode = (Bits16)obj->mode;
    obj->attrs->count = count;
    
    /* Create the freeList */
    ListMP_Params_init(&listMPParams);
    listMPParams.sharedAddr = (Ptr)_Ipc_roundup((UInt32)obj->attrs +
            sizeof(SemaphoreMP_Attrs), 
            SharedRegion_getCacheLineSize(obj->regionId));
    listMPParams.gate = (GateMP_Handle)obj->gate;
    obj->pendQ = (ti_sdo_ipc_ListMP_Handle)ListMP_create(&listMPParams);
    if (obj->pendQ == NULL) {
        return (3);
    }
    
    /* Last thing, set the status */
    obj->attrs->status = SemaphoreMP_CREATED;
    if (obj->cacheEnabled) {
        Cache_wbInv(obj->attrs, sizeof(SemaphoreMP_Attrs), Cache_Type_ALL, 
                TRUE);
    }
    
    /* Add entry to NameServer */
    if (params->name != NULL) {
        /* We will store a shared pointer in the NameServer */
        sharedShmBase = SharedRegion_getSRPtr(obj->attrs,
                                              obj->regionId);
        obj->nsKey = NameServer_addUInt32((NameServer_Handle)
                SemaphoreMP_module->nameServer, params->name,
                (UInt32)sharedShmBase);
        if (obj->nsKey == NULL) {
            /* NameServer_addUInt32 failed */
            return (4); 
        }
    }
    
    return (0);
}
/*
 *  ======== smain ========
 */
Int smain(Int argc, String argv[])
{
    Engine_Handle ce = NULL;
    VIDANALYTICS_Handle analyzer = NULL;
    FILE *in = NULL;
    FILE *out = NULL;
    String inFile, outFile;
    Memory_AllocParams allocParams;

    if (argc <= 1) {
        inFile = "./in.dat";
        outFile = "./out.dat";
        createInFileIfMissing(inFile);
    }
    else if (argc == 3) {
        progName = argv[0];
        inFile = argv[1];
        outFile = argv[2];
    }
    else {
        fprintf(stderr, usage, argv[0]);
        exit(1);
    }

    GT_0trace(curMask, GT_1CLASS, "App-> Application started.\n");

    /* allocate input, encoded, and output buffers */
    allocParams.type = Memory_CONTIGPOOL;
    allocParams.flags = Memory_NONCACHED;
    allocParams.align = BUFALIGN;
    allocParams.seg = 0;

    inBuf = (XDAS_Int8 *)Memory_alloc(IFRAMESIZE, &allocParams);
    outBuf = (XDAS_Int8 *)Memory_alloc(OFRAMESIZE, &allocParams);
    versionBuf = (XDAS_Int8 *)Memory_alloc(MAXVERSIONSIZE, &allocParams);

    if ((inBuf == NULL) || (outBuf == NULL) || (versionBuf == NULL)) {
        goto end;
    }

    /* open file streams for input and output */
    if ((in = fopen(inFile, "rb")) == NULL) {
        printf("App-> ERROR: can't read file %s\n", inFile);
        goto end;
    }
    if ((out = fopen(outFile, "wb")) == NULL) {
        printf("App-> ERROR: can't write to file %s\n", outFile);
        goto end;
    }

    /* reset, load, and start DSP Engine */
    if ((ce = Engine_open(engineName, NULL, NULL)) == NULL) {
        fprintf(stderr, "%s: error: can't open engine %s\n",
            progName, engineName);
        goto end;
    }

    /* allocate and initialize video analyzer on the engine */
    analyzer = VIDANALYTICS_create(ce, analyzerName, NULL);
    if (analyzer == NULL) {
        printf( "App-> ERROR: can't open codec %s\n", analyzerName);
        goto end;
    }

    /* use engine to encode, then decode the data */
    analyze(analyzer, in, out);

end:
    /* teardown the codec */
    if (analyzer) {
        VIDANALYTICS_delete(analyzer);
    }

    /* close the engine */
    if (ce) {
        Engine_close(ce);
    }

    /* close the files */
    if (in) {
        fclose(in);
    }
    if (out) {
        fclose(out);
    }

    /* free buffers */
    if (inBuf) {
        Memory_free(inBuf, IFRAMESIZE, &allocParams);
    }
    if (outBuf) {
        Memory_free(outBuf, OFRAMESIZE, &allocParams);
    }
    if (versionBuf) {
        Memory_free(versionBuf, MAXVERSIONSIZE, &allocParams);
    }

    GT_0trace(curMask, GT_1CLASS, "app done.\n");
    return (0);
}
Beispiel #24
0
/* ========================================================================== */
TIMM_OSAL_PTR TIMM_OSAL_MallocExtn(TIMM_OSAL_U32 size,
                                   TIMM_OSAL_BOOL bBlockContiguous,
                                   TIMM_OSAL_U32 unBlockAlignment,
                                   TIMMOSAL_MEM_SEGMENTID tMemSegId,
							       TIMM_OSAL_PTR hHeap)
{

    TIMM_OSAL_PTR pData = TIMM_OSAL_NULL;
    TIMM_OSAL_U32 * pIntPtr = NULL;
    TIMM_OSAL_U32 total_alloc_size;
    TIMM_OSAL_U32 bytes_to_skip;
	Error_Block eb;

    /* If the alignment is 0, 2, 4, 8 or 16*/
    if((MEMORY_HEADER_SIZE >= unBlockAlignment))
    { 
       total_alloc_size = size + MEMORY_HEADER_SIZE;
       bytes_to_skip = 0;
    }
    else
    { 
       /* For 32 byte alignment or more */
       total_alloc_size = size + unBlockAlignment;
       bytes_to_skip = total_alloc_size - (size + MEMORY_HEADER_SIZE);
    }

    pData = Memory_alloc((xdc_runtime_IHeap_Handle)(hHeap), total_alloc_size, 
		                 unBlockAlignment, &eb);

    if (pData == NULL) 
    {
       TIMM_OSAL_Error("Memory Allocation failed!!!");
       pData = TIMM_OSAL_NULL;
    } 
    else 
    {
        /* Memory Allocation was successfull
          Store the size and corruption check symb in
          extra allocated bytes
        */

        gMallocCounter++;
        gSizeCounter += total_alloc_size;

        pIntPtr = (TIMM_OSAL_U32 *)pData;
        /* Because this is U32 pointer */
        pIntPtr = pIntPtr + bytes_to_skip/sizeof(TIMM_OSAL_U32);

	   /*
	   First 4 bytes of the 16 byte header are empty.
	   Next 4 bytes contain the heap handle
	   Next 2 bytes have the magic number for checking corruption
	   Next 2 bytes contain the bytes_to_skip (in case of alignment)
	   Final 4 bytes contain the total allocated size
	   */
	    pIntPtr++;
	    *pIntPtr++ = (TIMM_OSAL_U32)hHeap;
        *pIntPtr++ = (MEM_CORRUPT_CHECK_VAL | bytes_to_skip);
        *pIntPtr++ = total_alloc_size;
        pData = pIntPtr;
    }
    return pData;
}
Beispiel #25
0
/*
 *  ======== Loader_setSearchPath ========
 */
Bool Loader_setSearchPath(String path)
{
    Bool    retVal = TRUE;

    Log_print1(Diags_ENTRY, "[+E] Loader_setSearchPath> Enter (%s)",
               (IArg)path);

    Assert_isTrue(((libPath != NULL) && (tmpPath != NULL) && (pathLen > 0)) ||
                  ((libPath == NULL) && (tmpPath == NULL) && (pathLen == 0)),
                  (Assert_Id)NULL);

    if (path == NULL) {
        /* Unsetting the library search path */
        if (libPath) {
            Memory_free(NULL, libPath, pathLen);
            Memory_free(NULL, tmpPath, pathLen);
            pathLen = 0;
        }
    }
    else if (pathLen < strlen(path) + 1) {
        /* Current path buffer is NULL or too small, free and re-allocate */
        if (libPath) {
            Memory_free(NULL, libPath, pathLen);
            Memory_free(NULL, tmpPath, pathLen);
            libPath = tmpPath  = NULL;
        }

        pathLen = strlen(path) + 1;
        libPath = Memory_alloc(NULL, pathLen, 0, NULL);

        if (libPath == NULL) {
            Log_print1(Diags_USER7, "[+7] Loader_setSearchPath> "
                       "Memory allocation of size %d failed!", (IArg)pathLen);
            retVal = FALSE;
        }
        else {
            tmpPath = Memory_alloc(NULL, pathLen, 0, NULL);
            if (tmpPath == NULL) {
                Log_print1(Diags_USER7, "[+7] Loader_setSearchPath> "
                           "Memory allocation of size %d failed!", (IArg)pathLen);
                retVal = FALSE;
            }
        }
    }

    if (!retVal) {
        /* Cleanup on failure */
        if (libPath) {
            Memory_free(NULL, libPath, pathLen);
            libPath = NULL;
        }
        if (tmpPath) {
            Memory_free(NULL, tmpPath, pathLen);
            tmpPath = NULL;
        }
        pathLen = 0;
    }
    else {
        if (path) {
            /* Copy in the new path */
            Assert_isTrue(strlen(path) + 1 <= pathLen, (Assert_Id)NULL);
            strcpy(libPath, path);
        }
    }

    Assert_isTrue(((libPath != NULL) && (tmpPath != NULL) && (pathLen > 0)) ||
                  ((libPath == NULL) && (tmpPath == NULL) && (pathLen == 0)),
                  (Assert_Id)NULL);

    Log_print1(Diags_EXIT, "[+X] Loader_setSearchPath> Exit, returning %s",
               (IArg)(retVal ? "TRUE" : "FALSE"));

    return (retVal);
}
Beispiel #26
0
/*
 *  ======== HeapMultiBuf_Instance_init ========
 *  Initializes a dynamically created HeapMultiBuf. Dynamic initialization
 *  requires different steps than static initialization because the buffers
 *  are provided by the user. With static allocation, buffers with matching
 *  properties can be merged before allocation. For dynamic creation, the
 *  buffers have already been allocated, so to merge them we must create a
 *  heapBuf from one buffer then add the other buffer to it.
 */
Int HeapMultiBuf_Instance_init(HeapMultiBuf_Object *obj,
                                const HeapMultiBuf_Params *params,
                                Error_Block *eb)
{
    HeapBuf_Handle heapBuf, heapBuf1, heapBuf2;
    Int i, j, k;
    HeapMultiBuf_AddrPair addrPair;
    Char *endAddr;

        /* Start with one HeapBuf per buffer, then merge */
    obj->numBufs = params->numBufs;
        obj->numHeapBufs = params->numBufs;
    obj->blockBorrow = params->blockBorrow;
    
    /*
     * The bufsByAddr array stores the pairing between the ending address of
     * a buffer and the HeapBuf that manages it, so there is one entry per
     * provided buffer.
     */
    obj->bufsByAddr =
        Memory_alloc(NULL, params->numBufs * sizeof(HeapMultiBuf_AddrPair),
                     0, eb);
    if (Error_check(eb)) {
        return (1); /* Failed at 1 */
    }

    /*
     * To simplify initialization, bufsBySize is allocated to the largest
     * potential size, meaning one entry per buffer. If any of the buffers
     * are merged, there will be wasted spots in the bufsBySize array, but
     * this greatly simplifies the initialization.
     *
     * This array is calloc'd so that if one of the HeapBuf creates fails,
     * we can know how many HeapBufs to delete in finalize by checking for
     * NULL.
     */
    obj->bufsBySize =
        Memory_calloc(NULL, obj->numBufs * sizeof(HeapBuf_Object*), 0, eb);
    if (Error_check(eb)) {
        return (2); /* Failed at 2 */
    }

    /* Create all of the HeapBufs */
    for (i = 0; i < obj->numBufs; i++) {
        heapBuf = HeapBuf_create(&(params->bufParams[i]), eb);
        if (Error_check(eb)) {
            return (3); /* Failed at 3 */
        }
        
        /* Add the new heapBuf to the bufsBySize array */
        obj->bufsBySize[i] = heapBuf;
        
        /* Add the new heapBuf to bufsByAddr */
        addrPair.lastAddr = HeapBuf_getEndAddr(heapBuf);
        addrPair.heapBuf = heapBuf;
        /* Copy by value */
        obj->bufsByAddr[i] = addrPair;
    }
    
    /*
     * Sort the bufConfigs by size, then by align. This simplifies the search
     * for matching bufConfigs.
     */
    qsort(obj->bufsBySize, obj->numBufs,
          sizeof(HeapBuf_Handle), HeapMultiBuf_sizeAlignCompare);
    
    /* Find any HeapBufs which need to be merged. */
    for (i = 0; i < obj->numHeapBufs; i++) {
        heapBuf1 = obj->bufsBySize[i];
        for (j = i + 1; j < obj->numHeapBufs; j++) {
            heapBuf2 = obj->bufsBySize[j];
            /* If the blockSize and align are equal, merge them. */
            if ((HeapBuf_getBlockSize(heapBuf1) == 
                 HeapBuf_getBlockSize(heapBuf2)) &&
                (HeapBuf_getAlign(heapBuf1) ==
                 HeapBuf_getAlign(heapBuf2))) {
                /* Merge heapBuf2 into heapBuf1 */
                
                /* Update the bufsByAddr array first. */
                endAddr = HeapBuf_getEndAddr(heapBuf2);
                for (k = 0; k < obj->numBufs; k++) {
                    if (obj->bufsByAddr[k].lastAddr == endAddr) {
                        obj->bufsByAddr[k].heapBuf = heapBuf1;
                                                break;
                    }
                }
                
                /* Give heapBuf2's buffer to heapBuf1. */
                HeapBuf_mergeHeapBufs(heapBuf1, heapBuf2);
                
                /* 
                 * Move heapBuf2 to end of array. heapBuf2 is no longer used, 
                 * but is stored at the end of the array so that it can be
                 * deleted when the HeapMultiBuf is deleted.
                 */
                HeapMultiBuf_moveToEnd(obj->bufsBySize, obj->numHeapBufs, j);
                
                /* Shorten the perceived array length. */
                obj->numHeapBufs--;
                
                /* 
                 * Since the array has been shifted left, incrementing j would
                 * skip over the next HeapBuf in the array.
                 */
                j--;
            }
            else {
                /* If this one didn't match, then none do, so break. */
                break;
            }
        }
    }
    
    /*
     * Once all of the heapBufs have been created, sort the bufsByAddr
     * array. The bufConfigs param was sorted, so bufsBySize does not
     * need to be sorted here.
     */
    qsort(obj->bufsByAddr, obj->numBufs,
          sizeof(struct HeapMultiBuf_AddrPair), HeapMultiBuf_addrPairCompare);

    return (0); /* Success */
}
Beispiel #27
0
/*
 *  ======== GIO_Instance_init ========
 */
Int GIO_Instance_init(GIO_Object *obj, String name, UInt mode,
    const GIO_Params *params, Error_Block *eb)
{
    Int                 i, status;
    Queue_Handle        doneList;
    Queue_Handle        freeList;
    DEV_Handle          device;
    IOM_Packet          *packets;
    IOM_Fxns            *iomFxns;
    Ptr                 devp;
    
    obj->name = name;
    obj->numPackets = params->numPackets;
    obj->doneCount = 0;
    obj->freeCount = 0;
    obj->submitCount = 0;
    obj->mode = mode;
    obj->model = params->model;
    obj->timeout = params->timeout;

    if (params->sync == NULL) {       
        obj->userSync = FALSE;
        obj->sync = SyncSemThread_Handle_upCast(SyncSemThread_create(NULL, eb));
        if (obj->sync == NULL) {
            return (1);
        }
    }
    else {
        obj->sync = params->sync;
        obj->userSync = TRUE;
    }

    doneList = GIO_Instance_State_doneList(obj);
    Queue_construct(Queue_struct(doneList), NULL);
    
    freeList = GIO_Instance_State_freeList(obj);
    Queue_construct(Queue_struct(freeList), NULL);
    
    /* allocate packets */
    packets = Memory_alloc(NULL, sizeof(IOM_Packet) * (obj->numPackets), 0, eb);

    if (packets == NULL) {
        return (2);
    }

    obj->packets = packets;
    obj->freeCount = obj->numPackets;
   
    /* 
     * Split the buffer into packets and add to freeList
     */
    for (i = 0; i < obj->numPackets; i++) {
        Queue_enqueue(freeList, (Queue_Elem *)&packets[i]);
    }
    
    name = DEV_match(name, &device);    
        
    if (device == NULL) {
        /* The name was not found */
        Error_raise(eb, GIO_E_notFound, obj->name, 0);
        return (3);
    }

    obj->fxns = DEV_getFxns(device);
    iomFxns = (IOM_Fxns *)obj->fxns;       

    devp = DEV_getDevp(device);

    status = iomFxns->mdCreateChan(&obj->mdChan, devp, name, mode,
        params->chanParams, callback, obj);
  
    if (status != IOM_COMPLETED) {
        Error_raise(eb, GIO_E_createFailed, status, 0);
        return (4);
    }
    
    return (0);
}
Beispiel #28
0
/*
 *  ======== ti_sdo_ipc_ListMP_Instance_init ========
 */
Int ti_sdo_ipc_ListMP_Instance_init(ti_sdo_ipc_ListMP_Object *obj,
        const ti_sdo_ipc_ListMP_Params *params,
        Error_Block *eb)
{
    SharedRegion_SRPtr sharedShmBase;
    Ptr localAddr;
    Int status;
    ListMP_Params sparams;
    IHeap_Handle regionHeap;

    if (params->openFlag == TRUE) {
        /* Open by sharedAddr */
        obj->objType = ti_sdo_ipc_Ipc_ObjType_OPENDYNAMIC;
        obj->attrs = (ti_sdo_ipc_ListMP_Attrs *)params->sharedAddr;
        obj->regionId = SharedRegion_getId(&(obj->attrs->head));
        obj->cacheEnabled = SharedRegion_isCacheEnabled(obj->regionId);
        obj->cacheLineSize = SharedRegion_getCacheLineSize(obj->regionId);
    
        /* get the local address of the SRPtr */
        localAddr = SharedRegion_getPtr(obj->attrs->gateMPAddr);
        
        status = GateMP_openByAddr(localAddr, (GateMP_Handle *)&(obj->gate));
        if (status != GateMP_S_SUCCESS) {
            Error_raise(eb, ti_sdo_ipc_Ipc_E_internal, 0, 0);
            return (1);
        }
        
        return (0);
    }

    /* init the gate */
    if (params->gate != NULL) {
        obj->gate = params->gate;
    }
    else {
        obj->gate = (ti_sdo_ipc_GateMP_Handle)GateMP_getDefaultRemote();
    }
    
    if (params->sharedAddr == NULL) {
        /* Creating using a shared region ID */                
        obj->objType = ti_sdo_ipc_Ipc_ObjType_CREATEDYNAMIC_REGION;
        obj->regionId = params->regionId;
        obj->cacheEnabled = SharedRegion_isCacheEnabled(obj->regionId);
        obj->cacheLineSize = SharedRegion_getCacheLineSize(obj->regionId);
                
        /* Need to allocate from the heap */
        ListMP_Params_init(&sparams);
        sparams.regionId = params->regionId;
        obj->allocSize = ListMP_sharedMemReq(&sparams);
            
        regionHeap = SharedRegion_getHeap(obj->regionId);
        Assert_isTrue(regionHeap != NULL, ti_sdo_ipc_SharedRegion_A_noHeap);

        /* The region heap will take care of the alignment */
        obj->attrs = Memory_alloc(regionHeap, obj->allocSize, 0, eb);

        if (obj->attrs == NULL) {
            return (2);
        }
    }
    else {
        /* Creating using sharedAddr */
        obj->regionId = SharedRegion_getId(params->sharedAddr);
            
        /* Assert that the buffer is in a valid shared region */
        Assert_isTrue(obj->regionId != SharedRegion_INVALIDREGIONID, 
                      ti_sdo_ipc_Ipc_A_addrNotInSharedRegion);
                        
        /* set object's cacheEnabled, objType, and attrs  */
        obj->cacheEnabled = SharedRegion_isCacheEnabled(obj->regionId);
        obj->cacheLineSize = SharedRegion_getCacheLineSize(obj->regionId);
        obj->objType = ti_sdo_ipc_Ipc_ObjType_CREATEDYNAMIC;
        obj->attrs = (ti_sdo_ipc_ListMP_Attrs *)params->sharedAddr;

        /* Assert that sharedAddr is cache aligned */
        Assert_isTrue((obj->cacheLineSize == 0) ||
                      ((UInt32)params->sharedAddr % obj->cacheLineSize == 0),
                      ti_sdo_ipc_Ipc_A_addrNotCacheAligned);
    }

    /* init the head (to be empty) */
    ListMP_elemClear(&(obj->attrs->head));
       
    /* store the GateMP sharedAddr in the Attrs */
    obj->attrs->gateMPAddr = ti_sdo_ipc_GateMP_getSharedAddr(obj->gate);

    /* last thing, set the status */
    obj->attrs->status = ti_sdo_ipc_ListMP_CREATED;
        
    if (obj->cacheEnabled) {
        Cache_wbInv(obj->attrs, sizeof(ti_sdo_ipc_ListMP_Attrs), 
                Cache_Type_ALL, TRUE);
    }
        
    /* add to NameServer if name not NULL */
    if (params->name != NULL) {
        sharedShmBase = SharedRegion_getSRPtr(obj->attrs, obj->regionId);
        obj->nsKey = NameServer_addUInt32(
            (NameServer_Handle)ListMP_module->nameServer, params->name,
            (UInt32)sharedShmBase);
        
        if (obj->nsKey == NULL) {
            Error_raise(eb, ti_sdo_ipc_Ipc_E_nameFailed, params->name, 0);
            return (3);
        }
    }

    return (0);
}
Beispiel #29
0
/*
 *  ======== NameServerDrv_ioctl ========
 *
 */
static long NameServerDrv_ioctl(struct file *filp, unsigned int cmd,
                                unsigned long args)
{
    int                         osStatus = 0;
    Int32                       status = NameServer_S_SUCCESS;
    Int32                       ret;
    NameServerDrv_CmdArgs       cargs;
    Osal_Pid                    pid;

    GT_3trace(curTrace, GT_ENTER, "NameServerDrv_ioctl", filp, cmd, args);

    /* save the process id for resource tracking */
    pid = pid_nr(filp->f_owner.pid);

    /* copy the full args from user space */
    ret = copy_from_user(&cargs, (Ptr)args, sizeof(NameServerDrv_CmdArgs));
    GT_assert(curTrace, (ret == 0));

    switch (cmd) {
    case CMD_NAMESERVER_ADD: {
        NameServerDrv_Res * res = NULL;
        Ptr                 buf;

        /* allocate resource tracker object */
        res = Memory_alloc(NULL, sizeof(NameServerDrv_Res), 0, NULL);

        if (res == NULL) {
            status = NameServer_E_MEMORY;
            GT_setFailureReason(curTrace, GT_4CLASS,
                                "NameServerDrv_ioctl", status, "out of memory");
        }

        /* allocate memory for the name */
        if (status == NameServer_S_SUCCESS) {
            res->args.add.len = cargs.args.add.nameLen;
            res->args.add.name = Memory_alloc(NULL,
                                              cargs.args.add.nameLen, 0, NULL);

            if (res->args.add.name == NULL) {
                status = NameServer_E_MEMORY;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status, "out of memory");
            }
        }

        /* copy the name from user memory */
        if (status == NameServer_S_SUCCESS) {
            status = copy_from_user(res->args.add.name,
                                    cargs.args.add.name, cargs.args.add.nameLen);

            if (status != 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "copy_from_user failed");
                status = NameServer_E_OSFAILURE;
                osStatus = -EFAULT;
            }
        }

        /* allocate memory for the buf */
        if (status == NameServer_S_SUCCESS) {
            buf = Memory_alloc(NULL, cargs.args.add.len, 0, NULL);

            if (buf == NULL) {
                status = NameServer_E_MEMORY;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status, "out of memory");
            }
        }

        /* copy the value from user buf */
        if (status == NameServer_S_SUCCESS) {
            status = copy_from_user(buf, cargs.args.add.buf,
                                    cargs.args.add.len);

            if (status != 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "copy_from_user failed");
                status = NameServer_E_OSFAILURE;
                osStatus = -EFAULT;
            }
        }

        /* invoke the module api */
        if (status == NameServer_S_SUCCESS) {
            cargs.args.add.entry = NameServer_add(cargs.args.add.handle,
                                                  res->args.add.name, buf, cargs.args.add.len);

            if (cargs.args.addUInt32.entry == NULL) {
                status = NameServer_E_FAIL;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "NameServer_addUInt32 failed");
            }
        }

        /* track the resource by process id */
        if (status == NameServer_S_SUCCESS) {
            Int rstat;

            res->cmd = CMD_NAMESERVER_ADD; /* use this command for both */
            res->args.add.handle = cargs.args.add.handle;
            res->args.add.entry = cargs.args.add.entry;

            rstat = ResTrack_push(NameServerDrv_state.resTrack, pid,
                                  (List_Elem *)res);

            GT_assert(curTrace, (rstat >= 0));
        }

        /* don't need the buf memory anymore */
        if (buf != NULL) {
            Memory_free(NULL, buf, cargs.args.add.len);
        }

        /* failure cleanup */
        if (status < 0) {
            if ((res != NULL) && (res->args.add.name != NULL)) {
                Memory_free(NULL, res->args.add.name,
                            cargs.args.add.nameLen);
            }
            if (res != NULL) {
                Memory_free(NULL, res, sizeof(NameServerDrv_Res));
            }
        }
    }
    break;

    case CMD_NAMESERVER_ADDUINT32: {
        NameServerDrv_Res * res = NULL;

        /* allocate resource tracker object */
        res = Memory_alloc(NULL, sizeof(NameServerDrv_Res), 0, NULL);

        if (res == NULL) {
            status = NameServer_E_MEMORY;
            GT_setFailureReason(curTrace, GT_4CLASS,
                                "NameServerDrv_ioctl", status, "out of memory");
        }

        /* allocate memory for the name */
        if (status == NameServer_S_SUCCESS) {
            res->args.add.len = cargs.args.addUInt32.nameLen;
            res->args.add.name = Memory_alloc(NULL,
                                              cargs.args.addUInt32.nameLen, 0, NULL);

            if (res->args.add.name == NULL) {
                status = NameServer_E_MEMORY;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status, "out of memory");
            }
        }

        /* copy the name from user memory */
        if (status == NameServer_S_SUCCESS) {
            status = copy_from_user(res->args.add.name,
                                    cargs.args.addUInt32.name,
                                    cargs.args.addUInt32.nameLen);

            if (status != 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "copy_from_user failed");
                status = NameServer_E_OSFAILURE;
                osStatus = -EFAULT;
            }
        }

        /* invoke the module api */
        if (status == NameServer_S_SUCCESS) {
            cargs.args.addUInt32.entry = NameServer_addUInt32(
                                             cargs.args.addUInt32.handle, res->args.add.name,
                                             cargs.args.addUInt32.value);

            if (cargs.args.addUInt32.entry == NULL) {
                status = NameServer_E_FAIL;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "NameServer_addUInt32 failed");
            }
        }

        /* track the resource by process id */
        if (status == NameServer_S_SUCCESS) {
            Int rstat;

            res->cmd = CMD_NAMESERVER_ADD; /* use this command for both */
            res->args.add.handle = cargs.args.addUInt32.handle;
            res->args.add.entry = cargs.args.addUInt32.entry;

            rstat = ResTrack_push(NameServerDrv_state.resTrack, pid,
                                  (List_Elem *)res);

            GT_assert(curTrace, (rstat >= 0));
        }

        /* failure cleanup */
        if (status < 0) {
            if ((res != NULL) && (res->args.add.name != NULL)) {
                Memory_free(NULL, res->args.add.name,
                            cargs.args.addUInt32.nameLen);
            }
            if (res != NULL) {
                Memory_free(NULL, res, sizeof(NameServerDrv_Res));
            }
        }
    }
    break;

    case CMD_NAMESERVER_GET:
    {
        String   name;
        Ptr      value;
        UInt16 * procId = NULL;

        /* Allocate memory for the name */
        name = Memory_alloc (NULL, cargs.args.get.nameLen, 0, NULL);
        GT_assert (curTrace, (name != NULL));
        /* Copy the name */
        ret = copy_from_user (name,
                              cargs.args.get.name,
                              cargs.args.get.nameLen);
        GT_assert (curTrace, (ret == 0));

        /* Allocate memory for the buf */
        value = Memory_alloc (NULL, cargs.args.get.len, 0, NULL);
        GT_assert (curTrace, (value != NULL));

        /* Allocate memory for the procId */
        if (cargs.args.get.procLen > 0) {
            procId = Memory_alloc (NULL,
                                   cargs.args.get.procLen * sizeof(UInt16),
                                   0,
                                   NULL);
            GT_assert (curTrace, (procId != NULL));
        }
        /* Copy the procIds */
        ret = copy_from_user (procId,
                              cargs.args.get.procId,
                              cargs.args.get.procLen);
        GT_assert (curTrace, (ret == 0));

        status = NameServer_get (cargs.args.get.handle,
                                 name,
                                 value,
                                 &cargs.args.get.len,
                                 procId);
        /* Do not assert. This can return NameServer_E_NOTFOUND
         * as a valid runtime failure.
         */

        /* Copy the value */
        ret = copy_to_user (cargs.args.get.value,
                            value,
                            cargs.args.get.len);
        GT_assert (curTrace, (ret == 0));

        /* free the allocated memory */
        Memory_free (NULL, name, cargs.args.get.nameLen);
        Memory_free (NULL, value, cargs.args.get.len);
        if (procId != NULL) {
            Memory_free (NULL,
                         procId,
                         cargs.args.get.procLen *sizeof(UInt16));
        }

    }
    break;

    case CMD_NAMESERVER_GETLOCAL:
    {
        String   name;
        Ptr      value;

        /* Allocate memory for the name */
        name = Memory_alloc (NULL, cargs.args.getLocal.nameLen, 0, NULL);
        GT_assert (curTrace, (name != NULL));
        /* Copy the name */
        ret = copy_from_user (name,
                              cargs.args.getLocal.name,
                              cargs.args.getLocal.nameLen);
        GT_assert (curTrace, (ret == 0));

        /* Allocate memory for the buf */
        value = Memory_alloc (NULL, cargs.args.getLocal.len, 0, NULL);
        GT_assert (curTrace, (value != NULL));

        status = NameServer_getLocal (cargs.args.getLocal.handle,
                                      name,
                                      value,
                                      &cargs.args.getLocal.len);
        GT_assert (curTrace, (status >= 0));

        /* Copy the value */
        ret = copy_to_user (cargs.args.getLocal.value,
                            value,
                            cargs.args.getLocal.len);
        GT_assert (curTrace, (ret == 0));

        /* free the allocated memory */
        Memory_free (NULL, name, cargs.args.getLocal.nameLen);
        Memory_free (NULL, value,  cargs.args.getLocal.len);
    }
    break;

    case CMD_NAMESERVER_MATCH:
    {
        String name;

        /* Allocate memory for the name */
        name = Memory_alloc (NULL, cargs.args.match.nameLen, 0, NULL);
        GT_assert (curTrace, (name != NULL));
        /* Copy the name */
        ret = copy_from_user (name,
                              cargs.args.match.name,
                              cargs.args.match.nameLen);
        GT_assert (curTrace, (ret == 0));

        cargs.args.match.count = NameServer_match (
                                     cargs.args.match.handle,
                                     name,
                                     &cargs.args.match.value);
        GT_assert (curTrace, (cargs.args.match.count >= 0));

        /* free the allocated memory */
        Memory_free (NULL, name, cargs.args.match.nameLen);
    }
    break;

    case CMD_NAMESERVER_REMOVE: {
        NameServerDrv_Res   res;
        List_Elem *         elem;

        /* save for resource untracking */
        res.cmd = CMD_NAMESERVER_ADD;
        res.args.add.entry = NULL;

        /* allocate memory for the name */
        res.args.add.len = cargs.args.remove.nameLen;
        res.args.add.name = Memory_alloc(NULL,
                                         cargs.args.remove.nameLen, 0, NULL);

        if (res.args.add.name == NULL) {
            status = NameServer_E_MEMORY;
            GT_setFailureReason(curTrace, GT_4CLASS,
                                "NameServerDrv_ioctl", status, "out of memory");
        }

        /* copy the name from user memory */
        if (status == NameServer_S_SUCCESS) {
            status = copy_from_user(res.args.add.name,
                                    cargs.args.remove.name, cargs.args.remove.nameLen);

            if (status != 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "copy_from_user failed");
                status = NameServer_E_OSFAILURE;
                osStatus = -EFAULT;
            }
        }

        /* invoke the module api */
        if (status == NameServer_S_SUCCESS) {
            status = NameServer_remove(cargs.args.remove.handle,
                                       res.args.add.name);

            if (status < 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "NameServer_remove failed");
            }
        }

        /* untrack the resource */
        if (status == NameServer_S_SUCCESS) {
            NameServerDrv_Res * resPtr;

            ResTrack_remove(NameServerDrv_state.resTrack, pid,
                            (List_Elem *)(&res), NameServerDrv_resCmpFxn, &elem);

            GT_assert(curTrace, (elem != NULL));

            resPtr = (NameServerDrv_Res *)elem;
            Memory_free(NULL, resPtr->args.add.name, resPtr->args.add.len);
            Memory_free(NULL, elem, sizeof(NameServerDrv_Res));
        }

        /* don't need the name memory anymore */
        if (res.args.add.name != NULL) {
            Memory_free(NULL, res.args.add.name,
                        cargs.args.remove.nameLen);
        }
    }
    break;

    case CMD_NAMESERVER_REMOVEENTRY: {
        NameServerDrv_Res   res;
        List_Elem *         elem;

        /* save for resource untracking */
        res.cmd = CMD_NAMESERVER_ADD;
        res.args.add.name = NULL;
        res.args.add.entry = cargs.args.removeEntry.entry;

        /* invoke the module api */
        status = NameServer_removeEntry(cargs.args.removeEntry.handle,
                                        cargs.args.removeEntry.entry);

        if (status < 0) {
            GT_setFailureReason(curTrace, GT_4CLASS, "NameServerDrv_ioctl",
                                status, "NameServer_remove failed");
        }

        /* untrack the resource */
        if (status == NameServer_S_SUCCESS) {
            NameServerDrv_Res * resPtr;

            ResTrack_remove(NameServerDrv_state.resTrack, pid,
                            (List_Elem *)(&res), NameServerDrv_resCmpFxn, &elem);

            GT_assert(curTrace, (elem != NULL));

            resPtr = (NameServerDrv_Res *)elem;
            Memory_free(NULL, resPtr->args.add.name, resPtr->args.add.len);
            Memory_free(NULL, elem, sizeof(NameServerDrv_Res));
        }
    }
    break;

    case CMD_NAMESERVER_PARAMS_INIT:
    {
        NameServer_Params params;

        NameServer_Params_init (&params);
        ret = copy_to_user (cargs.args.ParamsInit.params,
                            &params,
                            sizeof (NameServer_Params));
        GT_assert (curTrace, (ret == 0));
    }
    break;

    case CMD_NAMESERVER_CREATE: {
        NameServer_Params   params;
        String              name = NULL;
        NameServerDrv_Res * res = NULL;

        /* allocate memory for the name */
        name = Memory_alloc(NULL, cargs.args.create.nameLen, 0, NULL);

        if (name == NULL) {
            status = NameServer_E_MEMORY;
            GT_setFailureReason(curTrace, GT_4CLASS,
                                "NameServerDrv_ioctl", status, "out of memory");
        }

        /* copy the name from user memory */
        if (status == NameServer_S_SUCCESS) {
            status = copy_from_user(name, cargs.args.create.name,
                                    cargs.args.create.nameLen);

            if (status != 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "copy_from_user failed");
                status = NameServer_E_OSFAILURE;
                osStatus = -EFAULT;
            }
        }

        /* copy the params from user memory */
        if (status == NameServer_S_SUCCESS) {
            status = copy_from_user(&params, cargs.args.create.params,
                                    sizeof(NameServer_Params));

            if (status != 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "copy_from_user failed");
                status = NameServer_E_OSFAILURE;
                osStatus = -EFAULT;
            }
        }

        /* allocate resource tracker object */
        if (status == NameServer_S_SUCCESS) {
            res = Memory_alloc(NULL, sizeof(NameServerDrv_Res), 0, NULL);

            if (res == NULL) {
                status = NameServer_E_MEMORY;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status, "out of memory");
            }
        }

        /* invoke the module api */
        if (status == NameServer_S_SUCCESS) {
            cargs.args.create.handle = NameServer_create(name, &params);

            if (cargs.args.create.handle == NULL) {
                status = NameServer_E_FAIL;
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "NameServer_create failed");
            }
        }

        /* track the resource by process id */
        if (status == NameServer_S_SUCCESS) {
            Int rstat;

            res->cmd = cmd;
            res->args.create.handle = cargs.args.create.handle;

            rstat = ResTrack_push(NameServerDrv_state.resTrack, pid,
                                  (List_Elem *)res);

            GT_assert(curTrace, (rstat >= 0));
        }

        /* don't need name memory anymore */
        if (name != NULL) {
            Memory_free(NULL, name, cargs.args.create.nameLen);
        }

        /* failure cleanup */
        if (status < 0) {
            if (res != NULL) {
                Memory_free(NULL, res, sizeof(NameServerDrv_Res));
            }
        }
    }
    break;

    case CMD_NAMESERVER_DELETE: {
        NameServerDrv_Res   res;
        List_Elem *         elem;

        /* save for resource untracking, handle set to null by delete */
        res.cmd = CMD_NAMESERVER_CREATE;
        res.args.create.handle = cargs.args.delete.handle;

        /* common code for delete command */
        status = NameServerDrv_cmd_delete(&cargs.args.delete.handle);

        /* untrack the resource */
        if (status == NameServer_S_SUCCESS) {
            ResTrack_remove(NameServerDrv_state.resTrack, pid,
                            (List_Elem *)(&res), NameServerDrv_resCmpFxn, &elem);

            GT_assert(curTrace, (elem != NULL));
            Memory_free(NULL, elem, sizeof(NameServerDrv_Res));
        }
    }
    break;

    case CMD_NAMESERVER_GETHANDLE:
    {
        String   name;

        /* Allocate memory for the name */
        name = Memory_alloc (NULL, cargs.args.getHandle.nameLen, 0, NULL);
        GT_assert (curTrace, (name != NULL));
        /* Copy the name */
        ret = copy_from_user (name,
                              cargs.args.getHandle.name,
                              cargs.args.getHandle.nameLen);
        GT_assert (curTrace, (ret == 0));

        cargs.args.getHandle.handle = NameServer_getHandle (name);

        /* free the allocated memory */
        Memory_free (NULL, name, cargs.args.getHandle.nameLen);
    }
    break;

    case CMD_NAMESERVER_SETUP: {
        /* register process with resource tracker */
        status = ResTrack_register(NameServerDrv_state.resTrack, pid);

        if (status < 0) {
            GT_setFailureReason(curTrace, GT_4CLASS, "NameServerDrv_ioctl",
                                status, "resource tracker register failed");
            status = NameServer_E_FAIL;
            pid = 0;
        }

        /* setup the module */
        if (status == NameServer_S_SUCCESS) {
            status = NameServer_setup();

            if (status < 0) {
                GT_setFailureReason(curTrace, GT_4CLASS,
                                    "NameServerDrv_ioctl", status,
                                    "kernel-side MessageQ_setup failed");
            }
        }

        /* failure case */
        if (status < 0) {
            if (pid != 0) {
                ResTrack_unregister(NameServerDrv_state.resTrack, pid);
            }
        }
    }
    break;

    case CMD_NAMESERVER_DESTROY: {
        /* unregister process from resource tracker */
        status = ResTrack_unregister(NameServerDrv_state.resTrack, pid);
        GT_assert(curTrace, (status >= 0));

        /* finalize the module */
        status = NameServer_destroy();
        GT_assert(curTrace, (status >= 0));
    }
    break;

    default:
    {
        /* This does not impact return status of this function, so retVal
         * comment is not used.
         */
        status = NameServer_E_INVALIDARG;
        GT_setFailureReason (curTrace,
                             GT_4CLASS,
                             "NameServerDrv_ioctl",
                             status,
                             "Unsupported ioctl command specified");
    }
    break;
    }

    cargs.apiStatus = status;

    /* copy the full args back to user space */
    ret = copy_to_user((Ptr)args, &cargs, sizeof(NameServerDrv_CmdArgs));
    GT_assert (curTrace, (ret == 0));

    GT_1trace (curTrace, GT_LEAVE, "NameServerDrv_ioctl", osStatus);

    /*! @retval 0 Operation successfully completed. */
    return osStatus;
}
/******************************************************************************
 * appMain
 ******************************************************************************/
Int main(Int argc, Char *argv[])
{
    UInt32 framesize;
    Memory_AllocParams memParams = Memory_DEFAULTPARAMS;
    
    printf("******************************************************************************\n");
    printf("Sample application for testing kernels in C6Accel started.\n");
    printf("******************************************************************************\n");
    /* This call must be made before the Memory_xxx() functions as it is required for the tracing functions
     in all the codec engine APIs that are used*/
    CERuntime_init();

    /* Reset timeObj used for benchmarking*/
    Time_reset(&sTime);

    /* Create call generates a C6ACCEL handle */
    hC6 = C6accel_create(engineName, NULL,algName, NULL);

    /*Check for failure*/
    if ( hC6 == NULL)
       {printf("%s: C6accel_create() failed \n",progName);
        goto end;
    }

    /* Create buffers for use by algorithms */

    /* Want to use cached & contiguous memory to get best performance from cortex when it also uses the buffers.*/
    memParams.flags = Memory_CACHED;
    memParams.type = Memory_CONTIGHEAP;

    /* Size all buffers for 6 bytes, to cope with worst case 16 bit 422Planar*/
    framesize = (MAX_WIDTH * MAX_HEIGHT * sizeof(Int32)*3/2);

    /* Create 16bit buffers for use by algorithms*/
    pSrcBuf_16bpp = Memory_alloc(framesize, &memParams);
    if (pSrcBuf_16bpp == NULL) {
        goto end;
    }
    else {
       Memory_cacheWbInv(pSrcBuf_16bpp, framesize);
    }
    
      pOutBuf_16bpp = Memory_alloc(framesize, &memParams);
    if (pOutBuf_16bpp == NULL) {
        goto end;
    }
    else {
       Memory_cacheWbInv(pOutBuf_16bpp, framesize);
    }
    
    pRefBuf_16bpp = Memory_alloc(framesize, &memParams);
    if (pRefBuf_16bpp == NULL) {
        goto end;
    }
    else {
       Memory_cacheWbInv(pRefBuf_16bpp, framesize);
    }

      pWorkingBuf_16bpp = Memory_alloc(framesize, &memParams);
    if (pWorkingBuf_16bpp == NULL) {
        goto end;
    }
    else {
       Memory_cacheWbInv(pWorkingBuf_16bpp, framesize);
    }
    
    pWorkingBuf2_16bpp = Memory_alloc(framesize, &memParams);
    if (pWorkingBuf2_16bpp == NULL) {
        goto end;
    }
    else {
       Memory_cacheWbInv(pWorkingBuf2_16bpp, framesize);
    }
  
   #ifdef DEVICE_FLOAT
   pWorkingBuf3_16bpp = Memory_alloc(framesize, &memParams);
    if (pWorkingBuf3_16bpp == NULL) {
        goto end;
    }
    else {
       Memory_cacheWbInv(pWorkingBuf3_16bpp, framesize);
    }
    #endif
    
    /* open file for csv output*/
    OPEN_LOG_FILE("benchmarking.txt");
   
    /* Call test functions for kernels in C6accel*/
    LOG_STRING("IMGLib Functions\n");
    LOG_STRING("640x480 8bit/pixel b/w Test Image \n");
    
    printf("-----------------------------------------------------------------------------\n");
    printf("Test for Image processing functions in C6Accel: \n");
    printf("-----------------------------------------------------------------------------\n");

    c6accel_test_IMG_histogram(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_median(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_conv(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_corr(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_sobel(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_muls(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_adds(hC6,WIDTH,HEIGHT);
    c6accel_test_IMG_subs(hC6,WIDTH,HEIGHT);
    LOG_STRING("800x600 YUYV Test Image \n");
    c6accel_test_IMG_YC_demux(hC6,YUV_WIDTH,YUV_HEIGHT);
    c6accel_test_IMG_YUV422PLtoYUV422SP(hC6,2,16,16,16, 8);
    c6accel_test_IMG_YUV422SPtoYUV422ILE( hC6,2,16,16,32);
    c6accel_test_IMG_YUV422SPtoYUV420PL(hC6,2,16,16,16, 8);
    LOG_STRING("DSPLib Functions\n");
    LOG_STRING("64k sample FFT \n");
    
    printf("-----------------------------------------------------------------------------\n");
    printf("Test for Fixed point Signal processing functions in C6Accel \n");
    printf("-----------------------------------------------------------------------------\n");
    c6accel_test_DSP_FFT(hC6,N);
    c6accel_test_DSP_IFFT(hC6,N);
    c6accel_test_DSP_AUTOCOR(hC6,Nx,Nr);
    c6accel_test_DSP_DOTPROD(hC6,Nr);

    /* Implementation of this function limits
    the rows and columns of matrices to be multiples of 4 and r1 >8 */
    c6accel_test_DSP_MATMUL(hC6,ROW1,COL1,COL2,SHIFT);
    c6accel_test_DSP_FIR(hC6,NOUT,NCOEFF);
    c6accel_test_DSP_IIR(hC6,NXIN,NCOEFF);

  // No need to use these on floating point devices
  #ifndef DEVICE_FLOAT
    LOG_STRING_P1("MATH kernels tested with size of data block %d \n", NMAX+1);
    printf("-----------------------------------------------------------------------------\n");
    printf("Test for Fixed point Math functions in C6Accel\n");
    printf("-----------------------------------------------------------------------------\n");
    c6accel_test_MATH_RTSARITH(hC6,NMAX);
    c6accel_test_MATH_RTSCONV(hC6,NMAX);
    c6accel_test_MATH_IQCONV(hC6,NMAX,GLOBAL_Q, Q1);
    c6accel_test_MATH_IQMATH(hC6,NMAX,GLOBAL_Q);
    c6accel_test_MATH_IQARITH(hC6,NMAX,GLOBAL_Q);
    c6accel_test_MATH_IQTRIG(hC6,NMAX,GLOBAL_Q);
  #endif
  
  #ifdef DEVICE_FLOAT
  /*Test function calls for floating point kernels in C6accel*/ 
    printf("-----------------------------------------------------------------------------\n");
    printf("Test for Floating point Math Functions in C6Accel \n");
    printf("-----------------------------------------------------------------------------\n");
    c6accel_test_MATH_RTSARITH(hC6,NMAX);
    c6accel_test_MATH_RTSCONV(hC6,NMAX); 
    c6accel_test_MATH_RTSFLT(hC6,BUFSIZE) ;
    c6accel_test_MATH_RTSFLTDP(hC6,BUFSIZE) ;
    
    printf("-----------------------------------------------------------------------------\n");
    printf("Test for Floating point Signal processing Functions in C6accel\n");
    printf("-----------------------------------------------------------------------------\n");
    c6accel_test_DSPF_sp_fftSPxSP(hC6, Npt, rad, 0, Npt);
    c6accel_test_DSPF_VECMUL(hC6,  BUFSIZE );
    c6accel_test_DSPF_VECRECIP(hC6,  NumX );
    c6accel_test_DSPF_VECSUM_SQ(hC6,  Nelements );
    c6accel_test_DSPF_W_VEC(hC6, Mfactor,   BUFSIZE );
    c6accel_test_DSPF_DOTPRODFXNS(hC6,  Nelements);
    c6accel_test_DSPF_MATFXNS(hC6,  16,  16,  16 );
    c6accel_test_DSPF_MAT_MUL_CPLX(hC6,  4,  8,  8 ); 
    c6accel_test_DSPF_MAT_TRANS(hC6,  NumR,  NumR );
    c6accel_test_DSPF_AUTOCOR(hC6,NumX,NumR);
    c6accel_test_DSPF_CONVOL(hC6,NumH,NumR); 
    //c6accel_test_DSPF_IIR(hC6,  NumX);
    c6accel_test_DSPF_FIR(hC6, 128,  4);
    c6accel_test_DSPF_sp_ifftSPxSP(hC6, Npt, rad, 0, Npt);
    c6accel_test_DSPF_BIQUAD(hC6,  BUFSIZE);
  #endif   

    CLOSE_LOG_FILE();

end:
     // Tear down C6ACCEL
    if (hC6)
       C6accel_delete(hC6);

    if(pSrcBuf_16bpp)
        Memory_free(pSrcBuf_16bpp, framesize, &memParams);

    if(pOutBuf_16bpp)
        Memory_free(pOutBuf_16bpp, framesize, &memParams);

    if(pRefBuf_16bpp)
        Memory_free(pRefBuf_16bpp, framesize, &memParams);

    if(pWorkingBuf_16bpp)
        Memory_free(pWorkingBuf_16bpp, framesize, &memParams);

    if(pWorkingBuf2_16bpp)
        Memory_free(pWorkingBuf2_16bpp, framesize, &memParams);

    #ifdef DEVICE_FLOAT
    if(pWorkingBuf3_16bpp)
        Memory_free(pWorkingBuf3_16bpp, framesize, &memParams);
    #endif

    printf("******************************************************************************\n");
    printf("All tests done.\n");
    printf("******************************************************************************\n");
    printf("\n");

   return (0);
}