コード例 #1
0
/*!
 * @brief Initiate (start) a transfer using DMA. This is not a public API as it is called from
 *  other driver functions
 */
static dspi_status_t DSPI_DRV_DmaMasterStartTransfer(uint32_t instance,
        const dspi_dma_device_t * device,
        const uint8_t * sendBuffer,
        uint8_t * receiveBuffer,
        size_t transferByteCount)
{
    /* instantiate local variable of type dspi_dma_master_state_t and point to global state */
    dspi_dma_master_state_t * dspiDmaState = (dspi_dma_master_state_t *)g_dspiStatePtr[instance];
    /* For temporarily storing DMA instance and channel */
    uint8_t transferSizeInBytes = 1U;

    uint32_t calculatedBaudRate;
    dspi_command_config_t command;  /* create an instance of the data command struct*/
    SPI_Type *base = g_dspiBase[instance];
    uint32_t txTransferByteCnt = 0;
    uint32_t rxTransferByteCnt = 0;

    /* Initialize s_wordToSend */
    s_wordToSend = 0;

    /* Check that we're not busy.*/
    if (dspiDmaState->isTransferInProgress)
    {
        return kStatus_DSPI_Busy;
    }

    /* Calculate the transfer size on bits/frame */
    if (dspiDmaState->bitsPerFrame <= 8)
    {
        transferSizeInBytes = 1U;
    }
    else if (dspiDmaState->bitsPerFrame <= 16)
    {
        transferSizeInBytes = 2U;
    }
    else
    {
        transferSizeInBytes = 4U;
    }

    /* Configure bus for this device. If NULL is passed, we assume the caller has
     * preconfigured the bus using DSPI_DRV_DmaMasterConfigureBus().
     * Do nothing for calculatedBaudRate. If the user wants to know the calculatedBaudRate
     * then they can call this function separately.
     */
    if (device)
    {
        DSPI_DRV_DmaMasterConfigureBus(instance, device, &calculatedBaudRate);
        dspiDmaState->bitsPerFrame = device->dataBusConfig.bitsPerFrame; /*update bits/frame*/
    }

    /* Check the transfer byte count. If bits/frame > 8, meaning 2 bytes, and if
     * the transfer byte count is an odd count we'll have to increase the TX transfer byte count
     * by one and assert a flag to indicate to the send functions that it will
     * need to handle an extra byte.
     * For receive, we actually round down the transfer count to the next lowest even number.
     * Then in the interrupt handler, we take care of geting this last byte.
     */
    if ((dspiDmaState->bitsPerFrame > 8) && (transferByteCount & 1UL))
    {
        dspiDmaState->extraByte = true;
        txTransferByteCnt = transferByteCount + 1U;  /* Increment to next even byte count */
        rxTransferByteCnt = transferByteCount & ~1U;  /* Decrement to next even byte count */
    }
    else
    {
        dspiDmaState->extraByte = false;
        txTransferByteCnt = transferByteCount;
        rxTransferByteCnt = transferByteCount;
    }
    /* Store the receiveBuffer pointer and receive byte count to the run-time state struct
     * for later use in the interrupt handler.
     */
    dspiDmaState->rxBuffer = (uint8_t *)receiveBuffer;
    dspiDmaState->rxTransferByteCnt = rxTransferByteCnt;

    /* Save information about the transfer for use by the ISR.*/
    dspiDmaState->isTransferInProgress = true;

    /* Reset the transfer counter to 0. Normally this is done via the PUSHR[CTCNT], but as we
     * are under DMA controller, we won't be able to change this bit dynamically after the
     * first word is transferred.
     */
    DSPI_HAL_PresetTransferCount(base, 0);

    /* flush the fifos*/
    DSPI_HAL_SetFlushFifoCmd(base, true, true);

    /* Clear status flags that may have been set from previous transfers */
    DSPI_HAL_ClearStatusFlag(base, kDspiTxComplete);
    DSPI_HAL_ClearStatusFlag(base, kDspiEndOfQueue);
    DSPI_HAL_ClearStatusFlag(base, kDspiTxFifoUnderflow);
    DSPI_HAL_ClearStatusFlag(base, kDspiTxFifoFillRequest);
    DSPI_HAL_ClearStatusFlag(base, kDspiRxFifoOverflow);
    DSPI_HAL_ClearStatusFlag(base, kDspiRxFifoDrainRequest);

    /************************************************************************************
     * Set up the RX DMA channel Transfer Control Descriptor (TCD)
     * Do this before filling the TX FIFO.
     * Note, if there is no remaining receive count, then bypass RX DMA set up.
     * This means we only have one byte to read of a 16-bit data word and will read this
     * in the complete transfer function.
     ***********************************************************************************/
    /* If a receive buffer is used and if rxTransferByteCnt > 0 */
    if (rxTransferByteCnt)
    {
        if (!receiveBuffer)
        {
            /* Set up this channel's control which includes enabling the DMA interrupt */
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaRxChannel,
                                   kDmaPeripheralToPeripheral,
                                   transferSizeInBytes,
                                   DSPI_HAL_GetPoprRegAddr(base), /* src is data register */
                                   (uint32_t)(&s_rxBuffIfNull), /* dest is temporary location */
                                   (uint32_t)(rxTransferByteCnt));
        }
        else
        {
            /* Set up this channel's control which includes enabling the DMA interrupt */
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaRxChannel,
                                   kDmaPeripheralToMemory,
                                   transferSizeInBytes,
                                   DSPI_HAL_GetPoprRegAddr(base), /* src is data register */
                                   (uint32_t)(receiveBuffer), /* dest is rx buffer */
                                   (uint32_t)(rxTransferByteCnt));

            /* Destination size is only 1 byte */
            DMA_DRV_SetDestTransferSize(&dspiDmaState->dmaRxChannel, 1U);
        }

        /* Enable the DMA peripheral request */
        DMA_DRV_StartChannel(&dspiDmaState->dmaRxChannel);
    }
    else if (dspiDmaState->extraByte)
    {
        /* Need to receive only one frame - extra byte by calling Rx callback function*/
        DSPI_DRV_DmaRxCallback((void *)instance, kDmaIdle);
    }

    /************************************************************************************
     * Set up the Last Command/data Word Intermediate Buffer and fill up the TX FIFO.
     ***********************************************************************************/
    /* Before sending the data, we first need to initialize the data command struct
     * Configure the data command attributes for the desired PCS, CTAR, and continuous PCS
     * which are derived from the run-time state struct
     */
    command.whichPcs = dspiDmaState->whichPcs;
    command.whichCtar = dspiDmaState->whichCtar;
    command.clearTransferCount = false; /* don't clear the transfer count */

    /************************************************************************
     * Next, set up the Last Command/data Word Intermediate Buffer before
     * filling up the TX FIFO
     * Create a 32-bit word with the final 16-bit command settings. This means
     * that EOQ = 1 and CONT = 0.
     * This 32-bit word will also be initialized with the final data byte/word
     * from the send source buffer and then the entire 32-bit word will be
     * transferred to the DSPI PUSHR.
     ************************************************************************/
    /* Declare a variable for storing the last send data (either 8- or 16-bit) */
    uint32_t lastWord = 0;

    /* If a send buffer was provided, the word comes from there. Otherwise we just send
     * a zero (initialized above).
     */
    if (sendBuffer)
    {
        /* Store the last byte from the send buffer */
        if (dspiDmaState->bitsPerFrame <= 8)
        {
            lastWord = sendBuffer[txTransferByteCnt-1]; /* Last byte */
        }
        /* Store the last two bytes the send buffer */
        else
        {
            /* If 16-bit transfers and odd transfer byte count then an extra byte was added
             * to the transfer byte count, but we cannot access more of the send buffer
             */
            if(!dspiDmaState->extraByte)
            {
                lastWord = sendBuffer[txTransferByteCnt-1] ; /* Save off the last byte */
                lastWord = lastWord << 8U; /* Shift to MSB (separate step due to MISHA) */
            }
            lastWord |= sendBuffer[txTransferByteCnt-2]; /* OR with next to last byte */
        }
    }

    /* Now, build the last command/data word intermediate buffer */
    command.isChipSelectContinuous = false; /* Always clear CONT for last data word */
    command.isEndOfQueue = true; /* Set EOQ for last data word */
    s_lastCmdData = DSPI_HAL_GetFormattedCommand(base, &command) | lastWord;
    /************************************************************************
     * Begin TX DMA channels transfer control descriptor set up.
     * 1. First, set up intermediate buffers which contain 16-bit commands.
     * 2. Set up the DMA Software Transfer Control Descriptors (STCD) for various
     *    scenarios:
     *    - Channel for intermediate buffer to TX FIFO
     *    - Channel for source buffer to intermediate buffer
     *    - STCD for scatter/gather for end of previous channel to replace
     *      intermediate buffer with last-command buffer.
     ************************************************************************/

    /************************************************************************
     * Intermediate Buffer
     * Create a 32-bit word with the 16-bit command settings. Data from
     * the send source buffer will be transferred here and then the entire
     * 32-bit word will be transferred to the DSPI PUSHR.
     * This buffer will be preloaded with the next data word in the send buffer
     ************************************************************************/
    /* restore the isChipSelectContinuous setting to the original value as it was cleared above */
    command.isChipSelectContinuous = dspiDmaState->isChipSelectContinuous;
    command.isEndOfQueue = false; /* Clear End of Queue (previously set for last cmd/data word)*/
    s_cmdData = DSPI_HAL_GetFormattedCommand(base, &command);

    /* Place the next data from the send buffer into the intermediate buffer (preload it)
     * based on whether it is one byte or two.
     */
    if (dspiDmaState->bitsPerFrame <= 8)
    {
        /* If a send buffer was provided, the word comes from there. Otherwise we just send
         * a zero (initialized above).
         */
        if (sendBuffer)
        {
            s_wordToSend = *sendBuffer;  /* queue up the next data */
            ++sendBuffer; /* increment to next data word*/
        }
        --txTransferByteCnt; /* decrement txTransferByteCnt*/
    }
    else
    {
        /* If a send buffer was provided, the word comes from there. Otherwise we just send
         * a zero (initialized above).
         */
        if (sendBuffer)
        {
            s_wordToSend = *sendBuffer;
            ++sendBuffer; /* increment to next data byte */

            /* Note, if the extraByte flag is set and we're down to the last two bytes we can still
             * do this even though we're going past the sendBuffer size. We're just reading data we
             * don't care about anyways since it is dummy data to make up for the last byte.
             */
            s_wordToSend |= (unsigned)(*sendBuffer) << 8U;
            ++sendBuffer; /* increment to next data byte */

        }
        txTransferByteCnt -= 2;  /* decrement txTransferByteCnt by 2 bytes */
    }

    s_cmdData |= s_wordToSend; /* write s_wordToSend to intermediate buffer */

    /* For Tx, DSPI need two DMA channel, one for calculate the command and data into one value
     * (dmaTxCmdChannel), and another for push the value into DSPI PUSHR register (dmaTxDataChannel).
     * The dmaTxCmdChannel DMA channel will be triggered by DSPI Tx FIFO, and the dmaTxDataChannel
     * DMA channel will be linked to calculate DMA channel and triggered by this channel also.
     */

    /* If the transfer size is less than size of one frame, only transmit the last byte that calculated */
    if (!txTransferByteCnt)
    {
        DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxDataChannel, kDmaMemoryToPeripheral,
                               4u, (uint32_t)(&s_lastCmdData),
                               DSPI_HAL_GetMasterPushrRegAddr(base), 4u);
        /* Register callback for last byte transmitting */
        DMA_DRV_RegisterCallback(&dspiDmaState->dmaTxDataChannel, DSPI_DRV_DmaTxLastCallback, (void *)instance);
    }
    else
    {
        /* Config DMA to copy data from generated cmd data to FIFO */
        if (dspiDmaState->bitsPerFrame <= 8)
        {
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxDataChannel, kDmaPeripheralToPeripheral,
                                   4u, (uint32_t)(&s_cmdData),
                                   DSPI_HAL_GetMasterPushrRegAddr(base),
                                   (uint32_t)((txTransferByteCnt) * 4));
        }
        else
        {
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxDataChannel, kDmaPeripheralToPeripheral,
                                   4u, (uint32_t)(&s_cmdData),
                                   DSPI_HAL_GetMasterPushrRegAddr(base),
                                   (uint32_t)((txTransferByteCnt) * 2));
        }
        /* Register Tx callback function */
        DMA_DRV_RegisterCallback(&dspiDmaState->dmaTxDataChannel, DSPI_DRV_DmaTxCallback, (void *)instance);

        /* Config dmaTxCmdChannel channel if send buffer is provided */
        if (sendBuffer)
        {
            dma_channel_link_config_t config;
            DMA_DRV_ConfigTransfer(&dspiDmaState->dmaTxCmdChannel, kDmaMemoryToPeripheral,
                                   1u, (uint32_t)(sendBuffer),
                                   (uint32_t)(&s_cmdData),
                                   (uint32_t)(txTransferByteCnt - transferSizeInBytes));
            if (dspiDmaState->bitsPerFrame > 8)
            {
                DMA_DRV_SetDestTransferSize(&dspiDmaState->dmaTxCmdChannel, 2U);
            }

            /* Link dmaTxCmdChannel after dmaTxDataChannel */
            config.channel1 = dspiDmaState->dmaTxCmdChannel.channel;
            config.channel2 = 0;
            config.linkType = kDmaChannelLinkChan1;
            DMA_DRV_ConfigChanLink(&dspiDmaState->dmaTxDataChannel, &config);
            /* start channel */
            DMA_DRV_StartChannel(&dspiDmaState->dmaTxCmdChannel);
        }
    }

    /* Register callback */
    DMA_DRV_RegisterCallback(&dspiDmaState->dmaRxChannel, DSPI_DRV_DmaRxCallback, (void *)instance);

    /* Enable the Receive FIFO Drain DMA Request */
    DSPI_HAL_SetRxFifoDrainDmaIntMode(base, kDspiGenerateDmaReq, true);

    /* Enable TFFF DMA request */
    DSPI_HAL_SetTxFifoFillDmaIntMode(base, kDspiGenerateDmaReq, true);

    /* Enable the DMA peripheral request */
    DMA_DRV_StartChannel(&dspiDmaState->dmaTxDataChannel);

    return kStatus_DSPI_Success;
}
コード例 #2
0
/*!
 * @brief Fill up the TX FIFO with data.
 * This function fills up the TX FIFO with initial data for start of transfers where it will
 * first clear the transfer count.  Otherwise, if the TX FIFO fill is part of an ongoing transfer
 * then do not clear the transfer count.  The param "isInitialData" is used to determine if this
 * is an initial data fill.
 * This is not a public API as it is called from other driver functions.
 */
static void DSPI_DRV_MasterFillupTxFifo(uint32_t instance)
{
    /* instantiate local variable of type dspi_master_state_t and point to global state */
    dspi_master_state_t * dspiState = (dspi_master_state_t *)g_dspiStatePtr[instance];
    SPI_Type *base = g_dspiBase[instance];
    dspi_command_config_t command;  /* create an instance of the data command struct*/
    uint32_t cmd; /* Command word to be OR'd with data word */
    uint16_t wordToSend = 0;
    /* Declare variables for storing volatile data later in the code */
    uint32_t remainingReceiveByteCount, remainingSendByteCount;

    /* Before sending the data, we first need to initialize the data command struct
     * Configure the data command attributes for the desired PCS, CTAR, and continuous PCS
     * which are derived from the run-time state struct
     */
    command.whichPcs = dspiState->whichPcs;
    command.whichCtar = dspiState->whichCtar;
    command.isChipSelectContinuous = dspiState->isChipSelectContinuous;
    command.isEndOfQueue = 0;
    command.clearTransferCount = 0;

    /* "Build" the command word. Only do this once since the commad word members don't
     * change until the last word sent (which is when the end of queue flag gets set).
     */
    cmd = DSPI_HAL_GetFormattedCommand(base, &command);

    /* Store the DSPI state struct volatile member variables into temporary
     * non-volatile variables to allow for MISRA compliant calculations
     */
    remainingSendByteCount = dspiState->remainingSendByteCount;
    remainingReceiveByteCount = dspiState->remainingReceiveByteCount;

    /* Architectural note: When developing the TX FIFO fill functionality, it was found that to
     * achieve more efficient run-time performance, it was better to first check the bits/frame
     * setting and then proceed with the FIFO fill management process, rather than to clutter the
     * FIFO fill process with continual checks of the bits/frame setting.
     */

    /* If bits/frame is greater than one byte */
    if (dspiState->bitsPerFrame > 8)
    {
        /* Fill the fifo until it is full or until the send word count is 0 or until the difference
         * between the remainingReceiveByteCount and remainingSendByteCount equals the FIFO depth.
         * The reason for checking the difference is to ensure we only send as much as the
         * RX FIFO can receive.
         * For this case where bitsPerFrame > 8, each entry in the FIFO contains 2 bytes of the
         * send data, hence the difference between the remainingReceiveByteCount and
         * remainingSendByteCount must be divided by 2 to convert this difference into a
         * 16-bit (2 byte) value.
         */
        while((DSPI_HAL_GetStatusFlag(base, kDspiTxFifoFillRequest) == 1) &&
              ((remainingReceiveByteCount - remainingSendByteCount)/2 <
                g_dspiFifoSize[instance]))
        {
            /* On the last word to be sent, set the end of queue flag in the data command struct
             * and ensure that the CONT bit in the PUSHR is also cleared even if it was cleared to
             * begin with. If CONT is set it means continuous chip select operation and to ensure
             * the chip select is de-asserted, this bit must be cleared on the last data word.
             */
            if (dspiState->remainingSendByteCount == 2)
            {
                command.isEndOfQueue = 1;
                command.isChipSelectContinuous = 0;
                cmd = DSPI_HAL_GetFormattedCommand(base, &command);

                /* If there is an extra byte to send due to an odd byte count, prepare the final
                 * wordToSend here
                 */
                if (dspiState->sendBuffer)
                {
                    if (dspiState->extraByte)
                    {
                        wordToSend = *(dspiState->sendBuffer);
                    }
                    else
                    {
                        wordToSend = *(dspiState->sendBuffer);
                        ++dspiState->sendBuffer; /* increment to next data byte */
                        wordToSend |= (unsigned)(*(dspiState->sendBuffer)) << 8U;
                    }
                }
            }
            /* For all words except the last word */
            else
            {
                /* If a send buffer was provided, the word comes from there. Otherwise we just send
                 * a zero (initialized above).
                 */
                if (dspiState->sendBuffer)
                {
                    wordToSend = *(dspiState->sendBuffer);
                    ++dspiState->sendBuffer; /* increment to next data byte */
                    wordToSend |= (unsigned)(*(dspiState->sendBuffer)) << 8U;
                    ++dspiState->sendBuffer; /* increment to next data byte */
                }
            }
            DSPI_HAL_WriteCmdDataMastermode(base, cmd|wordToSend);

            /* Try to clear the TFFF; if the TX FIFO is full this will clear */
            DSPI_HAL_ClearStatusFlag(base, kDspiTxFifoFillRequest);

            dspiState->remainingSendByteCount -= 2; /* decrement remainingSendByteCount by 2 */

            /* exit loop if send count is zero, else update local variables for next loop */
            if (dspiState->remainingSendByteCount == 0)
            {
                break;
            }
            else
            {
                /* Store the DSPI state struct volatile member variables into temporary
                 * non-volatile variables to allow for MISRA compliant calculations
                 */
                remainingSendByteCount = dspiState->remainingSendByteCount;
            }
        } /* End of TX FIFO fill while loop */
    }
    /* Optimized for bits/frame less than or equal to one byte. */
    else
    {
        /* Fill the fifo until it is full or until the send word count is 0 or until the difference
         * between the remainingReceiveByteCount and remainingSendByteCount equals the FIFO depth.
         * The reason for checking the difference is to ensure we only send as much as the
         * RX FIFO can receive.
         */
        while((DSPI_HAL_GetStatusFlag(base, kDspiTxFifoFillRequest) == 1) &&
              ((remainingReceiveByteCount - remainingSendByteCount) <
                g_dspiFifoSize[instance]))
        {
            /* On the last word to be sent, set the end of queue flag in the data command struct
             * and ensure that the CONT bit in the PUSHR is also cleared even if it was cleared to
             * begin with. If CONT is set it means continuous chip select operation and to ensure
             * the chip select is de-asserted, this bit must be cleared on the last data word.
             */
            if (dspiState->remainingSendByteCount == 1)
            {
                command.isEndOfQueue = 1;
                command.isChipSelectContinuous = 0;
                cmd = DSPI_HAL_GetFormattedCommand(base, &command);
            }

            /* If a send buffer was provided, the word comes from there. Otherwise we just send
             * a zero (initialized above).
             */
            if (dspiState->sendBuffer)
            {
                wordToSend = *(dspiState->sendBuffer);
                ++dspiState->sendBuffer; /* increment to next data word*/
            }
            DSPI_HAL_WriteCmdDataMastermode(base, cmd|wordToSend);

            /* Try to clear the TFFF; if the TX FIFO is full this will clear */
            DSPI_HAL_ClearStatusFlag(base, kDspiTxFifoFillRequest);

            --dspiState->remainingSendByteCount; /* decrement remainingSendByteCount*/

            /* exit loop if send count is zero, else update local variables for next loop */
            if (dspiState->remainingSendByteCount == 0)
            {
                break;
            }
            else
            {
                /* Store the DSPI state struct volatile member variables into temporary
                 * non-volatile variables to allow for MISRA compliant calculations
                 */
                remainingSendByteCount = dspiState->remainingSendByteCount;
            }
        } /* End of TX FIFO fill while loop */
    }
}