1 /**
2   ******************************************************************************
3   * @file    stm32h7rsxx_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) 2022 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 (SDMMC 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 SDMMC memories which uses the HAL
38     SDMMC driver functions to interface with SD and uSD cards devices.
39     It is used as follows:
40 
41     (#)Initialize the SDMMC low level resources by implementing the HAL_SD_MspInit() API:
42         (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE();
43         (##) SDMMC pins configuration for SD card
44             (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE();
45             (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init()
46                   and according to your pin assignment;
47         (##) NVIC configuration if you need to use interrupt process (HAL_SD_ReadBlocks_IT()
48              and HAL_SD_WriteBlocks_IT() APIs).
49             (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority();
50             (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ()
51             (+++) SDMMC interrupts are managed using the macros __HAL_SD_ENABLE_IT()
52                   and __HAL_SD_DISABLE_IT() inside the communication process.
53             (+++) SDMMC interrupts pending bits are managed using the macros __HAL_SD_GET_IT()
54                   and __HAL_SD_CLEAR_IT()
55         (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used.
56 
57     (#) At this stage, you can perform SD read/write/erase operations after SD card initialization
58 
59   *** SD Card Initialization and configuration ***
60   ================================================
61   [..]
62     To initialize the SD Card, use the HAL_SD_Init() function. It Initializes
63     SDMMC Peripheral(STM32 side) and the SD Card, and put it into StandBy State (Ready for data transfer).
64     This function provide the following operations:
65 
66     (#) Apply the SD Card initialization process at 400KHz and check the SD Card
67         type (Standard Capacity or High Capacity). You can change or adapt this
68         frequency by adjusting the "ClockDiv" field.
69         The SD Card frequency (SDMMC_CK) is computed as follows:
70 
71            SDMMC_CK = SDMMCCLK / (2 * ClockDiv)
72 
73         In initialization mode and according to the SD Card standard,
74         make sure that the SDMMC_CK frequency doesn't exceed 400KHz.
75 
76         This phase of initialization is done through SDMMC_Init() and
77         SDMMC_PowerState_ON() SDMMC low level APIs.
78 
79     (#) Initialize the SD card. The API used is HAL_SD_InitCard().
80         This phase allows the card initialization and identification
81         and check the SD Card type (Standard Capacity or High Capacity)
82         The initialization flow is compatible with SD standard.
83 
84         This API (HAL_SD_InitCard()) could be used also to reinitialize the card in case
85         of plug-off plug-in.
86 
87     (#) Configure the SD Card Data transfer frequency. You can change or adapt this
88         frequency by adjusting the "ClockDiv" field.
89         In transfer mode and according to the SD Card standard, make sure that the
90         SDMMC_CK frequency doesn't exceed 25MHz and 100MHz in High-speed mode switch.
91 
92     (#) Select the corresponding SD Card according to the address read with the step 2.
93 
94     (#) Configure the SD Card in wide bus mode: 4-bits data.
95 
96   *** SD Card Read operation ***
97   ==============================
98   [..]
99     (+) You can read from SD card in polling mode by using function HAL_SD_ReadBlocks().
100         This function support only 512-bytes block length (the block size should be
101         chosen as 512 bytes).
102         You can choose either one block read operation or multiple block read operation
103         by adjusting the "NumberOfBlocks" parameter.
104         After this, you have to ensure that the transfer is done correctly. The check is done
105         through HAL_SD_GetCardState() function for SD card state.
106 
107     (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA().
108         This function support only 512-bytes block length (the block size should be
109         chosen as 512 bytes).
110         You can choose either one block read operation or multiple block read operation
111         by adjusting the "NumberOfBlocks" parameter.
112         After this, you have to ensure that the transfer is done correctly. The check is done
113         through HAL_SD_GetCardState() function for SD card state.
114         You could also check the DMA transfer process through the SD Rx interrupt event.
115 
116     (+) You can read from SD card in Interrupt mode by using function HAL_SD_ReadBlocks_IT().
117         This function support only 512-bytes block length (the block size should be
118         chosen as 512 bytes).
119         You can choose either one block read operation or multiple block read operation
120         by adjusting the "NumberOfBlocks" parameter.
121         After this, you have to ensure that the transfer is done correctly. The check is done
122         through HAL_SD_GetCardState() function for SD card state.
123         You could also check the IT transfer process through the SD Rx interrupt event.
124 
125   *** SD Card Write operation ***
126   ===============================
127   [..]
128     (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks().
129         This function support only 512-bytes block length (the block size should be
130         chosen as 512 bytes).
131         You can choose either one block read operation or multiple block read operation
132         by adjusting the "NumberOfBlocks" parameter.
133         After this, you have to ensure that the transfer is done correctly. The check is done
134         through HAL_SD_GetCardState() function for SD card state.
135 
136     (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA().
137         This function support only 512-bytes block length (the block size should be
138         chosen as 512 bytes).
139         You can choose either one block read operation or multiple block read operation
140         by adjusting the "NumberOfBlocks" parameter.
141         After this, you have to ensure that the transfer is done correctly. The check is done
142         through HAL_SD_GetCardState() function for SD card state.
143         You could also check the DMA transfer process through the SD Tx interrupt event.
144 
145     (+) You can write to SD card in Interrupt mode by using function HAL_SD_WriteBlocks_IT().
146         This function support only 512-bytes block length (the block size should be
147         chosen as 512 bytes).
148         You can choose either one block read operation or multiple block read operation
149         by adjusting the "NumberOfBlocks" parameter.
150         After this, you have to ensure that the transfer is done correctly. The check is done
151         through HAL_SD_GetCardState() function for SD card state.
152         You could also check the IT transfer process through the SD Tx interrupt event.
153 
154   *** SD card status ***
155   ======================
156   [..]
157     (+) The SD Status contains status bits that are related to the SD Memory
158         Card proprietary features. To get SD card status use the HAL_SD_GetCardStatus().
159 
160   *** SD card information ***
161   ===========================
162   [..]
163     (+) To get SD card information, you can use the function HAL_SD_GetCardInfo().
164         It returns useful information about the SD card such as block size, card type,
165         block number ...
166 
167   *** SD card CSD register ***
168   ============================
169     (+) The HAL_SD_GetCardCSD() API allows to get the parameters of the CSD register.
170         Some of the CSD parameters are useful for card initialization and identification.
171 
172   *** SD card CID register ***
173   ============================
174     (+) The HAL_SD_GetCardCID() API allows to get the parameters of the CID register.
175         Some of the CSD parameters are useful for card initialization and identification.
176 
177   *** SD HAL driver macros list ***
178   ==================================
179   [..]
180     Below the list of most used macros in SD HAL driver.
181 
182     (+) __HAL_SD_ENABLE_IT: Enable the SD device interrupt
183     (+) __HAL_SD_DISABLE_IT: Disable the SD device interrupt
184     (+) __HAL_SD_GET_FLAG:Check whether the specified SD flag is set or not
185     (+) __HAL_SD_CLEAR_FLAG: Clear the SD's pending flags
186 
187     (@) You can refer to the SD HAL driver header file for more useful macros
188 
189   *** Callback registration ***
190   =============================================
191   [..]
192     The compilation define USE_HAL_SD_REGISTER_CALLBACKS when set to 1
193     allows the user to configure dynamically the driver callbacks.
194 
195     Use Functions HAL_SD_RegisterCallback() to register a user callback,
196     it allows to register following callbacks:
197       (+) TxCpltCallback : callback when a transmission transfer is completed.
198       (+) RxCpltCallback : callback when a reception transfer is completed.
199       (+) ErrorCallback : callback when error occurs.
200       (+) AbortCpltCallback : callback when abort is completed.
201       (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed.
202       (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed.
203       (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed.
204       (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed.
205       (+) MspInitCallback    : SD MspInit.
206       (+) MspDeInitCallback  : SD MspDeInit.
207     This function takes as parameters the HAL peripheral handle, the Callback ID
208     and a pointer to the user callback function.
209     For specific callbacks TransceiverCallback use dedicated register callbacks:
210     respectively HAL_SD_RegisterTransceiverCallback().
211 
212     Use function HAL_SD_UnRegisterCallback() to reset a callback to the default
213     weak (overridden) function. It allows to reset following callbacks:
214       (+) TxCpltCallback : callback when a transmission transfer is completed.
215       (+) RxCpltCallback : callback when a reception transfer is completed.
216       (+) ErrorCallback : callback when error occurs.
217       (+) AbortCpltCallback : callback when abort is completed.
218       (+) Read_DMALnkLstBufCpltCallback : callback when the DMA reception of linked list node buffer is completed.
219       (+) Write_DMALnkLstBufCpltCallback : callback when the DMA transmission of linked list node buffer is completed.
220       (+) MspInitCallback    : SD MspInit.
221       (+) MspDeInitCallback  : SD MspDeInit.
222     This function) takes as parameters the HAL peripheral handle and the Callback ID.
223     For specific callbacks TransceiverCallback use dedicated unregister callbacks:
224     respectively HAL_SD_UnRegisterTransceiverCallback().
225 
226     By default, after the HAL_SD_Init and if the state is HAL_SD_STATE_RESET
227     all callbacks are reset to the corresponding legacy weak (overridden) functions.
228     Exception done for MspInit and MspDeInit callbacks that are respectively
229     reset to the legacy weak (overridden) functions in the HAL_SD_Init
230     and HAL_SD_DeInit only when these callbacks are null (not registered beforehand).
231     If not, MspInit or MspDeInit are not null, the HAL_SD_Init and HAL_SD_DeInit
232     keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
233 
234     Callbacks can be registered/unregistered in READY state only.
235     Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered
236     in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used
237     during the Init/DeInit.
238     In that case first register the MspInit/MspDeInit user callbacks
239     using HAL_SD_RegisterCallback before calling HAL_SD_DeInit
240     or HAL_SD_Init function.
241 
242     When The compilation define USE_HAL_SD_REGISTER_CALLBACKS is set to 0 or
243     not defined, the callback registering feature is not available
244     and weak (overridden) callbacks are used.
245 
246   @endverbatim
247   ******************************************************************************
248   */
249 
250 /* Includes ------------------------------------------------------------------*/
251 #include "stm32h7rsxx_hal.h"
252 
253 /** @addtogroup STM32H7RSxx_HAL_Driver
254   * @{
255   */
256 
257 /** @addtogroup SD
258   * @{
259   */
260 
261 #if defined (SDMMC1) || defined (SDMMC2)
262 #ifdef HAL_SD_MODULE_ENABLED
263 
264 /* Private typedef -----------------------------------------------------------*/
265 /* Private define ------------------------------------------------------------*/
266 /** @addtogroup SD_Private_Defines
267   * @{
268   */
269 /* Frequencies used in the driver for clock divider calculation */
270 #define SD_INIT_FREQ                   400000U   /* Initialization phase : 400 kHz max */
271 #define SD_NORMAL_SPEED_FREQ           25000000U /* Normal speed phase : 25 MHz max */
272 #define SD_HIGH_SPEED_FREQ             50000000U /* High speed phase : 50 MHz max */
273 /* Private macro -------------------------------------------------------------*/
274 #if defined (DLYB_SDMMC1) && defined (DLYB_SDMMC2)
275 #define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) (((SDMMC_INSTANCE) == SDMMC1)?  \
276                                               DLYB_SDMMC1 : DLYB_SDMMC2 )
277 #elif defined (DLYB_SDMMC1)
278 #define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) ( DLYB_SDMMC1 )
279 #endif /* (DLYB_SDMMC1) && defined (DLYB_SDMMC2) */
280 
281 /**
282   * @}
283   */
284 
285 /* Private variables ---------------------------------------------------------*/
286 /* Private function prototypes -----------------------------------------------*/
287 /* Private functions ---------------------------------------------------------*/
288 /** @defgroup SD_Private_Functions SD Private Functions
289   * @{
290   */
291 static uint32_t SD_InitCard(SD_HandleTypeDef *hsd);
292 static uint32_t SD_PowerON(SD_HandleTypeDef *hsd);
293 static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus);
294 static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus);
295 static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd);
296 static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd);
297 static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR);
298 static void     SD_PowerOFF(SD_HandleTypeDef *hsd);
299 static void     SD_Write_IT(SD_HandleTypeDef *hsd);
300 static void     SD_Read_IT(SD_HandleTypeDef *hsd);
301 static uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode);
302 #if (USE_SD_TRANSCEIVER != 0U)
303 static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode);
304 static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd);
305 #endif /* USE_SD_TRANSCEIVER */
306 /**
307   * @}
308   */
309 
310 /* Exported functions --------------------------------------------------------*/
311 /** @addtogroup SD_Exported_Functions
312   * @{
313   */
314 
315 /** @addtogroup SD_Exported_Functions_Group1
316   *  @brief   Initialization and de-initialization functions
317   *
318 @verbatim
319   ==============================================================================
320           ##### Initialization and de-initialization functions #####
321   ==============================================================================
322   [..]
323     This section provides functions allowing to initialize/de-initialize the SD
324     card device to be ready for use.
325 
326 @endverbatim
327   * @{
328   */
329 
330 /**
331   * @brief  Initializes the SD according to the specified parameters in the
332             SD_HandleTypeDef and create the associated handle.
333   * @param  hsd: Pointer to the SD handle
334   * @retval HAL status
335   */
HAL_SD_Init(SD_HandleTypeDef * hsd)336 HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd)
337 {
338   HAL_SD_CardStatusTypeDef CardStatus;
339   uint32_t speedgrade;
340   uint32_t unitsize;
341   uint32_t tickstart;
342 
343   /* Check the SD handle allocation */
344   if (hsd == NULL)
345   {
346     return HAL_ERROR;
347   }
348 
349   /* Check the parameters */
350   assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance));
351   assert_param(IS_SDMMC_CLOCK_EDGE(hsd->Init.ClockEdge));
352   assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave));
353   assert_param(IS_SDMMC_BUS_WIDE(hsd->Init.BusWide));
354   assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl));
355   assert_param(IS_SDMMC_CLKDIV(hsd->Init.ClockDiv));
356 
357   if (hsd->State == HAL_SD_STATE_RESET)
358   {
359     /* Allocate lock resource and initialize it */
360     hsd->Lock = HAL_UNLOCKED;
361 
362 #if (USE_SD_TRANSCEIVER != 0U)
363     /* Force  SDMMC_TRANSCEIVER_PRESENT for Legacy usage */
364     if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_UNKNOWN)
365     {
366       hsd->Init.TranceiverPresent = SDMMC_TRANSCEIVER_PRESENT;
367     }
368 #endif /*USE_SD_TRANSCEIVER */
369 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
370     /* Reset Callback pointers in HAL_SD_STATE_RESET only */
371     hsd->TxCpltCallback    = HAL_SD_TxCpltCallback;
372     hsd->RxCpltCallback    = HAL_SD_RxCpltCallback;
373     hsd->ErrorCallback     = HAL_SD_ErrorCallback;
374     hsd->AbortCpltCallback = HAL_SD_AbortCallback;
375     hsd->Read_DMALnkLstBufCpltCallback  = HAL_SDEx_Read_DMALnkLstBufCpltCallback;
376     hsd->Write_DMALnkLstBufCpltCallback = HAL_SDEx_Write_DMALnkLstBufCpltCallback;
377 #if (USE_SD_TRANSCEIVER != 0U)
378     if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
379     {
380       hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback;
381     }
382 #endif /* USE_SD_TRANSCEIVER */
383 
384     if (hsd->MspInitCallback == NULL)
385     {
386       hsd->MspInitCallback = HAL_SD_MspInit;
387     }
388 
389     /* Init the low level hardware */
390     hsd->MspInitCallback(hsd);
391 #else
392     /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
393     HAL_SD_MspInit(hsd);
394 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
395   }
396 
397   hsd->State = HAL_SD_STATE_PROGRAMMING;
398 
399   /* Initialize the Card parameters */
400   if (HAL_SD_InitCard(hsd) != HAL_OK)
401   {
402     return HAL_ERROR;
403   }
404 
405   if (HAL_SD_GetCardStatus(hsd, &CardStatus) != HAL_OK)
406   {
407     return HAL_ERROR;
408   }
409   /* Get Initial Card Speed from Card Status*/
410   speedgrade = CardStatus.UhsSpeedGrade;
411   unitsize = CardStatus.UhsAllocationUnitSize;
412   if ((hsd->SdCard.CardType == CARD_SDHC_SDXC) && ((speedgrade != 0U) || (unitsize != 0U)))
413   {
414     hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED;
415   }
416   else
417   {
418     if (hsd->SdCard.CardType == CARD_SDHC_SDXC)
419     {
420       hsd->SdCard.CardSpeed  = CARD_HIGH_SPEED;
421     }
422     else
423     {
424       hsd->SdCard.CardSpeed  = CARD_NORMAL_SPEED;
425     }
426 
427   }
428   /* Configure the bus wide */
429   if (HAL_SD_ConfigWideBusOperation(hsd, hsd->Init.BusWide) != HAL_OK)
430   {
431     return HAL_ERROR;
432   }
433 
434   /* Verify that SD card is ready to use after Initialization */
435   tickstart = HAL_GetTick();
436   while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER))
437   {
438     if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
439     {
440       hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
441       hsd->State = HAL_SD_STATE_READY;
442       return HAL_TIMEOUT;
443     }
444   }
445 
446   /* Initialize the error code */
447   hsd->ErrorCode = HAL_SD_ERROR_NONE;
448 
449   /* Initialize the SD operation */
450   hsd->Context = SD_CONTEXT_NONE;
451 
452   /* Initialize the SD state */
453   hsd->State = HAL_SD_STATE_READY;
454 
455   return HAL_OK;
456 }
457 
458 /**
459   * @brief  Initializes the SD Card.
460   * @param  hsd: Pointer to SD handle
461   * @note   This function initializes the SD card. It could be used when a card
462             re-initialization is needed.
463   * @retval HAL status
464   */
HAL_SD_InitCard(SD_HandleTypeDef * hsd)465 HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd)
466 {
467   uint32_t errorstate;
468   SD_InitTypeDef Init;
469   uint32_t sdmmc_clk;
470 
471   /* Default SDMMC peripheral configuration for SD card initialization */
472   Init.ClockEdge           = SDMMC_CLOCK_EDGE_RISING;
473   Init.ClockPowerSave      = SDMMC_CLOCK_POWER_SAVE_DISABLE;
474   Init.BusWide             = SDMMC_BUS_WIDE_1B;
475   Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE;
476 
477   /* Init Clock should be less or equal to 400Khz*/
478   sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12);
479   if (sdmmc_clk == 0U)
480   {
481     hsd->State = HAL_SD_STATE_READY;
482     hsd->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER;
483     return HAL_ERROR;
484   }
485   Init.ClockDiv = sdmmc_clk / (2U * SD_INIT_FREQ);
486 
487 #if (USE_SD_TRANSCEIVER != 0U)
488   Init.TranceiverPresent = hsd->Init.TranceiverPresent;
489 
490   if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
491   {
492     /* Set Transceiver polarity */
493     hsd->Instance->POWER |= SDMMC_POWER_DIRPOL;
494   }
495 #elif defined (USE_SD_DIRPOL)
496   /* Set Transceiver polarity */
497   hsd->Instance->POWER |= SDMMC_POWER_DIRPOL;
498 #endif /* USE_SD_TRANSCEIVER  */
499 
500   /* Initialize SDMMC peripheral interface with default configuration */
501   (void)SDMMC_Init(hsd->Instance, Init);
502 
503   /* Set Power State to ON */
504   (void)SDMMC_PowerState_ON(hsd->Instance);
505 
506   /* wait 74 Cycles: required power up waiting time before starting
507      the SD initialization sequence */
508   if (Init.ClockDiv != 0U)
509   {
510     sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv);
511   }
512 
513   if (sdmmc_clk != 0U)
514   {
515     HAL_Delay(1U + (74U * 1000U / (sdmmc_clk)));
516   }
517 
518   /* Identify card operating voltage */
519   errorstate = SD_PowerON(hsd);
520   if (errorstate != HAL_SD_ERROR_NONE)
521   {
522     hsd->State = HAL_SD_STATE_READY;
523     hsd->ErrorCode |= errorstate;
524     return HAL_ERROR;
525   }
526 
527   /* Card initialization */
528   errorstate = SD_InitCard(hsd);
529   if (errorstate != HAL_SD_ERROR_NONE)
530   {
531     hsd->State = HAL_SD_STATE_READY;
532     hsd->ErrorCode |= errorstate;
533     return HAL_ERROR;
534   }
535 
536   /* Set Block Size for Card */
537   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
538   if (errorstate != HAL_SD_ERROR_NONE)
539   {
540     /* Clear all the static flags */
541     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
542     hsd->ErrorCode |= errorstate;
543     hsd->State = HAL_SD_STATE_READY;
544     return HAL_ERROR;
545   }
546 
547   return HAL_OK;
548 }
549 
550 /**
551   * @brief  De-Initializes the SD card.
552   * @param  hsd: Pointer to SD handle
553   * @retval HAL status
554   */
HAL_SD_DeInit(SD_HandleTypeDef * hsd)555 HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd)
556 {
557   /* Check the SD handle allocation */
558   if (hsd == NULL)
559   {
560     return HAL_ERROR;
561   }
562 
563   /* Check the parameters */
564   assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance));
565 
566   hsd->State = HAL_SD_STATE_BUSY;
567 
568 #if (USE_SD_TRANSCEIVER != 0U)
569   /* Deactivate the 1.8V Mode */
570   if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
571   {
572 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
573     if (hsd->DriveTransceiver_1_8V_Callback == NULL)
574     {
575       hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback;
576     }
577     hsd->DriveTransceiver_1_8V_Callback(RESET);
578 #else
579     HAL_SD_DriveTransceiver_1_8V_Callback(RESET);
580 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
581   }
582 #endif /* USE_SD_TRANSCEIVER   */
583 
584   /* Set SD power state to off */
585   SD_PowerOFF(hsd);
586 
587 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
588   if (hsd->MspDeInitCallback == NULL)
589   {
590     hsd->MspDeInitCallback = HAL_SD_MspDeInit;
591   }
592 
593   /* DeInit the low level hardware */
594   hsd->MspDeInitCallback(hsd);
595 #else
596   /* De-Initialize the MSP layer */
597   HAL_SD_MspDeInit(hsd);
598 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
599 
600   hsd->ErrorCode = HAL_SD_ERROR_NONE;
601   hsd->State = HAL_SD_STATE_RESET;
602 
603   return HAL_OK;
604 }
605 
606 /**
607   * @brief  Initializes the SD MSP.
608   * @param  hsd: Pointer to SD handle
609   * @retval None
610   */
HAL_SD_MspInit(SD_HandleTypeDef * hsd)611 __weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
612 {
613   /* Prevent unused argument(s) compilation warning */
614   UNUSED(hsd);
615 
616   /* NOTE : This function should not be modified, when the callback is needed,
617             the HAL_SD_MspInit could be implemented in the user file
618    */
619 }
620 
621 /**
622   * @brief  De-Initialize SD MSP.
623   * @param  hsd: Pointer to SD handle
624   * @retval None
625   */
HAL_SD_MspDeInit(SD_HandleTypeDef * hsd)626 __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd)
627 {
628   /* Prevent unused argument(s) compilation warning */
629   UNUSED(hsd);
630 
631   /* NOTE : This function should not be modified, when the callback is needed,
632             the HAL_SD_MspDeInit could be implemented in the user file
633    */
634 }
635 
636 /**
637   * @}
638   */
639 
640 /** @addtogroup SD_Exported_Functions_Group2
641   *  @brief   Data transfer functions
642   *
643 @verbatim
644   ==============================================================================
645                         ##### IO operation functions #####
646   ==============================================================================
647   [..]
648     This subsection provides a set of functions allowing to manage the data
649     transfer from/to SD card.
650 
651 @endverbatim
652   * @{
653   */
654 
655 /**
656   * @brief  Reads block(s) from a specified address in a card. The Data transfer
657   *         is managed by polling mode.
658   * @note   This API should be followed by a check on the card state through
659   *         HAL_SD_GetCardState().
660   * @param  hsd: Pointer to SD handle
661   * @param  pData: pointer to the buffer that will contain the received data
662   * @param  BlockAdd: Block Address from where data is to be read
663   * @param  NumberOfBlocks: Number of SD blocks to read
664   * @param  Timeout: Specify timeout value
665   * @retval HAL status
666   */
HAL_SD_ReadBlocks(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks,uint32_t Timeout)667 HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks,
668                                     uint32_t Timeout)
669 {
670   SDMMC_DataInitTypeDef config;
671   uint32_t errorstate;
672   uint32_t tickstart = HAL_GetTick();
673   uint32_t count;
674   uint32_t data;
675   uint32_t dataremaining;
676   uint32_t add = BlockAdd;
677   uint8_t *tempbuff = pData;
678 
679   if (NULL == pData)
680   {
681     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
682     return HAL_ERROR;
683   }
684 
685   if (hsd->State == HAL_SD_STATE_READY)
686   {
687     hsd->ErrorCode = HAL_SD_ERROR_NONE;
688 
689     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
690     {
691       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
692       return HAL_ERROR;
693     }
694 
695     hsd->State = HAL_SD_STATE_BUSY;
696 
697     /* Initialize data control register */
698     hsd->Instance->DCTRL = 0U;
699 
700     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
701     {
702       add *= BLOCKSIZE;
703     }
704 
705     /* Configure the SD DPSM (Data Path State Machine) */
706     config.DataTimeOut   = SDMMC_DATATIMEOUT;
707     config.DataLength    = NumberOfBlocks * BLOCKSIZE;
708     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
709     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
710     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
711     config.DPSM          = SDMMC_DPSM_DISABLE;
712     (void)SDMMC_ConfigData(hsd->Instance, &config);
713     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
714 
715     /* Read block(s) in polling mode */
716     if (NumberOfBlocks > 1U)
717     {
718       hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK;
719 
720       /* Read Multi Block command */
721       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
722     }
723     else
724     {
725       hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK;
726 
727       /* Read Single Block command */
728       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
729     }
730     if (errorstate != HAL_SD_ERROR_NONE)
731     {
732       /* Clear all the static flags */
733       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
734       hsd->ErrorCode |= errorstate;
735       hsd->State = HAL_SD_STATE_READY;
736       hsd->Context = SD_CONTEXT_NONE;
737       return HAL_ERROR;
738     }
739 
740     /* Poll on SDMMC flags */
741     dataremaining = config.DataLength;
742     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
743     {
744       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= SDMMC_FIFO_SIZE))
745       {
746         /* Read data from SDMMC Rx FIFO */
747         for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++)
748         {
749           data = SDMMC_ReadFIFO(hsd->Instance);
750           *tempbuff = (uint8_t)(data & 0xFFU);
751           tempbuff++;
752           *tempbuff = (uint8_t)((data >> 8U) & 0xFFU);
753           tempbuff++;
754           *tempbuff = (uint8_t)((data >> 16U) & 0xFFU);
755           tempbuff++;
756           *tempbuff = (uint8_t)((data >> 24U) & 0xFFU);
757           tempbuff++;
758         }
759         dataremaining -= SDMMC_FIFO_SIZE;
760       }
761 
762       if (((HAL_GetTick() - tickstart) >=  Timeout) || (Timeout == 0U))
763       {
764         /* Clear all the static flags */
765         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
766         hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT;
767         hsd->State = HAL_SD_STATE_READY;
768         hsd->Context = SD_CONTEXT_NONE;
769         return HAL_TIMEOUT;
770       }
771     }
772     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
773 
774     /* Send stop transmission command in case of multiblock read */
775     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U))
776     {
777       if (hsd->SdCard.CardType != CARD_SECURED)
778       {
779         /* Send stop transmission command */
780         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
781         if (errorstate != HAL_SD_ERROR_NONE)
782         {
783           /* Clear all the static flags */
784           __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
785           hsd->ErrorCode |= errorstate;
786           hsd->State = HAL_SD_STATE_READY;
787           hsd->Context = SD_CONTEXT_NONE;
788           return HAL_ERROR;
789         }
790       }
791     }
792 
793     /* Get error state */
794     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
795     {
796       /* Clear all the static flags */
797       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
798       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
799       hsd->State = HAL_SD_STATE_READY;
800       hsd->Context = SD_CONTEXT_NONE;
801       return HAL_ERROR;
802     }
803     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
804     {
805       /* Clear all the static flags */
806       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
807       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
808       hsd->State = HAL_SD_STATE_READY;
809       hsd->Context = SD_CONTEXT_NONE;
810       return HAL_ERROR;
811     }
812     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
813     {
814       /* Clear all the static flags */
815       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
816       hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN;
817       hsd->State = HAL_SD_STATE_READY;
818       hsd->Context = SD_CONTEXT_NONE;
819       return HAL_ERROR;
820     }
821     else
822     {
823       /* Nothing to do */
824     }
825 
826     /* Clear all the static flags */
827     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
828 
829     hsd->State = HAL_SD_STATE_READY;
830 
831     return HAL_OK;
832   }
833   else
834   {
835     hsd->ErrorCode |= HAL_SD_ERROR_BUSY;
836     return HAL_ERROR;
837   }
838 }
839 
840 /**
841   * @brief  Allows to write block(s) to a specified address in a card. The Data
842   *         transfer is managed by polling mode.
843   * @note   This API should be followed by a check on the card state through
844   *         HAL_SD_GetCardState().
845   * @param  hsd: Pointer to SD handle
846   * @param  pData: pointer to the buffer that will contain the data to transmit
847   * @param  BlockAdd: Block Address where data will be written
848   * @param  NumberOfBlocks: Number of SD blocks to write
849   * @param  Timeout: Specify timeout value
850   * @retval HAL status
851   */
HAL_SD_WriteBlocks(SD_HandleTypeDef * hsd,const uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks,uint32_t Timeout)852 HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd,
853                                      uint32_t NumberOfBlocks, uint32_t Timeout)
854 {
855   SDMMC_DataInitTypeDef config;
856   uint32_t errorstate;
857   uint32_t tickstart = HAL_GetTick();
858   uint32_t count;
859   uint32_t data;
860   uint32_t dataremaining;
861   uint32_t add = BlockAdd;
862   const uint8_t *tempbuff = pData;
863 
864   if (NULL == pData)
865   {
866     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
867     return HAL_ERROR;
868   }
869 
870   if (hsd->State == HAL_SD_STATE_READY)
871   {
872     hsd->ErrorCode = HAL_SD_ERROR_NONE;
873 
874     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
875     {
876       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
877       return HAL_ERROR;
878     }
879 
880     hsd->State = HAL_SD_STATE_BUSY;
881 
882     /* Initialize data control register */
883     hsd->Instance->DCTRL = 0U;
884 
885     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
886     {
887       add *= BLOCKSIZE;
888     }
889 
890     /* Configure the SD DPSM (Data Path State Machine) */
891     config.DataTimeOut   = SDMMC_DATATIMEOUT;
892     config.DataLength    = NumberOfBlocks * BLOCKSIZE;
893     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
894     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_CARD;
895     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
896     config.DPSM          = SDMMC_DPSM_DISABLE;
897     (void)SDMMC_ConfigData(hsd->Instance, &config);
898     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
899 
900     /* Write Blocks in Polling mode */
901     if (NumberOfBlocks > 1U)
902     {
903       hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK;
904 
905       /* Write Multi Block command */
906       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
907     }
908     else
909     {
910       hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK;
911 
912       /* Write Single Block command */
913       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
914     }
915     if (errorstate != HAL_SD_ERROR_NONE)
916     {
917       /* Clear all the static flags */
918       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
919       hsd->ErrorCode |= errorstate;
920       hsd->State = HAL_SD_STATE_READY;
921       hsd->Context = SD_CONTEXT_NONE;
922       return HAL_ERROR;
923     }
924 
925     /* Write block(s) in polling mode */
926     dataremaining = config.DataLength;
927     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT |
928                               SDMMC_FLAG_DATAEND))
929     {
930       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= SDMMC_FIFO_SIZE))
931       {
932         /* Write data to SDMMC Tx FIFO */
933         for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++)
934         {
935           data = (uint32_t)(*tempbuff);
936           tempbuff++;
937           data |= ((uint32_t)(*tempbuff) << 8U);
938           tempbuff++;
939           data |= ((uint32_t)(*tempbuff) << 16U);
940           tempbuff++;
941           data |= ((uint32_t)(*tempbuff) << 24U);
942           tempbuff++;
943           (void)SDMMC_WriteFIFO(hsd->Instance, &data);
944         }
945         dataremaining -= SDMMC_FIFO_SIZE;
946       }
947 
948       if (((HAL_GetTick() - tickstart) >=  Timeout) || (Timeout == 0U))
949       {
950         /* Clear all the static flags */
951         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
952         hsd->ErrorCode |= errorstate;
953         hsd->State = HAL_SD_STATE_READY;
954         hsd->Context = SD_CONTEXT_NONE;
955         return HAL_TIMEOUT;
956       }
957     }
958     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
959 
960     /* Send stop transmission command in case of multiblock write */
961     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U))
962     {
963       if (hsd->SdCard.CardType != CARD_SECURED)
964       {
965         /* Send stop transmission command */
966         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
967         if (errorstate != HAL_SD_ERROR_NONE)
968         {
969           /* Clear all the static flags */
970           __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
971           hsd->ErrorCode |= errorstate;
972           hsd->State = HAL_SD_STATE_READY;
973           hsd->Context = SD_CONTEXT_NONE;
974           return HAL_ERROR;
975         }
976       }
977     }
978 
979     /* Get error state */
980     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
981     {
982       /* Clear all the static flags */
983       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
984       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
985       hsd->State = HAL_SD_STATE_READY;
986       hsd->Context = SD_CONTEXT_NONE;
987       return HAL_ERROR;
988     }
989     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
990     {
991       /* Clear all the static flags */
992       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
993       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
994       hsd->State = HAL_SD_STATE_READY;
995       hsd->Context = SD_CONTEXT_NONE;
996       return HAL_ERROR;
997     }
998     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR))
999     {
1000       /* Clear all the static flags */
1001       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1002       hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;
1003       hsd->State = HAL_SD_STATE_READY;
1004       hsd->Context = SD_CONTEXT_NONE;
1005       return HAL_ERROR;
1006     }
1007     else
1008     {
1009       /* Nothing to do */
1010     }
1011 
1012     /* Clear all the static flags */
1013     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
1014 
1015     hsd->State = HAL_SD_STATE_READY;
1016 
1017     return HAL_OK;
1018   }
1019   else
1020   {
1021     hsd->ErrorCode |= HAL_SD_ERROR_BUSY;
1022     return HAL_ERROR;
1023   }
1024 }
1025 
1026 /**
1027   * @brief  Reads block(s) from a specified address in a card. The Data transfer
1028   *         is managed in interrupt mode.
1029   * @note   This API should be followed by a check on the card state through
1030   *         HAL_SD_GetCardState().
1031   * @note   You could also check the IT transfer process through the SD Rx
1032   *         interrupt event.
1033   * @param  hsd: Pointer to SD handle
1034   * @param  pData: Pointer to the buffer that will contain the received data
1035   * @param  BlockAdd: Block Address from where data is to be read
1036   * @param  NumberOfBlocks: Number of blocks to read.
1037   * @retval HAL status
1038   */
HAL_SD_ReadBlocks_IT(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1039 HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd,
1040                                        uint32_t NumberOfBlocks)
1041 {
1042   SDMMC_DataInitTypeDef config;
1043   uint32_t errorstate;
1044   uint32_t add = BlockAdd;
1045 
1046   if (NULL == pData)
1047   {
1048     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1049     return HAL_ERROR;
1050   }
1051 
1052   if (hsd->State == HAL_SD_STATE_READY)
1053   {
1054     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1055 
1056     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1057     {
1058       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1059       return HAL_ERROR;
1060     }
1061 
1062     hsd->State = HAL_SD_STATE_BUSY;
1063 
1064     /* Initialize data control register */
1065     hsd->Instance->DCTRL = 0U;
1066 
1067     hsd->pRxBuffPtr = pData;
1068     hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks;
1069 
1070     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1071     {
1072       add *= BLOCKSIZE;
1073     }
1074 
1075     /* Configure the SD DPSM (Data Path State Machine) */
1076     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1077     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1078     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1079     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
1080     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1081     config.DPSM          = SDMMC_DPSM_DISABLE;
1082     (void)SDMMC_ConfigData(hsd->Instance, &config);
1083     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1084 
1085     /* Read Blocks in IT mode */
1086     if (NumberOfBlocks > 1U)
1087     {
1088       hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT);
1089 
1090       /* Read Multi Block command */
1091       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
1092     }
1093     else
1094     {
1095       hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT);
1096 
1097       /* Read Single Block command */
1098       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
1099     }
1100     if (errorstate != HAL_SD_ERROR_NONE)
1101     {
1102       /* Clear all the static flags */
1103       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1104       hsd->ErrorCode |= errorstate;
1105       hsd->State = HAL_SD_STATE_READY;
1106       hsd->Context = SD_CONTEXT_NONE;
1107       return HAL_ERROR;
1108     }
1109 
1110     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND |
1111                              SDMMC_FLAG_RXFIFOHF));
1112 
1113     return HAL_OK;
1114   }
1115   else
1116   {
1117     return HAL_BUSY;
1118   }
1119 }
1120 
1121 /**
1122   * @brief  Writes block(s) to a specified address in a card. The Data transfer
1123   *         is managed in interrupt mode.
1124   * @note   This API should be followed by a check on the card state through
1125   *         HAL_SD_GetCardState().
1126   * @note   You could also check the IT transfer process through the SD Tx
1127   *         interrupt event.
1128   * @param  hsd: Pointer to SD handle
1129   * @param  pData: Pointer to the buffer that will contain the data to transmit
1130   * @param  BlockAdd: Block Address where data will be written
1131   * @param  NumberOfBlocks: Number of blocks to write
1132   * @retval HAL status
1133   */
HAL_SD_WriteBlocks_IT(SD_HandleTypeDef * hsd,const uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1134 HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd,
1135                                         uint32_t NumberOfBlocks)
1136 {
1137   SDMMC_DataInitTypeDef config;
1138   uint32_t errorstate;
1139   uint32_t add = BlockAdd;
1140 
1141   if (NULL == pData)
1142   {
1143     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1144     return HAL_ERROR;
1145   }
1146 
1147   if (hsd->State == HAL_SD_STATE_READY)
1148   {
1149     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1150 
1151     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1152     {
1153       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1154       return HAL_ERROR;
1155     }
1156 
1157     hsd->State = HAL_SD_STATE_BUSY;
1158 
1159     /* Initialize data control register */
1160     hsd->Instance->DCTRL = 0U;
1161 
1162     hsd->pTxBuffPtr = pData;
1163     hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks;
1164 
1165     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1166     {
1167       add *= BLOCKSIZE;
1168     }
1169 
1170     /* Configure the SD DPSM (Data Path State Machine) */
1171     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1172     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1173     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1174     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_CARD;
1175     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1176     config.DPSM          = SDMMC_DPSM_DISABLE;
1177     (void)SDMMC_ConfigData(hsd->Instance, &config);
1178 
1179     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1180 
1181     /* Write Blocks in Polling mode */
1182     if (NumberOfBlocks > 1U)
1183     {
1184       hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_IT);
1185 
1186       /* Write Multi Block command */
1187       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
1188     }
1189     else
1190     {
1191       hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT);
1192 
1193       /* Write Single Block command */
1194       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
1195     }
1196     if (errorstate != HAL_SD_ERROR_NONE)
1197     {
1198       /* Clear all the static flags */
1199       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1200       hsd->ErrorCode |= errorstate;
1201       hsd->State = HAL_SD_STATE_READY;
1202       hsd->Context = SD_CONTEXT_NONE;
1203       return HAL_ERROR;
1204     }
1205 
1206     /* Enable transfer interrupts */
1207     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND |
1208                              SDMMC_FLAG_TXFIFOHE));
1209 
1210     return HAL_OK;
1211   }
1212   else
1213   {
1214     return HAL_BUSY;
1215   }
1216 }
1217 
1218 /**
1219   * @brief  Reads block(s) from a specified address in a card. The Data transfer
1220   *         is managed by DMA mode.
1221   * @note   This API should be followed by a check on the card state through
1222   *         HAL_SD_GetCardState().
1223   * @note   You could also check the DMA transfer process through the SD Rx
1224   *         interrupt event.
1225   * @param  hsd: Pointer SD handle
1226   * @param  pData: Pointer to the buffer that will contain the received data
1227   * @param  BlockAdd: Block Address from where data is to be read
1228   * @param  NumberOfBlocks: Number of blocks to read.
1229   * @retval HAL status
1230   */
HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef * hsd,uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1231 HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd,
1232                                         uint32_t NumberOfBlocks)
1233 {
1234   SDMMC_DataInitTypeDef config;
1235   uint32_t errorstate;
1236   uint32_t add = BlockAdd;
1237 
1238   if (NULL == pData)
1239   {
1240     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1241     return HAL_ERROR;
1242   }
1243 
1244   if (hsd->State == HAL_SD_STATE_READY)
1245   {
1246     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1247 
1248     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1249     {
1250       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1251       return HAL_ERROR;
1252     }
1253 
1254     hsd->State = HAL_SD_STATE_BUSY;
1255 
1256     /* Initialize data control register */
1257     hsd->Instance->DCTRL = 0U;
1258 
1259     hsd->pRxBuffPtr = pData;
1260     hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks;
1261 
1262     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1263     {
1264       add *= BLOCKSIZE;
1265     }
1266 
1267     /* Configure the SD DPSM (Data Path State Machine) */
1268     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1269     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1270     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1271     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
1272     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1273     config.DPSM          = SDMMC_DPSM_DISABLE;
1274     (void)SDMMC_ConfigData(hsd->Instance, &config);
1275 
1276     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1277     hsd->Instance->IDMABASER = (uint32_t) pData ;
1278     hsd->Instance->IDMACTRL  = SDMMC_ENABLE_IDMA_SINGLE_BUFF;
1279 
1280     /* Read Blocks in DMA mode */
1281     if (NumberOfBlocks > 1U)
1282     {
1283       hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA);
1284 
1285       /* Read Multi Block command */
1286       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
1287     }
1288     else
1289     {
1290       hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA);
1291 
1292       /* Read Single Block command */
1293       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
1294     }
1295     if (errorstate != HAL_SD_ERROR_NONE)
1296     {
1297       /* Clear all the static flags */
1298       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1299       hsd->ErrorCode |= errorstate;
1300       hsd->State = HAL_SD_STATE_READY;
1301       hsd->Context = SD_CONTEXT_NONE;
1302       return HAL_ERROR;
1303     }
1304 
1305     /* Enable transfer interrupts */
1306     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND));
1307 
1308     return HAL_OK;
1309   }
1310   else
1311   {
1312     return HAL_BUSY;
1313   }
1314 }
1315 
1316 /**
1317   * @brief  Writes block(s) to a specified address in a card. The Data transfer
1318   *         is managed by DMA mode.
1319   * @note   This API should be followed by a check on the card state through
1320   *         HAL_SD_GetCardState().
1321   * @note   You could also check the DMA transfer process through the SD Tx
1322   *         interrupt event.
1323   * @param  hsd: Pointer to SD handle
1324   * @param  pData: Pointer to the buffer that will contain the data to transmit
1325   * @param  BlockAdd: Block Address where data will be written
1326   * @param  NumberOfBlocks: Number of blocks to write
1327   * @retval HAL status
1328   */
HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef * hsd,const uint8_t * pData,uint32_t BlockAdd,uint32_t NumberOfBlocks)1329 HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd,
1330                                          uint32_t NumberOfBlocks)
1331 {
1332   SDMMC_DataInitTypeDef config;
1333   uint32_t errorstate;
1334   uint32_t add = BlockAdd;
1335 
1336   if (NULL == pData)
1337   {
1338     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1339     return HAL_ERROR;
1340   }
1341 
1342   if (hsd->State == HAL_SD_STATE_READY)
1343   {
1344     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1345 
1346     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1347     {
1348       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1349       return HAL_ERROR;
1350     }
1351 
1352     hsd->State = HAL_SD_STATE_BUSY;
1353 
1354     /* Initialize data control register */
1355     hsd->Instance->DCTRL = 0U;
1356 
1357     hsd->pTxBuffPtr = pData;
1358     hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks;
1359 
1360     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1361     {
1362       add *= BLOCKSIZE;
1363     }
1364 
1365     /* Configure the SD DPSM (Data Path State Machine) */
1366     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1367     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1368     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1369     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_CARD;
1370     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1371     config.DPSM          = SDMMC_DPSM_DISABLE;
1372     (void)SDMMC_ConfigData(hsd->Instance, &config);
1373 
1374     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1375 
1376     hsd->Instance->IDMABASER = (uint32_t) pData ;
1377     hsd->Instance->IDMACTRL  = SDMMC_ENABLE_IDMA_SINGLE_BUFF;
1378 
1379     /* Write Blocks in Polling mode */
1380     if (NumberOfBlocks > 1U)
1381     {
1382       hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA);
1383 
1384       /* Write Multi Block command */
1385       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
1386     }
1387     else
1388     {
1389       hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA);
1390 
1391       /* Write Single Block command */
1392       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
1393     }
1394     if (errorstate != HAL_SD_ERROR_NONE)
1395     {
1396       /* Clear all the static flags */
1397       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1398       hsd->ErrorCode |= errorstate;
1399       hsd->State = HAL_SD_STATE_READY;
1400       hsd->Context = SD_CONTEXT_NONE;
1401       return HAL_ERROR;
1402     }
1403 
1404     /* Enable transfer interrupts */
1405     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND));
1406 
1407     return HAL_OK;
1408   }
1409   else
1410   {
1411     return HAL_BUSY;
1412   }
1413 }
1414 
1415 /**
1416   * @brief  Erases the specified memory area of the given SD card.
1417   * @note   This API should be followed by a check on the card state through
1418   *         HAL_SD_GetCardState().
1419   * @param  hsd: Pointer to SD handle
1420   * @param  BlockStartAdd: Start Block address
1421   * @param  BlockEndAdd: End Block address
1422   * @retval HAL status
1423   */
HAL_SD_Erase(SD_HandleTypeDef * hsd,uint32_t BlockStartAdd,uint32_t BlockEndAdd)1424 HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd)
1425 {
1426   uint32_t errorstate;
1427   uint32_t start_add = BlockStartAdd;
1428   uint32_t end_add = BlockEndAdd;
1429 
1430   if (hsd->State == HAL_SD_STATE_READY)
1431   {
1432     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1433 
1434     if (end_add < start_add)
1435     {
1436       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1437       return HAL_ERROR;
1438     }
1439 
1440     if (end_add > (hsd->SdCard.LogBlockNbr))
1441     {
1442       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1443       return HAL_ERROR;
1444     }
1445 
1446     hsd->State = HAL_SD_STATE_BUSY;
1447 
1448     /* Check if the card command class supports erase command */
1449     if (((hsd->SdCard.Class) & SDMMC_CCCC_ERASE) == 0U)
1450     {
1451       /* Clear all the static flags */
1452       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1453       hsd->ErrorCode |= HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
1454       hsd->State = HAL_SD_STATE_READY;
1455       return HAL_ERROR;
1456     }
1457 
1458     if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
1459     {
1460       /* Clear all the static flags */
1461       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1462       hsd->ErrorCode |= HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
1463       hsd->State = HAL_SD_STATE_READY;
1464       return HAL_ERROR;
1465     }
1466 
1467     /* Get start and end block for high capacity cards */
1468     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1469     {
1470       start_add *= BLOCKSIZE;
1471       end_add   *= BLOCKSIZE;
1472     }
1473 
1474     /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */
1475     if (hsd->SdCard.CardType != CARD_SECURED)
1476     {
1477       /* Send CMD32 SD_ERASE_GRP_START with argument as addr  */
1478       errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, start_add);
1479       if (errorstate != HAL_SD_ERROR_NONE)
1480       {
1481         /* Clear all the static flags */
1482         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1483         hsd->ErrorCode |= errorstate;
1484         hsd->State = HAL_SD_STATE_READY;
1485         return HAL_ERROR;
1486       }
1487 
1488       /* Send CMD33 SD_ERASE_GRP_END with argument as addr  */
1489       errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, end_add);
1490       if (errorstate != HAL_SD_ERROR_NONE)
1491       {
1492         /* Clear all the static flags */
1493         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1494         hsd->ErrorCode |= errorstate;
1495         hsd->State = HAL_SD_STATE_READY;
1496         return HAL_ERROR;
1497       }
1498     }
1499 
1500     /* Send CMD38 ERASE */
1501     errorstate = SDMMC_CmdErase(hsd->Instance, 0UL);
1502     if (errorstate != HAL_SD_ERROR_NONE)
1503     {
1504       /* Clear all the static flags */
1505       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1506       hsd->ErrorCode |= errorstate;
1507       hsd->State = HAL_SD_STATE_READY;
1508       return HAL_ERROR;
1509     }
1510 
1511     hsd->State = HAL_SD_STATE_READY;
1512 
1513     return HAL_OK;
1514   }
1515   else
1516   {
1517     return HAL_BUSY;
1518   }
1519 }
1520 
1521 /**
1522   * @brief  This function handles SD card interrupt request.
1523   * @param  hsd: Pointer to SD handle
1524   * @retval None
1525   */
HAL_SD_IRQHandler(SD_HandleTypeDef * hsd)1526 void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd)
1527 {
1528   uint32_t errorstate;
1529   uint32_t context = hsd->Context;
1530 
1531   /* Check for SDMMC interrupt flags */
1532   if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) != RESET) && ((context & SD_CONTEXT_IT) != 0U))
1533   {
1534     SD_Read_IT(hsd);
1535   }
1536 
1537   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) != RESET)
1538   {
1539     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DATAEND);
1540 
1541     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND  | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
1542                         SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR  | SDMMC_IT_TXFIFOHE | \
1543                         SDMMC_IT_RXFIFOHF);
1544 
1545     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC);
1546     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
1547 
1548     if ((context & SD_CONTEXT_IT) != 0U)
1549     {
1550       if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1551       {
1552         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
1553         if (errorstate != HAL_SD_ERROR_NONE)
1554         {
1555           hsd->ErrorCode |= errorstate;
1556 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1557           hsd->ErrorCallback(hsd);
1558 #else
1559           HAL_SD_ErrorCallback(hsd);
1560 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1561         }
1562       }
1563 
1564       /* Clear all the static flags */
1565       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
1566 
1567       hsd->State = HAL_SD_STATE_READY;
1568       hsd->Context = SD_CONTEXT_NONE;
1569       if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
1570       {
1571 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1572         hsd->RxCpltCallback(hsd);
1573 #else
1574         HAL_SD_RxCpltCallback(hsd);
1575 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1576       }
1577       else
1578       {
1579 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1580         hsd->TxCpltCallback(hsd);
1581 #else
1582         HAL_SD_TxCpltCallback(hsd);
1583 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1584       }
1585     }
1586     else if ((context & SD_CONTEXT_DMA) != 0U)
1587     {
1588       hsd->Instance->DLEN = 0;
1589       hsd->Instance->DCTRL = 0;
1590       hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
1591 
1592       /* Stop Transfer for Write Multi blocks or Read Multi blocks */
1593       if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1594       {
1595         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
1596         if (errorstate != HAL_SD_ERROR_NONE)
1597         {
1598           hsd->ErrorCode |= errorstate;
1599 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1600           hsd->ErrorCallback(hsd);
1601 #else
1602           HAL_SD_ErrorCallback(hsd);
1603 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1604         }
1605       }
1606 
1607       hsd->State = HAL_SD_STATE_READY;
1608       hsd->Context = SD_CONTEXT_NONE;
1609       if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1610       {
1611 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1612         hsd->TxCpltCallback(hsd);
1613 #else
1614         HAL_SD_TxCpltCallback(hsd);
1615 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1616       }
1617       if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
1618       {
1619 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1620         hsd->RxCpltCallback(hsd);
1621 #else
1622         HAL_SD_RxCpltCallback(hsd);
1623 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1624       }
1625     }
1626     else
1627     {
1628       /* Nothing to do */
1629     }
1630   }
1631 
1632   else if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) != RESET) && ((context & SD_CONTEXT_IT) != 0U))
1633   {
1634     SD_Write_IT(hsd);
1635   }
1636 
1637   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR |
1638                              SDMMC_FLAG_TXUNDERR) != RESET)
1639   {
1640     /* Set Error code */
1641     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DCRCFAIL) != RESET)
1642     {
1643       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
1644     }
1645     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DTIMEOUT) != RESET)
1646     {
1647       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
1648     }
1649     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_RXOVERR) != RESET)
1650     {
1651       hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN;
1652     }
1653     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_TXUNDERR) != RESET)
1654     {
1655       hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;
1656     }
1657 
1658     /* Clear All flags */
1659     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
1660 
1661     /* Disable all interrupts */
1662     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
1663                         SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR);
1664 
1665     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
1666     hsd->Instance->DCTRL |= SDMMC_DCTRL_FIFORST;
1667     hsd->Instance->CMD |= SDMMC_CMD_CMDSTOP;
1668     hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance);
1669     hsd->Instance->CMD &= ~(SDMMC_CMD_CMDSTOP);
1670     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DABORT);
1671 
1672     if ((context & SD_CONTEXT_IT) != 0U)
1673     {
1674       /* Set the SD state to ready to be able to start again the process */
1675       hsd->State = HAL_SD_STATE_READY;
1676       hsd->Context = SD_CONTEXT_NONE;
1677 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1678       hsd->ErrorCallback(hsd);
1679 #else
1680       HAL_SD_ErrorCallback(hsd);
1681 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1682     }
1683     else if ((context & SD_CONTEXT_DMA) != 0U)
1684     {
1685       if (hsd->ErrorCode != HAL_SD_ERROR_NONE)
1686       {
1687         /* Disable Internal DMA */
1688         __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC);
1689         hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
1690 
1691         /* Set the SD state to ready to be able to start again the process */
1692         hsd->State = HAL_SD_STATE_READY;
1693 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1694         hsd->ErrorCallback(hsd);
1695 #else
1696         HAL_SD_ErrorCallback(hsd);
1697 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1698       }
1699     }
1700     else
1701     {
1702       /* Nothing to do */
1703     }
1704   }
1705 
1706   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_IDMABTC) != RESET)
1707   {
1708     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_IDMABTC);
1709 
1710     if ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)
1711     {
1712 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1713       hsd->Write_DMALnkLstBufCpltCallback(hsd);
1714 #else
1715       HAL_SDEx_Write_DMALnkLstBufCpltCallback(hsd);
1716 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1717     }
1718     else /* SD_CONTEXT_READ_MULTIPLE_BLOCK */
1719     {
1720 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1721       hsd->Read_DMALnkLstBufCpltCallback(hsd);
1722 #else
1723       HAL_SDEx_Read_DMALnkLstBufCpltCallback(hsd);
1724 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1725     }
1726   }
1727   else
1728   {
1729     /* Nothing to do */
1730   }
1731 }
1732 
1733 /**
1734   * @brief return the SD state
1735   * @param hsd: Pointer to sd handle
1736   * @retval HAL state
1737   */
HAL_SD_GetState(const SD_HandleTypeDef * hsd)1738 HAL_SD_StateTypeDef HAL_SD_GetState(const SD_HandleTypeDef *hsd)
1739 {
1740   return hsd->State;
1741 }
1742 
1743 /**
1744   * @brief  Return the SD error code
1745   * @param  hsd : Pointer to a SD_HandleTypeDef structure that contains
1746   *              the configuration information.
1747   * @retval SD Error Code
1748   */
HAL_SD_GetError(const SD_HandleTypeDef * hsd)1749 uint32_t HAL_SD_GetError(const SD_HandleTypeDef *hsd)
1750 {
1751   return hsd->ErrorCode;
1752 }
1753 
1754 /**
1755   * @brief Tx Transfer completed callbacks
1756   * @param hsd: Pointer to SD handle
1757   * @retval None
1758   */
HAL_SD_TxCpltCallback(SD_HandleTypeDef * hsd)1759 __weak void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd)
1760 {
1761   /* Prevent unused argument(s) compilation warning */
1762   UNUSED(hsd);
1763 
1764   /* NOTE : This function should not be modified, when the callback is needed,
1765             the HAL_SD_TxCpltCallback can be implemented in the user file
1766    */
1767 }
1768 
1769 /**
1770   * @brief Rx Transfer completed callbacks
1771   * @param hsd: Pointer SD handle
1772   * @retval None
1773   */
HAL_SD_RxCpltCallback(SD_HandleTypeDef * hsd)1774 __weak void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd)
1775 {
1776   /* Prevent unused argument(s) compilation warning */
1777   UNUSED(hsd);
1778 
1779   /* NOTE : This function should not be modified, when the callback is needed,
1780             the HAL_SD_RxCpltCallback can be implemented in the user file
1781    */
1782 }
1783 
1784 /**
1785   * @brief SD error callbacks
1786   * @param hsd: Pointer SD handle
1787   * @retval None
1788   */
HAL_SD_ErrorCallback(SD_HandleTypeDef * hsd)1789 __weak void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd)
1790 {
1791   /* Prevent unused argument(s) compilation warning */
1792   UNUSED(hsd);
1793 
1794   /* NOTE : This function should not be modified, when the callback is needed,
1795             the HAL_SD_ErrorCallback can be implemented in the user file
1796    */
1797 }
1798 
1799 /**
1800   * @brief SD Abort callbacks
1801   * @param hsd: Pointer SD handle
1802   * @retval None
1803   */
HAL_SD_AbortCallback(SD_HandleTypeDef * hsd)1804 __weak void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd)
1805 {
1806   /* Prevent unused argument(s) compilation warning */
1807   UNUSED(hsd);
1808 
1809   /* NOTE : This function should not be modified, when the callback is needed,
1810             the HAL_SD_AbortCallback can be implemented in the user file
1811    */
1812 }
1813 
1814 #if (USE_SD_TRANSCEIVER != 0U)
1815 /**
1816   * @brief  Enable/Disable the SD Transceiver 1.8V Mode Callback.
1817   * @param  status: Voltage Switch State
1818   * @retval None
1819   */
HAL_SD_DriveTransceiver_1_8V_Callback(FlagStatus status)1820 __weak  void HAL_SD_DriveTransceiver_1_8V_Callback(FlagStatus status)
1821 {
1822   /* Prevent unused argument(s) compilation warning */
1823   UNUSED(status);
1824   /* NOTE : This function should not be modified, when the callback is needed,
1825             the HAL_SD_EnableTransceiver could be implemented in the user file
1826    */
1827 }
1828 #endif /* USE_SD_TRANSCEIVER  */
1829 
1830 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1831 /**
1832   * @brief  Register a User SD Callback
1833   *         To be used instead of the weak (overridden) predefined callback
1834   * @note   The HAL_SD_RegisterCallback() may be called before HAL_SD_Init() in
1835   *         HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID
1836   *         and HAL_SD_MSP_DEINIT_CB_ID.
1837   * @param hsd : SD handle
1838   * @param CallbackID : ID of the callback to be registered
1839   *        This parameter can be one of the following values:
1840   *          @arg @ref HAL_SD_TX_CPLT_CB_ID                 SD Tx Complete Callback ID
1841   *          @arg @ref HAL_SD_RX_CPLT_CB_ID                 SD Rx Complete Callback ID
1842   *          @arg @ref HAL_SD_ERROR_CB_ID                   SD Error Callback ID
1843   *          @arg @ref HAL_SD_ABORT_CB_ID                   SD Abort Callback ID
1844   *          @arg @ref HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID  SD DMA Rx Linked List Node buffer Callback ID
1845   *          @arg @ref HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Tx Linked List Node buffer Callback ID
1846   *          @arg @ref HAL_SD_MSP_INIT_CB_ID                SD MspInit Callback ID
1847   *          @arg @ref HAL_SD_MSP_DEINIT_CB_ID              SD MspDeInit Callback ID
1848   * @param pCallback : pointer to the Callback function
1849   * @retval status
1850   */
HAL_SD_RegisterCallback(SD_HandleTypeDef * hsd,HAL_SD_CallbackIDTypeDef CallbackID,pSD_CallbackTypeDef pCallback)1851 HAL_StatusTypeDef HAL_SD_RegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID,
1852                                           pSD_CallbackTypeDef pCallback)
1853 {
1854   HAL_StatusTypeDef status = HAL_OK;
1855 
1856   if (pCallback == NULL)
1857   {
1858     /* Update the error code */
1859     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1860     return HAL_ERROR;
1861   }
1862 
1863   if (hsd->State == HAL_SD_STATE_READY)
1864   {
1865     switch (CallbackID)
1866     {
1867       case HAL_SD_TX_CPLT_CB_ID :
1868         hsd->TxCpltCallback = pCallback;
1869         break;
1870       case HAL_SD_RX_CPLT_CB_ID :
1871         hsd->RxCpltCallback = pCallback;
1872         break;
1873       case HAL_SD_ERROR_CB_ID :
1874         hsd->ErrorCallback = pCallback;
1875         break;
1876       case HAL_SD_ABORT_CB_ID :
1877         hsd->AbortCpltCallback = pCallback;
1878         break;
1879       case HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID :
1880         hsd->Read_DMALnkLstBufCpltCallback = pCallback;
1881         break;
1882       case HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID :
1883         hsd->Write_DMALnkLstBufCpltCallback = pCallback;
1884         break;
1885       case HAL_SD_MSP_INIT_CB_ID :
1886         hsd->MspInitCallback = pCallback;
1887         break;
1888       case HAL_SD_MSP_DEINIT_CB_ID :
1889         hsd->MspDeInitCallback = pCallback;
1890         break;
1891       default :
1892         /* Update the error code */
1893         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1894         /* update return status */
1895         status =  HAL_ERROR;
1896         break;
1897     }
1898   }
1899   else if (hsd->State == HAL_SD_STATE_RESET)
1900   {
1901     switch (CallbackID)
1902     {
1903       case HAL_SD_MSP_INIT_CB_ID :
1904         hsd->MspInitCallback = pCallback;
1905         break;
1906       case HAL_SD_MSP_DEINIT_CB_ID :
1907         hsd->MspDeInitCallback = pCallback;
1908         break;
1909       default :
1910         /* Update the error code */
1911         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1912         /* update return status */
1913         status =  HAL_ERROR;
1914         break;
1915     }
1916   }
1917   else
1918   {
1919     /* Update the error code */
1920     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1921     /* update return status */
1922     status =  HAL_ERROR;
1923   }
1924 
1925   return status;
1926 }
1927 
1928 /**
1929   * @brief  Unregister a User SD Callback
1930   *         SD Callback is redirected to the weak (overridden) predefined callback
1931   * @note   The HAL_SD_UnRegisterCallback() may be called before HAL_SD_Init() in
1932   *         HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID
1933   *         and HAL_SD_MSP_DEINIT_CB_ID.
1934   * @param hsd : SD handle
1935   * @param CallbackID : ID of the callback to be unregistered
1936   *        This parameter can be one of the following values:
1937   *          @arg @ref HAL_SD_TX_CPLT_CB_ID                 SD Tx Complete Callback ID
1938   *          @arg @ref HAL_SD_RX_CPLT_CB_ID                 SD Rx Complete Callback ID
1939   *          @arg @ref HAL_SD_ERROR_CB_ID                   SD Error Callback ID
1940   *          @arg @ref HAL_SD_ABORT_CB_ID                   SD Abort Callback ID
1941   *          @arg @ref HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID  SD DMA Rx Linked List Node buffer Callback ID
1942   *          @arg @ref HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID SD DMA Tx Linked List Node buffer Callback ID
1943   *          @arg @ref HAL_SD_MSP_INIT_CB_ID                SD MspInit Callback ID
1944   *          @arg @ref HAL_SD_MSP_DEINIT_CB_ID              SD MspDeInit Callback ID
1945   * @retval status
1946   */
HAL_SD_UnRegisterCallback(SD_HandleTypeDef * hsd,HAL_SD_CallbackIDTypeDef CallbackID)1947 HAL_StatusTypeDef HAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID)
1948 {
1949   HAL_StatusTypeDef status = HAL_OK;
1950 
1951   if (hsd->State == HAL_SD_STATE_READY)
1952   {
1953     switch (CallbackID)
1954     {
1955       case HAL_SD_TX_CPLT_CB_ID :
1956         hsd->TxCpltCallback = HAL_SD_TxCpltCallback;
1957         break;
1958       case HAL_SD_RX_CPLT_CB_ID :
1959         hsd->RxCpltCallback = HAL_SD_RxCpltCallback;
1960         break;
1961       case HAL_SD_ERROR_CB_ID :
1962         hsd->ErrorCallback = HAL_SD_ErrorCallback;
1963         break;
1964       case HAL_SD_ABORT_CB_ID :
1965         hsd->AbortCpltCallback = HAL_SD_AbortCallback;
1966         break;
1967       case HAL_SD_READ_DMA_LNKLST_BUF_CPLT_CB_ID :
1968         hsd->Read_DMALnkLstBufCpltCallback = HAL_SDEx_Read_DMALnkLstBufCpltCallback;
1969         break;
1970       case HAL_SD_WRITE_DMA_LNKLST_BUF_CPLT_CB_ID :
1971         hsd->Write_DMALnkLstBufCpltCallback = HAL_SDEx_Write_DMALnkLstBufCpltCallback;
1972         break;
1973       case HAL_SD_MSP_INIT_CB_ID :
1974         hsd->MspInitCallback = HAL_SD_MspInit;
1975         break;
1976       case HAL_SD_MSP_DEINIT_CB_ID :
1977         hsd->MspDeInitCallback = HAL_SD_MspDeInit;
1978         break;
1979       default :
1980         /* Update the error code */
1981         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1982         /* update return status */
1983         status =  HAL_ERROR;
1984         break;
1985     }
1986   }
1987   else if (hsd->State == HAL_SD_STATE_RESET)
1988   {
1989     switch (CallbackID)
1990     {
1991       case HAL_SD_MSP_INIT_CB_ID :
1992         hsd->MspInitCallback = HAL_SD_MspInit;
1993         break;
1994       case HAL_SD_MSP_DEINIT_CB_ID :
1995         hsd->MspDeInitCallback = HAL_SD_MspDeInit;
1996         break;
1997       default :
1998         /* Update the error code */
1999         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2000         /* update return status */
2001         status =  HAL_ERROR;
2002         break;
2003     }
2004   }
2005   else
2006   {
2007     /* Update the error code */
2008     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2009     /* update return status */
2010     status =  HAL_ERROR;
2011   }
2012 
2013   return status;
2014 }
2015 
2016 #if (USE_SD_TRANSCEIVER != 0U)
2017 /**
2018   * @brief  Register a User SD Transceiver Callback
2019   *         To be used instead of the weak (overridden) predefined callback
2020   * @param hsd : SD handle
2021   * @param pCallback : pointer to the Callback function
2022   * @retval status
2023   */
HAL_SD_RegisterTransceiverCallback(SD_HandleTypeDef * hsd,pSD_TransceiverCallbackTypeDef pCallback)2024 HAL_StatusTypeDef HAL_SD_RegisterTransceiverCallback(SD_HandleTypeDef *hsd, pSD_TransceiverCallbackTypeDef pCallback)
2025 {
2026   HAL_StatusTypeDef status = HAL_OK;
2027 
2028   if (pCallback == NULL)
2029   {
2030     /* Update the error code */
2031     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2032     return HAL_ERROR;
2033   }
2034 
2035   /* Process locked */
2036   __HAL_LOCK(hsd);
2037 
2038   if (hsd->State == HAL_SD_STATE_READY)
2039   {
2040     hsd->DriveTransceiver_1_8V_Callback = pCallback;
2041   }
2042   else
2043   {
2044     /* Update the error code */
2045     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2046     /* update return status */
2047     status =  HAL_ERROR;
2048   }
2049 
2050   /* Release Lock */
2051   __HAL_UNLOCK(hsd);
2052   return status;
2053 }
2054 
2055 /**
2056   * @brief  Unregister a User SD Transceiver Callback
2057   *         SD Callback is redirected to the weak (overridden) predefined callback
2058   * @param hsd : SD handle
2059   * @retval status
2060   */
HAL_SD_UnRegisterTransceiverCallback(SD_HandleTypeDef * hsd)2061 HAL_StatusTypeDef HAL_SD_UnRegisterTransceiverCallback(SD_HandleTypeDef *hsd)
2062 {
2063   HAL_StatusTypeDef status = HAL_OK;
2064 
2065   /* Process locked */
2066   __HAL_LOCK(hsd);
2067 
2068   if (hsd->State == HAL_SD_STATE_READY)
2069   {
2070     hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback;
2071   }
2072   else
2073   {
2074     /* Update the error code */
2075     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2076     /* update return status */
2077     status =  HAL_ERROR;
2078   }
2079 
2080   /* Release Lock */
2081   __HAL_UNLOCK(hsd);
2082   return status;
2083 }
2084 #endif /* USE_SD_TRANSCEIVER */
2085 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
2086 
2087 /**
2088   * @}
2089   */
2090 
2091 /** @addtogroup SD_Exported_Functions_Group3
2092   *  @brief   management functions
2093   *
2094 @verbatim
2095   ==============================================================================
2096                       ##### Peripheral Control functions #####
2097   ==============================================================================
2098   [..]
2099     This subsection provides a set of functions allowing to control the SD card
2100     operations and get the related information
2101 
2102 @endverbatim
2103   * @{
2104   */
2105 
2106 /**
2107   * @brief  Returns information the information of the card which are stored on
2108   *         the CID register.
2109   * @param  hsd: Pointer to SD handle
2110   * @param  pCID: Pointer to a HAL_SD_CardCIDTypeDef structure that
2111   *         contains all CID register parameters
2112   * @retval HAL status
2113   */
HAL_SD_GetCardCID(SD_HandleTypeDef * hsd,HAL_SD_CardCIDTypeDef * pCID)2114 HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID)
2115 {
2116   pCID->ManufacturerID = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24U);
2117 
2118   pCID->OEM_AppliID = (uint16_t)((hsd->CID[0] & 0x00FFFF00U) >> 8U);
2119 
2120   pCID->ProdName1 = (((hsd->CID[0] & 0x000000FFU) << 24U) | ((hsd->CID[1] & 0xFFFFFF00U) >> 8U));
2121 
2122   pCID->ProdName2 = (uint8_t)(hsd->CID[1] & 0x000000FFU);
2123 
2124   pCID->ProdRev = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24U);
2125 
2126   pCID->ProdSN = (((hsd->CID[2] & 0x00FFFFFFU) << 8U) | ((hsd->CID[3] & 0xFF000000U) >> 24U));
2127 
2128   pCID->Reserved1 = (uint8_t)((hsd->CID[3] & 0x00F00000U) >> 20U);
2129 
2130   pCID->ManufactDate = (uint16_t)((hsd->CID[3] & 0x000FFF00U) >> 8U);
2131 
2132   pCID->CID_CRC = (uint8_t)((hsd->CID[3] & 0x000000FEU) >> 1U);
2133 
2134   pCID->Reserved2 = 1U;
2135 
2136   return HAL_OK;
2137 }
2138 
2139 /**
2140   * @brief  Returns information the information of the card which are stored on
2141   *         the CSD register.
2142   * @param  hsd: Pointer to SD handle
2143   * @param  pCSD: Pointer to a HAL_SD_CardCSDTypeDef structure that
2144   *         contains all CSD register parameters
2145   * @retval HAL status
2146   */
HAL_SD_GetCardCSD(SD_HandleTypeDef * hsd,HAL_SD_CardCSDTypeDef * pCSD)2147 HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD)
2148 {
2149   pCSD->CSDStruct = (uint8_t)((hsd->CSD[0] & 0xC0000000U) >> 30U);
2150 
2151   pCSD->SysSpecVersion = (uint8_t)((hsd->CSD[0] & 0x3C000000U) >> 26U);
2152 
2153   pCSD->Reserved1 = (uint8_t)((hsd->CSD[0] & 0x03000000U) >> 24U);
2154 
2155   pCSD->TAAC = (uint8_t)((hsd->CSD[0] & 0x00FF0000U) >> 16U);
2156 
2157   pCSD->NSAC = (uint8_t)((hsd->CSD[0] & 0x0000FF00U) >> 8U);
2158 
2159   pCSD->MaxBusClkFrec = (uint8_t)(hsd->CSD[0] & 0x000000FFU);
2160 
2161   pCSD->CardComdClasses = (uint16_t)((hsd->CSD[1] & 0xFFF00000U) >> 20U);
2162 
2163   pCSD->RdBlockLen = (uint8_t)((hsd->CSD[1] & 0x000F0000U) >> 16U);
2164 
2165   pCSD->PartBlockRead   = (uint8_t)((hsd->CSD[1] & 0x00008000U) >> 15U);
2166 
2167   pCSD->WrBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00004000U) >> 14U);
2168 
2169   pCSD->RdBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00002000U) >> 13U);
2170 
2171   pCSD->DSRImpl = (uint8_t)((hsd->CSD[1] & 0x00001000U) >> 12U);
2172 
2173   pCSD->Reserved2 = 0U; /*!< Reserved */
2174 
2175   if (hsd->SdCard.CardType == CARD_SDSC)
2176   {
2177     pCSD->DeviceSize = (((hsd->CSD[1] & 0x000003FFU) << 2U) | ((hsd->CSD[2] & 0xC0000000U) >> 30U));
2178 
2179     pCSD->MaxRdCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x38000000U) >> 27U);
2180 
2181     pCSD->MaxRdCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x07000000U) >> 24U);
2182 
2183     pCSD->MaxWrCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x00E00000U) >> 21U);
2184 
2185     pCSD->MaxWrCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x001C0000U) >> 18U);
2186 
2187     pCSD->DeviceSizeMul = (uint8_t)((hsd->CSD[2] & 0x00038000U) >> 15U);
2188 
2189     hsd->SdCard.BlockNbr  = (pCSD->DeviceSize + 1U) ;
2190     hsd->SdCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U));
2191     hsd->SdCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU));
2192 
2193     hsd->SdCard.LogBlockNbr = (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / BLOCKSIZE);
2194     hsd->SdCard.LogBlockSize = BLOCKSIZE;
2195   }
2196   else if (hsd->SdCard.CardType == CARD_SDHC_SDXC)
2197   {
2198     /* Byte 7 */
2199     pCSD->DeviceSize = (((hsd->CSD[1] & 0x0000003FU) << 16U) | ((hsd->CSD[2] & 0xFFFF0000U) >> 16U));
2200 
2201     hsd->SdCard.BlockNbr = ((pCSD->DeviceSize + 1U) * 1024U);
2202     hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr;
2203     hsd->SdCard.BlockSize = BLOCKSIZE;
2204     hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize;
2205   }
2206   else
2207   {
2208     /* Clear all the static flags */
2209     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2210     hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2211     hsd->State = HAL_SD_STATE_READY;
2212     return HAL_ERROR;
2213   }
2214 
2215   pCSD->EraseGrSize = (uint8_t)((hsd->CSD[2] & 0x00004000U) >> 14U);
2216 
2217   pCSD->EraseGrMul = (uint8_t)((hsd->CSD[2] & 0x00003F80U) >> 7U);
2218 
2219   pCSD->WrProtectGrSize = (uint8_t)(hsd->CSD[2] & 0x0000007FU);
2220 
2221   pCSD->WrProtectGrEnable = (uint8_t)((hsd->CSD[3] & 0x80000000U) >> 31U);
2222 
2223   pCSD->ManDeflECC = (uint8_t)((hsd->CSD[3] & 0x60000000U) >> 29U);
2224 
2225   pCSD->WrSpeedFact = (uint8_t)((hsd->CSD[3] & 0x1C000000U) >> 26U);
2226 
2227   pCSD->MaxWrBlockLen = (uint8_t)((hsd->CSD[3] & 0x03C00000U) >> 22U);
2228 
2229   pCSD->WriteBlockPaPartial = (uint8_t)((hsd->CSD[3] & 0x00200000U) >> 21U);
2230 
2231   pCSD->Reserved3 = 0;
2232 
2233   pCSD->ContentProtectAppli = (uint8_t)((hsd->CSD[3] & 0x00010000U) >> 16U);
2234 
2235   pCSD->FileFormatGroup = (uint8_t)((hsd->CSD[3] & 0x00008000U) >> 15U);
2236 
2237   pCSD->CopyFlag = (uint8_t)((hsd->CSD[3] & 0x00004000U) >> 14U);
2238 
2239   pCSD->PermWrProtect = (uint8_t)((hsd->CSD[3] & 0x00002000U) >> 13U);
2240 
2241   pCSD->TempWrProtect = (uint8_t)((hsd->CSD[3] & 0x00001000U) >> 12U);
2242 
2243   pCSD->FileFormat = (uint8_t)((hsd->CSD[3] & 0x00000C00U) >> 10U);
2244 
2245   pCSD->ECC = (uint8_t)((hsd->CSD[3] & 0x00000300U) >> 8U);
2246 
2247   pCSD->CSD_CRC = (uint8_t)((hsd->CSD[3] & 0x000000FEU) >> 1U);
2248 
2249   pCSD->Reserved4 = 1;
2250 
2251   return HAL_OK;
2252 }
2253 
2254 /**
2255   * @brief  Gets the SD status info.( shall be called if there is no SD transaction ongoing )
2256   * @param  hsd: Pointer to SD handle
2257   * @param  pStatus: Pointer to the HAL_SD_CardStatusTypeDef structure that
2258   *         will contain the SD card status information
2259   * @retval HAL status
2260   */
HAL_SD_GetCardStatus(SD_HandleTypeDef * hsd,HAL_SD_CardStatusTypeDef * pStatus)2261 HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus)
2262 {
2263   uint32_t sd_status[16];
2264   uint32_t errorstate;
2265   HAL_StatusTypeDef status = HAL_OK;
2266 
2267   if (hsd->State == HAL_SD_STATE_BUSY)
2268   {
2269     return HAL_ERROR;
2270   }
2271 
2272   errorstate = SD_SendSDStatus(hsd, sd_status);
2273   if (errorstate != HAL_SD_ERROR_NONE)
2274   {
2275     /* Clear all the static flags */
2276     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2277     hsd->ErrorCode |= errorstate;
2278     hsd->State = HAL_SD_STATE_READY;
2279     status = HAL_ERROR;
2280   }
2281   else
2282   {
2283     pStatus->DataBusWidth = (uint8_t)((sd_status[0] & 0xC0U) >> 6U);
2284 
2285     pStatus->SecuredMode = (uint8_t)((sd_status[0] & 0x20U) >> 5U);
2286 
2287     pStatus->CardType = (uint16_t)(((sd_status[0] & 0x00FF0000U) >> 8U) | ((sd_status[0] & 0xFF000000U) >> 24U));
2288 
2289     pStatus->ProtectedAreaSize = (((sd_status[1] & 0xFFU) << 24U)    | ((sd_status[1] & 0xFF00U) << 8U) |
2290                                   ((sd_status[1] & 0xFF0000U) >> 8U) | ((sd_status[1] & 0xFF000000U) >> 24U));
2291 
2292     pStatus->SpeedClass = (uint8_t)(sd_status[2] & 0xFFU);
2293 
2294     pStatus->PerformanceMove = (uint8_t)((sd_status[2] & 0xFF00U) >> 8U);
2295 
2296     pStatus->AllocationUnitSize = (uint8_t)((sd_status[2] & 0xF00000U) >> 20U);
2297 
2298     pStatus->EraseSize = (uint16_t)(((sd_status[2] & 0xFF000000U) >> 16U) | (sd_status[3] & 0xFFU));
2299 
2300     pStatus->EraseTimeout = (uint8_t)((sd_status[3] & 0xFC00U) >> 10U);
2301 
2302     pStatus->EraseOffset = (uint8_t)((sd_status[3] & 0x0300U) >> 8U);
2303 
2304     pStatus->UhsSpeedGrade = (uint8_t)((sd_status[3] & 0x00F0U) >> 4U);
2305     pStatus->UhsAllocationUnitSize = (uint8_t)(sd_status[3] & 0x000FU) ;
2306     pStatus->VideoSpeedClass = (uint8_t)((sd_status[4] & 0xFF000000U) >> 24U);
2307   }
2308 
2309   /* Set Block Size for Card */
2310   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
2311   if (errorstate != HAL_SD_ERROR_NONE)
2312   {
2313     /* Clear all the static flags */
2314     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2315     hsd->ErrorCode = errorstate;
2316     hsd->State = HAL_SD_STATE_READY;
2317     status = HAL_ERROR;
2318   }
2319 
2320   return status;
2321 }
2322 
2323 /**
2324   * @brief  Gets the SD card info.
2325   * @param  hsd: Pointer to SD handle
2326   * @param  pCardInfo: Pointer to the HAL_SD_CardInfoTypeDef structure that
2327   *         will contain the SD card status information
2328   * @retval HAL status
2329   */
HAL_SD_GetCardInfo(SD_HandleTypeDef * hsd,HAL_SD_CardInfoTypeDef * pCardInfo)2330 HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo)
2331 {
2332   pCardInfo->CardType     = (uint32_t)(hsd->SdCard.CardType);
2333   pCardInfo->CardVersion  = (uint32_t)(hsd->SdCard.CardVersion);
2334   pCardInfo->Class        = (uint32_t)(hsd->SdCard.Class);
2335   pCardInfo->RelCardAdd   = (uint32_t)(hsd->SdCard.RelCardAdd);
2336   pCardInfo->BlockNbr     = (uint32_t)(hsd->SdCard.BlockNbr);
2337   pCardInfo->BlockSize    = (uint32_t)(hsd->SdCard.BlockSize);
2338   pCardInfo->LogBlockNbr  = (uint32_t)(hsd->SdCard.LogBlockNbr);
2339   pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize);
2340 
2341   return HAL_OK;
2342 }
2343 
2344 /**
2345   * @brief  Enables wide bus operation for the requested card if supported by
2346   *         card.
2347   * @param  hsd: Pointer to SD handle
2348   * @param  WideMode: Specifies the SD card wide bus mode
2349   *          This parameter can be one of the following values:
2350   *            @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer
2351   *            @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer
2352   *            @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer
2353   * @retval HAL status
2354   */
HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef * hsd,uint32_t WideMode)2355 HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode)
2356 {
2357   SDMMC_InitTypeDef Init;
2358   uint32_t errorstate;
2359   uint32_t sdmmc_clk;
2360 
2361   HAL_StatusTypeDef status = HAL_OK;
2362 
2363   /* Check the parameters */
2364   assert_param(IS_SDMMC_BUS_WIDE(WideMode));
2365 
2366   /* Change State */
2367   hsd->State = HAL_SD_STATE_BUSY;
2368 
2369   if (hsd->SdCard.CardType != CARD_SECURED)
2370   {
2371     if (WideMode == SDMMC_BUS_WIDE_8B)
2372     {
2373       hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2374     }
2375     else if (WideMode == SDMMC_BUS_WIDE_4B)
2376     {
2377       errorstate = SD_WideBus_Enable(hsd);
2378 
2379       hsd->ErrorCode |= errorstate;
2380     }
2381     else if (WideMode == SDMMC_BUS_WIDE_1B)
2382     {
2383       errorstate = SD_WideBus_Disable(hsd);
2384 
2385       hsd->ErrorCode |= errorstate;
2386     }
2387     else
2388     {
2389       /* WideMode is not a valid argument*/
2390       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2391     }
2392   }
2393   else
2394   {
2395     /* SD Card does not support this feature */
2396     hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2397   }
2398 
2399   if (hsd->ErrorCode != HAL_SD_ERROR_NONE)
2400   {
2401     /* Clear all the static flags */
2402     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2403     status = HAL_ERROR;
2404   }
2405   else
2406   {
2407     sdmmc_clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC12);
2408     if (sdmmc_clk != 0U)
2409     {
2410       /* Configure the SDMMC peripheral */
2411       Init.ClockEdge           = hsd->Init.ClockEdge;
2412       Init.ClockPowerSave      = hsd->Init.ClockPowerSave;
2413       Init.BusWide             = WideMode;
2414       Init.HardwareFlowControl = hsd->Init.HardwareFlowControl;
2415 
2416       /* Check if user Clock div < Normal speed 25Mhz, no change in Clockdiv */
2417       if (hsd->Init.ClockDiv >= (sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ)))
2418       {
2419         Init.ClockDiv = hsd->Init.ClockDiv;
2420       }
2421       else if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED)
2422       {
2423         /* UltraHigh speed SD card,user Clock div */
2424         Init.ClockDiv = hsd->Init.ClockDiv;
2425       }
2426       else if (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED)
2427       {
2428         /* High speed SD card, Max Frequency = 50Mhz */
2429         if (hsd->Init.ClockDiv == 0U)
2430         {
2431           if (sdmmc_clk > SD_HIGH_SPEED_FREQ)
2432           {
2433             Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ);
2434           }
2435           else
2436           {
2437             Init.ClockDiv = hsd->Init.ClockDiv;
2438           }
2439         }
2440         else
2441         {
2442           if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_HIGH_SPEED_FREQ)
2443           {
2444             Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ);
2445           }
2446           else
2447           {
2448             Init.ClockDiv = hsd->Init.ClockDiv;
2449           }
2450         }
2451       }
2452       else
2453       {
2454         /* No High speed SD card, Max Frequency = 25Mhz */
2455         if (hsd->Init.ClockDiv == 0U)
2456         {
2457           if (sdmmc_clk > SD_NORMAL_SPEED_FREQ)
2458           {
2459             Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ);
2460           }
2461           else
2462           {
2463             Init.ClockDiv = hsd->Init.ClockDiv;
2464           }
2465         }
2466         else
2467         {
2468           if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_NORMAL_SPEED_FREQ)
2469           {
2470             Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ);
2471           }
2472           else
2473           {
2474             Init.ClockDiv = hsd->Init.ClockDiv;
2475           }
2476         }
2477       }
2478 
2479 #if (USE_SD_TRANSCEIVER != 0U)
2480       Init.TranceiverPresent = hsd->Init.TranceiverPresent;
2481 #endif /* USE_SD_TRANSCEIVER */
2482 
2483       (void)SDMMC_Init(hsd->Instance, Init);
2484     }
2485     else
2486     {
2487       hsd->ErrorCode |= SDMMC_ERROR_INVALID_PARAMETER;
2488       status = HAL_ERROR;
2489     }
2490   }
2491 
2492   /* Set Block Size for Card */
2493   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
2494   if (errorstate != HAL_SD_ERROR_NONE)
2495   {
2496     /* Clear all the static flags */
2497     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2498     hsd->ErrorCode |= errorstate;
2499     status = HAL_ERROR;
2500   }
2501 
2502   /* Change State */
2503   hsd->State = HAL_SD_STATE_READY;
2504 
2505   return status;
2506 }
2507 
2508 /**
2509   * @brief  Configure the speed bus mode
2510   * @param  hsd: Pointer to the SD handle
2511   * @param  SpeedMode: Specifies the SD card speed bus mode
2512   *          This parameter can be one of the following values:
2513   *            @arg SDMMC_SPEED_MODE_AUTO: Max speed mode supported by the card
2514   *            @arg SDMMC_SPEED_MODE_DEFAULT: Default Speed/SDR12 mode
2515   *            @arg SDMMC_SPEED_MODE_HIGH: High Speed/SDR25 mode
2516   *            @arg SDMMC_SPEED_MODE_ULTRA: Ultra high speed mode
2517   * @retval HAL status
2518   */
2519 
HAL_SD_ConfigSpeedBusOperation(SD_HandleTypeDef * hsd,uint32_t SpeedMode)2520 HAL_StatusTypeDef HAL_SD_ConfigSpeedBusOperation(SD_HandleTypeDef *hsd, uint32_t SpeedMode)
2521 {
2522   uint32_t tickstart;
2523   uint32_t errorstate;
2524   HAL_StatusTypeDef status = HAL_OK;
2525 
2526   /* Check the parameters */
2527   assert_param(IS_SDMMC_SPEED_MODE(SpeedMode));
2528   /* Change State */
2529   hsd->State = HAL_SD_STATE_BUSY;
2530 
2531 #if (USE_SD_TRANSCEIVER != 0U)
2532   if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
2533   {
2534     switch (SpeedMode)
2535     {
2536       case SDMMC_SPEED_MODE_AUTO:
2537       {
2538         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2539             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2540         {
2541           hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED;
2542           /* Enable Ultra High Speed */
2543           if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2544           {
2545             if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2546             {
2547               hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2548               status = HAL_ERROR;
2549             }
2550           }
2551         }
2552         else if (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED)
2553         {
2554           /* Enable High Speed */
2555           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2556           {
2557             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2558             status = HAL_ERROR;
2559           }
2560         }
2561         else
2562         {
2563           /*Nothing to do, Use defaultSpeed */
2564         }
2565         break;
2566       }
2567       case SDMMC_SPEED_MODE_ULTRA_SDR104:
2568       {
2569         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2570             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2571         {
2572           /* Enable UltraHigh Speed */
2573           if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2574           {
2575             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2576             status = HAL_ERROR;
2577           }
2578           hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED;
2579         }
2580         else
2581         {
2582           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2583           status = HAL_ERROR;
2584         }
2585         break;
2586       }
2587       case SDMMC_SPEED_MODE_ULTRA_SDR50:
2588       {
2589         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2590             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2591         {
2592           /* Enable UltraHigh Speed */
2593           if (SD_UltraHighSpeed(hsd, SDMMC_SDR50_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2594           {
2595             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2596             status = HAL_ERROR;
2597           }
2598           hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED;
2599         }
2600         else
2601         {
2602           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2603           status = HAL_ERROR;
2604         }
2605         break;
2606       }
2607       case SDMMC_SPEED_MODE_DDR:
2608       {
2609         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2610             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2611         {
2612           /* Enable DDR Mode*/
2613           if (SD_DDR_Mode(hsd) != HAL_SD_ERROR_NONE)
2614           {
2615             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2616             status = HAL_ERROR;
2617           }
2618           hsd->Instance->CLKCR |=  SDMMC_CLKCR_BUSSPEED | SDMMC_CLKCR_DDR;
2619         }
2620         else
2621         {
2622           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2623           status = HAL_ERROR;
2624         }
2625         break;
2626       }
2627       case SDMMC_SPEED_MODE_HIGH:
2628       {
2629         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2630             (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2631             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2632         {
2633           /* Enable High Speed */
2634           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2635           {
2636             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2637             status = HAL_ERROR;
2638           }
2639         }
2640         else
2641         {
2642           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2643           status = HAL_ERROR;
2644         }
2645         break;
2646       }
2647       case SDMMC_SPEED_MODE_DEFAULT:
2648       {
2649         /* Switch to default Speed */
2650         if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2651         {
2652           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2653           status = HAL_ERROR;
2654         }
2655 
2656         break;
2657       }
2658       default:
2659         hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2660         status = HAL_ERROR;
2661         break;
2662     }
2663   }
2664   else
2665   {
2666     switch (SpeedMode)
2667     {
2668       case SDMMC_SPEED_MODE_AUTO:
2669       {
2670         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2671             (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2672             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2673         {
2674           /* Enable High Speed */
2675           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2676           {
2677             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2678             status = HAL_ERROR;
2679           }
2680         }
2681         else
2682         {
2683           /*Nothing to do, Use defaultSpeed */
2684         }
2685         break;
2686       }
2687       case SDMMC_SPEED_MODE_HIGH:
2688       {
2689         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2690             (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2691             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2692         {
2693           /* Enable High Speed */
2694           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2695           {
2696             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2697             status = HAL_ERROR;
2698           }
2699         }
2700         else
2701         {
2702           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2703           status = HAL_ERROR;
2704         }
2705         break;
2706       }
2707       case SDMMC_SPEED_MODE_DEFAULT:
2708       {
2709         /* Switch to default Speed */
2710         if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2711         {
2712           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2713           status = HAL_ERROR;
2714         }
2715 
2716         break;
2717       }
2718       case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/
2719       default:
2720         hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2721         status = HAL_ERROR;
2722         break;
2723     }
2724   }
2725 #else
2726   switch (SpeedMode)
2727   {
2728     case SDMMC_SPEED_MODE_AUTO:
2729     {
2730       if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2731           (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2732           (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2733       {
2734         /* Enable High Speed */
2735         if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2736         {
2737           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2738           status = HAL_ERROR;
2739         }
2740       }
2741       else
2742       {
2743         /*Nothing to do, Use defaultSpeed */
2744       }
2745       break;
2746     }
2747     case SDMMC_SPEED_MODE_HIGH:
2748     {
2749       if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2750           (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2751           (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2752       {
2753         /* Enable High Speed */
2754         if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2755         {
2756           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2757           status = HAL_ERROR;
2758         }
2759       }
2760       else
2761       {
2762         hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2763         status = HAL_ERROR;
2764       }
2765       break;
2766     }
2767     case SDMMC_SPEED_MODE_DEFAULT:
2768     {
2769       /* Switch to default Speed */
2770       if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2771       {
2772         hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2773         status = HAL_ERROR;
2774       }
2775 
2776       break;
2777     }
2778     case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/
2779     default:
2780       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2781       status = HAL_ERROR;
2782       break;
2783   }
2784 #endif /* USE_SD_TRANSCEIVER */
2785 
2786   /* Verify that SD card is ready to use after Speed mode switch*/
2787   tickstart = HAL_GetTick();
2788   while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER))
2789   {
2790     if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
2791     {
2792       hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2793       hsd->State = HAL_SD_STATE_READY;
2794       return HAL_TIMEOUT;
2795     }
2796   }
2797 
2798   /* Set Block Size for Card */
2799   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
2800   if (errorstate != HAL_SD_ERROR_NONE)
2801   {
2802     /* Clear all the static flags */
2803     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2804     hsd->ErrorCode |= errorstate;
2805     status = HAL_ERROR;
2806   }
2807 
2808   /* Change State */
2809   hsd->State = HAL_SD_STATE_READY;
2810   return status;
2811 }
2812 
2813 /**
2814   * @brief  Gets the current sd card data state.
2815   * @param  hsd: pointer to SD handle
2816   * @retval Card state
2817   */
HAL_SD_GetCardState(SD_HandleTypeDef * hsd)2818 HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd)
2819 {
2820   uint32_t cardstate;
2821   uint32_t errorstate;
2822   uint32_t resp1 = 0;
2823 
2824   errorstate = SD_SendStatus(hsd, &resp1);
2825   if (errorstate != HAL_SD_ERROR_NONE)
2826   {
2827     hsd->ErrorCode |= errorstate;
2828   }
2829 
2830   cardstate = ((resp1 >> 9U) & 0x0FU);
2831 
2832   return (HAL_SD_CardStateTypeDef)cardstate;
2833 }
2834 
2835 /**
2836   * @brief  Abort the current transfer and disable the SD.
2837   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
2838   *                the configuration information for SD module.
2839   * @retval HAL status
2840   */
HAL_SD_Abort(SD_HandleTypeDef * hsd)2841 HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd)
2842 {
2843   uint32_t error_code;
2844   uint32_t tickstart;
2845 
2846   if (hsd->State == HAL_SD_STATE_BUSY)
2847   {
2848     /* DIsable All interrupts */
2849     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
2850                         SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR);
2851     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
2852 
2853     /*we will send the CMD12 in all cases in order to stop the data transfers*/
2854     /*In case the data transfer just finished , the external memory will not respond
2855       and will return HAL_SD_ERROR_CMD_RSP_TIMEOUT*/
2856     /*In case the data transfer aborted , the external memory will respond and will return HAL_SD_ERROR_NONE*/
2857     /*Other scenario will return HAL_ERROR*/
2858 
2859     hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance);
2860     error_code = hsd->ErrorCode;
2861     if ((error_code != HAL_SD_ERROR_NONE) && (error_code != HAL_SD_ERROR_CMD_RSP_TIMEOUT))
2862     {
2863       return HAL_ERROR;
2864     }
2865 
2866     tickstart = HAL_GetTick();
2867     if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_CARD)
2868     {
2869       if (hsd->ErrorCode == HAL_SD_ERROR_NONE)
2870       {
2871         while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_BUSYD0END))
2872         {
2873           if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
2874           {
2875             hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2876             hsd->State = HAL_SD_STATE_READY;
2877             return HAL_TIMEOUT;
2878           }
2879         }
2880       }
2881 
2882       if (hsd->ErrorCode == HAL_SD_ERROR_CMD_RSP_TIMEOUT)
2883       {
2884         while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND))
2885         {
2886           if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
2887           {
2888             hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2889             hsd->State = HAL_SD_STATE_READY;
2890             return HAL_TIMEOUT;
2891           }
2892         }
2893       }
2894     }
2895     else if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_SDMMC)
2896     {
2897       while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_DATAEND))
2898       {
2899         if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
2900         {
2901           hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2902           hsd->State = HAL_SD_STATE_READY;
2903           return HAL_TIMEOUT;
2904         }
2905       }
2906     }
2907     else
2908     {
2909       /* Nothing to do*/
2910     }
2911 
2912     /*The reason of all these while conditions previously is that we need to wait the SDMMC and clear
2913       the appropriate flags that will be set depending of the abort/non abort of the memory */
2914     /*Not waiting the SDMMC flags will cause the next SDMMC_DISABLE_IDMA to not get cleared
2915       and will result in next SDMMC read/write operation to fail */
2916 
2917     /*SDMMC ready for clear data flags*/
2918     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_BUSYD0END);
2919     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
2920     /* If IDMA Context, disable Internal DMA */
2921     hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
2922 
2923     hsd->State = HAL_SD_STATE_READY;
2924 
2925     /* Initialize the SD operation */
2926     hsd->Context = SD_CONTEXT_NONE;
2927   }
2928   return HAL_OK;
2929 }
2930 
2931 /**
2932   * @brief  Abort the current transfer and disable the SD (IT mode).
2933   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
2934   *                the configuration information for SD module.
2935   * @retval HAL status
2936   */
HAL_SD_Abort_IT(SD_HandleTypeDef * hsd)2937 HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd)
2938 {
2939   HAL_SD_CardStateTypeDef CardState;
2940 
2941   /* Disable All interrupts */
2942   __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
2943                       SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR);
2944 
2945   /* If IDMA Context, disable Internal DMA */
2946   hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
2947 
2948   /* Clear All flags */
2949   __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
2950 
2951   CardState = HAL_SD_GetCardState(hsd);
2952   hsd->State = HAL_SD_STATE_READY;
2953 
2954   if ((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
2955   {
2956     hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance);
2957   }
2958 
2959   if (hsd->ErrorCode != HAL_SD_ERROR_NONE)
2960   {
2961     return HAL_ERROR;
2962   }
2963   else
2964   {
2965 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
2966     hsd->AbortCpltCallback(hsd);
2967 #else
2968     HAL_SD_AbortCallback(hsd);
2969 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
2970   }
2971 
2972   return HAL_OK;
2973 }
2974 
2975 /**
2976   * @}
2977   */
2978 
2979 /**
2980   * @}
2981   */
2982 
2983 /* Private function ----------------------------------------------------------*/
2984 /** @addtogroup SD_Private_Functions
2985   * @{
2986   */
2987 
2988 /**
2989   * @brief  Initializes the sd card.
2990   * @param  hsd: Pointer to SD handle
2991   * @retval SD Card error state
2992   */
SD_InitCard(SD_HandleTypeDef * hsd)2993 static uint32_t SD_InitCard(SD_HandleTypeDef *hsd)
2994 {
2995   HAL_SD_CardCSDTypeDef CSD;
2996   uint32_t errorstate;
2997   uint16_t sd_rca = 0U;
2998   uint32_t tickstart = HAL_GetTick();
2999 
3000   /* Check the power State */
3001   if (SDMMC_GetPowerState(hsd->Instance) == 0U)
3002   {
3003     /* Power off */
3004     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3005   }
3006 
3007   if (hsd->SdCard.CardType != CARD_SECURED)
3008   {
3009     /* Send CMD2 ALL_SEND_CID */
3010     errorstate = SDMMC_CmdSendCID(hsd->Instance);
3011     if (errorstate != HAL_SD_ERROR_NONE)
3012     {
3013       return errorstate;
3014     }
3015     else
3016     {
3017       /* Get Card identification number data */
3018       hsd->CID[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3019       hsd->CID[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2);
3020       hsd->CID[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3);
3021       hsd->CID[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4);
3022     }
3023   }
3024 
3025   if (hsd->SdCard.CardType != CARD_SECURED)
3026   {
3027     /* Send CMD3 SET_REL_ADDR with argument 0 */
3028     /* SD Card publishes its RCA. */
3029     while (sd_rca == 0U)
3030     {
3031       errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca);
3032       if (errorstate != HAL_SD_ERROR_NONE)
3033       {
3034         return errorstate;
3035       }
3036       if ((HAL_GetTick() - tickstart) >=  SDMMC_CMDTIMEOUT)
3037       {
3038         return HAL_SD_ERROR_TIMEOUT;
3039       }
3040     }
3041   }
3042   if (hsd->SdCard.CardType != CARD_SECURED)
3043   {
3044     /* Get the SD card RCA */
3045     hsd->SdCard.RelCardAdd = sd_rca;
3046 
3047     /* Send CMD9 SEND_CSD with argument as card's RCA */
3048     errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3049     if (errorstate != HAL_SD_ERROR_NONE)
3050     {
3051       return errorstate;
3052     }
3053     else
3054     {
3055       /* Get Card Specific Data */
3056       hsd->CSD[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3057       hsd->CSD[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2);
3058       hsd->CSD[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3);
3059       hsd->CSD[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4);
3060     }
3061   }
3062 
3063   /* Get the Card Class */
3064   hsd->SdCard.Class = (SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2) >> 20U);
3065 
3066   /* Get CSD parameters */
3067   if (HAL_SD_GetCardCSD(hsd, &CSD) != HAL_OK)
3068   {
3069     return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
3070   }
3071 
3072   /* Select the Card */
3073   errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U));
3074   if (errorstate != HAL_SD_ERROR_NONE)
3075   {
3076     return errorstate;
3077   }
3078 
3079   /* All cards are initialized */
3080   return HAL_SD_ERROR_NONE;
3081 }
3082 
3083 /**
3084   * @brief  Enquires cards about their operating voltage and configures clock
3085   *         controls and stores SD information that will be needed in future
3086   *         in the SD handle.
3087   * @param  hsd: Pointer to SD handle
3088   * @retval error state
3089   */
SD_PowerON(SD_HandleTypeDef * hsd)3090 static uint32_t SD_PowerON(SD_HandleTypeDef *hsd)
3091 {
3092   __IO uint32_t count = 0U;
3093   uint32_t response = 0U;
3094   uint32_t validvoltage = 0U;
3095   uint32_t errorstate;
3096 #if (USE_SD_TRANSCEIVER != 0U)
3097   uint32_t tickstart = HAL_GetTick();
3098 #endif /* USE_SD_TRANSCEIVER  */
3099 
3100   /* CMD0: GO_IDLE_STATE */
3101   errorstate = SDMMC_CmdGoIdleState(hsd->Instance);
3102   if (errorstate != HAL_SD_ERROR_NONE)
3103   {
3104     return errorstate;
3105   }
3106 
3107   /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */
3108   errorstate = SDMMC_CmdOperCond(hsd->Instance);
3109   if (errorstate == SDMMC_ERROR_TIMEOUT) /* No response to CMD8 */
3110   {
3111     hsd->SdCard.CardVersion = CARD_V1_X;
3112     /* CMD0: GO_IDLE_STATE */
3113     errorstate = SDMMC_CmdGoIdleState(hsd->Instance);
3114     if (errorstate != HAL_SD_ERROR_NONE)
3115     {
3116       return errorstate;
3117     }
3118 
3119   }
3120   else
3121   {
3122     hsd->SdCard.CardVersion = CARD_V2_X;
3123   }
3124 
3125   if (hsd->SdCard.CardVersion == CARD_V2_X)
3126   {
3127     /* SEND CMD55 APP_CMD with RCA as 0 */
3128     errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0);
3129     if (errorstate != HAL_SD_ERROR_NONE)
3130     {
3131       return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
3132     }
3133   }
3134   /* SD CARD */
3135   /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */
3136   while ((count < SDMMC_MAX_VOLT_TRIAL) && (validvoltage == 0U))
3137   {
3138     /* SEND CMD55 APP_CMD with RCA as 0 */
3139     errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0);
3140     if (errorstate != HAL_SD_ERROR_NONE)
3141     {
3142       return errorstate;
3143     }
3144 
3145     /* Send CMD41 */
3146     errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_VOLTAGE_WINDOW_SD | SDMMC_HIGH_CAPACITY |
3147                                          SD_SWITCH_1_8V_CAPACITY);
3148     if (errorstate != HAL_SD_ERROR_NONE)
3149     {
3150       return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
3151     }
3152 
3153     /* Get command response */
3154     response = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3155 
3156     /* Get operating voltage*/
3157     validvoltage = (((response >> 31U) == 1U) ? 1U : 0U);
3158 
3159     count++;
3160   }
3161 
3162   if (count >= SDMMC_MAX_VOLT_TRIAL)
3163   {
3164     return HAL_SD_ERROR_INVALID_VOLTRANGE;
3165   }
3166 
3167   /* Set default card type */
3168   hsd->SdCard.CardType = CARD_SDSC;
3169 
3170   if ((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY)
3171   {
3172     hsd->SdCard.CardType = CARD_SDHC_SDXC;
3173 #if (USE_SD_TRANSCEIVER != 0U)
3174     if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
3175     {
3176       if ((response & SD_SWITCH_1_8V_CAPACITY) == SD_SWITCH_1_8V_CAPACITY)
3177       {
3178         hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED;
3179 
3180         /* Start switching procedue */
3181         hsd->Instance->POWER |= SDMMC_POWER_VSWITCHEN;
3182 
3183         /* Send CMD11 to switch 1.8V mode */
3184         errorstate = SDMMC_CmdVoltageSwitch(hsd->Instance);
3185         if (errorstate != HAL_SD_ERROR_NONE)
3186         {
3187           return errorstate;
3188         }
3189 
3190         /* Check to CKSTOP */
3191         while ((hsd->Instance->STA & SDMMC_FLAG_CKSTOP) != SDMMC_FLAG_CKSTOP)
3192         {
3193           if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
3194           {
3195             return HAL_SD_ERROR_TIMEOUT;
3196           }
3197         }
3198 
3199         /* Clear CKSTOP Flag */
3200         hsd->Instance->ICR = SDMMC_FLAG_CKSTOP;
3201 
3202         /* Check to BusyD0 */
3203         if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) != SDMMC_FLAG_BUSYD0)
3204         {
3205           /* Error when activate Voltage Switch in SDMMC Peripheral */
3206           return SDMMC_ERROR_UNSUPPORTED_FEATURE;
3207         }
3208         else
3209         {
3210           /* Enable Transceiver Switch PIN */
3211 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
3212           hsd->DriveTransceiver_1_8V_Callback(SET);
3213 #else
3214           HAL_SD_DriveTransceiver_1_8V_Callback(SET);
3215 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
3216 
3217           /* Switch ready */
3218           hsd->Instance->POWER |= SDMMC_POWER_VSWITCH;
3219 
3220           /* Check VSWEND Flag */
3221           while ((hsd->Instance->STA & SDMMC_FLAG_VSWEND) != SDMMC_FLAG_VSWEND)
3222           {
3223             if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
3224             {
3225               return HAL_SD_ERROR_TIMEOUT;
3226             }
3227           }
3228 
3229           /* Clear VSWEND Flag */
3230           hsd->Instance->ICR = SDMMC_FLAG_VSWEND;
3231 
3232           /* Check BusyD0 status */
3233           if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) == SDMMC_FLAG_BUSYD0)
3234           {
3235             /* Error when enabling 1.8V mode */
3236             return HAL_SD_ERROR_INVALID_VOLTRANGE;
3237           }
3238           /* Switch to 1.8V OK */
3239 
3240           /* Disable VSWITCH FLAG from SDMMC Peripheral */
3241           hsd->Instance->POWER = 0x13U;
3242 
3243           /* Clean Status flags */
3244           hsd->Instance->ICR = 0xFFFFFFFFU;
3245         }
3246       }
3247     }
3248 #endif /* USE_SD_TRANSCEIVER  */
3249   }
3250 
3251   return HAL_SD_ERROR_NONE;
3252 }
3253 
3254 /**
3255   * @brief  Turns the SDMMC output signals off.
3256   * @param  hsd: Pointer to SD handle
3257   * @retval None
3258   */
SD_PowerOFF(SD_HandleTypeDef * hsd)3259 static void SD_PowerOFF(SD_HandleTypeDef *hsd)
3260 {
3261   /* Set Power State to OFF */
3262   (void)SDMMC_PowerState_OFF(hsd->Instance);
3263 }
3264 
3265 /**
3266   * @brief  Send Status info command.
3267   * @param  hsd: pointer to SD handle
3268   * @param  pSDstatus: Pointer to the buffer that will contain the SD card status
3269   *         SD Status register)
3270   * @retval error state
3271   */
SD_SendSDStatus(SD_HandleTypeDef * hsd,uint32_t * pSDstatus)3272 static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus)
3273 {
3274   SDMMC_DataInitTypeDef config;
3275   uint32_t errorstate;
3276   uint32_t tickstart = HAL_GetTick();
3277   uint32_t count;
3278   uint32_t *pData = pSDstatus;
3279 
3280   /* Check SD response */
3281   if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3282   {
3283     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3284   }
3285 
3286   /* Set block size for card if it is not equal to current block size for card */
3287   errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3288   if (errorstate != HAL_SD_ERROR_NONE)
3289   {
3290     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
3291     return errorstate;
3292   }
3293 
3294   /* Send CMD55 */
3295   errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3296   if (errorstate != HAL_SD_ERROR_NONE)
3297   {
3298     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
3299     return errorstate;
3300   }
3301 
3302   /* Configure the SD DPSM (Data Path State Machine) */
3303   config.DataTimeOut   = SDMMC_DATATIMEOUT;
3304   config.DataLength    = 64U;
3305   config.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B;
3306   config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3307   config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3308   config.DPSM          = SDMMC_DPSM_ENABLE;
3309   (void)SDMMC_ConfigData(hsd->Instance, &config);
3310 
3311   /* Send ACMD13 (SD_APP_STAUS)  with argument as card's RCA */
3312   errorstate = SDMMC_CmdStatusRegister(hsd->Instance);
3313   if (errorstate != HAL_SD_ERROR_NONE)
3314   {
3315     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
3316     return errorstate;
3317   }
3318 
3319   /* Get status data */
3320   while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
3321   {
3322     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3323     {
3324       for (count = 0U; count < 8U; count++)
3325       {
3326         *pData = SDMMC_ReadFIFO(hsd->Instance);
3327         pData++;
3328       }
3329     }
3330 
3331     if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
3332     {
3333       return HAL_SD_ERROR_TIMEOUT;
3334     }
3335   }
3336 
3337   if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3338   {
3339     return HAL_SD_ERROR_DATA_TIMEOUT;
3340   }
3341   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3342   {
3343     return HAL_SD_ERROR_DATA_CRC_FAIL;
3344   }
3345   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3346   {
3347     return HAL_SD_ERROR_RX_OVERRUN;
3348   }
3349   else
3350   {
3351     /* Nothing to do */
3352   }
3353 
3354   while ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DPSMACT)))
3355   {
3356     *pData = SDMMC_ReadFIFO(hsd->Instance);
3357     pData++;
3358 
3359     if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
3360     {
3361       return HAL_SD_ERROR_TIMEOUT;
3362     }
3363   }
3364 
3365   /* Clear all the static status flags*/
3366   __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3367 
3368   return HAL_SD_ERROR_NONE;
3369 }
3370 
3371 /**
3372   * @brief  Returns the current card's status.
3373   * @param  hsd: Pointer to SD handle
3374   * @param  pCardStatus: pointer to the buffer that will contain the SD card
3375   *         status (Card Status register)
3376   * @retval error state
3377   */
SD_SendStatus(SD_HandleTypeDef * hsd,uint32_t * pCardStatus)3378 static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus)
3379 {
3380   uint32_t errorstate;
3381 
3382   if (pCardStatus == NULL)
3383   {
3384     return HAL_SD_ERROR_PARAM;
3385   }
3386 
3387   /* Send Status command */
3388   errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3389   if (errorstate != HAL_SD_ERROR_NONE)
3390   {
3391     return errorstate;
3392   }
3393 
3394   /* Get SD card status */
3395   *pCardStatus = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3396 
3397   return HAL_SD_ERROR_NONE;
3398 }
3399 
3400 /**
3401   * @brief  Enables the SDMMC wide bus mode.
3402   * @param  hsd: pointer to SD handle
3403   * @retval error state
3404   */
SD_WideBus_Enable(SD_HandleTypeDef * hsd)3405 static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd)
3406 {
3407   uint32_t scr[2U] = {0UL, 0UL};
3408   uint32_t errorstate;
3409 
3410   if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3411   {
3412     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3413   }
3414 
3415   /* Get SCR Register */
3416   errorstate = SD_FindSCR(hsd, scr);
3417   if (errorstate != HAL_SD_ERROR_NONE)
3418   {
3419     return errorstate;
3420   }
3421 
3422   /* If requested card supports wide bus operation */
3423   if ((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO)
3424   {
3425     /* Send CMD55 APP_CMD with argument as card's RCA.*/
3426     errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3427     if (errorstate != HAL_SD_ERROR_NONE)
3428     {
3429       return errorstate;
3430     }
3431 
3432     /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
3433     errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U);
3434     if (errorstate != HAL_SD_ERROR_NONE)
3435     {
3436       return errorstate;
3437     }
3438 
3439     return HAL_SD_ERROR_NONE;
3440   }
3441   else
3442   {
3443     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3444   }
3445 }
3446 
3447 /**
3448   * @brief  Disables the SDMMC wide bus mode.
3449   * @param  hsd: Pointer to SD handle
3450   * @retval error state
3451   */
SD_WideBus_Disable(SD_HandleTypeDef * hsd)3452 static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd)
3453 {
3454   uint32_t scr[2U] = {0UL, 0UL};
3455   uint32_t errorstate;
3456 
3457   if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3458   {
3459     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3460   }
3461 
3462   /* Get SCR Register */
3463   errorstate = SD_FindSCR(hsd, scr);
3464   if (errorstate != HAL_SD_ERROR_NONE)
3465   {
3466     return errorstate;
3467   }
3468 
3469   /* If requested card supports 1 bit mode operation */
3470   if ((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO)
3471   {
3472     /* Send CMD55 APP_CMD with argument as card's RCA */
3473     errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3474     if (errorstate != HAL_SD_ERROR_NONE)
3475     {
3476       return errorstate;
3477     }
3478 
3479     /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */
3480     errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U);
3481     if (errorstate != HAL_SD_ERROR_NONE)
3482     {
3483       return errorstate;
3484     }
3485 
3486     return HAL_SD_ERROR_NONE;
3487   }
3488   else
3489   {
3490     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3491   }
3492 }
3493 
3494 /**
3495   * @brief  Finds the SD card SCR register value.
3496   * @param  hsd: Pointer to SD handle
3497   * @param  pSCR: pointer to the buffer that will contain the SCR value
3498   * @retval error state
3499   */
SD_FindSCR(SD_HandleTypeDef * hsd,uint32_t * pSCR)3500 static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR)
3501 {
3502   SDMMC_DataInitTypeDef config;
3503   uint32_t errorstate;
3504   uint32_t tickstart = HAL_GetTick();
3505   uint32_t index = 0U;
3506   uint32_t tempscr[2U] = {0UL, 0UL};
3507   uint32_t *scr = pSCR;
3508 
3509   /* Set Block Size To 8 Bytes */
3510   errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U);
3511   if (errorstate != HAL_SD_ERROR_NONE)
3512   {
3513     return errorstate;
3514   }
3515 
3516   /* Send CMD55 APP_CMD with argument as card's RCA */
3517   errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U));
3518   if (errorstate != HAL_SD_ERROR_NONE)
3519   {
3520     return errorstate;
3521   }
3522 
3523   config.DataTimeOut   = SDMMC_DATATIMEOUT;
3524   config.DataLength    = 8U;
3525   config.DataBlockSize = SDMMC_DATABLOCK_SIZE_8B;
3526   config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3527   config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3528   config.DPSM          = SDMMC_DPSM_ENABLE;
3529   (void)SDMMC_ConfigData(hsd->Instance, &config);
3530 
3531   /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */
3532   errorstate = SDMMC_CmdSendSCR(hsd->Instance);
3533   if (errorstate != HAL_SD_ERROR_NONE)
3534   {
3535     return errorstate;
3536   }
3537 
3538   while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3539                             SDMMC_FLAG_DATAEND))
3540   {
3541     if ((!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOE)) && (index == 0U))
3542     {
3543       tempscr[0] = SDMMC_ReadFIFO(hsd->Instance);
3544       tempscr[1] = SDMMC_ReadFIFO(hsd->Instance);
3545       index++;
3546     }
3547 
3548     if ((HAL_GetTick() - tickstart) >=  SDMMC_SWDATATIMEOUT)
3549     {
3550       return HAL_SD_ERROR_TIMEOUT;
3551     }
3552   }
3553 
3554   if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3555   {
3556     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3557 
3558     return HAL_SD_ERROR_DATA_TIMEOUT;
3559   }
3560   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3561   {
3562     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3563 
3564     return HAL_SD_ERROR_DATA_CRC_FAIL;
3565   }
3566   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3567   {
3568     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3569 
3570     return HAL_SD_ERROR_RX_OVERRUN;
3571   }
3572   else
3573   {
3574     /* No error flag set */
3575     /* Clear all the static flags */
3576     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3577 
3578     *scr = (((tempscr[1] & SDMMC_0TO7BITS) << 24U)  | ((tempscr[1] & SDMMC_8TO15BITS) << 8U) | \
3579             ((tempscr[1] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24U));
3580     scr++;
3581     *scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24U)  | ((tempscr[0] & SDMMC_8TO15BITS) << 8U) | \
3582             ((tempscr[0] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24U));
3583 
3584   }
3585 
3586   return HAL_SD_ERROR_NONE;
3587 }
3588 
3589 /**
3590   * @brief  Wrap up reading in non-blocking mode.
3591   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
3592   *              the configuration information.
3593   * @retval None
3594   */
SD_Read_IT(SD_HandleTypeDef * hsd)3595 static void SD_Read_IT(SD_HandleTypeDef *hsd)
3596 {
3597   uint32_t count;
3598   uint32_t data;
3599   uint8_t *tmp;
3600 
3601   tmp = hsd->pRxBuffPtr;
3602 
3603   if (hsd->RxXferSize >= SDMMC_FIFO_SIZE)
3604   {
3605     /* Read data from SDMMC Rx FIFO */
3606     for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++)
3607     {
3608       data = SDMMC_ReadFIFO(hsd->Instance);
3609       *tmp = (uint8_t)(data & 0xFFU);
3610       tmp++;
3611       *tmp = (uint8_t)((data >> 8U) & 0xFFU);
3612       tmp++;
3613       *tmp = (uint8_t)((data >> 16U) & 0xFFU);
3614       tmp++;
3615       *tmp = (uint8_t)((data >> 24U) & 0xFFU);
3616       tmp++;
3617     }
3618 
3619     hsd->pRxBuffPtr = tmp;
3620     hsd->RxXferSize -= SDMMC_FIFO_SIZE;
3621   }
3622 }
3623 
3624 /**
3625   * @brief  Wrap up writing in non-blocking mode.
3626   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
3627   *              the configuration information.
3628   * @retval None
3629   */
SD_Write_IT(SD_HandleTypeDef * hsd)3630 static void SD_Write_IT(SD_HandleTypeDef *hsd)
3631 {
3632   uint32_t count;
3633   uint32_t data;
3634   const uint8_t *tmp;
3635 
3636   tmp = hsd->pTxBuffPtr;
3637 
3638   if (hsd->TxXferSize >= SDMMC_FIFO_SIZE)
3639   {
3640     /* Write data to SDMMC Tx FIFO */
3641     for (count = 0U; count < (SDMMC_FIFO_SIZE / 4U); count++)
3642     {
3643       data = (uint32_t)(*tmp);
3644       tmp++;
3645       data |= ((uint32_t)(*tmp) << 8U);
3646       tmp++;
3647       data |= ((uint32_t)(*tmp) << 16U);
3648       tmp++;
3649       data |= ((uint32_t)(*tmp) << 24U);
3650       tmp++;
3651       (void)SDMMC_WriteFIFO(hsd->Instance, &data);
3652     }
3653 
3654     hsd->pTxBuffPtr = tmp;
3655     hsd->TxXferSize -= SDMMC_FIFO_SIZE;
3656   }
3657 }
3658 
3659 /**
3660   * @brief  Switches the SD card to High Speed mode.
3661   *         This API must be used after "Transfer State"
3662   * @note   This operation should be followed by the configuration
3663   *         of PLL to have SDMMCCK clock between 25 and 50 MHz
3664   * @param  hsd: SD handle
3665   * @param  SwitchSpeedMode: SD speed mode( SDMMC_SDR12_SWITCH_PATTERN, SDMMC_SDR25_SWITCH_PATTERN)
3666   * @retval SD Card error state
3667   */
SD_SwitchSpeed(SD_HandleTypeDef * hsd,uint32_t SwitchSpeedMode)3668 uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode)
3669 {
3670   uint32_t errorstate = HAL_SD_ERROR_NONE;
3671   SDMMC_DataInitTypeDef sdmmc_datainitstructure;
3672   uint32_t SD_hs[16]  = {0};
3673   uint32_t count;
3674   uint32_t loop = 0 ;
3675   uint32_t Timeout = HAL_GetTick();
3676 
3677   if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED)
3678   {
3679     /* Standard Speed Card <= 12.5Mhz  */
3680     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3681   }
3682 
3683   if (hsd->SdCard.CardSpeed >= CARD_HIGH_SPEED)
3684   {
3685     /* Initialize the Data control register */
3686     hsd->Instance->DCTRL = 0;
3687     errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3688 
3689     if (errorstate != HAL_SD_ERROR_NONE)
3690     {
3691       return errorstate;
3692     }
3693 
3694     /* Configure the SD DPSM (Data Path State Machine) */
3695     sdmmc_datainitstructure.DataTimeOut   = SDMMC_DATATIMEOUT;
3696     sdmmc_datainitstructure.DataLength    = 64U;
3697     sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ;
3698     sdmmc_datainitstructure.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3699     sdmmc_datainitstructure.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3700     sdmmc_datainitstructure.DPSM          = SDMMC_DPSM_ENABLE;
3701 
3702     (void)SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure);
3703 
3704     errorstate = SDMMC_CmdSwitch(hsd->Instance, SwitchSpeedMode);
3705     if (errorstate != HAL_SD_ERROR_NONE)
3706     {
3707       return errorstate;
3708     }
3709 
3710     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3711                               SDMMC_FLAG_DATAEND))
3712     {
3713       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3714       {
3715         for (count = 0U; count < 8U; count++)
3716         {
3717           SD_hs[(8U * loop) + count]  = SDMMC_ReadFIFO(hsd->Instance);
3718         }
3719         loop ++;
3720       }
3721       if ((HAL_GetTick() - Timeout) >=  SDMMC_SWDATATIMEOUT)
3722       {
3723         hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
3724         hsd->State = HAL_SD_STATE_READY;
3725         return HAL_SD_ERROR_TIMEOUT;
3726       }
3727     }
3728 
3729     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3730     {
3731       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3732 
3733       return errorstate;
3734     }
3735     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3736     {
3737       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3738 
3739       errorstate = SDMMC_ERROR_DATA_CRC_FAIL;
3740 
3741       return errorstate;
3742     }
3743     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3744     {
3745       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3746 
3747       errorstate = SDMMC_ERROR_RX_OVERRUN;
3748 
3749       return errorstate;
3750     }
3751     else
3752     {
3753       /* No error flag set */
3754     }
3755 
3756     /* Clear all the static flags */
3757     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3758 
3759     /* Test if the switch mode HS is ok */
3760     if ((((uint8_t *)SD_hs)[13] & 2U) != 2U)
3761     {
3762       errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE;
3763     }
3764 
3765   }
3766 
3767   return errorstate;
3768 }
3769 
3770 #if (USE_SD_TRANSCEIVER != 0U)
3771 /**
3772   * @brief  Switches the SD card to Ultra High Speed mode.
3773   *         This API must be used after "Transfer State"
3774   * @note   This operation should be followed by the configuration
3775   *         of PLL to have SDMMCCK clock between 50 and 120 MHz
3776   * @param  hsd: SD handle
3777   * @param  UltraHighSpeedMode: SD speed mode( SDMMC_SDR50_SWITCH_PATTERN, SDMMC_SDR104_SWITCH_PATTERN)
3778   * @retval SD Card error state
3779   */
SD_UltraHighSpeed(SD_HandleTypeDef * hsd,uint32_t UltraHighSpeedMode)3780 static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode)
3781 {
3782   uint32_t errorstate = HAL_SD_ERROR_NONE;
3783   SDMMC_DataInitTypeDef sdmmc_datainitstructure;
3784   uint32_t SD_hs[16]  = {0};
3785   uint32_t count;
3786   uint32_t loop = 0 ;
3787   uint32_t Timeout = HAL_GetTick();
3788 
3789   if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED)
3790   {
3791     /* Standard Speed Card <= 12.5Mhz  */
3792     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3793   }
3794 
3795   if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED)
3796   {
3797     /* Initialize the Data control register */
3798     hsd->Instance->DCTRL = 0;
3799     errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3800 
3801     if (errorstate != HAL_SD_ERROR_NONE)
3802     {
3803       return errorstate;
3804     }
3805 
3806     /* Configure the SD DPSM (Data Path State Machine) */
3807     sdmmc_datainitstructure.DataTimeOut   = SDMMC_DATATIMEOUT;
3808     sdmmc_datainitstructure.DataLength    = 64U;
3809     sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ;
3810     sdmmc_datainitstructure.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3811     sdmmc_datainitstructure.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3812     sdmmc_datainitstructure.DPSM          = SDMMC_DPSM_ENABLE;
3813 
3814     if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK)
3815     {
3816       return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR);
3817     }
3818 
3819     errorstate = SDMMC_CmdSwitch(hsd->Instance, UltraHighSpeedMode);
3820     if (errorstate != HAL_SD_ERROR_NONE)
3821     {
3822       return errorstate;
3823     }
3824 
3825     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3826                               SDMMC_FLAG_DATAEND))
3827     {
3828       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3829       {
3830         for (count = 0U; count < 8U; count++)
3831         {
3832           SD_hs[(8U * loop) + count]  = SDMMC_ReadFIFO(hsd->Instance);
3833         }
3834         loop ++;
3835       }
3836 
3837       if ((HAL_GetTick() - Timeout) >=  SDMMC_SWDATATIMEOUT)
3838       {
3839         hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
3840         hsd->State = HAL_SD_STATE_READY;
3841         return HAL_SD_ERROR_TIMEOUT;
3842       }
3843     }
3844 
3845     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3846     {
3847       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3848 
3849       return errorstate;
3850     }
3851     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3852     {
3853       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3854 
3855       errorstate = SDMMC_ERROR_DATA_CRC_FAIL;
3856 
3857       return errorstate;
3858     }
3859     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3860     {
3861       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3862 
3863       errorstate = SDMMC_ERROR_RX_OVERRUN;
3864 
3865       return errorstate;
3866     }
3867     else
3868     {
3869       /* No error flag set */
3870     }
3871 
3872     /* Clear all the static flags */
3873     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3874 
3875     /* Test if the switch mode HS is ok */
3876     if ((((uint8_t *)SD_hs)[13] & 2U) != 2U)
3877     {
3878       errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE;
3879     }
3880     else
3881     {
3882 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
3883       hsd->DriveTransceiver_1_8V_Callback(SET);
3884 #else
3885       HAL_SD_DriveTransceiver_1_8V_Callback(SET);
3886 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
3887 #if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2)
3888       /* Enable DelayBlock Peripheral */
3889       /* SDMMC_FB_CLK tuned feedback clock selected as receive clock, for SDR104 */
3890       MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_1);
3891       LL_DLYB_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance));
3892 #endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */
3893     }
3894   }
3895 
3896   return errorstate;
3897 }
3898 
3899 /**
3900   * @brief  Switches the SD card to Double Data Rate (DDR) mode.
3901   *         This API must be used after "Transfer State"
3902   * @note   This operation should be followed by the configuration
3903   *         of PLL to have SDMMCCK clock less than 50MHz
3904   * @param  hsd: SD handle
3905   * @retval SD Card error state
3906   */
SD_DDR_Mode(SD_HandleTypeDef * hsd)3907 static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd)
3908 {
3909   uint32_t errorstate = HAL_SD_ERROR_NONE;
3910   SDMMC_DataInitTypeDef sdmmc_datainitstructure;
3911   uint32_t SD_hs[16]  = {0};
3912   uint32_t count;
3913   uint32_t loop = 0 ;
3914   uint32_t Timeout = HAL_GetTick();
3915 
3916   if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED)
3917   {
3918     /* Standard Speed Card <= 12.5Mhz  */
3919     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3920   }
3921 
3922   if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED)
3923   {
3924     /* Initialize the Data control register */
3925     hsd->Instance->DCTRL = 0;
3926     errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3927 
3928     if (errorstate != HAL_SD_ERROR_NONE)
3929     {
3930       return errorstate;
3931     }
3932 
3933     /* Configure the SD DPSM (Data Path State Machine) */
3934     sdmmc_datainitstructure.DataTimeOut   = SDMMC_DATATIMEOUT;
3935     sdmmc_datainitstructure.DataLength    = 64U;
3936     sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ;
3937     sdmmc_datainitstructure.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3938     sdmmc_datainitstructure.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3939     sdmmc_datainitstructure.DPSM          = SDMMC_DPSM_ENABLE;
3940 
3941     if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK)
3942     {
3943       return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR);
3944     }
3945 
3946     errorstate = SDMMC_CmdSwitch(hsd->Instance, SDMMC_DDR50_SWITCH_PATTERN);
3947     if (errorstate != HAL_SD_ERROR_NONE)
3948     {
3949       return errorstate;
3950     }
3951 
3952     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3953                               SDMMC_FLAG_DATAEND))
3954     {
3955       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3956       {
3957         for (count = 0U; count < 8U; count++)
3958         {
3959           SD_hs[(8U * loop) + count]  = SDMMC_ReadFIFO(hsd->Instance);
3960         }
3961         loop ++;
3962       }
3963 
3964       if ((HAL_GetTick() - Timeout) >=  SDMMC_SWDATATIMEOUT)
3965       {
3966         hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
3967         hsd->State = HAL_SD_STATE_READY;
3968         return HAL_SD_ERROR_TIMEOUT;
3969       }
3970     }
3971 
3972     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3973     {
3974       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3975 
3976       return errorstate;
3977     }
3978     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3979     {
3980       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3981 
3982       errorstate = SDMMC_ERROR_DATA_CRC_FAIL;
3983 
3984       return errorstate;
3985     }
3986     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3987     {
3988       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3989 
3990       errorstate = SDMMC_ERROR_RX_OVERRUN;
3991 
3992       return errorstate;
3993     }
3994     else
3995     {
3996       /* No error flag set */
3997     }
3998 
3999     /* Clear all the static flags */
4000     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
4001 
4002     /* Test if the switch mode  is ok */
4003     if ((((uint8_t *)SD_hs)[13] & 2U) != 2U)
4004     {
4005       errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE;
4006     }
4007     else
4008     {
4009 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
4010       hsd->DriveTransceiver_1_8V_Callback(SET);
4011 #else
4012       HAL_SD_DriveTransceiver_1_8V_Callback(SET);
4013 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
4014 #if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2)
4015       /* Enable DelayBlock Peripheral */
4016       /* SDMMC_CKin feedback clock selected as receive clock, for DDR50 */
4017       MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_0);
4018       LL_DLYB_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance));
4019 #endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */
4020     }
4021   }
4022 
4023   return errorstate;
4024 }
4025 
4026 #endif /* USE_SD_TRANSCEIVER */
4027 
4028 /**
4029   * @brief Read DMA Linked list node Transfer completed callbacks
4030   * @param hsd: SD handle
4031   * @retval None
4032   */
HAL_SDEx_Read_DMALnkLstBufCpltCallback(SD_HandleTypeDef * hsd)4033 __weak void HAL_SDEx_Read_DMALnkLstBufCpltCallback(SD_HandleTypeDef *hsd)
4034 {
4035   /* Prevent unused argument(s) compilation warning */
4036   UNUSED(hsd);
4037 
4038   /* NOTE : This function should not be modified, when the callback is needed,
4039             the HAL_SDEx_Read_DMALnkLstBufCpltCallback can be implemented in the user file
4040    */
4041 }
4042 /**
4043   * @brief Read DMA Linked list node Transfer completed callbacks
4044   * @param hsd: SD handle
4045   * @retval None
4046   */
HAL_SDEx_Write_DMALnkLstBufCpltCallback(SD_HandleTypeDef * hsd)4047 __weak void HAL_SDEx_Write_DMALnkLstBufCpltCallback(SD_HandleTypeDef *hsd)
4048 {
4049   /* Prevent unused argument(s) compilation warning */
4050   UNUSED(hsd);
4051 
4052   /* NOTE : This function should not be modified, when the callback is needed,
4053             the HAL_SDEx_Write_DMALnkLstBufCpltCallback can be implemented in the user file
4054    */
4055 }
4056 
4057 /**
4058   * @}
4059   */
4060 
4061 #endif /* HAL_SD_MODULE_ENABLED */
4062 #endif /* SDMMC1 || SDMMC2 */
4063 
4064 /**
4065   * @}
4066   */
4067 
4068 /**
4069   * @}
4070   */
4071