Ejemplo n.º 1
0
int_t main(void)
{
   error_t error;
   NetInterface *interface;
   OsTask *task;
   MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
   Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
   Ipv6Addr ipv6Addr;
#endif

   //System initialization
   SystemInit();

   //Initialize kernel
   osInitKernel();
   //Configure debug UART
   debugInit(115200);

   //Start-up message
   TRACE_INFO("\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("*** CycloneTCP Web Server Demo ***\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("Copyright: 2010-2015 Oryx Embedded SARL\r\n");
   TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
   TRACE_INFO("Target: F28M35H52C1\r\n");
   TRACE_INFO("\r\n");

   //Configure I/Os
   ioInit();

   //TCP/IP stack initialization
   error = netInit();
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
   }

   //Configure the first Ethernet interface
   interface = &netInterface[0];

   //Set interface name
   netSetInterfaceName(interface, "eth0");
   //Set host name
   netSetHostname(interface, "WebServerDemo");
   //Select the relevant network adapter
   netSetDriver(interface, &f28m35xEthDriver);
   //Set host MAC address
   netSetPhyDriver(interface, &lan8710PhyDriver);
   macStringToAddr(APP_MAC_ADDR, &macAddr);
   netSetMacAddr(interface, &macAddr);

   //Initialize network interface
   error = netConfigInterface(interface);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
   }

#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
   //Get default settings
   dhcpClientGetDefaultSettings(&dhcpClientSettings);
   //Set the network interface to be configured by DHCP
   dhcpClientSettings.interface = interface;
   //Disable rapid commit option
   dhcpClientSettings.rapidCommit = FALSE;

   //DHCP client initialization
   error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
   //Failed to initialize DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize DHCP client!\r\n");
   }

   //Start DHCP client
   error = dhcpClientStart(&dhcpClientContext);
   //Failed to start DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start DHCP client!\r\n");
   }
#else
   //Set IPv4 host address
   ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
   ipv4SetHostAddr(interface, ipv4Addr);

   //Set subnet mask
   ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
   ipv4SetSubnetMask(interface, ipv4Addr);

   //Set default gateway
   ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
   ipv4SetDefaultGateway(interface, ipv4Addr);

   //Set primary and secondary DNS servers
   ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 0, ipv4Addr);
   ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif

#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
   //Get default settings
   slaacGetDefaultSettings(&slaacSettings);
   //Set the network interface to be configured
   slaacSettings.interface = interface;

   //SLAAC initialization
   error = slaacInit(&slaacContext, &slaacSettings);
   //Failed to initialize SLAAC?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize SLAAC!\r\n");
   }

   //Start IPv6 address autoconfiguration process
   error = slaacStart(&slaacContext);
   //Failed to start SLAAC process?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start SLAAC!\r\n");
   }
#else
   //Set link-local address
   ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
   ipv6SetLinkLocalAddr(interface, &ipv6Addr);

   //Set IPv6 prefix
   ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
   ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);

   //Set global address
   ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
   ipv6SetGlobalAddr(interface, &ipv6Addr);

   //Set router
   ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
   ipv6SetRouter(interface, &ipv6Addr);

   //Set primary and secondary DNS servers
   ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 0, &ipv6Addr);
   ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif

   //Get default settings
   httpServerGetDefaultSettings(&httpServerSettings);
   //Bind HTTP server to the desired interface
   httpServerSettings.interface = &netInterface[0];
   //Listen to port 80
   httpServerSettings.port = HTTP_PORT;
   //Client connections
   httpServerSettings.maxConnections = APP_HTTP_MAX_CONNECTIONS;
   httpServerSettings.connections = httpConnections;
   //Specify the server's root directory
   strcpy(httpServerSettings.rootDirectory, "/www/");
   //Set default home page
   strcpy(httpServerSettings.defaultDocument, "index.shtm");
   //Callback functions
   httpServerSettings.cgiCallback = httpServerCgiCallback;
   httpServerSettings.uriNotFoundCallback = httpServerUriNotFoundCallback;

   //HTTP server initialization
   error = httpServerInit(&httpServerContext, &httpServerSettings);
   //Failed to initialize HTTP server?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize HTTP server!\r\n");
   }

   //Start HTTP server
   error = httpServerStart(&httpServerContext);
   //Failed to start HTTP server?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start HTTP server!\r\n");
   }

   //Create a task to blink the LED
   task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Start the execution of tasks
   osStartKernel();

   //This function should never return
   return 0;
}
Ejemplo n.º 2
0
/**
 * \brief  Applet main entry. This function decodes received command and executes it.
 *
 * \param argc  always 1
 * \param argv  Address of the argument area..
 */
int main(int argc, char **argv)
{
    struct _Mailbox *pMailbox = (struct _Mailbox *) argv;
    uint32_t bufferSize, bufferAddr, memoryOffset, bytesToWrite;
    uint16_t pagesToWrite, pagesToRead;
    uint32_t bytesWritten = 0;
    uint32_t bytesRead = 0;
    uint32_t nbBadBlocks = 0;
    uint32_t nbBlocks = 0;
    /* Temporary buffer used for non block aligned read / write */
    uint32_t tempBufferAddr;
    uint16_t block, page, offset, i;
    uint8_t unAlignedPage;
    /* Index in source buffer during buffer copy */
    uint32_t offsetInSourceBuff;
    /* Index in destination buffer during buffer copy */
    uint32_t offsetInTargetBuff;
    /* Errors returned by SkipNandFlash functions */
    uint8_t error = 0;
    
    /* Global DMA driver instance for all DMA transfers in application. */
    sDmad dmad;

    /*----------------------------------------------------------
     * INIT:
     *----------------------------------------------------------*/
    if (pMailbox->command == APPLET_CMD_INIT) {
        /* Save info of communication link */
        comType = pMailbox->argument.inputInit.comType;

        /*  Re-configurate UART   (MCK maybe change in LowLevelInit())  */
        UART_Configure(115200, BOARD_MCK);

#if (DYN_TRACES == 1)
        dwTraceLevel = pMailbox->argument.inputInit.traceLevel;
#endif

        TRACE_INFO("-- NandFlash SAM-BA applet %s --\n\r", SAM_BA_APPLETS_VERSION);
        TRACE_INFO("-- %s\n\r", BOARD_NAME);
        TRACE_INFO("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);
        TRACE_INFO("INIT command\n\r");

        /* Initialize DMA driver instance with polling mode */
        DMAD_Initialize( &dmad, 1 );
        if ( NandFlashConfigureDmaChannels( &dmad ))
        {
            TRACE_INFO ("-E- Initialize DMA failed !");
        }
        TRACE_INFO ("-I- Initialize DMA done.\n\r");

        /* Configure SMC for Nandflash accesses */
        BOARD_ConfigureNandFlash(SMC);
        PIO_PinConfigure(pPinsNf, PIO_LISTSIZE(pPinsNf));

        if (pPinsNf->pio == 0) {
            pMailbox->status = APPLET_NO_DEV;
            pMailbox->argument.outputInit.bufferSize = 0;
            pMailbox->argument.outputInit.memorySize = 0;
            pMailbox->argument.outputInit.bufferAddress = (uint32_t) &end;
            TRACE_INFO("INIT command: No Nandflash defined for this board\n\r");
        }
        else {

            memset(&skipBlockNf, 0, sizeof(skipBlockNf));

            if (SkipBlockNandFlash_Initialize(&skipBlockNf,
                                              0,
                                              cmdBytesAddr,
                                              addrBytesAddr,
                                              dataBytesAddr,
                                              nfCePin,
                                              nfRbPin)) {

                pMailbox->status = APPLET_DEV_UNKNOWN;
                pMailbox->argument.outputInit.bufferSize = 0;
                pMailbox->argument.outputInit.memorySize = 0;
                TRACE_INFO("\tDevice Unknown\n\r");
            }
            else {

                TRACE_INFO("\tNandflash driver initialized\n\r");

                /* Get device parameters */
                memSize = NandFlashModel_GetDeviceSizeInBytes(&skipBlockNf.ecc.raw.model);
                blockSize = NandFlashModel_GetBlockSizeInBytes(&skipBlockNf.ecc.raw.model);
                numBlocks = NandFlashModel_GetDeviceSizeInBlocks(&skipBlockNf.ecc.raw.model);
                pageSize = NandFlashModel_GetPageDataSize(&skipBlockNf.ecc.raw.model);
                numPagesPerBlock = NandFlashModel_GetBlockSizeInPages(&skipBlockNf.ecc.raw.model);
                latestErasedBlock = 0xFFFF;

                pMailbox->status = APPLET_SUCCESS;
                pMailbox->argument.outputInit.bufferAddress = (uint32_t)EBI_SDRAMC_ADDR;
                pMailbox->argument.outputInit.bufferSize = blockSize;

                pMailbox->argument.outputInit.memorySize = memSize;
                TRACE_INFO("\t pageSize : 0x%x blockSize : 0x%x blockNb : 0x%x \n\r",  
                            (unsigned int)pageSize, (unsigned int)blockSize, (unsigned int)numBlocks);
            }
        }
    }

    /*----------------------------------------------------------
     * WRITE:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_WRITE) {

        memoryOffset = pMailbox->argument.inputWrite.memoryOffset;
        bufferAddr = pMailbox->argument.inputWrite.bufferAddr;
        tempBufferAddr = bufferAddr + blockSize;
        bytesToWrite = pMailbox->argument.inputWrite.bufferSize;
        unAlignedPage = 0;
        TRACE_INFO("WRITE arguments : offset 0x%x, buffer at 0x%x, of 0x%x Bytes\n\r",
               (unsigned int)memoryOffset, (unsigned int)bufferAddr, (unsigned int)bytesToWrite);

        pMailbox->argument.outputWrite.bytesWritten = 0;

        /* Check word alignment */
        if (memoryOffset % 4) {

            pMailbox->status = APPLET_ALIGN_ERROR;
            goto exit;
        }

        /* Retrieve page and block addresses */
        if (NandFlashModel_TranslateAccess(&(skipBlockNf.ecc.raw.model),
                                           memoryOffset,
                                           bytesToWrite,
                                           &block,
                                           &page,
                                           &offset)) {
            pMailbox->status = APPLET_FAIL;
            goto exit;
        }
        if (block != latestErasedBlock ){
            /* Erase target block */
            error = SkipBlockNandFlash_EraseBlock(&skipBlockNf, block, NORMAL_ERASE);
            if (error == NandCommon_ERROR_BADBLOCK) {
                pMailbox->status = APPLET_BAD_BLOCK;
                goto exit;
            }
            if (error) {
                pMailbox->status = APPLET_FAIL;
                goto exit;
            }
            latestErasedBlock = block;
            latestErasedPage = 0xff;
        }
        if (page <= ((uint8_t)(latestErasedPage + 1))){
            error = SkipBlockNandFlash_EraseBlock(&skipBlockNf, block, NORMAL_ERASE);
            if (error == NandCommon_ERROR_BADBLOCK) {
                pMailbox->status = APPLET_BAD_BLOCK;
                goto exit;
            }
            if (error) {
                pMailbox->status = APPLET_FAIL;
                goto exit;
            }
            latestErasedBlock = block;
            latestErasedPage = page;
        }

        offsetInSourceBuff = 0;
        TRACE_INFO("WRITE at block 0x%x, page 0x%x, offset 0x%x in page \n\r", 
                    (unsigned int)block, (unsigned int)page, (unsigned int)offset);
        if (offset ) {

            /* We are not page aligned. */
            offsetInTargetBuff = offset;
            memset((uint32_t *)tempBufferAddr, 0xFF, pageSize);
            while (offsetInTargetBuff < pageSize) {

                *(uint32_t *)(tempBufferAddr + offsetInTargetBuff) = *(uint32_t *)(bufferAddr + offsetInSourceBuff);
                offsetInSourceBuff += 4;
                offsetInTargetBuff += 4;
                bytesWritten += 4;
            }
            error = SkipBlockNandFlash_WritePage(&skipBlockNf, block, page, ( void *)tempBufferAddr ,0);
            if (error == NandCommon_ERROR_BADBLOCK) {
                pMailbox->status = APPLET_BAD_BLOCK;
                goto exit;
            }
            if (error) {
                pMailbox->status = APPLET_FAIL;
                goto exit;
            }
            unAlignedPage++;
        }

        pagesToWrite = (bytesToWrite - bytesWritten) / pageSize;
        if (bytesToWrite - ((pagesToWrite + unAlignedPage)  * pageSize)) {
            pagesToWrite++;
        }
        if ((pagesToWrite + page ) > numPagesPerBlock)
        {
            pagesToWrite = numPagesPerBlock - page;
        }
        /* Write target block */
        error = SkipBlockNandFlash_WriteBlockUnaligned(&skipBlockNf, block, (page + unAlignedPage), pagesToWrite, ( void *)(bufferAddr + offsetInSourceBuff));
        bytesWritten += pagesToWrite * pageSize;
        if (bytesWritten > bytesToWrite) {
            bytesWritten = bytesToWrite;
        }
        if (error == NandCommon_ERROR_BADBLOCK) {

            pMailbox->status = APPLET_BAD_BLOCK;
            goto exit;
        }
        if (error) {

            pMailbox->status = APPLET_FAIL;
            goto exit;
        }

        pMailbox->argument.outputWrite.bytesWritten = bytesWritten;
        pMailbox->status = APPLET_SUCCESS;
    }

    /*----------------------------------------------------------
     * READ:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_READ) {

        memoryOffset = pMailbox->argument.inputRead.memoryOffset;
        bufferAddr   = pMailbox->argument.inputRead.bufferAddr;
        tempBufferAddr = bufferAddr + blockSize;

        bufferSize   = pMailbox->argument.inputRead.bufferSize;

        TRACE_INFO("READ at offset: 0x%x buffer at : 0x%x of: 0x%x Bytes\n\r",
               (unsigned int)memoryOffset, (unsigned int)bufferAddr, (unsigned int)bufferSize);

        pMailbox->argument.outputRead.bytesRead = 0;
        unAlignedPage = 0;
        /* Check word alignment */

        if (memoryOffset % 4) {

            pMailbox->status = APPLET_ALIGN_ERROR;
            goto exit;
        }

        /* Retrieve page and block addresses */
        if (NandFlashModel_TranslateAccess(&(skipBlockNf.ecc.raw.model),
                                           memoryOffset,
                                           bufferSize,
                                           &block,
                                           &page,
                                           &offset)) {
            pMailbox->status = APPLET_FAIL;
            goto exit;
        }

        TRACE_INFO("READ at block 0x%x, page 0x%x, offset in page 0x%x\n\r", 
        (unsigned int)block, (unsigned int)page, (unsigned int)offset);
        offsetInTargetBuff = 0;
        if (offset) {
            memset((uint32_t *)tempBufferAddr, 0xFF, pageSize);
            error = SkipBlockNandFlash_ReadPage(&skipBlockNf, block, page, ( void *)tempBufferAddr ,0);
            if (error == NandCommon_ERROR_BADBLOCK) {
                pMailbox->status = APPLET_BAD_BLOCK;
                goto exit;
            }
            if (error) {
                pMailbox->status = APPLET_FAIL;
                goto exit;
            }

            /* Fill dest buffer with read data */
            offsetInSourceBuff = offset;
            while (offsetInSourceBuff < pageSize) {
                *(uint32_t *)(bufferAddr + offsetInTargetBuff) = *(uint32_t *)(tempBufferAddr + offsetInSourceBuff);
                offsetInSourceBuff += 4;
                offsetInTargetBuff += 4;
                bytesRead += 4;
            }
            unAlignedPage++;
        }
        pagesToRead = (bufferSize - bytesRead) / pageSize;
        if (bufferSize - ((pagesToRead + unAlignedPage)* pageSize)) {
            pagesToRead++;
        }
        if ((pagesToRead + page ) > numPagesPerBlock)
        {
            pagesToRead = numPagesPerBlock - page;
        }
        /* Read target block */
        error = SkipBlockNandFlash_ReadBlockUnaligned(&skipBlockNf, block, (page + unAlignedPage), pagesToRead, ( void *)(bufferAddr + offsetInTargetBuff));
        bytesRead += pagesToRead * pageSize;
        if (bytesRead > bufferSize) {
            bytesRead = bufferSize;
        }
        if (error == NandCommon_ERROR_BADBLOCK) {

            pMailbox->status = APPLET_BAD_BLOCK;
            goto exit;
        }
        if (error) {
            pMailbox->status = APPLET_FAIL;
            goto exit;
        }

        pMailbox->argument.outputRead.bytesRead = bytesRead;
        pMailbox->status = APPLET_SUCCESS;
    }

    /*----------------------------------------------------------
     * FULL ERASE:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_FULL_ERASE) {

        TRACE_INFO("FULL ERASE command\n\r");
        TRACE_INFO("\tForce erase flag: 0x%x\n\r", (unsigned int)pMailbox->argument.inputFullErase.eraseType);

        for (i = 0; i < numBlocks; i++) {

            /* Erase the page */
            if (SkipBlockNandFlash_EraseBlock(&skipBlockNf, i, pMailbox->argument.inputFullErase.eraseType)) {

                TRACE_INFO("Found block #%d BAD, skip it\n\r", (unsigned int)i);
            }
        }

        TRACE_INFO("Full Erase achieved\n\r");
        pMailbox->status = APPLET_SUCCESS;
    }

    /*----------------------------------------------------------
     * BATCH FULL ERASE:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_BATCH_ERASE) {

        TRACE_INFO("BATCH ERASE command\n\r");
        block = pMailbox->argument.inputBatchErase.batch * (numBlocks / ERASE_BATCH);

        TRACE_INFO("Erase block from #%d to #%d\n\r", (unsigned int)block, (unsigned int)(block + (numBlocks / ERASE_BATCH)));
        for (i = block ; i < block + (numBlocks / ERASE_BATCH) ; i++) {

            /* Erase the block */
            if (SkipBlockNandFlash_EraseBlock(&skipBlockNf, i, pMailbox->argument.inputBatchErase.eraseType)) {

                TRACE_INFO("Found block #%d BAD, skip it\n\r", (unsigned int)i);
            }
        }

        if ((pMailbox->argument.inputBatchErase.batch + 1) == ERASE_BATCH) {
            TRACE_INFO("Full Erase achieved, erase type is %d\n\r", (unsigned int)pMailbox->argument.inputBatchErase.eraseType);
            pMailbox->argument.outputBatchErase.nextBatch = 0;
        }
        else {
            pMailbox->argument.outputBatchErase.nextBatch =  pMailbox->argument.inputBatchErase.batch + 1;
            TRACE_INFO("Batch Erase achieved\n\r");
        }
        pMailbox->status = APPLET_SUCCESS;
    }

    /*----------------------------------------------------------
     * ERASE_BLOCKS:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_ERASE_BLOCKS) {

        TRACE_INFO("BLOCKS ERASE command\n\r");
        memoryOffset = pMailbox->argument.inputBlocksErase.memoryOffsetStart;
        if ((pMailbox->argument.inputBlocksErase.memoryOffsetEnd > memSize) || (pMailbox->argument.inputBlocksErase.memoryOffsetEnd < memoryOffset) ) {
            TRACE_INFO("Out of memory space\n\r");
            pMailbox->status = APPLET_ERASE_FAIL;
            goto exit;
        }
        nbBlocks = ((pMailbox->argument.inputBlocksErase.memoryOffsetEnd- memoryOffset)/ blockSize) + 1;

        TRACE_INFO("Erase blocks from %d  to %d \n\r",  (unsigned int)(memoryOffset / blockSize),(unsigned int)((memoryOffset / blockSize)+ nbBlocks) );
        /* Erase blocks */
        for (i =  memoryOffset / blockSize; i < memoryOffset / blockSize + nbBlocks ; i++) {
            if (SkipBlockNandFlash_EraseBlock(&skipBlockNf,  i , NORMAL_ERASE)) {
                 TRACE_INFO("Found block #%d BAD, skip it\n\r",  (unsigned int)i);
            }
        }
        TRACE_INFO("Blocks Erase achieved\n\r");
        pMailbox->status = APPLET_SUCCESS;
    }

    /*----------------------------------------------------------
     * LIST BAD BLOCKS:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_LIST_BAD_BLOCKS) {

        TRACE_INFO("LIST BAD BLOCKS command\n\r");

        nbBadBlocks = 0;
        bufferAddr = (uint32_t) &end;
        pMailbox->argument.outputListBadBlocks.bufferAddress = bufferAddr;

        for (i = 0; i < numBlocks; i++) {

            /* Erase the page */
            if (SkipBlockNandFlash_CheckBlock(&skipBlockNf, i) == BADBLOCK) {

                nbBadBlocks++;
                *((uint32_t *)bufferAddr) = i;
                bufferAddr += 4;
                TRACE_INFO("Found block #%d BAD\n\r", i);
            }
        }

        TRACE_INFO("LIST BAD BLOCKS achieved\n\r");

        pMailbox->argument.outputListBadBlocks.nbBadBlocks = nbBadBlocks;

        pMailbox->status = APPLET_SUCCESS;
    }

    /*----------------------------------------------------------
     * TAG BLOCK:
     *----------------------------------------------------------*/
    else if (pMailbox->command == APPLET_CMD_TAG_BLOCK) {

        TRACE_INFO("TAG BLOCK command\n\r");

        bufferAddr = (uint32_t) &end;
        block = pMailbox->argument.inputTagBlock.blockId;

        /* To tag the block as good, just erase it without bad block check */
        if ((uint8_t)pMailbox->argument.inputTagBlock.tag == 0xFF)
        {
            if (SkipBlockNandFlash_EraseBlock(&skipBlockNf, block, SCRUB_ERASE)) {

                TRACE_INFO("Cannot erase block %d\n\r", (unsigned int)block);
                pMailbox->status = APPLET_FAIL;
                goto exit;
            }
        }
        else {

            for (i = 0; i < 2; i++) {

                /* Start by reading the spare */
                memset((uint8_t *)bufferAddr, 0xFF, NandCommon_MAXSPAREECCBYTES);

                TRACE_INFO("Tag to write : 0x%x\n\r", (unsigned int)pMailbox->argument.inputTagBlock.tag);

                NandSpareScheme_WriteBadBlockMarker((struct NandSpareScheme *)(NandFlashModel_GetScheme((struct NandFlashModel *)(&skipBlockNf))),
                                                    (uint8_t *)bufferAddr,
                                                    ((uint8_t)pMailbox->argument.inputTagBlock.tag));

                if (RawNandFlash_WritePage((struct RawNandFlash *)(&skipBlockNf), block, i, 0, (uint8_t *)bufferAddr)) {

                    TRACE_ERROR("Failed to write spare data of page %d of block %d\n\r", i, block);
                    pMailbox->status = APPLET_FAIL;
                    goto exit;
                }
            }
        }

        TRACE_INFO("TAG BLOCK achieved\n\r");

        pMailbox->status = APPLET_SUCCESS;
    }

exit :
    /* Acknowledge the end of command */
    TRACE_INFO("\tEnd of applet (command : %x --- status : %x)\n\r", (unsigned int)pMailbox->command, (unsigned int)pMailbox->status);

    /* Notify the host application of the end of the command processing */
    pMailbox->command = ~(pMailbox->command);
    if (comType == DBGU_COM_TYPE) {
        UART_PutChar(0x6);
    }

    return 0;
}
Ejemplo n.º 3
0
uint8_t SkipBlockNandFlash_Initialize(
    struct SkipBlockNandFlash *skipBlock,
    const struct NandFlashModel *model,
    uint32_t commandAddress,
    uint32_t addressAddress,
    uint32_t dataAddress,
    const Pin pinChipEnable,
    const Pin pinReadyBusy)
{
    uint8_t error;
#if !defined(OP_BOOTSTRAP_on)
    uint32_t numBlocks;
    uint32_t block;
#endif

    TRACE_DEBUG("SkipBlockNandFlash_Initialize()\n\r");

    /* Initialize SkipBlockNandFlash */
    #if !defined(OP_BOOTSTRAP_on)
    error = EccNandFlash_Initialize(ECC(skipBlock),
                                    model,
                                    commandAddress,
                                    addressAddress,
                                    dataAddress,
                                    pinChipEnable,
                                    pinReadyBusy);
    #else
    error = RawNandFlash_Initialize(RAW(skipBlock),
                                    model,
                                    commandAddress,
                                    addressAddress,
                                    dataAddress,
                                    pinChipEnable,
                                    pinReadyBusy);
#endif

#if !defined(OP_BOOTSTRAP_on)
    if (error) {

        return error;
    }

    /* Retrieve model information */
    numBlocks = NandFlashModel_GetDeviceSizeInBlocks(MODEL(skipBlock));

    /* Initialize block statuses */
    TRACE_DEBUG("Retrieving bad block information ...\n\r");

    /* Retrieve block status from their first page spare area */

    for (block = 0; block < numBlocks; block++) {

        /* Read spare of first page */
        error = SkipBlockNandFlash_CheckBlock(skipBlock, block);

        if (error != GOODBLOCK) {
            
            if (error == BADBLOCK) {
                
                TRACE_DEBUG("Block #%d is bad\n\r", block);
            }
            else {
                
                TRACE_ERROR(
                "SkipBlockNandFlash_Initialize: Cannot retrieve info from block #%lu\n\r", block);
            }
        }
    }
#endif

    return 0;
}
Ejemplo n.º 4
0
int_t main(void)
{
   error_t error;
   NetInterface *interface;
   OsTask *task;
   MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
   Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
   Ipv6Addr ipv6Addr;
#endif

   //Update system core clock
   SystemCoreClockUpdate();

   //Initialize kernel
   osInitKernel();
   //Configure debug UART
   debugInit(115200);

   //Start-up message
   TRACE_INFO("\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("*** CycloneTCP FTP Client Demo ***\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("Copyright: 2010-2014 Oryx Embedded\r\n");
   TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
   TRACE_INFO("Target: LPC4330\r\n");
   TRACE_INFO("\r\n");

   //Configure I/Os
   ioInit();

   //TCP/IP stack initialization
   error = tcpIpStackInit();
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
   }

   //Configure the first Ethernet interface
   interface = &netInterface[0];

   //Set interface name
   tcpIpStackSetInterfaceName(interface, "eth0");
   //Set host name
   tcpIpStackSetHostname(interface, "FTPClientDemo");
   //Select the relevant network adapter
   tcpIpStackSetDriver(interface, &lpc43xxEthDriver);
   tcpIpStackSetPhyDriver(interface, &lan8720PhyDriver);
   //Set host MAC address
   macStringToAddr(APP_MAC_ADDR, &macAddr);
   tcpIpStackSetMacAddr(interface, &macAddr);

   //Initialize network interface
   error = tcpIpStackConfigInterface(interface);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
   }

#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
   //Get default settings
   dhcpClientGetDefaultSettings(&dhcpClientSettings);
   //Set the network interface to be configured by DHCP
   dhcpClientSettings.interface = interface;
   //Disable rapid commit option
   dhcpClientSettings.rapidCommit = FALSE;

   //DHCP client initialization
   error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
   //Failed to initialize DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize DHCP client!\r\n");
   }

   //Start DHCP client
   error = dhcpClientStart(&dhcpClientContext);
   //Failed to start DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start DHCP client!\r\n");
   }
#else
   //Set IPv4 host address
   ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
   ipv4SetHostAddr(interface, ipv4Addr);

   //Set subnet mask
   ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
   ipv4SetSubnetMask(interface, ipv4Addr);

   //Set default gateway
   ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
   ipv4SetDefaultGateway(interface, ipv4Addr);

   //Set primary and secondary DNS servers
   ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 0, ipv4Addr);
   ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif

#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
   //Get default settings
   slaacGetDefaultSettings(&slaacSettings);
   //Set the network interface to be configured
   slaacSettings.interface = interface;

   //SLAAC initialization
   error = slaacInit(&slaacContext, &slaacSettings);
   //Failed to initialize SLAAC?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize SLAAC!\r\n");
   }

   //Start IPv6 address autoconfiguration process
   error = slaacStart(&slaacContext);
   //Failed to start SLAAC process?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start SLAAC!\r\n");
   }
#else
   //Set link-local address
   ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
   ipv6SetLinkLocalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

   //Set IPv6 prefix
   ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
   ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);

   //Set global address
   ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
   ipv6SetGlobalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

   //Set router
   ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
   ipv6SetRouter(interface, &ipv6Addr);

   //Set primary and secondary DNS servers
   ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 0, &ipv6Addr);
   ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif

   //Create user task
   task = osCreateTask("User Task", userTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Create a task to blink the LED
   task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Start the execution of tasks
   osStartKernel();

   //This function should never return
   return 0;
}
Ejemplo n.º 5
0
NTSTATUS
UcaGetVolumeGuidName(_In_ PCFLT_RELATED_OBJECTS FltObjects,
                     _Inout_ PUNICODE_STRING VolumeGuidName)
{
    PUCA_INSTANCE_CONTEXT InstanceContext = NULL;
    NTSTATUS Status;

    //PAGED_CODE();

    /* Get the instance context, or create one if none exists */
    Status = UcaGetOrAllocContext(FltObjects->Instance,
                                  NULL,
                                  FLT_INSTANCE_CONTEXT,
                                  TRUE,
                                  (PFLT_CONTEXT *)&InstanceContext);
    if (!NT_SUCCESS(Status)) return Status;

    /* Check if we've already cached the volume guid in a previous call */
    if (InstanceContext->VolumeGuidName.Buffer == NULL)
    {
        UNICODE_STRING TempString;
        ULONG RequiredBytes;

        /* Get the required buffer for the string, plug an extra one for a trailing backslash */
        RequiredBytes = UCA_VOLUME_GUID_NAME_SIZE * sizeof(WCHAR) +  sizeof(WCHAR);

        /* Set the string data */
        TempString.Length = 0;
        TempString.MaximumLength = (USHORT)RequiredBytes;

        /* Allocate some memory to hold the target */
        TempString.Buffer = (PWCH)ExAllocatePoolWithTag(PagedPool,
                                                        RequiredBytes,
                                                        UCA_POOL_TAG);
        if (TempString.Buffer == NULL)
        {
            FltReleaseContext(InstanceContext);
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        /* Now get the volume guid name */
        Status = FltGetVolumeGuidName(FltObjects->Volume,
                                      &TempString,
                                      NULL);
        if (!NT_SUCCESS(Status))
        {
            TRACE_ERROR(TraceHandle, "FltGetVolumeGuidName returned %X", Status);
            ExFreePoolWithTag(TempString.Buffer, UCA_POOL_TAG);
            FltReleaseContext(InstanceContext);
            return Status;
        }

        /* Add the trailing backslash */
        RtlAppendUnicodeToString(&TempString, L"\\");

        /* Set the SourceGuidName to the TempString.
         * It's okay to set Length and MaximumLength with no synchronization
         * because those will always be the same value */
        InstanceContext->VolumeGuidName.Length = TempString.Length;
        InstanceContext->VolumeGuidName.MaximumLength = TempString.MaximumLength;

        /*  Setting the buffer, however, requires some synchronization,
         *  because another thread might be attempting to do the same,
         *  and even though they're exactly the same string, they're
         *  different allocations (buffers) so if the other thread we're
         *  racing with manages to set the buffer before us, we need to
         *  free our temporary string buffer */
        InterlockedCompareExchangePointer(&InstanceContext->VolumeGuidName.Buffer,
                                          TempString.Buffer,
                                          NULL);

        if (InstanceContext->VolumeGuidName.Buffer != TempString.Buffer)
        {
            /* We didn't manage to set the buffer, so free the TempString buffer */
            ExFreePoolWithTag(TempString.Buffer, UCA_POOL_TAG);
        }
    }

    /* Copy the guid name to the caller */
    RtlCopyUnicodeString(VolumeGuidName, &InstanceContext->VolumeGuidName);

    /* We're done with the instance context */
    FltReleaseContext(InstanceContext);

    return Status;
}
Ejemplo n.º 6
0
Archivo: Hub.cpp Proyecto: DonCN/haiku
Hub::Hub(Object *parent, int8 hubAddress, uint8 hubPort,
	usb_device_descriptor &desc, int8 deviceAddress, usb_speed speed,
	bool isRootHub)
	:	Device(parent, hubAddress, hubPort, desc, deviceAddress, speed,
			isRootHub),
		fInterruptPipe(NULL)
{
	TRACE("creating hub\n");

	memset(&fHubDescriptor, 0, sizeof(fHubDescriptor));
	for (int32 i = 0; i < USB_MAX_PORT_COUNT; i++)
		fChildren[i] = NULL;

	if (!fInitOK) {
		TRACE_ERROR("device failed to initialize\n");
		return;
	}

	// Set to false again for the hub init.
	fInitOK = false;

	if (fDeviceDescriptor.device_class != 9) {
		TRACE_ERROR("wrong class! bailing out\n");
		return;
	}

	TRACE("getting hub descriptor...\n");
	size_t actualLength;
	status_t status = GetDescriptor(USB_DESCRIPTOR_HUB, 0, 0,
		(void *)&fHubDescriptor, sizeof(usb_hub_descriptor), &actualLength);

	// we need at least 8 bytes
	if (status < B_OK || actualLength < 8) {
		TRACE_ERROR("error getting hub descriptor\n");
		return;
	}

	TRACE("hub descriptor (%ld bytes):\n", actualLength);
	TRACE("\tlength:..............%d\n", fHubDescriptor.length);
	TRACE("\tdescriptor_type:.....0x%02x\n", fHubDescriptor.descriptor_type);
	TRACE("\tnum_ports:...........%d\n", fHubDescriptor.num_ports);
	TRACE("\tcharacteristics:.....0x%04x\n", fHubDescriptor.characteristics);
	TRACE("\tpower_on_to_power_g:.%d\n", fHubDescriptor.power_on_to_power_good);
	TRACE("\tdevice_removeable:...0x%02x\n", fHubDescriptor.device_removeable);
	TRACE("\tpower_control_mask:..0x%02x\n", fHubDescriptor.power_control_mask);

	if (fHubDescriptor.num_ports > USB_MAX_PORT_COUNT) {
		TRACE_ALWAYS("hub supports more ports than we do (%d vs. %d)\n",
			fHubDescriptor.num_ports, USB_MAX_PORT_COUNT);
		fHubDescriptor.num_ports = USB_MAX_PORT_COUNT;
	}

	usb_interface_list *list = Configuration()->interface;
	Object *object = GetStack()->GetObject(list->active->endpoint[0].handle);
	if (object && (object->Type() & USB_OBJECT_INTERRUPT_PIPE) != 0) {
		fInterruptPipe = (InterruptPipe *)object;
		fInterruptPipe->QueueInterrupt(fInterruptStatus,
			sizeof(fInterruptStatus), InterruptCallback, this);
	} else {
		TRACE_ALWAYS("no interrupt pipe found\n");
	}

	// Wait some time before powering up the ports
	if (!isRootHub)
		snooze(USB_DELAY_HUB_POWER_UP);

	// Enable port power on all ports
	for (int32 i = 0; i < fHubDescriptor.num_ports; i++) {
		status = DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT,
			USB_REQUEST_SET_FEATURE, PORT_POWER, i + 1, 0, NULL, 0, NULL);

		if (status < B_OK)
			TRACE_ERROR("power up failed on port %" B_PRId32 "\n", i);
	}

	// Wait for power to stabilize
	snooze(fHubDescriptor.power_on_to_power_good * 2000);

	fInitOK = true;
	TRACE("initialised ok\n");
}
Ejemplo n.º 7
0
NTSTATUS WINAPI Hook_NtCreateProcessEx (PHANDLE ProcessHandle,
					ACCESS_MASK DesiredAccess, 
					POBJECT_ATTRIBUTES ObjectAttributes,
					HANDLE ParentProcess,
					BOOLEAN InheritObjectTable,
					HANDLE SectionHandle, 
					HANDLE DebugPort,
					HANDLE ExceptionPort,
					HANDLE Unknown)
{
  PROC		pfnStub = Hooks_GetStubAddress (HOOKS_NTCREATEPROCESSEX) ;
  NTSTATUS	nStatus ;
  UINT		nReaction, nOptions ;
  WCHAR		wszFilePath[MAX_PATH] ;
  LARGE_INTEGER liFileTime ;
  WOTSECTION	*pWotSectionData ;
  ULONG		nWotDataSize ;
  PVOID		pObjectSection = NULL ;

  //DbgPrint ("/ Enter \\ irql = %d\n", KeGetCurrentIrql()) ;  

  TRACE ;

  nStatus = ObReferenceObjectByHandle (SectionHandle, GENERIC_ALL, NULL, KernelMode, &pObjectSection, NULL) ;    
  if( nStatus!=STATUS_SUCCESS || pObjectSection==NULL )
    {
      TRACE_ERROR (TEXT("ObReferenceObjectByHandle failed (status=0x%08X)\n"), nStatus) ;
      return nStatus ;
    }
  
  nStatus = WatchObjs_Lock () ;
  if( nStatus != STATUS_SUCCESS ) 
    {
      ObDereferenceObject (pObjectSection) ;
      return nStatus ;
    }

  nStatus = WatchObjs_GetFromPointer (pObjectSection, WOT_SECTION, 
				     (void**)&pWotSectionData, &nWotDataSize) ;  
  if( nStatus!=STATUS_SUCCESS )
    {
      TRACE_WARNING (TEXT("SectionObject is not in watched object list\n")) ;
      
      wcscpy (wszFilePath, g_usUnknownFile.Buffer) ; 
      liFileTime.QuadPart = 0 ;
    }
  else
    {
      wcscpy (wszFilePath, pWotSectionData->wszFilePath) ;
      liFileTime = pWotSectionData->liFileTime ;
    }

  WatchObjs_Unlock () ;
  ObDereferenceObject (pObjectSection) ;

  TRACE_INFO (TEXT("File = %ls\n"), wszFilePath) ;

  HookCommon_CatchCall (&nReaction, &nOptions,
			FILTREASON_SYS_EXECUTE, 
			TEXT("s"), wszFilePath) ;

  if( (nOptions&RULE_SCAN)!=0 && nReaction==RULE_ACCEPT && HookCommon_ShouldScanFile(wszFilePath) )
    {
      HookCommon_ScanFile (&nReaction, wszFilePath, &liFileTime) ;
    }

  if( nReaction == RULE_REJECT ) 
    {
      *ProcessHandle = INVALID_HANDLE_VALUE ;
      return STATUS_FILE_INVALID ;
    }

  if( nReaction == RULE_FEIGN ) 
    {
      *ProcessHandle = INVALID_HANDLE_VALUE ;
      return STATUS_SUCCESS ; 
    }

  //DbgPrint ("Calling CreateProcessEx... %ls\n", wszFilePath) ;
  
  nStatus = pfnStub (ProcessHandle, DesiredAccess, 
		     ObjectAttributes,ParentProcess,
		     InheritObjectTable,SectionHandle, 
		     DebugPort, ExceptionPort, Unknown) ;

  //DbgPrint ("Calling CreateProcessEx... result = 0x%08X\n", nStatus); 
  
  if( SUCCEEDED (nStatus) )
    HookSys_ProcessCreated (*ProcessHandle, wszFilePath) ;

  //DbgPrint ("\\ Leave /\n") ;

  return nStatus ;
}
Ejemplo n.º 8
0
//-----------------------------------------------------------------------------
/// Asynchronously reads data from a slave on the TWI bus. An optional
/// callback function is triggered when the transfer is complete.
/// Returns 0 if the transfer has been started; otherwise returns a TWI error
/// code.
/// \param pTwid  Pointer to a Twid instance.
/// \param address  TWI slave address.
/// \param iaddress  Optional slave internal address.
/// \param isize  Internal address size in bytes.
/// \param pData  Data buffer for storing received bytes.
/// \param num  Number of bytes to read.
/// \param pAsync  Asynchronous transfer descriptor.
//-----------------------------------------------------------------------------
unsigned char TWID_Read(
    Twid *pTwid,
    unsigned char address,
    unsigned int iaddress,
    unsigned char isize,
    unsigned char *pData,
    unsigned int num,
    Async *pAsync)
{
    AT91S_TWI *pTwi = pTwid->pTwi;
    AsyncTwi *pTransfer = (AsyncTwi *) pTwid->pTransfer;
    unsigned int timeout;

    //TRACE_DEBUG("TWID_Read()\n\r");
    SANITY_CHECK(pTwid);
    SANITY_CHECK((address & 0x80) == 0);
    SANITY_CHECK((iaddress & 0xFF000000) == 0);
    SANITY_CHECK(isize < 4);

    // Check that no transfer is already pending
    if (pTransfer) {

        TRACE_ERROR("TWID_Read: A transfer is already pending\n\r");
        return TWID_ERROR_BUSY;
    }

    // Set STOP signal if only one byte is sent
    if (num == 1) {

        TWI_Stop(pTwi);
    }

    // Asynchronous transfer
    if (pAsync) {

        // Update the transfer descriptor
        pTwid->pTransfer = pAsync;
        pTransfer = (AsyncTwi *) pAsync;
        pTransfer->status = ASYNC_STATUS_PENDING;
        pTransfer->pData = pData;
        pTransfer->num = num;
        pTransfer->transferred = 0;

        // Enable read interrupt and start the transfer
        TWI_EnableIt(pTwi, AT91C_TWI_RXRDY);
        TWI_StartRead(pTwi, address, iaddress, isize);
    }
    // Synchronous transfer
    else {

        // Start read
        TWI_StartRead(pTwi, address, iaddress, isize);

        // Read all bytes, setting STOP before the last byte
        while (num > 0) {

            // Last byte
            if (num == 1) {

                TWI_Stop(pTwi);
            }

            // Wait for byte then read and store it
            timeout = 0;
            while( !TWI_ByteReceived(pTwi) && (++timeout<TWITIMEOUTMAX) );
            if (timeout == TWITIMEOUTMAX) {
                TRACE_ERROR("TWID Timeout BR\n\r");
                return TWID_ERROR_TIMEOUT;
            }
            *pData++ = TWI_ReadByte(pTwi);
            num--;
        }

        // Wait for transfer to be complete
        timeout = 0;
        while( !TWI_TransferComplete(pTwi) && (++timeout<TWITIMEOUTMAX) );
        if (timeout == TWITIMEOUTMAX) {
            TRACE_ERROR("TWID Timeout TC\n\r");
            return TWID_ERROR_TIMEOUT;
        }
    }

    return 0;
}
Ejemplo n.º 9
0
//------------------------------------------------------------------------------
/// Asynchronously sends data to a slave on the TWI bus. An optional callback
/// function is invoked whenever the transfer is complete.
/// \param pTwid  Pointer to a Twid instance.
/// \param address  Slave address.
/// \param iaddress  Optional slave internal address.
/// \param isize  Number of internal address bytes.
/// \param pData  Data buffer to send.
/// \param num  Number of bytes to send.
/// \param pAsync  Pointer to an Asynchronous transfer descriptor.
//------------------------------------------------------------------------------
unsigned char TWID_Write(
    Twid *pTwid,
    unsigned char address,
    unsigned int iaddress,
    unsigned char isize,
    unsigned char *pData,
    unsigned int num,
    Async *pAsync)
{
    AT91S_TWI *pTwi = pTwid->pTwi;
    AsyncTwi *pTransfer = (AsyncTwi *) pTwid->pTransfer;
    unsigned int timeout;

    //TRACE_DEBUG("TWID_Write()\n\r");
    //TRACE_DEBUG("0x%X\n\r", pData[0]);
    SANITY_CHECK(pTwi);
    SANITY_CHECK((address & 0x80) == 0);
    SANITY_CHECK((iaddress & 0xFF000000) == 0);
    SANITY_CHECK(isize < 4);

    // Check that no transfer is already pending
    if (pTransfer) {

        TRACE_ERROR("TWI_Write: A transfer is already pending\n\r");
        return TWID_ERROR_BUSY;
    }

    // Asynchronous transfer
    if (pAsync) {

        // Update the transfer descriptor
        pTwid->pTransfer = pAsync;
        pTransfer = (AsyncTwi *) pAsync;
        pTransfer->status = ASYNC_STATUS_PENDING;
        pTransfer->pData = pData;
        pTransfer->num = num;
        pTransfer->transferred = 1;

        // Enable write interrupt and start the transfer
        TWI_StartWrite(pTwi, address, iaddress, isize, *pData);
        TWI_EnableIt(pTwi, AT91C_TWI_TXRDY);
    }
    // Synchronous transfer
    else {

        // Start write
        TWI_StartWrite(pTwi, address, iaddress, isize, *pData++);
        num--;

        // Send all bytes
        while (num > 0) {

            // Wait before sending the next byte
            timeout = 0;
            while( !TWI_ByteSent(pTwi) && (++timeout<TWITIMEOUTMAX) );
            if (timeout == TWITIMEOUTMAX) {
                TRACE_ERROR("TWID Timeout BS\n\r");
                return TWID_ERROR_TIMEOUT;
            }

            TWI_WriteByte(pTwi, *pData++);
            num--;
        }

        // Wait for actual end of transfer
        timeout = 0;

#ifdef TWI_V3XX
        // Send a STOP condition
        TWI_SendSTOPCondition(pTwi);
#endif

        while( !TWI_TransferComplete(pTwi) && (++timeout<TWITIMEOUTMAX) );
        if (timeout == TWITIMEOUTMAX) {
            TRACE_ERROR("TWID Timeout TC2\n\r");
            return TWID_ERROR_TIMEOUT;
        }

    }

    return 0;
}
static S_RESULT SMCPropYacc(uint8_t* pBuffer, uint32_t nBufferLength,
                     CONF_FILE* pConfFile)
{
   S_RESULT nError=S_SUCCESS;
   LIST *pPublicPropertyList=NULL;
   LIST *pPrivatePropertyList=NULL;
   PROPERTY* pProperty=NULL;
   SERVICE_SECTION* pServSection;
   SERVICE_SECTION* pPreviousService=NULL;

   uint8_t* pName;
   uint32_t nNameLength;
   uint8_t* pValue;
   uint32_t nValueLength;
   char* pNameZ = NULL;
   char* pValueZ = NULL;
   LIB_MANIFEST2_CONTEXT sParserContext;
   char serviceManifestName[1024];

   sParserContext.pManifestName = "Configuration File";
   sParserContext.pManifestContent = pBuffer;
   sParserContext.nManifestLength = nBufferLength;
   sParserContext.nType = LIB_MANIFEST2_TYPE_SOURCE_WITH_SECTIONS;

   libManifest2InitContext(&sParserContext);

   while (true)
   {
      nError = libManifest2GetNextItem(
         &sParserContext,
         &pName,
         &nNameLength,
         &pValue,
         &nValueLength);
      if (nError == S_ERROR_ITEM_NOT_FOUND)
      {
         /* End of parsing */
         nError = S_SUCCESS;
         break;
      }
      else if (nError != S_SUCCESS)
      {
         /* Error */
         goto error;
      }

      /* Duplicate name and value in as zero-terminated strings */
      /* Unclean: those strings are not going to be deallocated
         This is not a problem because this code is run in a tool
      */
      pNameZ = malloc(nNameLength+1);
      if (pNameZ == NULL)
      {
         nError = S_ERROR_OUT_OF_MEMORY;
         goto error;
      }
      memcpy(pNameZ, pName, nNameLength);
      pNameZ[nNameLength] = 0;

      if (pValue == NULL)
      {
         /* It's a section */
         if (STRICMP(pNameZ, SYSTEM_SECTION_NAME) == 0)
         {
            free(pNameZ);
            pPublicPropertyList=&pConfFile->sSystemSectionPropertyList;
         }
         else
         {
            pServSection=(SERVICE_SECTION*)SMCPropListFindElement(
               &pConfFile->sDriverSectionList,
               pNameZ,
               false);
            if (pServSection==NULL)
            {
               pServSection=(SERVICE_SECTION*)SMCPropListFindElement(
                     &pConfFile->sPreinstalledSectionList,
                     pNameZ,
                     false);
            }
            if (pServSection==NULL)
            {
               pServSection=(SERVICE_SECTION*)SMCPropListFindElement(
                  &pConfFile->sSectionList,
                  pNameZ,
                  false);
               if (pServSection==NULL)
               {
                  nError=S_ERROR_ITEM_NOT_FOUND;
                  goto error;
               }
            }
            free(pNameZ);

            pServSection->inSCF=true;
            if (pPreviousService!=NULL)
            {
               pPreviousService->pNextInSCF=pServSection;
            }
            else
            {
               pConfFile->pFirstSectionInSCF=pServSection;
            }
            pPreviousService=pServSection;

            pPublicPropertyList=&pServSection->sPublicPropertyList;
            pPrivatePropertyList=&pServSection->sPrivatePropertyList;
         }
      }
      else
      {
         /* It's a property definition */
         pValueZ = malloc(nValueLength+1);
         if (pValueZ == NULL)
         {
            nError = S_ERROR_OUT_OF_MEMORY;
            goto error;
         }
         memcpy(pValueZ, pValue, nValueLength);
         pValueZ[nValueLength] = 0;

         pProperty=(PROPERTY*)malloc(sizeof(PROPERTY));
         if (pProperty==NULL)
         {
            nError=S_ERROR_OUT_OF_MEMORY;
            goto error;
         }
         memset(pProperty, 0x00, sizeof(PROPERTY));
         pProperty->sNode.pName=pNameZ;

         pProperty->pValue=pValueZ;

         if (pPrivatePropertyList==NULL)
         {
            nError=SMCPropListSortedAdd(pPublicPropertyList,(NODE*)pProperty);
            if (nError!=S_SUCCESS)
            {
               goto error;
            }
         }
         else
         {
            if ((nValueLength > strlen(CONFIG_PROPERTY_NAME)) &&
                (memcmp(pProperty->sNode.pName, CONFIG_PROPERTY_NAME, strlen(CONFIG_PROPERTY_NAME)) == 0))
            {
               nError=SMCPropListSortedAdd(pPrivatePropertyList,(NODE*)pProperty);
            }
            else
            {
               nError=SMCPropListSortedAdd(pPublicPropertyList,(NODE*)pProperty);
            }
            if (nError!=S_SUCCESS)
            {
               goto error;
            }
         }
      }
   }

error:
   if (nError!=S_SUCCESS)
   {
      switch (nError)
      {
      case S_ERROR_BAD_FORMAT:
         /* Error message already output */
         break;
      case S_ERROR_WRONG_SIGNATURE:
         TRACE_ERROR("Configuration file: wrong service UUID: %s\n", pValueZ);
         break;
      case S_ERROR_OUT_OF_MEMORY:
	  TRACE_ERROR("Out of memory\n");
         break;
      case S_ERROR_ITEM_NOT_FOUND:
	  TRACE_ERROR("Configuration file: service \"%s\" not found\n", pNameZ);
         break;
      }
   }
   return nError;
}
Ejemplo n.º 11
0
//------------------------------------------------------------------------------
// Generic CAN Interrupt handler
/// \param can_number can nulber
//------------------------------------------------------------------------------
static void CAN_Handler( unsigned char can_number )
{
    AT91PS_CAN base_can;
    AT91PS_CAN_MB CAN_Mailbox;

    unsigned int status;
    unsigned int can_msr;
    unsigned int* pCan_mcr;
    unsigned int message_mode;
    unsigned char numMailbox;
    unsigned char state0=CAN_DISABLED;
    unsigned char state1=CAN_DISABLED;

    if( can_number == 0 ) {
        base_can = AT91C_BASE_CAN0;
        CAN_Mailbox = AT91C_BASE_CAN0_MB0;
        state0 = pCAN0Transfer->state;
    }
#ifdef AT91C_BASE_CAN1
    else {
        base_can = AT91C_BASE_CAN1;
        CAN_Mailbox = AT91C_BASE_CAN1_MB0;
        state1 = pCAN1Transfer->state;
    }
#endif
    status = (base_can->CAN_SR) & (base_can->CAN_IMR);
    base_can->CAN_IDR = status;

    TRACE_DEBUG("CAN0 status=0x%X\n\r", status);
    if(status & AT91C_CAN_WAKEUP) {
        if( can_number == 0 ) {
            pCAN0Transfer->test_can = AT91C_TEST_OK;
            pCAN0Transfer->state = CAN_IDLE;
        }
#ifdef AT91C_BASE_CAN1
        else {
            pCAN1Transfer->test_can = AT91C_TEST_OK;
            pCAN1Transfer->state = CAN_IDLE;
        }
#endif
    }
    // Mailbox event ?
    else if ((status&0x0000FFFF) != 0) {
        TRACE_DEBUG("Mailbox event\n\r");

        // Handle Mailbox interrupts
        for (numMailbox = 0; numMailbox < NUM_MAILBOX_MAX; numMailbox++) {

            can_msr = *(unsigned int*)((unsigned int)CAN_Mailbox+(unsigned int)(0x10+(0x20*numMailbox)));
            if ((AT91C_CAN_MRDY & can_msr) == AT91C_CAN_MRDY) {
                // Mailbox object type
                message_mode =  ((*(unsigned int*)((unsigned int)CAN_Mailbox+(unsigned int)(0x00+(0x20*numMailbox))))>>24)&0x7;
                TRACE_DEBUG("message_mode 0x%X\n\r", message_mode);
                TRACE_DEBUG("numMailbox 0x%X\n\r", numMailbox);

                if( message_mode == 0 ) {
                    TRACE_ERROR("Error in MOT\n\r");
                }
                else if( ( message_mode == CAN_MOT_RECEPT )
                         || ( message_mode == CAN_MOT_RECEPT_OW )
                         || ( message_mode == CAN_MOT_PRODUCER ) ) {
                    TRACE_DEBUG("Mailbox is in RECEPTION\n\r");
                    TRACE_DEBUG("Length 0x%X\n\r", (can_msr>>16)&0xF);
                    TRACE_DEBUG("CAN_MB_MID 0x%X\n\r", ((*(unsigned int*)((unsigned int)CAN_Mailbox+(unsigned int)(0x08+(0x20*numMailbox)))&AT91C_CAN_MIDvA)>>18));

                    TRACE_DEBUG("can_number %d\n\r", can_number);
                    if( can_number == 0 ) {
                        //CAN_MB_MDLx
                        pCAN0Transfer->data_low_reg =
                            (*(unsigned int*)((unsigned int)CAN_Mailbox+(unsigned int)(0x14+(0x20*numMailbox))));
                        //CAN_MB_MDHx
                        pCAN0Transfer->data_high_reg =
                            (*(unsigned int*)((unsigned int)CAN_Mailbox+(unsigned int)(0x18+(0x20*numMailbox))));
                        pCAN0Transfer->size = (can_msr>>16)&0xF;
                        pCAN0Transfer->mailbox_number = numMailbox;
                        state0 = CAN_IDLE;
                    }
#ifdef AT91C_BASE_CAN1
                    else {
Ejemplo n.º 12
0
/**
 * XXX - TODO: This is an ugly function.. I will improve it on 2nd iteration
 */
socket_map_t 
AllocateSocket(mctx_t mctx, int socktype)
{
	mtcp_manager_t mtcp = g_mtcp[mctx->cpu];
	socket_map_t socket = NULL;

	switch (socktype) {
	case MOS_SOCK_MONITOR_STREAM:
		mtcp->num_msp++;
	case MOS_SOCK_MONITOR_STREAM_ACTIVE:
	case MOS_SOCK_MONITOR_RAW:
		socket = TAILQ_FIRST(&mtcp->free_msmap);
		if (!socket)
			goto alloc_error;
		TAILQ_REMOVE(&mtcp->free_msmap, socket, link);
		/* if there is not invalidated events, insert the socket to the end */
		/* and find another socket in the free smap list */
		if (socket->events) {
			TRACE_INFO("There are still not invalidate events remaining.\n");
			TRACE_DBG("There are still not invalidate events remaining.\n");
			TAILQ_INSERT_TAIL(&mtcp->free_msmap, socket, link);
			socket = NULL;
			goto alloc_error;
		}
		break;

	default:
		mtcp->num_esp++;
		socket = TAILQ_FIRST(&mtcp->free_smap);
		if (!socket)
			goto alloc_error;
		TAILQ_REMOVE(&mtcp->free_smap, socket, link);
		/* if there is not invalidated events, insert the socket to the end */
		/* and find another socket in the free smap list */
		if (socket->events) {
			TRACE_INFO("There are still not invalidate events remaining.\n");
			TRACE_DBG("There are still not invalidate events remaining.\n");
			TAILQ_INSERT_TAIL(&mtcp->free_smap, socket, link);
			socket = NULL;
			goto alloc_error;
		}
		socket->stream = NULL;
		/* 
		 * reset a few fields (needed for client socket) 
		 * addr = INADDR_ANY, port = INPORT_ANY
		 */
		memset(&socket->saddr, 0, sizeof(struct sockaddr_in));
		memset(&socket->ep_data, 0, sizeof(mtcp_epoll_data_t));
	}

	socket->socktype = socktype;
	socket->opts = 0;
	socket->epoll = 0;
	socket->events = 0;
	
	return socket;

 alloc_error:
	TRACE_ERROR("The concurrent sockets are at maximum.\n");
	return NULL;
}
Ejemplo n.º 13
0
int32_t main(int32_t argc, char **argv)
{
  int32_t ret_val = HM_OK;
  SOCKADDR_IN addr;

  int32_t cmd_opt;
  /* Randomly select a group for subscription */
  int32_t subs_group = random_num(0, 4);
  int32_t node[2] = {random_num(1,4), random_num(1,4)};

  int32_t pct_type = 0x75010001;
  int32_t pid = 0x00000034;

  extern char *optarg;

  while((cmd_opt = getopt(argc, argv, "l:")) != -1)
  {
    switch(cmd_opt)
    {
    case 'l':
      TRACE_INFO(("Location Index: %s", optarg));
      location_index = atoi(optarg);
      break;
    default:
      printf("\nUsage: %s -l <location_number>", argv[0]);
      break;
    }
  }

  if(location_index == 0)
  {
    TRACE_ERROR(("Did not find Location Index"));
    goto EXIT_LABEL;
  }

  pid = pid | (location_index << 24);
  TRACE_INFO(("PID Assigned: 0x%x", pid));

  /***************************************************************************/
  /* Setup address                               */
  /***************************************************************************/
  memset(&addr, 0, sizeof(SOCKADDR));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(4999);
  inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr);

  /***************************************************************************/
  /* Open Socket                                 */
  /***************************************************************************/
  sock_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if(sock_fd < 0)
  {
    TRACE_PERROR(("Error opening socket"));
    goto EXIT_LABEL;
  }

  /***************************************************************************/
  /* Send connect request                             */
  /***************************************************************************/
  ret_val = connect(sock_fd, (SOCKADDR *)&addr, (socklen_t)sizeof(SOCKADDR));
  if(ret_val < 0)
  {
    TRACE_PERROR(("Error connecting to HM."));
    goto EXIT_LABEL;
  }

  /***************************************************************************/
  /* Connected! Go ahead, send an init                     */
  /***************************************************************************/
  init_msg.hdr.msg_id = 1;
  init_msg.hdr.msg_len = sizeof(init_msg);
  init_msg.hdr.msg_type = HM_MSG_TYPE_INIT;
  init_msg.hdr.request = TRUE;
  init_msg.hdr.response_ok = FALSE;

  init_msg.hardware_num = 0;
  init_msg.index = location_index;
  init_msg.keepalive_period = 1000; /* ms */
  init_msg.location_status = TRUE;
  init_msg.service_group_index = location_index;

  TRACE_INFO(("Sending INIT message!"));
  ret_val = send(sock_fd, (char *)&init_msg, sizeof(init_msg), 0);
  if(ret_val != sizeof(init_msg))
  {
    TRACE_PERROR(("Error sending complete message on socket!"));
    goto EXIT_LABEL;
  }
  TRACE_INFO(("INIT Message sent."));

  ret_val = recv(sock_fd, (char *)&init_msg, sizeof(init_msg), 0);
  if(ret_val != sizeof(init_msg))
  {
    TRACE_WARN(("Partial Message Received!"));
    goto EXIT_LABEL;
  }
  TRACE_INFO(("Message response received"));
  if(init_msg.hdr.response_ok == TRUE)
  {
    TRACE_INFO(("Hardware Index is %d", init_msg.hardware_num));
  }

  //TRACE_INFO(("Send Keepalive"));
  //TODO: LATER

  //Send Process UP Notification
  proc_msg.hdr.msg_id = 1;
  proc_msg.hdr.msg_len = sizeof(proc_msg);
  proc_msg.hdr.msg_type = HM_MSG_TYPE_PROCESS_CREATE;
  proc_msg.hdr.request = TRUE;
  proc_msg.hdr.response_ok = FALSE;

  proc_msg.if_offset = 0;
  snprintf(proc_msg.name, sizeof(proc_msg.name), "TEST");
  proc_msg.pid = pid;
  proc_msg.proc_type = pct_type;

  TRACE_INFO(("Sending PROCESS_CREATED message!"));
  ret_val = send(sock_fd, (char *)&proc_msg, sizeof(proc_msg), 0);
  if(ret_val != sizeof(proc_msg))
  {
    TRACE_PERROR(("Error sending complete message on socket!"));
  }
  TRACE_INFO(("PROCESS_CREATED Message sent."));

  ret_val = recv(sock_fd, (char *)&proc_msg, sizeof(proc_msg), 0);
  if(ret_val != sizeof(proc_msg))
  {
    TRACE_WARN(("Partial Message Received!"));
  }
  TRACE_INFO(("Message response received"));

  if(proc_msg.hdr.response_ok == TRUE)
  {
    TRACE_INFO(("Process Create Notification OK"));
  }

  //Send REGISTER for Group
//  TRACE_INFO(("Sending Register for Group %d", subs_group));
  reg_msg = (HM_REGISTER_MSG *)malloc(sizeof(HM_REGISTER_MSG) + 1* sizeof(HM_REGISTER_TLV_CB));
  reg_msg->hdr.msg_id = 1;
  reg_msg->hdr.msg_len = sizeof(HM_REGISTER_MSG) + 2* sizeof(HM_REGISTER_TLV_CB);
  reg_msg->hdr.msg_type = HM_MSG_TYPE_REGISTER;
  reg_msg->hdr.request = TRUE;
  reg_msg->hdr.response_ok = FALSE;

  reg_msg->num_register = 2;
  reg_msg->subscriber_pid = pid;
  reg_msg->type = HM_REG_SUBS_TYPE_PROC;

  tlv = (HM_REGISTER_TLV_CB *)((char *)reg_msg + sizeof(HM_REGISTER_MSG));
  tlv->id = pct_type;

  TRACE_INFO(("Sending PROCESS_REGISTER message!"));
  ret_val = send(sock_fd, (char *)reg_msg, reg_msg->hdr.msg_len, 0);
  if(ret_val != reg_msg->hdr.msg_len)
  {
    TRACE_PERROR(("Error sending complete message on socket!"));
  }


  TRACE_INFO(("Sent Register"));

  //Receive REGISTER Response
  memset((void *)reg_msg, 0, sizeof(reg_msg->hdr.msg_len));

  ret_val = recv(sock_fd, (char *)reg_msg,
          (sizeof(HM_REGISTER_MSG) + 1* sizeof(HM_REGISTER_TLV_CB)), 0);
  if(ret_val != (sizeof(HM_REGISTER_MSG) + 1* sizeof(HM_REGISTER_TLV_CB)))
  {
    TRACE_WARN(("Partial Message Received!"));
  }
  TRACE_INFO(("Register response received"));

  if(reg_msg->hdr.response_ok == TRUE)
  {
    TRACE_INFO(("Register OK"));
  }

  //Send Unregister

  //Receive Unregister Response

  //Send REGISTER for Nodes
//  TRACE_INFO(("Sending Register for Nodes %d, %d", node[0], node[1]));

  //Receive REGISTER Response

  //Send Unregister

  //Receive Unregister Response



  while(1)
  {
    continue;
  }

EXIT_LABEL:
  if (sock_fd != -1)
  {
    close(sock_fd);
    sock_fd = -1;
  }
  return ret_val;
}
Ejemplo n.º 14
0
//-----------------------------------------------------------------------------
/// Send a packet with EMAC.
/// If the packet size is larger than transfer buffer size error returned.
/// \param buffer   The buffer to be send
/// \param size     The size of buffer to be send
/// \param fEMAC_TxCallback Threshold Wakeup callback
/// \param fWakeUpCb   TX Wakeup
/// \return         OK, Busy or invalid packet
//-----------------------------------------------------------------------------
unsigned char EMAC_Send(void *pBuffer,
                        unsigned int size,
                        EMAC_TxCallback fEMAC_TxCallback)
{
    volatile EmacTxTDescriptor *pTxTd;
    volatile EMAC_TxCallback   *pTxCb;

    //TRACE_DEBUG("EMAC_Send\n\r");

    // Check parameter
    if (size > EMAC_TX_UNITSIZE) {

        TRACE_ERROR("EMAC driver does not split send packets.");
        TRACE_ERROR(" It can send %d bytes max in one packet (%d bytes requested)\n\r",
                    EMAC_TX_UNITSIZE, size);
        return EMAC_TX_INVALID_PACKET;
    }

    // If no free TxTd, buffer can't be sent, schedule the wakeup callback
    if( CIRC_SPACE(txTd.head, txTd.tail, TX_BUFFERS) == 0) {
        return EMAC_TX_BUFFER_BUSY;

    }

    // Pointers to the current TxTd
    pTxTd = txTd.td + txTd.head;
    pTxCb = txTd.txCb + txTd.head;

    // Sanity check
    ASSERT((pTxTd->status & EMAC_TX_USED_BIT) != 0,
           "-F- Buffer is still under EMAC control\n\r");

    // Setup/Copy data to transmition buffer
    if (pBuffer && size) {
        // Driver manage the ring buffer
        memcpy((void *)pTxTd->addr, pBuffer, size);
    }

    // Tx Callback
    *pTxCb = fEMAC_TxCallback;

    // Update TD status
    // The buffer size defined is length of ethernet frame
    // so it's always the last buffer of the frame.
    if (txTd.head == TX_BUFFERS-1) {
        pTxTd->status =
            (size & EMAC_LENGTH_FRAME) | EMAC_TX_LAST_BUFFER_BIT | EMAC_TX_WRAP_BIT;
    } else {
        pTxTd->status = (size & EMAC_LENGTH_FRAME) | EMAC_TX_LAST_BUFFER_BIT;
    }

    CIRC_INC(txTd.head, TX_BUFFERS)

    // Tx packets count
    EmacStatistics.tx_packets++;

    // Now start to transmit if it is not already done
    AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_TSTART;

    return EMAC_TX_OK;
}
Ejemplo n.º 15
0
CK_RV
dp_x9dh_set_default_attributes( TEMPLATE *tmpl, CK_ULONG mode )
{
   CK_RV		rc;
   CK_ATTRIBUTE         *prime_attr;
   CK_ATTRIBUTE         *subprime_attr;
   CK_ATTRIBUTE         *base_attr;
   CK_ATTRIBUTE         *primebits_attr;
   CK_ATTRIBUTE		*subprimebits_attr;
   CK_ATTRIBUTE         *type_attr;

   rc = dp_object_set_default_attributes( tmpl, mode );
   if (rc != CKR_OK)
      return rc;

   prime_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) );
   subprime_attr  = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) );
   base_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) );
   primebits_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) );
   subprimebits_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) );
   type_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) + sizeof(CK_KEY_TYPE) );

   if (!prime_attr     || !subprime_attr     || !base_attr || 
       !primebits_attr || !subprimebits_attr || !type_attr) {
      if (prime_attr) free( prime_attr );
      if (subprime_attr) free( subprime_attr );
      if (base_attr) free( base_attr );
      if (primebits_attr) free( primebits_attr );
      if (subprimebits_attr) free( subprimebits_attr );
      if (type_attr) free( type_attr );
      TRACE_ERROR("%s\n", ock_err(ERR_HOST_MEMORY));
      return CKR_HOST_MEMORY;
   }

   prime_attr->type       = CKA_PRIME;
   prime_attr->ulValueLen = 0;
   prime_attr->pValue     = NULL;

   subprime_attr->type       = CKA_SUBPRIME;
   subprime_attr->ulValueLen = 0;
   subprime_attr->pValue     = NULL;

   base_attr->type       = CKA_BASE;
   base_attr->ulValueLen = 0;
   base_attr->pValue     = NULL;

   primebits_attr->type       = CKA_PRIME_BITS;
   primebits_attr->ulValueLen = 0;
   primebits_attr->pValue     = NULL;
   
   subprimebits_attr->type       = CKA_SUBPRIME_BITS;
   subprimebits_attr->ulValueLen = 0;
   subprimebits_attr->pValue     = NULL;
   
   type_attr->type       = CKA_KEY_TYPE;
   type_attr->ulValueLen = sizeof(CK_KEY_TYPE);
   type_attr->pValue     = (CK_BYTE *)type_attr + sizeof(CK_ATTRIBUTE);
   *(CK_KEY_TYPE *)type_attr->pValue = CKK_DSA;

   template_update_attribute( tmpl, prime_attr );
   template_update_attribute( tmpl, subprime_attr );
   template_update_attribute( tmpl, base_attr );
   template_update_attribute( tmpl, primebits_attr );
   template_update_attribute( tmpl, type_attr );

   return CKR_OK;

}
Ejemplo n.º 16
0
status_t
ATAPIDevice::SendPacket(ATARequest *request)
{
	TRACE_FUNCTION("%p\n", request);

	// only READ/WRITE commands can use DMA
	// (the device may support it always, but IDE controllers don't
	// report how much data is transmitted, and this information is
	// crucial for the SCSI protocol)
	// special offer: let READ_CD commands use DMA too
	uint8 command = fPacket[0];
	request->SetUseDMA(UseDMA()
		&& (command == SCSI_OP_READ_6 || command == SCSI_OP_WRITE_6
		|| command == SCSI_OP_READ_10 || command == SCSI_OP_WRITE_10
		|| command == SCSI_OP_READ_12 || command == SCSI_OP_WRITE_12
		|| command == SCSI_OP_READ_CD)
		&& fChannel->PrepareDMA(request) == B_OK);
	TRACE("using dma: %s\n", request->UseDMA() ? "yes" : "no");

	if (!request->UseDMA())
		request->PrepareSGInfo();

	if (_FillTaskFilePacket(request) != B_OK) {
		TRACE_ERROR("failed to setup transfer request\n");
		if (request->UseDMA())
			fChannel->FinishDMA();
		return B_ERROR;
	}

	status_t result = fChannel->SendRequest(request, 0);
	if (result != B_OK) {
		TRACE_ERROR("failed to send packet request\n");
		if (request->UseDMA())
			fChannel->FinishDMA();
		return result;
	}

	// wait for device to get ready for packet transmission
	if (fChannel->Wait(ATA_STATUS_DATA_REQUEST, ATA_STATUS_BUSY,
		ATA_CHECK_ERROR_BIT | ATA_CHECK_DEVICE_FAULT, 100 * 1000) != B_OK) {
		TRACE_ERROR("timeout waiting for data request\n");
		if (request->UseDMA())
			fChannel->FinishDMA();

		request->SetStatus(SCSI_SEQUENCE_FAIL);
		return B_TIMED_OUT;
	}

	// make sure device really asks for command packet
	fRegisterMask = ATA_MASK_INTERRUPT_REASON;
	fChannel->ReadRegs(this);

	if (!fTaskFile.packet_res.cmd_or_data
		|| fTaskFile.packet_res.input_or_output) {
		TRACE_ERROR("device doesn't ask for packet\n");
		if (request->UseDMA())
			fChannel->FinishDMA();

		request->SetStatus(SCSI_SEQUENCE_FAIL);
		return B_ERROR;
	}

	// some old drives need a delay before submitting the packet
	spin(10);

	// write packet
	if (fChannel->WritePIO(fPacket, sizeof(fPacket)) != B_OK) {
		TRACE_ERROR("failed to write packet\n");
		if (request->UseDMA())
			fChannel->FinishDMA();

		request->SetStatus(SCSI_HBA_ERR);
		return B_ERROR;
	}

	if (!request->HasData())
		return _FinishRequest(request, ATA_WAIT_FINISH);

	if (request->UseDMA()) {
		fChannel->PrepareWaitingForInterrupt();
		fChannel->StartDMA();

		result = fChannel->WaitForInterrupt(request->Timeout());
		status_t dmaResult = fChannel->FinishDMA();
		if (result != B_OK) {
			request->SetStatus(SCSI_CMD_TIMEOUT);
			return B_TIMED_OUT;
		}

		result = _FinishRequest(request, ATA_WAIT_FINISH);
		if (result != B_OK) {
			TRACE_ERROR("device indicates transfer error after dma\n");
			return result;
		}

		// for ATAPI it's ok for the device to send too much
		if (dmaResult == B_OK || dmaResult == B_DEV_DATA_OVERRUN) {
			fDMAFailures = 0;
			request->CCB()->data_resid = 0;
			return B_OK;
		}

		TRACE_ERROR("dma transfer failed\n");
		request->SetSense(SCSIS_KEY_HARDWARE_ERROR,
			SCSIS_ASC_LUN_COM_FAILURE);
		fDMAFailures++;
		if (fDMAFailures >= ATA_MAX_DMA_FAILURES) {
			TRACE_ALWAYS("disabling DMA after %u failures\n", fDMAFailures);
			fUseDMA = false;
		}

		return B_ERROR;
	}

	result = fChannel->Wait(ATA_STATUS_DATA_REQUEST, ATA_STATUS_BUSY,
		ATA_CHECK_ERROR_BIT | ATA_CHECK_DEVICE_FAULT, request->Timeout());
	if (result != B_OK) {
		if (result == B_TIMED_OUT) {
			TRACE_ERROR("timeout waiting for device to request data\n");
			request->SetStatus(SCSI_CMD_TIMEOUT);
			return B_TIMED_OUT;
		} else
			return _FinishRequest(request, 0);
	}

	// PIO data transfer
	while (true) {
		fRegisterMask = ATA_MASK_INTERRUPT_REASON | ATA_MASK_BYTE_COUNT;
		fChannel->ReadRegs(this);

		if (fTaskFile.packet_res.cmd_or_data) {
			TRACE_ERROR("device expecting command instead of data\n");
			request->SetStatus(SCSI_SEQUENCE_FAIL);
			return B_ERROR;
		}

		size_t length = fTaskFile.packet_res.byte_count_0_7
			| ((size_t)fTaskFile.packet_res.byte_count_8_15 << 8);
		TRACE("about to transfer %lu bytes\n", length);

		request->SetBytesLeft(length);
		fChannel->ExecutePIOTransfer(request);

		result = fChannel->Wait(0, ATA_STATUS_BUSY, 0, request->Timeout());
		if (result != B_OK) {
			if (result == B_TIMED_OUT) {
				TRACE_ERROR("timeout waiting for device to finish transfer\n");
				request->SetStatus(SCSI_CMD_TIMEOUT);
				return B_TIMED_OUT;
			} else
				return _FinishRequest(request, 0);
		}

		if ((fChannel->AltStatus() & ATA_STATUS_DATA_REQUEST) == 0) {
			// transfer complete
			TRACE("pio transfer complete\n");
			break;
		}
	}

	return _FinishRequest(request, ATA_WAIT_FINISH);
}
Ejemplo n.º 17
0
/** Decoder.
 The supplied buffer should contain an H264 video frame, then DecodeFrame
  will pass the buffer to the avcode_decode_video2 method. Once decoded we then
  use the get_picture command to convert the frame to RGB24.  The RGB24 buffer is
  then used to create a FrameInfo object which is placed on our video queue.

  \param pBuffer Memory buffer holding an H264 frame
  \param size Size of the buffer
*/
FrameInfo* CVideoDecoder::DecodeFrame(unsigned char *pBuffer, int size) 
{
		FrameInfo	*p_block=NULL;
        uint8_t startCode4[] = {0x00, 0x00, 0x00, 0x01};
        int got_frame = 0;
        AVPacket packet;

		//Initialize optional fields of a packet with default values. 
		av_init_packet(&packet);

		//set the buffer and the size	
        packet.data = pBuffer;
        packet.size = size;

        while (packet.size > sizeof(startCode4)) 
		{
			//Decode the video frame of size avpkt->size from avpkt->data into picture. 
			int len = avcodec_decode_video2(m_codecContext, m_frame, &got_frame, &packet);
			if(len<0)
			{
				TRACE_ERROR("Failed to decode video len=%d",len);
				break;
			}

			//sometime we dont get the whole frame, so move
			//forward and try again
            if ( !got_frame )
			{
				packet.size -= len;
				packet.data += len;
				continue;
			}

			//allocate a working frame to store our rgb image
            AVFrame * rgb = avcodec_alloc_frame();
			if(rgb==NULL)
			{
				TRACE_ERROR("Failed to allocate new av frame");
				return NULL;
			}

			//Allocate and return an SwsContext. 
			struct SwsContext * scale_ctx = sws_getContext(m_codecContext->width,	
				m_codecContext->height,
				m_codecContext->pix_fmt,
				m_codecContext->width,
				m_codecContext->height,
				PIX_FMT_BGR24,
				SWS_BICUBIC,
				NULL,
				NULL,
				NULL);
            if (scale_ctx == NULL)
			{
				TRACE_ERROR("Failed to get context");
				continue;
			}

			//Calculate the size in bytes that a picture of the given width and height would occupy if stored in the given picture format. 
			int numBytes = avpicture_get_size(PIX_FMT_RGB24,
				m_codecContext->width,
				m_codecContext->height);
						
			try{
				//create one of our FrameInfo objects
				p_block = FrameNew(numBytes);
				if(p_block==NULL){	

					//cleanup the working buffer
					av_free(rgb);
					sws_freeContext(scale_ctx);
					scale_ctx=NULL;
					return NULL;
				}

				//Fill our frame buffer with the rgb image
				avpicture_fill((AVPicture*)rgb, 
					(uint8_t*)p_block->pdata,
					PIX_FMT_RGB24,
					m_codecContext->width,
					m_codecContext->height);
					
				//Scale the image slice in srcSlice and put the resulting scaled slice in the image in dst. 
				sws_scale(scale_ctx, 
					m_frame->data, 
					m_frame->linesize, 
					0, 
					m_codecContext->height, 
					rgb->data, 
					rgb->linesize);
									
				//set the frame header to indicate rgb24
				p_block->frameHead.FrameType = (long)(PIX_FMT_RGB24);
				p_block->frameHead.TimeStamp = 0;
			}
			catch(...)
			{
				TRACE_ERROR("EXCEPTION: in afterGettingFrame1 ");
			}

			//cleanup the working buffer
             av_free(rgb);
			sws_freeContext(scale_ctx);

			//we got our frame no its time to move on
			break;
        }
		return p_block;
}
Ejemplo n.º 18
0
/**
 * \brief  Loads the logical mapping contained in the given physical block.
 * block contains the mapping, its index is stored in the provided variable (if
 * pointer is not 0).
 *
 * \param mapped  Pointer to a MappedNandFlash instance.
 * \param physicalBlock  Physical block number.
 * \return  0 if successful; otherwise, returns a NandCommon_ERROR code.
 */
static unsigned char LoadLogicalMapping(
    struct MappedNandFlash *mapped,
    unsigned short physicalBlock)
{
    unsigned char error;
    unsigned char data[NandCommon_MAXPAGEDATASIZE];
    unsigned short pageDataSize =
                    NandFlashModel_GetPageDataSize(MODEL(mapped));
    unsigned short numBlocks =
                    ManagedNandFlash_GetDeviceSizeInBlocks(MANAGED(mapped));
    unsigned int remainingSize;
    unsigned char *currentBuffer;
    unsigned short currentPage;
    unsigned int readSize;
    unsigned int i;
    unsigned char status;
    signed short logicalBlock;
    /*signed short firstBlock, lastBlock;*/

    TRACE_INFO("LoadLogicalMapping(B#%d)\n\r", physicalBlock);

    /* Load mapping from pages #1 - #XXX of block*/
    currentBuffer = (unsigned char *) mapped->logicalMapping;
    remainingSize = sizeof(mapped->logicalMapping);
    currentPage = 1;
    while (remainingSize > 0) {

        /* Read page*/
        readSize = min(remainingSize, pageDataSize);
        error = ManagedNandFlash_ReadPage(MANAGED(mapped),
                                          physicalBlock,
                                          currentPage,
                                          data,
                                          0);
        if (error) {

            TRACE_ERROR(
                      "LoadLogicalMapping: Failed to load mapping\n\r");
            return error;
        }

        /* Copy page info*/
        memcpy(currentBuffer, data, readSize);

        currentBuffer += readSize;
        remainingSize -= readSize;
        currentPage++;
    }

    /* Store mapping block index*/
    mapped->logicalMappingBlock = physicalBlock;

    /* Power-loss recovery*/
    for (i=0; i < numBlocks; i++) {

        /* Check that this is not the logical mapping block*/
        if (i != physicalBlock) {

            status = mapped->managed.blockStatuses[i].status;
            logicalBlock = MappedNandFlash_PhysicalToLogical(mapped, i);

            /* Block is LIVE*/
            if (status == NandBlockStatus_LIVE) {

                /* Block is not mapped -> release it*/
                if (logicalBlock == -1) {

                    TRACE_WARNING_WP("-I- Release unmapped LIVE #%d\n\r",
                                     i);
                    ManagedNandFlash_ReleaseBlock(MANAGED(mapped), i);
                }
            }
            /* Block is DIRTY*/
            else if (status == NandBlockStatus_DIRTY) {

                /* Block is mapped -> fake it as live*/
                if (logicalBlock != -1) {

                    TRACE_WARNING_WP("-I- Mark mapped DIRTY #%d -> LIVE\n\r",
                                     i);
                    mapped->managed.blockStatuses[i].status =
                                                    NandBlockStatus_LIVE;
                }
            }
            /* Block is FREE or BAD*/
            else {

                /* Block is mapped -> remove it from mapping*/
                if (logicalBlock != -1) {

                    TRACE_WARNING_WP("-I- Unmap FREE or BAD #%d\n\r", i);
                    mapped->logicalMapping[logicalBlock] = -1;
                }
            }
        }
    }

    TRACE_WARNING_WP("-I- Mapping loaded from block #%d\n\r", physicalBlock);

    return 0;
}
Ejemplo n.º 19
0
Archivo: Hub.cpp Proyecto: DonCN/haiku
void
Hub::Explore(change_item **changeList)
{
	for (int32 i = 0; i < fHubDescriptor.num_ports; i++) {
		status_t result = UpdatePortStatus(i);
		if (result < B_OK)
			continue;

#ifdef TRACE_USB
		if (fPortStatus[i].change) {
			TRACE("port %" B_PRId32 ": status: 0x%04x; change: 0x%04x\n", i,
				fPortStatus[i].status, fPortStatus[i].change);
			TRACE("device at port %" B_PRId32 ": %p (%" B_PRId32 ")\n", i,
				fChildren[i], fChildren[i] != NULL
					? fChildren[i]->USBID() : 0);
		}
#endif

		if (fPortStatus[i].change & PORT_STATUS_CONNECTION) {
			// clear status change
			DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT,
				USB_REQUEST_CLEAR_FEATURE, C_PORT_CONNECTION, i + 1,
				0, NULL, 0, NULL);

			if (fPortStatus[i].status & PORT_STATUS_CONNECTION) {
				// new device attached!
				TRACE_ALWAYS("port %" B_PRId32 ": new device connected\n", i);

				int32 retry = 2;
				while (retry--) {
					// wait for stable device power
					result = _DebouncePort(i);
					if (result != B_OK) {
						TRACE_ERROR("debouncing port %" B_PRId32
							" failed: %s\n", i, strerror(result));
						break;
					}

					// reset the port, this will also enable it
					result = ResetPort(i);
					if (result < B_OK) {
						TRACE_ERROR("resetting port %" B_PRId32 " failed\n",
							i);
						break;
					}

					result = UpdatePortStatus(i);
					if (result < B_OK)
						break;

					if ((fPortStatus[i].status & PORT_STATUS_CONNECTION) == 0) {
						// device has vanished after reset, ignore
						TRACE("device disappeared on reset\n");
						break;
					}

					if (fChildren[i] != NULL) {
						TRACE_ERROR("new device on a port that is already in "
							"use\n");
						fChildren[i]->Changed(changeList, false);
						fChildren[i] = NULL;
					}

					usb_speed speed = USB_SPEED_FULLSPEED;
					if (fDeviceDescriptor.usb_version == 0x300)
						speed = USB_SPEED_SUPER;
					else if (fPortStatus[i].status & PORT_STATUS_LOW_SPEED)
						speed = USB_SPEED_LOWSPEED;
					else if (fPortStatus[i].status & PORT_STATUS_HIGH_SPEED)
						speed = USB_SPEED_HIGHSPEED;

					// either let the device inherit our addresses (if we are
					// already potentially using a transaction translator) or
					// set ourselfs as the hub when we might become the
					// transaction translator for the device.
					int8 hubAddress = HubAddress();
					uint8 hubPort = HubPort();
					if (Speed() == USB_SPEED_HIGHSPEED || fDeviceDescriptor.usb_version == 0x300) {
						hubAddress = DeviceAddress();
						hubPort = i + 1;
					}

					Device *newDevice = GetBusManager()->AllocateDevice(this,
						hubAddress, hubPort, speed);

					if (newDevice) {
						newDevice->Changed(changeList, true);
						fChildren[i] = newDevice;
						break;
					} else {
						// the device failed to setup correctly, disable the
						// port so that the device doesn't get in the way of
						// future addressing.
						DisablePort(i);
					}
				}
			} else {
				// Device removed...
				TRACE_ALWAYS("port %" B_PRId32 ": device removed\n", i);
				if (fChildren[i] != NULL) {
					TRACE("removing device %p\n", fChildren[i]);
					fChildren[i]->Changed(changeList, false);
					fChildren[i] = NULL;
				}
			}
		}

		// other port changes we do not really handle, report and clear them
		if (fPortStatus[i].change & PORT_STATUS_ENABLE) {
			TRACE_ALWAYS("port %" B_PRId32 " %sabled\n", i,
				(fPortStatus[i].status & PORT_STATUS_ENABLE) ? "en" : "dis");
			DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT,
				USB_REQUEST_CLEAR_FEATURE, C_PORT_ENABLE, i + 1,
				0, NULL, 0, NULL);
		}

		if (fPortStatus[i].change & PORT_STATUS_SUSPEND) {
			TRACE_ALWAYS("port %" B_PRId32 " is %ssuspended\n", i,
				(fPortStatus[i].status & PORT_STATUS_SUSPEND) ? "" : "not ");
			DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT,
				USB_REQUEST_CLEAR_FEATURE, C_PORT_SUSPEND, i + 1,
				0, NULL, 0, NULL);
		}

		if (fPortStatus[i].change & PORT_STATUS_OVER_CURRENT) {
			TRACE_ALWAYS("port %" B_PRId32 " is %sin an over current state\n",
				i, (fPortStatus[i].status & PORT_STATUS_OVER_CURRENT) ? "" : "not ");
			DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT,
				USB_REQUEST_CLEAR_FEATURE, C_PORT_OVER_CURRENT, i + 1,
				0, NULL, 0, NULL);
		}

		if (fPortStatus[i].change & PORT_STATUS_RESET) {
			TRACE_ALWAYS("port %" B_PRId32 "was reset\n", i);
			DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT,
				USB_REQUEST_CLEAR_FEATURE, C_PORT_RESET, i + 1,
				0, NULL, 0, NULL);
		}
	}

	// explore down the tree if we have hubs connected
	for (int32 i = 0; i < fHubDescriptor.num_ports; i++) {
		if (!fChildren[i] || (fChildren[i]->Type() & USB_OBJECT_HUB) == 0)
			continue;

		((Hub *)fChildren[i])->Explore(changeList);
	}
}
Ejemplo n.º 20
0
/**
 * \brief  Saves the logical mapping on a FREE, unmapped physical block. Allocates the
 * new block, releases the previous one (if any) and save the mapping.
 *
 * \param mapped  Pointer to a MappedNandFlash instance.
 * \param physicalBlock  Physical block number.
 * \return  0 if successful; otherwise, returns NandCommon_ERROR_WRONGSTATUS
 * if the block is not LIVE, or a NandCommon_ERROR code.
 */
unsigned char MappedNandFlash_SaveLogicalMapping(
    struct MappedNandFlash *mapped,
    unsigned short physicalBlock)
{
    unsigned char error;
    unsigned char data[NandCommon_MAXPAGEDATASIZE];
    unsigned short pageDataSize =
                    NandFlashModel_GetPageDataSize(MODEL(mapped));
    /*unsigned short numBlocks =
                    ManagedNandFlash_GetDeviceSizeInBlocks(MANAGED(mapped));*/
    unsigned int i;
    unsigned int remainingSize;
    unsigned char *currentBuffer;
    unsigned short currentPage;
    unsigned int writeSize;
    signed short previousPhysicalBlock;

    TRACE_INFO("MappedNandFlash_SaveLogicalMapping(B#%d)\n\r", physicalBlock);

    /* If mapping has not been modified, do nothing*/
    if (!mapped->mappingModified) {

        return 0;
    }

    /* Allocate new block*/
    error = ManagedNandFlash_AllocateBlock(MANAGED(mapped), physicalBlock);
    if (error) {

        return error;
    }

    /* Save mapping*/
    previousPhysicalBlock = mapped->logicalMappingBlock;
    mapped->logicalMappingBlock = physicalBlock;

    /* Save actual mapping in pages #1-#XXX*/
    currentBuffer = (unsigned char *) mapped->logicalMapping;
    remainingSize = sizeof(mapped->logicalMapping);
    currentPage = 1;
    while (remainingSize > 0) {

        writeSize = min(remainingSize, pageDataSize);
        memset(data, 0xFF, pageDataSize);
        memcpy(data, currentBuffer, writeSize);
        error = ManagedNandFlash_WritePage(MANAGED(mapped),
                                           physicalBlock,
                                           currentPage,
                                           data,
                                           0);
        if (error) {

            TRACE_ERROR(
             "MappedNandFlash_SaveLogicalMapping: Failed to write mapping\n\r");
            return error;
        }

        currentBuffer += writeSize;
        remainingSize -= writeSize;
        currentPage++;
    }

    /* Mark page #0 of block with a distinguishible pattern, so the mapping can
       be retrieved at startup*/
    for (i=0; i < pageDataSize; i++) {

        data[i] = PATTERN(i);
    }
    error = ManagedNandFlash_WritePage(MANAGED(mapped),
                                       physicalBlock, 0,
                                       data, 0);
    if (error) {

        TRACE_ERROR(
            "MappedNandFlash_SaveLogicalMapping: Failed to write pattern\n\r");
        return error;
    }

    /* Mapping is not modified anymore*/
    mapped->mappingModified = 0;

    /* Release previous block (if any)*/
    if (previousPhysicalBlock != -1) {

        TRACE_DEBUG("Previous physical block was #%d\n\r",
                    previousPhysicalBlock);
        error = ManagedNandFlash_ReleaseBlock(MANAGED(mapped),
                                              previousPhysicalBlock);
        if (error) {

            return error;
        }
    }

    TRACE_INFO("Mapping saved on block #%d\n\r", physicalBlock);

    return 0;
}
Ejemplo n.º 21
0
NTSTATUS DDKAPI Hook_NtCreateSection (PHANDLE  SectionHandle,
				      ACCESS_MASK  DesiredAccess,
				      POBJECT_ATTRIBUTES  ObjectAttributes,
				      PLARGE_INTEGER  MaximumSize,
				      ULONG  SectionPageProtection,
				      ULONG  AllocationAttributes,
				      HANDLE  FileHandle)
{
  PROC		pfnStub = Hooks_GetStubAddress (HOOKS_NTCREATESECTION) ;
  NTSTATUS	nStatus ;

  TRACE ;

  //if( FileHandle==NULL )
  //  TRACE_WARNING (TEXT("FileHandle==NULL\n")) ;

  nStatus = pfnStub (SectionHandle, DesiredAccess,
		     ObjectAttributes, MaximumSize,
		     SectionPageProtection,
		     AllocationAttributes,
		     FileHandle) ;

  if( nStatus==STATUS_SUCCESS && FileHandle )
    {       
      WOTFILE		*pWotFileData ;
      WOTSECTION	*pWotSectionData ;
      ULONG		nWotDataSize ;
      PVOID		pObjectFile = NULL ;
      PVOID		pObjectSection = NULL ;

      nStatus = ObReferenceObjectByHandle (FileHandle, GENERIC_ALL, NULL, KernelMode, &pObjectFile, NULL) ;
      if( nStatus!=STATUS_SUCCESS || pObjectFile==NULL )
	{
	  TRACE_ERROR (TEXT("ObReferenceObjectByHandle failed (status=0x%08X)\n"), nStatus) ;
	  ZwClose (*SectionHandle) ;
	  return nStatus ;
	}

      nStatus = WatchObjs_Lock () ;
      if( nStatus != STATUS_SUCCESS ) 
	{
	  ObDereferenceObject (pObjectFile) ;
	  ZwClose (*SectionHandle) ;
	  return nStatus ;
	}
      
      nStatus = WatchObjs_GetFromPointer (pObjectFile, WOT_FILE, (void**)&pWotFileData, &nWotDataSize) ;
      
      if( nStatus==STATUS_SUCCESS )
	{
	  pWotSectionData = MALLOC (nWotDataSize) ;

	  if( pWotSectionData == NULL )
	    {
	      TRACE_ERROR (TEXT("Failed to allocate structure WOTSECTION (%u bytes)\n"), nWotDataSize) ;
	      WatchObjs_Unlock () ;
	      ObDereferenceObject (pObjectFile) ;
	      ZwClose (*SectionHandle) ;
	      return STATUS_INSUFFICIENT_RESOURCES ;
	    }
	  
	  memcpy (pWotSectionData, pWotFileData, nWotDataSize) ;

	  WatchObjs_Unlock () ;
	  ObDereferenceObject (pObjectFile) ;
	}
      else
	{
	  UNICODE_STRING	usFileName ;

	  WatchObjs_Unlock () ;
	  ObDereferenceObject (pObjectFile) ;
	  
	  nWotDataSize = sizeof(WOTSECTION) + MAX_PATH*sizeof(WCHAR) ;
	  pWotSectionData = MALLOC (nWotDataSize) ;

	  if( pWotSectionData == NULL )
	    {
	      TRACE_ERROR (TEXT("Failed to allocate structure WOTSECTION (%u bytes)\n"), nWotDataSize) ;
	      ZwClose (*SectionHandle) ;
	      return STATUS_INSUFFICIENT_RESOURCES ;
	    }

	  usFileName.Length = 0 ;
	  usFileName.MaximumLength = MAX_PATH *sizeof(WCHAR) ;	
	  usFileName.Buffer = MALLOC(usFileName.MaximumLength) ;

	  if( usFileName.Buffer == NULL )
	    {
	      TRACE_ERROR (TEXT("Failed to allocate buffer for filename (%u bytes)\n"), usFileName.MaximumLength) ;
	      FREE(pWotSectionData) ;
	      ZwClose (*SectionHandle) ;
	      return STATUS_INSUFFICIENT_RESOURCES ;
	    }	  
	  
	  nStatus = FileInfo_GetPath (FileHandle, &usFileName) ;
	  
	  if( nStatus!=STATUS_SUCCESS )
	    {
	      TRACE_ERROR (TEXT("FileInfo_GetDosPath failed (status=0x%08X)\n"), nStatus) ;
	      RtlCopyUnicodeString (&usFileName, &g_usUnknownFile) ;	  
	    }        
	}     

      TRACE_INFO (TEXT("File = %ls\n"), pWotSectionData->wszFilePath) ; 
      
      ASSERT (*SectionHandle!=NULL) ;

      nStatus = ObReferenceObjectByHandle (*SectionHandle, GENERIC_ALL, NULL, KernelMode, &pObjectSection, NULL) ;
      if( nStatus!=STATUS_SUCCESS || pObjectSection==NULL )
	{
	  TRACE_ERROR (TEXT("ObReferenceObjectByHandle failed (status=0x%08X)\n"), nStatus) ;
	  ZwClose (*SectionHandle) ;
	  return nStatus ;
	}

      nStatus = WatchObjs_Lock () ;
      if( nStatus != STATUS_SUCCESS ) 
	{
	  ZwClose (*SectionHandle) ;
	  ObDereferenceObject (pObjectSection) ;
	  return nStatus ;
	}
      
      nStatus = WatchObjs_AddFromPointer (pObjectSection,
					  WOT_SECTION,
					  pWotSectionData,
					  nWotDataSize) ;   
      WatchObjs_Unlock () ;  
      ObDereferenceObject (pObjectSection) ;    

      // restore original status
      nStatus = STATUS_SUCCESS ;
    }

  return nStatus ;
}
Ejemplo n.º 22
0
/**
 * \brief  Scans a mapped nandflash to find an existing logical block mapping. If a
 * block contains the mapping, its index is stored in the provided variable (if
 * pointer is not 0).
 *
 * \param mapped  Pointer to a MappedNandFlash instance.
 * \param logicalMappingBlock  Pointer to a variable for storing the block number.
 * \return  0 if mapping has been found; otherwise returns
 * NandCommon_ERROR_NOMAPPING if no mapping exists, or another NandCommon_ERROR_xxx code.
 */
static unsigned char FindLogicalMappingBlock(
    const struct MappedNandFlash *mapped,
    signed short *logicalMappingBlock)
{
    unsigned short block;
    unsigned char found;
    unsigned short numBlocks = ManagedNandFlash_GetDeviceSizeInBlocks(MANAGED(mapped));
    unsigned short pageDataSize = NandFlashModel_GetPageDataSize(MODEL(mapped));
    unsigned char error;
    unsigned char data[NandCommon_MAXPAGEDATASIZE];
    unsigned int i;

    TRACE_INFO("FindLogicalMappingBlock()~%d\n\r", numBlocks);

    /* Search each LIVE block */
    found = 0;
    block = 0;
    while (!found && (block < numBlocks)) {

        /* Check that block is LIVE*/
        if (MANAGED(mapped)->blockStatuses[block].status == NandBlockStatus_LIVE) {

            /* Read block*/
            TRACE_INFO("Checking LIVE block #%d\n\r", block);
            error = ManagedNandFlash_ReadPage(MANAGED(mapped), block, 0, data, 0);
            if (!error) {

                /* Compare data with logical mapping pattern*/
                i = 0;
                found = 1;
                while ((i < pageDataSize) && found) {

                    if (data[i] != PATTERN(i)) {

                        found = 0;
                    }
                    i++;
                }

                /* If this is the mapping, stop looking*/
                if (found) {

                    TRACE_WARNING_WP("-I- Logical mapping in block #%d\n\r",
                                     block);
                    if (logicalMappingBlock) {

                        *logicalMappingBlock = block;
                    }
                    return 0;
                }
            }
            else if (error != NandCommon_ERROR_WRONGSTATUS) {

                TRACE_ERROR(
                          "FindLogicalMappingBlock: Failed to scan block #%d\n\r",
                          block);
                return error;
            }
        }

        block++;
    }

    TRACE_WARNING("No logical mapping found in device\n\r");
    return NandCommon_ERROR_NOMAPPING;
}
Ejemplo n.º 23
0
int
get_srk_info(struct srk_info *srk)
{
	char *passwd_ptr = NULL;
	char *secret = NULL;
	int i;

	srk->mode = get_srk_mode();
	if (srk->mode == -1)
		return -1;

	srk->secret = NULL;
	passwd_ptr = getenv("OCK_SRK_SECRET");

	/* If nothing is set, then use original opencryptoki default of
	 *  secret is NULL and TSS_SECRET_MODE_PLAIN.
	 */
	if (passwd_ptr == NULL) {
		srk->len = 0;
		if (srk->mode == 0) {
			srk->mode = TSS_SECRET_MODE_PLAIN;
			return 0;
		}
	} else
		srk->len = strlen(passwd_ptr);

	/* A mode required at this point...  */
	if (srk->mode == 0) {
		TRACE_ERROR("SRK policy's secret mode is not set.\n");
		return -1;
	}

	 /*
	  * getenv() returns a ptr to the actual string in our env,
	  * so be sure to make a copy to avoid problems.
	  */

	if (srk->len != 0) {
		if ((secret = (char *)malloc(srk->len)) == NULL) {
			TRACE_ERROR("malloc of %d bytes failed.\n", srk->len);
			return -1;
		}
		memcpy(secret, passwd_ptr, srk->len);
		srk->secret = secret;
	}

	/* Secrets that are a hash, need to be converted from a
	 *  hex string to an array of bytes.
	 */
	if (srk->mode == TSS_SECRET_MODE_SHA1) {

		char *secret_h;
		int h_len = TPM_SHA1_160_HASH_LEN;

		if ((secret_h = (char *)malloc(h_len)) == NULL) {
			TRACE_ERROR("malloc of %d bytes failed.\n", h_len);
			goto error;
		}

		/* reuse passwd ptr since we dont need it anymore. */
		passwd_ptr = secret;

		/* Assume hash is read in as string of hexidecimal digits.
		 * 2 hex digits are required to represent a byte.
		 * thus we need 2 * TPM_SHA1_160_HASH_LEN to
		 * represent the hash.
		 */
		if (srk->len != (h_len * 2)) {
			free(secret_h);
			TRACE_DEVEL("Hashed secret is %d bytes, expected %d.\n",
				     srk->len, h_len*2);
			goto error;
		}

		/* convert hexadecimal string into a byte array... */
		for (i = 0; i < h_len; i++) {
			sscanf(passwd_ptr, "%2hhx", &secret_h[i]);
			passwd_ptr += 2;
		}

		srk->len = h_len;
		srk->secret = secret_h;
		free(secret);
	}

	return	0;

error:
	if (secret)
		free(secret);
	return -1;
}
Ejemplo n.º 24
0
/**
 * \brief  Reads the data and/or spare of a page of a nandflash chip, and verify that
 * the data is valid using the ECC information contained in the spare. If one
 * buffer pointer is 0, the corresponding area is not saved.
 * \param ecc  Pointer to an EccNandFlash instance.
 * \param block  Number of block to read from.
 * \param page  Number of page to read inside given block.
 * \param data  Data area buffer.
 * \param spare  Spare area buffer.
 * \return 0 if the data has been read and is valid; otherwise returns either
 * NandCommon_ERROR_CORRUPTEDDATA or ...
 */
unsigned char EccNandFlash_ReadPage(
    const struct EccNandFlash *ecc,
    unsigned short block,
    unsigned short page,
    void *data,
    void *spare)
{
    unsigned char tmpSpare[NandCommon_MAXPAGESPARESIZE];
    unsigned char error;
#ifndef HARDWARE_ECC
//    unsigned char tmpData[NandCommon_MAXPAGEDATASIZE];
    unsigned char hamming[NandCommon_MAXSPAREECCBYTES];
#else
    unsigned char hsiaoInSpare[NandCommon_MAXSPAREECCBYTES];
    unsigned char hsiao[NandCommon_MAXSPAREECCBYTES];
#endif

    unsigned short pageDataSize = NandFlashModel_GetPageDataSize(MODEL(ecc));
    unsigned char pageSpareSize = NandFlashModel_GetPageSpareSize(MODEL(ecc));

    TRACE_DEBUG("EccNandFlash_ReadPage(B#%d:P#%d)\n\r", block, page);
#ifndef HARDWARE_ECC
    /* Start by reading the spare and the data */
    error = RawNandFlash_ReadPage(RAW(ecc), block, page, gdwNandFlashTempBuffer, tmpSpare);
    if (error) {

        TRACE_ERROR("EccNandFlash_ReadPage: Failed to read page\n\r");
        return error;
    }

    /* Retrieve ECC information from page and verify the data */
    NandSpareScheme_ReadEcc(NandFlashModel_GetScheme(MODEL(ecc)), tmpSpare, hamming);
    error = Hamming_Verify256x(gdwNandFlashTempBuffer, pageDataSize, hamming);
#else
    error = RawNandFlash_ReadPage(RAW(ecc), block, page, (unsigned char*)data, tmpSpare);
    if (error) {

        TRACE_ERROR("EccNandFlash_ReadPage: $page %d.%d\n\r",
                    block, page);
        return error;
    }
    /* Retrieve ECC information from page */
    NandSpareScheme_ReadEcc(NandFlashModel_GetScheme(MODEL(ecc)), tmpSpare, hsiaoInSpare);
    HSMC4_GetEccParity(pageDataSize, hsiao, NandFlashModel_GetDataBusWidth(MODEL(ecc)));
    /* Verify the data */
    error = HSMC4_VerifyHsiao((unsigned char*) data,
                              pageDataSize,
                              hsiaoInSpare,
                              hsiao,
                              NandFlashModel_GetDataBusWidth(MODEL(ecc)));
#endif
    if (error && (error != Hamming_ERROR_SINGLEBIT)) {

        TRACE_ERROR("EccNandFlash_ReadPage: at B%d.P%d Unrecoverable data\n\r",
                    block, page);
        return NandCommon_ERROR_CORRUPTEDDATA;
    }
#ifndef HARDWARE_ECC
    /* Copy data and/or spare into final buffers */
    if (data) {

        memcpy(data, gdwNandFlashTempBuffer, pageDataSize);
    }
    if (spare) {

        memcpy(spare, tmpSpare, pageSpareSize);
    }
#else
     if (spare) {

        memcpy(spare, tmpSpare, pageSpareSize);
    }
#endif
    return 0;
}
Ejemplo n.º 25
0
/**
 *  \brief GMAC Interrupt handler
 *  \param pGmacd Pointer to GMAC Driver instance.
 */
void GMACD_Handler(sGmacd *pGmacd, gmacQueList_t queIdx)
{
	Gmac *pHw = pGmacd->pHw;
	uint32_t isr;
	uint32_t rsr;

	/* Interrupt Status Register is cleared on read */
	while ((isr = GMAC_GetItStatus(pHw, queIdx)) != 0) {
		/*  Sync Frame Received - PTP */
		if (0u != (isr & GMAC_ISR_SFR)) {
			rsr = GMAC_ISR_SFR;
			memory_barrier();

			/* Invoke callbacks */
			if (pGmacd->queueList[queIdx].fRxCb)
				pGmacd->queueList[queIdx].fRxCb(rsr);
			else {
			}
		} else {
		}

		/* Peer Delay Request Frame Received - PTP */
		if (0u != (isr & GMAC_ISR_PDRQFR)) {
			rsr = GMAC_ISR_PDRQFR;
			memory_barrier();

			/* Invoke callbacks */
			if (pGmacd->queueList[queIdx].fRxCb)
				pGmacd->queueList[queIdx].fRxCb(rsr);
			else {
			}
		} else {
		}

		/* Peer Delay Response Frame Received - PTP */
		if (0u != (isr & GMAC_ISR_PDRSFR)) {

			rsr = GMAC_ISR_PDRSFR;
			memory_barrier();

			/* Invoke callbacks */
			if (pGmacd->queueList[queIdx].fRxCb)
				pGmacd->queueList[queIdx].fRxCb(rsr);
			else {
			}
		} else {
		}

		if (0u != (isr & GMAC_ISR_TSU)) {
			/* Invoke call back with flag set to TSU comparison interrupt */
			rsr = GMAC_ISR_TSU;
			memory_barrier();

			/* Invoke callbacks */
			if (pGmacd->queueList[queIdx].fRxCb)
				pGmacd->queueList[queIdx].fRxCb(rsr);
			else {
			}
		} else {
		}

		/* RX packet */
		if (isr & GMAC_INT_RX_STATUS_BITS) {
			/* Clear status */
			rsr = GMAC_GetRxStatus(pHw);
			GMAC_ClearRxStatus(pHw, rsr);

			/* Invoke callback */
			if (pGmacd->queueList[queIdx].fRxCb)
				pGmacd->queueList[queIdx].fRxCb(rsr);
		}

		/* TX error */
		if (isr & GMAC_INT_TX_STATUS_ERR_BITS) {
			GMACD_TxErrorHandler(pGmacd, queIdx);
			break;
		}

#ifndef PTP_1588_TX_DISABLE

		/* Transmit of SYNC / PDELAY_REQ / PDELAY_RSP */
		if (0u != (isr & isrMasks[gPtpMsgTxQue[ptpTxQueReadIdx]])) {
			/* Invoke callback */
			/*  Check if it is possible for multiple messages to be triggered
			within a single isr. If so, a loop may be needed to validate the top
			of the queue with the actual interrupt that has been triggered */
			/* while (0u != (isr & (GMAC_IMR_SFT | GMAC_IMR_PDRQFT | GMAC_IMR_PDRSFT))) { */
			if (pGmacd->queueList[queIdx].fTxPtpEvtCb) {
				switch (gPtpMsgTxQue[ptpTxQueReadIdx]) {
				case SYNC_MSG_TYPE:
					pGmacd->queueList[queIdx].fTxPtpEvtCb
					(gPtpMsgTxQue[ptpTxQueReadIdx],
					 GMAC_GetTxEvtFrameSec(pHw),
					 GMAC_GetTxEvtFrameNsec(pHw),
					 gPtpMsgTxSeqId[ptpTxQueReadIdx]);
					isr &= GMAC_IMR_SFT;
					break;

				case PDELAY_REQ_TYPE:
					pGmacd->queueList[queIdx].fTxPtpEvtCb
					(gPtpMsgTxQue[ptpTxQueReadIdx],
					 GMAC_GetTxPeerEvtFrameSec(pHw),
					 GMAC_GetTxPeerEvtFrameNsec(pHw),
					 gPtpMsgTxSeqId[ptpTxQueReadIdx]);
					isr &= GMAC_IMR_PDRQFT;
					break;

				case PDELAY_RESP_TYPE:
					pGmacd->queueList[queIdx].fTxPtpEvtCb
					(gPtpMsgTxQue[ptpTxQueReadIdx],
					 GMAC_GetTxPeerEvtFrameSec(pHw),
					 GMAC_GetTxPeerEvtFrameNsec(pHw),
					 gPtpMsgTxSeqId[ptpTxQueReadIdx]);
					isr &= GMAC_IMR_PDRSFT;
					break;

				default:
					/* Only for Peer messages & sync messages */
					break;
				};
			} else {
			}

			ptpTxQueReadIdx++;
			ptpTxQueReadIdx &= (EFRS_BUFFER_LEN - 1);

		} else {
			/* if (0u != (isr & isrMasks[gPtpMsgTxQue[ptpTxQueReadIdx]])) */
		}

#endif /* #ifndef PTP_1588_TX_DISABLE */

		/* TX packet */
		if (isr & GMAC_IER_TCOMP)
			GMACD_TxCompleteHandler(pGmacd, queIdx);

		if (isr & GMAC_IER_HRESP)
			TRACE_ERROR("HRESP\n\r");
	}
}
Ejemplo n.º 26
0
/**
 * \brief  Writes the data and/or spare area of a nandflash page, after calculating an
 * ECC for the data area and storing it in the spare. If no data buffer is
 * provided, the ECC is read from the existing page spare. If no spare buffer
 * is provided, the spare area is still written with the ECC information
 * calculated on the data buffer.
 * \param ecc  Pointer to an EccNandFlash instance.
 * \param block  Number of block to read from.
 * \param page  Number of page to read inside given block.
 * \param data  Data area buffer.
 * \param spare  Spare area buffer.
 * \return 0 if successful; otherwise returns an error code.
 */
unsigned char EccNandFlash_WritePage(
    const struct EccNandFlash *ecc,
    unsigned short block,
    unsigned short page,
    void *data,
    void *spare)
{
    unsigned char error;
    unsigned char tmpSpare[NandCommon_MAXPAGESPARESIZE];
    unsigned short pageDataSize = NandFlashModel_GetPageDataSize(MODEL(ecc));
    unsigned short pageSpareSize = NandFlashModel_GetPageSpareSize(MODEL(ecc));
#ifndef HARDWARE_ECC
    unsigned char hamming[NandCommon_MAXSPAREECCBYTES];
#else
    unsigned char hsiao[NandCommon_MAXSPAREECCBYTES];
#endif

    assert( (data != NULL) || (spare != NULL) ) ;
//    TRACE_DEBUG(  "EccNandFlash_WritePage: At least one area must be written\n\r" ) ;
    TRACE_DEBUG("EccNandFlash_WritePage(B#%d:P#%d)\n\r", block, page);
#ifndef HARDWARE_ECC
    /* Compute ECC on the new data, if provided */
    /* If not provided, hamming code set to 0xFFFF.. to keep existing bytes */
    memset(hamming, 0xFF, NandCommon_MAXSPAREECCBYTES);
    if (data) {

        /* Compute hamming code on data */
        Hamming_Compute256x(data, pageDataSize, hamming);
    }

    /* Store code in spare buffer (if no buffer provided, use a temp. one) */
    if (!spare) {

        spare = tmpSpare;
        memset(spare, 0xFF, pageSpareSize);
    }
    NandSpareScheme_WriteEcc(NandFlashModel_GetScheme(MODEL(ecc)), spare, hamming);

    /* Perform write operation */
    error = RawNandFlash_WritePage(RAW(ecc), block, page, data, spare);
    if (error) {

        TRACE_ERROR("EccNandFlash_WritePage: Failed to write page\n\r");
        return error;
    }

#else
    /* Store code in spare buffer (if no buffer provided, use a temp. one) */
    if (!spare) {
        spare = tmpSpare;
        memset(spare, 0xFF, pageSpareSize);
    }
    /* Perform write operation */
    error = RawNandFlash_WritePage(RAW(ecc), block, page, data, spare);
    if (error) {

        TRACE_ERROR("EccNandFlash_WritePage: Failed to write page\n\r");
        return error;
    }
    HSMC4_GetEccParity(pageDataSize, hsiao, NandFlashModel_GetDataBusWidth(MODEL(ecc)));
    /* Perform write operation */
    NandSpareScheme_WriteEcc(NandFlashModel_GetScheme(MODEL(ecc)), spare, hsiao);
    error = RawNandFlash_WritePage(RAW(ecc), block, page, 0, spare);
    if (error) {
        TRACE_ERROR("EccNandFlash_WritePage: Failed to write page\n\r");
        return error;
    }
#endif
    return 0;
}
int DynamixelSimpleAPI::setSetting(const int id, const int reg_name, const int reg_value, int reg_type, const int device)
{
    int status = 0;

    if (checkId(id) == true)
    {
        // Device detection
        const int (*cctt)[8] = getRegisterTable(device);

        if (cctt == NULL)
        {
            // Using default control table from this SimpleAPI isntance
            cctt = ct;
        }

        if (cctt)
        {
            // Find register's informations (addr, size...)
            RegisterInfos infos = {-1, -1, -1, -1, -1, -1, -1, -1, -1};
            if (getRegisterInfos(cctt, reg_name, infos) == 1)
            {
                // Check if we have permission to write into this register
                if (infos.reg_access_mode == READ_WRITE)
                {
                    // Check value
                    if (reg_value >= infos.reg_value_min && reg_value <= infos.reg_value_max)
                    {
                        // Write value
                        if (infos.reg_size == 1)
                        {
                            dxl_write_byte(id, infos.reg_addr, reg_value);
                        }
                        else if (infos.reg_size == 2)
                        {
                            dxl_write_word(id, infos.reg_addr, reg_value);
                        }

                        // Check for error
                        if (dxl_print_error() == 0)
                        {
                            status = 1;
                        }
                    }
                    else
                    {
                        TRACE_ERROR(DAPI, "[#%i] setSetting(reg %i / %s) [VALUE ERROR] (min: %i / max: %i)\n",
                                    id, reg_name, getRegisterNameTxt(reg_name).c_str(), infos.reg_value_min, infos.reg_value_max);
                    }
                }
                else
                {
                    TRACE_ERROR(DAPI, "[#%i] setSetting(reg %i / %s) [REGISTER ACCESS ERROR]\n", id, reg_name, getRegisterNameTxt(reg_name).c_str());
                }
            }
            else
            {
                TRACE_ERROR(DAPI, "[#%i] setSetting(reg %i / %s) [REGISTER NAME ERROR]\n", id, reg_name, getRegisterNameTxt(reg_name).c_str());
            }
        }
        else
        {
            TRACE_ERROR(DAPI, "[#%i] setSetting(reg %i / %s) [CONTROL TABLE ERROR]\n", id, reg_name, getRegisterNameTxt(reg_name).c_str());
        }
    }
    else
    {
        TRACE_ERROR(DAPI, "[#%i] setSetting(reg %i / %s) [DEVICE ID ERROR]\n", id, reg_name, getRegisterNameTxt(reg_name).c_str());
    }

    return status;
}
Ejemplo n.º 28
0
int_t main(void)
{
   error_t error;
   NetInterface *interface;
   OsTask *task;
   MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
   Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
   Ipv6Addr ipv6Addr;
#endif

   //System initialization
   systemInit();

   //Initialize kernel
   osInitKernel();
   //Configure debug UART
   debugInit(115200);

   //Start-up message
   TRACE_INFO("\r\n");
   TRACE_INFO("******************************\r\n");
   TRACE_INFO("*** CycloneSSL Client Demo ***\r\n");
   TRACE_INFO("******************************\r\n");
   TRACE_INFO("Copyright: 2010-2014 Oryx Embedded\r\n");
   TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
   TRACE_INFO("Target: PIC32MX795F512L\r\n");
   TRACE_INFO("\r\n");

   //Configure I/Os
   ioInit();

   //Generate a random seed

   //PRNG initialization
   error = yarrowInit(&yarrowContext);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize PRNG!\r\n");
      //Exit immediately
      return ERROR_FAILURE;
   }

   //Properly seed the PRNG
   error = yarrowSeed(&yarrowContext, (uint8_t *) seed, 32);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to seed PRNG!\r\n");
      //Exit immediately
      return error;
   }

   //Debug message
   TRACE_INFO("Loading credentials...\r\n");

   //Start of exception handling block
   do
   {
      //Load trusted CA certificates
      error = resGetData(APP_CA_CERT_BUNDLE, (uint8_t **) &trustedCaList, &trustedCaListLength);
      //Any error to report?
      if(error) break;

      //Load client's certificate
      error = resGetData(APP_CLIENT_CERT, (uint8_t **) &clientCert, &clientCertLength);
      //Any error to report?
      if(error) break;

      //Load client's private key
      error = resGetData(APP_CLIENT_PRIVATE_KEY, (uint8_t **) &clientPrivateKey, &clientPrivateKeyLength);
      //Any error to report?
      if(error) break;

      //End of exception handling block
   } while(0);

   //Check error code
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to load credentials!\r\n");
   }

   //TCP/IP stack initialization
   error = tcpIpStackInit();
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
   }

   //Configure the first Ethernet interface
   interface = &netInterface[0];

   //Set interface name
   tcpIpStackSetInterfaceName(interface, "eth0");
   //Set host name
   tcpIpStackSetHostname(interface, "SSLClientDemo");
   //Select the relevant network adapter
   tcpIpStackSetDriver(interface, &pic32mxEthDriver);
   tcpIpStackSetPhyDriver(interface, &dp83848PhyDriver);
   //Set external interrupt line driver
   tcpIpStackSetExtIntDriver(interface, &extIntDriver);

#if (APP_USE_DEFAULT_MAC_ADDR == ENABLED)
   //Use the factory preprogrammed MAC address
   macStringToAddr("00-00-00-00-00-00", &macAddr);
   tcpIpStackSetMacAddr(interface, &macAddr);
#else
   //Override the factory preprogrammed address
   macStringToAddr(APP_MAC_ADDR, &macAddr);
   tcpIpStackSetMacAddr(interface, &macAddr);
#endif

   //Initialize network interface
   error = tcpIpStackConfigInterface(interface);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
   }

#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
   //Get default settings
   dhcpClientGetDefaultSettings(&dhcpClientSettings);
   //Set the network interface to be configured by DHCP
   dhcpClientSettings.interface = interface;
   //Disable rapid commit option
   dhcpClientSettings.rapidCommit = FALSE;

   //DHCP client initialization
   error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
   //Failed to initialize DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize DHCP client!\r\n");
   }

   //Start DHCP client
   error = dhcpClientStart(&dhcpClientContext);
   //Failed to start DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start DHCP client!\r\n");
   }
#else
   //Set IPv4 host address
   ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
   ipv4SetHostAddr(interface, ipv4Addr);

   //Set subnet mask
   ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
   ipv4SetSubnetMask(interface, ipv4Addr);

   //Set default gateway
   ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
   ipv4SetDefaultGateway(interface, ipv4Addr);

   //Set primary and secondary DNS servers
   ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 0, ipv4Addr);
   ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif

#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
   //Get default settings
   slaacGetDefaultSettings(&slaacSettings);
   //Set the network interface to be configured
   slaacSettings.interface = interface;

   //SLAAC initialization
   error = slaacInit(&slaacContext, &slaacSettings);
   //Failed to initialize SLAAC?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize SLAAC!\r\n");
   }

   //Start IPv6 address autoconfiguration process
   error = slaacStart(&slaacContext);
   //Failed to start SLAAC process?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start SLAAC!\r\n");
   }
#else
   //Set link-local address
   ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
   ipv6SetLinkLocalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

   //Set IPv6 prefix
   ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
   ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);

   //Set global address
   ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
   ipv6SetGlobalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

   //Set router
   ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
   ipv6SetRouter(interface, &ipv6Addr);

   //Set primary and secondary DNS servers
   ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 0, &ipv6Addr);
   ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif

   //Create user task
   task = osCreateTask("User Task", userTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Create a task to blink the LED
   task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Start the execution of tasks
   osStartKernel();

   //This function should never return
   return 0;
}
Ejemplo n.º 29
0
static void BCAN_Handler(unsigned int can_number) {
    CAN_t *can;
    AT91PS_CAN base_can;
    unsigned int status;

    switch (can_number) {
    case 0:
        base_can = AT91C_BASE_CAN0;
        can = &can0;
        break;
#ifdef AT91C_BASE_CAN1
    case 1:
        base_can = AT91C_BASE_CAN1;
        can = &can1;
        break;
#endif
    default:
        TRACE_ERROR("Unkown CAN %X\n\r", can_number);
        break;
    }

    status = (base_can->CAN_SR) & (base_can->CAN_IMR);

    TRACE_DEBUG("CAN%d status=0x%X\n\r", can_number, status);
    if (status & AT91C_CAN_WAKEUP) {
        can->test_status = AT91C_TEST_OK;
        can->state = CAN_IDLE;
        base_can->CAN_IDR = status;
    }
    // Mailbox event ?
    else if (status & 0x0000FFFF) {
        TRACE_DEBUG("Mailbox event\n\r");

        // Handle Mailbox interrupts
        for (unsigned int numMailbox = 0; numMailbox < NUM_MAILBOX_MAX; numMailbox++) {
            AT91PS_CAN_MB mailbox = CAN_Mailboxes[can_number][numMailbox];
            unsigned int can_msr = mailbox->CAN_MB_MSR;

            if ((AT91C_CAN_MRDY & can_msr) == AT91C_CAN_MRDY) {
                // Mailbox object type
                CAN_mot_t message_mode = (mailbox->CAN_MB_MMR >> 24) & 0x07;
                TRACE_DEBUG("message_mode 0x%X\n\r", message_mode);
                TRACE_DEBUG("numMailbox 0x%X\n\r", numMailbox);

                switch (message_mode) {
                case CAN_MOT_RECEPT:
                case CAN_MOT_RECEPT_OW:
                case CAN_MOT_PRODUCER:
                    TRACE_DEBUG("Mailbox is in RECEPTION\n\r");
                    TRACE_DEBUG("Length 0x%X\n\r", (can_msr >> 16) & 0xF);
                    TRACE_DEBUG("CAN_MB_MID 0x%X\n\r", (mailbox->CAN_MB_MID & AT91C_CAN_MIDvA) >> 18);
                    TRACE_DEBUG("CAN_MB_MAM 0x%X\n\r", (mailbox->CAN_MB_MAM & AT91C_CAN_MIDvA) >> 18);
                    TRACE_DEBUG("CAN_MB_MFID 0x%X\n\r", (mailbox->CAN_MB_MFID & AT91C_CAN_MIDvA) >> 18);

                    TRACE_DEBUG("can_number %d\n\r", can_number);
                    BCAN_Received_Packets[can_number][numMailbox].valid = 1;
                    BCAN_Received_Packets[can_number][numMailbox].mailbox = numMailbox;
                    BCAN_Received_Packets[can_number][numMailbox].data_low = mailbox->CAN_MB_MDL;
                    BCAN_Received_Packets[can_number][numMailbox].data_high = mailbox->CAN_MB_MDH;
                    BCAN_Received_Packets[can_number][numMailbox].size = (can_msr >> 16) & 0x0F;
                    can->state = CAN_IDLE;
                    // Message Data has been received
                    mailbox->CAN_MB_MCR = AT91C_CAN_MTCR;
                    if (can->callback && can->callback(BCAN_Received_Packets[can_number][numMailbox])) {
                        BCAN_Received_Packets[can_number][numMailbox].valid = 0;
                        BCAN_Received_Packets[can_number][numMailbox].mailbox = 0;
                        BCAN_Received_Packets[can_number][numMailbox].data_low = 0;
                        BCAN_Received_Packets[can_number][numMailbox].data_high = 0;
                        BCAN_Received_Packets[can_number][numMailbox].size = 0;
                    }

                    break;
                case CAN_MOT_TRANSMIT:
                case CAN_MOT_CONSUMER:
                    TRACE_DEBUG("Mailbox is in TRANSMIT\n\r");
                    TRACE_DEBUG("Length 0x%X\n\r", (can_msr>>16)&0xF);
                    TRACE_DEBUG("can_number %d\n\r", can_number);
                    can->state = CAN_IDLE;
                    base_can->CAN_IDR = (1 << numMailbox);
                    break;
                default:
                    TRACE_ERROR("Error in MOT\n\r");
                    break;
                }
            }
        }
Ejemplo n.º 30
0
int_t main(void)
{
    error_t error;
    NetInterface *interface;
    OsTask *task;
    MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
    Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
    Ipv6Addr ipv6Addr;
#endif

    //Update system core clock
    sysclk_init();
    board_init();

    // Initialize interrupt vector table support.
    irq_initialize_vectors();

    // Enable interrupts
    cpu_irq_enable();

    /* Call a local utility routine to initialize C-Library Standard I/O over
     * a USB CDC protocol. Tunable parameters in a conf_usb.h file must be
     * supplied to configure the USB device correctly.
     */
    stdio_usb_init();

    //Initialize kernel
    osInitKernel();
    //Configure debug UART

    //Start-up message
    TRACE_INFO("\r\n");
    TRACE_INFO("**********************************\r\n");
    TRACE_INFO("*** CycloneTCP Web Server Demo ***\r\n");
    TRACE_INFO("**********************************\r\n");
    TRACE_INFO("Copyright: 2010-2014 Oryx Embedded\r\n");
    TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
    TRACE_INFO("Target: SAM4E\r\n");
    TRACE_INFO("\r\n");

    //TCP/IP stack initialization
    error = tcpIpStackInit();
    //Any error to report?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
    }

    //Configure the first Ethernet interface
    interface = &netInterface[0];

    //Set interface name
    tcpIpStackSetInterfaceName(interface, "eth0");
    //Set host name
    tcpIpStackSetHostname(interface, "WebServerDemo");
    //Select the relevant network adapter
    tcpIpStackSetDriver(interface, &sam4eEthDriver);
    tcpIpStackSetPhyDriver(interface, &ksz8081PhyDriver);
    //Set external interrupt line driver
    tcpIpStackSetExtIntDriver(interface, &extIntDriver);
    //Set host MAC address
    macStringToAddr(APP_MAC_ADDR, &macAddr);
    tcpIpStackSetMacAddr(interface, &macAddr);

    //Initialize network interface
    error = tcpIpStackConfigInterface(interface);
    //Any error to report?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
    }

#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
    //Get default settings
    dhcpClientGetDefaultSettings(&dhcpClientSettings);
    //Set the network interface to be configured by DHCP
    dhcpClientSettings.interface = interface;
    //Disable rapid commit option
    dhcpClientSettings.rapidCommit = FALSE;

    //DHCP client initialization
    error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
    //Failed to initialize DHCP client?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to initialize DHCP client!\r\n");
    }

    //Start DHCP client
    error = dhcpClientStart(&dhcpClientContext);
    //Failed to start DHCP client?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start DHCP client!\r\n");
    }
#else
    //Set IPv4 host address
    ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
    ipv4SetHostAddr(interface, ipv4Addr);

    //Set subnet mask
    ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
    ipv4SetSubnetMask(interface, ipv4Addr);

    //Set default gateway
    ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
    ipv4SetDefaultGateway(interface, ipv4Addr);

    //Set primary and secondary DNS servers
    ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
    ipv4SetDnsServer(interface, 0, ipv4Addr);
    ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
    ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif

#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
    //Get default settings
    slaacGetDefaultSettings(&slaacSettings);
    //Set the network interface to be configured
    slaacSettings.interface = interface;

    //SLAAC initialization
    error = slaacInit(&slaacContext, &slaacSettings);
    //Failed to initialize SLAAC?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to initialize SLAAC!\r\n");
    }

    //Start IPv6 address autoconfiguration process
    error = slaacStart(&slaacContext);
    //Failed to start SLAAC process?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start SLAAC!\r\n");
    }
#else
    //Set link-local address
    ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
    ipv6SetLinkLocalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

    //Set IPv6 prefix
    ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
    ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);

    //Set global address
    ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
    ipv6SetGlobalAddr(interface, &ipv6Addr, IPV6_ADDR_STATE_VALID);

    //Set router
    ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
    ipv6SetRouter(interface, &ipv6Addr);

    //Set primary and secondary DNS servers
    ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
    ipv6SetDnsServer(interface, 0, &ipv6Addr);
    ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
    ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif

    //Get default settings
    httpServerGetDefaultSettings(&httpServerSettings);
    //Bind HTTP server to the desired interface
    httpServerSettings.interface = &netInterface[0];
    //Listen to port 80
    httpServerSettings.port = HTTP_PORT;
    //Specify the server's root directory
    strcpy(httpServerSettings.rootDirectory, "/www/");
    //Set default home page
    strcpy(httpServerSettings.defaultDocument, "index.shtm");
    //Callback functions
    httpServerSettings.authCallback = httpServerAuthCallback;
    httpServerSettings.cgiCallback = httpServerCgiCallback;
    httpServerSettings.uriNotFoundCallback = httpServerUriNotFoundCallback;

    //HTTP server initialization
    error = httpServerInit(&httpServerContext, &httpServerSettings);
    //Failed to initialize HTTP server?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to initialize HTTP server!\r\n");
    }

    //Start HTTP server
    error = httpServerStart(&httpServerContext);
    //Failed to start HTTP server?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start HTTP server!\r\n");
    }

    //Start TCP echo service
    error = tcpEchoStart();
    //Failed to TCP echo service?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start TCP echo service!\r\n");
    }

    //Start UDP echo service
    error = udpEchoStart();
    //Failed to TCP echo service?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start UDP echo service!\r\n");
    }

    //Start TCP discard service
    error = tcpDiscardStart();
    //Failed to TCP echo service?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start TCP discard service!\r\n");
    }

    //Start UDP discard service
    error = udpDiscardStart();
    //Failed to TCP echo service?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start UDP discard service!\r\n");
    }

    //Start TCP chargen service
    error = tcpChargenStart();
    //Failed to TCP echo service?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start TCP chargen service!\r\n");
    }

    //Start UDP chargen service
    error = udpChargenStart();
    //Failed to TCP echo service?
    if(error)
    {
        //Debug message
        TRACE_ERROR("Failed to start UDP chargen service!\r\n");
    }

    //Create user task
    task = osCreateTask("User Task", userTask, NULL, 500, 1);
    //Failed to create the task?
    if(task == OS_INVALID_HANDLE)
    {
        //Debug message
        TRACE_ERROR("Failed to create task!\r\n");
    }

    //Create a task to blink the LED
    task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
    //Failed to create the task?
    if(task == OS_INVALID_HANDLE)
    {
        //Debug message
        TRACE_ERROR("Failed to create task!\r\n");
    }

    //Start the execution of tasks
    osStartKernel();

    //This function should never return
    return 0;
}