os/boardsupport/emulator/emulatorbsp/specific/sdcard/sdcard4c/pp_cprm.cpp
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/boardsupport/emulator/emulatorbsp/specific/sdcard/sdcard4c/pp_cprm.cpp	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,1327 @@
     1.4 +// Copyright (c) 2000-2009 Nokia Corporation and/or its subsidiary(-ies).
     1.5 +// All rights reserved.
     1.6 +// This component and the accompanying materials are made available
     1.7 +// under the terms of "Eclipse Public License v1.0"
     1.8 +// which accompanies this distribution, and is available
     1.9 +// at the URL "http://www.eclipse.org/legal/epl-v10.html".
    1.10 +//
    1.11 +// Initial Contributors:
    1.12 +// Nokia Corporation - initial contribution.
    1.13 +//
    1.14 +// Contributors:
    1.15 +//
    1.16 +// Description:
    1.17 +//
    1.18 +
    1.19 +#include "plat_priv.h"
    1.20 +#include <property.h>
    1.21 +#include <variant.h>
    1.22 +#include "pp_cprm.h" 
    1.23 +
    1.24 +const TInt  KDiskSectorSize=512;
    1.25 +
    1.26 +const TInt KTotalMDiskSize=0x100000; // 1MB (if changing this then also change CSD response)
    1.27 +
    1.28 +// ======== error code conversion ========
    1.29 +
    1.30 +GLDEF_C TInt MapLastErrorEpoc()
    1.31 +//
    1.32 +// map an Win32 error code to Epoc32 value
    1.33 +//
    1.34 +	{
    1.35 +	TInt res=KErrGeneral;
    1.36 +	switch (GetLastError())
    1.37 +		{
    1.38 +		case ERROR_SHARING_VIOLATION : res=KErrAccessDenied; break;
    1.39 +		case ERROR_LOCK_VIOLATION : res=KErrLocked; break;
    1.40 +		case ERROR_FILE_NOT_FOUND: res=KErrNotFound; break;
    1.41 +		case ERROR_PATH_NOT_FOUND: res=KErrPathNotFound; break;
    1.42 +		case ERROR_ALREADY_EXISTS:
    1.43 +		case ERROR_FILE_EXISTS:
    1.44 +			res=KErrAlreadyExists;
    1.45 +			break;
    1.46 +		case ERROR_NOT_READY: res=KErrNotReady; break;
    1.47 +		case ERROR_UNRECOGNIZED_VOLUME:
    1.48 +		case ERROR_NOT_DOS_DISK:
    1.49 +			res=KErrUnknown;
    1.50 +			break;
    1.51 +		case ERROR_UNRECOGNIZED_MEDIA: res=KErrCorrupt; break;
    1.52 +		case ERROR_INVALID_NAME: res=KErrBadName; break;
    1.53 +		case ERROR_NO_MORE_FILES: res=KErrEof; break;
    1.54 +		}
    1.55 +	return(res);
    1.56 +	}
    1.57 +
    1.58 +GLDEF_C TMMCErr MapLastErrorMmc()
    1.59 +//
    1.60 +// map Win32 error to a TMMCErr error.
    1.61 +//
    1.62 +	{
    1.63 +	DWORD r=GetLastError();
    1.64 +	TInt res=KErrGeneral;
    1.65 +	switch (r)
    1.66 +		{
    1.67 +		case ERROR_SHARING_VIOLATION:
    1.68 +		case ERROR_LOCK_VIOLATION:
    1.69 +			res=KMMCErrLocked;			// KErrLocked
    1.70 +			break;
    1.71 +		case ERROR_FILE_NOT_FOUND:
    1.72 +		case ERROR_PATH_NOT_FOUND:
    1.73 +			res=KMMCErrNotFound;		// KErrNotFound
    1.74 +			break;
    1.75 +		case ERROR_ALREADY_EXISTS:
    1.76 +		case ERROR_FILE_EXISTS:
    1.77 +			res=KMMCErrAlreadyExists;	// KErrAlreadyExists
    1.78 +			break;
    1.79 +		case ERROR_NOT_READY: res=KMMCErrNoCard; break;
    1.80 +		case ERROR_UNRECOGNIZED_VOLUME:
    1.81 +		case ERROR_NOT_DOS_DISK:
    1.82 +			res=KMMCErrGeneral;			// KErrGeneral
    1.83 +			break;
    1.84 +		case ERROR_UNRECOGNIZED_MEDIA:
    1.85 +		case ERROR_INVALID_NAME:
    1.86 +		case ERROR_NO_MORE_FILES:
    1.87 +			res=KMMCErrResponseCRC; 	// KErrCorrupt
    1.88 +			break;
    1.89 +		}
    1.90 +	return(res);
    1.91 +	}
    1.92 +
    1.93 +// ======== DWinsCPRMStack ========
    1.94 +
    1.95 +DWinsCPRMStack::DWinsCPRMStack(TInt aBus, DMMCSocket* aSocket)
    1.96 +: DCPRMStack(aBus, aSocket)
    1.97 +	{	
    1.98 +	iAddressedCard=KBroadcastToAllCards;
    1.99 +//	iCMD42Failed=EFalse;
   1.100 +	}
   1.101 +
   1.102 +
   1.103 +TInt DWinsCPRMStack::Init()
   1.104 +//
   1.105 +// Allocate any resources. Only created once on kernel initialization so dont
   1.106 +// worry about cleanup if it leaves.
   1.107 +//
   1.108 +	{
   1.109 +	if((iCardArray = new TSDCardArray(this)) == NULL)
   1.110 +		return KErrNoMemory;
   1.111 +
   1.112 +	TInt r=DCPRMStack::Init();
   1.113 +	if(r!=KErrNone)
   1.114 +		return r;
   1.115 +
   1.116 +	DMediaChangeBase* pMCBase = MMCSocket()->iMediaChange;
   1.117 +	static_cast<DWinsMMCMediaChange*>(pMCBase)->SetStackP(this);
   1.118 +	Wins::SetMediaChangeCallBackPtr(DWinsMMCMediaChange::MediaChangeCallBack, (TAny*)pMCBase);
   1.119 +
   1.120 +	//
   1.121 +	// Over time memory can become fragmented, and so it is not possible to
   1.122 +	// allocate physically contiguous pages.  Therefore, the buffers for IO
   1.123 +	// are allocated at startup.
   1.124 +	//
   1.125 +	// block and erase sector size characteristics depend on the specific
   1.126 +	// card model, and so the initial values are estimates based on a typical
   1.127 +	// card.  If these do not match the actual card's block size (or erase
   1.128 +	// size, for SD,) then the media driver just gets a reduced or increased
   1.129 +	// buffer area, and its efficiency varies accordingly.
   1.130 +	//
   1.131 +	// For the WINS implementation, fragmentation does not matter because
   1.132 +	// DMA is not used.  The memory must still be allocated here so MEDMMC is
   1.133 +	// able to use it.
   1.134 +	//
   1.135 +	// The constant calculations could be folded, but this illustrates how the
   1.136 +	// values are derived.
   1.137 +	//
   1.138 +
   1.139 +	// MMC - values from Hitachi 16Mb card, datasheet HB288016MM1
   1.140 +
   1.141 +	// minor buffer must contain enough space for MBR or block
   1.142 +	const TUint mmcBlkSzLog2 = 9;				// READ_BLK_LEN and WRITE_BLK_LEN
   1.143 +	const TUint mmcBlkSz = 1 << mmcBlkSzLog2;
   1.144 +	const TInt mmcMinorBufLen = Max(KDiskSectorSize, mmcBlkSz);
   1.145 +
   1.146 +	const TInt KMinMMCBlocksInBuffer = 8;
   1.147 +	const TInt mmcCchBufLen = KMinMMCBlocksInBuffer << mmcBlkSzLog2;
   1.148 +
   1.149 +	const TInt mmcTotalBufLen = mmcMinorBufLen + mmcCchBufLen;
   1.150 +
   1.151 +	// SDCard - values from 64Mb Panasonic RP-SD064
   1.152 +
   1.153 +	const TUint sdBlkSzLog2 = 9;				// READ_BL_LEN and WRITE_BLK_LEN
   1.154 +	const TUint sdBlkSz = 1 << sdBlkSzLog2;
   1.155 +	const TInt sdMinorBufLen = Max(KDiskSectorSize, sdBlkSz);
   1.156 +
   1.157 +	const TUint ss = 0x1f;						// SECTOR_SIZE, add 1 for sector count
   1.158 +	const TInt KMinSDBlocksInBuffer = 8;
   1.159 +	const TInt sdCchBufLen = Max(KMinSDBlocksInBuffer, ss + 1) << sdBlkSzLog2;
   1.160 +
   1.161 +	const TInt sdTotalBufLen = sdMinorBufLen + sdCchBufLen;
   1.162 +
   1.163 +	const TInt totalBufLen = Max(mmcTotalBufLen, sdTotalBufLen);
   1.164 +
   1.165 +	iMDBuf = reinterpret_cast<TUint8*>(Kern::Alloc(totalBufLen));
   1.166 +	iMDBufLen = totalBufLen;
   1.167 +
   1.168 +	// initialize each card on the stack
   1.169 +	TInt i;
   1.170 +	for (i = 0; i < KTotalWinsCards; ++i)
   1.171 +		{
   1.172 +		TInt r = SetupSimulatedCard(i);
   1.173 +		if (r != KErrNone)
   1.174 +			return r;
   1.175 +		}
   1.176 +
   1.177 +	// initialize pointers to currently present cards
   1.178 +
   1.179 +	// Slot zero can toggle between no card; card 0 and card 1.  The current state is
   1.180 +	// determined by *Wins::CurrentPBusDevicePtr() and toggled by pressing F4 when F5
   1.181 +	// (door open) is held down.  Because this function is only executed at startup,
   1.182 +	// assume start with card zero.
   1.183 +	iCardInfo[0] = iCardPool[0];
   1.184 +	for (i = 1; i < KTotalWinsCardSlots; ++i)
   1.185 +		{
   1.186 +		iCardInfo[i]=iCardPool[i+1];
   1.187 +		}
   1.188 +
   1.189 +	return KErrNone;
   1.190 +	}
   1.191 +
   1.192 +void DWinsCPRMStack::MachineInfo(TMMCMachineInfo& aMachineInfo)
   1.193 +	{
   1.194 +	aMachineInfo.iTotalSockets=KTotalWinsCardSlots;
   1.195 +	aMachineInfo.iTotalMediaChanges=0;  		// Not used at present
   1.196 +	aMachineInfo.iTotalPrimarySupplies=0;		// Not used at present
   1.197 +
   1.198 +	aMachineInfo.iSPIMode=EFalse;
   1.199 +    aMachineInfo.iBaseBusNumber=0;
   1.200 +
   1.201 +	__ASSERT_DEBUG(aMachineInfo.iTotalSockets<=KMaxMMCardsPerStack,
   1.202 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCBadMachineInfo));
   1.203 +	}
   1.204 +
   1.205 +void DWinsCPRMStack::AdjustPartialRead(
   1.206 +#ifdef _DEBUG
   1.207 +	const TMMCard* aCard,
   1.208 +#else
   1.209 +	const TMMCard* /*aCard*/,
   1.210 +#endif
   1.211 +	TUint32 aStart, TUint32 aEnd, TUint32* aPhysStart, TUint32* aPhysEnd) const
   1.212 +	{
   1.213 +#ifdef _DEBUG
   1.214 +	const TUint32 blkLen = aCard->CSD().ReadBlockLength();
   1.215 +	const TUint32 blkMsk = blkLen - 1;
   1.216 +
   1.217 +	__ASSERT_DEBUG(aCard->CSD().ReadBlPartial(), Panic(EWinsMMCAPRNotSupp));
   1.218 +	__ASSERT_DEBUG(aEnd - aStart <= blkLen, Panic(EWinsMMCAPRRange));
   1.219 +	__ASSERT_DEBUG((aEnd & ~blkMsk) > (aStart & ~blkMsk), Panic(EWinsMMCAPRBoundary));
   1.220 +#endif
   1.221 +
   1.222 +	*aPhysStart = aStart & ~0x3;
   1.223 +	*aPhysEnd = (aEnd + 0x3) & ~0x3;
   1.224 +	}
   1.225 +
   1.226 +void DWinsCPRMStack::GetBufferInfo(TUint8** aMDBuf, TInt* aMDBufLen)
   1.227 +	{
   1.228 +	*aMDBuf = iMDBuf;
   1.229 +	*aMDBufLen = iMDBufLen;
   1.230 +	}
   1.231 +
   1.232 +void DWinsCPRMStack::Panic(TWinsMMCPanic aPanic)
   1.233 +	{
   1.234 +	_LIT(KPncNm,"PBUS-MMCSD-WINS");
   1.235 +	Kern::PanicCurrentThread(KPncNm,aPanic);
   1.236 +	}
   1.237 +
   1.238 +TInt DWinsCPRMStack::SetupSimulatedCard(TInt aCardNum)
   1.239 +//
   1.240 +// allocate individual card with Win32 file.  Only called at bootup, so no cleanup if fails.
   1.241 +//
   1.242 +	{
   1.243 +	TWinsCardInfo* cip = new TWinsCardInfo;
   1.244 +	if (cip == 0)
   1.245 +		return KErrNoMemory;
   1.246 +
   1.247 +	TUint8 cid[KMMCCIDLength];
   1.248 +	cid[0] = 'C';
   1.249 +	cid[1] = 'I';
   1.250 +	cid[2] = 'D';
   1.251 +	cid[3] = TUint8('0' + aCardNum);
   1.252 +	TInt j;
   1.253 +	for (j = 4; j < KMMCCIDLength - 1; ++j)
   1.254 +		cid[j] = 'c';
   1.255 +	cid[KMMCCIDLength - 1] = '#';				// '#' = 0x23, bit zero must be 1
   1.256 +	cip->iCID=cid;
   1.257 +
   1.258 +	cip->iPWD = new TMediaPassword;
   1.259 +	if (! cip->iPWD)
   1.260 +		{
   1.261 +		delete cip;
   1.262 +		return KErrNoMemory;
   1.263 +		}
   1.264 +
   1.265 +	// cards in slot zero are SD
   1.266 +	TInt mediaAreas;
   1.267 +	if (aCardNum <= 1)
   1.268 +		{
   1.269 +		cip->iIsSDCard = ETrue;
   1.270 +		mediaAreas = 2;
   1.271 +		}
   1.272 +	else
   1.273 +		{
   1.274 +		cip->iIsSDCard = EFalse;
   1.275 +		mediaAreas = 1;
   1.276 +		}
   1.277 +
   1.278 +	cip->iState=ECardStateIdle;
   1.279 +
   1.280 +	for (TInt area = 0; area < mediaAreas; ++area)
   1.281 +		{
   1.282 +		TInt r = CreateBinFileForCard(aCardNum, area, &cip->iAreaHandles[area]);
   1.283 +		if (r != KErrNone)
   1.284 +			return r;
   1.285 +		}
   1.286 +	iCardPool[aCardNum]=cip;
   1.287 +	return(KErrNone);
   1.288 +	}
   1.289 +
   1.290 +TInt DWinsCPRMStack::CreateBinFileForCard(TInt aCardNum, TInt aAreaNum, HANDLE* aHandle)
   1.291 +//
   1.292 +// create .bin file in temp directory to contain media area of card.
   1.293 +//
   1.294 +	{
   1.295 +	const char* emulatorPath = Property::GetString("EmulatorMediaPath");
   1.296 +	if (!Emulator::CreateAllDirectories(emulatorPath))
   1.297 +		return Emulator::LastError();
   1.298 +
   1.299 +	TBuf8<KMaxFileName> fn8(_L8(emulatorPath));
   1.300 +	fn8.Append(_L8("MMCCRD"));
   1.301 +	fn8.AppendNum(aCardNum);
   1.302 +	fn8.Append('A'+aAreaNum);
   1.303 +	fn8.Append(_L8(".BIN"));
   1.304 +	fn8.Append('\0');
   1.305 +
   1.306 +	*aHandle = CreateFileA(
   1.307 +		(LPCSTR) fn8.Ptr(),					// LPCSTR lpFileName,
   1.308 +		GENERIC_READ | GENERIC_WRITE,		// DWORD dwDesiredAccess
   1.309 +		FILE_SHARE_READ | FILE_SHARE_WRITE,	// DWORD dwShareMode
   1.310 +		NULL,								// LPSECURITY_ATTRIBUTES lpSecurityAttributes
   1.311 +		OPEN_ALWAYS,						// DWORD dwCreationDisposition
   1.312 +		FILE_FLAG_RANDOM_ACCESS,			// DWORD dwFlagsAndAttributes
   1.313 +		NULL);								// HANDLE hTemplateFile
   1.314 +
   1.315 +	if (*aHandle == INVALID_HANDLE_VALUE)
   1.316 +	    return MapLastErrorEpoc();
   1.317 +	
   1.318 +	if (	SetFilePointer(*aHandle, KTotalMDiskSize, NULL, FILE_BEGIN) == 0xffffffffu
   1.319 +		||	! SetEndOfFile(*aHandle) )
   1.320 +		{
   1.321 +		CloseHandle(*aHandle);
   1.322 +	    return MapLastErrorEpoc();
   1.323 +		}
   1.324 +
   1.325 +	return KErrNone;
   1.326 +	}
   1.327 +
   1.328 +void DWinsCPRMStack::SetBusConfigDefaults(TMMCBusConfig& aConfig, TUint aClock)
   1.329 +	{
   1.330 +	const TUint KWinsMaxHwInterfaceClk=104000;
   1.331 +	const TUint KWinsResponseTimeOut=6400;
   1.332 +	const TUint KWinsDataTimeOut=40000;
   1.333 +	const TUint KWinsBusyTimeOut=200000;
   1.334 +
   1.335 +	aConfig.iBusClock = (aClock > KWinsMaxHwInterfaceClk) ? KWinsMaxHwInterfaceClk : aClock;
   1.336 +	aConfig.iResponseTimeOut=KWinsResponseTimeOut;
   1.337 +	aConfig.iDataTimeOut=KWinsDataTimeOut;
   1.338 +	aConfig.iBusyTimeOut=KWinsBusyTimeOut;
   1.339 +	}
   1.340 +
   1.341 +void DWinsCPRMStack::InitClockOff()
   1.342 +	{
   1.343 +	// empty.
   1.344 +	}
   1.345 +
   1.346 +void DWinsCPRMStack::ASSPReset()
   1.347 +	{
   1.348 +	// empty.
   1.349 +	}
   1.350 +
   1.351 +void DWinsCPRMStack::ASSPDisengage()
   1.352 +	{
   1.353 +	// empty.
   1.354 +	}
   1.355 +
   1.356 +void DWinsCPRMStack::DoPowerDown()
   1.357 +	{
   1.358 +	// empty.
   1.359 +	}
   1.360 +
   1.361 +LOCAL_C TInt SetMediaPasswordEnvironmentVar(TInt aSocketNum,TInt aCardNum,const TDesC8& aPasswd)
   1.362 +// 
   1.363 +// Set the password for local drive 'aLocalDrive', card number 'aCardNum' to 'aPasswd' - as an
   1.364 +// environment variable. Note that the card number is only relevant where the emulated drive
   1.365 +// supports card hot-swapping (i.e. F4 whilst F5 is held down).
   1.366 +//
   1.367 +	{
   1.368 +	// Setup the appropriate environment variable string '_EPOC_LocDrv_<locDrvNum>_PWORD_<cardNum>'
   1.369 +	TUint16 envVar[]=L"_EPOC_Socket_X_PWORD_Y";
   1.370 +
   1.371 +	envVar[13]=(TUint16)('0'+aSocketNum);
   1.372 +	envVar[21]=(TUint16)('0'+aCardNum);
   1.373 +	
   1.374 +	// Setup the new value of the environment variable
   1.375 +	TUint16	envVal[100];
   1.376 +	TInt len=aPasswd.Length();
   1.377 +
   1.378 +	// the password may be empty if a card's password is cleared
   1.379 +	if (len>(100-1))
   1.380 +		return(KErrArgument);
   1.381 +	memcpy(&envVal[0],reinterpret_cast<const TUint16 *>(aPasswd.Ptr()),len);
   1.382 +	envVal[len>>1]='\0';
   1.383 +
   1.384 +	// Now set the new value for the environment variable
   1.385 +	if (SetEnvironmentVariable(envVar,&envVal[0]))
   1.386 +		return(KErrNone);
   1.387 +
   1.388 +	return KErrGeneral;
   1.389 +	}
   1.390 +
   1.391 +LOCAL_C TInt MediaPasswordEnvironmentVar(TInt aSocketNum,TInt aCardNum,TDes8& aPasswd)
   1.392 +// 
   1.393 +// Get the password for local drive 'aLocalDrive', card number 'aCardNum' into 'aPasswd' - from
   1.394 +// an environment variable. Note that the card number is only relevant where the emulated drive
   1.395 +// supports card hot-swapping (i.e. F4 whilst F5 is held down).
   1.396 +//
   1.397 +	{
   1.398 +	TUint16 envVar[]=L"_EPOC_Socket_X_PWORD_Y";
   1.399 +
   1.400 +	envVar[13]=(TUint16)('0'+aSocketNum);
   1.401 +	envVar[21]=(TUint16)('0'+aCardNum);
   1.402 +	
   1.403 +	TUint16 envVal[100];	// To hold the value of the retreived environment variable
   1.404 +	
   1.405 +	DWORD len=GetEnvironmentVariable(envVar,&envVal[0],100);
   1.406 +	if (len>(TUint)100)
   1.407 +		return(KErrGeneral);
   1.408 +	if (len)
   1.409 +		{
   1.410 +		// Found the requested environment variable so there is a password for this local drive / card. 
   1.411 +		if ((len<<1)<=KMaxMediaPassword)
   1.412 +			{
   1.413 +			aPasswd.FillZ(KMaxMediaPassword);
   1.414 +			aPasswd.Zero();
   1.415 +			aPasswd.Copy(reinterpret_cast<TUint8*>(&envVal[0]),len<<1);
   1.416 +			return(KErrNone);	
   1.417 +			}
   1.418 +		else	
   1.419 +			return(KErrGeneral);	
   1.420 +		}
   1.421 +
   1.422 +	return(KErrNotFound);
   1.423 +	}
   1.424 +
   1.425 +TMMCErr DWinsCPRMStack::DoPowerUpSM()
   1.426 +	{
   1.427 +	enum states
   1.428 +		{
   1.429 +		EStBegin=0,
   1.430 +		EStEnd
   1.431 +		};
   1.432 +
   1.433 +	SMF_BEGIN
   1.434 +
   1.435 +		if(MMCSocket()->iVcc->SetState(EPsuOnCurLimit) != KErrNone)
   1.436 +			return KMMCErrHardware;
   1.437 +
   1.438 +		for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.439 +			{
   1.440 +			// if card has a password, it will be locked on power up
   1.441 +			TInt cardNum = (i==0) ? *Wins::CurrentPBusDevicePtr() : i + 1;
   1.442 +			if (	cardNum >= 0
   1.443 +				&&	MediaPasswordEnvironmentVar(
   1.444 +						MMCSocket()->iSocketNumber, cardNum, *(iCardInfo[i]->iPWD))
   1.445 +					==	KErrNone)
   1.446 +				{
   1.447 +				iCardInfo[i]->iIsLocked = (iCardInfo[i]->iPWD->Length() > 0);
   1.448 +				}
   1.449 +			else	
   1.450 +				iCardInfo[i]->iIsLocked=EFalse;
   1.451 +
   1.452 +			iCardInfo[i]->iState = ECardStateIdle;
   1.453 +			iCardInfo[i]->iRCA=0x0001;		// Default RCA - spec 2.2, s4.2.1, 5.4
   1.454 +			}
   1.455 +
   1.456 +		ReportPowerUp();
   1.457 +
   1.458 +	SMF_END
   1.459 +	}
   1.460 +
   1.461 +TMMCErr DWinsCPRMStack::InitClockOnSM()
   1.462 +	{
   1.463 +	enum states
   1.464 +		{
   1.465 +		EStBegin=0,
   1.466 +		EStEnd
   1.467 +		};
   1.468 +	SMF_BEGIN
   1.469 +
   1.470 +	SMF_END
   1.471 +	}
   1.472 +
   1.473 +void DWinsCPRMStack::AddressCard(TInt aCardNumber)
   1.474 +	{
   1.475 +	iAddressedCard = aCardNumber;
   1.476 +	}
   1.477 +
   1.478 +
   1.479 +TInt DWinsCPRMStack::GetTargetSlotNumber(const TRCA& anRCA)
   1.480 +//
   1.481 +// when the controller is given a command with an embedded RCA, this function
   1.482 +// works out which physical card slot it corresponds to.  If no card has been
   1.483 +// assigned the RCA then it returns -1.
   1.484 +//
   1.485 +	{
   1.486 +	TInt targetIdx = -1;
   1.487 +
   1.488 +	for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.489 +		{
   1.490 +		if (iCardInfo[i]->iRCA==anRCA)
   1.491 +			{
   1.492 +			targetIdx=i;
   1.493 +			break;
   1.494 +			}
   1.495 +		}
   1.496 +
   1.497 +	return(targetIdx);
   1.498 +	}
   1.499 +
   1.500 +TMMCErr DWinsCPRMStack::IssueMMCCommandSM()
   1.501 +	{
   1.502 +	enum states
   1.503 +		{
   1.504 +		EStBegin=0,
   1.505 +		EStEnd
   1.506 +		};
   1.507 +
   1.508 +	TMMCCommandDesc& cmd = Command();
   1.509 +
   1.510 +	// If the command contains an embedded RCA then extract it	
   1.511 +	TRCA tgtRCA=0;
   1.512 +	TBool supRCA=EFalse;
   1.513 +	if (/*cmd.iCommand == ECmdSetRelativeAddr	||	*/cmd.iCommand == ECmdSelectCard
   1.514 +	||	cmd.iCommand == ECmdSendCSD			||	cmd.iCommand == ECmdSendCID
   1.515 +	||	cmd.iCommand == ECmdSendStatus		||	cmd.iCommand == ECmdGoInactiveState
   1.516 +	||	cmd.iCommand == ECmdFastIO 			||  cmd.iCommand == ECmdAppCmd )
   1.517 +		{
   1.518 +		if ((cmd.iArgument >> 16) != 0)
   1.519 +			{
   1.520 +			supRCA=ETrue;
   1.521 +			tgtRCA=TUint16(cmd.iArgument >> 16);
   1.522 +			}
   1.523 +		}
   1.524 +
   1.525 +	// if the card contains an embedded RCA, work out which slot it corresponds to.
   1.526 +	// At the end of the function, this card is used to generate the R1 response.
   1.527 +	// Assume that if rca is supplied it either corresponds to the selected card or
   1.528 +	// broadcast mode is on.  (An exception is CMD7 with arg0 to deselect all cards.)
   1.529 +
   1.530 +	TInt targetCard = supRCA ? GetTargetSlotNumber(tgtRCA) : iAddressedCard;
   1.531 +	TBool rto = EFalse;							// response timeout
   1.532 +
   1.533 +	// if try to access card zero has been set to holding no card via F5 / F4 then timeout.
   1.534 +	if ((targetCard == 0) && *Wins::CurrentPBusDevicePtr() < 0)
   1.535 +		return KMMCErrResponseTimeOut;
   1.536 +	
   1.537 +	HANDLE winHandle;
   1.538 +
   1.539 +	// CMD42 is a data transfer command.  That means the R1 response that it returns
   1.540 +	// immediately is the state it is in on receiving the data block, and not after
   1.541 +	// processing it.  If the data block is invalid then LOCK_UNLOCK_FAILED will be
   1.542 +	// set in the R1 response which is sent in reply to the next command.
   1.543 +
   1.544 +	TBool nextCMD42Failed = EFalse;
   1.545 +	TBool lock_unlock_failed=EFalse;
   1.546 +
   1.547 +	// When the card is locked, it will only respond to basic command class (0) and
   1.548 +	// lock card command class (7).  An exception is CMD16.  This is sent before CMD42,
   1.549 +	// but is classified (MMC Spec 23.2, table 5) as belonging to classes 2 and 4.
   1.550 +	// For data transfer commands, LOCK_UNLOCK_FAIL is set in response to the following
   1.551 +
   1.552 +	TMMCCommandEnum origCmd = cmd.iCommand;
   1.553 +
   1.554 +	// if targetting locked card...
   1.555 +	if (targetCard != KBroadcastToAllCards && iCardInfo[targetCard]->iIsLocked)
   1.556 +		{
   1.557 +		// ...and not command used in init or CMD42 sequence...
   1.558 +		if (!(	((cmd.iSpec.iCommandClass & (KMMCCmdClassApplication | KMMCCmdClassBasic | KMMCCmdClassLockCard)) != 0)
   1.559 +			||	(cmd.iCommand == ECmdSetBlockLen) || (cmd.iCommand == ECmdAppCmd) ))
   1.560 +			{
   1.561 +			lock_unlock_failed = ETrue;
   1.562 +			cmd.iCommand = (TMMCCommandEnum) -1;	// skip case processing
   1.563 +			}
   1.564 +		}
   1.565 +
   1.566 +	SMF_BEGIN
   1.567 +
   1.568 +	switch (cmd.iCommand)
   1.569 +		{
   1.570 +		case ECmdGoIdleState:	// CMD0
   1.571 +			if (iAddressedCard != KBroadcastToAllCards)
   1.572 +				iCardInfo[iAddressedCard]->iState = ECardStateIdle;
   1.573 +			else
   1.574 +				{
   1.575 +				for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.576 +					iCardInfo[i]->iState = ECardStateIdle;
   1.577 +				}
   1.578 +			break;
   1.579 +
   1.580 +		case ECmd41:
   1.581 +		case ECmdSendOpCond:	// CMD1
   1.582 +			{
   1.583 +			if (iAddressedCard != KBroadcastToAllCards)
   1.584 +				iCardInfo[iAddressedCard]->iState = ECardStateReady;
   1.585 +			else
   1.586 +				{
   1.587 +				for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.588 +					iCardInfo[i]->iState = ECardStateReady;
   1.589 +				}
   1.590 +
   1.591 +			// bit31 is set to indicate cards are not still powering up
   1.592 +			TUint32 r3 = KMMCWinsCardOCRValue | KMMCOCRBusy;
   1.593 +			TMMC::BigEndian4Bytes(cmd.iResponse, r3);
   1.594 +			}
   1.595 +			break;
   1.596 +
   1.597 +		case ECmdAllSendCID:	// CMD2
   1.598 +			{
   1.599 +			TInt idx;
   1.600 +			if (iAddressedCard != KBroadcastToAllCards)
   1.601 +				{
   1.602 +				idx = iAddressedCard;
   1.603 +				__ASSERT_DEBUG(
   1.604 +					iCardInfo[iAddressedCard]->iState == ECardStateReady,
   1.605 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EStkIMCBadStateCmd2));
   1.606 +				}
   1.607 +			else
   1.608 +				idx = FindAnyCardInStack(ECardStateReady);
   1.609 +
   1.610 +			if (idx == -1)
   1.611 +				rto = ETrue;
   1.612 +			else
   1.613 +				{
   1.614 +				iCardInfo[idx]->iCID.Copy(cmd.iResponse);
   1.615 +				iCardInfo[idx]->iState = ECardStateIdent;
   1.616 +				}
   1.617 +			}
   1.618 +			break;
   1.619 +
   1.620 +		case ECmdSetRelativeAddr:	// CMD3
   1.621 +			{
   1.622 +			TInt idx;
   1.623 +			if (iAddressedCard != KBroadcastToAllCards)
   1.624 +				{
   1.625 +				__ASSERT_DEBUG(
   1.626 +					iCardInfo[iAddressedCard]->iState == ECardStateIdent,
   1.627 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EStkIMCBadStateCmd3));
   1.628 +				
   1.629 +				if (iCardInfo[iAddressedCard]->iIsSDCard)
   1.630 +					{
   1.631 +					static TUint16 RCACounter = 0x1234;
   1.632 +					// SD Cards publish RCAs
   1.633 +					++RCACounter;
   1.634 +					iCardInfo[iAddressedCard]->iRCA = RCACounter;
   1.635 +					iCardInfo[iAddressedCard]->iState = ECardStateStby;
   1.636 +					TUint32 r6 = TUint32(RCACounter) << 16;
   1.637 +					TMMC::BigEndian4Bytes(&cmd.iResponse[0],r6); // Ignore bits 47-40
   1.638 +					}
   1.639 +				else
   1.640 +					{
   1.641 +					iCardInfo[iAddressedCard]->iRCA = TUint16(cmd.iArgument >> 16);
   1.642 +					iCardInfo[iAddressedCard]->iState=ECardStateStby;
   1.643 +					}
   1.644 +				}
   1.645 +			else
   1.646 +				{
   1.647 +				// MultiMediaCards are assigned RCAs
   1.648 +				idx = FindOneCardInStack(ECardStateIdent);
   1.649 +				iCardInfo[iAddressedCard]->iRCA = TUint16(cmd.iArgument >> 16);
   1.650 +				iCardInfo[iAddressedCard]->iState=ECardStateStby;
   1.651 +				targetCard = iAddressedCard;
   1.652 +				}
   1.653 +			}
   1.654 +			break;
   1.655 +
   1.656 +		case ECmd6:
   1.657 +			// if ACMD6 then change bus width
   1.658 +			if (cmd.iSpec.iCommandClass == KMMCCmdClassApplication)
   1.659 +				{
   1.660 +				switch (cmd.iArgument)
   1.661 +					{
   1.662 +				case 0x00:
   1.663 +					iCardInfo[iAddressedCard]->iBusWidth = 1;
   1.664 +					break;
   1.665 +				case 0x02:
   1.666 +					iCardInfo[iAddressedCard]->iBusWidth = 4;
   1.667 +					break;
   1.668 +				default:
   1.669 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EStkIMCCmd6InvalidWidth);
   1.670 +					break;
   1.671 +					}
   1.672 +				}
   1.673 +			break;
   1.674 +
   1.675 +		case ECmdSelectCard:		// CMD7
   1.676 +			{
   1.677 +			// switch to broadcast mode so the currently selected and new cards
   1.678 +			// receive the command simultaneously.
   1.679 +
   1.680 +			TInt idx = FindAnyCardInStack(ECardStateTran);
   1.681 +			if (idx != -1)
   1.682 +				iCardInfo[idx]->iState = ECardStateStby;
   1.683 +			if ((iAddressedCard=targetCard) == KBroadcastToAllCards)
   1.684 +				rto = ETrue;
   1.685 +			else
   1.686 +				{
   1.687 +				iCardInfo[targetCard]->iState = ECardStateTran;
   1.688 +				targetCard = targetCard;
   1.689 +				}
   1.690 +			}
   1.691 +			break;
   1.692 +
   1.693 +		case ECmdSendStatus:
   1.694 +			// R1 response so status return as for any other R1 command.
   1.695 +			if (cmd.iSpec.iCommandClass == KMMCCmdClassApplication)
   1.696 +				{
   1.697 +				__ASSERT_DEBUG(
   1.698 +					iCardInfo[targetCard]->iIsSDCard,
   1.699 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EStkICMACMD13NotSD));
   1.700 +
   1.701 +				memset(cmd.iDataMemoryP, 0, KSDStatusBlockLength);
   1.702 +				if (iCardInfo[targetCard]->iBusWidth == 1)
   1.703 +					cmd.iDataMemoryP[0] = 0x00 << 6;
   1.704 +				else	// if (iCardInfo[targetCard]->iBusWidth == 4)
   1.705 +					cmd.iDataMemoryP[0] = 0x02 << 6;
   1.706 +				cmd.iDataMemoryP[7] = 0x28;		// PROTECTED_AREA_SIZE
   1.707 +				}
   1.708 +			break;
   1.709 +
   1.710 +		case ECmdReadSingleBlock:
   1.711 +		case ECmdReadMultipleBlock:
   1.712 +			{
   1.713 +			winHandle=iCardInfo[targetCard]->iAreaHandles[KSDUserArea];
   1.714 +
   1.715 +			if ( cmd.iSpec.iUseStopTransmission && cmd.iBlockLength >= cmd.iTotalLength)
   1.716 +				return( KMMCErrNotSupported );
   1.717 +
   1.718 +    		TMMCErr err;
   1.719 +			TInt pos = cmd.iArgument;
   1.720 +    		if (SetFilePointer(winHandle,pos,NULL,FILE_BEGIN)==0xffffffffu)
   1.721 +        		err=MapLastErrorMmc();
   1.722 +    		else
   1.723 +        		{
   1.724 +	    		DWORD res;
   1.725 +				TInt len = cmd.iTotalLength;
   1.726 +		        if (ReadFile(winHandle,(TAny*)cmd.iDataMemoryP,len,&res,NULL)==FALSE)
   1.727 +                    err=MapLastErrorMmc();
   1.728 +                else if (res!=(DWORD)len)
   1.729 +                    err=KMMCErrGeneral;
   1.730 +                else
   1.731 +                    err=KMMCErrNone;
   1.732 +				}
   1.733 +			if (err!=KMMCErrNone)
   1.734 +				return(err);
   1.735 +			break;
   1.736 +			}
   1.737 +
   1.738 +		case ECmd22:
   1.739 +			if (cmd.iSpec.iCommandClass == KMMCCmdClassApplication)
   1.740 +				{
   1.741 +				TMMC::BigEndian4Bytes(cmd.iResponse, iMBWOKBlocks);
   1.742 +				}
   1.743 +			break;
   1.744 +		// ------------------------------------------------------------------
   1.745 +		case ECmdWriteBlock:
   1.746 +		case ECmdWriteMultipleBlock:
   1.747 +			{
   1.748 +			TUint32 writeLen;
   1.749 +
   1.750 +			// periodically fail multi-block writes to test ACMD22 error recovery
   1.751 +			if (cmd.iCommand != ECmdWriteMultipleBlock)
   1.752 +				writeLen = cmd.iTotalLength;
   1.753 +			else
   1.754 +				{
   1.755 +				const TInt KMaxFailCnt = 4;
   1.756 +				static TInt failCnt = 0;
   1.757 +				const TInt KMaxFailBlock = 4;
   1.758 +				static TInt failBlocks = 0;
   1.759 +				
   1.760 +				failCnt = (failCnt + 1) % KMaxFailCnt;
   1.761 +				if (failCnt != 0)
   1.762 +					writeLen = cmd.iTotalLength;
   1.763 +				else
   1.764 +					{
   1.765 +					failBlocks = (failBlocks + 1) % KMaxFailBlock;
   1.766 +					
   1.767 +					// fail at least one block
   1.768 +					TInt totalBlocks = cmd.iTotalLength / cmd.iBlockLength;
   1.769 +					TInt blocksToFail = Min(failBlocks + 1, totalBlocks);	// fail at least one block
   1.770 +					iMBWOKBlocks = (totalBlocks - blocksToFail);
   1.771 +					writeLen = iMBWOKBlocks * cmd.iBlockLength;
   1.772 +					if (writeLen == 0)
   1.773 +						return KMMCErrDataTimeOut;
   1.774 +					}
   1.775 +				}
   1.776 +			
   1.777 +			HANDLE h=iCardInfo[targetCard]->iAreaHandles[KSDUserArea];
   1.778 +
   1.779 +    		TMMCErr err;
   1.780 +			TInt pos = cmd.iArgument;
   1.781 +    		if (SetFilePointer(h, pos, NULL, FILE_BEGIN)==0xffffffffu)
   1.782 +        		err = MapLastErrorMmc();
   1.783 +    		else
   1.784 +        		{
   1.785 +	    		DWORD res;
   1.786 +				if (! WriteFile(h, (LPCVOID)cmd.iDataMemoryP,writeLen,&res,NULL))
   1.787 +                    err=MapLastErrorMmc();
   1.788 +                else if (res!=(DWORD)writeLen)
   1.789 +                    err=KMMCErrGeneral;
   1.790 +                else
   1.791 +                    err=KMMCErrNone;
   1.792 +				}
   1.793 +
   1.794 +			if (err!=KMMCErrNone)
   1.795 +				return(err);
   1.796 +			if (writeLen != cmd.iTotalLength)
   1.797 +				return KMMCErrDataTimeOut;
   1.798 +			}
   1.799 +			break;
   1.800 +
   1.801 +		case ECmdAppCmd:
   1.802 +			// targetCard == -1 when ACMD41 being sent because not yet supplied
   1.803 +			if (iAddressedCard != KBroadcastToAllCards)
   1.804 +				{
   1.805 +				// timeout if addressed card is not SD
   1.806 +				if (! iCardInfo[iAddressedCard]->iIsSDCard)
   1.807 +					rto = ETrue;
   1.808 +				}
   1.809 +			else
   1.810 +				{
   1.811 +				// request sent to specific non-SD card
   1.812 +				if (targetCard != -1 && ! iCardInfo[targetCard]->iIsSDCard)
   1.813 +					rto = ETrue;
   1.814 +				}
   1.815 +			break;
   1.816 +
   1.817 +		case ECmdSendCSD:
   1.818 +			{
   1.819 +			iCardInfo[targetCard]->GetCSD(cmd.iResponse);
   1.820 +			break;
   1.821 +			}
   1.822 +
   1.823 +		// ------------------------------------------------------------------
   1.824 +		case ECmdLockUnlock:
   1.825 +			// in EPOC, Lock() does not actually lock the card.  It just sets the
   1.826 +			// password.  This means that the card is still accessible to the user,
   1.827 +			// but must be unlocked the next time it is powered up.
   1.828 +
   1.829 +			// a real card will transiently go into rcv and prg state while processing
   1.830 +			// this command.  When finished, it will fall back into tran state.
   1.831 +			// The R1 response is sent immediately after CMD42.  CIMReadWriteBlocksSM()
   1.832 +			// sends CMD13 to find out whether or not LOCK_UNLOCK_FAIL was set.
   1.833 +
   1.834 +			// the asserts in this case protect against invalid data being sent from the
   1.835 +			// media driver.  A real card would fail these corrupt data blocks.
   1.836 +
   1.837 +			{
   1.838 +			const TInt8 cmd_byte(*cmd.iDataMemoryP);
   1.839 +			__ASSERT_DEBUG(										// ensure not CLR_PWD && SET_PWD
   1.840 +				!((cmd_byte & KMMCLockUnlockClrPwd) && (cmd_byte & KMMCLockUnlockSetPwd)),
   1.841 +				DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCCorruptCommand) );
   1.842 +			
   1.843 +			__ASSERT_DEBUG(										// not actually lock a card
   1.844 +				!(cmd_byte & KMMCLockUnlockLockUnlock),
   1.845 +				DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCLockAttempt) );
   1.846 +
   1.847 +			if (cmd_byte & KMMCLockUnlockErase)					// ERASE (not supported)
   1.848 +				return KMMCErrNotSupported;
   1.849 +
   1.850 +			const TInt8 pwd_len = *(cmd.iDataMemoryP + 1);
   1.851 +			const TPtrC8 pwd(cmd.iDataMemoryP + 2, pwd_len);
   1.852 +
   1.853 +			if ((cmd_byte & KMMCLockUnlockClrPwd) != 0)			// CLR_PWD == 1
   1.854 +				{
   1.855 +				__ASSERT_DEBUG(
   1.856 +					pwd_len >= 0 && pwd_len <= KMaxMediaPassword,
   1.857 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCCorruptCommand));
   1.858 +
   1.859 +				if (iCardInfo[targetCard]->iIsLocked)						// clear when locked
   1.860 +					nextCMD42Failed = ETrue;
   1.861 +				else														// clear when unlocked
   1.862 +					{
   1.863 +					if (iCardInfo[targetCard]->iPWD->Compare(pwd) != 0)		// clear when unlocked with wrong password
   1.864 +						nextCMD42Failed = ETrue;
   1.865 +					else													// clear when unlocked with right password
   1.866 +						{
   1.867 +						// Clear from password store 
   1.868 +						iCardInfo[targetCard]->iPWD->Zero();
   1.869 +						iCardInfo[targetCard]->iIsLocked = EFalse;
   1.870 +						nextCMD42Failed = EFalse;
   1.871 +						
   1.872 +						// Clear from environment settings
   1.873 +						TInt cardNum=(targetCard==0) ? *Wins::CurrentPBusDevicePtr() : 0; // Can't be -1 at this stage
   1.874 +						SetMediaPasswordEnvironmentVar(MMCSocket()->iSocketNumber,cardNum,*(iCardInfo[targetCard]->iPWD));
   1.875 +						}
   1.876 +					}
   1.877 +				}
   1.878 +			else if ((cmd_byte & KMMCLockUnlockSetPwd) == 0)	// SET_PWD == 0: unlock
   1.879 +				{
   1.880 +				__ASSERT_DEBUG(
   1.881 +					pwd_len >= 0 && pwd_len <= KMaxMediaPassword,
   1.882 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCCorruptCommand) );
   1.883 +				
   1.884 +				if (! iCardInfo[targetCard]->iIsLocked)						// unlock when unlocked
   1.885 +					nextCMD42Failed = ETrue;
   1.886 +				else
   1.887 +					{
   1.888 +					if (iCardInfo[targetCard]->iPWD->Compare(pwd) != 0)		// unlock when locked with wrong password
   1.889 +						nextCMD42Failed = ETrue;
   1.890 +					else													// unlock when locked with right password
   1.891 +						{
   1.892 +						iCardInfo[targetCard]->iIsLocked = EFalse;
   1.893 +						nextCMD42Failed = EFalse;
   1.894 +						}
   1.895 +					}
   1.896 +				}
   1.897 +			else /* ((cmd_byte & KMMCLockUnlockSetPwd) != 0) */	// SET_PWD == 1
   1.898 +				{
   1.899 +				__ASSERT_DEBUG(
   1.900 +					cmd_byte & KMMCLockUnlockSetPwd,
   1.901 +					DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCCorruptCommand) );
   1.902 +
   1.903 +				// if pwd_len < iCardInfo[targetCard]->iPWD->Length() then data block must be invalid.
   1.904 +				// This can be caused by bad user input rather than inaccurate formation.
   1.905 +				if (!(	pwd_len >= iCardInfo[targetCard]->iPWD->Length()
   1.906 +					&&	pwd_len <= iCardInfo[targetCard]->iPWD->Length() + KMaxMediaPassword ))
   1.907 +					{
   1.908 +					nextCMD42Failed = ETrue;
   1.909 +					}
   1.910 +				else
   1.911 +					{
   1.912 +					const TInt old_pwd_len = iCardInfo[targetCard]->iPWD->Length();
   1.913 +					TPtrC8 old_pwd(cmd.iDataMemoryP + 2, old_pwd_len);
   1.914 +					TPtrC8 new_pwd(cmd.iDataMemoryP + 2 + old_pwd_len, pwd_len - old_pwd_len);
   1.915 +
   1.916 +					// card must not be locked and supplied current password must be correct
   1.917 +					if (iCardInfo[targetCard]->iIsLocked || iCardInfo[targetCard]->iPWD->Compare(old_pwd) != 0)
   1.918 +						nextCMD42Failed = ETrue;
   1.919 +					else
   1.920 +						{
   1.921 +						// Set in password store
   1.922 +						iCardInfo[targetCard]->iPWD->Copy(new_pwd);
   1.923 +						nextCMD42Failed = EFalse;
   1.924 +						
   1.925 +						// Set in environment settings
   1.926 +						TInt cardNum=(targetCard==0) ? *Wins::CurrentPBusDevicePtr() : 0; // Can't be -1 at this stage
   1.927 +						SetMediaPasswordEnvironmentVar(MMCSocket()->iSocketNumber,cardNum,*(iCardInfo[targetCard]->iPWD));
   1.928 +						}
   1.929 +					}
   1.930 +				}	// else /* ((cmd_byte & KMMCLockUnlockSetPwd) != 0) */
   1.931 +			}	// case ECmdLockUnlock
   1.932 +		// ------------------------------------------------------------------
   1.933 +		default:
   1.934 +			break;
   1.935 +		}
   1.936 +
   1.937 +	if (rto)
   1.938 +		return(KMMCErrResponseTimeOut);
   1.939 +
   1.940 +	cmd.iCommand = origCmd;
   1.941 +	// If this is an R1 or R1b response type command then return card status as a response
   1.942 +	if (	targetCard != -1
   1.943 +		&&	(cmd.iSpec.iResponseType==ERespTypeR1 || cmd.iSpec.iResponseType==ERespTypeR1B) )
   1.944 +		{
   1.945 +		TUint32 resp(
   1.946 +				iCardInfo[targetCard]->iState
   1.947 +			|	((iCardInfo[targetCard]->iIsLocked ? 1 : 0) << 25)
   1.948 +			|	((lock_unlock_failed ? 1 : 0) << 24) );
   1.949 +
   1.950 +		if (iCMD42Failed)								// previous CMD42
   1.951 +			{
   1.952 +			resp |= KMMCStatErrLockUnlock;
   1.953 +			nextCMD42Failed = EFalse;
   1.954 +			}
   1.955 +		iCMD42Failed = nextCMD42Failed;
   1.956 +		TMMC::BigEndian4Bytes(&cmd.iResponse[0],resp); // Ignore bits 47-40
   1.957 +		}
   1.958 +	SMF_END
   1.959 +	}
   1.960 +
   1.961 +TInt DWinsCPRMStack::FindAnyCardInStack(TMMCardStateEnum aState)
   1.962 +//
   1.963 +// first first active card in supplied state.  Return -1 if
   1.964 +// no active card is in supplied state.
   1.965 +//
   1.966 +	{
   1.967 +	if (iAddressedCard != KBroadcastToAllCards)
   1.968 +		return (iCardInfo[iAddressedCard]->iState == aState) ? iAddressedCard : -1;
   1.969 +	else
   1.970 +		{
   1.971 +		for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.972 +			{
   1.973 +			if (iCardInfo[i]->iState == aState)
   1.974 +				return i;
   1.975 +			}
   1.976 +
   1.977 +		return -1;
   1.978 +		}
   1.979 +	}
   1.980 +
   1.981 +TInt DWinsCPRMStack::FindFirstCardInStack(TMMCardStateEnum aState)
   1.982 +//
   1.983 +// find card which is active on bus and in supplied state.
   1.984 +// There can be more than one active card in the the supplied state,
   1.985 +// but there should be at least one.
   1.986 +//
   1.987 +	{
   1.988 +	if (iAddressedCard != KBroadcastToAllCards)
   1.989 +		{
   1.990 +		__ASSERT_DEBUG(iCardInfo[iAddressedCard]->iState == aState, DWinsCPRMStack::Panic(DWinsCPRMStack::EStkFFCNotSelCard));
   1.991 +		return iAddressedCard;
   1.992 +		}
   1.993 +	else
   1.994 +		{
   1.995 +		TInt idx = -1;
   1.996 +		for (TInt i = 0; idx != -1 && i < KTotalWinsCardSlots; ++i)
   1.997 +			{
   1.998 +			if (iCardInfo[i]->iState == aState)
   1.999 +				idx = i;
  1.1000 +			}
  1.1001 +
  1.1002 +		__ASSERT_DEBUG(idx != -1, DWinsCPRMStack::Panic(DWinsCPRMStack::EStkFFCNoneSel));
  1.1003 +		return idx;
  1.1004 +		}
  1.1005 +	}
  1.1006 +
  1.1007 +TInt DWinsCPRMStack::FindOneCardInStack(TMMCardStateEnum aState)
  1.1008 +//
  1.1009 +// find card which is active on bus and in supplied state.
  1.1010 +// There should be exactly one active card in the supplied state.
  1.1011 +//
  1.1012 +	{
  1.1013 +	if (iAddressedCard != KBroadcastToAllCards)
  1.1014 +		{
  1.1015 +		__ASSERT_DEBUG(iCardInfo[iAddressedCard]->iState == aState, DWinsCPRMStack::Panic(DWinsCPRMStack::EStkFOCNotSelCard));
  1.1016 +		return iAddressedCard;
  1.1017 +		}
  1.1018 +	else
  1.1019 +		{
  1.1020 +		TInt idx = -1;
  1.1021 +		for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
  1.1022 +			{
  1.1023 +			if (iCardInfo[i]->iState == aState)
  1.1024 +				{
  1.1025 +				__ASSERT_DEBUG(idx == -1, DWinsCPRMStack::Panic(DWinsCPRMStack::EStkFOCMultiSel));
  1.1026 +				idx = i;
  1.1027 +				}
  1.1028 +			}
  1.1029 +
  1.1030 +		__ASSERT_DEBUG(idx != -1, DWinsCPRMStack::Panic(DWinsCPRMStack::EStkFOCNoneSel));
  1.1031 +		return idx;
  1.1032 +		}
  1.1033 +	}
  1.1034 +
  1.1035 +TMMCErr DWinsCPRMStack::CIMCalculateMediaKeySM()
  1.1036 +//
  1.1037 +// Calculate the Media Key record. 
  1.1038 +//
  1.1039 +	{
  1.1040 +  	enum states
  1.1041 +  		{
  1.1042 +  		EStBegin=0,
  1.1043 +  		EStEnd
  1.1044 +  		};
  1.1045 +
  1.1046 +	SMF_BEGIN
  1.1047 +
  1.1048 +  	return( KMMCErrNotSupported );
  1.1049 +
  1.1050 +	SMF_END
  1.1051 +	}
  1.1052 +
  1.1053 +TMMCErr DWinsCPRMStack::SetSecureCommandArgumentSM()
  1.1054 +//
  1.1055 +// Auxilary state machine function called during a secure read/write blocks operation.
  1.1056 +// Perform random number generation and setting the secure command argument.
  1.1057 +//
  1.1058 +	{
  1.1059 +  	enum states
  1.1060 +  		{
  1.1061 +  		EStBegin=0,
  1.1062 +  		EStEnd
  1.1063 +  		};
  1.1064 +
  1.1065 +	SMF_BEGIN
  1.1066 +
  1.1067 +  	return( KMMCErrNotSupported );
  1.1068 +
  1.1069 +	SMF_END
  1.1070 +	}				  
  1.1071 +  
  1.1072 +
  1.1073 +// ======== DWinsMMCMediaChange ========
  1.1074 +
  1.1075 +#pragma warning( disable : 4355 )	// this used in initializer list
  1.1076 +DWinsMMCMediaChange::DWinsMMCMediaChange(TInt aMediaChangeNum)
  1.1077 +	: DMMCMediaChange(aMediaChangeNum),
  1.1078 +      iDoorClosedCount(0),
  1.1079 +	  iMediaChangeEnable(ETrue),
  1.1080 +	  iStackP(NULL)
  1.1081 +	{
  1.1082 +	iMediaDoorCloseReload=2; 	// Units: In theory-20ms, Actual-100ms
  1.1083 +	}
  1.1084 +#pragma warning( default : 4355 )
  1.1085 +
  1.1086 +TInt DWinsMMCMediaChange::Create()
  1.1087 +//
  1.1088 +// Initialiser.
  1.1089 +//
  1.1090 +	{	
  1.1091 +	return(DMediaChangeBase::Create());
  1.1092 +	}
  1.1093 +
  1.1094 +void DWinsMMCMediaChange::DoorOpenService()
  1.1095 +//
  1.1096 +// Handle the media change (this function, never postponed is called on media
  1.1097 +// change interrupt). 
  1.1098 +//
  1.1099 +	{
  1.1100 +	Disable();		// Disable interrupt until door closes again.
  1.1101 +	iDoorOpenDfc.Enque();
  1.1102 +	}
  1.1103 +
  1.1104 +void DWinsMMCMediaChange::DoDoorOpen()
  1.1105 +//
  1.1106 +// Handle media door open (called on media door open interrupt). 
  1.1107 +//
  1.1108 +	{
  1.1109 +	iDoorClosedCount=iMediaDoorCloseReload;
  1.1110 +	// Just start a ticklink to poll for door closing
  1.1111 +	iTickLink.Periodic(KMediaChangeTickInterval,DWinsMMCMediaChange::Tick,this);
  1.1112 +    }
  1.1113 +
  1.1114 +void DWinsMMCMediaChange::DoDoorClosed()
  1.1115 +//
  1.1116 +// Handle media door closing (called on media door open interrupt).
  1.1117 +//
  1.1118 +	{
  1.1119 +
  1.1120 +	iTickLink.Cancel();	// Doesn't matter if wasn't enabled
  1.1121 +	Enable();	// Re-enable door interrupts
  1.1122 +
  1.1123 +	// While the door was open the user may have changed the card in slot 0
  1.1124 +	if (iStackP && *Wins::CurrentPBusDevicePtr()>=0)
  1.1125 +		iStackP->iCardInfo[0]=iStackP->iCardPool[*Wins::CurrentPBusDevicePtr()];
  1.1126 +	}
  1.1127 +
  1.1128 +void DWinsMMCMediaChange::ForceMediaChange()
  1.1129 +//
  1.1130 +// Force media change
  1.1131 +//
  1.1132 +	{
  1.1133 +	DoorOpenService();
  1.1134 +	}
  1.1135 +
  1.1136 +TMediaState DWinsMMCMediaChange::MediaState()
  1.1137 +//
  1.1138 +// Return status of media changed signal.
  1.1139 +//
  1.1140 +	{
  1.1141 +
  1.1142 +	if (iDoorClosedCount>0)
  1.1143 +		return(EDoorOpen);
  1.1144 +	return( (*Wins::MediaDoorOpenPtr())?EDoorOpen:EDoorClosed);
  1.1145 +	}
  1.1146 +
  1.1147 +void DWinsMMCMediaChange::Tick(TAny *aPtr)
  1.1148 +//
  1.1149 +// Called on the tick to poll for door closing (called on DFC).
  1.1150 +//
  1.1151 +	{
  1.1152 +
  1.1153 +	((DWinsMMCMediaChange*)aPtr)->TickService();
  1.1154 +	}
  1.1155 +
  1.1156 +void DWinsMMCMediaChange::TickService()
  1.1157 +//
  1.1158 +// Called on the tick to poll for door closing (called on DFC).
  1.1159 +//
  1.1160 +	{
  1.1161 +
  1.1162 +	__ASSERT_DEBUG(iDoorClosedCount>=0,DWinsCPRMStack::Panic(DWinsCPRMStack::EWinsMMCMediaChangeTickFault));
  1.1163 +	if (!(*Wins::MediaDoorOpenPtr()))
  1.1164 +		{
  1.1165 +		if (iDoorClosedCount > 0)
  1.1166 +			iDoorClosedCount--;
  1.1167 +		if (iDoorClosedCount == 0)
  1.1168 +			DoorClosedService();
  1.1169 +		}
  1.1170 +	else
  1.1171 +		iDoorClosedCount=iMediaDoorCloseReload; // Door open so start again.
  1.1172 +	}
  1.1173 +
  1.1174 +void DWinsMMCMediaChange::Enable()
  1.1175 +//
  1.1176 +// Enable media change 
  1.1177 +//
  1.1178 +	{
  1.1179 +
  1.1180 +	iMediaChangeEnable=ETrue;
  1.1181 +	}
  1.1182 +
  1.1183 +void DWinsMMCMediaChange::Disable()
  1.1184 +//
  1.1185 +// Disable media change
  1.1186 +//
  1.1187 +	{
  1.1188 +
  1.1189 +	iMediaChangeEnable=EFalse;
  1.1190 +	}
  1.1191 +
  1.1192 +void DWinsMMCMediaChange::MediaChangeCallBack(TAny *aPtr)
  1.1193 +//
  1.1194 +// Static called on media change
  1.1195 +//
  1.1196 +	{
  1.1197 +
  1.1198 +	DWinsMMCMediaChange* mc=(DWinsMMCMediaChange*)aPtr;
  1.1199 +	if (mc!=NULL&&mc->iMediaChangeEnable)
  1.1200 +		mc->DoorOpenService();
  1.1201 +	}
  1.1202 +
  1.1203 +
  1.1204 +// ======== TWinsCardInfo ========
  1.1205 +
  1.1206 +void TWinsCardInfo::GetCSD(TUint8* aResp) const
  1.1207 +	{
  1.1208 +	// Bits 127-96
  1.1209 +	TUint32 csd=(0x1<<30); 	/* CSD_STRUCTURE: CSD Version No 1.1 */
  1.1210 +	csd|=		(0x2<<26); 	/* SPEC_VERS: Version 2.1 */
  1.1211 +	csd|=		(0x0E<<16);	/* TAAC: 1mS */  
  1.1212 +	csd|=		(0x0A<<8);	/* NSAC: 1000 */  
  1.1213 +	csd|=		(0x59);		/* TRAN_SPEED: 5.0Mbit/s */  
  1.1214 +	TMMC::BigEndian4Bytes(&aResp[0],csd);
  1.1215 +	// Bits 95-64
  1.1216 +	const TUint32 ccc = 
  1.1217 +			KMMCCmdClassBasic | KMMCCmdClassBlockRead
  1.1218 +		|	KMMCCmdClassBlockWrite | KMMCCmdClassLockCard;
  1.1219 +	csd=		(ccc<<20); 	/* CCC: classes 0, 2, 4, and 7 */
  1.1220 +	csd|=		(0x9<<16); 	/* READ_BL_LEN: 512 bytes */
  1.1221 +	csd|=		(0x0<<15);	/* READ_BL_PARTIAL: No */  
  1.1222 +	csd|=		(0x0<<14);	/* WRITE_BLK_MISALIGN: No */  
  1.1223 +	csd|=		(0x0<<13);	/* READ_BLK_MISALIGN: No */  
  1.1224 +	csd|=		(0x0<<12);	/* DSR_IMP: No DSR */ 
  1.1225 +	csd|=		(0x0<<8);	/* C_SIZE: 1Mb */
  1.1226 +	csd|=		(0x7F);		/* C_SIZE: 1Mb (cont)*/  
  1.1227 +	TMMC::BigEndian4Bytes(&aResp[4],csd); 
  1.1228 +	// Bits 63-32
  1.1229 +	csd=		(3UL<<30); 	/* C_SIZE: 2Mb (cont) */
  1.1230 +	csd|=		(0x1<<27); 	/* VDD_R_CURR_MIN: 1mA */
  1.1231 +	csd|=		(0x1<<24);	/* VDD_R_CURR_MAX: 5mA */  
  1.1232 +	csd|=		(0x2<<21); 	/* VDD_W_CURR_MIN: 5mA */
  1.1233 +	csd|=		(0x3<<18);	/* VDD_W_CURR_MAX: 25mA */  
  1.1234 +	csd|=		(0x0<<15);	/* C_SIZE_MULT: 0 */  
  1.1235 +	if (! iIsSDCard)
  1.1236 +		{
  1.1237 +		csd|=		(0x0<<10);	/* SECTOR_SIZE: 1 write block */  
  1.1238 +		csd|=		(0x0<<5);	/* ERASE_GRP_SIZE: 1 sector */  
  1.1239 +		csd|=		(0x0);		/* WP_GRP_SIZE: 1 erase group */  
  1.1240 +		}
  1.1241 +	else
  1.1242 +		{
  1.1243 +		csd |= (0x00 << (46 - 32));	// ERASE_BLK_EN
  1.1244 +		csd |= (0x1f << (39 - 32));	// SECTOR_SIZE: 32 write blocks
  1.1245 +		csd |= (0x00 << (32 - 32));	// WP_GRP_SIZE: 1 erase sector.
  1.1246 +		}
  1.1247 +	TMMC::BigEndian4Bytes(&aResp[8],csd); 
  1.1248 +	// Bits 31-0
  1.1249 +	csd=		(0x0<<31); 	/* WP_GRP_ENABLE: No */
  1.1250 +	csd|=		(0x0<<29); 	/* DEFAULT_ECC: ? */
  1.1251 +	csd|=		(0x3<<26);	/* R2W_FACTOR: 8 */  
  1.1252 +	csd|=		(0x9<<22); 	/* WRITE_BL_LEN: 512 bytes */
  1.1253 +	csd|=		(0x0<<21);	/* WRITE_BL_PARTIAL: No */  
  1.1254 +	csd|=		(0x0<<15);	/* FILE_FORMAT_GRP: Hard disk */  
  1.1255 +	csd|=		(0x0<<14);	/* COPY: original */  
  1.1256 +	csd|=		(0x0<<13);	/* PERM_WRITE_PROTECT: No */  
  1.1257 +	csd|=		(0x0<<12);	/* TMP_WRITE_PROTECT: No */  
  1.1258 +	csd|=		(0x0<<10);	/* FILE_FORMAT: Hard disk */  
  1.1259 +	csd|=		(0x0<<8);	/* ECC: None */  
  1.1260 +	csd|=		(0x0<<1);	/* CRC: ? */  
  1.1261 +	csd|=		(0x1);		/* not used */  
  1.1262 +	TMMC::BigEndian4Bytes(&aResp[12],csd);
  1.1263 +	}
  1.1264 +
  1.1265 +// ======== DWinsMMCPsu ========
  1.1266 +
  1.1267 +
  1.1268 +DWinsMMCPsu::DWinsMMCPsu(TInt aVccNum, TInt aMcId)
  1.1269 +	: DMMCPsu(aVccNum, aMcId)
  1.1270 +	{}
  1.1271 +
  1.1272 +void DWinsMMCPsu::Init()
  1.1273 +//
  1.1274 +// Initialise the PSU
  1.1275 +//
  1.1276 +    {
  1.1277 +	// Nothing to do
  1.1278 +    }
  1.1279 +
  1.1280 +void DWinsMMCPsu::DoSetState(TPBusPsuState aState)
  1.1281 +//
  1.1282 +// Turn on/off the PSU. If it is possible to adjust the output voltage on this
  1.1283 +// PSU then retreive the required voltage level from TMMCPsu::iVoltageSetting
  1.1284 +// (which is in OCR register format).
  1.1285 +//
  1.1286 +    {
  1.1287 +
  1.1288 +    switch (aState)
  1.1289 +        {
  1.1290 +        case EPsuOff:
  1.1291 +            break;
  1.1292 +        case EPsuOnFull:
  1.1293 +            break;
  1.1294 +        case EPsuOnCurLimit:
  1.1295 +            break;
  1.1296 +        }
  1.1297 +    }
  1.1298 +
  1.1299 +TInt DWinsMMCPsu::VoltageInMilliVolts()
  1.1300 +//
  1.1301 +// Return the level of the PSU (in mV) or -ve if error.
  1.1302 +//
  1.1303 +    {
  1.1304 +
  1.1305 +    return(0);
  1.1306 +    }
  1.1307 +
  1.1308 +void DWinsMMCPsu::DoCheckVoltage()
  1.1309 +//
  1.1310 +// Check the voltage level of the PSU is as expected. Returns either KErrNone, KErrGeneral 
  1.1311 +// to indicate the pass/fail state or KErrNotReady if the voltage check isn't complete.
  1.1312 +//
  1.1313 +    {
  1.1314 +
  1.1315 +	ReceiveVoltageCheckResult(KErrNone);
  1.1316 +    }
  1.1317 +
  1.1318 +void DWinsMMCPsu::PsuInfo(TPBusPsuInfo &anInfo)
  1.1319 +//
  1.1320 +// Return machine info relating to the MMC PSU supply
  1.1321 +//
  1.1322 +    {
  1.1323 +
  1.1324 +	anInfo.iVoltageSupported=0x00040000; // 3.0V (OCR reg. format).
  1.1325 +	anInfo.iMaxCurrentInMicroAmps=0;
  1.1326 +	anInfo.iVoltCheckInterval=0;
  1.1327 +	anInfo.iVoltCheckMethod=EPsuChkComparator;
  1.1328 +    anInfo.iNotLockedTimeOut=0;  // Not enabled
  1.1329 +	anInfo.iInactivityTimeOut=5; // 5 Seconds
  1.1330 +    }