Add the Labs projects provided in the V10.2.1_191129 zip file.

This commit is contained in:
Richard Barry 2019-12-02 23:39:25 +00:00
parent 46e5937529
commit e5708b38e9
801 changed files with 356576 additions and 0 deletions

View file

@ -0,0 +1,894 @@
/*
* FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab!
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Authors include James Walmsley, Hein Tibosch and Richard Barry
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
*
*/
/* Standard includes. */
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
/* Xilinx library includes. */
#include "xparameters.h"
#include "xil_types.h"
#include "xsdps.h" /* SD device driver */
#include "xsdps_info.h" /* SD info */
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "portmacro.h"
/* FreeRTOS+FAT includes. */
#include "ff_headers.h"
#include "ff_sddisk.h"
#include "ff_sys.h"
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
#include "xil_exception.h"
#include "xscugic_hw.h"
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
#include "uncached_memory.h"
#define sdSIGNATURE 0x41404342
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) (int) (sizeof(x)/sizeof(x)[0])
#endif
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
#define SD_DEVICE_ID XPAR_XSDPS_0_DEVICE_ID
#define HIGH_SPEED_SUPPORT 0x01
#define WIDTH_4_BIT_SUPPORT 0x4
#define SD_CLK_12_MHZ 12000000
#define SD_CLK_25_MHZ 25000000
#define SD_CLK_26_MHZ 26000000
#define SD_CLK_52_MHZ 52000000
#define EXT_CSD_DEVICE_TYPE_BYTE 196
#define EXT_CSD_4_BIT_WIDTH_BYTE 183
#define EXT_CSD_HIGH_SPEED_BYTE 185
#define EXT_CSD_DEVICE_TYPE_HIGH_SPEED 0x3
#define HUNDRED_64_BIT 100ULL
#define BYTES_PER_MB ( 1024ull * 1024ull )
#define SECTORS_PER_MB ( BYTES_PER_MB / 512ull )
#define XSDPS_INTR_NORMAL_ENABLE ( XSDPS_INTR_CC_MASK | XSDPS_INTR_TC_MASK | \
XSDPS_INTR_DMA_MASK | XSDPS_INTR_CARD_INSRT_MASK | XSDPS_INTR_CARD_REM_MASK | \
XSDPS_INTR_ERR_MASK )
/* Two defines used to set or clear the interrupt */
#define INTC_BASE_ADDR XPAR_SCUGIC_CPU_BASEADDR
#define INTC_DIST_BASE_ADDR XPAR_SCUGIC_DIST_BASEADDR
/* Interupt numbers for SDIO units 0 and 1: */
#define SCUGIC_SDIO_0_INTR 0x38
#define SCUGIC_SDIO_1_INTR 0x4F
/* Define a timeout on data transfers for SDIO: */
#define sdWAIT_INT_TIME_OUT_MS 5000UL
/* Define a short timeout, used during card-detection only (CMD1): */
#define sdQUICK_WAIT_INT_TIME_OUT_MS 1000UL
/* XSdPs xSDCardInstance; */
static XSdPs *pxSDCardInstance;
static int sd_disk_status = STA_NOINIT; /* Disk status */
const int drive_nr = 0;
static SemaphoreHandle_t xPlusFATMutex;
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
/* Create a semaphore for each of the two memory-card slots. */
static SemaphoreHandle_t xSDSemaphores[ 2 ];
#endif
static int vSDMMC_Init( int iDriveNumber );
static int vSDMMC_Status( int iDriveNumber );
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
static void vInstallInterrupt( void );
#endif
struct xCACHE_MEMORY_INFO
{
/* Reserve 'uncached' memory for caching sectors, will be passed to the +FAT library. */
uint8_t pucCacheMemory[ 0x10000 ];
/* Reserve 'uncached' memory for i/o to the SD-card. */
uint8_t pucHelpMemory[ 0x40000 ];
XSdPs xSDCardInstance;
};
struct xCACHE_STATS
{
uint32_t xMemcpyReadCount;
uint32_t xMemcpyWriteCount;
uint32_t xPassReadCount;
uint32_t xPassWriteCount;
uint32_t xFailReadCount;
uint32_t xFailWriteCount;
};
struct xCACHE_STATS xCacheStats;
struct xCACHE_MEMORY_INFO *pxCacheMem = NULL;
static const uint8_t *prvStoreSDCardData( const uint8_t *pucBuffer, uint32_t ulByteCount );
static uint8_t *prvReadSDCardData( uint8_t *pucBuffer, uint32_t ulByteCount );
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
void XSdPs_IntrHandler(void *XSdPsPtr);
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
static int32_t prvFFRead( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk )
{
int32_t lReturnCode;
int iResult;
uint8_t *pucReadBuffer;
if( ( pxDisk != NULL ) && /*_RB_ Could this be changed to an assert? */
( pxDisk->ulSignature == sdSIGNATURE ) &&
( pxDisk->xStatus.bIsInitialised != pdFALSE ) &&
( ulSectorNumber < pxDisk->ulNumberOfSectors ) &&
( pxDisk->ulNumberOfSectors - ulSectorNumber ) >= ulSectorCount )
{
iResult = vSDMMC_Status( drive_nr );
if( ( iResult & STA_NODISK ) != 0 )
{
lReturnCode = FF_ERR_DRIVER_NOMEDIUM | FF_ERRFLAG;
FF_PRINTF( "prvFFRead: NOMEDIUM\n" );
}
else if( ( iResult & STA_NOINIT ) != 0 )
{
lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG;
FF_PRINTF( "prvFFRead: NOINIT\n" );
}
else if( ulSectorCount == 0ul )
{
lReturnCode = 0;
}
else
{
/* Convert LBA to byte address if needed */
if( pxSDCardInstance->HCS == 0 )
{
ulSectorNumber *= XSDPS_BLK_SIZE_512_MASK;
}
pucReadBuffer = prvReadSDCardData( pucBuffer, 512UL * ulSectorCount );
if( ucIsCachedMemory( pucReadBuffer ) != pdFALSE )
{
xCacheStats.xFailReadCount++;
}
iResult = XSdPs_ReadPolled( pxSDCardInstance, ulSectorNumber, ulSectorCount, pucReadBuffer );
if( pucBuffer != pucReadBuffer )
{
xCacheStats.xMemcpyReadCount++;
memcpy( pucBuffer, pucReadBuffer, 512 * ulSectorCount );
}
else
{
xCacheStats.xPassReadCount++;
}
if( iResult == XST_SUCCESS )
{
lReturnCode = 0l;
}
else
{
lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG;
}
}
}
else
{
memset( ( void *) pucBuffer, '\0', ulSectorCount * 512 );
if( pxDisk->xStatus.bIsInitialised != pdFALSE )
{
FF_PRINTF( "prvFFRead: warning: %lu + %lu > %lu\n", ulSectorNumber, ulSectorCount, pxDisk->ulNumberOfSectors );
}
lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG;
}
return lReturnCode;
}
/*-----------------------------------------------------------*/
static int32_t prvFFWrite( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk )
{
int32_t lReturnCode;
if( ( pxDisk != NULL ) &&
( pxDisk->ulSignature == sdSIGNATURE ) &&
( pxDisk->xStatus.bIsInitialised != pdFALSE ) &&
( ulSectorNumber < pxDisk->ulNumberOfSectors ) &&
( ( pxDisk->ulNumberOfSectors - ulSectorNumber ) >= ulSectorCount ) )
{
int iResult;
iResult = vSDMMC_Status(drive_nr);
if( ( iResult & STA_NODISK ) != 0 )
{
lReturnCode = FF_ERR_DRIVER_NOMEDIUM | FF_ERRFLAG;
FF_PRINTF( "prvFFWrite: NOMEDIUM\n" );
}
else if( ( iResult & STA_NOINIT ) != 0 )
{
lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_WRITE | FF_ERRFLAG;
FF_PRINTF( "prvFFWrite: NOINIT\n" );
}
else
{
if( ulSectorCount == 0ul )
{
lReturnCode = 0l;
}
else
{
/* Convert LBA to byte address if needed */
if (!(pxSDCardInstance->HCS)) ulSectorNumber *= XSDPS_BLK_SIZE_512_MASK;
pucBuffer = ( uint8_t * )prvStoreSDCardData( pucBuffer, 512UL * ulSectorCount );
if( ucIsCachedMemory( pucBuffer ) != pdFALSE )
{
xCacheStats.xFailWriteCount++;
}
iResult = XSdPs_WritePolled( pxSDCardInstance, ulSectorNumber, ulSectorCount, pucBuffer );
if( iResult == XST_SUCCESS )
{
lReturnCode = 0;
}
else
{
FF_PRINTF( "prvFFWrite[%d]: at 0x%X count %ld : %d\n",
(int)drive_nr, (unsigned)ulSectorNumber, ulSectorCount, iResult );
lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_WRITE | FF_ERRFLAG;
}
}
}
}
else
{
lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_WRITE | FF_ERRFLAG;
if( pxDisk->xStatus.bIsInitialised )
{
FF_PRINTF( "prvFFWrite::read: warning: %lu + %lu > %lu\n",
ulSectorNumber, ulSectorCount, pxDisk->ulNumberOfSectors );
}
}
return lReturnCode;
}
/*-----------------------------------------------------------*/
void FF_SDDiskFlush( FF_Disk_t *pxDisk )
{
if( ( pxDisk != NULL ) &&
( pxDisk->xStatus.bIsInitialised != pdFALSE ) &&
( pxDisk->pxIOManager != NULL ) )
{
FF_FlushCache( pxDisk->pxIOManager );
}
}
/*-----------------------------------------------------------*/
static const uint8_t *prvStoreSDCardData( const uint8_t *pucBuffer, uint32_t ulByteCount )
{
const uint8_t *pucReturn;
if( ( ucIsCachedMemory( pucBuffer ) != pdFALSE ) && ( ulByteCount <= sizeof( pxCacheMem->pucHelpMemory ) ) )
{
memcpy( pxCacheMem->pucHelpMemory, pucBuffer, ulByteCount );
pucReturn = pxCacheMem->pucHelpMemory;
xCacheStats.xMemcpyWriteCount++;
}
else
{
pucReturn = pucBuffer;
xCacheStats.xPassWriteCount++;
}
return pucReturn;
}
/*-----------------------------------------------------------*/
static uint8_t *prvReadSDCardData( uint8_t *pucBuffer, uint32_t ulByteCount )
{
uint8_t *pucReturn;
if( ( ucIsCachedMemory( pucBuffer ) != pdFALSE ) && ( ulByteCount <= sizeof( pxCacheMem->pucHelpMemory ) ) )
{
pucReturn = pxCacheMem->pucHelpMemory;
}
else
{
pucReturn = pucBuffer;
}
return pucReturn;
}
/*-----------------------------------------------------------*/
static struct xCACHE_MEMORY_INFO *pucGetSDIOCacheMemory( )
{
if( pxCacheMem == NULL )
{
pxCacheMem = ( struct xCACHE_MEMORY_INFO * ) pucGetUncachedMemory( sizeof( *pxCacheMem ) );
memset( pxCacheMem, '\0', sizeof( *pxCacheMem ) );
}
return pxCacheMem;
}
/*-----------------------------------------------------------*/
/* Initialise the SDIO driver and mount an SD card */
FF_Disk_t *FF_SDDiskInit( const char *pcName )
{
FF_Error_t xFFError;
BaseType_t xPartitionNumber = 0;
FF_CreationParameters_t xParameters;
FF_Disk_t * pxDisk;
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
int iIndex;
#endif
pucGetSDIOCacheMemory();
pxDisk = (FF_Disk_t *)pvPortMalloc( sizeof( *pxDisk ) );
if( pxDisk == NULL )
{
FF_PRINTF( "FF_SDDiskInit: Malloc failed\n" );
}
else if( pxCacheMem == NULL )
{
FF_PRINTF( "FF_SDDiskInit: Cached memory failed\n" );
}
else
{
pxSDCardInstance = &( pxCacheMem->xSDCardInstance );
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
{
for( iIndex = 0; iIndex < ARRAY_SIZE( xSDSemaphores ); iIndex++ )
{
if( xSDSemaphores[ iIndex ] == NULL )
{
xSDSemaphores[ iIndex ] = xSemaphoreCreateBinary();
configASSERT( xSDSemaphores[ iIndex ] != NULL );
}
}
}
#endif
vSDMMC_Init( 0 );
/* Initialise the created disk structure. */
memset( pxDisk, '\0', sizeof( *pxDisk ) );
pxDisk->ulNumberOfSectors = myCSD.sd_last_block_address + 1;
if( xPlusFATMutex == NULL )
{
xPlusFATMutex = xSemaphoreCreateRecursiveMutex();
}
pxDisk->ulSignature = sdSIGNATURE;
if( xPlusFATMutex != NULL)
{
memset( &xParameters, '\0', sizeof( xParameters ) );
xParameters.pucCacheMemory = pxCacheMem->pucCacheMemory;
xParameters.ulMemorySize = sizeof( pxCacheMem->pucCacheMemory );
xParameters.ulSectorSize = 512;
xParameters.fnWriteBlocks = prvFFWrite;
xParameters.fnReadBlocks = prvFFRead;
xParameters.pxDisk = pxDisk;
/* prvFFRead()/prvFFWrite() are not re-entrant and must be protected with
the use of a semaphore. */
xParameters.xBlockDeviceIsReentrant = pdFALSE;
/* The semaphore will be used to protect critical sections in the +FAT driver,
and also to avoid concurrent calls to prvFFRead()/prvFFWrite() from different tasks. */
xParameters.pvSemaphore = ( void * ) xPlusFATMutex;
pxDisk->pxIOManager = FF_CreateIOManger( &xParameters, &xFFError );
if( pxDisk->pxIOManager == NULL )
{
FF_PRINTF( "FF_SDDiskInit: FF_CreateIOManger: %s\n", (const char*)FF_GetErrMessage( xFFError ) );
FF_SDDiskDelete( pxDisk );
pxDisk = NULL;
}
else
{
pxDisk->xStatus.bIsInitialised = pdTRUE;
pxDisk->xStatus.bPartitionNumber = xPartitionNumber;
if( FF_SDDiskMount( pxDisk ) == 0 )
{
FF_SDDiskDelete( pxDisk );
pxDisk = NULL;
}
else
{
if( pcName == NULL )
{
pcName = "/";
}
FF_FS_Add( pcName, pxDisk );
FF_PRINTF( "FF_SDDiskInit: Mounted SD-card as root \"%s\"\n", pcName );
FF_SDDiskShowPartition( pxDisk );
}
}
}
}
return pxDisk;
}
/*-----------------------------------------------------------*/
BaseType_t FF_SDDiskFormat( FF_Disk_t *pxDisk, BaseType_t aPart )
{
FF_Error_t xError;
BaseType_t xReturn = 0;
FF_SDDiskUnmount( pxDisk );
{
/* Format the drive */
xError = FF_Format( pxDisk, aPart, pdFALSE, pdFALSE); // Try FAT32 with large clusters
if( FF_isERR( xError ) )
{
FF_PRINTF( "FF_SDDiskFormat: %s\n", (const char*)FF_GetErrMessage( xError ) );
return 0;
}
else
{
FF_PRINTF( "FF_SDDiskFormat: OK, now remounting\n" );
pxDisk->xStatus.bPartitionNumber = aPart;
xError = FF_SDDiskMount( pxDisk );
FF_PRINTF( "FF_SDDiskFormat: rc %08x\n", ( unsigned )xError );
if( FF_isERR( xError ) == pdFALSE )
{
xReturn = 1;
FF_SDDiskShowPartition( pxDisk );
}
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/* Unmount the volume */
BaseType_t FF_SDDiskUnmount( FF_Disk_t *pxDisk )
{
FF_Error_t xFFError;
BaseType_t xReturn = 1;
if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsMounted != pdFALSE ) )
{
pxDisk->xStatus.bIsMounted = pdFALSE;
xFFError = FF_Unmount( pxDisk );
FF_PRINTF( "FF_SDDiskUnmount: rc %08x\n", ( unsigned )xFFError );
if( FF_isERR( xFFError ) )
{
xReturn = 0;
}
else
{
FF_PRINTF( "Drive unmounted\n" );
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
BaseType_t FF_SDDiskReinit( FF_Disk_t *pxDisk )
{
int iStatus = vSDMMC_Init( 0 ); /* Hard coded index. */
/*_RB_ parameter not used. */
( void ) pxDisk;
FF_PRINTF( "FF_SDDiskReinit: rc %08x\n", ( unsigned )iStatus );
return iStatus;
}
/*-----------------------------------------------------------*/
BaseType_t FF_SDDiskMount( FF_Disk_t *pxDisk )
{
FF_Error_t xFFError;
BaseType_t xReturn = 1;
/* Mount the partition */
xFFError = FF_Mount( pxDisk, pxDisk->xStatus.bPartitionNumber );
if( FF_isERR( xFFError ) )
{
FF_PRINTF( "FF_SDDiskMount: %08lX\n", xFFError );
xReturn = 0;
}
else
{
pxDisk->xStatus.bIsMounted = pdTRUE;
FF_PRINTF( "****** FreeRTOS+FAT initialized %lu sectors\n", pxDisk->pxIOManager->xPartition.ulTotalSectors );
}
return xReturn;
}
/*-----------------------------------------------------------*/
/* Get a pointer to IOMAN, which can be used for all FreeRTOS+FAT functions */
FF_IOManager_t *sddisk_ioman( FF_Disk_t *pxDisk )
{
FF_IOManager_t *pxReturn;
if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) )
{
pxReturn = pxDisk->pxIOManager;
}
else
{
pxReturn = NULL;
}
return pxReturn;
}
/*-----------------------------------------------------------*/
/* Release all resources */
BaseType_t FF_SDDiskDelete( FF_Disk_t *pxDisk )
{
if( pxDisk != NULL )
{
pxDisk->ulSignature = 0;
pxDisk->xStatus.bIsInitialised = 0;
if( pxDisk->pxIOManager != NULL )
{
if( FF_Mounted( pxDisk->pxIOManager ) != pdFALSE )
{
FF_Unmount( pxDisk );
}
FF_DeleteIOManager( pxDisk->pxIOManager );
}
vPortFree( pxDisk );
}
return 1;
}
/*-----------------------------------------------------------*/
BaseType_t FF_SDDiskShowPartition( FF_Disk_t *pxDisk )
{
FF_Error_t xError;
uint64_t ullFreeSectors;
uint32_t ulTotalSizeMB, ulFreeSizeMB;
int iPercentageFree;
FF_IOManager_t *pxIOManager;
const char *pcTypeName = "unknown type";
BaseType_t xReturn = pdPASS;
if( pxDisk == NULL )
{
xReturn = pdFAIL;
}
else
{
pxIOManager = pxDisk->pxIOManager;
FF_PRINTF( "Reading FAT and calculating Free Space\n" );
switch( pxIOManager->xPartition.ucType )
{
case FF_T_FAT12:
pcTypeName = "FAT12";
break;
case FF_T_FAT16:
pcTypeName = "FAT16";
break;
case FF_T_FAT32:
pcTypeName = "FAT32";
break;
default:
pcTypeName = "UNKOWN";
break;
}
FF_GetFreeSize( pxIOManager, &xError );
ullFreeSectors = pxIOManager->xPartition.ulFreeClusterCount * pxIOManager->xPartition.ulSectorsPerCluster;
iPercentageFree = ( int ) ( ( HUNDRED_64_BIT * ullFreeSectors + pxIOManager->xPartition.ulDataSectors / 2 ) /
( ( uint64_t )pxIOManager->xPartition.ulDataSectors ) );
ulTotalSizeMB = pxIOManager->xPartition.ulDataSectors / SECTORS_PER_MB;
ulFreeSizeMB = ( uint32_t ) ( ullFreeSectors / SECTORS_PER_MB );
/* It is better not to use the 64-bit format such as %Lu because it
might not be implemented. */
FF_PRINTF( "Partition Nr %8u\n", pxDisk->xStatus.bPartitionNumber );
FF_PRINTF( "Type %8u (%s)\n", pxIOManager->xPartition.ucType, pcTypeName );
FF_PRINTF( "VolLabel '%8s' \n", pxIOManager->xPartition.pcVolumeLabel );
FF_PRINTF( "TotalSectors %8lu\n", pxIOManager->xPartition.ulTotalSectors );
FF_PRINTF( "DataSectors %8lu\n", pxIOManager->xPartition.ulDataSectors );
FF_PRINTF( "SecsPerCluster %8lu\n", pxIOManager->xPartition.ulSectorsPerCluster );
FF_PRINTF( "Size %8lu MB\n", ulTotalSizeMB );
FF_PRINTF( "FreeSize %8lu MB ( %d perc free )\n", ulFreeSizeMB, iPercentageFree );
FF_PRINTF( "BeginLBA %8lu\n", pxIOManager->xPartition.ulBeginLBA );
FF_PRINTF( "FATBeginLBA %8lu\n", pxIOManager->xPartition.ulFATBeginLBA );
}
return xReturn;
}
/*-----------------------------------------------------------*/
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
static void vInstallInterrupt( void )
{
/* Install an interrupt handler for SDIO_0 */
XScuGic_RegisterHandler( INTC_BASE_ADDR, SCUGIC_SDIO_0_INTR,
( Xil_ExceptionHandler )XSdPs_IntrHandler,
( void * )pxSDCardInstance );
/* Enable this interrupt. */
XScuGic_EnableIntr( INTC_DIST_BASE_ADDR, SCUGIC_SDIO_0_INTR );
/* Choose the signals. */
XSdPs_WriteReg16(pxSDCardInstance->Config.BaseAddress,
XSDPS_NORM_INTR_SIG_EN_OFFSET,
XSDPS_INTR_NORMAL_ENABLE );
XSdPs_WriteReg16(pxSDCardInstance->Config.BaseAddress,
XSDPS_ERR_INTR_SIG_EN_OFFSET,
0x0 );
}
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
/*-----------------------------------------------------------*/
static int vSDMMC_Init( int iDriveNumber )
{
int iReturnCode, iStatus;
XSdPs_Config *SdConfig;
/*_RB_ Function name not following convention, parameter not used, parameter
using plain int type. */
/* Open a do {} while(0) loop to allow the use of break. */
do
{
/* Check if card is in the socket */
iStatus = vSDMMC_Status( iDriveNumber );
if( ( iStatus & STA_NODISK ) != 0 )
{
break;
}
/* Assume that the initialisation will fail: set the 'STA_NOINIT' bit. */
iStatus |= STA_NOINIT;
/* Initialize the host controller */
SdConfig = XSdPs_LookupConfig(SD_DEVICE_ID);
if( SdConfig == NULL )
{
break;
}
iReturnCode = XSdPs_CfgInitialize(pxSDCardInstance, SdConfig, SdConfig->BaseAddress);
if( iReturnCode != XST_SUCCESS )
{
break;
}
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
{
vInstallInterrupt();
}
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
iReturnCode = XSdPs_CardInitialize( pxSDCardInstance );
if( iReturnCode != XST_SUCCESS )
{
break;
}
/* Disk is initialized OK: clear the 'STA_NOINIT' bit. */
iStatus &= ~( STA_NOINIT );
} while( 0 );
sd_disk_status = iStatus;
return iStatus;
}
/*-----------------------------------------------------------*/
static int vSDMMC_Status( int iDriveNumber )
{
int iStatus = sd_disk_status;
u32 ulStatusReg;
/*_RB_ Function name not following convention, parameter not used, parameter
using plain int type. */
( void ) iDriveNumber;
ulStatusReg = XSdPs_GetPresentStatusReg( XPAR_XSDPS_0_BASEADDR );
if( ( ulStatusReg & XSDPS_PSR_CARD_INSRT_MASK ) == 0 )
{
iStatus = STA_NODISK | STA_NOINIT;
}
else
{
iStatus &= ~STA_NODISK;
if( ( ulStatusReg & XSDPS_PSR_WPS_PL_MASK ) != 0 )
{
iStatus &= ~STA_PROTECT;
}
else
{
iStatus |= STA_PROTECT;
}
}
sd_disk_status = iStatus;
return iStatus;
}
/*-----------------------------------------------------------*/
BaseType_t FF_SDDiskInserted( BaseType_t xDriveNr )
{
BaseType_t xReturn;
int iStatus;
/* Check if card is in the socket */
iStatus = vSDMMC_Status( xDriveNr );
if( ( iStatus & STA_NODISK ) != 0 )
{
xReturn = pdFALSE;
}
else
{
xReturn = pdTRUE;
}
return xReturn;
}
volatile unsigned sd_int_count = 0;
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
volatile u32 ulSDInterruptStatus[2];
void XSdPs_IntrHandler(void *XSdPsPtr)
{
XSdPs *InstancePtr = (XSdPs *)XSdPsPtr;
int iIndex = InstancePtr->Config.DeviceId;
uint32_t ulStatusReg;
configASSERT( iIndex <= 1 );
sd_int_count++;
/* Read the current status. */
ulStatusReg = XSdPs_ReadReg( InstancePtr->Config.BaseAddress, XSDPS_NORM_INTR_STS_OFFSET );
/* Write to clear error bits. */
XSdPs_WriteReg( InstancePtr->Config.BaseAddress, XSDPS_NORM_INTR_STS_OFFSET, ulStatusReg );
/* The new value must be OR-ed, if not the
Command Complete (CC) event might get overwritten
by the Transfer Complete (TC) event. */
ulSDInterruptStatus[ iIndex ] |= ulStatusReg;
if( ( ulStatusReg & ( XSDPS_INTR_CARD_INSRT_MASK | XSDPS_INTR_CARD_REM_MASK ) ) != 0 )
{
/* Could wake-up another task. */
}
if( xSDSemaphores[ iIndex ] != NULL )
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xSemaphoreGiveFromISR( xSDSemaphores[ iIndex ], &xHigherPriorityTaskWoken );
if( xHigherPriorityTaskWoken != 0 )
{
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
}
}
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
/*-----------------------------------------------------------*/
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
void XSdPs_ClearInterrupt( XSdPs *InstancePtr )
{
int iIndex = InstancePtr->Config.DeviceId;
configASSERT( iIndex <= 1 );
ulSDInterruptStatus[ iIndex ] = 0;
}
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
/*-----------------------------------------------------------*/
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
/* Wait for an interrupt and return the 32 bits of the status register.
A return value of 0 means: time-out. */
u32 XSdPs_WaitInterrupt( XSdPs *InstancePtr, u32 ulMask, u32 ulWait )
{
u32 ulStatusReg;
int iIndex = InstancePtr->Config.DeviceId;
TickType_t xRemainingTime = pdMS_TO_TICKS( sdWAIT_INT_TIME_OUT_MS );
TimeOut_t xTimeOut;
if( ulWait == 0UL )
{
xRemainingTime = pdMS_TO_TICKS( sdQUICK_WAIT_INT_TIME_OUT_MS );
}
configASSERT( iIndex <= 1 );
configASSERT( xSDSemaphores[ iIndex ] != 0 );
vTaskSetTimeOutState( &xTimeOut );
/* Loop until:
1. Expected bit (ulMask) becomes high
2. Time-out reached (normally 2 seconds)
*/
do
{
if( xRemainingTime != 0 )
{
xSemaphoreTake( xSDSemaphores[ iIndex ], xRemainingTime );
}
ulStatusReg = ulSDInterruptStatus[ iIndex ];
if( ( ulStatusReg & XSDPS_INTR_ERR_MASK ) != 0 )
{
break;
}
}
while( ( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) == pdFALSE ) &&
( ( ulStatusReg & ulMask ) == 0 ) );
if( ( ulStatusReg & ulMask ) == 0 )
{
ulStatusReg = XSdPs_ReadReg( InstancePtr->Config.BaseAddress, XSDPS_NORM_INTR_STS_OFFSET );
if( ulWait != 0UL )
{
FF_PRINTF( "XSdPs_WaitInterrupt[ %d ]: Got %08lx, expect %08lx ints: %d\n",
iIndex,
ulStatusReg,
ulMask,
sd_int_count );
}
}
return ulStatusReg;
}
#endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */
/*-----------------------------------------------------------*/

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,221 @@
/******************************************************************************
*
* Copyright (C) 2013 - 2015 Xilinx, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Use of the Software is limited solely to applications:
* (a) running on a Xilinx device, or
* (b) that interact with a Xilinx device through a bus or interconnect.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xsdps.h
* @addtogroup sdps_v2_5
* @{
* @details
*
* This file contains the implementation of XSdPs driver.
* This driver is used initialize read from and write to the SD card.
* Features such as switching bus width to 4-bit and switching to high speed,
* changing clock frequency, block size etc. are supported.
* SD 2.0 uses 1/4 bus width and speeds of 25/50KHz. Initialization, however
* is done using 1-bit bus width and 400KHz clock frequency.
* SD commands are classified as broadcast and addressed. Commands can be
* those with response only (using only command line) or
* response + data (using command and data lines).
* Only one command can be sent at a time. During a data transfer however,
* when dsta lines are in use, certain commands (which use only the command
* line) can be sent, most often to obtain status.
* This driver does not support multi card slots at present.
*
* Intialization:
* This includes initialization on the host controller side to select
* clock frequency, bus power and default transfer related parameters.
* The default voltage is 3.3V.
* On the SD card side, the initialization and identification state diagram is
* implemented. This resets the card, gives it a unique address/ID and
* identifies key card related specifications.
*
* Data transfer:
* The SD card is put in tranfer state to read from or write to it.
* The default block size is 512 bytes and if supported,
* default bus width is 4-bit and bus speed is High speed.
* The read and write functions are implemented in polled mode using ADMA2.
*
* At any point, when key parameters such as block size or
* clock/speed or bus width are modified, this driver takes care of
* maintaining the same selection on host and card.
* All error bits in host controller are monitored by the driver and in the
* event one of them is set, driver will clear the interrupt status and
* communicate failure to the upper layer.
*
* File system use:
* This driver can be used with xilffs library to read and write files to SD.
* (Please refer to procedure in diskio.c). The file system read/write example
* in polled mode can used for reference.
*
* There is no example for using SD driver without file system at present.
* However, the driver can be used without the file system. The glue layer
* in filesytem can be used as reference for the same. The block count
* passed to the read/write function in one call is limited by the ADMA2
* descriptor table and hence care will have to be taken to call read/write
* API's in a loop for large file sizes.
*
* Interrupt mode is not supported because it offers no improvement when used
* with file system.
*
* eMMC support:
* SD driver supports SD and eMMC based on the "enable MMC" parameter in SDK.
* The features of eMMC supported by the driver will depend on those supported
* by the host controller. The current driver supports read/write on eMMC card
* using 4-bit and high speed mode currently.
*
* Features not supported include - card write protect, password setting,
* lock/unlock, interrupts, SDMA mode, programmed I/O mode and
* 64-bit addressed ADMA2, erase/pre-erase commands.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.00a hk/sg 10/17/13 Initial release
* 2.0 hk 03/07/14 Version number revised.
* 2.1 hk 04/18/14 Increase sleep for eMMC switch command.
* Add sleep for microblaze designs. CR# 781117.
* 2.2 hk 07/28/14 Make changes to enable use of data cache.
* 2.3 sk 09/23/14 Send command for relative card address
* when re-initialization is done.CR# 819614.
* Use XSdPs_Change_ClkFreq API whenever changing
* clock.CR# 816586.
* 2.4 sk 12/04/14 Added support for micro SD without
* WP/CD. CR# 810655.
* Checked for DAT Inhibit mask instead of CMD
* Inhibit mask in Cmd Transfer API.
* Added Support for SD Card v1.0
* 2.5 sg 07/09/15 Added SD 3.0 features
* kvn 07/15/15 Modified the code according to MISRAC-2012.
* 2.6 sk 10/12/15 Added support for SD card v1.0 CR# 840601.
*
* </pre>
*
******************************************************************************/
#ifndef SDPS_H_
#define SDPS_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "xstatus.h"
#include "xsdps_hw.h"
#include <string.h>
/************************** Constant Definitions *****************************/
#define XSDPS_CT_ERROR 0x2U /**< Command timeout flag */
/**************************** Type Definitions *******************************/
/**
* This typedef contains configuration information for the device.
*/
typedef struct {
u16 DeviceId; /**< Unique ID of device */
u32 BaseAddress; /**< Base address of the device */
u32 InputClockHz; /**< Input clock frequency */
u32 CardDetect; /**< Card Detect */
u32 WriteProtect; /**< Write Protect */
} XSdPs_Config;
/* ADMA2 descriptor table */
typedef struct {
u16 Attribute; /**< Attributes of descriptor */
u16 Length; /**< Length of current dma transfer */
u32 Address; /**< Address of current dma transfer */
} XSdPs_Adma2Descriptor;
/**
* The XSdPs driver instance data. The user is required to allocate a
* variable of this type for every SD device in the system. A pointer
* to a variable of this type is then passed to the driver API functions.
*/
typedef struct {
XSdPs_Config Config; /**< Configuration structure */
u32 IsReady; /**< Device is initialized and ready */
u32 Host_Caps; /**< Capabilities of host controller */
u32 Host_CapsExt; /**< Extended Capabilities */
u32 HCS; /**< High capacity support in card */
u8 CardType; /**< Type of card - SD/MMC/eMMC */
u8 Card_Version; /**< Card version */
u8 HC_Version; /**< Host controller version */
u8 BusWidth; /**< Current operating bus width */
u32 BusSpeed; /**< Current operating bus speed */
u8 Switch1v8; /**< 1.8V Switch support */
u32 CardID[4]; /**< Card ID Register */
u32 RelCardAddr; /**< Relative Card Address */
u32 CardSpecData[4]; /**< Card Specific Data Register */
u32 SdCardConfig; /**< Sd Card Configuration Register */
/**< ADMA Descriptors */
#ifdef __ICCARM__
#pragma data_alignment = 32
XSdPs_Adma2Descriptor Adma2_DescrTbl[32];
#pragma data_alignment = 4
#else
XSdPs_Adma2Descriptor Adma2_DescrTbl[32] __attribute__ ((aligned(32)));
#endif
} XSdPs;
/***************** Macros (Inline Functions) Definitions *********************/
/************************** Function Prototypes ******************************/
XSdPs_Config *XSdPs_LookupConfig(u16 DeviceId);
s32 XSdPs_CfgInitialize(XSdPs *InstancePtr, XSdPs_Config *ConfigPtr,
u32 EffectiveAddr);
s32 XSdPs_SdCardInitialize(XSdPs *InstancePtr);
s32 XSdPs_ReadPolled(XSdPs *InstancePtr, u32 Arg, u32 BlkCnt, u8 *Buff);
s32 XSdPs_WritePolled(XSdPs *InstancePtr, u32 Arg, u32 BlkCnt, const u8 *Buff);
s32 XSdPs_SetBlkSize(XSdPs *InstancePtr, u16 BlkSize);
s32 XSdPs_Select_Card (XSdPs *InstancePtr);
s32 XSdPs_Change_ClkFreq(XSdPs *InstancePtr, u32 SelFreq);
s32 XSdPs_Change_BusWidth(XSdPs *InstancePtr);
s32 XSdPs_Change_BusSpeed(XSdPs *InstancePtr);
s32 XSdPs_Get_BusWidth(XSdPs *InstancePtr, u8 *SCR);
s32 XSdPs_Get_BusSpeed(XSdPs *InstancePtr, u8 *ReadBuff);
s32 XSdPs_Pullup(XSdPs *InstancePtr);
s32 XSdPs_MmcCardInitialize(XSdPs *InstancePtr);
s32 XSdPs_CardInitialize(XSdPs *InstancePtr);
s32 XSdPs_Get_Mmc_ExtCsd(XSdPs *InstancePtr, u8 *ReadBuff);
/* Wait for Command/Transfer Complete. */
s32 XSdPs_Wait_For(XSdPs *InstancePtr, u32 Mask, u32 Wait);
#ifdef __cplusplus
}
#endif
#endif /* SD_H_ */
/** @} */

View file

@ -0,0 +1,69 @@
/******************************************************************************
*
* Copyright (C) 2013 - 2014 Xilinx, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Use of the Software is limited solely to applications:
* (a) running on a Xilinx device, or
* (b) that interact with a Xilinx device through a bus or interconnect.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* XILINX CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xsdps_g.c
*
* This file contains a configuration table that specifies the configuration of
* SD devices in the system.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.00a hk/sg 10/17/13 Initial release
*
* </pre>
*
******************************************************************************/
#include "xparameters.h"
#include "xsdps.h"
/*
* The configuration table for devices
*/
XSdPs_Config XSdPs_ConfigTable[] =
{
{
XPAR_XSDPS_0_DEVICE_ID,
XPAR_XSDPS_0_BASEADDR,
XPAR_XSDPS_0_SDIO_CLK_FREQ_HZ,
0,
0
}
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,300 @@
/******************************************************************************
*
* mmc_decode_cid() and sd_decode_csd()
*
* analyse the meta data of an SD-card to read its capacity and some other properties.
*
* CID and CSD Analysis borrowed from the Linux kernel.
*
******************************************************************************/
#include "xsdps.h"
#include "xparameters.h"
#include "xil_cache.h"
#include "ff_headers.h"
#include "xsdps_info.h"
struct mmc_cid myCID;
struct mmc_csd myCSD;
u32 UNSTUFF_BITS( u32 *ulResponse, int iFirst, int iSize )
{
const u32 ulMask = ( iSize < 32 ? ( 1 << iSize ) : 0 ) - 1;
const int iOffset = 3 - ( iFirst / 32);
const int iShiftCount = iFirst & 31;
u32 ulResult;
ulResult = ulResponse[ iOffset ] >> iShiftCount;
if( iSize + iShiftCount > 32 )
{
ulResult |= ulResponse[ iOffset - 1 ] << ( ( 32 - iShiftCount ) % 32 );
}
return ulResult & ulMask; \
}
int mmc_decode_cid( const struct mmc_csd *pxCSD, struct mmc_cid *pxCID, u32 *ulResponse )
{
int iResult = 0;
/*
* The selection of the format here is based upon published
* specs from sandisk and from what people have reported.
*/
switch( pxCSD->mmca_vsn )
{
case 0: /* MMC v1.0 - v1.2 */
case 1: /* MMC v1.4 */
pxCID->manfid = UNSTUFF_BITS( ulResponse, 104, 24 );
pxCID->prod_name[ 0 ] = UNSTUFF_BITS( ulResponse, 96, 8 );
pxCID->prod_name[ 1 ] = UNSTUFF_BITS( ulResponse, 88, 8 );
pxCID->prod_name[ 2 ] = UNSTUFF_BITS( ulResponse, 80, 8 );
pxCID->prod_name[ 3 ] = UNSTUFF_BITS( ulResponse, 72, 8 );
pxCID->prod_name[ 4 ] = UNSTUFF_BITS( ulResponse, 64, 8 );
pxCID->prod_name[ 5 ] = UNSTUFF_BITS( ulResponse, 56, 8 );
pxCID->prod_name[ 6 ] = UNSTUFF_BITS( ulResponse, 48, 8 );
pxCID->hwrev = UNSTUFF_BITS( ulResponse, 44, 4 );
pxCID->fwrev = UNSTUFF_BITS( ulResponse, 40, 4 );
pxCID->serial = UNSTUFF_BITS( ulResponse, 16, 24 );
pxCID->month = UNSTUFF_BITS( ulResponse, 12, 4 );
pxCID->year = UNSTUFF_BITS( ulResponse, 8, 4 ) + 1997;
break;
case 2: /* MMC v2.0 - v2.2 */
case 3: /* MMC v3.1 - v3.3 */
case 4: /* MMC v4 */
pxCID->manfid = UNSTUFF_BITS( ulResponse, 120, 8 );
pxCID->oemid = UNSTUFF_BITS( ulResponse, 104, 16 );
pxCID->prod_name[ 0 ] = UNSTUFF_BITS( ulResponse, 96, 8 );
pxCID->prod_name[ 1 ] = UNSTUFF_BITS( ulResponse, 88, 8 );
pxCID->prod_name[ 2 ] = UNSTUFF_BITS( ulResponse, 80, 8 );
pxCID->prod_name[ 3 ] = UNSTUFF_BITS( ulResponse, 72, 8 );
pxCID->prod_name[ 4 ] = UNSTUFF_BITS( ulResponse, 64, 8 );
pxCID->prod_name[ 5 ] = UNSTUFF_BITS( ulResponse, 56, 8 );
pxCID->serial = UNSTUFF_BITS( ulResponse, 16, 32 );
pxCID->month = UNSTUFF_BITS( ulResponse, 12, 4 );
pxCID->year = UNSTUFF_BITS( ulResponse, 8, 4 ) + 1997;
break;
default:
FF_PRINTF ("mmc_decode_cid: card has unknown MMCA version %d\n",
pxCSD->mmca_vsn);
iResult = -1;
break;
}
if( iResult >= 0 )
{
FF_PRINTF ("CID: Manfid %lu (%-8.8s) serial %lu oem %u mon/year %u/%u rev %u fw %u\n",
pxCID->manfid,
pxCID->prod_name,
pxCID->serial,
pxCID->oemid,
pxCID->month,
pxCID->year,
pxCID->hwrev,
pxCID->fwrev);
}
return iResult;
}
static const unsigned int tran_exp[] =
{
10000, 100000, 1000000, 10000000,
0, 0, 0, 0
};
static const unsigned char tran_mant[] =
{
0, 10, 12, 13, 15, 20, 25, 30,
35, 40, 45, 50, 55, 60, 70, 80,
};
static const unsigned int tacc_exp[] =
{
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
};
static const unsigned int tacc_mant[] =
{
0, 10, 12, 13, 15, 20, 25, 30,
35, 40, 45, 50, 55, 60, 70, 80,
};
char mmc_is_block_addressed;
/* Given a 128-bit response, decode to our card CSD structure. */
static __inline unsigned tobe32( unsigned value )
{
return
( value >> 24 ) |
( ( value >> 8 ) & 0x0000ff00 ) |
( ( value << 8 ) & 0x00ff0000 ) |
( value << 24 );
}
int sd_decode_csd( struct mmc_csd *pxCSD, u32 *ulResponse )
{
unsigned int e, m, csd_struct;
int iResult = 0;
csd_struct = UNSTUFF_BITS( ulResponse, 126, 2 );
pxCSD->mmca_vsn = UNSTUFF_BITS( ulResponse, 122, 4 );
FF_PRINTF("CSD data: %08x %08x %08x %08x mmca_vsn = %u\n",
( unsigned )ulResponse[0],
( unsigned )ulResponse[1],
( unsigned )ulResponse[2],
( unsigned )ulResponse[3],
pxCSD->mmca_vsn);
// pxCSD->mmca_vsn = 2;
// CSD data: 005e0032 5f5a83cb 2db7ffbf 9680000f
// sd_decode_csd: capacity 1989120 (byte addressed)
switch (csd_struct) {
case 0:
m = UNSTUFF_BITS( ulResponse, 115, 4 );
e = UNSTUFF_BITS( ulResponse, 112, 3 );
pxCSD->tacc_ns = ( tacc_exp[ e ] * tacc_mant[ m ] + 9 ) / 10;
pxCSD->tacc_clks = UNSTUFF_BITS( ulResponse, 104, 8 ) * 100;
m = UNSTUFF_BITS( ulResponse, 99, 4 );
e = UNSTUFF_BITS( ulResponse, 96, 3 );
pxCSD->max_dtr = tran_exp[ e ] * tran_mant[ m ];
pxCSD->cmdclass = UNSTUFF_BITS( ulResponse, 84, 12 );
e = UNSTUFF_BITS( ulResponse, 47, 3 );
m = UNSTUFF_BITS( ulResponse, 62, 12 );
pxCSD->capacity = ( 1 + m ) << ( e + 2 );
/*
* The CSD capacity field is in units of read_blkbits.
* set_capacity takes units of 512 bytes.
*/
pxCSD->read_blkbits = UNSTUFF_BITS( ulResponse, 80, 4 );
pxCSD->read_partial = UNSTUFF_BITS( ulResponse, 79, 1 );
pxCSD->write_misalign = UNSTUFF_BITS( ulResponse, 78, 1 );
pxCSD->read_misalign = UNSTUFF_BITS( ulResponse, 77, 1 );
pxCSD->r2w_factor = UNSTUFF_BITS( ulResponse, 26, 3 );
pxCSD->write_blkbits = UNSTUFF_BITS( ulResponse, 22, 4 );
pxCSD->write_partial = UNSTUFF_BITS( ulResponse, 21, 1 );
pxCSD->capacity <<= ( pxCSD->read_blkbits - 9 );
FF_PRINTF ("Capacity: (%u + 1) << (%u + 2) = %u Rd/Wr bits %u/%u\n",
m, e,
( unsigned )pxCSD->capacity,
( unsigned )pxCSD->read_blkbits,
( unsigned )pxCSD->write_blkbits);
if( UNSTUFF_BITS( ulResponse, 46, 1 ) )
{
pxCSD->erase_size = 1;
}
else if( pxCSD->write_blkbits >= 9 )
{
pxCSD->erase_size = UNSTUFF_BITS( ulResponse, 39, 7 ) + 1;
pxCSD->erase_size <<= pxCSD->write_blkbits - 9;
}
else
{
pxCSD->erase_size = 0; // Card is not eraseble
}
break;
case 1:
/*
* This is a block-addressed SDHC card. Most
* interesting fields are unused and have fixed
* values. To avoid getting tripped by buggy cards,
* we assume those fixed values ourselves.
*/
mmc_is_block_addressed = 1;
pxCSD->tacc_ns = 0; /* Unused */
pxCSD->tacc_clks = 0; /* Unused */
m = UNSTUFF_BITS( ulResponse, 99, 4 );
e = UNSTUFF_BITS( ulResponse, 96, 3 );
// max_dtr gives 25,000,000
pxCSD->max_dtr = tran_exp[ e ] * tran_mant[ m ];
// cmdClass gives: 10110110101 (0x5B5)
pxCSD->cmdclass = UNSTUFF_BITS( ulResponse, 84, 12 );
m = UNSTUFF_BITS( ulResponse, 48, 22 );
pxCSD->capacity = ( 1 + m ) << 10;
FF_PRINTF( "capacity: (1 + %u) << 10 DTR %u Mhz\n", m, pxCSD->max_dtr / 1000000);
pxCSD->read_blkbits = 9;
pxCSD->read_partial = 0;
pxCSD->write_misalign = 0;
pxCSD->read_misalign = 0;
pxCSD->r2w_factor = 4; /* Unused */
pxCSD->write_blkbits = 9;
pxCSD->write_partial = 0;
pxCSD->erase_size = 1;
break;
default:
FF_PRINTF ("sd_decode_csd: unrecognised CSD structure version %d\n", csd_struct);
iResult = -1;
break;
}
if( iResult >= 0 )
{
unsigned int sz;
FF_PRINTF ("sd_decode_csd: capacity %lu (%s addressed)\n",
pxCSD->capacity, mmc_is_block_addressed ? "block" : "byte");
sz = (pxCSD->capacity << (pxCSD->read_blkbits - 9)) >> 11;
if (sz < 128)
{
pxCSD->pref_erase = 512 * 1024 / 512;
}
else if (sz < 512)
{
pxCSD->pref_erase = 1024 * 1024 / 512;
}
else if (sz < 1024)
{
pxCSD->pref_erase = 2 * 1024 * 1024 / 512;
}
else
{
pxCSD->pref_erase = 4 * 1024 * 1024 / 512;
}
if (pxCSD->pref_erase < pxCSD->erase_size)
{
pxCSD->pref_erase = pxCSD->erase_size;
}
else
{
sz = ( pxCSD->pref_erase % pxCSD->erase_size );
if( sz != 0 )
{
pxCSD->pref_erase += ( pxCSD->erase_size - sz );
}
}
// compute last block addr
pxCSD->sd_last_block_address = pxCSD->capacity - 1;
// compute card capacity in bytes
pxCSD->capacity_bytes = ( ( uint64_t )XSDPS_BLK_SIZE_512_MASK ) * pxCSD->capacity;
FF_PRINTF( "sd_mmc_spi_get_capacity: Capacity %lu MB Erase %u Pref %lu\n",
( uint32_t ) ( pxCSD->capacity_bytes / ( 1024LLU * 1024LLU ) ),
pxCSD->erase_size,
pxCSD->pref_erase );
}
return iResult;
}

View file

@ -0,0 +1,56 @@
/******************************************************************************
*
* mmc_decode_cid() and sd_decode_csd()
*
* analyse the meta data of an SD-card to read its capacity and some other properties.
*
* CID and CSD Analysis borrowed from the Linux kernel.
*
******************************************************************************/
#ifndef SDPS_INFO_H_
#define SDPS_INFO_H_ 1
#include <stdint.h>
struct mmc_cid {
uint32_t manfid;
char prod_name[8];
uint32_t serial;
uint16_t oemid;
uint16_t year;
uint8_t hwrev;
uint8_t fwrev;
uint8_t month;
};
struct mmc_csd {
volatile uint64_t capacity_bytes;
uint32_t sd_last_block_address;
uint8_t mmca_vsn;
uint16_t erase_size;
uint8_t spare;
uint16_t cmdclass;
uint16_t tacc_clks;
int32_t erase_shift;
uint32_t tacc_ns;
uint32_t r2w_factor;
uint32_t max_dtr;
uint32_t read_blkbits;
uint32_t write_blkbits;
uint32_t capacity;
uint32_t pref_erase;
uint32_t read_partial : 1,
read_misalign : 1,
write_partial : 1,
write_misalign : 1;
};
extern struct mmc_cid myCID;
extern struct mmc_csd myCSD;
int mmc_decode_cid( const struct mmc_csd *pxCSD, struct mmc_cid *pxCID, uint32_t *raw_data );
int sd_decode_csd( struct mmc_csd *pxCSD, uint32_t *ulResponse );
#endif /* SDPS_INFO_H_ */

View file

@ -0,0 +1,978 @@
/******************************************************************************
*
* Copyright (C) 2013 - 2015 Xilinx, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Use of the Software is limited solely to applications:
* (a) running on a Xilinx device, or
* (b) that interact with a Xilinx device through a bus or interconnect.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xsdps_options.c
* @addtogroup sdps_v2_5
* @{
*
* Contains API's for changing the various options in host and card.
* See xsdps.h for a detailed description of the device and driver.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.00a hk/sg 10/17/13 Initial release
* 2.1 hk 04/18/14 Increase sleep for eMMC switch command.
* Add sleep for microblaze designs. CR# 781117.
* 2.3 sk 09/23/14 Use XSdPs_Change_ClkFreq API whenever changing
* clock.CR# 816586.
* 2.5 sg 07/09/15 Added SD 3.0 features
* kvn 07/15/15 Modified the code according to MISRAC-2012.
*
* </pre>
*
******************************************************************************/
/***************************** Include Files *********************************/
#include "xsdps.h"
#include "xil_cache.h"
/*
* The header sleep.h and API usleep() can only be used with an arm design.
* MB_Sleep() is used for microblaze design.
*/
#if defined (__arm__) || defined (__aarch64__)
#include "sleep.h"
#endif
#ifdef __MICROBLAZE__
#include "microblaze_sleep.h"
#endif
#include <FreeRTOS.h>
#include "task.h"
#include "FreeRTOSFATConfig.h"
#include "uncached_memory.h"
/************************** Constant Definitions *****************************/
/**************************** Type Definitions *******************************/
/***************** Macros (Inline Functions) Definitions *********************/
/************************** Function Prototypes ******************************/
s32 XSdPs_CmdTransfer(XSdPs *InstancePtr, u32 Cmd, u32 Arg, u32 BlkCnt);
void XSdPs_SetupADMA2DescTbl(XSdPs *InstancePtr, u32 BlkCnt, const u8 *Buff);
s32 XSdPs_Uhs_ModeInit(XSdPs *InstancePtr, u8 Mode);
static s32 XSdPs_Execute_Tuning(XSdPs *InstancePtr);
s32 XSdPs_Uhs_ModeInit(XSdPs *InstancePtr, u8 Mode);
#if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 )
/* Declared in ff_sddisk.c :
Function will sleep and get interrupted on a change of
the status register. It will loop until:
1. Expected bit (ulMask) becomes high
2. Time-out reached (normally 2 seconds)
*/
extern u32 XSdPs_WaitInterrupt( XSdPs *InstancePtr, u32 ulMask );
/* Clear the interrupt before using it. */
extern void XSdPs_ClearInterrupt( XSdPs *InstancePtr );
#else
#error Please define ffconfigSDIO_DRIVER_USES_INTERRUPT
#endif
/*****************************************************************************/
/**
* Update Block size for read/write operations.
*
* @param InstancePtr is a pointer to the instance to be worked on.
* @param BlkSize - Block size passed by the user.
*
* @return None
*
******************************************************************************/
s32 XSdPs_SetBlkSize(XSdPs *InstancePtr, u16 BlkSize)
{
s32 Status;
u32 PresentStateReg;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
PresentStateReg = XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_PRES_STATE_OFFSET);
if ((PresentStateReg & ((u32)XSDPS_PSR_INHIBIT_CMD_MASK |
(u32)XSDPS_PSR_INHIBIT_DAT_MASK |
(u32)XSDPS_PSR_WR_ACTIVE_MASK | (u32)XSDPS_PSR_RD_ACTIVE_MASK)) != 0U) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/* Send block write command */
Status = XSdPs_CmdTransfer(InstancePtr, CMD16, BlkSize, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
Status = (s32)XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_RESP0_OFFSET);
/* Set block size to the value passed */
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_BLK_SIZE_OFFSET,
BlkSize & XSDPS_BLK_SIZE_MASK);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to get bus width support by card.
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
* @param SCR - buffer to store SCR register returned by card.
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Get_BusWidth(XSdPs *InstancePtr, u8 *SCR)
{
s32 Status;
u16 BlkCnt;
u16 BlkSize;
s32 LoopCnt;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
for (LoopCnt = 0; LoopCnt < 8; LoopCnt++) {
SCR[LoopCnt] = 0U;
}
/* Send block write command */
Status = XSdPs_CmdTransfer(InstancePtr, CMD55,
InstancePtr->RelCardAddr, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
BlkCnt = XSDPS_SCR_BLKCNT;
BlkSize = XSDPS_SCR_BLKSIZE;
/* Set block size to the value passed */
BlkSize &= XSDPS_BLK_SIZE_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_BLK_SIZE_OFFSET, BlkSize);
XSdPs_SetupADMA2DescTbl(InstancePtr, BlkCnt, SCR);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_XFER_MODE_OFFSET,
XSDPS_TM_DAT_DIR_SEL_MASK | XSDPS_TM_DMA_EN_MASK);
Xil_DCacheInvalidateRange((u32)SCR, 8);
Status = XSdPs_CmdTransfer(InstancePtr, ACMD51, 0U, BlkCnt);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
Status = (s32)XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_RESP0_OFFSET);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to set bus width to 4-bit in card and host
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Change_BusWidth(XSdPs *InstancePtr)
{
s32 Status;
u32 StatusReg;
u32 Arg;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
if (InstancePtr->CardType == XSDPS_CARD_SD) {
Status = XSdPs_CmdTransfer(InstancePtr, CMD55, InstancePtr->RelCardAddr,
0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
InstancePtr->BusWidth = XSDPS_4_BIT_WIDTH;
Arg = ((u32)InstancePtr->BusWidth);
Status = XSdPs_CmdTransfer(InstancePtr, ACMD6, Arg, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
} else {
if ((InstancePtr->HC_Version == XSDPS_HC_SPEC_V3)
&& (InstancePtr->CardType == XSDPS_CHIP_EMMC)) {
/* in case of eMMC data width 8-bit */
InstancePtr->BusWidth = XSDPS_8_BIT_WIDTH;
} else {
InstancePtr->BusWidth = XSDPS_4_BIT_WIDTH;
}
if (InstancePtr->BusWidth == XSDPS_8_BIT_WIDTH) {
Arg = XSDPS_MMC_8_BIT_BUS_ARG;
} else {
Arg = XSDPS_MMC_4_BIT_BUS_ARG;
}
Status = XSdPs_CmdTransfer(InstancePtr, CMD6, Arg, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/* Check for transfer complete */
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
}
#if defined (__arm__) || defined (__aarch64__)
usleep(XSDPS_MMC_DELAY_FOR_SWITCH);
#endif
#ifdef __MICROBLAZE__
/* 2 msec delay */
MB_Sleep(2);
#endif
StatusReg = XSdPs_ReadReg8(InstancePtr->Config.BaseAddress,
XSDPS_HOST_CTRL1_OFFSET);
/* Width setting in controller */
if (InstancePtr->BusWidth == XSDPS_8_BIT_WIDTH) {
StatusReg |= XSDPS_HC_EXT_BUS_WIDTH;
} else {
StatusReg |= XSDPS_HC_WIDTH_MASK;
}
XSdPs_WriteReg8(InstancePtr->Config.BaseAddress,
XSDPS_HOST_CTRL1_OFFSET,
(u8)StatusReg);
Status = (s32)XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_RESP0_OFFSET);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to get bus speed supported by card.
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
* @param ReadBuff - buffer to store function group support data
* returned by card.
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Get_BusSpeed(XSdPs *InstancePtr, u8 *ReadBuff)
{
s32 Status;
u32 Arg;
u16 BlkCnt;
u16 BlkSize;
s32 LoopCnt;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
for (LoopCnt = 0; LoopCnt < 64; LoopCnt++) {
ReadBuff[LoopCnt] = 0U;
}
BlkCnt = XSDPS_SWITCH_CMD_BLKCNT;
BlkSize = XSDPS_SWITCH_CMD_BLKSIZE;
BlkSize &= XSDPS_BLK_SIZE_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_BLK_SIZE_OFFSET, BlkSize);
XSdPs_SetupADMA2DescTbl(InstancePtr, BlkCnt, ReadBuff);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_XFER_MODE_OFFSET,
XSDPS_TM_DAT_DIR_SEL_MASK | XSDPS_TM_DMA_EN_MASK);
Arg = XSDPS_SWITCH_CMD_HS_GET;
Xil_DCacheInvalidateRange((u32)ReadBuff, 64);
Status = XSdPs_CmdTransfer(InstancePtr, CMD6, Arg, 1U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
Status = (s32)XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_RESP0_OFFSET);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to set high speed in card and host. Changes clock in host accordingly.
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Change_BusSpeed(XSdPs *InstancePtr)
{
s32 Status;
u32 StatusReg;
u32 Arg;
u16 BlkCnt;
u16 BlkSize;
u8 ReadBuff[64];
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
if (InstancePtr->CardType == XSDPS_CARD_SD) {
BlkCnt = XSDPS_SWITCH_CMD_BLKCNT;
BlkSize = XSDPS_SWITCH_CMD_BLKSIZE;
BlkSize &= XSDPS_BLK_SIZE_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_BLK_SIZE_OFFSET, BlkSize);
XSdPs_SetupADMA2DescTbl(InstancePtr, BlkCnt, ReadBuff);
Xil_DCacheFlushRange((u32)ReadBuff, 64);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_XFER_MODE_OFFSET,
XSDPS_TM_DAT_DIR_SEL_MASK | XSDPS_TM_DMA_EN_MASK);
Arg = XSDPS_SWITCH_CMD_HS_SET;
Status = XSdPs_CmdTransfer(InstancePtr, CMD6, Arg, 1U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
/* Change the clock frequency to 50 MHz */
InstancePtr->BusSpeed = XSDPS_CLK_50_MHZ;
Status = XSdPs_Change_ClkFreq(InstancePtr, InstancePtr->BusSpeed);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
} else if (InstancePtr->CardType == XSDPS_CARD_MMC) {
Arg = XSDPS_MMC_HIGH_SPEED_ARG;
Status = XSdPs_CmdTransfer(InstancePtr, CMD6, Arg, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
/* Change the clock frequency to 52 MHz */
InstancePtr->BusSpeed = XSDPS_CLK_52_MHZ;
Status = XSdPs_Change_ClkFreq(InstancePtr, XSDPS_CLK_52_MHZ);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
} else {
Arg = XSDPS_MMC_HS200_ARG;
Status = XSdPs_CmdTransfer(InstancePtr, CMD6, Arg, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
/* Change the clock frequency to 200 MHz */
InstancePtr->BusSpeed = XSDPS_MMC_HS200_MAX_CLK;
Status = XSdPs_Change_ClkFreq(InstancePtr, InstancePtr->BusSpeed);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
Status = XSdPs_Execute_Tuning(InstancePtr);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
}
#if defined (__arm__) || defined (__aarch64__)
usleep(XSDPS_MMC_DELAY_FOR_SWITCH);
#endif
#ifdef __MICROBLAZE__
/* 2 msec delay */
MB_Sleep(2);
#endif
StatusReg = (s32)XSdPs_ReadReg8(InstancePtr->Config.BaseAddress,
XSDPS_HOST_CTRL1_OFFSET);
StatusReg |= XSDPS_HC_SPEED_MASK;
XSdPs_WriteReg8(InstancePtr->Config.BaseAddress,
XSDPS_HOST_CTRL1_OFFSET, (u8)StatusReg);
Status = (s32)XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_RESP0_OFFSET);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to change clock freq to given value.
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
* @param SelFreq - Clock frequency in Hz.
*
* @return None
*
* @note This API will change clock frequency to the value less than
* or equal to the given value using the permissible dividors.
*
******************************************************************************/
s32 XSdPs_Change_ClkFreq(XSdPs *InstancePtr, u32 SelFreq)
{
u16 ClockReg;
u16 DivCnt;
u16 Divisor = 0U;
u16 ExtDivisor;
s32 Status;
u16 ReadReg;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
/* Disable clock */
ClockReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET);
ClockReg &= ~(XSDPS_CC_SD_CLK_EN_MASK | XSDPS_CC_INT_CLK_EN_MASK);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET, ClockReg);
if (InstancePtr->HC_Version == XSDPS_HC_SPEC_V3) {
/* Calculate divisor */
for (DivCnt = 0x1U; DivCnt <= XSDPS_CC_EXT_MAX_DIV_CNT;DivCnt++) {
if (((InstancePtr->Config.InputClockHz) / DivCnt) <= SelFreq) {
Divisor = DivCnt >> 1;
break;
}
}
if (DivCnt > XSDPS_CC_EXT_MAX_DIV_CNT) {
/* No valid divisor found for given frequency */
Status = XST_FAILURE;
goto RETURN_PATH;
}
} else {
/* Calculate divisor */
DivCnt = 0x1U;
while (DivCnt <= XSDPS_CC_MAX_DIV_CNT) {
if (((InstancePtr->Config.InputClockHz) / DivCnt) <= SelFreq) {
Divisor = DivCnt / 2U;
break;
}
DivCnt = DivCnt << 1U;
}
if (DivCnt > XSDPS_CC_MAX_DIV_CNT) {
/* No valid divisor found for given frequency */
Status = XST_FAILURE;
goto RETURN_PATH;
}
}
/* Set clock divisor */
if (InstancePtr->HC_Version == XSDPS_HC_SPEC_V3) {
ClockReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET);
ClockReg &= ~(XSDPS_CC_SDCLK_FREQ_SEL_MASK |
XSDPS_CC_SDCLK_FREQ_SEL_EXT_MASK);
ExtDivisor = Divisor >> 8;
ExtDivisor <<= XSDPS_CC_EXT_DIV_SHIFT;
ExtDivisor &= XSDPS_CC_SDCLK_FREQ_SEL_EXT_MASK;
Divisor <<= XSDPS_CC_DIV_SHIFT;
Divisor &= XSDPS_CC_SDCLK_FREQ_SEL_MASK;
ClockReg |= Divisor | ExtDivisor | (u16)XSDPS_CC_INT_CLK_EN_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_CLK_CTRL_OFFSET,
ClockReg);
} else {
ClockReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET);
ClockReg &= (~XSDPS_CC_SDCLK_FREQ_SEL_MASK);
Divisor <<= XSDPS_CC_DIV_SHIFT;
Divisor &= XSDPS_CC_SDCLK_FREQ_SEL_MASK;
ClockReg |= Divisor | (u16)XSDPS_CC_INT_CLK_EN_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_CLK_CTRL_OFFSET,
ClockReg);
}
/* Wait for internal clock to stabilize */
ReadReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET);
while((ReadReg & XSDPS_CC_INT_CLK_STABLE_MASK) == 0U) {
ReadReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET);;
}
/* Enable SD clock */
ClockReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_CLK_CTRL_OFFSET,
ClockReg | XSDPS_CC_SD_CLK_EN_MASK);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to send pullup command to card before using DAT line 3(using 4-bit bus)
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Pullup(XSdPs *InstancePtr)
{
s32 Status;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
Status = XSdPs_CmdTransfer(InstancePtr, CMD55,
InstancePtr->RelCardAddr, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
Status = XSdPs_CmdTransfer(InstancePtr, ACMD42, 0U, 0U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to get EXT_CSD register of eMMC.
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
* @param ReadBuff - buffer to store EXT_CSD
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Get_Mmc_ExtCsd(XSdPs *InstancePtr, u8 *ReadBuff)
{
s32 Status;
u32 Arg = 0U;
u16 BlkCnt;
u16 BlkSize;
s32 LoopCnt;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
for (LoopCnt = 0; LoopCnt < 512; LoopCnt++) {
ReadBuff[LoopCnt] = 0U;
}
BlkCnt = XSDPS_EXT_CSD_CMD_BLKCNT;
BlkSize = XSDPS_EXT_CSD_CMD_BLKSIZE;
BlkSize &= XSDPS_BLK_SIZE_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_BLK_SIZE_OFFSET, BlkSize);
XSdPs_SetupADMA2DescTbl(InstancePtr, BlkCnt, ReadBuff);
Xil_DCacheInvalidateRange((u32)ReadBuff, 512U);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_XFER_MODE_OFFSET,
XSDPS_TM_DAT_DIR_SEL_MASK | XSDPS_TM_DMA_EN_MASK);
/* Send SEND_EXT_CSD command */
Status = XSdPs_CmdTransfer(InstancePtr, CMD8, Arg, 1U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
Status = (s32)XSdPs_ReadReg(InstancePtr->Config.BaseAddress,
XSDPS_RESP0_OFFSET);
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
/*****************************************************************************/
/**
*
* API to UHS-I mode initialization
*
*
* @param InstancePtr is a pointer to the XSdPs instance.
* @param Mode UHS-I mode
*
* @return
* - XST_SUCCESS if successful.
* - XST_FAILURE if fail.
*
* @note None.
*
******************************************************************************/
s32 XSdPs_Uhs_ModeInit(XSdPs *InstancePtr, u8 Mode)
{
s32 Status;
u16 CtrlReg;
u32 Arg;
u16 BlkCnt;
u16 BlkSize;
u8 ReadBuff[64];
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
/* Drive strength */
/* Bus speed mode selection */
BlkCnt = XSDPS_SWITCH_CMD_BLKCNT;
BlkSize = XSDPS_SWITCH_CMD_BLKSIZE;
BlkSize &= XSDPS_BLK_SIZE_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_BLK_SIZE_OFFSET,
BlkSize);
XSdPs_SetupADMA2DescTbl(InstancePtr, BlkCnt, ReadBuff);
Xil_DCacheFlushRange((u32)ReadBuff, 64);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_XFER_MODE_OFFSET,
XSDPS_TM_DAT_DIR_SEL_MASK | XSDPS_TM_DMA_EN_MASK);
switch (Mode) {
case 0U:
Arg = XSDPS_SWITCH_CMD_SDR12_SET;
InstancePtr->BusSpeed = XSDPS_SD_SDR12_MAX_CLK;
break;
case 1U:
Arg = XSDPS_SWITCH_CMD_SDR25_SET;
InstancePtr->BusSpeed = XSDPS_SD_SDR25_MAX_CLK;
break;
case 2U:
Arg = XSDPS_SWITCH_CMD_SDR50_SET;
InstancePtr->BusSpeed = XSDPS_SD_SDR50_MAX_CLK;
break;
case 3U:
Arg = XSDPS_SWITCH_CMD_SDR104_SET;
InstancePtr->BusSpeed = XSDPS_SD_SDR104_MAX_CLK;
break;
case 4U:
Arg = XSDPS_SWITCH_CMD_DDR50_SET;
InstancePtr->BusSpeed = XSDPS_SD_DDR50_MAX_CLK;
break;
default:
Status = XST_FAILURE;
goto RETURN_PATH;
break;
}
Status = XSdPs_CmdTransfer(InstancePtr, CMD6, Arg, 1U);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
/* Current limit */
/* Set UHS mode in controller */
CtrlReg = XSdPs_ReadReg16(InstancePtr->Config.BaseAddress,
XSDPS_HOST_CTRL2_OFFSET);
CtrlReg &= (u16)(~XSDPS_HC2_UHS_MODE_MASK);
CtrlReg |= Mode;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress,
XSDPS_HOST_CTRL2_OFFSET, CtrlReg);
/* Change the clock frequency */
Status = XSdPs_Change_ClkFreq(InstancePtr, InstancePtr->BusSpeed);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
if((Mode == XSDPS_UHS_SPEED_MODE_SDR104) ||
(Mode == XSDPS_UHS_SPEED_MODE_DDR50)) {
/* Send tuning pattern */
Status = XSdPs_Execute_Tuning(InstancePtr);
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
}
Status = XST_SUCCESS;
RETURN_PATH:
return Status;
}
static s32 XSdPs_Execute_Tuning(XSdPs *InstancePtr)
{
s32 Status;
u16 BlkCnt;
u16 BlkSize;
s32 LoopCnt;
u8 ReadBuff[128];
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
BlkCnt = XSDPS_TUNING_CMD_BLKCNT;
BlkSize = XSDPS_TUNING_CMD_BLKSIZE;
if(InstancePtr->BusWidth == XSDPS_8_BIT_WIDTH)
{
BlkSize = BlkSize*2U;
}
BlkSize &= XSDPS_BLK_SIZE_MASK;
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_BLK_SIZE_OFFSET,
BlkSize);
for (LoopCnt = 0; LoopCnt < (s32)BlkSize; LoopCnt++) {
ReadBuff[LoopCnt] = 0U;
}
XSdPs_SetupADMA2DescTbl(InstancePtr, BlkCnt, ReadBuff);
XSdPs_WriteReg16(InstancePtr->Config.BaseAddress, XSDPS_XFER_MODE_OFFSET,
XSDPS_TM_DAT_DIR_SEL_MASK | XSDPS_TM_DMA_EN_MASK);
Xil_DCacheInvalidateRange((u32)ReadBuff, BlkSize);
if(InstancePtr->CardType == XSDPS_CARD_SD) {
Status = XSdPs_CmdTransfer(InstancePtr, CMD19, 0U, 1U);
} else {
Status = XSdPs_CmdTransfer(InstancePtr, CMD21, 0U, 1U);
}
if (Status != XST_SUCCESS) {
Status = XST_FAILURE;
goto RETURN_PATH;
}
/*
* Check for transfer complete
* Polling for response for now
*/
Status = XSdPs_Wait_For(InstancePtr, XSDPS_INTR_TC_MASK, pdTRUE);
if (Status != XST_SUCCESS) {
goto RETURN_PATH;
}
Status = XST_SUCCESS;
RETURN_PATH: return Status;
}
/** @} */

View file

@ -0,0 +1,95 @@
/******************************************************************************
*
* Copyright (C) 2013 - 2014 Xilinx, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Use of the Software is limited solely to applications:
* (a) running on a Xilinx device, or
* (b) that interact with a Xilinx device through a bus or interconnect.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* XILINX CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xsdps_sinit.c
*
* The implementation of the XSdPs component's static initialization
* functionality.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.00a hk/sg 10/17/13 Initial release
*
* </pre>
*
******************************************************************************/
/***************************** Include Files *********************************/
#include "xstatus.h"
#include "xsdps.h"
#include "xparameters.h"
/************************** Constant Definitions *****************************/
/**************************** Type Definitions *******************************/
/***************** Macros (Inline Functions) Definitions *********************/
/************************** Function Prototypes ******************************/
/************************** Variable Definitions *****************************/
extern XSdPs_Config XSdPs_ConfigTable[];
/*****************************************************************************/
/**
*
* Looks up the device configuration based on the unique device ID. A table
* contains the configuration info for each device in the system.
*
* @param DeviceId contains the ID of the device to look up the
* configuration for.
*
* @return
*
* A pointer to the configuration found or NULL if the specified device ID was
* not found. See xsdps.h for the definition of XSdPs_Config.
*
* @note None.
*
******************************************************************************/
XSdPs_Config *XSdPs_LookupConfig(u16 DeviceId)
{
XSdPs_Config *CfgPtr = NULL;
int Index;
for (Index = 0; Index < XPAR_XSDPS_NUM_INSTANCES; Index++) {
if (XSdPs_ConfigTable[Index].DeviceId == DeviceId) {
CfgPtr = &XSdPs_ConfigTable[Index];
break;
}
}
return CfgPtr;
}