Back to home page

LXR

 
 

    


File indexing completed on 2025-05-11 08:23:09

0001 /**
0002   ******************************************************************************
0003   * @file    stm32h7xx_hal_sd.c
0004   * @author  MCD Application Team
0005   * @brief   SD card HAL module driver.
0006   *          This file provides firmware functions to manage the following
0007   *          functionalities of the Secure Digital (SD) peripheral:
0008   *           + Initialization and de-initialization functions
0009   *           + IO operation functions
0010   *           + Peripheral Control functions
0011   *           + Peripheral State functions
0012   *
0013   ******************************************************************************
0014   * @attention
0015   *
0016   * Copyright (c) 2017 STMicroelectronics.
0017   * All rights reserved.
0018   *
0019   * This software is licensed under terms that can be found in the LICENSE file
0020   * in the root directory of this software component.
0021   * If no LICENSE file comes with this software, it is provided AS-IS.
0022   *
0023   ******************************************************************************
0024   @verbatim
0025   ==============================================================================
0026                         ##### How to use this driver #####
0027   ==============================================================================
0028   [..]
0029     This driver implements a high level communication layer for read and write from/to
0030     this memory. The needed STM32 hardware resources (SDMMC and GPIO) are performed by
0031     the user in HAL_SD_MspInit() function (MSP layer).
0032     Basically, the MSP layer configuration should be the same as we provide in the
0033     examples.
0034     You can easily tailor this configuration according to hardware resources.
0035 
0036   [..]
0037     This driver is a generic layered driver for SDMMC memories which uses the HAL
0038     SDMMC driver functions to interface with SD and uSD cards devices.
0039     It is used as follows:
0040 
0041     (#)Initialize the SDMMC low level resources by implementing the HAL_SD_MspInit() API:
0042         (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE();
0043         (##) SDMMC pins configuration for SD card
0044             (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE();
0045             (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init()
0046                   and according to your pin assignment;
0047         (##) NVIC configuration if you need to use interrupt process (HAL_SD_ReadBlocks_IT()
0048              and HAL_SD_WriteBlocks_IT() APIs).
0049             (+++) Configure the SDMMC interrupt priorities using function HAL_NVIC_SetPriority();
0050             (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ()
0051             (+++) SDMMC interrupts are managed using the macros __HAL_SD_ENABLE_IT()
0052                   and __HAL_SD_DISABLE_IT() inside the communication process.
0053             (+++) SDMMC interrupts pending bits are managed using the macros __HAL_SD_GET_IT()
0054                   and __HAL_SD_CLEAR_IT()
0055         (##) No general propose DMA Configuration is needed, an Internal DMA for SDMMC Peripheral are used.
0056 
0057     (#) At this stage, you can perform SD read/write/erase operations after SD card initialization
0058 
0059 
0060   *** SD Card Initialization and configuration ***
0061   ================================================
0062   [..]
0063     To initialize the SD Card, use the HAL_SD_Init() function. It Initializes
0064     SDMMC Peripheral(STM32 side) and the SD Card, and put it into StandBy State (Ready for data transfer).
0065     This function provide the following operations:
0066 
0067     (#) Apply the SD Card initialization process at 400KHz and check the SD Card
0068         type (Standard Capacity or High Capacity). You can change or adapt this
0069         frequency by adjusting the "ClockDiv" field.
0070         The SD Card frequency (SDMMC_CK) is computed as follows:
0071 
0072            SDMMC_CK = SDMMCCLK / (2 * ClockDiv)
0073 
0074         In initialization mode and according to the SD Card standard,
0075         make sure that the SDMMC_CK frequency doesn't exceed 400KHz.
0076 
0077         This phase of initialization is done through SDMMC_Init() and
0078         SDMMC_PowerState_ON() SDMMC low level APIs.
0079 
0080     (#) Initialize the SD card. The API used is HAL_SD_InitCard().
0081         This phase allows the card initialization and identification
0082         and check the SD Card type (Standard Capacity or High Capacity)
0083         The initialization flow is compatible with SD standard.
0084 
0085         This API (HAL_SD_InitCard()) could be used also to reinitialize the card in case
0086         of plug-off plug-in.
0087 
0088     (#) Configure the SD Card Data transfer frequency. You can change or adapt this
0089         frequency by adjusting the "ClockDiv" field.
0090         In transfer mode and according to the SD Card standard, make sure that the
0091         SDMMC_CK frequency doesn't exceed 25MHz and 100MHz in High-speed mode switch.
0092 
0093     (#) Select the corresponding SD Card according to the address read with the step 2.
0094 
0095     (#) Configure the SD Card in wide bus mode: 4-bits data.
0096 
0097   *** SD Card Read operation ***
0098   ==============================
0099   [..]
0100     (+) You can read from SD card in polling mode by using function HAL_SD_ReadBlocks().
0101         This function support only 512-bytes block length (the block size should be
0102         chosen as 512 bytes).
0103         You can choose either one block read operation or multiple block read operation
0104         by adjusting the "NumberOfBlocks" parameter.
0105         After this, you have to ensure that the transfer is done correctly. The check is done
0106         through HAL_SD_GetCardState() function for SD card state.
0107 
0108     (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA().
0109         This function support only 512-bytes block length (the block size should be
0110         chosen as 512 bytes).
0111         You can choose either one block read operation or multiple block read operation
0112         by adjusting the "NumberOfBlocks" parameter.
0113         After this, you have to ensure that the transfer is done correctly. The check is done
0114         through HAL_SD_GetCardState() function for SD card state.
0115         You could also check the DMA transfer process through the SD Rx interrupt event.
0116 
0117     (+) You can read from SD card in Interrupt mode by using function HAL_SD_ReadBlocks_IT().
0118         This function support only 512-bytes block length (the block size should be
0119         chosen as 512 bytes).
0120         You can choose either one block read operation or multiple block read operation
0121         by adjusting the "NumberOfBlocks" parameter.
0122         After this, you have to ensure that the transfer is done correctly. The check is done
0123         through HAL_SD_GetCardState() function for SD card state.
0124         You could also check the IT transfer process through the SD Rx interrupt event.
0125 
0126   *** SD Card Write operation ***
0127   ===============================
0128   [..]
0129     (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks().
0130         This function support only 512-bytes block length (the block size should be
0131         chosen as 512 bytes).
0132         You can choose either one block read operation or multiple block read operation
0133         by adjusting the "NumberOfBlocks" parameter.
0134         After this, you have to ensure that the transfer is done correctly. The check is done
0135         through HAL_SD_GetCardState() function for SD card state.
0136 
0137     (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA().
0138         This function support only 512-bytes block length (the block size should be
0139         chosen as 512 bytes).
0140         You can choose either one block read operation or multiple block read operation
0141         by adjusting the "NumberOfBlocks" parameter.
0142         After this, you have to ensure that the transfer is done correctly. The check is done
0143         through HAL_SD_GetCardState() function for SD card state.
0144         You could also check the DMA transfer process through the SD Tx interrupt event.
0145 
0146     (+) You can write to SD card in Interrupt mode by using function HAL_SD_WriteBlocks_IT().
0147         This function support only 512-bytes block length (the block size should be
0148         chosen as 512 bytes).
0149         You can choose either one block read operation or multiple block read operation
0150         by adjusting the "NumberOfBlocks" parameter.
0151         After this, you have to ensure that the transfer is done correctly. The check is done
0152         through HAL_SD_GetCardState() function for SD card state.
0153         You could also check the IT transfer process through the SD Tx interrupt event.
0154 
0155   *** SD card status ***
0156   ======================
0157   [..]
0158     (+) The SD Status contains status bits that are related to the SD Memory
0159         Card proprietary features. To get SD card status use the HAL_SD_GetCardStatus().
0160 
0161   *** SD card information ***
0162   ===========================
0163   [..]
0164     (+) To get SD card information, you can use the function HAL_SD_GetCardInfo().
0165         It returns useful information about the SD card such as block size, card type,
0166         block number ...
0167 
0168   *** SD card CSD register ***
0169   ============================
0170     (+) The HAL_SD_GetCardCSD() API allows to get the parameters of the CSD register.
0171         Some of the CSD parameters are useful for card initialization and identification.
0172 
0173   *** SD card CID register ***
0174   ============================
0175     (+) The HAL_SD_GetCardCID() API allows to get the parameters of the CID register.
0176         Some of the CSD parameters are useful for card initialization and identification.
0177 
0178   *** SD HAL driver macros list ***
0179   ==================================
0180   [..]
0181     Below the list of most used macros in SD HAL driver.
0182 
0183     (+) __HAL_SD_ENABLE_IT: Enable the SD device interrupt
0184     (+) __HAL_SD_DISABLE_IT: Disable the SD device interrupt
0185     (+) __HAL_SD_GET_FLAG:Check whether the specified SD flag is set or not
0186     (+) __HAL_SD_CLEAR_FLAG: Clear the SD's pending flags
0187 
0188     (@) You can refer to the SD HAL driver header file for more useful macros
0189 
0190   *** Callback registration ***
0191   =============================================
0192   [..]
0193     The compilation define USE_HAL_SD_REGISTER_CALLBACKS when set to 1
0194     allows the user to configure dynamically the driver callbacks.
0195 
0196     Use Functions HAL_SD_RegisterCallback() to register a user callback,
0197     it allows to register following callbacks:
0198       (+) TxCpltCallback : callback when a transmission transfer is completed.
0199       (+) RxCpltCallback : callback when a reception transfer is completed.
0200       (+) ErrorCallback : callback when error occurs.
0201       (+) AbortCpltCallback : callback when abort is completed.
0202       (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed.
0203       (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed.
0204       (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed.
0205       (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed.
0206       (+) MspInitCallback    : SD MspInit.
0207       (+) MspDeInitCallback  : SD MspDeInit.
0208     This function takes as parameters the HAL peripheral handle, the Callback ID
0209     and a pointer to the user callback function.
0210     For specific callbacks TransceiverCallback use dedicated register callbacks:
0211     respectively HAL_SD_RegisterTransceiverCallback().
0212 
0213     Use function HAL_SD_UnRegisterCallback() to reset a callback to the default
0214     weak (surcharged) function. It allows to reset following callbacks:
0215       (+) TxCpltCallback : callback when a transmission transfer is completed.
0216       (+) RxCpltCallback : callback when a reception transfer is completed.
0217       (+) ErrorCallback : callback when error occurs.
0218       (+) AbortCpltCallback : callback when abort is completed.
0219       (+) Read_DMADblBuf0CpltCallback : callback when the DMA reception of first buffer is completed.
0220       (+) Read_DMADblBuf1CpltCallback : callback when the DMA reception of second buffer is completed.
0221       (+) Write_DMADblBuf0CpltCallback : callback when the DMA transmission of first buffer is completed.
0222       (+) Write_DMADblBuf1CpltCallback : callback when the DMA transmission of second buffer is completed.
0223       (+) MspInitCallback    : SD MspInit.
0224       (+) MspDeInitCallback  : SD MspDeInit.
0225     This function) takes as parameters the HAL peripheral handle and the Callback ID.
0226     For specific callbacks TransceiverCallback use dedicated unregister callbacks:
0227     respectively HAL_SD_UnRegisterTransceiverCallback().
0228 
0229     By default, after the HAL_SD_Init and if the state is HAL_SD_STATE_RESET
0230     all callbacks are reset to the corresponding legacy weak (surcharged) functions.
0231     Exception done for MspInit and MspDeInit callbacks that are respectively
0232     reset to the legacy weak (surcharged) functions in the HAL_SD_Init
0233     and HAL_SD_DeInit only when these callbacks are null (not registered beforehand).
0234     If not, MspInit or MspDeInit are not null, the HAL_SD_Init and HAL_SD_DeInit
0235     keep and use the user MspInit/MspDeInit callbacks (registered beforehand)
0236 
0237     Callbacks can be registered/unregistered in READY state only.
0238     Exception done for MspInit/MspDeInit callbacks that can be registered/unregistered
0239     in READY or RESET state, thus registered (user) MspInit/DeInit callbacks can be used
0240     during the Init/DeInit.
0241     In that case first register the MspInit/MspDeInit user callbacks
0242     using HAL_SD_RegisterCallback before calling HAL_SD_DeInit
0243     or HAL_SD_Init function.
0244 
0245     When The compilation define USE_HAL_SD_REGISTER_CALLBACKS is set to 0 or
0246     not defined, the callback registering feature is not available
0247     and weak (surcharged) callbacks are used.
0248 
0249   @endverbatim
0250   ******************************************************************************
0251   */
0252 
0253 /* Includes ------------------------------------------------------------------*/
0254 #include "stm32h7xx_hal.h"
0255 
0256 /** @addtogroup STM32H7xx_HAL_Driver
0257   * @{
0258   */
0259 
0260 /** @addtogroup SD
0261   * @{
0262   */
0263 
0264 #ifdef HAL_SD_MODULE_ENABLED
0265 
0266 /* Private typedef -----------------------------------------------------------*/
0267 /* Private define ------------------------------------------------------------*/
0268 /** @addtogroup SD_Private_Defines
0269   * @{
0270   */
0271 /* Frequencies used in the driver for clock divider calculation */
0272 #define SD_INIT_FREQ                   400000U   /* Initialization phase : 400 kHz max */
0273 #define SD_NORMAL_SPEED_FREQ           25000000U /* Normal speed phase : 25 MHz max */
0274 #define SD_HIGH_SPEED_FREQ             50000000U /* High speed phase : 50 MHz max */
0275 /* Private macro -------------------------------------------------------------*/
0276 #if defined (DLYB_SDMMC1) && defined (DLYB_SDMMC2)
0277 #define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) (((SDMMC_INSTANCE) == SDMMC1)?  \
0278                                               DLYB_SDMMC1 : DLYB_SDMMC2 )
0279 #elif defined (DLYB_SDMMC1)
0280 #define SD_GET_DLYB_INSTANCE(SDMMC_INSTANCE) ( DLYB_SDMMC1 )
0281 #endif /* (DLYB_SDMMC1) && defined (DLYB_SDMMC2) */
0282 
0283 /**
0284   * @}
0285   */
0286 
0287 /* Private variables ---------------------------------------------------------*/
0288 /* Private function prototypes -----------------------------------------------*/
0289 /* Private functions ---------------------------------------------------------*/
0290 /** @defgroup SD_Private_Functions SD Private Functions
0291   * @ingroup RTEMSBSPsARMSTM32H7
0292   * @{
0293   */
0294 static uint32_t SD_InitCard(SD_HandleTypeDef *hsd);
0295 static uint32_t SD_PowerON(SD_HandleTypeDef *hsd);
0296 static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus);
0297 static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus);
0298 static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd);
0299 static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd);
0300 static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR);
0301 static void     SD_PowerOFF(SD_HandleTypeDef *hsd);
0302 static void     SD_Write_IT(SD_HandleTypeDef *hsd);
0303 static void     SD_Read_IT(SD_HandleTypeDef *hsd);
0304 static uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode);
0305 #if (USE_SD_TRANSCEIVER != 0U)
0306 static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode);
0307 static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd);
0308 #endif /* USE_SD_TRANSCEIVER */
0309 /**
0310   * @}
0311   */
0312 
0313 /* Exported functions --------------------------------------------------------*/
0314 /** @addtogroup SD_Exported_Functions
0315   * @{
0316   */
0317 
0318 /** @addtogroup SD_Exported_Functions_Group1
0319   *  @brief   Initialization and de-initialization functions
0320   *
0321 @verbatim
0322   ==============================================================================
0323           ##### Initialization and de-initialization functions #####
0324   ==============================================================================
0325   [..]
0326     This section provides functions allowing to initialize/de-initialize the SD
0327     card device to be ready for use.
0328 
0329 @endverbatim
0330   * @{
0331   */
0332 
0333 /**
0334   * @brief  Initializes the SD according to the specified parameters in the
0335             SD_HandleTypeDef and create the associated handle.
0336   * @param  hsd: Pointer to the SD handle
0337   * @retval HAL status
0338   */
0339 HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd)
0340 {
0341   HAL_SD_CardStatusTypeDef CardStatus;
0342   uint32_t speedgrade;
0343   uint32_t unitsize;
0344   uint32_t tickstart;
0345 
0346   /* Check the SD handle allocation */
0347   if (hsd == NULL)
0348   {
0349     return HAL_ERROR;
0350   }
0351 
0352   /* Check the parameters */
0353   assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance));
0354   assert_param(IS_SDMMC_CLOCK_EDGE(hsd->Init.ClockEdge));
0355   assert_param(IS_SDMMC_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave));
0356   assert_param(IS_SDMMC_BUS_WIDE(hsd->Init.BusWide));
0357   assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl));
0358   assert_param(IS_SDMMC_CLKDIV(hsd->Init.ClockDiv));
0359 
0360   if (hsd->State == HAL_SD_STATE_RESET)
0361   {
0362     /* Allocate lock resource and initialize it */
0363     hsd->Lock = HAL_UNLOCKED;
0364 
0365 #if (USE_SD_TRANSCEIVER != 0U)
0366     /* Force  SDMMC_TRANSCEIVER_PRESENT for Legacy usage */
0367     if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_UNKNOWN)
0368     {
0369       hsd->Init.TranceiverPresent = SDMMC_TRANSCEIVER_PRESENT;
0370     }
0371 #endif /*USE_SD_TRANSCEIVER */
0372 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
0373     /* Reset Callback pointers in HAL_SD_STATE_RESET only */
0374     hsd->TxCpltCallback    = HAL_SD_TxCpltCallback;
0375     hsd->RxCpltCallback    = HAL_SD_RxCpltCallback;
0376     hsd->ErrorCallback     = HAL_SD_ErrorCallback;
0377     hsd->AbortCpltCallback = HAL_SD_AbortCallback;
0378     hsd->Read_DMADblBuf0CpltCallback = HAL_SDEx_Read_DMADoubleBuf0CpltCallback;
0379     hsd->Read_DMADblBuf1CpltCallback = HAL_SDEx_Read_DMADoubleBuf1CpltCallback;
0380     hsd->Write_DMADblBuf0CpltCallback = HAL_SDEx_Write_DMADoubleBuf0CpltCallback;
0381     hsd->Write_DMADblBuf1CpltCallback = HAL_SDEx_Write_DMADoubleBuf1CpltCallback;
0382 #if (USE_SD_TRANSCEIVER != 0U)
0383     if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
0384     {
0385       hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback;
0386     }
0387 #endif /* USE_SD_TRANSCEIVER */
0388 
0389     if (hsd->MspInitCallback == NULL)
0390     {
0391       hsd->MspInitCallback = HAL_SD_MspInit;
0392     }
0393 
0394     /* Init the low level hardware */
0395     hsd->MspInitCallback(hsd);
0396 #else
0397     /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
0398     HAL_SD_MspInit(hsd);
0399 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
0400   }
0401 
0402   hsd->State = HAL_SD_STATE_PROGRAMMING;
0403 
0404   /* Initialize the Card parameters */
0405   if (HAL_SD_InitCard(hsd) != HAL_OK)
0406   {
0407     return HAL_ERROR;
0408   }
0409 
0410   if (HAL_SD_GetCardStatus(hsd, &CardStatus) != HAL_OK)
0411   {
0412     return HAL_ERROR;
0413   }
0414   /* Get Initial Card Speed from Card Status*/
0415   speedgrade = CardStatus.UhsSpeedGrade;
0416   unitsize = CardStatus.UhsAllocationUnitSize;
0417   if ((hsd->SdCard.CardType == CARD_SDHC_SDXC) && ((speedgrade != 0U) || (unitsize != 0U)))
0418   {
0419     hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED;
0420   }
0421   else
0422   {
0423     if (hsd->SdCard.CardType == CARD_SDHC_SDXC)
0424     {
0425       hsd->SdCard.CardSpeed  = CARD_HIGH_SPEED;
0426     }
0427     else
0428     {
0429       hsd->SdCard.CardSpeed  = CARD_NORMAL_SPEED;
0430     }
0431 
0432   }
0433   /* Configure the bus wide */
0434   if (HAL_SD_ConfigWideBusOperation(hsd, hsd->Init.BusWide) != HAL_OK)
0435   {
0436     return HAL_ERROR;
0437   }
0438 
0439   /* Verify that SD card is ready to use after Initialization */
0440   tickstart = HAL_GetTick();
0441   while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER))
0442   {
0443     if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
0444     {
0445       hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
0446       hsd->State = HAL_SD_STATE_READY;
0447       return HAL_TIMEOUT;
0448     }
0449   }
0450 
0451   /* Initialize the error code */
0452   hsd->ErrorCode = HAL_SD_ERROR_NONE;
0453 
0454   /* Initialize the SD operation */
0455   hsd->Context = SD_CONTEXT_NONE;
0456 
0457   /* Initialize the SD state */
0458   hsd->State = HAL_SD_STATE_READY;
0459 
0460   return HAL_OK;
0461 }
0462 
0463 /**
0464   * @brief  Initializes the SD Card.
0465   * @param  hsd: Pointer to SD handle
0466   * @note   This function initializes the SD card. It could be used when a card
0467             re-initialization is needed.
0468   * @retval HAL status
0469   */
0470 HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd)
0471 {
0472   uint32_t errorstate;
0473   SD_InitTypeDef Init;
0474   uint32_t sdmmc_clk;
0475 
0476   /* Default SDMMC peripheral configuration for SD card initialization */
0477   Init.ClockEdge           = SDMMC_CLOCK_EDGE_RISING;
0478   Init.ClockPowerSave      = SDMMC_CLOCK_POWER_SAVE_DISABLE;
0479   Init.BusWide             = SDMMC_BUS_WIDE_1B;
0480   Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE;
0481 
0482   /* Init Clock should be less or equal to 400Khz*/
0483   sdmmc_clk     = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC);
0484   if (sdmmc_clk == 0U)
0485   {
0486     hsd->State = HAL_SD_STATE_READY;
0487     hsd->ErrorCode = SDMMC_ERROR_INVALID_PARAMETER;
0488     return HAL_ERROR;
0489   }
0490   Init.ClockDiv = sdmmc_clk / (2U * SD_INIT_FREQ);
0491 
0492 #if (USE_SD_TRANSCEIVER != 0U)
0493   Init.TranceiverPresent = hsd->Init.TranceiverPresent;
0494 
0495   if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
0496   {
0497     /* Set Transceiver polarity */
0498     hsd->Instance->POWER |= SDMMC_POWER_DIRPOL;
0499   }
0500 #elif defined (USE_SD_DIRPOL)
0501   /* Set Transceiver polarity */
0502   hsd->Instance->POWER |= SDMMC_POWER_DIRPOL;
0503 #endif /* USE_SD_TRANSCEIVER  */
0504 
0505   /* Initialize SDMMC peripheral interface with default configuration */
0506   (void)SDMMC_Init(hsd->Instance, Init);
0507 
0508   /* Set Power State to ON */
0509   (void)SDMMC_PowerState_ON(hsd->Instance);
0510 
0511   /* wait 74 Cycles: required power up waiting time before starting
0512      the SD initialization sequence */
0513   if (Init.ClockDiv != 0U)
0514   {
0515     sdmmc_clk = sdmmc_clk / (2U * Init.ClockDiv);
0516   }
0517 
0518   if (sdmmc_clk != 0U)
0519   {
0520     HAL_Delay(1U + (74U * 1000U / (sdmmc_clk)));
0521   }
0522 
0523   /* Identify card operating voltage */
0524   errorstate = SD_PowerON(hsd);
0525   if (errorstate != HAL_SD_ERROR_NONE)
0526   {
0527     hsd->State = HAL_SD_STATE_READY;
0528     hsd->ErrorCode |= errorstate;
0529     return HAL_ERROR;
0530   }
0531 
0532   /* Card initialization */
0533   errorstate = SD_InitCard(hsd);
0534   if (errorstate != HAL_SD_ERROR_NONE)
0535   {
0536     hsd->State = HAL_SD_STATE_READY;
0537     hsd->ErrorCode |= errorstate;
0538     return HAL_ERROR;
0539   }
0540 
0541   /* Set Block Size for Card */
0542   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
0543   if (errorstate != HAL_SD_ERROR_NONE)
0544   {
0545     /* Clear all the static flags */
0546     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0547     hsd->ErrorCode |= errorstate;
0548     hsd->State = HAL_SD_STATE_READY;
0549     return HAL_ERROR;
0550   }
0551 
0552   return HAL_OK;
0553 }
0554 
0555 /**
0556   * @brief  De-Initializes the SD card.
0557   * @param  hsd: Pointer to SD handle
0558   * @retval HAL status
0559   */
0560 HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd)
0561 {
0562   /* Check the SD handle allocation */
0563   if (hsd == NULL)
0564   {
0565     return HAL_ERROR;
0566   }
0567 
0568   /* Check the parameters */
0569   assert_param(IS_SDMMC_ALL_INSTANCE(hsd->Instance));
0570 
0571   hsd->State = HAL_SD_STATE_BUSY;
0572 
0573 #if (USE_SD_TRANSCEIVER != 0U)
0574   /* Deactivate the 1.8V Mode */
0575   if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
0576   {
0577 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
0578     if (hsd->DriveTransceiver_1_8V_Callback == NULL)
0579     {
0580       hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback;
0581     }
0582     hsd->DriveTransceiver_1_8V_Callback(RESET);
0583 #else
0584     HAL_SD_DriveTransceiver_1_8V_Callback(RESET);
0585 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
0586   }
0587 #endif /* USE_SD_TRANSCEIVER   */
0588 
0589   /* Set SD power state to off */
0590   SD_PowerOFF(hsd);
0591 
0592 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
0593   if (hsd->MspDeInitCallback == NULL)
0594   {
0595     hsd->MspDeInitCallback = HAL_SD_MspDeInit;
0596   }
0597 
0598   /* DeInit the low level hardware */
0599   hsd->MspDeInitCallback(hsd);
0600 #else
0601   /* De-Initialize the MSP layer */
0602   HAL_SD_MspDeInit(hsd);
0603 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
0604 
0605   hsd->ErrorCode = HAL_SD_ERROR_NONE;
0606   hsd->State = HAL_SD_STATE_RESET;
0607 
0608   return HAL_OK;
0609 }
0610 
0611 
0612 #ifndef __rtems__
0613 /**
0614   * @brief  Initializes the SD MSP.
0615   * @param  hsd: Pointer to SD handle
0616   * @retval None
0617   */
0618 __weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
0619 {
0620   /* Prevent unused argument(s) compilation warning */
0621   UNUSED(hsd);
0622 
0623   /* NOTE : This function should not be modified, when the callback is needed,
0624             the HAL_SD_MspInit could be implemented in the user file
0625    */
0626 }
0627 #endif /* __rtems__ */
0628 
0629 /**
0630   * @brief  De-Initialize SD MSP.
0631   * @param  hsd: Pointer to SD handle
0632   * @retval None
0633   */
0634 __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd)
0635 {
0636   /* Prevent unused argument(s) compilation warning */
0637   UNUSED(hsd);
0638 
0639   /* NOTE : This function should not be modified, when the callback is needed,
0640             the HAL_SD_MspDeInit could be implemented in the user file
0641    */
0642 }
0643 
0644 /**
0645   * @}
0646   */
0647 
0648 /** @addtogroup SD_Exported_Functions_Group2
0649   *  @brief   Data transfer functions
0650   *
0651 @verbatim
0652   ==============================================================================
0653                         ##### IO operation functions #####
0654   ==============================================================================
0655   [..]
0656     This subsection provides a set of functions allowing to manage the data
0657     transfer from/to SD card.
0658 
0659 @endverbatim
0660   * @{
0661   */
0662 
0663 /**
0664   * @brief  Reads block(s) from a specified address in a card. The Data transfer
0665   *         is managed by polling mode.
0666   * @note   This API should be followed by a check on the card state through
0667   *         HAL_SD_GetCardState().
0668   * @param  hsd: Pointer to SD handle
0669   * @param  pData: pointer to the buffer that will contain the received data
0670   * @param  BlockAdd: Block Address from where data is to be read
0671   * @param  NumberOfBlocks: Number of SD blocks to read
0672   * @param  Timeout: Specify timeout value
0673   * @retval HAL status
0674   */
0675 HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks,
0676                                     uint32_t Timeout)
0677 {
0678   SDMMC_DataInitTypeDef config;
0679   uint32_t errorstate;
0680   uint32_t tickstart = HAL_GetTick();
0681   uint32_t count;
0682   uint32_t data;
0683   uint32_t dataremaining;
0684   uint32_t add = BlockAdd;
0685   uint8_t *tempbuff = pData;
0686 
0687   if (NULL == pData)
0688   {
0689     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
0690     return HAL_ERROR;
0691   }
0692 
0693   if (hsd->State == HAL_SD_STATE_READY)
0694   {
0695     hsd->ErrorCode = HAL_SD_ERROR_NONE;
0696 
0697     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
0698     {
0699       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
0700       return HAL_ERROR;
0701     }
0702 
0703     hsd->State = HAL_SD_STATE_BUSY;
0704 
0705     /* Initialize data control register */
0706     hsd->Instance->DCTRL = 0U;
0707 
0708     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
0709     {
0710       add *= 512U;
0711     }
0712 
0713     /* Configure the SD DPSM (Data Path State Machine) */
0714     config.DataTimeOut   = SDMMC_DATATIMEOUT;
0715     config.DataLength    = NumberOfBlocks * BLOCKSIZE;
0716     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
0717     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
0718     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
0719     config.DPSM          = SDMMC_DPSM_DISABLE;
0720     (void)SDMMC_ConfigData(hsd->Instance, &config);
0721     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
0722 
0723     /* Read block(s) in polling mode */
0724     if (NumberOfBlocks > 1U)
0725     {
0726       hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK;
0727 
0728       /* Read Multi Block command */
0729       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
0730     }
0731     else
0732     {
0733       hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK;
0734 
0735       /* Read Single Block command */
0736       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
0737     }
0738     if (errorstate != HAL_SD_ERROR_NONE)
0739     {
0740       /* Clear all the static flags */
0741       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0742       hsd->ErrorCode |= errorstate;
0743       hsd->State = HAL_SD_STATE_READY;
0744       hsd->Context = SD_CONTEXT_NONE;
0745       return HAL_ERROR;
0746     }
0747 
0748     /* Poll on SDMMC flags */
0749     dataremaining = config.DataLength;
0750     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
0751     {
0752       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) && (dataremaining >= 32U))
0753       {
0754         /* Read data from SDMMC Rx FIFO */
0755         for (count = 0U; count < 8U; count++)
0756         {
0757           data = SDMMC_ReadFIFO(hsd->Instance);
0758           *tempbuff = (uint8_t)(data & 0xFFU);
0759           tempbuff++;
0760           *tempbuff = (uint8_t)((data >> 8U) & 0xFFU);
0761           tempbuff++;
0762           *tempbuff = (uint8_t)((data >> 16U) & 0xFFU);
0763           tempbuff++;
0764           *tempbuff = (uint8_t)((data >> 24U) & 0xFFU);
0765           tempbuff++;
0766         }
0767         dataremaining -= 32U;
0768       }
0769 
0770       if (((HAL_GetTick() - tickstart) >=  Timeout) || (Timeout == 0U))
0771       {
0772         /* Clear all the static flags */
0773         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0774         hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT;
0775         hsd->State = HAL_SD_STATE_READY;
0776         hsd->Context = SD_CONTEXT_NONE;
0777         return HAL_TIMEOUT;
0778       }
0779     }
0780     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
0781 
0782     /* Send stop transmission command in case of multiblock read */
0783     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U))
0784     {
0785       if (hsd->SdCard.CardType != CARD_SECURED)
0786       {
0787         /* Send stop transmission command */
0788         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
0789         if (errorstate != HAL_SD_ERROR_NONE)
0790         {
0791           /* Clear all the static flags */
0792           __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0793           hsd->ErrorCode |= errorstate;
0794           hsd->State = HAL_SD_STATE_READY;
0795           hsd->Context = SD_CONTEXT_NONE;
0796           return HAL_ERROR;
0797         }
0798       }
0799     }
0800 
0801     /* Get error state */
0802     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
0803     {
0804       /* Clear all the static flags */
0805       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0806       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
0807       hsd->State = HAL_SD_STATE_READY;
0808       hsd->Context = SD_CONTEXT_NONE;
0809       return HAL_ERROR;
0810     }
0811     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
0812     {
0813       /* Clear all the static flags */
0814       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0815       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
0816       hsd->State = HAL_SD_STATE_READY;
0817       hsd->Context = SD_CONTEXT_NONE;
0818       return HAL_ERROR;
0819     }
0820     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
0821     {
0822       /* Clear all the static flags */
0823       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0824       hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN;
0825       hsd->State = HAL_SD_STATE_READY;
0826       hsd->Context = SD_CONTEXT_NONE;
0827       return HAL_ERROR;
0828     }
0829     else
0830     {
0831       /* Nothing to do */
0832     }
0833 
0834     /* Clear all the static flags */
0835     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
0836 
0837     hsd->State = HAL_SD_STATE_READY;
0838 
0839     return HAL_OK;
0840   }
0841   else
0842   {
0843     hsd->ErrorCode |= HAL_SD_ERROR_BUSY;
0844     return HAL_ERROR;
0845   }
0846 }
0847 
0848 /**
0849   * @brief  Allows to write block(s) to a specified address in a card. The Data
0850   *         transfer is managed by polling mode.
0851   * @note   This API should be followed by a check on the card state through
0852   *         HAL_SD_GetCardState().
0853   * @param  hsd: Pointer to SD handle
0854   * @param  pData: pointer to the buffer that will contain the data to transmit
0855   * @param  BlockAdd: Block Address where data will be written
0856   * @param  NumberOfBlocks: Number of SD blocks to write
0857   * @param  Timeout: Specify timeout value
0858   * @retval HAL status
0859   */
0860 HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd,
0861                                      uint32_t NumberOfBlocks, uint32_t Timeout)
0862 {
0863   SDMMC_DataInitTypeDef config;
0864   uint32_t errorstate;
0865   uint32_t tickstart = HAL_GetTick();
0866   uint32_t count;
0867   uint32_t data;
0868   uint32_t dataremaining;
0869   uint32_t add = BlockAdd;
0870   const uint8_t *tempbuff = pData;
0871 
0872   if (NULL == pData)
0873   {
0874     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
0875     return HAL_ERROR;
0876   }
0877 
0878   if (hsd->State == HAL_SD_STATE_READY)
0879   {
0880     hsd->ErrorCode = HAL_SD_ERROR_NONE;
0881 
0882     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
0883     {
0884       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
0885       return HAL_ERROR;
0886     }
0887 
0888     hsd->State = HAL_SD_STATE_BUSY;
0889 
0890     /* Initialize data control register */
0891     hsd->Instance->DCTRL = 0U;
0892 
0893     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
0894     {
0895       add *= 512U;
0896     }
0897 
0898     /* Configure the SD DPSM (Data Path State Machine) */
0899     config.DataTimeOut   = SDMMC_DATATIMEOUT;
0900     config.DataLength    = NumberOfBlocks * BLOCKSIZE;
0901     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
0902     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_CARD;
0903     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
0904     config.DPSM          = SDMMC_DPSM_DISABLE;
0905     (void)SDMMC_ConfigData(hsd->Instance, &config);
0906     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
0907 
0908     /* Write Blocks in Polling mode */
0909     if (NumberOfBlocks > 1U)
0910     {
0911       hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK;
0912 
0913       /* Write Multi Block command */
0914       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
0915     }
0916     else
0917     {
0918       hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK;
0919 
0920       /* Write Single Block command */
0921       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
0922     }
0923     if (errorstate != HAL_SD_ERROR_NONE)
0924     {
0925       /* Clear all the static flags */
0926       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0927       hsd->ErrorCode |= errorstate;
0928       hsd->State = HAL_SD_STATE_READY;
0929       hsd->Context = SD_CONTEXT_NONE;
0930       return HAL_ERROR;
0931     }
0932 
0933     /* Write block(s) in polling mode */
0934     dataremaining = config.DataLength;
0935     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT |
0936                               SDMMC_FLAG_DATAEND))
0937     {
0938       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) && (dataremaining >= 32U))
0939       {
0940         /* Write data to SDMMC Tx FIFO */
0941         for (count = 0U; count < 8U; count++)
0942         {
0943           data = (uint32_t)(*tempbuff);
0944           tempbuff++;
0945           data |= ((uint32_t)(*tempbuff) << 8U);
0946           tempbuff++;
0947           data |= ((uint32_t)(*tempbuff) << 16U);
0948           tempbuff++;
0949           data |= ((uint32_t)(*tempbuff) << 24U);
0950           tempbuff++;
0951           (void)SDMMC_WriteFIFO(hsd->Instance, &data);
0952         }
0953         dataremaining -= 32U;
0954       }
0955 
0956       if (((HAL_GetTick() - tickstart) >=  Timeout) || (Timeout == 0U))
0957       {
0958         /* Clear all the static flags */
0959         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0960         hsd->ErrorCode |= errorstate;
0961         hsd->State = HAL_SD_STATE_READY;
0962         hsd->Context = SD_CONTEXT_NONE;
0963         return HAL_TIMEOUT;
0964       }
0965     }
0966     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
0967 
0968     /* Send stop transmission command in case of multiblock write */
0969     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) && (NumberOfBlocks > 1U))
0970     {
0971       if (hsd->SdCard.CardType != CARD_SECURED)
0972       {
0973         /* Send stop transmission command */
0974         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
0975         if (errorstate != HAL_SD_ERROR_NONE)
0976         {
0977           /* Clear all the static flags */
0978           __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0979           hsd->ErrorCode |= errorstate;
0980           hsd->State = HAL_SD_STATE_READY;
0981           hsd->Context = SD_CONTEXT_NONE;
0982           return HAL_ERROR;
0983         }
0984       }
0985     }
0986 
0987     /* Get error state */
0988     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
0989     {
0990       /* Clear all the static flags */
0991       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
0992       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
0993       hsd->State = HAL_SD_STATE_READY;
0994       hsd->Context = SD_CONTEXT_NONE;
0995       return HAL_ERROR;
0996     }
0997     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
0998     {
0999       /* Clear all the static flags */
1000       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1001       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
1002       hsd->State = HAL_SD_STATE_READY;
1003       hsd->Context = SD_CONTEXT_NONE;
1004       return HAL_ERROR;
1005     }
1006     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR))
1007     {
1008       /* Clear all the static flags */
1009       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1010       hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;
1011       hsd->State = HAL_SD_STATE_READY;
1012       hsd->Context = SD_CONTEXT_NONE;
1013       return HAL_ERROR;
1014     }
1015     else
1016     {
1017       /* Nothing to do */
1018     }
1019 
1020     /* Clear all the static flags */
1021     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
1022 
1023     hsd->State = HAL_SD_STATE_READY;
1024 
1025     return HAL_OK;
1026   }
1027   else
1028   {
1029     hsd->ErrorCode |= HAL_SD_ERROR_BUSY;
1030     return HAL_ERROR;
1031   }
1032 }
1033 
1034 /**
1035   * @brief  Reads block(s) from a specified address in a card. The Data transfer
1036   *         is managed in interrupt mode.
1037   * @note   This API should be followed by a check on the card state through
1038   *         HAL_SD_GetCardState().
1039   * @note   You could also check the IT transfer process through the SD Rx
1040   *         interrupt event.
1041   * @param  hsd: Pointer to SD handle
1042   * @param  pData: Pointer to the buffer that will contain the received data
1043   * @param  BlockAdd: Block Address from where data is to be read
1044   * @param  NumberOfBlocks: Number of blocks to read.
1045   * @retval HAL status
1046   */
1047 HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd,
1048                                        uint32_t NumberOfBlocks)
1049 {
1050   SDMMC_DataInitTypeDef config;
1051   uint32_t errorstate;
1052   uint32_t add = BlockAdd;
1053 
1054   if (NULL == pData)
1055   {
1056     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1057     return HAL_ERROR;
1058   }
1059 
1060   if (hsd->State == HAL_SD_STATE_READY)
1061   {
1062     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1063 
1064     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1065     {
1066       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1067       return HAL_ERROR;
1068     }
1069 
1070     hsd->State = HAL_SD_STATE_BUSY;
1071 
1072     /* Initialize data control register */
1073     hsd->Instance->DCTRL = 0U;
1074 
1075     hsd->pRxBuffPtr = pData;
1076     hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks;
1077 
1078     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1079     {
1080       add *= 512U;
1081     }
1082 
1083     /* Configure the SD DPSM (Data Path State Machine) */
1084     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1085     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1086     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1087     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
1088     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1089     config.DPSM          = SDMMC_DPSM_DISABLE;
1090     (void)SDMMC_ConfigData(hsd->Instance, &config);
1091     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1092 
1093     /* Read Blocks in IT mode */
1094     if (NumberOfBlocks > 1U)
1095     {
1096       hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT);
1097 
1098       /* Read Multi Block command */
1099       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
1100     }
1101     else
1102     {
1103       hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT);
1104 
1105       /* Read Single Block command */
1106       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
1107     }
1108     if (errorstate != HAL_SD_ERROR_NONE)
1109     {
1110       /* Clear all the static flags */
1111       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1112       hsd->ErrorCode |= errorstate;
1113       hsd->State = HAL_SD_STATE_READY;
1114       hsd->Context = SD_CONTEXT_NONE;
1115       return HAL_ERROR;
1116     }
1117 
1118     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND |
1119                              SDMMC_FLAG_RXFIFOHF));
1120 
1121     return HAL_OK;
1122   }
1123   else
1124   {
1125     return HAL_BUSY;
1126   }
1127 }
1128 
1129 /**
1130   * @brief  Writes block(s) to a specified address in a card. The Data transfer
1131   *         is managed in interrupt mode.
1132   * @note   This API should be followed by a check on the card state through
1133   *         HAL_SD_GetCardState().
1134   * @note   You could also check the IT transfer process through the SD Tx
1135   *         interrupt event.
1136   * @param  hsd: Pointer to SD handle
1137   * @param  pData: Pointer to the buffer that will contain the data to transmit
1138   * @param  BlockAdd: Block Address where data will be written
1139   * @param  NumberOfBlocks: Number of blocks to write
1140   * @retval HAL status
1141   */
1142 HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd,
1143                                         uint32_t NumberOfBlocks)
1144 {
1145   SDMMC_DataInitTypeDef config;
1146   uint32_t errorstate;
1147   uint32_t add = BlockAdd;
1148 
1149   if (NULL == pData)
1150   {
1151     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1152     return HAL_ERROR;
1153   }
1154 
1155   if (hsd->State == HAL_SD_STATE_READY)
1156   {
1157     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1158 
1159     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1160     {
1161       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1162       return HAL_ERROR;
1163     }
1164 
1165     hsd->State = HAL_SD_STATE_BUSY;
1166 
1167     /* Initialize data control register */
1168     hsd->Instance->DCTRL = 0U;
1169 
1170     hsd->pTxBuffPtr = pData;
1171     hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks;
1172 
1173     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1174     {
1175       add *= 512U;
1176     }
1177 
1178     /* Configure the SD DPSM (Data Path State Machine) */
1179     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1180     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1181     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1182     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_CARD;
1183     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1184     config.DPSM          = SDMMC_DPSM_DISABLE;
1185     (void)SDMMC_ConfigData(hsd->Instance, &config);
1186 
1187     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1188 
1189     /* Write Blocks in Polling mode */
1190     if (NumberOfBlocks > 1U)
1191     {
1192       hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_IT);
1193 
1194       /* Write Multi Block command */
1195       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
1196     }
1197     else
1198     {
1199       hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT);
1200 
1201       /* Write Single Block command */
1202       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
1203     }
1204     if (errorstate != HAL_SD_ERROR_NONE)
1205     {
1206       /* Clear all the static flags */
1207       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1208       hsd->ErrorCode |= errorstate;
1209       hsd->State = HAL_SD_STATE_READY;
1210       hsd->Context = SD_CONTEXT_NONE;
1211       return HAL_ERROR;
1212     }
1213 
1214     /* Enable transfer interrupts */
1215     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND |
1216                              SDMMC_FLAG_TXFIFOHE));
1217 
1218     return HAL_OK;
1219   }
1220   else
1221   {
1222     return HAL_BUSY;
1223   }
1224 }
1225 
1226 /**
1227   * @brief  Reads block(s) from a specified address in a card. The Data transfer
1228   *         is managed by DMA mode.
1229   * @note   This API should be followed by a check on the card state through
1230   *         HAL_SD_GetCardState().
1231   * @note   You could also check the DMA transfer process through the SD Rx
1232   *         interrupt event.
1233   * @param  hsd: Pointer SD handle
1234   * @param  pData: Pointer to the buffer that will contain the received data
1235   * @param  BlockAdd: Block Address from where data is to be read
1236   * @param  NumberOfBlocks: Number of blocks to read.
1237   * @retval HAL status
1238   */
1239 HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd,
1240                                         uint32_t NumberOfBlocks)
1241 {
1242   SDMMC_DataInitTypeDef config;
1243   uint32_t errorstate;
1244   uint32_t add = BlockAdd;
1245 
1246   if (NULL == pData)
1247   {
1248     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1249     return HAL_ERROR;
1250   }
1251 
1252   if (hsd->State == HAL_SD_STATE_READY)
1253   {
1254     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1255 
1256     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1257     {
1258       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1259       return HAL_ERROR;
1260     }
1261 
1262     hsd->State = HAL_SD_STATE_BUSY;
1263 
1264     /* Initialize data control register */
1265     hsd->Instance->DCTRL = 0U;
1266 
1267     hsd->pRxBuffPtr = pData;
1268     hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks;
1269 
1270     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1271     {
1272       add *= 512U;
1273     }
1274 
1275     /* Configure the SD DPSM (Data Path State Machine) */
1276     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1277     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1278     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1279     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
1280     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1281     config.DPSM          = SDMMC_DPSM_DISABLE;
1282     (void)SDMMC_ConfigData(hsd->Instance, &config);
1283 
1284     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1285     hsd->Instance->IDMABASE0 = (uint32_t) pData ;
1286     hsd->Instance->IDMACTRL  = SDMMC_ENABLE_IDMA_SINGLE_BUFF;
1287 
1288     /* Read Blocks in DMA mode */
1289     if (NumberOfBlocks > 1U)
1290     {
1291       hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA);
1292 
1293       /* Read Multi Block command */
1294       errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, add);
1295     }
1296     else
1297     {
1298       hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA);
1299 
1300       /* Read Single Block command */
1301       errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, add);
1302     }
1303     if (errorstate != HAL_SD_ERROR_NONE)
1304     {
1305       /* Clear all the static flags */
1306       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1307       hsd->ErrorCode |= errorstate;
1308       hsd->State = HAL_SD_STATE_READY;
1309       hsd->Context = SD_CONTEXT_NONE;
1310       return HAL_ERROR;
1311     }
1312 
1313     /* Enable transfer interrupts */
1314     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_RXOVERR | SDMMC_IT_DATAEND));
1315 
1316 
1317     return HAL_OK;
1318   }
1319   else
1320   {
1321     return HAL_BUSY;
1322   }
1323 }
1324 
1325 /**
1326   * @brief  Writes block(s) to a specified address in a card. The Data transfer
1327   *         is managed by DMA mode.
1328   * @note   This API should be followed by a check on the card state through
1329   *         HAL_SD_GetCardState().
1330   * @note   You could also check the DMA transfer process through the SD Tx
1331   *         interrupt event.
1332   * @param  hsd: Pointer to SD handle
1333   * @param  pData: Pointer to the buffer that will contain the data to transmit
1334   * @param  BlockAdd: Block Address where data will be written
1335   * @param  NumberOfBlocks: Number of blocks to write
1336   * @retval HAL status
1337   */
1338 HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, const uint8_t *pData, uint32_t BlockAdd,
1339                                          uint32_t NumberOfBlocks)
1340 {
1341   SDMMC_DataInitTypeDef config;
1342   uint32_t errorstate;
1343   uint32_t add = BlockAdd;
1344 
1345   if (NULL == pData)
1346   {
1347     hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1348     return HAL_ERROR;
1349   }
1350 
1351   if (hsd->State == HAL_SD_STATE_READY)
1352   {
1353     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1354 
1355     if ((add + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr))
1356     {
1357       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1358       return HAL_ERROR;
1359     }
1360 
1361     hsd->State = HAL_SD_STATE_BUSY;
1362 
1363     /* Initialize data control register */
1364     hsd->Instance->DCTRL = 0U;
1365 
1366     hsd->pTxBuffPtr = pData;
1367     hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks;
1368 
1369     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1370     {
1371       add *= 512U;
1372     }
1373 
1374     /* Configure the SD DPSM (Data Path State Machine) */
1375     config.DataTimeOut   = SDMMC_DATATIMEOUT;
1376     config.DataLength    = BLOCKSIZE * NumberOfBlocks;
1377     config.DataBlockSize = SDMMC_DATABLOCK_SIZE_512B;
1378     config.TransferDir   = SDMMC_TRANSFER_DIR_TO_CARD;
1379     config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
1380     config.DPSM          = SDMMC_DPSM_DISABLE;
1381     (void)SDMMC_ConfigData(hsd->Instance, &config);
1382 
1383 
1384     __SDMMC_CMDTRANS_ENABLE(hsd->Instance);
1385 
1386     hsd->Instance->IDMABASE0 = (uint32_t) pData ;
1387     hsd->Instance->IDMACTRL  = SDMMC_ENABLE_IDMA_SINGLE_BUFF;
1388 
1389     /* Write Blocks in Polling mode */
1390     if (NumberOfBlocks > 1U)
1391     {
1392       hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA);
1393 
1394       /* Write Multi Block command */
1395       errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, add);
1396     }
1397     else
1398     {
1399       hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA);
1400 
1401       /* Write Single Block command */
1402       errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, add);
1403     }
1404     if (errorstate != HAL_SD_ERROR_NONE)
1405     {
1406       /* Clear all the static flags */
1407       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1408       hsd->ErrorCode |= errorstate;
1409       hsd->State = HAL_SD_STATE_READY;
1410       hsd->Context = SD_CONTEXT_NONE;
1411       return HAL_ERROR;
1412     }
1413 
1414     /* Enable transfer interrupts */
1415     __HAL_SD_ENABLE_IT(hsd, (SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | SDMMC_IT_TXUNDERR | SDMMC_IT_DATAEND));
1416 
1417     return HAL_OK;
1418   }
1419   else
1420   {
1421     return HAL_BUSY;
1422   }
1423 }
1424 
1425 /**
1426   * @brief  Erases the specified memory area of the given SD card.
1427   * @note   This API should be followed by a check on the card state through
1428   *         HAL_SD_GetCardState().
1429   * @param  hsd: Pointer to SD handle
1430   * @param  BlockStartAdd: Start Block address
1431   * @param  BlockEndAdd: End Block address
1432   * @retval HAL status
1433   */
1434 HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd)
1435 {
1436   uint32_t errorstate;
1437   uint32_t start_add = BlockStartAdd;
1438   uint32_t end_add = BlockEndAdd;
1439 
1440   if (hsd->State == HAL_SD_STATE_READY)
1441   {
1442     hsd->ErrorCode = HAL_SD_ERROR_NONE;
1443 
1444     if (end_add < start_add)
1445     {
1446       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
1447       return HAL_ERROR;
1448     }
1449 
1450     if (end_add > (hsd->SdCard.LogBlockNbr))
1451     {
1452       hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE;
1453       return HAL_ERROR;
1454     }
1455 
1456     hsd->State = HAL_SD_STATE_BUSY;
1457 
1458     /* Check if the card command class supports erase command */
1459     if (((hsd->SdCard.Class) & SDMMC_CCCC_ERASE) == 0U)
1460     {
1461       /* Clear all the static flags */
1462       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1463       hsd->ErrorCode |= HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
1464       hsd->State = HAL_SD_STATE_READY;
1465       return HAL_ERROR;
1466     }
1467 
1468     if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
1469     {
1470       /* Clear all the static flags */
1471       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1472       hsd->ErrorCode |= HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
1473       hsd->State = HAL_SD_STATE_READY;
1474       return HAL_ERROR;
1475     }
1476 
1477     /* Get start and end block for high capacity cards */
1478     if (hsd->SdCard.CardType != CARD_SDHC_SDXC)
1479     {
1480       start_add *= 512U;
1481       end_add   *= 512U;
1482     }
1483 
1484     /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */
1485     if (hsd->SdCard.CardType != CARD_SECURED)
1486     {
1487       /* Send CMD32 SD_ERASE_GRP_START with argument as addr  */
1488       errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, start_add);
1489       if (errorstate != HAL_SD_ERROR_NONE)
1490       {
1491         /* Clear all the static flags */
1492         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1493         hsd->ErrorCode |= errorstate;
1494         hsd->State = HAL_SD_STATE_READY;
1495         return HAL_ERROR;
1496       }
1497 
1498       /* Send CMD33 SD_ERASE_GRP_END with argument as addr  */
1499       errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, end_add);
1500       if (errorstate != HAL_SD_ERROR_NONE)
1501       {
1502         /* Clear all the static flags */
1503         __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1504         hsd->ErrorCode |= errorstate;
1505         hsd->State = HAL_SD_STATE_READY;
1506         return HAL_ERROR;
1507       }
1508     }
1509 
1510     /* Send CMD38 ERASE */
1511     errorstate = SDMMC_CmdErase(hsd->Instance, 0UL);
1512     if (errorstate != HAL_SD_ERROR_NONE)
1513     {
1514       /* Clear all the static flags */
1515       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
1516       hsd->ErrorCode |= errorstate;
1517       hsd->State = HAL_SD_STATE_READY;
1518       return HAL_ERROR;
1519     }
1520 
1521     hsd->State = HAL_SD_STATE_READY;
1522 
1523     return HAL_OK;
1524   }
1525   else
1526   {
1527     return HAL_BUSY;
1528   }
1529 }
1530 
1531 /**
1532   * @brief  This function handles SD card interrupt request.
1533   * @param  hsd: Pointer to SD handle
1534   * @retval None
1535   */
1536 void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd)
1537 {
1538   uint32_t errorstate;
1539   uint32_t context = hsd->Context;
1540 
1541   /* Check for SDMMC interrupt flags */
1542   if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF) != RESET) && ((context & SD_CONTEXT_IT) != 0U))
1543   {
1544     SD_Read_IT(hsd);
1545   }
1546 
1547   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND) != RESET)
1548   {
1549     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DATAEND);
1550 
1551     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND  | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
1552                         SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR  | SDMMC_IT_TXFIFOHE | \
1553                         SDMMC_IT_RXFIFOHF);
1554 
1555     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC);
1556     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
1557 
1558     if ((context & SD_CONTEXT_IT) != 0U)
1559     {
1560       if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1561       {
1562         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
1563         if (errorstate != HAL_SD_ERROR_NONE)
1564         {
1565           hsd->ErrorCode |= errorstate;
1566 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1567           hsd->ErrorCallback(hsd);
1568 #else
1569           HAL_SD_ErrorCallback(hsd);
1570 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1571         }
1572       }
1573 
1574       /* Clear all the static flags */
1575       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
1576 
1577       hsd->State = HAL_SD_STATE_READY;
1578       hsd->Context = SD_CONTEXT_NONE;
1579       if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
1580       {
1581 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1582         hsd->RxCpltCallback(hsd);
1583 #else
1584         HAL_SD_RxCpltCallback(hsd);
1585 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1586       }
1587       else
1588       {
1589 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1590         hsd->TxCpltCallback(hsd);
1591 #else
1592         HAL_SD_TxCpltCallback(hsd);
1593 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1594       }
1595     }
1596     else if ((context & SD_CONTEXT_DMA) != 0U)
1597     {
1598       hsd->Instance->DLEN = 0;
1599       hsd->Instance->DCTRL = 0;
1600       hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
1601 
1602       /* Stop Transfer for Write Multi blocks or Read Multi blocks */
1603       if (((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1604       {
1605         errorstate = SDMMC_CmdStopTransfer(hsd->Instance);
1606         if (errorstate != HAL_SD_ERROR_NONE)
1607         {
1608           hsd->ErrorCode |= errorstate;
1609 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1610           hsd->ErrorCallback(hsd);
1611 #else
1612           HAL_SD_ErrorCallback(hsd);
1613 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1614         }
1615       }
1616 
1617       hsd->State = HAL_SD_STATE_READY;
1618       hsd->Context = SD_CONTEXT_NONE;
1619       if (((context & SD_CONTEXT_WRITE_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U))
1620       {
1621 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1622         hsd->TxCpltCallback(hsd);
1623 #else
1624         HAL_SD_TxCpltCallback(hsd);
1625 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1626       }
1627       if (((context & SD_CONTEXT_READ_SINGLE_BLOCK) != 0U) || ((context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != 0U))
1628       {
1629 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1630         hsd->RxCpltCallback(hsd);
1631 #else
1632         HAL_SD_RxCpltCallback(hsd);
1633 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1634       }
1635     }
1636     else
1637     {
1638       /* Nothing to do */
1639     }
1640   }
1641 
1642   else if ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE) != RESET) && ((context & SD_CONTEXT_IT) != 0U))
1643   {
1644     SD_Write_IT(hsd);
1645   }
1646 
1647   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_RXOVERR |
1648                              SDMMC_FLAG_TXUNDERR) != RESET)
1649   {
1650     /* Set Error code */
1651     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DCRCFAIL) != RESET)
1652     {
1653       hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL;
1654     }
1655     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_DTIMEOUT) != RESET)
1656     {
1657       hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT;
1658     }
1659     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_RXOVERR) != RESET)
1660     {
1661       hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN;
1662     }
1663     if (__HAL_SD_GET_FLAG(hsd, SDMMC_IT_TXUNDERR) != RESET)
1664     {
1665       hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;
1666     }
1667 
1668     /* Clear All flags */
1669     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
1670 
1671     /* Disable all interrupts */
1672     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
1673                         SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR);
1674 
1675     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
1676     hsd->Instance->DCTRL |= SDMMC_DCTRL_FIFORST;
1677     hsd->Instance->CMD |= SDMMC_CMD_CMDSTOP;
1678     hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance);
1679     hsd->Instance->CMD &= ~(SDMMC_CMD_CMDSTOP);
1680     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DABORT);
1681 
1682     if ((context & SD_CONTEXT_IT) != 0U)
1683     {
1684       /* Set the SD state to ready to be able to start again the process */
1685       hsd->State = HAL_SD_STATE_READY;
1686       hsd->Context = SD_CONTEXT_NONE;
1687 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1688       hsd->ErrorCallback(hsd);
1689 #else
1690       HAL_SD_ErrorCallback(hsd);
1691 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1692     }
1693     else if ((context & SD_CONTEXT_DMA) != 0U)
1694     {
1695       if (hsd->ErrorCode != HAL_SD_ERROR_NONE)
1696       {
1697         /* Disable Internal DMA */
1698         __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_IDMABTC);
1699         hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
1700 
1701         /* Set the SD state to ready to be able to start again the process */
1702         hsd->State = HAL_SD_STATE_READY;
1703 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1704         hsd->ErrorCallback(hsd);
1705 #else
1706         HAL_SD_ErrorCallback(hsd);
1707 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1708       }
1709     }
1710     else
1711     {
1712       /* Nothing to do */
1713     }
1714   }
1715 
1716   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_IDMABTC) != RESET)
1717   {
1718     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_IDMABTC);
1719     if (READ_BIT(hsd->Instance->IDMACTRL, SDMMC_IDMA_IDMABACT) == 0U)
1720     {
1721       /* Current buffer is buffer0, Transfer complete for buffer1 */
1722       if ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)
1723       {
1724 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1725         hsd->Write_DMADblBuf1CpltCallback(hsd);
1726 #else
1727         HAL_SDEx_Write_DMADoubleBuf1CpltCallback(hsd);
1728 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1729       }
1730       else /* SD_CONTEXT_READ_MULTIPLE_BLOCK */
1731       {
1732 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1733         hsd->Read_DMADblBuf1CpltCallback(hsd);
1734 #else
1735         HAL_SDEx_Read_DMADoubleBuf1CpltCallback(hsd);
1736 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1737       }
1738     }
1739     else /* SD_DMA_BUFFER1 */
1740     {
1741       /* Current buffer is buffer1, Transfer complete for buffer0 */
1742       if ((context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != 0U)
1743       {
1744 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1745         hsd->Write_DMADblBuf0CpltCallback(hsd);
1746 #else
1747         HAL_SDEx_Write_DMADoubleBuf0CpltCallback(hsd);
1748 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1749       }
1750       else /* SD_CONTEXT_READ_MULTIPLE_BLOCK */
1751       {
1752 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1753         hsd->Read_DMADblBuf0CpltCallback(hsd);
1754 #else
1755         HAL_SDEx_Read_DMADoubleBuf0CpltCallback(hsd);
1756 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
1757       }
1758     }
1759   }
1760   else
1761   {
1762     /* Nothing to do */
1763   }
1764 }
1765 
1766 /**
1767   * @brief return the SD state
1768   * @param hsd: Pointer to sd handle
1769   * @retval HAL state
1770   */
1771 HAL_SD_StateTypeDef HAL_SD_GetState(SD_HandleTypeDef *hsd)
1772 {
1773   return hsd->State;
1774 }
1775 
1776 /**
1777   * @brief  Return the SD error code
1778   * @param  hsd : Pointer to a SD_HandleTypeDef structure that contains
1779   *              the configuration information.
1780   * @retval SD Error Code
1781   */
1782 uint32_t HAL_SD_GetError(SD_HandleTypeDef *hsd)
1783 {
1784   return hsd->ErrorCode;
1785 }
1786 
1787 /**
1788   * @brief Tx Transfer completed callbacks
1789   * @param hsd: Pointer to SD handle
1790   * @retval None
1791   */
1792 __weak void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd)
1793 {
1794   /* Prevent unused argument(s) compilation warning */
1795   UNUSED(hsd);
1796 
1797   /* NOTE : This function should not be modified, when the callback is needed,
1798             the HAL_SD_TxCpltCallback can be implemented in the user file
1799    */
1800 }
1801 
1802 /**
1803   * @brief Rx Transfer completed callbacks
1804   * @param hsd: Pointer SD handle
1805   * @retval None
1806   */
1807 __weak void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd)
1808 {
1809   /* Prevent unused argument(s) compilation warning */
1810   UNUSED(hsd);
1811 
1812   /* NOTE : This function should not be modified, when the callback is needed,
1813             the HAL_SD_RxCpltCallback can be implemented in the user file
1814    */
1815 }
1816 
1817 /**
1818   * @brief SD error callbacks
1819   * @param hsd: Pointer SD handle
1820   * @retval None
1821   */
1822 __weak void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd)
1823 {
1824   /* Prevent unused argument(s) compilation warning */
1825   UNUSED(hsd);
1826 
1827   /* NOTE : This function should not be modified, when the callback is needed,
1828             the HAL_SD_ErrorCallback can be implemented in the user file
1829    */
1830 }
1831 
1832 /**
1833   * @brief SD Abort callbacks
1834   * @param hsd: Pointer SD handle
1835   * @retval None
1836   */
1837 __weak void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd)
1838 {
1839   /* Prevent unused argument(s) compilation warning */
1840   UNUSED(hsd);
1841 
1842   /* NOTE : This function should not be modified, when the callback is needed,
1843             the HAL_SD_AbortCallback can be implemented in the user file
1844    */
1845 }
1846 
1847 #if (USE_SD_TRANSCEIVER != 0U)
1848 /**
1849   * @brief  Enable/Disable the SD Transceiver 1.8V Mode Callback.
1850   * @param  status: Voltage Switch State
1851   * @retval None
1852   */
1853 __weak  void HAL_SD_DriveTransceiver_1_8V_Callback(FlagStatus status)
1854 {
1855   /* Prevent unused argument(s) compilation warning */
1856   UNUSED(status);
1857   /* NOTE : This function should not be modified, when the callback is needed,
1858             the HAL_SD_EnableTransceiver could be implemented in the user file
1859    */
1860 }
1861 #endif /* USE_SD_TRANSCEIVER  */
1862 
1863 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
1864 /**
1865   * @brief  Register a User SD Callback
1866   *         To be used instead of the weak (surcharged) predefined callback
1867   * @note   The HAL_SD_RegisterCallback() may be called before HAL_SD_Init() in 
1868   *         HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID 
1869   *         and HAL_SD_MSP_DEINIT_CB_ID.
1870   * @param hsd : SD handle
1871   * @param CallbackID : ID of the callback to be registered
1872   *        This parameter can be one of the following values:
1873   *          @arg @ref HAL_SD_TX_CPLT_CB_ID                 SD Tx Complete Callback ID
1874   *          @arg @ref HAL_SD_RX_CPLT_CB_ID                 SD Rx Complete Callback ID
1875   *          @arg @ref HAL_SD_ERROR_CB_ID                   SD Error Callback ID
1876   *          @arg @ref HAL_SD_ABORT_CB_ID                   SD Abort Callback ID
1877   *          @arg @ref HAL_SD_READ_DMA_DBL_BUF0_CPLT_CB_ID  SD DMA Rx Double buffer 0 Callback ID
1878   *          @arg @ref HAL_SD_READ_DMA_DBL_BUF1_CPLT_CB_ID  SD DMA Rx Double buffer 1 Callback ID
1879   *          @arg @ref HAL_SD_WRITE_DMA_DBL_BUF0_CPLT_CB_ID SD DMA Tx Double buffer 0 Callback ID
1880   *          @arg @ref HAL_SD_WRITE_DMA_DBL_BUF1_CPLT_CB_ID SD DMA Tx Double buffer 1 Callback ID
1881   *          @arg @ref HAL_SD_MSP_INIT_CB_ID                SD MspInit Callback ID
1882   *          @arg @ref HAL_SD_MSP_DEINIT_CB_ID              SD MspDeInit Callback ID
1883   * @param pCallback : pointer to the Callback function
1884   * @retval status
1885   */
1886 HAL_StatusTypeDef HAL_SD_RegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID,
1887                                           pSD_CallbackTypeDef pCallback)
1888 {
1889   HAL_StatusTypeDef status = HAL_OK;
1890 
1891   if (pCallback == NULL)
1892   {
1893     /* Update the error code */
1894     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1895     return HAL_ERROR;
1896   }
1897 
1898   if (hsd->State == HAL_SD_STATE_READY)
1899   {
1900     switch (CallbackID)
1901     {
1902       case HAL_SD_TX_CPLT_CB_ID :
1903         hsd->TxCpltCallback = pCallback;
1904         break;
1905       case HAL_SD_RX_CPLT_CB_ID :
1906         hsd->RxCpltCallback = pCallback;
1907         break;
1908       case HAL_SD_ERROR_CB_ID :
1909         hsd->ErrorCallback = pCallback;
1910         break;
1911       case HAL_SD_ABORT_CB_ID :
1912         hsd->AbortCpltCallback = pCallback;
1913         break;
1914       case HAL_SD_READ_DMA_DBL_BUF0_CPLT_CB_ID :
1915         hsd->Read_DMADblBuf0CpltCallback = pCallback;
1916         break;
1917       case HAL_SD_READ_DMA_DBL_BUF1_CPLT_CB_ID :
1918         hsd->Read_DMADblBuf1CpltCallback = pCallback;
1919         break;
1920       case HAL_SD_WRITE_DMA_DBL_BUF0_CPLT_CB_ID :
1921         hsd->Write_DMADblBuf0CpltCallback = pCallback;
1922         break;
1923       case HAL_SD_WRITE_DMA_DBL_BUF1_CPLT_CB_ID :
1924         hsd->Write_DMADblBuf1CpltCallback = pCallback;
1925         break;
1926       case HAL_SD_MSP_INIT_CB_ID :
1927         hsd->MspInitCallback = pCallback;
1928         break;
1929       case HAL_SD_MSP_DEINIT_CB_ID :
1930         hsd->MspDeInitCallback = pCallback;
1931         break;
1932       default :
1933         /* Update the error code */
1934         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1935         /* update return status */
1936         status =  HAL_ERROR;
1937         break;
1938     }
1939   }
1940   else if (hsd->State == HAL_SD_STATE_RESET)
1941   {
1942     switch (CallbackID)
1943     {
1944       case HAL_SD_MSP_INIT_CB_ID :
1945         hsd->MspInitCallback = pCallback;
1946         break;
1947       case HAL_SD_MSP_DEINIT_CB_ID :
1948         hsd->MspDeInitCallback = pCallback;
1949         break;
1950       default :
1951         /* Update the error code */
1952         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1953         /* update return status */
1954         status =  HAL_ERROR;
1955         break;
1956     }
1957   }
1958   else
1959   {
1960     /* Update the error code */
1961     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
1962     /* update return status */
1963     status =  HAL_ERROR;
1964   }
1965 
1966   return status;
1967 }
1968 
1969 /**
1970   * @brief  Unregister a User SD Callback
1971   *         SD Callback is redirected to the weak (surcharged) predefined callback
1972   * @note   The HAL_SD_UnRegisterCallback() may be called before HAL_SD_Init() in 
1973   *         HAL_SD_STATE_RESET to register callbacks for HAL_SD_MSP_INIT_CB_ID 
1974   *         and HAL_SD_MSP_DEINIT_CB_ID.
1975   * @param hsd : SD handle
1976   * @param CallbackID : ID of the callback to be unregistered
1977   *        This parameter can be one of the following values:
1978   *          @arg @ref HAL_SD_TX_CPLT_CB_ID                 SD Tx Complete Callback ID
1979   *          @arg @ref HAL_SD_RX_CPLT_CB_ID                 SD Rx Complete Callback ID
1980   *          @arg @ref HAL_SD_ERROR_CB_ID                   SD Error Callback ID
1981   *          @arg @ref HAL_SD_ABORT_CB_ID                   SD Abort Callback ID
1982   *          @arg @ref HAL_SD_READ_DMA_DBL_BUF0_CPLT_CB_ID  SD DMA Rx Double buffer 0 Callback ID
1983   *          @arg @ref HAL_SD_READ_DMA_DBL_BUF1_CPLT_CB_ID  SD DMA Rx Double buffer 1 Callback ID
1984   *          @arg @ref HAL_SD_WRITE_DMA_DBL_BUF0_CPLT_CB_ID SD DMA Tx Double buffer 0 Callback ID
1985   *          @arg @ref HAL_SD_WRITE_DMA_DBL_BUF1_CPLT_CB_ID SD DMA Tx Double buffer 1 Callback ID
1986   *          @arg @ref HAL_SD_MSP_INIT_CB_ID                SD MspInit Callback ID
1987   *          @arg @ref HAL_SD_MSP_DEINIT_CB_ID              SD MspDeInit Callback ID
1988   * @retval status
1989   */
1990 HAL_StatusTypeDef HAL_SD_UnRegisterCallback(SD_HandleTypeDef *hsd, HAL_SD_CallbackIDTypeDef CallbackID)
1991 {
1992   HAL_StatusTypeDef status = HAL_OK;
1993 
1994   if (hsd->State == HAL_SD_STATE_READY)
1995   {
1996     switch (CallbackID)
1997     {
1998       case HAL_SD_TX_CPLT_CB_ID :
1999         hsd->TxCpltCallback = HAL_SD_TxCpltCallback;
2000         break;
2001       case HAL_SD_RX_CPLT_CB_ID :
2002         hsd->RxCpltCallback = HAL_SD_RxCpltCallback;
2003         break;
2004       case HAL_SD_ERROR_CB_ID :
2005         hsd->ErrorCallback = HAL_SD_ErrorCallback;
2006         break;
2007       case HAL_SD_ABORT_CB_ID :
2008         hsd->AbortCpltCallback = HAL_SD_AbortCallback;
2009         break;
2010       case HAL_SD_READ_DMA_DBL_BUF0_CPLT_CB_ID :
2011         hsd->Read_DMADblBuf0CpltCallback = HAL_SDEx_Read_DMADoubleBuf0CpltCallback;
2012         break;
2013       case HAL_SD_READ_DMA_DBL_BUF1_CPLT_CB_ID :
2014         hsd->Read_DMADblBuf1CpltCallback = HAL_SDEx_Read_DMADoubleBuf1CpltCallback;
2015         break;
2016       case HAL_SD_WRITE_DMA_DBL_BUF0_CPLT_CB_ID :
2017         hsd->Write_DMADblBuf0CpltCallback = HAL_SDEx_Write_DMADoubleBuf0CpltCallback;
2018         break;
2019       case HAL_SD_WRITE_DMA_DBL_BUF1_CPLT_CB_ID :
2020         hsd->Write_DMADblBuf1CpltCallback = HAL_SDEx_Write_DMADoubleBuf1CpltCallback;
2021         break;
2022       case HAL_SD_MSP_INIT_CB_ID :
2023         hsd->MspInitCallback = HAL_SD_MspInit;
2024         break;
2025       case HAL_SD_MSP_DEINIT_CB_ID :
2026         hsd->MspDeInitCallback = HAL_SD_MspDeInit;
2027         break;
2028       default :
2029         /* Update the error code */
2030         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2031         /* update return status */
2032         status =  HAL_ERROR;
2033         break;
2034     }
2035   }
2036   else if (hsd->State == HAL_SD_STATE_RESET)
2037   {
2038     switch (CallbackID)
2039     {
2040       case HAL_SD_MSP_INIT_CB_ID :
2041         hsd->MspInitCallback = HAL_SD_MspInit;
2042         break;
2043       case HAL_SD_MSP_DEINIT_CB_ID :
2044         hsd->MspDeInitCallback = HAL_SD_MspDeInit;
2045         break;
2046       default :
2047         /* Update the error code */
2048         hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2049         /* update return status */
2050         status =  HAL_ERROR;
2051         break;
2052     }
2053   }
2054   else
2055   {
2056     /* Update the error code */
2057     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2058     /* update return status */
2059     status =  HAL_ERROR;
2060   }
2061 
2062   return status;
2063 }
2064 
2065 #if (USE_SD_TRANSCEIVER != 0U)
2066 /**
2067   * @brief  Register a User SD Transceiver Callback
2068   *         To be used instead of the weak (surcharged) predefined callback
2069   * @param hsd : SD handle
2070   * @param pCallback : pointer to the Callback function
2071   * @retval status
2072   */
2073 HAL_StatusTypeDef HAL_SD_RegisterTransceiverCallback(SD_HandleTypeDef *hsd, pSD_TransceiverCallbackTypeDef pCallback)
2074 {
2075   HAL_StatusTypeDef status = HAL_OK;
2076 
2077   if (pCallback == NULL)
2078   {
2079     /* Update the error code */
2080     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2081     return HAL_ERROR;
2082   }
2083 
2084   /* Process locked */
2085   __HAL_LOCK(hsd);
2086 
2087   if (hsd->State == HAL_SD_STATE_READY)
2088   {
2089     hsd->DriveTransceiver_1_8V_Callback = pCallback;
2090   }
2091   else
2092   {
2093     /* Update the error code */
2094     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2095     /* update return status */
2096     status =  HAL_ERROR;
2097   }
2098 
2099   /* Release Lock */
2100   __HAL_UNLOCK(hsd);
2101   return status;
2102 }
2103 
2104 /**
2105   * @brief  Unregister a User SD Transceiver Callback
2106   *         SD Callback is redirected to the weak (surcharged) predefined callback
2107   * @param hsd : SD handle
2108   * @retval status
2109   */
2110 HAL_StatusTypeDef HAL_SD_UnRegisterTransceiverCallback(SD_HandleTypeDef *hsd)
2111 {
2112   HAL_StatusTypeDef status = HAL_OK;
2113 
2114   /* Process locked */
2115   __HAL_LOCK(hsd);
2116 
2117   if (hsd->State == HAL_SD_STATE_READY)
2118   {
2119     hsd->DriveTransceiver_1_8V_Callback = HAL_SD_DriveTransceiver_1_8V_Callback;
2120   }
2121   else
2122   {
2123     /* Update the error code */
2124     hsd->ErrorCode |= HAL_SD_ERROR_INVALID_CALLBACK;
2125     /* update return status */
2126     status =  HAL_ERROR;
2127   }
2128 
2129   /* Release Lock */
2130   __HAL_UNLOCK(hsd);
2131   return status;
2132 }
2133 #endif /* USE_SD_TRANSCEIVER */
2134 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
2135 
2136 /**
2137   * @}
2138   */
2139 
2140 /** @addtogroup SD_Exported_Functions_Group3
2141   *  @brief   management functions
2142   *
2143 @verbatim
2144   ==============================================================================
2145                       ##### Peripheral Control functions #####
2146   ==============================================================================
2147   [..]
2148     This subsection provides a set of functions allowing to control the SD card
2149     operations and get the related information
2150 
2151 @endverbatim
2152   * @{
2153   */
2154 
2155 /**
2156   * @brief  Returns information the information of the card which are stored on
2157   *         the CID register.
2158   * @param  hsd: Pointer to SD handle
2159   * @param  pCID: Pointer to a HAL_SD_CardCIDTypeDef structure that
2160   *         contains all CID register parameters
2161   * @retval HAL status
2162   */
2163 HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID)
2164 {
2165   pCID->ManufacturerID = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24U);
2166 
2167   pCID->OEM_AppliID = (uint16_t)((hsd->CID[0] & 0x00FFFF00U) >> 8U);
2168 
2169   pCID->ProdName1 = (((hsd->CID[0] & 0x000000FFU) << 24U) | ((hsd->CID[1] & 0xFFFFFF00U) >> 8U));
2170 
2171   pCID->ProdName2 = (uint8_t)(hsd->CID[1] & 0x000000FFU);
2172 
2173   pCID->ProdRev = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24U);
2174 
2175   pCID->ProdSN = (((hsd->CID[2] & 0x00FFFFFFU) << 8U) | ((hsd->CID[3] & 0xFF000000U) >> 24U));
2176 
2177   pCID->Reserved1 = (uint8_t)((hsd->CID[3] & 0x00F00000U) >> 20U);
2178 
2179   pCID->ManufactDate = (uint16_t)((hsd->CID[3] & 0x000FFF00U) >> 8U);
2180 
2181   pCID->CID_CRC = (uint8_t)((hsd->CID[3] & 0x000000FEU) >> 1U);
2182 
2183   pCID->Reserved2 = 1U;
2184 
2185   return HAL_OK;
2186 }
2187 
2188 /**
2189   * @brief  Returns information the information of the card which are stored on
2190   *         the CSD register.
2191   * @param  hsd: Pointer to SD handle
2192   * @param  pCSD: Pointer to a HAL_SD_CardCSDTypeDef structure that
2193   *         contains all CSD register parameters
2194   * @retval HAL status
2195   */
2196 HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD)
2197 {
2198   pCSD->CSDStruct = (uint8_t)((hsd->CSD[0] & 0xC0000000U) >> 30U);
2199 
2200   pCSD->SysSpecVersion = (uint8_t)((hsd->CSD[0] & 0x3C000000U) >> 26U);
2201 
2202   pCSD->Reserved1 = (uint8_t)((hsd->CSD[0] & 0x03000000U) >> 24U);
2203 
2204   pCSD->TAAC = (uint8_t)((hsd->CSD[0] & 0x00FF0000U) >> 16U);
2205 
2206   pCSD->NSAC = (uint8_t)((hsd->CSD[0] & 0x0000FF00U) >> 8U);
2207 
2208   pCSD->MaxBusClkFrec = (uint8_t)(hsd->CSD[0] & 0x000000FFU);
2209 
2210   pCSD->CardComdClasses = (uint16_t)((hsd->CSD[1] & 0xFFF00000U) >> 20U);
2211 
2212   pCSD->RdBlockLen = (uint8_t)((hsd->CSD[1] & 0x000F0000U) >> 16U);
2213 
2214   pCSD->PartBlockRead   = (uint8_t)((hsd->CSD[1] & 0x00008000U) >> 15U);
2215 
2216   pCSD->WrBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00004000U) >> 14U);
2217 
2218   pCSD->RdBlockMisalign = (uint8_t)((hsd->CSD[1] & 0x00002000U) >> 13U);
2219 
2220   pCSD->DSRImpl = (uint8_t)((hsd->CSD[1] & 0x00001000U) >> 12U);
2221 
2222   pCSD->Reserved2 = 0U; /*!< Reserved */
2223 
2224   if (hsd->SdCard.CardType == CARD_SDSC)
2225   {
2226     pCSD->DeviceSize = (((hsd->CSD[1] & 0x000003FFU) << 2U) | ((hsd->CSD[2] & 0xC0000000U) >> 30U));
2227 
2228     pCSD->MaxRdCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x38000000U) >> 27U);
2229 
2230     pCSD->MaxRdCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x07000000U) >> 24U);
2231 
2232     pCSD->MaxWrCurrentVDDMin = (uint8_t)((hsd->CSD[2] & 0x00E00000U) >> 21U);
2233 
2234     pCSD->MaxWrCurrentVDDMax = (uint8_t)((hsd->CSD[2] & 0x001C0000U) >> 18U);
2235 
2236     pCSD->DeviceSizeMul = (uint8_t)((hsd->CSD[2] & 0x00038000U) >> 15U);
2237 
2238     hsd->SdCard.BlockNbr  = (pCSD->DeviceSize + 1U) ;
2239     hsd->SdCard.BlockNbr *= (1UL << ((pCSD->DeviceSizeMul & 0x07U) + 2U));
2240     hsd->SdCard.BlockSize = (1UL << (pCSD->RdBlockLen & 0x0FU));
2241 
2242     hsd->SdCard.LogBlockNbr = (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / 512U);
2243     hsd->SdCard.LogBlockSize = 512U;
2244   }
2245   else if (hsd->SdCard.CardType == CARD_SDHC_SDXC)
2246   {
2247     /* Byte 7 */
2248     pCSD->DeviceSize = (((hsd->CSD[1] & 0x0000003FU) << 16U) | ((hsd->CSD[2] & 0xFFFF0000U) >> 16U));
2249 
2250     hsd->SdCard.BlockNbr = ((pCSD->DeviceSize + 1U) * 1024U);
2251     hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr;
2252     hsd->SdCard.BlockSize = 512U;
2253     hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize;
2254   }
2255   else
2256   {
2257     /* Clear all the static flags */
2258     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2259     hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2260     hsd->State = HAL_SD_STATE_READY;
2261     return HAL_ERROR;
2262   }
2263 
2264   pCSD->EraseGrSize = (uint8_t)((hsd->CSD[2] & 0x00004000U) >> 14U);
2265 
2266   pCSD->EraseGrMul = (uint8_t)((hsd->CSD[2] & 0x00003F80U) >> 7U);
2267 
2268   pCSD->WrProtectGrSize = (uint8_t)(hsd->CSD[2] & 0x0000007FU);
2269 
2270   pCSD->WrProtectGrEnable = (uint8_t)((hsd->CSD[3] & 0x80000000U) >> 31U);
2271 
2272   pCSD->ManDeflECC = (uint8_t)((hsd->CSD[3] & 0x60000000U) >> 29U);
2273 
2274   pCSD->WrSpeedFact = (uint8_t)((hsd->CSD[3] & 0x1C000000U) >> 26U);
2275 
2276   pCSD->MaxWrBlockLen = (uint8_t)((hsd->CSD[3] & 0x03C00000U) >> 22U);
2277 
2278   pCSD->WriteBlockPaPartial = (uint8_t)((hsd->CSD[3] & 0x00200000U) >> 21U);
2279 
2280   pCSD->Reserved3 = 0;
2281 
2282   pCSD->ContentProtectAppli = (uint8_t)((hsd->CSD[3] & 0x00010000U) >> 16U);
2283 
2284   pCSD->FileFormatGroup = (uint8_t)((hsd->CSD[3] & 0x00008000U) >> 15U);
2285 
2286   pCSD->CopyFlag = (uint8_t)((hsd->CSD[3] & 0x00004000U) >> 14U);
2287 
2288   pCSD->PermWrProtect = (uint8_t)((hsd->CSD[3] & 0x00002000U) >> 13U);
2289 
2290   pCSD->TempWrProtect = (uint8_t)((hsd->CSD[3] & 0x00001000U) >> 12U);
2291 
2292   pCSD->FileFormat = (uint8_t)((hsd->CSD[3] & 0x00000C00U) >> 10U);
2293 
2294   pCSD->ECC = (uint8_t)((hsd->CSD[3] & 0x00000300U) >> 8U);
2295 
2296   pCSD->CSD_CRC = (uint8_t)((hsd->CSD[3] & 0x000000FEU) >> 1U);
2297 
2298   pCSD->Reserved4 = 1;
2299 
2300   return HAL_OK;
2301 }
2302 
2303 /**
2304   * @brief  Gets the SD status info.( shall be called if there is no SD transaction ongoing )
2305   * @param  hsd: Pointer to SD handle
2306   * @param  pStatus: Pointer to the HAL_SD_CardStatusTypeDef structure that
2307   *         will contain the SD card status information
2308   * @retval HAL status
2309   */
2310 HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus)
2311 {
2312   uint32_t sd_status[16];
2313   uint32_t errorstate;
2314   HAL_StatusTypeDef status = HAL_OK;
2315 
2316   if (hsd->State == HAL_SD_STATE_BUSY)
2317   {
2318     return HAL_ERROR;
2319   }
2320 
2321   errorstate = SD_SendSDStatus(hsd, sd_status);
2322   if (errorstate != HAL_SD_ERROR_NONE)
2323   {
2324     /* Clear all the static flags */
2325     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2326     hsd->ErrorCode |= errorstate;
2327     hsd->State = HAL_SD_STATE_READY;
2328     status = HAL_ERROR;
2329   }
2330   else
2331   {
2332     pStatus->DataBusWidth = (uint8_t)((sd_status[0] & 0xC0U) >> 6U);
2333 
2334     pStatus->SecuredMode = (uint8_t)((sd_status[0] & 0x20U) >> 5U);
2335 
2336     pStatus->CardType = (uint16_t)(((sd_status[0] & 0x00FF0000U) >> 8U) | ((sd_status[0] & 0xFF000000U) >> 24U));
2337 
2338     pStatus->ProtectedAreaSize = (((sd_status[1] & 0xFFU) << 24U)    | ((sd_status[1] & 0xFF00U) << 8U) |
2339                                   ((sd_status[1] & 0xFF0000U) >> 8U) | ((sd_status[1] & 0xFF000000U) >> 24U));
2340 
2341     pStatus->SpeedClass = (uint8_t)(sd_status[2] & 0xFFU);
2342 
2343     pStatus->PerformanceMove = (uint8_t)((sd_status[2] & 0xFF00U) >> 8U);
2344 
2345     pStatus->AllocationUnitSize = (uint8_t)((sd_status[2] & 0xF00000U) >> 20U);
2346 
2347     pStatus->EraseSize = (uint16_t)(((sd_status[2] & 0xFF000000U) >> 16U) | (sd_status[3] & 0xFFU));
2348 
2349     pStatus->EraseTimeout = (uint8_t)((sd_status[3] & 0xFC00U) >> 10U);
2350 
2351     pStatus->EraseOffset = (uint8_t)((sd_status[3] & 0x0300U) >> 8U);
2352 
2353     pStatus->UhsSpeedGrade = (uint8_t)((sd_status[3] & 0x00F0U) >> 4U);
2354     pStatus->UhsAllocationUnitSize = (uint8_t)(sd_status[3] & 0x000FU) ;
2355     pStatus->VideoSpeedClass = (uint8_t)((sd_status[4] & 0xFF000000U) >> 24U);
2356   }
2357 
2358   /* Set Block Size for Card */
2359   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
2360   if (errorstate != HAL_SD_ERROR_NONE)
2361   {
2362     /* Clear all the static flags */
2363     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2364     hsd->ErrorCode = errorstate;
2365     hsd->State = HAL_SD_STATE_READY;
2366     status = HAL_ERROR;
2367   }
2368 
2369 
2370   return status;
2371 }
2372 
2373 /**
2374   * @brief  Gets the SD card info.
2375   * @param  hsd: Pointer to SD handle
2376   * @param  pCardInfo: Pointer to the HAL_SD_CardInfoTypeDef structure that
2377   *         will contain the SD card status information
2378   * @retval HAL status
2379   */
2380 HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo)
2381 {
2382   pCardInfo->CardType     = (uint32_t)(hsd->SdCard.CardType);
2383   pCardInfo->CardVersion  = (uint32_t)(hsd->SdCard.CardVersion);
2384   pCardInfo->Class        = (uint32_t)(hsd->SdCard.Class);
2385   pCardInfo->RelCardAdd   = (uint32_t)(hsd->SdCard.RelCardAdd);
2386   pCardInfo->BlockNbr     = (uint32_t)(hsd->SdCard.BlockNbr);
2387   pCardInfo->BlockSize    = (uint32_t)(hsd->SdCard.BlockSize);
2388   pCardInfo->LogBlockNbr  = (uint32_t)(hsd->SdCard.LogBlockNbr);
2389   pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize);
2390 
2391   return HAL_OK;
2392 }
2393 
2394 /**
2395   * @brief  Enables wide bus operation for the requested card if supported by
2396   *         card.
2397   * @param  hsd: Pointer to SD handle
2398   * @param  WideMode: Specifies the SD card wide bus mode
2399   *          This parameter can be one of the following values:
2400   *            @arg SDMMC_BUS_WIDE_8B: 8-bit data transfer
2401   *            @arg SDMMC_BUS_WIDE_4B: 4-bit data transfer
2402   *            @arg SDMMC_BUS_WIDE_1B: 1-bit data transfer
2403   * @retval HAL status
2404   */
2405 HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode)
2406 {
2407   SDMMC_InitTypeDef Init;
2408   uint32_t errorstate;
2409   uint32_t sdmmc_clk;
2410   HAL_StatusTypeDef status = HAL_OK;
2411 
2412   /* Check the parameters */
2413   assert_param(IS_SDMMC_BUS_WIDE(WideMode));
2414 
2415   /* Change State */
2416   hsd->State = HAL_SD_STATE_BUSY;
2417 
2418   if (hsd->SdCard.CardType != CARD_SECURED)
2419   {
2420     if (WideMode == SDMMC_BUS_WIDE_8B)
2421     {
2422       hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2423     }
2424     else if (WideMode == SDMMC_BUS_WIDE_4B)
2425     {
2426       errorstate = SD_WideBus_Enable(hsd);
2427 
2428       hsd->ErrorCode |= errorstate;
2429     }
2430     else if (WideMode == SDMMC_BUS_WIDE_1B)
2431     {
2432       errorstate = SD_WideBus_Disable(hsd);
2433 
2434       hsd->ErrorCode |= errorstate;
2435     }
2436     else
2437     {
2438       /* WideMode is not a valid argument*/
2439       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2440     }
2441   }
2442   else
2443   {
2444     /* SD Card does not support this feature */
2445     hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2446   }
2447 
2448   if (hsd->ErrorCode != HAL_SD_ERROR_NONE)
2449   {
2450     /* Clear all the static flags */
2451     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2452     status = HAL_ERROR;
2453   }
2454   else
2455   {
2456     sdmmc_clk     = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC);
2457     if (sdmmc_clk != 0U)
2458     {
2459       /* Configure the SDMMC peripheral */
2460       Init.ClockEdge           = hsd->Init.ClockEdge;
2461       Init.ClockPowerSave      = hsd->Init.ClockPowerSave;
2462       Init.BusWide             = WideMode;
2463       Init.HardwareFlowControl = hsd->Init.HardwareFlowControl;
2464 
2465       /* Check if user Clock div < Normal speed 25Mhz, no change in Clockdiv */
2466       if (hsd->Init.ClockDiv >= (sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ)))
2467       {
2468         Init.ClockDiv = hsd->Init.ClockDiv;
2469       }
2470       else if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED)
2471       {
2472         /* UltraHigh speed SD card,user Clock div */
2473         Init.ClockDiv = hsd->Init.ClockDiv;
2474       }
2475       else if (hsd->SdCard.CardSpeed == CARD_HIGH_SPEED)
2476       {
2477         /* High speed SD card, Max Frequency = 50Mhz */
2478         if (hsd->Init.ClockDiv == 0U)
2479         {
2480           if (sdmmc_clk > SD_HIGH_SPEED_FREQ)
2481           {
2482             Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ);
2483           }
2484           else
2485           {
2486             Init.ClockDiv = hsd->Init.ClockDiv;
2487           }
2488         }
2489         else
2490         {
2491           if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_HIGH_SPEED_FREQ)
2492           {
2493             Init.ClockDiv = sdmmc_clk / (2U * SD_HIGH_SPEED_FREQ);
2494           }
2495           else
2496           {
2497             Init.ClockDiv = hsd->Init.ClockDiv;
2498           }
2499         }
2500       }
2501       else
2502       {
2503         /* No High speed SD card, Max Frequency = 25Mhz */
2504         if (hsd->Init.ClockDiv == 0U)
2505         {
2506           if (sdmmc_clk > SD_NORMAL_SPEED_FREQ)
2507           {
2508             Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ);
2509           }
2510           else
2511           {
2512             Init.ClockDiv = hsd->Init.ClockDiv;
2513           }
2514         }
2515         else
2516         {
2517           if ((sdmmc_clk / (2U * hsd->Init.ClockDiv)) > SD_NORMAL_SPEED_FREQ)
2518           {
2519             Init.ClockDiv = sdmmc_clk / (2U * SD_NORMAL_SPEED_FREQ);
2520           }
2521           else
2522           {
2523             Init.ClockDiv = hsd->Init.ClockDiv;
2524           }
2525         }
2526       }
2527 
2528 #if (USE_SD_TRANSCEIVER != 0U)
2529       Init.TranceiverPresent = hsd->Init.TranceiverPresent;
2530 #endif /* USE_SD_TRANSCEIVER */
2531 
2532       (void)SDMMC_Init(hsd->Instance, Init);
2533     }
2534     else
2535     {
2536       hsd->ErrorCode |= SDMMC_ERROR_INVALID_PARAMETER;
2537       status = HAL_ERROR;
2538     }
2539   }
2540 
2541   /* Set Block Size for Card */
2542   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
2543   if (errorstate != HAL_SD_ERROR_NONE)
2544   {
2545     /* Clear all the static flags */
2546     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2547     hsd->ErrorCode |= errorstate;
2548     status = HAL_ERROR;
2549   }
2550 
2551   /* Change State */
2552   hsd->State = HAL_SD_STATE_READY;
2553 
2554   return status;
2555 }
2556 
2557 /**
2558   * @brief  Configure the speed bus mode
2559   * @param  hsd: Pointer to the SD handle
2560   * @param  SpeedMode: Specifies the SD card speed bus mode
2561   *          This parameter can be one of the following values:
2562   *            @arg SDMMC_SPEED_MODE_AUTO: Max speed mode supported by the card
2563   *            @arg SDMMC_SPEED_MODE_DEFAULT: Default Speed/SDR12 mode
2564   *            @arg SDMMC_SPEED_MODE_HIGH: High Speed/SDR25 mode
2565   *            @arg SDMMC_SPEED_MODE_ULTRA: Ultra high speed mode
2566   * @retval HAL status
2567   */
2568 
2569 HAL_StatusTypeDef HAL_SD_ConfigSpeedBusOperation(SD_HandleTypeDef *hsd, uint32_t SpeedMode)
2570 {
2571   uint32_t tickstart;
2572   uint32_t errorstate;
2573   HAL_StatusTypeDef status = HAL_OK;
2574 
2575   /* Check the parameters */
2576   assert_param(IS_SDMMC_SPEED_MODE(SpeedMode));
2577   /* Change State */
2578   hsd->State = HAL_SD_STATE_BUSY;
2579 
2580 #if (USE_SD_TRANSCEIVER != 0U)
2581   if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
2582   {
2583     switch (SpeedMode)
2584     {
2585       case SDMMC_SPEED_MODE_AUTO:
2586       {
2587         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2588             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2589         {
2590           hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED;
2591           /* Enable Ultra High Speed */
2592           if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2593           {
2594             if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2595             {
2596               hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2597               status = HAL_ERROR;
2598             }
2599           }
2600         }
2601         else if (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED)
2602         {
2603           /* Enable High Speed */
2604           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2605           {
2606             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2607             status = HAL_ERROR;
2608           }
2609         }
2610         else
2611         {
2612           /*Nothing to do, Use defaultSpeed */
2613         }
2614         break;
2615       }
2616       case SDMMC_SPEED_MODE_ULTRA_SDR104:
2617       {
2618         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2619             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2620         {
2621           /* Enable UltraHigh Speed */
2622           if (SD_UltraHighSpeed(hsd, SDMMC_SDR104_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2623           {
2624             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2625             status = HAL_ERROR;
2626           }
2627           hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED;
2628         }
2629         else
2630         {
2631           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2632           status = HAL_ERROR;
2633         }
2634         break;
2635       }
2636       case SDMMC_SPEED_MODE_ULTRA_SDR50:
2637       {
2638         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2639             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2640         {
2641           /* Enable UltraHigh Speed */
2642           if (SD_UltraHighSpeed(hsd, SDMMC_SDR50_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2643           {
2644             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2645             status = HAL_ERROR;
2646           }
2647           hsd->Instance->CLKCR |= SDMMC_CLKCR_BUSSPEED;
2648         }
2649         else
2650         {
2651           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2652           status = HAL_ERROR;
2653         }
2654         break;
2655       }
2656       case SDMMC_SPEED_MODE_DDR:
2657       {
2658         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2659             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2660         {
2661           /* Enable DDR Mode*/
2662           if (SD_DDR_Mode(hsd) != HAL_SD_ERROR_NONE)
2663           {
2664             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2665             status = HAL_ERROR;
2666           }
2667           hsd->Instance->CLKCR |=  SDMMC_CLKCR_BUSSPEED | SDMMC_CLKCR_DDR;
2668         }
2669         else
2670         {
2671           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2672           status = HAL_ERROR;
2673         }
2674         break;
2675       }
2676       case SDMMC_SPEED_MODE_HIGH:
2677       {
2678         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2679             (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2680             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2681         {
2682           /* Enable High Speed */
2683           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2684           {
2685             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2686             status = HAL_ERROR;
2687           }
2688         }
2689         else
2690         {
2691           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2692           status = HAL_ERROR;
2693         }
2694         break;
2695       }
2696       case SDMMC_SPEED_MODE_DEFAULT:
2697       {
2698         /* Switch to default Speed */
2699         if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2700         {
2701           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2702           status = HAL_ERROR;
2703         }
2704 
2705         break;
2706       }
2707       default:
2708         hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2709         status = HAL_ERROR;
2710         break;
2711     }
2712   }
2713   else
2714   {
2715     switch (SpeedMode)
2716     {
2717       case SDMMC_SPEED_MODE_AUTO:
2718       {
2719         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2720             (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2721             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2722         {
2723           /* Enable High Speed */
2724           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2725           {
2726             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2727             status = HAL_ERROR;
2728           }
2729         }
2730         else
2731         {
2732           /*Nothing to do, Use defaultSpeed */
2733         }
2734         break;
2735       }
2736       case SDMMC_SPEED_MODE_HIGH:
2737       {
2738         if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2739             (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2740             (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2741         {
2742           /* Enable High Speed */
2743           if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2744           {
2745             hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2746             status = HAL_ERROR;
2747           }
2748         }
2749         else
2750         {
2751           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2752           status = HAL_ERROR;
2753         }
2754         break;
2755       }
2756       case SDMMC_SPEED_MODE_DEFAULT:
2757       {
2758         /* Switch to default Speed */
2759         if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2760         {
2761           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2762           status = HAL_ERROR;
2763         }
2764 
2765         break;
2766       }
2767       case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/
2768       default:
2769         hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2770         status = HAL_ERROR;
2771         break;
2772     }
2773   }
2774 #else
2775   switch (SpeedMode)
2776   {
2777     case SDMMC_SPEED_MODE_AUTO:
2778     {
2779       if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2780           (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2781           (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2782       {
2783         /* Enable High Speed */
2784         if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2785         {
2786           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2787           status = HAL_ERROR;
2788         }
2789       }
2790       else
2791       {
2792         /*Nothing to do, Use defaultSpeed */
2793       }
2794       break;
2795     }
2796     case SDMMC_SPEED_MODE_HIGH:
2797     {
2798       if ((hsd->SdCard.CardSpeed  == CARD_ULTRA_HIGH_SPEED) ||
2799           (hsd->SdCard.CardSpeed  == CARD_HIGH_SPEED) ||
2800           (hsd->SdCard.CardType == CARD_SDHC_SDXC))
2801       {
2802         /* Enable High Speed */
2803         if (SD_SwitchSpeed(hsd, SDMMC_SDR25_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2804         {
2805           hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2806           status = HAL_ERROR;
2807         }
2808       }
2809       else
2810       {
2811         hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2812         status = HAL_ERROR;
2813       }
2814       break;
2815     }
2816     case SDMMC_SPEED_MODE_DEFAULT:
2817     {
2818       /* Switch to default Speed */
2819       if (SD_SwitchSpeed(hsd, SDMMC_SDR12_SWITCH_PATTERN) != HAL_SD_ERROR_NONE)
2820       {
2821         hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE;
2822         status = HAL_ERROR;
2823       }
2824 
2825       break;
2826     }
2827     case SDMMC_SPEED_MODE_ULTRA: /*not valid without transceiver*/
2828     default:
2829       hsd->ErrorCode |= HAL_SD_ERROR_PARAM;
2830       status = HAL_ERROR;
2831       break;
2832   }
2833 #endif /* USE_SD_TRANSCEIVER */
2834 
2835   /* Verify that SD card is ready to use after Speed mode switch*/
2836   tickstart = HAL_GetTick();
2837   while ((HAL_SD_GetCardState(hsd) != HAL_SD_CARD_TRANSFER))
2838   {
2839     if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
2840     {
2841       hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2842       hsd->State = HAL_SD_STATE_READY;
2843       return HAL_TIMEOUT;
2844     }
2845   }
2846 
2847   /* Set Block Size for Card */
2848   errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE);
2849   if (errorstate != HAL_SD_ERROR_NONE)
2850   {
2851     /* Clear all the static flags */
2852     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_FLAGS);
2853     hsd->ErrorCode |= errorstate;
2854     status = HAL_ERROR;
2855   }
2856 
2857   /* Change State */
2858   hsd->State = HAL_SD_STATE_READY;
2859   return status;
2860 }
2861 
2862 /**
2863   * @brief  Gets the current sd card data state.
2864   * @param  hsd: pointer to SD handle
2865   * @retval Card state
2866   */
2867 HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd)
2868 {
2869   uint32_t cardstate;
2870   uint32_t errorstate;
2871   uint32_t resp1 = 0;
2872 
2873   errorstate = SD_SendStatus(hsd, &resp1);
2874   if (errorstate != HAL_SD_ERROR_NONE)
2875   {
2876     hsd->ErrorCode |= errorstate;
2877   }
2878 
2879   cardstate = ((resp1 >> 9U) & 0x0FU);
2880 
2881   return (HAL_SD_CardStateTypeDef)cardstate;
2882 }
2883 
2884 /**
2885   * @brief  Abort the current transfer and disable the SD.
2886   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
2887   *                the configuration information for SD module.
2888   * @retval HAL status
2889   */
2890 HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd)
2891 {
2892   uint32_t error_code;
2893   uint32_t tickstart;
2894 
2895   if (hsd->State == HAL_SD_STATE_BUSY)
2896   {
2897     /* DIsable All interrupts */
2898     __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
2899                          SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR);
2900     __SDMMC_CMDTRANS_DISABLE(hsd->Instance);
2901 
2902     /*we will send the CMD12 in all cases in order to stop the data transfers*/
2903     /*In case the data transfer just finished , the external memory will not respond and will return HAL_SD_ERROR_CMD_RSP_TIMEOUT*/
2904     /*In case the data transfer aborted , the external memory will respond and will return HAL_SD_ERROR_NONE*/
2905     /*Other scenario will return HAL_ERROR*/
2906 
2907     hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance);
2908     error_code = hsd->ErrorCode;
2909     if ((error_code != HAL_SD_ERROR_NONE) && (error_code != HAL_SD_ERROR_CMD_RSP_TIMEOUT))
2910     {
2911       return HAL_ERROR;
2912     }
2913 
2914     tickstart = HAL_GetTick();
2915     if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_CARD)
2916     {
2917       if (hsd->ErrorCode == HAL_SD_ERROR_NONE)
2918       {
2919          while(!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_BUSYD0END))
2920         {
2921            if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
2922            {
2923               hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2924               hsd->State = HAL_SD_STATE_READY;
2925               return HAL_TIMEOUT;
2926            }
2927         }
2928       }
2929 
2930       if (hsd->ErrorCode == HAL_SD_ERROR_CMD_RSP_TIMEOUT)
2931       {
2932         while(!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DATAEND))
2933         {
2934            if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
2935            {
2936               hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2937               hsd->State = HAL_SD_STATE_READY;
2938               return HAL_TIMEOUT;
2939            }
2940         }
2941       }
2942     }
2943     else if ((hsd->Instance->DCTRL & SDMMC_DCTRL_DTDIR) == SDMMC_TRANSFER_DIR_TO_SDMMC)
2944     {
2945       while(!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DABORT | SDMMC_FLAG_DATAEND))
2946       {
2947            if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
2948            {
2949               hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
2950               hsd->State = HAL_SD_STATE_READY;
2951               return HAL_TIMEOUT;
2952            }
2953       }
2954     }
2955     else
2956     {
2957       /* Nothing to do*/
2958     }
2959 
2960     /*The reason of all these while conditions previously is that we need to wait the SDMMC and clear
2961       the appropriate flags that will be set depending of the abort/non abort of the memory */
2962     /*Not waiting the SDMMC flags will cause the next SDMMC_DISABLE_IDMA to not get cleared
2963       and will result in next SDMMC read/write operation to fail */
2964 
2965     /*SDMMC ready for clear data flags*/
2966     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_BUSYD0END);
2967     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
2968       /* If IDMA Context, disable Internal DMA */
2969     hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
2970 
2971     hsd->State = HAL_SD_STATE_READY;
2972 
2973     /* Initialize the SD operation */
2974     hsd->Context = SD_CONTEXT_NONE;
2975   }
2976   return HAL_OK;
2977 }
2978 
2979 
2980 /**
2981   * @brief  Abort the current transfer and disable the SD (IT mode).
2982   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
2983   *                the configuration information for SD module.
2984   * @retval HAL status
2985   */
2986 HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd)
2987 {
2988   HAL_SD_CardStateTypeDef CardState;
2989 
2990   /* Disable All interrupts */
2991   __HAL_SD_DISABLE_IT(hsd, SDMMC_IT_DATAEND | SDMMC_IT_DCRCFAIL | SDMMC_IT_DTIMEOUT | \
2992                       SDMMC_IT_TXUNDERR | SDMMC_IT_RXOVERR);
2993 
2994   /* If IDMA Context, disable Internal DMA */
2995   hsd->Instance->IDMACTRL = SDMMC_DISABLE_IDMA;
2996 
2997   /* Clear All flags */
2998   __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
2999 
3000   CardState = HAL_SD_GetCardState(hsd);
3001   hsd->State = HAL_SD_STATE_READY;
3002 
3003   if ((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING))
3004   {
3005     hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance);
3006   }
3007 
3008   if (hsd->ErrorCode != HAL_SD_ERROR_NONE)
3009   {
3010     return HAL_ERROR;
3011   }
3012   else
3013   {
3014 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
3015     hsd->AbortCpltCallback(hsd);
3016 #else
3017     HAL_SD_AbortCallback(hsd);
3018 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
3019   }
3020 
3021   return HAL_OK;
3022 }
3023 
3024 /**
3025   * @}
3026   */
3027 
3028 /**
3029   * @}
3030   */
3031 
3032 /* Private function ----------------------------------------------------------*/
3033 /** @addtogroup SD_Private_Functions
3034   * @{
3035   */
3036 
3037 
3038 /**
3039   * @brief  Initializes the sd card.
3040   * @param  hsd: Pointer to SD handle
3041   * @retval SD Card error state
3042   */
3043 static uint32_t SD_InitCard(SD_HandleTypeDef *hsd)
3044 {
3045   HAL_SD_CardCSDTypeDef CSD;
3046   uint32_t errorstate;
3047   uint16_t sd_rca = 0U;
3048   uint32_t tickstart = HAL_GetTick();
3049 
3050   /* Check the power State */
3051   if (SDMMC_GetPowerState(hsd->Instance) == 0U)
3052   {
3053     /* Power off */
3054     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3055   }
3056 
3057   if (hsd->SdCard.CardType != CARD_SECURED)
3058   {
3059     /* Send CMD2 ALL_SEND_CID */
3060     errorstate = SDMMC_CmdSendCID(hsd->Instance);
3061     if (errorstate != HAL_SD_ERROR_NONE)
3062     {
3063       return errorstate;
3064     }
3065     else
3066     {
3067       /* Get Card identification number data */
3068       hsd->CID[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3069       hsd->CID[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2);
3070       hsd->CID[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3);
3071       hsd->CID[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4);
3072     }
3073   }
3074 
3075   if (hsd->SdCard.CardType != CARD_SECURED)
3076   {
3077     /* Send CMD3 SET_REL_ADDR with argument 0 */
3078     /* SD Card publishes its RCA. */
3079     while (sd_rca == 0U)
3080     {
3081       errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca);
3082       if (errorstate != HAL_SD_ERROR_NONE)
3083       {
3084         return errorstate;
3085       }
3086       if ((HAL_GetTick() - tickstart) >=  SDMMC_CMDTIMEOUT)
3087       {
3088         return HAL_SD_ERROR_TIMEOUT;
3089       }
3090     }
3091   }
3092   if (hsd->SdCard.CardType != CARD_SECURED)
3093   {
3094     /* Get the SD card RCA */
3095     hsd->SdCard.RelCardAdd = sd_rca;
3096 
3097     /* Send CMD9 SEND_CSD with argument as card's RCA */
3098     errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3099     if (errorstate != HAL_SD_ERROR_NONE)
3100     {
3101       return errorstate;
3102     }
3103     else
3104     {
3105       /* Get Card Specific Data */
3106       hsd->CSD[0U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3107       hsd->CSD[1U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2);
3108       hsd->CSD[2U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP3);
3109       hsd->CSD[3U] = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP4);
3110     }
3111   }
3112 
3113   /* Get the Card Class */
3114   hsd->SdCard.Class = (SDMMC_GetResponse(hsd->Instance, SDMMC_RESP2) >> 20U);
3115 
3116   /* Get CSD parameters */
3117   if (HAL_SD_GetCardCSD(hsd, &CSD) != HAL_OK)
3118   {
3119     return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
3120   }
3121 
3122   /* Select the Card */
3123   errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U));
3124   if (errorstate != HAL_SD_ERROR_NONE)
3125   {
3126     return errorstate;
3127   }
3128 
3129   /* All cards are initialized */
3130   return HAL_SD_ERROR_NONE;
3131 }
3132 
3133 /**
3134   * @brief  Enquires cards about their operating voltage and configures clock
3135   *         controls and stores SD information that will be needed in future
3136   *         in the SD handle.
3137   * @param  hsd: Pointer to SD handle
3138   * @retval error state
3139   */
3140 static uint32_t SD_PowerON(SD_HandleTypeDef *hsd)
3141 {
3142   __IO uint32_t count = 0U;
3143   uint32_t response = 0U;
3144   uint32_t validvoltage = 0U;
3145   uint32_t errorstate;
3146 #if (USE_SD_TRANSCEIVER != 0U)
3147   uint32_t tickstart = HAL_GetTick();
3148 #endif /* USE_SD_TRANSCEIVER  */
3149 
3150   /* CMD0: GO_IDLE_STATE */
3151   errorstate = SDMMC_CmdGoIdleState(hsd->Instance);
3152   if (errorstate != HAL_SD_ERROR_NONE)
3153   {
3154     return errorstate;
3155   }
3156 
3157   /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */
3158   errorstate = SDMMC_CmdOperCond(hsd->Instance);
3159   if (errorstate == SDMMC_ERROR_TIMEOUT) /* No response to CMD8 */
3160   {
3161     hsd->SdCard.CardVersion = CARD_V1_X;
3162     /* CMD0: GO_IDLE_STATE */
3163     errorstate = SDMMC_CmdGoIdleState(hsd->Instance);
3164     if (errorstate != HAL_SD_ERROR_NONE)
3165     {
3166       return errorstate;
3167     }
3168 
3169   }
3170   else
3171   {
3172     hsd->SdCard.CardVersion = CARD_V2_X;
3173   }
3174 
3175   if (hsd->SdCard.CardVersion == CARD_V2_X)
3176   {
3177     /* SEND CMD55 APP_CMD with RCA as 0 */
3178     errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0);
3179     if (errorstate != HAL_SD_ERROR_NONE)
3180     {
3181       return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
3182     }
3183   }
3184   /* SD CARD */
3185   /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */
3186   while ((count < SDMMC_MAX_VOLT_TRIAL) && (validvoltage == 0U))
3187   {
3188     /* SEND CMD55 APP_CMD with RCA as 0 */
3189     errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0);
3190     if (errorstate != HAL_SD_ERROR_NONE)
3191     {
3192       return errorstate;
3193     }
3194 
3195     /* Send CMD41 */
3196     errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_VOLTAGE_WINDOW_SD | SDMMC_HIGH_CAPACITY |
3197                                          SD_SWITCH_1_8V_CAPACITY);
3198     if (errorstate != HAL_SD_ERROR_NONE)
3199     {
3200       return HAL_SD_ERROR_UNSUPPORTED_FEATURE;
3201     }
3202 
3203     /* Get command response */
3204     response = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3205 
3206     /* Get operating voltage*/
3207     validvoltage = (((response >> 31U) == 1U) ? 1U : 0U);
3208 
3209     count++;
3210   }
3211 
3212   if (count >= SDMMC_MAX_VOLT_TRIAL)
3213   {
3214     return HAL_SD_ERROR_INVALID_VOLTRANGE;
3215   }
3216 
3217   /* Set default card type */
3218   hsd->SdCard.CardType = CARD_SDSC;
3219 
3220   if ((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY)
3221   {
3222     hsd->SdCard.CardType = CARD_SDHC_SDXC;
3223 #if (USE_SD_TRANSCEIVER != 0U)
3224     if (hsd->Init.TranceiverPresent == SDMMC_TRANSCEIVER_PRESENT)
3225     {
3226       if ((response & SD_SWITCH_1_8V_CAPACITY) == SD_SWITCH_1_8V_CAPACITY)
3227       {
3228         hsd->SdCard.CardSpeed = CARD_ULTRA_HIGH_SPEED;
3229 
3230         /* Start switching procedue */
3231         hsd->Instance->POWER |= SDMMC_POWER_VSWITCHEN;
3232 
3233         /* Send CMD11 to switch 1.8V mode */
3234         errorstate = SDMMC_CmdVoltageSwitch(hsd->Instance);
3235         if (errorstate != HAL_SD_ERROR_NONE)
3236         {
3237           return errorstate;
3238         }
3239 
3240         /* Check to CKSTOP */
3241         while ((hsd->Instance->STA & SDMMC_FLAG_CKSTOP) != SDMMC_FLAG_CKSTOP)
3242         {
3243           if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
3244           {
3245             return HAL_SD_ERROR_TIMEOUT;
3246           }
3247         }
3248 
3249         /* Clear CKSTOP Flag */
3250         hsd->Instance->ICR = SDMMC_FLAG_CKSTOP;
3251 
3252         /* Check to BusyD0 */
3253         if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) != SDMMC_FLAG_BUSYD0)
3254         {
3255           /* Error when activate Voltage Switch in SDMMC Peripheral */
3256           return SDMMC_ERROR_UNSUPPORTED_FEATURE;
3257         }
3258         else
3259         {
3260           /* Enable Transceiver Switch PIN */
3261 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
3262           hsd->DriveTransceiver_1_8V_Callback(SET);
3263 #else
3264           HAL_SD_DriveTransceiver_1_8V_Callback(SET);
3265 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
3266 
3267           /* Switch ready */
3268           hsd->Instance->POWER |= SDMMC_POWER_VSWITCH;
3269 
3270           /* Check VSWEND Flag */
3271           while ((hsd->Instance->STA & SDMMC_FLAG_VSWEND) != SDMMC_FLAG_VSWEND)
3272           {
3273             if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
3274             {
3275               return HAL_SD_ERROR_TIMEOUT;
3276             }
3277           }
3278 
3279           /* Clear VSWEND Flag */
3280           hsd->Instance->ICR = SDMMC_FLAG_VSWEND;
3281 
3282           /* Check BusyD0 status */
3283           if ((hsd->Instance->STA & SDMMC_FLAG_BUSYD0) == SDMMC_FLAG_BUSYD0)
3284           {
3285             /* Error when enabling 1.8V mode */
3286             return HAL_SD_ERROR_INVALID_VOLTRANGE;
3287           }
3288           /* Switch to 1.8V OK */
3289 
3290           /* Disable VSWITCH FLAG from SDMMC Peripheral */
3291           hsd->Instance->POWER = 0x13U;
3292 
3293           /* Clean Status flags */
3294           hsd->Instance->ICR = 0xFFFFFFFFU;
3295         }
3296       }
3297     }
3298 #endif /* USE_SD_TRANSCEIVER  */
3299   }
3300 
3301   return HAL_SD_ERROR_NONE;
3302 }
3303 
3304 /**
3305   * @brief  Turns the SDMMC output signals off.
3306   * @param  hsd: Pointer to SD handle
3307   * @retval None
3308   */
3309 static void SD_PowerOFF(SD_HandleTypeDef *hsd)
3310 {
3311   /* Set Power State to OFF */
3312   (void)SDMMC_PowerState_OFF(hsd->Instance);
3313 }
3314 
3315 /**
3316   * @brief  Send Status info command.
3317   * @param  hsd: pointer to SD handle
3318   * @param  pSDstatus: Pointer to the buffer that will contain the SD card status
3319   *         SD Status register)
3320   * @retval error state
3321   */
3322 static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus)
3323 {
3324   SDMMC_DataInitTypeDef config;
3325   uint32_t errorstate;
3326   uint32_t tickstart = HAL_GetTick();
3327   uint32_t count;
3328   uint32_t *pData = pSDstatus;
3329 
3330   /* Check SD response */
3331   if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3332   {
3333     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3334   }
3335 
3336   /* Set block size for card if it is not equal to current block size for card */
3337   errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3338   if (errorstate != HAL_SD_ERROR_NONE)
3339   {
3340     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
3341     return errorstate;
3342   }
3343 
3344   /* Send CMD55 */
3345   errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3346   if (errorstate != HAL_SD_ERROR_NONE)
3347   {
3348     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
3349     return errorstate;
3350   }
3351 
3352   /* Configure the SD DPSM (Data Path State Machine) */
3353   config.DataTimeOut   = SDMMC_DATATIMEOUT;
3354   config.DataLength    = 64U;
3355   config.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B;
3356   config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3357   config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3358   config.DPSM          = SDMMC_DPSM_ENABLE;
3359   (void)SDMMC_ConfigData(hsd->Instance, &config);
3360 
3361   /* Send ACMD13 (SD_APP_STAUS)  with argument as card's RCA */
3362   errorstate = SDMMC_CmdStatusRegister(hsd->Instance);
3363   if (errorstate != HAL_SD_ERROR_NONE)
3364   {
3365     hsd->ErrorCode |= HAL_SD_ERROR_NONE;
3366     return errorstate;
3367   }
3368 
3369   /* Get status data */
3370   while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
3371   {
3372     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3373     {
3374       for (count = 0U; count < 8U; count++)
3375       {
3376         *pData = SDMMC_ReadFIFO(hsd->Instance);
3377         pData++;
3378       }
3379     }
3380 
3381     if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
3382     {
3383       return HAL_SD_ERROR_TIMEOUT;
3384     }
3385   }
3386 
3387   if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3388   {
3389     return HAL_SD_ERROR_DATA_TIMEOUT;
3390   }
3391   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3392   {
3393     return HAL_SD_ERROR_DATA_CRC_FAIL;
3394   }
3395   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3396   {
3397     return HAL_SD_ERROR_RX_OVERRUN;
3398   }
3399   else
3400   {
3401     /* Nothing to do */
3402   }
3403 
3404   while ((__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DPSMACT)))
3405   {
3406     *pData = SDMMC_ReadFIFO(hsd->Instance);
3407     pData++;
3408 
3409     if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
3410     {
3411       return HAL_SD_ERROR_TIMEOUT;
3412     }
3413   }
3414 
3415   /* Clear all the static status flags*/
3416   __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3417 
3418   return HAL_SD_ERROR_NONE;
3419 }
3420 
3421 /**
3422   * @brief  Returns the current card's status.
3423   * @param  hsd: Pointer to SD handle
3424   * @param  pCardStatus: pointer to the buffer that will contain the SD card
3425   *         status (Card Status register)
3426   * @retval error state
3427   */
3428 static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus)
3429 {
3430   uint32_t errorstate;
3431 
3432   if (pCardStatus == NULL)
3433   {
3434     return HAL_SD_ERROR_PARAM;
3435   }
3436 
3437   /* Send Status command */
3438   errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3439   if (errorstate != HAL_SD_ERROR_NONE)
3440   {
3441     return errorstate;
3442   }
3443 
3444   /* Get SD card status */
3445   *pCardStatus = SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1);
3446 
3447   return HAL_SD_ERROR_NONE;
3448 }
3449 
3450 /**
3451   * @brief  Enables the SDMMC wide bus mode.
3452   * @param  hsd: pointer to SD handle
3453   * @retval error state
3454   */
3455 static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd)
3456 {
3457   uint32_t scr[2U] = {0UL, 0UL};
3458   uint32_t errorstate;
3459 
3460   if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3461   {
3462     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3463   }
3464 
3465   /* Get SCR Register */
3466   errorstate = SD_FindSCR(hsd, scr);
3467   if (errorstate != HAL_SD_ERROR_NONE)
3468   {
3469     return errorstate;
3470   }
3471 
3472   /* If requested card supports wide bus operation */
3473   if ((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO)
3474   {
3475     /* Send CMD55 APP_CMD with argument as card's RCA.*/
3476     errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3477     if (errorstate != HAL_SD_ERROR_NONE)
3478     {
3479       return errorstate;
3480     }
3481 
3482     /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
3483     errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U);
3484     if (errorstate != HAL_SD_ERROR_NONE)
3485     {
3486       return errorstate;
3487     }
3488 
3489     return HAL_SD_ERROR_NONE;
3490   }
3491   else
3492   {
3493     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3494   }
3495 }
3496 
3497 /**
3498   * @brief  Disables the SDMMC wide bus mode.
3499   * @param  hsd: Pointer to SD handle
3500   * @retval error state
3501   */
3502 static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd)
3503 {
3504   uint32_t scr[2U] = {0UL, 0UL};
3505   uint32_t errorstate;
3506 
3507   if ((SDMMC_GetResponse(hsd->Instance, SDMMC_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED)
3508   {
3509     return HAL_SD_ERROR_LOCK_UNLOCK_FAILED;
3510   }
3511 
3512   /* Get SCR Register */
3513   errorstate = SD_FindSCR(hsd, scr);
3514   if (errorstate != HAL_SD_ERROR_NONE)
3515   {
3516     return errorstate;
3517   }
3518 
3519   /* If requested card supports 1 bit mode operation */
3520   if ((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO)
3521   {
3522     /* Send CMD55 APP_CMD with argument as card's RCA */
3523     errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U));
3524     if (errorstate != HAL_SD_ERROR_NONE)
3525     {
3526       return errorstate;
3527     }
3528 
3529     /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */
3530     errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U);
3531     if (errorstate != HAL_SD_ERROR_NONE)
3532     {
3533       return errorstate;
3534     }
3535 
3536     return HAL_SD_ERROR_NONE;
3537   }
3538   else
3539   {
3540     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3541   }
3542 }
3543 
3544 
3545 /**
3546   * @brief  Finds the SD card SCR register value.
3547   * @param  hsd: Pointer to SD handle
3548   * @param  pSCR: pointer to the buffer that will contain the SCR value
3549   * @retval error state
3550   */
3551 static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR)
3552 {
3553   SDMMC_DataInitTypeDef config;
3554   uint32_t errorstate;
3555   uint32_t tickstart = HAL_GetTick();
3556   uint32_t index = 0U;
3557   uint32_t tempscr[2U] = {0UL, 0UL};
3558   uint32_t *scr = pSCR;
3559 
3560   /* Set Block Size To 8 Bytes */
3561   errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U);
3562   if (errorstate != HAL_SD_ERROR_NONE)
3563   {
3564     return errorstate;
3565   }
3566 
3567   /* Send CMD55 APP_CMD with argument as card's RCA */
3568   errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U));
3569   if (errorstate != HAL_SD_ERROR_NONE)
3570   {
3571     return errorstate;
3572   }
3573 
3574   config.DataTimeOut   = SDMMC_DATATIMEOUT;
3575   config.DataLength    = 8U;
3576   config.DataBlockSize = SDMMC_DATABLOCK_SIZE_8B;
3577   config.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3578   config.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3579   config.DPSM          = SDMMC_DPSM_ENABLE;
3580   (void)SDMMC_ConfigData(hsd->Instance, &config);
3581 
3582   /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */
3583   errorstate = SDMMC_CmdSendSCR(hsd->Instance);
3584   if (errorstate != HAL_SD_ERROR_NONE)
3585   {
3586     return errorstate;
3587   }
3588 
3589   while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3590                             SDMMC_FLAG_DATAEND))
3591   {
3592     if ((!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOE)) && (index == 0U))
3593     {
3594       tempscr[0] = SDMMC_ReadFIFO(hsd->Instance);
3595       tempscr[1] = SDMMC_ReadFIFO(hsd->Instance);
3596       index++;
3597     }
3598 
3599 
3600     if ((HAL_GetTick() - tickstart) >=  SDMMC_DATATIMEOUT)
3601     {
3602       return HAL_SD_ERROR_TIMEOUT;
3603     }
3604   }
3605 
3606   if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3607   {
3608     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3609 
3610     return HAL_SD_ERROR_DATA_TIMEOUT;
3611   }
3612   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3613   {
3614     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3615 
3616     return HAL_SD_ERROR_DATA_CRC_FAIL;
3617   }
3618   else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3619   {
3620     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3621 
3622     return HAL_SD_ERROR_RX_OVERRUN;
3623   }
3624   else
3625   {
3626     /* No error flag set */
3627     /* Clear all the static flags */
3628     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3629 
3630     *scr = (((tempscr[1] & SDMMC_0TO7BITS) << 24)  | ((tempscr[1] & SDMMC_8TO15BITS) << 8) | \
3631             ((tempscr[1] & SDMMC_16TO23BITS) >> 8) | ((tempscr[1] & SDMMC_24TO31BITS) >> 24));
3632     scr++;
3633     *scr = (((tempscr[0] & SDMMC_0TO7BITS) << 24)  | ((tempscr[0] & SDMMC_8TO15BITS) << 8) | \
3634             ((tempscr[0] & SDMMC_16TO23BITS) >> 8) | ((tempscr[0] & SDMMC_24TO31BITS) >> 24));
3635 
3636   }
3637 
3638   return HAL_SD_ERROR_NONE;
3639 }
3640 
3641 /**
3642   * @brief  Wrap up reading in non-blocking mode.
3643   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
3644   *              the configuration information.
3645   * @retval None
3646   */
3647 static void SD_Read_IT(SD_HandleTypeDef *hsd)
3648 {
3649   uint32_t count;
3650   uint32_t data;
3651   uint8_t *tmp;
3652 
3653   tmp = hsd->pRxBuffPtr;
3654 
3655   if (hsd->RxXferSize >= 32U)
3656   {
3657     /* Read data from SDMMC Rx FIFO */
3658     for (count = 0U; count < 8U; count++)
3659     {
3660       data = SDMMC_ReadFIFO(hsd->Instance);
3661       *tmp = (uint8_t)(data & 0xFFU);
3662       tmp++;
3663       *tmp = (uint8_t)((data >> 8U) & 0xFFU);
3664       tmp++;
3665       *tmp = (uint8_t)((data >> 16U) & 0xFFU);
3666       tmp++;
3667       *tmp = (uint8_t)((data >> 24U) & 0xFFU);
3668       tmp++;
3669     }
3670 
3671     hsd->pRxBuffPtr = tmp;
3672     hsd->RxXferSize -= 32U;
3673   }
3674 }
3675 
3676 /**
3677   * @brief  Wrap up writing in non-blocking mode.
3678   * @param  hsd: pointer to a SD_HandleTypeDef structure that contains
3679   *              the configuration information.
3680   * @retval None
3681   */
3682 static void SD_Write_IT(SD_HandleTypeDef *hsd)
3683 {
3684   uint32_t count;
3685   uint32_t data;
3686   const uint8_t *tmp;
3687 
3688   tmp = hsd->pTxBuffPtr;
3689 
3690   if (hsd->TxXferSize >= 32U)
3691   {
3692     /* Write data to SDMMC Tx FIFO */
3693     for (count = 0U; count < 8U; count++)
3694     {
3695       data = (uint32_t)(*tmp);
3696       tmp++;
3697       data |= ((uint32_t)(*tmp) << 8U);
3698       tmp++;
3699       data |= ((uint32_t)(*tmp) << 16U);
3700       tmp++;
3701       data |= ((uint32_t)(*tmp) << 24U);
3702       tmp++;
3703       (void)SDMMC_WriteFIFO(hsd->Instance, &data);
3704     }
3705 
3706     hsd->pTxBuffPtr = tmp;
3707     hsd->TxXferSize -= 32U;
3708   }
3709 }
3710 
3711 /**
3712   * @brief  Switches the SD card to High Speed mode.
3713   *         This API must be used after "Transfer State"
3714   * @note   This operation should be followed by the configuration
3715   *         of PLL to have SDMMCCK clock between 25 and 50 MHz
3716   * @param  hsd: SD handle
3717   * @param  SwitchSpeedMode: SD speed mode( SDMMC_SDR12_SWITCH_PATTERN, SDMMC_SDR25_SWITCH_PATTERN)
3718   * @retval SD Card error state
3719   */
3720 uint32_t SD_SwitchSpeed(SD_HandleTypeDef *hsd, uint32_t SwitchSpeedMode)
3721 {
3722   uint32_t errorstate = HAL_SD_ERROR_NONE;
3723   SDMMC_DataInitTypeDef sdmmc_datainitstructure;
3724   uint32_t SD_hs[16]  = {0};
3725   uint32_t count;
3726   uint32_t loop = 0 ;
3727   uint32_t Timeout = HAL_GetTick();
3728 
3729   if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED)
3730   {
3731     /* Standard Speed Card <= 12.5Mhz  */
3732     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3733   }
3734 
3735   if (hsd->SdCard.CardSpeed >= CARD_HIGH_SPEED)
3736   {
3737     /* Initialize the Data control register */
3738     hsd->Instance->DCTRL = 0;
3739     errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3740 
3741     if (errorstate != HAL_SD_ERROR_NONE)
3742     {
3743       return errorstate;
3744     }
3745 
3746     /* Configure the SD DPSM (Data Path State Machine) */
3747     sdmmc_datainitstructure.DataTimeOut   = SDMMC_DATATIMEOUT;
3748     sdmmc_datainitstructure.DataLength    = 64U;
3749     sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ;
3750     sdmmc_datainitstructure.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3751     sdmmc_datainitstructure.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3752     sdmmc_datainitstructure.DPSM          = SDMMC_DPSM_ENABLE;
3753 
3754     (void)SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure);
3755 
3756 
3757     errorstate = SDMMC_CmdSwitch(hsd->Instance, SwitchSpeedMode);
3758     if (errorstate != HAL_SD_ERROR_NONE)
3759     {
3760       return errorstate;
3761     }
3762 
3763     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3764                               SDMMC_FLAG_DATAEND))
3765     {
3766       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3767       {
3768         for (count = 0U; count < 8U; count++)
3769         {
3770           SD_hs[(8U * loop) + count]  = SDMMC_ReadFIFO(hsd->Instance);
3771         }
3772         loop ++;
3773       }
3774 
3775       if ((HAL_GetTick() - Timeout) >=  SDMMC_DATATIMEOUT)
3776       {
3777         hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
3778         hsd->State = HAL_SD_STATE_READY;
3779         return HAL_SD_ERROR_TIMEOUT;
3780       }
3781     }
3782 
3783     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3784     {
3785       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3786 
3787       return errorstate;
3788     }
3789     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3790     {
3791       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3792 
3793       errorstate = SDMMC_ERROR_DATA_CRC_FAIL;
3794 
3795       return errorstate;
3796     }
3797     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3798     {
3799       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3800 
3801       errorstate = SDMMC_ERROR_RX_OVERRUN;
3802 
3803       return errorstate;
3804     }
3805     else
3806     {
3807       /* No error flag set */
3808     }
3809 
3810     /* Clear all the static flags */
3811     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3812 
3813     /* Test if the switch mode HS is ok */
3814     if ((((uint8_t *)SD_hs)[13] & 2U) != 2U)
3815     {
3816       errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE;
3817     }
3818 
3819   }
3820 
3821   return errorstate;
3822 }
3823 
3824 #if (USE_SD_TRANSCEIVER != 0U)
3825 /**
3826   * @brief  Switches the SD card to Ultra High Speed mode.
3827   *         This API must be used after "Transfer State"
3828   * @note   This operation should be followed by the configuration
3829   *         of PLL to have SDMMCCK clock between 50 and 120 MHz
3830   * @param  hsd: SD handle
3831   * @param  UltraHighSpeedMode: SD speed mode( SDMMC_SDR50_SWITCH_PATTERN, SDMMC_SDR104_SWITCH_PATTERN)
3832   * @retval SD Card error state
3833   */
3834 static uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd, uint32_t UltraHighSpeedMode)
3835 {
3836   uint32_t errorstate = HAL_SD_ERROR_NONE;
3837   SDMMC_DataInitTypeDef sdmmc_datainitstructure;
3838   uint32_t SD_hs[16]  = {0};
3839   uint32_t count;
3840   uint32_t loop = 0 ;
3841   uint32_t Timeout = HAL_GetTick();
3842 
3843   if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED)
3844   {
3845     /* Standard Speed Card <= 12.5Mhz  */
3846     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3847   }
3848 
3849   if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED)
3850   {
3851     /* Initialize the Data control register */
3852     hsd->Instance->DCTRL = 0;
3853     errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3854 
3855     if (errorstate != HAL_SD_ERROR_NONE)
3856     {
3857       return errorstate;
3858     }
3859 
3860     /* Configure the SD DPSM (Data Path State Machine) */
3861     sdmmc_datainitstructure.DataTimeOut   = SDMMC_DATATIMEOUT;
3862     sdmmc_datainitstructure.DataLength    = 64U;
3863     sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ;
3864     sdmmc_datainitstructure.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3865     sdmmc_datainitstructure.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3866     sdmmc_datainitstructure.DPSM          = SDMMC_DPSM_ENABLE;
3867 
3868     if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK)
3869     {
3870       return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR);
3871     }
3872 
3873     errorstate = SDMMC_CmdSwitch(hsd->Instance, UltraHighSpeedMode);
3874     if (errorstate != HAL_SD_ERROR_NONE)
3875     {
3876       return errorstate;
3877     }
3878 
3879     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
3880                               SDMMC_FLAG_DATAEND))
3881     {
3882       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
3883       {
3884         for (count = 0U; count < 8U; count++)
3885         {
3886           SD_hs[(8U * loop) + count]  = SDMMC_ReadFIFO(hsd->Instance);
3887         }
3888         loop ++;
3889       }
3890 
3891       if ((HAL_GetTick() - Timeout) >=  SDMMC_DATATIMEOUT)
3892       {
3893         hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
3894         hsd->State = HAL_SD_STATE_READY;
3895         return HAL_SD_ERROR_TIMEOUT;
3896       }
3897     }
3898 
3899     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
3900     {
3901       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
3902 
3903       return errorstate;
3904     }
3905     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
3906     {
3907       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
3908 
3909       errorstate = SDMMC_ERROR_DATA_CRC_FAIL;
3910 
3911       return errorstate;
3912     }
3913     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
3914     {
3915       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
3916 
3917       errorstate = SDMMC_ERROR_RX_OVERRUN;
3918 
3919       return errorstate;
3920     }
3921     else
3922     {
3923       /* No error flag set */
3924     }
3925 
3926     /* Clear all the static flags */
3927     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
3928 
3929     /* Test if the switch mode HS is ok */
3930     if ((((uint8_t *)SD_hs)[13] & 2U) != 2U)
3931     {
3932       errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE;
3933     }
3934     else
3935     {
3936 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
3937       hsd->DriveTransceiver_1_8V_Callback(SET);
3938 #else
3939       HAL_SD_DriveTransceiver_1_8V_Callback(SET);
3940 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
3941 #if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2)
3942       /* Enable DelayBlock Peripheral */
3943       /* SDMMC_FB_CLK tuned feedback clock selected as receive clock, for SDR104 */
3944       MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_1);
3945       if (DelayBlock_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance)) != HAL_OK)
3946       {
3947         return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR);
3948       }
3949 #endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */
3950     }
3951   }
3952 
3953   return errorstate;
3954 }
3955 
3956 /**
3957   * @brief  Switches the SD card to Double Data Rate (DDR) mode.
3958   *         This API must be used after "Transfer State"
3959   * @note   This operation should be followed by the configuration
3960   *         of PLL to have SDMMCCK clock less than 50MHz
3961   * @param  hsd: SD handle
3962   * @retval SD Card error state
3963   */
3964 static uint32_t SD_DDR_Mode(SD_HandleTypeDef *hsd)
3965 {
3966   uint32_t errorstate = HAL_SD_ERROR_NONE;
3967   SDMMC_DataInitTypeDef sdmmc_datainitstructure;
3968   uint32_t SD_hs[16]  = {0};
3969   uint32_t count;
3970   uint32_t loop = 0 ;
3971   uint32_t Timeout = HAL_GetTick();
3972 
3973   if (hsd->SdCard.CardSpeed == CARD_NORMAL_SPEED)
3974   {
3975     /* Standard Speed Card <= 12.5Mhz  */
3976     return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE;
3977   }
3978 
3979   if (hsd->SdCard.CardSpeed == CARD_ULTRA_HIGH_SPEED)
3980   {
3981     /* Initialize the Data control register */
3982     hsd->Instance->DCTRL = 0;
3983     errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U);
3984 
3985     if (errorstate != HAL_SD_ERROR_NONE)
3986     {
3987       return errorstate;
3988     }
3989 
3990     /* Configure the SD DPSM (Data Path State Machine) */
3991     sdmmc_datainitstructure.DataTimeOut   = SDMMC_DATATIMEOUT;
3992     sdmmc_datainitstructure.DataLength    = 64U;
3993     sdmmc_datainitstructure.DataBlockSize = SDMMC_DATABLOCK_SIZE_64B ;
3994     sdmmc_datainitstructure.TransferDir   = SDMMC_TRANSFER_DIR_TO_SDMMC;
3995     sdmmc_datainitstructure.TransferMode  = SDMMC_TRANSFER_MODE_BLOCK;
3996     sdmmc_datainitstructure.DPSM          = SDMMC_DPSM_ENABLE;
3997 
3998     if (SDMMC_ConfigData(hsd->Instance, &sdmmc_datainitstructure) != HAL_OK)
3999     {
4000       return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR);
4001     }
4002 
4003     errorstate = SDMMC_CmdSwitch(hsd->Instance, SDMMC_DDR50_SWITCH_PATTERN);
4004     if (errorstate != HAL_SD_ERROR_NONE)
4005     {
4006       return errorstate;
4007     }
4008 
4009     while (!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DBCKEND |
4010                               SDMMC_FLAG_DATAEND))
4011     {
4012       if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXFIFOHF))
4013       {
4014         for (count = 0U; count < 8U; count++)
4015         {
4016           SD_hs[(8U * loop) + count]  = SDMMC_ReadFIFO(hsd->Instance);
4017         }
4018         loop ++;
4019       }
4020 
4021       if ((HAL_GetTick() - Timeout) >=  SDMMC_DATATIMEOUT)
4022       {
4023         hsd->ErrorCode = HAL_SD_ERROR_TIMEOUT;
4024         hsd->State = HAL_SD_STATE_READY;
4025         return HAL_SD_ERROR_TIMEOUT;
4026       }
4027     }
4028 
4029     if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DTIMEOUT))
4030     {
4031       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DTIMEOUT);
4032 
4033       return errorstate;
4034     }
4035     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_DCRCFAIL))
4036     {
4037       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_DCRCFAIL);
4038 
4039       errorstate = SDMMC_ERROR_DATA_CRC_FAIL;
4040 
4041       return errorstate;
4042     }
4043     else if (__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_RXOVERR))
4044     {
4045       __HAL_SD_CLEAR_FLAG(hsd, SDMMC_FLAG_RXOVERR);
4046 
4047       errorstate = SDMMC_ERROR_RX_OVERRUN;
4048 
4049       return errorstate;
4050     }
4051     else
4052     {
4053       /* No error flag set */
4054     }
4055 
4056     /* Clear all the static flags */
4057     __HAL_SD_CLEAR_FLAG(hsd, SDMMC_STATIC_DATA_FLAGS);
4058 
4059     /* Test if the switch mode  is ok */
4060     if ((((uint8_t *)SD_hs)[13] & 2U) != 2U)
4061     {
4062       errorstate = SDMMC_ERROR_UNSUPPORTED_FEATURE;
4063     }
4064     else
4065     {
4066 #if defined (USE_HAL_SD_REGISTER_CALLBACKS) && (USE_HAL_SD_REGISTER_CALLBACKS == 1U)
4067       hsd->DriveTransceiver_1_8V_Callback(SET);
4068 #else
4069       HAL_SD_DriveTransceiver_1_8V_Callback(SET);
4070 #endif /* USE_HAL_SD_REGISTER_CALLBACKS */
4071 #if defined (DLYB_SDMMC1) || defined (DLYB_SDMMC2)
4072       /* Enable DelayBlock Peripheral */
4073       /* SDMMC_CKin feedback clock selected as receive clock, for DDR50 */
4074       MODIFY_REG(hsd->Instance->CLKCR, SDMMC_CLKCR_SELCLKRX, SDMMC_CLKCR_SELCLKRX_0);
4075       if (DelayBlock_Enable(SD_GET_DLYB_INSTANCE(hsd->Instance)) != HAL_OK)
4076       {
4077         return (HAL_SD_ERROR_GENERAL_UNKNOWN_ERR);
4078       }
4079 #endif /* (DLYB_SDMMC1) || (DLYB_SDMMC2) */
4080     }
4081   }
4082 
4083   return errorstate;
4084 }
4085 
4086 #endif /* USE_SD_TRANSCEIVER */
4087 
4088 /**
4089   * @brief Read DMA Buffer 0 Transfer completed callbacks
4090   * @param hsd: SD handle
4091   * @retval None
4092   */
4093 __weak void HAL_SDEx_Read_DMADoubleBuf0CpltCallback(SD_HandleTypeDef *hsd)
4094 {
4095   /* Prevent unused argument(s) compilation warning */
4096   UNUSED(hsd);
4097 
4098   /* NOTE : This function should not be modified, when the callback is needed,
4099             the HAL_SDEx_Read_DMADoubleBuf0CpltCallback can be implemented in the user file
4100    */
4101 }
4102 
4103 /**
4104   * @brief Read DMA Buffer 1 Transfer completed callbacks
4105   * @param hsd: SD handle
4106   * @retval None
4107   */
4108 __weak void HAL_SDEx_Read_DMADoubleBuf1CpltCallback(SD_HandleTypeDef *hsd)
4109 {
4110   /* Prevent unused argument(s) compilation warning */
4111   UNUSED(hsd);
4112 
4113   /* NOTE : This function should not be modified, when the callback is needed,
4114             the HAL_SDEx_Read_DMADoubleBuf1CpltCallback can be implemented in the user file
4115    */
4116 }
4117 
4118 /**
4119   * @brief Write DMA Buffer 0 Transfer completed callbacks
4120   * @param hsd: SD handle
4121   * @retval None
4122   */
4123 __weak void HAL_SDEx_Write_DMADoubleBuf0CpltCallback(SD_HandleTypeDef *hsd)
4124 {
4125   /* Prevent unused argument(s) compilation warning */
4126   UNUSED(hsd);
4127 
4128   /* NOTE : This function should not be modified, when the callback is needed,
4129             the HAL_SDEx_Write_DMADoubleBuf0CpltCallback can be implemented in the user file
4130    */
4131 }
4132 
4133 /**
4134   * @brief Write DMA Buffer 1 Transfer completed callbacks
4135   * @param hsd: SD handle
4136   * @retval None
4137   */
4138 __weak void HAL_SDEx_Write_DMADoubleBuf1CpltCallback(SD_HandleTypeDef *hsd)
4139 {
4140   /* Prevent unused argument(s) compilation warning */
4141   UNUSED(hsd);
4142 
4143   /* NOTE : This function should not be modified, when the callback is needed,
4144             the HAL_SDEx_Write_DMADoubleBuf1CpltCallback can be implemented in the user file
4145    */
4146 }
4147 
4148 
4149 /**
4150   * @}
4151   */
4152 
4153 #endif /* HAL_SD_MODULE_ENABLED */
4154 
4155 /**
4156   * @}
4157   */
4158 
4159 /**
4160   * @}
4161   */