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