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