os/kernelhwsrv/kernel/eka/drivers/medmmc/medmmc.cpp
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
sl@0
     1
// Copyright (c) 1999-2009 Nokia Corporation and/or its subsidiary(-ies).
sl@0
     2
// All rights reserved.
sl@0
     3
// This component and the accompanying materials are made available
sl@0
     4
// under the terms of the License "Eclipse Public License v1.0"
sl@0
     5
// which accompanies this distribution, and is available
sl@0
     6
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
sl@0
     7
//
sl@0
     8
// Initial Contributors:
sl@0
     9
// Nokia Corporation - initial contribution.
sl@0
    10
//
sl@0
    11
// Contributors:
sl@0
    12
//
sl@0
    13
// Description:
sl@0
    14
// Media driver for MultiMediaCard Flash device
sl@0
    15
// 
sl@0
    16
//
sl@0
    17
sl@0
    18
#include "mmc.h" 
sl@0
    19
#include "pbusmedia.h"
sl@0
    20
#include <drivers/emmcptn.h>
sl@0
    21
sl@0
    22
#include "OstTraceDefinitions.h"
sl@0
    23
#ifdef OST_TRACE_COMPILER_IN_USE
sl@0
    24
#include "locmedia_ost.h"
sl@0
    25
#ifdef __VC32__
sl@0
    26
#pragma warning(disable: 4127) // disabling warning "conditional expression is constant"
sl@0
    27
#endif
sl@0
    28
#include "medmmcTraces.h"
sl@0
    29
#endif
sl@0
    30
sl@0
    31
#if defined(__DEMAND_PAGING__)
sl@0
    32
	// If in debug mode, enable paging stats and their retrieval using DLocalDrive::EControlIO
sl@0
    33
	#if defined( _DEBUG)
sl@0
    34
		#define __TEST_PAGING_MEDIA_DRIVER__
sl@0
    35
	#endif
sl@0
    36
	#include "mmcdp.h"
sl@0
    37
#endif
sl@0
    38
sl@0
    39
#ifndef BTRACE_PAGING_MEDIA
sl@0
    40
	#undef BTraceContext8
sl@0
    41
	#define BTraceContext8(aCategory,aSubCategory,a1,a2) 
sl@0
    42
#endif	// BTRACE_PAGING_MEDIA
sl@0
    43
sl@0
    44
// Enable this macro to debug cache: 
sl@0
    45
// NB The greater the number of blocks, the slower this is...
sl@0
    46
//#define _DEBUG_CACHE
sl@0
    47
#ifdef _DEBUG_CACHE
sl@0
    48
#define __ASSERT_CACHE(c,p) (void)((c)||(p,0))
sl@0
    49
#else
sl@0
    50
#define __ASSERT_CACHE(c,p)
sl@0
    51
#endif
sl@0
    52
sl@0
    53
sl@0
    54
GLREF_C TInt GetMediaDefaultPartitionInfo(TMBRPartitionEntry& aPartitionEntry, TUint16& aReservedSectors, const TMMCard* aCardP);
sl@0
    55
GLREF_C TBool MBRMandatory(const TMMCard* aCardP);
sl@0
    56
GLREF_C TBool CreateMBRAfterFormat(const TMMCard* aCardP);
sl@0
    57
GLREF_C TInt BlockSize(const TMMCard* aCardP);
sl@0
    58
GLREF_C TInt EraseBlockSize(const TMMCard* aCardP);
sl@0
    59
GLREF_C TInt GetCardFormatInfo(const TMMCard* aCardP, TLDFormatInfo& aFormatInfo);
sl@0
    60
sl@0
    61
const TInt KStackNumber = 0;
sl@0
    62
sl@0
    63
const TInt KDiskSectorSize=512;
sl@0
    64
const TInt KDiskSectorShift=9;
sl@0
    65
sl@0
    66
const TInt KIdleCurrentInMilliAmps = 1;
sl@0
    67
sl@0
    68
const TInt KMBRFirstPartitionEntry=0x1BE;
sl@0
    69
sl@0
    70
template <class T>
sl@0
    71
inline T UMin(T aLeft,T aRight)
sl@0
    72
	{return(aLeft<aRight ? aLeft : aRight);}
sl@0
    73
sl@0
    74
sl@0
    75
class DPhysicalDeviceMediaMmcFlash : public DPhysicalDevice
sl@0
    76
	{
sl@0
    77
public:
sl@0
    78
	DPhysicalDeviceMediaMmcFlash();
sl@0
    79
sl@0
    80
	virtual TInt Install();
sl@0
    81
	virtual void GetCaps(TDes8& aDes) const;
sl@0
    82
	virtual TInt Create(DBase*& aChannel, TInt aMediaId, const TDesC8* aInfo, const TVersion& aVer);
sl@0
    83
	virtual TInt Validate(TInt aDeviceType, const TDesC8* aInfo, const TVersion& aVer);
sl@0
    84
	virtual TInt Info(TInt aFunction, TAny* a1);
sl@0
    85
	};
sl@0
    86
sl@0
    87
sl@0
    88
// these should be static const members of DMmcMediaDriverFlash, but VC doesn't support this
sl@0
    89
const TInt64 KInvalidBlock = -1;
sl@0
    90
const TInt KNoCacheBlock = -1;
sl@0
    91
sl@0
    92
class DMmcMediaDriverFlash : public DMediaDriver
sl@0
    93
	{
sl@0
    94
public:
sl@0
    95
	DMmcMediaDriverFlash(TInt aMediaId);
sl@0
    96
	~DMmcMediaDriverFlash();
sl@0
    97
	// ...from DMediaDriver
sl@0
    98
	virtual void Close();
sl@0
    99
	// replacing pure virtual
sl@0
   100
	virtual void Disconnect(DLocalDrive* aLocalDrive, TThreadMessage*);
sl@0
   101
	virtual TInt Request(TLocDrvRequest& aRequest);
sl@0
   102
	virtual TInt PartitionInfo(TPartitionInfo& anInfo);
sl@0
   103
	virtual void NotifyPowerDown();
sl@0
   104
	virtual void NotifyEmergencyPowerDown();
sl@0
   105
	// For creation by DPhysicalDeviceMediaMmcFlash
sl@0
   106
	TInt DoCreate(TInt aMediaId);
sl@0
   107
sl@0
   108
private:
sl@0
   109
	enum TPanic
sl@0
   110
		{
sl@0
   111
		EDRInUse		= 0x0000,	EDRStart, EDRNotPositive, EDREnd,
sl@0
   112
		ELRRequest		= 0x0010,	ELRStart, ELRNotPositive, ELREnd, ELRCached,
sl@0
   113
		EDWInUse		= 0x0020,	EDWStart, EDWNotPositive, EDWEnd,
sl@0
   114
		EDFInUse		= 0x0030,	EDFStart, EDFNotPositive, EDFEnd, ENotMmcSocket,
sl@0
   115
		ELWRequest		= 0x0040,	ELWStart, ELWFmtStAlign, ELWNotPositive, ELWEnd, ELWFmtEndAlign, 
sl@0
   116
									ELWLength, ELFStart, ELFEnd, ELFNotPositive,
sl@0
   117
		ERPIInUse		= 0x0050,
sl@0
   118
		EPCInUse		= 0x0060,	EPCFunc,
sl@0
   119
		ESECBQueued		= 0x0070,
sl@0
   120
		EDSEDRequest	= 0x0080,	EDSEDNotErrComplete,
sl@0
   121
		ECRReqIdle		= 0x0090,	ECRRequest,
sl@0
   122
		ERRBStAlign		= 0x00a0,	ERRBStPos, ERRBNotPositive, ERRBEndAlign, ERRBEndPos,
sl@0
   123
									ERRBOverflow, ERRBCchInv, ERRBExist,
sl@0
   124
		ERWBStPos		= 0x00b0,	ERWBNotPositive, ERWBEndPos, ERWBOverflow, ERWBCchInv,
sl@0
   125
		EMBStPos		= 0x00c0,	EMBStAlign, EMBNotPositive, EMBEndPos, EMBEndAlign,
sl@0
   126
									EMBOverflow, EMBCchInvPre, EMBCchInvPost,
sl@0
   127
		EBGAStPos		= 0x00d0,	EBGAStAlign, EBGANotPositive, EBGAEndPos, EBGAEndAlign,
sl@0
   128
									EBGAOverflow, EBGACchInv,
sl@0
   129
		EICMNegative	= 0x00e0,	EICMOverflow, ECMIOverflow,
sl@0
   130
		EGCBAlign		= 0x00f0,	EGCBPos, EGCBCchInv,
sl@0
   131
		
sl@0
   132
		ECFSessPtrNull	= 0x0100,	// Code Fault - session pointer NULL
sl@0
   133
sl@0
   134
		EDBNotEven		= 0x0110,	// Not and even number of blocks in the buffer cache
sl@0
   135
		EDBCBQueued		= 0x0111,	// The data transfer callback is already queued
sl@0
   136
		EDBLength		= 0x0112,	// The length of data to transfer in data transfer callback is not positive
sl@0
   137
		EDBLengthTooBig	= 0x0113,	// The length of data to transfer in data transfer callback is too big
sl@0
   138
		EDBOffsetTooBig = 0x0114,	// The Offset into the user data buffer is too big
sl@0
   139
		EDBCacheInvalid	= 0x0115,	// The cache is invalid at the end of data transfer
sl@0
   140
		EDBNotOptimal	= 0x0116,	// Due to Cache size DB functionality will never be utilised
sl@0
   141
		ENoDBSupport	= 0x0120,	// DMA request arrived but PSL does not support double buffering
sl@0
   142
		ENotDMAAligned  = 0x0121,
sl@0
   143
		};
sl@0
   144
	static void Panic(TPanic aPnc);
sl@0
   145
sl@0
   146
	enum TMediaRequest
sl@0
   147
		{
sl@0
   148
		EMReqRead = 0,
sl@0
   149
		EMReqWrite = 1,
sl@0
   150
		EMReqFormat = 2,
sl@0
   151
		EMReqPtnInfo,
sl@0
   152
		EMReqPswdCtrl,
sl@0
   153
		EMReqForceErase,
sl@0
   154
		EMReqUpdatePtnInfo,
sl@0
   155
		EMReqWritePasswordData,
sl@0
   156
		EMReqIdle,
sl@0
   157
		EMReqEMMCPtnInfo,
sl@0
   158
		};
sl@0
   159
	enum TMediaReqType {EMReqTypeNormalRd,EMReqTypeNormalWr,EMReqTypeUnlockPswd,EMReqTypeChangePswd};
sl@0
   160
sl@0
   161
	enum {KWtRBMFst = 0x00000001, 	// iWtRBM - Read First Block only
sl@0
   162
		  KWtRBMLst = 0x00000002,	// iWtRBM - Read Last Block only
sl@0
   163
		  KWtMinFst = 0x00000004,	// iWtRBM - Write First Block only
sl@0
   164
		  KWtMinLst = 0x00000008,	// iWtRBM - Write Last Block only
sl@0
   165
		  KIPCSetup = 0x00000010,	// iRdROB - IPC Setup Next Iteration
sl@0
   166
		  KIPCWrite = 0x00000020};	// iRdROB - IPC Write Next Iteration
sl@0
   167
sl@0
   168
private:
sl@0
   169
	// MMC device specific stuff
sl@0
   170
	TInt DoRead();
sl@0
   171
	TInt DoWrite();
sl@0
   172
	TInt DoFormat();
sl@0
   173
	TInt Caps(TLocDrv& aDrive, TLocalDriveCapsV6& aInfo);
sl@0
   174
sl@0
   175
	inline DMMCStack& Stack() const;
sl@0
   176
	inline TInt CardNum() const;
sl@0
   177
	inline TMediaRequest CurrentRequest() const;
sl@0
   178
sl@0
   179
	TInt LaunchRead(TInt64 aStart, TUint32 aLength);
sl@0
   180
	TInt LaunchDBRead();
sl@0
   181
	TInt LaunchPhysRead(TInt64 aStart, TUint32 aLength);
sl@0
   182
	
sl@0
   183
	TInt LaunchWrite(TInt64 aStart, TUint32 aLength, TMediaRequest aMedReq);
sl@0
   184
	TInt LaunchFormat(TInt64 aStart, TUint32 aLength);
sl@0
   185
sl@0
   186
	TInt LaunchRPIUnlock(TLocalDrivePasswordData& aData);
sl@0
   187
	TInt LaunchRPIRead();
sl@0
   188
	TInt LaunchRPIErase();
sl@0
   189
	TInt DecodePartitionInfo();
sl@0
   190
	TInt WritePartitionInfo();
sl@0
   191
	TInt GetDefaultPartitionInfo(TMBRPartitionEntry& aPartitionEntry);
sl@0
   192
	TInt CreateDefaultPartition();
sl@0
   193
sl@0
   194
sl@0
   195
#if defined __TEST_PAGING_MEDIA_DRIVER__
sl@0
   196
	TInt HandleControlIORequest();
sl@0
   197
#endif
sl@0
   198
sl@0
   199
	static void SetPartitionEntry(TPartitionEntry* aEntry, TUint aFirstSector, TUint aNumSectors);
sl@0
   200
sl@0
   201
	TInt CheckDevice(TMediaReqType aReqType);
sl@0
   202
sl@0
   203
	static void SessionEndCallBack(TAny* aMediaDriver);
sl@0
   204
	static void SessionEndDfc(TAny* aMediaDriver);
sl@0
   205
	void DoSessionEndDfc();
sl@0
   206
sl@0
   207
	static void DataTransferCallBack(TAny* aMediaDriver);
sl@0
   208
	static void DataTransferCallBackDfc(TAny* aMediaDriver);
sl@0
   209
sl@0
   210
	void DoReadDataTransferCallBack();
sl@0
   211
	void DoWriteDataTransferCallBack();
sl@0
   212
	void DoPhysReadDataTransferCallBack();
sl@0
   213
	void DoPhysWriteDataTransferCallBack();
sl@0
   214
	
sl@0
   215
	TInt AdjustPhysicalFragment(TPhysAddr &physAddr, TInt &physLength);
sl@0
   216
	TInt PrepareFirstPhysicalFragment(TPhysAddr &aPhysAddr, TInt &aPhysLength, TUint32 aLength);
sl@0
   217
	void PrepareNextPhysicalFragment();
sl@0
   218
sl@0
   219
	TInt EngageAndSetReadRequest(TMediaRequest aRequest);
sl@0
   220
	TInt EngageAndSetWriteRequest(TMediaRequest aRequest);
sl@0
   221
	TInt EngageAndSetRequest(TMediaRequest aRequest, TInt aCurrent);
sl@0
   222
	void CompleteRequest(TInt aReason);
sl@0
   223
sl@0
   224
	TInt ReadDataUntilCacheExhausted(TBool* aAllDone);
sl@0
   225
	TInt WriteDataToUser(TUint8* aBufPtr);
sl@0
   226
	TInt ReadDataFromUser(TDes8& aDes, TInt aOffset);
sl@0
   227
	TUint8* ReserveReadBlocks(TInt64 aStart, TInt64 aEnd, TUint32* aLength);
sl@0
   228
	TUint8* ReserveWriteBlocks(TInt64 aMedStart, TInt64 aMedEnd, TUint* aRBM);
sl@0
   229
	void MarkBlocks(TInt64 aStart, TInt64 aEnd, TInt aStartIndex);
sl@0
   230
	void BuildGammaArray(TInt64 aStart, TInt64 aEnd);
sl@0
   231
	void InvalidateCache();
sl@0
   232
	void InvalidateCache(TInt64 aStart, TInt64 aEnd);
sl@0
   233
	TUint8* IdxToCchMem(TInt aIdx) const;
sl@0
   234
	TInt CchMemToIdx(TUint8* aMemP) const;
sl@0
   235
sl@0
   236
	TInt DoPasswordOp();
sl@0
   237
	void PasswordControl(TInt aFunc, TLocalDrivePasswordData& aData);
sl@0
   238
	void Reset();
sl@0
   239
	TInt AllocateSession();  
sl@0
   240
sl@0
   241
#ifdef _DEBUG_CACHE
sl@0
   242
	TBool CacheInvariant();
sl@0
   243
	TUint8* GetCachedBlock(TInt64 aAddr);
sl@0
   244
#endif
sl@0
   245
private:
sl@0
   246
	DMMCStack* iStack;			 				// controller objects
sl@0
   247
	TMMCard* iCard;
sl@0
   248
	DMMCSession* iSession;
sl@0
   249
	DMMCSocket* iSocket;
sl@0
   250
sl@0
   251
	TInt iCardNumber;
sl@0
   252
sl@0
   253
	TUint iBlkLenLog2;							// cached CSD data
sl@0
   254
	TUint32 iBlkLen;
sl@0
   255
	TInt64 iBlkMsk;
sl@0
   256
	TBool iReadBlPartial;
sl@0
   257
	TUint32 iPrWtGpLen;							// preferred write group size in bytes,
sl@0
   258
	TInt64 iPrWtGpMsk;
sl@0
   259
sl@0
   260
	TInt iReadCurrentInMilliAmps;				// power management
sl@0
   261
	TInt iWriteCurrentInMilliAmps;
sl@0
   262
sl@0
   263
	TUint8* iMinorBuf;							// MBR, CMD42, partial read
sl@0
   264
	TUint8* iCacheBuf;							// cached buffer
sl@0
   265
	TUint32 iMaxBufSize;
sl@0
   266
	TInt iBlocksInBuffer;
sl@0
   267
	TInt64* iCachedBlocks;
sl@0
   268
	TInt* iGamma;								// B lookup, ReserveReadBlocks()
sl@0
   269
	TUint8* iIntBuf;							// start of current buffer region
sl@0
   270
	TInt iLstUsdCchEnt;							// index of last used cache entry
sl@0
   271
sl@0
   272
	TLocDrvRequest* iCurrentReq;				// Current Request
sl@0
   273
	TMediaRequest iMedReq;
sl@0
   274
	
sl@0
   275
	TInt64 iReqStart;							// user-requested start region
sl@0
   276
	TInt64 iReqCur;								// Currently requested start region
sl@0
   277
	TInt64 iReqEnd;							    // user-requested end region
sl@0
   278
	TInt64 iPhysStart;							// physical region for one operation
sl@0
   279
	TInt64 iPhysEnd;						    // physical end point for one operation
sl@0
   280
	TInt64 iDbEnd;								// Double buffer end point for one operation
sl@0
   281
sl@0
   282
	TUint64 iEraseUnitMsk;
sl@0
   283
sl@0
   284
	TUint iWtRBM;								// Write - Read Before Modify Flags
sl@0
   285
	TUint iRdROB;								// Read  - Read Odd Blocks Flags
sl@0
   286
	
sl@0
   287
	TInt iFragOfset;			
sl@0
   288
	TUint32 iIPCLen;
sl@0
   289
	TUint32 iNxtIPCLen;
sl@0
   290
	TUint32 iBufOfset;
sl@0
   291
	
sl@0
   292
	TUint iHiddenSectors;						// bootup / password
sl@0
   293
sl@0
   294
	TMMCCallBack iSessionEndCallBack;
sl@0
   295
	TDfc iSessionEndDfc;
sl@0
   296
sl@0
   297
	TPartitionInfo* iPartitionInfo;
sl@0
   298
	TMMCMediaTypeEnum iMediaType;
sl@0
   299
	TMMCEraseInfo iEraseInfo;
sl@0
   300
	TBool iMbrMissing;
sl@0
   301
	TInt iMediaId;
sl@0
   302
sl@0
   303
	DMMCStack::TDemandPagingInfo iDemandPagingInfo;
sl@0
   304
sl@0
   305
#if defined(__TEST_PAGING_MEDIA_DRIVER__)
sl@0
   306
	SMmcStats iMmcStats;
sl@0
   307
#endif // __TEST_PAGING_MEDIA_DRIVER__
sl@0
   308
sl@0
   309
	TMMCCallBack iDataTransferCallBack;	// Callback registered with the MMC stack to perform double-buffering
sl@0
   310
	TDfc iDataTransferCallBackDfc;		// ...and the associated DFC queue.
sl@0
   311
sl@0
   312
	TBool iSecondBuffer;				// Specified the currently active buffer
sl@0
   313
	TBool iDoLastRMW;					// ETrue if the last double-buffer transfer requires RMW modification
sl@0
   314
	TBool iDoDoubleBuffer;				// ETrue if double-buffering is currently active
sl@0
   315
	TBool iDoPhysicalAddress;			// ETrue if Physical Addressing is currently active
sl@0
   316
	TBool iCreateMbr;
sl@0
   317
	TBool iReadToEndOfCard;				// {Read Only} ETrue if Reading to end of Card
sl@0
   318
sl@0
   319
	TBool iInternalSlot;
sl@0
   320
sl@0
   321
	DEMMCPartitionInfo* iMmcPartitionInfo;  // Responsible for decoding partitions for embedded devices
sl@0
   322
	};
sl@0
   323
	
sl@0
   324
// ======== DPhysicalDeviceMediaMmcFlash ========
sl@0
   325
sl@0
   326
sl@0
   327
DPhysicalDeviceMediaMmcFlash::DPhysicalDeviceMediaMmcFlash()
sl@0
   328
	{
sl@0
   329
	OstTraceFunctionEntry1( DPHYSICALDEVICEMEDIAMMCFLASH_DPHYSICALDEVICEMEDIAMMCFLASH_ENTRY, this );
sl@0
   330
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:ctr"));
sl@0
   331
sl@0
   332
	iUnitsMask = 0x01;
sl@0
   333
	iVersion = TVersion(KMediaDriverInterfaceMajorVersion,KMediaDriverInterfaceMinorVersion,KMediaDriverInterfaceBuildVersion);
sl@0
   334
	OstTraceFunctionExit1( DPHYSICALDEVICEMEDIAMMCFLASH_DPHYSICALDEVICEMEDIAMMCFLASH_EXIT, this );
sl@0
   335
	}
sl@0
   336
sl@0
   337
sl@0
   338
TInt DPhysicalDeviceMediaMmcFlash::Install()
sl@0
   339
	{
sl@0
   340
	OstTraceFunctionEntry1( DPHYSICALDEVICEMEDIAMMCFLASH_INSTALL_ENTRY, this );
sl@0
   341
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:ins"));
sl@0
   342
sl@0
   343
	_LIT(KDrvNm, "Media.MmcF");
sl@0
   344
	TInt r = SetName(&KDrvNm);
sl@0
   345
	OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_INSTALL_EXIT, this, r );
sl@0
   346
	return r;
sl@0
   347
	}
sl@0
   348
sl@0
   349
sl@0
   350
void DPhysicalDeviceMediaMmcFlash::GetCaps(TDes8& /* aDes */) const
sl@0
   351
	{
sl@0
   352
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:cap"));
sl@0
   353
	}
sl@0
   354
								 
sl@0
   355
									 
sl@0
   356
TInt DPhysicalDeviceMediaMmcFlash::Info(TInt aFunction, TAny* /*a1*/)
sl@0
   357
//
sl@0
   358
// Return the priority of this media driver
sl@0
   359
//
sl@0
   360
	{
sl@0
   361
	OstTraceExt2(TRACE_FLOW, DPHYSICALDEVICEMEDIAMMCFLASH_INFO_ENTRY ,"DPhysicalDeviceMediaMmcFlash::Info;aFunction=%d;this=%x", aFunction, (TUint) this);
sl@0
   362
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:info"));
sl@0
   363
	if (aFunction==EPriority)
sl@0
   364
	    {
sl@0
   365
		OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_INFO_EXIT1, this, KMediaDriverPriorityNormal );
sl@0
   366
		return KMediaDriverPriorityNormal;
sl@0
   367
	    }
sl@0
   368
	// Don't close media driver when peripheral bus powers down. This avoids the need for Caps() to power up the stack.
sl@0
   369
	if (aFunction==EMediaDriverPersistent)
sl@0
   370
	    {
sl@0
   371
		OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_INFO_EXIT2, this, KErrNone );
sl@0
   372
		return KErrNone;
sl@0
   373
	    }
sl@0
   374
	
sl@0
   375
	OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_INFO_EXIT3, this, KErrNotSupported );
sl@0
   376
	return KErrNotSupported;
sl@0
   377
	}
sl@0
   378
								 
sl@0
   379
TInt DPhysicalDeviceMediaMmcFlash::Validate(TInt aDeviceType, const TDesC8* /*aInfo*/, const TVersion& aVer)
sl@0
   380
	{
sl@0
   381
	OstTraceExt2(TRACE_FLOW, DPHYSICALDEVICEMEDIAMMCFLASH_VALIDATE_ENTRY ,"DPhysicalDeviceMediaMmcFlash::Validate;aDeviceType=%d;this=%x", aDeviceType, (TUint) this);
sl@0
   382
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:validate aDeviceType %d", aDeviceType));
sl@0
   383
	if (!Kern::QueryVersionSupported(iVersion,aVer))
sl@0
   384
	    {
sl@0
   385
		OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_VALIDATE_EXIT1, this, KErrNotSupported );
sl@0
   386
		return KErrNotSupported;
sl@0
   387
	    }
sl@0
   388
	if (aDeviceType!=MEDIA_DEVICE_MMC)
sl@0
   389
	    {
sl@0
   390
		OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_VALIDATE_EXIT2, this, KErrNotSupported );
sl@0
   391
		return KErrNotSupported;
sl@0
   392
	    }
sl@0
   393
sl@0
   394
	OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_VALIDATE_EXIT3, this, KErrNone );
sl@0
   395
	return KErrNone;
sl@0
   396
	}
sl@0
   397
								 
sl@0
   398
TInt DPhysicalDeviceMediaMmcFlash::Create(DBase*& aChannel, TInt aMediaId, const TDesC8* /*aInfo*/, const TVersion& aVer)
sl@0
   399
//
sl@0
   400
// Create an MMC Card media driver.
sl@0
   401
//
sl@0
   402
	{
sl@0
   403
	OstTraceExt2(TRACE_FLOW, DPHYSICALDEVICEMEDIAMMCFLASH_CREATE_ENTRY, "DPhysicalDeviceMediaMmcFlash::Create;aMediaId=%d;this=%x", aMediaId, (TUint) this);
sl@0
   404
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:crt"));
sl@0
   405
sl@0
   406
	if (!Kern::QueryVersionSupported(iVersion,aVer))
sl@0
   407
	    {
sl@0
   408
		OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_CREATE_EXIT1, this, KErrNotSupported );
sl@0
   409
		return KErrNotSupported;
sl@0
   410
	    }
sl@0
   411
sl@0
   412
	DMmcMediaDriverFlash* pD = new DMmcMediaDriverFlash(aMediaId);
sl@0
   413
	aChannel=pD;
sl@0
   414
sl@0
   415
	TInt r=KErrNoMemory;
sl@0
   416
	if (pD)
sl@0
   417
		r=pD->DoCreate(aMediaId);
sl@0
   418
	if (r==KErrNone)
sl@0
   419
		pD->OpenMediaDriverComplete(KErrNone);
sl@0
   420
sl@0
   421
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:mdf"));
sl@0
   422
sl@0
   423
	OstTraceFunctionExitExt( DPHYSICALDEVICEMEDIAMMCFLASH_CREATE_EXIT2, this, r );
sl@0
   424
	return r;
sl@0
   425
	}
sl@0
   426
sl@0
   427
sl@0
   428
// ======== DMmcMediaDriverFlash ========
sl@0
   429
sl@0
   430
sl@0
   431
void DMmcMediaDriverFlash::Panic(TPanic aPanic)
sl@0
   432
	{
sl@0
   433
	_LIT(KPncNm, "MEDMMC");
sl@0
   434
	Kern::PanicCurrentThread(KPncNm, aPanic);
sl@0
   435
	}
sl@0
   436
sl@0
   437
sl@0
   438
// ---- accessor functions -----
sl@0
   439
sl@0
   440
inline DMMCStack& DMmcMediaDriverFlash::Stack() const
sl@0
   441
	{ return *static_cast<DMMCStack*>(iStack); }
sl@0
   442
sl@0
   443
sl@0
   444
inline TInt DMmcMediaDriverFlash::CardNum() const
sl@0
   445
	{ return iCardNumber; }
sl@0
   446
sl@0
   447
sl@0
   448
inline DMmcMediaDriverFlash::TMediaRequest DMmcMediaDriverFlash::CurrentRequest() const
sl@0
   449
	{ return iMedReq; }
sl@0
   450
sl@0
   451
sl@0
   452
// Helper
sl@0
   453
template <class T>
sl@0
   454
inline T* KernAlloc(const TUint32 n)
sl@0
   455
	{ return static_cast<T*>(Kern::Alloc(n * sizeof(T))); }
sl@0
   456
sl@0
   457
// ---- ctor, open, close, dtor ----
sl@0
   458
sl@0
   459
#pragma warning( disable : 4355 )	// this used in initializer list
sl@0
   460
DMmcMediaDriverFlash::DMmcMediaDriverFlash(TInt aMediaId)
sl@0
   461
   :DMediaDriver(aMediaId),
sl@0
   462
	iMedReq(EMReqIdle),
sl@0
   463
    iSessionEndCallBack(DMmcMediaDriverFlash::SessionEndCallBack, this),
sl@0
   464
	iSessionEndDfc(DMmcMediaDriverFlash::SessionEndDfc, this, 1),
sl@0
   465
	iMediaId(iPrimaryMedia->iNextMediaId),
sl@0
   466
    iDataTransferCallBack(DMmcMediaDriverFlash::DataTransferCallBack, this),
sl@0
   467
	iDataTransferCallBackDfc(DMmcMediaDriverFlash::DataTransferCallBackDfc, this, 1)
sl@0
   468
	{
sl@0
   469
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:mmd"));
sl@0
   470
	// NB aMedia Id = the media ID of the primary media, iMediaId = the media ID of this media
sl@0
   471
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("DMmcMediaDriverFlash(), iMediaId %d, aMediaId %d\n", iMediaId, aMediaId));
sl@0
   472
	OstTraceExt2( TRACE_FLOW, DMMCMEDIADRIVERFLASH_DMMCMEDIADRIVERFLASH, "> DMmcMediaDriverFlash::DMmcMediaDriverFlash;aMediaId=%d;iMediaId=%d", (TInt) aMediaId, (TInt) iMediaId );
sl@0
   473
	
sl@0
   474
	}
sl@0
   475
sl@0
   476
#pragma warning( default : 4355 )
sl@0
   477
TInt DMmcMediaDriverFlash::DoCreate(TInt /*aMediaId*/)
sl@0
   478
	{
sl@0
   479
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOCREATE_ENTRY, this );
sl@0
   480
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:opn"));
sl@0
   481
sl@0
   482
	iSocket = ((DMMCSocket*)((DPBusPrimaryMedia*)iPrimaryMedia)->iSocket);
sl@0
   483
	if(iSocket == NULL)
sl@0
   484
	    {
sl@0
   485
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT1, this, KErrNoMemory );
sl@0
   486
		return KErrNoMemory;
sl@0
   487
	    }
sl@0
   488
sl@0
   489
	iCardNumber = ((DPBusPrimaryMedia*)iPrimaryMedia)->iSlotNumber;
sl@0
   490
sl@0
   491
	iStack = iSocket->Stack(KStackNumber);
sl@0
   492
	iCard = iStack->CardP(CardNum());
sl@0
   493
sl@0
   494
	TMMCMachineInfo machineInfo;
sl@0
   495
	Stack().MachineInfo(machineInfo);
sl@0
   496
	TInt slotFlag = iCardNumber == 0 ? TMMCMachineInfo::ESlot1Internal : TMMCMachineInfo::ESlot2Internal;
sl@0
   497
	iInternalSlot = machineInfo.iFlags & slotFlag;
sl@0
   498
sl@0
   499
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("DMmcMediaDriverFlash::DoCreate() slotNumber %d iInternalSlot %d", iCardNumber, iInternalSlot));
sl@0
   500
	OstTraceExt2(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_SLOT, "slotNumber=%d; iInternalSlot=%d", iCardNumber, iInternalSlot);
sl@0
   501
sl@0
   502
	iSessionEndDfc.SetDfcQ(&iSocket->iDfcQ);
sl@0
   503
	iDataTransferCallBackDfc.SetDfcQ(&iSocket->iDfcQ);
sl@0
   504
sl@0
   505
	// check right type of card
sl@0
   506
	if ((iMediaType=iCard->MediaType())==EMultiMediaNotSupported)	
sl@0
   507
	    {
sl@0
   508
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT2, this, KErrNotReady );
sl@0
   509
		return KErrNotReady;
sl@0
   510
	    }
sl@0
   511
sl@0
   512
	// get card characteristics
sl@0
   513
	const TCSD& csd = iCard->CSD();
sl@0
   514
	iBlkLenLog2 = iCard->MaxReadBlLen();
sl@0
   515
	iBlkLen = 1 << iBlkLenLog2;
sl@0
   516
	iBlkMsk = (TInt64)(iBlkLen - 1);
sl@0
   517
sl@0
   518
	SetTotalSizeInBytes(iCard->DeviceSize64());
sl@0
   519
	
sl@0
   520
	//
sl@0
   521
	// High capcity cards (block addressable, MMCV4.2, SD2.0) do not support partial reads
sl@0
   522
	// ...some cards incorrectly report that they do, so ensure that we don't
sl@0
   523
	//
sl@0
   524
	iReadBlPartial = iCard->IsHighCapacity() ? EFalse : csd.ReadBlPartial();
sl@0
   525
sl@0
   526
	// allocate and initialize session object
sl@0
   527
	TInt r = AllocateSession();
sl@0
   528
	if (r!= KErrNone)
sl@0
   529
	    {
sl@0
   530
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT3, this, r );
sl@0
   531
		return r;
sl@0
   532
	    }
sl@0
   533
sl@0
   534
	// get buffer memory from EPBUS
sl@0
   535
	TUint8* buf;
sl@0
   536
	TInt bufLen;
sl@0
   537
	TInt minorBufLen;
sl@0
   538
	Stack().BufferInfo(buf, bufLen, minorBufLen);
sl@0
   539
sl@0
   540
	iMinorBuf = buf;
sl@0
   541
	
sl@0
   542
	// cache buffer can use rest of blocks in buffer.  Does not have to be power of 2.
sl@0
   543
	iCacheBuf = iMinorBuf + minorBufLen;
sl@0
   544
sl@0
   545
	// We need to devide up the buffer space between the media drivers.
sl@0
   546
	// The number of buffer sub-areas = number of physical card slots * number of media
sl@0
   547
	bufLen-= minorBufLen;
sl@0
   548
	DPBusPrimaryMedia* primaryMedia = (DPBusPrimaryMedia*) iPrimaryMedia;
sl@0
   549
	TInt physicalCardSlots = iStack->iMaxCardsInStack;
sl@0
   550
	TInt numMedia = primaryMedia->iLastMediaId - primaryMedia->iMediaId + 1;
sl@0
   551
	TInt totalNumMedia = numMedia * physicalCardSlots;
sl@0
   552
sl@0
   553
	TInt mediaIndex = iMediaId - primaryMedia->iMediaId;
sl@0
   554
	TInt bufIndex = (iCardNumber * numMedia)  + mediaIndex;
sl@0
   555
	
sl@0
   556
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("physicalCardSlots %d, iCardNumber %d\n",  physicalCardSlots, iCardNumber));
sl@0
   557
	OstTraceExt2(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_VARS1, "physicalCardSlots=%d; iCardNumber=%d", physicalCardSlots, iCardNumber);
sl@0
   558
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("iMediaId %d numMedia %d, mediaIndex %d, totalNumMedia %d, bufIndex %d\n", 
sl@0
   559
			  iMediaId, numMedia, mediaIndex, totalNumMedia, bufIndex));
sl@0
   560
	OstTraceExt5(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_VARS2, "iMediaId=%d; numMedia=%d; mediaIndex=%d; totalNumMedia=%d; bufIndex=%d", iMediaId, numMedia, mediaIndex, totalNumMedia, bufIndex);
sl@0
   561
sl@0
   562
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("bufLen1 %08X iCacheBuf1 %08X", bufLen, iCacheBuf));
sl@0
   563
	OstTraceExt2(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_CACHEBUF1, "bufLen1=0x%08x; iCacheBuf1=0x%08x", (TUint) bufLen, (TUint) iCacheBuf);
sl@0
   564
	bufLen/= totalNumMedia;
sl@0
   565
	iCacheBuf+= bufIndex * bufLen;
sl@0
   566
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("bufLen2 %08X iCacheBuf2 %08X", bufLen, iCacheBuf));
sl@0
   567
	OstTraceExt2(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_CACHEBUF2, "bufLen2=0x%08x; iCacheBuf2=0x%08x", (TUint) bufLen, (TUint) iCacheBuf);
sl@0
   568
sl@0
   569
	iBlocksInBuffer = bufLen >> iBlkLenLog2;	// may lose partial block
sl@0
   570
	if(iSocket->SupportsDoubleBuffering())
sl@0
   571
		{
sl@0
   572
		// Ensure that there's always an even number of buffered blocks when double-buffering
sl@0
   573
		iBlocksInBuffer &= ~1;
sl@0
   574
		__ASSERT_DEBUG(iBlocksInBuffer >= 2, Panic(EDBNotEven));
sl@0
   575
#if defined(_DEBUG)		
sl@0
   576
		/** 
sl@0
   577
		 * If Double-Buffering is enabled then the cache should not be greater than the maximum addressable range of the DMA controller,
sl@0
   578
		 * otherwise Double buffering will never be utilised because all transfers will fit into the cache.
sl@0
   579
		 */
sl@0
   580
		const TUint32 maxDbBlocks = iSocket->MaxDataTransferLength() >> iBlkLenLog2;
sl@0
   581
        if (maxDbBlocks)
sl@0
   582
            {
sl@0
   583
            __ASSERT_DEBUG(iBlocksInBuffer <= (TInt)maxDbBlocks, Panic(EDBNotOptimal));
sl@0
   584
            }
sl@0
   585
#endif		
sl@0
   586
		}
sl@0
   587
sl@0
   588
	iMaxBufSize = iBlocksInBuffer << iBlkLenLog2;
sl@0
   589
sl@0
   590
	iPrWtGpLen = iCard->PreferredWriteGroupLength();
sl@0
   591
sl@0
   592
	// check the preferred write group length is a power of two
sl@0
   593
	if(iPrWtGpLen == 0 || (iPrWtGpLen & (~iPrWtGpLen + 1)) != iPrWtGpLen)
sl@0
   594
	    {
sl@0
   595
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT4, this, KErrNotReady );
sl@0
   596
		return KErrNotReady;
sl@0
   597
	    }
sl@0
   598
sl@0
   599
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("iMaxBufSize %d iPrWtGpLen %d\n", iMaxBufSize, iPrWtGpLen));
sl@0
   600
	OstTraceExt2(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_IPRWTGPLEN1, "iMaxBufSize=%d; iPrWtGpLen1=%d", iMaxBufSize, iPrWtGpLen);
sl@0
   601
	// ensure the preferred write group length is as large as possible
sl@0
   602
	// so we can write to more than one write group at once
sl@0
   603
	while (iPrWtGpLen < (TUint32) iMaxBufSize)
sl@0
   604
		iPrWtGpLen <<= 1;
sl@0
   605
sl@0
   606
	// ensure preferred write group length is no greater than internal cache buffer
sl@0
   607
	while (iPrWtGpLen > (TUint32) iMaxBufSize)
sl@0
   608
		iPrWtGpLen >>= 1;
sl@0
   609
	iPrWtGpMsk = TInt64(iPrWtGpLen - 1);
sl@0
   610
sl@0
   611
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("iPrWtGpLen #2 %d\n", iPrWtGpLen));
sl@0
   612
	OstTrace1(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOCREATE_IPRWTGPLEN2, "iPrWtGpLen2=%d", iPrWtGpLen);
sl@0
   613
sl@0
   614
	// allocate index for cached blocks
sl@0
   615
	iCachedBlocks =	KernAlloc<TInt64>(iBlocksInBuffer);
sl@0
   616
	if (iCachedBlocks == 0)
sl@0
   617
	    {
sl@0
   618
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT5, this, KErrNoMemory );
sl@0
   619
		return KErrNoMemory;
sl@0
   620
	    }
sl@0
   621
sl@0
   622
	InvalidateCache();
sl@0
   623
	iLstUsdCchEnt = iBlocksInBuffer - 1;		// use entry 0 first
sl@0
   624
sl@0
   625
	// allocate read lookup index
sl@0
   626
	iGamma = KernAlloc<TInt>(iBlocksInBuffer);
sl@0
   627
	if (iGamma == 0)
sl@0
   628
	    {
sl@0
   629
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT6, this, KErrNoMemory );
sl@0
   630
		return KErrNoMemory;
sl@0
   631
	    }
sl@0
   632
sl@0
   633
	// get current requirements
sl@0
   634
	iReadCurrentInMilliAmps = csd.MaxReadCurrentInMilliamps();
sl@0
   635
	iWriteCurrentInMilliAmps = csd.MaxWriteCurrentInMilliamps();
sl@0
   636
sl@0
   637
	// get preferred erase information for format operations
sl@0
   638
	const TInt err = iCard->GetEraseInfo(iEraseInfo);
sl@0
   639
	if(err != KErrNone)
sl@0
   640
	    {
sl@0
   641
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT7, this, err );
sl@0
   642
		return err;
sl@0
   643
	    }
sl@0
   644
sl@0
   645
	iEraseUnitMsk = TInt64(iEraseInfo.iPreferredEraseUnitSize) - 1;
sl@0
   646
sl@0
   647
	// Retrieve the demand paging info from the PSL of the stack
sl@0
   648
	Stack().DemandPagingInfo(iDemandPagingInfo);
sl@0
   649
sl@0
   650
	// if a password has been supplied then it is sent when the partition info is read
sl@0
   651
sl@0
   652
	//
sl@0
   653
	// If this is an internal slot, then use the eMMC partition function
sl@0
   654
	//
sl@0
   655
	if(iInternalSlot)
sl@0
   656
		{
sl@0
   657
		iMmcPartitionInfo = CreateEmmcPartitionInfo();
sl@0
   658
		if(iMmcPartitionInfo == NULL)
sl@0
   659
		    {
sl@0
   660
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT8, this, KErrNoMemory );
sl@0
   661
			return KErrNoMemory;
sl@0
   662
		    }
sl@0
   663
		TInt err = iMmcPartitionInfo->Initialise(this);
sl@0
   664
		if(err != KErrNone)
sl@0
   665
		    {
sl@0
   666
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT9, this, err );
sl@0
   667
			return err;
sl@0
   668
		    }
sl@0
   669
		}
sl@0
   670
sl@0
   671
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:opn"));
sl@0
   672
sl@0
   673
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOCREATE_EXIT10, this, KErrNone );
sl@0
   674
	return KErrNone;
sl@0
   675
	}
sl@0
   676
sl@0
   677
void DMmcMediaDriverFlash::Close()
sl@0
   678
//
sl@0
   679
// Close the media driver - also called on media change
sl@0
   680
//
sl@0
   681
	{
sl@0
   682
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_CLOSE_ENTRY );
sl@0
   683
	__KTRACE_OPT(KPBUSDRV,Kern::Printf("=mmd:cls"));
sl@0
   684
	
sl@0
   685
	EndInCritical();
sl@0
   686
	iSessionEndDfc.Cancel();
sl@0
   687
	iDataTransferCallBackDfc.Cancel();
sl@0
   688
	CompleteRequest(KErrNotReady);
sl@0
   689
	DMediaDriver::Close();
sl@0
   690
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_CLOSE_EXIT );
sl@0
   691
	}
sl@0
   692
sl@0
   693
sl@0
   694
DMmcMediaDriverFlash::~DMmcMediaDriverFlash()
sl@0
   695
	{
sl@0
   696
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_DMMCMEDIADRIVERFLASH_ENTRY );
sl@0
   697
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:dtr"));
sl@0
   698
sl@0
   699
	iSessionEndDfc.Cancel();
sl@0
   700
	iDataTransferCallBackDfc.Cancel();
sl@0
   701
sl@0
   702
	delete iSession;
sl@0
   703
	Kern::Free(iCachedBlocks);
sl@0
   704
	Kern::Free(iGamma);
sl@0
   705
sl@0
   706
	delete iMmcPartitionInfo;
sl@0
   707
sl@0
   708
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:dtr"));
sl@0
   709
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_DMMCMEDIADRIVERFLASH_EXIT );
sl@0
   710
	}
sl@0
   711
sl@0
   712
sl@0
   713
TInt DMmcMediaDriverFlash::AllocateSession()
sl@0
   714
	{
sl@0
   715
OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_ALLOCATESESSION_ENTRY, this );
sl@0
   716
sl@0
   717
	
sl@0
   718
	// already allocated ?
sl@0
   719
	if (iSession != NULL)
sl@0
   720
	    {
sl@0
   721
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ALLOCATESESSION_EXIT1, this, KErrNone );
sl@0
   722
		return KErrNone;
sl@0
   723
	    }
sl@0
   724
sl@0
   725
	iSession = iStack->AllocSession(iSessionEndCallBack);
sl@0
   726
	if (iSession == NULL)
sl@0
   727
	    {
sl@0
   728
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ALLOCATESESSION_EXIT2, this, KErrNoMemory );
sl@0
   729
		return KErrNoMemory;
sl@0
   730
	    }
sl@0
   731
sl@0
   732
	iSession->SetStack(iStack);
sl@0
   733
	iSession->SetCard(iCard);
sl@0
   734
	iSession->SetDataTransferCallback(iDataTransferCallBack);
sl@0
   735
sl@0
   736
sl@0
   737
sl@0
   738
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ALLOCATESESSION_EXIT3, this, KErrNone );
sl@0
   739
	return KErrNone;
sl@0
   740
	}
sl@0
   741
sl@0
   742
// ---- media access ----
sl@0
   743
sl@0
   744
TInt DMmcMediaDriverFlash::DoRead()
sl@0
   745
//
sl@0
   746
// set up iReqStart, iReqEnd and iReqCur and launch first read.  Subsequent reads
sl@0
   747
// will be launched from the callback DFC.
sl@0
   748
//
sl@0
   749
	{
sl@0
   750
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOREAD_ENTRY, this );
sl@0
   751
	TInt r = CheckDevice(EMReqTypeNormalRd); 
sl@0
   752
	if (r != KErrNone)
sl@0
   753
	    {
sl@0
   754
	    OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOREAD_EXIT1, this, r );
sl@0
   755
	    return r;
sl@0
   756
	    }
sl@0
   757
	
sl@0
   758
	const TInt64 pos(iCurrentReq->Pos());
sl@0
   759
	TUint32 length(I64LOW(iCurrentReq->Length()));
sl@0
   760
sl@0
   761
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:dr:0x%lx,0x%x", pos, length));
sl@0
   762
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DO_READ, "Position=0x%lx; Length=0x%x", (TUint) pos, (TUint) length);
sl@0
   763
	__ASSERT_DEBUG(CurrentRequest() == EMReqIdle, Panic(EDRInUse));
sl@0
   764
	__ASSERT_DEBUG(pos < TotalSizeInBytes(), Panic(EDRStart));
sl@0
   765
	__ASSERT_DEBUG(iCurrentReq->Length() >= 0, Panic(EDRNotPositive));
sl@0
   766
	__ASSERT_DEBUG(TotalSizeInBytes() >= pos + length, Panic(EDREnd));
sl@0
   767
sl@0
   768
	if(length > 0)
sl@0
   769
		{
sl@0
   770
		iReqCur = iReqStart = pos;
sl@0
   771
		iReqEnd = iReqStart + length;
sl@0
   772
sl@0
   773
		TBool allDone(EFalse);
sl@0
   774
		if ( ((r = ReadDataUntilCacheExhausted(&allDone)) == KErrNone) && !allDone)
sl@0
   775
			{
sl@0
   776
			iMedReq = EMReqRead;
sl@0
   777
			iPhysStart = iReqCur & ~iBlkMsk;
sl@0
   778
			__ASSERT_DEBUG(I64HIGH(iPhysStart >> KMMCardHighCapBlockSizeLog2) == 0, Panic(ELRStart));
sl@0
   779
			
sl@0
   780
			iReadToEndOfCard = ( iReqEnd >= TotalSizeInBytes() );
sl@0
   781
			// Re-calculate length as some data may have been recovered from cache
sl@0
   782
			length = I64LOW(iReqEnd - iReqCur);
sl@0
   783
			
sl@0
   784
			if (iCurrentReq->IsPhysicalAddress() && !iReadToEndOfCard && (length >= iBlkLen) )
sl@0
   785
				r = LaunchPhysRead(iReqCur, length);
sl@0
   786
			else if ( (iReqEnd - iPhysStart) > iMaxBufSize && iSocket->SupportsDoubleBuffering() && !iReadToEndOfCard)
sl@0
   787
				r = LaunchDBRead();
sl@0
   788
			else
sl@0
   789
				r = LaunchRead(iReqCur, length);
sl@0
   790
sl@0
   791
			if (r == KErrNone)
sl@0
   792
			    {
sl@0
   793
			    OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOREAD_EXIT2, this, r );
sl@0
   794
			    return r;
sl@0
   795
			    }
sl@0
   796
			}
sl@0
   797
		}
sl@0
   798
	else
sl@0
   799
		{
sl@0
   800
#if defined(__DEMAND_PAGING__) && !defined(__WINS__)
sl@0
   801
		if (DMediaPagingDevice::PageInRequest(*iCurrentReq))
sl@0
   802
			{
sl@0
   803
			r = iCurrentReq->WriteToPageHandler(NULL, 0, 0);
sl@0
   804
			}
sl@0
   805
		else
sl@0
   806
#endif	// __DEMAND_PAGING__
sl@0
   807
			{
sl@0
   808
			TPtrC8 zeroDes(NULL, 0);
sl@0
   809
			r = iCurrentReq->WriteRemote(&zeroDes,0);
sl@0
   810
			}
sl@0
   811
		}
sl@0
   812
sl@0
   813
	// error occurred or read all from cache so complete immediately
sl@0
   814
	if(r == KErrNone)
sl@0
   815
		r = KErrCompletion;
sl@0
   816
sl@0
   817
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:dr:%d", r));
sl@0
   818
	
sl@0
   819
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOREAD_EXIT3, this, r );
sl@0
   820
	return r;
sl@0
   821
	}
sl@0
   822
sl@0
   823
sl@0
   824
TInt DMmcMediaDriverFlash::LaunchRead(TInt64 aStart, TUint32 aLength)
sl@0
   825
//
sl@0
   826
// starts reads from DoRead() and the session end DFC.  This function does not maintain the
sl@0
   827
// iReq* instance variables.  It sets iPhysStart and iPhysEnd to the region that was actually
sl@0
   828
// read into iIntBuf. iIntBuf can be set to a cached entry or to the minor buffer.  It is
sl@0
   829
// assumed that before this function is called that ReadDataUntilCacheExhausted() has been used.
sl@0
   830
//
sl@0
   831
	{
sl@0
   832
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_LAUNCHREAD_ENTRY, this );
sl@0
   833
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHREAD, "position=0x%lx; length=0x%x", (TUint) iCurrentReq->Pos(), (TUint) I64LOW(iCurrentReq->Length()));
sl@0
   834
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:lr:0x%lx,0x%x", aStart, aLength));
sl@0
   835
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(ELRStart));
sl@0
   836
	__ASSERT_DEBUG(aLength > 0, Panic(ELRNotPositive));
sl@0
   837
	__ASSERT_DEBUG(TotalSizeInBytes() >= aStart + aLength, Panic(ELREnd));
sl@0
   838
	__ASSERT_CACHE(GetCachedBlock(aStart & ~iBlkMsk) == 0, Panic(ELRCached));
sl@0
   839
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
   840
sl@0
   841
	iDoPhysicalAddress = EFalse;
sl@0
   842
	iDoDoubleBuffer = EFalse;
sl@0
   843
	iSecondBuffer = EFalse;
sl@0
   844
	
sl@0
   845
	// 
sl@0
   846
	// if this read goes up to the end of the card then use only 
sl@0
   847
	// single sector reads to avoid CMD12 timing problems
sl@0
   848
	//
sl@0
   849
	const TUint32 bufSize(iReadToEndOfCard ? iBlkLen : iMaxBufSize);
sl@0
   850
	
sl@0
   851
	iPhysEnd = (UMin(iReqEnd, iPhysStart + bufSize) + iBlkMsk) & ~iBlkMsk;
sl@0
   852
	
sl@0
   853
	TUint32 physLen(I64LOW(iPhysEnd - iPhysStart));
sl@0
   854
	
sl@0
   855
	__ASSERT_DEBUG(I64HIGH(iPhysEnd - iPhysStart) == 0, Panic(ELREnd));
sl@0
   856
sl@0
   857
	// partial reads must be within a single physical block
sl@0
   858
	if (iReadBlPartial && physLen == iBlkLen && aLength <= (iBlkLen >> 1))
sl@0
   859
		{
sl@0
   860
		// 
sl@0
   861
		// Note : Partial reads are not supported for large block devices 
sl@0
   862
		//        (MMCV4.2 and SD2.0 high capacity cards)
sl@0
   863
		//
sl@0
   864
		__ASSERT_DEBUG(I64HIGH(aStart) == 0, Panic(ELRStart));
sl@0
   865
		__ASSERT_DEBUG(I64HIGH(aStart + aLength) == 0, Panic(ELREnd));
sl@0
   866
sl@0
   867
		iIntBuf = iMinorBuf;
sl@0
   868
		Stack().AdjustPartialRead(iCard, I64LOW(aStart), I64LOW(aStart + aLength), (TUint32*)&iPhysStart, (TUint32*)&iPhysEnd);
sl@0
   869
		iSession->SetupCIMReadBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iIntBuf, physLen >> KMMCardHighCapBlockSizeLog2);
sl@0
   870
		}
sl@0
   871
	else
sl@0
   872
		{	
sl@0
   873
		iIntBuf = ReserveReadBlocks(iPhysStart, iPhysEnd, &physLen);
sl@0
   874
			
sl@0
   875
		// EPBUSM automatically uses CMD17 instead of CMD18 for single block reads
sl@0
   876
		iSession->SetupCIMReadBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iIntBuf, physLen >> KMMCardHighCapBlockSizeLog2);
sl@0
   877
		
sl@0
   878
		// Update Physical end point as less may have been required due to additional blocks found in cache during ReserveReadBlocks
sl@0
   879
		iPhysEnd = iPhysStart + physLen;
sl@0
   880
		}
sl@0
   881
	
sl@0
   882
	TInt r = EngageAndSetReadRequest(EMReqRead);
sl@0
   883
	
sl@0
   884
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lr:%d", r));
sl@0
   885
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHREAD_EXIT, this, r );
sl@0
   886
	return r;
sl@0
   887
	}
sl@0
   888
sl@0
   889
TInt DMmcMediaDriverFlash::LaunchDBRead()
sl@0
   890
//
sl@0
   891
// starts reads from DoRead() and the session end DFC.  This function does not maintain the
sl@0
   892
// iReq* instance variables.  It sets iPhysStart and iPhysEnd to the region that was actually
sl@0
   893
// read into iIntBuf. iIntBuf can be set to a cached entry or to the minor buffer.  It is
sl@0
   894
// assumed that before this function is called that ReadDataUntilCacheExhausted() has been used.
sl@0
   895
//
sl@0
   896
	{
sl@0
   897
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_LAUNCHDBREAD_ENTRY, this );
sl@0
   898
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:ldbr:0x%lx,0x%x", iReqCur, I64LOW(iReqEnd - iReqCur)));
sl@0
   899
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHDBREAD, "position=0x%lx; length=0x%x", (TInt) iReqCur, (TInt) I64LOW(iReqEnd - iReqCur));
sl@0
   900
	__ASSERT_DEBUG(TotalSizeInBytes() > iReqCur, Panic(ELRStart));
sl@0
   901
	__ASSERT_DEBUG(I64LOW(iReqEnd - iReqCur) > 0, Panic(ELRNotPositive));
sl@0
   902
	__ASSERT_DEBUG(TotalSizeInBytes() >= iReqEnd, Panic(ELREnd));
sl@0
   903
	__ASSERT_CACHE(GetCachedBlock(iReqCur & ~iBlkMsk) == 0, Panic(ELRCached));
sl@0
   904
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
   905
sl@0
   906
	iDoDoubleBuffer = ETrue;
sl@0
   907
	iDoPhysicalAddress = EFalse;
sl@0
   908
	
sl@0
   909
	iDbEnd = iReqEnd;
sl@0
   910
	const TUint32 maxDbLength = iSocket->MaxDataTransferLength();
sl@0
   911
sl@0
   912
	if(maxDbLength)
sl@0
   913
		{
sl@0
   914
		//
sl@0
   915
		// If the PSL specifies a limit on the maximum size of a data transfer, then truncate the request...
sl@0
   916
		//
sl@0
   917
		iDbEnd = UMin(iDbEnd, iPhysStart + maxDbLength);
sl@0
   918
		}
sl@0
   919
sl@0
   920
	iDbEnd = (iDbEnd + iBlkMsk) & ~iBlkMsk;
sl@0
   921
sl@0
   922
	const TUint32 doubleBufferSize = iMaxBufSize >> 1;
sl@0
   923
	iPhysEnd = (iReqCur + doubleBufferSize) & ~iBlkMsk;	// The end of the first double-buffered transfer
sl@0
   924
	
sl@0
   925
	//
sl@0
   926
	// If we're double-buffering, then the entire cache will be re-used
sl@0
   927
	// continuously.  Rather than continually reserve blocks during each 
sl@0
   928
	// transfer we calculate the blocks that will be present after all
sl@0
   929
	// transfers have completed. 
sl@0
   930
	// @see DoSessionEndDfc()
sl@0
   931
	//
sl@0
   932
	InvalidateCache();
sl@0
   933
	iIntBuf = iCacheBuf;
sl@0
   934
	
sl@0
   935
	iSession->SetupCIMReadBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iIntBuf, I64LOW(iDbEnd - iPhysStart) >> KMMCardHighCapBlockSizeLog2);
sl@0
   936
sl@0
   937
	iSession->EnableDoubleBuffering(doubleBufferSize >> KDiskSectorShift);
sl@0
   938
sl@0
   939
	// ...and switch to the 'second' buffer, which will be populated in the
sl@0
   940
	// data transfer callback in parallel with hardware transfer of the first.
sl@0
   941
	iSecondBuffer = ETrue;
sl@0
   942
sl@0
   943
	TInt r = EngageAndSetReadRequest(EMReqRead);
sl@0
   944
sl@0
   945
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:ldbr:%d", r));
sl@0
   946
sl@0
   947
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHDBREAD_EXIT, this, r );
sl@0
   948
	return r;
sl@0
   949
	}
sl@0
   950
sl@0
   951
sl@0
   952
TInt DMmcMediaDriverFlash::LaunchPhysRead(TInt64 aStart, TUint32 aLength)
sl@0
   953
//
sl@0
   954
// This function does not maintain the iReq* instance variables.  
sl@0
   955
// It is assumed that before this function is called that 
sl@0
   956
// ReadDataUntilCacheExhausted() has been used.
sl@0
   957
//
sl@0
   958
	{
sl@0
   959
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_LAUNCHPHYSREAD_ENTRY, this );
sl@0
   960
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHPHYSREAD, "position=0x%lx; length=0x%x", (TInt) iReqCur, (TInt) I64LOW(iReqEnd - iReqCur));
sl@0
   961
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:physr:0x%lx,0x%x", aStart, aLength));
sl@0
   962
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(ELRStart));
sl@0
   963
	__ASSERT_DEBUG(aLength > 0, Panic(ELRNotPositive));
sl@0
   964
	__ASSERT_DEBUG(TotalSizeInBytes() >= aStart + aLength, Panic(ELREnd));
sl@0
   965
	__ASSERT_CACHE(GetCachedBlock(aStart & ~iBlkMsk) == 0, Panic(ELRCached));
sl@0
   966
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
   967
sl@0
   968
	TInt r(KErrNone);
sl@0
   969
	
sl@0
   970
	iDoPhysicalAddress = ETrue;  
sl@0
   971
	iDoDoubleBuffer = EFalse;
sl@0
   972
	
sl@0
   973
	// Local Media Subsystem ensures DMA Addressable range not exceeded.
sl@0
   974
	// @see LocDrv::RegisterDmaDevice()
sl@0
   975
	iPhysEnd = (iReqEnd + iBlkMsk) & ~iBlkMsk;
sl@0
   976
	
sl@0
   977
	iRdROB = 0;
sl@0
   978
	iFragOfset = iIPCLen = iNxtIPCLen = iBufOfset = 0; 
sl@0
   979
	
sl@0
   980
	// Determine if start/end are block aligned
sl@0
   981
	// physical memory can only read the exact amount, not more!
sl@0
   982
	const TBool firstPartial( (aStart & iBlkMsk) != 0);
sl@0
   983
	
sl@0
   984
	TPhysAddr physAddr(0);						
sl@0
   985
	TInt physLength(0);
sl@0
   986
	TUint32 physLen(I64LOW(iPhysEnd - iPhysStart));
sl@0
   987
	
sl@0
   988
	if (firstPartial)
sl@0
   989
		{
sl@0
   990
		__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:physr:FirstPartial"));
sl@0
   991
		OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCH_PHYSREAD_FP, "FirstPartial");
sl@0
   992
		// first index does not start on block boundary
sl@0
   993
		// iIntBuf linear address is used for IPC within DoReadDataTransferCallBack()
sl@0
   994
		iRdROB |= KIPCWrite;
sl@0
   995
		
sl@0
   996
		iIntBuf = ReserveReadBlocks(iPhysStart, iPhysStart+iBlkLen,(TUint32*)&physLength);
sl@0
   997
#if !defined(__WINS__)
sl@0
   998
		physAddr = Epoc::LinearToPhysical((TLinAddr)iIntBuf);
sl@0
   999
#else
sl@0
  1000
		physAddr = (TPhysAddr)iIntBuf;
sl@0
  1001
#endif
sl@0
  1002
		// Set SecondBuffer flag to indicate IPC cannot be done on next callback
sl@0
  1003
		iSecondBuffer = ETrue;
sl@0
  1004
		iBufOfset = I64LOW(iReqStart - iPhysStart);
sl@0
  1005
		//iReqCur already set in DoRead;
sl@0
  1006
		iFragOfset = iNxtIPCLen = physLength - iBufOfset;
sl@0
  1007
		}				
sl@0
  1008
	else
sl@0
  1009
		{
sl@0
  1010
		// Determine offset from start due to data possibly recovered from local cache
sl@0
  1011
		iFragOfset = I64LOW(aStart - iReqStart);	
sl@0
  1012
		r = PrepareFirstPhysicalFragment(physAddr, physLength, aLength);
sl@0
  1013
		
sl@0
  1014
		// No use for secondBuffer yet...
sl@0
  1015
		iSecondBuffer = EFalse;
sl@0
  1016
		}
sl@0
  1017
	
sl@0
  1018
	if(r == KErrNone)
sl@0
  1019
   		{         
sl@0
  1020
   		iDbEnd = iPhysEnd;
sl@0
  1021
   		iPhysEnd = iPhysStart + physLength;
sl@0
  1022
   		
sl@0
  1023
        if ((TUint32)physLength > physLen) physLength = physLen; // more memory in chunk than required
sl@0
  1024
        
sl@0
  1025
    	iSession->SetupCIMReadBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), (TUint8*)physAddr, physLen >> KMMCardHighCapBlockSizeLog2);				
sl@0
  1026
    	
sl@0
  1027
		iSession->Command().iFlags|= KMMCCmdFlagPhysAddr;
sl@0
  1028
		iSession->EnableDoubleBuffering(physLength >> KDiskSectorShift);
sl@0
  1029
		
sl@0
  1030
		r = EngageAndSetReadRequest(EMReqRead);
sl@0
  1031
   		} 
sl@0
  1032
		
sl@0
  1033
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lphysr:%d", r));
sl@0
  1034
sl@0
  1035
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHPHYSREAD_EXIT, this, r );
sl@0
  1036
	return r;
sl@0
  1037
	}
sl@0
  1038
sl@0
  1039
sl@0
  1040
TInt DMmcMediaDriverFlash::DoWrite()
sl@0
  1041
//
sl@0
  1042
// set up iReqStart, iReqEnd, and iReqCur, and launch first write.  Any subsequent
sl@0
  1043
// writes are launched from the session end DFC.  LaunchWrite() handles pre-reading
sl@0
  1044
// any sectors that are only partially modified.
sl@0
  1045
//
sl@0
  1046
	{
sl@0
  1047
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOWRITE_ENTRY, this );
sl@0
  1048
	const TInt64 pos = iCurrentReq->Pos();
sl@0
  1049
	const TUint32 length = I64LOW(iCurrentReq->Length());
sl@0
  1050
sl@0
  1051
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:dw:0x%lx,0x%x", pos, length));
sl@0
  1052
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOWRITE, "position=0x%lx; length=0x%x", (TUint) pos, (TUint) length);
sl@0
  1053
	__ASSERT_DEBUG(CurrentRequest() == EMReqIdle, Panic(EDWInUse));
sl@0
  1054
	__ASSERT_DEBUG(pos < TotalSizeInBytes(), Panic(EDWStart));
sl@0
  1055
	__ASSERT_DEBUG(length > 0, Panic(EDWNotPositive));
sl@0
  1056
	__ASSERT_DEBUG(TotalSizeInBytes() >= pos + length, Panic(EDWEnd));
sl@0
  1057
sl@0
  1058
	iReqCur = iReqStart = pos;
sl@0
  1059
	iReqEnd = iReqStart + length;
sl@0
  1060
sl@0
  1061
	// iWtRBM is zero on construction because CBase-derived, and cleared at end
sl@0
  1062
	// of successful writes.  If a write does not complete successfully, it may
sl@0
  1063
	// be left in non-zero state.
sl@0
  1064
	iWtRBM = 0;
sl@0
  1065
	
sl@0
  1066
	iSecondBuffer  = EFalse;
sl@0
  1067
	iDoLastRMW     = EFalse;
sl@0
  1068
	iDoDoubleBuffer= EFalse;
sl@0
  1069
	iDoPhysicalAddress = EFalse;
sl@0
  1070
	
sl@0
  1071
	const TInt r = LaunchWrite(iReqStart, length, EMReqWrite);
sl@0
  1072
sl@0
  1073
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:dw:%d", r));
sl@0
  1074
sl@0
  1075
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOWRITE_EXIT, this, r );
sl@0
  1076
	return r;
sl@0
  1077
	}
sl@0
  1078
sl@0
  1079
sl@0
  1080
TInt DMmcMediaDriverFlash::DoFormat()
sl@0
  1081
	{
sl@0
  1082
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOFORMAT_ENTRY, this );
sl@0
  1083
	const TInt64 pos = iCurrentReq->Pos();
sl@0
  1084
	const TUint32 length = I64LOW(iCurrentReq->Length());
sl@0
  1085
sl@0
  1086
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:df:0x%lx,0x%x", pos, length));
sl@0
  1087
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOFORMAT, "position=0x%lx; length=0x%x", (TUint) pos, (TUint) length);
sl@0
  1088
	__ASSERT_DEBUG(CurrentRequest() == EMReqIdle, Panic(EDFInUse));
sl@0
  1089
	__ASSERT_DEBUG(pos < TotalSizeInBytes(), Panic(EDFStart));
sl@0
  1090
	__ASSERT_DEBUG(length > 0, Panic(EDFNotPositive));
sl@0
  1091
	__ASSERT_DEBUG(TotalSizeInBytes() >= pos + length, Panic(EDFEnd));
sl@0
  1092
sl@0
  1093
	iReqCur = iReqStart = pos & ~iBlkMsk;
sl@0
  1094
	iReqEnd = (iReqStart + length + iBlkMsk) & ~iBlkMsk;
sl@0
  1095
sl@0
  1096
	// the cache isn't maintained during a format operation to avoid redundantly
sl@0
  1097
	// writing 0xff to memory (the blocks won't be re-used.)
sl@0
  1098
	InvalidateCache();
sl@0
  1099
sl@0
  1100
	// create an MBR after the first format step (or second if misaligned) 
sl@0
  1101
 
sl@0
  1102
	if (iInternalSlot)
sl@0
  1103
		{
sl@0
  1104
		iCreateMbr = EFalse;
sl@0
  1105
		}
sl@0
  1106
	else
sl@0
  1107
		{
sl@0
  1108
		if (iReqStart == (TInt64(iHiddenSectors) << KDiskSectorShift) && CreateMBRAfterFormat(iCard))
sl@0
  1109
			iCreateMbr = ETrue;
sl@0
  1110
		}
sl@0
  1111
sl@0
  1112
	const TInt r = LaunchFormat(iReqStart, I64LOW(iReqEnd - iReqStart));
sl@0
  1113
sl@0
  1114
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:df:%d", r));
sl@0
  1115
sl@0
  1116
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOFORMAT_EXIT, this, r );
sl@0
  1117
	return r;
sl@0
  1118
	}
sl@0
  1119
sl@0
  1120
sl@0
  1121
TInt DMmcMediaDriverFlash::LaunchFormat(TInt64 aStart, TUint32 aLength)
sl@0
  1122
//
sl@0
  1123
// starts writes from DoWrite(), DoFormat() and the session end DFC.  This function does not
sl@0
  1124
// maintain the iReq* instance variables.  It sets iIntBuf, iPhysStart and iPhysEnd.
sl@0
  1125
//
sl@0
  1126
	{
sl@0
  1127
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_LAUNCHFORMAT_ENTRY, this );
sl@0
  1128
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHFORMAT, "position=0x%lx; length=0x%x", (TInt) iReqCur, (TInt) I64LOW(iReqEnd - iReqCur));
sl@0
  1129
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:lf:0x%lx,0x%x", aStart, aLength));
sl@0
  1130
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(ELFStart));
sl@0
  1131
	__ASSERT_DEBUG((aStart & iBlkMsk) == 0, Panic(ELWFmtStAlign));
sl@0
  1132
	__ASSERT_DEBUG(aLength > 0, Panic(ELFNotPositive));
sl@0
  1133
	__ASSERT_DEBUG(TotalSizeInBytes() >= aStart + aLength, Panic(ELFEnd));
sl@0
  1134
	__ASSERT_DEBUG((aLength & iBlkMsk) == 0, Panic(ELWFmtEndAlign));
sl@0
  1135
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  1136
sl@0
  1137
	TInt r;
sl@0
  1138
sl@0
  1139
	if ((r = CheckDevice(EMReqTypeNormalWr)) == KErrNone)
sl@0
  1140
		{
sl@0
  1141
		iPhysStart = aStart & ~iBlkMsk;
sl@0
  1142
sl@0
  1143
		// formats are always block-aligned, and the buffer is initialized to 0xff
sl@0
  1144
		//  Check whether erase commands are supported by this card
sl@0
  1145
		if (iCard->CSD().CCC() & KMMCCmdClassErase)
sl@0
  1146
			{
sl@0
  1147
			// Determine the erase end point for the next command. We don't erase past the preferred erase unit
sl@0
  1148
			// size. Therefore, check which is lower, the preferred erase unit size or the end of the requested range.
sl@0
  1149
			TInt64 prefEraseUnitEnd = (iPhysStart + iEraseInfo.iPreferredEraseUnitSize) & ~iEraseUnitMsk;
sl@0
  1150
			iPhysEnd = UMin(prefEraseUnitEnd, aStart + aLength);
sl@0
  1151
sl@0
  1152
			const TUint32 minEraseSectorSize=iEraseInfo.iMinEraseSectorSize;
sl@0
  1153
			const TInt64  minEraseSecMsk = TInt64(minEraseSectorSize-1);
sl@0
  1154
			
sl@0
  1155
			// If erase start point doesn't lie on a min. erase unit boundary, then truncate the erase endpoint to
sl@0
  1156
			// the next min. erase unit boundary (assuming requested range allows this)
sl@0
  1157
			if ((iPhysStart & minEraseSecMsk)!=0)
sl@0
  1158
				{
sl@0
  1159
				prefEraseUnitEnd=(iPhysStart+minEraseSectorSize) & ~minEraseSecMsk;
sl@0
  1160
				iPhysEnd=UMin(prefEraseUnitEnd,iPhysEnd);
sl@0
  1161
				}
sl@0
  1162
				
sl@0
  1163
			// Otherwise, if calculated erase end point doesn't lie on a min. erase unit boundary, but is at least one
sl@0
  1164
			// min. erase unit beyond the erase start point then move erase endpoint back to last min. erase unit boundary
sl@0
  1165
			else if ((iPhysEnd & minEraseSecMsk)!=0 && (iPhysEnd & ~minEraseSecMsk)>iPhysStart)
sl@0
  1166
				{
sl@0
  1167
				iPhysEnd&=(~minEraseSecMsk);
sl@0
  1168
				}
sl@0
  1169
sl@0
  1170
			// Now, if the erase start/end points are aligned to a min. erase unit boundary, we can use an erase cmd.
sl@0
  1171
			if ((iPhysStart & minEraseSecMsk) == 0 && (iPhysEnd & minEraseSecMsk) == 0)
sl@0
  1172
				{
sl@0
  1173
				// Aligned erase
sl@0
  1174
				//  Check that erase commands are supported prior to issuing an erase command
sl@0
  1175
				if(iEraseInfo.EraseGroupCmdsSupported())
sl@0
  1176
					{
sl@0
  1177
					iSession->SetupCIMEraseMGroup(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2),
sl@0
  1178
												  I64LOW((iPhysEnd-iPhysStart) >> KMMCardHighCapBlockSizeLog2)); // Use ACMD35/36/38 (Erase Group)
sl@0
  1179
					}
sl@0
  1180
				else
sl@0
  1181
					{
sl@0
  1182
					iSession->SetupCIMEraseMSector(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2),
sl@0
  1183
												   I64LOW((iPhysEnd - iPhysStart) >> KMMCardHighCapBlockSizeLog2)); // Use ACMD32/33/38 (Erase Sector)
sl@0
  1184
					}
sl@0
  1185
				}
sl@0
  1186
			else
sl@0
  1187
				{
sl@0
  1188
				// Misaligned erase - use multi-block write. However, first - check write length doesn't exceed buffer size.
sl@0
  1189
				if ((iPhysEnd-iPhysStart)>(TUint32)iMaxBufSize)
sl@0
  1190
					{
sl@0
  1191
					iPhysEnd=(iPhysStart+iMaxBufSize);
sl@0
  1192
					}
sl@0
  1193
					
sl@0
  1194
				__ASSERT_DEBUG((iPhysEnd - iPhysStart) > 0, Panic(ELWLength));
sl@0
  1195
				const TUint32 writeLen = I64LOW(iPhysEnd - iPhysStart);
sl@0
  1196
				memset (iCacheBuf, 0x00, writeLen);
sl@0
  1197
				iSession->SetupCIMWriteBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iCacheBuf, writeLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1198
				}
sl@0
  1199
			}
sl@0
  1200
		else
sl@0
  1201
			{
sl@0
  1202
			// Write to end of current write group, or end of request range, whichever is lower
sl@0
  1203
			const TInt64 prefEraseUnitEnd = (iPhysStart + iPrWtGpLen) & ~iPrWtGpMsk;
sl@0
  1204
			iPhysEnd = Min(prefEraseUnitEnd, aStart + aLength);				
sl@0
  1205
			
sl@0
  1206
			__ASSERT_DEBUG((iPhysEnd - iPhysStart) > 0, Panic(ELWLength));
sl@0
  1207
			const TUint32 writeLen = I64LOW(iPhysEnd - iPhysStart);
sl@0
  1208
			memset (iCacheBuf, 0x00, writeLen);
sl@0
  1209
			iSession->SetupCIMWriteBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iCacheBuf, writeLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1210
			}
sl@0
  1211
		
sl@0
  1212
		r = EngageAndSetWriteRequest(EMReqFormat);
sl@0
  1213
		}
sl@0
  1214
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHFORMAT_EXIT, this, r );
sl@0
  1215
		return r;
sl@0
  1216
	}
sl@0
  1217
sl@0
  1218
sl@0
  1219
sl@0
  1220
TInt DMmcMediaDriverFlash::LaunchWrite(TInt64 aStart, TUint32 aLength, TMediaRequest aMedReq)
sl@0
  1221
//
sl@0
  1222
// starts writes from DoWrite(), DoFormat() and the session end DFC.  This function does not
sl@0
  1223
// maintain the iReq* instance variables.  It sets iIntBuf, iPhysStart and iPhysEnd.
sl@0
  1224
//
sl@0
  1225
	{
sl@0
  1226
	OstTraceExt4(TRACE_FLOW, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_ENTRY, "DMmcMediaDriverFlash::LaunchWrite;aStart=%Ld;aLength=%x;aMedReq=%d;this=%x", aStart, (TUint) aLength, (TInt) aMedReq, (TUint) this);
sl@0
  1227
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE, "position=0x%lx; length=0x%x", (TInt) iReqCur, (TInt) I64LOW(iReqEnd - iReqCur));
sl@0
  1228
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("\n>mmd:lw:0x%lx,%d,%d", aStart, aLength, aMedReq));
sl@0
  1229
	__ASSERT_DEBUG(aMedReq == EMReqWrite || aMedReq == EMReqFormat, Panic(ELWRequest));
sl@0
  1230
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(ELWStart));
sl@0
  1231
	__ASSERT_DEBUG(!(aMedReq == EMReqFormat) || (aStart & iBlkMsk) == 0, Panic(ELWFmtStAlign));
sl@0
  1232
	__ASSERT_DEBUG(aLength > 0, Panic(ELWNotPositive));
sl@0
  1233
	__ASSERT_DEBUG(TotalSizeInBytes() >= aStart + aLength, Panic(ELWEnd));
sl@0
  1234
	__ASSERT_DEBUG(!(aMedReq == EMReqFormat) || (aLength & iBlkMsk) == 0, Panic(ELWFmtEndAlign));
sl@0
  1235
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  1236
sl@0
  1237
	TInt r;
sl@0
  1238
sl@0
  1239
	if ((r = CheckDevice(EMReqTypeNormalWr)) == KErrNone)
sl@0
  1240
		{
sl@0
  1241
		iPhysStart = aStart & ~iBlkMsk;
sl@0
  1242
sl@0
  1243
		// PSL MUST support double-buffering for DMA requests
sl@0
  1244
		// first write, or have just completed previous write
sl@0
  1245
		if (iWtRBM == 0)
sl@0
  1246
			{
sl@0
  1247
			if(iDoDoubleBuffer == EFalse)
sl@0
  1248
				{
sl@0
  1249
				//
sl@0
  1250
				// Can we use double-buffering for this request?
sl@0
  1251
				//
sl@0
  1252
				//  - Only if PSL supports double buffering and the request length 
sl@0
  1253
				//	  is greater than the maximum PSL buffer size.
sl@0
  1254
				//
sl@0
  1255
				iDoPhysicalAddress = iCurrentReq->IsPhysicalAddress();
sl@0
  1256
								
sl@0
  1257
				TInt64 medEnd = aStart + aLength;
sl@0
  1258
		
sl@0
  1259
				TInt64 maxPslEnd = medEnd;
sl@0
  1260
				const TUint32 maxDbLength = iSocket->MaxDataTransferLength();
sl@0
  1261
				
sl@0
  1262
				if(maxDbLength)
sl@0
  1263
					{
sl@0
  1264
					//
sl@0
  1265
					// If the PSL specifies a limit on the maximum size of a data transfer, then truncate the request...
sl@0
  1266
					//
sl@0
  1267
					maxPslEnd = UMin(medEnd, iPhysStart + maxDbLength);
sl@0
  1268
					}
sl@0
  1269
sl@0
  1270
				iPhysEnd = (maxPslEnd + iBlkMsk) & ~iBlkMsk;
sl@0
  1271
				
sl@0
  1272
				if (iDoPhysicalAddress)
sl@0
  1273
					{
sl@0
  1274
					iDoDoubleBuffer = EFalse;
sl@0
  1275
					iIntBuf = ReserveWriteBlocks(aStart, medEnd, &iWtRBM);
sl@0
  1276
					iPhysEnd = (medEnd + iBlkMsk) & ~iBlkMsk;
sl@0
  1277
					}
sl@0
  1278
sl@0
  1279
				if (!iDoPhysicalAddress)
sl@0
  1280
					{
sl@0
  1281
					iDoDoubleBuffer = iSocket->SupportsDoubleBuffering() && ((iPhysEnd - iPhysStart) > iMaxBufSize);
sl@0
  1282
					if(iDoDoubleBuffer)
sl@0
  1283
						{
sl@0
  1284
						//
sl@0
  1285
						// Conditions for double-buffering are met.  Set up the size of the first
sl@0
  1286
						// transfer to half the size of the block cache.  
sl@0
  1287
						//
sl@0
  1288
						// Note that we don't bother to align to write groups here, as the entire
sl@0
  1289
						// request will be processed under one multi-block command so there's no 
sl@0
  1290
						// danger of forcing the card into RMW cycles as would be the case when
sl@0
  1291
						// issuing multiple misaligned commands.
sl@0
  1292
						//
sl@0
  1293
						iDbEnd = maxPslEnd;												// The end of the complete double-buffered transfer
sl@0
  1294
						iPhysEnd = (iPhysStart + (iMaxBufSize >> 1) + iBlkMsk) &~ iBlkMsk;	// The end of the first double-buffered transfer
sl@0
  1295
						__ASSERT_DEBUG(iPhysEnd - iPhysStart <= (iMaxBufSize >> 1), Panic(ELWLength));
sl@0
  1296
	
sl@0
  1297
						//
sl@0
  1298
						// Now reserve write blocks from the buffer cache. When double-buffering,
sl@0
  1299
						// write blocks are only really reserved during the last transfer to avoid
sl@0
  1300
						// continuously updating the cache indexes. Since the block cache is
sl@0
  1301
						// continuously recycled, the following call shall invalidate the cache
sl@0
  1302
						// and inform us as to whether we need to perform an RMW operation for
sl@0
  1303
						// the first and last blocks prior to initiating data transfer.
sl@0
  1304
						//
sl@0
  1305
						iIntBuf = ReserveWriteBlocks(aStart, iDbEnd, &iWtRBM);
sl@0
  1306
						}
sl@0
  1307
					else
sl@0
  1308
						{				
sl@0
  1309
						if ( (iPhysEnd - iPhysStart) > iMaxBufSize)
sl@0
  1310
						    {
sl@0
  1311
		                    //
sl@0
  1312
                            // reserve buffers to end of first write group, or end of request range,
sl@0
  1313
                            // whichever is lower.  Note that if the range already exists in the buffer,
sl@0
  1314
                            // e.g. because of a previous RBM, the same range will be returned.  This
sl@0
  1315
                            // means that iWtRBM can be set to zero in the callback DFC, and this code
sl@0
  1316
                            // will retrieve the reserved range.
sl@0
  1317
                            //  
sl@0
  1318
						    const TInt64 wtGpEnd = (iPhysStart + iPrWtGpLen) & ~iPrWtGpMsk;
sl@0
  1319
						    medEnd = UMin(wtGpEnd, aStart + aLength);
sl@0
  1320
						    iPhysEnd = (medEnd + iBlkMsk) & ~iBlkMsk;
sl@0
  1321
						    }
sl@0
  1322
						
sl@0
  1323
						iIntBuf = ReserveWriteBlocks(aStart, medEnd, &iWtRBM);
sl@0
  1324
						}
sl@0
  1325
					} //if (!iDoPhysicalAddress)
sl@0
  1326
				} //if(iDoDoubleBuffer == EFalse)
sl@0
  1327
			} //if (iWtRBM == 0)
sl@0
  1328
sl@0
  1329
		if (iWtRBM & KWtRBMFst)
sl@0
  1330
			{			
sl@0
  1331
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:lw: read-before-modify required on first block"));
sl@0
  1332
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_RBMF, "Read-before-modify required on first block");
sl@0
  1333
			if (iDoPhysicalAddress)
sl@0
  1334
				iSession->SetupCIMReadBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iMinorBuf, iBlkLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1335
			else
sl@0
  1336
				iSession->SetupCIMReadBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iIntBuf, iBlkLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1337
			r = EngageAndSetReadRequest(aMedReq);
sl@0
  1338
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHWRITE_EXIT1, this, r );
sl@0
  1339
			return r;
sl@0
  1340
			}
sl@0
  1341
sl@0
  1342
		else if (iWtRBM & KWtRBMLst)
sl@0
  1343
			{
sl@0
  1344
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:lw: read-before-modify required on last block"));			
sl@0
  1345
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_RBML, "Read-before-modify required on last block");
sl@0
  1346
			if(iDoDoubleBuffer || iDoPhysicalAddress)
sl@0
  1347
				{
sl@0
  1348
				//
sl@0
  1349
				// When double-buffering, the result of the RMW-read operation shall be stored
sl@0
  1350
				// in the minor buffer, otherwise the data would be overwritten before the last
sl@0
  1351
				// data transfer takes place.
sl@0
  1352
				//
sl@0
  1353
				const TInt64 lastBlock = (aStart + aLength) & ~iBlkMsk;  // start posn in media to read from (we know aStart + aLength isn't block aligned due to KWtRBMLst flag)
sl@0
  1354
				if (iDoDoubleBuffer)
sl@0
  1355
					iSession->SetupCIMReadBlock(I64LOW(lastBlock >> KMMCardHighCapBlockSizeLog2), iMinorBuf, iBlkLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1356
				else
sl@0
  1357
					iSession->SetupCIMReadBlock(I64LOW(lastBlock >> KMMCardHighCapBlockSizeLog2), iCacheBuf, iBlkLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1358
				}
sl@0
  1359
			else
sl@0
  1360
				{
sl@0
  1361
				//
sl@0
  1362
				// If not double-buffering, we can read the RMW data of the last block directly
sl@0
  1363
				// into the block cache as we know that the data transfer will fit entirely
sl@0
  1364
				// within the cache..
sl@0
  1365
				//
sl@0
  1366
				const TInt64 lastBlock = iPhysEnd - iBlkLen;		// start posn in media to read from
sl@0
  1367
				iSession->SetupCIMReadBlock(I64LOW(lastBlock >> KMMCardHighCapBlockSizeLog2), iIntBuf + (lastBlock - iPhysStart), iBlkLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1368
				}
sl@0
  1369
sl@0
  1370
			// Kick off the RMW-read operation for the last block...
sl@0
  1371
			r = EngageAndSetReadRequest(aMedReq);
sl@0
  1372
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHWRITE_EXIT2, this, r );
sl@0
  1373
			return r;
sl@0
  1374
			}
sl@0
  1375
		
sl@0
  1376
		if (iWtRBM & KWtMinFst)
sl@0
  1377
			{
sl@0
  1378
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:lw:Phys write-first-block-only"));			
sl@0
  1379
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_FBO, "Write first block only");
sl@0
  1380
			//Overwrite first block with the new data			
sl@0
  1381
			TInt32 tlen = I64LOW(aStart & iBlkMsk);
sl@0
  1382
			TInt32 wlen = UMin(I64LOW((iBlkMsk+1) - tlen), aLength);			
sl@0
  1383
			
sl@0
  1384
			const TInt64 usrOfst = (aStart - iReqStart);
sl@0
  1385
			TPtr8 tgt(&iMinorBuf[tlen], I64LOW(wlen));
sl@0
  1386
sl@0
  1387
			if ( (r = iCurrentReq->ReadRemote(&tgt,I64LOW(usrOfst))) != KErrNone)
sl@0
  1388
			    {
sl@0
  1389
				OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHWRITE_EXIT3, this, r );
sl@0
  1390
				return r;			
sl@0
  1391
			    }
sl@0
  1392
			}
sl@0
  1393
		
sl@0
  1394
		if (iWtRBM & KWtMinLst)
sl@0
  1395
			{
sl@0
  1396
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:lw:Phys write-last-block-only"));
sl@0
  1397
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_LBO, "Write last block only");
sl@0
  1398
			iWtRBM &= ~KWtMinLst;
sl@0
  1399
			//Overwrite last block with the new data
sl@0
  1400
			const TInt64 medEnds = aStart + aLength;
sl@0
  1401
			TInt64 tlen = medEnds & iBlkMsk;
sl@0
  1402
			
sl@0
  1403
			const TInt64 usrOfst = (aStart - iReqStart);					
sl@0
  1404
			TPtr8 tgt(iCacheBuf, I64LOW(tlen));			
sl@0
  1405
						
sl@0
  1406
			if ( (r = iCurrentReq->ReadRemote(&tgt,I64LOW(usrOfst+aLength-tlen))) !=KErrNone)
sl@0
  1407
			    {
sl@0
  1408
				OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHWRITE_EXIT4, this, r );
sl@0
  1409
				return r;			
sl@0
  1410
			    }
sl@0
  1411
			}
sl@0
  1412
		
sl@0
  1413
		// no reads required - read data from user buffer and launch write
sl@0
  1414
		const TInt64 usrOfst = (aStart - iReqStart);
sl@0
  1415
		const TInt64 bufOfst = aStart - iPhysStart;		// offset into first sector, not whole buffer
sl@0
  1416
		const TInt64 len = UMin(aStart + aLength, iPhysEnd) - iReqCur;
sl@0
  1417
		__ASSERT_DEBUG(len > 0, Panic(ELWLength));
sl@0
  1418
		__ASSERT_DEBUG(I64HIGH(usrOfst) == 0, Panic(ELWLength));
sl@0
  1419
sl@0
  1420
		if (iDoPhysicalAddress)
sl@0
  1421
			{
sl@0
  1422
			TPhysAddr physAddr = 0;
sl@0
  1423
			TInt physLength = 0;
sl@0
  1424
			TUint32 physLen = I64LOW(iPhysEnd - iPhysStart);
sl@0
  1425
			
sl@0
  1426
			if (iWtRBM & KWtMinFst)
sl@0
  1427
				{
sl@0
  1428
#if !defined(__WINS__)
sl@0
  1429
				physAddr = Epoc::LinearToPhysical((TLinAddr)iMinorBuf);
sl@0
  1430
#else
sl@0
  1431
				physAddr = (TPhysAddr)iMinorBuf;
sl@0
  1432
#endif
sl@0
  1433
				physLength = iBlkLen;
sl@0
  1434
				iBufOfset = I64LOW(iReqStart - iPhysStart);
sl@0
  1435
				//iReqCur already set in DoWrite
sl@0
  1436
				iFragOfset = iIPCLen = iBlkLen - iBufOfset;
sl@0
  1437
				iWtRBM &= ~KWtMinFst;
sl@0
  1438
				}
sl@0
  1439
			else
sl@0
  1440
				{
sl@0
  1441
				iFragOfset = I64LOW(usrOfst);
sl@0
  1442
			
sl@0
  1443
				r = PrepareFirstPhysicalFragment(physAddr, physLength, aLength);
sl@0
  1444
				}
sl@0
  1445
					           						
sl@0
  1446
			if (r == KErrNone)
sl@0
  1447
				{
sl@0
  1448
				iDbEnd = iPhysEnd;
sl@0
  1449
           		iPhysEnd = iPhysStart+physLength;
sl@0
  1450
           		
sl@0
  1451
           		if ((TUint32)physLength > physLen) physLength = physLen; // more memory in fragment than required!	
sl@0
  1452
           		OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_PHYSICAL, "Physical write request" );
sl@0
  1453
				iSession->SetupCIMWriteBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), (TUint8*) physAddr, physLen >> KMMCardHighCapBlockSizeLog2);
sl@0
  1454
				iSession->Command().iFlags|= KMMCCmdFlagPhysAddr;
sl@0
  1455
				iSession->EnableDoubleBuffering(physLength >> KDiskSectorShift);
sl@0
  1456
				}
sl@0
  1457
			else 
sl@0
  1458
				{
sl@0
  1459
				__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lw:Phys:%d", r));
sl@0
  1460
				
sl@0
  1461
				OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHWRITE_EXIT5, this, r );
sl@0
  1462
				return r;					
sl@0
  1463
				}
sl@0
  1464
			} // if (iDoPhysicalAddress)
sl@0
  1465
		else
sl@0
  1466
			{
sl@0
  1467
			TPtr8 tgt(&iIntBuf[bufOfst], I64LOW(len));
sl@0
  1468
	
sl@0
  1469
			r = ReadDataFromUser(tgt, I64LOW(usrOfst));
sl@0
  1470
			if (r == KErrNone)
sl@0
  1471
				{
sl@0
  1472
				if(!iDoDoubleBuffer)
sl@0
  1473
					{
sl@0
  1474
					// EPBUSM automatically uses CMD24 instead of CMD25 for single block writes
sl@0
  1475
					OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_STANDARD, "Standard write request" );
sl@0
  1476
					iSession->SetupCIMWriteBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iIntBuf, I64LOW((iPhysEnd - iPhysStart) >> KMMCardHighCapBlockSizeLog2));
sl@0
  1477
					}
sl@0
  1478
				else
sl@0
  1479
					{
sl@0
  1480
					// 
sl@0
  1481
					// When double-buffering, set up the data transfer command to the entire
sl@0
  1482
					// request range. and flag the session to enable double-buffering (as well
sl@0
  1483
					// as specifying the length of each double-buffered transfer as calculated
sl@0
  1484
					// in 'len' above).  This is performed only once - the double-buffering 
sl@0
  1485
					// is subsequently handled within the DoDataTransferCallback function.
sl@0
  1486
					//
sl@0
  1487
					OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHWRITE_DB, "Double-buffered write request" );
sl@0
  1488
					iSession->SetupCIMWriteBlock(I64LOW(iPhysStart >> KMMCardHighCapBlockSizeLog2), iIntBuf, I64LOW((((iDbEnd + iBlkMsk) & ~iBlkMsk) - iPhysStart) >> KMMCardHighCapBlockSizeLog2));
sl@0
  1489
					iSession->EnableDoubleBuffering(I64LOW((len + iBlkMsk) & ~iBlkMsk) >> KDiskSectorShift);
sl@0
  1490
	
sl@0
  1491
					// ...and switch to the 'second' buffer, which will be populated in the
sl@0
  1492
					// data transfer callback in parallel with hardware transfer of the first.
sl@0
  1493
					iSecondBuffer = ETrue;
sl@0
  1494
					}
sl@0
  1495
				}
sl@0
  1496
			}
sl@0
  1497
	
sl@0
  1498
			//Reliable Write only supported by v4.3+ MMC media
sl@0
  1499
			if (iCard->ExtendedCSD().ExtendedCSDRev() >= 3)
sl@0
  1500
				{
sl@0
  1501
				// One request, i.e. not end of previous DB request 
sl@0
  1502
				// 512 Bytes long when sector aligned
sl@0
  1503
				if ( ( I64LOW(iPhysEnd - iPhysStart) == iBlkLen) && ((iReqStart & ~iBlkMsk) == iPhysStart) )
sl@0
  1504
					{
sl@0
  1505
					__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:lw:AtomicWrite"));
sl@0
  1506
					iSession->Command().iFlags|= KMMCCmdFlagReliableWrite;
sl@0
  1507
					}
sl@0
  1508
				}
sl@0
  1509
		
sl@0
  1510
			// Engage the data transfer session...
sl@0
  1511
			r = EngageAndSetWriteRequest(aMedReq);
sl@0
  1512
		}	// if ((r = CheckDevice(EMReqTypeNormalWr)) == KErrNone)
sl@0
  1513
sl@0
  1514
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lw:%d", r));
sl@0
  1515
sl@0
  1516
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHWRITE_EXIT6, this, r );
sl@0
  1517
	return r;
sl@0
  1518
	}
sl@0
  1519
sl@0
  1520
TInt DMmcMediaDriverFlash::PartitionInfo(TPartitionInfo& anInfo)
sl@0
  1521
//
sl@0
  1522
// Read the partition information for the media.  If the user supplied a password,
sl@0
  1523
// then unlock the card before trying to read the first sector.
sl@0
  1524
//
sl@0
  1525
	{
sl@0
  1526
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_PARTITIONINFO_ENTRY, this );
sl@0
  1527
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:rpi"));
sl@0
  1528
	__ASSERT_DEBUG(CurrentRequest() == EMReqIdle, Panic(ERPIInUse));
sl@0
  1529
sl@0
  1530
	iPartitionInfo = &anInfo;
sl@0
  1531
sl@0
  1532
	if(iMmcPartitionInfo)
sl@0
  1533
		{
sl@0
  1534
		// If this is an embedded device, use the custom formatting function:
sl@0
  1535
		TInt r = iMmcPartitionInfo->PartitionInfo(*iPartitionInfo, iSessionEndCallBack);
sl@0
  1536
		
sl@0
  1537
		iHiddenSectors = 0; // Not used for internal media
sl@0
  1538
		
sl@0
  1539
		if (KErrNone == r)
sl@0
  1540
			iMedReq = EMReqEMMCPtnInfo;
sl@0
  1541
		
sl@0
  1542
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_PARTITIONINFO_EXIT1, this, r );
sl@0
  1543
		return r;
sl@0
  1544
		}
sl@0
  1545
	
sl@0
  1546
	// Assume MBR will be present or is not required
sl@0
  1547
	iMbrMissing = EFalse;
sl@0
  1548
sl@0
  1549
	// If media driver is persistent (see EMediaDriverPersistent), 
sl@0
  1550
	// the card may have changed since last power down, so reset CID
sl@0
  1551
	iSession->SetCard(iCard);
sl@0
  1552
sl@0
  1553
	TInt r = LaunchRPIRead();
sl@0
  1554
sl@0
  1555
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:rpi:%d", r));
sl@0
  1556
sl@0
  1557
	if(r == KErrLocked)
sl@0
  1558
		{
sl@0
  1559
		// If the media is locked, we present a default partition entry to the local
sl@0
  1560
		// media subsystem, which will be updated when the media is finally unlocked.
sl@0
  1561
		r = CreateDefaultPartition();
sl@0
  1562
		if (r != KErrNone)
sl@0
  1563
		    {
sl@0
  1564
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_PARTITIONINFO_EXIT2, this, r );
sl@0
  1565
			return r;
sl@0
  1566
		    }
sl@0
  1567
		
sl@0
  1568
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_PARTITIONINFO_EXIT3, this, KErrLocked );
sl@0
  1569
		return KErrLocked;
sl@0
  1570
		}
sl@0
  1571
sl@0
  1572
	// KErrNone indicates asynchronous completion
sl@0
  1573
	
sl@0
  1574
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_PARTITIONINFO_EXIT4, this, r );
sl@0
  1575
	return r;
sl@0
  1576
	}
sl@0
  1577
sl@0
  1578
TInt DMmcMediaDriverFlash::LaunchRPIUnlock(TLocalDrivePasswordData& aPasswordData)
sl@0
  1579
	{
sl@0
  1580
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_LAUNCHRPIUNLOCK_ENTRY, this );
sl@0
  1581
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:lru:%d,%d", iCard->IsReady(), iCard->IsLocked()));
sl@0
  1582
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHRPIUNLOCK_ICARD, "iCard->IsReady=%d; iCard->IsLocked=%d", iCard->IsReady(), iCard->IsLocked());
sl@0
  1583
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  1584
sl@0
  1585
	TInt r = KErrNone;
sl@0
  1586
sl@0
  1587
	// CMD42 is an adtc, so check state in same way as for write
sl@0
  1588
	if ((r = CheckDevice(EMReqTypeUnlockPswd)) == KErrNone)
sl@0
  1589
		{
sl@0
  1590
		r = Stack().MMCSocket()->PrepareStore(CardNum(), DLocalDrive::EPasswordUnlock, aPasswordData);
sl@0
  1591
sl@0
  1592
		if (r == KErrNone)
sl@0
  1593
			{
sl@0
  1594
			TMediaPassword curPwd;
sl@0
  1595
sl@0
  1596
			curPwd = *aPasswordData.iOldPasswd;
sl@0
  1597
sl@0
  1598
			TInt curPwdLen = curPwd.Length();
sl@0
  1599
			TInt blockLen = 2 + curPwdLen;
sl@0
  1600
sl@0
  1601
			TPtr8 pbuf(&iMinorBuf[0], 2, blockLen);
sl@0
  1602
			pbuf[0] = 0;				// LOCK_UNLOCK = 0; SET_PWD = 0
sl@0
  1603
			pbuf[1] = static_cast<TUint8>(curPwdLen);
sl@0
  1604
			pbuf.Append(curPwd);
sl@0
  1605
			iSession->SetupCIMLockUnlock(blockLen, iMinorBuf);
sl@0
  1606
sl@0
  1607
			r = EngageAndSetWriteRequest(EMReqUpdatePtnInfo);
sl@0
  1608
			}
sl@0
  1609
		}
sl@0
  1610
sl@0
  1611
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lru:%d", r));
sl@0
  1612
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHRPIUNLOCK_EXIT, this, r );
sl@0
  1613
	return r;
sl@0
  1614
	}
sl@0
  1615
sl@0
  1616
sl@0
  1617
TInt DMmcMediaDriverFlash::LaunchRPIRead()
sl@0
  1618
//
sl@0
  1619
// launch read request on first KDiskSectorSize (512) bytes
sl@0
  1620
//
sl@0
  1621
	{
sl@0
  1622
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_LAUNCHRPIREAD_ENTRY, this );
sl@0
  1623
	__KTRACE_OPT(KPBUSDRV, Kern::Printf((">mmd:lrr")));
sl@0
  1624
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  1625
sl@0
  1626
	// the partition information is read before any other area is read from /
sl@0
  1627
	// written to, and so does not need to maintain cache coherence.  Therefore
sl@0
  1628
	// it can safely use the minor buffer.
sl@0
  1629
sl@0
  1630
	TInt r;
sl@0
  1631
	if ((r = CheckDevice(EMReqTypeNormalRd)) == KErrNone)
sl@0
  1632
		{
sl@0
  1633
		iIntBuf = iMinorBuf;
sl@0
  1634
		iSession->SetupCIMReadBlock(0, iIntBuf);	// aBlocks = 1
sl@0
  1635
		r = EngageAndSetReadRequest(EMReqPtnInfo);
sl@0
  1636
		}
sl@0
  1637
sl@0
  1638
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lrr:%d", r));
sl@0
  1639
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHRPIREAD_EXIT, this, r );
sl@0
  1640
	return r;
sl@0
  1641
	}
sl@0
  1642
sl@0
  1643
sl@0
  1644
TInt DMmcMediaDriverFlash::LaunchRPIErase()
sl@0
  1645
	{
sl@0
  1646
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_LAUNCHRPIERASE_ENTRY, this );
sl@0
  1647
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:lre:%d,%d", iCard->IsReady(), iCard->IsLocked()));
sl@0
  1648
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  1649
sl@0
  1650
	TInt r = KErrNone;
sl@0
  1651
sl@0
  1652
	// CMD42 is an adtc, so check state in same way as for write
sl@0
  1653
	if ((r = CheckDevice(EMReqTypeUnlockPswd)) == KErrNone)
sl@0
  1654
		{
sl@0
  1655
		if(iCard->IsWriteProtected())
sl@0
  1656
			{
sl@0
  1657
			r = KErrAccessDenied;
sl@0
  1658
			}
sl@0
  1659
		else
sl@0
  1660
			{
sl@0
  1661
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:df:EMReqForceErase"));
sl@0
  1662
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_LAUNCHRPIERASE_FORCE_ERASE, "Force erase");
sl@0
  1663
			iMinorBuf[0] = KMMCLockUnlockErase;
sl@0
  1664
			iSession->SetupCIMLockUnlock(1, iMinorBuf);
sl@0
  1665
			r = EngageAndSetWriteRequest(EMReqForceErase);
sl@0
  1666
			}
sl@0
  1667
		}
sl@0
  1668
sl@0
  1669
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:lru:%d", r));
sl@0
  1670
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_LAUNCHRPIERASE_EXIT, this, r );
sl@0
  1671
	return r;
sl@0
  1672
	}
sl@0
  1673
sl@0
  1674
sl@0
  1675
TInt DMmcMediaDriverFlash::DecodePartitionInfo()
sl@0
  1676
//
sl@0
  1677
// decode partition info that was read into internal buffer 
sl@0
  1678
//
sl@0
  1679
	{
sl@0
  1680
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_ENTRY, this );
sl@0
  1681
	TInt partitionCount=iPartitionInfo->iPartitionCount=0;
sl@0
  1682
	TInt defaultPartitionNumber=-1;
sl@0
  1683
	TMBRPartitionEntry* pe;
sl@0
  1684
	const TUint KMBRFirstPartitionOffsetAligned = KMBRFirstPartitionOffset & ~3;
sl@0
  1685
	TInt i;
sl@0
  1686
sl@0
  1687
	// Read of the first sector successful so check for a Master Boot Record
sl@0
  1688
	if (*(TUint16*)(&iIntBuf[KMBRSignatureOffset])!=0xAA55)
sl@0
  1689
		goto mbr_done;
sl@0
  1690
sl@0
  1691
	__ASSERT_COMPILE(KMBRFirstPartitionOffsetAligned + KMBRMaxPrimaryPartitions * sizeof(TMBRPartitionEntry) <= KMBRSignatureOffset);
sl@0
  1692
sl@0
  1693
	memmove(&iIntBuf[0], &iIntBuf[2],
sl@0
  1694
		KMBRFirstPartitionOffsetAligned + KMBRMaxPrimaryPartitions * sizeof(TMBRPartitionEntry)); 
sl@0
  1695
sl@0
  1696
sl@0
  1697
	for (i=0, pe = (TMBRPartitionEntry*)(&iIntBuf[KMBRFirstPartitionOffsetAligned]);
sl@0
  1698
		pe->iPartitionType != 0 && i < KMBRMaxPrimaryPartitions;i++,pe++)
sl@0
  1699
		{
sl@0
  1700
		if (pe->IsDefaultBootPartition())
sl@0
  1701
			{
sl@0
  1702
			SetPartitionEntry(&iPartitionInfo->iEntry[0],pe->iFirstSector,pe->iNumSectors);
sl@0
  1703
			defaultPartitionNumber=i;
sl@0
  1704
			partitionCount++;
sl@0
  1705
			break;
sl@0
  1706
			}
sl@0
  1707
		}
sl@0
  1708
sl@0
  1709
	// Now add any other partitions
sl@0
  1710
	for (i=0, pe = (TMBRPartitionEntry*)(&iIntBuf[KMBRFirstPartitionOffsetAligned]);
sl@0
  1711
		pe->iPartitionType != 0 && i < KMBRMaxPrimaryPartitions;i++,pe++)
sl@0
  1712
		{
sl@0
  1713
		TBool validPartition = ETrue;	// assume partition valid
sl@0
  1714
sl@0
  1715
		if (defaultPartitionNumber==i)
sl@0
  1716
			{
sl@0
  1717
			// Already sorted
sl@0
  1718
			}
sl@0
  1719
sl@0
  1720
		// FAT partition ?
sl@0
  1721
		else if (pe->IsValidDosPartition() || pe->IsValidFAT32Partition() || pe->IsValidExFATPartition())
sl@0
  1722
			{
sl@0
  1723
			SetPartitionEntry(&iPartitionInfo->iEntry[partitionCount],pe->iFirstSector,pe->iNumSectors);
sl@0
  1724
			__KTRACE_OPT(KLOCDPAGING, Kern::Printf("Mmc: FAT partition found at sector #%u", pe->iFirstSector));
sl@0
  1725
			OstTrace1(TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_FS,"FAT partition found at sector #%u", pe->iFirstSector);
sl@0
  1726
			partitionCount++;
sl@0
  1727
			}
sl@0
  1728
		else
sl@0
  1729
			{
sl@0
  1730
			validPartition = EFalse;
sl@0
  1731
			}
sl@0
  1732
		
sl@0
  1733
		if (validPartition && partitionCount == 1)
sl@0
  1734
			iHiddenSectors = pe->iFirstSector;
sl@0
  1735
sl@0
  1736
		}
sl@0
  1737
sl@0
  1738
	// Check the validity of the partition address boundaries
sl@0
  1739
	// If there is any
sl@0
  1740
	if(partitionCount > 0)
sl@0
  1741
		{
sl@0
  1742
		const TInt64 deviceSize = iCard->DeviceSize64();
sl@0
  1743
		TPartitionEntry& part = iPartitionInfo->iEntry[partitionCount - 1];
sl@0
  1744
		// Check that the card address space boundary is not exceeded by the last partition
sl@0
  1745
		// In case of only 1 partition in the media check also it
sl@0
  1746
		if(part.iPartitionBaseAddr + part.iPartitionLen > deviceSize)
sl@0
  1747
			{
sl@0
  1748
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("Mmc: MBR partition exceeds card memory space"));
sl@0
  1749
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_PARTCOUNT1, "MBR partition exceeds card memory space" );
sl@0
  1750
			// Adjust the partition length to card address boundary
sl@0
  1751
			part.iPartitionLen = (deviceSize - part.iPartitionBaseAddr);
sl@0
  1752
sl@0
  1753
			// Check that the base address contained valid information
sl@0
  1754
			if(part.iPartitionLen <= 0)
sl@0
  1755
				{
sl@0
  1756
				__KTRACE_OPT(KPBUSDRV, Kern::Printf("Mmc: Invalid base address"));
sl@0
  1757
				OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_PARTCOUNT2, "Invalid base address" );
sl@0
  1758
				// Invalid MBR - assume the boot sector is in the first sector
sl@0
  1759
				defaultPartitionNumber =-1; 
sl@0
  1760
				partitionCount=0;
sl@0
  1761
				}
sl@0
  1762
			}
sl@0
  1763
		// More than one partition. Go through all of them
sl@0
  1764
		if (partitionCount > 0)
sl@0
  1765
			{
sl@0
  1766
			for(i=partitionCount-1; i>0; i--)
sl@0
  1767
				{
sl@0
  1768
				const TPartitionEntry& curr = iPartitionInfo->iEntry[i];
sl@0
  1769
				TPartitionEntry& prev = iPartitionInfo->iEntry[i-1];
sl@0
  1770
				// Check if partitions overlap
sl@0
  1771
				if(curr.iPartitionBaseAddr < (prev.iPartitionBaseAddr + prev.iPartitionLen))
sl@0
  1772
					{
sl@0
  1773
					__KTRACE_OPT(KPBUSDRV, Kern::Printf("Mmc: Overlapping partitions"));
sl@0
  1774
					OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_PARTCOUNT3, "Overlapping partitions" );
sl@0
  1775
					// Adjust the partition length to not overlap the next partition
sl@0
  1776
					prev.iPartitionLen = (curr.iPartitionBaseAddr - prev.iPartitionBaseAddr);
sl@0
  1777
sl@0
  1778
					// Check that the base address contained valid information
sl@0
  1779
					if(prev.iPartitionLen <= 0)
sl@0
  1780
						{
sl@0
  1781
						__KTRACE_OPT(KPBUSDRV, Kern::Printf("Mmc: Invalid base address"));
sl@0
  1782
						OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_PARTCOUNT4, "Invalid base address" );
sl@0
  1783
						// Invalid MBR - assume the boot sector is in the first sector
sl@0
  1784
						defaultPartitionNumber=(-1); 
sl@0
  1785
						partitionCount=0;
sl@0
  1786
						}
sl@0
  1787
					}
sl@0
  1788
				}
sl@0
  1789
			}
sl@0
  1790
		}
sl@0
  1791
sl@0
  1792
mbr_done:
sl@0
  1793
	if (defaultPartitionNumber==(-1) && partitionCount==0)
sl@0
  1794
		{
sl@0
  1795
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("Mmc:PartitionInfo no MBR"));
sl@0
  1796
		OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_MBRDONE1, "No MBR" );
sl@0
  1797
		if (MBRMandatory(iCard))
sl@0
  1798
			{
sl@0
  1799
			// If the MBR is missing AND is required, we present a default partition entry to the local
sl@0
  1800
			// media subsystem, which will be updated when the media is finally formatted
sl@0
  1801
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("MBR mandatory, defining space for MBR + default partition"));
sl@0
  1802
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_MBRDONE2, "MBR mandatory, defining space for MBR + default partition" );
sl@0
  1803
			iMbrMissing = ETrue;
sl@0
  1804
			TInt r = CreateDefaultPartition();
sl@0
  1805
			if (r != KErrNone)
sl@0
  1806
			    {
sl@0
  1807
				OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_EXIT1, this, r );
sl@0
  1808
				return r;
sl@0
  1809
			    }
sl@0
  1810
			}
sl@0
  1811
		else
sl@0
  1812
			{
sl@0
  1813
			// Assume it has no MBR, and the Boot Sector is in the 1st sector
sl@0
  1814
			SetPartitionEntry(&iPartitionInfo->iEntry[0],0,I64LOW(iCard->DeviceSize64()>>KDiskSectorShift));
sl@0
  1815
			iHiddenSectors=0;
sl@0
  1816
			}
sl@0
  1817
		partitionCount=1;
sl@0
  1818
		}
sl@0
  1819
sl@0
  1820
	iPartitionInfo->iPartitionCount=partitionCount;
sl@0
  1821
	iPartitionInfo->iMediaSizeInBytes=TotalSizeInBytes();
sl@0
  1822
sl@0
  1823
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<Mmc:PartitionInfo (C:%d)",iPartitionInfo->iPartitionCount));
sl@0
  1824
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("     Partition1 (B:%xH L:%xH)",I64LOW(iPartitionInfo->iEntry[0].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[0].iPartitionLen)));
sl@0
  1825
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("     Partition2 (B:%xH L:%xH)",I64LOW(iPartitionInfo->iEntry[1].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[1].iPartitionLen)));
sl@0
  1826
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("     Partition3 (B:%xH L:%xH)",I64LOW(iPartitionInfo->iEntry[2].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[2].iPartitionLen)));
sl@0
  1827
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("     Partition4 (B:%xH L:%xH)",I64LOW(iPartitionInfo->iEntry[3].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[3].iPartitionLen)));
sl@0
  1828
	OstTraceDefExt4(OST_TRACE_CATEGORY_RND, TRACE_MMCDEBUG, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_PARTINFO1, "Partition1 (B:0x%x L:0x%x); Partition2 (B:0x%x L:0x%x)", I64LOW(iPartitionInfo->iEntry[0].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[0].iPartitionLen),I64LOW(iPartitionInfo->iEntry[1].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[1].iPartitionLen));
sl@0
  1829
	OstTraceDefExt4(OST_TRACE_CATEGORY_RND, TRACE_MMCDEBUG, DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_PARTINFO2, "Partition3 (B:0x%x L:0x%x); Partition4 (B:0x%x L:0x%x)", I64LOW(iPartitionInfo->iEntry[2].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[2].iPartitionLen),I64LOW(iPartitionInfo->iEntry[3].iPartitionBaseAddr),I64LOW(iPartitionInfo->iEntry[3].iPartitionLen));
sl@0
  1830
sl@0
  1831
#ifdef _DEBUG
sl@0
  1832
	TMBRPartitionEntry cPe;
sl@0
  1833
	if(GetDefaultPartitionInfo(cPe) == KErrNone)
sl@0
  1834
		{
sl@0
  1835
		pe = (TMBRPartitionEntry*)(&iIntBuf[0]);
sl@0
  1836
sl@0
  1837
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("-------------------------------------------"));
sl@0
  1838
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("-- Partition Entry Validation/Comparison --"));
sl@0
  1839
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("-------------------------------------------"));
sl@0
  1840
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("-- iX86BootIndicator [%02x:%02x] %c       -", pe->iX86BootIndicator, cPe.iX86BootIndicator, pe->iX86BootIndicator == cPe.iX86BootIndicator ? ' ' : 'X'));
sl@0
  1841
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--        iStartHead [%02x:%02x] %c       -", pe->iStartHead,        cPe.iStartHead,        pe->iStartHead        == cPe.iStartHead        ? ' ' : 'X'));
sl@0
  1842
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--      iStartSector [%02x:%02x] %c       -", pe->iStartSector,      cPe.iStartSector,      pe->iStartSector      == cPe.iStartSector      ? ' ' : 'X'));
sl@0
  1843
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--    iStartCylinder [%02x:%02x] %c       -", pe->iStartCylinder,    cPe.iStartCylinder,    pe->iStartCylinder    == cPe.iStartCylinder    ? ' ' : 'X'));
sl@0
  1844
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--    iPartitionType [%02x:%02x] %c       -", pe->iPartitionType,    cPe.iPartitionType,    pe->iPartitionType    == cPe.iPartitionType    ? ' ' : 'X'));
sl@0
  1845
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--          iEndHead [%02x:%02x] %c       -", pe->iEndHead,          cPe.iEndHead,          pe->iEndHead          == cPe.iEndHead          ? ' ' : 'X'));
sl@0
  1846
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--        iEndSector [%02x:%02x] %c       -", pe->iEndSector,        cPe.iEndSector,        pe->iEndSector        == cPe.iEndSector        ? ' ' : 'X'));
sl@0
  1847
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--      iEndCylinder [%02x:%02x] %c       -", pe->iEndCylinder,      cPe.iEndCylinder,      pe->iEndCylinder      == cPe.iEndCylinder      ? ' ' : 'X'));
sl@0
  1848
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--      iFirstSector [%08x:%08x] %c       -", pe->iFirstSector,      cPe.iFirstSector,      pe->iFirstSector      == cPe.iFirstSector      ? ' ' : 'X'));
sl@0
  1849
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("--       iNumSectors [%08x:%08x] %c       -", pe->iNumSectors,       cPe.iNumSectors,       pe->iNumSectors       == cPe.iNumSectors       ? ' ' : 'X'));
sl@0
  1850
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("-------------------------------------------"));
sl@0
  1851
		}
sl@0
  1852
#endif
sl@0
  1853
sl@0
  1854
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DECODEPARTITIONINFO_EXIT2, this, KErrNone );
sl@0
  1855
	return KErrNone;
sl@0
  1856
	}
sl@0
  1857
sl@0
  1858
sl@0
  1859
TInt DMmcMediaDriverFlash::WritePartitionInfo()
sl@0
  1860
/**
sl@0
  1861
	Write the default partition table to freshly formatted media
sl@0
  1862
	@return Standard Symbian OS Error Code
sl@0
  1863
 */
sl@0
  1864
	{
sl@0
  1865
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_WRITEPARTITIONINFO_ENTRY, this );
sl@0
  1866
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:wpi"));
sl@0
  1867
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  1868
sl@0
  1869
	TMBRPartitionEntry partitionEntry;
sl@0
  1870
	TInt err = GetDefaultPartitionInfo(partitionEntry);
sl@0
  1871
	if(err == KErrNone)
sl@0
  1872
		{
sl@0
  1873
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:MBR/Partition Table"));
sl@0
  1874
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    Boot ID          : %02xh", partitionEntry.iX86BootIndicator));
sl@0
  1875
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    Start Head       : %02xh", partitionEntry.iStartHead));
sl@0
  1876
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    Start Sector     : %02xh", partitionEntry.iStartSector));
sl@0
  1877
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    Start Cyclinder  : %02xh", partitionEntry.iStartCylinder));
sl@0
  1878
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    System ID        : %02xh", partitionEntry.iPartitionType));
sl@0
  1879
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    End Head         : %02xh", partitionEntry.iEndHead));
sl@0
  1880
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    End Sector       : %02xh", partitionEntry.iEndSector));
sl@0
  1881
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    End Cyclinder    : %02xh", partitionEntry.iEndCylinder));
sl@0
  1882
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    Relative Sector  : %08xh", partitionEntry.iFirstSector));
sl@0
  1883
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("    Number of Sectors: %08xh", partitionEntry.iNumSectors));
sl@0
  1884
		OstTraceExt5(TRACE_MMCDEBUG, DMMCMEDIADRIVERFLASH_WRITEPARTITIONINFO_PARTINFO1, "Boot ID=0x%02x; Start Head=0x%02x; Start Sector=0x%02x; Start Cyclinder=0x%02x; System ID=0x%02x", (TUint) partitionEntry.iX86BootIndicator, (TUint) partitionEntry.iStartHead, (TUint) partitionEntry.iStartSector, (TUint) partitionEntry.iStartCylinder, (TUint) partitionEntry.iPartitionType);
sl@0
  1885
		OstTraceExt5(TRACE_MMCDEBUG, DMMCMEDIADRIVERFLASH_WRITEPARTITIONINFO_PARTINFO2, "End Head=0x%02x; End Sector=0x%02x; End Cyclinder=0x%02x; Relative Sector=0x%08x; Number of Sectors=0x%08x", (TUint) partitionEntry.iEndHead, (TUint) partitionEntry.iEndSector, (TUint) partitionEntry.iEndCylinder, (TUint) partitionEntry.iFirstSector, (TUint) partitionEntry.iNumSectors);
sl@0
  1886
		//
sl@0
  1887
		// Clear all other partition entries and align the partition info into the minor buffer for writing...
sl@0
  1888
		//
sl@0
  1889
		memclr(iMinorBuf, KDiskSectorSize);
sl@0
  1890
		memcpy(&iMinorBuf[KMBRFirstPartitionEntry], &partitionEntry, sizeof(TMBRPartitionEntry));
sl@0
  1891
sl@0
  1892
		*(TUint16*)(&iMinorBuf[KMBRSignatureOffset]) = 0xAA55;
sl@0
  1893
sl@0
  1894
		iSession->SetupCIMWriteBlock(0, iMinorBuf);
sl@0
  1895
		
sl@0
  1896
		//
sl@0
  1897
		// Write the partition table and engage the read to validate and complete the mount process
sl@0
  1898
		//
sl@0
  1899
		iMbrMissing = EFalse;
sl@0
  1900
		iCreateMbr = EFalse;
sl@0
  1901
		err = EngageAndSetWriteRequest(EMReqUpdatePtnInfo);
sl@0
  1902
		}
sl@0
  1903
sl@0
  1904
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:wpi:%d", err));
sl@0
  1905
sl@0
  1906
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_WRITEPARTITIONINFO_EXIT, this, err );
sl@0
  1907
	return err;
sl@0
  1908
	}
sl@0
  1909
sl@0
  1910
sl@0
  1911
TInt DMmcMediaDriverFlash::CreateDefaultPartition()
sl@0
  1912
	{
sl@0
  1913
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_CREATEDEFAULTPARTITION_ENTRY, this );
sl@0
  1914
	TMBRPartitionEntry defPartition;
sl@0
  1915
	TInt r = GetDefaultPartitionInfo(defPartition);
sl@0
  1916
	if (r == KErrNone)
sl@0
  1917
		{
sl@0
  1918
		SetPartitionEntry(&iPartitionInfo->iEntry[0], defPartition.iFirstSector, defPartition.iNumSectors);
sl@0
  1919
		iHiddenSectors = defPartition.iFirstSector;
sl@0
  1920
		iPartitionInfo->iPartitionCount   = 1;
sl@0
  1921
		iPartitionInfo->iMediaSizeInBytes = TotalSizeInBytes();
sl@0
  1922
		}
sl@0
  1923
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_CREATEDEFAULTPARTITION_EXIT, this, r );
sl@0
  1924
	return r;
sl@0
  1925
	}
sl@0
  1926
sl@0
  1927
TInt DMmcMediaDriverFlash::GetDefaultPartitionInfo(TMBRPartitionEntry& aPartitionEntry)
sl@0
  1928
/**
sl@0
  1929
	Calculates the default patition information for an specific card.
sl@0
  1930
	@param aPartitionEntry The TMBRPartitionEntry to be filled in with the format parameters
sl@0
  1931
	@return Standard Symbian OS Error Code
sl@0
  1932
 */
sl@0
  1933
	{
sl@0
  1934
	memclr(&aPartitionEntry, sizeof(TMBRPartitionEntry));
sl@0
  1935
	TUint16 reservedSectors; // Not used
sl@0
  1936
	TInt r = GetMediaDefaultPartitionInfo(aPartitionEntry, reservedSectors, iCard);
sl@0
  1937
	return r;
sl@0
  1938
	}
sl@0
  1939
sl@0
  1940
sl@0
  1941
void DMmcMediaDriverFlash::SetPartitionEntry(TPartitionEntry* aEntry, TUint aFirstSector, TUint aNumSectors)
sl@0
  1942
//
sl@0
  1943
// auxiliary static function to record partition information in TPartitionEntry object
sl@0
  1944
//
sl@0
  1945
	{
sl@0
  1946
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_SETPARTITIONENTRY_ENTRY );
sl@0
  1947
	aEntry->iPartitionBaseAddr=aFirstSector;
sl@0
  1948
	aEntry->iPartitionBaseAddr<<=KDiskSectorShift;
sl@0
  1949
	aEntry->iPartitionLen=aNumSectors;
sl@0
  1950
	aEntry->iPartitionLen<<=KDiskSectorShift;
sl@0
  1951
	aEntry->iPartitionType=KPartitionTypeFAT12;	
sl@0
  1952
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_SETPARTITIONENTRY_EXIT );
sl@0
  1953
	}
sl@0
  1954
sl@0
  1955
TInt DMmcMediaDriverFlash::DoPasswordOp()
sl@0
  1956
	{
sl@0
  1957
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOPASSWORDOP_ENTRY, this );
sl@0
  1958
	// Reconstruct password data structure in our address space
sl@0
  1959
	TLocalDrivePasswordData clientData;
sl@0
  1960
	TInt r = iCurrentReq->ReadRemoteRaw(&clientData, sizeof(TLocalDrivePasswordData));
sl@0
  1961
sl@0
  1962
	TMediaPassword oldPassword;
sl@0
  1963
	if (r == KErrNone)
sl@0
  1964
		r = iCurrentReq->ReadRemote(clientData.iOldPasswd, &oldPassword);
sl@0
  1965
sl@0
  1966
	TMediaPassword newPassword;
sl@0
  1967
	if (r == KErrNone)
sl@0
  1968
		r = iCurrentReq->ReadRemote(clientData.iNewPasswd, &newPassword);
sl@0
  1969
sl@0
  1970
	TLocalDrivePasswordData passData(oldPassword, newPassword, clientData.iStorePasswd);
sl@0
  1971
sl@0
  1972
	if (r == KErrNone)
sl@0
  1973
		{
sl@0
  1974
		TInt id=iCurrentReq->Id();
sl@0
  1975
		switch (id)
sl@0
  1976
			{
sl@0
  1977
			case DLocalDrive::EPasswordUnlock:
sl@0
  1978
				r = LaunchRPIUnlock(passData);
sl@0
  1979
				__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:rpi:%d", r));
sl@0
  1980
				break;
sl@0
  1981
			case DLocalDrive::EPasswordLock:
sl@0
  1982
			case DLocalDrive::EPasswordClear:
sl@0
  1983
				PasswordControl(id, passData);	
sl@0
  1984
				break;
sl@0
  1985
			}
sl@0
  1986
		}
sl@0
  1987
		
sl@0
  1988
	// This will complete the request in the event of an error
sl@0
  1989
	if(r != KErrNone)
sl@0
  1990
		PartitionInfoComplete(r);
sl@0
  1991
sl@0
  1992
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_DOPASSWORDOP_EXIT, this, KErrNone );
sl@0
  1993
	return KErrNone; // ensures to indicate asynchronoous completion
sl@0
  1994
	}
sl@0
  1995
sl@0
  1996
void DMmcMediaDriverFlash::PasswordControl(TInt aFunc, TLocalDrivePasswordData& aData)
sl@0
  1997
//
sl@0
  1998
// Change a card's password, or clear the pasword from a locked card.  The card
sl@0
  1999
// must be unlocked for this function.  A locked card is unlocked when it is mounted,
sl@0
  2000
// to read the partition information.  This is done from ReadPartitionInfo() and
sl@0
  2001
// LaunchRPIUnlock().
sl@0
  2002
//
sl@0
  2003
	{
sl@0
  2004
	OstTraceExt2(TRACE_FLOW, DMMCMEDIADRIVERFLASH_PASSWORDCONTROL_ENTRY ,"DMmcMediaDriverFlash::PasswordControl;aFunc=%d;this=%x", aFunc, (TUint) this);
sl@0
  2005
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:pc:%d", (TInt) aFunc));
sl@0
  2006
	__ASSERT_DEBUG(CurrentRequest() == EMReqIdle, Panic(EPCInUse));
sl@0
  2007
	__ASSERT_DEBUG(aFunc == DLocalDrive::EPasswordLock || aFunc == DLocalDrive::EPasswordClear, Panic(EPCFunc));
sl@0
  2008
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  2009
sl@0
  2010
	TInt r;
sl@0
  2011
sl@0
  2012
	if ((r = CheckDevice(EMReqTypeChangePswd)) == KErrNone)
sl@0
  2013
		{
sl@0
  2014
		// check if the current password is correct here.  (This makes the
sl@0
  2015
		// clear operation redundant only if the password is stored and it
sl@0
  2016
		// is wrong.)  Complete with same value as DoSessionEndDfc() would.
sl@0
  2017
sl@0
  2018
		TMediaPassword curPwd;
sl@0
  2019
		
sl@0
  2020
		curPwd = *aData.iOldPasswd;
sl@0
  2021
		TInt curPwdLen = curPwd.Length();
sl@0
  2022
		TInt blockLen;
sl@0
  2023
sl@0
  2024
		if (!(iCard->iFlags & KMMCardIsLockable))
sl@0
  2025
			r = KErrNotSupported;
sl@0
  2026
		else if (Stack().PasswordStore()->IsMappingIncorrect(iCard->CID(), curPwd))
sl@0
  2027
			r = KErrAccessDenied;
sl@0
  2028
		else
sl@0
  2029
			{
sl@0
  2030
			if ((r = Stack().MMCSocket()->PrepareStore(CardNum(), aFunc, aData/*, aThread*/)) == KErrNone)
sl@0
  2031
				{
sl@0
  2032
				switch (aFunc)
sl@0
  2033
					{
sl@0
  2034
				case DLocalDrive::EPasswordLock:
sl@0
  2035
					{
sl@0
  2036
					TMediaPassword newPwd;
sl@0
  2037
					newPwd = *aData.iNewPasswd;
sl@0
  2038
					TInt newPwdLen = newPwd.Length();
sl@0
  2039
					blockLen = 1 + 1 + curPwdLen + newPwdLen;
sl@0
  2040
					
sl@0
  2041
					#ifndef __EPOC32__
sl@0
  2042
					TUint16 env_Var[]=L"_EPOC_PWD_LEN";
sl@0
  2043
					TUint16 env_Val[2];
sl@0
  2044
					env_Val[0]=(TUint16)(curPwdLen+1);
sl@0
  2045
					env_Val[1]=0;//make a null terminated string
sl@0
  2046
					r=SetEnvironmentVariable(env_Var,&env_Val[0]);
sl@0
  2047
					__ASSERT_DEBUG(r!=0, Panic(EPCFunc));
sl@0
  2048
					
sl@0
  2049
					#endif
sl@0
  2050
					
sl@0
  2051
					TPtr8 pbuf(&iMinorBuf[0], 2, blockLen);
sl@0
  2052
					pbuf[0] = KMMCLockUnlockSetPwd; 	// LOCK_UNLOCK = 0, SET_PWD = 1
sl@0
  2053
					pbuf[1] = static_cast<TUint8>(curPwdLen + newPwdLen);
sl@0
  2054
					pbuf.Append(curPwd);
sl@0
  2055
					pbuf.Append(newPwd);
sl@0
  2056
					}
sl@0
  2057
					break;
sl@0
  2058
sl@0
  2059
				case DLocalDrive::EPasswordClear:
sl@0
  2060
					{
sl@0
  2061
					blockLen = 1 + 1 + curPwdLen;
sl@0
  2062
sl@0
  2063
					TPtr8 pbuf(&iMinorBuf[0], 2, blockLen);
sl@0
  2064
					pbuf[0] = KMMCLockUnlockClrPwd; 	// LOCK_UNLOCK = dc, CLR_PWD = 1
sl@0
  2065
					pbuf[1] = static_cast<TUint8>(curPwdLen);
sl@0
  2066
					pbuf.Append(curPwd);
sl@0
  2067
					}
sl@0
  2068
					break;
sl@0
  2069
sl@0
  2070
				default:
sl@0
  2071
					// DLocalDrive::EPasswordUnlock is not handled.  This avoids warnings for unused
sl@0
  2072
					// case, and uninitialized variable.
sl@0
  2073
					blockLen = 0;
sl@0
  2074
					break;
sl@0
  2075
					}	// switch (aFunc)
sl@0
  2076
sl@0
  2077
				iSession->SetupCIMLockUnlock(blockLen, iMinorBuf);
sl@0
  2078
				r = EngageAndSetWriteRequest(EMReqPswdCtrl);
sl@0
  2079
				}	// if ((r = Stack().PrepareStore(CardNum(), aFunc, aData, aThread)) == KErrNone)
sl@0
  2080
			}	// else (Stack().IsMappingIncorrect(iCard->CID(), curPwd))
sl@0
  2081
		}	// (r = CheckDevice(EMReqTypeChangePswd)) == KErrNone
sl@0
  2082
sl@0
  2083
	// complete immediately if error occured
sl@0
  2084
	if (r != KErrNone)
sl@0
  2085
		CompleteRequest(r);
sl@0
  2086
sl@0
  2087
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:pc:%d", r));
sl@0
  2088
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_PASSWORDCONTROL_EXIT, this );
sl@0
  2089
	}
sl@0
  2090
sl@0
  2091
sl@0
  2092
// ---- device status, callback DFC ----
sl@0
  2093
sl@0
  2094
TInt DMmcMediaDriverFlash::CheckDevice(TMediaReqType aReqType)
sl@0
  2095
//
sl@0
  2096
// Check the device before initiating a command
sl@0
  2097
//
sl@0
  2098
	{
sl@0
  2099
	OstTraceExt2(TRACE_FLOW, DMMCMEDIADRIVERFLASH_CHECKDEVICE_ENTRY, "DMmcMediaDriverFlash::CheckDevice;aReqType=%d;this=%x", (TInt) aReqType, (TUint) this);
sl@0
  2100
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:cd:%d",aReqType));
sl@0
  2101
sl@0
  2102
	TInt r=KErrNone;
sl@0
  2103
sl@0
  2104
	if (!iCard->IsReady())
sl@0
  2105
		r=KErrNotReady;
sl@0
  2106
sl@0
  2107
	// The card must be locked if attempting to unlock during RPI, and
sl@0
  2108
	// unlocked at all other times.
sl@0
  2109
	else if (aReqType!=EMReqTypeUnlockPswd && iCard->IsLocked())
sl@0
  2110
		r=KErrLocked;
sl@0
  2111
	// Don't perform Password setting for WriteProtected cards, 
sl@0
  2112
	// unable to recover (ForcedErase) if password lost.
sl@0
  2113
	else if (aReqType==EMReqTypeChangePswd)
sl@0
  2114
		{
sl@0
  2115
		if (iCard->MediaType()==EMultiMediaROM)
sl@0
  2116
			{
sl@0
  2117
			r=KErrAccessDenied;
sl@0
  2118
			}
sl@0
  2119
		}
sl@0
  2120
	else if (iMbrMissing && aReqType==EMReqTypeNormalRd)
sl@0
  2121
		r=KErrCorrupt;
sl@0
  2122
sl@0
  2123
#if !defined(__WINS__)
sl@0
  2124
	// Don't perform write/password operations when the battery is low
sl@0
  2125
//	else if (aReqType!=EMReqTypeNormalRd && Hal::MainBatteryStatus()<ELow && !Hal::ExternalPowerPresent())
sl@0
  2126
//		r=KErrBadPower;
sl@0
  2127
#endif
sl@0
  2128
	// Don't perform write operations when the mechanical write protect switch is set
sl@0
  2129
	else if (aReqType==EMReqTypeNormalWr && iCard->IsWriteProtected())
sl@0
  2130
		r=KErrAccessDenied;
sl@0
  2131
	// Don't perform write/format operations on MMC ROM cards
sl@0
  2132
	else if (iMediaType==EMultiMediaROM && aReqType == EMReqTypeNormalWr)
sl@0
  2133
		r=KErrAccessDenied;
sl@0
  2134
sl@0
  2135
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:cd:%d", r));
sl@0
  2136
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_CHECKDEVICE_EXIT, this, r );
sl@0
  2137
	return r;
sl@0
  2138
	}
sl@0
  2139
sl@0
  2140
void DMmcMediaDriverFlash::SessionEndCallBack(TAny* aMediaDriver)
sl@0
  2141
//
sl@0
  2142
// called by EPBUS when a single session has finished.  Queues DFC to launch
sl@0
  2143
// next session or to complete client request.
sl@0
  2144
//
sl@0
  2145
	{
sl@0
  2146
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_SESSIONENDCALLBACK_ENTRY );
sl@0
  2147
	DMmcMediaDriverFlash& md = *static_cast<DMmcMediaDriverFlash*>(aMediaDriver);
sl@0
  2148
	__ASSERT_DEBUG(! md.iSessionEndDfc.Queued(), Panic(ESECBQueued));
sl@0
  2149
	md.iSessionEndDfc.Enque();
sl@0
  2150
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_SESSIONENDCALLBACK_EXIT );
sl@0
  2151
	}
sl@0
  2152
sl@0
  2153
sl@0
  2154
void DMmcMediaDriverFlash::SessionEndDfc(TAny* aMediaDriver)
sl@0
  2155
	{
sl@0
  2156
	static_cast<DMmcMediaDriverFlash*>(aMediaDriver)->DoSessionEndDfc();
sl@0
  2157
	}
sl@0
  2158
sl@0
  2159
sl@0
  2160
void DMmcMediaDriverFlash::DoSessionEndDfc()
sl@0
  2161
//
sl@0
  2162
// launch next session or complete client request
sl@0
  2163
//
sl@0
  2164
	{
sl@0
  2165
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOSESSIONENDDFC_ENTRY, this );
sl@0
  2166
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:dsed:%d", CurrentRequest()));
sl@0
  2167
	OstTrace1( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOSESSIONENDDFC_REQUEST, "Current Request=%d", CurrentRequest());
sl@0
  2168
sl@0
  2169
	TInt r=KErrNone;
sl@0
  2170
sl@0
  2171
	EndInCritical();
sl@0
  2172
sl@0
  2173
	// Abort if writing or formatting and power has gone down
sl@0
  2174
	if (!Kern::PowerGood() && CurrentRequest()!=EMReqRead)
sl@0
  2175
		r=KErrAbort;
sl@0
  2176
	// Return KErrNotReady if we have has a deferred media change
sl@0
  2177
	if (!iCard->IsReady())
sl@0
  2178
		r=KErrNotReady;
sl@0
  2179
	// if stack has powered down session pointer will be NULL 
sl@0
  2180
	if (iSession == NULL)
sl@0
  2181
		r = KErrNotReady;
sl@0
  2182
sl@0
  2183
	TBool complete = ETrue;
sl@0
  2184
sl@0
  2185
	if (r==KErrNone)
sl@0
  2186
		{
sl@0
  2187
		r = iSession->EpocErrorCode();
sl@0
  2188
sl@0
  2189
		switch (CurrentRequest())
sl@0
  2190
			{
sl@0
  2191
			case EMReqRead:
sl@0
  2192
				{
sl@0
  2193
				if (r != KErrNone)						// abort if MMC error
sl@0
  2194
					break;
sl@0
  2195
				
sl@0
  2196
				if(iDoDoubleBuffer)
sl@0
  2197
					{
sl@0
  2198
					//
sl@0
  2199
					// This is the end of a double-buffered transfer.
sl@0
  2200
					//  - Now we have two buffers to copy back to the user...
sl@0
  2201
					//
sl@0
  2202
					TUint8* bufPtr = iIntBuf + (iSecondBuffer ? (iMaxBufSize >> 1) : 0);
sl@0
  2203
					if((r = WriteDataToUser(bufPtr)) == KErrNone)
sl@0
  2204
						{
sl@0
  2205
						MarkBlocks(iReqCur, iPhysEnd, CchMemToIdx(bufPtr));
sl@0
  2206
sl@0
  2207
						iReqCur  = iPhysEnd;
sl@0
  2208
						iPhysEnd = iDbEnd;
sl@0
  2209
sl@0
  2210
						bufPtr = iIntBuf + (iSecondBuffer ? 0 : (iMaxBufSize >> 1));
sl@0
  2211
						if((r = WriteDataToUser(bufPtr)) == KErrNone)
sl@0
  2212
							{
sl@0
  2213
							MarkBlocks(iReqCur, (iPhysEnd + iBlkMsk) & ~iBlkMsk, CchMemToIdx(bufPtr));
sl@0
  2214
							}
sl@0
  2215
						}
sl@0
  2216
					iDoDoubleBuffer = EFalse;
sl@0
  2217
					}
sl@0
  2218
				else if (iDoPhysicalAddress)
sl@0
  2219
					{
sl@0
  2220
					if (iRdROB & KIPCWrite)
sl@0
  2221
						{
sl@0
  2222
						// partial end point
sl@0
  2223
						TInt len = I64LOW(iReqEnd & iBlkMsk);
sl@0
  2224
						const TInt ofset = I64LOW(iPhysEnd - iBlkLen - iReqStart);								
sl@0
  2225
				
sl@0
  2226
						TPtrC8 extrView(iIntBuf, len);
sl@0
  2227
						r = iCurrentReq->WriteRemote(&extrView,ofset);
sl@0
  2228
						}
sl@0
  2229
					// Reset attributes
sl@0
  2230
					iRdROB = 0;
sl@0
  2231
					iFragOfset = iIPCLen = iBufOfset = 0;
sl@0
  2232
					iReqCur = iPhysEnd = iReqEnd;					
sl@0
  2233
					iDoPhysicalAddress = EFalse;
sl@0
  2234
					}
sl@0
  2235
				else
sl@0
  2236
					{
sl@0
  2237
					r = WriteDataToUser(&iIntBuf[I64LOW(iReqCur - iPhysStart)]);
sl@0
  2238
					}
sl@0
  2239
sl@0
  2240
				if (r != KErrNone)
sl@0
  2241
					break;
sl@0
  2242
sl@0
  2243
				// if there is more information to read for the user then engage another session
sl@0
  2244
				if ((iReqCur = iPhysEnd) < iReqEnd)
sl@0
  2245
					{
sl@0
  2246
					TBool allDone = EFalse;
sl@0
  2247
					if ( ((r = ReadDataUntilCacheExhausted(&allDone)) == KErrNone) && !allDone)
sl@0
  2248
						{
sl@0
  2249
						iPhysStart = iReqCur & ~iBlkMsk;
sl@0
  2250
						TUint32 length = I64LOW(iReqEnd - iReqCur);
sl@0
  2251
		
sl@0
  2252
						if ( (iReqEnd - iPhysStart) > iMaxBufSize && iSocket->SupportsDoubleBuffering() && !iReadToEndOfCard)
sl@0
  2253
							r = LaunchDBRead();				
sl@0
  2254
						else
sl@0
  2255
							r = LaunchRead(iReqCur, length);
sl@0
  2256
						
sl@0
  2257
						if ( r == KErrNone)
sl@0
  2258
							complete = EFalse;
sl@0
  2259
						}
sl@0
  2260
					}
sl@0
  2261
				}
sl@0
  2262
				break;
sl@0
  2263
sl@0
  2264
			case EMReqWrite:
sl@0
  2265
				{				
sl@0
  2266
				if (r != KErrNone)						// abort if MMC error
sl@0
  2267
					{
sl@0
  2268
					break;
sl@0
  2269
					}
sl@0
  2270
sl@0
  2271
				if (iWtRBM == 0)
sl@0
  2272
					{
sl@0
  2273
					iReqCur = iPhysEnd;
sl@0
  2274
					iDoDoubleBuffer = EFalse;
sl@0
  2275
					iDoPhysicalAddress = EFalse;
sl@0
  2276
					iRdROB = 0;
sl@0
  2277
					iFragOfset = iIPCLen = iBufOfset = 0;
sl@0
  2278
					}
sl@0
  2279
				// clear current RBM flag
sl@0
  2280
				else
sl@0
  2281
					{
sl@0
  2282
					if (iWtRBM & KWtRBMFst)
sl@0
  2283
						{
sl@0
  2284
						iWtRBM &= ~KWtRBMFst;
sl@0
  2285
						}
sl@0
  2286
					else if (iWtRBM & KWtRBMLst)
sl@0
  2287
						{
sl@0
  2288
						iWtRBM &= ~KWtRBMLst;
sl@0
  2289
						}
sl@0
  2290
					}
sl@0
  2291
sl@0
  2292
				// advance media position if just finished write, as opposed to read-before-modify
sl@0
  2293
				if (iReqCur < iReqEnd)
sl@0
  2294
					{
sl@0
  2295
					if ((r = LaunchWrite(iReqCur, I64LOW(iReqEnd - iReqCur), EMReqWrite)) == KErrNone)
sl@0
  2296
						{
sl@0
  2297
						complete = EFalse;
sl@0
  2298
						}
sl@0
  2299
sl@0
  2300
					complete = (r != KErrNone) ? (TBool)ETrue : (TBool)EFalse;
sl@0
  2301
					}
sl@0
  2302
				}
sl@0
  2303
				break;
sl@0
  2304
sl@0
  2305
			case EMReqFormat:
sl@0
  2306
				{
sl@0
  2307
				if (r != KErrNone)						// abort if MMC error
sl@0
  2308
					break;
sl@0
  2309
sl@0
  2310
				if ((iEraseUnitMsk == KMaxTUint64) ||	// no erase unit defined (Erase Class Commands not supported) ?
sl@0
  2311
					(iPhysEnd == iReqEnd) ||			// finshed already ?
sl@0
  2312
					((iPhysStart & iEraseUnitMsk) == 0 && (iPhysEnd & iEraseUnitMsk) == 0))
sl@0
  2313
					{
sl@0
  2314
					iReqCur = iPhysEnd;
sl@0
  2315
					}
sl@0
  2316
				else
sl@0
  2317
					{
sl@0
  2318
					// Formating to a mis-aligned boundary, so we can't make best use of
sl@0
  2319
					// multiple erase blocks.  We shall simply erase up to the next block
sl@0
  2320
					// boundary, and return the adjustment info to the file system
sl@0
  2321
					r = I64LOW(iPhysEnd - iPhysStart);
sl@0
  2322
					iReqCur = iReqEnd;
sl@0
  2323
					}
sl@0
  2324
sl@0
  2325
				if(r == KErrNone)
sl@0
  2326
					{
sl@0
  2327
					// advance media position if just finished write, as opposed to read-before-modify
sl@0
  2328
					if (iReqCur < iReqEnd)
sl@0
  2329
						{
sl@0
  2330
						if ((r = LaunchFormat(iReqCur, I64LOW(iReqEnd - iReqCur))) == KErrNone)
sl@0
  2331
							{
sl@0
  2332
							complete = EFalse;
sl@0
  2333
							}
sl@0
  2334
						}
sl@0
  2335
					// if format finished, write an MBR if required
sl@0
  2336
					// Always write an MBR if it's an SD card
sl@0
  2337
					else if (iCreateMbr)
sl@0
  2338
						{
sl@0
  2339
						// Finished Format, so write the MBR/default partition table if required
sl@0
  2340
						r = WritePartitionInfo();
sl@0
  2341
						complete = (r != KErrNone) ? (TBool)ETrue : (TBool)EFalse;
sl@0
  2342
						}
sl@0
  2343
					}
sl@0
  2344
				}
sl@0
  2345
				break;
sl@0
  2346
sl@0
  2347
			case EMReqPtnInfo:
sl@0
  2348
				if (r == KErrNone)
sl@0
  2349
					r = DecodePartitionInfo();		// set up iPartitionInfo
sl@0
  2350
sl@0
  2351
				PartitionInfoComplete(r == KErrNone?KErrNone:KErrNotReady);
sl@0
  2352
				break;
sl@0
  2353
				
sl@0
  2354
			case EMReqEMMCPtnInfo:
sl@0
  2355
				iMedReq = EMReqIdle;
sl@0
  2356
				// For now do nothing..
sl@0
  2357
				break;				
sl@0
  2358
				
sl@0
  2359
			case EMReqUpdatePtnInfo:
sl@0
  2360
				break;
sl@0
  2361
sl@0
  2362
			case EMReqPswdCtrl:
sl@0
  2363
				if (r == KErrLocked)
sl@0
  2364
					r = KErrAccessDenied;
sl@0
  2365
				break;
sl@0
  2366
sl@0
  2367
			case EMReqForceErase:
sl@0
  2368
				
sl@0
  2369
				if (r == KErrNone)
sl@0
  2370
					{
sl@0
  2371
					// Finished Forced Erase , so write the default partition table...
sl@0
  2372
					r = WritePartitionInfo();
sl@0
  2373
					}
sl@0
  2374
sl@0
  2375
				complete = (r != KErrNone) ? (TBool)ETrue : (TBool)EFalse;
sl@0
  2376
				break;
sl@0
  2377
sl@0
  2378
			case EMReqWritePasswordData:
sl@0
  2379
				// 
sl@0
  2380
				// WritePasswordData also kicks off an auto-unlock session to ensure that
sl@0
  2381
				// any locked cards that have passwords in the password store are immediately
sl@0
  2382
				// available.  We can safely ignore any errors returned at this stage, as the
sl@0
  2383
				// password store will have been successfully updated (in locmedia.cpp), even
sl@0
  2384
				// if the card is unable to accept the password.
sl@0
  2385
				//
sl@0
  2386
				r = KErrNone;
sl@0
  2387
				break;
sl@0
  2388
				
sl@0
  2389
			case EMReqIdle:
sl@0
  2390
				// request has been completed already (e.g. due to a power down)
sl@0
  2391
				break;
sl@0
  2392
sl@0
  2393
sl@0
  2394
			default:
sl@0
  2395
				__ASSERT_DEBUG(EFalse, Panic(EDSEDRequest));
sl@0
  2396
				break;
sl@0
  2397
			}
sl@0
  2398
		}
sl@0
  2399
sl@0
  2400
	// r != KErrNone => complete
sl@0
  2401
	__ASSERT_DEBUG(!(r != KErrNone) || complete, Panic(EDSEDNotErrComplete));
sl@0
  2402
sl@0
  2403
	if (complete)
sl@0
  2404
		{
sl@0
  2405
		if (r != KErrNone)
sl@0
  2406
			InvalidateCache();
sl@0
  2407
sl@0
  2408
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mdf:dsed:cmp:%d", r));
sl@0
  2409
		OstTrace1( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOSESSIONENDDFC_COMPLETE, "Complete request; retval=%d", r);
sl@0
  2410
		CompleteRequest(r);
sl@0
  2411
		}
sl@0
  2412
	else
sl@0
  2413
		{
sl@0
  2414
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mdf:dsed:ncmp"));
sl@0
  2415
		OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_DOSESSIONENDDFC_NOT_COMPLETE, "Request not complete");
sl@0
  2416
		}
sl@0
  2417
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOSESSIONENDDFC_EXIT, this );
sl@0
  2418
	}
sl@0
  2419
sl@0
  2420
void DMmcMediaDriverFlash::DataTransferCallBack(TAny* aMediaDriver)
sl@0
  2421
	{
sl@0
  2422
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_DATATRANSFERCALLBACK_ENTRY );
sl@0
  2423
	DMmcMediaDriverFlash& md = *static_cast<DMmcMediaDriverFlash*>(aMediaDriver);
sl@0
  2424
	__ASSERT_DEBUG(! md.iDataTransferCallBackDfc.Queued(), Panic(EDBCBQueued));
sl@0
  2425
	md.iDataTransferCallBackDfc.Enque();
sl@0
  2426
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_DATATRANSFERCALLBACK_EXIT );
sl@0
  2427
	}
sl@0
  2428
sl@0
  2429
void DMmcMediaDriverFlash::DataTransferCallBackDfc(TAny* aMediaDriver)
sl@0
  2430
	{
sl@0
  2431
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_DATATRANSFERCALLBACKDFC_ENTRY );
sl@0
  2432
	DMmcMediaDriverFlash& md = *static_cast<DMmcMediaDriverFlash*>(aMediaDriver);
sl@0
  2433
sl@0
  2434
	if (md.iDoPhysicalAddress)
sl@0
  2435
		{
sl@0
  2436
		if(md.CurrentRequest() == EMReqWrite)
sl@0
  2437
			{
sl@0
  2438
			md.DoPhysWriteDataTransferCallBack();
sl@0
  2439
			}
sl@0
  2440
		else
sl@0
  2441
			{
sl@0
  2442
			md.DoPhysReadDataTransferCallBack();
sl@0
  2443
			}
sl@0
  2444
		}
sl@0
  2445
	else
sl@0
  2446
		{
sl@0
  2447
		if(md.CurrentRequest() == EMReqWrite)
sl@0
  2448
			{
sl@0
  2449
			md.DoWriteDataTransferCallBack();
sl@0
  2450
			}
sl@0
  2451
		else
sl@0
  2452
			{
sl@0
  2453
			md.DoReadDataTransferCallBack();
sl@0
  2454
			}
sl@0
  2455
		}
sl@0
  2456
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_DATATRANSFERCALLBACKDFC_EXIT );
sl@0
  2457
	}
sl@0
  2458
sl@0
  2459
void DMmcMediaDriverFlash::DoPhysWriteDataTransferCallBack()
sl@0
  2460
	{
sl@0
  2461
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOPHYSWRITEDATATRANSFERCALLBACK_ENTRY, this );
sl@0
  2462
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("++DMmcMediaDriverFlash::DoPhysWriteDataTransferCallBack()"));
sl@0
  2463
sl@0
  2464
	TInt err = KErrNone;
sl@0
  2465
		
sl@0
  2466
	if ( (iRdROB & KIPCSetup) || ((iReqEnd - iPhysEnd) < iBlkLen) )
sl@0
  2467
		{
sl@0
  2468
		//IPC to be setup, or partial end block read
sl@0
  2469
		iRdROB &= ~KIPCSetup;
sl@0
  2470
sl@0
  2471
		if ((iReqEnd - iPhysEnd) < iBlkLen)
sl@0
  2472
			{
sl@0
  2473
			iIntBuf = iCacheBuf;
sl@0
  2474
			}
sl@0
  2475
		else
sl@0
  2476
			{	
sl@0
  2477
			TPtr8 tgt(iMinorBuf, iBlkLen);				
sl@0
  2478
			err = ReadDataFromUser(tgt, I64LOW(iPhysEnd-iReqStart));
sl@0
  2479
			iIntBuf = iMinorBuf;
sl@0
  2480
			}			
sl@0
  2481
sl@0
  2482
		iReqCur = iPhysEnd;
sl@0
  2483
		iPhysEnd += iBlkLen;
sl@0
  2484
		iBufOfset = 0;
sl@0
  2485
		iIPCLen = iBlkLen;
sl@0
  2486
sl@0
  2487
#if !defined(__WINS__)
sl@0
  2488
		iSession->MoreDataAvailable( (TInt)(iBlkLen >> KDiskSectorShift), (TUint8*)Epoc::LinearToPhysical((TLinAddr) iIntBuf), err);			
sl@0
  2489
#else
sl@0
  2490
		iSession->MoreDataAvailable( (TInt)(iBlkLen >> KDiskSectorShift), iIntBuf, err);
sl@0
  2491
#endif
sl@0
  2492
		__KTRACE_OPT(KPBUSDRV, 	Kern::Printf("--iDoPhysicalAddress(KIPCSetup)"));
sl@0
  2493
		OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOPHYSWRITEDATATRANSFERCALLBACK_EXIT1, this );
sl@0
  2494
		return;
sl@0
  2495
		}
sl@0
  2496
	
sl@0
  2497
	PrepareNextPhysicalFragment();
sl@0
  2498
sl@0
  2499
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("--DMmcMediaDriverFlash::DoPhysWriteDataTransferCallBack()"));
sl@0
  2500
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOPHYSWRITEDATATRANSFERCALLBACK_EXIT2, this );
sl@0
  2501
	}
sl@0
  2502
sl@0
  2503
sl@0
  2504
void DMmcMediaDriverFlash::DoPhysReadDataTransferCallBack()
sl@0
  2505
	{
sl@0
  2506
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOPHYSREADDATATRANSFERCALLBACK_ENTRY, this );
sl@0
  2507
	__KTRACE_OPT(KPBUSDRV, 	Kern::Printf("++DMmcMediaDriverFlash::DoPhysReadTransferCallBack()"));
sl@0
  2508
sl@0
  2509
	TInt err = KErrNone;
sl@0
  2510
	
sl@0
  2511
	if ((iRdROB & KIPCWrite) && !iSecondBuffer)
sl@0
  2512
		{
sl@0
  2513
		// an IPC transfer completed
sl@0
  2514
		iRdROB &= ~KIPCWrite;
sl@0
  2515
		if(iNxtIPCLen)
sl@0
  2516
			{
sl@0
  2517
			// First transfer is an IPC, 
sl@0
  2518
			// Corner-case - transfer is most likely IPC-DMA-IPC, 
sl@0
  2519
			// because write cannot occur until after the first 2 iterations it is possible to arrive here with both IPCSetup & IPCWrite Set. 
sl@0
  2520
			// need to use iIPCNxtLen instead
sl@0
  2521
			TPtrC8 extrView(&iIntBuf[iBufOfset], iNxtIPCLen);
sl@0
  2522
			err = iCurrentReq->WriteRemote(&extrView,I64LOW(iReqCur - iReqStart));
sl@0
  2523
			iNxtIPCLen = iBufOfset = 0;  
sl@0
  2524
			}
sl@0
  2525
		else
sl@0
  2526
			{
sl@0
  2527
			TPtrC8 extrView(&iIntBuf[iBufOfset], iIPCLen);
sl@0
  2528
			err = iCurrentReq->WriteRemote(&extrView,I64LOW(iReqCur - iReqStart));
sl@0
  2529
			iIPCLen = iBufOfset = 0;     
sl@0
  2530
			}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
sl@0
  2531
		}
sl@0
  2532
	
sl@0
  2533
	if ( (iRdROB & KIPCSetup) || ((iReqEnd - iPhysEnd) < iBlkLen) )
sl@0
  2534
		{
sl@0
  2535
		// IPC to be setup, or partial end block read.
sl@0
  2536
		iRdROB &= ~KIPCSetup;
sl@0
  2537
		iRdROB |= KIPCWrite;
sl@0
  2538
		
sl@0
  2539
		iIntBuf = ReserveReadBlocks(iPhysEnd,(iPhysEnd+iBlkLen), &iIPCLen);
sl@0
  2540
sl@0
  2541
		iReqCur = iPhysEnd;
sl@0
  2542
		iPhysEnd += iIPCLen;
sl@0
  2543
		iBufOfset = 0;
sl@0
  2544
#if !defined(__WINS__)
sl@0
  2545
		iSession->MoreDataAvailable( (TInt)(iIPCLen  >> KDiskSectorShift), (TUint8*)Epoc::LinearToPhysical((TLinAddr) iIntBuf), err);			
sl@0
  2546
#else
sl@0
  2547
		iSession->MoreDataAvailable( (TInt)(iIPCLen  >> KDiskSectorShift), iIntBuf, err);			
sl@0
  2548
#endif
sl@0
  2549
		iSecondBuffer = ETrue;
sl@0
  2550
		__KTRACE_OPT(KPBUSDRV, 	Kern::Printf("--iDoPhysicalAddress(KIPCWrite)"));
sl@0
  2551
		OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOPHYSREADDATATRANSFERCALLBACK_EXIT1, this );
sl@0
  2552
		return;
sl@0
  2553
		}
sl@0
  2554
sl@0
  2555
	PrepareNextPhysicalFragment();
sl@0
  2556
sl@0
  2557
	__KTRACE_OPT(KPBUSDRV, 	Kern::Printf("--DMmcMediaDriverFlash::DoPhysReadTransferCallBack()"));
sl@0
  2558
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOPHYSREADDATATRANSFERCALLBACK_EXIT2, this );
sl@0
  2559
	}
sl@0
  2560
sl@0
  2561
void DMmcMediaDriverFlash::DoWriteDataTransferCallBack()
sl@0
  2562
	{
sl@0
  2563
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOWRITEDATATRANSFERCALLBACK_ENTRY, this );
sl@0
  2564
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("++DMmcMediaDriverFlash::DoWriteDataTransferCallBack()"));
sl@0
  2565
sl@0
  2566
	TInt err = KErrNone;
sl@0
  2567
	
sl@0
  2568
	// Advance current request progress...
sl@0
  2569
	iReqCur = iPhysEnd;
sl@0
  2570
sl@0
  2571
	const TUint32 doubleBufferSize = iMaxBufSize >> 1;
sl@0
  2572
sl@0
  2573
	TInt64 length = iDbEnd - iReqCur;
sl@0
  2574
	TInt64 medEnd = UMin(iReqCur + doubleBufferSize, iReqCur + length);
sl@0
  2575
sl@0
  2576
	iPhysEnd = (medEnd + iBlkMsk) & ~iBlkMsk;
sl@0
  2577
	TInt64 len = UMin(iDbEnd, iPhysEnd) - iReqCur;
sl@0
  2578
	
sl@0
  2579
	if(len > doubleBufferSize)
sl@0
  2580
		{
sl@0
  2581
		// Adjust for maximum size of double-buffering
sl@0
  2582
		len = doubleBufferSize;
sl@0
  2583
		}
sl@0
  2584
sl@0
  2585
	__ASSERT_DEBUG(len > 0, Panic(EDBLength));
sl@0
  2586
	__ASSERT_DEBUG(I64HIGH((len + (KDiskSectorSize-1)) >> KDiskSectorShift) == 0, Panic(EDBLengthTooBig));
sl@0
  2587
sl@0
  2588
	TUint32 numBlocks = I64LOW((len + (KDiskSectorSize-1)) >> KDiskSectorShift);
sl@0
  2589
sl@0
  2590
	const TInt64 usrOfst = (iReqCur - iReqStart);
sl@0
  2591
	
sl@0
  2592
	__ASSERT_DEBUG(I64HIGH(usrOfst) == 0, Panic(EDBOffsetTooBig));
sl@0
  2593
sl@0
  2594
	// Setup the next buffer pointer and switch buffers...
sl@0
  2595
	TUint8* bufPtr = iIntBuf + (iSecondBuffer ? doubleBufferSize : 0);
sl@0
  2596
	TPtr8 tgt(bufPtr, I64LOW(len));
sl@0
  2597
	iSecondBuffer = iSecondBuffer ? (TBool)EFalse : (TBool)ETrue;
sl@0
  2598
sl@0
  2599
	if(iDoLastRMW && length < doubleBufferSize)
sl@0
  2600
		{
sl@0
  2601
		//
sl@0
  2602
		// This is the last transfer, and RMW is required.  The result of the read exists
sl@0
  2603
		// in iMinorBuf, so copy the non-modified section of the block to the active buffer.
sl@0
  2604
		//
sl@0
  2605
		memcpy(&bufPtr[(numBlocks-1) << KDiskSectorShift], iMinorBuf, KDiskSectorSize);
sl@0
  2606
		}
sl@0
  2607
sl@0
  2608
	if(I64LOW(iDbEnd - iReqCur) <= iMaxBufSize)
sl@0
  2609
		{
sl@0
  2610
		//
sl@0
  2611
		// This is the last transfer (with or without RMW)
sl@0
  2612
		//  - Mark the last blocks as active in the buffer cache.
sl@0
  2613
		//
sl@0
  2614
		MarkBlocks(iReqCur, iPhysEnd, CchMemToIdx(bufPtr));
sl@0
  2615
		}
sl@0
  2616
sl@0
  2617
	//
sl@0
  2618
	// Read the requested data from the remote thread...
sl@0
  2619
	//
sl@0
  2620
	err = ReadDataFromUser(tgt, I64LOW(usrOfst));
sl@0
  2621
sl@0
  2622
	//
sl@0
  2623
	// ...and signal that data is available to the PSL.
sl@0
  2624
	//
sl@0
  2625
	iSession->MoreDataAvailable(numBlocks, bufPtr, err);
sl@0
  2626
sl@0
  2627
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("--DMmcMediaDriverFlash::DoWriteDataTransferCallBack()"));
sl@0
  2628
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOWRITEDATATRANSFERCALLBACK_EXIT, this );
sl@0
  2629
	}
sl@0
  2630
sl@0
  2631
sl@0
  2632
void DMmcMediaDriverFlash::DoReadDataTransferCallBack()
sl@0
  2633
	{
sl@0
  2634
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DOREADDATATRANSFERCALLBACK_ENTRY, this );
sl@0
  2635
	__KTRACE_OPT(KPBUSDRV, 	Kern::Printf("++DMmcMediaDriverFlash::DoReadTransferCallBack()"));
sl@0
  2636
sl@0
  2637
	TInt err = KErrNone;
sl@0
  2638
	
sl@0
  2639
	const TUint32 doubleBufferSize = iMaxBufSize >> 1;
sl@0
  2640
sl@0
  2641
	TUint32 bufOfst = 0;
sl@0
  2642
sl@0
  2643
	if((iReqCur & ~iBlkMsk) == iPhysStart)
sl@0
  2644
		{
sl@0
  2645
		if(iSecondBuffer)
sl@0
  2646
			{
sl@0
  2647
			//
sl@0
  2648
			// If this is the first callback, don't copy data as it's not available yet
sl@0
  2649
			//  - just drop through to set up the next buffer.
sl@0
  2650
			//
sl@0
  2651
			TUint32 numBlocks = I64LOW((doubleBufferSize + (KDiskSectorSize-1)) >> KDiskSectorShift);
sl@0
  2652
			TUint8* bufPtr = iIntBuf + doubleBufferSize;
sl@0
  2653
sl@0
  2654
			iSecondBuffer = EFalse;
sl@0
  2655
sl@0
  2656
			iSession->MoreDataAvailable(numBlocks, bufPtr, KErrNone);
sl@0
  2657
			OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOREADDATATRANSFERCALLBACK_EXIT1, this );
sl@0
  2658
			return;
sl@0
  2659
			}
sl@0
  2660
		else
sl@0
  2661
			{
sl@0
  2662
			//
sl@0
  2663
			// If this is the second callback we're ready to copy
sl@0
  2664
			// back to the client - data may be mis-aligned in the first
sl@0
  2665
			// instance, but all subsequent data will be aligned...
sl@0
  2666
			//
sl@0
  2667
			bufOfst = I64LOW(iReqCur - iPhysStart);
sl@0
  2668
			}
sl@0
  2669
		}
sl@0
  2670
sl@0
  2671
	// ...otherwise, write the previous buffer contents to the user
sl@0
  2672
	TUint8* bufPtr = iIntBuf + (iSecondBuffer ? doubleBufferSize : 0);
sl@0
  2673
sl@0
  2674
	err = WriteDataToUser(bufPtr + bufOfst);
sl@0
  2675
sl@0
  2676
	// Advance current request progress...
sl@0
  2677
	iReqCur = iPhysEnd;
sl@0
  2678
sl@0
  2679
	TInt64 medEnd = UMin(iReqCur + doubleBufferSize, iDbEnd);
sl@0
  2680
sl@0
  2681
	iPhysEnd = (medEnd + iBlkMsk) & ~iBlkMsk;
sl@0
  2682
sl@0
  2683
	// Current buffer is one step ahead of the current request progress...
sl@0
  2684
	TInt64 len = UMin((iDbEnd - iPhysEnd + iBlkMsk) & ~iBlkMsk, TInt64(doubleBufferSize));
sl@0
  2685
sl@0
  2686
	__ASSERT_DEBUG(len == 0 || (I64HIGH((len + (KDiskSectorSize-1)) >> KDiskSectorShift) == 0), Panic(EDBLengthTooBig));
sl@0
  2687
sl@0
  2688
	TUint32 numBlocks = I64LOW((len + (KDiskSectorSize-1)) >> KDiskSectorShift);
sl@0
  2689
sl@0
  2690
	//
sl@0
  2691
	// ...switch buffers and signal that data is available to the PSL.
sl@0
  2692
	//
sl@0
  2693
	iSecondBuffer = iSecondBuffer ? (TBool)EFalse : (TBool)ETrue;
sl@0
  2694
sl@0
  2695
	iSession->MoreDataAvailable(numBlocks, bufPtr, err);
sl@0
  2696
sl@0
  2697
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("--DMmcMediaDriverFlash::DoDataTransferCallBack()"));
sl@0
  2698
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DOREADDATATRANSFERCALLBACK_EXIT2, this );
sl@0
  2699
	}
sl@0
  2700
sl@0
  2701
sl@0
  2702
// ---- request management ----
sl@0
  2703
sl@0
  2704
sl@0
  2705
TInt DMmcMediaDriverFlash::EngageAndSetReadRequest(DMmcMediaDriverFlash::TMediaRequest aRequest)
sl@0
  2706
	{
sl@0
  2707
	OstTraceExt2(TRACE_FLOW, DMMCMEDIADRIVERFLASH_ENGAGEANDSETREADREQUEST_ENTRY, "DMmcMediaDriverFlash::EngageAndSetReadRequest;aRequest=%d;this=%x", (TInt) aRequest, (TUint) this);
sl@0
  2708
	TInt r = EngageAndSetRequest(aRequest, iReadCurrentInMilliAmps);
sl@0
  2709
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ENGAGEANDSETREADREQUEST_EXIT, this, r );
sl@0
  2710
	return r;
sl@0
  2711
	}
sl@0
  2712
sl@0
  2713
sl@0
  2714
TInt DMmcMediaDriverFlash::EngageAndSetWriteRequest(DMmcMediaDriverFlash::TMediaRequest aRequest)
sl@0
  2715
	{
sl@0
  2716
	OstTraceExt2(TRACE_FLOW, DMMCMEDIADRIVERFLASH_ENGAGEANDSETWRITEREQUEST_ENTRY, "DMmcMediaDriverFlash::EngageAndSetReadRequest;aRequest=%d;this=%x", (TInt) aRequest, (TUint) this);
sl@0
  2717
	TInt r = EngageAndSetRequest(aRequest, iWriteCurrentInMilliAmps);
sl@0
  2718
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ENGAGEANDSETWRITEREQUEST_EXIT, this, r );
sl@0
  2719
	return r;
sl@0
  2720
	}
sl@0
  2721
sl@0
  2722
sl@0
  2723
TInt DMmcMediaDriverFlash::EngageAndSetRequest(DMmcMediaDriverFlash::TMediaRequest aRequest, TInt aCurrent)
sl@0
  2724
//
sl@0
  2725
// In WINS, all of the processing, including the callbacks, is done when Engage() is called,
sl@0
  2726
// so the request value must be set up in advanced.  Both the request and the current are
sl@0
  2727
// cleared in the corresponding call to CompleteRequest().
sl@0
  2728
//
sl@0
  2729
	{
sl@0
  2730
	OstTraceExt3(TRACE_FLOW, DMMCMEDIADRIVERFLASH_ENGAGEANDSETREQUEST_ENTRY, "DMmcMediaDriverFlash::EngageAndSetRequest;aRequest=%d;aCurrent=%d;this=%x", (TInt) aRequest, aCurrent, (TUint) this);
sl@0
  2731
	__ASSERT_DEBUG(iSession != NULL, Panic(ECFSessPtrNull));
sl@0
  2732
sl@0
  2733
	iMedReq = aRequest;
sl@0
  2734
	SetCurrentConsumption(aCurrent);
sl@0
  2735
sl@0
  2736
	TInt r = InCritical();
sl@0
  2737
	if (r == KErrNone)
sl@0
  2738
		{
sl@0
  2739
		r = iSession->Engage();
sl@0
  2740
		}
sl@0
  2741
sl@0
  2742
	if(r != KErrNone)
sl@0
  2743
		{
sl@0
  2744
		if (!Kern::PowerGood())
sl@0
  2745
			r=KErrAbort; // If emergency power down - return abort rather than anything else.
sl@0
  2746
		if (!iCard->IsReady())
sl@0
  2747
			r=KErrNotReady; // If media change - return not ready rather than anything else.
sl@0
  2748
		EndInCritical();
sl@0
  2749
		}
sl@0
  2750
sl@0
  2751
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ENGAGEANDSETREQUEST_EXIT, this, r );
sl@0
  2752
	return r;
sl@0
  2753
	}
sl@0
  2754
sl@0
  2755
sl@0
  2756
void DMmcMediaDriverFlash::CompleteRequest(TInt aReason)
sl@0
  2757
//
sl@0
  2758
// completes the specified request
sl@0
  2759
//
sl@0
  2760
	{
sl@0
  2761
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_COMPLETEREQUEST_ENTRY, this );
sl@0
  2762
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:cr0x%08x,%d", iCurrentReq, aReason));
sl@0
  2763
	
sl@0
  2764
	iMedReq = EMReqIdle;
sl@0
  2765
	SetCurrentConsumption(KIdleCurrentInMilliAmps);
sl@0
  2766
sl@0
  2767
	TLocDrvRequest* pR=iCurrentReq;
sl@0
  2768
	if (pR)
sl@0
  2769
		{
sl@0
  2770
#ifdef __DEMAND_PAGING__
sl@0
  2771
#if defined(__TEST_PAGING_MEDIA_DRIVER__)
sl@0
  2772
		__KTRACE_OPT(KLOCDPAGING,Kern::Printf("DMediaDriverFlash::Complete req Id(%d) with(%d)", pR->Id(), aReason));
sl@0
  2773
#endif		// __TEST_PAGING_MEDIA_DRIVER__
sl@0
  2774
#endif		// __DEMAND_PAGING__
sl@0
  2775
		iCurrentReq=NULL;
sl@0
  2776
		DMediaDriver::Complete(*pR,aReason);
sl@0
  2777
		}
sl@0
  2778
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_COMPLETEREQUEST_EXIT, this );
sl@0
  2779
	}
sl@0
  2780
sl@0
  2781
TInt DMmcMediaDriverFlash::Caps(TLocDrv& aDrive, TLocalDriveCapsV6& aInfo)
sl@0
  2782
	{
sl@0
  2783
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_CAPS_ENTRY, this );
sl@0
  2784
	// Fill buffer with current media caps.
sl@0
  2785
	aInfo.iType = EMediaHardDisk;
sl@0
  2786
	aInfo.iConnectionBusType = EConnectionBusInternal;
sl@0
  2787
	aInfo.iDriveAtt = KDriveAttLocal;
sl@0
  2788
	aInfo.iMediaAtt	= KMediaAttFormattable;
sl@0
  2789
sl@0
  2790
	if(iCard->iFlags & KMMCardIsLockable)
sl@0
  2791
		aInfo.iMediaAtt |= KMediaAttLockable;
sl@0
  2792
sl@0
  2793
	if (iCard->HasPassword())
sl@0
  2794
		aInfo.iMediaAtt |= KMediaAttHasPassword;
sl@0
  2795
	if (iCard->IsWriteProtected())
sl@0
  2796
		aInfo.iMediaAtt |= KMediaAttWriteProtected;
sl@0
  2797
	if (iCard->IsLocked())
sl@0
  2798
		aInfo.iMediaAtt |= KMediaAttLocked;
sl@0
  2799
sl@0
  2800
	aInfo.iFileSystemId = KDriveFileSysFAT;
sl@0
  2801
sl@0
  2802
	// Format is performed in multiples of the erase sector (or multiple block) size
sl@0
  2803
	aInfo.iMaxBytesPerFormat = iEraseInfo.iPreferredEraseUnitSize;
sl@0
  2804
sl@0
  2805
	if ((!iInternalSlot) && (GetCardFormatInfo(iCard,aInfo.iFormatInfo) == KErrNone))
sl@0
  2806
		{
sl@0
  2807
		TUint16 reservedSectors;
sl@0
  2808
		TMBRPartitionEntry dummy;	// Not used here
sl@0
  2809
		const TInt r = GetMediaDefaultPartitionInfo(dummy, reservedSectors, iCard);
sl@0
  2810
		if(r != KErrNone)
sl@0
  2811
		    {
sl@0
  2812
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_CAPS_EXIT1, this, r );
sl@0
  2813
			return r;
sl@0
  2814
		    }
sl@0
  2815
sl@0
  2816
		aInfo.iFormatInfo.iReservedSectors = reservedSectors;
sl@0
  2817
		aInfo.iExtraInfo = ETrue;
sl@0
  2818
		}
sl@0
  2819
sl@0
  2820
    // Set serial number to CID
sl@0
  2821
    __ASSERT_DEBUG(KMMCCIDLength<=KMaxSerialNumLength, Kern::PanicCurrentThread(_L("Mmc"), KErrOverflow));
sl@0
  2822
    aInfo.iSerialNumLength = KMMCCIDLength;
sl@0
  2823
    for (TUint i=0; i<KMMCCIDLength; i++)
sl@0
  2824
        aInfo.iSerialNum[i] = iCard->CID().At(i);
sl@0
  2825
    
sl@0
  2826
	// Get block size & erase block size to allow the file system to align first usable cluster correctly
sl@0
  2827
	aInfo.iBlockSize = BlockSize(iCard);
sl@0
  2828
	aInfo.iEraseBlockSize = EraseBlockSize(iCard);
sl@0
  2829
sl@0
  2830
#if defined(__DEMAND_PAGING__)
sl@0
  2831
	// If the stack has flagged this as a demand-paging device, then it is assumed that it is internal
sl@0
  2832
	// and (optionally) write protected.
sl@0
  2833
	if(aDrive.iPrimaryMedia->iPagingMedia)
sl@0
  2834
		{
sl@0
  2835
		aInfo.iMediaAtt|= KMediaAttPageable;
sl@0
  2836
		if (iDemandPagingInfo.iWriteProtected)
sl@0
  2837
			{
sl@0
  2838
			aInfo.iMediaAtt|= KMediaAttWriteProtected;
sl@0
  2839
			aInfo.iMediaAtt&= ~KMediaAttFormattable;
sl@0
  2840
			}		
sl@0
  2841
		}
sl@0
  2842
sl@0
  2843
	// code paging enabled on this drive ?
sl@0
  2844
	if(aDrive.iPagingDrv)
sl@0
  2845
		{
sl@0
  2846
		aInfo.iDriveAtt|= KDriveAttPageable;
sl@0
  2847
		}
sl@0
  2848
sl@0
  2849
#endif
sl@0
  2850
sl@0
  2851
	if (iInternalSlot)
sl@0
  2852
		{
sl@0
  2853
		aInfo.iDriveAtt|= KDriveAttInternal;
sl@0
  2854
		}
sl@0
  2855
	else
sl@0
  2856
		{
sl@0
  2857
		aInfo.iDriveAtt|= KDriveAttRemovable;
sl@0
  2858
		}
sl@0
  2859
sl@0
  2860
sl@0
  2861
	if (iMmcPartitionInfo)
sl@0
  2862
		{
sl@0
  2863
		TLocalDriveCapsV6Buf CapsInfo = aInfo;
sl@0
  2864
		iMmcPartitionInfo->PartitionCaps(aDrive,CapsInfo);
sl@0
  2865
		aInfo = CapsInfo();
sl@0
  2866
		}
sl@0
  2867
	
sl@0
  2868
	
sl@0
  2869
	if (iMediaType==EMultiMediaROM)
sl@0
  2870
		{
sl@0
  2871
		aInfo.iMediaAtt|= KMediaAttWriteProtected;
sl@0
  2872
		aInfo.iMediaAtt&= ~KMediaAttFormattable;
sl@0
  2873
		}
sl@0
  2874
	
sl@0
  2875
	// Must return KErrCompletion to indicate that this 
sl@0
  2876
	// is a synchronous version of the function
sl@0
  2877
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_CAPS_EXIT2, this, KErrCompletion );
sl@0
  2878
	return KErrCompletion;
sl@0
  2879
	}
sl@0
  2880
sl@0
  2881
sl@0
  2882
// ---- cache ----
sl@0
  2883
sl@0
  2884
TInt DMmcMediaDriverFlash::ReadDataUntilCacheExhausted(TBool* aAllDone)
sl@0
  2885
//
sl@0
  2886
// scans the cache for blocks corresponding to the range iReqCur to iReqEnd and
sl@0
  2887
// writes them to user memory.  Starts at iReqCur & ~iBlkMsk and looks for blocks
sl@0
  2888
// at sequential media positions.  Completes when a block is not available, even
sl@0
  2889
// if a following block is available in the cache.  *aAllDone is undefined if the
sl@0
  2890
// return value is not KErrNone.
sl@0
  2891
//
sl@0
  2892
// This function is linear in the number of blocks in the cache.
sl@0
  2893
//
sl@0
  2894
	{
sl@0
  2895
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_READDATAUNTILCACHEEXHAUSTED_ENTRY, this );
sl@0
  2896
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:rdc:%x,%x", iReqCur, iReqEnd));
sl@0
  2897
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_READDATAUNTILCACHEEXHAUSTED, "iReqCur=0x%x; iReqEnd=0x%x", (TUint) iReqCur, (TUint) iReqEnd );
sl@0
  2898
	
sl@0
  2899
	if ( iCurrentReq->IsPhysicalAddress()
sl@0
  2900
#if defined(__DEMAND_PAGING__) && !defined(__WINS__)
sl@0
  2901
	     || DMediaPagingDevice::PageInRequest(*iCurrentReq)
sl@0
  2902
#endif //DEMAND_PAGING 
sl@0
  2903
        )
sl@0
  2904
		{
sl@0
  2905
		*aAllDone = EFalse;
sl@0
  2906
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_READDATAUNTILCACHEEXHAUSTED_EXIT1, this, KErrNone );
sl@0
  2907
		return KErrNone;
sl@0
  2908
		}
sl@0
  2909
	
sl@0
  2910
	TInt64 physStart = iReqCur & ~iBlkMsk;
sl@0
  2911
	TInt64 physEnd = Min(physStart + iMaxBufSize, (iReqEnd + iBlkMsk) & ~iBlkMsk);
sl@0
  2912
	BuildGammaArray(physStart, physEnd);
sl@0
  2913
sl@0
  2914
	TInt r = KErrNone;
sl@0
  2915
	TInt curBlk = 0;
sl@0
  2916
	TInt cchBlk;
sl@0
  2917
	while (
sl@0
  2918
			r == KErrNone
sl@0
  2919
		&&	physStart + (curBlk << iBlkLenLog2) < physEnd
sl@0
  2920
		&&	(cchBlk = iGamma[curBlk]) != KNoCacheBlock )
sl@0
  2921
		{
sl@0
  2922
		// set up instance variables for WriteDataToUser()
sl@0
  2923
		iPhysStart = physStart + (curBlk << iBlkLenLog2);
sl@0
  2924
		iPhysEnd = iPhysStart + iBlkLen;
sl@0
  2925
		iIntBuf = IdxToCchMem(cchBlk);
sl@0
  2926
sl@0
  2927
		if ((r = WriteDataToUser(&iIntBuf[I64LOW(iReqCur - iPhysStart)])) == KErrNone)
sl@0
  2928
			{
sl@0
  2929
			iReqCur = iPhysEnd;
sl@0
  2930
			iLstUsdCchEnt = iGamma[curBlk];
sl@0
  2931
			++curBlk;
sl@0
  2932
			}
sl@0
  2933
		}
sl@0
  2934
sl@0
  2935
	*aAllDone = (iReqCur >= iReqEnd);
sl@0
  2936
sl@0
  2937
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:rdc:%d,%d", *aAllDone, r));
sl@0
  2938
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_READDATAUNTILCACHEEXHAUSTED_EXIT2, this, r );
sl@0
  2939
	return r;
sl@0
  2940
	}
sl@0
  2941
sl@0
  2942
sl@0
  2943
TInt DMmcMediaDriverFlash::WriteDataToUser(TUint8* aBufPtr)
sl@0
  2944
//
sl@0
  2945
// write the data from the most recent read operation to the user descriptor
sl@0
  2946
//
sl@0
  2947
	{
sl@0
  2948
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_WRITEDATATOUSER_ENTRY, this );
sl@0
  2949
	TInt r = KErrNotSupported;
sl@0
  2950
sl@0
  2951
	// get range of data to read out of internal buffer
sl@0
  2952
sl@0
  2953
	TInt len = I64LOW(UMin(iPhysEnd, iReqEnd) - iReqCur);
sl@0
  2954
	TPtrC8 extrView(aBufPtr, len);
sl@0
  2955
sl@0
  2956
	// write data from internal buffer
sl@0
  2957
	TUint usrOfst = I64LOW(iReqCur - iReqStart);
sl@0
  2958
sl@0
  2959
	OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_WRITEDATATOUSER_LATENCY1, "Begin writing user data" );
sl@0
  2960
#if defined(__DEMAND_PAGING__) && !defined(__WINS__)
sl@0
  2961
	if (DMediaPagingDevice::PageInRequest(*iCurrentReq))
sl@0
  2962
		r=iCurrentReq->WriteToPageHandler((TUint8 *)(&extrView[0]), len, usrOfst);
sl@0
  2963
	else
sl@0
  2964
#endif	// __DEMAND_PAGING__
sl@0
  2965
		r = iCurrentReq->WriteRemote(&extrView,usrOfst);
sl@0
  2966
	
sl@0
  2967
	OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_WRITEDATATOUSER_LATENCY2, "End writing user data" );
sl@0
  2968
sl@0
  2969
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_WRITEDATATOUSER_EXIT, this, r );
sl@0
  2970
	return r;
sl@0
  2971
	}
sl@0
  2972
sl@0
  2973
TInt DMmcMediaDriverFlash::ReadDataFromUser(TDes8& aDes, TInt aOffset)
sl@0
  2974
	{
sl@0
  2975
	OstTraceExt2(TRACE_FLOW, DMMCMEDIADRIVERFLASH_READDATAFROMUSER_ENTRY ,"DMmcMediaDriverFlash::ReadDataFromUser;aOffset=%d;this=%x", aOffset, (TUint) this);
sl@0
  2976
	TInt r = KErrNotSupported;
sl@0
  2977
#ifndef __WINS__
sl@0
  2978
	if (DMediaPagingDevice::PageOutRequest(*iCurrentReq))
sl@0
  2979
	    {
sl@0
  2980
		r = iCurrentReq->ReadFromPageHandler((TAny*) aDes.Ptr(), aDes.MaxLength(), aOffset);
sl@0
  2981
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_READDATAFROMUSER_EXIT1, this, r );
sl@0
  2982
		return r;
sl@0
  2983
	    }
sl@0
  2984
	else
sl@0
  2985
#endif // #ifndef __WINS__
sl@0
  2986
		r = iCurrentReq->ReadRemote(&aDes, aOffset);
sl@0
  2987
	
sl@0
  2988
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_READDATAFROMUSER_EXIT2, this, r );
sl@0
  2989
	return r;
sl@0
  2990
	}
sl@0
  2991
sl@0
  2992
TInt DMmcMediaDriverFlash::AdjustPhysicalFragment(TPhysAddr &aPhysAddr, TInt &aPhysLength)
sl@0
  2993
//
sl@0
  2994
// Retrieve next Physical memory fragment and adjust the start pointer and length with
sl@0
  2995
// respect to the set offset {iFragOfset}.
sl@0
  2996
// Note the offset may encompass multiple memory fragments.
sl@0
  2997
//
sl@0
  2998
	{
sl@0
  2999
	OstTraceExt3(TRACE_FLOW, DMMCMEDIADRIVERFLASH_ADJUSTPHYSICALFRAGMENT_ENTRY, "DMmcMediaDriverFlash::AdjustPhysicalFragment;aPhysAddr=%x;aPhysLength=%d;this=%x", (TUint) aPhysAddr, aPhysLength, (TUint) this);
sl@0
  3000
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:APF"));
sl@0
  3001
	
sl@0
  3002
	TInt err = KErrNone;
sl@0
  3003
	TInt offset = iFragOfset;
sl@0
  3004
sl@0
  3005
	do 
sl@0
  3006
		{				
sl@0
  3007
		err = iCurrentReq->GetNextPhysicalAddress(aPhysAddr, aPhysLength);
sl@0
  3008
sl@0
  3009
		if (err != KErrNone)
sl@0
  3010
		    {
sl@0
  3011
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ADJUSTPHYSICALFRAGMENT_EXIT1, this, err );
sl@0
  3012
			return err;
sl@0
  3013
		    }
sl@0
  3014
		
sl@0
  3015
		if (offset >= aPhysLength) // more offset than in this physical chunk
sl@0
  3016
			{
sl@0
  3017
			offset -= aPhysLength;
sl@0
  3018
			}
sl@0
  3019
		else
sl@0
  3020
			{
sl@0
  3021
			// offset < physLength
sl@0
  3022
			// offset lies within the memory chunk
sl@0
  3023
			// Adjust length and address for first transfer
sl@0
  3024
			aPhysLength -= offset;
sl@0
  3025
			aPhysAddr += offset;
sl@0
  3026
			offset = -1;
sl@0
  3027
			}
sl@0
  3028
			
sl@0
  3029
		} while (offset >= 0);
sl@0
  3030
	
sl@0
  3031
	iFragOfset = 0; // reset offset now complete
sl@0
  3032
	
sl@0
  3033
	if (aPhysAddr == 0)
sl@0
  3034
		{
sl@0
  3035
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ADJUSTPHYSICALFRAGMENT_EXIT2, this, KErrNoMemory );
sl@0
  3036
		return KErrNoMemory;
sl@0
  3037
		}
sl@0
  3038
sl@0
  3039
#ifdef _DEBUG
sl@0
  3040
	// DMAHelper ensures memory is dma aligned
sl@0
  3041
	if ( (aPhysAddr & (iSocket->DmaAlignment()-1) ) )
sl@0
  3042
		{
sl@0
  3043
		__KTRACE_OPT(KPBUSDRV, Kern::Printf("mmd:lr:Memory Fragment Not Word Aligned!"));
sl@0
  3044
		OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_ADJUSTPHYSICALFRAGMENT_DMA, "Memory fragment not word aligned");
sl@0
  3045
		Panic(ENotDMAAligned);
sl@0
  3046
		}
sl@0
  3047
#endif	//_DEBUG
sl@0
  3048
	
sl@0
  3049
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:APF physAddr(0x%x), physLength(%d)",aPhysAddr, aPhysLength));
sl@0
  3050
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_ADJUSTPHYSICALFRAGMENT_EXIT3, this, err );
sl@0
  3051
	return err;
sl@0
  3052
	}
sl@0
  3053
sl@0
  3054
TInt DMmcMediaDriverFlash::PrepareFirstPhysicalFragment(TPhysAddr &aPhysAddr, TInt &aPhysLength, TUint32 aLength)
sl@0
  3055
//
sl@0
  3056
// Retrieves the first Physical memory fragment and determines the type of the next transfer
sl@0
  3057
// Next transfer may either be the last block (end not block aligned) or a block may straddle
sl@0
  3058
// memory fragments.
sl@0
  3059
//
sl@0
  3060
	{
sl@0
  3061
	OstTraceExt4(TRACE_FLOW, DMMCMEDIADRIVERFLASH_PREPAREFIRSTPHYSICALFRAGMENT_ENTRY, "DMmcMediaDriverFlash::PrepareFirstPhysicalFragment;aPhysAddr=%x;aPhysLength=%d;aLength=%x;this=%x", (TUint) aPhysAddr, aPhysLength, (TUint) aLength, (TUint) this);
sl@0
  3062
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:PFPF"));
sl@0
  3063
	TInt r = KErrNone;
sl@0
  3064
	
sl@0
  3065
	r = AdjustPhysicalFragment(aPhysAddr, aPhysLength);
sl@0
  3066
	
sl@0
  3067
	if (r == KErrNone)
sl@0
  3068
		{
sl@0
  3069
		TUint len = I64LOW(iReqEnd & iBlkMsk);
sl@0
  3070
		if ( ((TUint32)aPhysLength >= aLength) && len )
sl@0
  3071
			{
sl@0
  3072
			__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:PFPF-end block"));
sl@0
  3073
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_PREPAREFIRSTPHYSICALFRAGMENT_EB, "End block");
sl@0
  3074
			//next iteration will be an IPC for the end block
sl@0
  3075
			//There is enough space in physical memory to fit
sl@0
  3076
			//the extended read, but exceeds boundary for this request.
sl@0
  3077
			iIPCLen = len;
sl@0
  3078
			iRdROB |= KIPCSetup; // IPC setup for next iteration
sl@0
  3079
			aPhysLength -= len;
sl@0
  3080
			}
sl@0
  3081
		
sl@0
  3082
		if (aPhysLength & iBlkMsk)
sl@0
  3083
			{
sl@0
  3084
			__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:PFPF-straddles boundary"));
sl@0
  3085
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_PREPAREFIRSTPHYSICALFRAGMENT_SB, "Straddles boundary");
sl@0
  3086
			// block must be straddling a fragment boundary
sl@0
  3087
			// Next iteration must be an IPC 
sl@0
  3088
			iRdROB |= KIPCSetup;
sl@0
  3089
			
sl@0
  3090
			// Calculate the offset into the next memory block
sl@0
  3091
			iFragOfset = I64LOW(iBlkLen - (aPhysLength & iBlkMsk));
sl@0
  3092
			aPhysLength &= ~iBlkMsk;
sl@0
  3093
			}
sl@0
  3094
		}
sl@0
  3095
	
sl@0
  3096
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:PFPF err(%d), physAddr(0x%x), physLength(%d)",r, aPhysAddr, aPhysLength));	
sl@0
  3097
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_PREPAREFIRSTPHYSICALFRAGMENT_EXIT, this, r );
sl@0
  3098
	return r;
sl@0
  3099
	}
sl@0
  3100
	
sl@0
  3101
sl@0
  3102
void DMmcMediaDriverFlash::PrepareNextPhysicalFragment()
sl@0
  3103
//
sl@0
  3104
// Retrieves next Physical memory fragment and determines the type of the next transfer
sl@0
  3105
// Next transfer may either be the last block (end not block aligned) or a block may straddle
sl@0
  3106
// memory fragments.
sl@0
  3107
//
sl@0
  3108
	{
sl@0
  3109
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_PREPARENEXTPHYSICALFRAGMENT_ENTRY );
sl@0
  3110
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:PNPF"));
sl@0
  3111
	TInt err = KErrNone;
sl@0
  3112
	TPhysAddr physAddr = 0;
sl@0
  3113
	TInt physLength = 0;
sl@0
  3114
	
sl@0
  3115
	err = AdjustPhysicalFragment(physAddr, physLength);
sl@0
  3116
	
sl@0
  3117
	if (err == KErrNone)
sl@0
  3118
		{
sl@0
  3119
		if (iPhysEnd+physLength >= iReqEnd)
sl@0
  3120
			{
sl@0
  3121
			//Last physical transfer ...
sl@0
  3122
			TUint len = I64LOW(iReqEnd & iBlkMsk);
sl@0
  3123
			if (len)
sl@0
  3124
				{
sl@0
  3125
				__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:PNPF-end block"));
sl@0
  3126
				OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_PREPARENEXTPHYSICALFRAGMENT_EB, "End block" );
sl@0
  3127
				
sl@0
  3128
				// end point not block aligned!
sl@0
  3129
				// next iteration must be an IPC call
sl@0
  3130
				iRdROB |= KIPCSetup;
sl@0
  3131
				iIPCLen = len;
sl@0
  3132
				physLength -= len;
sl@0
  3133
				}
sl@0
  3134
			else{
sl@0
  3135
				physLength = I64LOW(iDbEnd  - iPhysEnd);
sl@0
  3136
				}
sl@0
  3137
			}
sl@0
  3138
			
sl@0
  3139
		if (physLength & iBlkMsk)
sl@0
  3140
			{
sl@0
  3141
			__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:PNPF-straddles boundary"));
sl@0
  3142
			OstTrace0( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_PREPARENEXTPHYSICALFRAGMENT_SB, "Straddles boundary" );
sl@0
  3143
			
sl@0
  3144
			// block must be straddling a fragment boundary
sl@0
  3145
			// Next iteration must be an IPC 
sl@0
  3146
			iRdROB |= KIPCSetup;
sl@0
  3147
			
sl@0
  3148
			// Calculate the offset into the next memory block
sl@0
  3149
			iFragOfset = I64LOW(iBlkLen - (physLength & iBlkMsk));
sl@0
  3150
			physLength &= ~iBlkMsk;
sl@0
  3151
			}			
sl@0
  3152
		
sl@0
  3153
		iPhysEnd += physLength;
sl@0
  3154
		}
sl@0
  3155
		
sl@0
  3156
	iSession->MoreDataAvailable( (physLength  >> KDiskSectorShift), (TUint8*) physAddr, err);		
sl@0
  3157
	iSecondBuffer = EFalse;
sl@0
  3158
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:PNPF"));
sl@0
  3159
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_PREPARENEXTPHYSICALFRAGMENT_EXIT );
sl@0
  3160
	}
sl@0
  3161
sl@0
  3162
TUint8* DMmcMediaDriverFlash::ReserveReadBlocks(TInt64 aStart, TInt64 aEnd, TUint32* aLength)
sl@0
  3163
//
sl@0
  3164
// Assume the cache has been drained before this function is called and so
sl@0
  3165
// the first block is not in the cache.  The length of the allocated range is
sl@0
  3166
// either aEnd - aStart, or enough blocks such that the next block to read
sl@0
  3167
// is already available in the cache, and so will be read when
sl@0
  3168
// ReadDataUntilCacheExhausted() is called from the callback DFC.
sl@0
  3169
//
sl@0
  3170
	{
sl@0
  3171
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_RESERVEREADBLOCKS_ENTRY, this );
sl@0
  3172
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:rrb:%lx,%lx", aStart, aEnd));
sl@0
  3173
sl@0
  3174
	__ASSERT_DEBUG((aStart & iBlkMsk) == 0, Panic(ERRBStAlign));
sl@0
  3175
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(ERRBStPos));
sl@0
  3176
	__ASSERT_DEBUG(aEnd > aStart, Panic(ERRBNotPositive));
sl@0
  3177
	__ASSERT_DEBUG((aEnd & iBlkMsk) == 0, Panic(ERRBEndAlign));
sl@0
  3178
	__ASSERT_DEBUG(TotalSizeInBytes() >= aEnd, Panic(ERRBEndPos));
sl@0
  3179
	__ASSERT_DEBUG(!iDoDoubleBuffer, Panic(ENoDBSupport));
sl@0
  3180
	__ASSERT_CACHE(CacheInvariant(), Panic(ERRBCchInv));
sl@0
  3181
	__ASSERT_CACHE(GetCachedBlock(aStart & ~iBlkMsk) == 0, Panic(ERRBExist));
sl@0
  3182
sl@0
  3183
	TUint8* raby;
sl@0
  3184
sl@0
  3185
	BuildGammaArray(aStart, aEnd);
sl@0
  3186
sl@0
  3187
	// reposition start index at 0 if the full range would run off the end of the
sl@0
  3188
	// buffer.  This is heuristic - enabling a longer multi-block may cost some
sl@0
  3189
	// cached reads.  However, assume long reads do not generally re-read the same
sl@0
  3190
	// data, and are used for streaming large amounts of data into memory.
sl@0
  3191
sl@0
  3192
	const TInt blocksInRange = I64LOW((aEnd - aStart) >> iBlkLenLog2);
sl@0
  3193
	TInt startIndex = (iLstUsdCchEnt + 1) % iBlocksInBuffer;
sl@0
  3194
	if (startIndex + blocksInRange > iBlocksInBuffer)
sl@0
  3195
		startIndex = 0;
sl@0
  3196
sl@0
  3197
	// starting at startIndex, increase the range until it covers aEnd - aStart,
sl@0
  3198
	// or until the next block to read is available in the cache.
sl@0
  3199
sl@0
  3200
	TInt blkCnt = 0;
sl@0
  3201
	TBool finished;
sl@0
  3202
	do
sl@0
  3203
		{
sl@0
  3204
		finished = (
sl@0
  3205
			// range allocated for entire read
sl@0
  3206
				blkCnt == blocksInRange
sl@0
  3207
			// next block already exists in buffer and has not been overwritten
sl@0
  3208
			// by existing multi-block read
sl@0
  3209
			|| (	iGamma[blkCnt] != KNoCacheBlock
sl@0
  3210
				&&	(	iGamma[blkCnt] < startIndex
sl@0
  3211
					||	iGamma[blkCnt] >= startIndex + blkCnt ) ) );
sl@0
  3212
sl@0
  3213
		if (! finished)
sl@0
  3214
			++blkCnt;
sl@0
  3215
		} while (! finished);
sl@0
  3216
sl@0
  3217
	iLstUsdCchEnt = startIndex + blkCnt - 1;
sl@0
  3218
sl@0
  3219
	if (blkCnt < 1) blkCnt = 1; //RBW required < 1 block to be read
sl@0
  3220
	
sl@0
  3221
	OstTraceExt2( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_RESERVEREADBLOCKS_RANGE, "blocksInRange=%d; blkCnt=%d", blocksInRange, blkCnt );
sl@0
  3222
	
sl@0
  3223
	TUint32 lengthInBytes = blkCnt << iBlkLenLog2;
sl@0
  3224
	*aLength = lengthInBytes;
sl@0
  3225
	MarkBlocks(aStart, aStart + lengthInBytes, startIndex);
sl@0
  3226
sl@0
  3227
	raby = IdxToCchMem(startIndex);
sl@0
  3228
sl@0
  3229
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:rrb:%x", (TUint32) raby));
sl@0
  3230
sl@0
  3231
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_RESERVEREADBLOCKS_EXIT, this, ( TUint )( raby ) );
sl@0
  3232
	return raby;
sl@0
  3233
	}
sl@0
  3234
sl@0
  3235
sl@0
  3236
TUint8* DMmcMediaDriverFlash::ReserveWriteBlocks(TInt64 aStart, TInt64 aEnd, TUint* aRBM)
sl@0
  3237
//
sl@0
  3238
// reserve a range of blocks in the buffer.  If the block containing aStart or aEnd
sl@0
  3239
// are already in the buffer, attempts to position on them.  This can save one or two
sl@0
  3240
// RBMs for writes.
sl@0
  3241
//
sl@0
  3242
// This function is linear in the number of blocks - it runs through the array
sl@0
  3243
// exactly twice.
sl@0
  3244
//
sl@0
  3245
// aStart and aEnd are not necessarily block aligned - the function uses alignment
sl@0
  3246
// information to minimize RBMs.
sl@0
  3247
//
sl@0
  3248
	{
sl@0
  3249
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_RESERVEWRITEBLOCKS_ENTRY, this );
sl@0
  3250
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:rwb:%lx,%lx", aStart, aEnd));
sl@0
  3251
sl@0
  3252
	TInt64 physStart = aStart & ~iBlkMsk;
sl@0
  3253
	TInt64 physEnd = (aEnd + iBlkMsk) & ~iBlkMsk;
sl@0
  3254
sl@0
  3255
	__ASSERT_DEBUG(TotalSizeInBytes() > physStart, Panic(ERWBStPos));
sl@0
  3256
	__ASSERT_DEBUG(aEnd > aStart, Panic(ERWBNotPositive));
sl@0
  3257
	__ASSERT_DEBUG(TotalSizeInBytes() >= physEnd, Panic(ERWBEndPos));
sl@0
  3258
	__ASSERT_DEBUG(iDoPhysicalAddress || iDoDoubleBuffer || (!iDoDoubleBuffer && !iDoPhysicalAddress && physEnd - physStart <= (TInt64)iMaxBufSize), Panic(ERWBOverflow));
sl@0
  3259
	__ASSERT_CACHE(CacheInvariant(), Panic(ERWBCchInv));
sl@0
  3260
	
sl@0
  3261
	const TBool firstPartial = (aStart & iBlkMsk) != 0;
sl@0
  3262
	const TBool lastPartial  = (aEnd & iBlkMsk)   != 0;
sl@0
  3263
	
sl@0
  3264
	const TInt blkCnt = I64LOW((physEnd - physStart) >> iBlkLenLog2);
sl@0
  3265
	OstTrace1( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_RESERVEWRITEBLOCKS_RANGE, "blkCnt=%d", blkCnt );
sl@0
  3266
	
sl@0
  3267
	TBool startUsed = EFalse;
sl@0
  3268
	TBool endUsed   = EFalse;
sl@0
  3269
	
sl@0
  3270
	TUint8* raby = NULL;
sl@0
  3271
sl@0
  3272
	if(iDoDoubleBuffer)
sl@0
  3273
		{
sl@0
  3274
		//
sl@0
  3275
		// If we're double-buffering, then the entire cache will be re-used
sl@0
  3276
		// continuously.  Rather than continually reserve blocks during each 
sl@0
  3277
		// transfer we calculate the blocks that will be present after all
sl@0
  3278
		// transfers have completed.
sl@0
  3279
		//
sl@0
  3280
		InvalidateCache();
sl@0
  3281
		raby = iCacheBuf;
sl@0
  3282
		}
sl@0
  3283
	else
sl@0
  3284
		{
sl@0
  3285
		TInt idx;
sl@0
  3286
sl@0
  3287
		// check if the first or last blocks are already in the buffer.
sl@0
  3288
		TInt fst = -1, lst = -1;
sl@0
  3289
		const TInt64 lstBlk = physEnd - iBlkLen;
sl@0
  3290
		TInt i;
sl@0
  3291
		for (i = 0; i < iBlocksInBuffer; ++i)
sl@0
  3292
			{
sl@0
  3293
			if (iCachedBlocks[i] == physStart)
sl@0
  3294
				fst = i;
sl@0
  3295
sl@0
  3296
			if (iCachedBlocks[i] == lstBlk)
sl@0
  3297
				lst = i;
sl@0
  3298
			}
sl@0
  3299
sl@0
  3300
		const TBool firstUsable = (fst != -1) && (iBlocksInBuffer - fst) >= blkCnt;
sl@0
  3301
		const TBool lastUsable = (lst != -1) && lst >= (blkCnt - 1);
sl@0
  3302
sl@0
  3303
		if (iDoPhysicalAddress)
sl@0
  3304
			{				
sl@0
  3305
			if ( (firstPartial || lastPartial) && blkCnt <= 2)
sl@0
  3306
				{
sl@0
  3307
				//Physical addressing not to be used.
sl@0
  3308
				//more efficent to use local Cache copying
sl@0
  3309
				iDoPhysicalAddress = EFalse;
sl@0
  3310
				OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_RESERVEWRITEBLOCKS_EXIT1, this, ( TUint )( raby ) );
sl@0
  3311
				return raby;
sl@0
  3312
				}
sl@0
  3313
			else
sl@0
  3314
				{						
sl@0
  3315
				raby = iMinorBuf;
sl@0
  3316
				
sl@0
  3317
				const TBool firstPres = (fst != -1);
sl@0
  3318
				const TBool lastPres = (lst != -1);
sl@0
  3319
				
sl@0
  3320
				if (firstPartial && firstPres)
sl@0
  3321
					{
sl@0
  3322
					// move to minor buffer
sl@0
  3323
					memcpy(iMinorBuf, IdxToCchMem(fst), iBlkLen);
sl@0
  3324
					}
sl@0
  3325
				if (lastPartial && lastPres)
sl@0
  3326
					{
sl@0
  3327
					// move to beginning of cache
sl@0
  3328
					memcpy(iCacheBuf, IdxToCchMem(lst), iBlkLen);
sl@0
  3329
					}					
sl@0
  3330
								
sl@0
  3331
				InvalidateCache(physStart,physEnd);
sl@0
  3332
				
sl@0
  3333
				if (lastPartial)
sl@0
  3334
					{
sl@0
  3335
					//re-mark beginning of cache
sl@0
  3336
					MarkBlocks((physEnd-iBlkLen), physEnd, 0);
sl@0
  3337
					}
sl@0
  3338
				
sl@0
  3339
				if (aRBM)
sl@0
  3340
					{
sl@0
  3341
					*aRBM = 0;
sl@0
  3342
										
sl@0
  3343
					if (firstPartial) 
sl@0
  3344
						*aRBM |= KWtMinFst; 
sl@0
  3345
					
sl@0
  3346
					if (firstPartial && !firstPres) 
sl@0
  3347
						*aRBM |= KWtRBMFst;
sl@0
  3348
					
sl@0
  3349
					if (lastPartial) 
sl@0
  3350
						*aRBM |= KWtMinLst;					
sl@0
  3351
					
sl@0
  3352
					if (lastPartial && !lastPres) 
sl@0
  3353
						*aRBM |= KWtRBMLst;
sl@0
  3354
					}
sl@0
  3355
				
sl@0
  3356
				OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_RESERVEWRITEBLOCKS_EXIT2, this, ( TUint )( raby ) );
sl@0
  3357
				return raby;
sl@0
  3358
				}
sl@0
  3359
			} // if (iDoPhysicalAddress)			
sl@0
  3360
		
sl@0
  3361
		if (!firstUsable && !lastUsable)
sl@0
  3362
			{
sl@0
  3363
			if(iDoDoubleBuffer)
sl@0
  3364
				{
sl@0
  3365
				idx = iSecondBuffer ? iBlocksInBuffer >> 1 : 0;
sl@0
  3366
				}
sl@0
  3367
			else
sl@0
  3368
				{
sl@0
  3369
				idx = (iLstUsdCchEnt + 1) % iBlocksInBuffer;
sl@0
  3370
				if (idx + blkCnt > iBlocksInBuffer)
sl@0
  3371
					idx = 0;
sl@0
  3372
				}
sl@0
  3373
			}
sl@0
  3374
		else if (firstUsable && ! lastUsable)
sl@0
  3375
			{
sl@0
  3376
			idx = fst;
sl@0
  3377
			}
sl@0
  3378
		else if (! firstUsable && lastUsable)
sl@0
  3379
			{
sl@0
  3380
			idx = lst - (blkCnt - 1);
sl@0
  3381
			}
sl@0
  3382
		else	// (lastUsable && firstUsable)
sl@0
  3383
			{
sl@0
  3384
			if (firstPartial || ! lastPartial)
sl@0
  3385
				idx = fst;
sl@0
  3386
			else
sl@0
  3387
				idx = lst - (blkCnt - 1);
sl@0
  3388
			}
sl@0
  3389
sl@0
  3390
		MarkBlocks(physStart, physEnd, idx);
sl@0
  3391
sl@0
  3392
		// if the range started or ended on a partial block, but could not
sl@0
  3393
		// be allocated on that existing block, and the existing block is
sl@0
  3394
		// somewhere in the cache, then memcpy() that block to the end of the
sl@0
  3395
		// range.  used is not the same as usable - both the start and end
sl@0
  3396
		// blocks may be usable, through not in the same range, or any range.
sl@0
  3397
sl@0
  3398
		const TInt startExtent = I64LOW(aStart & iBlkMsk);
sl@0
  3399
		TBool firstInTemp = EFalse;
sl@0
  3400
		startUsed = (idx == fst);
sl@0
  3401
		if (! startUsed && firstPartial && fst != -1)
sl@0
  3402
			{
sl@0
  3403
			// if the range has started at index occupied by the last block then
sl@0
  3404
			// temporarily copy to minor buffer.  This is unnecessary when the
sl@0
  3405
			// last block is not partial because the last block does not need to
sl@0
  3406
			// be preserved.
sl@0
  3407
sl@0
  3408
			if (idx == lst && lastPartial)
sl@0
  3409
				{
sl@0
  3410
				firstInTemp = ETrue;
sl@0
  3411
				memcpy(iMinorBuf, IdxToCchMem(fst), startExtent);
sl@0
  3412
				}
sl@0
  3413
			else
sl@0
  3414
				{
sl@0
  3415
				memcpy(IdxToCchMem(idx), IdxToCchMem(fst), startExtent);
sl@0
  3416
				}
sl@0
  3417
sl@0
  3418
			startUsed = ETrue;
sl@0
  3419
			}
sl@0
  3420
sl@0
  3421
		endUsed = (idx + blkCnt - 1 == lst);
sl@0
  3422
		if (! endUsed && lastPartial && lst != -1)
sl@0
  3423
			{
sl@0
  3424
			const TInt endOffset = I64LOW(aEnd & iBlkMsk);
sl@0
  3425
			const TInt endExtent = iBlkLen - endOffset;
sl@0
  3426
			memcpy(IdxToCchMem(idx + blkCnt - 1) + endOffset, IdxToCchMem(lst) + endOffset, endExtent);
sl@0
  3427
			endUsed = ETrue;
sl@0
  3428
			}
sl@0
  3429
sl@0
  3430
		if (firstInTemp)
sl@0
  3431
			memcpy(IdxToCchMem(idx), iMinorBuf, startExtent);
sl@0
  3432
sl@0
  3433
		// start reclaiming at block following this range
sl@0
  3434
		iLstUsdCchEnt = idx + blkCnt - 1;
sl@0
  3435
		raby = IdxToCchMem(idx);
sl@0
  3436
		}
sl@0
  3437
sl@0
  3438
	// work out if read-before-write required
sl@0
  3439
	if (aRBM)
sl@0
  3440
		{
sl@0
  3441
		*aRBM = 0;
sl@0
  3442
		// first index was not already in range, and does not start on block boundary
sl@0
  3443
		if (firstPartial && ! startUsed)
sl@0
  3444
			*aRBM |= KWtRBMFst;
sl@0
  3445
sl@0
  3446
		// last index was not already in range, and does not end on block boundary
sl@0
  3447
		if (lastPartial && ! endUsed)
sl@0
  3448
			*aRBM |= KWtRBMLst;
sl@0
  3449
sl@0
  3450
		// only use one pre-read if contained in single block
sl@0
  3451
		if (blkCnt == 1 && *aRBM == (KWtRBMFst | KWtRBMLst))
sl@0
  3452
			*aRBM = KWtRBMFst;
sl@0
  3453
sl@0
  3454
		//
sl@0
  3455
		// When double-buffering, RMW for the last block is stored in the
sl@0
  3456
		// minor buffer and writen during the last transfer, so flag this
sl@0
  3457
		// seperately (as aRBM is used for the initial RMW Read then subsequently cleared).
sl@0
  3458
		//
sl@0
  3459
		if(iDoDoubleBuffer && (*aRBM & KWtRBMLst))
sl@0
  3460
			iDoLastRMW = ETrue;
sl@0
  3461
		}
sl@0
  3462
sl@0
  3463
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:rwb:%x", (TUint32) raby));
sl@0
  3464
sl@0
  3465
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_RESERVEWRITEBLOCKS_EXIT3, this, ( TUint )( raby ) );
sl@0
  3466
	return raby;
sl@0
  3467
	}
sl@0
  3468
sl@0
  3469
void DMmcMediaDriverFlash::MarkBlocks(TInt64 aStart, TInt64 aEnd, TInt aStartIndex)
sl@0
  3470
//
sl@0
  3471
// mark range of blocks for media range.  If existing cache entries for any part of
sl@0
  3472
// the cache are already in the buffer they are invalidated.
sl@0
  3473
//
sl@0
  3474
	{
sl@0
  3475
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_MARKBLOCKS_ENTRY, this );
sl@0
  3476
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:mb:%lx,%lx,%d", aStart, aEnd, aStartIndex));
sl@0
  3477
sl@0
  3478
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(EMBStPos));
sl@0
  3479
	__ASSERT_DEBUG((aStart & iBlkMsk) == 0, Panic(EMBStAlign));
sl@0
  3480
	__ASSERT_DEBUG(aEnd > aStart, Panic(EMBNotPositive));
sl@0
  3481
	__ASSERT_DEBUG(TotalSizeInBytes() >= aEnd, Panic(EMBEndPos));
sl@0
  3482
	__ASSERT_DEBUG((aEnd & iBlkMsk) == 0, Panic(EMBEndAlign));
sl@0
  3483
	__ASSERT_DEBUG(aStartIndex + (TInt)((aEnd - aStart) >> iBlkLenLog2) <= iBlocksInBuffer, Panic(EMBOverflow));
sl@0
  3484
	__ASSERT_CACHE(CacheInvariant(), Panic(EMBCchInvPre));
sl@0
  3485
sl@0
  3486
	TInt i;
sl@0
  3487
sl@0
  3488
	for (i = 0; i < aStartIndex; ++i)
sl@0
  3489
		{
sl@0
  3490
		if (iCachedBlocks[i] >= aStart && iCachedBlocks[i] < aEnd)
sl@0
  3491
			iCachedBlocks[i] = KInvalidBlock;
sl@0
  3492
		}
sl@0
  3493
sl@0
  3494
	TInt blkCnt = I64LOW((aEnd - aStart) >> iBlkLenLog2);
sl@0
  3495
	OstTrace1( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_MARKBLOCKS_RANGE, "blkCnt=%d", blkCnt );
sl@0
  3496
	for (i = aStartIndex; i < aStartIndex + blkCnt; ++i)
sl@0
  3497
		iCachedBlocks[i] = aStart + (static_cast<TUint32>(i - aStartIndex) << iBlkLenLog2);
sl@0
  3498
sl@0
  3499
	for (i = aStartIndex + blkCnt; i < iBlocksInBuffer; ++i)
sl@0
  3500
		{
sl@0
  3501
		if (iCachedBlocks[i] >= aStart && iCachedBlocks[i] < aEnd)
sl@0
  3502
			iCachedBlocks[i] = KInvalidBlock;
sl@0
  3503
		}
sl@0
  3504
sl@0
  3505
	__ASSERT_CACHE(CacheInvariant(), Panic(EMBCchInvPost));
sl@0
  3506
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_MARKBLOCKS_EXIT, this );
sl@0
  3507
	}
sl@0
  3508
sl@0
  3509
sl@0
  3510
void DMmcMediaDriverFlash::BuildGammaArray(TInt64 aStart, TInt64 aEnd)
sl@0
  3511
//
sl@0
  3512
// iGamma is an array of indexes that correspond to cached blocks starting
sl@0
  3513
// from aStart.  iGamma[0] is the index of aStart, iGamma[1] is the index of
sl@0
  3514
// aStart + iBlkLen, and so on.  Building an array here means that all of
sl@0
  3515
// the available cached entries can be found in linear time instead of
sl@0
  3516
// quadratically searching through the array for each block.
sl@0
  3517
//
sl@0
  3518
	{
sl@0
  3519
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_BUILDGAMMAARRAY_ENTRY, this );
sl@0
  3520
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:bga:%lx,%lx", aStart, aEnd));
sl@0
  3521
sl@0
  3522
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(EBGAStPos));
sl@0
  3523
	__ASSERT_DEBUG((aStart & iBlkMsk) == 0, Panic(EBGAStAlign));
sl@0
  3524
	__ASSERT_DEBUG(aEnd > aStart, Panic(EBGANotPositive));
sl@0
  3525
	__ASSERT_DEBUG(TotalSizeInBytes() >= aEnd, Panic(EBGAEndPos));
sl@0
  3526
	__ASSERT_DEBUG((aEnd & iBlkMsk) == 0, Panic(EBGAEndAlign));
sl@0
  3527
	__ASSERT_DEBUG(aEnd - aStart <= (TInt64) iMaxBufSize, Panic(EBGAOverflow));
sl@0
  3528
	__ASSERT_CACHE(CacheInvariant(), Panic(EBGACchInv));
sl@0
  3529
sl@0
  3530
	// KNoCacheBlock = (0xff) x 4
sl@0
  3531
	TUint blocksInRange = I64LOW((aEnd - aStart) >> iBlkLenLog2);
sl@0
  3532
	OstTrace1( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_BUILDGAMMAARRAY_RANGE, "blocksInRange=%d", blocksInRange );
sl@0
  3533
	memset(iGamma, 0xff, sizeof(*iGamma) * blocksInRange);
sl@0
  3534
sl@0
  3535
	TInt64 blkAddr = 0;
sl@0
  3536
	for (TInt i = 0; ( (blocksInRange > 0 ) && (i < iBlocksInBuffer) ); ++i)
sl@0
  3537
		{
sl@0
  3538
		blkAddr = iCachedBlocks[i];
sl@0
  3539
		if (blkAddr >= aStart && blkAddr < aEnd)
sl@0
  3540
			{
sl@0
  3541
			iGamma[I64LOW((blkAddr - aStart) >> iBlkLenLog2)] = i;
sl@0
  3542
			blocksInRange--;
sl@0
  3543
			}
sl@0
  3544
		}
sl@0
  3545
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_BUILDGAMMAARRAY_EXIT, this );
sl@0
  3546
	}
sl@0
  3547
sl@0
  3548
void DMmcMediaDriverFlash::InvalidateCache()
sl@0
  3549
	{
sl@0
  3550
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_INVALIDATECACHE1_ENTRY );
sl@0
  3551
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:ich"));
sl@0
  3552
sl@0
  3553
	// KInvalidBlock = (0xff) x 4
sl@0
  3554
	memset(iCachedBlocks, 0xff, sizeof(*iCachedBlocks) * iBlocksInBuffer);
sl@0
  3555
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_INVALIDATECACHE1_EXIT );
sl@0
  3556
	}
sl@0
  3557
sl@0
  3558
// Invalidate any cache entries from aStart to aEnd
sl@0
  3559
// This is for DMA writes and is to prevent the cache becoming inconsistent with the media.
sl@0
  3560
void DMmcMediaDriverFlash::InvalidateCache(TInt64 aStart, TInt64 aEnd)
sl@0
  3561
	{
sl@0
  3562
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_INVALIDATECACHE2_ENTRY, this );
sl@0
  3563
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:ich:%lx,%lx", aStart, aEnd));
sl@0
  3564
sl@0
  3565
	__ASSERT_DEBUG(TotalSizeInBytes() > aStart, Panic(EBGAStPos));
sl@0
  3566
	__ASSERT_DEBUG(aEnd > aStart, Panic(EBGANotPositive));
sl@0
  3567
	__ASSERT_DEBUG(TotalSizeInBytes() >= aEnd, Panic(EBGAEndPos));
sl@0
  3568
sl@0
  3569
	const TInt blkCnt = I64LOW((aStart - aEnd) >> iBlkLenLog2);
sl@0
  3570
	OstTrace1( TRACE_INTERNALS, DMMCMEDIADRIVERFLASH_INVALIDATECACHE_RANGE, "blocksInRange=%d", blkCnt );
sl@0
  3571
sl@0
  3572
	__ASSERT_CACHE(CacheInvariant(), Panic(EBGACchInv));
sl@0
  3573
	
sl@0
  3574
	TInt64 endBlk = (blkCnt == 0) ? (aStart+iBlkLen) : aEnd;			
sl@0
  3575
	
sl@0
  3576
	for (TInt i = 0; i < iBlocksInBuffer; ++i)
sl@0
  3577
		{
sl@0
  3578
		const TInt64 blkAddr = iCachedBlocks[i];
sl@0
  3579
		if (blkAddr >= aStart && blkAddr < endBlk)
sl@0
  3580
			iCachedBlocks[i] = KInvalidBlock;
sl@0
  3581
		}
sl@0
  3582
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_INVALIDATECACHE2_EXIT, this );
sl@0
  3583
	}
sl@0
  3584
sl@0
  3585
TUint8* DMmcMediaDriverFlash::IdxToCchMem(TInt aIdx) const
sl@0
  3586
	{
sl@0
  3587
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_IDXTOCCHMEM_ENTRY, this );
sl@0
  3588
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("=mmd:icm:%d", aIdx));
sl@0
  3589
sl@0
  3590
	__ASSERT_DEBUG(aIdx >= 0, Panic(EICMNegative));
sl@0
  3591
	__ASSERT_DEBUG(aIdx < iBlocksInBuffer, Panic(EICMOverflow));
sl@0
  3592
	
sl@0
  3593
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_IDXTOCCHMEM_EXIT, this );
sl@0
  3594
	return &iCacheBuf[aIdx << iBlkLenLog2];
sl@0
  3595
	}
sl@0
  3596
sl@0
  3597
TInt DMmcMediaDriverFlash::CchMemToIdx(TUint8* aMemP) const
sl@0
  3598
	{
sl@0
  3599
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_CCHMEMTOIDX_ENTRY, this );
sl@0
  3600
	__ASSERT_DEBUG((aMemP >= iCacheBuf) && (aMemP < iCacheBuf + (iBlocksInBuffer << iBlkLenLog2)), Panic(ECMIOverflow));
sl@0
  3601
sl@0
  3602
	return((aMemP - iCacheBuf) >> iBlkLenLog2);
sl@0
  3603
	}
sl@0
  3604
sl@0
  3605
#ifdef _DEBUG_CACHE
sl@0
  3606
TBool DMmcMediaDriverFlash::CacheInvariant()
sl@0
  3607
//
sl@0
  3608
// check each cache entry refers to a valid block and that no two
sl@0
  3609
// entries cover the same block.  This algorithm is quadratic in
sl@0
  3610
// the cache length.
sl@0
  3611
//
sl@0
  3612
	{
sl@0
  3613
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_CACHEINVARIANT_ENTRY, this );
sl@0
  3614
	for (TInt i = 0; i < iBlocksInBuffer; ++i)
sl@0
  3615
		{
sl@0
  3616
		if (iCachedBlocks[i] == KInvalidBlock)
sl@0
  3617
			continue;
sl@0
  3618
sl@0
  3619
		if ((iCachedBlocks[i] & iBlkMsk) != 0)
sl@0
  3620
			return EFalse;
sl@0
  3621
sl@0
  3622
		if (iCachedBlocks[i] >= TotalSizeInBytes())
sl@0
  3623
			return EFalse;
sl@0
  3624
sl@0
  3625
		for (TInt j = i + 1; j < iBlocksInBuffer; ++j)
sl@0
  3626
			{
sl@0
  3627
			if (iCachedBlocks[i] == iCachedBlocks[j])
sl@0
  3628
				return EFalse;
sl@0
  3629
			}
sl@0
  3630
		}
sl@0
  3631
sl@0
  3632
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_CACHEINVARIANT_EXIT, this );
sl@0
  3633
	return ETrue;
sl@0
  3634
	}
sl@0
  3635
#endif
sl@0
  3636
sl@0
  3637
void DMmcMediaDriverFlash::NotifyPowerDown()
sl@0
  3638
	{
sl@0
  3639
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_NOTIFYPOWERDOWN_ENTRY );
sl@0
  3640
	__KTRACE_OPT(KPBUSDRV,Kern::Printf(">Mmc:NotifyPowerDown"));
sl@0
  3641
sl@0
  3642
	iSessionEndDfc.Cancel();
sl@0
  3643
	iDataTransferCallBackDfc.Cancel();
sl@0
  3644
sl@0
  3645
	EndInCritical();
sl@0
  3646
sl@0
  3647
	// need to cancel the session as the stack doesn't take too kindly to having the same session engaged more than once.
sl@0
  3648
	if (iSession)
sl@0
  3649
		iStack->CancelSession(iSession);
sl@0
  3650
sl@0
  3651
	CompleteRequest(KErrNotReady);
sl@0
  3652
	iMedReq = EMReqIdle;
sl@0
  3653
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_NOTIFYPOWERDOWN_EXIT );
sl@0
  3654
	}
sl@0
  3655
sl@0
  3656
void DMmcMediaDriverFlash::NotifyEmergencyPowerDown()
sl@0
  3657
	{
sl@0
  3658
	OstTraceFunctionEntry0( DMMCMEDIADRIVERFLASH_NOTIFYEMERGENCYPOWERDOWN_ENTRY );
sl@0
  3659
	__KTRACE_OPT(KPBUSDRV,Kern::Printf(">Ata:NotifyEmergencyPowerDown"));
sl@0
  3660
sl@0
  3661
	iSessionEndDfc.Cancel();
sl@0
  3662
	iDataTransferCallBackDfc.Cancel();
sl@0
  3663
sl@0
  3664
	TInt r=KErrNotReady;
sl@0
  3665
	if (iCritical)
sl@0
  3666
		r=KErrAbort;
sl@0
  3667
	EndInCritical();
sl@0
  3668
sl@0
  3669
	// need to cancel the session as the stack doesn't take too kindly to having the same session engaged more than once.
sl@0
  3670
	if (iSession)
sl@0
  3671
		iStack->CancelSession(iSession);
sl@0
  3672
sl@0
  3673
	CompleteRequest(r);
sl@0
  3674
	iMedReq = EMReqIdle;
sl@0
  3675
	OstTraceFunctionExit0( DMMCMEDIADRIVERFLASH_NOTIFYEMERGENCYPOWERDOWN_EXIT );
sl@0
  3676
	}
sl@0
  3677
sl@0
  3678
TInt DMmcMediaDriverFlash::Request(TLocDrvRequest& aRequest)
sl@0
  3679
	{
sl@0
  3680
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_REQUEST_ENTRY, this );
sl@0
  3681
	__KTRACE_OPT(KLOCDRV,Kern::Printf("MmcMd:Req %08x id %d",&aRequest,aRequest.Id()));
sl@0
  3682
	TInt r=KErrNotSupported;
sl@0
  3683
	TInt id=aRequest.Id();
sl@0
  3684
	OstTraceDefExt2( OST_TRACE_CATEGORY_RND, TRACE_REQUEST, DMMCMEDIADRIVERFLASH_REQUEST_ID, "Request=0x%08x; Request ID=%d", (TUint) &aRequest, id);
sl@0
  3685
sl@0
  3686
#if defined (__TEST_PAGING_MEDIA_DRIVER__)
sl@0
  3687
	DThread* client=aRequest.Client();
sl@0
  3688
	__KTRACE_OPT(KLOCDPAGING,Kern::Printf("Client:0x%08x",client));
sl@0
  3689
	OstTraceDef1( OST_TRACE_CATEGORY_RND, TRACE_REQUEST, DMMCMEDIADRIVERFLASH_REQUEST_CLIENT, "Request client=0x%08x", (TUint) client);
sl@0
  3690
#endif // __TEST_PAGING_MEDIA_DRIVER__
sl@0
  3691
sl@0
  3692
	// First handle requests that can be handled without deferring
sl@0
  3693
	if(id==DLocalDrive::ECaps)
sl@0
  3694
		{
sl@0
  3695
		TLocalDriveCapsV6& c = *(TLocalDriveCapsV6*)aRequest.RemoteDes();
sl@0
  3696
		TLocDrv& drive = *aRequest.Drive();
sl@0
  3697
		r = Caps(drive, c);
sl@0
  3698
		c.iSize = drive.iPartitionLen;
sl@0
  3699
		c.iPartitionType = drive.iPartitionType;	
sl@0
  3700
		c.iHiddenSectors = (TUint) (drive.iPartitionBaseAddr >> KDiskSectorShift);
sl@0
  3701
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_REQUEST_EXIT1, this, r );
sl@0
  3702
		return r;
sl@0
  3703
		}
sl@0
  3704
sl@0
  3705
	// All other requests must be deferred if a request is currently in progress
sl@0
  3706
	if (iCurrentReq)
sl@0
  3707
		{
sl@0
  3708
sl@0
  3709
#if defined(__TEST_PAGING_MEDIA_DRIVER__)
sl@0
  3710
		if (DMediaPagingDevice::PageInRequest(*iCurrentReq))
sl@0
  3711
			iMmcStats.iReqPage++;
sl@0
  3712
		else
sl@0
  3713
			iMmcStats.iReqNormal++;
sl@0
  3714
#endif // __TEST_PAGING_MEDIA_DRIVER__
sl@0
  3715
sl@0
  3716
		// a request is already in progress, so hold on to this one
sl@0
  3717
		__KTRACE_OPT(KLOCDRV,Kern::Printf("MmcMd:Req %08x ret 1",&aRequest));
sl@0
  3718
		OstTraceDef1( OST_TRACE_CATEGORY_RND, TRACE_REQUEST, DMMCMEDIADRIVERFLASH_REQUEST_IN_PROGRESS, "Request in progress=0x%08x", (TUint) &aRequest);
sl@0
  3719
		OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_REQUEST_EXIT2, this, KMediaDriverDeferRequest );
sl@0
  3720
		return KMediaDriverDeferRequest;
sl@0
  3721
		}
sl@0
  3722
	else
sl@0
  3723
		{
sl@0
  3724
		iCurrentReq=&aRequest;
sl@0
  3725
		TUint partitionType = iCurrentReq->Drive()->iPartitionType;
sl@0
  3726
		TBool readOnly = (partitionType == KPartitionTypeRofs || partitionType == KPartitionTypeROM);
sl@0
  3727
sl@0
  3728
		switch (id)
sl@0
  3729
			{
sl@0
  3730
sl@0
  3731
sl@0
  3732
#if defined(__DEMAND_PAGING__)
sl@0
  3733
			case DMediaPagingDevice::ERomPageInRequest:
sl@0
  3734
				__KTRACE_OPT(KLOCDPAGING,Kern::Printf("DMediaDriverFlash::Request(ERomPageInRequest)"));
sl@0
  3735
				BTraceContext8(BTrace::EPagingMedia,BTrace::EPagingMediaPagingMedDrvBegin,MEDIA_DEVICE_MMC,iCurrentReq);
sl@0
  3736
				OstTraceDef0( OST_TRACE_CATEGORY_RND, TRACE_REQUEST, DMMCMEDIADRIVERFLASH_REQUEST_ROM_PAGE_IN, "ROM page-in request");
sl@0
  3737
				r=DoRead();
sl@0
  3738
				break;
sl@0
  3739
			case DMediaPagingDevice::ECodePageInRequest:
sl@0
  3740
				__KTRACE_OPT(KLOCDPAGING,Kern::Printf("DMediaDriverFlash::Request(ECodePageInRequest)"));
sl@0
  3741
				BTraceContext8(BTrace::EPagingMedia,BTrace::EPagingMediaPagingMedDrvBegin,MEDIA_DEVICE_MMC,iCurrentReq);
sl@0
  3742
				OstTraceDef0( OST_TRACE_CATEGORY_RND, TRACE_REQUEST, DMMCMEDIADRIVERFLASH_REQUEST_CODE_PAGE_IN, "Code page-in request");
sl@0
  3743
				r=DoRead();
sl@0
  3744
				break;
sl@0
  3745
#endif	// __DEMAND_PAGING__
sl@0
  3746
sl@0
  3747
			case DLocalDrive::EQueryDevice:
sl@0
  3748
				r = KErrNotSupported;
sl@0
  3749
				break;
sl@0
  3750
sl@0
  3751
			case DLocalDrive::ERead:
sl@0
  3752
				r=DoRead();
sl@0
  3753
				break;
sl@0
  3754
			case DLocalDrive::EWrite:
sl@0
  3755
				if (readOnly)
sl@0
  3756
				    {
sl@0
  3757
					OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_REQUEST_EXIT3, this, KErrNotSupported );
sl@0
  3758
					return KErrNotSupported;
sl@0
  3759
				    }
sl@0
  3760
				r=DoWrite();
sl@0
  3761
				break;
sl@0
  3762
			case DLocalDrive::EFormat:
sl@0
  3763
				if (readOnly)
sl@0
  3764
				    {
sl@0
  3765
					OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_REQUEST_EXIT4, this, KErrNotSupported );
sl@0
  3766
					return KErrNotSupported;
sl@0
  3767
				    }
sl@0
  3768
				r=DoFormat();
sl@0
  3769
				break;
sl@0
  3770
sl@0
  3771
#if defined __TEST_PAGING_MEDIA_DRIVER__
sl@0
  3772
			case DLocalDrive::EControlIO:
sl@0
  3773
				{
sl@0
  3774
				r = HandleControlIORequest();
sl@0
  3775
				break;
sl@0
  3776
				}
sl@0
  3777
#endif
sl@0
  3778
sl@0
  3779
			case DLocalDrive::EPasswordUnlock:
sl@0
  3780
			case DLocalDrive::EPasswordLock:
sl@0
  3781
			case DLocalDrive::EPasswordClear:
sl@0
  3782
				// Don't allow passords on internal MMC; one reason is that this may be used for paging and 
sl@0
  3783
				// we can't really stop paging just because the password hasn't been supplied
sl@0
  3784
				if (iInternalSlot)
sl@0
  3785
					r = KErrNotSupported;
sl@0
  3786
				else
sl@0
  3787
					r = DoPasswordOp();
sl@0
  3788
				break;
sl@0
  3789
			case DLocalDrive::EPasswordErase:
sl@0
  3790
				{
sl@0
  3791
				r = LaunchRPIErase();
sl@0
  3792
				// This will complete the request in the event of an error
sl@0
  3793
				if(r != KErrNone)
sl@0
  3794
					PartitionInfoComplete(r);
sl@0
  3795
sl@0
  3796
				r = KErrNone; // ensures to indicate asynchronoous completion
sl@0
  3797
				break;
sl@0
  3798
				}
sl@0
  3799
			case DLocalDrive::EWritePasswordStore:
sl@0
  3800
				{
sl@0
  3801
				//
sl@0
  3802
				// If the card is ready and locked, request the stack to perform the 
sl@0
  3803
				// auto-unlock sequence.  This is required, as the stack only performs
sl@0
  3804
				// automatic unlocking during power-up, and the stack may already be powered.
sl@0
  3805
				//
sl@0
  3806
				r = KErrNone; // asynchronous completion
sl@0
  3807
sl@0
  3808
				if(iCard->IsReady() && iCard->IsLocked())
sl@0
  3809
					{
sl@0
  3810
					iSession->SetupCIMAutoUnlock();
sl@0
  3811
					if(EngageAndSetRequest(EMReqWritePasswordData, 0) != KErrNone)
sl@0
  3812
						{
sl@0
  3813
						// If error, complete with KErrNone anyway
sl@0
  3814
						//  - The password store has been set, any errors
sl@0
  3815
						//    will be reported on the next access.
sl@0
  3816
						CompleteRequest(KErrNone);
sl@0
  3817
						}
sl@0
  3818
					}
sl@0
  3819
				else
sl@0
  3820
					{
sl@0
  3821
					CompleteRequest(KErrNone);
sl@0
  3822
					}
sl@0
  3823
				break;
sl@0
  3824
				}
sl@0
  3825
			case DLocalDrive::EEnlarge:
sl@0
  3826
			case DLocalDrive::EReduce:
sl@0
  3827
			default:
sl@0
  3828
				r=KErrNotSupported;
sl@0
  3829
				break;
sl@0
  3830
			}
sl@0
  3831
		}
sl@0
  3832
sl@0
  3833
	__KTRACE_OPT(KLOCDRV,Kern::Printf("MmcMd:Req %08x cmp %d",&aRequest,r));
sl@0
  3834
sl@0
  3835
	if (r != KErrNone)
sl@0
  3836
		{
sl@0
  3837
		iMedReq = EMReqIdle;
sl@0
  3838
		iCurrentReq=NULL;
sl@0
  3839
		SetCurrentConsumption(KIdleCurrentInMilliAmps);
sl@0
  3840
		}
sl@0
  3841
	
sl@0
  3842
	OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_REQUEST_EXIT5, this, r );
sl@0
  3843
	return r;
sl@0
  3844
	}
sl@0
  3845
sl@0
  3846
void DMmcMediaDriverFlash::Disconnect(DLocalDrive* aLocalDrive, TThreadMessage* aMsg)
sl@0
  3847
	{
sl@0
  3848
	OstTraceFunctionEntry1( DMMCMEDIADRIVERFLASH_DISCONNECT_ENTRY, this );
sl@0
  3849
	// Complete using the default implementation
sl@0
  3850
	DMediaDriver::Disconnect(aLocalDrive, aMsg);
sl@0
  3851
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_DISCONNECT_EXIT, this );
sl@0
  3852
	}
sl@0
  3853
sl@0
  3854
#ifdef _DEBUG_CACHE
sl@0
  3855
TUint8* DMmcMediaDriverFlash::GetCachedBlock(TInt64 aMdAddr)
sl@0
  3856
// 
sl@0
  3857
// return cache block for media at aMdAddr, 0 if not found.
sl@0
  3858
// This is a debug function to determine whether or not a block is in
sl@0
  3859
// the cache.  It should not be used for general block retrieval.
sl@0
  3860
// If there are m blocks in the cache, and n in the requested range,
sl@0
  3861
// this function is o(mn), whereas BuildGammaArray() is theta(m).
sl@0
  3862
//
sl@0
  3863
	{
sl@0
  3864
	OstTraceFunctionEntryExt( DMMCMEDIADRIVERFLASH_GETCACHEDBLOCK_ENTRY, this );
sl@0
  3865
	__KTRACE_OPT(KPBUSDRV, Kern::Printf(">mmd:gcb:%lx", aMdAddr));
sl@0
  3866
sl@0
  3867
	__ASSERT_DEBUG((aMdAddr & iBlkMsk) == 0, Panic(EGCBAlign));
sl@0
  3868
	__ASSERT_DEBUG(TotalSizeInBytes() > aMdAddr, Panic(EGCBPos));
sl@0
  3869
	__ASSERT_CACHE(CacheInvariant(), Panic(EGCBCchInv));
sl@0
  3870
sl@0
  3871
	for (TInt i = 0; i < iBlocksInBuffer; ++i)
sl@0
  3872
		{
sl@0
  3873
		if (iCachedBlocks[i] == aMdAddr)
sl@0
  3874
			{
sl@0
  3875
			TUint8* raby = IdxToCchMem(i);
sl@0
  3876
			__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:gcb:%x", (TUint32) raby));
sl@0
  3877
			OstTraceFunctionExitExt( DMMCMEDIADRIVERFLASH_GETCACHEDBLOCK_EXIT1, this, ( TUint )( raby ) );
sl@0
  3878
			return raby;
sl@0
  3879
			}
sl@0
  3880
		}
sl@0
  3881
sl@0
  3882
	__KTRACE_OPT(KPBUSDRV, Kern::Printf("<mmd:gcb:0"));
sl@0
  3883
	OstTraceFunctionExit1( DMMCMEDIADRIVERFLASH_GETCACHEDBLOCK_EXIT2, this );
sl@0
  3884
	return 0;
sl@0
  3885
	}
sl@0
  3886
#endif // _DEBUG_CACHE
sl@0
  3887
sl@0
  3888
sl@0
  3889
#if defined(__TEST_PAGING_MEDIA_DRIVER__)
sl@0
  3890
/**
sl@0
  3891
Handles a ControlIO request to the MMC media driver.
sl@0
  3892
made by one of the MMC paging tests
sl@0
  3893
sl@0
  3894
@internalTechnology
sl@0
  3895
sl@0
  3896
@return Corresponding Symbian OS error code
sl@0
  3897
*/
sl@0
  3898
TInt DMmcMediaDriverFlash::HandleControlIORequest()
sl@0
  3899
	{
sl@0
  3900
	const TInt command = iCurrentReq->Int0();
sl@0
  3901
	TAny* aParam1 = iCurrentReq->Ptr1();
sl@0
  3902
//	TAny* aParam2 = iCurrentReq->Ptr2();
sl@0
  3903
sl@0
  3904
	TInt r = KErrCompletion;
sl@0
  3905
sl@0
  3906
	__KTRACE_OPT(KLOCDPAGING,Kern::Printf("[MD :   ] HandleControlIORequest aCommand: 0x%x", command));
sl@0
  3907
sl@0
  3908
sl@0
  3909
	switch (command)
sl@0
  3910
		{
sl@0
  3911
		case KMmcGetStats:
sl@0
  3912
			{	
sl@0
  3913
			DThread* pC = iCurrentReq->Client();
sl@0
  3914
			DThread* pT = iCurrentReq->RemoteThread();
sl@0
  3915
			if (!pT)
sl@0
  3916
				pT = pC;
sl@0
  3917
			Kern::ThreadRawWrite(pT, aParam1, &iMmcStats, sizeof(iMmcStats), pC);
sl@0
  3918
		
sl@0
  3919
			iMmcStats.iReqNormal=0;
sl@0
  3920
			iMmcStats.iNormalFragmenting=0;
sl@0
  3921
			iMmcStats.iClashFragmenting=0;
sl@0
  3922
				
sl@0
  3923
			break; 
sl@0
  3924
			}
sl@0
  3925
		default:
sl@0
  3926
			r=KErrNotSupported;
sl@0
  3927
			break;
sl@0
  3928
		}
sl@0
  3929
sl@0
  3930
	return r;
sl@0
  3931
	}
sl@0
  3932
#endif	// __TEST_PAGING_MEDIA_DRIVER__
sl@0
  3933
sl@0
  3934
sl@0
  3935
sl@0
  3936
sl@0
  3937
DECLARE_EXTENSION_PDD()
sl@0
  3938
	{
sl@0
  3939
	// NB if the media driver has been defined as a kernel extension in the .OBY/.IBY file 
sl@0
  3940
	// i.e the "extension" keyword has been used rather than "device", then an instance of 
sl@0
  3941
	// DPhysicalDeviceMediaMmcFlash will already have been created by InitExtension(). In this 
sl@0
  3942
	// case the kernel will see that an object of the same name already exists and delete the 
sl@0
  3943
	// new one.
sl@0
  3944
	return new DPhysicalDeviceMediaMmcFlash;
sl@0
  3945
	}
sl@0
  3946
DECLARE_STANDARD_EXTENSION()
sl@0
  3947
	{	
sl@0
  3948
	__KTRACE_OPT(KBOOT,Kern::Printf("Creating MMCDrv PDD"));
sl@0
  3949
sl@0
  3950
	DPhysicalDeviceMediaMmcFlash* device = new DPhysicalDeviceMediaMmcFlash;
sl@0
  3951
sl@0
  3952
	TInt r;
sl@0
  3953
	if (device==NULL)
sl@0
  3954
		r=KErrNoMemory;
sl@0
  3955
	else
sl@0
  3956
		r=Kern::InstallPhysicalDevice(device);
sl@0
  3957
	__KTRACE_OPT(KBOOT,Kern::Printf("Installing MMCDrv PDD in kernel returned %d",r));
sl@0
  3958
sl@0
  3959
	__KTRACE_OPT(KBOOT,Kern::Printf("Mmc extension entry point drive returns %d",r));
sl@0
  3960
	return r;
sl@0
  3961
	}
sl@0
  3962
	
sl@0
  3963