os/kernelhwsrv/kernel/eka/drivers/pbus/mmc/sdcard/sdcard3c/sdcard.cpp
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
     1 // Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
     2 // All rights reserved.
     3 // This component and the accompanying materials are made available
     4 // under the terms of the License "Eclipse Public License v1.0"
     5 // which accompanies this distribution, and is available
     6 // at the URL "http://www.eclipse.org/legal/epl-v10.html".
     7 //
     8 // Initial Contributors:
     9 // Nokia Corporation - initial contribution.
    10 //
    11 // Contributors:
    12 //
    13 // Description:
    14 //
    15 
    16 #include <drivers/sdcard.h>
    17 #include "OstTraceDefinitions.h"
    18 #ifdef OST_TRACE_COMPILER_IN_USE
    19 #include "locmedia_ost.h"
    20 #ifdef __VC32__
    21 #pragma warning(disable: 4127) // disabling warning "conditional expression is constant"
    22 #endif
    23 #include "sdcardTraces.h"
    24 #endif
    25 
    26 
    27 // ======== TSDCard ========
    28 
    29 TSDCard::TSDCard()
    30 :	iProtectedAreaSize(0), iPARootDirEnd(KPARootDirEndUnknown)
    31 	{
    32 	// empty
    33 	}
    34 
    35 TInt64 TSDCard::DeviceSize64() const
    36 //
    37 // returns the SD device size
    38 //
    39 	{
    40 	OstTraceFunctionEntry1( TSDCARD_DEVICESIZE64_ENTRY, this );
    41 	if(iFlags & KSDCardIsSDCard)
    42 		{	
    43 		return (IsHighCapacity()) ? 512 * 1024 * (TInt64)(1 + CSD().CSDField(69, 48)) : TMMCard::DeviceSize64();
    44 		}
    45 		
    46 	return(TMMCard::DeviceSize64());
    47 	}
    48 
    49 TUint32 TSDCard::PreferredWriteGroupLength() const
    50 //
    51 // return SD erase sector size, (SECTOR_SIZE + 1) * 2 ** WRITE_BLK_LEN
    52 //
    53 	{
    54 	OstTraceFunctionEntry1( TSDCARD_PREFERREDWRITEGROUPLENGTH_ENTRY, this );
    55 	if(iFlags & KSDCardIsSDCard)
    56 		{	
    57 		TSDCSD sdcsd(CSD());
    58 		return (sdcsd.SDSectorSize() + 1) * (1 << sdcsd.WriteBlLen());
    59 		}
    60 		
    61 	return(TMMCard::PreferredWriteGroupLength());
    62 	}
    63 
    64 TInt TSDCard::GetFormatInfo(TLDFormatInfo& /*aFormatInfo*/) const
    65 	{
    66 	return KErrNotSupported;
    67 	}
    68 
    69 TUint32 TSDCard::MinEraseSectorSize() const
    70 	{
    71 	if(iFlags&KSDCardIsSDCard)
    72 		{	
    73 		TSDCSD sdcsd(CSD());
    74 		if (sdcsd.SDEraseBlkEn())
    75 			return sdcsd.WriteBlockLength();		// raised logarithm
    76 		else
    77 			return (sdcsd.SDSectorSize() + 1) * sdcsd.WriteBlockLength();
    78 		}
    79 
    80 	return TMMCard::MinEraseSectorSize();
    81 	}
    82 
    83 
    84 const TUint32 KEraseSectorSizeShift = 8;	// KEraseSectorSizeShift determines the multiple of the sector size 
    85 											// that can be erased in one operation
    86 TUint32 TSDCard::EraseSectorSize() const
    87 	{
    88 	if(iFlags&KSDCardIsSDCard)
    89 		{	
    90 		TSDCSD sdcsd(CSD());
    91 		return ((sdcsd.SDSectorSize() + 1) * sdcsd.WriteBlockLength()) << KEraseSectorSizeShift;
    92 		}
    93 
    94 	return TMMCard::EraseSectorSize();
    95 	}
    96 
    97 const TInt KDefaultBlockLen		   = 9;							// 2^9 = 512 bytes
    98 const TInt KDefaultBlockLenInBytes = 1 << KDefaultBlockLen;		// 2^9 = 512 bytes
    99 const TInt KTwoGbyteSDBlockLen	   = 10;						// 2^10 = 1024 bytes
   100 const TInt KFourGbyteSDBlockLen	   = 11;						// 2^11 = 2048 bytes
   101 
   102 TInt TSDCard::GetEraseInfo(TMMCEraseInfo& aEraseInfo) const
   103 //
   104 // Return info. on erase services for this card
   105 //
   106 	{
   107 	OstTraceFunctionEntry1( TSDCARD_GETERASEINFO_ENTRY, this );
   108 	
   109 	// SD Controllers support MMC cards too. Check if we are really dealing with an SD card
   110 	if(!(iFlags&KSDCardIsSDCard))
   111 		return(TMMCard::GetEraseInfo(aEraseInfo));
   112 		
   113 	if (CSD().CCC() & KMMCCmdClassErase)
   114 		{
   115 		// This card supports erase cmds. However, SD cards don't support Erase Group commands (i.e. CMD35, CMD36).
   116 		OstTrace0( TRACE_INTERNALS, TSDCARD_GETERASEINFO, "Card supports erase class commands" );		
   117 		aEraseInfo.iEraseFlags=KMMCEraseClassCmdsSupported; 
   118 		
   119 		// Return the preferred size to be used as the unit for erase operations.
   120 		TSDCSD sdcsd(CSD());
   121 		TUint32 prefSize=((sdcsd.SDSectorSize() + 1) * sdcsd.WriteBlockLength());
   122 		prefSize<<=KEraseSectorSizeShift;		// Use multiples of the sector size for each erase operation
   123 		aEraseInfo.iPreferredEraseUnitSize=prefSize;
   124 	
   125 		// Return the smallest size that can be used as the unit for erase operations
   126 		if (sdcsd.SDEraseBlkEn())
   127 			{
   128 			aEraseInfo.iMinEraseSectorSize = KDefaultBlockLenInBytes;
   129 			}
   130 		else
   131 			{
   132 			aEraseInfo.iMinEraseSectorSize=(sdcsd.SDSectorSize() + 1) * sdcsd.WriteBlockLength();
   133 			}
   134 		}
   135 	else		
   136 		aEraseInfo.iEraseFlags=0;
   137 		
   138 	OstTraceFunctionExitExt( TSDCARD_GETERASEINFO_EXIT, this, KErrNone );
   139 	return KErrNone;	
   140 	}
   141 
   142 TInt TSDCard::MaxReadBlLen() const
   143 /**
   144  * Returns the maximum read block length supported by the card encoded as a logarithm
   145  * Normally this is the same as the READ_BL_LEN field in the CSD register,
   146  * but for high capacity cards (> 2GB) this is set to a maximum of 512 bytes,
   147  * if possible, to try to avoid compatibility issues.
   148  */
   149 	{
   150 	OstTraceFunctionEntry1( TSDCARD_MAXREADBLLEN_ENTRY, this );
   151 	if (IsSDCard())
   152 		{
   153 		TInt blkLenLog2 = CSD().ReadBlLen();
   154 		if (blkLenLog2 == KTwoGbyteSDBlockLen || blkLenLog2 == KFourGbyteSDBlockLen)
   155 			{
   156 			// The SD card spec. makes a special case for 2GByte cards,
   157 			// ...and some manufacturers apply the same method to support 4G cards
   158 			__KTRACE_OPT(KPBUS1, Kern::Printf("=mmc:mrbl > 2GB SD"));
   159 			OstTrace0( TRACE_INTERNALS, TSDCARD_MAXREADBLLEN, "SD Card > 2GB" );
   160 			blkLenLog2 = KDefaultBlockLen;
   161 			}
   162 		OstTraceFunctionExitExt( TSDCARD_MAXREADBLLEN_EXIT, this, blkLenLog2 );
   163 		return blkLenLog2;
   164 		}
   165 	else		// MMC card
   166 		{
   167 		TInt ret = TMMCard::MaxReadBlLen();
   168 		OstTraceFunctionExitExt( DUP1_TSDCARD_MAXREADBLLEN_EXIT, this, ret );
   169 		return ret;
   170 		}
   171 	}
   172 
   173 TInt TSDCard::MaxWriteBlLen() const
   174 /**
   175  * Returns the maximum write block length supported by the card encoded as a logarithm
   176  * Normally this is the same as the WRITE_BL_LEN field in the CSD register,
   177  * but for high capacity cards (> 2GB) this is set to a maximum of 512 bytes,
   178  * if possible, to try to avoid compatibility issues.
   179  */
   180 	{
   181 	OstTraceFunctionEntry1( TSDCARD_MAXWRITEBLLEN_ENTRY, this );
   182 	if (IsSDCard())
   183 		{
   184 		TInt blkLenLog2 = CSD().WriteBlLen();
   185 		if (blkLenLog2 == KTwoGbyteSDBlockLen || blkLenLog2 == KFourGbyteSDBlockLen)
   186 			{
   187 			// The SD card spec. makes a special case for 2GByte cards,
   188 			// ...and some manufacturers apply the same method to support 4G cards
   189 			__KTRACE_OPT(KPBUS1, Kern::Printf("=mmc:mwbl > 2GB SD"));
   190 			OstTrace0( TRACE_INTERNALS, TSDCARD_MAXWRITEBLLEN, "SD Card > 2GB" );
   191 			blkLenLog2 = KDefaultBlockLen;
   192 			}
   193 		OstTraceFunctionExitExt( TSDCARD_MAXWRITEBLLEN_EXIT, this, blkLenLog2 );
   194 		return blkLenLog2;
   195 		}
   196 	else		// MMC card
   197 		{
   198 		TInt ret = TMMCard::MaxWriteBlLen();
   199 		OstTraceFunctionExitExt( DUP1_TSDCARD_MAXWRITEBLLEN_EXIT, this, ret );
   200 		return ret;
   201 		}
   202 	}
   203 	
   204 TUint TSDCard::MaxTranSpeedInKilohertz() const
   205 /**
   206  * Returns the maximum supported clock rate for the card, in Kilohertz.
   207  * @return Speed, in Kilohertz
   208  */
   209 	{
   210 	OstTraceFunctionEntry1( TSDCARD_MAXTRANSPEEDINKILOHERTZ_ENTRY, this );
   211 	TUint maxClk = TMMCard::MaxTranSpeedInKilohertz();
   212 	
   213 	if (IsSDCard())
   214 		{
   215 		__KTRACE_OPT(KPBUS1, Kern::Printf("\t >TSDCard(%d): MaxTranSpeedInKilohertz: %d",(iIndex-1),maxClk));
   216 		
   217 #ifdef _DEBUG
   218 		//MaxClk for SD should only be either 25000KHz or 50000KHz
   219 		if ( (maxClk != KSDDTClk25MHz) && (maxClk != KSDDTClk50MHz) )
   220 			{
   221 			__KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack: Non-Compliant DT Clock"));
   222 			OstTrace0( TRACE_INTERNALS, TSDCARD_MAXTRANSPEEDINKILOHERTZ, "Non-Compliant DT Clock" );			
   223 			}
   224 #endif
   225 		if (maxClk > KSDDTClk50MHz)
   226 			{
   227 			//Clock rate exceeds SD possible max clock rate
   228 			__KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack: Tuning DT Clock down to 50MHz"));
   229 			OstTrace0( TRACE_INTERNALS, TSDCARD_MAXTRANSPEEDINKILOHERTZ1, "Tuning DT Clock down to 50MHz" );			
   230 			maxClk = KSDDTClk50MHz;
   231 			}
   232 		}
   233 		
   234 	OstTraceFunctionExitExt( TSDCARD_MAXTRANSPEEDINKILOHERTZ_EXIT, this, maxClk );
   235 	return maxClk;
   236 	}
   237 
   238 // ======== TSDCardArray ========
   239 
   240 EXPORT_C TInt TSDCardArray::AllocCards()
   241 // 
   242 // allocate TSDCard objects for iCards and iNewCardsArray.  This function
   243 // is called at bootup as part of stack allocation so there is no cleanup
   244 // if it fails.
   245 //
   246 	{
   247 	OstTraceFunctionEntry1( TSDCARDARRAY_ALLOCCARDS_ENTRY, this );
   248 	for (TInt i = 0; i < (TInt) KMaxMMCardsPerStack; ++i)
   249 		{
   250 		// zeroing the card data used to be implicit because embedded in
   251 		// CBase-derived DMMCStack.
   252 		if ((iCards[i] = new TSDCard) == 0)
   253 		    {
   254 			OstTraceFunctionExitExt( TSDCARDARRAY_ALLOCCARDS_EXIT, this, KErrNoMemory );
   255 			return KErrNoMemory;
   256 		    }
   257 		iCards[i]->iUsingSessionP = 0;
   258 		if ((iNewCards[i] = new TSDCard) == 0)
   259 		    {
   260 			OstTraceFunctionExitExt( DUP1_TSDCARDARRAY_ALLOCCARDS_EXIT, this, KErrNoMemory );
   261 			return KErrNoMemory;
   262 			}
   263 		}
   264 
   265 	OstTraceFunctionExitExt( DUP2_TSDCARDARRAY_ALLOCCARDS_EXIT, this, KErrNone );
   266 	return KErrNone;
   267 	}
   268 
   269 void TSDCardArray::AddCardSDMode(TUint aCardNumber,const TUint8* aCID,TRCA* aNewRCA)
   270 //
   271 // Add an MMC card straight to the main card array in slot 'aCardNumber'. Save
   272 // the CID value in the slot. Return a RCA for the card.
   273 //
   274 	{
   275 	OstTraceFunctionEntryExt( TSDCARDARRAY_ADDCARDSDMODE_ENTRY, this );
   276 
   277 	TRCA rca=0;
   278 	
   279 	// First, lets check if the same card was here before. If it was, keep the same RCA
   280 	if (Card(aCardNumber).IsPresent() && Card(aCardNumber).iCID==aCID)
   281 		rca=Card(aCardNumber).iRCA;
   282 	else
   283 		{
   284 		// Allocate and new RCA and store the CID in the slot selected
   285 		__ASSERT_ALWAYS( (rca=iOwningStack->iRCAPool.GetFreeRCA())!=0,DMMCSocket::Panic(DMMCSocket::EMMCNoFreeRCA) );
   286 		Card(aCardNumber).iCID=aCID;
   287 		if ( Card(aCardNumber).iRCA != 0 )
   288 			iOwningStack->iRCAPool.UnlockRCA(Card(aCardNumber).iRCA);
   289 		Card(aCardNumber).iRCA=rca;
   290 		iOwningStack->iRCAPool.LockRCA(Card(aCardNumber).iRCA);
   291 		}
   292 
   293 	Card(aCardNumber).iIndex=(aCardNumber+1); // Mark card as being present
   294 	*aNewRCA=rca;
   295 	OstTraceFunctionExit1( TSDCARDARRAY_ADDCARDSDMODE_EXIT, this );
   296 	}
   297 
   298 TInt TSDCardArray::StoreRCAIfUnique(TUint aCardNumber,TRCA& anRCA)
   299 //
   300 // Check that no other array element has the same RCA value 'anRCA'. If no
   301 // no duplication then store in slot 'aCardNumber'.
   302 //
   303 	{
   304 	OstTraceExt3(TRACE_FLOW, TSDCARDARRAY_STORERCAIFUNIQUE_ENTRY ,"TSDCardArray::StoreRCAIfUnique;aCardNumber=%x;anRCA=%x;this=%x", aCardNumber, (TUint) anRCA, (TUint) this);
   305 
   306 	if (anRCA==0)
   307 		{
   308 		OstTraceFunctionExitExt( TSDCARDARRAY_STORERCAIFUNIQUE_EXIT, this, KErrGeneral );
   309 		return KErrGeneral;
   310 		}
   311 	Card(aCardNumber).iRCA=0;
   312 
   313 	// Now let's look if we've seen this card before
   314 	for ( TUint i=0 ; i<iOwningStack->iMaxCardsInStack ; i++ )
   315 		{
   316 		if ( Card(i).IsPresent() && Card(i).iRCA==anRCA )
   317 			{
   318 			OstTraceFunctionExitExt( DUP1_TSDCARDARRAY_STORERCAIFUNIQUE_EXIT, this, KErrInUse );
   319 			return KErrInUse;
   320 			}
   321 		}
   322 	Card(aCardNumber).iRCA=anRCA;
   323 	Card(aCardNumber).iIndex=(aCardNumber+1); // Mark card as being present
   324 	OstTraceFunctionExitExt( DUP2_TSDCARDARRAY_STORERCAIFUNIQUE_EXIT, this, KErrNone );
   325 	return KErrNone;
   326 	}
   327 
   328 EXPORT_C void TSDCardArray::DeclareCardAsGone(TUint aCardNumber)
   329 //
   330 // reset SD specific fields to initial values and then reset generic MultiMediaCard
   331 //
   332 	{
   333 	OstTraceFunctionEntryExt( TSDCARDARRAY_DECLARECARDASGONE_ENTRY, this );
   334 	Card(aCardNumber).SetBusWidth(1);
   335 	TMMCardArray::DeclareCardAsGone(aCardNumber);
   336 	OstTraceFunctionExit1( TSDCARDARRAY_DECLARECARDASGONE_EXIT, this );
   337 	}
   338 
   339 // ======== DSDSession ========
   340 
   341 void DSDSession::FillAppCommandDesc(TMMCCommandDesc& aDesc, TSDAppCmd aCmd)
   342 	{
   343 	OstTraceFunctionEntry0( DSDSESSION_FILLAPPCOMMANDDESC_ENTRY );
   344 	aDesc.iCommand = (TMMCCommandEnum) aCmd;
   345 	aDesc.iArgument = 0;						// set stuff bits to zero
   346 	FillAppCommandDesc(aDesc);
   347 	OstTraceFunctionExit0( DSDSESSION_FILLAPPCOMMANDDESC_EXIT );
   348 	}
   349 
   350 void DSDSession::FillAppCommandDesc(TMMCCommandDesc& aDesc, TSDAppCmd aCmd, TMMCArgument aArg)
   351 	{
   352 	OstTraceFunctionEntry0( DUP1_DSDSESSION_FILLAPPCOMMANDDESC_ENTRY );
   353 	aDesc.iCommand = (TMMCCommandEnum) aCmd;
   354 	aDesc.iArgument = aArg;
   355 	FillAppCommandDesc(aDesc);
   356 	OstTraceFunctionExit0( DUP1_DSDSESSION_FILLAPPCOMMANDDESC_EXIT );
   357 	}
   358 
   359 const TUint32 CCA = KMMCCmdClassApplication;
   360 const TMMCIdxCommandSpec AppCmdSpecTable[] =
   361 	{						//	Class	Type		Dir			MBlk	StopT	Rsp Type		Len
   362 	{ESDACmdSetBusWidth,		{CCA,ECmdTypeACS,	EDirNone,	EFalse, EFalse, ERespTypeR1,	4}}, //ACMD6
   363 	{ESDACmdSDStatus,			{CCA,ECmdTypeADTCS,	EDirRead,	EFalse, EFalse, ERespTypeR1,	4}}, //ACMD13
   364 	{ESDACmdSendNumWrBlocks,	{CCA,ECmdTypeADTCS,	EDirRead,	EFalse, EFalse, ERespTypeR1,	4}}, //ACMD22
   365 	{ESDACmdSetWrBlkEraseCount,	{CCA,ECmdTypeACS,	EDirNone,	EFalse, EFalse, ERespTypeR1,	4}}, //ACMD23
   366 	{ESDACmdSDAppOpCond,		{CCA,ECmdTypeBCR,	EDirNone,	EFalse, EFalse, ERespTypeR3,	4}}, //ACMD41
   367 	{ESDACmdSetClrCardDetect,	{CCA,ECmdTypeAC,	EDirNone,	EFalse, EFalse, ERespTypeR1,	4}}, //ACMD42
   368 	{ESDACmdSendSCR,			{CCA,ECmdTypeADTCS,	EDirRead,	EFalse, EFalse, ERespTypeR1,	4}}  //ACMD51
   369 };
   370 
   371 void DSDSession::FillAppCommandDesc(TMMCCommandDesc& aDesc)
   372 	{
   373 	OstTraceFunctionEntry0( DUP2_DSDSESSION_FILLAPPCOMMANDDESC_ENTRY );
   374 	aDesc.iSpec = FindCommandSpec(AppCmdSpecTable, aDesc.iCommand);
   375 	aDesc.iFlags = 0;
   376 	aDesc.iBytesDone = 0;
   377 	OstTraceFunctionExit0( DUP2_DSDSESSION_FILLAPPCOMMANDDESC_EXIT );
   378 	}
   379 
   380 const TMMCIdxCommandSpec SdSpecificCmdSpecTable[] =
   381 /**
   382  * SD Specific Command Table
   383  *
   384  *  - Some commands defined in the SD specification overload those defined in the MMC specification.
   385  *    This table contains the SD specific versions of those commands.
   386  */
   387 	{
   388 							//   Class				Type			Dir			MBlk	StopT	Rsp Type		Len
   389 	{ESDCmdSendRelativeAddress,	{KMMCCmdClassBasic,	ECmdTypeBCR,	EDirNone,	EFalse,	EFalse,	ERespTypeR6,	4}},	// CMD3 : SEND_RELATIVE_ADDRESS
   390 	{ESDCmdSwitchFunction,		{KMMCCmdClassSwitch,ECmdTypeADTCS,	EDirRead,	EFalse,	EFalse,	ERespTypeR1,	4}},	// CMD6 : SWITCH_FUNCTION
   391 	{ESDCmdSendIfCond,			{KMMCCmdClassBasic,	ECmdTypeBCR,	EDirNone,	EFalse,	EFalse,	ERespTypeR7,	4}}		// CMD8 : SEND_IF_COND
   392 	};
   393 
   394 void DSDSession::FillSdSpecificCommandDesc(TMMCCommandDesc& aDesc, TSDSpecificCmd aCmd, TMMCArgument aArg)
   395 	{
   396 	OstTraceFunctionEntry0( DSDSESSION_FILLSDSPECIFICCOMMANDDESC_ENTRY );
   397 	aDesc.iCommand = (TMMCCommandEnum) aCmd;
   398 	aDesc.iArgument = aArg;
   399 	FillSdSpecificCommandDesc(aDesc);
   400 	OstTraceFunctionExit0( DSDSESSION_FILLSDSPECIFICCOMMANDDESC_EXIT );
   401 	}
   402 
   403 void DSDSession::FillSdSpecificCommandDesc(TMMCCommandDesc& aDesc, TSDSpecificCmd aCmd)
   404 	{
   405 	OstTraceFunctionEntry0( DUP1_DSDSESSION_FILLSDSPECIFICCOMMANDDESC_ENTRY );
   406 	aDesc.iCommand = (TMMCCommandEnum) aCmd;
   407 	aDesc.iArgument = 0;						// set stuff bits to zero
   408 	FillSdSpecificCommandDesc(aDesc);
   409 	OstTraceFunctionExit0( DUP1_DSDSESSION_FILLSDSPECIFICCOMMANDDESC_EXIT );
   410 	}
   411 
   412 void DSDSession::FillSdSpecificCommandDesc(TMMCCommandDesc& aDesc)
   413 	{
   414 	OstTraceFunctionEntry0( DUP2_DSDSESSION_FILLSDSPECIFICCOMMANDDESC_ENTRY );
   415 	aDesc.iSpec = FindCommandSpec(SdSpecificCmdSpecTable, aDesc.iCommand);
   416 	aDesc.iFlags = 0;
   417 	aDesc.iBytesDone = 0;
   418 	OstTraceFunctionExit0( DUP2_DSDSESSION_FILLSDSPECIFICCOMMANDDESC_EXIT );
   419 	}
   420 
   421 
   422 // ======== DSDStack ========
   423 
   424 EXPORT_C TInt DSDStack::Init()
   425 	{
   426 	OstTraceFunctionEntry1( DSDSTACK_INIT_ENTRY, this );
   427 	TInt ret = DMMCStack::Init();
   428 	OstTraceFunctionExitExt( DSDSTACK_INIT_EXIT, this, ret );
   429 	return ret;
   430 	}
   431 
   432 
   433 const TInt KMaxRCASendLoops=3;
   434 const TUint KSDMaxPollAttempts=25;
   435 EXPORT_C TMMCErr DSDStack::AcquireStackSM()
   436 //
   437 // This macro acquires new cards in an SD Card - star topology stack.
   438 // This means each card has its own CMD and DAT lines and can be addressed
   439 // individually by the Controller in turn. Commands can also be broadcast 
   440 // simultaneously to the entire stack. 
   441 // It starts with the Controller reading the operating conditions of each 
   442 // card in the stack (SEND_OP_COND - ACMD41). Then, the following
   443 // initialisation sequence is performed to each card in turn:-
   444 // New cards in the stack are identified (ALL_SEND_CID - CMD2) and each one
   445 // is requested to publish a relative card address (SEND_RCA - CMD3). Finally,
   446 // the card specific data (SEND_CSD - CMD9) is read from each card.
   447 // Note that the initialization of MMC cards are supported by this function
   448 // if they are encountered. These require a slightly different init. procdure.
   449 //
   450 	{
   451 		enum states
   452 			{
   453 			EStBegin=0,
   454 			EStNextFullRange,
   455 			EStSendCIDIssued,
   456 			EStIssueSendRCA,
   457 			EStSendRCACheck,
   458 			EStRCADone,
   459 			EStMoreCardsCheck,
   460 			EStEnd
   461 			};
   462 
   463 		DMMCSession& s=Session();
   464 		OstTrace1( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM, "Current session = 0x%x", &s );
   465 
   466 	SMF_BEGIN
   467 
   468 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM1, "EStBegin" );
   469         __KTRACE_OPT(KPBUS1, Kern::Printf(">DSDStack::AcquireStackSM()"));
   470         
   471 		iRCAPool.ReleaseUnlocked();
   472 		iCxCardCount=0; 		// Reset current card number
   473 
   474 	SMF_STATE(EStNextFullRange)
   475 
   476 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM2, "EStNextFullRange" );
   477 		iCxCardType = ESDCardTypeUnknown;
   478 
   479 		AddressCard(iCxCardCount); 	// Address the next card
   480 
   481 		// Before issueing commands, see if there's actually a card present
   482 		if (!CardDetect(iCxCardCount))
   483 			SMF_GOTOS(EStMoreCardsCheck)
   484 
   485 		m.SetTraps(KMMCErrResponseTimeOut);
   486 		SMF_INVOKES(InitialiseMemoryCardSMST, EStSendCIDIssued)
   487 
   488 	SMF_STATE(EStSendCIDIssued)
   489 
   490 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM3, "EStSendCIDIssued" );
   491 		if( !err )
   492 			{
   493 			// The card responded with a CID. We need to initialise the
   494 			// appropriate entry in the card array with the CID. 
   495 			if (iCxCardType==ESDCardTypeIsSD)
   496 				{
   497 				// Now prepare to recieve an RCA from to the card
   498 				CardArray().CardP(iCxCardCount)->iCID=s.ResponseP();
   499 				DSDSession::FillSdSpecificCommandDesc(Command(), ESDCmdSendRelativeAddress,0); // SEND_RCA with argument just stuff bits
   500 
   501 				m.ResetTraps();
   502 				iCxPollRetryCount=0; // Init count of send RCA attempts 
   503 				SMF_GOTOS(EStIssueSendRCA)
   504 				}
   505 			else
   506 				{
   507 				// The card array allocates an RCA, either the old RCA
   508 				// if we have seen this card before, or a new one.
   509 				TRCA rca;
   510 				CardArray().AddCardSDMode(iCxCardCount,s.ResponseP(),&rca);
   511 
   512 				// Now assign the new RCA to the card
   513 				s.FillCommandDesc(ECmdSetRelativeAddr,TMMCArgument(rca));
   514 				m.ResetTraps();							
   515 				SMF_INVOKES(ExecCommandSMST,EStRCADone)
   516 				}
   517 			}
   518 		else
   519 			{
   520 			m.ResetTraps();
   521 			SMF_GOTOS(EStMoreCardsCheck) // Timed out, try the next card slot
   522 			}
   523 
   524 	SMF_STATE(EStIssueSendRCA)
   525 
   526 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM4, "EStIssueSendRCA" );
   527 		SMF_INVOKES(ExecCommandSMST,EStSendRCACheck)
   528 
   529 	SMF_STATE(EStSendRCACheck)
   530 
   531 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM5, "EStSendRCACheck" );
   532 		// We need to check that the RCA recieved from the card doesn't clash
   533 		// with any others in this stack. RCA is first 2 bytes of response buffer (in big endian)
   534 		TRCA rca=(TUint16)((s.ResponseP()[0]<<8) | s.ResponseP()[1]);
   535 		if (CardArray().StoreRCAIfUnique(iCxCardCount,rca)!=KErrNone)
   536 			SMF_GOTOS( ((++iCxPollRetryCount<KMaxRCASendLoops)?EStIssueSendRCA:EStMoreCardsCheck) )
   537 
   538 	SMF_STATE(EStRCADone)
   539 
   540 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM6, "EStRCADone" );
   541 		SMF_INVOKES(ConfigureMemoryCardSMST, EStMoreCardsCheck)
   542 
   543 	SMF_STATE(EStMoreCardsCheck)
   544 
   545 		OstTrace0( TRACE_INTERNALS, DSDSTACK_ATTACHCARDSM7, "EStMoreCardsCheck" );
   546 		if (++iCxCardCount < (TInt)iMaxCardsInStack)
   547 		    {
   548 		    __KTRACE_OPT(KPBUS1, Kern::Printf(">DSDStack::AcquireStackSM(): More Cards to check: %d",iCxCardCount));
   549 			OstTrace1( TRACE_INTERNALS, DSDSTACK_ACQUIRESTACKSM8, "More Cards to check: iCxCardCount=%d", iCxCardCount );		    
   550 			SMF_GOTOS(EStNextFullRange)
   551 		    }
   552 		else
   553 		    {		   
   554 			AddressCard(KBroadcastToAllCards); // Set back to broadcast mode
   555 			__KTRACE_OPT(KPBUS1, Kern::Printf("<DSDStack::AcquireStackSM()"));
   556 		    }
   557 
   558 	SMF_END
   559 	}
   560 
   561 
   562 TMMCErr DSDStack::InitialiseMemoryCardSMST(TAny* aStackP)
   563 	{ return static_cast<DSDStack*>(aStackP)->InitialiseMemoryCardSM(); }
   564 
   565 	
   566 TMMCErr DSDStack::InitialiseMemoryCardSM()
   567 /**
   568 */
   569 	{
   570 		enum states
   571 			{
   572 			EStBegin=0,
   573 			EStSendInterfaceCondition,
   574 			EStSentInterfaceCondition,
   575 			EStSetFullRangeCmd,
   576 			EStCheckForFullRangeCmd41Timeout,
   577 			EStSentAppCommandBeforeCheckVoltage,
   578 			EStCheckVoltage,
   579 			EStFullRangeDone,
   580 			EStSetRangeCmd,
   581 			EStCheckForRangeCmd41Timeout,
   582 			EStSetRangeBusyCheck,
   583 			EStCIDCmd,
   584 			EStSendCIDIssued,
   585 			EStEnd
   586 			};
   587 
   588 		DMMCSession& s=Session();
   589 		DMMCPsu* psu=(DMMCPsu*)MMCSocket()->iVcc;
   590 		OstTrace1( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM, "Current session = 0x%x", &s );
   591 			
   592 		static const TUint32 KCmd8Param		= 0x0100 | 0x00AA;	// Voltage supplied : 2.7-3.6V, Check Pattern 10101010b
   593 		static const TUint32 KCmd8CheckMask = 0x00000FFF;
   594 
   595 	SMF_BEGIN
   596 
   597 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM1, "EStBegin" );
   598 		iCxCardType = ESDCardTypeUnknown;
   599 		s.iCardP = NULL;	// This stops ExecCommandSM() from setting old RCA when sending CMD55
   600 
   601 		// Send CMD0 to initialise memory
   602 		SMF_INVOKES(GoIdleSMST, EStSendInterfaceCondition);
   603 
   604 	SMF_STATE(EStSendInterfaceCondition)
   605 
   606 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM2, "EStSendInterfaceCondition" );
   607 		iCxPollRetryCount=0; 						 // Reset max number of poll attempts on card busy
   608 		iConfig.SetPollAttempts(KSDMaxPollAttempts); // Increase card busy timeout to 1 Sec for SD Cards
   609 
   610 		iConfig.RemoveMode( KMMCModeEnableTimeOutRetry ); // Temporarily disable timeout retries - since we use a timeout event to distinguish between MMC and SD
   611 
   612 		DSDSession::FillSdSpecificCommandDesc(Command(), ESDCmdSendIfCond, KCmd8Param);
   613 
   614 		// SD2.0 defines CMD8 as having a new response type - R7
   615 		// if the PSL doesn't indicate support for R7, use R1 instead
   616 		if (!(MMCSocket()->MachineInfo().iFlags & TMMCMachineInfo::ESupportsR7))
   617 			{
   618 			__KTRACE_OPT(KPBUS1, Kern::Printf("R7 not supported."));
   619 			OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM3, "R7 not supported" );
   620 			Command().iSpec.iResponseType = ERespTypeR1;
   621 			}
   622 
   623  
   624  		m.SetTraps(KMMCErrAll);
   625  		SMF_INVOKES(ExecCommandSMST, EStSentInterfaceCondition)
   626  
   627  	SMF_STATE(EStSentInterfaceCondition)
   628  
   629  		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM4, "EStSentInterfaceCondition" );
   630  		if (err == KMMCErrNone)
   631  			{
   632  			// Check the response for voltage and check pattern
   633  			const TUint32 status = TMMC::BigEndian32(s.ResponseP());
   634  			if((status & KCmd8CheckMask) == KCmd8Param)
   635  				{
   636  				__KTRACE_OPT(KPBUS1, Kern::Printf("Found v2 card."));
   637  				OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM5, "Found v2 card" );
   638 				iCurrentOpRange |= KMMCOCRAccessModeHCS;
   639  				}
   640  			else
   641  				{
   642  				// Pattern Mis-match, card does not support the specified voltage range
   643  				OstTraceFunctionExitExt( DSDSTACK_INITIALISEMEMORYCARDSM_EXIT, this, (TInt) KMMCErrNotSupported );
   644  				return KMMCErrNotSupported;
   645  				}
   646 
   647 			SMF_GOTOS(EStCheckVoltage);
   648  			}
   649 
   650 		// Go idle again after CMD8 failure
   651 		SMF_INVOKES(GoIdleSMST, EStCheckVoltage);
   652 
   653 
   654 	SMF_STATE(EStCheckVoltage)
   655 
   656 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM6, "EStCheckVoltage" );
   657 		// If platform doesn't support an adjustable voltage PSU then there's no
   658 		// point in doing a full range for its supported range. To support range
   659 		// checking on a multi-card stack would require a complete scan of all
   660 		// cards before actually setting the range. This would over-complicate things
   661 		// and make the more normal single card/none adjustable cases less efficient.
   662 		if ( !(psu->VoltageSupported()&KMMCAdjustableOpVoltage) || iMaxCardsInStack>1)
   663 			{
   664 			// if the PSU isn't adjustable then it can't support low voltage mode
   665 			iCurrentOpRange&= ~KMMCOCRLowVoltage;
   666 
   667 			SMF_GOTOS(EStSetRangeCmd)
   668 			}
   669 
   670 	SMF_STATE(EStSetFullRangeCmd)
   671 
   672 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM7, "EStSetFullRangeCmd" );
   673 		// Issue ACMD41/CMD1 with omitted voltage range
   674 		if (iCxCardType==ESDCardTypeIsMMC)
   675 			{
   676 			s.FillCommandDesc(ECmdSendOpCond, KMMCOCRAccessModeHCS | KMMCOCRBusy); // Full range + Sector Access + Busy bit (iArgument==KBit31)
   677 			SMF_NEXTS(EStFullRangeDone)
   678 			}
   679 		else
   680 			{
   681 			DSDSession::FillAppCommandDesc(Command(), ESDACmdSDAppOpCond, TMMCArgument(0));
   682 			SMF_NEXTS(EStCheckForFullRangeCmd41Timeout)
   683 			}
   684 					
   685 		m.SetTraps(KMMCErrResponseTimeOut);
   686 		SMF_CALL(ExecCommandSMST)
   687 
   688 	SMF_STATE(EStCheckForFullRangeCmd41Timeout)
   689 	
   690 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM8, "EStCheckForFullRangeCmd41Timeout" );
   691 		if (err==KMMCErrResponseTimeOut)	
   692 			{
   693 			__KTRACE_OPT(KPBUS1, Kern::Printf("ACMD 41 not supported - Assuming MMC"));
   694 			OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM9, "ACMD 41 not supported - Assuming MMC" );
   695 			iCxCardType=ESDCardTypeIsMMC;
   696 
   697 			// Send CMD0 to re-initialise the card - otherwise we may get 
   698 			// KMMCStatErrIllegalCommand returned for the next command
   699 			// expecting an R1 response. NB The SD spec recommends ignoring the error
   700 			// whereas the SDIO spec recommends this approach (ignoring the error
   701 			// would be difficult to code anyway, since by then we're no longer
   702 			// in this state machine).
   703 			SMF_INVOKES(GoIdleSMST, EStSetFullRangeCmd);	// Repeat - but using CMD1
   704 			}
   705 		else
   706 			{
   707 			// No response timeout - so it must be an SD Card
   708 			(CardArray().CardP(iCxCardCount)->iFlags)|=KSDCardIsSDCard;
   709 			iCxCardType=ESDCardTypeIsSD;
   710 			}
   711 
   712 	SMF_STATE(EStFullRangeDone)
   713 
   714 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM10, "EStFullRangeDone" );
   715 		if (!err)												
   716 			{
   717 			// Card responded with Op range - evaluate the common subset with the current setting.
   718 			// Dont worry about the busy bit for now, we'll check that when we repeat the command
   719 			const TUint32 range = (iCurrentOpRange & ~KMMCOCRAccessModeHCS) & (TMMC::BigEndian32(s.ResponseP()) & ~KMMCOCRBusy);
   720 			if(range == 0)
   721 				{
   722 				OstTraceFunctionExitExt( DSDSTACK_INITIALISEMEMORYCARDSM_EXIT1, this, (TInt) KMMCErrNotSupported );
   723 				return KMMCErrNotSupported; // Card is incompatible with our h/w
   724 				}
   725 			iCurrentOpRange = range | (iCurrentOpRange & KMMCOCRAccessModeHCS);
   726 			}
   727 
   728 		// Repeat SEND_OP_COND this time setting Current Op Range
   729 		if (iCxCardType==ESDCardTypeIsMMC)
   730 			{
   731 			// If platform and the card both support low voltage mode (1.65 - 1.95v), switch
   732 			// NB If this fails then there is no recovery.
   733 			if (iCurrentOpRange & KMMCOCRLowVoltage)
   734 				{
   735 				iCurrentOpRange = KMMCOCRLowVoltage;
   736 				SMF_INVOKES( SwitchToLowVoltageSMST, EStSetRangeCmd )
   737 				}
   738 			}
   739 
   740 	SMF_STATE(EStSetRangeCmd)
   741 
   742 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM11, "EStSetRangeCmd" );
   743 		// Issue ACMD41/CMD1 with voltage range
   744 		if (iCxCardType==ESDCardTypeIsMMC)
   745 			{
   746 			s.FillCommandDesc(ECmdSendOpCond,(iCurrentOpRange | KMMCOCRAccessModeHCS | KMMCOCRBusy)); // Range supported + Sector Access Busy bit (iArgument==KBit31)
   747 			SMF_NEXTS(EStSetRangeBusyCheck)
   748 			}
   749 		else
   750 			{
   751 			TUint arg = (iCurrentOpRange & ~KMMCOCRAccessModeHCS); // Range supported
   752 			if((iCurrentOpRange & KMMCOCRAccessModeHCS) != 0)
   753 				{
   754 				arg |= KMMCOCRAccessModeHCS;
   755 				}
   756 			DSDSession::FillAppCommandDesc(Command(), ESDACmdSDAppOpCond, arg);
   757 			SMF_NEXTS((iCxCardType == ESDCardTypeUnknown)? EStCheckForRangeCmd41Timeout : EStSetRangeBusyCheck)
   758 			}
   759 
   760 		m.SetTraps(KMMCErrResponseTimeOut);
   761 		SMF_CALL(ExecCommandSMST)
   762 
   763 	SMF_STATE(EStCheckForRangeCmd41Timeout)
   764 	
   765 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM12, "EStCheckForRangeCmd41Timeout" );
   766 		__KTRACE_OPT(KPBUS1, Kern::Printf("-mst:ascs:crct:%d", err));
   767 		OstTrace1( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM13, "err=%d", (TInt) err);
   768 		if (err==KMMCErrResponseTimeOut)	
   769 			{
   770 			iCxCardType=ESDCardTypeIsMMC;
   771 			// Send CMD0 to re-initialise the card - otherwise we may get 
   772 			// KMMCStatErrIllegalCommand returned for the next command
   773 			// expecting an R1 response. NB The SD spec recommends ignoring the error
   774 			// whereas the SDIO spec recommends this approach (ignoring the error
   775 			// would be difficult to code anyway, since by then we're no longer
   776 			// in this state machine).
   777 			SMF_INVOKES(GoIdleSMST, EStSetRangeCmd);	// Repeat - but using CMD1
   778 			}
   779 		else
   780 			{
   781 			// No response timeout - so it must be an SD Card
   782 			__KTRACE_OPT(KPBUS1, Kern::Printf("-mst:ascs:crct2:%x", iCardArray));
   783 			__KTRACE_OPT(KPBUS1, Kern::Printf("-mst:ascs:crct3:%x", iCxCardCount));
   784 			__KTRACE_OPT(KPBUS1, Kern::Printf("-mst:ascs:crct4:%x", CardArray().CardP(iCxCardCount)));
   785 			OstTraceExt3(TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM14, "iCardArray=0x%x;iCxCardCount=%d;CardArray().CardP(iCxCardCount)=%d", (TUint) iCardArray, (TInt) iCxCardCount, (TInt) CardArray().CardP(iCxCardCount));
   786 
   787 			(CardArray().CardP(iCxCardCount)->iFlags)|=KSDCardIsSDCard;
   788 			iCxCardType=ESDCardTypeIsSD;
   789 			}
   790 			
   791 	SMF_STATE(EStSetRangeBusyCheck)
   792 
   793 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM15, "EStSetRangeBusyCheck" );
   794 		__KTRACE_OPT(KPBUS1, Kern::Printf("-mst:ascs:src:%d",iCxCardType)); // 1:MMC, 2:SD
   795 		OstTrace1( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM16, "iCxCardType=%d", iCxCardType);
   796 		
   797 		if ( !err )
   798 			{
   799 			const TUint32 ocrResponse = TMMC::BigEndian32(s.ResponseP());
   800 
   801 			if ((ocrResponse & KMMCOCRBusy) == 0)	
   802 				{
   803 				__KTRACE_OPT(KPBUS1,Kern::Printf("-sd:upd:bsy"));
   804 				// Card is still busy powering up. Check if we should timeout
   805 				if ( ++iCxPollRetryCount > iConfig.OpCondBusyTimeout() )
   806 					{
   807 					__KTRACE_OPT2(KPBUS1, KPANIC, Kern::Printf("-sd:ocr busy timed out"));
   808 					OstTraceFunctionExitExt( DSDSTACK_INITIALISEMEMORYCARDSM_EXIT2, this, (TInt) KMMCErrBusTimeOut );
   809 					return KMMCErrBusTimeOut;
   810 					}
   811 					
   812 #ifdef _DEBUG
   813 				if ( iCxPollRetryCount > KMMCSpecOpCondBusyTimeout )
   814 					{
   815 					__KTRACE_OPT2(KPBUS1, KPANIC, Kern::Printf("-sd:ocr exceeded spec timeout!! (%d ms)", (iCxPollRetryCount*KMMCRetryGapInMilliseconds)));
   816 					OstTrace1( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM17, "Exceeded spec timeout (%d ms)", (iCxPollRetryCount*KMMCRetryGapInMilliseconds));
   817 					}
   818 #endif
   819 				m.ResetTraps(); 
   820 
   821 				SMF_INVOKES(RetryGapTimerSMST,EStSetRangeCmd)
   822 				}
   823 			else
   824 				{
   825 				if(ocrResponse & KMMCOCRAccessModeHCS)
   826 					{
   827 					CardArray().CardP(iCxCardCount)->iFlags |= KMMCardIsHighCapacity;
   828 #ifdef _DEBUG				
   829 					if(iCxCardType == ESDCardTypeIsSD)
   830 						{
   831 						__KTRACE_OPT(KPBUS1, Kern::Printf("Found large SD card."));
   832 						OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM18, "Found large SD card" );
   833 						}
   834 					else if(iCxCardType == ESDCardTypeIsMMC)
   835 						{
   836 						__KTRACE_OPT(KPBUS1, Kern::Printf("Found large MMC card."));
   837 						OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM19, "Found large MMC card" );
   838 						}
   839 #endif
   840 					}
   841 				}
   842 			}
   843 
   844 		// Restore original settings
   845 		iConfig.SetMode( EffectiveModes(s.iConfig) & KMMCModeEnableTimeOutRetry );
   846 		iConfig.SetPollAttempts(KMMCMaxPollAttempts);
   847 
   848 		// All cards are now ready and notified of the voltage range - ask ASSP to set it up
   849 		if (iCxCardType==ESDCardTypeIsMMC)
   850 			{
   851 			iCurrentOpRange &= ~KMMCOCRAccessModeMask;
   852 			}
   853 		else
   854 			{
   855 			iCurrentOpRange &= ~KMMCOCRAccessModeHCS;
   856 			}
   857 
   858 		psu->SetVoltage(iCurrentOpRange);
   859 		if (psu->SetState(EPsuOnFull) != KErrNone)
   860 			{
   861 			OstTraceFunctionExitExt( DSDSTACK_INITIALISEMEMORYCARDSM_EXIT3, this, (TInt) KMMCErrHardware );
   862 			return KMMCErrHardware;
   863 			}
   864 
   865 	SMF_STATE(EStCIDCmd)
   866 
   867 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM20, "EStCIDCmd" );
   868 		s.FillCommandDesc(ECmdAllSendCID,0);
   869 		m.ResetTraps();
   870 		SMF_INVOKES(ExecCommandSMST,EStSendCIDIssued)
   871 
   872 	SMF_STATE(EStSendCIDIssued)
   873 
   874 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM21, "EStSendCIDIssued" );
   875 		// All done - Higher level state machine expects CID in s.ResponseP()
   876 
   877 	SMF_END
   878 	}
   879 
   880 TMMCErr DSDStack::ConfigureMemoryCardSMST(TAny* aStackP)
   881 	{ return static_cast<DSDStack*>(aStackP)->ConfigureMemoryCardSM(); }
   882 
   883 TMMCErr DSDStack::ConfigureMemoryCardSM()
   884 /**
   885 */
   886 	{
   887 		enum states
   888 			{
   889 			EStBegin=0,
   890 			EStSendCSDDone,
   891 			EStEnd
   892 			};
   893 
   894 		DMMCSession& s=Session();
   895 		OstTrace1( TRACE_INTERNALS, DSDSTACK_CONFIGUREMEMORYCARDSM, "Current session = 0x%x", &s );
   896 
   897 	//coverity[UNREACHABLE]
   898 	//Part of state machine design.
   899 	SMF_BEGIN
   900 
   901 		OstTrace0( TRACE_INTERNALS, DSDSTACK_CONFIGUREMEMORYCARDSM1, "EStBegin" );
   902 		// Cards is initialised so get its CSD
   903 
   904 		s.FillCommandDesc(ECmdSendCSD, TUint32(CardArray().CardP(iCxCardCount)->iRCA) << 16);
   905 		SMF_INVOKES(ExecCommandSMST, EStSendCSDDone)
   906 
   907 	SMF_STATE(EStSendCSDDone)
   908 
   909 		OstTrace0( TRACE_INTERNALS, DSDSTACK_CONFIGUREMEMORYCARDSM2, "EStSendCSDDone" );
   910 		// Store the CSD in the new card entry
   911 		TMMCard* cardP = CardArray().CardP(iCxCardCount);
   912 		cardP->iCSD = s.ResponseP();
   913 
   914 		if(CardArray().Card(iCxCardCount).IsSDCard())
   915 			{
   916 			// Perform SD Specific parsing of the CSD structure
   917 			if(cardP->CSD().CCC() & KMMCCmdClassLockCard)
   918 				{
   919 				cardP->iFlags |= KMMCardIsLockable;
   920 				}
   921 			}
   922 		else
   923 			{
   924 			// Perform MMC Specific parsing of the CSD structure
   925 			TUint specVers = cardP->CSD().SpecVers();	// 1 => 1.4, 2 => 2.0 - 2.2, 3 => 3.1
   926 			if ((specVers >= 2) && (cardP->CSD().CCC() & KMMCCmdClassLockCard))
   927 				{
   928 				cardP->iFlags |= KMMCardIsLockable;
   929 				}
   930 			}
   931 		
   932 		// Check the state of the mechanical write protect switch
   933 		if (WriteProtected(iCxCardCount))
   934 			{
   935 			cardP->iFlags |= KMMCardIsWriteProtected;
   936 			}
   937 
   938 	SMF_END
   939 	}
   940 
   941 EXPORT_C TMMCErr DSDStack::InitStackAfterUnlockSM()
   942 //
   943 // Performs initialisation of the SD card after the card has been unlocked
   944 //
   945 	{
   946 		enum states
   947 			{
   948 			EStBegin=0,
   949 			EStNextCard,
   950 			EStSelectCard,
   951 			EStSetBusWidth,
   952 			EStSetBusWidth1,
   953 			EStGetSDStatus,
   954 			EStGetSDStatus1,
   955 			EStDecodeSDStatus,
   956 			EStDeselectCard,
   957 			EStCardDeselectedReadCSD,
   958 			EStCSDCmdSent,
   959 			EStMoreCardsCheck,
   960 			EStEnd
   961 			};
   962 
   963 		DMMCSession& s=Session();
   964 		OstTrace1( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM, "Current session = 0x%x", &s );
   965 
   966 	SMF_BEGIN
   967 
   968 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM1, "EStBegin" );
   969         __KTRACE_OPT(KPBUS1, Kern::Printf(">DSDStack::InitStackAfterUnlockSM()"));
   970 		iRCAPool.ReleaseUnlocked();
   971 		iCxCardCount=0; 		// Reset current card number
   972 
   973 	SMF_STATE(EStNextCard)	    
   974 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM2, "EStNextCard" );
   975 		AddressCard(iCxCardCount); 	// Address the next card
   976 
   977 		if (!CardDetect(iCxCardCount))
   978 			SMF_GOTOS(EStMoreCardsCheck)
   979 
   980 		s.SetCard(CardArray().CardP(iCxCardCount));
   981 
   982 		if (!CardArray().Card(iCxCardCount).IsSDCard())
   983 			{
   984 			SMF_INVOKES( DMMCStack::InitCurrentCardAfterUnlockSMST, EStMoreCardsCheck )
   985 			}
   986 
   987 	SMF_STATE(EStSelectCard)
   988 
   989 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM3, "EStSelectCard" );
   990 		TRCA targetRCA = CardArray().Card(iCxCardCount).RCA();
   991 		if (targetRCA == SelectedCard())
   992 			{
   993 			SMF_GOTOS(EStSetBusWidth)
   994 			}
   995 
   996 		s.FillCommandDesc(ECmdSelectCard, targetRCA);
   997 		SMF_INVOKES(ExecCommandSMST,EStSetBusWidth)
   998 
   999 	SMF_STATE(EStSetBusWidth)
  1000 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM4, "EStSetBusWidth" );
  1001 		const TMMCStatus status = s.LastStatus();
  1002 		if((status & KMMCStatCardIsLocked) != 0)
  1003 			SMF_GOTOS(EStDeselectCard)
  1004 
  1005 		// set bus width with ACMD6
  1006 		TUint32 arg = TUint32(CardArray().Card(iCxCardCount).RCA()) << 16;
  1007 		s.FillCommandDesc(ECmdAppCmd, arg);
  1008 		SMF_INVOKES(IssueCommandCheckResponseSMST,EStSetBusWidth1)
  1009 
  1010 	SMF_STATE(EStSetBusWidth1)
  1011 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM5, "EStSetBusWidth1" );
  1012 		CardArray().Card(iCxCardCount).SetBusWidth(4);
  1013 		DSDSession::FillAppCommandDesc(Command(), ESDACmdSetBusWidth, KSDBusWidth4);
  1014 		SMF_INVOKES(IssueCommandCheckResponseSMST,EStGetSDStatus)
  1015 
  1016 	SMF_STATE(EStGetSDStatus)
  1017 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM6, "EStGetSDStatus" );
  1018 		// Now we have sent ACMD6, ask the controller to set the bus width to 4
  1019 		DoSetBusWidth(EBusWidth4);
  1020 
  1021 		// get protected area size with ACMD13
  1022 		TUint32 arg = TUint32(CardArray().Card(iCxCardCount).RCA()) << 16;
  1023 		s.FillCommandDesc(ECmdAppCmd,arg);
  1024 		SMF_INVOKES(IssueCommandCheckResponseSMST,EStGetSDStatus1)
  1025 
  1026 	SMF_STATE(EStGetSDStatus1)
  1027 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM7, "EStGetSDStatus1" );
  1028 		DSDSession::FillAppCommandDesc(Command(), ESDACmdSDStatus);
  1029 		s.FillCommandArgs(0, KSDStatusBlockLength, iPSLBuf, KSDStatusBlockLength);
  1030 		SMF_INVOKES(IssueCommandCheckResponseSMST,EStDecodeSDStatus);
  1031 
  1032 	SMF_STATE(EStDecodeSDStatus)
  1033 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM8, "EStDecodeSDStatus" );
  1034 #ifdef _DEBUG
  1035 		for (TUint i = 0; i < KSDStatusBlockLength; ++i)
  1036 			{
  1037 			__KTRACE_OPT(KPBUS1, Kern::Printf("SD_STATUS[0x%x] = %x", i, iPSLBuf[i]));
  1038 			OstTraceExt2( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM9, "SD_STATUS[0x%x]=0x%x", i, (TUint) iPSLBuf[i]);
  1039 			}
  1040 #endif
  1041 		// bits 495:480 are SD_CARD_TYPE.  Check this is 00xxh (x = don't care).
  1042 
  1043 		if (iPSLBuf[2] != 0)
  1044 		    {
  1045 			OstTraceFunctionExitExt( DSDSTACK_INITSTACKAFTERUNLOCKSM_EXIT, this, (TInt) KMMCErrNotSupported );
  1046 			return KMMCErrNotSupported;
  1047 		    }
  1048 
  1049 		// bits 479:448 contain SIZE_OF_PROTECTED_AREA.  
  1050 		// (This is bytes 4 to 7 in big-endian format.)
  1051 
  1052 		TSDCard& sdc = CardArray().Card(iCxCardCount);
  1053 		__KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack: Card %d", iCxCardCount));
  1054 		TUint32 size_of_protected_area = TMMC::BigEndian32(&iPSLBuf[4]);
  1055 		__KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack: SizeOfProtectedArea: %d", size_of_protected_area));
  1056 		OstTraceExt2( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM10, "iCxCardCount=%d;SizeOfProtectedArea=%d", iCxCardCount, (TInt) size_of_protected_area);
  1057 		const TCSD& csd = sdc.CSD();
  1058 		TUint32 pas = 0;
  1059 		
  1060 		if (sdc.IsHighCapacity())
  1061 			{
  1062 			// High Capacity Card
  1063 			// Protected Area = SIZE_OF_PROTECTED_AREA
  1064 			pas = size_of_protected_area;
  1065 			__KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack(SDHC): SetProtectedAreaSize: %d", pas));
  1066 			OstTrace1( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM11, "SDHC: SetProtectedAreaSize=%d", pas);
  1067 			}
  1068 		else
  1069 			{
  1070 			// Standard Capacity Card
  1071 			// Protected Area = SIZE_OF_PROTECTED_AREA * C_SIZE_MULT * BLOCK_LEN
  1072 			pas = size_of_protected_area * (1 << (csd.CSizeMult() + 2 + csd.ReadBlLen()));
  1073 			__KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack(SDSC): SetProtectedAreaSize: %d", pas));
  1074 			OstTrace1( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM12, "SDSC: SetProtectedAreaSize=%d", pas);
  1075 			}		
  1076 
  1077 		sdc.SetProtectedAreaSize(pas);
  1078 
  1079 		//bits 431:428 contain AU_SIZE
  1080 		//(This is higher order 4 bits of 10th byte in big endian format)
  1081 		TUint8 au = TUint8(iPSLBuf[10] >> 4);
  1082 		if(au == 0)	    //AU_SIZE field in SD status register is undefined.
  1083 			au = 6;		//Defaulting to value corresponding to 512K	
  1084 		sdc.SetAUSize(au);
  1085 
  1086 		SMF_INVOKES(SwitchToHighSpeedModeSMST, EStDeselectCard)
  1087 
  1088 	SMF_STATE(EStDeselectCard)
  1089 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM13, "EStDeselectCard" );
  1090 		s.FillCommandDesc(ECmdSelectCard, 0);
  1091 		SMF_INVOKES(ExecCommandSMST, EStCardDeselectedReadCSD)
  1092     
  1093 	SMF_STATE(EStCardDeselectedReadCSD)
  1094 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM14, "EStCardDeselectedReadCSD" );
  1095 		//
  1096       	// Read the card's CSD register (again)
  1097 		//
  1098 		//  - We re-read the CSD, as the TRAN_SPEED field may have changed due to a switch to HS Mode
  1099 		//
  1100       	TUint32 arg = TUint32(CardArray().Card(iCxCardCount).RCA()) << 16;
  1101       	s.FillCommandDesc( ECmdSendCSD, arg );
  1102       	SMF_INVOKES(ExecCommandSMST, EStCSDCmdSent)
  1103 
  1104 	SMF_STATE(EStCSDCmdSent)
  1105 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM15, "EStCSDCmdSent" );
  1106 		//
  1107       	// Store the CSD in the card entry
  1108 		//
  1109       	TMMCard* cardP = iCardArray->CardP(iCxCardCount);
  1110       	cardP->iCSD = s.ResponseP();
  1111 
  1112 	SMF_STATE(EStMoreCardsCheck)
  1113 		OstTrace0( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM16, "EStMoreCardsCheck" );
  1114 		if (++iCxCardCount < (TInt)iMaxCardsInStack)
  1115 		    {
  1116 		    __KTRACE_OPT(KPBUS1, Kern::Printf("\t >DSDStack: Address Next card: %d",iCxCardCount));
  1117 		    OstTrace1( TRACE_INTERNALS, DSDSTACK_INITSTACKAFTERUNLOCKSM17, "Address Next card=%d", iCxCardCount);
  1118 			SMF_GOTOS(EStNextCard)
  1119 		    }
  1120 		else
  1121 		    {
  1122 			AddressCard(KBroadcastToAllCards);
  1123 			__KTRACE_OPT(KPBUS1, Kern::Printf("<DSDStack::InitStackAfterUnlockSM()"));
  1124 		    }
  1125 
  1126 	SMF_END
  1127 	
  1128 	}
  1129 
  1130 TMMCErr DSDStack::CIMReadWriteMemoryBlocksSMST(TAny* aStackP)
  1131 	{ return( static_cast<DSDStack *>(aStackP)->DMMCStack::CIMReadWriteBlocksSM() ); }
  1132 
  1133 
  1134 EXPORT_C TMMCErr DSDStack::CIMReadWriteBlocksSM()
  1135 //
  1136 // This macro performs single/multiple block reads and writes
  1137 // For normal read/write block operations, this function determines the appropriate
  1138 // MMC command to send and fills the command descriptor accordingly based on 
  1139 // the value of the session ID set. However, it is necessary to have set the
  1140 // command arguments (with DMMCSession::FillCommandArgs()) before this function
  1141 // is called.
  1142 // For special block read/write operations, e.g. lock/unlock, it is required to
  1143 // have already filled the command descriptor (with DMMCSession::FillCommandDesc())
  1144 // for the special command required - in addition to have setup the command arguments.
  1145 //
  1146 	{
  1147 		enum states
  1148 			{
  1149 			EStBegin=0,
  1150 			EStRestart,
  1151 			EStAttached,
  1152 			EStLength1,
  1153 			EStLengthSet,
  1154 			EStIssued,
  1155 			EStWaitFinish,
  1156 			EStWaitFinish1,
  1157 			EStRWFinish,
  1158 			EStDone,
  1159 			EStEnd
  1160 			};
  1161 
  1162 		DMMCSession& s = Session();
  1163 		OstTrace1( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM, "Current session = 0x%x", &s );
  1164 
  1165 		__KTRACE_OPT(KPBUS1,Kern::Printf(">SD:RWBlocksSM %x",TUint(s.iLastStatus)));
  1166 
  1167 	SMF_BEGIN
  1168 
  1169         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM1, "EStBegin" );
  1170 		TSDCard& sdCard = *static_cast<TSDCard*>(s.iCardP);
  1171 		AddressCard(sdCard.iIndex-1);
  1172 
  1173 		if(sdCard.IsSDCard() == EFalse)
  1174 			{
  1175 			//
  1176 			// If this is not an SD card, then use the more appropriate
  1177 			// MMC state machine as this is optimised for MMC performance
  1178 			//
  1179 			SMF_INVOKES(CIMReadWriteMemoryBlocksSMST, EStDone);
  1180 			}
  1181 
  1182 		if(s.iSessionID == ECIMWriteBlock || s.iSessionID == ECIMWriteMBlock)
  1183 			{
  1184 			// Check that the card supports class 4 (Write) commands
  1185 			const TUint ccc = s.iCardP->CSD().CCC();
  1186 			if(!(ccc & KMMCCmdClassBlockWrite))
  1187 			    {
  1188 				OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT, this, (TInt) KMMCErrNotSupported );
  1189 				return KMMCErrNotSupported;
  1190 			    }
  1191 			}
  1192 
  1193 		Command().iCustomRetries = 0;			// MBW retries
  1194 		s.iState |= KMMCSessStateInProgress;
  1195 		m.SetTraps(KMMCErrInitContext);
  1196 
  1197 	SMF_STATE(EStRestart)		// NB: ErrBypass is not processed here
  1198 
  1199         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM2, "EStRestart" );
  1200 		SMF_CALLMEWR(EStRestart) // Create a recursive call entry to recover from the errors trapped
  1201 		m.SetTraps(KMMCErrStatus);
  1202 		if (s.Command().iSpec.iCommandClass!=KMMCCmdClassApplication || s.Command().iCommand==ECmdAppCmd )
  1203 			{
  1204 			s.ResetCommandStack();
  1205 			SMF_INVOKES( AttachCardSMST, EStAttached )	// attachment is mandatory here
  1206 			}
  1207 
  1208 	SMF_BPOINT(EStAttached)
  1209 
  1210         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM3, "EStAttached" );
  1211 		TMMCCommandDesc& cmd = s.Command();
  1212 
  1213 		const TUint32 blockLength = cmd.BlockLength();
  1214 		if((blockLength == 0) || (blockLength > (TUint)KDefaultBlockLenInBytes))
  1215 			{
  1216 			__KTRACE_OPT(KPBUS1,Kern::Printf(">SD:RWBlocksSM err BlockLen:%d",blockLength));
  1217 			OstTrace1( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM4, "blockLength=%d", blockLength );
  1218 			OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT1, this, (TInt) KMMCErrArgument );
  1219 			return KMMCErrArgument;
  1220 			}
  1221 
  1222 		if(s.iSessionID == ECIMReadBlock	||
  1223 		   s.iSessionID == ECIMWriteBlock	||
  1224 		   s.iSessionID == ECIMReadMBlock	||
  1225 		   s.iSessionID == ECIMWriteMBlock)
  1226 			{	
  1227 			// read/write operation
  1228 			if(!cmd.AdjustForBlockOrByteAccess(s))
  1229 				{
  1230 				// unable to convert command arguments to suit the underlying block/byte access mode
  1231 				OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT2, this, (TInt) KMMCErrArgument );
  1232 				return KMMCErrArgument;
  1233 				}
  1234 			}
  1235 
  1236 		// Set the block length if it has changed. Always set for ECIMLockUnlock.
  1237 		if ((blockLength == s.iCardP->iSetBlockLen) && (s.iSessionID != ECIMLockUnlock))
  1238 			{
  1239 			SMF_GOTOS( EStLengthSet )
  1240 			}
  1241 
  1242 		s.iCardP->iSetBlockLen = 0;
  1243 		s.PushCommandStack();
  1244 		s.FillCommandDesc( ECmdSetBlockLen, blockLength );
  1245 		SMF_INVOKES( ExecCommandSMST, EStLength1 )
  1246 
  1247 	SMF_STATE(EStLength1)
  1248 
  1249         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM5, "EStLength1" );
  1250 		const TMMCStatus status(s.ResponseP());
  1251 		s.PopCommandStack();
  1252 		if (status.Error())
  1253 		    {
  1254 		    OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT3, this, (TInt) KMMCErrStatus );
  1255 			SMF_RETURN(KMMCErrStatus)
  1256 		    }
  1257 		s.iCardP->iSetBlockLen = s.Command().BlockLength();
  1258 
  1259 	SMF_STATE(EStLengthSet)
  1260 
  1261         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM6, "EStLengthSet" );
  1262 		TMMCCommandDesc& cmd = s.Command();
  1263 		TUint opType = 0;
  1264 		const TUint kTypeWrite =	KBit0;
  1265 		const TUint kTypeMultiple =	KBit1;
  1266 		const TUint kTypeSpecial =	KBit2;
  1267 		static const TMMCCommandEnum cmdCodes[4] =
  1268 			{ECmdReadSingleBlock, ECmdWriteBlock, ECmdReadMultipleBlock, ECmdWriteMultipleBlock};
  1269 
  1270 		switch( s.iSessionID )
  1271 			{
  1272 			case ECIMReadBlock:
  1273 				break;
  1274 			case ECIMWriteBlock:
  1275 				opType=kTypeWrite;
  1276 				break;
  1277 			case ECIMReadMBlock:
  1278 				opType=kTypeMultiple;
  1279 				break;
  1280 			case ECIMWriteMBlock:
  1281 				opType=kTypeWrite|kTypeMultiple;
  1282 				break;
  1283 			case ECIMLockUnlock:
  1284 			default:
  1285 				opType=kTypeSpecial;
  1286 				break;
  1287 			}
  1288 
  1289 		const TUint blocks = cmd.iTotalLength / cmd.BlockLength();
  1290 		if ( blocks * cmd.BlockLength() != cmd.iTotalLength )
  1291 		    {
  1292 			OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT4, this, (TInt) KMMCErrArgument );
  1293 			return KMMCErrArgument;
  1294 		    }
  1295 
  1296 		if ( !(opType & kTypeSpecial) )	// A special session has already set its command descriptor
  1297 			{
  1298 			if (blocks==1)
  1299 				opType &= ~kTypeMultiple;
  1300 
  1301 			TUint32 oldFlags = cmd.iFlags;		// Store the existing command flags, as they will be reset by FillCommandDesc()
  1302 			cmd.iCommand = cmdCodes[opType];
  1303 			s.FillCommandDesc();
  1304 			cmd.iFlags = oldFlags;				// ...and restore the old command flags
  1305 			}
  1306 
  1307 		// NB We need to trap KMMCErrStatus errors, because if one occurs, 
  1308 		// we still need to wait to exit PRG/RCV/DATA state 
  1309 		if (Command().iCommand == ECmdWriteMultipleBlock)
  1310 			{
  1311 			Command().iExecNotHandle = KMMCErrDataCRC | KMMCErrDataTimeOut;
  1312 			m.SetTraps(KMMCErrStatus | KMMCErrDataCRC | KMMCErrDataTimeOut);
  1313 			}
  1314 		else
  1315 			{
  1316 			m.SetTraps(KMMCErrStatus);
  1317 			}
  1318 
  1319 		SMF_INVOKES( ExecCommandSMST, EStIssued )
  1320 
  1321 	SMF_STATE(EStIssued)
  1322 
  1323         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM7, "EStIssued" );
  1324 		// check state of card after data transfer with CMD13.
  1325 		if (s.Command().Direction() != 0)
  1326 			{
  1327 			SMF_GOTOS(EStWaitFinish)
  1328 			}
  1329 
  1330 		SMF_GOTOS(EStRWFinish);
  1331 
  1332 	SMF_STATE(EStWaitFinish)
  1333         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM8, "EStWaitFinish" );
  1334 		// if MBW fail, then recover by rewriting ALL blocks...
  1335 		// (used to recover using ACMD22, but this has been changed
  1336 		// as is difficult to test for little gain in efficiency)
  1337 		if (Command().iCommand == ECmdWriteMultipleBlock && err != 0)
  1338 			{
  1339 			if (Command().iCustomRetries++ >= (TInt) KSDMaxMBWRetries)
  1340 				{
  1341 				OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT5, this, (TInt) err );
  1342 				SMF_RETURN(err)
  1343 				}
  1344 
  1345 			m.Pop();		// remove recursive call to EStRestart
  1346 			SMF_GOTOS(EStRestart)			
  1347 			}
  1348 
  1349 		// Save the status and examine it after issuing CMD13...
  1350 		// NB We don't know where in the command stack the last response is stored (e.g. there may 
  1351 		// have bee a Deselect/Select issued), but we do know last response is stored in iLastStatus
  1352 		TMMC::BigEndian4Bytes(s.ResponseP(), s.iLastStatus);
  1353 
  1354 		// ...else issue CMD13 to poll for the card finishing and check for errors
  1355 		s.PushCommandStack();
  1356 		s.FillCommandDesc(ECmdSendStatus, 0);
  1357 		SMF_INVOKES(ExecCommandSMST, EStWaitFinish1)
  1358 
  1359 	SMF_STATE(EStWaitFinish1)
  1360 
  1361         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM9, "EStWaitFinish1" );
  1362 		const TMMCStatus status(s.ResponseP());
  1363 		s.PopCommandStack();
  1364 
  1365 #ifdef __WINS__
  1366 		SMF_GOTOS(EStRWFinish);
  1367 #else
  1368 		const TMMCardStateEnum st1 = status.State();
  1369 
  1370 		if (st1 == ECardStatePrg || st1 == ECardStateRcv || st1 == ECardStateData)
  1371 			{
  1372 			SMF_INVOKES(ProgramTimerSMST, EStWaitFinish);
  1373 			}
  1374 
  1375 		if (status.Error())
  1376 		    {
  1377 			OstTraceFunctionExitExt( DUP7_DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT, this, (TInt) KMMCErrStatus );
  1378 			SMF_RETURN(KMMCErrStatus)
  1379 		    }
  1380 #endif
  1381 		
  1382 		// Fall through if CURRENT_STATE is not PGM or DATA
  1383 	SMF_STATE(EStRWFinish)
  1384 
  1385         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM10, "EStRWFinish" );
  1386 		if (TMMCStatus(s.ResponseP()).Error() != 0)
  1387 		    {
  1388 		    OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT6, this, (TInt) KMMCErrStatus );
  1389 			SMF_RETURN(KMMCErrStatus);
  1390 		    }
  1391 
  1392 		s.iState &= ~KMMCSessStateInProgress;
  1393 
  1394 		// skip over recursive entry or throw error and catch in CIMLockUnlockSM()
  1395 		TMMCErr ret = (s.Command().iCommand == ECmdLockUnlock) ? KMMCErrUpdPswd : KMMCErrBypass; 
  1396 		OstTraceFunctionExitExt( DSDSTACK_CIMREADWRITEBLOCKSSM_EXIT7, this, (TInt) ret );
  1397 		return ret;
  1398 
  1399 	SMF_STATE(EStDone)
  1400 	    
  1401         OstTrace0( TRACE_INTERNALS, DSDSTACK_CIMREADWRITEBLOCKSSM11, "EStDone" );
  1402 	    __KTRACE_OPT(KPBUS1,Kern::Printf("<SD:RWBlocksSM()"));
  1403 
  1404 	SMF_END
  1405 	}
  1406 
  1407 EXPORT_C TMMCErr DSDStack::ModifyCardCapabilitySM()
  1408 //
  1409 // This function provides a chance to modify the capability of paticular cards.
  1410 // Licensee may overide this function to modify certain card's capability as needed.
  1411 // A state machine is needed in derived function and function of base class should be
  1412 // called in order to act more generic behaviour.
  1413 //
  1414     {
  1415 		enum states
  1416 			{
  1417 			EStBegin=0,
  1418 			EStDone,
  1419 			EStEnd
  1420 			};
  1421 
  1422 	//coverity[unreachable]
  1423 	//Part of state machine design.
  1424 	SMF_BEGIN
  1425 
  1426         OstTrace0( TRACE_INTERNALS, DSDSTACK_MODIFYCARDCAPABILITYSM, "EStBegin" );
  1427     	SMF_INVOKES( DMMCStack::BaseModifyCardCapabilitySMST, EStDone )
  1428 
  1429     SMF_STATE(EStDone)
  1430     
  1431         OstTrace0( TRACE_INTERNALS, DSDSTACK_MODIFYCARDCAPABILITYSM1, "EStDone" );
  1432 
  1433     SMF_END
  1434 	}
  1435 
  1436 inline TMMCErr DSDStack::SwitchToHighSpeedModeSMST( TAny* aStackP )
  1437 	{ return( static_cast<DSDStack *>(aStackP)->DSDStack::SwitchToHighSpeedModeSM() ); }
  1438 
  1439 TMMCErr DSDStack::SwitchToHighSpeedModeSM()
  1440 	{
  1441 		enum states
  1442 			{
  1443 			EStBegin=0,
  1444 			EstCheckController,
  1445 			EStSendSCRCmd,
  1446 			EStCheckSpecVer,
  1447 			EStCheckFunction,
  1448 			EStCheckFunctionSent,
  1449 			EStSwitchFunctionSent,
  1450 			EStDone,
  1451 			EStEnd
  1452 			};
  1453 
  1454 		__KTRACE_OPT(KPBUS1,Kern::Printf(">SD:SwitchToHighSpeedModeSM "));
  1455 
  1456 		DMMCSession& s = Session();
  1457 		OstTrace1( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM, "Current session = 0x%x", &s );
  1458 
  1459 	SMF_BEGIN
  1460 
  1461         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM1, "EStBegin");
  1462 	
  1463 	SMF_STATE(EstCheckController) 	
  1464         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM2, "EstCheckController");
  1465 	  	// Get the clock speed supported by the controller
  1466 		TMMCMachineInfoV4 machineInfo;
  1467 		TMMCMachineInfoV4Pckg machineInfoPckg(machineInfo);
  1468 		MachineInfo(machineInfoPckg);
  1469 		
  1470 		if (machineInfo.iVersion >= TMMCMachineInfoV4::EVersion4)
  1471 			{
  1472 			if (machineInfo.iMaxClockSpeedInMhz < (KSDDTClk50MHz/1000) )
  1473 				{
  1474 				__KTRACE_OPT(KPBUS1, Kern::Printf("High speed mode not supported by controller"));
  1475 				OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM3, "High speed mode not supported by controller");
  1476 				SMF_GOTOS(EStDone);
  1477 				}
  1478 			}	
  1479 
  1480 	SMF_STATE(EStSendSCRCmd)
  1481         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM4, "EStSendSCRCmd");
  1482 		//
  1483       	// ACMD51 Read the SD Configuration Register
  1484       	//
  1485 		DSDSession::FillAppCommandDesc(Command(), ESDACmdSendSCR);
  1486       	s.FillCommandArgs(0, KSDSCRLength, iPSLBuf, KSDSCRLength);
  1487       	SMF_INVOKES(ExecCommandSMST, EStCheckSpecVer);
  1488 
  1489 	SMF_STATE(EStCheckSpecVer)
  1490         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM5, "EStCheckSpecVer");
  1491       	//	
  1492       	// Check the SD version
  1493 		//
  1494       	// 0 : version 1.0-1.01	: SDHS Is NOT Supported
  1495       	// 1 : version 1.10+	: SDHS Is Supported
  1496 		//
  1497       	__KTRACE_OPT(KPBUS1,Kern::Printf("   SD Configuration Register received"));
  1498       	__KTRACE_OPT(KPBUS1,Kern::Printf("   ...card_status=%x", TUint(s.iLastStatus)));
  1499       	OstTrace1( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM6, "SD Configuration Register received: card_status=0x%x", (TUint) s.iLastStatus);
  1500 
  1501 #ifdef _DEBUG
  1502       	for (TUint32 i = 0; i < KSDSCRLength; ++i)
  1503 			{
  1504 			__KTRACE_OPT(KPBUS1, Kern::Printf("   ...SCR_STATUS[0x%x] = %x", i, iPSLBuf[i]));
  1505 			}
  1506 #endif
  1507 
  1508       	if(iPSLBuf[0]==2)
  1509 			{
  1510 			__KTRACE_OPT(KPBUS1,Kern::Printf("   ...SD Spec Version 2"));
  1511 			OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM7, "SD Spec Version 2");
  1512 			SMF_GOTOS(EStCheckFunction);
  1513 			}
  1514   
  1515       	if(iPSLBuf[0]==1)
  1516 			{
  1517 			__KTRACE_OPT(KPBUS1,Kern::Printf("   ...SD Spec Version 1.10"));
  1518 			OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM8, "SD Spec Version 1.10");
  1519 			SMF_GOTOS(EStCheckFunction);
  1520 			}
  1521   
  1522       	if(iPSLBuf[0]==0)
  1523 			{
  1524 			__KTRACE_OPT(KPBUS1,Kern::Printf("   ...SD Spec Version 1.01"));
  1525 			OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM9, "SD Spec Version 1.01");
  1526 			SMF_GOTOS(EStDone);
  1527         	}
  1528 
  1529 	__KTRACE_OPT(KPBUS1,Kern::Printf("   ...SD Spec Version > 2 !"));
  1530 	OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM10, "SD Spec Version > 2");
  1531 
  1532 	SMF_STATE(EStCheckFunction)
  1533 
  1534         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM11, "EStCheckFunction");
  1535 		m.SetTraps(KMMCErrResponseTimeOut | KMMCErrNotSupported);
  1536 
  1537  		//
  1538 		// SD1.1 uses CMD6 which is not defined by the MMCA
  1539 		//  - fill in command details using the SD Specific command description table
  1540 		//
  1541 
  1542 		DSDSession::FillSdSpecificCommandDesc(Command(), ESDCmdSwitchFunction);
  1543 		s.FillCommandArgs(KSDCheckFunctionHighSpeed, KSDSwitchFuncLength, iPSLBuf, KSDSwitchFuncLength);
  1544 
  1545 		SMF_INVOKES(IssueCommandCheckResponseSMST,EStCheckFunctionSent)
  1546 
  1547 	SMF_STATE(EStCheckFunctionSent)
  1548  
  1549         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM12, "EStCheckFunctionSent");
  1550        	__KTRACE_OPT(KPBUS1,Kern::Printf("   CheckFunctionSent %x",TUint(s.iLastStatus)));
  1551        	OstTrace1( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM13, "CheckFunctionSent=0x%x", (TUint) s.iLastStatus);
  1552 
  1553 		m.ResetTraps();
  1554 
  1555 		if(err == KMMCErrResponseTimeOut)
  1556 			{
  1557 	       	__KTRACE_OPT(KPBUS1,Kern::Printf("   ...CMD6 [Read] Response Timeout"));
  1558 	       	OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM14, "CMD6 [Read] Response Timeout");
  1559 			SMF_GOTOS(EStDone);
  1560 			}
  1561 		else if(err == KMMCErrNotSupported)
  1562 			{
  1563 	       	__KTRACE_OPT(KPBUS1,Kern::Printf("   ...CMD6 [Read] Not Supported"));
  1564 	       	OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM15, "CMD6 [Read] Not Supported");
  1565 			SMF_GOTOS(EStDone);
  1566 			}
  1567 
  1568 #ifdef _DEBUG
  1569 		for (TUint32 i = 0; i < KSDSwitchFuncLength; ++i)
  1570 			{
  1571 	  		__KTRACE_OPT(KPBUS1, Kern::Printf("   ...SD Switch Func Status[0x%x] = %x", i, iPSLBuf[i]));
  1572 			}
  1573 
  1574 		m.SetTraps(KMMCErrResponseTimeOut);
  1575 #endif
  1576 
  1577  		//
  1578 		// SD1.1 uses CMD6 which is not defined by the MMCA
  1579 		//  - fill in command details using the SD Specific command description table
  1580 		//
  1581 
  1582 		DSDSession::FillSdSpecificCommandDesc(Command(), ESDCmdSwitchFunction);
  1583       	s.FillCommandArgs(KSDSwitchFunctionHighSpeed, KSDSwitchFuncLength, iPSLBuf, KSDSwitchFuncLength);
  1584 
  1585       	SMF_INVOKES(IssueCommandCheckResponseSMST,EStSwitchFunctionSent)
  1586 	
  1587 	SMF_STATE(EStSwitchFunctionSent)
  1588 
  1589         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM16, "EStSwitchFunctionSent");
  1590 #ifdef _DEBUG
  1591 		m.ResetTraps();
  1592 
  1593 		if(err == KMMCErrResponseTimeOut)
  1594 			{
  1595 	       	__KTRACE_OPT(KPBUS1,Kern::Printf("   ...CMD6 [Write] Response Timeout"));
  1596 	       	OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM17, "CMD6 [Write] Response Timeout");
  1597 			}
  1598 
  1599 		for (TUint32 i = 0; i < KSDSwitchFuncLength; ++i)
  1600 			{
  1601 	  		__KTRACE_OPT(KPBUS1, Kern::Printf("   ...SD Switch[0x%x] = %x", i, iPSLBuf[i]));
  1602 	  		OstTraceExt2( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM18, "SD Switch[0x%x]=0x%x", (TUint) i, (TUint) iPSLBuf[i]);
  1603 			}
  1604 #endif
  1605 
  1606 	SMF_STATE(EStDone)
  1607 	
  1608         OstTrace0( TRACE_INTERNALS, DSDSTACK_SWITCHTOHIGHSPEEDMODESM19, "EStSwitchFunctionSent");
  1609       
  1610 	SMF_END
  1611 	}
  1612 
  1613 
  1614 EXPORT_C DMMCSession* DSDStack::AllocSession(const TMMCCallBack& aCallBack) const
  1615 /**
  1616 * Factory function to create DMMCSession derived object.  Non-generic MMC
  1617 * controllers can override this to generate more specific objects.
  1618 * @param aCallBack Callback function to notify the client that a session has completed
  1619 * @return A pointer to the new session
  1620 */
  1621 	{
  1622 	OstTraceFunctionEntry1( DSDSTACK_ALLOCSESSION_ENTRY, this );
  1623 	return new DSDSession(aCallBack);
  1624 	}
  1625 
  1626 EXPORT_C void DSDStack::Dummy1() {}
  1627 EXPORT_C void DSDStack::Dummy2() {}
  1628 EXPORT_C void DSDStack::Dummy3() {}
  1629 EXPORT_C void DSDStack::Dummy4() {}