fsl_lpi2c_edma.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. * Copyright (c) 2015, Freescale Semiconductor, Inc.
  3. * Copyright 2016-2017 NXP
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification,
  6. * are permitted provided that the following conditions are met:
  7. *
  8. * o Redistributions of source code must retain the above copyright notice, this list
  9. * of conditions and the following disclaimer.
  10. *
  11. * o Redistributions in binary form must reproduce the above copyright notice, this
  12. * list of conditions and the following disclaimer in the documentation and/or
  13. * other materials provided with the distribution.
  14. *
  15. * o Neither the name of the copyright holder nor the names of its
  16. * contributors may be used to endorse or promote products derived from this
  17. * software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  20. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  23. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  26. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "fsl_lpi2c_edma.h"
  31. #include <stdlib.h>
  32. #include <string.h>
  33. /*******************************************************************************
  34. * Definitions
  35. ******************************************************************************/
  36. /* @brief Mask to align an address to 32 bytes. */
  37. #define ALIGN_32_MASK (0x1fU)
  38. /*! @brief Common sets of flags used by the driver. */
  39. enum _lpi2c_flag_constants
  40. {
  41. /*! All flags which are cleared by the driver upon starting a transfer. */
  42. kMasterClearFlags = kLPI2C_MasterEndOfPacketFlag | kLPI2C_MasterStopDetectFlag | kLPI2C_MasterNackDetectFlag |
  43. kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterFifoErrFlag | kLPI2C_MasterPinLowTimeoutFlag |
  44. kLPI2C_MasterDataMatchFlag,
  45. /*! IRQ sources enabled by the non-blocking transactional API. */
  46. kMasterIrqFlags = kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterTxReadyFlag | kLPI2C_MasterRxReadyFlag |
  47. kLPI2C_MasterStopDetectFlag | kLPI2C_MasterNackDetectFlag | kLPI2C_MasterPinLowTimeoutFlag |
  48. kLPI2C_MasterFifoErrFlag,
  49. /*! Errors to check for. */
  50. kMasterErrorFlags = kLPI2C_MasterNackDetectFlag | kLPI2C_MasterArbitrationLostFlag | kLPI2C_MasterFifoErrFlag |
  51. kLPI2C_MasterPinLowTimeoutFlag,
  52. /*! All flags which are cleared by the driver upon starting a transfer. */
  53. kSlaveClearFlags = kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveStopDetectFlag | kLPI2C_SlaveBitErrFlag |
  54. kLPI2C_SlaveFifoErrFlag,
  55. /*! IRQ sources enabled by the non-blocking transactional API. */
  56. kSlaveIrqFlags = kLPI2C_SlaveTxReadyFlag | kLPI2C_SlaveRxReadyFlag | kLPI2C_SlaveStopDetectFlag |
  57. kLPI2C_SlaveRepeatedStartDetectFlag | kLPI2C_SlaveFifoErrFlag | kLPI2C_SlaveBitErrFlag |
  58. kLPI2C_SlaveTransmitAckFlag | kLPI2C_SlaveAddressValidFlag,
  59. /*! Errors to check for. */
  60. kSlaveErrorFlags = kLPI2C_SlaveFifoErrFlag | kLPI2C_SlaveBitErrFlag,
  61. };
  62. /* ! @brief LPI2C master fifo commands. */
  63. enum _lpi2c_master_fifo_cmd
  64. {
  65. kTxDataCmd = LPI2C_MTDR_CMD(0x0U), /*!< Transmit DATA[7:0] */
  66. kRxDataCmd = LPI2C_MTDR_CMD(0X1U), /*!< Receive (DATA[7:0] + 1) bytes */
  67. kStopCmd = LPI2C_MTDR_CMD(0x2U), /*!< Generate STOP condition */
  68. kStartCmd = LPI2C_MTDR_CMD(0x4U), /*!< Generate(repeated) START and transmit address in DATA[[7:0] */
  69. };
  70. /*! @brief States for the state machine used by transactional APIs. */
  71. enum _lpi2c_transfer_states
  72. {
  73. kIdleState = 0,
  74. kSendCommandState,
  75. kIssueReadCommandState,
  76. kTransferDataState,
  77. kStopState,
  78. kWaitForCompletionState,
  79. };
  80. /*! @brief Typedef for interrupt handler. */
  81. typedef void (*lpi2c_isr_t)(LPI2C_Type *base, void *handle);
  82. /*******************************************************************************
  83. * Prototypes
  84. ******************************************************************************/
  85. /* Defined in fsl_lpi2c.c. */
  86. extern status_t LPI2C_CheckForBusyBus(LPI2C_Type *base);
  87. /* Defined in fsl_lpi2c.c. */
  88. extern status_t LPI2C_MasterCheckAndClearError(LPI2C_Type *base, uint32_t status);
  89. static uint32_t LPI2C_GenerateCommands(lpi2c_master_edma_handle_t *handle);
  90. static void LPI2C_MasterEDMACallback(edma_handle_t *dmaHandle, void *userData, bool isTransferDone, uint32_t tcds);
  91. /*******************************************************************************
  92. * Code
  93. ******************************************************************************/
  94. void LPI2C_MasterCreateEDMAHandle(LPI2C_Type *base,
  95. lpi2c_master_edma_handle_t *handle,
  96. edma_handle_t *rxDmaHandle,
  97. edma_handle_t *txDmaHandle,
  98. lpi2c_master_edma_transfer_callback_t callback,
  99. void *userData)
  100. {
  101. assert(handle);
  102. assert(rxDmaHandle);
  103. assert(txDmaHandle);
  104. /* Clear out the handle. */
  105. memset(handle, 0, sizeof(*handle));
  106. /* Set up the handle. For combined rx/tx DMA requests, the tx channel handle is set to the rx handle */
  107. /* in order to make the transfer API code simpler. */
  108. handle->base = base;
  109. handle->completionCallback = callback;
  110. handle->userData = userData;
  111. handle->rx = rxDmaHandle;
  112. handle->tx = FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base) ? txDmaHandle : rxDmaHandle;
  113. /* Set DMA channel completion callbacks. */
  114. EDMA_SetCallback(handle->rx, LPI2C_MasterEDMACallback, handle);
  115. if (FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  116. {
  117. EDMA_SetCallback(handle->tx, LPI2C_MasterEDMACallback, handle);
  118. }
  119. }
  120. /*!
  121. * @brief Prepares the command buffer with the sequence of commands needed to send the requested transaction.
  122. * @param handle Master DMA driver handle.
  123. * @return Number of command words.
  124. */
  125. static uint32_t LPI2C_GenerateCommands(lpi2c_master_edma_handle_t *handle)
  126. {
  127. lpi2c_master_transfer_t *xfer = &handle->transfer;
  128. uint16_t *cmd = (uint16_t *)&handle->commandBuffer;
  129. uint32_t cmdCount = 0;
  130. /* Handle no start option. */
  131. if (xfer->flags & kLPI2C_TransferNoStartFlag)
  132. {
  133. if (xfer->direction == kLPI2C_Read)
  134. {
  135. /* Need to issue read command first. */
  136. cmd[cmdCount++] = kRxDataCmd | LPI2C_MTDR_DATA(xfer->dataSize - 1);
  137. }
  138. }
  139. else
  140. {
  141. /*
  142. * Initial direction depends on whether a subaddress was provided, and of course the actual
  143. * data transfer direction.
  144. */
  145. lpi2c_direction_t direction = xfer->subaddressSize ? kLPI2C_Write : xfer->direction;
  146. /* Start command. */
  147. cmd[cmdCount++] =
  148. (uint16_t)kStartCmd | (uint16_t)((uint16_t)((uint16_t)xfer->slaveAddress << 1U) | (uint16_t)direction);
  149. /* Subaddress, MSB first. */
  150. if (xfer->subaddressSize)
  151. {
  152. uint32_t subaddressRemaining = xfer->subaddressSize;
  153. while (subaddressRemaining--)
  154. {
  155. uint8_t subaddressByte = (xfer->subaddress >> (8 * subaddressRemaining)) & 0xff;
  156. cmd[cmdCount++] = subaddressByte;
  157. }
  158. }
  159. /* Reads need special handling because we have to issue a read command and maybe a repeated start. */
  160. if ((xfer->dataSize) && (xfer->direction == kLPI2C_Read))
  161. {
  162. /* Need to send repeated start if switching directions to read. */
  163. if (direction == kLPI2C_Write)
  164. {
  165. cmd[cmdCount++] = (uint16_t)kStartCmd |
  166. (uint16_t)((uint16_t)((uint16_t)xfer->slaveAddress << 1U) | (uint16_t)kLPI2C_Read);
  167. }
  168. /* Read command. */
  169. cmd[cmdCount++] = kRxDataCmd | LPI2C_MTDR_DATA(xfer->dataSize - 1);
  170. }
  171. }
  172. return cmdCount;
  173. }
  174. status_t LPI2C_MasterTransferEDMA(LPI2C_Type *base,
  175. lpi2c_master_edma_handle_t *handle,
  176. lpi2c_master_transfer_t *transfer)
  177. {
  178. status_t result;
  179. assert(handle);
  180. assert(transfer);
  181. assert(transfer->subaddressSize <= sizeof(transfer->subaddress));
  182. /* Return busy if another transaction is in progress. */
  183. if (handle->isBusy)
  184. {
  185. return kStatus_LPI2C_Busy;
  186. }
  187. /* Return an error if the bus is already in use not by us. */
  188. result = LPI2C_CheckForBusyBus(base);
  189. if (result)
  190. {
  191. return result;
  192. }
  193. /* We're now busy. */
  194. handle->isBusy = true;
  195. /* Disable LPI2C IRQ and DMA sources while we configure stuff. */
  196. LPI2C_MasterDisableInterrupts(base, kMasterIrqFlags);
  197. LPI2C_MasterEnableDMA(base, false, false);
  198. /* Clear all flags. */
  199. LPI2C_MasterClearStatusFlags(base, kMasterClearFlags);
  200. /* Save transfer into handle. */
  201. handle->transfer = *transfer;
  202. /* Generate commands to send. */
  203. uint32_t commandCount = LPI2C_GenerateCommands(handle);
  204. /* If the user is transmitting no data with no start or stop, then just go ahead and invoke the callback. */
  205. if ((!commandCount) && (transfer->dataSize == 0))
  206. {
  207. if (handle->completionCallback)
  208. {
  209. handle->completionCallback(base, handle, kStatus_Success, handle->userData);
  210. }
  211. return kStatus_Success;
  212. }
  213. /* Reset DMA channels. */
  214. EDMA_ResetChannel(handle->rx->base, handle->rx->channel);
  215. if (FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  216. {
  217. EDMA_ResetChannel(handle->tx->base, handle->tx->channel);
  218. }
  219. /* Get a 32-byte aligned TCD pointer. */
  220. edma_tcd_t *tcd = (edma_tcd_t *)((uint32_t)(&handle->tcds[1]) & (~ALIGN_32_MASK));
  221. bool hasSendData = (transfer->direction == kLPI2C_Write) && (transfer->dataSize);
  222. bool hasReceiveData = (transfer->direction == kLPI2C_Read) && (transfer->dataSize);
  223. edma_transfer_config_t transferConfig;
  224. edma_tcd_t *linkTcd = NULL;
  225. /* Set up data transmit. */
  226. if (hasSendData)
  227. {
  228. transferConfig.srcAddr = (uint32_t)transfer->data;
  229. transferConfig.destAddr = (uint32_t)LPI2C_MasterGetTxFifoAddress(base);
  230. transferConfig.srcTransferSize = kEDMA_TransferSize1Bytes;
  231. transferConfig.destTransferSize = kEDMA_TransferSize1Bytes;
  232. transferConfig.srcOffset = sizeof(uint8_t);
  233. transferConfig.destOffset = 0;
  234. transferConfig.minorLoopBytes = sizeof(uint8_t); /* TODO optimize to fill fifo */
  235. transferConfig.majorLoopCounts = transfer->dataSize;
  236. /* Store the initially configured eDMA minor byte transfer count into the LPI2C handle */
  237. handle->nbytes = transferConfig.minorLoopBytes;
  238. if (commandCount)
  239. {
  240. /* Create a software TCD, which will be chained after the commands. */
  241. EDMA_TcdReset(tcd);
  242. EDMA_TcdSetTransferConfig(tcd, &transferConfig, NULL);
  243. EDMA_TcdEnableInterrupts(tcd, kEDMA_MajorInterruptEnable);
  244. linkTcd = tcd;
  245. }
  246. else
  247. {
  248. /* User is only transmitting data with no required commands, so this transfer can stand alone. */
  249. EDMA_SetTransferConfig(handle->tx->base, handle->tx->channel, &transferConfig, NULL);
  250. EDMA_EnableChannelInterrupts(handle->tx->base, handle->tx->channel, kEDMA_MajorInterruptEnable);
  251. }
  252. }
  253. else if (hasReceiveData)
  254. {
  255. /* Set up data receive. */
  256. transferConfig.srcAddr = (uint32_t)LPI2C_MasterGetRxFifoAddress(base);
  257. transferConfig.destAddr = (uint32_t)transfer->data;
  258. transferConfig.srcTransferSize = kEDMA_TransferSize1Bytes;
  259. transferConfig.destTransferSize = kEDMA_TransferSize1Bytes;
  260. transferConfig.srcOffset = 0;
  261. transferConfig.destOffset = sizeof(uint8_t);
  262. transferConfig.minorLoopBytes = sizeof(uint8_t); /* TODO optimize to empty fifo */
  263. transferConfig.majorLoopCounts = transfer->dataSize;
  264. /* Store the initially configured eDMA minor byte transfer count into the LPI2C handle */
  265. handle->nbytes = transferConfig.minorLoopBytes;
  266. if (FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base) || (!commandCount))
  267. {
  268. /* We can put this receive transfer on its own DMA channel. */
  269. EDMA_SetTransferConfig(handle->rx->base, handle->rx->channel, &transferConfig, NULL);
  270. EDMA_EnableChannelInterrupts(handle->rx->base, handle->rx->channel, kEDMA_MajorInterruptEnable);
  271. }
  272. else
  273. {
  274. /* For shared rx/tx DMA requests when there are commands, create a software TCD which will be */
  275. /* chained onto the commands transfer, notice that in this situation assume tx/rx uses same channel */
  276. EDMA_TcdReset(tcd);
  277. EDMA_TcdSetTransferConfig(tcd, &transferConfig, NULL);
  278. EDMA_TcdEnableInterrupts(tcd, kEDMA_MajorInterruptEnable);
  279. linkTcd = tcd;
  280. }
  281. }
  282. else
  283. {
  284. /* No data to send */
  285. }
  286. /* Set up commands transfer. */
  287. if (commandCount)
  288. {
  289. transferConfig.srcAddr = (uint32_t)handle->commandBuffer;
  290. transferConfig.destAddr = (uint32_t)LPI2C_MasterGetTxFifoAddress(base);
  291. transferConfig.srcTransferSize = kEDMA_TransferSize2Bytes;
  292. transferConfig.destTransferSize = kEDMA_TransferSize2Bytes;
  293. transferConfig.srcOffset = sizeof(uint16_t);
  294. transferConfig.destOffset = 0;
  295. transferConfig.minorLoopBytes = sizeof(uint16_t); /* TODO optimize to fill fifo */
  296. transferConfig.majorLoopCounts = commandCount;
  297. EDMA_SetTransferConfig(handle->tx->base, handle->tx->channel, &transferConfig, linkTcd);
  298. }
  299. /* Start DMA transfer. */
  300. if (hasReceiveData || !FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  301. {
  302. EDMA_StartTransfer(handle->rx);
  303. }
  304. if (hasReceiveData && !FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  305. {
  306. EDMA_EnableChannelInterrupts(handle->tx->base, handle->tx->channel, kEDMA_MajorInterruptEnable);
  307. }
  308. if ((hasSendData || commandCount) && FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  309. {
  310. EDMA_StartTransfer(handle->tx);
  311. }
  312. /* Enable DMA in both directions. This actually kicks of the transfer. */
  313. LPI2C_MasterEnableDMA(base, true, true);
  314. return result;
  315. }
  316. status_t LPI2C_MasterTransferGetCountEDMA(LPI2C_Type *base, lpi2c_master_edma_handle_t *handle, size_t *count)
  317. {
  318. assert(handle);
  319. if (!count)
  320. {
  321. return kStatus_InvalidArgument;
  322. }
  323. /* Catch when there is not an active transfer. */
  324. if (!handle->isBusy)
  325. {
  326. *count = 0;
  327. return kStatus_NoTransferInProgress;
  328. }
  329. uint32_t remaining = handle->transfer.dataSize;
  330. /* If the DMA is still on a commands transfer that chains to the actual data transfer, */
  331. /* we do nothing and return the number of transferred bytes as zero. */
  332. if (EDMA_GetNextTCDAddress(handle->tx) == 0)
  333. {
  334. if (handle->transfer.direction == kLPI2C_Write)
  335. {
  336. remaining =
  337. (uint32_t)handle->nbytes * EDMA_GetRemainingMajorLoopCount(handle->tx->base, handle->tx->channel);
  338. }
  339. else
  340. {
  341. remaining =
  342. (uint32_t)handle->nbytes * EDMA_GetRemainingMajorLoopCount(handle->rx->base, handle->rx->channel);
  343. }
  344. }
  345. *count = handle->transfer.dataSize - remaining;
  346. return kStatus_Success;
  347. }
  348. status_t LPI2C_MasterTransferAbortEDMA(LPI2C_Type *base, lpi2c_master_edma_handle_t *handle)
  349. {
  350. /* Catch when there is not an active transfer. */
  351. if (!handle->isBusy)
  352. {
  353. return kStatus_LPI2C_Idle;
  354. }
  355. /* Terminate DMA transfers. */
  356. EDMA_AbortTransfer(handle->rx);
  357. if (FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  358. {
  359. EDMA_AbortTransfer(handle->tx);
  360. }
  361. /* Reset fifos. */
  362. base->MCR |= LPI2C_MCR_RRF_MASK | LPI2C_MCR_RTF_MASK;
  363. /* Send a stop command to finalize the transfer. */
  364. base->MTDR = kStopCmd;
  365. /* Reset handle. */
  366. handle->isBusy = false;
  367. return kStatus_Success;
  368. }
  369. /*!
  370. * @brief DMA completion callback.
  371. * @param dmaHandle DMA channel handle for the channel that completed.
  372. * @param userData User data associated with the channel handle. For this callback, the user data is the
  373. * LPI2C DMA driver handle.
  374. * @param isTransferDone Whether the DMA transfer has completed.
  375. * @param tcds Number of TCDs that completed.
  376. */
  377. static void LPI2C_MasterEDMACallback(edma_handle_t *dmaHandle, void *userData, bool isTransferDone, uint32_t tcds)
  378. {
  379. lpi2c_master_edma_handle_t *handle = (lpi2c_master_edma_handle_t *)userData;
  380. bool hasReceiveData = (handle->transfer.direction == kLPI2C_Read) && (handle->transfer.dataSize);
  381. if (hasReceiveData && !FSL_FEATURE_LPI2C_HAS_SEPARATE_DMA_RX_TX_REQn(base))
  382. {
  383. if (EDMA_GetNextTCDAddress(handle->tx) != 0)
  384. {
  385. LPI2C_MasterEnableDMA(handle->base, false, true);
  386. }
  387. }
  388. if (!handle)
  389. {
  390. return;
  391. }
  392. /* Check for errors. */
  393. status_t result = LPI2C_MasterCheckAndClearError(handle->base, LPI2C_MasterGetStatusFlags(handle->base));
  394. /* Done with this transaction. */
  395. handle->isBusy = false;
  396. if (!(handle->transfer.flags & kLPI2C_TransferNoStopFlag))
  397. {
  398. /* Send a stop command to finalize the transfer. */
  399. handle->base->MTDR = kStopCmd;
  400. }
  401. /* Invoke callback. */
  402. if (handle->completionCallback)
  403. {
  404. handle->completionCallback(handle->base, handle, result, handle->userData);
  405. }
  406. }