1 /**
2   ******************************************************************************
3   * @file    stm32l1xx_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 (SDIO 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 SDIO memories which uses the HAL
27     SDIO driver functions to interface with SD and uSD cards devices.
28     It is used as follows:
29 
30     (#)Initialize the SDIO low level resources by implement the HAL_SD_MspInit() API:
31         (##) Enable the SDIO interface clock using __HAL_RCC_SDIO_CLK_ENABLE();
32         (##) SDIO pins configuration for SD card
33             (+++) Enable the clock for the SDIO GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE();
34             (+++) Configure these SDIO pins as alternate function pull-up using HAL_GPIO_Init()
35                   and according to your pin assignment;
36         (##) DMA Configuration if you need to use DMA process (HAL_SD_ReadBlocks_DMA()
37              and HAL_SD_WriteBlocks_DMA() APIs).
38             (+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE();
39             (+++) Configure the DMA using the function HAL_DMA_Init() with predeclared and filled.
40         (##) NVIC configuration if you need to use interrupt process when using DMA transfer.
41             (+++) Configure the SDIO and DMA interrupt priorities using functions
42                   HAL_NVIC_SetPriority(); DMA priority is superior to SDIO's priority
43             (+++) Enable the NVIC DMA and SDIO IRQs using function HAL_NVIC_EnableIRQ()
44             (+++) SDIO interrupts are managed using the macros __HAL_SD_SDIO_ENABLE_IT()
45                   and __HAL_SD_SDIO_DISABLE_IT() inside the communication process.
46             (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_SDIO_GET_IT()
47                   and __HAL_SD_SDIO_CLEAR_IT()
48     (#) At this stage, you can perform SD read/write/erase operations after SD card initialization
49 
50 
51   *** SD Card Initialization and configuration ***
52   ================================================
53   [..]
54     To initialize the SD Card, use the HAL_SD_Init() function.  It Initializes
55     the SD Card and put it into Standby State (Ready for data transfer).
56     This function provide the following operations:
57 
58     (#) Apply the SD Card initialization process at 400KHz and check the SD Card
59         type (Standard Capacity or High Capacity). You can change or adapt this
60         frequency by adjusting the "ClockDiv" field.
61         The SD Card frequency (SDIO_CK) is computed as follows:
62 
63            SDIO_CK = SDIOCLK / (ClockDiv + 2)
64 
65         In initialization mode and according to the SD Card standard,
66         make sure that the SDIO_CK frequency doesn't exceed 400KHz.
67 
68     (#) Get the SD CID and CSD data. All these information are managed by the SDCardInfo
69         structure. This structure provide also ready computed SD Card capacity
70         and Block size.
71 
72         -@- These information are stored in SD handle structure in case of future use.
73 
74     (#) Configure the SD Card Data transfer frequency. By Default, the card transfer
75         frequency is set to 48MHz / (SDIO_TRANSFER_CLK_DIV + 2) = 8MHz. You can change or adapt this frequency by adjusting
76         the "ClockDiv" field.
77         The SD Card frequency (SDIO_CK) is computed as follows:
78 
79            SDIO_CK = SDIOCLK / (ClockDiv + 2)
80 
81         In transfer mode and according to the SD Card standard, make sure that the
82         SDIO_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch.
83         To be able to use a frequency higher than 24MHz, you should use the SDIO
84         peripheral in bypass mode. Refer to the corresponding reference manual
85         for more details.
86 
87     (#) Select the corresponding SD Card according to the address read with the step 2.
88 
89     (#) Configure the SD Card in wide bus mode: 4-bits data.
90 
91   *** SD Card Read operation ***
92   ==============================
93   [..]
94     (+) You can read from SD card in polling mode by using function HAL_SD_ReadBlocks().
95         This function support only 512-bytes block length (the block size should be
96         chosen as 512 bytes).
97         You can choose either one block read operation or multiple block read operation
98         by adjusting the "NumberOfBlocks" parameter.
99 
100     (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA().
101         This function support only 512-bytes block length (the block size should be
102         chosen as 512 bytes).
103         You can choose either one block read operation or multiple block read operation
104         by adjusting the "NumberOfBlocks" parameter.
105         After this, you have to call the function HAL_SD_CheckReadOperation(), to insure
106         that the read transfer is done correctly in both DMA and SD sides.
107 
108   *** SD Card Write operation ***
109   ===============================
110   [..]
111     (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks().
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 
117     (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA().
118         This function support only 512-bytes block length (the block size should be
119         chosen as 512 byte).
120         You can choose either one block read operation or multiple block read operation
121         by adjusting the "NumberOfBlocks" parameter.
122         After this, you have to call the function HAL_SD_CheckWriteOperation(), to insure
123         that the write transfer is done correctly in both DMA and SD sides.
124 
125   *** SD card status ***
126   ======================
127   [..]
128     (+) At any time, you can check the SD Card status and get the SD card state
129         by using the HAL_SD_GetStatus() function. This function checks first if the
130         SD card is still connected and then get the internal SD Card transfer state.
131     (+) You can also get the SD card SD Status register by using the HAL_SD_SendSDStatus()
132         function.
133 
134   *** SD HAL driver macros list ***
135   ==================================
136   [..]
137     Below the list of most used macros in SD HAL driver.
138 
139     (+) __HAL_SD_SDIO_ENABLE : Enable the SD device
140     (+) __HAL_SD_SDIO_DISABLE : Disable the SD device
141     (+) __HAL_SD_SDIO_DMA_ENABLE: Enable the SDIO DMA transfer
142     (+) __HAL_SD_SDIO_DMA_DISABLE: Disable the SDIO DMA transfer
143     (+) __HAL_SD_SDIO_ENABLE_IT: Enable the SD device interrupt
144     (+) __HAL_SD_SDIO_DISABLE_IT: Disable the SD device interrupt
145     (+) __HAL_SD_SDIO_GET_FLAG:Check whether the specified SD flag is set or not
146     (+) __HAL_SD_SDIO_CLEAR_FLAG: Clear the SD's pending flags
147 
148     (@) You can refer to the SD HAL driver header file for more useful macros
149 
150   @endverbatim
151   ******************************************************************************
152   * @attention
153   *
154   * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
155   *
156   * Redistribution and use in source and binary forms, with or without modification,
157   * are permitted provided that the following conditions are met:
158   *   1. Redistributions of source code must retain the above copyright notice,
159   *      this list of conditions and the following disclaimer.
160   *   2. Redistributions in binary form must reproduce the above copyright notice,
161   *      this list of conditions and the following disclaimer in the documentation
162   *      and/or other materials provided with the distribution.
163   *   3. Neither the name of STMicroelectronics nor the names of its contributors
164   *      may be used to endorse or promote products derived from this software
165   *      without specific prior written permission.
166   *
167   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
168   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
169   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
170   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
171   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
172   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
173   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
174   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
175   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
176   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
177   *
178   ******************************************************************************
179   */
180 
181 /* Includes ------------------------------------------------------------------*/
182 #include "stm32l1xx_hal.h"
183 
184 #ifdef HAL_SD_MODULE_ENABLED
185 
186 /** @addtogroup STM32L1xx_HAL_Driver
187   * @{
188   */
189 
190 /** @addtogroup SD
191   * @{
192   */
193 
194 #if defined(STM32L151xD) || defined(STM32L152xD) || defined(STM32L162xD)
195 
196 /* Private typedef -----------------------------------------------------------*/
197 /* Private define ------------------------------------------------------------*/
198 /** @addtogroup SD_Private_Defines
199   * @{
200   */
201 /**
202   * @brief  SDIO Data block size
203   */
204 #define DATA_BLOCK_SIZE                  ((uint32_t)(9 << 4))
205 /**
206   * @brief  SDIO Static flags, Timeout, FIFO Address
207   */
208 #define SDIO_STATIC_FLAGS               ((uint32_t)(SDIO_FLAG_CCRCFAIL | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_CTIMEOUT |\
209                                                     SDIO_FLAG_DTIMEOUT | SDIO_FLAG_TXUNDERR | SDIO_FLAG_RXOVERR  |\
210                                                     SDIO_FLAG_CMDREND  | SDIO_FLAG_CMDSENT  | SDIO_FLAG_DATAEND  |\
211                                                     SDIO_FLAG_DBCKEND))
212 
213 #define SDIO_CMD0TIMEOUT                (0x00010000U)
214 
215 /**
216   * @brief  Mask for errors Card Status R1 (OCR Register)
217   */
218 #define SD_OCR_ADDR_OUT_OF_RANGE        (0x80000000U)
219 #define SD_OCR_ADDR_MISALIGNED          (0x40000000U)
220 #define SD_OCR_BLOCK_LEN_ERR            (0x20000000U)
221 #define SD_OCR_ERASE_SEQ_ERR            (0x10000000U)
222 #define SD_OCR_BAD_ERASE_PARAM          (0x08000000U)
223 #define SD_OCR_WRITE_PROT_VIOLATION     (0x04000000U)
224 #define SD_OCR_LOCK_UNLOCK_FAILED       (0x01000000U)
225 #define SD_OCR_COM_CRC_FAILED           (0x00800000U)
226 #define SD_OCR_ILLEGAL_CMD              (0x00400000U)
227 #define SD_OCR_CARD_ECC_FAILED          (0x00200000U)
228 #define SD_OCR_CC_ERROR                 (0x00100000U)
229 #define SD_OCR_GENERAL_UNKNOWN_ERROR    (0x00080000U)
230 #define SD_OCR_STREAM_READ_UNDERRUN     (0x00040000U)
231 #define SD_OCR_STREAM_WRITE_OVERRUN     (0x00020000U)
232 #define SD_OCR_CID_CSD_OVERWRITE        (0x00010000U)
233 #define SD_OCR_WP_ERASE_SKIP            (0x00008000U)
234 #define SD_OCR_CARD_ECC_DISABLED        (0x00004000U)
235 #define SD_OCR_ERASE_RESET              (0x00002000U)
236 #define SD_OCR_AKE_SEQ_ERROR            (0x00000008U)
237 #define SD_OCR_ERRORBITS                (0xFDFFE008U)
238 
239 /**
240   * @brief  Masks for R6 Response
241   */
242 #define SD_R6_GENERAL_UNKNOWN_ERROR     (0x00002000U)
243 #define SD_R6_ILLEGAL_CMD               (0x00004000U)
244 #define SD_R6_COM_CRC_FAILED            (0x00008000U)
245 
246 #define SD_VOLTAGE_WINDOW_SD            (0x80100000U)
247 #define SD_HIGH_CAPACITY                (0x40000000U)
248 #define SD_STD_CAPACITY                 (0x00000000U)
249 #define SD_CHECK_PATTERN                (0x000001AAU)
250 
251 #define SD_MAX_VOLT_TRIAL               (0x0000FFFFU)
252 #define SD_ALLZERO                      (0x00000000U)
253 
254 #define SD_WIDE_BUS_SUPPORT             (0x00040000U)
255 #define SD_SINGLE_BUS_SUPPORT           (0x00010000U)
256 #define SD_CARD_LOCKED                  (0x02000000U)
257 
258 #define SD_DATATIMEOUT                  (0xFFFFFFFFU)
259 #define SD_0TO7BITS                     (0x000000FFU)
260 #define SD_8TO15BITS                    (0x0000FF00U)
261 #define SD_16TO23BITS                   (0x00FF0000U)
262 #define SD_24TO31BITS                   (0xFF000000U)
263 #define SD_MAX_DATA_LENGTH              (0x01FFFFFFU)
264 
265 #define SD_HALFFIFO                     (0x00000008U)
266 #define SD_HALFFIFOBYTES                (0x00000020U)
267 
268 /**
269   * @brief  Command Class Supported
270   */
271 #define SD_CCCC_LOCK_UNLOCK             (0x00000080U)
272 #define SD_CCCC_WRITE_PROT              (0x00000040U)
273 #define SD_CCCC_ERASE                   (0x00000020U)
274 
275 /**
276   * @brief  Following commands are SD Card Specific commands.
277   *         SDIO_APP_CMD should be sent before sending these commands.
278   */
279 #define SD_SDIO_SEND_IF_COND            ((uint32_t)SD_CMD_HS_SEND_EXT_CSD)
280 
281 /**
282   * @}
283   */
284 
285 /* Private macro -------------------------------------------------------------*/
286 /* Private variables ---------------------------------------------------------*/
287 /* Private function prototypes -----------------------------------------------*/
288 /** @addtogroup SD_Private_Functions_Prototypes
289   * @{
290   */
291 static HAL_SD_ErrorTypedef SD_Initialize_Cards(SD_HandleTypeDef *hsd);
292 static HAL_SD_ErrorTypedef SD_Select_Deselect(SD_HandleTypeDef *hsd, uint64_t addr);
293 static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd);
294 static HAL_SD_ErrorTypedef SD_PowerOFF(SD_HandleTypeDef *hsd);
295 static HAL_SD_ErrorTypedef SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus);
296 static HAL_SD_CardStateTypedef SD_GetState(SD_HandleTypeDef *hsd);
297 static HAL_SD_ErrorTypedef SD_IsCardProgramming(SD_HandleTypeDef *hsd, uint8_t *pStatus);
298 static HAL_SD_ErrorTypedef SD_CmdError(SD_HandleTypeDef *hsd);
299 static HAL_SD_ErrorTypedef SD_CmdResp1Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD);
300 static HAL_SD_ErrorTypedef SD_CmdResp7Error(SD_HandleTypeDef *hsd);
301 static HAL_SD_ErrorTypedef SD_CmdResp3Error(SD_HandleTypeDef *hsd);
302 static HAL_SD_ErrorTypedef SD_CmdResp2Error(SD_HandleTypeDef *hsd);
303 static HAL_SD_ErrorTypedef SD_CmdResp6Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD, uint16_t *pRCA);
304 static HAL_SD_ErrorTypedef SD_WideBus_Enable(SD_HandleTypeDef *hsd);
305 static HAL_SD_ErrorTypedef SD_WideBus_Disable(SD_HandleTypeDef *hsd);
306 static HAL_SD_ErrorTypedef SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR);
307 static void SD_DMA_RxCplt(DMA_HandleTypeDef *hdma);
308 static void SD_DMA_RxError(DMA_HandleTypeDef *hdma);
309 static void SD_DMA_TxCplt(DMA_HandleTypeDef *hdma);
310 static void SD_DMA_TxError(DMA_HandleTypeDef *hdma);
311 /**
312   * @}
313   */
314 /* Exported functions --------------------------------------------------------*/
315 /** @addtogroup SD_Exported_Functions
316   * @{
317   */
318 
319 /** @addtogroup SD_Exported_Functions_Group1
320  *  @brief   Initialization and de-initialization functions
321  *
322 @verbatim
323   ==============================================================================
324           ##### Initialization and de-initialization functions #####
325   ==============================================================================
326   [..]
327     This section provides functions allowing to initialize/de-initialize the SD
328     card device to be ready for use.
329 
330 
331 @endverbatim
332   * @{
333   */
334 
335 /**
336   * @brief  Initializes the SD card according to the specified parameters in the
337             SD_HandleTypeDef and create the associated handle.
338   * @param  hsd: SD handle
339   * @param  SDCardInfo: HAL_SD_CardInfoTypedef structure for SD card information
340   * @retval HAL SD error state
341   */
HAL_SD_Init(SD_HandleTypeDef * hsd,HAL_SD_CardInfoTypedef * SDCardInfo)342 HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo)
343 {
344   __IO HAL_SD_ErrorTypedef errorstate = SD_OK;
345   SD_InitTypeDef tmpinit;
346 
347   /* Initialize the low level hardware (MSP) */
348   HAL_SD_MspInit(hsd);
349 
350   /* Default SDIO peripheral configuration for SD card initialization */
351   tmpinit.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
352   tmpinit.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
353   tmpinit.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_DISABLE;
354   tmpinit.BusWide             = SDIO_BUS_WIDE_1B;
355   tmpinit.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
356   tmpinit.ClockDiv            = SDIO_INIT_CLK_DIV;
357 
358   /* Initialize SDIO peripheral interface with default configuration */
359   SDIO_Init(hsd->Instance, tmpinit);
360 
361   /* Identify card operating voltage */
362   errorstate = SD_PowerON(hsd);
363 
364   if(errorstate != SD_OK)
365   {
366     return errorstate;
367   }
368 
369   /* Initialize the present SDIO card(s) and put them in idle state */
370   errorstate = SD_Initialize_Cards(hsd);
371 
372   if (errorstate != SD_OK)
373   {
374     return errorstate;
375   }
376 
377   /* Read CSD/CID MSD registers */
378   errorstate = HAL_SD_Get_CardInfo(hsd, SDCardInfo);
379 
380   if (errorstate == SD_OK)
381   {
382     /* Select the Card */
383     errorstate = SD_Select_Deselect(hsd, (uint32_t)(((uint32_t)SDCardInfo->RCA) << 16));
384   }
385 
386   /* Configure SDIO peripheral interface */
387   SDIO_Init(hsd->Instance, hsd->Init);
388 
389   return errorstate;
390 }
391 
392 /**
393   * @brief  De-Initializes the SD card.
394   * @param  hsd: SD handle
395   * @retval HAL status
396   */
HAL_SD_DeInit(SD_HandleTypeDef * hsd)397 HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd)
398 {
399 
400   /* Set SD power state to off */
401   SD_PowerOFF(hsd);
402 
403   /* De-Initialize the MSP layer */
404   HAL_SD_MspDeInit(hsd);
405 
406   return HAL_OK;
407 }
408 
409 
410 /**
411   * @brief  Initializes the SD MSP.
412   * @param  hsd: SD handle
413   * @retval None
414   */
HAL_SD_MspInit(SD_HandleTypeDef * hsd)415 __weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
416 {
417   /* Prevent unused argument(s) compilation warning */
418   UNUSED(hsd);
419 
420   /* NOTE : This function Should not be modified, when the callback is needed,
421             the HAL_SD_MspInit could be implemented in the user file
422    */
423 }
424 
425 /**
426   * @brief  De-Initialize SD MSP.
427   * @param  hsd: SD handle
428   * @retval None
429   */
HAL_SD_MspDeInit(SD_HandleTypeDef * hsd)430 __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd)
431 {
432   /* Prevent unused argument(s) compilation warning */
433   UNUSED(hsd);
434 
435   /* NOTE : This function Should not be modified, when the callback is needed,
436             the HAL_SD_MspDeInit could be implemented in the user file
437    */
438 }
439 
440 /**
441   * @}
442   */
443 
444 /** @addtogroup SD_Exported_Functions_Group2
445  *  @brief   Data transfer functions
446  *
447 @verbatim
448   ==============================================================================
449                         ##### IO operation functions #####
450   ==============================================================================
451   [..]
452     This subsection provides a set of functions allowing to manage the data
453     transfer from/to SD card.
454 
455 @endverbatim
456   * @{
457   */
458 
459 /**
460   * @brief  Reads block(s) from a specified address in a card. The Data transfer
461   *         is managed by polling mode.
462   * @param  hsd: SD handle
463   * @param  pReadBuffer: pointer to the buffer that will contain the received data
464   * @param  ReadAddr: Address from where data is to be read
465   * @param  BlockSize: SD card Data block size
466   * @note   BlockSize must be 512 bytes.
467   * @param  NumberOfBlocks: Number of SD blocks to read
468   * @retval SD Card error state
469   */
HAL_SD_ReadBlocks(SD_HandleTypeDef * hsd,uint32_t * pReadBuffer,uint64_t ReadAddr,uint32_t BlockSize,uint32_t NumberOfBlocks)470 HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
471 {
472   SDIO_CmdInitTypeDef  sdio_cmdinitstructure;
473   SDIO_DataInitTypeDef sdio_datainitstructure;
474   HAL_SD_ErrorTypedef errorstate = SD_OK;
475   uint32_t count = 0, *tempbuff = (uint32_t *)pReadBuffer;
476 
477   /* Initialize data control register */
478   hsd->Instance->DCTRL = 0;
479 
480   if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
481   {
482     BlockSize = 512;
483     ReadAddr /= 512;
484   }
485 
486   /* Set Block Size for Card */
487   sdio_cmdinitstructure.Argument         = (uint32_t) BlockSize;
488   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
489   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
490   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
491   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
492   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
493 
494   /* Check for error conditions */
495   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
496 
497   if (errorstate != SD_OK)
498   {
499     return errorstate;
500   }
501 
502   /* Configure the SD DPSM (Data Path State Machine) */
503   sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
504   sdio_datainitstructure.DataLength    = NumberOfBlocks * BlockSize;
505   sdio_datainitstructure.DataBlockSize = DATA_BLOCK_SIZE;
506   sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
507   sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
508   sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
509   SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
510 
511   if(NumberOfBlocks > 1)
512   {
513     /* Send CMD18 READ_MULT_BLOCK with argument data address */
514     sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_MULT_BLOCK;
515   }
516   else
517   {
518     /* Send CMD17 READ_SINGLE_BLOCK */
519     sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_SINGLE_BLOCK;
520   }
521 
522   sdio_cmdinitstructure.Argument         = (uint32_t)ReadAddr;
523   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
524 
525   /* Read block(s) in polling mode */
526   if(NumberOfBlocks > 1)
527   {
528     /* Check for error conditions */
529     errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_MULT_BLOCK);
530 
531     if (errorstate != SD_OK)
532     {
533       return errorstate;
534     }
535 
536     /* Poll on SDIO flags */
537     while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR))
538     {
539       if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
540       {
541         /* Read data from SDIO Rx FIFO */
542         for (count = 0; count < 8; count++)
543         {
544           *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance);
545         }
546 
547         tempbuff += 8;
548       }
549     }
550   }
551   else
552   {
553     /* Check for error conditions */
554     errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_SINGLE_BLOCK);
555 
556     if (errorstate != SD_OK)
557     {
558       return errorstate;
559     }
560 
561     /* In case of single block transfer, no need of stop transfer at all */
562     while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
563     {
564       if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
565       {
566         /* Read data from SDIO Rx FIFO */
567         for (count = 0; count < 8; count++)
568         {
569           *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance);
570         }
571 
572         tempbuff += 8;
573       }
574     }
575   }
576 
577   /* Send stop transmission command in case of multiblock read */
578   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1))
579   {
580     if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) ||\
581       (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
582         (hsd->CardType == HIGH_CAPACITY_SD_CARD))
583     {
584       /* Send stop transmission command */
585       errorstate = HAL_SD_StopTransfer(hsd);
586     }
587   }
588 
589   /* Get error state */
590   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
591   {
592     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
593 
594     errorstate = SD_DATA_TIMEOUT;
595 
596     return errorstate;
597   }
598   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
599   {
600     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
601 
602     errorstate = SD_DATA_CRC_FAIL;
603 
604     return errorstate;
605   }
606   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
607   {
608     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
609 
610     errorstate = SD_RX_OVERRUN;
611 
612     return errorstate;
613   }
614   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
615   {
616     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
617 
618     errorstate = SD_START_BIT_ERR;
619 
620     return errorstate;
621   }
622   else
623   {
624     /* No error flag set */
625   }
626 
627   count = SD_DATATIMEOUT;
628 
629   /* Empty FIFO if there is still any data */
630   while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0))
631   {
632     *tempbuff = SDIO_ReadFIFO(hsd->Instance);
633     tempbuff++;
634     count--;
635   }
636 
637   /* Clear all the static flags */
638   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
639 
640   return errorstate;
641 }
642 
643 /**
644   * @brief  Allows to write block(s) to a specified address in a card. The Data
645   *         transfer is managed by polling mode.
646   * @param  hsd: SD handle
647   * @param  pWriteBuffer: pointer to the buffer that will contain the data to transmit
648   * @param  WriteAddr: Address from where data is to be written
649   * @param  BlockSize: SD card Data block size
650   * @note   BlockSize must be 512 bytes.
651   * @param  NumberOfBlocks: Number of SD blocks to write
652   * @retval SD Card error state
653   */
HAL_SD_WriteBlocks(SD_HandleTypeDef * hsd,uint32_t * pWriteBuffer,uint64_t WriteAddr,uint32_t BlockSize,uint32_t NumberOfBlocks)654 HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
655 {
656   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
657   SDIO_DataInitTypeDef sdio_datainitstructure;
658   HAL_SD_ErrorTypedef errorstate = SD_OK;
659   uint32_t totalnumberofbytes = 0, bytestransferred = 0, count = 0, restwords = 0;
660   uint32_t *tempbuff = (uint32_t *)pWriteBuffer;
661   uint8_t cardstate  = 0;
662 
663   /* Initialize data control register */
664   hsd->Instance->DCTRL = 0;
665 
666   if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
667   {
668     BlockSize = 512;
669     WriteAddr /= 512;
670   }
671 
672   /* Set Block Size for Card */
673   sdio_cmdinitstructure.Argument         = (uint32_t)BlockSize;
674   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
675   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
676   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
677   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
678   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
679 
680   /* Check for error conditions */
681   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
682 
683   if (errorstate != SD_OK)
684   {
685     return errorstate;
686   }
687 
688   if(NumberOfBlocks > 1)
689   {
690     /* Send CMD25 WRITE_MULT_BLOCK with argument data address */
691     sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_MULT_BLOCK;
692   }
693   else
694   {
695     /* Send CMD24 WRITE_SINGLE_BLOCK */
696     sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK;
697   }
698 
699   sdio_cmdinitstructure.Argument         = (uint32_t)WriteAddr;
700   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
701 
702   /* Check for error conditions */
703   if(NumberOfBlocks > 1)
704   {
705     errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_MULT_BLOCK);
706   }
707   else
708   {
709     errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_SINGLE_BLOCK);
710   }
711 
712   if (errorstate != SD_OK)
713   {
714     return errorstate;
715   }
716 
717   /* Set total number of bytes to write */
718   totalnumberofbytes = NumberOfBlocks * BlockSize;
719 
720   /* Configure the SD DPSM (Data Path State Machine) */
721   sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
722   sdio_datainitstructure.DataLength    = NumberOfBlocks * BlockSize;
723   sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
724   sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_CARD;
725   sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
726   sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
727   SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
728 
729   /* Write block(s) in polling mode */
730   if(NumberOfBlocks > 1)
731   {
732     while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR))
733     {
734       if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE))
735       {
736         if ((totalnumberofbytes - bytestransferred) < 32)
737         {
738           restwords = ((totalnumberofbytes - bytestransferred) % 4 == 0) ? ((totalnumberofbytes - bytestransferred) / 4) : (( totalnumberofbytes -  bytestransferred) / 4 + 1);
739 
740           /* Write data to SDIO Tx FIFO */
741           for (count = 0; count < restwords; count++)
742           {
743             SDIO_WriteFIFO(hsd->Instance, tempbuff);
744             tempbuff++;
745             bytestransferred += 4;
746           }
747         }
748         else
749         {
750           /* Write data to SDIO Tx FIFO */
751           for (count = 0; count < 8; count++)
752           {
753             SDIO_WriteFIFO(hsd->Instance, (tempbuff + count));
754           }
755 
756           tempbuff += 8;
757           bytestransferred += 32;
758         }
759       }
760     }
761   }
762   else
763   {
764     /* In case of single data block transfer no need of stop command at all */
765     while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
766     {
767       if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE))
768       {
769         if ((totalnumberofbytes - bytestransferred) < 32)
770         {
771           restwords = ((totalnumberofbytes - bytestransferred) % 4 == 0) ? ((totalnumberofbytes - bytestransferred) / 4) : (( totalnumberofbytes -  bytestransferred) / 4 + 1);
772 
773           /* Write data to SDIO Tx FIFO */
774           for (count = 0; count < restwords; count++)
775           {
776             SDIO_WriteFIFO(hsd->Instance, tempbuff);
777             tempbuff++;
778             bytestransferred += 4;
779           }
780         }
781         else
782         {
783           /* Write data to SDIO Tx FIFO */
784           for (count = 0; count < 8; count++)
785           {
786             SDIO_WriteFIFO(hsd->Instance, (tempbuff + count));
787           }
788 
789           tempbuff += 8;
790           bytestransferred += 32;
791         }
792       }
793     }
794   }
795 
796   /* Send stop transmission command in case of multiblock write */
797   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1))
798   {
799     if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
800       (hsd->CardType == HIGH_CAPACITY_SD_CARD))
801     {
802       /* Send stop transmission command */
803       errorstate = HAL_SD_StopTransfer(hsd);
804     }
805   }
806 
807   /* Get error state */
808   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
809   {
810     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
811 
812     errorstate = SD_DATA_TIMEOUT;
813 
814     return errorstate;
815   }
816   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
817   {
818     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
819 
820     errorstate = SD_DATA_CRC_FAIL;
821 
822     return errorstate;
823   }
824   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR))
825   {
826     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_TXUNDERR);
827 
828     errorstate = SD_TX_UNDERRUN;
829 
830     return errorstate;
831   }
832   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
833   {
834     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
835 
836     errorstate = SD_START_BIT_ERR;
837 
838     return errorstate;
839   }
840   else
841   {
842     /* No error flag set */
843   }
844 
845   /* Clear all the static flags */
846   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
847 
848   /* Wait till the card is in programming state */
849   errorstate = SD_IsCardProgramming(hsd, &cardstate);
850 
851   while ((errorstate == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING)))
852   {
853     errorstate = SD_IsCardProgramming(hsd, &cardstate);
854   }
855 
856   return errorstate;
857 }
858 
859 /**
860   * @brief  Reads block(s) from a specified address in a card. The Data transfer
861   *         is managed by DMA mode.
862   * @note   This API should be followed by the function HAL_SD_CheckReadOperation()
863   *         to check the completion of the read process
864   * @param  hsd: SD handle
865   * @param  pReadBuffer: Pointer to the buffer that will contain the received data
866   * @param  ReadAddr: Address from where data is to be read
867   * @param  BlockSize: SD card Data block size
868   * @note   BlockSize must be 512 bytes.
869   * @param  NumberOfBlocks: Number of blocks to read.
870   * @retval SD Card error state
871   */
HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef * hsd,uint32_t * pReadBuffer,uint64_t ReadAddr,uint32_t BlockSize,uint32_t NumberOfBlocks)872 HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
873 {
874   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
875   SDIO_DataInitTypeDef sdio_datainitstructure;
876   HAL_SD_ErrorTypedef errorstate = SD_OK;
877 
878   /* Initialize data control register */
879   hsd->Instance->DCTRL = 0;
880 
881   /* Initialize handle flags */
882   hsd->SdTransferCplt  = 0;
883   hsd->DmaTransferCplt = 0;
884   hsd->SdTransferErr   = SD_OK;
885 
886   /* Initialize SD Read operation */
887   if(NumberOfBlocks > 1)
888   {
889     hsd->SdOperation = SD_READ_MULTIPLE_BLOCK;
890   }
891   else
892   {
893     hsd->SdOperation = SD_READ_SINGLE_BLOCK;
894   }
895 
896   /* Enable transfer interrupts */
897   __HAL_SD_SDIO_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL |\
898                                 SDIO_IT_DTIMEOUT |\
899                                 SDIO_IT_DATAEND  |\
900                                 SDIO_IT_RXOVERR  |\
901                                 SDIO_IT_STBITERR));
902 
903   /* Enable SDIO DMA transfer */
904   __HAL_SD_SDIO_DMA_ENABLE();
905 
906   /* Configure DMA user callbacks */
907   hsd->hdmarx->XferCpltCallback  = SD_DMA_RxCplt;
908   hsd->hdmarx->XferErrorCallback = SD_DMA_RxError;
909 
910   /* Enable the DMA Stream */
911   HAL_DMA_Start_IT(hsd->hdmarx, (uint32_t)&hsd->Instance->FIFO, (uint32_t)pReadBuffer, (uint32_t)(BlockSize * NumberOfBlocks)/4);
912 
913   if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
914   {
915     BlockSize = 512;
916     ReadAddr /= 512;
917   }
918 
919   /* Set Block Size for Card */
920   sdio_cmdinitstructure.Argument         = (uint32_t)BlockSize;
921   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
922   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
923   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
924   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
925   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
926 
927   /* Check for error conditions */
928   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
929 
930   if (errorstate != SD_OK)
931   {
932     return errorstate;
933   }
934 
935   /* Configure the SD DPSM (Data Path State Machine) */
936   sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
937   sdio_datainitstructure.DataLength    = BlockSize * NumberOfBlocks;
938   sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
939   sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
940   sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
941   sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
942   SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
943 
944   /* Check number of blocks command */
945   if(NumberOfBlocks > 1)
946   {
947     /* Send CMD18 READ_MULT_BLOCK with argument data address */
948     sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_MULT_BLOCK;
949   }
950   else
951   {
952     /* Send CMD17 READ_SINGLE_BLOCK */
953     sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_SINGLE_BLOCK;
954   }
955 
956   sdio_cmdinitstructure.Argument = (uint32_t)ReadAddr;
957   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
958 
959   /* Check for error conditions */
960   if(NumberOfBlocks > 1)
961   {
962     errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_MULT_BLOCK);
963   }
964   else
965   {
966     errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_SINGLE_BLOCK);
967   }
968 
969   /* Update the SD transfer error in SD handle */
970   hsd->SdTransferErr = errorstate;
971 
972   return errorstate;
973 }
974 
975 
976 /**
977   * @brief  Writes block(s) to a specified address in a card. The Data transfer
978   *         is managed by DMA mode.
979   * @note   This API should be followed by the function HAL_SD_CheckWriteOperation()
980   *         to check the completion of the write process (by SD current status polling).
981   * @param  hsd: SD handle
982   * @param  pWriteBuffer: pointer to the buffer that will contain the data to transmit
983   * @param  WriteAddr: Address from where data is to be read
984   * @param  BlockSize: the SD card Data block size
985   * @note   BlockSize must be 512 bytes.
986   * @param  NumberOfBlocks: Number of blocks to write
987   * @retval SD Card error state
988   */
HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef * hsd,uint32_t * pWriteBuffer,uint64_t WriteAddr,uint32_t BlockSize,uint32_t NumberOfBlocks)989 HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks)
990 {
991   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
992   SDIO_DataInitTypeDef sdio_datainitstructure;
993   HAL_SD_ErrorTypedef errorstate = SD_OK;
994 
995   /* Initialize data control register */
996   hsd->Instance->DCTRL = 0;
997 
998   /* Initialize handle flags */
999   hsd->SdTransferCplt  = 0;
1000   hsd->DmaTransferCplt = 0;
1001   hsd->SdTransferErr   = SD_OK;
1002 
1003   /* Initialize SD Write operation */
1004   if(NumberOfBlocks > 1)
1005   {
1006     hsd->SdOperation = SD_WRITE_MULTIPLE_BLOCK;
1007   }
1008   else
1009   {
1010     hsd->SdOperation = SD_WRITE_SINGLE_BLOCK;
1011   }
1012 
1013   /* Enable transfer interrupts */
1014   __HAL_SD_SDIO_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL |\
1015                                 SDIO_IT_DTIMEOUT |\
1016                                 SDIO_IT_DATAEND  |\
1017                                 SDIO_IT_TXUNDERR |\
1018                                 SDIO_IT_STBITERR));
1019 
1020   /* Configure DMA user callbacks */
1021   hsd->hdmatx->XferCpltCallback  = SD_DMA_TxCplt;
1022   hsd->hdmatx->XferErrorCallback = SD_DMA_TxError;
1023 
1024   /* Enable the DMA Stream */
1025   HAL_DMA_Start_IT(hsd->hdmatx, (uint32_t)pWriteBuffer, (uint32_t)&hsd->Instance->FIFO, (uint32_t)(BlockSize * NumberOfBlocks)/4);
1026 
1027   /* Enable SDIO DMA transfer */
1028   __HAL_SD_SDIO_DMA_ENABLE();
1029 
1030   if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
1031   {
1032     BlockSize = 512;
1033     WriteAddr /= 512;
1034   }
1035 
1036   /* Set Block Size for Card */
1037   sdio_cmdinitstructure.Argument         = (uint32_t)BlockSize;
1038   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
1039   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
1040   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
1041   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
1042   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1043 
1044   /* Check for error conditions */
1045   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
1046 
1047   if (errorstate != SD_OK)
1048   {
1049     return errorstate;
1050   }
1051 
1052   /* Check number of blocks command */
1053   if(NumberOfBlocks <= 1)
1054   {
1055     /* Send CMD24 WRITE_SINGLE_BLOCK */
1056     sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK;
1057   }
1058   else
1059   {
1060     /* Send CMD25 WRITE_MULT_BLOCK with argument data address */
1061     sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_MULT_BLOCK;
1062   }
1063 
1064   sdio_cmdinitstructure.Argument         = (uint32_t)WriteAddr;
1065   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1066 
1067   /* Check for error conditions */
1068   if(NumberOfBlocks > 1)
1069   {
1070     errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_MULT_BLOCK);
1071   }
1072   else
1073   {
1074     errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_SINGLE_BLOCK);
1075   }
1076 
1077   if (errorstate != SD_OK)
1078   {
1079     return errorstate;
1080   }
1081 
1082   /* Configure the SD DPSM (Data Path State Machine) */
1083   sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
1084   sdio_datainitstructure.DataLength    = BlockSize * NumberOfBlocks;
1085   sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B;
1086   sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_CARD;
1087   sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
1088   sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
1089   SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
1090 
1091   hsd->SdTransferErr = errorstate;
1092 
1093   return errorstate;
1094 }
1095 
1096 /**
1097   * @brief  This function waits until the SD DMA data read transfer is finished.
1098   *         This API should be called after HAL_SD_ReadBlocks_DMA() function
1099   *         to insure that all data sent by the card is already transferred by the
1100   *         DMA controller.
1101   * @param  hsd: SD handle
1102   * @param  Timeout: Timeout duration
1103   * @retval SD Card error state
1104   */
HAL_SD_CheckReadOperation(SD_HandleTypeDef * hsd,uint32_t Timeout)1105 HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout)
1106 {
1107   HAL_SD_ErrorTypedef errorstate = SD_OK;
1108   uint32_t timeout = Timeout;
1109   uint32_t tmp1, tmp2;
1110   HAL_SD_ErrorTypedef tmp3;
1111 
1112   /* Wait for DMA/SD transfer end or SD error variables to be in SD handle */
1113   tmp1 = hsd->DmaTransferCplt;
1114   tmp2 = hsd->SdTransferCplt;
1115   tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
1116 
1117   while ((tmp1 == 0) && (tmp2 == 0) && (tmp3 == SD_OK) && (timeout > 0))
1118   {
1119     tmp1 = hsd->DmaTransferCplt;
1120     tmp2 = hsd->SdTransferCplt;
1121     tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
1122     timeout--;
1123   }
1124 
1125   timeout = Timeout;
1126 
1127   /* Wait until the Rx transfer is no longer active */
1128   while((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXACT)) && (timeout > 0))
1129   {
1130     timeout--;
1131   }
1132 
1133   /* Send stop command in multiblock read */
1134   if (hsd->SdOperation == SD_READ_MULTIPLE_BLOCK)
1135   {
1136     errorstate = HAL_SD_StopTransfer(hsd);
1137   }
1138 
1139   if ((timeout == 0) && (errorstate == SD_OK))
1140   {
1141     errorstate = SD_DATA_TIMEOUT;
1142   }
1143 
1144   /* Clear all the static flags */
1145   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1146 
1147   /* Return error state */
1148   if (hsd->SdTransferErr != SD_OK)
1149   {
1150     return (HAL_SD_ErrorTypedef)(hsd->SdTransferErr);
1151   }
1152 
1153   return errorstate;
1154 }
1155 
1156 /**
1157   * @brief  This function waits until the SD DMA data write transfer is finished.
1158   *         This API should be called after HAL_SD_WriteBlocks_DMA() function
1159   *         to insure that all data sent by the card is already transferred by the
1160   *         DMA controller.
1161   * @param  hsd: SD handle
1162   * @param  Timeout: Timeout duration
1163   * @retval SD Card error state
1164   */
HAL_SD_CheckWriteOperation(SD_HandleTypeDef * hsd,uint32_t Timeout)1165 HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout)
1166 {
1167   HAL_SD_ErrorTypedef errorstate = SD_OK;
1168   uint32_t timeout = Timeout;
1169   uint32_t tmp1, tmp2;
1170   HAL_SD_ErrorTypedef tmp3;
1171 
1172   /* Wait for DMA/SD transfer end or SD error variables to be in SD handle */
1173   tmp1 = hsd->DmaTransferCplt;
1174   tmp2 = hsd->SdTransferCplt;
1175   tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
1176 
1177   while ((tmp1 == 0) && (tmp2 == 0) && (tmp3 == SD_OK) && (timeout > 0))
1178   {
1179     tmp1 = hsd->DmaTransferCplt;
1180     tmp2 = hsd->SdTransferCplt;
1181     tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr;
1182     timeout--;
1183   }
1184 
1185   timeout = Timeout;
1186 
1187   /* Wait until the Tx transfer is no longer active */
1188   while((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXACT))  && (timeout > 0))
1189   {
1190     timeout--;
1191   }
1192 
1193   /* Send stop command in multiblock write */
1194   if (hsd->SdOperation == SD_WRITE_MULTIPLE_BLOCK)
1195   {
1196     errorstate = HAL_SD_StopTransfer(hsd);
1197   }
1198 
1199   if ((timeout == 0) && (errorstate == SD_OK))
1200   {
1201     errorstate = SD_DATA_TIMEOUT;
1202   }
1203 
1204   /* Clear all the static flags */
1205   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1206 
1207   /* Return error state */
1208   if (hsd->SdTransferErr != SD_OK)
1209   {
1210     return (HAL_SD_ErrorTypedef)(hsd->SdTransferErr);
1211   }
1212 
1213   /* Wait until write is complete */
1214   while(HAL_SD_GetStatus(hsd) != SD_TRANSFER_OK)
1215   {
1216   }
1217 
1218   return errorstate;
1219 }
1220 
1221 /**
1222   * @brief  Erases the specified memory area of the given SD card.
1223   * @param  hsd: SD handle
1224   * @param  startaddr: Start byte address
1225   * @param  endaddr: End byte address
1226   * @retval SD Card error state
1227   */
HAL_SD_Erase(SD_HandleTypeDef * hsd,uint64_t startaddr,uint64_t endaddr)1228 HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t startaddr, uint64_t endaddr)
1229 {
1230   HAL_SD_ErrorTypedef errorstate = SD_OK;
1231   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
1232 
1233   uint32_t delay         = 0;
1234   __IO uint32_t maxdelay = 0;
1235   uint8_t cardstate      = 0;
1236 
1237   /* Check if the card command class supports erase command */
1238   if (((hsd->CSD[1] >> 20) & SD_CCCC_ERASE) == 0)
1239   {
1240     errorstate = SD_REQUEST_NOT_APPLICABLE;
1241 
1242     return errorstate;
1243   }
1244 
1245   /* Get max delay value */
1246   maxdelay = 120000 / (((hsd->Instance->CLKCR) & 0xFF) + 2);
1247 
1248   if((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
1249   {
1250     errorstate = SD_LOCK_UNLOCK_FAILED;
1251 
1252     return errorstate;
1253   }
1254 
1255   /* Get start and end block for high capacity cards */
1256   if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
1257   {
1258     startaddr /= 512;
1259     endaddr   /= 512;
1260   }
1261 
1262   /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */
1263   if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
1264     (hsd->CardType == HIGH_CAPACITY_SD_CARD))
1265   {
1266     /* Send CMD32 SD_ERASE_GRP_START with argument as addr  */
1267     sdio_cmdinitstructure.Argument         =(uint32_t)startaddr;
1268     sdio_cmdinitstructure.CmdIndex         = SD_CMD_SD_ERASE_GRP_START;
1269     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
1270     sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
1271     sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
1272     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1273 
1274     /* Check for error conditions */
1275     errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_ERASE_GRP_START);
1276 
1277     if (errorstate != SD_OK)
1278     {
1279       return errorstate;
1280     }
1281 
1282     /* Send CMD33 SD_ERASE_GRP_END with argument as addr  */
1283     sdio_cmdinitstructure.Argument         = (uint32_t)endaddr;
1284     sdio_cmdinitstructure.CmdIndex         = SD_CMD_SD_ERASE_GRP_END;
1285     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1286 
1287     /* Check for error conditions */
1288     errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_ERASE_GRP_END);
1289 
1290     if (errorstate != SD_OK)
1291     {
1292       return errorstate;
1293     }
1294   }
1295 
1296   /* Send CMD38 ERASE */
1297   sdio_cmdinitstructure.Argument         = 0;
1298   sdio_cmdinitstructure.CmdIndex         = SD_CMD_ERASE;
1299   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1300 
1301   /* Check for error conditions */
1302   errorstate = SD_CmdResp1Error(hsd, SD_CMD_ERASE);
1303 
1304   if (errorstate != SD_OK)
1305   {
1306     return errorstate;
1307   }
1308 
1309   for (; delay < maxdelay; delay++)
1310   {
1311   }
1312 
1313   /* Wait until the card is in programming state */
1314   errorstate = SD_IsCardProgramming(hsd, &cardstate);
1315 
1316   delay = SD_DATATIMEOUT;
1317 
1318   while ((delay > 0) && (errorstate == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING)))
1319   {
1320     errorstate = SD_IsCardProgramming(hsd, &cardstate);
1321     delay--;
1322   }
1323 
1324   return errorstate;
1325 }
1326 
1327 /**
1328   * @brief  This function handles SD card interrupt request.
1329   * @param  hsd: SD handle
1330   * @retval None
1331   */
HAL_SD_IRQHandler(SD_HandleTypeDef * hsd)1332 void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd)
1333 {
1334   /* Check for SDIO interrupt flags */
1335   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DATAEND))
1336   {
1337     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_IT_DATAEND);
1338 
1339     /* SD transfer is complete */
1340     hsd->SdTransferCplt = 1;
1341 
1342     /* No transfer error */
1343     hsd->SdTransferErr  = SD_OK;
1344 
1345     HAL_SD_XferCpltCallback(hsd);
1346   }
1347   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DCRCFAIL))
1348   {
1349     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
1350 
1351     hsd->SdTransferErr = SD_DATA_CRC_FAIL;
1352 
1353     HAL_SD_XferErrorCallback(hsd);
1354 
1355   }
1356   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DTIMEOUT))
1357   {
1358     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
1359 
1360     hsd->SdTransferErr = SD_DATA_TIMEOUT;
1361 
1362     HAL_SD_XferErrorCallback(hsd);
1363   }
1364   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_RXOVERR))
1365   {
1366     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
1367 
1368     hsd->SdTransferErr = SD_RX_OVERRUN;
1369 
1370     HAL_SD_XferErrorCallback(hsd);
1371   }
1372   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_TXUNDERR))
1373   {
1374     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_TXUNDERR);
1375 
1376     hsd->SdTransferErr = SD_TX_UNDERRUN;
1377 
1378     HAL_SD_XferErrorCallback(hsd);
1379   }
1380   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_STBITERR))
1381   {
1382     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
1383 
1384     hsd->SdTransferErr = SD_START_BIT_ERR;
1385 
1386     HAL_SD_XferErrorCallback(hsd);
1387   }
1388   else
1389   {
1390     /* No error flag set */
1391   }
1392 
1393   /* Disable all SDIO peripheral interrupt sources */
1394   __HAL_SD_SDIO_DISABLE_IT(hsd, SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND  |\
1395                                 SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |\
1396                                 SDIO_IT_RXOVERR  | SDIO_IT_STBITERR);
1397 }
1398 
1399 
1400 /**
1401   * @brief  SD end of transfer callback.
1402   * @param  hsd: SD handle
1403   * @retval None
1404   */
HAL_SD_XferCpltCallback(SD_HandleTypeDef * hsd)1405 __weak void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd)
1406 {
1407   /* Prevent unused argument(s) compilation warning */
1408   UNUSED(hsd);
1409 
1410   /* NOTE : This function Should not be modified, when the callback is needed,
1411             the HAL_SD_XferCpltCallback could be implemented in the user file
1412    */
1413 }
1414 
1415 /**
1416   * @brief  SD Transfer Error callback.
1417   * @param  hsd: SD handle
1418   * @retval None
1419   */
HAL_SD_XferErrorCallback(SD_HandleTypeDef * hsd)1420 __weak void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd)
1421 {
1422   /* Prevent unused argument(s) compilation warning */
1423   UNUSED(hsd);
1424 
1425   /* NOTE : This function Should not be modified, when the callback is needed,
1426             the HAL_SD_XferErrorCallback could be implemented in the user file
1427    */
1428 }
1429 
1430 /**
1431   * @brief  SD Transfer complete Rx callback in non blocking mode.
1432   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1433   *                the configuration information for the specified DMA module.
1434   * @retval None
1435   */
HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef * hdma)1436 __weak void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma)
1437 {
1438   /* Prevent unused argument(s) compilation warning */
1439   UNUSED(hdma);
1440 
1441   /* NOTE : This function Should not be modified, when the callback is needed,
1442             the HAL_SD_DMA_RxCpltCallback could be implemented in the user file
1443    */
1444 }
1445 
1446 /**
1447   * @brief  SD DMA transfer complete Rx error callback.
1448   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1449   *                the configuration information for the specified DMA module.
1450   * @retval None
1451   */
HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef * hdma)1452 __weak void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma)
1453 {
1454   /* Prevent unused argument(s) compilation warning */
1455   UNUSED(hdma);
1456 
1457   /* NOTE : This function Should not be modified, when the callback is needed,
1458             the HAL_SD_DMA_RxErrorCallback could be implemented in the user file
1459    */
1460 }
1461 
1462 /**
1463   * @brief  SD Transfer complete Tx callback in non blocking mode.
1464   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1465   *                the configuration information for the specified DMA module.
1466   * @retval None
1467   */
HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef * hdma)1468 __weak void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma)
1469 {
1470   /* Prevent unused argument(s) compilation warning */
1471   UNUSED(hdma);
1472 
1473   /* NOTE : This function Should not be modified, when the callback is needed,
1474             the HAL_SD_DMA_TxCpltCallback could be implemented in the user file
1475    */
1476 }
1477 
1478 /**
1479   * @brief  SD DMA transfer complete error Tx callback.
1480   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1481   *                the configuration information for the specified DMA module.
1482   * @retval None
1483   */
HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef * hdma)1484 __weak void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma)
1485 {
1486   /* Prevent unused argument(s) compilation warning */
1487   UNUSED(hdma);
1488 
1489   /* NOTE : This function Should not be modified, when the callback is needed,
1490             the HAL_SD_DMA_TxErrorCallback could be implemented in the user file
1491    */
1492 }
1493 
1494 /**
1495   * @}
1496   */
1497 
1498 /** @addtogroup SD_Exported_Functions_Group3
1499  *  @brief   management functions
1500  *
1501 @verbatim
1502   ==============================================================================
1503                       ##### Peripheral Control functions #####
1504   ==============================================================================
1505   [..]
1506     This subsection provides a set of functions allowing to control the SD card
1507     operations.
1508 
1509 @endverbatim
1510   * @{
1511   */
1512 
1513 /**
1514   * @brief  Returns information about specific card.
1515   * @param  hsd: SD handle
1516   * @param  pCardInfo: Pointer to a HAL_SD_CardInfoTypedef structure that
1517   *         contains all SD cardinformation
1518   * @retval SD Card error state
1519   */
HAL_SD_Get_CardInfo(SD_HandleTypeDef * hsd,HAL_SD_CardInfoTypedef * pCardInfo)1520 HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo)
1521 {
1522   HAL_SD_ErrorTypedef errorstate = SD_OK;
1523   uint32_t tmp = 0;
1524 
1525   pCardInfo->CardType = (uint8_t)(hsd->CardType);
1526   pCardInfo->RCA      = (uint16_t)(hsd->RCA);
1527 
1528   /* Byte 0 */
1529   tmp = (hsd->CSD[0] & 0xFF000000U) >> 24;
1530   pCardInfo->SD_csd.CSDStruct      = (uint8_t)((tmp & 0xC0) >> 6);
1531   pCardInfo->SD_csd.SysSpecVersion = (uint8_t)((tmp & 0x3C) >> 2);
1532   pCardInfo->SD_csd.Reserved1      = tmp & 0x03;
1533 
1534   /* Byte 1 */
1535   tmp = (hsd->CSD[0] & 0x00FF0000U) >> 16;
1536   pCardInfo->SD_csd.TAAC = (uint8_t)tmp;
1537 
1538   /* Byte 2 */
1539   tmp = (hsd->CSD[0] & 0x0000FF00U) >> 8;
1540   pCardInfo->SD_csd.NSAC = (uint8_t)tmp;
1541 
1542   /* Byte 3 */
1543   tmp = hsd->CSD[0] & 0x000000FFU;
1544   pCardInfo->SD_csd.MaxBusClkFrec = (uint8_t)tmp;
1545 
1546   /* Byte 4 */
1547   tmp = (hsd->CSD[1] & 0xFF000000U) >> 24;
1548   pCardInfo->SD_csd.CardComdClasses = (uint16_t)(tmp << 4);
1549 
1550   /* Byte 5 */
1551   tmp = (hsd->CSD[1] & 0x00FF0000U) >> 16;
1552   pCardInfo->SD_csd.CardComdClasses |= (uint16_t)((tmp & 0xF0) >> 4);
1553   pCardInfo->SD_csd.RdBlockLen       = (uint8_t)(tmp & 0x0F);
1554 
1555   /* Byte 6 */
1556   tmp = (hsd->CSD[1] & 0x0000FF00U) >> 8;
1557   pCardInfo->SD_csd.PartBlockRead   = (uint8_t)((tmp & 0x80) >> 7);
1558   pCardInfo->SD_csd.WrBlockMisalign = (uint8_t)((tmp & 0x40) >> 6);
1559   pCardInfo->SD_csd.RdBlockMisalign = (uint8_t)((tmp & 0x20) >> 5);
1560   pCardInfo->SD_csd.DSRImpl         = (uint8_t)((tmp & 0x10) >> 4);
1561   pCardInfo->SD_csd.Reserved2       = 0; /*!< Reserved */
1562 
1563   if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0))
1564   {
1565     pCardInfo->SD_csd.DeviceSize = (tmp & 0x03) << 10;
1566 
1567     /* Byte 7 */
1568     tmp = (uint8_t)(hsd->CSD[1] & 0x000000FFU);
1569     pCardInfo->SD_csd.DeviceSize |= (tmp) << 2;
1570 
1571     /* Byte 8 */
1572     tmp = (uint8_t)((hsd->CSD[2] & 0xFF000000U) >> 24);
1573     pCardInfo->SD_csd.DeviceSize |= (tmp & 0xC0) >> 6;
1574 
1575     pCardInfo->SD_csd.MaxRdCurrentVDDMin = (tmp & 0x38) >> 3;
1576     pCardInfo->SD_csd.MaxRdCurrentVDDMax = (tmp & 0x07);
1577 
1578     /* Byte 9 */
1579     tmp = (uint8_t)((hsd->CSD[2] & 0x00FF0000U) >> 16);
1580     pCardInfo->SD_csd.MaxWrCurrentVDDMin = (tmp & 0xE0) >> 5;
1581     pCardInfo->SD_csd.MaxWrCurrentVDDMax = (tmp & 0x1C) >> 2;
1582     pCardInfo->SD_csd.DeviceSizeMul      = (tmp & 0x03) << 1;
1583     /* Byte 10 */
1584     tmp = (uint8_t)((hsd->CSD[2] & 0x0000FF00U) >> 8);
1585     pCardInfo->SD_csd.DeviceSizeMul |= (tmp & 0x80) >> 7;
1586 
1587     pCardInfo->CardCapacity  = (pCardInfo->SD_csd.DeviceSize + 1) ;
1588     pCardInfo->CardCapacity *= (1 << (pCardInfo->SD_csd.DeviceSizeMul + 2));
1589     pCardInfo->CardBlockSize = 1 << (pCardInfo->SD_csd.RdBlockLen);
1590     pCardInfo->CardCapacity *= pCardInfo->CardBlockSize;
1591   }
1592   else if (hsd->CardType == HIGH_CAPACITY_SD_CARD)
1593   {
1594     /* Byte 7 */
1595     tmp = (uint8_t)(hsd->CSD[1] & 0x000000FFU);
1596     pCardInfo->SD_csd.DeviceSize = (tmp & 0x3F) << 16;
1597 
1598     /* Byte 8 */
1599     tmp = (uint8_t)((hsd->CSD[2] & 0xFF000000U) >> 24);
1600 
1601     pCardInfo->SD_csd.DeviceSize |= (tmp << 8);
1602 
1603     /* Byte 9 */
1604     tmp = (uint8_t)((hsd->CSD[2] & 0x00FF0000U) >> 16);
1605 
1606     pCardInfo->SD_csd.DeviceSize |= (tmp);
1607 
1608     /* Byte 10 */
1609     tmp = (uint8_t)((hsd->CSD[2] & 0x0000FF00U) >> 8);
1610 
1611     pCardInfo->CardCapacity = (uint64_t)((((uint64_t)pCardInfo->SD_csd.DeviceSize + 1)) * 512 * 1024);
1612     pCardInfo->CardBlockSize = 512;
1613   }
1614   else
1615   {
1616     /* Not supported card type */
1617     errorstate = SD_ERROR;
1618   }
1619 
1620   pCardInfo->SD_csd.EraseGrSize = (tmp & 0x40) >> 6;
1621   pCardInfo->SD_csd.EraseGrMul  = (tmp & 0x3F) << 1;
1622 
1623   /* Byte 11 */
1624   tmp = (uint8_t)(hsd->CSD[2] & 0x000000FFU);
1625   pCardInfo->SD_csd.EraseGrMul     |= (tmp & 0x80) >> 7;
1626   pCardInfo->SD_csd.WrProtectGrSize = (tmp & 0x7F);
1627 
1628   /* Byte 12 */
1629   tmp = (uint8_t)((hsd->CSD[3] & 0xFF000000U) >> 24);
1630   pCardInfo->SD_csd.WrProtectGrEnable = (tmp & 0x80) >> 7;
1631   pCardInfo->SD_csd.ManDeflECC        = (tmp & 0x60) >> 5;
1632   pCardInfo->SD_csd.WrSpeedFact       = (tmp & 0x1C) >> 2;
1633   pCardInfo->SD_csd.MaxWrBlockLen     = (tmp & 0x03) << 2;
1634 
1635   /* Byte 13 */
1636   tmp = (uint8_t)((hsd->CSD[3] & 0x00FF0000U) >> 16);
1637   pCardInfo->SD_csd.MaxWrBlockLen      |= (tmp & 0xC0) >> 6;
1638   pCardInfo->SD_csd.WriteBlockPaPartial = (tmp & 0x20) >> 5;
1639   pCardInfo->SD_csd.Reserved3           = 0;
1640   pCardInfo->SD_csd.ContentProtectAppli = (tmp & 0x01);
1641 
1642   /* Byte 14 */
1643   tmp = (uint8_t)((hsd->CSD[3] & 0x0000FF00U) >> 8);
1644   pCardInfo->SD_csd.FileFormatGrouop = (tmp & 0x80) >> 7;
1645   pCardInfo->SD_csd.CopyFlag         = (tmp & 0x40) >> 6;
1646   pCardInfo->SD_csd.PermWrProtect    = (tmp & 0x20) >> 5;
1647   pCardInfo->SD_csd.TempWrProtect    = (tmp & 0x10) >> 4;
1648   pCardInfo->SD_csd.FileFormat       = (tmp & 0x0C) >> 2;
1649   pCardInfo->SD_csd.ECC              = (tmp & 0x03);
1650 
1651   /* Byte 15 */
1652   tmp = (uint8_t)(hsd->CSD[3] & 0x000000FFU);
1653   pCardInfo->SD_csd.CSD_CRC   = (tmp & 0xFE) >> 1;
1654   pCardInfo->SD_csd.Reserved4 = 1;
1655 
1656   /* Byte 0 */
1657   tmp = (uint8_t)((hsd->CID[0] & 0xFF000000U) >> 24);
1658   pCardInfo->SD_cid.ManufacturerID = tmp;
1659 
1660   /* Byte 1 */
1661   tmp = (uint8_t)((hsd->CID[0] & 0x00FF0000U) >> 16);
1662   pCardInfo->SD_cid.OEM_AppliID = tmp << 8;
1663 
1664   /* Byte 2 */
1665   tmp = (uint8_t)((hsd->CID[0] & 0x000000FF00U) >> 8);
1666   pCardInfo->SD_cid.OEM_AppliID |= tmp;
1667 
1668   /* Byte 3 */
1669   tmp = (uint8_t)(hsd->CID[0] & 0x000000FFU);
1670   pCardInfo->SD_cid.ProdName1 = tmp << 24;
1671 
1672   /* Byte 4 */
1673   tmp = (uint8_t)((hsd->CID[1] & 0xFF000000U) >> 24);
1674   pCardInfo->SD_cid.ProdName1 |= tmp << 16;
1675 
1676   /* Byte 5 */
1677   tmp = (uint8_t)((hsd->CID[1] & 0x00FF0000U) >> 16);
1678   pCardInfo->SD_cid.ProdName1 |= tmp << 8;
1679 
1680   /* Byte 6 */
1681   tmp = (uint8_t)((hsd->CID[1] & 0x0000FF00U) >> 8);
1682   pCardInfo->SD_cid.ProdName1 |= tmp;
1683 
1684   /* Byte 7 */
1685   tmp = (uint8_t)(hsd->CID[1] & 0x000000FFU);
1686   pCardInfo->SD_cid.ProdName2 = tmp;
1687 
1688   /* Byte 8 */
1689   tmp = (uint8_t)((hsd->CID[2] & 0xFF000000U) >> 24);
1690   pCardInfo->SD_cid.ProdRev = tmp;
1691 
1692   /* Byte 9 */
1693   tmp = (uint8_t)((hsd->CID[2] & 0x00FF0000U) >> 16);
1694   pCardInfo->SD_cid.ProdSN = tmp << 24;
1695 
1696   /* Byte 10 */
1697   tmp = (uint8_t)((hsd->CID[2] & 0x0000FF00U) >> 8);
1698   pCardInfo->SD_cid.ProdSN |= tmp << 16;
1699 
1700   /* Byte 11 */
1701   tmp = (uint8_t)(hsd->CID[2] & 0x000000FFU);
1702   pCardInfo->SD_cid.ProdSN |= tmp << 8;
1703 
1704   /* Byte 12 */
1705   tmp = (uint8_t)((hsd->CID[3] & 0xFF000000U) >> 24);
1706   pCardInfo->SD_cid.ProdSN |= tmp;
1707 
1708   /* Byte 13 */
1709   tmp = (uint8_t)((hsd->CID[3] & 0x00FF0000U) >> 16);
1710   pCardInfo->SD_cid.Reserved1   |= (tmp & 0xF0) >> 4;
1711   pCardInfo->SD_cid.ManufactDate = (tmp & 0x0F) << 8;
1712 
1713   /* Byte 14 */
1714   tmp = (uint8_t)((hsd->CID[3] & 0x0000FF00U) >> 8);
1715   pCardInfo->SD_cid.ManufactDate |= tmp;
1716 
1717   /* Byte 15 */
1718   tmp = (uint8_t)(hsd->CID[3] & 0x000000FFU);
1719   pCardInfo->SD_cid.CID_CRC   = (tmp & 0xFE) >> 1;
1720   pCardInfo->SD_cid.Reserved2 = 1;
1721 
1722   return errorstate;
1723 }
1724 
1725 /**
1726   * @brief  Enables wide bus operation for the requested card if supported by
1727   *         card.
1728   * @param  hsd: SD handle
1729   * @param  WideMode: Specifies the SD card wide bus mode
1730   *          This parameter can be one of the following values:
1731   *            @arg SDIO_BUS_WIDE_8B: 8-bit data transfer (Only for MMC)
1732   *            @arg SDIO_BUS_WIDE_4B: 4-bit data transfer
1733   *            @arg SDIO_BUS_WIDE_1B: 1-bit data transfer
1734   * @retval SD Card error state
1735   */
HAL_SD_WideBusOperation_Config(SD_HandleTypeDef * hsd,uint32_t WideMode)1736 HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode)
1737 {
1738   HAL_SD_ErrorTypedef errorstate = SD_OK;
1739   SDIO_InitTypeDef tmpinit;
1740 
1741   /* MMC Card does not support this feature */
1742   if (hsd->CardType == MULTIMEDIA_CARD)
1743   {
1744     errorstate = SD_UNSUPPORTED_FEATURE;
1745   }
1746   else if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
1747     (hsd->CardType == HIGH_CAPACITY_SD_CARD))
1748   {
1749     if (WideMode == SDIO_BUS_WIDE_8B)
1750     {
1751       errorstate = SD_UNSUPPORTED_FEATURE;
1752     }
1753     else if (WideMode == SDIO_BUS_WIDE_4B)
1754     {
1755       errorstate = SD_WideBus_Enable(hsd);
1756     }
1757     else if (WideMode == SDIO_BUS_WIDE_1B)
1758     {
1759       errorstate = SD_WideBus_Disable(hsd);
1760     }
1761     else
1762     {
1763       /* WideMode is not a valid argument*/
1764       errorstate = SD_INVALID_PARAMETER;
1765     }
1766 
1767     if (errorstate == SD_OK)
1768     {
1769       /* Configure the SDIO peripheral */
1770       tmpinit.ClockEdge           = hsd->Init.ClockEdge;
1771       tmpinit.ClockBypass         = hsd->Init.ClockBypass;
1772       tmpinit.ClockPowerSave      = hsd->Init.ClockPowerSave;
1773       tmpinit.BusWide             = WideMode;
1774       tmpinit.HardwareFlowControl = hsd->Init.HardwareFlowControl;
1775       tmpinit.ClockDiv            = hsd->Init.ClockDiv;
1776 
1777       /* Configure SDIO peripheral interface */
1778       SDIO_Init(hsd->Instance, tmpinit);
1779     }
1780     else
1781     {
1782       /* An error occured while enabling/disabling the wide bus*/
1783     }
1784   }
1785   else
1786   {
1787     /* Not supported card type */
1788     errorstate = SD_ERROR;
1789   }
1790 
1791   return errorstate;
1792 }
1793 
1794 /**
1795   * @brief  Aborts an ongoing data transfer.
1796   * @param  hsd: SD handle
1797   * @retval SD Card error state
1798   */
HAL_SD_StopTransfer(SD_HandleTypeDef * hsd)1799 HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd)
1800 {
1801   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
1802   HAL_SD_ErrorTypedef errorstate = SD_OK;
1803 
1804   /* Send CMD12 STOP_TRANSMISSION  */
1805   sdio_cmdinitstructure.Argument         = 0;
1806   sdio_cmdinitstructure.CmdIndex         = SD_CMD_STOP_TRANSMISSION;
1807   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
1808   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
1809   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
1810   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1811 
1812   /* Check for error conditions */
1813   errorstate = SD_CmdResp1Error(hsd, SD_CMD_STOP_TRANSMISSION);
1814 
1815   return errorstate;
1816 }
1817 
1818 /**
1819   * @brief  Switches the SD card to High Speed mode.
1820   *         This API must be used after "Transfer State"
1821   * @note   This operation should be followed by the configuration
1822   *         of PLL to have SDIOCK clock between 67 and 75 MHz
1823   * @param  hsd: SD handle
1824   * @retval SD Card error state
1825   */
HAL_SD_HighSpeed(SD_HandleTypeDef * hsd)1826 HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd)
1827 {
1828   HAL_SD_ErrorTypedef errorstate = SD_OK;
1829   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
1830   SDIO_DataInitTypeDef sdio_datainitstructure;
1831 
1832   uint8_t SD_hs[64]  = {0};
1833   uint32_t SD_scr[2] = {0, 0};
1834   uint32_t SD_SPEC   = 0 ;
1835   uint32_t count = 0, *tempbuff = (uint32_t *)SD_hs;
1836 
1837   /* Initialize the Data control register */
1838   hsd->Instance->DCTRL = 0;
1839 
1840   /* Get SCR Register */
1841   errorstate = SD_FindSCR(hsd, SD_scr);
1842 
1843   if (errorstate != SD_OK)
1844   {
1845     return errorstate;
1846   }
1847 
1848   /* Test the Version supported by the card*/
1849   SD_SPEC = (SD_scr[1]  & 0x01000000U) | (SD_scr[1]  & 0x02000000U);
1850 
1851   if (SD_SPEC != SD_ALLZERO)
1852   {
1853     /* Set Block Size for Card */
1854     sdio_cmdinitstructure.Argument         = 64U;
1855     sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
1856     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
1857     sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
1858     sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
1859     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1860 
1861     /* Check for error conditions */
1862     errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
1863 
1864     if (errorstate != SD_OK)
1865     {
1866       return errorstate;
1867     }
1868 
1869     /* Configure the SD DPSM (Data Path State Machine) */
1870     sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
1871     sdio_datainitstructure.DataLength    = 64;
1872     sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_64B ;
1873     sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
1874     sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
1875     sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
1876     SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
1877 
1878     /* Send CMD6 switch mode */
1879     sdio_cmdinitstructure.Argument         = 0x80FFFF01U;
1880     sdio_cmdinitstructure.CmdIndex         = SD_CMD_HS_SWITCH;
1881     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
1882 
1883     /* Check for error conditions */
1884     errorstate = SD_CmdResp1Error(hsd, SD_CMD_HS_SWITCH);
1885 
1886     if (errorstate != SD_OK)
1887     {
1888       return errorstate;
1889     }
1890 
1891     while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
1892     {
1893       if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
1894       {
1895         for (count = 0; count < 8; count++)
1896         {
1897           *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance);
1898         }
1899 
1900         tempbuff += 8;
1901       }
1902     }
1903 
1904     if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
1905     {
1906       __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
1907 
1908       errorstate = SD_DATA_TIMEOUT;
1909 
1910       return errorstate;
1911     }
1912     else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
1913     {
1914       __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
1915 
1916       errorstate = SD_DATA_CRC_FAIL;
1917 
1918       return errorstate;
1919     }
1920     else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
1921     {
1922       __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
1923 
1924       errorstate = SD_RX_OVERRUN;
1925 
1926       return errorstate;
1927     }
1928     else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
1929     {
1930       __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
1931 
1932       errorstate = SD_START_BIT_ERR;
1933 
1934       return errorstate;
1935     }
1936     else
1937     {
1938       /* No error flag set */
1939     }
1940 
1941     count = SD_DATATIMEOUT;
1942 
1943     while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0))
1944     {
1945       *tempbuff = SDIO_ReadFIFO(hsd->Instance);
1946       tempbuff++;
1947       count--;
1948     }
1949 
1950     /* Clear all the static flags */
1951     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
1952 
1953     /* Test if the switch mode HS is ok */
1954     if ((SD_hs[13]& 2) != 2)
1955     {
1956       errorstate = SD_UNSUPPORTED_FEATURE;
1957     }
1958   }
1959 
1960   return errorstate;
1961 }
1962 
1963 /**
1964   * @}
1965   */
1966 
1967 /** @addtogroup SD_Exported_Functions_Group4
1968  *  @brief   Peripheral State functions
1969  *
1970 @verbatim
1971   ==============================================================================
1972                       ##### Peripheral State functions #####
1973   ==============================================================================
1974   [..]
1975     This subsection permits to get in runtime the status of the peripheral
1976     and the data flow.
1977 
1978 @endverbatim
1979   * @{
1980   */
1981 
1982 /**
1983   * @brief  Returns the current SD card's status.
1984   * @param  hsd: SD handle
1985   * @param  pSDstatus: Pointer to the buffer that will contain the SD card status
1986   *         SD Status register)
1987   * @retval SD Card error state
1988   */
HAL_SD_SendSDStatus(SD_HandleTypeDef * hsd,uint32_t * pSDstatus)1989 HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus)
1990 {
1991   SDIO_CmdInitTypeDef  sdio_cmdinitstructure;
1992   SDIO_DataInitTypeDef sdio_datainitstructure;
1993   HAL_SD_ErrorTypedef errorstate = SD_OK;
1994   uint32_t count = 0;
1995 
1996   /* Check SD response */
1997   if ((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
1998   {
1999     errorstate = SD_LOCK_UNLOCK_FAILED;
2000 
2001     return errorstate;
2002   }
2003 
2004   /* Set block size for card if it is not equal to current block size for card */
2005   sdio_cmdinitstructure.Argument         = 64;
2006   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
2007   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2008   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2009   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2010   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2011 
2012   /* Check for error conditions */
2013   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
2014 
2015   if (errorstate != SD_OK)
2016   {
2017     return errorstate;
2018   }
2019 
2020   /* Send CMD55 */
2021   sdio_cmdinitstructure.Argument         = (uint32_t)(hsd->RCA << 16);
2022   sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_CMD;
2023   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2024 
2025   /* Check for error conditions */
2026   errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
2027 
2028   if (errorstate != SD_OK)
2029   {
2030     return errorstate;
2031   }
2032 
2033   /* Configure the SD DPSM (Data Path State Machine) */
2034   sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
2035   sdio_datainitstructure.DataLength    = 64;
2036   sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_64B;
2037   sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
2038   sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
2039   sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
2040   SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
2041 
2042   /* Send ACMD13 (SD_APP_STATUS)  with argument as card's RCA */
2043   sdio_cmdinitstructure.Argument         = 0;
2044   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SD_APP_STATUS;
2045   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2046 
2047   /* Check for error conditions */
2048   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_APP_STATUS);
2049 
2050   if (errorstate != SD_OK)
2051   {
2052     return errorstate;
2053   }
2054 
2055   /* Get status data */
2056   while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
2057   {
2058     if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF))
2059     {
2060       for (count = 0; count < 8; count++)
2061       {
2062         *(pSDstatus + count) = SDIO_ReadFIFO(hsd->Instance);
2063       }
2064 
2065       pSDstatus += 8;
2066     }
2067   }
2068 
2069   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
2070   {
2071     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
2072 
2073     errorstate = SD_DATA_TIMEOUT;
2074 
2075     return errorstate;
2076   }
2077   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
2078   {
2079     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
2080 
2081     errorstate = SD_DATA_CRC_FAIL;
2082 
2083     return errorstate;
2084   }
2085   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
2086   {
2087     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
2088 
2089     errorstate = SD_RX_OVERRUN;
2090 
2091     return errorstate;
2092   }
2093   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
2094   {
2095     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
2096 
2097     errorstate = SD_START_BIT_ERR;
2098 
2099     return errorstate;
2100   }
2101   else
2102   {
2103     /* No error flag set */
2104   }
2105 
2106   count = SD_DATATIMEOUT;
2107   while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0))
2108   {
2109     *pSDstatus = SDIO_ReadFIFO(hsd->Instance);
2110     pSDstatus++;
2111     count--;
2112   }
2113 
2114   /* Clear all the static status flags*/
2115   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2116 
2117   return errorstate;
2118 }
2119 
2120 /**
2121   * @brief  Gets the current sd card data status.
2122   * @param  hsd: SD handle
2123   * @retval Data Transfer state
2124   */
HAL_SD_GetStatus(SD_HandleTypeDef * hsd)2125 HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd)
2126 {
2127   HAL_SD_CardStateTypedef cardstate =  SD_CARD_TRANSFER;
2128 
2129   /* Get SD card state */
2130   cardstate = SD_GetState(hsd);
2131 
2132   /* Find SD status according to card state*/
2133   if (cardstate == SD_CARD_TRANSFER)
2134   {
2135     return SD_TRANSFER_OK;
2136   }
2137   else if(cardstate == SD_CARD_ERROR)
2138   {
2139     return SD_TRANSFER_ERROR;
2140   }
2141   else
2142   {
2143     return SD_TRANSFER_BUSY;
2144   }
2145 }
2146 
2147 /**
2148   * @brief  Gets the SD card status.
2149   * @param  hsd: SD handle
2150   * @param  pCardStatus: Pointer to the HAL_SD_CardStatusTypedef structure that
2151   *         will contain the SD card status information
2152   * @retval SD Card error state
2153   */
HAL_SD_GetCardStatus(SD_HandleTypeDef * hsd,HAL_SD_CardStatusTypedef * pCardStatus)2154 HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus)
2155 {
2156   HAL_SD_ErrorTypedef errorstate = SD_OK;
2157   uint32_t tmp = 0;
2158   uint32_t sd_status[16];
2159 
2160   errorstate = HAL_SD_SendSDStatus(hsd, sd_status);
2161 
2162   if (errorstate  != SD_OK)
2163   {
2164     return errorstate;
2165   }
2166 
2167   /* Byte 0 */
2168   tmp = (sd_status[0] & 0xC0) >> 6;
2169   pCardStatus->DAT_BUS_WIDTH = (uint8_t)tmp;
2170 
2171   /* Byte 0 */
2172   tmp = (sd_status[0] & 0x20) >> 5;
2173   pCardStatus->SECURED_MODE = (uint8_t)tmp;
2174 
2175   /* Byte 2 */
2176   tmp = (sd_status[2] & 0xFF);
2177   pCardStatus->SD_CARD_TYPE = (uint8_t)(tmp << 8);
2178 
2179   /* Byte 3 */
2180   tmp = (sd_status[3] & 0xFF);
2181   pCardStatus->SD_CARD_TYPE |= (uint8_t)tmp;
2182 
2183   /* Byte 4 */
2184   tmp = (sd_status[4] & 0xFF);
2185   pCardStatus->SIZE_OF_PROTECTED_AREA = (uint8_t)(tmp << 24);
2186 
2187   /* Byte 5 */
2188   tmp = (sd_status[5] & 0xFF);
2189   pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(tmp << 16);
2190 
2191   /* Byte 6 */
2192   tmp = (sd_status[6] & 0xFF);
2193   pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(tmp << 8);
2194 
2195   /* Byte 7 */
2196   tmp = (sd_status[7] & 0xFF);
2197   pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)tmp;
2198 
2199   /* Byte 8 */
2200   tmp = (sd_status[8] & 0xFF);
2201   pCardStatus->SPEED_CLASS = (uint8_t)tmp;
2202 
2203   /* Byte 9 */
2204   tmp = (sd_status[9] & 0xFF);
2205   pCardStatus->PERFORMANCE_MOVE = (uint8_t)tmp;
2206 
2207   /* Byte 10 */
2208   tmp = (sd_status[10] & 0xF0) >> 4;
2209   pCardStatus->AU_SIZE = (uint8_t)tmp;
2210 
2211   /* Byte 11 */
2212   tmp = (sd_status[11] & 0xFF);
2213   pCardStatus->ERASE_SIZE = (uint8_t)(tmp << 8);
2214 
2215   /* Byte 12 */
2216   tmp = (sd_status[12] & 0xFF);
2217   pCardStatus->ERASE_SIZE |= (uint8_t)tmp;
2218 
2219   /* Byte 13 */
2220   tmp = (sd_status[13] & 0xFC) >> 2;
2221   pCardStatus->ERASE_TIMEOUT = (uint8_t)tmp;
2222 
2223   /* Byte 13 */
2224   tmp = (sd_status[13] & 0x3);
2225   pCardStatus->ERASE_OFFSET = (uint8_t)tmp;
2226 
2227   return errorstate;
2228 }
2229 
2230 /**
2231   * @}
2232   */
2233 
2234 /**
2235   * @}
2236   */
2237 
2238 /* Private function ----------------------------------------------------------*/
2239 /** @addtogroup SD_Private_Functions
2240   * @{
2241   */
2242 
2243 /**
2244   * @brief  SD DMA transfer complete Rx callback.
2245   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
2246   *                the configuration information for the specified DMA module.
2247   * @retval None
2248   */
SD_DMA_RxCplt(DMA_HandleTypeDef * hdma)2249 static void SD_DMA_RxCplt(DMA_HandleTypeDef *hdma)
2250 {
2251   SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
2252 
2253   /* DMA transfer is complete */
2254   hsd->DmaTransferCplt = 1;
2255 
2256   /* Wait until SD transfer is complete */
2257   while(hsd->SdTransferCplt == 0)
2258   {
2259   }
2260 
2261   /* Disable the DMA channel */
2262   HAL_DMA_Abort(hdma);
2263 
2264   /* Transfer complete user callback */
2265   HAL_SD_DMA_RxCpltCallback(hsd->hdmarx);
2266 }
2267 
2268 /**
2269   * @brief  SD DMA transfer Error Rx callback.
2270   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
2271   *                the configuration information for the specified DMA module.
2272   * @retval None
2273   */
SD_DMA_RxError(DMA_HandleTypeDef * hdma)2274 static void SD_DMA_RxError(DMA_HandleTypeDef *hdma)
2275 {
2276   SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
2277 
2278   /* Transfer complete user callback */
2279   HAL_SD_DMA_RxErrorCallback(hsd->hdmarx);
2280 }
2281 
2282 /**
2283   * @brief  SD DMA transfer complete Tx callback.
2284   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
2285   *                the configuration information for the specified DMA module.
2286   * @retval None
2287   */
SD_DMA_TxCplt(DMA_HandleTypeDef * hdma)2288 static void SD_DMA_TxCplt(DMA_HandleTypeDef *hdma)
2289 {
2290   SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
2291 
2292   /* DMA transfer is complete */
2293   hsd->DmaTransferCplt = 1;
2294 
2295   /* Wait until SD transfer is complete */
2296   while(hsd->SdTransferCplt == 0)
2297   {
2298   }
2299 
2300   /* Disable the DMA channel */
2301   HAL_DMA_Abort(hdma);
2302 
2303   /* Transfer complete user callback */
2304   HAL_SD_DMA_TxCpltCallback(hsd->hdmatx);
2305 }
2306 
2307 /**
2308   * @brief  SD DMA transfer Error Tx callback.
2309   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
2310   *                the configuration information for the specified DMA module.
2311   * @retval None
2312   */
SD_DMA_TxError(DMA_HandleTypeDef * hdma)2313 static void SD_DMA_TxError(DMA_HandleTypeDef *hdma)
2314 {
2315   SD_HandleTypeDef *hsd = ( SD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
2316 
2317   /* Transfer complete user callback */
2318   HAL_SD_DMA_TxErrorCallback(hsd->hdmatx);
2319 }
2320 
2321 /**
2322   * @brief  Returns the SD current state.
2323   * @param  hsd: SD handle
2324   * @retval SD card current state
2325   */
SD_GetState(SD_HandleTypeDef * hsd)2326 static HAL_SD_CardStateTypedef SD_GetState(SD_HandleTypeDef *hsd)
2327 {
2328   uint32_t resp1 = 0;
2329 
2330   if (SD_SendStatus(hsd, &resp1) != SD_OK)
2331   {
2332     return SD_CARD_ERROR;
2333   }
2334   else
2335   {
2336     return (HAL_SD_CardStateTypedef)((resp1 >> 9) & 0x0F);
2337   }
2338 }
2339 
2340 /**
2341   * @brief  Initializes all cards or single card as the case may be Card(s) come
2342   *         into standby state.
2343   * @param  hsd: SD handle
2344   * @retval SD Card error state
2345   */
SD_Initialize_Cards(SD_HandleTypeDef * hsd)2346 static HAL_SD_ErrorTypedef SD_Initialize_Cards(SD_HandleTypeDef *hsd)
2347 {
2348   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
2349   HAL_SD_ErrorTypedef errorstate = SD_OK;
2350   uint16_t sd_rca = 1;
2351 
2352   if(SDIO_GetPowerState(hsd->Instance) == 0) /* Power off */
2353   {
2354     errorstate = SD_REQUEST_NOT_APPLICABLE;
2355 
2356     return errorstate;
2357   }
2358 
2359   if(hsd->CardType != SECURE_DIGITAL_IO_CARD)
2360   {
2361     /* Send CMD2 ALL_SEND_CID */
2362     sdio_cmdinitstructure.Argument         = 0;
2363     sdio_cmdinitstructure.CmdIndex         = SD_CMD_ALL_SEND_CID;
2364     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_LONG;
2365     sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2366     sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2367     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2368 
2369     /* Check for error conditions */
2370     errorstate = SD_CmdResp2Error(hsd);
2371 
2372     if(errorstate != SD_OK)
2373     {
2374       return errorstate;
2375     }
2376 
2377     /* Get Card identification number data */
2378     hsd->CID[0] = SDIO_GetResponse(SDIO_RESP1);
2379     hsd->CID[1] = SDIO_GetResponse(SDIO_RESP2);
2380     hsd->CID[2] = SDIO_GetResponse(SDIO_RESP3);
2381     hsd->CID[3] = SDIO_GetResponse(SDIO_RESP4);
2382   }
2383 
2384   if((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1)    || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\
2385      (hsd->CardType == SECURE_DIGITAL_IO_COMBO_CARD) || (hsd->CardType == HIGH_CAPACITY_SD_CARD))
2386   {
2387     /* Send CMD3 SET_REL_ADDR with argument 0 */
2388     /* SD Card publishes its RCA. */
2389     sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_REL_ADDR;
2390     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2391     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2392 
2393     /* Check for error conditions */
2394     errorstate = SD_CmdResp6Error(hsd, SD_CMD_SET_REL_ADDR, &sd_rca);
2395 
2396     if(errorstate != SD_OK)
2397     {
2398       return errorstate;
2399     }
2400   }
2401 
2402   if (hsd->CardType != SECURE_DIGITAL_IO_CARD)
2403   {
2404     /* Get the SD card RCA */
2405     hsd->RCA = sd_rca;
2406 
2407     /* Send CMD9 SEND_CSD with argument as card's RCA */
2408     sdio_cmdinitstructure.Argument         = (uint32_t)(hsd->RCA << 16);
2409     sdio_cmdinitstructure.CmdIndex         = SD_CMD_SEND_CSD;
2410     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_LONG;
2411     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2412 
2413     /* Check for error conditions */
2414     errorstate = SD_CmdResp2Error(hsd);
2415 
2416     if(errorstate != SD_OK)
2417     {
2418       return errorstate;
2419     }
2420 
2421     /* Get Card Specific Data */
2422     hsd->CSD[0] = SDIO_GetResponse(SDIO_RESP1);
2423     hsd->CSD[1] = SDIO_GetResponse(SDIO_RESP2);
2424     hsd->CSD[2] = SDIO_GetResponse(SDIO_RESP3);
2425     hsd->CSD[3] = SDIO_GetResponse(SDIO_RESP4);
2426   }
2427 
2428   /* All cards are initialized */
2429   return errorstate;
2430 }
2431 
2432 /**
2433   * @brief  Selects of Deselects the corresponding card.
2434   * @param  hsd: SD handle
2435   * @param  addr: Address of the card to be selected
2436   * @retval SD Card error state
2437   */
SD_Select_Deselect(SD_HandleTypeDef * hsd,uint64_t addr)2438 static HAL_SD_ErrorTypedef SD_Select_Deselect(SD_HandleTypeDef *hsd, uint64_t addr)
2439 {
2440   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
2441   HAL_SD_ErrorTypedef errorstate = SD_OK;
2442 
2443   /* Send CMD7 SDIO_SEL_DESEL_CARD */
2444   sdio_cmdinitstructure.Argument         = (uint32_t)addr;
2445   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SEL_DESEL_CARD;
2446   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2447   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2448   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2449   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2450 
2451   /* Check for error conditions */
2452   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SEL_DESEL_CARD);
2453 
2454   return errorstate;
2455 }
2456 
2457 /**
2458   * @brief  Enquires cards about their operating voltage and configures clock
2459   *         controls and stores SD information that will be needed in future
2460   *         in the SD handle.
2461   * @param  hsd: SD handle
2462   * @retval SD Card error state
2463   */
SD_PowerON(SD_HandleTypeDef * hsd)2464 static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd)
2465 {
2466   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
2467   __IO HAL_SD_ErrorTypedef errorstate = SD_OK;
2468   uint32_t response = 0, count = 0, validvoltage = 0;
2469   uint32_t sdtype = SD_STD_CAPACITY;
2470 
2471   /* Power ON Sequence -------------------------------------------------------*/
2472   /* Disable SDIO Clock */
2473   __HAL_SD_SDIO_DISABLE();
2474 
2475   /* Set Power State to ON */
2476   SDIO_PowerState_ON(hsd->Instance);
2477 
2478   /* 1ms: required power up waiting time before starting the SD initialization
2479      sequence */
2480   HAL_Delay(1);
2481 
2482   /* Enable SDIO Clock */
2483   __HAL_SD_SDIO_ENABLE();
2484 
2485   /* CMD0: GO_IDLE_STATE -----------------------------------------------------*/
2486   /* No CMD response required */
2487   sdio_cmdinitstructure.Argument         = 0;
2488   sdio_cmdinitstructure.CmdIndex         = SD_CMD_GO_IDLE_STATE;
2489   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_NO;
2490   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2491   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2492   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2493 
2494   /* Check for error conditions */
2495   errorstate = SD_CmdError(hsd);
2496 
2497   if(errorstate != SD_OK)
2498   {
2499     /* CMD Response Timeout (wait for CMDSENT flag) */
2500     return errorstate;
2501   }
2502 
2503   /* CMD8: SEND_IF_COND ------------------------------------------------------*/
2504   /* Send CMD8 to verify SD card interface operating condition */
2505   /* Argument: - [31:12]: Reserved (shall be set to '0')
2506   - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V)
2507   - [7:0]: Check Pattern (recommended 0xAA) */
2508   /* CMD Response: R7 */
2509   sdio_cmdinitstructure.Argument         = SD_CHECK_PATTERN;
2510   sdio_cmdinitstructure.CmdIndex         = SD_SDIO_SEND_IF_COND;
2511   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2512   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2513 
2514   /* Check for error conditions */
2515   errorstate = SD_CmdResp7Error(hsd);
2516 
2517   if (errorstate == SD_OK)
2518   {
2519     /* SD Card 2.0 */
2520     hsd->CardType = STD_CAPACITY_SD_CARD_V2_0;
2521     sdtype        = SD_HIGH_CAPACITY;
2522   }
2523 
2524   /* Send CMD55 */
2525   sdio_cmdinitstructure.Argument         = 0;
2526   sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_CMD;
2527   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2528 
2529   /* Check for error conditions */
2530   errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
2531 
2532   /* If errorstate is Command Timeout, it is a MMC card */
2533   /* If errorstate is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch)
2534      or SD card 1.x */
2535   if(errorstate == SD_OK)
2536   {
2537     /* SD CARD */
2538     /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */
2539     while((!validvoltage) && (count < SD_MAX_VOLT_TRIAL))
2540     {
2541 
2542       /* SEND CMD55 APP_CMD with RCA as 0 */
2543       sdio_cmdinitstructure.Argument         = 0;
2544       sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_CMD;
2545       sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2546       sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2547       sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2548       SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2549 
2550       /* Check for error conditions */
2551       errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
2552 
2553       if(errorstate != SD_OK)
2554       {
2555         return errorstate;
2556       }
2557 
2558       /* Send CMD41 */
2559       sdio_cmdinitstructure.Argument         = SD_VOLTAGE_WINDOW_SD | sdtype;
2560       sdio_cmdinitstructure.CmdIndex         = SD_CMD_SD_APP_OP_COND;
2561       sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2562       sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2563       sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2564       SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2565 
2566       /* Check for error conditions */
2567       errorstate = SD_CmdResp3Error(hsd);
2568 
2569       if(errorstate != SD_OK)
2570       {
2571         return errorstate;
2572       }
2573 
2574       /* Get command response */
2575       response = SDIO_GetResponse(SDIO_RESP1);
2576 
2577       /* Get operating voltage*/
2578       validvoltage = (((response >> 31) == 1) ? 1 : 0);
2579 
2580       count++;
2581     }
2582 
2583     if(count >= SD_MAX_VOLT_TRIAL)
2584     {
2585       errorstate = SD_INVALID_VOLTRANGE;
2586 
2587       return errorstate;
2588     }
2589 
2590     if((response & SD_HIGH_CAPACITY) == SD_HIGH_CAPACITY) /* (response &= SD_HIGH_CAPACITY) */
2591     {
2592       hsd->CardType = HIGH_CAPACITY_SD_CARD;
2593     }
2594 
2595   } /* else MMC Card */
2596 
2597   return errorstate;
2598 }
2599 
2600 /**
2601   * @brief  Turns the SDIO output signals off.
2602   * @param  hsd: SD handle
2603   * @retval SD Card error state
2604   */
SD_PowerOFF(SD_HandleTypeDef * hsd)2605 static HAL_SD_ErrorTypedef SD_PowerOFF(SD_HandleTypeDef *hsd)
2606 {
2607   HAL_SD_ErrorTypedef errorstate = SD_OK;
2608 
2609   /* Set Power State to OFF */
2610   SDIO_PowerState_OFF(hsd->Instance);
2611 
2612   return errorstate;
2613 }
2614 
2615 /**
2616   * @brief  Returns the current card's status.
2617   * @param  hsd: SD handle
2618   * @param  pCardStatus: pointer to the buffer that will contain the SD card
2619   *         status (Card Status register)
2620   * @retval SD Card error state
2621   */
SD_SendStatus(SD_HandleTypeDef * hsd,uint32_t * pCardStatus)2622 static HAL_SD_ErrorTypedef SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus)
2623 {
2624   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
2625   HAL_SD_ErrorTypedef errorstate = SD_OK;
2626 
2627   if(pCardStatus == NULL)
2628   {
2629     errorstate = SD_INVALID_PARAMETER;
2630 
2631     return errorstate;
2632   }
2633 
2634   /* Send Status command */
2635   sdio_cmdinitstructure.Argument         = (uint32_t)(hsd->RCA << 16);
2636   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SEND_STATUS;
2637   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
2638   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
2639   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
2640   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
2641 
2642   /* Check for error conditions */
2643   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SEND_STATUS);
2644 
2645   if(errorstate != SD_OK)
2646   {
2647     return errorstate;
2648   }
2649 
2650   /* Get SD card status */
2651   *pCardStatus = SDIO_GetResponse(SDIO_RESP1);
2652 
2653   return errorstate;
2654 }
2655 
2656 /**
2657   * @brief  Checks for error conditions for CMD0.
2658   * @param  hsd: SD handle
2659   * @retval SD Card error state
2660   */
SD_CmdError(SD_HandleTypeDef * hsd)2661 static HAL_SD_ErrorTypedef SD_CmdError(SD_HandleTypeDef *hsd)
2662 {
2663   HAL_SD_ErrorTypedef errorstate = SD_OK;
2664   uint32_t timeout, tmp;
2665 
2666   timeout = SDIO_CMD0TIMEOUT;
2667 
2668   tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDSENT);
2669 
2670   while((timeout > 0) && (!tmp))
2671   {
2672     tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDSENT);
2673     timeout--;
2674   }
2675 
2676   if(timeout == 0)
2677   {
2678     errorstate = SD_CMD_RSP_TIMEOUT;
2679     return errorstate;
2680   }
2681 
2682   /* Clear all the static flags */
2683   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2684 
2685   return errorstate;
2686 }
2687 
2688 /**
2689   * @brief  Checks for error conditions for R7 response.
2690   * @param  hsd: SD handle
2691   * @retval SD Card error state
2692   */
SD_CmdResp7Error(SD_HandleTypeDef * hsd)2693 static HAL_SD_ErrorTypedef SD_CmdResp7Error(SD_HandleTypeDef *hsd)
2694 {
2695   HAL_SD_ErrorTypedef errorstate = SD_ERROR;
2696   uint32_t timeout = SDIO_CMD0TIMEOUT, tmp;
2697 
2698   tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT);
2699 
2700   while((!tmp) && (timeout > 0))
2701   {
2702     tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT);
2703     timeout--;
2704   }
2705 
2706   tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
2707 
2708   if((timeout == 0) || tmp)
2709   {
2710     /* Card is not V2.0 compliant or card does not support the set voltage range */
2711     errorstate = SD_CMD_RSP_TIMEOUT;
2712 
2713     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
2714 
2715     return errorstate;
2716   }
2717 
2718   if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDREND))
2719   {
2720     /* Card is SD V2.0 compliant */
2721     errorstate = SD_OK;
2722 
2723     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CMDREND);
2724 
2725     return errorstate;
2726   }
2727 
2728   return errorstate;
2729 }
2730 
2731 /**
2732   * @brief  Checks for error conditions for R1 response.
2733   * @param  hsd: SD handle
2734   * @param  SD_CMD: The sent command index
2735   * @retval SD Card error state
2736   */
SD_CmdResp1Error(SD_HandleTypeDef * hsd,uint8_t SD_CMD)2737 static HAL_SD_ErrorTypedef SD_CmdResp1Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD)
2738 {
2739   HAL_SD_ErrorTypedef errorstate = SD_OK;
2740   uint32_t response_r1;
2741 
2742   while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
2743   {
2744   }
2745 
2746   if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
2747   {
2748     errorstate = SD_CMD_RSP_TIMEOUT;
2749 
2750     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
2751 
2752     return errorstate;
2753   }
2754   else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
2755   {
2756     errorstate = SD_CMD_CRC_FAIL;
2757 
2758     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
2759 
2760     return errorstate;
2761   }
2762   else
2763   {
2764     /* No error flag set */
2765   }
2766 
2767   /* Check response received is of desired command */
2768   if(SDIO_GetCommandResponse(hsd->Instance) != SD_CMD)
2769   {
2770     errorstate = SD_ILLEGAL_CMD;
2771 
2772     return errorstate;
2773   }
2774 
2775   /* Clear all the static flags */
2776   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2777 
2778   /* We have received response, retrieve it for analysis  */
2779   response_r1 = SDIO_GetResponse(SDIO_RESP1);
2780 
2781   if((response_r1 & SD_OCR_ERRORBITS) == SD_ALLZERO)
2782   {
2783     return errorstate;
2784   }
2785 
2786   if((response_r1 & SD_OCR_ADDR_OUT_OF_RANGE) == SD_OCR_ADDR_OUT_OF_RANGE)
2787   {
2788     return(SD_ADDR_OUT_OF_RANGE);
2789   }
2790 
2791   if((response_r1 & SD_OCR_ADDR_MISALIGNED) == SD_OCR_ADDR_MISALIGNED)
2792   {
2793     return(SD_ADDR_MISALIGNED);
2794   }
2795 
2796   if((response_r1 & SD_OCR_BLOCK_LEN_ERR) == SD_OCR_BLOCK_LEN_ERR)
2797   {
2798     return(SD_BLOCK_LEN_ERR);
2799   }
2800 
2801   if((response_r1 & SD_OCR_ERASE_SEQ_ERR) == SD_OCR_ERASE_SEQ_ERR)
2802   {
2803     return(SD_ERASE_SEQ_ERR);
2804   }
2805 
2806   if((response_r1 & SD_OCR_BAD_ERASE_PARAM) == SD_OCR_BAD_ERASE_PARAM)
2807   {
2808     return(SD_BAD_ERASE_PARAM);
2809   }
2810 
2811   if((response_r1 & SD_OCR_WRITE_PROT_VIOLATION) == SD_OCR_WRITE_PROT_VIOLATION)
2812   {
2813     return(SD_WRITE_PROT_VIOLATION);
2814   }
2815 
2816   if((response_r1 & SD_OCR_LOCK_UNLOCK_FAILED) == SD_OCR_LOCK_UNLOCK_FAILED)
2817   {
2818     return(SD_LOCK_UNLOCK_FAILED);
2819   }
2820 
2821   if((response_r1 & SD_OCR_COM_CRC_FAILED) == SD_OCR_COM_CRC_FAILED)
2822   {
2823     return(SD_COM_CRC_FAILED);
2824   }
2825 
2826   if((response_r1 & SD_OCR_ILLEGAL_CMD) == SD_OCR_ILLEGAL_CMD)
2827   {
2828     return(SD_ILLEGAL_CMD);
2829   }
2830 
2831   if((response_r1 & SD_OCR_CARD_ECC_FAILED) == SD_OCR_CARD_ECC_FAILED)
2832   {
2833     return(SD_CARD_ECC_FAILED);
2834   }
2835 
2836   if((response_r1 & SD_OCR_CC_ERROR) == SD_OCR_CC_ERROR)
2837   {
2838     return(SD_CC_ERROR);
2839   }
2840 
2841   if((response_r1 & SD_OCR_GENERAL_UNKNOWN_ERROR) == SD_OCR_GENERAL_UNKNOWN_ERROR)
2842   {
2843     return(SD_GENERAL_UNKNOWN_ERROR);
2844   }
2845 
2846   if((response_r1 & SD_OCR_STREAM_READ_UNDERRUN) == SD_OCR_STREAM_READ_UNDERRUN)
2847   {
2848     return(SD_STREAM_READ_UNDERRUN);
2849   }
2850 
2851   if((response_r1 & SD_OCR_STREAM_WRITE_OVERRUN) == SD_OCR_STREAM_WRITE_OVERRUN)
2852   {
2853     return(SD_STREAM_WRITE_OVERRUN);
2854   }
2855 
2856   if((response_r1 & SD_OCR_CID_CSD_OVERWRITE) == SD_OCR_CID_CSD_OVERWRITE)
2857   {
2858     return(SD_CID_CSD_OVERWRITE);
2859   }
2860 
2861   if((response_r1 & SD_OCR_WP_ERASE_SKIP) == SD_OCR_WP_ERASE_SKIP)
2862   {
2863     return(SD_WP_ERASE_SKIP);
2864   }
2865 
2866   if((response_r1 & SD_OCR_CARD_ECC_DISABLED) == SD_OCR_CARD_ECC_DISABLED)
2867   {
2868     return(SD_CARD_ECC_DISABLED);
2869   }
2870 
2871   if((response_r1 & SD_OCR_ERASE_RESET) == SD_OCR_ERASE_RESET)
2872   {
2873     return(SD_ERASE_RESET);
2874   }
2875 
2876   if((response_r1 & SD_OCR_AKE_SEQ_ERROR) == SD_OCR_AKE_SEQ_ERROR)
2877   {
2878     return(SD_AKE_SEQ_ERROR);
2879   }
2880 
2881   return errorstate;
2882 }
2883 
2884 /**
2885   * @brief  Checks for error conditions for R3 (OCR) response.
2886   * @param  hsd: SD handle
2887   * @retval SD Card error state
2888   */
SD_CmdResp3Error(SD_HandleTypeDef * hsd)2889 static HAL_SD_ErrorTypedef SD_CmdResp3Error(SD_HandleTypeDef *hsd)
2890 {
2891   HAL_SD_ErrorTypedef errorstate = SD_OK;
2892 
2893   while (!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
2894   {
2895   }
2896 
2897   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
2898   {
2899     errorstate = SD_CMD_RSP_TIMEOUT;
2900 
2901     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
2902 
2903     return errorstate;
2904   }
2905 
2906   /* Clear all the static flags */
2907   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2908 
2909   return errorstate;
2910 }
2911 
2912 /**
2913   * @brief  Checks for error conditions for R2 (CID or CSD) response.
2914   * @param  hsd: SD handle
2915   * @retval SD Card error state
2916   */
SD_CmdResp2Error(SD_HandleTypeDef * hsd)2917 static HAL_SD_ErrorTypedef SD_CmdResp2Error(SD_HandleTypeDef *hsd)
2918 {
2919   HAL_SD_ErrorTypedef errorstate = SD_OK;
2920 
2921   while (!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
2922   {
2923   }
2924 
2925   if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
2926   {
2927     errorstate = SD_CMD_RSP_TIMEOUT;
2928 
2929     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
2930 
2931     return errorstate;
2932   }
2933   else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
2934   {
2935     errorstate = SD_CMD_CRC_FAIL;
2936 
2937     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
2938 
2939     return errorstate;
2940   }
2941   else
2942   {
2943     /* No error flag set */
2944   }
2945 
2946   /* Clear all the static flags */
2947   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
2948 
2949   return errorstate;
2950 }
2951 
2952 /**
2953   * @brief  Checks for error conditions for R6 (RCA) response.
2954   * @param  hsd: SD handle
2955   * @param  SD_CMD: The sent command index
2956   * @param  pRCA: Pointer to the variable that will contain the SD card relative
2957   *         address RCA
2958   * @retval SD Card error state
2959   */
SD_CmdResp6Error(SD_HandleTypeDef * hsd,uint8_t SD_CMD,uint16_t * pRCA)2960 static HAL_SD_ErrorTypedef SD_CmdResp6Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD, uint16_t *pRCA)
2961 {
2962   HAL_SD_ErrorTypedef errorstate = SD_OK;
2963   uint32_t response_r1;
2964 
2965   while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
2966   {
2967   }
2968 
2969   if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
2970   {
2971     errorstate = SD_CMD_RSP_TIMEOUT;
2972 
2973     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
2974 
2975     return errorstate;
2976   }
2977   else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
2978   {
2979     errorstate = SD_CMD_CRC_FAIL;
2980 
2981     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
2982 
2983     return errorstate;
2984   }
2985   else
2986   {
2987     /* No error flag set */
2988   }
2989 
2990   /* Check response received is of desired command */
2991   if(SDIO_GetCommandResponse(hsd->Instance) != SD_CMD)
2992   {
2993     errorstate = SD_ILLEGAL_CMD;
2994 
2995     return errorstate;
2996   }
2997 
2998   /* Clear all the static flags */
2999   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
3000 
3001   /* We have received response, retrieve it.  */
3002   response_r1 = SDIO_GetResponse(SDIO_RESP1);
3003 
3004   if((response_r1 & (SD_R6_GENERAL_UNKNOWN_ERROR | SD_R6_ILLEGAL_CMD | SD_R6_COM_CRC_FAILED)) == SD_ALLZERO)
3005   {
3006     *pRCA = (uint16_t) (response_r1 >> 16);
3007 
3008     return errorstate;
3009   }
3010 
3011   if((response_r1 & SD_R6_GENERAL_UNKNOWN_ERROR) == SD_R6_GENERAL_UNKNOWN_ERROR)
3012   {
3013     return(SD_GENERAL_UNKNOWN_ERROR);
3014   }
3015 
3016   if((response_r1 & SD_R6_ILLEGAL_CMD) == SD_R6_ILLEGAL_CMD)
3017   {
3018     return(SD_ILLEGAL_CMD);
3019   }
3020 
3021   if((response_r1 & SD_R6_COM_CRC_FAILED) == SD_R6_COM_CRC_FAILED)
3022   {
3023     return(SD_COM_CRC_FAILED);
3024   }
3025 
3026   return errorstate;
3027 }
3028 
3029 /**
3030   * @brief  Enables the SDIO wide bus mode.
3031   * @param  hsd: SD handle
3032   * @retval SD Card error state
3033   */
SD_WideBus_Enable(SD_HandleTypeDef * hsd)3034 static HAL_SD_ErrorTypedef SD_WideBus_Enable(SD_HandleTypeDef *hsd)
3035 {
3036   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
3037   HAL_SD_ErrorTypedef errorstate = SD_OK;
3038 
3039   uint32_t scr[2] = {0, 0};
3040 
3041   if((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
3042   {
3043     errorstate = SD_LOCK_UNLOCK_FAILED;
3044 
3045     return errorstate;
3046   }
3047 
3048   /* Get SCR Register */
3049   errorstate = SD_FindSCR(hsd, scr);
3050 
3051   if(errorstate != SD_OK)
3052   {
3053     return errorstate;
3054   }
3055 
3056   /* If requested card supports wide bus operation */
3057   if((scr[1] & SD_WIDE_BUS_SUPPORT) != SD_ALLZERO)
3058   {
3059     /* Send CMD55 APP_CMD with argument as card's RCA.*/
3060     sdio_cmdinitstructure.Argument         = (uint32_t)(hsd->RCA << 16);
3061     sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_CMD;
3062     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
3063     sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
3064     sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
3065     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3066 
3067     /* Check for error conditions */
3068     errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
3069 
3070     if(errorstate != SD_OK)
3071     {
3072       return errorstate;
3073     }
3074 
3075     /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */
3076     sdio_cmdinitstructure.Argument         = 2;
3077     sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_SD_SET_BUSWIDTH;
3078     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3079 
3080     /* Check for error conditions */
3081     errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_SD_SET_BUSWIDTH);
3082 
3083     if(errorstate != SD_OK)
3084     {
3085       return errorstate;
3086     }
3087 
3088     return errorstate;
3089   }
3090   else
3091   {
3092     errorstate = SD_REQUEST_NOT_APPLICABLE;
3093 
3094     return errorstate;
3095   }
3096 }
3097 
3098 /**
3099   * @brief  Disables the SDIO wide bus mode.
3100   * @param  hsd: SD handle
3101   * @retval SD Card error state
3102   */
SD_WideBus_Disable(SD_HandleTypeDef * hsd)3103 static HAL_SD_ErrorTypedef SD_WideBus_Disable(SD_HandleTypeDef *hsd)
3104 {
3105   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
3106   HAL_SD_ErrorTypedef errorstate = SD_OK;
3107 
3108   uint32_t scr[2] = {0, 0};
3109 
3110   if((SDIO_GetResponse(SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED)
3111   {
3112     errorstate = SD_LOCK_UNLOCK_FAILED;
3113 
3114     return errorstate;
3115   }
3116 
3117   /* Get SCR Register */
3118   errorstate = SD_FindSCR(hsd, scr);
3119 
3120   if(errorstate != SD_OK)
3121   {
3122     return errorstate;
3123   }
3124 
3125   /* If requested card supports 1 bit mode operation */
3126   if((scr[1] & SD_SINGLE_BUS_SUPPORT) != SD_ALLZERO)
3127   {
3128     /* Send CMD55 APP_CMD with argument as card's RCA */
3129     sdio_cmdinitstructure.Argument         = (uint32_t)(hsd->RCA << 16);
3130     sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_CMD;
3131     sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
3132     sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
3133     sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
3134     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3135 
3136     /* Check for error conditions */
3137     errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
3138 
3139     if(errorstate != SD_OK)
3140     {
3141       return errorstate;
3142     }
3143 
3144     /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */
3145     sdio_cmdinitstructure.Argument         = 0;
3146     sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_SD_SET_BUSWIDTH;
3147     SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3148 
3149     /* Check for error conditions */
3150     errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_SD_SET_BUSWIDTH);
3151 
3152     if(errorstate != SD_OK)
3153     {
3154       return errorstate;
3155     }
3156 
3157     return errorstate;
3158   }
3159   else
3160   {
3161     errorstate = SD_REQUEST_NOT_APPLICABLE;
3162 
3163     return errorstate;
3164   }
3165 }
3166 
3167 
3168 /**
3169   * @brief  Finds the SD card SCR register value.
3170   * @param  hsd: SD handle
3171   * @param  pSCR: pointer to the buffer that will contain the SCR value
3172   * @retval SD Card error state
3173   */
SD_FindSCR(SD_HandleTypeDef * hsd,uint32_t * pSCR)3174 static HAL_SD_ErrorTypedef SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR)
3175 {
3176   SDIO_CmdInitTypeDef  sdio_cmdinitstructure;
3177   SDIO_DataInitTypeDef sdio_datainitstructure;
3178   HAL_SD_ErrorTypedef errorstate = SD_OK;
3179   uint32_t index = 0;
3180   uint32_t tempscr[2] = {0, 0};
3181 
3182   /* Set Block Size To 8 Bytes */
3183   /* Send CMD55 APP_CMD with argument as card's RCA */
3184   sdio_cmdinitstructure.Argument         = 8U;
3185   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SET_BLOCKLEN;
3186   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
3187   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
3188   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
3189   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3190 
3191   /* Check for error conditions */
3192   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN);
3193 
3194   if(errorstate != SD_OK)
3195   {
3196     return errorstate;
3197   }
3198 
3199   /* Send CMD55 APP_CMD with argument as card's RCA */
3200   sdio_cmdinitstructure.Argument         = (uint32_t)((hsd->RCA) << 16);
3201   sdio_cmdinitstructure.CmdIndex         = SD_CMD_APP_CMD;
3202   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3203 
3204   /* Check for error conditions */
3205   errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD);
3206 
3207   if(errorstate != SD_OK)
3208   {
3209     return errorstate;
3210   }
3211   sdio_datainitstructure.DataTimeOut   = SD_DATATIMEOUT;
3212   sdio_datainitstructure.DataLength    = 8;
3213   sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_8B;
3214   sdio_datainitstructure.TransferDir   = SDIO_TRANSFER_DIR_TO_SDIO;
3215   sdio_datainitstructure.TransferMode  = SDIO_TRANSFER_MODE_BLOCK;
3216   sdio_datainitstructure.DPSM          = SDIO_DPSM_ENABLE;
3217   SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure);
3218 
3219   /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */
3220   sdio_cmdinitstructure.Argument         = 0;
3221   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SD_APP_SEND_SCR;
3222   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3223 
3224   /* Check for error conditions */
3225   errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_APP_SEND_SCR);
3226 
3227   if(errorstate != SD_OK)
3228   {
3229     return errorstate;
3230   }
3231 
3232   while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR))
3233   {
3234     if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL))
3235     {
3236       *(tempscr + index) = SDIO_ReadFIFO(hsd->Instance);
3237       index++;
3238     }
3239   }
3240 
3241   if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT))
3242   {
3243     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT);
3244 
3245     errorstate = SD_DATA_TIMEOUT;
3246 
3247     return errorstate;
3248   }
3249   else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL))
3250   {
3251     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL);
3252 
3253     errorstate = SD_DATA_CRC_FAIL;
3254 
3255     return errorstate;
3256   }
3257   else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR))
3258   {
3259     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR);
3260 
3261     errorstate = SD_RX_OVERRUN;
3262 
3263     return errorstate;
3264   }
3265   else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR))
3266   {
3267     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR);
3268 
3269     errorstate = SD_START_BIT_ERR;
3270 
3271     return errorstate;
3272   }
3273   else
3274   {
3275     /* No error flag set */
3276   }
3277 
3278   /* Clear all the static flags */
3279   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
3280 
3281   *(pSCR + 1) = ((tempscr[0] & SD_0TO7BITS) << 24)  | ((tempscr[0] & SD_8TO15BITS) << 8) |\
3282     ((tempscr[0] & SD_16TO23BITS) >> 8) | ((tempscr[0] & SD_24TO31BITS) >> 24);
3283 
3284   *(pSCR) = ((tempscr[1] & SD_0TO7BITS) << 24)  | ((tempscr[1] & SD_8TO15BITS) << 8) |\
3285     ((tempscr[1] & SD_16TO23BITS) >> 8) | ((tempscr[1] & SD_24TO31BITS) >> 24);
3286 
3287   return errorstate;
3288 }
3289 
3290 /**
3291   * @brief  Checks if the SD card is in programming state.
3292   * @param  hsd: SD handle
3293   * @param  pStatus: pointer to the variable that will contain the SD card state
3294   * @retval SD Card error state
3295   */
SD_IsCardProgramming(SD_HandleTypeDef * hsd,uint8_t * pStatus)3296 static HAL_SD_ErrorTypedef SD_IsCardProgramming(SD_HandleTypeDef *hsd, uint8_t *pStatus)
3297 {
3298   SDIO_CmdInitTypeDef sdio_cmdinitstructure;
3299   HAL_SD_ErrorTypedef errorstate = SD_OK;
3300   __IO uint32_t responseR1 = 0;
3301 
3302   sdio_cmdinitstructure.Argument         = (uint32_t)(hsd->RCA << 16);
3303   sdio_cmdinitstructure.CmdIndex         = SD_CMD_SEND_STATUS;
3304   sdio_cmdinitstructure.Response         = SDIO_RESPONSE_SHORT;
3305   sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO;
3306   sdio_cmdinitstructure.CPSM             = SDIO_CPSM_ENABLE;
3307   SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure);
3308 
3309   while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT))
3310   {
3311   }
3312 
3313   if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT))
3314   {
3315     errorstate = SD_CMD_RSP_TIMEOUT;
3316 
3317     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT);
3318 
3319     return errorstate;
3320   }
3321   else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL))
3322   {
3323     errorstate = SD_CMD_CRC_FAIL;
3324 
3325     __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL);
3326 
3327     return errorstate;
3328   }
3329   else
3330   {
3331     /* No error flag set */
3332   }
3333 
3334   /* Check response received is of desired command */
3335   if((uint32_t)SDIO_GetCommandResponse(hsd->Instance) != SD_CMD_SEND_STATUS)
3336   {
3337     errorstate = SD_ILLEGAL_CMD;
3338 
3339     return errorstate;
3340   }
3341 
3342   /* Clear all the static flags */
3343   __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS);
3344 
3345 
3346   /* We have received response, retrieve it for analysis */
3347   responseR1 = SDIO_GetResponse(SDIO_RESP1);
3348 
3349   /* Find out card status */
3350   *pStatus = (uint8_t)((responseR1 >> 9) & 0x0000000F);
3351 
3352   if((responseR1 & SD_OCR_ERRORBITS) == SD_ALLZERO)
3353   {
3354     return errorstate;
3355   }
3356 
3357   if((responseR1 & SD_OCR_ADDR_OUT_OF_RANGE) == SD_OCR_ADDR_OUT_OF_RANGE)
3358   {
3359     return(SD_ADDR_OUT_OF_RANGE);
3360   }
3361 
3362   if((responseR1 & SD_OCR_ADDR_MISALIGNED) == SD_OCR_ADDR_MISALIGNED)
3363   {
3364     return(SD_ADDR_MISALIGNED);
3365   }
3366 
3367   if((responseR1 & SD_OCR_BLOCK_LEN_ERR) == SD_OCR_BLOCK_LEN_ERR)
3368   {
3369     return(SD_BLOCK_LEN_ERR);
3370   }
3371 
3372   if((responseR1 & SD_OCR_ERASE_SEQ_ERR) == SD_OCR_ERASE_SEQ_ERR)
3373   {
3374     return(SD_ERASE_SEQ_ERR);
3375   }
3376 
3377   if((responseR1 & SD_OCR_BAD_ERASE_PARAM) == SD_OCR_BAD_ERASE_PARAM)
3378   {
3379     return(SD_BAD_ERASE_PARAM);
3380   }
3381 
3382   if((responseR1 & SD_OCR_WRITE_PROT_VIOLATION) == SD_OCR_WRITE_PROT_VIOLATION)
3383   {
3384     return(SD_WRITE_PROT_VIOLATION);
3385   }
3386 
3387   if((responseR1 & SD_OCR_LOCK_UNLOCK_FAILED) == SD_OCR_LOCK_UNLOCK_FAILED)
3388   {
3389     return(SD_LOCK_UNLOCK_FAILED);
3390   }
3391 
3392   if((responseR1 & SD_OCR_COM_CRC_FAILED) == SD_OCR_COM_CRC_FAILED)
3393   {
3394     return(SD_COM_CRC_FAILED);
3395   }
3396 
3397   if((responseR1 & SD_OCR_ILLEGAL_CMD) == SD_OCR_ILLEGAL_CMD)
3398   {
3399     return(SD_ILLEGAL_CMD);
3400   }
3401 
3402   if((responseR1 & SD_OCR_CARD_ECC_FAILED) == SD_OCR_CARD_ECC_FAILED)
3403   {
3404     return(SD_CARD_ECC_FAILED);
3405   }
3406 
3407   if((responseR1 & SD_OCR_CC_ERROR) == SD_OCR_CC_ERROR)
3408   {
3409     return(SD_CC_ERROR);
3410   }
3411 
3412   if((responseR1 & SD_OCR_GENERAL_UNKNOWN_ERROR) == SD_OCR_GENERAL_UNKNOWN_ERROR)
3413   {
3414     return(SD_GENERAL_UNKNOWN_ERROR);
3415   }
3416 
3417   if((responseR1 & SD_OCR_STREAM_READ_UNDERRUN) == SD_OCR_STREAM_READ_UNDERRUN)
3418   {
3419     return(SD_STREAM_READ_UNDERRUN);
3420   }
3421 
3422   if((responseR1 & SD_OCR_STREAM_WRITE_OVERRUN) == SD_OCR_STREAM_WRITE_OVERRUN)
3423   {
3424     return(SD_STREAM_WRITE_OVERRUN);
3425   }
3426 
3427   if((responseR1 & SD_OCR_CID_CSD_OVERWRITE) == SD_OCR_CID_CSD_OVERWRITE)
3428   {
3429     return(SD_CID_CSD_OVERWRITE);
3430   }
3431 
3432   if((responseR1 & SD_OCR_WP_ERASE_SKIP) == SD_OCR_WP_ERASE_SKIP)
3433   {
3434     return(SD_WP_ERASE_SKIP);
3435   }
3436 
3437   if((responseR1 & SD_OCR_CARD_ECC_DISABLED) == SD_OCR_CARD_ECC_DISABLED)
3438   {
3439     return(SD_CARD_ECC_DISABLED);
3440   }
3441 
3442   if((responseR1 & SD_OCR_ERASE_RESET) == SD_OCR_ERASE_RESET)
3443   {
3444     return(SD_ERASE_RESET);
3445   }
3446 
3447   if((responseR1 & SD_OCR_AKE_SEQ_ERROR) == SD_OCR_AKE_SEQ_ERROR)
3448   {
3449     return(SD_AKE_SEQ_ERROR);
3450   }
3451 
3452   return errorstate;
3453 }
3454 
3455 /**
3456   * @}
3457   */
3458 
3459 #endif /* STM32L151xD || STM32L152xD || STM32L162xD */
3460 #endif /* HAL_SD_MODULE_ENABLED */
3461 
3462 /**
3463   * @}
3464   */
3465 
3466 /**
3467   * @}
3468   */
3469 
3470 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
3471