os/boardsupport/emulator/emulatorbsp/specific/sdcard/sdcard3c/pp_sdc.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/sdcard3c/pp_sdc.cpp	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,1350 @@
     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_sdc.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 +// ======== DWinsSDStack ========
    1.94 +
    1.95 +DWinsSDStack::DWinsSDStack(TInt aBus, DMMCSocket* aSocket)
    1.96 +: DSDStack(aBus, aSocket)
    1.97 +	{	
    1.98 +	iAddressedCard=KBroadcastToAllCards;
    1.99 +//	iCMD42Failed=EFalse;
   1.100 +	}
   1.101 +
   1.102 +
   1.103 +TInt DWinsSDStack::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=DMMCStack::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 DWinsSDStack::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 +					DWinsSDStack::Panic(DWinsSDStack::EWinsMMCBadMachineInfo));
   1.203 +	}
   1.204 +
   1.205 +void DWinsSDStack::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 DWinsSDStack::GetBufferInfo(TUint8** aMDBuf, TInt* aMDBufLen)
   1.227 +	{
   1.228 +	*aMDBuf = iMDBuf;
   1.229 +	*aMDBufLen = iMDBufLen;
   1.230 +	}
   1.231 +
   1.232 +void DWinsSDStack::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 DWinsSDStack::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 DWinsSDStack::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 DWinsSDStack::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 DWinsSDStack::InitClockOff()
   1.342 +	{
   1.343 +	// empty.
   1.344 +	}
   1.345 +
   1.346 +void DWinsSDStack::ASSPReset()
   1.347 +	{
   1.348 +	// empty.
   1.349 +	}
   1.350 +
   1.351 +void DWinsSDStack::ASSPDisengage()
   1.352 +	{
   1.353 +	// empty.
   1.354 +	}
   1.355 +
   1.356 +void DWinsSDStack::DoPowerDown()
   1.357 +	{
   1.358 +	// empty.
   1.359 +	}
   1.360 +
   1.361 +
   1.362 +LOCAL_C TInt SetMediaPasswordEnvironmentVar(TInt aSocketNum,TInt aCardNum,const TDesC8& aPasswd)
   1.363 +// 
   1.364 +// Set the password for local drive 'aLocalDrive', card number 'aCardNum' to 'aPasswd' - as an
   1.365 +// environment variable. Note that the card number is only relevant where the emulated drive
   1.366 +// supports card hot-swapping (i.e. F4 whilst F5 is held down).
   1.367 +//
   1.368 +	{
   1.369 +	// Setup the appropriate environment variable string '_EPOC_LocDrv_<locDrvNum>_PWORD_<cardNum>'
   1.370 +	TUint16 envVar[]=L"_EPOC_Socket_X_PWORD_Y";
   1.371 +
   1.372 +	envVar[13]=(TUint16)('0'+aSocketNum);
   1.373 +	envVar[21]=(TUint16)('0'+aCardNum);
   1.374 +	
   1.375 +	// Setup the new value of the environment variable
   1.376 +	TUint16	envVal[100];
   1.377 +	TInt len=aPasswd.Length();
   1.378 +
   1.379 +	// the password may be empty if a card's password is cleared
   1.380 +	if (len>(100-1))
   1.381 +		return(KErrArgument);
   1.382 +	memcpy(&envVal[0],reinterpret_cast<const TUint16 *>(aPasswd.Ptr()),len);
   1.383 +	envVal[len>>1]='\0';
   1.384 +
   1.385 +	// Now set the new value for the environment variable
   1.386 +	if (SetEnvironmentVariable(envVar,&envVal[0]))
   1.387 +		return(KErrNone);
   1.388 +
   1.389 +	return KErrGeneral;
   1.390 +	}
   1.391 +
   1.392 +LOCAL_C TInt MediaPasswordEnvironmentVar(TInt aSocketNum,TInt aCardNum,TDes8& aPasswd)
   1.393 +// 
   1.394 +// Get the password for local drive 'aLocalDrive', card number 'aCardNum' into 'aPasswd' - from
   1.395 +// an environment variable. Note that the card number is only relevant where the emulated drive
   1.396 +// supports card hot-swapping (i.e. F4 whilst F5 is held down).
   1.397 +//
   1.398 +	{
   1.399 +	TUint16 envVar[]=L"_EPOC_Socket_X_PWORD_Y";
   1.400 +
   1.401 +	envVar[13]=(TUint16)('0'+aSocketNum);
   1.402 +	envVar[21]=(TUint16)('0'+aCardNum);
   1.403 +	
   1.404 +	TUint16 envVal[100];	// To hold the value of the retreived environment variable
   1.405 +	
   1.406 +	DWORD len=GetEnvironmentVariable(envVar,&envVal[0],100);
   1.407 +	if (len>(TUint)100)
   1.408 +		return(KErrGeneral);
   1.409 +	if (len)
   1.410 +		{
   1.411 +		// Found the requested environment variable so there is a password for this local drive / card. 
   1.412 +		if ((len<<1)<=KMaxMediaPassword)
   1.413 +			{
   1.414 +			aPasswd.FillZ(KMaxMediaPassword);
   1.415 +			aPasswd.Zero();
   1.416 +			aPasswd.Copy(reinterpret_cast<TUint8*>(&envVal[0]),len<<1);
   1.417 +			return(KErrNone);	
   1.418 +			}
   1.419 +		else	
   1.420 +			return(KErrGeneral);	
   1.421 +		}
   1.422 +
   1.423 +	return(KErrNotFound);
   1.424 +	}
   1.425 +
   1.426 +TMMCErr DWinsSDStack::DoPowerUpSM()
   1.427 +	{
   1.428 +	enum states
   1.429 +		{
   1.430 +		EStBegin=0,
   1.431 +		EStEnd
   1.432 +		};
   1.433 +
   1.434 +	SMF_BEGIN
   1.435 +
   1.436 +		if(MMCSocket()->iVcc->SetState(EPsuOnCurLimit) != KErrNone)
   1.437 +			return KMMCErrHardware;
   1.438 +
   1.439 +		for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.440 +			{
   1.441 +			// if card has a password, it will be locked on power up
   1.442 +			TInt cardNum = (i==0) ? *Wins::CurrentPBusDevicePtr() : i;
   1.443 +			if (	cardNum >= 0
   1.444 +				&&	MediaPasswordEnvironmentVar(
   1.445 +						MMCSocket()->iSocketNumber, cardNum, *(iCardInfo[i]->iPWD))
   1.446 +					==	KErrNone)
   1.447 +				{
   1.448 +				iCardInfo[i]->iIsLocked = (iCardInfo[i]->iPWD->Length() > 0);
   1.449 +				}
   1.450 +			else	
   1.451 +				iCardInfo[i]->iIsLocked=EFalse;
   1.452 +
   1.453 +			iCardInfo[i]->iState = ECardStateIdle;
   1.454 +			iCardInfo[i]->iRCA=0x0001;		// Default RCA - spec 2.2, s4.2.1, 5.4
   1.455 +			}
   1.456 +
   1.457 +		ReportPowerUp();
   1.458 +
   1.459 +	SMF_END
   1.460 +	}
   1.461 +
   1.462 +TMMCErr DWinsSDStack::InitClockOnSM()
   1.463 +	{
   1.464 +	enum states
   1.465 +		{
   1.466 +		EStBegin=0,
   1.467 +		EStEnd
   1.468 +		};
   1.469 +	SMF_BEGIN
   1.470 +
   1.471 +	SMF_END
   1.472 +	}
   1.473 +
   1.474 +void DWinsSDStack::AddressCard(TInt aCardNumber)
   1.475 +	{
   1.476 +	iAddressedCard = aCardNumber;
   1.477 +	}
   1.478 +
   1.479 +
   1.480 +TInt DWinsSDStack::GetTargetSlotNumber(const TRCA& anRCA)
   1.481 +//
   1.482 +// when the controller is given a command with an embedded RCA, this function
   1.483 +// works out which physical card slot it corresponds to.  If no card has been
   1.484 +// assigned the RCA then it returns -1.
   1.485 +//
   1.486 +	{
   1.487 +	TInt targetIdx = -1;
   1.488 +
   1.489 +	for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.490 +		{
   1.491 +		if (iCardInfo[i]->iRCA==anRCA)
   1.492 +			{
   1.493 +			targetIdx=i;
   1.494 +			break;
   1.495 +			}
   1.496 +		}
   1.497 +
   1.498 +	return(targetIdx);
   1.499 +	}
   1.500 +
   1.501 +TMMCErr DWinsSDStack::IssueMMCCommandSM()
   1.502 +	{
   1.503 +	enum states
   1.504 +		{
   1.505 +		EStBegin=0,
   1.506 +		EStEnd
   1.507 +		};
   1.508 +
   1.509 +	TMMCCommandDesc& cmd = Command();
   1.510 +
   1.511 +	// If the command contains an embedded RCA then extract it	
   1.512 +	TRCA tgtRCA=0;
   1.513 +	TBool supRCA=EFalse;
   1.514 +	if (/*cmd.iCommand == ECmdSetRelativeAddr	||	*/cmd.iCommand == ECmdSelectCard
   1.515 +	||	cmd.iCommand == ECmdSendCSD			||	cmd.iCommand == ECmdSendCID
   1.516 +	||	cmd.iCommand == ECmdSendStatus		||	cmd.iCommand == ECmdGoInactiveState
   1.517 +	||	cmd.iCommand == ECmdFastIO 			||  cmd.iCommand == ECmdAppCmd )
   1.518 +		{
   1.519 +		if ((cmd.iArgument >> 16) != 0)
   1.520 +			{
   1.521 +			supRCA=ETrue;
   1.522 +			tgtRCA=TUint16(cmd.iArgument >> 16);
   1.523 +			}
   1.524 +		}
   1.525 +
   1.526 +	// if the card contains an embedded RCA, work out which slot it corresponds to.
   1.527 +	// At the end of the function, this card is used to generate the R1 response.
   1.528 +	// Assume that if rca is supplied it either corresponds to the selected card or
   1.529 +	// broadcast mode is on.  (An exception is CMD7 with arg0 to deselect all cards.)
   1.530 +
   1.531 +	TInt targetCard = supRCA ? GetTargetSlotNumber(tgtRCA) : iAddressedCard;
   1.532 +	TBool rto = EFalse;							// response timeout
   1.533 +
   1.534 +	// if try to access card zero has been set to holding no card via F5 / F4 then timeout.
   1.535 +	if ((targetCard == 0) && *Wins::CurrentPBusDevicePtr() < 0)
   1.536 +		return KMMCErrResponseTimeOut;
   1.537 +	
   1.538 +	HANDLE winHandle;
   1.539 +
   1.540 +	// CMD42 is a data transfer command.  That means the R1 response that it returns
   1.541 +	// immediately is the state it is in on receiving the data block, and not after
   1.542 +	// processing it.  If the data block is invalid then LOCK_UNLOCK_FAILED will be
   1.543 +	// set in the R1 response which is sent in reply to the next command.
   1.544 +
   1.545 +	TBool nextCMD42Failed = EFalse;
   1.546 +	TBool lock_unlock_failed=EFalse;
   1.547 +
   1.548 +	// When the card is locked, it will only respond to basic command class (0) and
   1.549 +	// lock card command class (7).  An exception is CMD16.  This is sent before CMD42,
   1.550 +	// but is classified (MMC Spec 23.2, table 5) as belonging to classes 2 and 4.
   1.551 +	// For data transfer commands, LOCK_UNLOCK_FAIL is set in response to the following
   1.552 +
   1.553 +	TMMCCommandEnum origCmd = cmd.iCommand;
   1.554 +
   1.555 +	// if targetting locked card...
   1.556 +	if (targetCard != KBroadcastToAllCards && iCardInfo[targetCard]->iIsLocked)
   1.557 +		{
   1.558 +		// ...and not command used in init or CMD42 sequence...
   1.559 +		if (!(	((cmd.iSpec.iCommandClass & (KMMCCmdClassApplication | KMMCCmdClassBasic | KMMCCmdClassLockCard)) != 0)
   1.560 +			||	(cmd.iCommand == ECmdSetBlockLen) || (cmd.iCommand == ECmdAppCmd) ))
   1.561 +			{
   1.562 +			lock_unlock_failed = ETrue;
   1.563 +			cmd.iCommand = (TMMCCommandEnum) -1;	// skip case processing
   1.564 +			}
   1.565 +		}
   1.566 +
   1.567 +	SMF_BEGIN
   1.568 +
   1.569 +	switch (cmd.iCommand)
   1.570 +		{
   1.571 +		case ECmdGoIdleState:	// CMD0
   1.572 +			if (iAddressedCard != KBroadcastToAllCards)
   1.573 +				iCardInfo[iAddressedCard]->iState = ECardStateIdle;
   1.574 +			else
   1.575 +				{
   1.576 +				for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.577 +					iCardInfo[i]->iState = ECardStateIdle;
   1.578 +				}
   1.579 +			break;
   1.580 +
   1.581 +		case ECmd41:
   1.582 +		case ECmdSendOpCond:	// CMD1
   1.583 +			{
   1.584 +			if (iAddressedCard != KBroadcastToAllCards)
   1.585 +				iCardInfo[iAddressedCard]->iState = ECardStateReady;
   1.586 +			else
   1.587 +				{
   1.588 +				for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
   1.589 +					iCardInfo[i]->iState = ECardStateReady;
   1.590 +				}
   1.591 +
   1.592 +			// bit31 is set to indicate cards are not still powering up
   1.593 +			TUint32 r3 = KMMCWinsCardOCRValue | KMMCOCRBusy;
   1.594 +			TMMC::BigEndian4Bytes(cmd.iResponse, r3);
   1.595 +			}
   1.596 +			break;
   1.597 +
   1.598 +		case ECmdAllSendCID:	// CMD2
   1.599 +			{
   1.600 +			TInt idx;
   1.601 +			if (iAddressedCard != KBroadcastToAllCards)
   1.602 +				{
   1.603 +				idx = iAddressedCard;
   1.604 +				__ASSERT_DEBUG(
   1.605 +					iCardInfo[iAddressedCard]->iState == ECardStateReady,
   1.606 +					DWinsSDStack::Panic(DWinsSDStack::EStkIMCBadStateCmd2));
   1.607 +				}
   1.608 +			else
   1.609 +				idx = FindAnyCardInStack(ECardStateReady);
   1.610 +
   1.611 +			if (idx == -1)
   1.612 +				rto = ETrue;
   1.613 +			else
   1.614 +				{
   1.615 +				iCardInfo[idx]->iCID.Copy(cmd.iResponse);
   1.616 +				iCardInfo[idx]->iState = ECardStateIdent;
   1.617 +				}
   1.618 +			}
   1.619 +			break;
   1.620 +
   1.621 +		case ECmdSetRelativeAddr:	// CMD3
   1.622 +			{
   1.623 +			TInt idx;
   1.624 +			if (iAddressedCard != KBroadcastToAllCards)
   1.625 +				{
   1.626 +				__ASSERT_DEBUG(
   1.627 +					iCardInfo[iAddressedCard]->iState == ECardStateIdent,
   1.628 +					DWinsSDStack::Panic(DWinsSDStack::EStkIMCBadStateCmd3));
   1.629 +				
   1.630 +				if (iCardInfo[iAddressedCard]->iIsSDCard)
   1.631 +					{
   1.632 +					static TUint16 RCACounter = 0x1234;
   1.633 +					// SD Cards publish RCAs
   1.634 +					++RCACounter;
   1.635 +					iCardInfo[iAddressedCard]->iRCA = RCACounter;
   1.636 +					iCardInfo[iAddressedCard]->iState = ECardStateStby;
   1.637 +					TUint32 r6 = TUint32(RCACounter) << 16;
   1.638 +					TMMC::BigEndian4Bytes(&cmd.iResponse[0],r6); // Ignore bits 47-40
   1.639 +					}
   1.640 +				else
   1.641 +					{
   1.642 +					iCardInfo[iAddressedCard]->iRCA = TUint16(cmd.iArgument >> 16);
   1.643 +					iCardInfo[iAddressedCard]->iState=ECardStateStby;
   1.644 +					}
   1.645 +				}
   1.646 +			else
   1.647 +				{
   1.648 +				// MultiMediaCards are assigned RCAs
   1.649 +				idx = FindOneCardInStack(ECardStateIdent);
   1.650 +				iCardInfo[iAddressedCard]->iRCA = TUint16(cmd.iArgument >> 16);
   1.651 +				iCardInfo[iAddressedCard]->iState=ECardStateStby;
   1.652 +				targetCard = iAddressedCard;
   1.653 +				}
   1.654 +			}
   1.655 +			break;
   1.656 +
   1.657 +		case ECmd6:
   1.658 +			// if ACMD6 then change bus width
   1.659 +			if (cmd.iSpec.iCommandClass == KMMCCmdClassApplication)
   1.660 +				{
   1.661 +				switch (cmd.iArgument)
   1.662 +					{
   1.663 +				case 0x00:
   1.664 +					iCardInfo[iAddressedCard]->iBusWidth = 1;
   1.665 +					break;
   1.666 +				case 0x02:
   1.667 +					iCardInfo[iAddressedCard]->iBusWidth = 4;
   1.668 +					break;
   1.669 +				default:
   1.670 +					DWinsSDStack::Panic(DWinsSDStack::EStkIMCCmd6InvalidWidth);
   1.671 +					break;
   1.672 +					}
   1.673 +				}
   1.674 +			break;
   1.675 +
   1.676 +		case ECmdSelectCard:		// CMD7
   1.677 +			{
   1.678 +			// switch to broadcast mode so the currently selected and new cards
   1.679 +			// receive the command simultaneously.
   1.680 +
   1.681 +			TInt idx = FindAnyCardInStack(ECardStateTran);
   1.682 +			if (idx != -1)
   1.683 +				iCardInfo[idx]->iState = ECardStateStby;
   1.684 +			if ((iAddressedCard=targetCard) == KBroadcastToAllCards)
   1.685 +				rto = ETrue;
   1.686 +			else
   1.687 +				{
   1.688 +				iCardInfo[targetCard]->iState = ECardStateTran;
   1.689 +				targetCard = targetCard;
   1.690 +				}
   1.691 +			}
   1.692 +			break;
   1.693 +
   1.694 +		case ECmdSendStatus:
   1.695 +			// R1 response so status return as for any other R1 command.
   1.696 +			if (cmd.iSpec.iCommandClass == KMMCCmdClassApplication)
   1.697 +				{
   1.698 +				__ASSERT_DEBUG(
   1.699 +					iCardInfo[targetCard]->iIsSDCard,
   1.700 +					DWinsSDStack::Panic(DWinsSDStack::EStkICMACMD13NotSD));
   1.701 +
   1.702 +				memset(cmd.iDataMemoryP, 0, KSDStatusBlockLength);
   1.703 +				if (iCardInfo[targetCard]->iBusWidth == 1)
   1.704 +					cmd.iDataMemoryP[0] = 0x00 << 6;
   1.705 +				else	// if (iCardInfo[targetCard]->iBusWidth == 4)
   1.706 +					cmd.iDataMemoryP[0] = 0x02 << 6;
   1.707 +				cmd.iDataMemoryP[7] = 0x28;		// PROTECTED_AREA_SIZE
   1.708 +				}
   1.709 +			break;
   1.710 +
   1.711 +		case ECmdReadSingleBlock:
   1.712 +		case ECmdReadMultipleBlock:
   1.713 +			{
   1.714 +			winHandle=iCardInfo[targetCard]->iAreaHandles[KSDUserArea];
   1.715 +
   1.716 +			if ( cmd.iSpec.iUseStopTransmission && cmd.iBlockLength >= cmd.iTotalLength)
   1.717 +				return( KMMCErrNotSupported );
   1.718 +
   1.719 +    		TMMCErr err;
   1.720 +			TInt pos = cmd.iArgument;
   1.721 +    		if (SetFilePointer(winHandle,pos,NULL,FILE_BEGIN)==0xffffffffu)
   1.722 +        		err=MapLastErrorMmc();
   1.723 +    		else
   1.724 +        		{
   1.725 +	    		DWORD res;
   1.726 +				TInt len = cmd.iTotalLength;
   1.727 +		        if (ReadFile(winHandle,(TAny*)cmd.iDataMemoryP,len,&res,NULL)==FALSE)
   1.728 +                    err=MapLastErrorMmc();
   1.729 +                else if (res!=(DWORD)len)
   1.730 +                    err=KMMCErrGeneral;
   1.731 +                else
   1.732 +                    err=KMMCErrNone;
   1.733 +				}
   1.734 +			if (err!=KMMCErrNone)
   1.735 +				return(err);
   1.736 +			break;
   1.737 +			}
   1.738 +
   1.739 +		case ECmd22:
   1.740 +			if (cmd.iSpec.iCommandClass == KMMCCmdClassApplication)
   1.741 +				{
   1.742 +				TMMC::BigEndian4Bytes(cmd.iResponse, iMBWOKBlocks);
   1.743 +				}
   1.744 +			break;
   1.745 +		// ------------------------------------------------------------------
   1.746 +		case ECmdWriteBlock:
   1.747 +		case ECmdWriteMultipleBlock:
   1.748 +			{
   1.749 +			TUint32 writeLen;
   1.750 +
   1.751 +			// periodically fail multi-block writes to test ACMD22 error recovery
   1.752 +			if (cmd.iCommand != ECmdWriteMultipleBlock)
   1.753 +				writeLen = cmd.iTotalLength;
   1.754 +			else
   1.755 +				{
   1.756 +				const TInt KMaxFailCnt = 4;
   1.757 +				static TInt failCnt = 0;
   1.758 +				const TInt KMaxFailBlock = 4;
   1.759 +				static TInt failBlocks = 0;
   1.760 +				
   1.761 +				failCnt = (failCnt + 1) % KMaxFailCnt;
   1.762 +				if (failCnt != 0)
   1.763 +					writeLen = cmd.iTotalLength;
   1.764 +				else
   1.765 +					{
   1.766 +					failBlocks = (failBlocks + 1) % KMaxFailBlock;
   1.767 +					
   1.768 +					// fail at least one block
   1.769 +					TInt totalBlocks = cmd.iTotalLength / cmd.iBlockLength;
   1.770 +					TInt blocksToFail = Min(failBlocks + 1, totalBlocks);	// fail at least one block
   1.771 +					iMBWOKBlocks = (totalBlocks - blocksToFail);
   1.772 +					writeLen = iMBWOKBlocks * cmd.iBlockLength;
   1.773 +					if (writeLen == 0)
   1.774 +						return KMMCErrDataTimeOut;
   1.775 +					}
   1.776 +				}
   1.777 +			
   1.778 +			HANDLE h=iCardInfo[targetCard]->iAreaHandles[KSDUserArea];
   1.779 +
   1.780 +    		TMMCErr err;
   1.781 +			TInt pos = cmd.iArgument;
   1.782 +    		if (SetFilePointer(h, pos, NULL, FILE_BEGIN)==0xffffffffu)
   1.783 +        		err = MapLastErrorMmc();
   1.784 +    		else
   1.785 +        		{
   1.786 +	    		DWORD res;
   1.787 +				if (! WriteFile(h, (LPCVOID)cmd.iDataMemoryP,writeLen,&res,NULL))
   1.788 +                    err=MapLastErrorMmc();
   1.789 +                else if (res!=(DWORD)writeLen)
   1.790 +                    err=KMMCErrGeneral;
   1.791 +                else
   1.792 +                    err=KMMCErrNone;
   1.793 +				}
   1.794 +
   1.795 +			if (err!=KMMCErrNone)
   1.796 +				return(err);
   1.797 +			if (writeLen != cmd.iTotalLength)
   1.798 +				return KMMCErrDataTimeOut;
   1.799 +			}
   1.800 +			break;
   1.801 +
   1.802 +		case ECmdAppCmd:
   1.803 +			// targetCard == -1 when ACMD41 being sent because not yet supplied
   1.804 +			if (iAddressedCard != KBroadcastToAllCards)
   1.805 +				{
   1.806 +				// timeout if addressed card is not SD
   1.807 +				if (! iCardInfo[iAddressedCard]->iIsSDCard)
   1.808 +					rto = ETrue;
   1.809 +				}
   1.810 +			else
   1.811 +				{
   1.812 +				// request sent to specific non-SD card
   1.813 +				if (targetCard != -1 && ! iCardInfo[targetCard]->iIsSDCard)
   1.814 +					rto = ETrue;
   1.815 +				}
   1.816 +			break;
   1.817 +
   1.818 +		case ECmdSendCSD:
   1.819 +			{
   1.820 +			iCardInfo[targetCard]->GetCSD(cmd.iResponse);
   1.821 +			break;
   1.822 +			}
   1.823 +
   1.824 +		// ------------------------------------------------------------------
   1.825 +		case ECmdLockUnlock:
   1.826 +			// in EPOC, Lock() does not actually lock the card.  It just sets the
   1.827 +			// password.  This means that the card is still accessible to the user,
   1.828 +			// but must be unlocked the next time it is powered up.
   1.829 +
   1.830 +			// a real card will transiently go into rcv and prg state while processing
   1.831 +			// this command.  When finished, it will fall back into tran state.
   1.832 +			// The R1 response is sent immediately after CMD42.  CIMReadWriteBlocksSM()
   1.833 +			// sends CMD13 to find out whether or not LOCK_UNLOCK_FAIL was set.
   1.834 +
   1.835 +			// the asserts in this case protect against invalid data being sent from the
   1.836 +			// media driver.  A real card would fail these corrupt data blocks.
   1.837 +
   1.838 +			{
   1.839 +			const TInt8 cmd_byte(*cmd.iDataMemoryP);
   1.840 +			__ASSERT_DEBUG(										// ensure not CLR_PWD && SET_PWD
   1.841 +				!((cmd_byte & KMMCLockUnlockClrPwd) && (cmd_byte & KMMCLockUnlockSetPwd)),
   1.842 +				DWinsSDStack::Panic(DWinsSDStack::EWinsMMCCorruptCommand) );
   1.843 +			
   1.844 +			__ASSERT_DEBUG(										// not actually lock a card while setting the password
   1.845 +				((cmd_byte & (KMMCLockUnlockLockUnlock | KMMCLockUnlockSetPwd)) != (KMMCLockUnlockLockUnlock | KMMCLockUnlockSetPwd)),
   1.846 +				DWinsSDStack::Panic(DWinsSDStack::EWinsMMCLockAttempt) );
   1.847 +
   1.848 +			if (cmd_byte & KMMCLockUnlockErase)					// ERASE (not supported)
   1.849 +				return KMMCErrNotSupported;
   1.850 +
   1.851 +			const TInt8 pwd_len = *(cmd.iDataMemoryP + 1);
   1.852 +			const TPtrC8 pwd(cmd.iDataMemoryP + 2, pwd_len);
   1.853 +
   1.854 +			if ((cmd_byte & KMMCLockUnlockClrPwd) != 0)			// CLR_PWD == 1
   1.855 +				{
   1.856 +				__ASSERT_DEBUG(
   1.857 +					pwd_len >= 0 && pwd_len <= KMaxMediaPassword,
   1.858 +					DWinsSDStack::Panic(DWinsSDStack::EWinsMMCCorruptCommand));
   1.859 +
   1.860 +				if (iCardInfo[targetCard]->iIsLocked)						// clear when locked
   1.861 +					nextCMD42Failed = ETrue;
   1.862 +				else														// clear when unlocked
   1.863 +					{
   1.864 +					if (iCardInfo[targetCard]->iPWD->Compare(pwd) != 0)		// clear when unlocked with wrong password
   1.865 +						{
   1.866 +						nextCMD42Failed = ETrue;
   1.867 +						lock_unlock_failed = ETrue;
   1.868 +						}
   1.869 +					else													// clear when unlocked with right password
   1.870 +						{
   1.871 +						// Clear from password store 
   1.872 +						iCardInfo[targetCard]->iPWD->Zero();
   1.873 +						iCardInfo[targetCard]->iIsLocked = EFalse;
   1.874 +						nextCMD42Failed = EFalse;
   1.875 +						
   1.876 +						// Clear from environment settings
   1.877 +						TInt cardNum=(targetCard==0) ? *Wins::CurrentPBusDevicePtr() : targetCard; // Can't be -1 at this stage
   1.878 +						SetMediaPasswordEnvironmentVar(MMCSocket()->iSocketNumber,cardNum,*(iCardInfo[targetCard]->iPWD));
   1.879 +						}
   1.880 +					}
   1.881 +				}
   1.882 +			else if ((cmd_byte & KMMCLockUnlockSetPwd) == 0)	// SET_PWD == 0: unlock
   1.883 +				{
   1.884 +				__ASSERT_DEBUG(
   1.885 +					pwd_len >= 0 && pwd_len <= KMaxMediaPassword,
   1.886 +					DWinsSDStack::Panic(DWinsSDStack::EWinsMMCCorruptCommand) );
   1.887 +				
   1.888 +				if (! iCardInfo[targetCard]->iIsLocked)						// unlock when unlocked
   1.889 +					nextCMD42Failed = ETrue;
   1.890 +				else
   1.891 +					{
   1.892 +					if (iCardInfo[targetCard]->iPWD->Compare(pwd) != 0)		// unlock when locked with wrong password
   1.893 +						{
   1.894 +						nextCMD42Failed = ETrue;
   1.895 +						lock_unlock_failed = ETrue;
   1.896 +						}
   1.897 +					else													// unlock when locked with right password
   1.898 +						{
   1.899 +						iCardInfo[targetCard]->iIsLocked = EFalse;
   1.900 +						nextCMD42Failed = EFalse;
   1.901 +						}
   1.902 +					}
   1.903 +				}
   1.904 +			else  if ((cmd_byte & KMMCLockUnlockSetPwd) == KMMCLockUnlockSetPwd)	// SET_PWD == 1
   1.905 +				{
   1.906 +				__ASSERT_DEBUG(
   1.907 +					cmd_byte & KMMCLockUnlockSetPwd,
   1.908 +					DWinsSDStack::Panic(DWinsSDStack::EWinsMMCCorruptCommand) );
   1.909 +
   1.910 +				// if pwd_len < iCardInfo[targetCard]->iPWD->Length() then data block must be invalid.
   1.911 +				// This can be caused by bad user input rather than inaccurate formation.
   1.912 +				if (!(	pwd_len >= iCardInfo[targetCard]->iPWD->Length()
   1.913 +					&&	pwd_len <= iCardInfo[targetCard]->iPWD->Length() + KMaxMediaPassword ))
   1.914 +					{
   1.915 +					nextCMD42Failed = ETrue;
   1.916 +					}
   1.917 +				else
   1.918 +					{
   1.919 +					const TInt old_pwd_len = iCardInfo[targetCard]->iPWD->Length();
   1.920 +					TPtrC8 old_pwd(cmd.iDataMemoryP + 2, old_pwd_len);
   1.921 +					TPtrC8 new_pwd(cmd.iDataMemoryP + 2 + old_pwd_len, pwd_len - old_pwd_len);
   1.922 +
   1.923 +					// card must not be locked and supplied current password must be correct
   1.924 +					if (iCardInfo[targetCard]->iIsLocked || iCardInfo[targetCard]->iPWD->Compare(old_pwd) != 0)
   1.925 +						{
   1.926 +						nextCMD42Failed = ETrue;
   1.927 +						lock_unlock_failed = ETrue;
   1.928 +						}
   1.929 +					else
   1.930 +						{
   1.931 +						// Set in password store
   1.932 +						iCardInfo[targetCard]->iPWD->Copy(new_pwd);
   1.933 +						nextCMD42Failed = EFalse;
   1.934 +						
   1.935 +						// Set in environment settings
   1.936 +						TInt cardNum=(targetCard==0) ? *Wins::CurrentPBusDevicePtr() : targetCard; // Can't be -1 at this stage
   1.937 +						SetMediaPasswordEnvironmentVar(MMCSocket()->iSocketNumber,cardNum,*(iCardInfo[targetCard]->iPWD));
   1.938 +						}
   1.939 +					}
   1.940 +				}
   1.941 +			else  if ((cmd_byte & KMMCLockUnlockLockUnlock) == KMMCLockUnlockLockUnlock)
   1.942 +				{
   1.943 +				__ASSERT_DEBUG(
   1.944 +					pwd_len >= 0 && pwd_len <= KMaxMediaPassword,
   1.945 +					DWinsSDStack::Panic(DWinsSDStack::EWinsMMCCorruptCommand) );
   1.946 +				
   1.947 +				if (iCardInfo[targetCard]->iIsLocked)						// lock when locked
   1.948 +					nextCMD42Failed = ETrue;
   1.949 +				else
   1.950 +					{
   1.951 +					if (iCardInfo[targetCard]->iPWD->Compare(pwd) != 0)		// lock with wrong password
   1.952 +						{
   1.953 +						nextCMD42Failed = ETrue;
   1.954 +						lock_unlock_failed = ETrue;
   1.955 +						}
   1.956 +					else													// lock with right password
   1.957 +						{
   1.958 +						iCardInfo[targetCard]->iIsLocked = ETrue;
   1.959 +						nextCMD42Failed = EFalse;
   1.960 +						}
   1.961 +					}
   1.962 +				}
   1.963 +			else
   1.964 +				{
   1.965 +				__ASSERT_DEBUG(EFalse, DWinsSDStack::Panic(DWinsSDStack::EWinsMMCLockAttempt) );
   1.966 +				}
   1.967 +			}	// case ECmdLockUnlock
   1.968 +		// ------------------------------------------------------------------
   1.969 +		default:
   1.970 +			break;
   1.971 +		}
   1.972 +
   1.973 +	if (rto)
   1.974 +		return(KMMCErrResponseTimeOut);
   1.975 +
   1.976 +	cmd.iCommand = origCmd;
   1.977 +	// If this is an R1 or R1b response type command then return card status as a response
   1.978 +	if (	targetCard != -1
   1.979 +		&&	(cmd.iSpec.iResponseType==ERespTypeR1 || cmd.iSpec.iResponseType==ERespTypeR1B) )
   1.980 +		{
   1.981 +		TUint32 resp(
   1.982 +				iCardInfo[targetCard]->iState
   1.983 +			|	((iCardInfo[targetCard]->iIsLocked ? 1 : 0) << 25)
   1.984 +			|	((lock_unlock_failed ? 1 : 0) << 24) );
   1.985 +
   1.986 +		if (iCMD42Failed)								// previous CMD42
   1.987 +			{
   1.988 +			resp |= KMMCStatErrLockUnlock;
   1.989 +			nextCMD42Failed = EFalse;
   1.990 +			}
   1.991 +		iCMD42Failed = nextCMD42Failed;
   1.992 +		TMMC::BigEndian4Bytes(&cmd.iResponse[0],resp); // Ignore bits 47-40
   1.993 +		}
   1.994 +	SMF_END
   1.995 +	}
   1.996 +
   1.997 +TMMCErr DWinsSDStack::ModifyCardCapabilitySM()
   1.998 +//
   1.999 +// This function provides a chance to modify the capability of paticular cards.
  1.1000 +// Licensee may overide this function to modify certain card's capability as needed.
  1.1001 +// A state machine is needed in derived function and function of base class should be
  1.1002 +// called in order to act more generic behaviour.
  1.1003 +//
  1.1004 +    {
  1.1005 +		enum states
  1.1006 +			{
  1.1007 +			EStBegin=0,
  1.1008 +			EStDone,
  1.1009 +			EStEnd
  1.1010 +			};
  1.1011 +
  1.1012 +    SMF_BEGIN
  1.1013 +
  1.1014 +		SMF_INVOKES( DSDStack::BaseModifyCardCapabilitySMST, EStDone )
  1.1015 +
  1.1016 +    SMF_STATE(EStDone)
  1.1017 +
  1.1018 +    SMF_END
  1.1019 +    }
  1.1020 +
  1.1021 +TInt DWinsSDStack::FindAnyCardInStack(TMMCardStateEnum aState)
  1.1022 +//
  1.1023 +// first first active card in supplied state.  Return -1 if
  1.1024 +// no active card is in supplied state.
  1.1025 +//
  1.1026 +	{
  1.1027 +	if (iAddressedCard != KBroadcastToAllCards)
  1.1028 +		return (iCardInfo[iAddressedCard]->iState == aState) ? iAddressedCard : -1;
  1.1029 +	else
  1.1030 +		{
  1.1031 +		for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
  1.1032 +			{
  1.1033 +			if (iCardInfo[i]->iState == aState)
  1.1034 +				return i;
  1.1035 +			}
  1.1036 +
  1.1037 +		return -1;
  1.1038 +		}
  1.1039 +	}
  1.1040 +
  1.1041 +TInt DWinsSDStack::FindFirstCardInStack(TMMCardStateEnum aState)
  1.1042 +//
  1.1043 +// find card which is active on bus and in supplied state.
  1.1044 +// There can be more than one active card in the the supplied state,
  1.1045 +// but there should be at least one.
  1.1046 +//
  1.1047 +	{
  1.1048 +	if (iAddressedCard != KBroadcastToAllCards)
  1.1049 +		{
  1.1050 +		__ASSERT_DEBUG(iCardInfo[iAddressedCard]->iState == aState, DWinsSDStack::Panic(DWinsSDStack::EStkFFCNotSelCard));
  1.1051 +		return iAddressedCard;
  1.1052 +		}
  1.1053 +	else
  1.1054 +		{
  1.1055 +		TInt idx = -1;
  1.1056 +		for (TInt i = 0; idx != -1 && i < KTotalWinsCardSlots; ++i)
  1.1057 +			{
  1.1058 +			if (iCardInfo[i]->iState == aState)
  1.1059 +				idx = i;
  1.1060 +			}
  1.1061 +
  1.1062 +		__ASSERT_DEBUG(idx != -1, DWinsSDStack::Panic(DWinsSDStack::EStkFFCNoneSel));
  1.1063 +		return idx;
  1.1064 +		}
  1.1065 +	}
  1.1066 +
  1.1067 +TInt DWinsSDStack::FindOneCardInStack(TMMCardStateEnum aState)
  1.1068 +//
  1.1069 +// find card which is active on bus and in supplied state.
  1.1070 +// There should be exactly one active card in the supplied state.
  1.1071 +//
  1.1072 +	{
  1.1073 +	if (iAddressedCard != KBroadcastToAllCards)
  1.1074 +		{
  1.1075 +		__ASSERT_DEBUG(iCardInfo[iAddressedCard]->iState == aState, DWinsSDStack::Panic(DWinsSDStack::EStkFOCNotSelCard));
  1.1076 +		return iAddressedCard;
  1.1077 +		}
  1.1078 +	else
  1.1079 +		{
  1.1080 +		TInt idx = -1;
  1.1081 +		for (TInt i = 0; i < KTotalWinsCardSlots; ++i)
  1.1082 +			{
  1.1083 +			if (iCardInfo[i]->iState == aState)
  1.1084 +				{
  1.1085 +				__ASSERT_DEBUG(idx == -1, DWinsSDStack::Panic(DWinsSDStack::EStkFOCMultiSel));
  1.1086 +				idx = i;
  1.1087 +				}
  1.1088 +			}
  1.1089 +
  1.1090 +		__ASSERT_DEBUG(idx != -1, DWinsSDStack::Panic(DWinsSDStack::EStkFOCNoneSel));
  1.1091 +		return idx;
  1.1092 +		}
  1.1093 +	}
  1.1094 +
  1.1095 +
  1.1096 +// ======== DWinsMMCMediaChange ========
  1.1097 +
  1.1098 +#pragma warning( disable : 4355 )	// this used in initializer list
  1.1099 +DWinsMMCMediaChange::DWinsMMCMediaChange(TInt aMediaChangeNum)
  1.1100 +	: DMMCMediaChange(aMediaChangeNum),
  1.1101 +      iDoorClosedCount(0),
  1.1102 +	  iMediaChangeEnable(ETrue),
  1.1103 +	  iStackP(NULL)
  1.1104 +	{
  1.1105 +	iMediaDoorCloseReload=2; 	// Units: In theory-20ms, Actual-100ms
  1.1106 +	}
  1.1107 +#pragma warning( default : 4355 )
  1.1108 +
  1.1109 +TInt DWinsMMCMediaChange::Create()
  1.1110 +//
  1.1111 +// Initialiser.
  1.1112 +//
  1.1113 +	{	
  1.1114 +	return(DMediaChangeBase::Create());
  1.1115 +	}
  1.1116 +
  1.1117 +void DWinsMMCMediaChange::DoorOpenService()
  1.1118 +//
  1.1119 +// Handle the media change (this function, never postponed is called on media
  1.1120 +// change interrupt). 
  1.1121 +//
  1.1122 +	{
  1.1123 +	Disable();		// Disable interrupt until door closes again.
  1.1124 +	iDoorOpenDfc.Enque();
  1.1125 +	}
  1.1126 +
  1.1127 +void DWinsMMCMediaChange::DoDoorOpen()
  1.1128 +//
  1.1129 +// Handle media door open (called on media door open interrupt). 
  1.1130 +//
  1.1131 +	{
  1.1132 +	iDoorClosedCount=iMediaDoorCloseReload;
  1.1133 +	// Just start a ticklink to poll for door closing
  1.1134 +	iTickLink.Periodic(KMediaChangeTickInterval,DWinsMMCMediaChange::Tick,this);
  1.1135 +    }
  1.1136 +
  1.1137 +void DWinsMMCMediaChange::DoDoorClosed()
  1.1138 +//
  1.1139 +// Handle media door closing (called on media door open interrupt).
  1.1140 +//
  1.1141 +	{
  1.1142 +
  1.1143 +	iTickLink.Cancel();	// Doesn't matter if wasn't enabled
  1.1144 +	Enable();	// Re-enable door interrupts
  1.1145 +
  1.1146 +	// While the door was open the user may have changed the card in slot 0
  1.1147 +	if (iStackP && *Wins::CurrentPBusDevicePtr()>=0)
  1.1148 +		iStackP->iCardInfo[0]=iStackP->iCardPool[*Wins::CurrentPBusDevicePtr()];
  1.1149 +	}
  1.1150 +
  1.1151 +void DWinsMMCMediaChange::ForceMediaChange()
  1.1152 +//
  1.1153 +// Force media change
  1.1154 +//
  1.1155 +	{
  1.1156 +	DoorOpenService();
  1.1157 +	}
  1.1158 +
  1.1159 +TMediaState DWinsMMCMediaChange::MediaState()
  1.1160 +//
  1.1161 +// Return status of media changed signal.
  1.1162 +//
  1.1163 +	{
  1.1164 +
  1.1165 +	if (iDoorClosedCount>0)
  1.1166 +		return(EDoorOpen);
  1.1167 +	return( (*Wins::MediaDoorOpenPtr())?EDoorOpen:EDoorClosed);
  1.1168 +	}
  1.1169 +
  1.1170 +void DWinsMMCMediaChange::Tick(TAny *aPtr)
  1.1171 +//
  1.1172 +// Called on the tick to poll for door closing (called on DFC).
  1.1173 +//
  1.1174 +	{
  1.1175 +
  1.1176 +	((DWinsMMCMediaChange*)aPtr)->TickService();
  1.1177 +	}
  1.1178 +
  1.1179 +void DWinsMMCMediaChange::TickService()
  1.1180 +//
  1.1181 +// Called on the tick to poll for door closing (called on DFC).
  1.1182 +//
  1.1183 +	{
  1.1184 +
  1.1185 +	__ASSERT_DEBUG(iDoorClosedCount>=0,DWinsSDStack::Panic(DWinsSDStack::EWinsMMCMediaChangeTickFault));
  1.1186 +	if (!(*Wins::MediaDoorOpenPtr()))
  1.1187 +		{
  1.1188 +		if (iDoorClosedCount > 0)
  1.1189 +			iDoorClosedCount--;
  1.1190 +		if (iDoorClosedCount == 0)
  1.1191 +			DoorClosedService();
  1.1192 +		}
  1.1193 +	else
  1.1194 +		iDoorClosedCount=iMediaDoorCloseReload; // Door open so start again.
  1.1195 +	}
  1.1196 +
  1.1197 +void DWinsMMCMediaChange::Enable()
  1.1198 +//
  1.1199 +// Enable media change 
  1.1200 +//
  1.1201 +	{
  1.1202 +
  1.1203 +	iMediaChangeEnable=ETrue;
  1.1204 +	}
  1.1205 +
  1.1206 +void DWinsMMCMediaChange::Disable()
  1.1207 +//
  1.1208 +// Disable media change
  1.1209 +//
  1.1210 +	{
  1.1211 +
  1.1212 +	iMediaChangeEnable=EFalse;
  1.1213 +	}
  1.1214 +
  1.1215 +void DWinsMMCMediaChange::MediaChangeCallBack(TAny *aPtr)
  1.1216 +//
  1.1217 +// Static called on media change
  1.1218 +//
  1.1219 +	{
  1.1220 +
  1.1221 +	DWinsMMCMediaChange* mc=(DWinsMMCMediaChange*)aPtr;
  1.1222 +	if (mc!=NULL&&mc->iMediaChangeEnable)
  1.1223 +		mc->DoorOpenService();
  1.1224 +	}
  1.1225 +
  1.1226 +
  1.1227 +// ======== TWinsCardInfo ========
  1.1228 +
  1.1229 +void TWinsCardInfo::GetCSD(TUint8* aResp) const
  1.1230 +	{
  1.1231 +	// Bits 127-96
  1.1232 +	TUint32 csd=(0x1<<30); 	/* CSD_STRUCTURE: CSD Version No 1.1 */
  1.1233 +	csd|=		(0x2<<26); 	/* SPEC_VERS: Version 2.1 */
  1.1234 +	csd|=		(0x0E<<16);	/* TAAC: 1mS */  
  1.1235 +	csd|=		(0x0A<<8);	/* NSAC: 1000 */  
  1.1236 +	csd|=		(0x59);		/* TRAN_SPEED: 5.0Mbit/s */  
  1.1237 +	TMMC::BigEndian4Bytes(&aResp[0],csd);
  1.1238 +	// Bits 95-64
  1.1239 +	const TUint32 ccc = 
  1.1240 +			KMMCCmdClassBasic | KMMCCmdClassBlockRead
  1.1241 +		|	KMMCCmdClassBlockWrite | KMMCCmdClassLockCard;
  1.1242 +	csd=		(ccc<<20); 	/* CCC: classes 0, 2, 4, and 7 */
  1.1243 +	csd|=		(0x9<<16); 	/* READ_BL_LEN: 512 bytes */
  1.1244 +	csd|=		(0x0<<15);	/* READ_BL_PARTIAL: No */  
  1.1245 +	csd|=		(0x0<<14);	/* WRITE_BLK_MISALIGN: No */  
  1.1246 +	csd|=		(0x0<<13);	/* READ_BLK_MISALIGN: No */  
  1.1247 +	csd|=		(0x0<<12);	/* DSR_IMP: No DSR */ 
  1.1248 +	csd|=		(0x0<<8);	/* C_SIZE: 1Mb */
  1.1249 +	csd|=		(0x7F);		/* C_SIZE: 1Mb (cont)*/  
  1.1250 +	TMMC::BigEndian4Bytes(&aResp[4],csd); 
  1.1251 +	// Bits 63-32
  1.1252 +	csd=		(3UL<<30); 	/* C_SIZE: 2Mb (cont) */
  1.1253 +	csd|=		(0x1<<27); 	/* VDD_R_CURR_MIN: 1mA */
  1.1254 +	csd|=		(0x1<<24);	/* VDD_R_CURR_MAX: 5mA */  
  1.1255 +	csd|=		(0x2<<21); 	/* VDD_W_CURR_MIN: 5mA */
  1.1256 +	csd|=		(0x3<<18);	/* VDD_W_CURR_MAX: 25mA */  
  1.1257 +	csd|=		(0x0<<15);	/* C_SIZE_MULT: 0 */  
  1.1258 +	if (! iIsSDCard)
  1.1259 +		{
  1.1260 +		csd|=		(0x0<<10);	/* SECTOR_SIZE: 1 write block */  
  1.1261 +		csd|=		(0x0<<5);	/* ERASE_GRP_SIZE: 1 sector */  
  1.1262 +		csd|=		(0x0);		/* WP_GRP_SIZE: 1 erase group */  
  1.1263 +		}
  1.1264 +	else
  1.1265 +		{
  1.1266 +		csd |= (0x00 << (46 - 32));	// ERASE_BLK_EN
  1.1267 +		csd |= (0x1f << (39 - 32));	// SECTOR_SIZE: 32 write blocks
  1.1268 +		csd |= (0x00 << (32 - 32));	// WP_GRP_SIZE: 1 erase sector.
  1.1269 +		}
  1.1270 +	TMMC::BigEndian4Bytes(&aResp[8],csd); 
  1.1271 +	// Bits 31-0
  1.1272 +	csd=		(0x0<<31); 	/* WP_GRP_ENABLE: No */
  1.1273 +	csd|=		(0x0<<29); 	/* DEFAULT_ECC: ? */
  1.1274 +	csd|=		(0x3<<26);	/* R2W_FACTOR: 8 */  
  1.1275 +	csd|=		(0x9<<22); 	/* WRITE_BL_LEN: 512 bytes */
  1.1276 +	csd|=		(0x0<<21);	/* WRITE_BL_PARTIAL: No */  
  1.1277 +	csd|=		(0x0<<15);	/* FILE_FORMAT_GRP: Hard disk */  
  1.1278 +	csd|=		(0x0<<14);	/* COPY: original */  
  1.1279 +	csd|=		(0x0<<13);	/* PERM_WRITE_PROTECT: No */  
  1.1280 +	csd|=		(0x0<<12);	/* TMP_WRITE_PROTECT: No */  
  1.1281 +	csd|=		(0x0<<10);	/* FILE_FORMAT: Hard disk */  
  1.1282 +	csd|=		(0x0<<8);	/* ECC: None */  
  1.1283 +	csd|=		(0x0<<1);	/* CRC: ? */  
  1.1284 +	csd|=		(0x1);		/* not used */  
  1.1285 +	TMMC::BigEndian4Bytes(&aResp[12],csd);
  1.1286 +	}
  1.1287 +
  1.1288 +// ======== DWinsMMCPsu ========
  1.1289 +
  1.1290 +
  1.1291 +DWinsMMCPsu::DWinsMMCPsu(TInt aVccNum, TInt aMcId)
  1.1292 +	: DMMCPsu(aVccNum, aMcId)
  1.1293 +	{}
  1.1294 +
  1.1295 +void DWinsMMCPsu::Init()
  1.1296 +//
  1.1297 +// Initialise the PSU
  1.1298 +//
  1.1299 +    {
  1.1300 +	// Nothing to do
  1.1301 +    }
  1.1302 +
  1.1303 +void DWinsMMCPsu::DoSetState(TPBusPsuState aState)
  1.1304 +//
  1.1305 +// Turn on/off the PSU. If it is possible to adjust the output voltage on this
  1.1306 +// PSU then retreive the required voltage level from TMMCPsu::iVoltageSetting
  1.1307 +// (which is in OCR register format).
  1.1308 +//
  1.1309 +    {
  1.1310 +
  1.1311 +    switch (aState)
  1.1312 +        {
  1.1313 +        case EPsuOff:
  1.1314 +            break;
  1.1315 +        case EPsuOnFull:
  1.1316 +            break;
  1.1317 +        case EPsuOnCurLimit:
  1.1318 +            break;
  1.1319 +        }
  1.1320 +    }
  1.1321 +
  1.1322 +TInt DWinsMMCPsu::VoltageInMilliVolts()
  1.1323 +//
  1.1324 +// Return the level of the PSU (in mV) or -ve if error.
  1.1325 +//
  1.1326 +    {
  1.1327 +
  1.1328 +    return(0);
  1.1329 +    }
  1.1330 +
  1.1331 +void DWinsMMCPsu::DoCheckVoltage()
  1.1332 +//
  1.1333 +// Check the voltage level of the PSU is as expected. Returns either KErrNone, KErrGeneral 
  1.1334 +// to indicate the pass/fail state or KErrNotReady if the voltage check isn't complete.
  1.1335 +//
  1.1336 +    {
  1.1337 +
  1.1338 +	ReceiveVoltageCheckResult(KErrNone);
  1.1339 +    }
  1.1340 +
  1.1341 +void DWinsMMCPsu::PsuInfo(TPBusPsuInfo &anInfo)
  1.1342 +//
  1.1343 +// Return machine info relating to the MMC PSU supply
  1.1344 +//
  1.1345 +    {
  1.1346 +
  1.1347 +	anInfo.iVoltageSupported=0x00040000; // 3.0V (OCR reg. format).
  1.1348 +	anInfo.iMaxCurrentInMicroAmps=0;
  1.1349 +	anInfo.iVoltCheckInterval=0;
  1.1350 +	anInfo.iVoltCheckMethod=EPsuChkComparator;
  1.1351 +    anInfo.iNotLockedTimeOut=0;  // Not enabled
  1.1352 +	anInfo.iInactivityTimeOut=5; // 5 Seconds
  1.1353 +    }