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