201041_05
authorhgs
Mon, 18 Oct 2010 15:31:10 +0100
changeset 291 206a6eaaeb71
parent 289 55a0a1279a7e
child 293 0659d0e1a03c
201041_05
bsptemplate/asspandvariant/template_assp/iic/iic_slave.cpp
halservices/hal/inc/hal_data.h
kernel/eka/compsupp/ARM EABI LICENCE.txt
kernel/eka/compsupp/bld.inf
kernel/eka/compsupp/compsupp.iby
kernel/eka/compsupp/eabi/drtaeabiu.def
kernel/eka/compsupp/rt_2_2.zip
kernel/eka/compsupp/rt_3_1.zip
kernel/eka/compsupp/rt_4_0.zip
kernel/eka/compsupp/rvct/usrt.mmp
kernel/eka/compsupp/rvct/usrt_nx.mmp
kernel/eka/compsupp/symaehabi/callfirstprocessfn.cpp
kernel/eka/compsupp/symaehabi/cppsemantics.cpp
kernel/eka/compsupp/symaehabi/emergency_buffer.h
kernel/eka/compsupp/symaehabi/symbian_support.cpp
kernel/eka/compsupp/symaehabi/symbian_support.h
kernel/eka/drivers/hcr/hcr_pil.cpp
kernel/eka/drivers/iic/iic_channel.cpp
kernel/eka/drivers/pbus/mmc/sdcard/sdcard3c/sdcard.cpp
kernel/eka/drivers/pbus/mmc/stack.cpp
kernel/eka/drivers/resmanus/d_resmanus.cpp
kernel/eka/euser/epoc/up_dll_tls.cpp
kernel/eka/euser/us_time.cpp
kernel/eka/include/drivers/mmc.h
kernel/eka/include/e32hal.h
kernel/eka/include/e32std.h
kernel/eka/include/e32ver.h
kernel/eka/include/kernel/crash_gzip.h
kernel/eka/kernel/smonitor.cpp
kernel/eka/kernel/smonlog.cpp
kernel/eka/kernel/stimer.cpp
kernel/eka/memmodel/epoc/flexible/mmu/mmu.cpp
kernel/eka/release.txt
kerneltest/e32test/digitiser/d_ldddigitisertest.cpp
kerneltest/e32test/group/romstuff.mke
kerneltest/e32test/hcr/d_hcrext_client.mmp
kerneltest/e32test/hcr/d_hcrext_own.mmp
kerneltest/e32test/hcr/d_hcrsim.cpp
kerneltest/e32test/hcr/d_hcrsim_client.mmp
kerneltest/e32test/hcr/d_hcrsim_own.mmp
kerneltest/e32test/hcr/d_hcrsim_testdata.h
kerneltest/e32test/hcr/d_hcrut.cpp
kerneltest/e32test/hcr/d_hcrut.h
kerneltest/e32test/hcr/d_hcrut.mmp
kerneltest/e32test/hcr/hcr.inf
kerneltest/e32test/hcr/hcr_tests.iby
kerneltest/e32test/hcr/t_hcr.cpp
kerneltest/e32test/hcr/t_hcrut.cpp
kerneltest/e32test/mmu/d_shadow.cpp
kerneltest/e32test/mmu/d_shadow.h
kerneltest/e32test/mmu/t_shadow.cpp
kerneltest/e32test/resmanus/resourcecontrol.mmp
kerneltest/e32test/resmanus/resourcecontrollerextended.mmp
kerneltest/e32test/usbho/t_usbdi/t_usbhost_usbman_src/t_usbhost_usbman.cpp
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/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/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/testdata/testdata.zip
kerneltest/f32test/loader/dlltree.txt
kerneltest/f32test/server/t_falsespace.cpp
kerneltest/f32test/server/t_fsys.cpp
userlibandfileserver/fileserver/etshell/ts_com.cpp
userlibandfileserver/fileserver/etshell/ts_edshl.cpp
userlibandfileserver/fileserver/fs_utils/bit_vector.cpp
userlibandfileserver/fileserver/group/release.txt
userlibandfileserver/fileserver/inc/f32file.h
userlibandfileserver/fileserver/inc/f32ver.h
userlibandfileserver/fileserver/runtests/runtests.cpp
userlibandfileserver/fileserver/sfat32/fat_table32.cpp
userlibandfileserver/fileserver/sfat32/sl_bpb32.cpp
userlibandfileserver/fileserver/sfat32/sl_fatmisc32.cpp
userlibandfileserver/fileserver/sfat32/sl_file.cpp
userlibandfileserver/fileserver/sfat32/sl_fmt.cpp
userlibandfileserver/fileserver/sfat32/sl_fsy.cpp
userlibandfileserver/fileserver/sfat32/sl_leafdir_cache.cpp
userlibandfileserver/fileserver/sfat32/sl_mnt.cpp
userlibandfileserver/fileserver/sfat32/sl_mnt32.cpp
userlibandfileserver/fileserver/sfat32/sl_scan32.cpp
userlibandfileserver/fileserver/sfat32/sl_vfat.cpp
userlibandfileserver/fileserver/sfile/sf_drv.cpp
userlibandfileserver/fileserver/sfsrv/cl_cli.cpp
--- a/bsptemplate/asspandvariant/template_assp/iic/iic_slave.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/bsptemplate/asspandvariant/template_assp/iic/iic_slave.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -602,7 +602,7 @@
 		//		while(AsspRegister::Read32(iChannelBase + KFifoLevelOffset) <= (KFifoMaxLevel - iWordSize) &&
 		//		      iTxData != iTxDataEnd)
 		// For the template port, will just use a dummy variable (dummyFifoLvlChk )in place of the register read
-		TInt dummyFifoLvlChk = 0;
+		TInt dummyFifoLvlChk = 1;
 		while((dummyFifoLvlChk)	&&	// Replace this dummy variable with a read of the hardware
 			(iTxData != iTxDataEnd))
 			{
--- a/halservices/hal/inc/hal_data.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/halservices/hal/inc/hal_data.h	Mon Oct 18 15:31:10 2010 +0100
@@ -1025,7 +1025,7 @@
 		/**
 		Maximum Number of Pointers supported by hardware/driver
 
-		Returns the maximum number of pointers for a multi-touch configuration (or KErrNotSupported or 0 or 1 for single-touch legacy configuration)
+		Returns the maximum number of pointers for a multipletouch configuration (or KErrNotSupported or 0 or 1 for single-touch legacy configuration)
 		*/
 		EPointerMaxPointers,
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kernel/eka/compsupp/ARM EABI LICENCE.txt	Mon Oct 18 15:31:10 2010 +0100
@@ -0,0 +1,130 @@
+The Specimen Implementations of the Exception Handling Components of the ABI for the ARM(R) Architecture consists of copyright owned by ARM Limited and copyright owned by Nokia Corporation. Each is licensed to you separately by the respective copyright owner, on the terms set out in this file.
+
+1. LICENSE TO ARM COPYRIGHT
+
+IMPORTANT: THIS IS A LEGAL AGREEMENT ("LICENCE") BETWEEN YOU (AN INDIVIDUAL OR
+SINGLE ENTITY WHO IS RECEIVING THIS SOURCE CODE DIRECTLY FROM ARM LIMITED)
+("LICENSEE") AND ARM LIMITED ("ARM") FOR THE VERSION OF THE SOURCE CODE SUPPLIED
+WITH THIS LICENCE ("SOURCE CODE"). THE SOURCE CODE IS A SPECIMEN IMPLEMENTATION OF
+EXCEPTION HANDLING COMPONENTS COMPLYING WITH THE SPECIFICATION DEFINED IMMEDIATELY
+BELOW. BY DOWNLOADING OR OTHERWISE USING THE SOURCE CODE, YOU AGREE TO BE BOUND BY
+ALL OF THE TERMS OF THIS LICENCE. IF YOU DO NOT AGREE TO THIS, DO NOT DOWNLOAD OR
+USE THE SOURCE CODE.
+
+“Specification” means, and is limited to, version 2 of the specification for the
+Applications Binary Interface for the ARM Architecture published by ARM.
+Notwithstanding the foregoing,  Specification” shall not include (i) the
+implementation of other published specifications referenced in this  Specification;
+(ii) any enabling technologies that may be necessary to make or use any product or
+portion thereof that complies with this Specification, but are not themselves
+expressly set forth in this Specification (e.g. compiler front ends, code
+generators, back ends, libraries or other compiler, assembler or linker
+technologies; validation or debug software or hardware; applications, operating
+system or driver software; RISC architecture; processor microarchitecture);
+(iii) maskworks and physical layouts of integrated circuit designs; or (iv) RTL or
+other high level representations of integrated circuit designs.
+
+Use, copying or disclosure by the US Government is subject to the restrictions set
+out in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software
+clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial
+Computer Software - Restricted Rights at 48 C.F.R. 52.227-19, as applicable.
+
+The Source Code is owned by ARM or its licensors and is protected by copyright laws
+and international copyright treaties as well as other intellectual property laws and
+treaties. The Source Code is licensed not sold.
+
+1.  Subject to the provisions of Clauses 2 and 3, ARM hereby grants to LICENSEE,
+under any intellectual property that is (i) owned or freely licensable by ARM
+without payment to unaffiliated third parties and (ii) either embodied in the Source
+Code, or Necessary to copy or implement an applications binary interface compliant
+with the Specification, a perpetual, non-exclusive, non-transferable, fully paid,
+worldwide limited licence to use, copy, modify and sublicense this Source Code (in
+source or object code form) solely for the purpose of developing, having developed,
+manufacturing, having manufactured, offering to sell, selling, supplying or
+otherwise distributing products which comply with the Specification, provided that
+LICENSEE preserves all copyright notices included in the Source Code. All other
+rights are reserved to ARM or its licensors.
+
+2. THIS SOURCE CODE IS PROVIDED "AS IS" WITH NO WARRANTIES EXPRESS, IMPLIED OR
+STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY OF SATISFACTORY QUALITY,
+MERCHANTABILITY, NONINFRINGEMENT OR FITNESS FOR A PARTICULAR PURPOSE. THE SOURCE
+CODE MAY INCLUDE ERRORS. ARM RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE
+SOURCE CODE IN LATER REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE
+SPECIFICATION OR THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
+
+3.  This Licence shall immediately terminate and shall be unavailable to LICENSEE if
+LICENSEE or any party affiliated to LICENSEE asserts any patents against ARM, ARM
+affiliates, third parties who have a valid licence from ARM for the Specification or
+the Source Code, or any customers or distributors of any of them based upon a claim
+that a LICENSEE (or LICENSEE affiliate) patent is Necessary to implement the
+Specification. In this Licence; (i) "affiliate" means any entity controlling,
+controlled by or under common control with a party (in fact or in law, via voting
+securities, management control or otherwise) and "affiliated" shall be construed
+accordingly; (ii) "assert" means to allege infringement in legal or administrative
+proceedings, or proceedings before any other competent trade, arbitral or
+international authority; (iii) “Necessary” means with respect to any claims of any
+patent, those claims which, without the appropriate permission of the patent owner,
+will be infringed when implementing the Specification because no alternative,
+commercially reasonable, non-infringing way of implementing the Specification is
+known; and (iv) English law and the jurisdiction of the English courts shall apply
+to all aspects of this Licence, its interpretation and enforcement. The total
+liability of ARM and any of its suppliers and licensors under or in relation to this
+Licence shall be limited to the greater of the amount actually paid by LICENSEE for
+the Specification or US$10.00. The limitations, exclusions and disclaimers in this
+Licence shall apply to the maximum extent allowed by applicable law.
+
+
+ARM contract reference number LEC-ELA-00080-V2.0.
+
+
+2. LICENSE TO NOKIA COPYRIGHT
+
+IMPORTANT: THIS IS A LEGAL AGREEMENT ("LICENCE") BETWEEN YOU (AN INDIVIDUAL OR
+SINGLE ENTITY WHO IS RECEIVING THIS SOURCE CODE FROM NOKIA CORPORATION)
+("LICENSEE") AND NOKIA CORPORATION ("NOKIA") FOR THE VERSION OF THE SOURCE CODE SUPPLIED WITH THIS LICENCE ("SOURCE CODE"). THE SOURCE CODE IS A SPECIMEN IMPLEMENTATION OF EXCEPTION HANDLING COMPONENTS COMPLYING WITH THE SPECIFICATION DEFINED IMMEDIATELY BELOW. BY DOWNLOADING OR OTHERWISE USING THE SOURCE CODE, YOU AGREE TO BE BOUND BY ALL OF THE TERMS OF THIS LICENCE. IF YOU DO NOT AGREE TO THIS, DO NOT DOWNLOAD OR USE THE SOURCE CODE.
+
+“Specification” means, and is limited to, version 2 of the specification for the
+Applications Binary Interface for the ARM Architecture published by ARM LIMITED.
+Notwithstanding the foregoing,  Specification” shall not include (i) the
+implementation of other published specifications referenced in this Specification;
+(ii) any enabling technologies that may be necessary to make or use any product or
+portion thereof that complies with this Specification, but are not themselves
+expressly set forth in this Specification (e.g. compiler front ends, code
+generators, back ends, libraries or other compiler, assembler or linker
+technologies; validation or debug software or hardware; applications, operating
+system or driver software; RISC architecture; processor microarchitecture);
+(iii) maskworks and physical layouts of integrated circuit designs; or (iv) RTL or
+other high level representations of integrated circuit designs.
+
+Use, copying or disclosure by the US Government is subject to the restrictions set
+out in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software
+clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial
+Computer Software - Restricted Rights at 48 C.F.R. 52.227-19, as applicable.
+
+The Source Code is owned by Nokia or its licensors and is protected by copyright laws
+and international copyright treaties as well as other intellectual property laws and
+treaties. The Source Code is licensed not sold.
+
+1.  Subject to the provisions of Clauses 2 and 3, Nokia hereby grants to LICENSEE,
+under any intellectual property that is (i) owned or freely licensable by Nokia
+without payment to unaffiliated third parties and (ii) either embodied in the Source
+Code, or Necessary to copy or implement an applications binary interface compliant
+with the Specification, a perpetual, non-exclusive, non-transferable, fully paid,
+worldwide limited licence to use, copy, modify and sublicense this Source Code (in
+source or object code form) solely for the purpose of developing, having developed,
+manufacturing, having manufactured, offering to sell, selling, supplying or
+otherwise distributing products which comply with the Specification, provided that
+LICENSEE preserves all copyright notices included in the Source Code. All other
+rights are reserved to Nokia or its licensors.
+
+2. THIS SOURCE CODE IS PROVIDED "AS IS" WITH NO WARRANTIES EXPRESS, IMPLIED OR
+STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY OF SATISFACTORY QUALITY,
+MERCHANTABILITY, NONINFRINGEMENT OR FITNESS FOR A PARTICULAR PURPOSE. THE SOURCE
+CODE MAY INCLUDE ERRORS. ARM RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE
+SOURCE CODE IN LATER REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE
+SPECIFICATION OR THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
+
+3.  English law and the jurisdiction of the English courts shall apply
+to all aspects of this Licence, its interpretation and enforcement. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL NOKIA, ITS EMPLOYEES OR LICENSORS OR AFFILIATES BE LIABLE FOR ANY LOST PROFITS, REVENUE, SALES, DATA, OR COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, PROPERTY DAMAGE, PERSONAL INJURY, INTERRUPTION OF BUSINESS, LOSS OF BUSINESS INFORMATION, OR FOR ANY SPECIAL, DIRECT, INDIRECT, INCIDENTAL, ECONOMIC, COVER, PUNITIVE, OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED AND WHETHER ARISING UNDER CONTRACT, TORT, NEGLIGENCE, OR OTHER THEORY OF LIABILITY ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, EVEN IF NOKIA OR ITS LICENSORS OR AFFILIATES ARE ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME COUNTRIES/STATES/JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF LIABILITY, BUT MAY ALLOW LIABILITY TO BE LIMITED, IN SUCH CASES, NOKIA, ITS EMPLOYEES OR LICENSORS OR AFFILIATES' LIABILITY SHALL BE LIMITED TO U.S. $50. Nothing contained in this Agreement shall prejudice the statutory rights of any party dealing as a consumer. Nothing contained in this Agreement limits Nokia's liability to You in the event of death or personal injury resulting from Nokia's negligence. Nokia is acting on behalf of its employees and licensors or affiliates for the purpose of disclaiming, excluding, and/or restricting obligations, warranties, and liability as provided in this clause 9, but in no other respects and for no other purpose.
+
+</End>
--- a/kernel/eka/compsupp/bld.inf	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/bld.inf	Mon Oct 18 15:31:10 2010 +0100
@@ -1,4 +1,4 @@
-// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2005-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 "ARM EABI LICENCE.txt"
@@ -13,66 +13,66 @@
 // Description:
 // Compiler runtime support.
 // 
-//
 
 PRJ_PLATFORMS
 
-ARMV4 ARMV5 ARMV5SMP ARMV7
-
+ARMV4 ARMV5 ARMV5SMP ARMV6 ARMV7
 
 PRJ_EXPORTS
 
-rvct.h                      SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(rvct/)
-gcce/gcce.h                 SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(gcce/)
+rvct.h              SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(rvct/)
+gcce/gcce.h         SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(gcce/)
+symcpp/symcpp.h     SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(symcpp.h)
 
-symcpp/symcpp.h SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(symcpp.h)
-
-compsupp.iby                /epoc32/rom/include/
-
+compsupp.iby        /epoc32/rom/include/
 
 PRJ_MMPFILES
 
-#if !defined GCCXML && !defined GCCE
+#if !defined(GCCXML) && !defined(GCCE)
 
     symcpp/scppnwdl.mmp
     rvct/dfprvct-thunk.mmp
     rvct/usrt.mmp
+    rvct/usrt_nx.mmp
     rvct/ksrt.mmp
 
-    #ifndef SMP // Only static libraries build for SMP.
-
-    rvct/drtaeabi.mmp
-
-    rvct/dfpaeabi.mmp
-    rvct/dfpaeabi_vfpv2.mmp
+    #ifndef SMP
+        rvct/drtaeabi.mmp
+        rvct/dfpaeabi.mmp
+        rvct/dfpaeabi_vfpv2.mmp
 
-    #if defined(ARMCC_2_2) || defined(ARMCC_3_1)
-
-        rvct/drtrvct.mmp
-        rvct/drtrvct_vfpv2.mmp
-
-        rvct/dfprvct.mmp
-        rvct/dfprvct_vfpv2.mmp
-    #endif
-
+        // As of RVCT 4.0 we no longer export compiler-internal functions.
+        #if defined(ARMCC_2_2) || defined(ARMCC_3_1)
+            rvct/drtrvct.mmp
+            rvct/drtrvct_vfpv2.mmp
+            rvct/dfprvct.mmp
+            rvct/dfprvct_vfpv2.mmp
+        #endif
     #endif
 
 PRJ_EXTENSIONS
 
-// Unzip RVCT3.1 runtime if being built with RVCT2.2 or RVCT4.0
-
-start extension tools/compsupp
+    #ifndef ARMCC_2_2
+    start extension tools/compsupp
+    option  FILE  $(EXTENSION_ROOT)/rt_2_2.zip
+    option  TODIR $(EPOCROOT)epoc32/release
+    end
+    #endif
 
-#if defined(ARMCC_2_2) || defined(ARMCC_4_0)
-option  FILE  $(EXTENSION_ROOT)/rt_3_1.zip
-#elif defined(ARMCC_3_1)
-option  FILE  $(EXTENSION_ROOT)/rt_2_2.zip
+    #ifndef ARMCC_3_1
+    start extension tools/compsupp
+    option  FILE  $(EXTENSION_ROOT)/rt_3_1.zip
+    option  TODIR $(EPOCROOT)epoc32/release
+    end
+    #endif
+
+    #ifndef ARMCC_4_0
+    start extension tools/compsupp
+    option  FILE  $(EXTENSION_ROOT)/rt_4_0.zip
+    option  TODIR $(EPOCROOT)epoc32/release
+    end
+    #endif
+
 #endif
 
-option  TODIR $(EPOCROOT)epoc32/release
 
-end
-
-#endif // #if !defined GCCXML && !defined GCCE
-
-
--- a/kernel/eka/compsupp/compsupp.iby	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/compsupp.iby	Mon Oct 18 15:31:10 2010 +0100
@@ -25,9 +25,9 @@
 #   error "RVCT 2.1 is not supported."
 #endif
 
-// Set a default run-time version. In the future, 3.1 or 4.X should be the default.
+// Set RVCT4.0 as the default run-time version for TB10.1
 #if !( defined(RVCT2_2) || defined(RVCT3_1) || defined(RVCT4_0) )
-#   define RVCT2_2
+#   define RVCT4_0
 #endif
 
 #if defined(VFPHELPERS) && !defined(NOVFPHELPERS)
--- a/kernel/eka/compsupp/eabi/drtaeabiu.def	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/eabi/drtaeabiu.def	Mon Oct 18 15:31:10 2010 +0100
@@ -224,4 +224,6 @@
 	__aeabi_uidiv @ 223 NONAME
 	__ARM_get_typeid @ 224 NONAME
 	__cxa_get_exception_ptr @ 225 NONAME
+	_ZN23TCppRTExceptionsGlobals22Init2ndEmergencyBufferEv @ 226 NONAME
+	_ZN23TCppRTExceptionsGlobals22Kill2ndEmergencyBufferEv @ 227 NONAME
 
Binary file kernel/eka/compsupp/rt_2_2.zip has changed
Binary file kernel/eka/compsupp/rt_3_1.zip has changed
Binary file kernel/eka/compsupp/rt_4_0.zip has changed
--- a/kernel/eka/compsupp/rvct/usrt.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/rvct/usrt.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -22,8 +22,6 @@
 target          usrt3_1.lib
 #elif defined(ARMCC_4_0)
 target 		    usrt4_0.lib
-#else
-target          error
 #endif
 
 SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kernel/eka/compsupp/rvct/usrt_nx.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -0,0 +1,49 @@
+// Copyright (c) 2009-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 "ARM EABI LICENCE.txt"
+// which accompanies this distribution, and is available
+// in kernel/eka/compsupp.
+//
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+//
+
+#if defined(ARMCC_2_2)
+target          usrt_nx_2_2.lib
+#elif defined(ARMCC_3_1)
+target          usrt_nx_3_1.lib
+#elif defined(ARMCC_4_0)
+target 		    usrt_nx_4_0.lib
+#endif
+
+SMPSAFE
+targettype      lib
+
+macro           ENABLE_2ND_EMERGENCY_BUFFER
+
+always_build_as_arm
+
+source          ucppfini.cpp
+source          ucppinit.cpp 
+source          dllexp.cpp
+source          ../symaehabi/callfirstprocessfn.cpp
+
+#if defined(ARMCC_2_2) || defined(ARMCC_3_1)
+sourcepath      call_via_rx
+source          r0.cpp r1.cpp r2.cpp r3.cpp 
+source          r4.cpp r5.cpp r6.cpp r7.cpp 
+#endif
+
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+start armcc
+    arminc
+end
+
--- a/kernel/eka/compsupp/symaehabi/callfirstprocessfn.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/symaehabi/callfirstprocessfn.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-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 "ARM EABI LICENCE.txt"
@@ -39,14 +39,18 @@
 	{
 	TCppRTExceptionsGlobals aExceptionGlobals;
 
+	#if ENABLE_2ND_EMERGENCY_BUFFER
+	aExceptionGlobals.Init2ndEmergencyBuffer();
+	#endif
+
 	if (!aNotFirst)
 		{
 		// Init statics for implicitly linked DLLs
 		User::InitProcess();
 
-		// Init statics for EXE
 		//pick up export table if we're an exexp
 		__DLL_Export_Table__();
+		// Init statics for EXE
 		__cpp_initialize__aeabi_();
 		}
 #ifdef __LEAVE_EQUALS_THROW__
@@ -54,9 +58,15 @@
 
 	try {
 		r = aNotFirst ? (*aFn)(aPtr) : E32Main();
+        #if ENABLE_2ND_EMERGENCY_BUFFER
+        aExceptionGlobals.Kill2ndEmergencyBuffer();
+        #endif
 		}
 	catch (XLeaveException&)
 		{
+        #if ENABLE_2ND_EMERGENCY_BUFFER
+        aExceptionGlobals.Kill2ndEmergencyBuffer();
+        #endif
 		User::Panic(KLitUser, EUserLeaveWithoutTrap);
 		}
 
--- a/kernel/eka/compsupp/symaehabi/cppsemantics.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/symaehabi/cppsemantics.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -6,7 +6,7 @@
  * text file LICENCE.txt (ARM contract number LEC-ELA-00080 v1.0).
  */
 
-/* Portions copyright Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). */
+/* Portions copyright Copyright (c) 2009-2010 Nokia Corporation and/or its subsidiary(-ies). */
 
 /*
  * RCS $Revision: 92950 $
@@ -354,9 +354,26 @@
 void *__ARM_exceptions_buffer_allocate(void *buffer, size_t size)
 {
   emergency_buffer *b = (emergency_buffer *)buffer;
+
+  #ifndef __EPOC32__
   if (size > sizeof(emergency_eco) || b == NULL || b->inuse) return NULL;
   b->inuse = true;
   return &b->eco;
+  #else
+  ASSERT(b);
+
+  if (size > sizeof(emergency_eco) || b->inuse) {
+    // The first buffer isn't usable; try the second one instead, if it exists.
+    if (b->em_buf2_p)
+    	return b->em_buf2_p->Alloc(size);
+    else
+    	return NULL;
+  }
+  else {
+    b->inuse = true;
+    return &b->eco;
+  }
+  #endif
 }
 
 // Deallocator: Must return non-NULL if and only if it recognises
@@ -364,9 +381,26 @@
 void *__ARM_exceptions_buffer_free(void *buffer, void *addr)
 {
   emergency_buffer *b = (emergency_buffer *)buffer;
+
+  #ifndef __EPOC32__
   if (b == NULL || addr != &b->eco) return NULL;
   b->inuse = false;
   return b;
+  #else
+  ASSERT(b);
+
+  if (addr != &b->eco) {
+    // The object wasn't from the first buffer; see if it is from the second one.
+    if (b->em_buf2_p)
+      return b->em_buf2_p->Free(addr);
+    else
+      return NULL;
+  }
+  else {
+    b->inuse = false;
+    return b;
+  }
+  #endif
 }
 
 #  if 0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kernel/eka/compsupp/symaehabi/emergency_buffer.h	Mon Oct 18 15:31:10 2010 +0100
@@ -0,0 +1,75 @@
+// Copyright (c) 2009-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 "ARM EABI LICENCE.txt"
+// which accompanies this distribution, and is available
+// in kernel/eka/compsupp.
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+//
+
+template<typename T, unsigned N> class TEmergencyBuffer
+	{
+public:
+	void Init();
+public:
+	void* Alloc(unsigned);
+	void* Free(void*);
+private:
+	bool iIsOccupied[N];
+	T iSlots[N];
+private:
+	TEmergencyBuffer();
+	};
+
+template<typename T, unsigned N> inline void TEmergencyBuffer<T,N>::Init()
+	{
+	for (int i=0; i < N; i++)
+		{
+		iIsOccupied[i] = 0;
+		}
+	}
+
+template<typename T, unsigned N> void* TEmergencyBuffer<T,N>::Alloc(unsigned n)
+	{
+	if ( n <= sizeof(T) )
+		{
+		for (int i=0; i < N; i++)
+			{
+			bool& isOccupied = iIsOccupied[i];
+
+			if ( ! isOccupied )
+				{
+				isOccupied = 1;
+				return &iSlots[i];
+				}
+			}
+		}
+
+	return NULL;
+	}
+
+template<typename T, unsigned N> void* TEmergencyBuffer<T,N>::Free(void* p)
+	{
+	for (int i=0; i < N; i++)
+		{
+		const void* bp = &iSlots[i];
+		bool& isOccupied = iIsOccupied[i];
+
+		if ( bp == p && isOccupied )
+			{
+			isOccupied = 0;
+			return p;
+			}
+		}
+
+	return NULL;
+	}
+
+
--- a/kernel/eka/compsupp/symaehabi/symbian_support.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/symaehabi/symbian_support.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-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 "ARM EABI LICENCE.txt"
@@ -12,7 +12,7 @@
 //
 // Description:
 // e32/compsupp/symaehabi/symbian_support.cpp
-// 
+//
 //
 
 /* Environment: */
@@ -40,6 +40,7 @@
 EXPORT_C TCppRTExceptionsGlobals::TCppRTExceptionsGlobals()
 	{
 	buffer.inuse = false;
+	buffer.em_buf2_p = NULL;
 	thread_globals.uncaughtExceptions = 0;
 	thread_globals.unexpectedHandler = NAMES::default_unexpected_handler;
 	thread_globals.terminateHandler = __default_terminate_handler;
@@ -50,8 +51,27 @@
 	thread_globals.emergency_buffer = &buffer;
 	Dll::SetTls(this);
 	}
+
+EXPORT_C void TCppRTExceptionsGlobals::Init2ndEmergencyBuffer()
+	{
+	ASSERT(buffer.em_buf2_p == NULL);
+
+	TEmergencyBuffer2* p = (TEmergencyBuffer2*) User::Alloc( sizeof(TEmergencyBuffer2) );
+	if (!p)
+		abort();
+	p->Init();
+	buffer.em_buf2_p = p;
+	}
+
+EXPORT_C void TCppRTExceptionsGlobals::Kill2ndEmergencyBuffer()
+	{
+	ASSERT(buffer.em_buf2_p);
+
+	User::Free(buffer.em_buf2_p);
+	}
+
 #if __ARMCC_VERSION < 220000
-extern "C" 
+extern "C"
 {
   /*
     we have to dummy up the following for 2.1. The names changed in the def file
@@ -78,7 +98,7 @@
 	}
 }
 
-#else 
+#else
 // This is the key function that forces the class impedimenta to be get exported in RVCT 2.2 and later.
 EXPORT_C void XLeaveException::ForceKeyFunction(){}
 #endif
@@ -224,9 +244,9 @@
 		// look in extension ROM if there is one
 		TUint main_start = UserSvr::RomHeaderAddress();
 		TUint main_end = main_start + ((TRomHeader*)main_start)->iUncompressedSize;
-		
+
 		TUint rda = UserSvr::RomRootDirectoryAddress();
-		
+
 		// Assume rom starts on multiple of 4k
 		if (rda > main_end)
 			{
@@ -237,7 +257,7 @@
 			// 3. the extension ROM is mapped starting at a megabyte boundary
 			// Thus the address of the extension ROM header may be obtained by rounding the root directory
 			// address down to the next megabyte boundary.
-         
+
  			TUint ext_start = rda &~ 0x000fffffu;
 			TRomExceptionSearchTable* extrom_exctab = (TRomExceptionSearchTable*)(((TExtensionRomHeader*)ext_start)->iRomExceptionSearchTable);
 			if (extrom_exctab && addr >= extrom_exctab->iEntries[0] && addr < GET_EST_FENCEPOST(extrom_exctab))
@@ -315,7 +335,7 @@
 public:
 	virtual void Overflow(TDes8& /*aDes*/) {}
 	};
-	
+
 #endif
 
 void DebugPrintf(const char * aFmt, ...)
@@ -333,7 +353,7 @@
 	RDebug::RawPrint(buf2);
 #else
 	(void)aFmt;
-#endif		
+#endif
 	}
 
 } // extern "C"
--- a/kernel/eka/compsupp/symaehabi/symbian_support.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/compsupp/symaehabi/symbian_support.h	Mon Oct 18 15:31:10 2010 +0100
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-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 "ARM EABI LICENCE.txt"
@@ -69,8 +69,25 @@
     XLeaveException aUserLeaveException;
 };
 
+
+
+#include "emergency_buffer.h"
+
+struct emergency_eco2 : emergency_eco {
+  // The secondary emergency buffer might as well support slightly bigger objects.
+  int spacer[6];
+};
+
+typedef TEmergencyBuffer<emergency_eco2, 2> TEmergencyBuffer2;
+
+
 struct emergency_buffer {
   bool inuse;
+
+  TEmergencyBuffer2* em_buf2_p; // offset = 4, size = 4.
+
+  // This field has always been forced to an 8-byte alignment, so the fact that
+  // em_buf2_p has been added shouldn't break compatibility with existing binaries.
   struct emergency_eco eco;
 };
 
@@ -79,6 +96,9 @@
 	{
 public:
 	IMPORT_C TCppRTExceptionsGlobals();
+public:
+	IMPORT_C void Init2ndEmergencyBuffer();
+	IMPORT_C void Kill2ndEmergencyBuffer();
 private:
 	__cxa_eh_globals thread_globals;
 	emergency_buffer buffer;
--- a/kernel/eka/drivers/hcr/hcr_pil.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/drivers/hcr/hcr_pil.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -93,7 +93,7 @@
 
 // -- WINS Specific ----------------------------------------------------------
 
-#ifdef __WINS__
+#if defined(__WINS__) || defined(HCRTEST_AVOID_BSP_HCR_DAT)
 
 // Set to ensure Rom Hdr dependency does not break compilation in 
 // LocateCoreImgRepository() at the end of this file.
@@ -104,6 +104,7 @@
 
 #endif
 
+
 // -- FUNCTIONS ---------------------------------------------------------------
 
 /**
@@ -2955,10 +2956,14 @@
     // Use this testing more on Emulator platform
     // and on hardware when ROM Header is not to be used or not implemented
     
+#ifdef HCRTEST_AVOID_BSP_HCR_DAT
+	const TText8* hcrfile = (const TText8*) "test_hcr.dat";
+#else
 	const TText8* hcrfile = (const TText8*) "hcr.dat";
+#endif
 	TInt retVal = SearchCoreImgRepository(aRepos, hcrfile);
 	if (retVal != KErrNone)
-		return retVal;
+		HCR_TRACE_RETURN(retVal);
 	
 #else
 
@@ -2980,10 +2985,10 @@
 			aRepos = HCR::TRepositoryFile::New(reinterpret_cast<const HCR::SRepositoryFile *>(romHeader.iHcrFileAddress));
 			NKern::ThreadLeaveCS();
 			if (aRepos == 0)
-				return KErrNoMemory;
+				HCR_TRACE_RETURN(KErrNoMemory);
 			}
 	else
-		return KErrNotFound;
+		HCR_TRACE_RETURN(KErrNotFound);
 		
 #endif // HCRTEST_COREIMG_DONTUSE_ROMHDR
 
--- a/kernel/eka/drivers/iic/iic_channel.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/drivers/iic/iic_channel.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -443,6 +443,8 @@
 
 		if(r == KErrNone)
 			{
+			// Use placement new to re-initialise the iClientTimeoutDfc callback object (don't re-allocate the memory)
+			new (iClientTimeoutDfc) TDfc(SlaveStaticCB,(TAny*)this, 7);	// Highest Dfc priority
 			iClient->Open();
 			aCallback->iChannel=this;
 			iNotif = aCallback;
@@ -456,7 +458,6 @@
 				}
 			else
 				r=DoRequest(ESyncConfigPwrUp);
-
 			if(r == KErrNone)
 				{
 				if(!aAsynch)	// For asynchronous version there is nothing more to do until the callback is invoked
@@ -477,6 +478,7 @@
 	return r;
 	}
 
+
 TInt DIicBusChannelSlave::ReleaseChannel()
 	{
 	__KTRACE_OPT(KIIC, Kern::Printf("DIicBusChannelSlave::ReleaseChannel\n"));
@@ -494,6 +496,10 @@
 	r=DoRequest(EPowerDown);
 	if(r == KErrNone)
 		{
+		if(iClientTimeoutDfc != NULL)
+			{
+			iClientTimeoutDfc->~TDfc();	// call destructor directly, ie don't free the memory
+			}
 		TInt intState=__SPIN_LOCK_IRQSAVE(iSpinLock);
 		iClient=NULL;
 		iChannelInUse=0;	// Channel now available for capture by other clients
@@ -802,7 +808,7 @@
 
 DIicBusChannelSlave::DIicBusChannelSlave(TBusType aBusType, TChannelDuplex aChanDuplex, TInt16 aChannelId)
 	: DIicBusChannel(DIicBusChannel::ESlave, aBusType, aChanDuplex),
-	iChannelId(aChannelId), iTimerState(EInactive),
+	iChannelId(aChannelId), iClientTimeoutDfc(NULL), iTimerState(EInactive),
 	iMasterWaitTime(KSlaveDefMWaitTime), iClientWaitTime(KSlaveDefCWaitTime),
 	iSpinLock(TSpinLock::EOrderGenericIrqLow2)  // Semi-arbitrary, low priority value
 	{
@@ -813,7 +819,12 @@
 
 DIicBusChannelSlave::~DIicBusChannelSlave()
     {
-    delete iClientTimeoutDfc;
+	if(iClientTimeoutDfc != NULL)
+		{
+		delete iClientTimeoutDfc;
+		iClientTimeoutDfc = NULL;
+		}
+	return;
     }
 
 void DIicBusChannelSlave::SlaveStaticCB(TAny* aPtr)
@@ -1139,9 +1150,7 @@
 
 TInt DIicBusChannelMasterSlave::ReleaseChannel()
     {
-	iMasterChannel->Lock();
 	TInt r=iSlaveChannel->ReleaseChannel();
-	iMasterChannel->Unlock();
 	return r;
 	};
 
--- a/kernel/eka/drivers/pbus/mmc/sdcard/sdcard3c/sdcard.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/drivers/pbus/mmc/sdcard/sdcard3c/sdcard.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -636,6 +636,7 @@
 			__KTRACE_OPT(KPBUS1, Kern::Printf("R7 not supported."));
 			OstTrace0( TRACE_INTERNALS, DSDSTACK_INITIALISEMEMORYCARDSM3, "R7 not supported" );
 			Command().iSpec.iResponseType = ERespTypeR1;
+			Command().iFlags |= KMMCCmdFlagIgnoreStatus;
 			}
 
  
--- a/kernel/eka/drivers/pbus/mmc/stack.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/drivers/pbus/mmc/stack.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -5712,10 +5712,15 @@
 		else
 			{
 			// If commands returns card status and there we no command errors
-			// (or the status contains errors) then save the status info.
-			if ( (cmd.iFlags & KMMCCmdFlagStatusReceived) ||
-				 ((exitCode==KMMCErrNone || (exitCode & KMMCErrStatus)) &&
-				  (cmd.iSpec.iResponseType==ERespTypeR1 || cmd.iSpec.iResponseType==ERespTypeR1B)) )
+			// (or the status contains errors) and the status is not to be ignored, 
+			// then save the status info.
+			if ( !(cmd.iFlags & KMMCCmdFlagIgnoreStatus) &&
+				 ((cmd.iFlags & KMMCCmdFlagStatusReceived) ||
+				 ((exitCode==KMMCErrNone || (exitCode & KMMCErrStatus))) &&
+				 (cmd.iSpec.iResponseType==ERespTypeR1 || cmd.iSpec.iResponseType==ERespTypeR1B)) )
+
+				  
+				  
 				{
 				TMMCStatus status=s.ResponseP();
 				s.iLastStatus=status;
--- a/kernel/eka/drivers/resmanus/d_resmanus.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/drivers/resmanus/d_resmanus.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -77,32 +77,45 @@
 			__ASSERT_ALWAYS(0,RESMANUS_FAULT());					\
 		}															\
 	}
+
 /***************************************************************************************
 	class TTrackGetStateBuf
  ***************************************************************************************/
-TTrackGetStateBuf::TTrackGetStateBuf(TPowerResourceCbFn aFn, TAny* aPtr,
+TTrackGetStateBuf::TTrackGetStateBuf(TPowerResourceCbFn aFn, TAny* /*aPtr*/,
 						       TDfcQue* aQue, TInt aPriority)
-							   :	iCtrlBlock(aFn, aPtr, aQue, aPriority)
+							   :	iCtrlBlock(aFn, this, aQue, aPriority)
 	{
 	iRequest = NULL;
 	}
 
+TTrackGetStateBuf::~TTrackGetStateBuf()
+	{
+	if(iRequest)
+		Kern::DestroyClientRequest(iRequest);
+	}
+
 /***************************************************************************************
 	class TTrackSetStateBuf
  ***************************************************************************************/
-TTrackSetStateBuf::TTrackSetStateBuf(TPowerResourceCbFn aFn, TAny* aPtr,
+TTrackSetStateBuf::TTrackSetStateBuf(TPowerResourceCbFn aFn, TAny* /*aPtr*/,
 						       TDfcQue* aQue, TInt aPriority)
-							   :	iCtrlBlock(aFn, aPtr, aQue, aPriority)
+							   :	iCtrlBlock(aFn, this, aQue, aPriority)
 	{
 	iRequest = NULL;
 	}
 
+TTrackSetStateBuf::~TTrackSetStateBuf()
+	{
+	if(iRequest)
+		Kern::DestroyClientRequest(iRequest);
+	}
+
 /***************************************************************************************
 	class TTrackNotifyBuf
  ***************************************************************************************/
-TTrackNotifyBuf::TTrackNotifyBuf(TPowerResourceCbFn aFn, TAny* aPtr,
+TTrackNotifyBuf::TTrackNotifyBuf(TPowerResourceCbFn aFn, TAny* /*aPtr*/,
 								 TDfcQue* aQue, TInt aPriority)
-							   :	iNotifyBlock(aFn, aPtr, aQue, aPriority)
+							   :	iNotifyBlock(aFn, this, aQue, aPriority)
 	{
 	iRequest = NULL;
 	}
@@ -113,17 +126,6 @@
 		Kern::DestroyClientRequest(iRequest);
 	}
 
-TTrackSetStateBuf::~TTrackSetStateBuf()
-	{
-	if(iRequest)
-		Kern::DestroyClientRequest(iRequest);
-	}
-
-TTrackGetStateBuf::~TTrackGetStateBuf()
-	{
-	if(iRequest)
-		Kern::DestroyClientRequest(iRequest);
-	}
 	
 /***************************************************************************************
 	class DDeviceResManUs
@@ -505,7 +507,6 @@
 			if( r != KErrNone)
 				return r;
 			callBack = &(((TTrackSetStateBuf*)trackBuf)->iCtrlBlock);
-			new (callBack) TPowerResourceCb(&AsyncCallBackFn, (TAny*)trackBuf, iDfcQ, KResManCallBackPriority);
 			parms[0] = (TUint)m.Ptr2();
 			parms[1] = (TUint)callBack;
 			m.iArg[2] = &(parms[0]);
@@ -532,7 +533,6 @@
 			if(r != KErrNone)
 				return r;
 			prn = &(((TTrackNotifyBuf*)trackBuf)->iNotifyBlock);
-			new (prn) DPowerResourceNotification(&AsyncCallBackFn, (TAny*)trackBuf, iDfcQ, KResManCallBackPriority);
 			m.iArg[2] = (TAny*)prn;
 			break;
 			}
@@ -546,7 +546,6 @@
 			if(r != KErrNone)
 				return r;
 			prn = &(((TTrackNotifyBuf*)trackBuf)->iNotifyBlock);
-			new (prn) DPowerResourceNotification(&AsyncCallBackFn, (TAny*)trackBuf, iDfcQ, KResManCallBackPriority);
 			parms[2] = (TUint)prn;
 			break;
 			}
@@ -2020,9 +2019,7 @@
 		TTrackGetStateBuf* stateBuf = (TTrackGetStateBuf*)aBuffer;
 		stateBuf->iRequest->SetDestPtr1(aState);
 		stateBuf->iRequest->SetDestPtr2(aLevelOwnerPtr);
-		// Use placement new to update the content of the TPowerResourceCb
 		aCb = &(stateBuf->iCtrlBlock);
-		new (aCb) TPowerResourceCb(&AsyncCallBackFn,(TAny*)aBuffer,iDfcQ,KResManCallBackPriority);
 		}
 	return r;
 	}
@@ -2052,18 +2049,30 @@
 		}
 	Kern::Printf("iOwningChannel at 0x%x\n",aTracker->iOwningChannel);
 	Kern::Printf("iFreeQue at 0x%x\n",aTracker->iFreeQue);
+	
 	SDblQueLink* buf;
 	if(aTracker->iFreeQue!=NULL)
 		{
-		buf=aTracker->iFreeQue->First();
-		while(buf!=aTracker->iFreeQue->Last())
+		SDblQueLink* anchor = &(aTracker->iFreeQue->iA);
+		buf = anchor->iNext;
+		while(anchor != buf )
 			{
-			Kern::Printf("iFreeQue first buffer at 0x%x\n",buf);
+			Kern::Printf("iFreeQue buffer at 0x%x\n",buf);
 			TAny* intermediatePtr = (TAny*)buf;
-			if((aTracker->iType == EGetState)||(aTracker->iType == ESetState))
+			if(aTracker->iType == EGetState)
+				{
+				TTrackGetStateBuf* tempBuf =(TTrackGetStateBuf*)intermediatePtr;
+				Kern::Printf("TTrackGetStateBuf buffer control block at 0x%x\n",&(tempBuf->iCtrlBlock));
+				}
+			else if(aTracker->iType == ESetState)
 				{
 				TTrackSetStateBuf* tempBuf =(TTrackSetStateBuf*)intermediatePtr;
-				Kern::Printf("buffer control block at 0x%x\n",(TInt)&tempBuf->iCtrlBlock);
+				Kern::Printf("TTrackSetStateBuf buffer control block at 0x%x\n",&(tempBuf->iCtrlBlock));
+				}
+			else if(aTracker->iType == ENotify)
+				{
+				TTrackNotifyBuf* tempBuf =(TTrackNotifyBuf*)intermediatePtr;
+				Kern::Printf("TTrackNotifyBuf buffer notify block at 0x%x\n",&(tempBuf->iNotifyBlock));
 				}
 			buf = buf->iNext;
 			};
@@ -2071,15 +2080,26 @@
 	Kern::Printf("iBusyQue at 0x%x\n",aTracker->iBusyQue);
 	if(aTracker->iBusyQue!=NULL)
 		{
-		buf=aTracker->iBusyQue->First();
-		while(buf!=aTracker->iBusyQue->Last())
+		SDblQueLink* anchor = &(aTracker->iBusyQue->iA);
+		buf = anchor->iNext;
+		while(anchor != buf )
 			{
 			Kern::Printf("iBusyQue buffer at 0x%x\n",buf);
 			TAny* intermediatePtr = (TAny*)buf;
-			if((aTracker->iType == EGetState)||(aTracker->iType == ESetState))
+			if(aTracker->iType == EGetState)
+				{
+				TTrackGetStateBuf* tempBuf =(TTrackGetStateBuf*)intermediatePtr;
+				Kern::Printf("TTrackGetStateBuf buffer control block at 0x%x\n",&(tempBuf->iCtrlBlock));
+				}
+			else if(aTracker->iType == ESetState)
 				{
 				TTrackSetStateBuf* tempBuf =(TTrackSetStateBuf*)intermediatePtr;
-				Kern::Printf("buffer control block at 0x%x\n", (TInt)&tempBuf->iCtrlBlock);
+				Kern::Printf("TTrackSetStateBuf buffer control block at 0x%x\n",&(tempBuf->iCtrlBlock));
+				}
+			else if(aTracker->iType == ENotify)
+				{
+				TTrackNotifyBuf* tempBuf =(TTrackNotifyBuf*)intermediatePtr;
+				Kern::Printf("TTrackNotifyBuf buffer notify block at 0x%x\n",&(tempBuf->iNotifyBlock));
 				}
 			buf= buf->iNext;
 			};
@@ -2157,12 +2177,14 @@
 		if(r!=KErrNone)
 			{
 			SDblQueLink* ptr = (aTracker->iFreeQue)->First();
+			TTrackingBuffer *buf = NULL;
 			do
 				{
 				SDblQueLink* next = NULL;
 				if(ptr !=NULL)
 					next = ptr->iNext;
-				delete ptr;
+				buf = (TTrackingBuffer *)ptr;
+				DELETE_TRACKING_BUFFER(aTracker,buf)
 				ptr = next;
 				} while ((ptr!=NULL)&&(ptr!=(aTracker->iFreeQue)->Last()));
 			delete aTracker->iFreeQue;
--- a/kernel/eka/euser/epoc/up_dll_tls.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/euser/epoc/up_dll_tls.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -26,6 +26,11 @@
 /**
 Sets the value of the Thread Local Storage (TLS) variable.
 
+Note that the TLS value for a given DLL may be preserved even if the DLL has
+been unloaded from the current process and loaded again since it was set. The
+value is not guaranteed to be preserved. The DLL must take steps to ensure that
+Dll::FreeTls is called for all relevant threads if this must be avoided.
+
 @param aPtr       The value to be assigned to the Thread Local Storage variable.
                   In practice, this is almost always a pointer to memory
                   that has previously been allocated, but does not necessarily
@@ -49,6 +54,11 @@
 /**
 Gets the value of the Thread Local Storage (TLS) variable.
 
+Note that the TLS value for a given DLL may be preserved even if the DLL has
+been unloaded from the current process and loaded again since it was set. The
+value is not guaranteed to be preserved. The DLL must take steps to ensure that
+Dll::FreeTls is called for all relevant threads if this must be avoided.
+
 @return           The value of the Thread Local Storage variable as set by
                   a previous call to Dll::SetTls(). If no value has previously
                   been set, then the returned value is NULL.
--- a/kernel/eka/euser/us_time.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/euser/us_time.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -380,7 +380,10 @@
 
 YYYYMMDD:HHMMSS.MMMMMM
 
-If omitted, the first component is set to January 1st 0 AD nominal Gregorian. 
+If omitted, the first component defaults to 1 January, year 0 (nominal Gregorian).
+This is the base date for TTime, so the result of this method will be the number
+of microseconds in the time specified by the second and third components.
+
 If either the second or third components are omitted, they are set to zero.
 
 Notes:
@@ -1472,7 +1475,7 @@
 
 EXPORT_C TDay TTime::DayNoInWeek() const
 //
-// 1st January 0AD was a Monday
+// 1st January year 0 was a Monday
 //
 /**
 Gets the day number within the current week.
@@ -2480,8 +2483,8 @@
 
 EXPORT_C TBool Time::IsLeapYear(TInt aYear)
 //
-// up to and including 1600 leap years were every 4 years,since then leap years are every 4 years unless
-// the year falls on a century which is not divisible by 4 (ie 1900 wasnt,2000 will be)
+// up to and including 1600 leap years were every 4 years; since then leap years are every 4 years unless
+// the year falls on a century which is not divisible by 4 (i.e. 1900 wasn't, 2000 will be)
 // for simplicity define year 0 as a leap year
 //
 /**
@@ -2500,16 +2503,24 @@
 
 EXPORT_C TInt Time::LeapYearsUpTo(TInt aYear)
 //
-// from 0AD to present year according to the rule above
+// from year 0 to specified year according to the rule above
 //
 /**
-Gets the number of leap years between 0 AD nominal Gregorian and the specified 
-year - inclusive.
+Gets the number of leap years between year 0 (nominal Gregorian) and the specified 
+year, inclusive.
+
+The calendar used is nominal Gregorian with astronomical numbering (where
+year 2000 = 2000 AD, year 1600 = 1600 AD, year 1 = 1 AD, and so year 0 =
+1 BC, year -100 = 101 BC).  No days are removed from September 1752 or any
+other month.  Leap year calculation before 1600 uses the Julian method of
+every four years, even for years which are exactly divisible by 100 but not
+by 400.  Thus leap years include: 1200, 1300, 1400, 1500, 1600 and 2000;
+non-leap years include: 1601, 1700, 1800, 1900 and 2100.
 
 @param aYear The final year in the range to search. If negative, the function 
              will return a negative number of leap years.
 
-@return The number of leap years between 0 AD nominal Gregorian and aYear.
+@return The number of leap years between year 0 (nominal Gregorian) and aYear.
 */
 	{
 
@@ -2523,4 +2534,3 @@
 	num+=(aYear/4-century+century/4);
 	return(num);
 	}
-
--- a/kernel/eka/include/drivers/mmc.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/include/drivers/mmc.h	Mon Oct 18 15:31:10 2010 +0100
@@ -2286,6 +2286,7 @@
 const TUint32 KMMCCmdFlagReliableWrite=	KBit9;  // Current command is Reliable Write
 const TUint32 KMMCCmdFlagDeleteNotify=  KBit10; // Current command is Delete Notify
 const TUint32 KMMCCmdFlagRpmbIO=        KBit11; // Current command is of RPMB type
+const TUint32 KMMCCmdFlagIgnoreStatus=  KBit12; // Ignore card status from response
 
 const TUint32 KMMCCmdFlagASSPFlags=	KMMCCmdFlagBytesValid	|
 									KMMCCmdFlagTransStopped	|
--- a/kernel/eka/include/e32hal.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/include/e32hal.h	Mon Oct 18 15:31:10 2010 +0100
@@ -216,7 +216,7 @@
 	TInt iProximityStep;    /**<proximity resolution, e.g. proximity readings change in steps of 1, 5, 10, ... */
 	TInt iMaxPressure;      /**< maximum pressure reading*/
 	TInt iPressureStep;     /**< pressure resolution, */	
-	TUint8 iMaxPointers;    /**< max number of multi-touch pointers supported by hardware/driver.*/ 
+	TUint8 iMaxPointers;    /**< max number of multipletouch pointers supported by hardware/driver.*/ 
 	TUint8 iNumberOfPointers;/**< Number of pointers it supports (settable).*/
 	};
 
--- a/kernel/eka/include/e32std.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/include/e32std.h	Mon Oct 18 15:31:10 2010 +0100
@@ -1758,18 +1758,26 @@
 
 Stores and manipulates the date and time. 
 
-It represents a date and time as a number of microseconds since midnight, 
-January 1st, 1 AD nominal Gregorian. BC dates are represented by negative 
-TTime values. A TTime object may be constructed from a TInt64, a TDateTime 
-a string literal, or by default, which initialises the time to an arbitrary 
-value. To access human-readable time information, the TTime may be converted 
-from a TInt64 into a TDateTime, which represents the date and time as seven 
-numeric fields and provides functions to extract these fields. Alternatively, 
-to display the time as text, the time may be formatted and placed into a
-descriptor using a variety of formatting commands and which may or may not
-honour the system's locale settings. The conversion between time and text may
-be performed the other way around, so that a descriptor can be parsed and
-converted into a TTime value.
+It represents a date and time as a number of microseconds since midnight
+at the beginning of 1 January, year 0 (using astronomical numbering, where
+year 2000 = 2000 AD, year 1600 = 1600 AD, year 1 = 1 AD, and so year 0 =
+1 BC, year -100 = 101 BC, etc).  The calendar used is nominal Gregorian, so
+no days are removed from September 1752 or any other month, but leap year
+calculations before 1600 use the Julian method of every four years, even
+for years which are exactly divisible by 100 but not by 400.  Thus leap
+years include: 1200, 1300, 1400, 1500, 1600 and 2000; non-leap years
+include: 1601, 1700, 1800, 1900 and 2100.
+
+A TTime object may be constructed from a TInt64, a TDateTime, a string literal,
+or by default, which initialises the time to an arbitrary value. To access
+human-readable time information, the TTime may be converted from a TInt64
+into a TDateTime, which represents the date and time as seven numeric fields
+and provides functions to extract these fields. Alternatively, to display the
+time as text, the time may be formatted and placed into a descriptor using a
+variety of formatting commands and which may or may not honour the system's
+locale settings. The conversion between time and text may be performed the
+other way around, so that a descriptor can be parsed and converted into a
+TTime value.
 
 In addition to setting and getting the date and time and converting between 
 text and time, TTime provides functions to get intervals between times and 
--- a/kernel/eka/include/e32ver.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/include/e32ver.h	Mon Oct 18 15:31:10 2010 +0100
@@ -28,7 +28,7 @@
 
 const TInt KE32MajorVersionNumber=2;
 const TInt KE32MinorVersionNumber=0;
-const TInt KE32BuildVersionNumber=4010;
+const TInt KE32BuildVersionNumber=4011;
 
 const TInt KMachineConfigurationMajorVersionNumber=1;
 const TInt KMachineConfigurationMinorVersionNumber=0;
--- a/kernel/eka/include/kernel/crash_gzip.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/include/kernel/crash_gzip.h	Mon Oct 18 15:31:10 2010 +0100
@@ -118,9 +118,11 @@
 */							
 const TInt KCrashGzipOutBufSize = 128;
 
-/** Number of seconds elapsed between 01/01/0000 AD and 01/01/1970 AD.
+/** Number of seconds elapsed between 01/01/0000 and 01/01/1970.
     Value is the number of days multiplied by the number of seconds per day:
     719540 * 86400
+
+    @see TTime
  */
 const TInt64 KYear1970ADInSeconds = I64LIT(62168256000);
 
--- a/kernel/eka/kernel/smonitor.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/kernel/smonitor.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -835,7 +835,7 @@
 /**
 Time of system crash.
 
-@return Time of crash in seconds since 0AD, or zero if crash time un-available.
+@return Time of crash in seconds since year 0 (nominal Gregorian), or zero if crash time un-available.
 */
 EXPORT_C TInt64 CrashTime()
 	{
--- a/kernel/eka/kernel/smonlog.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/kernel/smonlog.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -26,7 +26,7 @@
 
 const TInt KRestartType = CrashLogger::ESoftRestart;
 
-/** Number of seconds elapsed between 01/01/0000 AD and 01/01/2000 AD.
+/** Number of seconds elapsed between 01/01/0000 and 01/01/2000.
     Value is the number of days multiplied by the number of seconds per day:
     730497 * 86400
  */
@@ -321,7 +321,7 @@
 
 void CrashLogger::DumpCrashTime()
 	{                   
-	// We want time from 2000AD when SystemTime starts from 0AD hence the adjustment.
+	// We want time from 2000AD when SystemTime starts from year 0 hence the adjustment.
 	TTimeK secsSince0AD = CrashTime();
 
     if(!secsSince0AD)
--- a/kernel/eka/kernel/stimer.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/kernel/stimer.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -1524,7 +1524,7 @@
 /**
 	Gets the current system time.
 
-	@return The current time as the number of microseconds since midnight, January 1st, 0 AD nominal Gregorian.
+	@return The current time as the number of microseconds since midnight, January 1st, year 0 (nominal Gregorian).
 */
 	{
 	TTimeK r = Kern::SystemTime();
@@ -1555,7 +1555,7 @@
 /**
 	Gets the current nonsecure (user-settable) system time.
 
-	@return The current time as the number of microseconds since midnight, January 1st, 0 AD nominal Gregorian.
+	@return The current time as the number of microseconds since midnight, January 1st, year 0 (nominal Gregorian).
 */
 	{
 	TTickQ& q=*K::TickQ;
--- a/kernel/eka/memmodel/epoc/flexible/mmu/mmu.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/memmodel/epoc/flexible/mmu/mmu.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -297,7 +297,7 @@
 	iTempPteCacheMaintenance = BlankPte((TMemoryAttributes)(CacheMaintenance::TemporaryMapping()|EMemoryAttributeDefaultShareable),pteType);
 	
 	// other
-	PP::MaxUserThreadStack=0x14000;			// 80K - STDLIB asks for 64K for PosixServer!!!!
+	PP::MaxUserThreadStack=0x100000;		// 1Mb - STDLIB asks for 64K for PosixServer!!!!
 	PP::UserThreadStackGuard=0x2000;		// 8K
 	PP::MaxStackSpacePerProcess=0x200000;	// 2Mb
 	K::SupervisorThreadStackSize=0x1000;	// 4K
--- a/kernel/eka/release.txt	Wed Oct 13 13:34:03 2010 +0100
+++ b/kernel/eka/release.txt	Mon Oct 18 15:31:10 2010 +0100
@@ -1,4 +1,45 @@
-Version 2.00.4009
+Version 2.00.4011
+=================
+(Made by fadhliM 15/10/2010)
+
+1.	stmansfi
+	1.	ou1cimx1#594006 ENV t_hcrut test faults and t_hcr fails on Bridge
+
+2.	ahiron
+	1.	ou1cimx1#604699 TDfc usage in Resmanus and IIC
+	2.	ou1cimx1#607313 SPB10.1 Coverity Prevent defects, Mandatory Checkers
+
+3.	dlyokhin
+	1.	ou1cimx1#602572 SD stack should correctly support SD cards larger than 32GB
+
+4.	lanerobe
+	1.	ou1cimx1#600014 LOADER T_LDRTST should explicitly use bytepair for exet110 and exet111
+
+5.	jcoppear
+	1.	ou1cimx1#609854 SIROCCO - Vasco - t_shadow faults
+
+6.	tocosgro
+	1.	ou1cimx1#600880 TTime class, base year wrong
+
+7.	fagortz
+	1.	ou1cimx1#606677 Linux build problem with kernelhwsrv
+	2.	ou1cimx1#604084 ENV Automounter is referenced in both SF and Nokia packages
+	3.	ou1cimx1#614366 8GB SD card does not mount properly
+
+8.	jessiezh
+	1.	ou1cimx1#600789 MCL MaxUserThreadStack size must be increased from 80KB to 1MB 
+
+9.	kmetherm
+	1.	ou1cimx1#587561 MCL The term 'Multi-Touch' must be removed from all KHS documentation including doxygen comments
+
+10.	davegord
+	1.	ou1cimx1#598182 ENV T_TLDD requires building invalid LDD which Raptor does not support
+
+11.	ricoles
+	1.	ou1cimx1#611968 [mcl] Update Dll::Tls API doc to describe what happens on DLL unload/reload
+
+
+Version 2.00.4010
 =================
 (Made by fadhliM 11/10/2010)
 
@@ -3323,7 +3364,7 @@
 (Made by GeorgeSin 08/04/2009)
 
 1.	Archana H
-	1.	DEFECT FIX: DEF137353: Emulator multitouch support broken on Win2K 
+	1.	DEFECT FIX: DEF137353: Emulator multipletouch support broken on Win2K 
 	
 2.	MiguelB
 	1.	DEFECT FIX: DEF136839: NAND media driver doesn't cancel garbage collection DFC 
@@ -3448,7 +3489,7 @@
 	3.	MINOR_CHANGE: Fix incorrect interrupt enable/disable sequence for the naviengine GCE driver plus offset fix.
 
 2.	kelly li
-	1.	MILESTONE: Ermine, GT0488, MS3.1, DS1448, PREQ2338: Base: Emulator support for multi-touch, pressure & proximity
+	1.	MILESTONE: Ermine, GT0488, MS3.1, DS1448, PREQ2338: Base: Emulator support for multipletouch, pressure & proximity
 	
 3.	Gavin Cochrane
 	1.	DEFECT FIX: PDEF135653: Lumiere20.024_Memory: Phone resets automatically after RAM low(2000~3000kb). 
--- a/kerneltest/e32test/digitiser/d_ldddigitisertest.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/digitiser/d_ldddigitisertest.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -69,7 +69,7 @@
 //	TInt iProximityStep;    	/**<proximity resolution, e.g. proximity readings change in steps of 1, 5, 10, ... */
 //	TInt iMaxPressure;      	/**< maximum pressure reading*/
 //	TInt iPressureStep;     	/**< pressure resolution, */	
-//	TUint8 iMaxPointers;    	/**< max number of multi-touch pointers supported by hardware/driver.*/ 
+//	TUint8 iMaxPointers;    	/**< max number of multipletouch pointers supported by hardware/driver.*/ 
 //	TUint8 iNumberOfPointers;	/**< Number of pointers it supports (settable).*/
 //	};
 
--- a/kerneltest/e32test/group/romstuff.mke	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/group/romstuff.mke	Mon Oct 18 15:31:10 2010 +0100
@@ -37,5 +37,5 @@
 	@echo data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos_bc0.dat sys\data\filerepos_bc0.dat	unpaged paging_unmovable
 	@echo data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos_bc1.dat sys\data\filerepos_bc1.dat	unpaged paging_unmovable
 	@echo data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos_cds.dat sys\data\filerepos_cds.dat  unpaged paging_unmovable
-	@echo hcrdata=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos.dat  sys\data\hcr.dat
+	@echo data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos.dat     sys\data\test_hcr.dat		unpaged paging_unmovable
 #endif
--- a/kerneltest/e32test/hcr/d_hcrext_client.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrext_client.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -16,6 +16,7 @@
 
 macro HCRTEST_USERSIDE_INTERFACE
 macro HCRTEST_CLIENT_THREAD
+macro HCRTEST_AVOID_BSP_HCR_DAT
 #include		<variant_test.mmh>
 #include		"kernel/kern_ext.mmh"
 
--- a/kerneltest/e32test/hcr/d_hcrext_own.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrext_own.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -15,6 +15,7 @@
 //
 
 macro HCRTEST_USERSIDE_INTERFACE
+macro HCRTEST_AVOID_BSP_HCR_DAT
 #include		<variant_test.mmh>
 #include		"kernel/kern_ext.mmh"
 
--- a/kerneltest/e32test/hcr/d_hcrsim.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrsim.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 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"
@@ -154,9 +154,12 @@
 		}											\
 	}
 
+// Invoke some non-fatal calls on the real HCR.dll in the BSP to show
+// a kernel extension can use the HCR API early in boot.
 void KextInitTests()
 	{
 	TInt r;
+	
 	// Get last Setting in Reference Compiled Repository
 	TUint32 value1;
 	TSettingId setting1(0xFFFFFFFF, 0xFFFFFFFF);
@@ -164,88 +167,8 @@
 	KEXT_TESTKERRNONE(r);
 	KEXT_TEST(value1==0x4C415354); // 'L', 'A', 'S', 'T'
 
-	// Determine what test repositories the HCR has loaded
-	// Make sure we have the file repository
-	const TRomHeader& romheader = Epoc::RomHeader();
-	KEXT_TEST(romheader.iHcrFileAddress != NULL); // Assuming this is the test repository (hcr.dat)
-	// Find the nand repository
-	TBool smr;
-	TBool smrrep;
-	SSettingC* repos = NULL;
-	TInt nosettings = 0;
-	HasRepositoryInSmr(smr, smrrep);
-	if (smrrep)
-		{
-		repos = SettingsList6; // File+Nand
-		nosettings = sizeof(SettingsList6) / sizeof(SSettingC);
-		}
-	else if (!smr)
-		{
-		repos = SettingsList7; // File Only
-		nosettings = sizeof(SettingsList7) / sizeof(SSettingC);
-		}
-	else
-		{
-		// SMR partitions found but no HCR repository
-		KEXT_TEST(0);
-		return;
-		}
-
-	// Simple word setting Get
-	for (SSettingC* setting = repos; setting < repos + nosettings; setting++)
-		{
-// Note: these macros are irrelevant here, it is just so the two test kernel
-// extensions do something different
-#ifdef HCRTEST_CLIENT_THREAD
-		if (setting->iName.iType == ETypeInt32)
-			{
-			TSettingId id(setting->iName.iId.iCat, setting->iName.iId.iKey);
-			TInt32 val;
-			r = GetInt(id, val);
-			KEXT_TESTKERRNONE(r);
-			KEXT_TEST(setting->iValue.iLit.iInt32 == val);
-			}
-#else // !HCRTEST_CLIENT_THREAD
-		if (setting->iName.iType == ETypeUInt32)
-			{
-			TSettingId id(setting->iName.iId.iCat, setting->iName.iId.iKey);
-			TUint32 val;
-			r = GetUInt(id, val);
-			KEXT_TESTKERRNONE(r);
-			KEXT_TEST(setting->iValue.iLit.iUInt32 == val);
-			}
-#endif // !HCRTEST_CLIENT_THREAD
-		}
-
-	// Large setting Get
-	for (SSettingC* setting = repos; setting < repos + nosettings; setting++)
-		{
-// Note: these macros are irrelevant here, it is just so the two test kernel
-// extensions do something different
-#ifdef HCRTEST_CLIENT_THREAD
-		if (setting->iName.iType == ETypeBinData)
-			{
-			TSettingId id(setting->iName.iId.iCat, setting->iName.iId.iKey);
-			TBuf8<KMaxSettingLength> val;
-			TPtrC8 aval(setting->iValue.iPtr.iData, setting->iName.iLen);
-			r = GetData(id, val);
-			KEXT_TESTKERRNONE(r);
-			KEXT_TEST(0 == val.Compare(aval));
-			}
-#else // !HCRTEST_CLIENT_THREAD
-		if (setting->iName.iType == ETypeText8)
-			{
-			TSettingId id(setting->iName.iId.iCat, setting->iName.iId.iKey);
-			TBuf8<KMaxSettingLength> val;
-			TPtrC8 aval(setting->iValue.iPtr.iString8, setting->iName.iLen);
-			r = GetString(id, val);
-			KEXT_TESTKERRNONE(r);
-			KEXT_TEST(0 == val.Compare(aval));
-			}
-#endif // !HCRTEST_CLIENT_THREAD
-		}
-
-	// Some other API calls
+	// Check number of settings in some test categories.
+	// Most likely these categories are not used in the real HCR.dll
 	TUint i;
 	for (i = 0; i < sizeof(KTestCategories) / sizeof(TCategoryUid); i++)
 		{
@@ -296,6 +219,9 @@
 	r = Kern::DynamicDfcQCreate(iDfcQ, KHcrSimTestThreadPriority, KHcrSimTestThread);
 	if (r != KErrNone)
 		return r;
+	// Allow this test DFCQ thread to take page faults should it happen rather
+	// than let the Kernel panic it with 2,61 KERN-EXEC.
+	iDfcQ->SetRealtimeState(ERealtimeStateOff);
 #ifdef HCRTEST_USERSIDE_INTERFACE
 	r = SetName(&KTestHcrRealOwn);
 #else
--- a/kerneltest/e32test/hcr/d_hcrsim_client.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrsim_client.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -14,8 +14,19 @@
 // Hardware Configuration Respoitory Tests
 //
 
+// Defined when the HCR API must not be exported e.g. when compiled
+// into a test driver.
 macro HCRTEST_NO_EXPORT
-macro HCRTEST_CLIENT_THREAD
+
+// No DFCQ thread when this is defined, test cases execute in user-side
+// test application thread context
+macro HCRTEST_CLIENT_THREAD 
+
+// Defined to ensure PIL does not make use of production HCR.DAT in core 
+// image when under test.
+macro HCRTEST_AVOID_BSP_HCR_DAT
+
+// Define this to increase amount of trace output from HCR code.
 //macro HCR_TRACE
 
 #define HCRTEST_TEST_MMP
--- a/kerneltest/e32test/hcr/d_hcrsim_own.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrsim_own.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -14,7 +14,19 @@
 // Hardware Configuration Respoitory Tests
 //
 
+// Defined when the HCR API must not be exported e.g. when compiled
+// into a test driver.
 macro HCRTEST_NO_EXPORT
+
+// No DFCQ thread when this is defined, test cases execute in user-side
+// test application thread context
+//macro HCRTEST_CLIENT_THREAD 
+
+// Defined to ensure PIL does not make use of production HCR.DAT in core 
+// image when under test.
+macro HCRTEST_AVOID_BSP_HCR_DAT
+
+// Define this to increase amount of trace output from HCR code.
 //macro HCR_TRACE
 
 #define HCRTEST_TEST_MMP
--- a/kerneltest/e32test/hcr/d_hcrsim_testdata.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrsim_testdata.h	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -258,7 +258,7 @@
 	{{{ KTestCategories[0], 1}, ETypeInt32, 0x0000, 0 }, {{ 0 }}},
 	{{{ KTestCategories[0], 2}, ETypeInt32, 0x0000, 0 }, {{ 0 }}},
 	};
-#if !defined(__KERNEL_MODE__) || defined(HCRTEST_USERSIDE_INTERFACE)
+#if !defined(__KERNEL_MODE__) 
 const TUint32 KTestInvalidCategory = 0;
 const TUint32 KTestInvalidSettingId = 5678;
 
@@ -670,5 +670,5 @@
 	{{{ KTestCategories[5], 0x00d0}, ETypeUInt64, 0x0000, sizeof(TUint64) }, {{ reinterpret_cast<TInt32>(&KTestU64Three) }}},
 	{{{ KTestCategories[5], 0xffffffff}, ETypeInt8, 0x0000, 0 }, {{ 1 }}},
 	};
-#endif // !defined(__KERNEL_MODE__) || defined(HCRTEST_USERSIDE_INTERFACE)
+#endif // !defined(__KERNEL_MODE__) 
 #endif // !D_HCRSIM_TESTDATA_H
--- a/kerneltest/e32test/hcr/d_hcrut.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrut.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -535,11 +535,13 @@
     case RHcrTest::ECtrlSwitchFileRepository:
 	    {
 	    TInt r;
-	    TAny* args[2];
+	    TAny* args[2];	// args[1] length includes null terminating char
 	    TEST_MEMGET(a1, args, sizeof(args));
-	    const TText* fileRepName = (TText*) args[0];
 	    
-	    r = gObserver.SwitchRepository(fileRepName, HCR::HCRInternal::ECoreRepos);
+	    TBuf8<MAX_FILENAME_LEN> fileName;
+	    TEST_MEMGET(args[0], (TAny*)fileName.Ptr(), ((TInt)args[1])); 
+	    
+	    r = gObserver.SwitchRepository(fileName.Ptr(), HCR::HCRInternal::ECoreRepos);
 	    if (r != KErrNone)
 	        {
 	        HCR_TRACE_RETURN(r);
--- a/kerneltest/e32test/hcr/d_hcrut.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrut.h	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -25,6 +25,8 @@
 #include <e32std.h>
 #endif
 
+#define MAX_FILENAME_LEN 64
+
 
 /**
 Interface to the fast-trace memory buffer.
@@ -77,10 +79,14 @@
 	    return DoControl(ECtrlFileFindSettingsInCategory, (TAny*)args);
 	    }
 	
-	inline TUint Test_SwitchFileRepository(const TText* aRepName)
+	// aNameLen includes the null terminator
+	inline TUint Test_SwitchFileRepository(const TText8* aRepName, TInt aNameLen)
 	    {
-	    TAny* args[1];
+	    __ASSERT_ALWAYS((aNameLen<MAX_FILENAME_LEN),User::Panic(_L("d_hcrut.h"), __LINE__));
+	    
+	    TAny* args[2];
 	    args[0] = (TAny*) aRepName;
+	    args[1] = (TAny*) aNameLen;
 	    return DoControl(ECtrlSwitchFileRepository, (TAny*)args);
 	    }
 		
--- a/kerneltest/e32test/hcr/d_hcrut.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/d_hcrut.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -16,6 +16,7 @@
 
 macro HCRTEST_NO_EXPORT
 macro HCRTEST_NO_KEXT_ENTRY_POINT
+macro HCRTEST_AVOID_BSP_HCR_DAT
 // Uncomment for debug trace
 // macro HCR_TRACE
 #define HCRTEST_TEST_MMP
--- a/kerneltest/e32test/hcr/hcr.inf	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/hcr.inf	Mon Oct 18 15:31:10 2010 +0100
@@ -56,7 +56,7 @@
 empty.dat             /epoc32/release/wins/udeb/z/sys/data/empty.dat
 megalarge1.dat        /epoc32/release/wins/udeb/z/sys/data/megalarge1.dat
 megalarge2.dat        /epoc32/release/wins/udeb/z/sys/data/megalarge2.dat
-filerepos.dat         /epoc32/release/wins/udeb/z/sys/data/hcr.dat
+filerepos.dat         /epoc32/release/wins/udeb/z/sys/data/test_hcr.dat
 
 
 filerepos_cds.dat     /epoc32/release/wins/urel/z/sys/data/filerepos_cds.dat
@@ -69,7 +69,7 @@
 empty.dat             /epoc32/release/wins/urel/z/sys/data/empty.dat
 megalarge1.dat        /epoc32/release/wins/urel/z/sys/data/megalarge1.dat
 megalarge2.dat        /epoc32/release/wins/urel/z/sys/data/megalarge2.dat
-filerepos.dat         /epoc32/release/wins/urel/z/sys/data/hcr.dat
+filerepos.dat         /epoc32/release/wins/urel/z/sys/data/test_hcr.dat
 
 
 filerepos_cds.dat     /epoc32/release/winscw/udeb/z/sys/data/filerepos_cds.dat
@@ -82,7 +82,7 @@
 empty.dat             /epoc32/release/winscw/udeb/z/sys/data/empty.dat
 megalarge1.dat        /epoc32/release/winscw/udeb/z/sys/data/megalarge1.dat
 megalarge2.dat        /epoc32/release/winscw/udeb/z/sys/data/megalarge2.dat
-filerepos.dat         /epoc32/release/winscw/udeb/z/sys/data/hcr.dat
+filerepos.dat         /epoc32/release/winscw/udeb/z/sys/data/test_hcr.dat
 
 
 filerepos_cds.dat     /epoc32/release/winscw/urel/z/sys/data/filerepos_cds.dat
@@ -95,7 +95,7 @@
 empty.dat             /epoc32/release/winscw/urel/z/sys/data/empty.dat
 megalarge1.dat        /epoc32/release/winscw/urel/z/sys/data/megalarge1.dat
 megalarge2.dat        /epoc32/release/winscw/urel/z/sys/data/megalarge2.dat
-filerepos.dat         /epoc32/release/winscw/urel/z/sys/data/hcr.dat
+filerepos.dat         /epoc32/release/winscw/urel/z/sys/data/test_hcr.dat
 
 PRJ_TESTMMPFILES
 
--- a/kerneltest/e32test/hcr/hcr_tests.iby	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/hcr_tests.iby	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -45,5 +45,5 @@
 data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos_bc0.dat     \sys\data\filerepos_bc0.dat   unpaged paging_unmovable
 data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos_bc1.dat     \sys\data\filerepos_bc1.dat   unpaged paging_unmovable
 data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos_cds.dat     \sys\data\filerepos_cds.dat   unpaged paging_unmovable
-hcrdata=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos.dat  \sys\data\hcr.dat
+data=##BASEPATH##kernelhwsrv\kerneltest\e32test\hcr\filerepos.dat  		\sys\data\test_hcr.dat 			unpaged paging_unmovable
 #endif // __HCR_TEST_IBY__
--- a/kerneltest/e32test/hcr/t_hcr.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/t_hcr.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -2091,7 +2091,7 @@
 	test.Next(_L("Reload Device Driver"));
 	HcrSimTest.Close();
 	r = User::FreeLogicalDevice(aDriver);
-	test_KErrNone(r);
+    test_KErrNone(r);
 	r = User::LoadLogicalDevice(aDriver);
 	test_KErrNone(r);
 	r = HcrSimTest.Open(aDriver);
@@ -2322,12 +2322,11 @@
 	{
 	test.Next(_L("Rom Header"));
 #ifdef __WINS__
-	test.Printf(_L("Not available on the emulator.\n"));
+	test.Printf(_L("HCR Core Image DAT File not available on the emulator.\n"));
 #else
 	const TRomHeader* romheader = (TRomHeader*) UserSvr::RomHeaderAddress();
-	test.Printf(_L("HCR File Address: %08x\n"), romheader->iHcrFileAddress);
-	test(romheader->iHcrFileAddress);
-	if (romheader->iPageableRomStart)
+	test.Printf(_L("HCR Core Image DAT File Address: %08x\n"), romheader->iHcrFileAddress);
+	if (romheader->iHcrFileAddress && romheader->iPageableRomStart)
 		{
 		// If this is a paged ROM, HCR file must be in the unpaged area
 		test_Compare(romheader->iRomBase + romheader->iPageableRomStart, >, romheader->iHcrFileAddress);
@@ -2337,8 +2336,9 @@
 
 void HcrRealSettingDiscovery()
 	{
-	test.Next(_L("Setting Discovery"));
+	test.Next(_L("BSP HCR.dll Test Setting Discovery"));
 	TInt r;
+	TBool anyFound = EFalse;
 	TCategoryUid cat;
 	test.Printf(_L("Category Element  Type     Len  Value\n"));
 	test.Printf(_L("--------------------------------------------------\n"));
@@ -2349,6 +2349,7 @@
 		test_Compare(0, <=, nosettings);
 		if (nosettings > 0)
 			{
+			anyFound = ETrue;
 			TElementId* elids;
 			TSettingType* types;
 			TUint16* lens;
@@ -2551,6 +2552,11 @@
 			User::Free(lens);
 			}
 		}
+	if (anyFound == EFalse)
+		{
+		test.Printf(_L("No TEST settings found in BSP HCR.dll\n"));
+		}
+	test.Printf(_L("--------------------------------------------------\n"));	
 	}
 void HcrRealRetrieveKernelExtensionTestResults()
 	{
@@ -2598,33 +2604,14 @@
 		test_KErrNone(r);
 		r = HcrSimTest.Open(aDriver);
 		test_KErrNone(r);
-		//
+		
+		// Check the BSP specific HCR-using test kernel extensions were
+		// able to retrieve HCR settings during kernel initialisation.
 		HcrRealRetrieveKernelExtensionTestResults();
+		// Discovery of settings, may not print any if repositories for BSP
+		// do not contain any test settings.
 		HcrRealSettingDiscovery();
 
-		// Initialize static variable with the right HCR client type
-		if(aDriver.Compare(KTestHcrRealOwn) == 0)
-			gHcrThread = KSimOwnThread;
-		else if(aDriver.Compare(KTestHcrRealClient) == 0)
-			gHcrThread = KSimClientThread;
-		else
-			test(EFalse);
-		//
-		TBool smr;
-		TBool smrrep;
-		r = HcrSimTest.HasRepositoryInSmr(smr, smrrep);
-		test_KErrNone(r);
-		if (smrrep)
-			{
-			// File + NAND
-			HcrSimTestApiTests(SettingsList6, sizeof(SettingsList6) / sizeof(SSettingC));
-			}
-		else
-			{
-			// File
-			HcrSimTestApiTests(SettingsList7, sizeof(SettingsList7) / sizeof(SSettingC));
-			}
-		//
 		test.Next(_L("Close LDD"));
 		HcrSimTest.Close();
 		r = User::FreeLogicalDevice(aDriver);
@@ -2635,9 +2622,6 @@
 
 void HcrCatRecodsExampleTest(const TDesC& aDriver)
     {
-    using namespace HCR;
-
-   
     test.Start(_L("HCR Record Structured Category Test"));
     test.Next(_L("Load HCR Test driver"));
     
--- a/kerneltest/e32test/hcr/t_hcrut.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/hcr/t_hcrut.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -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"
@@ -56,8 +56,9 @@
     test_Equal((lastEl - firstEl + 1), NumInTestCat);
 
     // Load file repository data for the boundary test condition
-    const TText * fileBc0 = (const TText *)"filerepos_bc0.dat";
-    test_KErrNone(HcrTest.Test_SwitchFileRepository(fileBc0));
+    const TText8 * fileBc0 = (const TText8 *)"filerepos_bc0.dat";
+	TInt len0 = sizeof("filerepos_bc0.dat");
+	test_KErrNone(HcrTest.Test_SwitchFileRepository(fileBc0, len0));
 
     // Test the low end boundary conditions in the file repository.
     // First element in the category is also the first element in the
@@ -82,8 +83,9 @@
 
 
     //Load relevant coreImg repository
-    const TText * fileBc1 = (const TText *)"filerepos_bc1.dat";
-    test_KErrNone(HcrTest.Test_SwitchFileRepository(fileBc1));
+    const TText8 * fileBc1 = (const TText8 *)"filerepos_bc1.dat";
+	TInt len1 = sizeof("filerepos_bc1.dat");
+    test_KErrNone(HcrTest.Test_SwitchFileRepository(fileBc1, len1));
 
 
     //Test the low end boundary condition when first element of the 
--- a/kerneltest/e32test/mmu/d_shadow.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/mmu/d_shadow.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -36,6 +36,10 @@
 const TUint KMaxNumberOfPageDirectories = 256;
 #endif
 
+// A buffer used to test shadowing of unpaged ROM.  It is two pages in size so that it will always
+// contain at least one memory page.
+const TUint8 UnpagedMemory[8192] = { 1 };
+
 class DShadow;
 
 class DShadowFactory : public DLogicalDevice
@@ -395,7 +399,10 @@
 			
 			break;	
 			}
-			
+
+		case RShadow::EControlGetUnpagedPage:
+			return _ALIGN_UP((TLinAddr)UnpagedMemory, pageSize);
+
 		default:
 			r=KErrNotSupported;
 			break;
--- a/kerneltest/e32test/mmu/d_shadow.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/mmu/d_shadow.h	Mon Oct 18 15:31:10 2010 +0100
@@ -71,7 +71,8 @@
 		EControlClaimPhys,
 		EControlGetMemoryArchitecture,
 		EControlGetMemModelInfo,
-		EControlGetPdInfo		
+		EControlGetPdInfo,
+		EControlGetUnpagedPage,
 		};
 		
 public:
@@ -94,6 +95,7 @@
 	inline void GetMemoryArchitecture(TCpu &aCpu, TUint &aCR);
 	inline TMemModel GetMemModelInfo(TUint &aPageTable, TUint &aNumPds);
 	inline TInt GetPdInfo(TUint aPdNo, TUint &aPdSize, TUint &aPdBase, TUint &aOffset);
+	inline TLinAddr GetUnpagedPage();
 	};
 
 
@@ -161,7 +163,10 @@
 	aOffset =  ret & KPageOffsetMask;
 	return (ret & KErrNoPageTable)?KErrNotFound:KErrNone;
 	}
-	
+
+inline TLinAddr RShadow::GetUnpagedPage()
+	{ return DoControl(EControlGetUnpagedPage, NULL, NULL); }
+
 #endif
 
 #endif
--- a/kerneltest/e32test/mmu/t_shadow.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/mmu/t_shadow.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -78,7 +78,11 @@
 TUint8* PageBuffer2 = NULL;
 TUint8* PageBuffer3 = NULL;
 
-void TestShadowPage(TLinAddr aPageAddr, TPaged aPageType)
+// A buffer used to test shadowing of paged ROM.  It is two pages in size so that it will always
+// contain at least one memory page.
+const TUint8 RomToShadow[8192] = { 1 };
+
+void TestShadowPage(TLinAddr aPageAddr, TPaged aPageType, TBool aCanModify)
 	{
 	test.Start(_L("Test shadowing a page"));	
 	test.Printf(_L("  addr == 0x%08x, type == %d\n"), aPageAddr, aPageType);
@@ -130,16 +134,19 @@
 	test.Next(_L("Check page following shadow page is unaltered"));
 	test_Equal(0, Mem::Compare((TUint8*)(secondPage),PageSize,PageBuffer3,PageSize));
 
-	test.Next(_L("Write data into shadow page"));
-	for(TInt i=0; i<PageSize; i++)
+	if (aCanModify)
 		{
-		TInt i2=i*i;
-		PageBuffer2[i]=TUint8(i2^(i2>>8)^(i2>>16));
+		test.Next(_L("Write data into shadow page"));
+		for(TInt i=0; i<PageSize; i++)
+			{
+			TInt i2=i*i;
+			PageBuffer2[i]=TUint8(i2^(i2>>8)^(i2>>16));
+			}
+		test_KErrNone(Shadow.Write(aPageAddr,PageBuffer2));
+
+		test.Next(_L("Check data written into shadow page"));
+		test_Equal(0, Mem::Compare((TUint8*)aPageAddr,PageSize,PageBuffer2,PageSize));
 		}
-	test_KErrNone(Shadow.Write(aPageAddr,PageBuffer2));
-
-	test.Next(_L("Check data written into shadow page"));
-	test_Equal(0, Mem::Compare((TUint8*)aPageAddr,PageSize,PageBuffer2,PageSize));
 	
 	test.Next(_L("Check page following shadow page is unaltered"));
 	test_Equal(0, Mem::Compare((TUint8*)(secondPage),PageSize,PageBuffer3,PageSize));
@@ -460,6 +467,18 @@
 	User::Free(PageBuffer3);
 	}
 
+static TLinAddr PageToShadow(TBool aPaged)
+	{
+	if (aPaged)
+		{
+		test(RomPagingSupported);
+		test(sizeof(RomToShadow) >= ((TUint)(2 * PageSize)));
+		return _ALIGN_UP((TLinAddr)RomToShadow, PageSize);
+		}
+	else
+		return Shadow.GetUnpagedPage();
+	}
+
 GLDEF_C TInt E32Main()
 //
 // Test ROM shadowing
@@ -484,22 +503,28 @@
 	test.Start(_L("Testing ROM shadowing"));
 	Initialise();
 
-	TestRomIsSectionMapped(); 
+	TestRomIsSectionMapped();
 
-	TestShadowPage(RomUnpagedStart, EUnpaged);
-	TestShadowPage(RomUnpagedStart + PageSize, EUnpaged);
-	TestShadowPage(RomUnpagedEnd - PageSize, EUnpaged);
-	TestNoFreeRAM(RomUnpagedStart);
-	TestShadowPageOOM(RomUnpagedStart);
+	TLinAddr unpagedPage = PageToShadow(EFalse);
+	
+	TestShadowPage(unpagedPage,              EUnpaged, ETrue);
+	TestShadowPage(RomUnpagedStart,          EUnpaged, EFalse);
+	TestShadowPage(RomUnpagedEnd - PageSize, EUnpaged, EFalse);
+	
+	TestNoFreeRAM(unpagedPage);
+	TestShadowPageOOM(unpagedPage);
 	
 	if (RomPagingSupported)
 		{
-		TestShadowPage(RomPagedStart, EPaged);
-		TestShadowPage(RomPagedStart + PageSize, EPaged);
-		TestShadowPage(RomPagedEnd - PageSize, EPaged);
-		TestNoFreeRAM(RomPagedEnd - PageSize);
-		TestShadowPageOOM(RomPagedStart);
-		TestInteractionWithPinning(RomPagedStart);
+		TLinAddr pagedPage = PageToShadow(ETrue);
+	
+		TestShadowPage(pagedPage,              EPaged, ETrue);
+		TestShadowPage(RomPagedStart,          EPaged, EFalse);
+		TestShadowPage(RomPagedEnd - PageSize, EPaged, EFalse);
+		
+		TestNoFreeRAM(pagedPage);
+		TestShadowPageOOM(pagedPage);
+		TestInteractionWithPinning(pagedPage);
 		}
 
 	// todo: add test when reforming section mappings is implemented
--- a/kerneltest/e32test/resmanus/resourcecontrol.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/resmanus/resourcecontrol.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -30,7 +30,7 @@
 #endif
 
 macro RESOURCE_MANAGER_SIMULATED_PSL
-macro _DUMP_TRACKERS
+//macro _DUMP_TRACKERS
 macro BTRACE_RESMANUS
 macro PRM_US_INSTRUMENTATION_MACRO
 
--- a/kerneltest/e32test/resmanus/resourcecontrollerextended.mmp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/resmanus/resourcecontrollerextended.mmp	Mon Oct 18 15:31:10 2010 +0100
@@ -31,7 +31,7 @@
 
 macro RESOURCE_MANAGER_SIMULATED_PSL
 macro BTRACE_RESMANUS
-macro _DUMP_TRACKERS
+//macro _DUMP_TRACKERS
 macro PRM_US_INSTRUMENTATION_MACRO
 macro PRM_ENABLE_EXTENDED_VERSION
 
--- a/kerneltest/e32test/usbho/t_usbdi/t_usbhost_usbman_src/t_usbhost_usbman.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/e32test/usbho/t_usbdi/t_usbhost_usbman_src/t_usbhost_usbman.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -17,7 +17,7 @@
 #include <e32cmn_private.h>
 #include <e32property.h>
 #include <d32otgdi.h>
-#include "..\..\t_usbdi\inc\testdebug.h"
+#include "../../t_usbdi/inc/testdebug.h"
 #include "OstTraceDefinitions.h"
 #ifdef OST_TRACE_COMPILER_IN_USE
 #include "t_usbhost_usbmanTraces.h"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kerneltest/e32utils/nistsecurerng/include/cephes.h	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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/src/approximateEntropy.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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/matrix.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -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	Mon Oct 18 15:31:10 2010 +0100
@@ -0,0 +1,637 @@
+/*
+* 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 = int(1U << (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;
+    }
+
Binary file kerneltest/e32utils/nistsecurerng/testdata/testdata.zip has changed
--- a/kerneltest/f32test/loader/dlltree.txt	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/f32test/loader/dlltree.txt	Mon Oct 18 15:31:10 2010 +0100
@@ -212,8 +212,8 @@
 
 # just add some data paged executables so loading gets OOM tested
 
-DataPagedExe1	X PD T
-DataPagedExe2	X PD D T
+DataPagedExe1	X B PD I T
+DataPagedExe2	X B PD D I T
 
 !TESTCASES
 
--- a/kerneltest/f32test/server/t_falsespace.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/f32test/server/t_falsespace.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -30,6 +30,9 @@
 const TInt KNumberThreads=2;
 const TInt KHeapSize=0x2000;
 
+//-- this is taken from the file server. Hardcoded constant that specifies session limits on reserving the drive space
+const TInt KMaxSessionDriveReserved	=0x10000; 
+
 static TInt RsrvSpaceThread(TAny* aArg);
 static TInt SessCloseThread(TAny* aArg);
 static void GetFreeDiskSpace(TInt64 &aFree);
@@ -80,6 +83,24 @@
 	User::WaitForRequest(s);
 	}
 
+//-----------------------------------------------------------------------------
+/**
+    Get a cluster size for the currently mounted FS (if it supports clusters). 
+    @return 0 if there was an error (e.g. cluster size query is not supported), otherwise a cluster size
+*/
+static TUint32 FsClusterSize()
+{
+    TVolumeIOParamInfo volIop;
+    TInt nRes = TheFs.VolumeIOParam(gTestDrive, volIop);
+
+    if(nRes != KErrNone || volIop.iClusterSize < 512 || !IsPowerOf2(volIop.iClusterSize))
+        {
+        test.Printf(_L("FsClusterSize() The FS hasn't reported a cluster size\n"));
+        return 0;
+        }
+        
+    return volIop.iClusterSize;
+}
 
 static TInt CreateFileX(const TDesC& aBaseName,TInt aX, TInt aFileSize)
 //
@@ -147,8 +168,7 @@
 // Test that a full disk is ok
 //
 	{
-
-	test.Start(_L("Fill disk to capacity"));
+	test.Next(_L("Fill disk to capacity\n"));
 	TInt r=TheFs.MkDirAll(KBasePath);
 	test_Value(r, r == KErrNone || r==KErrAlreadyExists);
 	gCount=0;
@@ -211,8 +231,6 @@
 		while (freespaceBeforeScanDrive != freespaceAfterScanDrive );
 
 	gCount--;
-
-	test.End();
 	}
 
 static void GetFreeDiskSpace(TInt64 &aFree)
@@ -233,7 +251,7 @@
 //	Test the API fundamentaly works for one session
 //
 	{
-	test.Next(_L("Test Disk Space reserve APIs"));
+	test.Next(_L("Test Disk Space reserve APIs\n"));
 	TInt r=0;
 	
     FormatDrive();
@@ -303,7 +321,7 @@
 //	
 	{
 
-	test.Next(_L("Test Session and total reserve limits"));
+	test.Next(_L("Test Session and total reserve limits\n"));
 	
     FormatDrive();
 	
@@ -319,7 +337,7 @@
 		test_KErrNone(r);
 		}
 
-	test.Next(_L("Test breaching sesson reserve limit"));
+	test.Next(_L("Test breaching sesson reserve limit\n"));
 	r=sessions[0].ReserveDriveSpace(gTestDrive,0x10001);
 	test_Value(r, r == KErrArgument);
 
@@ -328,7 +346,7 @@
 
 	if(v.iFree > 0x100000)
 		{
-		test.Next(_L("Test breaching drive reserve limit"));
+		test.Next(_L("Test breaching drive reserve limit\n"));
 
 		for (i=0; i<16; i++)
 			{
@@ -343,7 +361,7 @@
 	else
 		{
 		test.Printf(_L("Drive too small: breaching drive reserve limit test skipped\n"));
-		test.Next(_L("Testing exhausting available drive free space instead"));
+		test.Next(_L("Testing exhausting available drive free space instead\n"));
 
 		for(i=0; (v.iFree -= 0x10000) >= 0; i++)
 			{
@@ -368,7 +386,7 @@
 //	Test session cleanup
 //		
 	{
-	test.Next(_L("Test session close and clean up of resrved space"));
+	test.Next(_L("Test session close and clean up of resrved space\n"));
 
 	FormatDrive();
 	
@@ -439,16 +457,26 @@
 //	reserve an area etc
 //	
 	{
-	test.Next(_L("Test Filling disk and using APIs"));
+	test.Next(_L("Test Filling disk and using APIs\n"));
 
 	if(IsTestingLFFS())
 		{
-		//-- This test is not valid for LFFS, because free space on this FS can change itself because of some 
-        //-- internal FS activities
+		//-- This test is not valid for LFFS, because free space on this FS can change itself because of some internal FS activities
 		test.Printf(_L("This test is inconsistent on LFFS\n"));
 		return;
 		}
 	
+
+    const TInt KThreshold = 0x10000;
+	
+    //-- check that the cluster size doesn't exceed the max. limit
+    const TInt KClusterSz = FsClusterSize();
+    if(KClusterSz > KThreshold)
+        {
+        test.Printf(_L("The cluster size(%d) is bigger than threshold to test (%d)! Skipping the test!\n"), KClusterSz, KThreshold);
+		return;
+		}
+	
     FormatDrive();
 
 	RFs fs;
@@ -473,7 +501,7 @@
 
 	file.Close();
 
-	r=fs.ReserveDriveSpace(gTestDrive,0x10000);		//reserve some disk space
+	r=fs.ReserveDriveSpace(gTestDrive,KThreshold);		//reserve some disk space
 	test_KErrNone(r);
 		
 	FillUpDisk();									//fill up the disk
@@ -493,7 +521,7 @@
 	r=fs.ReleaseReserveAccess(gTestDrive);			//release reserve space
 	test_KErrNone(r);
 	
-	test(freeA == (freeB - 0x10000));				//test difference in space is equal to the amount reserved
+	test(freeA == (freeB - KThreshold));				//test difference in space is equal to the amount reserved
 
 	r=fs.Volume(v,gTestDrive);						//get disk space
 	test_KErrNone(r);
@@ -611,7 +639,7 @@
 //
 //
 	{
-	test.Next(_L("Test Session limits"));
+	test.Next(_L("Test Session limits\n"));
 
 	if(IsTestingLFFS())
 		{
@@ -731,7 +759,7 @@
 //
 	{
 	
-	test.Next(_L("Test sharable session"));
+	test.Next(_L("Test sharable session\n"));
 
 	RFs fsess;
 	TInt r=KErrNone;
@@ -787,6 +815,8 @@
 // Tests notifier events for sessions with and without reserved access
 //
 	{
+	test.Next(_L("Test reserved access notification\n"));
+
 	if(IsTestingLFFS())
 		{
 		// This test is not valid for LFFS...
@@ -794,11 +824,26 @@
 		return;
 		}
 
-	
-	test.Next(_L("Test reserved access notification"));
-	
 	FormatDrive();
 
+    //-- find out the cluster size
+    const TInt KClusterSz = FsClusterSize();
+    if(!IsPowerOf2(KClusterSz))
+        {
+        test.Printf(_L("The FS hasn't reported a cluster size. The test is inconsistent, skipping\n"));
+        return;
+        }
+
+    //-- check that the cluster size doesn't exceed the max. limit
+    if(KClusterSz > KMaxSessionDriveReserved)
+        {
+        test.Printf(_L("The cluster size(%d) is bigger than reserve limit (%d)! Skipping the test!\n"), KClusterSz, KMaxSessionDriveReserved);
+        return;
+        }
+
+    
+    const TInt resSpace = Max(0x1000, KClusterSz);
+
 	RFs theNrm;
 	RFs theRes;
 
@@ -823,25 +868,6 @@
 	err = theTestSession.Connect();
 	test_KErrNone(err);
 
-	// determine the cluster size
-	RFile theFile;
-	err=theFile.Replace(theTestSession, fileName, EFileShareAny | EFileWrite);
-	test_KErrNone(err);
-
-	// Neither notifier should be triggered here
-	err = theFile.SetSize(1);
-	test(KErrNone == err);
-	theFile.Close();
-
-	TInt64 newFreeSpace;
-	GetFreeDiskSpace(newFreeSpace);
-	TInt clusterSize = TInt(freeSpace - newFreeSpace);
-	theTestSession.Delete(fileName);
-	GetFreeDiskSpace(newFreeSpace);
-	test (newFreeSpace == freeSpace);
-
-	TInt resSpace = Max(0x1000, clusterSize);
-		
 	TVolumeInfo volInfo;
 	theNrm.Volume(volInfo, gTestDrive);
 	test(volInfo.iFree == freeSpace);
@@ -858,6 +884,8 @@
 	test(volInfo.iFree == freeSpace - resSpace);
 
 
+    RFile theFile;
+
 	//
 	// Register the notifiers and verify that the only the "Normal"
 	// and not the "Reserved" session is triggered.
@@ -918,7 +946,7 @@
 
 LOCAL_C void TestForDEF142554()
     {
-    test.Next(_L("Test for DEF142554: test RFile::Modified and RFile::Att when disk full"));
+    test.Next(_L("Test for DEF142554: test RFile::Modified and RFile::Att when disk full\n"));
     
     Format(gTestDrive);
     
@@ -990,7 +1018,7 @@
 	{
     const TInt64 K4Gig = 4*(TInt64)K1GigaByte;
 
-	test.Next(_L("Test files crossing 4G boundary on FAT"));
+	test.Next(_L("Test files crossing 4G boundary on FAT\n"));
 
     if(!Is_Fat32(TheFs, gTestDrive))
 		{
@@ -1056,7 +1084,7 @@
 
 void TestRAMDriveNotification()
 	{
-	test.Next(_L("Verifying RFs::ReserveDriveSpace() triggers RFs::NotifyDiskSpace() events"));
+	test.Next(_L("Verifying RFs::ReserveDriveSpace() triggers RFs::NotifyDiskSpace() events\n"));
 
 	TInt64 freeSpace;
 	GetFreeDiskSpace(freeSpace);
@@ -1065,19 +1093,19 @@
 	// set a notification on half the amount we plan to reserve
 	TInt reserve = 4096;
 	TInt64 trigger = freeSpace - 2048;
-	test.Printf(_L("setting notification for space to fall below: 0x%Lx bytes ... "), trigger);
+	test.Printf(_L("setting notification for space to fall below: 0x%Lx bytes ... \n"), trigger);
 	TRequestStatus stat;
 	TheFs.NotifyDiskSpace(trigger, gTestDrive, stat);
 	test_Value(stat.Int(), stat == KRequestPending);
 	test.Printf(_L("ok\n"));
 
 	// reserve the space and validate that this triggers the notification
-	test.Printf(_L("reserving 0x%x bytes ..."), reserve);
+	test.Printf(_L("reserving 0x%x bytes ...\n"), reserve);
 	TInt r = TheFs.ReserveDriveSpace(gTestDrive, reserve);
 	test_KErrNone(r);
 	test.Printf(_L("ok\n"));
 
-	test.Printf(_L("validating that the disk space notification triggered ... "));
+	test.Printf(_L("validating that the disk space notification triggered ...\n"));
 	User::After(2000000);	// 2 seconds should be enough to cause the trigger
 	test_Value(stat.Int(), stat == KErrNone);
 	test.Printf(_L("ok\n"));
@@ -1090,10 +1118,9 @@
 */
 void Test0()
 {
-    test.Next(_L("test ReserveDriveSpace threshold"));
+    test.Next(_L("test ReserveDriveSpace threshold\n"));
 
     TInt nRes;
-    TVolumeIOParamInfo volIop;
     TInt64 freespace=0;
 
     //-- 1. format the volume
@@ -1102,15 +1129,21 @@
     GetFreeDiskSpace(freespace);
     const TInt64 freeSpace1 = freespace; //-- initial amount of free space on the volume
 
-    nRes = TheFs.VolumeIOParam(gTestDrive, volIop);
-    test_KErrNone(nRes);
-    const TInt KClusterSz = volIop.iClusterSize;
+    const TInt KClusterSz = FsClusterSize();
     if(!IsPowerOf2(KClusterSz))
         {
-        test.Next(_L("The FS hasn't reported a cluster size. The test is inconsistent, skipping"));
+        test.Printf(_L("The FS hasn't reported a cluster size. The test is inconsistent, skipping\n"));
         return;
         }
 
+    //-- check that the cluster size doesn't exceed the max. limit
+    if(KClusterSz > KMaxSessionDriveReserved)
+        {
+        test.Printf(_L("The cluster size(%d) is bigger than reserve limit (%d)! Skipping the test!\n"), KClusterSz, KMaxSessionDriveReserved);
+        return;
+        }
+
+
     //-- reserve exactly 1 cluster worth drive space.
     nRes = TheFs.ReserveDriveSpace(gTestDrive, KClusterSz);
     test_KErrNone(nRes);
@@ -1162,7 +1195,7 @@
 	// If TESTFAST mode (for automated test builds) is set, don't run LFFS tests.
 	if ((UserSvr::DebugMask(2) & 0x00000002) && IsTestingLFFS())
 		{
-		test.Printf(_L("TEST NOT RUN FOR LFFS DRIVE"));
+		test.Printf(_L("TEST NOT RUN FOR LFFS DRIVE\n"));
 		return;
 		}
 
--- a/kerneltest/f32test/server/t_fsys.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/kerneltest/f32test/server/t_fsys.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -697,7 +697,7 @@
     test(remounts ==  KMaxMountFailures);
     
     // simulate a media change to reset failure count
-    r = TheFs.RemountDrive(aDrive, NULL, 0);
+    r = TheFs.RemountDrive(aDrive, NULL, RFs::KForceMediaChangeReOpenAllMediaDrivers);
 
     // now try mounting again & verify the the file server attempts to mount the drive again
     for (entryAttempts=0; entryAttempts < KEntryAttempts; entryAttempts++)
@@ -1335,14 +1335,13 @@
     nRes = TheFs.DismountFileSystem(fsName, drvNumber);
     test_Value(nRes, nRes == KErrInUse);
 
-    // Flag from locmedia.h to simulate ejecting and re-inserting the media.
-    const TUint KMediaRemountForceMediaChange = 0x00000001;
+    
     TRequestStatus changeStatus;
     TheFs.NotifyChange(ENotifyAll, changeStatus);
     
     
-    //-- 3. forcedly remount the drive
-    nRes = TheFs.RemountDrive(drvNumber, NULL, KMediaRemountForceMediaChange);
+    //-- 3. forcedly remount the drive to simulate ejecting and re-inserting the media.
+    nRes = TheFs.RemountDrive(drvNumber, NULL, RFs::KMediaRemountForceMediaChange);
     
     if(nRes == KErrNotSupported)
     	{//-- this feature is not supported and the test is inconsistent.
--- a/userlibandfileserver/fileserver/etshell/ts_com.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/etshell/ts_com.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -338,7 +338,7 @@
 
     if (nRes != KErrNone)
 	{
-    	CShell::TheConsole->Printf(_L("Wrong drive specified!\n"));
+    	CShell::Printf(_L("Wrong drive specified!\n"));
         return nRes;
     }
     
@@ -348,7 +348,7 @@
         nRes=TheShell->TheFs.ScanDrive(aPath);
         if(nRes == KErrNone)
         {
-            CShell::TheConsole->Printf(_L("No errors.\n"));
+            CShell::Printf(_L("No errors.\n"));
         }
     }
     else if(bFinaliseDrv)
@@ -357,7 +357,7 @@
         if(nRes != KErrNone)
             return nRes;
 
-        CShell::TheConsole->Printf(_L("Drive %c: is finalised RW\n"), 'A'+drive);
+        CShell::Printf(_L("Drive %c: is finalised RW\n"), 'A'+drive);
     }
     else if(bUnFinaliseDrv)
     {//-- Unfinalise the drive
@@ -365,7 +365,7 @@
         if(nRes != KErrNone)
             return nRes;
 
-        CShell::TheConsole->Printf(_L("Drive %c: is Unfinalised\n"), 'A'+drive);
+        CShell::Printf(_L("Drive %c: is Unfinalised\n"), 'A'+drive);
     }
     else
     {//-- run CheckDisk on the specified drive
@@ -377,22 +377,22 @@
 	    switch(nRes)
 		    {
 	    case 0:
-		    CShell::TheConsole->Printf(_L("Completed - no errors found\n"));
+		    CShell::Printf(_L("Completed - no errors found\n"));
 		    break;
 	    case 1:
-		    CShell::TheConsole->Printf(_L("Error - File cluster chain contains a bad value (<2 or >maxCluster)\n"));
+		    CShell::Printf(_L("Error - File cluster chain contains a bad value (<2 or >maxCluster)\n"));
 		    break;
 	    case 2:
-		    CShell::TheConsole->Printf(_L("Error - Two files are linked to the same cluster\n"));
+		    CShell::Printf(_L("Error - Two files are linked to the same cluster\n"));
 		    break;
 	    case 3:
-		    CShell::TheConsole->Printf(_L("Error - Unallocated cluster contains a value != 0\n"));
+		    CShell::Printf(_L("Error - Unallocated cluster contains a value != 0\n"));
 		    break;
 	    case 4:
-		    CShell::TheConsole->Printf(_L("Error - Size of file != number of clusters in chain\n"));
+		    CShell::Printf(_L("Error - Size of file != number of clusters in chain\n"));
 		    break;
 	    default:
-		    CShell::TheConsole->Printf(_L("Undefined Error value\n"));
+		    CShell::Printf(_L("Undefined Error value\n"));
 		    }
 	 }
     return nRes;
@@ -1494,12 +1494,12 @@
     nRes = aFs.DismountFileSystem(fsName, aDrvNum);
     if(nRes != KErrNone)
         {
-        CShell::TheConsole->Printf(_L("Can't dismount FS!\n"));
+        CShell::Printf(_L("Can't dismount FS!\n"));
         return nRes;
         }
     else
         {
-        CShell::TheConsole->Printf(_L("'%S' filesystem dismounted from drive %c:\n"), &fsName, 'A'+aDrvNum);
+        CShell::Printf(_L("'%S' filesystem dismounted from drive %c:\n"), &fsName, 'A'+aDrvNum);
         return KErrNone;
         }
     }
@@ -1509,7 +1509,7 @@
         aFs.NotifyDismount(aDrvNum, rqStat, EFsDismountForceDismount);  
         User::WaitForRequest(rqStat);
         
-        CShell::TheConsole->Printf(_L("'%S' filesystem Forcedly dismounted from drive %c:\n"), &fsName, 'A'+aDrvNum);
+        CShell::Printf(_L("'%S' filesystem Forcedly dismounted from drive %c:\n"), &fsName, 'A'+aDrvNum);
 
         return rqStat.Int(); 
     }
@@ -1551,7 +1551,7 @@
         nRes = aFs.ExtensionName(extName, aDrvNum, 1);
         if(nRes == KErrNone)
         {   
-            CShell::TheConsole->Printf(_L("Non-primary extensions are not supported!\n"));
+            CShell::Printf(_L("Non-primary extensions are not supported!\n"));
             return KErrNotSupported;
         }
     }
@@ -1579,7 +1579,7 @@
 
     if(nRes == KErrNone)
     {
-        CShell::TheConsole->Printf(_L("mounted filesystem:%S\n"), &fsName);
+        CShell::Printf(_L("mounted filesystem:%S\n"), &fsName);
     }
 
     return nRes;
@@ -1630,7 +1630,7 @@
     nRes = DoExtractDriveLetter(token);
     if(nRes < 0)
     {
-        CShell::TheConsole->Printf(KErrInvalidDrive);
+        CShell::Printf(KErrInvalidDrive);
         return KErrArgument;
     }
 
@@ -1651,7 +1651,7 @@
         
         if(nRes == KErrNotFound)
         {//-- nothing to dismount
-            CShell::TheConsole->Printf(_L("specified drive doesn't have FS mounted\n"));
+            CShell::Printf(_L("specified drive doesn't have FS mounted\n"));
             return KErrNone;
         }
 
@@ -1673,8 +1673,8 @@
     nRes = fs.FileSystemName(fsName, drvNum);
     if(nRes == KErrNone)
     {
-        CShell::TheConsole->Printf(_L("specified drive already has '%S' file system mounted.\n"), &fsName);
-        CShell::TheConsole->Printf(_L("Dismount it first using '/U' switch or use '/F' switch.\n"));
+        CShell::Printf(_L("specified drive already has '%S' file system mounted.\n"), &fsName);
+        CShell::Printf(_L("Dismount it first using '/U' switch or use '/F' switch.\n"));
         return KErrNone;
     }
 
@@ -1692,13 +1692,13 @@
 
     if(!DoFindToken(aArgs, KFSY_Param, ptrFSYName))
     {//-- FSY plugin name, like "elocal.fsy"
-        CShell::TheConsole->Printf(_L("'%S' parameter is required!\n"), &KFSY_Param);
+        CShell::Printf(_L("'%S' parameter is required!\n"), &KFSY_Param);
         return KErrNone;
     }
 
     if(!DoFindToken(aArgs, KFsName_Param, ptrFSName))
     {//-- file system name, like "FAT"
-        CShell::TheConsole->Printf(_L("'%S' parameter is required!\n"), &KFsName_Param);
+        CShell::Printf(_L("'%S' parameter is required!\n"), &KFsName_Param);
         return KErrNone;
     }
 
@@ -1714,7 +1714,7 @@
     nRes = fs.AddFileSystem(ptrFSYName);
     if(nRes != KErrNone && nRes != KErrAlreadyExists)
     {
-        CShell::TheConsole->Printf(_L("Can't load '%S' file system plugin!\n"), &ptrFSYName);        
+        CShell::Printf(_L("Can't load '%S' file system plugin!\n"), &ptrFSYName);        
         return nRes;
     }
 
@@ -1723,7 +1723,7 @@
         nRes = fs.AddExtension(ptrPExtName);
         if(nRes != KErrNone && nRes != KErrAlreadyExists)
         {
-            CShell::TheConsole->Printf(_L("Can't load '%S' FS extension plugin!\n"), &ptrPExtName);        
+            CShell::Printf(_L("Can't load '%S' FS extension plugin!\n"), &ptrPExtName);        
             return nRes;
         }
     }
@@ -1738,11 +1738,11 @@
         nRes = fs.MountFileSystem(ptrFSName, drvNum, bDrvSynch);
     }
 
-    CShell::TheConsole->Printf(_L("Mounting new file system...\n"));        
+    CShell::Printf(_L("Mounting new file system...\n"));        
 
     if(nRes != KErrNone && nRes != KErrCorrupt)
     {//-- KErrCorrupt might mean that the FS mounted OK onto the drive, but ve volume itself needs formatting
-        CShell::TheConsole->Printf(_L("Error mounting the filesystem! (%d)\n"), nRes);
+        CShell::Printf(_L("Error mounting the filesystem! (%d)\n"), nRes);
         return nRes;
     }
 
@@ -1810,7 +1810,7 @@
     const TInt nDrv = DoExtractDriveLetter(ptrPath);
     if(nDrv < 0 )
         {
-        CShell::TheConsole->Printf(_L("type \"format /?\" for help.\n"));
+        CShell::Printf(_L("type \"format /?\" for help.\n"));
         return KErrNone;
         }
 
@@ -1908,7 +1908,7 @@
                 }
                 else
                 {
-                CShell::TheConsole->Printf(_L("Invalid SectorsPerCluster value!\n"));
+                CShell::Printf(_L("Invalid SectorsPerCluster value!\n"));
                 return KErrNone;
                 }
             }
@@ -1925,7 +1925,7 @@
                 }
             else
                 {
-                CShell::TheConsole->Printf(_L("Invalid Reserved Sectors value!\n"));
+                CShell::Printf(_L("Invalid Reserved Sectors value!\n"));
                 return KErrNone;
                 }
             }
@@ -1942,7 +1942,7 @@
                 }
             else
                 {
-                CShell::TheConsole->Printf(_L("Invalid FAT tables number value!\n"));
+                CShell::Printf(_L("Invalid FAT tables number value!\n"));
                 return KErrNone;
                 }
             }
@@ -1967,7 +1967,7 @@
                 }
                 else
                 {
-                CShell::TheConsole->Printf(_L("Invalid SectorsPerCluster value!\n"));
+                CShell::Printf(_L("Invalid SectorsPerCluster value!\n"));
                 return KErrNone;
                 }
             }
@@ -1984,7 +1984,7 @@
                 }
             else
                 {
-                CShell::TheConsole->Printf(_L("Invalid FAT tables number value!\n"));
+                CShell::Printf(_L("Invalid FAT tables number value!\n"));
                 return KErrNone;
                 }
             }
@@ -1999,7 +1999,7 @@
         }
     else
         {
-        CShell::TheConsole->Printf(_L("The new file system is:%S\n"), &fsName);
+        CShell::Printf(_L("The new file system is:%S\n"), &fsName);
         nRes = format.Open(TheShell->TheFs, ptrPath, fmtMode, fmtCnt, volFmtParamBuf);
         }
 
@@ -2028,28 +2028,28 @@
     //-- format errors processing
     if(nRes != KErrNone)
         {
-        CShell::TheConsole->Printf(_L("Format failed.\n"));
+        CShell::Printf(_L("Format failed.\n"));
         }
 
     switch(nRes)
         {
         case KErrNone:
-            CShell::TheConsole->Printf(_L("Format complete.\n"));
+            CShell::Printf(_L("Format complete.\n"));
         break;
 
         
         case KErrArgument: //-- FORMAT has rejected specified parameters
-            CShell::TheConsole->Printf(_L("Possible reason: Invalid combination of formatting parameters.\n"));
+            CShell::Printf(_L("Possible reason: Invalid combination of formatting parameters.\n"));
             nRes = KErrNone;
         break;
 
         case KErrNotSupported: //-- trying to format SD card with parameters or not supported FS name specified
-            CShell::TheConsole->Printf(_L("Possible reasons: media does not support special formatting or specified file system is not supported\n"));
+            CShell::Printf(_L("Possible reasons: media does not support special formatting or specified file system is not supported\n"));
             nRes = KErrNone;
         break;
 
         case KErrNotFound: //-- possible reason: unrecognisable media and automounter FS + formatting without specifying the FS name
-            CShell::TheConsole->Printf(_L("Possible reason: Unable to chose appropriate file system (not specified)\n"));
+            CShell::Printf(_L("Possible reason: Unable to chose appropriate file system (not specified)\n"));
             nRes = KErrNone;
         break;
 
@@ -2146,7 +2146,7 @@
 	TInt fileNameLen=aPath.LocateReverse(' ');
 	if (fileNameLen==KErrNotFound)	//	No spaces implies no filelength specified
 		{
-		CShell::TheConsole->Printf(_L("Please specify a file name and a file length\n"));
+		CShell::Printf(_L("Please specify a file name and a file length\n"));
 		return (KErrNone);
 		}
 
@@ -2164,7 +2164,7 @@
 	TInt r=size.Val(fileSize,radix);
 	if (r!=KErrNone || ! size.Eos())
 		{
-		CShell::TheConsole->Printf(_L("Please specify a file length\n"));
+		CShell::Printf(_L("Please specify a file length\n"));
 		return (KErrNone);
 		}
 
@@ -2211,7 +2211,7 @@
     //-- this can make write faster on rugged fat.
     if(aSwitches&TShellCommand::EESwitch)
     {//-- /e switch is specified, create an empty file without writing data
-        CShell::TheConsole->Printf(_L("Creating an empty file, size:%LD bytes\n"), fileSize);
+        CShell::Printf(_L("Creating an empty file, size:%LD bytes\n"), fileSize);
     }
 
     r=file.SetSize(fileSize);
@@ -2249,8 +2249,8 @@
 
     endTime.SecondsFrom(startTime, timeTaken);
 
-    CShell::TheConsole->Printf(_L("Total bytes written:%LD\n"), cntBytes);
-    CShell::TheConsole->Printf(_L("Time taken:%d Sec.\n"), timeTaken.Int());
+    CShell::Printf(_L("Total bytes written:%LD\n"), cntBytes);
+    CShell::Printf(_L("Time taken:%d Sec.\n"), timeTaken.Int());
 
     return r;
 
@@ -2261,7 +2261,7 @@
     if(r!= KErrAlreadyExists) //this is to ensure that an existing file does not get deleted
 	    CShell::TheFs.Delete(fileName.FullName());
 
-    CShell::TheConsole->Printf(_L("Error - could not create file, code:%d\n"), r);
+    CShell::Printf(_L("Error - could not create file, code:%d\n"), r);
 
     return r;
 	}
@@ -3033,7 +3033,7 @@
 	r=directory.Open(TheShell->TheFs,dirPath.FullName(),KEntryAttMatchExclusive|KEntryAttDir);
 	if (r!=KErrNone)
 		{
-		CShell::TheConsole->Printf(_L("Directory %S was not found\n"),&dirPath.FullName());
+		CShell::Printf(_L("Directory %S was not found\n"),&dirPath.FullName());
 		return (KErrNone);
 		}
 	directory.Close();
@@ -3041,10 +3041,10 @@
 	TInt ret=TheShell->TheFs.RmDir(dirPath.FullName());
     
     if (ret==KErrNone)
-	    CShell::TheConsole->Printf(_L("Directory %S was removed\n"),&dirPath.FullName());
+	    CShell::Printf(_L("Directory %S was removed\n"),&dirPath.FullName());
     else if(ret==KErrInUse)
 	    {
-		CShell::TheConsole->Printf(_L("Directory %S is in use and cannot be deleted\n"),&dirPath.FullName());
+		CShell::Printf(_L("Directory %S is in use and cannot be deleted\n"),&dirPath.FullName());
 		return KErrNone;
 		}
 	
@@ -3069,11 +3069,14 @@
 
 TInt ShellFunction::Time(TDes&,TUint /*aSwitches*/)
 	{
-	TTime time;
+	
+    TTime time;
 	time.HomeTime();
 	TDateTime dateTime(time.DateTime());
-	CShell::TheConsole->Printf(_L("  %+02d/%+02d/%+04d %+02d:%+02d:%+02d.%+06d\n"),dateTime.Day()+1,dateTime.Month()+1,dateTime.Year(),dateTime.Hour(),dateTime.Minute(),dateTime.Second(),dateTime.MicroSecond());
-	return(KErrNone);
+	
+	CShell::Printf(_L("  %+02d/%+02d/%+04d %+02d:%+02d:%+02d.%+03d\n"),dateTime.Day()+1,dateTime.Month()+1,dateTime.Year(),dateTime.Hour(),dateTime.Minute(),dateTime.Second(),dateTime.MicroSecond());
+
+    return KErrNone;
 	}
 
 TInt ShellFunction::Trace(TDes& aState,TUint aSwitches)
@@ -3359,6 +3362,7 @@
 	aPath.Insert(0,pathParse.FullName());
 	}
 
+/*
 TBool ShellFunction::Certain()
 	{
 	CShell::TheConsole->Printf(_L("Are you sure? Y/N..."));
@@ -3372,6 +3376,7 @@
 	CShell::TheConsole->Printf(_L("%c\n"),r);
 	return(r=='Y');
 	}
+*/
 
 TInt ShellFunction::GetFullPath(TDes& aPath,TParse& aParse)
 //
--- a/userlibandfileserver/fileserver/etshell/ts_edshl.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/etshell/ts_edshl.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -1059,7 +1059,9 @@
 		readBuf.SetLength(r);
 		
 		readBuf.Trim();
-		TheFs.SessionPath(currentPath);
+		r = TheFs.SessionPath(currentPath);
+		if(r!=KErrNone)
+		    break;
 		TheConsole->Printf(currentPath);		
 		TheConsole->Printf(_L(">%S\n"),&readBuf);
 
@@ -1093,7 +1095,7 @@
 	
     
     file.Close();
-	return KErrNone;
+	return r;
 	}
 
 
--- a/userlibandfileserver/fileserver/fs_utils/bit_vector.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/fs_utils/bit_vector.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -327,11 +327,11 @@
             return FindNearest(aStartPos, aBitVal, EFalse);
 
         default:
-            Panic(EWrondFindDirection);
-            return EFalse;
+            break;
+        };
 
-        };
-    
+    Panic(EWrondFindDirection);
+    return EFalse;
     }
 
 //-----------------------------------------------------------------------------
@@ -670,11 +670,9 @@
 {
     if(aIdx == 0)
         return ETrue;
-    else
-    {
-        aIdx--;
-        return EFalse;
-    }
+    
+    aIdx--;
+    return EFalse;
 }
 
 //-----------------------------------------------------------------------------
@@ -692,8 +690,8 @@
         aIdx++;
         return EFalse;
     }
-    else
-        return ETrue;
+
+    return ETrue;
 }
 
 //-----------------------------------------------------------------------------
--- a/userlibandfileserver/fileserver/group/release.txt	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/group/release.txt	Mon Oct 18 15:31:10 2010 +0100
@@ -1,3 +1,17 @@
+Version 2.00.4006
+=================
+(Made by fadhliM 13/10/2010)
+
+1.	dlyokhin
+	1.	ou1cimx1#582827 RFormat causes all logical drives (associated with a primary removable media device) to be deleted and recreated
+	2.	ou1cimx1#603919 TDrive::ForceDismount() shouldn't finalise drive in RO mode
+	3.	ou1cimx1#602572 SD stack should correctly support SD cards larger than 32GB
+
+2.	michcox
+	1.	ou1cimx1#512321 coverity defects - Fileserver - cases 125100, 126171, 130137
+	2.	ou1cimx1#565164 Fix Change - coverity defects - Fileserver
+
+
 Version 2.00.4005
 =================
 (Made by fadhliM 04/10/2010)
--- a/userlibandfileserver/fileserver/inc/f32file.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/inc/f32file.h	Mon Oct 18 15:31:10 2010 +0100
@@ -2106,7 +2106,7 @@
 	IMPORT_C TInt RemoveProxyDrive(const TDesC& aDriveName);
 	
 	template <class T0,class T1> inline TInt MountProxyDrive(const TUint aDrive, const TDesC& aName, T0 a0, T1 a1)
-		{ return(DoMountProxyDrive(TIpcArgs(aDrive, &aName, a0, a1))); };
+		{ return(DoMountProxyDrive(TIpcArgs(aDrive, &aName, a0, a1))); }
 	IMPORT_C TInt DismountProxyDrive(const TUint aDrive);
 	
 	TInt Unclamp(const RFileClamp& aHandle);
@@ -2152,6 +2152,33 @@
 
     EFSRV_IMPORT_C TInt SupportedFileSystemName(TDes& aName, TInt aDrive, TInt aFsEnumerator) const;
 
+
+    
+    /**
+        A set of special flags passed directly to the media driver via RFs::RemountDrive() API.
+        They are used to specify how exactly the drive should be remounted. For more information see RLocalDrive::ForceMediaChange()
+        @see RFs::RemountDrive()
+    */     
+    enum TForceMediaChangeFlags
+        {
+        /**
+        Passing this flag to RFs::RemountDrive() API results in all media drivers associated with the primary media being closed and reopened.
+        All pending requests on all logical drives associated with the primary media will be cancelled.
+        */
+        KForceMediaChangeReOpenAllMediaDrivers = 0,
+        
+        /**
+        This flag is used to simulate ejecting and re-inserting the media.
+        All pending requests on all logical drives associated with the primary media will be cancelled.
+        */
+        KMediaRemountForceMediaChange = 0x00000001,
+        
+        /** This flag is used to force the media driver for the specified logical drive to be closed and reopened.
+        It should not affect any pending requests on other logical drives associated with the primary media.
+        */
+        KForceMediaChangeReOpenMediaDriver = 0x80000000
+        };
+
 protected:
 	TInt SendReceive(TInt aFunction,const TIpcArgs& aArgs) const;
 
--- a/userlibandfileserver/fileserver/inc/f32ver.h	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/inc/f32ver.h	Mon Oct 18 15:31:10 2010 +0100
@@ -58,6 +58,6 @@
 
 @see TVersion
 */
-const TInt KF32BuildVersionNumber=4005;
+const TInt KF32BuildVersionNumber=4006;
 //
 #endif
--- a/userlibandfileserver/fileserver/runtests/runtests.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/runtests/runtests.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -722,7 +722,7 @@
 	r=listfile.Open(TheFs,listfilename,EFileRead|EFileShareAny);
 	if (r!=KErrNone)
 		__PANIC(r);
-	TInt listfilesize;
+	TInt listfilesize = 0;
 	r=listfile.Size(listfilesize);
 	if (r!=KErrNone)
 		__PANIC(r);
--- a/userlibandfileserver/fileserver/sfat32/fat_table32.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/fat_table32.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -649,10 +649,11 @@
             return aFatIndex<<2; //-- 4 bytes per FAT entry
 
         default:
-            ASSERT(0);
-            return 0;//-- get rid of warning
+            break;
         };
 
+    ASSERT(0);
+    return 0;//-- get rid of warning
 	}
 
 //-----------------------------------------------------------------------------
--- a/userlibandfileserver/fileserver/sfat32/sl_bpb32.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_bpb32.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -274,9 +274,9 @@
         return EFat12;
     else if(clusterCnt < 65525)
         return EFat16;
-    else
-        return EFat32;
 
+    
+    return EFat32;
     }
 
 
--- a/userlibandfileserver/fileserver/sfat32/sl_fatmisc32.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_fatmisc32.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -107,15 +107,12 @@
 	ASSERT(iReservedSectors >= (bFat32 ? KDefFat32ResvdSec : KDefFatResvdSec));
 
 	if ((FirstDataSector() & (aEraseBlockSizeInSectors-1)) == 0)
-		{
 		return KErrNone;
-		}
-	else
-		{
-		iReservedSectors = reservedSectorsSaved;
-		iSectorsPerFat = sectorsPerFatSaved;
-		return KErrGeneral;
-		}
+
+	
+    iReservedSectors = reservedSectorsSaved;
+	iSectorsPerFat = sectorsPerFatSaved;
+	return KErrGeneral;
 	}
 
 
@@ -283,10 +280,17 @@
 			}
 		}
 
-	// ReMount since MBR may have been rewritten and partition may have moved / changed size
-	TInt ret = LocalDrive()->ForceRemount(0);
-	if (ret != KErrNone && ret != KErrNotSupported)
-		User::Leave(ret);
+    
+    {//-- ReMount whole driver stack since MBR may have been rewritten and partition may have moved / changed size.
+     
+    //-- this is mostly applicable to SD cards formatting, since SD stack takes care of creating partition table.
+    //-- use KForceMediaChangeReOpenAllMediaDrivers flag that will cause remounting media 
+    //-- drivers associatied with the current partition only and not affecting other ones.
+    const TInt ret = LocalDrive()->ForceRemount((TUint)RFs::KForceMediaChangeReOpenMediaDriver);
+    if(ret != KErrNone && ret != KErrNotSupported)
+	    User::Leave(ret);
+    }
+	
 
 	// MBR may have changed, so need to re-read iHiddenSectors etc.before BPB is written
 	InitializeFormatDataL();
--- a/userlibandfileserver/fileserver/sfat32/sl_file.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_file.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -877,8 +877,9 @@
     aStartPos = iCurrentPos.iPos;
     if ((I64LOW(aStartPos) == FCB_FileSize()) || ( I64LOW(aStartPos) == (myStartPos + length)))
         return KErrCompletion;
-    else
-        return KErrNone;
+    
+    
+    return KErrNone;
     }
 
 
@@ -898,8 +899,10 @@
             return FatMount().LocalDrive()->GetLocalDrive((TBusLocalDrive*&) aInterface);
 
         default:
-            return CFileCB::GetInterface(aInterfaceId,aInterface,aInput);
+            break;
         }
+    
+    return CFileCB::GetInterface(aInterfaceId,aInterface,aInput);
     }
 
 
--- a/userlibandfileserver/fileserver/sfat32/sl_fmt.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_fmt.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -137,8 +137,8 @@
         return EFat12;
     else if(clusterCnt < 65525)
         return EFat16;
-    else
-        return EFat32;
+
+    return EFat32;
 }
 
 //-------------------------------------------------------------------------------------------------------------------
--- a/userlibandfileserver/fileserver/sfat32/sl_fsy.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_fsy.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -145,6 +145,8 @@
 			return KErrNone;
 
         default:
-            return(CFileSystem::GetInterface(aInterfaceId, aInterface, aInput));
+            break;
         }
+    
+    return(CFileSystem::GetInterface(aInterfaceId, aInterface, aInput));
     }
--- a/userlibandfileserver/fileserver/sfat32/sl_leafdir_cache.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_leafdir_cache.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -893,10 +893,8 @@
 		CLeafDirTreeNode* dummy = NULL;
 		return (iTree->Search(path, dummy, aLeafDirData));
 		}
-	else
-		{
-		return KErrBadName;
-		}
+
+	return KErrBadName;
 	}
 
 /*
--- a/userlibandfileserver/fileserver/sfat32/sl_mnt.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_mnt.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -1634,15 +1634,20 @@
         MoveToDosEntryL(dirEntryPos,dirEntry);
         if (dirEntry.IsParentDirectory() || dirEntry.IsCurrentDirectory())
             goto LoopEnd;
+        
         if (dirEntry.IsEndOfDirectory())
             return ETrue;
+        
         if (IsRootDir(dirEntryPos)&&(dirEntryPos.iPos+StartOfRootDirInBytes()==RootDirEnd()))
             return ETrue;   //  Root Directory has no end of directory marker
+        
         if (!dirEntry.IsErased())
-            return EFalse;
+            break; //-- found a valid dir. entry
 LoopEnd:
         MoveToNextEntryL(dirEntryPos);
         }
+    
+    return EFalse;
     }
 
 //-----------------------------------------------------------------------------------------
@@ -1810,7 +1815,7 @@
         if (offset<length)
             {__ASSERT_ALWAYS(FAT().GetNextClusterL(aPos.iCluster),User::Leave(KErrCorrupt));}
         if (offset>=length)
-            return;
+            break;
         }
     }
 
@@ -1884,7 +1889,7 @@
             __ASSERT_ALWAYS(FAT().GetNextClusterL(aPos.iCluster),User::Leave(KErrCorrupt));
             }
         if (offset>=aLength)
-            return;
+            break;
         }
     }
 
@@ -3513,7 +3518,8 @@
 
     TLeafDirData leafDir;
     pos.iCluster=FindLeafDirL(aShortName.Left(namePos), leafDir);
-    FOREVER
+    
+    for(;;)
         {
         TFatDirEntry startEntry;
         User::LeaveIfError(GetDirEntry(pos,entry,startEntry,aLongName));
@@ -3529,13 +3535,14 @@
             LocaleUtils::ConvertToUnicodeL(entryName, entryName8);
             if (shortNameWithoutPathDelimiter.MatchF(entryName)!=KErrNotFound)
                 {
-                if (entryIsVFat==EFalse)
+                if(!entryIsVFat)
                     aLongName=shortNameWithoutPathDelimiter;
-                return;
+                
+                break;
                 }
             }
         MoveToNextEntryL(pos);
-        }
+        }//for(;;)
     }
 
 
@@ -3815,8 +3822,12 @@
     r=local->ErasePassword();
     if(r==KErrNone)
         {
-        // ...media change to ensure a fresh remount the drive
-        r = local->ForceRemount(0);
+        //-- ReMount whole driver stack since MBR may have been rewritten and partition may have moved / changed size.
+        //-- this is mostly applicable to SD cards formatting, since SD stack takes care of creating partition table.
+        //-- use KForceMediaChangeReOpenAllMediaDrivers flag that will cause remounting media 
+        //-- drivers associatied with the current partition only and not affecting other ones.
+        r = LocalDrive()->ForceRemount((TUint)RFs::KForceMediaChangeReOpenMediaDriver);
+        
         local->Status() = KErrNotReady;
         WritePasswordData();
         }
@@ -4366,13 +4377,10 @@
 TTimeIntervalSeconds CFatMountCB::TimeOffset() const
 	{
     if((Drive().Att() & KDriveAttRemovable) && FatFileSystem().GetUseLocalTime() )
-	    {
         return User::UTCOffset();
-        }
-	else
-        {
-        return TTimeIntervalSeconds(0);
-        }
+
+    
+    return TTimeIntervalSeconds(0);
 	}
 
 
@@ -4431,10 +4439,11 @@
         return  EOF_12Bit-7; //-- 0xff8
         
         default: 
-        ASSERT(aFatType == EInvalid); 
-        return 0;
+        break;
         }
 
+    ASSERT(aFatType == EInvalid); 
+    return 0;
     }
 
 //-----------------------------------------------------------------------------------------
--- a/userlibandfileserver/fileserver/sfat32/sl_mnt32.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_mnt32.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -335,8 +335,7 @@
         User::LeaveIfError(drive.ReadNonCritical(StartOfFatInBytes()+KFatEntrySize, KFatEntrySize, ptrFatEntry)); //read FAT32[1] entry
         return (fatEntry & KFat32CleanShutDownMask);
         }
-    else 
-    if(Is16BitFat())
+    else if(Is16BitFat())
         {//-- Fat16
         TFat16Entry fatEntry;
         const TInt  KFatEntrySize=sizeof(fatEntry); //-- FAT entry size in bytes
@@ -659,7 +658,7 @@
 	if(aName.MaxLength() < 5)
 		return KErrArgument;
 	
-	switch (FatType())
+	switch(FatType())
 		{
 		case EFat12:
 			{
@@ -676,11 +675,14 @@
 			aName = KFSSubType_FAT32;
 			return KErrNone;
 			}
+
 		default:
-		// case EInvalidFatType
-			return KErrNotReady;
+		    break;
+			
 		}
-	}
+	
+        return KErrNotReady;
+    }
 
 
 //-------------------------------------------------------------------------------------------------------------------
@@ -1006,8 +1008,10 @@
            	return KErrNone;
         
         default:
-            return(CMountCB::GetInterface(aInterfaceId, aInterface, aInput));
+            break;
         }
+    
+    return(CMountCB::GetInterface(aInterfaceId, aInterface, aInput));
     }
 
 //-----------------------------------------------------------------------------------------
--- a/userlibandfileserver/fileserver/sfat32/sl_scan32.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_scan32.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -234,11 +234,10 @@
 */
 CScanDrive::TGenericError CScanDrive::ProblemsDiscovered() const
 {
-
     if(IsDirError()) 
         return EScanDriveDirError;
-    else
-        return iGenericError;
+
+    return iGenericError;
 }
 
 /**
--- a/userlibandfileserver/fileserver/sfat32/sl_vfat.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfat32/sl_vfat.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -548,16 +548,11 @@
 		User::Leave(KErrAlreadyExists);
 
 	if((i == -1) && IsLegalDosName(aName,EFalse,EFalse,EFalse,EFalse,ETrue))
-		{
-		// Original file name is a legal 8.3 name
-		return(ETrue);
-		}
-	else
-		{
-	    return(EFalse);
+		{// Original file name is a legal 8.3 name
+		return ETrue;
 		}
 
-
+	return EFalse;
 	}
 
 
--- a/userlibandfileserver/fileserver/sfile/sf_drv.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfile/sf_drv.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -2201,8 +2201,7 @@
 
 /**
     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.
-
+    After calling this function there is no current mount on the drive.
 */
 EXPORT_C void TDrive::Dismount()
 	{
@@ -2216,8 +2215,8 @@
     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)
-    //-- finalise the mount in RO mode, we are dismounting the FS anyway
-    TRAP_IGNORE(iCurrentMount->FinaliseMountL(RFs::EFinal_RO));
+    //-- finalise the mount in RW mode
+    TRAP_IGNORE(iCurrentMount->FinaliseMountL(RFs::EFinal_RW));
     
     DoDismount();
 	}
@@ -2240,8 +2239,9 @@
 	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)
-    //-- finalise the mount in RO mode, we are dismounting the FS anyway
-    TRAP_IGNORE(iCurrentMount->FinaliseMountL(RFs::EFinal_RO));
+    //-- finalise the mount in RW mode. It is possible that the mount is being forcedly dismounted with some files opened on it.
+    //-- in this case further attempt to access may will result in successful remountng and re-attaching mount and its files to the media.
+    TRAP_IGNORE(iCurrentMount->FinaliseMountL(RFs::EFinal_RW));
 
     //-- 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.
@@ -2541,10 +2541,8 @@
 TInt TDrive::ClearDeferredDismount()
 // debug-only function for testing
 	{
-	Lock();
 	FsNotify::HandleDismount(EFsDismountRegisterClient, DriveNumber(), ETrue, KErrNone);
 	SetDismountDeferred(EFalse);
-	UnLock();
 	return KErrNone;
 	}
 #endif
--- a/userlibandfileserver/fileserver/sfsrv/cl_cli.cpp	Wed Oct 13 13:34:03 2010 +0100
+++ b/userlibandfileserver/fileserver/sfsrv/cl_cli.cpp	Mon Oct 18 15:31:10 2010 +0100
@@ -832,7 +832,6 @@
 
 
 
-EFSRV_EXPORT_C TInt RFs::RemountDrive(TInt aDrive,const TDesC8* aMountInfo,TUint aFlags)
 /**
 Forces a remount of the specified drive.
 
@@ -840,14 +839,13 @@
 @param aMountInfo Information passed down to the media driver. The meaning of
                   this information depends on the media driver, for example,
                   keys for secure areas.
-@param aFlags     When the flag is set to
-                  0x00000001 - Used to simulate ejecting and re-inserting the media.
-                  0x80000000 - used to force the media driver for the specified logical
-                               drive to be closed and reopened.
-
-@return KErrNone if successful, otherwise one of
-        the other system wide error codes.
+
+@param aFlags     one of the flags specified in RFs::TForceMediaChangeFlags and describing the way 
+                  drive is going to be remounted.   
+
+@return KErrNone if successful, otherwise one of the other system wide error codes.
 */
+EFSRV_EXPORT_C TInt RFs::RemountDrive(TInt aDrive,const TDesC8* aMountInfo,TUint aFlags)
 	{
 	OstTraceExt4(TRACE_BORDER, EFSRV_EFSREMOUNTDRIVE, "sess %x aDrive %d aMountInfo %x aFlags %x", (TUint) Handle(), aDrive, (TUint) aMountInfo, (TUint) aFlags);
 	TInt r = SendReceive(EFsRemountDrive,TIpcArgs(aDrive,aMountInfo,aFlags));