Revision: 201036 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Wed, 15 Sep 2010 13:42:27 +0300
branchRCL_3
changeset 268 345b1ca54e88
parent 263 9e2d4f7f5028
child 294 039a3e647356
Revision: 201036 Kit: 201036
kernel/eka/base_e32.history.xml
kernel/eka/base_e32.mrp
kernel/eka/drivers/bsp/base_e32_drivers_bsp.mrp
kernel/eka/drivers/debug/group/base_e32_drivers_debug.mrp
kernel/eka/drivers/locmedia/locmedia.cpp
kernel/eka/drivers/media/base_e32_drivers_media.mrp
kernel/eka/include/e32const.h
kernel/eka/include/e32ver.h
kernel/eka/kernel/random.cpp
kernel/eka/release.txt
kernelhwsrv_info/doc_pub/base_how_to_use_t_fatcharsetconv_framework.doc
kernelhwsrv_info/doc_pub/base_smp_user_side_migration_guide.doc
kerneltest/e32test/group/bld.inf
kerneltest/e32test/group/t_pci.mmp
kerneltest/e32test/pci/t_pci.cpp
kerneltest/e32test/pci/t_pci.h
kerneltest/e32utils/group/base_e32utils.mrp
kerneltest/e32utils/hcrscripts/hcrdat.pm
kerneltest/e32utils/hcrscripts/hcrmd.bat
kerneltest/e32utils/hcrscripts/hcrrec.pm
kerneltest/e32utils/hcrscripts/hcrscripts.inf
kerneltest/e32utils/hcrscripts/makehcrdat.pl
kerneltest/e32utils/hcrscripts/test/array_hcrfile.dat
kerneltest/e32utils/hcrscripts/test/array_hcrfile.dat.img
kerneltest/e32utils/hcrscripts/test/array_test.txt
kerneltest/e32utils/hcrscripts/test/integer_hcrfile.dat
kerneltest/e32utils/hcrscripts/test/integer_hcrfile.dat.img
kerneltest/e32utils/hcrscripts/test/integer_test.txt
kerneltest/e32utils/hcrscripts/test/large_hcrfile.dat
kerneltest/e32utils/hcrscripts/test/large_hcrfile.dat.img
kerneltest/e32utils/hcrscripts/test/large_test.txt
kerneltest/e32utils/nistsecurerng/include/cephes.h
kerneltest/e32utils/nistsecurerng/include/config.h
kerneltest/e32utils/nistsecurerng/include/decls.h
kerneltest/e32utils/nistsecurerng/include/defs.h
kerneltest/e32utils/nistsecurerng/include/externs.h
kerneltest/e32utils/nistsecurerng/include/generators.h
kerneltest/e32utils/nistsecurerng/include/genutils.h
kerneltest/e32utils/nistsecurerng/include/matrix.h
kerneltest/e32utils/nistsecurerng/include/stat_fncs.h
kerneltest/e32utils/nistsecurerng/include/utilities.h
kerneltest/e32utils/nistsecurerng/include/utils/openc.h
kerneltest/e32utils/nistsecurerng/src/approximateentropy.cpp
kerneltest/e32utils/nistsecurerng/src/assess.cpp
kerneltest/e32utils/nistsecurerng/src/blockfrequency.cpp
kerneltest/e32utils/nistsecurerng/src/cephes.cpp
kerneltest/e32utils/nistsecurerng/src/cusum.cpp
kerneltest/e32utils/nistsecurerng/src/dfft.cpp
kerneltest/e32utils/nistsecurerng/src/discretefouriertransform.cpp
kerneltest/e32utils/nistsecurerng/src/frequency.cpp
kerneltest/e32utils/nistsecurerng/src/generators.cpp
kerneltest/e32utils/nistsecurerng/src/genutils.cpp
kerneltest/e32utils/nistsecurerng/src/linearcomplexity.cpp
kerneltest/e32utils/nistsecurerng/src/longestrunofones.cpp
kerneltest/e32utils/nistsecurerng/src/math/erf.cpp
kerneltest/e32utils/nistsecurerng/src/matrix.cpp
kerneltest/e32utils/nistsecurerng/src/nonoverlappingtemplatematchings.cpp
kerneltest/e32utils/nistsecurerng/src/overlappingtemplatematchings.cpp
kerneltest/e32utils/nistsecurerng/src/randomexcursions.cpp
kerneltest/e32utils/nistsecurerng/src/randomexcursionsvariant.cpp
kerneltest/e32utils/nistsecurerng/src/rank.cpp
kerneltest/e32utils/nistsecurerng/src/runs.cpp
kerneltest/e32utils/nistsecurerng/src/serial.cpp
kerneltest/e32utils/nistsecurerng/src/universal.cpp
kerneltest/e32utils/nistsecurerng/src/utilities.cpp
kerneltest/e32utils/nistsecurerng/src/utils/openc.cpp
kerneltest/e32utils/nistsecurerng/src/utils/qsort.cpp
kerneltest/e32utils/nistsecurerng/testdata/testdata.zip
kerneltest/f32test/filesystem/fat/t_mount.cpp
kerneltest/f32test/group/t_misc.mmp
kerneltest/f32test/server/t_fsys.cpp
kerneltest/f32test/server/t_misc.cpp
kerneltest/f32test/server/t_proxydrive1.cpp
kerneltest/sdiotest/base_sdiotests.history.xml
kerneltest/sdiotest/base_sdiotests.mrp
kerneltest/sdiotest/bld.inf
kerneltest/sdiotest/d_sdioif.mmp
kerneltest/sdiotest/sdiotest.mmp
kerneltest/sdiotest/source/d_sdioif.cpp
kerneltest/sdiotest/source/d_sdioif.h
kerneltest/sdiotest/source/sdio_io.cpp
kerneltest/sdiotest/source/sdio_io.h
kerneltest/sdiotest/source/sdiotest.cpp
kerneltest/sdiotest/source/sdiotests.h
package_definition.xml
userlibandfileserver/fileserver/group/release.txt
userlibandfileserver/fileserver/inc/f32fsys.inl
userlibandfileserver/fileserver/inc/f32ver.h
userlibandfileserver/fileserver/sfat32/fat_table32.cpp
userlibandfileserver/fileserver/sfat32/sl_mnt.cpp
userlibandfileserver/fileserver/sfat32/sl_mnt32.cpp
userlibandfileserver/fileserver/sfile/sf_drv.cpp
userlibandfileserver/fileserver/sfile/sf_memory_man.cpp
userlibandfileserver/fileserver/sfile/sf_thread.cpp
userlibandfileserver/fileserver/sfile/sf_utl.cpp
userlibandfileserver/fileserver/sfsrv/cl_cli.cpp
userlibandfileserver/fileserver/sfsrv/cl_fman.cpp
userlibandfileserver/fileserver/shostmassstorage/server/controller/cusbhostmsdevice.cpp
userlibandfileserver/fileserver/shostmassstorage/server/controller/cusbhostmsdevicethread.cpp
userlibandfileserver/fileserver/shostmassstorage/server/src/cusbhostmssession.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kernel/eka/base_e32.history.xml	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<relnotes name="Kernel Architecture 2">
+  <purpose>
+  </purpose>
+
+  <minorchange revision="001">
+    MINOR CHANGE: Improved test code T_Match by adding more cases to test for INC092513 (SYSLIB-UNICODE-CT-3337)
+  </minorchange>
+</relnotes>
--- a/kernel/eka/base_e32.mrp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/base_e32.mrp	Wed Sep 15 13:42:27 2010 +0300
@@ -18,6 +18,7 @@
 source	\sf\os\kernelhwsrv\kernel\eka\rombuild
 source	\sf\os\kernelhwsrv\kernel\eka\drivers\paging
 source	\sf\os\kernelhwsrv\kernel\eka\drivers\pipe
+source	\sf\os\kernelhwsrv\kernel\eka\base_e32.history.xml
 source	\sf\os\kernelhwsrv\kernel\eka\base_e32.mrp
 source	\sf\os\kernelhwsrv\kernel\eka\base.bld
 source	\sf\os\kernelhwsrv\kernel\eka\bld.inf
--- a/kernel/eka/drivers/bsp/base_e32_drivers_bsp.mrp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/drivers/bsp/base_e32_drivers_bsp.mrp	Wed Sep 15 13:42:27 2010 +0300
@@ -10,6 +10,8 @@
 source	\sf\os\kernelhwsrv\kernel\eka\drivers\xyin
 source	\sf\os\kernelhwsrv\kernel\eka\drivers\iic
 source  \sf\os\kernelhwsrv\kernel\eka\drivers\hcr
+source  \sf\os\kernelhwsrv\kerneltest\e32utils\hcrscripts
+
 
 binary	\sf\os\kernelhwsrv\kernel\eka\drivers\bsp all
 exports	\sf\os\kernelhwsrv\kernel\eka\drivers\bsp
@@ -18,4 +20,5 @@
 
 
 ipr E
+ipr T \sf\os\kernelhwsrv\kerneltest\e32utils\hcrscripts
 
--- a/kernel/eka/drivers/debug/group/base_e32_drivers_debug.mrp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/drivers/debug/group/base_e32_drivers_debug.mrp	Wed Sep 15 13:42:27 2010 +0300
@@ -3,7 +3,6 @@
 component	base_e32_drivers_debug
 
 source	\sf\os\kernelhwsrv\kernel\eka\debug
-source	\sf\os\kernelhwsrv\kernel\eka\debug\crashMonitor
 source	\sf\os\kernelhwsrv\kernel\eka\drivers\debug
 
 binary	\sf\os\kernelhwsrv\kernel\eka\drivers\debug\group all
--- a/kernel/eka/drivers/locmedia/locmedia.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/drivers/locmedia/locmedia.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -5377,8 +5377,6 @@
 
 		TLocalDriveCapsV6& caps = *(TLocalDriveCapsV6*)capsBuf.Ptr();
 		blockSize = caps.iBlockSize;
-		__ASSERT_DEBUG(blockSize,LOCM_FAULT());
-		__ASSERT_DEBUG(__e32_bit_count_32(blockSize)==1,LOCM_FAULT());
 		
 		TLocDrv* drive;
 		for (i=0; i<KMaxLocalDrives; ++i)
--- a/kernel/eka/drivers/media/base_e32_drivers_media.mrp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/drivers/media/base_e32_drivers_media.mrp	Wed Sep 15 13:42:27 2010 +0300
@@ -54,9 +54,3 @@
 
 
 ipr E
-
-ipr E \sf\os\kernelhwsrv\kernel\eka\drivers\pbus\mmc\sdcard
-# Access to SD Card PIL and PSL Software Source Code and Documentation 
-# is subject to the relevant party entering into the necessary
-# agreement(s) with SD-3C LLC and/or 4C LLC.
-
--- a/kernel/eka/include/e32const.h	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/include/e32const.h	Wed Sep 15 13:42:27 2010 +0300
@@ -2409,7 +2409,7 @@
 	
 
 	/**
-	The free memory level has crossed a specified threshold value.
+	The system's free memory level has crossed a specified threshold value.
 	
 	On systems that support data paging, this is also generated where the available swap space
 	crosses one of the specified threshold values.
@@ -2418,13 +2418,20 @@
 
 	
 	/**
-	A memory allocation has failed due to insufficient free memory.
+	A memory allocation has failed due to insufficient free memory somewhere in the system.
+
+	Please note that this notifcation is generated when any memory allocation fails, not just
+	allocations attempted by the current process.
+
+	This is designed to notify a system memory manager component when a memory allocation failed
+	even when the system's memory has not crossed the low-memory threshold.  It should not be used
+	as part of a memory management strategy within a single process.
 	*/
 	EChangesOutOfMemory=0x40,
 	
 
 	/**
-	The free memory level has fallen below the low-memory threshold
+	The system's free memory level has fallen below the low-memory threshold
 	@see UserSvr::SetMemoryThresholds()
 	*/
 	EChangesLowMemory=0x80,
--- a/kernel/eka/include/e32ver.h	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/include/e32ver.h	Wed Sep 15 13:42:27 2010 +0300
@@ -28,7 +28,7 @@
 
 const TInt KE32MajorVersionNumber=2;
 const TInt KE32MinorVersionNumber=0;
-const TInt KE32BuildVersionNumber=2657;
+const TInt KE32BuildVersionNumber=2660;
 
 const TInt KMachineConfigurationMajorVersionNumber=1;
 const TInt KMachineConfigurationMinorVersionNumber=0;
--- a/kernel/eka/kernel/random.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/kernel/random.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 1994-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 1994-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of the License "Eclipse Public License v1.0"
@@ -119,9 +119,9 @@
 
 	// The random number generator requires a temporary buffer to write the data to, before we write it back to
 	// userspace's buffer. The buffer is allocated here on the stack to avoid having to heap-allocate, and if
-	// the requested amount of data is larger, a loop is used. 2048 bytes will always fit onto the stack in an
+	// the requested amount of data is larger, a loop is used. 1024 bytes will always fit onto the stack in an
 	// exec handler.
-	const TInt KRandomBufferSize = 2048;
+	const TInt KRandomBufferSize = 1024;
 	TBuf8<KRandomBufferSize> randomBuffer;
 
 	TInt err = KErrNone;
--- a/kernel/eka/release.txt	Tue Sep 14 23:56:21 2010 +0300
+++ b/kernel/eka/release.txt	Wed Sep 15 13:42:27 2010 +0300
@@ -1,3 +1,42 @@
+Version 2.00.2660
+=================
+(Made by fadhliM 24/08/2010)
+
+1.	cnotton
+	1.	ou1cimx1#532041 ENV ExecHandler::MathSecureRandom() allocates a large amount of stack space
+
+
+Version 2.00.2659
+=================
+(Made by fadhliM 23/08/2010)
+
+1.	jimhofe
+	1.	ou1cimx1#526275 [System Build] Dummy MPR files cause build break in TB92SF_1229
+
+
+Version 2.00.2658
+=================
+(Made by fadhliM 16/08/2010)
+
+1.	jimhofe
+	1.	MINOR_CHANGE Removing names from documentation
+
+2.	t30zhang
+	1.	ou1cimx1#521838 Mutex order issue in USB host stack
+
+3.	jcoppear
+	1.	ou1cimx1#524810 EChangesOutOfMemory is prone to misuse
+
+4.	fagortz
+	1.	ou1cimx1#522998 LocDrv::RegisterPagingDevice() assumes iblockSize is non-zero
+
+5.	mmoate
+	1.	ou1cimx1#462350 DEV TB92 CBR issues affecting component delivery to foundation for Symbian^3
+
+6.	jukwak
+	1.	ou1cimx1#516021 [DEV] t_pci has dependency on naviengine. Propagated from MCL.
+
+
 Version 2.00.2657
 =================
 (Made by fadhliM 06/08/2010)
Binary file kernelhwsrv_info/doc_pub/base_how_to_use_t_fatcharsetconv_framework.doc has changed
Binary file kernelhwsrv_info/doc_pub/base_smp_user_side_migration_guide.doc has changed
--- a/kerneltest/e32test/group/bld.inf	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/e32test/group/bld.inf	Wed Sep 15 13:42:27 2010 +0300
@@ -69,7 +69,6 @@
 ../dll/oe/eabi/urel/t_oeexport1.exe     /epoc32/release/armv5/urel/t_oeexport1.exe
 
 ../demandpaging/d_pagestress.h		/epoc32/include/
-../pci/t_pci.h						/epoc32/include/e32test/t_pci.h
 
 ../iic/iic_psl/i2c.h			/epoc32/include/e32test/
 ../iic/iic_psl/spi.h			/epoc32/include/e32test/
@@ -1046,7 +1045,4 @@
 
 #include "../hcr/hcr.inf"
 
-//pci tests
-t_pci
-
 sdapctest
--- a/kerneltest/e32test/group/t_pci.mmp	Tue Sep 14 23:56:21 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "Eclipse Public License v1.0"
-// which accompanies this distribution, and is available
-// at the URL "http://www.eclipse.org/legal/epl-v10.html".
-//
-// Initial Contributors:
-// Nokia Corporation - initial contribution.
-//
-// Contributors:
-//
-// Description: 
-// e32test/group/t_pci.mmp
-
-TARGET         t_pci.exe
-TARGETTYPE     EXE
-SOURCEPATH	../pci
-SOURCE         t_pci.cpp
-LIBRARY        euser.lib
-OS_LAYER_SYSTEMINCLUDE_SYMBIAN
-
-CAPABILITY	ReadDeviceData WriteDeviceData
-
-VENDORID 0x70000001
-
-SMPSAFE
--- a/kerneltest/e32test/pci/t_pci.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,865 +0,0 @@
-// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "Eclipse Public License v1.0"
-// which accompanies this distribution, and is available
-// at the URL "http://www.eclipse.org/legal/epl-v10.html".
-//
-// Initial Contributors:
-// Nokia Corporation - initial contribution.
-//
-// Contributors:
-//
-// Description:
-// This is a test for the PCI driver, so far implemented only on the
-// Naviengine platform. It aims to test:
-//	-That known values of data in config and memory space, on a given
-//	device can be read as expected.
-//	-That data can be written and modified in config and memory space
-//	-PCI memory buffers mapped or allocated by the PCI driver work as
-//	expected. These are
-//		-DChunk created by PCI driver and accessible from PCI
-//		-DPlatHwChunk created by PCI driver and accessible from PCI
-//		-DChunk created externally, then mapped in to PCI memory space
-//	There are tests to:
-//		- Create and close each buffer. Heap checking ensures proper
-//		cleanup
-//		- Create and close multiple buffers from multiple threads.
-//		This is an SMP focused test to check that the implementation
-//		of the chunk manager and allocator in the driver are thread
-//		safe. The tests should pass without triggering any assertions in
-//		the driver's invariance checks.
-//		- Write to buffers from software, and read back via the
-//		system to PCI window, and vice-versa -- a loop-back test.
-//		This checks that PCI buffers are indeed accessible to PCI devices.
-//
-// The tests require several pieces of PSL specific information:
-//	- A TPciDevice containing the vendor and device IDs of a PCI device
-//	to use for testing.
-//	- TAddrSpaceTests which identify regions of a device's config and
-//	memory space with known values, or which are known to be writable.
-//
-//	The test driver grants access to the PCI API with the following
-//	constructs: 
-//	- TUserConfigSpace and TUserMemorySpace, derived from TUserPciSpace,
-//	which are user side equivalents of kernel-side objects allowing
-//	accesses of different sizes to a PCI device's config space or
-//	memory space.
-//	- RPciChunk which is derived from and RChunk and corresponds to
-//	a kernel-side DChunk, which in turn corresponds to a PCI chunk or
-//	buffer. The test driver uses these for all PCI chunk types (a
-//	"wrapper" DChunk is used to map the memory of a PCI DPlatHwChunk
-//	to user side).
-//
-//	Known Issues:
-//	The test driver d_pci is intended to be platform independent but
-//	for now still contains some PSL specific information .eg the test
-//	info structure (which should really be passed up from the PSL) and
-//	the address and size of the system to pci window. For now the
-//	test driver code will remain in the Naviengine baseport directory.
-//	If the PCI driver is ever ported to a new platform this can be
-//	rectified.
-//	
-//
-//
-#include "../misc/test_thread.h"
-#include <e32std.h>
-#define __E32TEST_EXTENSION__
-#include <e32test.h>
-#include "t_pci.h"
-#include <assp/naviengine/pci.h>
-
-class RPci;
-/**
-Extends RChunk to hold the PCI address
-associated with a chunk.
-*/
-class RPciChunk: public RChunk
-	{
-public:
-	TUint PciBase()
-		{
-		return iPciBaseAddr;
-		}
-
-	/**
-	Return the PCI accessible size
-	*/
-	TInt Size() const
-		{
-		return iPciSize;
-		}
-
-private:
-	friend class RPci;
-	TUint iPciBaseAddr;
-	TInt iPciSize; //size of the region mapped into PCI
-	};
-
-typedef TInt (RPci::*ChunkOpenFn)(RPciChunk&, TInt, TRequestStatus*);
-
-class RPci : public RBusLogicalChannel
-	{
-public:
-	TInt Open();
-	TInt GetTestInfo(TPciTestInfo& aTestInfo);
-
-	TInt Open(const TPciDevice&);
-
-	TUint AccessConfigSpace(const TUserConfigSpace& aCs);
-	TUint AccessMemorySpace(const TUserMemorySpace& aMs);
-	TInt  OpenPciDChunk(RPciChunk& aPciChunk,TInt aPciChunkSize, TRequestStatus* aStatus=0);
-	TInt  OpenPciPlatHwChunk(RPciChunk& aPciHwChunk,TInt aPciChunkSize, TRequestStatus* aStatus=0);
-	TInt  OpenPciMappedChunk(RPciChunk& aPciMappedChunk,TInt aPciChunkSize, TRequestStatus* aStatus=0);	
-	TInt  OpenPciWindowChunk(RChunk& aPciWindowChunk);
-	TInt  RunUnitTests();
-private:	
-	TInt DoOpenPciChunk(RPciChunk& aPciChunk, TInt aPciChunkSize, TPciTestCmd aCmd, TRequestStatus* aStatus);
-	};
-
-inline TInt RPci::Open()
-	{
-	return DoCreate(KPciLddFactory, TVersion(), KNullUnit, NULL, NULL);
-	}
-
-inline TInt RPci::Open(const TPciDevice& aDevice) 
-	{
-	TPckgC<TPciDevice> devicePkg(aDevice);
-	return DoCreate(KPciLddFactory, TVersion(), KNullUnit, NULL, &devicePkg);
-	}
-
-inline TInt RPci::GetTestInfo(TPciTestInfo& aTestInfo)
-	{
-	TPckg<TPciTestInfo> info(aTestInfo);
-	return DoControl(EGetTestInfo, &info);
-	}
-
-inline TInt RPci::RunUnitTests()
-	{
-	return DoControl(ERunUnitTests);
-	}
-
-TUint RPci::AccessConfigSpace(const TUserConfigSpace& aCs)
-	{
-	TPckgC<TUserConfigSpace> pkg(aCs);
-	return DoControl(EAccessConfigSpace, &pkg);
-	}
-
-TUint RPci::AccessMemorySpace(const TUserMemorySpace& aMs)
-	{
-	TPckgC<TUserMemorySpace> pkg(aMs);
-	return DoControl(EAccessMemorySpace, &pkg);
-	}
-
-TInt RPci::OpenPciDChunk(RPciChunk& aPciChunk,TInt aPciChunkSize, TRequestStatus* aStatus)	
-	{	
-	return DoOpenPciChunk(aPciChunk, aPciChunkSize, EOpenPciDChunk, aStatus);
-	}
-
-TInt RPci::OpenPciPlatHwChunk(RPciChunk& aPciHwChunk,TInt aPciChunkSize, TRequestStatus* aStatus)	
-	{
-	return DoOpenPciChunk(aPciHwChunk, aPciChunkSize, EOpenPciPlatHwChunk, aStatus);
-	}
-
-TInt RPci::OpenPciMappedChunk(RPciChunk& aPciMappedChunk,TInt aPciChunkSize, TRequestStatus* aStatus)	
-	{
-	return DoOpenPciChunk(aPciMappedChunk, aPciChunkSize, EOpenPciMappedChunk, aStatus);
-	}
-
-TInt RPci::OpenPciWindowChunk(RChunk& aPciWindowChunk)
-	{	
-	TUint chunkHandle = DoControl(EOpenPciWindowChunk);			
-	return aPciWindowChunk.SetReturnedHandle(chunkHandle);
-	}
-
-TInt RPci::DoOpenPciChunk(RPciChunk& aPciChunk, TInt aPciChunkSize, TPciTestCmd aCmd, TRequestStatus* aStatus)
-	{
-	const TInt constPciChunkSize = aPciChunkSize;
-	TPciChunkCreateInfo info(constPciChunkSize, aPciChunk.iPciBaseAddr, aStatus);
-	TPckgC<TPciChunkCreateInfo> pkg(info);
-
-	TUint chunkHandle = DoControl(aCmd, &pkg);	
-	
-	const TInt r = aPciChunk.SetReturnedHandle(chunkHandle);
-	if(r == KErrNone)
-		{		
-		aPciChunk.iPciSize = constPciChunkSize;					
-		}
-	return r;
-	}
-
-TUserPciSpace::TUserPciSpace(RPci& aPci)
-	:iPci(&aPci)
-	{}
-
-TUserConfigSpace::TUserConfigSpace(RPci& aPci)
-	:TUserPciSpace(aPci)
-	{}
-
-TUint TUserConfigSpace::Call()
-	{
-	return iPci->AccessConfigSpace(*this);
-	}
-
-TUserPciSpace* TUserConfigSpace::Clone() const
-	{
-	return new TUserConfigSpace(*this);
-	}
-
-TUserMemorySpace::TUserMemorySpace(RPci& aPci, TInt aBarIndex)
-	:TUserPciSpace(aPci), iBarIndex(aBarIndex)
-	{}
-
-TUint TUserMemorySpace::Call()
-	{
-	return iPci->AccessMemorySpace(*this);
-	}
-
-TUserPciSpace* TUserMemorySpace::Clone() const
-	{
-	return new TUserMemorySpace(*this);
-	}
-
-/**
-Test address allocator
-*/
-TInt TestRunPciUnitTest(RPci& pci)
-	{		
-	return pci.RunUnitTests();
-	}
-
-
-/**
-Read from a defined address in memory or config space, compare against expected values.
-8,16, and 32 bit accesses performed.
-
-@param aSpace Object gving access to either the config or memory space of a PCI device
-@param aInfo Contains the address and expected value of a dword
-*/
-void TestReadAddressSpace(TUserPciSpace& aSpace, const TPciTestInfo::TAddrSpaceTest& aInfo, RTest& test, TBool aVerbose=EFalse)
-	{
-	const TUint os = aInfo.iOffset;
-	//Iterate over different widths, and possible
-	//subfields of 32 bit word
-	for(TInt bitWidth=32; bitWidth>=8; bitWidth>>=1)
-		{
-		const TInt numberOfFields = (32/bitWidth);
-		for(TInt i=0; i< numberOfFields; i++)
-			{
-			const TInt extraByteOffset = i * (bitWidth >> 3);
-			const TInt byteOffset = os + extraByteOffset;
-			if(aVerbose)
-				test.Printf(_L("Access bitWidth=%d byte offset=%d\n"), bitWidth, byteOffset);
-
-			const TUint expected = aInfo.Expected(bitWidth, byteOffset);
-			const TUint read = aSpace.Read(bitWidth, byteOffset);
-			if(aVerbose)
-				test.Printf(_L("expect 0x%08x, read 0x%08x\n"), expected, read);
-			test_Equal(expected, read);
-			}
-		}
-	}
-
-/**
-Verify writes and modifications to a defined address in memory or config space. 8,16, and 32 bit
-accesses performed.
-
-@param aSpace Object gving access to either the config or memory space of a PCI device
-@param aInfo Contains the address of a (at least partially) writable dword
-*/
-void TestWriteAddressSpace(TUserPciSpace& aSpace, TPciTestInfo::TAddrSpaceTest& aInfo, RTest& test, TBool aVerbose=EFalse)
-	{
-	const TUint original = aSpace.Read(32, aInfo.iOffset);
-	const TUint os = aInfo.iOffset;
-	TUint mask = ~aInfo.iReadOnlyMask;
-
-	//The pattern will be truncated when used with bit widths
-	//less than 32.
-	const TUint initPattern = 0xFFFFFFFF;
-
-	for(TInt bitWidth=32; bitWidth>=8; bitWidth>>=1)
-		{
-		const TUint pattern = initPattern >> (32-bitWidth);
-		const TInt numberOfFields = (32/bitWidth);
-		for(TInt i=0; i< numberOfFields; i++)
-			{
-			const TInt extraByteOffset = i * (bitWidth >> 3);
-			const TInt byteOffset = os + extraByteOffset;
-			if(aVerbose)
-				test.Printf(_L("Access bitWidth=%d byte offset=%d\n"), bitWidth, byteOffset);
-			//the full dword we expect
-			//currently assume that the unwritable bits will be 0
-			const TUint writeExpect = (pattern << (bitWidth * i) ) & mask; 
-			const TUint clearExpect = 0;
-						
-			//do write followed by clear
-			const TUint expect[] = {writeExpect, clearExpect};
-			const TUint write[] = {pattern, 0};
-			for(TInt n = 0; n < 2; n++)
-				{
-				aSpace.Write(bitWidth, byteOffset, write[n]);
-				TUint result = aSpace.Read(32, os);
-							
-				if(aVerbose)
-					test.Printf(_L("wrote 0x%08x, expect 0x%08x, read 0x%08x\n"),
-						write[n], expect[n], result);
-				test_Equal(expect[n], result);
-				}
-
-			//test Modify calls. Set then clear pattern
-			TUint set[] = {pattern, 0};
-			TUint clear[] = {0, pattern};
-
-			for(TInt m = 0; m < 2; m++)
-				{	
-				aSpace.Modify(bitWidth, byteOffset, clear[m], set[m]);
-				TUint result = aSpace.Read(32, os);
-						
-				if(aVerbose)
-					test.Printf(_L("clear 0x%08x, set 0x%08x,  expect 0x%08x, read 0x%08x\n"), clear[m], set[m], expect[m], result);
-				test_Equal(expect[m], result);
-				}
-			}
-		}
-
-	//restore orginal value or we will not be able to access device
-	aSpace.Write(32, os, original);
-	}
-
-
-/**
-Verify that a PCI DChunk can be opened and closed from user side
-
-@param pci  The RPci object to use
-@param test The RTest object to use
-@param aPciChunkSize The size of the DChunk which would be created
-*/
-void TestOpenAndCloseDChunk(RPci& pci,RTest& test,TInt aPciChunkSize)
-	{
-	RPciChunk testPciDChunk;
-
-	// Create and open Chunk
-	TRequestStatus status;
-	TInt r = pci.OpenPciDChunk(testPciDChunk,aPciChunkSize, &status);	
-	test_KErrNone(r);
-	
-	test(testPciDChunk.IsWritable());
-	test(testPciDChunk.IsReadable());
-
-	test.Printf(_L("PCI Chunk base = 0x%08x\n"), testPciDChunk.Base());
-	test.Printf(_L("PCI Chunk size = %d\n"), testPciDChunk.Size());
-	test.Printf(_L("PCI Address = 0x%08x\n"), testPciDChunk.PciBase());	
-
-	//Close Chunk
-	test.Next(_L("Close PCI Chunk handle"));	
-
-	RTest::CloseHandleAndWaitForDestruction(testPciDChunk);
-	User::WaitForRequest(status);
-	}
-
-/**
-Verify that a PCI PlatHwChunk can be opened and closed from user side
-
-
-@param pci  The RPci object to use
-@param test The RTest object to use
-@param aPciChunkSize The size of the PlatHwChunk which would be created
-*/
-void TestOpenAndClosePciPlatHwChunk(RPci& pci,RTest& test,TInt aPciChunkSize)
-	{
-	RPciChunk testPciPlatHwChunk;
-
-	// Create and open Chunk
-	TRequestStatus status;
-	TInt r = pci.OpenPciPlatHwChunk(testPciPlatHwChunk,aPciChunkSize, &status);	
-	test_KErrNone(r);
-	
-	test(testPciPlatHwChunk.IsWritable());
-	test(testPciPlatHwChunk.IsReadable());
-
-	test.Printf(_L("PCI Chunk base = 0x%08x\n"), testPciPlatHwChunk.Base());
-	test.Printf(_L("PCI Chunk size = %d\n"), testPciPlatHwChunk.Size());
-	test.Printf(_L("PCI Address = 0x%08x\n"), testPciPlatHwChunk.PciBase());	
-
-	//Close Chunk	
-	testPciPlatHwChunk.Close();
-	User::WaitForRequest(status);
-	test.Next(_L("Closed PCI PlatHwChunk handle"));	
-	}
-
-/**
-Verify that pci-mapped DChunk can be opended and closed form user side 
-
-@param pci  The RPci object to use
-@param test The RTest object to use
-@param aPciChunkSize The size of the pci-mapped DChunk which would be created
-*/
-void TestPciMapppedChunk(RPci& pci,RTest& test,TInt aPciChunkSize)
-	{
-	RPciChunk testPciMappedChunk;
-
-	// Create and open Chunk
-	TRequestStatus status;
-	TInt r = pci.OpenPciMappedChunk(testPciMappedChunk,aPciChunkSize, &status);	
-	test_KErrNone(r);
-	
-	test(testPciMappedChunk.IsWritable());
-	test(testPciMappedChunk.IsReadable());
-
-	test.Printf(_L("PCI Chunk base = 0x%08x\n"), testPciMappedChunk.Base());
-	test.Printf(_L("PCI Chunk size = %d\n"), testPciMappedChunk.Size());
-	test.Printf(_L("PCI Address = 0x%08x\n"), testPciMappedChunk.PciBase());	
-
-	//Close Chunk
-	testPciMappedChunk.Close();
-	User::WaitForRequest(status);
-	test.Next(_L("Closed PCI Mapped Chunk handle"));	
-	}
-
-/**
-Verify that an RChunk can be open to grant access to the internal PCI window from the user side
-
-@param pci  The RPci object to use
-@param test The RTest object to use
-*/
-void TestPciWindowChunk(RPci& pci,RTest& test)
-	{
-	RChunk testPciWindowChunk;
-
-	// Create and open DChunk
-	TInt r = pci.OpenPciWindowChunk(testPciWindowChunk);	
-	test_KErrNone(r);
-	
-	test(testPciWindowChunk.IsWritable());
-	test(testPciWindowChunk.IsReadable());
-
-	test.Printf(_L("PCI Window Chunk base = 0x%08x\n"), testPciWindowChunk.Base());
-	test.Printf(_L("PCI Window Chunk size = %d\n"), testPciWindowChunk.Size());
-	
-	//Close Chunk
-	testPciWindowChunk.Close();
-	test.Next(_L("Closed PCI Window Chunk handle"));	
-	}
-
-
-class CPciTest : public CTest
-	{
-protected:
-	CPciTest(const TDesC& aName, TInt aIterations, RPci& aDevice)
-		: CTest(aName, aIterations), iDevice(aDevice)
-		{}
-
-	RPci iDevice;
-	};
-
-/**
-Each instance of test will open a chunk, using the function specified in
-the template argument, FUNC.
-
-The total number of chunks that can be opened by all instances is limited
-by iMaxCount.
-
-All intances of the test will hold their chunk open until iMaxCount has
-been reached.
-*/
-template<ChunkOpenFn FUNC>
-class CPciOpenChunkTest : public CPciTest
-	{
-public:
-	CPciOpenChunkTest(const TDesC& aName, TInt aIterations, RPci& aDevice,
-			RSemaphore aSemOpen, RSemaphore aSemClose, RFastLock aLock, TInt aMaxCount)
-		:CPciTest(aName, aIterations, aDevice),
-			iSemOpen(aSemOpen), iSemClose(aSemClose), iLock(aLock), iMaxCount(aMaxCount)
-		{
-		}
-
-	virtual void RunTest()
-		{
-		RTest test(iName);
-		RPciChunk chunk;
-
-		iSemOpen.Wait();
-		TRequestStatus status;
-		const TInt chunkSize = 0x400;
-		//open chunk by calling FUNC
-		TInt r = ((iDevice).*(FUNC))(chunk, chunkSize, &status);
-		test_KErrNone(r);
-
-		iLock.Wait();
-		iOpenCount++;
-		test.Printf(_L("Opened chunk %d\n"), iOpenCount);
-		if(iOpenCount == iMaxCount)
-			{
-			test.Printf(_L("Opened=%d, max=%d: Allow chunks to close\n"), iOpenCount, iMaxCount);
-			//release all waiting threads
-			//plus 1 preincrement so this
-			//thread also passes
-			iSemClose.Signal(iOpenCount);			
-			iOpenCount = 0;
-			}	
-		iLock.Signal();
-
-
-		iSemClose.Wait();
-		chunk.Close();
-		User::WaitForRequest(status);
-
-		// permit another chunk to be opened  
-		iSemOpen.Signal();
-		test.Close();
-		}
-
-	virtual CTest* Clone() const
-		{
-		//make shallow copy
-		return new CPciOpenChunkTest(*this);
-		}
-
-
-private:
-	RSemaphore& iSemOpen; ///!< Represents the number of available PCI mappings
-	RSemaphore& iSemClose; ///!< Represents the number of threads waiting to close their chunk
-	RFastLock& iLock;
-	static TInt iOpenCount;
-	const TInt iMaxCount;
-	};
-
-template<ChunkOpenFn FUNC>
-TInt CPciOpenChunkTest<FUNC>::iOpenCount = 0;
-
-
-/**
-Test which will perform various reads from a PCI address
-space (config or memory) and confirm that values are read
-as expected
-*/
-class CPciAddressSpaceRead : public CPciTest
-	{
-public:
-	CPciAddressSpaceRead(const TDesC& aName, TInt aIterations, RPci& aDevice,
-		const TUserPciSpace& aSpace, const TPciTestInfo::TAddrSpaceTest& aInfo)
-		:CPciTest(aName, aIterations, aDevice),
-			iAddressSpace(aSpace.Clone()), iSpaceTestInfo(aInfo)
-	{
-	}
-
-	CPciAddressSpaceRead(const CPciAddressSpaceRead& aOther)
-		:CPciTest(aOther)/* TODO-REVIEW have object-sliced aOther - is this ok?*/,
-			iAddressSpace(aOther.iAddressSpace->Clone()), iSpaceTestInfo(aOther.iSpaceTestInfo)
-	{
-	}
-
-	virtual ~CPciAddressSpaceRead()
-		{
-		delete iAddressSpace;
-		}
-
-	virtual void RunTest()
-		{
-		__UHEAP_MARK;
-		RTest test(iName);
-		TestReadAddressSpace(*iAddressSpace, iSpaceTestInfo, test);
-		test.Close();
-		__UHEAP_MARKEND;
-		}
-
-	virtual CTest* Clone() const
-		{
-		//make shallow copy
-		return new CPciAddressSpaceRead(*this);
-		}
-
-private:
-	TUserPciSpace* iAddressSpace;
-	const TPciTestInfo::TAddrSpaceTest& iSpaceTestInfo;
-	};
-
-/**
-For aBuffer, test writing to it then reading back from aWindow
-then write via window and read back from chunk
-
-@param test The RTest object to use
-@param aBuffer RChunk corresponding to a PCI accessible buffer
-@param aWindow RChunk coressponding an appropriate System-to-PCI memory window
-It is presumed to start at PCI address 0
-*/
-void DoLoopBackTest(RTest& test, RPciChunk aBuffer, RChunk aWindow)
-	{
-	test.Start(_L("Test accessing memory via PCI"));
-
-	TUint8* const bufferBase = aBuffer.Base();
-	const TUint bufferSize = aBuffer.Size();
-	const TUint bufferPciBase = aBuffer.PciBase();
-
-	TUint8* const windowBase = aWindow.Base();
-	const TUint windowSize = aWindow.Size();
-
-#define PRINT(N) RDebug::Printf("%s = 0x%08x (%d)", #N, (N), (N)) 
-	PRINT(bufferBase);
-	PRINT(bufferSize);
-	PRINT(bufferPciBase);
-
-	PRINT(windowBase);
-	PRINT(windowSize);
-
-#undef PRINT
-
-	//need to check that the end of the buffer
-	//is within the windowed region
-	test(bufferPciBase + bufferSize <= windowSize);
-	TUint8* const bufferBaseWithinWindow = windowBase + bufferPciBase;
-
-	test.Next(_L("write chunk"));
-	for(TUint i = 0; i < bufferSize; ++i)
-		{
-		//each byte will hold its own offset modulo 256
-		bufferBase[i] = (TUint8)i;
-		}
-
-	test.Next(_L("read back via window"));
-	for(TUint j=0; j < bufferSize; ++j)
-		{
-		const TUint8 result = bufferBaseWithinWindow[j];
-		test_Equal(j%256, result);
-		}
-
-	//clear chunk
-	memclr(bufferBase, bufferSize);
-	test.Next(_L("write via window"));
-	for(TUint k=0; k < bufferSize; ++k)
-		{
-		//each byte will hold its own offset modulo 256
-		bufferBaseWithinWindow[k] = (TUint8)k;
-		}
-
-	test.Next(_L("read back from chunk"));
-	for(TUint l=0; l < bufferSize; ++l)
-		{
-		const TUint8 result = bufferBase[l];
-		test_Equal(l%256, result);
-		}
-
-	test.End();
-	}
-
-/**
-Take care of opening a chunk, running the test and closing
-*/
-template<ChunkOpenFn OPEN_FUNC>
-inline void LoopBackTest(RPci& aPci, RTest& test, RChunk& aWindow)
-	{
-	RPciChunk pciChunk;
-	const TInt chunkSize = 0x400; //1k
-
-	//call the specified chunk opening function
-	TRequestStatus status;
-	TInt r = ((aPci).*(OPEN_FUNC))(pciChunk, chunkSize, &status);	
-	test_KErrNone(r);
-	DoLoopBackTest(test, pciChunk, aWindow);
-	pciChunk.Close();
-	User::WaitForRequest(status);
-	}
-
-/**
-Run the loopback test for the 3 types of buffer supported by the PCI driver.
-DChunk
-DPlatChunk
-Mapped In external memory
-*/
-void TestLoopBack(RPci& aPci, RTest& test)
-	{
-	test.Next(_L("Open PCI window"));
-	RChunk window;
-	
-	TInt r = aPci.OpenPciWindowChunk(window);	
-	test_KErrNone(r);
-
-	test.Next(_L("DChunk"));
-	LoopBackTest<&RPci::OpenPciDChunk>(aPci, test, window);
-
-	test.Next(_L("DPlatHwChunk"));
-	LoopBackTest<&RPci::OpenPciPlatHwChunk>(aPci, test, window);
-
-	test.Next(_L("DChunk (mapped in)"));
-	LoopBackTest<&RPci::OpenPciMappedChunk>(aPci, test, window);
-
-	window.Close();
-	}
-#ifndef __VC32__ //visual studio 6 doesn't approve of pointer to member function template parameters
-/**
-Run the CPciOpenChunkTest for each type of chunk. This function also creates (and destroys) the
-necessary semaphores and locks.
-CPciOpenChunkTest objects are run in multiple threads using MultipleTestRun().
-
-@param aDevice Handle to the test driver
-@param test RTest to use.
-@param aBufferLimit The maximum number of buffers which can be opened simultaneously
-*/
-void TestBufferOpenConcurrency(RPci& aDevice, RTest& test, TInt aBufferLimit)
-	{
-	RSemaphore semaphoreOpen;
-	RSemaphore semaphoreClose;
-	RFastLock lock;
-
-	TInt r = semaphoreOpen.CreateLocal(aBufferLimit);
-	test_KErrNone(r);
-
-	r = semaphoreClose.CreateLocal(0);
-	test_KErrNone(r);
-
-	r = lock.CreateLocal();
-	test_KErrNone(r);
-
-	const TInt iterations = 3;
-	{
-	test.Printf(_L("Opening %d PCI DChunks in %d threads\n"), aBufferLimit, aBufferLimit);
-	CPciOpenChunkTest<&RPci::OpenPciDChunk>
-		dChunkTest(_L("Concurrent-DChunk"), iterations, aDevice, semaphoreOpen, semaphoreClose, lock, aBufferLimit);
-
-	MultipleTestRun(test, dChunkTest, aBufferLimit);
-	}
-
-	{
-	test.Printf(_L("Opening %d PCI DPlatHwChunks in %d threads\n"), aBufferLimit, aBufferLimit);
-	CPciOpenChunkTest<&RPci::OpenPciPlatHwChunk>
-		platChunkTest(_L("Concurrent-DPlatHwChunk"), iterations, aDevice, semaphoreOpen, semaphoreClose, lock, aBufferLimit);
-
-	MultipleTestRun(test, platChunkTest, aBufferLimit);
-	}
-
-	{
-	test.Printf(_L("Opening %d PCI Mapped chunks in %d threads\n"), aBufferLimit, aBufferLimit);
-	CPciOpenChunkTest<&RPci::OpenPciMappedChunk>
-		mappedChunkTest(_L("Concurrent-DChunk(mapped)"), iterations, aDevice, semaphoreOpen, semaphoreClose, lock, aBufferLimit);
-
-	MultipleTestRun(test, mappedChunkTest, aBufferLimit);
-	}
-
-	semaphoreOpen.Close();
-	semaphoreClose.Close();
-	lock.Close();
-	}
-#endif
-
-TInt E32Main()
-	{
-	__UHEAP_MARK;
-
-	_LIT(KPci, "PCI");
-	RTest test(KPci);
-	test.Start(_L("Running PCI tests\n"));
-
-	TInt r = User::LoadLogicalDevice(KPciLdd);
-
-	__KHEAP_MARK;
-	
-	if(r==KErrNotFound)
-		{
-		test.Printf(_L("No PCI system present - skipping test\n"));
-		return KErrNone;
-		}
-	if(r!=KErrNone && r!=KErrAlreadyExists)
-		{
-		test_KErrNone(r);
-		}
-	
-	test.Next(_L("Open non-existant device\n"));
-	RPci device;
-	TPciDevice unavailable;
-	r = device.Open(unavailable);
-	test_Equal(KErrNotFound, r);
-
-	RPci pciInfo;
-	r = pciInfo.Open();
-	test_KErrNone(r);
-
-	test.Next(_L("Get test info from driver\n"));
-	TPciTestInfo info;
-	r = pciInfo.GetTestInfo(info);
-	test_KErrNone(r);
-	pciInfo.Close();
-
-	test.Next(_L("Open test device\n"));
-	r = device.Open(info.iDevice);
-	test_KErrNone(r);
-
-	test.Next(_L("Run Device Unit Test\n"));
-	r=TestRunPciUnitTest(device);	
-	test_KErrNone(r);
-
-	test.Next(_L("Read config space\n"));
-	TUserConfigSpace cs(device);
-	TestReadAddressSpace(cs, info.iCfgSpaceRead, test);
-
-	test.Next(_L("Write config space\n"));
-	TestWriteAddressSpace(cs, info.iCfgSpaceWrite, test);
-	
-	test.Next(_L("Read memory space\n"));
-	TUserMemorySpace ms(device, info.iMemSpaceIndex);
-	TestReadAddressSpace(ms, info.iMemSpaceRead, test);
-
-	test.Next(_L("Modify memory space\n"));
-	TestWriteAddressSpace(ms, info.iMemSpaceWrite, test);
-
-	{
-	const TInt addrSpaceThreadCount = 4;
-	const TInt iterations = 100;
-	test.Next(_L("Concurrent config space reads")); 
-	CPciAddressSpaceRead cfgSpaceRead(_L("Cfg Space Read"), iterations, device, cs, info.iCfgSpaceRead);
-	MultipleTestRun(test, cfgSpaceRead, addrSpaceThreadCount);
-
-	test.Next(_L("Concurrent memory space reads")); 
-	CPciAddressSpaceRead memSpaceRead(_L("Memory Space Read"), iterations, device, ms, info.iMemSpaceRead);
-	MultipleTestRun(test, memSpaceRead, addrSpaceThreadCount);
-	}
-
-	TInt testDChunkSize = 0x4000;
-	test.Next(_L("Open and Close DChunks\n"));	
-	TestOpenAndCloseDChunk(device,test,testDChunkSize);
-	
-	TInt testDPlatChunkSize = 0x2000;
-	test.Next(_L("Open and Close PlatHwChunks\n"));	
-	TestOpenAndClosePciPlatHwChunk(device,test,testDPlatChunkSize);
-
-	//TestPciMapppedChunk() fails for sizes greater than 4K.
-	//The issue is that a block of externally mapped memory must be
-	//naturally alligned in order to be accessible to the PCI bus (ie
-	//an 8k buffer would have to start at an address which is a
-	//multiple of 8k.
-	//
-	//Now we could fix this for sure on the kernel side, by making
-	//sure we only commit correctly aligned memory into the chunk (as
-	//the pci driver itself does),
-	//However, by using a 4k chunk, we know this will be on a page
-	//boundary so the alignment is correct (assuming the page size
-	//isn't changed). 	
-	TInt testMapppedChunkSize = 0x1000; 
-	test.Next(_L("Open and Close Pci Mappped Chunk\n"));	
-	TestPciMapppedChunk(device,test,testMapppedChunkSize);
-
-	test.Next(_L("Open and Close Pci Window Chunk\n"));	
-	TestPciWindowChunk(device,test);
-
-	const TInt numberOfThreads = info.iNumberOfBars;
-	test.Printf(_L("Open buffers concurrently, max supported = %d\n"), numberOfThreads);
-#ifndef __VC32__
-	TestBufferOpenConcurrency(device, test, numberOfThreads);
-#else
-	test.Printf(_L("TestBufferOpenConcurrency not implemented for WINS"), numberOfThreads);
-#endif
-
-	test.Next(_L("Test loop back"));	
-	TestLoopBack(device, test);
-
-	device.Close();
-	__KHEAP_MARKEND;
-
-	r = User::FreeLogicalDevice(KPciLdd);
-	test_KErrNone(r);
-
-	test.End();
-	test.Close();
-
-	__UHEAP_MARKEND;
-	return KErrNone;
-	}	
--- a/kerneltest/e32test/pci/t_pci.h	Tue Sep 14 23:56:21 2010 +0300
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,254 +0,0 @@
-// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of the License "Eclipse Public License v1.0"
-// which accompanies this distribution, and is available
-// at the URL "http://www.eclipse.org/legal/epl-v10.html".
-//
-// Initial Contributors:
-// Nokia Corporation - initial contribution.
-//
-// Contributors:
-//
-// Description: This is the header file for the PCI driver test , so far implemented 
-//				only on the  Naviengine platform
-
-#ifndef __TPCI_TEST_H
-#define __TPCI_TEST_H
-
-#ifndef __KERNEL_MODE__
-#define __E32TEST_EXTENSION__
-#include <e32test.h>
- #include <e32def_private.h>
-#endif // __KERNEL_MODE__
-
-_LIT(KPciLdd, "d_pci.ldd");
-_LIT(KPciLddFactory, "PCI_test_factory");
-_LIT(KPciTest, "PCI Test LDD");
-
-/**
-Test driver op-codes
-*/
-enum TPciTestCmd
-	{
-	EGetTestInfo,
-	EAccessConfigSpace,
-	EAccessMemorySpace,
-	EOpenPciDChunk,
-	EOpenPciPlatHwChunk,
-	EOpenPciMappedChunk,
-	EOpenPciWindowChunk,
-	ERunUnitTests
-	};
-
-/**
-Identifies a PCI Function (device) on the system
-*/
-struct TPciDevice
-	{
-	TPciDevice()
-		:iVendorId(0xFFFFFFFF), iDeviceId(0xFFFFFFFF), iInstance(0) {}
-
-	TPciDevice(TUint aVendorId, TUint aDeviceId, TInt aInstance=0)
-		:iVendorId(aVendorId), iDeviceId(aDeviceId), iInstance(aInstance) {}
-
-	TUint iVendorId;
-	TUint iDeviceId;
-	TInt iInstance; ///< Unit to open (there could be multiple devices on system)
-	};
-
-/**
-Used to send chunk size and recieve
-PCI address
-*/
-struct TPciChunkCreateInfo
-	{
-	TPciChunkCreateInfo()
-		:iSize(0), iPciAddress(NULL)
-		{
-		}
-
-	TPciChunkCreateInfo(TInt aSize, TUint& aPciAddress, TRequestStatus* aStatus=NULL)
-		:iSize(aSize), iPciAddress(&aPciAddress), iStatus(aStatus)
-		{
-		}
-	TInt iSize;
-	TUint* iPciAddress;
-	TRequestStatus* iStatus;
-	};	
-
-/**
-Information about the PSL required by the
-user side test
-*/
-struct TPciTestInfo
-	{
-	TPciDevice iDevice; ///< Probe for this
-
-	/**
-	Supplies the necessary information to test Read, Write, and
-	Modify for a word of PCI memory or configuration space
-	*/
-	struct TAddrSpaceTest
-		{
-		TAddrSpaceTest()
-			:iOffset(0), iExpectedValue(0), iReadOnlyMask(0)
-			{}
-
-		TAddrSpaceTest(TUint aOffset, TUint aExpectedValue, TUint aReadOnlyMask)
-			:iOffset(aOffset), iExpectedValue(aExpectedValue), iReadOnlyMask(aReadOnlyMask)
-			{}
-
-		/**
-		Returns a specified sub byte, or word from the whole dword
-		*/
-		inline TUint Expected(TInt aBitWidth, TInt aExtraOffset) const
-			{
-			//the right shift required to get field to bit 0
-			const TInt shift = 8 *((aExtraOffset + iOffset) % 4);
-			
-			const TUint mask = 0xFFFFFFFF >> (32-aBitWidth);
-			return (iExpectedValue >> shift) & mask;
-			}
-
-		const TUint iOffset;
-		const TUint iExpectedValue; ///< The initial value of word
-		const TUint iReadOnlyMask; ///< Mask of unwritable bits
-		//Future work, memory spaces should state a bar index
-		};
-
-
-	TAddrSpaceTest iCfgSpaceRead;
-	TAddrSpaceTest iCfgSpaceWrite;
-
-	TUint iMemSpaceIndex; ///< Memory space to select
-	TAddrSpaceTest iMemSpaceRead;
-	TAddrSpaceTest iMemSpaceWrite;
-
-	TInt iNumberOfBars; ///< Number of simultaneous mappings into PCI space
-	};
-
-class RPci;
-class TAddrSpace;
-/**
-This class encapsulates all the various read/write/and modify commands
-that can be carried out on a PCI memory space. The command is stored user
-side, and then executed on kernel side when KRun() is called.
-*/
-class TUserPciSpace
-	{
-public:
-	TUserPciSpace()
-		:iPci(NULL), iOperation(EInvalid), iBitWidth(0), iOffset(0),
-		iWriteValue(0), iClearMask(0), iSetMask(0)
-	{}
-	TUserPciSpace(RPci& aPci);
-	
-	/**
-	Perform the encapsulated read/write/or modify
-	@note Only run on kernel side
-	*/
-	TUint KRun(TAddrSpace& aAddrSpace);
-	
-	/**
-	Clone method is required so that multiple threads may
-	have their own copy of a TUserPciSpace (without knowing
-	its runtime type)
-	*/
-	virtual TUserPciSpace* Clone() const = 0;
-
-	TUint Read(TInt aBitWidth, TUint aOffset)
-		{
-		iOffset = aOffset;
-		iOperation = ERead;
-		iBitWidth = aBitWidth;
-
-		return Call();
-		}
-
-	void Write(TInt aBitWidth, TUint aOffset, TUint aValue)
-		{
-		iOffset = aOffset;
-		iOperation = EWrite;
-		iBitWidth = aBitWidth;
-		
-		iWriteValue = aValue;
-		Call();
-		}
-
-	void Modify(TInt aBitWidth, TUint aOffset, TUint aClearMask, TUint aSetMask)
-		{
-		iOffset = aOffset;
-		iOperation = EModify;
-		iBitWidth = aBitWidth;
-
-		iClearMask = aClearMask;
-		iSetMask = aSetMask;
-		Call();
-		}
-
-protected:
-	/**
-	Makes a request to iPci and passes a copy of this object to
-	the kernel side.
-	*/
-	virtual TUint Call() =0;
-
-	enum TOperation {EInvalid, ERead, EWrite, EModify};
-
-	/**
-	Pointer to a PCI device handle
-	*/
-	RPci* iPci;
-
-	TOperation iOperation; //!< Type of access to perform
-	TInt iBitWidth;
-	
-	TUint iOffset;
-	TUint32 iWriteValue;
-	TUint32 iClearMask;
-	TUint32 iSetMask;
-	};
-
-/**
-Grants access to a PCI device's (identified
-by aPci) config space from user side
-*/
-class TUserConfigSpace : public TUserPciSpace
-	{
-public:
-	TUserConfigSpace()
-		:TUserPciSpace()
-		{}
-	TUserConfigSpace(RPci& aPci);
-
-	virtual TUserPciSpace* Clone() const;
-private:
-	TUint Call();
-	};
-
-/**
-Grants access to some region of a PCI
-device's memory space. A PCI device(or function)
-may have up to 8 distinct memory spaces
-*/
-class TUserMemorySpace : public TUserPciSpace
-	{
-public:
-	TUserMemorySpace()
-		:TUserPciSpace(), iBarIndex(-1)
-		{}
-
-	TUserMemorySpace(RPci& aPci, TInt aBarIndex);	
-
-	virtual TUserPciSpace* Clone() const;
-	
-	inline TInt BarIndex() {return iBarIndex;}
-
-private:
-	TUint Call();
-
-	TInt iBarIndex; ///< Each PCI function may have up to 8 memory spaces
-	};
-
-#endif //__TPCI_TEST_H
--- a/kerneltest/e32utils/group/base_e32utils.mrp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/e32utils/group/base_e32utils.mrp	Wed Sep 15 13:42:27 2010 +0300
@@ -11,6 +11,7 @@
 source	\sf\os\kernelhwsrv\kerneltest\e32utils\demandpaging
 source	\sf\os\kernelhwsrv\kerneltest\e32utils\group
 source	\sf\os\kernelhwsrv\kerneltest\e32utils\netcards
+source	\sf\os\kernelhwsrv\kerneltest\e32utils\nistsecurerng
 source	\sf\os\kernelhwsrv\kerneltest\e32utils\profiler
 source	\sf\os\kernelhwsrv\kerneltest\e32utils\setcap
 source	\sf\os\kernelhwsrv\kerneltest\e32utils\testusbcldd
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/hcrdat.pm	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,378 @@
+#!perl -w
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+#
+use strict;
+
+#use Math::BigInt;
+
+#
+# Perl module to create and maintain feature manager data files.
+# You can either set up the information programmatically or else load up
+# information from a pre-existing feature data file and then modify it. You
+# can also save the information to a file (in feature manager dataset format).
+#
+# This class maintains header information plus two arrays, one containing
+# feature flag information and the other containing default supported range
+# information. Those are themselves objects and have their own accessor
+# methods.
+#
+
+package HCRdat;
+
+use HCRrec;
+
+
+#
+# n e w
+#
+# Create a new HCRdat object. For example 'my $hd = HCRdat->new("filea");
+#
+sub new
+{
+	my $arg = shift;
+	my $fn = shift;
+	my $class = ref($arg) || $arg;
+	my $self = {
+			        fingerprint => "HCRf",  # 4 bytes wide.
+					fileversion => 1,       # 2 bytes.
+					fileflags => 0x0001,  # 2 bytes.
+					numrecords => 0,      # 4 bytes. 
+					lsdoffset => 0,       # 4 bytes. 
+					lsdsize => 0,         # 4 bytes.
+				    packprefix => "V",    # Changed with endian-ness.
+					                      # Used to create binary strings.
+
+					settingrecords => [],  # Array of objects
+					lsd => [],             # Array of bytes
+	           };
+    bless $self, $class;
+	return $self;
+}
+
+
+# Print to STDOUT the header information we have.
+sub ShowHeader
+{
+	my $self = shift;
+	return undef unless(ref($self));
+
+	# Get header information..
+	my $typefield = $self->TypeField();
+	my $fileversion = $self->FileVersion();
+	my $fileflags = $self->FileFlags();
+	my $numrecords = $self->NumRecords();
+	my $lsdoffset = $self->LsdOffset();
+	my $lsdsize = $self->LsdSize();
+	
+	# Display it in English.
+	print "  FINGERPRINTF: '$typefield'\n";
+	print "  FILEVERSION: '$fileversion'\n";
+	print "  FILEFLAGS: '$fileflags'\n";
+	print "  NUMRECORDS: '$numrecords'\n";
+	print "  LSDOFFSET: '$lsdoffset'\n";
+    print "  LSDSIZE: '$lsdsize'\n";
+
+	return(0);
+}
+
+# Get/Set the endian-ness we want. Changes the 'packprefix' member which is
+# used in the creation of binary data.
+sub Endian
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	return $self->{endian} unless(defined($arg));
+	if($arg =~ m/(LE|BE)/i)
+	{
+		my $endian = uc($1);
+		$self->{endian} = $endian;
+		# Used by 'pack' to generate binary strings.
+		$self->{packprefix} = "V" if($endian eq "LE");
+		$self->{packprefix} = "N" if($endian eq "BE");
+	}
+	return $self->{endian};
+}
+
+# This is the fingerprint.
+sub TypeField
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	$self->{fingerprint} = $arg if(defined($arg));
+	return $self->{fingerprint};
+}
+
+sub FileVersion
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	# Should we be testing for a numeric value?
+	$self->{fileversion} = $arg if(defined($arg));
+	return $self->{fileversion};
+}
+
+sub FileFlags
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	$self->{fileflags} = $arg if(defined($arg));
+	return $self->{fileflags};
+}
+
+# How many feature flag objects have we got?
+sub NumRecords
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	$self->{numrecords} += $arg if(defined($arg));
+	return $self->{numrecords};
+}
+
+
+sub LsdOffset
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	$self->{lsdoffset} = $arg if(defined($arg));
+	return $self->{lsdoffset};
+}
+
+sub LsdSize
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	$self->{lsdsize} = $arg if(defined($arg));
+	return $self->{lsdsize};
+}
+
+# Create a binary string containing the header information for the
+# feature manager data file based on the various fields in this object.
+sub CreateBinaryHeader
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $hdrstring;
+
+	# Get the letter for packing information with 'pack' into a binary form.
+	my $pack16 = lc($self->{packprefix});
+	my $pack32 = uc($self->{packprefix});
+	
+	# Get header information..
+	my $typefield = $self->TypeField();
+	my $fileversion = $self->FileVersion();
+	my $fileflags = $self->FileFlags();
+	my $numrecords = $self->NumRecords();
+	my $lsdoffset = $self->LsdOffset();
+	my $lsdsize = $self->LsdSize();
+
+	# Write the 'type' field out. This is 'feat'. Would this be different on
+	# big-endian systems?
+	$hdrstring = $typefield;
+
+	# Now the file version number. A 16-bit value.. Will this cause trouble
+	# if the shifted value is signed?
+	$hdrstring .= pack($pack16 . "1", $fileversion);
+
+	# Now the file flags. Another 16-bit value..
+	$hdrstring .= pack($pack16 . "1", $fileflags);
+
+	# Now the number of listed features - a 32-bit value.
+	$hdrstring .= pack($pack32 . "1", $numrecords);
+
+	# Now the number of listed features - a 32-bit value.
+	$hdrstring .= pack($pack32 . "1", $lsdoffset);
+
+	# Now the number of listed features - a 32-bit value.
+	$hdrstring .= pack($pack32 . "1", $lsdsize);
+
+	# Now the 3 reserved words
+	$hdrstring .= pack($pack32 . "3", (0, 0, 0));
+
+	return $hdrstring;
+}
+
+sub CreateImageHdr
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	#my $partid = shift;
+	#return -1 unless(defined($partid));
+
+	# Add fingerprint, 1st reserved word and format version
+	my $imghdr = pack "V4", (0x5F524348, 0x54524150, 0x00000000, 0x00000001);
+	# Add space for image size, timestamp, 2nd reserved word
+	$imghdr .= pack "V3", (0x00000000, time, 0x00000000);
+	# Add space for payload checksum, HCR Payload constants: UID and 0x0 flags
+    $imghdr .= pack "V3", (0x00000000, 0x10286AB8, 0x00000000);
+    #Reserved space
+    $imghdr .= pack "x216", (0x00000000);
+ 
+    return $imghdr;
+}
+
+sub WriteToImage
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $imgfile = shift;
+	return -1 unless(defined($imgfile));
+	my $datfile = shift;
+	return -1 unless(defined($datfile));
+	#my $partid = shift;
+	#return -1 unless(defined($partid));
+	my $rc = 0;
+	
+    open IMGFILE, "> $imgfile" or die "Couldn't open file '$imgfile' for writing.\n";
+	binmode IMGFILE;
+   
+ 	syswrite(IMGFILE, $self->CreateImageHdr(), 256);	
+ 	
+    open DATFILE, "$datfile" or die "Couldn't open file '$datfile' for reading.\n";
+	binmode DATFILE;
+	# print FILE $self->BinaryContent();
+	
+    #my $wordsum = 0x1200000000;
+    #my $wordsum = Math::BigInt->new("0x0220100123");
+    #printf("test: %x\n", $wordsum->external();
+
+	my $imgsize = 256;
+	my $word;
+	printf("-reading image:\n")  if ($mhd::otrace);
+	while (sysread (DATFILE, $word, 4)) {
+	    #printf ("%08x ",$word)  if ($mhd::otrace);
+        my $iword = unpack("V" , $word);
+	    printf ("%08x ",$iword)  if ($mhd::otrace);
+        $rc = syswrite (IMGFILE, $word, 4);
+        die "error: ($rc) failed to write datfile word into imgfile.\n" if ($rc != 4);
+	    #$wordsum->badd($iword);
+        $imgsize += 4;
+	    print "\n" if (($mhd::otrace) && ($imgsize%16==0));
+        }
+    print "\n" if ($mhd::otrace);
+    # ordsum: 0x". $wordsum ."\n" if ($mhd::otrace);
+	my $checksum = 0x12345678;
+	close DATFILE;
+	
+	printf("-image size: %d, checksum: 0x%08x", $imgsize, $checksum) if ($mhd::otrace);
+	
+	$rc = sysseek(IMGFILE, 16, 0);
+	die "error: ($rc) failed to seek in image to write header.\n" if ($rc != 16);
+
+	# Write out the image size	
+	my $imginfo1 = pack "V1", ($imgsize);
+	$rc = syswrite(IMGFILE, $imginfo1, 4);
+	die "error: ($rc) failed to write image size/checksum to image header.\n" if ($rc != 4);
+
+	$rc = sysseek(IMGFILE, 28, 0);
+	die "error: ($rc) failed to seek in image to write header.\n" if ($rc != 28);
+	
+	# Write out the image checksum 
+	my $imginfo2 = pack "V1", ($checksum);
+	$rc = syswrite(IMGFILE, $imginfo2, 4);
+	die "error: ($rc) failed to write image size/checksum to image header.\n" if ($rc != 4);
+  
+	close IMGFILE; 	
+	
+    return 0;
+}
+
+# Writes the binary file specified as an argument with the content of this
+# and contained feature flag and dsr objects.
+sub WriteToFile
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $file = shift;
+	return undef unless(defined($file));
+    open FILE, "> $file" or die "Couldn't open file '$file' for writing.\n";
+	binmode FILE;
+	print FILE $self->BinaryContent();
+	
+	close FILE;
+	return 0;
+}
+
+
+# Create the binary equivalent of the internal data and return it as a
+# string.
+sub BinaryContent
+{
+	my $self = shift;
+	return undef unless(ref($self));
+
+    # Get the feature flag entries.. This is an array reference.
+	# For each one append the binary representation of the information
+	# contained.
+	my $records = "";
+    my $lsd = "";
+   	my $ffs_ref = $self->SettingRecords();
+	my $ff;
+
+    my $count = 0;
+	foreach $ff (@$ffs_ref)
+	{
+	    $count++;
+	    printf("-encoding record: %04d (0x%08x:%04d)\n", $count, $ff->CUID(), $ff->EID());
+		$records .= $ff->GetRecHdrBinary(length ($lsd));
+	    my $stype = $ff->Type();
+    	if (($stype & 0xffff0000) && ($ff->Length() > 0)) {
+		    $lsd .= $ff->GetRecLsdBinary();
+            }
+	}
+
+    $self->LsdOffset(32+length ($records));     # header size 32
+    $self->LsdSize(length ($lsd));
+    
+	my $header = $self->CreateBinaryHeader();
+
+	return $header . $records . $lsd;
+}
+
+# Return a reference to the 'feature flags' array.
+sub SettingRecords
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	return $self->{settingrecords};
+}
+
+# Add a Feature Flag object. Perhaps there should be code to check if we
+# already know about this feature flag. (i.e check the uid against the ones
+# we have).
+sub AddSettingRecord
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	die "panic: method 'AddSettingRecord' requires a 'HCRrec' object as argument.\n"
+   	    unless(ref($arg) eq  "HCRrec");
+   	
+	push @{$self->SettingRecords()}, $arg;
+	$self->NumRecords(1);
+	
+    return 0;
+}
+
+
+1;
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/hcrmd.bat	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,19 @@
+@rem
+@rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+@rem All rights reserved.
+@rem This component and the accompanying materials are made available
+@rem under the terms of the License "Eclipse Public License v1.0"
+@rem which accompanies this distribution, and is available
+@rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+@rem
+@rem Initial Contributors:
+@rem Nokia Corporation - initial contribution.
+@rem
+@rem Contributors:
+@rem
+@rem Description:
+@rem
+
+@echo off
+
+@perl -S -I%EPOCROOT%epoc32/tools/hcr %EPOCROOT%epoc32/tools/hcr/makehcrdat.pl %*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/hcrrec.pm	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,437 @@
+#!perl -w
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+#
+use strict;
+
+#
+# A simple class to manage feature flags for a feature set data file.
+#
+package HCRrec;
+
+my %typemap = (
+    Int32 =>       0x00000001,
+    Int16 =>       0x00000002,    
+    Int8 =>        0x00000004,
+    Bool =>        0x00000008,    
+    UInt32 =>      0x00000010,
+    UInt16 =>      0x00000020,    
+    UInt8 =>       0x00000040,
+    LinAddr =>     0x00000100,
+    BinData =>     0x00010000,
+    Text8 =>       0x00020000,    
+	ArrayInt32 =>  0x00040000,
+	ArrayUInt32 => 0x00080000,
+    Int64 =>       0x01000000,
+    UInt64 =>      0x02000000,    
+);
+my %maptype = reverse %typemap;
+my %lsdtype2packmap = (
+    0x00010000 => "C",
+    0x00020000 => "a",    
+    0x01000000 => "C",
+    0x02000000 => "C",    
+);
+
+# Create a feature flag object.
+sub new
+{
+	my $arg = shift;
+	my $class = ref($arg) || $arg;
+
+	my $self = {
+			     cuid => 0,              # 4 bytes
+			     eid => 0,               # 4 bytes
+			     type => 0,              # 4 bytes
+			     flagword => 0x0000,     # 2 bytes 
+                 valueset => 0,
+                           
+			     intvalue => 0,           # 4 bytes
+			     strvalue => "",          # array of chars
+			     binvalue => [],          # array of bytes
+			     arrvalue => [],		  # array of 4 byte integers
+			     
+   				 endian => "LE",
+			   };
+ 
+	bless $self, $class;
+	return $self;
+}
+
+sub Endian
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $arg = shift;
+	return $self->{endian} unless(defined($arg) and $arg =~ m/(^BE$|^LE$)/i);
+	$self->{endian} = lc($1);
+	return $self->{endian};
+}
+
+# Return a twelve byte string 'feature flag' information.
+sub GetRecHdrBinary
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	
+	my $lsd_size = shift;
+	
+	my $stype = $self->Type(); 
+	my @hdrarr = ( $self->CUID(), $self->EID(), $stype, $self->Flags(),
+                $self->SizeInBytes() );
+    
+	# Decide whether we want big or little endian output.
+	# According to the documentation, 'V', 'N' are GUARANTEED to be 32-bit.
+	my $packstring;
+	if($self->Endian() eq "BE") {
+	    $packstring = "N3n2N";
+        }
+    else {
+        $packstring = "V3v2V"; # Little endian.
+        }
+        
+    #
+    # Could add range checks here for 8-bit and 16-bit types.
+    # However would stop negative test cases from being generated.
+    # Do it later.
+    #
+    
+    if ($stype & 0xffff) {
+        print "Writing integer\n" if ($mhd::otrace);
+        push @hdrarr, $self->IntValue();
+        }
+    
+    if ($stype & 0xffff0000) {
+        if ($self->Length() > 0) {
+            print "Writing offset: " . $lsd_size . "\n" if ($mhd::otrace);
+            push @hdrarr, $lsd_size;
+            }
+        else {
+            print "Writing null offset: 0\n" if ($mhd::otrace);
+            push @hdrarr, 0;            
+            }
+        }
+
+	my $hdr_string = pack $packstring, @hdrarr;
+	
+	return $hdr_string;
+}
+
+# Return a twelve byte string 'feature flag' information.
+# Assumes Little Endian output!
+sub GetRecLsdBinary
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	
+    my $value = "";
+    my $valuelen = $self->Length();
+    my $vallen = $valuelen;
+    #print "vallen before:" . $vallen . "\n";
+    $vallen = ($valuelen+3)&0xfffc if ($valuelen%4) ;
+    #print "vallen after:" . $vallen . "\n";
+	my $valtype = $self->{type};
+
+    # String
+    if ($valtype & 0x00020000) {
+	    my $packstr = $lsdtype2packmap{$valtype} . $vallen;
+	    printf ("packstr:%s\n", $packstr) if($mhd::otrace);
+        printf ("strvalue:%s\n", $self->{strvalue}) if($mhd::otrace);
+        $value = pack $packstr,  $self->{strvalue} ;
+        }
+    # Binary Data
+    elsif ($valtype & 0x00010000) {
+        for (my $c=0;  $c < $valuelen; $c++) {
+            my $byte = $self->{binvalue}[$c];
+            $value .= pack $lsdtype2packmap{$valtype}, $byte;
+            $vallen--;     
+        }
+        while ($vallen > 0) {
+            $value .= pack "C", ( 0x00 );
+            $vallen--;
+            }
+    }
+    # 64bit quantity
+    elsif ($valtype & 0x03000000) {
+        die "error: 64 bit integer missing hex binvalues\n" if (! exists $self->{binvalue}[7]);
+        $value  = pack $lsdtype2packmap{$valtype}, $self->{binvalue}[0];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[1];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[2];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[3];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[4];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[5];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[6];
+        $value  .= pack $lsdtype2packmap{$valtype}, $self->{binvalue}[7];
+        }
+    # array of 32bit quantity
+    elsif ($valtype & 0x000C0000) {
+        for (my $c=0;  $c < $valuelen; $c++) {
+            my $int = $self->{arrvalue}[$c];
+            $value .= pack "V", $int;
+            $vallen--;     
+            }
+	}    
+    else {
+        die "panic: proramming error!!";
+    }
+    
+	return $value;
+	}
+
+# A single 32-bit number.
+sub CUID
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $uid = shift;
+	return $self->{cuid} unless(defined($uid));
+	my $uidv = hex($uid);
+	$self->{cuid} = $uidv;
+	return $uidv;
+}
+
+# A single 32-bit number.
+sub EID
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $id = shift;
+	return $self->{eid} unless(defined($id));
+	my $idv = int($id);
+	$self->{eid} = $idv;
+	return $idv;
+}
+
+sub Type
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $type = shift;
+	return $self->{type} unless(defined($type));
+	my $enum = $typemap{$type};
+	#print "--->Defined\n" if (defined $enum);
+	#print "--->NOT Defined\n" if (! defined $enum);
+	die "error: unknown setting type found in input file\n" if (! defined $enum);
+   	$self->{type} = $enum;
+	return $enum;
+}
+
+sub TypeName
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	return "Undefined Type" if (! exists $maptype{$self->{type}});
+	return $maptype{$self->{type}};
+}
+
+sub Flags
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $flags = shift;
+	return $self->{flagword} unless(defined($flags));
+	my $vf = hex($flags);
+	$self->{flagword} = $vf;
+	return $vf;
+}
+
+sub Length
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $len = shift;
+	die "panic: Length() does not take an argument!\n" if (defined($len));
+	
+	my $length = 0;
+	if ($self->{type} & 0x00020000) {
+        $length = length ($self->{strvalue});
+        }
+    elsif ($self->{type} & 0x03010000) {
+	    my $array_ref = $self->{binvalue};
+	    my @array = @$array_ref;
+	    $length = $#array+1;
+	    }
+    elsif ($self->{type} & 0x000C0000) {
+	    my $array_ref = $self->{arrvalue};
+	    my @array = @$array_ref;
+	    $length = $#array+1;
+	    #printf ("arrval length %d %d\n",  length ($self->{arrval}), $length);
+	    }
+	else {
+	    $length = 0;
+        }
+	return $length;	
+}
+
+sub SizeInBytes
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $len = shift;
+	die "panic: Length() does not take an argument!\n" if (defined($len));
+	
+	my $size = 0;
+	if ($self->{type} & 0x00020000) {
+        $size = length ($self->{strvalue});
+        }
+    elsif ($self->{type} & 0x03010000) {
+	    my $array_ref = $self->{binvalue};
+	    my @array = @$array_ref;
+	    $size = $#array+1;
+	    }
+    elsif ($self->{type} & 0x000C0000) {
+	    my $array_ref = $self->{arrvalue};
+	    my @array = @$array_ref;
+	    $size = ($#array+1)*4;
+	    #printf ("arrval length %d %d\n",  length ($self->{arrval}), $length);
+	    }
+	else {
+	    $size = 0;
+        }
+	return $size;	
+}
+
+sub IsValid
+{
+	my $self = shift;
+	return undef unless(ref($self));
+
+    if (($self->{cuid} == 0) || ($self->{eid} == 0) ||
+        ($self->{type} == 0) || ($self->{flagword} != 0) ||
+        ($self->IsValueSet() == 0)) {
+        return 0;
+        }    
+    
+    #Record valid if we reach here
+    return 1;    
+}
+
+sub IsValueSet
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	return $self->{valueset};
+}
+
+sub MarkValueSet
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	$self->{valueset} = 1;
+}
+
+sub IntValue
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $value = shift;
+	if (defined($value)) {
+        my $int = int($value);
+        $self->{intvalue} = $int;
+        $self->MarkValueSet();
+        }
+	return $self->{intvalue};
+}
+
+sub HexValue
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $value = shift;
+	return $self->{intvalue} unless(defined($value));
+	my $int = hex($value);
+	$self->{intvalue} = $int;
+	$self->MarkValueSet();
+    return $int;
+}
+
+sub StrValue
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $value = shift;
+	return $self->{strvalue} unless(defined($value));
+	#printf ("strlen before %d\n", length ($self->{strvalue}));	
+    $self->{strvalue} .= $value;
+	#printf ("strlen after %d\n",  length ($self->{strvalue}));
+	$self->MarkValueSet();
+    return $value;
+}
+
+sub ArrValue
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $value = shift;
+
+	return $self->{arrvalue} unless(defined($value));
+
+    my $int = int($value);
+	my $index = $self->Length();
+
+	$self->{arrvalue}[$index] = $int; # Increments the array size as well as appending item
+	$index*=4; 
+
+	printf ("warning: array value larger than HCR maximum (512 bytes): %d\n", $index) if ($index > 512);    
+	$self->MarkValueSet();
+
+    return $self->{arrvalue};
+}
+
+sub BinValue
+{
+	my $self = shift;
+	return undef unless(ref($self));
+	my $value = shift;
+	
+	return $self->{binvalue} unless(defined($value));
+
+    my @hwords = split(/\s/,$value);
+    shift @hwords if ($hwords[0] eq "");
+    my $hwordslen = scalar(@hwords);  
+
+    #printf("(len:%d)(0:%04x 1:%04x last:%04x)\n", $hwordslen, hex($hwords[0]), hex($hwords[1]), hex($hwords[$hwordslen-1])) if ($mhd::trace);
+    
+    my $index = $self->Length();
+	#printf ("binlen before %d\n", $index);
+         
+    #print "Index: " . $index . "\n";
+    foreach my $word (@hwords) {
+        if (length ($word) == 2) {
+	        $self->{binvalue}[$index] = hex($word);
+            }
+        else {
+            die "error: hexadecimal value '$word' too short/large for 8-bit integer\n";
+            }
+
+
+	   #$self->{binvalue}[$index] = $mint;
+	   #printf("%d: %04x\n", $count, $self->{binvalue}[$count]);
+       $index++;	  
+	   }
+	  
+
+	#printf ("binlen after %d\n", $index);
+            
+    printf ("warning: binary value larger than HCR maximum (512 bytes): %d\n", $index) if ($index > 512);
+    $self->MarkValueSet();            
+	return $self->{binvalue};
+}
+
+
+# ###########################################################################
+
+1;
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/hcrscripts.inf	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,31 @@
+// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Hardware Configuration Respoitory Scripts and Utils
+// Convienence inf file, to build:  bldmake -f hcrscripts.inf bldfiles
+// Scripts not part of the offical OS build, hence these are unsupported.
+// Available for developer adhoc-testing only until offical HCR tools available.
+//
+
+/**
+@file
+Hardware Configuration Repository Scripts
+*/
+
+PRJ_EXPORTS
+
+./hcrmd.bat								/epoc32/tools/hcrmd.bat
+./hcrdat.pm								/epoc32/tools/hcr/hcrdat.pm
+./hcrrec.pm								/epoc32/tools/hcr/hcrrec.pm	
+./makehcrdat.pl							/epoc32/tools/hcr/makehcrdat.pl
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/makehcrdat.pl	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,219 @@
+#!perl -w
+#
+# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of the License "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# This simple script makes a binary HCR data file from a text input file
+#
+use strict;
+
+use HCRdat;
+use HCRrec;
+
+package mhd;
+
+#
+# Find out what file the user is interested in..
+# Make sure it's specified and exists.
+#
+$mhd::trace = 0;
+$mhd::otrace = 0;
+
+if (@ARGV < 2 || @ARGV > 4) {
+    die "\nUsage: hcrmd.bat <source_textfile> <dest_datfile> [-i]\n";
+    }
+
+my $textfile = shift @ARGV;
+my $datfile  = shift @ARGV;
+
+my $do_create_image = 0;
+my $opt_i = shift @ARGV;
+#my $partid = 0x10000005;
+if (defined($opt_i)) {
+    $do_create_image = 1 if ($opt_i eq "-i");
+    die "error: unknown command option\n" if ($opt_i ne "-i");
+    #my $i_no = shift @ARGV;
+    #$partid = hex($i_no) if (defined($i_no)); 
+    #printf("partitionid: 0x%x\n", $partid)
+    }
+
+
+print "\n    HCR Binary Data File Generator, version v0.1\n";
+print "    Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.\n\n";
+print "-input: $textfile\n" if($mhd::trace);
+print "-output: $datfile\n" if($mhd::trace);
+
+die "error: Specifed source_textfile not found!" unless(-f $textfile);
+#die "error: Specified dest_binfile '$datfile' already exists!" if(-e $datfile);
+
+printf "\nReading input file... $textfile\n";
+
+printf "-opening text file\n" if($mhd::trace);
+my $tfh;
+open($tfh, "<$textfile");
+
+printf "-started conversion...\n"  if($mhd::trace);
+my $datobj = HCRdat->new();
+my $inrec = 0;
+my $ln = 0;
+my $recobj;
+
+while (<$tfh>)
+    {
+    $ln++;
+    if ($_ =~ '^\s*#') {
+        printf "-comment\n" if($mhd::trace);
+        }
+    elsif ($_ =~ '^@') {
+        die "error: Syntax error line $ln: New record started before previous one is closed" if($inrec > 0);
+        printf "-start\n" if($mhd::trace);
+        $inrec = 1;
+        $recobj = HCRrec->new();
+        }
+    elsif ($_ =~ '^\.') {
+        die "error: Syntax error line $ln: Record closed before a new record has been opened" if($inrec == 0); 
+        printf "-end\n" if($mhd::trace);
+        if ($recobj->IsValid()) {
+            $datobj->AddSettingRecord($recobj);
+            }
+        else {
+            die "error: Record after record " . $datobj->NumRecords() . " completed but not valid, missing or has =0  fields?\n";
+            }
+        $inrec = 0;
+        }
+    elsif ($_ =~ '^\s*$') {
+        printf "-blank\n" if($mhd::trace);
+        }
+    elsif ($_ =~ '^\s*cuid:\s') {
+        print "--cuid " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'cuid:' line incorrectly formed" if (scalar(@hwords) != 2); 
+
+        $recobj->CUID($hwords[1]);
+        printf("=0x%08x\n", $recobj->CUID()) if($mhd::trace);
+        }
+    elsif ($_ =~ '^\s*eid:\s') {
+        print "--eid " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'eid:' line incorrectly formed" if (scalar(@hwords) != 2); 
+
+        $recobj->EID($hwords[1]);
+        print "=".($recobj->EID())."\n" if($mhd::trace);  
+        }
+    elsif ($_ =~ '^\s*type:\s') {
+        print "--type " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'type:' line incorrectly formed" if (scalar(@hwords) != 2); 
+        
+        $recobj->Type($hwords[1]); 
+        printf("=0x%08x (%s)\n", $recobj->Type(), $recobj->TypeName()) if($mhd::trace);
+        }
+    elsif ($_ =~ '^\s*flags:\s') {
+        print "--flags " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'flags:' line incorrectly formed" if (scalar(@hwords) != 2);
+        
+        $recobj->Flags($hwords[1]);
+        printf ("=0x%x\n", $recobj->Flags()) if($mhd::trace);  
+        printf ("warning: flag length value greater than 2-bytes\n") if ($recobj->Flags() > 0xffff);
+        }
+    elsif ($_ =~ '^\s*intval:\s') {
+        print "--intval " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'intval:' line incorrectly formed" if (scalar(@hwords) != 2); 
+
+        $recobj->IntValue($hwords[1]);
+        printf("=%d (0x%x)\n", $recobj->IntValue(), $recobj->IntValue()) if($mhd::trace);  
+        }
+    elsif ($_ =~ '^\s*hexval:\s') {
+        print "--hexval " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'hexval:' line incorrectly formed" if (scalar(@hwords) != 2); 
+
+        $recobj->HexValue($hwords[1]);
+        printf("=%d (0x%x)\n", $recobj->IntValue(), $recobj->IntValue()) if($mhd::trace);  
+        }
+    elsif ($_ =~ '^\s*arrval:\s') {
+        print "--arrval " if($mhd::trace);
+        my @hwords = split(/\s+/,$_);
+        die "error: 'arrval:' line incorrectly formed" if (scalar(@hwords) != 2); 
+        
+		print  $hwords[1]."\n" if ($mhd::trace);
+        $recobj->ArrValue($hwords[1]);  
+        }
+    elsif ($_ =~ '^\s*strval:\s') {
+        print "--strval " if($mhd::trace);
+        my @hwords = split(/\"/,$_);
+        die "error: 'strval:' line incorrectly formed" if (scalar(@hwords) != 3); 
+
+        my $strval_size = $recobj->Length();
+        $recobj->StrValue($hwords[1]);
+        
+        printf("=\"%s\"\n", substr($recobj->StrValue(), $strval_size)) if($mhd::trace);  
+        }
+    elsif ($_ =~ '^\s*binval:\s') {
+        print "--binval " if($mhd::trace);
+        my @hwords = split(/:/,$_);
+        die "error: 'binval:' line incorrectly formed" if (scalar(@hwords) < 2); 
+
+        my $binval_size = $recobj->Length();
+        $recobj->BinValue($hwords[1]);
+        
+        my $binval_ref = $recobj->BinValue();
+        my @binval = @$binval_ref;
+        
+        printf("(%d) =", $#binval+1) if($mhd::trace);
+        my $uint16 = $binval_size;
+        for (; $uint16 < @binval; $uint16++) {
+            printf("%02x ", $binval[$uint16]) if($mhd::trace);
+            } 
+
+        print "\n" if($mhd::trace);
+        }
+    elsif ($_ =~ '') {
+        }
+    else {
+        die "error: unknown line type '$_'" 
+#        print $_  if($mhd::trace);
+        }
+    }
+
+close $tfh;
+
+printf "\nGenerating output file... $datfile\n";
+
+printf "-creating binary data file\n"  if($mhd::otrace);
+if ($datobj->WriteToFile($datfile.".tmp") != 0) {
+    die "error: failed to write to dest_binfile";
+    }
+    
+printf "-renaming file to temp file to $datfile\n"  if($mhd::otrace);
+rename ($datfile.".tmp", $datfile);
+
+printf "-file header written:\n"  if($mhd::otrace);
+$datobj->ShowHeader() if($mhd::otrace);
+
+if ($do_create_image) {
+    my $imgfile = $datfile . ".img";
+    print "\nGenerating partition image... ".  $imgfile . "\n";
+
+    if ($datobj->WriteToImage($imgfile, $datfile) != 0) {
+        die "error: failed to write to image file $imgfile";
+        }
+    }
+
+print "\nDone.\n";
+exit 0;
+
+
+
Binary file kerneltest/e32utils/hcrscripts/test/array_hcrfile.dat has changed
Binary file kerneltest/e32utils/hcrscripts/test/array_hcrfile.dat.img has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/test/array_test.txt	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,54 @@
+#------------------------------------------------------------------------------
+# Large Array Settings Test file for use with the 'hcrmd' tool.
+#
+
+#------------------------------------------------------------------------------
+# Signed Integer array 32-bit tests
+#
+@
+cuid: 0xee000001
+eid:  121
+type: ArrayInt32
+flags: 0x0000
+arrval: 2147483647
+arrval: 2147483647
+.
+@
+cuid: 0xee000001
+eid:  122
+type: ArrayInt32
+flags: 0x0000
+arrval: 1
+.
+@
+cuid: 0xee000001
+eid:  123
+type: ArrayInt32
+flags: 0x0000
+arrval: -2147483648
+arrval: -2147483648
+arrval: -2147483648
+.
+
+
+#------------------------------------------------------------------------------
+# Unsigned Integer array 32-bit tests
+#
+@
+cuid: 0xee000004
+eid:  131
+type: ArrayUInt32
+flags: 0x0000
+arrval: 4294967295
+arrval: 4294967295
+arrval: 4294967295
+arrval: 4294967295
+.
+
+@
+cuid: 0xee000004
+eid:  132
+type: ArrayUInt32
+flags: 0x0000
+arrval: 0
+.
Binary file kerneltest/e32utils/hcrscripts/test/integer_hcrfile.dat has changed
Binary file kerneltest/e32utils/hcrscripts/test/integer_hcrfile.dat.img has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/test/integer_test.txt	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,205 @@
+#------------------------------------------------------------------------------
+# Integer Setting Test file for use with the 'hcrmd' tool.
+#
+
+#------------------------------------------------------------------------------
+# Signed Integer 32-bit tests
+#
+@
+cuid: 0xff000001
+eid:  1
+type: Int32
+flags: 0x0000
+intval: 2147483647
+.
+@
+cuid: 0xff000001
+eid:  2
+type: Int32
+flags: 0x0000
+intval: 0
+.
+@
+cuid: 0xff000001
+eid:  3
+type: Int32
+flags: 0x0000
+intval: -2147483648
+.
+
+#------------------------------------------------------------------------------
+# Signed Integer 16-bit tests
+#
+@
+cuid: 0xff000002
+eid:  11
+type: Int16
+flags: 0x0000
+intval: 32767
+.
+@
+cuid: 0xff000002
+eid:  12
+type: Int16
+flags: 0x0000
+intval: 0
+.
+@
+cuid: 0xff000002
+eid:  13
+type: Int16
+flags: 0x0000
+intval: -32768
+.
+
+#------------------------------------------------------------------------------
+# Signed Integer 8-bit tests
+#
+@
+cuid: 0xff000003
+eid:  21
+type: Int8
+flags: 0x0000
+intval: 127
+.
+
+@
+cuid: 0xff000003
+eid:  22
+type: Int8
+flags: 0x0000
+intval: 0
+.
+@
+cuid: 0xff000003
+eid:  23
+type: Int8
+flags: 0x0000
+intval: -128
+.
+
+#------------------------------------------------------------------------------
+# Unsigned Integer tests
+#
+@
+cuid: 0xff000004
+eid:  31
+type: UInt32
+flags: 0x0000
+intval: 4294967295
+.
+@
+cuid: 0xff000004
+eid:  32
+type: UInt16
+flags: 0x0000
+intval: 65535
+.
+@
+cuid: 0xff000004
+eid:  33
+type: UInt8
+flags: 0x0000
+intval: 255
+.
+
+#------------------------------------------------------------------------------
+# Boolean tests
+#
+@
+cuid: 0xff000005
+eid:  41
+type: Bool
+flags: 0x0000
+intval: 1
+.
+@
+cuid: 0xff000005
+eid:  42
+type: Bool
+flags: 0x0000
+intval: 0
+.
+
+
+#------------------------------------------------------------------------------
+# Linear Addrress tests
+#
+@
+cuid: 0xff000006
+eid:  51
+type: LinAddr
+flags: 0x0000
+hexval: 0x80000000
+.
+@
+cuid: 0xff000006
+eid:  52
+type: LinAddr
+flags: 0x0000
+hexval: 0x01008004
+.
+@
+cuid: 0xff000006
+eid:  53
+type: LinAddr
+flags: 0x0000
+hexval: 0x00000000
+.
+
+
+#------------------------------------------------------------------------------
+# Synatx tests
+#
+
+# Tool should cope with these
+@
+cuid: 0xffff0001
+eid:  101
+type: Int32
+intval: 1889025
+.
+@
+cuid: 0xffff0002
+eid:  102
+type: Int32
+intval: 5889025
+.
+
+# Missing fields - Tool should abort for these records
+# 
+#@
+#cuid: 0xffff0003
+#eid:  103
+#type: Int32
+#.
+#@
+#cuid: 0xffff0004
+#eid:  104
+#.
+#@
+#cuid: 0xffff0005
+#.
+#@
+#.
+
+# Incorrect Types - Tool should abort for these records
+# 
+#@
+#cuid: 0xffff0006
+#eid:  106
+#type: int32
+#intval: 1889025
+#.
+#@
+#cuid: 0xffff0007
+#eid:  107
+#type: Int
+#intval: 1889025
+#.
+#@
+#cuid: 0xffff0008
+#eid:  108
+#type: Int32ab
+#intval: 1889025
+#.
Binary file kerneltest/e32utils/hcrscripts/test/large_hcrfile.dat has changed
Binary file kerneltest/e32utils/hcrscripts/test/large_hcrfile.dat.img has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/hcrscripts/test/large_test.txt	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,378 @@
+#------------------------------------------------------------------------------
+# Large Settings Test file for use with the 'hcrmd' tool.
+#
+
+#------------------------------------------------------------------------------
+# BinData tests
+#
+
+@
+cuid: 0x000000ff
+eid:  13
+type: BinData
+flags: 000000
+binval: 0E
+.
+@
+cuid: 0x000000ff
+eid:  23
+type: BinData
+flags: 000000
+binval: 0E 1F 
+.
+@
+cuid: 0x000000ff
+eid:  33
+type: BinData
+flags: 000000
+binval: 0E 1F BA
+.
+@
+cuid: 0x000000ff
+eid:  43
+type: BinData
+flags: 000000
+binval: 0E 1F BA 11
+.
+@
+cuid: 0x000000ff
+eid:  53
+type: BinData
+flags: 000000
+binval: 0E 1F BA 11 1F
+.
+@
+cuid: 0x000000ff
+eid:  63
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 
+.
+@
+cuid: 0x000000ff
+eid:  64
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 2E
+.
+@
+cuid: 0x000000ff
+eid:  73
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 2E AA
+.
+@
+cuid: 0x000000ff
+eid:  83
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 2E AA DD
+.
+@
+cuid: 0x000000ff
+eid:  93
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+.
+
+@
+cuid: 0x000000ff
+eid:  103
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+.
+
+@
+cuid: 0x000000ff
+eid:  113
+type: BinData
+flags: 000000
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F 
+binval: 74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20 
+binval: 6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 0F
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F  
+binval: 0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 
+binval: 69 73 20 70 72 6F 67 72 61 6D 11 11 22 22 00 FF
+binval: FF FF BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
+binval: 69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F  
+.
+
+#------------------------------------------------------------------------------
+# Text8 tests
+#
+
+# Length field tests
+#
+@
+cuid: 0x11223301
+eid:  1
+type: Text8
+flags: 0x0000
+strval: "Hello World!!"   
+.
+@
+cuid: 0x11223302
+eid:  2
+type: Text8
+flags: 0x0000
+strval: "Hell"   
+.
+@
+cuid: 0x11223303
+eid:  3
+type: Text8
+flags: 0x0000
+strval: "Hello World!!    "   
+.
+
+# strval field tests
+#
+@
+cuid: 0x11223304
+eid:  1
+type: Text8
+flags: 0x0000
+strval: ""   
+.
+@
+cuid: 0x11223305
+eid:  5
+type: Text8
+flags: 0x0000
+strval: "012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab"
+.
+
+@
+cuid: 0x11223306
+eid:  6
+type: Text8
+flags: 0x0000
+strval: "012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab"
+strval: "012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789bc"
+strval: "012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789cd"
+strval: "012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789ab012345678901234567890123456789de" 
+.
+
+
+# strval field and padding tests
+#
+@
+cuid: 0x11223311
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "A"   
+.
+@
+cuid: 0x11223312
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "We"  
+. 
+@
+cuid: 0x11223313
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "Car"   
+.
+@
+cuid: 0x11223314
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "Cake"   
+.
+@
+cuid: 0x11223315
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---A"
+.
+@
+cuid: 0x11223316
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---We"  
+. 
+@
+cuid: 0x11223317
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---Car"   
+.
+@
+cuid: 0x11223318
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---Cake"   
+.
+@
+cuid: 0x11223319
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---A"
+.
+@
+cuid: 0x1122331a 
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---We"  
+. 
+@
+cuid: 0x1122331b
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---Car"   
+.
+@
+cuid: 0x1122331c
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---Cake"   
+.
+@
+cuid: 0x1122331d
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---3---A"
+.
+@
+cuid: 0x1122331e
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---3---We"  
+. 
+@
+cuid: 0x1122331f
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---3---Car"   
+.
+@
+cuid: 0x11223320
+eid:  128
+type: Text8
+flags: 0x0000
+strval: "1---2---3---Cake"   
+.
+
+
+#------------------------------------------------------------------------------
+# UInt64 & Int64 tests
+#
+
+@
+cuid: 0x55667711
+eid:  91
+type: Int64
+flags: 0x0000
+binval: 00 00 00 00 00 00 00 80
+.
+@
+cuid: 0x55667711
+eid:  92
+type: Int64
+flags: 0x0000
+binval: 00 00 00 00 00 00 00 00
+.
+#@
+#cuid: 0x55667711
+#eid:  192
+#type: Int64
+#flags: 0x0000
+#binval: 00
+#.
+@
+cuid: 0x55667711
+eid:  93
+type: Int64
+flags: 0x0000
+binval: ff ff ff ff ff ff ff 7f 
+.
+@
+cuid: 0x55667711
+eid:  94
+type: UInt64
+flags: 0x0000
+binval: ff ff ff ff ff ff ff ff
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/cephes.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,27 @@
+/*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#ifndef _CEPHES_H_
+#define _CEPHES_H_
+
+double cephes_igamc(double a, double x);
+double cephes_igam(double a, double x);
+double cephes_lgam(double x);
+double cephes_p1evl(double x, double *coef, int N);
+double cephes_polevl(double x, double *coef, int N);
+double cephes_erf(double x);
+double cephes_erfc(double x);
+double cephes_normal(double x);
+
+#endif /*  _CEPHES_H_  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/config.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,65 @@
+/*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#ifndef _CONFIG_H_
+#define	_CONFIG_H_
+
+//#define	WINDOWS32
+//#define	PROTOTYPES
+//#define	LITTLE_ENDIAN
+//#define	LOWHI
+
+/*
+ * AUTO DEFINES (DON'T TOUCH!)
+ */
+
+#ifndef	CSTRTD
+typedef char *CSTRTD;
+#endif
+#ifndef	BSTRTD
+typedef unsigned char *BSTRTD;
+#endif
+
+#ifndef	BYTE
+typedef unsigned char BYTE;
+#endif
+#ifndef	UINT
+typedef unsigned int UINT;
+#endif
+#ifndef	USHORT
+typedef unsigned short USHORT;
+#endif
+#ifndef	ULONG
+typedef unsigned long ULONG;
+#endif
+#ifndef	DIGIT
+typedef USHORT DIGIT;	/* 16-bit word */
+#endif
+#ifndef	DBLWORD
+typedef ULONG DBLWORD;  /* 32-bit word */
+#endif
+
+#ifndef	WORD64
+typedef ULONG WORD64[2];  /* 64-bit word */
+#endif
+
+#endif /* _CONFIG_H_ */
+
+#if defined(__cplusplus)
+}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/decls.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,52 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#ifndef _DECLS_H_
+#define _DECLS_H_ 
+
+#include "../include/defs.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                   G L O B A L   D A T A  S T R U C T U R E S 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+BitSequence	*epsilon;				// BIT STREAM
+TP			tp;						// TEST PARAMETER STRUCTURE
+FILE		*stats[NUMOFTESTS+1];	// FILE OUTPUT STREAM
+FILE		*results[NUMOFTESTS+1];	// FILE OUTPUT STREAM
+FILE		*freqfp;				// FILE OUTPUT STREAM
+FILE		*summary;				// FILE OUTPUT STREAM
+int			testVector[NUMOFTESTS+1];
+
+char	generatorDir[NUMOFGENERATORS][20] = { "AlgorithmTesting", "LCG", "QCG1", "QCG2","CCG", "XOR",
+			"MODEXP", "BBS", "MS", "G-SHA1", "HASH_DRBG" };
+				
+char	testNames[NUMOFTESTS+1][32] = { " ", "Frequency", "BlockFrequency", "CumulativeSums", "Runs", "LongestRun", "Rank",
+			"FFT", "NonOverlappingTemplate", "OverlappingTemplate", "Universal", "ApproximateEntropy", "RandomExcursions",
+			"RandomExcursionsVariant", "Serial", "LinearComplexity" };
+
+#endif // _DECLS_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/defs.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,92 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                       D E B U G G I N G  A I D E S
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+#ifndef _DEFS_H_
+#define _DEFS_H_
+
+#include "config.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                              M A C R O S
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+#define MAX(x,y)             ((x) <  (y)  ? (y)  : (x))
+#define MIN(x,y)             ((x) >  (y)  ? (y)  : (x))
+#define isNonPositive(x)     ((x) <= 0.e0 ?   1  : 0)
+#define isPositive(x)        ((x) >  0.e0 ?   1 : 0)
+#define isNegative(x)        ((x) <  0.e0 ?   1 : 0)
+#define isGreaterThanOne(x)  ((x) >  1.e0 ?   1 : 0)
+#define isZero(x)            ((x) == 0.e0 ?   1 : 0)
+#define isOne(x)             ((x) == 1.e0 ?   1 : 0)
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
+                         G L O B A L  C O N S T A N T S
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+#define ALPHA							0.01	/* SIGNIFICANCE LEVEL */
+#define MAXNUMOFTEMPLATES				148		/* APERIODIC TEMPLATES: 148=>temp_length=9 */
+#define NUMOFTESTS						15		/* MAX TESTS DEFINED  */
+#define NUMOFGENERATORS					11		/* MAX PRNGs */
+#define MAXFILESPERMITTEDFORPARTITION	148
+#define	TEST_FREQUENCY					1
+#define	TEST_BLOCK_FREQUENCY			2
+#define	TEST_CUSUM						3
+#define	TEST_RUNS						4
+#define	TEST_LONGEST_RUN				5
+#define	TEST_RANK						6
+#define	TEST_FFT						7
+#define	TEST_NONPERIODIC				8
+#define	TEST_OVERLAPPING				9
+#define	TEST_UNIVERSAL					10
+#define	TEST_APEN						11
+#define	TEST_RND_EXCURSION				12
+#define	TEST_RND_EXCURSION_VAR			13
+#define	TEST_SERIAL						14
+#define	TEST_LINEARCOMPLEXITY			15
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                   G L O B A L   D A T A  S T R U C T U R E S
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+typedef unsigned char	BitSequence;
+
+typedef struct _testParameters {
+	int		n;
+	int		blockFrequencyBlockLength;
+	int		nonOverlappingTemplateBlockLength;
+	int		overlappingTemplateBlockLength;
+	int		serialBlockLength;
+	int		linearComplexitySequenceLength;
+	int		approximateEntropyBlockLength;
+	int		numOfBitStreams;
+} TP;
+
+#endif // _DEFS_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/externs.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#ifndef _EXTERNS_H_
+#define _EXTERNS_H_
+
+#include "../include/defs.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                   G L O B A L   D A T A  S T R U C T U R E S 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+extern BitSequence	*epsilon;				// BIT STREAM
+extern TP			tp;						// TEST PARAMETER STRUCTURE
+extern FILE			*stats[NUMOFTESTS+1];	// FILE OUTPUT STREAM
+extern FILE			*results[NUMOFTESTS+1];	// FILE OUTPUT STREAM
+extern FILE			*freqfp;				// FILE OUTPUT STREAM
+extern FILE			*summary;				// FILE OUTPUT STREAM
+extern int			testVector[NUMOFTESTS+1];
+
+extern char	generatorDir[NUMOFGENERATORS][20];
+extern char	testNames[NUMOFTESTS+1][32];
+
+#endif // _EXTERNS_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/generators.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,116 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#ifndef _GENERATORS_H_
+#define _GENERATORS_H_
+//#include	"../include/sha.h"
+
+void	lcg();
+double	lcg_rand(int, double, double*, int);
+void	quadRes1();
+void	quadRes2();
+void	cubicRes();
+void	exclusiveOR();
+void	modExp();
+void	bbs();
+void	micali_schnorr();
+void	SHA1();
+void    HASH_DRBG();
+
+/* The circular shifts. */
+#define CS1(x) ((((ULONG)x)<<1)|(((ULONG)x)>>31))
+#define CS5(x)  ((((ULONG)x)<<5)|(((ULONG)x)>>27))
+#define CS30(x)  ((((ULONG)x)<<30)|(((ULONG)x)>>2))
+
+/* K constants */
+
+#define K0  0x5a827999L
+#define K1  0x6ed9eba1L
+#define K2  0x8f1bbcdcL
+#define K3  0xca62c1d6L
+
+#define f1(x,y,z)   ( (x & (y ^ z)) ^ z )
+
+#define f3(x,y,z)   ( (x & ( y ^ z )) ^ (z & y) )
+
+#define f2(x,y,z)   ( x ^ y ^ z )                           /* Rounds 20-39 */
+
+#define  expand(x)  Wbuff[x%16] = CS1(Wbuff[(x - 3)%16 ] ^ Wbuff[(x - 8)%16 ] ^ Wbuff[(x - 14)%16] ^ Wbuff[x%16])
+
+#define sub1Round1(count)      { \
+	 temp = CS5(A) + f1(B, C, D) + E + Wbuff[count] + K0; \
+	 E = D; \
+	 D = C; \
+	 C = CS30( B ); \
+	 B = A; \
+	 A = temp; \
+	 } \
+
+#define sub2Round1(count)   \
+	 { \
+	 expand(count); \
+	 temp = CS5(A) + f1(B, C, D) + E + Wbuff[count%16] + K0; \
+	 E = D; \
+	 D = C; \
+	 C = CS30( B ); \
+	 B = A; \
+	 A = temp; \
+	} \
+
+#define Round2(count)     \
+	 { \
+	 expand(count); \
+	 temp = CS5( A ) + f2( B, C, D ) + E + Wbuff[count%16] + K1;  \
+	 E = D; \
+	 D = C; \
+	 C = CS30( B ); \
+	 B = A; \
+	 A = temp;  \
+	 } \
+
+#define Round3(count)    \
+	 { \
+	 expand(count); \
+	 temp = CS5( A ) + f3( B, C, D ) + E + Wbuff[count%16] + K2; \
+	 E = D; \
+	 D = C; \
+	 C = CS30( B ); \
+	 B = A; \
+	 A = temp; \
+	 }
+
+#define Round4(count)    \
+	 { \
+	 expand(count); \
+	 temp = CS5( A ) + f2( B, C, D ) + E + Wbuff[count%16] + K3; \
+	 E = D; \
+	 D = C; \
+	 C = CS30( B ); \
+	 B = A; \
+	 A = temp; \
+	 }
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/genutils.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,71 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#ifndef _GENUTILS_H_
+#define _GENUTILS_H_
+
+#include "openc.h"
+#include "config.h"
+
+typedef struct _MP_struct {
+	int		size;	/*  in bytes  */
+	int		bitlen;	/*  in bits, duh  */
+	BYTE	*val;
+	} MP;
+
+#define	FREE(A)	if ( (A) ) { free((A)); (A) = NULL; }
+#define	ASCII2BIN(ch)	( (((ch) >= '0') && ((ch) <= '9')) ? ((ch) - '0') : (((ch) >= 'A') && ((ch) <= 'F')) ? ((ch) - 'A' + 10) : ((ch) - 'a' + 10) )
+
+#ifndef EXPWD
+#define	EXPWD		((DBLWORD)1<<NUMLEN)
+#endif
+
+#define	sniff_bit(ptr,mask)		(*(ptr) & mask)
+
+/*
+ * Function Declarations
+ */
+int		greater(BYTE *x, BYTE *y, int l);
+int		less(BYTE *x, BYTE *y, int l);
+BYTE	bshl(BYTE *x, int l);
+void	bshr(BYTE *x, int l);
+int		Mult(BYTE *A, BYTE *B, int LB, BYTE *C, int LC);
+void	ModSqr(BYTE *A, BYTE *B, int LB, BYTE *M, int LM);
+void	ModMult(BYTE *A, BYTE *B, int LB, BYTE *C, int LC, BYTE *M, int LM);
+void	smult(BYTE *A, BYTE b, BYTE *C, int L);
+void	Square(BYTE *A, BYTE *B, int L);
+void	ModExp(BYTE *A, BYTE *B, int LB, BYTE *C, int LC, BYTE *M, int LM);
+int		DivMod(BYTE *x, int lenx, BYTE *n, int lenn, BYTE *quot, BYTE *rem);
+void	Mod(BYTE *x, int lenx, BYTE *n, int lenn);
+void	Div(BYTE *x, int lenx, BYTE *n, int lenn);
+void	sub(BYTE *A, int LA, BYTE *B, int LB);
+int		negate(BYTE *A, int L);
+BYTE	add(BYTE *A, int LA, BYTE *B, int LB);
+void	prettyprintBstr(char *S, BYTE *A, int L);
+void	byteReverse(ULONG *buffer, int byteCount);
+void	ahtopb (char *ascii_hex, BYTE *p_binary, int bin_len);
+
+#endif  /* _GENUTILS_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/matrix.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,43 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+       R A N K  A L G O R I T H M  F U N C T I O N  P R O T O T Y P E S 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+#ifndef _MATRIX_H_
+#define _MATRIX_H_
+
+int				computeRank(int M, int Q, BitSequence **matrix);
+void			perform_elementary_row_operations(int flag, int i, int M, int Q, BitSequence **A);
+int				find_unit_element_and_swap(int flag, int i, int M, int Q, BitSequence **A);
+int				swap_rows(int i, int index, int Q, BitSequence **A);
+int				determine_rank(int m, int M, int Q, BitSequence **A);
+BitSequence**	create_matrix(int M, int Q);
+void			display_matrix(int M, int Q, BitSequence **m);
+void			def_matrix(int M, int Q, BitSequence **m,int k);
+void			delete_matrix(int M, BitSequence **matrix);
+
+#endif // _MATRIX_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/stat_fncs.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+     S T A T I S T I C A L  T E S T  F U N C T I O N  P R O T O T Y P E S 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+#ifndef _STAT_FNCS_H_
+#define _STAT_FNCS_H_
+
+void	Frequency(int n);
+void	BlockFrequency(int M, int n);
+void	CumulativeSums(int n);
+void	Runs(int n);
+void	LongestRunOfOnes(int n);
+void	Rank(int n);
+void	DiscreteFourierTransform(int n);
+void	NonOverlappingTemplateMatchings(int m, int n);
+void	OverlappingTemplateMatchings(int m, int n);
+void	Universal(int n);
+void	ApproximateEntropy(int m, int n);
+void	RandomExcursions(int n);
+void	RandomExcursionsVariant(int n);
+void	LinearComplexity(int M, int n);
+void	Serial(int m, int n);
+
+#endif // _STAT_FNCS_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/utilities.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,66 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+              U T I L I T Y  F U N C T I O N  P R O T O T Y P E S 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+#ifndef _UTILITIES_H_
+#define _UTILITIES_H_
+
+int		displayGeneratorOptions();
+int		generatorOptions(char** streamFile);
+void	chooseTests();
+void	fixParameters();
+void	fileBasedBitStreams(char *streamFile);
+void	readBinaryDigitsInASCIIFormat(FILE *fp, char *streamFile);
+void	readHexDigitsInBinaryFormat(FILE *fp);
+int		convertToBits(const BYTE *x, int xBitLength, int bitsNeeded, int *num_0s, int *num_1s, int *bitsRead);
+void	openOutputStreams(int option);
+void    InitializeNISTSuiteL(int option);
+void    ReleaseResources();
+void	invokeTestSuite(int option, char *streamFile);
+void	nist_test_suite();
+void    GetNextTemplateItem(BitSequence aBitSequence[]);
+
+
+extern CConsoleBase*    gConsole;
+extern TBuf8<KMaxFileName>       gLogFilePath;
+
+extern TInt gTemplateIndex;
+
+const TInt KMaxBit = 32;
+
+
+
+// inline functions
+inline void ResetTemplateIndex()
+    {
+    gTemplateIndex = 1;
+    }
+
+
+#endif // _UTILITIES_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/utils/openc.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*/
+
+
+#ifndef _OPENC_H_
+#define _OPENC_H_
+
+#include <e32base.h>
+#include <e32std.h>
+#include <e32cons.h>            // Console
+#include <f32file.h>
+
+#include <e32math.h>
+
+extern RFs gFileSession;
+
+// Math functions
+double log(double);
+double exp(double);
+double fabs(double);
+double floor(double);
+double sqrt(double);
+double erf(double);
+double erfc(double);
+
+double pow(double, double);
+
+// Math trigonometric functions
+double sin(double);
+double cos(double);
+
+
+// data types
+typedef RFile FILE;
+#define EOF (-1)
+typedef TUint32     u_int32_t;
+typedef TInt32      int32_t;
+
+#define SEEK_SET    0   /* set file offset to offset */
+#define SEEK_CUR    1   /* set file offset to current plus offset */
+#define SEEK_END    2   /* set file offset to EOF plus offset */
+
+
+// stdio functions
+int     printf(const char * __restrict, ...);
+int     scanf(const char * __restrict, ...);
+int     sprintf(char * __restrict, const char * __restrict, ...);
+int     puts ( const char * str );
+int     putchar ( int character );
+char*   strcpy(char* aDest, const char* aSrc);
+
+FILE    *fopen(const char * __restrict, const char * __restrict);
+int     fclose(FILE *);
+int     fprintf(FILE * __restrict, const char * __restrict, ...);
+int     fscanf(FILE * __restrict, const char * __restrict, ...);
+TUint32  fread(void * __restrict, TUint32, TUint32, FILE * __restrict);
+int     fseek(FILE *, long, int);
+
+int     fflush(FILE *);
+
+// stdlib functions
+void*   calloc(TUint32, TUint32);
+void    free(void *);
+
+void    qsort (void* base, TUint32 nmemb, TUint32 size, int (*compar)(const void*, const void*));
+
+void    exit (int status);
+
+// Other utility functions
+void ReadStringFromConsole(TDes& aString);
+TInt ReadIntL(TInt& aValue);
+
+#endif /* _OPENC_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/approximateentropy.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,111 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/cephes.h"  
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                A P P R O X I M A T E  E N T R O P Y   T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+ApproximateEntropy(int m, int n)
+{
+	int				i, j, k, r, blockSize, seqLength, powLen, index;
+	double			sum, numOfBlocks, ApEn[2], apen, chi_squared, p_value;
+	unsigned int	*P;
+	
+	fprintf(stats[TEST_APEN], "\t\t\tAPPROXIMATE ENTROPY TEST\n");
+	fprintf(stats[TEST_APEN], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_APEN], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_APEN], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_APEN], "\t\t(a) m (block length)    = %d\n", m);
+
+	seqLength = n;
+	r = 0;
+	
+	for ( blockSize=m; blockSize<=m+1; blockSize++ ) {
+		if ( blockSize == 0 ) {
+			ApEn[0] = 0.00;
+			r++;
+		}
+		else {
+			numOfBlocks = (double)seqLength;
+			powLen = (int)pow(2, blockSize+1)-1;
+			if ( (P = (unsigned int*)calloc(powLen,sizeof(unsigned int)))== NULL ) {
+				fprintf(stats[TEST_APEN], "ApEn:  Insufficient memory available.\n");
+				return;
+			}
+			for ( i=1; i<powLen-1; i++ )
+				P[i] = 0;
+			for ( i=0; i<numOfBlocks; i++ ) { /* COMPUTE FREQUENCY */
+				k = 1;
+				for ( j=0; j<blockSize; j++ ) {
+					k <<= 1;
+					if ( (int)epsilon[(i+j) % seqLength] == 1 )
+						k++;
+				}
+				P[k-1]++;
+			}
+			/* DISPLAY FREQUENCY */
+			sum = 0.0;
+			index = (int)pow(2, blockSize)-1;
+			for ( i=0; i<(int)pow(2, blockSize); i++ ) {
+				if ( P[index] > 0 )
+					sum += P[index]*log(P[index]/numOfBlocks);
+				index++;
+			}
+			sum /= numOfBlocks;
+			ApEn[r] = sum;
+			r++;
+			free(P);
+		}
+	}
+	apen = ApEn[0] - ApEn[1];
+	
+	chi_squared = 2.0*seqLength*(log(2) - apen);
+	p_value = cephes_igamc(pow(2, m-1), chi_squared/2.0);
+	
+	fprintf(stats[TEST_APEN], "\t\t(b) n (sequence length) = %d\n", seqLength);
+	fprintf(stats[TEST_APEN], "\t\t(c) Chi^2               = %f\n", chi_squared);
+	fprintf(stats[TEST_APEN], "\t\t(d) Phi(m)	       = %f\n", ApEn[0]);
+	fprintf(stats[TEST_APEN], "\t\t(e) Phi(m+1)	       = %f\n", ApEn[1]);
+	fprintf(stats[TEST_APEN], "\t\t(f) ApEn                = %f\n", apen);
+	fprintf(stats[TEST_APEN], "\t\t(g) Log(2)              = %f\n", log(2.0));
+	fprintf(stats[TEST_APEN], "\t\t--------------------------------------------\n");
+
+	if ( m > (int)(log(seqLength)/log(2)-5) ) {
+		fprintf(stats[TEST_APEN], "\t\tNote: The blockSize = %d exceeds recommended value of %d\n", m,
+			MAX(1, (int)(log(seqLength)/log(2)-5)));
+		fprintf(stats[TEST_APEN], "\t\tResults are inaccurate!\n");
+		fprintf(stats[TEST_APEN], "\t\t--------------------------------------------\n");
+	}
+	
+	fprintf(stats[TEST_APEN], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_APEN], "%f\n", p_value);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/assess.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,419 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*/
+
+
+/* --------------------------------------------------------------------------
+   Title       :  The NIST Statistical Test Suite
+
+   Date        :  December 1999
+
+   Programmer  :  Juan Soto
+
+   Summary     :  For use in the evaluation of the randomness of bitstreams
+                  produced by cryptographic random number generators.
+
+   Package     :  Version 1.0
+
+   Copyright   :  (c) 1999 by the National Institute Of Standards & Technology
+
+   History     :  Version 1.0 by J. Soto, October 1999
+                  Revised by J. Soto, November 1999
+                  Revised by Larry Bassham, March 2008
+
+   Keywords    :  Pseudorandom Number Generator (PRNG), Randomness, Statistical 
+                  Tests, Complementary Error functions, Incomplete Gamma 
+                  Function, Random Walks, Rank, Fast Fourier Transform, 
+                  Template, Cryptographically Secure PRNG (CSPRNG),
+                  Approximate Entropy (ApEn), Secure Hash Algorithm (SHA-1), 
+                  Blum-Blum-Shub (BBS) CSPRNG, Micali-Schnorr (MS) CSPRNG, 
+
+   Source      :  David Banks, Elaine Barker, James Dray, Allen Heckert, 
+                  Stefan Leigh, Mark Levenson, James Nechvatal, Andrew Rukhin, 
+                  Miles Smid, Juan Soto, Mark Vangel, and San Vo.
+
+   Technical
+   Assistance  :  Larry Bassham, Ron Boisvert, James Filliben, Daniel Lozier,
+                  and Bert Rust.
+
+   Warning     :  Portability Issues.
+
+   Limitation  :  Amount of memory allocated for workspace.
+
+   Restrictions:  Permission to use, copy, and modify this software without 
+                  fee is hereby granted, provided that this entire notice is 
+                  included in all copies of any software which is or includes
+                  a copy or modification of this software and in all copies 
+                  of the supporting documentation for such software.
+   -------------------------------------------------------------------------- */
+//system include
+#include <e32base.h>
+#include <e32std.h>
+#include <e32cons.h>
+
+// user include
+#include "openc.h"
+#include "../include/decls.h"
+#include "../include/cephes.h"  
+#include "../include/utilities.h"
+#include "../include/generators.h"
+
+typedef int (*CompareFnType)(const void*, const void*);
+
+void	partitionResultFile(int numOfFiles, int numOfSequences, int option, int testNameID);
+void	postProcessResults(int option);
+int		cmp(const double *a, const double *b);
+int		computeMetrics(char *s, int test);
+
+int
+StartNISTTest()
+{
+	int		i;
+	int		option = 10;			/* TEMPLATE LENGTH/STREAM LENGTH/GENERATOR*/
+	char	*streamFile = NULL;	/* STREAM FILENAME     */
+	
+
+	tp.n = 1000000; // length of the individual bit stream(s) to be processed
+	tp.blockFrequencyBlockLength = 128;
+	tp.nonOverlappingTemplateBlockLength = 9;
+	tp.overlappingTemplateBlockLength = 9;
+	tp.approximateEntropyBlockLength = 10;
+	tp.serialBlockLength = 16;
+	tp.linearComplexitySequenceLength = 500;
+	tp.numOfBitStreams = 100;
+	chooseTests();
+	fixParameters();
+	openOutputStreams(option);
+	invokeTestSuite(option, streamFile);
+	fclose(freqfp);
+	for( i=1; i<=NUMOFTESTS; i++ ) {
+		if ( stats[i] != NULL )
+			fclose(stats[i]);
+		if ( results[i] != NULL )
+			fclose(results[i]);
+	}
+	if ( (testVector[0] == 1) || (testVector[TEST_CUSUM] == 1) ) 
+		partitionResultFile(2, tp.numOfBitStreams, option, TEST_CUSUM);
+	if ( (testVector[0] == 1) || (testVector[TEST_NONPERIODIC] == 1) ) 
+		partitionResultFile(MAXNUMOFTEMPLATES, tp.numOfBitStreams, option, TEST_NONPERIODIC);
+	if ( (testVector[0] == 1) || (testVector[TEST_RND_EXCURSION] == 1) )
+		partitionResultFile(8, tp.numOfBitStreams, option, TEST_RND_EXCURSION);
+	if ( (testVector[0] == 1) || (testVector[TEST_RND_EXCURSION_VAR] == 1) )
+		partitionResultFile(18, tp.numOfBitStreams, option, TEST_RND_EXCURSION_VAR);
+	if ( (testVector[0] == 1) || (testVector[TEST_SERIAL] == 1) )
+		partitionResultFile(2, tp.numOfBitStreams, option, TEST_SERIAL);
+	fprintf(summary, "------------------------------------------------------------------------------\n");
+	fprintf(summary, "RESULTS FOR THE UNIFORMITY OF P-VALUES AND THE PROPORTION OF PASSING SEQUENCES\n");
+	fprintf(summary, "------------------------------------------------------------------------------\n");
+	fprintf(summary, " C1  C2  C3  C4  C5  C6  C7  C8  C9 C10  P-VALUE  PROPORTION  STATISTICAL TEST\n");
+	fprintf(summary, "------------------------------------------------------------------------------\n");
+	postProcessResults(option);
+	fclose(summary);
+
+	return 1;
+    }
+
+void
+partitionResultFile(int numOfFiles, int numOfSequences, int option, int testNameID)
+{ 
+	int		i, k, m, j, start, end, num, numread;
+	float	c;
+	FILE	**fp = (FILE **)calloc(numOfFiles+1, sizeof(FILE *));
+	int		*results = (int *)calloc(numOfFiles, sizeof(int *));
+	char	*s[MAXFILESPERMITTEDFORPARTITION];
+	char	resultsDir[200];
+	
+	for ( i=0; i<MAXFILESPERMITTEDFORPARTITION; i++ )
+		s[i] = (char*)calloc(200, sizeof(char));
+	
+	sprintf(resultsDir, "%s\\experiments\\%s\\%s\\results", gLogFilePath.PtrZ(), generatorDir[option], testNames[testNameID]);
+	
+	if ( (fp[numOfFiles] = fopen(resultsDir, "r")) == NULL ) {
+		printf("%s", resultsDir);
+		printf(" -- file not found. Exiting program.\n");
+		exit(-1);
+	}
+	
+	for ( i=0; i<numOfFiles; i++ ) 
+	    {
+		sprintf(s[i], "%s\\experiments\\%s\\%s\\data%d", gLogFilePath.PtrZ(), generatorDir[option], testNames[testNameID], i+1);
+        }
+	numread = 0;
+	m = numOfFiles/20;
+	if ( (numOfFiles%20) != 0 )
+		m++;
+	for ( i=0; i<numOfFiles; i++ ) {
+		if ( (fp[i] = fopen(s[i], "w")) == NULL ) {
+			printf("%s", s[i]);
+			printf(" -- file not found. Exiting program.\n");
+			exit(-1);
+		}
+		fclose(fp[i]);
+	}
+	for ( num=0; num<numOfSequences; num++ ) {
+		for ( k=0; k<m; k++ ) { 			/* FOR EACH BATCH */
+			
+			start = k*20;		/* BOUNDARY SEGMENTS */
+			end   = k*20+19;
+			if ( k == (m-1) )
+				end = numOfFiles-1;
+			
+			for ( i=start; i<=end; i++ ) {		/* OPEN FILE */
+				if ( (fp[i] = fopen(s[i], "a")) == NULL ) {
+					printf("%s", s[i]);
+					printf(" -- file not found. Exiting program.\n");
+					exit(-1);
+				}
+			}
+			
+			for ( j=start; j<=end; j++ ) {		/* POPULATE FILE */
+				fscanf(fp[numOfFiles], "%f", &c);
+				fprintf(fp[j], "%f\n", c);
+				numread++;
+			}
+
+			for ( i=start; i<=end; i++ )		/* CLOSE FILE */
+				fclose(fp[i]);
+		}
+	}
+	fclose(fp[numOfFiles]);
+	for ( i=0; i<MAXFILESPERMITTEDFORPARTITION; i++ )
+		free(s[i]);
+	
+	free(fp);
+	free(results);
+	return;
+}
+
+int
+cmp(const double *a, const double *b)
+{
+	if ( *a < *b )
+		return -1;
+	if ( *a == *b )
+		return 0;
+	return 1;
+}
+
+void
+postProcessResults(int option)
+{
+	int    i, k;
+	int    randomExcursionSampleSize = 0;
+	int    generalSampleSize = 0;
+	int		case1, case2, numOfFiles = 2;
+	double	passRate;
+	char	s[200];
+	
+	for ( i=1; i<=NUMOFTESTS; i++ ) {		// FOR EACH TEST
+		if ( testVector[i] ) {
+			// SPECIAL CASES -- HANDLING MULTIPLE FILES FOR A SINGLE TEST
+			if ( ((i == TEST_CUSUM) && testVector[TEST_CUSUM] ) ||
+				 ((i == TEST_NONPERIODIC) && testVector[TEST_NONPERIODIC] ) ||
+				 ((i == TEST_RND_EXCURSION) && testVector[TEST_RND_EXCURSION]) ||
+				 ((i == TEST_RND_EXCURSION_VAR) && testVector[TEST_RND_EXCURSION_VAR]) || 
+				 ((i == TEST_SERIAL) && testVector[TEST_SERIAL]) ) {
+				
+				if ( (i == TEST_NONPERIODIC) && testVector[TEST_NONPERIODIC] )  
+					numOfFiles = MAXNUMOFTEMPLATES;
+				else if ( (i == TEST_RND_EXCURSION) && testVector[TEST_RND_EXCURSION] ) 
+					numOfFiles = 8;
+				else if ( (i == TEST_RND_EXCURSION_VAR) && testVector[TEST_RND_EXCURSION_VAR] ) 
+					numOfFiles = 18;
+				else
+					numOfFiles = 2;
+				for ( k=0; k<numOfFiles; k++ ) {
+					if ( k < 10 )
+						sprintf(s, "%s\\experiments\\%s\\%s\\data%1d", gLogFilePath.PtrZ(), generatorDir[option], testNames[i], k+1);
+					else if ( k < 100 )
+						sprintf(s, "%s\\experiments\\%s\\%s\\data%2d", gLogFilePath.PtrZ(), generatorDir[option], testNames[i], k+1);
+					else
+						sprintf(s, "%s\\experiments\\%s\\%s\\data%3d", gLogFilePath.PtrZ(), generatorDir[option], testNames[i], k+1);
+					if ( (i == TEST_RND_EXCURSION) || (i == TEST_RND_EXCURSION_VAR) ) 
+						randomExcursionSampleSize = computeMetrics(s,i);
+					else
+						generalSampleSize = computeMetrics(s,i);
+				}
+			}
+			else {
+				sprintf(s, "%s\\experiments\\%s\\%s\\results", gLogFilePath.PtrZ(), generatorDir[option], testNames[i]);
+				generalSampleSize = computeMetrics(s,i);
+			}
+		}
+	}
+
+	fprintf(summary, "\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
+	case1 = 0;
+	case2 = 0;
+	if ( testVector[TEST_RND_EXCURSION] || testVector[TEST_RND_EXCURSION_VAR] ) 
+		case2 = 1;
+	for ( i=1; i<=NUMOFTESTS; i++ ) {
+		if ( testVector[i] && (i != TEST_RND_EXCURSION) && (i != TEST_RND_EXCURSION_VAR) ) {
+			case1 = 1;
+			break;
+		}
+	}
+	if ( case1 ) {
+		if ( generalSampleSize == 0 ) {
+			fprintf(summary, "The minimum pass rate for each statistical test with the exception of the\n");
+			fprintf(summary, "random excursion (variant) test is undefined.\n\n");
+		}
+		else {
+			passRate = 0.99-3.0*sqrt(0.01*(1.0-ALPHA)/(double)generalSampleSize);
+			fprintf(summary, "The minimum pass rate for each statistical test with the exception of the\n");
+			fprintf(summary, "random excursion (variant) test is approximately = %f for a\n", generalSampleSize ? passRate : 0.0);
+			fprintf(summary, "sample size = %d binary sequences.\n\n", generalSampleSize);
+		}
+	}
+	if ( case2 ) {
+		if ( randomExcursionSampleSize == 0 )
+			fprintf(summary, "The minimum pass rate for the random excursion (variant) test is undefined.\n\n");
+		else {
+			passRate = 0.99-3.0*sqrt(0.01*(1.0-ALPHA)/(double)randomExcursionSampleSize);
+			fprintf(summary, "The minimum pass rate for the random excursion (variant) test\n");
+			fprintf(summary, "is approximately %f for a sample size = %d binary sequences.\n\n", passRate, randomExcursionSampleSize);
+		}
+	}
+	fprintf(summary, "For further guidelines construct a probability table using the MAPLE program\n");
+	fprintf(summary, "provided in the addendum section of the documentation.\n");
+	fprintf(summary, "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
+}
+
+int
+computeMetrics(char *s, int test)
+{
+	int		j, pos, count, sampleSize, expCount;
+	int		freqPerBin[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+	double	*A = NULL;
+	double  *T = NULL;
+	double  chi2, proportion, uniformity;
+	float	c;
+	FILE	*fp = NULL;
+
+	if ( (fp = fopen(s, "r")) == NULL ) {
+		printf("%s",s);
+		printf(" -- file not found. Exiting program.\n");
+		exit(-1);
+	}
+	
+	/* Compute Metric 1: Proportion of Passing Sequences */
+	
+	count = 0; 		
+	sampleSize = tp.numOfBitStreams;
+	
+	if ( (test == TEST_RND_EXCURSION) || (test == TEST_RND_EXCURSION_VAR) ) { /* Special Case: Random Excursion Tests */
+		if ( (T = (double *)calloc(tp.numOfBitStreams, sizeof(double))) == NULL ) {
+			printf("Final Analysis Report aborted due to insufficient workspace\n");
+			// Perform cleanup before returning
+			fclose(fp);
+			return 0;
+		}
+		for ( j=0; j<sampleSize; j++ ) {
+			fscanf(fp, "%f", &c);
+			if ( c > 0.000000 )
+				T[count++] = c;
+		}
+
+		if ( (A = (double *)calloc(count, sizeof(double))) == NULL ) {
+			printf("Final Analysis Report aborted due to insufficient workspace\n");
+            // Perform cleanup before returning
+            fclose(fp);
+            free(T);
+			return 0;
+		}
+
+		for ( j=0; j<count; j++ )
+			A[j] = T[j];
+		
+		sampleSize = count;
+		count = 0;
+		for ( j=0; j<sampleSize; j++ )
+			if ( A[j] < ALPHA )
+				count++;
+		free(T);
+		T = NULL;
+	}
+	else {
+		if ( (A = (double *)calloc(sampleSize, sizeof(double))) == NULL ) {
+			printf("Final Analysis Report aborted due to insufficient workspace\n");
+            // Perform cleanup before returning
+            fclose(fp);
+			return 0;
+		}
+		for ( j=0; j<sampleSize; j++ ) {
+			fscanf(fp, "%f", &c);
+			if ( c < ALPHA )
+				count++;
+			A[j] = c;
+		}
+	}
+	if ( sampleSize == 0 )
+		proportion = 0.0;
+	else
+		proportion = 1.0-(double)count/sampleSize;
+
+	/* Compute Metric 2: Histogram */
+
+	qsort((void *)A, sampleSize, sizeof(double), (CompareFnType)cmp);
+	
+	for ( j=0; j<sampleSize; j++ ) {
+		pos = (int)floor(A[j]*10);
+		if ( pos == 10 )
+			pos--;
+		freqPerBin[pos]++;
+	}
+	chi2 = 0.0;
+	expCount = sampleSize/10;
+	for ( j=0; j<10; j++ )
+		chi2 += pow(freqPerBin[j]-expCount, 2)/expCount;
+	uniformity = cephes_igamc(9.0/2.0, chi2/2.0);
+
+	for ( j=0; j<10; j++ )			/* DISPLAY RESULTS */
+		fprintf(summary, "%3d ", freqPerBin[j]);
+
+	if ( expCount == 0 )
+		fprintf(summary, "    ----    ");
+	else if ( uniformity < 0.0001 )
+		fprintf(summary, " %8.6f * ", uniformity);
+	else
+		fprintf(summary, " %8.6f   ", uniformity);
+
+	if ( sampleSize == 0 )
+		fprintf(summary, " ----     %s\n", testNames[test]);
+	else if ( proportion < 0.96 )
+		fprintf(summary, "%6.4f *  %s\n", proportion, testNames[test]);
+	else
+		fprintf(summary, "%6.4f    %s\n", proportion, testNames[test]);
+
+	fclose(fp);
+	free(A);
+	
+	return sampleSize;
+}
+
+/*
+Gobal Entry Function
+*/
+GLDEF_C TInt E32Main()
+    {
+    __UHEAP_MARK;
+    TInt ret = StartNISTTest();
+    __UHEAP_MARKEND;
+    
+    return ret;
+    }
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/blockfrequency.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,68 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                    B L O C K  F R E Q U E N C Y  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+BlockFrequency(int M, int n)
+{
+	int		i, j, N, blockSum;
+	double	p_value, sum, pi, v, chi_squared;
+	
+	N = n/M; 		/* # OF SUBSTRING BLOCKS      */
+	sum = 0.0;
+	
+	for ( i=0; i<N; i++ ) {
+		blockSum = 0;
+		for ( j=0; j<M; j++ )
+			blockSum += epsilon[j+i*M];
+		pi = (double)blockSum/(double)M;
+		v = pi - 0.5;
+		sum += v*v;
+	}
+	chi_squared = 4.0 * M * sum;
+	p_value = cephes_igamc(N/2.0, chi_squared/2.0);
+
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t\tBLOCK FREQUENCY TEST\n");
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t(a) Chi^2           = %f\n", chi_squared);
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t(b) # of substrings = %d\n", N);
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t(c) block length    = %d\n", M);
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t(d) Note: %d bits were discarded.\n", n % M);
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "\t\t---------------------------------------------\n");
+
+	fprintf(stats[TEST_BLOCK_FREQUENCY], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_BLOCK_FREQUENCY], "%f\n", p_value);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/cephes.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,357 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+
+
+#include "openc.h"
+#include "../include/cephes.h"
+
+static const double	rel_error = 1E-12;
+
+double MACHEP = 1.11022302462515654042E-16;		// 2**-53
+double MAXLOG = 7.09782712893383996732224E2;	// log(MAXNUM)
+double MAXNUM = 1.7976931348623158E308;			// 2**1024*(1-MACHEP)
+double PI     = 3.14159265358979323846;			// pi, duh!
+
+static double big = 4.503599627370496e15;
+static double biginv =  2.22044604925031308085e-16;
+
+int sgngam = 0;
+
+double
+cephes_igamc(double a, double x)
+{
+	double ans, ax, c, yc, r, t, y, z;
+	double pk, pkm1, pkm2, qk, qkm1, qkm2;
+
+	if ( (x <= 0) || ( a <= 0) )
+		return( 1.0 );
+
+	if ( (x < 1.0) || (x < a) )
+		return( 1.e0 - cephes_igam(a,x) );
+
+	ax = a * log(x) - x - cephes_lgam(a);
+
+	if ( ax < -MAXLOG ) {
+		printf("igamc: UNDERFLOW\n");
+		return 0.0;
+	}
+	ax = exp(ax);
+
+	/* continued fraction */
+	y = 1.0 - a;
+	z = x + y + 1.0;
+	c = 0.0;
+	pkm2 = 1.0;
+	qkm2 = x;
+	pkm1 = x + 1.0;
+	qkm1 = z * x;
+	ans = pkm1/qkm1;
+
+	do {
+		c += 1.0;
+		y += 1.0;
+		z += 2.0;
+		yc = y * c;
+		pk = pkm1 * z  -  pkm2 * yc;
+		qk = qkm1 * z  -  qkm2 * yc;
+		if ( qk != 0 ) {
+			r = pk/qk;
+			t = fabs( (ans - r)/r );
+			ans = r;
+		}
+		else
+			t = 1.0;
+		pkm2 = pkm1;
+		pkm1 = pk;
+		qkm2 = qkm1;
+		qkm1 = qk;
+		if ( fabs(pk) > big ) {
+			pkm2 *= biginv;
+			pkm1 *= biginv;
+			qkm2 *= biginv;
+			qkm1 *= biginv;
+		}
+	} while ( t > MACHEP );
+
+	return ans*ax;
+}
+
+double
+cephes_igam(double a, double x)
+{
+	double ans, ax, c, r;
+
+	if ( (x <= 0) || ( a <= 0) )
+		return 0.0;
+
+	if ( (x > 1.0) && (x > a ) )
+		return 1.e0 - cephes_igamc(a,x);
+
+	/* Compute  x**a * exp(-x) / gamma(a)  */
+	ax = a * log(x) - x - cephes_lgam(a);
+	if ( ax < -MAXLOG ) {
+		printf("igam: UNDERFLOW\n");
+		return 0.0;
+	}
+	ax = exp(ax);
+
+	/* power series */
+	r = a;
+	c = 1.0;
+	ans = 1.0;
+
+	do {
+		r += 1.0;
+		c *= x/r;
+		ans += c;
+	} while ( c/ans > MACHEP );
+
+	return ans * ax/a;
+}
+
+
+/* A[]: Stirling's formula expansion of log gamma
+ * B[], C[]: log gamma function between 2 and 3
+ */
+static unsigned short A[] = {
+	0x6661,0x2733,0x9850,0x3f4a,
+	0xe943,0xb580,0x7fbd,0xbf43,
+	0x5ebb,0x20dc,0x019f,0x3f4a,
+	0xa5a1,0x16b0,0xc16c,0xbf66,
+	0x554b,0x5555,0x5555,0x3fb5
+};
+static unsigned short B[] = {
+	0x6761,0x8ff3,0x8901,0xc095,
+	0xb93e,0x355b,0xf234,0xc0e2,
+	0x89e5,0xf890,0x3d73,0xc114,
+	0xdb51,0xf994,0xbc82,0xc131,
+	0xf20b,0x0219,0x4589,0xc13a,
+	0x055e,0x5418,0x0c67,0xc12a
+};
+static unsigned short C[] = {
+	/*0x0000,0x0000,0x0000,0x3ff0,*/
+	0x12b2,0x1cf3,0xfd0d,0xc075,
+	0xd757,0x7b89,0xaa0d,0xc0d0,
+	0x4c9b,0xb974,0xeb84,0xc10a,
+	0x0043,0x7195,0x6286,0xc131,
+	0xf34c,0x892f,0x5255,0xc143,
+	0xe14a,0x6a11,0xce4b,0xc13e
+};
+
+#define MAXLGM 2.556348e305
+
+
+/* Logarithm of gamma function */
+double
+cephes_lgam(double x)
+{
+	double	p, q, u, w, z;
+	int		i;
+
+	sgngam = 1;
+
+	if ( x < -34.0 ) {
+		q = -x;
+		w = cephes_lgam(q); /* note this modifies sgngam! */
+		p = floor(q);
+		if ( p == q ) {
+lgsing:
+			goto loverf;
+		}
+		i = (int)p;
+		if ( (i & 1) == 0 )
+			sgngam = -1;
+		else
+			sgngam = 1;
+		z = q - p;
+		if ( z > 0.5 ) {
+			p += 1.0;
+			z = p - q;
+		}
+		z = q * sin( PI * z );
+		if ( z == 0.0 )
+			goto lgsing;
+		/*      z = log(PI) - log( z ) - w;*/
+		z = log(PI) - log( z ) - w;
+		return z;
+	}
+
+	if ( x < 13.0 ) {
+		z = 1.0;
+		p = 0.0;
+		u = x;
+		while ( u >= 3.0 ) {
+			p -= 1.0;
+			u = x + p;
+			z *= u;
+		}
+		while ( u < 2.0 ) {
+			if ( u == 0.0 )
+				goto lgsing;
+			z /= u;
+			p += 1.0;
+			u = x + p;
+		}
+		if ( z < 0.0 ) {
+			sgngam = -1;
+			z = -z;
+		}
+		else
+			sgngam = 1;
+		if ( u == 2.0 )
+			return( log(z) );
+		p -= 2.0;
+		x = x + p;
+		p = x * cephes_polevl( x, (double *)B, 5 ) / cephes_p1evl( x, (double *)C, 6);
+
+		return log(z) + p;
+	}
+
+	if ( x > MAXLGM ) {
+loverf:
+		printf("lgam: OVERFLOW\n");
+
+		return sgngam * MAXNUM;
+	}
+
+	q = ( x - 0.5 ) * log(x) - x + log( sqrt( 2*PI ) );
+	if ( x > 1.0e8 )
+		return q;
+
+	p = 1.0/(x*x);
+	if ( x >= 1000.0 )
+		q += ((   7.9365079365079365079365e-4 * p
+		        - 2.7777777777777777777778e-3) *p
+				+ 0.0833333333333333333333) / x;
+	else
+		q += cephes_polevl( p, (double *)A, 4 ) / x;
+
+	return q;
+}
+
+double
+cephes_polevl(double x, double *coef, int N)
+{
+	double	ans;
+	int		i;
+	double	*p;
+
+	p = coef;
+	ans = *p++;
+	i = N;
+
+	do
+		ans = ans * x  +  *p++;
+	while ( --i );
+
+	return ans;
+}
+
+double
+cephes_p1evl(double x, double *coef, int N)
+{
+	double	ans;
+	double	*p;
+	int		i;
+
+	p = coef;
+	ans = x + *p++;
+	i = N-1;
+
+	do
+		ans = ans * x  + *p++;
+	while ( --i );
+
+	return ans;
+}
+
+double
+cephes_erf(double x)
+{
+	static const double two_sqrtpi = 1.128379167095512574;
+	double	sum = x, term = x, xsqr = x * x;
+	int		j = 1;
+
+	if ( fabs(x) > 2.2 )
+		return 1.0 - cephes_erfc(x);
+
+	do {
+		term *= xsqr/j;
+		sum -= term/(2*j+1);
+		j++;
+		term *= xsqr/j;
+		sum += term/(2*j+1);
+		j++;
+	} while ( fabs(term)/sum > rel_error );
+
+	return two_sqrtpi*sum;
+}
+
+double
+cephes_erfc(double x)
+{
+	static const double one_sqrtpi = 0.564189583547756287;
+	double	a = 1, b = x, c = x, d = x*x + 0.5;
+	double	q1, q2 = b/d, n = 1.0, t;
+
+	if ( fabs(x) < 2.2 )
+		return 1.0 - cephes_erf(x);
+	if ( x < 0 )
+		return 2.0 - cephes_erfc(-x);
+
+	do {
+		t = a*n + b*x;
+		a = b;
+		b = t;
+		t = c*n + d*x;
+		c = d;
+		d = t;
+		n += 0.5;
+		q1 = q2;
+		q2 = b/d;
+	} while ( fabs(q1-q2)/q2 > rel_error );
+
+	return one_sqrtpi*exp(-x*x)*q2;
+}
+
+
+double
+cephes_normal(double x)
+{
+	double arg, result, sqrt2=1.414213562373095048801688724209698078569672;
+
+	if (x > 0) {
+		arg = x/sqrt2;
+		result = 0.5 * ( 1 + erf(arg) );
+	}
+	else {
+		arg = -x/sqrt2;
+		result = 0.5 * ( 1 - erf(arg) );
+	}
+
+	return( result);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/cusum.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,109 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+		    C U M U L A T I V E  S U M S  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+CumulativeSums(int n)
+{
+	int	   S, sup, inf;
+	int    z = 0;
+	int    zrev = 0;
+	int    k;
+	double	sum1, sum2, p_value;
+
+	S = 0;
+	sup = 0;
+	inf = 0;
+	for ( k=0; k<n; k++ ) {
+		epsilon[k] ? S++ : S--;
+		if ( S > sup )
+			sup++;
+		if ( S < inf )
+			inf--;
+		z = (sup > -inf) ? sup : -inf;
+		zrev = (sup-S > S-inf) ? sup-S : S-inf;
+	}
+	
+	// forward
+	sum1 = 0.0;
+	for ( k=(-n/z+1)/4; k<=(n/z-1)/4; k++ ) {
+		sum1 += cephes_normal(((4*k+1)*z)/sqrt(n));
+		sum1 -= cephes_normal(((4*k-1)*z)/sqrt(n));
+	}
+	sum2 = 0.0;
+	for ( k=(-n/z-3)/4; k<=(n/z-1)/4; k++ ) {
+		sum2 += cephes_normal(((4*k+3)*z)/sqrt(n));
+		sum2 -= cephes_normal(((4*k+1)*z)/sqrt(n));
+	}
+
+	p_value = 1.0 - sum1 + sum2;
+	
+	fprintf(stats[TEST_CUSUM], "\t\t      CUMULATIVE SUMS (FORWARD) TEST\n");
+	fprintf(stats[TEST_CUSUM], "\t\t-------------------------------------------\n");
+	fprintf(stats[TEST_CUSUM], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_CUSUM], "\t\t-------------------------------------------\n");
+	fprintf(stats[TEST_CUSUM], "\t\t(a) The maximum partial sum = %d\n", z);
+	fprintf(stats[TEST_CUSUM], "\t\t-------------------------------------------\n");
+
+	if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+		fprintf(stats[TEST_CUSUM], "\t\tWARNING:  P_VALUE IS OUT OF RANGE\n");
+
+	fprintf(stats[TEST_CUSUM], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_CUSUM], "%f\n", p_value);
+		
+	// backwards
+	sum1 = 0.0;
+	for ( k=(-n/zrev+1)/4; k<=(n/zrev-1)/4; k++ ) {
+		sum1 += cephes_normal(((4*k+1)*zrev)/sqrt(n));
+		sum1 -= cephes_normal(((4*k-1)*zrev)/sqrt(n));
+	}
+	sum2 = 0.0;
+	for ( k=(-n/zrev-3)/4; k<=(n/zrev-1)/4; k++ ) {
+		sum2 += cephes_normal(((4*k+3)*zrev)/sqrt(n));
+		sum2 -= cephes_normal(((4*k+1)*zrev)/sqrt(n));
+	}
+	p_value = 1.0 - sum1 + sum2;
+
+	fprintf(stats[TEST_CUSUM], "\t\t      CUMULATIVE SUMS (REVERSE) TEST\n");
+	fprintf(stats[TEST_CUSUM], "\t\t-------------------------------------------\n");
+	fprintf(stats[TEST_CUSUM], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_CUSUM], "\t\t-------------------------------------------\n");
+	fprintf(stats[TEST_CUSUM], "\t\t(a) The maximum partial sum = %d\n", zrev);
+	fprintf(stats[TEST_CUSUM], "\t\t-------------------------------------------\n");
+
+	if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+		fprintf(stats[TEST_CUSUM], "\t\tWARNING:  P_VALUE IS OUT OF RANGE\n");
+
+	fprintf(stats[TEST_CUSUM], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_CUSUM], "%f\n", p_value);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/dfft.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,1399 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original of this file was released into the public domain, see below for details
+*/
+
+
+/* Notes from RFB: 
+
+   Looks like the user-level routines are:
+
+   Real FFT
+
+   void __ogg_fdrffti(int n, double *wsave, int *ifac)
+   void __ogg_fdrfftf(int n,double *r,double *wsave,int *ifac)
+   void __ogg_fdrfftb(int n, double *r, double *wsave, int *ifac)
+
+     __ogg_fdrffti == initialization
+     __ogg_fdrfftf == forward transform
+     __ogg_fdrfftb == backward transform
+
+     Parameters are
+     n == length of sequence
+     r == sequence to be transformed (input)
+       == transformed sequence (output)
+     wsave == work array of length 2n (allocated by caller)
+     ifac == work array of length 15 (allocated by caller)
+
+   Cosine quarter-wave FFT
+
+   void __ogg_fdcosqi(int n, double *wsave, int *ifac)
+   void __ogg_fdcosqf(int n,double *x,double *wsave,int *ifac)
+   void __ogg_fdcosqb(int n,double *x,double *wsave,int *ifac)
+*/
+
+/********************************************************************
+ *                                                                  *
+ * THIS FILE IS PART OF THE OggSQUISH SOFTWARE CODEC SOURCE CODE.   *
+ *                                                                  *
+ ********************************************************************
+
+  file: fft.c
+  function: Fast discrete Fourier and cosine transforms and inverses
+  author: Monty <xiphmont@mit.edu>
+  modifications by: Monty
+  last modification date: Jul 1 1996
+
+ ********************************************************************/
+
+/* These Fourier routines were originally based on the Fourier
+   routines of the same names from the NETLIB bihar and fftpack
+   fortran libraries developed by Paul N. Swarztrauber at the National
+   Center for Atmospheric Research in Boulder, CO USA.  They have been
+   reimplemented in C and optimized in a few ways for OggSquish. */
+
+/* As the original fortran libraries are public domain, the C Fourier
+   routines in this file are hereby released to the public domain as
+   well.  The C routines here produce output exactly equivalent to the
+   original fortran routines.  Of particular interest are the facts
+   that (like the original fortran), these routines can work on
+   arbitrary length vectors that need not be powers of two in
+   length. */
+
+#include "openc.h"
+#define STIN static
+
+static void drfti1(int n, double *wa, int *ifac){
+  static int ntryh[4] = { 4,2,3,5 };
+  static double tpi = 6.28318530717958647692528676655900577;
+  double arg,argh,argld,fi;
+  int ntry=0,i,j=-1;
+  int k1, l1, l2, ib;
+  int ld, ii, ip, is, nq, nr;
+  int ido, ipm, nfm1;
+  int nl=n;
+  int nf=0;
+
+ L101:
+  j++;
+  if (j < 4)
+    ntry=ntryh[j];
+  else
+    ntry+=2;
+
+ L104:
+  nq=nl/ntry;
+  nr=nl-ntry*nq;
+  if (nr!=0) goto L101;
+
+  nf++;
+  ifac[nf+1]=ntry;
+  nl=nq;
+  if(ntry!=2)goto L107;
+  if(nf==1)goto L107;
+
+  for (i=1;i<nf;i++){
+    ib=nf-i+1;
+    ifac[ib+1]=ifac[ib];
+  }
+  ifac[2] = 2;
+
+ L107:
+  if(nl!=1)goto L104;
+  ifac[0]=n;
+  ifac[1]=nf;
+  argh=tpi/n;
+  is=0;
+  nfm1=nf-1;
+  l1=1;
+
+  if(nfm1==0)return;
+
+  for (k1=0;k1<nfm1;k1++){
+    ip=ifac[k1+2];
+    ld=0;
+    l2=l1*ip;
+    ido=n/l2;
+    ipm=ip-1;
+
+    for (j=0;j<ipm;j++){
+      ld+=l1;
+      i=is;
+      argld=(double)ld*argh;
+      fi=0.;
+      for (ii=2;ii<ido;ii+=2){
+	fi+=1.;
+	arg=fi*argld;
+	wa[i++]=cos(arg);
+	wa[i++]=sin(arg);
+      }
+      is+=ido;
+    }
+    l1=l2;
+  }
+}
+
+void __ogg_fdrffti(int n, double *wsave, int *ifac){
+
+  if (n == 1) return;
+  drfti1(n, wsave+n, ifac);
+}
+
+void __ogg_fdcosqi(int n, double *wsave, int *ifac){
+  static double pih = 1.57079632679489661923132169163975;
+  static int k;
+  static double fk, dt;
+
+  dt=pih/n;
+  fk=0.;
+  for(k=0;k<n;k++){
+    fk+=1.;
+    wsave[k] = cos(fk*dt);
+  }
+
+  __ogg_fdrffti(n, wsave+n,ifac);
+}
+
+STIN void dradf2(int ido,int l1,double *cc,double *ch,double *wa1){
+  int i,k;
+  double ti2,tr2;
+  int t0,t1,t2,t3,t4,t5,t6;
+  
+  t1=0;
+  t0=(t2=l1*ido);
+  t3=ido<<1;
+  for(k=0;k<l1;k++){
+    ch[t1<<1]=cc[t1]+cc[t2];
+    ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
+    t1+=ido;
+    t2+=ido;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  t2=t0;
+  for(k=0;k<l1;k++){
+    t3=t2;
+    t4=(t1<<1)+(ido<<1);
+    t5=t1;
+    t6=t1+t1;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4-=2;
+      t5+=2;
+      t6+=2;
+      tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
+      ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
+      ch[t6]=cc[t5]+ti2;
+      ch[t4]=ti2-cc[t5];
+      ch[t6-1]=cc[t5-1]+tr2;
+      ch[t4-1]=cc[t5-1]-tr2;
+    }
+    t1+=ido;
+    t2+=ido;
+  }
+
+  if(ido%2==1)return;
+
+ L105:
+  t3=(t2=(t1=ido)-1);
+  t2+=t0;
+  for(k=0;k<l1;k++){
+    ch[t1]=-cc[t2];
+    ch[t1-1]=cc[t3];
+    t1+=ido<<1;
+    t2+=ido;
+    t3+=ido;
+  }
+}
+
+STIN void dradf4(int ido,int l1,double *cc,double *ch,double *wa1,
+	    double *wa2,double *wa3){
+  static double hsqt2 = .70710678118654752440084436210485;
+  int i,k,t0,t1,t2,t3,t4,t5,t6;
+  double ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
+  t0=l1*ido;
+  
+  t1=t0;
+  t4=t1<<1;
+  t2=t1+(t1<<1);
+  t3=0;
+
+  for(k=0;k<l1;k++){
+    tr1=cc[t1]+cc[t2];
+    tr2=cc[t3]+cc[t4];
+    ch[t5=t3<<2]=tr1+tr2;
+    ch[(ido<<2)+t5-1]=tr2-tr1;
+    ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
+    ch[t5]=cc[t2]-cc[t1];
+
+    t1+=ido;
+    t2+=ido;
+    t3+=ido;
+    t4+=ido;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  for(k=0;k<l1;k++){
+    t2=t1;
+    t4=t1<<2;
+    t5=(t6=ido<<1)+t4;
+    for(i=2;i<ido;i+=2){
+      t3=(t2+=2);
+      t4+=2;
+      t5-=2;
+
+      t3+=t0;
+      cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
+      ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
+      t3+=t0;
+      cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
+      ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
+      t3+=t0;
+      cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
+      ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
+
+      tr1=cr2+cr4;
+      tr4=cr4-cr2;
+      ti1=ci2+ci4;
+      ti4=ci2-ci4;
+      ti2=cc[t2]+ci3;
+      ti3=cc[t2]-ci3;
+      tr2=cc[t2-1]+cr3;
+      tr3=cc[t2-1]-cr3;
+
+      
+      ch[t4-1]=tr1+tr2;
+      ch[t4]=ti1+ti2;
+
+      ch[t5-1]=tr3-ti4;
+      ch[t5]=tr4-ti3;
+
+      ch[t4+t6-1]=ti4+tr3;
+      ch[t4+t6]=tr4+ti3;
+
+      ch[t5+t6-1]=tr2-tr1;
+      ch[t5+t6]=ti1-ti2;
+    }
+    t1+=ido;
+  }
+  if(ido%2==1)return;
+
+ L105:
+  
+  t2=(t1=t0+ido-1)+(t0<<1);
+  t3=ido<<2;
+  t4=ido;
+  t5=ido<<1;
+  t6=ido;
+
+  for(k=0;k<l1;k++){
+    ti1=-hsqt2*(cc[t1]+cc[t2]);
+    tr1=hsqt2*(cc[t1]-cc[t2]);
+    ch[t4-1]=tr1+cc[t6-1];
+    ch[t4+t5-1]=cc[t6-1]-tr1;
+    ch[t4]=ti1-cc[t1+t0];
+    ch[t4+t5]=ti1+cc[t1+t0];
+    t1+=ido;
+    t2+=ido;
+    t4+=t3;
+    t6+=ido;
+  }
+}
+
+STIN void dradfg(int ido,int ip,int l1,int idl1,double *cc,double *c1,
+			  double *c2,double *ch,double *ch2,double *wa){
+
+  static double tpi=6.28318530717958647692528676655900577;
+  int idij,ipph,i,j,k,l,ic,ik,is;
+  int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
+  double dc2,ai1,ai2,ar1,ar2,ds2;
+  int nbd;
+  double dcp,arg,dsp,ar1h,ar2h;
+  int idp2,ipp2;
+  
+  arg=tpi/(double)ip;
+  dcp=cos(arg);
+  dsp=sin(arg);
+  ipph=(ip+1)>>1;
+  ipp2=ip;
+  idp2=ido;
+  nbd=(ido-1)>>1;
+  t0=l1*ido;
+  t10=ip*ido;
+
+  if(ido==1)goto L119;
+  for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
+
+  t1=0;
+  for(j=1;j<ip;j++){
+    t1+=t0;
+    t2=t1;
+    for(k=0;k<l1;k++){
+      ch[t2]=c1[t2];
+      t2+=ido;
+    }
+  }
+
+  is=-ido;
+  t1=0;
+  if(nbd>l1){
+    for(j=1;j<ip;j++){
+      t1+=t0;
+      is+=ido;
+      t2= -ido+t1;
+      for(k=0;k<l1;k++){
+	idij=is-1;
+	t2+=ido;
+	t3=t2;
+	for(i=2;i<ido;i+=2){
+	  idij+=2;
+	  t3+=2;
+	  ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
+	  ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
+	}
+      }
+    }
+  }else{
+
+    for(j=1;j<ip;j++){
+      is+=ido;
+      idij=is-1;
+      t1+=t0;
+      t2=t1;
+      for(i=2;i<ido;i+=2){
+	idij+=2;
+	t2+=2;
+	t3=t2;
+	for(k=0;k<l1;k++){
+	  ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
+	  ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
+	  t3+=ido;
+	}
+      }
+    }
+  }
+
+  t1=0;
+  t2=ipp2*t0;
+  if(nbd<l1){
+    for(j=1;j<ipph;j++){
+      t1+=t0;
+      t2-=t0;
+      t3=t1;
+      t4=t2;
+      for(i=2;i<ido;i+=2){
+	t3+=2;
+	t4+=2;
+	t5=t3-ido;
+	t6=t4-ido;
+	for(k=0;k<l1;k++){
+	  t5+=ido;
+	  t6+=ido;
+	  c1[t5-1]=ch[t5-1]+ch[t6-1];
+	  c1[t6-1]=ch[t5]-ch[t6];
+	  c1[t5]=ch[t5]+ch[t6];
+	  c1[t6]=ch[t6-1]-ch[t5-1];
+	}
+      }
+    }
+  }else{
+    for(j=1;j<ipph;j++){
+      t1+=t0;
+      t2-=t0;
+      t3=t1;
+      t4=t2;
+      for(k=0;k<l1;k++){
+	t5=t3;
+	t6=t4;
+	for(i=2;i<ido;i+=2){
+	  t5+=2;
+	  t6+=2;
+	  c1[t5-1]=ch[t5-1]+ch[t6-1];
+	  c1[t6-1]=ch[t5]-ch[t6];
+	  c1[t5]=ch[t5]+ch[t6];
+	  c1[t6]=ch[t6-1]-ch[t5-1];
+	}
+	t3+=ido;
+	t4+=ido;
+      }
+    }
+  }
+
+L119:
+  for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
+
+  t1=0;
+  t2=ipp2*idl1;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1-ido;
+    t4=t2-ido;
+    for(k=0;k<l1;k++){
+      t3+=ido;
+      t4+=ido;
+      c1[t3]=ch[t3]+ch[t4];
+      c1[t4]=ch[t4]-ch[t3];
+    }
+  }
+
+  ar1=1.;
+  ai1=0.;
+  t1=0;
+  t2=ipp2*idl1;
+  t3=(ip-1)*idl1;
+  for(l=1;l<ipph;l++){
+    t1+=idl1;
+    t2-=idl1;
+    ar1h=dcp*ar1-dsp*ai1;
+    ai1=dcp*ai1+dsp*ar1;
+    ar1=ar1h;
+    t4=t1;
+    t5=t2;
+    t6=t3;
+    t7=idl1;
+
+    for(ik=0;ik<idl1;ik++){
+      ch2[t4++]=c2[ik]+ar1*c2[t7++];
+      ch2[t5++]=ai1*c2[t6++];
+    }
+
+    dc2=ar1;
+    ds2=ai1;
+    ar2=ar1;
+    ai2=ai1;
+
+    t4=idl1;
+    t5=(ipp2-1)*idl1;
+    for(j=2;j<ipph;j++){
+      t4+=idl1;
+      t5-=idl1;
+
+      ar2h=dc2*ar2-ds2*ai2;
+      ai2=dc2*ai2+ds2*ar2;
+      ar2=ar2h;
+
+      t6=t1;
+      t7=t2;
+      t8=t4;
+      t9=t5;
+      for(ik=0;ik<idl1;ik++){
+	ch2[t6++]+=ar2*c2[t8++];
+	ch2[t7++]+=ai2*c2[t9++];
+      }
+    }
+  }
+
+  t1=0;
+  for(j=1;j<ipph;j++){
+    t1+=idl1;
+    t2=t1;
+    for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
+  }
+
+  if(ido<l1)goto L132;
+
+  t1=0;
+  t2=0;
+  for(k=0;k<l1;k++){
+    t3=t1;
+    t4=t2;
+    for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
+    t1+=ido;
+    t2+=t10;
+  }
+
+  goto L135;
+
+ L132:
+  for(i=0;i<ido;i++){
+    t1=i;
+    t2=i;
+    for(k=0;k<l1;k++){
+      cc[t2]=ch[t1];
+      t1+=ido;
+      t2+=t10;
+    }
+  }
+
+ L135:
+  t1=0;
+  t2=ido<<1;
+  t3=0;
+  t4=ipp2*t0;
+  for(j=1;j<ipph;j++){
+
+    t1+=t2;
+    t3+=t0;
+    t4-=t0;
+
+    t5=t1;
+    t6=t3;
+    t7=t4;
+
+    for(k=0;k<l1;k++){
+      cc[t5-1]=ch[t6];
+      cc[t5]=ch[t7];
+      t5+=t10;
+      t6+=ido;
+      t7+=ido;
+    }
+  }
+
+  if(ido==1)return;
+  if(nbd<l1)goto L141;
+
+  t1=-ido;
+  t3=0;
+  t4=0;
+  t5=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t2;
+    t3+=t2;
+    t4+=t0;
+    t5-=t0;
+    t6=t1;
+    t7=t3;
+    t8=t4;
+    t9=t5;
+    for(k=0;k<l1;k++){
+      for(i=2;i<ido;i+=2){
+	ic=idp2-i;
+	cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
+	cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
+	cc[i+t7]=ch[i+t8]+ch[i+t9];
+	cc[ic+t6]=ch[i+t9]-ch[i+t8];
+      }
+      t6+=t10;
+      t7+=t10;
+      t8+=ido;
+      t9+=ido;
+    }
+  }
+  return;
+
+ L141:
+
+  t1=-ido;
+  t3=0;
+  t4=0;
+  t5=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t2;
+    t3+=t2;
+    t4+=t0;
+    t5-=t0;
+    for(i=2;i<ido;i+=2){
+      t6=idp2+t1-i;
+      t7=i+t3;
+      t8=i+t4;
+      t9=i+t5;
+      for(k=0;k<l1;k++){
+	cc[t7-1]=ch[t8-1]+ch[t9-1];
+	cc[t6-1]=ch[t8-1]-ch[t9-1];
+	cc[t7]=ch[t8]+ch[t9];
+	cc[t6]=ch[t9]-ch[t8];
+	t6+=t10;
+	t7+=t10;
+	t8+=ido;
+	t9+=ido;
+      }
+    }
+  }
+}
+
+STIN void drftf1(int n,double *c,double *ch,double *wa,int *ifac){
+  int i,k1,l1,l2;
+  int na,kh,nf;
+  int ip,iw,ido,idl1,ix2,ix3;
+
+  nf=ifac[1];
+  na=1;
+  l2=n;
+  iw=n;
+
+  for(k1=0;k1<nf;k1++){
+    kh=nf-k1;
+    ip=ifac[kh+1];
+    l1=l2/ip;
+    ido=n/l2;
+    idl1=ido*l1;
+    iw-=(ip-1)*ido;
+    na=1-na;
+
+    if(ip!=4)goto L102;
+
+    ix2=iw+ido;
+    ix3=ix2+ido;
+    if(na!=0)
+      dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    else
+      dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    goto L110;
+
+ L102:
+    if(ip!=2)goto L104;
+    if(na!=0)goto L103;
+
+    dradf2(ido,l1,c,ch,wa+iw-1);
+    goto L110;
+
+  L103:
+    dradf2(ido,l1,ch,c,wa+iw-1);
+    goto L110;
+
+  L104:
+    if(ido==1)na=1-na;
+    if(na!=0)goto L109;
+
+    dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
+    na=1;
+    goto L110;
+
+  L109:
+    dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
+    na=0;
+
+  L110:
+    l2=l1;
+  }
+
+  if(na==1)return;
+
+  for(i=0;i<n;i++)c[i]=ch[i];
+}
+
+void __ogg_fdrfftf(int n,double *r,double *wsave,int *ifac){
+  if(n==1)return;
+  drftf1(n,r,wsave,wsave+n,ifac);
+}
+
+STIN void dcsqf1(int n,double *x,double *w,double *xh,int *ifac){
+  int modn,i,k,kc;
+  int np2,ns2;
+  double xim1;
+
+  ns2=(n+1)>>1;
+  np2=n;
+
+  kc=np2;
+  for(k=1;k<ns2;k++){
+    kc--;
+    xh[k]=x[k]+x[kc];
+    xh[kc]=x[k]-x[kc];
+  }
+
+  modn=n%2;
+  if(modn==0)xh[ns2]=x[ns2]+x[ns2];
+
+  for(k=1;k<ns2;k++){
+    kc=np2-k;
+    x[k]=w[k-1]*xh[kc]+w[kc-1]*xh[k];
+    x[kc]=w[k-1]*xh[k]-w[kc-1]*xh[kc];
+  }
+
+  if(modn==0)x[ns2]=w[ns2-1]*xh[ns2];
+
+  __ogg_fdrfftf(n,x,xh,ifac);
+
+  for(i=2;i<n;i+=2){
+    xim1=x[i-1]-x[i];
+    x[i]=x[i-1]+x[i];
+    x[i-1]=xim1;
+  }
+}
+
+void __ogg_fdcosqf(int n,double *x,double *wsave,int *ifac){
+    static double sqrt2=1.4142135623730950488016887242097;
+    double tsqx;
+
+  switch(n){
+  case 0:case 1:
+    return;
+  case 2:
+    tsqx=sqrt2*x[1];
+    x[1]=x[0]-tsqx;
+    x[0]+=tsqx;
+    return;
+  default:
+    dcsqf1(n,x,wsave,wsave+n,ifac);
+    return;
+  }
+}
+
+STIN void dradb2(int ido,int l1,double *cc,double *ch,double *wa1){
+  int i,k,t0,t1,t2,t3,t4,t5,t6;
+  double ti2,tr2;
+
+  t0=l1*ido;
+  
+  t1=0;
+  t2=0;
+  t3=(ido<<1)-1;
+  for(k=0;k<l1;k++){
+    ch[t1]=cc[t2]+cc[t3+t2];
+    ch[t1+t0]=cc[t2]-cc[t3+t2];
+    t2=(t1+=ido)<<1;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  t2=0;
+  for(k=0;k<l1;k++){
+    t3=t1;
+    t5=(t4=t2)+(ido<<1);
+    t6=t0+t1;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4+=2;
+      t5-=2;
+      t6+=2;
+      ch[t3-1]=cc[t4-1]+cc[t5-1];
+      tr2=cc[t4-1]-cc[t5-1];
+      ch[t3]=cc[t4]-cc[t5];
+      ti2=cc[t4]+cc[t5];
+      ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
+      ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
+    }
+    t2=(t1+=ido)<<1;
+  }
+
+  if(ido%2==1)return;
+
+L105:
+  t1=ido-1;
+  t2=ido-1;
+  for(k=0;k<l1;k++){
+    ch[t1]=cc[t2]+cc[t2];
+    ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
+    t1+=ido;
+    t2+=ido<<1;
+  }
+}
+
+STIN void dradb3(int ido,int l1,double *cc,double *ch,double *wa1,
+			  double *wa2){
+  static double taur = -.5;
+  static double taui = .86602540378443864676372317075293618;
+  int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
+  double ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
+  t0=l1*ido;
+
+  t1=0;
+  t2=t0<<1;
+  t3=ido<<1;
+  t4=ido+(ido<<1);
+  t5=0;
+  for(k=0;k<l1;k++){
+    tr2=cc[t3-1]+cc[t3-1];
+    cr2=cc[t5]+(taur*tr2);
+    ch[t1]=cc[t5]+tr2;
+    ci3=taui*(cc[t3]+cc[t3]);
+    ch[t1+t0]=cr2-ci3;
+    ch[t1+t2]=cr2+ci3;
+    t1+=ido;
+    t3+=t4;
+    t5+=t4;
+  }
+
+  if(ido==1)return;
+
+  t1=0;
+  t3=ido<<1;
+  for(k=0;k<l1;k++){
+    t7=t1+(t1<<1);
+    t6=(t5=t7+t3);
+    t8=t1;
+    t10=(t9=t1+t0)+t0;
+
+    for(i=2;i<ido;i+=2){
+      t5+=2;
+      t6-=2;
+      t7+=2;
+      t8+=2;
+      t9+=2;
+      t10+=2;
+      tr2=cc[t5-1]+cc[t6-1];
+      cr2=cc[t7-1]+(taur*tr2);
+      ch[t8-1]=cc[t7-1]+tr2;
+      ti2=cc[t5]-cc[t6];
+      ci2=cc[t7]+(taur*ti2);
+      ch[t8]=cc[t7]+ti2;
+      cr3=taui*(cc[t5-1]-cc[t6-1]);
+      ci3=taui*(cc[t5]+cc[t6]);
+      dr2=cr2-ci3;
+      dr3=cr2+ci3;
+      di2=ci2+cr3;
+      di3=ci2-cr3;
+      ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
+      ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
+      ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
+      ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
+    }
+    t1+=ido;
+  }
+}
+
+STIN void dradb4(int ido,int l1,double *cc,double *ch,double *wa1,
+			  double *wa2,double *wa3){
+  static double sqrt2=1.4142135623730950488016887242097;
+  int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
+  double ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
+  t0=l1*ido;
+  
+  t1=0;
+  t2=ido<<2;
+  t3=0;
+  t6=ido<<1;
+  for(k=0;k<l1;k++){
+    t4=t3+t6;
+    t5=t1;
+    tr3=cc[t4-1]+cc[t4-1];
+    tr4=cc[t4]+cc[t4]; 
+    tr1=cc[t3]-cc[(t4+=t6)-1];
+    tr2=cc[t3]+cc[t4-1];
+    ch[t5]=tr2+tr3;
+    ch[t5+=t0]=tr1-tr4;
+    ch[t5+=t0]=tr2-tr3;
+    ch[t5+=t0]=tr1+tr4;
+    t1+=ido;
+    t3+=t2;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  for(k=0;k<l1;k++){
+    t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
+    t7=t1;
+    for(i=2;i<ido;i+=2){
+      t2+=2;
+      t3+=2;
+      t4-=2;
+      t5-=2;
+      t7+=2;
+      ti1=cc[t2]+cc[t5];
+      ti2=cc[t2]-cc[t5];
+      ti3=cc[t3]-cc[t4];
+      tr4=cc[t3]+cc[t4];
+      tr1=cc[t2-1]-cc[t5-1];
+      tr2=cc[t2-1]+cc[t5-1];
+      ti4=cc[t3-1]-cc[t4-1];
+      tr3=cc[t3-1]+cc[t4-1];
+      ch[t7-1]=tr2+tr3;
+      cr3=tr2-tr3;
+      ch[t7]=ti2+ti3;
+      ci3=ti2-ti3;
+      cr2=tr1-tr4;
+      cr4=tr1+tr4;
+      ci2=ti1+ti4;
+      ci4=ti1-ti4;
+
+      ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
+      ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
+      ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
+      ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
+      ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
+      ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
+    }
+    t1+=ido;
+  }
+
+  if(ido%2 == 1)return;
+
+ L105:
+
+  t1=ido;
+  t2=ido<<2;
+  t3=ido-1;
+  t4=ido+(ido<<1);
+  for(k=0;k<l1;k++){
+    t5=t3;
+    ti1=cc[t1]+cc[t4];
+    ti2=cc[t4]-cc[t1];
+    tr1=cc[t1-1]-cc[t4-1];
+    tr2=cc[t1-1]+cc[t4-1];
+    ch[t5]=tr2+tr2;
+    ch[t5+=t0]=sqrt2*(tr1-ti1);
+    ch[t5+=t0]=ti2+ti2;
+    ch[t5+=t0]=-sqrt2*(tr1+ti1);
+
+    t3+=ido;
+    t1+=t2;
+    t4+=t2;
+  }
+}
+
+STIN void dradbg(int ido,int ip,int l1,int idl1,double *cc,double *c1,
+	    double *c2,double *ch,double *ch2,double *wa){
+  static double tpi=6.28318530717958647692528676655900577;
+  int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
+      t11,t12;
+  double dc2,ai1,ai2,ar1,ar2,ds2;
+  int nbd;
+  double dcp,arg,dsp,ar1h,ar2h;
+  int ipp2;
+
+  t10=ip*ido;
+  t0=l1*ido;
+  arg=tpi/(double)ip;
+  dcp=cos(arg);
+  dsp=sin(arg);
+  nbd=(ido-1)>>1;
+  ipp2=ip;
+  ipph=(ip+1)>>1;
+  if(ido<l1)goto L103;
+  
+  t1=0;
+  t2=0;
+  for(k=0;k<l1;k++){
+    t3=t1;
+    t4=t2;
+    for(i=0;i<ido;i++){
+      ch[t3]=cc[t4];
+      t3++;
+      t4++;
+    }
+    t1+=ido;
+    t2+=t10;
+  }
+  goto L106;
+
+ L103:
+  t1=0;
+  for(i=0;i<ido;i++){
+    t2=t1;
+    t3=t1;
+    for(k=0;k<l1;k++){
+      ch[t2]=cc[t3];
+      t2+=ido;
+      t3+=t10;
+    }
+    t1++;
+  }
+
+ L106:
+  t1=0;
+  t2=ipp2*t0;
+  t7=(t5=ido<<1);
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    t6=t5;
+    for(k=0;k<l1;k++){
+      ch[t3]=cc[t6-1]+cc[t6-1];
+      ch[t4]=cc[t6]+cc[t6];
+      t3+=ido;
+      t4+=ido;
+      t6+=t10;
+    }
+    t5+=t7;
+  }
+
+  if (ido == 1)goto L116;
+  if(nbd<l1)goto L112;
+
+  t1=0;
+  t2=ipp2*t0;
+  t7=0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+
+    t7+=(ido<<1);
+    t8=t7;
+    for(k=0;k<l1;k++){
+      t5=t3;
+      t6=t4;
+      t9=t8;
+      t11=t8;
+      for(i=2;i<ido;i+=2){
+	t5+=2;
+	t6+=2;
+	t9+=2;
+	t11-=2;
+	ch[t5-1]=cc[t9-1]+cc[t11-1];
+	ch[t6-1]=cc[t9-1]-cc[t11-1];
+	ch[t5]=cc[t9]-cc[t11];
+	ch[t6]=cc[t9]+cc[t11];
+      }
+      t3+=ido;
+      t4+=ido;
+      t8+=t10;
+    }
+  }
+  goto L116;
+
+ L112:
+  t1=0;
+  t2=ipp2*t0;
+  t7=0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    t7+=(ido<<1);
+    t8=t7;
+    t9=t7;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4+=2;
+      t8+=2;
+      t9-=2;
+      t5=t3;
+      t6=t4;
+      t11=t8;
+      t12=t9;
+      for(k=0;k<l1;k++){
+	ch[t5-1]=cc[t11-1]+cc[t12-1];
+	ch[t6-1]=cc[t11-1]-cc[t12-1];
+	ch[t5]=cc[t11]-cc[t12];
+	ch[t6]=cc[t11]+cc[t12];
+	t5+=ido;
+	t6+=ido;
+	t11+=t10;
+	t12+=t10;
+      }
+    }
+  }
+
+L116:
+  ar1=1.;
+  ai1=0.;
+  t1=0;
+  t9=(t2=ipp2*idl1);
+  t3=(ip-1)*idl1;
+  for(l=1;l<ipph;l++){
+    t1+=idl1;
+    t2-=idl1;
+
+    ar1h=dcp*ar1-dsp*ai1;
+    ai1=dcp*ai1+dsp*ar1;
+    ar1=ar1h;
+    t4=t1;
+    t5=t2;
+    t6=0;
+    t7=idl1;
+    t8=t3;
+    for(ik=0;ik<idl1;ik++){
+      c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
+      c2[t5++]=ai1*ch2[t8++];
+    }
+    dc2=ar1;
+    ds2=ai1;
+    ar2=ar1;
+    ai2=ai1;
+
+    t6=idl1;
+    t7=t9-idl1;
+    for(j=2;j<ipph;j++){
+      t6+=idl1;
+      t7-=idl1;
+      ar2h=dc2*ar2-ds2*ai2;
+      ai2=dc2*ai2+ds2*ar2;
+      ar2=ar2h;
+      t4=t1;
+      t5=t2;
+      t11=t6;
+      t12=t7;
+      for(ik=0;ik<idl1;ik++){
+	c2[t4++]+=ar2*ch2[t11++];
+	c2[t5++]+=ai2*ch2[t12++];
+      }
+    }
+  }
+
+  t1=0;
+  for(j=1;j<ipph;j++){
+    t1+=idl1;
+    t2=t1;
+    for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
+  }
+
+  t1=0;
+  t2=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    for(k=0;k<l1;k++){
+      ch[t3]=c1[t3]-c1[t4];
+      ch[t4]=c1[t3]+c1[t4];
+      t3+=ido;
+      t4+=ido;
+    }
+  }
+
+  if(ido==1)goto L132;
+  if(nbd<l1)goto L128;
+
+  t1=0;
+  t2=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    for(k=0;k<l1;k++){
+      t5=t3;
+      t6=t4;
+      for(i=2;i<ido;i+=2){
+	t5+=2;
+	t6+=2;
+	ch[t5-1]=c1[t5-1]-c1[t6];
+	ch[t6-1]=c1[t5-1]+c1[t6];
+	ch[t5]=c1[t5]+c1[t6-1];
+	ch[t6]=c1[t5]-c1[t6-1];
+      }
+      t3+=ido;
+      t4+=ido;
+    }
+  }
+  goto L132;
+
+ L128:
+  t1=0;
+  t2=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4+=2;
+      t5=t3;
+      t6=t4;
+      for(k=0;k<l1;k++){
+	ch[t5-1]=c1[t5-1]-c1[t6];
+	ch[t6-1]=c1[t5-1]+c1[t6];
+	ch[t5]=c1[t5]+c1[t6-1];
+	ch[t6]=c1[t5]-c1[t6-1];
+	t5+=ido;
+	t6+=ido;
+      }
+    }
+  }
+
+L132:
+  if(ido==1)return;
+
+  for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
+
+  t1=0;
+  for(j=1;j<ip;j++){
+    t2=(t1+=t0);
+    for(k=0;k<l1;k++){
+      c1[t2]=ch[t2];
+      t2+=ido;
+    }
+  }
+
+  if(nbd>l1)goto L139;
+
+  is= -ido-1;
+  t1=0;
+  for(j=1;j<ip;j++){
+    is+=ido;
+    t1+=t0;
+    idij=is;
+    t2=t1;
+    for(i=2;i<ido;i+=2){
+      t2+=2;
+      idij+=2;
+      t3=t2;
+      for(k=0;k<l1;k++){
+	c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
+	c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
+	t3+=ido;
+      }
+    }
+  }
+  return;
+
+ L139:
+  is= -ido-1;
+  t1=0;
+  for(j=1;j<ip;j++){
+    is+=ido;
+    t1+=t0;
+    t2=t1;
+    for(k=0;k<l1;k++){
+      idij=is;
+      t3=t2;
+      for(i=2;i<ido;i+=2){
+	idij+=2;
+	t3+=2;
+	c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
+	c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
+      }
+      t2+=ido;
+    }
+  }
+}
+
+STIN void drftb1(int n, double *c, double *ch, double *wa, int *ifac){
+  int i,k1,l1,l2;
+  int na;
+  int nf,ip,iw,ix2,ix3,ido,idl1;
+
+  nf=ifac[1];
+  na=0;
+  l1=1;
+  iw=1;
+
+  for(k1=0;k1<nf;k1++){
+    ip=ifac[k1 + 2];
+    l2=ip*l1;
+    ido=n/l2;
+    idl1=ido*l1;
+    if(ip!=4)goto L103;
+    ix2=iw+ido;
+    ix3=ix2+ido;
+
+    if(na!=0)
+      dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    else
+      dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    na=1-na;
+    goto L115;
+
+  L103:
+    if(ip!=2)goto L106;
+
+    if(na!=0)
+      dradb2(ido,l1,ch,c,wa+iw-1);
+    else
+      dradb2(ido,l1,c,ch,wa+iw-1);
+    na=1-na;
+    goto L115;
+
+  L106:
+    if(ip!=3)goto L109;
+
+    ix2=iw+ido;
+    if(na!=0)
+      dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
+    else
+      dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
+    na=1-na;
+    goto L115;
+
+  L109:
+/*    The radix five case can be translated later..... */
+/*    if(ip!=5)goto L112;
+
+    ix2=iw+ido;
+    ix3=ix2+ido;
+    ix4=ix3+ido;
+    if(na!=0)
+      dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
+    else
+      dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
+    na=1-na;
+    goto L115;
+
+  L112:*/
+    if(na!=0)
+      dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
+    else
+      dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
+    if(ido==1)na=1-na;
+
+  L115:
+    l1=l2;
+    iw+=(ip-1)*ido;
+  }
+
+  if(na==0)return;
+
+  for(i=0;i<n;i++)c[i]=ch[i];
+}
+
+void __ogg_fdrfftb(int n, double *r, double *wsave, int *ifac){
+  if (n == 1)return;
+  drftb1(n, r, wsave, wsave+n, ifac);
+}
+
+STIN void dcsqb1(int n,double *x,double *w,double *xh,int *ifac){
+  int modn,i,k,kc;
+  int np2,ns2;
+  double xim1;
+
+  ns2=(n+1)>>1;
+  np2=n;
+
+  for(i=2;i<n;i+=2){
+    xim1=x[i-1]+x[i];
+    x[i]-=x[i-1];
+    x[i-1]=xim1;
+  }
+
+  x[0]+=x[0];
+  modn=n%2;
+  if(modn==0)x[n-1]+=x[n-1];
+
+  __ogg_fdrfftb(n,x,xh,ifac);
+
+  kc=np2;
+  for(k=1;k<ns2;k++){
+    kc--;
+    xh[k]=w[k-1]*x[kc]+w[kc-1]*x[k];
+    xh[kc]=w[k-1]*x[k]-w[kc-1]*x[kc];
+  }
+
+  if(modn==0)x[ns2]=w[ns2-1]*(x[ns2]+x[ns2]);
+
+  kc=np2;
+  for(k=1;k<ns2;k++){
+    kc--;
+    x[k]=xh[k]+xh[kc];
+    x[kc]=xh[k]-xh[kc];
+  }
+  x[0]+=x[0];
+}
+
+void __ogg_fdcosqb(int n,double *x,double *wsave,int *ifac){
+  static double tsqrt2 = 2.8284271247461900976033774484194;
+  double x1;
+
+  if(n<2){
+    x[0]*=4;
+    return;
+  }
+  if(n==2){
+    x1=(x[0]+x[1])*4;
+    x[1]=tsqrt2*(x[0]-x[1]);
+    x[0]=x1;
+    return;
+  }
+  
+  dcsqb1(n,x,wsave,wsave+n,ifac);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/discretefouriertransform.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,102 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/cephes.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+         D I S C R E T E  F O U R I E R  T R A N S F O R M  T E S T 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+void  __ogg_fdrffti(int n, double* wsave, int* ifac);
+void  __ogg_fdrfftf(int n, double* X, double* wsave, int* ifac);
+
+void
+DiscreteFourierTransform(int n)
+{
+	double     p_value, upperBound, percentile, N_l, N_o, d;
+	double*    m = NULL;
+	double*    X = NULL;
+	double*    wsave = NULL;
+	int*       ifac = NULL;
+	int		i, count;
+	
+	if ( ((X = (double*) calloc(n,sizeof(double))) == NULL) ||
+		 ((wsave = (double *)calloc(2*n+15,sizeof(double))) == NULL) ||
+		 ((ifac = (int *)calloc(15,sizeof(int))) == NULL) ||
+		 ((m = (double*)calloc(n/2+1, sizeof(double))) == NULL) ) {
+			fprintf(stats[7],"\t\tUnable to allocate working arrays for the DFT.\n");
+			if( X != NULL )
+				free(X);
+			if( wsave != NULL )
+				free(wsave);
+			if( ifac != NULL )
+				free(ifac);
+			if( m != NULL )
+				free(m);
+			return;
+	}
+	for ( i=0; i<n; i++ )
+		X[i] = 2*(int)epsilon[i] - 1;
+	
+	__ogg_fdrffti(n, wsave, ifac);		/* INITIALIZE WORK ARRAYS */
+	__ogg_fdrfftf(n, X, wsave, ifac);	/* APPLY FORWARD FFT */
+	
+	m[0] = sqrt(X[0]*X[0]);	    /* COMPUTE MAGNITUDE */
+	
+	for ( i=0; i<n/2; i++ ) {	   	    /* DISPLAY FOURIER POINTS */
+		m[i+1] = sqrt(pow(X[2*i+1],2)+pow(X[2*i+2],2)); 
+	}
+	count = 0;				       /* CONFIDENCE INTERVAL */
+	upperBound = sqrt(2.995732274*n);
+	for ( i=0; i<n/2; i++ )
+		if ( m[i] < upperBound )
+			count++;
+	percentile = (double)count/(n/2)*100;
+	N_l = (double) count;       /* number of peaks less than h = sqrt(3*n) */
+	N_o = (double) 0.95*n/2.0;
+	d = (N_l - N_o)/sqrt(n/2.0*0.95*0.05);
+	p_value = erfc(fabs(d)/sqrt(2.0));
+
+	fprintf(stats[TEST_FFT], "\t\t\t\tFFT TEST\n");
+	fprintf(stats[TEST_FFT], "\t\t-------------------------------------------\n");
+	fprintf(stats[TEST_FFT], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_FFT], "\t\t-------------------------------------------\n");
+	fprintf(stats[TEST_FFT], "\t\t(a) Percentile = %f\n", percentile);
+	fprintf(stats[TEST_FFT], "\t\t(b) N_l        = %f\n", N_l);
+	fprintf(stats[TEST_FFT], "\t\t(c) N_o        = %f\n", N_o);
+	fprintf(stats[TEST_FFT], "\t\t(d) d          = %f\n", d);
+	fprintf(stats[TEST_FFT], "\t\t-------------------------------------------\n");
+
+	fprintf(stats[TEST_FFT], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_FFT], "%f\n", p_value);
+
+	free(X);
+	free(wsave);
+	free(ifac);
+	free(m);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/frequency.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,57 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                          F R E Q U E N C Y  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+Frequency(int n)
+{
+	int		i;
+	double	f, s_obs, p_value, sum, sqrt2 = 1.41421356237309504880;
+	
+	sum = 0.0;
+	for ( i=0; i<n; i++ )
+		sum += 2*(int)epsilon[i]-1;
+	s_obs = fabs(sum)/sqrt(n);
+	f = s_obs/sqrt2;
+	p_value = erfc(f);
+
+	fprintf(stats[TEST_FREQUENCY], "\t\t\t      FREQUENCY TEST\n");
+	fprintf(stats[TEST_FREQUENCY], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_FREQUENCY], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_FREQUENCY], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_FREQUENCY], "\t\t(a) The nth partial sum = %d\n", (int)sum);
+	fprintf(stats[TEST_FREQUENCY], "\t\t(b) S_n/n               = %f\n", sum/n);
+	fprintf(stats[TEST_FREQUENCY], "\t\t---------------------------------------------\n");
+
+	fprintf(stats[TEST_FREQUENCY], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_FREQUENCY], "%f\n", p_value);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/generators.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,510 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/generators.h"
+#include "../include/genutils.h"
+
+const int KRandomByteCount = 1024;
+
+double
+lcg_rand(int N, double SEED, double* DUNIF, int NDIM)
+{
+	int    i;
+	double	DZ, DOVER, DZ1, DZ2, DOVER1, DOVER2;
+	double	DTWO31, DMDLS, DA1, DA2;
+
+	DTWO31 = 2147483648.0; /* DTWO31=2**31  */
+	DMDLS  = 2147483647.0; /* DMDLS=2**31-1 */
+	DA1 = 41160.0;       /* DA1=950706376 MOD 2**16 */
+	DA2 = 950665216.0;   /* DA2=950706376-DA1 */
+
+	DZ = SEED;
+	if ( N > NDIM )
+		N = NDIM;
+	for ( i=1; i<=N; i++ ) {
+		DZ = floor(DZ);
+		DZ1 = DZ*DA1;
+		DZ2 = DZ*DA2;
+		DOVER1 = floor(DZ1/DTWO31);
+		DOVER2 = floor(DZ2/DTWO31);
+		DZ1 = DZ1-DOVER1*DTWO31;
+		DZ2 = DZ2-DOVER2*DTWO31;
+		DZ = DZ1+DZ2+DOVER1+DOVER2;
+		DOVER = floor(DZ/DMDLS);
+		DZ = DZ-DOVER*DMDLS;
+		DUNIF[i-1] = DZ/DMDLS;
+		SEED = DZ;
+	}
+
+	return SEED;
+}
+
+void
+lcg()
+{
+	double*    DUNIF = NULL;
+	double     SEED;
+	int		i;
+	unsigned bit;
+	int		num_0s, num_1s, v, bitsRead;
+
+	SEED = 23482349.0;
+	if ( ((epsilon = (BitSequence *) calloc(tp.n, sizeof(BitSequence))) == NULL) ||
+	     ((DUNIF = (double*)calloc(tp.n, sizeof(double))) == NULL) ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	 
+	for ( v=0; v<tp.numOfBitStreams; v++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		SEED = lcg_rand(tp.n, SEED, DUNIF, tp.n);
+		for ( i=0; i<tp.n; i++ ) {
+			if ( DUNIF[i] < 0.5 ) {
+				bit = 0;
+				num_0s++;
+			}
+			else {
+				bit = 1;
+				num_1s++;
+			}
+			bitsRead++;
+			epsilon[i] = (BitSequence)bit;
+		}
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+		}
+	free(DUNIF);
+	free(epsilon);
+}
+
+
+void
+quadRes1()
+{
+	int		k, num_0s, num_1s, bitsRead, done;
+	BYTE	p[64], g[64], x[128];
+	
+	if ( ((epsilon = (BitSequence *)calloc(tp.n, sizeof(BitSequence))) == NULL) ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	ahtopb("987b6a6bf2c56a97291c445409920032499f9ee7ad128301b5d0254aa1a9633fdbd378d40149f1e23a13849f3d45992f5c4c6b7104099bc301f6005f9d8115e1", p, 64);
+	ahtopb("3844506a9456c564b8b8538e0cc15aff46c95e69600f084f0657c2401b3c244734b62ea9bb95be4923b9b7e84eeaf1a224894ef0328d44bc3eb3e983644da3f5", g, 64);
+	num_0s = 0;
+	num_1s = 0;
+	done = 0;
+	bitsRead = 0;
+	for ( k=0; k<tp.numOfBitStreams; k++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		done = 0;
+		bitsRead = 0;
+		do {
+			memset(x, 0x00, 128);
+			ModMult(x, g, 64, g, 64, p,64);
+			memcpy(g, x+64, 64);
+			done = convertToBits(g, 512, tp.n, &num_0s, &num_1s, &bitsRead);
+		} while ( !done );
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+
+	return;
+}
+
+void
+quadRes2()
+{
+	BYTE	g[64], x[129], t1[65];
+	BYTE	One[1], Two, Three[1];
+	int		k, num_0s, num_1s, bitsRead, done;
+	
+	if ( ((epsilon = (BitSequence *)calloc(tp.n, sizeof(BitSequence))) == NULL) ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	One[0] = 0x01;
+	Two = 0x02;
+	Three[0] = 0x03;
+
+	ahtopb("7844506a9456c564b8b8538e0cc15aff46c95e69600f084f0657c2401b3c244734b62ea9bb95be4923b9b7e84eeaf1a224894ef0328d44bc3eb3e983644da3f5", g, 64);
+	
+	for( k=0; k<tp.numOfBitStreams; k++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		done = 0;
+		bitsRead = 0;
+		do {
+			memset(t1, 0x00, 65);
+			memset(x, 0x00, 129);
+			smult(t1, Two, g, 64);		/* 2x */
+			add(t1, 65, Three, 1);		/* 2x+3 */
+			Mult(x, t1, 65, g, 64);		/* x(2x+3) */
+			add(x, 129, One, 1);		/* x(2x+3)+1 */
+			memcpy(g, x+65, 64);
+			done = convertToBits(g, 512, tp.n, &num_0s, &num_1s, &bitsRead);
+		} while ( !done) ;
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+
+	return;
+}
+
+void
+cubicRes()
+{
+	BYTE	g[64], tmp[128], x[192];
+	int		k, num_0s, num_1s, bitsRead, done;
+	
+	if ( ((epsilon = (BitSequence *)calloc(tp.n, sizeof(BitSequence))) == NULL) ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	
+	ahtopb("7844506a9456c564b8b8538e0cc15aff46c95e69600f084f0657c2401b3c244734b62ea9bb95be4923b9b7e84eeaf1a224894ef0328d44bc3eb3e983644da3f5", g, 64);
+
+	for ( k=0; k<tp.numOfBitStreams; k++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		done = 0;
+		do {
+			memset(tmp, 0x00, 128);
+			memset(x, 0x00, 192);
+			Mult(tmp, g, 64, g, 64);
+			Mult(x, tmp, 128, g, 64); // Don't need to mod by 2^512, just take low 64 bytes
+			memcpy(g, x+128, 64);
+			done = convertToBits(g, 512, tp.n, &num_0s, &num_1s, &bitsRead);
+		} while ( !done );
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+
+	return;
+}
+
+void
+exclusiveOR()
+{
+	int		i, num_0s, num_1s, bitsRead;
+	BYTE	bit_sequence[127];
+	
+	if ( ((epsilon = (BitSequence *)calloc(tp.n,sizeof(BitSequence))) == NULL) ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+
+	memcpy(bit_sequence, "0001011011011001000101111001001010011011101101000100000010101111111010100100001010110110000000000100110000101110011111111100111", 127);
+	num_0s = 0;
+	num_1s = 0;
+	bitsRead = 0;
+	for (i=0; i<127; i++ ) {
+		if ( bit_sequence[i]  ) {
+			epsilon[bitsRead] = 1;
+			num_1s++;
+		}
+		else {
+			epsilon[bitsRead] = 0;
+			num_1s++;
+		}
+		bitsRead++;
+	}
+	for ( i=127; i<tp.n*tp.numOfBitStreams; i++ ) {
+		if ( bit_sequence[(i-1)%127] != bit_sequence[(i-127)%127] ) {
+			bit_sequence[i%127] = 1;
+			epsilon[bitsRead] = 1;
+			num_1s++;
+		}
+		else {
+			bit_sequence[i%127] = 0;
+			epsilon[bitsRead] = 0;
+			num_0s++;
+		}
+		bitsRead++;
+		if ( bitsRead == tp.n ) {
+			fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+			nist_test_suite();
+			num_0s = 0;
+			num_1s = 0;
+			bitsRead = 0;
+		}
+	}
+	free(epsilon);
+		
+	return;
+}
+
+
+void
+modExp()
+{
+	int		k, num_0s, num_1s, bitsRead, done;
+	BYTE	p[64], g[64], x[192], y[20];
+
+	if ( (epsilon = (BitSequence *)calloc(tp.n, sizeof(BitSequence))) == NULL ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	ahtopb("7AB36982CE1ADF832019CDFEB2393CABDF0214EC", y, 20);
+	ahtopb("987b6a6bf2c56a97291c445409920032499f9ee7ad128301b5d0254aa1a9633fdbd378d40149f1e23a13849f3d45992f5c4c6b7104099bc301f6005f9d8115e1", p, 64);
+	ahtopb("3844506a9456c564b8b8538e0cc15aff46c95e69600f084f0657c2401b3c244734b62ea9bb95be4923b9b7e84eeaf1a224894ef0328d44bc3eb3e983644da3f5", g, 64);
+
+	for ( k=0; k<tp.numOfBitStreams; k++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		done = 0;
+		do {
+			memset(x, 0x00, 128);
+			ModExp(x, g, 64, y, 20, p, 64);	      /* NOTE:  g must be less than p */
+			done = convertToBits(x, 512, tp.n, &num_0s, &num_1s, &bitsRead);
+			memcpy(y, x+44, 20);
+			} while ( !done );
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+
+	return;
+}
+
+void
+bbs()
+{
+	int		i, v, bitsRead;
+	BYTE	p[64], q[64], n[128], s[64], x[256];
+	int		num_0s, num_1s;
+
+	if ( (epsilon = (BitSequence*)calloc(tp.n, sizeof(BitSequence))) == NULL ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	ahtopb("E65097BAEC92E70478CAF4ED0ED94E1C94B154466BFB9EC9BE37B2B0FF8526C222B76E0E915017535AE8B9207250257D0A0C87C0DACEF78E17D1EF9DC44FD91F", p, 64);
+	ahtopb("E029AEFCF8EA2C29D99CB53DD5FA9BC1D0176F5DF8D9110FD16EE21F32E37BA86FF42F00531AD5B8A43073182CC2E15F5C86E8DA059E346777C9A985F7D8A867", q, 64);
+	memset(n, 0x00, 128);
+	Mult(n, p, 64, q, 64);
+	memset(s, 0x00, 64);
+	ahtopb("10d6333cfac8e30e808d2192f7c0439480da79db9bbca1667d73be9a677ed31311f3b830937763837cb7b1b1dc75f14eea417f84d9625628750de99e7ef1e976", s, 64);
+	memset(x, 0x00, 256);
+	ModSqr(x, s, 64, n, 128);
+ 
+	for ( v=0; v<tp.numOfBitStreams; v++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		for ( i=0; i<tp.n; i++ ) {
+			ModSqr(x, x, 128, n, 128);
+			memcpy(x, x+128, 128);
+			if ( (x[127] & 0x01) == 0 ) {
+				num_0s++;
+				epsilon[i] = 0;
+			}
+			else {
+				num_1s++;
+				epsilon[i] = 1;
+			}
+			bitsRead++;
+			if ( (i % 50000) == 0 )
+				printf("\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		}
+
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+}
+
+
+// The exponent, e, is set to 11
+// This results in k = 837 and r = 187
+void
+micali_schnorr()
+{
+	long	i, j;
+	int		k=837, num_0s, num_1s, bitsRead, done;
+	BYTE	p[64], q[64], n[128], e[1], X[128], Y[384], Tail[105];
+
+	if ( (epsilon = (BitSequence *)calloc(tp.n, sizeof(BitSequence))) == NULL ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+	ahtopb("E65097BAEC92E70478CAF4ED0ED94E1C94B154466BFB9EC9BE37B2B0FF8526C222B76E0E915017535AE8B9207250257D0A0C87C0DACEF78E17D1EF9DC44FD91F", p, 64);
+	ahtopb("E029AEFCF8EA2C29D99CB53DD5FA9BC1D0176F5DF8D9110FD16EE21F32E37BA86FF42F00531AD5B8A43073182CC2E15F5C86E8DA059E346777C9A985F7D8A867", q, 64);
+	memset(n, 0x00, 128);
+	Mult(n, p, 64, q, 64);
+	e[0] = 0x0b;
+	memset(X, 0x00, 128);
+	ahtopb("237c5f791c2cfe47bfb16d2d54a0d60665b20904ec822a6", X+104, 24);
+
+	for ( i=0; i<tp.numOfBitStreams; i++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		do {
+			ModExp(Y, X, 128, e, 1, n, 128);
+			memcpy(Tail, Y+23, 105);
+			for ( j=0; j<3; j++ )
+				bshl(Tail, 105);
+			done = convertToBits(Tail, k, tp.n, &num_0s, &num_1s, &bitsRead);
+			memset(X, 0x00, 128);
+			memcpy(X+104, Y, 24);
+			for ( j=0; j<5; j++ )
+				bshr(X+104, 24);
+		} while ( !done );
+
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+}
+
+//  Uses 160 bit Xkey and no XSeed (b=160)
+//  This is the generic form of the generator found on the last page of the Change Notice for FIPS 186-2
+void
+SHA1()
+{
+	ULONG	A, B, C, D, E, temp, Wbuff[16];
+	BYTE	Xkey[20], G[20], M[64];
+	BYTE	One[1] = { 0x01 };
+	int		i, num_0s, num_1s, bitsRead;
+	int		done;
+	ULONG	tx[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };
+	
+	if ( ((epsilon = (BitSequence *) calloc(tp.n,sizeof(BitSequence))) == NULL) ) {
+		printf("Insufficient memory available.\n");
+		exit(1);
+	}
+
+	ahtopb("ec822a619d6ed5d9492218a7a4c5b15d57c61601", Xkey, 20);
+	
+	for ( i=0; i<tp.numOfBitStreams; i++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		do {
+			memcpy(M, Xkey, 20);
+			memset(M+20, 0x00, 44);
+			
+			// Start: SHA Steps A-E
+			A = tx[0];
+			B = tx[1];
+			C = tx[2];
+			D = tx[3];
+			E = tx[4];
+
+			memcpy((BYTE *)Wbuff, M, 64);
+#ifdef LITTLE_ENDIAN
+			byteReverse(Wbuff, 20);
+#endif
+			sub1Round1( 0 );  sub1Round1( 1 );  sub1Round1( 2 );  sub1Round1( 3 );
+			sub1Round1( 4 );  sub1Round1( 5 );  sub1Round1( 6 );  sub1Round1( 7 );
+			sub1Round1( 8 );  sub1Round1( 9 );  sub1Round1( 10 ); sub1Round1( 11 );
+			sub1Round1( 12 ); sub1Round1( 13 ); sub1Round1( 14 ); sub1Round1( 15 );
+			sub2Round1( 16 ); sub2Round1( 17 ); sub2Round1( 18 ); sub2Round1( 19 );
+			Round2( 20 ); Round2( 21 ); Round2( 22 ); Round2( 23 );
+			Round2( 24 ); Round2( 25 ); Round2( 26 ); Round2( 27 );
+			Round2( 28 ); Round2( 29 ); Round2( 30 ); Round2( 31 );
+			Round2( 32 ); Round2( 33 ); Round2( 34 ); Round2( 35 );
+			Round2( 36 ); Round2( 37 ); Round2( 38 ); Round2( 39 );
+			Round3( 40 ); Round3( 41 ); Round3( 42 ); Round3( 43 );
+			Round3( 44 ); Round3( 45 ); Round3( 46 ); Round3( 47 );
+			Round3( 48 ); Round3( 49 ); Round3( 50 ); Round3( 51 );
+			Round3( 52 ); Round3( 53 ); Round3( 54 ); Round3( 55 );
+			Round3( 56 ); Round3( 57 ); Round3( 58 ); Round3( 59 );
+			Round4( 60 ); Round4( 61 ); Round4( 62 ); Round4( 63 );
+			Round4( 64 ); Round4( 65 ); Round4( 66 ); Round4( 67 );
+			Round4( 68 ); Round4( 69 ); Round4( 70 ); Round4( 71 );
+			Round4( 72 ); Round4( 73 ); Round4( 74 ); Round4( 75 );
+			Round4( 76 ); Round4( 77 ); Round4( 78 ); Round4( 79 );
+			
+			A += tx[0];
+			B += tx[1];
+			C += tx[2];
+			D += tx[3];
+			E += tx[4];
+			
+			memcpy(G, (BYTE *)&A, 4);
+			memcpy(G+4, (BYTE *)&B, 4);
+			memcpy(G+8, (BYTE *)&C, 4);
+			memcpy(G+12, (BYTE *)&D, 4);
+			memcpy(G+16, (BYTE *)&E, 4);
+#ifdef LITTLE_ENDIAN
+			byteReverse((ULONG *)G, 20);
+#endif
+			// End: SHA Steps A-E
+
+			done = convertToBits(G, 160, tp.n, &num_0s, &num_1s, &bitsRead);
+			add(Xkey, 20, G, 20);
+			add(Xkey, 20, One, 1);
+		} while ( !done );
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+}
+
+void HASH_DRBG()
+    {
+    int     done = 0;
+    int     num_0s = 0;
+    int     num_1s = 0;
+    int     bitsRead = 0;
+
+    if ( ((epsilon = (BitSequence *) calloc(tp.n,sizeof(BitSequence))) == NULL) ) {
+        printf("Insufficient memory available.\n");
+        exit(1);
+    }
+    
+    TBuf8<KRandomByteCount> randBuffer(KRandomByteCount);
+
+    for (int i = 0; i < tp.numOfBitStreams; ++i) 
+        {
+        gConsole->Printf(_L("Starting test %d\n"), i+1);
+        num_0s = 0;
+        num_1s = 0;
+        bitsRead = 0;
+        done = 0;
+        do 
+            {
+            Math::Random(randBuffer);
+            done = convertToBits(randBuffer.Ptr() , KRandomByteCount*8, tp.n, &num_0s, &num_1s, &bitsRead);
+            } while ( !done );
+        fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+        
+        nist_test_suite();
+        }
+        free(epsilon);
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/genutils.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,693 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/*
+ * file: mp.c
+ *
+ * DESCRIPTION
+ *
+ * These functions comprise a multi-precision integer arithmetic
+ * and discrete function package.
+ */
+
+#include	"../include/genutils.h"
+
+#define	MAXPLEN		384
+
+
+/*****************************************
+** greater - Test if x > y               *
+**                                       *
+** Returns TRUE (1) if x greater than y, *
+** otherwise FALSE (0).                  *
+**                                       *
+** Parameters:                           *
+**                                       *
+**  x      Address of array x            *
+**  y      Address of array y            *
+**  l      Length both x and y in bytes  *
+**                                       *
+******************************************/ 
+int greater(BYTE *x, BYTE *y, int l)
+{
+	int		i;
+
+	for ( i=0; i<l; i++ )
+		if ( x[i] != y[i] )
+			break;
+
+	if ( i == l )
+		return 0;
+
+	if ( x[i] > y[i] )
+		return 1;
+
+	return 0;
+}
+
+
+/*****************************************
+** less - Test if x < y                  *
+**                                       *
+** Returns TRUE (1) if x less than y,    *
+** otherwise FALSE (0).                  *
+**                                       *
+** Parameters:                           *
+**                                       *
+**  x      Address of array x            *
+**  y      Address of array y            *
+**  l      Length both x and y in bytes  *
+**                                       *
+******************************************/ 
+int less(BYTE *x, BYTE *y, int l)
+{
+	int		i;
+
+	for ( i=0; i<l; i++ )
+		if ( x[i] != y[i] )
+			break;
+
+	if ( i == l ) {
+		return 0;
+	}
+
+	if ( x[i] < y[i] ) {
+		return 1;
+	}
+
+	return 0;
+}
+
+
+/*****************************************
+** bshl - shifts array left              *
+**                  by one bit.          *
+**                                       *	
+** x = x * 2                             *
+**                                       *
+** Parameters:                           *	
+**                                       *
+**  x      Address of array x            *
+**  l      Length array x in bytes       *
+**                                       *
+******************************************/ 
+BYTE bshl(BYTE *x, int l)
+{
+	BYTE	*p;
+	int		c1, c2;
+
+	p = x + l - 1;
+	c1 = 0;
+	c2 = 0;
+	while ( p != x ) {
+		if ( *p & 0x80 )
+			c2 = 1;
+		*p <<= 1;  /* shift the word left once (ls bit = 0) */
+		if ( c1 )
+			*p |= 1;
+		c1 = c2;
+		c2 = 0;
+		p--;
+	}
+
+	if ( *p & 0x80 )
+		c2 = 1;
+	*p <<= 1;  /* shift the word left once (ls bit = 0) */
+	if ( c1 )
+		*p |= (DIGIT)1;
+
+	return (BYTE)c2;
+}
+
+
+/*****************************************
+** bshr - shifts array right             *
+**                   by one bit.         *
+**                                       *	
+** x = x / 2                             *
+**                                       *
+** Parameters:                           *	
+**                                       *
+**  x      Address of array x            *
+**  l      Length array x in bytes       *	
+**                                       *
+******************************************/
+void bshr(BYTE *x, int l)	
+{
+	BYTE	*p;
+	int		c1,c2;
+
+	p = x;
+	c1 = 0;
+	c2 = 0;
+	while ( p != x+l-1 ) {
+		if ( *p & 0x01 )
+			c2 = 1;
+		*p >>= 1;  /* shift the word right once (ms bit = 0) */
+		if ( c1 )
+			*p |= 0x80;
+		c1 = c2;
+		c2 = 0;
+		p++;
+	}
+
+	*p >>= 1;  /* shift the word right once (ms bit = 0) */
+	if ( c1 )
+		*p |= 0x80;
+}
+
+
+/*****************************************
+** Mult - Multiply two integers          *
+**                                       *
+** A = B * C                             *
+**                                       *
+** Parameters:                           *	
+**                                       *
+**  A      Address of the result         *
+**  B      Address of the multiplier     *
+**  C      Address of the multiplicand   *
+**  LB      Length of B in bytes         *
+**  LC      Length of C in bytes         *
+**                                       *
+**  NOTE:  A MUST be LB+LC in length     *
+**                                       *
+******************************************/
+int Mult(BYTE *A, BYTE *B, int LB, BYTE *C, int LC)
+{
+	int    i, j;
+	int    k = 0;
+	DIGIT	result;
+
+
+	for ( i=LB-1; i>=0; i-- ) {
+		result = 0;
+		for ( j=LC-1; j>=0; j-- ) {
+			k = i+j+1;
+			result = (DIGIT)((DIGIT)A[k] + ((DIGIT)(B[i] * C[j])) + (result >> 8));
+			A[k] = (BYTE)result;
+			}
+		A[--k] = (BYTE)(result >> 8);
+	}
+
+	return 0;
+}
+
+
+void ModSqr(BYTE *A, BYTE *B, int LB, BYTE *M, int LM)
+{
+
+	Square(A, B, LB);
+	Mod(A, 2*LB, M, LM);
+}
+
+void ModMult(BYTE *A, BYTE *B, int LB, BYTE *C, int LC, BYTE *M, int LM)
+{
+	Mult(A, B, LB, C, LC);
+	Mod(A, (LB+LC), M, LM);
+}
+
+
+/*****************************************
+** smult - Multiply array by a scalar.   *
+**                                       *
+** A = b * C                             *
+**                                       *
+** Parameters:                           *	
+**                                       *
+**  A      Address of the result         *
+**  b      Scalar (1 BYTE)               *
+**  C      Address of the multiplicand   *
+**  L      Length of C in bytes          *
+**                                       *
+**  NOTE:  A MUST be L+1 in length       *
+**                                       *
+******************************************/
+void smult(BYTE *A, BYTE b, BYTE *C, int L)
+{
+	int		i;
+	DIGIT	result;
+
+	result = 0;
+	for ( i=L-1; i>0; i-- ) {
+		result = (DIGIT)(A[i] + ((DIGIT)b * C[i]) + (result >> 8));
+		A[i] = (BYTE)(result & 0xff);
+		A[i-1] = (BYTE)(result >> 8);
+	}
+}
+
+/*****************************************
+** Square() - Square an integer          *
+**                                       *
+** A = B^2                               *
+**                                       *
+** Parameters:                           *
+**                                       *
+**  A      Address of the result         *
+**  B      Address of the operand        *
+**  L      Length of B in bytes          *
+**                                       *
+**  NOTE:  A MUST be 2*L in length       *
+**                                       *
+******************************************/
+void Square(BYTE *A, BYTE *B, int L)
+{
+	Mult(A, B, L, B, L);
+}
+
+/*****************************************
+** ModExp - Modular Exponentiation       *
+**                                       *
+** A = B ** C (MOD M)                    *
+**                                       *	
+** Parameters:                           *	
+**                                       *
+**  A      Address of result             *
+**  B      Address of mantissa           *
+**  C      Address of exponent           *
+**  M      Address of modulus            *
+**  LB     Length of B in bytes          *
+**  LC     Length of C in bytes          *
+**  LM     Length of M in bytes          *
+**                                       *
+**  NOTE: The integer B must be less     *
+**        than the modulus M.      	 *
+**  NOTE: A must be at least 3*LM        *
+**        bytes long.  However, the      *
+**        result stored in A will be     *
+**        only LM bytes long.            *
+******************************************/
+void ModExp(BYTE *A, BYTE *B, int LB, BYTE *C, int LC, BYTE *M, int LM)
+{
+	BYTE	wmask;
+	int		bits;
+
+	bits = LC*8;
+	wmask = 0x80;
+
+	A[LM-1] = 1;
+
+	while ( !sniff_bit(C,wmask) ) {
+		wmask >>= 1;
+		bits--;
+		if ( !wmask ) {
+			wmask = 0x80;
+			C++;
+		}
+	}
+
+	while ( bits-- ) {
+		memset(A+LM, 0x00, LM*2);
+
+		/* temp = A*A (MOD M) */
+		ModSqr(A+LM, A,LM,  M,LM);
+
+		/* A = lower L bytes of temp */
+		memcpy(A, A+LM*2, LM);
+		memset(A+LM, 0x00, 2*LM);
+
+		if ( sniff_bit(C,wmask) ) {
+			memset(A+LM, 0x00, (LM+LB));
+			ModMult(A+LM, B,LB, A,LM,  M,LM);       /* temp = B * A (MOD M) */
+			memcpy(A, A+LM+(LM+LB)-LM, LM);  /* A = lower LM bytes of temp */
+			memset(A+LM, 0x00, 2*LM);
+		}
+ 
+		wmask >>= 1;
+		if ( !wmask ) {
+			wmask = 0x80;
+			C++;
+		}
+	}
+}
+
+
+/* DivMod:
+ *
+ *   computes:
+ *         quot = x / n
+ *         rem = x % n
+ *   returns:
+ *         length of "quot"
+ *
+ *  len of rem is lenx+1
+ */
+int DivMod(BYTE *x, int lenx, BYTE *n, int lenn, BYTE *quot, BYTE *rem)
+{
+	BYTE	*tx, *tn, *ttx, *ts, bmult[1];
+	int		i, shift, lgth_x, lgth_n, t_len, lenq;
+	DIGIT	tMSn, mult;
+	ULONG	tMSx;
+	int		underflow;
+
+	tx = x;
+	tn = n;
+	
+	/* point to the MSD of n  */
+	for ( i=0, lgth_n=lenn; i<lenn; i++, lgth_n-- ) {
+		if ( *tn )
+			break;
+		tn++;
+	}
+	if ( !lgth_n )
+		return 0;
+	
+	/* point to the MSD of x  */
+	for ( i=0, lgth_x=lenx; i<lenx; i++, lgth_x-- ) {
+		if ( *tx )
+			break;
+		tx++;
+	}
+	if ( !lgth_x )
+		return 0;
+
+	if ( lgth_x < lgth_n )
+		lenq = 1;
+	else
+		lenq = lgth_x - lgth_n + 1;
+	memset(quot, 0x00, lenq);
+	
+	/* Loop while x > n,  WATCH OUT if lgth_x == lgth_n */
+	while ( (lgth_x > lgth_n) || ((lgth_x == lgth_n) && !less(tx, tn, lgth_n)) ) {
+		shift = 1;
+		if ( lgth_n == 1 ) {
+			if ( *tx < *tn ) {
+				tMSx = (DIGIT) (((*tx) << 8) | *(tx+1));
+				tMSn = *tn;
+				shift = 0;
+			}
+			else {
+				tMSx = *tx;
+				tMSn = *tn;
+			}
+		}
+		else if ( lgth_n > 1 ) {
+			tMSx = (DIGIT) (((*tx) << 8) | *(tx+1));
+			tMSn = (DIGIT) (((*tn) << 8) | *(tn+1));
+			if ( (tMSx < tMSn) || ((tMSx == tMSn) && less(tx, tn, lgth_n)) ) {
+				tMSx = (tMSx << 8) | *(tx+2);
+				shift = 0;
+			}
+		}
+		else {
+			tMSx = (DIGIT) (((*tx) << 8) | *(tx+1));
+			tMSn = *tn;
+			shift = 0;
+		}
+
+		mult = (DIGIT) (tMSx / tMSn);
+		if ( mult > 0xff )
+			mult = 0xff;
+		bmult[0] = (BYTE)(mult & 0xff);
+
+		ts = rem;
+		do {
+			memset(ts, 0x00, lgth_x+1);
+			Mult(ts, tn, lgth_n, bmult, 1);
+
+			underflow = 0;
+			if ( shift ) {
+				if ( ts[0] != 0 )
+					underflow = 1;
+				else {
+					for ( i=0; i<lgth_x; i++ )
+						ts[i] = ts[i+1];
+					ts[lgth_x] = 0x00;
+				}
+			}
+			if ( greater(ts, tx, lgth_x) || underflow ) {
+				bmult[0]--;
+				underflow = 1;
+			}
+			else
+				underflow = 0;
+		} while ( underflow );
+		sub(tx, lgth_x, ts, lgth_x);
+		if ( shift )
+			quot[lenq - (lgth_x - lgth_n) - 1] = bmult[0];
+		else
+			quot[lenq - (lgth_x - lgth_n)] = bmult[0];
+		
+		ttx = tx;
+		t_len = lgth_x;
+		for ( i=0, lgth_x=t_len; i<t_len; i++, lgth_x-- ) {
+			if ( *ttx )
+				break;
+			ttx++;
+		}
+		tx = ttx;
+	}
+	memset(rem, 0x00, lenn);
+	if ( lgth_x )
+		memcpy(rem+lenn-lgth_x, tx, lgth_x);
+
+	return lenq;
+}
+
+
+/* 
+ * Mod - Computes an integer modulo another integer
+ *
+ * x = x (mod n)
+ *
+ */
+void Mod(BYTE *x, int lenx, BYTE *n, int lenn)
+{
+	BYTE	quot[MAXPLEN+1], rem[2*MAXPLEN+1];
+
+	memset(quot, 0x00, sizeof(quot));
+	memset(rem, 0x00, sizeof(rem));
+	if ( DivMod(x, lenx, n, lenn, quot, rem) ) {
+		memset(x, 0x00, lenx);
+		memcpy(x+lenx-lenn, rem, lenn);
+	}
+}
+
+/* 
+ * Div - Computes the integer division of two numbers
+ *
+ * x = x / n
+ *
+ */
+void Div(BYTE *x, int lenx, BYTE *n, int lenn)
+{
+	BYTE	quot[MAXPLEN+1], rem[2*MAXPLEN+1];
+	int		lenq;
+
+	memset(quot, 0x00, sizeof(quot));
+	memset(rem, 0x00, sizeof(rem));
+	if ( (lenq = DivMod(x, lenx, n, lenn, quot, rem)) != 0 ) {
+		memset(x, 0x00, lenx);
+		memcpy(x+lenx-lenq, quot, lenq);
+	}
+}
+
+
+/*****************************************
+** sub - Subtract two integers           *
+**                                       *
+** A = A - B                             *
+**                                       *
+**                                       *
+** Parameters:                           *	
+**                                       *
+**  A      Address of subtrahend integer *
+**  B      Address of subtractor integer *
+**  L      Length of A and B in bytes    *
+**                                       *
+**  NOTE: In order to save RAM, B is     *
+**        two's complemented twice,      *
+**        rather than using a copy of B  *
+**                                       *
+******************************************/
+void sub(BYTE *A, int LA, BYTE *B, int LB)
+{
+	BYTE	*tb;
+
+	tb = (BYTE *)calloc(LA, 1);
+	memcpy(tb, B, LB);
+	negate(tb, LB);
+	add(A, LA, tb, LA);
+
+	FREE(tb);
+}
+
+
+/*****************************************
+** negate - Negate an integer            *
+**                                       *
+** A = -A                                *
+**                                       *
+**                                       *
+** Parameters:                           *	
+**                                       *
+**  A      Address of integer to negate  *
+**  L      Length of A in bytes          *
+**                                       *
+******************************************/
+int negate(BYTE *A, int L)
+{
+	int		i, tL;
+	DIGIT	accum;
+
+	/* Take one's complement of A */
+	for ( i=0; i<L; i++ )
+		A[i] = (BYTE)(~(A[i]));
+
+	/* Add one to get two's complement of A */
+	accum = 1;
+	tL = L-1;
+	while ( accum && (tL >= 0) ) {
+		accum = (DIGIT)(accum + A[tL]);
+		A[tL--] = (BYTE)(accum & 0xff);
+		accum = (DIGIT)(accum >> 8);
+	}
+
+	return accum;
+}
+
+
+/*
+ * add()
+ *
+ * A = A + B
+ *
+ * LB must be <= LA
+ *
+ */
+BYTE add(BYTE *A, int LA, BYTE *B, int LB)
+{
+	int		i, indexA, indexB;
+	DIGIT	accum;
+
+	indexA = LA - 1; 	/* LSD of result */
+	indexB = LB - 1; 	/* LSD of B */
+
+	accum = 0;
+	for ( i = 0; i < LB; i++ ) {
+		accum = (DIGIT)(accum + A[indexA]);
+		accum = (DIGIT)(accum + B[indexB--]);
+		A[indexA--] = (BYTE)(accum & 0xff);
+		accum = (DIGIT)(accum >> 8);
+	}
+
+	if ( LA > LB )
+		while ( accum  && (indexA >= 0) ) {
+			accum = (DIGIT)(accum + A[indexA]);
+			A[indexA--] = (BYTE)(accum & 0xff);
+			accum = (DIGIT)(accum >> 8);
+		}
+
+	return (BYTE)accum;
+}
+
+
+void prettyprintBstr(char *S, BYTE *A, int L)
+{
+	int		i, extra, ctrb, ctrl;
+
+	if ( L == 0 )
+		printf("%s <empty>", S);
+	else
+		printf("%s\n\t", S);
+	extra = L % 24;
+	if ( extra ) {
+		ctrb = 0;
+		for ( i=0; i<24-extra; i++ ) {
+			printf("  ");
+			if ( ++ctrb == 4) {
+				printf(" ");
+				ctrb = 0;
+			}
+		}
+
+		for ( i=0; i<extra; i++ ) {
+			printf("%02X", A[i]);
+			if ( ++ctrb == 4) {
+				printf(" ");
+				ctrb = 0;
+			}
+		}
+		printf("\n\t");
+	}
+
+	ctrb = ctrl = 0;
+	for ( i=extra; i<L; i++ ) {
+		printf("%02X", A[i]);
+		if ( ++ctrb == 4) {
+			ctrl++;
+			if ( ctrl == 6 ) {
+				printf("\n\t");
+				ctrl = 0;
+			}
+			else
+				printf(" ");
+			ctrb = 0;
+		}
+	}
+	printf("\n\n");
+}
+
+
+/**********************************************************************/
+/*  Performs byte reverse for PC based implementation (little endian) */
+/**********************************************************************/
+void byteReverse(ULONG *buffer, int byteCount)
+{
+	ULONG value;
+	int count;
+
+	byteCount /= sizeof( ULONG );
+	for( count = 0; count < byteCount; count++ ) {
+		value = ( buffer[ count ] << 16 ) | ( buffer[ count ] >> 16 );
+		buffer[ count ] = ( ( value & 0xFF00FF00L ) >> 8 ) | ( ( value & 0x00FF00FFL ) << 8 );
+	}
+}
+
+void
+ahtopb (char *ascii_hex, BYTE *p_binary, int bin_len)
+{
+	BYTE    nibble;
+	int     i; 
+	
+	for ( i=0; i<bin_len; i++ ) {
+        nibble = ascii_hex[i * 2];
+	    if ( nibble > 'F' )
+	        nibble -= 0x20;   
+	    if ( nibble > '9' )
+	        nibble -= 7;      
+	    nibble -= '0';   
+	    p_binary[i] = (BYTE)(nibble << 4);
+		
+	    nibble = ascii_hex[i * 2 + 1];
+	    if ( nibble > 'F' )
+			nibble -= 0x20;
+        if ( nibble > '9' )
+            nibble -= 7;   
+        nibble -= '0';
+		p_binary[i] = (BYTE)(p_binary[i] + nibble);
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/linearcomplexity.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,153 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"  
+
+void
+LinearComplexity(int M, int n)
+{
+	int       i, ii, j, d, N, L, m, N_, sign, K = 6;
+	double    p_value, T_, mean, nu[7], chi2;
+	double    pi[7] = { 0.01047, 0.03125, 0.12500, 0.50000, 0.25000, 0.06250, 0.020833 };
+	BitSequence*   T = NULL;
+	BitSequence*   P = NULL;
+	BitSequence*   B_ = NULL;
+	BitSequence*   C = NULL;
+	
+	N = (int)floor(n/M);
+	if ( ((B_ = (BitSequence *) calloc(M, sizeof(BitSequence))) == NULL) ||
+		 ((C  = (BitSequence *) calloc(M, sizeof(BitSequence))) == NULL) ||
+		 ((P  = (BitSequence *) calloc(M, sizeof(BitSequence))) == NULL) ||
+		 ((T  = (BitSequence *) calloc(M, sizeof(BitSequence))) == NULL) ) {
+		printf("Insufficient Memory for Work Space:: Linear Complexity Test\n");
+		if ( B_!= NULL )
+			free(B_);
+		if ( C != NULL )
+			free(C);
+		if ( P != NULL )
+			free(P);
+		if ( T != NULL )
+			free(T);
+		return;
+	}
+
+
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "-----------------------------------------------------\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "\tL I N E A R  C O M P L E X I T Y\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "-----------------------------------------------------\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "\tM (substring length)     = %d\n", M);
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "\tN (number of substrings) = %d\n", N);
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "-----------------------------------------------------\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "        F R E Q U E N C Y                            \n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "-----------------------------------------------------\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "  C0   C1   C2   C3   C4   C5   C6    CHI2    P-value\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "-----------------------------------------------------\n");
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "\tNote: %d bits were discarded!\n", n%M);
+
+	for ( i=0; i<K+1; i++ )
+		nu[i] = 0.00;
+	for ( ii=0; ii<N; ii++ ) {
+		for ( i=0; i<M; i++ ) {
+			B_[i] = 0;
+			C[i] = 0;
+			T[i] = 0;
+			P[i] = 0;
+		}
+		L = 0;
+		m = -1;
+		d = 0;
+		C[0] = 1;
+		B_[0] = 1;
+		
+		/* DETERMINE LINEAR COMPLEXITY */
+		N_ = 0;
+		while ( N_ < M ) {
+			d = (int)epsilon[ii*M+N_];
+			for ( i=1; i<=L; i++ )
+				d += C[i] * epsilon[ii*M+N_-i];
+			d = d%2;
+			if ( d == 1 ) {
+				for ( i=0; i<M; i++ ) {
+					T[i] = C[i];
+					P[i] = 0;
+				}
+				for ( j=0; j<M; j++ )
+					if ( B_[j] == 1 )
+						P[j+N_-m] = 1;
+				for ( i=0; i<M; i++ )
+					C[i] = (BitSequence)((C[i] + P[i])%2);
+				if ( L <= N_/2 ) {
+					L = N_ + 1 - L;
+					m = N_;
+					for ( i=0; i<M; i++ )
+						B_[i] = T[i];
+				}
+			}
+			N_++;
+		}
+		if (((M+1)%2) == 0 ) 
+			sign = -1;
+		else 
+			sign = 1;
+		mean = M/2.0 + (9.0+sign)/36.0 - 1.0/pow(2, M) * (M/3.0 + 2.0/9.0);
+		if ( (M%2) == 0 )
+			sign = 1;
+		else 
+			sign = -1;
+		T_ = sign * (L - mean) + 2.0/9.0;
+		
+		if ( T_ <= -2.5 )
+			nu[0]++;
+		else if ( T_ > -2.5 && T_ <= -1.5 )
+			nu[1]++;
+		else if ( T_ > -1.5 && T_ <= -0.5 )
+			nu[2]++;
+		else if ( T_ > -0.5 && T_ <= 0.5 )
+			nu[3]++;
+		else if ( T_ > 0.5 && T_ <= 1.5 )
+			nu[4]++;
+		else if ( T_ > 1.5 && T_ <= 2.5 )
+			nu[5]++;
+		else
+			nu[6]++;
+	}
+	chi2 = 0.00;
+	for ( i=0; i<K+1; i++ ) 
+		fprintf(stats[TEST_LINEARCOMPLEXITY], "%4d ", (int)nu[i]);
+	for ( i=0; i<K+1; i++ )
+		chi2 += pow(nu[i]-N*pi[i], 2) / (N*pi[i]);
+	p_value = cephes_igamc(K/2.0, chi2/2.0);
+
+	fprintf(stats[TEST_LINEARCOMPLEXITY], "%9.6f%9.6f\n", chi2, p_value);
+	fprintf(results[TEST_LINEARCOMPLEXITY], "%f\n", p_value);
+
+	free(B_);
+	free(P);
+	free(C);
+	free(T);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/longestrunofones.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,142 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/* got rid of unused 'k' */
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"  
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                      L O N G E S T  R U N S  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+LongestRunOfOnes(int n)
+{
+	double			pval, chi2, pi[7];
+	int				run, v_n_obs, N, i, j, K, M, V[7];
+	unsigned int	nu[7] = { 0, 0, 0, 0, 0, 0, 0 };
+
+	if ( n < 128 ) {
+		fprintf(stats[TEST_LONGEST_RUN], "\t\t\t  LONGEST RUNS OF ONES TEST\n");
+		fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
+		fprintf(stats[TEST_LONGEST_RUN], "\t\t   n=%d is too short\n", n);
+		return;
+	}
+	if ( n < 6272 ) {
+		K = 3;
+		M = 8;
+		V[0] = 1; V[1] = 2; V[2] = 3; V[3] = 4;
+		pi[0] = 0.21484375;
+		pi[1] = 0.3671875;
+		pi[2] = 0.23046875;
+		pi[3] = 0.1875;
+	}
+	else if ( n < 750000 ) {
+		K = 5;
+		M = 128;
+		V[0] = 4; V[1] = 5; V[2] = 6; V[3] = 7; V[4] = 8; V[5] = 9;
+		pi[0] = 0.1174035788;
+		pi[1] = 0.242955959;
+		pi[2] = 0.249363483;
+		pi[3] = 0.17517706;
+		pi[4] = 0.102701071;
+		pi[5] = 0.112398847;
+	}
+	else {
+		K = 6;
+		M = 10000;
+			V[0] = 10; V[1] = 11; V[2] = 12; V[3] = 13; V[4] = 14; V[5] = 15; V[6] = 16;
+		pi[0] = 0.0882;
+		pi[1] = 0.2092;
+		pi[2] = 0.2483;
+		pi[3] = 0.1933;
+		pi[4] = 0.1208;
+		pi[5] = 0.0675;
+		pi[6] = 0.0727;
+	}
+	
+	N = n/M;
+	for ( i=0; i<N; i++ ) {
+		v_n_obs = 0;
+		run = 0;
+		for ( j=0; j<M; j++ ) {
+			if ( epsilon[i*M+j] == 1 ) {
+				run++;
+				if ( run > v_n_obs )
+					v_n_obs = run;
+			}
+			else
+				run = 0;
+		}
+		if ( v_n_obs < V[0] )
+			nu[0]++;
+		for ( j=0; j<=K; j++ ) {
+			if ( v_n_obs == V[j] )
+				nu[j]++;
+		}
+		if ( v_n_obs > V[K] )
+			nu[K]++;
+	}
+
+	chi2 = 0.0;
+	for ( i=0; i<=K; i++ )
+		chi2 += ((nu[i] - N * pi[i]) * (nu[i] - N * pi[i])) / (N * pi[i]);
+
+	pval = cephes_igamc((double)(K/2.0), chi2 / 2.0);
+
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t\t  LONGEST RUNS OF ONES TEST\n");
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_LONGEST_RUN], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t(a) N (# of substrings)  = %d\n", N);
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t(b) M (Substring Length) = %d\n", M);
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t(c) Chi^2                = %f\n", chi2);
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t      F R E Q U E N C Y\n");
+	fprintf(stats[TEST_LONGEST_RUN], "\t\t---------------------------------------------\n");
+
+	if ( K == 3 ) {
+		fprintf(stats[TEST_LONGEST_RUN], "\t\t  <=1     2     3    >=4   P-value  Assignment");
+		fprintf(stats[TEST_LONGEST_RUN], "\n\t\t %3d %3d %3d  %3d ", nu[0], nu[1], nu[2], nu[3]);
+	}
+	else if ( K == 5 ) {
+		fprintf(stats[TEST_LONGEST_RUN], "\t\t<=4  5  6  7  8  >=9 P-value  Assignment");
+		fprintf(stats[TEST_LONGEST_RUN], "\n\t\t %3d %3d %3d %3d %3d  %3d ", nu[0], nu[1], nu[2],
+				nu[3], nu[4], nu[5]);
+	}
+	else {
+		fprintf(stats[TEST_LONGEST_RUN],"\t\t<=10  11  12  13  14  15 >=16 P-value  Assignment");
+		fprintf(stats[TEST_LONGEST_RUN],"\n\t\t %3d %3d %3d %3d %3d %3d  %3d ", nu[0], nu[1], nu[2],
+				nu[3], nu[4], nu[5], nu[6]);
+	}
+	if ( isNegative(pval) || isGreaterThanOne(pval) )
+		fprintf(stats[TEST_LONGEST_RUN], "WARNING:  P_VALUE IS OUT OF RANGE.\n");
+
+	fprintf(stats[TEST_LONGEST_RUN], "%s\t\tp_value = %f\n\n", pval < ALPHA ? "FAILURE" : "SUCCESS", pval);
+	fprintf(results[TEST_LONGEST_RUN], "%f\n", pval);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/math/erf.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,355 @@
+/*
+* Portions Copyright (c) 2006, 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*/
+
+/* @(#)s_erf.c 5.1 93/09/24 */
+/*
+ * ====================================================
+ * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+ *
+ * Developed at SunPro, a Sun Microsystems, Inc. business.
+ * Permission to use, copy, modify, and distribute this
+ * software is freely granted, provided that this notice
+ * is preserved.
+ * ====================================================
+ */
+#ifndef __SYMBIAN32__
+#ifndef lint
+static char rcsid[] = "$FreeBSD: src/lib/msun/src/s_erf.c,v 1.7 2002/05/28 18:15:04 alfred Exp $";
+#endif
+#endif //__SYMBIAN32__
+
+#include <e32std.h>
+
+#include "openc.h"
+
+/* double erf(double x)
+ * double erfc(double x)
+ *               x
+ *            2      |\
+ *     erf(x)  =  ---------  | exp(-t*t)dt
+ *         sqrt(pi) \|
+ *               0
+ *
+ *     erfc(x) =  1-erf(x)
+ *  Note that
+ *      erf(-x) = -erf(x)
+ *      erfc(-x) = 2 - erfc(x)
+ *
+ * Method:
+ *  1. For |x| in [0, 0.84375]
+ *      erf(x)  = x + x*R(x^2)
+ *          erfc(x) = 1 - erf(x)           if x in [-.84375,0.25]
+ *                  = 0.5 + ((0.5-x)-x*R)  if x in [0.25,0.84375]
+ *     where R = P/Q where P is an odd poly of degree 8 and
+ *     Q is an odd poly of degree 10.
+ *                       -57.90
+ *          | R - (erf(x)-x)/x | <= 2
+ *
+ *
+ *     Remark. The formula is derived by noting
+ *          erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....)
+ *     and that
+ *          2/sqrt(pi) = 1.128379167095512573896158903121545171688
+ *     is close to one. The interval is chosen because the fix
+ *     point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is
+ *     near 0.6174), and by some experiment, 0.84375 is chosen to
+ *     guarantee the error is less than one ulp for erf.
+ *
+ *      2. For |x| in [0.84375,1.25], let s = |x| - 1, and
+ *         c = 0.84506291151 rounded to single (24 bits)
+ *          erf(x)  = sign(x) * (c  + P1(s)/Q1(s))
+ *          erfc(x) = (1-c)  - P1(s)/Q1(s) if x > 0
+ *            1+(c+P1(s)/Q1(s))    if x < 0
+ *          |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06
+ *     Remark: here we use the taylor series expansion at x=1.
+ *      erf(1+s) = erf(1) + s*Poly(s)
+ *           = 0.845.. + P1(s)/Q1(s)
+ *     That is, we use rational approximation to approximate
+ *          erf(1+s) - (c = (single)0.84506291151)
+ *     Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]
+ *     where
+ *      P1(s) = degree 6 poly in s
+ *      Q1(s) = degree 6 poly in s
+ *
+ *      3. For x in [1.25,1/0.35(~2.857143)],
+ *          erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)
+ *          erf(x)  = 1 - erfc(x)
+ *     where
+ *      R1(z) = degree 7 poly in z, (z=1/x^2)
+ *      S1(z) = degree 8 poly in z
+ *
+ *      4. For x in [1/0.35,28]
+ *          erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0
+ *          = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6<x<0
+ *          = 2.0 - tiny        (if x <= -6)
+ *          erf(x)  = sign(x)*(1.0 - erfc(x)) if x < 6, else
+ *          erf(x)  = sign(x)*(1.0 - tiny)
+ *     where
+ *      R2(z) = degree 6 poly in z, (z=1/x^2)
+ *      S2(z) = degree 7 poly in z
+ *
+ *      Note1:
+ *     To compute exp(-x*x-0.5625+R/S), let s be a single
+ *     precision number and s := x; then
+ *      -x*x = -s*s + (s-x)*(s+x)
+ *          exp(-x*x-0.5626+R/S) =
+ *          exp(-s*s-0.5625)*exp((s-x)*(s+x)+R/S);
+ *      Note2:
+ *     Here 4 and 5 make use of the asymptotic series
+ *            exp(-x*x)
+ *      erfc(x) ~ ---------- * ( 1 + Poly(1/x^2) )
+ *            x*sqrt(pi)
+ *     We use rational approximation to approximate
+ *          g(s)=f(1/x^2) = log(erfc(x)*x) - x*x + 0.5625
+ *     Here is the error bound for R1/S1 and R2/S2
+ *          |R1/S1 - f(x)|  < 2**(-62.57)
+ *          |R2/S2 - f(x)|  < 2**(-61.52)
+ *
+ *      5. For inf > x >= 28
+ *          erf(x)  = sign(x) *(1 - tiny)  (raise inexact)
+ *          erfc(x) = tiny*tiny (raise underflow) if x > 0
+ *          = 2 - tiny if x<0
+ *
+ *      7. Special case:
+ *          erf(0)  = 0, erf(inf)  = 1, erf(-inf) = -1,
+ *          erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,
+ *      erfc/erf(NaN) is NaN
+ */
+
+
+
+
+
+////--------------------------------------------------
+
+#define __ieee754_exp   exp
+typedef TUint32 u_int32_t;
+typedef TInt32 int32_t;
+
+typedef union
+    {
+    double value;
+    struct
+        {
+        u_int32_t lsw;
+        u_int32_t msw;
+        } parts;
+    } ieee_double_shape_type;
+
+
+inline void GET_HIGH_WORD(int32_t& aHighWord, double aValue)
+    {
+    ieee_double_shape_type gh_u;
+    gh_u.value = aValue;
+    aHighWord = gh_u.parts.msw;                  
+    }
+    
+inline void SET_LOW_WORD(double& aValue, int32_t aLowWord)
+    {
+    ieee_double_shape_type sl_u;
+    sl_u.value = aValue;
+    sl_u.parts.lsw = aLowWord;
+    aValue = sl_u.value;
+    }
+
+//----------------------------------------------------------------math_private.h
+
+static const double tiny    = 1e-300;
+static const double tinySquare    = 0.00; // tiny * tiny 
+static const double half    = 5.00000000000000000000e-01; /* 0x3FE00000, 0x00000000 */
+static const double one     = 1.00000000000000000000e+00; /* 0x3FF00000, 0x00000000 */
+static const double two     = 2.00000000000000000000e+00; /* 0x40000000, 0x00000000 */
+    /* c = (float)0.84506291151 */
+static const double erx     = 8.45062911510467529297e-01; /* 0x3FEB0AC1, 0x60000000 */
+/*
+ * Coefficients for approximation to  erf on [0,0.84375]
+ */
+static const double efx     =  1.28379167095512586316e-01; /* 0x3FC06EBA, 0x8214DB69 */
+static const double efx8    =  1.02703333676410069053e+00; /* 0x3FF06EBA, 0x8214DB69 */
+static const double pp0     =  1.28379167095512558561e-01; /* 0x3FC06EBA, 0x8214DB68 */
+static const double pp1     = -3.25042107247001499370e-01; /* 0xBFD4CD7D, 0x691CB913 */
+static const double pp2     = -2.84817495755985104766e-02; /* 0xBF9D2A51, 0xDBD7194F */
+static const double pp3     = -5.77027029648944159157e-03; /* 0xBF77A291, 0x236668E4 */
+static const double pp4     = -2.37630166566501626084e-05; /* 0xBEF8EAD6, 0x120016AC */
+static const double qq1     =  3.97917223959155352819e-01; /* 0x3FD97779, 0xCDDADC09 */
+static const double qq2     =  6.50222499887672944485e-02; /* 0x3FB0A54C, 0x5536CEBA */
+static const double qq3     =  5.08130628187576562776e-03; /* 0x3F74D022, 0xC4D36B0F */
+static const double qq4     =  1.32494738004321644526e-04; /* 0x3F215DC9, 0x221C1A10 */
+static const double qq5     = -3.96022827877536812320e-06; /* 0xBED09C43, 0x42A26120 */
+/*
+ * Coefficients for approximation to  erf  in [0.84375,1.25]
+ */
+static const double pa0     = -2.36211856075265944077e-03; /* 0xBF6359B8, 0xBEF77538 */
+static const double pa1     =  4.14856118683748331666e-01; /* 0x3FDA8D00, 0xAD92B34D */
+static const double pa2     = -3.72207876035701323847e-01; /* 0xBFD7D240, 0xFBB8C3F1 */
+static const double pa3     =  3.18346619901161753674e-01; /* 0x3FD45FCA, 0x805120E4 */
+static const double pa4     = -1.10894694282396677476e-01; /* 0xBFBC6398, 0x3D3E28EC */
+static const double pa5     =  3.54783043256182359371e-02; /* 0x3FA22A36, 0x599795EB */
+static const double pa6     = -2.16637559486879084300e-03; /* 0xBF61BF38, 0x0A96073F */
+static const double qa1     =  1.06420880400844228286e-01; /* 0x3FBB3E66, 0x18EEE323 */
+static const double qa2     =  5.40397917702171048937e-01; /* 0x3FE14AF0, 0x92EB6F33 */
+static const double qa3     =  7.18286544141962662868e-02; /* 0x3FB2635C, 0xD99FE9A7 */
+static const double qa4     =  1.26171219808761642112e-01; /* 0x3FC02660, 0xE763351F */
+static const double qa5     =  1.36370839120290507362e-02; /* 0x3F8BEDC2, 0x6B51DD1C */
+static const double qa6     =  1.19844998467991074170e-02; /* 0x3F888B54, 0x5735151D */
+/*
+ * Coefficients for approximation to  erfc in [1.25,1/0.35]
+ */
+static const double ra0     = -9.86494403484714822705e-03; /* 0xBF843412, 0x600D6435 */
+static const double ra1     = -6.93858572707181764372e-01; /* 0xBFE63416, 0xE4BA7360 */
+static const double ra2     = -1.05586262253232909814e+01; /* 0xC0251E04, 0x41B0E726 */
+static const double ra3     = -6.23753324503260060396e+01; /* 0xC04F300A, 0xE4CBA38D */
+static const double ra4     = -1.62396669462573470355e+02; /* 0xC0644CB1, 0x84282266 */
+static const double ra5     = -1.84605092906711035994e+02; /* 0xC067135C, 0xEBCCABB2 */
+static const double ra6     = -8.12874355063065934246e+01; /* 0xC0545265, 0x57E4D2F2 */
+static const double ra7     = -9.81432934416914548592e+00; /* 0xC023A0EF, 0xC69AC25C */
+static const double sa1     =  1.96512716674392571292e+01; /* 0x4033A6B9, 0xBD707687 */
+static const double sa2     =  1.37657754143519042600e+02; /* 0x4061350C, 0x526AE721 */
+static const double sa3     =  4.34565877475229228821e+02; /* 0x407B290D, 0xD58A1A71 */
+static const double sa4     =  6.45387271733267880336e+02; /* 0x40842B19, 0x21EC2868 */
+static const double sa5     =  4.29008140027567833386e+02; /* 0x407AD021, 0x57700314 */
+static const double sa6     =  1.08635005541779435134e+02; /* 0x405B28A3, 0xEE48AE2C */
+static const double sa7     =  6.57024977031928170135e+00; /* 0x401A47EF, 0x8E484A93 */
+static const double sa8     = -6.04244152148580987438e-02; /* 0xBFAEEFF2, 0xEE749A62 */
+/*
+ * Coefficients for approximation to  erfc in [1/.35,28]
+ */
+static const double rb0     = -9.86494292470009928597e-03; /* 0xBF843412, 0x39E86F4A */
+static const double rb1     = -7.99283237680523006574e-01; /* 0xBFE993BA, 0x70C285DE */
+static const double rb2     = -1.77579549177547519889e+01; /* 0xC031C209, 0x555F995A */
+static const double rb3     = -1.60636384855821916062e+02; /* 0xC064145D, 0x43C5ED98 */
+static const double rb4     = -6.37566443368389627722e+02; /* 0xC083EC88, 0x1375F228 */
+static const double rb5     = -1.02509513161107724954e+03; /* 0xC0900461, 0x6A2E5992 */
+static const double rb6     = -4.83519191608651397019e+02; /* 0xC07E384E, 0x9BDC383F */
+static const double sb1     =  3.03380607434824582924e+01; /* 0x403E568B, 0x261D5190 */
+static const double sb2     =  3.25792512996573918826e+02; /* 0x40745CAE, 0x221B9F0A */
+static const double sb3     =  1.53672958608443695994e+03; /* 0x409802EB, 0x189D5118 */
+static const double sb4     =  3.19985821950859553908e+03; /* 0x40A8FFB7, 0x688C246A */
+static const double sb5     =  2.55305040643316442583e+03; /* 0x40A3F219, 0xCEDF3BE6 */
+static const double sb6     =  4.74528541206955367215e+02; /* 0x407DA874, 0xE79FE763 */
+static const double sb7     = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */
+
+double erf(double x)
+{
+    TInt32 hx,ix,i;
+    double R,S,P,Q,s,y,z,r;
+    GET_HIGH_WORD(hx,x);
+    ix = hx&0x7fffffff;
+    if(ix>=0x7ff00000) {        /* erf(nan)=nan */
+        i = ((TUint32)hx>>31)<<1;
+        return (double)(1-i)+one/x; /* erf(+-inf)=+-1 */
+    }
+
+    if(ix < 0x3feb0000) {       /* |x|<0.84375 */
+        if(ix < 0x3e300000) {   /* |x|<2**-28 */
+            if (ix < 0x00800000)
+            return 0.125*(8.0*x+efx8*x);  /*avoid underflow */
+        return x + efx*x;
+        }
+        z = x*x;
+        r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
+        s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
+        y = r/s;
+        return x + x*y;
+    }
+    if(ix < 0x3ff40000) {       /* 0.84375 <= |x| < 1.25 */
+        s = fabs(x)-one;
+        P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
+        Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
+        if(hx>=0) return erx + P/Q; else return -erx - P/Q;
+    }
+    if (ix >= 0x40180000) {     /* inf>|x|>=6 */
+        if(hx>=0) return one-tiny; else return tiny-one;
+    }
+    x = fabs(x);
+    s = one/(x*x);
+    if(ix< 0x4006DB6E) {    /* |x| < 1/0.35 */
+        R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(
+                ra5+s*(ra6+s*ra7))))));
+        S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(
+                sa5+s*(sa6+s*(sa7+s*sa8)))))));
+    } else {    /* |x| >= 1/0.35 */
+        R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(
+                rb5+s*rb6)))));
+        S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(
+                sb5+s*(sb6+s*sb7))))));
+    }
+    z  = x;
+    SET_LOW_WORD(z,0);
+    r  =  __ieee754_exp(-z*z-0.5625)*__ieee754_exp((z-x)*(z+x)+R/S);
+    if(hx>=0) return one-r/x; else return  r/x-one;
+}
+
+double erfc(double x)
+{
+    int32_t hx,ix;
+    double R,S,P,Q,s,y,z,r;
+    GET_HIGH_WORD(hx,x);
+    ix = hx&0x7fffffff;
+    if(ix>=0x7ff00000) {            /* erfc(nan)=nan */
+                        /* erfc(+-inf)=0,2 */
+        return (double)(((u_int32_t)hx>>31)<<1)+one/x;
+    }
+
+    if(ix < 0x3feb0000) {       /* |x|<0.84375 */
+        if(ix < 0x3c700000)     /* |x|<2**-56 */
+        return one-x;
+        z = x*x;
+        r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
+        s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
+        y = r/s;
+        if(hx < 0x3fd00000) {   /* x<1/4 */
+        return one-(x+x*y);
+        } else {
+        r = x*y;
+        r += (x-half);
+            return half - r ;
+        }
+    }
+    if(ix < 0x3ff40000) {       /* 0.84375 <= |x| < 1.25 */
+        s = fabs(x)-one;
+        P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
+        Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
+        if(hx>=0) {
+            z  = one-erx; return z - P/Q;
+        } else {
+        z = erx+P/Q; return one+z;
+        }
+    }
+    if (ix < 0x403c0000) {      /* |x|<28 */
+        x = fabs(x);
+        s = one/(x*x);
+        if(ix< 0x4006DB6D) {    /* |x| < 1/.35 ~ 2.857143*/
+            R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(
+                ra5+s*(ra6+s*ra7))))));
+            S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(
+                sa5+s*(sa6+s*(sa7+s*sa8)))))));
+        } else {            /* |x| >= 1/.35 ~ 2.857143 */
+        if(hx<0&&ix>=0x40180000) return two-tiny;/* x < -6 */
+            R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(
+                rb5+s*rb6)))));
+            S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(
+                sb5+s*(sb6+s*sb7))))));
+        }
+        z  = x;
+        SET_LOW_WORD(z,0);
+        r  =  __ieee754_exp(-z*z-0.5625)*
+            __ieee754_exp((z-x)*(z+x)+R/S);
+        if(hx>0) return r/x; else return two-r/x;
+    } else {
+        if(hx>0) return tinySquare; else return two-tiny;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/matrix.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,189 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/matrix.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+R A N K  A L G O R I T H M  R O U T I N E S
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+#define	MATRIX_FORWARD_ELIMINATION	0
+#define	MATRIX_BACKWARD_ELIMINATION	1
+
+int
+computeRank(int M, int Q, BitSequence **matrix)
+{
+	int		i, rank, m=MIN(M,Q);
+	
+	/* FORWARD APPLICATION OF ELEMENTARY ROW OPERATIONS */ 
+	for ( i=0; i<m-1; i++ ) {
+		if ( matrix[i][i] == 1 ) 
+			perform_elementary_row_operations(MATRIX_FORWARD_ELIMINATION, i, M, Q, matrix);
+		else { 	/* matrix[i][i] = 0 */
+			if ( find_unit_element_and_swap(MATRIX_FORWARD_ELIMINATION, i, M, Q, matrix) == 1 ) 
+				perform_elementary_row_operations(MATRIX_FORWARD_ELIMINATION, i, M, Q, matrix);
+		}
+	}
+
+	/* BACKWARD APPLICATION OF ELEMENTARY ROW OPERATIONS */ 
+	for ( i=m-1; i>0; i-- ) {
+		if ( matrix[i][i] == 1 )
+			perform_elementary_row_operations(MATRIX_BACKWARD_ELIMINATION, i, M, Q, matrix);
+		else { 	/* matrix[i][i] = 0 */
+			if ( find_unit_element_and_swap(MATRIX_BACKWARD_ELIMINATION, i, M, Q, matrix) == 1 )
+				perform_elementary_row_operations(MATRIX_BACKWARD_ELIMINATION, i, M, Q, matrix);
+		}
+	} 
+
+	rank = determine_rank(m, M, Q, matrix);
+
+	return rank;
+}
+
+void
+perform_elementary_row_operations(int flag, int i, int M, int Q, BitSequence **A)
+{
+	int		j, k;
+	
+	if ( flag == MATRIX_FORWARD_ELIMINATION ) {
+		for ( j=i+1; j<M;  j++ )
+			if ( A[j][i] == 1 ) 
+				for ( k=i; k<Q; k++ ) 
+					A[j][k] = (BitSequence)((A[j][k] + A[i][k]) % 2);
+	}
+	else {
+		for ( j=i-1; j>=0;  j-- )
+			if ( A[j][i] == 1 )
+				for ( k=0; k<Q; k++ )
+					A[j][k] = (BitSequence)((A[j][k] + A[i][k]) % 2);
+	}
+}
+
+int
+find_unit_element_and_swap(int flag, int i, int M, int Q, BitSequence **A)
+{ 
+	int		index, row_op=0;
+	
+	if ( flag == MATRIX_FORWARD_ELIMINATION ) {
+		index = i+1;
+		while ( (index < M) && (A[index][i] == 0) ) 
+			index++;
+			if ( index < M )
+				row_op = swap_rows(i, index, Q, A);
+	}
+	else {
+		index = i-1;
+		while ( (index >= 0) && (A[index][i] == 0) ) 
+			index--;
+			if ( index >= 0 )
+				row_op = swap_rows(i, index, Q, A);
+	}
+	
+	return row_op;
+}
+
+int
+swap_rows(int i, int index, int Q, BitSequence **A)
+{
+	int			p;
+	BitSequence	temp;
+	
+	for ( p=0; p<Q; p++ ) {
+		temp = A[i][p];
+		A[i][p] = A[index][p];
+		A[index][p] = temp;
+	}
+	
+	return 1;
+}
+
+int
+determine_rank(int m, int M, int Q, BitSequence **A)
+{
+	int		i, j, rank, allZeroes;
+	
+	/* DETERMINE RANK, THAT IS, COUNT THE NUMBER OF NONZERO ROWS */
+	
+	rank = m;
+	for ( i=0; i<M; i++ ) {
+		allZeroes = 1; 
+		for ( j=0; j<Q; j++)  {
+			if ( A[i][j] == 1 ) {
+				allZeroes = 0;
+				break;
+			}
+		}
+		if ( allZeroes == 1 )
+			rank--;
+	} 
+	
+	return rank;
+}
+
+BitSequence**
+create_matrix(int M, int Q)
+{
+	int			i;
+	BitSequence	**matrix;
+	
+	if ( (matrix = (BitSequence **) calloc(M, sizeof(BitSequence *))) == NULL ) {
+		printf("ERROR IN FUNCTION create_matrix:  Insufficient memory available.\n");
+		
+		return NULL;
+	}
+	else {
+		for ( i=0; i<M; i++ ) {
+			if ( (matrix[i] = (unsigned char*)calloc(Q, sizeof(BitSequence))) == NULL ) {
+				printf("ERROR IN FUNCTION create_matrix: Insufficient memory for %dx%d matrix.\n", M, M);
+
+				return NULL;
+			}
+		}
+		return matrix;
+	}
+}
+
+void
+def_matrix(int M, int Q, BitSequence **m,int k)
+{
+	int		i,j;
+	
+	for ( i=0; i<M; i++ ) 
+		for ( j=0; j<Q; j++ )
+			m[i][j] = epsilon[k*(M*Q)+j+i*M];
+}
+
+void
+delete_matrix(int M, BitSequence **matrix)
+{
+	int		i;
+
+	for ( i=0; i<M; i++ )
+		free(matrix[i]);
+	free(matrix);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/nonoverlappingtemplatematchings.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,149 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/cephes.h"  
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+          N O N O V E R L A P P I N G  T E M P L A T E  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+NonOverlappingTemplateMatchings(int m, int n)
+{
+	int		numOfTemplates[100] = {0, 0, 2, 4, 6, 12, 20, 40, 74, 148, 284, 568, 1116,
+						2232, 4424, 8848, 17622, 35244, 70340, 140680, 281076, 562152};
+	/*----------------------------------------------------------------------------
+	NOTE:  Should additional templates lengths beyond 21 be desired, they must 
+	first be constructed, saved into files and then the corresponding 
+	number of nonperiodic templates for that file be stored in the m-th 
+	position in the numOfTemplates variable.
+	----------------------------------------------------------------------------*/
+	unsigned int	W_obs, *Wj = NULL; 
+	double			sum, chi2, p_value, lambda, pi[6], varWj;
+	int				i, j, jj, k, match, SKIP, M, N, K = 5;
+	
+	ResetTemplateIndex();
+
+	N = 8;
+	M = n/N;
+
+	if ( (Wj = (unsigned int*)calloc(N, sizeof(unsigned int))) == NULL ) {
+		fprintf(stats[TEST_NONPERIODIC], "\tNONOVERLAPPING TEMPLATES TESTS ABORTED DUE TO ONE OF THE FOLLOWING : \n");
+		fprintf(stats[TEST_NONPERIODIC], "\tInsufficient memory for required work space.\n");
+		return;
+	}
+	lambda = (M-m+1)/pow(2, m);
+	varWj = M*(1.0/pow(2.0, m) - (2.0*m-1.0)/pow(2.0, 2.0*m));
+
+	if ( isNegative(lambda) || isZero(lambda)) 
+	    {
+		fprintf(stats[TEST_NONPERIODIC], "\tNONOVERLAPPING TEMPLATES TESTS ABORTED DUE TO ONE OF THE FOLLOWING : \n");
+		fprintf(stats[TEST_NONPERIODIC], "\tLambda (%f) not being positive!\n", lambda);
+		}
+	else {
+		fprintf(stats[TEST_NONPERIODIC], "\t\t  NONPERIODIC TEMPLATES TEST\n");
+		fprintf(stats[TEST_NONPERIODIC], "-------------------------------------------------------------------------------------\n");
+		fprintf(stats[TEST_NONPERIODIC], "\t\t  COMPUTATIONAL INFORMATION\n");
+		fprintf(stats[TEST_NONPERIODIC], "-------------------------------------------------------------------------------------\n");
+		fprintf(stats[TEST_NONPERIODIC], "\tLAMBDA = %f\tM = %d\tN = %d\tm = %d\tn = %d\n", lambda, M, N, m, n);
+		fprintf(stats[TEST_NONPERIODIC], "-------------------------------------------------------------------------------------\n");
+		fprintf(stats[TEST_NONPERIODIC], "\t\tF R E Q U E N C Y\n");
+		fprintf(stats[TEST_NONPERIODIC], "Template   W_1  W_2  W_3  W_4  W_5  W_6  W_7  W_8    Chi^2   P_value Assignment Index\n");
+		fprintf(stats[TEST_NONPERIODIC], "-------------------------------------------------------------------------------------\n");
+
+		if ( numOfTemplates[m] < MAXNUMOFTEMPLATES )
+			SKIP = 1;
+		else
+			SKIP = (int)(numOfTemplates[m]/MAXNUMOFTEMPLATES);
+		numOfTemplates[m] = (int)numOfTemplates[m]/SKIP;
+		
+		sum = 0.0;
+		for ( i=0; i<2; i++ ) {                      /* Compute Probabilities */
+			pi[i] = exp(-lambda+i*log(lambda)-cephes_lgam(i+1));
+			sum += pi[i];
+		}
+		pi[0] = sum;
+		for ( i=2; i<=K; i++ ) {                      /* Compute Probabilities */
+			pi[i-1] = exp(-lambda+i*log(lambda)-cephes_lgam(i+1));
+			sum += pi[i-1];
+		}
+		pi[K] = 1 - sum;
+
+        BitSequence templateSequence[KMaxBit];
+
+        for( jj=0; jj<MIN(MAXNUMOFTEMPLATES, numOfTemplates[m]); jj++ ) {
+			sum = 0;
+            GetNextTemplateItem(templateSequence);
+
+			fprintf(stats[TEST_NONPERIODIC], " ");
+			for ( i=0; i<N; i++ ) {
+				W_obs = 0;
+				for ( j=0; j<M-m+1; j++ ) {
+					match = 1;
+					for ( k=0; k<m; k++ ) {
+					
+                    if ( (int)templateSequence[KMaxBit - k - 1] != (int)epsilon[i*M+j+k] ) {
+							match = 0;
+							break;
+						}
+					}
+					if ( match == 1 )
+						W_obs++;
+				}
+				Wj[i] = W_obs;
+			}
+			sum = 0;
+			chi2 = 0.0;                                   /* Compute Chi Square */
+			for ( i=0; i<N; i++ ) {
+				if ( m == 10 )
+					fprintf(stats[TEST_NONPERIODIC], "%3d  ", Wj[i]);
+				else
+					fprintf(stats[TEST_NONPERIODIC], "%4d ", Wj[i]);
+				chi2 += pow(((double)Wj[i] - lambda)/pow(varWj, 0.5), 2);
+			}
+			p_value = cephes_igamc(N/2.0, chi2/2.0);
+		
+			if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+				fprintf(stats[TEST_NONPERIODIC], "\t\tWARNING:  P_VALUE IS OUT OF RANGE.\n");
+
+			fprintf(stats[TEST_NONPERIODIC], "%9.6f %f %s %3d\n", chi2, p_value, p_value < ALPHA ? "FAILURE" : "SUCCESS", jj);
+			if ( SKIP > 1 )
+			    {
+			    for(int index = 0; index < (SKIP-1)*2*m; ++index)
+			        {
+			        GetNextTemplateItem(templateSequence);
+			        }
+			    }
+			fprintf(results[TEST_NONPERIODIC], "%f\n", p_value);
+		}
+	}
+	
+	fprintf(stats[TEST_NONPERIODIC], "\n");
+	free(Wj);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/overlappingtemplatematchings.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,132 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/cephes.h"  
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+               O V E R L A P P I N G  T E M P L A T E  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+double	Pr(int u, double eta);
+
+void
+OverlappingTemplateMatchings(int m, int n)
+{
+	int				i, k, match;
+	double			W_obs, eta, sum, chi2, p_value, lambda;
+	int				M, N, j, K = 5;
+	unsigned int	nu[6] = { 0, 0, 0, 0, 0, 0 };
+	double			pi[6] = { 0.143783, 0.139430, 0.137319, 0.124314, 0.106209, 0.348945 };
+	BitSequence		*sequence;
+
+	M = 1032;
+	N = n/M;
+	
+	if ( (sequence = (BitSequence *) calloc(m, sizeof(BitSequence))) == NULL ) {
+		fprintf(stats[TEST_OVERLAPPING], "\t\t    OVERLAPPING TEMPLATE OF ALL ONES TEST\n");
+		fprintf(stats[TEST_OVERLAPPING], "\t\t---------------------------------------------\n");
+		fprintf(stats[TEST_OVERLAPPING], "\t\tTEMPLATE DEFINITION:  Insufficient memory, Overlapping Template Matchings test aborted!\n");
+	}
+	else
+		for ( i=0; i<m; i++ )
+			sequence[i] = 1;
+	
+	lambda = (double)(M-m+1)/pow(2,m);
+	eta = lambda/2.0;
+	sum = 0.0;
+	for ( i=0; i<K; i++ ) {			/* Compute Probabilities */
+		pi[i] = Pr(i, eta);
+		sum += pi[i];
+	}
+	pi[K] = 1 - sum;
+
+	for ( i=0; i<N; i++ ) {
+		W_obs = 0;
+		for ( j=0; j<M-m+1; j++ ) {
+			match = 1;
+			for ( k=0; k<m; k++ ) {
+				if ( sequence[k] != epsilon[i*M+j+k] )
+					match = 0;
+			}
+			if ( match == 1 )
+				W_obs++;
+		}
+		if ( W_obs <= 4 )
+			nu[(int)W_obs]++;
+		else
+			nu[K]++;
+	}
+	sum = 0;
+	chi2 = 0.0;                                   /* Compute Chi Square */
+	for ( i=0; i<K+1; i++ ) {
+		chi2 += pow((double)nu[i] - (double)N*pi[i], 2)/((double)N*pi[i]);
+		sum += nu[i];
+	}
+	p_value = cephes_igamc(K/2.0, chi2/2.0);
+
+	fprintf(stats[TEST_OVERLAPPING], "\t\t    OVERLAPPING TEMPLATE OF ALL ONES TEST\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t-----------------------------------------------\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t-----------------------------------------------\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t(a) n (sequence_length)      = %d\n", n);
+	fprintf(stats[TEST_OVERLAPPING], "\t\t(b) m (block length of 1s)   = %d\n", m);
+	fprintf(stats[TEST_OVERLAPPING], "\t\t(c) M (length of substring)  = %d\n", M);
+	fprintf(stats[TEST_OVERLAPPING], "\t\t(d) N (number of substrings) = %d\n", N);
+	fprintf(stats[TEST_OVERLAPPING], "\t\t(e) lambda [(M-m+1)/2^m]     = %f\n", lambda);
+	fprintf(stats[TEST_OVERLAPPING], "\t\t(f) eta                      = %f\n", eta);
+	fprintf(stats[TEST_OVERLAPPING], "\t\t-----------------------------------------------\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t   F R E Q U E N C Y\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t  0   1   2   3   4 >=5   Chi^2   P-value  Assignment\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t-----------------------------------------------\n");
+	fprintf(stats[TEST_OVERLAPPING], "\t\t%3d %3d %3d %3d %3d %3d  %f ",
+		nu[0], nu[1], nu[2], nu[3], nu[4], nu[5], chi2);
+
+	if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+		fprintf(stats[TEST_OVERLAPPING], "WARNING:  P_VALUE IS OUT OF RANGE.\n");
+
+	free(sequence);
+	fprintf(stats[TEST_OVERLAPPING], "%f %s\n\n", p_value, p_value < ALPHA ? "FAILURE" : "SUCCESS");
+	fprintf(results[TEST_OVERLAPPING], "%f\n", p_value);
+}
+
+double
+Pr(int u, double eta)
+{
+	int		l;
+	double	sum, p;
+	
+	if ( u == 0 )
+		p = exp(-eta);
+	else {
+		sum = 0.0;
+		for ( l=1; l<=u; l++ )
+			sum += exp(-eta-u*log(2)+l*log(eta)-cephes_lgam(l+1)+cephes_lgam(u)-cephes_lgam(l)-cephes_lgam(u-l+1));
+		p = sum;
+	}
+	return p;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/randomexcursions.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,145 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"  
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                     R A N D O M  E X C U R S I O N S  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+RandomExcursions(int n)
+{
+	int		b, i, j, k, J, x;
+	int		cycleStart, cycleStop, *cycle = NULL, *S_k = NULL;
+	int		stateX[8] = { -4, -3, -2, -1, 1, 2, 3, 4 };
+	int		counter[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
+	double	p_value, sum, constraint, nu[6][8];
+	double	pi[5][6] = { {0.0000000000, 0.00000000000, 0.00000000000, 0.00000000000, 0.00000000000, 0.0000000000}, 
+						 {0.5000000000, 0.25000000000, 0.12500000000, 0.06250000000, 0.03125000000, 0.0312500000},
+						 {0.7500000000, 0.06250000000, 0.04687500000, 0.03515625000, 0.02636718750, 0.0791015625},
+						 {0.8333333333, 0.02777777778, 0.02314814815, 0.01929012346, 0.01607510288, 0.0803755143},
+						 {0.8750000000, 0.01562500000, 0.01367187500, 0.01196289063, 0.01046752930, 0.0732727051} };
+	
+	if ( ((S_k = (int *)calloc(n, sizeof(int))) == NULL) ||
+		 ((cycle = (int *)calloc(MAX(1000, n/100), sizeof(int))) == NULL) ) {
+		printf("Random Excursions Test:  Insufficent Work Space Allocated.\n");
+		if ( S_k != NULL )
+			free(S_k);
+		if ( cycle != NULL )
+			free(cycle);
+		return;
+	}
+	
+	J = 0; 					/* DETERMINE CYCLES */
+	S_k[0] = 2*(int)epsilon[0] - 1;
+	for( i=1; i<n; i++ ) {
+		S_k[i] = S_k[i-1] + 2*epsilon[i] - 1;
+		if ( S_k[i] == 0 ) {
+			J++;
+			if ( J > MAX(1000, n/100) ) {
+				printf("ERROR IN FUNCTION randomExcursions:  EXCEEDING THE MAX NUMBER OF CYCLES EXPECTED\n.");
+				free(S_k);
+				free(cycle);
+				return;
+			}
+			cycle[J] = i;
+		}
+	}
+	if ( S_k[n-1] != 0 )
+		J++;
+	cycle[J] = n;
+
+	fprintf(stats[TEST_RND_EXCURSION], "\t\t\t  RANDOM EXCURSIONS TEST\n");
+	fprintf(stats[TEST_RND_EXCURSION], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_RND_EXCURSION], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_RND_EXCURSION], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_RND_EXCURSION], "\t\t(a) Number Of Cycles (J) = %04d\n", J);
+	fprintf(stats[TEST_RND_EXCURSION], "\t\t(b) Sequence Length (n)  = %d\n", n);
+
+	constraint = MAX(0.005*pow(n, 0.5), 500);
+	if (J < constraint) {
+		fprintf(stats[TEST_RND_EXCURSION], "\t\t---------------------------------------------\n");
+		fprintf(stats[TEST_RND_EXCURSION], "\t\tWARNING:  TEST NOT APPLICABLE.  THERE ARE AN\n");
+		fprintf(stats[TEST_RND_EXCURSION], "\t\t\t  INSUFFICIENT NUMBER OF CYCLES.\n");
+		fprintf(stats[TEST_RND_EXCURSION], "\t\t---------------------------------------------\n");
+		for(i = 0; i < 8; i++)
+			fprintf(results[TEST_RND_EXCURSION], "%f\n", 0.0);
+	}
+	else {
+		fprintf(stats[TEST_RND_EXCURSION], "\t\t(c) Rejection Constraint = %f\n", constraint);
+		fprintf(stats[TEST_RND_EXCURSION], "\t\t-------------------------------------------\n");
+
+		cycleStart = 0;
+		cycleStop  = cycle[1];
+		for ( k=0; k<6; k++ )
+			for ( i=0; i<8; i++ )
+				nu[k][i] = 0.;
+		for ( j=1; j<=J; j++ ) {                           /* FOR EACH CYCLE */
+			for ( i=0; i<8; i++ )
+				counter[i] = 0;
+			for ( i=cycleStart; i<cycleStop; i++ ) {
+				if ( (S_k[i] >= 1 && S_k[i] <= 4) || (S_k[i] >= -4 && S_k[i] <= -1) ) {
+					if ( S_k[i] < 0 )
+						b = 4;
+					else
+						b = 3;
+					counter[S_k[i]+b]++;
+				}
+			}
+			cycleStart = cycle[j]+1;
+			if ( j < J )
+				cycleStop = cycle[j+1];
+			
+			for ( i=0; i<8; i++ ) {
+				if ( (counter[i] >= 0) && (counter[i] <= 4) )
+					nu[counter[i]][i]++;
+				else if ( counter[i] >= 5 )
+					nu[5][i]++;
+			}
+		}
+		
+		for ( i=0; i<8; i++ ) {
+			x = stateX[i];
+			sum = 0.;
+			for ( k=0; k<6; k++ )
+				sum += pow(nu[k][i] - J*pi[(int)fabs(x)][k], 2) / (J*pi[(int)fabs(x)][k]);
+			p_value = cephes_igamc(2.5, sum/2.0);
+			
+			if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+				fprintf(stats[TEST_RND_EXCURSION], "WARNING:  P_VALUE IS OUT OF RANGE.\n");
+
+			fprintf(stats[TEST_RND_EXCURSION], "%s\t\tx = %2d chi^2 = %9.6f p_value = %f\n",
+					p_value < ALPHA ? "FAILURE" : "SUCCESS", x, sum, p_value);
+			fprintf(results[TEST_RND_EXCURSION], "%f\n", p_value);
+		}
+	} 
+	fprintf(stats[TEST_RND_EXCURSION], "\n");
+	free(S_k);
+	free(cycle);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/randomexcursionsvariant.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,90 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+            R A N D O M  E X C U R S I O N S  V A R I A N T  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+RandomExcursionsVariant(int n)
+{
+	int		i, p, J, x, constraint, count, *S_k;
+	int		stateX[18] = { -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+	double	p_value;
+	
+	if ( (S_k = (int *)calloc(n, sizeof(int))) == NULL ) {
+		fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\tRANDOM EXCURSIONS VARIANT: Insufficent memory allocated.\n");
+		return;
+	}
+	J = 0;
+	S_k[0] = 2*(int)epsilon[0] - 1;
+	for ( i=1; i<n; i++ ) {
+		S_k[i] = S_k[i-1] + 2*epsilon[i] - 1;
+		if ( S_k[i] == 0 )
+			J++;
+	}
+	if ( S_k[n-1] != 0 )
+		J++;
+
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t\tRANDOM EXCURSIONS VARIANT TEST\n");
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t(a) Number Of Cycles (J) = %d\n", J);
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t(b) Sequence Length (n)  = %d\n", n);
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t--------------------------------------------\n");
+
+	constraint = (int)MAX(0.005*pow(n, 0.5), 500);
+	if (J < constraint) {
+		fprintf(stats[TEST_RND_EXCURSION_VAR], "\n\t\tWARNING:  TEST NOT APPLICABLE.  THERE ARE AN\n");
+		fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t\t  INSUFFICIENT NUMBER OF CYCLES.\n");
+		fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t---------------------------------------------\n");
+		for ( i=0; i<18; i++ )
+			fprintf(results[TEST_RND_EXCURSION_VAR], "%f\n", 0.0);
+	}
+	else {
+		for ( p=0; p<=17; p++ ) {
+			x = stateX[p];
+			count = 0;
+			for ( i=0; i<n; i++ )
+				if ( S_k[i] == x )
+					count++;
+			p_value = erfc(fabs(count-J)/(sqrt(2.0*J*(4.0*fabs(x)-2))));
+
+			if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+				fprintf(stats[TEST_RND_EXCURSION_VAR], "\t\t(b) WARNING: P_VALUE IS OUT OF RANGE.\n");
+			fprintf(stats[TEST_RND_EXCURSION_VAR], "%s\t\t", p_value < ALPHA ? "FAILURE" : "SUCCESS");
+			fprintf(stats[TEST_RND_EXCURSION_VAR], "(x = %2d) Total visits = %4d; p-value = %f\n", x, count, p_value);
+			fprintf(results[TEST_RND_EXCURSION_VAR], "%f\n", p_value);
+		}
+	}
+	fprintf(stats[TEST_RND_EXCURSION_VAR], "\n");
+	free(S_k);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/rank.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,111 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"
+#include "../include/matrix.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                              R A N K  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+Rank(int n)
+{
+	int			N, i, k, r;
+	double		p_value, product, chi_squared, arg1, p_32, p_31, p_30, R, F_32, F_31, F_30;
+	
+	N = n/(32*32);
+	if ( isZero(N) ) {
+		fprintf(stats[TEST_RANK], "\t\t\t\tRANK TEST\n");
+		fprintf(stats[TEST_RANK], "\t\tError: Insuffucient # Of Bits To Define An 32x32 (%dx%d) Matrix\n", 32, 32);
+		p_value = 0.00;
+	}
+	else {
+        BitSequence **matrix = create_matrix(32, 32);
+		
+        r = 32;					/* COMPUTE PROBABILITIES */
+		product = 1;
+		for ( i=0; i<=r-1; i++ )
+			product *= ((1.e0-pow(2, i-32))*(1.e0-pow(2, i-32)))/(1.e0-pow(2, i-r));
+		p_32 = pow(2, r*(32+32-r)-32*32) * product;
+		
+		r = 31;
+		product = 1;
+		for ( i=0; i<=r-1; i++ )
+			product *= ((1.e0-pow(2, i-32))*(1.e0-pow(2, i-32)))/(1.e0-pow(2, i-r));
+		p_31 = pow(2, r*(32+32-r)-32*32) * product;
+		
+		p_30 = 1 - (p_32+p_31);
+		
+		F_32 = 0;
+		F_31 = 0;
+		for ( k=0; k<N; k++ ) {			/* FOR EACH 32x32 MATRIX   */
+			def_matrix(32, 32, matrix, k);
+#if (DISPLAY_MATRICES == 1)
+			display_matrix(32, 32, matrix);
+#endif
+			R = computeRank(32, 32, matrix);
+			if ( R == 32 )
+				F_32++;			/* DETERMINE FREQUENCIES */
+			if ( R == 31 )
+				F_31++;
+		}
+		F_30 = (double)N - (F_32+F_31);
+		
+		chi_squared =(pow(F_32 - N*p_32, 2)/(double)(N*p_32) +
+					  pow(F_31 - N*p_31, 2)/(double)(N*p_31) +
+					  pow(F_30 - N*p_30, 2)/(double)(N*p_30));
+		
+		arg1 = -chi_squared/2.e0;
+
+		fprintf(stats[TEST_RANK], "\t\t\t\tRANK TEST\n");
+		fprintf(stats[TEST_RANK], "\t\t---------------------------------------------\n");
+		fprintf(stats[TEST_RANK], "\t\tCOMPUTATIONAL INFORMATION:\n");
+		fprintf(stats[TEST_RANK], "\t\t---------------------------------------------\n");
+		fprintf(stats[TEST_RANK], "\t\t(a) Probability P_%d = %f\n", 32,p_32);
+		fprintf(stats[TEST_RANK], "\t\t(b)             P_%d = %f\n", 31,p_31);
+		fprintf(stats[TEST_RANK], "\t\t(c)             P_%d = %f\n", 30,p_30);
+		fprintf(stats[TEST_RANK], "\t\t(d) Frequency   F_%d = %d\n", 32,(int)F_32);
+		fprintf(stats[TEST_RANK], "\t\t(e)             F_%d = %d\n", 31,(int)F_31);
+		fprintf(stats[TEST_RANK], "\t\t(f)             F_%d = %d\n", 30,(int)F_30);
+		fprintf(stats[TEST_RANK], "\t\t(g) # of matrices    = %d\n", N);
+		fprintf(stats[TEST_RANK], "\t\t(h) Chi^2            = %f\n", chi_squared);
+		fprintf(stats[TEST_RANK], "\t\t(i) NOTE: %d BITS WERE DISCARDED.\n", n%(32*32));
+		fprintf(stats[TEST_RANK], "\t\t---------------------------------------------\n");
+
+		p_value = exp(arg1);
+		if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+			fprintf(stats[TEST_RANK], "WARNING:  P_VALUE IS OUT OF RANGE.\n");
+
+		for ( i=0; i<32; i++ )				/* DEALLOCATE MATRIX  */
+			free(matrix[i]);
+		free(matrix);
+	}
+	fprintf(stats[TEST_RANK], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	fprintf(results[TEST_RANK], "%f\n", p_value);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/runs.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,80 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                              R U N S  T E S T 
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+Runs(int n)
+{
+	int		S, k;
+	double	pi, V, erfc_arg, p_value;
+
+	S = 0;
+	for ( k=0; k<n; k++ )
+		if ( epsilon[k] )
+			S++;
+	pi = (double)S / (double)n;
+
+	if ( fabs(pi - 0.5) > (2.0 / sqrt(n)) ) {
+		fprintf(stats[TEST_RUNS], "\t\t\t\tRUNS TEST\n");
+		fprintf(stats[TEST_RUNS], "\t\t------------------------------------------\n");
+		fprintf(stats[TEST_RUNS], "\t\tPI ESTIMATOR CRITERIA NOT MET! PI = %f\n", pi);
+		p_value = 0.0;
+	}
+	else {
+
+		V = 1;
+		for ( k=1; k<n; k++ )
+			if ( epsilon[k] != epsilon[k-1] )
+				V++;
+	
+		erfc_arg = fabs(V - 2.0 * n * pi * (1-pi)) / (2.0 * pi * (1-pi) * sqrt(2*n));
+		p_value = erfc(erfc_arg);
+		
+		fprintf(stats[TEST_RUNS], "\t\t\t\tRUNS TEST\n");
+		fprintf(stats[TEST_RUNS], "\t\t------------------------------------------\n");
+		fprintf(stats[TEST_RUNS], "\t\tCOMPUTATIONAL INFORMATION:\n");
+		fprintf(stats[TEST_RUNS], "\t\t------------------------------------------\n");
+		fprintf(stats[TEST_RUNS], "\t\t(a) Pi                        = %f\n", pi);
+		fprintf(stats[TEST_RUNS], "\t\t(b) V_n_obs (Total # of runs) = %d\n", (int)V);
+		fprintf(stats[TEST_RUNS], "\t\t(c) V_n_obs - 2 n pi (1-pi)\n");
+		fprintf(stats[TEST_RUNS], "\t\t    -----------------------   = %f\n", erfc_arg);
+		fprintf(stats[TEST_RUNS], "\t\t      2 sqrt(2n) pi (1-pi)\n");
+		fprintf(stats[TEST_RUNS], "\t\t------------------------------------------\n");
+		if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+			fprintf(stats[TEST_RUNS], "WARNING:  P_VALUE IS OUT OF RANGE.\n");
+
+		fprintf(stats[TEST_RUNS], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);
+	}
+
+	fprintf(results[TEST_RUNS], "%f\n", p_value);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/serial.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,101 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/cephes.h"  
+
+double psi2(int m, int n);
+
+void
+Serial(int m, int n)
+{
+	double	p_value1, p_value2, psim0, psim1, psim2, del1, del2;
+	
+	psim0 = psi2(m, n);
+	psim1 = psi2(m-1, n);
+	psim2 = psi2(m-2, n);
+	del1 = psim0 - psim1;
+	del2 = psim0 - 2.0*psim1 + psim2;
+	p_value1 = cephes_igamc(pow(2, m-1)/2, del1/2.0);
+	p_value2 = cephes_igamc(pow(2, m-2)/2, del2/2.0);
+	
+	fprintf(stats[TEST_SERIAL], "\t\t\t       SERIAL TEST\n");
+	fprintf(stats[TEST_SERIAL], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_SERIAL], "\t\t COMPUTATIONAL INFORMATION:		  \n");
+	fprintf(stats[TEST_SERIAL], "\t\t---------------------------------------------\n");
+	fprintf(stats[TEST_SERIAL], "\t\t(a) Block length    (m) = %d\n", m);
+	fprintf(stats[TEST_SERIAL], "\t\t(b) Sequence length (n) = %d\n", n);
+	fprintf(stats[TEST_SERIAL], "\t\t(c) Psi_m               = %f\n", psim0);
+	fprintf(stats[TEST_SERIAL], "\t\t(d) Psi_m-1             = %f\n", psim1);
+	fprintf(stats[TEST_SERIAL], "\t\t(e) Psi_m-2             = %f\n", psim2);
+	fprintf(stats[TEST_SERIAL], "\t\t(f) Del_1               = %f\n", del1);
+	fprintf(stats[TEST_SERIAL], "\t\t(g) Del_2               = %f\n", del2);
+	fprintf(stats[TEST_SERIAL], "\t\t---------------------------------------------\n");
+
+	fprintf(stats[TEST_SERIAL], "%s\t\tp_value1 = %f\n", p_value1 < ALPHA ? "FAILURE" : "SUCCESS", p_value1);
+	fprintf(results[TEST_SERIAL], "%f\n", p_value1);
+
+	fprintf(stats[TEST_SERIAL], "%s\t\tp_value2 = %f\n\n", p_value2 < ALPHA ? "FAILURE" : "SUCCESS", p_value2);
+	fprintf(results[TEST_SERIAL], "%f\n", p_value2);
+}
+
+double
+psi2(int m, int n)
+{
+	int				i, j, k, powLen;
+	double			sum, numOfBlocks;
+	unsigned int	*P;
+	
+	if ( (m == 0) || (m == -1) )
+		return 0.0;
+	numOfBlocks = n;
+	powLen = (int)pow(2, m+1)-1;
+	if ( (P = (unsigned int*)calloc(powLen,sizeof(unsigned int)))== NULL ) {
+		fprintf(stats[TEST_SERIAL], "Serial Test:  Insufficient memory available.\n");
+		fflush(stats[TEST_SERIAL]);
+		return 0.0;
+	}
+	for ( i=1; i<powLen-1; i++ )
+		P[i] = 0;	  /* INITIALIZE NODES */
+	for ( i=0; i<numOfBlocks; i++ ) {		 /* COMPUTE FREQUENCY */
+		k = 1;
+		for ( j=0; j<m; j++ ) {
+			if ( epsilon[(i+j)%n] == 0 )
+				k *= 2;
+			else if ( epsilon[(i+j)%n] == 1 )
+				k = 2*k+1;
+		}
+		P[k-1]++;
+	}
+	sum = 0.0;
+	for ( i=(int)pow(2, m)-1; i<(int)pow(2, m+1)-1; i++ )
+		sum += pow(P[i], 2);
+	sum = (sum * pow(2, m)/(double)n) - (double)n;
+	free(P);
+	
+	return sum;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/universal.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,125 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/cephes.h"
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+                         U N I V E R S A L  T E S T
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+void
+Universal(int n)
+{
+	int		i, j, p, L, Q, K;
+	double	arg, sqrt2, sigma, phi, sum, p_value, c;
+	long	*T, decRep;
+	double	expected_value[17] = { 0, 0, 0, 0, 0, 0, 5.2177052, 6.1962507, 7.1836656,
+				8.1764248, 9.1723243, 10.170032, 11.168765,
+				12.168070, 13.167693, 14.167488, 15.167379 };
+	double   variance[17] = { 0, 0, 0, 0, 0, 0, 2.954, 3.125, 3.238, 3.311, 3.356, 3.384,
+				3.401, 3.410, 3.416, 3.419, 3.421 };
+	
+	/* * * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+	 * THE FOLLOWING REDEFINES L, SHOULD THE CONDITION:     n >= 1010*2^L*L       *
+	 * NOT BE MET, FOR THE BLOCK LENGTH L.                                        *
+	 * * * * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+	L = 5;
+	if ( n >= 387840 )     L = 6;
+	if ( n >= 904960 )     L = 7;
+	if ( n >= 2068480 )    L = 8;
+	if ( n >= 4654080 )    L = 9;
+	if ( n >= 10342400 )   L = 10;
+	if ( n >= 22753280 )   L = 11;
+	if ( n >= 49643520 )   L = 12;
+	if ( n >= 107560960 )  L = 13;
+	if ( n >= 231669760 )  L = 14;
+	if ( n >= 496435200 )  L = 15;
+	if ( n >= 1059061760 ) L = 16;
+	
+	Q = 10*(int)pow(2, L);
+	K = (int) (floor(n/L) - (double)Q);	 		    /* BLOCKS TO TEST */
+	
+	p = (int)pow(2, L);
+	if ( (L < 6) || (L > 16) || ((double)Q < 10*pow(2, L)) ||
+		 ((T = (long *)calloc(p, sizeof(long))) == NULL) ) {
+		fprintf(stats[TEST_UNIVERSAL], "\t\tUNIVERSAL STATISTICAL TEST\n");
+		fprintf(stats[TEST_UNIVERSAL], "\t\t---------------------------------------------\n");
+		fprintf(stats[TEST_UNIVERSAL], "\t\tERROR:  L IS OUT OF RANGE.\n");
+		fprintf(stats[TEST_UNIVERSAL], "\t\t-OR- :  Q IS LESS THAN %f.\n", 10*pow(2, L));
+		fprintf(stats[TEST_UNIVERSAL], "\t\t-OR- :  Unable to allocate T.\n");
+		return;
+	}
+	
+	/* COMPUTE THE EXPECTED:  Formula 16, in Marsaglia's Paper */
+	c = 0.7 - 0.8/(double)L + (4 + 32/(double)L)*pow(K, -3/(double)L)/15;
+	sigma = c * sqrt(variance[L]/(double)K);
+	sqrt2 = sqrt(2);
+	sum = 0.0;
+	for ( i=0; i<p; i++ )
+		T[i] = 0;
+	for ( i=1; i<=Q; i++ ) {		/* INITIALIZE TABLE */
+		decRep = 0;
+		for ( j=0; j<L; j++ )
+			decRep += epsilon[(i-1)*L+j] * (long)pow(2, L-1-j);
+		T[decRep] = i;
+	}
+	for ( i=Q+1; i<=Q+K; i++ ) { 	/* PROCESS BLOCKS */
+		decRep = 0;
+		for ( j=0; j<L; j++ )
+			decRep += epsilon[(i-1)*L+j] * (long)pow(2, L-1-j);
+		sum += log(i - T[decRep])/log(2);
+		T[decRep] = i;
+	}
+	phi = (double)(sum/(double)K);
+
+	fprintf(stats[TEST_UNIVERSAL], "\t\tUNIVERSAL STATISTICAL TEST\n");
+	fprintf(stats[TEST_UNIVERSAL], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_UNIVERSAL], "\t\tCOMPUTATIONAL INFORMATION:\n");
+	fprintf(stats[TEST_UNIVERSAL], "\t\t--------------------------------------------\n");
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(a) L         = %d\n", L);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(b) Q         = %d\n", Q);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(c) K         = %d\n", K);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(d) sum       = %f\n", sum);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(e) sigma     = %f\n", sigma);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(f) variance  = %f\n", variance[L]);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(g) exp_value = %f\n", expected_value[L]);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(h) phi       = %f\n", phi);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t(i) WARNING:  %d bits were discarded.\n", n-(Q+K)*L);
+	fprintf(stats[TEST_UNIVERSAL], "\t\t-----------------------------------------\n");
+
+	arg = fabs(phi-expected_value[L])/(sqrt2 * sigma);
+	p_value = erfc(arg);
+	if ( isNegative(p_value) || isGreaterThanOne(p_value) )
+		fprintf(stats[TEST_UNIVERSAL], "\t\tWARNING:  P_VALUE IS OUT OF RANGE\n");
+
+	fprintf(stats[TEST_UNIVERSAL], "%s\t\tp_value = %f\n\n", p_value < ALPHA ? "FAILURE" : "SUCCESS", p_value);    
+	fprintf(results[TEST_UNIVERSAL], "%f\n", p_value);
+	
+	free(T);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/utilities.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,636 @@
+/*
+* Portions Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+* The original NIST Statistical Test Suite code is placed in public domain.
+* (http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html) 
+* 
+* This software was developed at the National Institute of Standards and Technology by 
+* employees of the Federal Government in the course of their official duties. Pursuant
+* to title 17 Section 105 of the United States Code this software is not subject to 
+* copyright protection and is in the public domain. The NIST Statistical Test Suite is
+* an experimental system. NIST assumes no responsibility whatsoever for its use by other 
+* parties, and makes no guarantees, expressed or implied, about its quality, reliability, 
+* or any other characteristic. We would appreciate acknowledgment if the software is used.
+*/
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+U T I L I T I E S
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+#include "openc.h"
+#include "../include/externs.h"
+#include "../include/utilities.h"
+#include "../include/generators.h"
+#include "../include/stat_fncs.h"
+
+
+TBuf8<KMaxFileName> gLogFilePath;
+TInt                gTemplateIndex = 1;
+
+bool ConvertToAperiodicBits(BitSequence aSequence[32], long value);
+
+
+int
+displayGeneratorOptions()
+{
+	int		option = 0;
+
+	printf("           G E N E R A T O R    S E L E C T I O N \n");
+	printf("           ______________________________________\n\n");
+	printf("    [0] Input File                 [1] Linear Congruential\n");
+	printf("    [2] Quadratic Congruential I   [3] Quadratic Congruential II\n");
+	printf("    [4] Cubic Congruential         [5] XOR\n");
+	printf("    [6] Modular Exponentiation     [7] Blum-Blum-Shub\n");
+	printf("    [8] Micali-Schnorr             [9] G Using SHA-1\n\n");
+	printf("   Enter Choice: ");
+	scanf("%d", &option);
+	printf("\n\n");
+
+	return option;
+}
+
+
+int
+generatorOptions(char** streamFile)
+{
+	char	file[200];
+	int		option = NUMOFGENERATORS+1; 
+	
+	while ( (option < 0) || (option > NUMOFGENERATORS) ) {
+		option = displayGeneratorOptions();
+		switch( option ) {
+			case 0:
+				printf("\t\tUser Prescribed Input File: ");
+				scanf("%s", file);
+				*streamFile = (char*)calloc(200, sizeof(char));
+				sprintf(*streamFile, "%s", file);
+				printf("\n");
+				break;
+			case 1:
+				*streamFile = "Linear-Congruential";
+				break;
+			case 2:
+				*streamFile = "Quadratic-Congruential-1";
+				break;
+			case 3:
+				*streamFile = "Quadratic-Congruential-2";
+				break;
+			case 4:
+				*streamFile = "Cubic-Congruential";
+				break;
+			case 5:
+				*streamFile = "XOR";
+				break;
+			case 6:
+				*streamFile = "Modular-Exponentiation";
+				break;
+			case 7:
+				*streamFile = "Blum-Blum-Shub";
+				break;
+			case 8:
+				*streamFile = "Micali-Schnorr";
+				break;
+			case 9:
+				*streamFile = "G using SHA-1";
+				break;
+				
+			/* INTRODUCE NEW PRNG NAMES HERE */
+			/*
+			case 10:  *streamFile = "myNewPRNG";
+				break;
+			*/
+			default:
+				printf("Error:  Out of range - Try again!\n");
+				break;
+		}
+	}
+	return option;
+}
+
+
+void
+chooseTests()
+{
+	int		i;
+	
+	printf("                S T A T I S T I C A L   T E S T S\n");
+	printf("                _________________________________\n\n");
+	printf("    [01] Frequency                       [02] Block Frequency\n");
+	printf("    [03] Cumulative Sums                 [04] Runs\n");
+	printf("    [05] Longest Run of Ones             [06] Rank\n");
+	printf("    [07] Discrete Fourier Transform      [08] Nonperiodic Template Matchings\n");
+	printf("    [09] Overlapping Template Matchings  [10] Universal Statistical\n");
+	printf("    [11] Approximate Entropy             [12] Random Excursions\n");
+	printf("    [13] Random Excursions Variant       [14] Serial\n");
+	printf("    [15] Linear Complexity\n\n");
+	printf("         INSTRUCTIONS\n");
+	printf("            Enter 0 if you DO NOT want to apply all of the\n");
+	printf("            statistical tests to each sequence and 1 if you DO.\n\n");
+	printf("   Enter Choice: ");
+	scanf("%d", &testVector[0]);
+	printf("\n");
+	if ( testVector[0] == 1 )
+	    {
+		for( i=1; i<=NUMOFTESTS; i++ )
+			testVector[i] = 1;
+		
+		// Disable Fast Fourier Transform Test.
+		// NIST has discovered a problem with the Fast Fourier Transform test. 
+		// At this time NIST advises disregarding the results of this test until 
+		// a further update is posted.
+		// Link: http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html
+		//
+		// When the FFT test is fixed remove the following 5 lines.
+		printf(" Please Note: \n");
+		printf(" NIST has discovered a problem with the DFT test and hence the DFT results are invalid currently.\n");
+		printf(" DFT test will be disabled at the momemt in the NIST test suite run \n \n");        
+		testVector[TEST_FFT] = 0; 
+		testVector[0] = 0; 
+	    }
+	else {
+		printf("         INSTRUCTIONS\n");
+		printf("            Enter a 0 or 1 to indicate whether or not the numbered statistical\n");
+		printf("            test should be applied to each sequence.\n\n");
+		printf("      123456789111111\n");
+		printf("               012345\n");
+		printf("      ");
+        for ( i=1; i<=NUMOFTESTS; i++ ) 
+            scanf("%1d", &testVector[i]);
+        printf("\n\n");
+    }
+}
+
+
+void
+fixParameters()
+{
+	int		counter, testid;
+	
+	//  Check to see if any parameterized tests are selected
+	if ( (testVector[TEST_BLOCK_FREQUENCY] != 1) && (testVector[TEST_NONPERIODIC] != 1) && 
+		 (testVector[TEST_OVERLAPPING] != 1) && (testVector[TEST_APEN] != 1) &&
+		 (testVector[TEST_SERIAL] != 1) && (testVector[TEST_LINEARCOMPLEXITY] != 1) )
+			return;
+		
+	do {
+		counter = 1;
+		printf("        P a r a m e t e r   A d j u s t m e n t s\n");
+		printf("        -----------------------------------------\n");
+		if ( testVector[TEST_BLOCK_FREQUENCY] == 1 )
+			printf("    [%d] Block Frequency Test - block length(M):         %d\n", counter++, tp.blockFrequencyBlockLength);
+		if ( testVector[TEST_NONPERIODIC] == 1 )
+			printf("    [%d] NonOverlapping Template Test - block length(m): %d\n", counter++, tp.nonOverlappingTemplateBlockLength);
+		if ( testVector[TEST_OVERLAPPING] == 1 )
+			printf("    [%d] Overlapping Template Test - block length(m):    %d\n", counter++, tp.overlappingTemplateBlockLength);
+		if ( testVector[TEST_APEN] == 1 )
+			printf("    [%d] Approximate Entropy Test - block length(m):     %d\n", counter++, tp.approximateEntropyBlockLength);
+		if ( testVector[TEST_SERIAL] == 1 )
+			printf("    [%d] Serial Test - block length(m):                  %d\n", counter++, tp.serialBlockLength);
+		if ( testVector[TEST_LINEARCOMPLEXITY] == 1 )
+			printf("    [%d] Linear Complexity Test - block length(M):       %d\n", counter++, tp.linearComplexitySequenceLength);
+		printf("\n");
+		printf("   Select Test (0 to continue): ");
+		scanf("%1d", &testid);
+		printf("\n");
+		
+		counter = 0;
+		if ( testVector[TEST_BLOCK_FREQUENCY] == 1 ) {
+			counter++;
+			if ( counter == testid ) {
+				printf("   Enter Block Frequency Test block length: ");
+				scanf("%d", &tp.blockFrequencyBlockLength);
+				printf("\n");
+				continue;
+			}
+		}
+		if ( testVector[TEST_NONPERIODIC] == 1 ) {
+			counter++;
+			if ( counter == testid ) {
+				printf("   Enter NonOverlapping Template Test block Length: ");
+				scanf("%d", &tp.nonOverlappingTemplateBlockLength);
+				printf("\n");
+				continue;
+			}
+		}
+		if ( testVector[TEST_OVERLAPPING] == 1 ) {
+			counter++;
+			if ( counter == testid ) {
+				printf("   Enter Overlapping Template Test block Length: ");
+				scanf("%d", &tp.overlappingTemplateBlockLength);
+				printf("\n");
+				continue;
+			}
+		}
+		if ( testVector[TEST_APEN] == 1 ) {
+			counter++;
+			if ( counter == testid ) {
+				printf("   Enter Approximate Entropy Test block Length: ");
+				scanf("%d", &tp.approximateEntropyBlockLength);
+				printf("\n");
+				continue;
+			}
+		}
+		if ( testVector[TEST_SERIAL] == 1 ) {
+			counter++;
+			if ( counter == testid ) {
+				printf("   Enter Serial Test block Length: ");
+				scanf("%d", &tp.serialBlockLength);
+				printf("\n");
+				continue;
+			}
+		}
+		if ( testVector[TEST_LINEARCOMPLEXITY] == 1 ) {
+			counter++;
+			if ( counter == testid ) {
+				printf("   Enter Linear Complexity Test block Length: ");
+				scanf("%d", &tp.linearComplexitySequenceLength);
+				printf("\n");
+				continue;
+			}
+		}
+	} while ( testid != 0 );
+}
+
+
+void
+fileBasedBitStreams(char *streamFile)
+{
+	FILE	*fp;
+	int		mode;
+	
+	printf("   Input File Format:\n");
+	printf("    [0] ASCII - A sequence of ASCII 0's and 1's\n");
+	printf("    [1] Binary - Each byte in data file contains 8 bits of data\n\n");
+	printf("   Select input mode:  ");
+	scanf("%1d", &mode);
+	printf("\n");
+	if ( mode == 0 ) {
+		if ( (fp = fopen(streamFile, "r")) == NULL ) {
+			printf("ERROR IN FUNCTION fileBasedBitStreams:  file %s could not be opened.\n",  streamFile);
+			exit(-1);
+		}
+		readBinaryDigitsInASCIIFormat(fp, streamFile);
+		fclose(fp);
+	}
+	else if ( mode == 1 ) {
+		if ( (fp = fopen(streamFile, "rb")) == NULL ) {
+			printf("ERROR IN FUNCTION fileBasedBitStreams:  file %s could not be opened.\n", streamFile);
+			exit(-1);
+		}
+		readHexDigitsInBinaryFormat(fp);
+		fclose(fp);
+	}
+}
+
+
+void
+readBinaryDigitsInASCIIFormat(FILE *fp, char *streamFile)
+{
+	int		i, j, num_0s, num_1s, bitsRead, bit;
+	
+	if ( (epsilon = (BitSequence *) calloc(tp.n, sizeof(BitSequence))) == NULL ) {
+		printf("BITSTREAM DEFINITION:  Insufficient memory available.\n");
+		printf("Statistical Testing Aborted!\n");
+		return;
+	}
+	printf("     Statistical Testing In Progress.........\n\n");   
+	for ( i=0; i<tp.numOfBitStreams; i++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		for ( j=0; j<tp.n; j++ ) {
+			if ( fscanf(fp, "%1d", &bit) == EOF ) {
+				printf("ERROR:  Insufficient data in file %s.  %d bits were read.\n", streamFile, bitsRead);
+				fclose(fp);
+				free(epsilon);
+				return;
+			}
+			else {
+				bitsRead++;
+				if ( bit == 0 ) 
+					num_0s++;
+				else 
+					num_1s++;
+				epsilon[j] = (BitSequence)bit;
+			}
+		}
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		nist_test_suite();
+	}
+	free(epsilon);
+}
+
+
+void
+readHexDigitsInBinaryFormat(FILE *fp)
+{
+	int		i, done, num_0s, num_1s, bitsRead;
+	BYTE	buffer[4];
+	
+	if ( (epsilon = (BitSequence *) calloc(tp.n,sizeof(BitSequence))) == NULL ) {
+		printf("BITSTREAM DEFINITION:  Insufficient memory available.\n");
+		return;
+	}
+
+	printf("     Statistical Testing In Progress.........\n\n");   
+	for ( i=0; i<tp.numOfBitStreams; i++ ) {
+		num_0s = 0;
+		num_1s = 0;
+		bitsRead = 0;
+		done = 0;
+		do {
+			if ( fread(buffer, sizeof(unsigned char), 4, fp) != 4 ) {
+				printf("READ ERROR:  Insufficient data in file.\n");
+				free(epsilon);
+				return;
+			}
+			done = convertToBits(buffer, 32, tp.n, &num_0s, &num_1s, &bitsRead);
+		} while ( !done );
+		fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s);
+		
+		nist_test_suite();
+		
+	}
+	free(epsilon);
+}
+
+
+int
+convertToBits(const BYTE *x, int xBitLength, int bitsNeeded, int *num_0s, int *num_1s, int *bitsRead)
+{
+	int		i, j, count, bit;
+	BYTE	mask;
+	int		zeros, ones;
+
+	count = 0;
+	zeros = ones = 0;
+	for ( i=0; i<(xBitLength+7)/8; i++ ) {
+		mask = 0x80;
+		for ( j=0; j<8; j++ ) {
+			if ( *(x+i) & mask ) {
+				bit = 1;
+				(*num_1s)++;
+				ones++;
+			}
+			else {
+				bit = 0;
+				(*num_0s)++;
+				zeros++;
+			}
+			mask >>= 1;
+			epsilon[*bitsRead] = (BitSequence)bit;
+			(*bitsRead)++;
+			if ( *bitsRead == bitsNeeded )
+				return 1;
+			if ( ++count == xBitLength )
+				return 0;
+		}
+	}
+	
+	return 0;
+}
+
+
+void
+openOutputStreams(int option)
+{
+	int		i, numOfBitStreams, numOfOpenFiles = 0;
+	char	freqfn[200], statsDir[200], resultsDir[200];
+    TBuf16<200>      logFilePath;
+    logFilePath.Copy(_L("c:\\nist"));
+
+    printf("      Directory for logs : ");
+    gConsole->Printf(logFilePath);
+    ReadStringFromConsole(logFilePath);
+    gConsole->Printf(_L("\r\n"));
+    gLogFilePath.Copy(logFilePath);
+
+    TBuf8<100> tempName;
+    TBuf<100> directoryName;
+
+    for(i = 1; i <= NUMOFTESTS; ++i)
+        {
+        tempName.Format(_L8("%s\\experiments\\%s\\%s\\"), gLogFilePath.PtrZ(),  generatorDir[option], testNames[i]);
+        directoryName.Copy(tempName);
+        gFileSession.MkDirAll(directoryName);
+        }
+	
+	sprintf(freqfn, "%s\\experiments\\%s\\freq", gLogFilePath.PtrZ(), generatorDir[option]);
+	if ( (freqfp = fopen(freqfn, "w")) == NULL ) {
+		printf("\t\tMAIN:  Could not open freq file: experiments/%s/freq", generatorDir[option]);
+		exit(-1);
+	}
+
+	TBuf8<512> finalAnalysisReport;
+    finalAnalysisReport.Format(_L8("%s\\finalAnalysisReport"), gLogFilePath.PtrZ());
+
+    if ( (summary = fopen((const char *)finalAnalysisReport.PtrZ(), "w")) == NULL ) {
+		printf("\t\tMAIN:  Could not open stats file: %s\\experiments\\%s\\finalAnalysisReport",gLogFilePath.PtrZ(), generatorDir[option]);
+		exit(-1);
+	}
+	
+	for( i=1; i<=NUMOFTESTS; i++ ) {
+		if ( testVector[i] == 1 ) {
+			sprintf(statsDir, "%s\\experiments\\%s\\%s\\stats", gLogFilePath.PtrZ(), generatorDir[option], testNames[i]);
+			sprintf(resultsDir, "%s\\experiments\\%s\\%s\\results", gLogFilePath.PtrZ(), generatorDir[option], testNames[i]);
+			if ( (stats[i] = fopen(statsDir, "w")) == NULL ) {	/* STATISTICS LOG */
+				printf("ERROR: LOG FILES COULD NOT BE OPENED.\n");
+				printf("       MAX # OF OPENED FILES HAS BEEN REACHED = %d\n", numOfOpenFiles);
+				printf("-OR-   THE OUTPUT DIRECTORY DOES NOT EXIST.\n");
+				exit(-1);
+			}
+			else
+				numOfOpenFiles++;
+			if ( (results[i] = fopen(resultsDir, "w")) == NULL ) {	/* P_VALUES LOG   */
+				 printf("ERROR: LOG FILES COULD NOT BE OPENED.\n");
+				 printf("       MAX # OF OPENED FILES HAS BEEN REACHED = %d\n", numOfOpenFiles);
+				 printf("-OR-   THE OUTPUT DIRECTORY DOES NOT EXIST.\n");
+				 exit(-1);
+			}
+			else
+				numOfOpenFiles++;
+		}
+	}
+	printf("   How many bitstreams? ");
+	scanf("%d", &numOfBitStreams);
+	tp.numOfBitStreams = numOfBitStreams;
+	printf("\n");
+}
+
+
+void
+invokeTestSuite(int option, char *streamFile)
+{
+	fprintf(freqfp, "________________________________________________________________________________\n\n");
+	fprintf(freqfp, "\t\tALPHA = %6.4f\n", ALPHA);
+	fprintf(freqfp, "________________________________________________________________________________\n\n");
+	if ( option != 0 )
+		printf("     Statistical Testing In Progress.........\n\n");
+	switch( option ) {
+		case 0:
+			fileBasedBitStreams(streamFile);
+			break;
+		case 1:
+			lcg();
+			break;
+		case 2:
+			quadRes1();
+			break;
+		case 3:
+			quadRes2();
+			break;
+		case 4:
+			cubicRes();
+			break;
+		case 5:
+			exclusiveOR();
+			break;
+		case 6:
+			modExp();
+			break;
+		case 7:
+			bbs();
+			break;
+		case 8:
+			micali_schnorr();
+			break;
+		case 9:
+			SHA1();
+			break;
+		case 10:
+		    HASH_DRBG();
+		    break;
+			
+		/* INTRODUCE NEW PSEUDO RANDOM NUMBER GENERATORS HERE */
+			
+		default:
+			printf("Error in invokeTestSuite!\n");
+			break;
+	}
+	printf("     Statistical Testing Complete!!!!!!!!!!!!\n\n");
+}
+
+
+void
+nist_test_suite()
+{
+	if ( (testVector[0] == 1) || (testVector[TEST_FREQUENCY] == 1) ) 
+		Frequency(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_BLOCK_FREQUENCY] == 1) ) 
+		BlockFrequency(tp.blockFrequencyBlockLength, tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_CUSUM] == 1) )
+		CumulativeSums(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_RUNS] == 1) )
+		Runs(tp.n); 
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_LONGEST_RUN] == 1) )
+		LongestRunOfOnes(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_RANK] == 1) )
+		Rank(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_FFT] == 1) )
+	    {
+        // Disable Fast Fourier Transform Test.
+		// NIST has discovered a problem with the Fast Fourier Transform test. 
+		// At this time NIST advises disregarding the results of this test until 
+		// a further update is posted.
+		// Link: http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html
+		//
+		// When the FFT test is fixed remove the following 3 printf lines and uncomment the 4th line.
+        printf("  Please Note: NIST has discovered a problem with the DFT test and hence\n");
+        printf("  the DFT results are invalid currently.\n");
+        printf("  So all tests except DFT will run until futher notification from NIST \n \n");   
+        //DiscreteFourierTransform(tp.n);
+	    }
+	    	
+	if ( (testVector[0] == 1) || (testVector[TEST_NONPERIODIC] == 1) )
+		NonOverlappingTemplateMatchings(tp.nonOverlappingTemplateBlockLength, tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_OVERLAPPING] == 1) )
+		OverlappingTemplateMatchings(tp.overlappingTemplateBlockLength, tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_UNIVERSAL] == 1) )
+		Universal(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_APEN] == 1) )
+		ApproximateEntropy(tp.approximateEntropyBlockLength, tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_RND_EXCURSION] == 1) )
+		RandomExcursions(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_RND_EXCURSION_VAR] == 1) )
+		RandomExcursionsVariant(tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_SERIAL] == 1) )
+		Serial(tp.serialBlockLength,tp.n);
+	
+	if ( (testVector[0] == 1) || (testVector[TEST_LINEARCOMPLEXITY] == 1) )
+		LinearComplexity(tp.linearComplexitySequenceLength, tp.n);
+}
+
+void GetNextTemplateItem(BitSequence aBitSequence[])
+    {
+    int count = (TInt)pow(2, tp.overlappingTemplateBlockLength);
+    
+    for(bool isSuccess = false; (!isSuccess) && (gTemplateIndex < count); ++gTemplateIndex)
+        {
+        isSuccess = ConvertToAperiodicBits(aBitSequence, gTemplateIndex);
+        }
+    }
+
+
+bool ConvertToAperiodicBits(BitSequence aSequence[32], long value)
+    {
+    int bitMask = 1 << (KMaxBit-1);
+    long count = tp.overlappingTemplateBlockLength;
+    
+    for(int c = 0; c < KMaxBit; c++) 
+        {
+        if (value & bitMask)
+            aSequence[c] = 1;
+        else
+            aSequence[c] = 0;
+        value <<= 1;
+        }
+
+    bool match = false;
+    
+    for(int i = 1; i < count; i++) 
+        {
+        match = false;
+        if ((aSequence[KMaxBit-count]!= aSequence[KMaxBit-1]) && ((aSequence[KMaxBit-count]!= aSequence[KMaxBit-2])||(aSequence[KMaxBit-count+1] != aSequence[KMaxBit-1]))) 
+            {
+            for(int c = KMaxBit-count; c <= (KMaxBit-1)-i; c++) 
+                {
+                if (aSequence[c] != aSequence[c+i]) 
+                    {
+                    match = true;
+                    break;
+                    }
+                }
+            }
+        
+        if (!match) 
+            {
+            break;
+            }
+        }
+
+    return match;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/utils/openc.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,616 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*/
+
+
+//------------------------------------ System Header Files ------------------------------------------------
+#include <e32cons.h>        // ConsoleBase
+//------------------------------------ Local Header Files -------------------------------------------------
+#include "openc.h"
+
+//-------------------------------- Constants, global variables and Macro Definitions ----------------------------------------
+_LIT(KConsoleName, "NIST Test Console");
+CConsoleBase* gConsole = NULL;
+
+
+int PrintToScreen(const char* aString);
+
+const TInt KIntStringLen = 10;
+RFs gFileSession;
+
+enum TDataType
+    {
+    EInteger,
+    EFloat,
+    EUnknownType = 0x10000
+    };
+
+const TInt KMaxReadSize = 50;
+const TInt KMaxScreenBufferSize = 100;
+
+TBuf<KMaxScreenBufferSize> gScreenBuffer;
+
+class GlobalInitilizer
+    {
+public:
+    GlobalInitilizer()
+        {
+        TInt err = gFileSession.Connect();
+
+        if(err != KErrNone)
+            {
+            User::Exit(err);
+            }
+
+        TRAP(err, gConsole = Console::NewL(KConsoleName, TSize(KConsFullScreen,KConsFullScreen)));
+        if(err != KErrNone)
+            {
+            User::Exit(err);
+            }
+        }
+    ~GlobalInitilizer()
+        {
+        gFileSession.Close();
+        delete gConsole;
+        }
+    };
+
+GlobalInitilizer globalObj;
+
+//------------------------------------ Function Definitions -----------------------------------------------
+
+double log(double aSource)
+    {
+    double result = 0.0;
+    Math::Ln(result, aSource);
+    return result;
+    }
+
+double exp(double aSource)
+    {
+    double result = 0.0;
+    Math::Exp(result, aSource);
+    return result;
+    }
+
+double fabs(double aSource)
+    {
+    return (aSource >= 0.0)? aSource: -aSource;
+    }
+
+
+double floor(double aSource)
+    {
+    if(aSource >= 0.0 || aSource == (TInt64)aSource)
+        {
+        return (double)(TInt64)aSource;
+        }
+   
+    return (double)((TInt64)aSource - 1);
+    }
+
+double sqrt(double aSource)
+    {
+    double result = 0.0;
+    Math::Sqrt(result, aSource);
+    return result;
+    }
+
+double pow(double aSource, double aPower)
+    {
+    double result = 0.0;
+    Math::Pow(result, aSource, aPower);
+    return result;
+    }
+
+// Math trigonometric functions
+double sin(double aSource)
+    {
+    double result = 0.0;
+    Math::Sin(result, aSource);
+    return result;
+    }
+
+double cos(double aSource)
+    {
+    double result = 0.0;
+    Math::Cos(result, aSource);
+    return result;
+    }
+
+// Stdio functions
+int printf(const char* aFormatString, ...)
+    {
+    TUint length = User::StringLength((TUint8*)aFormatString) + 100;
+    HBufC8* buffer = HBufC8::New(length);
+    if(NULL == buffer)
+        {
+        return KErrNoMemory;
+        }
+    
+    TPtr8 targetPtr = buffer->Des();
+    TPtrC8 formatPtr((TUint8*)aFormatString);
+
+    VA_LIST list;
+    VA_START(list, aFormatString);
+    
+    targetPtr.FormatList(formatPtr, list);
+    
+    PrintToScreen((const char*)targetPtr.PtrZ());
+
+    delete buffer;
+
+    return targetPtr.Length();
+    }
+
+int puts(const char* aString)
+    {
+    int ret = PrintToScreen(aString);
+    gConsole->Printf(_L("\n"));
+    
+    return ret;
+    }
+
+int putchar(int aChar)
+    {
+    gConsole->Printf(_L("%c"), aChar);
+    return aChar;
+    }
+
+char* strcpy(char* aDst, const char* aSrc)
+    {
+    char* cp = aDst;
+
+    while((*cp++ = *aSrc++) != 0)
+        ; // Copy src over dst
+
+    return(aDst);
+    }
+
+int scanf(const char* aFormatString, ...)
+    {
+    TDataType type = EUnknownType;
+    TBool byteRead = EFalse;
+    
+    if(Mem::Compare((const unsigned char*)aFormatString, 2, (const unsigned char*)"%d", 2) == 0)
+        {
+        type = EInteger;
+        }
+    else if(Mem::Compare((const unsigned char*)aFormatString, 2, (const unsigned char*)"%f", 2) == 0)
+        {
+        type = EFloat;
+        }
+    else if(Mem::Compare((const unsigned char*)aFormatString, 3, (const unsigned char*)"%1d", 3) == 0)
+        {
+        type = EInteger;
+        byteRead = ETrue;
+        }
+    else
+        {
+        User::Panic(_L("NIST TestSuit Error"), KErrArgument);
+        }
+    
+    if(!byteRead || (gScreenBuffer.Length() == 0))
+        {
+        ReadStringFromConsole(gScreenBuffer);
+        }
+
+    TLex parser(gScreenBuffer);
+    parser.SkipSpace();
+    
+    VA_LIST list;
+    VA_START(list, aFormatString);
+
+    switch(type)
+        {
+        case EInteger:
+            {
+            TInt* ptr = VA_ARG(list, TInt*);
+            if(byteRead)
+                {
+                TChar ch(gScreenBuffer[0]);
+                gScreenBuffer.Delete(0, 1);
+                *ptr = ch.GetNumericValue();
+                }
+            else
+                {
+                parser.Val(*ptr);
+                gScreenBuffer.Zero();
+                }
+            break;
+            }
+        case EFloat:
+            {
+            float* ptr = VA_ARG(list, float*);
+            parser.Val(*ptr);
+            gScreenBuffer.Zero();
+            break;
+            }
+        case EUnknownType:
+            {
+            User::Panic(_L("NIST TestSuit Error"), KErrArgument);
+            }
+        }
+
+    return 1;
+    }
+
+int sprintf(char *aBuffer, const char* aFormatString, ...)
+    {
+    TUint length = User::StringLength((TUint8*)aFormatString) + 100;
+    TPtr8 aTargetPtr((TUint8*)aBuffer, length);
+    TPtrC8 formatPtr((TUint8*)aFormatString);
+
+    VA_LIST list;
+    VA_START(list, aFormatString);
+    
+    aTargetPtr.FormatList(formatPtr, list);
+    aTargetPtr.ZeroTerminate();
+
+    return User::StringLength((TUint8*)aBuffer);;
+    }
+
+int GetFileMode(const char* aModeStr, TFileMode& aFileMode, TBool& aIsAppend)
+    {
+    aIsAppend = EFalse;
+    switch (*aModeStr)
+        {
+        case 'r':
+            aFileMode = EFileRead;
+            break;
+            
+        case 'w':
+            aFileMode = EFileWrite;
+            break;
+            
+        case 'a':
+            aFileMode = EFileWrite;
+            aIsAppend = ETrue;
+            break;
+            
+        default:
+            return KErrArgument;
+        } 
+      
+    return KErrNone;
+    }
+
+FILE *fopen(const char *aFileName, const char *aMode)
+    {
+    TPtrC8 fileNamePtr(reinterpret_cast<const unsigned char*>(aFileName));
+    TFileName fileName;
+    fileName.Copy(fileNamePtr);
+    RFile* file = new RFile;
+    if(NULL == file)
+        {
+        return NULL;
+        }
+
+    TFileMode mode = EFileRead;
+    TBool isAppend = EFalse;
+    GetFileMode(aMode, mode, isAppend);
+    int err = KErrArgument;
+    switch(mode)
+        {
+        case EFileRead:
+            {
+            err = file->Open(gFileSession, fileName, mode);
+            break;
+            }
+        case EFileWrite:
+            {
+            if(isAppend)
+                {
+                err = file->Open(gFileSession, fileName, mode);
+                if(err == KErrNone)
+                    {
+                    TInt offset = 0;
+                    err = file->Seek(ESeekEnd, offset);
+                    break;
+                    }
+                }
+            
+            err = file->Replace(gFileSession, fileName, mode);
+            break;
+            }
+        default:
+            err = KErrArgument;
+        }
+
+    if(KErrNone != err)
+        {
+        file->Close();
+        delete file;
+        file = NULL;
+        }
+    return file;
+    }
+
+
+
+int fclose(FILE *aFp)
+    {
+    if(NULL != aFp)
+        {
+        aFp->Close();
+        delete aFp;
+        }
+    return KErrNone;
+    }
+
+int fprintf(FILE* aFile, const char* aFormatString, ...)
+    {
+    TUint length = User::StringLength((TUint8*)aFormatString) + 100;
+    HBufC8* buffer = HBufC8::New(length);
+    if(NULL == buffer)
+        {
+        return KErrNoMemory;
+        }
+    
+    TPtr8 targetPtr = buffer->Des();
+    TPtrC8 formatPtr((TUint8*)aFormatString);
+
+    VA_LIST list;
+    VA_START(list, aFormatString);
+    
+    targetPtr.FormatList(formatPtr, list);
+    targetPtr.ZeroTerminate();
+    
+    aFile->Write(targetPtr);
+    
+    delete buffer;
+
+    return targetPtr.Length();
+    }
+
+int fscanf(FILE* aFp, const char * aFormatString, ...)
+    {
+    TDataType type = EUnknownType;
+    TBool byteRead = EFalse;
+    
+    if(Mem::Compare((const unsigned char*)aFormatString, 2, (const unsigned char*)"%d", 2) == 0)
+        {
+        type = EInteger;
+        }
+    else if(Mem::Compare((const unsigned char*)aFormatString, 2, (const unsigned char*)"%f", 2) == 0)
+        {
+        type = EFloat;
+        }
+    else if(Mem::Compare((const unsigned char*)aFormatString, 3, (const unsigned char*)"%1d", 3) == 0)
+        {
+        type = EInteger;
+        byteRead = ETrue;
+        }
+    else
+        {
+        User::Panic(_L("NIST TestSuit Error"), KErrArgument);
+        }
+    
+    TInt initialOffset = 0;
+    aFp->Seek(ESeekCurrent, initialOffset);
+    TBuf8<KMaxReadSize + 1> readBuffer;
+    aFp->Read(readBuffer, KMaxReadSize);
+    readBuffer.ZeroTerminate();
+    TLex8 parser(readBuffer);
+    parser.SkipSpace();
+    
+    VA_LIST list;
+    VA_START(list, aFormatString);
+
+    switch(type)
+        {
+        case EInteger:
+            {
+            TInt* ptr = VA_ARG(list, TInt*);
+            TChar ch = parser.Peek();
+            
+            if(!ch.IsDigit())
+                {
+                break;
+                }
+            
+            if(byteRead)
+                {
+                ch = parser.Get();
+                *ptr = ch.GetNumericValue();
+                }
+            else
+                {
+                parser.Val(*ptr);
+                }
+
+            break;
+            }
+        case EFloat:
+            {
+            float* ptr = VA_ARG(list, float*);
+            parser.Val(*ptr);
+            break;
+            }
+        case EUnknownType:
+            {
+            User::Panic(_L("NIST TestSuit Error"), KErrArgument);
+            }
+        }
+
+    TInt len = initialOffset + parser.Offset();
+    aFp->Seek(ESeekStart, len);
+    
+    return 1;
+    }
+
+TUint32 fread(void* aPtr, TUint32 aSize, TUint32 aCount, FILE* aFile)
+    {
+    TUint32 size = aSize * aCount;
+    TPtr8 dataPtr((TUint8*)aPtr, size);
+    TInt err = aFile->Read(dataPtr);
+    if(KErrNone != err)
+        {
+        size = (TUint32)dataPtr.Length();
+        }
+    return size;
+    }
+
+int fseek(FILE* aFile, long aOffset, int aWhence)
+    {
+    int ret = KErrNone;
+    int fileOffset = aOffset;
+    switch(aWhence)
+        {
+        case SEEK_SET:
+            {
+            ret = aFile->Seek(ESeekStart, fileOffset);
+            break;
+            }
+        case SEEK_CUR:
+            {
+            ret = aFile->Seek(ESeekCurrent, fileOffset);
+            break;
+            }
+        case SEEK_END:
+            {
+            ret = aFile->Seek(ESeekEnd, fileOffset);
+            break;
+            }
+        default:
+            User::Panic(_L("NIST TestSuit Error"), KErrArgument);
+        }
+    
+    return ret;
+    }
+
+
+
+int fflush(FILE *aFile)
+    {
+    TInt err = aFile->Flush();
+    if(err != KErrNone)
+        {
+        err = EOF;
+        }
+    return err;
+    }
+
+
+// Conio functions
+void* calloc(TUint32 aElementCount, TUint32 aSize)
+    {
+    aSize *= aElementCount;
+    return User::AllocZ(aSize);
+    }
+
+void free(void *aMemory)
+    {
+    User::Free(aMemory);
+    }
+
+TBool IsCharacterKey(TKeyCode aKey)
+    {
+    if(aKey > EKeyEscape && aKey < EKeyDelete)
+        {
+        return ETrue;
+        }
+    
+    return EFalse;
+    }
+
+_LIT(KLineBreaker, "\r\n");
+
+void ReadStringFromConsole(TDes& aString)
+    {
+    // This infinte loop terminates when user hits an "enter" key
+    FOREVER
+        {
+        // Get a key(character) from the console
+        TKeyCode ch = gConsole->Getch();
+        
+        switch(ch)
+            {
+            case EKeyEnter:
+                {
+                if(aString.Length() == 0)
+                    {
+                    break;// At least one character should be read.
+                    }
+                gConsole->Printf(KLineBreaker);
+                return;
+                }
+            case EKeyBackspace:
+                {
+                if(0 != aString.Length())
+                    {
+                    // Back-space only takes the cursor one position back
+                    // So to delete a character blank-space is inserted at
+                    // that position and later cursor is again adjusted.
+                    gConsole->Printf(_L("%c%c%c"), EKeyBackspace, 
+                                                   EKeySpace, 
+                                                   EKeyBackspace);
+                    // Delete the character from the target string also. 
+                    aString.Delete(aString.Length() - 1, 1);
+                    }
+                break;
+                }
+            default:
+                {
+                TInt maxBufferLength = aString.MaxLength();
+                // IsCharacterKey will return true if ch is a displayable
+                // character else it will return false.
+                if(IsCharacterKey(ch) && aString.Length() != maxBufferLength)
+                    {
+                    gConsole->Printf(_L("%c"), ch);
+                    aString.Append(ch);
+                    }
+                }
+            }
+        }
+    }
+  
+TInt ReadIntL(TInt& aValue)
+    {
+    TBuf<KIntStringLen> string;
+    ReadStringFromConsole(string);
+    TLex lexObj(string);
+    return lexObj.Val(aValue);
+    }
+
+int PrintToScreen(const char* aString)
+    {
+    TUint length = User::StringLength((TUint8*)aString);
+    HBufC* buffer = HBufC::New(length);
+    if(NULL == buffer)
+        {
+        return EOF;
+        }
+    
+    TPtr targetPtr = buffer->Des();
+
+    TPtrC8 stringPtr((TUint8*)aString);
+
+    targetPtr.Copy(stringPtr);
+    gConsole->Printf(targetPtr);
+    
+    delete buffer;
+    
+    return KErrNone;
+    }
+
+void exit ( int status )
+    {
+    User::Exit(status);
+    for(;;){} // So that GCC compiler don't complain about noreturn function returns.
+    }
+
+//------------------------------------------  E  O  F -----------------------------------------------------
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/src/utils/qsort.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,203 @@
+/*
+* Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:
+* Map ANSI bsearch and qsort onto EPOC32 functions 
+*/
+
+#include <e32std.h>
+#include "openc.h"
+
+NONSHARABLE_CLASS(TAnsiKey) : public TKey
+	{
+public:
+	TAnsiKey(const TAny* key, const TAny* base, TInt length, TInt (*compar)(const TAny*, const TAny*))
+		: iSearchKey(key), iCmp(compar)
+		{ SetPtr(base); iKeyLength=length; }
+
+	virtual TInt Compare(TInt aLeft,TInt aRight) const;
+	virtual TAny *At(TInt anIndex) const;
+private:
+	const TAny* iSearchKey;
+	TInt (*iCmp)(const TAny*, const TAny*);
+	};
+
+TInt TAnsiKey::Compare (TInt aLeft,TInt aRight) const
+	{
+	if (aRight==KIndexPtr)
+		return (*iCmp)(At(aLeft),iSearchKey);
+	else
+		return (*iCmp)(At(aLeft),At(aRight));
+	}
+
+TAny* TAnsiKey::At (TInt aPos) const
+	{
+	return (TUint8*)iPtr+(aPos*iKeyLength);
+	}
+
+NONSHARABLE_CLASS(TAnsiSwap) : public TSwap
+	{
+public:
+	TAnsiSwap(const TAny* base, TInt length) : iPtr(base), iLength(length) {}
+
+	virtual void Swap(TInt aLeft,TInt aRight) const;
+private:
+	TUint8* At(TInt aPos) const {return (TUint8*)iPtr+(aPos*iLength);}
+
+	const TAny* iPtr;
+	TInt  iLength;
+	};
+
+void TAnsiSwap::Swap(TInt aLeft,TInt aRight) const
+	{
+	TUint8* left=At(aLeft);
+	TUint8* right=At(aRight);
+	TUint8 tmp;
+
+	for (TInt i=iLength; i>0; i--)
+		{
+		tmp=*left;
+		*left++=*right;
+		*right++=tmp;
+		}
+	}
+
+/*
+FUNCTION
+<<bsearch>>---binary search
+
+INDEX
+	bsearch
+
+ANSI_SYNOPSIS
+	#include <stdlib.h>
+	void *bsearch(const void *<[key]>, const void *<[base]>,
+		size_t <[nmemb]>, size_t <[size]>,
+		int (*<[compar]>)(const void *, const void *));
+
+TRAD_SYNOPSIS
+	#include <stdlib.h>
+	char *bsearch(<[key]>, <[base]>, <[nmemb]>, <[size]>, <[compar]>)
+	char *<[key]>;
+	char *<[base]>;
+	size_t <[nmemb]>, <[size]>;
+	int (*<[compar]>)();
+
+DESCRIPTION
+<<bsearch>> searches an array beginning at <[base]> for any element
+that matches <[key]>, using binary search.  <[nmemb]> is the element
+count of the array; <[size]> is the size of each element.
+
+The array must be sorted in ascending order with respect to the
+comparison function <[compar]> (which you supply as the last argument of
+<<bsearch>>).
+
+You must define the comparison function <<(*<[compar]>)>> to have two
+arguments; its result must be negative if the first argument is
+less than the second, zero if the two arguments match, and
+positive if the first argument is greater than the second (where
+``less than'' and ``greater than'' refer to whatever arbitrary
+ordering is appropriate).
+
+RETURNS
+Returns a pointer to an element of <[array]> that matches <[key]>.  If
+more than one matching element is available, the result may point to
+any of them. Returns NULL if no matching element is found.
+
+PORTABILITY
+<<bsearch>> is ANSI.
+
+No supporting OS subroutines are required.
+*/
+
+/**
+searches an array beginning at <[base]> for any element
+that matches <[key]>, using binary search
+@return a pointer to an element of <[array]> that matches <[key]>.  If
+more than one matching element is available, the result may point to
+any of them. Returns NULL if no matching element is found.
+@param key
+@param base
+@param nmemb
+@param size
+*/
+void* bsearch (const void* key, const void* base, TUint32 nmemb, TUint32 size,
+	int (*compar)(const void*, const void*))
+	{
+	TAnsiKey searchMe(key, base, size, compar);
+	TInt result=KIndexPtr;
+	TInt r=User::BinarySearch(nmemb, searchMe, result);
+	if (r==0)
+		return searchMe.At(result);
+	else
+		return NULL;
+	}
+
+/*
+FUNCTION
+<<qsort>>---sort an array
+
+INDEX
+	qsort
+
+ANSI_SYNOPSIS
+	#include <stdlib.h>
+	void qsort(void *<[base]>, size_t <[nmemb]>, size_t <[size]>,
+		   int (*<[compar]>)(const void *, const void *) );
+
+TRAD_SYNOPSIS
+	#include <stdlib.h>
+	qsort(<[base]>, <[nmemb]>, <[size]>, <[compar]> )
+	char *<[base]>;
+	size_t <[nmemb]>;
+	size_t <[size]>;
+	int (*<[compar]>)();
+
+DESCRIPTION
+<<qsort>> sorts an array (beginning at <[base]>) of <[nmemb]> objects.
+<[size]> describes the size of each element of the array.
+
+You must supply a pointer to a comparison function, using the argument
+shown as <[compar]>.  (This permits sorting objects of unknown
+properties.)  Define the comparison function to accept two arguments,
+each a pointer to an element of the array starting at <[base]>.  The
+result of <<(*<[compar]>)>> must be negative if the first argument is
+less than the second, zero if the two arguments match, and positive if
+the first argument is greater than the second (where ``less than'' and
+``greater than'' refer to whatever arbitrary ordering is appropriate).
+
+The array is sorted in place; that is, when <<qsort>> returns, the
+array elements beginning at <[base]> have been reordered.
+
+RETURNS
+<<qsort>> does not return a result.
+
+PORTABILITY
+<<qsort>> is required by ANSI (without specifying the sorting algorithm).
+*/
+
+/**
+Sort an array.
+@param base 
+@param nmemb
+@param size describes the size of each element of the array
+*/
+void qsort (void* base, TUint32 nmemb, TUint32 size,
+	int (*compar)(const void*, const void*))
+	{
+	TAnsiKey  searchMe(NULL, base, size, compar);
+	TAnsiSwap swapUs(base,size);
+	User::QuickSort(nmemb, searchMe, swapUs);
+	return;
+	}
+
Binary file kerneltest/e32utils/nistsecurerng/testdata/testdata.zip has changed
--- a/kerneltest/f32test/filesystem/fat/t_mount.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/f32test/filesystem/fat/t_mount.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -629,12 +629,12 @@
     bDriveFinalised = DoCheckVolumeFinalised(gDriveNum);
     test(!bDriveFinalised); //-- the volume has become "unfinalised"
 
-    //-- 2.1 open a file, try to finalise; Shall dail with KErrInUse
+    //-- 2.1 open a file, try to finalise; This should be OK
     nRes = file.Replace(TheFs, KFileName, EFileWrite | EFileRead);
     test_KErrNone(nRes);
 
     nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
-    test(nRes==KErrInUse); //-- can't finalise drives with opened objects
+    test_KErrNone(nRes);
 
     file.Close();
 
--- a/kerneltest/f32test/group/t_misc.mmp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/f32test/group/t_misc.mmp	Wed Sep 15 13:42:27 2010 +0300
@@ -21,6 +21,7 @@
 SOURCE          t_misc.cpp
 SOURCE          t_main.cpp
 SOURCEPATH      ../fileutils/src
+SOURCE          f32_test_utils.cpp
 SOURCE          t_chlffs.cpp
 
 LIBRARY         euser.lib efsrv.lib hal.lib
--- a/kerneltest/f32test/server/t_fsys.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/f32test/server/t_fsys.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -20,6 +20,7 @@
 #include <f32file.h>
 #include <f32file_private.h>
 #include <e32test.h>
+#include <e32math.h>
 #include "t_server.h"
 #include "fat_utils.h"
 #include "filesystem_fat.h"
@@ -27,26 +28,68 @@
 using namespace Fat_Test_Utils;
 
 RTest test(_L("T_FSYS"));
+static TInt64   gRndSeed;
 
+_LIT(KTestFsy,  "T_TFSYS");
+_LIT(KTestFsy2, "T_TFSYS2");
+_LIT(KTestFsy3, "T_TFSYS3");
+
+_LIT(KTestFsName,  "Test");
+_LIT(KTestFsName2, "Test2");
+_LIT(KTestFsName3, "Test3");
+
+
+
+//---------------------------------------------------
+
+
+void InitGlobals()
+{
+    //-- initialise random generator 
+    gRndSeed = 0xf73c1ab;
+    Math::Rand(gRndSeed);
+}
+
+//---------------------------------------------------
+void DestroyGlobals()
+{
+}
+
+//---------------------------------------------------
 static void TestFileSystemNames()
     {
-    test.Next(_L("Read file system names for all drives"));
+    test.Next(_L("TestFileSystemNames(). Read file system names for all drives\n"));
     TFullName name;
-    TInt r;
-    for(TInt i=EDriveA;i<KMaxDrives;++i)
+    TBuf<60>  buf;
+    TInt nRes;
+
+    TDriveList drvList;
+    nRes = TheFs.DriveList(drvList);
+    test_KErrNone(nRes);
+
+    for(TInt i=0; i<KMaxDrives; ++i)
         {
-        r=TheFs.FileSystemName(name,i);
-        test(r==KErrNone || r==KErrNotFound);
-        TChar c;
-        r=RFs::DriveToChar(i,c);
-        test(r==KErrNone);
-        if(name.Length())       
-            test.Printf(_L("File System Name on drive %c is %S\n"),(char)c,&name);
+        buf.Format(_L("drv %C: att:0x%02x"), 'A'+i, drvList[i]);
+        
+        nRes = TheFs.FileSystemName(name, i);
+        test_Value(nRes, nRes == KErrNone || nRes==KErrNotFound);
+        
+        if(nRes == KErrNone)
+            {
+            buf.AppendFormat(_L(" Mounted FS:%S"), &name);
+            }
         else
-            test.Printf(_L("No file system on drive %c\n"),(char)c);
+            {
+            buf.Append(_L(" Mounted FS:"));
+            }
+
+        buf.Append(_L("\n"));
+        test.Printf(buf);
         }
+    
     }
 
+//---------------------------------------------------
 static void CheckDismount(TDesC& aFs,TInt aDrive)
     {
 
@@ -55,10 +98,10 @@
     TInt r;
     TFullName oldSess, newSess;
     r=TheFs.SessionPath(oldSess);
-    test(r==KErrNone);
+    test_KErrNone(r);
     TChar c;
     r=TheFs.DriveToChar(aDrive,c);
-    test(r==KErrNone);
+    test_KErrNone(r);
     newSess.Append(c);
     newSess.Append(':');
     newSess.Append('\\');
@@ -66,60 +109,60 @@
     TBuf<128> b;
     TDriveInfo di;
     r=TheFs.Drive(di,aDrive);
-    test(r==KErrNone);
-    b.Format(_L("Test dismounting of test file system on %c: (DrvAtt:%x MedAtt:%x)"),(TUint)c,di.iDriveAtt,di.iMediaAtt);
+    test_KErrNone(r);
+    b.Format(_L("Test dismounting of test file system on %c: (DrvAtt:%x MedAtt:%x)\n"),(TUint)c,di.iDriveAtt,di.iMediaAtt);
     test.Next(b);
     
     // Test cannot dismount on rom drive
-    test.Next(_L("Test cannot dismount on Rom drive"));
+    test.Next(_L("Test cannot dismount on Rom drive\n"));
     TFullName zName;
     r=TheFs.FileSystemName(zName,EDriveZ);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r=TheFs.DismountFileSystem(zName,EDriveZ);
-    test.Printf(_L("r=%d"),r);
+    test.Printf(_L("r=%d\n"),r);
     // NB if paging is enabled on a ROFS partition which is part of the composite file system then the 
     // likelihood is that there will be a at least one file clamped: in this case there error will be KErrInUse
-    test(r==KErrAccessDenied || r==KErrInUse);
+    test_Value(r, r == KErrAccessDenied || r==KErrInUse);
 
     // Test cannot dismount on wrong drive
-    test.Next(_L("Test cannot dismount on wrong drive"));
+    test.Next(_L("Test cannot dismount on wrong drive\n"));
     r=TheFs.DismountFileSystem(aFs,EDriveA);
-    test(r==KErrNotReady);
+    test_Value(r, r == KErrNotReady);
 
     // Test cannot dismount with wrong name
-    test.Next(_L("Test cannot dismount with wrong file system name"));
+    test.Next(_L("Test cannot dismount with wrong file system name\n"));
     r=TheFs.DismountFileSystem(_L("abc"),aDrive);
-    test(r==KErrNotFound);
+    test_Value(r, r == KErrNotFound);
  
     // Test cannot dismount with a file open
-    test.Next(_L("Test cannot dismount with a file open"));
+    test.Next(_L("Test cannot dismount with a file open\n"));
     r=TheFs.SetSessionPath(newSess);
     RFile file;
     r=file.Replace(TheFs,_L("abc"),EFileShareAny);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r=TheFs.SessionPath(newSess);
     TBool open;
     r=TheFs.IsFileOpen(_L("abc"),open);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test(open);
     r=TheFs.DismountFileSystem(aFs,aDrive);
-    test(r==KErrInUse);
+    test_Value(r, r == KErrInUse);
     file.Close();
 
     // Now test dismount works
-    test.Next(_L("Test dismounts OK"));
+    test.Next(_L("Test dismounts OK\n"));
     r=TheFs.DismountFileSystem(aFs,aDrive);
     if(r!=KErrNone)
         {
-        test.Printf(_L("Error = %d"),r);    
+        test.Printf(_L("Error = %d\n"),r);    
         test(EFalse);
         }
     TFullName n;
     r=TheFs.FileSystemName(n,aDrive);
-    test(r==KErrNone || r==KErrNotFound);
+    test_Value(r, r == KErrNone || r==KErrNotFound);
     test(!n.Length());
     r=file.Replace(TheFs,_L("abc"),EFileShareAny);
-    test(r==KErrNotReady);
+    test_Value(r, r == KErrNotReady);
     file.Close();
 
     r=TheFs.MountFileSystem(aFs,aDrive);
@@ -129,47 +172,55 @@
         test(EFalse);
         }
     r=TheFs.FileSystemName(n,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test(n.Compare(aFs)==0);
     r=file.Replace(TheFs,_L("abc"),EFileShareAny); // ??? bang
-    test(r==KErrNone);
+    test_KErrNone(r);
     file.Close();
     r=TheFs.SetSessionPath(oldSess);
-    test(r==KErrNone);
+    test_KErrNone(r);
     }
 
 static void TestDismountFileSystem(TInt aDrive)
     {
-
+    test.Next(_L("TestDismountFileSystem()\n"));
     TInt r;
     TFullName name;
     r=TheFs.FileSystemName(name,aDrive);
-    test(r==KErrNone || r==KErrNotFound);
+    test_Value(r, r == KErrNone || r==KErrNotFound);
     if(name.Length())
         CheckDismount(name,aDrive);
     }
 
-#if defined(__EPOC32__)
-static void TestFileSystem(TInt aDrive)
+//---------------------------------------------------
 //
 // Mount a new CTestFileSystem on the drive under test
 //
+static void TestFileSystem(TInt aDrive)
     {
+    test.Next(_L("TestFileSystem()\n"));
+
+    if(Is_Win32(TheFs, aDrive))
+        {
+        test.Printf(_L("Can't test on a simulated drive, skipping!\n"));
+        return;
+        }
+
     TBuf<64> b;
     TChar c;
     TInt r=TheFs.DriveToChar(aDrive,c);
-    test(r==KErrNone);
+    test_KErrNone(r);
     TDriveInfo di;
     r=TheFs.Drive(di,aDrive);
-    test(r==KErrNone);
-    b.Format(_L("Test mounting of test file system on %c: (DrvAtt:%x MedAtt:%x)"),(TUint)c,di.iDriveAtt,di.iMediaAtt);
+    test_KErrNone(r);
+    b.Format(_L("Test mounting of test file system on %c: (DrvAtt:%x MedAtt:%x)\n"),(TUint)c,di.iDriveAtt,di.iMediaAtt);
     test.Next(b);
 
-    test.Next(_L("Test mounting of test file system"));
-    r=TheFs.AddFileSystem(_L("T_TFSYS"));
+    test.Next(_L("Test mounting of test file system\n"));
+    r=TheFs.AddFileSystem(KTestFsy);
     if(r!=KErrNone && r!=KErrAlreadyExists)
         {
-        test.Printf(_L("error=%d"),r);
+        test.Printf(_L("error=%d\n"),r);
         test(EFalse);
         }
 
@@ -177,71 +228,72 @@
     r=TheFs.FileSystemName(oldFs,aDrive);
 //  TFileName oldFs;
 //  r=TheFs.FileSystemName(oldFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r=TheFs.DismountFileSystem(oldFs,aDrive);
     if(r!=KErrNone)
         {
-        test.Printf(_L("Error = %d"),r);    
+        test.Printf(_L("Error = %d\n"),r);    
         test(EFalse);
         }
-    r=TheFs.MountFileSystem(_L("Test"),aDrive);
-    test(r==KErrNone);
+    r=TheFs.MountFileSystem(KTestFsName,aDrive);
+    test_KErrNone(r);
 
     TFileName newFs;
     r=TheFs.FileSystemName(newFs,aDrive);
-    test(r==KErrNone);
-    test(newFs.Compare(_L("Test"))==0);
+    test_KErrNone(r);
+    test(newFs.Compare(KTestFsName)==0);
 
     // Check attributes
     TDriveInfo info;
     r=TheFs.Drive(info,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
  
-    test.Printf(_L("iType=%d,iConnectionBusType=%d,iDriveAtt=%x,iMediaAtt=%x\n"),(TUint)info.iType,\
-        (TUint)info.iConnectionBusType,info.iDriveAtt,info.iMediaAtt);
+    test.Printf(_L("iType=%d,iConnectionBusType=%d,iDriveAtt=%x,iMediaAtt=%x\n"),(TUint)info.iType, (TUint)info.iConnectionBusType,info.iDriveAtt,info.iMediaAtt);
 
     //Try to remove filesystem without dismounting.
-    r=TheFs.RemoveFileSystem(_L("Test"));
+    r=TheFs.RemoveFileSystem(KTestFsName);
     if(r!=KErrInUse)
         {
-        test.Printf(_L("error=%d"),r);
+        test.Printf(_L("error=%d\n"),r);
         test(EFalse);
         }
     r=TheFs.FileSystemName(newFs,aDrive);
-    test(r==KErrNone);
-    test(newFs.Compare(_L("Test"))==0);
+    test_KErrNone(r);
+    test(newFs.Compare(KTestFsName)==0);
 
     r=TheFs.DismountFileSystem(newFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
 
     r=TheFs.MountFileSystem(oldFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     }
-#endif
 
+//---------------------------------------------------
 static void TestMountInvalidDrive()
-//
-// Attempt to mount FAT on non-local drive
     {
-    test.Start(_L("TestMountInvalidDrive"));
+    test.Next(_L("TestMountInvalidDrive(). Try mounting FS on an invalid drive\n"));
 
-    TInt r;
+    //-- 1. find an invalid drive
+    TInt drv = 0;
+    TDriveList drvList;
+    
+    TInt nRes = TheFs.DriveList(drvList);
+    test_KErrNone(nRes);
 
-    test.Next(_L("Adding EFAT"));
-#ifdef __WINS__
-    _LIT(KFsNm, "EFAT32");
-#else
-    _LIT(KFsNm, "ELOCAL");
-#endif
+    for(drv =0; drv<KMaxDrives; ++drv)
+        {
+        if(!drvList[drv])
+            break;
+        }
 
-    r = TheFs.AddFileSystem(KFsNm);
-    test.Printf(_L("afs: r = %d\n"), r);
-    test(r == KErrNone || r == KErrAlreadyExists);
-    test.Next(_L("mounting FAT on drive R"));
-    r = TheFs.MountFileSystem(KFileSystemName_FAT, EDriveR);
-    test(r == KErrArgument);
+    test.Printf(_L("Try mounting a test FS onto drive:%C:\n"), 'A'+drv);
+
+    nRes = TheFs.AddFileSystem(KTestFsy);
+    test_Value(nRes, nRes == KErrNone || nRes == KErrAlreadyExists);
+
+    nRes = TheFs.MountFileSystem(KTestFsName, drv);
+    test_Value(nRes, nRes == KErrArgument);
     
-    test.End();
     }
 
 // Additional step for INC083446: Corrupted miniSD not detected as corrupted by phone 
@@ -256,48 +308,48 @@
     TBuf<64> b;
     TChar c;
     TInt r=TheFs.DriveToChar(aDrive,c);
-    test(r==KErrNone);
+    test_KErrNone(r);
     TDriveInfo di;
     r=TheFs.Drive(di,aDrive);
-    test(r==KErrNone);
-    b.Format(_L("Test mounting of test file system on %c: (DrvAtt:%x MedAtt:%x)"),(TUint)c,di.iDriveAtt,di.iMediaAtt);
+    test_KErrNone(r);
+    b.Format(_L("Test mounting of test file system on %c: (DrvAtt:%x MedAtt:%x)\n"),(TUint)c,di.iDriveAtt,di.iMediaAtt);
     test.Next(b);
 
-    test.Next(_L("Test mounting of test file system"));
-    r=TheFs.AddFileSystem(_L("T_TFSYS2"));
+    test.Next(_L("Test mounting of test file system\n"));
+    r=TheFs.AddFileSystem(KTestFsy2);
     if(r!=KErrNone && r!=KErrAlreadyExists)
         {
-        test.Printf(_L("error=%d"),r);
+        test.Printf(_L("error=%d\n"),r);
         test(EFalse);
         }
 
     TFullName oldFs;
     r=TheFs.FileSystemName(oldFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r=TheFs.DismountFileSystem(oldFs,aDrive);
     if(r!=KErrNone)
         {
-        test.Printf(_L("Error = %d"),r);    
+        test.Printf(_L("Error = %d\n"),r);    
         test(EFalse);
         }
-    r=TheFs.MountFileSystem(_L("Test2"),aDrive);
-    test(r == KErrCorrupt);
+    r=TheFs.MountFileSystem(KTestFsName2 ,aDrive);
+    test_Value(r, r == KErrCorrupt);
 
     TFileName newFs;
     r=TheFs.FileSystemName(newFs,aDrive);
-    test(r==KErrNone);
-    test(newFs.Compare(_L("Test2"))==0);
+    test_KErrNone(r);
+    test(newFs.Compare(KTestFsName2)==0);
 
     // Get the number of remounts by checking the volume attributes -
     // T_TFSYS2 hijacks the iBattery member to report back the number of times MountL() has been called
     TDriveInfo info;
     TInt remounts;
     r=TheFs.Drive(info,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test.Printf(_L("iType=%d,iBattery=%d,iDriveAtt=%x,iMediaAtt=%x\n"),(TUint)info.iType,\
         (TUint)info.iBattery,info.iDriveAtt,info.iMediaAtt);
     remounts = (TInt) info.iBattery;
-    test.Printf(_L("Initial remounts = %d"), remounts);
+    test.Printf(_L("Initial remounts = %d\n"), remounts);
 
     // Make the file server attempt to remount the drive by looking for a non-existant DLL
     // The file server should setop trying to remount the driver after KMaxMountFailures attempts
@@ -309,14 +361,14 @@
         TEntry entry;
         _LIT(KNonExistantFilename, "NONEXISTANT_FILENAME.DLL");
         r = TheFs.Entry(KNonExistantFilename, entry);
-        test(r == KErrCorrupt);
+        test_Value(r, r == KErrCorrupt);
         }
     r=TheFs.Drive(info,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test.Printf(_L("iType=%d,iBattery=%d,iDriveAtt=%x,iMediaAtt=%x\n"),(TUint)info.iType,\
         (TUint)info.iBattery,info.iDriveAtt,info.iMediaAtt);
     remounts = (TInt) info.iBattery;
-    test.Printf(_L("Remounts = %d"), remounts);
+    test.Printf(_L("Remounts = %d\n"), remounts);
     test(remounts ==  KMaxMountFailures);
     
     // simulate a media change to reset failure count
@@ -328,27 +380,27 @@
         TEntry entry;
         _LIT(KNonExistantFilename, "NONEXISTANT_FILENAME.DLL");
         r = TheFs.Entry(KNonExistantFilename, entry);
-        test(r == KErrCorrupt);
+        test_Value(r, r == KErrCorrupt);
         }
     r=TheFs.Drive(info,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test.Printf(_L("iType=%d,iBattery=%d,iDriveAtt=%x,iMediaAtt=%x\n"),(TUint)info.iType,\
         (TUint)info.iBattery,info.iDriveAtt,info.iMediaAtt);
     remounts = (TInt) info.iBattery;
-    test.Printf(_L("Remounts = %d"), remounts);
+    test.Printf(_L("Remounts = %d\n"), remounts);
     test(remounts ==  KMaxMountFailures * 2);
     
 
 
     r=TheFs.DismountFileSystem(newFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r=TheFs.MountFileSystem(oldFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     
-    r=TheFs.RemoveFileSystem(_L("Test2"));
+    r=TheFs.RemoveFileSystem(KTestFsName2);
     if(r!=KErrNone)
         {
-        test.Printf(_L("error=%d"),r);
+        test.Printf(_L("error=%d\n"),r);
         test(EFalse);
         }
     }
@@ -359,14 +411,14 @@
 */
 static void TestSubstDriveMediaSerialNumber()
 {
-    test.Next(_L("Test obtaining media serial number for the substituted drives"));
+    test.Next(_L("Test obtaining media serial number for the substituted drives\n"));
 
     TInt  nRes;
     const TInt currDrvNum=CurrentDrive();
     
     TDriveInfo drvInfo;
     nRes=TheFs.Drive(drvInfo, currDrvNum);
-    test(nRes==KErrNone);
+    test_KErrNone(nRes);
 
     if(drvInfo.iDriveAtt & (KDriveAttRom | KDriveAttRedirected | KDriveAttSubsted))
     {
@@ -385,7 +437,7 @@
             {
             // found a non-extant drive, test it...
             nRes = TheFs.GetMediaSerialNumber(serNum, drvNum);
-            test(nRes == KErrNotReady);
+            test_Value(nRes, nRes == KErrNotReady);
             break;
             }
         }
@@ -406,15 +458,15 @@
     MakeDir(substPath);
   
     nRes = TheFs.SetSubst(substPath, KSubstDrv);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
     //-- an attempt to obtain Media Serial Number on a substed drive shall result in KErrNotSupported
     nRes = TheFs.GetMediaSerialNumber(serNum, KSubstDrv);
-    test(nRes == KErrNotSupported);
+    test_Value(nRes, nRes == KErrNotSupported);
 
     //-- delete substed drive
     nRes = TheFs.SetSubst(_L(""), KSubstDrv);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 }
 
 
@@ -438,7 +490,7 @@
 //----------------------------------------------------------------------------------------------
 static void TestFileSystemSubTypeQuery()
     {
-    test.Next(_L("Test querying sub type of the mounted file system"));
+    test.Next(_L("Test querying sub type of the mounted file system\n"));
     TFSName fsName;
     TPckgBuf<TFSName> subName;
     TInt i, r;
@@ -453,19 +505,19 @@
             {
             test.Printf(_L("Tested on drive: %c.\n"), (char)(i+'A'));
             r=TheFs.Drive(driveInfo, i);
-            test(r==KErrNone);
+            test_KErrNone(r);
             
             if (driveInfo.iType==EMediaNotPresent)
                 {
                 test.Printf(_L("The media is not present.\n"));
                 r = TheFs.QueryVolumeInfoExt(i, EFileSystemSubType, subName);
-                test(r == KErrNone || r == KErrNotReady);
+                test_Value(r, r == KErrNone || r == KErrNotReady);
                 }
             else if (driveInfo.iType==EMediaCdRom)
                 {
                 test.Printf(_L("CD ROM with no media will report not ready!\n"));
                 r = TheFs.QueryVolumeInfoExt(i, EFileSystemSubType, subName);
-                test(r == KErrNotReady);
+                test_Value(r, r == KErrNotReady);
                 }
             else
                 {
@@ -474,7 +526,7 @@
 
                 //-- test EIsDriveSync command
                 r = TheFs.QueryVolumeInfoExt(i, EIsDriveSync, fDrvSyncBuf);
-                test(r == KErrNone);
+                test_KErrNone(r);
                 if(fDrvSyncBuf())
                     test.Printf(_L("The drive is Synchronous.\n"));
                 else
@@ -485,7 +537,7 @@
                 // if Fat, testing returning sub type name
                 if (fsName.CompareF(KFileSystemName_FAT)==0)
                     {
-                    test(r == KErrNone);
+                    test_KErrNone(r);
                     test(subName().CompareF(KFSSubType_FAT12)==0 ||
                          subName().CompareF(KFSSubType_FAT16)==0 ||
                          subName().CompareF(KFSSubType_FAT32)==0);
@@ -495,27 +547,27 @@
                 // if Lffs, testing returning file system name
                 if (fsName.CompareF(_L("Lffs"))==0)
                     {
-                    test(r == KErrNone);
+                    test_KErrNone(r);
                     test(subName().CompareF(_L("Lffs"))==0);
                     continue;
                     }
                 // if rofs, testing returning file system name
                 if (fsName.CompareF(_L("rofs"))==0)
                     {
-                    test(r == KErrNone);
+                    test_KErrNone(r);
                     test(subName().CompareF(_L("rofs"))==0);
                     continue;
                     }
                 // if Composite, testing returning file system name
                 if (fsName.CompareF(_L("Composite"))==0)
                     {
-                    test(r == KErrNone);
+                    test_KErrNone(r);
                     test(subName().CompareF(_L("Composite"))==0);
                     continue;
                     }
 
                 // else
-                test(r == KErrNone);
+                test_KErrNone(r);
                 test(subName().Length()!=0);
                 
                 }
@@ -541,7 +593,7 @@
 //----------------------------------------------------------------------------------------------
 static void TestFileSystemClusterSizeQuery()
     {
-    test.Next(_L("Test querying cluster size information of the mounted file system"));
+    test.Next(_L("Test querying cluster size information of the mounted file system\n"));
     TFullName fsName;
     TPckgBuf<TVolumeIOParamInfo> ioInfo;
     TInt i, r;
@@ -554,18 +606,18 @@
             test.Printf(_L("Tested on drive: %c.\n"), (char)(i+'A'));
 
             r=TheFs.Drive(driveInfo, i);
-            test(r==KErrNone);
+            test_KErrNone(r);
             // if no media present
             if (driveInfo.iType==EMediaNotPresent)
                 {
                 r = TheFs.QueryVolumeInfoExt(i, EIOParamInfo, ioInfo);
-                test(r == KErrNone || r == KErrNotReady);
+                test_Value(r, r == KErrNone || r == KErrNotReady);
                 }
             else if (driveInfo.iType==EMediaCdRom)
                 {
                 test.Printf(_L("CD ROM with no media!\n"));
                 r = TheFs.QueryVolumeInfoExt(i, EIOParamInfo, ioInfo);
-                test(r == KErrNone || r == KErrNotReady);
+                test_Value(r, r == KErrNone || r == KErrNotReady);
                 }
             else
                 {
@@ -602,7 +654,7 @@
                         }
                         TPckg<TLocalDriveCapsV7> capsPckg(DriveCapsV7);
                         r=drive.Caps(capsPckg);
-                        test(r==KErrNone);
+                        test_KErrNone(r);
                         drive.Disconnect();
                         if(DriveCapsV7.iObjectModeSize == 0)
                         {
@@ -646,12 +698,12 @@
 //----------------------------------------------------------------------------------------------
 static void TestMediaBlockSizeQuery()
     {
-    test.Next(_L("Test querying block size information of the underlying media"));
+    test.Next(_L("Test querying block size information of the underlying media\n"));
     #if defined(__WINS__)
-        test.Printf(_L("This test case runs on hardware only"));
+        test.Printf(_L("This test case runs on hardware only\n"));
         return;
-    
     #else   // test runs on hardware only.
+ 
     TFSName fsName;
     TPckgBuf<TVolumeIOParamInfo> ioInfo;
     TInt i, r;
@@ -663,18 +715,18 @@
             {
             test.Printf(_L("Tested on drive: %c.\n"), (char)(i+'A'));
             r=TheFs.Drive(driveInfo, i);
-            test(r==KErrNone);
+            test_KErrNone(r);
             // if no media present
             if (driveInfo.iType==EMediaNotPresent)
                 {
                 r = TheFs.QueryVolumeInfoExt(i, EIOParamInfo, ioInfo);
-                test(r == KErrNone || r == KErrNotReady);
+                test_Value(r, r == KErrNone || r == KErrNotReady);
                 }
             else if (driveInfo.iType==EMediaCdRom)
                 {
                 test.Printf(_L("CD ROM with no media will report not ready!\n"));
                 r = TheFs.QueryVolumeInfoExt(i, EIOParamInfo, ioInfo);
-                test(r == KErrNotReady);
+                test_Value(r, r == KErrNotReady);
                 }
             else
                 {
@@ -725,7 +777,7 @@
                         }
                     TPckg<TLocalDriveCapsV7> capsPckg(DriveCapsV7);
                     r=drive.Caps(capsPckg);
-                    test(r==KErrNone);
+                    test_KErrNone(r);
                     if ((fsName.CompareF(_L("Lffs"))==0) && (DriveCapsV7.iObjectModeSize != 0))
                         {                   
                         test(ioInfo().iBlockSize == (TInt) DriveCapsV7.iObjectModeSize);
@@ -765,7 +817,7 @@
 //----------------------------------------------------------------------------------------------
 static void TestFileSystemSubType()
     {
-    test.Next(_L("Test wrapper API RFs::FileSystemSubType()'s behaviour"));
+    test.Next(_L("Test wrapper API RFs::FileSystemSubType()'s behaviour\n"));
     TFSName fsName;
     TPckgBuf<TFSName> subName;
     TInt r;
@@ -780,7 +832,7 @@
             test.Printf(_L("Tested on drive: %c.\n"), (char)(i+'A'));
             r = TheFs.QueryVolumeInfoExt(i, EFileSystemSubType, subName);
             r1 = TheFs.FileSystemSubType(i, subName1);
-            test(r==r1);
+            test_Value(r, r == r1);
             if (subName().Length())
                 {
                 test(subName().CompareF(subName1)==0);
@@ -807,7 +859,7 @@
 //----------------------------------------------------------------------------------------------
 static void TestVolumeIOParam()
     {
-    test.Next(_L("Test wrapper API RFs::VolumeIOParam()'s behaviour"));
+    test.Next(_L("Test wrapper API RFs::VolumeIOParam()'s behaviour\n"));
     TFSName fsName;
     TPckgBuf<TVolumeIOParamInfo> ioInfo;
     TInt r;
@@ -822,7 +874,7 @@
             test.Printf(_L("Tested on drive: %c.\n"), (char)(i+'A'));
             r = TheFs.QueryVolumeInfoExt(i, EIOParamInfo, ioInfo);
             r1 = TheFs.VolumeIOParam(i, ioInfo1);
-            test(r==r1);
+            test_Value(r, r == r1);
             test(ioInfo().iBlockSize == ioInfo1.iBlockSize);
             test(ioInfo().iClusterSize == ioInfo1.iClusterSize);
             test(ioInfo().iRecReadBufSize == ioInfo1.iRecReadBufSize);
@@ -856,51 +908,51 @@
     test.Printf(_L("Tested on drive: %c.\n"), (char)(aDrive+'A'));
 
     // Mount a new CTestFileSystem on the drive under test
-    test.Next(_L("Test RFs::QueryVolumeInfoExt() on Testing File System"));
-    r = TheFs.AddFileSystem(_L("T_TFSYS3"));
+    test.Next(_L("Test RFs::QueryVolumeInfoExt() on Testing File System\n"));
+    r = TheFs.AddFileSystem(KTestFsy3);
     if (r != KErrNone && r != KErrAlreadyExists)
         {
-        test.Printf(_L("error=%d"),r);
+        test.Printf(_L("error=%d\n"),r);
         test(EFalse);
         }
     TFSName oldFs;
     r = TheFs.FileSystemName(oldFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r = TheFs.DismountFileSystem(oldFs,aDrive);
     if (r != KErrNone)
         {
-        test.Printf(_L("Error = %d"),r);    
+        test.Printf(_L("Error = %d\n"),r);    
         test(EFalse);
         }
-    r = TheFs.MountFileSystem(_L("Test3"),aDrive);
-    test(r==KErrNone);
+    r = TheFs.MountFileSystem(KTestFsName3, aDrive);
+    test_KErrNone(r);
     TFSName newFs;
     r = TheFs.FileSystemName(newFs,aDrive);
-    test(r==KErrNone);
-    test(newFs.Compare(_L("Test3"))==0);
+    test_KErrNone(r);
+    test(newFs.Compare(KTestFsName3)==0);
 
     // Sub type name query: 
     TPckgBuf<TFSName> subNameP;
     r = TheFs.QueryVolumeInfoExt(aDrive, EFileSystemSubType, subNameP);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test(subNameP() == _L("Test3SubType"));
 
     // Cluster size querys:
     TPckgBuf<TVolumeIOParamInfo> ioInfoP;
     r = TheFs.QueryVolumeInfoExt(aDrive, EIOParamInfo, ioInfoP);
-    test(r==KErrNone);
+    test_KErrNone(r);
     test(ioInfoP().iClusterSize==1024);
 
     // Mount the original file system back
     r=TheFs.DismountFileSystem(newFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     r=TheFs.MountFileSystem(oldFs,aDrive);
-    test(r==KErrNone);
+    test_KErrNone(r);
     
-    r=TheFs.RemoveFileSystem(_L("Test3"));
+    r=TheFs.RemoveFileSystem(KTestFsName3);
     if(r!=KErrNone)
         {
-        test.Printf(_L("error=%d"),r);
+        test.Printf(_L("error=%d\n"),r);
         test(EFalse);
         }
     }
@@ -919,8 +971,22 @@
 {
     test.Next(_L("Testing forcedly remounting FS with objects opened.\n"));
     
+    //-- don't perform this test on a non-removable drive, generating media change on such drive
+    //-- doesn't always work
     TInt nRes;
-    
+    const TInt drvNumber = CurrentDrive();
+    TDriveInfo driveInfo;
+
+    nRes = TheFs.Drive(driveInfo, drvNumber);
+    test_KErrNone(nRes);
+
+    if(! (driveInfo.iDriveAtt & KDriveAttRemovable))
+    {
+        test.Printf(_L("Can't perform this test on a non-removable drive. Skippping!\n"));
+        return;
+    }
+
+
     //-- 1. create a file
     _LIT(KFile, "\\test_file.file");
     const TUint KFileSz = 5000;
@@ -934,7 +1000,7 @@
     nRes = file.Open(TheFs, KFile, EFileRead);
     test_KErrNone(nRes);
     
-    const TInt drvNumber = CurrentDrive();
+    
 
     //-- 2.1 try to dismount the FS, it must fail because of the opened object.
     TBuf<40> fsName;
@@ -948,14 +1014,14 @@
     const TUint KMediaRemountForceMediaChange = 0x00000001;
     TRequestStatus changeStatus;
     TheFs.NotifyChange(ENotifyAll, changeStatus);
-    TDriveInfo driveInfo;
+    
     
     //-- 3. forcedly remount the drive
     nRes = TheFs.RemountDrive(drvNumber, NULL, KMediaRemountForceMediaChange);
     
     if(nRes == KErrNotSupported)
     	{//-- this feature is not supported and the test is inconsistent.
-        test.Printf(_L("RemountDrive() is not supported, the test is inconsistent!"));
+        test.Printf(_L("RemountDrive() is not supported, the test is inconsistent!\n"));
         
         //-- remounting must work at least on MMC drives
         const TBool isFAT = Is_Fat(TheFs, drvNumber);
@@ -968,7 +1034,8 @@
     else
     	{
 		test_Value(nRes, nRes == KErrNotReady || nRes == KErrNone);
-		
+		test.Printf(_L("Waiting for the simulated media change...\n"));
+
 		//-- 3.1 wait for media change to complete
 		do
 			{
@@ -1003,7 +1070,7 @@
 //----------------------------------------------------------------------------------------------
 static void TestFileSystem_MaxSupportedFileSizeQuery()
 {
-    test.Next(_L("Test querying max. supported file size on this file system"));
+    test.Next(_L("Test querying max. supported file size on this file system\n"));
     TFullName fsName;
     TPckgBuf<TVolumeIOParamInfo> ioInfo;
     TVolumeIOParamInfo& volInfo = ioInfo();
@@ -1034,44 +1101,38 @@
 }
 
 //----------------------------------------------------------------------------------------------
-GLDEF_C void CallTestsL()
-//
-// Do all tests
-//
+void CallTestsL()
     {
 
     //-- set up console output 
     Fat_Test_Utils::SetConsole(test.Console()); 
 
-    TInt drive=CurrentDrive();
-
+    const TInt drive=CurrentDrive();
     PrintDrvInfo(TheFs, drive);
 
-    //Do not run this test on the NAND drive, as
-    //this has the FTL mounted as a primary extension
+    //Do not run this test on the NAND drive, as this has the FTL mounted as a primary extension
     //which causes the test to fail
-    #if defined(__WINS__)
-        if (drive==EDriveU)
-            return;
-    #else
-        TDriveInfo driveInfo;
-        TheFs.Drive(driveInfo,drive);
-        if (driveInfo.iType == EMediaNANDFlash)
-            {
-            return;
-            }
-    #endif
+    
+    TFSName pExtName;
+    pExtName.Zero();
+   
+    TInt nRes = TheFs.ExtensionName(pExtName, drive, 0);
+   
+    if(nRes == KErrNone && pExtName.Length())
+        {
+        test.Printf(_L("This test can't be run on a drive that has a primary extension:%S\n"), &pExtName);   
+        return;
+        }
 
     //---------------------------------------
 
+    InitGlobals();
+    
+    //---------------------------------------
     TestFileSystemNames();
     TestDismountFileSystem(CurrentDrive());
-#if defined(__EPOC32__)
     TestFileSystem(CurrentDrive());
-#endif
-
     TestMountInvalidDrive();
-    
     TestMountingBrokenMedia(CurrentDrive());
     TestSubstDriveMediaSerialNumber();
 
@@ -1081,10 +1142,9 @@
     TestFileSystemSubType();
     TestVolumeIOParam();
     TestQueryVolumeInfoExtOnTestFS(CurrentDrive());
-
     TestFileSystem_MaxSupportedFileSizeQuery();
-
     TestRemountFSWithOpenedObjects();
     
-    
+    //---------------------------------------
+    DestroyGlobals();    
     }
--- a/kerneltest/f32test/server/t_misc.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/f32test/server/t_misc.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -15,10 +15,15 @@
 // 
 //
 
+#define __E32TEST_EXTENSION__
 #include <f32file.h>
 #include <e32test.h>
 #include "t_server.h"
 
+#include "f32_test_utils.h"
+using namespace F32_Test_Utils;
+
+
 // If there is an NFE media driver present, then because of the way EDeleteNotify requests work,
 // the data retrieved from a deleted file will not be a buffer full of zero's, but instead a buffer
 // full of decrypted zero's
@@ -29,11 +34,13 @@
     #pragma setlocale("english")
 #endif
 
-GLDEF_D RTest test(_L("T_MISC"));
+RTest test(_L("T_MISC"));
 
+
+TInt gDriveNum = -1;
 const TUint KBufLength = 0x100;
 
-LOCAL_C void Test1()
+static void Test1()
 //
 // Open, write to and read from a file
 //
@@ -41,24 +48,24 @@
 
 	test.Next(_L("Open, write to and read from a file"));
 	TInt r=TheFs.SetSessionPath(gSessionPath);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	RFile file;
 	r=file.Create(TheFs,_L("Hello.Wld"),EFileWrite);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=file.Write(_L8("Hello World"),11);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	file.Close();
 
 	r=file.Open(TheFs,_L("Hello.Wld"),EFileRead);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	TBuf8<256> buf;
 	r=file.Read(buf);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(buf==_L8("Hello World"));
 	file.Close();
 	}
 
-LOCAL_C void Test2()
+static void Test2()
 //
 // Open and read from a file
 //
@@ -66,20 +73,20 @@
 
 	test.Next(_L("Open and read from a file"));
 	TInt r=TheFs.SetSessionPath(gSessionPath);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	RFile file;
 	r=file.Open(TheFs,_L("Hello.Wld"),EFileRead);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	TBuf8<256> buf;
 	r=file.Read(buf);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(buf==_L8("Hello World"));
 	file.Close();
 	r=TheFs.Delete(_L("HELLO.WLD"));
-	test(r==KErrNone);
+	test_KErrNone(r);
 	}
 
-LOCAL_C void Test3()
+static void Test3()
 //
 // Create nested directories
 //
@@ -87,28 +94,28 @@
 
 	test.Next(_L("Create nested directories"));
 	TInt r=TheFs.SetSessionPath(gSessionPath);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	TheFs.ResourceCountMarkStart();
 //
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\A.B"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\F32-TST\\RIGHT\\"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 //
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\ONE\\"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\TWO\\"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\THREE\\"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\TWO\\BOTTOM\\"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 //
 	r=TheFs.MkDirAll(_L("\\F32-TST\\RIGHT\\TOP\\MID\\BOT\\"));
-	test(r==KErrNone || r==KErrAlreadyExists);
+	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 	}
 
-LOCAL_C void Test4()
+static void Test4()
 //
 // Test returned error values
 //
@@ -116,62 +123,62 @@
 
 	test.Next(_L("Test returned error values"));
 	TInt r=TheFs.SetSessionPath(gSessionPath);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	TheFs.ResourceCountMarkStart();
 //
 	r=TheFs.MkDir(_L("\\"));
-	test(r==KErrAlreadyExists);
+	test_Value(r, r == KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\LEFT"));
-	test(r==KErrAlreadyExists);
+	test_Value(r, r == KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\"));
-	test(r==KErrAlreadyExists);
+	test_Value(r, r == KErrAlreadyExists);
 	r=TheFs.MkDir(_L("\\F32-TST\\LEFT\\..\\NEWDIR\\"));
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 	r=TheFs.MkDir(_L("\\F32-TST\\NEWDIR\\SUBDIR\\"));
-	test(r==KErrPathNotFound);
+	test_Value(r, r == KErrPathNotFound);
 //
 	r=TheFs.RmDir(_L("\\"));
-	test(r==KErrInUse);
+	test_Value(r, r == KErrInUse);
 	r=TheFs.RmDir(_L("\\PROG"));
-	test(r==KErrInUse);
+	test_Value(r, r == KErrInUse);
 	r=TheFs.RmDir(_L("\\F32-TST\\"));
-	test(r==KErrInUse);
+	test_Value(r, r == KErrInUse);
 
 
 	RDir dir;
 	r=dir.Open(TheFs,_L("V:\\asdf"),KEntryAttNormal);
-	test(r==KErrNone || r==KErrNotReady || r==KErrNotFound);
+	test_Value(r, r == KErrNone || r==KErrNotReady || r==KErrNotFound);
 	if (r==KErrNone)
 		dir.Close();
 	r=dir.Open(TheFs,_L("L:\\asdf"),KEntryAttNormal);
-	test(r==KErrNone || r==KErrNotReady || r==KErrNotFound);
+	test_Value(r, r == KErrNone || r==KErrNotReady || r==KErrNotFound);
 	dir.Close();
 //
 	TEntry entry;
 	r=TheFs.Entry(_L("z:\\NOTEXiSTS\\file.txt"),entry);
-	test(r==KErrPathNotFound);
+	test_Value(r, r == KErrPathNotFound);
 	r=TheFs.Entry(_L("z:\\NOTEXiSTS\\"),entry);
-	test(r==KErrNotFound);
+	test_Value(r, r == KErrNotFound);
 	r=TheFs.Entry(_L("z:\\SYSTEM\\"),entry);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.Entry(PlatSec::ConfigSetting(PlatSec::EPlatSecEnforceSysBin)?_L("z:\\SYS\\BIN\\ESHELL.EXE"):_L("z:\\SYSTEM\\BIN\\ESHELL.EXE"),entry);
-	test(r==KErrNone);
+	test_KErrNone(r);
 
 	r=dir.Open(TheFs,_L("\\*"),NULL);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	TEntry dirEntry;
 	r=dir.Read(dirEntry);
-	test(r==KErrNone || r==KErrEof);
+	test_Value(r, r == KErrNone || r==KErrEof);
 	if (r==KErrNone)
 		test.Printf(_L("%S\n"),&dirEntry.iName);
 	dir.Close();
 
 	r=dir.Open(TheFs,_L("A:\\*"),NULL);
-	test(r==KErrNotReady || r==KErrNone);
+	test_Value(r, r == KErrNotReady || r==KErrNone);
 	dir.Close();
 	}
 
-LOCAL_C void Test5()
+static void Test5()
 //
 // Read files directly from the rom
 //
@@ -188,13 +195,13 @@
 		{
 		RFile f;
 		r=f.Open(TheFs,KTFileCpp,EFileRead);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		r=f.Seek(ESeekAddress,pos);
 		TText8* ptrPos=*(TText8**)&pos;
-		test(r==KErrNone);
+		test_KErrNone(r);
 		TBuf8<1024> readBuf;
 		r=f.Read(readBuf);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		test(readBuf.Length()==readBuf.MaxLength());
 		TPtrC8 memBuf(ptrPos,readBuf.Length());
 		test(memBuf==readBuf);
@@ -202,10 +209,10 @@
 		ptrPos+=9913;
 		pos=9913;
 		r=f.Seek(ESeekStart,pos);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		readBuf.SetLength(0);
 		r=f.Read(readBuf);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		test(readBuf.Length()==readBuf.MaxLength());
 		memBuf.Set(ptrPos,readBuf.Length());
 		test(memBuf==readBuf);
@@ -214,16 +221,16 @@
 		pos=10;
 		r=f2.Open(TheFs,KTFsrvCpp,EFileRead);
 
-		test(r==KErrNone);
+		test_KErrNone(r);
 		r=f2.Seek(ESeekAddress,pos);
 		ptrPos=*(TText8**)&pos;
-		test(r==KErrNone);
+		test_KErrNone(r);
 		readBuf.SetLength(0);
 		pos=10;
 		r=f2.Seek(ESeekStart,pos);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		r=f2.Read(readBuf);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		test(readBuf.Length()==readBuf.MaxLength());
 		memBuf.Set(ptrPos,readBuf.Length());
 		test(memBuf==readBuf);
@@ -231,10 +238,10 @@
 		ptrPos+=2445;
 		pos=10+2445;
 		r=f2.Seek(ESeekStart,pos);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		readBuf.SetLength(0);
 		r=f2.Read(readBuf);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		test(readBuf.Length()==readBuf.MaxLength());
 		memBuf.Set(ptrPos,readBuf.Length());
 		test(memBuf==readBuf);
@@ -242,13 +249,13 @@
 		pos=0;
 		r=f.Seek(ESeekAddress,pos);
 		ptrPos=*(TText8**)&pos;
-		test(r==KErrNone);
+		test_KErrNone(r);
 		readBuf.SetLength(0);
 		pos=0;
 		r=f.Seek(ESeekStart,pos);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		r=f.Read(readBuf);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		test(readBuf.Length()==readBuf.MaxLength());
 		memBuf.Set(ptrPos,readBuf.Length());
 		test(memBuf==readBuf);
@@ -256,10 +263,10 @@
 		ptrPos+=5245;
 		pos=5245;
 		r=f.Seek(ESeekStart,pos);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		readBuf.SetLength(0);
 		r=f.Read(readBuf);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		test(readBuf.Length()==readBuf.MaxLength());
 		memBuf.Set(ptrPos,readBuf.Length());
 		test(memBuf==readBuf);
@@ -269,7 +276,7 @@
 		}
 	}
 
-LOCAL_C void Test6()
+static void Test6()
 //
 // Test rom return values
 //
@@ -278,17 +285,17 @@
 
 	RFile f;
 	TInt r=f.Replace(TheFs,_L("Z:\\Test\\T_Fsrv.Cpp"),EFileRead);
-	test(r==KErrAccessDenied);
+	test_Value(r, r == KErrAccessDenied);
 	r=f.Create(TheFs,_L("Z:\\Test\\newT_Fsrv.Cpp"),EFileRead);
-	test(r==KErrAccessDenied);
+	test_Value(r, r == KErrAccessDenied);
 	r=f.Open(TheFs,_L("Z:\\Test\\T_Fsrv.Cpp"),EFileRead);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	f.Close();
 	r=f.Open(TheFs,_L("Z:\\Test\\T_Fsrv.Cpp"),EFileRead|EFileWrite);
-	test(r==KErrAccessDenied);
+	test_Value(r, r == KErrAccessDenied);
 	}
 
-LOCAL_C void Test7()
+static void Test7()
 //
 // Test cache
 //
@@ -302,7 +309,7 @@
 
 	TEntry entry;
 	TInt r=TheFs.Entry(file1,entry);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(entry.iType==uid1);
 
 	TUidType uid2(TUid::Uid(4),TUid::Uid(5),TUid::Uid(6));
@@ -310,23 +317,23 @@
 	TPtrC8 uidData((TUint8*)&checkedUid,sizeof(TCheckedUid));
 	RFile f;
 	r=f.Open(TheFs,file1,EFileRead|EFileWrite);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=f.Write(uidData);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r = f.Flush();
-	test(r==KErrNone);
+	test_KErrNone(r);
 
 	r=TheFs.Entry(file1,entry);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(entry.iType==uid2);
 
 	f.Close();
 	r=TheFs.Entry(file1,entry);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(entry.iType==uid2);
 	}
 
-LOCAL_C void Test8()
+static void Test8()
 //
 // Test IsValidName
 //
@@ -535,7 +542,7 @@
         }
 	}
 
-LOCAL_C void Test9()
+static void Test9()
 //
 // Test IsFileInRom
 //
@@ -545,7 +552,7 @@
 
 	CFileMan* fMan=CFileMan::NewL(TheFs);
 	TInt r=fMan->Copy(_L("Z:\\TEST\\T_FILE.CPP"),_L("C:\\T_FILE.CPP"));
-	test(r==KErrNone || r==KErrAccessDenied);
+	test_Value(r, r == KErrNone || r==KErrAccessDenied);
 	delete fMan;
 	TUint8* addr=TheFs.IsFileInRom(_L("C:\\ESHELL.EXE"));
 	test(addr==NULL);
@@ -562,7 +569,7 @@
 		}
 	}
 
-LOCAL_C void Test10()
+static void Test10()
 //
 // Test drive names
 //
@@ -574,7 +581,7 @@
 	for(i=0;i<KMaxDrives;i++)
 		{
 		TInt r=TheFs.GetDriveName(i,driveName);
-		test(r==KErrNone);
+		test_KErrNone(r);
 		if (driveName.Length())
 			test.Printf(_L("Default name of %c: == %S\n"),'A'+i,&driveName);
 		}
@@ -584,32 +591,32 @@
 	TBuf<64> drive17=_L("Flibble");
 	TBuf<64> drive25=_L("RAMDRIVE");
 	TInt r=TheFs.SetDriveName(0,drive0);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.SetDriveName(4,drive4);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.SetDriveName(17,drive17);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.SetDriveName(25,drive25);
-	test(r==KErrNone);
+	test_KErrNone(r);
 
 	r=TheFs.GetDriveName(0,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive0);
 	r=TheFs.GetDriveName(4,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive4);
 	r=TheFs.GetDriveName(17,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive17);
 	r=TheFs.GetDriveName(25,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive25);
 
 	drive0=_L("askdjflsdfourewoqiuroiuaksjdvx,cvsdhwjhjhalsjhfshfkjhslj");
 	r=TheFs.SetDriveName(0,drive0);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.GetDriveName(0,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive0);
 
 //	Test with illegal characters in drive name
@@ -619,13 +626,13 @@
 	drive25=_L("RAMD//RIVE");
 
 	r=TheFs.SetDriveName(0,drive0);
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 	r=TheFs.SetDriveName(4,drive4);
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 	r=TheFs.SetDriveName(17,drive17);
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 	r=TheFs.SetDriveName(25,drive25);
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 
 //	Test that it is OK to set the name to no characters
 
@@ -635,31 +642,31 @@
 	drive25=_L("");
 
 	r=TheFs.SetDriveName(0,drive0);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.SetDriveName(4,drive4);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.SetDriveName(17,drive17);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.SetDriveName(25,drive25);
-	test(r==KErrNone);
+	test_KErrNone(r);
 
 	r=TheFs.GetDriveName(0,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive0);
 	r=TheFs.GetDriveName(4,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive4);
 	r=TheFs.GetDriveName(17,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive17);
 	r=TheFs.GetDriveName(25,driveName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	test(driveName==drive25);
 
 
 	}
 
-LOCAL_C void Test11()
+static void Test11()
 //
 // Miscellaneous tests
 //
@@ -669,14 +676,14 @@
 	TVolumeInfo vol;
 	TInt r=TheFs.Volume(vol);
 	test.Printf(_L("VolumeName = %S\n"),&vol.iName);
-	test(r==KErrNone);
+	test_KErrNone(r);
 	r=TheFs.RmDir(_L("\\asdfasdf.\\"));
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 	r=TheFs.MkDir(_L("\\asdfasdf.\\"));
-	test(r==KErrBadName);
+	test_Value(r, r == KErrBadName);
 	}
 
-LOCAL_C void Test12()
+static void Test12()
 //
 // Test SetNotifyUser and GetNotifyUser
 //
@@ -695,7 +702,7 @@
 	test(notifyState);
 	}
 
-LOCAL_C void Test13()
+static void Test13()
 //
 // Test return values from RFs::Volume on cf-cards
 //
@@ -704,30 +711,29 @@
 	test.Next(_L("Test RFs::Volume"));
 	TVolumeInfo vol;
 	TInt r=TheFs.Volume(vol,EDriveB);
-	test(r==KErrNotReady || r==KErrNone || KErrPathNotFound);
+	test_Value(r, r == KErrNotReady || r==KErrNone || r == KErrPathNotFound);
 	test.Printf(_L("RFs::Volume EDriveB returned %d\n"),r);
 
 	r=TheFs.Volume(vol,EDriveC);
-	test(r==KErrNotReady || r==KErrNone || KErrPathNotFound);
+	test_Value(r, r == KErrNotReady || r==KErrNone || r == KErrPathNotFound);
 	test.Printf(_L("RFs::Volume EDriveC returned %d\n"),r);
 
 	r=TheFs.Volume(vol,EDriveD);
-	test(r==KErrNotReady || r==KErrNone || KErrPathNotFound);
+	test_Value(r, r == KErrNotReady || r==KErrNone || r == KErrPathNotFound);
 	test.Printf(_L("RFs::Volume EDriveD returned %d\n"),r);
 
 	r=TheFs.Volume(vol,EDriveE);
-	test(r==KErrNotReady || r==KErrNone || KErrPathNotFound);
+	test_Value(r, r == KErrNotReady || r==KErrNone || r == KErrPathNotFound);
 	test.Printf(_L("RFs::Volume EDriveE returned %d\n"),r);
 
 	r=TheFs.Volume(vol,EDriveF);
-	test(r==KErrNotReady || r==KErrNone || KErrPathNotFound);
+	test_Value(r, r == KErrNotReady || r==KErrNone || r == KErrPathNotFound);
 	test.Printf(_L("RFs::Volume EDriveF returned %d\n"),r);
 	}
 
 
 void    DoTest14(TInt aDrvNum);
 TInt    CreateStuffedFile(RFs& aFs, const TDesC& aFileName, TUint aFileSize);
-TInt    CreateEmptyFile(RFs& aFs, const TDesC& aFileName, TUint aFileSize);
 TBool   CheckFileContents(RFs& aFs, const TDesC& aFileName);
 #ifndef __NFE_MEDIA_DRIVER_PRESENT__
 TBool   CheckBufferContents(const TDesC8& aBuffer, TUint aPrintBaseAddr=0);
@@ -738,73 +744,27 @@
 This test is performed on RAM drives and non-removable media that supports DeleteNotify (KMediaAttDeleteNotify flag)
 e.g. XSR NAND
 */
-LOCAL_C void Test14()
+static void Test14()
 {
-	TInt nRes;
 
 	test.Next(_L("Testing unallocated data initialization vulnerability in RFile"));
 
-	TDriveList driveList;
 	TDriveInfo driveInfo;
 
-	//-- 1. get drives list
-	nRes=TheFs.DriveList(driveList);
-    test(nRes == KErrNone);
-
-	//-- 2. walk through all drives, performing the test only on suitable ones
-	for (TInt drvNum=0; drvNum<KMaxDrives; ++drvNum)
-    {
-	    if(!driveList[drvNum])
-	        continue;   //-- skip unexisting drive
-
 	    //-- get drive info
-	    test(TheFs.Drive(driveInfo, drvNum) == KErrNone);
-
-	    //-- select a suitable drive for the testing. It shall be RAM drive, of FLASH but not removable
-	    //-- and not read only, if it is FLASH, it shall support "Delete Notify" facility
-        switch(driveInfo.iType)
-        {
-        //-- RAM drive, OK
-        case EMediaRam:
-        break;
-
-        //-- FLASH drive, OK
-        case EMediaFlash:
-        case EMediaNANDFlash:
-            if(driveInfo.iMediaAtt & KMediaAttDeleteNotify)
-                break; //-- this type of media shall support DeleteNotify flag, otherwise this test is inconsistent
-            else continue;
-
-        //break; //unreacable
-
-        default:
-            continue;
-        }//switch(driveInfo.iType)
+	test(TheFs.Drive(driveInfo, gDriveNum) == KErrNone);
 
-		if (driveInfo.iDriveAtt	& KDriveAttSubsted)
-			{
-			// skip subst drives.
-			continue;
-			}
-
-        TBool readOnly = driveInfo.iMediaAtt & KMediaAttWriteProtected;
-        if(readOnly)
-            continue; //-- nothing to do, can't create any file etc.
-
-        //-- skip test on the emulator's C: drive, doesn't make any sense because
-        //-- in this case we deal with WIN32 API and filesystem.
-        #ifdef __WINS__
-        if(drvNum == 2)
-        {
-             test.Printf(_L("Skipping test on emulator's C: drive\n"));
-             continue;
-        }
-        #endif
-
-        DoTest14(drvNum);
-
-    }// for (TInt drvNum=0; ...
-
+    const TBool bMediaSuitable = (driveInfo.iType == EMediaRam)     || //-- RAM drives should be tested
+                                 (driveInfo.iType == EMediaFlash)   || //-- NOR FLASH drives should be tested
+                                 (driveInfo.iType == EMediaNANDFlash && driveInfo.iMediaAtt & KMediaAttDeleteNotify); //-- NAND media with DeleteNotify support
+    
+    if(!bMediaSuitable)
+    {
+        test.Printf(_L("This test can't be performed on this type of the media! Skipping.\n"));
+        return;
+    }
+    
+    DoTest14(gDriveNum);
 }
 
 //--------------------------------------------------------
@@ -835,17 +795,17 @@
 
     //-- 1. create an empty file
     nRes = CreateEmptyFile(TheFs, fileName, KFileSize);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
 #ifndef __NFE_MEDIA_DRIVER_PRESENT__	// can't easily check for illegitimate information if drive is encrypted
     //-- 1.1  check that this file doesn't contain illegitimate information.
     nRes = CheckFileContents(TheFs, fileName);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 #endif
 
     //-- 1.2 delete the empty file
     nRes = TheFs.Delete(fileName);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
     //==============================
     //== Scenario 2.
@@ -858,25 +818,25 @@
 
     //-- 2. create file filled with some data pattern
     nRes = CreateStuffedFile(TheFs, fileName, KFileSize);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
     //-- 2.1 delete this file
     TheFs.Delete(fileName);
 
     //-- 2.1 create an empty file on the place of just deleted one (hopefully)
     nRes = CreateEmptyFile(TheFs, fileName, KFileSize);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
     //-- 2.2  check that this file doesn't contain illegitimate information.
     nRes = CheckFileContents(TheFs, fileName);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
     //-- 2.3 delete this file
     TheFs.Delete(fileName);
 
 }
 
-LOCAL_C void Test15()
+static void Test15()
 //
 // Test IsValidName
 //
@@ -1173,11 +1133,11 @@
 	test.Next(_L("Test RFs::GetMediaSerialNumber"));	
     TInt theDrive;
     TInt r = TheFs.CharToDrive(gDriveToTest,theDrive);
-    test(r == KErrNone);
+    test_KErrNone(r);
     TMediaSerialNumber serNum;
     r = TheFs.GetMediaSerialNumber(serNum, theDrive);
 	if (r) test.Printf(_L("RFs::GetMediaSerialNumber returned error %d"), r);
-    test(r == KErrNotSupported || r == KErrNotReady || r == KErrNone);
+    test_Value(r, r == KErrNotSupported || r == KErrNotReady || r == KErrNone);
     if (r == KErrNotSupported)
         {
         test.Printf(_L("MediaSerialNumber: Not Supported\n"));
@@ -1209,32 +1169,6 @@
 
 //--------------------------------------------------------
 
-/**
-    Create an empty file of specified size.
-    @param  aFs		    ref. to the FS
-    @param  aFileName   name of the file
-    @param  aFileSize   size of the file to be created
-    @return    KErrNone on success, system-wide error code otherwise
-*/
-TInt CreateEmptyFile(RFs& aFs, const TDesC& aFileName, TUint aFileSize)
-{
-    RFile   file;
-	TInt    nRes;
-
-	nRes = file.Create(aFs, aFileName, EFileRead|EFileWrite);
-    if(nRes != KErrNone)
-        return nRes;
-
-	nRes = file.SetSize(aFileSize);
-    if(nRes != KErrNone)
-        return nRes;
-
-    file.Close();
-
-    return KErrNone;
-}
-
-//--------------------------------------------------------
 
 /**
     Create a file of specified size filled with some data pattern.
@@ -1304,7 +1238,7 @@
 
     //-- open the file
     nRes = file.Open(aFs, aFileName, EFileRead);
-    test(nRes == KErrNone);
+    test_KErrNone(nRes);
 
     //-- check file contents
     TUint nFilePos=0;
@@ -1312,7 +1246,7 @@
     {
         //-- read data from the file into the buffer
         nRes = file.Read(buffer);
-        test(nRes == KErrNone);
+        test_KErrNone(nRes);
 
         if(buffer.Length() == 0)
         {
@@ -1363,11 +1297,11 @@
 
     //-- check if the buffer filled with allowable data (RAM page initialisation data or something similar)
     //-- but not something meaningful.
-    //-- allowable bytes: 0x00, 0x03, 0xff, 0xcc
+    //-- Actually, the buffer should be filled with uniformed bytes (most probably, 0x00)
     for(TInt i=0; i<aBuffer.Size(); ++i)
     {
         TUint8 byte = aBuffer[i];
-        if(byte != 0x00 && byte != 0x03 && byte != 0xff && byte != 0xcc )
+        if(byte != aBuffer[0])
         {
             bRes = EFalse;
             break;
@@ -1394,13 +1328,368 @@
     return bRes;
 }
 
+//--------------------------------------------------------
+/**
+    Check if the drive aDriveNo is finalised or not.
+    The "CleanShutDown" is obtained by QueryVolumeInfoExt API which is FS-agnostic.
 
-GLDEF_C void CallTestsL()
-//
-// Call tests that may leave
-//
+    @param  aDriveNo drive number to query.
+    @return ETrue if the drive if finalised
+*/
+static TBool IsVolumeFinalised(TInt aDriveNo)
+{
+    TInt nRes;
+    TPckgBuf<TBool> boolPckg;
+
+    //-- 1. get "Finalised" state by using the API
+    nRes = TheFs.QueryVolumeInfoExt(aDriveNo, EIsDriveFinalised, boolPckg);
+    test_KErrNone(nRes);
+    
+    return boolPckg();
+}
+
+
+//--------------------------------------------------------
+/**
+    This is a file system - agnostic test that verifies RFs::FinaliseDrive() API
+    There are also file system - specific tests that check similar functionallity (see t_mount for example)
+
+*/
+void TestDriveFinalisation()
+{
+    test.Next(_L("TestDriveFinalisation(). Testing RFs::FinaliseDrives() API\n"));    
+    
+
+    if((!Is_Fat(TheFs, gDriveNum) && !Is_ExFat(TheFs, gDriveNum)) || Is_Fat12(TheFs, gDriveNum) )
+    {
+        test.Printf(_L("This test can't be performed on current file system, skipping.\n"));
+        return;
+    }
+
+    TVolumeInfo v;
+    TInt  nRes;
+
+    nRes = TheFs.Volume(v);
+    test(nRes==KErrNone);
+
+    if(v.iDrive.iMediaAtt & KMediaAttVariableSize)
+        {
+        test.Printf(_L("Skipping. RAM drive not tested.\n"));
+        return;
+        }
+
+
+    TBool bDriveFinalised;
+
+    //============= 1. finalise the drive (RW mode) and check the result
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //-- 1.1 finalise the drive second time EFinal_RW -> EFinal_RW shall work
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //============= 2. create a file. Shall succeed (EFinal_RW), the volume shall become unfinalised
+
+    RFile file;
+    _LIT(KFileName, "\\my_file1.dat");
+    _LIT8(KSomeData, "this is some data");
+
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised); //-- the volume has become "unfinalised"
+
+    //----------------------------------------------------------------------------------
+    //-- test volume finalisation with opened objects
+
+    //-- 2.1 having opened files should be OK for volume finalisation
+    
+    //-- 2.1.1 RW finalisation; after the volume finalised it should be possible to write to the opened file
+    nRes = file.Open(TheFs, KFileName, EFileWrite | EFileWriteDirectIO);
+    test_KErrNone(nRes);
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    nRes = file.Write(0, KSomeData);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised); //-- the volume should become "unfinalised"
+
+    //-- 2.1.2 RO finalisation; after the volume finalised it shouldn't be possible to write to the opened file
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RO);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    nRes = file.Write(0, KSomeData);
+    test(nRes == KErrAccessDenied);  //-- no write access to the volume
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised); //-- the volume should become "unfinalised"
+
+    file.Close();
+    
+    //-- remount FS, the drive shall become RW
+    nRes = RemountFS(TheFs, gDriveNum);
+    test_KErrNone(nRes);
+    
+    
+    //-- 2.2 having opened directories should be OK for volume finalisation
+    _LIT(KDirName,  "\\Dir11235tt\\");
+    MakeDir(KDirName);
+    RDir dir;
+
+    //-- 2.2.1 RW finalisation; after the volume finalised it should be possible to have write access to it
+    nRes = dir.Open(TheFs, KDirName, KEntryAttNormal);
+    test_KErrNone(nRes);
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised);
+
+    //-- 2.1.2 RO finalisation; after the volume finalised it shouldn't be possible to write to it
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RO);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test(nRes == KErrAccessDenied);  //-- no write access to the volume
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised); //-- the volume should become "unfinalised"
+
+    dir.Close();
+
+    //-- remount FS, the drive shall become RW
+    nRes = RemountFS(TheFs, gDriveNum);
+    test_KErrNone(nRes);
+    
+    //-- 2.3 having opened disk access objects, like formats or raw disks makes finalisation impossible
+    RFormat  format;
+    RRawDisk rawDisk;
+    TInt     fmtCnt;
+
+    //-- 2.3.1 format
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test_KErrNone(nRes);
+
+    nRes = format.Open(TheFs, gSessionPath, EFullFormat, fmtCnt);
+    test_KErrNone(nRes);
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test(nRes == KErrInUse);  
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RO);
+    test(nRes == KErrInUse);  
+
+    format.Close();
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test_KErrNone(nRes);
+
+    //-- 2.3.2 raw disk
+    nRes = rawDisk.Open(TheFs, gDriveNum);
+    test_KErrNone(nRes);
+
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test(nRes == KErrInUse);  
+
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RO);
+    test(nRes == KErrInUse);  
+    
+    rawDisk.Close();
+
+    //-- 2.4 Volume finalisation and file system dismounting
+
+    //-- 2.4.1 "graceful" dismounting should finalise the drive correctly
+
+    //-- "unfinalise the volume"
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised);
+
+    TFSDescriptor fsDesc;
+    nRes = GetFileSystemDescriptor(TheFs, gDriveNum, fsDesc);
+    test_KErrNone(nRes);
+
+    //-- gracefully dismount the file system
+    nRes = TheFs.DismountFileSystem(fsDesc.iFsName, gDriveNum);
+    test_KErrNone(nRes);
+
+    //-- mount it back
+    nRes = MountFileSystem(TheFs, gDriveNum, fsDesc);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //-- 2.4.2 "forced" dismounting, usually happens when "graceful doesn't work, because there are files opened on the volume.
+    //-- Should also finalise the drive correctly
+
+    //-- "unfinalise the volume"
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised);
+
+    //-- open a file on the volume, this will prevent graceful dismounting
+    nRes = file.Open(TheFs, KFileName, EFileWrite | EFileWriteDirectIO);
+    test_KErrNone(nRes);
+
+    nRes = GetFileSystemDescriptor(TheFs, gDriveNum, fsDesc);
+    test_KErrNone(nRes);
+
+    //-- try gracefully dismount the file system
+    nRes = TheFs.DismountFileSystem(fsDesc.iFsName, gDriveNum);
+    test(nRes == KErrInUse); //-- no luck, as expected
+
+    //-- now do dismounting by force
+    TRequestStatus  rqStat;
+    TheFs.NotifyDismount(gDriveNum, rqStat, EFsDismountForceDismount);
+    User::WaitForRequest(rqStat);
+    test_KErrNone(rqStat.Int());
+
+    nRes = file.Write(0, KSomeData);
+    test(nRes == KErrNotReady);    
+
+    file.Close();
+
+    //-- mount it back
+    nRes = MountFileSystem(TheFs, gDriveNum, fsDesc);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //============= 3. test "unfinalise API"
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EForceUnfinalise);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised); //-- the volume has become "unfinalised"
+
+    //============= 4. test finalisation into RO mode
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RO); //-- the volume becomes RO
+    test_KErrNone(nRes);
+
+    //-- try to write a file on RO volume; it shall fail with KErrAccessDenied
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test(nRes == KErrAccessDenied);
+    file.Close();
+
+    //-- 4.1 try to finalise into EFinal_RW mode, shall fail with KErrAccessDenied
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test(nRes == KErrAccessDenied);
+
+    //-- 4.2 "unfinalise" the volume, it still shall remain RO
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EForceUnfinalise);
+    test_KErrNone(nRes);
+
+    //-- try to write a file on RO volume; it shall fail with KErrAccessDenied
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test(nRes == KErrAccessDenied);
+    file.Close();
+
+    //-- remount FS, the drive shall become RW
+    nRes = RemountFS(TheFs, gDriveNum);
+    test_KErrNone(nRes);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //-- try to write a file on RW volume, shall be OK
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test(nRes == KErrNone);
+    file.Close();
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised);
+
+    //============= 5. test various finalisation modes
+
+    //-- 5.1  Not finalised -> EFinal_RW (KErrNone)
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test(nRes == KErrNone);
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //-- 5.2  EFinal_RW -> EFinal_RO (KErrNone)
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RO);
+    test(nRes == KErrNone);
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //-- 5.2  EFinal_RO -> EFinal_RW  (KErrAccessDenied)
+    nRes =TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW);
+    test(nRes == KErrAccessDenied);
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    //-- 5.3 restore
+    nRes = RemountFS(TheFs, gDriveNum);
+    test_KErrNone(nRes);
+
+
+    //============= 6. test old RFs::FinaliseDrives API
+
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test(nRes == KErrNone);
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(!bDriveFinalised);
+
+    TheFs.FinaliseDrives(); //-- shall work as TheFs.FinaliseDrive(gDriveNum, RFs::EFinal_RW) but for ALL drives
+
+    bDriveFinalised = IsVolumeFinalised(gDriveNum);
+    test(bDriveFinalised);
+
+    nRes = CreateEmptyFile(TheFs, KFileName, 128000);
+    test(nRes == KErrNone);
+
+
+
+}
+
+
+void CallTestsL()
 	{
+    //-- set up console output
+    F32_Test_Utils::SetConsole(test.Console());
 
+    TInt nRes=TheFs.CharToDrive(gDriveToTest, gDriveNum);
+    test_KErrNone(nRes);
+    
+    PrintDrvInfo(TheFs, gDriveNum);
+
+    TestDriveFinalisation();
 	Test1();
 	Test2();
 	Test3();
@@ -1417,4 +1706,5 @@
 	Test14();
 	Test15();
     TestGetMediaSerialNumber();
+
 	}
--- a/kerneltest/f32test/server/t_proxydrive1.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/kerneltest/f32test/server/t_proxydrive1.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -24,7 +24,7 @@
 using namespace F32_Test_Utils;
 
 
-GLDEF_D RTest test(_L("T_PROXYDRIVE1"));
+RTest test(_L("T_PROXYDRIVE1"));
 
 
 TInt GetRemovableDrive(TInt aDriveNumber)
@@ -81,7 +81,7 @@
 
 
 
-GLDEF_C void CallTestsL()
+void CallTestsL()
 	{
     TInt drive;
 	TInt err=RFs::CharToDrive(gDriveToTest,drive);
@@ -96,7 +96,7 @@
 
 	TInt r;
 
-	TInt localDriveNumber = GetRemovableDrive(drive);
+	TInt localDriveNumber = GetRemovableDrive(drive); //-- local _physical_ drive number
 	if (localDriveNumber < 0)
 		{
 		test.Printf(_L("Not a removable drive, skipping test\n"));
@@ -113,16 +113,25 @@
 	TBuf<1> p2;
 	TInt driveNumber = EDriveM;
 
+    //-- this is a hack - mount the proxy drive to the existing one with alive file system just to check
+    //-- that it works.
+
 	r = TheFs.MountProxyDrive(driveNumber, KBitProxyDrive, &p1, &p2);
 	test.Printf(_L("MountProxyDrive(%d, %S) r %d\n"), driveNumber, &KBitProxyDrive, r);
 	test (r >= 0);
 
-	_LIT(KFileSystem, "FAT");
-	r = TheFs.MountFileSystem(KFileSystem, driveNumber);
-	test.Printf(_L("MountFileSystem(%S) r %d\n"), &KFileSystem, r);
+    //-- query existing file system name on the drive that we are be parasiting on.
+    TFSName fsName;
+    r = TheFs.FileSystemName(fsName, drive);
 	test(r == KErrNone);
 
 
+	r = TheFs.MountFileSystem(fsName, driveNumber);
+	test.Printf(_L("MountFileSystem(%S) r %d\n"), &fsName, r);
+	test(r == KErrNone);
+
+
+
 	RFs fs;
 	r = fs.Connect();
 	test(r == KErrNone);
@@ -135,8 +144,8 @@
 	test.Printf(_L("RDir::Open(%S) r %d\n"), &dirPath, r);
 
 
-	r = TheFs.DismountFileSystem(KFileSystem, driveNumber);
-	test.Printf(_L("DismountFileSystem(%S) r %d\n"), &KFileSystem, r);
+	r = TheFs.DismountFileSystem(fsName, driveNumber);
+	test.Printf(_L("DismountFileSystem(%S) r %d\n"), &fsName, r);
 	test (r == KErrInUse);
 
 	// dismount failed - attempt a forced dismount
@@ -144,7 +153,7 @@
 	TheFs.NotifyDismount(driveNumber, stat, EFsDismountForceDismount);
 	User::WaitForRequest(stat);
 	r = stat.Int();
-	test.Printf(_L("DismountFileSystem(%S, EFsDismountForceDismount) r %d\n"), &KFileSystem, r);
+	test.Printf(_L("DismountFileSystem(%S, EFsDismountForceDismount) r %d\n"), &fsName, r);
 	test (r == KErrNone);
 
 	r = TheFs.DismountProxyDrive(driveNumber);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/base_sdiotests.history.xml	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<relnotes name="E32TEST">
+  <purpose>
+  </purpose>
+</relnotes>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/base_sdiotests.mrp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,12 @@
+# component name "SDIO Tests"
+
+component	base_sdiotests
+source		\sf\os\kernelhwsrv\kerneltest\sdiotest
+binary		\sf\os\kernelhwsrv\kerneltest\sdiotest all
+exports		\sf\os\kernelhwsrv\kerneltest\sdiotest
+
+notes_source	\component_defs\release.src
+
+
+ipr T 
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/bld.inf	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,49 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// SDIO tests
+// 
+//
+
+/**
+ @file
+*/
+
+
+
+PRJ_PLATFORMS
+
+ARM4 ARM4T ARMV4 ARMV5
+ARM4SMP ARMV4SMP ARMV5SMP ARMV6SMP
+
+// To build for WINS/WINSCW comment out the following line - if this is required, 
+// need to delete medmmc.pdd to stop the fileserver startup thread from attempting
+// to load both
+// WINS WINSCW
+
+PRJ_EXPORTS
+PRJ_MMPFILES
+
+PRJ_TESTMMPFILES
+
+
+#if defined(GENERIC_MARM)
+#ifndef SMP
+sdiotest		manual
+#endif
+
+d_sdioif		manual
+#endif
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/d_sdioif.mmp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,42 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// LDD for testing SDIO functions
+// 
+//
+
+#include "kernel/kern_ext.mmh"
+
+TARGET         d_sdioif.ldd
+TARGETTYPE     LDD
+sourcepath	source
+SOURCE         d_sdioif.cpp
+LIBRARY		epbussdio.lib
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+USERINCLUDE  ../../kernel/eka/drivers/pbus/mmc/sdcard/sdcard3c
+USERINCLUDE  ../../kernel/eka/drivers/pbus/mmc/sdcard/sdcard3c/sdio
+USERINCLUDE	 ../../kernel/eka/include/drivers
+
+start wins
+win32_library			kernel32.lib
+#if defined(VC32)
+win32_library			libc.lib
+#endif
+end
+
+epocallowdlldata
+
+capability	all
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/sdiotest.mmp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,30 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Test for SDIO functions
+// 
+//
+
+OPTION CW   -w off
+TARGET         sdiotest.exe
+TARGETTYPE     EXE
+SOURCEPATH	source
+SOURCE         sdiotest.cpp sdio_io.cpp
+SOURCEPATH     ../e32utils/pccd
+SOURCE         tdisplay.cpp
+LIBRARY        euser.lib
+USERINCLUDE    ../e32utils/pccd
+USERINCLUDE    ../sdiotest
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+macro		__SECURE_API__
+capability	all
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/source/d_sdioif.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,825 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// LDD for testing SDIO functions
+// 
+//
+
+#include <kernel/kernel.h>
+#include "regifc.h"
+#include "cisreader.h"
+#include "d_sdioif.h"
+
+/**
+Define the name of the LDD.
+
+@internal
+@test
+*/
+_LIT(KLddName,"D_SDIOIF");
+
+/**
+Define the version of the LDD.
+
+@internal
+@test
+*/
+const TInt KMajorVersionNumber=1;
+const TInt KMinorVersionNumber=0;
+const TInt KBuildVersionNumber=1;
+
+/**
+Define the default socket number.
+
+@internal
+@test
+*/
+#ifdef __WINS__
+	const TInt KSocketNumber = 0;
+#else
+	const TInt KSocketNumber = 0;
+//	const TInt KSocketNumber = 1;	// 1 for Integrator!!
+#endif
+
+/**
+Define the default stack number.
+
+@internal
+@test
+*/
+const TInt KStackNumber  = 0;
+
+/**
+Define the default card number.
+
+@internal
+@test
+*/
+const TInt KCardNumber   = 0;
+
+/**
+Define an invalid function number outside the normal 0-7 range.
+
+@internal
+@test
+*/
+const TUint8 KInvalidFuncNum = 8;
+
+/**
+Define the global Dfc Que.
+
+@internal
+@test
+*/
+TDynamicDfcQue* gDfcQ;
+
+class DTestFactory : public DLogicalDevice
+/**
+Class to act as a factory for the test LDD
+
+@internal
+@test
+*/
+	{
+public:
+	DTestFactory();
+	~DTestFactory();
+	virtual TInt Install(); 					//overriding pure virtual
+	virtual void GetCaps(TDes8& aDes) const;	//overriding pure virtual
+	virtual TInt Create(DLogicalChannelBase*& aChannel); 	//overriding pure virtual
+	};
+
+
+class DTest : public DLogicalChannel
+/**
+Class containing the logical device driver to drive the SDIO classes.
+
+@internal
+@test
+*/
+	{
+public:
+	DTest();
+	virtual ~DTest();
+protected:
+	virtual TInt DoCreate(TInt aUnit, const TDesC8* anInfo, const TVersion& aVer);
+	virtual void HandleMsg(class TMessageBase *);
+	virtual TInt SendMsg(TMessageBase* aMsg);
+private:
+	TInt SendRequest(TMessageBase* aMsg);
+	TInt DoRequest(TInt aReqNo, TRequestStatus* aStatus, TAny* a1, TAny* a2);
+	TInt SendControl(TMessageBase* aMsg);
+	TInt DoControl(TInt aFunction, TAny* a1, TAny* a2);
+	TInt CheckForChangeOfCis(TInt aFunc);
+	TInt DoCancel(TUint aMask);
+	static void EventCallBack(TAny* aPtr, TInt aReason, TAny* a1, TAny* a2);
+
+private:
+	// The SDIO objects
+	DMMCSocket* iSocketP;
+	DMMCStack*  iStackP;
+	TSDIOCard*  iCardP;
+    TInt iFunc;
+	TCisReader iCisRd;
+
+	DThread* iClient;
+	TPBusCallBack iBusEventCallback;
+
+	// Client requests used for creating local copies of user requests, WDP safe
+	TClientRequest* 								iPowerUpRequest;
+	TClientRequest* 								iResetCisRequest;
+	TClientDataRequest<TSDIOCardConfig>*			iCardCommonReadRequest;
+	TClientDataRequest<TSDIOFunctionCaps>*			iFunctionCapsRequest;
+	TClientDataRequest<TUint>*						iReadDirectRequest; // Use TUint rather than TUint8 for alignment purposes
+	};
+
+DECLARE_STANDARD_LDD()
+/**
+The standard entry point for logical device drivers.
+
+@internal
+@test
+*/
+	{
+	return new DTestFactory;
+	}
+
+DTestFactory::DTestFactory()
+/**
+Constructor.
+
+@internal
+@test
+*/
+	{
+    iParseMask=KDeviceAllowUnit;
+	iUnitsMask=0xffffffff;
+	iVersion=TVersion(KMajorVersionNumber,KMinorVersionNumber,KBuildVersionNumber);
+	}
+
+TInt DTestFactory::Create(DLogicalChannelBase*& aChannel)
+/**
+Create a new DTest on this logical device.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	aChannel=new DTest;
+	return aChannel?KErrNone:KErrNoMemory;
+	}
+
+const TInt KDSdioIfThreadPriority = 27;
+ _LIT(KDSdioIfThread,"DSdioIfThread");
+
+TInt DTestFactory::Install()
+/**
+Install the LDD - overriding pure virtual.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	// Allocate a kernel thread to run the DFC 
+	TInt r = Kern::DynamicDfcQCreate(gDfcQ, KDSdioIfThreadPriority, KDSdioIfThread);
+
+	if (r != KErrNone)
+		return r; 	
+
+	return SetName(&KLddName);
+	}
+
+void DTestFactory::GetCaps(TDes8& aDes) const
+/**
+Return the capabilities of the LDD.
+
+@return A packaged TCapsTestV01.
+
+@internal
+@test
+*/
+	{
+	TCapsTestV01 b;
+	b.iVersion=TVersion(KMajorVersionNumber,KMinorVersionNumber,KBuildVersionNumber);
+    Kern::InfoCopy(aDes,(TUint8*)&b,sizeof(b));
+	}
+
+DTestFactory::~DTestFactory()
+/**
+Destructor
+
+@internal
+@test
+*/
+	{
+	if (gDfcQ)
+		gDfcQ->Destroy();
+	}
+
+TInt DTest::DoCreate(TInt aUnit, const TDesC8* /*aInfo*/, const TVersion& aVer)
+/**
+Create a logical channel.
+
+@param aUnit The socket number.
+@param aInfo Not used.
+@param aVer The version requested.
+
+@return KErrNone if the channel was created. KErrNotSupported if the version is not supported
+        otherwise one of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+
+	if (!Kern::QueryVersionSupported(TVersion(KMajorVersionNumber,KMinorVersionNumber,KBuildVersionNumber),aVer))
+		return KErrNotSupported;
+
+	// Create the asynchronous callback client request
+	TInt ret = Kern::CreateClientRequest(iPowerUpRequest);
+	if (ret != KErrNone)
+		return ret;
+
+	ret = Kern::CreateClientRequest(iResetCisRequest);
+	if (ret != KErrNone)
+		return ret;
+	
+	ret = Kern::CreateClientDataRequest(iReadDirectRequest);
+	if (ret != KErrNone)
+		return ret;
+
+	ret = Kern::CreateClientDataRequest(iCardCommonReadRequest);
+	if (ret != KErrNone)
+		return ret;
+
+	ret = Kern::CreateClientDataRequest(iFunctionCapsRequest);
+	if (ret != KErrNone)
+		return ret;
+	
+	//
+	// Obtain the appropriate card from the socket/stack
+	//
+	iSocketP = static_cast<DMMCSocket*>(DPBusSocket::SocketFromId(KSocketNumber));
+	if(iSocketP == NULL)
+		return KErrNoMemory;
+
+	iStackP = static_cast<DSDIOStack*>(iSocketP->Stack(KStackNumber));
+	if(iStackP == NULL)
+		return KErrNoMemory;
+
+	iCardP = static_cast<TSDIOCard*>(iStackP->CardP(KCardNumber));
+	if(iCardP == NULL)
+		return KErrNoMemory;
+
+	iFunc=KInvalidFuncNum; // Indicates Cis reader isn't selected
+
+	SetDfcQ(gDfcQ);
+	iMsgQ.Receive();
+
+	iBusEventCallback.SetSocket(aUnit);
+	iBusEventCallback.Add();
+
+	return KErrNone;
+	}
+
+DTest::DTest()
+/**
+Constructor.
+
+@internal
+@test
+*/
+	: iBusEventCallback(DTest::EventCallBack, this)
+	{
+	iClient=&Kern::CurrentThread();
+	((DObject*)iClient)->Open();	// can't fail since thread is running
+	}
+
+
+DTest::~DTest()
+/**
+Destructor.
+
+@internal
+@test
+*/
+	{
+	iBusEventCallback.Remove();
+	
+	// Destroy the client requests 
+	Kern::DestroyClientRequest(iPowerUpRequest);
+	Kern::DestroyClientRequest(iResetCisRequest);
+	Kern::DestroyClientRequest(iReadDirectRequest);	
+	Kern::DestroyClientRequest(iCardCommonReadRequest);
+	Kern::DestroyClientRequest(iFunctionCapsRequest);
+	
+	Kern::SafeClose((DObject*&)iClient,NULL);
+	}
+
+/**
+Pre-process the received message to prepare the client's request.
+
+@param aMsg A pointer to a message (request) from the user side.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::SendMsg(TMessageBase* aMsg)
+	{
+	TThreadMessage& m = *(TThreadMessage*)aMsg;
+    TInt id = m.iValue;
+
+	// we only support one client
+	if (id != (TInt)ECloseMsg && m.Client() != iClient)
+		return KErrAccessDenied;
+	
+	TInt r = KErrNone;
+	if (id != (TInt)ECloseMsg && id != KMaxTInt)
+		{
+		if (id<0)
+			{
+			// It's a request
+			TRequestStatus* pS = (TRequestStatus*)m.Ptr0();
+			
+			// Pre-process the request
+			r = SendRequest(aMsg);
+			if (r != KErrNone)
+				Kern::RequestComplete(pS,r);
+			}
+		else
+			{
+			// Pre-process the control 
+			r = SendControl(aMsg);
+			}
+		}
+	else
+		r = DLogicalChannel::SendMsg(aMsg);
+	
+	return r;
+	}
+
+/**
+Handle a request message from the user side RSdioCardCntrlIf.
+
+@param aMsg A pointer to a message (request) from the user side.
+
+@internal
+@test
+*/
+void DTest::HandleMsg(TMessageBase* aMsg)
+    {
+    TThreadMessage& m=*(TThreadMessage*)aMsg;
+    TInt id=m.iValue;
+    
+	if (id==(TInt)ECloseMsg)
+		{
+	    // Check for a close message
+		m.Complete(KErrNone, EFalse);
+		return;
+		}
+    else if (id==KMaxTInt)
+		{
+		// DoCancel
+		DoCancel(m.Int0());
+		m.Complete(KErrNone, ETrue);
+		return;
+		}
+
+    if (id<0)
+		{
+		// DoRequest
+		TRequestStatus* pS=(TRequestStatus*)m.Ptr0();
+		TInt r=DoRequest(~id, pS, m.Ptr1(), m.Ptr2());
+		if (r!=KErrNone)
+	    	Kern::RequestComplete(iClient, pS, r);
+		m.Complete(KErrNone,ETrue);
+		}
+    else
+		{
+		// DoControl
+		TInt r=DoControl(id,m.Ptr0(),m.Ptr1());
+		m.Complete(r,ETrue);
+		}
+	}
+
+/**
+Handle a pre-process for a request message from the user side RSdioCardCntrlIf.
+This will set-up the client requests.
+
+@param aMsg A pointer to a message (request) from the user side.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::SendRequest(TMessageBase* aMsg)
+	{
+	TThreadMessage& m = *(TThreadMessage*)aMsg;
+    TInt function = ~m.iValue;
+	TRequestStatus* pS = (TRequestStatus*)m.Ptr0();
+	TAny* a2 = m.Ptr2();
+		
+	TInt r = KErrNotSupported;
+	switch (function)
+		{
+		// A request to power up the SDIO card & stack
+		case RSdioCardCntrlIf::EReqPwrUp:
+			r = iPowerUpRequest->SetStatus(pS);
+	       	if (r != KErrNone)
+        		return r;
+ 			break;
+		// A request to read generic data from the SDIO card 
+        case RSdioCardCntrlIf::ERequestReadDirect:
+           	{
+            r = iReadDirectRequest->SetStatus(pS);
+            if (r != KErrNone)
+            	return r;
+            iReadDirectRequest->SetDestPtr(a2);            
+            }
+    		break;			
+    	// A request to reset the CIS pointer 
+        case RSdioCardCntrlIf::ERequestResetCis:
+			r = iResetCisRequest->SetStatus(pS);
+			if (r != KErrNone)
+				return r;
+			break;
+			
+       	// A request to read the Card Common Config  
+        case RSdioCardCntrlIf::ERequestGetCommonConfig:
+        	{
+        	r = iCardCommonReadRequest->SetStatus(pS);
+        	if (r != KErrNone)
+        		return r;
+        	iCardCommonReadRequest->SetDestPtr(a2);
+        	}
+			break;
+			
+        // A request to read the function data (FBR)  
+        case RSdioCardCntrlIf::ERequestGetFunctionConfig:
+        	{
+        	r = iFunctionCapsRequest->SetStatus(pS);
+        	if (r != KErrNone)
+        		return r;
+        	iFunctionCapsRequest->SetDestPtr(a2);
+        	}
+			break;
+		}
+
+	if (r == KErrNone)
+		r = DLogicalChannel::SendMsg(aMsg);
+	return r;
+	}
+
+/**
+Process any asynchronous requests from the user side.
+
+@param aFunction The asynchronous function to invoke. 
+@param aStatus On completion, the success code for the function.
+@param a1 Context sensitive data.
+@param a2 Context sensitive data.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::DoRequest(TInt aFunction, TRequestStatus* aStatus, TAny* a1, TAny* a2)
+	{
+	TInt r=KErrNone;
+    TInt func = (TInt)a1;
+	switch (aFunction)
+		{
+		// A request to power up the SDIO card & stack
+        case RSdioCardCntrlIf::EReqPwrUp:
+			{
+			if(!iSocketP->CardIsPresent())
+				{
+				// An SDIO card is not present
+				Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrNotReady);
+				}
+			else if(iSocketP->State() == EPBusOn)
+				{
+				// The card is already powered up
+				Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrNone);
+				}
+			else
+				{
+				// Power up the card
+				iSocketP->PowerUp();
+				}
+			break;
+			}
+
+		// A request to read generic data from the SDIO card 
+        case RSdioCardCntrlIf::ERequestReadDirect:
+            {
+            TInt addr = (TInt)a1;
+
+    		TUint8 val = 0;
+			r = iCardP->CommonRegisterInterface()->Read8(addr, &val);
+			if(r == KErrNone)
+				{
+		   		iReadDirectRequest->Data() = (TUint)val;
+				}
+				
+			Kern::QueueRequestComplete(iClient, iReadDirectRequest, r);
+			break;
+            }
+
+    	// A request to reset the CIS pointer 
+        case RSdioCardCntrlIf::ERequestResetCis:
+            {
+	        if ((r=CheckForChangeOfCis(func))==KErrNone)
+	            {
+			    iCisRd.Restart();
+	            }
+	            
+			Kern::QueueRequestComplete(iClient, iResetCisRequest, r);
+			break;
+            }
+
+       	// A request to read the card common config  
+        case RSdioCardCntrlIf::ERequestGetCommonConfig:
+            {
+	        if ((r=CheckForChangeOfCis(func))==KErrNone)
+                {
+				memset(&iCardCommonReadRequest->Data(), 0, sizeof(TSDIOCardConfig));
+				
+		        r = iCisRd.FindReadCommonConfig(iCardCommonReadRequest->Data());
+				Kern::QueueRequestComplete(iClient, iCardCommonReadRequest, r);
+                }
+			break;
+            }
+
+        // A request to read the function data (FBR)  
+        case RSdioCardCntrlIf::ERequestGetFunctionConfig:
+            {		        
+	        if ((r=CheckForChangeOfCis(func))==KErrNone)
+                {
+				memset(&iFunctionCapsRequest->Data(), 0, sizeof(TSDIOFunctionCaps));
+				
+		        r=iCisRd.FindReadFunctionConfig(iFunctionCapsRequest->Data());	
+				Kern::QueueRequestComplete(iClient, iFunctionCapsRequest, r);
+                }            
+			break;
+            }
+
+		default:
+			r=KErrNotSupported;
+			break;
+		}
+	return r;
+	}
+
+/**
+Surround the DoControl command, creating a kernel copy of the user side data, then copying back afterwards
+
+@param aMsg The message 
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::SendControl(TMessageBase* aMsg)
+	{
+	TThreadMessage& m = *(TThreadMessage*)aMsg;
+    TInt id = m.iValue;
+
+    TSdioCardInfo kernelCardInfo;
+    TAny* userCardInfoPtr = m.Ptr0();
+    
+	// thread-local copy of configuration data	
+	switch (id)
+		{
+		case RSdioCardCntrlIf::ESvCardInfo:
+			// copy config from client to local buffer in context of client thread
+			umemget32(&kernelCardInfo, userCardInfoPtr, sizeof(TSdioCardInfo));
+			// update message to point to kernel-side buffer
+			m.iArg[0] = &kernelCardInfo;
+			break;
+		}
+
+	TInt r = DLogicalChannel::SendMsg(aMsg);
+	if (r != KErrNone)
+		return r;
+
+	switch (id)
+		{
+		case RSdioCardCntrlIf::ESvCardInfo:
+			// copy config from local bufferto client in context of client thread
+			umemput32(userCardInfoPtr, &kernelCardInfo, sizeof(TSdioCardInfo));
+			break;
+		}
+
+	return r;
+	}
+
+/**
+Process any synchronous requests from the user side.
+
+@param aFunction The synchronous function to invoke. 
+@param a1 Context sensitive data.
+@param a2 Context sensitive data.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::DoControl(TInt aFunction, TAny* a1, TAny* /*a2*/)
+	{
+	TInt r=KErrNone;
+	switch (aFunction)
+		{
+		// Read the card information data
+		case RSdioCardCntrlIf::ESvCardInfo:
+            {
+			if(iCardP)
+				{
+				iCardP->CheckCIS();
+				TSdioCardInfo* cardInfoPtr = (TSdioCardInfo*)a1;
+				TSdioCardInfo& info = *cardInfoPtr;
+
+				//
+				// Extract the card information
+				//
+				info.isComboCard=iCardP->IsComboCard();				
+	            info.iIsReady=iCardP->IsPresent();
+	            info.iIsLocked=iCardP->IsLocked();
+	            info.iCardSpeed=iCardP->MaxTranSpeedInKilohertz();
+				TCID* cid=(TCID*)&(iCardP->CID());
+				TInt i;
+				for (i=0;i<16;i++)
+					info.iCID[i]=cid->At(i);
+				const TCSD& csd = iCardP->CSD();
+				for (i=0;i<16;i++)
+					info.iCSD[i]=csd.At(i);
+	            info.iRCA=TUint16(iCardP->RCA());
+	            info.iMediaType=TMmcMediaType(iCardP->MediaType());
+
+				//
+				// Extract the function information
+				//
+				info.iFuncCount = iCardP->FunctionCount();
+
+				TSDIOFunctionCaps functionCaps;
+				TSDIOFunction* functionP = NULL;
+
+				for(TUint8 func=0; func<=info.iFuncCount; func++)
+					{
+					functionP = iCardP->IoFunction((TUint8) (func));
+					if(functionP)
+						{
+						functionCaps = functionP->Capabilities();
+						info.iFunction[func].iType = (TSdioFunctionType)(functionCaps.iType);
+						}
+					}
+				}
+			else
+			    {
+                r = KErrGeneral;
+			    }
+
+			break;
+            }
+		default:
+			r=KErrNotSupported;
+			break;
+		}
+	return r;
+	}
+
+
+/**
+Check if diferent function selected, select new CIS if necessary.
+
+@param aFunc The SDIO function. 
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::CheckForChangeOfCis(TInt aFunc)
+	{
+
+	if (iFunc!=aFunc||iFunc==KInvalidFuncNum)
+		{
+		TInt err;
+		if ((err=iCisRd.SelectCis(KSocketNumber,0,0,(TUint8) aFunc))==KErrNone)
+			iFunc=aFunc;
+		return(err);
+		}
+	return(KErrNone);
+	}
+
+/**
+Cancel an asynchronous request
+
+@param aMask Mask of requests to cancel
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+TInt DTest::DoCancel(TUint /*aMask*/)
+	{	
+	if (iPowerUpRequest->IsReady())
+		{
+		Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrCancel);
+		}
+	
+	if (iResetCisRequest->IsReady())
+		{
+		Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrCancel);
+		}
+
+	if (iCardCommonReadRequest->IsReady())
+		{
+		Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrCancel);
+		}
+
+	if (iFunctionCapsRequest->IsReady())
+		{
+		Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrCancel);
+		}
+
+	if (iReadDirectRequest->IsReady())
+		{
+		Kern::QueueRequestComplete(iClient, iPowerUpRequest, KErrCancel);
+		}
+	
+	return KErrNone;
+	}
+
+/**
+Asynchronous call backs from the SDIO stack
+
+@param aPtr Data passed in when the callback was registered.
+@param aReason The reason for the callback, one of TPBusCallBack::EPBusStateChange
+               or TPBusCallBack::EPBusCustomNotification.                  
+@param a1 Context sensitive data.
+@param a2 Context sensitive data.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+void DTest::EventCallBack(TAny* aPtr, TInt aReason, TAny* a1, TAny* a2)
+	{
+	DTest &mci = *(DTest*)aPtr;
+
+	if (mci.iPowerUpRequest->IsReady())
+		{
+		// There is an TRequestStatus pending
+		TInt retCode = KErrCompletion;
+
+		switch(aReason)
+			{
+			// There has been a state change
+			case TPBusCallBack::EPBusStateChange:
+				{
+				TPBusState newState = (TPBusState)(TInt)a1;
+				TInt errorCode = (TInt)a2;
+
+				switch(newState)
+					{
+					case EPBusCardAbsent:	retCode = KErrNotFound;		break;			
+					case EPBusOff:			retCode = errorCode;		break;
+					case EPBusPsuFault:		retCode = KErrBadPower;		break;
+					case EPBusOn:			retCode = KErrNone;			break;
+					case EPBusPowerUpPending:
+					case EPBusPoweringUp:
+					default:	
+						break;
+					}
+
+				break;
+				}
+			}
+
+		if(retCode != KErrCompletion)
+			{
+   			Kern::QueueRequestComplete(mci.iClient, mci.iPowerUpRequest, retCode);
+			}
+		}
+	}
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/source/d_sdioif.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,327 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// LDD for testing SDIO functions
+// 
+//
+
+#ifndef __D_SDIOIF_H__
+#define __D_SDIOIF_H__
+#include <e32cmn.h>
+
+#ifdef __KERNEL_MODE__
+#include "function.h"
+#else
+#include <e32std.h>
+#endif
+#include "sdiotests.h"
+
+/**
+Defines the type of media.
+    
+@internal
+@test
+*/
+enum TMmcMediaType 
+	{
+	/** An MMC ROM card.*/
+	EMmcROM,
+	/** An MMC Flash card.*/
+	EMmcFlash,
+	/** An SDIO card.*/
+	EMmcIO,
+	/** Another type of supported card.*/
+	EMmcOther,
+	/** A non-supported card.*/
+	EMmcNotSupported
+	};
+
+/**
+Defines the SDIO Card Status.
+    
+@internal
+@test
+@test
+*/
+enum TSdioCardStatus 
+	{
+	/** An SDIO card is not present.*/
+	ESdioCardNotPresent,
+	/** An SDIO card is present but is not ready to be accessed.*/
+	ESdioCardNotReady,
+	/** An SDIO card is present but is not valid.*/
+	ESdioCardBad,
+	/** An SDIO card is present and ready to be used.*/
+	ESdioCardReady
+	};
+
+typedef TInt TSocket;
+
+class TSdioFunctionInfo
+/**
+Class to encapsulate function information.
+
+@internal
+@test
+*/
+	{
+public:
+	inline TSdioFunctionInfo()
+	/**
+	Constructor.
+	
+	Sets the function type to unknown.
+	*/
+		: iType(ESdioFunctionTypeUnknown) { /* Empty */ }
+public:
+	TSdioFunctionType iType;
+	};
+
+/**
+Defines the maximum number of functions an SDIO card can support.
+*/
+const TUint KMaxCardFunc=8;
+
+class TSdioCardInfo
+/**
+Class to encapsulate the SDIO card CCCR information.
+
+@internal
+@test
+*/
+	{
+public:
+	inline TSdioCardInfo()
+	/**
+	Constructor.
+	
+	Clears the memory and sets the media type to not supported. 
+	*/
+		  {memset(this, 0, sizeof(TSdioCardInfo)); iMediaType=EMmcNotSupported;}
+public:
+	/** The ready status for the card.*/
+	TBool iIsReady;
+	/** The lock status for the card.*/
+	TBool iIsLocked;
+	/** The CID (Card Identification number) buffer.*/
+	TUint8 iCID[16];
+	/** The CSD (Card Specific Data register) buffer.*/
+	TUint8 iCSD[16];
+	/** The RCA (Relative Card Address).*/
+	TUint16 iRCA;
+	/** The Media Type.*/
+	TMmcMediaType iMediaType;
+	/** The SDIO card speed.*/
+	TUint iCardSpeed;
+	/** Whether the SDIO card is a combo card i.e. has a memory portion.*/
+	TBool isComboCard;
+	/** The number of function this card supports.*/
+	TInt iFuncCount;
+	/** Information for each function.*/
+	TSdioFunctionInfo iFunction[KMaxCardFunc];
+	};
+
+/**
+Package the TSdioCardInfo
+
+@internal
+@test
+*/
+typedef TPckgBuf<TSdioCardInfo> TSdioCardInfoPckg;
+
+/**
+Class to encapsulate the LDD version
+
+@internal
+@test
+*/
+class TCapsTestV01
+	{
+public:
+	/** Version information.*/
+	TVersion	iVersion;
+	};
+
+class TReadDirectData
+/**
+Class to encapsulate data read from the SDIO card
+
+@internal
+@test
+*/
+    {
+public:
+    inline TReadDirectData(TInt aAddr,TUint8 *aVal) 
+	/**
+	Constructor. Sets the address and value buffer.
+	
+	@param aAddr The address of the register to read
+	@param aVal The address to read the contents of the register into.
+	*/
+        : iAddr(aAddr), iVal(aVal) 
+        {}
+public:
+	/** The register address.*/
+    TInt iAddr;
+	/** The memory location to read data into.*/
+    TUint8* iVal;
+    };
+
+class RSdioCardCntrlIf : public RBusLogicalChannel
+/**
+Class for the user side logical device channel to the kernel side device driver (LDD).
+
+@internal
+@test
+*/
+	{
+public:
+	/**
+	Defines the version information.
+	    
+	@internal
+	@test
+	*/
+	enum
+		{
+		/** The major version number.*/
+		EMajorVersionNumber=1,
+		/** The minor version number.*/
+		EMinorVersionNumber=0,
+		/** The build number.*/
+		EBuildVersionNumber=1
+		};
+
+	/**
+	Defines the type of media.
+	    
+	@internal
+	@test
+	*/
+    enum
+		{
+		/** Retrieve the card information.*/
+		ESvCardInfo,
+
+		/** Request the card to power up.*/
+		EReqPwrUp,
+		/** Retrieve to read data from the card's registers.*/
+        ERequestReadDirect,
+		/** Reset the CIS (Card information Structure) pointer.*/
+        ERequestResetCis,
+		/** Retrieve the CCCR data.*/
+        ERequestGetCommonConfig,
+		/** Retrieve the function information.*/
+        ERequestGetFunctionConfig,		
+		};
+
+public:
+	/**
+	Cancel the current request.
+	*/
+	inline void Cancel();
+	
+	/**
+	Open a channel to the device driver.	
+	
+	@param aSocket The socket number to open a channel for.
+	@param aVer The version of the LDD required.
+	
+	@return One of the system wide codes.
+	*/ 
+	inline TInt Open(TInt aSocket, const TVersion& aVer)
+		{return(DoCreate(_L("D_SDIOIF"),aVer,(TInt)aSocket,NULL,NULL));}
+	
+	/**
+	Return the version required.	
+
+	@return The version required.
+	*/ 
+	inline TVersion VersionRequired() const
+		{return(TVersion(EMajorVersionNumber,EMinorVersionNumber,EBuildVersionNumber));}
+	
+	//
+	// DoControl...
+	// 
+
+	/**
+	Return the card information.	
+
+	@param aInfo A pointer to a TSdioCardInfo class which will contain card information on completion.
+	
+	@return One of the system wide codes.
+	*/ 
+	inline TInt CardInfo(TSdioCardInfo *aInfo)
+		{return(DoControl(ESvCardInfo, (TAny*)aInfo));}
+	
+	//
+	// DoRequest...
+	// 
+
+	/**
+	Power up the SDIO card and the stack and stop it from powering down.	
+
+	@param aStatus On completion, the power up system wide error code.
+	*/ 
+	inline void PwrUpAndInitStack(TRequestStatus& aStatus)
+		{DoRequest(EReqPwrUp,aStatus);}
+
+	/**
+	Read data from the SDIO card	
+
+	@param aStatus On completion, the power up system wide error code.
+	@param aAddr The register address to read.
+	@param aVal On completion, the value of the register. A TUint rather than TUint8 for alignment purposes.
+	*/ 
+	inline void ReadDirect(TRequestStatus& aStatus, TInt aAddr, TUint &aVal)
+		{
+		DoRequest(ERequestReadDirect, aStatus, (TAny*)aAddr, (TAny*)&aVal);
+		}
+
+	/**
+	Reset the CIS pointer.	
+
+	@param aStatus On completion, the power up system wide error code.
+	@param aFunc The function number to address on the card.
+	*/ 
+	inline void ResetCis(TRequestStatus& aStatus, TInt aFunc)
+		{
+		DoRequest(ERequestResetCis, aStatus, (TAny*)aFunc);
+		}
+
+	/**
+	Get the SDIO card Common config.	
+
+	@param aStatus On completion, the power up system wide error code.
+	@param aFunc The function number to address on the card.
+	@param anInfo A pointer to a TSDIOCardConfig class which will contain coomon config information on completion.
+	*/ 
+	inline void GetCommonConfig(TRequestStatus& aStatus, TInt aFunc,TSDIOCardConfigTest *anInfo)
+		{
+		DoRequest(ERequestGetCommonConfig, aStatus, (TAny*)aFunc, (TAny*)anInfo);
+		}
+
+	/**
+	Get the FBR (Function Basic Registers) data	.
+	
+	@param aStatus On completion, the power up system wide error code.
+	@param aFunc The function number to address on the card.
+	@param anInfo A pointer to a TSDIOFunctionCaps class which will contain FBR information on completion.
+	*/ 
+	inline void GetFunctionConfig(TRequestStatus& aStatus, TInt aFunc, TSDIOFunctionCapsTest *anInfo)
+		{
+		DoRequest(ERequestGetFunctionConfig, aStatus, (TAny*)aFunc, (TAny*)anInfo);
+		}
+	};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/source/sdio_io.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,139 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// LDD for testing SDIO functions
+// 
+//
+
+#include "sdio_io.h"
+
+/** Text to replace any overflow in logging */
+_LIT(KEllipses, "...");
+
+#if defined(_UNICODE)
+void CIOBase::TIOOverflowHandler::Overflow(TDes16 &aDes)
+	{
+	// Replace the last three characters with ellipses
+	aDes.RightTPtr(KEllipses().Length()).Copy(KEllipses);
+	}
+#else
+void CIOBase::TIOOverflowHandler::Overflow(TDes8 &aDes)
+	{
+	// Replace the last three characters with ellipses
+	aDes.RightTPtr(KEllipses().Length()).Copy(KEllipses);
+	}
+#endif
+
+//
+// CIOBase
+//
+void CIOBase::Heading(TRefByValue<const TDesC> aFmt,...)
+	{
+	FORMAT_TEXT(aFmt);
+	DoHeading();
+	}
+
+void CIOBase::Instructions(TBool topLine, TRefByValue<const TDesC> aFmt,...)
+	{
+	FORMAT_TEXT(aFmt);
+	DoInstructions(topLine);
+	}
+
+void CIOBase::Printf(TRefByValue<const TDesC> aFmt,...)
+	{
+	FORMAT_TEXT(aFmt);
+	DoPrintf();
+	}
+
+void CIOBase::FormatText(TRefByValue<const TDesC> aFmt, VA_LIST aList)
+	{
+	iText.Zero();
+	iText.AppendFormatList(aFmt, aList, &iOverflowHandler);
+	}
+
+//
+// CIOConsole
+//
+CIOConsole::~CIOConsole()
+	{
+	iDisplay.Destroy();
+	}
+	
+void CIOConsole::CreateL(TPtrC aName)
+	{
+	iDisplay.CreateL(aName);
+	}
+
+void CIOConsole::DoHeading()
+	{
+	iDisplay.Heading(iText);
+	}
+
+void CIOConsole::DoInstructions(TBool topLine)
+	{
+	iDisplay.Instructions(topLine, iText);
+	}
+
+void CIOConsole::DoPrintf()
+	{
+	iDisplay.Printf(iText);
+	}
+
+void CIOConsole::ReportError(TPtrC errText, TInt anErr)
+	{
+	iDisplay.ReportError(errText, anErr);
+	}
+
+void CIOConsole::CurserToDataStart()
+	{
+	iDisplay.CurserToDataStart();
+	}
+
+TKeyCode CIOConsole::Getch()
+	{
+	return iDisplay.Getch();
+	}
+
+void CIOConsole::ClearScreen()
+	{
+	iDisplay.ClearScreen();
+	}
+
+//
+// CIORDebug
+//
+void CIORDebug::CreateL(TPtrC aName)
+	{
+	RDebug::RawPrint(aName);
+	}
+
+void CIORDebug::DoHeading()
+	{
+	RDebug::RawPrint(iText);
+	}
+
+void CIORDebug::DoPrintf()
+	{
+	RDebug::RawPrint(iText);
+	}
+
+void CIORDebug::ReportError(TPtrC errText, TInt anErr)
+	{
+	RDebug::RawPrint(errText);
+	RDebug::Printf("Error Code: %d", anErr);
+	}
+	
+void CIORDebug::ClearScreen()
+	{
+	RDebug::Printf("\n\n");
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/source/sdio_io.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,337 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// LDD for testing SDIO functions
+// 
+//
+
+#if !defined(__SDIO_IO_H__)
+#define __SDIO_IO_H__
+
+#include "tdisplay.h"
+
+/**
+Macro to format a variable length number of parameters into the iText member variable.
+
+@param c The format string
+
+@internal
+@test
+*/
+#define FORMAT_TEXT(c) VA_LIST list; \
+	VA_START(list, c); \
+	FormatText(c, list); \
+	VA_END(list)
+
+class CIOBase : public CBase
+/**
+Base class to provide input/output facilities. Uses the function signatures from THexDisplay, 
+with dummy implementation.
+
+@internal
+@test
+*/
+	{
+public:
+
+#if defined(_UNICODE)
+	class TIOOverflowHandler : public TDes16Overflow
+	/**
+	Base class to handle any logging overflows. 
+
+	@internal
+	@test
+	*/
+		{
+		public:
+			/**
+			Handle the overflow. 
+
+			@param aDes The descriptor at its maximum length.
+			
+			@internal
+			@test
+			*/
+			virtual void Overflow(TDes16 &aDes);
+		};
+#else
+	class TIOOverflowHandler : public TDes8Overflow
+	/**
+	Base class to handle any logging overflows. 
+
+	@internal
+	@test
+	*/
+		{
+		public:
+			/**
+			Handle the overflow. 
+
+			@param aDes The descriptor at its maximum length.
+			
+			@internal
+			@test
+			*/
+			virtual void Overflow(TDes8 &aDes);
+		};
+#endif
+	
+	/**
+	Constructor. 
+
+	@internal
+	@test
+	*/
+	CIOBase() {};
+
+	/**
+	Destructor. 
+
+	@internal
+	@test
+	*/
+	~CIOBase() {};
+
+	/**
+	Create the underlying resource. 
+
+	@param aName The name for the tests.
+	
+	@internal
+	@test
+	*/
+	virtual void CreateL(TPtrC aName) {};
+
+	/**
+	Provide a heading for the next test. 
+
+	@param aFmt The heading format.
+	
+	@internal
+	@test
+	*/
+	void Heading(TRefByValue<const TDesC> aFmt,...);
+
+	/**
+	Provide some instructions. 
+
+	@param aTopLine Whether to start from the top.
+	@param aFmt The formmatted text..
+	
+	@internal
+	@test
+	*/
+	void Instructions(TBool aTopLine, TRefByValue<const TDesC> aFmt,...);
+
+	/**
+	Print formatted output. 
+
+	@param aFmt The formmatted text.
+	
+	@internal
+	@test
+	*/
+	void Printf(TRefByValue<const TDesC> aFmt,...);
+
+	/**
+	Report an error. 
+
+	@param aErrText The heading format.
+	@param aErr The error code.
+	
+	@internal
+	@test
+	*/
+	virtual void ReportError(TPtrC aErrText, TInt aErr = KErrNone) {};
+
+	/**
+	Move to the curser to the start of the line. 
+	
+	@internal
+	@test
+	*/
+	virtual void CurserToDataStart() {};
+
+	/**
+	Get a character from the input stream.
+	
+	@return The keycode of the input character. 
+	
+	@internal
+	@test
+	*/
+	virtual TKeyCode Getch() { return EKeyNull; };
+	
+	/**
+	Clear the screen.
+		
+	@internal
+	@test
+	*/
+	virtual void ClearScreen() {};
+	
+protected:
+	virtual void DoHeading() {};
+	virtual void DoInstructions(TBool aTopLine) {};
+	virtual void DoPrintf() {};
+	void FormatText(TRefByValue<const TDesC> aFmt, VA_LIST aList);
+
+protected:	
+	/** A temporary buffer for formatting text */
+	TBuf<512>			iText;
+	/** An overflow handler */
+	TIOOverflowHandler	iOverflowHandler;
+	};
+
+class CIOConsole : public CIOBase
+/**
+Class to provide input/output facilities using THexDisplay.
+
+@internal
+@test
+*/
+	{
+public:
+	/**
+	Constructor. 
+
+	@internal
+	@test
+	*/
+	CIOConsole() {};
+
+	/**
+	Destructor. 
+
+	@internal
+	@test
+	*/
+	~CIOConsole();
+	
+	/**
+	Create the underlying resource. 
+
+	@param aName The name for the tests.
+	
+	@internal
+	@test
+	*/
+	virtual void CreateL(TPtrC aName);
+
+	/**
+	Report an error. 
+
+	@param aErrText The heading format.
+	@param aErr The error code.
+	
+	@internal
+	@test
+	*/
+	virtual void ReportError(TPtrC aErrText, TInt aErr=KErrNone);
+
+	/**
+	Move to the curser to the start of the line. 
+	
+	@internal
+	@test
+	*/
+	virtual void CurserToDataStart();
+
+	/**
+	Get a character from the input stream.
+	
+	@return The keycode of the input character. 
+	
+	@internal
+	@test
+	*/
+	virtual TKeyCode Getch();
+
+	/**
+	Clear the screen.
+		
+	@internal
+	@test
+	*/
+	virtual void ClearScreen();	
+	
+protected:
+	virtual void DoHeading();
+	virtual void DoInstructions(TBool aTopLine);
+	virtual void DoPrintf();
+
+private:
+	THexDisplay	iDisplay;
+	};
+
+class CIORDebug : public CIOBase
+/**
+Class to provide input/output facilities using RDebug.
+
+@internal
+@test
+*/
+	{
+public:
+	/**
+	Constructor. 
+
+	@internal
+	@test
+	*/
+	CIORDebug() {};
+
+	/**
+	Destructor. 
+
+	@internal
+	@test
+	*/
+	~CIORDebug() {};
+	
+	/**
+	Create the underlying resource. 
+
+	@param aName The name for the tests.
+	
+	@internal
+	@test
+	*/
+	virtual void CreateL(TPtrC aName);
+
+	/**
+	Report an error. 
+
+	@param aErrText The heading format.
+	@param aErr The error code.
+	
+	@internal
+	@test
+	*/
+	virtual void ReportError(TPtrC aErrText, TInt aErr=KErrNone);
+	
+	/**
+	Clear the screen.
+	
+	@internal
+	@test
+	*/
+	virtual void ClearScreen();	
+
+protected:
+	virtual void DoHeading();
+	virtual void DoPrintf();
+	};
+
+#endif // __SDIO_IO_H__
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/source/sdiotest.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,729 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Test for SDIO functions
+// 
+//
+
+#include <d32comm.h>
+
+#include "d_sdioif.h"
+#include "sdio_io.h"
+#include "sdiotests.h"
+
+
+enum TPanic {ECreatingIO, ELoadingMmcDriver, EReadingCommandLine};
+
+class RComm : public RBusDevComm
+/**
+Class to serialize writing to the COMM port
+
+@internal
+@test
+*/
+	{
+public:
+	TInt WriteS(const TDesC8& aDes);
+	TInt WriteS(const TDesC8& aDes,TInt aLength);
+	};
+
+TInt RComm::WriteS(const TDesC8& aDes)
+/**
+Write to the COMM port an 8-bit descriptor
+
+@param aDes The descriptor to send to the UART.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	return(WriteS(aDes,aDes.Length()));
+	}
+
+	
+TInt RComm::WriteS(const TDesC8& aDes,TInt aLength)
+/**
+Write to the COMM port an 8-bit descriptor of a specific length
+
+@param aDes The descriptor to send to the UART.
+@param aLength The maximum length of data to send.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	TRequestStatus s;
+	Write(s,aDes,aLength);
+	User::WaitForRequest(s);
+	return(s.Int());
+	}
+
+//
+//
+class TSdioCardDiagServices
+/**
+Class to provide test services for the SDIO common features.
+Uses the RSdioCardCntrlIf user side logical device driver.
+
+@internal
+@test
+*/
+	{
+public:
+	TSdioCardDiagServices();
+    ~TSdioCardDiagServices();
+    TInt Start();
+    
+    TInt doPowerUp(CIOBase& aIO);
+	TInt doGetCardInfo(CIOBase& aIO);	
+	TInt doCardCommonControlRegs(CIOBase& aIO);
+	TInt doCardCommonConfig(CIOBase& aIO);
+    TInt doGetFunctionInfo(CIOBase& aIO);
+    
+	TInt doQuit();
+
+    inline TInt CurrentSocket()
+        {return(iSocket);}
+
+    inline TInt CurrentFunc()
+        {return(iFunc);}
+private:
+    RSdioCardCntrlIf iDriver;
+    TInt iSocket;
+    TInt iFunc;
+	TBool iDriverOpen;
+    };
+
+LOCAL_C void Panic(TPanic aPanic)
+/**
+Panic
+
+@param aPanic The panic code.
+
+@internal
+@test
+*/
+	{
+	User::Panic(_L("SDIOTEST"),aPanic);
+	}
+
+LOCAL_C TPtrC MediaTypeText(TMmcMediaType aType)
+/**
+Convert a media type enumeration to human readable text.
+
+@param aType The media type enumeration value.
+@return A human readable format for the media type.
+
+@internal
+@test
+*/
+	{
+	switch(aType)
+		{
+		case EMmcROM:			return(_L("ROM"));
+		case EMmcFlash:			return(_L("Flash"));
+		case EMmcIO:			return(_L("IO"));
+		case EMmcOther:			return(_L("Other"));
+		case EMmcNotSupported:	return(_L("Not Supported"));
+		default:				return(_L("Unknown"));
+		}
+	}
+
+TSdioCardDiagServices::TSdioCardDiagServices()
+/**
+Constructor.
+
+@internal
+@test
+*/
+    {
+
+    iSocket=0;
+    iFunc=0;
+	iDriverOpen=EFalse;
+    }
+
+TSdioCardDiagServices::~TSdioCardDiagServices()
+/**
+Destructor.
+
+@internal
+@test
+*/
+    {
+
+    iDriver.Close();
+    }
+
+TInt TSdioCardDiagServices::Start()
+/**
+Start the testing by connecting to the uset side logical device driver.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+
+	iDriver.Close();
+	TInt r=iDriver.Open(iSocket,iDriver.VersionRequired());
+	iDriverOpen=(r==KErrNone)?ETrue:EFalse;
+	return(r);
+    }
+
+
+//---------------------------------------------
+//! @SYMTestCaseID FSBASE-SDIOTEST-1
+//! @SYMTestType CIT
+//! @SYMTestCaseDesc Power up the SDIO stack
+//! @SYMPREQ PREQ1623
+//! @SYMREQ REQ5742 
+//! @SYMTestPriority Critical
+//! @SYMTestActions Power up the SDIO stack with an SDIO card inserted
+//! @SYMTestExpectedResults  The stack should report that it is powered up
+//---------------------------------------------
+TInt TSdioCardDiagServices::doPowerUp(CIOBase& aIO)
+/**
+Power up the SDIO stack.
+
+@param aIO The input output device.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+
+	if (!iDriverOpen)
+		return(KErrNotSupported);
+	
+	aIO.ClearScreen();
+	aIO.Heading(_L("Powering up card\n\n"));
+	
+	TInt err;
+	TRequestStatus rs;
+	iDriver.PwrUpAndInitStack(rs);
+	User::WaitForRequest(rs);
+	if ((err=rs.Int())!=KErrNone)
+		{
+		aIO.ReportError(_L("Error Powering Stack"),err);
+		return(err);
+		}
+
+	return(KErrNone);
+	}
+
+//---------------------------------------------
+//! @SYMTestCaseID FSBASE-SDIOTEST-2
+//! @SYMTestType CIT
+//! @SYMTestCaseDesc Read general card information.
+//! @SYMPREQ PREQ1623
+//! @SYMREQ REQ5742  
+//! @SYMTestPriority Critical
+//! @SYMTestActions Read the Media type, CID and CSD registers and number of functions and their names. Display the results.
+//! @SYMTestExpectedResults  The CID and CSD registers should be read with no error.
+//---------------------------------------------
+TInt TSdioCardDiagServices::doGetCardInfo(CIOBase& aIO)
+/**
+Read general card information.
+
+@param aIO The input output device.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	// Make sure stack is powered up
+	TInt err = doPowerUp(aIO);
+	if (err != KErrNone)
+		return err;
+	
+
+	aIO.ClearScreen();
+	aIO.Heading(_L("Card Info"));
+
+	TSdioCardInfo ci;
+	err = iDriver.CardInfo(&ci);
+	if (err!=KErrNone)
+		{
+		aIO.ReportError(_L("Error getting card info"),err);
+		return(err);
+		}
+
+	aIO.CurserToDataStart();
+	aIO.Printf(_L("\nCard Ready     : %d"),ci.iIsReady);
+	aIO.Printf(_L("\nCard Locked    : %d"),ci.iIsLocked);
+	aIO.Printf(_L("\nCard Max Speed : %d Khz"),ci.iCardSpeed);
+	aIO.Printf(_L("\nCard ID        : "));
+	TInt i;
+	for (i=12;i>=0;i-=4)
+		{
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCID[i]);
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCID[i + 1]);
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCID[i + 2]);
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCID[i + 3]);
+		aIO.Printf(_L("\n\t\t\t\t "));
+		}
+	aIO.Printf(_L("\nCard CSD       : "));
+	for (i=12;i>=0;i-=4)
+		{
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCSD[i]);
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCSD[i + 1]);
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCSD[i + 2]);
+		aIO.Printf(_L("%02x"), *(TUint8*)&ci.iCSD[i + 3]);
+		aIO.Printf(_L("\n\t\t\t\t "));
+		}
+	aIO.Printf(_L("\nCard RCA       : %x"),ci.iRCA);
+	TPtrC mtt=MediaTypeText(ci.iMediaType);
+	aIO.Printf(_L("\nMedia Type     : %S"),&mtt);
+	aIO.Printf(_L("\nCombo Card     : %d"),ci.isComboCard);
+
+	aIO.Printf(_L("\n\nDetected %d Function(s)\n"),ci.iFuncCount);
+	for(i=1; i<ci.iFuncCount+1; i++)
+		{
+		TSdioFunctionType type = ci.iFunction[i].iType;
+		TPtrC tt = TSDIOTestUtils::FunctionTypeText(type);
+		aIO.Printf(_L("Function %d : %S (%d)\n"),i, &tt, type);
+		}
+	
+	return KErrNone;
+	}
+
+//---------------------------------------------
+//! @SYMTestCaseID FSBASE-SDIOTEST-3
+//! @SYMTestType CIT
+//! @SYMTestCaseDesc Read the Card Common Control Registers (CCCR)
+//! @SYMPREQ PREQ1623
+//! @SYMREQ REQ5742  
+//! @SYMTestPriority Critical
+//! @SYMTestActions Read the CCCR and displays the results on the screen
+//! @SYMTestExpectedResults  The CCCR should be read successfully. The CCCR Format Version number should be <= 1; the SDIO Specification number should be <= 1; The SD Format Version number should be <= 1;
+//---------------------------------------------
+TInt TSdioCardDiagServices::doCardCommonControlRegs(CIOBase& aIO)
+/**
+Read the Card Common Control Registers (CCCR).
+
+@param aIO The input output device.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+
+	if (!iDriverOpen)
+		return(KErrNotSupported);
+
+	// Make sure stack is powered up
+	TInt err = doPowerUp(aIO);
+	if (err != KErrNone)
+		return err;
+	
+	aIO.ClearScreen();
+	aIO.Heading(_L("Read CCCR"));
+	aIO.CurserToDataStart();
+
+	TUint8 reg[0x14];
+	for (TInt i=0;i<0x14;i++)
+		{
+		TRequestStatus rs;
+		
+		TUint tempVal;
+		iDriver.ReadDirect(rs, i, tempVal);
+		User::WaitForRequest(rs);
+		reg[i] = (TUint8)tempVal;
+		err=rs.Int();
+		if (err!=KErrNone)
+			{
+			aIO.ReportError(_L("Error reading config"),err);
+			return(err);
+			}
+		}
+
+	const TUint32 ptrCIS    = reg[0x0b] << 16 | reg[0x0a] << 8 | reg[0x09];
+	const TUint16 blockSize = (TUint16) (reg[0x11] << 8  | reg[0x10]);
+
+	TUint8 cccrFormatVersionNumber = (TUint8) (reg[0x00] & 0x0F);
+	TUint8 sdioSpecRevisionNumber = (TUint8) ((reg[0x00] & 0xF0) >> 4);
+	TUint8 sdFormatVersionNumber = (TUint8) (reg[0x01]);
+
+	aIO.Printf(_L("\nCCCR/SDIO Revision    : %02xH\n (CCCR Rev: %d, SDIO Rev: %d)"),	reg[0x00], cccrFormatVersionNumber, sdioSpecRevisionNumber);
+	aIO.Printf(_L("\nSD Format Revision    : %02xH"),sdFormatVersionNumber);
+	aIO.Printf(_L("\nI/O Enable            : %02xH"),reg[0x02]);
+	aIO.Printf(_L("\nI/O Ready             : %02xH"),reg[0x03]);
+	aIO.Printf(_L("\nInt Enable            : %02xH"),reg[0x04]);
+	aIO.Printf(_L("\nInt Pending           : %02xH"),reg[0x05]);
+	aIO.Printf(_L("\nI/O Abort             : %02xH"),reg[0x06]);
+
+	aIO.Printf(_L("\nBus Interface Control : %02xH"), reg[0x07]);
+	aIO.Printf(_L("\n - CD Disable : %db"),	(reg[0x07] & 0x80) ? ETrue : EFalse);
+	aIO.Printf(_L("\n - SCSI       : %db"),	(reg[0x07] & 0x40) ? ETrue : EFalse);
+	aIO.Printf(_L("\n - ECSI       : %db"),	(reg[0x07] & 0x20) ? ETrue : EFalse);
+	aIO.Printf(_L("\n - Bus Width  : %d-bit"), (reg[0x07] & 0x03) ? 4 : 1);
+	aIO.Printf(_L("\nCard Capability : %02xH"),reg[0x08]);
+	aIO.Printf(_L("\n - 4BLS : %db"),			reg[0x08], reg[0x08] & 0x80 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - LSC  : %db"),			reg[0x08] & 0x40 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - E4MI : %db"),	reg[0x08] & 0x20 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - S4MI : %db"), reg[0x08] & 0x10 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - SBS  : %db"),		reg[0x08] & 0x08 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - SRW  : %db"),			reg[0x08] & 0x04 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - SMB  : %db"),			reg[0x08] & 0x02 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - SDC  : %db"),	reg[0x08] & 0x01 ? ETrue : EFalse);
+	aIO.Printf(_L("\n - SHS  : %db"),	reg[0x0D] & 0x01 ? ETrue : EFalse);
+
+	aIO.Printf(_L("\nCommon CIS Ptr  : %06xH"),ptrCIS);
+	aIO.Printf(_L("\nBus Suspend     : %02xH"),reg[0x0c]);
+	aIO.Printf(_L("\nFunction Select : %02xH"),reg[0x0d]);
+	aIO.Printf(_L("\nExec Flags      : %02xH"),reg[0x0e]);
+	aIO.Printf(_L("\nReady Flags     : %02xH"),reg[0x0f]);
+	aIO.Printf(_L("\nFN0 Block Size  : %04xH\n"),blockSize);	
+
+	// Test the version numbers are correct
+	if (cccrFormatVersionNumber > 1)
+		{
+		aIO.ReportError(_L("Invalid cccrFormatVersionNumber"), cccrFormatVersionNumber);
+		aIO.Getch();
+		return KErrNotSupported;
+		}
+	if (sdioSpecRevisionNumber > 1)
+		{
+		aIO.ReportError(_L("Invalid sdioSpecRevisionNumber"), sdioSpecRevisionNumber);
+		aIO.Getch();
+		return KErrNotSupported;
+		}
+	if (sdFormatVersionNumber > 1)
+		{
+		aIO.ReportError(_L("Invalid sdFormatVersionNumber"), sdFormatVersionNumber);
+		aIO.Getch();
+		return KErrNotSupported;
+		}
+
+	return(KErrNone);
+	}
+
+//---------------------------------------------
+//! @SYMTestCaseID FSBASE-SDIOTEST-4
+//! @SYMTestType CIT
+//! @SYMTestCaseDesc Read common configuration data
+//! @SYMPREQ PREQ1623
+//! @SYMREQ REQ5742  
+//! @SYMTestPriority Critical
+//! @SYMTestActions Read data common to all functions. Some of the data comes from the CCCR, others from the common (function 0) tuple.
+//! @SYMTestExpectedResults  The common data should be read with no error.
+//---------------------------------------------
+TInt TSdioCardDiagServices::doCardCommonConfig(CIOBase& aIO)
+/**
+Read common configuration data.
+
+@param aIO The input output device.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+
+	if (!iDriverOpen)
+		return(KErrNotSupported);
+
+	// Make sure stack is powered up
+	TInt err = doPowerUp(aIO);
+	if (err != KErrNone)
+		return err;
+	
+	aIO.ClearScreen();
+	aIO.Printf(_L("\nCommon Configuration\n"));
+
+	TRequestStatus rs;
+	iDriver.ResetCis(rs, iFunc);
+	User::WaitForRequest(rs);
+	err = rs.Int();
+	if (err!=KErrNone)
+		{
+		aIO.ReportError(_L("Error reseting CIS"),err);
+		return(err);
+		}
+
+	TSDIOCardConfigTest ci;
+	aIO.CurserToDataStart();
+
+
+	TRequestStatus rs1;
+	iDriver.GetCommonConfig(rs1, 0, &ci);
+	User::WaitForRequest(rs1);
+	err=rs1.Int();
+	if(err !=KErrNone)
+		return err;
+
+	aIO.Printf(_L("\n  Manufacturer ID : %04x"), ci.iManufacturerID);
+	aIO.Printf(_L("\n  Card ID         : %04x"), ci.iCardID);
+	aIO.Printf(_L("\n  FN0 Block Size  : %04x"), ci.iFn0MaxBlockSize);
+	aIO.Printf(_L("\n  Max Tran Speed  : %02x"), ci.iMaxTranSpeed);
+	aIO.Printf(_L("\n  CurrentBlockSize: %04x"), ci.iCurrentBlockSize);
+	aIO.Printf(_L("\n  Revision        : %04x"), ci.iRevision);
+	aIO.Printf(_L("\n  SDFormatVer     : %04x"), ci.iSDFormatVer);
+	aIO.Printf(_L("\n  CardCaps        : %04x"), ci.iCardCaps);
+	aIO.Printf(_L("\n  CommonCisP      : %04x\n"), ci.iCommonCisP);
+
+	return(KErrNone);
+
+	}
+
+//---------------------------------------------
+//! @SYMTestCaseID FSBASE-SDIOTEST-5
+//! @SYMTestType CIT
+//! @SYMTestCaseDesc Get the configuration data for each function.
+//! @SYMPREQ PREQ1623
+//! @SYMREQ REQ5742  
+//! @SYMTestPriority Critical
+//! @SYMTestActions Determine the number of functions by reading the CCR and then retrieve information from the Card Information Structure CIS for each function. Display the results on the screen. 
+//! @SYMTestExpectedResults  The number of functions should be >= 1. The function number should increment by one for each function. The function description should be as expected for the type of card (e.g. Wireless LAN).
+//---------------------------------------------
+TInt TSdioCardDiagServices::doGetFunctionInfo(CIOBase& aIO)
+/**
+Display the configuration data for each function.
+
+@param aIO The input output device.
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	if (!iDriverOpen)
+		return(KErrNotSupported);
+
+	// Make sure stack is powered up
+	TInt err = doPowerUp(aIO);
+	if (err != KErrNone)
+		return err;
+	
+	aIO.ClearScreen();
+	aIO.Heading(_L("Display Function Info"));
+	
+	TInt functionsFound = 0;
+	for(TInt i=1; i<7; i++)
+		{
+		TSDIOFunctionCapsTest fc;
+		
+		TRequestStatus rs2;
+		iDriver.GetFunctionConfig(rs2,i,&fc);
+		User::WaitForRequest(rs2);
+		err=rs2.Int();
+
+		if (err != KErrNone && err != KErrNotFound)
+			return err;
+
+		if(err==KErrNone)
+			{
+			functionsFound++;
+			if(i > 1)
+				{
+				aIO.Printf(_L("\n\n\t...More (Hit a key)"));
+				aIO.Getch();
+				aIO.ClearScreen();
+				aIO.Heading(_L("Display Function Info"));
+				}
+			
+			aIO.Printf(_L("\nFunction #  : %d"), fc.iNumber);
+			TPtrC functionType = TSDIOTestUtils::FunctionTypeText(fc.iType);
+			aIO.Printf(_L("\nFuncType    : %S"), &functionType);
+			aIO.Printf(_L("\nRevision    : 0x%02x"), fc.iRevision);
+			aIO.Printf(_L("\nSerial      : 0x%08x"), fc.iSerialNumber);
+			aIO.Printf(_L("\nOCR         : 0x%08x"), fc.iOCR);
+	 		aIO.Printf(_L("\nFn Info     : 0x%02x"), fc.iFunctionInfo);
+			aIO.Printf(_L("\nCSA Size    : 0x%08x"), fc.iCSASize);
+	 		aIO.Printf(_L("\nCSA Caps    : 0x%02x"), fc.iCSAProperties);
+			aIO.Printf(_L("\nMax Blk Sz  : 0x%04x"), fc.iMaxBlockSize);
+	 		aIO.Printf(_L("\nStby Min    : %dmA"),   fc.iMinPwrStby);
+			aIO.Printf(_L("\nStby Ave    : %dmA"),   fc.iAvePwrStby);
+	 		aIO.Printf(_L("\nStby Max    : %dmA"),   fc.iMaxPwrStby);
+	 		aIO.Printf(_L("\nOp Min      : %dmA"),   fc.iMinPwrOp);
+			aIO.Printf(_L("\nOp Ave      : %dmA"),   fc.iAvePwrOp);
+	 		aIO.Printf(_L("\nOp Max      : %dmA"),   fc.iMaxPwrOp);
+			aIO.Printf(_L("\nMin B/W     : %dKB/s"), fc.iMinBandwidth);
+			aIO.Printf(_L("\nOpt B/W     : %dKB/s"), fc.iOptBandwidth);
+			aIO.Printf(_L("\nEnable T/O  : %dms"),   fc.iEnableTimeout*10);
+			aIO.Printf(_L("\nHiPwr Ave   : %dmA"),   fc.iAveHiPwr);
+			aIO.Printf(_L("\nHiPwr Max   : %dmA"),   fc.iMaxHiPwr);		
+			
+			aIO.Printf(_L("\n"));
+
+			if (i != fc.iNumber)
+				{
+				aIO.ReportError(_L("Invalid function number"), fc.iNumber);
+				aIO.Getch();
+				return KErrNotFound;
+				}
+
+			}
+		}
+
+	if (functionsFound < 1)
+		{
+		aIO.ReportError(_L("Not enough functions"), functionsFound);
+		aIO.Getch();
+		return KErrNotFound;
+		}
+
+	return(KErrNone);
+
+	}
+
+TInt TSdioCardDiagServices::doQuit()
+/**
+Quit the program and close the logical device driver.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+    {
+
+    iDriver.Close();
+	return(KErrNone);
+    }
+
+
+
+GLDEF_C TInt E32Main()
+/**
+The entry point.
+
+@return One of the system wide error codes.
+
+@internal
+@test
+*/
+	{
+	TInt err;
+	err = User::LoadLogicalDevice(_L("D_SDIOIF"));
+	__ASSERT_ALWAYS((err==KErrNone||err==KErrAlreadyExists),Panic(ELoadingMmcDriver));
+
+	TSdioCardDiagServices sdioIf;
+	sdioIf.Start();
+
+	// Read the command line
+	HBufC* commandLine = NULL;
+	TRAPD(r, commandLine = HBufC::NewL(User::CommandLineLength()));
+	__ASSERT_ALWAYS(r==KErrNone, Panic(EReadingCommandLine));
+
+	TPtr commandLinePtr(commandLine->Des());
+	User::CommandLine(commandLinePtr);
+	
+	if (commandLinePtr.FindC(_L("--auto")) != KErrNotFound)
+		{
+		CIOBase* inputOutput = new (ELeave) CIORDebug;
+		TRAPD(r, inputOutput->CreateL(_L("SDIOTEST")))
+		__ASSERT_ALWAYS(r==KErrNone,Panic(ECreatingIO));
+		
+		// Start tests
+		sdioIf.doPowerUp(*inputOutput);
+	
+		// FSBASE-SDIOTEST-2
+		sdioIf.doGetCardInfo(*inputOutput);
+
+		// FSBASE-SDIOTEST-3
+		sdioIf.doCardCommonControlRegs(*inputOutput);
+
+		// FSBASE-SDIOTEST-4
+		sdioIf.doCardCommonConfig(*inputOutput);
+
+		// FSBASE-SDIOTEST-5
+		sdioIf.doGetFunctionInfo(*inputOutput);
+		
+		delete inputOutput;
+		}
+	else
+		{
+		TBuf<20> b(_L("CDFIRPUQ\x1b"));
+
+		CIOBase* inputOutput = new (ELeave) CIOConsole;
+		TRAPD(r, inputOutput->CreateL(_L("SDIOTEST")))
+		__ASSERT_ALWAYS(r==KErrNone,Panic(ECreatingIO));
+		
+		TBool quit=EFalse;
+		while (!quit)
+			{
+			inputOutput->ClearScreen();
+			inputOutput->Heading(_L("Current socket: %d\n- Current Function: %d"),sdioIf.CurrentSocket(),sdioIf.CurrentFunc());
+			inputOutput->Instructions(EFalse,
+				_L("(P)owerUp\nCard(I)nfo\n(R)eadCCCR\n(C)ommonConfig\n(F)unctionInfo\n(Q)uit\n"));
+			TChar c;
+			
+			do
+				{
+				c=(TUint)inputOutput->Getch();
+				c.UpperCase();
+				}
+			while(b.Locate(c)==KErrNotFound);
+	
+			TInt err = KErrNone;
+	
+			switch (c)
+				{
+				// FSBASE-SDIOTEST-1
+				case 'P':   // PowerUp
+					err = sdioIf.doPowerUp(*inputOutput);
+					break;
+	
+				// FSBASE-SDIOTEST-2
+				case 'I':   // Card Info - read CSD AND CID regs
+					err = sdioIf.doGetCardInfo(*inputOutput);
+					break;
+	
+				// FSBASE-SDIOTEST-3
+				case 'R':   // CCCR
+					err = sdioIf.doCardCommonControlRegs(*inputOutput);
+					break;
+	
+				// FSBASE-SDIOTEST-4
+				case 'C':   // Common configuration data
+					err = sdioIf.doCardCommonConfig(*inputOutput);
+					break;
+	
+				// FSBASE-SDIOTEST-5
+				case 'F':   // Function Info
+					err = sdioIf.doGetFunctionInfo(*inputOutput);
+					break;
+
+				case 'Q':	// Quit
+				case 0x1b:	// Ascii character for Escape key 
+					sdioIf.doQuit();
+		            User::FreeLogicalDevice(_L("D_SDIOIF"));
+					quit=ETrue;
+					break;
+	
+				}
+	
+			if (err != KErrNone)
+				inputOutput->Printf(_L("Test Failed! (%d)\n"), err);
+			
+			if (!quit)
+				{
+				inputOutput->Printf(_L("\n\tPress Any Key"));
+				inputOutput->Getch();
+				}	
+			} 
+		delete inputOutput;
+		}
+	delete commandLine;
+
+	return(KErrNone);
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/sdiotest/source/sdiotests.h	Wed Sep 15 13:42:27 2010 +0300
@@ -0,0 +1,272 @@
+// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of the License "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Test for SDIO functions
+// 
+//
+
+/**
+ @file sdiotests.h
+ @internal
+ @test
+*/
+
+#ifndef __SDIO_TESTS_H__
+#define __SDIO_TESTS_H__
+
+class DSDIORegisterInterface;
+class TSDIOCard;
+
+
+class TSDIOCardConfigTest
+/**
+Class to store card configuration parameters.
+NB should be exactly the same layout as private class TSDIOCardConfig, defined in sdiocard.h
+
+@internal
+@test
+*/
+	{
+public:								 
+	/** The Manufacture ID */
+	TUint16 iManufacturerID;
+	/** The Card ID */
+	TUint16 iCardID;		
+	/** The maximum block size for Function 0 */
+	TUint16 iFn0MaxBlockSize;
+	/** The maximum transfer rate (encoded) */
+	TUint8  iMaxTranSpeed;		
+	/** The current block size (of function 0) */
+	TUint16 iCurrentBlockSize;	
+	/** SDIO/CCCR Revision	(as CCCR offset 0x00) */
+	TUint8 iRevision;			
+	/** SD Format Version	(as CCCR offset 0x01) */
+	TUint8 iSDFormatVer;		
+	/** Card Capabilities	(as CCCR offset 0x08) */
+	TUint8 iCardCaps;			
+	/** Common CIS Pointer	(as CCCR offset 0x09:0x0B) */
+	TUint32 iCommonCisP;		
+	/** High speed register (as CCCR offset 0x0D) */
+	TUint8 iHighSpeed;			
+
+    TInt iReserved[4];
+	};
+
+/**
+Package up the TSDIOCardConfigTest as a descriptor.
+
+@internal
+@test
+*/
+typedef TPckgBuf<TSDIOCardConfigTest> TSDIOCardConfigTestPckg;
+
+
+#ifndef __KERNEL_MODE__
+enum TSdioFunctionType
+/** These define the standard SDIO Function Types
+	These are defined by the SDA and provide a standard, common 
+	register interface for each class of peripheral.
+*/
+	{
+	/** Not an SDIO standard interface */
+	ESdioFunctionTypeUnknown  = 0,
+	/** SDIO UART standard interface */
+	ESdioFunctionTypeUART	  = 1,
+	/** SDIO 'thin' Bluetooth standard interface */
+	ESdioFunctionTypeThinBT	  = 2,
+	/** SDIO 'complete' Bluetooth standard interface */
+	ESdioFunctionTypeFullBT	  = 3,
+	/** SDIO GPS standard interface */
+	ESdioFunctionTypeGPS	  = 4,
+	/** SDIO Camera standard interface */
+	ESdioFunctionTypeCamera	  = 5,
+	/** SDIO PHS Radio standard interface */
+	ESdioFunctionTypePHS	  = 6,
+	/** SDIO WLAN standard interface (Introduced in SDIO Rev. 1.10f) */
+	ESdioFunctionTypeWLAN	  = 7,
+	/** Extended SDIO standard interface (Introduced in SDIO Rev. 1.10f) */
+	ESdioFunctionTypeExtended = 15,
+	};
+#endif // #ifvdef __KERNEL_MODE__
+
+
+
+
+class TSDIOFunctionCapsTest
+/**
+Class to store card function parameters.
+NB should be exactly the same layout as private class TSDIOFunctionCaps, defined in function.h
+
+@internal
+@test
+*/
+	{
+public:
+	//
+	// The following data is obtained from the functions FBR
+	//
+		
+	/** Function number within the card */
+	TUint8 iNumber;
+	/** Extended devide code */
+	TUint8 iDevCodeEx;
+	/** Type of function */
+	TSdioFunctionType iType;
+	/** Function contains Code Storage Area */
+	TBool iHasCSA;
+	/** High-Power Requirements */
+	TUint8 iPowerFlags;
+	
+	//
+	// The following data is obtained from the functions CIS
+	//
+		
+	/** Function Info */
+	TUint8 iFunctionInfo;	
+	/** Function revision of standard function */
+	TUint8 iRevision;
+	/** Product Serial Number */
+	TUint32 iSerialNumber;
+	/** CSA Size */
+	TUint32 iCSASize;
+	/** CSA Properties */
+	TUint8 iCSAProperties;
+	/** Maximum Block Size */
+	TUint16 iMaxBlockSize;
+	/** 32-Bit SD OCR */
+	TUint32 iOCR;
+	/** Minimum standby current (mA) */
+	TUint8 iMinPwrStby;
+	/** Average standby current (mA) */
+	TUint8 iAvePwrStby;
+	/** Maximum standby current (mA) */
+	TUint8 iMaxPwrStby;
+	/** Minumum operating current (mA) */
+	TUint8 iMinPwrOp;
+	/** Average operating current (mA) */
+	TUint8 iAvePwrOp;
+	/** Maximum operating current (mA) */
+	TUint8 iMaxPwrOp;
+	/** Minimum Bandwidth */
+	TUint16 iMinBandwidth;
+	/** Optimum Bandwidth */
+	TUint16 iOptBandwidth;
+	/** Enable Timeout (Added in SDIO Rev 1.1) */
+	TUint16 iEnableTimeout;
+	/** Average operating current required in High Power mode (mA) (Added in SDIO Rev 1.1) */
+	TUint16 iAveHiPwr;
+	/** Maximum operating current required in High Power mode (mA) (Added in SDIO Rev 1.1) */
+	TUint16 iMaxHiPwr;
+
+	/** Standard Function ID */
+	TUint8 iStandardFunctionID;	
+	/** Standard Function Type */
+	TUint8 iStandardFunctionType;
+
+	enum TSDIOCapsMatch
+	/** These bits define the capabilities to match when enumerating SDIO functions.
+		@see TSDIOFunctionCaps::CapabilitiesMatch
+		@see TSDIOCard::FindFunction
+	*/
+		{
+		/** Specify EDontCare to match functions without specific properties */
+		EDontCare 		= KClear32,
+		/** Find functions with a specific function number */
+		EFunctionNumber	= KBit0,
+		/** Find functions with a specific device code */
+		EFunctionType	= KBit1,
+		/** Find functions that have a Code Storage Area */
+		EHasCSA			= KBit2,
+		/** Find functions with specific High-Power support */
+		EPowerFlags		= KBit3,
+		/** Find functions with specific capabilities (Currently only Wake-Up Supported) */
+		EFunctionInfo	= KBit4,
+		/** Find functions with a specific revision code */
+		ERevision		= KBit5,
+		/** Find functions with a specific serial number */
+		ESerialNumber	= KBit6,
+		/** Find functions with a CSA size greater than or equal to that specified */
+		ECSASize		= KBit7,
+		/** Find functions with specific CSA properties (re-formattable, write-protected) */
+		ECSAProperties	= KBit8,
+		/** Find functions that support a block size greater than or equal to that specified */
+		EMaxBlockSize	= KBit9,
+		/** Find functions that support a subset of the requested OCR */
+		EOcr			= KBit10,
+		/** Find functions where the minimum standby current does not exceed that specified */
+		EMinPwrStby		= KBit11,
+		/** Find functions where the average standby current does not exceed that specified */
+		EAvePwrStby		= KBit12,
+		/** Find functions where the maximum standby current does not exceed that specified */
+		EMaxPwrStby		= KBit13,
+		/** Find functions where the minimum operating current does not exceed that specified */
+		EMinPwrOp		= KBit14,
+		/** Find functions where the average operating current does not exceed that specified */
+		EAvePwrOp		= KBit15,
+		/** Find functions where the maximum operating current does not exceed that specified */
+		EMaxPwrOp		= KBit16,
+		/** Find functions where the average operating current in high-power mode does not exceed that specified */
+		EAveHiPwr		= KBit17,
+		/** Find functions where the maximum operating current in high-power mode does not exceed that specified */
+		EMaxHiPwr		= KBit18,
+		/** Find functions that support bandwidth greater than or equal to that specified*/
+		EMinBandwidth	= KBit19,
+		/** Find functions that support an optimum bandwidth greater than or equal to that specified*/
+		EOptBandwidth	= KBit20,
+		/** Find functions with a specific standard function ID */
+		EStandardFunctionID		= KBit21,
+		/** Find functions with a specific standard function type */
+		EStandardFunctionType	= KBit22,		
+		};	
+
+    TInt iReserved[2];		
+	};
+typedef TPckgBuf<TSDIOFunctionCapsTest> TSDIOFunctionCapsTestPckg;
+
+class TSDIOTestUtils
+/**
+Utility class.
+
+@internal
+@test
+*/
+	{
+public:
+	static inline TPtrC FunctionTypeText(TSdioFunctionType aType)
+	/**
+	Convert a function type enumeration to human readable text.
+
+	@param aType The function type enum value
+	@return The Human readable text
+	
+	@internal
+	@test
+	*/
+		{
+		switch(aType)
+			{
+			case ESdioFunctionTypeUnknown:	return(_L("Not a standard SDIO interface"));
+			case ESdioFunctionTypeUART:		return(_L("UART standard interface"));
+			case ESdioFunctionTypeThinBT:	return(_L("'thin' Bluetooth standard interface"));
+			case ESdioFunctionTypeFullBT:	return(_L("'complete' Bluetooth standard interface"));
+			case ESdioFunctionTypeGPS:		return(_L("GPS standard interface"));
+			case ESdioFunctionTypeCamera:	return(_L("Camera standard interface"));
+			case ESdioFunctionTypePHS:		return(_L("PHS Radio standard interface"));
+			case ESdioFunctionTypeWLAN:		return(_L("WLAN standard interface"));
+			case ESdioFunctionTypeExtended: return(_L("Extended standard interface"));
+			default: 						return(_L("Unknown"));
+			}
+		}
+	};
+
+#endif
--- a/package_definition.xml	Tue Sep 14 23:56:21 2010 +0300
+++ b/package_definition.xml	Wed Sep 15 13:42:27 2010 +0300
@@ -17,6 +17,9 @@
       </component>
     </collection>
     <collection id="kerneltest" name="Kernel Test" level="hw-if">
+	  <component id="sdiotest" name="SDIO Tests" introduced="9.2" purpose="development">
+      <unit bldFile="kerneltest/sdiotest" mrp="kerneltest/sdiotest/base_sdiotests.mrp"/>
+      </component>
       <component id="e32utils" name="E32 Utilities" purpose="development">
       <unit bldFile="kerneltest/e32utils/group" mrp="kerneltest/e32utils/group/base_e32utils.mrp"/>
       </component>
@@ -26,6 +29,12 @@
       <component id="f32test" name="File Server Tests" purpose="development">
         <unit bldFile="kerneltest/f32test/group" mrp="kerneltest/f32test/group/base_f32test.mrp"/>
       </component>
+      <component id="rofstests" name="Read Only File System Tests" purpose="development" filter="test">
+        <unit bldFile="kerneltest/f32test/rofs"/>
+      </component>
+      <component id="loadertest" name="Loader Tests" purpose="development" filter="test">
+        <unit bldFile="kerneltest/f32test/loader"/>
+      </component>
     </collection>
     <collection id="ldds" name="Logical Device Drivers" level="adaptation">
       <component id="ethernetldd" name="Ethernet Drivers" purpose="optional">
--- a/userlibandfileserver/fileserver/group/release.txt	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/group/release.txt	Wed Sep 15 13:42:27 2010 +0300
@@ -1,3 +1,35 @@
+Version 2.00.2510
+=================
+(Made by fadhliM 31/08/2010)
+
+1.	niccox
+	1.	ou1cimx1#543431 SPPR_PERF: USB not suspended
+
+
+Version 2.00.2509
+=================
+(Made by fadhliM 25/08/2010)
+
+1.	frhofman
+	1.	ou1cimx1#538302 IT_BITO_SSS_SD - TB9.2 wk29 - sf/os/kernelhwsrv - Resource Leak for objects of handle-based R classes 
+
+
+Version 2.00.2508
+=================
+(Made by fadhliM 24/08/2010)
+
+1.	dlyokhin
+	1.	ou1cimx1#529937 ENV 9_2_SIROCCO - Vasco - T_FSYS Fails with -20
+
+
+Version 2.00.2507
+=================
+(Made by fadhliM 12/08/2010)
+
+1.	niccox
+	1.	ou1cimx1#521106 Vasco to Vasco connection can freeze the USB/Connectivity UI
+
+
 Version 2.00.2506
 =================
 (Made by fadhliM 06/08/2010)
--- a/userlibandfileserver/fileserver/inc/f32fsys.inl	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/inc/f32fsys.inl	Wed Sep 15 13:42:27 2010 +0300
@@ -270,53 +270,48 @@
 	__IS_DRIVETHREAD();
 	iDriveFlags |= ENotifyOff;
 	}
+
 /**
-
 Locks the drive.This function acquires iLock mutex.
-
 */
 inline void TDrive::Lock()
 	{iLock.Wait();}
+
 /**
-
 UnLocks the drive.This function signals the iLock mutex.
-
 */
-
 inline void TDrive::UnLock()
 	{iLock.Signal();}
 
 
 /**
-
-Gets the reserved space of a drive
-
 @return	Amount of space reserved in bytes.
-
 */
-
 inline TInt TDrive::ReservedSpace() const
-	{return iReservedSpace;}
+	{
+    return iReservedSpace;
+    }
 
 /**
-
-Reserves a space of a drive.
+    Reserves space on a drive. The amount of 'reserved space' is subtracted  
+    from the amount of available free space on the volume reported by file system, when the user 
+    queries it.
 
 @param	aReservedSpace	Amount of space to reserve in bytes.
-
 */
 inline void TDrive::SetReservedSpace(const TInt aReservedSpace)
-	{iReservedSpace=aReservedSpace; }
+	{
+    iReservedSpace=aReservedSpace; 
+    }
 
 /**
-
-Sets the rugged flag in the drive object.
+    Sets the 'rugged mode' flag in the drive object. The file system associated with this TDrive object 
+    can use this flag for changing its behaviour.
+    For example, FAT file system if this flag is set, operates in 'Rugged FAT' mode, when the performance is 
+    sacrificed for the sake of reliability. 
 
-@param Flag to set or clear the rugged flag.
-@see	IsRugged()
-
+    @param aIsRugged  the 'rugged mode' flag.
 */
-
 inline void TDrive::SetRugged(TBool aIsRugged)
 	{
 	if (!aIsRugged)
@@ -326,17 +321,13 @@
 	}
 
 /**
-
-Returns whether the current drive is running as rugged Fat
-or not.If IsRugged flag is set then in the event of power 
-failure fat/metadata will be in a valid state if the scandrive 
-utility is run immediately after.
-
-@return Is rugged fat flag.
+    @return 'Is rugged' flag.
+    See TDrive::SetRugged()
 */
-
 inline TBool TDrive::IsRugged() const
-	{return !(iDriveFlags & ENotRugged); }
+	{
+    return !(iDriveFlags & ENotRugged); 
+    }
 
 
 /**
@@ -451,64 +442,69 @@
 	{Drive().SetNotifyOff();}
 
 
+//---------------------------------------------------------------------------------------------------------------------------------
 
+/**
+
+    Increment mount's lock counter. This happens on following events:
+        - RemoveResource() call, when file (share) or directory is closed
+        - AddDiskAccess() call,  when disk access object (like Format or RawDisk access) is opened on the mount.
+
+    See also: CMountCB::LockStatus()   
+*/
+inline void CMountCB::IncLock()
+	{
+    iLockMount++;
+    }
+
+
+//---------------------------------------------------------------------------------------------------------------------------------
 
 /**
-Locks the mount by incrementing the internal lock counter.
+    Decrement mount's lock counter. This happens on following events:
+
+    AddResource()       call when file (share) or directory is opened on the mount 
+    RemoveDiskAccess()  call when disk access object (like Format or RawDisk access) is closed.
+
+    See also: CMountCB::LockStatus()   
+*/
+inline void CMountCB::DecLock()
+	{
+    iLockMount--;
+    }
 
-The mount becomes locked on formatting or on the opening of a resource
-(a file or a directory) or raw disk subsession.
-A format, resource or raw disk subsession can only be opened if the mount
-is not locked.
+//---------------------------------------------------------------------------------------------------------------------------------
+
+/**
+    @return value of the Mount's lock counter value.
+    
+    The meaning of 'iLockMount' is overloaded a bit, it's value is:
+        0   when there are no files, directories, formats and any other objects opened on the mount
+        >0  when there are disk access objects opened (raw disk access or format)
+        <0  when there are files or directories opened on the mount, and the value reflects their total number 
 */
-inline void CMountCB::IncLock()
-	{iLockMount++;}
-
+inline TInt CMountCB::LockStatus() const
+	{
+    return iLockMount;
+    }
 
 
 
-/**
-Unlocks the mount by decrementing the internal lock counter.
-
-The mount becomes locked on formatting or on the opening of a resource
-(a file or a directory) or raw disk subsession.
-A format, resource or raw disk subsession can only be opened if the mount
-is not locked.
-*/
-inline void CMountCB::DecLock()
-	{iLockMount--;}
-
-
-
-
-/**
-Gets the current lock status.
-
-It delivers the current lock status by returning the internal lock counter.
-
-@return The current lock status.
-*/
-inline TInt CMountCB::LockStatus() const
-	{return(iLockMount);}
-
-
-
-
+//---------------------------------------------------------------------------------------------------------------------------------
 /**
 Tests whether the mount is currently locked. 
 
 A mount is locked when the internal lock counter is greater than zero.
-On creation, the lock counter is set to zero.
+    This happens when a format, resource or raw disk subsession is opened on the mount.
 
-The mount becomes locked on formatting or on the opening of a resource
-(a file or a directory) or raw disk subsession.
-A format, resource or raw disk subsession can only be opened if the mount
-is not locked.
+    See also: CMountCB::LockStatus()   
 
-@return True if the mount is locked, false, otherwise.
+    @return True if the mount is locked by having disk access objects opened
 */
 inline TBool CMountCB::Locked() const
-	{return iLockMount>0; }
+	{
+    return iLockMount > 0; 
+    }
 
 
 
@@ -537,7 +533,9 @@
 /**
 */
 inline TInt64 CMountCB::Size() const
-	{return(iSize);}
+	{
+    return iSize;
+    }
 
 
 
@@ -547,14 +545,19 @@
 @param aMountNumber - The unique mount number
 */
 const TInt KMountDismounted = 0x80000000;
+
 inline void CMountCB::SetMountNumber(TInt aMountNumber)
-	{ iMountNumber = (aMountNumber &~ KMountDismounted); }
+	{ 
+    iMountNumber = (aMountNumber & ~KMountDismounted); 
+    }
 
 
 
 
 /**
-Set the mount to be dismounted
+    Set the mount flag indicating that it is in 'dismounted' state.
+    The CMountCB object in this case is still alive, but any attempts to access resources on this 
+    mount result in KErrDismounted.
 */
 inline void CMountCB::SetDismounted(TBool aDismounted)
 	{
@@ -568,21 +571,23 @@
 
 
 /**
-Returns the unique mount number
 @return The unique mount number
 */
 inline TInt CMountCB::MountNumber() const
-	{ return(iMountNumber &~ KMountDismounted); }
+	{ 
+    return(iMountNumber &~ KMountDismounted); 
+    }
 
 
 
 
 /**
-Returns ETrue if the mount is flagged as dismounted.
 @return ETrue if the mount is flagged as dismounted
 */
 inline TBool CMountCB::IsDismounted() const
-	{ return(iMountNumber & KMountDismounted); }
+	{ 
+    return(iMountNumber & KMountDismounted); 
+    }
 
 
 
--- a/userlibandfileserver/fileserver/inc/f32ver.h	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/inc/f32ver.h	Wed Sep 15 13:42:27 2010 +0300
@@ -58,6 +58,6 @@
 
 @see TVersion
 */
-const TInt KF32BuildVersionNumber=2506;
+const TInt KF32BuildVersionNumber=2510;
 //
 #endif
--- a/userlibandfileserver/fileserver/sfat32/fat_table32.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfat32/fat_table32.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -1036,11 +1036,17 @@
             //-- create helper thread object and start the thread
             ipHelperThread = CFat32BitCachePopulator::NewL(*this);
 
-            ipHelperThread->Launch(); 
+            if(ipHelperThread->Launch() != KErrNone)
+                {//-- failed for some reason
+                DestroyHelperThread();
+                }
+                else
+                {
             //-- background FAT bit cache populating thread is running now.
             //-- the result of thread start up and completion isn't very interesting: If it fails to 
             //-- properly populate the cache, nothing fatal will happen.
             }
+            }
 
         //-- CFat32BitCachePopulator doesn't affect FAT table state. 
         SetState(EMounted);
@@ -1472,7 +1478,7 @@
                 {//-- test property for this drive is defined
                     if(nMntDebugFlags & KMntDisable_FatBkGndScan)
                     {
-                    __PRINT(_L("#- FAT32 BkGnd scan is disabled is disabled by debug interface."));
+                    __PRINT(_L("#- FAT32 BkGnd scan is disabled by debug interface."));
                     bFat32BkGndScan = EFalse;
                     }
             
@@ -1536,7 +1542,8 @@
     
     SetState(EFreeClustersScan);
     
-    ipHelperThread->Launch(); 
+    User::LeaveIfError(ipHelperThread->Launch()); 
+    
     //-- background FAT scanning thread is running now
     }
 
@@ -1978,7 +1985,8 @@
 
 /**
     Launches the FAT32_ScanThread scaner thread.
-    @return  standard error code
+    @return  KErrNone if the thread launched OK
+             standard error code otherwise
 */
 TInt CFat32ScanThread::Launch()
     {
@@ -2540,9 +2548,15 @@
             //-- allow this thread to be preempted by another one that wants to access the media driver.
             //-- without this wait we will have priority inversion, because this (low priority) thread continiously reads data by big chunks 
             //-- and doesn't allow others to access the driver.
-            //-- On the other hand, if the thread's priority is boosted, there is no reason to be polite.
+            //-- On the other hand, if the thread's priority is boosted, there is no reason to be so polite.
             if(!pSelf->IsPriorityBoosted())
-                User::After(K1mSec); //-- User::After() granularity can be much coarser than 1ms
+                {//-- User::After() granularity can be much coarser than 1ms, e.g. 1/64 Sec. This will add up to the scanning time
+                User::After(K1mSec); 
+                }
+            else
+                {//-- use much less coarse granularity to allow this thread to be preempted even if its priority is boosted.
+                User::AfterHighRes(128); 
+                }
 
             //-------------------------------------------
             mediaPos += bytesToRead;
--- a/userlibandfileserver/fileserver/sfat32/sl_mnt.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfat32/sl_mnt.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -539,7 +539,7 @@
             User::Leave(KErrAccessDenied); //-- can't override RO flag
             }
 
-		(void)LocalDrive()->Finalise(ETrue);
+        (void)LocalDrive()->Finalise(ETrue);
 
         if(aOperation == RFs::EFinal_RO)
             {
@@ -550,10 +550,8 @@
         return;
         }
 
-    if(LockStatus() != 0)
-        {//-- can't finalise the volume if it has opened objects and not in the consistent state.
-         //-- Theoretically, we can finalise the mount if we have files opened only for read, but at present,
-         //-- it's impossible to detect such situation.
+    if(Locked())
+        {//-- can't finalise the volume if it has opened disk access objects, like Format or RawAccess
         User::Leave(KErrInUse);
         }
 
@@ -601,6 +599,8 @@
     if(aOperation == RFs::EFinal_RO)
         SetReadOnly(ETrue);
 
+    (void)LocalDrive()->Finalise(ETrue);
+
     SetState(EFinalised);
     }
 
--- a/userlibandfileserver/fileserver/sfat32/sl_mnt32.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfat32/sl_mnt32.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -218,8 +218,8 @@
 void CFatMountCB::SetVolumeCleanL(TBool aClean) 
     {
 
-	//-- The volume can't be set clean if there are objects opened on it. This precondition must be checked before calling this function
-    if(aClean && LockStatus()!=0)
+	//-- The volume can't be set clean if there are disk access objects opened on it. This precondition must be checked before calling this function
+    if(aClean && Locked())
         {
         __PRINT1(_L("#- CFatMountCB::SetVolumeCleanL drive:%d isn't free!"),DriveNumber());
         ASSERT(0);
--- a/userlibandfileserver/fileserver/sfile/sf_drv.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfile/sf_drv.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -2221,8 +2221,9 @@
 
 
 /**
-Dismounts the current mount. This is method is called from outside, so do some finalisation work on mount.
+    Gracefully dismounts the current mount. This is method is called from outside, so do some finalisation work on mount.
 After calling this function there is no current mount on the drive.
+
 */
 EXPORT_C void TDrive::Dismount()
 	{
@@ -2232,10 +2233,12 @@
 	if (!iCurrentMount)
 		return;
 
+    //-- try to do the best flushing file caches
     TRAP_IGNORE(FlushCachedFileInfoL());
 
     //-- try our best to finalise the mount (the mount can decide to do some job during finalisation, e.g. write some data)
-    TRAP_IGNORE(iCurrentMount->FinaliseMountL());
+    //-- finalise the mount in RO mode, we are dismounting the FS anyway
+    TRAP_IGNORE(iCurrentMount->FinaliseMountL(RFs::EFinal_RO));
     
     DoDismount();
 	}
@@ -2244,8 +2247,7 @@
 
 
 /**
-Forcibly dismounts the current mount and prevents it being remounted.
-After calling this function there is no current mount on the drive.
+    Dismounts the current mount by force.
 */
 void TDrive::ForceDismount()
 	{
@@ -2257,7 +2259,15 @@
 		return;
   
 	TRAP_IGNORE(FlushCachedFileInfoL());
-	iCurrentMount->SetDismounted(); //! this affects TDrive::ReMount()
+
+    //-- try our best to finalise the mount (the mount can decide to do some job during finalisation, e.g. write some data)
+    //-- finalise the mount in RO mode, we are dismounting the FS anyway
+    TRAP_IGNORE(iCurrentMount->FinaliseMountL(RFs::EFinal_RO));
+
+    //-- mark the mount as 'Dismounted'; this invalidates all object handles until the mount is successfully "remounted". 
+    //-- if there are still some objects opened on this mount, CMountCB::Close() won't destroy it until all objects are closed.
+    iCurrentMount->SetDismounted(); 
+    
     DoDismount();
 	}
 
--- a/userlibandfileserver/fileserver/sfile/sf_memory_man.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfile/sf_memory_man.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -42,6 +42,7 @@
 		delete iRegisteredClients[i];
 		}
 	iRegisteredClients.Close();
+	iChunk.Close();
 	}
 
 /**
--- a/userlibandfileserver/fileserver/sfile/sf_thread.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfile/sf_thread.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -858,15 +858,7 @@
 	TDrive& drive = TheDrives[self.iDriveNumber];
 	if(drive.IsMounted())
         {
-        if (drive.CurrentMount().LockStatus() == 0)
-            {
-            // Ignore the error here, as there's nothing we can do about it...
-            (void)drive.FinaliseMount(RFs::EFinal_RW);
-            }
-        else
-            {
-            self.StartFinalisationTimer();
-            }
+        (void)drive.FinaliseMount(RFs::EFinal_RW);
         }
 
 	return KErrNone;
@@ -929,14 +921,14 @@
   : iPlugin(aPlugin)
 	{
 	/** @prototype */
-	iOperationLock.Close();
 	iPlugin.Open();
 	}
 
 CPluginThread::~CPluginThread()
-    {
-    iPlugin.Close();
-    }
+	{
+	iPlugin.Close();
+	iOperationLock.Close();
+	}
 
 
 CPluginThread* CPluginThread::NewL(CFsPlugin& aPlugin)
--- a/userlibandfileserver/fileserver/sfile/sf_utl.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfile/sf_utl.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -613,9 +613,11 @@
 	}
 
 
-//
-// Returns ETrue if aDes only contains spaces or is zero length
-//
+
+/**
+    @return ETrue if aDes only contains spaces or is zero length
+    Note that _all_ UNICODE space characters are treated as usual spaces
+*/
 static TBool IsSpace(const TDesC& aDes)
 	{
 
@@ -890,38 +892,43 @@
 	return powerGood;
 	}
 
+//---------------------------------------------------------------------------------------------------------------------------------
+/**
+    Decrement mount's lock counter when the mount resource, like a file or directory is opened. 
+    See also: CMountCB::LockStatus()   
+*/
 void AddResource(CMountCB& aMount)
-//
-// Decrement resource counters
-//
 	{
 	__CHECK_DRIVETHREAD(aMount.Drive().DriveNumber());
 	__ASSERT_DEBUG(aMount.LockStatus()<=0,Fault(ERawDiskBadAccessCount2));
 	aMount.DecLock();
 	}
 
+/**
+    Increment mount's lock counter when the mount resource, like a file or directory is closed. 
+    See also: CMountCB::LockStatus()   
+*/
 void RemoveResource(CMountCB& aMount)
-//
-// Increment resource counters
-//
 	{
 	__ASSERT_DEBUG(aMount.LockStatus()<0,Fault(ERawDiskBadAccessCount1));
 	aMount.IncLock();
 	}
 
 
+/**
+    Increment mount's lock counter when the disk access (Format, Raw disk) is opened on the mount
+    See also: CMountCB::LockStatus()   
+*/
 void AddDiskAccess(CMountCB& aMount)
-//
-// Increment resource counters
-//
 	{
 	aMount.IncLock();
 	}
 
+/**
+    Decrement mount's lock counter when the disk access (Format, Raw disk) is closed on the mount
+    See also: CMountCB::LockStatus()   
+*/
 void RemoveDiskAccess(CMountCB& aMount)
-//
-// Decrement resource counters
-//
 	{
 	aMount.DecLock();
 	}
--- a/userlibandfileserver/fileserver/sfsrv/cl_cli.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfsrv/cl_cli.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -3306,7 +3306,7 @@
 
     @return KErrNone on success,
             KErrArgument if the function arguments are invalid
-            KErrInUse    if the drive has opened objects (files, directories etc.) and therefore can not be finalised
+            KErrInUse    if the drive has opened disk access objects (format, raw disk access, etc) and therefore can not be finalised
             KErrCorrupt  if the drive is corrupt.
             System wide error codes otherwise.
 
--- a/userlibandfileserver/fileserver/sfsrv/cl_fman.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/sfsrv/cl_fman.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -265,21 +265,24 @@
 // Initialise New thread
 //
 	{
-
+	TInt r = KErrNoMemory;	// return value if a trap harness cannot be created
 	CTrapCleanup* cleanup=CTrapCleanup::New();
-	if (cleanup==NULL)
-		return(KErrNoMemory);
 	CFileBase& fMan=*(CFileBase*)aPtr;
-	fMan.iSynchronizer.Wait();
-	TRAPD(ret,DoFManBaseOperationL(aPtr));
-	if (ret==KErrNone)
-		ret=fMan.iLastError;
-	delete cleanup;
+
+	if (cleanup != NULL)
+		{
+		fMan.iSynchronizer.Wait();
+		TRAP(r,DoFManBaseOperationL(aPtr));
+		if (r == KErrNone)
+			r = fMan.iLastError;
+		delete cleanup;
+		}
+
 	fMan.iSwitches=0;
 	fMan.iFs=fMan.iFsOld;
 	fMan.iStatus=NULL;
 	fMan.iFManThread.Close();
-	return(ret);
+	return (r);
 	}
 
 
@@ -292,9 +295,6 @@
 @param aThreadFunction The thread function.
 */
 	{
-	iSwitches|=KFManBusyFlag;
-	User::LeaveIfError(iFManThread.Create(KNullDesC,aThreadFunction,KDefaultStackSize,NULL,this));
-	iFManThread.SetPriority(EPriorityMuchLess);
 	TFileName sessionPath;
 	User::LeaveIfError(iFs.SessionPath(sessionPath));
 	if (iSessionPath==NULL)
@@ -302,6 +302,14 @@
 	else if (iSessionPath->Des().MaxLength()<sessionPath.Length())
 		iSessionPath=iSessionPath->ReAllocL(IncPathLength(sessionPath.Length()));
 	iSessionPath->Des()=sessionPath;
+
+	User::LeaveIfError(iFManThread.Create(KNullDesC,aThreadFunction,KDefaultStackSize,NULL,this));
+
+	// The code won't leave anymore after this.
+	// The effect of any further state changes to this instance
+	// should be undone / completed by the thread function.
+	iFManThread.SetPriority(EPriorityMuchLess);
+	iSwitches|=KFManBusyFlag;
 	iFsOld=iFs;
 	iLastError=KErrNone;
 	iFManThread.Logon(*iStatus);
--- a/userlibandfileserver/fileserver/shostmassstorage/server/controller/cusbhostmsdevice.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/shostmassstorage/server/controller/cusbhostmsdevice.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -160,7 +160,12 @@
 void CUsbHostMsDevice::SuspendLunL(TLun aLun)
 	{
     __MSFNLOG
-	iLuList.GetLuL(aLun).ReadyToSuspend();
+    if (IsSuspended())
+        {
+        return;
+        }
+
+    iLuList.GetLuL(aLun).ReadyToSuspend();
 
     // check whether all the luns are suspended, if so then request usb
     // interface suspension to the transport layer
--- a/userlibandfileserver/fileserver/shostmassstorage/server/controller/cusbhostmsdevicethread.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/shostmassstorage/server/controller/cusbhostmsdevicethread.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -173,11 +173,16 @@
         {
         if (iUsbHostMsDevice->IsSuspended())
             {
-            // request resume 
-            Unlock();
-            iUsbHostMsDevice->Resume(iStatus);
-            SetActive();
-            return;
+
+            RMessage2 msg = iRMessage2[iDequeueIndex];      
+            if (msg.Function() != EUsbHostMsSuspendLun)
+                {
+                // request resume 
+                Unlock();
+                iUsbHostMsDevice->Resume(iStatus);
+                SetActive();
+                return;
+                }            
             }
         }
 
@@ -309,8 +314,11 @@
 		return;
 	case EUsbHostMsUnRegisterInterface:
 		// Check whether all luns have got uninitialised. 
-		for(TInt i = 0, j = iUsbHostMsDevice->GetMaxLun(); i <= j; i++)
-			TRAP_IGNORE(iUsbHostMsDevice->RemoveLunL(i));
+        if (iUsbHostMsDevice)
+            {
+            for(TInt i = 0, j = iUsbHostMsDevice->GetMaxLun(); i <= j; i++)
+                TRAP_IGNORE(iUsbHostMsDevice->RemoveLunL(i));
+            }
 		TRAP(ret, UnRegisterInterfaceL(aMessage));
 		break;
 	case EUsbHostMsRegisterLun:
--- a/userlibandfileserver/fileserver/shostmassstorage/server/src/cusbhostmssession.cpp	Tue Sep 14 23:56:21 2010 +0300
+++ b/userlibandfileserver/fileserver/shostmassstorage/server/src/cusbhostmssession.cpp	Wed Sep 15 13:42:27 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of the License "Eclipse Public License v1.0"
@@ -114,8 +114,16 @@
 			return;
 			}
 		break;
-	case EUsbHostMsUnRegisterInterface:
-		iCleanupInProgress = ETrue;
+    case EUsbHostMsUnRegisterInterface:
+        if(iCleanupInProgress)
+            {
+            aMessage.Complete(KErrInUse);
+            return;
+            }
+        else
+            {
+            iCleanupInProgress = ETrue;
+            }
 		break;
 	/* If it is a cleanup then we need to delete the iDeviceThread */
 	case EUsbHostMsFinalCleanup:	
@@ -128,12 +136,17 @@
 		break;
 		}
 
-	if (iDeviceThread == NULL || iCleanupInProgress ) 
+	if (iDeviceThread == NULL) 
 		{
 		aMessage.Complete(KErrBadHandle);
 		return;
 		}
 
+    if (iCleanupInProgress && aMessage.Function() != EUsbHostMsUnRegisterInterface) 
+        {
+        aMessage.Complete(KErrBadHandle);
+        return;
+        }
 
 	r = iDeviceThread->QueueMsg(aMessage);
 	if (r != KErrNone)