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