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