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