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