xref: /btstack/port/stm32-f4discovery-usb/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sd.c (revision a8f7f3fcbcd51f8d2e92aca076b6a9f812db358c)
1 /**
2   ******************************************************************************
3   * @file    stm32f4xx_hal_sd.c
4   * @author  MCD Application Team
5   * @brief   SD card HAL module driver.
6   *          This file provides firmware functions to manage the following
7   *          functionalities of the Secure Digital (SD) peripheral:
8   *           + Initialization and de-initialization functions
9   *           + IO operation functions
10   *           + Peripheral Control functions
11   *           + Peripheral State functions
12   *
13   @verbatim
14   ==============================================================================
15                         ##### How to use this driver #####
16   ==============================================================================
17   [..]
18     This driver implements a high level communication layer for read and write from/to
19     this memory. The needed STM32 hardware resources (SDIO and GPIO) are performed by
20     the user in HAL_SD_MspInit() function (MSP layer).
21     Basically, the MSP layer configuration should be the same as we provide in the
22     examples.
23     You can easily tailor this configuration according to hardware resources.
24 
25   [..]
26     This driver is a generic layered driver for SDIO memories which uses the HAL
27     SDIO driver functions to interface with SD and uSD cards devices.
28     It is used as follows:
29 
30     (#)Initialize the SDIO low level resources by implementing the HAL_SD_MspInit() API:
31         (##) Enable the SDIO interface clock using __HAL_RCC_SDIO_CLK_ENABLE();
32         (##) SDIO pins configuration for SD card
33             (+++) Enable the clock for the SDIO GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE();
34             (+++) Configure these SDIO pins as alternate function pull-up using HAL_GPIO_Init()
35                   and according to your pin assignment;
36         (##) DMA configuration if you need to use DMA process (HAL_SD_ReadBlocks_DMA()
37              and HAL_SD_WriteBlocks_DMA() APIs).
38             (+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE();
39             (+++) Configure the DMA using the function HAL_DMA_Init() with predeclared and filled.
40         (##) NVIC configuration if you need to use interrupt process when using DMA transfer.
41             (+++) Configure the SDIO and DMA interrupt priorities using functions
42                   HAL_NVIC_SetPriority(); DMA priority is superior to SDIO's priority
43             (+++) Enable the NVIC DMA and SDIO IRQs using function HAL_NVIC_EnableIRQ()
44             (+++) SDIO interrupts are managed using the macros __HAL_SD_ENABLE_IT()
45                   and __HAL_SD_DISABLE_IT() inside the communication process.
46             (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_GET_IT()
47                   and __HAL_SD_CLEAR_IT()
48         (##) NVIC configuration if you need to use interrupt process (HAL_SD_ReadBlocks_IT()
49              and HAL_SD_WriteBlocks_IT() APIs).
50             (+++) Configure the SDIO interrupt priorities using function HAL_NVIC_SetPriority();
51             (+++) Enable the NVIC SDIO IRQs using function HAL_NVIC_EnableIRQ()
52             (+++) SDIO interrupts are managed using the macros __HAL_SD_ENABLE_IT()
53                   and __HAL_SD_DISABLE_IT() inside the communication process.
54             (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_GET_IT()
55                   and __HAL_SD_CLEAR_IT()
56     (#) At this stage, you can perform SD read/write/erase operations after SD card initialization
57 
58 
59   *** SD Card Initialization and configuration ***
60   ================================================
61   [..]
62     To initialize the SD Card, use the HAL_SD_Init() function. It Initializes
63     SDIO Peripheral(STM32 side) and the SD Card, and put it into StandBy State (Ready for data transfer).
64     This function provide the following operations:
65 
66     (#) Apply the SD Card initialization process at 400KHz and check the SD Card
67         type (Standard Capacity or High Capacity). You can change or adapt this
68         frequency by adjusting the "ClockDiv" field.
69         The SD Card frequency (SDIO_CK) is computed as follows:
70 
71            SDIO_CK = SDIOCLK / (ClockDiv + 2)
72 
73         In initialization mode and according to the SD Card standard,
74         make sure that the SDIO_CK frequency doesn't exceed 400KHz.
75 
76         This phase of initialization is done through SDIO_Init() and
77         SDIO_PowerState_ON() SDIO low level APIs.
78 
79     (#) Initialize the SD card. The API used is HAL_SD_InitCard().
80         This phase allows the card initialization and identification
81         and check the SD Card type (Standard Capacity or High Capacity)
82         The initialization flow is compatible with SD standard.
83 
84         This API (HAL_SD_InitCard()) could be used also to reinitialize the card in case
85         of plug-off plug-in.
86 
87     (#) Configure the SD Card Data transfer frequency. You can change or adapt this
88         frequency by adjusting the "ClockDiv" field.
89         In transfer mode and according to the SD Card standard, make sure that the
90         SDIO_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch.
91         To be able to use a frequency higher than 24MHz, you should use the SDIO
92         peripheral in bypass mode. Refer to the corresponding reference manual
93         for more details.
94 
95     (#) Select the corresponding SD Card according to the address read with the step 2.
96 
97     (#) Configure the SD Card in wide bus mode: 4-bits data.
98 
99   *** SD Card Read operation ***
100   ==============================
101   [..]
102     (+) You can read from SD card in polling mode by using function HAL_SD_ReadBlocks().
103         This function support only 512-bytes block length (the block size should be
104         chosen as 512 bytes).
105         You can choose either one block read operation or multiple block read operation
106         by adjusting the "NumberOfBlocks" parameter.
107         After this, you have to ensure that the transfer is done correctly. The check is done
108         through HAL_SD_GetCardState() function for SD card state.
109 
110     (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA().
111         This function support only 512-bytes block length (the block size should be
112         chosen as 512 bytes).
113         You can choose either one block read operation or multiple block read operation
114         by adjusting the "NumberOfBlocks" parameter.
115         After this, you have to ensure that the transfer is done correctly. The check is done
116         through HAL_SD_GetCardState() function for SD card state.
117         You could also check the DMA transfer process through the SD Rx interrupt event.
118 
119     (+) You can read from SD card in Interrupt mode by using function HAL_SD_ReadBlocks_IT().
120         This function support only 512-bytes block length (the block size should be
121         chosen as 512 bytes).
122         You can choose either one block read operation or multiple block read operation
123         by adjusting the "NumberOfBlocks" parameter.
124         After this, you have to ensure that the transfer is done correctly. The check is done
125         through HAL_SD_GetCardState() function for SD card state.
126         You could also check the IT transfer process through the SD Rx interrupt event.
127 
128   *** SD Card Write operation ***
129   ===============================
130   [..]
131     (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks().
132         This function support only 512-bytes block length (the block size should be
133         chosen as 512 bytes).
134         You can choose either one block read operation or multiple block read operation
135         by adjusting the "NumberOfBlocks" parameter.
136         After this, you have to ensure that the transfer is done correctly. The check is done
137         through HAL_SD_GetCardState() function for SD card state.
138 
139     (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA().
140         This function support only 512-bytes block length (the block size should be
141         chosen as 512 bytes).
142         You can choose either one block read operation or multiple block read operation
143         by adjusting the "NumberOfBlocks" parameter.
144         After this, you have to ensure that the transfer is done correctly. The check is done
145         through HAL_SD_GetCardState() function for SD card state.
146         You could also check the DMA transfer process through the SD Tx interrupt event.
147 
148     (+) You can write to SD card in Interrupt mode by using function HAL_SD_WriteBlocks_IT().
149         This function support only 512-bytes block length (the block size should be
150         chosen as 512 bytes).
151         You can choose either one block read operation or multiple block read operation
152         by adjusting the "NumberOfBlocks" parameter.
153         After this, you have to ensure that the transfer is done correctly. The check is done
154         through HAL_SD_GetCardState() function for SD card state.
155         You could also check the IT transfer process through the SD Tx interrupt event.
156 
157   *** SD card status ***
158   ======================
159   [..]
160     (+) The SD Status contains status bits that are related to the SD Memory
161         Card proprietary features. To get SD card status use the HAL_SD_GetCardStatus().
162 
163   *** SD card information ***
164   ===========================
165   [..]
166     (+) To get SD card information, you can use the function HAL_SD_GetCardInfo().
167         It returns useful information about the SD card such as block size, card type,
168         block number ...
169 
170   *** SD card CSD register ***
171   ============================
172     (+) The HAL_SD_GetCardCSD() API allows to get the parameters of the CSD register.
173         Some of the CSD parameters are useful for card initialization and identification.
174 
175   *** SD card CID register ***
176   ============================
177     (+) The HAL_SD_GetCardCID() API allows to get the parameters of the CID register.
178         Some of the CSD parameters are useful for card initialization and identification.
179 
180   *** SD HAL driver macros list ***
181   ==================================
182   [..]
183     Below the list of most used macros in SD HAL driver.
184 
185     (+) __HAL_SD_ENABLE : Enable the SD device
186     (+) __HAL_SD_DISABLE : Disable the SD device
187     (+) __HAL_SD_DMA_ENABLE: Enable the SDIO DMA transfer
188     (+) __HAL_SD_DMA_DISABLE: Disable the SDIO DMA transfer
189     (+) __HAL_SD_ENABLE_IT: Enable the SD device interrupt
190     (+) __HAL_SD_DISABLE_IT: Disable the SD device interrupt
191     (+) __HAL_SD_GET_FLAG:Check whether the specified SD flag is set or not
192     (+) __HAL_SD_CLEAR_FLAG: Clear the SD's pending flags
193 
194     (@) You can refer to the SD HAL driver header file for more useful macros
195 
196   *** Callback registration ***
197   =============================================
198   [..]
199     The compilation define USE_HAL_SD_REGISTER_CALLBACKS when set to 1
200     allows the user to configure dynamically the driver callbacks.
201 
202     Use Functions @ref HAL_SD_RegisterCallback() to register a user callback,
203     it allows to register following callbacks:
204       (+) TxCpltCallback : callback when a transmission transfer is completed.
205       (+) RxCpltCallback : callback when a reception transfer is completed.
206       (+) ErrorCallback : callback when error occurs.
207       (+) AbortCpltCallback : callback when abort is completed.
208       (+) MspInitCallback    : SD MspInit.
209       (+) MspDeInitCallback  : SD MspDeInit.
210     This function takes as parameters the HAL peripheral handle, the Callback ID
211     and a pointer to the user callback function.
212 
213     Use function @ref HAL_SD_UnRegisterCallback() to reset a callback to the default
214     weak (surcharged) function. It allows to reset following callbacks:
215       (+) TxCpltCallback : callback when a transmission transfer is completed.
216       (+) RxCpltCallback : callback when a reception transfer is completed.
217       (+) ErrorCallback : callback when error occurs.
218       (+) AbortCpltCallback : callback when abort is completed.
219       (+) MspInitCallback    : SD MspInit.
220       (+) MspDeInitCallback  : SD MspDeInit.
221     This function) takes as parameters the HAL peripheral handle and the Callback ID.
222 
223     By default, after the @ref HAL_SD_Init and if the state is HAL_SD_STATE_RESET
224     all callbacks are reset to the corresponding legacy weak (surcharged) functions.
225     Exception done for MspInit and MspDeInit callbacks that are respectively
226     reset to the legacy weak (surcharged) functions in the @ref HAL_SD_Init
227     and @ref  HAL_SD_DeInit only when these callbacks are null (not registered beforehand).
228     If not, MspInit or MspDeInit are not null, the @ref HAL_SD_Init and @ref HAL_SD_DeInit
229     keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
230 
231     Callbacks can be registered/unregistered in READY state only.
232     Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered
233     in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used
234     during the Init/DeInit.
235     In that case first register the MspInit/MspDeInit user callbacks
236     using @ref HAL_SD_RegisterCallback before calling @ref HAL_SD_DeInit
237     or @ref HAL_SD_Init function.
238 
239     When The compilation define USE_HAL_SD_REGISTER_CALLBACKS is set to 0 or
240     not defined, the callback registering feature is not available
241     and weak (surcharged) callbacks are used.
242 
243   @endverbatim
244   ******************************************************************************
245   * @attention
246   *
247   * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics.
248   * All rights reserved.</center></h2>
249   *
250   * This software component is licensed by ST under BSD 3-Clause license,
251   * the "License"; You may not use this file except in compliance with the
252   * License. You may obtain a copy of the License at:
253   *                       opensource.org/licenses/BSD-3-Clause
254   *
255   ******************************************************************************
256   */
257 
258 /* Includes ------------------------------------------------------------------*/
259 #include "stm32f4xx_hal.h"
260 
261 #if defined(SDIO)
262 
263 /** @addtogroup STM32F4xx_HAL_Driver
264   * @{
265   */
266 
267 /** @addtogroup SD
268   * @{
269   */
270 
271 #ifdef HAL_SD_MODULE_ENABLED
272 
273 /* Private typedef -----------------------------------------------------------*/
274 /* Private define ------------------------------------------------------------*/
275 /** @addtogroup SD_Private_Defines
276   * @{
277   */
278 
279 /**
280   * @}
281   */
282 
283 /* Private macro -------------------------------------------------------------*/
284 /* Private variables ---------------------------------------------------------*/
285 /* Private function prototypes -----------------------------------------------*/
286 /* Private functions ---------------------------------------------------------*/
287 /** @defgroup SD_Private_Functions SD Private Functions
288   * @{
289   */
290 static uint32_t SD_InitCard(SD_HandleTypeDef *hsd);
291 static uint32_t SD_PowerON(SD_HandleTypeDef *hsd);
292 static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus);
293 static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus);
294 static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd);
295 static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd);
296 static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR);
297 static void SD_PowerOFF(SD_HandleTypeDef *hsd);
298 static void SD_Write_IT(SD_HandleTypeDef *hsd);
299 static void SD_Read_IT(SD_HandleTypeDef *hsd);
300 static void SD_DMATransmitCplt(DMA_HandleTypeDef *hdma);
301 static void SD_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
302 static void SD_DMAError(DMA_HandleTypeDef *hdma);
303 static void SD_DMATxAbort(DMA_HandleTypeDef *hdma);
304 static void SD_DMARxAbort(DMA_HandleTypeDef *hdma);
305 /**
306   * @}
307   */
308 
309 /* Exported functions --------------------------------------------------------*/
310 /** @addtogroup SD_Exported_Functions
311   * @{
312   */
313 
314 /** @addtogroup SD_Exported_Functions_Group1
315  *  @brief   Initialization and de-initialization functions
316  *
317 @verbatim
318   ==============================================================================
319           ##### Initialization and de-initialization functions #####
320   ==============================================================================
321   [..]
322     This section provides functions allowing to initialize/de-initialize the SD
323     card device to be ready for use.
324 
325 @endverbatim
326   * @{
327   */
328 
329 /**
330   * @brief  Initializes the SD according to the specified parameters in the
331             SD_HandleTypeDef and create the associated handle.
332   * @param  hsd: Pointer to the SD handle
333   * @retval HAL status
334   */
HAL_SD_Init(SD_HandleTypeDef * hsd)335 HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd)
336 {
337   /* Check the SD handle allocation */
338   if(hsd == NULL)
339   {
340     return HAL_ERROR;
341   }
342 
343   /* Check the parameters */
344   assert_param(IS_SDIO_ALL_INSTANCE(hsd->Instance));
345   assert_param(IS_SDIO_CLOCK_EDGE(hsd->Init.ClockEdge));
346   assert_param(IS_SDIO_CLOCK_BYPASS(hsd->Init.ClockBypass));
347   assert_param(IS_SDIO_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave));
348   assert_param(IS_SDIO_BUS_WIDE(hsd->Init.BusWide));
349   assert_param(IS_SDIO_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl));
350   assert_param(IS_SDIO_CLKDIV(hsd->Init.ClockDiv));
351 
352   if(hsd->State == HAL_SD_STATE_RESET)
353   {
354     /* Allocate lock resource and initialize it */
355     hsd->Lock = HAL_UNLOCKED;
356 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
357     /* Reset Callback pointers in HAL_SD_STATE_RESET only */
358     hsd->TxCpltCallback    = HAL_SD_TxCpltCallback;
359     hsd->RxCpltCallback    = HAL_SD_RxCpltCallback;
360     hsd->ErrorCallback     = HAL_SD_ErrorCallback;
361     hsd->AbortCpltCallback = HAL_SD_AbortCallback;
362 
363     if(hsd->MspInitCallback == NULL)
364     {
365       hsd->MspInitCallback = HAL_SD_MspInit;
366     }
367 
368     /* Init the low level hardware */
369     hsd->MspInitCallback(hsd);
370 #else
371     /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
372     HAL_SD_MspInit(hsd);
373 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
374   }
375 
376   hsd->State = HAL_SD_STATE_BUSY;
377 
378   /* Initialize the Card parameters */
379   if (HAL_SD_InitCard(hsd) != HAL_OK)
380   {
381     return HAL_ERROR;
382   }
383 
384   /* Initialize the error code */
385   hsd->ErrorCode = HAL_SD_ERROR_NONE;
386 
387   /* Initialize the SD operation */
388   hsd->Context = SD_CONTEXT_NONE;
389 
390   /* Initialize the SD state */
391   hsd->State = HAL_SD_STATE_READY;
392 
393   return HAL_OK;
394 }
395 
396 /**
397   * @brief  Initializes the SD Card.
398   * @param  hsd: Pointer to SD handle
399   * @note   This function initializes the SD card. It could be used when a card
400             re-initialization is needed.
401   * @retval HAL status
402   */
HAL_SD_InitCard(SD_HandleTypeDef * hsd)403 HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd)
404 {
405   uint32_t errorstate;
406   HAL_StatusTypeDef status;
407   SD_InitTypeDef Init;
408 
409   /* Default SDIO peripheral configuration for SD card initialization */
410   Init.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
411   Init.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
412   Init.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_DISABLE;
413   Init.BusWide             = SDIO_BUS_WIDE_1B;
414   Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
415   Init.ClockDiv            = SDIO_INIT_CLK_DIV;
416 
417   /* Initialize SDIO peripheral interface with default configuration */
418   status = SDIO_Init(hsd->Instance, Init);
419   if(status != HAL_OK)
420   {
421     return HAL_ERROR;
422   }
423 
424   /* Disable SDIO Clock */
425   __HAL_SD_DISABLE(hsd);
426 
427   /* Set Power State to ON */
428   (void)SDIO_PowerState_ON(hsd->Instance);
429 
430   /* Enable SDIO Clock */
431   __HAL_SD_ENABLE(hsd);
432 
433   /* Identify card operating voltage */
434   errorstate = SD_PowerON(hsd);
435   if(errorstate != HAL_SD_ERROR_NONE)
436   {
437     hsd->State = HAL_SD_STATE_READY;
438     hsd->ErrorCode |= errorstate;
439     return HAL_ERROR;
440   }
441 
442   /* Card initialization */
443   errorstate = SD_InitCard(hsd);
444   if(errorstate != HAL_SD_ERROR_NONE)
445   {
446     hsd->State = HAL_SD_STATE_READY;
447     hsd->ErrorCode |= errorstate;
448     return HAL_ERROR;
449   }
450 
451   return HAL_OK;
452 }
453 
454 /**
455   * @brief  De-Initializes the SD card.
456   * @param  hsd: Pointer to SD handle
457   * @retval HAL status
458   */
HAL_SD_DeInit(SD_HandleTypeDef * hsd)459 HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd)
460 {
461   /* Check the SD handle allocation */
462   if(hsd == NULL)
463   {
464     return HAL_ERROR;
465   }
466 
467   /* Check the parameters */
468   assert_param(IS_SDIO_ALL_INSTANCE(hsd->Instance));
469 
470   hsd->State = HAL_SD_STATE_BUSY;
471 
472   /* Set SD power state to off */
473   SD_PowerOFF(hsd);
474 
475 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
476   if(hsd->MspDeInitCallback == NULL)
477   {
478     hsd->MspDeInitCallback = HAL_SD_MspDeInit;
479   }
480 
481   /* DeInit the low level hardware */
482   hsd->MspDeInitCallback(hsd);
483 #else
484   /* De-Initialize the MSP layer */
485   HAL_SD_MspDeInit(hsd);
486 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
487 
488   hsd->ErrorCode = HAL_SD_ERROR_NONE;
489   hsd->State = HAL_SD_STATE_RESET;
490 
491   return HAL_OK;
492 }
493 
494 
495 /**
496   * @brief  Initializes the SD MSP.
497   * @param  hsd: Pointer to SD handle
498   * @retval None
499   */
HAL_SD_MspInit(SD_HandleTypeDef * hsd)500 __weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
501 {
502   /* Prevent unused argument(s) compilation warning */
503   UNUSED(hsd);
504 
505   /* NOTE : This function should not be modified, when the callback is needed,
506             the HAL_SD_MspInit could be implemented in the user file
507    */
508 }
509 
510 /**
511   * @brief  De-Initialize SD MSP.
512   * @param  hsd: Pointer to SD handle
513   * @retval None
514   */
HAL_SD_MspDeInit(SD_HandleTypeDef * hsd)515 __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd)
516 {
517   /* Prevent unused argument(s) compilation warning */
518   UNUSED(hsd);
519 
520   /* NOTE : This function should not be modified, when the callback is needed,
521             the HAL_SD_MspDeInit could be implemented in the user file
522    */
523 }
524 
525 /**
526   * @}
527   */
528 
529 /** @addtogroup SD_Exported_Functions_Group2
530  *  @brief   Data transfer functions
531  *
532 @verbatim
533   ==============================================================================
534                         ##### IO operation functions #####
535   ==============================================================================
536   [..]
537     This subsection provides a set of functions allowing to manage the data
538     transfer from/to SD card.
539 
540 @endverbatim
541   * @{
542   */
543 
544 /**
545   * @brief  Reads block(s) from a specified address in a card. The Data transfer
546   *         is managed by polling mode.
547   * @note   This API should be followed by a check on the card state through
548   *         HAL_SD_GetCardState().
549   * @param  hsd: Pointer to SD handle
550   * @param  pData: pointer to the buffer that will contain the received data
551   * @param  BlockAdd: Block Address from where data is to be read
552   * @param  NumberOfBlocks: Number of SD blocks to read
553   * @param  Timeout: Specify timeout value
554   * @retval HAL status
555   */
HAL_SD_ReadBlocks(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks,uint32_t Timeout)556 HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout)
557 {
558   SDIO_DataInitTypeDef config;
559   uint32_t errorstate;
560   uint32_t tickstart = HAL_GetTick();
561   uint32_t count, data, dataremaining;
562   uint32_t add = BlockAdd;
563   uint8_t *tempbuff = pData;
564 
565   if(NULL == pData)
566   {
567     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
568     return HAL_ERROR;
569   }
570 
571   if(hsd->State == HAL_SD_STATE_READY)
572   {
573     hsd->ErrorCode = HAL_SD_ERROR_NONE;
574 
575     if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
576     {
577       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
578       return HAL_ERROR;
579     }
580 
581     hsd->State = HAL_SD_STATE_BUSY;
582 
583     /* Initialize data control register */
584     hsd->Instance->DCTRL = 0U;
585 
586     if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
587     {
588       add *= 512U;
589     }
590 
591     /* Set Block Size for Card */
592     errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
593     if(errorstate != HAL_SD_ERROR_NONE)
594     {
595       /* Clear all the static flags */
596       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
597       hsd->ErrorCode |= errorstate;
598       hsd->State = HAL_SD_STATE_READY;
599       return HAL_ERROR;
600     }
601 
602     /* Configure the SD DPSM (Data Path State Machine) */
603     config.DataTimeOut   = SDMMC_DATATIMEOUT;
604     config.DataLength    = NumberOfBlocks * BLOCKSIZE;
605     config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
606     config.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
607     config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
608     config.DPSM          = SDIO_DPSM_ENABLE;
609     (void)SDIO_ConfigData(hsd->Instance, &config);
610 
611     /* Read block(s) in polling mode */
612     if(NumberOfBlocks > 1U)
613     {
614       hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK;
615 
616       /* Read Multi Block command */
617       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
618     }
619     else
620     {
621       hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK;
622 
623       /* Read Single Block command */
624       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
625     }
626     if(errorstate != HAL_SD_ERROR_NONE)
627     {
628       /* Clear all the static flags */
629       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
630       hsd->ErrorCode |= errorstate;
631       hsd->State = HAL_SD_STATE_READY;
632       hsd->Context = SD_CONTEXT_NONE;
633       return HAL_ERROR;
634     }
635 
636     /* Poll on SDIO flags */
637     dataremaining = config.DataLength;
638 #if defined(SDIO_STA_STBITERR)
639     while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR))
640 #else /* SDIO_STA_STBITERR not defined */
641     while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND))
642 #endif /* SDIO_STA_STBITERR */
643     {
644       if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF) && (dataremaining > 0U))
645       {
646         /* Read data from SDIO Rx FIFO */
647         for(count = 0U; count < 8U; count++)
648         {
649           data = SDIO_ReadFIFO(hsd->Instance);
650           *tempbuff = (uint8_t)(data & 0xFFU);
651           tempbuff++;
652           dataremaining--;
653           *tempbuff = (uint8_t)((data >> 8U) & 0xFFU);
654           tempbuff++;
655           dataremaining--;
656           *tempbuff = (uint8_t)((data >> 16U) & 0xFFU);
657           tempbuff++;
658           dataremaining--;
659           *tempbuff = (uint8_t)((data >> 24U) & 0xFFU);
660           tempbuff++;
661           dataremaining--;
662         }
663       }
664 
665       if(((HAL_GetTick()-tickstart) >=  Timeout) || (Timeout == 0U))
666       {
667         /* Clear all the static flags */
668         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
669         hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT;
670         hsd->State= HAL_SD_STATE_READY;
671         hsd->Context = SD_CONTEXT_NONE;
672         return HAL_TIMEOUT;
673       }
674     }
675 
676     /* Send stop transmission command in case of multiblock read */
677     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U))
678     {
679       if(hsd->SdCard.CardType != CARD_SECURED)
680       {
681         /* Send stop transmission command */
682         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
683         if(errorstate != HAL_SD_ERROR_NONE)
684         {
685           /* Clear all the static flags */
686           __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
687           hsd->ErrorCode |= errorstate;
688           hsd->State = HAL_SD_STATE_READY;
689           hsd->Context = SD_CONTEXT_NONE;
690           return HAL_ERROR;
691         }
692       }
693     }
694 
695     /* Get error state */
696     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
697     {
698       /* Clear all the static flags */
699       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
700       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
701       hsd->State = HAL_SD_STATE_READY;
702       hsd->Context = SD_CONTEXT_NONE;
703       return HAL_ERROR;
704     }
705     else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
706     {
707       /* Clear all the static flags */
708       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
709       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
710       hsd->State = HAL_SD_STATE_READY;
711       hsd->Context = SD_CONTEXT_NONE;
712       return HAL_ERROR;
713     }
714     else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
715     {
716       /* Clear all the static flags */
717       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
718       hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN;
719       hsd->State = HAL_SD_STATE_READY;
720       hsd->Context = SD_CONTEXT_NONE;
721       return HAL_ERROR;
722     }
723     else
724     {
725       /* Nothing to do */
726     }
727 
728     /* Empty FIFO if there is still any data */
729     while ((__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (dataremaining > 0U))
730     {
731       data = SDIO_ReadFIFO(hsd->Instance);
732       *tempbuff = (uint8_t)(data & 0xFFU);
733       tempbuff++;
734       dataremaining--;
735       *tempbuff = (uint8_t)((data >> 8U) & 0xFFU);
736       tempbuff++;
737       dataremaining--;
738       *tempbuff = (uint8_t)((data >> 16U) & 0xFFU);
739       tempbuff++;
740       dataremaining--;
741       *tempbuff = (uint8_t)((data >> 24U) & 0xFFU);
742       tempbuff++;
743       dataremaining--;
744 
745       if(((HAL_GetTick()-tickstart) >=  Timeout) || (Timeout == 0U))
746       {
747         /* Clear all the static flags */
748         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
749         hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT;
750         hsd->State= HAL_SD_STATE_READY;
751         hsd->Context = SD_CONTEXT_NONE;
752         return HAL_ERROR;
753       }
754     }
755 
756     /* Clear all the static flags */
757     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
758 
759     hsd->State = HAL_SD_STATE_READY;
760 
761     return HAL_OK;
762   }
763   else
764   {
765     hsd->ErrorCode |= HAL_SD_ERROR_BUSY;
766     return HAL_ERROR;
767   }
768 }
769 
770 /**
771   * @brief  Allows to write block(s) to a specified address in a card. The Data
772   *         transfer is managed by polling mode.
773   * @note   This API should be followed by a check on the card state through
774   *         HAL_SD_GetCardState().
775   * @param  hsd: Pointer to SD handle
776   * @param  pData: pointer to the buffer that will contain the data to transmit
777   * @param  BlockAdd: Block Address where data will be written
778   * @param  NumberOfBlocks: Number of SD blocks to write
779   * @param  Timeout: Specify timeout value
780   * @retval HAL status
781   */
HAL_SD_WriteBlocks(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks,uint32_t Timeout)782 HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout)
783 {
784   SDIO_DataInitTypeDef config;
785   uint32_t errorstate;
786   uint32_t tickstart = HAL_GetTick();
787   uint32_t count, data, dataremaining;
788   uint32_t add = BlockAdd;
789   uint8_t *tempbuff = pData;
790 
791   if(NULL == pData)
792   {
793     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
794     return HAL_ERROR;
795   }
796 
797   if(hsd->State == HAL_SD_STATE_READY)
798   {
799     hsd->ErrorCode = HAL_SD_ERROR_NONE;
800 
801     if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
802     {
803       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
804       return HAL_ERROR;
805     }
806 
807     hsd->State = HAL_SD_STATE_BUSY;
808 
809     /* Initialize data control register */
810     hsd->Instance->DCTRL = 0U;
811 
812     if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
813     {
814       add *= 512U;
815     }
816 
817     /* Set Block Size for Card */
818     errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
819     if(errorstate != HAL_SD_ERROR_NONE)
820     {
821       /* Clear all the static flags */
822       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
823       hsd->ErrorCode |= errorstate;
824       hsd->State = HAL_SD_STATE_READY;
825       return HAL_ERROR;
826     }
827 
828     /* Configure the SD DPSM (Data Path State Machine) */
829     config.DataTimeOut   = SDMMC_DATATIMEOUT;
830     config.DataLength    = NumberOfBlocks * BLOCKSIZE;
831     config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
832     config.TransferDir   = SDIO_TRANSFER_DIR_TO_CARD;
833     config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
834     config.DPSM          = SDIO_DPSM_ENABLE;
835     (void)SDIO_ConfigData(hsd->Instance, &config);
836 
837     /* Write Blocks in Polling mode */
838     if(NumberOfBlocks > 1U)
839     {
840       hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK;
841 
842       /* Write Multi Block command */
843       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
844     }
845     else
846     {
847       hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK;
848 
849       /* Write Single Block command */
850       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
851     }
852     if(errorstate != HAL_SD_ERROR_NONE)
853     {
854       /* Clear all the static flags */
855       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
856       hsd->ErrorCode |= errorstate;
857       hsd->State = HAL_SD_STATE_READY;
858       hsd->Context = SD_CONTEXT_NONE;
859       return HAL_ERROR;
860     }
861 
862     /* Write block(s) in polling mode */
863     dataremaining = config.DataLength;
864 #if defined(SDIO_STA_STBITERR)
865     while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR))
866 #else /* SDIO_STA_STBITERR not defined */
867     while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND))
868 #endif /* SDIO_STA_STBITERR */
869     {
870       if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE) && (dataremaining > 0U))
871       {
872         /* Write data to SDIO Tx FIFO */
873         for(count = 0U; count < 8U; count++)
874         {
875           data = (uint32_t)(*tempbuff);
876           tempbuff++;
877           dataremaining--;
878           data |= ((uint32_t)(*tempbuff) << 8U);
879           tempbuff++;
880           dataremaining--;
881           data |= ((uint32_t)(*tempbuff) << 16U);
882           tempbuff++;
883           dataremaining--;
884           data |= ((uint32_t)(*tempbuff) << 24U);
885           tempbuff++;
886           dataremaining--;
887           (void)SDIO_WriteFIFO(hsd->Instance, &data);
888         }
889       }
890 
891       if(((HAL_GetTick()-tickstart) >=  Timeout) || (Timeout == 0U))
892       {
893         /* Clear all the static flags */
894         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
895         hsd->ErrorCode |= errorstate;
896         hsd->State = HAL_SD_STATE_READY;
897         hsd->Context = SD_CONTEXT_NONE;
898         return HAL_TIMEOUT;
899       }
900     }
901 
902     /* Send stop transmission command in case of multiblock write */
903     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U))
904     {
905       if(hsd->SdCard.CardType != CARD_SECURED)
906       {
907         /* Send stop transmission command */
908         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
909         if(errorstate != HAL_SD_ERROR_NONE)
910         {
911           /* Clear all the static flags */
912           __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
913           hsd->ErrorCode |= errorstate;
914           hsd->State = HAL_SD_STATE_READY;
915           hsd->Context = SD_CONTEXT_NONE;
916           return HAL_ERROR;
917         }
918       }
919     }
920 
921     /* Get error state */
922     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
923     {
924       /* Clear all the static flags */
925       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
926       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
927       hsd->State = HAL_SD_STATE_READY;
928       hsd->Context = SD_CONTEXT_NONE;
929       return HAL_ERROR;
930     }
931     else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
932     {
933       /* Clear all the static flags */
934       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
935       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
936       hsd->State = HAL_SD_STATE_READY;
937       hsd->Context = SD_CONTEXT_NONE;
938       return HAL_ERROR;
939     }
940     else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR))
941     {
942       /* Clear all the static flags */
943       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
944       hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;
945       hsd->State = HAL_SD_STATE_READY;
946       hsd->Context = SD_CONTEXT_NONE;
947       return HAL_ERROR;
948     }
949     else
950     {
951       /* Nothing to do */
952     }
953 
954     /* Clear all the static flags */
955     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
956 
957     hsd->State = HAL_SD_STATE_READY;
958 
959     return HAL_OK;
960   }
961   else
962   {
963     hsd->ErrorCode |= HAL_SD_ERROR_BUSY;
964     return HAL_ERROR;
965   }
966 }
967 
968 /**
969   * @brief  Reads block(s) from a specified address in a card. The Data transfer
970   *         is managed in interrupt mode.
971   * @note   This API should be followed by a check on the card state through
972   *         HAL_SD_GetCardState().
973   * @note   You could also check the IT transfer process through the SD Rx
974   *         interrupt event.
975   * @param  hsd: Pointer to SD handle
976   * @param  pData: Pointer to the buffer that will contain the received data
977   * @param  BlockAdd: Block Address from where data is to be read
978   * @param  NumberOfBlocks: Number of blocks to read.
979   * @retval HAL status
980   */
HAL_SD_ReadBlocks_IT(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)981 HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
982 {
983   SDIO_DataInitTypeDef config;
984   uint32_t errorstate;
985   uint32_t add = BlockAdd;
986 
987   if(NULL == pData)
988   {
989     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
990     return HAL_ERROR;
991   }
992 
993   if(hsd->State == HAL_SD_STATE_READY)
994   {
995     hsd->ErrorCode = HAL_SD_ERROR_NONE;
996 
997     if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
998     {
999       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1000       return HAL_ERROR;
1001     }
1002 
1003     hsd->State = HAL_SD_STATE_BUSY;
1004 
1005     /* Initialize data control register */
1006     hsd->Instance->DCTRL = 0U;
1007 
1008     hsd->pRxBuffPtr = pData;
1009     hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks;
1010 
1011 #if defined(SDIO_STA_STBITERR)
1012     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF | SDIO_IT_STBITERR));
1013 #else /* SDIO_STA_STBITERR not defined */
1014     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF));
1015 #endif /* SDIO_STA_STBITERR */
1016 
1017     if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
1018     {
1019       add *= 512U;
1020     }
1021 
1022     /* Set Block Size for Card */
1023     errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
1024     if(errorstate != HAL_SD_ERROR_NONE)
1025     {
1026       /* Clear all the static flags */
1027       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1028       hsd->ErrorCode |= errorstate;
1029       hsd->State = HAL_SD_STATE_READY;
1030       return HAL_ERROR;
1031     }
1032 
1033     /* Configure the SD DPSM (Data Path State Machine) */
1034     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1035     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1036     config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
1037     config.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
1038     config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
1039     config.DPSM          = SDIO_DPSM_ENABLE;
1040     (void)SDIO_ConfigData(hsd->Instance, &config);
1041 
1042     /* Read Blocks in IT mode */
1043     if(NumberOfBlocks > 1U)
1044     {
1045       hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT);
1046 
1047       /* Read Multi Block command */
1048       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
1049     }
1050     else
1051     {
1052       hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT);
1053 
1054       /* Read Single Block command */
1055       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
1056     }
1057     if(errorstate != HAL_SD_ERROR_NONE)
1058     {
1059       /* Clear all the static flags */
1060       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1061       hsd->ErrorCode |= errorstate;
1062       hsd->State = HAL_SD_STATE_READY;
1063       hsd->Context = SD_CONTEXT_NONE;
1064       return HAL_ERROR;
1065     }
1066 
1067     return HAL_OK;
1068   }
1069   else
1070   {
1071     return HAL_BUSY;
1072   }
1073 }
1074 
1075 /**
1076   * @brief  Writes block(s) to a specified address in a card. The Data transfer
1077   *         is managed in interrupt mode.
1078   * @note   This API should be followed by a check on the card state through
1079   *         HAL_SD_GetCardState().
1080   * @note   You could also check the IT transfer process through the SD Tx
1081   *         interrupt event.
1082   * @param  hsd: Pointer to SD handle
1083   * @param  pData: Pointer to the buffer that will contain the data to transmit
1084   * @param  BlockAdd: Block Address where data will be written
1085   * @param  NumberOfBlocks: Number of blocks to write
1086   * @retval HAL status
1087   */
HAL_SD_WriteBlocks_IT(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1088 HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
1089 {
1090   SDIO_DataInitTypeDef config;
1091   uint32_t errorstate;
1092   uint32_t add = BlockAdd;
1093 
1094   if(NULL == pData)
1095   {
1096     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1097     return HAL_ERROR;
1098   }
1099 
1100   if(hsd->State == HAL_SD_STATE_READY)
1101   {
1102     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1103 
1104     if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1105     {
1106       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1107       return HAL_ERROR;
1108     }
1109 
1110     hsd->State = HAL_SD_STATE_BUSY;
1111 
1112     /* Initialize data control register */
1113     hsd->Instance->DCTRL = 0U;
1114 
1115     hsd->pTxBuffPtr = pData;
1116     hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks;
1117 
1118     /* Enable transfer interrupts */
1119 #if defined(SDIO_STA_STBITERR)
1120     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE | SDIO_IT_STBITERR));
1121 #else /* SDIO_STA_STBITERR not defined */
1122     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE));
1123 #endif /* SDIO_STA_STBITERR */
1124 
1125     if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
1126     {
1127       add *= 512U;
1128     }
1129 
1130     /* Set Block Size for Card */
1131     errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
1132     if(errorstate != HAL_SD_ERROR_NONE)
1133     {
1134       /* Clear all the static flags */
1135       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1136       hsd->ErrorCode |= errorstate;
1137       hsd->State = HAL_SD_STATE_READY;
1138       return HAL_ERROR;
1139     }
1140 
1141     /* Write Blocks in Polling mode */
1142     if(NumberOfBlocks > 1U)
1143     {
1144       hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK| SD_CONTEXT_IT);
1145 
1146       /* Write Multi Block command */
1147       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
1148     }
1149     else
1150     {
1151       hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT);
1152 
1153       /* Write Single Block command */
1154       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
1155     }
1156     if(errorstate != HAL_SD_ERROR_NONE)
1157     {
1158       /* Clear all the static flags */
1159       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1160       hsd->ErrorCode |= errorstate;
1161       hsd->State = HAL_SD_STATE_READY;
1162       hsd->Context = SD_CONTEXT_NONE;
1163       return HAL_ERROR;
1164     }
1165 
1166     /* Configure the SD DPSM (Data Path State Machine) */
1167     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1168     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1169     config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
1170     config.TransferDir   = SDIO_TRANSFER_DIR_TO_CARD;
1171     config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
1172     config.DPSM          = SDIO_DPSM_ENABLE;
1173     (void)SDIO_ConfigData(hsd->Instance, &config);
1174 
1175     return HAL_OK;
1176   }
1177   else
1178   {
1179     return HAL_BUSY;
1180   }
1181 }
1182 
1183 /**
1184   * @brief  Reads block(s) from a specified address in a card. The Data transfer
1185   *         is managed by DMA mode.
1186   * @note   This API should be followed by a check on the card state through
1187   *         HAL_SD_GetCardState().
1188   * @note   You could also check the DMA transfer process through the SD Rx
1189   *         interrupt event.
1190   * @param  hsd: Pointer SD handle
1191   * @param  pData: Pointer to the buffer that will contain the received data
1192   * @param  BlockAdd: Block Address from where data is to be read
1193   * @param  NumberOfBlocks: Number of blocks to read.
1194   * @retval HAL status
1195   */
HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1196 HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
1197 {
1198   SDIO_DataInitTypeDef config;
1199   uint32_t errorstate;
1200   uint32_t add = BlockAdd;
1201 
1202   if(NULL == pData)
1203   {
1204     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1205     return HAL_ERROR;
1206   }
1207 
1208   if(hsd->State == HAL_SD_STATE_READY)
1209   {
1210     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1211 
1212     if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1213     {
1214       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1215       return HAL_ERROR;
1216     }
1217 
1218     hsd->State = HAL_SD_STATE_BUSY;
1219 
1220     /* Initialize data control register */
1221     hsd->Instance->DCTRL = 0U;
1222 
1223 #if defined(SDIO_STA_STBITERR)
1224     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_IT_STBITERR));
1225 #else /* SDIO_STA_STBITERR not defined */
1226     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND));
1227 #endif /* SDIO_STA_STBITERR */
1228 
1229     /* Set the DMA transfer complete callback */
1230     hsd->hdmarx->XferCpltCallback = SD_DMAReceiveCplt;
1231 
1232     /* Set the DMA error callback */
1233     hsd->hdmarx->XferErrorCallback = SD_DMAError;
1234 
1235     /* Set the DMA Abort callback */
1236     hsd->hdmarx->XferAbortCallback = NULL;
1237 
1238     /* Enable the DMA Channel */
1239     if(HAL_DMA_Start_IT(hsd->hdmarx, (uint32_t)&hsd->Instance->FIFO, (uint32_t)pData, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4U) != HAL_OK)
1240     {
1241       __HAL_SD_DISABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND));
1242       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1243       hsd->ErrorCode |= HAL_SD_ERROR_DMA;
1244       hsd->State = HAL_SD_STATE_READY;
1245       return HAL_ERROR;
1246     }
1247     else
1248     {
1249       /* Enable SD DMA transfer */
1250       __HAL_SD_DMA_ENABLE(hsd);
1251 
1252       if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
1253       {
1254         add *= 512U;
1255       }
1256 
1257       /* Set Block Size for Card */
1258       errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
1259       if(errorstate != HAL_SD_ERROR_NONE)
1260       {
1261         /* Clear all the static flags */
1262         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1263         hsd->ErrorCode |= errorstate;
1264         hsd->State = HAL_SD_STATE_READY;
1265         return HAL_ERROR;
1266       }
1267 
1268       /* Configure the SD DPSM (Data Path State Machine) */
1269       config.DataTimeOut   = SDMMC_DATATIMEOUT;
1270       config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1271       config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
1272       config.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
1273       config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
1274       config.DPSM          = SDIO_DPSM_ENABLE;
1275       (void)SDIO_ConfigData(hsd->Instance, &config);
1276 
1277       /* Read Blocks in DMA mode */
1278       if(NumberOfBlocks > 1U)
1279       {
1280         hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA);
1281 
1282         /* Read Multi Block command */
1283         errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
1284       }
1285       else
1286       {
1287         hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA);
1288 
1289         /* Read Single Block command */
1290         errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
1291       }
1292       if(errorstate != HAL_SD_ERROR_NONE)
1293       {
1294         /* Clear all the static flags */
1295         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1296         hsd->ErrorCode |= errorstate;
1297         hsd->State = HAL_SD_STATE_READY;
1298         hsd->Context = SD_CONTEXT_NONE;
1299         return HAL_ERROR;
1300       }
1301 
1302       return HAL_OK;
1303     }
1304   }
1305   else
1306   {
1307     return HAL_BUSY;
1308   }
1309 }
1310 
1311 /**
1312   * @brief  Writes block(s) to a specified address in a card. The Data transfer
1313   *         is managed by DMA mode.
1314   * @note   This API should be followed by a check on the card state through
1315   *         HAL_SD_GetCardState().
1316   * @note   You could also check the DMA transfer process through the SD Tx
1317   *         interrupt event.
1318   * @param  hsd: Pointer to SD handle
1319   * @param  pData: Pointer to the buffer that will contain the data to transmit
1320   * @param  BlockAdd: Block Address where data will be written
1321   * @param  NumberOfBlocks: Number of blocks to write
1322   * @retval HAL status
1323   */
HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1324 HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks)
1325 {
1326   SDIO_DataInitTypeDef config;
1327   uint32_t errorstate;
1328   uint32_t add = BlockAdd;
1329 
1330   if(NULL == pData)
1331   {
1332     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1333     return HAL_ERROR;
1334   }
1335 
1336   if(hsd->State == HAL_SD_STATE_READY)
1337   {
1338     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1339 
1340     if((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1341     {
1342       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1343       return HAL_ERROR;
1344     }
1345 
1346     hsd->State = HAL_SD_STATE_BUSY;
1347 
1348     /* Initialize data control register */
1349     hsd->Instance->DCTRL = 0U;
1350 
1351     /* Enable SD Error interrupts */
1352 #if defined(SDIO_STA_STBITERR)
1353     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR));
1354 #else /* SDIO_STA_STBITERR not defined */
1355     __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR));
1356 #endif /* SDIO_STA_STBITERR */
1357 
1358     /* Set the DMA transfer complete callback */
1359     hsd->hdmatx->XferCpltCallback = SD_DMATransmitCplt;
1360 
1361     /* Set the DMA error callback */
1362     hsd->hdmatx->XferErrorCallback = SD_DMAError;
1363 
1364     /* Set the DMA Abort callback */
1365     hsd->hdmatx->XferAbortCallback = NULL;
1366 
1367     if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
1368     {
1369       add *= 512U;
1370     }
1371 
1372     /* Set Block Size for Card */
1373     errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
1374     if(errorstate != HAL_SD_ERROR_NONE)
1375     {
1376       /* Clear all the static flags */
1377       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1378       hsd->ErrorCode |= errorstate;
1379       hsd->State = HAL_SD_STATE_READY;
1380       return HAL_ERROR;
1381     }
1382 
1383     /* Write Blocks in Polling mode */
1384     if(NumberOfBlocks > 1U)
1385     {
1386       hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA);
1387 
1388       /* Write Multi Block command */
1389       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
1390     }
1391     else
1392     {
1393       hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA);
1394 
1395       /* Write Single Block command */
1396       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
1397     }
1398     if(errorstate != HAL_SD_ERROR_NONE)
1399     {
1400       /* Clear all the static flags */
1401       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1402       hsd->ErrorCode |= errorstate;
1403       hsd->State = HAL_SD_STATE_READY;
1404       hsd->Context = SD_CONTEXT_NONE;
1405       return HAL_ERROR;
1406     }
1407 
1408     /* Enable SDIO DMA transfer */
1409     __HAL_SD_DMA_ENABLE(hsd);
1410 
1411     /* Enable the DMA Channel */
1412     if(HAL_DMA_Start_IT(hsd->hdmatx, (uint32_t)pData, (uint32_t)&hsd->Instance->FIFO, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4U) != HAL_OK)
1413     {
1414 #if defined(SDIO_STA_STBITERR)
1415       __HAL_SD_DISABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR));
1416 #else /* SDIO_STA_STBITERR not defined */
1417       __HAL_SD_DISABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR));
1418 #endif /* SDIO_STA_STBITERR */
1419       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1420       hsd->ErrorCode |= HAL_SD_ERROR_DMA;
1421       hsd->State = HAL_SD_STATE_READY;
1422       hsd->Context = SD_CONTEXT_NONE;
1423       return HAL_ERROR;
1424     }
1425     else
1426     {
1427       /* Configure the SD DPSM (Data Path State Machine) */
1428       config.DataTimeOut   = SDMMC_DATATIMEOUT;
1429       config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1430       config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
1431       config.TransferDir   = SDIO_TRANSFER_DIR_TO_CARD;
1432       config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
1433       config.DPSM          = SDIO_DPSM_ENABLE;
1434       (void)SDIO_ConfigData(hsd->Instance, &config);
1435 
1436       return HAL_OK;
1437     }
1438   }
1439   else
1440   {
1441     return HAL_BUSY;
1442   }
1443 }
1444 
1445 /**
1446   * @brief  Erases the specified memory area of the given SD card.
1447   * @note   This API should be followed by a check on the card state through
1448   *         HAL_SD_GetCardState().
1449   * @param  hsd: Pointer to SD handle
1450   * @param  BlockStartAdd: Start Block address
1451   * @param  BlockEndAdd: End Block address
1452   * @retval HAL status
1453   */
HAL_SD_Erase(SD_HandleTypeDef * hsd,uint32_t BlockStartAdd,uint32_t BlockEndAdd)1454 HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd)
1455 {
1456   uint32_t errorstate;
1457   uint32_t start_add = BlockStartAdd;
1458   uint32_t end_add = BlockEndAdd;
1459 
1460   if(hsd->State == HAL_SD_STATE_READY)
1461   {
1462     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1463 
1464     if(end_add < start_add)
1465     {
1466       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1467       return HAL_ERROR;
1468     }
1469 
1470     if(end_add > (hsd->SdCard.LogBlockNbr))
1471     {
1472       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1473       return HAL_ERROR;
1474     }
1475 
1476     hsd->State = HAL_SD_STATE_BUSY;
1477 
1478     /* Check if the card command class supports erase command */
1479     if(((hsd->SdCard.Class) & SDIO_CCCC_ERASE) == 0U)
1480     {
1481       /* Clear all the static flags */
1482       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1483       hsd->ErrorCode |= HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
1484       hsd->State = HAL_SD_STATE_READY;
1485       return HAL_ERROR;
1486     }
1487 
1488     if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
1489     {
1490       /* Clear all the static flags */
1491       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1492       hsd->ErrorCode |= HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
1493       hsd->State = HAL_SD_STATE_READY;
1494       return HAL_ERROR;
1495     }
1496 
1497     /* Get start and end block for high capacity cards */
1498     if(hsd->SdCard.CardType != CARD_SDHC_SDXC)
1499     {
1500       start_add *= 512U;
1501       end_add   *= 512U;
1502     }
1503 
1504     /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */
1505     if(hsd->SdCard.CardType != CARD_SECURED)
1506     {
1507       /* Send CMD32 SD_ERASE_GRP_START with argument as addr  */
1508       errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, start_add);
1509       if(errorstate != HAL_SD_ERROR_NONE)
1510       {
1511         /* Clear all the static flags */
1512         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1513         hsd->ErrorCode |= errorstate;
1514         hsd->State = HAL_SD_STATE_READY;
1515         return HAL_ERROR;
1516       }
1517 
1518       /* Send CMD33 SD_ERASE_GRP_END with argument as addr  */
1519       errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, end_add);
1520       if(errorstate != HAL_SD_ERROR_NONE)
1521       {
1522         /* Clear all the static flags */
1523         __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1524         hsd->ErrorCode |= errorstate;
1525         hsd->State = HAL_SD_STATE_READY;
1526         return HAL_ERROR;
1527       }
1528     }
1529 
1530     /* Send CMD38 ERASE */
1531     errorstate = SDMMC_CmdErase(hsd->Instance);
1532     if(errorstate != HAL_SD_ERROR_NONE)
1533     {
1534       /* Clear all the static flags */
1535       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1536       hsd->ErrorCode |= errorstate;
1537       hsd->State = HAL_SD_STATE_READY;
1538       return HAL_ERROR;
1539     }
1540 
1541     hsd->State = HAL_SD_STATE_READY;
1542 
1543     return HAL_OK;
1544   }
1545   else
1546   {
1547     return HAL_BUSY;
1548   }
1549 }
1550 
1551 /**
1552   * @brief  This function handles SD card interrupt request.
1553   * @param  hsd: Pointer to SD handle
1554   * @retval None
1555   */
HAL_SD_IRQHandler(SD_HandleTypeDef * hsd)1556 void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd)
1557 {
1558   uint32_t errorstate;
1559   uint32_t context = hsd->Context;
1560 
1561   /* Check for SDIO interrupt flags */
1562   if((__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF) != RESET) && ((context & SD_CONTEXT_IT) != 0U))
1563   {
1564     SD_Read_IT(hsd);
1565   }
1566 
1567   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) != RESET)
1568   {
1569     __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DATAEND);
1570 
1571 #if defined(SDIO_STA_STBITERR)
1572     __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND  | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
1573                              SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR  | SDIO_IT_TXFIFOHE |\
1574                              SDIO_IT_RXFIFOHF | SDIO_IT_STBITERR);
1575 #else /* SDIO_STA_STBITERR not defined */
1576     __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND  | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
1577                              SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR  | SDIO_IT_TXFIFOHE |\
1578                              SDIO_IT_RXFIFOHF);
1579 #endif /* SDIO_STA_STBITERR */
1580 
1581     hsd->Instance->DCTRL &= ~(SDIO_DCTRL_DTEN);
1582 
1583     if((context & SD_CONTEXT_IT) != 0U)
1584     {
1585       if(((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1586       {
1587         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
1588         if(errorstate != HAL_SD_ERROR_NONE)
1589         {
1590           hsd->ErrorCode |= errorstate;
1591 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1592           hsd->ErrorCallback(hsd);
1593 #else
1594           HAL_SD_ErrorCallback(hsd);
1595 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1596         }
1597       }
1598 
1599       /* Clear all the static flags */
1600       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
1601 
1602       hsd->State = HAL_SD_STATE_READY;
1603       hsd->Context = SD_CONTEXT_NONE;
1604       if(((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
1605       {
1606 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1607         hsd->RxCpltCallback(hsd);
1608 #else
1609         HAL_SD_RxCpltCallback(hsd);
1610 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1611       }
1612       else
1613       {
1614 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1615         hsd->TxCpltCallback(hsd);
1616 #else
1617         HAL_SD_TxCpltCallback(hsd);
1618 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1619       }
1620     }
1621     else if((context & SD_CONTEXT_DMA) != 0U)
1622     {
1623       if((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)
1624       {
1625         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
1626         if(errorstate != HAL_SD_ERROR_NONE)
1627         {
1628           hsd->ErrorCode |= errorstate;
1629 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1630           hsd->ErrorCallback(hsd);
1631 #else
1632           HAL_SD_ErrorCallback(hsd);
1633 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1634         }
1635       }
1636       if(((context & SD_CONTEXT_READ_SINGLE_BLOCK) == 0U) && ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) == 0U))
1637       {
1638         /* Disable the DMA transfer for transmit request by setting the DMAEN bit
1639         in the SD DCTRL register */
1640         hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN);
1641 
1642         hsd->State = HAL_SD_STATE_READY;
1643 
1644 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1645         hsd->TxCpltCallback(hsd);
1646 #else
1647         HAL_SD_TxCpltCallback(hsd);
1648 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1649       }
1650     }
1651     else
1652     {
1653       /* Nothing to do */
1654     }
1655   }
1656 
1657   else if((__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE) != RESET) && ((context & SD_CONTEXT_IT) != 0U))
1658   {
1659     SD_Write_IT(hsd);
1660   }
1661 
1662 #if defined(SDIO_STA_STBITERR)
1663   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_TXUNDERR | SDIO_FLAG_STBITERR) != RESET)
1664 #else /* SDIO_STA_STBITERR not defined */
1665   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_TXUNDERR) != RESET)
1666 #endif /* SDIO_STA_STBITERR */
1667   {
1668     /* Set Error code */
1669     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL) != RESET)
1670     {
1671       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
1672     }
1673     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT) != RESET)
1674     {
1675       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
1676     }
1677     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR) != RESET)
1678     {
1679       hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN;
1680     }
1681     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR) != RESET)
1682     {
1683       hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;
1684     }
1685 #if defined(SDIO_STA_STBITERR)
1686     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_STBITERR) != RESET)
1687     {
1688       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
1689     }
1690 #endif /* SDIO_STA_STBITERR */
1691 
1692 #if defined(SDIO_STA_STBITERR)
1693     /* Clear All flags */
1694     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS | SDIO_FLAG_STBITERR);
1695 
1696     /* Disable all interrupts */
1697     __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
1698                              SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR | SDIO_IT_STBITERR);
1699 #else /* SDIO_STA_STBITERR not defined */
1700     /* Clear All flags */
1701     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
1702 
1703     /* Disable all interrupts */
1704     __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
1705                              SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR);
1706 #endif /* SDIO_STA_STBITERR */
1707 
1708     hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance);
1709 
1710     if((context & SD_CONTEXT_IT) != 0U)
1711     {
1712       /* Set the SD state to ready to be able to start again the process */
1713       hsd->State = HAL_SD_STATE_READY;
1714       hsd->Context = SD_CONTEXT_NONE;
1715 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1716       hsd->ErrorCallback(hsd);
1717 #else
1718       HAL_SD_ErrorCallback(hsd);
1719 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1720     }
1721     else if((context & SD_CONTEXT_DMA) != 0U)
1722     {
1723       /* Abort the SD DMA channel */
1724       if(((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1725       {
1726         /* Set the DMA Tx abort callback */
1727         hsd->hdmatx->XferAbortCallback = SD_DMATxAbort;
1728         /* Abort DMA in IT mode */
1729         if(HAL_DMA_Abort_IT(hsd->hdmatx) != HAL_OK)
1730         {
1731           SD_DMATxAbort(hsd->hdmatx);
1732         }
1733       }
1734       else if(((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
1735       {
1736         /* Set the DMA Rx abort callback */
1737         hsd->hdmarx->XferAbortCallback = SD_DMARxAbort;
1738         /* Abort DMA in IT mode */
1739         if(HAL_DMA_Abort_IT(hsd->hdmarx) != HAL_OK)
1740         {
1741           SD_DMARxAbort(hsd->hdmarx);
1742         }
1743       }
1744       else
1745       {
1746         hsd->ErrorCode = HAL_SD_ERROR_NONE;
1747         hsd->State = HAL_SD_STATE_READY;
1748         hsd->Context = SD_CONTEXT_NONE;
1749 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1750         hsd->AbortCpltCallback(hsd);
1751 #else
1752         HAL_SD_AbortCallback(hsd);
1753 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1754       }
1755     }
1756     else
1757     {
1758       /* Nothing to do */
1759     }
1760   }
1761   else
1762   {
1763     /* Nothing to do */
1764   }
1765 }
1766 
1767 /**
1768   * @brief return the SD state
1769   * @param hsd: Pointer to sd handle
1770   * @retval HAL state
1771   */
HAL_SD_GetState(SD_HandleTypeDef * hsd)1772 HAL_SD_StateTypeDef HAL_SD_GetState(SD_HandleTypeDef *hsd)
1773 {
1774   return hsd->State;
1775 }
1776 
1777 /**
1778 * @brief  Return the SD error code
1779 * @param  hsd : Pointer to a SD_HandleTypeDef structure that contains
1780   *              the configuration information.
1781 * @retval SD Error Code
1782 */
HAL_SD_GetError(SD_HandleTypeDef * hsd)1783 uint32_t HAL_SD_GetError(SD_HandleTypeDef *hsd)
1784 {
1785   return hsd->ErrorCode;
1786 }
1787 
1788 /**
1789   * @brief Tx Transfer completed callbacks
1790   * @param hsd: Pointer to SD handle
1791   * @retval None
1792   */
HAL_SD_TxCpltCallback(SD_HandleTypeDef * hsd)1793 __weak void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd)
1794 {
1795   /* Prevent unused argument(s) compilation warning */
1796   UNUSED(hsd);
1797 
1798   /* NOTE : This function should not be modified, when the callback is needed,
1799             the HAL_SD_TxCpltCallback can be implemented in the user file
1800    */
1801 }
1802 
1803 /**
1804   * @brief Rx Transfer completed callbacks
1805   * @param hsd: Pointer SD handle
1806   * @retval None
1807   */
HAL_SD_RxCpltCallback(SD_HandleTypeDef * hsd)1808 __weak void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd)
1809 {
1810   /* Prevent unused argument(s) compilation warning */
1811   UNUSED(hsd);
1812 
1813   /* NOTE : This function should not be modified, when the callback is needed,
1814             the HAL_SD_RxCpltCallback can be implemented in the user file
1815    */
1816 }
1817 
1818 /**
1819   * @brief SD error callbacks
1820   * @param hsd: Pointer SD handle
1821   * @retval None
1822   */
HAL_SD_ErrorCallback(SD_HandleTypeDef * hsd)1823 __weak void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd)
1824 {
1825   /* Prevent unused argument(s) compilation warning */
1826   UNUSED(hsd);
1827 
1828   /* NOTE : This function should not be modified, when the callback is needed,
1829             the HAL_SD_ErrorCallback can be implemented in the user file
1830    */
1831 }
1832 
1833 /**
1834   * @brief SD Abort callbacks
1835   * @param hsd: Pointer SD handle
1836   * @retval None
1837   */
HAL_SD_AbortCallback(SD_HandleTypeDef * hsd)1838 __weak void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd)
1839 {
1840   /* Prevent unused argument(s) compilation warning */
1841   UNUSED(hsd);
1842 
1843   /* NOTE : This function should not be modified, when the callback is needed,
1844             the HAL_SD_AbortCallback can be implemented in the user file
1845    */
1846 }
1847 
1848 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1849 /**
1850   * @brief  Register a User SD Callback
1851   *         To be used instead of the weak (surcharged) predefined callback
1852   * @param hsd : SD handle
1853   * @param CallbackID : ID of the callback to be registered
1854   *        This parameter can be one of the following values:
1855   *          @arg @ref HAL_SD_TX_CPLT_CB_ID    SD Tx Complete Callback ID
1856   *          @arg @ref HAL_SD_RX_CPLT_CB_ID    SD Rx Complete Callback ID
1857   *          @arg @ref HAL_SD_ERROR_CB_ID      SD Error Callback ID
1858   *          @arg @ref HAL_SD_ABORT_CB_ID      SD Abort Callback ID
1859   *          @arg @ref HAL_SD_MSP_INIT_CB_ID   SD MspInit Callback ID
1860   *          @arg @ref HAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID
1861   * @param pCallback : pointer to the Callback function
1862   * @retval status
1863   */
HAL_SD_RegisterCallback(SD_HandleTypeDef * hsd,HAL_SD_CallbackIDTypeDef CallbackID,pSD_CallbackTypeDef pCallback)1864 HAL_StatusTypeDef HAL_SD_RegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID, pSD_CallbackTypeDef pCallback)
1865 {
1866   HAL_StatusTypeDef status = HAL_OK;
1867 
1868   if(pCallback == NULL)
1869   {
1870     /* Update the error code */
1871     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1872     return HAL_ERROR;
1873   }
1874 
1875   /* Process locked */
1876   __HAL_LOCK(hsd);
1877 
1878   if(hsd->State == HAL_SD_STATE_READY)
1879   {
1880     switch (CallbackID)
1881     {
1882     case HAL_SD_TX_CPLT_CB_ID :
1883       hsd->TxCpltCallback = pCallback;
1884       break;
1885     case HAL_SD_RX_CPLT_CB_ID :
1886       hsd->RxCpltCallback = pCallback;
1887       break;
1888     case HAL_SD_ERROR_CB_ID :
1889       hsd->ErrorCallback = pCallback;
1890       break;
1891     case HAL_SD_ABORT_CB_ID :
1892       hsd->AbortCpltCallback = pCallback;
1893       break;
1894     case HAL_SD_MSP_INIT_CB_ID :
1895       hsd->MspInitCallback = pCallback;
1896       break;
1897     case HAL_SD_MSP_DEINIT_CB_ID :
1898       hsd->MspDeInitCallback = pCallback;
1899       break;
1900     default :
1901       /* Update the error code */
1902       hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1903       /* update return status */
1904       status =  HAL_ERROR;
1905       break;
1906     }
1907   }
1908   else if (hsd->State == HAL_SD_STATE_RESET)
1909   {
1910     switch (CallbackID)
1911     {
1912     case HAL_SD_MSP_INIT_CB_ID :
1913       hsd->MspInitCallback = pCallback;
1914       break;
1915     case HAL_SD_MSP_DEINIT_CB_ID :
1916       hsd->MspDeInitCallback = pCallback;
1917       break;
1918     default :
1919       /* Update the error code */
1920       hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1921       /* update return status */
1922       status =  HAL_ERROR;
1923       break;
1924     }
1925   }
1926   else
1927   {
1928     /* Update the error code */
1929     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1930     /* update return status */
1931     status =  HAL_ERROR;
1932   }
1933 
1934   /* Release Lock */
1935   __HAL_UNLOCK(hsd);
1936   return status;
1937 }
1938 
1939 /**
1940   * @brief  Unregister a User SD Callback
1941   *         SD Callback is redirected to the weak (surcharged) predefined callback
1942   * @param hsd : SD handle
1943   * @param CallbackID : ID of the callback to be unregistered
1944   *        This parameter can be one of the following values:
1945   *          @arg @ref HAL_SD_TX_CPLT_CB_ID    SD Tx Complete Callback ID
1946   *          @arg @ref HAL_SD_RX_CPLT_CB_ID    SD Rx Complete Callback ID
1947   *          @arg @ref HAL_SD_ERROR_CB_ID      SD Error Callback ID
1948   *          @arg @ref HAL_SD_ABORT_CB_ID      SD Abort Callback ID
1949   *          @arg @ref HAL_SD_MSP_INIT_CB_ID   SD MspInit Callback ID
1950   *          @arg @ref HAL_SD_MSP_DEINIT_CB_ID SD MspDeInit Callback ID
1951   * @retval status
1952   */
HAL_SD_UnRegisterCallback(SD_HandleTypeDef * hsd,HAL_SD_CallbackIDTypeDef CallbackID)1953 HAL_StatusTypeDef HAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID)
1954 {
1955   HAL_StatusTypeDef status = HAL_OK;
1956 
1957   /* Process locked */
1958   __HAL_LOCK(hsd);
1959 
1960   if(hsd->State == HAL_SD_STATE_READY)
1961   {
1962     switch (CallbackID)
1963     {
1964     case HAL_SD_TX_CPLT_CB_ID :
1965       hsd->TxCpltCallback = HAL_SD_TxCpltCallback;
1966       break;
1967     case HAL_SD_RX_CPLT_CB_ID :
1968       hsd->RxCpltCallback = HAL_SD_RxCpltCallback;
1969       break;
1970     case HAL_SD_ERROR_CB_ID :
1971       hsd->ErrorCallback = HAL_SD_ErrorCallback;
1972       break;
1973     case HAL_SD_ABORT_CB_ID :
1974       hsd->AbortCpltCallback = HAL_SD_AbortCallback;
1975       break;
1976     case HAL_SD_MSP_INIT_CB_ID :
1977       hsd->MspInitCallback = HAL_SD_MspInit;
1978       break;
1979     case HAL_SD_MSP_DEINIT_CB_ID :
1980       hsd->MspDeInitCallback = HAL_SD_MspDeInit;
1981       break;
1982     default :
1983       /* Update the error code */
1984       hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1985       /* update return status */
1986       status =  HAL_ERROR;
1987       break;
1988     }
1989   }
1990   else if (hsd->State == HAL_SD_STATE_RESET)
1991   {
1992     switch (CallbackID)
1993     {
1994     case HAL_SD_MSP_INIT_CB_ID :
1995       hsd->MspInitCallback = HAL_SD_MspInit;
1996       break;
1997     case HAL_SD_MSP_DEINIT_CB_ID :
1998       hsd->MspDeInitCallback = HAL_SD_MspDeInit;
1999       break;
2000     default :
2001       /* Update the error code */
2002       hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2003       /* update return status */
2004       status =  HAL_ERROR;
2005       break;
2006     }
2007   }
2008   else
2009   {
2010     /* Update the error code */
2011     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2012     /* update return status */
2013     status =  HAL_ERROR;
2014   }
2015 
2016   /* Release Lock */
2017   __HAL_UNLOCK(hsd);
2018   return status;
2019 }
2020 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
2021 
2022 /**
2023   * @}
2024   */
2025 
2026 /** @addtogroup SD_Exported_Functions_Group3
2027  *  @brief   management functions
2028  *
2029 @verbatim
2030   ==============================================================================
2031                       ##### Peripheral Control functions #####
2032   ==============================================================================
2033   [..]
2034     This subsection provides a set of functions allowing to control the SD card
2035     operations and get the related information
2036 
2037 @endverbatim
2038   * @{
2039   */
2040 
2041 /**
2042   * @brief  Returns information the information of the card which are stored on
2043   *         the CID register.
2044   * @param  hsd: Pointer to SD handle
2045   * @param  pCID: Pointer to a HAL_SD_CardCIDTypeDef structure that
2046   *         contains all CID register parameters
2047   * @retval HAL status
2048   */
HAL_SD_GetCardCID(SD_HandleTypeDef * hsd,HAL_SD_CardCIDTypeDef * pCID)2049 HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID)
2050 {
2051   pCID->ManufacturerID = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24U);
2052 
2053   pCID->OEM_AppliID = (uint16_t)((hsd->CID[0] & 0x00FFFF00U) >> 8U);
2054 
2055   pCID->ProdName1 = (((hsd->CID[0] & 0x000000FFU) << 24U) | ((hsd->CID[1] & 0xFFFFFF00U) >> 8U));
2056 
2057   pCID->ProdName2 = (uint8_t)(hsd->CID[1] & 0x000000FFU);
2058 
2059   pCID->ProdRev = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24U);
2060 
2061   pCID->ProdSN = (((hsd->CID[2] & 0x00FFFFFFU) << 8U) | ((hsd->CID[3] & 0xFF000000U) >> 24U));
2062 
2063   pCID->Reserved1 = (uint8_t)((hsd->CID[3] & 0x00F00000U) >> 20U);
2064 
2065   pCID->ManufactDate = (uint16_t)((hsd->CID[3] & 0x000FFF00U) >> 8U);
2066 
2067   pCID->CID_CRC = (uint8_t)((hsd->CID[3] & 0x000000FEU) >> 1U);
2068 
2069   pCID->Reserved2 = 1U;
2070 
2071   return HAL_OK;
2072 }
2073 
2074 /**
2075   * @brief  Returns information the information of the card which are stored on
2076   *         the CSD register.
2077   * @param  hsd: Pointer to SD handle
2078   * @param  pCSD: Pointer to a HAL_SD_CardCSDTypeDef structure that
2079   *         contains all CSD register parameters
2080   * @retval HAL status
2081   */
HAL_SD_GetCardCSD(SD_HandleTypeDef * hsd,HAL_SD_CardCSDTypeDef * pCSD)2082 HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD)
2083 {
2084   pCSD->CSDStruct = (uint8_t)((hsd->CSD[0] & 0xC0000000U) >> 30U);
2085 
2086   pCSD->SysSpecVersion = (uint8_t)((hsd->CSD[0] & 0x3C000000U) >> 26U);
2087 
2088   pCSD->Reserved1 = (uint8_t)((hsd->CSD[0] & 0x03000000U) >> 24U);
2089 
2090   pCSD->TAAC = (uint8_t)((hsd->CSD[0] & 0x00FF0000U) >> 16U);
2091 
2092   pCSD->NSAC = (uint8_t)((hsd->CSD[0] & 0x0000FF00U) >> 8U);
2093 
2094   pCSD->MaxBusClkFrec = (uint8_t)(hsd->CSD[0] & 0x000000FFU);
2095 
2096   pCSD->CardComdClasses = (uint16_t)((hsd->CSD[1] & 0xFFF00000U) >> 20U);
2097 
2098   pCSD->RdBlockLen = (uint8_t)((hsd->CSD[1] & 0x000F0000U) >> 16U);
2099 
2100   pCSD->PartBlockRead   = (uint8_t)((hsd->CSD[1] & 0x00008000U) >> 15U);
2101 
2102   pCSD->WrBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00004000U) >> 14U);
2103 
2104   pCSD->RdBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00002000U) >> 13U);
2105 
2106   pCSD->DSRImpl = (uint8_t)((hsd->CSD[1] & 0x00001000U) >> 12U);
2107 
2108   pCSD->Reserved2 = 0U; /*!< Reserved */
2109 
2110   if(hsd->SdCard.CardType == CARD_SDSC)
2111   {
2112     pCSD->DeviceSize = (((hsd->CSD[1] & 0x000003FFU) << 2U) | ((hsd->CSD[2] & 0xC0000000U) >> 30U));
2113 
2114     pCSD->MaxRdCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x38000000U) >> 27U);
2115 
2116     pCSD->MaxRdCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x07000000U) >> 24U);
2117 
2118     pCSD->MaxWrCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x00E00000U) >> 21U);
2119 
2120     pCSD->MaxWrCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x001C0000U) >> 18U);
2121 
2122     pCSD->DeviceSizeMul = (uint8_t)((hsd->CSD[2] & 0x00038000U) >> 15U);
2123 
2124     hsd->SdCard.BlockNbr  = (pCSD->DeviceSize + 1U) ;
2125     hsd->SdCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U));
2126     hsd->SdCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU));
2127 
2128     hsd->SdCard.LogBlockNbr =  (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / 512U);
2129     hsd->SdCard.LogBlockSize = 512U;
2130   }
2131   else if(hsd->SdCard.CardType == CARD_SDHC_SDXC)
2132   {
2133     /* Byte 7 */
2134     pCSD->DeviceSize = (((hsd->CSD[1] & 0x0000003FU) << 16U) | ((hsd->CSD[2] & 0xFFFF0000U) >> 16U));
2135 
2136     hsd->SdCard.BlockNbr = ((pCSD->DeviceSize + 1U) * 1024U);
2137     hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr;
2138     hsd->SdCard.BlockSize = 512U;
2139     hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize;
2140   }
2141   else
2142   {
2143     /* Clear all the static flags */
2144     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2145     hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2146     hsd->State = HAL_SD_STATE_READY;
2147     return HAL_ERROR;
2148   }
2149 
2150   pCSD->EraseGrSize = (uint8_t)((hsd->CSD[2] & 0x00004000U) >> 14U);
2151 
2152   pCSD->EraseGrMul = (uint8_t)((hsd->CSD[2] & 0x00003F80U) >> 7U);
2153 
2154   pCSD->WrProtectGrSize = (uint8_t)(hsd->CSD[2] & 0x0000007FU);
2155 
2156   pCSD->WrProtectGrEnable = (uint8_t)((hsd->CSD[3] & 0x80000000U) >> 31U);
2157 
2158   pCSD->ManDeflECC = (uint8_t)((hsd->CSD[3] & 0x60000000U) >> 29U);
2159 
2160   pCSD->WrSpeedFact = (uint8_t)((hsd->CSD[3] & 0x1C000000U) >> 26U);
2161 
2162   pCSD->MaxWrBlockLen= (uint8_t)((hsd->CSD[3] & 0x03C00000U) >> 22U);
2163 
2164   pCSD->WriteBlockPaPartial = (uint8_t)((hsd->CSD[3] & 0x00200000U) >> 21U);
2165 
2166   pCSD->Reserved3 = 0;
2167 
2168   pCSD->ContentProtectAppli = (uint8_t)((hsd->CSD[3] & 0x00010000U) >> 16U);
2169 
2170   pCSD->FileFormatGroup = (uint8_t)((hsd->CSD[3] & 0x00008000U) >> 15U);
2171 
2172   pCSD->CopyFlag = (uint8_t)((hsd->CSD[3] & 0x00004000U) >> 14U);
2173 
2174   pCSD->PermWrProtect = (uint8_t)((hsd->CSD[3] & 0x00002000U) >> 13U);
2175 
2176   pCSD->TempWrProtect = (uint8_t)((hsd->CSD[3] & 0x00001000U) >> 12U);
2177 
2178   pCSD->FileFormat = (uint8_t)((hsd->CSD[3] & 0x00000C00U) >> 10U);
2179 
2180   pCSD->ECC= (uint8_t)((hsd->CSD[3] & 0x00000300U) >> 8U);
2181 
2182   pCSD->CSD_CRC = (uint8_t)((hsd->CSD[3] & 0x000000FEU) >> 1U);
2183 
2184   pCSD->Reserved4 = 1;
2185 
2186   return HAL_OK;
2187 }
2188 
2189 /**
2190   * @brief  Gets the SD status info.
2191   * @param  hsd: Pointer to SD handle
2192   * @param  pStatus: Pointer to the HAL_SD_CardStatusTypeDef structure that
2193   *         will contain the SD card status information
2194   * @retval HAL status
2195   */
HAL_SD_GetCardStatus(SD_HandleTypeDef * hsd,HAL_SD_CardStatusTypeDef * pStatus)2196 HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus)
2197 {
2198   uint32_t sd_status[16];
2199   uint32_t errorstate;
2200 
2201   errorstate = SD_SendSDStatus(hsd, sd_status);
2202   if(errorstate != HAL_SD_ERROR_NONE)
2203   {
2204     /* Clear all the static flags */
2205     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2206     hsd->ErrorCode |= errorstate;
2207     hsd->State = HAL_SD_STATE_READY;
2208     return HAL_ERROR;
2209   }
2210   else
2211   {
2212     pStatus->DataBusWidth = (uint8_t)((sd_status[0] & 0xC0U) >> 6U);
2213 
2214     pStatus->SecuredMode = (uint8_t)((sd_status[0] & 0x20U) >> 5U);
2215 
2216     pStatus->CardType = (uint16_t)(((sd_status[0] & 0x00FF0000U) >> 8U) | ((sd_status[0] & 0xFF000000U) >> 24U));
2217 
2218     pStatus->ProtectedAreaSize = (((sd_status[1] & 0xFFU) << 24U)    | ((sd_status[1] & 0xFF00U) << 8U) |
2219                                   ((sd_status[1] & 0xFF0000U) >> 8U) | ((sd_status[1] & 0xFF000000U) >> 24U));
2220 
2221     pStatus->SpeedClass = (uint8_t)(sd_status[2] & 0xFFU);
2222 
2223     pStatus->PerformanceMove = (uint8_t)((sd_status[2] & 0xFF00U) >> 8U);
2224 
2225     pStatus->AllocationUnitSize = (uint8_t)((sd_status[2] & 0xF00000U) >> 20U);
2226 
2227     pStatus->EraseSize = (uint16_t)(((sd_status[2] & 0xFF000000U) >> 16U) | (sd_status[3] & 0xFFU));
2228 
2229     pStatus->EraseTimeout = (uint8_t)((sd_status[3] & 0xFC00U) >> 10U);
2230 
2231     pStatus->EraseOffset = (uint8_t)((sd_status[3] & 0x0300U) >> 8U);
2232   }
2233 
2234   return HAL_OK;
2235 }
2236 
2237 /**
2238   * @brief  Gets the SD card info.
2239   * @param  hsd: Pointer to SD handle
2240   * @param  pCardInfo: Pointer to the HAL_SD_CardInfoTypeDef structure that
2241   *         will contain the SD card status information
2242   * @retval HAL status
2243   */
HAL_SD_GetCardInfo(SD_HandleTypeDef * hsd,HAL_SD_CardInfoTypeDef * pCardInfo)2244 HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo)
2245 {
2246   pCardInfo->CardType     = (uint32_t)(hsd->SdCard.CardType);
2247   pCardInfo->CardVersion  = (uint32_t)(hsd->SdCard.CardVersion);
2248   pCardInfo->Class        = (uint32_t)(hsd->SdCard.Class);
2249   pCardInfo->RelCardAdd   = (uint32_t)(hsd->SdCard.RelCardAdd);
2250   pCardInfo->BlockNbr     = (uint32_t)(hsd->SdCard.BlockNbr);
2251   pCardInfo->BlockSize    = (uint32_t)(hsd->SdCard.BlockSize);
2252   pCardInfo->LogBlockNbr  = (uint32_t)(hsd->SdCard.LogBlockNbr);
2253   pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize);
2254 
2255   return HAL_OK;
2256 }
2257 
2258 /**
2259   * @brief  Enables wide bus operation for the requested card if supported by
2260   *         card.
2261   * @param  hsd: Pointer to SD handle
2262   * @param  WideMode: Specifies the SD card wide bus mode
2263   *          This parameter can be one of the following values:
2264   *            @arg SDIO_BUS_WIDE_8B: 8-bit data transfer
2265   *            @arg SDIO_BUS_WIDE_4B: 4-bit data transfer
2266   *            @arg SDIO_BUS_WIDE_1B: 1-bit data transfer
2267   * @retval HAL status
2268   */
HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef * hsd,uint32_t WideMode)2269 HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode)
2270 {
2271   SDIO_InitTypeDef Init;
2272   uint32_t errorstate;
2273 
2274   /* Check the parameters */
2275   assert_param(IS_SDIO_BUS_WIDE(WideMode));
2276 
2277   /* Change State */
2278   hsd->State = HAL_SD_STATE_BUSY;
2279 
2280   if(hsd->SdCard.CardType != CARD_SECURED)
2281   {
2282     if(WideMode == SDIO_BUS_WIDE_8B)
2283     {
2284       hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2285     }
2286     else if(WideMode == SDIO_BUS_WIDE_4B)
2287     {
2288       errorstate = SD_WideBus_Enable(hsd);
2289 
2290       hsd->ErrorCode |= errorstate;
2291     }
2292     else if(WideMode == SDIO_BUS_WIDE_1B)
2293     {
2294       errorstate = SD_WideBus_Disable(hsd);
2295 
2296       hsd->ErrorCode |= errorstate;
2297     }
2298     else
2299     {
2300       /* WideMode is not a valid argument*/
2301       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2302     }
2303   }
2304   else
2305   {
2306     /* MMC Card does not support this feature */
2307     hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2308   }
2309 
2310   if(hsd->ErrorCode != HAL_SD_ERROR_NONE)
2311   {
2312     /* Clear all the static flags */
2313     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2314     hsd->State = HAL_SD_STATE_READY;
2315     return HAL_ERROR;
2316   }
2317   else
2318   {
2319     /* Configure the SDIO peripheral */
2320     Init.ClockEdge           = hsd->Init.ClockEdge;
2321     Init.ClockBypass         = hsd->Init.ClockBypass;
2322     Init.ClockPowerSave      = hsd->Init.ClockPowerSave;
2323     Init.BusWide             = WideMode;
2324     Init.HardwareFlowControl = hsd->Init.HardwareFlowControl;
2325     Init.ClockDiv            = hsd->Init.ClockDiv;
2326     (void)SDIO_Init(hsd->Instance, Init);
2327   }
2328 
2329   /* Change State */
2330   hsd->State = HAL_SD_STATE_READY;
2331 
2332   return HAL_OK;
2333 }
2334 
2335 /**
2336   * @brief  Gets the current sd card data state.
2337   * @param  hsd: pointer to SD handle
2338   * @retval Card state
2339   */
HAL_SD_GetCardState(SD_HandleTypeDef * hsd)2340 HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd)
2341 {
2342   uint32_t cardstate;
2343   uint32_t errorstate;
2344   uint32_t resp1 = 0;
2345 
2346   errorstate = SD_SendStatus(hsd, &resp1);
2347   if(errorstate != HAL_SD_ERROR_NONE)
2348   {
2349     hsd->ErrorCode |= errorstate;
2350   }
2351 
2352   cardstate = ((resp1 >> 9U) & 0x0FU);
2353 
2354   return (HAL_SD_CardStateTypeDef)cardstate;
2355 }
2356 
2357 /**
2358   * @brief  Abort the current transfer and disable the SD.
2359   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
2360   *                the configuration information for SD module.
2361   * @retval HAL status
2362   */
HAL_SD_Abort(SD_HandleTypeDef * hsd)2363 HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd)
2364 {
2365   HAL_SD_CardStateTypeDef CardState;
2366   uint32_t context = hsd->Context;
2367 
2368   /* DIsable All interrupts */
2369   __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
2370                            SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR);
2371 
2372   /* Clear All flags */
2373   __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
2374 
2375   CLEAR_BIT(hsd->Instance->DCTRL, SDIO_DCTRL_DTEN);
2376 
2377   if ((context & SD_CONTEXT_DMA) != 0U)
2378   {
2379     /* Disable the SD DMA request */
2380     hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN);
2381 
2382     /* Abort the SD DMA Tx channel */
2383     if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
2384     {
2385       if(HAL_DMA_Abort(hsd->hdmatx) != HAL_OK)
2386       {
2387         hsd->ErrorCode |= HAL_SD_ERROR_DMA;
2388       }
2389     }
2390     /* Abort the SD DMA Rx channel */
2391     else if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
2392     {
2393       if(HAL_DMA_Abort(hsd->hdmarx) != HAL_OK)
2394       {
2395         hsd->ErrorCode |= HAL_SD_ERROR_DMA;
2396       }
2397     }
2398     else
2399     {
2400       /* Nothing to do */
2401     }
2402   }
2403 
2404   hsd->State = HAL_SD_STATE_READY;
2405 
2406   /* Initialize the SD operation */
2407   hsd->Context = SD_CONTEXT_NONE;
2408 
2409   CardState = HAL_SD_GetCardState(hsd);
2410   if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
2411   {
2412     hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance);
2413   }
2414   if(hsd->ErrorCode != HAL_SD_ERROR_NONE)
2415   {
2416     return HAL_ERROR;
2417   }
2418   return HAL_OK;
2419 }
2420 
2421 /**
2422   * @brief  Abort the current transfer and disable the SD (IT mode).
2423   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
2424   *                the configuration information for SD module.
2425   * @retval HAL status
2426   */
HAL_SD_Abort_IT(SD_HandleTypeDef * hsd)2427 HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd)
2428 {
2429   HAL_SD_CardStateTypeDef CardState;
2430   uint32_t context = hsd->Context;
2431 
2432   /* Disable All interrupts */
2433   __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
2434                            SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR);
2435 
2436   CLEAR_BIT(hsd->Instance->DCTRL, SDIO_DCTRL_DTEN);
2437 
2438   if ((context & SD_CONTEXT_DMA) != 0U)
2439   {
2440     /* Disable the SD DMA request */
2441     hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN);
2442 
2443     /* Abort the SD DMA Tx channel */
2444     if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
2445     {
2446       hsd->hdmatx->XferAbortCallback = SD_DMATxAbort;
2447       if(HAL_DMA_Abort_IT(hsd->hdmatx) != HAL_OK)
2448       {
2449         hsd->hdmatx = NULL;
2450       }
2451     }
2452     /* Abort the SD DMA Rx channel */
2453     else if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
2454     {
2455       hsd->hdmarx->XferAbortCallback = SD_DMARxAbort;
2456       if(HAL_DMA_Abort_IT(hsd->hdmarx) != HAL_OK)
2457       {
2458         hsd->hdmarx = NULL;
2459       }
2460     }
2461     else
2462     {
2463       /* Nothing to do */
2464     }
2465   }
2466   /* No transfer ongoing on both DMA channels*/
2467   else
2468   {
2469     /* Clear All flags */
2470     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
2471 
2472     CardState = HAL_SD_GetCardState(hsd);
2473     hsd->State = HAL_SD_STATE_READY;
2474     hsd->Context = SD_CONTEXT_NONE;
2475     if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
2476     {
2477       hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance);
2478     }
2479     if(hsd->ErrorCode != HAL_SD_ERROR_NONE)
2480     {
2481       return HAL_ERROR;
2482     }
2483     else
2484     {
2485 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
2486       hsd->AbortCpltCallback(hsd);
2487 #else
2488       HAL_SD_AbortCallback(hsd);
2489 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
2490     }
2491   }
2492 
2493   return HAL_OK;
2494 }
2495 
2496 /**
2497   * @}
2498   */
2499 
2500 /**
2501   * @}
2502   */
2503 
2504 /* Private function ----------------------------------------------------------*/
2505 /** @addtogroup SD_Private_Functions
2506   * @{
2507   */
2508 
2509 /**
2510   * @brief  DMA SD transmit process complete callback
2511   * @param  hdma: DMA handle
2512   * @retval None
2513   */
SD_DMATransmitCplt(DMA_HandleTypeDef * hdma)2514 static void SD_DMATransmitCplt(DMA_HandleTypeDef *hdma)
2515 {
2516   SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent);
2517 
2518   /* Enable DATAEND Interrupt */
2519   __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DATAEND));
2520 }
2521 
2522 /**
2523   * @brief  DMA SD receive process complete callback
2524   * @param  hdma: DMA handle
2525   * @retval None
2526   */
SD_DMAReceiveCplt(DMA_HandleTypeDef * hdma)2527 static void SD_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
2528 {
2529   SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent);
2530   uint32_t errorstate;
2531 
2532   /* Send stop command in multiblock write */
2533   if(hsd->Context == (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA))
2534   {
2535     errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
2536     if(errorstate != HAL_SD_ERROR_NONE)
2537     {
2538       hsd->ErrorCode |= errorstate;
2539 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2540       hsd->ErrorCallback(hsd);
2541 #else
2542       HAL_SD_ErrorCallback(hsd);
2543 #endif
2544     }
2545   }
2546 
2547   /* Disable the DMA transfer for transmit request by setting the DMAEN bit
2548   in the SD DCTRL register */
2549   hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN);
2550 
2551   /* Clear all the static flags */
2552   __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
2553 
2554   hsd->State = HAL_SD_STATE_READY;
2555   hsd->Context = SD_CONTEXT_NONE;
2556 
2557 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2558   hsd->RxCpltCallback(hsd);
2559 #else
2560   HAL_SD_RxCpltCallback(hsd);
2561 #endif
2562 }
2563 
2564 /**
2565   * @brief  DMA SD communication error callback
2566   * @param  hdma: DMA handle
2567   * @retval None
2568   */
SD_DMAError(DMA_HandleTypeDef * hdma)2569 static void SD_DMAError(DMA_HandleTypeDef *hdma)
2570 {
2571   SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent);
2572   HAL_SD_CardStateTypeDef CardState;
2573   uint32_t RxErrorCode, TxErrorCode;
2574 
2575   /* if DMA error is FIFO error ignore it */
2576   if(HAL_DMA_GetError(hdma) != HAL_DMA_ERROR_FE)
2577   {
2578     RxErrorCode = hsd->hdmarx->ErrorCode;
2579     TxErrorCode = hsd->hdmatx->ErrorCode;
2580     if((RxErrorCode == HAL_DMA_ERROR_TE) || (TxErrorCode == HAL_DMA_ERROR_TE))
2581     {
2582       /* Clear All flags */
2583       __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2584 
2585       /* Disable All interrupts */
2586       __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\
2587         SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR);
2588 
2589       hsd->ErrorCode |= HAL_SD_ERROR_DMA;
2590       CardState = HAL_SD_GetCardState(hsd);
2591       if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
2592       {
2593         hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance);
2594       }
2595 
2596       hsd->State= HAL_SD_STATE_READY;
2597       hsd->Context = SD_CONTEXT_NONE;
2598     }
2599 
2600 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2601     hsd->ErrorCallback(hsd);
2602 #else
2603     HAL_SD_ErrorCallback(hsd);
2604 #endif
2605   }
2606 }
2607 
2608 /**
2609   * @brief  DMA SD Tx Abort callback
2610   * @param  hdma: DMA handle
2611   * @retval None
2612   */
SD_DMATxAbort(DMA_HandleTypeDef * hdma)2613 static void SD_DMATxAbort(DMA_HandleTypeDef *hdma)
2614 {
2615   SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent);
2616   HAL_SD_CardStateTypeDef CardState;
2617 
2618   /* Clear All flags */
2619   __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
2620 
2621   CardState = HAL_SD_GetCardState(hsd);
2622   hsd->State = HAL_SD_STATE_READY;
2623   hsd->Context = SD_CONTEXT_NONE;
2624   if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
2625   {
2626     hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance);
2627   }
2628 
2629   if(hsd->ErrorCode == HAL_SD_ERROR_NONE)
2630   {
2631 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2632     hsd->AbortCpltCallback(hsd);
2633 #else
2634     HAL_SD_AbortCallback(hsd);
2635 #endif
2636   }
2637   else
2638   {
2639 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2640     hsd->ErrorCallback(hsd);
2641 #else
2642     HAL_SD_ErrorCallback(hsd);
2643 #endif
2644   }
2645 }
2646 
2647 /**
2648   * @brief  DMA SD Rx Abort callback
2649   * @param  hdma: DMA handle
2650   * @retval None
2651   */
SD_DMARxAbort(DMA_HandleTypeDef * hdma)2652 static void SD_DMARxAbort(DMA_HandleTypeDef *hdma)
2653 {
2654   SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent);
2655   HAL_SD_CardStateTypeDef CardState;
2656 
2657   /* Clear All flags */
2658   __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
2659 
2660   CardState = HAL_SD_GetCardState(hsd);
2661   hsd->State = HAL_SD_STATE_READY;
2662   hsd->Context = SD_CONTEXT_NONE;
2663   if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
2664   {
2665     hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance);
2666   }
2667 
2668   if(hsd->ErrorCode == HAL_SD_ERROR_NONE)
2669   {
2670 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2671     hsd->AbortCpltCallback(hsd);
2672 #else
2673     HAL_SD_AbortCallback(hsd);
2674 #endif
2675   }
2676   else
2677   {
2678 #if (USE_HAL_SD_REGISTER_CALLBACKS == 1)
2679     hsd->ErrorCallback(hsd);
2680 #else
2681     HAL_SD_ErrorCallback(hsd);
2682 #endif
2683   }
2684 }
2685 
2686 /**
2687   * @brief  Initializes the sd card.
2688   * @param  hsd: Pointer to SD handle
2689   * @retval SD Card error state
2690   */
SD_InitCard(SD_HandleTypeDef * hsd)2691 static uint32_t SD_InitCard(SD_HandleTypeDef *hsd)
2692 {
2693   HAL_SD_CardCSDTypeDef CSD;
2694   uint32_t errorstate;
2695   uint16_t sd_rca = 1U;
2696 
2697   /* Check the power State */
2698   if(SDIO_GetPowerState(hsd->Instance) == 0U)
2699   {
2700     /* Power off */
2701     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
2702   }
2703 
2704   if(hsd->SdCard.CardType != CARD_SECURED)
2705   {
2706     /* Send CMD2 ALL_SEND_CID */
2707     errorstate = SDMMC_CmdSendCID(hsd->Instance);
2708     if(errorstate != HAL_SD_ERROR_NONE)
2709     {
2710       return errorstate;
2711     }
2712     else
2713     {
2714       /* Get Card identification number data */
2715       hsd->CID[0U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP1);
2716       hsd->CID[1U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP2);
2717       hsd->CID[2U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP3);
2718       hsd->CID[3U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP4);
2719     }
2720   }
2721 
2722   if(hsd->SdCard.CardType != CARD_SECURED)
2723   {
2724     /* Send CMD3 SET_REL_ADDR with argument 0 */
2725     /* SD Card publishes its RCA. */
2726     errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca);
2727     if(errorstate != HAL_SD_ERROR_NONE)
2728     {
2729       return errorstate;
2730     }
2731   }
2732   if(hsd->SdCard.CardType != CARD_SECURED)
2733   {
2734     /* Get the SD card RCA */
2735     hsd->SdCard.RelCardAdd = sd_rca;
2736 
2737     /* Send CMD9 SEND_CSD with argument as card's RCA */
2738     errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
2739     if(errorstate != HAL_SD_ERROR_NONE)
2740     {
2741       return errorstate;
2742     }
2743     else
2744     {
2745       /* Get Card Specific Data */
2746       hsd->CSD[0U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP1);
2747       hsd->CSD[1U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP2);
2748       hsd->CSD[2U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP3);
2749       hsd->CSD[3U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP4);
2750     }
2751   }
2752 
2753   /* Get the Card Class */
2754   hsd->SdCard.Class = (SDIO_GetResponse(hsd->Instance, SDIO_RESP2) >> 20U);
2755 
2756   /* Get CSD parameters */
2757   if (HAL_SD_GetCardCSD(hsd, &CSD) != HAL_OK)
2758   {
2759     return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2760   }
2761 
2762   /* Select the Card */
2763   errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U));
2764   if(errorstate != HAL_SD_ERROR_NONE)
2765   {
2766     return errorstate;
2767   }
2768 
2769   /* Configure SDIO peripheral interface */
2770   (void)SDIO_Init(hsd->Instance, hsd->Init);
2771 
2772   /* All cards are initialized */
2773   return HAL_SD_ERROR_NONE;
2774 }
2775 
2776 /**
2777   * @brief  Enquires cards about their operating voltage and configures clock
2778   *         controls and stores SD information that will be needed in future
2779   *         in the SD handle.
2780   * @param  hsd: Pointer to SD handle
2781   * @retval error state
2782   */
SD_PowerON(SD_HandleTypeDef * hsd)2783 static uint32_t SD_PowerON(SD_HandleTypeDef *hsd)
2784 {
2785   __IO uint32_t count = 0U;
2786   uint32_t response = 0U, validvoltage = 0U;
2787   uint32_t errorstate;
2788 
2789   /* CMD0: GO_IDLE_STATE */
2790   errorstate = SDMMC_CmdGoIdleState(hsd->Instance);
2791   if(errorstate != HAL_SD_ERROR_NONE)
2792   {
2793     return errorstate;
2794   }
2795 
2796   /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */
2797   errorstate = SDMMC_CmdOperCond(hsd->Instance);
2798   if(errorstate != HAL_SD_ERROR_NONE)
2799   {
2800     hsd->SdCard.CardVersion = CARD_V1_X;
2801     /* CMD0: GO_IDLE_STATE */
2802     errorstate = SDMMC_CmdGoIdleState(hsd->Instance);
2803     if(errorstate != HAL_SD_ERROR_NONE)
2804     {
2805       return errorstate;
2806     }
2807 
2808   }
2809   else
2810   {
2811     hsd->SdCard.CardVersion = CARD_V2_X;
2812   }
2813 
2814   if( hsd->SdCard.CardVersion == CARD_V2_X)
2815   {
2816     /* SEND CMD55 APP_CMD with RCA as 0 */
2817     errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0);
2818     if(errorstate != HAL_SD_ERROR_NONE)
2819     {
2820       return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2821     }
2822   }
2823   /* SD CARD */
2824   /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */
2825   while((count < SDMMC_MAX_VOLT_TRIAL) && (validvoltage == 0U))
2826   {
2827     /* SEND CMD55 APP_CMD with RCA as 0 */
2828     errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0);
2829     if(errorstate != HAL_SD_ERROR_NONE)
2830     {
2831       return errorstate;
2832     }
2833 
2834     /* Send CMD41 */
2835     errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_VOLTAGE_WINDOW_SD | SDMMC_HIGH_CAPACITY | SD_SWITCH_1_8V_CAPACITY);
2836     if(errorstate != HAL_SD_ERROR_NONE)
2837     {
2838       return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2839     }
2840 
2841     /* Get command response */
2842     response = SDIO_GetResponse(hsd->Instance, SDIO_RESP1);
2843 
2844     /* Get operating voltage*/
2845     validvoltage = (((response >> 31U) == 1U) ? 1U : 0U);
2846 
2847     count++;
2848   }
2849 
2850   if(count >= SDMMC_MAX_VOLT_TRIAL)
2851   {
2852     return HAL_SD_ERROR_INVALID_VOLTRANGE;
2853   }
2854 
2855   if((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY) /* (response &= SD_HIGH_CAPACITY) */
2856   {
2857     hsd->SdCard.CardType = CARD_SDHC_SDXC;
2858   }
2859   else
2860   {
2861     hsd->SdCard.CardType = CARD_SDSC;
2862   }
2863 
2864 
2865   return HAL_SD_ERROR_NONE;
2866 }
2867 
2868 /**
2869   * @brief  Turns the SDIO output signals off.
2870   * @param  hsd: Pointer to SD handle
2871   * @retval None
2872   */
SD_PowerOFF(SD_HandleTypeDef * hsd)2873 static void SD_PowerOFF(SD_HandleTypeDef *hsd)
2874 {
2875   /* Set Power State to OFF */
2876   (void)SDIO_PowerState_OFF(hsd->Instance);
2877 }
2878 
2879 /**
2880   * @brief  Send Status info command.
2881   * @param  hsd: pointer to SD handle
2882   * @param  pSDstatus: Pointer to the buffer that will contain the SD card status
2883   *         SD Status register)
2884   * @retval error state
2885   */
SD_SendSDStatus(SD_HandleTypeDef * hsd,uint32_t * pSDstatus)2886 static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus)
2887 {
2888   SDIO_DataInitTypeDef config;
2889   uint32_t errorstate;
2890   uint32_t tickstart = HAL_GetTick();
2891   uint32_t count;
2892   uint32_t *pData = pSDstatus;
2893 
2894   /* Check SD response */
2895   if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
2896   {
2897     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
2898   }
2899 
2900   /* Set block size for card if it is not equal to current block size for card */
2901   errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
2902   if(errorstate != HAL_SD_ERROR_NONE)
2903   {
2904     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
2905     return errorstate;
2906   }
2907 
2908   /* Send CMD55 */
2909   errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
2910   if(errorstate != HAL_SD_ERROR_NONE)
2911   {
2912     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
2913     return errorstate;
2914   }
2915 
2916   /* Configure the SD DPSM (Data Path State Machine) */
2917   config.DataTimeOut   = SDMMC_DATATIMEOUT;
2918   config.DataLength    = 64U;
2919   config.DataBlockSize = SDIO_DATABLOCK_SIZE_64B;
2920   config.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
2921   config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
2922   config.DPSM          = SDIO_DPSM_ENABLE;
2923   (void)SDIO_ConfigData(hsd->Instance, &config);
2924 
2925   /* Send ACMD13 (SD_APP_STAUS)  with argument as card's RCA */
2926   errorstate = SDMMC_CmdStatusRegister(hsd->Instance);
2927   if(errorstate != HAL_SD_ERROR_NONE)
2928   {
2929     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
2930     return errorstate;
2931   }
2932 
2933   /* Get status data */
2934   while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND))
2935   {
2936     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
2937     {
2938       for(count = 0U; count < 8U; count++)
2939       {
2940         *pData = SDIO_ReadFIFO(hsd->Instance);
2941         pData++;
2942       }
2943     }
2944 
2945     if((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
2946     {
2947       return HAL_SD_ERROR_TIMEOUT;
2948     }
2949   }
2950 
2951   if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
2952   {
2953     return HAL_SD_ERROR_DATA_TIMEOUT;
2954   }
2955   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
2956   {
2957     return HAL_SD_ERROR_DATA_CRC_FAIL;
2958   }
2959   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
2960   {
2961     return HAL_SD_ERROR_RX_OVERRUN;
2962   }
2963   else
2964   {
2965     /* Nothing to do */
2966   }
2967 
2968   while ((__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)))
2969   {
2970     *pData = SDIO_ReadFIFO(hsd->Instance);
2971     pData++;
2972 
2973     if((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
2974     {
2975       return HAL_SD_ERROR_TIMEOUT;
2976     }
2977   }
2978 
2979   /* Clear all the static status flags*/
2980   __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
2981 
2982   return HAL_SD_ERROR_NONE;
2983 }
2984 
2985 /**
2986   * @brief  Returns the current card's status.
2987   * @param  hsd: Pointer to SD handle
2988   * @param  pCardStatus: pointer to the buffer that will contain the SD card
2989   *         status (Card Status register)
2990   * @retval error state
2991   */
SD_SendStatus(SD_HandleTypeDef * hsd,uint32_t * pCardStatus)2992 static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus)
2993 {
2994   uint32_t errorstate;
2995 
2996   if(pCardStatus == NULL)
2997   {
2998     return HAL_SD_ERROR_PARAM;
2999   }
3000 
3001   /* Send Status command */
3002   errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3003   if(errorstate != HAL_SD_ERROR_NONE)
3004   {
3005     return errorstate;
3006   }
3007 
3008   /* Get SD card status */
3009   *pCardStatus = SDIO_GetResponse(hsd->Instance, SDIO_RESP1);
3010 
3011   return HAL_SD_ERROR_NONE;
3012 }
3013 
3014 /**
3015   * @brief  Enables the SDIO wide bus mode.
3016   * @param  hsd: pointer to SD handle
3017   * @retval error state
3018   */
SD_WideBus_Enable(SD_HandleTypeDef * hsd)3019 static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd)
3020 {
3021   uint32_t scr[2U] = {0U, 0U};
3022   uint32_t errorstate;
3023 
3024   if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3025   {
3026     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3027   }
3028 
3029   /* Get SCR Register */
3030   errorstate = SD_FindSCR(hsd, scr);
3031   if(errorstate != HAL_SD_ERROR_NONE)
3032   {
3033     return errorstate;
3034   }
3035 
3036   /* If requested card supports wide bus operation */
3037   if((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO)
3038   {
3039     /* Send CMD55 APP_CMD with argument as card's RCA.*/
3040     errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3041     if(errorstate != HAL_SD_ERROR_NONE)
3042     {
3043       return errorstate;
3044     }
3045 
3046     /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
3047     errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U);
3048     if(errorstate != HAL_SD_ERROR_NONE)
3049     {
3050       return errorstate;
3051     }
3052 
3053     return HAL_SD_ERROR_NONE;
3054   }
3055   else
3056   {
3057     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3058   }
3059 }
3060 
3061 /**
3062   * @brief  Disables the SDIO wide bus mode.
3063   * @param  hsd: Pointer to SD handle
3064   * @retval error state
3065   */
SD_WideBus_Disable(SD_HandleTypeDef * hsd)3066 static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd)
3067 {
3068   uint32_t scr[2U] = {0U, 0U};
3069   uint32_t errorstate;
3070 
3071   if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3072   {
3073     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3074   }
3075 
3076   /* Get SCR Register */
3077   errorstate = SD_FindSCR(hsd, scr);
3078   if(errorstate != HAL_SD_ERROR_NONE)
3079   {
3080     return errorstate;
3081   }
3082 
3083   /* If requested card supports 1 bit mode operation */
3084   if((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO)
3085   {
3086     /* Send CMD55 APP_CMD with argument as card's RCA */
3087     errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3088     if(errorstate != HAL_SD_ERROR_NONE)
3089     {
3090       return errorstate;
3091     }
3092 
3093     /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */
3094     errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U);
3095     if(errorstate != HAL_SD_ERROR_NONE)
3096     {
3097       return errorstate;
3098     }
3099 
3100     return HAL_SD_ERROR_NONE;
3101   }
3102   else
3103   {
3104     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3105   }
3106 }
3107 
3108 
3109 /**
3110   * @brief  Finds the SD card SCR register value.
3111   * @param  hsd: Pointer to SD handle
3112   * @param  pSCR: pointer to the buffer that will contain the SCR value
3113   * @retval error state
3114   */
SD_FindSCR(SD_HandleTypeDef * hsd,uint32_t * pSCR)3115 static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR)
3116 {
3117   SDIO_DataInitTypeDef config;
3118   uint32_t errorstate;
3119   uint32_t tickstart = HAL_GetTick();
3120   uint32_t index = 0U;
3121   uint32_t tempscr[2U] = {0U, 0U};
3122   uint32_t *scr = pSCR;
3123 
3124   /* Set Block Size To 8 Bytes */
3125   errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U);
3126   if(errorstate != HAL_SD_ERROR_NONE)
3127   {
3128     return errorstate;
3129   }
3130 
3131   /* Send CMD55 APP_CMD with argument as card's RCA */
3132   errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U));
3133   if(errorstate != HAL_SD_ERROR_NONE)
3134   {
3135     return errorstate;
3136   }
3137 
3138   config.DataTimeOut   = SDMMC_DATATIMEOUT;
3139   config.DataLength    = 8U;
3140   config.DataBlockSize = SDIO_DATABLOCK_SIZE_8B;
3141   config.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
3142   config.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
3143   config.DPSM          = SDIO_DPSM_ENABLE;
3144   (void)SDIO_ConfigData(hsd->Instance, &config);
3145 
3146   /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */
3147   errorstate = SDMMC_CmdSendSCR(hsd->Instance);
3148   if(errorstate != HAL_SD_ERROR_NONE)
3149   {
3150     return errorstate;
3151   }
3152 
3153   while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND))
3154   {
3155     if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL))
3156     {
3157       *(tempscr + index) = SDIO_ReadFIFO(hsd->Instance);
3158       index++;
3159     }
3160 
3161     if((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
3162     {
3163       return HAL_SD_ERROR_TIMEOUT;
3164     }
3165   }
3166 
3167   if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
3168   {
3169     __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
3170 
3171     return HAL_SD_ERROR_DATA_TIMEOUT;
3172   }
3173   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
3174   {
3175     __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
3176 
3177     return HAL_SD_ERROR_DATA_CRC_FAIL;
3178   }
3179   else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
3180   {
3181     __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
3182 
3183     return HAL_SD_ERROR_RX_OVERRUN;
3184   }
3185   else
3186   {
3187     /* No error flag set */
3188     /* Clear all the static flags */
3189     __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_DATA_FLAGS);
3190 
3191     *scr = (((tempscr[1] & SDMMC_0TO7BITS) << 24)  | ((tempscr[1] & SDMMC_8TO15BITS) << 8) |\
3192             ((tempscr[1] & SDMMC_16TO23BITS) >> 8) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24));
3193     scr++;
3194     *scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24)  | ((tempscr[0] & SDMMC_8TO15BITS) << 8) |\
3195             ((tempscr[0] & SDMMC_16TO23BITS) >> 8) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24));
3196 
3197   }
3198 
3199   return HAL_SD_ERROR_NONE;
3200 }
3201 
3202 /**
3203   * @brief  Wrap up reading in non-blocking mode.
3204   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
3205   *              the configuration information.
3206   * @retval None
3207   */
SD_Read_IT(SD_HandleTypeDef * hsd)3208 static void SD_Read_IT(SD_HandleTypeDef *hsd)
3209 {
3210   uint32_t count, data, dataremaining;
3211   uint8_t* tmp;
3212 
3213   tmp = hsd->pRxBuffPtr;
3214   dataremaining = hsd->RxXferSize;
3215 
3216   if (dataremaining > 0U)
3217   {
3218     /* Read data from SDIO Rx FIFO */
3219     for(count = 0U; count < 8U; count++)
3220     {
3221       data = SDIO_ReadFIFO(hsd->Instance);
3222       *tmp = (uint8_t)(data & 0xFFU);
3223       tmp++;
3224       dataremaining--;
3225       *tmp = (uint8_t)((data >> 8U) & 0xFFU);
3226       tmp++;
3227       dataremaining--;
3228       *tmp = (uint8_t)((data >> 16U) & 0xFFU);
3229       tmp++;
3230       dataremaining--;
3231       *tmp = (uint8_t)((data >> 24U) & 0xFFU);
3232       tmp++;
3233       dataremaining--;
3234     }
3235 
3236     hsd->pRxBuffPtr = tmp;
3237     hsd->RxXferSize = dataremaining;
3238   }
3239 }
3240 
3241 /**
3242   * @brief  Wrap up writing in non-blocking mode.
3243   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
3244   *              the configuration information.
3245   * @retval None
3246   */
SD_Write_IT(SD_HandleTypeDef * hsd)3247 static void SD_Write_IT(SD_HandleTypeDef *hsd)
3248 {
3249   uint32_t count, data, dataremaining;
3250   uint8_t* tmp;
3251 
3252   tmp = hsd->pTxBuffPtr;
3253   dataremaining = hsd->TxXferSize;
3254 
3255   if (dataremaining > 0U)
3256   {
3257     /* Write data to SDIO Tx FIFO */
3258     for(count = 0U; count < 8U; count++)
3259     {
3260       data = (uint32_t)(*tmp);
3261       tmp++;
3262       dataremaining--;
3263       data |= ((uint32_t)(*tmp) << 8U);
3264       tmp++;
3265       dataremaining--;
3266       data |= ((uint32_t)(*tmp) << 16U);
3267       tmp++;
3268       dataremaining--;
3269       data |= ((uint32_t)(*tmp) << 24U);
3270       tmp++;
3271       dataremaining--;
3272       (void)SDIO_WriteFIFO(hsd->Instance, &data);
3273     }
3274 
3275     hsd->pTxBuffPtr = tmp;
3276     hsd->TxXferSize = dataremaining;
3277   }
3278 }
3279 
3280 /**
3281   * @}
3282   */
3283 
3284 #endif /* HAL_SD_MODULE_ENABLED */
3285 
3286 /**
3287   * @}
3288   */
3289 
3290 /**
3291   * @}
3292   */
3293 
3294 #endif /* SDIO */
3295 
3296 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
3297