summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRyan Harkin <ryan.harkin@linaro.org>2013-02-21 16:43:46 +0000
committerRyan Harkin <ryan.harkin@linaro.org>2013-02-21 16:43:46 +0000
commitd9875a6d13d3ac0a4d040567d393d4dc180dac87 (patch)
tree59f66de3648275508f5aaa9c342d92c62f12713a
parent212a71099ba8e17037ca41aaddb83a12e21bc83e (diff)
parentc553da4d0d9b3e65303656b2a4d497458aab74a7 (diff)
Merge branch 'armlt-tracking' of git://git.linaro.org/arm/uefi/uefi-nextlinaro-uefi-2013.02
Signed-off-by: Ryan Harkin <ryan.harkin@linaro.org>
-rw-r--r--AppPkg/Applications/Main/Main.c1
-rw-r--r--AppPkg/Applications/Python/Efi/config.c77
-rw-r--r--AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h121
-rw-r--r--AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c6279
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_external.h6
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlparse.c8
-rw-r--r--AppPkg/Applications/Python/PythonCore.inf49
-rw-r--r--AppPkg/ISSUES.txt28
-rw-r--r--ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf4
-rw-r--r--ArmPkg/Application/LinuxLoader/LinuxConfig.c707
-rw-r--r--ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf4
-rw-r--r--ArmPkg/Application/LinuxLoader/LinuxInternal.h99
-rw-r--r--ArmPkg/ArmPkg.dsc262
-rw-r--r--ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S382
-rw-r--r--ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.asm304
-rw-r--r--ArmPkg/Drivers/CpuDxe/ArmV6/ExceptionSupport.S594
-rwxr-xr-xArmPkg/Drivers/CpuPei/CpuPei.inf2
-rw-r--r--ArmPkg/Drivers/PL390Gic/PL390GicDxe.c851
-rw-r--r--ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf114
-rw-r--r--ArmPkg/Drivers/PL390Gic/PL390GicLib.inf3
-rw-r--r--ArmPkg/Drivers/TimerDxe/TimerDxe.c760
-rw-r--r--ArmPkg/Drivers/TimerDxe/TimerDxe.inf118
-rw-r--r--ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c7
-rw-r--r--ArmPkg/Filesystem/SemihostFs/SemihostFs.inf92
-rw-r--r--ArmPkg/Include/Chipset/ArmV7.h20
-rw-r--r--ArmPkg/Include/Library/ArmCpuLib.h56
-rw-r--r--ArmPkg/Include/Library/ArmDisassemblerLib.h82
-rw-r--r--ArmPkg/Include/Library/ArmLib.h1134
-rw-r--r--ArmPkg/Include/Library/ArmV7ArchTimerLib.h230
-rw-r--r--ArmPkg/Include/Library/DefaultExceptionHandlerLib.h62
-rw-r--r--ArmPkg/Include/Library/SemihostLib.h200
-rw-r--r--ArmPkg/Include/Library/UncachedMemoryAllocationLib.h1330
-rw-r--r--ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.c250
-rw-r--r--ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf74
-rwxr-xr-xArmPkg/Library/ArmDmaLib/ArmDmaLib.inf2
-rw-r--r--ArmPkg/Library/ArmLib/Arm11/Arm11LibMem.c266
-rw-r--r--ArmPkg/Library/ArmLib/Arm11/Arm11Support.S524
-rw-r--r--ArmPkg/Library/ArmLib/Arm11/Arm11Support.asm314
-rw-r--r--ArmPkg/Library/ArmLib/Arm9/Arm9Lib.c262
-rw-r--r--ArmPkg/Library/ArmLib/Arm9/Arm9Support.S306
-rw-r--r--ArmPkg/Library/ArmLib/Arm9/Arm9Support.asm306
-rw-r--r--ArmPkg/Library/ArmLib/ArmV7/ArmV7ArchTimer.c550
-rw-r--r--ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.c528
-rw-r--r--ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.h24
-rwxr-xr-xArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm122
-rwxr-xr-xArmPkg/Library/BaseMemoryLibVstm/Arm/CopyMem.asm140
-rwxr-xr-xArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.S2
-rwxr-xr-xArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.asm4
-rw-r--r--ArmPkg/Library/BdsLib/BdsAppLoader.c288
-rw-r--r--ArmPkg/Library/BdsLib/BdsFilePath.c1812
-rw-r--r--ArmPkg/Library/BdsLib/BdsHelper.c694
-rw-r--r--ArmPkg/Library/BdsLib/BdsInternal.h196
-rw-r--r--ArmPkg/Library/BdsLib/BdsLib.inf155
-rw-r--r--ArmPkg/Library/BdsLib/BdsLinuxAtag.c346
-rw-r--r--ArmPkg/Library/BdsLib/BdsLinuxLoader.c546
-rw-r--r--ArmPkg/Library/BdsLib/BdsLinuxLoader.h312
-rw-r--r--ArmPkg/Library/BdsLib/BdsLoadOption.c540
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/Llvm_int_lib.h198
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.S70
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.c166
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.S72
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.c168
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.S114
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.c192
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.S98
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.c196
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.S306
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.asm310
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.S98
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.c154
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.S64
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c156
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/lasr.asm82
-rwxr-xr-xArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.S118
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.asm116
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.S40
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm86
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.S40
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm88
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.S70
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.c166
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.S68
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.asm80
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy4.asm122
-rwxr-xr-xArmPkg/Library/CompilerIntrinsicsLib/Arm/memmove.asm108
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.S76
-rwxr-xr-xArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.asm118
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.S92
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.c154
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.S54
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.c140
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.S116
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.c196
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/mullu.asm98
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch.asm58
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch16.S62
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch32.S60
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch8.S56
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/switchu8.S58
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.S76
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.c164
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.S54
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.c142
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.S484
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.c574
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.S114
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.c222
-rwxr-xr-xArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.S534
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.asm536
-rwxr-xr-xArmPkg/Library/CompilerIntrinsicsLib/Arm/uldivmod.c86
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.S58
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.c144
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.S56
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.c136
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/Arm/uwrite.asm136
-rw-r--r--ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf208
-rw-r--r--ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S552
-rwxr-xr-xArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf78
-rw-r--r--ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf2
-rw-r--r--ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf82
-rwxr-xr-xArmPkg/Library/SemihostLib/Arm/GccSemihost.S78
-rw-r--r--ArmPkg/Library/SemihostLib/Arm/SemihostPrivate.h368
-rw-r--r--ArmPkg/Library/SemihostLib/SemihostLib.inf6
-rw-r--r--ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf2
-rw-r--r--ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc715
-rw-r--r--ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf498
-rw-r--r--ArmPlatformPkg/ArmPlatformPkg.dec2
-rw-r--r--ArmPlatformPkg/ArmPlatformPkg.dsc4
-rw-r--r--ArmPlatformPkg/ArmPlatformPkg.fdf612
-rw-r--r--ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf620
-rw-r--r--ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbLibRTSM/ArmRealViewEb.c292
-rw-r--r--ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbSecLibRTSM/ArmRealViewEbSec.c152
-rw-r--r--ArmPlatformPkg/ArmRealViewEbPkg/Library/NorFlashArmRealViewEbLib/NorFlashArmRealViewEbLib.inf70
-rw-r--r--ArmPlatformPkg/ArmRealViewEbPkg/Library/PL111LcdArmRealViewEbLib/PL111LcdArmRealViewEbLib.inf130
-rw-r--r--ArmPlatformPkg/ArmRealViewEbPkg/Library/SysConfigArmRealViewEbLib/SysConfigArmRealViewEbLib.inf68
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15-A7.dsc12
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15x2.dsc11
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA5s.dsc11
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA9x4.dsc8
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf636
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15_MPCore.fdf636
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/ArmVExpressLib.inf110
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c435
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSM.c326
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSMMem.c2
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibCTA9x4/CTA9x4Sec.c296
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/ArmVExpressSecLib.inf104
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/RTSMSec.c166
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf70
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/HdLcdArmVExpressLib/HdLcdArmVExpressLib.inf2
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf64
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/PL111LcdArmVExpressLib/PL111LcdArmVExpressLib.inf86
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.c162
-rw-r--r--ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.inf70
-rw-r--r--ArmPlatformPkg/Bds/Bds.c9
-rw-r--r--ArmPlatformPkg/Bds/Bds.inf153
-rw-r--r--ArmPlatformPkg/Bds/BdsHelper.c634
-rw-r--r--ArmPlatformPkg/Bds/BootMenu.c82
-rw-r--r--ArmPlatformPkg/Bds/BootOption.c8
-rw-r--r--ArmPlatformPkg/Bds/BootOptionSupport.c17
-rw-r--r--ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c1764
-rw-r--r--ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c752
-rw-r--r--ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf112
-rw-r--r--ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c238
-rw-r--r--ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c1602
-rw-r--r--ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.h632
-rw-r--r--ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf136
-rw-r--r--ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvbDxe.c1624
-rw-r--r--ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c688
-rw-r--r--ArmPlatformPkg/Drivers/PL061GpioDxe/PL061GpioDxe.inf100
-rw-r--r--ArmPlatformPkg/Drivers/SP804TimerDxe/SP804Timer.c790
-rw-r--r--ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf118
-rw-r--r--ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c774
-rw-r--r--ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf104
-rw-r--r--ArmPlatformPkg/Include/Drivers/PL111Lcd.h280
-rw-r--r--ArmPlatformPkg/Include/Drivers/PL301Axi.h42
-rw-r--r--ArmPlatformPkg/Include/Drivers/PL341Dmc.h672
-rw-r--r--ArmPlatformPkg/Include/Guid/ArmGlobalVariableHob.h96
-rw-r--r--ArmPlatformPkg/Include/Library/ArmPlatformGlobalVariableLib.h76
-rw-r--r--ArmPlatformPkg/Include/Library/ArmPlatformLib.h262
-rw-r--r--ArmPlatformPkg/Include/Library/ArmPlatformSecLib.h176
-rw-r--r--ArmPlatformPkg/Include/Library/ArmPlatformSysConfigLib.h126
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.c152
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf88
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.c168
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.inf80
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.c210
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Sec/SecArmPlatformGlobalVariableLib.c162
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.S30
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.asm35
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.c328
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf4
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNullSec.inf44
-rw-r--r--ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c148
-rw-r--r--ArmPlatformPkg/Library/ArmTrustedMonitorLibNull/ArmTrustedMonitorLibNull.c4
-rwxr-xr-xArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf110
-rw-r--r--ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.c6
-rw-r--r--ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.c368
-rw-r--r--ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c147
-rw-r--r--ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.inf6
-rw-r--r--ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.c520
-rw-r--r--ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.inf88
-rwxr-xr-xArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf132
-rwxr-xr-xArmPlatformPkg/PlatformPei/PlatformPeiLib.inf106
-rwxr-xr-xArmPlatformPkg/PrePi/ModuleEntryPoint.S7
-rw-r--r--ArmPlatformPkg/PrePi/ModuleEntryPoint.asm7
-rw-r--r--ArmPlatformPkg/Scripts/Ds5/build_report.py108
-rw-r--r--ArmPlatformPkg/Scripts/Ds5/cmd_load_symbols.py14
-rw-r--r--ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py438
-rw-r--r--ArmPlatformPkg/Scripts/Ds5/firmware_volume.py613
-rw-r--r--ArmPlatformPkg/Scripts/Ds5/system_table.py268
-rw-r--r--ArmPlatformPkg/Sec/Sec.c390
-rw-r--r--ArmPlatformPkg/Sec/SecInternal.h4
-rw-r--r--BaseTools/Source/C/VfrCompile/VfrError.cpp3
-rw-r--r--BaseTools/Source/C/VfrCompile/VfrError.h3
-rw-r--r--BaseTools/Source/C/VfrCompile/VfrFormPkg.cpp16
-rw-r--r--BaseTools/Source/C/VfrCompile/VfrSyntax.g164
-rw-r--r--BaseTools/Source/C/VfrCompile/VfrUtilityLib.cpp453
-rw-r--r--BaseTools/Source/C/VfrCompile/VfrUtilityLib.h31
-rw-r--r--BaseTools/Source/Python/GenFds/FdfParser.py20
-rwxr-xr-xBaseTools/Source/Python/GenFds/FfsFileStatement.py2
-rw-r--r--BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py15
-rw-r--r--BaseTools/Source/Python/GenFds/VerSection.py2
-rw-r--r--BeagleBoardPkg/BeagleBoardPkg.dec72
-rwxr-xr-xBeagleBoardPkg/Library/BeagleBoardLib/BeagleBoard.c270
-rwxr-xr-xBeagleBoardPkg/Library/BeagleBoardLib/BeagleBoardLib.inf106
-rw-r--r--BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.c206
-rw-r--r--BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.inf82
-rw-r--r--BeagleBoardPkg/Sec/Cache.c2
-rw-r--r--BeagleBoardPkg/Sec/Sec.inf146
-rw-r--r--BeagleBoardPkg/Tools/generate_image.c816
-rw-r--r--EmbeddedPkg/Ebl/Ebl.h414
-rw-r--r--EmbeddedPkg/EmbeddedPkg.dsc524
-rw-r--r--EmbeddedPkg/GdbStub/GdbStub.c2526
-rw-r--r--EmbeddedPkg/GdbStub/GdbStubInternal.h1492
-rw-r--r--EmbeddedPkg/GdbStub/Ia32/Processor.c1986
-rw-r--r--EmbeddedPkg/GdbStub/SerialIo.c1102
-rwxr-xr-xEmbeddedPkg/Include/Library/DebugAgentTimerLib.h2
-rwxr-xr-xEmbeddedPkg/Include/Library/DmaLib.h144
-rw-r--r--EmbeddedPkg/Include/Library/EblAddExternalCommandLib.h244
-rw-r--r--EmbeddedPkg/Include/Library/EblCmdLib.h96
-rw-r--r--EmbeddedPkg/Include/Library/EblNetworkLib.h136
-rw-r--r--EmbeddedPkg/Include/Library/GdbSerialLib.h214
-rw-r--r--EmbeddedPkg/Include/Library/PrePiLib.h1580
-rw-r--r--EmbeddedPkg/Include/Library/SerialPortExtLib.h132
-rw-r--r--EmbeddedPkg/Include/Protocol/EblAddCommand.h10
-rw-r--r--EmbeddedPkg/Include/Protocol/EmbeddedExternalDevice.h188
-rw-r--r--EmbeddedPkg/Include/Protocol/EmbeddedGpio.h334
-rw-r--r--EmbeddedPkg/Include/fdt.h148
-rw-r--r--EmbeddedPkg/Include/libfdt.h2956
-rw-r--r--EmbeddedPkg/Include/libfdt_env.h154
-rwxr-xr-xEmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLib.c2
-rw-r--r--EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf2
-rw-r--r--EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf2
-rw-r--r--EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.c346
-rw-r--r--EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf2
-rw-r--r--EmbeddedPkg/Library/EfiFileLib/EfiFileLib.c3556
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt.c444
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt_empty_tree.c168
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt_ro.c1150
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt_rw.c990
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt_strerror.c192
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt_sw.c512
-rw-r--r--EmbeddedPkg/Library/FdtLib/fdt_wip.c236
-rw-r--r--EmbeddedPkg/Library/FdtLib/libfdt_internal.h190
-rwxr-xr-xEmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.S516
-rwxr-xr-xEmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.asm518
-rwxr-xr-xEmbeddedPkg/Library/GdbDebugAgent/Arm/Processor.c104
-rwxr-xr-xEmbeddedPkg/Library/GdbDebugAgent/GdbDebugAgent.h1398
-rwxr-xr-xEmbeddedPkg/Library/GdbDebugAgent/Ia32/Processor.c1824
-rwxr-xr-xEmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf2
-rw-r--r--EmbeddedPkg/Library/PrePiHobLib/Hob.c1704
-rw-r--r--EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c10
-rw-r--r--EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf2
-rw-r--r--EmbeddedPkg/Library/PrePiLib/FwVol.c1684
-rw-r--r--EmbeddedPkg/Library/PrePiLib/PrePi.h92
-rw-r--r--EmbeddedPkg/Library/PrePiLib/PrePiLib.c452
-rw-r--r--EmbeddedPkg/Library/PrePiLib/ReportStatusCode.c654
-rw-r--r--EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf2
-rw-r--r--EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf2
-rw-r--r--EmbeddedPkg/TemplateSec/TemplateSec.inf130
-rw-r--r--EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf2
-rw-r--r--IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/BiosVideo.c108
-rw-r--r--IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VesaBiosExtensions.h25
-rw-r--r--IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c6
-rw-r--r--IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c6
-rw-r--r--IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c3
-rw-r--r--MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c9
-rw-r--r--MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c9
-rw-r--r--MdeModulePkg/Core/Pei/Image/Image.c27
-rw-r--r--MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c4
-rw-r--r--MdeModulePkg/Library/UefiHiiLib/HiiLib.c7
-rw-r--r--MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c10
-rw-r--r--MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveState.c27
-rw-r--r--MdeModulePkg/Universal/Acpi/SmmS3SaveState/SmmS3SaveState.c27
-rw-r--r--MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsole.c6
-rw-r--r--MdeModulePkg/Universal/Disk/PartitionDxe/Mbr.c9
-rw-r--r--MdeModulePkg/Universal/DriverSampleDxe/DriverSample.c51
-rw-r--r--MdeModulePkg/Universal/DriverSampleDxe/DriverSample.h3
-rw-r--r--MdeModulePkg/Universal/DriverSampleDxe/DriverSampleDxe.inf3
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/Expression.c27
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/Presentation.c4
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/Setup.c12
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/Setup.h6
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf3
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserStr.unibin14292 -> 14784 bytes
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/Ui.c344
-rw-r--r--MdeModulePkg/Universal/SetupBrowserDxe/Ui.h15
-rw-r--r--MdeModulePkg/Universal/Variable/Pei/Variable.c59
-rw-r--r--MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c125
-rw-r--r--MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h13
-rw-r--r--MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c96
-rw-r--r--MdePkg/Library/BaseLib/Ia32/Thunk16.S4
-rw-r--r--MdePkg/Library/BaseLib/Ia32/Thunk16.asm4
-rw-r--r--MdePkg/Library/BaseLib/X64/Thunk16.S4
-rw-r--r--MdePkg/Library/BaseLib/X64/Thunk16.asm4
-rw-r--r--MdePkg/Library/UefiLib/Console.c25
-rw-r--r--NetworkPkg/Dhcp6Dxe/Dhcp6Impl.c6
-rw-r--r--NetworkPkg/Dhcp6Dxe/Dhcp6Impl.h4
-rw-r--r--NetworkPkg/Dhcp6Dxe/Dhcp6Io.c194
-rw-r--r--NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c148
-rw-r--r--NetworkPkg/Dhcp6Dxe/Dhcp6Utility.h7
-rw-r--r--NetworkPkg/Ip6Dxe/Ip6ConfigNv.c483
-rw-r--r--NetworkPkg/Ip6Dxe/Ip6NvData.h4
-rw-r--r--Omap35xxPkg/Flash/Flash.c1560
-rw-r--r--Omap35xxPkg/Flash/Flash.h212
-rw-r--r--Omap35xxPkg/Flash/Flash.inf96
-rw-r--r--Omap35xxPkg/Gpio/Gpio.c270
-rw-r--r--Omap35xxPkg/Gpio/Gpio.inf90
-rwxr-xr-xOmap35xxPkg/Include/Library/OmapDmaLib.h94
-rw-r--r--Omap35xxPkg/Include/Library/OmapLib.h88
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530.h80
-rwxr-xr-xOmap35xxPkg/Include/Omap3530/Omap3530Dma.h260
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530Gpio.h262
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530Gpmc.h214
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530I2c.h124
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530Interrupt.h96
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530MMCHS.h428
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530PadConfiguration.h606
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530Prcm.h330
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530Timer.h164
-rw-r--r--Omap35xxPkg/Include/Omap3530/Omap3530Usb.h86
-rw-r--r--Omap35xxPkg/Include/TPS65950.h160
-rw-r--r--Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c890
-rw-r--r--Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c806
-rw-r--r--Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h314
-rw-r--r--Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf104
-rwxr-xr-xOmap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c100
-rwxr-xr-xOmap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.inf8
-rw-r--r--Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.c204
-rw-r--r--Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.inf82
-rwxr-xr-xOmap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf2
-rwxr-xr-xOmap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.c594
-rwxr-xr-xOmap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.inf76
-rw-r--r--Omap35xxPkg/MMCHSDxe/MMCHS.c2990
-rw-r--r--Omap35xxPkg/MMCHSDxe/MMCHS.h54
-rw-r--r--Omap35xxPkg/MMCHSDxe/MMCHS.inf108
-rwxr-xr-xOmap35xxPkg/MmcHostDxe/MmcHostDxe.c1354
-rwxr-xr-xOmap35xxPkg/MmcHostDxe/MmcHostDxe.h88
-rwxr-xr-xOmap35xxPkg/MmcHostDxe/MmcHostDxe.inf106
-rw-r--r--Omap35xxPkg/Omap35xxPkg.dsc376
-rw-r--r--Omap35xxPkg/PciEmulation/PciEmulation.c1048
-rw-r--r--Omap35xxPkg/PciEmulation/PciEmulation.h2
-rw-r--r--Omap35xxPkg/PciEmulation/PciEmulation.inf2
-rw-r--r--Omap35xxPkg/SmbusDxe/Smbus.c650
-rw-r--r--Omap35xxPkg/SmbusDxe/Smbus.inf90
-rw-r--r--Omap35xxPkg/TPS65950Dxe/TPS65950.c232
-rw-r--r--Omap35xxPkg/TPS65950Dxe/TPS65950.inf96
-rw-r--r--Omap35xxPkg/TimerDxe/Timer.c752
-rw-r--r--Omap35xxPkg/TimerDxe/TimerDxe.inf114
-rw-r--r--OvmfPkg/Include/Library/LoadLinuxLib.h22
-rw-r--r--OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.S19
-rw-r--r--OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.asm21
-rw-r--r--OvmfPkg/Library/LoadLinuxLib/Linux.c51
-rw-r--r--OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.h11
-rw-r--r--OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.S67
-rw-r--r--OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.asm69
-rw-r--r--OvmfPkg/Library/PlatformBdsLib/QemuKernel.c7
-rwxr-xr-xOvmfPkg/build.sh32
-rwxr-xr-xPandaBoardPkg/Tools/chtoolbin0 -> 42621 bytes
-rwxr-xr-xPandaBoardPkg/build.sh28
-rw-r--r--SamsungPlatformPkg/ArndaleBoardPkg/ArndaleBoardPkg.dsc.inc12
-rwxr-xr-xSamsungPlatformPkg/ArndaleBoardPkg/arndale-Exynos5250.dsc5
-rw-r--r--SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/DisplayDxe/DisplayDxe.c3
-rwxr-xr-xSamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/SDHCDxe_EVT1/SDHCDxe.c9
-rwxr-xr-xSamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.c7
-rwxr-xr-xSamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.h2
-rw-r--r--SamsungPlatformPkg/ExynosPkg/Exynos5250/Sec/SecEntryPoint.S2
-rw-r--r--SecurityPkg/Library/DxeTcgPhysicalPresenceLib/DxeTcgPhysicalPresenceLib.c16
-rw-r--r--SecurityPkg/VariableAuthenticated/Pei/Variable.c59
-rw-r--r--SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c81
-rw-r--r--SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c533
-rw-r--r--SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.h44
-rw-r--r--SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableSmmRuntimeDxe.c96
-rw-r--r--SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfig.vfr11
-rw-r--r--SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c167
-rw-r--r--SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigNvData.h4
-rw-r--r--SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigStrings.unibin9518 -> 10086 bytes
-rw-r--r--ShellPkg/Application/Shell/ShellParametersProtocol.c4
-rw-r--r--ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c2
-rw-r--r--ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c2
-rw-r--r--ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c6
-rw-r--r--ShellPkg/Library/UefiShellLib/UefiShellLib.c35
-rw-r--r--SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.c101
-rw-r--r--SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.inf48
-rw-r--r--SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.c45
-rw-r--r--SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.inf44
-rw-r--r--SourceLevelDebugPkg/Include/ImageDebugSupport.h3
-rw-r--r--SourceLevelDebugPkg/Include/TransferProtocol.h22
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c999
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h287
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.c97
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.h37
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugTimer.c27
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/ArchDebugSupport.c56
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.S5
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.asm5
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/ArchDebugSupport.c54
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.S5
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.asm5
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.c449
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.h15
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c246
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf10
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.c364
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.h40
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf10
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgent/SmmDebugAgentLib.c193
-rw-r--r--SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf11
-rw-r--r--SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c184
-rw-r--r--SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf10
-rw-r--r--SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c228
-rw-r--r--SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.inf5
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.S28
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.asm33
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c96
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.c61
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h74
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf13
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.S28
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.asm29
-rw-r--r--SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c98
-rw-r--r--SourceLevelDebugPkg/SourceLevelDebugPkg.dec8
-rw-r--r--SourceLevelDebugPkg/SourceLevelDebugPkg.dsc41
-rw-r--r--StdLib/ISSUES.txt54
-rw-r--r--StdLib/Include/Containers/Fifo.h4
-rw-r--r--StdLib/LibC/Uefi/InteractiveIO/IIOutilities.c16
447 files changed, 61955 insertions, 51279 deletions
diff --git a/AppPkg/Applications/Main/Main.c b/AppPkg/Applications/Main/Main.c
index c2762d57d..f588a30fb 100644
--- a/AppPkg/Applications/Main/Main.c
+++ b/AppPkg/Applications/Main/Main.c
@@ -32,7 +32,6 @@
@retval Other An error occurred.
***/
int
-EFIAPI
main (
IN int Argc,
IN char **Argv
diff --git a/AppPkg/Applications/Python/Efi/config.c b/AppPkg/Applications/Python/Efi/config.c
index 7ae26319b..7cc021c96 100644
--- a/AppPkg/Applications/Python/Efi/config.c
+++ b/AppPkg/Applications/Python/Efi/config.c
@@ -17,46 +17,59 @@
#include "Python.h"
extern void initarray(void);
+extern void init_ast(void);
extern void initbinascii(void);
+extern void init_bisect(void);
extern void initcmath(void);
+extern void init_codecs(void);
+extern void init_collections(void);
+extern void initcPickle(void);
+extern void initcStringIO(void);
+extern void init_csv(void);
+extern void init_ctypes(void);
+extern void initdatetime(void);
+extern void initedk2(void);
extern void initerrno(void);
+extern void init_functools(void);
extern void initfuture_builtins(void);
extern void initgc(void);
+extern void init_heapq(void);
+extern void init_hotshot(void);
+extern void initimp(void);
+extern void init_io(void);
+extern void inititertools(void);
+extern void init_json(void);
+extern void init_lsprof(void);
extern void initmath(void);
extern void init_md5(void);
-extern void initedk2(void);
+extern void initmmap(void);
extern void initoperator(void);
-extern void initsignal(void);
+extern void initparser(void);
+extern void initpyexpat(void);
+extern void init_random(void);
+extern void initselect(void);
extern void init_sha(void);
extern void init_sha256(void);
extern void init_sha512(void);
+extern void initsignal(void);
+extern void init_socket(void);
+extern void init_sre(void);
extern void initstrop(void);
-extern void inittime(void);
+extern void init_struct(void);
+extern void init_subprocess(void);
+extern void init_symtable(void);
extern void initthread(void);
-extern void initcStringIO(void);
-extern void initcPickle(void);
-extern void init_codecs(void);
+extern void inittime(void);
+extern void initunicodedata(void);
extern void init_weakref(void);
-extern void init_hotshot(void);
+extern void init_winreg(void);
extern void initxxsubtype(void);
extern void initzipimport(void);
-extern void init_random(void);
-extern void inititertools(void);
-extern void init_collections(void);
-extern void init_heapq(void);
-extern void init_bisect(void);
-extern void init_symtable(void);
-extern void initmmap(void);
-extern void init_csv(void);
-extern void init_sre(void);
-extern void initparser(void);
-extern void init_winreg(void);
-extern void init_struct(void);
-extern void initdatetime(void);
-extern void init_functools(void);
-extern void init_json(void);
extern void initzlib(void);
+extern void PyMarshal_Init(void);
+extern void _PyWarnings_Init(void);
+
extern void init_multibytecodec(void);
extern void init_codecs_cn(void);
extern void init_codecs_hk(void);
@@ -64,26 +77,13 @@ extern void init_codecs_iso2022(void);
extern void init_codecs_jp(void);
extern void init_codecs_kr(void);
extern void init_codecs_tw(void);
-extern void init_subprocess(void);
-extern void init_lsprof(void);
-extern void init_ast(void);
-extern void init_io(void);
-extern void _PyWarnings_Init(void);
-
-extern void init_socket(void);
-extern void initselect(void);
-
-extern void PyMarshal_Init(void);
-extern void initimp(void);
-extern void initunicodedata(void);
-extern void init_ctypes(void);
struct _inittab _PyImport_Inittab[] = {
//{"_ast", init_ast},
- //{"_bisect", init_bisect}, /* A fast version of bisect.py */
+ //{"_bisect", init_bisect}, /* A fast version of bisect.py */
//{"_csv", init_csv},
- //{"_heapq", init_heapq}, /* A fast version of heapq.py */
+ //{"_heapq", init_heapq}, /* A fast version of heapq.py */
//{"_io", init_io},
//{"_json", init_json},
//{"_md5", init_md5},
@@ -99,9 +99,10 @@ struct _inittab _PyImport_Inittab[] = {
//{"datetime", initdatetime},
//{"future_builtins", initfuture_builtins},
//{"parser", initparser},
+ //{"pyexpat", initpyexpat},
//{"select", initselect},
//{"signal", initsignal},
- //{"strop", initstrop}, /* redefines some string operations that are 100-1000 times faster */
+ //{"strop", initstrop}, /* redefines some string operations that are 100-1000 times faster */
//{"unicodedata", initunicodedata},
//{"xxsubtype", initxxsubtype},
//{"zipimport", initzipimport},
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h
new file mode 100644
index 000000000..b73959580
--- /dev/null
+++ b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/expat_external.h
@@ -0,0 +1,121 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
+ See the file COPYING for copying permission.
+*/
+
+#ifndef Expat_External_INCLUDED
+#define Expat_External_INCLUDED 1
+
+/* External API definitions */
+
+/* Namespace external symbols to allow multiple libexpat version to
+ co-exist. */
+#if !defined(UEFI_C_SOURCE)
+ #include "pyexpatns.h"
+#endif
+
+#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
+#define XML_USE_MSC_EXTENSIONS 1
+#endif
+
+/* Expat tries very hard to make the API boundary very specifically
+ defined. There are two macros defined to control this boundary;
+ each of these can be defined before including this header to
+ achieve some different behavior, but doing so it not recommended or
+ tested frequently.
+
+ XMLCALL - The calling convention to use for all calls across the
+ "library boundary." This will default to cdecl, and
+ try really hard to tell the compiler that's what we
+ want.
+
+ XMLIMPORT - Whatever magic is needed to note that a function is
+ to be imported from a dynamically loaded library
+ (.dll, .so, or .sl, depending on your platform).
+
+ The XMLCALL macro was added in Expat 1.95.7. The only one which is
+ expected to be directly useful in client code is XMLCALL.
+
+ Note that on at least some Unix versions, the Expat library must be
+ compiled with the cdecl calling convention as the default since
+ system headers may assume the cdecl convention.
+*/
+#ifndef XMLCALL
+#if defined(XML_USE_MSC_EXTENSIONS)
+#define XMLCALL __cdecl
+#elif defined(__GNUC__) && defined(__i386)
+#define XMLCALL __attribute__((cdecl))
+#else
+/* For any platform which uses this definition and supports more than
+ one calling convention, we need to extend this definition to
+ declare the convention used on that platform, if it's possible to
+ do so.
+
+ If this is the case for your platform, please file a bug report
+ with information on how to identify your platform via the C
+ pre-processor and how to specify the same calling convention as the
+ platform's malloc() implementation.
+*/
+#define XMLCALL
+#endif
+#endif /* not defined XMLCALL */
+
+
+#if !defined(XML_STATIC) && !defined(XMLIMPORT)
+#ifndef XML_BUILDING_EXPAT
+/* using Expat from an application */
+
+#ifdef XML_USE_MSC_EXTENSIONS
+#define XMLIMPORT __declspec(dllimport)
+#endif
+
+#endif
+#endif /* not defined XML_STATIC */
+
+
+/* If we didn't define it above, define it away: */
+#ifndef XMLIMPORT
+#define XMLIMPORT
+#endif
+
+
+#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef XML_UNICODE_WCHAR_T
+#define XML_UNICODE
+#endif
+
+#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
+#ifdef XML_UNICODE_WCHAR_T
+typedef wchar_t XML_Char;
+typedef wchar_t XML_LChar;
+#else
+typedef unsigned short XML_Char;
+typedef char XML_LChar;
+#endif /* XML_UNICODE_WCHAR_T */
+#else /* Information is UTF-8 encoded. */
+typedef char XML_Char;
+typedef char XML_LChar;
+#endif /* XML_UNICODE */
+
+#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
+#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
+typedef __int64 XML_Index;
+typedef unsigned __int64 XML_Size;
+#else
+typedef long long XML_Index;
+typedef unsigned long long XML_Size;
+#endif
+#else
+typedef long XML_Index;
+typedef unsigned long XML_Size;
+#endif /* XML_LARGE_SIZE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* not Expat_External_INCLUDED */
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c
new file mode 100644
index 000000000..e303c7a7b
--- /dev/null
+++ b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/expat/xmlparse.c
@@ -0,0 +1,6279 @@
+/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
+ See the file COPYING for copying permission.
+*/
+
+#define XML_BUILDING_EXPAT 1
+
+#ifdef COMPILED_FROM_DSP
+#include "winconfig.h"
+#elif defined(MACOS_CLASSIC)
+#include "macconfig.h"
+#elif defined(__amigaos4__)
+#include "amigaconfig.h"
+#elif defined(HAVE_EXPAT_CONFIG_H)
+#include <expat_config.h>
+#endif /* ndef COMPILED_FROM_DSP */
+
+#include <stddef.h>
+#include <string.h> /* memset(), memcpy() */
+#include <assert.h>
+
+#if defined(UEFI_C_SOURCE)
+ #include <expat/expat.h>
+#else
+ #include "expat.h"
+#endif
+
+#ifdef XML_UNICODE
+#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
+#define XmlConvert XmlUtf16Convert
+#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
+#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
+#define XmlEncode XmlUtf16Encode
+#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((unsigned long)s) & 1))
+typedef unsigned short ICHAR;
+#else
+#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
+#define XmlConvert XmlUtf8Convert
+#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
+#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
+#define XmlEncode XmlUtf8Encode
+#define MUST_CONVERT(enc, s) (!(enc)->isUtf8)
+typedef char ICHAR;
+#endif
+
+
+#ifndef XML_NS
+
+#define XmlInitEncodingNS XmlInitEncoding
+#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
+#undef XmlGetInternalEncodingNS
+#define XmlGetInternalEncodingNS XmlGetInternalEncoding
+#define XmlParseXmlDeclNS XmlParseXmlDecl
+
+#endif
+
+#ifdef XML_UNICODE
+
+#ifdef XML_UNICODE_WCHAR_T
+#define XML_T(x) (const wchar_t)x
+#define XML_L(x) L ## x
+#else
+#define XML_T(x) (const unsigned short)x
+#define XML_L(x) x
+#endif
+
+#else
+
+#define XML_T(x) x
+#define XML_L(x) x
+
+#endif
+
+/* Round up n to be a multiple of sz, where sz is a power of 2. */
+#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
+
+/* Handle the case where memmove() doesn't exist. */
+#ifndef HAVE_MEMMOVE
+#ifdef HAVE_BCOPY
+#define memmove(d,s,l) bcopy((s),(d),(l))
+#else
+#error memmove does not exist on this platform, nor is a substitute available
+#endif /* HAVE_BCOPY */
+#endif /* HAVE_MEMMOVE */
+
+#include "internal.h"
+#include "xmltok.h"
+#include "xmlrole.h"
+
+typedef const XML_Char *KEY;
+
+typedef struct {
+ KEY name;
+} NAMED;
+
+typedef struct {
+ NAMED **v;
+ unsigned char power;
+ size_t size;
+ size_t used;
+ const XML_Memory_Handling_Suite *mem;
+} HASH_TABLE;
+
+/* Basic character hash algorithm, taken from Python's string hash:
+ h = h * 1000003 ^ character, the constant being a prime number.
+
+*/
+#ifdef XML_UNICODE
+#define CHAR_HASH(h, c) \
+ (((h) * 0xF4243) ^ (unsigned short)(c))
+#else
+#define CHAR_HASH(h, c) \
+ (((h) * 0xF4243) ^ (unsigned char)(c))
+#endif
+
+/* For probing (after a collision) we need a step size relative prime
+ to the hash table size, which is a power of 2. We use double-hashing,
+ since we can calculate a second hash value cheaply by taking those bits
+ of the first hash value that were discarded (masked out) when the table
+ index was calculated: index = hash & mask, where mask = table->size - 1.
+ We limit the maximum step size to table->size / 4 (mask >> 2) and make
+ it odd, since odd numbers are always relative prime to a power of 2.
+*/
+#define SECOND_HASH(hash, mask, power) \
+ ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
+#define PROBE_STEP(hash, mask, power) \
+ ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
+
+typedef struct {
+ NAMED **p;
+ NAMED **end;
+} HASH_TABLE_ITER;
+
+#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
+#define INIT_DATA_BUF_SIZE 1024
+#define INIT_ATTS_SIZE 16
+#define INIT_ATTS_VERSION 0xFFFFFFFF
+#define INIT_BLOCK_SIZE 1024
+#define INIT_BUFFER_SIZE 1024
+
+#define EXPAND_SPARE 24
+
+typedef struct binding {
+ struct prefix *prefix;
+ struct binding *nextTagBinding;
+ struct binding *prevPrefixBinding;
+ const struct attribute_id *attId;
+ XML_Char *uri;
+ int uriLen;
+ int uriAlloc;
+} BINDING;
+
+typedef struct prefix {
+ const XML_Char *name;
+ BINDING *binding;
+} PREFIX;
+
+typedef struct {
+ const XML_Char *str;
+ const XML_Char *localPart;
+ const XML_Char *prefix;
+ int strLen;
+ int uriLen;
+ int prefixLen;
+} TAG_NAME;
+
+/* TAG represents an open element.
+ The name of the element is stored in both the document and API
+ encodings. The memory buffer 'buf' is a separately-allocated
+ memory area which stores the name. During the XML_Parse()/
+ XMLParseBuffer() when the element is open, the memory for the 'raw'
+ version of the name (in the document encoding) is shared with the
+ document buffer. If the element is open across calls to
+ XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
+ contain the 'raw' name as well.
+
+ A parser re-uses these structures, maintaining a list of allocated
+ TAG objects in a free list.
+*/
+typedef struct tag {
+ struct tag *parent; /* parent of this element */
+ const char *rawName; /* tagName in the original encoding */
+ int rawNameLength;
+ TAG_NAME name; /* tagName in the API encoding */
+ char *buf; /* buffer for name components */
+ char *bufEnd; /* end of the buffer */
+ BINDING *bindings;
+} TAG;
+
+typedef struct {
+ const XML_Char *name;
+ const XML_Char *textPtr;
+ int textLen; /* length in XML_Chars */
+ int processed; /* # of processed bytes - when suspended */
+ const XML_Char *systemId;
+ const XML_Char *base;
+ const XML_Char *publicId;
+ const XML_Char *notation;
+ XML_Bool open;
+ XML_Bool is_param;
+ XML_Bool is_internal; /* true if declared in internal subset outside PE */
+} ENTITY;
+
+typedef struct {
+ enum XML_Content_Type type;
+ enum XML_Content_Quant quant;
+ const XML_Char * name;
+ int firstchild;
+ int lastchild;
+ int childcnt;
+ int nextsib;
+} CONTENT_SCAFFOLD;
+
+#define INIT_SCAFFOLD_ELEMENTS 32
+
+typedef struct block {
+ struct block *next;
+ int size;
+ XML_Char s[1];
+} BLOCK;
+
+typedef struct {
+ BLOCK *blocks;
+ BLOCK *freeBlocks;
+ const XML_Char *end;
+ XML_Char *ptr;
+ XML_Char *start;
+ const XML_Memory_Handling_Suite *mem;
+} STRING_POOL;
+
+/* The XML_Char before the name is used to determine whether
+ an attribute has been specified. */
+typedef struct attribute_id {
+ XML_Char *name;
+ PREFIX *prefix;
+ XML_Bool maybeTokenized;
+ XML_Bool xmlns;
+} ATTRIBUTE_ID;
+
+typedef struct {
+ const ATTRIBUTE_ID *id;
+ XML_Bool isCdata;
+ const XML_Char *value;
+} DEFAULT_ATTRIBUTE;
+
+typedef struct {
+ unsigned long version;
+ unsigned long hash;
+ const XML_Char *uriName;
+} NS_ATT;
+
+typedef struct {
+ const XML_Char *name;
+ PREFIX *prefix;
+ const ATTRIBUTE_ID *idAtt;
+ int nDefaultAtts;
+ int allocDefaultAtts;
+ DEFAULT_ATTRIBUTE *defaultAtts;
+} ELEMENT_TYPE;
+
+typedef struct {
+ HASH_TABLE generalEntities;
+ HASH_TABLE elementTypes;
+ HASH_TABLE attributeIds;
+ HASH_TABLE prefixes;
+ STRING_POOL pool;
+ STRING_POOL entityValuePool;
+ /* false once a parameter entity reference has been skipped */
+ XML_Bool keepProcessing;
+ /* true once an internal or external PE reference has been encountered;
+ this includes the reference to an external subset */
+ XML_Bool hasParamEntityRefs;
+ XML_Bool standalone;
+#ifdef XML_DTD
+ /* indicates if external PE has been read */
+ XML_Bool paramEntityRead;
+ HASH_TABLE paramEntities;
+#endif /* XML_DTD */
+ PREFIX defaultPrefix;
+ /* === scaffolding for building content model === */
+ XML_Bool in_eldecl;
+ CONTENT_SCAFFOLD *scaffold;
+ unsigned contentStringLen;
+ unsigned scaffSize;
+ unsigned scaffCount;
+ int scaffLevel;
+ int *scaffIndex;
+} DTD;
+
+typedef struct open_internal_entity {
+ const char *internalEventPtr;
+ const char *internalEventEndPtr;
+ struct open_internal_entity *next;
+ ENTITY *entity;
+ int startTagLevel;
+ XML_Bool betweenDecl; /* WFC: PE Between Declarations */
+} OPEN_INTERNAL_ENTITY;
+
+typedef enum XML_Error PTRCALL Processor(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr);
+
+static Processor prologProcessor;
+static Processor prologInitProcessor;
+static Processor contentProcessor;
+static Processor cdataSectionProcessor;
+#ifdef XML_DTD
+static Processor ignoreSectionProcessor;
+static Processor externalParEntProcessor;
+static Processor externalParEntInitProcessor;
+static Processor entityValueProcessor;
+static Processor entityValueInitProcessor;
+#endif /* XML_DTD */
+static Processor epilogProcessor;
+static Processor errorProcessor;
+static Processor externalEntityInitProcessor;
+static Processor externalEntityInitProcessor2;
+static Processor externalEntityInitProcessor3;
+static Processor externalEntityContentProcessor;
+static Processor internalEntityProcessor;
+
+static enum XML_Error
+handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName);
+static enum XML_Error
+processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
+ const char *s, const char *next);
+static enum XML_Error
+initializeEncoding(XML_Parser parser);
+static enum XML_Error
+doProlog(XML_Parser parser, const ENCODING *enc, const char *s,
+ const char *end, int tok, const char *next, const char **nextPtr,
+ XML_Bool haveMore);
+static enum XML_Error
+processInternalEntity(XML_Parser parser, ENTITY *entity,
+ XML_Bool betweenDecl);
+static enum XML_Error
+doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
+ const char *start, const char *end, const char **endPtr,
+ XML_Bool haveMore);
+static enum XML_Error
+doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr,
+ const char *end, const char **nextPtr, XML_Bool haveMore);
+#ifdef XML_DTD
+static enum XML_Error
+doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr,
+ const char *end, const char **nextPtr, XML_Bool haveMore);
+#endif /* XML_DTD */
+
+static enum XML_Error
+storeAtts(XML_Parser parser, const ENCODING *, const char *s,
+ TAG_NAME *tagNamePtr, BINDING **bindingsPtr);
+static enum XML_Error
+addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
+ const XML_Char *uri, BINDING **bindingsPtr);
+static int
+defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
+ XML_Bool isId, const XML_Char *dfltValue, XML_Parser parser);
+static enum XML_Error
+storeAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
+ const char *, const char *, STRING_POOL *);
+static enum XML_Error
+appendAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
+ const char *, const char *, STRING_POOL *);
+static ATTRIBUTE_ID *
+getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
+ const char *end);
+static int
+setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
+static enum XML_Error
+storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start,
+ const char *end);
+static int
+reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
+ const char *start, const char *end);
+static int
+reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
+ const char *end);
+static void
+reportDefault(XML_Parser parser, const ENCODING *enc, const char *start,
+ const char *end);
+
+static const XML_Char * getContext(XML_Parser parser);
+static XML_Bool
+setContext(XML_Parser parser, const XML_Char *context);
+
+static void FASTCALL normalizePublicId(XML_Char *s);
+
+static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms);
+/* do not call if parentParser != NULL */
+static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
+static void
+dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms);
+static int
+dtdCopy(DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms);
+static int
+copyEntityTable(HASH_TABLE *, STRING_POOL *, const HASH_TABLE *);
+
+static NAMED *
+lookup(HASH_TABLE *table, KEY name, size_t createSize);
+static void FASTCALL
+hashTableInit(HASH_TABLE *, const XML_Memory_Handling_Suite *ms);
+static void FASTCALL hashTableClear(HASH_TABLE *);
+static void FASTCALL hashTableDestroy(HASH_TABLE *);
+static void FASTCALL
+hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
+static NAMED * FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
+
+static void FASTCALL
+poolInit(STRING_POOL *, const XML_Memory_Handling_Suite *ms);
+static void FASTCALL poolClear(STRING_POOL *);
+static void FASTCALL poolDestroy(STRING_POOL *);
+static XML_Char *
+poolAppend(STRING_POOL *pool, const ENCODING *enc,
+ const char *ptr, const char *end);
+static XML_Char *
+poolStoreString(STRING_POOL *pool, const ENCODING *enc,
+ const char *ptr, const char *end);
+static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
+static const XML_Char * FASTCALL
+poolCopyString(STRING_POOL *pool, const XML_Char *s);
+static const XML_Char *
+poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n);
+static const XML_Char * FASTCALL
+poolAppendString(STRING_POOL *pool, const XML_Char *s);
+
+static int FASTCALL nextScaffoldPart(XML_Parser parser);
+static XML_Content * build_model(XML_Parser parser);
+static ELEMENT_TYPE *
+getElementType(XML_Parser parser, const ENCODING *enc,
+ const char *ptr, const char *end);
+
+static XML_Parser
+parserCreate(const XML_Char *encodingName,
+ const XML_Memory_Handling_Suite *memsuite,
+ const XML_Char *nameSep,
+ DTD *dtd);
+static void
+parserInit(XML_Parser parser, const XML_Char *encodingName);
+
+#define poolStart(pool) ((pool)->start)
+#define poolEnd(pool) ((pool)->ptr)
+#define poolLength(pool) ((pool)->ptr - (pool)->start)
+#define poolChop(pool) ((void)--(pool->ptr))
+#define poolLastChar(pool) (((pool)->ptr)[-1])
+#define poolDiscard(pool) ((pool)->ptr = (pool)->start)
+#define poolFinish(pool) ((pool)->start = (pool)->ptr)
+#define poolAppendChar(pool, c) \
+ (((pool)->ptr == (pool)->end && !poolGrow(pool)) \
+ ? 0 \
+ : ((*((pool)->ptr)++ = c), 1))
+
+struct XML_ParserStruct {
+ /* The first member must be userData so that the XML_GetUserData
+ macro works. */
+ void *m_userData;
+ void *m_handlerArg;
+ char *m_buffer;
+ const XML_Memory_Handling_Suite m_mem;
+ /* first character to be parsed */
+ const char *m_bufferPtr;
+ /* past last character to be parsed */
+ char *m_bufferEnd;
+ /* allocated end of buffer */
+ const char *m_bufferLim;
+ XML_Index m_parseEndByteIndex;
+ const char *m_parseEndPtr;
+ XML_Char *m_dataBuf;
+ XML_Char *m_dataBufEnd;
+ XML_StartElementHandler m_startElementHandler;
+ XML_EndElementHandler m_endElementHandler;
+ XML_CharacterDataHandler m_characterDataHandler;
+ XML_ProcessingInstructionHandler m_processingInstructionHandler;
+ XML_CommentHandler m_commentHandler;
+ XML_StartCdataSectionHandler m_startCdataSectionHandler;
+ XML_EndCdataSectionHandler m_endCdataSectionHandler;
+ XML_DefaultHandler m_defaultHandler;
+ XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
+ XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
+ XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
+ XML_NotationDeclHandler m_notationDeclHandler;
+ XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
+ XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
+ XML_NotStandaloneHandler m_notStandaloneHandler;
+ XML_ExternalEntityRefHandler m_externalEntityRefHandler;
+ XML_Parser m_externalEntityRefHandlerArg;
+ XML_SkippedEntityHandler m_skippedEntityHandler;
+ XML_UnknownEncodingHandler m_unknownEncodingHandler;
+ XML_ElementDeclHandler m_elementDeclHandler;
+ XML_AttlistDeclHandler m_attlistDeclHandler;
+ XML_EntityDeclHandler m_entityDeclHandler;
+ XML_XmlDeclHandler m_xmlDeclHandler;
+ const ENCODING *m_encoding;
+ INIT_ENCODING m_initEncoding;
+ const ENCODING *m_internalEncoding;
+ const XML_Char *m_protocolEncodingName;
+ XML_Bool m_ns;
+ XML_Bool m_ns_triplets;
+ void *m_unknownEncodingMem;
+ void *m_unknownEncodingData;
+ void *m_unknownEncodingHandlerData;
+ void (XMLCALL *m_unknownEncodingRelease)(void *);
+ PROLOG_STATE m_prologState;
+ Processor *m_processor;
+ enum XML_Error m_errorCode;
+ const char *m_eventPtr;
+ const char *m_eventEndPtr;
+ const char *m_positionPtr;
+ OPEN_INTERNAL_ENTITY *m_openInternalEntities;
+ OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
+ XML_Bool m_defaultExpandInternalEntities;
+ int m_tagLevel;
+ ENTITY *m_declEntity;
+ const XML_Char *m_doctypeName;
+ const XML_Char *m_doctypeSysid;
+ const XML_Char *m_doctypePubid;
+ const XML_Char *m_declAttributeType;
+ const XML_Char *m_declNotationName;
+ const XML_Char *m_declNotationPublicId;
+ ELEMENT_TYPE *m_declElementType;
+ ATTRIBUTE_ID *m_declAttributeId;
+ XML_Bool m_declAttributeIsCdata;
+ XML_Bool m_declAttributeIsId;
+ DTD *m_dtd;
+ const XML_Char *m_curBase;
+ TAG *m_tagStack;
+ TAG *m_freeTagList;
+ BINDING *m_inheritedBindings;
+ BINDING *m_freeBindingList;
+ int m_attsSize;
+ int m_nSpecifiedAtts;
+ int m_idAttIndex;
+ ATTRIBUTE *m_atts;
+ NS_ATT *m_nsAtts;
+ unsigned long m_nsAttsVersion;
+ unsigned char m_nsAttsPower;
+ POSITION m_position;
+ STRING_POOL m_tempPool;
+ STRING_POOL m_temp2Pool;
+ char *m_groupConnector;
+ unsigned int m_groupSize;
+ XML_Char m_namespaceSeparator;
+ XML_Parser m_parentParser;
+ XML_ParsingStatus m_parsingStatus;
+#ifdef XML_DTD
+ XML_Bool m_isParamEntity;
+ XML_Bool m_useForeignDTD;
+ enum XML_ParamEntityParsing m_paramEntityParsing;
+#endif
+};
+
+#define MALLOC(s) (parser->m_mem.malloc_fcn((s)))
+#define REALLOC(p,s) (parser->m_mem.realloc_fcn((p),(s)))
+#define FREE(p) (parser->m_mem.free_fcn((p)))
+
+#define userData (parser->m_userData)
+#define handlerArg (parser->m_handlerArg)
+#define startElementHandler (parser->m_startElementHandler)
+#define endElementHandler (parser->m_endElementHandler)
+#define characterDataHandler (parser->m_characterDataHandler)
+#define processingInstructionHandler \
+ (parser->m_processingInstructionHandler)
+#define commentHandler (parser->m_commentHandler)
+#define startCdataSectionHandler \
+ (parser->m_startCdataSectionHandler)
+#define endCdataSectionHandler (parser->m_endCdataSectionHandler)
+#define defaultHandler (parser->m_defaultHandler)
+#define startDoctypeDeclHandler (parser->m_startDoctypeDeclHandler)
+#define endDoctypeDeclHandler (parser->m_endDoctypeDeclHandler)
+#define unparsedEntityDeclHandler \
+ (parser->m_unparsedEntityDeclHandler)
+#define notationDeclHandler (parser->m_notationDeclHandler)
+#define startNamespaceDeclHandler \
+ (parser->m_startNamespaceDeclHandler)
+#define endNamespaceDeclHandler (parser->m_endNamespaceDeclHandler)
+#define notStandaloneHandler (parser->m_notStandaloneHandler)
+#define externalEntityRefHandler \
+ (parser->m_externalEntityRefHandler)
+#define externalEntityRefHandlerArg \
+ (parser->m_externalEntityRefHandlerArg)
+#define internalEntityRefHandler \
+ (parser->m_internalEntityRefHandler)
+#define skippedEntityHandler (parser->m_skippedEntityHandler)
+#define unknownEncodingHandler (parser->m_unknownEncodingHandler)
+#define elementDeclHandler (parser->m_elementDeclHandler)
+#define attlistDeclHandler (parser->m_attlistDeclHandler)
+#define entityDeclHandler (parser->m_entityDeclHandler)
+#define xmlDeclHandler (parser->m_xmlDeclHandler)
+#define encoding (parser->m_encoding)
+#define initEncoding (parser->m_initEncoding)
+#define internalEncoding (parser->m_internalEncoding)
+#define unknownEncodingMem (parser->m_unknownEncodingMem)
+#define unknownEncodingData (parser->m_unknownEncodingData)
+#define unknownEncodingHandlerData \
+ (parser->m_unknownEncodingHandlerData)
+#define unknownEncodingRelease (parser->m_unknownEncodingRelease)
+#define protocolEncodingName (parser->m_protocolEncodingName)
+#define ns (parser->m_ns)
+#define ns_triplets (parser->m_ns_triplets)
+#define prologState (parser->m_prologState)
+#define processor (parser->m_processor)
+#define errorCode (parser->m_errorCode)
+#define eventPtr (parser->m_eventPtr)
+#define eventEndPtr (parser->m_eventEndPtr)
+#define positionPtr (parser->m_positionPtr)
+#define position (parser->m_position)
+#define openInternalEntities (parser->m_openInternalEntities)
+#define freeInternalEntities (parser->m_freeInternalEntities)
+#define defaultExpandInternalEntities \
+ (parser->m_defaultExpandInternalEntities)
+#define tagLevel (parser->m_tagLevel)
+#define buffer (parser->m_buffer)
+#define bufferPtr (parser->m_bufferPtr)
+#define bufferEnd (parser->m_bufferEnd)
+#define parseEndByteIndex (parser->m_parseEndByteIndex)
+#define parseEndPtr (parser->m_parseEndPtr)
+#define bufferLim (parser->m_bufferLim)
+#define dataBuf (parser->m_dataBuf)
+#define dataBufEnd (parser->m_dataBufEnd)
+#define _dtd (parser->m_dtd)
+#define curBase (parser->m_curBase)
+#define declEntity (parser->m_declEntity)
+#define doctypeName (parser->m_doctypeName)
+#define doctypeSysid (parser->m_doctypeSysid)
+#define doctypePubid (parser->m_doctypePubid)
+#define declAttributeType (parser->m_declAttributeType)
+#define declNotationName (parser->m_declNotationName)
+#define declNotationPublicId (parser->m_declNotationPublicId)
+#define declElementType (parser->m_declElementType)
+#define declAttributeId (parser->m_declAttributeId)
+#define declAttributeIsCdata (parser->m_declAttributeIsCdata)
+#define declAttributeIsId (parser->m_declAttributeIsId)
+#define freeTagList (parser->m_freeTagList)
+#define freeBindingList (parser->m_freeBindingList)
+#define inheritedBindings (parser->m_inheritedBindings)
+#define tagStack (parser->m_tagStack)
+#define atts (parser->m_atts)
+#define attsSize (parser->m_attsSize)
+#define nSpecifiedAtts (parser->m_nSpecifiedAtts)
+#define idAttIndex (parser->m_idAttIndex)
+#define nsAtts (parser->m_nsAtts)
+#define nsAttsVersion (parser->m_nsAttsVersion)
+#define nsAttsPower (parser->m_nsAttsPower)
+#define tempPool (parser->m_tempPool)
+#define temp2Pool (parser->m_temp2Pool)
+#define groupConnector (parser->m_groupConnector)
+#define groupSize (parser->m_groupSize)
+#define namespaceSeparator (parser->m_namespaceSeparator)
+#define parentParser (parser->m_parentParser)
+#define ps_parsing (parser->m_parsingStatus.parsing)
+#define ps_finalBuffer (parser->m_parsingStatus.finalBuffer)
+#ifdef XML_DTD
+#define isParamEntity (parser->m_isParamEntity)
+#define useForeignDTD (parser->m_useForeignDTD)
+#define paramEntityParsing (parser->m_paramEntityParsing)
+#endif /* XML_DTD */
+
+XML_Parser XMLCALL
+XML_ParserCreate(const XML_Char *encodingName)
+{
+ return XML_ParserCreate_MM(encodingName, NULL, NULL);
+}
+
+XML_Parser XMLCALL
+XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep)
+{
+ XML_Char tmp[2];
+ *tmp = nsSep;
+ return XML_ParserCreate_MM(encodingName, NULL, tmp);
+}
+
+static const XML_Char implicitContext[] = {
+ 'x', 'm', 'l', '=', 'h', 't', 't', 'p', ':', '/', '/',
+ 'w', 'w', 'w', '.', 'w', '3', '.', 'o', 'r', 'g', '/',
+ 'X', 'M', 'L', '/', '1', '9', '9', '8', '/',
+ 'n', 'a', 'm', 'e', 's', 'p', 'a', 'c', 'e', '\0'
+};
+
+XML_Parser XMLCALL
+XML_ParserCreate_MM(const XML_Char *encodingName,
+ const XML_Memory_Handling_Suite *memsuite,
+ const XML_Char *nameSep)
+{
+ XML_Parser parser = parserCreate(encodingName, memsuite, nameSep, NULL);
+ if (parser != NULL && ns) {
+ /* implicit context only set for root parser, since child
+ parsers (i.e. external entity parsers) will inherit it
+ */
+ if (!setContext(parser, implicitContext)) {
+ XML_ParserFree(parser);
+ return NULL;
+ }
+ }
+ return parser;
+}
+
+static XML_Parser
+parserCreate(const XML_Char *encodingName,
+ const XML_Memory_Handling_Suite *memsuite,
+ const XML_Char *nameSep,
+ DTD *dtd)
+{
+ XML_Parser parser;
+
+ if (memsuite) {
+ XML_Memory_Handling_Suite *mtemp;
+ parser = (XML_Parser)
+ memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
+ if (parser != NULL) {
+ mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
+ mtemp->malloc_fcn = memsuite->malloc_fcn;
+ mtemp->realloc_fcn = memsuite->realloc_fcn;
+ mtemp->free_fcn = memsuite->free_fcn;
+ }
+ }
+ else {
+ XML_Memory_Handling_Suite *mtemp;
+ parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
+ if (parser != NULL) {
+ mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
+ mtemp->malloc_fcn = malloc;
+ mtemp->realloc_fcn = realloc;
+ mtemp->free_fcn = free;
+ }
+ }
+
+ if (!parser)
+ return parser;
+
+ buffer = NULL;
+ bufferLim = NULL;
+
+ attsSize = INIT_ATTS_SIZE;
+ atts = (ATTRIBUTE *)MALLOC(attsSize * sizeof(ATTRIBUTE));
+ if (atts == NULL) {
+ FREE(parser);
+ return NULL;
+ }
+ dataBuf = (XML_Char *)MALLOC(INIT_DATA_BUF_SIZE * sizeof(XML_Char));
+ if (dataBuf == NULL) {
+ FREE(atts);
+ FREE(parser);
+ return NULL;
+ }
+ dataBufEnd = dataBuf + INIT_DATA_BUF_SIZE;
+
+ if (dtd)
+ _dtd = dtd;
+ else {
+ _dtd = dtdCreate(&parser->m_mem);
+ if (_dtd == NULL) {
+ FREE(dataBuf);
+ FREE(atts);
+ FREE(parser);
+ return NULL;
+ }
+ }
+
+ freeBindingList = NULL;
+ freeTagList = NULL;
+ freeInternalEntities = NULL;
+
+ groupSize = 0;
+ groupConnector = NULL;
+
+ unknownEncodingHandler = NULL;
+ unknownEncodingHandlerData = NULL;
+
+ namespaceSeparator = '!';
+ ns = XML_FALSE;
+ ns_triplets = XML_FALSE;
+
+ nsAtts = NULL;
+ nsAttsVersion = 0;
+ nsAttsPower = 0;
+
+ poolInit(&tempPool, &(parser->m_mem));
+ poolInit(&temp2Pool, &(parser->m_mem));
+ parserInit(parser, encodingName);
+
+ if (encodingName && !protocolEncodingName) {
+ XML_ParserFree(parser);
+ return NULL;
+ }
+
+ if (nameSep) {
+ ns = XML_TRUE;
+ internalEncoding = XmlGetInternalEncodingNS();
+ namespaceSeparator = *nameSep;
+ }
+ else {
+ internalEncoding = XmlGetInternalEncoding();
+ }
+
+ return parser;
+}
+
+static void
+parserInit(XML_Parser parser, const XML_Char *encodingName)
+{
+ processor = prologInitProcessor;
+ XmlPrologStateInit(&prologState);
+ protocolEncodingName = (encodingName != NULL
+ ? poolCopyString(&tempPool, encodingName)
+ : NULL);
+ curBase = NULL;
+ XmlInitEncoding(&initEncoding, &encoding, 0);
+ userData = NULL;
+ handlerArg = NULL;
+ startElementHandler = NULL;
+ endElementHandler = NULL;
+ characterDataHandler = NULL;
+ processingInstructionHandler = NULL;
+ commentHandler = NULL;
+ startCdataSectionHandler = NULL;
+ endCdataSectionHandler = NULL;
+ defaultHandler = NULL;
+ startDoctypeDeclHandler = NULL;
+ endDoctypeDeclHandler = NULL;
+ unparsedEntityDeclHandler = NULL;
+ notationDeclHandler = NULL;
+ startNamespaceDeclHandler = NULL;
+ endNamespaceDeclHandler = NULL;
+ notStandaloneHandler = NULL;
+ externalEntityRefHandler = NULL;
+ externalEntityRefHandlerArg = parser;
+ skippedEntityHandler = NULL;
+ elementDeclHandler = NULL;
+ attlistDeclHandler = NULL;
+ entityDeclHandler = NULL;
+ xmlDeclHandler = NULL;
+ bufferPtr = buffer;
+ bufferEnd = buffer;
+ parseEndByteIndex = 0;
+ parseEndPtr = NULL;
+ declElementType = NULL;
+ declAttributeId = NULL;
+ declEntity = NULL;
+ doctypeName = NULL;
+ doctypeSysid = NULL;
+ doctypePubid = NULL;
+ declAttributeType = NULL;
+ declNotationName = NULL;
+ declNotationPublicId = NULL;
+ declAttributeIsCdata = XML_FALSE;
+ declAttributeIsId = XML_FALSE;
+ memset(&position, 0, sizeof(POSITION));
+ errorCode = XML_ERROR_NONE;
+ eventPtr = NULL;
+ eventEndPtr = NULL;
+ positionPtr = NULL;
+ openInternalEntities = NULL;
+ defaultExpandInternalEntities = XML_TRUE;
+ tagLevel = 0;
+ tagStack = NULL;
+ inheritedBindings = NULL;
+ nSpecifiedAtts = 0;
+ unknownEncodingMem = NULL;
+ unknownEncodingRelease = NULL;
+ unknownEncodingData = NULL;
+ parentParser = NULL;
+ ps_parsing = XML_INITIALIZED;
+#ifdef XML_DTD
+ isParamEntity = XML_FALSE;
+ useForeignDTD = XML_FALSE;
+ paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
+#endif
+}
+
+/* moves list of bindings to freeBindingList */
+static void FASTCALL
+moveToFreeBindingList(XML_Parser parser, BINDING *bindings)
+{
+ while (bindings) {
+ BINDING *b = bindings;
+ bindings = bindings->nextTagBinding;
+ b->nextTagBinding = freeBindingList;
+ freeBindingList = b;
+ }
+}
+
+XML_Bool XMLCALL
+XML_ParserReset(XML_Parser parser, const XML_Char *encodingName)
+{
+ TAG *tStk;
+ OPEN_INTERNAL_ENTITY *openEntityList;
+ if (parentParser)
+ return XML_FALSE;
+ /* move tagStack to freeTagList */
+ tStk = tagStack;
+ while (tStk) {
+ TAG *tag = tStk;
+ tStk = tStk->parent;
+ tag->parent = freeTagList;
+ moveToFreeBindingList(parser, tag->bindings);
+ tag->bindings = NULL;
+ freeTagList = tag;
+ }
+ /* move openInternalEntities to freeInternalEntities */
+ openEntityList = openInternalEntities;
+ while (openEntityList) {
+ OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
+ openEntityList = openEntity->next;
+ openEntity->next = freeInternalEntities;
+ freeInternalEntities = openEntity;
+ }
+ moveToFreeBindingList(parser, inheritedBindings);
+ FREE(unknownEncodingMem);
+ if (unknownEncodingRelease)
+ unknownEncodingRelease(unknownEncodingData);
+ poolClear(&tempPool);
+ poolClear(&temp2Pool);
+ parserInit(parser, encodingName);
+ dtdReset(_dtd, &parser->m_mem);
+ return setContext(parser, implicitContext);
+}
+
+enum XML_Status XMLCALL
+XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName)
+{
+ /* Block after XML_Parse()/XML_ParseBuffer() has been called.
+ XXX There's no way for the caller to determine which of the
+ XXX possible error cases caused the XML_STATUS_ERROR return.
+ */
+ if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ return XML_STATUS_ERROR;
+ if (encodingName == NULL)
+ protocolEncodingName = NULL;
+ else {
+ protocolEncodingName = poolCopyString(&tempPool, encodingName);
+ if (!protocolEncodingName)
+ return XML_STATUS_ERROR;
+ }
+ return XML_STATUS_OK;
+}
+
+XML_Parser XMLCALL
+XML_ExternalEntityParserCreate(XML_Parser oldParser,
+ const XML_Char *context,
+ const XML_Char *encodingName)
+{
+ XML_Parser parser = oldParser;
+ DTD *newDtd = NULL;
+ DTD *oldDtd = _dtd;
+ XML_StartElementHandler oldStartElementHandler = startElementHandler;
+ XML_EndElementHandler oldEndElementHandler = endElementHandler;
+ XML_CharacterDataHandler oldCharacterDataHandler = characterDataHandler;
+ XML_ProcessingInstructionHandler oldProcessingInstructionHandler
+ = processingInstructionHandler;
+ XML_CommentHandler oldCommentHandler = commentHandler;
+ XML_StartCdataSectionHandler oldStartCdataSectionHandler
+ = startCdataSectionHandler;
+ XML_EndCdataSectionHandler oldEndCdataSectionHandler
+ = endCdataSectionHandler;
+ XML_DefaultHandler oldDefaultHandler = defaultHandler;
+ XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler
+ = unparsedEntityDeclHandler;
+ XML_NotationDeclHandler oldNotationDeclHandler = notationDeclHandler;
+ XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler
+ = startNamespaceDeclHandler;
+ XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler
+ = endNamespaceDeclHandler;
+ XML_NotStandaloneHandler oldNotStandaloneHandler = notStandaloneHandler;
+ XML_ExternalEntityRefHandler oldExternalEntityRefHandler
+ = externalEntityRefHandler;
+ XML_SkippedEntityHandler oldSkippedEntityHandler = skippedEntityHandler;
+ XML_UnknownEncodingHandler oldUnknownEncodingHandler
+ = unknownEncodingHandler;
+ XML_ElementDeclHandler oldElementDeclHandler = elementDeclHandler;
+ XML_AttlistDeclHandler oldAttlistDeclHandler = attlistDeclHandler;
+ XML_EntityDeclHandler oldEntityDeclHandler = entityDeclHandler;
+ XML_XmlDeclHandler oldXmlDeclHandler = xmlDeclHandler;
+ ELEMENT_TYPE * oldDeclElementType = declElementType;
+
+ void *oldUserData = userData;
+ void *oldHandlerArg = handlerArg;
+ XML_Bool oldDefaultExpandInternalEntities = defaultExpandInternalEntities;
+ XML_Parser oldExternalEntityRefHandlerArg = externalEntityRefHandlerArg;
+#ifdef XML_DTD
+ enum XML_ParamEntityParsing oldParamEntityParsing = paramEntityParsing;
+ int oldInEntityValue = prologState.inEntityValue;
+#endif
+ XML_Bool oldns_triplets = ns_triplets;
+
+#ifdef XML_DTD
+ if (!context)
+ newDtd = oldDtd;
+#endif /* XML_DTD */
+
+ /* Note that the magical uses of the pre-processor to make field
+ access look more like C++ require that `parser' be overwritten
+ here. This makes this function more painful to follow than it
+ would be otherwise.
+ */
+ if (ns) {
+ XML_Char tmp[2];
+ *tmp = namespaceSeparator;
+ parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
+ }
+ else {
+ parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
+ }
+
+ if (!parser)
+ return NULL;
+
+ startElementHandler = oldStartElementHandler;
+ endElementHandler = oldEndElementHandler;
+ characterDataHandler = oldCharacterDataHandler;
+ processingInstructionHandler = oldProcessingInstructionHandler;
+ commentHandler = oldCommentHandler;
+ startCdataSectionHandler = oldStartCdataSectionHandler;
+ endCdataSectionHandler = oldEndCdataSectionHandler;
+ defaultHandler = oldDefaultHandler;
+ unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
+ notationDeclHandler = oldNotationDeclHandler;
+ startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
+ endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
+ notStandaloneHandler = oldNotStandaloneHandler;
+ externalEntityRefHandler = oldExternalEntityRefHandler;
+ skippedEntityHandler = oldSkippedEntityHandler;
+ unknownEncodingHandler = oldUnknownEncodingHandler;
+ elementDeclHandler = oldElementDeclHandler;
+ attlistDeclHandler = oldAttlistDeclHandler;
+ entityDeclHandler = oldEntityDeclHandler;
+ xmlDeclHandler = oldXmlDeclHandler;
+ declElementType = oldDeclElementType;
+ userData = oldUserData;
+ if (oldUserData == oldHandlerArg)
+ handlerArg = userData;
+ else
+ handlerArg = parser;
+ if (oldExternalEntityRefHandlerArg != oldParser)
+ externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
+ defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
+ ns_triplets = oldns_triplets;
+ parentParser = oldParser;
+#ifdef XML_DTD
+ paramEntityParsing = oldParamEntityParsing;
+ prologState.inEntityValue = oldInEntityValue;
+ if (context) {
+#endif /* XML_DTD */
+ if (!dtdCopy(_dtd, oldDtd, &parser->m_mem)
+ || !setContext(parser, context)) {
+ XML_ParserFree(parser);
+ return NULL;
+ }
+ processor = externalEntityInitProcessor;
+#ifdef XML_DTD
+ }
+ else {
+ /* The DTD instance referenced by _dtd is shared between the document's
+ root parser and external PE parsers, therefore one does not need to
+ call setContext. In addition, one also *must* not call setContext,
+ because this would overwrite existing prefix->binding pointers in
+ _dtd with ones that get destroyed with the external PE parser.
+ This would leave those prefixes with dangling pointers.
+ */
+ isParamEntity = XML_TRUE;
+ XmlPrologStateInitExternalEntity(&prologState);
+ processor = externalParEntInitProcessor;
+ }
+#endif /* XML_DTD */
+ return parser;
+}
+
+static void FASTCALL
+destroyBindings(BINDING *bindings, XML_Parser parser)
+{
+ for (;;) {
+ BINDING *b = bindings;
+ if (!b)
+ break;
+ bindings = b->nextTagBinding;
+ FREE(b->uri);
+ FREE(b);
+ }
+}
+
+void XMLCALL
+XML_ParserFree(XML_Parser parser)
+{
+ TAG *tagList;
+ OPEN_INTERNAL_ENTITY *entityList;
+ if (parser == NULL)
+ return;
+ /* free tagStack and freeTagList */
+ tagList = tagStack;
+ for (;;) {
+ TAG *p;
+ if (tagList == NULL) {
+ if (freeTagList == NULL)
+ break;
+ tagList = freeTagList;
+ freeTagList = NULL;
+ }
+ p = tagList;
+ tagList = tagList->parent;
+ FREE(p->buf);
+ destroyBindings(p->bindings, parser);
+ FREE(p);
+ }
+ /* free openInternalEntities and freeInternalEntities */
+ entityList = openInternalEntities;
+ for (;;) {
+ OPEN_INTERNAL_ENTITY *openEntity;
+ if (entityList == NULL) {
+ if (freeInternalEntities == NULL)
+ break;
+ entityList = freeInternalEntities;
+ freeInternalEntities = NULL;
+ }
+ openEntity = entityList;
+ entityList = entityList->next;
+ FREE(openEntity);
+ }
+
+ destroyBindings(freeBindingList, parser);
+ destroyBindings(inheritedBindings, parser);
+ poolDestroy(&tempPool);
+ poolDestroy(&temp2Pool);
+#ifdef XML_DTD
+ /* external parameter entity parsers share the DTD structure
+ parser->m_dtd with the root parser, so we must not destroy it
+ */
+ if (!isParamEntity && _dtd)
+#else
+ if (_dtd)
+#endif /* XML_DTD */
+ dtdDestroy(_dtd, (XML_Bool)!parentParser, &parser->m_mem);
+ FREE((void *)atts);
+ FREE(groupConnector);
+ FREE(buffer);
+ FREE(dataBuf);
+ FREE(nsAtts);
+ FREE(unknownEncodingMem);
+ if (unknownEncodingRelease)
+ unknownEncodingRelease(unknownEncodingData);
+ FREE(parser);
+}
+
+void XMLCALL
+XML_UseParserAsHandlerArg(XML_Parser parser)
+{
+ handlerArg = parser;
+}
+
+enum XML_Error XMLCALL
+XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
+{
+#ifdef XML_DTD
+ /* block after XML_Parse()/XML_ParseBuffer() has been called */
+ if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
+ useForeignDTD = useDTD;
+ return XML_ERROR_NONE;
+#else
+ return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
+#endif
+}
+
+void XMLCALL
+XML_SetReturnNSTriplet(XML_Parser parser, int do_nst)
+{
+ /* block after XML_Parse()/XML_ParseBuffer() has been called */
+ if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ return;
+ ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
+}
+
+void XMLCALL
+XML_SetUserData(XML_Parser parser, void *p)
+{
+ if (handlerArg == userData)
+ handlerArg = userData = p;
+ else
+ userData = p;
+}
+
+enum XML_Status XMLCALL
+XML_SetBase(XML_Parser parser, const XML_Char *p)
+{
+ if (p) {
+ p = poolCopyString(&_dtd->pool, p);
+ if (!p)
+ return XML_STATUS_ERROR;
+ curBase = p;
+ }
+ else
+ curBase = NULL;
+ return XML_STATUS_OK;
+}
+
+const XML_Char * XMLCALL
+XML_GetBase(XML_Parser parser)
+{
+ return curBase;
+}
+
+int XMLCALL
+XML_GetSpecifiedAttributeCount(XML_Parser parser)
+{
+ return nSpecifiedAtts;
+}
+
+int XMLCALL
+XML_GetIdAttributeIndex(XML_Parser parser)
+{
+ return idAttIndex;
+}
+
+void XMLCALL
+XML_SetElementHandler(XML_Parser parser,
+ XML_StartElementHandler start,
+ XML_EndElementHandler end)
+{
+ startElementHandler = start;
+ endElementHandler = end;
+}
+
+void XMLCALL
+XML_SetStartElementHandler(XML_Parser parser,
+ XML_StartElementHandler start) {
+ startElementHandler = start;
+}
+
+void XMLCALL
+XML_SetEndElementHandler(XML_Parser parser,
+ XML_EndElementHandler end) {
+ endElementHandler = end;
+}
+
+void XMLCALL
+XML_SetCharacterDataHandler(XML_Parser parser,
+ XML_CharacterDataHandler handler)
+{
+ characterDataHandler = handler;
+}
+
+void XMLCALL
+XML_SetProcessingInstructionHandler(XML_Parser parser,
+ XML_ProcessingInstructionHandler handler)
+{
+ processingInstructionHandler = handler;
+}
+
+void XMLCALL
+XML_SetCommentHandler(XML_Parser parser,
+ XML_CommentHandler handler)
+{
+ commentHandler = handler;
+}
+
+void XMLCALL
+XML_SetCdataSectionHandler(XML_Parser parser,
+ XML_StartCdataSectionHandler start,
+ XML_EndCdataSectionHandler end)
+{
+ startCdataSectionHandler = start;
+ endCdataSectionHandler = end;
+}
+
+void XMLCALL
+XML_SetStartCdataSectionHandler(XML_Parser parser,
+ XML_StartCdataSectionHandler start) {
+ startCdataSectionHandler = start;
+}
+
+void XMLCALL
+XML_SetEndCdataSectionHandler(XML_Parser parser,
+ XML_EndCdataSectionHandler end) {
+ endCdataSectionHandler = end;
+}
+
+void XMLCALL
+XML_SetDefaultHandler(XML_Parser parser,
+ XML_DefaultHandler handler)
+{
+ defaultHandler = handler;
+ defaultExpandInternalEntities = XML_FALSE;
+}
+
+void XMLCALL
+XML_SetDefaultHandlerExpand(XML_Parser parser,
+ XML_DefaultHandler handler)
+{
+ defaultHandler = handler;
+ defaultExpandInternalEntities = XML_TRUE;
+}
+
+void XMLCALL
+XML_SetDoctypeDeclHandler(XML_Parser parser,
+ XML_StartDoctypeDeclHandler start,
+ XML_EndDoctypeDeclHandler end)
+{
+ startDoctypeDeclHandler = start;
+ endDoctypeDeclHandler = end;
+}
+
+void XMLCALL
+XML_SetStartDoctypeDeclHandler(XML_Parser parser,
+ XML_StartDoctypeDeclHandler start) {
+ startDoctypeDeclHandler = start;
+}
+
+void XMLCALL
+XML_SetEndDoctypeDeclHandler(XML_Parser parser,
+ XML_EndDoctypeDeclHandler end) {
+ endDoctypeDeclHandler = end;
+}
+
+void XMLCALL
+XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
+ XML_UnparsedEntityDeclHandler handler)
+{
+ unparsedEntityDeclHandler = handler;
+}
+
+void XMLCALL
+XML_SetNotationDeclHandler(XML_Parser parser,
+ XML_NotationDeclHandler handler)
+{
+ notationDeclHandler = handler;
+}
+
+void XMLCALL
+XML_SetNamespaceDeclHandler(XML_Parser parser,
+ XML_StartNamespaceDeclHandler start,
+ XML_EndNamespaceDeclHandler end)
+{
+ startNamespaceDeclHandler = start;
+ endNamespaceDeclHandler = end;
+}
+
+void XMLCALL
+XML_SetStartNamespaceDeclHandler(XML_Parser parser,
+ XML_StartNamespaceDeclHandler start) {
+ startNamespaceDeclHandler = start;
+}
+
+void XMLCALL
+XML_SetEndNamespaceDeclHandler(XML_Parser parser,
+ XML_EndNamespaceDeclHandler end) {
+ endNamespaceDeclHandler = end;
+}
+
+void XMLCALL
+XML_SetNotStandaloneHandler(XML_Parser parser,
+ XML_NotStandaloneHandler handler)
+{
+ notStandaloneHandler = handler;
+}
+
+void XMLCALL
+XML_SetExternalEntityRefHandler(XML_Parser parser,
+ XML_ExternalEntityRefHandler handler)
+{
+ externalEntityRefHandler = handler;
+}
+
+void XMLCALL
+XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg)
+{
+ if (arg)
+ externalEntityRefHandlerArg = (XML_Parser)arg;
+ else
+ externalEntityRefHandlerArg = parser;
+}
+
+void XMLCALL
+XML_SetSkippedEntityHandler(XML_Parser parser,
+ XML_SkippedEntityHandler handler)
+{
+ skippedEntityHandler = handler;
+}
+
+void XMLCALL
+XML_SetUnknownEncodingHandler(XML_Parser parser,
+ XML_UnknownEncodingHandler handler,
+ void *data)
+{
+ unknownEncodingHandler = handler;
+ unknownEncodingHandlerData = data;
+}
+
+void XMLCALL
+XML_SetElementDeclHandler(XML_Parser parser,
+ XML_ElementDeclHandler eldecl)
+{
+ elementDeclHandler = eldecl;
+}
+
+void XMLCALL
+XML_SetAttlistDeclHandler(XML_Parser parser,
+ XML_AttlistDeclHandler attdecl)
+{
+ attlistDeclHandler = attdecl;
+}
+
+void XMLCALL
+XML_SetEntityDeclHandler(XML_Parser parser,
+ XML_EntityDeclHandler handler)
+{
+ entityDeclHandler = handler;
+}
+
+void XMLCALL
+XML_SetXmlDeclHandler(XML_Parser parser,
+ XML_XmlDeclHandler handler) {
+ xmlDeclHandler = handler;
+}
+
+int XMLCALL
+XML_SetParamEntityParsing(XML_Parser parser,
+ enum XML_ParamEntityParsing peParsing)
+{
+ /* block after XML_Parse()/XML_ParseBuffer() has been called */
+ if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ return 0;
+#ifdef XML_DTD
+ paramEntityParsing = peParsing;
+ return 1;
+#else
+ return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
+#endif
+}
+
+enum XML_Status XMLCALL
+XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
+{
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ errorCode = XML_ERROR_SUSPENDED;
+ return XML_STATUS_ERROR;
+ case XML_FINISHED:
+ errorCode = XML_ERROR_FINISHED;
+ return XML_STATUS_ERROR;
+ default:
+ ps_parsing = XML_PARSING;
+ }
+
+ if (len == 0) {
+ ps_finalBuffer = (XML_Bool)isFinal;
+ if (!isFinal)
+ return XML_STATUS_OK;
+ positionPtr = bufferPtr;
+ parseEndPtr = bufferEnd;
+
+ /* If data are left over from last buffer, and we now know that these
+ data are the final chunk of input, then we have to check them again
+ to detect errors based on that fact.
+ */
+ errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr);
+
+ if (errorCode == XML_ERROR_NONE) {
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
+ positionPtr = bufferPtr;
+ return XML_STATUS_SUSPENDED;
+ case XML_INITIALIZED:
+ case XML_PARSING:
+ ps_parsing = XML_FINISHED;
+ /* fall through */
+ default:
+ return XML_STATUS_OK;
+ }
+ }
+ eventEndPtr = eventPtr;
+ processor = errorProcessor;
+ return XML_STATUS_ERROR;
+ }
+#ifndef XML_CONTEXT_BYTES
+ else if (bufferPtr == bufferEnd) {
+ const char *end;
+ int nLeftOver;
+ enum XML_Error result;
+ parseEndByteIndex += len;
+ positionPtr = s;
+ ps_finalBuffer = (XML_Bool)isFinal;
+
+ errorCode = processor(parser, s, parseEndPtr = s + len, &end);
+
+ if (errorCode != XML_ERROR_NONE) {
+ eventEndPtr = eventPtr;
+ processor = errorProcessor;
+ return XML_STATUS_ERROR;
+ }
+ else {
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ result = XML_STATUS_SUSPENDED;
+ break;
+ case XML_INITIALIZED:
+ case XML_PARSING:
+ result = XML_STATUS_OK;
+ if (isFinal) {
+ ps_parsing = XML_FINISHED;
+ return result;
+ }
+ break;
+ default:
+ /* XML_FINISHED case required by compiler - but not tested - djv */
+ return XML_STATUS_OK;
+ }
+ }
+
+ XmlUpdatePosition(encoding, positionPtr, end, &position);
+ nLeftOver = s + len - end;
+ if (nLeftOver) {
+ if (buffer == NULL || nLeftOver > bufferLim - buffer) {
+ /* FIXME avoid integer overflow */
+ char *temp;
+ temp = (buffer == NULL
+ ? (char *)MALLOC(len * 2)
+ : (char *)REALLOC(buffer, len * 2));
+ if (temp == NULL) {
+ errorCode = XML_ERROR_NO_MEMORY;
+ return XML_STATUS_ERROR;
+ }
+ buffer = temp;
+ if (!buffer) {
+ errorCode = XML_ERROR_NO_MEMORY;
+ eventPtr = eventEndPtr = NULL;
+ processor = errorProcessor;
+ return XML_STATUS_ERROR;
+ }
+ bufferLim = buffer + len * 2;
+ }
+ memcpy(buffer, end, nLeftOver);
+ }
+ bufferPtr = buffer;
+ bufferEnd = buffer + nLeftOver;
+ positionPtr = bufferPtr;
+ parseEndPtr = bufferEnd;
+ eventPtr = bufferPtr;
+ eventEndPtr = bufferPtr;
+ return result;
+ }
+#endif /* not defined XML_CONTEXT_BYTES */
+ else {
+ void *buff = XML_GetBuffer(parser, len);
+ if (buff == NULL)
+ return XML_STATUS_ERROR;
+ else {
+ memcpy(buff, s, len);
+ return XML_ParseBuffer(parser, len, isFinal);
+ }
+ }
+}
+
+enum XML_Status XMLCALL
+XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
+{
+ const char *start;
+ enum XML_Status result = XML_STATUS_OK;
+
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ errorCode = XML_ERROR_SUSPENDED;
+ return XML_STATUS_ERROR;
+ case XML_FINISHED:
+ errorCode = XML_ERROR_FINISHED;
+ return XML_STATUS_ERROR;
+ default:
+ ps_parsing = XML_PARSING;
+ }
+
+ start = bufferPtr;
+ positionPtr = start;
+ bufferEnd += len;
+ parseEndPtr = bufferEnd;
+ parseEndByteIndex += len;
+ ps_finalBuffer = (XML_Bool)isFinal;
+
+ errorCode = processor(parser, start, parseEndPtr, &bufferPtr);
+
+ if (errorCode != XML_ERROR_NONE) {
+ eventEndPtr = eventPtr;
+ processor = errorProcessor;
+ return XML_STATUS_ERROR;
+ }
+ else {
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ result = XML_STATUS_SUSPENDED;
+ break;
+ case XML_INITIALIZED:
+ case XML_PARSING:
+ if (isFinal) {
+ ps_parsing = XML_FINISHED;
+ return result;
+ }
+ default: ; /* should not happen */
+ }
+ }
+
+ XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
+ positionPtr = bufferPtr;
+ return result;
+}
+
+void * XMLCALL
+XML_GetBuffer(XML_Parser parser, int len)
+{
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ errorCode = XML_ERROR_SUSPENDED;
+ return NULL;
+ case XML_FINISHED:
+ errorCode = XML_ERROR_FINISHED;
+ return NULL;
+ default: ;
+ }
+
+ if (len > bufferLim - bufferEnd) {
+ /* FIXME avoid integer overflow */
+ int neededSize = len + (int)(bufferEnd - bufferPtr);
+#ifdef XML_CONTEXT_BYTES
+ int keep = (int)(bufferPtr - buffer);
+
+ if (keep > XML_CONTEXT_BYTES)
+ keep = XML_CONTEXT_BYTES;
+ neededSize += keep;
+#endif /* defined XML_CONTEXT_BYTES */
+ if (neededSize <= bufferLim - buffer) {
+#ifdef XML_CONTEXT_BYTES
+ if (keep < bufferPtr - buffer) {
+ int offset = (int)(bufferPtr - buffer) - keep;
+ memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep);
+ bufferEnd -= offset;
+ bufferPtr -= offset;
+ }
+#else
+ memmove(buffer, bufferPtr, bufferEnd - bufferPtr);
+ bufferEnd = buffer + (bufferEnd - bufferPtr);
+ bufferPtr = buffer;
+#endif /* not defined XML_CONTEXT_BYTES */
+ }
+ else {
+ char *newBuf;
+ int bufferSize = (int)(bufferLim - bufferPtr);
+ if (bufferSize == 0)
+ bufferSize = INIT_BUFFER_SIZE;
+ do {
+ bufferSize *= 2;
+ } while (bufferSize < neededSize);
+ newBuf = (char *)MALLOC(bufferSize);
+ if (newBuf == 0) {
+ errorCode = XML_ERROR_NO_MEMORY;
+ return NULL;
+ }
+ bufferLim = newBuf + bufferSize;
+#ifdef XML_CONTEXT_BYTES
+ if (bufferPtr) {
+ int keep = (int)(bufferPtr - buffer);
+ if (keep > XML_CONTEXT_BYTES)
+ keep = XML_CONTEXT_BYTES;
+ memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep);
+ FREE(buffer);
+ buffer = newBuf;
+ bufferEnd = buffer + (bufferEnd - bufferPtr) + keep;
+ bufferPtr = buffer + keep;
+ }
+ else {
+ bufferEnd = newBuf + (bufferEnd - bufferPtr);
+ bufferPtr = buffer = newBuf;
+ }
+#else
+ if (bufferPtr) {
+ memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr);
+ FREE(buffer);
+ }
+ bufferEnd = newBuf + (bufferEnd - bufferPtr);
+ bufferPtr = buffer = newBuf;
+#endif /* not defined XML_CONTEXT_BYTES */
+ }
+ }
+ return bufferEnd;
+}
+
+enum XML_Status XMLCALL
+XML_StopParser(XML_Parser parser, XML_Bool resumable)
+{
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ if (resumable) {
+ errorCode = XML_ERROR_SUSPENDED;
+ return XML_STATUS_ERROR;
+ }
+ ps_parsing = XML_FINISHED;
+ break;
+ case XML_FINISHED:
+ errorCode = XML_ERROR_FINISHED;
+ return XML_STATUS_ERROR;
+ default:
+ if (resumable) {
+#ifdef XML_DTD
+ if (isParamEntity) {
+ errorCode = XML_ERROR_SUSPEND_PE;
+ return XML_STATUS_ERROR;
+ }
+#endif
+ ps_parsing = XML_SUSPENDED;
+ }
+ else
+ ps_parsing = XML_FINISHED;
+ }
+ return XML_STATUS_OK;
+}
+
+enum XML_Status XMLCALL
+XML_ResumeParser(XML_Parser parser)
+{
+ enum XML_Status result = XML_STATUS_OK;
+
+ if (ps_parsing != XML_SUSPENDED) {
+ errorCode = XML_ERROR_NOT_SUSPENDED;
+ return XML_STATUS_ERROR;
+ }
+ ps_parsing = XML_PARSING;
+
+ errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr);
+
+ if (errorCode != XML_ERROR_NONE) {
+ eventEndPtr = eventPtr;
+ processor = errorProcessor;
+ return XML_STATUS_ERROR;
+ }
+ else {
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ result = XML_STATUS_SUSPENDED;
+ break;
+ case XML_INITIALIZED:
+ case XML_PARSING:
+ if (ps_finalBuffer) {
+ ps_parsing = XML_FINISHED;
+ return result;
+ }
+ default: ;
+ }
+ }
+
+ XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
+ positionPtr = bufferPtr;
+ return result;
+}
+
+void XMLCALL
+XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status)
+{
+ assert(status != NULL);
+ *status = parser->m_parsingStatus;
+}
+
+enum XML_Error XMLCALL
+XML_GetErrorCode(XML_Parser parser)
+{
+ return errorCode;
+}
+
+XML_Index XMLCALL
+XML_GetCurrentByteIndex(XML_Parser parser)
+{
+ if (eventPtr)
+ return parseEndByteIndex - (parseEndPtr - eventPtr);
+ return -1;
+}
+
+int XMLCALL
+XML_GetCurrentByteCount(XML_Parser parser)
+{
+ if (eventEndPtr && eventPtr)
+ return (int)(eventEndPtr - eventPtr);
+ return 0;
+}
+
+const char * XMLCALL
+XML_GetInputContext(XML_Parser parser, int *offset, int *size)
+{
+#ifdef XML_CONTEXT_BYTES
+ if (eventPtr && buffer) {
+ *offset = (int)(eventPtr - buffer);
+ *size = (int)(bufferEnd - buffer);
+ return buffer;
+ }
+#endif /* defined XML_CONTEXT_BYTES */
+ return (char *) 0;
+}
+
+XML_Size XMLCALL
+XML_GetCurrentLineNumber(XML_Parser parser)
+{
+ if (eventPtr && eventPtr >= positionPtr) {
+ XmlUpdatePosition(encoding, positionPtr, eventPtr, &position);
+ positionPtr = eventPtr;
+ }
+ return position.lineNumber + 1;
+}
+
+XML_Size XMLCALL
+XML_GetCurrentColumnNumber(XML_Parser parser)
+{
+ if (eventPtr && eventPtr >= positionPtr) {
+ XmlUpdatePosition(encoding, positionPtr, eventPtr, &position);
+ positionPtr = eventPtr;
+ }
+ return position.columnNumber;
+}
+
+void XMLCALL
+XML_FreeContentModel(XML_Parser parser, XML_Content *model)
+{
+ FREE(model);
+}
+
+void * XMLCALL
+XML_MemMalloc(XML_Parser parser, size_t size)
+{
+ return MALLOC(size);
+}
+
+void * XMLCALL
+XML_MemRealloc(XML_Parser parser, void *ptr, size_t size)
+{
+ return REALLOC(ptr, size);
+}
+
+void XMLCALL
+XML_MemFree(XML_Parser parser, void *ptr)
+{
+ FREE(ptr);
+}
+
+void XMLCALL
+XML_DefaultCurrent(XML_Parser parser)
+{
+ if (defaultHandler) {
+ if (openInternalEntities)
+ reportDefault(parser,
+ internalEncoding,
+ openInternalEntities->internalEventPtr,
+ openInternalEntities->internalEventEndPtr);
+ else
+ reportDefault(parser, encoding, eventPtr, eventEndPtr);
+ }
+}
+
+const XML_LChar * XMLCALL
+XML_ErrorString(enum XML_Error code)
+{
+ static const XML_LChar* const message[] = {
+ 0,
+ XML_L("out of memory"),
+ XML_L("syntax error"),
+ XML_L("no element found"),
+ XML_L("not well-formed (invalid token)"),
+ XML_L("unclosed token"),
+ XML_L("partial character"),
+ XML_L("mismatched tag"),
+ XML_L("duplicate attribute"),
+ XML_L("junk after document element"),
+ XML_L("illegal parameter entity reference"),
+ XML_L("undefined entity"),
+ XML_L("recursive entity reference"),
+ XML_L("asynchronous entity"),
+ XML_L("reference to invalid character number"),
+ XML_L("reference to binary entity"),
+ XML_L("reference to external entity in attribute"),
+ XML_L("XML or text declaration not at start of entity"),
+ XML_L("unknown encoding"),
+ XML_L("encoding specified in XML declaration is incorrect"),
+ XML_L("unclosed CDATA section"),
+ XML_L("error in processing external entity reference"),
+ XML_L("document is not standalone"),
+ XML_L("unexpected parser state - please send a bug report"),
+ XML_L("entity declared in parameter entity"),
+ XML_L("requested feature requires XML_DTD support in Expat"),
+ XML_L("cannot change setting once parsing has begun"),
+ XML_L("unbound prefix"),
+ XML_L("must not undeclare prefix"),
+ XML_L("incomplete markup in parameter entity"),
+ XML_L("XML declaration not well-formed"),
+ XML_L("text declaration not well-formed"),
+ XML_L("illegal character(s) in public id"),
+ XML_L("parser suspended"),
+ XML_L("parser not suspended"),
+ XML_L("parsing aborted"),
+ XML_L("parsing finished"),
+ XML_L("cannot suspend in external parameter entity"),
+ XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name"),
+ XML_L("reserved prefix (xmlns) must not be declared or undeclared"),
+ XML_L("prefix must not be bound to one of the reserved namespace names")
+ };
+ if (code > 0 && code < sizeof(message)/sizeof(message[0]))
+ return message[code];
+ return NULL;
+}
+
+const XML_LChar * XMLCALL
+XML_ExpatVersion(void) {
+
+ /* V1 is used to string-ize the version number. However, it would
+ string-ize the actual version macro *names* unless we get them
+ substituted before being passed to V1. CPP is defined to expand
+ a macro, then rescan for more expansions. Thus, we use V2 to expand
+ the version macros, then CPP will expand the resulting V1() macro
+ with the correct numerals. */
+ /* ### I'm assuming cpp is portable in this respect... */
+
+#define V1(a,b,c) XML_L(#a)XML_L(".")XML_L(#b)XML_L(".")XML_L(#c)
+#define V2(a,b,c) XML_L("expat_")V1(a,b,c)
+
+ return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
+
+#undef V1
+#undef V2
+}
+
+XML_Expat_Version XMLCALL
+XML_ExpatVersionInfo(void)
+{
+ XML_Expat_Version version;
+
+ version.major = XML_MAJOR_VERSION;
+ version.minor = XML_MINOR_VERSION;
+ version.micro = XML_MICRO_VERSION;
+
+ return version;
+}
+
+const XML_Feature * XMLCALL
+XML_GetFeatureList(void)
+{
+ static const XML_Feature features[] = {
+ {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
+ sizeof(XML_Char)},
+ {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
+ sizeof(XML_LChar)},
+#ifdef XML_UNICODE
+ {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
+#endif
+#ifdef XML_UNICODE_WCHAR_T
+ {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
+#endif
+#ifdef XML_DTD
+ {XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
+#endif
+#ifdef XML_CONTEXT_BYTES
+ {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
+ XML_CONTEXT_BYTES},
+#endif
+#ifdef XML_MIN_SIZE
+ {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
+#endif
+#ifdef XML_NS
+ {XML_FEATURE_NS, XML_L("XML_NS"), 0},
+#endif
+ {XML_FEATURE_END, NULL, 0}
+ };
+
+ return features;
+}
+
+/* Initially tag->rawName always points into the parse buffer;
+ for those TAG instances opened while the current parse buffer was
+ processed, and not yet closed, we need to store tag->rawName in a more
+ permanent location, since the parse buffer is about to be discarded.
+*/
+static XML_Bool
+storeRawNames(XML_Parser parser)
+{
+ TAG *tag = tagStack;
+ while (tag) {
+ int bufSize;
+ int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
+ char *rawNameBuf = tag->buf + nameLen;
+ /* Stop if already stored. Since tagStack is a stack, we can stop
+ at the first entry that has already been copied; everything
+ below it in the stack is already been accounted for in a
+ previous call to this function.
+ */
+ if (tag->rawName == rawNameBuf)
+ break;
+ /* For re-use purposes we need to ensure that the
+ size of tag->buf is a multiple of sizeof(XML_Char).
+ */
+ bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
+ if (bufSize > tag->bufEnd - tag->buf) {
+ char *temp = (char *)REALLOC(tag->buf, bufSize);
+ if (temp == NULL)
+ return XML_FALSE;
+ /* if tag->name.str points to tag->buf (only when namespace
+ processing is off) then we have to update it
+ */
+ if (tag->name.str == (XML_Char *)tag->buf)
+ tag->name.str = (XML_Char *)temp;
+ /* if tag->name.localPart is set (when namespace processing is on)
+ then update it as well, since it will always point into tag->buf
+ */
+ if (tag->name.localPart)
+ tag->name.localPart = (XML_Char *)temp + (tag->name.localPart -
+ (XML_Char *)tag->buf);
+ tag->buf = temp;
+ tag->bufEnd = temp + bufSize;
+ rawNameBuf = temp + nameLen;
+ }
+ memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
+ tag->rawName = rawNameBuf;
+ tag = tag->parent;
+ }
+ return XML_TRUE;
+}
+
+static enum XML_Error PTRCALL
+contentProcessor(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ enum XML_Error result = doContent(parser, 0, encoding, start, end,
+ endPtr, (XML_Bool)!ps_finalBuffer);
+ if (result == XML_ERROR_NONE) {
+ if (!storeRawNames(parser))
+ return XML_ERROR_NO_MEMORY;
+ }
+ return result;
+}
+
+static enum XML_Error PTRCALL
+externalEntityInitProcessor(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ enum XML_Error result = initializeEncoding(parser);
+ if (result != XML_ERROR_NONE)
+ return result;
+ processor = externalEntityInitProcessor2;
+ return externalEntityInitProcessor2(parser, start, end, endPtr);
+}
+
+static enum XML_Error PTRCALL
+externalEntityInitProcessor2(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ const char *next = start; /* XmlContentTok doesn't always set the last arg */
+ int tok = XmlContentTok(encoding, start, end, &next);
+ switch (tok) {
+ case XML_TOK_BOM:
+ /* If we are at the end of the buffer, this would cause the next stage,
+ i.e. externalEntityInitProcessor3, to pass control directly to
+ doContent (by detecting XML_TOK_NONE) without processing any xml text
+ declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
+ */
+ if (next == end && !ps_finalBuffer) {
+ *endPtr = next;
+ return XML_ERROR_NONE;
+ }
+ start = next;
+ break;
+ case XML_TOK_PARTIAL:
+ if (!ps_finalBuffer) {
+ *endPtr = start;
+ return XML_ERROR_NONE;
+ }
+ eventPtr = start;
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ if (!ps_finalBuffer) {
+ *endPtr = start;
+ return XML_ERROR_NONE;
+ }
+ eventPtr = start;
+ return XML_ERROR_PARTIAL_CHAR;
+ }
+ processor = externalEntityInitProcessor3;
+ return externalEntityInitProcessor3(parser, start, end, endPtr);
+}
+
+static enum XML_Error PTRCALL
+externalEntityInitProcessor3(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ int tok;
+ const char *next = start; /* XmlContentTok doesn't always set the last arg */
+ eventPtr = start;
+ tok = XmlContentTok(encoding, start, end, &next);
+ eventEndPtr = next;
+
+ switch (tok) {
+ case XML_TOK_XML_DECL:
+ {
+ enum XML_Error result;
+ result = processXmlDecl(parser, 1, start, next);
+ if (result != XML_ERROR_NONE)
+ return result;
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ *endPtr = next;
+ return XML_ERROR_NONE;
+ case XML_FINISHED:
+ return XML_ERROR_ABORTED;
+ default:
+ start = next;
+ }
+ }
+ break;
+ case XML_TOK_PARTIAL:
+ if (!ps_finalBuffer) {
+ *endPtr = start;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ if (!ps_finalBuffer) {
+ *endPtr = start;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_PARTIAL_CHAR;
+ }
+ processor = externalEntityContentProcessor;
+ tagLevel = 1;
+ return externalEntityContentProcessor(parser, start, end, endPtr);
+}
+
+static enum XML_Error PTRCALL
+externalEntityContentProcessor(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ enum XML_Error result = doContent(parser, 1, encoding, start, end,
+ endPtr, (XML_Bool)!ps_finalBuffer);
+ if (result == XML_ERROR_NONE) {
+ if (!storeRawNames(parser))
+ return XML_ERROR_NO_MEMORY;
+ }
+ return result;
+}
+
+static enum XML_Error
+doContent(XML_Parser parser,
+ int startTagLevel,
+ const ENCODING *enc,
+ const char *s,
+ const char *end,
+ const char **nextPtr,
+ XML_Bool haveMore)
+{
+ /* save one level of indirection */
+ DTD * const dtd = _dtd;
+
+ const char **eventPP;
+ const char **eventEndPP;
+ if (enc == encoding) {
+ eventPP = &eventPtr;
+ eventEndPP = &eventEndPtr;
+ }
+ else {
+ eventPP = &(openInternalEntities->internalEventPtr);
+ eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ }
+ *eventPP = s;
+
+ for (;;) {
+ const char *next = s; /* XmlContentTok doesn't always set the last arg */
+ int tok = XmlContentTok(enc, s, end, &next);
+ *eventEndPP = next;
+ switch (tok) {
+ case XML_TOK_TRAILING_CR:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ *eventEndPP = end;
+ if (characterDataHandler) {
+ XML_Char c = 0xA;
+ characterDataHandler(handlerArg, &c, 1);
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, end);
+ /* We are at the end of the final buffer, should we check for
+ XML_SUSPENDED, XML_FINISHED?
+ */
+ if (startTagLevel == 0)
+ return XML_ERROR_NO_ELEMENTS;
+ if (tagLevel != startTagLevel)
+ return XML_ERROR_ASYNC_ENTITY;
+ *nextPtr = end;
+ return XML_ERROR_NONE;
+ case XML_TOK_NONE:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ if (startTagLevel > 0) {
+ if (tagLevel != startTagLevel)
+ return XML_ERROR_ASYNC_ENTITY;
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_NO_ELEMENTS;
+ case XML_TOK_INVALID:
+ *eventPP = next;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_PARTIAL_CHAR;
+ case XML_TOK_ENTITY_REF:
+ {
+ const XML_Char *name;
+ ENTITY *entity;
+ XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (ch) {
+ if (characterDataHandler)
+ characterDataHandler(handlerArg, &ch, 1);
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ }
+ name = poolStoreString(&dtd->pool, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!name)
+ return XML_ERROR_NO_MEMORY;
+ entity = (ENTITY *)lookup(&dtd->generalEntities, name, 0);
+ poolDiscard(&dtd->pool);
+ /* First, determine if a check for an existing declaration is needed;
+ if yes, check that the entity exists, and that it is internal,
+ otherwise call the skipped entity or default handler.
+ */
+ if (!dtd->hasParamEntityRefs || dtd->standalone) {
+ if (!entity)
+ return XML_ERROR_UNDEFINED_ENTITY;
+ else if (!entity->is_internal)
+ return XML_ERROR_ENTITY_DECLARED_IN_PE;
+ }
+ else if (!entity) {
+ if (skippedEntityHandler)
+ skippedEntityHandler(handlerArg, name, 0);
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ }
+ if (entity->open)
+ return XML_ERROR_RECURSIVE_ENTITY_REF;
+ if (entity->notation)
+ return XML_ERROR_BINARY_ENTITY_REF;
+ if (entity->textPtr) {
+ enum XML_Error result;
+ if (!defaultExpandInternalEntities) {
+ if (skippedEntityHandler)
+ skippedEntityHandler(handlerArg, entity->name, 0);
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ }
+ result = processInternalEntity(parser, entity, XML_FALSE);
+ if (result != XML_ERROR_NONE)
+ return result;
+ }
+ else if (externalEntityRefHandler) {
+ const XML_Char *context;
+ entity->open = XML_TRUE;
+ context = getContext(parser);
+ entity->open = XML_FALSE;
+ if (!context)
+ return XML_ERROR_NO_MEMORY;
+ if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ context,
+ entity->base,
+ entity->systemId,
+ entity->publicId))
+ return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
+ poolDiscard(&tempPool);
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ }
+ case XML_TOK_START_TAG_NO_ATTS:
+ /* fall through */
+ case XML_TOK_START_TAG_WITH_ATTS:
+ {
+ TAG *tag;
+ enum XML_Error result;
+ XML_Char *toPtr;
+ if (freeTagList) {
+ tag = freeTagList;
+ freeTagList = freeTagList->parent;
+ }
+ else {
+ tag = (TAG *)MALLOC(sizeof(TAG));
+ if (!tag)
+ return XML_ERROR_NO_MEMORY;
+ tag->buf = (char *)MALLOC(INIT_TAG_BUF_SIZE);
+ if (!tag->buf) {
+ FREE(tag);
+ return XML_ERROR_NO_MEMORY;
+ }
+ tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
+ }
+ tag->bindings = NULL;
+ tag->parent = tagStack;
+ tagStack = tag;
+ tag->name.localPart = NULL;
+ tag->name.prefix = NULL;
+ tag->rawName = s + enc->minBytesPerChar;
+ tag->rawNameLength = XmlNameLength(enc, tag->rawName);
+ ++tagLevel;
+ {
+ const char *rawNameEnd = tag->rawName + tag->rawNameLength;
+ const char *fromPtr = tag->rawName;
+ toPtr = (XML_Char *)tag->buf;
+ for (;;) {
+ int bufSize;
+ int convLen;
+ XmlConvert(enc,
+ &fromPtr, rawNameEnd,
+ (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1);
+ convLen = (int)(toPtr - (XML_Char *)tag->buf);
+ if (fromPtr == rawNameEnd) {
+ tag->name.strLen = convLen;
+ break;
+ }
+ bufSize = (int)(tag->bufEnd - tag->buf) << 1;
+ {
+ char *temp = (char *)REALLOC(tag->buf, bufSize);
+ if (temp == NULL)
+ return XML_ERROR_NO_MEMORY;
+ tag->buf = temp;
+ tag->bufEnd = temp + bufSize;
+ toPtr = (XML_Char *)temp + convLen;
+ }
+ }
+ }
+ tag->name.str = (XML_Char *)tag->buf;
+ *toPtr = XML_T('\0');
+ result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
+ if (result)
+ return result;
+ if (startElementHandler)
+ startElementHandler(handlerArg, tag->name.str,
+ (const XML_Char **)atts);
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ poolClear(&tempPool);
+ break;
+ }
+ case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
+ /* fall through */
+ case XML_TOK_EMPTY_ELEMENT_WITH_ATTS:
+ {
+ const char *rawName = s + enc->minBytesPerChar;
+ enum XML_Error result;
+ BINDING *bindings = NULL;
+ XML_Bool noElmHandlers = XML_TRUE;
+ TAG_NAME name;
+ name.str = poolStoreString(&tempPool, enc, rawName,
+ rawName + XmlNameLength(enc, rawName));
+ if (!name.str)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&tempPool);
+ result = storeAtts(parser, enc, s, &name, &bindings);
+ if (result)
+ return result;
+ poolFinish(&tempPool);
+ if (startElementHandler) {
+ startElementHandler(handlerArg, name.str, (const XML_Char **)atts);
+ noElmHandlers = XML_FALSE;
+ }
+ if (endElementHandler) {
+ if (startElementHandler)
+ *eventPP = *eventEndPP;
+ endElementHandler(handlerArg, name.str);
+ noElmHandlers = XML_FALSE;
+ }
+ if (noElmHandlers && defaultHandler)
+ reportDefault(parser, enc, s, next);
+ poolClear(&tempPool);
+ while (bindings) {
+ BINDING *b = bindings;
+ if (endNamespaceDeclHandler)
+ endNamespaceDeclHandler(handlerArg, b->prefix->name);
+ bindings = bindings->nextTagBinding;
+ b->nextTagBinding = freeBindingList;
+ freeBindingList = b;
+ b->prefix->binding = b->prevPrefixBinding;
+ }
+ }
+ if (tagLevel == 0)
+ return epilogProcessor(parser, next, end, nextPtr);
+ break;
+ case XML_TOK_END_TAG:
+ if (tagLevel == startTagLevel)
+ return XML_ERROR_ASYNC_ENTITY;
+ else {
+ int len;
+ const char *rawName;
+ TAG *tag = tagStack;
+ tagStack = tag->parent;
+ tag->parent = freeTagList;
+ freeTagList = tag;
+ rawName = s + enc->minBytesPerChar*2;
+ len = XmlNameLength(enc, rawName);
+ if (len != tag->rawNameLength
+ || memcmp(tag->rawName, rawName, len) != 0) {
+ *eventPP = rawName;
+ return XML_ERROR_TAG_MISMATCH;
+ }
+ --tagLevel;
+ if (endElementHandler) {
+ const XML_Char *localPart;
+ const XML_Char *prefix;
+ XML_Char *uri;
+ localPart = tag->name.localPart;
+ if (ns && localPart) {
+ /* localPart and prefix may have been overwritten in
+ tag->name.str, since this points to the binding->uri
+ buffer which gets re-used; so we have to add them again
+ */
+ uri = (XML_Char *)tag->name.str + tag->name.uriLen;
+ /* don't need to check for space - already done in storeAtts() */
+ while (*localPart) *uri++ = *localPart++;
+ prefix = (XML_Char *)tag->name.prefix;
+ if (ns_triplets && prefix) {
+ *uri++ = namespaceSeparator;
+ while (*prefix) *uri++ = *prefix++;
+ }
+ *uri = XML_T('\0');
+ }
+ endElementHandler(handlerArg, tag->name.str);
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ while (tag->bindings) {
+ BINDING *b = tag->bindings;
+ if (endNamespaceDeclHandler)
+ endNamespaceDeclHandler(handlerArg, b->prefix->name);
+ tag->bindings = tag->bindings->nextTagBinding;
+ b->nextTagBinding = freeBindingList;
+ freeBindingList = b;
+ b->prefix->binding = b->prevPrefixBinding;
+ }
+ if (tagLevel == 0)
+ return epilogProcessor(parser, next, end, nextPtr);
+ }
+ break;
+ case XML_TOK_CHAR_REF:
+ {
+ int n = XmlCharRefNumber(enc, s);
+ if (n < 0)
+ return XML_ERROR_BAD_CHAR_REF;
+ if (characterDataHandler) {
+ XML_Char buf[XML_ENCODE_MAX];
+ characterDataHandler(handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ }
+ break;
+ case XML_TOK_XML_DECL:
+ return XML_ERROR_MISPLACED_XML_PI;
+ case XML_TOK_DATA_NEWLINE:
+ if (characterDataHandler) {
+ XML_Char c = 0xA;
+ characterDataHandler(handlerArg, &c, 1);
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ case XML_TOK_CDATA_SECT_OPEN:
+ {
+ enum XML_Error result;
+ if (startCdataSectionHandler)
+ startCdataSectionHandler(handlerArg);
+#if 0
+ /* Suppose you doing a transformation on a document that involves
+ changing only the character data. You set up a defaultHandler
+ and a characterDataHandler. The defaultHandler simply copies
+ characters through. The characterDataHandler does the
+ transformation and writes the characters out escaping them as
+ necessary. This case will fail to work if we leave out the
+ following two lines (because & and < inside CDATA sections will
+ be incorrectly escaped).
+
+ However, now we have a start/endCdataSectionHandler, so it seems
+ easier to let the user deal with this.
+ */
+ else if (characterDataHandler)
+ characterDataHandler(handlerArg, dataBuf, 0);
+#endif
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
+ if (result != XML_ERROR_NONE)
+ return result;
+ else if (!next) {
+ processor = cdataSectionProcessor;
+ return result;
+ }
+ }
+ break;
+ case XML_TOK_TRAILING_RSQB:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ if (characterDataHandler) {
+ if (MUST_CONVERT(enc, s)) {
+ ICHAR *dataPtr = (ICHAR *)dataBuf;
+ XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
+ characterDataHandler(handlerArg, dataBuf,
+ (int)(dataPtr - (ICHAR *)dataBuf));
+ }
+ else
+ characterDataHandler(handlerArg,
+ (XML_Char *)s,
+ (int)((XML_Char *)end - (XML_Char *)s));
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, end);
+ /* We are at the end of the final buffer, should we check for
+ XML_SUSPENDED, XML_FINISHED?
+ */
+ if (startTagLevel == 0) {
+ *eventPP = end;
+ return XML_ERROR_NO_ELEMENTS;
+ }
+ if (tagLevel != startTagLevel) {
+ *eventPP = end;
+ return XML_ERROR_ASYNC_ENTITY;
+ }
+ *nextPtr = end;
+ return XML_ERROR_NONE;
+ case XML_TOK_DATA_CHARS:
+ if (characterDataHandler) {
+ if (MUST_CONVERT(enc, s)) {
+ for (;;) {
+ ICHAR *dataPtr = (ICHAR *)dataBuf;
+ XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
+ *eventEndPP = s;
+ characterDataHandler(handlerArg, dataBuf,
+ (int)(dataPtr - (ICHAR *)dataBuf));
+ if (s == next)
+ break;
+ *eventPP = s;
+ }
+ }
+ else
+ characterDataHandler(handlerArg,
+ (XML_Char *)s,
+ (int)((XML_Char *)next - (XML_Char *)s));
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ case XML_TOK_PI:
+ if (!reportProcessingInstruction(parser, enc, s, next))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ case XML_TOK_COMMENT:
+ if (!reportComment(parser, enc, s, next))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ default:
+ if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ }
+ *eventPP = s = next;
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ case XML_FINISHED:
+ return XML_ERROR_ABORTED;
+ default: ;
+ }
+ }
+ /* not reached */
+}
+
+/* Precondition: all arguments must be non-NULL;
+ Purpose:
+ - normalize attributes
+ - check attributes for well-formedness
+ - generate namespace aware attribute names (URI, prefix)
+ - build list of attributes for startElementHandler
+ - default attributes
+ - process namespace declarations (check and report them)
+ - generate namespace aware element name (URI, prefix)
+*/
+static enum XML_Error
+storeAtts(XML_Parser parser, const ENCODING *enc,
+ const char *attStr, TAG_NAME *tagNamePtr,
+ BINDING **bindingsPtr)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ ELEMENT_TYPE *elementType;
+ int nDefaultAtts;
+ const XML_Char **appAtts; /* the attribute list for the application */
+ int attIndex = 0;
+ int prefixLen;
+ int i;
+ int n;
+ XML_Char *uri;
+ int nPrefixes = 0;
+ BINDING *binding;
+ const XML_Char *localPart;
+
+ /* lookup the element type name */
+ elementType = (ELEMENT_TYPE *)lookup(&dtd->elementTypes, tagNamePtr->str,0);
+ if (!elementType) {
+ const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
+ if (!name)
+ return XML_ERROR_NO_MEMORY;
+ elementType = (ELEMENT_TYPE *)lookup(&dtd->elementTypes, name,
+ sizeof(ELEMENT_TYPE));
+ if (!elementType)
+ return XML_ERROR_NO_MEMORY;
+ if (ns && !setElementTypePrefix(parser, elementType))
+ return XML_ERROR_NO_MEMORY;
+ }
+ nDefaultAtts = elementType->nDefaultAtts;
+
+ /* get the attributes from the tokenizer */
+ n = XmlGetAttributes(enc, attStr, attsSize, atts);
+ if (n + nDefaultAtts > attsSize) {
+ int oldAttsSize = attsSize;
+ ATTRIBUTE *temp;
+ attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
+ temp = (ATTRIBUTE *)REALLOC((void *)atts, attsSize * sizeof(ATTRIBUTE));
+ if (temp == NULL)
+ return XML_ERROR_NO_MEMORY;
+ atts = temp;
+ if (n > oldAttsSize)
+ XmlGetAttributes(enc, attStr, n, atts);
+ }
+
+ appAtts = (const XML_Char **)atts;
+ for (i = 0; i < n; i++) {
+ /* add the name and value to the attribute list */
+ ATTRIBUTE_ID *attId = getAttributeId(parser, enc, atts[i].name,
+ atts[i].name
+ + XmlNameLength(enc, atts[i].name));
+ if (!attId)
+ return XML_ERROR_NO_MEMORY;
+ /* Detect duplicate attributes by their QNames. This does not work when
+ namespace processing is turned on and different prefixes for the same
+ namespace are used. For this case we have a check further down.
+ */
+ if ((attId->name)[-1]) {
+ if (enc == encoding)
+ eventPtr = atts[i].name;
+ return XML_ERROR_DUPLICATE_ATTRIBUTE;
+ }
+ (attId->name)[-1] = 1;
+ appAtts[attIndex++] = attId->name;
+ if (!atts[i].normalized) {
+ enum XML_Error result;
+ XML_Bool isCdata = XML_TRUE;
+
+ /* figure out whether declared as other than CDATA */
+ if (attId->maybeTokenized) {
+ int j;
+ for (j = 0; j < nDefaultAtts; j++) {
+ if (attId == elementType->defaultAtts[j].id) {
+ isCdata = elementType->defaultAtts[j].isCdata;
+ break;
+ }
+ }
+ }
+
+ /* normalize the attribute value */
+ result = storeAttributeValue(parser, enc, isCdata,
+ atts[i].valuePtr, atts[i].valueEnd,
+ &tempPool);
+ if (result)
+ return result;
+ appAtts[attIndex] = poolStart(&tempPool);
+ poolFinish(&tempPool);
+ }
+ else {
+ /* the value did not need normalizing */
+ appAtts[attIndex] = poolStoreString(&tempPool, enc, atts[i].valuePtr,
+ atts[i].valueEnd);
+ if (appAtts[attIndex] == 0)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&tempPool);
+ }
+ /* handle prefixed attribute names */
+ if (attId->prefix) {
+ if (attId->xmlns) {
+ /* deal with namespace declarations here */
+ enum XML_Error result = addBinding(parser, attId->prefix, attId,
+ appAtts[attIndex], bindingsPtr);
+ if (result)
+ return result;
+ --attIndex;
+ }
+ else {
+ /* deal with other prefixed names later */
+ attIndex++;
+ nPrefixes++;
+ (attId->name)[-1] = 2;
+ }
+ }
+ else
+ attIndex++;
+ }
+
+ /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
+ nSpecifiedAtts = attIndex;
+ if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
+ for (i = 0; i < attIndex; i += 2)
+ if (appAtts[i] == elementType->idAtt->name) {
+ idAttIndex = i;
+ break;
+ }
+ }
+ else
+ idAttIndex = -1;
+
+ /* do attribute defaulting */
+ for (i = 0; i < nDefaultAtts; i++) {
+ const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
+ if (!(da->id->name)[-1] && da->value) {
+ if (da->id->prefix) {
+ if (da->id->xmlns) {
+ enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
+ da->value, bindingsPtr);
+ if (result)
+ return result;
+ }
+ else {
+ (da->id->name)[-1] = 2;
+ nPrefixes++;
+ appAtts[attIndex++] = da->id->name;
+ appAtts[attIndex++] = da->value;
+ }
+ }
+ else {
+ (da->id->name)[-1] = 1;
+ appAtts[attIndex++] = da->id->name;
+ appAtts[attIndex++] = da->value;
+ }
+ }
+ }
+ appAtts[attIndex] = 0;
+
+ /* expand prefixed attribute names, check for duplicates,
+ and clear flags that say whether attributes were specified */
+ i = 0;
+ if (nPrefixes) {
+ int j; /* hash table index */
+ unsigned long version = nsAttsVersion;
+ int nsAttsSize = (int)1 << nsAttsPower;
+ /* size of hash table must be at least 2 * (# of prefixed attributes) */
+ if ((nPrefixes << 1) >> nsAttsPower) { /* true for nsAttsPower = 0 */
+ NS_ATT *temp;
+ /* hash table size must also be a power of 2 and >= 8 */
+ while (nPrefixes >> nsAttsPower++);
+ if (nsAttsPower < 3)
+ nsAttsPower = 3;
+ nsAttsSize = (int)1 << nsAttsPower;
+ temp = (NS_ATT *)REALLOC(nsAtts, nsAttsSize * sizeof(NS_ATT));
+ if (!temp)
+ return XML_ERROR_NO_MEMORY;
+ nsAtts = temp;
+ version = 0; /* force re-initialization of nsAtts hash table */
+ }
+ /* using a version flag saves us from initializing nsAtts every time */
+ if (!version) { /* initialize version flags when version wraps around */
+ version = INIT_ATTS_VERSION;
+ for (j = nsAttsSize; j != 0; )
+ nsAtts[--j].version = version;
+ }
+ nsAttsVersion = --version;
+
+ /* expand prefixed names and check for duplicates */
+ for (; i < attIndex; i += 2) {
+ const XML_Char *s = appAtts[i];
+ if (s[-1] == 2) { /* prefixed */
+ ATTRIBUTE_ID *id;
+ const BINDING *b;
+ unsigned long uriHash = 0;
+ ((XML_Char *)s)[-1] = 0; /* clear flag */
+ id = (ATTRIBUTE_ID *)lookup(&dtd->attributeIds, s, 0);
+ if (!id)
+ return XML_ERROR_NO_MEMORY;
+ b = id->prefix->binding;
+ if (!b)
+ return XML_ERROR_UNBOUND_PREFIX;
+
+ /* as we expand the name we also calculate its hash value */
+ for (j = 0; j < b->uriLen; j++) {
+ const XML_Char c = b->uri[j];
+ if (!poolAppendChar(&tempPool, c))
+ return XML_ERROR_NO_MEMORY;
+ uriHash = CHAR_HASH(uriHash, c);
+ }
+ while (*s++ != XML_T(':'))
+ ;
+ do { /* copies null terminator */
+ const XML_Char c = *s;
+ if (!poolAppendChar(&tempPool, *s))
+ return XML_ERROR_NO_MEMORY;
+ uriHash = CHAR_HASH(uriHash, c);
+ } while (*s++);
+
+ { /* Check hash table for duplicate of expanded name (uriName).
+ Derived from code in lookup(HASH_TABLE *table, ...).
+ */
+ unsigned char step = 0;
+ unsigned long mask = nsAttsSize - 1;
+ j = uriHash & mask; /* index into hash table */
+ while (nsAtts[j].version == version) {
+ /* for speed we compare stored hash values first */
+ if (uriHash == nsAtts[j].hash) {
+ const XML_Char *s1 = poolStart(&tempPool);
+ const XML_Char *s2 = nsAtts[j].uriName;
+ /* s1 is null terminated, but not s2 */
+ for (; *s1 == *s2 && *s1 != 0; s1++, s2++);
+ if (*s1 == 0)
+ return XML_ERROR_DUPLICATE_ATTRIBUTE;
+ }
+ if (!step)
+ step = PROBE_STEP(uriHash, mask, nsAttsPower);
+ j < step ? (j += nsAttsSize - step) : (j -= step);
+ }
+ }
+
+ if (ns_triplets) { /* append namespace separator and prefix */
+ tempPool.ptr[-1] = namespaceSeparator;
+ s = b->prefix->name;
+ do {
+ if (!poolAppendChar(&tempPool, *s))
+ return XML_ERROR_NO_MEMORY;
+ } while (*s++);
+ }
+
+ /* store expanded name in attribute list */
+ s = poolStart(&tempPool);
+ poolFinish(&tempPool);
+ appAtts[i] = s;
+
+ /* fill empty slot with new version, uriName and hash value */
+ nsAtts[j].version = version;
+ nsAtts[j].hash = uriHash;
+ nsAtts[j].uriName = s;
+
+ if (!--nPrefixes) {
+ i += 2;
+ break;
+ }
+ }
+ else /* not prefixed */
+ ((XML_Char *)s)[-1] = 0; /* clear flag */
+ }
+ }
+ /* clear flags for the remaining attributes */
+ for (; i < attIndex; i += 2)
+ ((XML_Char *)(appAtts[i]))[-1] = 0;
+ for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
+ binding->attId->name[-1] = 0;
+
+ if (!ns)
+ return XML_ERROR_NONE;
+
+ /* expand the element type name */
+ if (elementType->prefix) {
+ binding = elementType->prefix->binding;
+ if (!binding)
+ return XML_ERROR_UNBOUND_PREFIX;
+ localPart = tagNamePtr->str;
+ while (*localPart++ != XML_T(':'))
+ ;
+ }
+ else if (dtd->defaultPrefix.binding) {
+ binding = dtd->defaultPrefix.binding;
+ localPart = tagNamePtr->str;
+ }
+ else
+ return XML_ERROR_NONE;
+ prefixLen = 0;
+ if (ns_triplets && binding->prefix->name) {
+ for (; binding->prefix->name[prefixLen++];)
+ ; /* prefixLen includes null terminator */
+ }
+ tagNamePtr->localPart = localPart;
+ tagNamePtr->uriLen = binding->uriLen;
+ tagNamePtr->prefix = binding->prefix->name;
+ tagNamePtr->prefixLen = prefixLen;
+ for (i = 0; localPart[i++];)
+ ; /* i includes null terminator */
+ n = i + binding->uriLen + prefixLen;
+ if (n > binding->uriAlloc) {
+ TAG *p;
+ uri = (XML_Char *)MALLOC((n + EXPAND_SPARE) * sizeof(XML_Char));
+ if (!uri)
+ return XML_ERROR_NO_MEMORY;
+ binding->uriAlloc = n + EXPAND_SPARE;
+ memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
+ for (p = tagStack; p; p = p->parent)
+ if (p->name.str == binding->uri)
+ p->name.str = uri;
+ FREE(binding->uri);
+ binding->uri = uri;
+ }
+ /* if namespaceSeparator != '\0' then uri includes it already */
+ uri = binding->uri + binding->uriLen;
+ memcpy(uri, localPart, i * sizeof(XML_Char));
+ /* we always have a namespace separator between localPart and prefix */
+ if (prefixLen) {
+ uri += i - 1;
+ *uri = namespaceSeparator; /* replace null terminator */
+ memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
+ }
+ tagNamePtr->str = binding->uri;
+ return XML_ERROR_NONE;
+}
+
+/* addBinding() overwrites the value of prefix->binding without checking.
+ Therefore one must keep track of the old value outside of addBinding().
+*/
+static enum XML_Error
+addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
+ const XML_Char *uri, BINDING **bindingsPtr)
+{
+ static const XML_Char xmlNamespace[] = {
+ 'h', 't', 't', 'p', ':', '/', '/',
+ 'w', 'w', 'w', '.', 'w', '3', '.', 'o', 'r', 'g', '/',
+ 'X', 'M', 'L', '/', '1', '9', '9', '8', '/',
+ 'n', 'a', 'm', 'e', 's', 'p', 'a', 'c', 'e', '\0'
+ };
+ static const int xmlLen =
+ (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1;
+ static const XML_Char xmlnsNamespace[] = {
+ 'h', 't', 't', 'p', ':', '/', '/',
+ 'w', 'w', 'w', '.', 'w', '3', '.', 'o', 'r', 'g', '/',
+ '2', '0', '0', '0', '/', 'x', 'm', 'l', 'n', 's', '/', '\0'
+ };
+ static const int xmlnsLen =
+ (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1;
+
+ XML_Bool mustBeXML = XML_FALSE;
+ XML_Bool isXML = XML_TRUE;
+ XML_Bool isXMLNS = XML_TRUE;
+
+ BINDING *b;
+ int len;
+
+ /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
+ if (*uri == XML_T('\0') && prefix->name)
+ return XML_ERROR_UNDECLARING_PREFIX;
+
+ if (prefix->name
+ && prefix->name[0] == XML_T('x')
+ && prefix->name[1] == XML_T('m')
+ && prefix->name[2] == XML_T('l')) {
+
+ /* Not allowed to bind xmlns */
+ if (prefix->name[3] == XML_T('n')
+ && prefix->name[4] == XML_T('s')
+ && prefix->name[5] == XML_T('\0'))
+ return XML_ERROR_RESERVED_PREFIX_XMLNS;
+
+ if (prefix->name[3] == XML_T('\0'))
+ mustBeXML = XML_TRUE;
+ }
+
+ for (len = 0; uri[len]; len++) {
+ if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
+ isXML = XML_FALSE;
+
+ if (!mustBeXML && isXMLNS
+ && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
+ isXMLNS = XML_FALSE;
+ }
+ isXML = isXML && len == xmlLen;
+ isXMLNS = isXMLNS && len == xmlnsLen;
+
+ if (mustBeXML != isXML)
+ return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
+ : XML_ERROR_RESERVED_NAMESPACE_URI;
+
+ if (isXMLNS)
+ return XML_ERROR_RESERVED_NAMESPACE_URI;
+
+ if (namespaceSeparator)
+ len++;
+ if (freeBindingList) {
+ b = freeBindingList;
+ if (len > b->uriAlloc) {
+ XML_Char *temp = (XML_Char *)REALLOC(b->uri,
+ sizeof(XML_Char) * (len + EXPAND_SPARE));
+ if (temp == NULL)
+ return XML_ERROR_NO_MEMORY;
+ b->uri = temp;
+ b->uriAlloc = len + EXPAND_SPARE;
+ }
+ freeBindingList = b->nextTagBinding;
+ }
+ else {
+ b = (BINDING *)MALLOC(sizeof(BINDING));
+ if (!b)
+ return XML_ERROR_NO_MEMORY;
+ b->uri = (XML_Char *)MALLOC(sizeof(XML_Char) * (len + EXPAND_SPARE));
+ if (!b->uri) {
+ FREE(b);
+ return XML_ERROR_NO_MEMORY;
+ }
+ b->uriAlloc = len + EXPAND_SPARE;
+ }
+ b->uriLen = len;
+ memcpy(b->uri, uri, len * sizeof(XML_Char));
+ if (namespaceSeparator)
+ b->uri[len - 1] = namespaceSeparator;
+ b->prefix = prefix;
+ b->attId = attId;
+ b->prevPrefixBinding = prefix->binding;
+ /* NULL binding when default namespace undeclared */
+ if (*uri == XML_T('\0') && prefix == &_dtd->defaultPrefix)
+ prefix->binding = NULL;
+ else
+ prefix->binding = b;
+ b->nextTagBinding = *bindingsPtr;
+ *bindingsPtr = b;
+ /* if attId == NULL then we are not starting a namespace scope */
+ if (attId && startNamespaceDeclHandler)
+ startNamespaceDeclHandler(handlerArg, prefix->name,
+ prefix->binding ? uri : 0);
+ return XML_ERROR_NONE;
+}
+
+/* The idea here is to avoid using stack for each CDATA section when
+ the whole file is parsed with one call.
+*/
+static enum XML_Error PTRCALL
+cdataSectionProcessor(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ enum XML_Error result = doCdataSection(parser, encoding, &start, end,
+ endPtr, (XML_Bool)!ps_finalBuffer);
+ if (result != XML_ERROR_NONE)
+ return result;
+ if (start) {
+ if (parentParser) { /* we are parsing an external entity */
+ processor = externalEntityContentProcessor;
+ return externalEntityContentProcessor(parser, start, end, endPtr);
+ }
+ else {
+ processor = contentProcessor;
+ return contentProcessor(parser, start, end, endPtr);
+ }
+ }
+ return result;
+}
+
+/* startPtr gets set to non-null if the section is closed, and to null if
+ the section is not yet closed.
+*/
+static enum XML_Error
+doCdataSection(XML_Parser parser,
+ const ENCODING *enc,
+ const char **startPtr,
+ const char *end,
+ const char **nextPtr,
+ XML_Bool haveMore)
+{
+ const char *s = *startPtr;
+ const char **eventPP;
+ const char **eventEndPP;
+ if (enc == encoding) {
+ eventPP = &eventPtr;
+ *eventPP = s;
+ eventEndPP = &eventEndPtr;
+ }
+ else {
+ eventPP = &(openInternalEntities->internalEventPtr);
+ eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ }
+ *eventPP = s;
+ *startPtr = NULL;
+
+ for (;;) {
+ const char *next;
+ int tok = XmlCdataSectionTok(enc, s, end, &next);
+ *eventEndPP = next;
+ switch (tok) {
+ case XML_TOK_CDATA_SECT_CLOSE:
+ if (endCdataSectionHandler)
+ endCdataSectionHandler(handlerArg);
+#if 0
+ /* see comment under XML_TOK_CDATA_SECT_OPEN */
+ else if (characterDataHandler)
+ characterDataHandler(handlerArg, dataBuf, 0);
+#endif
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ *startPtr = next;
+ *nextPtr = next;
+ if (ps_parsing == XML_FINISHED)
+ return XML_ERROR_ABORTED;
+ else
+ return XML_ERROR_NONE;
+ case XML_TOK_DATA_NEWLINE:
+ if (characterDataHandler) {
+ XML_Char c = 0xA;
+ characterDataHandler(handlerArg, &c, 1);
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ case XML_TOK_DATA_CHARS:
+ if (characterDataHandler) {
+ if (MUST_CONVERT(enc, s)) {
+ for (;;) {
+ ICHAR *dataPtr = (ICHAR *)dataBuf;
+ XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
+ *eventEndPP = next;
+ characterDataHandler(handlerArg, dataBuf,
+ (int)(dataPtr - (ICHAR *)dataBuf));
+ if (s == next)
+ break;
+ *eventPP = s;
+ }
+ }
+ else
+ characterDataHandler(handlerArg,
+ (XML_Char *)s,
+ (int)((XML_Char *)next - (XML_Char *)s));
+ }
+ else if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ break;
+ case XML_TOK_INVALID:
+ *eventPP = next;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_PARTIAL_CHAR;
+ case XML_TOK_PARTIAL:
+ case XML_TOK_NONE:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_UNCLOSED_CDATA_SECTION;
+ default:
+ *eventPP = next;
+ return XML_ERROR_UNEXPECTED_STATE;
+ }
+
+ *eventPP = s = next;
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ case XML_FINISHED:
+ return XML_ERROR_ABORTED;
+ default: ;
+ }
+ }
+ /* not reached */
+}
+
+#ifdef XML_DTD
+
+/* The idea here is to avoid using stack for each IGNORE section when
+ the whole file is parsed with one call.
+*/
+static enum XML_Error PTRCALL
+ignoreSectionProcessor(XML_Parser parser,
+ const char *start,
+ const char *end,
+ const char **endPtr)
+{
+ enum XML_Error result = doIgnoreSection(parser, encoding, &start, end,
+ endPtr, (XML_Bool)!ps_finalBuffer);
+ if (result != XML_ERROR_NONE)
+ return result;
+ if (start) {
+ processor = prologProcessor;
+ return prologProcessor(parser, start, end, endPtr);
+ }
+ return result;
+}
+
+/* startPtr gets set to non-null is the section is closed, and to null
+ if the section is not yet closed.
+*/
+static enum XML_Error
+doIgnoreSection(XML_Parser parser,
+ const ENCODING *enc,
+ const char **startPtr,
+ const char *end,
+ const char **nextPtr,
+ XML_Bool haveMore)
+{
+ const char *next;
+ int tok;
+ const char *s = *startPtr;
+ const char **eventPP;
+ const char **eventEndPP;
+ if (enc == encoding) {
+ eventPP = &eventPtr;
+ *eventPP = s;
+ eventEndPP = &eventEndPtr;
+ }
+ else {
+ eventPP = &(openInternalEntities->internalEventPtr);
+ eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ }
+ *eventPP = s;
+ *startPtr = NULL;
+ tok = XmlIgnoreSectionTok(enc, s, end, &next);
+ *eventEndPP = next;
+ switch (tok) {
+ case XML_TOK_IGNORE_SECT:
+ if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ *startPtr = next;
+ *nextPtr = next;
+ if (ps_parsing == XML_FINISHED)
+ return XML_ERROR_ABORTED;
+ else
+ return XML_ERROR_NONE;
+ case XML_TOK_INVALID:
+ *eventPP = next;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_PARTIAL_CHAR;
+ case XML_TOK_PARTIAL:
+ case XML_TOK_NONE:
+ if (haveMore) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
+ default:
+ *eventPP = next;
+ return XML_ERROR_UNEXPECTED_STATE;
+ }
+ /* not reached */
+}
+
+#endif /* XML_DTD */
+
+static enum XML_Error
+initializeEncoding(XML_Parser parser)
+{
+ const char *s;
+#ifdef XML_UNICODE
+ char encodingBuf[128];
+ if (!protocolEncodingName)
+ s = NULL;
+ else {
+ int i;
+ for (i = 0; protocolEncodingName[i]; i++) {
+ if (i == sizeof(encodingBuf) - 1
+ || (protocolEncodingName[i] & ~0x7f) != 0) {
+ encodingBuf[0] = '\0';
+ break;
+ }
+ encodingBuf[i] = (char)protocolEncodingName[i];
+ }
+ encodingBuf[i] = '\0';
+ s = encodingBuf;
+ }
+#else
+ s = protocolEncodingName;
+#endif
+ if ((ns ? XmlInitEncodingNS : XmlInitEncoding)(&initEncoding, &encoding, s))
+ return XML_ERROR_NONE;
+ return handleUnknownEncoding(parser, protocolEncodingName);
+}
+
+static enum XML_Error
+processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
+ const char *s, const char *next)
+{
+ const char *encodingName = NULL;
+ const XML_Char *storedEncName = NULL;
+ const ENCODING *newEncoding = NULL;
+ const char *version = NULL;
+ const char *versionend;
+ const XML_Char *storedversion = NULL;
+ int standalone = -1;
+ if (!(ns
+ ? XmlParseXmlDeclNS
+ : XmlParseXmlDecl)(isGeneralTextEntity,
+ encoding,
+ s,
+ next,
+ &eventPtr,
+ &version,
+ &versionend,
+ &encodingName,
+ &newEncoding,
+ &standalone)) {
+ if (isGeneralTextEntity)
+ return XML_ERROR_TEXT_DECL;
+ else
+ return XML_ERROR_XML_DECL;
+ }
+ if (!isGeneralTextEntity && standalone == 1) {
+ _dtd->standalone = XML_TRUE;
+#ifdef XML_DTD
+ if (paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
+ paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
+#endif /* XML_DTD */
+ }
+ if (xmlDeclHandler) {
+ if (encodingName != NULL) {
+ storedEncName = poolStoreString(&temp2Pool,
+ encoding,
+ encodingName,
+ encodingName
+ + XmlNameLength(encoding, encodingName));
+ if (!storedEncName)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&temp2Pool);
+ }
+ if (version) {
+ storedversion = poolStoreString(&temp2Pool,
+ encoding,
+ version,
+ versionend - encoding->minBytesPerChar);
+ if (!storedversion)
+ return XML_ERROR_NO_MEMORY;
+ }
+ xmlDeclHandler(handlerArg, storedversion, storedEncName, standalone);
+ }
+ else if (defaultHandler)
+ reportDefault(parser, encoding, s, next);
+ if (protocolEncodingName == NULL) {
+ if (newEncoding) {
+ if (newEncoding->minBytesPerChar != encoding->minBytesPerChar) {
+ eventPtr = encodingName;
+ return XML_ERROR_INCORRECT_ENCODING;
+ }
+ encoding = newEncoding;
+ }
+ else if (encodingName) {
+ enum XML_Error result;
+ if (!storedEncName) {
+ storedEncName = poolStoreString(
+ &temp2Pool, encoding, encodingName,
+ encodingName + XmlNameLength(encoding, encodingName));
+ if (!storedEncName)
+ return XML_ERROR_NO_MEMORY;
+ }
+ result = handleUnknownEncoding(parser, storedEncName);
+ poolClear(&temp2Pool);
+ if (result == XML_ERROR_UNKNOWN_ENCODING)
+ eventPtr = encodingName;
+ return result;
+ }
+ }
+
+ if (storedEncName || storedversion)
+ poolClear(&temp2Pool);
+
+ return XML_ERROR_NONE;
+}
+
+static enum XML_Error
+handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
+{
+ if (unknownEncodingHandler) {
+ XML_Encoding info;
+ int i;
+ for (i = 0; i < 256; i++)
+ info.map[i] = -1;
+ info.convert = NULL;
+ info.data = NULL;
+ info.release = NULL;
+ if (unknownEncodingHandler(unknownEncodingHandlerData, encodingName,
+ &info)) {
+ ENCODING *enc;
+ unknownEncodingMem = MALLOC(XmlSizeOfUnknownEncoding());
+ if (!unknownEncodingMem) {
+ if (info.release)
+ info.release(info.data);
+ return XML_ERROR_NO_MEMORY;
+ }
+ enc = (ns
+ ? XmlInitUnknownEncodingNS
+ : XmlInitUnknownEncoding)(unknownEncodingMem,
+ info.map,
+ info.convert,
+ info.data);
+ if (enc) {
+ unknownEncodingData = info.data;
+ unknownEncodingRelease = info.release;
+ encoding = enc;
+ return XML_ERROR_NONE;
+ }
+ }
+ if (info.release != NULL)
+ info.release(info.data);
+ }
+ return XML_ERROR_UNKNOWN_ENCODING;
+}
+
+static enum XML_Error PTRCALL
+prologInitProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ enum XML_Error result = initializeEncoding(parser);
+ if (result != XML_ERROR_NONE)
+ return result;
+ processor = prologProcessor;
+ return prologProcessor(parser, s, end, nextPtr);
+}
+
+#ifdef XML_DTD
+
+static enum XML_Error PTRCALL
+externalParEntInitProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ enum XML_Error result = initializeEncoding(parser);
+ if (result != XML_ERROR_NONE)
+ return result;
+
+ /* we know now that XML_Parse(Buffer) has been called,
+ so we consider the external parameter entity read */
+ _dtd->paramEntityRead = XML_TRUE;
+
+ if (prologState.inEntityValue) {
+ processor = entityValueInitProcessor;
+ return entityValueInitProcessor(parser, s, end, nextPtr);
+ }
+ else {
+ processor = externalParEntProcessor;
+ return externalParEntProcessor(parser, s, end, nextPtr);
+ }
+}
+
+static enum XML_Error PTRCALL
+entityValueInitProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ int tok;
+ const char *start = s;
+ const char *next = start;
+ eventPtr = start;
+
+ for (;;) {
+ tok = XmlPrologTok(encoding, start, end, &next);
+ eventEndPtr = next;
+ if (tok <= 0) {
+ if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ switch (tok) {
+ case XML_TOK_INVALID:
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ return XML_ERROR_PARTIAL_CHAR;
+ case XML_TOK_NONE: /* start == end */
+ default:
+ break;
+ }
+ /* found end of entity value - can store it now */
+ return storeEntityValue(parser, encoding, s, end);
+ }
+ else if (tok == XML_TOK_XML_DECL) {
+ enum XML_Error result;
+ result = processXmlDecl(parser, 0, start, next);
+ if (result != XML_ERROR_NONE)
+ return result;
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ case XML_FINISHED:
+ return XML_ERROR_ABORTED;
+ default:
+ *nextPtr = next;
+ }
+ /* stop scanning for text declaration - we found one */
+ processor = entityValueProcessor;
+ return entityValueProcessor(parser, next, end, nextPtr);
+ }
+ /* If we are at the end of the buffer, this would cause XmlPrologTok to
+ return XML_TOK_NONE on the next call, which would then cause the
+ function to exit with *nextPtr set to s - that is what we want for other
+ tokens, but not for the BOM - we would rather like to skip it;
+ then, when this routine is entered the next time, XmlPrologTok will
+ return XML_TOK_INVALID, since the BOM is still in the buffer
+ */
+ else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ }
+ start = next;
+ eventPtr = start;
+ }
+}
+
+static enum XML_Error PTRCALL
+externalParEntProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ const char *next = s;
+ int tok;
+
+ tok = XmlPrologTok(encoding, s, end, &next);
+ if (tok <= 0) {
+ if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ switch (tok) {
+ case XML_TOK_INVALID:
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ return XML_ERROR_PARTIAL_CHAR;
+ case XML_TOK_NONE: /* start == end */
+ default:
+ break;
+ }
+ }
+ /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
+ However, when parsing an external subset, doProlog will not accept a BOM
+ as valid, and report a syntax error, so we have to skip the BOM
+ */
+ else if (tok == XML_TOK_BOM) {
+ s = next;
+ tok = XmlPrologTok(encoding, s, end, &next);
+ }
+
+ processor = prologProcessor;
+ return doProlog(parser, encoding, s, end, tok, next,
+ nextPtr, (XML_Bool)!ps_finalBuffer);
+}
+
+static enum XML_Error PTRCALL
+entityValueProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ const char *start = s;
+ const char *next = s;
+ const ENCODING *enc = encoding;
+ int tok;
+
+ for (;;) {
+ tok = XmlPrologTok(enc, start, end, &next);
+ if (tok <= 0) {
+ if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ switch (tok) {
+ case XML_TOK_INVALID:
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ return XML_ERROR_PARTIAL_CHAR;
+ case XML_TOK_NONE: /* start == end */
+ default:
+ break;
+ }
+ /* found end of entity value - can store it now */
+ return storeEntityValue(parser, enc, s, end);
+ }
+ start = next;
+ }
+}
+
+#endif /* XML_DTD */
+
+static enum XML_Error PTRCALL
+prologProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ const char *next = s;
+ int tok = XmlPrologTok(encoding, s, end, &next);
+ return doProlog(parser, encoding, s, end, tok, next,
+ nextPtr, (XML_Bool)!ps_finalBuffer);
+}
+
+static enum XML_Error
+doProlog(XML_Parser parser,
+ const ENCODING *enc,
+ const char *s,
+ const char *end,
+ int tok,
+ const char *next,
+ const char **nextPtr,
+ XML_Bool haveMore)
+{
+#ifdef XML_DTD
+ static const XML_Char externalSubsetName[] = { '#' , '\0' };
+#endif /* XML_DTD */
+ static const XML_Char atypeCDATA[] = { 'C', 'D', 'A', 'T', 'A', '\0' };
+ static const XML_Char atypeID[] = { 'I', 'D', '\0' };
+ static const XML_Char atypeIDREF[] = { 'I', 'D', 'R', 'E', 'F', '\0' };
+ static const XML_Char atypeIDREFS[] = { 'I', 'D', 'R', 'E', 'F', 'S', '\0' };
+ static const XML_Char atypeENTITY[] = { 'E', 'N', 'T', 'I', 'T', 'Y', '\0' };
+ static const XML_Char atypeENTITIES[] =
+ { 'E', 'N', 'T', 'I', 'T', 'I', 'E', 'S', '\0' };
+ static const XML_Char atypeNMTOKEN[] = {
+ 'N', 'M', 'T', 'O', 'K', 'E', 'N', '\0' };
+ static const XML_Char atypeNMTOKENS[] = {
+ 'N', 'M', 'T', 'O', 'K', 'E', 'N', 'S', '\0' };
+ static const XML_Char notationPrefix[] = {
+ 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N', '(', '\0' };
+ static const XML_Char enumValueSep[] = { '|', '\0' };
+ static const XML_Char enumValueStart[] = { '(', '\0' };
+
+ /* save one level of indirection */
+ DTD * const dtd = _dtd;
+
+ const char **eventPP;
+ const char **eventEndPP;
+ enum XML_Content_Quant quant;
+
+ if (enc == encoding) {
+ eventPP = &eventPtr;
+ eventEndPP = &eventEndPtr;
+ }
+ else {
+ eventPP = &(openInternalEntities->internalEventPtr);
+ eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ }
+
+ for (;;) {
+ int role;
+ XML_Bool handleDefault = XML_TRUE;
+ *eventPP = s;
+ *eventEndPP = next;
+ if (tok <= 0) {
+ if (haveMore && tok != XML_TOK_INVALID) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ switch (tok) {
+ case XML_TOK_INVALID:
+ *eventPP = next;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ return XML_ERROR_PARTIAL_CHAR;
+ case -XML_TOK_PROLOG_S:
+ tok = -tok;
+ break;
+ case XML_TOK_NONE:
+#ifdef XML_DTD
+ /* for internal PE NOT referenced between declarations */
+ if (enc != encoding && !openInternalEntities->betweenDecl) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ /* WFC: PE Between Declarations - must check that PE contains
+ complete markup, not only for external PEs, but also for
+ internal PEs if the reference occurs between declarations.
+ */
+ if (isParamEntity || enc != encoding) {
+ if (XmlTokenRole(&prologState, XML_TOK_NONE, end, end, enc)
+ == XML_ROLE_ERROR)
+ return XML_ERROR_INCOMPLETE_PE;
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+#endif /* XML_DTD */
+ return XML_ERROR_NO_ELEMENTS;
+ default:
+ tok = -tok;
+ next = end;
+ break;
+ }
+ }
+ role = XmlTokenRole(&prologState, tok, s, next, enc);
+ switch (role) {
+ case XML_ROLE_XML_DECL:
+ {
+ enum XML_Error result = processXmlDecl(parser, 0, s, next);
+ if (result != XML_ERROR_NONE)
+ return result;
+ enc = encoding;
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_DOCTYPE_NAME:
+ if (startDoctypeDeclHandler) {
+ doctypeName = poolStoreString(&tempPool, enc, s, next);
+ if (!doctypeName)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&tempPool);
+ doctypePubid = NULL;
+ handleDefault = XML_FALSE;
+ }
+ doctypeSysid = NULL; /* always initialize to NULL */
+ break;
+ case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
+ if (startDoctypeDeclHandler) {
+ startDoctypeDeclHandler(handlerArg, doctypeName, doctypeSysid,
+ doctypePubid, 1);
+ doctypeName = NULL;
+ poolClear(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+ break;
+#ifdef XML_DTD
+ case XML_ROLE_TEXT_DECL:
+ {
+ enum XML_Error result = processXmlDecl(parser, 1, s, next);
+ if (result != XML_ERROR_NONE)
+ return result;
+ enc = encoding;
+ handleDefault = XML_FALSE;
+ }
+ break;
+#endif /* XML_DTD */
+ case XML_ROLE_DOCTYPE_PUBLIC_ID:
+#ifdef XML_DTD
+ useForeignDTD = XML_FALSE;
+ declEntity = (ENTITY *)lookup(&dtd->paramEntities,
+ externalSubsetName,
+ sizeof(ENTITY));
+ if (!declEntity)
+ return XML_ERROR_NO_MEMORY;
+#endif /* XML_DTD */
+ dtd->hasParamEntityRefs = XML_TRUE;
+ if (startDoctypeDeclHandler) {
+ if (!XmlIsPublicId(enc, s, next, eventPP))
+ return XML_ERROR_PUBLICID;
+ doctypePubid = poolStoreString(&tempPool, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!doctypePubid)
+ return XML_ERROR_NO_MEMORY;
+ normalizePublicId((XML_Char *)doctypePubid);
+ poolFinish(&tempPool);
+ handleDefault = XML_FALSE;
+ goto alreadyChecked;
+ }
+ /* fall through */
+ case XML_ROLE_ENTITY_PUBLIC_ID:
+ if (!XmlIsPublicId(enc, s, next, eventPP))
+ return XML_ERROR_PUBLICID;
+ alreadyChecked:
+ if (dtd->keepProcessing && declEntity) {
+ XML_Char *tem = poolStoreString(&dtd->pool,
+ enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!tem)
+ return XML_ERROR_NO_MEMORY;
+ normalizePublicId(tem);
+ declEntity->publicId = tem;
+ poolFinish(&dtd->pool);
+ if (entityDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_DOCTYPE_CLOSE:
+ if (doctypeName) {
+ startDoctypeDeclHandler(handlerArg, doctypeName,
+ doctypeSysid, doctypePubid, 0);
+ poolClear(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+ /* doctypeSysid will be non-NULL in the case of a previous
+ XML_ROLE_DOCTYPE_SYSTEM_ID, even if startDoctypeDeclHandler
+ was not set, indicating an external subset
+ */
+#ifdef XML_DTD
+ if (doctypeSysid || useForeignDTD) {
+ XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
+ dtd->hasParamEntityRefs = XML_TRUE;
+ if (paramEntityParsing && externalEntityRefHandler) {
+ ENTITY *entity = (ENTITY *)lookup(&dtd->paramEntities,
+ externalSubsetName,
+ sizeof(ENTITY));
+ if (!entity)
+ return XML_ERROR_NO_MEMORY;
+ if (useForeignDTD)
+ entity->base = curBase;
+ dtd->paramEntityRead = XML_FALSE;
+ if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ 0,
+ entity->base,
+ entity->systemId,
+ entity->publicId))
+ return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
+ if (dtd->paramEntityRead) {
+ if (!dtd->standalone &&
+ notStandaloneHandler &&
+ !notStandaloneHandler(handlerArg))
+ return XML_ERROR_NOT_STANDALONE;
+ }
+ /* if we didn't read the foreign DTD then this means that there
+ is no external subset and we must reset dtd->hasParamEntityRefs
+ */
+ else if (!doctypeSysid)
+ dtd->hasParamEntityRefs = hadParamEntityRefs;
+ /* end of DTD - no need to update dtd->keepProcessing */
+ }
+ useForeignDTD = XML_FALSE;
+ }
+#endif /* XML_DTD */
+ if (endDoctypeDeclHandler) {
+ endDoctypeDeclHandler(handlerArg);
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_INSTANCE_START:
+#ifdef XML_DTD
+ /* if there is no DOCTYPE declaration then now is the
+ last chance to read the foreign DTD
+ */
+ if (useForeignDTD) {
+ XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
+ dtd->hasParamEntityRefs = XML_TRUE;
+ if (paramEntityParsing && externalEntityRefHandler) {
+ ENTITY *entity = (ENTITY *)lookup(&dtd->paramEntities,
+ externalSubsetName,
+ sizeof(ENTITY));
+ if (!entity)
+ return XML_ERROR_NO_MEMORY;
+ entity->base = curBase;
+ dtd->paramEntityRead = XML_FALSE;
+ if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ 0,
+ entity->base,
+ entity->systemId,
+ entity->publicId))
+ return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
+ if (dtd->paramEntityRead) {
+ if (!dtd->standalone &&
+ notStandaloneHandler &&
+ !notStandaloneHandler(handlerArg))
+ return XML_ERROR_NOT_STANDALONE;
+ }
+ /* if we didn't read the foreign DTD then this means that there
+ is no external subset and we must reset dtd->hasParamEntityRefs
+ */
+ else
+ dtd->hasParamEntityRefs = hadParamEntityRefs;
+ /* end of DTD - no need to update dtd->keepProcessing */
+ }
+ }
+#endif /* XML_DTD */
+ processor = contentProcessor;
+ return contentProcessor(parser, s, end, nextPtr);
+ case XML_ROLE_ATTLIST_ELEMENT_NAME:
+ declElementType = getElementType(parser, enc, s, next);
+ if (!declElementType)
+ return XML_ERROR_NO_MEMORY;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_NAME:
+ declAttributeId = getAttributeId(parser, enc, s, next);
+ if (!declAttributeId)
+ return XML_ERROR_NO_MEMORY;
+ declAttributeIsCdata = XML_FALSE;
+ declAttributeType = NULL;
+ declAttributeIsId = XML_FALSE;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
+ declAttributeIsCdata = XML_TRUE;
+ declAttributeType = atypeCDATA;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_ID:
+ declAttributeIsId = XML_TRUE;
+ declAttributeType = atypeID;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
+ declAttributeType = atypeIDREF;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
+ declAttributeType = atypeIDREFS;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
+ declAttributeType = atypeENTITY;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
+ declAttributeType = atypeENTITIES;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
+ declAttributeType = atypeNMTOKEN;
+ goto checkAttListDeclHandler;
+ case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
+ declAttributeType = atypeNMTOKENS;
+ checkAttListDeclHandler:
+ if (dtd->keepProcessing && attlistDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
+ case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
+ if (dtd->keepProcessing && attlistDeclHandler) {
+ const XML_Char *prefix;
+ if (declAttributeType) {
+ prefix = enumValueSep;
+ }
+ else {
+ prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE
+ ? notationPrefix
+ : enumValueStart);
+ }
+ if (!poolAppendString(&tempPool, prefix))
+ return XML_ERROR_NO_MEMORY;
+ if (!poolAppend(&tempPool, enc, s, next))
+ return XML_ERROR_NO_MEMORY;
+ declAttributeType = tempPool.start;
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
+ case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
+ if (dtd->keepProcessing) {
+ if (!defineAttribute(declElementType, declAttributeId,
+ declAttributeIsCdata, declAttributeIsId,
+ 0, parser))
+ return XML_ERROR_NO_MEMORY;
+ if (attlistDeclHandler && declAttributeType) {
+ if (*declAttributeType == XML_T('(')
+ || (*declAttributeType == XML_T('N')
+ && declAttributeType[1] == XML_T('O'))) {
+ /* Enumerated or Notation type */
+ if (!poolAppendChar(&tempPool, XML_T(')'))
+ || !poolAppendChar(&tempPool, XML_T('\0')))
+ return XML_ERROR_NO_MEMORY;
+ declAttributeType = tempPool.start;
+ poolFinish(&tempPool);
+ }
+ *eventEndPP = s;
+ attlistDeclHandler(handlerArg, declElementType->name,
+ declAttributeId->name, declAttributeType,
+ 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
+ poolClear(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+ }
+ break;
+ case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
+ case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
+ if (dtd->keepProcessing) {
+ const XML_Char *attVal;
+ enum XML_Error result =
+ storeAttributeValue(parser, enc, declAttributeIsCdata,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar,
+ &dtd->pool);
+ if (result)
+ return result;
+ attVal = poolStart(&dtd->pool);
+ poolFinish(&dtd->pool);
+ /* ID attributes aren't allowed to have a default */
+ if (!defineAttribute(declElementType, declAttributeId,
+ declAttributeIsCdata, XML_FALSE, attVal, parser))
+ return XML_ERROR_NO_MEMORY;
+ if (attlistDeclHandler && declAttributeType) {
+ if (*declAttributeType == XML_T('(')
+ || (*declAttributeType == XML_T('N')
+ && declAttributeType[1] == XML_T('O'))) {
+ /* Enumerated or Notation type */
+ if (!poolAppendChar(&tempPool, XML_T(')'))
+ || !poolAppendChar(&tempPool, XML_T('\0')))
+ return XML_ERROR_NO_MEMORY;
+ declAttributeType = tempPool.start;
+ poolFinish(&tempPool);
+ }
+ *eventEndPP = s;
+ attlistDeclHandler(handlerArg, declElementType->name,
+ declAttributeId->name, declAttributeType,
+ attVal,
+ role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
+ poolClear(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+ }
+ break;
+ case XML_ROLE_ENTITY_VALUE:
+ if (dtd->keepProcessing) {
+ enum XML_Error result = storeEntityValue(parser, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (declEntity) {
+ declEntity->textPtr = poolStart(&dtd->entityValuePool);
+ declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
+ poolFinish(&dtd->entityValuePool);
+ if (entityDeclHandler) {
+ *eventEndPP = s;
+ entityDeclHandler(handlerArg,
+ declEntity->name,
+ declEntity->is_param,
+ declEntity->textPtr,
+ declEntity->textLen,
+ curBase, 0, 0, 0);
+ handleDefault = XML_FALSE;
+ }
+ }
+ else
+ poolDiscard(&dtd->entityValuePool);
+ if (result != XML_ERROR_NONE)
+ return result;
+ }
+ break;
+ case XML_ROLE_DOCTYPE_SYSTEM_ID:
+#ifdef XML_DTD
+ useForeignDTD = XML_FALSE;
+#endif /* XML_DTD */
+ dtd->hasParamEntityRefs = XML_TRUE;
+ if (startDoctypeDeclHandler) {
+ doctypeSysid = poolStoreString(&tempPool, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (doctypeSysid == NULL)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+#ifdef XML_DTD
+ else
+ /* use externalSubsetName to make doctypeSysid non-NULL
+ for the case where no startDoctypeDeclHandler is set */
+ doctypeSysid = externalSubsetName;
+#endif /* XML_DTD */
+ if (!dtd->standalone
+#ifdef XML_DTD
+ && !paramEntityParsing
+#endif /* XML_DTD */
+ && notStandaloneHandler
+ && !notStandaloneHandler(handlerArg))
+ return XML_ERROR_NOT_STANDALONE;
+#ifndef XML_DTD
+ break;
+#else /* XML_DTD */
+ if (!declEntity) {
+ declEntity = (ENTITY *)lookup(&dtd->paramEntities,
+ externalSubsetName,
+ sizeof(ENTITY));
+ if (!declEntity)
+ return XML_ERROR_NO_MEMORY;
+ declEntity->publicId = NULL;
+ }
+ /* fall through */
+#endif /* XML_DTD */
+ case XML_ROLE_ENTITY_SYSTEM_ID:
+ if (dtd->keepProcessing && declEntity) {
+ declEntity->systemId = poolStoreString(&dtd->pool, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!declEntity->systemId)
+ return XML_ERROR_NO_MEMORY;
+ declEntity->base = curBase;
+ poolFinish(&dtd->pool);
+ if (entityDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_ENTITY_COMPLETE:
+ if (dtd->keepProcessing && declEntity && entityDeclHandler) {
+ *eventEndPP = s;
+ entityDeclHandler(handlerArg,
+ declEntity->name,
+ declEntity->is_param,
+ 0,0,
+ declEntity->base,
+ declEntity->systemId,
+ declEntity->publicId,
+ 0);
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_ENTITY_NOTATION_NAME:
+ if (dtd->keepProcessing && declEntity) {
+ declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
+ if (!declEntity->notation)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&dtd->pool);
+ if (unparsedEntityDeclHandler) {
+ *eventEndPP = s;
+ unparsedEntityDeclHandler(handlerArg,
+ declEntity->name,
+ declEntity->base,
+ declEntity->systemId,
+ declEntity->publicId,
+ declEntity->notation);
+ handleDefault = XML_FALSE;
+ }
+ else if (entityDeclHandler) {
+ *eventEndPP = s;
+ entityDeclHandler(handlerArg,
+ declEntity->name,
+ 0,0,0,
+ declEntity->base,
+ declEntity->systemId,
+ declEntity->publicId,
+ declEntity->notation);
+ handleDefault = XML_FALSE;
+ }
+ }
+ break;
+ case XML_ROLE_GENERAL_ENTITY_NAME:
+ {
+ if (XmlPredefinedEntityName(enc, s, next)) {
+ declEntity = NULL;
+ break;
+ }
+ if (dtd->keepProcessing) {
+ const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
+ if (!name)
+ return XML_ERROR_NO_MEMORY;
+ declEntity = (ENTITY *)lookup(&dtd->generalEntities, name,
+ sizeof(ENTITY));
+ if (!declEntity)
+ return XML_ERROR_NO_MEMORY;
+ if (declEntity->name != name) {
+ poolDiscard(&dtd->pool);
+ declEntity = NULL;
+ }
+ else {
+ poolFinish(&dtd->pool);
+ declEntity->publicId = NULL;
+ declEntity->is_param = XML_FALSE;
+ /* if we have a parent parser or are reading an internal parameter
+ entity, then the entity declaration is not considered "internal"
+ */
+ declEntity->is_internal = !(parentParser || openInternalEntities);
+ if (entityDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ }
+ else {
+ poolDiscard(&dtd->pool);
+ declEntity = NULL;
+ }
+ }
+ break;
+ case XML_ROLE_PARAM_ENTITY_NAME:
+#ifdef XML_DTD
+ if (dtd->keepProcessing) {
+ const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
+ if (!name)
+ return XML_ERROR_NO_MEMORY;
+ declEntity = (ENTITY *)lookup(&dtd->paramEntities,
+ name, sizeof(ENTITY));
+ if (!declEntity)
+ return XML_ERROR_NO_MEMORY;
+ if (declEntity->name != name) {
+ poolDiscard(&dtd->pool);
+ declEntity = NULL;
+ }
+ else {
+ poolFinish(&dtd->pool);
+ declEntity->publicId = NULL;
+ declEntity->is_param = XML_TRUE;
+ /* if we have a parent parser or are reading an internal parameter
+ entity, then the entity declaration is not considered "internal"
+ */
+ declEntity->is_internal = !(parentParser || openInternalEntities);
+ if (entityDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ }
+ else {
+ poolDiscard(&dtd->pool);
+ declEntity = NULL;
+ }
+#else /* not XML_DTD */
+ declEntity = NULL;
+#endif /* XML_DTD */
+ break;
+ case XML_ROLE_NOTATION_NAME:
+ declNotationPublicId = NULL;
+ declNotationName = NULL;
+ if (notationDeclHandler) {
+ declNotationName = poolStoreString(&tempPool, enc, s, next);
+ if (!declNotationName)
+ return XML_ERROR_NO_MEMORY;
+ poolFinish(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_NOTATION_PUBLIC_ID:
+ if (!XmlIsPublicId(enc, s, next, eventPP))
+ return XML_ERROR_PUBLICID;
+ if (declNotationName) { /* means notationDeclHandler != NULL */
+ XML_Char *tem = poolStoreString(&tempPool,
+ enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!tem)
+ return XML_ERROR_NO_MEMORY;
+ normalizePublicId(tem);
+ declNotationPublicId = tem;
+ poolFinish(&tempPool);
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_NOTATION_SYSTEM_ID:
+ if (declNotationName && notationDeclHandler) {
+ const XML_Char *systemId
+ = poolStoreString(&tempPool, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!systemId)
+ return XML_ERROR_NO_MEMORY;
+ *eventEndPP = s;
+ notationDeclHandler(handlerArg,
+ declNotationName,
+ curBase,
+ systemId,
+ declNotationPublicId);
+ handleDefault = XML_FALSE;
+ }
+ poolClear(&tempPool);
+ break;
+ case XML_ROLE_NOTATION_NO_SYSTEM_ID:
+ if (declNotationPublicId && notationDeclHandler) {
+ *eventEndPP = s;
+ notationDeclHandler(handlerArg,
+ declNotationName,
+ curBase,
+ 0,
+ declNotationPublicId);
+ handleDefault = XML_FALSE;
+ }
+ poolClear(&tempPool);
+ break;
+ case XML_ROLE_ERROR:
+ switch (tok) {
+ case XML_TOK_PARAM_ENTITY_REF:
+ /* PE references in internal subset are
+ not allowed within declarations. */
+ return XML_ERROR_PARAM_ENTITY_REF;
+ case XML_TOK_XML_DECL:
+ return XML_ERROR_MISPLACED_XML_PI;
+ default:
+ return XML_ERROR_SYNTAX;
+ }
+#ifdef XML_DTD
+ case XML_ROLE_IGNORE_SECT:
+ {
+ enum XML_Error result;
+ if (defaultHandler)
+ reportDefault(parser, enc, s, next);
+ handleDefault = XML_FALSE;
+ result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
+ if (result != XML_ERROR_NONE)
+ return result;
+ else if (!next) {
+ processor = ignoreSectionProcessor;
+ return result;
+ }
+ }
+ break;
+#endif /* XML_DTD */
+ case XML_ROLE_GROUP_OPEN:
+ if (prologState.level >= groupSize) {
+ if (groupSize) {
+ char *temp = (char *)REALLOC(groupConnector, groupSize *= 2);
+ if (temp == NULL)
+ return XML_ERROR_NO_MEMORY;
+ groupConnector = temp;
+ if (dtd->scaffIndex) {
+ int *temp = (int *)REALLOC(dtd->scaffIndex,
+ groupSize * sizeof(int));
+ if (temp == NULL)
+ return XML_ERROR_NO_MEMORY;
+ dtd->scaffIndex = temp;
+ }
+ }
+ else {
+ groupConnector = (char *)MALLOC(groupSize = 32);
+ if (!groupConnector)
+ return XML_ERROR_NO_MEMORY;
+ }
+ }
+ groupConnector[prologState.level] = 0;
+ if (dtd->in_eldecl) {
+ int myindex = nextScaffoldPart(parser);
+ if (myindex < 0)
+ return XML_ERROR_NO_MEMORY;
+ dtd->scaffIndex[dtd->scaffLevel] = myindex;
+ dtd->scaffLevel++;
+ dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
+ if (elementDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ break;
+ case XML_ROLE_GROUP_SEQUENCE:
+ if (groupConnector[prologState.level] == '|')
+ return XML_ERROR_SYNTAX;
+ groupConnector[prologState.level] = ',';
+ if (dtd->in_eldecl && elementDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_GROUP_CHOICE:
+ if (groupConnector[prologState.level] == ',')
+ return XML_ERROR_SYNTAX;
+ if (dtd->in_eldecl
+ && !groupConnector[prologState.level]
+ && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
+ != XML_CTYPE_MIXED)
+ ) {
+ dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
+ = XML_CTYPE_CHOICE;
+ if (elementDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ groupConnector[prologState.level] = '|';
+ break;
+ case XML_ROLE_PARAM_ENTITY_REF:
+#ifdef XML_DTD
+ case XML_ROLE_INNER_PARAM_ENTITY_REF:
+ dtd->hasParamEntityRefs = XML_TRUE;
+ if (!paramEntityParsing)
+ dtd->keepProcessing = dtd->standalone;
+ else {
+ const XML_Char *name;
+ ENTITY *entity;
+ name = poolStoreString(&dtd->pool, enc,
+ s + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!name)
+ return XML_ERROR_NO_MEMORY;
+ entity = (ENTITY *)lookup(&dtd->paramEntities, name, 0);
+ poolDiscard(&dtd->pool);
+ /* first, determine if a check for an existing declaration is needed;
+ if yes, check that the entity exists, and that it is internal,
+ otherwise call the skipped entity handler
+ */
+ if (prologState.documentEntity &&
+ (dtd->standalone
+ ? !openInternalEntities
+ : !dtd->hasParamEntityRefs)) {
+ if (!entity)
+ return XML_ERROR_UNDEFINED_ENTITY;
+ else if (!entity->is_internal)
+ return XML_ERROR_ENTITY_DECLARED_IN_PE;
+ }
+ else if (!entity) {
+ dtd->keepProcessing = dtd->standalone;
+ /* cannot report skipped entities in declarations */
+ if ((role == XML_ROLE_PARAM_ENTITY_REF) && skippedEntityHandler) {
+ skippedEntityHandler(handlerArg, name, 1);
+ handleDefault = XML_FALSE;
+ }
+ break;
+ }
+ if (entity->open)
+ return XML_ERROR_RECURSIVE_ENTITY_REF;
+ if (entity->textPtr) {
+ enum XML_Error result;
+ XML_Bool betweenDecl =
+ (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
+ result = processInternalEntity(parser, entity, betweenDecl);
+ if (result != XML_ERROR_NONE)
+ return result;
+ handleDefault = XML_FALSE;
+ break;
+ }
+ if (externalEntityRefHandler) {
+ dtd->paramEntityRead = XML_FALSE;
+ entity->open = XML_TRUE;
+ if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ 0,
+ entity->base,
+ entity->systemId,
+ entity->publicId)) {
+ entity->open = XML_FALSE;
+ return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
+ }
+ entity->open = XML_FALSE;
+ handleDefault = XML_FALSE;
+ if (!dtd->paramEntityRead) {
+ dtd->keepProcessing = dtd->standalone;
+ break;
+ }
+ }
+ else {
+ dtd->keepProcessing = dtd->standalone;
+ break;
+ }
+ }
+#endif /* XML_DTD */
+ if (!dtd->standalone &&
+ notStandaloneHandler &&
+ !notStandaloneHandler(handlerArg))
+ return XML_ERROR_NOT_STANDALONE;
+ break;
+
+ /* Element declaration stuff */
+
+ case XML_ROLE_ELEMENT_NAME:
+ if (elementDeclHandler) {
+ declElementType = getElementType(parser, enc, s, next);
+ if (!declElementType)
+ return XML_ERROR_NO_MEMORY;
+ dtd->scaffLevel = 0;
+ dtd->scaffCount = 0;
+ dtd->in_eldecl = XML_TRUE;
+ handleDefault = XML_FALSE;
+ }
+ break;
+
+ case XML_ROLE_CONTENT_ANY:
+ case XML_ROLE_CONTENT_EMPTY:
+ if (dtd->in_eldecl) {
+ if (elementDeclHandler) {
+ XML_Content * content = (XML_Content *) MALLOC(sizeof(XML_Content));
+ if (!content)
+ return XML_ERROR_NO_MEMORY;
+ content->quant = XML_CQUANT_NONE;
+ content->name = NULL;
+ content->numchildren = 0;
+ content->children = NULL;
+ content->type = ((role == XML_ROLE_CONTENT_ANY) ?
+ XML_CTYPE_ANY :
+ XML_CTYPE_EMPTY);
+ *eventEndPP = s;
+ elementDeclHandler(handlerArg, declElementType->name, content);
+ handleDefault = XML_FALSE;
+ }
+ dtd->in_eldecl = XML_FALSE;
+ }
+ break;
+
+ case XML_ROLE_CONTENT_PCDATA:
+ if (dtd->in_eldecl) {
+ dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
+ = XML_CTYPE_MIXED;
+ if (elementDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ break;
+
+ case XML_ROLE_CONTENT_ELEMENT:
+ quant = XML_CQUANT_NONE;
+ goto elementContent;
+ case XML_ROLE_CONTENT_ELEMENT_OPT:
+ quant = XML_CQUANT_OPT;
+ goto elementContent;
+ case XML_ROLE_CONTENT_ELEMENT_REP:
+ quant = XML_CQUANT_REP;
+ goto elementContent;
+ case XML_ROLE_CONTENT_ELEMENT_PLUS:
+ quant = XML_CQUANT_PLUS;
+ elementContent:
+ if (dtd->in_eldecl) {
+ ELEMENT_TYPE *el;
+ const XML_Char *name;
+ int nameLen;
+ const char *nxt = (quant == XML_CQUANT_NONE
+ ? next
+ : next - enc->minBytesPerChar);
+ int myindex = nextScaffoldPart(parser);
+ if (myindex < 0)
+ return XML_ERROR_NO_MEMORY;
+ dtd->scaffold[myindex].type = XML_CTYPE_NAME;
+ dtd->scaffold[myindex].quant = quant;
+ el = getElementType(parser, enc, s, nxt);
+ if (!el)
+ return XML_ERROR_NO_MEMORY;
+ name = el->name;
+ dtd->scaffold[myindex].name = name;
+ nameLen = 0;
+ for (; name[nameLen++]; );
+ dtd->contentStringLen += nameLen;
+ if (elementDeclHandler)
+ handleDefault = XML_FALSE;
+ }
+ break;
+
+ case XML_ROLE_GROUP_CLOSE:
+ quant = XML_CQUANT_NONE;
+ goto closeGroup;
+ case XML_ROLE_GROUP_CLOSE_OPT:
+ quant = XML_CQUANT_OPT;
+ goto closeGroup;
+ case XML_ROLE_GROUP_CLOSE_REP:
+ quant = XML_CQUANT_REP;
+ goto closeGroup;
+ case XML_ROLE_GROUP_CLOSE_PLUS:
+ quant = XML_CQUANT_PLUS;
+ closeGroup:
+ if (dtd->in_eldecl) {
+ if (elementDeclHandler)
+ handleDefault = XML_FALSE;
+ dtd->scaffLevel--;
+ dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
+ if (dtd->scaffLevel == 0) {
+ if (!handleDefault) {
+ XML_Content *model = build_model(parser);
+ if (!model)
+ return XML_ERROR_NO_MEMORY;
+ *eventEndPP = s;
+ elementDeclHandler(handlerArg, declElementType->name, model);
+ }
+ dtd->in_eldecl = XML_FALSE;
+ dtd->contentStringLen = 0;
+ }
+ }
+ break;
+ /* End element declaration stuff */
+
+ case XML_ROLE_PI:
+ if (!reportProcessingInstruction(parser, enc, s, next))
+ return XML_ERROR_NO_MEMORY;
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_COMMENT:
+ if (!reportComment(parser, enc, s, next))
+ return XML_ERROR_NO_MEMORY;
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_NONE:
+ switch (tok) {
+ case XML_TOK_BOM:
+ handleDefault = XML_FALSE;
+ break;
+ }
+ break;
+ case XML_ROLE_DOCTYPE_NONE:
+ if (startDoctypeDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_ENTITY_NONE:
+ if (dtd->keepProcessing && entityDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_NOTATION_NONE:
+ if (notationDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_ATTLIST_NONE:
+ if (dtd->keepProcessing && attlistDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ case XML_ROLE_ELEMENT_NONE:
+ if (elementDeclHandler)
+ handleDefault = XML_FALSE;
+ break;
+ } /* end of big switch */
+
+ if (handleDefault && defaultHandler)
+ reportDefault(parser, enc, s, next);
+
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ case XML_FINISHED:
+ return XML_ERROR_ABORTED;
+ default:
+ s = next;
+ tok = XmlPrologTok(enc, s, end, &next);
+ }
+ }
+ /* not reached */
+}
+
+static enum XML_Error PTRCALL
+epilogProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ processor = epilogProcessor;
+ eventPtr = s;
+ for (;;) {
+ const char *next = NULL;
+ int tok = XmlPrologTok(encoding, s, end, &next);
+ eventEndPtr = next;
+ switch (tok) {
+ /* report partial linebreak - it might be the last token */
+ case -XML_TOK_PROLOG_S:
+ if (defaultHandler) {
+ reportDefault(parser, encoding, s, next);
+ if (ps_parsing == XML_FINISHED)
+ return XML_ERROR_ABORTED;
+ }
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ case XML_TOK_NONE:
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ case XML_TOK_PROLOG_S:
+ if (defaultHandler)
+ reportDefault(parser, encoding, s, next);
+ break;
+ case XML_TOK_PI:
+ if (!reportProcessingInstruction(parser, encoding, s, next))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ case XML_TOK_COMMENT:
+ if (!reportComment(parser, encoding, s, next))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ case XML_TOK_INVALID:
+ eventPtr = next;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ if (!ps_finalBuffer) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_UNCLOSED_TOKEN;
+ case XML_TOK_PARTIAL_CHAR:
+ if (!ps_finalBuffer) {
+ *nextPtr = s;
+ return XML_ERROR_NONE;
+ }
+ return XML_ERROR_PARTIAL_CHAR;
+ default:
+ return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
+ }
+ eventPtr = s = next;
+ switch (ps_parsing) {
+ case XML_SUSPENDED:
+ *nextPtr = next;
+ return XML_ERROR_NONE;
+ case XML_FINISHED:
+ return XML_ERROR_ABORTED;
+ default: ;
+ }
+ }
+}
+
+static enum XML_Error
+processInternalEntity(XML_Parser parser, ENTITY *entity,
+ XML_Bool betweenDecl)
+{
+ const char *textStart, *textEnd;
+ const char *next;
+ enum XML_Error result;
+ OPEN_INTERNAL_ENTITY *openEntity;
+
+ if (freeInternalEntities) {
+ openEntity = freeInternalEntities;
+ freeInternalEntities = openEntity->next;
+ }
+ else {
+ openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(sizeof(OPEN_INTERNAL_ENTITY));
+ if (!openEntity)
+ return XML_ERROR_NO_MEMORY;
+ }
+ entity->open = XML_TRUE;
+ entity->processed = 0;
+ openEntity->next = openInternalEntities;
+ openInternalEntities = openEntity;
+ openEntity->entity = entity;
+ openEntity->startTagLevel = tagLevel;
+ openEntity->betweenDecl = betweenDecl;
+ openEntity->internalEventPtr = NULL;
+ openEntity->internalEventEndPtr = NULL;
+ textStart = (char *)entity->textPtr;
+ textEnd = (char *)(entity->textPtr + entity->textLen);
+
+#ifdef XML_DTD
+ if (entity->is_param) {
+ int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next);
+ result = doProlog(parser, internalEncoding, textStart, textEnd, tok,
+ next, &next, XML_FALSE);
+ }
+ else
+#endif /* XML_DTD */
+ result = doContent(parser, tagLevel, internalEncoding, textStart,
+ textEnd, &next, XML_FALSE);
+
+ if (result == XML_ERROR_NONE) {
+ if (textEnd != next && ps_parsing == XML_SUSPENDED) {
+ entity->processed = (int)(next - textStart);
+ processor = internalEntityProcessor;
+ }
+ else {
+ entity->open = XML_FALSE;
+ openInternalEntities = openEntity->next;
+ /* put openEntity back in list of free instances */
+ openEntity->next = freeInternalEntities;
+ freeInternalEntities = openEntity;
+ }
+ }
+ return result;
+}
+
+static enum XML_Error PTRCALL
+internalEntityProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ ENTITY *entity;
+ const char *textStart, *textEnd;
+ const char *next;
+ enum XML_Error result;
+ OPEN_INTERNAL_ENTITY *openEntity = openInternalEntities;
+ if (!openEntity)
+ return XML_ERROR_UNEXPECTED_STATE;
+
+ entity = openEntity->entity;
+ textStart = ((char *)entity->textPtr) + entity->processed;
+ textEnd = (char *)(entity->textPtr + entity->textLen);
+
+#ifdef XML_DTD
+ if (entity->is_param) {
+ int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next);
+ result = doProlog(parser, internalEncoding, textStart, textEnd, tok,
+ next, &next, XML_FALSE);
+ }
+ else
+#endif /* XML_DTD */
+ result = doContent(parser, openEntity->startTagLevel, internalEncoding,
+ textStart, textEnd, &next, XML_FALSE);
+
+ if (result != XML_ERROR_NONE)
+ return result;
+ else if (textEnd != next && ps_parsing == XML_SUSPENDED) {
+ entity->processed = (int)(next - (char *)entity->textPtr);
+ return result;
+ }
+ else {
+ entity->open = XML_FALSE;
+ openInternalEntities = openEntity->next;
+ /* put openEntity back in list of free instances */
+ openEntity->next = freeInternalEntities;
+ freeInternalEntities = openEntity;
+ }
+
+#ifdef XML_DTD
+ if (entity->is_param) {
+ int tok;
+ processor = prologProcessor;
+ tok = XmlPrologTok(encoding, s, end, &next);
+ return doProlog(parser, encoding, s, end, tok, next, nextPtr,
+ (XML_Bool)!ps_finalBuffer);
+ }
+ else
+#endif /* XML_DTD */
+ {
+ processor = contentProcessor;
+ /* see externalEntityContentProcessor vs contentProcessor */
+ return doContent(parser, parentParser ? 1 : 0, encoding, s, end,
+ nextPtr, (XML_Bool)!ps_finalBuffer);
+ }
+}
+
+static enum XML_Error PTRCALL
+errorProcessor(XML_Parser parser,
+ const char *s,
+ const char *end,
+ const char **nextPtr)
+{
+ return errorCode;
+}
+
+static enum XML_Error
+storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
+ const char *ptr, const char *end,
+ STRING_POOL *pool)
+{
+ enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr,
+ end, pool);
+ if (result)
+ return result;
+ if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
+ poolChop(pool);
+ if (!poolAppendChar(pool, XML_T('\0')))
+ return XML_ERROR_NO_MEMORY;
+ return XML_ERROR_NONE;
+}
+
+static enum XML_Error
+appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
+ const char *ptr, const char *end,
+ STRING_POOL *pool)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ for (;;) {
+ const char *next;
+ int tok = XmlAttributeValueTok(enc, ptr, end, &next);
+ switch (tok) {
+ case XML_TOK_NONE:
+ return XML_ERROR_NONE;
+ case XML_TOK_INVALID:
+ if (enc == encoding)
+ eventPtr = next;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_PARTIAL:
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_INVALID_TOKEN;
+ case XML_TOK_CHAR_REF:
+ {
+ XML_Char buf[XML_ENCODE_MAX];
+ int i;
+ int n = XmlCharRefNumber(enc, ptr);
+ if (n < 0) {
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_BAD_CHAR_REF;
+ }
+ if (!isCdata
+ && n == 0x20 /* space */
+ && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
+ break;
+ n = XmlEncode(n, (ICHAR *)buf);
+ if (!n) {
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_BAD_CHAR_REF;
+ }
+ for (i = 0; i < n; i++) {
+ if (!poolAppendChar(pool, buf[i]))
+ return XML_ERROR_NO_MEMORY;
+ }
+ }
+ break;
+ case XML_TOK_DATA_CHARS:
+ if (!poolAppend(pool, enc, ptr, next))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ case XML_TOK_TRAILING_CR:
+ next = ptr + enc->minBytesPerChar;
+ /* fall through */
+ case XML_TOK_ATTRIBUTE_VALUE_S:
+ case XML_TOK_DATA_NEWLINE:
+ if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
+ break;
+ if (!poolAppendChar(pool, 0x20))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ case XML_TOK_ENTITY_REF:
+ {
+ const XML_Char *name;
+ ENTITY *entity;
+ char checkEntityDecl;
+ XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
+ ptr + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (ch) {
+ if (!poolAppendChar(pool, ch))
+ return XML_ERROR_NO_MEMORY;
+ break;
+ }
+ name = poolStoreString(&temp2Pool, enc,
+ ptr + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!name)
+ return XML_ERROR_NO_MEMORY;
+ entity = (ENTITY *)lookup(&dtd->generalEntities, name, 0);
+ poolDiscard(&temp2Pool);
+ /* First, determine if a check for an existing declaration is needed;
+ if yes, check that the entity exists, and that it is internal.
+ */
+ if (pool == &dtd->pool) /* are we called from prolog? */
+ checkEntityDecl =
+#ifdef XML_DTD
+ prologState.documentEntity &&
+#endif /* XML_DTD */
+ (dtd->standalone
+ ? !openInternalEntities
+ : !dtd->hasParamEntityRefs);
+ else /* if (pool == &tempPool): we are called from content */
+ checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone;
+ if (checkEntityDecl) {
+ if (!entity)
+ return XML_ERROR_UNDEFINED_ENTITY;
+ else if (!entity->is_internal)
+ return XML_ERROR_ENTITY_DECLARED_IN_PE;
+ }
+ else if (!entity) {
+ /* Cannot report skipped entity here - see comments on
+ skippedEntityHandler.
+ if (skippedEntityHandler)
+ skippedEntityHandler(handlerArg, name, 0);
+ */
+ /* Cannot call the default handler because this would be
+ out of sync with the call to the startElementHandler.
+ if ((pool == &tempPool) && defaultHandler)
+ reportDefault(parser, enc, ptr, next);
+ */
+ break;
+ }
+ if (entity->open) {
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_RECURSIVE_ENTITY_REF;
+ }
+ if (entity->notation) {
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_BINARY_ENTITY_REF;
+ }
+ if (!entity->textPtr) {
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
+ }
+ else {
+ enum XML_Error result;
+ const XML_Char *textEnd = entity->textPtr + entity->textLen;
+ entity->open = XML_TRUE;
+ result = appendAttributeValue(parser, internalEncoding, isCdata,
+ (char *)entity->textPtr,
+ (char *)textEnd, pool);
+ entity->open = XML_FALSE;
+ if (result)
+ return result;
+ }
+ }
+ break;
+ default:
+ if (enc == encoding)
+ eventPtr = ptr;
+ return XML_ERROR_UNEXPECTED_STATE;
+ }
+ ptr = next;
+ }
+ /* not reached */
+}
+
+static enum XML_Error
+storeEntityValue(XML_Parser parser,
+ const ENCODING *enc,
+ const char *entityTextPtr,
+ const char *entityTextEnd)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ STRING_POOL *pool = &(dtd->entityValuePool);
+ enum XML_Error result = XML_ERROR_NONE;
+#ifdef XML_DTD
+ int oldInEntityValue = prologState.inEntityValue;
+ prologState.inEntityValue = 1;
+#endif /* XML_DTD */
+ /* never return Null for the value argument in EntityDeclHandler,
+ since this would indicate an external entity; therefore we
+ have to make sure that entityValuePool.start is not null */
+ if (!pool->blocks) {
+ if (!poolGrow(pool))
+ return XML_ERROR_NO_MEMORY;
+ }
+
+ for (;;) {
+ const char *next;
+ int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
+ switch (tok) {
+ case XML_TOK_PARAM_ENTITY_REF:
+#ifdef XML_DTD
+ if (isParamEntity || enc != encoding) {
+ const XML_Char *name;
+ ENTITY *entity;
+ name = poolStoreString(&tempPool, enc,
+ entityTextPtr + enc->minBytesPerChar,
+ next - enc->minBytesPerChar);
+ if (!name) {
+ result = XML_ERROR_NO_MEMORY;
+ goto endEntityValue;
+ }
+ entity = (ENTITY *)lookup(&dtd->paramEntities, name, 0);
+ poolDiscard(&tempPool);
+ if (!entity) {
+ /* not a well-formedness error - see XML 1.0: WFC Entity Declared */
+ /* cannot report skipped entity here - see comments on
+ skippedEntityHandler
+ if (skippedEntityHandler)
+ skippedEntityHandler(handlerArg, name, 0);
+ */
+ dtd->keepProcessing = dtd->standalone;
+ goto endEntityValue;
+ }
+ if (entity->open) {
+ if (enc == encoding)
+ eventPtr = entityTextPtr;
+ result = XML_ERROR_RECURSIVE_ENTITY_REF;
+ goto endEntityValue;
+ }
+ if (entity->systemId) {
+ if (externalEntityRefHandler) {
+ dtd->paramEntityRead = XML_FALSE;
+ entity->open = XML_TRUE;
+ if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ 0,
+ entity->base,
+ entity->systemId,
+ entity->publicId)) {
+ entity->open = XML_FALSE;
+ result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
+ goto endEntityValue;
+ }
+ entity->open = XML_FALSE;
+ if (!dtd->paramEntityRead)
+ dtd->keepProcessing = dtd->standalone;
+ }
+ else
+ dtd->keepProcessing = dtd->standalone;
+ }
+ else {
+ entity->open = XML_TRUE;
+ result = storeEntityValue(parser,
+ internalEncoding,
+ (char *)entity->textPtr,
+ (char *)(entity->textPtr
+ + entity->textLen));
+ entity->open = XML_FALSE;
+ if (result)
+ goto endEntityValue;
+ }
+ break;
+ }
+#endif /* XML_DTD */
+ /* In the internal subset, PE references are not legal
+ within markup declarations, e.g entity values in this case. */
+ eventPtr = entityTextPtr;
+ result = XML_ERROR_PARAM_ENTITY_REF;
+ goto endEntityValue;
+ case XML_TOK_NONE:
+ result = XML_ERROR_NONE;
+ goto endEntityValue;
+ case XML_TOK_ENTITY_REF:
+ case XML_TOK_DATA_CHARS:
+ if (!poolAppend(pool, enc, entityTextPtr, next)) {
+ result = XML_ERROR_NO_MEMORY;
+ goto endEntityValue;
+ }
+ break;
+ case XML_TOK_TRAILING_CR:
+ next = entityTextPtr + enc->minBytesPerChar;
+ /* fall through */
+ case XML_TOK_DATA_NEWLINE:
+ if (pool->end == pool->ptr && !poolGrow(pool)) {
+ result = XML_ERROR_NO_MEMORY;
+ goto endEntityValue;
+ }
+ *(pool->ptr)++ = 0xA;
+ break;
+ case XML_TOK_CHAR_REF:
+ {
+ XML_Char buf[XML_ENCODE_MAX];
+ int i;
+ int n = XmlCharRefNumber(enc, entityTextPtr);
+ if (n < 0) {
+ if (enc == encoding)
+ eventPtr = entityTextPtr;
+ result = XML_ERROR_BAD_CHAR_REF;
+ goto endEntityValue;
+ }
+ n = XmlEncode(n, (ICHAR *)buf);
+ if (!n) {
+ if (enc == encoding)
+ eventPtr = entityTextPtr;
+ result = XML_ERROR_BAD_CHAR_REF;
+ goto endEntityValue;
+ }
+ for (i = 0; i < n; i++) {
+ if (pool->end == pool->ptr && !poolGrow(pool)) {
+ result = XML_ERROR_NO_MEMORY;
+ goto endEntityValue;
+ }
+ *(pool->ptr)++ = buf[i];
+ }
+ }
+ break;
+ case XML_TOK_PARTIAL:
+ if (enc == encoding)
+ eventPtr = entityTextPtr;
+ result = XML_ERROR_INVALID_TOKEN;
+ goto endEntityValue;
+ case XML_TOK_INVALID:
+ if (enc == encoding)
+ eventPtr = next;
+ result = XML_ERROR_INVALID_TOKEN;
+ goto endEntityValue;
+ default:
+ if (enc == encoding)
+ eventPtr = entityTextPtr;
+ result = XML_ERROR_UNEXPECTED_STATE;
+ goto endEntityValue;
+ }
+ entityTextPtr = next;
+ }
+endEntityValue:
+#ifdef XML_DTD
+ prologState.inEntityValue = oldInEntityValue;
+#endif /* XML_DTD */
+ return result;
+}
+
+static void FASTCALL
+normalizeLines(XML_Char *s)
+{
+ XML_Char *p;
+ for (;; s++) {
+ if (*s == XML_T('\0'))
+ return;
+ if (*s == 0xD)
+ break;
+ }
+ p = s;
+ do {
+ if (*s == 0xD) {
+ *p++ = 0xA;
+ if (*++s == 0xA)
+ s++;
+ }
+ else
+ *p++ = *s++;
+ } while (*s);
+ *p = XML_T('\0');
+}
+
+static int
+reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
+ const char *start, const char *end)
+{
+ const XML_Char *target;
+ XML_Char *data;
+ const char *tem;
+ if (!processingInstructionHandler) {
+ if (defaultHandler)
+ reportDefault(parser, enc, start, end);
+ return 1;
+ }
+ start += enc->minBytesPerChar * 2;
+ tem = start + XmlNameLength(enc, start);
+ target = poolStoreString(&tempPool, enc, start, tem);
+ if (!target)
+ return 0;
+ poolFinish(&tempPool);
+ data = poolStoreString(&tempPool, enc,
+ XmlSkipS(enc, tem),
+ end - enc->minBytesPerChar*2);
+ if (!data)
+ return 0;
+ normalizeLines(data);
+ processingInstructionHandler(handlerArg, target, data);
+ poolClear(&tempPool);
+ return 1;
+}
+
+static int
+reportComment(XML_Parser parser, const ENCODING *enc,
+ const char *start, const char *end)
+{
+ XML_Char *data;
+ if (!commentHandler) {
+ if (defaultHandler)
+ reportDefault(parser, enc, start, end);
+ return 1;
+ }
+ data = poolStoreString(&tempPool,
+ enc,
+ start + enc->minBytesPerChar * 4,
+ end - enc->minBytesPerChar * 3);
+ if (!data)
+ return 0;
+ normalizeLines(data);
+ commentHandler(handlerArg, data);
+ poolClear(&tempPool);
+ return 1;
+}
+
+static void
+reportDefault(XML_Parser parser, const ENCODING *enc,
+ const char *s, const char *end)
+{
+ if (MUST_CONVERT(enc, s)) {
+ const char **eventPP;
+ const char **eventEndPP;
+ if (enc == encoding) {
+ eventPP = &eventPtr;
+ eventEndPP = &eventEndPtr;
+ }
+ else {
+ eventPP = &(openInternalEntities->internalEventPtr);
+ eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ }
+ do {
+ ICHAR *dataPtr = (ICHAR *)dataBuf;
+ XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
+ *eventEndPP = s;
+ defaultHandler(handlerArg, dataBuf, (int)(dataPtr - (ICHAR *)dataBuf));
+ *eventPP = s;
+ } while (s != end);
+ }
+ else
+ defaultHandler(handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
+}
+
+
+static int
+defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
+ XML_Bool isId, const XML_Char *value, XML_Parser parser)
+{
+ DEFAULT_ATTRIBUTE *att;
+ if (value || isId) {
+ /* The handling of default attributes gets messed up if we have
+ a default which duplicates a non-default. */
+ int i;
+ for (i = 0; i < type->nDefaultAtts; i++)
+ if (attId == type->defaultAtts[i].id)
+ return 1;
+ if (isId && !type->idAtt && !attId->xmlns)
+ type->idAtt = attId;
+ }
+ if (type->nDefaultAtts == type->allocDefaultAtts) {
+ if (type->allocDefaultAtts == 0) {
+ type->allocDefaultAtts = 8;
+ type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(type->allocDefaultAtts
+ * sizeof(DEFAULT_ATTRIBUTE));
+ if (!type->defaultAtts)
+ return 0;
+ }
+ else {
+ DEFAULT_ATTRIBUTE *temp;
+ int count = type->allocDefaultAtts * 2;
+ temp = (DEFAULT_ATTRIBUTE *)
+ REALLOC(type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
+ if (temp == NULL)
+ return 0;
+ type->allocDefaultAtts = count;
+ type->defaultAtts = temp;
+ }
+ }
+ att = type->defaultAtts + type->nDefaultAtts;
+ att->id = attId;
+ att->value = value;
+ att->isCdata = isCdata;
+ if (!isCdata)
+ attId->maybeTokenized = XML_TRUE;
+ type->nDefaultAtts += 1;
+ return 1;
+}
+
+static int
+setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ const XML_Char *name;
+ for (name = elementType->name; *name; name++) {
+ if (*name == XML_T(':')) {
+ PREFIX *prefix;
+ const XML_Char *s;
+ for (s = elementType->name; s != name; s++) {
+ if (!poolAppendChar(&dtd->pool, *s))
+ return 0;
+ }
+ if (!poolAppendChar(&dtd->pool, XML_T('\0')))
+ return 0;
+ prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&dtd->pool),
+ sizeof(PREFIX));
+ if (!prefix)
+ return 0;
+ if (prefix->name == poolStart(&dtd->pool))
+ poolFinish(&dtd->pool);
+ else
+ poolDiscard(&dtd->pool);
+ elementType->prefix = prefix;
+
+ }
+ }
+ return 1;
+}
+
+static ATTRIBUTE_ID *
+getAttributeId(XML_Parser parser, const ENCODING *enc,
+ const char *start, const char *end)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ ATTRIBUTE_ID *id;
+ const XML_Char *name;
+ if (!poolAppendChar(&dtd->pool, XML_T('\0')))
+ return NULL;
+ name = poolStoreString(&dtd->pool, enc, start, end);
+ if (!name)
+ return NULL;
+ /* skip quotation mark - its storage will be re-used (like in name[-1]) */
+ ++name;
+ id = (ATTRIBUTE_ID *)lookup(&dtd->attributeIds, name, sizeof(ATTRIBUTE_ID));
+ if (!id)
+ return NULL;
+ if (id->name != name)
+ poolDiscard(&dtd->pool);
+ else {
+ poolFinish(&dtd->pool);
+ if (!ns)
+ ;
+ else if (name[0] == XML_T('x')
+ && name[1] == XML_T('m')
+ && name[2] == XML_T('l')
+ && name[3] == XML_T('n')
+ && name[4] == XML_T('s')
+ && (name[5] == XML_T('\0') || name[5] == XML_T(':'))) {
+ if (name[5] == XML_T('\0'))
+ id->prefix = &dtd->defaultPrefix;
+ else
+ id->prefix = (PREFIX *)lookup(&dtd->prefixes, name + 6, sizeof(PREFIX));
+ id->xmlns = XML_TRUE;
+ }
+ else {
+ int i;
+ for (i = 0; name[i]; i++) {
+ /* attributes without prefix are *not* in the default namespace */
+ if (name[i] == XML_T(':')) {
+ int j;
+ for (j = 0; j < i; j++) {
+ if (!poolAppendChar(&dtd->pool, name[j]))
+ return NULL;
+ }
+ if (!poolAppendChar(&dtd->pool, XML_T('\0')))
+ return NULL;
+ id->prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&dtd->pool),
+ sizeof(PREFIX));
+ if (!id->prefix)
+ return NULL;
+ if (id->prefix->name == poolStart(&dtd->pool))
+ poolFinish(&dtd->pool);
+ else
+ poolDiscard(&dtd->pool);
+ break;
+ }
+ }
+ }
+ }
+ return id;
+}
+
+#define CONTEXT_SEP XML_T('\f')
+
+static const XML_Char *
+getContext(XML_Parser parser)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ HASH_TABLE_ITER iter;
+ XML_Bool needSep = XML_FALSE;
+
+ if (dtd->defaultPrefix.binding) {
+ int i;
+ int len;
+ if (!poolAppendChar(&tempPool, XML_T('=')))
+ return NULL;
+ len = dtd->defaultPrefix.binding->uriLen;
+ if (namespaceSeparator)
+ len--;
+ for (i = 0; i < len; i++)
+ if (!poolAppendChar(&tempPool, dtd->defaultPrefix.binding->uri[i]))
+ return NULL;
+ needSep = XML_TRUE;
+ }
+
+ hashTableIterInit(&iter, &(dtd->prefixes));
+ for (;;) {
+ int i;
+ int len;
+ const XML_Char *s;
+ PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
+ if (!prefix)
+ break;
+ if (!prefix->binding)
+ continue;
+ if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP))
+ return NULL;
+ for (s = prefix->name; *s; s++)
+ if (!poolAppendChar(&tempPool, *s))
+ return NULL;
+ if (!poolAppendChar(&tempPool, XML_T('=')))
+ return NULL;
+ len = prefix->binding->uriLen;
+ if (namespaceSeparator)
+ len--;
+ for (i = 0; i < len; i++)
+ if (!poolAppendChar(&tempPool, prefix->binding->uri[i]))
+ return NULL;
+ needSep = XML_TRUE;
+ }
+
+
+ hashTableIterInit(&iter, &(dtd->generalEntities));
+ for (;;) {
+ const XML_Char *s;
+ ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
+ if (!e)
+ break;
+ if (!e->open)
+ continue;
+ if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP))
+ return NULL;
+ for (s = e->name; *s; s++)
+ if (!poolAppendChar(&tempPool, *s))
+ return 0;
+ needSep = XML_TRUE;
+ }
+
+ if (!poolAppendChar(&tempPool, XML_T('\0')))
+ return NULL;
+ return tempPool.start;
+}
+
+static XML_Bool
+setContext(XML_Parser parser, const XML_Char *context)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ const XML_Char *s = context;
+
+ while (*context != XML_T('\0')) {
+ if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
+ ENTITY *e;
+ if (!poolAppendChar(&tempPool, XML_T('\0')))
+ return XML_FALSE;
+ e = (ENTITY *)lookup(&dtd->generalEntities, poolStart(&tempPool), 0);
+ if (e)
+ e->open = XML_TRUE;
+ if (*s != XML_T('\0'))
+ s++;
+ context = s;
+ poolDiscard(&tempPool);
+ }
+ else if (*s == XML_T('=')) {
+ PREFIX *prefix;
+ if (poolLength(&tempPool) == 0)
+ prefix = &dtd->defaultPrefix;
+ else {
+ if (!poolAppendChar(&tempPool, XML_T('\0')))
+ return XML_FALSE;
+ prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&tempPool),
+ sizeof(PREFIX));
+ if (!prefix)
+ return XML_FALSE;
+ if (prefix->name == poolStart(&tempPool)) {
+ prefix->name = poolCopyString(&dtd->pool, prefix->name);
+ if (!prefix->name)
+ return XML_FALSE;
+ }
+ poolDiscard(&tempPool);
+ }
+ for (context = s + 1;
+ *context != CONTEXT_SEP && *context != XML_T('\0');
+ context++)
+ if (!poolAppendChar(&tempPool, *context))
+ return XML_FALSE;
+ if (!poolAppendChar(&tempPool, XML_T('\0')))
+ return XML_FALSE;
+ if (addBinding(parser, prefix, NULL, poolStart(&tempPool),
+ &inheritedBindings) != XML_ERROR_NONE)
+ return XML_FALSE;
+ poolDiscard(&tempPool);
+ if (*context != XML_T('\0'))
+ ++context;
+ s = context;
+ }
+ else {
+ if (!poolAppendChar(&tempPool, *s))
+ return XML_FALSE;
+ s++;
+ }
+ }
+ return XML_TRUE;
+}
+
+static void FASTCALL
+normalizePublicId(XML_Char *publicId)
+{
+ XML_Char *p = publicId;
+ XML_Char *s;
+ for (s = publicId; *s; s++) {
+ switch (*s) {
+ case 0x20:
+ case 0xD:
+ case 0xA:
+ if (p != publicId && p[-1] != 0x20)
+ *p++ = 0x20;
+ break;
+ default:
+ *p++ = *s;
+ }
+ }
+ if (p != publicId && p[-1] == 0x20)
+ --p;
+ *p = XML_T('\0');
+}
+
+static DTD *
+dtdCreate(const XML_Memory_Handling_Suite *ms)
+{
+ DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD));
+ if (p == NULL)
+ return p;
+ poolInit(&(p->pool), ms);
+ poolInit(&(p->entityValuePool), ms);
+ hashTableInit(&(p->generalEntities), ms);
+ hashTableInit(&(p->elementTypes), ms);
+ hashTableInit(&(p->attributeIds), ms);
+ hashTableInit(&(p->prefixes), ms);
+#ifdef XML_DTD
+ p->paramEntityRead = XML_FALSE;
+ hashTableInit(&(p->paramEntities), ms);
+#endif /* XML_DTD */
+ p->defaultPrefix.name = NULL;
+ p->defaultPrefix.binding = NULL;
+
+ p->in_eldecl = XML_FALSE;
+ p->scaffIndex = NULL;
+ p->scaffold = NULL;
+ p->scaffLevel = 0;
+ p->scaffSize = 0;
+ p->scaffCount = 0;
+ p->contentStringLen = 0;
+
+ p->keepProcessing = XML_TRUE;
+ p->hasParamEntityRefs = XML_FALSE;
+ p->standalone = XML_FALSE;
+ return p;
+}
+
+static void
+dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms)
+{
+ HASH_TABLE_ITER iter;
+ hashTableIterInit(&iter, &(p->elementTypes));
+ for (;;) {
+ ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
+ if (!e)
+ break;
+ if (e->allocDefaultAtts != 0)
+ ms->free_fcn(e->defaultAtts);
+ }
+ hashTableClear(&(p->generalEntities));
+#ifdef XML_DTD
+ p->paramEntityRead = XML_FALSE;
+ hashTableClear(&(p->paramEntities));
+#endif /* XML_DTD */
+ hashTableClear(&(p->elementTypes));
+ hashTableClear(&(p->attributeIds));
+ hashTableClear(&(p->prefixes));
+ poolClear(&(p->pool));
+ poolClear(&(p->entityValuePool));
+ p->defaultPrefix.name = NULL;
+ p->defaultPrefix.binding = NULL;
+
+ p->in_eldecl = XML_FALSE;
+
+ ms->free_fcn(p->scaffIndex);
+ p->scaffIndex = NULL;
+ ms->free_fcn(p->scaffold);
+ p->scaffold = NULL;
+
+ p->scaffLevel = 0;
+ p->scaffSize = 0;
+ p->scaffCount = 0;
+ p->contentStringLen = 0;
+
+ p->keepProcessing = XML_TRUE;
+ p->hasParamEntityRefs = XML_FALSE;
+ p->standalone = XML_FALSE;
+}
+
+static void
+dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms)
+{
+ HASH_TABLE_ITER iter;
+ hashTableIterInit(&iter, &(p->elementTypes));
+ for (;;) {
+ ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
+ if (!e)
+ break;
+ if (e->allocDefaultAtts != 0)
+ ms->free_fcn(e->defaultAtts);
+ }
+ hashTableDestroy(&(p->generalEntities));
+#ifdef XML_DTD
+ hashTableDestroy(&(p->paramEntities));
+#endif /* XML_DTD */
+ hashTableDestroy(&(p->elementTypes));
+ hashTableDestroy(&(p->attributeIds));
+ hashTableDestroy(&(p->prefixes));
+ poolDestroy(&(p->pool));
+ poolDestroy(&(p->entityValuePool));
+ if (isDocEntity) {
+ ms->free_fcn(p->scaffIndex);
+ ms->free_fcn(p->scaffold);
+ }
+ ms->free_fcn(p);
+}
+
+/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
+ The new DTD has already been initialized.
+*/
+static int
+dtdCopy(DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms)
+{
+ HASH_TABLE_ITER iter;
+
+ /* Copy the prefix table. */
+
+ hashTableIterInit(&iter, &(oldDtd->prefixes));
+ for (;;) {
+ const XML_Char *name;
+ const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
+ if (!oldP)
+ break;
+ name = poolCopyString(&(newDtd->pool), oldP->name);
+ if (!name)
+ return 0;
+ if (!lookup(&(newDtd->prefixes), name, sizeof(PREFIX)))
+ return 0;
+ }
+
+ hashTableIterInit(&iter, &(oldDtd->attributeIds));
+
+ /* Copy the attribute id table. */
+
+ for (;;) {
+ ATTRIBUTE_ID *newA;
+ const XML_Char *name;
+ const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
+
+ if (!oldA)
+ break;
+ /* Remember to allocate the scratch byte before the name. */
+ if (!poolAppendChar(&(newDtd->pool), XML_T('\0')))
+ return 0;
+ name = poolCopyString(&(newDtd->pool), oldA->name);
+ if (!name)
+ return 0;
+ ++name;
+ newA = (ATTRIBUTE_ID *)lookup(&(newDtd->attributeIds), name,
+ sizeof(ATTRIBUTE_ID));
+ if (!newA)
+ return 0;
+ newA->maybeTokenized = oldA->maybeTokenized;
+ if (oldA->prefix) {
+ newA->xmlns = oldA->xmlns;
+ if (oldA->prefix == &oldDtd->defaultPrefix)
+ newA->prefix = &newDtd->defaultPrefix;
+ else
+ newA->prefix = (PREFIX *)lookup(&(newDtd->prefixes),
+ oldA->prefix->name, 0);
+ }
+ }
+
+ /* Copy the element type table. */
+
+ hashTableIterInit(&iter, &(oldDtd->elementTypes));
+
+ for (;;) {
+ int i;
+ ELEMENT_TYPE *newE;
+ const XML_Char *name;
+ const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
+ if (!oldE)
+ break;
+ name = poolCopyString(&(newDtd->pool), oldE->name);
+ if (!name)
+ return 0;
+ newE = (ELEMENT_TYPE *)lookup(&(newDtd->elementTypes), name,
+ sizeof(ELEMENT_TYPE));
+ if (!newE)
+ return 0;
+ if (oldE->nDefaultAtts) {
+ newE->defaultAtts = (DEFAULT_ATTRIBUTE *)
+ ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
+ if (!newE->defaultAtts) {
+ ms->free_fcn(newE);
+ return 0;
+ }
+ }
+ if (oldE->idAtt)
+ newE->idAtt = (ATTRIBUTE_ID *)
+ lookup(&(newDtd->attributeIds), oldE->idAtt->name, 0);
+ newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
+ if (oldE->prefix)
+ newE->prefix = (PREFIX *)lookup(&(newDtd->prefixes),
+ oldE->prefix->name, 0);
+ for (i = 0; i < newE->nDefaultAtts; i++) {
+ newE->defaultAtts[i].id = (ATTRIBUTE_ID *)
+ lookup(&(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
+ newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
+ if (oldE->defaultAtts[i].value) {
+ newE->defaultAtts[i].value
+ = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
+ if (!newE->defaultAtts[i].value)
+ return 0;
+ }
+ else
+ newE->defaultAtts[i].value = NULL;
+ }
+ }
+
+ /* Copy the entity tables. */
+ if (!copyEntityTable(&(newDtd->generalEntities),
+ &(newDtd->pool),
+ &(oldDtd->generalEntities)))
+ return 0;
+
+#ifdef XML_DTD
+ if (!copyEntityTable(&(newDtd->paramEntities),
+ &(newDtd->pool),
+ &(oldDtd->paramEntities)))
+ return 0;
+ newDtd->paramEntityRead = oldDtd->paramEntityRead;
+#endif /* XML_DTD */
+
+ newDtd->keepProcessing = oldDtd->keepProcessing;
+ newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
+ newDtd->standalone = oldDtd->standalone;
+
+ /* Don't want deep copying for scaffolding */
+ newDtd->in_eldecl = oldDtd->in_eldecl;
+ newDtd->scaffold = oldDtd->scaffold;
+ newDtd->contentStringLen = oldDtd->contentStringLen;
+ newDtd->scaffSize = oldDtd->scaffSize;
+ newDtd->scaffLevel = oldDtd->scaffLevel;
+ newDtd->scaffIndex = oldDtd->scaffIndex;
+
+ return 1;
+} /* End dtdCopy */
+
+static int
+copyEntityTable(HASH_TABLE *newTable,
+ STRING_POOL *newPool,
+ const HASH_TABLE *oldTable)
+{
+ HASH_TABLE_ITER iter;
+ const XML_Char *cachedOldBase = NULL;
+ const XML_Char *cachedNewBase = NULL;
+
+ hashTableIterInit(&iter, oldTable);
+
+ for (;;) {
+ ENTITY *newE;
+ const XML_Char *name;
+ const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
+ if (!oldE)
+ break;
+ name = poolCopyString(newPool, oldE->name);
+ if (!name)
+ return 0;
+ newE = (ENTITY *)lookup(newTable, name, sizeof(ENTITY));
+ if (!newE)
+ return 0;
+ if (oldE->systemId) {
+ const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
+ if (!tem)
+ return 0;
+ newE->systemId = tem;
+ if (oldE->base) {
+ if (oldE->base == cachedOldBase)
+ newE->base = cachedNewBase;
+ else {
+ cachedOldBase = oldE->base;
+ tem = poolCopyString(newPool, cachedOldBase);
+ if (!tem)
+ return 0;
+ cachedNewBase = newE->base = tem;
+ }
+ }
+ if (oldE->publicId) {
+ tem = poolCopyString(newPool, oldE->publicId);
+ if (!tem)
+ return 0;
+ newE->publicId = tem;
+ }
+ }
+ else {
+ const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr,
+ oldE->textLen);
+ if (!tem)
+ return 0;
+ newE->textPtr = tem;
+ newE->textLen = oldE->textLen;
+ }
+ if (oldE->notation) {
+ const XML_Char *tem = poolCopyString(newPool, oldE->notation);
+ if (!tem)
+ return 0;
+ newE->notation = tem;
+ }
+ newE->is_param = oldE->is_param;
+ newE->is_internal = oldE->is_internal;
+ }
+ return 1;
+}
+
+#define INIT_POWER 6
+
+static XML_Bool FASTCALL
+keyeq(KEY s1, KEY s2)
+{
+ for (; *s1 == *s2; s1++, s2++)
+ if (*s1 == 0)
+ return XML_TRUE;
+ return XML_FALSE;
+}
+
+static unsigned long FASTCALL
+hash(KEY s)
+{
+ unsigned long h = 0;
+ while (*s)
+ h = CHAR_HASH(h, *s++);
+ return h;
+}
+
+static NAMED *
+lookup(HASH_TABLE *table, KEY name, size_t createSize)
+{
+ size_t i;
+ if (table->size == 0) {
+ size_t tsize;
+ if (!createSize)
+ return NULL;
+ table->power = INIT_POWER;
+ /* table->size is a power of 2 */
+ table->size = (size_t)1 << INIT_POWER;
+ tsize = table->size * sizeof(NAMED *);
+ table->v = (NAMED **)table->mem->malloc_fcn(tsize);
+ if (!table->v) {
+ table->size = 0;
+ return NULL;
+ }
+ memset(table->v, 0, tsize);
+ i = hash(name) & ((unsigned long)table->size - 1);
+ }
+ else {
+ unsigned long h = hash(name);
+ unsigned long mask = (unsigned long)table->size - 1;
+ unsigned char step = 0;
+ i = h & mask;
+ while (table->v[i]) {
+ if (keyeq(name, table->v[i]->name))
+ return table->v[i];
+ if (!step)
+ step = PROBE_STEP(h, mask, table->power);
+ i < step ? (i += table->size - step) : (i -= step);
+ }
+ if (!createSize)
+ return NULL;
+
+ /* check for overflow (table is half full) */
+ if (table->used >> (table->power - 1)) {
+ unsigned char newPower = table->power + 1;
+ size_t newSize = (size_t)1 << newPower;
+ unsigned long newMask = (unsigned long)newSize - 1;
+ size_t tsize = newSize * sizeof(NAMED *);
+ NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize);
+ if (!newV)
+ return NULL;
+ memset(newV, 0, tsize);
+ for (i = 0; i < table->size; i++)
+ if (table->v[i]) {
+ unsigned long newHash = hash(table->v[i]->name);
+ size_t j = newHash & newMask;
+ step = 0;
+ while (newV[j]) {
+ if (!step)
+ step = PROBE_STEP(newHash, newMask, newPower);
+ j < step ? (j += newSize - step) : (j -= step);
+ }
+ newV[j] = table->v[i];
+ }
+ table->mem->free_fcn(table->v);
+ table->v = newV;
+ table->power = newPower;
+ table->size = newSize;
+ i = h & newMask;
+ step = 0;
+ while (table->v[i]) {
+ if (!step)
+ step = PROBE_STEP(h, newMask, newPower);
+ i < step ? (i += newSize - step) : (i -= step);
+ }
+ }
+ }
+ table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize);
+ if (!table->v[i])
+ return NULL;
+ memset(table->v[i], 0, createSize);
+ table->v[i]->name = name;
+ (table->used)++;
+ return table->v[i];
+}
+
+static void FASTCALL
+hashTableClear(HASH_TABLE *table)
+{
+ size_t i;
+ for (i = 0; i < table->size; i++) {
+ table->mem->free_fcn(table->v[i]);
+ table->v[i] = NULL;
+ }
+ table->used = 0;
+}
+
+static void FASTCALL
+hashTableDestroy(HASH_TABLE *table)
+{
+ size_t i;
+ for (i = 0; i < table->size; i++)
+ table->mem->free_fcn(table->v[i]);
+ table->mem->free_fcn(table->v);
+}
+
+static void FASTCALL
+hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms)
+{
+ p->power = 0;
+ p->size = 0;
+ p->used = 0;
+ p->v = NULL;
+ p->mem = ms;
+}
+
+static void FASTCALL
+hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table)
+{
+ iter->p = table->v;
+ iter->end = iter->p + table->size;
+}
+
+static NAMED * FASTCALL
+hashTableIterNext(HASH_TABLE_ITER *iter)
+{
+ while (iter->p != iter->end) {
+ NAMED *tem = *(iter->p)++;
+ if (tem)
+ return tem;
+ }
+ return NULL;
+}
+
+static void FASTCALL
+poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms)
+{
+ pool->blocks = NULL;
+ pool->freeBlocks = NULL;
+ pool->start = NULL;
+ pool->ptr = NULL;
+ pool->end = NULL;
+ pool->mem = ms;
+}
+
+static void FASTCALL
+poolClear(STRING_POOL *pool)
+{
+ if (!pool->freeBlocks)
+ pool->freeBlocks = pool->blocks;
+ else {
+ BLOCK *p = pool->blocks;
+ while (p) {
+ BLOCK *tem = p->next;
+ p->next = pool->freeBlocks;
+ pool->freeBlocks = p;
+ p = tem;
+ }
+ }
+ pool->blocks = NULL;
+ pool->start = NULL;
+ pool->ptr = NULL;
+ pool->end = NULL;
+}
+
+static void FASTCALL
+poolDestroy(STRING_POOL *pool)
+{
+ BLOCK *p = pool->blocks;
+ while (p) {
+ BLOCK *tem = p->next;
+ pool->mem->free_fcn(p);
+ p = tem;
+ }
+ p = pool->freeBlocks;
+ while (p) {
+ BLOCK *tem = p->next;
+ pool->mem->free_fcn(p);
+ p = tem;
+ }
+}
+
+static XML_Char *
+poolAppend(STRING_POOL *pool, const ENCODING *enc,
+ const char *ptr, const char *end)
+{
+ if (!pool->ptr && !poolGrow(pool))
+ return NULL;
+ for (;;) {
+ XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
+ if (ptr == end)
+ break;
+ if (!poolGrow(pool))
+ return NULL;
+ }
+ return pool->start;
+}
+
+static const XML_Char * FASTCALL
+poolCopyString(STRING_POOL *pool, const XML_Char *s)
+{
+ do {
+ if (!poolAppendChar(pool, *s))
+ return NULL;
+ } while (*s++);
+ s = pool->start;
+ poolFinish(pool);
+ return s;
+}
+
+static const XML_Char *
+poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n)
+{
+ if (!pool->ptr && !poolGrow(pool))
+ return NULL;
+ for (; n > 0; --n, s++) {
+ if (!poolAppendChar(pool, *s))
+ return NULL;
+ }
+ s = pool->start;
+ poolFinish(pool);
+ return s;
+}
+
+static const XML_Char * FASTCALL
+poolAppendString(STRING_POOL *pool, const XML_Char *s)
+{
+ while (*s) {
+ if (!poolAppendChar(pool, *s))
+ return NULL;
+ s++;
+ }
+ return pool->start;
+}
+
+static XML_Char *
+poolStoreString(STRING_POOL *pool, const ENCODING *enc,
+ const char *ptr, const char *end)
+{
+ if (!poolAppend(pool, enc, ptr, end))
+ return NULL;
+ if (pool->ptr == pool->end && !poolGrow(pool))
+ return NULL;
+ *(pool->ptr)++ = 0;
+ return pool->start;
+}
+
+static XML_Bool FASTCALL
+poolGrow(STRING_POOL *pool)
+{
+ if (pool->freeBlocks) {
+ if (pool->start == 0) {
+ pool->blocks = pool->freeBlocks;
+ pool->freeBlocks = pool->freeBlocks->next;
+ pool->blocks->next = NULL;
+ pool->start = pool->blocks->s;
+ pool->end = pool->start + pool->blocks->size;
+ pool->ptr = pool->start;
+ return XML_TRUE;
+ }
+ if (pool->end - pool->start < pool->freeBlocks->size) {
+ BLOCK *tem = pool->freeBlocks->next;
+ pool->freeBlocks->next = pool->blocks;
+ pool->blocks = pool->freeBlocks;
+ pool->freeBlocks = tem;
+ memcpy(pool->blocks->s, pool->start,
+ (pool->end - pool->start) * sizeof(XML_Char));
+ pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
+ pool->start = pool->blocks->s;
+ pool->end = pool->start + pool->blocks->size;
+ return XML_TRUE;
+ }
+ }
+ if (pool->blocks && pool->start == pool->blocks->s) {
+ int blockSize = (int)(pool->end - pool->start)*2;
+ pool->blocks = (BLOCK *)
+ pool->mem->realloc_fcn(pool->blocks,
+ (offsetof(BLOCK, s)
+ + blockSize * sizeof(XML_Char)));
+ if (pool->blocks == NULL)
+ return XML_FALSE;
+ pool->blocks->size = blockSize;
+ pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
+ pool->start = pool->blocks->s;
+ pool->end = pool->start + blockSize;
+ }
+ else {
+ BLOCK *tem;
+ int blockSize = (int)(pool->end - pool->start);
+ if (blockSize < INIT_BLOCK_SIZE)
+ blockSize = INIT_BLOCK_SIZE;
+ else
+ blockSize *= 2;
+ tem = (BLOCK *)pool->mem->malloc_fcn(offsetof(BLOCK, s)
+ + blockSize * sizeof(XML_Char));
+ if (!tem)
+ return XML_FALSE;
+ tem->size = blockSize;
+ tem->next = pool->blocks;
+ pool->blocks = tem;
+ if (pool->ptr != pool->start)
+ memcpy(tem->s, pool->start,
+ (pool->ptr - pool->start) * sizeof(XML_Char));
+ pool->ptr = tem->s + (pool->ptr - pool->start);
+ pool->start = tem->s;
+ pool->end = tem->s + blockSize;
+ }
+ return XML_TRUE;
+}
+
+static int FASTCALL
+nextScaffoldPart(XML_Parser parser)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ CONTENT_SCAFFOLD * me;
+ int next;
+
+ if (!dtd->scaffIndex) {
+ dtd->scaffIndex = (int *)MALLOC(groupSize * sizeof(int));
+ if (!dtd->scaffIndex)
+ return -1;
+ dtd->scaffIndex[0] = 0;
+ }
+
+ if (dtd->scaffCount >= dtd->scaffSize) {
+ CONTENT_SCAFFOLD *temp;
+ if (dtd->scaffold) {
+ temp = (CONTENT_SCAFFOLD *)
+ REALLOC(dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
+ if (temp == NULL)
+ return -1;
+ dtd->scaffSize *= 2;
+ }
+ else {
+ temp = (CONTENT_SCAFFOLD *)MALLOC(INIT_SCAFFOLD_ELEMENTS
+ * sizeof(CONTENT_SCAFFOLD));
+ if (temp == NULL)
+ return -1;
+ dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
+ }
+ dtd->scaffold = temp;
+ }
+ next = dtd->scaffCount++;
+ me = &dtd->scaffold[next];
+ if (dtd->scaffLevel) {
+ CONTENT_SCAFFOLD *parent = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel-1]];
+ if (parent->lastchild) {
+ dtd->scaffold[parent->lastchild].nextsib = next;
+ }
+ if (!parent->childcnt)
+ parent->firstchild = next;
+ parent->lastchild = next;
+ parent->childcnt++;
+ }
+ me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
+ return next;
+}
+
+static void
+build_node(XML_Parser parser,
+ int src_node,
+ XML_Content *dest,
+ XML_Content **contpos,
+ XML_Char **strpos)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ dest->type = dtd->scaffold[src_node].type;
+ dest->quant = dtd->scaffold[src_node].quant;
+ if (dest->type == XML_CTYPE_NAME) {
+ const XML_Char *src;
+ dest->name = *strpos;
+ src = dtd->scaffold[src_node].name;
+ for (;;) {
+ *(*strpos)++ = *src;
+ if (!*src)
+ break;
+ src++;
+ }
+ dest->numchildren = 0;
+ dest->children = NULL;
+ }
+ else {
+ unsigned int i;
+ int cn;
+ dest->numchildren = dtd->scaffold[src_node].childcnt;
+ dest->children = *contpos;
+ *contpos += dest->numchildren;
+ for (i = 0, cn = dtd->scaffold[src_node].firstchild;
+ i < dest->numchildren;
+ i++, cn = dtd->scaffold[cn].nextsib) {
+ build_node(parser, cn, &(dest->children[i]), contpos, strpos);
+ }
+ dest->name = NULL;
+ }
+}
+
+static XML_Content *
+build_model (XML_Parser parser)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ XML_Content *ret;
+ XML_Content *cpos;
+ XML_Char * str;
+ int allocsize = (dtd->scaffCount * sizeof(XML_Content)
+ + (dtd->contentStringLen * sizeof(XML_Char)));
+
+ ret = (XML_Content *)MALLOC(allocsize);
+ if (!ret)
+ return NULL;
+
+ str = (XML_Char *) (&ret[dtd->scaffCount]);
+ cpos = &ret[1];
+
+ build_node(parser, 0, ret, &cpos, &str);
+ return ret;
+}
+
+static ELEMENT_TYPE *
+getElementType(XML_Parser parser,
+ const ENCODING *enc,
+ const char *ptr,
+ const char *end)
+{
+ DTD * const dtd = _dtd; /* save one level of indirection */
+ const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
+ ELEMENT_TYPE *ret;
+
+ if (!name)
+ return NULL;
+ ret = (ELEMENT_TYPE *) lookup(&dtd->elementTypes, name, sizeof(ELEMENT_TYPE));
+ if (!ret)
+ return NULL;
+ if (ret->name != name)
+ poolDiscard(&dtd->pool);
+ else {
+ poolFinish(&dtd->pool);
+ if (!setElementTypePrefix(parser, ret))
+ return NULL;
+ }
+ return ret;
+}
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_external.h b/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_external.h
index 5246622bf..d71d051a6 100644
--- a/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_external.h
+++ b/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/expat_external.h
@@ -9,7 +9,9 @@
/* Namespace external symbols to allow multiple libexpat version to
co-exist. */
-#include "pyexpatns.h"
+#if !defined(UEFI_C_SOURCE)
+ #include "pyexpatns.h"
+#endif
#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
#define XML_USE_MSC_EXTENSIONS 1
@@ -101,7 +103,7 @@ typedef char XML_LChar;
#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
-typedef __int64 XML_Index;
+typedef __int64 XML_Index;
typedef unsigned __int64 XML_Size;
#else
typedef long long XML_Index;
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlparse.c b/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlparse.c
index cb84274d0..87ee2ea12 100644
--- a/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlparse.c
+++ b/AppPkg/Applications/Python/Python-2.7.2/Modules/expat/xmlparse.c
@@ -18,7 +18,11 @@
#include <string.h> /* memset(), memcpy() */
#include <assert.h>
+#if defined(UEFI_C_SOURCE)
+ #include <expat/expat.h>
+#else
#include "expat.h"
+#endif
#ifdef XML_UNICODE
#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
@@ -1493,6 +1497,10 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
ps_parsing = XML_FINISHED;
return result;
}
+ break;
+ default:
+ /* XML_FINISHED case required by compiler - but not tested - djv */
+ return XML_STATUS_OK;
}
}
diff --git a/AppPkg/Applications/Python/PythonCore.inf b/AppPkg/Applications/Python/PythonCore.inf
index 630986587..91c3afa22 100644
--- a/AppPkg/Applications/Python/PythonCore.inf
+++ b/AppPkg/Applications/Python/PythonCore.inf
@@ -41,9 +41,12 @@
LibWchar
LibGen
LibNetUtil
- BsdSocketLib
- EfiSocketLib
DevShell
+ #
+ # Comment out the following two library classes if socket support is
+ # NOT being built in to Python.
+ #BsdSocketLib
+ #EfiSocketLib
[FixedPcd]
gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x0F
@@ -72,8 +75,10 @@
#Python
PyMod-$(PYTHON_VERSION)/Python/getcopyright.c
PyMod-$(PYTHON_VERSION)/Python/marshal.c
+ PyMod-$(PYTHON_VERSION)/Python/import.c
Python-$(PYTHON_VERSION)/Python/_warnings.c
+ Python-$(PYTHON_VERSION)/Python/Python-ast.c
Python-$(PYTHON_VERSION)/Python/asdl.c
Python-$(PYTHON_VERSION)/Python/ast.c
Python-$(PYTHON_VERSION)/Python/bltinmodule.c
@@ -93,7 +98,6 @@
Python-$(PYTHON_VERSION)/Python/getplatform.c
Python-$(PYTHON_VERSION)/Python/getversion.c
Python-$(PYTHON_VERSION)/Python/graminit.c
- Python-$(PYTHON_VERSION)/Python/import.c
Python-$(PYTHON_VERSION)/Python/importdl.c
Python-$(PYTHON_VERSION)/Python/modsupport.c
Python-$(PYTHON_VERSION)/Python/mysnprintf.c
@@ -106,7 +110,6 @@
Python-$(PYTHON_VERSION)/Python/pystate.c
Python-$(PYTHON_VERSION)/Python/pystrcmp.c
Python-$(PYTHON_VERSION)/Python/pystrtod.c
- Python-$(PYTHON_VERSION)/Python/Python-ast.c
Python-$(PYTHON_VERSION)/Python/pythonrun.c
Python-$(PYTHON_VERSION)/Python/structmember.c
Python-$(PYTHON_VERSION)/Python/symtable.c
@@ -114,6 +117,8 @@
Python-$(PYTHON_VERSION)/Python/traceback.c
#Objects
+ PyMod-$(PYTHON_VERSION)/Objects/longobject.c
+
Python-$(PYTHON_VERSION)/Objects/abstract.c
Python-$(PYTHON_VERSION)/Objects/boolobject.c
Python-$(PYTHON_VERSION)/Objects/bufferobject.c
@@ -137,7 +142,6 @@
Python-$(PYTHON_VERSION)/Objects/intobject.c
Python-$(PYTHON_VERSION)/Objects/iterobject.c
Python-$(PYTHON_VERSION)/Objects/listobject.c
- Python-$(PYTHON_VERSION)/Objects/longobject.c
Python-$(PYTHON_VERSION)/Objects/memoryobject.c
Python-$(PYTHON_VERSION)/Objects/methodobject.c
Python-$(PYTHON_VERSION)/Objects/moduleobject.c
@@ -170,6 +174,7 @@
Python-$(PYTHON_VERSION)/Modules/_bisectmodule.c #
Python-$(PYTHON_VERSION)/Modules/_codecsmodule.c #
Python-$(PYTHON_VERSION)/Modules/_collectionsmodule.c #
+ Python-$(PYTHON_VERSION)/Modules/_csv.c #
Python-$(PYTHON_VERSION)/Modules/_heapqmodule.c #
Python-$(PYTHON_VERSION)/Modules/_json.c #
Python-$(PYTHON_VERSION)/Modules/_localemodule.c #
@@ -190,20 +195,27 @@
Python-$(PYTHON_VERSION)/Modules/md5module.c #
Python-$(PYTHON_VERSION)/Modules/operator.c #
Python-$(PYTHON_VERSION)/Modules/parsermodule.c #
- Python-$(PYTHON_VERSION)/Modules/shamodule.c #
Python-$(PYTHON_VERSION)/Modules/sha256module.c #
Python-$(PYTHON_VERSION)/Modules/sha512module.c #
+ Python-$(PYTHON_VERSION)/Modules/shamodule.c #
Python-$(PYTHON_VERSION)/Modules/signalmodule.c #
Python-$(PYTHON_VERSION)/Modules/socketmodule.c #
Python-$(PYTHON_VERSION)/Modules/stropmodule.c #
+ Python-$(PYTHON_VERSION)/Modules/symtablemodule.c #
Python-$(PYTHON_VERSION)/Modules/timemodule.c #
Python-$(PYTHON_VERSION)/Modules/unicodedata.c #
Python-$(PYTHON_VERSION)/Modules/xxsubtype.c #
Python-$(PYTHON_VERSION)/Modules/zipimport.c #
Python-$(PYTHON_VERSION)/Modules/zlibmodule.c #
- Python-$(PYTHON_VERSION)/Modules/_csv.c #
- Python-$(PYTHON_VERSION)/Modules/symtablemodule.c #
+#Modules/_io
+ Python-$(PYTHON_VERSION)/Modules/_io/_iomodule.c #
+ Python-$(PYTHON_VERSION)/Modules/_io/bufferedio.c #
+ Python-$(PYTHON_VERSION)/Modules/_io/bytesio.c #
+ Python-$(PYTHON_VERSION)/Modules/_io/fileio.c #
+ Python-$(PYTHON_VERSION)/Modules/_io/iobase.c #
+ Python-$(PYTHON_VERSION)/Modules/_io/stringio.c #
+ Python-$(PYTHON_VERSION)/Modules/_io/textio.c #
#Modules/cjkcodecs
Python-$(PYTHON_VERSION)/Modules/cjkcodecs/multibytecodec.c #
@@ -214,14 +226,11 @@
Python-$(PYTHON_VERSION)/Modules/cjkcodecs/_codecs_kr.c #
Python-$(PYTHON_VERSION)/Modules/cjkcodecs/_codecs_tw.c #
-#Modules/_io
- Python-$(PYTHON_VERSION)/Modules/_io/_iomodule.c #
- Python-$(PYTHON_VERSION)/Modules/_io/bufferedio.c #
- Python-$(PYTHON_VERSION)/Modules/_io/bytesio.c #
- Python-$(PYTHON_VERSION)/Modules/_io/fileio.c #
- Python-$(PYTHON_VERSION)/Modules/_io/iobase.c #
- Python-$(PYTHON_VERSION)/Modules/_io/stringio.c #
- Python-$(PYTHON_VERSION)/Modules/_io/textio.c #
+#Modules/expat
+ Python-$(PYTHON_VERSION)/Modules/pyexpat.c #
+ PyMod-$(PYTHON_VERSION)/Modules/expat/xmlparse.c #
+ Python-$(PYTHON_VERSION)/Modules/expat/xmlrole.c #
+ Python-$(PYTHON_VERSION)/Modules/expat/xmltok.c #
#Modules/zlib
Python-$(PYTHON_VERSION)/Modules/zlib/adler32.c #
@@ -238,8 +247,8 @@
Python-$(PYTHON_VERSION)/Modules/zlib/zutil.c #
[BuildOptions]
- MSFT:*_*_IA32_CC_FLAGS = /Oi- /wd4018 /wd4054 /wd4055 /wd4101 /wd4131 /wd4152 /wd4204 /wd4210 /wd4244 /wd4267 /wd4305 /wd4310 /wd4389 /wd4701 /wd4702 /wd4706 /I$(WORKSPACE)\AppPkg\Applications\Python\Ia32 /I$(WORKSPACE)\AppPkg\Applications\Python\Efi /I$(WORKSPACE)\AppPkg\Applications\Python\Python-$(PYTHON_VERSION)\Include
- MSFT:*_*_X64_CC_FLAGS = /Oi- /wd4018 /wd4054 /wd4055 /wd4101 /wd4131 /wd4152 /wd4204 /wd4210 /wd4244 /wd4267 /wd4305 /wd4310 /wd4389 /wd4701 /wd4702 /wd4706 /I$(WORKSPACE)\AppPkg\Applications\Python\X64 /I$(WORKSPACE)\AppPkg\Applications\Python\Efi /I$(WORKSPACE)\AppPkg\Applications\Python\Python-$(PYTHON_VERSION)\Include
- GCC:*_*_IA32_CC_FLAGS = -fno-builtin -Wno-format -I$(WORKSPACE)/AppPkg/Applications/Python/Ia32 -I$(WORKSPACE)/AppPkg/Applications/Python/Python-$(PYTHON_VERSION)/Include
- GCC:*_*_X64_CC_FLAGS = -Wno-format -I$(WORKSPACE)/AppPkg/Applications/Python/X64 -I$(WORKSPACE)/AppPkg/Applications/Python/Python-$(PYTHON_VERSION)/Include
+ MSFT:*_*_IA32_CC_FLAGS = /Oi- /wd4018 /wd4054 /wd4055 /wd4101 /wd4131 /wd4152 /wd4204 /wd4210 /wd4244 /wd4267 /wd4305 /wd4310 /wd4389 /wd4701 /wd4702 /wd4706 /I$(WORKSPACE)\AppPkg\Applications\Python\Ia32 /I$(WORKSPACE)\AppPkg\Applications\Python\Efi /I$(WORKSPACE)\AppPkg\Applications\Python\Python-$(PYTHON_VERSION)\Include /DHAVE_MEMMOVE /DUSE_PYEXPAT_CAPI /DXML_STATIC
+ MSFT:*_*_X64_CC_FLAGS = /Oi- /wd4018 /wd4054 /wd4055 /wd4101 /wd4131 /wd4152 /wd4204 /wd4210 /wd4244 /wd4267 /wd4305 /wd4310 /wd4389 /wd4701 /wd4702 /wd4706 /I$(WORKSPACE)\AppPkg\Applications\Python\X64 /I$(WORKSPACE)\AppPkg\Applications\Python\Efi /I$(WORKSPACE)\AppPkg\Applications\Python\Python-$(PYTHON_VERSION)\Include /DHAVE_MEMMOVE /DUSE_PYEXPAT_CAPI /DXML_STATIC
+ GCC:*_*_IA32_CC_FLAGS = -fno-builtin -Wno-format -I$(WORKSPACE)/AppPkg/Applications/Python/Ia32 -I$(WORKSPACE)/AppPkg/Applications/Python/Python-$(PYTHON_VERSION)/Include -DHAVE_MEMMOVE -DUSE_PYEXPAT_CAPI -DXML_STATIC
+ GCC:*_*_X64_CC_FLAGS = -Wno-format -I$(WORKSPACE)/AppPkg/Applications/Python/X64 -I$(WORKSPACE)/AppPkg/Applications/Python/Python-$(PYTHON_VERSION)/Include -DHAVE_MEMMOVE -DUSE_PYEXPAT_CAPI -DXML_STATIC
GCC:*_*_IPF_SYMRENAME_FLAGS = --redefine-syms=$(WORKSPACE)/StdLib/GccSymRename.txt
diff --git a/AppPkg/ISSUES.txt b/AppPkg/ISSUES.txt
new file mode 100644
index 000000000..0458deec0
--- /dev/null
+++ b/AppPkg/ISSUES.txt
@@ -0,0 +1,28 @@
+ Status Key:
+ Open Problem is unresolved and final disposition unknown.
+ Verified Problem has been reproduced.
+ Understood Root cause of problem is understood.
+ Document Problem is to be fixed through improved documentation.
+ Fixed Problem has been resolved and changes committed.
+
+Enquire Issues
+=============
+ Category Reported Status
+ ---------------------------------------------- -------------- -----------
+
+Main Issues
+=============
+ Category Reported Status
+ ---------------------------------------------- -------------- -----------
+1: The main() function should not be defined EFIAPI 2012 Fixed 1/2013
+
+Python Issues
+=============
+ Category Reported Status
+ ---------------------------------------------- -------------- -----------
+1: Setup documentation is unclear. 2012 Understood
+ Not all sources in the Python tree are the patched version, yet the
+ documentation implies that they are.
+
+2: The EDK II Python User's Manual is not on tianocore. 2012 Understood
+
diff --git a/ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf b/ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf
index 0c0ee477b..db1a3dc82 100644
--- a/ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf
+++ b/ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf
@@ -1,5 +1,5 @@
#/* @file
-# Copyright (c) 2011, ARM Limited. All rights reserved.
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -35,3 +35,5 @@
[Protocols]
gEfiLoadedImageProtocolGuid
+ gEfiDevicePathToTextProtocolGuid
+
diff --git a/ArmPkg/Application/LinuxLoader/LinuxConfig.c b/ArmPkg/Application/LinuxLoader/LinuxConfig.c
index b95d0a4dc..273fecd2d 100644
--- a/ArmPkg/Application/LinuxLoader/LinuxConfig.c
+++ b/ArmPkg/Application/LinuxLoader/LinuxConfig.c
@@ -1,353 +1,354 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "LinuxInternal.h"
-
-#define DEFAULT_BOOT_ENTRY_DESCRIPTION L"Linux"
-#define MAX_STR_INPUT 300
-#define MAX_ASCII_INPUT 300
-
-typedef enum {
- LINUX_LOADER_NEW = 1,
- LINUX_LOADER_UPDATE
-} LINUX_LOADER_ACTION;
-
-STATIC
-EFI_STATUS
-EditHIInputStr (
- IN OUT CHAR16 *CmdLine,
- IN UINTN MaxCmdLine
- )
-{
- UINTN CmdLineIndex;
- UINTN WaitIndex;
- CHAR8 Char;
- EFI_INPUT_KEY Key;
- EFI_STATUS Status;
-
- Print (CmdLine);
-
- for (CmdLineIndex = StrLen (CmdLine); CmdLineIndex < MaxCmdLine; ) {
- Status = gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &WaitIndex);
- ASSERT_EFI_ERROR (Status);
-
- Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
- ASSERT_EFI_ERROR (Status);
-
- // Unicode character is valid when Scancode is NUll
- if (Key.ScanCode == SCAN_NULL) {
- // Scan code is NUll, hence read Unicode character
- Char = (CHAR8)Key.UnicodeChar;
- } else {
- Char = CHAR_NULL;
- }
-
- if ((Char == CHAR_LINEFEED) || (Char == CHAR_CARRIAGE_RETURN) || (Char == 0x7f)) {
- CmdLine[CmdLineIndex] = '\0';
- Print (L"\n\r");
-
- return EFI_SUCCESS;
- } else if ((Key.UnicodeChar == L'\b') || (Key.ScanCode == SCAN_LEFT) || (Key.ScanCode == SCAN_DELETE)){
- if (CmdLineIndex != 0) {
- CmdLineIndex--;
- Print (L"\b \b");
- }
- } else if ((Key.ScanCode == SCAN_ESC) || (Char == 0x1B) || (Char == 0x0)) {
- return EFI_INVALID_PARAMETER;
- } else {
- CmdLine[CmdLineIndex++] = Key.UnicodeChar;
- Print (L"%c", Key.UnicodeChar);
- }
- }
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-EditHIInputAscii (
- IN OUT CHAR8 *CmdLine,
- IN UINTN MaxCmdLine
- )
-{
- CHAR16* Str;
- EFI_STATUS Status;
-
- Str = (CHAR16*)AllocatePool (MaxCmdLine * sizeof(CHAR16));
- AsciiStrToUnicodeStr (CmdLine, Str);
-
- Status = EditHIInputStr (Str, MaxCmdLine);
-
- UnicodeStrToAsciiStr (Str, CmdLine);
- FreePool (Str);
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-GetHIInputInteger (
- OUT UINTN *Integer
- )
-{
- CHAR16 CmdLine[255];
- EFI_STATUS Status;
-
- CmdLine[0] = '\0';
- Status = EditHIInputStr (CmdLine, 255);
- if (!EFI_ERROR(Status)) {
- *Integer = StrDecimalToUintn (CmdLine);
- }
-
- return Status;
-}
-
-#if 0
-EFI_STATUS
-GenerateDeviceDescriptionName (
- IN EFI_HANDLE Handle,
- IN OUT CHAR16* Description
- )
-{
- EFI_STATUS Status;
- EFI_COMPONENT_NAME_PROTOCOL* ComponentName2Protocol;
- EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* DevicePathToTextProtocol;
- EFI_DEVICE_PATH_PROTOCOL* DevicePathProtocol;
- CHAR16* DriverName;
- CHAR16* DevicePathTxt;
- EFI_DEVICE_PATH* DevicePathNode;
-
- ComponentName2Protocol = NULL;
- Status = gBS->HandleProtocol (Handle, &gEfiComponentName2ProtocolGuid, (VOID **)&ComponentName2Protocol);
- if (!EFI_ERROR(Status)) {
- //TODO: Fixme. we must find the best langague
- Status = ComponentName2Protocol->GetDriverName (ComponentName2Protocol,"en",&DriverName);
- if (!EFI_ERROR(Status)) {
- StrnCpy (Description,DriverName,BOOT_DEVICE_DESCRIPTION_MAX);
- }
- }
-
- if (EFI_ERROR(Status)) {
- // Use the lastest non null entry of the Device path as a description
- Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathProtocol);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Convert the last non end-type Device Path Node in text for the description
- DevicePathNode = GetLastDevicePathNode (DevicePathProtocol);
- Status = gBS->LocateProtocol (&gEfiDevicePathToTextProtocolGuid, NULL, (VOID **)&DevicePathToTextProtocol);
- ASSERT_EFI_ERROR(Status);
- DevicePathTxt = DevicePathToTextProtocol->ConvertDevicePathToText(DevicePathNode,TRUE,TRUE);
- StrnCpy (Description, DevicePathTxt, BOOT_DEVICE_DESCRIPTION_MAX);
- FreePool (DevicePathTxt);
- }
-
- return EFI_SUCCESS;
-}
-#endif
-
-EFI_STATUS
-LinuxLoaderConfig (
- IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage
- )
-{
- EFI_STATUS Status;
- LINUX_LOADER_ACTION Choice;
- UINTN BootOrderSize;
- UINT16* BootOrder;
- UINTN BootOrderCount;
- UINTN Index;
- CHAR16 Description[MAX_ASCII_INPUT];
- CHAR8 CmdLine[MAX_ASCII_INPUT];
- CHAR16 Initrd[MAX_STR_INPUT];
- UINT16 InitrdPathListLength;
- UINT16 CmdLineLength;
- BDS_LOAD_OPTION* BdsLoadOption;
- BDS_LOAD_OPTION** SupportedBdsLoadOptions;
- UINTN SupportedBdsLoadOptionCount;
- LINUX_LOADER_OPTIONAL_DATA* LinuxOptionalData;
- EFI_DEVICE_PATH* DevicePathRoot;
-
- SupportedBdsLoadOptions = NULL;
- SupportedBdsLoadOptionCount = 0;
-
- do {
- Print (L"[%d] Create new Linux Boot Entry\n",LINUX_LOADER_NEW);
- Print (L"[%d] Update Linux Boot Entry\n",LINUX_LOADER_UPDATE);
-
- Print (L"Option: ");
- Status = GetHIInputInteger (&Choice);
- if (Status == EFI_INVALID_PARAMETER) {
- Print (L"\n");
- return Status;
- } else if ((Choice != LINUX_LOADER_NEW) && (Choice != LINUX_LOADER_UPDATE)) {
- Print (L"Error: the option should be either '%d' or '%d'\n",LINUX_LOADER_NEW,LINUX_LOADER_UPDATE);
- Status = EFI_INVALID_PARAMETER;
- }
- } while (EFI_ERROR(Status));
-
- if (Choice == LINUX_LOADER_UPDATE) {
- // If no compatible entry then we just create a new entry
- Choice = LINUX_LOADER_NEW;
-
- // Scan the OptionalData of every entry for the correct signature
- Status = GetEnvironmentVariable (L"BootOrder", NULL, &BootOrderSize, (VOID**)&BootOrder);
- if (!EFI_ERROR(Status)) {
- BootOrderCount = BootOrderSize / sizeof(UINT16);
-
- // Allocate an array to handle maximum number of supported Boot Entry
- SupportedBdsLoadOptions = (BDS_LOAD_OPTION**)AllocatePool(sizeof(BDS_LOAD_OPTION*) * BootOrderCount);
-
- SupportedBdsLoadOptionCount = 0;
-
- // Check if the signature is present in the list of the current Boot entries
- for (Index = 0; Index < BootOrderCount; Index++) {
- Status = BootOptionFromLoadOptionIndex (BootOrder[Index], &BdsLoadOption);
- if (!EFI_ERROR(Status)) {
- if ((BdsLoadOption->OptionalDataSize >= sizeof(UINT32)) &&
- (*(UINT32*)BdsLoadOption->OptionalData == LINUX_LOADER_SIGNATURE)) {
- SupportedBdsLoadOptions[SupportedBdsLoadOptionCount++] = BdsLoadOption;
- Choice = LINUX_LOADER_UPDATE;
- }
- }
- }
- }
- FreePool (BootOrder);
- }
-
- if (Choice == LINUX_LOADER_NEW) {
- Description[0] = '\0';
- CmdLine[0] = '\0';
- Initrd[0] = '\0';
-
- BdsLoadOption = (BDS_LOAD_OPTION*)AllocateZeroPool (sizeof(BDS_LOAD_OPTION));
-
- DEBUG_CODE_BEGIN();
- CHAR16* DevicePathTxt;
- EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* DevicePathToTextProtocol;
-
- Status = gBS->LocateProtocol (&gEfiDevicePathToTextProtocolGuid, NULL, (VOID **)&DevicePathToTextProtocol);
- ASSERT_EFI_ERROR(Status);
- DevicePathTxt = DevicePathToTextProtocol->ConvertDevicePathToText (LoadedImage->FilePath, TRUE, TRUE);
-
- Print(L"EFI OS Loader: %s\n",DevicePathTxt);
-
- FreePool(DevicePathTxt);
- DEBUG_CODE_END();
-
- //
- // Fill the known fields of BdsLoadOption
- //
-
- BdsLoadOption->Attributes = LOAD_OPTION_ACTIVE | LOAD_OPTION_CATEGORY_BOOT;
-
- // Get the full Device Path for this file
- Status = gBS->HandleProtocol (LoadedImage->DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathRoot);
- ASSERT_EFI_ERROR(Status);
-
- BdsLoadOption->FilePathList = AppendDevicePath (DevicePathRoot, LoadedImage->FilePath);
- BdsLoadOption->FilePathListLength = GetDevicePathSize (BdsLoadOption->FilePathList);
- } else {
- if (SupportedBdsLoadOptionCount > 1) {
- for (Index = 0; Index < SupportedBdsLoadOptionCount; Index++) {
- Print (L"[%d] %s\n",Index + 1,SupportedBdsLoadOptions[Index]->Description);
- }
-
- do {
- Print (L"Update Boot Entry: ");
- Status = GetHIInputInteger (&Choice);
- if (Status == EFI_INVALID_PARAMETER) {
- Print (L"\n");
- return Status;
- } else if ((Choice < 1) && (Choice > SupportedBdsLoadOptionCount)) {
- Print (L"Choose entry from 1 to %d\n",SupportedBdsLoadOptionCount);
- Status = EFI_INVALID_PARAMETER;
- }
- } while (EFI_ERROR(Status));
- BdsLoadOption = SupportedBdsLoadOptions[Choice-1];
- }
- StrnCpy (Description, BdsLoadOption->Description, MAX_STR_INPUT);
-
- LinuxOptionalData = (LINUX_LOADER_OPTIONAL_DATA*)BdsLoadOption->OptionalData;
- if (LinuxOptionalData->CmdLineLength > 0) {
- CopyMem (CmdLine, (CHAR8*)LinuxOptionalData + sizeof(LINUX_LOADER_OPTIONAL_DATA), LinuxOptionalData->CmdLineLength);
- } else {
- CmdLine[0] = '\0';
- }
-
- if (LinuxOptionalData->InitrdPathListLength > 0) {
- CopyMem (Initrd, (CHAR8*)LinuxOptionalData + sizeof(LINUX_LOADER_OPTIONAL_DATA) + LinuxOptionalData->CmdLineLength, LinuxOptionalData->InitrdPathListLength);
- } else {
- Initrd[0] = L'\0';
- }
- DEBUG((EFI_D_ERROR,"L\n"));
- }
-
- // Description
- Print (L"Description: ");
- Status = EditHIInputStr (Description, MAX_STR_INPUT);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- if (StrLen (Description) == 0) {
- StrnCpy (Description, DEFAULT_BOOT_ENTRY_DESCRIPTION, MAX_STR_INPUT);
- }
- BdsLoadOption->Description = Description;
-
- // CmdLine
- Print (L"Command Line: ");
- Status = EditHIInputAscii (CmdLine, MAX_ASCII_INPUT);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Initrd
- Print (L"Initrd name: ");
- Status = EditHIInputStr (Initrd, MAX_STR_INPUT);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- CmdLineLength = AsciiStrLen (CmdLine);
- if (CmdLineLength > 0) {
- CmdLineLength += sizeof(CHAR8);
- }
-
- InitrdPathListLength = StrLen (Initrd) * sizeof(CHAR16);
- if (InitrdPathListLength > 0) {
- InitrdPathListLength += sizeof(CHAR16);
- }
-
- BdsLoadOption->OptionalDataSize = sizeof(LINUX_LOADER_OPTIONAL_DATA) + CmdLineLength + InitrdPathListLength;
-
- LinuxOptionalData = (LINUX_LOADER_OPTIONAL_DATA*)AllocatePool (BdsLoadOption->OptionalDataSize);
- BdsLoadOption->OptionalData = LinuxOptionalData;
-
- LinuxOptionalData->Signature = LINUX_LOADER_SIGNATURE;
- LinuxOptionalData->CmdLineLength = CmdLineLength;
- LinuxOptionalData->InitrdPathListLength = InitrdPathListLength;
-
- if (CmdLineLength > 0) {
- CopyMem (LinuxOptionalData + 1, CmdLine, CmdLineLength);
- }
- if (InitrdPathListLength > 0) {
- CopyMem ((UINT8*)(LinuxOptionalData + 1) + CmdLineLength, Initrd, InitrdPathListLength);
- }
-
- // Create or Update the boot entry
- Status = BootOptionToLoadOptionVariable (BdsLoadOption);
-
- return Status;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "LinuxInternal.h"
+
+#define DEFAULT_BOOT_ENTRY_DESCRIPTION L"Linux"
+#define MAX_STR_INPUT 300
+#define MAX_ASCII_INPUT 300
+
+typedef enum {
+ LINUX_LOADER_NEW = 1,
+ LINUX_LOADER_UPDATE
+} LINUX_LOADER_ACTION;
+
+STATIC
+EFI_STATUS
+EditHIInputStr (
+ IN OUT CHAR16 *CmdLine,
+ IN UINTN MaxCmdLine
+ )
+{
+ UINTN CmdLineIndex;
+ UINTN WaitIndex;
+ CHAR8 Char;
+ EFI_INPUT_KEY Key;
+ EFI_STATUS Status;
+
+ Print (CmdLine);
+
+ for (CmdLineIndex = StrLen (CmdLine); CmdLineIndex < MaxCmdLine; ) {
+ Status = gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &WaitIndex);
+ ASSERT_EFI_ERROR (Status);
+
+ Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
+ ASSERT_EFI_ERROR (Status);
+
+ // Unicode character is valid when Scancode is NUll
+ if (Key.ScanCode == SCAN_NULL) {
+ // Scan code is NUll, hence read Unicode character
+ Char = (CHAR8)Key.UnicodeChar;
+ } else {
+ Char = CHAR_NULL;
+ }
+
+ if ((Char == CHAR_LINEFEED) || (Char == CHAR_CARRIAGE_RETURN) || (Char == 0x7f)) {
+ CmdLine[CmdLineIndex] = '\0';
+ Print (L"\n\r");
+
+ return EFI_SUCCESS;
+ } else if ((Key.UnicodeChar == L'\b') || (Key.ScanCode == SCAN_LEFT) || (Key.ScanCode == SCAN_DELETE)){
+ if (CmdLineIndex != 0) {
+ CmdLineIndex--;
+ Print (L"\b \b");
+ }
+ } else if ((Key.ScanCode == SCAN_ESC) || (Char == 0x1B) || (Char == 0x0)) {
+ return EFI_INVALID_PARAMETER;
+ } else {
+ CmdLine[CmdLineIndex++] = Key.UnicodeChar;
+ Print (L"%c", Key.UnicodeChar);
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+EditHIInputAscii (
+ IN OUT CHAR8 *CmdLine,
+ IN UINTN MaxCmdLine
+ )
+{
+ CHAR16* Str;
+ EFI_STATUS Status;
+
+ Str = (CHAR16*)AllocatePool (MaxCmdLine * sizeof(CHAR16));
+ AsciiStrToUnicodeStr (CmdLine, Str);
+
+ Status = EditHIInputStr (Str, MaxCmdLine);
+
+ UnicodeStrToAsciiStr (Str, CmdLine);
+ FreePool (Str);
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+GetHIInputInteger (
+ OUT UINTN *Integer
+ )
+{
+ CHAR16 CmdLine[255];
+ EFI_STATUS Status;
+
+ CmdLine[0] = '\0';
+ Status = EditHIInputStr (CmdLine, 255);
+ if (!EFI_ERROR(Status)) {
+ *Integer = StrDecimalToUintn (CmdLine);
+ }
+
+ return Status;
+}
+
+#if 0
+EFI_STATUS
+GenerateDeviceDescriptionName (
+ IN EFI_HANDLE Handle,
+ IN OUT CHAR16* Description
+ )
+{
+ EFI_STATUS Status;
+ EFI_COMPONENT_NAME_PROTOCOL* ComponentName2Protocol;
+ EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* DevicePathToTextProtocol;
+ EFI_DEVICE_PATH_PROTOCOL* DevicePathProtocol;
+ CHAR16* DriverName;
+ CHAR16* DevicePathTxt;
+ EFI_DEVICE_PATH* DevicePathNode;
+
+ ComponentName2Protocol = NULL;
+ Status = gBS->HandleProtocol (Handle, &gEfiComponentName2ProtocolGuid, (VOID **)&ComponentName2Protocol);
+ if (!EFI_ERROR(Status)) {
+ //TODO: Fixme. we must find the best langague
+ Status = ComponentName2Protocol->GetDriverName (ComponentName2Protocol,"en",&DriverName);
+ if (!EFI_ERROR(Status)) {
+ StrnCpy (Description,DriverName,BOOT_DEVICE_DESCRIPTION_MAX);
+ }
+ }
+
+ if (EFI_ERROR(Status)) {
+ // Use the lastest non null entry of the Device path as a description
+ Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathProtocol);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Convert the last non end-type Device Path Node in text for the description
+ DevicePathNode = GetLastDevicePathNode (DevicePathProtocol);
+ Status = gBS->LocateProtocol (&gEfiDevicePathToTextProtocolGuid, NULL, (VOID **)&DevicePathToTextProtocol);
+ ASSERT_EFI_ERROR(Status);
+ DevicePathTxt = DevicePathToTextProtocol->ConvertDevicePathToText(DevicePathNode,TRUE,TRUE);
+ StrnCpy (Description, DevicePathTxt, BOOT_DEVICE_DESCRIPTION_MAX);
+ FreePool (DevicePathTxt);
+ }
+
+ return EFI_SUCCESS;
+}
+#endif
+
+EFI_STATUS
+LinuxLoaderConfig (
+ IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage
+ )
+{
+ EFI_STATUS Status;
+ LINUX_LOADER_ACTION Choice;
+ UINTN BootOrderSize;
+ UINT16* BootOrder;
+ UINTN BootOrderCount;
+ UINTN Index;
+ CHAR16 Description[MAX_ASCII_INPUT];
+ CHAR8 CmdLine[MAX_ASCII_INPUT];
+ CHAR16 Initrd[MAX_STR_INPUT];
+ UINT16 InitrdPathListLength;
+ UINT16 CmdLineLength;
+ BDS_LOAD_OPTION* BdsLoadOption;
+ BDS_LOAD_OPTION** SupportedBdsLoadOptions;
+ UINTN SupportedBdsLoadOptionCount;
+ LINUX_LOADER_OPTIONAL_DATA* LinuxOptionalData;
+ EFI_DEVICE_PATH* DevicePathRoot;
+
+ Choice = (LINUX_LOADER_ACTION)0;
+ SupportedBdsLoadOptions = NULL;
+ SupportedBdsLoadOptionCount = 0;
+
+ do {
+ Print (L"[%d] Create new Linux Boot Entry\n",LINUX_LOADER_NEW);
+ Print (L"[%d] Update Linux Boot Entry\n",LINUX_LOADER_UPDATE);
+
+ Print (L"Option: ");
+ Status = GetHIInputInteger (&Choice);
+ if (Status == EFI_INVALID_PARAMETER) {
+ Print (L"\n");
+ return Status;
+ } else if ((Choice != LINUX_LOADER_NEW) && (Choice != LINUX_LOADER_UPDATE)) {
+ Print (L"Error: the option should be either '%d' or '%d'\n",LINUX_LOADER_NEW,LINUX_LOADER_UPDATE);
+ Status = EFI_INVALID_PARAMETER;
+ }
+ } while (EFI_ERROR(Status));
+
+ if (Choice == LINUX_LOADER_UPDATE) {
+ // If no compatible entry then we just create a new entry
+ Choice = LINUX_LOADER_NEW;
+
+ // Scan the OptionalData of every entry for the correct signature
+ Status = GetEnvironmentVariable (L"BootOrder", NULL, &BootOrderSize, (VOID**)&BootOrder);
+ if (!EFI_ERROR(Status)) {
+ BootOrderCount = BootOrderSize / sizeof(UINT16);
+
+ // Allocate an array to handle maximum number of supported Boot Entry
+ SupportedBdsLoadOptions = (BDS_LOAD_OPTION**)AllocatePool(sizeof(BDS_LOAD_OPTION*) * BootOrderCount);
+
+ SupportedBdsLoadOptionCount = 0;
+
+ // Check if the signature is present in the list of the current Boot entries
+ for (Index = 0; Index < BootOrderCount; Index++) {
+ Status = BootOptionFromLoadOptionIndex (BootOrder[Index], &BdsLoadOption);
+ if (!EFI_ERROR(Status)) {
+ if ((BdsLoadOption->OptionalDataSize >= sizeof(UINT32)) &&
+ (*(UINT32*)BdsLoadOption->OptionalData == LINUX_LOADER_SIGNATURE)) {
+ SupportedBdsLoadOptions[SupportedBdsLoadOptionCount++] = BdsLoadOption;
+ Choice = LINUX_LOADER_UPDATE;
+ }
+ }
+ }
+ }
+ FreePool (BootOrder);
+ }
+
+ if (Choice == LINUX_LOADER_NEW) {
+ Description[0] = '\0';
+ CmdLine[0] = '\0';
+ Initrd[0] = '\0';
+
+ BdsLoadOption = (BDS_LOAD_OPTION*)AllocateZeroPool (sizeof(BDS_LOAD_OPTION));
+
+ DEBUG_CODE_BEGIN();
+ CHAR16* DevicePathTxt;
+ EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* DevicePathToTextProtocol;
+
+ Status = gBS->LocateProtocol (&gEfiDevicePathToTextProtocolGuid, NULL, (VOID **)&DevicePathToTextProtocol);
+ ASSERT_EFI_ERROR(Status);
+ DevicePathTxt = DevicePathToTextProtocol->ConvertDevicePathToText (LoadedImage->FilePath, TRUE, TRUE);
+
+ Print(L"EFI OS Loader: %s\n",DevicePathTxt);
+
+ FreePool(DevicePathTxt);
+ DEBUG_CODE_END();
+
+ //
+ // Fill the known fields of BdsLoadOption
+ //
+
+ BdsLoadOption->Attributes = LOAD_OPTION_ACTIVE | LOAD_OPTION_CATEGORY_BOOT;
+
+ // Get the full Device Path for this file
+ Status = gBS->HandleProtocol (LoadedImage->DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathRoot);
+ ASSERT_EFI_ERROR(Status);
+
+ BdsLoadOption->FilePathList = AppendDevicePath (DevicePathRoot, LoadedImage->FilePath);
+ BdsLoadOption->FilePathListLength = GetDevicePathSize (BdsLoadOption->FilePathList);
+ } else {
+ if (SupportedBdsLoadOptionCount > 1) {
+ for (Index = 0; Index < SupportedBdsLoadOptionCount; Index++) {
+ Print (L"[%d] %s\n",Index + 1,SupportedBdsLoadOptions[Index]->Description);
+ }
+
+ do {
+ Print (L"Update Boot Entry: ");
+ Status = GetHIInputInteger (&Choice);
+ if (Status == EFI_INVALID_PARAMETER) {
+ Print (L"\n");
+ return Status;
+ } else if ((Choice < 1) && (Choice > SupportedBdsLoadOptionCount)) {
+ Print (L"Choose entry from 1 to %d\n",SupportedBdsLoadOptionCount);
+ Status = EFI_INVALID_PARAMETER;
+ }
+ } while (EFI_ERROR(Status));
+ BdsLoadOption = SupportedBdsLoadOptions[Choice-1];
+ }
+ StrnCpy (Description, BdsLoadOption->Description, MAX_STR_INPUT);
+
+ LinuxOptionalData = (LINUX_LOADER_OPTIONAL_DATA*)BdsLoadOption->OptionalData;
+ if (LinuxOptionalData->CmdLineLength > 0) {
+ CopyMem (CmdLine, (CHAR8*)LinuxOptionalData + sizeof(LINUX_LOADER_OPTIONAL_DATA), LinuxOptionalData->CmdLineLength);
+ } else {
+ CmdLine[0] = '\0';
+ }
+
+ if (LinuxOptionalData->InitrdPathListLength > 0) {
+ CopyMem (Initrd, (CHAR8*)LinuxOptionalData + sizeof(LINUX_LOADER_OPTIONAL_DATA) + LinuxOptionalData->CmdLineLength, LinuxOptionalData->InitrdPathListLength);
+ } else {
+ Initrd[0] = L'\0';
+ }
+ DEBUG((EFI_D_ERROR,"L\n"));
+ }
+
+ // Description
+ Print (L"Description: ");
+ Status = EditHIInputStr (Description, MAX_STR_INPUT);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ if (StrLen (Description) == 0) {
+ StrnCpy (Description, DEFAULT_BOOT_ENTRY_DESCRIPTION, MAX_STR_INPUT);
+ }
+ BdsLoadOption->Description = Description;
+
+ // CmdLine
+ Print (L"Command Line: ");
+ Status = EditHIInputAscii (CmdLine, MAX_ASCII_INPUT);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Initrd
+ Print (L"Initrd name: ");
+ Status = EditHIInputStr (Initrd, MAX_STR_INPUT);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ CmdLineLength = AsciiStrLen (CmdLine);
+ if (CmdLineLength > 0) {
+ CmdLineLength += sizeof(CHAR8);
+ }
+
+ InitrdPathListLength = StrLen (Initrd) * sizeof(CHAR16);
+ if (InitrdPathListLength > 0) {
+ InitrdPathListLength += sizeof(CHAR16);
+ }
+
+ BdsLoadOption->OptionalDataSize = sizeof(LINUX_LOADER_OPTIONAL_DATA) + CmdLineLength + InitrdPathListLength;
+
+ LinuxOptionalData = (LINUX_LOADER_OPTIONAL_DATA*)AllocatePool (BdsLoadOption->OptionalDataSize);
+ BdsLoadOption->OptionalData = LinuxOptionalData;
+
+ LinuxOptionalData->Signature = LINUX_LOADER_SIGNATURE;
+ LinuxOptionalData->CmdLineLength = CmdLineLength;
+ LinuxOptionalData->InitrdPathListLength = InitrdPathListLength;
+
+ if (CmdLineLength > 0) {
+ CopyMem (LinuxOptionalData + 1, CmdLine, CmdLineLength);
+ }
+ if (InitrdPathListLength > 0) {
+ CopyMem ((UINT8*)(LinuxOptionalData + 1) + CmdLineLength, Initrd, InitrdPathListLength);
+ }
+
+ // Create or Update the boot entry
+ Status = BootOptionToLoadOptionVariable (BdsLoadOption);
+
+ return Status;
+}
diff --git a/ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf b/ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf
index a132dd9fe..fbd13308a 100644
--- a/ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf
+++ b/ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf
@@ -1,5 +1,5 @@
#/* @file
-# Copyright (c) 2011, ARM Limited. All rights reserved.
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -35,3 +35,5 @@
[Protocols]
gEfiLoadedImageProtocolGuid
+ gEfiDevicePathToTextProtocolGuid
+
diff --git a/ArmPkg/Application/LinuxLoader/LinuxInternal.h b/ArmPkg/Application/LinuxLoader/LinuxInternal.h
index e48627352..88d786f69 100644
--- a/ArmPkg/Application/LinuxLoader/LinuxInternal.h
+++ b/ArmPkg/Application/LinuxLoader/LinuxInternal.h
@@ -1,49 +1,50 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef __LOADER_INTERNAL_H
-#define __LOADER_INTERNAL_H
-
-#include <Uefi.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/BdsLib.h>
-#include <Library/DebugLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-
-#include <Protocol/LoadedImage.h>
-
-#define LINUX_KERNEL_NAME L"zImage"
-#define FDT_NAME L"platform.dtb"
-
-#define LINUX_LOADER_SIGNATURE SIGNATURE_32('l', 'i', 'l', 'o')
-
-typedef struct {
- UINT32 Signature;
- UINT16 CmdLineLength;
- UINT16 InitrdPathListLength;
-
- // These following fields have variable length:
- //CHAR8* CmdLine;
- //CHAR16* Initrd;
-} LINUX_LOADER_OPTIONAL_DATA;
-
-EFI_STATUS
-LinuxLoaderConfig (
- IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage
- );
-
-#endif
+/** @file
+*
+* Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef __LOADER_INTERNAL_H
+#define __LOADER_INTERNAL_H
+
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/BdsLib.h>
+#include <Library/DebugLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+
+#include <Protocol/LoadedImage.h>
+#include <Protocol/DevicePathToText.h>
+
+#define LINUX_KERNEL_NAME L"zImage"
+#define FDT_NAME L"platform.dtb"
+
+#define LINUX_LOADER_SIGNATURE SIGNATURE_32('l', 'i', 'l', 'o')
+
+typedef struct {
+ UINT32 Signature;
+ UINT16 CmdLineLength;
+ UINT16 InitrdPathListLength;
+
+ // These following fields have variable length:
+ //CHAR8* CmdLine;
+ //CHAR16* Initrd;
+} LINUX_LOADER_OPTIONAL_DATA;
+
+EFI_STATUS
+LinuxLoaderConfig (
+ IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage
+ );
+
+#endif
diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc
index abc25a69a..da55d6051 100644
--- a/ArmPkg/ArmPkg.dsc
+++ b/ArmPkg/ArmPkg.dsc
@@ -1,131 +1,131 @@
-#/** @file
-# ARM processor package.
-#
-# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-################################################################################
-#
-# Defines Section - statements that will be processed to create a Makefile.
-#
-################################################################################
-[Defines]
- PLATFORM_NAME = ArmPkg
- PLATFORM_GUID = 5CFBD99E-3C43-4E7F-8054-9CDEAFF7710F
- PLATFORM_VERSION = 0.1
- DSC_SPECIFICATION = 0x00010005
- OUTPUT_DIRECTORY = Build/Arm
- SUPPORTED_ARCHITECTURES = ARM
- BUILD_TARGETS = DEBUG|RELEASE
- SKUID_IDENTIFIER = DEFAULT
-
-[BuildOptions]
- XCODE:*_*_ARM_PLATFORM_FLAGS == -arch armv7
- XCODE:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG
-
- GCC:*_*_ARM_PLATFORM_FLAGS == -march=armv7-a -mfpu=neon
- GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG
-
- RVCT:*_*_ARM_PLATFORM_FLAGS == --cpu Cortex-A8
- RVCT:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG
-
-[LibraryClasses.common]
- BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
- BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
- CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
- DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
- HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
- PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
- PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
- TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
- UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
- UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
- UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
- DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
- UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
- PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
-
- SemihostLib|ArmPkg/Library/SemihostLib/SemihostLib.inf
- UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
- DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
- DefaultExceptionHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
-
- ArmLib|ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
- CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
- ArmDisassemblerLib|ArmPkg/Library/ArmDisassemblerLib/ArmDisassemblerLib.inf
- DmaLib|ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
- ArmTrustZoneLib|ArmPkg/Library/ArmTrustZoneLib/ArmTrustZoneLib.inf
-
- UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
- PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
- # TODO: Check if we cannot remove this dependancy (Mayve using the SerialLibNull implementation makes the EFI application do not print)
- SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf
-
- BdsLib|ArmPkg/Library/BdsLib/BdsLib.inf
- FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf
-
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
-
-[LibraryClasses.common.PEIM]
- HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
- PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
- MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
- PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
- PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf
-
-[LibraryClasses.common.DXE_DRIVER]
- ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
-
-[LibraryClasses.ARM]
- NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
-
-[Components.common]
- ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
- ArmPkg/Library/ArmDisassemblerLib/ArmDisassemblerLib.inf
- ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
-# ArmPkg/Library/ArmLib/Arm11/Arm11ArmLib.inf
-# ArmPkg/Library/ArmLib/Arm11/Arm11ArmLibPrePi.inf
-# ArmPkg/Library/ArmLib/Arm9/Arm9ArmLib.inf
-# ArmPkg/Library/ArmLib/Arm9/Arm9ArmLibPrePi.inf
- ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
- ArmPkg/Library/ArmLib/ArmV7/ArmV7LibPrePi.inf
- ArmPkg/Library/ArmLib/ArmV7/ArmV7LibSec.inf
- ArmPkg/Library/ArmLib/Null/NullArmLib.inf
- ArmPkg/Library/BaseMemoryLibStm/BaseMemoryLibStm.inf
- ArmPkg/Library/BaseMemoryLibVstm/BaseMemoryLibVstm.inf
- ArmPkg/Library/BasePeCoffLib/BasePeCoffLib.inf
- ArmPkg/Library/BdsLib/BdsLib.inf
- ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
- ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
- ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
- ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
- ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
- ArmPkg/Library/SemiHostingDebugLib/SemiHostingDebugLib.inf
- ArmPkg/Library/SemiHostingSerialPortLib/SemiHostingSerialPortLib.inf
- ArmPkg/Library/SemihostLib/SemihostLib.inf
- ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
-
- ArmPkg/Drivers/ArmCpuLib/ArmCortexA8Lib/ArmCortexA8Lib.inf
- ArmPkg/Drivers/ArmCpuLib/ArmCortexA9Lib/ArmCortexA9Lib.inf
- ArmPkg/Drivers/ArmCpuLib/ArmCortexA15Lib/ArmCortexA15Lib.inf
- ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- ArmPkg/Drivers/CpuPei/CpuPei.inf
- ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
- ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
- ArmPkg/Drivers/PL390Gic/PL390GicSecLib.inf
- ArmPkg/Drivers/TimerDxe/TimerDxe.inf
-
- ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf
- ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf
+#/** @file
+# ARM processor package.
+#
+# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
+# Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+ PLATFORM_NAME = ArmPkg
+ PLATFORM_GUID = 5CFBD99E-3C43-4E7F-8054-9CDEAFF7710F
+ PLATFORM_VERSION = 0.1
+ DSC_SPECIFICATION = 0x00010005
+ OUTPUT_DIRECTORY = Build/Arm
+ SUPPORTED_ARCHITECTURES = ARM
+ BUILD_TARGETS = DEBUG|RELEASE
+ SKUID_IDENTIFIER = DEFAULT
+
+[BuildOptions]
+ XCODE:*_*_ARM_PLATFORM_FLAGS == -arch armv7
+ XCODE:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG
+
+ GCC:*_*_ARM_PLATFORM_FLAGS == -march=armv7-a -mfpu=neon
+ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG
+
+ RVCT:*_*_ARM_PLATFORM_FLAGS == --cpu Cortex-A8
+ RVCT:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG
+
+[LibraryClasses.common]
+ BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+ CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
+ DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
+ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+ TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
+ UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
+ UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
+ UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
+ PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+
+ SemihostLib|ArmPkg/Library/SemihostLib/SemihostLib.inf
+ UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
+ DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
+ DefaultExceptionHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
+
+ ArmLib|ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
+ CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
+ ArmDisassemblerLib|ArmPkg/Library/ArmDisassemblerLib/ArmDisassemblerLib.inf
+ DmaLib|ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
+
+ UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
+ PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
+ SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf
+
+ BdsLib|ArmPkg/Library/BdsLib/BdsLib.inf
+ FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf
+
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+
+[LibraryClasses.common.PEIM]
+ HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
+ PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
+ MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
+ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
+ PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf
+
+[LibraryClasses.common.DXE_DRIVER]
+ ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
+
+[LibraryClasses.ARM]
+ NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
+
+[Components.common]
+ ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
+ ArmPkg/Library/ArmDisassemblerLib/ArmDisassemblerLib.inf
+ ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
+# ArmPkg/Library/ArmLib/Arm11/Arm11ArmLib.inf
+# ArmPkg/Library/ArmLib/Arm11/Arm11ArmLibPrePi.inf
+# ArmPkg/Library/ArmLib/Arm9/Arm9ArmLib.inf
+# ArmPkg/Library/ArmLib/Arm9/Arm9ArmLibPrePi.inf
+ ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
+ ArmPkg/Library/ArmLib/ArmV7/ArmV7LibPrePi.inf
+ ArmPkg/Library/ArmLib/ArmV7/ArmV7LibSec.inf
+ ArmPkg/Library/ArmLib/Null/NullArmLib.inf
+ ArmPkg/Library/BaseMemoryLibStm/BaseMemoryLibStm.inf
+ ArmPkg/Library/BaseMemoryLibVstm/BaseMemoryLibVstm.inf
+ ArmPkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+ ArmPkg/Library/BdsLib/BdsLib.inf
+ ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
+ ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentSymbolsBaseLib.inf
+ ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
+ ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
+ ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
+ ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
+ ArmPkg/Library/SemiHostingDebugLib/SemiHostingDebugLib.inf
+ ArmPkg/Library/SemiHostingSerialPortLib/SemiHostingSerialPortLib.inf
+ ArmPkg/Library/SemihostLib/SemihostLib.inf
+ ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
+
+ ArmPkg/Drivers/ArmCpuLib/ArmCortexA8Lib/ArmCortexA8Lib.inf
+ ArmPkg/Drivers/ArmCpuLib/ArmCortexA9Lib/ArmCortexA9Lib.inf
+ ArmPkg/Drivers/ArmCpuLib/ArmCortexA15Lib/ArmCortexA15Lib.inf
+ ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ ArmPkg/Drivers/CpuPei/CpuPei.inf
+ ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
+ ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
+ ArmPkg/Drivers/PL390Gic/PL390GicSecLib.inf
+ ArmPkg/Drivers/TimerDxe/TimerDxe.inf
+
+ ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ ArmPkg/Application/LinuxLoader/LinuxAtagLoader.inf
+ ArmPkg/Application/LinuxLoader/LinuxFdtLoader.inf
diff --git a/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S b/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S
index 96bd68246..2b439f333 100644
--- a/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S
+++ b/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.S
@@ -1,191 +1,191 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-.text
-.align 3
-
-GCC_ASM_EXPORT(ExceptionHandlersStart)
-GCC_ASM_EXPORT(ExceptionHandlersEnd)
-GCC_ASM_EXPORT(CommonExceptionEntry)
-GCC_ASM_EXPORT(AsmCommonExceptionEntry)
-GCC_ASM_EXPORT(CommonCExceptionHandler)
-
-ASM_PFX(ExceptionHandlersStart):
-
-ASM_PFX(Reset):
- b ASM_PFX(ResetEntry)
-
-ASM_PFX(UndefinedInstruction):
- b ASM_PFX(UndefinedInstructionEntry)
-
-ASM_PFX(SoftwareInterrupt):
- b ASM_PFX(SoftwareInterruptEntry)
-
-ASM_PFX(PrefetchAbort):
- b ASM_PFX(PrefetchAbortEntry)
-
-ASM_PFX(DataAbort):
- b ASM_PFX(DataAbortEntry)
-
-ASM_PFX(ReservedException):
- b ASM_PFX(ReservedExceptionEntry)
-
-ASM_PFX(Irq):
- b ASM_PFX(IrqEntry)
-
-ASM_PFX(Fiq):
- b ASM_PFX(FiqEntry)
-
-ASM_PFX(ResetEntry):
- srsdb #0x13! @ Store return state on SVC stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#0
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(UndefinedInstructionEntry):
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#1
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(SoftwareInterruptEntry):
- srsdb #0x13! @ Store return state on SVC stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#2
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(PrefetchAbortEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#3
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(DataAbortEntry):
- sub LR,LR,#8
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#4
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(ReservedExceptionEntry):
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#5
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(IrqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#6
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(FiqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov r0,#7
- ldr r1,ASM_PFX(CommonExceptionEntry)
- bx r1
-
-ASM_PFX(CommonExceptionEntry):
- .byte 0x12
- .byte 0x34
- .byte 0x56
- .byte 0x78
-
-ASM_PFX(ExceptionHandlersEnd):
-
-ASM_PFX(AsmCommonExceptionEntry):
- mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
- str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
-
- mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
- str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
-
- mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
- str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
-
- mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
- str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
-
- ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
- str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
- and r1, r1, #0x1f @ Check to see if User or System Mode
- cmp r1, #0x1f
- cmpne r1, #0x10
- add R2, SP, #0x38 @ Store it in EFI_SYSTEM_CONTEXT_ARM.LR
- ldmneed r2, {lr}^ @ User or System mode, use unbanked register
- ldmneed r2, {lr} @ All other modes used banked register
-
- ldr R1, [SP, #0x58] @ PC is the LR pushed by srsdb
- str R1, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
-
- sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
- str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
-
- @ R0 is exception type
- mov R1,SP @ Prepare System Context pointer as an argument for the exception handler
- blx ASM_PFX(CommonCExceptionHandler) @ Call exception handler
-
- ldr R2,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
- str R2,[SP,#0x5c] @ Store it back to srsdb stack slot so it can be restored
-
- ldr R2,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
- str R2,[SP,#0x58] @ Store it back to srsdb stack slot so it can be restored
-
- ldmfd SP!,{R0-R12} @ Restore general purpose registers
- @ Exception handler can not change SP or LR as we would blow chunks
-
- add SP,SP,#0x20 @ Clear out the remaining stack space
- ldmfd SP!,{LR} @ restore the link register for this context
- rfefd SP! @ return from exception via srsdb stack slot
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+.text
+.align 3
+
+GCC_ASM_EXPORT(ExceptionHandlersStart)
+GCC_ASM_EXPORT(ExceptionHandlersEnd)
+GCC_ASM_EXPORT(CommonExceptionEntry)
+GCC_ASM_EXPORT(AsmCommonExceptionEntry)
+GCC_ASM_EXPORT(CommonCExceptionHandler)
+
+ASM_PFX(ExceptionHandlersStart):
+
+ASM_PFX(Reset):
+ b ASM_PFX(ResetEntry)
+
+ASM_PFX(UndefinedInstruction):
+ b ASM_PFX(UndefinedInstructionEntry)
+
+ASM_PFX(SoftwareInterrupt):
+ b ASM_PFX(SoftwareInterruptEntry)
+
+ASM_PFX(PrefetchAbort):
+ b ASM_PFX(PrefetchAbortEntry)
+
+ASM_PFX(DataAbort):
+ b ASM_PFX(DataAbortEntry)
+
+ASM_PFX(ReservedException):
+ b ASM_PFX(ReservedExceptionEntry)
+
+ASM_PFX(Irq):
+ b ASM_PFX(IrqEntry)
+
+ASM_PFX(Fiq):
+ b ASM_PFX(FiqEntry)
+
+ASM_PFX(ResetEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#0
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(UndefinedInstructionEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#1
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(SoftwareInterruptEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#2
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(PrefetchAbortEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#3
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(DataAbortEntry):
+ sub LR,LR,#8
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#4
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(ReservedExceptionEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#5
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(IrqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#6
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(FiqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov r0,#7
+ ldr r1,ASM_PFX(CommonExceptionEntry)
+ bx r1
+
+ASM_PFX(CommonExceptionEntry):
+ .byte 0x12
+ .byte 0x34
+ .byte 0x56
+ .byte 0x78
+
+ASM_PFX(ExceptionHandlersEnd):
+
+ASM_PFX(AsmCommonExceptionEntry):
+ mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
+ str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
+
+ mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
+ str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
+
+ mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
+ str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
+
+ mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
+ str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
+
+ ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
+ str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
+ and r1, r1, #0x1f @ Check to see if User or System Mode
+ cmp r1, #0x1f
+ cmpne r1, #0x10
+ add R2, SP, #0x38 @ Store it in EFI_SYSTEM_CONTEXT_ARM.LR
+ ldmneed r2, {lr}^ @ User or System mode, use unbanked register
+ ldmneed r2, {lr} @ All other modes used banked register
+
+ ldr R1, [SP, #0x58] @ PC is the LR pushed by srsdb
+ str R1, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
+
+ sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
+ str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
+
+ @ R0 is exception type
+ mov R1,SP @ Prepare System Context pointer as an argument for the exception handler
+ blx ASM_PFX(CommonCExceptionHandler) @ Call exception handler
+
+ ldr R2,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
+ str R2,[SP,#0x5c] @ Store it back to srsdb stack slot so it can be restored
+
+ ldr R2,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
+ str R2,[SP,#0x58] @ Store it back to srsdb stack slot so it can be restored
+
+ ldmfd SP!,{R0-R12} @ Restore general purpose registers
+ @ Exception handler can not change SP or LR as we would blow chunks
+
+ add SP,SP,#0x20 @ Clear out the remaining stack space
+ ldmfd SP!,{LR} @ restore the link register for this context
+ rfefd SP! @ return from exception via srsdb stack slot
diff --git a/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.asm b/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.asm
index 4af58339b..2ea8d65f1 100644
--- a/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.asm
+++ b/ArmPkg/Drivers/CpuDxe/ArmV4/ExceptionSupport.asm
@@ -1,152 +1,152 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
- EXPORT ExceptionHandlersStart
- EXPORT ExceptionHandlersEnd
- EXPORT CommonExceptionEntry
- EXPORT AsmCommonExceptionEntry
- IMPORT CommonCExceptionHandler
-
- PRESERVE8
- AREA DxeExceptionHandlers, CODE, READONLY
-
-ExceptionHandlersStart
-
-Reset
- b ResetEntry
-
-UndefinedInstruction
- b UndefinedInstructionEntry
-
-SoftwareInterrupt
- b SoftwareInterruptEntry
-
-PrefetchAbort
- b PrefetchAbortEntry
-
-DataAbort
- b DataAbortEntry
-
-ReservedException
- b ReservedExceptionEntry
-
-Irq
- b IrqEntry
-
-Fiq
- b FiqEntry
-
-ResetEntry
- stmfd SP!,{R0-R1}
- mov R0,#0
- ldr R1,CommonExceptionEntry
- bx R1
-
-UndefinedInstructionEntry
- stmfd SP!,{R0-R1}
- mov R0,#1
- ldr R1,CommonExceptionEntry
- bx R1
-
-SoftwareInterruptEntry
- stmfd SP!,{R0-R1}
- mov R0,#2
- ldr R1,CommonExceptionEntry
- bx R1
-
-PrefetchAbortEntry
- stmfd SP!,{R0-R1}
- mov R0,#3
- SUB LR,LR,#4
- ldr R1,CommonExceptionEntry
- bx R1
-
-DataAbortEntry
- stmfd SP!,{R0-R1}
- mov R0,#4
- SUB LR,LR,#8
- ldr R1,CommonExceptionEntry
- bx R1
-
-ReservedExceptionEntry
- stmfd SP!,{R0-R1}
- mov R0,#5
- ldr R1,CommonExceptionEntry
- bx R1
-
-IrqEntry
- stmfd SP!,{R0-R1}
- mov R0,#6
- SUB LR,LR,#4
- ldr R1,CommonExceptionEntry
- bx R1
-
-FiqEntry
- stmfd SP!,{R0-R1}
- mov R0,#7
- SUB LR,LR,#4
- ldr R1,CommonExceptionEntry
- bx R1
-
-CommonExceptionEntry
- dcd 0x12345678
-
-ExceptionHandlersEnd
-
-AsmCommonExceptionEntry
- mrc p15, 0, r1, c6, c0, 2 ; Read IFAR
- stmfd SP!,{R1} ; Store the IFAR
-
- mrc p15, 0, r1, c5, c0, 1 ; Read IFSR
- stmfd SP!,{R1} ; Store the IFSR
-
- mrc p15, 0, r1, c6, c0, 0 ; Read DFAR
- stmfd SP!,{R1} ; Store the DFAR
-
- mrc p15, 0, r1, c5, c0, 0 ; Read DFSR
- stmfd SP!,{R1} ; Store the DFSR
-
- mrs R1,SPSR ; Read SPSR (which is the pre-exception CPSR)
- stmfd SP!,{R1} ; Store the SPSR
-
- stmfd SP!,{LR} ; Store the link register (which is the pre-exception PC)
- stmfd SP,{SP,LR}^ ; Store user/system mode stack pointer and link register
- nop ; Required by ARM architecture
- SUB SP,SP,#0x08 ; Adjust stack pointer
- stmfd SP!,{R2-R12} ; Store general purpose registers
-
- ldr R3,[SP,#0x50] ; Read saved R1 from the stack (it was saved by the exception entry routine)
- ldr R2,[SP,#0x4C] ; Read saved R0 from the stack (it was saved by the exception entry routine)
- stmfd SP!,{R2-R3} ; Store general purpose registers R0 and R1
-
- mov R1,SP ; Prepare System Context pointer as an argument for the exception handler
-
- sub SP,SP,#4 ; Adjust SP to preserve 8-byte alignment
- blx CommonCExceptionHandler ; Call exception handler
- add SP,SP,#4 ; Adjust SP back to where we were
-
- ldr R2,[SP,#0x40] ; Load CPSR from context, in case it has changed
- MSR SPSR_cxsf,R2 ; Store it back to the SPSR to be restored when exiting this handler
-
- ldmfd SP!,{R0-R12} ; Restore general purpose registers
- ldm SP,{SP,LR}^ ; Restore user/system mode stack pointer and link register
- nop ; Required by ARM architecture
- add SP,SP,#0x08 ; Adjust stack pointer
- ldmfd SP!,{LR} ; Restore the link register (which is the pre-exception PC)
- add SP,SP,#0x1C ; Clear out the remaining stack space
- movs PC,LR ; Return from exception
-
- END
-
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+ EXPORT ExceptionHandlersStart
+ EXPORT ExceptionHandlersEnd
+ EXPORT CommonExceptionEntry
+ EXPORT AsmCommonExceptionEntry
+ IMPORT CommonCExceptionHandler
+
+ PRESERVE8
+ AREA DxeExceptionHandlers, CODE, READONLY
+
+ExceptionHandlersStart
+
+Reset
+ b ResetEntry
+
+UndefinedInstruction
+ b UndefinedInstructionEntry
+
+SoftwareInterrupt
+ b SoftwareInterruptEntry
+
+PrefetchAbort
+ b PrefetchAbortEntry
+
+DataAbort
+ b DataAbortEntry
+
+ReservedException
+ b ReservedExceptionEntry
+
+Irq
+ b IrqEntry
+
+Fiq
+ b FiqEntry
+
+ResetEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#0
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+UndefinedInstructionEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#1
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+SoftwareInterruptEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#2
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+PrefetchAbortEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#3
+ SUB LR,LR,#4
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+DataAbortEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#4
+ SUB LR,LR,#8
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+ReservedExceptionEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#5
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+IrqEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#6
+ SUB LR,LR,#4
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+FiqEntry
+ stmfd SP!,{R0-R1}
+ mov R0,#7
+ SUB LR,LR,#4
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+CommonExceptionEntry
+ dcd 0x12345678
+
+ExceptionHandlersEnd
+
+AsmCommonExceptionEntry
+ mrc p15, 0, r1, c6, c0, 2 ; Read IFAR
+ stmfd SP!,{R1} ; Store the IFAR
+
+ mrc p15, 0, r1, c5, c0, 1 ; Read IFSR
+ stmfd SP!,{R1} ; Store the IFSR
+
+ mrc p15, 0, r1, c6, c0, 0 ; Read DFAR
+ stmfd SP!,{R1} ; Store the DFAR
+
+ mrc p15, 0, r1, c5, c0, 0 ; Read DFSR
+ stmfd SP!,{R1} ; Store the DFSR
+
+ mrs R1,SPSR ; Read SPSR (which is the pre-exception CPSR)
+ stmfd SP!,{R1} ; Store the SPSR
+
+ stmfd SP!,{LR} ; Store the link register (which is the pre-exception PC)
+ stmfd SP,{SP,LR}^ ; Store user/system mode stack pointer and link register
+ nop ; Required by ARM architecture
+ SUB SP,SP,#0x08 ; Adjust stack pointer
+ stmfd SP!,{R2-R12} ; Store general purpose registers
+
+ ldr R3,[SP,#0x50] ; Read saved R1 from the stack (it was saved by the exception entry routine)
+ ldr R2,[SP,#0x4C] ; Read saved R0 from the stack (it was saved by the exception entry routine)
+ stmfd SP!,{R2-R3} ; Store general purpose registers R0 and R1
+
+ mov R1,SP ; Prepare System Context pointer as an argument for the exception handler
+
+ sub SP,SP,#4 ; Adjust SP to preserve 8-byte alignment
+ blx CommonCExceptionHandler ; Call exception handler
+ add SP,SP,#4 ; Adjust SP back to where we were
+
+ ldr R2,[SP,#0x40] ; Load CPSR from context, in case it has changed
+ MSR SPSR_cxsf,R2 ; Store it back to the SPSR to be restored when exiting this handler
+
+ ldmfd SP!,{R0-R12} ; Restore general purpose registers
+ ldm SP,{SP,LR}^ ; Restore user/system mode stack pointer and link register
+ nop ; Required by ARM architecture
+ add SP,SP,#0x08 ; Adjust stack pointer
+ ldmfd SP!,{LR} ; Restore the link register (which is the pre-exception PC)
+ add SP,SP,#0x1C ; Clear out the remaining stack space
+ movs PC,LR ; Return from exception
+
+ END
+
+
diff --git a/ArmPkg/Drivers/CpuDxe/ArmV6/ExceptionSupport.S b/ArmPkg/Drivers/CpuDxe/ArmV6/ExceptionSupport.S
index 86d2a7135..948ad6994 100644
--- a/ArmPkg/Drivers/CpuDxe/ArmV6/ExceptionSupport.S
+++ b/ArmPkg/Drivers/CpuDxe/ArmV6/ExceptionSupport.S
@@ -1,297 +1,297 @@
-#------------------------------------------------------------------------------
-#
-# Use ARMv6 instruction to operate on a single stack
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-#include <Library/PcdLib.h>
-
-/*
-
-This is the stack constructed by the exception handler (low address to high address)
- # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
- Reg Offset
- === ======
- R0 0x00 # stmfd SP!,{R0-R12}
- R1 0x04
- R2 0x08
- R3 0x0c
- R4 0x10
- R5 0x14
- R6 0x18
- R7 0x1c
- R8 0x20
- R9 0x24
- R10 0x28
- R11 0x2c
- R12 0x30
- SP 0x34 # reserved via adding 0x20 (32) to the SP
- LR 0x38
- PC 0x3c
- CPSR 0x40
- DFSR 0x44
- DFAR 0x48
- IFSR 0x4c
- IFAR 0x50
-
- LR 0x54 # SVC Link register (we need to restore it)
-
- LR 0x58 # pushed by srsfd
- CPSR 0x5c
-
- */
-
-
-GCC_ASM_EXPORT(ExceptionHandlersStart)
-GCC_ASM_EXPORT(ExceptionHandlersEnd)
-GCC_ASM_EXPORT(CommonExceptionEntry)
-GCC_ASM_EXPORT(AsmCommonExceptionEntry)
-GCC_ASM_EXPORT(CommonCExceptionHandler)
-
-.text
-#if !defined(__APPLE__)
-.fpu neon @ makes vpush/vpop assemble
-#endif
-.align 5
-
-
-//
-// This code gets copied to the ARM vector table
-// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
-//
-ASM_PFX(ExceptionHandlersStart):
-
-ASM_PFX(Reset):
- b ASM_PFX(ResetEntry)
-
-ASM_PFX(UndefinedInstruction):
- b ASM_PFX(UndefinedInstructionEntry)
-
-ASM_PFX(SoftwareInterrupt):
- b ASM_PFX(SoftwareInterruptEntry)
-
-ASM_PFX(PrefetchAbort):
- b ASM_PFX(PrefetchAbortEntry)
-
-ASM_PFX(DataAbort):
- b ASM_PFX(DataAbortEntry)
-
-ASM_PFX(ReservedException):
- b ASM_PFX(ReservedExceptionEntry)
-
-ASM_PFX(Irq):
- b ASM_PFX(IrqEntry)
-
-ASM_PFX(Fiq):
- b ASM_PFX(FiqEntry)
-
-ASM_PFX(ResetEntry):
- srsdb #0x13! @ Store return state on SVC stack
- @ We are already in SVC mode
-
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#0 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(UndefinedInstructionEntry):
- sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#1 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(SoftwareInterruptEntry):
- sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
- srsdb #0x13! @ Store return state on SVC stack
- @ We are already in SVC mode
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#2 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(PrefetchAbortEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#3 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(DataAbortEntry):
- sub LR,LR,#8
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#4
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(ReservedExceptionEntry):
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#5
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(IrqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#6 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(FiqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
- @ Since we have already switch to SVC R8_fiq - R12_fiq
- @ never get used or saved
- mov R0,#7 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-//
-// This gets patched by the C code that patches in the vector table
-//
-ASM_PFX(CommonExceptionEntry):
- .word ASM_PFX(AsmCommonExceptionEntry)
-
-ASM_PFX(ExceptionHandlersEnd):
-
-//
-// This code runs from CpuDxe driver loaded address. It is patched into
-// CommonExceptionEntry.
-//
-ASM_PFX(AsmCommonExceptionEntry):
- mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
- str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
-
- mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
- str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
-
- mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
- str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
-
- mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
- str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
-
- ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
- str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
-
- add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R3, R1, #0x1f @ Check CPSR to see if User or System Mode
- cmp R3, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1df))
- cmpne R3, #0x10 @
- stmeqed R2, {lr}^ @ save unbanked lr
- @ else
- stmneed R2, {lr} @ save SVC lr
-
-
- ldr R5, [SP, #0x58] @ PC is the LR pushed by srsfd
- @ Check to see if we have to adjust for Thumb entry
- sub r4, r0, #1 @ if (ExceptionType == 1 || ExceptionType ==2)) {
- cmp r4, #1 @ // UND & SVC have differnt LR adjust for Thumb
- bhi NoAdjustNeeded
-
- tst r1, #0x20 @ if ((CPSR & T)) == T) { // Thumb Mode on entry
- addne R5, R5, #2 @ PC += 2@
- str R5,[SP,#0x58] @ Update LR value pused by srsfd
-
-NoAdjustNeeded:
-
- str R5, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
-
- sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
- str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
-
- @ R0 is ExceptionType
- mov R1,SP @ R1 is SystemContext
-
-#if (FixedPcdGet32(PcdVFPEnabled))
- vpush {d0-d15} @ save vstm registers in case they are used in optimizations
-#endif
-
-/*
-VOID
-EFIAPI
-CommonCExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType, R0
- IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
- )
-
-*/
- blx ASM_PFX(CommonCExceptionHandler) @ Call exception handler
-
-#if (FixedPcdGet32(PcdVFPEnabled))
- vpop {d0-d15}
-#endif
-
- ldr R1, [SP, #0x4c] @ Restore EFI_SYSTEM_CONTEXT_ARM.IFSR
- mcr p15, 0, R1, c5, c0, 1 @ Write IFSR
-
- ldr R1, [SP, #0x44] @ sRestore EFI_SYSTEM_CONTEXT_ARM.DFSR
- mcr p15, 0, R1, c5, c0, 0 @ Write DFSR
-
- ldr R1,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
- str R1,[SP,#0x58] @ Store it back to srsfd stack slot so it can be restored
-
- ldr R1,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
- str R1,[SP,#0x5c] @ Store it back to srsfd stack slot so it can be restored
-
- add R3, SP, #0x54 @ Make R3 point to SVC LR saved on entry
- add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R1, R1, #0x1f @ Check to see if User or System Mode
- cmp R1, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1f))
- cmpne R1, #0x10 @
- ldmeqed R2, {lr}^ @ restore unbanked lr
- @ else
- ldmneed R3, {lr} @ restore SVC lr, via ldmfd SP!, {LR}
-
- ldmfd SP!,{R0-R12} @ Restore general purpose registers
- @ Exception handler can not change SP
-
- add SP,SP,#0x20 @ Clear out the remaining stack space
- ldmfd SP!,{LR} @ restore the link register for this context
- rfefd SP! @ return from exception via srsfd stack slot
-
+#------------------------------------------------------------------------------
+#
+# Use ARMv6 instruction to operate on a single stack
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+#include <Library/PcdLib.h>
+
+/*
+
+This is the stack constructed by the exception handler (low address to high address)
+ # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
+ Reg Offset
+ === ======
+ R0 0x00 # stmfd SP!,{R0-R12}
+ R1 0x04
+ R2 0x08
+ R3 0x0c
+ R4 0x10
+ R5 0x14
+ R6 0x18
+ R7 0x1c
+ R8 0x20
+ R9 0x24
+ R10 0x28
+ R11 0x2c
+ R12 0x30
+ SP 0x34 # reserved via adding 0x20 (32) to the SP
+ LR 0x38
+ PC 0x3c
+ CPSR 0x40
+ DFSR 0x44
+ DFAR 0x48
+ IFSR 0x4c
+ IFAR 0x50
+
+ LR 0x54 # SVC Link register (we need to restore it)
+
+ LR 0x58 # pushed by srsfd
+ CPSR 0x5c
+
+ */
+
+
+GCC_ASM_EXPORT(ExceptionHandlersStart)
+GCC_ASM_EXPORT(ExceptionHandlersEnd)
+GCC_ASM_EXPORT(CommonExceptionEntry)
+GCC_ASM_EXPORT(AsmCommonExceptionEntry)
+GCC_ASM_EXPORT(CommonCExceptionHandler)
+
+.text
+#if !defined(__APPLE__)
+.fpu neon @ makes vpush/vpop assemble
+#endif
+.align 5
+
+
+//
+// This code gets copied to the ARM vector table
+// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
+//
+ASM_PFX(ExceptionHandlersStart):
+
+ASM_PFX(Reset):
+ b ASM_PFX(ResetEntry)
+
+ASM_PFX(UndefinedInstruction):
+ b ASM_PFX(UndefinedInstructionEntry)
+
+ASM_PFX(SoftwareInterrupt):
+ b ASM_PFX(SoftwareInterruptEntry)
+
+ASM_PFX(PrefetchAbort):
+ b ASM_PFX(PrefetchAbortEntry)
+
+ASM_PFX(DataAbort):
+ b ASM_PFX(DataAbortEntry)
+
+ASM_PFX(ReservedException):
+ b ASM_PFX(ReservedExceptionEntry)
+
+ASM_PFX(Irq):
+ b ASM_PFX(IrqEntry)
+
+ASM_PFX(Fiq):
+ b ASM_PFX(FiqEntry)
+
+ASM_PFX(ResetEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ @ We are already in SVC mode
+
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#0 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(UndefinedInstructionEntry):
+ sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#1 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(SoftwareInterruptEntry):
+ sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsdb #0x13! @ Store return state on SVC stack
+ @ We are already in SVC mode
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#2 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(PrefetchAbortEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#3 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(DataAbortEntry):
+ sub LR,LR,#8
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#4
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(ReservedExceptionEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#5
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(IrqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#6 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(FiqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+ @ Since we have already switch to SVC R8_fiq - R12_fiq
+ @ never get used or saved
+ mov R0,#7 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+//
+// This gets patched by the C code that patches in the vector table
+//
+ASM_PFX(CommonExceptionEntry):
+ .word ASM_PFX(AsmCommonExceptionEntry)
+
+ASM_PFX(ExceptionHandlersEnd):
+
+//
+// This code runs from CpuDxe driver loaded address. It is patched into
+// CommonExceptionEntry.
+//
+ASM_PFX(AsmCommonExceptionEntry):
+ mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
+ str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
+
+ mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
+ str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
+
+ mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
+ str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
+
+ mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
+ str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
+
+ ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
+ str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
+
+ add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R3, R1, #0x1f @ Check CPSR to see if User or System Mode
+ cmp R3, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1df))
+ cmpne R3, #0x10 @
+ stmeqed R2, {lr}^ @ save unbanked lr
+ @ else
+ stmneed R2, {lr} @ save SVC lr
+
+
+ ldr R5, [SP, #0x58] @ PC is the LR pushed by srsfd
+ @ Check to see if we have to adjust for Thumb entry
+ sub r4, r0, #1 @ if (ExceptionType == 1 || ExceptionType ==2)) {
+ cmp r4, #1 @ // UND & SVC have differnt LR adjust for Thumb
+ bhi NoAdjustNeeded
+
+ tst r1, #0x20 @ if ((CPSR & T)) == T) { // Thumb Mode on entry
+ addne R5, R5, #2 @ PC += 2@
+ str R5,[SP,#0x58] @ Update LR value pused by srsfd
+
+NoAdjustNeeded:
+
+ str R5, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
+
+ sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
+ str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
+
+ @ R0 is ExceptionType
+ mov R1,SP @ R1 is SystemContext
+
+#if (FixedPcdGet32(PcdVFPEnabled))
+ vpush {d0-d15} @ save vstm registers in case they are used in optimizations
+#endif
+
+/*
+VOID
+EFIAPI
+CommonCExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType, R0
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
+ )
+
+*/
+ blx ASM_PFX(CommonCExceptionHandler) @ Call exception handler
+
+#if (FixedPcdGet32(PcdVFPEnabled))
+ vpop {d0-d15}
+#endif
+
+ ldr R1, [SP, #0x4c] @ Restore EFI_SYSTEM_CONTEXT_ARM.IFSR
+ mcr p15, 0, R1, c5, c0, 1 @ Write IFSR
+
+ ldr R1, [SP, #0x44] @ sRestore EFI_SYSTEM_CONTEXT_ARM.DFSR
+ mcr p15, 0, R1, c5, c0, 0 @ Write DFSR
+
+ ldr R1,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
+ str R1,[SP,#0x58] @ Store it back to srsfd stack slot so it can be restored
+
+ ldr R1,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
+ str R1,[SP,#0x5c] @ Store it back to srsfd stack slot so it can be restored
+
+ add R3, SP, #0x54 @ Make R3 point to SVC LR saved on entry
+ add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R1, R1, #0x1f @ Check to see if User or System Mode
+ cmp R1, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1f))
+ cmpne R1, #0x10 @
+ ldmeqed R2, {lr}^ @ restore unbanked lr
+ @ else
+ ldmneed R3, {lr} @ restore SVC lr, via ldmfd SP!, {LR}
+
+ ldmfd SP!,{R0-R12} @ Restore general purpose registers
+ @ Exception handler can not change SP
+
+ add SP,SP,#0x20 @ Clear out the remaining stack space
+ ldmfd SP!,{LR} @ restore the link register for this context
+ rfefd SP! @ return from exception via srsfd stack slot
+
diff --git a/ArmPkg/Drivers/CpuPei/CpuPei.inf b/ArmPkg/Drivers/CpuPei/CpuPei.inf
index 3d1665aab..ec8b9f5c5 100755
--- a/ArmPkg/Drivers/CpuPei/CpuPei.inf
+++ b/ArmPkg/Drivers/CpuPei/CpuPei.inf
@@ -53,7 +53,7 @@
gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize
gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize
-[FeaturePcd]
+[FeaturePcd]
gEmbeddedTokenSpaceGuid.PcdCacheEnable
[depex]
diff --git a/ArmPkg/Drivers/PL390Gic/PL390GicDxe.c b/ArmPkg/Drivers/PL390Gic/PL390GicDxe.c
index 1a8239e73..31e91f9c3 100644
--- a/ArmPkg/Drivers/PL390Gic/PL390GicDxe.c
+++ b/ArmPkg/Drivers/PL390Gic/PL390GicDxe.c
@@ -1,425 +1,426 @@
-/*++
-
-Copyright (c) 2009, Hewlett-Packard Company. All rights reserved.<BR>
-Portions copyright (c) 2010, Apple Inc. All rights reserved.<BR>
-Portions copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution. The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
-
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-Module Name:
-
- Gic.c
-
-Abstract:
-
- Driver implementing the GIC interrupt controller protocol
-
---*/
-
-#include <PiDxe.h>
-
-#include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-#include <Library/ArmGicLib.h>
-
-#include <Protocol/Cpu.h>
-#include <Protocol/HardwareInterrupt.h>
-
-#define ARM_GIC_DEFAULT_PRIORITY 0x80
-
-extern EFI_HARDWARE_INTERRUPT_PROTOCOL gHardwareInterruptProtocol;
-
-//
-// Notifications
-//
-EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
-
-// Maximum Number of Interrupts
-UINTN mGicNumInterrupts = 0;
-
-HARDWARE_INTERRUPT_HANDLER *gRegisteredInterruptHandlers = NULL;
-
-/**
- Register Handler for the specified interrupt source.
-
- @param This Instance pointer for this protocol
- @param Source Hardware source of the interrupt
- @param Handler Callback for interrupt. NULL to unregister
-
- @retval EFI_SUCCESS Source was updated to support Handler.
- @retval EFI_DEVICE_ERROR Hardware could not be programmed.
-
-**/
-EFI_STATUS
-EFIAPI
-RegisterInterruptSource (
- IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
- IN HARDWARE_INTERRUPT_SOURCE Source,
- IN HARDWARE_INTERRUPT_HANDLER Handler
- )
-{
- if (Source > mGicNumInterrupts) {
- ASSERT(FALSE);
- return EFI_UNSUPPORTED;
- }
-
- if ((Handler == NULL) && (gRegisteredInterruptHandlers[Source] == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
-
- if ((Handler != NULL) && (gRegisteredInterruptHandlers[Source] != NULL)) {
- return EFI_ALREADY_STARTED;
- }
-
- gRegisteredInterruptHandlers[Source] = Handler;
-
- // If the interrupt handler is unregistered then disable the interrupt
- if (NULL == Handler){
- return This->DisableInterruptSource (This, Source);
- } else {
- return This->EnableInterruptSource (This, Source);
- }
-}
-
-/**
- Enable interrupt source Source.
-
- @param This Instance pointer for this protocol
- @param Source Hardware source of the interrupt
-
- @retval EFI_SUCCESS Source interrupt enabled.
- @retval EFI_DEVICE_ERROR Hardware could not be programmed.
-
-**/
-EFI_STATUS
-EFIAPI
-EnableInterruptSource (
- IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
- IN HARDWARE_INTERRUPT_SOURCE Source
- )
-{
- UINT32 RegOffset;
- UINTN RegShift;
-
- if (Source > mGicNumInterrupts) {
- ASSERT(FALSE);
- return EFI_UNSUPPORTED;
- }
-
- // Calculate enable register offset and bit position
- RegOffset = Source / 32;
- RegShift = Source % 32;
-
- // Write set-enable register
- MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDISER + (4*RegOffset), 1 << RegShift);
-
- return EFI_SUCCESS;
-}
-
-/**
- Disable interrupt source Source.
-
- @param This Instance pointer for this protocol
- @param Source Hardware source of the interrupt
-
- @retval EFI_SUCCESS Source interrupt disabled.
- @retval EFI_DEVICE_ERROR Hardware could not be programmed.
-
-**/
-EFI_STATUS
-EFIAPI
-DisableInterruptSource (
- IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
- IN HARDWARE_INTERRUPT_SOURCE Source
- )
-{
- UINT32 RegOffset;
- UINTN RegShift;
-
- if (Source > mGicNumInterrupts) {
- ASSERT(FALSE);
- return EFI_UNSUPPORTED;
- }
-
- // Calculate enable register offset and bit position
- RegOffset = Source / 32;
- RegShift = Source % 32;
-
- // Write set-enable register
- MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDICER + (4*RegOffset), 1 << RegShift);
-
- return EFI_SUCCESS;
-}
-
-/**
- Return current state of interrupt source Source.
-
- @param This Instance pointer for this protocol
- @param Source Hardware source of the interrupt
- @param InterruptState TRUE: source enabled, FALSE: source disabled.
-
- @retval EFI_SUCCESS InterruptState is valid
- @retval EFI_DEVICE_ERROR InterruptState is not valid
-
-**/
-EFI_STATUS
-EFIAPI
-GetInterruptSourceState (
- IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
- IN HARDWARE_INTERRUPT_SOURCE Source,
- IN BOOLEAN *InterruptState
- )
-{
- UINT32 RegOffset;
- UINTN RegShift;
-
- if (Source > mGicNumInterrupts) {
- ASSERT(FALSE);
- return EFI_UNSUPPORTED;
- }
-
- // calculate enable register offset and bit position
- RegOffset = Source / 32;
- RegShift = Source % 32;
-
- if ((MmioRead32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDISER + (4*RegOffset)) & (1<<RegShift)) == 0) {
- *InterruptState = FALSE;
- } else {
- *InterruptState = TRUE;
- }
-
- return EFI_SUCCESS;
-}
-
-/**
- Signal to the hardware that the End Of Intrrupt state
- has been reached.
-
- @param This Instance pointer for this protocol
- @param Source Hardware source of the interrupt
-
- @retval EFI_SUCCESS Source interrupt EOI'ed.
- @retval EFI_DEVICE_ERROR Hardware could not be programmed.
-
-**/
-EFI_STATUS
-EFIAPI
-EndOfInterrupt (
- IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
- IN HARDWARE_INTERRUPT_SOURCE Source
- )
-{
- if (Source > mGicNumInterrupts) {
- ASSERT(FALSE);
- return EFI_UNSUPPORTED;
- }
-
- MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCEIOR, Source);
- return EFI_SUCCESS;
-}
-
-/**
- EFI_CPU_INTERRUPT_HANDLER that is called when a processor interrupt occurs.
-
- @param InterruptType Defines the type of interrupt or exception that
- occurred on the processor.This parameter is processor architecture specific.
- @param SystemContext A pointer to the processor context when
- the interrupt occurred on the processor.
-
- @return None
-
-**/
-VOID
-EFIAPI
-IrqInterruptHandler (
- IN EFI_EXCEPTION_TYPE InterruptType,
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- UINT32 GicInterrupt;
- HARDWARE_INTERRUPT_HANDLER InterruptHandler;
-
- GicInterrupt = MmioRead32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCIAR);
-
- // Special Interrupts (ID1020-ID1023) have an Interrupt ID greater than the number of interrupt (ie: Spurious interrupt).
- if (GicInterrupt >= mGicNumInterrupts) {
- // The special interrupt do not need to be acknowledge
- return;
- }
-
- InterruptHandler = gRegisteredInterruptHandlers[GicInterrupt];
- if (InterruptHandler != NULL) {
- // Call the registered interrupt handler.
- InterruptHandler (GicInterrupt, SystemContext);
- } else {
- DEBUG ((EFI_D_ERROR, "Spurious GIC interrupt: 0x%x\n", GicInterrupt));
- }
-
- EndOfInterrupt (&gHardwareInterruptProtocol, GicInterrupt);
-}
-
-//
-// Making this global saves a few bytes in image size
-//
-EFI_HANDLE gHardwareInterruptHandle = NULL;
-
-//
-// The protocol instance produced by this driver
-//
-EFI_HARDWARE_INTERRUPT_PROTOCOL gHardwareInterruptProtocol = {
- RegisterInterruptSource,
- EnableInterruptSource,
- DisableInterruptSource,
- GetInterruptSourceState,
- EndOfInterrupt
-};
-
-/**
- Shutdown our hardware
-
- DXE Core will disable interrupts and turn off the timer and disable interrupts
- after all the event handlers have run.
-
- @param[in] Event The Event that is being processed
- @param[in] Context Event Context
-**/
-VOID
-EFIAPI
-ExitBootServicesEvent (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- UINTN Index;
-
- // Acknowledge all pending interrupts
- for (Index = 0; Index < mGicNumInterrupts; Index++) {
- DisableInterruptSource (&gHardwareInterruptProtocol, Index);
- }
-
- for (Index = 0; Index < mGicNumInterrupts; Index++) {
- EndOfInterrupt (&gHardwareInterruptProtocol, Index);
- }
-
- // Disable Gic Interface
- MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCICR, 0x0);
- MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCPMR, 0x0);
-
- // Disable Gic Distributor
- MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDDCR, 0x0);
-}
-
-/**
- Initialize the state information for the CPU Architectural Protocol
-
- @param ImageHandle of the loaded driver
- @param SystemTable Pointer to the System Table
-
- @retval EFI_SUCCESS Protocol registered
- @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
- @retval EFI_DEVICE_ERROR Hardware problems
-
-**/
-EFI_STATUS
-InterruptDxeInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- UINTN Index;
- UINT32 RegOffset;
- UINTN RegShift;
- EFI_CPU_ARCH_PROTOCOL *Cpu;
- UINT32 CpuTarget;
-
- // Check PcdGicPrimaryCoreId has been set in case the Primary Core is not the core 0 of Cluster 0
- DEBUG_CODE_BEGIN();
- if ((PcdGet32(PcdArmPrimaryCore) != 0) && (PcdGet32 (PcdGicPrimaryCoreId) == 0)) {
- DEBUG((EFI_D_WARN,"Warning: the PCD PcdGicPrimaryCoreId does not seem to be set up for the configuration.\n"));
- }
- DEBUG_CODE_END();
-
- // Make sure the Interrupt Controller Protocol is not already installed in the system.
- ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gHardwareInterruptProtocolGuid);
-
- mGicNumInterrupts = ArmGicGetMaxNumInterrupts (PcdGet32(PcdGicDistributorBase));
-
- for (Index = 0; Index < mGicNumInterrupts; Index++) {
- DisableInterruptSource (&gHardwareInterruptProtocol, Index);
-
- // Set Priority
- RegOffset = Index / 4;
- RegShift = (Index % 4) * 8;
- MmioAndThenOr32 (
- PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDIPR + (4*RegOffset),
- ~(0xff << RegShift),
- ARM_GIC_DEFAULT_PRIORITY << RegShift
- );
- }
-
- // Configure interrupts for Primary Cpu
- CpuTarget = (1 << PcdGet32 (PcdGicPrimaryCoreId));
- CpuTarget |= (CpuTarget << 24) | (CpuTarget << 16) | (CpuTarget << 8);
- for (Index = 0; Index < (mGicNumInterrupts / 4); Index++) {
- MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDIPTR + (Index*4), CpuTarget);
- }
-
- // Set binary point reg to 0x7 (no preemption)
- MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCBPR, 0x7);
-
- // Set priority mask reg to 0xff to allow all priorities through
- MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCPMR, 0xff);
-
- // Enable gic cpu interface
- MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCICR, 0x1);
-
- // Enable gic distributor
- MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDDCR, 0x1);
-
- // Initialize the array for the Interrupt Handlers
- gRegisteredInterruptHandlers = (HARDWARE_INTERRUPT_HANDLER*)AllocateZeroPool (sizeof(HARDWARE_INTERRUPT_HANDLER) * mGicNumInterrupts);
-
- Status = gBS->InstallMultipleProtocolInterfaces (
- &gHardwareInterruptHandle,
- &gHardwareInterruptProtocolGuid, &gHardwareInterruptProtocol,
- NULL
- );
- ASSERT_EFI_ERROR (Status);
-
- //
- // Get the CPU protocol that this driver requires.
- //
- Status = gBS->LocateProtocol(&gEfiCpuArchProtocolGuid, NULL, (VOID **)&Cpu);
- ASSERT_EFI_ERROR(Status);
-
- //
- // Unregister the default exception handler.
- //
- Status = Cpu->RegisterInterruptHandler(Cpu, EXCEPT_ARM_IRQ, NULL);
- ASSERT_EFI_ERROR(Status);
-
- //
- // Register to receive interrupts
- //
- Status = Cpu->RegisterInterruptHandler(Cpu, EXCEPT_ARM_IRQ, IrqInterruptHandler);
- ASSERT_EFI_ERROR(Status);
-
- // Register for an ExitBootServicesEvent
- Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
- ASSERT_EFI_ERROR (Status);
-
- return Status;
-}
+/*++
+
+Copyright (c) 2009, Hewlett-Packard Company. All rights reserved.<BR>
+Portions copyright (c) 2010, Apple Inc. All rights reserved.<BR>
+Portions copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
+
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+Module Name:
+
+ Gic.c
+
+Abstract:
+
+ Driver implementing the GIC interrupt controller protocol
+
+--*/
+
+#include <PiDxe.h>
+
+#include <Library/ArmLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+#include <Library/ArmGicLib.h>
+
+#include <Protocol/Cpu.h>
+#include <Protocol/HardwareInterrupt.h>
+
+#define ARM_GIC_DEFAULT_PRIORITY 0x80
+
+extern EFI_HARDWARE_INTERRUPT_PROTOCOL gHardwareInterruptProtocol;
+
+//
+// Notifications
+//
+EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
+
+// Maximum Number of Interrupts
+UINTN mGicNumInterrupts = 0;
+
+HARDWARE_INTERRUPT_HANDLER *gRegisteredInterruptHandlers = NULL;
+
+/**
+ Register Handler for the specified interrupt source.
+
+ @param This Instance pointer for this protocol
+ @param Source Hardware source of the interrupt
+ @param Handler Callback for interrupt. NULL to unregister
+
+ @retval EFI_SUCCESS Source was updated to support Handler.
+ @retval EFI_DEVICE_ERROR Hardware could not be programmed.
+
+**/
+EFI_STATUS
+EFIAPI
+RegisterInterruptSource (
+ IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
+ IN HARDWARE_INTERRUPT_SOURCE Source,
+ IN HARDWARE_INTERRUPT_HANDLER Handler
+ )
+{
+ if (Source > mGicNumInterrupts) {
+ ASSERT(FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ if ((Handler == NULL) && (gRegisteredInterruptHandlers[Source] == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ((Handler != NULL) && (gRegisteredInterruptHandlers[Source] != NULL)) {
+ return EFI_ALREADY_STARTED;
+ }
+
+ gRegisteredInterruptHandlers[Source] = Handler;
+
+ // If the interrupt handler is unregistered then disable the interrupt
+ if (NULL == Handler){
+ return This->DisableInterruptSource (This, Source);
+ } else {
+ return This->EnableInterruptSource (This, Source);
+ }
+}
+
+/**
+ Enable interrupt source Source.
+
+ @param This Instance pointer for this protocol
+ @param Source Hardware source of the interrupt
+
+ @retval EFI_SUCCESS Source interrupt enabled.
+ @retval EFI_DEVICE_ERROR Hardware could not be programmed.
+
+**/
+EFI_STATUS
+EFIAPI
+EnableInterruptSource (
+ IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
+ IN HARDWARE_INTERRUPT_SOURCE Source
+ )
+{
+ UINT32 RegOffset;
+ UINTN RegShift;
+
+ if (Source > mGicNumInterrupts) {
+ ASSERT(FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ // Calculate enable register offset and bit position
+ RegOffset = Source / 32;
+ RegShift = Source % 32;
+
+ // Write set-enable register
+ MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDISER + (4*RegOffset), 1 << RegShift);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Disable interrupt source Source.
+
+ @param This Instance pointer for this protocol
+ @param Source Hardware source of the interrupt
+
+ @retval EFI_SUCCESS Source interrupt disabled.
+ @retval EFI_DEVICE_ERROR Hardware could not be programmed.
+
+**/
+EFI_STATUS
+EFIAPI
+DisableInterruptSource (
+ IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
+ IN HARDWARE_INTERRUPT_SOURCE Source
+ )
+{
+ UINT32 RegOffset;
+ UINTN RegShift;
+
+ if (Source > mGicNumInterrupts) {
+ ASSERT(FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ // Calculate enable register offset and bit position
+ RegOffset = Source / 32;
+ RegShift = Source % 32;
+
+ // Write set-enable register
+ MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDICER + (4*RegOffset), 1 << RegShift);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Return current state of interrupt source Source.
+
+ @param This Instance pointer for this protocol
+ @param Source Hardware source of the interrupt
+ @param InterruptState TRUE: source enabled, FALSE: source disabled.
+
+ @retval EFI_SUCCESS InterruptState is valid
+ @retval EFI_DEVICE_ERROR InterruptState is not valid
+
+**/
+EFI_STATUS
+EFIAPI
+GetInterruptSourceState (
+ IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
+ IN HARDWARE_INTERRUPT_SOURCE Source,
+ IN BOOLEAN *InterruptState
+ )
+{
+ UINT32 RegOffset;
+ UINTN RegShift;
+
+ if (Source > mGicNumInterrupts) {
+ ASSERT(FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ // calculate enable register offset and bit position
+ RegOffset = Source / 32;
+ RegShift = Source % 32;
+
+ if ((MmioRead32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDISER + (4*RegOffset)) & (1<<RegShift)) == 0) {
+ *InterruptState = FALSE;
+ } else {
+ *InterruptState = TRUE;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Signal to the hardware that the End Of Intrrupt state
+ has been reached.
+
+ @param This Instance pointer for this protocol
+ @param Source Hardware source of the interrupt
+
+ @retval EFI_SUCCESS Source interrupt EOI'ed.
+ @retval EFI_DEVICE_ERROR Hardware could not be programmed.
+
+**/
+EFI_STATUS
+EFIAPI
+EndOfInterrupt (
+ IN EFI_HARDWARE_INTERRUPT_PROTOCOL *This,
+ IN HARDWARE_INTERRUPT_SOURCE Source
+ )
+{
+ if (Source > mGicNumInterrupts) {
+ ASSERT(FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCEIOR, Source);
+ return EFI_SUCCESS;
+}
+
+/**
+ EFI_CPU_INTERRUPT_HANDLER that is called when a processor interrupt occurs.
+
+ @param InterruptType Defines the type of interrupt or exception that
+ occurred on the processor.This parameter is processor architecture specific.
+ @param SystemContext A pointer to the processor context when
+ the interrupt occurred on the processor.
+
+ @return None
+
+**/
+VOID
+EFIAPI
+IrqInterruptHandler (
+ IN EFI_EXCEPTION_TYPE InterruptType,
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ UINT32 GicInterrupt;
+ HARDWARE_INTERRUPT_HANDLER InterruptHandler;
+
+ GicInterrupt = MmioRead32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCIAR);
+
+ // Special Interrupts (ID1020-ID1023) have an Interrupt ID greater than the number of interrupt (ie: Spurious interrupt).
+ if (GicInterrupt >= mGicNumInterrupts) {
+ // The special interrupt do not need to be acknowledge
+ return;
+ }
+
+ InterruptHandler = gRegisteredInterruptHandlers[GicInterrupt];
+ if (InterruptHandler != NULL) {
+ // Call the registered interrupt handler.
+ InterruptHandler (GicInterrupt, SystemContext);
+ } else {
+ DEBUG ((EFI_D_ERROR, "Spurious GIC interrupt: 0x%x\n", GicInterrupt));
+ }
+
+ EndOfInterrupt (&gHardwareInterruptProtocol, GicInterrupt);
+}
+
+//
+// Making this global saves a few bytes in image size
+//
+EFI_HANDLE gHardwareInterruptHandle = NULL;
+
+//
+// The protocol instance produced by this driver
+//
+EFI_HARDWARE_INTERRUPT_PROTOCOL gHardwareInterruptProtocol = {
+ RegisterInterruptSource,
+ EnableInterruptSource,
+ DisableInterruptSource,
+ GetInterruptSourceState,
+ EndOfInterrupt
+};
+
+/**
+ Shutdown our hardware
+
+ DXE Core will disable interrupts and turn off the timer and disable interrupts
+ after all the event handlers have run.
+
+ @param[in] Event The Event that is being processed
+ @param[in] Context Event Context
+**/
+VOID
+EFIAPI
+ExitBootServicesEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ UINTN Index;
+
+ // Acknowledge all pending interrupts
+ for (Index = 0; Index < mGicNumInterrupts; Index++) {
+ DisableInterruptSource (&gHardwareInterruptProtocol, Index);
+ }
+
+ for (Index = 0; Index < mGicNumInterrupts; Index++) {
+ EndOfInterrupt (&gHardwareInterruptProtocol, Index);
+ }
+
+ // Disable Gic Interface
+ MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCICR, 0x0);
+ MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCPMR, 0x0);
+
+ // Disable Gic Distributor
+ MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDDCR, 0x0);
+}
+
+/**
+ Initialize the state information for the CPU Architectural Protocol
+
+ @param ImageHandle of the loaded driver
+ @param SystemTable Pointer to the System Table
+
+ @retval EFI_SUCCESS Protocol registered
+ @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
+ @retval EFI_DEVICE_ERROR Hardware problems
+
+**/
+EFI_STATUS
+InterruptDxeInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ UINT32 RegOffset;
+ UINTN RegShift;
+ EFI_CPU_ARCH_PROTOCOL *Cpu;
+ UINT32 CpuTarget;
+
+ // Check PcdGicPrimaryCoreId has been set in case the Primary Core is not the core 0 of Cluster 0
+ DEBUG_CODE_BEGIN();
+ if ((PcdGet32(PcdArmPrimaryCore) != 0) && (PcdGet32 (PcdGicPrimaryCoreId) == 0)) {
+ DEBUG((EFI_D_WARN,"Warning: the PCD PcdGicPrimaryCoreId does not seem to be set up for the configuration.\n"));
+ }
+ DEBUG_CODE_END();
+
+ // Make sure the Interrupt Controller Protocol is not already installed in the system.
+ ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gHardwareInterruptProtocolGuid);
+
+ mGicNumInterrupts = ArmGicGetMaxNumInterrupts (PcdGet32(PcdGicDistributorBase));
+
+ for (Index = 0; Index < mGicNumInterrupts; Index++) {
+ DisableInterruptSource (&gHardwareInterruptProtocol, Index);
+
+ // Set Priority
+ RegOffset = Index / 4;
+ RegShift = (Index % 4) * 8;
+ MmioAndThenOr32 (
+ PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDIPR + (4*RegOffset),
+ ~(0xff << RegShift),
+ ARM_GIC_DEFAULT_PRIORITY << RegShift
+ );
+ }
+
+ // Configure interrupts for Primary Cpu
+ CpuTarget = (1 << PcdGet32 (PcdGicPrimaryCoreId));
+ CpuTarget |= (CpuTarget << 24) | (CpuTarget << 16) | (CpuTarget << 8);
+ for (Index = 0; Index < (mGicNumInterrupts / 4); Index++) {
+ MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDIPTR + (Index*4), CpuTarget);
+ }
+
+ // Set binary point reg to 0x7 (no preemption)
+ MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCBPR, 0x7);
+
+ // Set priority mask reg to 0xff to allow all priorities through
+ MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCPMR, 0xff);
+
+ // Enable gic cpu interface
+ MmioWrite32 (PcdGet32(PcdGicInterruptInterfaceBase) + ARM_GIC_ICCICR, 0x1);
+
+ // Enable gic distributor
+ MmioWrite32 (PcdGet32(PcdGicDistributorBase) + ARM_GIC_ICDDCR, 0x1);
+
+ // Initialize the array for the Interrupt Handlers
+ gRegisteredInterruptHandlers = (HARDWARE_INTERRUPT_HANDLER*)AllocateZeroPool (sizeof(HARDWARE_INTERRUPT_HANDLER) * mGicNumInterrupts);
+
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &gHardwareInterruptHandle,
+ &gHardwareInterruptProtocolGuid, &gHardwareInterruptProtocol,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Get the CPU protocol that this driver requires.
+ //
+ Status = gBS->LocateProtocol(&gEfiCpuArchProtocolGuid, NULL, (VOID **)&Cpu);
+ ASSERT_EFI_ERROR(Status);
+
+ //
+ // Unregister the default exception handler.
+ //
+ Status = Cpu->RegisterInterruptHandler(Cpu, ARM_ARCH_EXCEPTION_IRQ, NULL);
+ ASSERT_EFI_ERROR(Status);
+
+ //
+ // Register to receive interrupts
+ //
+ Status = Cpu->RegisterInterruptHandler(Cpu, ARM_ARCH_EXCEPTION_IRQ, IrqInterruptHandler);
+ ASSERT_EFI_ERROR(Status);
+
+ // Register for an ExitBootServicesEvent
+ Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
diff --git a/ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf b/ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
index b63216ee9..422fd414b 100644
--- a/ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
+++ b/ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
@@ -1,57 +1,57 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# Copyright (c) 2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = PL390GicDxe
- FILE_GUID = DE371F7C-DEC4-4D21-ADF1-593ABCC15882
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = InterruptDxeInitialize
-
-
-[Sources.common]
- PL390Gic.c
- PL390GicDxe.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
-
-[LibraryClasses]
- BaseLib
- UefiLib
- UefiBootServicesTableLib
- DebugLib
- PrintLib
- MemoryAllocationLib
- UefiDriverEntryPoint
- IoLib
-
-[Protocols]
- gHardwareInterruptProtocolGuid
- gEfiCpuArchProtocolGuid
-
-[FixedPcd.common]
- gArmTokenSpaceGuid.PcdGicDistributorBase
- gArmTokenSpaceGuid.PcdGicInterruptInterfaceBase
-
- gArmTokenSpaceGuid.PcdArmPrimaryCore
- gArmTokenSpaceGuid.PcdGicPrimaryCoreId
-
-[Depex]
- gEfiCpuArchProtocolGuid
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# Copyright (c) 2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PL390GicDxe
+ FILE_GUID = DE371F7C-DEC4-4D21-ADF1-593ABCC15882
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = InterruptDxeInitialize
+
+
+[Sources.common]
+ PL390Gic.c
+ PL390GicDxe.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ UefiLib
+ UefiBootServicesTableLib
+ DebugLib
+ PrintLib
+ MemoryAllocationLib
+ UefiDriverEntryPoint
+ IoLib
+
+[Protocols]
+ gHardwareInterruptProtocolGuid
+ gEfiCpuArchProtocolGuid
+
+[FixedPcd.common]
+ gArmTokenSpaceGuid.PcdGicDistributorBase
+ gArmTokenSpaceGuid.PcdGicInterruptInterfaceBase
+
+ gArmTokenSpaceGuid.PcdArmPrimaryCore
+ gArmTokenSpaceGuid.PcdGicPrimaryCoreId
+
+[Depex]
+ gEfiCpuArchProtocolGuid
diff --git a/ArmPkg/Drivers/PL390Gic/PL390GicLib.inf b/ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
index 4eb6ffbdb..d0cac0203 100644
--- a/ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
+++ b/ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
@@ -23,6 +23,9 @@
PL390Gic.c
PL390GicNonSec.c
+[LibraryClasses]
+ IoLib
+
[Packages]
ArmPkg/ArmPkg.dec
MdePkg/MdePkg.dec
diff --git a/ArmPkg/Drivers/TimerDxe/TimerDxe.c b/ArmPkg/Drivers/TimerDxe/TimerDxe.c
index 50de7668e..cbc34e8e4 100644
--- a/ArmPkg/Drivers/TimerDxe/TimerDxe.c
+++ b/ArmPkg/Drivers/TimerDxe/TimerDxe.c
@@ -1,380 +1,380 @@
-/** @file
- Timer Architecture Protocol driver of the ARM flavor
-
- Copyright (c) 2011 ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-
-#include <PiDxe.h>
-
-#include <Library/ArmLib.h>
-#include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-#include <Library/ArmV7ArchTimerLib.h>
-
-#include <Protocol/Timer.h>
-#include <Protocol/HardwareInterrupt.h>
-
-// The notification function to call on every timer interrupt.
-EFI_TIMER_NOTIFY mTimerNotifyFunction = (EFI_TIMER_NOTIFY)NULL;
-EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
-
-// The current period of the timer interrupt
-UINT64 mTimerPeriod = 0;
-
-// Cached copy of the Hardware Interrupt protocol instance
-EFI_HARDWARE_INTERRUPT_PROTOCOL *gInterrupt = NULL;
-
-/**
- This function registers the handler NotifyFunction so it is called every time
- the timer interrupt fires. It also passes the amount of time since the last
- handler call to the NotifyFunction. If NotifyFunction is NULL, then the
- handler is unregistered. If the handler is registered, then EFI_SUCCESS is
- returned. If the CPU does not support registering a timer interrupt handler,
- then EFI_UNSUPPORTED is returned. If an attempt is made to register a handler
- when a handler is already registered, then EFI_ALREADY_STARTED is returned.
- If an attempt is made to unregister a handler when a handler is not registered,
- then EFI_INVALID_PARAMETER is returned. If an error occurs attempting to
- register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
- is returned.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param NotifyFunction The function to call when a timer interrupt fires. This
- function executes at TPL_HIGH_LEVEL. The DXE Core will
- register a handler for the timer interrupt, so it can know
- how much time has passed. This information is used to
- signal timer based events. NULL will unregister the handler.
- @retval EFI_SUCCESS The timer handler was registered.
- @retval EFI_UNSUPPORTED The platform does not support timer interrupts.
- @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
- registered.
- @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
- previously registered.
- @retval EFI_DEVICE_ERROR The timer handler could not be registered.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverRegisterHandler (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- IN EFI_TIMER_NOTIFY NotifyFunction
- )
-{
- if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
-
- if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
- return EFI_ALREADY_STARTED;
- }
-
- mTimerNotifyFunction = NotifyFunction;
-
- return EFI_SUCCESS;
-}
-
-/**
- Disable the timer
-**/
-VOID
-EFIAPI
-ExitBootServicesEvent (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- ArmArchTimerDisableTimer ();
-}
-
-/**
-
- This function adjusts the period of timer interrupts to the value specified
- by TimerPeriod. If the timer period is updated, then the selected timer
- period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
- If an error occurs while attempting to update the timer period, then the
- timer hardware will be put back in its state prior to this call, and
- EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
- is disabled. This is not the same as disabling the CPU's interrupts.
- Instead, it must either turn off the timer hardware, or it must adjust the
- interrupt controller so that a CPU interrupt is not generated when the timer
- interrupt fires.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is
- returned. If the timer is programmable, then the timer period
- will be rounded up to the nearest timer period that is supported
- by the timer hardware. If TimerPeriod is set to 0, then the
- timer interrupts will be disabled.
-
-
- @retval EFI_SUCCESS The timer period was changed.
- @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
- @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverSetTimerPeriod (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- IN UINT64 TimerPeriod
- )
-{
- UINT64 TimerTicks;
-
- // Always disable the timer
- ArmArchTimerDisableTimer ();
-
- if (TimerPeriod != 0) {
- // Convert TimerPeriod to micro sec units
- TimerTicks = DivU64x32 (TimerPeriod, 10);
-
- TimerTicks = MultU64x32 (TimerTicks, (PcdGet32(PcdArmArchTimerFreqInHz)/1000000));
-
- ArmArchTimerSetTimerVal((UINTN)TimerTicks);
-
- // Enable the timer
- ArmArchTimerEnableTimer ();
- }
-
- // Save the new timer period
- mTimerPeriod = TimerPeriod;
- return EFI_SUCCESS;
-}
-
-/**
- This function retrieves the period of timer interrupts in 100 ns units,
- returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
- is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
- returned, then the timer is currently disabled.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
- 0 is returned, then the timer is currently disabled.
-
-
- @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
- @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverGetTimerPeriod (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- OUT UINT64 *TimerPeriod
- )
-{
- if (TimerPeriod == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- *TimerPeriod = mTimerPeriod;
- return EFI_SUCCESS;
-}
-
-/**
- This function generates a soft timer interrupt. If the platform does not support soft
- timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
- If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
- service, then a soft timer interrupt will be generated. If the timer interrupt is
- enabled when this service is called, then the registered handler will be invoked. The
- registered handler should not be able to distinguish a hardware-generated timer
- interrupt from a software-generated timer interrupt.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
-
- @retval EFI_SUCCESS The soft timer interrupt was generated.
- @retval EFI_UNSUPPORTED The platform does not support the generation of soft timer interrupts.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverGenerateSoftInterrupt (
- IN EFI_TIMER_ARCH_PROTOCOL *This
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- Interface structure for the Timer Architectural Protocol.
-
- @par Protocol Description:
- This protocol provides the services to initialize a periodic timer
- interrupt, and to register a handler that is called each time the timer
- interrupt fires. It may also provide a service to adjust the rate of the
- periodic timer interrupt. When a timer interrupt occurs, the handler is
- passed the amount of time that has passed since the previous timer
- interrupt.
-
- @param RegisterHandler
- Registers a handler that will be called each time the
- timer interrupt fires. TimerPeriod defines the minimum
- time between timer interrupts, so TimerPeriod will also
- be the minimum time between calls to the registered
- handler.
-
- @param SetTimerPeriod
- Sets the period of the timer interrupt in 100 nS units.
- This function is optional, and may return EFI_UNSUPPORTED.
- If this function is supported, then the timer period will
- be rounded up to the nearest supported timer period.
-
-
- @param GetTimerPeriod
- Retrieves the period of the timer interrupt in 100 nS units.
-
- @param GenerateSoftInterrupt
- Generates a soft timer interrupt that simulates the firing of
- the timer interrupt. This service can be used to invoke the registered handler if the timer interrupt has been masked for
- a period of time.
-
-**/
-EFI_TIMER_ARCH_PROTOCOL gTimer = {
- TimerDriverRegisterHandler,
- TimerDriverSetTimerPeriod,
- TimerDriverGetTimerPeriod,
- TimerDriverGenerateSoftInterrupt
-};
-
-/**
-
- C Interrupt Handler called in the interrupt context when Source interrupt is active.
-
-
- @param Source Source of the interrupt. Hardware routing off a specific platform defines
- what source means.
-
- @param SystemContext Pointer to system register context. Mostly used by debuggers and will
- update the system context after the return from the interrupt if
- modified. Don't change these values unless you know what you are doing
-
-**/
-VOID
-EFIAPI
-TimerInterruptHandler (
- IN HARDWARE_INTERRUPT_SOURCE Source,
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- EFI_TPL OriginalTPL;
-
- //
- // DXE core uses this callback for the EFI timer tick. The DXE core uses locks
- // that raise to TPL_HIGH and then restore back to current level. Thus we need
- // to make sure TPL level is set to TPL_HIGH while we are handling the timer tick.
- //
- OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-
- // Check if the timer interrupt is active
- if ((ArmArchTimerGetTimerCtrlReg () ) & ARM_ARCH_TIMER_ISTATUS) {
-
- // Signal end of interrupt early to help avoid losing subsequent ticks from long duration handlers
- gInterrupt->EndOfInterrupt (gInterrupt, Source);
-
- if (mTimerNotifyFunction) {
- mTimerNotifyFunction (mTimerPeriod);
- }
-
- // Reload the Timer
- TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod));
- }
-
- // Enable timer interrupts
- gInterrupt->EnableInterruptSource (gInterrupt, Source);
-
- gBS->RestoreTPL (OriginalTPL);
-}
-
-
-/**
- Initialize the state information for the Timer Architectural Protocol and
- the Timer Debug support protocol that allows the debugger to break into a
- running program.
-
- @param ImageHandle of the loaded driver
- @param SystemTable Pointer to the System Table
-
- @retval EFI_SUCCESS Protocol registered
- @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
- @retval EFI_DEVICE_ERROR Hardware problems
-
-**/
-EFI_STATUS
-EFIAPI
-TimerInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_HANDLE Handle = NULL;
- EFI_STATUS Status;
- UINTN TimerCtrlReg;
-
- if (ArmIsArchTimerImplemented () == 0) {
- DEBUG ((EFI_D_ERROR, "ARM Architectural Timer is not available in the CPU, hence cann't use this Driver \n"));
- ASSERT (0);
- }
-
- // Find the interrupt controller protocol. ASSERT if not found.
- Status = gBS->LocateProtocol (&gHardwareInterruptProtocolGuid, NULL, (VOID **)&gInterrupt);
- ASSERT_EFI_ERROR (Status);
-
- // Disable the timer
- Status = TimerDriverSetTimerPeriod (&gTimer, 0);
- ASSERT_EFI_ERROR (Status);
-
- // Install secure and Non-secure interrupt handlers
- // Note: Because it is not possible to determine the security state of the
- // CPU dynamically, we just install interrupt handler for both sec and non-sec
- // timer PPI
- Status = gInterrupt->RegisterInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerSecIntrNum), TimerInterruptHandler);
- ASSERT_EFI_ERROR (Status);
-
- Status = gInterrupt->RegisterInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerIntrNum), TimerInterruptHandler);
- ASSERT_EFI_ERROR (Status);
-
- // Unmask timer interrupts
- TimerCtrlReg = ArmArchTimerGetTimerCtrlReg ();
- TimerCtrlReg &= ~ARM_ARCH_TIMER_IMASK;
- ArmArchTimerSetTimerCtrlReg (TimerCtrlReg);
-
- // Set up default timer
- Status = TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod)); // TIMER_DEFAULT_PERIOD
- ASSERT_EFI_ERROR (Status);
-
- // Install the Timer Architectural Protocol onto a new handle
- Status = gBS->InstallMultipleProtocolInterfaces(
- &Handle,
- &gEfiTimerArchProtocolGuid, &gTimer,
- NULL
- );
- ASSERT_EFI_ERROR(Status);
-
- // enable Secure timer interrupts
- Status = gInterrupt->EnableInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerSecIntrNum));
-
- // enable NonSecure timer interrupts
- Status = gInterrupt->EnableInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerIntrNum));
-
- // Register for an ExitBootServicesEvent
- Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
- ASSERT_EFI_ERROR (Status);
-
- return Status;
-}
+/** @file
+ Timer Architecture Protocol driver of the ARM flavor
+
+ Copyright (c) 2011 ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+
+#include <PiDxe.h>
+
+#include <Library/ArmLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+#include <Library/ArmV7ArchTimerLib.h>
+
+#include <Protocol/Timer.h>
+#include <Protocol/HardwareInterrupt.h>
+
+// The notification function to call on every timer interrupt.
+EFI_TIMER_NOTIFY mTimerNotifyFunction = (EFI_TIMER_NOTIFY)NULL;
+EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
+
+// The current period of the timer interrupt
+UINT64 mTimerPeriod = 0;
+
+// Cached copy of the Hardware Interrupt protocol instance
+EFI_HARDWARE_INTERRUPT_PROTOCOL *gInterrupt = NULL;
+
+/**
+ This function registers the handler NotifyFunction so it is called every time
+ the timer interrupt fires. It also passes the amount of time since the last
+ handler call to the NotifyFunction. If NotifyFunction is NULL, then the
+ handler is unregistered. If the handler is registered, then EFI_SUCCESS is
+ returned. If the CPU does not support registering a timer interrupt handler,
+ then EFI_UNSUPPORTED is returned. If an attempt is made to register a handler
+ when a handler is already registered, then EFI_ALREADY_STARTED is returned.
+ If an attempt is made to unregister a handler when a handler is not registered,
+ then EFI_INVALID_PARAMETER is returned. If an error occurs attempting to
+ register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
+ is returned.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param NotifyFunction The function to call when a timer interrupt fires. This
+ function executes at TPL_HIGH_LEVEL. The DXE Core will
+ register a handler for the timer interrupt, so it can know
+ how much time has passed. This information is used to
+ signal timer based events. NULL will unregister the handler.
+ @retval EFI_SUCCESS The timer handler was registered.
+ @retval EFI_UNSUPPORTED The platform does not support timer interrupts.
+ @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
+ registered.
+ @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
+ previously registered.
+ @retval EFI_DEVICE_ERROR The timer handler could not be registered.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverRegisterHandler (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ IN EFI_TIMER_NOTIFY NotifyFunction
+ )
+{
+ if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
+ return EFI_ALREADY_STARTED;
+ }
+
+ mTimerNotifyFunction = NotifyFunction;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Disable the timer
+**/
+VOID
+EFIAPI
+ExitBootServicesEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ ArmArchTimerDisableTimer ();
+}
+
+/**
+
+ This function adjusts the period of timer interrupts to the value specified
+ by TimerPeriod. If the timer period is updated, then the selected timer
+ period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+ If an error occurs while attempting to update the timer period, then the
+ timer hardware will be put back in its state prior to this call, and
+ EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
+ is disabled. This is not the same as disabling the CPU's interrupts.
+ Instead, it must either turn off the timer hardware, or it must adjust the
+ interrupt controller so that a CPU interrupt is not generated when the timer
+ interrupt fires.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is
+ returned. If the timer is programmable, then the timer period
+ will be rounded up to the nearest timer period that is supported
+ by the timer hardware. If TimerPeriod is set to 0, then the
+ timer interrupts will be disabled.
+
+
+ @retval EFI_SUCCESS The timer period was changed.
+ @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
+ @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverSetTimerPeriod (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ IN UINT64 TimerPeriod
+ )
+{
+ UINT64 TimerTicks;
+
+ // Always disable the timer
+ ArmArchTimerDisableTimer ();
+
+ if (TimerPeriod != 0) {
+ // Convert TimerPeriod to micro sec units
+ TimerTicks = DivU64x32 (TimerPeriod, 10);
+
+ TimerTicks = MultU64x32 (TimerTicks, (PcdGet32(PcdArmArchTimerFreqInHz)/1000000));
+
+ ArmArchTimerSetTimerVal((UINTN)TimerTicks);
+
+ // Enable the timer
+ ArmArchTimerEnableTimer ();
+ }
+
+ // Save the new timer period
+ mTimerPeriod = TimerPeriod;
+ return EFI_SUCCESS;
+}
+
+/**
+ This function retrieves the period of timer interrupts in 100 ns units,
+ returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
+ is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
+ returned, then the timer is currently disabled.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
+ 0 is returned, then the timer is currently disabled.
+
+
+ @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
+ @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGetTimerPeriod (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ OUT UINT64 *TimerPeriod
+ )
+{
+ if (TimerPeriod == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *TimerPeriod = mTimerPeriod;
+ return EFI_SUCCESS;
+}
+
+/**
+ This function generates a soft timer interrupt. If the platform does not support soft
+ timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
+ If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
+ service, then a soft timer interrupt will be generated. If the timer interrupt is
+ enabled when this service is called, then the registered handler will be invoked. The
+ registered handler should not be able to distinguish a hardware-generated timer
+ interrupt from a software-generated timer interrupt.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+
+ @retval EFI_SUCCESS The soft timer interrupt was generated.
+ @retval EFI_UNSUPPORTED The platform does not support the generation of soft timer interrupts.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGenerateSoftInterrupt (
+ IN EFI_TIMER_ARCH_PROTOCOL *This
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Interface structure for the Timer Architectural Protocol.
+
+ @par Protocol Description:
+ This protocol provides the services to initialize a periodic timer
+ interrupt, and to register a handler that is called each time the timer
+ interrupt fires. It may also provide a service to adjust the rate of the
+ periodic timer interrupt. When a timer interrupt occurs, the handler is
+ passed the amount of time that has passed since the previous timer
+ interrupt.
+
+ @param RegisterHandler
+ Registers a handler that will be called each time the
+ timer interrupt fires. TimerPeriod defines the minimum
+ time between timer interrupts, so TimerPeriod will also
+ be the minimum time between calls to the registered
+ handler.
+
+ @param SetTimerPeriod
+ Sets the period of the timer interrupt in 100 nS units.
+ This function is optional, and may return EFI_UNSUPPORTED.
+ If this function is supported, then the timer period will
+ be rounded up to the nearest supported timer period.
+
+
+ @param GetTimerPeriod
+ Retrieves the period of the timer interrupt in 100 nS units.
+
+ @param GenerateSoftInterrupt
+ Generates a soft timer interrupt that simulates the firing of
+ the timer interrupt. This service can be used to invoke the registered handler if the timer interrupt has been masked for
+ a period of time.
+
+**/
+EFI_TIMER_ARCH_PROTOCOL gTimer = {
+ TimerDriverRegisterHandler,
+ TimerDriverSetTimerPeriod,
+ TimerDriverGetTimerPeriod,
+ TimerDriverGenerateSoftInterrupt
+};
+
+/**
+
+ C Interrupt Handler called in the interrupt context when Source interrupt is active.
+
+
+ @param Source Source of the interrupt. Hardware routing off a specific platform defines
+ what source means.
+
+ @param SystemContext Pointer to system register context. Mostly used by debuggers and will
+ update the system context after the return from the interrupt if
+ modified. Don't change these values unless you know what you are doing
+
+**/
+VOID
+EFIAPI
+TimerInterruptHandler (
+ IN HARDWARE_INTERRUPT_SOURCE Source,
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ EFI_TPL OriginalTPL;
+
+ //
+ // DXE core uses this callback for the EFI timer tick. The DXE core uses locks
+ // that raise to TPL_HIGH and then restore back to current level. Thus we need
+ // to make sure TPL level is set to TPL_HIGH while we are handling the timer tick.
+ //
+ OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ // Check if the timer interrupt is active
+ if ((ArmArchTimerGetTimerCtrlReg () ) & ARM_ARCH_TIMER_ISTATUS) {
+
+ // Signal end of interrupt early to help avoid losing subsequent ticks from long duration handlers
+ gInterrupt->EndOfInterrupt (gInterrupt, Source);
+
+ if (mTimerNotifyFunction) {
+ mTimerNotifyFunction (mTimerPeriod);
+ }
+
+ // Reload the Timer
+ TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod));
+ }
+
+ // Enable timer interrupts
+ gInterrupt->EnableInterruptSource (gInterrupt, Source);
+
+ gBS->RestoreTPL (OriginalTPL);
+}
+
+
+/**
+ Initialize the state information for the Timer Architectural Protocol and
+ the Timer Debug support protocol that allows the debugger to break into a
+ running program.
+
+ @param ImageHandle of the loaded driver
+ @param SystemTable Pointer to the System Table
+
+ @retval EFI_SUCCESS Protocol registered
+ @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
+ @retval EFI_DEVICE_ERROR Hardware problems
+
+**/
+EFI_STATUS
+EFIAPI
+TimerInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_HANDLE Handle = NULL;
+ EFI_STATUS Status;
+ UINTN TimerCtrlReg;
+
+ if (ArmIsArchTimerImplemented () == 0) {
+ DEBUG ((EFI_D_ERROR, "ARM Architectural Timer is not available in the CPU, hence cann't use this Driver \n"));
+ ASSERT (0);
+ }
+
+ // Find the interrupt controller protocol. ASSERT if not found.
+ Status = gBS->LocateProtocol (&gHardwareInterruptProtocolGuid, NULL, (VOID **)&gInterrupt);
+ ASSERT_EFI_ERROR (Status);
+
+ // Disable the timer
+ Status = TimerDriverSetTimerPeriod (&gTimer, 0);
+ ASSERT_EFI_ERROR (Status);
+
+ // Install secure and Non-secure interrupt handlers
+ // Note: Because it is not possible to determine the security state of the
+ // CPU dynamically, we just install interrupt handler for both sec and non-sec
+ // timer PPI
+ Status = gInterrupt->RegisterInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerSecIntrNum), TimerInterruptHandler);
+ ASSERT_EFI_ERROR (Status);
+
+ Status = gInterrupt->RegisterInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerIntrNum), TimerInterruptHandler);
+ ASSERT_EFI_ERROR (Status);
+
+ // Unmask timer interrupts
+ TimerCtrlReg = ArmArchTimerGetTimerCtrlReg ();
+ TimerCtrlReg &= ~ARM_ARCH_TIMER_IMASK;
+ ArmArchTimerSetTimerCtrlReg (TimerCtrlReg);
+
+ // Set up default timer
+ Status = TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod)); // TIMER_DEFAULT_PERIOD
+ ASSERT_EFI_ERROR (Status);
+
+ // Install the Timer Architectural Protocol onto a new handle
+ Status = gBS->InstallMultipleProtocolInterfaces(
+ &Handle,
+ &gEfiTimerArchProtocolGuid, &gTimer,
+ NULL
+ );
+ ASSERT_EFI_ERROR(Status);
+
+ // enable Secure timer interrupts
+ Status = gInterrupt->EnableInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerSecIntrNum));
+
+ // enable NonSecure timer interrupts
+ Status = gInterrupt->EnableInterruptSource (gInterrupt, PcdGet32 (PcdArmArchTimerIntrNum));
+
+ // Register for an ExitBootServicesEvent
+ Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
diff --git a/ArmPkg/Drivers/TimerDxe/TimerDxe.inf b/ArmPkg/Drivers/TimerDxe/TimerDxe.inf
index 4fe2e2f0b..061fcbc68 100644
--- a/ArmPkg/Drivers/TimerDxe/TimerDxe.inf
+++ b/ArmPkg/Drivers/TimerDxe/TimerDxe.inf
@@ -1,59 +1,59 @@
-#/** @file
-#
-# Component description file for Timer DXE module
-#
-# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmTimerDxe
- FILE_GUID = 49ea041e-6752-42ca-b0b1-7344fe2546b7
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = TimerInitialize
-
-[Sources.common]
- TimerDxe.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- ArmLib
- BaseLib
- UefiRuntimeServicesTableLib
- UefiLib
- UefiBootServicesTableLib
- BaseMemoryLib
- DebugLib
- UefiDriverEntryPoint
- IoLib
-
-[Guids]
-
-[Protocols]
- gEfiTimerArchProtocolGuid
- gHardwareInterruptProtocolGuid
-
-[Pcd.common]
- gEmbeddedTokenSpaceGuid.PcdTimerPeriod
- gArmTokenSpaceGuid.PcdArmArchTimerSecIntrNum
- gArmTokenSpaceGuid.PcdArmArchTimerIntrNum
- gArmTokenSpaceGuid.PcdArmArchTimerFreqInHz
-
-[Depex]
- gHardwareInterruptProtocolGuid
- \ No newline at end of file
+#/** @file
+#
+# Component description file for Timer DXE module
+#
+# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmTimerDxe
+ FILE_GUID = 49ea041e-6752-42ca-b0b1-7344fe2546b7
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = TimerInitialize
+
+[Sources.common]
+ TimerDxe.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ ArmLib
+ BaseLib
+ UefiRuntimeServicesTableLib
+ UefiLib
+ UefiBootServicesTableLib
+ BaseMemoryLib
+ DebugLib
+ UefiDriverEntryPoint
+ IoLib
+
+[Guids]
+
+[Protocols]
+ gEfiTimerArchProtocolGuid
+ gHardwareInterruptProtocolGuid
+
+[Pcd.common]
+ gEmbeddedTokenSpaceGuid.PcdTimerPeriod
+ gArmTokenSpaceGuid.PcdArmArchTimerSecIntrNum
+ gArmTokenSpaceGuid.PcdArmArchTimerIntrNum
+ gArmTokenSpaceGuid.PcdArmArchTimerFreqInHz
+
+[Depex]
+ gHardwareInterruptProtocolGuid
+ \ No newline at end of file
diff --git a/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c b/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c
index e6604ba0e..5c70e51ce 100644
--- a/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c
+++ b/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c
@@ -177,8 +177,11 @@ FileOpen (
*AsciiPtr++ = *FileName++ & 0xFF;
}
- if ((AsciiStrCmp (AsciiFileName, "\\") == 0) || (AsciiStrCmp (AsciiFileName, "/") == 0) || (AsciiStrCmp (AsciiFileName, "") == 0)) {
- // Opening '/', '\', or the NULL pathname is trying to open the root directory
+ if ((AsciiStrCmp (AsciiFileName, "\\") == 0) ||
+ (AsciiStrCmp (AsciiFileName, "/") == 0) ||
+ (AsciiStrCmp (AsciiFileName, "") == 0) ||
+ (AsciiStrCmp (AsciiFileName, ".") == 0)) {
+ // Opening '/', '\', '.', or the NULL pathname is trying to open the root directory
IsRoot = TRUE;
// Root directory node doesn't have a name.
diff --git a/ArmPkg/Filesystem/SemihostFs/SemihostFs.inf b/ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
index 25b728948..30ce6665f 100644
--- a/ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+++ b/ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
@@ -1,46 +1,46 @@
-#/** @file
-# Support a Semi Host file system over a debuggers JTAG
-#
-# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = SemihostFs
- FILE_GUID = C5B9C74A-6D72-4719-99AB-C59F199091EB
- MODULE_TYPE = UEFI_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = SemihostFsEntryPoint
-
-[Sources.ARM]
- Arm/SemihostFs.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPkg/ArmPkg.dec
-
-[LibraryClasses]
- BaseLib
- MemoryAllocationLib
- SemihostLib
- UefiDriverEntryPoint
- UefiLib
-
-[Guids]
- gEfiFileSystemInfoGuid
- gEfiFileInfoGuid
- gEfiFileSystemVolumeLabelInfoIdGuid
-
-[Protocols]
- gEfiSimpleFileSystemProtocolGuid
- gEfiDevicePathProtocolGuid
-
+#/** @file
+# Support a Semi Host file system over a debuggers JTAG
+#
+# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SemihostFs
+ FILE_GUID = C5B9C74A-6D72-4719-99AB-C59F199091EB
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = SemihostFsEntryPoint
+
+[Sources.ARM]
+ Arm/SemihostFs.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPkg/ArmPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ MemoryAllocationLib
+ SemihostLib
+ UefiDriverEntryPoint
+ UefiLib
+
+[Guids]
+ gEfiFileSystemInfoGuid
+ gEfiFileInfoGuid
+ gEfiFileSystemVolumeLabelInfoIdGuid
+
+[Protocols]
+ gEfiSimpleFileSystemProtocolGuid
+ gEfiDevicePathProtocolGuid
+
diff --git a/ArmPkg/Include/Chipset/ArmV7.h b/ArmPkg/Include/Chipset/ArmV7.h
index 3d1b4eea4..e64deb141 100644
--- a/ArmPkg/Include/Chipset/ArmV7.h
+++ b/ArmPkg/Include/Chipset/ArmV7.h
@@ -1,7 +1,7 @@
/** @file
Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+ Copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -19,6 +19,9 @@
#include <Chipset/ArmV7Mmu.h>
#include <Chipset/ArmV7ArchTimer.h>
+// ARM Interrupt ID in Exception Table
+#define ARM_ARCH_EXCEPTION_IRQ EXCEPT_ARM_IRQ
+
// Domain Access Control Register
#define DOMAIN_ACCESS_CONTROL_MASK(a) (3UL << (2 * (a)))
#define DOMAIN_ACCESS_CONTROL_NONE(a) (0UL << (2 * (a)))
@@ -26,6 +29,21 @@
#define DOMAIN_ACCESS_CONTROL_RESERVED(a) (2UL << (2 * (a)))
#define DOMAIN_ACCESS_CONTROL_MANAGER(a) (3UL << (2 * (a)))
+// CPSR - Coprocessor Status Register definitions
+#define CPSR_MODE_USER 0x10
+#define CPSR_MODE_FIQ 0x11
+#define CPSR_MODE_IRQ 0x12
+#define CPSR_MODE_SVC 0x13
+#define CPSR_MODE_ABORT 0x17
+#define CPSR_MODE_HYP 0x1A
+#define CPSR_MODE_UNDEFINED 0x1B
+#define CPSR_MODE_SYSTEM 0x1F
+#define CPSR_MODE_MASK 0x1F
+#define CPSR_ASYNC_ABORT (1 << 8)
+#define CPSR_IRQ (1 << 7)
+#define CPSR_FIQ (1 << 6)
+
+
// CPACR - Coprocessor Access Control Register definitions
#define CPACR_CP_DENIED(cp) 0x00
#define CPACR_CP_PRIV(cp) ((0x1 << ((cp) << 1)) & 0x0FFFFFFF)
diff --git a/ArmPkg/Include/Library/ArmCpuLib.h b/ArmPkg/Include/Library/ArmCpuLib.h
index 6f92b111d..0c415992d 100644
--- a/ArmPkg/Include/Library/ArmCpuLib.h
+++ b/ArmPkg/Include/Library/ArmCpuLib.h
@@ -1,28 +1,28 @@
-/** @file
-
- Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __ARMCPU_LIB__
-#define __ARMCPU_LIB__
-
-VOID
-ArmCpuSetup (
- IN UINTN MpId
- );
-
-VOID
-ArmCpuSetupSmpNonSecure (
- IN UINTN MpId
- );
-
-#endif // __ARMCPU_LIB__
+/** @file
+
+ Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __ARMCPU_LIB__
+#define __ARMCPU_LIB__
+
+VOID
+ArmCpuSetup (
+ IN UINTN MpId
+ );
+
+VOID
+ArmCpuSetupSmpNonSecure (
+ IN UINTN MpId
+ );
+
+#endif // __ARMCPU_LIB__
diff --git a/ArmPkg/Include/Library/ArmDisassemblerLib.h b/ArmPkg/Include/Library/ArmDisassemblerLib.h
index 038f2ddfa..757c95ec7 100644
--- a/ArmPkg/Include/Library/ArmDisassemblerLib.h
+++ b/ArmPkg/Include/Library/ArmDisassemblerLib.h
@@ -1,43 +1,43 @@
-/** @file
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __ARM_DISASSEBLER_LIB_H__
-#define __ARM_DISASSEBLER_LIB_H__
-
-/**
- Place a dissasembly of of **OpCodePtr into buffer, and update OpCodePtr to
- point to next instructin.
-
- We cheat and only decode instructions that access
- memory. If the instruction is not found we dump the instruction in hex.
-
- @param OpCodePtrPtr Pointer to pointer of ARM Thumb instruction to disassemble.
- @param Thumb TRUE for Thumb(2), FALSE for ARM instruction stream
- @param Extended TRUE dump hex for instruction too.
+/** @file
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __ARM_DISASSEBLER_LIB_H__
+#define __ARM_DISASSEBLER_LIB_H__
+
+/**
+ Place a dissasembly of of **OpCodePtr into buffer, and update OpCodePtr to
+ point to next instructin.
+
+ We cheat and only decode instructions that access
+ memory. If the instruction is not found we dump the instruction in hex.
+
+ @param OpCodePtrPtr Pointer to pointer of ARM Thumb instruction to disassemble.
+ @param Thumb TRUE for Thumb(2), FALSE for ARM instruction stream
+ @param Extended TRUE dump hex for instruction too.
@param ItBlock Size of IT Block
- @param Buf Buffer to sprintf disassembly into.
- @param Size Size of Buf in bytes.
-
-**/
-VOID
-DisassembleInstruction (
- IN UINT8 **OpCodePtr,
- IN BOOLEAN Thumb,
- IN BOOLEAN Extended,
+ @param Buf Buffer to sprintf disassembly into.
+ @param Size Size of Buf in bytes.
+
+**/
+VOID
+DisassembleInstruction (
+ IN UINT8 **OpCodePtr,
+ IN BOOLEAN Thumb,
+ IN BOOLEAN Extended,
IN OUT UINT32 *ItBlock,
- OUT CHAR8 *Buf,
- OUT UINTN Size
- );
-
-#endif
+ OUT CHAR8 *Buf,
+ OUT UINTN Size
+ );
+
+#endif
diff --git a/ArmPkg/Include/Library/ArmLib.h b/ArmPkg/Include/Library/ArmLib.h
index 23beb2427..4550ea6ba 100644
--- a/ArmPkg/Include/Library/ArmLib.h
+++ b/ArmPkg/Include/Library/ArmLib.h
@@ -1,561 +1,573 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
- Copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __ARM_LIB__
-#define __ARM_LIB__
-
-#include <Uefi/UefiBaseType.h>
-
-#ifdef ARM_CPU_ARMv6
-#include <Chipset/ARM1176JZ-S.h>
-#else
-#include <Chipset/ArmV7.h>
-#endif
-
-typedef enum {
- ARM_CACHE_TYPE_WRITE_BACK,
- ARM_CACHE_TYPE_UNKNOWN
-} ARM_CACHE_TYPE;
-
-typedef enum {
- ARM_CACHE_ARCHITECTURE_UNIFIED,
- ARM_CACHE_ARCHITECTURE_SEPARATE,
- ARM_CACHE_ARCHITECTURE_UNKNOWN
-} ARM_CACHE_ARCHITECTURE;
-
-typedef struct {
- ARM_CACHE_TYPE Type;
- ARM_CACHE_ARCHITECTURE Architecture;
- BOOLEAN DataCachePresent;
- UINTN DataCacheSize;
- UINTN DataCacheAssociativity;
- UINTN DataCacheLineLength;
- BOOLEAN InstructionCachePresent;
- UINTN InstructionCacheSize;
- UINTN InstructionCacheAssociativity;
- UINTN InstructionCacheLineLength;
-} ARM_CACHE_INFO;
-
-/**
- * The UEFI firmware must not use the ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_* attributes.
- *
- * The Non Secure memory attribute (ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_*) should only
- * be used in Secure World to distinguished Secure to Non-Secure memory.
- */
-typedef enum {
- ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED = 0,
- ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED,
- ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK,
- ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK,
- ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH,
- ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH,
- ARM_MEMORY_REGION_ATTRIBUTE_DEVICE,
- ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_DEVICE
-} ARM_MEMORY_REGION_ATTRIBUTES;
-
-#define IS_ARM_MEMORY_REGION_ATTRIBUTES_SECURE(attr) ((UINT32)(attr) & 1)
-
-typedef struct {
- EFI_PHYSICAL_ADDRESS PhysicalBase;
- EFI_VIRTUAL_ADDRESS VirtualBase;
- UINTN Length;
- ARM_MEMORY_REGION_ATTRIBUTES Attributes;
-} ARM_MEMORY_REGION_DESCRIPTOR;
-
-typedef VOID (*CACHE_OPERATION)(VOID);
-typedef VOID (*LINE_OPERATION)(UINTN);
-
-//
-// ARM Processor Mode
-//
-typedef enum {
- ARM_PROCESSOR_MODE_USER = 0x10,
- ARM_PROCESSOR_MODE_FIQ = 0x11,
- ARM_PROCESSOR_MODE_IRQ = 0x12,
- ARM_PROCESSOR_MODE_SUPERVISOR = 0x13,
- ARM_PROCESSOR_MODE_ABORT = 0x17,
- ARM_PROCESSOR_MODE_HYP = 0x1A,
- ARM_PROCESSOR_MODE_UNDEFINED = 0x1B,
- ARM_PROCESSOR_MODE_SYSTEM = 0x1F,
- ARM_PROCESSOR_MODE_MASK = 0x1F
-} ARM_PROCESSOR_MODE;
-
-//
-// ARM Cpu IDs
-//
-#define ARM_CPU_IMPLEMENTER_MASK (0xFFU << 24)
-#define ARM_CPU_IMPLEMENTER_ARMLTD (0x41U << 24)
-#define ARM_CPU_IMPLEMENTER_DEC (0x44U << 24)
-#define ARM_CPU_IMPLEMENTER_MOT (0x4DU << 24)
-#define ARM_CPU_IMPLEMENTER_QUALCOMM (0x51U << 24)
-#define ARM_CPU_IMPLEMENTER_MARVELL (0x56U << 24)
-
-#define ARM_CPU_PRIMARY_PART_MASK (0xFFF << 4)
-#define ARM_CPU_PRIMARY_PART_CORTEXA5 (0xC05 << 4)
-#define ARM_CPU_PRIMARY_PART_CORTEXA7 (0xC07 << 4)
-#define ARM_CPU_PRIMARY_PART_CORTEXA8 (0xC08 << 4)
-#define ARM_CPU_PRIMARY_PART_CORTEXA9 (0xC09 << 4)
-#define ARM_CPU_PRIMARY_PART_CORTEXA15 (0xC0F << 4)
-
-//
-// ARM MP Core IDs
-//
-#define IS_PRIMARY_CORE(MpId) (((MpId) & PcdGet32(PcdArmPrimaryCoreMask)) == PcdGet32(PcdArmPrimaryCore))
-#define ARM_CORE_MASK 0xFF
-#define ARM_CLUSTER_MASK (0xFF << 8)
-#define GET_CORE_ID(MpId) ((MpId) & ARM_CORE_MASK)
-#define GET_CLUSTER_ID(MpId) (((MpId) & ARM_CLUSTER_MASK) >> 8)
-// Get the position of the core for the Stack Offset (4 Core per Cluster)
-// Position = (ClusterId * 4) + CoreId
-#define GET_CORE_POS(MpId) ((((MpId) & ARM_CLUSTER_MASK) >> 6) + ((MpId) & ARM_CORE_MASK))
-#define PRIMARY_CORE_ID (PcdGet32(PcdArmPrimaryCore) & ARM_CORE_MASK)
-
-ARM_CACHE_TYPE
-EFIAPI
-ArmCacheType (
- VOID
- );
-
-ARM_CACHE_ARCHITECTURE
-EFIAPI
-ArmCacheArchitecture (
- VOID
- );
-
-VOID
-EFIAPI
-ArmCacheInformation (
- OUT ARM_CACHE_INFO *CacheInfo
- );
-
-BOOLEAN
-EFIAPI
-ArmDataCachePresent (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDataCacheSize (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDataCacheAssociativity (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDataCacheLineLength (
- VOID
- );
-
-BOOLEAN
-EFIAPI
-ArmInstructionCachePresent (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmInstructionCacheSize (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmInstructionCacheAssociativity (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmInstructionCacheLineLength (
- VOID
- );
-
-UINT32
-EFIAPI
-Cp15IdCode (
- VOID
- );
-
-UINT32
-EFIAPI
-Cp15CacheInfo (
- VOID
- );
-
-BOOLEAN
-EFIAPI
-ArmIsMpCore (
- VOID
- );
-
-VOID
-EFIAPI
-ArmInvalidateDataCache (
- VOID
- );
-
-
-VOID
-EFIAPI
-ArmCleanInvalidateDataCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmCleanDataCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmCleanDataCacheToPoU (
- VOID
- );
-
-VOID
-EFIAPI
-ArmInvalidateInstructionCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmInvalidateDataCacheEntryByMVA (
- IN UINTN Address
- );
-
-VOID
-EFIAPI
-ArmCleanDataCacheEntryByMVA (
- IN UINTN Address
- );
-
-VOID
-EFIAPI
-ArmCleanInvalidateDataCacheEntryByMVA (
- IN UINTN Address
- );
-
-VOID
-EFIAPI
-ArmEnableDataCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDisableDataCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmEnableInstructionCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDisableInstructionCache (
- VOID
- );
-
-VOID
-EFIAPI
-ArmEnableMmu (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDisableMmu (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDisableCachesAndMmu (
- VOID
- );
-
-VOID
-EFIAPI
-ArmInvalidateInstructionAndDataTlb (
- VOID
- );
-
-VOID
-EFIAPI
-ArmEnableInterrupts (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDisableInterrupts (
- VOID
- );
-
-BOOLEAN
-EFIAPI
-ArmGetInterruptState (
- VOID
- );
-
-VOID
-EFIAPI
-ArmEnableFiq (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDisableFiq (
- VOID
- );
-
-BOOLEAN
-EFIAPI
-ArmGetFiqState (
- VOID
- );
-
-VOID
-EFIAPI
-ArmInvalidateTlb (
- VOID
- );
-
-VOID
-EFIAPI
-ArmUpdateTranslationTableEntry (
- IN VOID *TranslationTableEntry,
- IN VOID *Mva
- );
-
-VOID
-EFIAPI
-ArmSetDomainAccessControl (
- IN UINT32 Domain
- );
-
-VOID
-EFIAPI
-ArmSetTTBR0 (
- IN VOID *TranslationTableBase
- );
-
-VOID *
-EFIAPI
-ArmGetTTBR0BaseAddress (
- VOID
- );
-
-VOID
-EFIAPI
-ArmConfigureMmu (
- IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable,
- OUT VOID **TranslationTableBase OPTIONAL,
- OUT UINTN *TranslationTableSize OPTIONAL
- );
-
-BOOLEAN
-EFIAPI
-ArmMmuEnabled (
- VOID
- );
-
-VOID
-EFIAPI
-ArmSwitchProcessorMode (
- IN ARM_PROCESSOR_MODE Mode
- );
-
-ARM_PROCESSOR_MODE
-EFIAPI
-ArmProcessorMode (
- VOID
- );
-
-VOID
-EFIAPI
-ArmEnableBranchPrediction (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDisableBranchPrediction (
- VOID
- );
-
-VOID
-EFIAPI
-ArmSetLowVectors (
- VOID
- );
-
-VOID
-EFIAPI
-ArmSetHighVectors (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDataMemoryBarrier (
- VOID
- );
-
-VOID
-EFIAPI
-ArmDataSyncronizationBarrier (
- VOID
- );
-
-VOID
-EFIAPI
-ArmInstructionSynchronizationBarrier (
- VOID
- );
-
-VOID
-EFIAPI
-ArmWriteVBar (
- IN UINT32 VectorBase
- );
-
-UINT32
-EFIAPI
-ArmReadVBar (
- VOID
- );
-
-VOID
-EFIAPI
-ArmWriteAuxCr (
- IN UINT32 Bit
- );
-
-UINT32
-EFIAPI
-ArmReadAuxCr (
- VOID
- );
-
-VOID
-EFIAPI
-ArmSetAuxCrBit (
- IN UINT32 Bits
- );
-
-VOID
-EFIAPI
-ArmUnsetAuxCrBit (
- IN UINT32 Bits
- );
-
-VOID
-EFIAPI
-ArmCallSEV (
- VOID
- );
-
-VOID
-EFIAPI
-ArmCallWFE (
- VOID
- );
-
-VOID
-EFIAPI
-ArmCallWFI (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmReadMpidr (
- VOID
- );
-
-UINT32
-EFIAPI
-ArmReadCpacr (
- VOID
- );
-
-VOID
-EFIAPI
-ArmWriteCpacr (
- IN UINT32 Access
- );
-
-VOID
-EFIAPI
-ArmEnableVFP (
- VOID
- );
-
-UINT32
-EFIAPI
-ArmReadNsacr (
- VOID
- );
-
-VOID
-EFIAPI
-ArmWriteNsacr (
- IN UINT32 SetWayFormat
- );
-
-UINT32
-EFIAPI
-ArmReadScr (
- VOID
- );
-
-VOID
-EFIAPI
-ArmWriteScr (
- IN UINT32 SetWayFormat
- );
-
-UINT32
-EFIAPI
-ArmReadMVBar (
- VOID
- );
-
-VOID
-EFIAPI
-ArmWriteMVBar (
- IN UINT32 VectorMonitorBase
- );
-
-UINT32
-EFIAPI
-ArmReadSctlr (
- VOID
- );
-
-#endif // __ARM_LIB__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+ Copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __ARM_LIB__
+#define __ARM_LIB__
+
+#include <Uefi/UefiBaseType.h>
+
+#ifdef ARM_CPU_ARMv6
+#include <Chipset/ARM1176JZ-S.h>
+#else
+#include <Chipset/ArmV7.h>
+#endif
+
+typedef enum {
+ ARM_CACHE_TYPE_WRITE_BACK,
+ ARM_CACHE_TYPE_UNKNOWN
+} ARM_CACHE_TYPE;
+
+typedef enum {
+ ARM_CACHE_ARCHITECTURE_UNIFIED,
+ ARM_CACHE_ARCHITECTURE_SEPARATE,
+ ARM_CACHE_ARCHITECTURE_UNKNOWN
+} ARM_CACHE_ARCHITECTURE;
+
+typedef struct {
+ ARM_CACHE_TYPE Type;
+ ARM_CACHE_ARCHITECTURE Architecture;
+ BOOLEAN DataCachePresent;
+ UINTN DataCacheSize;
+ UINTN DataCacheAssociativity;
+ UINTN DataCacheLineLength;
+ BOOLEAN InstructionCachePresent;
+ UINTN InstructionCacheSize;
+ UINTN InstructionCacheAssociativity;
+ UINTN InstructionCacheLineLength;
+} ARM_CACHE_INFO;
+
+/**
+ * The UEFI firmware must not use the ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_* attributes.
+ *
+ * The Non Secure memory attribute (ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_*) should only
+ * be used in Secure World to distinguished Secure to Non-Secure memory.
+ */
+typedef enum {
+ ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED = 0,
+ ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED,
+ ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK,
+ ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK,
+ ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH,
+ ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH,
+ ARM_MEMORY_REGION_ATTRIBUTE_DEVICE,
+ ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_DEVICE
+} ARM_MEMORY_REGION_ATTRIBUTES;
+
+#define IS_ARM_MEMORY_REGION_ATTRIBUTES_SECURE(attr) ((UINT32)(attr) & 1)
+
+typedef struct {
+ EFI_PHYSICAL_ADDRESS PhysicalBase;
+ EFI_VIRTUAL_ADDRESS VirtualBase;
+ UINTN Length;
+ ARM_MEMORY_REGION_ATTRIBUTES Attributes;
+} ARM_MEMORY_REGION_DESCRIPTOR;
+
+typedef VOID (*CACHE_OPERATION)(VOID);
+typedef VOID (*LINE_OPERATION)(UINTN);
+
+//
+// ARM Processor Mode
+//
+typedef enum {
+ ARM_PROCESSOR_MODE_USER = 0x10,
+ ARM_PROCESSOR_MODE_FIQ = 0x11,
+ ARM_PROCESSOR_MODE_IRQ = 0x12,
+ ARM_PROCESSOR_MODE_SUPERVISOR = 0x13,
+ ARM_PROCESSOR_MODE_ABORT = 0x17,
+ ARM_PROCESSOR_MODE_HYP = 0x1A,
+ ARM_PROCESSOR_MODE_UNDEFINED = 0x1B,
+ ARM_PROCESSOR_MODE_SYSTEM = 0x1F,
+ ARM_PROCESSOR_MODE_MASK = 0x1F
+} ARM_PROCESSOR_MODE;
+
+//
+// ARM Cpu IDs
+//
+#define ARM_CPU_IMPLEMENTER_MASK (0xFFU << 24)
+#define ARM_CPU_IMPLEMENTER_ARMLTD (0x41U << 24)
+#define ARM_CPU_IMPLEMENTER_DEC (0x44U << 24)
+#define ARM_CPU_IMPLEMENTER_MOT (0x4DU << 24)
+#define ARM_CPU_IMPLEMENTER_QUALCOMM (0x51U << 24)
+#define ARM_CPU_IMPLEMENTER_MARVELL (0x56U << 24)
+
+#define ARM_CPU_PRIMARY_PART_MASK (0xFFF << 4)
+#define ARM_CPU_PRIMARY_PART_CORTEXA5 (0xC05 << 4)
+#define ARM_CPU_PRIMARY_PART_CORTEXA7 (0xC07 << 4)
+#define ARM_CPU_PRIMARY_PART_CORTEXA8 (0xC08 << 4)
+#define ARM_CPU_PRIMARY_PART_CORTEXA9 (0xC09 << 4)
+#define ARM_CPU_PRIMARY_PART_CORTEXA15 (0xC0F << 4)
+
+//
+// ARM MP Core IDs
+//
+#define IS_PRIMARY_CORE(MpId) (((MpId) & PcdGet32(PcdArmPrimaryCoreMask)) == PcdGet32(PcdArmPrimaryCore))
+#define ARM_CORE_MASK 0xFF
+#define ARM_CLUSTER_MASK (0xFF << 8)
+#define GET_CORE_ID(MpId) ((MpId) & ARM_CORE_MASK)
+#define GET_CLUSTER_ID(MpId) (((MpId) & ARM_CLUSTER_MASK) >> 8)
+// Get the position of the core for the Stack Offset (4 Core per Cluster)
+// Position = (ClusterId * 4) + CoreId
+#define GET_CORE_POS(MpId) ((((MpId) & ARM_CLUSTER_MASK) >> 6) + ((MpId) & ARM_CORE_MASK))
+#define PRIMARY_CORE_ID (PcdGet32(PcdArmPrimaryCore) & ARM_CORE_MASK)
+
+ARM_CACHE_TYPE
+EFIAPI
+ArmCacheType (
+ VOID
+ );
+
+ARM_CACHE_ARCHITECTURE
+EFIAPI
+ArmCacheArchitecture (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmCacheInformation (
+ OUT ARM_CACHE_INFO *CacheInfo
+ );
+
+BOOLEAN
+EFIAPI
+ArmDataCachePresent (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmDataCacheSize (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmDataCacheAssociativity (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmDataCacheLineLength (
+ VOID
+ );
+
+BOOLEAN
+EFIAPI
+ArmInstructionCachePresent (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmInstructionCacheSize (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmInstructionCacheAssociativity (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmInstructionCacheLineLength (
+ VOID
+ );
+
+UINT32
+EFIAPI
+Cp15IdCode (
+ VOID
+ );
+
+UINT32
+EFIAPI
+Cp15CacheInfo (
+ VOID
+ );
+
+BOOLEAN
+EFIAPI
+ArmIsMpCore (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmInvalidateDataCache (
+ VOID
+ );
+
+
+VOID
+EFIAPI
+ArmCleanInvalidateDataCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmCleanDataCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmCleanDataCacheToPoU (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmInvalidateInstructionCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmInvalidateDataCacheEntryByMVA (
+ IN UINTN Address
+ );
+
+VOID
+EFIAPI
+ArmCleanDataCacheEntryByMVA (
+ IN UINTN Address
+ );
+
+VOID
+EFIAPI
+ArmCleanInvalidateDataCacheEntryByMVA (
+ IN UINTN Address
+ );
+
+VOID
+EFIAPI
+ArmEnableDataCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDisableDataCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmEnableInstructionCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDisableInstructionCache (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmEnableMmu (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDisableMmu (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDisableCachesAndMmu (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmInvalidateInstructionAndDataTlb (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmEnableInterrupts (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmDisableInterrupts (
+ VOID
+ );
+
+BOOLEAN
+EFIAPI
+ArmGetInterruptState (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmDisableIrq (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmEnableIrq (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmEnableFiq (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmDisableFiq (
+ VOID
+ );
+
+BOOLEAN
+EFIAPI
+ArmGetFiqState (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmInvalidateTlb (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmUpdateTranslationTableEntry (
+ IN VOID *TranslationTableEntry,
+ IN VOID *Mva
+ );
+
+VOID
+EFIAPI
+ArmSetDomainAccessControl (
+ IN UINT32 Domain
+ );
+
+VOID
+EFIAPI
+ArmSetTTBR0 (
+ IN VOID *TranslationTableBase
+ );
+
+VOID *
+EFIAPI
+ArmGetTTBR0BaseAddress (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmConfigureMmu (
+ IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable,
+ OUT VOID **TranslationTableBase OPTIONAL,
+ OUT UINTN *TranslationTableSize OPTIONAL
+ );
+
+BOOLEAN
+EFIAPI
+ArmMmuEnabled (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmSwitchProcessorMode (
+ IN ARM_PROCESSOR_MODE Mode
+ );
+
+ARM_PROCESSOR_MODE
+EFIAPI
+ArmProcessorMode (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmEnableBranchPrediction (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDisableBranchPrediction (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmSetLowVectors (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmSetHighVectors (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDataMemoryBarrier (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmDataSyncronizationBarrier (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmInstructionSynchronizationBarrier (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmWriteVBar (
+ IN UINT32 VectorBase
+ );
+
+UINT32
+EFIAPI
+ArmReadVBar (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmWriteAuxCr (
+ IN UINT32 Bit
+ );
+
+UINT32
+EFIAPI
+ArmReadAuxCr (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmSetAuxCrBit (
+ IN UINT32 Bits
+ );
+
+VOID
+EFIAPI
+ArmUnsetAuxCrBit (
+ IN UINT32 Bits
+ );
+
+VOID
+EFIAPI
+ArmCallSEV (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmCallWFE (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmCallWFI (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmReadMpidr (
+ VOID
+ );
+
+UINT32
+EFIAPI
+ArmReadCpacr (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmWriteCpacr (
+ IN UINT32 Access
+ );
+
+VOID
+EFIAPI
+ArmEnableVFP (
+ VOID
+ );
+
+UINT32
+EFIAPI
+ArmReadNsacr (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmWriteNsacr (
+ IN UINT32 SetWayFormat
+ );
+
+UINT32
+EFIAPI
+ArmReadScr (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmWriteScr (
+ IN UINT32 SetWayFormat
+ );
+
+UINT32
+EFIAPI
+ArmReadMVBar (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmWriteMVBar (
+ IN UINT32 VectorMonitorBase
+ );
+
+UINT32
+EFIAPI
+ArmReadSctlr (
+ VOID
+ );
+
+#endif // __ARM_LIB__
diff --git a/ArmPkg/Include/Library/ArmV7ArchTimerLib.h b/ArmPkg/Include/Library/ArmV7ArchTimerLib.h
index d2f4a46c6..983184810 100644
--- a/ArmPkg/Include/Library/ArmV7ArchTimerLib.h
+++ b/ArmPkg/Include/Library/ArmV7ArchTimerLib.h
@@ -1,115 +1,115 @@
-/** @file
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __ARM_V7_ARCH_TIMER_LIB_H__
-#define __ARM_V7_ARCH_TIMER_LIB_H__
-
-#define ARM_ARCH_TIMER_ENABLE (1 << 0)
-#define ARM_ARCH_TIMER_IMASK (1 << 1)
-#define ARM_ARCH_TIMER_ISTATUS (1 << 2)
-
-typedef enum {
- CntFrq = 0,
- CntPct,
- CntkCtl,
- CntpTval,
- CntpCtl,
- CntvTval,
- CntvCtl,
- CntvCt,
- CntpCval,
- CntvCval,
- CntvOff,
- CnthCtl,
- CnthpTval,
- CnthpCtl,
- CnthpCval,
- RegMaximum
-}ARM_ARCH_TIMER_REGS;
-
-VOID
-EFIAPI
-ArmArchTimerReadReg (
- IN ARM_ARCH_TIMER_REGS Reg,
- OUT VOID *DstBuf
- );
-
-VOID
-EFIAPI
-ArmArchTimerWriteReg (
- IN ARM_ARCH_TIMER_REGS Reg,
- IN VOID *SrcBuf
- );
-
-VOID
-EFIAPI
-ArmArchTimerEnableTimer (
- VOID
- );
-
-VOID
-EFIAPI
-ArmArchTimerDisableTimer (
- VOID
- );
-
-VOID
-EFIAPI
-ArmArchTimerSetTimerFreq (
- IN UINTN FreqInHz
- );
-
-UINTN
-EFIAPI
-ArmArchTimerGetTimerFreq (
- VOID
- );
-
-VOID
-EFIAPI
-ArmArchTimerSetTimerVal (
- IN UINTN Val
- );
-
-UINTN
-EFIAPI
-ArmArchTimerGetTimerVal (
- VOID
- );
-
-UINT64
-EFIAPI
-ArmArchTimerGetSystemCount (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmArchTimerGetTimerCtrlReg (
- VOID
- );
-
-VOID
-EFIAPI
-ArmArchTimerSetTimerCtrlReg (
- UINTN Val
- );
-
-VOID
-EFIAPI
-ArmArchTimerSetCompareVal (
- IN UINT64 Val
- );
-
-#endif // __ARM_V7_ARCH_TIMER_LIB_H__
+/** @file
+
+ Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __ARM_V7_ARCH_TIMER_LIB_H__
+#define __ARM_V7_ARCH_TIMER_LIB_H__
+
+#define ARM_ARCH_TIMER_ENABLE (1 << 0)
+#define ARM_ARCH_TIMER_IMASK (1 << 1)
+#define ARM_ARCH_TIMER_ISTATUS (1 << 2)
+
+typedef enum {
+ CntFrq = 0,
+ CntPct,
+ CntkCtl,
+ CntpTval,
+ CntpCtl,
+ CntvTval,
+ CntvCtl,
+ CntvCt,
+ CntpCval,
+ CntvCval,
+ CntvOff,
+ CnthCtl,
+ CnthpTval,
+ CnthpCtl,
+ CnthpCval,
+ RegMaximum
+}ARM_ARCH_TIMER_REGS;
+
+VOID
+EFIAPI
+ArmArchTimerReadReg (
+ IN ARM_ARCH_TIMER_REGS Reg,
+ OUT VOID *DstBuf
+ );
+
+VOID
+EFIAPI
+ArmArchTimerWriteReg (
+ IN ARM_ARCH_TIMER_REGS Reg,
+ IN VOID *SrcBuf
+ );
+
+VOID
+EFIAPI
+ArmArchTimerEnableTimer (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmArchTimerDisableTimer (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmArchTimerSetTimerFreq (
+ IN UINTN FreqInHz
+ );
+
+UINTN
+EFIAPI
+ArmArchTimerGetTimerFreq (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmArchTimerSetTimerVal (
+ IN UINTN Val
+ );
+
+UINTN
+EFIAPI
+ArmArchTimerGetTimerVal (
+ VOID
+ );
+
+UINT64
+EFIAPI
+ArmArchTimerGetSystemCount (
+ VOID
+ );
+
+UINTN
+EFIAPI
+ArmArchTimerGetTimerCtrlReg (
+ VOID
+ );
+
+VOID
+EFIAPI
+ArmArchTimerSetTimerCtrlReg (
+ UINTN Val
+ );
+
+VOID
+EFIAPI
+ArmArchTimerSetCompareVal (
+ IN UINT64 Val
+ );
+
+#endif // __ARM_V7_ARCH_TIMER_LIB_H__
diff --git a/ArmPkg/Include/Library/DefaultExceptionHandlerLib.h b/ArmPkg/Include/Library/DefaultExceptionHandlerLib.h
index cf3fe0cca..7166dbb36 100644
--- a/ArmPkg/Include/Library/DefaultExceptionHandlerLib.h
+++ b/ArmPkg/Include/Library/DefaultExceptionHandlerLib.h
@@ -1,31 +1,31 @@
-/** @file
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __DEFAULT_EXCEPTION_HANDLER_LIB_H__
-#define __DEFAULT_EXCEPTION_HANDLER_LIB_H__
-
-/**
- This is the default action to take on an unexpected exception
-
- @param ExceptionType Type of the exception
- @param SystemContext Register state at the time of the Exception
-
-**/
-VOID
-DefaultExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType,
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-#endif
+/** @file
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __DEFAULT_EXCEPTION_HANDLER_LIB_H__
+#define __DEFAULT_EXCEPTION_HANDLER_LIB_H__
+
+/**
+ This is the default action to take on an unexpected exception
+
+ @param ExceptionType Type of the exception
+ @param SystemContext Register state at the time of the Exception
+
+**/
+VOID
+DefaultExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+#endif
diff --git a/ArmPkg/Include/Library/SemihostLib.h b/ArmPkg/Include/Library/SemihostLib.h
index 68f4b772e..2ced7f107 100644
--- a/ArmPkg/Include/Library/SemihostLib.h
+++ b/ArmPkg/Include/Library/SemihostLib.h
@@ -1,100 +1,100 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __SEMIHOSTING_H__
-#define __SEMIHOSTING_H__
-
-/*
- *
- * Please refer to ARM RVDS 3.0 Compiler and Libraries Guide for more information
- * about the semihosting interface.
- *
- */
-
-#define SEMIHOST_FILE_MODE_READ (0 << 2)
-#define SEMIHOST_FILE_MODE_WRITE (1 << 2)
-#define SEMIHOST_FILE_MODE_APPEND (2 << 2)
-#define SEMIHOST_FILE_MODE_CREATE (1 << 1)
-#define SEMIHOST_FILE_MODE_BINARY (1 << 0)
-#define SEMIHOST_FILE_MODE_ASCII (0 << 0)
-
-BOOLEAN
-SemihostConnectionSupported (
- VOID
- );
-
-RETURN_STATUS
-SemihostFileOpen (
- IN CHAR8 *FileName,
- IN UINT32 Mode,
- OUT UINT32 *FileHandle
- );
-
-RETURN_STATUS
-SemihostFileSeek (
- IN UINT32 FileHandle,
- IN UINT32 Offset
- );
-
-RETURN_STATUS
-SemihostFileRead (
- IN UINT32 FileHandle,
- IN OUT UINT32 *Length,
- OUT VOID *Buffer
- );
-
-RETURN_STATUS
-SemihostFileWrite (
- IN UINT32 FileHandle,
- IN OUT UINT32 *Length,
- IN VOID *Buffer
- );
-
-RETURN_STATUS
-SemihostFileClose (
- IN UINT32 FileHandle
- );
-
-RETURN_STATUS
-SemihostFileLength (
- IN UINT32 FileHandle,
- OUT UINT32 *Length
- );
-
-RETURN_STATUS
-SemihostFileRemove (
- IN CHAR8 *FileName
- );
-
-CHAR8
-SemihostReadCharacter (
- VOID
- );
-
-VOID
-SemihostWriteCharacter (
- IN CHAR8 Character
- );
-
-VOID
-SemihostWriteString (
- IN CHAR8 *String
- );
-
-UINT32
-SemihostSystem (
- IN CHAR8 *CommandLine
- );
-
-#endif // __SEMIHOSTING_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __SEMIHOSTING_H__
+#define __SEMIHOSTING_H__
+
+/*
+ *
+ * Please refer to ARM RVDS 3.0 Compiler and Libraries Guide for more information
+ * about the semihosting interface.
+ *
+ */
+
+#define SEMIHOST_FILE_MODE_READ (0 << 2)
+#define SEMIHOST_FILE_MODE_WRITE (1 << 2)
+#define SEMIHOST_FILE_MODE_APPEND (2 << 2)
+#define SEMIHOST_FILE_MODE_CREATE (1 << 1)
+#define SEMIHOST_FILE_MODE_BINARY (1 << 0)
+#define SEMIHOST_FILE_MODE_ASCII (0 << 0)
+
+BOOLEAN
+SemihostConnectionSupported (
+ VOID
+ );
+
+RETURN_STATUS
+SemihostFileOpen (
+ IN CHAR8 *FileName,
+ IN UINT32 Mode,
+ OUT UINT32 *FileHandle
+ );
+
+RETURN_STATUS
+SemihostFileSeek (
+ IN UINT32 FileHandle,
+ IN UINT32 Offset
+ );
+
+RETURN_STATUS
+SemihostFileRead (
+ IN UINT32 FileHandle,
+ IN OUT UINT32 *Length,
+ OUT VOID *Buffer
+ );
+
+RETURN_STATUS
+SemihostFileWrite (
+ IN UINT32 FileHandle,
+ IN OUT UINT32 *Length,
+ IN VOID *Buffer
+ );
+
+RETURN_STATUS
+SemihostFileClose (
+ IN UINT32 FileHandle
+ );
+
+RETURN_STATUS
+SemihostFileLength (
+ IN UINT32 FileHandle,
+ OUT UINT32 *Length
+ );
+
+RETURN_STATUS
+SemihostFileRemove (
+ IN CHAR8 *FileName
+ );
+
+CHAR8
+SemihostReadCharacter (
+ VOID
+ );
+
+VOID
+SemihostWriteCharacter (
+ IN CHAR8 Character
+ );
+
+VOID
+SemihostWriteString (
+ IN CHAR8 *String
+ );
+
+UINT32
+SemihostSystem (
+ IN CHAR8 *CommandLine
+ );
+
+#endif // __SEMIHOSTING_H__
diff --git a/ArmPkg/Include/Library/UncachedMemoryAllocationLib.h b/ArmPkg/Include/Library/UncachedMemoryAllocationLib.h
index ac77fbc69..4161fc7c6 100644
--- a/ArmPkg/Include/Library/UncachedMemoryAllocationLib.h
+++ b/ArmPkg/Include/Library/UncachedMemoryAllocationLib.h
@@ -1,665 +1,665 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __UNCACHED_MEMORY_ALLOCATION_LIB_H__
-#define __UNCACHED_MEMORY_ALLOCATION_LIB_H__
-
-/**
- Converts a cached or uncached address to a physical address suitable for use in SoC registers.
-
- @param VirtualAddress The pointer to convert.
-
- @return The physical address of the supplied virtual pointer.
-
-**/
-EFI_PHYSICAL_ADDRESS
-ConvertToPhysicalAddress (
- IN VOID *VirtualAddress
- );
-
-/**
- Converts a cached or uncached address to a cached address.
-
- @param Address The pointer to convert.
-
- @return The address of the cached memory location corresponding to the input address.
-
-**/
-VOID *
-ConvertToCachedAddress (
- IN VOID *Address
- );
-
-/**
- Converts a cached or uncached address to an uncached address.
-
- @param Address The pointer to convert.
-
- @return The address of the uncached memory location corresponding to the input address.
-
-**/
-VOID *
-ConvertToUncachedAddress (
- IN VOID *Address
- );
-
-/**
- Allocates one or more 4KB pages of type EfiBootServicesData.
-
- Allocates the number of 4KB pages of type EfiBootServicesData and returns a pointer to the
- allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
- is returned. If there is not enough memory remaining to satisfy the request, then NULL is
- returned.
-
- @param Pages The number of 4 KB pages to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocatePages (
- IN UINTN Pages
- );
-
-/**
- Allocates one or more 4KB pages of type EfiRuntimeServicesData.
-
- Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
- allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
- is returned. If there is not enough memory remaining to satisfy the request, then NULL is
- returned.
-
- @param Pages The number of 4 KB pages to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateRuntimePages (
- IN UINTN Pages
- );
-
-/**
- Allocates one or more 4KB pages of type EfiReservedMemoryType.
-
- Allocates the number of 4KB pages of type EfiReservedMemoryType and returns a pointer to the
- allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
- is returned. If there is not enough memory remaining to satisfy the request, then NULL is
- returned.
-
- @param Pages The number of 4 KB pages to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateReservedPages (
- IN UINTN Pages
- );
-
-/**
- Frees one or more 4KB pages that were previously allocated with one of the page allocation
- functions in the Memory Allocation Library.
-
- Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer
- must have been allocated on a previous call to the page allocation services of the Memory
- Allocation Library.
- If Buffer was not allocated with a page allocation function in the Memory Allocation Library,
- then ASSERT().
- If Pages is zero, then ASSERT().
-
- @param Buffer Pointer to the buffer of pages to free.
- @param Pages The number of 4 KB pages to free.
-
-**/
-VOID
-EFIAPI
-UncachedFreePages (
- IN VOID *Buffer,
- IN UINTN Pages
- );
-
-/**
- Allocates one or more 4KB pages of type EfiBootServicesData at a specified alignment.
-
- Allocates the number of 4KB pages specified by Pages of type EfiBootServicesData with an
- alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
- returned. If there is not enough memory at the specified alignment remaining to satisfy the
- request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param Pages The number of 4 KB pages to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedPages (
- IN UINTN Pages,
- IN UINTN Alignment
- );
-
-/**
- Allocates one or more 4KB pages of type EfiRuntimeServicesData at a specified alignment.
-
- Allocates the number of 4KB pages specified by Pages of type EfiRuntimeServicesData with an
- alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
- returned. If there is not enough memory at the specified alignment remaining to satisfy the
- request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param Pages The number of 4 KB pages to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedRuntimePages (
- IN UINTN Pages,
- IN UINTN Alignment
- );
-
-/**
- Allocates one or more 4KB pages of type EfiReservedMemoryType at a specified alignment.
-
- Allocates the number of 4KB pages specified by Pages of type EfiReservedMemoryType with an
- alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
- returned. If there is not enough memory at the specified alignment remaining to satisfy the
- request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param Pages The number of 4 KB pages to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedReservedPages (
- IN UINTN Pages,
- IN UINTN Alignment
- );
-
-/**
- Frees one or more 4KB pages that were previously allocated with one of the aligned page
- allocation functions in the Memory Allocation Library.
-
- Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer
- must have been allocated on a previous call to the aligned page allocation services of the Memory
- Allocation Library.
- If Buffer was not allocated with an aligned page allocation function in the Memory Allocation
- Library, then ASSERT().
- If Pages is zero, then ASSERT().
-
- @param Buffer Pointer to the buffer of pages to free.
- @param Pages The number of 4 KB pages to free.
-
-**/
-VOID
-EFIAPI
-UncachedFreeAlignedPages (
- IN VOID *Buffer,
- IN UINTN Pages
- );
-
-/**
- Allocates a buffer of type EfiBootServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData and returns a
- pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
- returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocatePool (
- IN UINTN AllocationSize
- );
-
-/**
- Allocates a buffer of type EfiRuntimeServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData and returns
- a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
- returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateRuntimePool (
- IN UINTN AllocationSize
- );
-
-/**
- Allocates a buffer of type EfieservedMemoryType.
-
- Allocates the number bytes specified by AllocationSize of type EfieservedMemoryType and returns
- a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
- returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateReservedPool (
- IN UINTN AllocationSize
- );
-
-/**
- Allocates and zeros a buffer of type EfiBootServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, clears the
- buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a
- valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the
- request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate and zero.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateZeroPool (
- IN UINTN AllocationSize
- );
-
-/**
- Allocates and zeros a buffer of type EfiRuntimeServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, clears the
- buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a
- valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the
- request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate and zero.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateRuntimeZeroPool (
- IN UINTN AllocationSize
- );
-
-/**
- Allocates and zeros a buffer of type EfiReservedMemoryType.
-
- Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, clears the
- buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a
- valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the
- request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate and zero.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateReservedZeroPool (
- IN UINTN AllocationSize
- );
-
-/**
- Copies a buffer to an allocated buffer of type EfiBootServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, copies
- AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
- allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
- is not enough memory remaining to satisfy the request, then NULL is returned.
- If Buffer is NULL, then ASSERT().
- If AllocationSize is greater than (MAX_ADDRESS ? Buffer + 1), then ASSERT().
-
- @param AllocationSize The number of bytes to allocate and zero.
- @param Buffer The buffer to copy to the allocated buffer.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateCopyPool (
- IN UINTN AllocationSize,
- IN CONST VOID *Buffer
- );
-
-/**
- Copies a buffer to an allocated buffer of type EfiRuntimeServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, copies
- AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
- allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
- is not enough memory remaining to satisfy the request, then NULL is returned.
- If Buffer is NULL, then ASSERT().
- If AllocationSize is greater than (MAX_ADDRESS ? Buffer + 1), then ASSERT().
-
- @param AllocationSize The number of bytes to allocate and zero.
- @param Buffer The buffer to copy to the allocated buffer.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateRuntimeCopyPool (
- IN UINTN AllocationSize,
- IN CONST VOID *Buffer
- );
-
-/**
- Copies a buffer to an allocated buffer of type EfiReservedMemoryType.
-
- Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, copies
- AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
- allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
- is not enough memory remaining to satisfy the request, then NULL is returned.
- If Buffer is NULL, then ASSERT().
- If AllocationSize is greater than (MAX_ADDRESS ? Buffer + 1), then ASSERT().
-
- @param AllocationSize The number of bytes to allocate and zero.
- @param Buffer The buffer to copy to the allocated buffer.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateReservedCopyPool (
- IN UINTN AllocationSize,
- IN CONST VOID *Buffer
- );
-
-/**
- Frees a buffer that was previously allocated with one of the pool allocation functions in the
- Memory Allocation Library.
-
- Frees the buffer specified by Buffer. Buffer must have been allocated on a previous call to the
- pool allocation services of the Memory Allocation Library.
- If Buffer was not allocated with a pool allocation function in the Memory Allocation Library,
- then ASSERT().
-
- @param Buffer Pointer to the buffer to free.
-
-**/
-VOID
-EFIAPI
-UncachedFreePool (
- IN VOID *Buffer
- );
-
-/**
- Allocates a buffer of type EfiBootServicesData at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData with an
- alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
- then a valid buffer of 0 size is returned. If there is not enough memory at the specified
- alignment remaining to satisfy the request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedPool (
- IN UINTN AllocationSize,
- IN UINTN Alignment
- );
-
-/**
- Allocates a buffer of type EfiRuntimeServicesData at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData with an
- alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
- then a valid buffer of 0 size is returned. If there is not enough memory at the specified
- alignment remaining to satisfy the request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedRuntimePool (
- IN UINTN AllocationSize,
- IN UINTN Alignment
- );
-
-/**
- Allocates a buffer of type EfieservedMemoryType at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfieservedMemoryType with an
- alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
- then a valid buffer of 0 size is returned. If there is not enough memory at the specified
- alignment remaining to satisfy the request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedReservedPool (
- IN UINTN AllocationSize,
- IN UINTN Alignment
- );
-
-/**
- Allocates and zeros a buffer of type EfiBootServicesData at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData with an
- alignment specified by Alignment, clears the buffer with zeros, and returns a pointer to the
- allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
- is not enough memory at the specified alignment remaining to satisfy the request, then NULL is
- returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedZeroPool (
- IN UINTN AllocationSize,
- IN UINTN Alignment
- );
-
-/**
- Allocates and zeros a buffer of type EfiRuntimeServicesData at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData with an
- alignment specified by Alignment, clears the buffer with zeros, and returns a pointer to the
- allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
- is not enough memory at the specified alignment remaining to satisfy the request, then NULL is
- returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedRuntimeZeroPool (
- IN UINTN AllocationSize,
- IN UINTN Alignment
- );
-
-/**
- Allocates and zeros a buffer of type EfieservedMemoryType at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfieservedMemoryType with an
- alignment specified by Alignment, clears the buffer with zeros, and returns a pointer to the
- allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
- is not enough memory at the specified alignment remaining to satisfy the request, then NULL is
- returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedReservedZeroPool (
- IN UINTN AllocationSize,
- IN UINTN Alignment
- );
-
-/**
- Copies a buffer to an allocated buffer of type EfiBootServicesData at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData type with an
- alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
- then a valid buffer of 0 size is returned. If there is not enough memory at the specified
- alignment remaining to satisfy the request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Buffer The buffer to copy to the allocated buffer.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedCopyPool (
- IN UINTN AllocationSize,
- IN CONST VOID *Buffer,
- IN UINTN Alignment
- );
-
-/**
- Copies a buffer to an allocated buffer of type EfiRuntimeServicesData at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData type with an
- alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
- then a valid buffer of 0 size is returned. If there is not enough memory at the specified
- alignment remaining to satisfy the request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Buffer The buffer to copy to the allocated buffer.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedRuntimeCopyPool (
- IN UINTN AllocationSize,
- IN CONST VOID *Buffer,
- IN UINTN Alignment
- );
-
-/**
- Copies a buffer to an allocated buffer of type EfiReservedMemoryType at a specified alignment.
-
- Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType type with an
- alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
- then a valid buffer of 0 size is returned. If there is not enough memory at the specified
- alignment remaining to satisfy the request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param AllocationSize The number of bytes to allocate.
- @param Buffer The buffer to copy to the allocated buffer.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-UncachedAllocateAlignedReservedCopyPool (
- IN UINTN AllocationSize,
- IN CONST VOID *Buffer,
- IN UINTN Alignment
- );
-
-/**
- Frees a buffer that was previously allocated with one of the aligned pool allocation functions
- in the Memory Allocation Library.
-
- Frees the buffer specified by Buffer. Buffer must have been allocated on a previous call to the
- aligned pool allocation services of the Memory Allocation Library.
- If Buffer was not allocated with an aligned pool allocation function in the Memory Allocation
- Library, then ASSERT().
-
- @param Buffer Pointer to the buffer to free.
-
-**/
-VOID
-EFIAPI
-UncachedFreeAlignedPool (
- IN VOID *Buffer
- );
-
-VOID
-EFIAPI
-UncachedSafeFreePool (
- IN VOID *Buffer
- );
-
-#endif // __UNCACHED_MEMORY_ALLOCATION_LIB_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __UNCACHED_MEMORY_ALLOCATION_LIB_H__
+#define __UNCACHED_MEMORY_ALLOCATION_LIB_H__
+
+/**
+ Converts a cached or uncached address to a physical address suitable for use in SoC registers.
+
+ @param VirtualAddress The pointer to convert.
+
+ @return The physical address of the supplied virtual pointer.
+
+**/
+EFI_PHYSICAL_ADDRESS
+ConvertToPhysicalAddress (
+ IN VOID *VirtualAddress
+ );
+
+/**
+ Converts a cached or uncached address to a cached address.
+
+ @param Address The pointer to convert.
+
+ @return The address of the cached memory location corresponding to the input address.
+
+**/
+VOID *
+ConvertToCachedAddress (
+ IN VOID *Address
+ );
+
+/**
+ Converts a cached or uncached address to an uncached address.
+
+ @param Address The pointer to convert.
+
+ @return The address of the uncached memory location corresponding to the input address.
+
+**/
+VOID *
+ConvertToUncachedAddress (
+ IN VOID *Address
+ );
+
+/**
+ Allocates one or more 4KB pages of type EfiBootServicesData.
+
+ Allocates the number of 4KB pages of type EfiBootServicesData and returns a pointer to the
+ allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
+ is returned. If there is not enough memory remaining to satisfy the request, then NULL is
+ returned.
+
+ @param Pages The number of 4 KB pages to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocatePages (
+ IN UINTN Pages
+ );
+
+/**
+ Allocates one or more 4KB pages of type EfiRuntimeServicesData.
+
+ Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
+ allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
+ is returned. If there is not enough memory remaining to satisfy the request, then NULL is
+ returned.
+
+ @param Pages The number of 4 KB pages to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateRuntimePages (
+ IN UINTN Pages
+ );
+
+/**
+ Allocates one or more 4KB pages of type EfiReservedMemoryType.
+
+ Allocates the number of 4KB pages of type EfiReservedMemoryType and returns a pointer to the
+ allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
+ is returned. If there is not enough memory remaining to satisfy the request, then NULL is
+ returned.
+
+ @param Pages The number of 4 KB pages to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateReservedPages (
+ IN UINTN Pages
+ );
+
+/**
+ Frees one or more 4KB pages that were previously allocated with one of the page allocation
+ functions in the Memory Allocation Library.
+
+ Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer
+ must have been allocated on a previous call to the page allocation services of the Memory
+ Allocation Library.
+ If Buffer was not allocated with a page allocation function in the Memory Allocation Library,
+ then ASSERT().
+ If Pages is zero, then ASSERT().
+
+ @param Buffer Pointer to the buffer of pages to free.
+ @param Pages The number of 4 KB pages to free.
+
+**/
+VOID
+EFIAPI
+UncachedFreePages (
+ IN VOID *Buffer,
+ IN UINTN Pages
+ );
+
+/**
+ Allocates one or more 4KB pages of type EfiBootServicesData at a specified alignment.
+
+ Allocates the number of 4KB pages specified by Pages of type EfiBootServicesData with an
+ alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
+ returned. If there is not enough memory at the specified alignment remaining to satisfy the
+ request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param Pages The number of 4 KB pages to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedPages (
+ IN UINTN Pages,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates one or more 4KB pages of type EfiRuntimeServicesData at a specified alignment.
+
+ Allocates the number of 4KB pages specified by Pages of type EfiRuntimeServicesData with an
+ alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
+ returned. If there is not enough memory at the specified alignment remaining to satisfy the
+ request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param Pages The number of 4 KB pages to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedRuntimePages (
+ IN UINTN Pages,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates one or more 4KB pages of type EfiReservedMemoryType at a specified alignment.
+
+ Allocates the number of 4KB pages specified by Pages of type EfiReservedMemoryType with an
+ alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
+ returned. If there is not enough memory at the specified alignment remaining to satisfy the
+ request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param Pages The number of 4 KB pages to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedReservedPages (
+ IN UINTN Pages,
+ IN UINTN Alignment
+ );
+
+/**
+ Frees one or more 4KB pages that were previously allocated with one of the aligned page
+ allocation functions in the Memory Allocation Library.
+
+ Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer
+ must have been allocated on a previous call to the aligned page allocation services of the Memory
+ Allocation Library.
+ If Buffer was not allocated with an aligned page allocation function in the Memory Allocation
+ Library, then ASSERT().
+ If Pages is zero, then ASSERT().
+
+ @param Buffer Pointer to the buffer of pages to free.
+ @param Pages The number of 4 KB pages to free.
+
+**/
+VOID
+EFIAPI
+UncachedFreeAlignedPages (
+ IN VOID *Buffer,
+ IN UINTN Pages
+ );
+
+/**
+ Allocates a buffer of type EfiBootServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData and returns a
+ pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
+ returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocatePool (
+ IN UINTN AllocationSize
+ );
+
+/**
+ Allocates a buffer of type EfiRuntimeServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData and returns
+ a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
+ returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateRuntimePool (
+ IN UINTN AllocationSize
+ );
+
+/**
+ Allocates a buffer of type EfieservedMemoryType.
+
+ Allocates the number bytes specified by AllocationSize of type EfieservedMemoryType and returns
+ a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
+ returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateReservedPool (
+ IN UINTN AllocationSize
+ );
+
+/**
+ Allocates and zeros a buffer of type EfiBootServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, clears the
+ buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a
+ valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the
+ request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate and zero.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateZeroPool (
+ IN UINTN AllocationSize
+ );
+
+/**
+ Allocates and zeros a buffer of type EfiRuntimeServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, clears the
+ buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a
+ valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the
+ request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate and zero.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateRuntimeZeroPool (
+ IN UINTN AllocationSize
+ );
+
+/**
+ Allocates and zeros a buffer of type EfiReservedMemoryType.
+
+ Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, clears the
+ buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a
+ valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the
+ request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate and zero.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateReservedZeroPool (
+ IN UINTN AllocationSize
+ );
+
+/**
+ Copies a buffer to an allocated buffer of type EfiBootServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, copies
+ AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
+ allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
+ is not enough memory remaining to satisfy the request, then NULL is returned.
+ If Buffer is NULL, then ASSERT().
+ If AllocationSize is greater than (MAX_ADDRESS ? Buffer + 1), then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate and zero.
+ @param Buffer The buffer to copy to the allocated buffer.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateCopyPool (
+ IN UINTN AllocationSize,
+ IN CONST VOID *Buffer
+ );
+
+/**
+ Copies a buffer to an allocated buffer of type EfiRuntimeServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, copies
+ AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
+ allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
+ is not enough memory remaining to satisfy the request, then NULL is returned.
+ If Buffer is NULL, then ASSERT().
+ If AllocationSize is greater than (MAX_ADDRESS ? Buffer + 1), then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate and zero.
+ @param Buffer The buffer to copy to the allocated buffer.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateRuntimeCopyPool (
+ IN UINTN AllocationSize,
+ IN CONST VOID *Buffer
+ );
+
+/**
+ Copies a buffer to an allocated buffer of type EfiReservedMemoryType.
+
+ Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, copies
+ AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
+ allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
+ is not enough memory remaining to satisfy the request, then NULL is returned.
+ If Buffer is NULL, then ASSERT().
+ If AllocationSize is greater than (MAX_ADDRESS ? Buffer + 1), then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate and zero.
+ @param Buffer The buffer to copy to the allocated buffer.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateReservedCopyPool (
+ IN UINTN AllocationSize,
+ IN CONST VOID *Buffer
+ );
+
+/**
+ Frees a buffer that was previously allocated with one of the pool allocation functions in the
+ Memory Allocation Library.
+
+ Frees the buffer specified by Buffer. Buffer must have been allocated on a previous call to the
+ pool allocation services of the Memory Allocation Library.
+ If Buffer was not allocated with a pool allocation function in the Memory Allocation Library,
+ then ASSERT().
+
+ @param Buffer Pointer to the buffer to free.
+
+**/
+VOID
+EFIAPI
+UncachedFreePool (
+ IN VOID *Buffer
+ );
+
+/**
+ Allocates a buffer of type EfiBootServicesData at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData with an
+ alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
+ then a valid buffer of 0 size is returned. If there is not enough memory at the specified
+ alignment remaining to satisfy the request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedPool (
+ IN UINTN AllocationSize,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates a buffer of type EfiRuntimeServicesData at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData with an
+ alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
+ then a valid buffer of 0 size is returned. If there is not enough memory at the specified
+ alignment remaining to satisfy the request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedRuntimePool (
+ IN UINTN AllocationSize,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates a buffer of type EfieservedMemoryType at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfieservedMemoryType with an
+ alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
+ then a valid buffer of 0 size is returned. If there is not enough memory at the specified
+ alignment remaining to satisfy the request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedReservedPool (
+ IN UINTN AllocationSize,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates and zeros a buffer of type EfiBootServicesData at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData with an
+ alignment specified by Alignment, clears the buffer with zeros, and returns a pointer to the
+ allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
+ is not enough memory at the specified alignment remaining to satisfy the request, then NULL is
+ returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedZeroPool (
+ IN UINTN AllocationSize,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates and zeros a buffer of type EfiRuntimeServicesData at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData with an
+ alignment specified by Alignment, clears the buffer with zeros, and returns a pointer to the
+ allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
+ is not enough memory at the specified alignment remaining to satisfy the request, then NULL is
+ returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedRuntimeZeroPool (
+ IN UINTN AllocationSize,
+ IN UINTN Alignment
+ );
+
+/**
+ Allocates and zeros a buffer of type EfieservedMemoryType at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfieservedMemoryType with an
+ alignment specified by Alignment, clears the buffer with zeros, and returns a pointer to the
+ allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there
+ is not enough memory at the specified alignment remaining to satisfy the request, then NULL is
+ returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedReservedZeroPool (
+ IN UINTN AllocationSize,
+ IN UINTN Alignment
+ );
+
+/**
+ Copies a buffer to an allocated buffer of type EfiBootServicesData at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData type with an
+ alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
+ then a valid buffer of 0 size is returned. If there is not enough memory at the specified
+ alignment remaining to satisfy the request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Buffer The buffer to copy to the allocated buffer.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedCopyPool (
+ IN UINTN AllocationSize,
+ IN CONST VOID *Buffer,
+ IN UINTN Alignment
+ );
+
+/**
+ Copies a buffer to an allocated buffer of type EfiRuntimeServicesData at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData type with an
+ alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
+ then a valid buffer of 0 size is returned. If there is not enough memory at the specified
+ alignment remaining to satisfy the request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Buffer The buffer to copy to the allocated buffer.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedRuntimeCopyPool (
+ IN UINTN AllocationSize,
+ IN CONST VOID *Buffer,
+ IN UINTN Alignment
+ );
+
+/**
+ Copies a buffer to an allocated buffer of type EfiReservedMemoryType at a specified alignment.
+
+ Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType type with an
+ alignment specified by Alignment. The allocated buffer is returned. If AllocationSize is 0,
+ then a valid buffer of 0 size is returned. If there is not enough memory at the specified
+ alignment remaining to satisfy the request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param AllocationSize The number of bytes to allocate.
+ @param Buffer The buffer to copy to the allocated buffer.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+UncachedAllocateAlignedReservedCopyPool (
+ IN UINTN AllocationSize,
+ IN CONST VOID *Buffer,
+ IN UINTN Alignment
+ );
+
+/**
+ Frees a buffer that was previously allocated with one of the aligned pool allocation functions
+ in the Memory Allocation Library.
+
+ Frees the buffer specified by Buffer. Buffer must have been allocated on a previous call to the
+ aligned pool allocation services of the Memory Allocation Library.
+ If Buffer was not allocated with an aligned pool allocation function in the Memory Allocation
+ Library, then ASSERT().
+
+ @param Buffer Pointer to the buffer to free.
+
+**/
+VOID
+EFIAPI
+UncachedFreeAlignedPool (
+ IN VOID *Buffer
+ );
+
+VOID
+EFIAPI
+UncachedSafeFreePool (
+ IN VOID *Buffer
+ );
+
+#endif // __UNCACHED_MEMORY_ALLOCATION_LIB_H__
diff --git a/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.c b/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.c
index 0dd453003..2557a2cf0 100644
--- a/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.c
+++ b/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.c
@@ -1,125 +1,125 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-#include <Base.h>
-#include <Library/ArmLib.h>
-#include <Library/PcdLib.h>
-
-VOID
-CacheRangeOperation (
- IN VOID *Start,
- IN UINTN Length,
- IN CACHE_OPERATION CacheOperation,
- IN LINE_OPERATION LineOperation
- )
-{
- UINTN ArmCacheLineLength = ArmDataCacheLineLength();
- UINTN ArmCacheLineAlignmentMask = ArmCacheLineLength - 1;
- UINTN ArmCacheOperationThreshold = PcdGet32(PcdArmCacheOperationThreshold);
-
- if ((CacheOperation != NULL) && (Length >= ArmCacheOperationThreshold)) {
- CacheOperation ();
- } else {
- // Align address (rounding down)
- UINTN AlignedAddress = (UINTN)Start - ((UINTN)Start & ArmCacheLineAlignmentMask);
- UINTN EndAddress = (UINTN)Start + Length;
-
- // Perform the line operation on an address in each cache line
- while (AlignedAddress < EndAddress) {
- LineOperation(AlignedAddress);
- AlignedAddress += ArmCacheLineLength;
- }
- }
-}
-
-VOID
-EFIAPI
-InvalidateInstructionCache (
- VOID
- )
-{
- ArmCleanDataCache();
- ArmInvalidateInstructionCache();
-}
-
-VOID
-EFIAPI
-InvalidateDataCache (
- VOID
- )
-{
- ArmInvalidateDataCache();
-}
-
-VOID *
-EFIAPI
-InvalidateInstructionCacheRange (
- IN VOID *Address,
- IN UINTN Length
- )
-{
- CacheRangeOperation (Address, Length, ArmCleanDataCacheToPoU, ArmCleanDataCacheEntryByMVA);
- ArmInvalidateInstructionCache ();
- return Address;
-}
-
-VOID
-EFIAPI
-WriteBackInvalidateDataCache (
- VOID
- )
-{
- ArmCleanInvalidateDataCache();
-}
-
-VOID *
-EFIAPI
-WriteBackInvalidateDataCacheRange (
- IN VOID *Address,
- IN UINTN Length
- )
-{
- CacheRangeOperation(Address, Length, ArmCleanInvalidateDataCache, ArmCleanInvalidateDataCacheEntryByMVA);
- return Address;
-}
-
-VOID
-EFIAPI
-WriteBackDataCache (
- VOID
- )
-{
- ArmCleanDataCache();
-}
-
-VOID *
-EFIAPI
-WriteBackDataCacheRange (
- IN VOID *Address,
- IN UINTN Length
- )
-{
- CacheRangeOperation(Address, Length, ArmCleanDataCache, ArmCleanDataCacheEntryByMVA);
- return Address;
-}
-
-VOID *
-EFIAPI
-InvalidateDataCacheRange (
- IN VOID *Address,
- IN UINTN Length
- )
-{
- CacheRangeOperation(Address, Length, NULL, ArmInvalidateDataCacheEntryByMVA);
- return Address;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+#include <Base.h>
+#include <Library/ArmLib.h>
+#include <Library/PcdLib.h>
+
+VOID
+CacheRangeOperation (
+ IN VOID *Start,
+ IN UINTN Length,
+ IN CACHE_OPERATION CacheOperation,
+ IN LINE_OPERATION LineOperation
+ )
+{
+ UINTN ArmCacheLineLength = ArmDataCacheLineLength();
+ UINTN ArmCacheLineAlignmentMask = ArmCacheLineLength - 1;
+ UINTN ArmCacheOperationThreshold = PcdGet32(PcdArmCacheOperationThreshold);
+
+ if ((CacheOperation != NULL) && (Length >= ArmCacheOperationThreshold)) {
+ CacheOperation ();
+ } else {
+ // Align address (rounding down)
+ UINTN AlignedAddress = (UINTN)Start - ((UINTN)Start & ArmCacheLineAlignmentMask);
+ UINTN EndAddress = (UINTN)Start + Length;
+
+ // Perform the line operation on an address in each cache line
+ while (AlignedAddress < EndAddress) {
+ LineOperation(AlignedAddress);
+ AlignedAddress += ArmCacheLineLength;
+ }
+ }
+}
+
+VOID
+EFIAPI
+InvalidateInstructionCache (
+ VOID
+ )
+{
+ ArmCleanDataCache();
+ ArmInvalidateInstructionCache();
+}
+
+VOID
+EFIAPI
+InvalidateDataCache (
+ VOID
+ )
+{
+ ArmInvalidateDataCache();
+}
+
+VOID *
+EFIAPI
+InvalidateInstructionCacheRange (
+ IN VOID *Address,
+ IN UINTN Length
+ )
+{
+ CacheRangeOperation (Address, Length, ArmCleanDataCacheToPoU, ArmCleanDataCacheEntryByMVA);
+ ArmInvalidateInstructionCache ();
+ return Address;
+}
+
+VOID
+EFIAPI
+WriteBackInvalidateDataCache (
+ VOID
+ )
+{
+ ArmCleanInvalidateDataCache();
+}
+
+VOID *
+EFIAPI
+WriteBackInvalidateDataCacheRange (
+ IN VOID *Address,
+ IN UINTN Length
+ )
+{
+ CacheRangeOperation(Address, Length, ArmCleanInvalidateDataCache, ArmCleanInvalidateDataCacheEntryByMVA);
+ return Address;
+}
+
+VOID
+EFIAPI
+WriteBackDataCache (
+ VOID
+ )
+{
+ ArmCleanDataCache();
+}
+
+VOID *
+EFIAPI
+WriteBackDataCacheRange (
+ IN VOID *Address,
+ IN UINTN Length
+ )
+{
+ CacheRangeOperation(Address, Length, ArmCleanDataCache, ArmCleanDataCacheEntryByMVA);
+ return Address;
+}
+
+VOID *
+EFIAPI
+InvalidateDataCacheRange (
+ IN VOID *Address,
+ IN UINTN Length
+ )
+{
+ CacheRangeOperation(Address, Length, NULL, ArmInvalidateDataCacheEntryByMVA);
+ return Address;
+}
diff --git a/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf b/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
index 12470480d..7a43bfe9b 100644
--- a/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
+++ b/ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
@@ -1,37 +1,37 @@
-#/** @file
-# Semihosting serail port lib
-#
-# Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmCacheMaintenanceLib
- FILE_GUID = 1A20BE1F-33AD-450C-B49A-7123FCA8B7F9
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = CacheMaintenanceLib
-
-[Sources.common]
- ArmCacheMaintenanceLib.c
-
-[Packages]
- ArmPkg/ArmPkg.dec
- MdePkg/MdePkg.dec
-
-[LibraryClasses]
- ArmLib
- BaseLib
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdArmCacheOperationThreshold
-
+#/** @file
+# Semihosting serail port lib
+#
+# Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmCacheMaintenanceLib
+ FILE_GUID = 1A20BE1F-33AD-450C-B49A-7123FCA8B7F9
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = CacheMaintenanceLib
+
+[Sources.common]
+ ArmCacheMaintenanceLib.c
+
+[Packages]
+ ArmPkg/ArmPkg.dec
+ MdePkg/MdePkg.dec
+
+[LibraryClasses]
+ ArmLib
+ BaseLib
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdArmCacheOperationThreshold
+
diff --git a/ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf b/ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
index 5c809ba3a..546569511 100755
--- a/ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
+++ b/ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
@@ -47,4 +47,4 @@
[Pcd]
[Depex]
- gEfiCpuArchProtocolGuid \ No newline at end of file
+ gEfiCpuArchProtocolGuid \ No newline at end of file
diff --git a/ArmPkg/Library/ArmLib/Arm11/Arm11LibMem.c b/ArmPkg/Library/ArmLib/Arm11/Arm11LibMem.c
index 86427035e..c683861cb 100644
--- a/ArmPkg/Library/ArmLib/Arm11/Arm11LibMem.c
+++ b/ArmPkg/Library/ArmLib/Arm11/Arm11LibMem.c
@@ -1,133 +1,133 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Chipset/ARM1176JZ-S.h>
-#include <Library/ArmLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-
-VOID
-FillTranslationTable (
- IN UINT32 *TranslationTable,
- IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryRegion
- )
-{
- UINT32 *Entry;
- UINTN Sections;
- UINTN Index;
- UINT32 Attributes;
- UINT32 PhysicalBase = MemoryRegion->PhysicalBase;
-
- switch (MemoryRegion->Attributes) {
- case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK:
- Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK(0);
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH:
- Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH(0);
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED:
- Attributes = TT_DESCRIPTOR_SECTION_UNCACHED(0);
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK:
- Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK(1);
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH:
- Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH(1);
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED:
- Attributes = TT_DESCRIPTOR_SECTION_UNCACHED(1);
- break;
- default:
- Attributes = TT_DESCRIPTOR_SECTION_UNCACHED(0);
- break;
- }
-
- Entry = TRANSLATION_TABLE_ENTRY_FOR_VIRTUAL_ADDRESS(TranslationTable, MemoryRegion->VirtualBase);
- Sections = ((( MemoryRegion->Length - 1 ) / TT_DESCRIPTOR_SECTION_SIZE ) + 1 );
-
- for (Index = 0; Index < Sections; Index++)
- {
- *Entry++ = TT_DESCRIPTOR_SECTION_BASE_ADDRESS(PhysicalBase) | Attributes;
- PhysicalBase += TT_DESCRIPTOR_SECTION_SIZE;
- }
-}
-
-VOID
-EFIAPI
-ArmConfigureMmu (
- IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable,
- OUT VOID **TranslationTableBase OPTIONAL,
- OUT UINTN *TranslationTableSize OPTIONAL
- )
-{
- VOID *TranslationTable;
-
- // Allocate pages for translation table.
- TranslationTable = AllocatePages(EFI_SIZE_TO_PAGES(TRANSLATION_TABLE_SIZE + TRANSLATION_TABLE_ALIGNMENT));
- TranslationTable = (VOID *)(((UINTN)TranslationTable + TRANSLATION_TABLE_ALIGNMENT_MASK) & ~TRANSLATION_TABLE_ALIGNMENT_MASK);
-
- if (TranslationTableBase != NULL) {
- *TranslationTableBase = TranslationTable;
- }
-
- if (TranslationTableBase != NULL) {
- *TranslationTableSize = TRANSLATION_TABLE_SIZE;
- }
-
- ZeroMem(TranslationTable, TRANSLATION_TABLE_SIZE);
-
- ArmCleanInvalidateDataCache();
- ArmInvalidateInstructionCache();
- ArmInvalidateTlb();
-
- ArmDisableDataCache();
- ArmDisableInstructionCache();
- ArmDisableMmu();
-
- // Make sure nothing sneaked into the cache
- ArmCleanInvalidateDataCache();
- ArmInvalidateInstructionCache();
-
- while (MemoryTable->Length != 0) {
- FillTranslationTable(TranslationTable, MemoryTable);
- MemoryTable++;
- }
-
- ArmSetTTBR0(TranslationTable);
-
- ArmSetDomainAccessControl(DOMAIN_ACCESS_CONTROL_NONE(15) |
- DOMAIN_ACCESS_CONTROL_NONE(14) |
- DOMAIN_ACCESS_CONTROL_NONE(13) |
- DOMAIN_ACCESS_CONTROL_NONE(12) |
- DOMAIN_ACCESS_CONTROL_NONE(11) |
- DOMAIN_ACCESS_CONTROL_NONE(10) |
- DOMAIN_ACCESS_CONTROL_NONE( 9) |
- DOMAIN_ACCESS_CONTROL_NONE( 8) |
- DOMAIN_ACCESS_CONTROL_NONE( 7) |
- DOMAIN_ACCESS_CONTROL_NONE( 6) |
- DOMAIN_ACCESS_CONTROL_NONE( 5) |
- DOMAIN_ACCESS_CONTROL_NONE( 4) |
- DOMAIN_ACCESS_CONTROL_NONE( 3) |
- DOMAIN_ACCESS_CONTROL_NONE( 2) |
- DOMAIN_ACCESS_CONTROL_NONE( 1) |
- DOMAIN_ACCESS_CONTROL_MANAGER(0));
-
- ArmEnableInstructionCache();
- ArmEnableDataCache();
- ArmEnableMmu();
-}
-
-
-
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Chipset/ARM1176JZ-S.h>
+#include <Library/ArmLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+
+VOID
+FillTranslationTable (
+ IN UINT32 *TranslationTable,
+ IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryRegion
+ )
+{
+ UINT32 *Entry;
+ UINTN Sections;
+ UINTN Index;
+ UINT32 Attributes;
+ UINT32 PhysicalBase = MemoryRegion->PhysicalBase;
+
+ switch (MemoryRegion->Attributes) {
+ case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK:
+ Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK(0);
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH:
+ Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH(0);
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED:
+ Attributes = TT_DESCRIPTOR_SECTION_UNCACHED(0);
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK:
+ Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK(1);
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH:
+ Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH(1);
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED:
+ Attributes = TT_DESCRIPTOR_SECTION_UNCACHED(1);
+ break;
+ default:
+ Attributes = TT_DESCRIPTOR_SECTION_UNCACHED(0);
+ break;
+ }
+
+ Entry = TRANSLATION_TABLE_ENTRY_FOR_VIRTUAL_ADDRESS(TranslationTable, MemoryRegion->VirtualBase);
+ Sections = ((( MemoryRegion->Length - 1 ) / TT_DESCRIPTOR_SECTION_SIZE ) + 1 );
+
+ for (Index = 0; Index < Sections; Index++)
+ {
+ *Entry++ = TT_DESCRIPTOR_SECTION_BASE_ADDRESS(PhysicalBase) | Attributes;
+ PhysicalBase += TT_DESCRIPTOR_SECTION_SIZE;
+ }
+}
+
+VOID
+EFIAPI
+ArmConfigureMmu (
+ IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable,
+ OUT VOID **TranslationTableBase OPTIONAL,
+ OUT UINTN *TranslationTableSize OPTIONAL
+ )
+{
+ VOID *TranslationTable;
+
+ // Allocate pages for translation table.
+ TranslationTable = AllocatePages(EFI_SIZE_TO_PAGES(TRANSLATION_TABLE_SIZE + TRANSLATION_TABLE_ALIGNMENT));
+ TranslationTable = (VOID *)(((UINTN)TranslationTable + TRANSLATION_TABLE_ALIGNMENT_MASK) & ~TRANSLATION_TABLE_ALIGNMENT_MASK);
+
+ if (TranslationTableBase != NULL) {
+ *TranslationTableBase = TranslationTable;
+ }
+
+ if (TranslationTableBase != NULL) {
+ *TranslationTableSize = TRANSLATION_TABLE_SIZE;
+ }
+
+ ZeroMem(TranslationTable, TRANSLATION_TABLE_SIZE);
+
+ ArmCleanInvalidateDataCache();
+ ArmInvalidateInstructionCache();
+ ArmInvalidateTlb();
+
+ ArmDisableDataCache();
+ ArmDisableInstructionCache();
+ ArmDisableMmu();
+
+ // Make sure nothing sneaked into the cache
+ ArmCleanInvalidateDataCache();
+ ArmInvalidateInstructionCache();
+
+ while (MemoryTable->Length != 0) {
+ FillTranslationTable(TranslationTable, MemoryTable);
+ MemoryTable++;
+ }
+
+ ArmSetTTBR0(TranslationTable);
+
+ ArmSetDomainAccessControl(DOMAIN_ACCESS_CONTROL_NONE(15) |
+ DOMAIN_ACCESS_CONTROL_NONE(14) |
+ DOMAIN_ACCESS_CONTROL_NONE(13) |
+ DOMAIN_ACCESS_CONTROL_NONE(12) |
+ DOMAIN_ACCESS_CONTROL_NONE(11) |
+ DOMAIN_ACCESS_CONTROL_NONE(10) |
+ DOMAIN_ACCESS_CONTROL_NONE( 9) |
+ DOMAIN_ACCESS_CONTROL_NONE( 8) |
+ DOMAIN_ACCESS_CONTROL_NONE( 7) |
+ DOMAIN_ACCESS_CONTROL_NONE( 6) |
+ DOMAIN_ACCESS_CONTROL_NONE( 5) |
+ DOMAIN_ACCESS_CONTROL_NONE( 4) |
+ DOMAIN_ACCESS_CONTROL_NONE( 3) |
+ DOMAIN_ACCESS_CONTROL_NONE( 2) |
+ DOMAIN_ACCESS_CONTROL_NONE( 1) |
+ DOMAIN_ACCESS_CONTROL_MANAGER(0));
+
+ ArmEnableInstructionCache();
+ ArmEnableDataCache();
+ ArmEnableMmu();
+}
+
+
+
+
diff --git a/ArmPkg/Library/ArmLib/Arm11/Arm11Support.S b/ArmPkg/Library/ArmLib/Arm11/Arm11Support.S
index 7ff377c02..2f4be7e93 100644
--- a/ArmPkg/Library/ArmLib/Arm11/Arm11Support.S
+++ b/ArmPkg/Library/ArmLib/Arm11/Arm11Support.S
@@ -1,262 +1,262 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-#include <AsmMacroIoLib.h>
-
-.text
-.align 2
-GCC_ASM_EXPORT(ArmDisableCachesAndMmu)
-GCC_ASM_EXPORT(ArmInvalidateInstructionAndDataTlb)
-GCC_ASM_EXPORT(ArmCleanInvalidateDataCache)
-GCC_ASM_EXPORT(ArmCleanDataCache)
-GCC_ASM_EXPORT(ArmInvalidateDataCache)
-GCC_ASM_EXPORT(ArmInvalidateInstructionCache)
-GCC_ASM_EXPORT(ArmInvalidateDataCacheEntryByMVA)
-GCC_ASM_EXPORT(ArmCleanDataCacheEntryByMVA)
-GCC_ASM_EXPORT(ArmCleanInvalidateDataCacheEntryByMVA)
-GCC_ASM_EXPORT(ArmEnableMmu)
-GCC_ASM_EXPORT(ArmDisableMmu)
-GCC_ASM_EXPORT(ArmMmuEnabled)
-GCC_ASM_EXPORT(ArmEnableDataCache)
-GCC_ASM_EXPORT(ArmDisableDataCache)
-GCC_ASM_EXPORT(ArmEnableInstructionCache)
-GCC_ASM_EXPORT(ArmDisableInstructionCache)
-GCC_ASM_EXPORT(ArmEnableBranchPrediction)
-GCC_ASM_EXPORT(ArmDisableBranchPrediction)
-GCC_ASM_EXPORT(ArmDataMemoryBarrier)
-GCC_ASM_EXPORT(ArmDataSyncronizationBarrier)
-GCC_ASM_EXPORT(ArmInstructionSynchronizationBarrier)
-GCC_ASM_EXPORT(ArmSetLowVectors)
-GCC_ASM_EXPORT(ArmSetHighVectors)
-GCC_ASM_EXPORT(ArmIsMpCore)
-GCC_ASM_EXPORT(ArmCallWFI)
-GCC_ASM_EXPORT(ArmReadMpidr)
-GCC_ASM_EXPORT(ArmUpdateTranslationTableEntry)
-GCC_ASM_EXPORT(ArmEnableFiq)
-GCC_ASM_EXPORT(ArmDisableFiq)
-GCC_ASM_EXPORT(ArmEnableInterrupts)
-GCC_ASM_EXPORT(ArmDisableInterrupts)
-GCC_ASM_EXPORT (ArmEnableVFP)
-
-Arm11PartNumberMask: .word 0xFFF0
-Arm11PartNumber: .word 0xB020
-
-.set DC_ON, (0x1<<2)
-.set IC_ON, (0x1<<12)
-.set XP_ON, (0x1<<23)
-.set CTRL_M_BIT, (1 << 0)
-.set CTRL_C_BIT, (1 << 2)
-.set CTRL_I_BIT, (1 << 12)
-
-ASM_PFX(ArmDisableCachesAndMmu):
- mrc p15, 0, r0, c1, c0, 0 @ Get control register
- bic r0, r0, #CTRL_M_BIT @ Disable MMU
- bic r0, r0, #CTRL_C_BIT @ Disable D Cache
- bic r0, r0, #CTRL_I_BIT @ Disable I Cache
- mcr p15, 0, r0, c1, c0, 0 @ Write control register
- bx LR
-
-ASM_PFX(ArmInvalidateInstructionAndDataTlb):
- mcr p15, 0, r0, c8, c7, 0 @ Invalidate Inst TLB and Data TLB
- bx lr
-
-ASM_PFX(ArmInvalidateDataCacheEntryByMVA):
- mcr p15, 0, r0, c7, c6, 1 @invalidate single data cache line
- bx lr
-
-
-ASM_PFX(ArmCleanDataCacheEntryByMVA):
- mcr p15, 0, r0, c7, c10, 1 @clean single data cache line
- bx lr
-
-
-ASM_PFX(ArmCleanInvalidateDataCacheEntryByMVA):
- mcr p15, 0, r0, c7, c14, 1 @clean and invalidate single data cache line
- bx lr
-
-
-ASM_PFX(ArmCleanDataCache):
- mcr p15, 0, r0, c7, c10, 0 @ clean entire data cache
- bx lr
-
-
-ASM_PFX(ArmCleanInvalidateDataCache):
- mcr p15, 0, r0, c7, c14, 0 @ clean and invalidate entire data cache
- bx lr
-
-
-ASM_PFX(ArmInvalidateDataCache):
- mcr p15, 0, r0, c7, c6, 0 @ invalidate entire data cache
- bx lr
-
-
-ASM_PFX(ArmInvalidateInstructionCache):
- mcr p15, 0, r0, c7, c5, 0 @invalidate entire instruction cache
- mov R0,#0
- mcr p15,0,R0,c7,c5,4 @Flush Prefetch buffer
- bx lr
-
-ASM_PFX(ArmEnableMmu):
- mrc p15,0,R0,c1,c0,0
- orr R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- bx LR
-
-ASM_PFX(ArmMmuEnabled):
- mrc p15,0,R0,c1,c0,0
- and R0,R0,#1
- bx LR
-
-ASM_PFX(ArmDisableMmu):
- mrc p15,0,R0,c1,c0,0
- bic R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 @Data synchronization barrier
- mov R0,#0
- mcr p15,0,R0,c7,c5,4 @Flush Prefetch buffer
- bx LR
-
-ASM_PFX(ArmEnableDataCache):
- LoadConstantToReg(DC_ON, R1) @ldr R1,=DC_ON
- mrc p15,0,R0,c1,c0,0 @Read control register configuration data
- orr R0,R0,R1 @Set C bit
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmDisableDataCache):
- LoadConstantToReg(DC_ON, R1) @ldr R1,=DC_ON
- mrc p15,0,R0,c1,c0,0 @Read control register configuration data
- bic R0,R0,R1 @Clear C bit
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmEnableInstructionCache):
- ldr R1,=IC_ON
- mrc p15,0,R0,c1,c0,0 @Read control register configuration data
- orr R0,R0,R1 @Set I bit
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmDisableInstructionCache):
- ldr R1,=IC_ON
- mrc p15,0,R0,c1,c0,0 @Read control register configuration data
- bic R0,R0,R1 @Clear I bit.
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmEnableBranchPrediction):
- mrc p15, 0, r0, c1, c0, 0
- orr r0, r0, #0x00000800
- mcr p15, 0, r0, c1, c0, 0
- bx LR
-
-ASM_PFX(ArmDisableBranchPrediction):
- mrc p15, 0, r0, c1, c0, 0
- bic r0, r0, #0x00000800
- mcr p15, 0, r0, c1, c0, 0
- bx LR
-
-ASM_PFX(ArmDataMemoryBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #5
- bx LR
-
-ASM_PFX(ArmDataSyncronizationBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #4
- bx LR
-
-ASM_PFX(ArmInstructionSynchronizationBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C5, #4
- bx LR
-
-ASM_PFX(ArmSetLowVectors):
- mrc p15, 0, r0, c1, c0, 0 @ Read SCTLR into R0 (Read control register configuration data)
- bic r0, r0, #0x00002000 @ clear V bit
- mcr p15, 0, r0, c1, c0, 0 @ Write R0 into SCTLR (Write control register configuration data)
- bx LR
-
-ASM_PFX(ArmSetHighVectors):
- mrc p15, 0, r0, c1, c0, 0 @ Read SCTLR into R0 (Read control register configuration data)
- orr r0, r0, #0x00002000 @ clear V bit
- mcr p15, 0, r0, c1, c0, 0 @ Write R0 into SCTLR (Write control register configuration data)
- bx LR
-
-ASM_PFX(ArmIsMpCore):
- push { r1 }
- mrc p15, 0, r0, c0, c0, 0
- # Extract Part Number to check it is an ARM11MP core (0xB02)
- LoadConstantToReg (Arm11PartNumberMask, r1)
- and r0, r0, r1
- LoadConstantToReg (Arm11PartNumber, r1)
- cmp r0, r1
- movne r0, #0
- pop { r1 }
- bx lr
-
-ASM_PFX(ArmCallWFI):
- wfi
- bx lr
-
-ASM_PFX(ArmReadMpidr):
- mrc p15, 0, r0, c0, c0, 5 @ read MPIDR
- bx lr
-
-ASM_PFX(ArmEnableFiq):
- mrs R0,CPSR
- bic R0,R0,#0x40 @Enable FIQ interrupts
- msr CPSR_c,R0
- bx LR
-
-ASM_PFX(ArmDisableFiq):
- mrs R0,CPSR
- orr R1,R0,#0x40 @Disable FIQ interrupts
- msr CPSR_c,R1
- tst R0,#0x80
- moveq R0,#1
- movne R0,#0
- bx LR
-
-ASM_PFX(ArmEnableInterrupts):
- mrs R0,CPSR
- bic R0,R0,#0x80 @Enable IRQ interrupts
- msr CPSR_c,R0
- bx LR
-
-ASM_PFX(ArmDisableInterrupts):
- mrs R0,CPSR
- orr R1,R0,#0x80 @Disable IRQ interrupts
- msr CPSR_c,R1
- tst R0,#0x80
- moveq R0,#1
- movne R0,#0
- bx LR
-
-ASM_PFX(ArmEnableVFP):
- # Read CPACR (Coprocessor Access Control Register)
- mrc p15, 0, r0, c1, c0, 2
- # Enable VPF access (Full Access to CP10, CP11) (V* instructions)
- orr r0, r0, #0x00f00000
- # Write back CPACR (Coprocessor Access Control Register)
- mcr p15, 0, r0, c1, c0, 2
- # Set EN bit in FPEXC. The Advanced SIMD and VFP extensions are enabled and operate normally.
- mov r0, #0x40000000
- #TODO: Fixme - need compilation flag
- #fmxr FPEXC, r0
- bx lr
-
-ASM_FUNCTION_REMOVE_IF_UNREFERENCED
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+# Copyright (c) 2011, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+#include <AsmMacroIoLib.h>
+
+.text
+.align 2
+GCC_ASM_EXPORT(ArmDisableCachesAndMmu)
+GCC_ASM_EXPORT(ArmInvalidateInstructionAndDataTlb)
+GCC_ASM_EXPORT(ArmCleanInvalidateDataCache)
+GCC_ASM_EXPORT(ArmCleanDataCache)
+GCC_ASM_EXPORT(ArmInvalidateDataCache)
+GCC_ASM_EXPORT(ArmInvalidateInstructionCache)
+GCC_ASM_EXPORT(ArmInvalidateDataCacheEntryByMVA)
+GCC_ASM_EXPORT(ArmCleanDataCacheEntryByMVA)
+GCC_ASM_EXPORT(ArmCleanInvalidateDataCacheEntryByMVA)
+GCC_ASM_EXPORT(ArmEnableMmu)
+GCC_ASM_EXPORT(ArmDisableMmu)
+GCC_ASM_EXPORT(ArmMmuEnabled)
+GCC_ASM_EXPORT(ArmEnableDataCache)
+GCC_ASM_EXPORT(ArmDisableDataCache)
+GCC_ASM_EXPORT(ArmEnableInstructionCache)
+GCC_ASM_EXPORT(ArmDisableInstructionCache)
+GCC_ASM_EXPORT(ArmEnableBranchPrediction)
+GCC_ASM_EXPORT(ArmDisableBranchPrediction)
+GCC_ASM_EXPORT(ArmDataMemoryBarrier)
+GCC_ASM_EXPORT(ArmDataSyncronizationBarrier)
+GCC_ASM_EXPORT(ArmInstructionSynchronizationBarrier)
+GCC_ASM_EXPORT(ArmSetLowVectors)
+GCC_ASM_EXPORT(ArmSetHighVectors)
+GCC_ASM_EXPORT(ArmIsMpCore)
+GCC_ASM_EXPORT(ArmCallWFI)
+GCC_ASM_EXPORT(ArmReadMpidr)
+GCC_ASM_EXPORT(ArmUpdateTranslationTableEntry)
+GCC_ASM_EXPORT(ArmEnableFiq)
+GCC_ASM_EXPORT(ArmDisableFiq)
+GCC_ASM_EXPORT(ArmEnableInterrupts)
+GCC_ASM_EXPORT(ArmDisableInterrupts)
+GCC_ASM_EXPORT (ArmEnableVFP)
+
+Arm11PartNumberMask: .word 0xFFF0
+Arm11PartNumber: .word 0xB020
+
+.set DC_ON, (0x1<<2)
+.set IC_ON, (0x1<<12)
+.set XP_ON, (0x1<<23)
+.set CTRL_M_BIT, (1 << 0)
+.set CTRL_C_BIT, (1 << 2)
+.set CTRL_I_BIT, (1 << 12)
+
+ASM_PFX(ArmDisableCachesAndMmu):
+ mrc p15, 0, r0, c1, c0, 0 @ Get control register
+ bic r0, r0, #CTRL_M_BIT @ Disable MMU
+ bic r0, r0, #CTRL_C_BIT @ Disable D Cache
+ bic r0, r0, #CTRL_I_BIT @ Disable I Cache
+ mcr p15, 0, r0, c1, c0, 0 @ Write control register
+ bx LR
+
+ASM_PFX(ArmInvalidateInstructionAndDataTlb):
+ mcr p15, 0, r0, c8, c7, 0 @ Invalidate Inst TLB and Data TLB
+ bx lr
+
+ASM_PFX(ArmInvalidateDataCacheEntryByMVA):
+ mcr p15, 0, r0, c7, c6, 1 @invalidate single data cache line
+ bx lr
+
+
+ASM_PFX(ArmCleanDataCacheEntryByMVA):
+ mcr p15, 0, r0, c7, c10, 1 @clean single data cache line
+ bx lr
+
+
+ASM_PFX(ArmCleanInvalidateDataCacheEntryByMVA):
+ mcr p15, 0, r0, c7, c14, 1 @clean and invalidate single data cache line
+ bx lr
+
+
+ASM_PFX(ArmCleanDataCache):
+ mcr p15, 0, r0, c7, c10, 0 @ clean entire data cache
+ bx lr
+
+
+ASM_PFX(ArmCleanInvalidateDataCache):
+ mcr p15, 0, r0, c7, c14, 0 @ clean and invalidate entire data cache
+ bx lr
+
+
+ASM_PFX(ArmInvalidateDataCache):
+ mcr p15, 0, r0, c7, c6, 0 @ invalidate entire data cache
+ bx lr
+
+
+ASM_PFX(ArmInvalidateInstructionCache):
+ mcr p15, 0, r0, c7, c5, 0 @invalidate entire instruction cache
+ mov R0,#0
+ mcr p15,0,R0,c7,c5,4 @Flush Prefetch buffer
+ bx lr
+
+ASM_PFX(ArmEnableMmu):
+ mrc p15,0,R0,c1,c0,0
+ orr R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ bx LR
+
+ASM_PFX(ArmMmuEnabled):
+ mrc p15,0,R0,c1,c0,0
+ and R0,R0,#1
+ bx LR
+
+ASM_PFX(ArmDisableMmu):
+ mrc p15,0,R0,c1,c0,0
+ bic R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 @Data synchronization barrier
+ mov R0,#0
+ mcr p15,0,R0,c7,c5,4 @Flush Prefetch buffer
+ bx LR
+
+ASM_PFX(ArmEnableDataCache):
+ LoadConstantToReg(DC_ON, R1) @ldr R1,=DC_ON
+ mrc p15,0,R0,c1,c0,0 @Read control register configuration data
+ orr R0,R0,R1 @Set C bit
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmDisableDataCache):
+ LoadConstantToReg(DC_ON, R1) @ldr R1,=DC_ON
+ mrc p15,0,R0,c1,c0,0 @Read control register configuration data
+ bic R0,R0,R1 @Clear C bit
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmEnableInstructionCache):
+ ldr R1,=IC_ON
+ mrc p15,0,R0,c1,c0,0 @Read control register configuration data
+ orr R0,R0,R1 @Set I bit
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmDisableInstructionCache):
+ ldr R1,=IC_ON
+ mrc p15,0,R0,c1,c0,0 @Read control register configuration data
+ bic R0,R0,R1 @Clear I bit.
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmEnableBranchPrediction):
+ mrc p15, 0, r0, c1, c0, 0
+ orr r0, r0, #0x00000800
+ mcr p15, 0, r0, c1, c0, 0
+ bx LR
+
+ASM_PFX(ArmDisableBranchPrediction):
+ mrc p15, 0, r0, c1, c0, 0
+ bic r0, r0, #0x00000800
+ mcr p15, 0, r0, c1, c0, 0
+ bx LR
+
+ASM_PFX(ArmDataMemoryBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #5
+ bx LR
+
+ASM_PFX(ArmDataSyncronizationBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #4
+ bx LR
+
+ASM_PFX(ArmInstructionSynchronizationBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C5, #4
+ bx LR
+
+ASM_PFX(ArmSetLowVectors):
+ mrc p15, 0, r0, c1, c0, 0 @ Read SCTLR into R0 (Read control register configuration data)
+ bic r0, r0, #0x00002000 @ clear V bit
+ mcr p15, 0, r0, c1, c0, 0 @ Write R0 into SCTLR (Write control register configuration data)
+ bx LR
+
+ASM_PFX(ArmSetHighVectors):
+ mrc p15, 0, r0, c1, c0, 0 @ Read SCTLR into R0 (Read control register configuration data)
+ orr r0, r0, #0x00002000 @ clear V bit
+ mcr p15, 0, r0, c1, c0, 0 @ Write R0 into SCTLR (Write control register configuration data)
+ bx LR
+
+ASM_PFX(ArmIsMpCore):
+ push { r1 }
+ mrc p15, 0, r0, c0, c0, 0
+ # Extract Part Number to check it is an ARM11MP core (0xB02)
+ LoadConstantToReg (Arm11PartNumberMask, r1)
+ and r0, r0, r1
+ LoadConstantToReg (Arm11PartNumber, r1)
+ cmp r0, r1
+ movne r0, #0
+ pop { r1 }
+ bx lr
+
+ASM_PFX(ArmCallWFI):
+ wfi
+ bx lr
+
+ASM_PFX(ArmReadMpidr):
+ mrc p15, 0, r0, c0, c0, 5 @ read MPIDR
+ bx lr
+
+ASM_PFX(ArmEnableFiq):
+ mrs R0,CPSR
+ bic R0,R0,#0x40 @Enable FIQ interrupts
+ msr CPSR_c,R0
+ bx LR
+
+ASM_PFX(ArmDisableFiq):
+ mrs R0,CPSR
+ orr R1,R0,#0x40 @Disable FIQ interrupts
+ msr CPSR_c,R1
+ tst R0,#0x80
+ moveq R0,#1
+ movne R0,#0
+ bx LR
+
+ASM_PFX(ArmEnableInterrupts):
+ mrs R0,CPSR
+ bic R0,R0,#0x80 @Enable IRQ interrupts
+ msr CPSR_c,R0
+ bx LR
+
+ASM_PFX(ArmDisableInterrupts):
+ mrs R0,CPSR
+ orr R1,R0,#0x80 @Disable IRQ interrupts
+ msr CPSR_c,R1
+ tst R0,#0x80
+ moveq R0,#1
+ movne R0,#0
+ bx LR
+
+ASM_PFX(ArmEnableVFP):
+ # Read CPACR (Coprocessor Access Control Register)
+ mrc p15, 0, r0, c1, c0, 2
+ # Enable VPF access (Full Access to CP10, CP11) (V* instructions)
+ orr r0, r0, #0x00f00000
+ # Write back CPACR (Coprocessor Access Control Register)
+ mcr p15, 0, r0, c1, c0, 2
+ # Set EN bit in FPEXC. The Advanced SIMD and VFP extensions are enabled and operate normally.
+ mov r0, #0x40000000
+ #TODO: Fixme - need compilation flag
+ #fmxr FPEXC, r0
+ bx lr
+
+ASM_FUNCTION_REMOVE_IF_UNREFERENCED
diff --git a/ArmPkg/Library/ArmLib/Arm11/Arm11Support.asm b/ArmPkg/Library/ArmLib/Arm11/Arm11Support.asm
index fb3e91b7e..8c2709304 100644
--- a/ArmPkg/Library/ArmLib/Arm11/Arm11Support.asm
+++ b/ArmPkg/Library/ArmLib/Arm11/Arm11Support.asm
@@ -1,157 +1,157 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
- EXPORT ArmCleanInvalidateDataCache
- EXPORT ArmCleanDataCache
- EXPORT ArmInvalidateDataCache
- EXPORT ArmInvalidateInstructionCache
- EXPORT ArmInvalidateDataCacheEntryByMVA
- EXPORT ArmCleanDataCacheEntryByMVA
- EXPORT ArmCleanInvalidateDataCacheEntryByMVA
- EXPORT ArmEnableMmu
- EXPORT ArmDisableMmu
- EXPORT ArmMmuEnabled
- EXPORT ArmEnableDataCache
- EXPORT ArmDisableDataCache
- EXPORT ArmEnableInstructionCache
- EXPORT ArmDisableInstructionCache
- EXPORT ArmEnableBranchPrediction
- EXPORT ArmDisableBranchPrediction
- EXPORT ArmDataMemoryBarrier
- EXPORT ArmDataSyncronizationBarrier
- EXPORT ArmInstructionSynchronizationBarrier
-
-
-DC_ON EQU ( 0x1:SHL:2 )
-IC_ON EQU ( 0x1:SHL:12 )
-XP_ON EQU ( 0x1:SHL:23 )
-
-
- AREA ArmCacheLib, CODE, READONLY
- PRESERVE8
-
-
-ArmInvalidateDataCacheEntryByMVA
- mcr p15, 0, r0, c7, c6, 1 ; invalidate single data cache line
- bx lr
-
-
-ArmCleanDataCacheEntryByMVA
- mcr p15, 0, r0, c7, c10, 1 ; clean single data cache line
- bx lr
-
-
-ArmCleanInvalidateDataCacheEntryByMVA
- mcr p15, 0, r0, c7, c14, 1 ; clean and invalidate single data cache line
- bx lr
-
-
-ArmCleanDataCache
- mcr p15, 0, r0, c7, c10, 0 ; clean entire data cache
- bx lr
-
-
-ArmCleanInvalidateDataCache
- mcr p15, 0, r0, c7, c14, 0 ; clean and invalidate entire data cache
- bx lr
-
-
-ArmInvalidateDataCache
- mcr p15, 0, r0, c7, c6, 0 ; invalidate entire data cache
- bx lr
-
-
-ArmInvalidateInstructionCache
- mcr p15, 0, r0, c7, c5, 0 ;invalidate entire instruction cache
- mov R0,#0
- mcr p15,0,R0,c7,c5,4 ;Flush Prefetch buffer
- bx lr
-
-ArmEnableMmu
- mrc p15,0,R0,c1,c0,0
- orr R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- bx LR
-
-ArmMmuEnabled
- mrc p15,0,R0,c1,c0,0
- and R0,R0,#1
- bx LR
-
-ArmDisableMmu
- mrc p15,0,R0,c1,c0,0
- bic R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 ;Data synchronization barrier
- mov R0,#0
- mcr p15,0,R0,c7,c5,4 ;Flush Prefetch buffer
- bx LR
-
-ArmEnableDataCache
- LDR R1,=DC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- ORR R0,R0,R1 ;Set C bit
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmDisableDataCache
- LDR R1,=DC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- BIC R0,R0,R1 ;Clear C bit
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmEnableInstructionCache
- LDR R1,=IC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- ORR R0,R0,R1 ;Set I bit
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmDisableInstructionCache
- LDR R1,=IC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- BIC R0,R0,R1 ;Clear I bit.
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmEnableBranchPrediction
- mrc p15, 0, r0, c1, c0, 0
- orr r0, r0, #0x00000800
- mcr p15, 0, r0, c1, c0, 0
- bx LR
-
-ArmDisableBranchPrediction
- mrc p15, 0, r0, c1, c0, 0
- bic r0, r0, #0x00000800
- mcr p15, 0, r0, c1, c0, 0
- bx LR
-
-ASM_PFX(ArmDataMemoryBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #5
- bx LR
-
-ASM_PFX(ArmDataSyncronizationBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #4
- bx LR
-
-ASM_PFX(ArmInstructionSynchronizationBarrier):
- MOV R0, #0
- MCR P15, #0, R0, C7, C5, #4
- bx LR
-
- END
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+ EXPORT ArmCleanInvalidateDataCache
+ EXPORT ArmCleanDataCache
+ EXPORT ArmInvalidateDataCache
+ EXPORT ArmInvalidateInstructionCache
+ EXPORT ArmInvalidateDataCacheEntryByMVA
+ EXPORT ArmCleanDataCacheEntryByMVA
+ EXPORT ArmCleanInvalidateDataCacheEntryByMVA
+ EXPORT ArmEnableMmu
+ EXPORT ArmDisableMmu
+ EXPORT ArmMmuEnabled
+ EXPORT ArmEnableDataCache
+ EXPORT ArmDisableDataCache
+ EXPORT ArmEnableInstructionCache
+ EXPORT ArmDisableInstructionCache
+ EXPORT ArmEnableBranchPrediction
+ EXPORT ArmDisableBranchPrediction
+ EXPORT ArmDataMemoryBarrier
+ EXPORT ArmDataSyncronizationBarrier
+ EXPORT ArmInstructionSynchronizationBarrier
+
+
+DC_ON EQU ( 0x1:SHL:2 )
+IC_ON EQU ( 0x1:SHL:12 )
+XP_ON EQU ( 0x1:SHL:23 )
+
+
+ AREA ArmCacheLib, CODE, READONLY
+ PRESERVE8
+
+
+ArmInvalidateDataCacheEntryByMVA
+ mcr p15, 0, r0, c7, c6, 1 ; invalidate single data cache line
+ bx lr
+
+
+ArmCleanDataCacheEntryByMVA
+ mcr p15, 0, r0, c7, c10, 1 ; clean single data cache line
+ bx lr
+
+
+ArmCleanInvalidateDataCacheEntryByMVA
+ mcr p15, 0, r0, c7, c14, 1 ; clean and invalidate single data cache line
+ bx lr
+
+
+ArmCleanDataCache
+ mcr p15, 0, r0, c7, c10, 0 ; clean entire data cache
+ bx lr
+
+
+ArmCleanInvalidateDataCache
+ mcr p15, 0, r0, c7, c14, 0 ; clean and invalidate entire data cache
+ bx lr
+
+
+ArmInvalidateDataCache
+ mcr p15, 0, r0, c7, c6, 0 ; invalidate entire data cache
+ bx lr
+
+
+ArmInvalidateInstructionCache
+ mcr p15, 0, r0, c7, c5, 0 ;invalidate entire instruction cache
+ mov R0,#0
+ mcr p15,0,R0,c7,c5,4 ;Flush Prefetch buffer
+ bx lr
+
+ArmEnableMmu
+ mrc p15,0,R0,c1,c0,0
+ orr R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ bx LR
+
+ArmMmuEnabled
+ mrc p15,0,R0,c1,c0,0
+ and R0,R0,#1
+ bx LR
+
+ArmDisableMmu
+ mrc p15,0,R0,c1,c0,0
+ bic R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 ;Data synchronization barrier
+ mov R0,#0
+ mcr p15,0,R0,c7,c5,4 ;Flush Prefetch buffer
+ bx LR
+
+ArmEnableDataCache
+ LDR R1,=DC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ ORR R0,R0,R1 ;Set C bit
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmDisableDataCache
+ LDR R1,=DC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ BIC R0,R0,R1 ;Clear C bit
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmEnableInstructionCache
+ LDR R1,=IC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ ORR R0,R0,R1 ;Set I bit
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmDisableInstructionCache
+ LDR R1,=IC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ BIC R0,R0,R1 ;Clear I bit.
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmEnableBranchPrediction
+ mrc p15, 0, r0, c1, c0, 0
+ orr r0, r0, #0x00000800
+ mcr p15, 0, r0, c1, c0, 0
+ bx LR
+
+ArmDisableBranchPrediction
+ mrc p15, 0, r0, c1, c0, 0
+ bic r0, r0, #0x00000800
+ mcr p15, 0, r0, c1, c0, 0
+ bx LR
+
+ASM_PFX(ArmDataMemoryBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #5
+ bx LR
+
+ASM_PFX(ArmDataSyncronizationBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #4
+ bx LR
+
+ASM_PFX(ArmInstructionSynchronizationBarrier):
+ MOV R0, #0
+ MCR P15, #0, R0, C7, C5, #4
+ bx LR
+
+ END
diff --git a/ArmPkg/Library/ArmLib/Arm9/Arm9Lib.c b/ArmPkg/Library/ArmLib/Arm9/Arm9Lib.c
index 7c3a384a9..c92f9159c 100644
--- a/ArmPkg/Library/ArmLib/Arm9/Arm9Lib.c
+++ b/ArmPkg/Library/ArmLib/Arm9/Arm9Lib.c
@@ -1,131 +1,131 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Chipset/ARM926EJ-S.h>
-#include <Library/ArmLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-
-VOID
-FillTranslationTable (
- IN UINT32 *TranslationTable,
- IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryRegion
- )
-{
- UINT32 *Entry;
- UINTN Sections;
- UINTN Index;
- UINT32 Attributes;
- UINT32 PhysicalBase = MemoryRegion->PhysicalBase;
-
- switch (MemoryRegion->Attributes) {
- case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK:
- Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK;
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH:
- Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH;
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED:
- Attributes = TT_DESCRIPTOR_SECTION_UNCACHED_UNBUFFERED;
- break;
- case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK:
- case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH:
- case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED:
- ASSERT(0); // Trustzone is not supported on ARMv5
- default:
- Attributes = TT_DESCRIPTOR_SECTION_UNCACHED_UNBUFFERED;
- break;
- }
-
- Entry = TRANSLATION_TABLE_ENTRY_FOR_VIRTUAL_ADDRESS(TranslationTable, MemoryRegion->VirtualBase);
- Sections = MemoryRegion->Length / TT_DESCRIPTOR_SECTION_SIZE;
-
- // The current code does not support memory region size that is not aligned on TT_DESCRIPTOR_SECTION_SIZE boundary
- ASSERT (MemoryRegion->Length % TT_DESCRIPTOR_SECTION_SIZE == 0);
-
- for (Index = 0; Index < Sections; Index++)
- {
- *Entry++ = TT_DESCRIPTOR_SECTION_BASE_ADDRESS(PhysicalBase) | Attributes;
- PhysicalBase += TT_DESCRIPTOR_SECTION_SIZE;
- }
-}
-
-VOID
-EFIAPI
-ArmConfigureMmu (
- IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable,
- OUT VOID **TranslationTableBase OPTIONAL,
- OUT UINTN *TranslationTableSize OPTIONAL
- )
-{
- VOID *TranslationTable;
-
- // Allocate pages for translation table.
- TranslationTable = AllocatePages(EFI_SIZE_TO_PAGES(TRANSLATION_TABLE_SIZE + TRANSLATION_TABLE_ALIGNMENT));
- TranslationTable = (VOID *)(((UINTN)TranslationTable + TRANSLATION_TABLE_ALIGNMENT_MASK) & ~TRANSLATION_TABLE_ALIGNMENT_MASK);
-
- if (TranslationTableBase != NULL) {
- *TranslationTableBase = TranslationTable;
- }
-
- if (TranslationTableBase != NULL) {
- *TranslationTableSize = TRANSLATION_TABLE_SIZE;
- }
-
- ZeroMem(TranslationTable, TRANSLATION_TABLE_SIZE);
-
- ArmCleanInvalidateDataCache();
- ArmInvalidateInstructionCache();
- ArmInvalidateTlb();
-
- ArmDisableDataCache();
- ArmDisableInstructionCache();
- ArmDisableMmu();
-
- // Make sure nothing sneaked into the cache
- ArmCleanInvalidateDataCache();
- ArmInvalidateInstructionCache();
-
- while (MemoryTable->Length != 0) {
- FillTranslationTable(TranslationTable, MemoryTable);
- MemoryTable++;
- }
-
- ArmSetTTBR0(TranslationTable);
-
- ArmSetDomainAccessControl(DOMAIN_ACCESS_CONTROL_NONE(15) |
- DOMAIN_ACCESS_CONTROL_NONE(14) |
- DOMAIN_ACCESS_CONTROL_NONE(13) |
- DOMAIN_ACCESS_CONTROL_NONE(12) |
- DOMAIN_ACCESS_CONTROL_NONE(11) |
- DOMAIN_ACCESS_CONTROL_NONE(10) |
- DOMAIN_ACCESS_CONTROL_NONE( 9) |
- DOMAIN_ACCESS_CONTROL_NONE( 8) |
- DOMAIN_ACCESS_CONTROL_NONE( 7) |
- DOMAIN_ACCESS_CONTROL_NONE( 6) |
- DOMAIN_ACCESS_CONTROL_NONE( 5) |
- DOMAIN_ACCESS_CONTROL_NONE( 4) |
- DOMAIN_ACCESS_CONTROL_NONE( 3) |
- DOMAIN_ACCESS_CONTROL_NONE( 2) |
- DOMAIN_ACCESS_CONTROL_NONE( 1) |
- DOMAIN_ACCESS_CONTROL_MANAGER(0));
-
- ArmEnableInstructionCache();
- ArmEnableDataCache();
- ArmEnableMmu();
-}
-
-
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Chipset/ARM926EJ-S.h>
+#include <Library/ArmLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+
+VOID
+FillTranslationTable (
+ IN UINT32 *TranslationTable,
+ IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryRegion
+ )
+{
+ UINT32 *Entry;
+ UINTN Sections;
+ UINTN Index;
+ UINT32 Attributes;
+ UINT32 PhysicalBase = MemoryRegion->PhysicalBase;
+
+ switch (MemoryRegion->Attributes) {
+ case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK:
+ Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK;
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH:
+ Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH;
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED:
+ Attributes = TT_DESCRIPTOR_SECTION_UNCACHED_UNBUFFERED;
+ break;
+ case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK:
+ case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH:
+ case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED:
+ ASSERT(0); // Trustzone is not supported on ARMv5
+ default:
+ Attributes = TT_DESCRIPTOR_SECTION_UNCACHED_UNBUFFERED;
+ break;
+ }
+
+ Entry = TRANSLATION_TABLE_ENTRY_FOR_VIRTUAL_ADDRESS(TranslationTable, MemoryRegion->VirtualBase);
+ Sections = MemoryRegion->Length / TT_DESCRIPTOR_SECTION_SIZE;
+
+ // The current code does not support memory region size that is not aligned on TT_DESCRIPTOR_SECTION_SIZE boundary
+ ASSERT (MemoryRegion->Length % TT_DESCRIPTOR_SECTION_SIZE == 0);
+
+ for (Index = 0; Index < Sections; Index++)
+ {
+ *Entry++ = TT_DESCRIPTOR_SECTION_BASE_ADDRESS(PhysicalBase) | Attributes;
+ PhysicalBase += TT_DESCRIPTOR_SECTION_SIZE;
+ }
+}
+
+VOID
+EFIAPI
+ArmConfigureMmu (
+ IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable,
+ OUT VOID **TranslationTableBase OPTIONAL,
+ OUT UINTN *TranslationTableSize OPTIONAL
+ )
+{
+ VOID *TranslationTable;
+
+ // Allocate pages for translation table.
+ TranslationTable = AllocatePages(EFI_SIZE_TO_PAGES(TRANSLATION_TABLE_SIZE + TRANSLATION_TABLE_ALIGNMENT));
+ TranslationTable = (VOID *)(((UINTN)TranslationTable + TRANSLATION_TABLE_ALIGNMENT_MASK) & ~TRANSLATION_TABLE_ALIGNMENT_MASK);
+
+ if (TranslationTableBase != NULL) {
+ *TranslationTableBase = TranslationTable;
+ }
+
+ if (TranslationTableBase != NULL) {
+ *TranslationTableSize = TRANSLATION_TABLE_SIZE;
+ }
+
+ ZeroMem(TranslationTable, TRANSLATION_TABLE_SIZE);
+
+ ArmCleanInvalidateDataCache();
+ ArmInvalidateInstructionCache();
+ ArmInvalidateTlb();
+
+ ArmDisableDataCache();
+ ArmDisableInstructionCache();
+ ArmDisableMmu();
+
+ // Make sure nothing sneaked into the cache
+ ArmCleanInvalidateDataCache();
+ ArmInvalidateInstructionCache();
+
+ while (MemoryTable->Length != 0) {
+ FillTranslationTable(TranslationTable, MemoryTable);
+ MemoryTable++;
+ }
+
+ ArmSetTTBR0(TranslationTable);
+
+ ArmSetDomainAccessControl(DOMAIN_ACCESS_CONTROL_NONE(15) |
+ DOMAIN_ACCESS_CONTROL_NONE(14) |
+ DOMAIN_ACCESS_CONTROL_NONE(13) |
+ DOMAIN_ACCESS_CONTROL_NONE(12) |
+ DOMAIN_ACCESS_CONTROL_NONE(11) |
+ DOMAIN_ACCESS_CONTROL_NONE(10) |
+ DOMAIN_ACCESS_CONTROL_NONE( 9) |
+ DOMAIN_ACCESS_CONTROL_NONE( 8) |
+ DOMAIN_ACCESS_CONTROL_NONE( 7) |
+ DOMAIN_ACCESS_CONTROL_NONE( 6) |
+ DOMAIN_ACCESS_CONTROL_NONE( 5) |
+ DOMAIN_ACCESS_CONTROL_NONE( 4) |
+ DOMAIN_ACCESS_CONTROL_NONE( 3) |
+ DOMAIN_ACCESS_CONTROL_NONE( 2) |
+ DOMAIN_ACCESS_CONTROL_NONE( 1) |
+ DOMAIN_ACCESS_CONTROL_MANAGER(0));
+
+ ArmEnableInstructionCache();
+ ArmEnableDataCache();
+ ArmEnableMmu();
+}
+
+
+
diff --git a/ArmPkg/Library/ArmLib/Arm9/Arm9Support.S b/ArmPkg/Library/ArmLib/Arm9/Arm9Support.S
index 49e266dd3..28cc5b6e6 100644
--- a/ArmPkg/Library/ArmLib/Arm9/Arm9Support.S
+++ b/ArmPkg/Library/ArmLib/Arm9/Arm9Support.S
@@ -1,153 +1,153 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-.text
-.align 2
-GCC_ASM_EXPORT(ArmCleanInvalidateDataCache)
-GCC_ASM_EXPORT(ArmCleanDataCache)
-GCC_ASM_EXPORT(ArmInvalidateDataCache)
-GCC_ASM_EXPORT(ArmInvalidateInstructionCache)
-GCC_ASM_EXPORT(ArmInvalidateDataCacheEntryByMVA)
-GCC_ASM_EXPORT(ArmCleanDataCacheEntryByMVA)
-GCC_ASM_EXPORT(ArmCleanInvalidateDataCacheEntryByMVA)
-GCC_ASM_EXPORT(ArmEnableMmu)
-GCC_ASM_EXPORT(ArmDisableMmu)
-GCC_ASM_EXPORT(ArmMmuEnabled)
-GCC_ASM_EXPORT(ArmEnableDataCache)
-GCC_ASM_EXPORT(ArmDisableDataCache)
-GCC_ASM_EXPORT(ArmEnableInstructionCache)
-GCC_ASM_EXPORT(ArmDisableInstructionCache)
-GCC_ASM_EXPORT(ArmEnableBranchPrediction)
-GCC_ASM_EXPORT(ArmDisableBranchPrediction)
-GCC_ASM_EXPORT(ArmDataMemoryBarrier)
-GCC_ASM_EXPORT(ArmDataSyncronizationBarrier)
-GCC_ASM_EXPORT(ArmInstructionSynchronizationBarrier)
-
-
-.set DC_ON, (1<<2)
-.set IC_ON, (1<<12)
-
-#------------------------------------------------------------------------------
-
-ASM_PFX(ArmInvalidateDataCacheEntryByMVA):
- mcr p15, 0, r0, c7, c6, 1 @ invalidate single data cache line
- bx lr
-
-ASM_PFX(ArmCleanDataCacheEntryByMVA):
- mcr p15, 0, r0, c7, c10, 1 @ clean single data cache line
- bx lr
-
-ASM_PFX(ArmCleanInvalidateDataCacheEntryByMVA):
- mcr p15, 0, r0, c7, c14, 1 @ clean and invalidate single data cache line
- bx lr
-
-ASM_PFX(ArmEnableInstructionCache):
- ldr r1,=IC_ON
- mrc p15,0,r0,c1,c0,0 @Read control register configuration data
- orr r0,r0,r1 @Set I bit
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmDisableInstructionCache):
- ldr r1,=IC_ON
- mrc p15,0,r0,c1,c0,0 @Read control register configuration data
- bic r0,r0,r1 @Clear I bit.
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmInvalidateInstructionCache):
- mov r0,#0
- mcr p15,0,r0,c7,c5,0 @Invalidate entire Instruction cache.
- @Also flushes the branch target cache.
- mov r0,#0
- mcr p15,0,r0,c7,c10,4 @Data write buffer
- bx LR
-
-ASM_PFX(ArmEnableMmu):
- mrc p15,0,R0,c1,c0,0
- orr R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- bx LR
-
-ASM_PFX(ArmMmuEnabled):
- mrc p15,0,R0,c1,c0,0
- and R0,R0,#1
- bx LR
-
-ASM_PFX(ArmDisableMmu):
- mrc p15,0,R0,c1,c0,0
- bic R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 @Drain write buffer
- bx LR
-
-ASM_PFX(ArmEnableDataCache):
- ldr R1,=DC_ON
- mrc p15,0,R0,c1,c0,0 @Read control register configuration data
- orr R0,R0,R1 @Set C bit
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmDisableDataCache):
- ldr R1,=DC_ON
- mrc p15,0,R0,c1,c0,0 @Read control register configuration data
- bic R0,R0,R1 @Clear C bit
- mcr p15,0,r0,c1,c0,0 @Write control register configuration data
- bx LR
-
-ASM_PFX(ArmCleanDataCache):
- mrc p15,0,r15,c7,c10,3
- bne ASM_PFX(ArmCleanDataCache)
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 @Drain write buffer
- bx LR
-
-ASM_PFX(ArmInvalidateDataCache):
- mov R0,#0
- mcr p15,0,R0,c7,c6,0 @Invalidate entire data cache
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 @Drain write buffer
- bx LR
-
-ASM_PFX(ArmCleanInvalidateDataCache):
- mrc p15,0,r15,c7,c14,3
- bne ASM_PFX(ArmCleanInvalidateDataCache)
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 @Drain write buffer
- bx LR
-
-ASM_PFX(ArmEnableBranchPrediction):
- bx LR @Branch prediction is not supported.
-
-ASM_PFX(ArmDisableBranchPrediction):
- bx LR @Branch prediction is not supported.
-
-ASM_PFX(ArmDataMemoryBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #5 @ check if this is OK?
- bx LR
-
-ASM_PFX(ArmDataSyncronizationBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #4 @ check if this is OK?
- bx LR
-
-ASM_PFX(ArmInstructionSynchronizationBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C5, #4 @ check if this is OK?
- bx LR
-
-ASM_FUNCTION_REMOVE_IF_UNREFERENCED
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+.text
+.align 2
+GCC_ASM_EXPORT(ArmCleanInvalidateDataCache)
+GCC_ASM_EXPORT(ArmCleanDataCache)
+GCC_ASM_EXPORT(ArmInvalidateDataCache)
+GCC_ASM_EXPORT(ArmInvalidateInstructionCache)
+GCC_ASM_EXPORT(ArmInvalidateDataCacheEntryByMVA)
+GCC_ASM_EXPORT(ArmCleanDataCacheEntryByMVA)
+GCC_ASM_EXPORT(ArmCleanInvalidateDataCacheEntryByMVA)
+GCC_ASM_EXPORT(ArmEnableMmu)
+GCC_ASM_EXPORT(ArmDisableMmu)
+GCC_ASM_EXPORT(ArmMmuEnabled)
+GCC_ASM_EXPORT(ArmEnableDataCache)
+GCC_ASM_EXPORT(ArmDisableDataCache)
+GCC_ASM_EXPORT(ArmEnableInstructionCache)
+GCC_ASM_EXPORT(ArmDisableInstructionCache)
+GCC_ASM_EXPORT(ArmEnableBranchPrediction)
+GCC_ASM_EXPORT(ArmDisableBranchPrediction)
+GCC_ASM_EXPORT(ArmDataMemoryBarrier)
+GCC_ASM_EXPORT(ArmDataSyncronizationBarrier)
+GCC_ASM_EXPORT(ArmInstructionSynchronizationBarrier)
+
+
+.set DC_ON, (1<<2)
+.set IC_ON, (1<<12)
+
+#------------------------------------------------------------------------------
+
+ASM_PFX(ArmInvalidateDataCacheEntryByMVA):
+ mcr p15, 0, r0, c7, c6, 1 @ invalidate single data cache line
+ bx lr
+
+ASM_PFX(ArmCleanDataCacheEntryByMVA):
+ mcr p15, 0, r0, c7, c10, 1 @ clean single data cache line
+ bx lr
+
+ASM_PFX(ArmCleanInvalidateDataCacheEntryByMVA):
+ mcr p15, 0, r0, c7, c14, 1 @ clean and invalidate single data cache line
+ bx lr
+
+ASM_PFX(ArmEnableInstructionCache):
+ ldr r1,=IC_ON
+ mrc p15,0,r0,c1,c0,0 @Read control register configuration data
+ orr r0,r0,r1 @Set I bit
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmDisableInstructionCache):
+ ldr r1,=IC_ON
+ mrc p15,0,r0,c1,c0,0 @Read control register configuration data
+ bic r0,r0,r1 @Clear I bit.
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmInvalidateInstructionCache):
+ mov r0,#0
+ mcr p15,0,r0,c7,c5,0 @Invalidate entire Instruction cache.
+ @Also flushes the branch target cache.
+ mov r0,#0
+ mcr p15,0,r0,c7,c10,4 @Data write buffer
+ bx LR
+
+ASM_PFX(ArmEnableMmu):
+ mrc p15,0,R0,c1,c0,0
+ orr R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ bx LR
+
+ASM_PFX(ArmMmuEnabled):
+ mrc p15,0,R0,c1,c0,0
+ and R0,R0,#1
+ bx LR
+
+ASM_PFX(ArmDisableMmu):
+ mrc p15,0,R0,c1,c0,0
+ bic R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 @Drain write buffer
+ bx LR
+
+ASM_PFX(ArmEnableDataCache):
+ ldr R1,=DC_ON
+ mrc p15,0,R0,c1,c0,0 @Read control register configuration data
+ orr R0,R0,R1 @Set C bit
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmDisableDataCache):
+ ldr R1,=DC_ON
+ mrc p15,0,R0,c1,c0,0 @Read control register configuration data
+ bic R0,R0,R1 @Clear C bit
+ mcr p15,0,r0,c1,c0,0 @Write control register configuration data
+ bx LR
+
+ASM_PFX(ArmCleanDataCache):
+ mrc p15,0,r15,c7,c10,3
+ bne ASM_PFX(ArmCleanDataCache)
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 @Drain write buffer
+ bx LR
+
+ASM_PFX(ArmInvalidateDataCache):
+ mov R0,#0
+ mcr p15,0,R0,c7,c6,0 @Invalidate entire data cache
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 @Drain write buffer
+ bx LR
+
+ASM_PFX(ArmCleanInvalidateDataCache):
+ mrc p15,0,r15,c7,c14,3
+ bne ASM_PFX(ArmCleanInvalidateDataCache)
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 @Drain write buffer
+ bx LR
+
+ASM_PFX(ArmEnableBranchPrediction):
+ bx LR @Branch prediction is not supported.
+
+ASM_PFX(ArmDisableBranchPrediction):
+ bx LR @Branch prediction is not supported.
+
+ASM_PFX(ArmDataMemoryBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #5 @ check if this is OK?
+ bx LR
+
+ASM_PFX(ArmDataSyncronizationBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #4 @ check if this is OK?
+ bx LR
+
+ASM_PFX(ArmInstructionSynchronizationBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C5, #4 @ check if this is OK?
+ bx LR
+
+ASM_FUNCTION_REMOVE_IF_UNREFERENCED
+
diff --git a/ArmPkg/Library/ArmLib/Arm9/Arm9Support.asm b/ArmPkg/Library/ArmLib/Arm9/Arm9Support.asm
index dfee136b2..fc87828e2 100644
--- a/ArmPkg/Library/ArmLib/Arm9/Arm9Support.asm
+++ b/ArmPkg/Library/ArmLib/Arm9/Arm9Support.asm
@@ -1,153 +1,153 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
- EXPORT ArmCleanInvalidateDataCache
- EXPORT ArmCleanDataCache
- EXPORT ArmInvalidateDataCache
- EXPORT ArmInvalidateInstructionCache
- EXPORT ArmInvalidateDataCacheEntryByMVA
- EXPORT ArmCleanDataCacheEntryByMVA
- EXPORT ArmCleanInvalidateDataCacheEntryByMVA
- EXPORT ArmEnableMmu
- EXPORT ArmDisableMmu
- EXPORT ArmMmuEnabled
- EXPORT ArmEnableDataCache
- EXPORT ArmDisableDataCache
- EXPORT ArmEnableInstructionCache
- EXPORT ArmDisableInstructionCache
- EXPORT ArmEnableBranchPrediction
- EXPORT ArmDisableBranchPrediction
- EXPORT ArmDataMemoryBarrier
- EXPORT ArmDataSyncronizationBarrier
- EXPORT ArmInstructionSynchronizationBarrier
-
-
-DC_ON EQU ( 0x1:SHL:2 )
-IC_ON EQU ( 0x1:SHL:12 )
-
- AREA ArmCacheLib, CODE, READONLY
- PRESERVE8
-
-
-ArmInvalidateDataCacheEntryByMVA
- MCR p15, 0, r0, c7, c6, 1 ; invalidate single data cache line
- BX lr
-
-
-ArmCleanDataCacheEntryByMVA
- MCR p15, 0, r0, c7, c10, 1 ; clean single data cache line
- BX lr
-
-
-ArmCleanInvalidateDataCacheEntryByMVA
- MCR p15, 0, r0, c7, c14, 1 ; clean and invalidate single data cache line
- BX lr
-
-ArmEnableInstructionCache
- LDR R1,=IC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- ORR R0,R0,R1 ;Set I bit
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmDisableInstructionCache
- LDR R1,=IC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- BIC R0,R0,R1 ;Clear I bit.
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmInvalidateInstructionCache
- MOV R0,#0
- MCR p15,0,R0,c7,c5,0 ;Invalidate entire instruction cache
- MOV R0,#0
- MCR p15,0,R0,c7,c10,4 ;Drain write buffer
- BX LR
-
-ArmEnableMmu
- mrc p15,0,R0,c1,c0,0
- orr R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- bx LR
-
-ArmMmuEnabled
- mrc p15,0,R0,c1,c0,0
- and R0,R0,#1
- bx LR
-
-ArmDisableMmu
- mrc p15,0,R0,c1,c0,0
- bic R0,R0,#1
- mcr p15,0,R0,c1,c0,0
- mov R0,#0
- mcr p15,0,R0,c7,c10,4 ;Drain write buffer
- bx LR
-
-ArmEnableDataCache
- LDR R1,=DC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- ORR R0,R0,R1 ;Set C bit
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmDisableDataCache
- LDR R1,=DC_ON
- MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
- BIC R0,R0,R1 ;Clear C bit
- MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
- BX LR
-
-ArmCleanDataCache
- MRC p15,0,r15,c7,c10,3
- BNE ArmCleanDataCache
- MOV R0,#0
- MCR p15,0,R0,c7,c10,4 ;Drain write buffer
- BX LR
-
-ArmInvalidateDataCache
- MOV R0,#0
- MCR p15,0,R0,c7,c6,0 ;Invalidate entire data cache
- MOV R0,#0
- MCR p15,0,R0,c7,c10,4 ;Drain write buffer
- BX LR
-
-ArmCleanInvalidateDataCache
- MRC p15,0,r15,c7,c14,3
- BNE ArmCleanInvalidateDataCache
- MOV R0,#0
- MCR p15,0,R0,c7,c10,4 ;Drain write buffer
- BX LR
-
-ArmEnableBranchPrediction
- bx LR ;Branch prediction is not supported.
-
-ArmDisableBranchPrediction
- bx LR ;Branch prediction is not supported.
-
-ASM_PFX(ArmDataMemoryBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #5 ; Check to see if this is correct
- bx LR
-
-ASM_PFX(ArmDataSyncronizationBarrier):
- mov R0, #0
- mcr P15, #0, R0, C7, C10, #4 ; Check to see if this is correct
- bx LR
-
-ASM_PFX(ArmInstructionSynchronizationBarrier):
- MOV R0, #0
- MCR P15, #0, R0, C7, C5, #4 ; Check to see if this is correct
- bx LR
-
- END
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+ EXPORT ArmCleanInvalidateDataCache
+ EXPORT ArmCleanDataCache
+ EXPORT ArmInvalidateDataCache
+ EXPORT ArmInvalidateInstructionCache
+ EXPORT ArmInvalidateDataCacheEntryByMVA
+ EXPORT ArmCleanDataCacheEntryByMVA
+ EXPORT ArmCleanInvalidateDataCacheEntryByMVA
+ EXPORT ArmEnableMmu
+ EXPORT ArmDisableMmu
+ EXPORT ArmMmuEnabled
+ EXPORT ArmEnableDataCache
+ EXPORT ArmDisableDataCache
+ EXPORT ArmEnableInstructionCache
+ EXPORT ArmDisableInstructionCache
+ EXPORT ArmEnableBranchPrediction
+ EXPORT ArmDisableBranchPrediction
+ EXPORT ArmDataMemoryBarrier
+ EXPORT ArmDataSyncronizationBarrier
+ EXPORT ArmInstructionSynchronizationBarrier
+
+
+DC_ON EQU ( 0x1:SHL:2 )
+IC_ON EQU ( 0x1:SHL:12 )
+
+ AREA ArmCacheLib, CODE, READONLY
+ PRESERVE8
+
+
+ArmInvalidateDataCacheEntryByMVA
+ MCR p15, 0, r0, c7, c6, 1 ; invalidate single data cache line
+ BX lr
+
+
+ArmCleanDataCacheEntryByMVA
+ MCR p15, 0, r0, c7, c10, 1 ; clean single data cache line
+ BX lr
+
+
+ArmCleanInvalidateDataCacheEntryByMVA
+ MCR p15, 0, r0, c7, c14, 1 ; clean and invalidate single data cache line
+ BX lr
+
+ArmEnableInstructionCache
+ LDR R1,=IC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ ORR R0,R0,R1 ;Set I bit
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmDisableInstructionCache
+ LDR R1,=IC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ BIC R0,R0,R1 ;Clear I bit.
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmInvalidateInstructionCache
+ MOV R0,#0
+ MCR p15,0,R0,c7,c5,0 ;Invalidate entire instruction cache
+ MOV R0,#0
+ MCR p15,0,R0,c7,c10,4 ;Drain write buffer
+ BX LR
+
+ArmEnableMmu
+ mrc p15,0,R0,c1,c0,0
+ orr R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ bx LR
+
+ArmMmuEnabled
+ mrc p15,0,R0,c1,c0,0
+ and R0,R0,#1
+ bx LR
+
+ArmDisableMmu
+ mrc p15,0,R0,c1,c0,0
+ bic R0,R0,#1
+ mcr p15,0,R0,c1,c0,0
+ mov R0,#0
+ mcr p15,0,R0,c7,c10,4 ;Drain write buffer
+ bx LR
+
+ArmEnableDataCache
+ LDR R1,=DC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ ORR R0,R0,R1 ;Set C bit
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmDisableDataCache
+ LDR R1,=DC_ON
+ MRC p15,0,R0,c1,c0,0 ;Read control register configuration data
+ BIC R0,R0,R1 ;Clear C bit
+ MCR p15,0,r0,c1,c0,0 ;Write control register configuration data
+ BX LR
+
+ArmCleanDataCache
+ MRC p15,0,r15,c7,c10,3
+ BNE ArmCleanDataCache
+ MOV R0,#0
+ MCR p15,0,R0,c7,c10,4 ;Drain write buffer
+ BX LR
+
+ArmInvalidateDataCache
+ MOV R0,#0
+ MCR p15,0,R0,c7,c6,0 ;Invalidate entire data cache
+ MOV R0,#0
+ MCR p15,0,R0,c7,c10,4 ;Drain write buffer
+ BX LR
+
+ArmCleanInvalidateDataCache
+ MRC p15,0,r15,c7,c14,3
+ BNE ArmCleanInvalidateDataCache
+ MOV R0,#0
+ MCR p15,0,R0,c7,c10,4 ;Drain write buffer
+ BX LR
+
+ArmEnableBranchPrediction
+ bx LR ;Branch prediction is not supported.
+
+ArmDisableBranchPrediction
+ bx LR ;Branch prediction is not supported.
+
+ASM_PFX(ArmDataMemoryBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #5 ; Check to see if this is correct
+ bx LR
+
+ASM_PFX(ArmDataSyncronizationBarrier):
+ mov R0, #0
+ mcr P15, #0, R0, C7, C10, #4 ; Check to see if this is correct
+ bx LR
+
+ASM_PFX(ArmInstructionSynchronizationBarrier):
+ MOV R0, #0
+ MCR P15, #0, R0, C7, C5, #4 ; Check to see if this is correct
+ bx LR
+
+ END
diff --git a/ArmPkg/Library/ArmLib/ArmV7/ArmV7ArchTimer.c b/ArmPkg/Library/ArmLib/ArmV7/ArmV7ArchTimer.c
index 7835b414c..478a5da69 100644
--- a/ArmPkg/Library/ArmLib/ArmV7/ArmV7ArchTimer.c
+++ b/ArmPkg/Library/ArmLib/ArmV7/ArmV7ArchTimer.c
@@ -1,275 +1,275 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Uefi.h>
-#include <Chipset/ArmV7.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/ArmLib.h>
-#include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
-#include "ArmV7Lib.h"
-#include "ArmLibPrivate.h"
-#include <Library/ArmV7ArchTimerLib.h>
-
-VOID
-EFIAPI
-ArmArchTimerReadReg (
- IN ARM_ARCH_TIMER_REGS Reg,
- OUT VOID *DstBuf
- )
-{
- // Check if the Generic/Architecture timer is implemented
- if (ArmIsArchTimerImplemented ()) {
-
- switch (Reg) {
-
- case CntFrq:
- *((UINTN *)DstBuf) = ArmReadCntFrq ();
- break;
-
- case CntPct:
- *((UINT64 *)DstBuf) = ArmReadCntPct ();
- break;
-
- case CntkCtl:
- *((UINTN *)DstBuf) = ArmReadCntkCtl();
- break;
-
- case CntpTval:
- *((UINTN *)DstBuf) = ArmReadCntpTval ();
- break;
-
- case CntpCtl:
- *((UINTN *)DstBuf) = ArmReadCntpCtl ();
- break;
-
- case CntvTval:
- *((UINTN *)DstBuf) = ArmReadCntvTval ();
- break;
-
- case CntvCtl:
- *((UINTN *)DstBuf) = ArmReadCntvCtl ();
- break;
-
- case CntvCt:
- *((UINT64 *)DstBuf) = ArmReadCntvCt ();
- break;
-
- case CntpCval:
- *((UINT64 *)DstBuf) = ArmReadCntpCval ();
- break;
-
- case CntvCval:
- *((UINT64 *)DstBuf) = ArmReadCntvCval ();
- break;
-
- case CntvOff:
- *((UINT64 *)DstBuf) = ArmReadCntvOff ();
- break;
-
- case CnthCtl:
- case CnthpTval:
- case CnthpCtl:
- case CnthpCval:
- DEBUG ((EFI_D_ERROR, "The register is related to Hypervisor Mode. Can't perform requested operation\n "));
- break;
-
- default:
- DEBUG ((EFI_D_ERROR, "Unknown ARM Generic Timer register %x. \n ", Reg));
- }
- } else {
- DEBUG ((EFI_D_ERROR, "Attempt to read ARM Generic Timer registers. But ARM Generic Timer extension is not implemented \n "));
- ASSERT (0);
- }
-}
-
-VOID
-EFIAPI
-ArmArchTimerWriteReg (
- IN ARM_ARCH_TIMER_REGS Reg,
- IN VOID *SrcBuf
- )
-{
- // Check if the Generic/Architecture timer is implemented
- if (ArmIsArchTimerImplemented ()) {
-
- switch (Reg) {
-
- case CntFrq:
- ArmWriteCntFrq (*((UINTN *)SrcBuf));
- break;
-
- case CntPct:
- DEBUG ((EFI_D_ERROR, "Can't write to Read Only Register: CNTPCT \n"));
- break;
-
- case CntkCtl:
- ArmWriteCntkCtl (*((UINTN *)SrcBuf));
- break;
-
- case CntpTval:
- ArmWriteCntpTval (*((UINTN *)SrcBuf));
- break;
-
- case CntpCtl:
- ArmWriteCntpCtl (*((UINTN *)SrcBuf));
- break;
-
- case CntvTval:
- ArmWriteCntvTval (*((UINTN *)SrcBuf));
- break;
-
- case CntvCtl:
- ArmWriteCntvCtl (*((UINTN *)SrcBuf));
- break;
-
- case CntvCt:
- DEBUG ((EFI_D_ERROR, "Can't write to Read Only Register: CNTVCT \n"));
- break;
-
- case CntpCval:
- ArmWriteCntpCval (*((UINT64 *)SrcBuf) );
- break;
-
- case CntvCval:
- ArmWriteCntvCval (*((UINT64 *)SrcBuf) );
- break;
-
- case CntvOff:
- ArmWriteCntvOff (*((UINT64 *)SrcBuf));
- break;
-
- case CnthCtl:
- case CnthpTval:
- case CnthpCtl:
- case CnthpCval:
- DEBUG ((EFI_D_ERROR, "The register is related to Hypervisor Mode. Can't perform requested operation\n "));
- break;
-
- default:
- DEBUG ((EFI_D_ERROR, "Unknown ARM Generic Timer register %x. \n ", Reg));
- }
- } else {
- DEBUG ((EFI_D_ERROR, "Attempt to write to ARM Generic Timer registers. But ARM Generic Timer extension is not implemented \n "));
- ASSERT (0);
- }
-}
-
-VOID
-EFIAPI
-ArmArchTimerEnableTimer (
- VOID
- )
-{
- UINTN TimerCtrlReg;
-
- ArmArchTimerReadReg (CntpCtl, (VOID *)&TimerCtrlReg);
- TimerCtrlReg |= ARM_ARCH_TIMER_ENABLE;
- ArmArchTimerWriteReg (CntpCtl, (VOID *)&TimerCtrlReg);
-}
-
-VOID
-EFIAPI
-ArmArchTimerDisableTimer (
- VOID
- )
-{
- UINTN TimerCtrlReg;
-
- ArmArchTimerReadReg (CntpCtl, (VOID *)&TimerCtrlReg);
- TimerCtrlReg &= ~ARM_ARCH_TIMER_ENABLE;
- ArmArchTimerWriteReg (CntpCtl, (VOID *)&TimerCtrlReg);
-}
-
-VOID
-EFIAPI
-ArmArchTimerSetTimerFreq (
- IN UINTN FreqInHz
- )
-{
- ArmArchTimerWriteReg (CntFrq, (VOID *)&FreqInHz);
-}
-
-UINTN
-EFIAPI
-ArmArchTimerGetTimerFreq (
- VOID
- )
-{
- UINTN ArchTimerFreq = 0;
- ArmArchTimerReadReg (CntFrq, (VOID *)&ArchTimerFreq);
- return ArchTimerFreq;
-}
-
-UINTN
-EFIAPI
-ArmArchTimerGetTimerVal (
- VOID
- )
-{
- UINTN ArchTimerVal;
- ArmArchTimerReadReg (CntpTval, (VOID *)&ArchTimerVal);
- return ArchTimerVal;
-}
-
-
-VOID
-EFIAPI
-ArmArchTimerSetTimerVal (
- IN UINTN Val
- )
-{
- ArmArchTimerWriteReg (CntpTval, (VOID *)&Val);
-}
-
-UINT64
-EFIAPI
-ArmArchTimerGetSystemCount (
- VOID
- )
-{
- UINT64 SystemCount;
- ArmArchTimerReadReg (CntPct, (VOID *)&SystemCount);
- return SystemCount;
-}
-
-UINTN
-EFIAPI
-ArmArchTimerGetTimerCtrlReg (
- VOID
- )
-{
- UINTN Val;
- ArmArchTimerReadReg (CntpCtl, (VOID *)&Val);
- return Val;
-}
-
-VOID
-EFIAPI
-ArmArchTimerSetTimerCtrlReg (
- UINTN Val
- )
-{
- ArmArchTimerWriteReg (CntpCtl, (VOID *)&Val);
-}
-
-VOID
-EFIAPI
-ArmArchTimerSetCompareVal (
- IN UINT64 Val
- )
-{
- ArmArchTimerWriteReg (CntpCval, (VOID *)&Val);
-}
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Uefi.h>
+#include <Chipset/ArmV7.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/ArmLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include "ArmV7Lib.h"
+#include "ArmLibPrivate.h"
+#include <Library/ArmV7ArchTimerLib.h>
+
+VOID
+EFIAPI
+ArmArchTimerReadReg (
+ IN ARM_ARCH_TIMER_REGS Reg,
+ OUT VOID *DstBuf
+ )
+{
+ // Check if the Generic/Architecture timer is implemented
+ if (ArmIsArchTimerImplemented ()) {
+
+ switch (Reg) {
+
+ case CntFrq:
+ *((UINTN *)DstBuf) = ArmReadCntFrq ();
+ break;
+
+ case CntPct:
+ *((UINT64 *)DstBuf) = ArmReadCntPct ();
+ break;
+
+ case CntkCtl:
+ *((UINTN *)DstBuf) = ArmReadCntkCtl();
+ break;
+
+ case CntpTval:
+ *((UINTN *)DstBuf) = ArmReadCntpTval ();
+ break;
+
+ case CntpCtl:
+ *((UINTN *)DstBuf) = ArmReadCntpCtl ();
+ break;
+
+ case CntvTval:
+ *((UINTN *)DstBuf) = ArmReadCntvTval ();
+ break;
+
+ case CntvCtl:
+ *((UINTN *)DstBuf) = ArmReadCntvCtl ();
+ break;
+
+ case CntvCt:
+ *((UINT64 *)DstBuf) = ArmReadCntvCt ();
+ break;
+
+ case CntpCval:
+ *((UINT64 *)DstBuf) = ArmReadCntpCval ();
+ break;
+
+ case CntvCval:
+ *((UINT64 *)DstBuf) = ArmReadCntvCval ();
+ break;
+
+ case CntvOff:
+ *((UINT64 *)DstBuf) = ArmReadCntvOff ();
+ break;
+
+ case CnthCtl:
+ case CnthpTval:
+ case CnthpCtl:
+ case CnthpCval:
+ DEBUG ((EFI_D_ERROR, "The register is related to Hypervisor Mode. Can't perform requested operation\n "));
+ break;
+
+ default:
+ DEBUG ((EFI_D_ERROR, "Unknown ARM Generic Timer register %x. \n ", Reg));
+ }
+ } else {
+ DEBUG ((EFI_D_ERROR, "Attempt to read ARM Generic Timer registers. But ARM Generic Timer extension is not implemented \n "));
+ ASSERT (0);
+ }
+}
+
+VOID
+EFIAPI
+ArmArchTimerWriteReg (
+ IN ARM_ARCH_TIMER_REGS Reg,
+ IN VOID *SrcBuf
+ )
+{
+ // Check if the Generic/Architecture timer is implemented
+ if (ArmIsArchTimerImplemented ()) {
+
+ switch (Reg) {
+
+ case CntFrq:
+ ArmWriteCntFrq (*((UINTN *)SrcBuf));
+ break;
+
+ case CntPct:
+ DEBUG ((EFI_D_ERROR, "Can't write to Read Only Register: CNTPCT \n"));
+ break;
+
+ case CntkCtl:
+ ArmWriteCntkCtl (*((UINTN *)SrcBuf));
+ break;
+
+ case CntpTval:
+ ArmWriteCntpTval (*((UINTN *)SrcBuf));
+ break;
+
+ case CntpCtl:
+ ArmWriteCntpCtl (*((UINTN *)SrcBuf));
+ break;
+
+ case CntvTval:
+ ArmWriteCntvTval (*((UINTN *)SrcBuf));
+ break;
+
+ case CntvCtl:
+ ArmWriteCntvCtl (*((UINTN *)SrcBuf));
+ break;
+
+ case CntvCt:
+ DEBUG ((EFI_D_ERROR, "Can't write to Read Only Register: CNTVCT \n"));
+ break;
+
+ case CntpCval:
+ ArmWriteCntpCval (*((UINT64 *)SrcBuf) );
+ break;
+
+ case CntvCval:
+ ArmWriteCntvCval (*((UINT64 *)SrcBuf) );
+ break;
+
+ case CntvOff:
+ ArmWriteCntvOff (*((UINT64 *)SrcBuf));
+ break;
+
+ case CnthCtl:
+ case CnthpTval:
+ case CnthpCtl:
+ case CnthpCval:
+ DEBUG ((EFI_D_ERROR, "The register is related to Hypervisor Mode. Can't perform requested operation\n "));
+ break;
+
+ default:
+ DEBUG ((EFI_D_ERROR, "Unknown ARM Generic Timer register %x. \n ", Reg));
+ }
+ } else {
+ DEBUG ((EFI_D_ERROR, "Attempt to write to ARM Generic Timer registers. But ARM Generic Timer extension is not implemented \n "));
+ ASSERT (0);
+ }
+}
+
+VOID
+EFIAPI
+ArmArchTimerEnableTimer (
+ VOID
+ )
+{
+ UINTN TimerCtrlReg;
+
+ ArmArchTimerReadReg (CntpCtl, (VOID *)&TimerCtrlReg);
+ TimerCtrlReg |= ARM_ARCH_TIMER_ENABLE;
+ ArmArchTimerWriteReg (CntpCtl, (VOID *)&TimerCtrlReg);
+}
+
+VOID
+EFIAPI
+ArmArchTimerDisableTimer (
+ VOID
+ )
+{
+ UINTN TimerCtrlReg;
+
+ ArmArchTimerReadReg (CntpCtl, (VOID *)&TimerCtrlReg);
+ TimerCtrlReg &= ~ARM_ARCH_TIMER_ENABLE;
+ ArmArchTimerWriteReg (CntpCtl, (VOID *)&TimerCtrlReg);
+}
+
+VOID
+EFIAPI
+ArmArchTimerSetTimerFreq (
+ IN UINTN FreqInHz
+ )
+{
+ ArmArchTimerWriteReg (CntFrq, (VOID *)&FreqInHz);
+}
+
+UINTN
+EFIAPI
+ArmArchTimerGetTimerFreq (
+ VOID
+ )
+{
+ UINTN ArchTimerFreq = 0;
+ ArmArchTimerReadReg (CntFrq, (VOID *)&ArchTimerFreq);
+ return ArchTimerFreq;
+}
+
+UINTN
+EFIAPI
+ArmArchTimerGetTimerVal (
+ VOID
+ )
+{
+ UINTN ArchTimerVal;
+ ArmArchTimerReadReg (CntpTval, (VOID *)&ArchTimerVal);
+ return ArchTimerVal;
+}
+
+
+VOID
+EFIAPI
+ArmArchTimerSetTimerVal (
+ IN UINTN Val
+ )
+{
+ ArmArchTimerWriteReg (CntpTval, (VOID *)&Val);
+}
+
+UINT64
+EFIAPI
+ArmArchTimerGetSystemCount (
+ VOID
+ )
+{
+ UINT64 SystemCount;
+ ArmArchTimerReadReg (CntPct, (VOID *)&SystemCount);
+ return SystemCount;
+}
+
+UINTN
+EFIAPI
+ArmArchTimerGetTimerCtrlReg (
+ VOID
+ )
+{
+ UINTN Val;
+ ArmArchTimerReadReg (CntpCtl, (VOID *)&Val);
+ return Val;
+}
+
+VOID
+EFIAPI
+ArmArchTimerSetTimerCtrlReg (
+ UINTN Val
+ )
+{
+ ArmArchTimerWriteReg (CntpCtl, (VOID *)&Val);
+}
+
+VOID
+EFIAPI
+ArmArchTimerSetCompareVal (
+ IN UINT64 Val
+ )
+{
+ ArmArchTimerWriteReg (CntpCval, (VOID *)&Val);
+}
diff --git a/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.c b/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.c
index d9cf8826c..cc5074bfc 100644
--- a/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.c
+++ b/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.c
@@ -1,264 +1,264 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-#include <Uefi.h>
-#include <Chipset/ArmV7.h>
-#include <Library/ArmLib.h>
-#include <Library/BaseLib.h>
-#include <Library/IoLib.h>
-#include "ArmV7Lib.h"
-#include "ArmLibPrivate.h"
-
-ARM_CACHE_TYPE
-EFIAPI
-ArmCacheType (
- VOID
- )
-{
- return ARM_CACHE_TYPE_WRITE_BACK;
-}
-
-ARM_CACHE_ARCHITECTURE
-EFIAPI
-ArmCacheArchitecture (
- VOID
- )
-{
- UINT32 CLIDR = ReadCLIDR ();
-
- return (ARM_CACHE_ARCHITECTURE)CLIDR; // BugBug Fix Me
-}
-
-BOOLEAN
-EFIAPI
-ArmDataCachePresent (
- VOID
- )
-{
- UINT32 CLIDR = ReadCLIDR ();
-
- if ((CLIDR & 0x2) == 0x2) {
- // Instruction cache exists
- return TRUE;
- }
- if ((CLIDR & 0x7) == 0x4) {
- // Unified cache
- return TRUE;
- }
-
- return FALSE;
-}
-
-UINTN
-EFIAPI
-ArmDataCacheSize (
- VOID
- )
-{
- UINT32 NumSets;
- UINT32 Associativity;
- UINT32 LineSize;
- UINT32 CCSIDR = ReadCCSIDR (0);
-
- LineSize = (1 << ((CCSIDR & 0x7) + 2));
- Associativity = ((CCSIDR >> 3) & 0x3ff) + 1;
- NumSets = ((CCSIDR >> 13) & 0x7fff) + 1;
-
- // LineSize is in words (4 byte chunks)
- return NumSets * Associativity * LineSize * 4;
-}
-
-UINTN
-EFIAPI
-ArmDataCacheAssociativity (
- VOID
- )
-{
- UINT32 CCSIDR = ReadCCSIDR (0);
-
- return ((CCSIDR >> 3) & 0x3ff) + 1;
-}
-
-UINTN
-ArmDataCacheSets (
- VOID
- )
-{
- UINT32 CCSIDR = ReadCCSIDR (0);
-
- return ((CCSIDR >> 13) & 0x7fff) + 1;
-}
-
-UINTN
-EFIAPI
-ArmDataCacheLineLength (
- VOID
- )
-{
- UINT32 CCSIDR = ReadCCSIDR (0) & 7;
-
- // * 4 converts to bytes
- return (1 << (CCSIDR + 2)) * 4;
-}
-
-BOOLEAN
-EFIAPI
-ArmInstructionCachePresent (
- VOID
- )
-{
- UINT32 CLIDR = ReadCLIDR ();
-
- if ((CLIDR & 1) == 1) {
- // Instruction cache exists
- return TRUE;
- }
- if ((CLIDR & 0x7) == 0x4) {
- // Unified cache
- return TRUE;
- }
-
- return FALSE;
-}
-
-UINTN
-EFIAPI
-ArmInstructionCacheSize (
- VOID
- )
-{
- UINT32 NumSets;
- UINT32 Associativity;
- UINT32 LineSize;
- UINT32 CCSIDR = ReadCCSIDR (1);
-
- LineSize = (1 << ((CCSIDR & 0x7) + 2));
- Associativity = ((CCSIDR >> 3) & 0x3ff) + 1;
- NumSets = ((CCSIDR >> 13) & 0x7fff) + 1;
-
- // LineSize is in words (4 byte chunks)
- return NumSets * Associativity * LineSize * 4;
-}
-
-UINTN
-EFIAPI
-ArmInstructionCacheAssociativity (
- VOID
- )
-{
- UINT32 CCSIDR = ReadCCSIDR (1);
-
- return ((CCSIDR >> 3) & 0x3ff) + 1;
-// return 4;
-}
-
-UINTN
-EFIAPI
-ArmInstructionCacheSets (
- VOID
- )
-{
- UINT32 CCSIDR = ReadCCSIDR (1);
-
- return ((CCSIDR >> 13) & 0x7fff) + 1;
-}
-
-UINTN
-EFIAPI
-ArmInstructionCacheLineLength (
- VOID
- )
-{
- UINT32 CCSIDR = ReadCCSIDR (1) & 7;
-
- // * 4 converts to bytes
- return (1 << (CCSIDR + 2)) * 4;
-
-// return 64;
-}
-
-
-VOID
-ArmV7DataCacheOperation (
- IN ARM_V7_CACHE_OPERATION DataCacheOperation
- )
-{
- UINTN SavedInterruptState;
-
- SavedInterruptState = ArmGetInterruptState ();
- ArmDisableInterrupts ();
-
- ArmV7AllDataCachesOperation (DataCacheOperation);
-
- ArmDrainWriteBuffer ();
-
- if (SavedInterruptState) {
- ArmEnableInterrupts ();
- }
-}
-
-
-VOID
-ArmV7PoUDataCacheOperation (
- IN ARM_V7_CACHE_OPERATION DataCacheOperation
- )
-{
- UINTN SavedInterruptState;
-
- SavedInterruptState = ArmGetInterruptState ();
- ArmDisableInterrupts ();
-
- ArmV7PerformPoUDataCacheOperation (DataCacheOperation);
-
- ArmDrainWriteBuffer ();
-
- if (SavedInterruptState) {
- ArmEnableInterrupts ();
- }
-}
-
-VOID
-EFIAPI
-ArmInvalidateDataCache (
- VOID
- )
-{
- ArmV7DataCacheOperation (ArmInvalidateDataCacheEntryBySetWay);
-}
-
-VOID
-EFIAPI
-ArmCleanInvalidateDataCache (
- VOID
- )
-{
- ArmV7DataCacheOperation (ArmCleanInvalidateDataCacheEntryBySetWay);
-}
-
-VOID
-EFIAPI
-ArmCleanDataCache (
- VOID
- )
-{
- ArmV7DataCacheOperation (ArmCleanDataCacheEntryBySetWay);
-}
-
-VOID
-EFIAPI
-ArmCleanDataCacheToPoU (
- VOID
- )
-{
- ArmV7PoUDataCacheOperation (ArmCleanDataCacheEntryBySetWay);
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+#include <Uefi.h>
+#include <Chipset/ArmV7.h>
+#include <Library/ArmLib.h>
+#include <Library/BaseLib.h>
+#include <Library/IoLib.h>
+#include "ArmV7Lib.h"
+#include "ArmLibPrivate.h"
+
+ARM_CACHE_TYPE
+EFIAPI
+ArmCacheType (
+ VOID
+ )
+{
+ return ARM_CACHE_TYPE_WRITE_BACK;
+}
+
+ARM_CACHE_ARCHITECTURE
+EFIAPI
+ArmCacheArchitecture (
+ VOID
+ )
+{
+ UINT32 CLIDR = ReadCLIDR ();
+
+ return (ARM_CACHE_ARCHITECTURE)CLIDR; // BugBug Fix Me
+}
+
+BOOLEAN
+EFIAPI
+ArmDataCachePresent (
+ VOID
+ )
+{
+ UINT32 CLIDR = ReadCLIDR ();
+
+ if ((CLIDR & 0x2) == 0x2) {
+ // Instruction cache exists
+ return TRUE;
+ }
+ if ((CLIDR & 0x7) == 0x4) {
+ // Unified cache
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+UINTN
+EFIAPI
+ArmDataCacheSize (
+ VOID
+ )
+{
+ UINT32 NumSets;
+ UINT32 Associativity;
+ UINT32 LineSize;
+ UINT32 CCSIDR = ReadCCSIDR (0);
+
+ LineSize = (1 << ((CCSIDR & 0x7) + 2));
+ Associativity = ((CCSIDR >> 3) & 0x3ff) + 1;
+ NumSets = ((CCSIDR >> 13) & 0x7fff) + 1;
+
+ // LineSize is in words (4 byte chunks)
+ return NumSets * Associativity * LineSize * 4;
+}
+
+UINTN
+EFIAPI
+ArmDataCacheAssociativity (
+ VOID
+ )
+{
+ UINT32 CCSIDR = ReadCCSIDR (0);
+
+ return ((CCSIDR >> 3) & 0x3ff) + 1;
+}
+
+UINTN
+ArmDataCacheSets (
+ VOID
+ )
+{
+ UINT32 CCSIDR = ReadCCSIDR (0);
+
+ return ((CCSIDR >> 13) & 0x7fff) + 1;
+}
+
+UINTN
+EFIAPI
+ArmDataCacheLineLength (
+ VOID
+ )
+{
+ UINT32 CCSIDR = ReadCCSIDR (0) & 7;
+
+ // * 4 converts to bytes
+ return (1 << (CCSIDR + 2)) * 4;
+}
+
+BOOLEAN
+EFIAPI
+ArmInstructionCachePresent (
+ VOID
+ )
+{
+ UINT32 CLIDR = ReadCLIDR ();
+
+ if ((CLIDR & 1) == 1) {
+ // Instruction cache exists
+ return TRUE;
+ }
+ if ((CLIDR & 0x7) == 0x4) {
+ // Unified cache
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+UINTN
+EFIAPI
+ArmInstructionCacheSize (
+ VOID
+ )
+{
+ UINT32 NumSets;
+ UINT32 Associativity;
+ UINT32 LineSize;
+ UINT32 CCSIDR = ReadCCSIDR (1);
+
+ LineSize = (1 << ((CCSIDR & 0x7) + 2));
+ Associativity = ((CCSIDR >> 3) & 0x3ff) + 1;
+ NumSets = ((CCSIDR >> 13) & 0x7fff) + 1;
+
+ // LineSize is in words (4 byte chunks)
+ return NumSets * Associativity * LineSize * 4;
+}
+
+UINTN
+EFIAPI
+ArmInstructionCacheAssociativity (
+ VOID
+ )
+{
+ UINT32 CCSIDR = ReadCCSIDR (1);
+
+ return ((CCSIDR >> 3) & 0x3ff) + 1;
+// return 4;
+}
+
+UINTN
+EFIAPI
+ArmInstructionCacheSets (
+ VOID
+ )
+{
+ UINT32 CCSIDR = ReadCCSIDR (1);
+
+ return ((CCSIDR >> 13) & 0x7fff) + 1;
+}
+
+UINTN
+EFIAPI
+ArmInstructionCacheLineLength (
+ VOID
+ )
+{
+ UINT32 CCSIDR = ReadCCSIDR (1) & 7;
+
+ // * 4 converts to bytes
+ return (1 << (CCSIDR + 2)) * 4;
+
+// return 64;
+}
+
+
+VOID
+ArmV7DataCacheOperation (
+ IN ARM_V7_CACHE_OPERATION DataCacheOperation
+ )
+{
+ UINTN SavedInterruptState;
+
+ SavedInterruptState = ArmGetInterruptState ();
+ ArmDisableInterrupts ();
+
+ ArmV7AllDataCachesOperation (DataCacheOperation);
+
+ ArmDrainWriteBuffer ();
+
+ if (SavedInterruptState) {
+ ArmEnableInterrupts ();
+ }
+}
+
+
+VOID
+ArmV7PoUDataCacheOperation (
+ IN ARM_V7_CACHE_OPERATION DataCacheOperation
+ )
+{
+ UINTN SavedInterruptState;
+
+ SavedInterruptState = ArmGetInterruptState ();
+ ArmDisableInterrupts ();
+
+ ArmV7PerformPoUDataCacheOperation (DataCacheOperation);
+
+ ArmDrainWriteBuffer ();
+
+ if (SavedInterruptState) {
+ ArmEnableInterrupts ();
+ }
+}
+
+VOID
+EFIAPI
+ArmInvalidateDataCache (
+ VOID
+ )
+{
+ ArmV7DataCacheOperation (ArmInvalidateDataCacheEntryBySetWay);
+}
+
+VOID
+EFIAPI
+ArmCleanInvalidateDataCache (
+ VOID
+ )
+{
+ ArmV7DataCacheOperation (ArmCleanInvalidateDataCacheEntryBySetWay);
+}
+
+VOID
+EFIAPI
+ArmCleanDataCache (
+ VOID
+ )
+{
+ ArmV7DataCacheOperation (ArmCleanDataCacheEntryBySetWay);
+}
+
+VOID
+EFIAPI
+ArmCleanDataCacheToPoU (
+ VOID
+ )
+{
+ ArmV7PoUDataCacheOperation (ArmCleanDataCacheEntryBySetWay);
+}
diff --git a/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.h b/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.h
index 66995c7bb..88848da58 100644
--- a/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.h
+++ b/ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.h
@@ -60,30 +60,6 @@ ArmDisableAsynchronousAbort (
);
VOID
-EFIAPI
-ArmEnableIrq (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDisableIrq (
- VOID
- );
-
-VOID
-EFIAPI
-ArmEnableFiq (
- VOID
- );
-
-UINTN
-EFIAPI
-ArmDisableFiq (
- VOID
- );
-
-VOID
ArmV7PerformPoUDataCacheOperation (
IN ARM_V7_CACHE_OPERATION DataCacheOperation
);
diff --git a/ArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm b/ArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm
index ca8d06a55..d0faa00d1 100755
--- a/ArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm
+++ b/ArmPkg/Library/BaseMemoryLibStm/Arm/CopyMem.asm
@@ -38,16 +38,16 @@ InternalMemCopyMem (
)
**/
EXPORT InternalMemCopyMem
-
- AREA AsmMemStuff, CODE, READONLY
+
+ AREA AsmMemStuff, CODE, READONLY
InternalMemCopyMem
- stmfd sp!, {r4-r11, lr}
- // Save the input parameters in extra registers (r11 = destination, r14 = source, r12 = length)
- mov r11, r0
- mov r10, r0
- mov r12, r2
- mov r14, r1
+ stmfd sp!, {r4-r11, lr}
+ // Save the input parameters in extra registers (r11 = destination, r14 = source, r12 = length)
+ mov r11, r0
+ mov r10, r0
+ mov r12, r2
+ mov r14, r1
memcopy_check_overlapped
cmp r11, r1
@@ -70,42 +70,42 @@ memcopy_check_overlapped
memcopy_check_optim_default
// Check if we can use an optimized path ((length >= 32) && destination word-aligned && source word-aligned) for the memcopy (optimized path if r0 == 1)
tst r0, #0xF
- movne r0, #0
- bne memcopy_default
- tst r1, #0xF
- movne r3, #0
- moveq r3, #1
- cmp r2, #31
- movls r0, #0
- andhi r0, r3, #1
- b memcopy_default
-
-memcopy_check_optim_overlap
- // r10 = dest_end, r14 = source_end
- add r10, r11, r12
- add r14, r12, r1
-
- // Are we in the optimized case ((length >= 32) && dest_end word-aligned && source_end word-aligned)
- cmp r2, #31
- movls r0, #0
- movhi r0, #1
- tst r10, #0xF
- movne r0, #0
- tst r14, #0xF
- movne r0, #0
+ movne r0, #0
+ bne memcopy_default
+ tst r1, #0xF
+ movne r3, #0
+ moveq r3, #1
+ cmp r2, #31
+ movls r0, #0
+ andhi r0, r3, #1
+ b memcopy_default
+
+memcopy_check_optim_overlap
+ // r10 = dest_end, r14 = source_end
+ add r10, r11, r12
+ add r14, r12, r1
+
+ // Are we in the optimized case ((length >= 32) && dest_end word-aligned && source_end word-aligned)
+ cmp r2, #31
+ movls r0, #0
+ movhi r0, #1
+ tst r10, #0xF
+ movne r0, #0
+ tst r14, #0xF
+ movne r0, #0
b memcopy_overlapped
-
+
memcopy_overlapped_non_optim
// We read 1 byte from the end of the source buffer
- sub r3, r14, #1
- sub r12, r12, #1
- ldrb r3, [r3, #0]
- sub r2, r10, #1
- cmp r12, #0
+ sub r3, r14, #1
+ sub r12, r12, #1
+ ldrb r3, [r3, #0]
+ sub r2, r10, #1
+ cmp r12, #0
// We write 1 byte at the end of the dest buffer
- sub r10, r10, #1
- sub r14, r14, #1
- strb r3, [r2, #0]
+ sub r10, r10, #1
+ sub r14, r14, #1
+ strb r3, [r2, #0]
bne memcopy_overlapped_non_optim
b memcopy_end
@@ -114,16 +114,16 @@ memcopy_overlapped
// Are we in the optimized case ?
cmp r0, #0
beq memcopy_overlapped_non_optim
-
+
// Optimized Overlapped - Read 32 bytes
sub r14, r14, #32
sub r12, r12, #32
cmp r12, #31
ldmia r14, {r2-r9}
-
+
// If length is less than 32 then disable optim
movls r0, #0
-
+
cmp r12, #0
// Optimized Overlapped - Write 32 bytes
@@ -136,37 +136,37 @@ memcopy_overlapped
memcopy_default_non_optim
// Byte copy
- ldrb r3, [r14], #1
- sub r12, r12, #1
- strb r3, [r10], #1
-
+ ldrb r3, [r14], #1
+ sub r12, r12, #1
+ strb r3, [r10], #1
+
memcopy_default
- cmp r12, #0
- beq memcopy_end
-
+ cmp r12, #0
+ beq memcopy_end
+
// r10 = dest, r14 = source
memcopy_default_loop
- cmp r0, #0
+ cmp r0, #0
beq memcopy_default_non_optim
-
+
// Optimized memcopy - Read 32 Bytes
- sub r12, r12, #32
- cmp r12, #31
- ldmia r14!, {r2-r9}
+ sub r12, r12, #32
+ cmp r12, #31
+ ldmia r14!, {r2-r9}
// If length is less than 32 then disable optim
- movls r0, #0
+ movls r0, #0
- cmp r12, #0
+ cmp r12, #0
// Optimized memcopy - Write 32 Bytes
- stmia r10!, {r2-r9}
-
+ stmia r10!, {r2-r9}
+
// while (length != 0)
bne memcopy_default_loop
-
+
memcopy_end
- mov r0, r11
+ mov r0, r11
ldmfd sp!, {r4-r11, pc}
END
diff --git a/ArmPkg/Library/BaseMemoryLibVstm/Arm/CopyMem.asm b/ArmPkg/Library/BaseMemoryLibVstm/Arm/CopyMem.asm
index e7cbdf1ed..5df7c6b79 100755
--- a/ArmPkg/Library/BaseMemoryLibVstm/Arm/CopyMem.asm
+++ b/ArmPkg/Library/BaseMemoryLibVstm/Arm/CopyMem.asm
@@ -38,78 +38,78 @@ InternalMemCopyMem (
)
**/
EXPORT InternalMemCopyMem
-
- AREA AsmMemStuff, CODE, READONLY
+
+ AREA AsmMemStuff, CODE, READONLY
InternalMemCopyMem
- stmfd sp!, {r4, r9, lr}
- tst r0, #3
- mov r4, r0
- mov r9, r0
- mov ip, r2
- mov lr, r1
- movne r0, #0
- bne L4
- tst r1, #3
- movne r3, #0
- moveq r3, #1
- cmp r2, #127
- movls r0, #0
- andhi r0, r3, #1
-L4
- cmp r4, r1
- bcc L26
- bls L7
- rsb r3, r1, r4
- cmp ip, r3
- bcc L26
- cmp ip, #0
- beq L7
- add r9, r4, ip
- add lr, ip, r1
- b L16
-L29
- sub ip, ip, #8
- cmp ip, #7
- ldrd r2, [lr, #-8]!
- movls r0, #0
- cmp ip, #0
- strd r2, [r9, #-8]!
- beq L7
-L16
- cmp r0, #0
- bne L29
- sub r3, lr, #1
- sub ip, ip, #1
- ldrb r3, [r3, #0]
- sub r2, r9, #1
- cmp ip, #0
- sub r9, r9, #1
- sub lr, lr, #1
- strb r3, [r2, #0]
- bne L16
- b L7
-L11
- ldrb r3, [lr], #1
- sub ip, ip, #1
- strb r3, [r9], #1
-L26
- cmp ip, #0
- beq L7
-L30
- cmp r0, #0
- beq L11
- sub ip, ip, #128 // 32
- cmp ip, #127 // 31
- vldm lr!, {d0-d15}
- movls r0, #0
- cmp ip, #0
- vstm r9!, {d0-d15}
- bne L30
-L7
- dsb
- mov r0, r4
- ldmfd sp!, {r4, r9, pc}
+ stmfd sp!, {r4, r9, lr}
+ tst r0, #3
+ mov r4, r0
+ mov r9, r0
+ mov ip, r2
+ mov lr, r1
+ movne r0, #0
+ bne L4
+ tst r1, #3
+ movne r3, #0
+ moveq r3, #1
+ cmp r2, #127
+ movls r0, #0
+ andhi r0, r3, #1
+L4
+ cmp r4, r1
+ bcc L26
+ bls L7
+ rsb r3, r1, r4
+ cmp ip, r3
+ bcc L26
+ cmp ip, #0
+ beq L7
+ add r9, r4, ip
+ add lr, ip, r1
+ b L16
+L29
+ sub ip, ip, #8
+ cmp ip, #7
+ ldrd r2, [lr, #-8]!
+ movls r0, #0
+ cmp ip, #0
+ strd r2, [r9, #-8]!
+ beq L7
+L16
+ cmp r0, #0
+ bne L29
+ sub r3, lr, #1
+ sub ip, ip, #1
+ ldrb r3, [r3, #0]
+ sub r2, r9, #1
+ cmp ip, #0
+ sub r9, r9, #1
+ sub lr, lr, #1
+ strb r3, [r2, #0]
+ bne L16
+ b L7
+L11
+ ldrb r3, [lr], #1
+ sub ip, ip, #1
+ strb r3, [r9], #1
+L26
+ cmp ip, #0
+ beq L7
+L30
+ cmp r0, #0
+ beq L11
+ sub ip, ip, #128 // 32
+ cmp ip, #127 // 31
+ vldm lr!, {d0-d15}
+ movls r0, #0
+ cmp ip, #0
+ vstm r9!, {d0-d15}
+ bne L30
+L7
+ dsb
+ mov r0, r4
+ ldmfd sp!, {r4, r9, pc}
END
diff --git a/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.S b/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.S
index d5c50cbef..0415ed709 100755
--- a/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.S
+++ b/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.S
@@ -77,4 +77,4 @@ L43:
cmp r1, #0
bne L34
ldmfd sp!, {pc}
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.asm b/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.asm
index bbab580cf..de438d6c5 100755
--- a/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.asm
+++ b/ArmPkg/Library/BaseMemoryLibVstm/Arm/SetMem.asm
@@ -36,7 +36,7 @@ InternalMemSetMem (
EXPORT InternalMemSetMem
- AREA AsmMemStuff, CODE, READONLY
+ AREA AsmMemStuff, CODE, READONLY
InternalMemSetMem
stmfd sp!, {lr}
@@ -77,4 +77,4 @@ L43
ldmfd sp!, {pc}
END
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/ArmPkg/Library/BdsLib/BdsAppLoader.c b/ArmPkg/Library/BdsLib/BdsAppLoader.c
index 2d7f96e28..2b88bf1e0 100644
--- a/ArmPkg/Library/BdsLib/BdsAppLoader.c
+++ b/ArmPkg/Library/BdsLib/BdsAppLoader.c
@@ -1,144 +1,144 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-
-//#include <Library/DxeServicesLib.h>
-
-STATIC
-EFI_STATUS
-BdsLoadFileFromFirmwareVolume (
- IN EFI_HANDLE FvHandle,
- IN CHAR16 *FilePath,
- IN EFI_FV_FILETYPE FileTypeFilter,
- OUT EFI_DEVICE_PATH **EfiAppDevicePath
- )
-{
- EFI_FIRMWARE_VOLUME2_PROTOCOL *FvProtocol;
- VOID *Key;
- EFI_STATUS Status, FileStatus;
- EFI_GUID NameGuid;
- EFI_FV_FILETYPE FileType;
- EFI_FV_FILE_ATTRIBUTES Attributes;
- UINTN Size;
- UINTN UiStringLen;
- CHAR16 *UiSection;
- UINT32 Authentication;
- EFI_DEVICE_PATH *FvDevicePath;
- MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FileDevicePath;
-
- Status = gBS->HandleProtocol (FvHandle,&gEfiFirmwareVolume2ProtocolGuid, (VOID **)&FvProtocol);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Length of FilePath
- UiStringLen = StrLen (FilePath);
-
- // Allocate Key
- Key = AllocatePool (FvProtocol->KeySize);
- ASSERT (Key != NULL);
- ZeroMem (Key, FvProtocol->KeySize);
-
- do {
- // Search in all files
- FileType = FileTypeFilter;
-
- Status = FvProtocol->GetNextFile (FvProtocol, Key, &FileType, &NameGuid, &Attributes, &Size);
- if (!EFI_ERROR (Status)) {
- UiSection = NULL;
- FileStatus = FvProtocol->ReadSection (
- FvProtocol,
- &NameGuid,
- EFI_SECTION_USER_INTERFACE,
- 0,
- (VOID **)&UiSection,
- &Size,
- &Authentication
- );
- if (!EFI_ERROR (FileStatus)) {
- if (StrnCmp (FilePath, UiSection, UiStringLen) == 0) {
- //
- // We found a UiString match.
- //
- Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
-
- // Generate the Device Path for the file
- //DevicePath = DuplicateDevicePath(FvDevicePath);
- EfiInitializeFwVolDevicepathNode (&FileDevicePath, &NameGuid);
- *EfiAppDevicePath = AppendDevicePathNode (FvDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&FileDevicePath);
-
- FreePool (Key);
- FreePool (UiSection);
- return FileStatus;
- }
- FreePool (UiSection);
- }
- }
- } while (!EFI_ERROR (Status));
-
- FreePool(Key);
- return Status;
-}
-
-/**
- Start an EFI Application from any Firmware Volume
-
- @param EfiApp EFI Application Name
-
- @retval EFI_SUCCESS All drivers have been connected
- @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
- @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
-
-**/
-EFI_STATUS
-BdsLoadApplication (
- IN EFI_HANDLE ParentImageHandle,
- IN CHAR16* EfiApp,
- IN UINTN LoadOptionsSize,
- IN VOID* LoadOptions
- )
-{
- EFI_STATUS Status;
- UINTN NoHandles, HandleIndex;
- EFI_HANDLE *Handles;
- EFI_DEVICE_PATH *EfiAppDevicePath;
-
- // Need to connect every drivers to ensure no dependencies are missing for the application
- Status = BdsConnectAllDrivers();
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "FAIL to connect all drivers\n"));
- return Status;
- }
-
- // Search the application in any Firmware Volume
- Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiFirmwareVolume2ProtocolGuid, NULL, &NoHandles, &Handles);
- if (EFI_ERROR (Status) || (NoHandles == 0)) {
- DEBUG ((EFI_D_ERROR, "FAIL to find Firmware Volume\n"));
- return Status;
- }
-
- // Search in all Firmware Volume for the EFI Application
- for (HandleIndex = 0; HandleIndex < NoHandles; HandleIndex++) {
- EfiAppDevicePath = NULL;
- Status = BdsLoadFileFromFirmwareVolume (Handles[HandleIndex], EfiApp, EFI_FV_FILETYPE_APPLICATION, &EfiAppDevicePath);
- if (!EFI_ERROR (Status)) {
- // Start the application
- Status = BdsStartEfiApplication (ParentImageHandle, EfiAppDevicePath, LoadOptionsSize, LoadOptions);
- return Status;
- }
- }
-
- return Status;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+
+//#include <Library/DxeServicesLib.h>
+
+STATIC
+EFI_STATUS
+BdsLoadFileFromFirmwareVolume (
+ IN EFI_HANDLE FvHandle,
+ IN CHAR16 *FilePath,
+ IN EFI_FV_FILETYPE FileTypeFilter,
+ OUT EFI_DEVICE_PATH **EfiAppDevicePath
+ )
+{
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *FvProtocol;
+ VOID *Key;
+ EFI_STATUS Status, FileStatus;
+ EFI_GUID NameGuid;
+ EFI_FV_FILETYPE FileType;
+ EFI_FV_FILE_ATTRIBUTES Attributes;
+ UINTN Size;
+ UINTN UiStringLen;
+ CHAR16 *UiSection;
+ UINT32 Authentication;
+ EFI_DEVICE_PATH *FvDevicePath;
+ MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FileDevicePath;
+
+ Status = gBS->HandleProtocol (FvHandle,&gEfiFirmwareVolume2ProtocolGuid, (VOID **)&FvProtocol);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Length of FilePath
+ UiStringLen = StrLen (FilePath);
+
+ // Allocate Key
+ Key = AllocatePool (FvProtocol->KeySize);
+ ASSERT (Key != NULL);
+ ZeroMem (Key, FvProtocol->KeySize);
+
+ do {
+ // Search in all files
+ FileType = FileTypeFilter;
+
+ Status = FvProtocol->GetNextFile (FvProtocol, Key, &FileType, &NameGuid, &Attributes, &Size);
+ if (!EFI_ERROR (Status)) {
+ UiSection = NULL;
+ FileStatus = FvProtocol->ReadSection (
+ FvProtocol,
+ &NameGuid,
+ EFI_SECTION_USER_INTERFACE,
+ 0,
+ (VOID **)&UiSection,
+ &Size,
+ &Authentication
+ );
+ if (!EFI_ERROR (FileStatus)) {
+ if (StrnCmp (FilePath, UiSection, UiStringLen) == 0) {
+ //
+ // We found a UiString match.
+ //
+ Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
+
+ // Generate the Device Path for the file
+ //DevicePath = DuplicateDevicePath(FvDevicePath);
+ EfiInitializeFwVolDevicepathNode (&FileDevicePath, &NameGuid);
+ *EfiAppDevicePath = AppendDevicePathNode (FvDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&FileDevicePath);
+
+ FreePool (Key);
+ FreePool (UiSection);
+ return FileStatus;
+ }
+ FreePool (UiSection);
+ }
+ }
+ } while (!EFI_ERROR (Status));
+
+ FreePool(Key);
+ return Status;
+}
+
+/**
+ Start an EFI Application from any Firmware Volume
+
+ @param EfiApp EFI Application Name
+
+ @retval EFI_SUCCESS All drivers have been connected
+ @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
+ @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
+
+**/
+EFI_STATUS
+BdsLoadApplication (
+ IN EFI_HANDLE ParentImageHandle,
+ IN CHAR16* EfiApp,
+ IN UINTN LoadOptionsSize,
+ IN VOID* LoadOptions
+ )
+{
+ EFI_STATUS Status;
+ UINTN NoHandles, HandleIndex;
+ EFI_HANDLE *Handles;
+ EFI_DEVICE_PATH *EfiAppDevicePath;
+
+ // Need to connect every drivers to ensure no dependencies are missing for the application
+ Status = BdsConnectAllDrivers();
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "FAIL to connect all drivers\n"));
+ return Status;
+ }
+
+ // Search the application in any Firmware Volume
+ Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiFirmwareVolume2ProtocolGuid, NULL, &NoHandles, &Handles);
+ if (EFI_ERROR (Status) || (NoHandles == 0)) {
+ DEBUG ((EFI_D_ERROR, "FAIL to find Firmware Volume\n"));
+ return Status;
+ }
+
+ // Search in all Firmware Volume for the EFI Application
+ for (HandleIndex = 0; HandleIndex < NoHandles; HandleIndex++) {
+ EfiAppDevicePath = NULL;
+ Status = BdsLoadFileFromFirmwareVolume (Handles[HandleIndex], EfiApp, EFI_FV_FILETYPE_APPLICATION, &EfiAppDevicePath);
+ if (!EFI_ERROR (Status)) {
+ // Start the application
+ Status = BdsStartEfiApplication (ParentImageHandle, EfiAppDevicePath, LoadOptionsSize, LoadOptions);
+ return Status;
+ }
+ }
+
+ return Status;
+}
diff --git a/ArmPkg/Library/BdsLib/BdsFilePath.c b/ArmPkg/Library/BdsLib/BdsFilePath.c
index a8b77a3d2..2c9324379 100644
--- a/ArmPkg/Library/BdsLib/BdsFilePath.c
+++ b/ArmPkg/Library/BdsLib/BdsFilePath.c
@@ -1,906 +1,906 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-
-#include <Protocol/UsbIo.h>
-#include <Protocol/DiskIo.h>
-#include <Protocol/LoadedImage.h>
-
-#define IS_DEVICE_PATH_NODE(node,type,subtype) (((node)->Type == (type)) && ((node)->SubType == (subtype)))
-
-// Extract the FilePath from the Device Path
-CHAR16*
-BdsExtractFilePathFromDevicePath (
- IN CONST CHAR16 *StrDevicePath,
- IN UINTN NumberDevicePathNode
- )
-{
- UINTN Node;
- CHAR16 *Str;
-
- Str = (CHAR16*)StrDevicePath;
- Node = 0;
- while ((Str != NULL) && (*Str != L'\0') && (Node < NumberDevicePathNode)) {
- if ((*Str == L'/') || (*Str == L'\\')) {
- Node++;
- }
- Str++;
- }
-
- if (*Str == L'\0') {
- return NULL;
- } else {
- return Str;
- }
-}
-
-BOOLEAN
-BdsIsRemovableUsb (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- return ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) &&
- ((DevicePathSubType (DevicePath) == MSG_USB_CLASS_DP) ||
- (DevicePathSubType (DevicePath) == MSG_USB_WWID_DP)));
-}
-
-EFI_STATUS
-BdsGetDeviceUsb (
- IN EFI_DEVICE_PATH* RemovableDevicePath,
- OUT EFI_HANDLE* DeviceHandle,
- OUT EFI_DEVICE_PATH** NewDevicePath
- )
-{
- EFI_STATUS Status;
- UINTN Index;
- UINTN UsbIoHandleCount;
- EFI_HANDLE *UsbIoBuffer;
- EFI_DEVICE_PATH* UsbIoDevicePath;
- EFI_DEVICE_PATH* TmpDevicePath;
- USB_WWID_DEVICE_PATH* WwidDevicePath1;
- USB_WWID_DEVICE_PATH* WwidDevicePath2;
- USB_CLASS_DEVICE_PATH* UsbClassDevicePath1;
- USB_CLASS_DEVICE_PATH* UsbClassDevicePath2;
-
- // Get all the UsbIo handles
- UsbIoHandleCount = 0;
- Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiUsbIoProtocolGuid, NULL, &UsbIoHandleCount, &UsbIoBuffer);
- if (EFI_ERROR(Status) || (UsbIoHandleCount == 0)) {
- return Status;
- }
-
- // Check if one of the handles matches the USB description
- for (Index = 0; Index < UsbIoHandleCount; Index++) {
- Status = gBS->HandleProtocol (UsbIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **) &UsbIoDevicePath);
- if (!EFI_ERROR(Status)) {
- TmpDevicePath = UsbIoDevicePath;
- while (!IsDevicePathEnd (TmpDevicePath)) {
- // Check if the Device Path node is a USB Removable device Path node
- if (BdsIsRemovableUsb (TmpDevicePath)) {
- if (TmpDevicePath->SubType == MSG_USB_WWID_DP) {
- WwidDevicePath1 = (USB_WWID_DEVICE_PATH*)RemovableDevicePath;
- WwidDevicePath2 = (USB_WWID_DEVICE_PATH*)TmpDevicePath;
- if ((WwidDevicePath1->VendorId == WwidDevicePath2->VendorId) &&
- (WwidDevicePath1->ProductId == WwidDevicePath2->ProductId) &&
- (CompareMem (WwidDevicePath1+1, WwidDevicePath2+1, DevicePathNodeLength(WwidDevicePath1)-sizeof(USB_WWID_DEVICE_PATH)) == 0))
- {
- *DeviceHandle = UsbIoBuffer[Index];
- // Add the additional original Device Path Nodes (eg: FilePath Device Path Node) to the new Device Path
- *NewDevicePath = AppendDevicePath (UsbIoDevicePath, NextDevicePathNode(RemovableDevicePath));
- return EFI_SUCCESS;
- }
- } else {
- UsbClassDevicePath1 = (USB_CLASS_DEVICE_PATH*)RemovableDevicePath;
- UsbClassDevicePath2 = (USB_CLASS_DEVICE_PATH*)TmpDevicePath;
- if ((UsbClassDevicePath1->VendorId != 0xFFFF) && (UsbClassDevicePath1->VendorId == UsbClassDevicePath2->VendorId) &&
- (UsbClassDevicePath1->ProductId != 0xFFFF) && (UsbClassDevicePath1->ProductId == UsbClassDevicePath2->ProductId) &&
- (UsbClassDevicePath1->DeviceClass != 0xFF) && (UsbClassDevicePath1->DeviceClass == UsbClassDevicePath2->DeviceClass) &&
- (UsbClassDevicePath1->DeviceSubClass != 0xFF) && (UsbClassDevicePath1->DeviceSubClass == UsbClassDevicePath2->DeviceSubClass) &&
- (UsbClassDevicePath1->DeviceProtocol != 0xFF) && (UsbClassDevicePath1->DeviceProtocol == UsbClassDevicePath2->DeviceProtocol))
- {
- *DeviceHandle = UsbIoBuffer[Index];
- // Add the additional original Device Path Nodes (eg: FilePath Device Path Node) to the new Device Path
- *NewDevicePath = AppendDevicePath (UsbIoDevicePath, NextDevicePathNode(RemovableDevicePath));
- return EFI_SUCCESS;
- }
- }
- }
- TmpDevicePath = NextDevicePathNode (TmpDevicePath);
- }
-
- }
- }
-
- return EFI_NOT_FOUND;
-}
-
-BOOLEAN
-BdsIsRemovableHd (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- return IS_DEVICE_PATH_NODE(DevicePath, MEDIA_DEVICE_PATH, MEDIA_HARDDRIVE_DP);
-}
-
-EFI_STATUS
-BdsGetDeviceHd (
- IN EFI_DEVICE_PATH* RemovableDevicePath,
- OUT EFI_HANDLE* DeviceHandle,
- OUT EFI_DEVICE_PATH** NewDevicePath
- )
-{
- EFI_STATUS Status;
- UINTN Index;
- UINTN PartitionHandleCount;
- EFI_HANDLE *PartitionBuffer;
- EFI_DEVICE_PATH* PartitionDevicePath;
- EFI_DEVICE_PATH* TmpDevicePath;
- HARDDRIVE_DEVICE_PATH* HardDriveDevicePath1;
- HARDDRIVE_DEVICE_PATH* HardDriveDevicePath2;
-
- // Get all the DiskIo handles
- PartitionHandleCount = 0;
- Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiDiskIoProtocolGuid, NULL, &PartitionHandleCount, &PartitionBuffer);
- if (EFI_ERROR(Status) || (PartitionHandleCount == 0)) {
- return Status;
- }
-
- // Check if one of the handles matches the Hard Disk Description
- for (Index = 0; Index < PartitionHandleCount; Index++) {
- Status = gBS->HandleProtocol (PartitionBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **) &PartitionDevicePath);
- if (!EFI_ERROR(Status)) {
- TmpDevicePath = PartitionDevicePath;
- while (!IsDevicePathEnd (TmpDevicePath)) {
- // Check if the Device Path node is a HD Removable device Path node
- if (BdsIsRemovableHd (TmpDevicePath)) {
- HardDriveDevicePath1 = (HARDDRIVE_DEVICE_PATH*)RemovableDevicePath;
- HardDriveDevicePath2 = (HARDDRIVE_DEVICE_PATH*)TmpDevicePath;
- if ((HardDriveDevicePath1->SignatureType == HardDriveDevicePath2->SignatureType) &&
- (CompareGuid ((EFI_GUID *)HardDriveDevicePath1->Signature,(EFI_GUID *)HardDriveDevicePath2->Signature) == TRUE) &&
- (HardDriveDevicePath1->PartitionNumber == HardDriveDevicePath2->PartitionNumber))
- {
- *DeviceHandle = PartitionBuffer[Index];
- // Add the additional original Device Path Nodes (eg: FilePath Device Path Node) to the new Device Path
- *NewDevicePath = AppendDevicePath (PartitionDevicePath, NextDevicePathNode(RemovableDevicePath));
- return EFI_SUCCESS;
- }
- }
- TmpDevicePath = NextDevicePathNode (TmpDevicePath);
- }
-
- }
- }
-
- return EFI_NOT_FOUND;
-}
-
-/*BOOLEAN
-BdsIsRemovableCdrom (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- return IS_DEVICE_PATH_NODE(DevicePath, MEDIA_DEVICE_PATH, MEDIA_CDROM_DP);
-}
-
-EFI_STATUS
-BdsGetDeviceCdrom (
- IN EFI_DEVICE_PATH* RemovableDevicePath,
- OUT EFI_HANDLE* DeviceHandle,
- OUT EFI_DEVICE_PATH** DevicePath
- )
-{
- ASSERT(0);
- return EFI_UNSUPPORTED;
-}*/
-
-typedef BOOLEAN
-(*BDS_IS_REMOVABLE) (
- IN EFI_DEVICE_PATH* DevicePath
- );
-
-typedef EFI_STATUS
-(*BDS_GET_DEVICE) (
- IN EFI_DEVICE_PATH* RemovableDevicePath,
- OUT EFI_HANDLE* DeviceHandle,
- OUT EFI_DEVICE_PATH** DevicePath
- );
-
-typedef struct {
- BDS_IS_REMOVABLE IsRemovable;
- BDS_GET_DEVICE GetDevice;
-} BDS_REMOVABLE_DEVICE_SUPPORT;
-
-BDS_REMOVABLE_DEVICE_SUPPORT RemovableDeviceSupport[] = {
- { BdsIsRemovableUsb, BdsGetDeviceUsb },
- { BdsIsRemovableHd, BdsGetDeviceHd },
- //{ BdsIsRemovableCdrom, BdsGetDeviceCdrom }
-};
-
-STATIC
-BOOLEAN
-IsRemovableDevice (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- UINTN Index;
- EFI_DEVICE_PATH* TmpDevicePath;
-
- TmpDevicePath = DevicePath;
- while (!IsDevicePathEnd (TmpDevicePath)) {
- for (Index = 0; Index < sizeof(RemovableDeviceSupport) / sizeof(BDS_REMOVABLE_DEVICE_SUPPORT); Index++) {
- if (RemovableDeviceSupport[Index].IsRemovable(TmpDevicePath)) {
- return TRUE;
- }
- }
- TmpDevicePath = NextDevicePathNode (TmpDevicePath);
- }
-
- return FALSE;
-}
-
-STATIC
-EFI_STATUS
-TryRemovableDevice (
- IN EFI_DEVICE_PATH* DevicePath,
- OUT EFI_HANDLE* DeviceHandle,
- OUT EFI_DEVICE_PATH** NewDevicePath
- )
-{
- EFI_STATUS Status;
- UINTN Index;
- EFI_DEVICE_PATH* TmpDevicePath;
- BDS_REMOVABLE_DEVICE_SUPPORT* RemovableDevice;
- EFI_DEVICE_PATH* RemovableDevicePath;
- BOOLEAN RemovableFound;
-
- RemovableDevice = NULL;
- RemovableDevicePath = NULL;
- RemovableFound = FALSE;
- TmpDevicePath = DevicePath;
-
- while (!IsDevicePathEnd (TmpDevicePath) && !RemovableFound) {
- for (Index = 0; Index < sizeof(RemovableDeviceSupport) / sizeof(BDS_REMOVABLE_DEVICE_SUPPORT); Index++) {
- RemovableDevice = &RemovableDeviceSupport[Index];
- if (RemovableDevice->IsRemovable(TmpDevicePath)) {
- RemovableDevicePath = TmpDevicePath;
- RemovableFound = TRUE;
- break;
- }
- }
- TmpDevicePath = NextDevicePathNode (TmpDevicePath);
- }
-
- if (!RemovableFound) {
- return EFI_NOT_FOUND;
- }
-
- // Search into the current started drivers
- Status = RemovableDevice->GetDevice (RemovableDevicePath, DeviceHandle, NewDevicePath);
- if (Status == EFI_NOT_FOUND) {
- // Connect all the drivers
- BdsConnectAllDrivers ();
-
- // Search again into all the drivers
- Status = RemovableDevice->GetDevice (RemovableDevicePath, DeviceHandle, NewDevicePath);
- }
-
- return Status;
-}
-
-/**
- Connect a Device Path and return the handle of the driver that support this DevicePath
-
- @param DevicePath Device Path of the File to connect
- @param Handle Handle of the driver that support this DevicePath
- @param RemainingDevicePath Remaining DevicePath nodes that do not match the driver DevicePath
-
- @retval EFI_SUCCESS A driver that matches the Device Path has been found
- @retval EFI_NOT_FOUND No handles match the search.
- @retval EFI_INVALID_PARAMETER DevicePath or Handle is NULL
-
-**/
-EFI_STATUS
-BdsConnectDevicePath (
- IN EFI_DEVICE_PATH_PROTOCOL* DevicePath,
- OUT EFI_HANDLE *Handle,
- OUT EFI_DEVICE_PATH_PROTOCOL **RemainingDevicePath
- )
-{
- EFI_DEVICE_PATH* Remaining;
- EFI_DEVICE_PATH* NewDevicePath;
- EFI_STATUS Status;
-
- if ((DevicePath == NULL) || (Handle == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
-
- do {
- Remaining = DevicePath;
- // The LocateDevicePath() function locates all devices on DevicePath that support Protocol and returns
- // the handle to the device that is closest to DevicePath. On output, the device path pointer is modified
- // to point to the remaining part of the device path
- Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &Remaining, Handle);
- if (!EFI_ERROR (Status)) {
- // Recursive = FALSE: We do not want to start all the device tree
- Status = gBS->ConnectController (*Handle, NULL, Remaining, FALSE);
- }
-
- /*// We need to check if RemainingDevicePath does not point on the last node. Otherwise, calling
- // NextDevicePathNode() will return an undetermined Device Path Node
- if (!IsDevicePathEnd (RemainingDevicePath)) {
- RemainingDevicePath = NextDevicePathNode (RemainingDevicePath);
- }*/
- } while (!EFI_ERROR (Status) && !IsDevicePathEnd (Remaining));
-
- if (!EFI_ERROR (Status)) {
- // Now, we have got the whole Device Path connected, call again ConnectController to ensure all the supported Driver
- // Binding Protocol are connected (such as DiskIo and SimpleFileSystem)
- Remaining = DevicePath;
- Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid,&Remaining,Handle);
- if (!EFI_ERROR (Status)) {
- Status = gBS->ConnectController (*Handle, NULL, Remaining, FALSE);
- if (EFI_ERROR (Status)) {
- // If the last node is a Memory Map Device Path just return EFI_SUCCESS.
- if ((Remaining->Type == HARDWARE_DEVICE_PATH) && (Remaining->SubType == HW_MEMMAP_DP)) {
- Status = EFI_SUCCESS;
- }
- }
- }
- } else if (!IsDevicePathEnd (Remaining) && !IsRemovableDevice (Remaining)) {
-
- /*// If the remaining Device Path is a FilePath or MemoryMap then we consider the Device Path has been loaded correctly
- if ((Remaining->Type == MEDIA_DEVICE_PATH) && (Remaining->SubType == MEDIA_FILEPATH_DP)) {
- Status = EFI_SUCCESS;
- } else if ((Remaining->Type == HARDWARE_DEVICE_PATH) && (Remaining->SubType == HW_MEMMAP_DP)) {
- Status = EFI_SUCCESS;
- }*/
-
- //TODO: Should we just return success and leave the caller decide if it is the expected RemainingPath
- Status = EFI_SUCCESS;
- } else {
- Status = TryRemovableDevice (DevicePath, Handle, &NewDevicePath);
- if (!EFI_ERROR (Status)) {
- return BdsConnectDevicePath (NewDevicePath, Handle, RemainingDevicePath);
- }
- }
-
- if (RemainingDevicePath) {
- *RemainingDevicePath = Remaining;
- }
-
- return Status;
-}
-
-BOOLEAN
-BdsFileSystemSupport (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath
- )
-{
- EFI_STATUS Status;
- EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *FsProtocol;
-
- Status = gBS->HandleProtocol (Handle,&gEfiSimpleFileSystemProtocolGuid, (VOID **)&FsProtocol);
-
- return (!EFI_ERROR(Status) && IS_DEVICE_PATH_NODE(RemainingDevicePath,MEDIA_DEVICE_PATH,MEDIA_FILEPATH_DP));
-}
-
-EFI_STATUS
-BdsFileSystemLoadImage (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS* Image,
- OUT UINTN *ImageSize
- )
-{
- FILEPATH_DEVICE_PATH* FilePathDevicePath;
- EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *FsProtocol;
- EFI_FILE_PROTOCOL *Fs;
- EFI_STATUS Status;
- EFI_FILE_INFO *FileInfo;
- EFI_FILE_PROTOCOL *File;
- UINTN Size;
-
- ASSERT (IS_DEVICE_PATH_NODE(RemainingDevicePath,MEDIA_DEVICE_PATH,MEDIA_FILEPATH_DP));
-
- FilePathDevicePath = (FILEPATH_DEVICE_PATH*)RemainingDevicePath;
-
- Status = gBS->HandleProtocol(Handle,&gEfiSimpleFileSystemProtocolGuid, (VOID **)&FsProtocol);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Try to Open the volume and get root directory
- Status = FsProtocol->OpenVolume (FsProtocol, &Fs);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- File = NULL;
- Status = Fs->Open(Fs, &File, FilePathDevicePath->PathName, EFI_FILE_MODE_READ, 0);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Size = 0;
- File->GetInfo(File, &gEfiFileInfoGuid, &Size, NULL);
- FileInfo = AllocatePool (Size);
- Status = File->GetInfo(File, &gEfiFileInfoGuid, &Size, FileInfo);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Get the file size
- Size = FileInfo->FileSize;
- if (ImageSize) {
- *ImageSize = Size;
- }
- FreePool(FileInfo);
-
- Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
- // Try to allocate in any pages if failed to allocate memory at the defined location
- if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
- Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
- }
- if (!EFI_ERROR(Status)) {
- Status = File->Read (File, &Size, (VOID*)(UINTN)(*Image));
- }
-
- return Status;
-}
-
-BOOLEAN
-BdsMemoryMapSupport (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath
- )
-{
- return IS_DEVICE_PATH_NODE(DevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP) ||
- IS_DEVICE_PATH_NODE(RemainingDevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP);
-}
-
-EFI_STATUS
-BdsMemoryMapLoadImage (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS* Image,
- OUT UINTN *ImageSize
- )
-{
- EFI_STATUS Status;
- MEMMAP_DEVICE_PATH* MemMapPathDevicePath;
- UINTN Size;
-
- if (IS_DEVICE_PATH_NODE(RemainingDevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP)) {
- MemMapPathDevicePath = (MEMMAP_DEVICE_PATH*)RemainingDevicePath;
- } else {
- ASSERT (IS_DEVICE_PATH_NODE(DevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP));
- MemMapPathDevicePath = (MEMMAP_DEVICE_PATH*)DevicePath;
- }
-
- Size = MemMapPathDevicePath->EndingAddress - MemMapPathDevicePath->StartingAddress;
- if (Size == 0) {
- return EFI_INVALID_PARAMETER;
- }
-
- Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
- // Try to allocate in any pages if failed to allocate memory at the defined location
- if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
- Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
- }
- if (!EFI_ERROR(Status)) {
- CopyMem ((VOID*)(UINTN)(*Image), (CONST VOID*)(UINTN)MemMapPathDevicePath->StartingAddress, Size);
-
- if (ImageSize != NULL) {
- *ImageSize = Size;
- }
- }
-
- return Status;
-}
-
-BOOLEAN
-BdsFirmwareVolumeSupport (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath
- )
-{
- return IS_DEVICE_PATH_NODE(RemainingDevicePath, MEDIA_DEVICE_PATH, MEDIA_PIWG_FW_FILE_DP);
-}
-
-EFI_STATUS
-BdsFirmwareVolumeLoadImage (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS* Image,
- OUT UINTN *ImageSize
- )
-{
- EFI_STATUS Status;
- EFI_FIRMWARE_VOLUME2_PROTOCOL *FwVol;
- EFI_GUID *FvNameGuid;
- EFI_SECTION_TYPE SectionType;
- EFI_FV_FILETYPE FvType;
- EFI_FV_FILE_ATTRIBUTES Attrib;
- UINT32 AuthenticationStatus;
- VOID* ImageBuffer;
-
- ASSERT (IS_DEVICE_PATH_NODE(RemainingDevicePath, MEDIA_DEVICE_PATH, MEDIA_PIWG_FW_FILE_DP));
-
- Status = gBS->HandleProtocol(Handle,&gEfiFirmwareVolume2ProtocolGuid, (VOID **)&FwVol);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- FvNameGuid = EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)RemainingDevicePath);
- if (FvNameGuid == NULL) {
- Status = EFI_INVALID_PARAMETER;
- }
-
- SectionType = EFI_SECTION_PE32;
- AuthenticationStatus = 0;
- //Note: ReadSection at the opposite of ReadFile does not allow to pass ImageBuffer == NULL to get the size of the file.
- ImageBuffer = NULL;
- Status = FwVol->ReadSection (
- FwVol,
- FvNameGuid,
- SectionType,
- 0,
- &ImageBuffer,
- ImageSize,
- &AuthenticationStatus
- );
- if (!EFI_ERROR (Status)) {
-#if 0
- // In case the buffer has some address requirements, we must copy the buffer to a buffer following the requirements
- if (Type != AllocateAnyPages) {
- Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize),Image);
- if (!EFI_ERROR(Status)) {
- CopyMem ((VOID*)(UINTN)(*Image), ImageBuffer, *ImageSize);
- FreePool (ImageBuffer);
- }
- }
-#else
- // We must copy the buffer into a page allocations. Otherwise, the caller could call gBS->FreePages() on the pool allocation
- Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
- // Try to allocate in any pages if failed to allocate memory at the defined location
- if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
- Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
- }
- if (!EFI_ERROR(Status)) {
- CopyMem ((VOID*)(UINTN)(*Image), ImageBuffer, *ImageSize);
- FreePool (ImageBuffer);
- }
-#endif
- } else {
- // Try a raw file, since a PE32 SECTION does not exist
- Status = FwVol->ReadFile (
- FwVol,
- FvNameGuid,
- NULL,
- ImageSize,
- &FvType,
- &Attrib,
- &AuthenticationStatus
- );
- if (!EFI_ERROR(Status)) {
- Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
- // Try to allocate in any pages if failed to allocate memory at the defined location
- if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
- Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
- }
- if (!EFI_ERROR(Status)) {
- Status = FwVol->ReadFile (
- FwVol,
- FvNameGuid,
- (VOID*)(UINTN)(*Image),
- ImageSize,
- &FvType,
- &Attrib,
- &AuthenticationStatus
- );
- }
- }
- }
- return Status;
-}
-
-BOOLEAN
-BdsPxeSupport (
- IN EFI_DEVICE_PATH* DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH* RemainingDevicePath
- )
-{
- EFI_STATUS Status;
- EFI_PXE_BASE_CODE_PROTOCOL* PxeBcProtocol;
-
- if (!IsDevicePathEnd(RemainingDevicePath)) {
- return FALSE;
- }
-
- Status = gBS->HandleProtocol (Handle, &gEfiPxeBaseCodeProtocolGuid, (VOID **)&PxeBcProtocol);
- if (EFI_ERROR (Status)) {
- return FALSE;
- } else {
- return TRUE;
- }
-}
-
-EFI_STATUS
-BdsPxeLoadImage (
- IN EFI_DEVICE_PATH* DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH* RemainingDevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS *Image,
- OUT UINTN *ImageSize
- )
-{
- EFI_STATUS Status;
- EFI_LOAD_FILE_PROTOCOL *LoadFileProtocol;
- UINTN BufferSize;
-
- // Get Load File Protocol attached to the PXE protocol
- Status = gBS->HandleProtocol (Handle, &gEfiLoadFileProtocolGuid, (VOID **)&LoadFileProtocol);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- Status = LoadFileProtocol->LoadFile (LoadFileProtocol, DevicePath, TRUE, &BufferSize, NULL);
- if (Status == EFI_BUFFER_TOO_SMALL) {
- Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(BufferSize), Image);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Status = LoadFileProtocol->LoadFile (LoadFileProtocol, DevicePath, TRUE, &BufferSize, (VOID*)(UINTN)(*Image));
- if (!EFI_ERROR(Status) && (ImageSize != NULL)) {
- *ImageSize = BufferSize;
- }
- }
-
- return Status;
-}
-
-BOOLEAN
-BdsTftpSupport (
- IN EFI_DEVICE_PATH* DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH* RemainingDevicePath
- )
-{
- EFI_STATUS Status;
- EFI_DEVICE_PATH *NextDevicePath;
- EFI_PXE_BASE_CODE_PROTOCOL *PxeBcProtocol;
-
- // Validate the Remaining Device Path
- if (IsDevicePathEnd(RemainingDevicePath)) {
- return FALSE;
- }
- if (!IS_DEVICE_PATH_NODE(RemainingDevicePath,MESSAGING_DEVICE_PATH,MSG_IPv4_DP) &&
- !IS_DEVICE_PATH_NODE(RemainingDevicePath,MESSAGING_DEVICE_PATH,MSG_IPv6_DP)) {
- return FALSE;
- }
- NextDevicePath = NextDevicePathNode (RemainingDevicePath);
- if (IsDevicePathEnd(NextDevicePath)) {
- return FALSE;
- }
- if (!IS_DEVICE_PATH_NODE(NextDevicePath,MEDIA_DEVICE_PATH,MEDIA_FILEPATH_DP)) {
- return FALSE;
- }
-
- Status = gBS->HandleProtocol (Handle, &gEfiPxeBaseCodeProtocolGuid, (VOID **)&PxeBcProtocol);
- if (EFI_ERROR (Status)) {
- return FALSE;
- } else {
- return TRUE;
- }
-}
-
-EFI_STATUS
-BdsTftpLoadImage (
- IN EFI_DEVICE_PATH* DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH* RemainingDevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS *Image,
- OUT UINTN *ImageSize
- )
-{
- EFI_STATUS Status;
- EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
- UINT64 TftpBufferSize;
- VOID* TftpBuffer;
- EFI_IP_ADDRESS ServerIp;
- IPv4_DEVICE_PATH* IPv4DevicePathNode;
- FILEPATH_DEVICE_PATH* FilePathDevicePath;
- EFI_IP_ADDRESS LocalIp;
-
- ASSERT(IS_DEVICE_PATH_NODE(RemainingDevicePath,MESSAGING_DEVICE_PATH,MSG_IPv4_DP));
-
- IPv4DevicePathNode = (IPv4_DEVICE_PATH*)RemainingDevicePath;
- FilePathDevicePath = (FILEPATH_DEVICE_PATH*)(IPv4DevicePathNode + 1);
-
- Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Status = Pxe->Start (Pxe, FALSE);
- if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
- return Status;
- }
-
- if (!IPv4DevicePathNode->StaticIpAddress) {
- Status = Pxe->Dhcp(Pxe, TRUE);
- } else {
- CopyMem (&LocalIp.v4, &IPv4DevicePathNode->LocalIpAddress, sizeof (EFI_IPv4_ADDRESS));
- Status = Pxe->SetStationIp (Pxe, &LocalIp, NULL);
- }
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- CopyMem (&ServerIp.v4, &IPv4DevicePathNode->RemoteIpAddress, sizeof (EFI_IPv4_ADDRESS));
-
- Status = Pxe->Mtftp (
- Pxe,
- EFI_PXE_BASE_CODE_TFTP_GET_FILE_SIZE,
- NULL,
- FALSE,
- &TftpBufferSize,
- NULL,
- &ServerIp,
- (UINT8 *)FilePathDevicePath->PathName,
- NULL,
- TRUE
- );
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Allocate a buffer to hold the whole file.
- TftpBuffer = AllocatePool(TftpBufferSize);
- if (TftpBuffer == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- Status = Pxe->Mtftp (
- Pxe,
- EFI_PXE_BASE_CODE_TFTP_READ_FILE,
- TftpBuffer,
- FALSE,
- &TftpBufferSize,
- NULL,
- &ServerIp,
- (UINT8 *)FilePathDevicePath->PathName,
- NULL,
- FALSE
- );
- if (EFI_ERROR(Status)) {
- FreePool(TftpBuffer);
- } else if (ImageSize != NULL) {
- *ImageSize = (UINTN)TftpBufferSize;
- }
-
- return Status;
-}
-
-BDS_FILE_LOADER FileLoaders[] = {
- { BdsFileSystemSupport, BdsFileSystemLoadImage },
- { BdsFirmwareVolumeSupport, BdsFirmwareVolumeLoadImage },
- //{ BdsLoadFileSupport, BdsLoadFileLoadImage },
- { BdsMemoryMapSupport, BdsMemoryMapLoadImage },
- { BdsPxeSupport, BdsPxeLoadImage },
- { BdsTftpSupport, BdsTftpLoadImage },
- { NULL, NULL }
-};
-
-EFI_STATUS
-BdsLoadImage (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS* Image,
- OUT UINTN *FileSize
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE Handle;
- EFI_DEVICE_PATH *RemainingDevicePath;
- BDS_FILE_LOADER* FileLoader;
-
- Status = BdsConnectDevicePath (DevicePath, &Handle, &RemainingDevicePath);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- FileLoader = FileLoaders;
- while (FileLoader->Support != NULL) {
- if (FileLoader->Support (DevicePath, Handle, RemainingDevicePath)) {
- return FileLoader->LoadImage (DevicePath, Handle, RemainingDevicePath, Type, Image, FileSize);
- }
- FileLoader++;
- }
-
- return EFI_UNSUPPORTED;
-}
-
-/**
- Start an EFI Application from a Device Path
-
- @param ParentImageHandle Handle of the calling image
- @param DevicePath Location of the EFI Application
-
- @retval EFI_SUCCESS All drivers have been connected
- @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
- @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
-
-**/
-EFI_STATUS
-BdsStartEfiApplication (
- IN EFI_HANDLE ParentImageHandle,
- IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
- IN UINTN LoadOptionsSize,
- IN VOID* LoadOptions
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE ImageHandle;
- EFI_PHYSICAL_ADDRESS BinaryBuffer;
- UINTN BinarySize;
- EFI_LOADED_IMAGE_PROTOCOL* LoadedImage;
-
- // Find the nearest supported file loader
- Status = BdsLoadImage (DevicePath, AllocateAnyPages, &BinaryBuffer, &BinarySize);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Load the image from the Buffer with Boot Services function
- Status = gBS->LoadImage (TRUE, ParentImageHandle, DevicePath, (VOID*)(UINTN)BinaryBuffer, BinarySize, &ImageHandle);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Passed LoadOptions to the EFI Application
- if (LoadOptionsSize != 0) {
- Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &LoadedImage);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- LoadedImage->LoadOptionsSize = LoadOptionsSize;
- LoadedImage->LoadOptions = LoadOptions;
- }
-
- // Before calling the image, enable the Watchdog Timer for the 5 Minute period
- gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
- // Start the image
- Status = gBS->StartImage (ImageHandle, NULL, NULL);
- // Clear the Watchdog Timer after the image returns
- gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
-
- return Status;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+
+#include <Protocol/UsbIo.h>
+#include <Protocol/DiskIo.h>
+#include <Protocol/LoadedImage.h>
+
+#define IS_DEVICE_PATH_NODE(node,type,subtype) (((node)->Type == (type)) && ((node)->SubType == (subtype)))
+
+// Extract the FilePath from the Device Path
+CHAR16*
+BdsExtractFilePathFromDevicePath (
+ IN CONST CHAR16 *StrDevicePath,
+ IN UINTN NumberDevicePathNode
+ )
+{
+ UINTN Node;
+ CHAR16 *Str;
+
+ Str = (CHAR16*)StrDevicePath;
+ Node = 0;
+ while ((Str != NULL) && (*Str != L'\0') && (Node < NumberDevicePathNode)) {
+ if ((*Str == L'/') || (*Str == L'\\')) {
+ Node++;
+ }
+ Str++;
+ }
+
+ if (*Str == L'\0') {
+ return NULL;
+ } else {
+ return Str;
+ }
+}
+
+BOOLEAN
+BdsIsRemovableUsb (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ return ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) &&
+ ((DevicePathSubType (DevicePath) == MSG_USB_CLASS_DP) ||
+ (DevicePathSubType (DevicePath) == MSG_USB_WWID_DP)));
+}
+
+EFI_STATUS
+BdsGetDeviceUsb (
+ IN EFI_DEVICE_PATH* RemovableDevicePath,
+ OUT EFI_HANDLE* DeviceHandle,
+ OUT EFI_DEVICE_PATH** NewDevicePath
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN UsbIoHandleCount;
+ EFI_HANDLE *UsbIoBuffer;
+ EFI_DEVICE_PATH* UsbIoDevicePath;
+ EFI_DEVICE_PATH* TmpDevicePath;
+ USB_WWID_DEVICE_PATH* WwidDevicePath1;
+ USB_WWID_DEVICE_PATH* WwidDevicePath2;
+ USB_CLASS_DEVICE_PATH* UsbClassDevicePath1;
+ USB_CLASS_DEVICE_PATH* UsbClassDevicePath2;
+
+ // Get all the UsbIo handles
+ UsbIoHandleCount = 0;
+ Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiUsbIoProtocolGuid, NULL, &UsbIoHandleCount, &UsbIoBuffer);
+ if (EFI_ERROR(Status) || (UsbIoHandleCount == 0)) {
+ return Status;
+ }
+
+ // Check if one of the handles matches the USB description
+ for (Index = 0; Index < UsbIoHandleCount; Index++) {
+ Status = gBS->HandleProtocol (UsbIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **) &UsbIoDevicePath);
+ if (!EFI_ERROR(Status)) {
+ TmpDevicePath = UsbIoDevicePath;
+ while (!IsDevicePathEnd (TmpDevicePath)) {
+ // Check if the Device Path node is a USB Removable device Path node
+ if (BdsIsRemovableUsb (TmpDevicePath)) {
+ if (TmpDevicePath->SubType == MSG_USB_WWID_DP) {
+ WwidDevicePath1 = (USB_WWID_DEVICE_PATH*)RemovableDevicePath;
+ WwidDevicePath2 = (USB_WWID_DEVICE_PATH*)TmpDevicePath;
+ if ((WwidDevicePath1->VendorId == WwidDevicePath2->VendorId) &&
+ (WwidDevicePath1->ProductId == WwidDevicePath2->ProductId) &&
+ (CompareMem (WwidDevicePath1+1, WwidDevicePath2+1, DevicePathNodeLength(WwidDevicePath1)-sizeof(USB_WWID_DEVICE_PATH)) == 0))
+ {
+ *DeviceHandle = UsbIoBuffer[Index];
+ // Add the additional original Device Path Nodes (eg: FilePath Device Path Node) to the new Device Path
+ *NewDevicePath = AppendDevicePath (UsbIoDevicePath, NextDevicePathNode(RemovableDevicePath));
+ return EFI_SUCCESS;
+ }
+ } else {
+ UsbClassDevicePath1 = (USB_CLASS_DEVICE_PATH*)RemovableDevicePath;
+ UsbClassDevicePath2 = (USB_CLASS_DEVICE_PATH*)TmpDevicePath;
+ if ((UsbClassDevicePath1->VendorId != 0xFFFF) && (UsbClassDevicePath1->VendorId == UsbClassDevicePath2->VendorId) &&
+ (UsbClassDevicePath1->ProductId != 0xFFFF) && (UsbClassDevicePath1->ProductId == UsbClassDevicePath2->ProductId) &&
+ (UsbClassDevicePath1->DeviceClass != 0xFF) && (UsbClassDevicePath1->DeviceClass == UsbClassDevicePath2->DeviceClass) &&
+ (UsbClassDevicePath1->DeviceSubClass != 0xFF) && (UsbClassDevicePath1->DeviceSubClass == UsbClassDevicePath2->DeviceSubClass) &&
+ (UsbClassDevicePath1->DeviceProtocol != 0xFF) && (UsbClassDevicePath1->DeviceProtocol == UsbClassDevicePath2->DeviceProtocol))
+ {
+ *DeviceHandle = UsbIoBuffer[Index];
+ // Add the additional original Device Path Nodes (eg: FilePath Device Path Node) to the new Device Path
+ *NewDevicePath = AppendDevicePath (UsbIoDevicePath, NextDevicePathNode(RemovableDevicePath));
+ return EFI_SUCCESS;
+ }
+ }
+ }
+ TmpDevicePath = NextDevicePathNode (TmpDevicePath);
+ }
+
+ }
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+BOOLEAN
+BdsIsRemovableHd (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ return IS_DEVICE_PATH_NODE(DevicePath, MEDIA_DEVICE_PATH, MEDIA_HARDDRIVE_DP);
+}
+
+EFI_STATUS
+BdsGetDeviceHd (
+ IN EFI_DEVICE_PATH* RemovableDevicePath,
+ OUT EFI_HANDLE* DeviceHandle,
+ OUT EFI_DEVICE_PATH** NewDevicePath
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ UINTN PartitionHandleCount;
+ EFI_HANDLE *PartitionBuffer;
+ EFI_DEVICE_PATH* PartitionDevicePath;
+ EFI_DEVICE_PATH* TmpDevicePath;
+ HARDDRIVE_DEVICE_PATH* HardDriveDevicePath1;
+ HARDDRIVE_DEVICE_PATH* HardDriveDevicePath2;
+
+ // Get all the DiskIo handles
+ PartitionHandleCount = 0;
+ Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiDiskIoProtocolGuid, NULL, &PartitionHandleCount, &PartitionBuffer);
+ if (EFI_ERROR(Status) || (PartitionHandleCount == 0)) {
+ return Status;
+ }
+
+ // Check if one of the handles matches the Hard Disk Description
+ for (Index = 0; Index < PartitionHandleCount; Index++) {
+ Status = gBS->HandleProtocol (PartitionBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **) &PartitionDevicePath);
+ if (!EFI_ERROR(Status)) {
+ TmpDevicePath = PartitionDevicePath;
+ while (!IsDevicePathEnd (TmpDevicePath)) {
+ // Check if the Device Path node is a HD Removable device Path node
+ if (BdsIsRemovableHd (TmpDevicePath)) {
+ HardDriveDevicePath1 = (HARDDRIVE_DEVICE_PATH*)RemovableDevicePath;
+ HardDriveDevicePath2 = (HARDDRIVE_DEVICE_PATH*)TmpDevicePath;
+ if ((HardDriveDevicePath1->SignatureType == HardDriveDevicePath2->SignatureType) &&
+ (CompareGuid ((EFI_GUID *)HardDriveDevicePath1->Signature,(EFI_GUID *)HardDriveDevicePath2->Signature) == TRUE) &&
+ (HardDriveDevicePath1->PartitionNumber == HardDriveDevicePath2->PartitionNumber))
+ {
+ *DeviceHandle = PartitionBuffer[Index];
+ // Add the additional original Device Path Nodes (eg: FilePath Device Path Node) to the new Device Path
+ *NewDevicePath = AppendDevicePath (PartitionDevicePath, NextDevicePathNode(RemovableDevicePath));
+ return EFI_SUCCESS;
+ }
+ }
+ TmpDevicePath = NextDevicePathNode (TmpDevicePath);
+ }
+
+ }
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+/*BOOLEAN
+BdsIsRemovableCdrom (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ return IS_DEVICE_PATH_NODE(DevicePath, MEDIA_DEVICE_PATH, MEDIA_CDROM_DP);
+}
+
+EFI_STATUS
+BdsGetDeviceCdrom (
+ IN EFI_DEVICE_PATH* RemovableDevicePath,
+ OUT EFI_HANDLE* DeviceHandle,
+ OUT EFI_DEVICE_PATH** DevicePath
+ )
+{
+ ASSERT(0);
+ return EFI_UNSUPPORTED;
+}*/
+
+typedef BOOLEAN
+(*BDS_IS_REMOVABLE) (
+ IN EFI_DEVICE_PATH* DevicePath
+ );
+
+typedef EFI_STATUS
+(*BDS_GET_DEVICE) (
+ IN EFI_DEVICE_PATH* RemovableDevicePath,
+ OUT EFI_HANDLE* DeviceHandle,
+ OUT EFI_DEVICE_PATH** DevicePath
+ );
+
+typedef struct {
+ BDS_IS_REMOVABLE IsRemovable;
+ BDS_GET_DEVICE GetDevice;
+} BDS_REMOVABLE_DEVICE_SUPPORT;
+
+BDS_REMOVABLE_DEVICE_SUPPORT RemovableDeviceSupport[] = {
+ { BdsIsRemovableUsb, BdsGetDeviceUsb },
+ { BdsIsRemovableHd, BdsGetDeviceHd },
+ //{ BdsIsRemovableCdrom, BdsGetDeviceCdrom }
+};
+
+STATIC
+BOOLEAN
+IsRemovableDevice (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ UINTN Index;
+ EFI_DEVICE_PATH* TmpDevicePath;
+
+ TmpDevicePath = DevicePath;
+ while (!IsDevicePathEnd (TmpDevicePath)) {
+ for (Index = 0; Index < sizeof(RemovableDeviceSupport) / sizeof(BDS_REMOVABLE_DEVICE_SUPPORT); Index++) {
+ if (RemovableDeviceSupport[Index].IsRemovable(TmpDevicePath)) {
+ return TRUE;
+ }
+ }
+ TmpDevicePath = NextDevicePathNode (TmpDevicePath);
+ }
+
+ return FALSE;
+}
+
+STATIC
+EFI_STATUS
+TryRemovableDevice (
+ IN EFI_DEVICE_PATH* DevicePath,
+ OUT EFI_HANDLE* DeviceHandle,
+ OUT EFI_DEVICE_PATH** NewDevicePath
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_DEVICE_PATH* TmpDevicePath;
+ BDS_REMOVABLE_DEVICE_SUPPORT* RemovableDevice;
+ EFI_DEVICE_PATH* RemovableDevicePath;
+ BOOLEAN RemovableFound;
+
+ RemovableDevice = NULL;
+ RemovableDevicePath = NULL;
+ RemovableFound = FALSE;
+ TmpDevicePath = DevicePath;
+
+ while (!IsDevicePathEnd (TmpDevicePath) && !RemovableFound) {
+ for (Index = 0; Index < sizeof(RemovableDeviceSupport) / sizeof(BDS_REMOVABLE_DEVICE_SUPPORT); Index++) {
+ RemovableDevice = &RemovableDeviceSupport[Index];
+ if (RemovableDevice->IsRemovable(TmpDevicePath)) {
+ RemovableDevicePath = TmpDevicePath;
+ RemovableFound = TRUE;
+ break;
+ }
+ }
+ TmpDevicePath = NextDevicePathNode (TmpDevicePath);
+ }
+
+ if (!RemovableFound) {
+ return EFI_NOT_FOUND;
+ }
+
+ // Search into the current started drivers
+ Status = RemovableDevice->GetDevice (RemovableDevicePath, DeviceHandle, NewDevicePath);
+ if (Status == EFI_NOT_FOUND) {
+ // Connect all the drivers
+ BdsConnectAllDrivers ();
+
+ // Search again into all the drivers
+ Status = RemovableDevice->GetDevice (RemovableDevicePath, DeviceHandle, NewDevicePath);
+ }
+
+ return Status;
+}
+
+/**
+ Connect a Device Path and return the handle of the driver that support this DevicePath
+
+ @param DevicePath Device Path of the File to connect
+ @param Handle Handle of the driver that support this DevicePath
+ @param RemainingDevicePath Remaining DevicePath nodes that do not match the driver DevicePath
+
+ @retval EFI_SUCCESS A driver that matches the Device Path has been found
+ @retval EFI_NOT_FOUND No handles match the search.
+ @retval EFI_INVALID_PARAMETER DevicePath or Handle is NULL
+
+**/
+EFI_STATUS
+BdsConnectDevicePath (
+ IN EFI_DEVICE_PATH_PROTOCOL* DevicePath,
+ OUT EFI_HANDLE *Handle,
+ OUT EFI_DEVICE_PATH_PROTOCOL **RemainingDevicePath
+ )
+{
+ EFI_DEVICE_PATH* Remaining;
+ EFI_DEVICE_PATH* NewDevicePath;
+ EFI_STATUS Status;
+
+ if ((DevicePath == NULL) || (Handle == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ do {
+ Remaining = DevicePath;
+ // The LocateDevicePath() function locates all devices on DevicePath that support Protocol and returns
+ // the handle to the device that is closest to DevicePath. On output, the device path pointer is modified
+ // to point to the remaining part of the device path
+ Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &Remaining, Handle);
+ if (!EFI_ERROR (Status)) {
+ // Recursive = FALSE: We do not want to start all the device tree
+ Status = gBS->ConnectController (*Handle, NULL, Remaining, FALSE);
+ }
+
+ /*// We need to check if RemainingDevicePath does not point on the last node. Otherwise, calling
+ // NextDevicePathNode() will return an undetermined Device Path Node
+ if (!IsDevicePathEnd (RemainingDevicePath)) {
+ RemainingDevicePath = NextDevicePathNode (RemainingDevicePath);
+ }*/
+ } while (!EFI_ERROR (Status) && !IsDevicePathEnd (Remaining));
+
+ if (!EFI_ERROR (Status)) {
+ // Now, we have got the whole Device Path connected, call again ConnectController to ensure all the supported Driver
+ // Binding Protocol are connected (such as DiskIo and SimpleFileSystem)
+ Remaining = DevicePath;
+ Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid,&Remaining,Handle);
+ if (!EFI_ERROR (Status)) {
+ Status = gBS->ConnectController (*Handle, NULL, Remaining, FALSE);
+ if (EFI_ERROR (Status)) {
+ // If the last node is a Memory Map Device Path just return EFI_SUCCESS.
+ if ((Remaining->Type == HARDWARE_DEVICE_PATH) && (Remaining->SubType == HW_MEMMAP_DP)) {
+ Status = EFI_SUCCESS;
+ }
+ }
+ }
+ } else if (!IsDevicePathEnd (Remaining) && !IsRemovableDevice (Remaining)) {
+
+ /*// If the remaining Device Path is a FilePath or MemoryMap then we consider the Device Path has been loaded correctly
+ if ((Remaining->Type == MEDIA_DEVICE_PATH) && (Remaining->SubType == MEDIA_FILEPATH_DP)) {
+ Status = EFI_SUCCESS;
+ } else if ((Remaining->Type == HARDWARE_DEVICE_PATH) && (Remaining->SubType == HW_MEMMAP_DP)) {
+ Status = EFI_SUCCESS;
+ }*/
+
+ //TODO: Should we just return success and leave the caller decide if it is the expected RemainingPath
+ Status = EFI_SUCCESS;
+ } else {
+ Status = TryRemovableDevice (DevicePath, Handle, &NewDevicePath);
+ if (!EFI_ERROR (Status)) {
+ return BdsConnectDevicePath (NewDevicePath, Handle, RemainingDevicePath);
+ }
+ }
+
+ if (RemainingDevicePath) {
+ *RemainingDevicePath = Remaining;
+ }
+
+ return Status;
+}
+
+BOOLEAN
+BdsFileSystemSupport (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath
+ )
+{
+ EFI_STATUS Status;
+ EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *FsProtocol;
+
+ Status = gBS->HandleProtocol (Handle,&gEfiSimpleFileSystemProtocolGuid, (VOID **)&FsProtocol);
+
+ return (!EFI_ERROR(Status) && IS_DEVICE_PATH_NODE(RemainingDevicePath,MEDIA_DEVICE_PATH,MEDIA_FILEPATH_DP));
+}
+
+EFI_STATUS
+BdsFileSystemLoadImage (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS* Image,
+ OUT UINTN *ImageSize
+ )
+{
+ FILEPATH_DEVICE_PATH* FilePathDevicePath;
+ EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *FsProtocol;
+ EFI_FILE_PROTOCOL *Fs;
+ EFI_STATUS Status;
+ EFI_FILE_INFO *FileInfo;
+ EFI_FILE_PROTOCOL *File;
+ UINTN Size;
+
+ ASSERT (IS_DEVICE_PATH_NODE(RemainingDevicePath,MEDIA_DEVICE_PATH,MEDIA_FILEPATH_DP));
+
+ FilePathDevicePath = (FILEPATH_DEVICE_PATH*)RemainingDevicePath;
+
+ Status = gBS->HandleProtocol(Handle,&gEfiSimpleFileSystemProtocolGuid, (VOID **)&FsProtocol);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Try to Open the volume and get root directory
+ Status = FsProtocol->OpenVolume (FsProtocol, &Fs);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ File = NULL;
+ Status = Fs->Open(Fs, &File, FilePathDevicePath->PathName, EFI_FILE_MODE_READ, 0);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Size = 0;
+ File->GetInfo(File, &gEfiFileInfoGuid, &Size, NULL);
+ FileInfo = AllocatePool (Size);
+ Status = File->GetInfo(File, &gEfiFileInfoGuid, &Size, FileInfo);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Get the file size
+ Size = FileInfo->FileSize;
+ if (ImageSize) {
+ *ImageSize = Size;
+ }
+ FreePool(FileInfo);
+
+ Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
+ // Try to allocate in any pages if failed to allocate memory at the defined location
+ if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
+ Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
+ }
+ if (!EFI_ERROR(Status)) {
+ Status = File->Read (File, &Size, (VOID*)(UINTN)(*Image));
+ }
+
+ return Status;
+}
+
+BOOLEAN
+BdsMemoryMapSupport (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath
+ )
+{
+ return IS_DEVICE_PATH_NODE(DevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP) ||
+ IS_DEVICE_PATH_NODE(RemainingDevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP);
+}
+
+EFI_STATUS
+BdsMemoryMapLoadImage (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS* Image,
+ OUT UINTN *ImageSize
+ )
+{
+ EFI_STATUS Status;
+ MEMMAP_DEVICE_PATH* MemMapPathDevicePath;
+ UINTN Size;
+
+ if (IS_DEVICE_PATH_NODE(RemainingDevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP)) {
+ MemMapPathDevicePath = (MEMMAP_DEVICE_PATH*)RemainingDevicePath;
+ } else {
+ ASSERT (IS_DEVICE_PATH_NODE(DevicePath,HARDWARE_DEVICE_PATH,HW_MEMMAP_DP));
+ MemMapPathDevicePath = (MEMMAP_DEVICE_PATH*)DevicePath;
+ }
+
+ Size = MemMapPathDevicePath->EndingAddress - MemMapPathDevicePath->StartingAddress;
+ if (Size == 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
+ // Try to allocate in any pages if failed to allocate memory at the defined location
+ if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
+ Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(Size), Image);
+ }
+ if (!EFI_ERROR(Status)) {
+ CopyMem ((VOID*)(UINTN)(*Image), (CONST VOID*)(UINTN)MemMapPathDevicePath->StartingAddress, Size);
+
+ if (ImageSize != NULL) {
+ *ImageSize = Size;
+ }
+ }
+
+ return Status;
+}
+
+BOOLEAN
+BdsFirmwareVolumeSupport (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath
+ )
+{
+ return IS_DEVICE_PATH_NODE(RemainingDevicePath, MEDIA_DEVICE_PATH, MEDIA_PIWG_FW_FILE_DP);
+}
+
+EFI_STATUS
+BdsFirmwareVolumeLoadImage (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS* Image,
+ OUT UINTN *ImageSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_FIRMWARE_VOLUME2_PROTOCOL *FwVol;
+ EFI_GUID *FvNameGuid;
+ EFI_SECTION_TYPE SectionType;
+ EFI_FV_FILETYPE FvType;
+ EFI_FV_FILE_ATTRIBUTES Attrib;
+ UINT32 AuthenticationStatus;
+ VOID* ImageBuffer;
+
+ ASSERT (IS_DEVICE_PATH_NODE(RemainingDevicePath, MEDIA_DEVICE_PATH, MEDIA_PIWG_FW_FILE_DP));
+
+ Status = gBS->HandleProtocol(Handle,&gEfiFirmwareVolume2ProtocolGuid, (VOID **)&FwVol);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ FvNameGuid = EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)RemainingDevicePath);
+ if (FvNameGuid == NULL) {
+ Status = EFI_INVALID_PARAMETER;
+ }
+
+ SectionType = EFI_SECTION_PE32;
+ AuthenticationStatus = 0;
+ //Note: ReadSection at the opposite of ReadFile does not allow to pass ImageBuffer == NULL to get the size of the file.
+ ImageBuffer = NULL;
+ Status = FwVol->ReadSection (
+ FwVol,
+ FvNameGuid,
+ SectionType,
+ 0,
+ &ImageBuffer,
+ ImageSize,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR (Status)) {
+#if 0
+ // In case the buffer has some address requirements, we must copy the buffer to a buffer following the requirements
+ if (Type != AllocateAnyPages) {
+ Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize),Image);
+ if (!EFI_ERROR(Status)) {
+ CopyMem ((VOID*)(UINTN)(*Image), ImageBuffer, *ImageSize);
+ FreePool (ImageBuffer);
+ }
+ }
+#else
+ // We must copy the buffer into a page allocations. Otherwise, the caller could call gBS->FreePages() on the pool allocation
+ Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
+ // Try to allocate in any pages if failed to allocate memory at the defined location
+ if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
+ Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
+ }
+ if (!EFI_ERROR(Status)) {
+ CopyMem ((VOID*)(UINTN)(*Image), ImageBuffer, *ImageSize);
+ FreePool (ImageBuffer);
+ }
+#endif
+ } else {
+ // Try a raw file, since a PE32 SECTION does not exist
+ Status = FwVol->ReadFile (
+ FwVol,
+ FvNameGuid,
+ NULL,
+ ImageSize,
+ &FvType,
+ &Attrib,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR(Status)) {
+ Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
+ // Try to allocate in any pages if failed to allocate memory at the defined location
+ if ((Status == EFI_OUT_OF_RESOURCES) && (Type != AllocateAnyPages)) {
+ Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesCode, EFI_SIZE_TO_PAGES(*ImageSize), Image);
+ }
+ if (!EFI_ERROR(Status)) {
+ Status = FwVol->ReadFile (
+ FwVol,
+ FvNameGuid,
+ (VOID*)(UINTN)(*Image),
+ ImageSize,
+ &FvType,
+ &Attrib,
+ &AuthenticationStatus
+ );
+ }
+ }
+ }
+ return Status;
+}
+
+BOOLEAN
+BdsPxeSupport (
+ IN EFI_DEVICE_PATH* DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH* RemainingDevicePath
+ )
+{
+ EFI_STATUS Status;
+ EFI_PXE_BASE_CODE_PROTOCOL* PxeBcProtocol;
+
+ if (!IsDevicePathEnd(RemainingDevicePath)) {
+ return FALSE;
+ }
+
+ Status = gBS->HandleProtocol (Handle, &gEfiPxeBaseCodeProtocolGuid, (VOID **)&PxeBcProtocol);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ } else {
+ return TRUE;
+ }
+}
+
+EFI_STATUS
+BdsPxeLoadImage (
+ IN EFI_DEVICE_PATH* DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH* RemainingDevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS *Image,
+ OUT UINTN *ImageSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_LOAD_FILE_PROTOCOL *LoadFileProtocol;
+ UINTN BufferSize;
+
+ // Get Load File Protocol attached to the PXE protocol
+ Status = gBS->HandleProtocol (Handle, &gEfiLoadFileProtocolGuid, (VOID **)&LoadFileProtocol);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Status = LoadFileProtocol->LoadFile (LoadFileProtocol, DevicePath, TRUE, &BufferSize, NULL);
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ Status = gBS->AllocatePages (Type, EfiBootServicesCode, EFI_SIZE_TO_PAGES(BufferSize), Image);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status = LoadFileProtocol->LoadFile (LoadFileProtocol, DevicePath, TRUE, &BufferSize, (VOID*)(UINTN)(*Image));
+ if (!EFI_ERROR(Status) && (ImageSize != NULL)) {
+ *ImageSize = BufferSize;
+ }
+ }
+
+ return Status;
+}
+
+BOOLEAN
+BdsTftpSupport (
+ IN EFI_DEVICE_PATH* DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH* RemainingDevicePath
+ )
+{
+ EFI_STATUS Status;
+ EFI_DEVICE_PATH *NextDevicePath;
+ EFI_PXE_BASE_CODE_PROTOCOL *PxeBcProtocol;
+
+ // Validate the Remaining Device Path
+ if (IsDevicePathEnd(RemainingDevicePath)) {
+ return FALSE;
+ }
+ if (!IS_DEVICE_PATH_NODE(RemainingDevicePath,MESSAGING_DEVICE_PATH,MSG_IPv4_DP) &&
+ !IS_DEVICE_PATH_NODE(RemainingDevicePath,MESSAGING_DEVICE_PATH,MSG_IPv6_DP)) {
+ return FALSE;
+ }
+ NextDevicePath = NextDevicePathNode (RemainingDevicePath);
+ if (IsDevicePathEnd(NextDevicePath)) {
+ return FALSE;
+ }
+ if (!IS_DEVICE_PATH_NODE(NextDevicePath,MEDIA_DEVICE_PATH,MEDIA_FILEPATH_DP)) {
+ return FALSE;
+ }
+
+ Status = gBS->HandleProtocol (Handle, &gEfiPxeBaseCodeProtocolGuid, (VOID **)&PxeBcProtocol);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ } else {
+ return TRUE;
+ }
+}
+
+EFI_STATUS
+BdsTftpLoadImage (
+ IN EFI_DEVICE_PATH* DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH* RemainingDevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS *Image,
+ OUT UINTN *ImageSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
+ UINT64 TftpBufferSize;
+ VOID* TftpBuffer;
+ EFI_IP_ADDRESS ServerIp;
+ IPv4_DEVICE_PATH* IPv4DevicePathNode;
+ FILEPATH_DEVICE_PATH* FilePathDevicePath;
+ EFI_IP_ADDRESS LocalIp;
+
+ ASSERT(IS_DEVICE_PATH_NODE(RemainingDevicePath,MESSAGING_DEVICE_PATH,MSG_IPv4_DP));
+
+ IPv4DevicePathNode = (IPv4_DEVICE_PATH*)RemainingDevicePath;
+ FilePathDevicePath = (FILEPATH_DEVICE_PATH*)(IPv4DevicePathNode + 1);
+
+ Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status = Pxe->Start (Pxe, FALSE);
+ if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
+ return Status;
+ }
+
+ if (!IPv4DevicePathNode->StaticIpAddress) {
+ Status = Pxe->Dhcp(Pxe, TRUE);
+ } else {
+ CopyMem (&LocalIp.v4, &IPv4DevicePathNode->LocalIpAddress, sizeof (EFI_IPv4_ADDRESS));
+ Status = Pxe->SetStationIp (Pxe, &LocalIp, NULL);
+ }
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ CopyMem (&ServerIp.v4, &IPv4DevicePathNode->RemoteIpAddress, sizeof (EFI_IPv4_ADDRESS));
+
+ Status = Pxe->Mtftp (
+ Pxe,
+ EFI_PXE_BASE_CODE_TFTP_GET_FILE_SIZE,
+ NULL,
+ FALSE,
+ &TftpBufferSize,
+ NULL,
+ &ServerIp,
+ (UINT8 *)FilePathDevicePath->PathName,
+ NULL,
+ TRUE
+ );
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Allocate a buffer to hold the whole file.
+ TftpBuffer = AllocatePool(TftpBufferSize);
+ if (TftpBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Status = Pxe->Mtftp (
+ Pxe,
+ EFI_PXE_BASE_CODE_TFTP_READ_FILE,
+ TftpBuffer,
+ FALSE,
+ &TftpBufferSize,
+ NULL,
+ &ServerIp,
+ (UINT8 *)FilePathDevicePath->PathName,
+ NULL,
+ FALSE
+ );
+ if (EFI_ERROR(Status)) {
+ FreePool(TftpBuffer);
+ } else if (ImageSize != NULL) {
+ *ImageSize = (UINTN)TftpBufferSize;
+ }
+
+ return Status;
+}
+
+BDS_FILE_LOADER FileLoaders[] = {
+ { BdsFileSystemSupport, BdsFileSystemLoadImage },
+ { BdsFirmwareVolumeSupport, BdsFirmwareVolumeLoadImage },
+ //{ BdsLoadFileSupport, BdsLoadFileLoadImage },
+ { BdsMemoryMapSupport, BdsMemoryMapLoadImage },
+ { BdsPxeSupport, BdsPxeLoadImage },
+ { BdsTftpSupport, BdsTftpLoadImage },
+ { NULL, NULL }
+};
+
+EFI_STATUS
+BdsLoadImage (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS* Image,
+ OUT UINTN *FileSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+ EFI_DEVICE_PATH *RemainingDevicePath;
+ BDS_FILE_LOADER* FileLoader;
+
+ Status = BdsConnectDevicePath (DevicePath, &Handle, &RemainingDevicePath);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ FileLoader = FileLoaders;
+ while (FileLoader->Support != NULL) {
+ if (FileLoader->Support (DevicePath, Handle, RemainingDevicePath)) {
+ return FileLoader->LoadImage (DevicePath, Handle, RemainingDevicePath, Type, Image, FileSize);
+ }
+ FileLoader++;
+ }
+
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Start an EFI Application from a Device Path
+
+ @param ParentImageHandle Handle of the calling image
+ @param DevicePath Location of the EFI Application
+
+ @retval EFI_SUCCESS All drivers have been connected
+ @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
+ @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
+
+**/
+EFI_STATUS
+BdsStartEfiApplication (
+ IN EFI_HANDLE ParentImageHandle,
+ IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
+ IN UINTN LoadOptionsSize,
+ IN VOID* LoadOptions
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE ImageHandle;
+ EFI_PHYSICAL_ADDRESS BinaryBuffer;
+ UINTN BinarySize;
+ EFI_LOADED_IMAGE_PROTOCOL* LoadedImage;
+
+ // Find the nearest supported file loader
+ Status = BdsLoadImage (DevicePath, AllocateAnyPages, &BinaryBuffer, &BinarySize);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Load the image from the Buffer with Boot Services function
+ Status = gBS->LoadImage (TRUE, ParentImageHandle, DevicePath, (VOID*)(UINTN)BinaryBuffer, BinarySize, &ImageHandle);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Passed LoadOptions to the EFI Application
+ if (LoadOptionsSize != 0) {
+ Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &LoadedImage);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ LoadedImage->LoadOptionsSize = LoadOptionsSize;
+ LoadedImage->LoadOptions = LoadOptions;
+ }
+
+ // Before calling the image, enable the Watchdog Timer for the 5 Minute period
+ gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
+ // Start the image
+ Status = gBS->StartImage (ImageHandle, NULL, NULL);
+ // Clear the Watchdog Timer after the image returns
+ gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
+
+ return Status;
+}
diff --git a/ArmPkg/Library/BdsLib/BdsHelper.c b/ArmPkg/Library/BdsLib/BdsHelper.c
index 29cc12bd3..5016bedcd 100644
--- a/ArmPkg/Library/BdsLib/BdsHelper.c
+++ b/ArmPkg/Library/BdsLib/BdsHelper.c
@@ -1,347 +1,347 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-
-#include <Library/DxeServicesTableLib.h>
-#include <Library/HobLib.h>
-#include <Library/TimerLib.h>
-#include <Library/PrintLib.h>
-#include <Library/SerialPortLib.h>
-
-STATIC CHAR8 *mTokenList[] = {
- /*"SEC",*/
- "PEI",
- "DXE",
- "BDS",
- NULL
-};
-
-EFI_STATUS
-ShutdownUefiBootServices (
- VOID
- )
-{
- EFI_STATUS Status;
- UINTN MemoryMapSize;
- EFI_MEMORY_DESCRIPTOR *MemoryMap;
- UINTN MapKey;
- UINTN DescriptorSize;
- UINT32 DescriptorVersion;
- UINTN Pages;
-
- MemoryMap = NULL;
- MemoryMapSize = 0;
- Pages = 0;
-
- do {
- Status = gBS->GetMemoryMap (
- &MemoryMapSize,
- MemoryMap,
- &MapKey,
- &DescriptorSize,
- &DescriptorVersion
- );
- if (Status == EFI_BUFFER_TOO_SMALL) {
-
- Pages = EFI_SIZE_TO_PAGES (MemoryMapSize) + 1;
- MemoryMap = AllocatePages (Pages);
-
- //
- // Get System MemoryMap
- //
- Status = gBS->GetMemoryMap (
- &MemoryMapSize,
- MemoryMap,
- &MapKey,
- &DescriptorSize,
- &DescriptorVersion
- );
- }
-
- // Don't do anything between the GetMemoryMap() and ExitBootServices()
- if (!EFI_ERROR(Status)) {
- Status = gBS->ExitBootServices (gImageHandle, MapKey);
- if (EFI_ERROR(Status)) {
- FreePages (MemoryMap, Pages);
- MemoryMap = NULL;
- MemoryMapSize = 0;
- }
- }
- } while (EFI_ERROR(Status));
-
- return Status;
-}
-
-/**
- Connect all DXE drivers
-
- @retval EFI_SUCCESS All drivers have been connected
- @retval EFI_NOT_FOUND No handles match the search.
- @retval EFI_OUT_OF_RESOURCES There is not resource pool memory to store the matching results.
-
-**/
-EFI_STATUS
-BdsConnectAllDrivers (
- VOID
- )
-{
- UINTN HandleCount, Index;
- EFI_HANDLE *HandleBuffer;
- EFI_STATUS Status;
-
- do {
- // Locate all the driver handles
- Status = gBS->LocateHandleBuffer (
- AllHandles,
- NULL,
- NULL,
- &HandleCount,
- &HandleBuffer
- );
- if (EFI_ERROR (Status)) {
- break;
- }
-
- // Connect every handles
- for (Index = 0; Index < HandleCount; Index++) {
- gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE);
- }
-
- if (HandleBuffer != NULL) {
- FreePool (HandleBuffer);
- }
-
- // Check if new handles have been created after the start of the previous handles
- Status = gDS->Dispatch ();
- } while (!EFI_ERROR(Status));
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-InsertSystemMemoryResources (
- LIST_ENTRY *ResourceList,
- EFI_HOB_RESOURCE_DESCRIPTOR *ResHob
- )
-{
- BDS_SYSTEM_MEMORY_RESOURCE *NewResource;
- LIST_ENTRY *Link;
- LIST_ENTRY *NextLink;
- LIST_ENTRY AttachedResources;
- BDS_SYSTEM_MEMORY_RESOURCE *Resource;
- EFI_PHYSICAL_ADDRESS NewResourceEnd;
-
- if (IsListEmpty (ResourceList)) {
- NewResource = AllocateZeroPool (sizeof(BDS_SYSTEM_MEMORY_RESOURCE));
- NewResource->PhysicalStart = ResHob->PhysicalStart;
- NewResource->ResourceLength = ResHob->ResourceLength;
- InsertTailList (ResourceList, &NewResource->Link);
- return EFI_SUCCESS;
- }
-
- InitializeListHead (&AttachedResources);
-
- Link = ResourceList->ForwardLink;
- ASSERT (Link != NULL);
- while (Link != ResourceList) {
- Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)Link;
-
- // Sanity Check. The resources should not overlapped.
- ASSERT(!((ResHob->PhysicalStart >= Resource->PhysicalStart) && (ResHob->PhysicalStart < (Resource->PhysicalStart + Resource->ResourceLength))));
- ASSERT(!((ResHob->PhysicalStart + ResHob->ResourceLength - 1 >= Resource->PhysicalStart) &&
- ((ResHob->PhysicalStart + ResHob->ResourceLength - 1) < (Resource->PhysicalStart + Resource->ResourceLength))));
-
- // The new resource is attached after this resource descriptor
- if (ResHob->PhysicalStart == Resource->PhysicalStart + Resource->ResourceLength) {
- Resource->ResourceLength = Resource->ResourceLength + ResHob->ResourceLength;
-
- NextLink = RemoveEntryList (&Resource->Link);
- InsertTailList (&AttachedResources, &Resource->Link);
- Link = NextLink;
- }
- // The new resource is attached before this resource descriptor
- else if (ResHob->PhysicalStart + ResHob->ResourceLength == Resource->PhysicalStart) {
- Resource->PhysicalStart = ResHob->PhysicalStart;
- Resource->ResourceLength = Resource->ResourceLength + ResHob->ResourceLength;
-
- NextLink = RemoveEntryList (&Resource->Link);
- InsertTailList (&AttachedResources, &Resource->Link);
- Link = NextLink;
- } else {
- Link = Link->ForwardLink;
- }
- }
-
- if (!IsListEmpty (&AttachedResources)) {
- // See if we can merge the attached resource with other resources
-
- NewResource = (BDS_SYSTEM_MEMORY_RESOURCE*)GetFirstNode (&AttachedResources);
- Link = RemoveEntryList (&NewResource->Link);
- while (!IsListEmpty (&AttachedResources)) {
- // Merge resources
- Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)Link;
-
- // Ensure they overlap each other
- ASSERT(
- ((NewResource->PhysicalStart >= Resource->PhysicalStart) && (NewResource->PhysicalStart < (Resource->PhysicalStart + Resource->ResourceLength))) ||
- (((NewResource->PhysicalStart + NewResource->ResourceLength) >= Resource->PhysicalStart) && ((NewResource->PhysicalStart + NewResource->ResourceLength) < (Resource->PhysicalStart + Resource->ResourceLength)))
- );
-
- NewResourceEnd = MAX (NewResource->PhysicalStart + NewResource->ResourceLength, Resource->PhysicalStart + Resource->ResourceLength);
- NewResource->PhysicalStart = MIN (NewResource->PhysicalStart, Resource->PhysicalStart);
- NewResource->ResourceLength = NewResourceEnd - NewResource->PhysicalStart;
-
- Link = RemoveEntryList (Link);
- }
- } else {
- // None of the Resource of the list is attached to this ResHob. Create a new entry for it
- NewResource = AllocateZeroPool (sizeof(BDS_SYSTEM_MEMORY_RESOURCE));
- NewResource->PhysicalStart = ResHob->PhysicalStart;
- NewResource->ResourceLength = ResHob->ResourceLength;
- }
- InsertTailList (ResourceList, &NewResource->Link);
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-GetSystemMemoryResources (
- IN LIST_ENTRY *ResourceList
- )
-{
- EFI_HOB_RESOURCE_DESCRIPTOR *ResHob;
-
- InitializeListHead (ResourceList);
-
- // Find the first System Memory Resource Descriptor
- ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR);
- while ((ResHob != NULL) && (ResHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY)) {
- ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,(VOID *)((UINTN)ResHob + ResHob->Header.HobLength));
- }
-
- // Did not find any
- if (ResHob == NULL) {
- return EFI_NOT_FOUND;
- } else {
- InsertSystemMemoryResources (ResourceList, ResHob);
- }
-
- ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,(VOID *)((UINTN)ResHob + ResHob->Header.HobLength));
- while (ResHob != NULL) {
- if (ResHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) {
- InsertSystemMemoryResources (ResourceList, ResHob);
- }
- ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,(VOID *)((UINTN)ResHob + ResHob->Header.HobLength));
- }
-
- return EFI_SUCCESS;
-}
-
-VOID
-PrintPerformance (
- VOID
- )
-{
- UINTN Key;
- CONST VOID *Handle;
- CONST CHAR8 *Token, *Module;
- UINT64 Start, Stop, TimeStamp;
- UINT64 Delta, TicksPerSecond, Milliseconds;
- UINTN Index;
- CHAR8 Buffer[100];
- UINTN CharCount;
- BOOLEAN CountUp;
-
- TicksPerSecond = GetPerformanceCounterProperties (&Start, &Stop);
- if (Start < Stop) {
- CountUp = TRUE;
- } else {
- CountUp = FALSE;
- }
-
- TimeStamp = 0;
- Key = 0;
- do {
- Key = GetPerformanceMeasurement (Key, (CONST VOID **)&Handle, &Token, &Module, &Start, &Stop);
- if (Key != 0) {
- for (Index = 0; mTokenList[Index] != NULL; Index++) {
- if (AsciiStriCmp (mTokenList[Index], Token) == 0) {
- Delta = CountUp?(Stop - Start):(Start - Stop);
- TimeStamp += Delta;
- Milliseconds = DivU64x64Remainder (MultU64x32 (Delta, 1000), TicksPerSecond, NULL);
- CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"%6a %6ld ms\n", Token, Milliseconds);
- SerialPortWrite ((UINT8 *) Buffer, CharCount);
- break;
- }
- }
- }
- } while (Key != 0);
-
- CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Total Time = %ld ms\n\n", DivU64x64Remainder (MultU64x32 (TimeStamp, 1000), TicksPerSecond, NULL));
- SerialPortWrite ((UINT8 *) Buffer, CharCount);
-}
-
-EFI_STATUS
-GetEnvironmentVariable (
- IN CONST CHAR16* VariableName,
- IN VOID* DefaultValue,
- IN OUT UINTN* Size,
- OUT VOID** Value
- )
-{
- EFI_STATUS Status;
- UINTN VariableSize;
-
- // Try to get the variable size.
- *Value = NULL;
- VariableSize = 0;
- Status = gRT->GetVariable ((CHAR16 *) VariableName, &gEfiGlobalVariableGuid, NULL, &VariableSize, *Value);
- if (Status == EFI_NOT_FOUND) {
- if ((DefaultValue != NULL) && (Size != NULL) && (*Size != 0)) {
- // If the environment variable does not exist yet then set it with the default value
- Status = gRT->SetVariable (
- (CHAR16*)VariableName,
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- *Size,
- DefaultValue
- );
- *Value = DefaultValue;
- } else {
- return EFI_NOT_FOUND;
- }
- } else if (Status == EFI_BUFFER_TOO_SMALL) {
- // Get the environment variable value
- *Value = AllocatePool (VariableSize);
- if (*Value == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- Status = gRT->GetVariable ((CHAR16 *)VariableName, &gEfiGlobalVariableGuid, NULL, &VariableSize, *Value);
- if (EFI_ERROR (Status)) {
- FreePool(*Value);
- return EFI_INVALID_PARAMETER;
- }
-
- if (Size) {
- *Size = VariableSize;
- }
- } else {
- *Value = DefaultValue;
- return Status;
- }
-
- return EFI_SUCCESS;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+
+#include <Library/DxeServicesTableLib.h>
+#include <Library/HobLib.h>
+#include <Library/TimerLib.h>
+#include <Library/PrintLib.h>
+#include <Library/SerialPortLib.h>
+
+STATIC CHAR8 *mTokenList[] = {
+ /*"SEC",*/
+ "PEI",
+ "DXE",
+ "BDS",
+ NULL
+};
+
+EFI_STATUS
+ShutdownUefiBootServices (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN MemoryMapSize;
+ EFI_MEMORY_DESCRIPTOR *MemoryMap;
+ UINTN MapKey;
+ UINTN DescriptorSize;
+ UINT32 DescriptorVersion;
+ UINTN Pages;
+
+ MemoryMap = NULL;
+ MemoryMapSize = 0;
+ Pages = 0;
+
+ do {
+ Status = gBS->GetMemoryMap (
+ &MemoryMapSize,
+ MemoryMap,
+ &MapKey,
+ &DescriptorSize,
+ &DescriptorVersion
+ );
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+
+ Pages = EFI_SIZE_TO_PAGES (MemoryMapSize) + 1;
+ MemoryMap = AllocatePages (Pages);
+
+ //
+ // Get System MemoryMap
+ //
+ Status = gBS->GetMemoryMap (
+ &MemoryMapSize,
+ MemoryMap,
+ &MapKey,
+ &DescriptorSize,
+ &DescriptorVersion
+ );
+ }
+
+ // Don't do anything between the GetMemoryMap() and ExitBootServices()
+ if (!EFI_ERROR(Status)) {
+ Status = gBS->ExitBootServices (gImageHandle, MapKey);
+ if (EFI_ERROR(Status)) {
+ FreePages (MemoryMap, Pages);
+ MemoryMap = NULL;
+ MemoryMapSize = 0;
+ }
+ }
+ } while (EFI_ERROR(Status));
+
+ return Status;
+}
+
+/**
+ Connect all DXE drivers
+
+ @retval EFI_SUCCESS All drivers have been connected
+ @retval EFI_NOT_FOUND No handles match the search.
+ @retval EFI_OUT_OF_RESOURCES There is not resource pool memory to store the matching results.
+
+**/
+EFI_STATUS
+BdsConnectAllDrivers (
+ VOID
+ )
+{
+ UINTN HandleCount, Index;
+ EFI_HANDLE *HandleBuffer;
+ EFI_STATUS Status;
+
+ do {
+ // Locate all the driver handles
+ Status = gBS->LocateHandleBuffer (
+ AllHandles,
+ NULL,
+ NULL,
+ &HandleCount,
+ &HandleBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ // Connect every handles
+ for (Index = 0; Index < HandleCount; Index++) {
+ gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE);
+ }
+
+ if (HandleBuffer != NULL) {
+ FreePool (HandleBuffer);
+ }
+
+ // Check if new handles have been created after the start of the previous handles
+ Status = gDS->Dispatch ();
+ } while (!EFI_ERROR(Status));
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+InsertSystemMemoryResources (
+ LIST_ENTRY *ResourceList,
+ EFI_HOB_RESOURCE_DESCRIPTOR *ResHob
+ )
+{
+ BDS_SYSTEM_MEMORY_RESOURCE *NewResource;
+ LIST_ENTRY *Link;
+ LIST_ENTRY *NextLink;
+ LIST_ENTRY AttachedResources;
+ BDS_SYSTEM_MEMORY_RESOURCE *Resource;
+ EFI_PHYSICAL_ADDRESS NewResourceEnd;
+
+ if (IsListEmpty (ResourceList)) {
+ NewResource = AllocateZeroPool (sizeof(BDS_SYSTEM_MEMORY_RESOURCE));
+ NewResource->PhysicalStart = ResHob->PhysicalStart;
+ NewResource->ResourceLength = ResHob->ResourceLength;
+ InsertTailList (ResourceList, &NewResource->Link);
+ return EFI_SUCCESS;
+ }
+
+ InitializeListHead (&AttachedResources);
+
+ Link = ResourceList->ForwardLink;
+ ASSERT (Link != NULL);
+ while (Link != ResourceList) {
+ Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)Link;
+
+ // Sanity Check. The resources should not overlapped.
+ ASSERT(!((ResHob->PhysicalStart >= Resource->PhysicalStart) && (ResHob->PhysicalStart < (Resource->PhysicalStart + Resource->ResourceLength))));
+ ASSERT(!((ResHob->PhysicalStart + ResHob->ResourceLength - 1 >= Resource->PhysicalStart) &&
+ ((ResHob->PhysicalStart + ResHob->ResourceLength - 1) < (Resource->PhysicalStart + Resource->ResourceLength))));
+
+ // The new resource is attached after this resource descriptor
+ if (ResHob->PhysicalStart == Resource->PhysicalStart + Resource->ResourceLength) {
+ Resource->ResourceLength = Resource->ResourceLength + ResHob->ResourceLength;
+
+ NextLink = RemoveEntryList (&Resource->Link);
+ InsertTailList (&AttachedResources, &Resource->Link);
+ Link = NextLink;
+ }
+ // The new resource is attached before this resource descriptor
+ else if (ResHob->PhysicalStart + ResHob->ResourceLength == Resource->PhysicalStart) {
+ Resource->PhysicalStart = ResHob->PhysicalStart;
+ Resource->ResourceLength = Resource->ResourceLength + ResHob->ResourceLength;
+
+ NextLink = RemoveEntryList (&Resource->Link);
+ InsertTailList (&AttachedResources, &Resource->Link);
+ Link = NextLink;
+ } else {
+ Link = Link->ForwardLink;
+ }
+ }
+
+ if (!IsListEmpty (&AttachedResources)) {
+ // See if we can merge the attached resource with other resources
+
+ NewResource = (BDS_SYSTEM_MEMORY_RESOURCE*)GetFirstNode (&AttachedResources);
+ Link = RemoveEntryList (&NewResource->Link);
+ while (!IsListEmpty (&AttachedResources)) {
+ // Merge resources
+ Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)Link;
+
+ // Ensure they overlap each other
+ ASSERT(
+ ((NewResource->PhysicalStart >= Resource->PhysicalStart) && (NewResource->PhysicalStart < (Resource->PhysicalStart + Resource->ResourceLength))) ||
+ (((NewResource->PhysicalStart + NewResource->ResourceLength) >= Resource->PhysicalStart) && ((NewResource->PhysicalStart + NewResource->ResourceLength) < (Resource->PhysicalStart + Resource->ResourceLength)))
+ );
+
+ NewResourceEnd = MAX (NewResource->PhysicalStart + NewResource->ResourceLength, Resource->PhysicalStart + Resource->ResourceLength);
+ NewResource->PhysicalStart = MIN (NewResource->PhysicalStart, Resource->PhysicalStart);
+ NewResource->ResourceLength = NewResourceEnd - NewResource->PhysicalStart;
+
+ Link = RemoveEntryList (Link);
+ }
+ } else {
+ // None of the Resource of the list is attached to this ResHob. Create a new entry for it
+ NewResource = AllocateZeroPool (sizeof(BDS_SYSTEM_MEMORY_RESOURCE));
+ NewResource->PhysicalStart = ResHob->PhysicalStart;
+ NewResource->ResourceLength = ResHob->ResourceLength;
+ }
+ InsertTailList (ResourceList, &NewResource->Link);
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+GetSystemMemoryResources (
+ IN LIST_ENTRY *ResourceList
+ )
+{
+ EFI_HOB_RESOURCE_DESCRIPTOR *ResHob;
+
+ InitializeListHead (ResourceList);
+
+ // Find the first System Memory Resource Descriptor
+ ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR);
+ while ((ResHob != NULL) && (ResHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY)) {
+ ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,(VOID *)((UINTN)ResHob + ResHob->Header.HobLength));
+ }
+
+ // Did not find any
+ if (ResHob == NULL) {
+ return EFI_NOT_FOUND;
+ } else {
+ InsertSystemMemoryResources (ResourceList, ResHob);
+ }
+
+ ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,(VOID *)((UINTN)ResHob + ResHob->Header.HobLength));
+ while (ResHob != NULL) {
+ if (ResHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) {
+ InsertSystemMemoryResources (ResourceList, ResHob);
+ }
+ ResHob = (EFI_HOB_RESOURCE_DESCRIPTOR *)GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,(VOID *)((UINTN)ResHob + ResHob->Header.HobLength));
+ }
+
+ return EFI_SUCCESS;
+}
+
+VOID
+PrintPerformance (
+ VOID
+ )
+{
+ UINTN Key;
+ CONST VOID *Handle;
+ CONST CHAR8 *Token, *Module;
+ UINT64 Start, Stop, TimeStamp;
+ UINT64 Delta, TicksPerSecond, Milliseconds;
+ UINTN Index;
+ CHAR8 Buffer[100];
+ UINTN CharCount;
+ BOOLEAN CountUp;
+
+ TicksPerSecond = GetPerformanceCounterProperties (&Start, &Stop);
+ if (Start < Stop) {
+ CountUp = TRUE;
+ } else {
+ CountUp = FALSE;
+ }
+
+ TimeStamp = 0;
+ Key = 0;
+ do {
+ Key = GetPerformanceMeasurement (Key, (CONST VOID **)&Handle, &Token, &Module, &Start, &Stop);
+ if (Key != 0) {
+ for (Index = 0; mTokenList[Index] != NULL; Index++) {
+ if (AsciiStriCmp (mTokenList[Index], Token) == 0) {
+ Delta = CountUp?(Stop - Start):(Start - Stop);
+ TimeStamp += Delta;
+ Milliseconds = DivU64x64Remainder (MultU64x32 (Delta, 1000), TicksPerSecond, NULL);
+ CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"%6a %6ld ms\n", Token, Milliseconds);
+ SerialPortWrite ((UINT8 *) Buffer, CharCount);
+ break;
+ }
+ }
+ }
+ } while (Key != 0);
+
+ CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Total Time = %ld ms\n\n", DivU64x64Remainder (MultU64x32 (TimeStamp, 1000), TicksPerSecond, NULL));
+ SerialPortWrite ((UINT8 *) Buffer, CharCount);
+}
+
+EFI_STATUS
+GetEnvironmentVariable (
+ IN CONST CHAR16* VariableName,
+ IN VOID* DefaultValue,
+ IN OUT UINTN* Size,
+ OUT VOID** Value
+ )
+{
+ EFI_STATUS Status;
+ UINTN VariableSize;
+
+ // Try to get the variable size.
+ *Value = NULL;
+ VariableSize = 0;
+ Status = gRT->GetVariable ((CHAR16 *) VariableName, &gEfiGlobalVariableGuid, NULL, &VariableSize, *Value);
+ if (Status == EFI_NOT_FOUND) {
+ if ((DefaultValue != NULL) && (Size != NULL) && (*Size != 0)) {
+ // If the environment variable does not exist yet then set it with the default value
+ Status = gRT->SetVariable (
+ (CHAR16*)VariableName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ *Size,
+ DefaultValue
+ );
+ *Value = DefaultValue;
+ } else {
+ return EFI_NOT_FOUND;
+ }
+ } else if (Status == EFI_BUFFER_TOO_SMALL) {
+ // Get the environment variable value
+ *Value = AllocatePool (VariableSize);
+ if (*Value == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Status = gRT->GetVariable ((CHAR16 *)VariableName, &gEfiGlobalVariableGuid, NULL, &VariableSize, *Value);
+ if (EFI_ERROR (Status)) {
+ FreePool(*Value);
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (Size) {
+ *Size = VariableSize;
+ }
+ } else {
+ *Value = DefaultValue;
+ return Status;
+ }
+
+ return EFI_SUCCESS;
+}
diff --git a/ArmPkg/Library/BdsLib/BdsInternal.h b/ArmPkg/Library/BdsLib/BdsInternal.h
index 85f9f4159..5ae46f86e 100644
--- a/ArmPkg/Library/BdsLib/BdsInternal.h
+++ b/ArmPkg/Library/BdsLib/BdsInternal.h
@@ -1,98 +1,98 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef __BDS_INTERNAL_H__
-#define __BDS_INTERNAL_H__
-
-#include <PiDxe.h>
-#include <Library/ArmLib.h>
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/HobLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BdsLib.h>
-#include <Library/PcdLib.h>
-#include <Library/PerformanceLib.h>
-#include <Library/PrintLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-
-#include <Guid/ArmMpCoreInfo.h>
-#include <Guid/GlobalVariable.h>
-#include <Guid/FileInfo.h>
-
-#include <Protocol/DevicePath.h>
-#include <Protocol/DevicePathFromText.h>
-#include <Protocol/SimpleFileSystem.h>
-#include <Protocol/FirmwareVolume2.h>
-#include <Protocol/LoadFile.h>
-#include <Protocol/PxeBaseCode.h>
-
-#include <Uefi.h>
-
-typedef BOOLEAN (*BDS_FILE_LOADER_SUPPORT) (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath
- );
-
-typedef EFI_STATUS (*BDS_FILE_LOADER_LOAD_IMAGE) (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_HANDLE Handle,
- IN EFI_DEVICE_PATH *RemainingDevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS* Image,
- OUT UINTN *ImageSize
- );
-
-typedef struct {
- BDS_FILE_LOADER_SUPPORT Support;
- BDS_FILE_LOADER_LOAD_IMAGE LoadImage;
-} BDS_FILE_LOADER;
-
-typedef struct _BDS_SYSTEM_MEMORY_RESOURCE {
- LIST_ENTRY Link; // This attribute must be the first entry of this structure (to avoid pointer computation)
- EFI_PHYSICAL_ADDRESS PhysicalStart;
- UINT64 ResourceLength;
-} BDS_SYSTEM_MEMORY_RESOURCE;
-
-
-// BdsHelper.c
-EFI_STATUS
-ShutdownUefiBootServices (
- VOID
- );
-
-EFI_STATUS
-GetSystemMemoryResources (
- LIST_ENTRY *ResourceList
- );
-
-VOID
-PrintPerformance (
- VOID
- );
-
-EFI_STATUS
-BdsLoadImage (
- IN EFI_DEVICE_PATH *DevicePath,
- IN EFI_ALLOCATE_TYPE Type,
- IN OUT EFI_PHYSICAL_ADDRESS* Image,
- OUT UINTN *FileSize
- );
-
-#endif
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef __BDS_INTERNAL_H__
+#define __BDS_INTERNAL_H__
+
+#include <PiDxe.h>
+#include <Library/ArmLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/HobLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BdsLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PerformanceLib.h>
+#include <Library/PrintLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+
+#include <Guid/ArmMpCoreInfo.h>
+#include <Guid/GlobalVariable.h>
+#include <Guid/FileInfo.h>
+
+#include <Protocol/DevicePath.h>
+#include <Protocol/DevicePathFromText.h>
+#include <Protocol/SimpleFileSystem.h>
+#include <Protocol/FirmwareVolume2.h>
+#include <Protocol/LoadFile.h>
+#include <Protocol/PxeBaseCode.h>
+
+#include <Uefi.h>
+
+typedef BOOLEAN (*BDS_FILE_LOADER_SUPPORT) (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath
+ );
+
+typedef EFI_STATUS (*BDS_FILE_LOADER_LOAD_IMAGE) (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_HANDLE Handle,
+ IN EFI_DEVICE_PATH *RemainingDevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS* Image,
+ OUT UINTN *ImageSize
+ );
+
+typedef struct {
+ BDS_FILE_LOADER_SUPPORT Support;
+ BDS_FILE_LOADER_LOAD_IMAGE LoadImage;
+} BDS_FILE_LOADER;
+
+typedef struct _BDS_SYSTEM_MEMORY_RESOURCE {
+ LIST_ENTRY Link; // This attribute must be the first entry of this structure (to avoid pointer computation)
+ EFI_PHYSICAL_ADDRESS PhysicalStart;
+ UINT64 ResourceLength;
+} BDS_SYSTEM_MEMORY_RESOURCE;
+
+
+// BdsHelper.c
+EFI_STATUS
+ShutdownUefiBootServices (
+ VOID
+ );
+
+EFI_STATUS
+GetSystemMemoryResources (
+ LIST_ENTRY *ResourceList
+ );
+
+VOID
+PrintPerformance (
+ VOID
+ );
+
+EFI_STATUS
+BdsLoadImage (
+ IN EFI_DEVICE_PATH *DevicePath,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN OUT EFI_PHYSICAL_ADDRESS* Image,
+ OUT UINTN *FileSize
+ );
+
+#endif
diff --git a/ArmPkg/Library/BdsLib/BdsLib.inf b/ArmPkg/Library/BdsLib/BdsLib.inf
index 9dee03a79..541bce88b 100644
--- a/ArmPkg/Library/BdsLib/BdsLib.inf
+++ b/ArmPkg/Library/BdsLib/BdsLib.inf
@@ -1,77 +1,78 @@
-#/* @file
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#*/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = BdsLib
- FILE_GUID = ddbf73a0-bb25-11df-8e4e-0002a5d5c51b
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- LIBRARY_CLASS = BdsLib
-
-[Sources.common]
- BdsFilePath.c
- BdsAppLoader.c
- BdsHelper.c
- BdsLoadOption.c
-
- BdsLinuxLoader.c
- BdsLinuxAtag.c
- BdsLinuxFdt.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
-
-[LibraryClasses]
- ArmLib
- BaseLib
- DebugLib
- DevicePathLib
- HobLib
- PerformanceLib
- SerialPortLib
- FdtLib
-
-[Guids]
- gEfiFileInfoGuid
- gArmMpCoreInfoGuid
-
-[Protocols]
- gEfiBdsArchProtocolGuid
- gEfiDevicePathProtocolGuid
- gEfiDevicePathFromTextProtocolGuid
- gEfiSimpleFileSystemProtocolGuid
- gEfiFirmwareVolume2ProtocolGuid
- gEfiLoadFileProtocolGuid
- gEfiPxeBaseCodeProtocolGuid
- gEfiDiskIoProtocolGuid
- gEfiUsbIoProtocolGuid
- gEfiLoadedImageProtocolGuid
-
-[FeaturePcd]
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdSystemMemoryBase
- gArmTokenSpaceGuid.PcdSystemMemorySize
-
- gArmTokenSpaceGuid.PcdArmMachineType
- gArmTokenSpaceGuid.PcdArmLinuxFdtMaxOffset
- gArmTokenSpaceGuid.PcdArmLinuxKernelFixedOffset
- gArmTokenSpaceGuid.PcdArmLinuxKernelMaxOffset
- gArmTokenSpaceGuid.PcdArmLinuxAtagMaxOffset
-
-[Depex]
- TRUE
+#/* @file
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#*/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = BdsLib
+ FILE_GUID = ddbf73a0-bb25-11df-8e4e-0002a5d5c51b
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = BdsLib
+
+[Sources.common]
+ BdsFilePath.c
+ BdsAppLoader.c
+ BdsHelper.c
+ BdsLoadOption.c
+
+ BdsLinuxLoader.c
+ BdsLinuxAtag.c
+ BdsLinuxFdt.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+
+[LibraryClasses]
+ ArmLib
+ BaseLib
+ DebugLib
+ DevicePathLib
+ HobLib
+ PerformanceLib
+ SerialPortLib
+ FdtLib
+ TimerLib
+
+[Guids]
+ gEfiFileInfoGuid
+ gArmMpCoreInfoGuid
+
+[Protocols]
+ gEfiBdsArchProtocolGuid
+ gEfiDevicePathProtocolGuid
+ gEfiDevicePathFromTextProtocolGuid
+ gEfiSimpleFileSystemProtocolGuid
+ gEfiFirmwareVolume2ProtocolGuid
+ gEfiLoadFileProtocolGuid
+ gEfiPxeBaseCodeProtocolGuid
+ gEfiDiskIoProtocolGuid
+ gEfiUsbIoProtocolGuid
+ gEfiLoadedImageProtocolGuid
+
+[FeaturePcd]
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdSystemMemoryBase
+ gArmTokenSpaceGuid.PcdSystemMemorySize
+
+ gArmTokenSpaceGuid.PcdArmMachineType
+ gArmTokenSpaceGuid.PcdArmLinuxFdtMaxOffset
+ gArmTokenSpaceGuid.PcdArmLinuxKernelFixedOffset
+ gArmTokenSpaceGuid.PcdArmLinuxKernelMaxOffset
+ gArmTokenSpaceGuid.PcdArmLinuxAtagMaxOffset
+
+[Depex]
+ TRUE
diff --git a/ArmPkg/Library/BdsLib/BdsLinuxAtag.c b/ArmPkg/Library/BdsLib/BdsLinuxAtag.c
index b59df0762..8946b1423 100644
--- a/ArmPkg/Library/BdsLib/BdsLinuxAtag.c
+++ b/ArmPkg/Library/BdsLib/BdsLinuxAtag.c
@@ -1,173 +1,173 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-#include "BdsLinuxLoader.h"
-
-// Point to the current ATAG
-STATIC LINUX_ATAG *mLinuxKernelCurrentAtag;
-
-STATIC
-VOID
-SetupCoreTag (
- IN UINT32 PageSize
- )
-{
- mLinuxKernelCurrentAtag->header.size = tag_size(LINUX_ATAG_CORE);
- mLinuxKernelCurrentAtag->header.type = ATAG_CORE;
-
- mLinuxKernelCurrentAtag->body.core_tag.flags = 1; /* ensure read-only */
- mLinuxKernelCurrentAtag->body.core_tag.pagesize = PageSize; /* systems PageSize (4k) */
- mLinuxKernelCurrentAtag->body.core_tag.rootdev = 0; /* zero root device (typically overridden from kernel command line )*/
-
- // move pointer to next tag
- mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
-}
-
-STATIC
-VOID
-SetupMemTag (
- IN UINTN StartAddress,
- IN UINT32 Size
- )
-{
- mLinuxKernelCurrentAtag->header.size = tag_size(LINUX_ATAG_MEM);
- mLinuxKernelCurrentAtag->header.type = ATAG_MEM;
-
- mLinuxKernelCurrentAtag->body.mem_tag.start = StartAddress; /* Start of memory chunk for AtagMem */
- mLinuxKernelCurrentAtag->body.mem_tag.size = Size; /* Size of memory chunk for AtagMem */
-
- // move pointer to next tag
- mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
-}
-
-STATIC
-VOID
-SetupCmdlineTag (
- IN CONST CHAR8 *CmdLine
- )
-{
- UINT32 LineLength;
-
- // Increment the line length by 1 to account for the null string terminator character
- LineLength = AsciiStrLen(CmdLine) + 1;
-
- /* Check for NULL strings.
- * Do not insert a tag for an empty CommandLine, don't even modify the tag address pointer.
- * Remember, you have at least one null string terminator character.
- */
- if(LineLength > 1) {
- mLinuxKernelCurrentAtag->header.size = ((UINT32)sizeof(LINUX_ATAG_HEADER) + LineLength + (UINT32)3) >> 2;
- mLinuxKernelCurrentAtag->header.type = ATAG_CMDLINE;
-
- /* place CommandLine into tag */
- AsciiStrCpy(mLinuxKernelCurrentAtag->body.cmdline_tag.cmdline, CmdLine);
-
- // move pointer to next tag
- mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
- }
-}
-
-STATIC
-VOID
-SetupInitrdTag (
- IN UINT32 InitrdImage,
- IN UINT32 InitrdImageSize
- )
-{
- mLinuxKernelCurrentAtag->header.size = tag_size(LINUX_ATAG_INITRD2);
- mLinuxKernelCurrentAtag->header.type = ATAG_INITRD2;
-
- mLinuxKernelCurrentAtag->body.initrd2_tag.start = InitrdImage;
- mLinuxKernelCurrentAtag->body.initrd2_tag.size = InitrdImageSize;
-
- // Move pointer to next tag
- mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
-}
-STATIC
-VOID
-SetupEndTag (
- VOID
- )
-{
- // Empty tag ends list; this has zero length and no body
- mLinuxKernelCurrentAtag->header.type = ATAG_NONE;
- mLinuxKernelCurrentAtag->header.size = 0;
-
- /* We can not calculate the next address by using the standard macro:
- * Params = next_tag_address(Params);
- * because it relies on the header.size, which here it is 0 (zero).
- * The easiest way is to add the sizeof(mLinuxKernelCurrentAtag->header).
- */
- mLinuxKernelCurrentAtag = (LINUX_ATAG*)((UINT32)mLinuxKernelCurrentAtag + sizeof(mLinuxKernelCurrentAtag->header));
-}
-
-EFI_STATUS
-PrepareAtagList (
- IN CONST CHAR8* CommandLineString,
- IN EFI_PHYSICAL_ADDRESS InitrdImage,
- IN UINTN InitrdImageSize,
- OUT EFI_PHYSICAL_ADDRESS *AtagBase,
- OUT UINT32 *AtagSize
- )
-{
- EFI_STATUS Status;
- LIST_ENTRY *ResourceLink;
- LIST_ENTRY ResourceList;
- EFI_PHYSICAL_ADDRESS AtagStartAddress;
- BDS_SYSTEM_MEMORY_RESOURCE *Resource;
-
- AtagStartAddress = LINUX_ATAG_MAX_OFFSET;
- Status = gBS->AllocatePages (AllocateMaxAddress, EfiBootServicesData, EFI_SIZE_TO_PAGES(ATAG_MAX_SIZE), &AtagStartAddress);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_WARN, "Warning: Failed to allocate Atag at 0x%lX (%r). The Atag will be allocated somewhere else in System Memory.\n", AtagStartAddress, Status));
- Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, EFI_SIZE_TO_PAGES(ATAG_MAX_SIZE), &AtagStartAddress);
- ASSERT_EFI_ERROR(Status);
- }
-
- // Ready to setup the atag list
- mLinuxKernelCurrentAtag = (LINUX_ATAG*)(UINTN)AtagStartAddress;
-
- // Standard core tag 4k PageSize
- SetupCoreTag( (UINT32)SIZE_4KB );
-
- // Physical memory setup
- GetSystemMemoryResources (&ResourceList);
- ResourceLink = ResourceList.ForwardLink;
- while (ResourceLink != NULL && ResourceLink != &ResourceList) {
- Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)ResourceLink;
- DEBUG((EFI_D_INFO,"- [0x%08X,0x%08X]\n",(UINT32)Resource->PhysicalStart,(UINT32)Resource->PhysicalStart+(UINT32)Resource->ResourceLength));
- SetupMemTag( (UINT32)Resource->PhysicalStart, (UINT32)Resource->ResourceLength );
- ResourceLink = ResourceLink->ForwardLink;
- }
-
- // CommandLine setting root device
- if (CommandLineString) {
- SetupCmdlineTag (CommandLineString);
- }
-
- if (InitrdImageSize > 0 && InitrdImage != 0) {
- SetupInitrdTag ((UINT32)InitrdImage, (UINT32)InitrdImageSize);
- }
-
- // End of tags
- SetupEndTag();
-
- // Calculate atag list size
- *AtagBase = AtagStartAddress;
- *AtagSize = (UINT32)mLinuxKernelCurrentAtag - (UINT32)AtagStartAddress + 1;
-
- return EFI_SUCCESS;
-}
-
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+#include "BdsLinuxLoader.h"
+
+// Point to the current ATAG
+STATIC LINUX_ATAG *mLinuxKernelCurrentAtag;
+
+STATIC
+VOID
+SetupCoreTag (
+ IN UINT32 PageSize
+ )
+{
+ mLinuxKernelCurrentAtag->header.size = tag_size(LINUX_ATAG_CORE);
+ mLinuxKernelCurrentAtag->header.type = ATAG_CORE;
+
+ mLinuxKernelCurrentAtag->body.core_tag.flags = 1; /* ensure read-only */
+ mLinuxKernelCurrentAtag->body.core_tag.pagesize = PageSize; /* systems PageSize (4k) */
+ mLinuxKernelCurrentAtag->body.core_tag.rootdev = 0; /* zero root device (typically overridden from kernel command line )*/
+
+ // move pointer to next tag
+ mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
+}
+
+STATIC
+VOID
+SetupMemTag (
+ IN UINTN StartAddress,
+ IN UINT32 Size
+ )
+{
+ mLinuxKernelCurrentAtag->header.size = tag_size(LINUX_ATAG_MEM);
+ mLinuxKernelCurrentAtag->header.type = ATAG_MEM;
+
+ mLinuxKernelCurrentAtag->body.mem_tag.start = StartAddress; /* Start of memory chunk for AtagMem */
+ mLinuxKernelCurrentAtag->body.mem_tag.size = Size; /* Size of memory chunk for AtagMem */
+
+ // move pointer to next tag
+ mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
+}
+
+STATIC
+VOID
+SetupCmdlineTag (
+ IN CONST CHAR8 *CmdLine
+ )
+{
+ UINT32 LineLength;
+
+ // Increment the line length by 1 to account for the null string terminator character
+ LineLength = AsciiStrLen(CmdLine) + 1;
+
+ /* Check for NULL strings.
+ * Do not insert a tag for an empty CommandLine, don't even modify the tag address pointer.
+ * Remember, you have at least one null string terminator character.
+ */
+ if(LineLength > 1) {
+ mLinuxKernelCurrentAtag->header.size = ((UINT32)sizeof(LINUX_ATAG_HEADER) + LineLength + (UINT32)3) >> 2;
+ mLinuxKernelCurrentAtag->header.type = ATAG_CMDLINE;
+
+ /* place CommandLine into tag */
+ AsciiStrCpy(mLinuxKernelCurrentAtag->body.cmdline_tag.cmdline, CmdLine);
+
+ // move pointer to next tag
+ mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
+ }
+}
+
+STATIC
+VOID
+SetupInitrdTag (
+ IN UINT32 InitrdImage,
+ IN UINT32 InitrdImageSize
+ )
+{
+ mLinuxKernelCurrentAtag->header.size = tag_size(LINUX_ATAG_INITRD2);
+ mLinuxKernelCurrentAtag->header.type = ATAG_INITRD2;
+
+ mLinuxKernelCurrentAtag->body.initrd2_tag.start = InitrdImage;
+ mLinuxKernelCurrentAtag->body.initrd2_tag.size = InitrdImageSize;
+
+ // Move pointer to next tag
+ mLinuxKernelCurrentAtag = next_tag_address(mLinuxKernelCurrentAtag);
+}
+STATIC
+VOID
+SetupEndTag (
+ VOID
+ )
+{
+ // Empty tag ends list; this has zero length and no body
+ mLinuxKernelCurrentAtag->header.type = ATAG_NONE;
+ mLinuxKernelCurrentAtag->header.size = 0;
+
+ /* We can not calculate the next address by using the standard macro:
+ * Params = next_tag_address(Params);
+ * because it relies on the header.size, which here it is 0 (zero).
+ * The easiest way is to add the sizeof(mLinuxKernelCurrentAtag->header).
+ */
+ mLinuxKernelCurrentAtag = (LINUX_ATAG*)((UINT32)mLinuxKernelCurrentAtag + sizeof(mLinuxKernelCurrentAtag->header));
+}
+
+EFI_STATUS
+PrepareAtagList (
+ IN CONST CHAR8* CommandLineString,
+ IN EFI_PHYSICAL_ADDRESS InitrdImage,
+ IN UINTN InitrdImageSize,
+ OUT EFI_PHYSICAL_ADDRESS *AtagBase,
+ OUT UINT32 *AtagSize
+ )
+{
+ EFI_STATUS Status;
+ LIST_ENTRY *ResourceLink;
+ LIST_ENTRY ResourceList;
+ EFI_PHYSICAL_ADDRESS AtagStartAddress;
+ BDS_SYSTEM_MEMORY_RESOURCE *Resource;
+
+ AtagStartAddress = LINUX_ATAG_MAX_OFFSET;
+ Status = gBS->AllocatePages (AllocateMaxAddress, EfiBootServicesData, EFI_SIZE_TO_PAGES(ATAG_MAX_SIZE), &AtagStartAddress);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_WARN, "Warning: Failed to allocate Atag at 0x%lX (%r). The Atag will be allocated somewhere else in System Memory.\n", AtagStartAddress, Status));
+ Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, EFI_SIZE_TO_PAGES(ATAG_MAX_SIZE), &AtagStartAddress);
+ ASSERT_EFI_ERROR(Status);
+ }
+
+ // Ready to setup the atag list
+ mLinuxKernelCurrentAtag = (LINUX_ATAG*)(UINTN)AtagStartAddress;
+
+ // Standard core tag 4k PageSize
+ SetupCoreTag( (UINT32)SIZE_4KB );
+
+ // Physical memory setup
+ GetSystemMemoryResources (&ResourceList);
+ ResourceLink = ResourceList.ForwardLink;
+ while (ResourceLink != NULL && ResourceLink != &ResourceList) {
+ Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)ResourceLink;
+ DEBUG((EFI_D_INFO,"- [0x%08X,0x%08X]\n",(UINT32)Resource->PhysicalStart,(UINT32)Resource->PhysicalStart+(UINT32)Resource->ResourceLength));
+ SetupMemTag( (UINT32)Resource->PhysicalStart, (UINT32)Resource->ResourceLength );
+ ResourceLink = ResourceLink->ForwardLink;
+ }
+
+ // CommandLine setting root device
+ if (CommandLineString) {
+ SetupCmdlineTag (CommandLineString);
+ }
+
+ if (InitrdImageSize > 0 && InitrdImage != 0) {
+ SetupInitrdTag ((UINT32)InitrdImage, (UINT32)InitrdImageSize);
+ }
+
+ // End of tags
+ SetupEndTag();
+
+ // Calculate atag list size
+ *AtagBase = AtagStartAddress;
+ *AtagSize = (UINT32)mLinuxKernelCurrentAtag - (UINT32)AtagStartAddress + 1;
+
+ return EFI_SUCCESS;
+}
+
diff --git a/ArmPkg/Library/BdsLib/BdsLinuxLoader.c b/ArmPkg/Library/BdsLib/BdsLinuxLoader.c
index cc54343fa..bf3e850a5 100644
--- a/ArmPkg/Library/BdsLib/BdsLinuxLoader.c
+++ b/ArmPkg/Library/BdsLib/BdsLinuxLoader.c
@@ -1,274 +1,274 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-#include "BdsLinuxLoader.h"
-
-#define ALIGN32_BELOW(addr) ALIGN_POINTER(addr - 32,32)
-
-STATIC
-EFI_STATUS
-PreparePlatformHardware (
- VOID
- )
-{
- //Note: Interrupts will be disabled by the GIC driver when ExitBootServices() will be called.
-
- // Clean, invalidate, disable data cache
- ArmCleanInvalidateDataCache();
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+#include "BdsLinuxLoader.h"
+
+#define ALIGN32_BELOW(addr) ALIGN_POINTER(addr - 32,32)
+
+STATIC
+EFI_STATUS
+PreparePlatformHardware (
+ VOID
+ )
+{
+ //Note: Interrupts will be disabled by the GIC driver when ExitBootServices() will be called.
+
+ // Clean, invalidate, disable data cache
+ ArmCleanInvalidateDataCache();
ArmDisableDataCache();
-
- // Invalidate and disable the Instruction cache
- ArmDisableInstructionCache ();
- ArmInvalidateInstructionCache ();
-
- // Turn off MMU
- ArmDisableMmu();
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-StartLinux (
- IN EFI_PHYSICAL_ADDRESS LinuxImage,
- IN UINTN LinuxImageSize,
- IN EFI_PHYSICAL_ADDRESS KernelParamsAddress,
- IN UINTN KernelParamsSize,
- IN UINT32 MachineType
- )
-{
- EFI_STATUS Status;
- LINUX_KERNEL LinuxKernel;
-
- // Shut down UEFI boot services. ExitBootServices() will notify every driver that created an event on
- // ExitBootServices event. Example the Interrupt DXE driver will disable the interrupts on this event.
- Status = ShutdownUefiBootServices ();
- if(EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR,"ERROR: Can not shutdown UEFI boot services. Status=0x%X\n", Status));
- goto Exit;
- }
-
- // Move the kernel parameters to any address inside the first 1MB.
- // This is necessary because the ARM Linux kernel requires
- // the FTD / ATAG List to reside entirely inside the first 1MB of
- // physical memory.
- //Note: There is no requirement on the alignment
- if (MachineType != ARM_FDT_MACHINE_TYPE) {
- if (((UINTN)KernelParamsAddress > LINUX_ATAG_MAX_OFFSET) && (KernelParamsSize < PcdGet32(PcdArmLinuxAtagMaxOffset))) {
- KernelParamsAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)CopyMem (ALIGN32_BELOW(LINUX_ATAG_MAX_OFFSET - KernelParamsSize), (VOID*)(UINTN)KernelParamsAddress, KernelParamsSize);
- }
- } else {
- if (((UINTN)KernelParamsAddress > LINUX_FDT_MAX_OFFSET) && (KernelParamsSize < PcdGet32(PcdArmLinuxFdtMaxOffset))) {
- KernelParamsAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)CopyMem (ALIGN32_BELOW(LINUX_FDT_MAX_OFFSET - KernelParamsSize), (VOID*)(UINTN)KernelParamsAddress, KernelParamsSize);
- }
- }
-
- if ((UINTN)LinuxImage > LINUX_KERNEL_MAX_OFFSET) {
- //Note: There is no requirement on the alignment
- LinuxKernel = (LINUX_KERNEL)CopyMem (ALIGN32_BELOW(LINUX_KERNEL_MAX_OFFSET - LinuxImageSize), (VOID*)(UINTN)LinuxImage, LinuxImageSize);
- } else {
- LinuxKernel = (LINUX_KERNEL)(UINTN)LinuxImage;
- }
-
- // Check if the Linux Image is a uImage
- if (*(UINT32*)LinuxKernel == LINUX_UIMAGE_SIGNATURE) {
- // Assume the Image Entry Point is just after the uImage header (64-byte size)
- LinuxKernel = (LINUX_KERNEL)((UINTN)LinuxKernel + 64);
- LinuxImageSize -= 64;
- }
-
- //TODO: Check there is no overlapping between kernel and Atag
-
- //
- // Switch off interrupts, caches, mmu, etc
- //
- Status = PreparePlatformHardware ();
- ASSERT_EFI_ERROR(Status);
-
- // Register and print out performance information
- PERF_END (NULL, "BDS", NULL, 0);
- if (PerformanceMeasurementEnabled ()) {
- PrintPerformance ();
- }
-
- //
- // Start the Linux Kernel
- //
-
- // Outside BootServices, so can't use Print();
- DEBUG((EFI_D_ERROR, "\nStarting the kernel:\n\n"));
-
- // Jump to kernel with register set
- LinuxKernel ((UINTN)0, MachineType, (UINTN)KernelParamsAddress);
-
- // Kernel should never exit
- // After Life services are not provided
- ASSERT(FALSE);
-
-Exit:
- // Only be here if we fail to start Linux
- Print (L"ERROR : Can not start the kernel. Status=0x%X\n", Status);
-
- // Free Runtimee Memory (kernel and FDT)
- return Status;
-}
-
-/**
- Start a Linux kernel from a Device Path
-
- @param LinuxKernel Device Path to the Linux Kernel
- @param Parameters Linux kernel arguments
- @param Fdt Device Path to the Flat Device Tree
-
- @retval EFI_SUCCESS All drivers have been connected
- @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
- @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
-
-**/
-EFI_STATUS
-BdsBootLinuxAtag (
- IN EFI_DEVICE_PATH_PROTOCOL* LinuxKernelDevicePath,
- IN EFI_DEVICE_PATH_PROTOCOL* InitrdDevicePath,
- IN CONST CHAR8* CommandLineArguments
- )
-{
- EFI_STATUS Status;
- UINT32 LinuxImageSize;
- UINT32 InitrdImageSize = 0;
- UINT32 AtagSize;
- EFI_PHYSICAL_ADDRESS AtagBase;
- EFI_PHYSICAL_ADDRESS LinuxImage;
- EFI_PHYSICAL_ADDRESS InitrdImage;
-
- PERF_START (NULL, "BDS", NULL, 0);
-
- // Load the Linux kernel from a device path
- LinuxImage = LINUX_KERNEL_MAX_OFFSET;
- Status = BdsLoadImage (LinuxKernelDevicePath, AllocateMaxAddress, &LinuxImage, &LinuxImageSize);
- if (EFI_ERROR(Status)) {
- Print (L"ERROR: Did not find Linux kernel.\n");
- return Status;
- }
-
- if (InitrdDevicePath) {
- // Load the initrd near to the Linux kernel
- InitrdImage = LINUX_KERNEL_MAX_OFFSET;
- Status = BdsLoadImage (InitrdDevicePath, AllocateMaxAddress, &InitrdImage, &InitrdImageSize);
- if (Status == EFI_OUT_OF_RESOURCES) {
- Status = BdsLoadImage (InitrdDevicePath, AllocateAnyPages, &InitrdImage, &InitrdImageSize);
- }
- if (EFI_ERROR(Status)) {
- Print (L"ERROR: Did not find initrd image.\n");
- return Status;
- }
-
- // Check if the initrd is a uInitrd
- if (*(UINT32*)((UINTN)InitrdImage) == LINUX_UIMAGE_SIGNATURE) {
- // Skip the 64-byte image header
- InitrdImage = (EFI_PHYSICAL_ADDRESS)((UINTN)InitrdImage + 64);
- InitrdImageSize -= 64;
- }
- }
-
- //
- // Setup the Linux Kernel Parameters
- //
-
- // By setting address=0 we leave the memory allocation to the function
- Status = PrepareAtagList (CommandLineArguments, InitrdImage, InitrdImageSize, &AtagBase, &AtagSize);
- if (EFI_ERROR(Status)) {
- Print(L"ERROR: Can not prepare ATAG list. Status=0x%X\n", Status);
- return Status;
- }
-
- return StartLinux (LinuxImage, LinuxImageSize, AtagBase, AtagSize, PcdGet32(PcdArmMachineType));
-}
-
-/**
- Start a Linux kernel from a Device Path
-
- @param LinuxKernel Device Path to the Linux Kernel
- @param Parameters Linux kernel arguments
- @param Fdt Device Path to the Flat Device Tree
-
- @retval EFI_SUCCESS All drivers have been connected
- @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
- @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
-
-**/
-EFI_STATUS
-BdsBootLinuxFdt (
- IN EFI_DEVICE_PATH_PROTOCOL* LinuxKernelDevicePath,
- IN EFI_DEVICE_PATH_PROTOCOL* InitrdDevicePath,
- IN CONST CHAR8* CommandLineArguments,
- IN EFI_DEVICE_PATH_PROTOCOL* FdtDevicePath
- )
-{
- EFI_STATUS Status;
- UINT32 LinuxImageSize;
- UINT32 InitrdImageSize = 0;
- UINT32 FdtBlobSize;
- EFI_PHYSICAL_ADDRESS FdtBlobBase;
- EFI_PHYSICAL_ADDRESS LinuxImage;
- EFI_PHYSICAL_ADDRESS InitrdImage;
-
- PERF_START (NULL, "BDS", NULL, 0);
-
- // Load the Linux kernel from a device path
- LinuxImage = LINUX_KERNEL_MAX_OFFSET;
- Status = BdsLoadImage (LinuxKernelDevicePath, AllocateMaxAddress, &LinuxImage, &LinuxImageSize);
- if (EFI_ERROR(Status)) {
- Print (L"ERROR: Did not find Linux kernel.\n");
- return Status;
- }
-
- if (InitrdDevicePath) {
- InitrdImage = LINUX_KERNEL_MAX_OFFSET;
- Status = BdsLoadImage (InitrdDevicePath, AllocateMaxAddress, &InitrdImage, &InitrdImageSize);
- if (Status == EFI_OUT_OF_RESOURCES) {
- Status = BdsLoadImage (InitrdDevicePath, AllocateAnyPages, &InitrdImage, &InitrdImageSize);
- }
- if (EFI_ERROR(Status)) {
- Print (L"ERROR: Did not find initrd image.\n");
- return Status;
- }
-
- // Check if the initrd is a uInitrd
- if (*(UINT32*)((UINTN)InitrdImage) == LINUX_UIMAGE_SIGNATURE) {
- // Skip the 64-byte image header
- InitrdImage = (EFI_PHYSICAL_ADDRESS)((UINTN)InitrdImage + 64);
- InitrdImageSize -= 64;
- }
- }
-
- // Load the FDT binary from a device path. The FDT will be reloaded later to a more appropriate location for the Linux kernel.
- FdtBlobBase = 0;
- Status = BdsLoadImage (FdtDevicePath, AllocateAnyPages, &FdtBlobBase, &FdtBlobSize);
- if (EFI_ERROR(Status)) {
- Print (L"ERROR: Did not find Device Tree blob.\n");
- return Status;
- }
-
- // Update the Fdt with the Initrd information. The FDT will increase in size.
- // By setting address=0 we leave the memory allocation to the function
- Status = PrepareFdt (CommandLineArguments, InitrdImage, InitrdImageSize, &FdtBlobBase, &FdtBlobSize);
- if (EFI_ERROR(Status)) {
- Print(L"ERROR: Can not load kernel with FDT. Status=%r\n", Status);
- return Status;
- }
-
- return StartLinux (LinuxImage, LinuxImageSize, FdtBlobBase, FdtBlobSize, ARM_FDT_MACHINE_TYPE);
-}
-
+
+ // Invalidate and disable the Instruction cache
+ ArmDisableInstructionCache ();
+ ArmInvalidateInstructionCache ();
+
+ // Turn off MMU
+ ArmDisableMmu();
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+StartLinux (
+ IN EFI_PHYSICAL_ADDRESS LinuxImage,
+ IN UINTN LinuxImageSize,
+ IN EFI_PHYSICAL_ADDRESS KernelParamsAddress,
+ IN UINTN KernelParamsSize,
+ IN UINT32 MachineType
+ )
+{
+ EFI_STATUS Status;
+ LINUX_KERNEL LinuxKernel;
+
+ // Shut down UEFI boot services. ExitBootServices() will notify every driver that created an event on
+ // ExitBootServices event. Example the Interrupt DXE driver will disable the interrupts on this event.
+ Status = ShutdownUefiBootServices ();
+ if(EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR,"ERROR: Can not shutdown UEFI boot services. Status=0x%X\n", Status));
+ goto Exit;
+ }
+
+ // Move the kernel parameters to any address inside the first 1MB.
+ // This is necessary because the ARM Linux kernel requires
+ // the FTD / ATAG List to reside entirely inside the first 1MB of
+ // physical memory.
+ //Note: There is no requirement on the alignment
+ if (MachineType != ARM_FDT_MACHINE_TYPE) {
+ if (((UINTN)KernelParamsAddress > LINUX_ATAG_MAX_OFFSET) && (KernelParamsSize < PcdGet32(PcdArmLinuxAtagMaxOffset))) {
+ KernelParamsAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)CopyMem (ALIGN32_BELOW(LINUX_ATAG_MAX_OFFSET - KernelParamsSize), (VOID*)(UINTN)KernelParamsAddress, KernelParamsSize);
+ }
+ } else {
+ if (((UINTN)KernelParamsAddress > LINUX_FDT_MAX_OFFSET) && (KernelParamsSize < PcdGet32(PcdArmLinuxFdtMaxOffset))) {
+ KernelParamsAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)CopyMem (ALIGN32_BELOW(LINUX_FDT_MAX_OFFSET - KernelParamsSize), (VOID*)(UINTN)KernelParamsAddress, KernelParamsSize);
+ }
+ }
+
+ if ((UINTN)LinuxImage > LINUX_KERNEL_MAX_OFFSET) {
+ //Note: There is no requirement on the alignment
+ LinuxKernel = (LINUX_KERNEL)CopyMem (ALIGN32_BELOW(LINUX_KERNEL_MAX_OFFSET - LinuxImageSize), (VOID*)(UINTN)LinuxImage, LinuxImageSize);
+ } else {
+ LinuxKernel = (LINUX_KERNEL)(UINTN)LinuxImage;
+ }
+
+ // Check if the Linux Image is a uImage
+ if (*(UINT32*)LinuxKernel == LINUX_UIMAGE_SIGNATURE) {
+ // Assume the Image Entry Point is just after the uImage header (64-byte size)
+ LinuxKernel = (LINUX_KERNEL)((UINTN)LinuxKernel + 64);
+ LinuxImageSize -= 64;
+ }
+
+ //TODO: Check there is no overlapping between kernel and Atag
+
+ //
+ // Switch off interrupts, caches, mmu, etc
+ //
+ Status = PreparePlatformHardware ();
+ ASSERT_EFI_ERROR(Status);
+
+ // Register and print out performance information
+ PERF_END (NULL, "BDS", NULL, 0);
+ if (PerformanceMeasurementEnabled ()) {
+ PrintPerformance ();
+ }
+
+ //
+ // Start the Linux Kernel
+ //
+
+ // Outside BootServices, so can't use Print();
+ DEBUG((EFI_D_ERROR, "\nStarting the kernel:\n\n"));
+
+ // Jump to kernel with register set
+ LinuxKernel ((UINTN)0, MachineType, (UINTN)KernelParamsAddress);
+
+ // Kernel should never exit
+ // After Life services are not provided
+ ASSERT(FALSE);
+
+Exit:
+ // Only be here if we fail to start Linux
+ Print (L"ERROR : Can not start the kernel. Status=0x%X\n", Status);
+
+ // Free Runtimee Memory (kernel and FDT)
+ return Status;
+}
+
+/**
+ Start a Linux kernel from a Device Path
+
+ @param LinuxKernel Device Path to the Linux Kernel
+ @param Parameters Linux kernel arguments
+ @param Fdt Device Path to the Flat Device Tree
+
+ @retval EFI_SUCCESS All drivers have been connected
+ @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
+ @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
+
+**/
+EFI_STATUS
+BdsBootLinuxAtag (
+ IN EFI_DEVICE_PATH_PROTOCOL* LinuxKernelDevicePath,
+ IN EFI_DEVICE_PATH_PROTOCOL* InitrdDevicePath,
+ IN CONST CHAR8* CommandLineArguments
+ )
+{
+ EFI_STATUS Status;
+ UINT32 LinuxImageSize;
+ UINT32 InitrdImageSize = 0;
+ UINT32 AtagSize;
+ EFI_PHYSICAL_ADDRESS AtagBase;
+ EFI_PHYSICAL_ADDRESS LinuxImage;
+ EFI_PHYSICAL_ADDRESS InitrdImage;
+
+ PERF_START (NULL, "BDS", NULL, 0);
+
+ // Load the Linux kernel from a device path
+ LinuxImage = LINUX_KERNEL_MAX_OFFSET;
+ Status = BdsLoadImage (LinuxKernelDevicePath, AllocateMaxAddress, &LinuxImage, &LinuxImageSize);
+ if (EFI_ERROR(Status)) {
+ Print (L"ERROR: Did not find Linux kernel.\n");
+ return Status;
+ }
+
+ if (InitrdDevicePath) {
+ // Load the initrd near to the Linux kernel
+ InitrdImage = LINUX_KERNEL_MAX_OFFSET;
+ Status = BdsLoadImage (InitrdDevicePath, AllocateMaxAddress, &InitrdImage, &InitrdImageSize);
+ if (Status == EFI_OUT_OF_RESOURCES) {
+ Status = BdsLoadImage (InitrdDevicePath, AllocateAnyPages, &InitrdImage, &InitrdImageSize);
+ }
+ if (EFI_ERROR(Status)) {
+ Print (L"ERROR: Did not find initrd image.\n");
+ return Status;
+ }
+
+ // Check if the initrd is a uInitrd
+ if (*(UINT32*)((UINTN)InitrdImage) == LINUX_UIMAGE_SIGNATURE) {
+ // Skip the 64-byte image header
+ InitrdImage = (EFI_PHYSICAL_ADDRESS)((UINTN)InitrdImage + 64);
+ InitrdImageSize -= 64;
+ }
+ }
+
+ //
+ // Setup the Linux Kernel Parameters
+ //
+
+ // By setting address=0 we leave the memory allocation to the function
+ Status = PrepareAtagList (CommandLineArguments, InitrdImage, InitrdImageSize, &AtagBase, &AtagSize);
+ if (EFI_ERROR(Status)) {
+ Print(L"ERROR: Can not prepare ATAG list. Status=0x%X\n", Status);
+ return Status;
+ }
+
+ return StartLinux (LinuxImage, LinuxImageSize, AtagBase, AtagSize, PcdGet32(PcdArmMachineType));
+}
+
+/**
+ Start a Linux kernel from a Device Path
+
+ @param LinuxKernel Device Path to the Linux Kernel
+ @param Parameters Linux kernel arguments
+ @param Fdt Device Path to the Flat Device Tree
+
+ @retval EFI_SUCCESS All drivers have been connected
+ @retval EFI_NOT_FOUND The Linux kernel Device Path has not been found
+ @retval EFI_OUT_OF_RESOURCES There is not enough resource memory to store the matching results.
+
+**/
+EFI_STATUS
+BdsBootLinuxFdt (
+ IN EFI_DEVICE_PATH_PROTOCOL* LinuxKernelDevicePath,
+ IN EFI_DEVICE_PATH_PROTOCOL* InitrdDevicePath,
+ IN CONST CHAR8* CommandLineArguments,
+ IN EFI_DEVICE_PATH_PROTOCOL* FdtDevicePath
+ )
+{
+ EFI_STATUS Status;
+ UINT32 LinuxImageSize;
+ UINT32 InitrdImageSize = 0;
+ UINT32 FdtBlobSize;
+ EFI_PHYSICAL_ADDRESS FdtBlobBase;
+ EFI_PHYSICAL_ADDRESS LinuxImage;
+ EFI_PHYSICAL_ADDRESS InitrdImage;
+
+ PERF_START (NULL, "BDS", NULL, 0);
+
+ // Load the Linux kernel from a device path
+ LinuxImage = LINUX_KERNEL_MAX_OFFSET;
+ Status = BdsLoadImage (LinuxKernelDevicePath, AllocateMaxAddress, &LinuxImage, &LinuxImageSize);
+ if (EFI_ERROR(Status)) {
+ Print (L"ERROR: Did not find Linux kernel.\n");
+ return Status;
+ }
+
+ if (InitrdDevicePath) {
+ InitrdImage = LINUX_KERNEL_MAX_OFFSET;
+ Status = BdsLoadImage (InitrdDevicePath, AllocateMaxAddress, &InitrdImage, &InitrdImageSize);
+ if (Status == EFI_OUT_OF_RESOURCES) {
+ Status = BdsLoadImage (InitrdDevicePath, AllocateAnyPages, &InitrdImage, &InitrdImageSize);
+ }
+ if (EFI_ERROR(Status)) {
+ Print (L"ERROR: Did not find initrd image.\n");
+ return Status;
+ }
+
+ // Check if the initrd is a uInitrd
+ if (*(UINT32*)((UINTN)InitrdImage) == LINUX_UIMAGE_SIGNATURE) {
+ // Skip the 64-byte image header
+ InitrdImage = (EFI_PHYSICAL_ADDRESS)((UINTN)InitrdImage + 64);
+ InitrdImageSize -= 64;
+ }
+ }
+
+ // Load the FDT binary from a device path. The FDT will be reloaded later to a more appropriate location for the Linux kernel.
+ FdtBlobBase = 0;
+ Status = BdsLoadImage (FdtDevicePath, AllocateAnyPages, &FdtBlobBase, &FdtBlobSize);
+ if (EFI_ERROR(Status)) {
+ Print (L"ERROR: Did not find Device Tree blob.\n");
+ return Status;
+ }
+
+ // Update the Fdt with the Initrd information. The FDT will increase in size.
+ // By setting address=0 we leave the memory allocation to the function
+ Status = PrepareFdt (CommandLineArguments, InitrdImage, InitrdImageSize, &FdtBlobBase, &FdtBlobSize);
+ if (EFI_ERROR(Status)) {
+ Print(L"ERROR: Can not load kernel with FDT. Status=%r\n", Status);
+ return Status;
+ }
+
+ return StartLinux (LinuxImage, LinuxImageSize, FdtBlobBase, FdtBlobSize, ARM_FDT_MACHINE_TYPE);
+}
+
diff --git a/ArmPkg/Library/BdsLib/BdsLinuxLoader.h b/ArmPkg/Library/BdsLib/BdsLinuxLoader.h
index a9b7037d1..a3ecddc4f 100644
--- a/ArmPkg/Library/BdsLib/BdsLinuxLoader.h
+++ b/ArmPkg/Library/BdsLib/BdsLinuxLoader.h
@@ -1,156 +1,156 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef __BDSLINUXLOADER_H
-#define __BDSLINUXLOADER_H
-
-#define LINUX_UIMAGE_SIGNATURE 0x56190527
-#define LINUX_KERNEL_MAX_OFFSET (PcdGet32(PcdSystemMemoryBase) + PcdGet32(PcdArmLinuxKernelMaxOffset))
-#define LINUX_ATAG_MAX_OFFSET (PcdGet32(PcdSystemMemoryBase) + PcdGet32(PcdArmLinuxAtagMaxOffset))
-#define LINUX_FDT_MAX_OFFSET (PcdGet32(PcdSystemMemoryBase) + PcdGet32(PcdArmLinuxFdtMaxOffset))
-
-// Additional size that could be used for FDT entries added by the UEFI OS Loader
-// Estimation based on: EDID (300bytes) + bootargs (200bytes) + initrd region (20bytes)
-// + system memory region (20bytes) + mp_core entries (200 bytes)
-#define FDT_ADDITIONAL_ENTRIES_SIZE 0x300
-
-#define ARM_FDT_MACHINE_TYPE 0xFFFFFFFF
-
-typedef VOID (*LINUX_KERNEL)(UINT32 Zero, UINT32 Arch, UINTN ParametersBase);
-
-//
-// ATAG Definitions
-//
-
-#define ATAG_MAX_SIZE 0x3000
-
-/* ATAG : list of possible tags */
-#define ATAG_NONE 0x00000000
-#define ATAG_CORE 0x54410001
-#define ATAG_MEM 0x54410002
-#define ATAG_VIDEOTEXT 0x54410003
-#define ATAG_RAMDISK 0x54410004
-#define ATAG_INITRD2 0x54420005
-#define ATAG_SERIAL 0x54410006
-#define ATAG_REVISION 0x54410007
-#define ATAG_VIDEOLFB 0x54410008
-#define ATAG_CMDLINE 0x54410009
-#define ATAG_ARM_MP_CORE 0x5441000A
-
-#define next_tag_address(t) ((LINUX_ATAG*)((UINT32)(t) + (((t)->header.size) << 2) ))
-#define tag_size(type) ((UINT32)((sizeof(LINUX_ATAG_HEADER) + sizeof(type)) >> 2))
-
-typedef struct {
- UINT32 size; /* length of tag in words including this header */
- UINT32 type; /* tag type */
-} LINUX_ATAG_HEADER;
-
-typedef struct {
- UINT32 flags;
- UINT32 pagesize;
- UINT32 rootdev;
-} LINUX_ATAG_CORE;
-
-typedef struct {
- UINT32 size;
- UINTN start;
-} LINUX_ATAG_MEM;
-
-typedef struct {
- UINT8 x;
- UINT8 y;
- UINT16 video_page;
- UINT8 video_mode;
- UINT8 video_cols;
- UINT16 video_ega_bx;
- UINT8 video_lines;
- UINT8 video_isvga;
- UINT16 video_points;
-} LINUX_ATAG_VIDEOTEXT;
-
-typedef struct {
- UINT32 flags;
- UINT32 size;
- UINTN start;
-} LINUX_ATAG_RAMDISK;
-
-typedef struct {
- UINT32 start;
- UINT32 size;
-} LINUX_ATAG_INITRD2;
-
-typedef struct {
- UINT32 low;
- UINT32 high;
-} LINUX_ATAG_SERIALNR;
-
-typedef struct {
- UINT32 rev;
-} LINUX_ATAG_REVISION;
-
-typedef struct {
- UINT16 lfb_width;
- UINT16 lfb_height;
- UINT16 lfb_depth;
- UINT16 lfb_linelength;
- UINT32 lfb_base;
- UINT32 lfb_size;
- UINT8 red_size;
- UINT8 red_pos;
- UINT8 green_size;
- UINT8 green_pos;
- UINT8 blue_size;
- UINT8 blue_pos;
- UINT8 rsvd_size;
- UINT8 rsvd_pos;
-} LINUX_ATAG_VIDEOLFB;
-
-typedef struct {
- CHAR8 cmdline[1];
-} LINUX_ATAG_CMDLINE;
-
-typedef struct {
- LINUX_ATAG_HEADER header;
- union {
- LINUX_ATAG_CORE core_tag;
- LINUX_ATAG_MEM mem_tag;
- LINUX_ATAG_VIDEOTEXT videotext_tag;
- LINUX_ATAG_RAMDISK ramdisk_tag;
- LINUX_ATAG_INITRD2 initrd2_tag;
- LINUX_ATAG_SERIALNR serialnr_tag;
- LINUX_ATAG_REVISION revision_tag;
- LINUX_ATAG_VIDEOLFB videolfb_tag;
- LINUX_ATAG_CMDLINE cmdline_tag;
- } body;
-} LINUX_ATAG;
-
-EFI_STATUS
-PrepareAtagList (
- IN CONST CHAR8* CommandLineString,
- IN EFI_PHYSICAL_ADDRESS InitrdImage,
- IN UINTN InitrdImageSize,
- OUT EFI_PHYSICAL_ADDRESS *AtagBase,
- OUT UINT32 *AtagSize
- );
-
-EFI_STATUS
-PrepareFdt (
- IN CONST CHAR8* CommandLineArguments,
- IN EFI_PHYSICAL_ADDRESS InitrdImage,
- IN UINTN InitrdImageSize,
- IN OUT EFI_PHYSICAL_ADDRESS *FdtBlobBase,
- IN OUT UINT32 *FdtBlobSize
- );
-
-#endif
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef __BDSLINUXLOADER_H
+#define __BDSLINUXLOADER_H
+
+#define LINUX_UIMAGE_SIGNATURE 0x56190527
+#define LINUX_KERNEL_MAX_OFFSET (PcdGet32(PcdSystemMemoryBase) + PcdGet32(PcdArmLinuxKernelMaxOffset))
+#define LINUX_ATAG_MAX_OFFSET (PcdGet32(PcdSystemMemoryBase) + PcdGet32(PcdArmLinuxAtagMaxOffset))
+#define LINUX_FDT_MAX_OFFSET (PcdGet32(PcdSystemMemoryBase) + PcdGet32(PcdArmLinuxFdtMaxOffset))
+
+// Additional size that could be used for FDT entries added by the UEFI OS Loader
+// Estimation based on: EDID (300bytes) + bootargs (200bytes) + initrd region (20bytes)
+// + system memory region (20bytes) + mp_core entries (200 bytes)
+#define FDT_ADDITIONAL_ENTRIES_SIZE 0x300
+
+#define ARM_FDT_MACHINE_TYPE 0xFFFFFFFF
+
+typedef VOID (*LINUX_KERNEL)(UINT32 Zero, UINT32 Arch, UINTN ParametersBase);
+
+//
+// ATAG Definitions
+//
+
+#define ATAG_MAX_SIZE 0x3000
+
+/* ATAG : list of possible tags */
+#define ATAG_NONE 0x00000000
+#define ATAG_CORE 0x54410001
+#define ATAG_MEM 0x54410002
+#define ATAG_VIDEOTEXT 0x54410003
+#define ATAG_RAMDISK 0x54410004
+#define ATAG_INITRD2 0x54420005
+#define ATAG_SERIAL 0x54410006
+#define ATAG_REVISION 0x54410007
+#define ATAG_VIDEOLFB 0x54410008
+#define ATAG_CMDLINE 0x54410009
+#define ATAG_ARM_MP_CORE 0x5441000A
+
+#define next_tag_address(t) ((LINUX_ATAG*)((UINT32)(t) + (((t)->header.size) << 2) ))
+#define tag_size(type) ((UINT32)((sizeof(LINUX_ATAG_HEADER) + sizeof(type)) >> 2))
+
+typedef struct {
+ UINT32 size; /* length of tag in words including this header */
+ UINT32 type; /* tag type */
+} LINUX_ATAG_HEADER;
+
+typedef struct {
+ UINT32 flags;
+ UINT32 pagesize;
+ UINT32 rootdev;
+} LINUX_ATAG_CORE;
+
+typedef struct {
+ UINT32 size;
+ UINTN start;
+} LINUX_ATAG_MEM;
+
+typedef struct {
+ UINT8 x;
+ UINT8 y;
+ UINT16 video_page;
+ UINT8 video_mode;
+ UINT8 video_cols;
+ UINT16 video_ega_bx;
+ UINT8 video_lines;
+ UINT8 video_isvga;
+ UINT16 video_points;
+} LINUX_ATAG_VIDEOTEXT;
+
+typedef struct {
+ UINT32 flags;
+ UINT32 size;
+ UINTN start;
+} LINUX_ATAG_RAMDISK;
+
+typedef struct {
+ UINT32 start;
+ UINT32 size;
+} LINUX_ATAG_INITRD2;
+
+typedef struct {
+ UINT32 low;
+ UINT32 high;
+} LINUX_ATAG_SERIALNR;
+
+typedef struct {
+ UINT32 rev;
+} LINUX_ATAG_REVISION;
+
+typedef struct {
+ UINT16 lfb_width;
+ UINT16 lfb_height;
+ UINT16 lfb_depth;
+ UINT16 lfb_linelength;
+ UINT32 lfb_base;
+ UINT32 lfb_size;
+ UINT8 red_size;
+ UINT8 red_pos;
+ UINT8 green_size;
+ UINT8 green_pos;
+ UINT8 blue_size;
+ UINT8 blue_pos;
+ UINT8 rsvd_size;
+ UINT8 rsvd_pos;
+} LINUX_ATAG_VIDEOLFB;
+
+typedef struct {
+ CHAR8 cmdline[1];
+} LINUX_ATAG_CMDLINE;
+
+typedef struct {
+ LINUX_ATAG_HEADER header;
+ union {
+ LINUX_ATAG_CORE core_tag;
+ LINUX_ATAG_MEM mem_tag;
+ LINUX_ATAG_VIDEOTEXT videotext_tag;
+ LINUX_ATAG_RAMDISK ramdisk_tag;
+ LINUX_ATAG_INITRD2 initrd2_tag;
+ LINUX_ATAG_SERIALNR serialnr_tag;
+ LINUX_ATAG_REVISION revision_tag;
+ LINUX_ATAG_VIDEOLFB videolfb_tag;
+ LINUX_ATAG_CMDLINE cmdline_tag;
+ } body;
+} LINUX_ATAG;
+
+EFI_STATUS
+PrepareAtagList (
+ IN CONST CHAR8* CommandLineString,
+ IN EFI_PHYSICAL_ADDRESS InitrdImage,
+ IN UINTN InitrdImageSize,
+ OUT EFI_PHYSICAL_ADDRESS *AtagBase,
+ OUT UINT32 *AtagSize
+ );
+
+EFI_STATUS
+PrepareFdt (
+ IN CONST CHAR8* CommandLineArguments,
+ IN EFI_PHYSICAL_ADDRESS InitrdImage,
+ IN UINTN InitrdImageSize,
+ IN OUT EFI_PHYSICAL_ADDRESS *FdtBlobBase,
+ IN OUT UINT32 *FdtBlobSize
+ );
+
+#endif
diff --git a/ArmPkg/Library/BdsLib/BdsLoadOption.c b/ArmPkg/Library/BdsLib/BdsLoadOption.c
index 8abbc9b5c..3f4566ffa 100644
--- a/ArmPkg/Library/BdsLib/BdsLoadOption.c
+++ b/ArmPkg/Library/BdsLib/BdsLoadOption.c
@@ -1,270 +1,270 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-
-EFI_STATUS
-BootOptionParseLoadOption (
- IN EFI_LOAD_OPTION EfiLoadOption,
- IN UINTN EfiLoadOptionSize,
- IN OUT BDS_LOAD_OPTION **BdsLoadOption
- )
-{
- BDS_LOAD_OPTION *LoadOption;
- UINTN DescriptionLength;
-
- if (EfiLoadOption == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- if (EfiLoadOptionSize < sizeof(UINT32) + sizeof(UINT16) + sizeof(CHAR16) + sizeof(EFI_DEVICE_PATH_PROTOCOL)) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- if (*BdsLoadOption == NULL) {
- LoadOption = (BDS_LOAD_OPTION*)AllocateZeroPool (sizeof(BDS_LOAD_OPTION));
- if (LoadOption == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
- } else {
- LoadOption = *BdsLoadOption;
- }
-
- LoadOption->LoadOption = EfiLoadOption;
- LoadOption->LoadOptionSize = EfiLoadOptionSize;
-
- LoadOption->Attributes = *(UINT32*)EfiLoadOption;
- LoadOption->FilePathListLength = *(UINT16*)(EfiLoadOption + sizeof(UINT32));
- LoadOption->Description = (CHAR16*)(EfiLoadOption + sizeof(UINT32) + sizeof(UINT16));
- DescriptionLength = StrSize (LoadOption->Description);
- LoadOption->FilePathList = (EFI_DEVICE_PATH_PROTOCOL*)(EfiLoadOption + sizeof(UINT32) + sizeof(UINT16) + DescriptionLength);
-
- // If ((End of EfiLoadOptiony - Start of EfiLoadOption) == EfiLoadOptionSize) then No Optional Data
- if ((UINTN)((UINTN)LoadOption->FilePathList + LoadOption->FilePathListLength - (UINTN)EfiLoadOption) == EfiLoadOptionSize) {
- LoadOption->OptionalData = NULL;
- LoadOption->OptionalDataSize = 0;
- } else {
- LoadOption->OptionalData = (VOID*)((UINTN)(LoadOption->FilePathList) + LoadOption->FilePathListLength);
- LoadOption->OptionalDataSize = EfiLoadOptionSize - ((UINTN)LoadOption->OptionalData - (UINTN)EfiLoadOption);
- }
-
- if (*BdsLoadOption == NULL) {
- *BdsLoadOption = LoadOption;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-BootOptionFromLoadOptionVariable (
- IN CHAR16* BootVariableName,
- OUT BDS_LOAD_OPTION** BdsLoadOption
- )
-{
- EFI_STATUS Status;
- EFI_LOAD_OPTION EfiLoadOption;
- UINTN EfiLoadOptionSize;
-
- Status = GetEnvironmentVariable (BootVariableName, NULL, &EfiLoadOptionSize, (VOID**)&EfiLoadOption);
- if (!EFI_ERROR(Status)) {
- *BdsLoadOption = NULL;
- Status = BootOptionParseLoadOption (EfiLoadOption, EfiLoadOptionSize, BdsLoadOption);
- }
-
- return Status;
-}
-
-EFI_STATUS
-BootOptionFromLoadOptionIndex (
- IN UINT16 LoadOptionIndex,
- OUT BDS_LOAD_OPTION **BdsLoadOption
- )
-{
- CHAR16 BootVariableName[9];
- EFI_STATUS Status;
-
- UnicodeSPrint (BootVariableName, 9 * sizeof(CHAR16), L"Boot%04X", LoadOptionIndex);
-
- Status = BootOptionFromLoadOptionVariable (BootVariableName, BdsLoadOption);
- if (!EFI_ERROR(Status)) {
- (*BdsLoadOption)->LoadOptionIndex = LoadOptionIndex;
- }
-
- return Status;
-}
-
-EFI_STATUS
-BootOptionToLoadOptionVariable (
- IN BDS_LOAD_OPTION* BdsLoadOption
- )
-{
- EFI_STATUS Status;
- UINTN DescriptionSize;
- //UINT16 FilePathListLength;
- EFI_DEVICE_PATH_PROTOCOL* DevicePathNode;
- UINTN NodeLength;
- UINT8* EfiLoadOptionPtr;
- VOID* OldLoadOption;
- CHAR16 BootVariableName[9];
- UINTN BootOrderSize;
- UINT16* BootOrder;
-
- // If we are overwriting an existent Boot Option then we have to free previously allocated memory
- if (BdsLoadOption->LoadOptionSize > 0) {
- OldLoadOption = BdsLoadOption->LoadOption;
- } else {
- OldLoadOption = NULL;
-
- // If this function is called at the creation of the Boot Device entry (not at the update) the
- // BootOption->LoadOptionSize must be zero then we get a new BootIndex for this entry
- BdsLoadOption->LoadOptionIndex = BootOptionAllocateBootIndex ();
-
- //TODO: Add to the the Boot Entry List
- }
-
- DescriptionSize = StrSize(BdsLoadOption->Description);
-
- // Ensure the FilePathListLength information is correct
- ASSERT (GetDevicePathSize (BdsLoadOption->FilePathList) == BdsLoadOption->FilePathListLength);
-
- // Allocate the memory for the EFI Load Option
- BdsLoadOption->LoadOptionSize = sizeof(UINT32) + sizeof(UINT16) + DescriptionSize + BdsLoadOption->FilePathListLength + BdsLoadOption->OptionalDataSize;
-
- BdsLoadOption->LoadOption = (EFI_LOAD_OPTION)AllocateZeroPool (BdsLoadOption->LoadOptionSize);
- if (BdsLoadOption->LoadOption == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- EfiLoadOptionPtr = BdsLoadOption->LoadOption;
-
- //
- // Populate the EFI Load Option and BDS Boot Option structures
- //
-
- // Attributes fields
- *(UINT32*)EfiLoadOptionPtr = BdsLoadOption->Attributes;
- EfiLoadOptionPtr += sizeof(UINT32);
-
- // FilePath List fields
- *(UINT16*)EfiLoadOptionPtr = BdsLoadOption->FilePathListLength;
- EfiLoadOptionPtr += sizeof(UINT16);
-
- // Boot description fields
- CopyMem (EfiLoadOptionPtr, BdsLoadOption->Description, DescriptionSize);
- EfiLoadOptionPtr += DescriptionSize;
-
- // File path fields
- DevicePathNode = BdsLoadOption->FilePathList;
- while (!IsDevicePathEndType (DevicePathNode)) {
- NodeLength = DevicePathNodeLength(DevicePathNode);
- CopyMem (EfiLoadOptionPtr, DevicePathNode, NodeLength);
- EfiLoadOptionPtr += NodeLength;
- DevicePathNode = NextDevicePathNode (DevicePathNode);
- }
-
- // Set the End Device Path Type
- SetDevicePathEndNode (EfiLoadOptionPtr);
- EfiLoadOptionPtr += sizeof(EFI_DEVICE_PATH);
-
- // Fill the Optional Data
- if (BdsLoadOption->OptionalDataSize > 0) {
- CopyMem (EfiLoadOptionPtr, BdsLoadOption->OptionalData, BdsLoadOption->OptionalDataSize);
- }
-
- // Case where the fields have been updated
- if (OldLoadOption) {
- // Now, the old data has been copied to the new allocated packed structure, we need to update the pointers of BdsLoadOption
- BootOptionParseLoadOption (BdsLoadOption->LoadOption, BdsLoadOption->LoadOptionSize, &BdsLoadOption);
- // Free the old packed structure
- FreePool (OldLoadOption);
- }
-
- // Create/Update Boot#### environment variable
- UnicodeSPrint (BootVariableName, 9 * sizeof(CHAR16), L"Boot%04X", BdsLoadOption->LoadOptionIndex);
- Status = gRT->SetVariable (
- BootVariableName,
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- BdsLoadOption->LoadOptionSize,
- BdsLoadOption->LoadOption
- );
-
- // When it is a new entry we must add the entry to the BootOrder
- if (OldLoadOption == NULL) {
- // Add the new Boot Index to the list
- Status = GetEnvironmentVariable (L"BootOrder", NULL, &BootOrderSize, (VOID**)&BootOrder);
- if (!EFI_ERROR(Status)) {
- BootOrder = ReallocatePool (BootOrderSize, BootOrderSize + sizeof(UINT16), BootOrder);
- // Add the new index at the end
- BootOrder[BootOrderSize / sizeof(UINT16)] = BdsLoadOption->LoadOptionIndex;
- BootOrderSize += sizeof(UINT16);
- } else {
- // BootOrder does not exist. Create it
- BootOrderSize = sizeof(UINT16);
- BootOrder = &(BdsLoadOption->LoadOptionIndex);
- }
-
- // Update (or Create) the BootOrder environment variable
- gRT->SetVariable (
- L"BootOrder",
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- BootOrderSize,
- BootOrder
- );
- DEBUG((EFI_D_ERROR,"Create %s\n",BootVariableName));
-
- // Free memory allocated by GetEnvironmentVariable
- if (!EFI_ERROR(Status)) {
- FreePool (BootOrder);
- }
- } else {
- DEBUG((EFI_D_ERROR,"Update %s\n",BootVariableName));
- }
-
- return EFI_SUCCESS;
-}
-
-UINT16
-BootOptionAllocateBootIndex (
- VOID
- )
-{
- EFI_STATUS Status;
- UINTN Index;
- UINT32 BootIndex;
- UINT16 *BootOrder;
- UINTN BootOrderSize;
- BOOLEAN Found;
-
- // Get the Boot Option Order from the environment variable
- Status = GetEnvironmentVariable (L"BootOrder", NULL, &BootOrderSize, (VOID**)&BootOrder);
- if (!EFI_ERROR(Status)) {
- for (BootIndex = 0; BootIndex <= 0xFFFF; BootIndex++) {
- Found = FALSE;
- for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
- if (BootOrder[Index] == BootIndex) {
- Found = TRUE;
- break;
- }
- }
- if (!Found) {
- return BootIndex;
- }
- }
- FreePool (BootOrder);
- }
- // Return the first index
- return 0;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+
+EFI_STATUS
+BootOptionParseLoadOption (
+ IN EFI_LOAD_OPTION EfiLoadOption,
+ IN UINTN EfiLoadOptionSize,
+ IN OUT BDS_LOAD_OPTION **BdsLoadOption
+ )
+{
+ BDS_LOAD_OPTION *LoadOption;
+ UINTN DescriptionLength;
+
+ if (EfiLoadOption == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (EfiLoadOptionSize < sizeof(UINT32) + sizeof(UINT16) + sizeof(CHAR16) + sizeof(EFI_DEVICE_PATH_PROTOCOL)) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ if (*BdsLoadOption == NULL) {
+ LoadOption = (BDS_LOAD_OPTION*)AllocateZeroPool (sizeof(BDS_LOAD_OPTION));
+ if (LoadOption == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ } else {
+ LoadOption = *BdsLoadOption;
+ }
+
+ LoadOption->LoadOption = EfiLoadOption;
+ LoadOption->LoadOptionSize = EfiLoadOptionSize;
+
+ LoadOption->Attributes = *(UINT32*)EfiLoadOption;
+ LoadOption->FilePathListLength = *(UINT16*)(EfiLoadOption + sizeof(UINT32));
+ LoadOption->Description = (CHAR16*)(EfiLoadOption + sizeof(UINT32) + sizeof(UINT16));
+ DescriptionLength = StrSize (LoadOption->Description);
+ LoadOption->FilePathList = (EFI_DEVICE_PATH_PROTOCOL*)(EfiLoadOption + sizeof(UINT32) + sizeof(UINT16) + DescriptionLength);
+
+ // If ((End of EfiLoadOptiony - Start of EfiLoadOption) == EfiLoadOptionSize) then No Optional Data
+ if ((UINTN)((UINTN)LoadOption->FilePathList + LoadOption->FilePathListLength - (UINTN)EfiLoadOption) == EfiLoadOptionSize) {
+ LoadOption->OptionalData = NULL;
+ LoadOption->OptionalDataSize = 0;
+ } else {
+ LoadOption->OptionalData = (VOID*)((UINTN)(LoadOption->FilePathList) + LoadOption->FilePathListLength);
+ LoadOption->OptionalDataSize = EfiLoadOptionSize - ((UINTN)LoadOption->OptionalData - (UINTN)EfiLoadOption);
+ }
+
+ if (*BdsLoadOption == NULL) {
+ *BdsLoadOption = LoadOption;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+BootOptionFromLoadOptionVariable (
+ IN CHAR16* BootVariableName,
+ OUT BDS_LOAD_OPTION** BdsLoadOption
+ )
+{
+ EFI_STATUS Status;
+ EFI_LOAD_OPTION EfiLoadOption;
+ UINTN EfiLoadOptionSize;
+
+ Status = GetEnvironmentVariable (BootVariableName, NULL, &EfiLoadOptionSize, (VOID**)&EfiLoadOption);
+ if (!EFI_ERROR(Status)) {
+ *BdsLoadOption = NULL;
+ Status = BootOptionParseLoadOption (EfiLoadOption, EfiLoadOptionSize, BdsLoadOption);
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+BootOptionFromLoadOptionIndex (
+ IN UINT16 LoadOptionIndex,
+ OUT BDS_LOAD_OPTION **BdsLoadOption
+ )
+{
+ CHAR16 BootVariableName[9];
+ EFI_STATUS Status;
+
+ UnicodeSPrint (BootVariableName, 9 * sizeof(CHAR16), L"Boot%04X", LoadOptionIndex);
+
+ Status = BootOptionFromLoadOptionVariable (BootVariableName, BdsLoadOption);
+ if (!EFI_ERROR(Status)) {
+ (*BdsLoadOption)->LoadOptionIndex = LoadOptionIndex;
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+BootOptionToLoadOptionVariable (
+ IN BDS_LOAD_OPTION* BdsLoadOption
+ )
+{
+ EFI_STATUS Status;
+ UINTN DescriptionSize;
+ //UINT16 FilePathListLength;
+ EFI_DEVICE_PATH_PROTOCOL* DevicePathNode;
+ UINTN NodeLength;
+ UINT8* EfiLoadOptionPtr;
+ VOID* OldLoadOption;
+ CHAR16 BootVariableName[9];
+ UINTN BootOrderSize;
+ UINT16* BootOrder;
+
+ // If we are overwriting an existent Boot Option then we have to free previously allocated memory
+ if (BdsLoadOption->LoadOptionSize > 0) {
+ OldLoadOption = BdsLoadOption->LoadOption;
+ } else {
+ OldLoadOption = NULL;
+
+ // If this function is called at the creation of the Boot Device entry (not at the update) the
+ // BootOption->LoadOptionSize must be zero then we get a new BootIndex for this entry
+ BdsLoadOption->LoadOptionIndex = BootOptionAllocateBootIndex ();
+
+ //TODO: Add to the the Boot Entry List
+ }
+
+ DescriptionSize = StrSize(BdsLoadOption->Description);
+
+ // Ensure the FilePathListLength information is correct
+ ASSERT (GetDevicePathSize (BdsLoadOption->FilePathList) == BdsLoadOption->FilePathListLength);
+
+ // Allocate the memory for the EFI Load Option
+ BdsLoadOption->LoadOptionSize = sizeof(UINT32) + sizeof(UINT16) + DescriptionSize + BdsLoadOption->FilePathListLength + BdsLoadOption->OptionalDataSize;
+
+ BdsLoadOption->LoadOption = (EFI_LOAD_OPTION)AllocateZeroPool (BdsLoadOption->LoadOptionSize);
+ if (BdsLoadOption->LoadOption == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ EfiLoadOptionPtr = BdsLoadOption->LoadOption;
+
+ //
+ // Populate the EFI Load Option and BDS Boot Option structures
+ //
+
+ // Attributes fields
+ *(UINT32*)EfiLoadOptionPtr = BdsLoadOption->Attributes;
+ EfiLoadOptionPtr += sizeof(UINT32);
+
+ // FilePath List fields
+ *(UINT16*)EfiLoadOptionPtr = BdsLoadOption->FilePathListLength;
+ EfiLoadOptionPtr += sizeof(UINT16);
+
+ // Boot description fields
+ CopyMem (EfiLoadOptionPtr, BdsLoadOption->Description, DescriptionSize);
+ EfiLoadOptionPtr += DescriptionSize;
+
+ // File path fields
+ DevicePathNode = BdsLoadOption->FilePathList;
+ while (!IsDevicePathEndType (DevicePathNode)) {
+ NodeLength = DevicePathNodeLength(DevicePathNode);
+ CopyMem (EfiLoadOptionPtr, DevicePathNode, NodeLength);
+ EfiLoadOptionPtr += NodeLength;
+ DevicePathNode = NextDevicePathNode (DevicePathNode);
+ }
+
+ // Set the End Device Path Type
+ SetDevicePathEndNode (EfiLoadOptionPtr);
+ EfiLoadOptionPtr += sizeof(EFI_DEVICE_PATH);
+
+ // Fill the Optional Data
+ if (BdsLoadOption->OptionalDataSize > 0) {
+ CopyMem (EfiLoadOptionPtr, BdsLoadOption->OptionalData, BdsLoadOption->OptionalDataSize);
+ }
+
+ // Case where the fields have been updated
+ if (OldLoadOption) {
+ // Now, the old data has been copied to the new allocated packed structure, we need to update the pointers of BdsLoadOption
+ BootOptionParseLoadOption (BdsLoadOption->LoadOption, BdsLoadOption->LoadOptionSize, &BdsLoadOption);
+ // Free the old packed structure
+ FreePool (OldLoadOption);
+ }
+
+ // Create/Update Boot#### environment variable
+ UnicodeSPrint (BootVariableName, 9 * sizeof(CHAR16), L"Boot%04X", BdsLoadOption->LoadOptionIndex);
+ Status = gRT->SetVariable (
+ BootVariableName,
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ BdsLoadOption->LoadOptionSize,
+ BdsLoadOption->LoadOption
+ );
+
+ // When it is a new entry we must add the entry to the BootOrder
+ if (OldLoadOption == NULL) {
+ // Add the new Boot Index to the list
+ Status = GetEnvironmentVariable (L"BootOrder", NULL, &BootOrderSize, (VOID**)&BootOrder);
+ if (!EFI_ERROR(Status)) {
+ BootOrder = ReallocatePool (BootOrderSize, BootOrderSize + sizeof(UINT16), BootOrder);
+ // Add the new index at the end
+ BootOrder[BootOrderSize / sizeof(UINT16)] = BdsLoadOption->LoadOptionIndex;
+ BootOrderSize += sizeof(UINT16);
+ } else {
+ // BootOrder does not exist. Create it
+ BootOrderSize = sizeof(UINT16);
+ BootOrder = &(BdsLoadOption->LoadOptionIndex);
+ }
+
+ // Update (or Create) the BootOrder environment variable
+ gRT->SetVariable (
+ L"BootOrder",
+ &gEfiGlobalVariableGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ BootOrderSize,
+ BootOrder
+ );
+ DEBUG((EFI_D_ERROR,"Create %s\n",BootVariableName));
+
+ // Free memory allocated by GetEnvironmentVariable
+ if (!EFI_ERROR(Status)) {
+ FreePool (BootOrder);
+ }
+ } else {
+ DEBUG((EFI_D_ERROR,"Update %s\n",BootVariableName));
+ }
+
+ return EFI_SUCCESS;
+}
+
+UINT16
+BootOptionAllocateBootIndex (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ UINT32 BootIndex;
+ UINT16 *BootOrder;
+ UINTN BootOrderSize;
+ BOOLEAN Found;
+
+ // Get the Boot Option Order from the environment variable
+ Status = GetEnvironmentVariable (L"BootOrder", NULL, &BootOrderSize, (VOID**)&BootOrder);
+ if (!EFI_ERROR(Status)) {
+ for (BootIndex = 0; BootIndex <= 0xFFFF; BootIndex++) {
+ Found = FALSE;
+ for (Index = 0; Index < BootOrderSize / sizeof (UINT16); Index++) {
+ if (BootOrder[Index] == BootIndex) {
+ Found = TRUE;
+ break;
+ }
+ }
+ if (!Found) {
+ return BootIndex;
+ }
+ }
+ FreePool (BootOrder);
+ }
+ // Return the first index
+ return 0;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/Llvm_int_lib.h b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/Llvm_int_lib.h
index eb0a65062..6e42dcd14 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/Llvm_int_lib.h
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/Llvm_int_lib.h
@@ -1,99 +1,99 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-#include <Base.h>
-#include <Library/DebugLib.h>
-
-#define CHAR_BIT 8
-
-typedef union {
- INT64 all;
- struct {
- UINT32 low;
- INT32 high;
- };
-} dwords;
-
-typedef union {
- UINT64 all;
- struct {
- UINT32 low;
- UINT32 high;
- };
-} udwords;
-
-// __aeabi_ return values
-typedef struct {
- UINT64 Quotent;
- UINT64 Remainder;
-} ulldiv_t;
-
-typedef struct {
- INT64 Quotent;
- INT64 Remainder;
-} lldiv_t;
-
-typedef struct {
- UINT32 Quotent;
- UINT32 Remainder;
-} uidiv_return;
-
-#if __GNUC__
- #define COUNT_LEADING_ZEROS(_a) __builtin_clz((_a))
- #define COUNT_TRAILING_ZEROS(_a) __builtin_ctz((_a))
-#else
-#error COUNT_LEADING_ZEROS() and COUNT_TRAILING_ZEROS() macros not ported to your compiler
-#endif
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+#include <Base.h>
+#include <Library/DebugLib.h>
+
+#define CHAR_BIT 8
+
+typedef union {
+ INT64 all;
+ struct {
+ UINT32 low;
+ INT32 high;
+ };
+} dwords;
+
+typedef union {
+ UINT64 all;
+ struct {
+ UINT32 low;
+ UINT32 high;
+ };
+} udwords;
+
+// __aeabi_ return values
+typedef struct {
+ UINT64 Quotent;
+ UINT64 Remainder;
+} ulldiv_t;
+
+typedef struct {
+ INT64 Quotent;
+ INT64 Remainder;
+} lldiv_t;
+
+typedef struct {
+ UINT32 Quotent;
+ UINT32 Remainder;
+} uidiv_return;
+
+#if __GNUC__
+ #define COUNT_LEADING_ZEROS(_a) __builtin_clz((_a))
+ #define COUNT_TRAILING_ZEROS(_a) __builtin_ctz((_a))
+#else
+#error COUNT_LEADING_ZEROS() and COUNT_TRAILING_ZEROS() macros not ported to your compiler
+#endif
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.S
index 557879712..cec0c55f1 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.S
@@ -1,35 +1,35 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__ashldi3)
-
-ASM_PFX(__ashldi3):
- cmp r2, #31
- bls L2
- cmp r2, #63
- subls r2, r2, #32
- movls r2, r0, asl r2
- movhi r2, #0
- mov r1, r2
- mov r0, #0
- bx lr
-L2:
- cmp r2, #0
- rsbne r3, r2, #32
- movne r3, r0, lsr r3
- movne r0, r0, asl r2
- orrne r1, r3, r1, asl r2
- bx lr
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__ashldi3)
+
+ASM_PFX(__ashldi3):
+ cmp r2, #31
+ bls L2
+ cmp r2, #63
+ subls r2, r2, #32
+ movls r2, r0, asl r2
+ movhi r2, #0
+ mov r1, r2
+ mov r0, #0
+ bx lr
+L2:
+ cmp r2, #0
+ rsbne r3, r2, #32
+ movne r3, r0, lsr r3
+ movne r0, r0, asl r2
+ orrne r1, r3, r1, asl r2
+ bx lr
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.c
index 80ec5a600..526fcab65 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashldi3.c
@@ -1,83 +1,83 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-#include "Llvm_int_lib.h"
-
-// Returns: a << b
-
-// Precondition: 0 <= b < bits_in_dword
-
-INT64
-__ashldi3(INT64 a, INT32 b)
-{
- const int bits_in_word = (int)(sizeof(INT32) * CHAR_BIT);
- dwords input;
- dwords result;
- input.all = a;
- if (b & bits_in_word) // bits_in_word <= b < bits_in_dword
- {
- result.low = 0;
- result.high = input.low << (b - bits_in_word);
- }
- else // 0 <= b < bits_in_word
- {
- if (b == 0)
- return a;
- result.low = input.low << b;
- result.high = (input.high << b) | (input.low >> (bits_in_word - b));
- }
- return result.all;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+#include "Llvm_int_lib.h"
+
+// Returns: a << b
+
+// Precondition: 0 <= b < bits_in_dword
+
+INT64
+__ashldi3(INT64 a, INT32 b)
+{
+ const int bits_in_word = (int)(sizeof(INT32) * CHAR_BIT);
+ dwords input;
+ dwords result;
+ input.all = a;
+ if (b & bits_in_word) // bits_in_word <= b < bits_in_dword
+ {
+ result.low = 0;
+ result.high = input.low << (b - bits_in_word);
+ }
+ else // 0 <= b < bits_in_word
+ {
+ if (b == 0)
+ return a;
+ result.low = input.low << b;
+ result.high = (input.high << b) | (input.low >> (bits_in_word - b));
+ }
+ return result.all;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.S
index defd1f081..09c927ca6 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.S
@@ -1,36 +1,36 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__ashrdi3)
-
-ASM_PFX(__ashrdi3):
- cmp r2, #31
- bls L2
- cmp r2, #63
- subls r2, r2, #32
- mov ip, r1, asr #31
- movls r2, r1, asr r2
- movhi r2, ip
- mov r0, r2
- mov r1, ip
- bx lr
-L2:
- cmp r2, #0
- rsbne r3, r2, #32
- movne r3, r1, asl r3
- movne r1, r1, asr r2
- orrne r0, r3, r0, lsr r2
- bx lr
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__ashrdi3)
+
+ASM_PFX(__ashrdi3):
+ cmp r2, #31
+ bls L2
+ cmp r2, #63
+ subls r2, r2, #32
+ mov ip, r1, asr #31
+ movls r2, r1, asr r2
+ movhi r2, ip
+ mov r0, r2
+ mov r1, ip
+ bx lr
+L2:
+ cmp r2, #0
+ rsbne r3, r2, #32
+ movne r3, r1, asl r3
+ movne r1, r1, asr r2
+ orrne r0, r3, r0, lsr r2
+ bx lr
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.c
index 703a37fd7..229531ed2 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ashrdi3.c
@@ -1,84 +1,84 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-#include "Llvm_int_lib.h"
-
-// Returns: arithmetic a >> b
-
-// Precondition: 0 <= b < bits_in_dword
-
-INT64
-__ashrdi3(INT64 a, INT32 b)
-{
- const int bits_in_word = (int)(sizeof(INT32) * CHAR_BIT);
- dwords input;
- dwords result;
- input.all = a;
- if (b & bits_in_word) // bits_in_word <= b < bits_in_dword
- {
- // result.high = input.high < 0 ? -1 : 0
- result.high = input.high >> (bits_in_word - 1);
- result.low = input.high >> (b - bits_in_word);
- }
- else // 0 <= b < bits_in_word
- {
- if (b == 0)
- return a;
- result.high = input.high >> b;
- result.low = (input.high << (bits_in_word - b)) | (input.low >> b);
- }
- return result.all;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+#include "Llvm_int_lib.h"
+
+// Returns: arithmetic a >> b
+
+// Precondition: 0 <= b < bits_in_dword
+
+INT64
+__ashrdi3(INT64 a, INT32 b)
+{
+ const int bits_in_word = (int)(sizeof(INT32) * CHAR_BIT);
+ dwords input;
+ dwords result;
+ input.all = a;
+ if (b & bits_in_word) // bits_in_word <= b < bits_in_dword
+ {
+ // result.high = input.high < 0 ? -1 : 0
+ result.high = input.high >> (bits_in_word - 1);
+ result.low = input.high >> (b - bits_in_word);
+ }
+ else // 0 <= b < bits_in_word
+ {
+ if (b == 0)
+ return a;
+ result.high = input.high >> b;
+ result.low = (input.high << (bits_in_word - b)) | (input.low >> b);
+ }
+ return result.all;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.S
index 11ea95cef..942344674 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.S
@@ -1,57 +1,57 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__clzsi2)
-
-ASM_PFX(__clzsi2):
- @ frame_needed = 1, uses_anonymous_args = 0
- stmfd sp!, {r7, lr}
- add r7, sp, #0
- movs r3, r0, lsr #16
- movne r3, #16
- moveq r3, #0
- movne r9, #0
- moveq r9, #16
- mov r3, r0, lsr r3
- tst r3, #65280
- movne r0, #8
- moveq r0, #0
- movne lr, #0
- moveq lr, #8
- mov r3, r3, lsr r0
- tst r3, #240
- movne r0, #4
- moveq r0, #0
- movne ip, #0
- moveq ip, #4
- mov r3, r3, lsr r0
- tst r3, #12
- movne r0, #2
- moveq r0, #0
- movne r1, #0
- moveq r1, #2
- mov r2, r3, lsr r0
- add r3, lr, r9
- add r0, r3, ip
- add r1, r0, r1
- mov r0, r2, lsr #1
- eor r0, r0, #1
- ands r0, r0, #1
- mvnne r0, #0
- rsb r3, r2, #2
- and r0, r0, r3
- add r0, r1, r0
- ldmfd sp!, {r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__clzsi2)
+
+ASM_PFX(__clzsi2):
+ @ frame_needed = 1, uses_anonymous_args = 0
+ stmfd sp!, {r7, lr}
+ add r7, sp, #0
+ movs r3, r0, lsr #16
+ movne r3, #16
+ moveq r3, #0
+ movne r9, #0
+ moveq r9, #16
+ mov r3, r0, lsr r3
+ tst r3, #65280
+ movne r0, #8
+ moveq r0, #0
+ movne lr, #0
+ moveq lr, #8
+ mov r3, r3, lsr r0
+ tst r3, #240
+ movne r0, #4
+ moveq r0, #0
+ movne ip, #0
+ moveq ip, #4
+ mov r3, r3, lsr r0
+ tst r3, #12
+ movne r0, #2
+ moveq r0, #0
+ movne r1, #0
+ moveq r1, #2
+ mov r2, r3, lsr r0
+ add r3, lr, r9
+ add r0, r3, ip
+ add r1, r0, r1
+ mov r0, r2, lsr #1
+ eor r0, r0, #1
+ ands r0, r0, #1
+ mvnne r0, #0
+ rsb r3, r2, #2
+ and r0, r0, r3
+ add r0, r1, r0
+ ldmfd sp!, {r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.c
index 196f23f8c..50ae87a6c 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/clzsi2.c
@@ -1,96 +1,96 @@
-/** @file
- Compiler intrinsic to return the number of leading zeros, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-// Returns: the number of leading 0-bits
-
-// Precondition: a != 0
-
-INT32
-__clzsi2(INT32 a)
-{
- UINT32 x = (UINT32)a;
- INT32 t = ((x & 0xFFFF0000) == 0) << 4; // if (x is small) t = 16 else 0
- x >>= 16 - t; // x = [0 - 0xFFFF]
- UINT32 r = t; // r = [0, 16]
- // return r + clz(x)
- t = ((x & 0xFF00) == 0) << 3;
- x >>= 8 - t; // x = [0 - 0xFF]
- r += t; // r = [0, 8, 16, 24]
- // return r + clz(x)
- t = ((x & 0xF0) == 0) << 2;
- x >>= 4 - t; // x = [0 - 0xF]
- r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]
- // return r + clz(x)
- t = ((x & 0xC) == 0) << 1;
- x >>= 2 - t; // x = [0 - 3]
- r += t; // r = [0 - 30] and is even
- // return r + clz(x)
-// switch (x)
-// {
-// case 0:
-// return r + 2;
-// case 1:
-// return r + 1;
-// case 2:
-// case 3:
-// return r;
-// }
- return r + ((2 - x) & -((x & 2) == 0));
-}
+/** @file
+ Compiler intrinsic to return the number of leading zeros, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+// Returns: the number of leading 0-bits
+
+// Precondition: a != 0
+
+INT32
+__clzsi2(INT32 a)
+{
+ UINT32 x = (UINT32)a;
+ INT32 t = ((x & 0xFFFF0000) == 0) << 4; // if (x is small) t = 16 else 0
+ x >>= 16 - t; // x = [0 - 0xFFFF]
+ UINT32 r = t; // r = [0, 16]
+ // return r + clz(x)
+ t = ((x & 0xFF00) == 0) << 3;
+ x >>= 8 - t; // x = [0 - 0xFF]
+ r += t; // r = [0, 8, 16, 24]
+ // return r + clz(x)
+ t = ((x & 0xF0) == 0) << 2;
+ x >>= 4 - t; // x = [0 - 0xF]
+ r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]
+ // return r + clz(x)
+ t = ((x & 0xC) == 0) << 1;
+ x >>= 2 - t; // x = [0 - 3]
+ r += t; // r = [0 - 30] and is even
+ // return r + clz(x)
+// switch (x)
+// {
+// case 0:
+// return r + 2;
+// case 1:
+// return r + 1;
+// case 2:
+// case 3:
+// return r;
+// }
+ return r + ((2 - x) & -((x & 2) == 0));
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.S
index 0c8e78d96..d530025a1 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.S
@@ -1,49 +1,49 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__ctzsi2)
-
-ASM_PFX(__ctzsi2):
- uxth r3, r0
- cmp r3, #0
- moveq ip, #16
- movne ip, #0
- @ lr needed for prologue
- mov r0, r0, lsr ip
- tst r0, #255
- movne r3, #0
- moveq r3, #8
- mov r0, r0, lsr r3
- tst r0, #15
- movne r1, #0
- moveq r1, #4
- add r3, r3, ip
- mov r0, r0, lsr r1
- tst r0, #3
- movne r2, #0
- moveq r2, #2
- add r3, r3, r1
- mov r0, r0, lsr r2
- and r0, r0, #3
- add r2, r3, r2
- eor r3, r0, #1
- mov r0, r0, lsr #1
- ands r3, r3, #1
- mvnne r3, #0
- rsb r0, r0, #2
- and r0, r3, r0
- add r0, r2, r0
- bx lr
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__ctzsi2)
+
+ASM_PFX(__ctzsi2):
+ uxth r3, r0
+ cmp r3, #0
+ moveq ip, #16
+ movne ip, #0
+ @ lr needed for prologue
+ mov r0, r0, lsr ip
+ tst r0, #255
+ movne r3, #0
+ moveq r3, #8
+ mov r0, r0, lsr r3
+ tst r0, #15
+ movne r1, #0
+ moveq r1, #4
+ add r3, r3, ip
+ mov r0, r0, lsr r1
+ tst r0, #3
+ movne r2, #0
+ moveq r2, #2
+ add r3, r3, r1
+ mov r0, r0, lsr r2
+ and r0, r0, #3
+ add r2, r3, r2
+ eor r3, r0, #1
+ mov r0, r0, lsr #1
+ ands r3, r3, #1
+ mvnne r3, #0
+ rsb r0, r0, #2
+ and r0, r3, r0
+ add r0, r2, r0
+ bx lr
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.c
index 425d8b9e4..71f303b34 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ctzsi2.c
@@ -1,98 +1,98 @@
-/** @file
- Compiler intrinsic to return the number of trailing zeros, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-// Returns: the number of trailing 0-bits
-
-// Precondition: a != 0
-
-INT32
-__ctzsi2(INT32 a)
-{
- UINT32 x = (UINT32)a;
- INT32 t = ((x & 0x0000FFFF) == 0) << 4; // if (x has no small bits) t = 16 else 0
- x >>= t; // x = [0 - 0xFFFF] + higher garbage bits
- UINT32 r = t; // r = [0, 16]
- // return r + ctz(x)
- t = ((x & 0x00FF) == 0) << 3;
- x >>= t; // x = [0 - 0xFF] + higher garbage bits
- r += t; // r = [0, 8, 16, 24]
- // return r + ctz(x)
- t = ((x & 0x0F) == 0) << 2;
- x >>= t; // x = [0 - 0xF] + higher garbage bits
- r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]
- // return r + ctz(x)
- t = ((x & 0x3) == 0) << 1;
- x >>= t;
- x &= 3; // x = [0 - 3]
- r += t; // r = [0 - 30] and is even
- // return r + ctz(x)
-// The branch-less return statement below is equivalent
-// to the following switch statement:
-// switch (x)
-// {
-// case 0:
-// return r + 2;
-// case 2:
-// return r + 1;
-// case 1:
-// case 3:
-// return r;
-// }
- return r + ((2 - (x >> 1)) & -((x & 1) == 0));
-}
+/** @file
+ Compiler intrinsic to return the number of trailing zeros, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+// Returns: the number of trailing 0-bits
+
+// Precondition: a != 0
+
+INT32
+__ctzsi2(INT32 a)
+{
+ UINT32 x = (UINT32)a;
+ INT32 t = ((x & 0x0000FFFF) == 0) << 4; // if (x has no small bits) t = 16 else 0
+ x >>= t; // x = [0 - 0xFFFF] + higher garbage bits
+ UINT32 r = t; // r = [0, 16]
+ // return r + ctz(x)
+ t = ((x & 0x00FF) == 0) << 3;
+ x >>= t; // x = [0 - 0xFF] + higher garbage bits
+ r += t; // r = [0, 8, 16, 24]
+ // return r + ctz(x)
+ t = ((x & 0x0F) == 0) << 2;
+ x >>= t; // x = [0 - 0xF] + higher garbage bits
+ r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]
+ // return r + ctz(x)
+ t = ((x & 0x3) == 0) << 1;
+ x >>= t;
+ x &= 3; // x = [0 - 3]
+ r += t; // r = [0 - 30] and is even
+ // return r + ctz(x)
+// The branch-less return statement below is equivalent
+// to the following switch statement:
+// switch (x)
+// {
+// case 0:
+// return r + 2;
+// case 2:
+// return r + 1;
+// case 1:
+// case 3:
+// return r;
+// }
+ return r + ((2 - (x >> 1)) & -((x & 1) == 0));
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.S
index 3534eaba2..faf70dbf4 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.S
@@ -1,153 +1,153 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2011, ARM. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-.text
-.align 2
-GCC_ASM_EXPORT(__aeabi_uidiv)
-GCC_ASM_EXPORT(__aeabi_uidivmod)
-GCC_ASM_EXPORT(__aeabi_idiv)
-GCC_ASM_EXPORT(__aeabi_idivmod)
-
-# AREA Math, CODE, READONLY
-
-#
-#UINT32
-#EFIAPI
-#__aeabi_uidivmode (
-# IN UINT32 Dividen
-# IN UINT32 Divisor
-# );
-#
-
-ASM_PFX(__aeabi_uidiv):
-ASM_PFX(__aeabi_uidivmod):
- rsbs r12, r1, r0, LSR #4
- mov r2, #0
- bcc ASM_PFX(__arm_div4)
- rsbs r12, r1, r0, LSR #8
- bcc ASM_PFX(__arm_div8)
- mov r3, #0
- b ASM_PFX(__arm_div_large)
-
-#
-#INT32
-#EFIAPI
-#__aeabi_idivmode (
-# IN INT32 Dividen
-# IN INT32 Divisor
-# );
-#
-ASM_PFX(__aeabi_idiv):
-ASM_PFX(__aeabi_idivmod):
- orrs r12, r0, r1
- bmi ASM_PFX(__arm_div_negative)
- rsbs r12, r1, r0, LSR #1
- mov r2, #0
- bcc ASM_PFX(__arm_div1)
- rsbs r12, r1, r0, LSR #4
- bcc ASM_PFX(__arm_div4)
- rsbs r12, r1, r0, LSR #8
- bcc ASM_PFX(__arm_div8)
- mov r3, #0
- b ASM_PFX(__arm_div_large)
-ASM_PFX(__arm_div8):
- rsbs r12, r1, r0, LSR #7
- subcs r0, r0, r1, LSL #7
- adc r2, r2, r2
- rsbs r12, r1, r0,LSR #6
- subcs r0, r0, r1, LSL #6
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #5
- subcs r0, r0, r1, LSL #5
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #4
- subcs r0, r0, r1, LSL #4
- adc r2, r2, r2
-ASM_PFX(__arm_div4):
- rsbs r12, r1, r0, LSR #3
- subcs r0, r0, r1, LSL #3
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #2
- subcs r0, r0, r1, LSL #2
- adcs r2, r2, r2
- rsbs r12, r1, r0, LSR #1
- subcs r0, r0, r1, LSL #1
- adc r2, r2, r2
-ASM_PFX(__arm_div1):
- subs r1, r0, r1
- movcc r1, r0
- adc r0, r2, r2
- bx r14
-ASM_PFX(__arm_div_negative):
- ands r2, r1, #0x80000000
- rsbmi r1, r1, #0
- eors r3, r2, r0, ASR #32
- rsbcs r0, r0, #0
- rsbs r12, r1, r0, LSR #4
- bcc label1
- rsbs r12, r1, r0, LSR #8
- bcc label2
-ASM_PFX(__arm_div_large):
- lsl r1, r1, #6
- rsbs r12, r1, r0, LSR #8
- orr r2, r2, #0xfc000000
- bcc label2
- lsl r1, r1, #6
- rsbs r12, r1, r0, LSR #8
- orr r2, r2, #0x3f00000
- bcc label2
- lsl r1, r1, #6
- rsbs r12, r1, r0, LSR #8
- orr r2, r2, #0xfc000
- orrcs r2, r2, #0x3f00
- lslcs r1, r1, #6
- rsbs r12, r1, #0
- bcs ASM_PFX(__aeabi_idiv0)
-label3:
- lsrcs r1, r1, #6
-label2:
- rsbs r12, r1, r0, LSR #7
- subcs r0, r0, r1, LSL #7
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #6
- subcs r0, r0, r1, LSL #6
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #5
- subcs r0, r0, r1, LSL #5
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #4
- subcs r0, r0, r1, LSL #4
- adc r2, r2, r2
-label1:
- rsbs r12, r1, r0, LSR #3
- subcs r0, r0, r1, LSL #3
- adc r2, r2, r2
- rsbs r12, r1, r0, LSR #2
- subcs r0, r0, r1, LSL #2
- adcs r2, r2, r2
- bcs label3
- rsbs r12, r1, r0, LSR #1
- subcs r0, r0, r1, LSL #1
- adc r2, r2, r2
- subs r1, r0, r1
- movcc r1, r0
- adc r0, r2, r2
- asrs r3, r3, #31
- rsbmi r0, r0, #0
- rsbcs r1, r1, #0
- bx r14
-
- @ What to do about division by zero? For now, just return.
-ASM_PFX(__aeabi_idiv0):
- bx r14
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2011, ARM. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+.text
+.align 2
+GCC_ASM_EXPORT(__aeabi_uidiv)
+GCC_ASM_EXPORT(__aeabi_uidivmod)
+GCC_ASM_EXPORT(__aeabi_idiv)
+GCC_ASM_EXPORT(__aeabi_idivmod)
+
+# AREA Math, CODE, READONLY
+
+#
+#UINT32
+#EFIAPI
+#__aeabi_uidivmode (
+# IN UINT32 Dividen
+# IN UINT32 Divisor
+# );
+#
+
+ASM_PFX(__aeabi_uidiv):
+ASM_PFX(__aeabi_uidivmod):
+ rsbs r12, r1, r0, LSR #4
+ mov r2, #0
+ bcc ASM_PFX(__arm_div4)
+ rsbs r12, r1, r0, LSR #8
+ bcc ASM_PFX(__arm_div8)
+ mov r3, #0
+ b ASM_PFX(__arm_div_large)
+
+#
+#INT32
+#EFIAPI
+#__aeabi_idivmode (
+# IN INT32 Dividen
+# IN INT32 Divisor
+# );
+#
+ASM_PFX(__aeabi_idiv):
+ASM_PFX(__aeabi_idivmod):
+ orrs r12, r0, r1
+ bmi ASM_PFX(__arm_div_negative)
+ rsbs r12, r1, r0, LSR #1
+ mov r2, #0
+ bcc ASM_PFX(__arm_div1)
+ rsbs r12, r1, r0, LSR #4
+ bcc ASM_PFX(__arm_div4)
+ rsbs r12, r1, r0, LSR #8
+ bcc ASM_PFX(__arm_div8)
+ mov r3, #0
+ b ASM_PFX(__arm_div_large)
+ASM_PFX(__arm_div8):
+ rsbs r12, r1, r0, LSR #7
+ subcs r0, r0, r1, LSL #7
+ adc r2, r2, r2
+ rsbs r12, r1, r0,LSR #6
+ subcs r0, r0, r1, LSL #6
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #5
+ subcs r0, r0, r1, LSL #5
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #4
+ subcs r0, r0, r1, LSL #4
+ adc r2, r2, r2
+ASM_PFX(__arm_div4):
+ rsbs r12, r1, r0, LSR #3
+ subcs r0, r0, r1, LSL #3
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #2
+ subcs r0, r0, r1, LSL #2
+ adcs r2, r2, r2
+ rsbs r12, r1, r0, LSR #1
+ subcs r0, r0, r1, LSL #1
+ adc r2, r2, r2
+ASM_PFX(__arm_div1):
+ subs r1, r0, r1
+ movcc r1, r0
+ adc r0, r2, r2
+ bx r14
+ASM_PFX(__arm_div_negative):
+ ands r2, r1, #0x80000000
+ rsbmi r1, r1, #0
+ eors r3, r2, r0, ASR #32
+ rsbcs r0, r0, #0
+ rsbs r12, r1, r0, LSR #4
+ bcc label1
+ rsbs r12, r1, r0, LSR #8
+ bcc label2
+ASM_PFX(__arm_div_large):
+ lsl r1, r1, #6
+ rsbs r12, r1, r0, LSR #8
+ orr r2, r2, #0xfc000000
+ bcc label2
+ lsl r1, r1, #6
+ rsbs r12, r1, r0, LSR #8
+ orr r2, r2, #0x3f00000
+ bcc label2
+ lsl r1, r1, #6
+ rsbs r12, r1, r0, LSR #8
+ orr r2, r2, #0xfc000
+ orrcs r2, r2, #0x3f00
+ lslcs r1, r1, #6
+ rsbs r12, r1, #0
+ bcs ASM_PFX(__aeabi_idiv0)
+label3:
+ lsrcs r1, r1, #6
+label2:
+ rsbs r12, r1, r0, LSR #7
+ subcs r0, r0, r1, LSL #7
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #6
+ subcs r0, r0, r1, LSL #6
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #5
+ subcs r0, r0, r1, LSL #5
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #4
+ subcs r0, r0, r1, LSL #4
+ adc r2, r2, r2
+label1:
+ rsbs r12, r1, r0, LSR #3
+ subcs r0, r0, r1, LSL #3
+ adc r2, r2, r2
+ rsbs r12, r1, r0, LSR #2
+ subcs r0, r0, r1, LSL #2
+ adcs r2, r2, r2
+ bcs label3
+ rsbs r12, r1, r0, LSR #1
+ subcs r0, r0, r1, LSL #1
+ adc r2, r2, r2
+ subs r1, r0, r1
+ movcc r1, r0
+ adc r0, r2, r2
+ asrs r3, r3, #31
+ rsbmi r0, r0, #0
+ rsbcs r1, r1, #0
+ bx r14
+
+ @ What to do about division by zero? For now, just return.
+ASM_PFX(__aeabi_idiv0):
+ bx r14
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.asm
index e38105dd6..13f701358 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/div.asm
@@ -1,155 +1,155 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_uidiv
- EXPORT __aeabi_uidivmod
- EXPORT __aeabi_idiv
- EXPORT __aeabi_idivmod
-
- AREA Math, CODE, READONLY
-
-;
-;UINT32
-;EFIAPI
-;__aeabi_uidivmode (
-; IN UINT32 Dividen
-; IN UINT32 Divisor
-; );
-;
-
-__aeabi_uidiv
-__aeabi_uidivmod
- RSBS r12, r1, r0, LSR #4
- MOV r2, #0
- BCC __arm_div4
- RSBS r12, r1, r0, LSR #8
- BCC __arm_div8
- MOV r3, #0
- B __arm_div_large
-
-;
-;INT32
-;EFIAPI
-;__aeabi_idivmode (
-; IN INT32 Dividen
-; IN INT32 Divisor
-; );
-;
-__aeabi_idiv
-__aeabi_idivmod
- ORRS r12, r0, r1
- BMI __arm_div_negative
- RSBS r12, r1, r0, LSR #1
- MOV r2, #0
- BCC __arm_div1
- RSBS r12, r1, r0, LSR #4
- BCC __arm_div4
- RSBS r12, r1, r0, LSR #8
- BCC __arm_div8
- MOV r3, #0
- B __arm_div_large
-__arm_div8
- RSBS r12, r1, r0, LSR #7
- SUBCS r0, r0, r1, LSL #7
- ADC r2, r2, r2
- RSBS r12, r1, r0,LSR #6
- SUBCS r0, r0, r1, LSL #6
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #5
- SUBCS r0, r0, r1, LSL #5
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #4
- SUBCS r0, r0, r1, LSL #4
- ADC r2, r2, r2
-__arm_div4
- RSBS r12, r1, r0, LSR #3
- SUBCS r0, r0, r1, LSL #3
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #2
- SUBCS r0, r0, r1, LSL #2
- ADCS r2, r2, r2
- RSBS r12, r1, r0, LSR #1
- SUBCS r0, r0, r1, LSL #1
- ADC r2, r2, r2
-__arm_div1
- SUBS r1, r0, r1
- MOVCC r1, r0
- ADC r0, r2, r2
- BX r14
-__arm_div_negative
- ANDS r2, r1, #0x80000000
- RSBMI r1, r1, #0
- EORS r3, r2, r0, ASR #32
- RSBCS r0, r0, #0
- RSBS r12, r1, r0, LSR #4
- BCC label1
- RSBS r12, r1, r0, LSR #8
- BCC label2
-__arm_div_large
- LSL r1, r1, #6
- RSBS r12, r1, r0, LSR #8
- ORR r2, r2, #0xfc000000
- BCC label2
- LSL r1, r1, #6
- RSBS r12, r1, r0, LSR #8
- ORR r2, r2, #0x3f00000
- BCC label2
- LSL r1, r1, #6
- RSBS r12, r1, r0, LSR #8
- ORR r2, r2, #0xfc000
- ORRCS r2, r2, #0x3f00
- LSLCS r1, r1, #6
- RSBS r12, r1, #0
- BCS __aeabi_idiv0
-label3
- LSRCS r1, r1, #6
-label2
- RSBS r12, r1, r0, LSR #7
- SUBCS r0, r0, r1, LSL #7
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #6
- SUBCS r0, r0, r1, LSL #6
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #5
- SUBCS r0, r0, r1, LSL #5
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #4
- SUBCS r0, r0, r1, LSL #4
- ADC r2, r2, r2
-label1
- RSBS r12, r1, r0, LSR #3
- SUBCS r0, r0, r1, LSL #3
- ADC r2, r2, r2
- RSBS r12, r1, r0, LSR #2
- SUBCS r0, r0, r1, LSL #2
- ADCS r2, r2, r2
- BCS label3
- RSBS r12, r1, r0, LSR #1
- SUBCS r0, r0, r1, LSL #1
- ADC r2, r2, r2
- SUBS r1, r0, r1
- MOVCC r1, r0
- ADC r0, r2, r2
- ASRS r3, r3, #31
- RSBMI r0, r0, #0
- RSBCS r1, r1, #0
- BX r14
-
- ; What to do about division by zero? For now, just return.
-__aeabi_idiv0
- BX r14
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_uidiv
+ EXPORT __aeabi_uidivmod
+ EXPORT __aeabi_idiv
+ EXPORT __aeabi_idivmod
+
+ AREA Math, CODE, READONLY
+
+;
+;UINT32
+;EFIAPI
+;__aeabi_uidivmode (
+; IN UINT32 Dividen
+; IN UINT32 Divisor
+; );
+;
+
+__aeabi_uidiv
+__aeabi_uidivmod
+ RSBS r12, r1, r0, LSR #4
+ MOV r2, #0
+ BCC __arm_div4
+ RSBS r12, r1, r0, LSR #8
+ BCC __arm_div8
+ MOV r3, #0
+ B __arm_div_large
+
+;
+;INT32
+;EFIAPI
+;__aeabi_idivmode (
+; IN INT32 Dividen
+; IN INT32 Divisor
+; );
+;
+__aeabi_idiv
+__aeabi_idivmod
+ ORRS r12, r0, r1
+ BMI __arm_div_negative
+ RSBS r12, r1, r0, LSR #1
+ MOV r2, #0
+ BCC __arm_div1
+ RSBS r12, r1, r0, LSR #4
+ BCC __arm_div4
+ RSBS r12, r1, r0, LSR #8
+ BCC __arm_div8
+ MOV r3, #0
+ B __arm_div_large
+__arm_div8
+ RSBS r12, r1, r0, LSR #7
+ SUBCS r0, r0, r1, LSL #7
+ ADC r2, r2, r2
+ RSBS r12, r1, r0,LSR #6
+ SUBCS r0, r0, r1, LSL #6
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #5
+ SUBCS r0, r0, r1, LSL #5
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #4
+ SUBCS r0, r0, r1, LSL #4
+ ADC r2, r2, r2
+__arm_div4
+ RSBS r12, r1, r0, LSR #3
+ SUBCS r0, r0, r1, LSL #3
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #2
+ SUBCS r0, r0, r1, LSL #2
+ ADCS r2, r2, r2
+ RSBS r12, r1, r0, LSR #1
+ SUBCS r0, r0, r1, LSL #1
+ ADC r2, r2, r2
+__arm_div1
+ SUBS r1, r0, r1
+ MOVCC r1, r0
+ ADC r0, r2, r2
+ BX r14
+__arm_div_negative
+ ANDS r2, r1, #0x80000000
+ RSBMI r1, r1, #0
+ EORS r3, r2, r0, ASR #32
+ RSBCS r0, r0, #0
+ RSBS r12, r1, r0, LSR #4
+ BCC label1
+ RSBS r12, r1, r0, LSR #8
+ BCC label2
+__arm_div_large
+ LSL r1, r1, #6
+ RSBS r12, r1, r0, LSR #8
+ ORR r2, r2, #0xfc000000
+ BCC label2
+ LSL r1, r1, #6
+ RSBS r12, r1, r0, LSR #8
+ ORR r2, r2, #0x3f00000
+ BCC label2
+ LSL r1, r1, #6
+ RSBS r12, r1, r0, LSR #8
+ ORR r2, r2, #0xfc000
+ ORRCS r2, r2, #0x3f00
+ LSLCS r1, r1, #6
+ RSBS r12, r1, #0
+ BCS __aeabi_idiv0
+label3
+ LSRCS r1, r1, #6
+label2
+ RSBS r12, r1, r0, LSR #7
+ SUBCS r0, r0, r1, LSL #7
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #6
+ SUBCS r0, r0, r1, LSL #6
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #5
+ SUBCS r0, r0, r1, LSL #5
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #4
+ SUBCS r0, r0, r1, LSL #4
+ ADC r2, r2, r2
+label1
+ RSBS r12, r1, r0, LSR #3
+ SUBCS r0, r0, r1, LSL #3
+ ADC r2, r2, r2
+ RSBS r12, r1, r0, LSR #2
+ SUBCS r0, r0, r1, LSL #2
+ ADCS r2, r2, r2
+ BCS label3
+ RSBS r12, r1, r0, LSR #1
+ SUBCS r0, r0, r1, LSL #1
+ ADC r2, r2, r2
+ SUBS r1, r0, r1
+ MOVCC r1, r0
+ ADC r0, r2, r2
+ ASRS r3, r3, #31
+ RSBMI r0, r0, #0
+ RSBCS r1, r1, #0
+ BX r14
+
+ ; What to do about division by zero? For now, just return.
+__aeabi_idiv0
+ BX r14
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.S
index 342f376bb..7be2e2886 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.S
@@ -1,49 +1,49 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__divdi3)
-
-ASM_PFX(__divdi3):
- @ args = 0, pretend = 0, frame = 0
- @ frame_needed = 1, uses_anonymous_args = 0
- stmfd sp!, {r4, r5, r7, lr}
- mov r4, r3, asr #31
- add r7, sp, #8
- stmfd sp!, {r10, r11}
- mov r10, r1, asr #31
- sub sp, sp, #8
- mov r11, r10
- mov r5, r4
- eor r0, r0, r10
- eor r1, r1, r10
- eor r2, r2, r4
- eor r3, r3, r4
- subs r2, r2, r4
- sbc r3, r3, r5
- mov ip, #0
- subs r0, r0, r10
- sbc r1, r1, r11
- str ip, [sp, #0]
- bl ASM_PFX(__udivmoddi4)
- eor r2, r10, r4
- eor r3, r10, r4
- eor r0, r0, r2
- eor r1, r1, r3
- subs r0, r0, r2
- sbc r1, r1, r3
- sub sp, r7, #16
- ldmfd sp!, {r10, r11}
- ldmfd sp!, {r4, r5, r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__divdi3)
+
+ASM_PFX(__divdi3):
+ @ args = 0, pretend = 0, frame = 0
+ @ frame_needed = 1, uses_anonymous_args = 0
+ stmfd sp!, {r4, r5, r7, lr}
+ mov r4, r3, asr #31
+ add r7, sp, #8
+ stmfd sp!, {r10, r11}
+ mov r10, r1, asr #31
+ sub sp, sp, #8
+ mov r11, r10
+ mov r5, r4
+ eor r0, r0, r10
+ eor r1, r1, r10
+ eor r2, r2, r4
+ eor r3, r3, r4
+ subs r2, r2, r4
+ sbc r3, r3, r5
+ mov ip, #0
+ subs r0, r0, r10
+ sbc r1, r1, r11
+ str ip, [sp, #0]
+ bl ASM_PFX(__udivmoddi4)
+ eor r2, r10, r4
+ eor r3, r10, r4
+ eor r0, r0, r2
+ eor r1, r1, r3
+ subs r0, r0, r2
+ sbc r1, r1, r3
+ sub sp, r7, #16
+ ldmfd sp!, {r10, r11}
+ ldmfd sp!, {r4, r5, r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.c
index 4d790b8f9..e86bd1361 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divdi3.c
@@ -1,77 +1,77 @@
-/** @file
- Compiler intrinsic for 64-bit compare, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-UINT64 __udivmoddi4(UINT64 a, UINT64 b, UINT64* rem);
-
-// Returns: a / b
-
-INT64
-__divdi3(INT64 a, INT64 b)
-{
- const int bits_in_dword_m1 = (int)(sizeof(INT64) * CHAR_BIT) - 1;
- INT64 s_a = a >> bits_in_dword_m1; // s_a = a < 0 ? -1 : 0
- INT64 s_b = b >> bits_in_dword_m1; // s_b = b < 0 ? -1 : 0
- a = (a ^ s_a) - s_a; // negate if s_a == -1
- b = (b ^ s_b) - s_b; // negate if s_b == -1
- s_a ^= s_b; // sign of quotient
- return (__udivmoddi4(a, b, (UINT64*)0) ^ s_a) - s_a; // negate if s_a == -1
-}
-
-
+/** @file
+ Compiler intrinsic for 64-bit compare, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+UINT64 __udivmoddi4(UINT64 a, UINT64 b, UINT64* rem);
+
+// Returns: a / b
+
+INT64
+__divdi3(INT64 a, INT64 b)
+{
+ const int bits_in_dword_m1 = (int)(sizeof(INT64) * CHAR_BIT) - 1;
+ INT64 s_a = a >> bits_in_dword_m1; // s_a = a < 0 ? -1 : 0
+ INT64 s_b = b >> bits_in_dword_m1; // s_b = b < 0 ? -1 : 0
+ a = (a ^ s_a) - s_a; // negate if s_a == -1
+ b = (b ^ s_b) - s_b; // negate if s_b == -1
+ s_a ^= s_b; // sign of quotient
+ return (__udivmoddi4(a, b, (UINT64*)0) ^ s_a) - s_a; // negate if s_a == -1
+}
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.S
index 3976fda14..b74cbb643 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.S
@@ -1,32 +1,32 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__divsi3)
-
-ASM_PFX(__divsi3):
- eor r3, r0, r0, asr #31
- eor r2, r1, r1, asr #31
- stmfd sp!, {r4, r5, r7, lr}
- mov r5, r0, asr #31
- add r7, sp, #8
- mov r4, r1, asr #31
- sub r0, r3, r0, asr #31
- sub r1, r2, r1, asr #31
- bl ASM_PFX(__udivsi3)
- eor r1, r5, r4
- eor r0, r0, r1
- rsb r0, r1, r0
- ldmfd sp!, {r4, r5, r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__divsi3)
+
+ASM_PFX(__divsi3):
+ eor r3, r0, r0, asr #31
+ eor r2, r1, r1, asr #31
+ stmfd sp!, {r4, r5, r7, lr}
+ mov r5, r0, asr #31
+ add r7, sp, #8
+ mov r4, r1, asr #31
+ sub r0, r3, r0, asr #31
+ sub r1, r2, r1, asr #31
+ bl ASM_PFX(__udivsi3)
+ eor r1, r5, r4
+ eor r0, r0, r1
+ rsb r0, r1, r0
+ ldmfd sp!, {r4, r5, r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c
index 4a19e15a3..b322f9a57 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/divsi3.c
@@ -1,78 +1,78 @@
-/** @file
- Compiler intrinsic for 32--bit unsigned division, ported from LLVM code.
-
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-UINT32 __udivsi3(UINT32 n, UINT32 d);
-
-// Returns: a / b
-
-INT32
-__divsi3(INT32 a, INT32 b)
-{
- const int bits_in_word_m1 = (int)(sizeof(INT32) * CHAR_BIT) - 1;
- INT32 s_a = a >> bits_in_word_m1; // s_a = a < 0 ? -1 : 0
- INT32 s_b = b >> bits_in_word_m1; // s_b = b < 0 ? -1 : 0
- a = (a ^ s_a) - s_a; // negate if s_a == -1
- b = (b ^ s_b) - s_b; // negate if s_b == -1
- s_a ^= s_b; // sign of quotient
- return (__udivsi3(a, b) ^ s_a) - s_a; // negate if s_a == -1
-}
-
-
+/** @file
+ Compiler intrinsic for 32--bit unsigned division, ported from LLVM code.
+
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+UINT32 __udivsi3(UINT32 n, UINT32 d);
+
+// Returns: a / b
+
+INT32
+__divsi3(INT32 a, INT32 b)
+{
+ const int bits_in_word_m1 = (int)(sizeof(INT32) * CHAR_BIT) - 1;
+ INT32 s_a = a >> bits_in_word_m1; // s_a = a < 0 ? -1 : 0
+ INT32 s_b = b >> bits_in_word_m1; // s_b = b < 0 ? -1 : 0
+ a = (a ^ s_a) - s_a; // negate if s_a == -1
+ b = (b ^ s_b) - s_b; // negate if s_b == -1
+ s_a ^= s_b; // sign of quotient
+ return (__udivsi3(a, b) ^ s_a) - s_a; // negate if s_a == -1
+}
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lasr.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lasr.asm
index 1821816ab..069438c92 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lasr.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lasr.asm
@@ -1,41 +1,41 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_lasr
-
- AREA Math, CODE, READONLY
-
-;
-;UINT32
-;EFIAPI
-;__aeabi_lasr (
-; IN UINT32 Dividen
-; IN UINT32 Divisor
-; );
-;
-__aeabi_lasr
- SUBS r3,r2,#0x20
- BPL {pc} + 0x18 ; 0x1c
- RSB r3,r2,#0x20
- LSR r0,r0,r2
- ORR r0,r0,r1,LSL r3
- ASR r1,r1,r2
- BX lr
- ASR r0,r1,r3
- ASR r1,r1,#31
- BX lr
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_lasr
+
+ AREA Math, CODE, READONLY
+
+;
+;UINT32
+;EFIAPI
+;__aeabi_lasr (
+; IN UINT32 Dividen
+; IN UINT32 Divisor
+; );
+;
+__aeabi_lasr
+ SUBS r3,r2,#0x20
+ BPL {pc} + 0x18 ; 0x1c
+ RSB r3,r2,#0x20
+ LSR r0,r0,r2
+ ORR r0,r0,r1,LSL r3
+ ASR r1,r1,r2
+ BX lr
+ ASR r0,r1,r3
+ ASR r1,r1,#31
+ BX lr
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.S
index 02ecdfe8d..510778ab0 100755
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.S
@@ -1,59 +1,59 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- .text
- .align 2
- GCC_ASM_EXPORT(__aeabi_ldivmod)
-
-//
-// A pair of (unsigned) long longs is returned in {{r0, r1}, {r2, r3}},
-// the quotient in {r0, r1}, and the remainder in {r2, r3}.
-//
-//__value_in_regs lldiv_t
-//EFIAPI
-//__aeabi_ldivmod (
-// IN UINT64 Dividen
-// IN UINT64 Divisor
-// )//
-//
-
-ASM_PFX(__aeabi_ldivmod):
- push {r4,lr}
- asrs r4,r1,#1
- eor r4,r4,r3,LSR #1
- bpl L_Test1
- rsbs r0,r0,#0
- rsc r1,r1,#0
-L_Test1:
- tst r3,r3
- bpl L_Test2
- rsbs r2,r2,#0
- rsc r3,r3,#0
-L_Test2:
- bl ASM_PFX(__aeabi_uldivmod)
- tst r4,#0x40000000
- beq L_Test3
- rsbs r0,r0,#0
- rsc r1,r1,#0
-L_Test3:
- tst r4,#0x80000000
- beq L_Exit
- rsbs r2,r2,#0
- rsc r3,r3,#0
-L_Exit:
- pop {r4,pc}
-
-
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__aeabi_ldivmod)
+
+//
+// A pair of (unsigned) long longs is returned in {{r0, r1}, {r2, r3}},
+// the quotient in {r0, r1}, and the remainder in {r2, r3}.
+//
+//__value_in_regs lldiv_t
+//EFIAPI
+//__aeabi_ldivmod (
+// IN UINT64 Dividen
+// IN UINT64 Divisor
+// )//
+//
+
+ASM_PFX(__aeabi_ldivmod):
+ push {r4,lr}
+ asrs r4,r1,#1
+ eor r4,r4,r3,LSR #1
+ bpl L_Test1
+ rsbs r0,r0,#0
+ rsc r1,r1,#0
+L_Test1:
+ tst r3,r3
+ bpl L_Test2
+ rsbs r2,r2,#0
+ rsc r3,r3,#0
+L_Test2:
+ bl ASM_PFX(__aeabi_uldivmod)
+ tst r4,#0x40000000
+ beq L_Test3
+ rsbs r0,r0,#0
+ rsc r1,r1,#0
+L_Test3:
+ tst r4,#0x80000000
+ beq L_Exit
+ rsbs r2,r2,#0
+ rsc r3,r3,#0
+L_Exit:
+ pop {r4,pc}
+
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.asm
index 32b65df52..0059c2f6f 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ldivmod.asm
@@ -1,58 +1,58 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_ldivmod
- EXTERN __aeabi_uldivmod
-
- AREA Math, CODE, READONLY
-
-;
-;UINT32
-;EFIAPI
-;__aeabi_uidivmode (
-; IN UINT32 Dividen
-; IN UINT32 Divisor
-; );
-;
-
-__aeabi_ldivmod
- PUSH {r4,lr}
- ASRS r4,r1,#1
- EOR r4,r4,r3,LSR #1
- BPL L_Test1
- RSBS r0,r0,#0
- RSC r1,r1,#0
-L_Test1
- TST r3,r3
- BPL L_Test2
- RSBS r2,r2,#0
- RSC r3,r3,#0
-L_Test2
- BL __aeabi_uldivmod ;
- TST r4,#0x40000000
- BEQ L_Test3
- RSBS r0,r0,#0
- RSC r1,r1,#0
-L_Test3
- TST r4,#0x80000000
- BEQ L_Exit
- RSBS r2,r2,#0
- RSC r3,r3,#0
-L_Exit
- POP {r4,pc}
-
- END
-
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_ldivmod
+ EXTERN __aeabi_uldivmod
+
+ AREA Math, CODE, READONLY
+
+;
+;UINT32
+;EFIAPI
+;__aeabi_uidivmode (
+; IN UINT32 Dividen
+; IN UINT32 Divisor
+; );
+;
+
+__aeabi_ldivmod
+ PUSH {r4,lr}
+ ASRS r4,r1,#1
+ EOR r4,r4,r3,LSR #1
+ BPL L_Test1
+ RSBS r0,r0,#0
+ RSC r1,r1,#0
+L_Test1
+ TST r3,r3
+ BPL L_Test2
+ RSBS r2,r2,#0
+ RSC r3,r3,#0
+L_Test2
+ BL __aeabi_uldivmod ;
+ TST r4,#0x40000000
+ BEQ L_Test3
+ RSBS r0,r0,#0
+ RSC r1,r1,#0
+L_Test3
+ TST r4,#0x80000000
+ BEQ L_Exit
+ RSBS r2,r2,#0
+ RSC r3,r3,#0
+L_Exit
+ POP {r4,pc}
+
+ END
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.S
new file mode 100644
index 000000000..ba8ab1cf5
--- /dev/null
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.S
@@ -0,0 +1,40 @@
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2013, ARM. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+
+.text
+.align 2
+GCC_ASM_EXPORT(__aeabi_llsl)
+
+#
+#VOID
+#EFIAPI
+#__aeabi_llsl (
+# IN VOID *Destination,
+# IN VOID *Source,
+# IN UINT32 Size
+# );
+#
+ASM_PFX(__aeabi_llsl):
+ subs r3,r2,#0x20
+ bpl 1f
+ rsb r3,r2,#0x20
+ lsl r1,r1,r2
+ orr r1,r1,r0,lsr r3
+ lsl r0,r0,r2
+ bx lr
+1:
+ lsl r1,r0,r3
+ mov r0,#0
+ bx lr
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm
index 099693949..43d9e729c 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsl.asm
@@ -1,43 +1,43 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_llsl
-
- AREA Math, CODE, READONLY
-
-;
-;VOID
-;EFIAPI
-;__aeabi_llsl (
-; IN VOID *Destination,
-; IN VOID *Source,
-; IN UINT32 Size
-; );
-;
-
-__aeabi_llsl
- SUBS r3,r2,#0x20
- BPL {pc} + 0x18 ; 0x1c
- RSB r3,r2,#0x20
- LSL r1,r1,r2
- ORR r1,r1,r0,LSR r3
- LSL r0,r0,r2
- BX lr
- LSL r1,r0,r3
- MOV r0,#0
- BX lr
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_llsl
+
+ AREA Math, CODE, READONLY
+
+;
+;VOID
+;EFIAPI
+;__aeabi_llsl (
+; IN VOID *Destination,
+; IN VOID *Source,
+; IN UINT32 Size
+; );
+;
+
+__aeabi_llsl
+ SUBS r3,r2,#0x20
+ BPL {pc} + 0x18 ; 0x1c
+ RSB r3,r2,#0x20
+ LSL r1,r1,r2
+ ORR r1,r1,r0,LSR r3
+ LSL r0,r0,r2
+ BX lr
+ LSL r1,r0,r3
+ MOV r0,#0
+ BX lr
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.S
new file mode 100644
index 000000000..3d2c10627
--- /dev/null
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.S
@@ -0,0 +1,40 @@
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2013, ARM. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+
+.text
+.align 2
+GCC_ASM_EXPORT(__aeabi_llsr)
+
+#
+#VOID
+#EFIAPI
+#__aeabi_llsr (
+# IN VOID *Destination,
+# IN VOID *Source,
+# IN UINT32 Size
+# );
+#
+ASM_PFX(__aeabi_llsr):
+ subs r3,r2,#0x20
+ bpl 1f
+ rsb r3,r2,#0x20
+ lsr r0,r0,r2
+ orr r0,r0,r1,lsl r3
+ lsr r1,r1,r2
+ bx lr
+1:
+ lsr r0,r1,r3
+ mov r1,#0
+ bx lr
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm
index 8f1af0ed4..de9a2186c 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/llsr.asm
@@ -1,44 +1,44 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_llsr
-
- AREA Math, CODE, READONLY
-
-;
-;VOID
-;EFIAPI
-;__aeabi_llsr (
-; IN VOID *Destination,
-; IN VOID *Source,
-; IN UINT32 Size
-; );
-;
-__aeabi_llsr
- SUBS r3,r2,#0x20
- BPL {pc} + 0x18 ; 0x1c
- RSB r3,r2,#0x20
- LSR r0,r0,r2
- ORR r0,r0,r1,LSL r3
- LSR r1,r1,r2
- BX lr
- LSR r0,r1,r3
- MOV r1,#0
- BX lr
-
- END
-
-
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_llsr
+
+ AREA Math, CODE, READONLY
+
+;
+;VOID
+;EFIAPI
+;__aeabi_llsr (
+; IN VOID *Destination,
+; IN VOID *Source,
+; IN UINT32 Size
+; );
+;
+__aeabi_llsr
+ SUBS r3,r2,#0x20
+ BPL {pc} + 0x18 ; 0x1c
+ RSB r3,r2,#0x20
+ LSR r0,r0,r2
+ ORR r0,r0,r1,LSL r3
+ LSR r1,r1,r2
+ BX lr
+ LSR r0,r1,r3
+ MOV r1,#0
+ BX lr
+
+ END
+
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.S
index 73d83599b..efec070c0 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.S
@@ -1,35 +1,35 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__lshrdi3)
-
-ASM_PFX(__lshrdi3):
- cmp r2, #31
- bls L2
- cmp r2, #63
- subls r2, r2, #32
- movls r2, r1, lsr r2
- movhi r2, #0
- mov r0, r2
- mov r1, #0
- bx lr
-L2:
- cmp r2, #0
- rsbne r3, r2, #32
- movne r3, r1, asl r3
- movne r1, r1, lsr r2
- orrne r0, r3, r0, lsr r2
- bx lr
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__lshrdi3)
+
+ASM_PFX(__lshrdi3):
+ cmp r2, #31
+ bls L2
+ cmp r2, #63
+ subls r2, r2, #32
+ movls r2, r1, lsr r2
+ movhi r2, #0
+ mov r0, r2
+ mov r1, #0
+ bx lr
+L2:
+ cmp r2, #0
+ rsbne r3, r2, #32
+ movne r3, r1, asl r3
+ movne r1, r1, lsr r2
+ orrne r0, r3, r0, lsr r2
+ bx lr
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.c
index 4353be9de..47c80c2d2 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/lshrdi3.c
@@ -1,83 +1,83 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-#include "Llvm_int_lib.h"
-
-// Returns: logical a >> b
-
-// Precondition: 0 <= b < bits_in_dword
-
-INT64
-__lshrdi3(INT64 a, INT32 b)
-{
- const int bits_in_word = (int)(sizeof(INT32) * CHAR_BIT);
- udwords input;
- udwords result;
- input.all = a;
- if (b & bits_in_word) // bits_in_word <= b < bits_in_dword
- {
- result.high = 0;
- result.low = input.high >> (b - bits_in_word);
- }
- else // 0 <= b < bits_in_word
- {
- if (b == 0)
- return a;
- result.high = input.high >> b;
- result.low = (input.high << (bits_in_word - b)) | (input.low >> b);
- }
- return result.all;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+#include "Llvm_int_lib.h"
+
+// Returns: logical a >> b
+
+// Precondition: 0 <= b < bits_in_dword
+
+INT64
+__lshrdi3(INT64 a, INT32 b)
+{
+ const int bits_in_word = (int)(sizeof(INT32) * CHAR_BIT);
+ udwords input;
+ udwords result;
+ input.all = a;
+ if (b & bits_in_word) // bits_in_word <= b < bits_in_dword
+ {
+ result.high = 0;
+ result.low = input.high >> (b - bits_in_word);
+ }
+ else // 0 <= b < bits_in_word
+ {
+ if (b == 0)
+ return a;
+ result.high = input.high >> b;
+ result.low = (input.high << (bits_in_word - b)) | (input.low >> b);
+ }
+ return result.all;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.S
index 18299326c..07e0cd6bb 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.S
@@ -1,34 +1,34 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(memcpy)
-
-ASM_PFX(memcpy):
- stmfd sp!, {r7, lr}
- mov ip, #0
- add r7, sp, #0
- mov lr, r0
- b L4
-L5:
- ldrb r3, [r1], #1 @ zero_extendqisi2
- add ip, ip, #1
- and r3, r3, #255
- strb r3, [lr], #1
-L4:
- cmp ip, r2
- bne L5
- ldmfd sp!, {r7, pc}
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(memcpy)
+
+ASM_PFX(memcpy):
+ stmfd sp!, {r7, lr}
+ mov ip, #0
+ add r7, sp, #0
+ mov lr, r0
+ b L4
+L5:
+ ldrb r3, [r1], #1 @ zero_extendqisi2
+ add ip, ip, #1
+ and r3, r3, #255
+ strb r3, [lr], #1
+L4:
+ cmp ip, r2
+ bne L5
+ ldmfd sp!, {r7, pc}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.asm
index aef8a5c11..e01b80d4b 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy.asm
@@ -1,40 +1,40 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_memcpy
-
- AREA Memcpy, CODE, READONLY
-
-;
-;VOID
-;EFIAPI
-;__aeabi_memcpy (
-; IN VOID *Destination,
-; IN VOID *Source,
-; IN UINT32 Size
-; );
-;
-__aeabi_memcpy
- CMP r2, #0
- BXEQ r14
-loop
- LDRB r3, [r1], #1
- STRB r3, [r0], #1
- SUBS r2, r2, #1
- BXEQ r14
- B loop
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_memcpy
+
+ AREA Memcpy, CODE, READONLY
+
+;
+;VOID
+;EFIAPI
+;__aeabi_memcpy (
+; IN VOID *Destination,
+; IN VOID *Source,
+; IN UINT32 Size
+; );
+;
+__aeabi_memcpy
+ CMP r2, #0
+ BXEQ r14
+loop
+ LDRB r3, [r1], #1
+ STRB r3, [r0], #1
+ SUBS r2, r2, #1
+ BXEQ r14
+ B loop
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy4.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy4.asm
index a3cd58aba..9780060c1 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy4.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memcpy4.asm
@@ -1,61 +1,61 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_memcpy4
-
- AREA Memcpy4, CODE, READONLY
-
-;
-;VOID
-;EFIAPI
-;__aeabi_memcpy (
-; IN VOID *Destination,
-; IN VOID *Source,
-; IN UINT32 Size
-; );
-;
-__aeabi_memcpy4
- stmdb sp!, {r4, lr}
- subs r2, r2, #32 ; 0x20
- bcc memcpy4_label2
-memcpy4_label1
- ldmcsia r1!, {r3, r4, ip, lr}
- stmcsia r0!, {r3, r4, ip, lr}
- ldmcsia r1!, {r3, r4, ip, lr}
- stmcsia r0!, {r3, r4, ip, lr}
- subcss r2, r2, #32 ; 0x20
- bcs memcpy4_label1
-memcpy4_label2
- movs ip, r2, lsl #28
- ldmcsia r1!, {r3, r4, ip, lr}
- stmcsia r0!, {r3, r4, ip, lr}
- ldmmiia r1!, {r3, r4}
- stmmiia r0!, {r3, r4}
- ldmia sp!, {r4, lr}
- movs ip, r2, lsl #30
- ldrcs r3, [r1], #4
- strcs r3, [r0], #4
- bxeq lr
-
-_memcpy4_lastbytes_aligned
- movs r2, r2, lsl #31
- ldrcsh r3, [r1], #2
- ldrmib r2, [r1], #1
- strcsh r3, [r0], #2
- strmib r2, [r0], #1
- bx lr
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_memcpy4
+
+ AREA Memcpy4, CODE, READONLY
+
+;
+;VOID
+;EFIAPI
+;__aeabi_memcpy (
+; IN VOID *Destination,
+; IN VOID *Source,
+; IN UINT32 Size
+; );
+;
+__aeabi_memcpy4
+ stmdb sp!, {r4, lr}
+ subs r2, r2, #32 ; 0x20
+ bcc memcpy4_label2
+memcpy4_label1
+ ldmcsia r1!, {r3, r4, ip, lr}
+ stmcsia r0!, {r3, r4, ip, lr}
+ ldmcsia r1!, {r3, r4, ip, lr}
+ stmcsia r0!, {r3, r4, ip, lr}
+ subcss r2, r2, #32 ; 0x20
+ bcs memcpy4_label1
+memcpy4_label2
+ movs ip, r2, lsl #28
+ ldmcsia r1!, {r3, r4, ip, lr}
+ stmcsia r0!, {r3, r4, ip, lr}
+ ldmmiia r1!, {r3, r4}
+ stmmiia r0!, {r3, r4}
+ ldmia sp!, {r4, lr}
+ movs ip, r2, lsl #30
+ ldrcs r3, [r1], #4
+ strcs r3, [r0], #4
+ bxeq lr
+
+_memcpy4_lastbytes_aligned
+ movs r2, r2, lsl #31
+ ldrcsh r3, [r1], #2
+ ldrmib r2, [r1], #1
+ strcsh r3, [r0], #2
+ strmib r2, [r0], #1
+ bx lr
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memmove.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memmove.asm
index d84429ef7..ae5c990f5 100755
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memmove.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memmove.asm
@@ -1,54 +1,54 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2011, ARM Limited. All rights reserved.
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_memmove
-
- AREA Memmove, CODE, READONLY
-
-;
-;VOID
-;EFIAPI
-;__aeabi_memmove (
-; IN VOID *Destination,
-; IN CONST VOID *Source,
-; IN UINT32 Size
-; );
-;
-__aeabi_memmove
- CMP r2, #0
- BXEQ r14
- CMP r0, r1
- BXEQ r14
- BHI memmove_backward
- BLS memmove_forward
-
-memmove_forward
- LDRB r3, [r1], #1
- STRB r3, [r0], #1
- SUBS r2, r2, #1
- BXEQ r14
- B memmove_forward
-
-memmove_backward
- add r0, r2
- add r1, r2
-memmove_backward_loop
- LDRB r3, [r1], #-1
- STRB r3, [r0], #-1
- SUBS r2, r2, #-1
- BXEQ r14
- B memmove_backward_loop
-
- END
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2011, ARM Limited. All rights reserved.
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_memmove
+
+ AREA Memmove, CODE, READONLY
+
+;
+;VOID
+;EFIAPI
+;__aeabi_memmove (
+; IN VOID *Destination,
+; IN CONST VOID *Source,
+; IN UINT32 Size
+; );
+;
+__aeabi_memmove
+ CMP r2, #0
+ BXEQ r14
+ CMP r0, r1
+ BXEQ r14
+ BHI memmove_backward
+ BLS memmove_forward
+
+memmove_forward
+ LDRB r3, [r1], #1
+ STRB r3, [r0], #1
+ SUBS r2, r2, #1
+ BXEQ r14
+ B memmove_forward
+
+memmove_backward
+ add r0, r2
+ add r1, r2
+memmove_backward_loop
+ LDRB r3, [r1], #-1
+ STRB r3, [r0], #-1
+ SUBS r2, r2, #-1
+ BXEQ r14
+ B memmove_backward_loop
+
+ END
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.S
index 35783620c..7b1cf8d97 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.S
@@ -1,38 +1,38 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-
- .text
- .align 2
- GCC_ASM_EXPORT (memset)
-
-
-ASM_PFX(memset):
-
- @ args = 0, pretend = 0, frame = 0
- @ frame_needed = 1, uses_anonymous_args = 0
- stmfd sp!, {r7, lr}
- mov ip, #0
- add r7, sp, #0
- mov lr, r0
- b L9
-L10:
- and r3, r1, #255
- add ip, ip, #1
- strb r3, [lr], #1
-L9:
- cmp ip, r2
- bne L10
- ldmfd sp!, {r7, pc}
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT (memset)
+
+
+ASM_PFX(memset):
+
+ @ args = 0, pretend = 0, frame = 0
+ @ frame_needed = 1, uses_anonymous_args = 0
+ stmfd sp!, {r7, lr}
+ mov ip, #0
+ add r7, sp, #0
+ mov lr, r0
+ b L9
+L10:
+ and r3, r1, #255
+ add ip, ip, #1
+ strb r3, [lr], #1
+L9:
+ cmp ip, r2
+ bne L10
+ ldmfd sp!, {r7, pc}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.asm
index d567cd54e..74e024304 100755
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memset.asm
@@ -1,59 +1,59 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_memset
- EXPORT __aeabi_memclr
- EXPORT __aeabi_memclr4
-
- AREA Memset, CODE, READONLY
-
-;
-;VOID
-;EFIAPI
-;__aeabi_memset (
-; IN VOID *Destination,
-; IN UINT32 Character,
-; IN UINT32 Size
-; );
-;
-__aeabi_memset
-
- ; args = 0, pretend = 0, frame = 0
- ; frame_needed = 1, uses_anonymous_args = 0
- stmfd sp!, {r7, lr}
- mov ip, #0
- add r7, sp, #0
- mov lr, r0
- b L9
-L10
- and r3, r1, #255
- add ip, ip, #1
- strb r3, [lr], #1
-L9
- cmp ip, r2
- bne L10
- ldmfd sp!, {r7, pc}
-
-__aeabi_memclr
- mov r2, r1
- mov r1, #0
- b __aeabi_memset
-
-__aeabi_memclr4
- mov r2, r1
- mov r1, #0
- b __aeabi_memset
-
- END
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_memset
+ EXPORT __aeabi_memclr
+ EXPORT __aeabi_memclr4
+
+ AREA Memset, CODE, READONLY
+
+;
+;VOID
+;EFIAPI
+;__aeabi_memset (
+; IN VOID *Destination,
+; IN UINT32 Character,
+; IN UINT32 Size
+; );
+;
+__aeabi_memset
+
+ ; args = 0, pretend = 0, frame = 0
+ ; frame_needed = 1, uses_anonymous_args = 0
+ stmfd sp!, {r7, lr}
+ mov ip, #0
+ add r7, sp, #0
+ mov lr, r0
+ b L9
+L10
+ and r3, r1, #255
+ add ip, ip, #1
+ strb r3, [lr], #1
+L9
+ cmp ip, r2
+ bne L10
+ ldmfd sp!, {r7, pc}
+
+__aeabi_memclr
+ mov r2, r1
+ mov r1, #0
+ b __aeabi_memset
+
+__aeabi_memclr4
+ mov r2, r1
+ mov r1, #0
+ b __aeabi_memset
+
+ END
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.S
index 75572c82b..e058ea446 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.S
@@ -1,46 +1,46 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__moddi3)
-
-ASM_PFX(__moddi3):
- stmfd sp!, {r4, r5, r7, lr}
- mov r4, r1, asr #31
- add r7, sp, #8
- stmfd sp!, {r10, r11}
- mov r10, r3, asr #31
- sub sp, sp, #16
- mov r5, r4
- mov r11, r10
- eor r0, r0, r4
- eor r1, r1, r4
- eor r2, r2, r10
- eor r3, r3, r10
- add ip, sp, #8
- subs r0, r0, r4
- sbc r1, r1, r5
- subs r2, r2, r10
- sbc r3, r3, r11
- str ip, [sp, #0]
- bl ASM_PFX(__udivmoddi4)
- ldrd r0, [sp, #8]
- eor r0, r0, r4
- eor r1, r1, r4
- subs r0, r0, r4
- sbc r1, r1, r5
- sub sp, r7, #16
- ldmfd sp!, {r10, r11}
- ldmfd sp!, {r4, r5, r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__moddi3)
+
+ASM_PFX(__moddi3):
+ stmfd sp!, {r4, r5, r7, lr}
+ mov r4, r1, asr #31
+ add r7, sp, #8
+ stmfd sp!, {r10, r11}
+ mov r10, r3, asr #31
+ sub sp, sp, #16
+ mov r5, r4
+ mov r11, r10
+ eor r0, r0, r4
+ eor r1, r1, r4
+ eor r2, r2, r10
+ eor r3, r3, r10
+ add ip, sp, #8
+ subs r0, r0, r4
+ sbc r1, r1, r5
+ subs r2, r2, r10
+ sbc r3, r3, r11
+ str ip, [sp, #0]
+ bl ASM_PFX(__udivmoddi4)
+ ldrd r0, [sp, #8]
+ eor r0, r0, r4
+ eor r1, r1, r4
+ subs r0, r0, r4
+ sbc r1, r1, r5
+ sub sp, r7, #16
+ ldmfd sp!, {r10, r11}
+ ldmfd sp!, {r4, r5, r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.c
index f9e5afe91..972fc065e 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/moddi3.c
@@ -1,77 +1,77 @@
-/** @file
- Compiler intrinsic for 64-bit mod, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-UINT64 __udivmoddi4(UINT64 a, UINT64 b, UINT64* rem);
-
-// Returns: a % b
-
-INT64
-__moddi3(INT64 a, INT64 b)
-{
- const int bits_in_dword_m1 = (int)(sizeof(INT64) * CHAR_BIT) - 1;
- INT64 s = b >> bits_in_dword_m1; // s = b < 0 ? -1 : 0
- b = (b ^ s) - s; // negate if s == -1
- s = a >> bits_in_dword_m1; // s = a < 0 ? -1 : 0
- a = (a ^ s) - s; // negate if s == -1
- INT64 r;
- __udivmoddi4(a, b, (UINT64*)&r);
- return (r ^ s) - s; // negate if s == -1
-}
-
+/** @file
+ Compiler intrinsic for 64-bit mod, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+UINT64 __udivmoddi4(UINT64 a, UINT64 b, UINT64* rem);
+
+// Returns: a % b
+
+INT64
+__moddi3(INT64 a, INT64 b)
+{
+ const int bits_in_dword_m1 = (int)(sizeof(INT64) * CHAR_BIT) - 1;
+ INT64 s = b >> bits_in_dword_m1; // s = b < 0 ? -1 : 0
+ b = (b ^ s) - s; // negate if s == -1
+ s = a >> bits_in_dword_m1; // s = a < 0 ? -1 : 0
+ a = (a ^ s) - s; // negate if s == -1
+ INT64 r;
+ __udivmoddi4(a, b, (UINT64*)&r);
+ return (r ^ s) - s; // negate if s == -1
+}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.S
index eb698d604..07f8ef72f 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.S
@@ -1,27 +1,27 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__modsi3)
-
-ASM_PFX(__modsi3):
- stmfd sp!, {r4, r5, r7, lr}
- add r7, sp, #8
- mov r5, r0
- mov r4, r1
- bl ___divsi3
- mul r0, r4, r0
- rsb r0, r0, r5
- ldmfd sp!, {r4, r5, r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__modsi3)
+
+ASM_PFX(__modsi3):
+ stmfd sp!, {r4, r5, r7, lr}
+ add r7, sp, #8
+ mov r5, r0
+ mov r4, r1
+ bl ___divsi3
+ mul r0, r4, r0
+ rsb r0, r0, r5
+ ldmfd sp!, {r4, r5, r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.c
index 68373d9c2..9bdf077fb 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/modsi3.c
@@ -1,70 +1,70 @@
-/** @file
- Compiler intrinsic for 32-bit mod, ported from LLVM code.
-
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-// Returns: a % b
-
-INT32
-__modsi3(INT32 a, INT32 b)
-{
- return a - (a / b) * b;
-}
-
-
+/** @file
+ Compiler intrinsic for 32-bit mod, ported from LLVM code.
+
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+// Returns: a % b
+
+INT32
+__modsi3(INT32 a, INT32 b)
+{
+ return a - (a / b) * b;
+}
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.S
index 36956c24e..e8ac1ffff 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.S
@@ -1,58 +1,58 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__muldi3)
-
-ASM_PFX(__muldi3):
- stmfd sp!, {r4, r5, r6, r7, lr}
- add r7, sp, #12
- stmfd sp!, {r8, r10, r11}
- ldr r11, L4
- mov r4, r0, lsr #16
- and r8, r0, r11
- and ip, r2, r11
- mul lr, ip, r8
- mul ip, r4, ip
- sub sp, sp, #8
- add r10, ip, lr, lsr #16
- and ip, r10, r11
- and lr, lr, r11
- mov r6, r2, lsr #16
- str r4, [sp, #4]
- add r4, lr, ip, asl #16
- mul ip, r8, r6
- mov r5, r10, lsr #16
- add r10, ip, r4, lsr #16
- and ip, r10, r11
- and lr, r4, r11
- add r4, lr, ip, asl #16
- mul r0, r3, r0
- add ip, r5, r10, lsr #16
- ldr r5, [sp, #4]
- mla r0, r2, r1, r0
- mla r5, r6, r5, ip
- mov r10, r4
- add r11, r0, r5
- mov r1, r11
- mov r0, r4
- sub sp, r7, #24
- ldmfd sp!, {r8, r10, r11}
- ldmfd sp!, {r4, r5, r6, r7, pc}
- .p2align 2
-L5:
- .align 2
-L4:
- .long 65535
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__muldi3)
+
+ASM_PFX(__muldi3):
+ stmfd sp!, {r4, r5, r6, r7, lr}
+ add r7, sp, #12
+ stmfd sp!, {r8, r10, r11}
+ ldr r11, L4
+ mov r4, r0, lsr #16
+ and r8, r0, r11
+ and ip, r2, r11
+ mul lr, ip, r8
+ mul ip, r4, ip
+ sub sp, sp, #8
+ add r10, ip, lr, lsr #16
+ and ip, r10, r11
+ and lr, lr, r11
+ mov r6, r2, lsr #16
+ str r4, [sp, #4]
+ add r4, lr, ip, asl #16
+ mul ip, r8, r6
+ mov r5, r10, lsr #16
+ add r10, ip, r4, lsr #16
+ and ip, r10, r11
+ and lr, r4, r11
+ add r4, lr, ip, asl #16
+ mul r0, r3, r0
+ add ip, r5, r10, lsr #16
+ ldr r5, [sp, #4]
+ mla r0, r2, r1, r0
+ mla r5, r6, r5, ip
+ mov r10, r4
+ add r11, r0, r5
+ mov r1, r11
+ mov r0, r4
+ sub sp, r7, #24
+ ldmfd sp!, {r8, r10, r11}
+ ldmfd sp!, {r4, r5, r6, r7, pc}
+ .p2align 2
+L5:
+ .align 2
+L4:
+ .long 65535
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.c
index d48bd22b4..67d0e4eed 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/muldi3.c
@@ -1,98 +1,98 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-#include <Base.h>
-#include "Llvm_int_lib.h"
-
-
-// Returns: a * b
-
-static
-INT64
-__muldsi3(UINT32 a, UINT32 b)
-{
- dwords r;
- const int bits_in_word_2 = (int)(sizeof(INT32) * CHAR_BIT) / 2;
- const UINT32 lower_mask = (UINT32)~0 >> bits_in_word_2;
- r.low = (a & lower_mask) * (b & lower_mask);
- UINT32 t = r.low >> bits_in_word_2;
- r.low &= lower_mask;
- t += (a >> bits_in_word_2) * (b & lower_mask);
- r.low += (t & lower_mask) << bits_in_word_2;
- r.high = t >> bits_in_word_2;
- t = r.low >> bits_in_word_2;
- r.low &= lower_mask;
- t += (b >> bits_in_word_2) * (a & lower_mask);
- r.low += (t & lower_mask) << bits_in_word_2;
- r.high += t >> bits_in_word_2;
- r.high += (a >> bits_in_word_2) * (b >> bits_in_word_2);
- return r.all;
-}
-
-// Returns: a * b
-
-INT64
-__muldi3(INT64 a, INT64 b)
-{
- dwords x;
- x.all = a;
- dwords y;
- y.all = b;
- dwords r;
- r.all = __muldsi3(x.low, y.low);
- r.high += x.high * y.low + x.low * y.high;
- return r.all;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+#include <Base.h>
+#include "Llvm_int_lib.h"
+
+
+// Returns: a * b
+
+static
+INT64
+__muldsi3(UINT32 a, UINT32 b)
+{
+ dwords r;
+ const int bits_in_word_2 = (int)(sizeof(INT32) * CHAR_BIT) / 2;
+ const UINT32 lower_mask = (UINT32)~0 >> bits_in_word_2;
+ r.low = (a & lower_mask) * (b & lower_mask);
+ UINT32 t = r.low >> bits_in_word_2;
+ r.low &= lower_mask;
+ t += (a >> bits_in_word_2) * (b & lower_mask);
+ r.low += (t & lower_mask) << bits_in_word_2;
+ r.high = t >> bits_in_word_2;
+ t = r.low >> bits_in_word_2;
+ r.low &= lower_mask;
+ t += (b >> bits_in_word_2) * (a & lower_mask);
+ r.low += (t & lower_mask) << bits_in_word_2;
+ r.high += t >> bits_in_word_2;
+ r.high += (a >> bits_in_word_2) * (b >> bits_in_word_2);
+ return r.all;
+}
+
+// Returns: a * b
+
+INT64
+__muldi3(INT64 a, INT64 b)
+{
+ dwords x;
+ x.all = a;
+ dwords y;
+ y.all = b;
+ dwords r;
+ r.all = __muldsi3(x.low, y.low);
+ r.high += x.high * y.low + x.low * y.high;
+ return r.all;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/mullu.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/mullu.asm
index 5d369e9af..489763648 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/mullu.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/mullu.asm
@@ -1,49 +1,49 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __ARM_ll_mullu
- EXPORT __aeabi_lmul
-
- AREA Math, CODE, READONLY
-
-;
-;INT64
-;EFIAPI
-;__aeabi_lmul (
-; IN INT64 Multiplicand
-; IN INT32 Multiplier
-; );
-;
-__ARM_ll_mullu
- mov r3, #0
-// Make upper part of INT64 Multiplier 0 and use __aeabi_lmul
-
-;
-;INT64
-;EFIAPI
-;__aeabi_lmul (
-; IN INT64 Multiplicand
-; IN INT64 Multiplier
-; );
-;
-__aeabi_lmul
- stmdb sp!, {lr}
- mov lr, r0
- umull r0, ip, r2, lr
- mla r1, r2, r1, ip
- mla r1, r3, lr, r1
- ldmia sp!, {pc}
-
- END
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __ARM_ll_mullu
+ EXPORT __aeabi_lmul
+
+ AREA Math, CODE, READONLY
+
+;
+;INT64
+;EFIAPI
+;__aeabi_lmul (
+; IN INT64 Multiplicand
+; IN INT32 Multiplier
+; );
+;
+__ARM_ll_mullu
+ mov r3, #0
+// Make upper part of INT64 Multiplier 0 and use __aeabi_lmul
+
+;
+;INT64
+;EFIAPI
+;__aeabi_lmul (
+; IN INT64 Multiplicand
+; IN INT64 Multiplier
+; );
+;
+__aeabi_lmul
+ stmdb sp!, {lr}
+ mov lr, r0
+ umull r0, ip, r2, lr
+ mla r1, r2, r1, ip
+ mla r1, r3, lr, r1
+ ldmia sp!, {pc}
+
+ END
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch.asm
index 8d34c5de5..2c8a0318d 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch.asm
@@ -1,29 +1,29 @@
-///------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
-
- EXPORT __ARM_switch8
-
- AREA ArmSwitch, CODE, READONLY
-
-__ARM_switch8
- LDRB r12,[lr,#-1]
- CMP r3,r12
- LDRBCC r3,[lr,r3]
- LDRBCS r3,[lr,r12]
- ADD r12,lr,r3,LSL #1
- BX r12
-
- END
+///------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+
+ EXPORT __ARM_switch8
+
+ AREA ArmSwitch, CODE, READONLY
+
+__ARM_switch8
+ LDRB r12,[lr,#-1]
+ CMP r3,r12
+ LDRBCC r3,[lr,r3]
+ LDRBCS r3,[lr,r12]
+ ADD r12,lr,r3,LSL #1
+ BX r12
+
+ END
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch16.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch16.S
index 97ebf7935..ce6904e0c 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch16.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch16.S
@@ -1,31 +1,31 @@
-#/** @file
-# Compiler intrinsic for ARM compiler
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
-#
-#**/
-#
-
-.text
-.p2align 2
-
-GCC_ASM_EXPORT(__switch16)
-
-ASM_PFX(__switch16):
- ldrh ip, [lr, #-1]
- cmp r0, ip
- add r0, lr, r0, lsl #1
- ldrccsh r0, [r0, #1]
- add ip, lr, ip, lsl #1
- ldrcssh r0, [ip, #1]
- add ip, lr, r0, lsl #1
- bx ip
-
-
+#/** @file
+# Compiler intrinsic for ARM compiler
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
+#
+#**/
+#
+
+.text
+.p2align 2
+
+GCC_ASM_EXPORT(__switch16)
+
+ASM_PFX(__switch16):
+ ldrh ip, [lr, #-1]
+ cmp r0, ip
+ add r0, lr, r0, lsl #1
+ ldrccsh r0, [r0, #1]
+ add ip, lr, ip, lsl #1
+ ldrcssh r0, [ip, #1]
+ add ip, lr, r0, lsl #1
+ bx ip
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch32.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch32.S
index e0fd100aa..63aed6e6b 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch32.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch32.S
@@ -1,30 +1,30 @@
-#/** @file
-# Compiler intrinsic for ARM compiler
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
-#
-#**/
-#
-
-.text
-.p2align 2
-
-GCC_ASM_EXPORT(__switch32)
-
-ASM_PFX(__switch32):
- ldr ip, [lr, #-1]
- cmp r0, ip
- add r0, lr, r0, lsl #2
- ldrcc r0, [r0, #3]
- add ip, lr, ip, lsl #2
- ldrcs r0, [ip, #3]
- add ip, lr, r0
- bx ip
-
+#/** @file
+# Compiler intrinsic for ARM compiler
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
+#
+#**/
+#
+
+.text
+.p2align 2
+
+GCC_ASM_EXPORT(__switch32)
+
+ASM_PFX(__switch32):
+ ldr ip, [lr, #-1]
+ cmp r0, ip
+ add r0, lr, r0, lsl #2
+ ldrcc r0, [r0, #3]
+ add ip, lr, ip, lsl #2
+ ldrcs r0, [ip, #3]
+ add ip, lr, r0
+ bx ip
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch8.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch8.S
index ea3340c9a..688e106a9 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch8.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switch8.S
@@ -1,28 +1,28 @@
-#/** @file
-# Compiler intrinsic for ARM compiler
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http)://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
-#
-#**/
-#
-
-.text
-.p2align 2
-
-GCC_ASM_EXPORT(__switch8)
-
-ASM_PFX(__switch8):
- ldrb ip, [lr, #-1]
- cmp r0, ip
- ldrccsb r0, [lr, r0]
- ldrcssb r0, [lr, ip]
- add ip, lr, r0, lsl #1
- bx ip
-
+#/** @file
+# Compiler intrinsic for ARM compiler
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http)://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
+#
+#**/
+#
+
+.text
+.p2align 2
+
+GCC_ASM_EXPORT(__switch8)
+
+ASM_PFX(__switch8):
+ ldrb ip, [lr, #-1]
+ cmp r0, ip
+ ldrccsb r0, [lr, r0]
+ ldrcssb r0, [lr, ip]
+ add ip, lr, r0, lsl #1
+ bx ip
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switchu8.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switchu8.S
index 83636e1f5..254b05435 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switchu8.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/switchu8.S
@@ -1,29 +1,29 @@
-#/** @file
-# Compiler intrinsic for ARM compiler
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http)://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
-#
-#**/
-#
-
-.text
-.p2align 2
-
-GCC_ASM_EXPORT(__switchu8)
-
-
-ASM_PFX(__switchu8):
- ldrb ip,[lr,#-1]
- cmp r0,ip
- ldrccb r0,[lr,r0]
- ldrcsb r0,[lr,ip]
- add ip,lr,r0,LSL #1
- bx ip
-
+#/** @file
+# Compiler intrinsic for ARM compiler
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http)://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.;
+#
+#**/
+#
+
+.text
+.p2align 2
+
+GCC_ASM_EXPORT(__switchu8)
+
+
+ASM_PFX(__switchu8):
+ ldrb ip,[lr,#-1]
+ cmp r0,ip
+ ldrccb r0,[lr,r0]
+ ldrcsb r0,[lr,ip]
+ add ip,lr,r0,LSL #1
+ bx ip
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.S
index e85be6cae..f448ed58c 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.S
@@ -1,38 +1,38 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__ucmpdi2)
-
-ASM_PFX(__ucmpdi2):
- stmfd sp!, {r4, r5, r8, lr}
- cmp r1, r3
- mov r8, r0
- mov r4, r2
- mov r5, r3
- bcc L2
- bhi L4
- cmp r0, r2
- bcc L2
- movls r0, #1
- bls L8
- b L4
-L2:
- mov r0, #0
- b L8
-L4:
- mov r0, #2
-L8:
- ldmfd sp!, {r4, r5, r8, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__ucmpdi2)
+
+ASM_PFX(__ucmpdi2):
+ stmfd sp!, {r4, r5, r8, lr}
+ cmp r1, r3
+ mov r8, r0
+ mov r4, r2
+ mov r5, r3
+ bcc L2
+ bhi L4
+ cmp r0, r2
+ bcc L2
+ movls r0, #1
+ bls L8
+ b L4
+L2:
+ mov r0, #0
+ b L8
+L4:
+ mov r0, #2
+L8:
+ ldmfd sp!, {r4, r5, r8, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.c
index 25a821ef8..70d5a531b 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/ucmpdi2.c
@@ -1,82 +1,82 @@
-/** @file
- Compiler intrinsic for 64-bit compare, ported from LLVM code.
-
- Copyright (c) 2008-2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-
-// Returns: if (a < b) returns 0
-// if (a == b) returns 1
-// if (a > b) returns 2
-
-UINT32
-__ucmpdi2(UINT64 a, UINT64 b)
-{
- udwords x;
- x.all = a;
- udwords y;
- y.all = b;
- if (x.high < y.high)
- return 0;
- if (x.high > y.high)
- return 2;
- if (x.low < y.low)
- return 0;
- if (x.low > y.low)
- return 2;
- return 1;
-}
+/** @file
+ Compiler intrinsic for 64-bit compare, ported from LLVM code.
+
+ Copyright (c) 2008-2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+
+// Returns: if (a < b) returns 0
+// if (a == b) returns 1
+// if (a > b) returns 2
+
+UINT32
+__ucmpdi2(UINT64 a, UINT64 b)
+{
+ udwords x;
+ x.all = a;
+ udwords y;
+ y.all = b;
+ if (x.high < y.high)
+ return 0;
+ if (x.high > y.high)
+ return 2;
+ if (x.low < y.low)
+ return 0;
+ if (x.low > y.low)
+ return 2;
+ return 1;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.S
index a8b970270..f274901fa 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.S
@@ -1,27 +1,27 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__udivdi3)
-
-ASM_PFX(__udivdi3):
- stmfd sp!, {r7, lr}
- add r7, sp, #0
- sub sp, sp, #8
- mov ip, #0
- str ip, [sp, #0]
- bl ASM_PFX(__udivmoddi4)
- sub sp, r7, #0
- ldmfd sp!, {r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__udivdi3)
+
+ASM_PFX(__udivdi3):
+ stmfd sp!, {r7, lr}
+ add r7, sp, #0
+ sub sp, sp, #8
+ mov ip, #0
+ str ip, [sp, #0]
+ bl ASM_PFX(__udivmoddi4)
+ sub sp, r7, #0
+ ldmfd sp!, {r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.c
index b24606f09..a8d9b0967 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivdi3.c
@@ -1,71 +1,71 @@
-/** @file
- Compiler intrinsic for 64-bit unisigned div, ported from LLVM code.
-
- Copyright (c) 2008-2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-UINT64 __udivmoddi4 (UINT64 a, UINT64 b, UINT64 *rem);
-
-// Returns: a / b
-
-UINT64
-__udivdi3(UINT64 a, UINT64 b)
-{
- return __udivmoddi4(a, b, 0);
-}
-
-
+/** @file
+ Compiler intrinsic for 64-bit unisigned div, ported from LLVM code.
+
+ Copyright (c) 2008-2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+UINT64 __udivmoddi4 (UINT64 a, UINT64 b, UINT64 *rem);
+
+// Returns: a / b
+
+UINT64
+__udivdi3(UINT64 a, UINT64 b)
+{
+ return __udivmoddi4(a, b, 0);
+}
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.S
index cadc1d291..1c0f2eae6 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.S
@@ -1,242 +1,242 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__udivmoddi4)
-
-ASM_PFX(__udivmoddi4):
- stmfd sp!, {r4, r5, r6, r7, lr}
- add r7, sp, #12
- stmfd sp!, {r10, r11}
- sub sp, sp, #20
- stmia sp, {r2-r3}
- ldr r6, [sp, #48]
- orrs r2, r2, r3
- mov r10, r0
- mov r11, r1
- beq L2
- subs ip, r1, #0
- bne L4
- cmp r3, #0
- bne L6
- cmp r6, #0
- beq L8
- mov r1, r2
- bl ASM_PFX(__umodsi3)
- mov r1, #0
- stmia r6, {r0-r1}
-L8:
- ldr r1, [sp, #0]
- mov r0, r10
- b L45
-L6:
- cmp r6, #0
- movne r1, #0
- stmneia r6, {r0-r1}
- b L2
-L4:
- ldr r1, [sp, #0]
- cmp r1, #0
- bne L12
- ldr r2, [sp, #4]
- cmp r2, #0
- bne L14
- cmp r6, #0
- beq L16
- mov r1, r2
- mov r0, r11
- bl ASM_PFX(__umodsi3)
- mov r1, #0
- stmia r6, {r0-r1}
-L16:
- ldr r1, [sp, #4]
- mov r0, r11
-L45:
- bl ASM_PFX(__udivsi3)
-L46:
- mov r10, r0
- mov r11, #0
- b L10
-L14:
- subs r1, r0, #0
- bne L18
- cmp r6, #0
- beq L16
- ldr r1, [sp, #4]
- mov r0, r11
- bl ASM_PFX(__umodsi3)
- mov r4, r10
- mov r5, r0
- stmia r6, {r4-r5}
- b L16
-L18:
- sub r3, r2, #1
- tst r2, r3
- bne L22
- cmp r6, #0
- movne r4, r0
- andne r5, ip, r3
- stmneia r6, {r4-r5}
-L24:
- rsb r3, r2, #0
- and r3, r2, r3
- clz r3, r3
- rsb r3, r3, #31
- mov r0, ip, lsr r3
- b L46
-L22:
- clz r2, r2
- clz r3, ip
- rsb r3, r3, r2
- cmp r3, #30
- bhi L48
- rsb r2, r3, #31
- add lr, r3, #1
- mov r3, r1, asl r2
- str r3, [sp, #12]
- mov r3, r1, lsr lr
- ldr r0, [sp, #0]
- mov r5, ip, lsr lr
- orr r4, r3, ip, asl r2
- str r0, [sp, #8]
- b L29
-L12:
- ldr r3, [sp, #4]
- cmp r3, #0
- bne L30
- sub r3, r1, #1
- tst r1, r3
- bne L32
- cmp r6, #0
- andne r3, r3, r0
- movne r2, r3
- movne r3, #0
- stmneia r6, {r2-r3}
-L34:
- cmp r1, #1
- beq L10
- rsb r3, r1, #0
- and r3, r1, r3
- clz r3, r3
- rsb r0, r3, #31
- mov r1, ip, lsr r0
- rsb r3, r0, #32
- mov r0, r10, lsr r0
- orr ip, r0, ip, asl r3
- str r1, [sp, #12]
- str ip, [sp, #8]
- ldrd r10, [sp, #8]
- b L10
-L32:
- clz r2, r1
- clz r3, ip
- rsb r3, r3, r2
- rsb r4, r3, #31
- mov r2, r0, asl r4
- mvn r1, r3
- and r2, r2, r1, asr #31
- add lr, r3, #33
- str r2, [sp, #8]
- add r2, r3, #1
- mov r3, r3, asr #31
- and r0, r3, r0, asl r1
- mov r3, r10, lsr r2
- orr r3, r3, ip, asl r4
- and r3, r3, r1, asr #31
- orr r0, r0, r3
- mov r3, ip, lsr lr
- str r0, [sp, #12]
- mov r0, r10, lsr lr
- and r5, r3, r2, asr #31
- rsb r3, lr, #31
- mov r3, r3, asr #31
- orr r0, r0, ip, asl r1
- and r3, r3, ip, lsr r2
- and r0, r0, r2, asr #31
- orr r4, r3, r0
- b L29
-L30:
- clz r2, r3
- clz r3, ip
- rsb r3, r3, r2
- cmp r3, #31
- bls L37
-L48:
- cmp r6, #0
- stmneia r6, {r10-r11}
- b L2
-L37:
- rsb r1, r3, #31
- mov r0, r0, asl r1
- add lr, r3, #1
- mov r2, #0
- str r0, [sp, #12]
- mov r0, r10, lsr lr
- str r2, [sp, #8]
- sub r2, r3, #31
- and r0, r0, r2, asr #31
- mov r3, ip, lsr lr
- orr r4, r0, ip, asl r1
- and r5, r3, r2, asr #31
-L29:
- mov ip, #0
- mov r10, ip
- b L40
-L41:
- ldr r1, [sp, #12]
- ldr r2, [sp, #8]
- mov r3, r4, lsr #31
- orr r5, r3, r5, asl #1
- mov r3, r1, lsr #31
- orr r4, r3, r4, asl #1
- mov r3, r2, lsr #31
- orr r0, r3, r1, asl #1
- orr r1, ip, r2, asl #1
- ldmia sp, {r2-r3}
- str r0, [sp, #12]
- subs r2, r2, r4
- sbc r3, r3, r5
- str r1, [sp, #8]
- subs r0, r2, #1
- sbc r1, r3, #0
- mov r2, r1, asr #31
- ldmia sp, {r0-r1}
- mov r3, r2
- and ip, r2, #1
- and r3, r3, r1
- and r2, r2, r0
- subs r4, r4, r2
- sbc r5, r5, r3
- add r10, r10, #1
-L40:
- cmp r10, lr
- bne L41
- ldrd r0, [sp, #8]
- adds r0, r0, r0
- adc r1, r1, r1
- cmp r6, #0
- orr r10, r0, ip
- mov r11, r1
- stmneia r6, {r4-r5}
- b L10
-L2:
- mov r10, #0
- mov r11, #0
-L10:
- mov r0, r10
- mov r1, r11
- sub sp, r7, #20
- ldmfd sp!, {r10, r11}
- ldmfd sp!, {r4, r5, r6, r7, pc}
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__udivmoddi4)
+
+ASM_PFX(__udivmoddi4):
+ stmfd sp!, {r4, r5, r6, r7, lr}
+ add r7, sp, #12
+ stmfd sp!, {r10, r11}
+ sub sp, sp, #20
+ stmia sp, {r2-r3}
+ ldr r6, [sp, #48]
+ orrs r2, r2, r3
+ mov r10, r0
+ mov r11, r1
+ beq L2
+ subs ip, r1, #0
+ bne L4
+ cmp r3, #0
+ bne L6
+ cmp r6, #0
+ beq L8
+ mov r1, r2
+ bl ASM_PFX(__umodsi3)
+ mov r1, #0
+ stmia r6, {r0-r1}
+L8:
+ ldr r1, [sp, #0]
+ mov r0, r10
+ b L45
+L6:
+ cmp r6, #0
+ movne r1, #0
+ stmneia r6, {r0-r1}
+ b L2
+L4:
+ ldr r1, [sp, #0]
+ cmp r1, #0
+ bne L12
+ ldr r2, [sp, #4]
+ cmp r2, #0
+ bne L14
+ cmp r6, #0
+ beq L16
+ mov r1, r2
+ mov r0, r11
+ bl ASM_PFX(__umodsi3)
+ mov r1, #0
+ stmia r6, {r0-r1}
+L16:
+ ldr r1, [sp, #4]
+ mov r0, r11
+L45:
+ bl ASM_PFX(__udivsi3)
+L46:
+ mov r10, r0
+ mov r11, #0
+ b L10
+L14:
+ subs r1, r0, #0
+ bne L18
+ cmp r6, #0
+ beq L16
+ ldr r1, [sp, #4]
+ mov r0, r11
+ bl ASM_PFX(__umodsi3)
+ mov r4, r10
+ mov r5, r0
+ stmia r6, {r4-r5}
+ b L16
+L18:
+ sub r3, r2, #1
+ tst r2, r3
+ bne L22
+ cmp r6, #0
+ movne r4, r0
+ andne r5, ip, r3
+ stmneia r6, {r4-r5}
+L24:
+ rsb r3, r2, #0
+ and r3, r2, r3
+ clz r3, r3
+ rsb r3, r3, #31
+ mov r0, ip, lsr r3
+ b L46
+L22:
+ clz r2, r2
+ clz r3, ip
+ rsb r3, r3, r2
+ cmp r3, #30
+ bhi L48
+ rsb r2, r3, #31
+ add lr, r3, #1
+ mov r3, r1, asl r2
+ str r3, [sp, #12]
+ mov r3, r1, lsr lr
+ ldr r0, [sp, #0]
+ mov r5, ip, lsr lr
+ orr r4, r3, ip, asl r2
+ str r0, [sp, #8]
+ b L29
+L12:
+ ldr r3, [sp, #4]
+ cmp r3, #0
+ bne L30
+ sub r3, r1, #1
+ tst r1, r3
+ bne L32
+ cmp r6, #0
+ andne r3, r3, r0
+ movne r2, r3
+ movne r3, #0
+ stmneia r6, {r2-r3}
+L34:
+ cmp r1, #1
+ beq L10
+ rsb r3, r1, #0
+ and r3, r1, r3
+ clz r3, r3
+ rsb r0, r3, #31
+ mov r1, ip, lsr r0
+ rsb r3, r0, #32
+ mov r0, r10, lsr r0
+ orr ip, r0, ip, asl r3
+ str r1, [sp, #12]
+ str ip, [sp, #8]
+ ldrd r10, [sp, #8]
+ b L10
+L32:
+ clz r2, r1
+ clz r3, ip
+ rsb r3, r3, r2
+ rsb r4, r3, #31
+ mov r2, r0, asl r4
+ mvn r1, r3
+ and r2, r2, r1, asr #31
+ add lr, r3, #33
+ str r2, [sp, #8]
+ add r2, r3, #1
+ mov r3, r3, asr #31
+ and r0, r3, r0, asl r1
+ mov r3, r10, lsr r2
+ orr r3, r3, ip, asl r4
+ and r3, r3, r1, asr #31
+ orr r0, r0, r3
+ mov r3, ip, lsr lr
+ str r0, [sp, #12]
+ mov r0, r10, lsr lr
+ and r5, r3, r2, asr #31
+ rsb r3, lr, #31
+ mov r3, r3, asr #31
+ orr r0, r0, ip, asl r1
+ and r3, r3, ip, lsr r2
+ and r0, r0, r2, asr #31
+ orr r4, r3, r0
+ b L29
+L30:
+ clz r2, r3
+ clz r3, ip
+ rsb r3, r3, r2
+ cmp r3, #31
+ bls L37
+L48:
+ cmp r6, #0
+ stmneia r6, {r10-r11}
+ b L2
+L37:
+ rsb r1, r3, #31
+ mov r0, r0, asl r1
+ add lr, r3, #1
+ mov r2, #0
+ str r0, [sp, #12]
+ mov r0, r10, lsr lr
+ str r2, [sp, #8]
+ sub r2, r3, #31
+ and r0, r0, r2, asr #31
+ mov r3, ip, lsr lr
+ orr r4, r0, ip, asl r1
+ and r5, r3, r2, asr #31
+L29:
+ mov ip, #0
+ mov r10, ip
+ b L40
+L41:
+ ldr r1, [sp, #12]
+ ldr r2, [sp, #8]
+ mov r3, r4, lsr #31
+ orr r5, r3, r5, asl #1
+ mov r3, r1, lsr #31
+ orr r4, r3, r4, asl #1
+ mov r3, r2, lsr #31
+ orr r0, r3, r1, asl #1
+ orr r1, ip, r2, asl #1
+ ldmia sp, {r2-r3}
+ str r0, [sp, #12]
+ subs r2, r2, r4
+ sbc r3, r3, r5
+ str r1, [sp, #8]
+ subs r0, r2, #1
+ sbc r1, r3, #0
+ mov r2, r1, asr #31
+ ldmia sp, {r0-r1}
+ mov r3, r2
+ and ip, r2, #1
+ and r3, r3, r1
+ and r2, r2, r0
+ subs r4, r4, r2
+ sbc r5, r5, r3
+ add r10, r10, #1
+L40:
+ cmp r10, lr
+ bne L41
+ ldrd r0, [sp, #8]
+ adds r0, r0, r0
+ adc r1, r1, r1
+ cmp r6, #0
+ orr r10, r0, ip
+ mov r11, r1
+ stmneia r6, {r4-r5}
+ b L10
+L2:
+ mov r10, #0
+ mov r11, #0
+L10:
+ mov r0, r10
+ mov r1, r11
+ sub sp, r7, #20
+ ldmfd sp!, {r10, r11}
+ ldmfd sp!, {r4, r5, r6, r7, pc}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.c
index de2264740..829482ddf 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivmoddi4.c
@@ -1,287 +1,287 @@
-/** @file
- Compiler intrinsic for 64-bit compare, ported from LLVM code.
-
- Copyright (c) 2008-2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-// Effects: if rem != 0, *rem = a % b
-// Returns: a / b
-
-// Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide
-
-UINT64
-__udivmoddi4 (UINT64 a, UINT64 b, UINT64* rem)
-{
- const unsigned n_uword_bits = sizeof(UINT32) * CHAR_BIT;
- const unsigned n_udword_bits = sizeof(UINT64) * CHAR_BIT;
- udwords n;
- n.all = a;
- udwords d;
- d.all = b;
- udwords q;
- udwords r;
- unsigned sr;
-
- if (b == 0) {
-// ASSERT (FALSE);
- return 0;
- }
-
- // special cases, X is unknown, K != 0
- if (n.high == 0)
- {
- if (d.high == 0)
- {
- // 0 X
- // ---
- // 0 X
- if (rem)
- *rem = n.low % d.low;
- return n.low / d.low;
- }
- // 0 X
- // ---
- // K X
- if (rem)
- *rem = n.low;
- return 0;
- }
- // n.high != 0
- if (d.low == 0)
- {
- if (d.high == 0)
- {
- // K X
- // ---
- // 0 0
- if (rem)
- *rem = n.high % d.low;
- return n.high / d.low;
- }
- // d.high != 0
- if (n.low == 0)
- {
- // K 0
- // ---
- // K 0
- if (rem)
- {
- r.high = n.high % d.high;
- r.low = 0;
- *rem = r.all;
- }
- return n.high / d.high;
- }
- // K K
- // ---
- // K 0
- if ((d.high & (d.high - 1)) == 0) // if d is a power of 2
- {
- if (rem)
- {
- r.low = n.low;
- r.high = n.high & (d.high - 1);
- *rem = r.all;
- }
- return n.high >> COUNT_TRAILING_ZEROS(d.high);
- }
- // K K
- // ---
- // K 0
- sr = COUNT_LEADING_ZEROS(d.high) - COUNT_LEADING_ZEROS(n.high);
- // 0 <= sr <= n_uword_bits - 2 or sr large
- if (sr > n_uword_bits - 2)
- {
- if (rem)
- *rem = n.all;
- return 0;
- }
- ++sr;
- // 1 <= sr <= n_uword_bits - 1
- // q.all = n.all << (n_udword_bits - sr);
- q.low = 0;
- q.high = n.low << (n_uword_bits - sr);
- // r.all = n.all >> sr;
- r.high = n.high >> sr;
- r.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
- }
- else // d.low != 0
- {
- if (d.high == 0)
- {
- // K X
- // ---
- // 0 K
- if ((d.low & (d.low - 1)) == 0) // if d is a power of 2
- {
- if (rem)
- *rem = n.low & (d.low - 1);
- if (d.low == 1)
- return n.all;
- unsigned sr = COUNT_TRAILING_ZEROS(d.low);
- q.high = n.high >> sr;
- q.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
- return q.all;
- }
- // K X
- // ---
- // 0 K
- sr = 1 + n_uword_bits + COUNT_LEADING_ZEROS(d.low) - COUNT_LEADING_ZEROS(n.high);
- // 2 <= sr <= n_udword_bits - 1
- // q.all = n.all << (n_udword_bits - sr);
- // r.all = n.all >> sr;
- // if (sr == n_uword_bits)
- // {
- // q.low = 0;
- // q.high = n.low;
- // r.high = 0;
- // r.low = n.high;
- // }
- // else if (sr < n_uword_bits) // 2 <= sr <= n_uword_bits - 1
- // {
- // q.low = 0;
- // q.high = n.low << (n_uword_bits - sr);
- // r.high = n.high >> sr;
- // r.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
- // }
- // else // n_uword_bits + 1 <= sr <= n_udword_bits - 1
- // {
- // q.low = n.low << (n_udword_bits - sr);
- // q.high = (n.high << (n_udword_bits - sr)) |
- // (n.low >> (sr - n_uword_bits));
- // r.high = 0;
- // r.low = n.high >> (sr - n_uword_bits);
- // }
- q.low = (n.low << (n_udword_bits - sr)) &
- ((INT32)(n_uword_bits - sr) >> (n_uword_bits-1));
- q.high = ((n.low << ( n_uword_bits - sr)) &
- ((INT32)(sr - n_uword_bits - 1) >> (n_uword_bits-1))) |
- (((n.high << (n_udword_bits - sr)) |
- (n.low >> (sr - n_uword_bits))) &
- ((INT32)(n_uword_bits - sr) >> (n_uword_bits-1)));
- r.high = (n.high >> sr) &
- ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1));
- r.low = ((n.high >> (sr - n_uword_bits)) &
- ((INT32)(n_uword_bits - sr - 1) >> (n_uword_bits-1))) |
- (((n.high << (n_uword_bits - sr)) |
- (n.low >> sr)) &
- ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1)));
- }
- else
- {
- // K X
- // ---
- // K K
- sr = COUNT_LEADING_ZEROS(d.high) - COUNT_LEADING_ZEROS(n.high);
- // 0 <= sr <= n_uword_bits - 1 or sr large
- if (sr > n_uword_bits - 1)
- {
- if (rem)
- *rem = n.all;
- return 0;
- }
- ++sr;
- // 1 <= sr <= n_uword_bits
- // q.all = n.all << (n_udword_bits - sr);
- q.low = 0;
- q.high = n.low << (n_uword_bits - sr);
- // r.all = n.all >> sr;
- // if (sr < n_uword_bits)
- // {
- // r.high = n.high >> sr;
- // r.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
- // }
- // else
- // {
- // r.high = 0;
- // r.low = n.high;
- // }
- r.high = (n.high >> sr) &
- ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1));
- r.low = (n.high << (n_uword_bits - sr)) |
- ((n.low >> sr) &
- ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1)));
- }
- }
- // Not a special case
- // q and r are initialized with:
- // q.all = n.all << (n_udword_bits - sr);
- // r.all = n.all >> sr;
- // 1 <= sr <= n_udword_bits - 1
- UINT32 carry = 0;
- for (; sr > 0; --sr)
- {
- // r:q = ((r:q) << 1) | carry
- r.high = (r.high << 1) | (r.low >> (n_uword_bits - 1));
- r.low = (r.low << 1) | (q.high >> (n_uword_bits - 1));
- q.high = (q.high << 1) | (q.low >> (n_uword_bits - 1));
- q.low = (q.low << 1) | carry;
- // carry = 0;
- // if (r.all >= d.all)
- // {
- // r.all -= d.all;
- // carry = 1;
- // }
- const INT64 s = (INT64)(d.all - r.all - 1) >> (n_udword_bits - 1);
- carry = s & 1;
- r.all -= d.all & s;
- }
- q.all = (q.all << 1) | carry;
- if (rem)
- *rem = r.all;
- return q.all;
-}
+/** @file
+ Compiler intrinsic for 64-bit compare, ported from LLVM code.
+
+ Copyright (c) 2008-2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+// Effects: if rem != 0, *rem = a % b
+// Returns: a / b
+
+// Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide
+
+UINT64
+__udivmoddi4 (UINT64 a, UINT64 b, UINT64* rem)
+{
+ const unsigned n_uword_bits = sizeof(UINT32) * CHAR_BIT;
+ const unsigned n_udword_bits = sizeof(UINT64) * CHAR_BIT;
+ udwords n;
+ n.all = a;
+ udwords d;
+ d.all = b;
+ udwords q;
+ udwords r;
+ unsigned sr;
+
+ if (b == 0) {
+// ASSERT (FALSE);
+ return 0;
+ }
+
+ // special cases, X is unknown, K != 0
+ if (n.high == 0)
+ {
+ if (d.high == 0)
+ {
+ // 0 X
+ // ---
+ // 0 X
+ if (rem)
+ *rem = n.low % d.low;
+ return n.low / d.low;
+ }
+ // 0 X
+ // ---
+ // K X
+ if (rem)
+ *rem = n.low;
+ return 0;
+ }
+ // n.high != 0
+ if (d.low == 0)
+ {
+ if (d.high == 0)
+ {
+ // K X
+ // ---
+ // 0 0
+ if (rem)
+ *rem = n.high % d.low;
+ return n.high / d.low;
+ }
+ // d.high != 0
+ if (n.low == 0)
+ {
+ // K 0
+ // ---
+ // K 0
+ if (rem)
+ {
+ r.high = n.high % d.high;
+ r.low = 0;
+ *rem = r.all;
+ }
+ return n.high / d.high;
+ }
+ // K K
+ // ---
+ // K 0
+ if ((d.high & (d.high - 1)) == 0) // if d is a power of 2
+ {
+ if (rem)
+ {
+ r.low = n.low;
+ r.high = n.high & (d.high - 1);
+ *rem = r.all;
+ }
+ return n.high >> COUNT_TRAILING_ZEROS(d.high);
+ }
+ // K K
+ // ---
+ // K 0
+ sr = COUNT_LEADING_ZEROS(d.high) - COUNT_LEADING_ZEROS(n.high);
+ // 0 <= sr <= n_uword_bits - 2 or sr large
+ if (sr > n_uword_bits - 2)
+ {
+ if (rem)
+ *rem = n.all;
+ return 0;
+ }
+ ++sr;
+ // 1 <= sr <= n_uword_bits - 1
+ // q.all = n.all << (n_udword_bits - sr);
+ q.low = 0;
+ q.high = n.low << (n_uword_bits - sr);
+ // r.all = n.all >> sr;
+ r.high = n.high >> sr;
+ r.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
+ }
+ else // d.low != 0
+ {
+ if (d.high == 0)
+ {
+ // K X
+ // ---
+ // 0 K
+ if ((d.low & (d.low - 1)) == 0) // if d is a power of 2
+ {
+ if (rem)
+ *rem = n.low & (d.low - 1);
+ if (d.low == 1)
+ return n.all;
+ unsigned sr = COUNT_TRAILING_ZEROS(d.low);
+ q.high = n.high >> sr;
+ q.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
+ return q.all;
+ }
+ // K X
+ // ---
+ // 0 K
+ sr = 1 + n_uword_bits + COUNT_LEADING_ZEROS(d.low) - COUNT_LEADING_ZEROS(n.high);
+ // 2 <= sr <= n_udword_bits - 1
+ // q.all = n.all << (n_udword_bits - sr);
+ // r.all = n.all >> sr;
+ // if (sr == n_uword_bits)
+ // {
+ // q.low = 0;
+ // q.high = n.low;
+ // r.high = 0;
+ // r.low = n.high;
+ // }
+ // else if (sr < n_uword_bits) // 2 <= sr <= n_uword_bits - 1
+ // {
+ // q.low = 0;
+ // q.high = n.low << (n_uword_bits - sr);
+ // r.high = n.high >> sr;
+ // r.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
+ // }
+ // else // n_uword_bits + 1 <= sr <= n_udword_bits - 1
+ // {
+ // q.low = n.low << (n_udword_bits - sr);
+ // q.high = (n.high << (n_udword_bits - sr)) |
+ // (n.low >> (sr - n_uword_bits));
+ // r.high = 0;
+ // r.low = n.high >> (sr - n_uword_bits);
+ // }
+ q.low = (n.low << (n_udword_bits - sr)) &
+ ((INT32)(n_uword_bits - sr) >> (n_uword_bits-1));
+ q.high = ((n.low << ( n_uword_bits - sr)) &
+ ((INT32)(sr - n_uword_bits - 1) >> (n_uword_bits-1))) |
+ (((n.high << (n_udword_bits - sr)) |
+ (n.low >> (sr - n_uword_bits))) &
+ ((INT32)(n_uword_bits - sr) >> (n_uword_bits-1)));
+ r.high = (n.high >> sr) &
+ ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1));
+ r.low = ((n.high >> (sr - n_uword_bits)) &
+ ((INT32)(n_uword_bits - sr - 1) >> (n_uword_bits-1))) |
+ (((n.high << (n_uword_bits - sr)) |
+ (n.low >> sr)) &
+ ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1)));
+ }
+ else
+ {
+ // K X
+ // ---
+ // K K
+ sr = COUNT_LEADING_ZEROS(d.high) - COUNT_LEADING_ZEROS(n.high);
+ // 0 <= sr <= n_uword_bits - 1 or sr large
+ if (sr > n_uword_bits - 1)
+ {
+ if (rem)
+ *rem = n.all;
+ return 0;
+ }
+ ++sr;
+ // 1 <= sr <= n_uword_bits
+ // q.all = n.all << (n_udword_bits - sr);
+ q.low = 0;
+ q.high = n.low << (n_uword_bits - sr);
+ // r.all = n.all >> sr;
+ // if (sr < n_uword_bits)
+ // {
+ // r.high = n.high >> sr;
+ // r.low = (n.high << (n_uword_bits - sr)) | (n.low >> sr);
+ // }
+ // else
+ // {
+ // r.high = 0;
+ // r.low = n.high;
+ // }
+ r.high = (n.high >> sr) &
+ ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1));
+ r.low = (n.high << (n_uword_bits - sr)) |
+ ((n.low >> sr) &
+ ((INT32)(sr - n_uword_bits) >> (n_uword_bits-1)));
+ }
+ }
+ // Not a special case
+ // q and r are initialized with:
+ // q.all = n.all << (n_udword_bits - sr);
+ // r.all = n.all >> sr;
+ // 1 <= sr <= n_udword_bits - 1
+ UINT32 carry = 0;
+ for (; sr > 0; --sr)
+ {
+ // r:q = ((r:q) << 1) | carry
+ r.high = (r.high << 1) | (r.low >> (n_uword_bits - 1));
+ r.low = (r.low << 1) | (q.high >> (n_uword_bits - 1));
+ q.high = (q.high << 1) | (q.low >> (n_uword_bits - 1));
+ q.low = (q.low << 1) | carry;
+ // carry = 0;
+ // if (r.all >= d.all)
+ // {
+ // r.all -= d.all;
+ // carry = 1;
+ // }
+ const INT64 s = (INT64)(d.all - r.all - 1) >> (n_udword_bits - 1);
+ carry = s & 1;
+ r.all -= d.all & s;
+ }
+ q.all = (q.all << 1) | carry;
+ if (rem)
+ *rem = r.all;
+ return q.all;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.S
index 92c9cad96..a9223d7fb 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.S
@@ -1,57 +1,57 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__udivsi3)
-
-ASM_PFX(__udivsi3):
- cmp r1, #0
- cmpne r0, #0
- stmfd sp!, {r4, r5, r7, lr}
- add r7, sp, #8
- beq L2
- clz r2, r1
- clz r3, r0
- rsb r3, r3, r2
- cmp r3, #31
- bhi L2
- ldmeqfd sp!, {r4, r5, r7, pc}
- add r5, r3, #1
- rsb r3, r3, #31
- mov lr, #0
- mov r2, r0, asl r3
- mov ip, r0, lsr r5
- mov r4, lr
- b L8
-L9:
- mov r0, r2, lsr #31
- orr ip, r0, ip, asl #1
- orr r2, r3, lr
- rsb r3, ip, r1
- sub r3, r3, #1
- and r0, r1, r3, asr #31
- mov lr, r3, lsr #31
- rsb ip, r0, ip
- add r4, r4, #1
-L8:
- cmp r4, r5
- mov r3, r2, asl #1
- bne L9
- orr r0, r3, lr
- ldmfd sp!, {r4, r5, r7, pc}
-L2:
- mov r0, #0
- ldmfd sp!, {r4, r5, r7, pc}
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__udivsi3)
+
+ASM_PFX(__udivsi3):
+ cmp r1, #0
+ cmpne r0, #0
+ stmfd sp!, {r4, r5, r7, lr}
+ add r7, sp, #8
+ beq L2
+ clz r2, r1
+ clz r3, r0
+ rsb r3, r3, r2
+ cmp r3, #31
+ bhi L2
+ ldmeqfd sp!, {r4, r5, r7, pc}
+ add r5, r3, #1
+ rsb r3, r3, #31
+ mov lr, #0
+ mov r2, r0, asl r3
+ mov ip, r0, lsr r5
+ mov r4, lr
+ b L8
+L9:
+ mov r0, r2, lsr #31
+ orr ip, r0, ip, asl #1
+ orr r2, r3, lr
+ rsb r3, ip, r1
+ sub r3, r3, #1
+ and r0, r1, r3, asr #31
+ mov lr, r3, lsr #31
+ rsb ip, r0, ip
+ add r4, r4, #1
+L8:
+ cmp r4, r5
+ mov r3, r2, asl #1
+ bne L9
+ orr r0, r3, lr
+ ldmfd sp!, {r4, r5, r7, pc}
+L2:
+ mov r0, #0
+ ldmfd sp!, {r4, r5, r7, pc}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.c
index aec1a1ccb..020b3fadc 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/udivsi3.c
@@ -1,111 +1,111 @@
-/** @file
- Compiler intrinsic for 32-bit unsigned div, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-
-// Returns: n / d
-
-// Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide
-
-UINT32
-__udivsi3(UINT32 n, UINT32 d)
-{
- const unsigned n_uword_bits = sizeof(UINT32) * CHAR_BIT;
- UINT32 q;
- UINT32 r;
- unsigned sr;
-
- // special cases
- if (d == 0) {
-// ASSERT (FALSE);
- return 0; // ?!
- }
- if (n == 0)
- return 0;
-
- sr = COUNT_LEADING_ZEROS(d) - COUNT_LEADING_ZEROS(n);
- // 0 <= sr <= n_uword_bits - 1 or sr large
- if (sr > n_uword_bits - 1) // d > r
- return 0;
- if (sr == n_uword_bits - 1) // d == 1
- return n;
- ++sr;
- // 1 <= sr <= n_uword_bits - 1
- // Not a special case
- q = n << (n_uword_bits - sr);
- r = n >> sr;
- UINT32 carry = 0;
- for (; sr > 0; --sr)
- {
- // r:q = ((r:q) << 1) | carry
- r = (r << 1) | (q >> (n_uword_bits - 1));
- q = (q << 1) | carry;
- // carry = 0;
- // if (r.all >= d.all)
- // {
- // r.all -= d.all;
- // carry = 1;
- // }
- const INT32 s = (INT32)(d - r - 1) >> (n_uword_bits - 1);
- carry = s & 1;
- r -= d & s;
- }
- q = (q << 1) | carry;
- return q;
-}
+/** @file
+ Compiler intrinsic for 32-bit unsigned div, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+
+// Returns: n / d
+
+// Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide
+
+UINT32
+__udivsi3(UINT32 n, UINT32 d)
+{
+ const unsigned n_uword_bits = sizeof(UINT32) * CHAR_BIT;
+ UINT32 q;
+ UINT32 r;
+ unsigned sr;
+
+ // special cases
+ if (d == 0) {
+// ASSERT (FALSE);
+ return 0; // ?!
+ }
+ if (n == 0)
+ return 0;
+
+ sr = COUNT_LEADING_ZEROS(d) - COUNT_LEADING_ZEROS(n);
+ // 0 <= sr <= n_uword_bits - 1 or sr large
+ if (sr > n_uword_bits - 1) // d > r
+ return 0;
+ if (sr == n_uword_bits - 1) // d == 1
+ return n;
+ ++sr;
+ // 1 <= sr <= n_uword_bits - 1
+ // Not a special case
+ q = n << (n_uword_bits - sr);
+ r = n >> sr;
+ UINT32 carry = 0;
+ for (; sr > 0; --sr)
+ {
+ // r:q = ((r:q) << 1) | carry
+ r = (r << 1) | (q >> (n_uword_bits - 1));
+ q = (q << 1) | carry;
+ // carry = 0;
+ // if (r.all >= d.all)
+ // {
+ // r.all -= d.all;
+ // carry = 1;
+ // }
+ const INT32 s = (INT32)(d - r - 1) >> (n_uword_bits - 1);
+ carry = s & 1;
+ r -= d & s;
+ }
+ q = (q << 1) | carry;
+ return q;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.S
index 6b55135f3..75b0bb93a 100755
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.S
@@ -1,267 +1,267 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
-
- .text
- .align 2
- GCC_ASM_EXPORT(__aeabi_uldivmod)
-
-//
-//UINT64
-//EFIAPI
-//__aeabi_uldivmod (
-// IN UINT64 Dividend
-// IN UINT64 Divisor
-// )
-//
-ASM_PFX(__aeabi_uldivmod):
- stmdb sp!, {r4, r5, r6, lr}
- mov r4, r1
- mov r5, r0
- mov r6, #0 // 0x0
- orrs ip, r3, r2, lsr #31
- bne ASM_PFX(__aeabi_uldivmod_label1)
- tst r2, r2
- beq ASM_PFX(_ll_div0)
- movs ip, r2, lsr #15
- addeq r6, r6, #16 // 0x10
- mov ip, r2, lsl r6
- movs lr, ip, lsr #23
- moveq ip, ip, lsl #8
- addeq r6, r6, #8 // 0x8
- movs lr, ip, lsr #27
- moveq ip, ip, lsl #4
- addeq r6, r6, #4 // 0x4
- movs lr, ip, lsr #29
- moveq ip, ip, lsl #2
- addeq r6, r6, #2 // 0x2
- movs lr, ip, lsr #30
- moveq ip, ip, lsl #1
- addeq r6, r6, #1 // 0x1
- b ASM_PFX(_ll_udiv_small)
-ASM_PFX(__aeabi_uldivmod_label1):
- tst r3, #-2147483648 // 0x80000000
- bne ASM_PFX(__aeabi_uldivmod_label2)
- movs ip, r3, lsr #15
- addeq r6, r6, #16 // 0x10
- mov ip, r3, lsl r6
- movs lr, ip, lsr #23
- moveq ip, ip, lsl #8
- addeq r6, r6, #8 // 0x8
- movs lr, ip, lsr #27
- moveq ip, ip, lsl #4
- addeq r6, r6, #4 // 0x4
- movs lr, ip, lsr #29
- moveq ip, ip, lsl #2
- addeq r6, r6, #2 // 0x2
- movs lr, ip, lsr #30
- addeq r6, r6, #1 // 0x1
- rsb r3, r6, #32 // 0x20
- moveq ip, ip, lsl #1
- orr ip, ip, r2, lsr r3
- mov lr, r2, lsl r6
- b ASM_PFX(_ll_udiv_big)
-ASM_PFX(__aeabi_uldivmod_label2):
- mov ip, r3
- mov lr, r2
- b ASM_PFX(_ll_udiv_ginormous)
-
-ASM_PFX(_ll_udiv_small):
- cmp r4, ip, lsl #1
- mov r3, #0 // 0x0
- subcs r4, r4, ip, lsl #1
- addcs r3, r3, #2 // 0x2
- cmp r4, ip
- subcs r4, r4, ip
- adcs r3, r3, #0 // 0x0
- add r2, r6, #32 // 0x20
- cmp r2, #32 // 0x20
- rsb ip, ip, #0 // 0x0
- bcc ASM_PFX(_ll_udiv_small_label1)
- orrs r0, r4, r5, lsr #30
- moveq r4, r5
- moveq r5, #0 // 0x0
- subeq r2, r2, #32 // 0x20
-ASM_PFX(_ll_udiv_small_label1):
- mov r1, #0 // 0x0
- cmp r2, #16 // 0x10
- bcc ASM_PFX(_ll_udiv_small_label2)
- movs r0, r4, lsr #14
- moveq r4, r4, lsl #16
- addeq r1, r1, #16 // 0x10
-ASM_PFX(_ll_udiv_small_label2):
- sub lr, r2, r1
- cmp lr, #8 // 0x8
- bcc ASM_PFX(_ll_udiv_small_label3)
- movs r0, r4, lsr #22
- moveq r4, r4, lsl #8
- addeq r1, r1, #8 // 0x8
-ASM_PFX(_ll_udiv_small_label3):
- rsb r0, r1, #32 // 0x20
- sub r2, r2, r1
- orr r4, r4, r5, lsr r0
- mov r5, r5, lsl r1
- cmp r2, #1 // 0x1
- bcc ASM_PFX(_ll_udiv_small_label5)
- sub r2, r2, #1 // 0x1
- and r0, r2, #7 // 0x7
- eor r0, r0, #7 // 0x7
- adds r0, r0, r0, lsl #1
- add pc, pc, r0, lsl #2
- nop // (mov r0,r0)
-ASM_PFX(_ll_udiv_small_label4):
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- sub r2, r2, #8 // 0x8
- tst r2, r2
- rsbcc r4, ip, r4
- bpl ASM_PFX(_ll_udiv_small_label4)
-ASM_PFX(_ll_udiv_small_label5):
- mov r2, r4, lsr r6
- bic r4, r4, r2, lsl r6
- adcs r0, r5, r5
- adc r1, r4, r4
- add r1, r1, r3, lsl r6
- mov r3, #0 // 0x0
- ldmia sp!, {r4, r5, r6, pc}
-
-ASM_PFX(_ll_udiv_big):
- subs r0, r5, lr
- mov r3, #0 // 0x0
- sbcs r1, r4, ip
- movcs r5, r0
- movcs r4, r1
- adcs r3, r3, #0 // 0x0
- subs r0, r5, lr
- sbcs r1, r4, ip
- movcs r5, r0
- movcs r4, r1
- adcs r3, r3, #0 // 0x0
- subs r0, r5, lr
- sbcs r1, r4, ip
- movcs r5, r0
- movcs r4, r1
- adcs r3, r3, #0 // 0x0
- mov r1, #0 // 0x0
- rsbs lr, lr, #0 // 0x0
- rsc ip, ip, #0 // 0x0
- cmp r6, #16 // 0x10
- bcc ASM_PFX(_ll_udiv_big_label1)
- movs r0, r4, lsr #14
- moveq r4, r4, lsl #16
- addeq r1, r1, #16 // 0x10
-ASM_PFX(_ll_udiv_big_label1):
- sub r2, r6, r1
- cmp r2, #8 // 0x8
- bcc ASM_PFX(_ll_udiv_big_label2)
- movs r0, r4, lsr #22
- moveq r4, r4, lsl #8
- addeq r1, r1, #8 // 0x8
-ASM_PFX(_ll_udiv_big_label2):
- rsb r0, r1, #32 // 0x20
- sub r2, r6, r1
- orr r4, r4, r5, lsr r0
- mov r5, r5, lsl r1
- cmp r2, #1 // 0x1
- bcc ASM_PFX(_ll_udiv_big_label4)
- sub r2, r2, #1 // 0x1
- and r0, r2, #3 // 0x3
- rsb r0, r0, #3 // 0x3
- adds r0, r0, r0, lsl #1
- add pc, pc, r0, lsl #3
- nop // (mov r0,r0)
-ASM_PFX(_ll_udiv_big_label3):
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- movcs r5, r0
- movcs r4, r1
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- movcs r5, r0
- movcs r4, r1
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- movcs r5, r0
- movcs r4, r1
- sub r2, r2, #4 // 0x4
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- tst r2, r2
- movcs r5, r0
- movcs r4, r1
- bpl ASM_PFX(_ll_udiv_big_label3)
-ASM_PFX(_ll_udiv_big_label4):
- mov r1, #0 // 0x0
- mov r2, r5, lsr r6
- bic r5, r5, r2, lsl r6
- adcs r0, r5, r5
- adc r1, r1, #0 // 0x0
- movs lr, r3, lsl r6
- mov r3, r4, lsr r6
- bic r4, r4, r3, lsl r6
- adc r1, r1, #0 // 0x0
- adds r0, r0, lr
- orr r2, r2, r4, ror r6
- adc r1, r1, #0 // 0x0
- ldmia sp!, {r4, r5, r6, pc}
-
-ASM_PFX(_ll_udiv_ginormous):
- subs r2, r5, lr
- mov r1, #0 // 0x0
- sbcs r3, r4, ip
- adc r0, r1, r1
- movcc r2, r5
- movcc r3, r4
- ldmia sp!, {r4, r5, r6, pc}
-
-ASM_PFX(_ll_div0):
- ldmia sp!, {r4, r5, r6, lr}
- mov r0, #0 // 0x0
- mov r1, #0 // 0x0
- b ASM_PFX(__aeabi_ldiv0)
-
-ASM_PFX(__aeabi_ldiv0):
- bx r14
-
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__aeabi_uldivmod)
+
+//
+//UINT64
+//EFIAPI
+//__aeabi_uldivmod (
+// IN UINT64 Dividend
+// IN UINT64 Divisor
+// )
+//
+ASM_PFX(__aeabi_uldivmod):
+ stmdb sp!, {r4, r5, r6, lr}
+ mov r4, r1
+ mov r5, r0
+ mov r6, #0 // 0x0
+ orrs ip, r3, r2, lsr #31
+ bne ASM_PFX(__aeabi_uldivmod_label1)
+ tst r2, r2
+ beq ASM_PFX(_ll_div0)
+ movs ip, r2, lsr #15
+ addeq r6, r6, #16 // 0x10
+ mov ip, r2, lsl r6
+ movs lr, ip, lsr #23
+ moveq ip, ip, lsl #8
+ addeq r6, r6, #8 // 0x8
+ movs lr, ip, lsr #27
+ moveq ip, ip, lsl #4
+ addeq r6, r6, #4 // 0x4
+ movs lr, ip, lsr #29
+ moveq ip, ip, lsl #2
+ addeq r6, r6, #2 // 0x2
+ movs lr, ip, lsr #30
+ moveq ip, ip, lsl #1
+ addeq r6, r6, #1 // 0x1
+ b ASM_PFX(_ll_udiv_small)
+ASM_PFX(__aeabi_uldivmod_label1):
+ tst r3, #-2147483648 // 0x80000000
+ bne ASM_PFX(__aeabi_uldivmod_label2)
+ movs ip, r3, lsr #15
+ addeq r6, r6, #16 // 0x10
+ mov ip, r3, lsl r6
+ movs lr, ip, lsr #23
+ moveq ip, ip, lsl #8
+ addeq r6, r6, #8 // 0x8
+ movs lr, ip, lsr #27
+ moveq ip, ip, lsl #4
+ addeq r6, r6, #4 // 0x4
+ movs lr, ip, lsr #29
+ moveq ip, ip, lsl #2
+ addeq r6, r6, #2 // 0x2
+ movs lr, ip, lsr #30
+ addeq r6, r6, #1 // 0x1
+ rsb r3, r6, #32 // 0x20
+ moveq ip, ip, lsl #1
+ orr ip, ip, r2, lsr r3
+ mov lr, r2, lsl r6
+ b ASM_PFX(_ll_udiv_big)
+ASM_PFX(__aeabi_uldivmod_label2):
+ mov ip, r3
+ mov lr, r2
+ b ASM_PFX(_ll_udiv_ginormous)
+
+ASM_PFX(_ll_udiv_small):
+ cmp r4, ip, lsl #1
+ mov r3, #0 // 0x0
+ subcs r4, r4, ip, lsl #1
+ addcs r3, r3, #2 // 0x2
+ cmp r4, ip
+ subcs r4, r4, ip
+ adcs r3, r3, #0 // 0x0
+ add r2, r6, #32 // 0x20
+ cmp r2, #32 // 0x20
+ rsb ip, ip, #0 // 0x0
+ bcc ASM_PFX(_ll_udiv_small_label1)
+ orrs r0, r4, r5, lsr #30
+ moveq r4, r5
+ moveq r5, #0 // 0x0
+ subeq r2, r2, #32 // 0x20
+ASM_PFX(_ll_udiv_small_label1):
+ mov r1, #0 // 0x0
+ cmp r2, #16 // 0x10
+ bcc ASM_PFX(_ll_udiv_small_label2)
+ movs r0, r4, lsr #14
+ moveq r4, r4, lsl #16
+ addeq r1, r1, #16 // 0x10
+ASM_PFX(_ll_udiv_small_label2):
+ sub lr, r2, r1
+ cmp lr, #8 // 0x8
+ bcc ASM_PFX(_ll_udiv_small_label3)
+ movs r0, r4, lsr #22
+ moveq r4, r4, lsl #8
+ addeq r1, r1, #8 // 0x8
+ASM_PFX(_ll_udiv_small_label3):
+ rsb r0, r1, #32 // 0x20
+ sub r2, r2, r1
+ orr r4, r4, r5, lsr r0
+ mov r5, r5, lsl r1
+ cmp r2, #1 // 0x1
+ bcc ASM_PFX(_ll_udiv_small_label5)
+ sub r2, r2, #1 // 0x1
+ and r0, r2, #7 // 0x7
+ eor r0, r0, #7 // 0x7
+ adds r0, r0, r0, lsl #1
+ add pc, pc, r0, lsl #2
+ nop // (mov r0,r0)
+ASM_PFX(_ll_udiv_small_label4):
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ sub r2, r2, #8 // 0x8
+ tst r2, r2
+ rsbcc r4, ip, r4
+ bpl ASM_PFX(_ll_udiv_small_label4)
+ASM_PFX(_ll_udiv_small_label5):
+ mov r2, r4, lsr r6
+ bic r4, r4, r2, lsl r6
+ adcs r0, r5, r5
+ adc r1, r4, r4
+ add r1, r1, r3, lsl r6
+ mov r3, #0 // 0x0
+ ldmia sp!, {r4, r5, r6, pc}
+
+ASM_PFX(_ll_udiv_big):
+ subs r0, r5, lr
+ mov r3, #0 // 0x0
+ sbcs r1, r4, ip
+ movcs r5, r0
+ movcs r4, r1
+ adcs r3, r3, #0 // 0x0
+ subs r0, r5, lr
+ sbcs r1, r4, ip
+ movcs r5, r0
+ movcs r4, r1
+ adcs r3, r3, #0 // 0x0
+ subs r0, r5, lr
+ sbcs r1, r4, ip
+ movcs r5, r0
+ movcs r4, r1
+ adcs r3, r3, #0 // 0x0
+ mov r1, #0 // 0x0
+ rsbs lr, lr, #0 // 0x0
+ rsc ip, ip, #0 // 0x0
+ cmp r6, #16 // 0x10
+ bcc ASM_PFX(_ll_udiv_big_label1)
+ movs r0, r4, lsr #14
+ moveq r4, r4, lsl #16
+ addeq r1, r1, #16 // 0x10
+ASM_PFX(_ll_udiv_big_label1):
+ sub r2, r6, r1
+ cmp r2, #8 // 0x8
+ bcc ASM_PFX(_ll_udiv_big_label2)
+ movs r0, r4, lsr #22
+ moveq r4, r4, lsl #8
+ addeq r1, r1, #8 // 0x8
+ASM_PFX(_ll_udiv_big_label2):
+ rsb r0, r1, #32 // 0x20
+ sub r2, r6, r1
+ orr r4, r4, r5, lsr r0
+ mov r5, r5, lsl r1
+ cmp r2, #1 // 0x1
+ bcc ASM_PFX(_ll_udiv_big_label4)
+ sub r2, r2, #1 // 0x1
+ and r0, r2, #3 // 0x3
+ rsb r0, r0, #3 // 0x3
+ adds r0, r0, r0, lsl #1
+ add pc, pc, r0, lsl #3
+ nop // (mov r0,r0)
+ASM_PFX(_ll_udiv_big_label3):
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ movcs r5, r0
+ movcs r4, r1
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ movcs r5, r0
+ movcs r4, r1
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ movcs r5, r0
+ movcs r4, r1
+ sub r2, r2, #4 // 0x4
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ tst r2, r2
+ movcs r5, r0
+ movcs r4, r1
+ bpl ASM_PFX(_ll_udiv_big_label3)
+ASM_PFX(_ll_udiv_big_label4):
+ mov r1, #0 // 0x0
+ mov r2, r5, lsr r6
+ bic r5, r5, r2, lsl r6
+ adcs r0, r5, r5
+ adc r1, r1, #0 // 0x0
+ movs lr, r3, lsl r6
+ mov r3, r4, lsr r6
+ bic r4, r4, r3, lsl r6
+ adc r1, r1, #0 // 0x0
+ adds r0, r0, lr
+ orr r2, r2, r4, ror r6
+ adc r1, r1, #0 // 0x0
+ ldmia sp!, {r4, r5, r6, pc}
+
+ASM_PFX(_ll_udiv_ginormous):
+ subs r2, r5, lr
+ mov r1, #0 // 0x0
+ sbcs r3, r4, ip
+ adc r0, r1, r1
+ movcc r2, r5
+ movcc r3, r4
+ ldmia sp!, {r4, r5, r6, pc}
+
+ASM_PFX(_ll_div0):
+ ldmia sp!, {r4, r5, r6, lr}
+ mov r0, #0 // 0x0
+ mov r1, #0 // 0x0
+ b ASM_PFX(__aeabi_ldiv0)
+
+ASM_PFX(__aeabi_ldiv0):
+ bx r14
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.asm
index d792342e1..393794c13 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldiv.asm
@@ -1,268 +1,268 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
-
- EXPORT __aeabi_uldivmod
-
- AREA Uldivmod, CODE, READONLY
-
-;
-;UINT64
-;EFIAPI
-;__aeabi_uldivmod (
-; IN UINT64 Dividend
-; IN UINT64 Divisor
-; )
-;
-__aeabi_uldivmod
- stmdb sp!, {r4, r5, r6, lr}
- mov r4, r1
- mov r5, r0
- mov r6, #0 ; 0x0
- orrs ip, r3, r2, lsr #31
- bne __aeabi_uldivmod_label1
- tst r2, r2
- beq _ll_div0
- movs ip, r2, lsr #15
- addeq r6, r6, #16 ; 0x10
- mov ip, r2, lsl r6
- movs lr, ip, lsr #23
- moveq ip, ip, lsl #8
- addeq r6, r6, #8 ; 0x8
- movs lr, ip, lsr #27
- moveq ip, ip, lsl #4
- addeq r6, r6, #4 ; 0x4
- movs lr, ip, lsr #29
- moveq ip, ip, lsl #2
- addeq r6, r6, #2 ; 0x2
- movs lr, ip, lsr #30
- moveq ip, ip, lsl #1
- addeq r6, r6, #1 ; 0x1
- b _ll_udiv_small
-__aeabi_uldivmod_label1
- tst r3, #-2147483648 ; 0x80000000
- bne __aeabi_uldivmod_label2
- movs ip, r3, lsr #15
- addeq r6, r6, #16 ; 0x10
- mov ip, r3, lsl r6
- movs lr, ip, lsr #23
- moveq ip, ip, lsl #8
- addeq r6, r6, #8 ; 0x8
- movs lr, ip, lsr #27
- moveq ip, ip, lsl #4
- addeq r6, r6, #4 ; 0x4
- movs lr, ip, lsr #29
- moveq ip, ip, lsl #2
- addeq r6, r6, #2 ; 0x2
- movs lr, ip, lsr #30
- addeq r6, r6, #1 ; 0x1
- rsb r3, r6, #32 ; 0x20
- moveq ip, ip, lsl #1
- orr ip, ip, r2, lsr r3
- mov lr, r2, lsl r6
- b _ll_udiv_big
-__aeabi_uldivmod_label2
- mov ip, r3
- mov lr, r2
- b _ll_udiv_ginormous
-
-_ll_udiv_small
- cmp r4, ip, lsl #1
- mov r3, #0 ; 0x0
- subcs r4, r4, ip, lsl #1
- addcs r3, r3, #2 ; 0x2
- cmp r4, ip
- subcs r4, r4, ip
- adcs r3, r3, #0 ; 0x0
- add r2, r6, #32 ; 0x20
- cmp r2, #32 ; 0x20
- rsb ip, ip, #0 ; 0x0
- bcc _ll_udiv_small_label1
- orrs r0, r4, r5, lsr #30
- moveq r4, r5
- moveq r5, #0 ; 0x0
- subeq r2, r2, #32 ; 0x20
-_ll_udiv_small_label1
- mov r1, #0 ; 0x0
- cmp r2, #16 ; 0x10
- bcc _ll_udiv_small_label2
- movs r0, r4, lsr #14
- moveq r4, r4, lsl #16
- addeq r1, r1, #16 ; 0x10
-_ll_udiv_small_label2
- sub lr, r2, r1
- cmp lr, #8 ; 0x8
- bcc _ll_udiv_small_label3
- movs r0, r4, lsr #22
- moveq r4, r4, lsl #8
- addeq r1, r1, #8 ; 0x8
-_ll_udiv_small_label3
- rsb r0, r1, #32 ; 0x20
- sub r2, r2, r1
- orr r4, r4, r5, lsr r0
- mov r5, r5, lsl r1
- cmp r2, #1 ; 0x1
- bcc _ll_udiv_small_label5
- sub r2, r2, #1 ; 0x1
- and r0, r2, #7 ; 0x7
- eor r0, r0, #7 ; 0x7
- adds r0, r0, r0, lsl #1
- add pc, pc, r0, lsl #2
- nop ; (mov r0,r0)
-_ll_udiv_small_label4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- rsbcc r4, ip, r4
- adcs r5, r5, r5
- adcs r4, ip, r4, lsl #1
- sub r2, r2, #8 ; 0x8
- tst r2, r2
- rsbcc r4, ip, r4
- bpl _ll_udiv_small_label4
-_ll_udiv_small_label5
- mov r2, r4, lsr r6
- bic r4, r4, r2, lsl r6
- adcs r0, r5, r5
- adc r1, r4, r4
- add r1, r1, r3, lsl r6
- mov r3, #0 ; 0x0
- ldmia sp!, {r4, r5, r6, pc}
-
-_ll_udiv_big
- subs r0, r5, lr
- mov r3, #0 ; 0x0
- sbcs r1, r4, ip
- movcs r5, r0
- movcs r4, r1
- adcs r3, r3, #0 ; 0x0
- subs r0, r5, lr
- sbcs r1, r4, ip
- movcs r5, r0
- movcs r4, r1
- adcs r3, r3, #0 ; 0x0
- subs r0, r5, lr
- sbcs r1, r4, ip
- movcs r5, r0
- movcs r4, r1
- adcs r3, r3, #0 ; 0x0
- mov r1, #0 ; 0x0
- rsbs lr, lr, #0 ; 0x0
- rsc ip, ip, #0 ; 0x0
- cmp r6, #16 ; 0x10
- bcc _ll_udiv_big_label1
- movs r0, r4, lsr #14
- moveq r4, r4, lsl #16
- addeq r1, r1, #16 ; 0x10
-_ll_udiv_big_label1
- sub r2, r6, r1
- cmp r2, #8 ; 0x8
- bcc _ll_udiv_big_label2
- movs r0, r4, lsr #22
- moveq r4, r4, lsl #8
- addeq r1, r1, #8 ; 0x8
-_ll_udiv_big_label2
- rsb r0, r1, #32 ; 0x20
- sub r2, r6, r1
- orr r4, r4, r5, lsr r0
- mov r5, r5, lsl r1
- cmp r2, #1 ; 0x1
- bcc _ll_udiv_big_label4
- sub r2, r2, #1 ; 0x1
- and r0, r2, #3 ; 0x3
- rsb r0, r0, #3 ; 0x3
- adds r0, r0, r0, lsl #1
- add pc, pc, r0, lsl #3
- nop ; (mov r0,r0)
-_ll_udiv_big_label3
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- movcs r5, r0
- movcs r4, r1
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- movcs r5, r0
- movcs r4, r1
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- movcs r5, r0
- movcs r4, r1
- sub r2, r2, #4 ; 0x4
- adcs r5, r5, r5
- adcs r4, r4, r4
- adcs r0, lr, r5
- adcs r1, ip, r4
- tst r2, r2
- movcs r5, r0
- movcs r4, r1
- bpl _ll_udiv_big_label3
-_ll_udiv_big_label4
- mov r1, #0 ; 0x0
- mov r2, r5, lsr r6
- bic r5, r5, r2, lsl r6
- adcs r0, r5, r5
- adc r1, r1, #0 ; 0x0
- movs lr, r3, lsl r6
- mov r3, r4, lsr r6
- bic r4, r4, r3, lsl r6
- adc r1, r1, #0 ; 0x0
- adds r0, r0, lr
- orr r2, r2, r4, ror r6
- adc r1, r1, #0 ; 0x0
- ldmia sp!, {r4, r5, r6, pc}
-
-_ll_udiv_ginormous
- subs r2, r5, lr
- mov r1, #0 ; 0x0
- sbcs r3, r4, ip
- adc r0, r1, r1
- movcc r2, r5
- movcc r3, r4
- ldmia sp!, {r4, r5, r6, pc}
-
-_ll_div0
- ldmia sp!, {r4, r5, r6, lr}
- mov r0, #0 ; 0x0
- mov r1, #0 ; 0x0
- b __aeabi_ldiv0
-
-__aeabi_ldiv0
- BX r14
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+
+ EXPORT __aeabi_uldivmod
+
+ AREA Uldivmod, CODE, READONLY
+
+;
+;UINT64
+;EFIAPI
+;__aeabi_uldivmod (
+; IN UINT64 Dividend
+; IN UINT64 Divisor
+; )
+;
+__aeabi_uldivmod
+ stmdb sp!, {r4, r5, r6, lr}
+ mov r4, r1
+ mov r5, r0
+ mov r6, #0 ; 0x0
+ orrs ip, r3, r2, lsr #31
+ bne __aeabi_uldivmod_label1
+ tst r2, r2
+ beq _ll_div0
+ movs ip, r2, lsr #15
+ addeq r6, r6, #16 ; 0x10
+ mov ip, r2, lsl r6
+ movs lr, ip, lsr #23
+ moveq ip, ip, lsl #8
+ addeq r6, r6, #8 ; 0x8
+ movs lr, ip, lsr #27
+ moveq ip, ip, lsl #4
+ addeq r6, r6, #4 ; 0x4
+ movs lr, ip, lsr #29
+ moveq ip, ip, lsl #2
+ addeq r6, r6, #2 ; 0x2
+ movs lr, ip, lsr #30
+ moveq ip, ip, lsl #1
+ addeq r6, r6, #1 ; 0x1
+ b _ll_udiv_small
+__aeabi_uldivmod_label1
+ tst r3, #-2147483648 ; 0x80000000
+ bne __aeabi_uldivmod_label2
+ movs ip, r3, lsr #15
+ addeq r6, r6, #16 ; 0x10
+ mov ip, r3, lsl r6
+ movs lr, ip, lsr #23
+ moveq ip, ip, lsl #8
+ addeq r6, r6, #8 ; 0x8
+ movs lr, ip, lsr #27
+ moveq ip, ip, lsl #4
+ addeq r6, r6, #4 ; 0x4
+ movs lr, ip, lsr #29
+ moveq ip, ip, lsl #2
+ addeq r6, r6, #2 ; 0x2
+ movs lr, ip, lsr #30
+ addeq r6, r6, #1 ; 0x1
+ rsb r3, r6, #32 ; 0x20
+ moveq ip, ip, lsl #1
+ orr ip, ip, r2, lsr r3
+ mov lr, r2, lsl r6
+ b _ll_udiv_big
+__aeabi_uldivmod_label2
+ mov ip, r3
+ mov lr, r2
+ b _ll_udiv_ginormous
+
+_ll_udiv_small
+ cmp r4, ip, lsl #1
+ mov r3, #0 ; 0x0
+ subcs r4, r4, ip, lsl #1
+ addcs r3, r3, #2 ; 0x2
+ cmp r4, ip
+ subcs r4, r4, ip
+ adcs r3, r3, #0 ; 0x0
+ add r2, r6, #32 ; 0x20
+ cmp r2, #32 ; 0x20
+ rsb ip, ip, #0 ; 0x0
+ bcc _ll_udiv_small_label1
+ orrs r0, r4, r5, lsr #30
+ moveq r4, r5
+ moveq r5, #0 ; 0x0
+ subeq r2, r2, #32 ; 0x20
+_ll_udiv_small_label1
+ mov r1, #0 ; 0x0
+ cmp r2, #16 ; 0x10
+ bcc _ll_udiv_small_label2
+ movs r0, r4, lsr #14
+ moveq r4, r4, lsl #16
+ addeq r1, r1, #16 ; 0x10
+_ll_udiv_small_label2
+ sub lr, r2, r1
+ cmp lr, #8 ; 0x8
+ bcc _ll_udiv_small_label3
+ movs r0, r4, lsr #22
+ moveq r4, r4, lsl #8
+ addeq r1, r1, #8 ; 0x8
+_ll_udiv_small_label3
+ rsb r0, r1, #32 ; 0x20
+ sub r2, r2, r1
+ orr r4, r4, r5, lsr r0
+ mov r5, r5, lsl r1
+ cmp r2, #1 ; 0x1
+ bcc _ll_udiv_small_label5
+ sub r2, r2, #1 ; 0x1
+ and r0, r2, #7 ; 0x7
+ eor r0, r0, #7 ; 0x7
+ adds r0, r0, r0, lsl #1
+ add pc, pc, r0, lsl #2
+ nop ; (mov r0,r0)
+_ll_udiv_small_label4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ rsbcc r4, ip, r4
+ adcs r5, r5, r5
+ adcs r4, ip, r4, lsl #1
+ sub r2, r2, #8 ; 0x8
+ tst r2, r2
+ rsbcc r4, ip, r4
+ bpl _ll_udiv_small_label4
+_ll_udiv_small_label5
+ mov r2, r4, lsr r6
+ bic r4, r4, r2, lsl r6
+ adcs r0, r5, r5
+ adc r1, r4, r4
+ add r1, r1, r3, lsl r6
+ mov r3, #0 ; 0x0
+ ldmia sp!, {r4, r5, r6, pc}
+
+_ll_udiv_big
+ subs r0, r5, lr
+ mov r3, #0 ; 0x0
+ sbcs r1, r4, ip
+ movcs r5, r0
+ movcs r4, r1
+ adcs r3, r3, #0 ; 0x0
+ subs r0, r5, lr
+ sbcs r1, r4, ip
+ movcs r5, r0
+ movcs r4, r1
+ adcs r3, r3, #0 ; 0x0
+ subs r0, r5, lr
+ sbcs r1, r4, ip
+ movcs r5, r0
+ movcs r4, r1
+ adcs r3, r3, #0 ; 0x0
+ mov r1, #0 ; 0x0
+ rsbs lr, lr, #0 ; 0x0
+ rsc ip, ip, #0 ; 0x0
+ cmp r6, #16 ; 0x10
+ bcc _ll_udiv_big_label1
+ movs r0, r4, lsr #14
+ moveq r4, r4, lsl #16
+ addeq r1, r1, #16 ; 0x10
+_ll_udiv_big_label1
+ sub r2, r6, r1
+ cmp r2, #8 ; 0x8
+ bcc _ll_udiv_big_label2
+ movs r0, r4, lsr #22
+ moveq r4, r4, lsl #8
+ addeq r1, r1, #8 ; 0x8
+_ll_udiv_big_label2
+ rsb r0, r1, #32 ; 0x20
+ sub r2, r6, r1
+ orr r4, r4, r5, lsr r0
+ mov r5, r5, lsl r1
+ cmp r2, #1 ; 0x1
+ bcc _ll_udiv_big_label4
+ sub r2, r2, #1 ; 0x1
+ and r0, r2, #3 ; 0x3
+ rsb r0, r0, #3 ; 0x3
+ adds r0, r0, r0, lsl #1
+ add pc, pc, r0, lsl #3
+ nop ; (mov r0,r0)
+_ll_udiv_big_label3
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ movcs r5, r0
+ movcs r4, r1
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ movcs r5, r0
+ movcs r4, r1
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ movcs r5, r0
+ movcs r4, r1
+ sub r2, r2, #4 ; 0x4
+ adcs r5, r5, r5
+ adcs r4, r4, r4
+ adcs r0, lr, r5
+ adcs r1, ip, r4
+ tst r2, r2
+ movcs r5, r0
+ movcs r4, r1
+ bpl _ll_udiv_big_label3
+_ll_udiv_big_label4
+ mov r1, #0 ; 0x0
+ mov r2, r5, lsr r6
+ bic r5, r5, r2, lsl r6
+ adcs r0, r5, r5
+ adc r1, r1, #0 ; 0x0
+ movs lr, r3, lsl r6
+ mov r3, r4, lsr r6
+ bic r4, r4, r3, lsl r6
+ adc r1, r1, #0 ; 0x0
+ adds r0, r0, lr
+ orr r2, r2, r4, ror r6
+ adc r1, r1, #0 ; 0x0
+ ldmia sp!, {r4, r5, r6, pc}
+
+_ll_udiv_ginormous
+ subs r2, r5, lr
+ mov r1, #0 ; 0x0
+ sbcs r3, r4, ip
+ adc r0, r1, r1
+ movcc r2, r5
+ movcc r3, r4
+ ldmia sp!, {r4, r5, r6, pc}
+
+_ll_div0
+ ldmia sp!, {r4, r5, r6, lr}
+ mov r0, #0 ; 0x0
+ mov r1, #0 ; 0x0
+ b __aeabi_ldiv0
+
+__aeabi_ldiv0
+ BX r14
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldivmod.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldivmod.c
index 487674333..feac60195 100755
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldivmod.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uldivmod.c
@@ -1,43 +1,43 @@
-/** @file
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "Llvm_int_lib.h"
-#include <Library/BaseLib.h>
-
-
-UINT32 __udivsi3(UINT32 n, UINT32 d);
-UINT32 __umodsi3(UINT32 a, UINT32 b);
-
-
-UINT64
-__aeabi_uidivmod(unsigned numerator, unsigned denominator)
-{
- UINT64 Return;
-
- Return = __udivsi3 (numerator, denominator);
- Return |= LShiftU64 (__umodsi3 (numerator, denominator), 32);
-
- return Return;
-}
-
-unsigned
-__aeabi_uidiv (unsigned n, unsigned d)
-{
- return __udivsi3 (n, d);
-}
-
-
-
-
-
+/** @file
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "Llvm_int_lib.h"
+#include <Library/BaseLib.h>
+
+
+UINT32 __udivsi3(UINT32 n, UINT32 d);
+UINT32 __umodsi3(UINT32 a, UINT32 b);
+
+
+UINT64
+__aeabi_uidivmod(unsigned numerator, unsigned denominator)
+{
+ UINT64 Return;
+
+ Return = __udivsi3 (numerator, denominator);
+ Return |= LShiftU64 (__umodsi3 (numerator, denominator), 32);
+
+ return Return;
+}
+
+unsigned
+__aeabi_uidiv (unsigned n, unsigned d)
+{
+ return __udivsi3 (n, d);
+}
+
+
+
+
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.S
index 75bb24088..6e23057c2 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.S
@@ -1,29 +1,29 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__umoddi3)
-
-ASM_PFX(__umoddi3):
- stmfd sp!, {r7, lr}
- add r7, sp, #0
- sub sp, sp, #16
- add ip, sp, #8
- str ip, [sp, #0]
- bl ASM_PFX(__udivmoddi4)
- ldrd r0, [sp, #8]
- sub sp, r7, #0
- ldmfd sp!, {r7, pc}
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__umoddi3)
+
+ASM_PFX(__umoddi3):
+ stmfd sp!, {r7, lr}
+ add r7, sp, #0
+ sub sp, sp, #16
+ add ip, sp, #8
+ str ip, [sp, #0]
+ bl ASM_PFX(__udivmoddi4)
+ ldrd r0, [sp, #8]
+ sub sp, r7, #0
+ ldmfd sp!, {r7, pc}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.c
index 125af09b6..ebd769755 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umoddi3.c
@@ -1,72 +1,72 @@
-/** @file
- Compiler intrinsic for 64-bit unsigned mod, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-UINT64 __udivmoddi4(UINT64 a, UINT64 b, UINT64* rem);
-
-// Returns: a % b
-
-UINT64
-__umoddi3(UINT64 a, UINT64 b)
-{
- UINT64 r;
- __udivmoddi4(a, b, &r);
- return r;
-}
-
+/** @file
+ Compiler intrinsic for 64-bit unsigned mod, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+UINT64 __udivmoddi4(UINT64 a, UINT64 b, UINT64* rem);
+
+// Returns: a % b
+
+UINT64
+__umoddi3(UINT64 a, UINT64 b)
+{
+ UINT64 r;
+ __udivmoddi4(a, b, &r);
+ return r;
+}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.S b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.S
index 9d0f17e6e..bd32fd124 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.S
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.S
@@ -1,28 +1,28 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
- .text
- .align 2
- GCC_ASM_EXPORT(__umodsi3)
-
-ASM_PFX(__umodsi3):
- stmfd sp!, {r4, r5, r7, lr}
- add r7, sp, #8
- mov r5, r0
- mov r4, r1
- bl ASM_PFX(__udivsi3)
- mul r0, r4, r0
- rsb r0, r0, r5
- ldmfd sp!, {r4, r5, r7, pc}
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+ .text
+ .align 2
+ GCC_ASM_EXPORT(__umodsi3)
+
+ASM_PFX(__umodsi3):
+ stmfd sp!, {r4, r5, r7, lr}
+ add r7, sp, #8
+ mov r5, r0
+ mov r4, r1
+ bl ASM_PFX(__udivsi3)
+ mul r0, r4, r0
+ rsb r0, r0, r5
+ ldmfd sp!, {r4, r5, r7, pc}
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.c b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.c
index 5e302d619..e3aa4da87 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.c
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/umodsi3.c
@@ -1,68 +1,68 @@
-/** @file
- Compiler intrinsic for 32-bit unsigned mod, ported from LLVM code.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-/**
- University of Illinois/NCSA
- Open Source License
-
- Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
- All rights reserved.
-
- Developed by:
-
- LLVM Team
-
- University of Illinois at Urbana-Champaign
-
- http://llvm.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy of
- this software and associated documentation files (the "Software"), to deal with
- the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- of the Software, and to permit persons to whom the Software is furnished to do
- so, subject to the following conditions:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimers.
-
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimers in the
- documentation and/or other materials provided with the distribution.
-
- * Neither the names of the LLVM Team, University of Illinois at
- Urbana-Champaign, nor the names of its contributors may be used to
- endorse or promote products derived from this Software without specific
- prior written permission.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
- SOFTWARE.
-**/
-
-
-#include "Llvm_int_lib.h"
-
-
-// Returns: a % b
-
-UINT32
-__umodsi3(UINT32 a, UINT32 b)
-{
- return a - (a / b) * b;
-}
+/** @file
+ Compiler intrinsic for 32-bit unsigned mod, ported from LLVM code.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+/**
+ University of Illinois/NCSA
+ Open Source License
+
+ Copyright (c) 2003-2008 University of Illinois at Urbana-Champaign.
+ All rights reserved.
+
+ Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal with
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ of the Software, and to permit persons to whom the Software is furnished to do
+ so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ SOFTWARE.
+**/
+
+
+#include "Llvm_int_lib.h"
+
+
+// Returns: a % b
+
+UINT32
+__umodsi3(UINT32 a, UINT32 b)
+{
+ return a - (a / b) * b;
+}
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uwrite.asm b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uwrite.asm
index a456ea250..0b79e3416 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uwrite.asm
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/Arm/uwrite.asm
@@ -1,68 +1,68 @@
-//------------------------------------------------------------------------------
-//
-// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
- EXPORT __aeabi_uwrite4
- EXPORT __aeabi_uwrite8
-
- AREA Uwrite4, CODE, READONLY
-
-;
-;UINT32
-;EFIAPI
-;__aeabi_uwrite4 (
-; IN UINT32 Data,
-; IN VOID *Pointer
-; );
-;
-;
-__aeabi_uwrite4
- mov r2, r0, lsr #8
- strb r0, [r1]
- strb r2, [r1, #1]
- mov r2, r0, lsr #16
- strb r2, [r1, #2]
- mov r2, r0, lsr #24
- strb r2, [r1, #3]
- bx lr
-
-;
-;UINT64
-;EFIAPI
-;__aeabi_uwrite8 (
-; IN UINT64 Data, //r0-r1
-; IN VOID *Pointer //r2
-; );
-;
-;
-__aeabi_uwrite8
- mov r3, r0, lsr #8
- strb r0, [r2]
- strb r3, [r2, #1]
- mov r3, r0, lsr #16
- strb r3, [r2, #2]
- mov r3, r0, lsr #24
- strb r3, [r2, #3]
-
- mov r3, r1, lsr #8
- strb r1, [r2, #4]
- strb r3, [r2, #5]
- mov r3, r1, lsr #16
- strb r3, [r2, #6]
- mov r3, r1, lsr #24
- strb r3, [r2, #7]
- bx lr
-
- END
-
+//------------------------------------------------------------------------------
+//
+// Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+ EXPORT __aeabi_uwrite4
+ EXPORT __aeabi_uwrite8
+
+ AREA Uwrite4, CODE, READONLY
+
+;
+;UINT32
+;EFIAPI
+;__aeabi_uwrite4 (
+; IN UINT32 Data,
+; IN VOID *Pointer
+; );
+;
+;
+__aeabi_uwrite4
+ mov r2, r0, lsr #8
+ strb r0, [r1]
+ strb r2, [r1, #1]
+ mov r2, r0, lsr #16
+ strb r2, [r1, #2]
+ mov r2, r0, lsr #24
+ strb r2, [r1, #3]
+ bx lr
+
+;
+;UINT64
+;EFIAPI
+;__aeabi_uwrite8 (
+; IN UINT64 Data, //r0-r1
+; IN VOID *Pointer //r2
+; );
+;
+;
+__aeabi_uwrite8
+ mov r3, r0, lsr #8
+ strb r0, [r2]
+ strb r3, [r2, #1]
+ mov r3, r0, lsr #16
+ strb r3, [r2, #2]
+ mov r3, r0, lsr #24
+ strb r3, [r2, #3]
+
+ mov r3, r1, lsr #8
+ strb r1, [r2, #4]
+ strb r3, [r2, #5]
+ mov r3, r1, lsr #16
+ strb r3, [r2, #6]
+ mov r3, r1, lsr #24
+ strb r3, [r2, #7]
+ bx lr
+
+ END
+
diff --git a/ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf b/ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
index 9b116f890..53b1b15c7 100644
--- a/ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
+++ b/ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
@@ -1,102 +1,106 @@
-#/** @file
-# Base Library implementation.
-#
-# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = CompilerIntrinsicsLib
- FILE_GUID = 855274FA-3575-4C20-9709-C031DC5589FA
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = CompilerIntrinsicsLib
-
-
-[Sources.common]
-
-
-[Sources.ARM]
- Arm/mullu.asm | RVCT
- Arm/switch.asm | RVCT
- Arm/llsr.asm | RVCT
- Arm/memcpy.asm | RVCT
- Arm/memcpy4.asm | RVCT
- Arm/memset.asm | RVCT
- Arm/memmove.asm | RVCT
- Arm/uread.asm | RVCT
- Arm/uwrite.asm | RVCT
- Arm/lasr.asm | RVCT
- Arm/llsl.asm | RVCT
- Arm/div.asm | RVCT
- Arm/uldiv.asm | RVCT
- Arm/ldivmod.asm | RVCT
-
-
-#
-# Move .c to .s to work around LLVM issues
-#
-# Arm/ashrdi3.c | GCC
-# Arm/ashldi3.c | GCC
-# Arm/divdi3.c | GCC
-# Arm/divsi3.c | GCC
-# Arm/lshrdi3.c | GCC
- Arm/ashrdi3.S | GCC
- Arm/ashldi3.S | GCC
- Arm/div.S | GCC
- Arm/divdi3.S | GCC
- Arm/divsi3.S | GCC
- Arm/lshrdi3.S | GCC
-
- Arm/memcpy.S | GCC
- Arm/memset.S | GCC
-
-# Arm/modsi3.c | GCC
-# Arm/moddi3.c | GCC
-# Arm/muldi3.c | GCC
- Arm/modsi3.S | GCC
- Arm/moddi3.S | GCC
- Arm/muldi3.S | GCC
- Arm/mullu.S | GCC
-
-# Arm/udivsi3.c | GCC
-# Arm/umodsi3.c | GCC
-# Arm/udivdi3.c | GCC
-# Arm/umoddi3.c | GCC
-# Arm/udivmoddi4.c | GCC
- Arm/udivsi3.S | GCC
- Arm/umodsi3.S | GCC
- Arm/udivdi3.S | GCC
- Arm/umoddi3.S | GCC
- Arm/udivmoddi4.S | GCC
-
-# Arm/clzsi2.c | GCC
-# Arm/ctzsi2.c | GCC
-# Arm/ucmpdi2.c | GCC
- Arm/clzsi2.S | GCC
- Arm/ctzsi2.S | GCC
- Arm/ucmpdi2.S | GCC
- Arm/switch8.S | GCC
- Arm/switchu8.S | GCC
- Arm/switch16.S | GCC
- Arm/switch32.S | GCC
-
- Arm/sourcery.S | GCC
- Arm/uldiv.S | GCC
- Arm/ldivmod.S | GCC
-
-[Packages]
- MdePkg/MdePkg.dec
-
-[LibraryClasses]
-
+#/** @file
+# Base Library implementation.
+#
+# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = CompilerIntrinsicsLib
+ FILE_GUID = 855274FA-3575-4C20-9709-C031DC5589FA
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = CompilerIntrinsicsLib
+
+
+[Sources.common]
+
+
+[Sources.ARM]
+ Arm/mullu.asm | RVCT
+ Arm/switch.asm | RVCT
+ Arm/llsr.asm | RVCT
+ Arm/memcpy.asm | RVCT
+ Arm/memcpy4.asm | RVCT
+ Arm/memset.asm | RVCT
+ Arm/memmove.asm | RVCT
+ Arm/uread.asm | RVCT
+ Arm/uwrite.asm | RVCT
+ Arm/lasr.asm | RVCT
+ Arm/llsl.asm | RVCT
+ Arm/div.asm | RVCT
+ Arm/uldiv.asm | RVCT
+ Arm/ldivmod.asm | RVCT
+
+
+#
+# Move .c to .s to work around LLVM issues
+#
+# Arm/ashrdi3.c | GCC
+# Arm/ashldi3.c | GCC
+# Arm/divdi3.c | GCC
+# Arm/divsi3.c | GCC
+# Arm/lshrdi3.c | GCC
+ Arm/ashrdi3.S | GCC
+ Arm/ashldi3.S | GCC
+ Arm/div.S | GCC
+ Arm/divdi3.S | GCC
+ Arm/divsi3.S | GCC
+ Arm/lshrdi3.S | GCC
+
+ Arm/memcpy.S | GCC
+ Arm/memset.S | GCC
+
+# Arm/modsi3.c | GCC
+# Arm/moddi3.c | GCC
+# Arm/muldi3.c | GCC
+ Arm/modsi3.S | GCC
+ Arm/moddi3.S | GCC
+ Arm/muldi3.S | GCC
+ Arm/mullu.S | GCC
+
+# Arm/udivsi3.c | GCC
+# Arm/umodsi3.c | GCC
+# Arm/udivdi3.c | GCC
+# Arm/umoddi3.c | GCC
+# Arm/udivmoddi4.c | GCC
+ Arm/udivsi3.S | GCC
+ Arm/umodsi3.S | GCC
+ Arm/udivdi3.S | GCC
+ Arm/umoddi3.S | GCC
+ Arm/udivmoddi4.S | GCC
+
+# Arm/clzsi2.c | GCC
+# Arm/ctzsi2.c | GCC
+# Arm/ucmpdi2.c | GCC
+ Arm/clzsi2.S | GCC
+ Arm/ctzsi2.S | GCC
+ Arm/ucmpdi2.S | GCC
+ Arm/switch8.S | GCC
+ Arm/switchu8.S | GCC
+ Arm/switch16.S | GCC
+ Arm/switch32.S | GCC
+
+ Arm/sourcery.S | GCC
+ Arm/uldiv.S | GCC
+ Arm/ldivmod.S | GCC
+
+ Arm/llsr.S | GCC
+ Arm/llsl.S | GCC
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+
+[LibraryClasses]
+
diff --git a/ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S b/ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S
index 3c1738676..d92acfeac 100644
--- a/ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S
+++ b/ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentException.S
@@ -1,276 +1,276 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# Copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-#include <Library/PcdLib.h>
-
-/*
-
-This is the stack constructed by the exception handler (low address to high address)
- # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
- Reg Offset
- === ======
- R0 0x00 # stmfd SP!,{R0-R12}
- R1 0x04
- R2 0x08
- R3 0x0c
- R4 0x10
- R5 0x14
- R6 0x18
- R7 0x1c
- R8 0x20
- R9 0x24
- R10 0x28
- R11 0x2c
- R12 0x30
- SP 0x34 # reserved via adding 0x20 (32) to the SP
- LR 0x38
- PC 0x3c
- CPSR 0x40
- DFSR 0x44
- DFAR 0x48
- IFSR 0x4c
- IFAR 0x50
-
- LR 0x54 # SVC Link register (we need to restore it)
-
- LR 0x58 # pushed by srsfd
- CPSR 0x5c
-
- */
-
-GCC_ASM_EXPORT(DebugAgentVectorTable)
-GCC_ASM_IMPORT(DefaultExceptionHandler)
-
-.text
-#if !defined(__APPLE__)
-.fpu neon @ makes vpush/vpop assemble
-#endif
-.align 5
-
-
-//
-// This code gets copied to the ARM vector table
-// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
-//
-ASM_PFX(DebugAgentVectorTable):
- b ASM_PFX(ResetEntry)
- b ASM_PFX(UndefinedInstructionEntry)
- b ASM_PFX(SoftwareInterruptEntry)
- b ASM_PFX(PrefetchAbortEntry)
- b ASM_PFX(DataAbortEntry)
- b ASM_PFX(ReservedExceptionEntry)
- b ASM_PFX(IrqEntry)
- b ASM_PFX(FiqEntry)
-
-ASM_PFX(ResetEntry):
- srsdb #0x13! @ Store return state on SVC stack
- @ We are already in SVC mode
-
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#0 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(UndefinedInstructionEntry):
- sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#1 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(SoftwareInterruptEntry):
- sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
- srsdb #0x13! @ Store return state on SVC stack
- @ We are already in SVC mode
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#2 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(PrefetchAbortEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#3 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(DataAbortEntry):
- sub LR,LR,#8
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#4
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(ReservedExceptionEntry):
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#5
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(IrqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#6 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(FiqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
- @ Since we have already switch to SVC R8_fiq - R12_fiq
- @ never get used or saved
- mov R0,#7 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-//
-// This gets patched by the C code that patches in the vector table
-//
-ASM_PFX(CommonExceptionEntry):
- .word ASM_PFX(AsmCommonExceptionEntry)
-
-ASM_PFX(ExceptionHandlersEnd):
-
-//
-// This code runs from CpuDxe driver loaded address. It is patched into
-// CommonExceptionEntry.
-//
-ASM_PFX(AsmCommonExceptionEntry):
- mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
- str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
-
- mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
- str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
-
- mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
- str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
-
- mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
- str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
-
- ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
- str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
-
- add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R3, R1, #0x1f @ Check CPSR to see if User or System Mode
- cmp R3, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1df))
- cmpne R3, #0x10 @
- stmeqed R2, {lr}^ @ save unbanked lr
- @ else
- stmneed R2, {lr} @ save SVC lr
-
-
- ldr R5, [SP, #0x58] @ PC is the LR pushed by srsfd
- @ Check to see if we have to adjust for Thumb entry
- sub r4, r0, #1 @ if (ExceptionType == 1 || ExceptionType ==2)) {
- cmp r4, #1 @ // UND & SVC have differnt LR adjust for Thumb
- bhi NoAdjustNeeded
-
- tst r1, #0x20 @ if ((CPSR & T)) == T) { // Thumb Mode on entry
- addne R5, R5, #2 @ PC += 2@
- str R5,[SP,#0x58] @ Update LR value pused by srsfd
-
-NoAdjustNeeded:
-
- str R5, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
-
- sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
- str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
-
- @ R0 is ExceptionType
- mov R1,SP @ R1 is SystemContext
-
-#if (FixedPcdGet32(PcdVFPEnabled))
- vpush {d0-d15} @ save vstm registers in case they are used in optimizations
-#endif
-
-/*
-VOID
-EFIAPI
-DefaultExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType, R0
- IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
- )
-
-*/
- blx ASM_PFX(DefaultExceptionHandler) @ Call exception handler
-
-#if (FixedPcdGet32(PcdVFPEnabled))
- vpop {d0-d15}
-#endif
-
- ldr R1, [SP, #0x4c] @ Restore EFI_SYSTEM_CONTEXT_ARM.IFSR
- mcr p15, 0, R1, c5, c0, 1 @ Write IFSR
-
- ldr R1, [SP, #0x44] @ sRestore EFI_SYSTEM_CONTEXT_ARM.DFSR
- mcr p15, 0, R1, c5, c0, 0 @ Write DFSR
-
- ldr R1,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
- str R1,[SP,#0x58] @ Store it back to srsfd stack slot so it can be restored
-
- ldr R1,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
- str R1,[SP,#0x5c] @ Store it back to srsfd stack slot so it can be restored
-
- add R3, SP, #0x54 @ Make R3 point to SVC LR saved on entry
- add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R1, R1, #0x1f @ Check to see if User or System Mode
- cmp R1, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1f))
- cmpne R1, #0x10 @
- ldmeqed R2, {lr}^ @ restore unbanked lr
- @ else
- ldmneed R3, {lr} @ restore SVC lr, via ldmfd SP!, {LR}
-
- ldmfd SP!,{R0-R12} @ Restore general purpose registers
- @ Exception handler can not change SP
-
- add SP,SP,#0x20 @ Clear out the remaining stack space
- ldmfd SP!,{LR} @ restore the link register for this context
- rfefd SP! @ return from exception via srsfd stack slot
-
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# Copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+#include <Library/PcdLib.h>
+
+/*
+
+This is the stack constructed by the exception handler (low address to high address)
+ # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
+ Reg Offset
+ === ======
+ R0 0x00 # stmfd SP!,{R0-R12}
+ R1 0x04
+ R2 0x08
+ R3 0x0c
+ R4 0x10
+ R5 0x14
+ R6 0x18
+ R7 0x1c
+ R8 0x20
+ R9 0x24
+ R10 0x28
+ R11 0x2c
+ R12 0x30
+ SP 0x34 # reserved via adding 0x20 (32) to the SP
+ LR 0x38
+ PC 0x3c
+ CPSR 0x40
+ DFSR 0x44
+ DFAR 0x48
+ IFSR 0x4c
+ IFAR 0x50
+
+ LR 0x54 # SVC Link register (we need to restore it)
+
+ LR 0x58 # pushed by srsfd
+ CPSR 0x5c
+
+ */
+
+GCC_ASM_EXPORT(DebugAgentVectorTable)
+GCC_ASM_IMPORT(DefaultExceptionHandler)
+
+.text
+#if !defined(__APPLE__)
+.fpu neon @ makes vpush/vpop assemble
+#endif
+.align 5
+
+
+//
+// This code gets copied to the ARM vector table
+// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
+//
+ASM_PFX(DebugAgentVectorTable):
+ b ASM_PFX(ResetEntry)
+ b ASM_PFX(UndefinedInstructionEntry)
+ b ASM_PFX(SoftwareInterruptEntry)
+ b ASM_PFX(PrefetchAbortEntry)
+ b ASM_PFX(DataAbortEntry)
+ b ASM_PFX(ReservedExceptionEntry)
+ b ASM_PFX(IrqEntry)
+ b ASM_PFX(FiqEntry)
+
+ASM_PFX(ResetEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ @ We are already in SVC mode
+
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#0 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(UndefinedInstructionEntry):
+ sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#1 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(SoftwareInterruptEntry):
+ sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsdb #0x13! @ Store return state on SVC stack
+ @ We are already in SVC mode
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#2 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(PrefetchAbortEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#3 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(DataAbortEntry):
+ sub LR,LR,#8
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#4
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(ReservedExceptionEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#5
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(IrqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#6 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(FiqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+ @ Since we have already switch to SVC R8_fiq - R12_fiq
+ @ never get used or saved
+ mov R0,#7 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+//
+// This gets patched by the C code that patches in the vector table
+//
+ASM_PFX(CommonExceptionEntry):
+ .word ASM_PFX(AsmCommonExceptionEntry)
+
+ASM_PFX(ExceptionHandlersEnd):
+
+//
+// This code runs from CpuDxe driver loaded address. It is patched into
+// CommonExceptionEntry.
+//
+ASM_PFX(AsmCommonExceptionEntry):
+ mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
+ str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
+
+ mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
+ str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
+
+ mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
+ str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
+
+ mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
+ str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
+
+ ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
+ str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
+
+ add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R3, R1, #0x1f @ Check CPSR to see if User or System Mode
+ cmp R3, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1df))
+ cmpne R3, #0x10 @
+ stmeqed R2, {lr}^ @ save unbanked lr
+ @ else
+ stmneed R2, {lr} @ save SVC lr
+
+
+ ldr R5, [SP, #0x58] @ PC is the LR pushed by srsfd
+ @ Check to see if we have to adjust for Thumb entry
+ sub r4, r0, #1 @ if (ExceptionType == 1 || ExceptionType ==2)) {
+ cmp r4, #1 @ // UND & SVC have differnt LR adjust for Thumb
+ bhi NoAdjustNeeded
+
+ tst r1, #0x20 @ if ((CPSR & T)) == T) { // Thumb Mode on entry
+ addne R5, R5, #2 @ PC += 2@
+ str R5,[SP,#0x58] @ Update LR value pused by srsfd
+
+NoAdjustNeeded:
+
+ str R5, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
+
+ sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
+ str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
+
+ @ R0 is ExceptionType
+ mov R1,SP @ R1 is SystemContext
+
+#if (FixedPcdGet32(PcdVFPEnabled))
+ vpush {d0-d15} @ save vstm registers in case they are used in optimizations
+#endif
+
+/*
+VOID
+EFIAPI
+DefaultExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType, R0
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
+ )
+
+*/
+ blx ASM_PFX(DefaultExceptionHandler) @ Call exception handler
+
+#if (FixedPcdGet32(PcdVFPEnabled))
+ vpop {d0-d15}
+#endif
+
+ ldr R1, [SP, #0x4c] @ Restore EFI_SYSTEM_CONTEXT_ARM.IFSR
+ mcr p15, 0, R1, c5, c0, 1 @ Write IFSR
+
+ ldr R1, [SP, #0x44] @ sRestore EFI_SYSTEM_CONTEXT_ARM.DFSR
+ mcr p15, 0, R1, c5, c0, 0 @ Write DFSR
+
+ ldr R1,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
+ str R1,[SP,#0x58] @ Store it back to srsfd stack slot so it can be restored
+
+ ldr R1,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
+ str R1,[SP,#0x5c] @ Store it back to srsfd stack slot so it can be restored
+
+ add R3, SP, #0x54 @ Make R3 point to SVC LR saved on entry
+ add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R1, R1, #0x1f @ Check to see if User or System Mode
+ cmp R1, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1f))
+ cmpne R1, #0x10 @
+ ldmeqed R2, {lr}^ @ restore unbanked lr
+ @ else
+ ldmneed R3, {lr} @ restore SVC lr, via ldmfd SP!, {LR}
+
+ ldmfd SP!,{R0-R12} @ Restore general purpose registers
+ @ Exception handler can not change SP
+
+ add SP,SP,#0x20 @ Clear out the remaining stack space
+ ldmfd SP!,{LR} @ restore the link register for this context
+ rfefd SP! @ return from exception via srsfd stack slot
+
diff --git a/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf b/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
index ab57bbd56..c1f717e5b 100755
--- a/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
+++ b/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
@@ -1,39 +1,39 @@
-#/** @file
-# PeCoff extra action libary for DXE phase that run Unix emulator.
-#
-# Lib to provide memory journal status code reporting Routines
-# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
-# Portions copyright (c) 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = DebugUnixPeCoffExtraActionLib
- FILE_GUID = C3E9448E-1726-42fb-9368-41F75B038C0C
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = PeCoffExtraActionLib
-
-#
-# The following information is for reference only and not required by the build tools.
-#
-# VALID_ARCHITECTURES = ARM
-#
-
-[Sources.common]
- DebugPeCoffExtraActionLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
-
-[LibraryClasses]
- DebugLib
+#/** @file
+# PeCoff extra action libary for DXE phase that run Unix emulator.
+#
+# Lib to provide memory journal status code reporting Routines
+# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
+# Portions copyright (c) 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DebugUnixPeCoffExtraActionLib
+ FILE_GUID = C3E9448E-1726-42fb-9368-41F75B038C0C
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = PeCoffExtraActionLib
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = ARM
+#
+
+[Sources.common]
+ DebugPeCoffExtraActionLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+
+[LibraryClasses]
+ DebugLib
diff --git a/ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf b/ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
index d1f815828..b5e9fd8e9 100644
--- a/ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
+++ b/ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
@@ -44,4 +44,4 @@
[Depex]
- gEfiCpuArchProtocolGuid AND gVirtualUncachedPagesProtocolGuid \ No newline at end of file
+ gEfiCpuArchProtocolGuid AND gVirtualUncachedPagesProtocolGuid \ No newline at end of file
diff --git a/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf b/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
index e634d39b9..3be0237a3 100644
--- a/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
+++ b/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
@@ -1,41 +1,41 @@
-#/** @file
-# PeCoff extra action libary for DXE phase that run Unix emulator.
-#
-# Lib to provide memory journal status code reporting Routines
-# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
-# Portions copyright (c) 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = RvdUnixPeCoffExtraActionLib
- FILE_GUID = 5EDEB7E7-EA55-4E92-8216-335AC98A3B11
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = PeCoffExtraActionLib
-
-#
-# The following information is for reference only and not required by the build tools.
-#
-# VALID_ARCHITECTURES = ARM
-#
-
-[Sources.common]
- RvdPeCoffExtraActionLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPkg/ArmPkg.dec
-
-[LibraryClasses]
- DebugLib
- SemihostLib
+#/** @file
+# PeCoff extra action libary for DXE phase that run Unix emulator.
+#
+# Lib to provide memory journal status code reporting Routines
+# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
+# Portions copyright (c) 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = RvdUnixPeCoffExtraActionLib
+ FILE_GUID = 5EDEB7E7-EA55-4E92-8216-335AC98A3B11
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = PeCoffExtraActionLib
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = ARM
+#
+
+[Sources.common]
+ RvdPeCoffExtraActionLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPkg/ArmPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ SemihostLib
diff --git a/ArmPkg/Library/SemihostLib/Arm/GccSemihost.S b/ArmPkg/Library/SemihostLib/Arm/GccSemihost.S
index 2d33664f7..4aa886182 100755
--- a/ArmPkg/Library/SemihostLib/Arm/GccSemihost.S
+++ b/ArmPkg/Library/SemihostLib/Arm/GccSemihost.S
@@ -1,41 +1,41 @@
-#------------------------------------------------------------------------------
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-.text
-.align 2
-
-.globl ASM_PFX(GccSemihostCall)
-INTERWORK_FUNC(GccSemihostCall)
-
-/*
- Semihosting operation request mechanism
-
- SVC 0x123456 in ARM state (for all architectures)
- SVC 0xAB in Thumb state (excluding ARMv7-M)
- BKPT 0xAB for ARMv7-M (Thumb-2 only)
-
- R0 - operation type
- R1 - block containing all other parametes
-
- lr - must be saved as svc instruction will cause an svc exception and write
- the svc lr register. That happens to be the one we are using, so we must
- save it or we will not be able to return.
- */
-ASM_PFX(GccSemihostCall):
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+.text
+.align 2
+
+.globl ASM_PFX(GccSemihostCall)
+INTERWORK_FUNC(GccSemihostCall)
+
+/*
+ Semihosting operation request mechanism
+
+ SVC 0x123456 in ARM state (for all architectures)
+ SVC 0xAB in Thumb state (excluding ARMv7-M)
+ BKPT 0xAB for ARMv7-M (Thumb-2 only)
+
+ R0 - operation type
+ R1 - block containing all other parametes
+
+ lr - must be saved as svc instruction will cause an svc exception and write
+ the svc lr register. That happens to be the one we are using, so we must
+ save it or we will not be able to return.
+ */
+ASM_PFX(GccSemihostCall):
stmfd sp!, {lr}
- svc #0x123456
+ svc #0x123456
ldmfd sp!, {lr}
- bx lr
-
-
+ bx lr
+
+
diff --git a/ArmPkg/Library/SemihostLib/Arm/SemihostPrivate.h b/ArmPkg/Library/SemihostLib/Arm/SemihostPrivate.h
index f8a76528f..02836ca28 100644
--- a/ArmPkg/Library/SemihostLib/Arm/SemihostPrivate.h
+++ b/ArmPkg/Library/SemihostLib/Arm/SemihostPrivate.h
@@ -1,184 +1,184 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __SEMIHOST_PRIVATE_H__
-#define __SEMIHOST_PRIVATE_H__
-
-typedef struct {
- CHAR8 *FileName;
- UINT32 Mode;
- UINT32 NameLength;
-} SEMIHOST_FILE_OPEN_BLOCK;
-
-typedef struct {
- UINT32 Handle;
- VOID *Buffer;
- UINT32 Length;
-} SEMIHOST_FILE_READ_WRITE_BLOCK;
-
-typedef struct {
- UINT32 Handle;
- UINT32 Location;
-} SEMIHOST_FILE_SEEK_BLOCK;
-
-typedef struct {
- CHAR8 *FileName;
- UINT32 NameLength;
-} SEMIHOST_FILE_REMOVE_BLOCK;
-
-typedef struct {
- CHAR8 *CommandLine;
- UINT32 CommandLength;
-} SEMIHOST_SYSTEM_BLOCK;
-
-#if defined(__CC_ARM)
-
-#if defined(__thumb__)
-#define SWI 0xAB
-#else
-#define SWI 0x123456
-#endif
-
-#define SEMIHOST_SUPPORTED TRUE
-
-__swi(SWI)
-INT32
-_Semihost_SYS_OPEN(
- IN UINTN SWI_0x01,
- IN SEMIHOST_FILE_OPEN_BLOCK *OpenBlock
- );
-
-__swi(SWI)
-INT32
-_Semihost_SYS_CLOSE(
- IN UINTN SWI_0x02,
- IN UINT32 *Handle
- );
-
-__swi(SWI)
-VOID
-_Semihost_SYS_WRITEC(
- IN UINTN SWI_0x03,
- IN CHAR8 *Character
- );
-
-__swi(SWI)
-VOID
-_Semihost_SYS_WRITE0(
- IN UINTN SWI_0x04,
- IN CHAR8 *String
- );
-
-__swi(SWI)
-UINT32
-_Semihost_SYS_WRITE(
- IN UINTN SWI_0x05,
- IN OUT SEMIHOST_FILE_READ_WRITE_BLOCK *WriteBlock
- );
-
-__swi(SWI)
-UINT32
-_Semihost_SYS_READ(
- IN UINTN SWI_0x06,
- IN OUT SEMIHOST_FILE_READ_WRITE_BLOCK *ReadBlock
- );
-
-__swi(SWI)
-CHAR8
-_Semihost_SYS_READC(
- IN UINTN SWI_0x07,
- IN UINTN Zero
- );
-
-__swi(SWI)
-INT32
-_Semihost_SYS_SEEK(
- IN UINTN SWI_0x0A,
- IN SEMIHOST_FILE_SEEK_BLOCK *SeekBlock
- );
-
-__swi(SWI)
-INT32
-_Semihost_SYS_FLEN(
- IN UINTN SWI_0x0C,
- IN UINT32 *Handle
- );
-
-__swi(SWI)
-UINT32
-_Semihost_SYS_REMOVE(
- IN UINTN SWI_0x0E,
- IN SEMIHOST_FILE_REMOVE_BLOCK *RemoveBlock
- );
-
-__swi(SWI)
-UINT32
-_Semihost_SYS_SYSTEM(
- IN UINTN SWI_0x12,
- IN SEMIHOST_SYSTEM_BLOCK *SystemBlock
- );
-
-#define Semihost_SYS_OPEN(OpenBlock) _Semihost_SYS_OPEN(0x01, OpenBlock)
-#define Semihost_SYS_CLOSE(Handle) _Semihost_SYS_CLOSE(0x02, Handle)
-#define Semihost_SYS_WRITE0(String) _Semihost_SYS_WRITE0(0x04, String)
-#define Semihost_SYS_WRITEC(Character) _Semihost_SYS_WRITEC(0x03, Character)
-#define Semihost_SYS_WRITE(WriteBlock) _Semihost_SYS_WRITE(0x05, WriteBlock)
-#define Semihost_SYS_READ(ReadBlock) _Semihost_SYS_READ(0x06, ReadBlock)
-#define Semihost_SYS_READC() _Semihost_SYS_READC(0x07, 0)
-#define Semihost_SYS_SEEK(SeekBlock) _Semihost_SYS_SEEK(0x0A, SeekBlock)
-#define Semihost_SYS_FLEN(Handle) _Semihost_SYS_FLEN(0x0C, Handle)
-#define Semihost_SYS_REMOVE(RemoveBlock) _Semihost_SYS_REMOVE(0x0E, RemoveBlock)
-#define Semihost_SYS_SYSTEM(SystemBlock) _Semihost_SYS_SYSTEM(0x12, SystemBlock)
-
-#elif defined(__GNUC__) // __CC_ARM
-
-#define SEMIHOST_SUPPORTED TRUE
-
-UINT32
-GccSemihostCall (
- IN UINT32 Operation,
- IN UINTN SystemBlockAddress
- ); // __attribute__ ((interrupt ("SVC")));
-
-#define Semihost_SYS_OPEN(OpenBlock) GccSemihostCall(0x01, (UINTN)(OpenBlock))
-#define Semihost_SYS_CLOSE(Handle) GccSemihostCall(0x02, (UINTN)(Handle))
-#define Semihost_SYS_WRITE0(String) GccSemihostCall(0x04, (UINTN)(String))
-#define Semihost_SYS_WRITEC(Character) GccSemihostCall(0x03, (UINTN)(Character))
-#define Semihost_SYS_WRITE(WriteBlock) GccSemihostCall(0x05, (UINTN)(WriteBlock))
-#define Semihost_SYS_READ(ReadBlock) GccSemihostCall(0x06, (UINTN)(ReadBlock))
-#define Semihost_SYS_READC() GccSemihostCall(0x07, (UINTN)(0))
-#define Semihost_SYS_SEEK(SeekBlock) GccSemihostCall(0x0A, (UINTN)(SeekBlock))
-#define Semihost_SYS_FLEN(Handle) GccSemihostCall(0x0C, (UINTN)(Handle))
-#define Semihost_SYS_REMOVE(RemoveBlock) GccSemihostCall(0x0E, (UINTN)(RemoveBlock))
-#define Semihost_SYS_SYSTEM(SystemBlock) GccSemihostCall(0x12, (UINTN)(SystemBlock))
-
-#else // __CC_ARM
-
-#define SEMIHOST_SUPPORTED FALSE
-
-#define Semihost_SYS_OPEN(OpenBlock) (-1)
-#define Semihost_SYS_CLOSE(Handle) (-1)
-#define Semihost_SYS_WRITE0(String)
-#define Semihost_SYS_WRITEC(Character)
-#define Semihost_SYS_WRITE(WriteBlock) (0)
-#define Semihost_SYS_READ(ReadBlock) ((ReadBlock)->Length)
-#define Semihost_SYS_READC() ('x')
-#define Semihost_SYS_SEEK(SeekBlock) (-1)
-#define Semihost_SYS_FLEN(Handle) (-1)
-#define Semihost_SYS_REMOVE(RemoveBlock) (-1)
-#define Semihost_SYS_SYSTEM(SystemBlock) (-1)
-
-#endif // __CC_ARM
-
-#endif //__SEMIHOST_PRIVATE_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __SEMIHOST_PRIVATE_H__
+#define __SEMIHOST_PRIVATE_H__
+
+typedef struct {
+ CHAR8 *FileName;
+ UINT32 Mode;
+ UINT32 NameLength;
+} SEMIHOST_FILE_OPEN_BLOCK;
+
+typedef struct {
+ UINT32 Handle;
+ VOID *Buffer;
+ UINT32 Length;
+} SEMIHOST_FILE_READ_WRITE_BLOCK;
+
+typedef struct {
+ UINT32 Handle;
+ UINT32 Location;
+} SEMIHOST_FILE_SEEK_BLOCK;
+
+typedef struct {
+ CHAR8 *FileName;
+ UINT32 NameLength;
+} SEMIHOST_FILE_REMOVE_BLOCK;
+
+typedef struct {
+ CHAR8 *CommandLine;
+ UINT32 CommandLength;
+} SEMIHOST_SYSTEM_BLOCK;
+
+#if defined(__CC_ARM)
+
+#if defined(__thumb__)
+#define SWI 0xAB
+#else
+#define SWI 0x123456
+#endif
+
+#define SEMIHOST_SUPPORTED TRUE
+
+__swi(SWI)
+INT32
+_Semihost_SYS_OPEN(
+ IN UINTN SWI_0x01,
+ IN SEMIHOST_FILE_OPEN_BLOCK *OpenBlock
+ );
+
+__swi(SWI)
+INT32
+_Semihost_SYS_CLOSE(
+ IN UINTN SWI_0x02,
+ IN UINT32 *Handle
+ );
+
+__swi(SWI)
+VOID
+_Semihost_SYS_WRITEC(
+ IN UINTN SWI_0x03,
+ IN CHAR8 *Character
+ );
+
+__swi(SWI)
+VOID
+_Semihost_SYS_WRITE0(
+ IN UINTN SWI_0x04,
+ IN CHAR8 *String
+ );
+
+__swi(SWI)
+UINT32
+_Semihost_SYS_WRITE(
+ IN UINTN SWI_0x05,
+ IN OUT SEMIHOST_FILE_READ_WRITE_BLOCK *WriteBlock
+ );
+
+__swi(SWI)
+UINT32
+_Semihost_SYS_READ(
+ IN UINTN SWI_0x06,
+ IN OUT SEMIHOST_FILE_READ_WRITE_BLOCK *ReadBlock
+ );
+
+__swi(SWI)
+CHAR8
+_Semihost_SYS_READC(
+ IN UINTN SWI_0x07,
+ IN UINTN Zero
+ );
+
+__swi(SWI)
+INT32
+_Semihost_SYS_SEEK(
+ IN UINTN SWI_0x0A,
+ IN SEMIHOST_FILE_SEEK_BLOCK *SeekBlock
+ );
+
+__swi(SWI)
+INT32
+_Semihost_SYS_FLEN(
+ IN UINTN SWI_0x0C,
+ IN UINT32 *Handle
+ );
+
+__swi(SWI)
+UINT32
+_Semihost_SYS_REMOVE(
+ IN UINTN SWI_0x0E,
+ IN SEMIHOST_FILE_REMOVE_BLOCK *RemoveBlock
+ );
+
+__swi(SWI)
+UINT32
+_Semihost_SYS_SYSTEM(
+ IN UINTN SWI_0x12,
+ IN SEMIHOST_SYSTEM_BLOCK *SystemBlock
+ );
+
+#define Semihost_SYS_OPEN(OpenBlock) _Semihost_SYS_OPEN(0x01, OpenBlock)
+#define Semihost_SYS_CLOSE(Handle) _Semihost_SYS_CLOSE(0x02, Handle)
+#define Semihost_SYS_WRITE0(String) _Semihost_SYS_WRITE0(0x04, String)
+#define Semihost_SYS_WRITEC(Character) _Semihost_SYS_WRITEC(0x03, Character)
+#define Semihost_SYS_WRITE(WriteBlock) _Semihost_SYS_WRITE(0x05, WriteBlock)
+#define Semihost_SYS_READ(ReadBlock) _Semihost_SYS_READ(0x06, ReadBlock)
+#define Semihost_SYS_READC() _Semihost_SYS_READC(0x07, 0)
+#define Semihost_SYS_SEEK(SeekBlock) _Semihost_SYS_SEEK(0x0A, SeekBlock)
+#define Semihost_SYS_FLEN(Handle) _Semihost_SYS_FLEN(0x0C, Handle)
+#define Semihost_SYS_REMOVE(RemoveBlock) _Semihost_SYS_REMOVE(0x0E, RemoveBlock)
+#define Semihost_SYS_SYSTEM(SystemBlock) _Semihost_SYS_SYSTEM(0x12, SystemBlock)
+
+#elif defined(__GNUC__) // __CC_ARM
+
+#define SEMIHOST_SUPPORTED TRUE
+
+UINT32
+GccSemihostCall (
+ IN UINT32 Operation,
+ IN UINTN SystemBlockAddress
+ ); // __attribute__ ((interrupt ("SVC")));
+
+#define Semihost_SYS_OPEN(OpenBlock) GccSemihostCall(0x01, (UINTN)(OpenBlock))
+#define Semihost_SYS_CLOSE(Handle) GccSemihostCall(0x02, (UINTN)(Handle))
+#define Semihost_SYS_WRITE0(String) GccSemihostCall(0x04, (UINTN)(String))
+#define Semihost_SYS_WRITEC(Character) GccSemihostCall(0x03, (UINTN)(Character))
+#define Semihost_SYS_WRITE(WriteBlock) GccSemihostCall(0x05, (UINTN)(WriteBlock))
+#define Semihost_SYS_READ(ReadBlock) GccSemihostCall(0x06, (UINTN)(ReadBlock))
+#define Semihost_SYS_READC() GccSemihostCall(0x07, (UINTN)(0))
+#define Semihost_SYS_SEEK(SeekBlock) GccSemihostCall(0x0A, (UINTN)(SeekBlock))
+#define Semihost_SYS_FLEN(Handle) GccSemihostCall(0x0C, (UINTN)(Handle))
+#define Semihost_SYS_REMOVE(RemoveBlock) GccSemihostCall(0x0E, (UINTN)(RemoveBlock))
+#define Semihost_SYS_SYSTEM(SystemBlock) GccSemihostCall(0x12, (UINTN)(SystemBlock))
+
+#else // __CC_ARM
+
+#define SEMIHOST_SUPPORTED FALSE
+
+#define Semihost_SYS_OPEN(OpenBlock) (-1)
+#define Semihost_SYS_CLOSE(Handle) (-1)
+#define Semihost_SYS_WRITE0(String)
+#define Semihost_SYS_WRITEC(Character)
+#define Semihost_SYS_WRITE(WriteBlock) (0)
+#define Semihost_SYS_READ(ReadBlock) ((ReadBlock)->Length)
+#define Semihost_SYS_READC() ('x')
+#define Semihost_SYS_SEEK(SeekBlock) (-1)
+#define Semihost_SYS_FLEN(Handle) (-1)
+#define Semihost_SYS_REMOVE(RemoveBlock) (-1)
+#define Semihost_SYS_SYSTEM(SystemBlock) (-1)
+
+#endif // __CC_ARM
+
+#endif //__SEMIHOST_PRIVATE_H__
diff --git a/ArmPkg/Library/SemihostLib/SemihostLib.inf b/ArmPkg/Library/SemihostLib/SemihostLib.inf
index f575a35f0..5ec7fef3a 100644
--- a/ArmPkg/Library/SemihostLib/SemihostLib.inf
+++ b/ArmPkg/Library/SemihostLib/SemihostLib.inf
@@ -32,11 +32,11 @@
Arm/SemihostLib.c
-[Packages]
+[Packages]
MdePkg/MdePkg.dec
ArmPkg/ArmPkg.dec
-[LibraryClasses]
+[LibraryClasses]
BaseLib
[Protocols]
@@ -44,4 +44,4 @@
[Guids]
[Pcd]
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf b/ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
index 4037b7794..a48d94eef 100644
--- a/ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
+++ b/ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
@@ -39,4 +39,4 @@
DxeServicesTableLib
[Depex]
- gEfiCpuArchProtocolGuid \ No newline at end of file
+ gEfiCpuArchProtocolGuid \ No newline at end of file
diff --git a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc
index 02778a807..6de48414b 100644
--- a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc
+++ b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.dsc
@@ -1,357 +1,358 @@
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#
-################################################################################
-#
-# Defines Section - statements that will be processed to create a Makefile.
-#
-################################################################################
-[Defines]
- PLATFORM_NAME = ArmPlatform
- PLATFORM_GUID = 4fe82b83-9315-4ff3-8cc0-ab77ca93cb7f
- PLATFORM_VERSION = 0.1
- DSC_SPECIFICATION = 0x00010005
- OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME)
- SUPPORTED_ARCHITECTURES = ARM
- BUILD_TARGETS = DEBUG|RELEASE
- SKUID_IDENTIFIER = DEFAULT
- FLASH_DEFINITION = ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf
-
-[LibraryClasses.common]
- ArmLib|ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
- ArmCpuLib|ArmPkg/Drivers/ArmCpuLib/ArmCortexA9Lib/ArmCortexA9Lib.inf
- ArmPlatformLib|ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf
-
-!if $(TARGET) == RELEASE
- DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
- UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
-!else
- DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
- UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
-# UncachedMemoryAllocationLib|ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
-!endif
- DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf
-
- BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
- SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
- PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
- PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
- PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
- PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
- UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
- CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
-
- UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
- HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
- UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
- DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
- UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
- DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
- UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
- UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
- HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
- UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf
-
- UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf
-
- #
- # Assume everything is fixed at build
- #
- PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
-
- # 1/123 faster than Stm or Vstm version
- #BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
- BaseMemoryLib|ArmPkg/Library/BaseMemoryLibStm/BaseMemoryLibStm.inf
-
- # ARM Architectural Libraries
- CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
- DefaultExceptionHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
- CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf
- ArmDisassemblerLib|ArmPkg/Library/ArmDisassemblerLib/ArmDisassemblerLib.inf
- DmaLib|ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
- ArmGicLib|ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
-
- SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf
- TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
- EfiResetSystemLib|EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
- RealTimeClockLib|EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
-
- # EBL Related Libraries
- EblCmdLib|ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.inf
- EfiFileLib|EmbeddedPkg/Library/EfiFileLib/EfiFileLib.inf
- EblAddExternalCommandLib|EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
- EblNetworkLib|EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
-
- #
- # Uncomment (and comment out the next line) For RealView Debugger. The Standard IO window
- # in the debugger will show load and unload commands for symbols. You can cut and paste this
- # into the command window to load symbols. We should be able to use a script to do this, but
- # the version of RVD I have does not support scripts accessing system memory.
- #
- #PeCoffExtraActionLib|ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
- PeCoffExtraActionLib|ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
- #PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
-
- DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf
- DebugAgentTimerLib|EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLibNull.inf
-
- SemihostLib|ArmPkg/Library/SemihostLib/SemihostLib.inf
-
- # BDS Libraries
- BdsLib|ArmPkg/Library/BdsLib/BdsLib.inf
- FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf
-
-[LibraryClasses.common.SEC]
- ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.inf
-
- ArmPlatformSecExtraActionLib|ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf
- DebugAgentLib|ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentSymbolsBaseLib.inf
-
- PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
- ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
- LzmaDecompressLib|IntelFrameworkModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
- MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf
- HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf
- PrePiHobListPointerLib|ArmPlatformPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
- PerformanceLib|MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.inf
- PlatformPeiLib|ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf
- MemoryInitPeiLib|ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf
-
-[LibraryClasses.common.DXE_CORE]
- HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
- MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf
- DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
- ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
- UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
- DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
- PerformanceLib|MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.inf
-
-[LibraryClasses.common.DXE_DRIVER]
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
- DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
- SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf
- PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
- ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
-
-[LibraryClasses.common.UEFI_APPLICATION]
- UefiDecompressLib|IntelFrameworkModulePkg/Library/BaseUefiTianoCustomDecompressLib/BaseUefiTianoCustomDecompressLib.inf
- PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
- HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
-
-[LibraryClasses.common.UEFI_DRIVER]
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
- UefiDecompressLib|IntelFrameworkModulePkg/Library/BaseUefiTianoCustomDecompressLib/BaseUefiTianoCustomDecompressLib.inf
- ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
- PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
-
-[LibraryClasses.common.DXE_RUNTIME_DRIVER]
- HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
- CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
-
-[LibraryClasses.ARM]
- #
- # It is not possible to prevent the ARM compiler for generic intrinsic functions.
- # This library provides the instrinsic functions generate by a given compiler.
- # [LibraryClasses.ARM] and NULL mean link this library into all ARM images.
- #
- NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
-
-[BuildOptions]
- XCODE:*_*_ARM_PLATFORM_FLAGS == -arch armv7
-
- GCC:*_*_ARM_PLATFORM_FLAGS == -march=armv7-a
-
- RVCT:*_*_ARM_PLATFORM_FLAGS == --cpu Cortex-A8
-
-################################################################################
-#
-# Pcd Section - list of all EDK II PCD Entries defined by this Platform
-#
-################################################################################
-
-[PcdsFeatureFlag.common]
- gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|TRUE
- gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnosticsDisable|TRUE
- gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|TRUE
- gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|TRUE
-
- #
- # Control what commands are supported from the UI
- # Turn these on and off to add features or save size
- #
- gEmbeddedTokenSpaceGuid.PcdEmbeddedMacBoot|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedDirCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedHobCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedHwDebugCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPciDebugCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedIoEnable|FALSE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedScriptCmd|FALSE
-
- gEmbeddedTokenSpaceGuid.PcdCacheEnable|TRUE
-
- # Use the Vector Table location in CpuDxe. We will not copy the Vector Table at PcdCpuVectorBaseAddress
- gArmTokenSpaceGuid.PcdRelocateVectorTable|FALSE
-
- gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob|TRUE
-
- gEfiMdeModulePkgTokenSpaceGuid.PcdTurnOffUsbLegacySupport|TRUE
-
-[PcdsFixedAtBuild.common]
- gArmPlatformTokenSpaceGuid.PcdFirmwareVendor|"ARM Platform"
-
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPrompt|"ArmPlatform"
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|32
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|0
- gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000
- gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000
- gEfiMdePkgTokenSpaceGuid.PcdMaximumLinkedListLength|1000000
- gEfiMdePkgTokenSpaceGuid.PcdSpinLockTimeout|10000000
- gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue|0xAF
- gEfiMdePkgTokenSpaceGuid.PcdPerformanceLibraryPropertyMask|1
- gEfiMdePkgTokenSpaceGuid.PcdPostCodePropertyMask|0
- gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|320
-
- # DEBUG_ASSERT_ENABLED 0x01
- # DEBUG_PRINT_ENABLED 0x02
- # DEBUG_CODE_ENABLED 0x04
- # CLEAR_MEMORY_ENABLED 0x08
- # ASSERT_BREAKPOINT_ENABLED 0x10
- # ASSERT_DEADLOOP_ENABLED 0x20
-!if $(TARGET) == RELEASE
- gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x21
-!else
- gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f
-!endif
-
- # DEBUG_INIT 0x00000001 // Initialization
- # DEBUG_WARN 0x00000002 // Warnings
- # DEBUG_LOAD 0x00000004 // Load events
- # DEBUG_FS 0x00000008 // EFI File system
- # DEBUG_POOL 0x00000010 // Alloc & Free's
- # DEBUG_PAGE 0x00000020 // Alloc & Free's
- # DEBUG_INFO 0x00000040 // Verbose
- # DEBUG_DISPATCH 0x00000080 // PEI/DXE Dispatchers
- # DEBUG_VARIABLE 0x00000100 // Variable
- # DEBUG_BM 0x00000400 // Boot Manager
- # DEBUG_BLKIO 0x00001000 // BlkIo Driver
- # DEBUG_NET 0x00004000 // SNI Driver
- # DEBUG_UNDI 0x00010000 // UNDI Driver
- # DEBUG_LOADFILE 0x00020000 // UNDI Driver
- # DEBUG_EVENT 0x00080000 // Event messages
- # DEBUG_ERROR 0x80000000 // Error
- gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000000F
-
- gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07
-
- gEmbeddedTokenSpaceGuid.PcdEmbeddedAutomaticBootCommand|""
- gEmbeddedTokenSpaceGuid.PcdEmbeddedDefaultTextColor|0x07
- gEmbeddedTokenSpaceGuid.PcdEmbeddedMemVariableStoreSize|0x10000
-
- #
- # Optional feature to help prevent EFI memory map fragments
- # Turned on and off via: PcdPrePiProduceMemoryTypeInformationHob
- # Values are in EFI Pages (4K). DXE Core will make sure that
- # at least this much of each type of memory can be allocated
- # from a single memory range. This way you only end up with
- # maximum of two fragements for each type in the memory map
- # (the memory used, and the free memory that was prereserved
- # but not used).
- #
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|50
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|20
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|400
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData|20000
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|20
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0
-
- #
- # ARM Pcds
- #
- gArmTokenSpaceGuid.PcdArmUncachedMemoryMask|0x0000000000000000
-
- gArmTokenSpaceGuid.PcdSystemMemoryBase|0
- gArmTokenSpaceGuid.PcdSystemMemorySize|0
-
-################################################################################
-#
-# Components Section - list of all EDK II Modules needed by this Platform
-#
-################################################################################
-[Components.common]
-
- #
- # PEI Phase modules
- #
- ArmPlatformPkg/PrePi/PeiUniCore.inf
-
- #
- # DXE
- #
- MdeModulePkg/Core/Dxe/DxeMain.inf {
- <LibraryClasses>
- PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
- NULL|MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.inf
- }
-
- #
- # Architectural Protocols
- #
- ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
- MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
- MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- MdeModulePkg/Universal/Variable/EmuRuntimeDxe/EmuVariableRuntimeDxe.inf
- EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
-
- EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- # Simple TextIn/TextOut for UEFI Terminal
- EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
-
- #
- #
- # Semi-hosting filesystem
- #
- ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- #
- # FAT filesystem + GPT/MBR partitioning
- #
- MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
- MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- FatPkg/EnhancedFatDxe/Fat.inf
- MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
-
- #
- # Application
- #
- EmbeddedPkg/Ebl/Ebl.inf
-
- #
- # Bds
- #
- MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
- ArmPlatformPkg/Bds/Bds.inf
-
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+ PLATFORM_NAME = ArmPlatform
+ PLATFORM_GUID = 4fe82b83-9315-4ff3-8cc0-ab77ca93cb7f
+ PLATFORM_VERSION = 0.1
+ DSC_SPECIFICATION = 0x00010005
+ OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME)
+ SUPPORTED_ARCHITECTURES = ARM
+ BUILD_TARGETS = DEBUG|RELEASE
+ SKUID_IDENTIFIER = DEFAULT
+ FLASH_DEFINITION = ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf
+
+[LibraryClasses.common]
+ ArmLib|ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
+ ArmCpuLib|ArmPkg/Drivers/ArmCpuLib/ArmCortexA9Lib/ArmCortexA9Lib.inf
+ ArmPlatformLib|ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf
+
+!if $(TARGET) == RELEASE
+ DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
+ UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
+!else
+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+ UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
+# UncachedMemoryAllocationLib|ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
+!endif
+ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf
+
+ BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
+ SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
+ PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+ PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+ PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
+ CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
+
+ UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
+ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+ UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
+ DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
+ UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
+ UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
+ HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
+ UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf
+
+ UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf
+
+ #
+ # Assume everything is fixed at build
+ #
+ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+
+ # 1/123 faster than Stm or Vstm version
+ #BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+ BaseMemoryLib|ArmPkg/Library/BaseMemoryLibStm/BaseMemoryLibStm.inf
+
+ # ARM Architectural Libraries
+ CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
+ DefaultExceptionHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
+ CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf
+ ArmDisassemblerLib|ArmPkg/Library/ArmDisassemblerLib/ArmDisassemblerLib.inf
+ DmaLib|ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
+ ArmGicLib|ArmPkg/Drivers/PL390Gic/PL390GicLib.inf
+ ArmPlatformStackLib|ArmPlatformPkg/Library/ArmPlatformStackLib/ArmPlatformStackLib.inf
+
+ SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf
+ TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
+ EfiResetSystemLib|EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
+ RealTimeClockLib|EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
+
+ # EBL Related Libraries
+ EblCmdLib|ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.inf
+ EfiFileLib|EmbeddedPkg/Library/EfiFileLib/EfiFileLib.inf
+ EblAddExternalCommandLib|EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
+ EblNetworkLib|EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
+
+ #
+ # Uncomment (and comment out the next line) For RealView Debugger. The Standard IO window
+ # in the debugger will show load and unload commands for symbols. You can cut and paste this
+ # into the command window to load symbols. We should be able to use a script to do this, but
+ # the version of RVD I have does not support scripts accessing system memory.
+ #
+ #PeCoffExtraActionLib|ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf
+ PeCoffExtraActionLib|ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf
+ #PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
+
+ DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf
+ DebugAgentTimerLib|EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLibNull.inf
+
+ SemihostLib|ArmPkg/Library/SemihostLib/SemihostLib.inf
+
+ # BDS Libraries
+ BdsLib|ArmPkg/Library/BdsLib/BdsLib.inf
+ FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf
+
+[LibraryClasses.common.SEC]
+ ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.inf
+
+ ArmPlatformSecExtraActionLib|ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf
+ DebugAgentLib|ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentSymbolsBaseLib.inf
+ DefaultExceptionHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLibBase.inf
+
+ PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
+ ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
+ LzmaDecompressLib|IntelFrameworkModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
+ MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf
+ HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf
+ PrePiHobListPointerLib|ArmPlatformPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
+ PerformanceLib|MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.inf
+ PlatformPeiLib|ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf
+ MemoryInitPeiLib|ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf
+
+[LibraryClasses.common.DXE_CORE]
+ HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
+ MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf
+ DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+ ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
+ UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
+ DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
+ PerformanceLib|MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.inf
+
+[LibraryClasses.common.DXE_DRIVER]
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+ DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
+ SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf
+ PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
+
+[LibraryClasses.common.UEFI_APPLICATION]
+ UefiDecompressLib|IntelFrameworkModulePkg/Library/BaseUefiTianoCustomDecompressLib/BaseUefiTianoCustomDecompressLib.inf
+ PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
+
+[LibraryClasses.common.UEFI_DRIVER]
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+ UefiDecompressLib|IntelFrameworkModulePkg/Library/BaseUefiTianoCustomDecompressLib/BaseUefiTianoCustomDecompressLib.inf
+ ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
+ PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+
+[LibraryClasses.common.DXE_RUNTIME_DRIVER]
+ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+ CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
+
+[LibraryClasses.ARM]
+ #
+ # It is not possible to prevent the ARM compiler for generic intrinsic functions.
+ # This library provides the instrinsic functions generate by a given compiler.
+ # [LibraryClasses.ARM] and NULL mean link this library into all ARM images.
+ #
+ NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
+
+[BuildOptions]
+ XCODE:*_*_ARM_PLATFORM_FLAGS == -arch armv7
+
+ GCC:*_*_ARM_PLATFORM_FLAGS == -march=armv7-a
+
+ RVCT:*_*_ARM_PLATFORM_FLAGS == --cpu Cortex-A8
+
+################################################################################
+#
+# Pcd Section - list of all EDK II PCD Entries defined by this Platform
+#
+################################################################################
+
+[PcdsFeatureFlag.common]
+ gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|TRUE
+ gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnosticsDisable|TRUE
+ gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|TRUE
+ gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|TRUE
+
+ #
+ # Control what commands are supported from the UI
+ # Turn these on and off to add features or save size
+ #
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedMacBoot|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedDirCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedHobCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedHwDebugCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPciDebugCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedIoEnable|FALSE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedScriptCmd|FALSE
+
+ gEmbeddedTokenSpaceGuid.PcdCacheEnable|TRUE
+
+ # Use the Vector Table location in CpuDxe. We will not copy the Vector Table at PcdCpuVectorBaseAddress
+ gArmTokenSpaceGuid.PcdRelocateVectorTable|FALSE
+
+ gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob|TRUE
+
+ gEfiMdeModulePkgTokenSpaceGuid.PcdTurnOffUsbLegacySupport|TRUE
+
+[PcdsFixedAtBuild.common]
+ gArmPlatformTokenSpaceGuid.PcdFirmwareVendor|"ARM Platform"
+
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPrompt|"ArmPlatform"
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|32
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|0
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumLinkedListLength|1000000
+ gEfiMdePkgTokenSpaceGuid.PcdSpinLockTimeout|10000000
+ gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue|0xAF
+ gEfiMdePkgTokenSpaceGuid.PcdPerformanceLibraryPropertyMask|1
+ gEfiMdePkgTokenSpaceGuid.PcdPostCodePropertyMask|0
+ gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|320
+
+ # DEBUG_ASSERT_ENABLED 0x01
+ # DEBUG_PRINT_ENABLED 0x02
+ # DEBUG_CODE_ENABLED 0x04
+ # CLEAR_MEMORY_ENABLED 0x08
+ # ASSERT_BREAKPOINT_ENABLED 0x10
+ # ASSERT_DEADLOOP_ENABLED 0x20
+!if $(TARGET) == RELEASE
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x21
+!else
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f
+!endif
+
+ # DEBUG_INIT 0x00000001 // Initialization
+ # DEBUG_WARN 0x00000002 // Warnings
+ # DEBUG_LOAD 0x00000004 // Load events
+ # DEBUG_FS 0x00000008 // EFI File system
+ # DEBUG_POOL 0x00000010 // Alloc & Free's
+ # DEBUG_PAGE 0x00000020 // Alloc & Free's
+ # DEBUG_INFO 0x00000040 // Verbose
+ # DEBUG_DISPATCH 0x00000080 // PEI/DXE Dispatchers
+ # DEBUG_VARIABLE 0x00000100 // Variable
+ # DEBUG_BM 0x00000400 // Boot Manager
+ # DEBUG_BLKIO 0x00001000 // BlkIo Driver
+ # DEBUG_NET 0x00004000 // SNI Driver
+ # DEBUG_UNDI 0x00010000 // UNDI Driver
+ # DEBUG_LOADFILE 0x00020000 // UNDI Driver
+ # DEBUG_EVENT 0x00080000 // Event messages
+ # DEBUG_ERROR 0x80000000 // Error
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000000F
+
+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07
+
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedAutomaticBootCommand|""
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedDefaultTextColor|0x07
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedMemVariableStoreSize|0x10000
+
+ #
+ # Optional feature to help prevent EFI memory map fragments
+ # Turned on and off via: PcdPrePiProduceMemoryTypeInformationHob
+ # Values are in EFI Pages (4K). DXE Core will make sure that
+ # at least this much of each type of memory can be allocated
+ # from a single memory range. This way you only end up with
+ # maximum of two fragements for each type in the memory map
+ # (the memory used, and the free memory that was prereserved
+ # but not used).
+ #
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|50
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|20
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|400
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData|20000
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|20
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0
+
+ #
+ # ARM Pcds
+ #
+ gArmTokenSpaceGuid.PcdArmUncachedMemoryMask|0x0000000000000000
+
+ gArmTokenSpaceGuid.PcdSystemMemoryBase|0
+ gArmTokenSpaceGuid.PcdSystemMemorySize|0
+
+################################################################################
+#
+# Components Section - list of all EDK II Modules needed by this Platform
+#
+################################################################################
+[Components.common]
+
+ #
+ # PEI Phase modules
+ #
+ ArmPlatformPkg/PrePi/PeiUniCore.inf
+
+ #
+ # DXE
+ #
+ MdeModulePkg/Core/Dxe/DxeMain.inf {
+ <LibraryClasses>
+ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+ NULL|MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.inf
+ }
+
+ #
+ # Architectural Protocols
+ #
+ ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+ MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ MdeModulePkg/Universal/Variable/EmuRuntimeDxe/EmuVariableRuntimeDxe.inf
+ EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+
+ EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ # Simple TextIn/TextOut for UEFI Terminal
+ EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
+
+ #
+ #
+ # Semi-hosting filesystem
+ #
+ ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ #
+ # FAT filesystem + GPT/MBR partitioning
+ #
+ MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ #
+ # Application
+ #
+ EmbeddedPkg/Ebl/Ebl.inf
+
+ #
+ # Bds
+ #
+ MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ ArmPlatformPkg/Bds/Bds.inf
+
diff --git a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf
index b66994712..afc2fff48 100644
--- a/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf
+++ b/ArmPlatformPkg/ArmPlatformPkg-2ndstage.fdf
@@ -1,245 +1,253 @@
-#
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-################################################################################
-#
-# FD Section
-# The [FD] Section is made up of the definition statements and a
-# description of what goes into the Flash Device Image. Each FD section
-# defines one flash "device" image. A flash device image may be one of
-# the following: Removable media bootable image (like a boot floppy
-# image,) an Option ROM image (that would be "flashed" into an add-in
-# card,) a System "Flash" image (that would be burned into a system's
-# flash) or an Update ("Capsule") image that will be used to update and
-# existing system flash.
-#
-################################################################################
-
-[FD.ArmPlatform_EFI]
-BaseAddress = 0xEC200000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
-Size = 0x00200000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
-ErasePolarity = 1
-
-# This one is tricky, it must be: BlockSize * NumBlocks = Size
-BlockSize = 0x00001000
-NumBlocks = 0x200
-
-################################################################################
-#
-# Following are lists of FD Region layout which correspond to the locations of different
-# images within the flash device.
-#
-# Regions must be defined in ascending order and may not overlap.
-#
-# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
-# the pipe "|" character, followed by the size of the region, also in hex with the leading
-# "0x" characters. Like:
-# Offset|Size
-# PcdOffsetCName|PcdSizeCName
-# RegionType <FV, DATA, or FILE>
-#
-################################################################################
-
-0x00000000|0x00200000
-gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
-FV = FVMAIN_COMPACT
-
-
-################################################################################
-#
-# FV Section
-#
-# [FV] section is used to define what components or modules are placed within a flash
-# device file. This section also defines order the components and modules are positioned
-# within the image. The [FV] section consists of define statements, set statements and
-# module statements.
-#
-################################################################################
-
-[FV.FvMain]
-BlockSize = 0x40
-NumBlocks = 0 # This FV gets compressed so make it just big enough
-FvAlignment = 8 # FV alignment and FV attributes setting.
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF MdeModulePkg/Core/Dxe/DxeMain.inf
-
- #
- # PI DXE Drivers producing Architectural Protocols (EFI Services)
- #
- INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
- INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
- INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/Variable/EmuRuntimeDxe/EmuVariableRuntimeDxe.inf
- INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
- INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- # Simple TextIn/TextOut for UEFI Terminal
- INF EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
-
- #
- # Semi-hosting filesystem (Required the Hardware Debugger to be connected)
- #
- INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- #
- # FAT filesystem + GPT/MBR partitioning
- #
- INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
- INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- INF FatPkg/EnhancedFatDxe/Fat.inf
- INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
-
- #
- # UEFI application (Shell Embedded Boot Loader)
- #
- INF EmbeddedPkg/Ebl/Ebl.inf
-
- #
- # Bds
- #
- INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
- INF ArmPlatformPkg/Bds/Bds.inf
-
-
-[FV.FVMAIN_COMPACT]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF ArmPlatformPkg/PrePi/PeiUniCore.inf
-
- FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
- SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
- SECTION FV_IMAGE = FVMAIN
- }
- }
-
-
-################################################################################
-#
-# Rules are use with the [FV] section's module INF type to define
-# how an FFS file is created for a given INF file. The following Rule are the default
-# rules for the different module type. User can add the customized rules to define the
-# content of the FFS file.
-#
-################################################################################
-
-
-############################################################################
-# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
-############################################################################
-#
-#[Rule.Common.DXE_DRIVER]
-# FILE DRIVER = $(NAMED_GUID) {
-# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
-# COMPRESS PI_STD {
-# GUIDED {
-# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
-# UI STRING="$(MODULE_NAME)" Optional
-# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
-# }
-# }
-# }
-#
-############################################################################
-
-[Rule.Common.SEC]
- FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
- TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.PEI_CORE]
- FILE PEI_CORE = $(NAMED_GUID) {
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING ="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM]
- FILE PEIM = $(NAMED_GUID) {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM.TIANOCOMPRESSED]
- FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
- }
-
-[Rule.Common.DXE_CORE]
- FILE DXE_CORE = $(NAMED_GUID) {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_RUNTIME_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_APPLICATION]
- FILE APPLICATION = $(NAMED_GUID) {
- UI STRING ="$(MODULE_NAME)" Optional
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+################################################################################
+#
+# FD Section
+# The [FD] Section is made up of the definition statements and a
+# description of what goes into the Flash Device Image. Each FD section
+# defines one flash "device" image. A flash device image may be one of
+# the following: Removable media bootable image (like a boot floppy
+# image,) an Option ROM image (that would be "flashed" into an add-in
+# card,) a System "Flash" image (that would be burned into a system's
+# flash) or an Update ("Capsule") image that will be used to update and
+# existing system flash.
+#
+################################################################################
+
+[FD.ArmPlatform_EFI]
+BaseAddress = 0xEC200000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
+Size = 0x00200000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
+ErasePolarity = 1
+
+# This one is tricky, it must be: BlockSize * NumBlocks = Size
+BlockSize = 0x00001000
+NumBlocks = 0x200
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|0x00200000
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+
+################################################################################
+#
+# FV Section
+#
+# [FV] section is used to define what components or modules are placed within a flash
+# device file. This section also defines order the components and modules are positioned
+# within the image. The [FV] section consists of define statements, set statements and
+# module statements.
+#
+################################################################################
+
+[FV.FvMain]
+BlockSize = 0x40
+NumBlocks = 0 # This FV gets compressed so make it just big enough
+FvAlignment = 8 # FV alignment and FV attributes setting.
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+
+ #
+ # PI DXE Drivers producing Architectural Protocols (EFI Services)
+ #
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/Variable/EmuRuntimeDxe/EmuVariableRuntimeDxe.inf
+ INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+ INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ # Simple TextIn/TextOut for UEFI Terminal
+ INF EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
+
+ #
+ # Semi-hosting filesystem (Required the Hardware Debugger to be connected)
+ #
+ INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ #
+ # FAT filesystem + GPT/MBR partitioning
+ #
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF FatBinPkg/EnhancedFatDxe/Fat.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ #
+ # UEFI application (Shell Embedded Boot Loader)
+ #
+ INF EmbeddedPkg/Ebl/Ebl.inf
+
+ #
+ # Bds
+ #
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF ArmPlatformPkg/Bds/Bds.inf
+
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF ArmPlatformPkg/PrePi/PeiUniCore.inf
+
+ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+ SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+ SECTION FV_IMAGE = FVMAIN
+ }
+ }
+
+
+################################################################################
+#
+# Rules are use with the [FV] section's module INF type to define
+# how an FFS file is created for a given INF file. The following Rule are the default
+# rules for the different module type. User can add the customized rules to define the
+# content of the FFS file.
+#
+################################################################################
+
+
+############################################################################
+# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
+############################################################################
+#
+#[Rule.Common.DXE_DRIVER]
+# FILE DRIVER = $(NAMED_GUID) {
+# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+# COMPRESS PI_STD {
+# GUIDED {
+# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+# UI STRING="$(MODULE_NAME)" Optional
+# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+# }
+# }
+# }
+#
+############################################################################
+
+[Rule.Common.SEC]
+ FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
+ TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.PEI_CORE]
+ FILE PEI_CORE = $(NAMED_GUID) {
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING ="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM]
+ FILE PEIM = $(NAMED_GUID) {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM.TIANOCOMPRESSED]
+ FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+ }
+
+[Rule.Common.DXE_CORE]
+ FILE DXE_CORE = $(NAMED_GUID) {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER.BINARY]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional |.depex
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
+
+[Rule.Common.DXE_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_RUNTIME_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_APPLICATION]
+ FILE APPLICATION = $(NAMED_GUID) {
+ UI STRING ="$(MODULE_NAME)" Optional
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
diff --git a/ArmPlatformPkg/ArmPlatformPkg.dec b/ArmPlatformPkg/ArmPlatformPkg.dec
index 07205273b..024023df2 100644
--- a/ArmPlatformPkg/ArmPlatformPkg.dec
+++ b/ArmPlatformPkg/ArmPlatformPkg.dec
@@ -135,7 +135,7 @@
# - 2 = a Linux kernel with FDT support
gArmPlatformTokenSpaceGuid.PcdDefaultBootType|0|UINT32|0x00000010
gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L""|VOID*|0x00000011
- gArmPlatformTokenSpaceGuid.PcdFdtLocalDevicePath|L""|VOID*|0x0000002E
+ gArmPlatformTokenSpaceGuid.PcdDefaultFdtLocalDevicePath|L""|VOID*|0x0000002E
## Timeout value for displaying progressing bar in before boot OS.
# According to UEFI 2.0 spec, the default TimeOut should be 0xffff.
diff --git a/ArmPlatformPkg/ArmPlatformPkg.dsc b/ArmPlatformPkg/ArmPlatformPkg.dsc
index c9ef38510..82159fcb2 100644
--- a/ArmPlatformPkg/ArmPlatformPkg.dsc
+++ b/ArmPlatformPkg/ArmPlatformPkg.dsc
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -121,6 +121,7 @@
ArmPlatformGlobalVariableLib|ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Sec/SecArmPlatformGlobalVariableLib.inf
DebugAgentLib|ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentSymbolsBaseLib.inf
+ DefaultExceptionHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLibBase.inf
[LibraryClasses.common.PEI_CORE]
HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
@@ -400,7 +401,6 @@
#
MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- FatPkg/EnhancedFatDxe/Fat.inf
MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
#
diff --git a/ArmPlatformPkg/ArmPlatformPkg.fdf b/ArmPlatformPkg/ArmPlatformPkg.fdf
index d829d4043..887c1c10d 100644
--- a/ArmPlatformPkg/ArmPlatformPkg.fdf
+++ b/ArmPlatformPkg/ArmPlatformPkg.fdf
@@ -1,302 +1,310 @@
-#
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-################################################################################
-#
-# FD Section
-# The [FD] Section is made up of the definition statements and a
-# description of what goes into the Flash Device Image. Each FD section
-# defines one flash "device" image. A flash device image may be one of
-# the following: Removable media bootable image (like a boot floppy
-# image,) an Option ROM image (that would be "flashed" into an add-in
-# card,) a System "Flash" image (that would be burned into a system's
-# flash) or an Update ("Capsule") image that will be used to update and
-# existing system flash.
-#
-################################################################################
-
-[FD.Sec_ArmPlatform_EFI]
-BaseAddress = 0xEC000000|gArmTokenSpaceGuid.PcdSecureFdBaseAddress #The base address of the Secure FLASH Device.
-Size = 0x00010000|gArmTokenSpaceGuid.PcdSecureFdSize #The size in bytes of the Secure FLASH Device
-ErasePolarity = 1
-BlockSize = 0x00001000
-NumBlocks = 0x10
-
-################################################################################
-#
-# Following are lists of FD Region layout which correspond to the locations of different
-# images within the flash device.
-#
-# Regions must be defined in ascending order and may not overlap.
-#
-# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
-# the pipe "|" character, followed by the size of the region, also in hex with the leading
-# "0x" characters. Like:
-# Offset|Size
-# PcdOffsetCName|PcdSizeCName
-# RegionType <FV, DATA, or FILE>
-#
-################################################################################
-
-0x00000000|0x00010000
-gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
-FV = FVMAIN_SEC
-
-
-[FD.ArmPlatform_EFI]
-BaseAddress = 0xEC200000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
-Size = 0x00200000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
-ErasePolarity = 1
-
-# This one is tricky, it must be: BlockSize * NumBlocks = Size
-BlockSize = 0x00001000
-NumBlocks = 0x200
-
-################################################################################
-#
-# Following are lists of FD Region layout which correspond to the locations of different
-# images within the flash device.
-#
-# Regions must be defined in ascending order and may not overlap.
-#
-# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
-# the pipe "|" character, followed by the size of the region, also in hex with the leading
-# "0x" characters. Like:
-# Offset|Size
-# PcdOffsetCName|PcdSizeCName
-# RegionType <FV, DATA, or FILE>
-#
-################################################################################
-
-0x00000000|0x00200000
-gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
-FV = FVMAIN_COMPACT
-
-
-################################################################################
-#
-# FV Section
-#
-# [FV] section is used to define what components or modules are placed within a flash
-# device file. This section also defines order the components and modules are positioned
-# within the image. The [FV] section consists of define statements, set statements and
-# module statements.
-#
-################################################################################
-
-[FV.FVMAIN_SEC]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF ArmPlatformPkg/Sec/Sec.inf
-
-
-[FV.FvMain]
-BlockSize = 0x40
-NumBlocks = 0 # This FV gets compressed so make it just big enough
-FvAlignment = 8 # FV alignment and FV attributes setting.
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF MdeModulePkg/Core/Dxe/DxeMain.inf
-
- #
- # PI DXE Drivers producing Architectural Protocols (EFI Services)
- #
- INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
- INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
- INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/Variable/EmuRuntimeDxe/EmuVariableRuntimeDxe.inf
- INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
- INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- # Simple TextIn/TextOut for UEFI Terminal
- INF EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
-
- #
- # Semi-hosting filesystem (Required the Hardware Debugger to be connected)
- #
- INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- #
- # FAT filesystem + GPT/MBR partitioning
- #
- INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
- INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- INF FatPkg/EnhancedFatDxe/Fat.inf
- INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
-
- #
- # UEFI application (Shell Embedded Boot Loader)
- #
- INF EmbeddedPkg/Ebl/Ebl.inf
-
- #
- # Bds
- #
- INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
- INF ArmPlatformPkg/Bds/Bds.inf
-
-
-[FV.FVMAIN_COMPACT]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf
- INF MdeModulePkg/Core/Pei/PeiMain.inf
- INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
- INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
- INF ArmPkg/Drivers/CpuPei/CpuPei.inf
- INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
- INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
- INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
- INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
-
- FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
- SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
- SECTION FV_IMAGE = FVMAIN
- }
- }
-
-
-################################################################################
-#
-# Rules are use with the [FV] section's module INF type to define
-# how an FFS file is created for a given INF file. The following Rule are the default
-# rules for the different module type. User can add the customized rules to define the
-# content of the FFS file.
-#
-################################################################################
-
-
-############################################################################
-# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
-############################################################################
-#
-#[Rule.Common.DXE_DRIVER]
-# FILE DRIVER = $(NAMED_GUID) {
-# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
-# COMPRESS PI_STD {
-# GUIDED {
-# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
-# UI STRING="$(MODULE_NAME)" Optional
-# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
-# }
-# }
-# }
-#
-############################################################################
-
-[Rule.Common.SEC]
- FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
- TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.PEI_CORE]
- FILE PEI_CORE = $(NAMED_GUID) {
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING ="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM]
- FILE PEIM = $(NAMED_GUID) {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM.TIANOCOMPRESSED]
- FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
- }
-
-[Rule.Common.DXE_CORE]
- FILE DXE_CORE = $(NAMED_GUID) {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_RUNTIME_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_APPLICATION]
- FILE APPLICATION = $(NAMED_GUID) {
- UI STRING ="$(MODULE_NAME)" Optional
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+################################################################################
+#
+# FD Section
+# The [FD] Section is made up of the definition statements and a
+# description of what goes into the Flash Device Image. Each FD section
+# defines one flash "device" image. A flash device image may be one of
+# the following: Removable media bootable image (like a boot floppy
+# image,) an Option ROM image (that would be "flashed" into an add-in
+# card,) a System "Flash" image (that would be burned into a system's
+# flash) or an Update ("Capsule") image that will be used to update and
+# existing system flash.
+#
+################################################################################
+
+[FD.Sec_ArmPlatform_EFI]
+BaseAddress = 0xEC000000|gArmTokenSpaceGuid.PcdSecureFdBaseAddress #The base address of the Secure FLASH Device.
+Size = 0x00012000|gArmTokenSpaceGuid.PcdSecureFdSize #The size in bytes of the Secure FLASH Device
+ErasePolarity = 1
+BlockSize = 0x00001200
+NumBlocks = 0x10
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|0x00012000
+gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
+FV = FVMAIN_SEC
+
+
+[FD.ArmPlatform_EFI]
+BaseAddress = 0xEC200000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
+Size = 0x00200000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
+ErasePolarity = 1
+
+# This one is tricky, it must be: BlockSize * NumBlocks = Size
+BlockSize = 0x00001000
+NumBlocks = 0x200
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|0x00200000
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+
+################################################################################
+#
+# FV Section
+#
+# [FV] section is used to define what components or modules are placed within a flash
+# device file. This section also defines order the components and modules are positioned
+# within the image. The [FV] section consists of define statements, set statements and
+# module statements.
+#
+################################################################################
+
+[FV.FVMAIN_SEC]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF ArmPlatformPkg/Sec/Sec.inf
+
+
+[FV.FvMain]
+BlockSize = 0x40
+NumBlocks = 0 # This FV gets compressed so make it just big enough
+FvAlignment = 8 # FV alignment and FV attributes setting.
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+
+ #
+ # PI DXE Drivers producing Architectural Protocols (EFI Services)
+ #
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/Variable/EmuRuntimeDxe/EmuVariableRuntimeDxe.inf
+ INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+ INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ # Simple TextIn/TextOut for UEFI Terminal
+ INF EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
+
+ #
+ # Semi-hosting filesystem (Required the Hardware Debugger to be connected)
+ #
+ INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ #
+ # FAT filesystem + GPT/MBR partitioning
+ #
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF FatBinPkg/EnhancedFatDxe/Fat.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ #
+ # UEFI application (Shell Embedded Boot Loader)
+ #
+ INF EmbeddedPkg/Ebl/Ebl.inf
+
+ #
+ # Bds
+ #
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF ArmPlatformPkg/Bds/Bds.inf
+
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf
+ INF MdeModulePkg/Core/Pei/PeiMain.inf
+ INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
+ INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
+ INF ArmPkg/Drivers/CpuPei/CpuPei.inf
+ INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+ INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
+ INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
+ INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+
+ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+ SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+ SECTION FV_IMAGE = FVMAIN
+ }
+ }
+
+
+################################################################################
+#
+# Rules are use with the [FV] section's module INF type to define
+# how an FFS file is created for a given INF file. The following Rule are the default
+# rules for the different module type. User can add the customized rules to define the
+# content of the FFS file.
+#
+################################################################################
+
+
+############################################################################
+# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
+############################################################################
+#
+#[Rule.Common.DXE_DRIVER]
+# FILE DRIVER = $(NAMED_GUID) {
+# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+# COMPRESS PI_STD {
+# GUIDED {
+# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+# UI STRING="$(MODULE_NAME)" Optional
+# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+# }
+# }
+# }
+#
+############################################################################
+
+[Rule.Common.SEC]
+ FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
+ TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.PEI_CORE]
+ FILE PEI_CORE = $(NAMED_GUID) {
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING ="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM]
+ FILE PEIM = $(NAMED_GUID) {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM.TIANOCOMPRESSED]
+ FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+ }
+
+[Rule.Common.DXE_CORE]
+ FILE DXE_CORE = $(NAMED_GUID) {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER.BINARY]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional |.depex
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
+
+[Rule.Common.DXE_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_RUNTIME_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_APPLICATION]
+ FILE APPLICATION = $(NAMED_GUID) {
+ UI STRING ="$(MODULE_NAME)" Optional
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf b/ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf
index 558e304f5..70fc87bcf 100644
--- a/ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf
+++ b/ArmPlatformPkg/ArmRealViewEbPkg/ArmRealViewEb-RTSM-MPCore.fdf
@@ -1,310 +1,310 @@
-# FLASH layout file for ARM VE.
-#
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-################################################################################
-#
-# FD Section
-# The [FD] Section is made up of the definition statements and a
-# description of what goes into the Flash Device Image. Each FD section
-# defines one flash "device" image. A flash device image may be one of
-# the following: Removable media bootable image (like a boot floppy
-# image,) an Option ROM image (that would be "flashed" into an add-in
-# card,) a System "Flash" image (that would be burned into a system's
-# flash) or an Update ("Capsule") image that will be used to update and
-# existing system flash.
-#
-################################################################################
-
-
-[FD.ArmRealViewEb_EFI]
-BaseAddress = 0x40000000|gArmTokenSpaceGuid.PcdFdBaseAddress
-Size = 0x00200000|gArmTokenSpaceGuid.PcdFdSize
-ErasePolarity = 1
-BlockSize = 0x00010000
-NumBlocks = 0x20
-
-################################################################################
-#
-# Following are lists of FD Region layout which correspond to the locations of different
-# images within the flash device.
-#
-# Regions must be defined in ascending order and may not overlap.
-#
-# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
-# the pipe "|" character, followed by the size of the region, also in hex with the leading
-# "0x" characters. Like:
-# Offset|Size
-# PcdOffsetCName|PcdSizeCName
-# RegionType <FV, DATA, or FILE>
-#
-################################################################################
-
-0x00000000|0x00050000
-gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
-FV = FVMAIN_SEC
-
-0x00050000|0x00100000
-gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
-FV = FVMAIN_COMPACT
-
-################################################################################
-#
-# FV Section
-#
-# [FV] section is used to define what components or modules are placed within a flash
-# device file. This section also defines order the components and modules are positioned
-# within the image. The [FV] section consists of define statements, set statements and
-# module statements.
-#
-################################################################################
-
-[FV.FVMAIN_SEC]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF ArmPlatformPkg/Sec/Sec.inf
-
-
-[FV.FvMain]
-BlockSize = 0x40
-NumBlocks = 0 # This FV gets compressed so make it just big enough
-FvAlignment = 8 # FV alignment and FV attributes setting.
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF MdeModulePkg/Core/Dxe/DxeMain.inf
-
- #
- # PI DXE Drivers producing Architectural Protocols (EFI Services)
- #
- INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
- INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
- INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
- INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
- INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
- INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
- INF ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
-
- #
- # Multiple Console IO support
- #
- INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
- INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
- INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
- INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
- INF EmbeddedPkg/SerialDxe/SerialDxe.inf
-
- INF ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
- INF ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf
-
- INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
-
- #
- # Semi-hosting filesystem
- #
- INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- #
- # FAT filesystem + GPT/MBR partitioning
- #
- INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
- INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- INF FatBinPkg/EnhancedFatDxe/Fat.inf
- INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
-
- #
- # UEFI application (Shell Embedded Boot Loader)
- #
- INF ShellBinPkg/UefiShell/UefiShell.inf
-
- #
- # Bds
- #
- INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
- INF ArmPlatformPkg/Bds/Bds.inf
-
-
-[FV.FVMAIN_COMPACT]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
-!if $(EDK2_SKIP_PEICORE) == 1
- INF ArmPlatformPkg/PrePi/PeiMPCore.inf
-!else
- INF ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf
- INF MdeModulePkg/Core/Pei/PeiMain.inf
- INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
- INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
- INF ArmPkg/Drivers/CpuPei/CpuPei.inf
- INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
- INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
- INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
- INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
-!endif
-
- FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
- SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
- SECTION FV_IMAGE = FVMAIN
- }
- }
-
-################################################################################
-#
-# Rules are use with the [FV] section's module INF type to define
-# how an FFS file is created for a given INF file. The following Rule are the default
-# rules for the different module type. User can add the customized rules to define the
-# content of the FFS file.
-#
-################################################################################
-
-
-############################################################################
-# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
-############################################################################
-#
-#[Rule.Common.DXE_DRIVER]
-# FILE DRIVER = $(NAMED_GUID) {
-# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
-# COMPRESS PI_STD {
-# GUIDED {
-# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
-# UI STRING="$(MODULE_NAME)" Optional
-# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
-# }
-# }
-# }
-#
-############################################################################
-
-[Rule.Common.SEC]
- FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
- TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.PEI_CORE]
- FILE PEI_CORE = $(NAMED_GUID) {
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING ="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM]
- FILE PEIM = $(NAMED_GUID) {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM.TIANOCOMPRESSED]
- FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
- }
-
-[Rule.Common.DXE_CORE]
- FILE DXE_CORE = $(NAMED_GUID) {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_RUNTIME_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_APPLICATION]
- FILE APPLICATION = $(NAMED_GUID) {
- UI STRING ="$(MODULE_NAME)" Optional
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.UEFI_DRIVER.BINARY]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional |.depex
- PE32 PE32 |.efi
- UI STRING="$(MODULE_NAME)" Optional
- VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
- }
-
-[Rule.Common.UEFI_APPLICATION.BINARY]
- FILE APPLICATION = $(NAMED_GUID) {
- PE32 PE32 |.efi
- UI STRING="$(MODULE_NAME)" Optional
- VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
- }
+# FLASH layout file for ARM VE.
+#
+# Copyright (c) 2011, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+################################################################################
+#
+# FD Section
+# The [FD] Section is made up of the definition statements and a
+# description of what goes into the Flash Device Image. Each FD section
+# defines one flash "device" image. A flash device image may be one of
+# the following: Removable media bootable image (like a boot floppy
+# image,) an Option ROM image (that would be "flashed" into an add-in
+# card,) a System "Flash" image (that would be burned into a system's
+# flash) or an Update ("Capsule") image that will be used to update and
+# existing system flash.
+#
+################################################################################
+
+
+[FD.ArmRealViewEb_EFI]
+BaseAddress = 0x40000000|gArmTokenSpaceGuid.PcdFdBaseAddress
+Size = 0x00200000|gArmTokenSpaceGuid.PcdFdSize
+ErasePolarity = 1
+BlockSize = 0x00010000
+NumBlocks = 0x20
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|0x00050000
+gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
+FV = FVMAIN_SEC
+
+0x00050000|0x00100000
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+################################################################################
+#
+# FV Section
+#
+# [FV] section is used to define what components or modules are placed within a flash
+# device file. This section also defines order the components and modules are positioned
+# within the image. The [FV] section consists of define statements, set statements and
+# module statements.
+#
+################################################################################
+
+[FV.FVMAIN_SEC]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF ArmPlatformPkg/Sec/Sec.inf
+
+
+[FV.FvMain]
+BlockSize = 0x40
+NumBlocks = 0 # This FV gets compressed so make it just big enough
+FvAlignment = 8 # FV alignment and FV attributes setting.
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+
+ #
+ # PI DXE Drivers producing Architectural Protocols (EFI Services)
+ #
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+ INF EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+ INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+ INF ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
+
+ #
+ # Multiple Console IO support
+ #
+ INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+ INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+ INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
+ INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
+ INF EmbeddedPkg/SerialDxe/SerialDxe.inf
+
+ INF ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
+ INF ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf
+
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
+
+ #
+ # Semi-hosting filesystem
+ #
+ INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ #
+ # FAT filesystem + GPT/MBR partitioning
+ #
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF FatBinPkg/EnhancedFatDxe/Fat.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ #
+ # UEFI application (Shell Embedded Boot Loader)
+ #
+ INF ShellBinPkg/UefiShell/UefiShell.inf
+
+ #
+ # Bds
+ #
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF ArmPlatformPkg/Bds/Bds.inf
+
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+!if $(EDK2_SKIP_PEICORE) == 1
+ INF ArmPlatformPkg/PrePi/PeiMPCore.inf
+!else
+ INF ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf
+ INF MdeModulePkg/Core/Pei/PeiMain.inf
+ INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
+ INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
+ INF ArmPkg/Drivers/CpuPei/CpuPei.inf
+ INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+ INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
+ INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
+ INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+!endif
+
+ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+ SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+ SECTION FV_IMAGE = FVMAIN
+ }
+ }
+
+################################################################################
+#
+# Rules are use with the [FV] section's module INF type to define
+# how an FFS file is created for a given INF file. The following Rule are the default
+# rules for the different module type. User can add the customized rules to define the
+# content of the FFS file.
+#
+################################################################################
+
+
+############################################################################
+# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
+############################################################################
+#
+#[Rule.Common.DXE_DRIVER]
+# FILE DRIVER = $(NAMED_GUID) {
+# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+# COMPRESS PI_STD {
+# GUIDED {
+# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+# UI STRING="$(MODULE_NAME)" Optional
+# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+# }
+# }
+# }
+#
+############################################################################
+
+[Rule.Common.SEC]
+ FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
+ TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.PEI_CORE]
+ FILE PEI_CORE = $(NAMED_GUID) {
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING ="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM]
+ FILE PEIM = $(NAMED_GUID) {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM.TIANOCOMPRESSED]
+ FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+ }
+
+[Rule.Common.DXE_CORE]
+ FILE DXE_CORE = $(NAMED_GUID) {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_RUNTIME_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_APPLICATION]
+ FILE APPLICATION = $(NAMED_GUID) {
+ UI STRING ="$(MODULE_NAME)" Optional
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.UEFI_DRIVER.BINARY]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional |.depex
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
+
+[Rule.Common.UEFI_APPLICATION.BINARY]
+ FILE APPLICATION = $(NAMED_GUID) {
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbLibRTSM/ArmRealViewEb.c b/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbLibRTSM/ArmRealViewEb.c
index a5fb26a32..77d48acce 100644
--- a/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbLibRTSM/ArmRealViewEb.c
+++ b/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbLibRTSM/ArmRealViewEb.c
@@ -1,146 +1,146 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/IoLib.h>
-#include <Library/ArmLib.h>
-#include <Library/ArmPlatformLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-
-#include <Drivers/PL341Dmc.h>
-#include <Drivers/SP804Timer.h>
-
-#include <Ppi/ArmMpCoreInfo.h>
-
-#include <ArmPlatform.h>
-
-ARM_CORE_INFO mRealViewEbMpCoreInfoTable[] = {
- {
- // Cluster 0, Core 0
- 0x0, 0x0,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 1
- 0x0, 0x1,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- }
-};
-
-/**
- Return the current Boot Mode
-
- This function returns the boot reason on the platform
-
-**/
-EFI_BOOT_MODE
-ArmPlatformGetBootMode (
- VOID
- )
-{
- return BOOT_WITH_FULL_CONFIGURATION;
-}
-
-/**
- Initialize controllers that must setup in the normal world
-
- This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
- in the PEI phase.
-
-**/
-RETURN_STATUS
-ArmPlatformInitialize (
- IN UINTN MpId
- )
-{
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // Disable memory remapping and return to normal mapping
- MmioOr32 (ARM_EB_SYSCTRL, BIT8); //EB_SP810_CTRL_BASE
-
- // Configure periodic timer (TIMER0) for 1MHz operation
- MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER0_TIMCLK);
- // Configure 1MHz clock
- MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER1_TIMCLK);
- // configure SP810 to use 1MHz clock and disable
- MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER2_EN, SP810_SYS_CTRL_TIMER2_TIMCLK);
- // Configure SP810 to use 1MHz clock and disable
- MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER3_EN, SP810_SYS_CTRL_TIMER3_TIMCLK);
-
- return RETURN_SUCCESS;
-}
-
-/**
- Initialize the system (or sometimes called permanent) memory
-
- This memory is generally represented by the DRAM.
-
-**/
-VOID
-ArmPlatformInitializeSystemMemory (
- VOID
- )
-{
- // We do not need to initialize the System Memory on RTSM
-}
-
-EFI_STATUS
-PrePeiCoreGetMpCoreInfo (
- OUT UINTN *CoreCount,
- OUT ARM_CORE_INFO **ArmCoreTable
- )
-{
- if ((MmioRead32 (ARM_EB_SYS_PROCID0_REG) & ARM_EB_SYS_PROC_ID_MASK) == ARM_EB_SYS_PROC_ID_CORTEX_A9) {
- *CoreCount = sizeof(mRealViewEbMpCoreInfoTable) / sizeof(ARM_CORE_INFO);
- *ArmCoreTable = mRealViewEbMpCoreInfoTable;
- return EFI_SUCCESS;
- } else {
- return EFI_UNSUPPORTED;
- }
-}
-
-// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
-EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
-ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
-
-EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
- {
- EFI_PEI_PPI_DESCRIPTOR_PPI,
- &mArmMpCoreInfoPpiGuid,
- &mMpCoreInfoPpi
- }
-};
-
-VOID
-ArmPlatformGetPlatformPpiList (
- OUT UINTN *PpiListSize,
- OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
- )
-{
- *PpiListSize = sizeof(gPlatformPpiTable);
- *PpiList = gPlatformPpiTable;
-}
-
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/IoLib.h>
+#include <Library/ArmLib.h>
+#include <Library/ArmPlatformLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+
+#include <Drivers/PL341Dmc.h>
+#include <Drivers/SP804Timer.h>
+
+#include <Ppi/ArmMpCoreInfo.h>
+
+#include <ArmPlatform.h>
+
+ARM_CORE_INFO mRealViewEbMpCoreInfoTable[] = {
+ {
+ // Cluster 0, Core 0
+ 0x0, 0x0,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 1
+ 0x0, 0x1,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_EB_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ }
+};
+
+/**
+ Return the current Boot Mode
+
+ This function returns the boot reason on the platform
+
+**/
+EFI_BOOT_MODE
+ArmPlatformGetBootMode (
+ VOID
+ )
+{
+ return BOOT_WITH_FULL_CONFIGURATION;
+}
+
+/**
+ Initialize controllers that must setup in the normal world
+
+ This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
+ in the PEI phase.
+
+**/
+RETURN_STATUS
+ArmPlatformInitialize (
+ IN UINTN MpId
+ )
+{
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // Disable memory remapping and return to normal mapping
+ MmioOr32 (ARM_EB_SYSCTRL, BIT8); //EB_SP810_CTRL_BASE
+
+ // Configure periodic timer (TIMER0) for 1MHz operation
+ MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER0_TIMCLK);
+ // Configure 1MHz clock
+ MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER1_TIMCLK);
+ // configure SP810 to use 1MHz clock and disable
+ MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER2_EN, SP810_SYS_CTRL_TIMER2_TIMCLK);
+ // Configure SP810 to use 1MHz clock and disable
+ MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER3_EN, SP810_SYS_CTRL_TIMER3_TIMCLK);
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Initialize the system (or sometimes called permanent) memory
+
+ This memory is generally represented by the DRAM.
+
+**/
+VOID
+ArmPlatformInitializeSystemMemory (
+ VOID
+ )
+{
+ // We do not need to initialize the System Memory on RTSM
+}
+
+EFI_STATUS
+PrePeiCoreGetMpCoreInfo (
+ OUT UINTN *CoreCount,
+ OUT ARM_CORE_INFO **ArmCoreTable
+ )
+{
+ if ((MmioRead32 (ARM_EB_SYS_PROCID0_REG) & ARM_EB_SYS_PROC_ID_MASK) == ARM_EB_SYS_PROC_ID_CORTEX_A9) {
+ *CoreCount = sizeof(mRealViewEbMpCoreInfoTable) / sizeof(ARM_CORE_INFO);
+ *ArmCoreTable = mRealViewEbMpCoreInfoTable;
+ return EFI_SUCCESS;
+ } else {
+ return EFI_UNSUPPORTED;
+ }
+}
+
+// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
+EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
+ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
+
+EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
+ {
+ EFI_PEI_PPI_DESCRIPTOR_PPI,
+ &mArmMpCoreInfoPpiGuid,
+ &mMpCoreInfoPpi
+ }
+};
+
+VOID
+ArmPlatformGetPlatformPpiList (
+ OUT UINTN *PpiListSize,
+ OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
+ )
+{
+ *PpiListSize = sizeof(gPlatformPpiTable);
+ *PpiList = gPlatformPpiTable;
+}
+
diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbSecLibRTSM/ArmRealViewEbSec.c b/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbSecLibRTSM/ArmRealViewEbSec.c
index 10dcef92a..033c9d7ea 100644
--- a/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbSecLibRTSM/ArmRealViewEbSec.c
+++ b/ArmPlatformPkg/ArmRealViewEbPkg/Library/ArmRealViewEbSecLibRTSM/ArmRealViewEbSec.c
@@ -1,76 +1,76 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/IoLib.h>
-#include <Library/ArmLib.h>
-#include <Library/ArmPlatformSecLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-
-#include <Drivers/PL341Dmc.h>
-#include <Drivers/SP804Timer.h>
-
-#include <ArmPlatform.h>
-
-/**
- Initialize the Secure peripherals and memory regions
-
- If Trustzone is supported by your platform then this function makes the required initialization
- of the secure peripherals and memory regions.
-
-**/
-VOID
-ArmPlatformSecTrustzoneInit (
- IN UINTN MpId
- )
-{
- ASSERT(FALSE);
-}
-
-/**
- Initialize controllers that must setup at the early stage
-
- Some peripherals must be initialized in Secure World.
- For example, some L2x0 requires to be initialized in Secure World
-
-**/
-RETURN_STATUS
-ArmPlatformSecInitialize (
- IN UINTN MpId
- )
-{
- // If it is not the primary core then there is nothing to do
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // Do nothing yet
- return RETURN_SUCCESS;
-}
-
-/**
- Call before jumping to Normal World
-
- This function allows the firmware platform to do extra actions before
- jumping to the Normal World
-
-**/
-VOID
-ArmPlatformSecExtraAction (
- IN UINTN MpId,
- OUT UINTN* JumpAddress
- )
-{
- *JumpAddress = PcdGet32(PcdFvBaseAddress);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/IoLib.h>
+#include <Library/ArmLib.h>
+#include <Library/ArmPlatformSecLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+
+#include <Drivers/PL341Dmc.h>
+#include <Drivers/SP804Timer.h>
+
+#include <ArmPlatform.h>
+
+/**
+ Initialize the Secure peripherals and memory regions
+
+ If Trustzone is supported by your platform then this function makes the required initialization
+ of the secure peripherals and memory regions.
+
+**/
+VOID
+ArmPlatformSecTrustzoneInit (
+ IN UINTN MpId
+ )
+{
+ ASSERT(FALSE);
+}
+
+/**
+ Initialize controllers that must setup at the early stage
+
+ Some peripherals must be initialized in Secure World.
+ For example, some L2x0 requires to be initialized in Secure World
+
+**/
+RETURN_STATUS
+ArmPlatformSecInitialize (
+ IN UINTN MpId
+ )
+{
+ // If it is not the primary core then there is nothing to do
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // Do nothing yet
+ return RETURN_SUCCESS;
+}
+
+/**
+ Call before jumping to Normal World
+
+ This function allows the firmware platform to do extra actions before
+ jumping to the Normal World
+
+**/
+VOID
+ArmPlatformSecExtraAction (
+ IN UINTN MpId,
+ OUT UINTN* JumpAddress
+ )
+{
+ *JumpAddress = PcdGet32(PcdFvBaseAddress);
+}
diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/Library/NorFlashArmRealViewEbLib/NorFlashArmRealViewEbLib.inf b/ArmPlatformPkg/ArmRealViewEbPkg/Library/NorFlashArmRealViewEbLib/NorFlashArmRealViewEbLib.inf
index 9a68da96a..48dd960cf 100644
--- a/ArmPlatformPkg/ArmRealViewEbPkg/Library/NorFlashArmRealViewEbLib/NorFlashArmRealViewEbLib.inf
+++ b/ArmPlatformPkg/ArmRealViewEbPkg/Library/NorFlashArmRealViewEbLib/NorFlashArmRealViewEbLib.inf
@@ -1,35 +1,35 @@
-#/** @file
-#
-# Component description file for NorFlashArmRealViewEbLib module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = NorFlashArmRealViewEbLib
- FILE_GUID = a3a49a60-7597-11e0-b07c-0002a5d5c51b
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- LIBRARY_CLASS = NorFlashPlatformLib
-
-[Sources.common]
- NorFlashArmRealViewEb.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- IoLib
+#/** @file
+#
+# Component description file for NorFlashArmRealViewEbLib module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = NorFlashArmRealViewEbLib
+ FILE_GUID = a3a49a60-7597-11e0-b07c-0002a5d5c51b
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = NorFlashPlatformLib
+
+[Sources.common]
+ NorFlashArmRealViewEb.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ IoLib
diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/Library/PL111LcdArmRealViewEbLib/PL111LcdArmRealViewEbLib.inf b/ArmPlatformPkg/ArmRealViewEbPkg/Library/PL111LcdArmRealViewEbLib/PL111LcdArmRealViewEbLib.inf
index fda59de7f..b44e868c0 100644
--- a/ArmPlatformPkg/ArmRealViewEbPkg/Library/PL111LcdArmRealViewEbLib/PL111LcdArmRealViewEbLib.inf
+++ b/ArmPlatformPkg/ArmRealViewEbPkg/Library/PL111LcdArmRealViewEbLib/PL111LcdArmRealViewEbLib.inf
@@ -1,65 +1,65 @@
-#/** @file
-#
-# Component description file for ArmRealViewGraphicsDxe module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = PL111LcdArmRealViewEbLib
- FILE_GUID = 51396ee0-4973-11e0-868a-0002a5d5c51b
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- LIBRARY_CLASS = PL111LcdPlatformLib
-
-[Sources.common]
- PL111LcdArmRealViewEb.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- IoLib
-
-[Guids]
-
-[Protocols]
- gEfiEdidDiscoveredProtocolGuid # Produced
- gEfiEdidActiveProtocolGuid # Produced
-
-[FixedPcd.common]
-
- #
- # The following modes are supported by PL111
- #
- # 0 : 640 x 480 x 24 bpp
- # 1 : 800 x 600 x 24 bpp
- # 2 : 1024 x 768 x 24 bpp
- # 3 : 640 x 480 x 16 bpp (565 RGB Mode)
- # 4 : 800 x 600 x 16 bpp (565 RGB Mode)
- # 5 : 1024 x 768 x 16 bpp (565 RGB Mode)
- # 6 : 640 x 480 x 15 bpp (555 RGB Mode)
- # 7 : 800 x 600 x 15 bpp (555 RGB Mode)
- # 8 : 1024 x 768 x 15 bpp (555 RGB Mode)
- # 9 : 1024 x 768 x 15 bpp (555 RGB Mode) - Linux driver settings
- # 10 : 640 x 480 x 12 bpp (444 RGB Mode)
- # 11 : 800 x 600 x 12 bpp (444 RGB Mode)
- # 12 : 1024 x 768 x 12 bpp (444 RGB Mode)
- #
-
-[Pcd.common]
-
-[Depex]
- # gEfiCpuArchProtocolGuid
+#/** @file
+#
+# Component description file for ArmRealViewGraphicsDxe module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PL111LcdArmRealViewEbLib
+ FILE_GUID = 51396ee0-4973-11e0-868a-0002a5d5c51b
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = PL111LcdPlatformLib
+
+[Sources.common]
+ PL111LcdArmRealViewEb.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ IoLib
+
+[Guids]
+
+[Protocols]
+ gEfiEdidDiscoveredProtocolGuid # Produced
+ gEfiEdidActiveProtocolGuid # Produced
+
+[FixedPcd.common]
+
+ #
+ # The following modes are supported by PL111
+ #
+ # 0 : 640 x 480 x 24 bpp
+ # 1 : 800 x 600 x 24 bpp
+ # 2 : 1024 x 768 x 24 bpp
+ # 3 : 640 x 480 x 16 bpp (565 RGB Mode)
+ # 4 : 800 x 600 x 16 bpp (565 RGB Mode)
+ # 5 : 1024 x 768 x 16 bpp (565 RGB Mode)
+ # 6 : 640 x 480 x 15 bpp (555 RGB Mode)
+ # 7 : 800 x 600 x 15 bpp (555 RGB Mode)
+ # 8 : 1024 x 768 x 15 bpp (555 RGB Mode)
+ # 9 : 1024 x 768 x 15 bpp (555 RGB Mode) - Linux driver settings
+ # 10 : 640 x 480 x 12 bpp (444 RGB Mode)
+ # 11 : 800 x 600 x 12 bpp (444 RGB Mode)
+ # 12 : 1024 x 768 x 12 bpp (444 RGB Mode)
+ #
+
+[Pcd.common]
+
+[Depex]
+ # gEfiCpuArchProtocolGuid
diff --git a/ArmPlatformPkg/ArmRealViewEbPkg/Library/SysConfigArmRealViewEbLib/SysConfigArmRealViewEbLib.inf b/ArmPlatformPkg/ArmRealViewEbPkg/Library/SysConfigArmRealViewEbLib/SysConfigArmRealViewEbLib.inf
index b45c20b5b..e1a735345 100644
--- a/ArmPlatformPkg/ArmRealViewEbPkg/Library/SysConfigArmRealViewEbLib/SysConfigArmRealViewEbLib.inf
+++ b/ArmPlatformPkg/ArmRealViewEbPkg/Library/SysConfigArmRealViewEbLib/SysConfigArmRealViewEbLib.inf
@@ -1,34 +1,34 @@
-#/** @file
-#
-# Component description file for SysConfigArmRealViewEbLib module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = SysConfigArmRealViewEbLib
- FILE_GUID = 46eddfa0-8de0-11e0-944b-0002a5d5c51b
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformSysConfigLib
-
-[Sources.common]
- SysConfigArmRealViewEb.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
+#/** @file
+#
+# Component description file for SysConfigArmRealViewEbLib module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SysConfigArmRealViewEbLib
+ FILE_GUID = 46eddfa0-8de0-11e0-944b-0002a5d5c51b
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformSysConfigLib
+
+[Sources.common]
+ SysConfigArmRealViewEb.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
diff --git a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15-A7.dsc b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15-A7.dsc
index cbacd315c..1997743c9 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15-A7.dsc
+++ b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15-A7.dsc
@@ -180,11 +180,13 @@
#
# Versatile Express machine type (ARM VERSATILE EXPRESS = 2272) required for ARM Linux:
gArmTokenSpaceGuid.PcdArmMachineType|2272
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"Linux from NorFlash"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(1F15DA3C-37FF-4070-B471-BB4AF12A724A)/MemoryMapped(0x0,0xE000000,0xE800000)"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"console=ttyAMA0,38400 earlyprintk debug verbose"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootType|2
- gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(1F15DA3C-37FF-4070-B471-BB4AF12A724A)/MemoryMapped(0x0,0x0E800000,0x0E803000)"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"Linaro image on SD card"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uImage"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uInitrd"
+ gArmPlatformTokenSpaceGuid.PcdDefaultFdtLocalDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca15-tc2.dtb"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"console=tty0 console=ttyAMA0,38400n8 root=/dev/mmcblk0p2 rootwait ro androidboot.console=ttyAMA0 mmci.fmax=12000000"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootType|3
+ gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca15-tc2.dtb"
# Use the serial console (ConIn & ConOut) and the Graphic driver (ConOut)
# PL111 - CLCD
diff --git a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15x2.dsc b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15x2.dsc
index d785eb3d8..0feee1f8e 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15x2.dsc
+++ b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA15x2.dsc
@@ -179,10 +179,13 @@
#
# Versatile Express machine type (ARM VERSATILE EXPRESS = 2272) required for ARM Linux:
gArmTokenSpaceGuid.PcdArmMachineType|2272
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"NorFlash"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(1F15DA3C-37FF-4070-B471-BB4AF12A724A)/MemoryMapped(0x0,0x46000000,0x46400000)"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|""
- gArmPlatformTokenSpaceGuid.PcdDefaultBootType|1
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"Linaro image on SD card"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uImage"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uInitrd"
+ gArmPlatformTokenSpaceGuid.PcdDefaultFdtLocalDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca15-tc1.dtb"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"console=tty0 console=ttyAMA0,38400n8 root=/dev/mmcblk0p2 rootwait ro androidboot.console=ttyAMA0 mmci.fmax=12000000"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootType|3
+ gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca15-tc1.dtb"
# Use the serial console (ConIn & ConOut) and the Graphic driver (ConOut)
gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths|L"VenHw(D3987D4B-971A-435F-8CAF-4967EB627241)/Uart(38400,8,N,1)/VenPcAnsi();VenHw(407B4008-BF5B-11DF-9547-CF16E0D72085)"
diff --git a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA5s.dsc b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA5s.dsc
index a41680d23..03d1d0951 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA5s.dsc
+++ b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA5s.dsc
@@ -179,10 +179,13 @@
#
# Versatile Express machine type (ARM VERSATILE EXPRESS = 2272) required for ARM Linux:
gArmTokenSpaceGuid.PcdArmMachineType|2272
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"NorFlash"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(1F15DA3C-37FF-4070-B471-BB4AF12A724A)/MemoryMapped(0x0,0x46000000,0x46400000)"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|""
- gArmPlatformTokenSpaceGuid.PcdDefaultBootType|1
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"Linaro image on SD card"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uImage"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uInitrd"
+ gArmPlatformTokenSpaceGuid.PcdDefaultFdtLocalDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca5s.dtb"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"console=tty0 console=ttyAMA0,38400n8 root=/dev/mmcblk0p2 rootwait ro androidboot.console=ttyAMA0 mmci.fmax=12000000"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootType|3
+ gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca5s.dtb"
# Use the serial console (ConIn & ConOut) and the Graphic driver (ConOut)
gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths|L"VenHw(D3987D4B-971A-435F-8CAF-4967EB627241)/Uart(38400,8,N,1)/VenPcAnsi();VenHw(407B4008-BF5B-11DF-9547-CF16E0D72085)"
diff --git a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA9x4.dsc b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA9x4.dsc
index 11eba89d9..1171e90fa 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA9x4.dsc
+++ b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-CTA9x4.dsc
@@ -176,10 +176,12 @@
#
# Versatile Express machine type (ARM VERSATILE EXPRESS = 2272) required for ARM Linux:
gArmTokenSpaceGuid.PcdArmMachineType|2272
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"NorFlash"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(1F15DA3C-37FF-4070-B471-BB4AF12A724A)/MemoryMapped(0x0,0x46000000,0x46400000)"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|""
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"Linaro image on SD card"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uImage"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/uInitrd"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"console=tty0 console=ttyAMA0,38400n8 root=/dev/mmcblk0p2 rootwait ro androidboot.console=ttyAMA0 mmci.fmax=12000000"
gArmPlatformTokenSpaceGuid.PcdDefaultBootType|1
+ gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(09831032-6FA3-4484-AF4F-0A000A8D3A82)/HD(1,MBR,0x00000000,0x3F,0x19FC0)/v2p-ca9.dtb"
# Use the serial console (ConIn & ConOut) and the Graphic driver (ConOut)
gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths|L"VenHw(D3987D4B-971A-435F-8CAF-4967EB627241)/Uart(38400,8,N,1)/VenPcAnsi();VenHw(407B4008-BF5B-11DF-9547-CF16E0D72085)"
diff --git a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf
index 4be620c3f..c961897d0 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf
+++ b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15.fdf
@@ -1,318 +1,318 @@
-# FLASH layout file for ARM VE.
-#
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-################################################################################
-#
-# FD Section
-# The [FD] Section is made up of the definition statements and a
-# description of what goes into the Flash Device Image. Each FD section
-# defines one flash "device" image. A flash device image may be one of
-# the following: Removable media bootable image (like a boot floppy
-# image,) an Option ROM image (that would be "flashed" into an add-in
-# card,) a System "Flash" image (that would be burned into a system's
-# flash) or an Update ("Capsule") image that will be used to update and
-# existing system flash.
-#
-################################################################################
-
-[FD.RTSM_VE_Cortex-A15_EFI]
-BaseAddress = 0x08000000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
-Size = 0x00280000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
-ErasePolarity = 1
-
-# This one is tricky, it must be: BlockSize * NumBlocks = Size
-BlockSize = 0x00001000
-NumBlocks = 0x280
-
-################################################################################
-#
-# Following are lists of FD Region layout which correspond to the locations of different
-# images within the flash device.
-#
-# Regions must be defined in ascending order and may not overlap.
-#
-# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
-# the pipe "|" character, followed by the size of the region, also in hex with the leading
-# "0x" characters. Like:
-# Offset|Size
-# PcdOffsetCName|PcdSizeCName
-# RegionType <FV, DATA, or FILE>
-#
-################################################################################
-
-0x00000000|0x00080000
-gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
-FV = FVMAIN_SEC
-
-0x00080000|0x00280000
-gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
-FV = FVMAIN_COMPACT
-
-
-################################################################################
-#
-# FV Section
-#
-# [FV] section is used to define what components or modules are placed within a flash
-# device file. This section also defines order the components and modules are positioned
-# within the image. The [FV] section consists of define statements, set statements and
-# module statements.
-#
-################################################################################
-
-[FV.FVMAIN_SEC]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF ArmPlatformPkg/Sec/Sec.inf
-
-
-[FV.FvMain]
-BlockSize = 0x40
-NumBlocks = 0 # This FV gets compressed so make it just big enough
-FvAlignment = 8 # FV alignment and FV attributes setting.
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF MdeModulePkg/Core/Dxe/DxeMain.inf
-
- #
- # PI DXE Drivers producing Architectural Protocols (EFI Services)
- #
- INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
- INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
- INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
- INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
- INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
-
- #
- # Multiple Console IO support
- #
- INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
- INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
- INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
- INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
- INF EmbeddedPkg/SerialDxe/SerialDxe.inf
-
- INF ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
- INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
- INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
- INF ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
- INF ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
-
- #
- # Semi-hosting filesystem
- #
- INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- #
- # FAT filesystem + GPT/MBR partitioning
- #
- INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
- INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- INF FatBinPkg/EnhancedFatDxe/Fat.inf
- INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
-
- #
- # Multimedia Card Interface
- #
- INF EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
- INF ArmPlatformPkg/Drivers/PL180MciDxe/PL180MciDxe.inf
-
- #
- # UEFI application (Shell Embedded Boot Loader)
- #
- INF ShellBinPkg/UefiShell/UefiShell.inf
-
- #
- # Bds
- #
- INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
- INF ArmPlatformPkg/Bds/Bds.inf
-
-
-[FV.FVMAIN_COMPACT]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
-!if $(EDK2_SKIP_PEICORE) == 1
- INF ArmPlatformPkg/PrePi/PeiUniCore.inf
-!else
- INF ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf
- INF MdeModulePkg/Core/Pei/PeiMain.inf
- INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
- INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
- INF ArmPkg/Drivers/CpuPei/CpuPei.inf
- INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
- INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
- INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
- INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
-!endif
-
- FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
- SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
- SECTION FV_IMAGE = FVMAIN
- }
- }
-
-
-################################################################################
-#
-# Rules are use with the [FV] section's module INF type to define
-# how an FFS file is created for a given INF file. The following Rule are the default
-# rules for the different module type. User can add the customized rules to define the
-# content of the FFS file.
-#
-################################################################################
-
-
-############################################################################
-# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
-############################################################################
-#
-#[Rule.Common.DXE_DRIVER]
-# FILE DRIVER = $(NAMED_GUID) {
-# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
-# COMPRESS PI_STD {
-# GUIDED {
-# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
-# UI STRING="$(MODULE_NAME)" Optional
-# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
-# }
-# }
-# }
-#
-############################################################################
-
-[Rule.Common.SEC]
- FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
- TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.PEI_CORE]
- FILE PEI_CORE = $(NAMED_GUID) {
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING ="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM]
- FILE PEIM = $(NAMED_GUID) {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM.TIANOCOMPRESSED]
- FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
- }
-
-[Rule.Common.DXE_CORE]
- FILE DXE_CORE = $(NAMED_GUID) {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_RUNTIME_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_APPLICATION]
- FILE APPLICATION = $(NAMED_GUID) {
- UI STRING ="$(MODULE_NAME)" Optional
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.UEFI_DRIVER.BINARY]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional |.depex
- PE32 PE32 |.efi
- UI STRING="$(MODULE_NAME)" Optional
- VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
- }
-
-[Rule.Common.UEFI_APPLICATION.BINARY]
- FILE APPLICATION = $(NAMED_GUID) {
- PE32 PE32 |.efi
- UI STRING="$(MODULE_NAME)" Optional
- VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
- }
+# FLASH layout file for ARM VE.
+#
+# Copyright (c) 2011, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+################################################################################
+#
+# FD Section
+# The [FD] Section is made up of the definition statements and a
+# description of what goes into the Flash Device Image. Each FD section
+# defines one flash "device" image. A flash device image may be one of
+# the following: Removable media bootable image (like a boot floppy
+# image,) an Option ROM image (that would be "flashed" into an add-in
+# card,) a System "Flash" image (that would be burned into a system's
+# flash) or an Update ("Capsule") image that will be used to update and
+# existing system flash.
+#
+################################################################################
+
+[FD.RTSM_VE_Cortex-A15_EFI]
+BaseAddress = 0x08000000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
+Size = 0x00280000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
+ErasePolarity = 1
+
+# This one is tricky, it must be: BlockSize * NumBlocks = Size
+BlockSize = 0x00001000
+NumBlocks = 0x280
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|0x00080000
+gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
+FV = FVMAIN_SEC
+
+0x00080000|0x00280000
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+
+################################################################################
+#
+# FV Section
+#
+# [FV] section is used to define what components or modules are placed within a flash
+# device file. This section also defines order the components and modules are positioned
+# within the image. The [FV] section consists of define statements, set statements and
+# module statements.
+#
+################################################################################
+
+[FV.FVMAIN_SEC]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF ArmPlatformPkg/Sec/Sec.inf
+
+
+[FV.FvMain]
+BlockSize = 0x40
+NumBlocks = 0 # This FV gets compressed so make it just big enough
+FvAlignment = 8 # FV alignment and FV attributes setting.
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+
+ #
+ # PI DXE Drivers producing Architectural Protocols (EFI Services)
+ #
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+ INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
+ INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+
+ #
+ # Multiple Console IO support
+ #
+ INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+ INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+ INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
+ INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
+ INF EmbeddedPkg/SerialDxe/SerialDxe.inf
+
+ INF ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
+ INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
+ INF ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
+ INF ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
+
+ #
+ # Semi-hosting filesystem
+ #
+ INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ #
+ # FAT filesystem + GPT/MBR partitioning
+ #
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF FatBinPkg/EnhancedFatDxe/Fat.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ #
+ # Multimedia Card Interface
+ #
+ INF EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
+ INF ArmPlatformPkg/Drivers/PL180MciDxe/PL180MciDxe.inf
+
+ #
+ # UEFI application (Shell Embedded Boot Loader)
+ #
+ INF ShellBinPkg/UefiShell/UefiShell.inf
+
+ #
+ # Bds
+ #
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF ArmPlatformPkg/Bds/Bds.inf
+
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+!if $(EDK2_SKIP_PEICORE) == 1
+ INF ArmPlatformPkg/PrePi/PeiUniCore.inf
+!else
+ INF ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf
+ INF MdeModulePkg/Core/Pei/PeiMain.inf
+ INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
+ INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
+ INF ArmPkg/Drivers/CpuPei/CpuPei.inf
+ INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+ INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
+ INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
+ INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+!endif
+
+ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+ SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+ SECTION FV_IMAGE = FVMAIN
+ }
+ }
+
+
+################################################################################
+#
+# Rules are use with the [FV] section's module INF type to define
+# how an FFS file is created for a given INF file. The following Rule are the default
+# rules for the different module type. User can add the customized rules to define the
+# content of the FFS file.
+#
+################################################################################
+
+
+############################################################################
+# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
+############################################################################
+#
+#[Rule.Common.DXE_DRIVER]
+# FILE DRIVER = $(NAMED_GUID) {
+# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+# COMPRESS PI_STD {
+# GUIDED {
+# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+# UI STRING="$(MODULE_NAME)" Optional
+# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+# }
+# }
+# }
+#
+############################################################################
+
+[Rule.Common.SEC]
+ FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
+ TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.PEI_CORE]
+ FILE PEI_CORE = $(NAMED_GUID) {
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING ="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM]
+ FILE PEIM = $(NAMED_GUID) {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM.TIANOCOMPRESSED]
+ FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+ }
+
+[Rule.Common.DXE_CORE]
+ FILE DXE_CORE = $(NAMED_GUID) {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_RUNTIME_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_APPLICATION]
+ FILE APPLICATION = $(NAMED_GUID) {
+ UI STRING ="$(MODULE_NAME)" Optional
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.UEFI_DRIVER.BINARY]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional |.depex
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
+
+[Rule.Common.UEFI_APPLICATION.BINARY]
+ FILE APPLICATION = $(NAMED_GUID) {
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
diff --git a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15_MPCore.fdf b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15_MPCore.fdf
index 4718c1859..58170490a 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15_MPCore.fdf
+++ b/ArmPlatformPkg/ArmVExpressPkg/ArmVExpress-RTSM-A15_MPCore.fdf
@@ -1,318 +1,318 @@
-# FLASH layout file for ARM VE.
-#
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-################################################################################
-#
-# FD Section
-# The [FD] Section is made up of the definition statements and a
-# description of what goes into the Flash Device Image. Each FD section
-# defines one flash "device" image. A flash device image may be one of
-# the following: Removable media bootable image (like a boot floppy
-# image,) an Option ROM image (that would be "flashed" into an add-in
-# card,) a System "Flash" image (that would be burned into a system's
-# flash) or an Update ("Capsule") image that will be used to update and
-# existing system flash.
-#
-################################################################################
-
-[FD.RTSM_VE_Cortex-A15_MPCore_EFI]
-BaseAddress = 0x08000000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
-Size = 0x00280000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
-ErasePolarity = 1
-
-# This one is tricky, it must be: BlockSize * NumBlocks = Size
-BlockSize = 0x00001000
-NumBlocks = 0x280
-
-################################################################################
-#
-# Following are lists of FD Region layout which correspond to the locations of different
-# images within the flash device.
-#
-# Regions must be defined in ascending order and may not overlap.
-#
-# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
-# the pipe "|" character, followed by the size of the region, also in hex with the leading
-# "0x" characters. Like:
-# Offset|Size
-# PcdOffsetCName|PcdSizeCName
-# RegionType <FV, DATA, or FILE>
-#
-################################################################################
-
-0x00000000|0x00080000
-gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
-FV = FVMAIN_SEC
-
-0x00080000|0x00280000
-gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
-FV = FVMAIN_COMPACT
-
-
-################################################################################
-#
-# FV Section
-#
-# [FV] section is used to define what components or modules are placed within a flash
-# device file. This section also defines order the components and modules are positioned
-# within the image. The [FV] section consists of define statements, set statements and
-# module statements.
-#
-################################################################################
-
-[FV.FVMAIN_SEC]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF ArmPlatformPkg/Sec/Sec.inf
-
-
-[FV.FvMain]
-BlockSize = 0x40
-NumBlocks = 0 # This FV gets compressed so make it just big enough
-FvAlignment = 8 # FV alignment and FV attributes setting.
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
- INF MdeModulePkg/Core/Dxe/DxeMain.inf
-
- #
- # PI DXE Drivers producing Architectural Protocols (EFI Services)
- #
- INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
- INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
- INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
- INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
- INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
- INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
-
- #
- # Multiple Console IO support
- #
- INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
- INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
- INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
- INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
- INF EmbeddedPkg/SerialDxe/SerialDxe.inf
-
- INF ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
- INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
- INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
- INF ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
- INF ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
-
- #
- # Semi-hosting filesystem
- #
- INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
-
- #
- # FAT filesystem + GPT/MBR partitioning
- #
- INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
- INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
- INF FatBinPkg/EnhancedFatDxe/Fat.inf
- INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
-
- #
- # Multimedia Card Interface
- #
- INF EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
- INF ArmPlatformPkg/Drivers/PL180MciDxe/PL180MciDxe.inf
-
- #
- # UEFI application (Shell Embedded Boot Loader)
- #
- INF ShellBinPkg/UefiShell/UefiShell.inf
-
- #
- # Bds
- #
- INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
- INF ArmPlatformPkg/Bds/Bds.inf
-
-
-[FV.FVMAIN_COMPACT]
-FvAlignment = 8
-ERASE_POLARITY = 1
-MEMORY_MAPPED = TRUE
-STICKY_WRITE = TRUE
-LOCK_CAP = TRUE
-LOCK_STATUS = TRUE
-WRITE_DISABLED_CAP = TRUE
-WRITE_ENABLED_CAP = TRUE
-WRITE_STATUS = TRUE
-WRITE_LOCK_CAP = TRUE
-WRITE_LOCK_STATUS = TRUE
-READ_DISABLED_CAP = TRUE
-READ_ENABLED_CAP = TRUE
-READ_STATUS = TRUE
-READ_LOCK_CAP = TRUE
-READ_LOCK_STATUS = TRUE
-
-!if $(EDK2_SKIP_PEICORE) == 1
- INF ArmPlatformPkg/PrePi/PeiMPCore.inf
-!else
- INF ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf
- INF MdeModulePkg/Core/Pei/PeiMain.inf
- INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
- INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
- INF ArmPkg/Drivers/CpuPei/CpuPei.inf
- INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
- INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
- INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
- INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
-!endif
-
- FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
- SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
- SECTION FV_IMAGE = FVMAIN
- }
- }
-
-
-################################################################################
-#
-# Rules are use with the [FV] section's module INF type to define
-# how an FFS file is created for a given INF file. The following Rule are the default
-# rules for the different module type. User can add the customized rules to define the
-# content of the FFS file.
-#
-################################################################################
-
-
-############################################################################
-# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
-############################################################################
-#
-#[Rule.Common.DXE_DRIVER]
-# FILE DRIVER = $(NAMED_GUID) {
-# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
-# COMPRESS PI_STD {
-# GUIDED {
-# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
-# UI STRING="$(MODULE_NAME)" Optional
-# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
-# }
-# }
-# }
-#
-############################################################################
-
-[Rule.Common.SEC]
- FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
- TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.PEI_CORE]
- FILE PEI_CORE = $(NAMED_GUID) {
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING ="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM]
- FILE PEIM = $(NAMED_GUID) {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.PEIM.TIANOCOMPRESSED]
- FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
- PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
- }
-
-[Rule.Common.DXE_CORE]
- FILE DXE_CORE = $(NAMED_GUID) {
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.DXE_RUNTIME_DRIVER]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- UI STRING="$(MODULE_NAME)" Optional
- }
-
-[Rule.Common.UEFI_APPLICATION]
- FILE APPLICATION = $(NAMED_GUID) {
- UI STRING ="$(MODULE_NAME)" Optional
- PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
- }
-
-[Rule.Common.UEFI_DRIVER.BINARY]
- FILE DRIVER = $(NAMED_GUID) {
- DXE_DEPEX DXE_DEPEX Optional |.depex
- PE32 PE32 |.efi
- UI STRING="$(MODULE_NAME)" Optional
- VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
- }
-
-[Rule.Common.UEFI_APPLICATION.BINARY]
- FILE APPLICATION = $(NAMED_GUID) {
- PE32 PE32 |.efi
- UI STRING="$(MODULE_NAME)" Optional
- VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
- }
+# FLASH layout file for ARM VE.
+#
+# Copyright (c) 2011, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+################################################################################
+#
+# FD Section
+# The [FD] Section is made up of the definition statements and a
+# description of what goes into the Flash Device Image. Each FD section
+# defines one flash "device" image. A flash device image may be one of
+# the following: Removable media bootable image (like a boot floppy
+# image,) an Option ROM image (that would be "flashed" into an add-in
+# card,) a System "Flash" image (that would be burned into a system's
+# flash) or an Update ("Capsule") image that will be used to update and
+# existing system flash.
+#
+################################################################################
+
+[FD.RTSM_VE_Cortex-A15_MPCore_EFI]
+BaseAddress = 0x08000000|gArmTokenSpaceGuid.PcdFdBaseAddress # The base address of the Firmware in NOR Flash.
+Size = 0x00280000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the FLASH Device
+ErasePolarity = 1
+
+# This one is tricky, it must be: BlockSize * NumBlocks = Size
+BlockSize = 0x00001000
+NumBlocks = 0x280
+
+################################################################################
+#
+# Following are lists of FD Region layout which correspond to the locations of different
+# images within the flash device.
+#
+# Regions must be defined in ascending order and may not overlap.
+#
+# A Layout Region start with a eight digit hex offset (leading "0x" required) followed by
+# the pipe "|" character, followed by the size of the region, also in hex with the leading
+# "0x" characters. Like:
+# Offset|Size
+# PcdOffsetCName|PcdSizeCName
+# RegionType <FV, DATA, or FILE>
+#
+################################################################################
+
+0x00000000|0x00080000
+gArmTokenSpaceGuid.PcdSecureFvBaseAddress|gArmTokenSpaceGuid.PcdSecureFvSize
+FV = FVMAIN_SEC
+
+0x00080000|0x00280000
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+
+################################################################################
+#
+# FV Section
+#
+# [FV] section is used to define what components or modules are placed within a flash
+# device file. This section also defines order the components and modules are positioned
+# within the image. The [FV] section consists of define statements, set statements and
+# module statements.
+#
+################################################################################
+
+[FV.FVMAIN_SEC]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF ArmPlatformPkg/Sec/Sec.inf
+
+
+[FV.FvMain]
+BlockSize = 0x40
+NumBlocks = 0 # This FV gets compressed so make it just big enough
+FvAlignment = 8 # FV alignment and FV attributes setting.
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF MdeModulePkg/Core/Dxe/DxeMain.inf
+
+ #
+ # PI DXE Drivers producing Architectural Protocols (EFI Services)
+ #
+ INF ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+ INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+ INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+ INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+ INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
+ INF EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+
+ #
+ # Multiple Console IO support
+ #
+ INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+ INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+ INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
+ INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
+ INF EmbeddedPkg/SerialDxe/SerialDxe.inf
+
+ INF ArmPkg/Drivers/PL390Gic/PL390GicDxe.inf
+ INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
+ INF ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
+ INF ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
+
+ #
+ # Semi-hosting filesystem
+ #
+ INF ArmPkg/Filesystem/SemihostFs/SemihostFs.inf
+
+ #
+ # FAT filesystem + GPT/MBR partitioning
+ #
+ INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+ INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+ INF FatBinPkg/EnhancedFatDxe/Fat.inf
+ INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+
+ #
+ # Multimedia Card Interface
+ #
+ INF EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
+ INF ArmPlatformPkg/Drivers/PL180MciDxe/PL180MciDxe.inf
+
+ #
+ # UEFI application (Shell Embedded Boot Loader)
+ #
+ INF ShellBinPkg/UefiShell/UefiShell.inf
+
+ #
+ # Bds
+ #
+ INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+ INF ArmPlatformPkg/Bds/Bds.inf
+
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 8
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+!if $(EDK2_SKIP_PEICORE) == 1
+ INF ArmPlatformPkg/PrePi/PeiMPCore.inf
+!else
+ INF ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf
+ INF MdeModulePkg/Core/Pei/PeiMain.inf
+ INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf
+ INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
+ INF ArmPkg/Drivers/CpuPei/CpuPei.inf
+ INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+ INF IntelFrameworkModulePkg/Universal/StatusCode/Pei/StatusCodePei.inf
+ INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
+ INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+!endif
+
+ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+ SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+ SECTION FV_IMAGE = FVMAIN
+ }
+ }
+
+
+################################################################################
+#
+# Rules are use with the [FV] section's module INF type to define
+# how an FFS file is created for a given INF file. The following Rule are the default
+# rules for the different module type. User can add the customized rules to define the
+# content of the FFS file.
+#
+################################################################################
+
+
+############################################################################
+# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section #
+############################################################################
+#
+#[Rule.Common.DXE_DRIVER]
+# FILE DRIVER = $(NAMED_GUID) {
+# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+# COMPRESS PI_STD {
+# GUIDED {
+# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+# UI STRING="$(MODULE_NAME)" Optional
+# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+# }
+# }
+# }
+#
+############################################################################
+
+[Rule.Common.SEC]
+ FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED {
+ TE TE Align = 32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.PEI_CORE]
+ FILE PEI_CORE = $(NAMED_GUID) {
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING ="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM]
+ FILE PEIM = $(NAMED_GUID) {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ TE TE $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.PEIM.TIANOCOMPRESSED]
+ FILE PEIM = $(NAMED_GUID) DEBUG_MYTOOLS_IA32 {
+ PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ GUIDED A31280AD-481E-41B6-95E8-127F4C984779 PROCESSING_REQUIRED = TRUE {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+ }
+
+[Rule.Common.DXE_CORE]
+ FILE DXE_CORE = $(NAMED_GUID) {
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.DXE_RUNTIME_DRIVER]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ }
+
+[Rule.Common.UEFI_APPLICATION]
+ FILE APPLICATION = $(NAMED_GUID) {
+ UI STRING ="$(MODULE_NAME)" Optional
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.UEFI_DRIVER.BINARY]
+ FILE DRIVER = $(NAMED_GUID) {
+ DXE_DEPEX DXE_DEPEX Optional |.depex
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
+
+[Rule.Common.UEFI_APPLICATION.BINARY]
+ FILE APPLICATION = $(NAMED_GUID) {
+ PE32 PE32 |.efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/ArmVExpressLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/ArmVExpressLib.inf
index f20db58d6..a255c40b3 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/ArmVExpressLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/ArmVExpressLib.inf
@@ -1,55 +1,55 @@
-#/* @file
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#*/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = CTA9x4ArmVExpressLib
- FILE_GUID = b16c63a0-f417-11df-b3af-0002a5d5c51b
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformLib
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- IoLib
- ArmLib
- ArmTrustZoneLib
- MemoryAllocationLib
- PL341DmcLib
- PL301AxiLib
- L2X0CacheLib
- SerialPortLib
-
-[Sources.common]
- CTA9x4.c
- CTA9x4Mem.c
-
-[FeaturePcd]
- gEmbeddedTokenSpaceGuid.PcdCacheEnable
- gArmPlatformTokenSpaceGuid.PcdNorFlashRemapping
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdTrustzoneSupport
- gArmTokenSpaceGuid.PcdSystemMemoryBase
- gArmTokenSpaceGuid.PcdSystemMemorySize
-
- gArmTokenSpaceGuid.PcdL2x0ControllerBase
-
- gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
- gArmTokenSpaceGuid.PcdArmPrimaryCore
+#/* @file
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#*/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = CTA9x4ArmVExpressLib
+ FILE_GUID = b16c63a0-f417-11df-b3af-0002a5d5c51b
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ IoLib
+ ArmLib
+ ArmTrustZoneLib
+ MemoryAllocationLib
+ PL341DmcLib
+ PL301AxiLib
+ L2X0CacheLib
+ SerialPortLib
+
+[Sources.common]
+ CTA9x4.c
+ CTA9x4Mem.c
+
+[FeaturePcd]
+ gEmbeddedTokenSpaceGuid.PcdCacheEnable
+ gArmPlatformTokenSpaceGuid.PcdNorFlashRemapping
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdTrustzoneSupport
+ gArmTokenSpaceGuid.PcdSystemMemoryBase
+ gArmTokenSpaceGuid.PcdSystemMemorySize
+
+ gArmTokenSpaceGuid.PcdL2x0ControllerBase
+
+ gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
+ gArmTokenSpaceGuid.PcdArmPrimaryCore
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c
index 986044156..fb920aa49 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibCTA9x4/CTA9x4.c
@@ -1,222 +1,213 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/IoLib.h>
-#include <Library/ArmPlatformLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-#include <Library/SerialPortLib.h>
-
-#include <Drivers/PL341Dmc.h>
-#include <Drivers/PL301Axi.h>
-#include <Drivers/SP804Timer.h>
-
-#include <Ppi/ArmMpCoreInfo.h>
-
-#include <ArmPlatform.h>
-
-#define SerialPrint(txt) SerialPortWrite ((UINT8*)(txt), AsciiStrLen(txt)+1);
-
-ARM_CORE_INFO mVersatileExpressMpCoreInfoCTA9x4[] = {
- {
- // Cluster 0, Core 0
- 0x0, 0x0,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 1
- 0x0, 0x1,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 2
- 0x0, 0x2,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 3
- 0x0, 0x3,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- }
-};
-
-// DDR2 timings
-PL341_DMC_CONFIG DDRTimings = {
- .MaxChip = 1,
- .IsUserCfg = TRUE,
- .User0Cfg = 0x7C924924,
- .User2Cfg = (TC_UIOLHXC_VALUE << TC_UIOLHNC_SHIFT) | (TC_UIOLHXC_VALUE << TC_UIOLHPC_SHIFT) | (0x1 << TC_UIOHOCT_SHIFT) | (0x1 << TC_UIOHSTOP_SHIFT),
- .HasQos = TRUE,
- .RefreshPeriod = 0x3D0,
- .CasLatency = 0x8,
- .WriteLatency = 0x3,
- .t_mrd = 0x2,
- .t_ras = 0xA,
- .t_rc = 0xE,
- .t_rcd = 0x104,
- .t_rfc = 0x2f32,
- .t_rp = 0x14,
- .t_rrd = 0x2,
- .t_wr = 0x4,
- .t_wtr = 0x2,
- .t_xp = 0x2,
- .t_xsr = 0xC8,
- .t_esr = 0x14,
- .MemoryCfg = DMC_MEMORY_CONFIG_ACTIVE_CHIP_1 | DMC_MEMORY_CONFIG_BURST_4 |
- DMC_MEMORY_CONFIG_ROW_ADDRESS_15 | DMC_MEMORY_CONFIG_COLUMN_ADDRESS_10,
- .MemoryCfg2 = DMC_MEMORY_CFG2_DQM_INIT | DMC_MEMORY_CFG2_CKE_INIT |
- DMC_MEMORY_CFG2_BANK_BITS_3 | DMC_MEMORY_CFG2_MEM_WIDTH_32,
- .MemoryCfg3 = 0x00000001,
- .ChipCfg0 = 0x00010000,
- .t_faw = 0x00000A0D,
- .ModeReg = DDR2_MR_BURST_LENGTH_4 | DDR2_MR_CAS_LATENCY_4 | DDR2_MR_WR_CYCLES_4,
- .ExtModeReg = DDR_EMR_RTT_50R | (DDR_EMR_ODS_VAL << DDR_EMR_ODS_MASK),
-};
-
-/**
- Return the current Boot Mode
-
- This function returns the boot reason on the platform
-
- @return Return the current Boot Mode of the platform
-
-**/
-EFI_BOOT_MODE
-ArmPlatformGetBootMode (
- VOID
- )
-{
- if (MmioRead32(ARM_VE_SYS_FLAGS_NV_REG) == 0) {
- return BOOT_WITH_FULL_CONFIGURATION;
- } else {
- return BOOT_ON_S2_RESUME;
- }
-}
-
-/**
- Initialize controllers that must setup in the normal world
-
- This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
- in the PEI phase.
-
-**/
-RETURN_STATUS
-ArmPlatformInitialize (
- IN UINTN MpId
- )
-{
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // Configure periodic timer (TIMER0) for 1MHz operation
- MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER0_TIMCLK);
- // Configure 1MHz clock
- MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER1_TIMCLK);
- // configure SP810 to use 1MHz clock and disable
- MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER2_EN, SP810_SYS_CTRL_TIMER2_TIMCLK);
- // Configure SP810 to use 1MHz clock and disable
- MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER3_EN, SP810_SYS_CTRL_TIMER3_TIMCLK);
-
- return RETURN_SUCCESS;
-}
-
-/**
- Initialize the system (or sometimes called permanent) memory
-
- This memory is generally represented by the DRAM.
-
-**/
-VOID
-ArmPlatformInitializeSystemMemory (
- VOID
- )
-{
- UINT32 Value;
-
- // Memory Map remapping
- if (FeaturePcdGet(PcdNorFlashRemapping)) {
- SerialPrint ("Secure ROM at 0x0\n\r");
- } else {
- Value = MmioRead32(ARM_VE_SYS_CFGRW1_REG); //Scc - CFGRW1
- // Remap the DRAM to 0x0
- MmioWrite32(ARM_VE_SYS_CFGRW1_REG, (Value & 0x0FFFFFFF) | ARM_VE_CFGRW1_REMAP_DRAM);
- }
-
- PL341DmcInit(ARM_VE_DMC_BASE, &DDRTimings);
- PL301AxiInit(ARM_VE_FAXI_BASE);
-}
-
-EFI_STATUS
-PrePeiCoreGetMpCoreInfo (
- OUT UINTN *CoreCount,
- OUT ARM_CORE_INFO **ArmCoreTable
- )
-{
- *CoreCount = sizeof(mVersatileExpressMpCoreInfoCTA9x4) / sizeof(ARM_CORE_INFO);
- *ArmCoreTable = mVersatileExpressMpCoreInfoCTA9x4;
-
- return EFI_SUCCESS;
-}
-
-// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
-EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
-ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
-
-EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
- {
- EFI_PEI_PPI_DESCRIPTOR_PPI,
- &mArmMpCoreInfoPpiGuid,
- &mMpCoreInfoPpi
- }
-};
-
-VOID
-ArmPlatformGetPlatformPpiList (
- OUT UINTN *PpiListSize,
- OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
- )
-{
- *PpiListSize = sizeof(gPlatformPpiTable);
- *PpiList = gPlatformPpiTable;
-}
-
-UINTN
-ArmPlatformGetCorePosition (
- IN UINTN MpId
- )
-{
- return 1;
-}
-
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/IoLib.h>
+#include <Library/ArmPlatformLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+#include <Library/SerialPortLib.h>
+
+#include <Drivers/PL341Dmc.h>
+#include <Drivers/PL301Axi.h>
+#include <Drivers/SP804Timer.h>
+
+#include <Ppi/ArmMpCoreInfo.h>
+
+#include <ArmPlatform.h>
+
+#define SerialPrint(txt) SerialPortWrite ((UINT8*)(txt), AsciiStrLen(txt)+1);
+
+ARM_CORE_INFO mVersatileExpressMpCoreInfoCTA9x4[] = {
+ {
+ // Cluster 0, Core 0
+ 0x0, 0x0,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 1
+ 0x0, 0x1,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 2
+ 0x0, 0x2,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 3
+ 0x0, 0x3,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ }
+};
+
+// DDR2 timings
+PL341_DMC_CONFIG DDRTimings = {
+ .MaxChip = 1,
+ .IsUserCfg = TRUE,
+ .User0Cfg = 0x7C924924,
+ .User2Cfg = (TC_UIOLHXC_VALUE << TC_UIOLHNC_SHIFT) | (TC_UIOLHXC_VALUE << TC_UIOLHPC_SHIFT) | (0x1 << TC_UIOHOCT_SHIFT) | (0x1 << TC_UIOHSTOP_SHIFT),
+ .HasQos = TRUE,
+ .RefreshPeriod = 0x3D0,
+ .CasLatency = 0x8,
+ .WriteLatency = 0x3,
+ .t_mrd = 0x2,
+ .t_ras = 0xA,
+ .t_rc = 0xE,
+ .t_rcd = 0x104,
+ .t_rfc = 0x2f32,
+ .t_rp = 0x14,
+ .t_rrd = 0x2,
+ .t_wr = 0x4,
+ .t_wtr = 0x2,
+ .t_xp = 0x2,
+ .t_xsr = 0xC8,
+ .t_esr = 0x14,
+ .MemoryCfg = DMC_MEMORY_CONFIG_ACTIVE_CHIP_1 | DMC_MEMORY_CONFIG_BURST_4 |
+ DMC_MEMORY_CONFIG_ROW_ADDRESS_15 | DMC_MEMORY_CONFIG_COLUMN_ADDRESS_10,
+ .MemoryCfg2 = DMC_MEMORY_CFG2_DQM_INIT | DMC_MEMORY_CFG2_CKE_INIT |
+ DMC_MEMORY_CFG2_BANK_BITS_3 | DMC_MEMORY_CFG2_MEM_WIDTH_32,
+ .MemoryCfg3 = 0x00000001,
+ .ChipCfg0 = 0x00010000,
+ .t_faw = 0x00000A0D,
+ .ModeReg = DDR2_MR_BURST_LENGTH_4 | DDR2_MR_CAS_LATENCY_4 | DDR2_MR_WR_CYCLES_4,
+ .ExtModeReg = DDR_EMR_RTT_50R | (DDR_EMR_ODS_VAL << DDR_EMR_ODS_MASK),
+};
+
+/**
+ Return the current Boot Mode
+
+ This function returns the boot reason on the platform
+
+ @return Return the current Boot Mode of the platform
+
+**/
+EFI_BOOT_MODE
+ArmPlatformGetBootMode (
+ VOID
+ )
+{
+ if (MmioRead32(ARM_VE_SYS_FLAGS_NV_REG) == 0) {
+ return BOOT_WITH_FULL_CONFIGURATION;
+ } else {
+ return BOOT_ON_S2_RESUME;
+ }
+}
+
+/**
+ Initialize controllers that must setup in the normal world
+
+ This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
+ in the PEI phase.
+
+**/
+RETURN_STATUS
+ArmPlatformInitialize (
+ IN UINTN MpId
+ )
+{
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // Configure periodic timer (TIMER0) for 1MHz operation
+ MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER0_TIMCLK);
+ // Configure 1MHz clock
+ MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER1_TIMCLK);
+ // configure SP810 to use 1MHz clock and disable
+ MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER2_EN, SP810_SYS_CTRL_TIMER2_TIMCLK);
+ // Configure SP810 to use 1MHz clock and disable
+ MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER3_EN, SP810_SYS_CTRL_TIMER3_TIMCLK);
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Initialize the system (or sometimes called permanent) memory
+
+ This memory is generally represented by the DRAM.
+
+**/
+VOID
+ArmPlatformInitializeSystemMemory (
+ VOID
+ )
+{
+ UINT32 Value;
+
+ // Memory Map remapping
+ if (FeaturePcdGet(PcdNorFlashRemapping)) {
+ SerialPrint ("Secure ROM at 0x0\n\r");
+ } else {
+ Value = MmioRead32(ARM_VE_SYS_CFGRW1_REG); //Scc - CFGRW1
+ // Remap the DRAM to 0x0
+ MmioWrite32(ARM_VE_SYS_CFGRW1_REG, (Value & 0x0FFFFFFF) | ARM_VE_CFGRW1_REMAP_DRAM);
+ }
+
+ PL341DmcInit(ARM_VE_DMC_BASE, &DDRTimings);
+ PL301AxiInit(ARM_VE_FAXI_BASE);
+}
+
+EFI_STATUS
+PrePeiCoreGetMpCoreInfo (
+ OUT UINTN *CoreCount,
+ OUT ARM_CORE_INFO **ArmCoreTable
+ )
+{
+ *CoreCount = sizeof(mVersatileExpressMpCoreInfoCTA9x4) / sizeof(ARM_CORE_INFO);
+ *ArmCoreTable = mVersatileExpressMpCoreInfoCTA9x4;
+
+ return EFI_SUCCESS;
+}
+
+// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
+EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
+ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
+
+EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
+ {
+ EFI_PEI_PPI_DESCRIPTOR_PPI,
+ &mArmMpCoreInfoPpiGuid,
+ &mMpCoreInfoPpi
+ }
+};
+
+VOID
+ArmPlatformGetPlatformPpiList (
+ OUT UINTN *PpiListSize,
+ OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
+ )
+{
+ *PpiListSize = sizeof(gPlatformPpiTable);
+ *PpiList = gPlatformPpiTable;
+}
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSM.c b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSM.c
index 69ffd45fd..f055608ab 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSM.c
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSM.c
@@ -1,163 +1,163 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/IoLib.h>
-#include <Library/ArmPlatformLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-
-#include <Ppi/ArmMpCoreInfo.h>
-
-#include <ArmPlatform.h>
-
-UINTN
-ArmGetCpuCountPerCluster (
- VOID
- );
-
-ARM_CORE_INFO mVersatileExpressMpCoreInfoTable[] = {
- {
- // Cluster 0, Core 0
- 0x0, 0x0,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 1
- 0x0, 0x1,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 2
- 0x0, 0x2,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 3
- 0x0, 0x3,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
- (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
- (UINT64)0xFFFFFFFF
- }
-};
-
-/**
- Return the current Boot Mode
-
- This function returns the boot reason on the platform
-
- @return Return the current Boot Mode of the platform
-
-**/
-EFI_BOOT_MODE
-ArmPlatformGetBootMode (
- VOID
- )
-{
- return BOOT_WITH_FULL_CONFIGURATION;
-}
-
-/**
- Initialize controllers that must setup in the normal world
-
- This function is called by the ArmPlatformPkg/Pei or ArmPlatformPkg/Pei/PlatformPeim
- in the PEI phase.
-
-**/
-RETURN_STATUS
-ArmPlatformInitialize (
- IN UINTN MpId
- )
-{
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // Disable memory remapping and return to normal mapping
- MmioOr32 (SP810_CTRL_BASE, BIT8);
-
- return RETURN_SUCCESS;
-}
-
-/**
- Initialize the system (or sometimes called permanent) memory
-
- This memory is generally represented by the DRAM.
-
-**/
-VOID
-ArmPlatformInitializeSystemMemory (
- VOID
- )
-{
- // Nothing to do here
-}
-
-EFI_STATUS
-PrePeiCoreGetMpCoreInfo (
- OUT UINTN *CoreCount,
- OUT ARM_CORE_INFO **ArmCoreTable
- )
-{
- UINT32 ProcType;
-
- ProcType = MmioRead32 (ARM_VE_SYS_PROCID0_REG) & ARM_VE_SYS_PROC_ID_MASK;
- if ((ProcType == ARM_VE_SYS_PROC_ID_CORTEX_A9) || (ProcType == ARM_VE_SYS_PROC_ID_CORTEX_A15)) {
- // Only support one cluster
- *CoreCount = ArmGetCpuCountPerCluster ();
- *ArmCoreTable = mVersatileExpressMpCoreInfoTable;
- return EFI_SUCCESS;
- } else {
- return EFI_UNSUPPORTED;
- }
-}
-
-// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
-EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
-ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
-
-EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
- {
- EFI_PEI_PPI_DESCRIPTOR_PPI,
- &mArmMpCoreInfoPpiGuid,
- &mMpCoreInfoPpi
- }
-};
-
-VOID
-ArmPlatformGetPlatformPpiList (
- OUT UINTN *PpiListSize,
- OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
- )
-{
- *PpiListSize = sizeof(gPlatformPpiTable);
- *PpiList = gPlatformPpiTable;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/IoLib.h>
+#include <Library/ArmPlatformLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+
+#include <Ppi/ArmMpCoreInfo.h>
+
+#include <ArmPlatform.h>
+
+UINTN
+ArmGetCpuCountPerCluster (
+ VOID
+ );
+
+ARM_CORE_INFO mVersatileExpressMpCoreInfoTable[] = {
+ {
+ // Cluster 0, Core 0
+ 0x0, 0x0,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 1
+ 0x0, 0x1,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 2
+ 0x0, 0x2,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 3
+ 0x0, 0x3,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_SET_REG,
+ (EFI_PHYSICAL_ADDRESS)ARM_VE_SYS_FLAGS_CLR_REG,
+ (UINT64)0xFFFFFFFF
+ }
+};
+
+/**
+ Return the current Boot Mode
+
+ This function returns the boot reason on the platform
+
+ @return Return the current Boot Mode of the platform
+
+**/
+EFI_BOOT_MODE
+ArmPlatformGetBootMode (
+ VOID
+ )
+{
+ return BOOT_WITH_FULL_CONFIGURATION;
+}
+
+/**
+ Initialize controllers that must setup in the normal world
+
+ This function is called by the ArmPlatformPkg/Pei or ArmPlatformPkg/Pei/PlatformPeim
+ in the PEI phase.
+
+**/
+RETURN_STATUS
+ArmPlatformInitialize (
+ IN UINTN MpId
+ )
+{
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // Disable memory remapping and return to normal mapping
+ MmioOr32 (SP810_CTRL_BASE, BIT8);
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Initialize the system (or sometimes called permanent) memory
+
+ This memory is generally represented by the DRAM.
+
+**/
+VOID
+ArmPlatformInitializeSystemMemory (
+ VOID
+ )
+{
+ // Nothing to do here
+}
+
+EFI_STATUS
+PrePeiCoreGetMpCoreInfo (
+ OUT UINTN *CoreCount,
+ OUT ARM_CORE_INFO **ArmCoreTable
+ )
+{
+ UINT32 ProcType;
+
+ ProcType = MmioRead32 (ARM_VE_SYS_PROCID0_REG) & ARM_VE_SYS_PROC_ID_MASK;
+ if ((ProcType == ARM_VE_SYS_PROC_ID_CORTEX_A9) || (ProcType == ARM_VE_SYS_PROC_ID_CORTEX_A15)) {
+ // Only support one cluster
+ *CoreCount = ArmGetCpuCountPerCluster ();
+ *ArmCoreTable = mVersatileExpressMpCoreInfoTable;
+ return EFI_SUCCESS;
+ } else {
+ return EFI_UNSUPPORTED;
+ }
+}
+
+// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
+EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
+ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
+
+EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
+ {
+ EFI_PEI_PPI_DESCRIPTOR_PPI,
+ &mArmMpCoreInfoPpiGuid,
+ &mMpCoreInfoPpi
+ }
+};
+
+VOID
+ArmPlatformGetPlatformPpiList (
+ OUT UINTN *PpiListSize,
+ OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
+ )
+{
+ *PpiListSize = sizeof(gPlatformPpiTable);
+ *PpiList = gPlatformPpiTable;
+}
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSMMem.c b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSMMem.c
index f3e8cafc0..cb6376f65 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSMMem.c
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressLibRTSM/RTSMMem.c
@@ -103,7 +103,7 @@ ArmPlatformGetVirtualMemoryMap (
VirtualMemoryTable[++Index].PhysicalBase = ARM_VE_SMB_PERIPH_BASE;
VirtualMemoryTable[Index].VirtualBase = ARM_VE_SMB_PERIPH_BASE;
VirtualMemoryTable[Index].Length = 2 * ARM_VE_SMB_PERIPH_SZ;
- VirtualMemoryTable[Index].Attributes = ARM_MEMORY_REGION_ATTRIBUTE_DEVICE;
+ VirtualMemoryTable[Index].Attributes = ARM_MEMORY_REGION_ATTRIBUTE_DEVICE;
//TODO:This should be enabled for final release. Right now, ARM VE RTSM crashes.
// // If a Logic Tile is connected to The ARM Versatile Express Motherboard
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibCTA9x4/CTA9x4Sec.c b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibCTA9x4/CTA9x4Sec.c
index ce9bc8b27..228a0fb0f 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibCTA9x4/CTA9x4Sec.c
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibCTA9x4/CTA9x4Sec.c
@@ -1,148 +1,148 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/ArmPlatformLib.h>
-#include <Library/ArmPlatformSysConfigLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-
-#include <Drivers/ArmTrustzone.h>
-#include <Drivers/PL310L2Cache.h>
-
-#include <ArmPlatform.h>
-
-/**
- Initialize the Secure peripherals and memory regions
-
- If Trustzone is supported by your platform then this function makes the required initialization
- of the secure peripherals and memory regions.
-
-**/
-VOID
-ArmPlatformSecTrustzoneInit (
- IN UINTN MpId
- )
-{
- // Nothing to do
- if (!IS_PRIMARY_CORE(MpId)) {
- return;
- }
-
- //
- // Setup TZ Protection Controller
- //
-
- if (MmioRead32(ARM_VE_SYS_CFGRW1_REG) & ARM_VE_CFGRW1_TZASC_EN_BIT_MASK) {
- ASSERT (PcdGetBool (PcdTrustzoneSupport) == TRUE);
- } else {
- ASSERT (PcdGetBool (PcdTrustzoneSupport) == FALSE);
- }
-
- // Set Non Secure access for all devices
- TZPCSetDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_0, 0xFFFFFFFF);
- TZPCSetDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_1, 0xFFFFFFFF);
- TZPCSetDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_2, 0xFFFFFFFF);
-
- // Remove Non secure access to secure devices
- TZPCClearDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_0,
- ARM_VE_DECPROT_BIT_TZPC | ARM_VE_DECPROT_BIT_DMC_TZASC | ARM_VE_DECPROT_BIT_NMC_TZASC | ARM_VE_DECPROT_BIT_SMC_TZASC);
-
- TZPCClearDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_2,
- ARM_VE_DECPROT_BIT_EXT_MAST_TZ | ARM_VE_DECPROT_BIT_DMC_TZASC_LOCK | ARM_VE_DECPROT_BIT_NMC_TZASC_LOCK | ARM_VE_DECPROT_BIT_SMC_TZASC_LOCK);
-
- //
- // Setup TZ Address Space Controller for the SMC. Create 5 Non Secure regions (NOR0, NOR1, SRAM, SMC Peripheral regions)
- //
-
- // NOR Flash 0 non secure (BootMon)
- TZASCSetRegion(ARM_VE_TZASC_BASE,1,TZASC_REGION_ENABLED,
- ARM_VE_SMB_NOR0_BASE,0,
- TZASC_REGION_SIZE_64MB, TZASC_REGION_SECURITY_NSRW);
-
- // NOR Flash 1. The first half of the NOR Flash1 must be secure for the secure firmware (sec_uefi.bin)
- if (PcdGetBool (PcdTrustzoneSupport) == TRUE) {
- //Note: Your OS Kernel must be aware of the secure regions before to enable this region
- TZASCSetRegion(ARM_VE_TZASC_BASE,2,TZASC_REGION_ENABLED,
- ARM_VE_SMB_NOR1_BASE + SIZE_32MB,0,
- TZASC_REGION_SIZE_32MB, TZASC_REGION_SECURITY_NSRW);
- } else {
- TZASCSetRegion(ARM_VE_TZASC_BASE,2,TZASC_REGION_ENABLED,
- ARM_VE_SMB_NOR1_BASE,0,
- TZASC_REGION_SIZE_64MB, TZASC_REGION_SECURITY_NSRW);
- }
-
- // Base of SRAM. Only half of SRAM in Non Secure world
- // First half non secure (16MB) + Second Half secure (16MB) = 32MB of SRAM
- if (PcdGetBool (PcdTrustzoneSupport) == TRUE) {
- //Note: Your OS Kernel must be aware of the secure regions before to enable this region
- TZASCSetRegion(ARM_VE_TZASC_BASE,3,TZASC_REGION_ENABLED,
- ARM_VE_SMB_SRAM_BASE,0,
- TZASC_REGION_SIZE_16MB, TZASC_REGION_SECURITY_NSRW);
- } else {
- TZASCSetRegion(ARM_VE_TZASC_BASE,3,TZASC_REGION_ENABLED,
- ARM_VE_SMB_SRAM_BASE,0,
- TZASC_REGION_SIZE_32MB, TZASC_REGION_SECURITY_NSRW);
- }
-
- // Memory Mapped Peripherals. All in non secure world
- TZASCSetRegion(ARM_VE_TZASC_BASE,4,TZASC_REGION_ENABLED,
- ARM_VE_SMB_PERIPH_BASE,0,
- TZASC_REGION_SIZE_64MB, TZASC_REGION_SECURITY_NSRW);
-
- // MotherBoard Peripherals and On-chip peripherals.
- TZASCSetRegion(ARM_VE_TZASC_BASE,5,TZASC_REGION_ENABLED,
- ARM_VE_SMB_MB_ON_CHIP_PERIPH_BASE,0,
- TZASC_REGION_SIZE_256MB, TZASC_REGION_SECURITY_NSRW);
-}
-
-/**
- Initialize controllers that must setup at the early stage
-
- Some peripherals must be initialized in Secure World.
- For example, some L2x0 requires to be initialized in Secure World
-
-**/
-RETURN_STATUS
-ArmPlatformSecInitialize (
- IN UINTN MpId
- )
-{
- // If it is not the primary core then there is nothing to do
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // The L2x0 controller must be intialize in Secure World
- L2x0CacheInit(PcdGet32(PcdL2x0ControllerBase),
- PL310_TAG_LATENCIES(L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES),
- PL310_DATA_LATENCIES(L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES),
- 0,~0, // Use default setting for the Auxiliary Control Register
- FALSE);
-
- // Initialize the System Configuration
- ArmPlatformSysConfigInitialize ();
-
- // If we skip the PEI Core we could want to initialize the DRAM in the SEC phase.
- // If we are in standalone, we need the initialization to copy the UEFI firmware into DRAM
- if ((FeaturePcdGet (PcdSystemMemoryInitializeInSec)) || (FeaturePcdGet (PcdStandalone) == FALSE)) {
- // If it is not a standalone build ensure the PcdSystemMemoryInitializeInSec has been set
- ASSERT(FeaturePcdGet (PcdSystemMemoryInitializeInSec) == TRUE);
-
- // Initialize system memory (DRAM)
- ArmPlatformInitializeSystemMemory ();
- }
-
- return RETURN_SUCCESS;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/ArmPlatformLib.h>
+#include <Library/ArmPlatformSysConfigLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+
+#include <Drivers/ArmTrustzone.h>
+#include <Drivers/PL310L2Cache.h>
+
+#include <ArmPlatform.h>
+
+/**
+ Initialize the Secure peripherals and memory regions
+
+ If Trustzone is supported by your platform then this function makes the required initialization
+ of the secure peripherals and memory regions.
+
+**/
+VOID
+ArmPlatformSecTrustzoneInit (
+ IN UINTN MpId
+ )
+{
+ // Nothing to do
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return;
+ }
+
+ //
+ // Setup TZ Protection Controller
+ //
+
+ if (MmioRead32(ARM_VE_SYS_CFGRW1_REG) & ARM_VE_CFGRW1_TZASC_EN_BIT_MASK) {
+ ASSERT (PcdGetBool (PcdTrustzoneSupport) == TRUE);
+ } else {
+ ASSERT (PcdGetBool (PcdTrustzoneSupport) == FALSE);
+ }
+
+ // Set Non Secure access for all devices
+ TZPCSetDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_0, 0xFFFFFFFF);
+ TZPCSetDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_1, 0xFFFFFFFF);
+ TZPCSetDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_2, 0xFFFFFFFF);
+
+ // Remove Non secure access to secure devices
+ TZPCClearDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_0,
+ ARM_VE_DECPROT_BIT_TZPC | ARM_VE_DECPROT_BIT_DMC_TZASC | ARM_VE_DECPROT_BIT_NMC_TZASC | ARM_VE_DECPROT_BIT_SMC_TZASC);
+
+ TZPCClearDecProtBits(ARM_VE_TZPC_BASE, TZPC_DECPROT_2,
+ ARM_VE_DECPROT_BIT_EXT_MAST_TZ | ARM_VE_DECPROT_BIT_DMC_TZASC_LOCK | ARM_VE_DECPROT_BIT_NMC_TZASC_LOCK | ARM_VE_DECPROT_BIT_SMC_TZASC_LOCK);
+
+ //
+ // Setup TZ Address Space Controller for the SMC. Create 5 Non Secure regions (NOR0, NOR1, SRAM, SMC Peripheral regions)
+ //
+
+ // NOR Flash 0 non secure (BootMon)
+ TZASCSetRegion(ARM_VE_TZASC_BASE,1,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_NOR0_BASE,0,
+ TZASC_REGION_SIZE_64MB, TZASC_REGION_SECURITY_NSRW);
+
+ // NOR Flash 1. The first half of the NOR Flash1 must be secure for the secure firmware (sec_uefi.bin)
+ if (PcdGetBool (PcdTrustzoneSupport) == TRUE) {
+ //Note: Your OS Kernel must be aware of the secure regions before to enable this region
+ TZASCSetRegion(ARM_VE_TZASC_BASE,2,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_NOR1_BASE + SIZE_32MB,0,
+ TZASC_REGION_SIZE_32MB, TZASC_REGION_SECURITY_NSRW);
+ } else {
+ TZASCSetRegion(ARM_VE_TZASC_BASE,2,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_NOR1_BASE,0,
+ TZASC_REGION_SIZE_64MB, TZASC_REGION_SECURITY_NSRW);
+ }
+
+ // Base of SRAM. Only half of SRAM in Non Secure world
+ // First half non secure (16MB) + Second Half secure (16MB) = 32MB of SRAM
+ if (PcdGetBool (PcdTrustzoneSupport) == TRUE) {
+ //Note: Your OS Kernel must be aware of the secure regions before to enable this region
+ TZASCSetRegion(ARM_VE_TZASC_BASE,3,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_SRAM_BASE,0,
+ TZASC_REGION_SIZE_16MB, TZASC_REGION_SECURITY_NSRW);
+ } else {
+ TZASCSetRegion(ARM_VE_TZASC_BASE,3,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_SRAM_BASE,0,
+ TZASC_REGION_SIZE_32MB, TZASC_REGION_SECURITY_NSRW);
+ }
+
+ // Memory Mapped Peripherals. All in non secure world
+ TZASCSetRegion(ARM_VE_TZASC_BASE,4,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_PERIPH_BASE,0,
+ TZASC_REGION_SIZE_64MB, TZASC_REGION_SECURITY_NSRW);
+
+ // MotherBoard Peripherals and On-chip peripherals.
+ TZASCSetRegion(ARM_VE_TZASC_BASE,5,TZASC_REGION_ENABLED,
+ ARM_VE_SMB_MB_ON_CHIP_PERIPH_BASE,0,
+ TZASC_REGION_SIZE_256MB, TZASC_REGION_SECURITY_NSRW);
+}
+
+/**
+ Initialize controllers that must setup at the early stage
+
+ Some peripherals must be initialized in Secure World.
+ For example, some L2x0 requires to be initialized in Secure World
+
+**/
+RETURN_STATUS
+ArmPlatformSecInitialize (
+ IN UINTN MpId
+ )
+{
+ // If it is not the primary core then there is nothing to do
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // The L2x0 controller must be intialize in Secure World
+ L2x0CacheInit(PcdGet32(PcdL2x0ControllerBase),
+ PL310_TAG_LATENCIES(L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES),
+ PL310_DATA_LATENCIES(L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES,L2x0_LATENCY_8_CYCLES),
+ 0,~0, // Use default setting for the Auxiliary Control Register
+ FALSE);
+
+ // Initialize the System Configuration
+ ArmPlatformSysConfigInitialize ();
+
+ // If we skip the PEI Core we could want to initialize the DRAM in the SEC phase.
+ // If we are in standalone, we need the initialization to copy the UEFI firmware into DRAM
+ if ((FeaturePcdGet (PcdSystemMemoryInitializeInSec)) || (FeaturePcdGet (PcdStandalone) == FALSE)) {
+ // If it is not a standalone build ensure the PcdSystemMemoryInitializeInSec has been set
+ ASSERT(FeaturePcdGet (PcdSystemMemoryInitializeInSec) == TRUE);
+
+ // Initialize system memory (DRAM)
+ ArmPlatformInitializeSystemMemory ();
+ }
+
+ return RETURN_SUCCESS;
+}
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/ArmVExpressSecLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/ArmVExpressSecLib.inf
index 4a1e056af..ff8476718 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/ArmVExpressSecLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/ArmVExpressSecLib.inf
@@ -1,52 +1,52 @@
-#/* @file
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#*/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = RTSMArmVExpressSecLib
- FILE_GUID = 1fdaabb0-ab7d-480c-91ff-428dc1546f3a
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformSecLib
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- IoLib
- ArmLib
- SerialPortLib
-
-[Sources.common]
- RTSMSec.c
-
-[Sources.ARM]
- Arm/RTSMBoot.asm | RVCT
- Arm/RTSMBoot.S | GCC
- Arm/RTSMHelper.asm | RVCT
- Arm/RTSMHelper.S | GCC
-
-[FeaturePcd]
- gEmbeddedTokenSpaceGuid.PcdCacheEnable
- gArmPlatformTokenSpaceGuid.PcdNorFlashRemapping
- gArmPlatformTokenSpaceGuid.PcdStandalone
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdFvBaseAddress
-
- gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
- gArmTokenSpaceGuid.PcdArmPrimaryCore
+#/* @file
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#*/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = RTSMArmVExpressSecLib
+ FILE_GUID = 1fdaabb0-ab7d-480c-91ff-428dc1546f3a
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformSecLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ IoLib
+ ArmLib
+ SerialPortLib
+
+[Sources.common]
+ RTSMSec.c
+
+[Sources.ARM]
+ Arm/RTSMBoot.asm | RVCT
+ Arm/RTSMBoot.S | GCC
+ Arm/RTSMHelper.asm | RVCT
+ Arm/RTSMHelper.S | GCC
+
+[FeaturePcd]
+ gEmbeddedTokenSpaceGuid.PcdCacheEnable
+ gArmPlatformTokenSpaceGuid.PcdNorFlashRemapping
+ gArmPlatformTokenSpaceGuid.PcdStandalone
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdFvBaseAddress
+
+ gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
+ gArmTokenSpaceGuid.PcdArmPrimaryCore
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/RTSMSec.c b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/RTSMSec.c
index 4ae630160..92df56cd5 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/RTSMSec.c
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSecLibRTSM/RTSMSec.c
@@ -1,83 +1,83 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/IoLib.h>
-#include <Library/ArmPlatformLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-
-#include <Drivers/PL310L2Cache.h>
-#include <Drivers/SP804Timer.h>
-
-#include <ArmPlatform.h>
-
-/**
- Initialize the Secure peripherals and memory regions
-
- If Trustzone is supported by your platform then this function makes the required initialization
- of the secure peripherals and memory regions.
-
-**/
-VOID
-ArmPlatformSecTrustzoneInit (
- IN UINTN MpId
- )
-{
- // No TZPC or TZASC on RTSM to initialize
-}
-
-/**
- Initialize controllers that must setup at the early stage
-
- Some peripherals must be initialized in Secure World.
- For example, some L2x0 requires to be initialized in Secure World
-
-**/
-RETURN_STATUS
-ArmPlatformSecInitialize (
- IN UINTN MpId
- )
-{
- // If it is not the primary core then there is nothing to do
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // Configure periodic timer (TIMER0) for 1MHz operation
- MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER0_TIMCLK);
- // Configure 1MHz clock
- MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER1_TIMCLK);
- // Configure SP810 to use 1MHz clock and disable
- MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER2_EN, SP810_SYS_CTRL_TIMER2_TIMCLK);
- // Configure SP810 to use 1MHz clock and disable
- MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER3_EN, SP810_SYS_CTRL_TIMER3_TIMCLK);
-
- return RETURN_SUCCESS;
-}
-
-/**
- Call before jumping to Normal World
-
- This function allows the firmware platform to do extra actions before
- jumping to the Normal World
-
-**/
-VOID
-ArmPlatformSecExtraAction (
- IN UINTN MpId,
- OUT UINTN* JumpAddress
- )
-{
- *JumpAddress = PcdGet32(PcdFvBaseAddress);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/IoLib.h>
+#include <Library/ArmPlatformLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+
+#include <Drivers/PL310L2Cache.h>
+#include <Drivers/SP804Timer.h>
+
+#include <ArmPlatform.h>
+
+/**
+ Initialize the Secure peripherals and memory regions
+
+ If Trustzone is supported by your platform then this function makes the required initialization
+ of the secure peripherals and memory regions.
+
+**/
+VOID
+ArmPlatformSecTrustzoneInit (
+ IN UINTN MpId
+ )
+{
+ // No TZPC or TZASC on RTSM to initialize
+}
+
+/**
+ Initialize controllers that must setup at the early stage
+
+ Some peripherals must be initialized in Secure World.
+ For example, some L2x0 requires to be initialized in Secure World
+
+**/
+RETURN_STATUS
+ArmPlatformSecInitialize (
+ IN UINTN MpId
+ )
+{
+ // If it is not the primary core then there is nothing to do
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // Configure periodic timer (TIMER0) for 1MHz operation
+ MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER0_TIMCLK);
+ // Configure 1MHz clock
+ MmioOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, SP810_SYS_CTRL_TIMER1_TIMCLK);
+ // Configure SP810 to use 1MHz clock and disable
+ MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER2_EN, SP810_SYS_CTRL_TIMER2_TIMCLK);
+ // Configure SP810 to use 1MHz clock and disable
+ MmioAndThenOr32 (SP810_CTRL_BASE + SP810_SYS_CTRL_REG, ~SP810_SYS_CTRL_TIMER3_EN, SP810_SYS_CTRL_TIMER3_TIMCLK);
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Call before jumping to Normal World
+
+ This function allows the firmware platform to do extra actions before
+ jumping to the Normal World
+
+**/
+VOID
+ArmPlatformSecExtraAction (
+ IN UINTN MpId,
+ OUT UINTN* JumpAddress
+ )
+{
+ *JumpAddress = PcdGet32(PcdFvBaseAddress);
+}
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf
index 3dfa756dd..8d4f52c52 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf
@@ -1,35 +1,35 @@
-#/** @file
-#
-# Component description file for ArmVExpressSysConfigLib module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmVExpressSysConfigLib
- FILE_GUID = a05b5cc0-82d2-11e0-82cb-0002a5d5c51b
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformSysConfigLib
-
-[Sources.common]
- ArmVExpressSysConfig.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- IoLib
+#/** @file
+#
+# Component description file for ArmVExpressSysConfigLib module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmVExpressSysConfigLib
+ FILE_GUID = a05b5cc0-82d2-11e0-82cb-0002a5d5c51b
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformSysConfigLib
+
+[Sources.common]
+ ArmVExpressSysConfig.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ IoLib
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/HdLcdArmVExpressLib/HdLcdArmVExpressLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/HdLcdArmVExpressLib/HdLcdArmVExpressLib.inf
index 73a17fb81..6a1814e09 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/HdLcdArmVExpressLib/HdLcdArmVExpressLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/HdLcdArmVExpressLib/HdLcdArmVExpressLib.inf
@@ -41,4 +41,4 @@ HdLcdArmVExpress.c
[Pcd]
gArmVExpressTokenSpaceGuid.PcdPL111LcdMaxMode
- gArmVExpressTokenSpaceGuid.PcdHdLcdVideoModeOscId \ No newline at end of file
+ gArmVExpressTokenSpaceGuid.PcdHdLcdVideoModeOscId \ No newline at end of file
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf
index 45af92126..af227d5e6 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf
@@ -1,32 +1,32 @@
-#/** @file
-#
-# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = NorFlashArmVExpressLib
- FILE_GUID = c0f5dfa0-7599-11e0-9665-0002a5d5c51b
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- LIBRARY_CLASS = NorFlashPlatformLib
-
-[Sources.common]
- NorFlashArmVExpress.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- IoLib
+#/** @file
+#
+# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = NorFlashArmVExpressLib
+ FILE_GUID = c0f5dfa0-7599-11e0-9665-0002a5d5c51b
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = NorFlashPlatformLib
+
+[Sources.common]
+ NorFlashArmVExpress.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ IoLib
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/PL111LcdArmVExpressLib/PL111LcdArmVExpressLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/PL111LcdArmVExpressLib/PL111LcdArmVExpressLib.inf
index c9b6a98c2..2440ea99c 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/PL111LcdArmVExpressLib/PL111LcdArmVExpressLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/PL111LcdArmVExpressLib/PL111LcdArmVExpressLib.inf
@@ -1,43 +1,43 @@
-#/** @file
-#
-# Component description file for ArmVeGraphicsDxe module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = PL111LcdArmVExpressLib
- FILE_GUID = b7f06f20-496f-11e0-a8e8-0002a5d5c51b
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- LIBRARY_CLASS = LcdPlatformLib
-
-[Sources.common]
- PL111LcdArmVExpress.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- ArmPlatformSysConfigLib
-
-[Protocols]
- gEfiEdidDiscoveredProtocolGuid # Produced
- gEfiEdidActiveProtocolGuid # Produced
-
-[Pcd]
- gArmVExpressTokenSpaceGuid.PcdPL111LcdMaxMode
- gArmVExpressTokenSpaceGuid.PcdPL111LcdVideoModeOscId
+#/** @file
+#
+# Component description file for ArmVeGraphicsDxe module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PL111LcdArmVExpressLib
+ FILE_GUID = b7f06f20-496f-11e0-a8e8-0002a5d5c51b
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = LcdPlatformLib
+
+[Sources.common]
+ PL111LcdArmVExpress.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ ArmPlatformSysConfigLib
+
+[Protocols]
+ gEfiEdidDiscoveredProtocolGuid # Produced
+ gEfiEdidActiveProtocolGuid # Produced
+
+[Pcd]
+ gArmVExpressTokenSpaceGuid.PcdPL111LcdMaxMode
+ gArmVExpressTokenSpaceGuid.PcdPL111LcdVideoModeOscId
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.c b/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.c
index a471eb260..f85831755 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.c
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.c
@@ -1,81 +1,81 @@
-/** @file
- Template library implementation to support ResetSystem Runtime call.
-
- Fill in the templates with what ever makes you system reset.
-
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <PiDxe.h>
-
-#include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
-#include <Library/EfiResetSystemLib.h>
-#include <Library/ArmPlatformSysConfigLib.h>
-
-#include <ArmPlatform.h>
-
-/**
- Resets the entire platform.
-
- @param ResetType The type of reset to perform.
- @param ResetStatus The status code for the reset.
- @param DataSize The size, in bytes, of WatchdogData.
- @param ResetData For a ResetType of EfiResetCold, EfiResetWarm, or
- EfiResetShutdown the data buffer starts with a Null-terminated
- Unicode string, optionally followed by additional binary data.
-
-**/
-EFI_STATUS
-EFIAPI
-LibResetSystem (
- IN EFI_RESET_TYPE ResetType,
- IN EFI_STATUS ResetStatus,
- IN UINTN DataSize,
- IN CHAR16 *ResetData OPTIONAL
- )
-{
- switch (ResetType) {
- case EfiResetWarm:
- // Map a warm reset into a cold reset
- case EfiResetCold:
- case EfiResetShutdown:
- // Send the REBOOT function to the platform microcontroller
- ArmPlatformSysConfigSet (SYS_CFG_REBOOT, 0);
-
- // We should never be here
- while(1);
- }
-
- ASSERT(FALSE);
- return EFI_UNSUPPORTED;
-}
-
-/**
- Initialize any infrastructure required for LibResetSystem () to function.
-
- @param ImageHandle The firmware allocated handle for the EFI image.
- @param SystemTable A pointer to the EFI System Table.
-
- @retval EFI_SUCCESS The constructor always returns EFI_SUCCESS.
-
-**/
-EFI_STATUS
-EFIAPI
-LibInitializeResetSystem (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- return EFI_SUCCESS;
-}
+/** @file
+ Template library implementation to support ResetSystem Runtime call.
+
+ Fill in the templates with what ever makes you system reset.
+
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PiDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/EfiResetSystemLib.h>
+#include <Library/ArmPlatformSysConfigLib.h>
+
+#include <ArmPlatform.h>
+
+/**
+ Resets the entire platform.
+
+ @param ResetType The type of reset to perform.
+ @param ResetStatus The status code for the reset.
+ @param DataSize The size, in bytes, of WatchdogData.
+ @param ResetData For a ResetType of EfiResetCold, EfiResetWarm, or
+ EfiResetShutdown the data buffer starts with a Null-terminated
+ Unicode string, optionally followed by additional binary data.
+
+**/
+EFI_STATUS
+EFIAPI
+LibResetSystem (
+ IN EFI_RESET_TYPE ResetType,
+ IN EFI_STATUS ResetStatus,
+ IN UINTN DataSize,
+ IN CHAR16 *ResetData OPTIONAL
+ )
+{
+ switch (ResetType) {
+ case EfiResetWarm:
+ // Map a warm reset into a cold reset
+ case EfiResetCold:
+ case EfiResetShutdown:
+ // Send the REBOOT function to the platform microcontroller
+ ArmPlatformSysConfigSet (SYS_CFG_REBOOT, 0);
+
+ // We should never be here
+ while(1);
+ }
+
+ ASSERT(FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Initialize any infrastructure required for LibResetSystem () to function.
+
+ @param ImageHandle The firmware allocated handle for the EFI image.
+ @param SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The constructor always returns EFI_SUCCESS.
+
+**/
+EFI_STATUS
+EFIAPI
+LibInitializeResetSystem (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ return EFI_SUCCESS;
+}
diff --git a/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.inf b/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.inf
index 3965e211e..8dbd1c869 100644
--- a/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.inf
+++ b/ArmPlatformPkg/ArmVExpressPkg/Library/ResetSystemLib/ResetSystemLib.inf
@@ -1,35 +1,35 @@
-#/** @file
-# Reset System lib to make it easy to port new platforms
-#
-# Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmVeResetSystemLib
- FILE_GUID = 36885202-0854-4373-bfd2-95d229b44d44
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = EfiResetSystemLib
-
-[Sources.common]
- ResetSystemLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- DebugLib
- BaseLib
- ArmPlatformSysConfigLib
+#/** @file
+# Reset System lib to make it easy to port new platforms
+#
+# Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmVeResetSystemLib
+ FILE_GUID = 36885202-0854-4373-bfd2-95d229b44d44
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = EfiResetSystemLib
+
+[Sources.common]
+ ResetSystemLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ BaseLib
+ ArmPlatformSysConfigLib
diff --git a/ArmPlatformPkg/Bds/Bds.c b/ArmPlatformPkg/Bds/Bds.c
index fe463774e..129c7b1d9 100644
--- a/ArmPlatformPkg/Bds/Bds.c
+++ b/ArmPlatformPkg/Bds/Bds.c
@@ -268,8 +268,13 @@ DefineDefaultBootEntries (
CmdLineSize = AsciiStrSize ((CHAR8*)PcdGetPtr(PcdDefaultBootArgument));
InitrdPath = EfiDevicePathFromTextProtocol->ConvertTextToDevicePath ((CHAR16*)PcdGetPtr(PcdDefaultBootInitrdPath));
InitrdSize = GetDevicePathSize (InitrdPath);
- FdtLocalPath = EfiDevicePathFromTextProtocol->ConvertTextToDevicePath ((CHAR16*)PcdGetPtr(PcdFdtLocalDevicePath));
- FdtLocalSize = GetDevicePathSize (FdtLocalPath);
+ if (BootType == BDS_LOADER_KERNEL_LINUX_LOCAL_FDT) {
+ FdtLocalPath = EfiDevicePathFromTextProtocol->ConvertTextToDevicePath ((CHAR16*)PcdGetPtr(PcdDefaultFdtLocalDevicePath));
+ FdtLocalSize = GetDevicePathSize (FdtLocalPath);
+ } else {
+ FdtLocalPath = NULL;
+ FdtLocalSize = 0;
+ }
BootArguments = (ARM_BDS_LOADER_ARGUMENTS*)AllocatePool (sizeof(ARM_BDS_LOADER_ARGUMENTS) + CmdLineSize + InitrdSize + FdtLocalSize);
BootArguments->LinuxArguments.CmdLineSize = CmdLineSize;
diff --git a/ArmPlatformPkg/Bds/Bds.inf b/ArmPlatformPkg/Bds/Bds.inf
index f48879367..a032d5e47 100644
--- a/ArmPlatformPkg/Bds/Bds.inf
+++ b/ArmPlatformPkg/Bds/Bds.inf
@@ -1,76 +1,77 @@
-#/** @file
-#
-# Component description file for Bds module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmPlatformBds
- FILE_GUID = 5a50aa81-c3ae-4608-a0e3-41a2e69baf94
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = BdsInitialize
-
-[Sources.common]
- Bds.c
- BdsHelper.c
- BootMenu.c
- BootOption.c
- BootOptionSupport.c
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BdsLib
- TimerLib
- PerformanceLib
- UefiBootServicesTableLib
- DxeServicesTableLib
- UefiDriverEntryPoint
- DebugLib
- PrintLib
- BaseLib
-
-[Guids]
- gEfiFileSystemInfoGuid
-
-[Protocols]
- gEfiBdsArchProtocolGuid
- gEfiBlockIoProtocolGuid
- gEfiSimpleTextInProtocolGuid
- gEfiPxeBaseCodeProtocolGuid
- gEfiSimpleNetworkProtocolGuid
- gEfiDevicePathToTextProtocolGuid
-
-[Pcd]
- gArmPlatformTokenSpaceGuid.PcdFirmwareVendor
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath
- gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath
- gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument
- gArmPlatformTokenSpaceGuid.PcdDefaultBootType
- gArmPlatformTokenSpaceGuid.PcdFdtDevicePath
- gArmPlatformTokenSpaceGuid.PcdFdtLocalDevicePath
- gArmPlatformTokenSpaceGuid.PcdPlatformBootTimeOut
- gArmPlatformTokenSpaceGuid.PcdDefaultConInPaths
- gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths
-
-[Depex]
- TRUE
+#/** @file
+#
+# Component description file for Bds module
+#
+# Copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmPlatformBds
+ FILE_GUID = 5a50aa81-c3ae-4608-a0e3-41a2e69baf94
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = BdsInitialize
+
+[Sources.common]
+ Bds.c
+ BdsHelper.c
+ BootMenu.c
+ BootOption.c
+ BootOptionSupport.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BdsLib
+ TimerLib
+ PerformanceLib
+ UefiBootServicesTableLib
+ DxeServicesTableLib
+ UefiDriverEntryPoint
+ DebugLib
+ PrintLib
+ BaseLib
+
+[Guids]
+ gEfiFileSystemInfoGuid
+ gArmGlobalVariableGuid
+
+[Protocols]
+ gEfiBdsArchProtocolGuid
+ gEfiBlockIoProtocolGuid
+ gEfiSimpleTextInProtocolGuid
+ gEfiPxeBaseCodeProtocolGuid
+ gEfiSimpleNetworkProtocolGuid
+ gEfiDevicePathToTextProtocolGuid
+
+[Pcd]
+ gArmPlatformTokenSpaceGuid.PcdFirmwareVendor
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootType
+ gArmPlatformTokenSpaceGuid.PcdFdtDevicePath
+ gArmPlatformTokenSpaceGuid.PcdDefaultFdtLocalDevicePath
+ gArmPlatformTokenSpaceGuid.PcdPlatformBootTimeOut
+ gArmPlatformTokenSpaceGuid.PcdDefaultConInPaths
+ gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths
+
+[Depex]
+ TRUE
diff --git a/ArmPlatformPkg/Bds/BdsHelper.c b/ArmPlatformPkg/Bds/BdsHelper.c
index 84988f046..cd7c8a583 100644
--- a/ArmPlatformPkg/Bds/BdsHelper.c
+++ b/ArmPlatformPkg/Bds/BdsHelper.c
@@ -1,320 +1,320 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "BdsInternal.h"
-
-EFI_STATUS
-EditHIInputStr (
- IN OUT CHAR16 *CmdLine,
- IN UINTN MaxCmdLine
- )
-{
- UINTN CmdLineIndex;
- UINTN WaitIndex;
- CHAR8 Char;
- EFI_INPUT_KEY Key;
- EFI_STATUS Status;
-
- Print (CmdLine);
-
- for (CmdLineIndex = StrLen (CmdLine); CmdLineIndex < MaxCmdLine; ) {
- Status = gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &WaitIndex);
- ASSERT_EFI_ERROR (Status);
-
- Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
- ASSERT_EFI_ERROR (Status);
-
- // Unicode character is valid when Scancode is NUll
- if (Key.ScanCode == SCAN_NULL) {
- // Scan code is NUll, hence read Unicode character
- Char = (CHAR8)Key.UnicodeChar;
- } else {
- Char = CHAR_NULL;
- }
-
- if ((Char == CHAR_LINEFEED) || (Char == CHAR_CARRIAGE_RETURN) || (Char == 0x7f)) {
- CmdLine[CmdLineIndex] = '\0';
- Print (L"\n\r");
-
- return EFI_SUCCESS;
- } else if ((Key.UnicodeChar == L'\b') || (Key.ScanCode == SCAN_LEFT) || (Key.ScanCode == SCAN_DELETE)){
- if (CmdLineIndex != 0) {
- CmdLineIndex--;
- Print (L"\b \b");
- }
- } else if ((Key.ScanCode == SCAN_ESC) || (Char == 0x1B) || (Char == 0x0)) {
- return EFI_INVALID_PARAMETER;
- } else {
- CmdLine[CmdLineIndex++] = Key.UnicodeChar;
- Print (L"%c", Key.UnicodeChar);
- }
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-GetHIInputStr (
- IN OUT CHAR16 *CmdLine,
- IN UINTN MaxCmdLine
- )
-{
- EFI_STATUS Status;
-
- // For a new input just passed an empty string
- CmdLine[0] = L'\0';
-
- Status = EditHIInputStr (CmdLine, MaxCmdLine);
-
- return Status;
-}
-
-EFI_STATUS
-EditHIInputAscii (
- IN OUT CHAR8 *CmdLine,
- IN UINTN MaxCmdLine
- )
-{
- CHAR16* Str;
- EFI_STATUS Status;
-
- Str = (CHAR16*)AllocatePool (MaxCmdLine * sizeof(CHAR16));
- AsciiStrToUnicodeStr (CmdLine, Str);
-
- Status = EditHIInputStr (Str, MaxCmdLine);
- if (!EFI_ERROR(Status)) {
- UnicodeStrToAsciiStr (Str, CmdLine);
- }
- FreePool (Str);
-
- return Status;
-}
-
-EFI_STATUS
-GetHIInputAscii (
- IN OUT CHAR8 *CmdLine,
- IN UINTN MaxCmdLine
- )
-{
- // For a new input just passed an empty string
- CmdLine[0] = '\0';
-
- return EditHIInputAscii (CmdLine,MaxCmdLine);
-}
-
-EFI_STATUS
-GetHIInputInteger (
- OUT UINTN *Integer
- )
-{
- CHAR16 CmdLine[255];
- EFI_STATUS Status;
-
- CmdLine[0] = '\0';
- Status = EditHIInputStr (CmdLine, 255);
- if (!EFI_ERROR(Status)) {
- *Integer = StrDecimalToUintn (CmdLine);
- }
-
- return Status;
-}
-
-EFI_STATUS
-GetHIInputIP (
- OUT EFI_IP_ADDRESS *Ip
- )
-{
- CHAR16 CmdLine[255];
- CHAR16 *Str;
- EFI_STATUS Status;
-
- CmdLine[0] = '\0';
- Status = EditHIInputStr (CmdLine,255);
- if (!EFI_ERROR(Status)) {
- Str = CmdLine;
- Ip->v4.Addr[0] = (UINT8)StrDecimalToUintn (Str);
-
- Str = StrStr (Str, L".");
- if (Str == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- Ip->v4.Addr[1] = (UINT8)StrDecimalToUintn (++Str);
-
- Str = StrStr (Str, L".");
- if (Str == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- Ip->v4.Addr[2] = (UINT8)StrDecimalToUintn (++Str);
-
- Str = StrStr (Str, L".");
- if (Str == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- Ip->v4.Addr[3] = (UINT8)StrDecimalToUintn (++Str);
- }
-
- return Status;
-}
-
-EFI_STATUS
-GetHIInputBoolean (
- OUT BOOLEAN *Value
- )
-{
- CHAR16 CmdBoolean[2];
- EFI_STATUS Status;
-
- while(1) {
- Print (L"[y/n] ");
- Status = GetHIInputStr (CmdBoolean, 2);
- if (EFI_ERROR(Status)) {
- return Status;
- } else if ((CmdBoolean[0] == L'y') || (CmdBoolean[0] == L'Y')) {
- if (Value) *Value = TRUE;
- return EFI_SUCCESS;
- } else if ((CmdBoolean[0] == L'n') || (CmdBoolean[0] == L'N')) {
- if (Value) *Value = FALSE;
- return EFI_SUCCESS;
- }
- }
-}
-
-BOOLEAN
-HasFilePathEfiExtension (
- IN CHAR16* FilePath
- )
-{
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "BdsInternal.h"
+
+EFI_STATUS
+EditHIInputStr (
+ IN OUT CHAR16 *CmdLine,
+ IN UINTN MaxCmdLine
+ )
+{
+ UINTN CmdLineIndex;
+ UINTN WaitIndex;
+ CHAR8 Char;
+ EFI_INPUT_KEY Key;
+ EFI_STATUS Status;
+
+ Print (CmdLine);
+
+ for (CmdLineIndex = StrLen (CmdLine); CmdLineIndex < MaxCmdLine; ) {
+ Status = gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &WaitIndex);
+ ASSERT_EFI_ERROR (Status);
+
+ Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
+ ASSERT_EFI_ERROR (Status);
+
+ // Unicode character is valid when Scancode is NUll
+ if (Key.ScanCode == SCAN_NULL) {
+ // Scan code is NUll, hence read Unicode character
+ Char = (CHAR8)Key.UnicodeChar;
+ } else {
+ Char = CHAR_NULL;
+ }
+
+ if ((Char == CHAR_LINEFEED) || (Char == CHAR_CARRIAGE_RETURN) || (Char == 0x7f)) {
+ CmdLine[CmdLineIndex] = '\0';
+ Print (L"\n\r");
+
+ return EFI_SUCCESS;
+ } else if ((Key.UnicodeChar == L'\b') || (Key.ScanCode == SCAN_LEFT) || (Key.ScanCode == SCAN_DELETE)){
+ if (CmdLineIndex != 0) {
+ CmdLineIndex--;
+ Print (L"\b \b");
+ }
+ } else if ((Key.ScanCode == SCAN_ESC) || (Char == 0x1B) || (Char == 0x0)) {
+ return EFI_INVALID_PARAMETER;
+ } else {
+ CmdLine[CmdLineIndex++] = Key.UnicodeChar;
+ Print (L"%c", Key.UnicodeChar);
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+GetHIInputStr (
+ IN OUT CHAR16 *CmdLine,
+ IN UINTN MaxCmdLine
+ )
+{
+ EFI_STATUS Status;
+
+ // For a new input just passed an empty string
+ CmdLine[0] = L'\0';
+
+ Status = EditHIInputStr (CmdLine, MaxCmdLine);
+
+ return Status;
+}
+
+EFI_STATUS
+EditHIInputAscii (
+ IN OUT CHAR8 *CmdLine,
+ IN UINTN MaxCmdLine
+ )
+{
+ CHAR16* Str;
+ EFI_STATUS Status;
+
+ Str = (CHAR16*)AllocatePool (MaxCmdLine * sizeof(CHAR16));
+ AsciiStrToUnicodeStr (CmdLine, Str);
+
+ Status = EditHIInputStr (Str, MaxCmdLine);
+ if (!EFI_ERROR(Status)) {
+ UnicodeStrToAsciiStr (Str, CmdLine);
+ }
+ FreePool (Str);
+
+ return Status;
+}
+
+EFI_STATUS
+GetHIInputAscii (
+ IN OUT CHAR8 *CmdLine,
+ IN UINTN MaxCmdLine
+ )
+{
+ // For a new input just passed an empty string
+ CmdLine[0] = '\0';
+
+ return EditHIInputAscii (CmdLine,MaxCmdLine);
+}
+
+EFI_STATUS
+GetHIInputInteger (
+ OUT UINTN *Integer
+ )
+{
+ CHAR16 CmdLine[255];
+ EFI_STATUS Status;
+
+ CmdLine[0] = '\0';
+ Status = EditHIInputStr (CmdLine, 255);
+ if (!EFI_ERROR(Status)) {
+ *Integer = StrDecimalToUintn (CmdLine);
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+GetHIInputIP (
+ OUT EFI_IP_ADDRESS *Ip
+ )
+{
+ CHAR16 CmdLine[255];
+ CHAR16 *Str;
+ EFI_STATUS Status;
+
+ CmdLine[0] = '\0';
+ Status = EditHIInputStr (CmdLine,255);
+ if (!EFI_ERROR(Status)) {
+ Str = CmdLine;
+ Ip->v4.Addr[0] = (UINT8)StrDecimalToUintn (Str);
+
+ Str = StrStr (Str, L".");
+ if (Str == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Ip->v4.Addr[1] = (UINT8)StrDecimalToUintn (++Str);
+
+ Str = StrStr (Str, L".");
+ if (Str == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Ip->v4.Addr[2] = (UINT8)StrDecimalToUintn (++Str);
+
+ Str = StrStr (Str, L".");
+ if (Str == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Ip->v4.Addr[3] = (UINT8)StrDecimalToUintn (++Str);
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+GetHIInputBoolean (
+ OUT BOOLEAN *Value
+ )
+{
+ CHAR16 CmdBoolean[2];
+ EFI_STATUS Status;
+
+ while(1) {
+ Print (L"[y/n] ");
+ Status = GetHIInputStr (CmdBoolean, 2);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ } else if ((CmdBoolean[0] == L'y') || (CmdBoolean[0] == L'Y')) {
+ if (Value) *Value = TRUE;
+ return EFI_SUCCESS;
+ } else if ((CmdBoolean[0] == L'n') || (CmdBoolean[0] == L'N')) {
+ if (Value) *Value = FALSE;
+ return EFI_SUCCESS;
+ }
+ }
+}
+
+BOOLEAN
+HasFilePathEfiExtension (
+ IN CHAR16* FilePath
+ )
+{
if (StrCmp (FilePath + (StrSize(FilePath)/sizeof(CHAR16)) - 5, L".EFI") == 0)
return 1;
- return (StrCmp (FilePath + (StrSize(FilePath)/sizeof(CHAR16)) - 5, L".efi") == 0);
-}
-
-// Return the last non end-type Device Path Node from a Device Path
-EFI_DEVICE_PATH*
-GetLastDevicePathNode (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- EFI_DEVICE_PATH* PrevDevicePathNode;
-
- PrevDevicePathNode = DevicePath;
- while (!IsDevicePathEndType (DevicePath)) {
- PrevDevicePathNode = DevicePath;
- DevicePath = NextDevicePathNode (DevicePath);
- }
-
- return PrevDevicePathNode;
-}
-
-EFI_STATUS
-GenerateDeviceDescriptionName (
- IN EFI_HANDLE Handle,
- IN OUT CHAR16* Description
- )
-{
- EFI_STATUS Status;
- EFI_COMPONENT_NAME_PROTOCOL* ComponentName2Protocol;
- EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* DevicePathToTextProtocol;
- EFI_DEVICE_PATH_PROTOCOL* DevicePathProtocol;
- CHAR16* DriverName;
- CHAR16* DevicePathTxt;
- EFI_DEVICE_PATH* DevicePathNode;
-
- ComponentName2Protocol = NULL;
- Status = gBS->HandleProtocol (Handle, &gEfiComponentName2ProtocolGuid, (VOID **)&ComponentName2Protocol);
- if (!EFI_ERROR(Status)) {
- //TODO: Fixme. we must find the best langague
- Status = ComponentName2Protocol->GetDriverName (ComponentName2Protocol,"en",&DriverName);
- if (!EFI_ERROR(Status)) {
- StrnCpy (Description, DriverName, BOOT_DEVICE_DESCRIPTION_MAX);
- }
- }
-
- if (EFI_ERROR(Status)) {
- // Use the lastest non null entry of the Device path as a description
- Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathProtocol);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Convert the last non end-type Device Path Node in text for the description
- DevicePathNode = GetLastDevicePathNode (DevicePathProtocol);
- Status = gBS->LocateProtocol (&gEfiDevicePathToTextProtocolGuid, NULL, (VOID **)&DevicePathToTextProtocol);
- ASSERT_EFI_ERROR(Status);
- DevicePathTxt = DevicePathToTextProtocol->ConvertDevicePathToText (DevicePathNode, TRUE, TRUE);
- StrnCpy (Description, DevicePathTxt, BOOT_DEVICE_DESCRIPTION_MAX);
- FreePool (DevicePathTxt);
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-BdsStartBootOption (
- IN CHAR16* BootOption
- )
-{
- EFI_STATUS Status;
- BDS_LOAD_OPTION *BdsLoadOption;
-
- Status = BootOptionFromLoadOptionVariable (BootOption, &BdsLoadOption);
- if (!EFI_ERROR(Status)) {
- Status = BootOptionStart (BdsLoadOption);
- FreePool (BdsLoadOption);
-
- if (!EFI_ERROR(Status)) {
- Status = EFI_SUCCESS;
- } else {
- Status = EFI_NOT_STARTED;
- }
- } else {
- Status = EFI_NOT_FOUND;
- }
- return Status;
-}
-
-UINTN
-GetUnalignedDevicePathSize (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- UINTN Size;
- EFI_DEVICE_PATH* AlignedDevicePath;
-
- if ((UINTN)DevicePath & 0x1) {
- AlignedDevicePath = DuplicateDevicePath (DevicePath);
- Size = GetDevicePathSize (AlignedDevicePath);
- FreePool (AlignedDevicePath);
- } else {
- Size = GetDevicePathSize (DevicePath);
- }
- return Size;
-}
-
-EFI_DEVICE_PATH*
-GetAlignedDevicePath (
- IN EFI_DEVICE_PATH* DevicePath
- )
-{
- if ((UINTN)DevicePath & 0x1) {
- return DuplicateDevicePath (DevicePath);
- } else {
- return DevicePath;
- }
-}
-
+ return (StrCmp (FilePath + (StrSize(FilePath)/sizeof(CHAR16)) - 5, L".efi") == 0);
+}
+
+// Return the last non end-type Device Path Node from a Device Path
+EFI_DEVICE_PATH*
+GetLastDevicePathNode (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ EFI_DEVICE_PATH* PrevDevicePathNode;
+
+ PrevDevicePathNode = DevicePath;
+ while (!IsDevicePathEndType (DevicePath)) {
+ PrevDevicePathNode = DevicePath;
+ DevicePath = NextDevicePathNode (DevicePath);
+ }
+
+ return PrevDevicePathNode;
+}
+
+EFI_STATUS
+GenerateDeviceDescriptionName (
+ IN EFI_HANDLE Handle,
+ IN OUT CHAR16* Description
+ )
+{
+ EFI_STATUS Status;
+ EFI_COMPONENT_NAME_PROTOCOL* ComponentName2Protocol;
+ EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* DevicePathToTextProtocol;
+ EFI_DEVICE_PATH_PROTOCOL* DevicePathProtocol;
+ CHAR16* DriverName;
+ CHAR16* DevicePathTxt;
+ EFI_DEVICE_PATH* DevicePathNode;
+
+ ComponentName2Protocol = NULL;
+ Status = gBS->HandleProtocol (Handle, &gEfiComponentName2ProtocolGuid, (VOID **)&ComponentName2Protocol);
+ if (!EFI_ERROR(Status)) {
+ //TODO: Fixme. we must find the best langague
+ Status = ComponentName2Protocol->GetDriverName (ComponentName2Protocol,"en",&DriverName);
+ if (!EFI_ERROR(Status)) {
+ StrnCpy (Description, DriverName, BOOT_DEVICE_DESCRIPTION_MAX);
+ }
+ }
+
+ if (EFI_ERROR(Status)) {
+ // Use the lastest non null entry of the Device path as a description
+ Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathProtocol);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Convert the last non end-type Device Path Node in text for the description
+ DevicePathNode = GetLastDevicePathNode (DevicePathProtocol);
+ Status = gBS->LocateProtocol (&gEfiDevicePathToTextProtocolGuid, NULL, (VOID **)&DevicePathToTextProtocol);
+ ASSERT_EFI_ERROR(Status);
+ DevicePathTxt = DevicePathToTextProtocol->ConvertDevicePathToText (DevicePathNode, TRUE, TRUE);
+ StrnCpy (Description, DevicePathTxt, BOOT_DEVICE_DESCRIPTION_MAX);
+ FreePool (DevicePathTxt);
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+BdsStartBootOption (
+ IN CHAR16* BootOption
+ )
+{
+ EFI_STATUS Status;
+ BDS_LOAD_OPTION *BdsLoadOption;
+
+ Status = BootOptionFromLoadOptionVariable (BootOption, &BdsLoadOption);
+ if (!EFI_ERROR(Status)) {
+ Status = BootOptionStart (BdsLoadOption);
+ FreePool (BdsLoadOption);
+
+ if (!EFI_ERROR(Status)) {
+ Status = EFI_SUCCESS;
+ } else {
+ Status = EFI_NOT_STARTED;
+ }
+ } else {
+ Status = EFI_NOT_FOUND;
+ }
+ return Status;
+}
+
+UINTN
+GetUnalignedDevicePathSize (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ UINTN Size;
+ EFI_DEVICE_PATH* AlignedDevicePath;
+
+ if ((UINTN)DevicePath & 0x1) {
+ AlignedDevicePath = DuplicateDevicePath (DevicePath);
+ Size = GetDevicePathSize (AlignedDevicePath);
+ FreePool (AlignedDevicePath);
+ } else {
+ Size = GetDevicePathSize (DevicePath);
+ }
+ return Size;
+}
+
+EFI_DEVICE_PATH*
+GetAlignedDevicePath (
+ IN EFI_DEVICE_PATH* DevicePath
+ )
+{
+ if ((UINTN)DevicePath & 0x1) {
+ return DuplicateDevicePath (DevicePath);
+ } else {
+ return DevicePath;
+ }
+}
+
diff --git a/ArmPlatformPkg/Bds/BootMenu.c b/ArmPlatformPkg/Bds/BootMenu.c
index 114f159bd..215be6ba4 100644
--- a/ArmPlatformPkg/Bds/BootMenu.c
+++ b/ArmPlatformPkg/Bds/BootMenu.c
@@ -1,6 +1,6 @@
/** @file
*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+* Copyright (c) 2011-2013, ARM Limited. All rights reserved.
*
* This program and the accompanying materials
* are licensed and made available under the terms and conditions of the BSD License
@@ -14,9 +14,12 @@
#include "BdsInternal.h"
+#include <Guid/ArmGlobalVariableHob.h>
+
extern EFI_HANDLE mImageHandle;
extern BDS_LOAD_OPTION_SUPPORT *BdsLoadOptionSupportList;
+
EFI_STATUS
SelectBootDevice (
OUT BDS_SUPPORTED_DEVICE** SupportedBootDevice
@@ -102,7 +105,7 @@ SelectBootDevice (
}
Index++;
}
-
+
EXIT:
BootDeviceListSupportedFree (&SupportedDeviceList, *SupportedBootDevice);
return Status;
@@ -187,7 +190,7 @@ BootMenuAddBootOption (
if (BootType == BDS_LOADER_KERNEL_LINUX_LOCAL_FDT) {
// Create the specific device path node
Status = SupportedBootDevice->Support->CreateDevicePathNode (L"local FDT", &FdtLocalPathNode, NULL, NULL);
- if (EFI_ERROR(Status) && Status != EFI_NOT_FOUND) { // EFI_NOT_FOUND is returned on empty input string, but we can boot without an initrd
+ if (EFI_ERROR(Status) || (FdtLocalPathNode == NULL)) {
Status = EFI_ABORTED;
goto EXIT;
}
@@ -207,7 +210,7 @@ BootMenuAddBootOption (
FdtLocalSize = GetDevicePathSize (FdtLocalPath);
BootArguments = (ARM_BDS_LOADER_ARGUMENTS*)AllocatePool (sizeof(ARM_BDS_LOADER_ARGUMENTS) + CmdLineSize + InitrdSize + FdtLocalSize);
-
+
BootArguments->LinuxArguments.CmdLineSize = CmdLineSize;
BootArguments->LinuxArguments.InitrdSize = InitrdSize;
BootArguments->LinuxArguments.FdtLocalSize = FdtLocalSize;
@@ -235,7 +238,7 @@ BootMenuAddBootOption (
FREE_DEVICE_PATH:
FreePool (DevicePath);
-
+
EXIT:
if (Status == EFI_ABORTED) {
Print(L"\n");
@@ -422,6 +425,57 @@ BootMenuUpdateBootOption (
CmdLineSize = ReadUnaligned16 ((CONST UINT16*)&LinuxArguments->CmdLineSize);
InitrdSize = ReadUnaligned16 ((CONST UINT16*)&LinuxArguments->InitrdSize);
+ FdtLocalSize = ReadUnaligned16 ((CONST UINT16*)&LinuxArguments->FdtLocalSize);
+
+ if (BootType == BDS_LOADER_KERNEL_LINUX_LOCAL_FDT) {
+ if (FdtLocalSize > 0) {
+ Print(L"Keep the local FDT: ");
+ } else {
+ Print(L"Add a local FDT: ");
+ }
+ Status = GetHIInputBoolean (&FdtLocalSupport);
+ if (EFI_ERROR(Status)) {
+ Status = EFI_ABORTED;
+ goto EXIT;
+ }
+ if (FdtLocalSupport && BootType == BDS_LOADER_KERNEL_LINUX_LOCAL_FDT) {
+ if (FdtLocalSize > 0) {
+ // Case we update the FDT local device path
+ Status = DeviceSupport->UpdateDevicePathNode ((EFI_DEVICE_PATH*)((UINTN)(LinuxArguments + 1) + CmdLineSize + InitrdSize), L"local FDT", &FdtLocalPath, NULL, NULL);
+ if (EFI_ERROR(Status) && Status != EFI_NOT_FOUND) {// EFI_NOT_FOUND is returned on empty input string
+ Status = EFI_ABORTED;
+ goto EXIT;
+ }
+ FdtLocalSize = GetDevicePathSize (FdtLocalPath);
+ } else {
+ // Case we create the FdtLocal device path
+
+ Status = DeviceSupport->CreateDevicePathNode (L"local FDT", &FdtLocalPathNode, NULL, NULL);
+ if (EFI_ERROR(Status) || (FdtLocalPathNode == NULL)) {
+ Status = EFI_ABORTED;
+ goto EXIT;
+ }
+
+ if (FdtLocalPathNode != NULL) {
+ // Duplicate Linux kernel Device Path
+ TempFdtLocalPath = DuplicateDevicePath (BootOption->FilePathList);
+ // Replace Linux kernel Node by EndNode
+ SetDevicePathEndNode (GetLastDevicePathNode (TempFdtLocalPath));
+ // Append the Device Path node to the select device path
+ FdtLocalPath = AppendDevicePathNode (TempFdtLocalPath, (CONST EFI_DEVICE_PATH_PROTOCOL *)FdtLocalPathNode);
+ FreePool (TempFdtLocalPath);
+ FdtLocalSize = GetDevicePathSize (FdtLocalPath);
+ } else {
+ FdtLocalPath = NULL;
+ }
+ }
+ } else {
+ FdtLocalSize = 0;
+ }
+ } else {
+ FdtLocalSupport = FALSE;
+ }
+
if (InitrdSize > 0) {
Print(L"Keep the initrd: ");
} else {
@@ -468,7 +522,7 @@ BootMenuUpdateBootOption (
InitrdSize = 0;
}
- Print(L"Arguments to pass to the binary: ");
+ Print(L"Arguments to pass to the binary: ");
if (CmdLineSize > 0) {
AsciiStrnCpy(CmdLine, (CONST CHAR8*)(LinuxArguments + 1), CmdLineSize);
} else {
@@ -592,10 +646,22 @@ UpdateFdtPath (
// Append the Device Path node to the select device path
FdtDevicePath = AppendDevicePathNode (SupportedBootDevice->DevicePathProtocol, FdtDevicePathNode);
FdtDevicePathSize = GetDevicePathSize (FdtDevicePath);
- Status = gRT->SetVariable ((CHAR16*)L"Fdt", &gEfiGlobalVariableGuid, (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS ), FdtDevicePathSize, FdtDevicePath);
+ Status = gRT->SetVariable (
+ (CHAR16*)L"Fdt",
+ &gArmGlobalVariableGuid,
+ EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
+ FdtDevicePathSize,
+ FdtDevicePath
+ );
ASSERT_EFI_ERROR(Status);
} else {
- gRT->SetVariable ((CHAR16*)L"Fdt", &gEfiGlobalVariableGuid, (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS ), 0, NULL);
+ gRT->SetVariable (
+ (CHAR16*)L"Fdt",
+ &gArmGlobalVariableGuid,
+ EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
+ 0,
+ NULL
+ );
ASSERT_EFI_ERROR(Status);
}
diff --git a/ArmPlatformPkg/Bds/BootOption.c b/ArmPlatformPkg/Bds/BootOption.c
index 364ad4083..78a42306d 100644
--- a/ArmPlatformPkg/Bds/BootOption.c
+++ b/ArmPlatformPkg/Bds/BootOption.c
@@ -1,6 +1,6 @@
/** @file
*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+* Copyright (c) 2011-2013, ARM Limited. All rights reserved.
*
* This program and the accompanying materials
* are licensed and made available under the terms and conditions of the BSD License
@@ -385,7 +385,11 @@ BootOptionDelete (
if (BootOrder[Index] == BootOption->LoadOptionIndex) {
// If it the last entry we do not need to rearrange the BootOrder list
if (Index + 1 != BootOrderCount) {
- CopyMem (&BootOrder[Index],&BootOrder[Index+1], BootOrderCount - (Index + 1));
+ CopyMem (
+ &BootOrder[Index],
+ &BootOrder[Index + 1],
+ (BootOrderCount - (Index + 1)) * sizeof(UINT16)
+ );
}
break;
}
diff --git a/ArmPlatformPkg/Bds/BootOptionSupport.c b/ArmPlatformPkg/Bds/BootOptionSupport.c
index 897786f5a..bf7a1c7d5 100644
--- a/ArmPlatformPkg/Bds/BootOptionSupport.c
+++ b/ArmPlatformPkg/Bds/BootOptionSupport.c
@@ -25,6 +25,7 @@
#include <Guid/FileSystemInfo.h>
#define IS_DEVICE_PATH_NODE(node,type,subtype) (((node)->Type == (type)) && ((node)->SubType == (subtype)))
+#define LOCAL_FDT_RESPONSE_LEN 2 // 1 character, plus carriage return
EFI_STATUS
BdsLoadOptionFileSystemList (
@@ -233,7 +234,7 @@ BootDeviceGetType (
EFI_STATUS Status;
BOOLEAN IsEfiApp;
BOOLEAN IsBootLoader;
- CHAR16 FDTType[16];
+ CHAR16 FDTType[ LOCAL_FDT_RESPONSE_LEN ];
if (FileName == NULL) {
Print(L"Is an EFI Application? ");
@@ -259,19 +260,19 @@ BootDeviceGetType (
*BootType = BDS_LOADER_EFI_APPLICATION;
} else {
Print(L"Boot Type: [a] ATAGS, [g] Global FDT or [l] Local FDT? [a/g/l] ");
- Status = GetHIInputStr (FDTType, 16);
+ Status = GetHIInputStr (FDTType, LOCAL_FDT_RESPONSE_LEN );
if (EFI_ERROR(Status)) {
return EFI_ABORTED;
}
- if (StrCmp(FDTType, L"g") == 0) {
+ if (StrCmp(FDTType, L"g") == 0) {
*BootType = BDS_LOADER_KERNEL_LINUX_GLOBAL_FDT;
- } else if (StrCmp(FDTType, L"l") == 0) {
+ } else if (StrCmp(FDTType, L"l") == 0) {
*BootType = BDS_LOADER_KERNEL_LINUX_LOCAL_FDT;
- } else if (StrCmp(FDTType, L"a") == 0) {
+ } else if (StrCmp(FDTType, L"a") == 0) {
*BootType = BDS_LOADER_KERNEL_LINUX_ATAG;
- } else {
- return EFI_ABORTED;
- }
+ } else {
+ return EFI_ABORTED;
+ }
}
return EFI_SUCCESS;
diff --git a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c
index 3c267df4d..ef85e7125 100644
--- a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c
+++ b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c
@@ -1,882 +1,882 @@
-/** @file
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
- **/
-
-#include <PiDxe.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/MemoryAllocationLib.h>
-
-#include <Guid/GlobalVariable.h>
-
-#include "LcdGraphicsOutputDxe.h"
-
-extern BOOLEAN mDisplayInitialized;
-
-//
-// Function Definitions
-//
-
-STATIC
-EFI_STATUS
-VideoCopyNoHorizontalOverlap (
- IN UINTN BitsPerPixel,
- IN volatile VOID *FrameBufferBase,
- IN UINT32 HorizontalResolution,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height
-)
-{
- EFI_STATUS Status = EFI_SUCCESS;
- UINTN SourceLine;
- UINTN DestinationLine;
- UINTN WidthInBytes;
- UINTN LineCount;
- INTN Step;
- VOID *SourceAddr;
- VOID *DestinationAddr;
-
- if( DestinationY <= SourceY ) {
- // scrolling up (or horizontally but without overlap)
- SourceLine = SourceY;
- DestinationLine = DestinationY;
- Step = 1;
- } else {
- // scrolling down
- SourceLine = SourceY + Height;
- DestinationLine = DestinationY + Height;
- Step = -1;
- }
-
- switch (BitsPerPixel) {
-
- case LCD_BITS_PER_PIXEL_24:
-
- WidthInBytes = Width * 4;
-
- for( LineCount = 0; LineCount < Height; LineCount++ ) {
- // Update the start addresses of source & destination using 32bit pointer arithmetic
- SourceAddr = (VOID *)((UINT32 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
- DestinationAddr = (VOID *)((UINT32 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
-
- // Copy the entire line Y from video ram to the temp buffer
- CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
-
- // Update the line numbers
- SourceLine += Step;
- DestinationLine += Step;
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_555:
- case LCD_BITS_PER_PIXEL_16_565:
- case LCD_BITS_PER_PIXEL_12_444:
-
- WidthInBytes = Width * 2;
-
- for( LineCount = 0; LineCount < Height; LineCount++ ) {
- // Update the start addresses of source & destination using 16bit pointer arithmetic
- SourceAddr = (VOID *)((UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
- DestinationAddr = (VOID *)((UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
-
- // Copy the entire line Y from video ram to the temp buffer
- CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
-
- // Update the line numbers
- SourceLine += Step;
- DestinationLine += Step;
- }
- break;
-
- case LCD_BITS_PER_PIXEL_8:
- case LCD_BITS_PER_PIXEL_4:
- case LCD_BITS_PER_PIXEL_2:
- case LCD_BITS_PER_PIXEL_1:
- default:
- // Can't handle this case
- DEBUG((DEBUG_ERROR, "ArmVeGraphics_Blt: EfiBltVideoToVideo: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- // break;
-
- }
-
- EXIT:
- return Status;
-}
-
-STATIC
-EFI_STATUS
-VideoCopyHorizontalOverlap (
- IN UINTN BitsPerPixel,
- IN volatile VOID *FrameBufferBase,
- UINT32 HorizontalResolution,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height
-)
-{
- EFI_STATUS Status = EFI_SUCCESS;
-
- UINT32 *PixelBuffer32bit;
- UINT32 *SourcePixel32bit;
- UINT32 *DestinationPixel32bit;
-
- UINT16 *PixelBuffer16bit;
- UINT16 *SourcePixel16bit;
- UINT16 *DestinationPixel16bit;
-
- UINT32 SourcePixelY;
- UINT32 DestinationPixelY;
- UINTN SizeIn32Bits;
- UINTN SizeIn16Bits;
-
- switch (BitsPerPixel) {
-
- case LCD_BITS_PER_PIXEL_24:
- // Allocate a temporary buffer
-
- PixelBuffer32bit = (UINT32 *) AllocatePool((Height * Width) * sizeof(UINT32));
-
- if (PixelBuffer32bit == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto EXIT;
- }
-
- SizeIn32Bits = Width * 4;
-
- // Copy from the video ram (source region) to a temp buffer
- for (SourcePixelY = SourceY, DestinationPixel32bit = PixelBuffer32bit;
- SourcePixelY < SourceY + Height;
- SourcePixelY++, DestinationPixel32bit += Width)
- {
- // Update the start address of line Y (source)
- SourcePixel32bit = (UINT32 *)FrameBufferBase + SourcePixelY * HorizontalResolution + SourceX;
-
- // Copy the entire line Y from video ram to the temp buffer
- CopyMem( (VOID *)DestinationPixel32bit, (CONST VOID *)SourcePixel32bit, SizeIn32Bits);
- }
-
- // Copy from the temp buffer to the video ram (destination region)
- for (DestinationPixelY = DestinationY, SourcePixel32bit = PixelBuffer32bit;
- DestinationPixelY < DestinationY + Height;
- DestinationPixelY++, SourcePixel32bit += Width)
- {
- // Update the start address of line Y (target)
- DestinationPixel32bit = (UINT32 *)FrameBufferBase + DestinationPixelY * HorizontalResolution + DestinationX;
-
- // Copy the entire line Y from the temp buffer to video ram
- CopyMem( (VOID *)DestinationPixel32bit, (CONST VOID *)SourcePixel32bit, SizeIn32Bits);
- }
-
- // Free up the allocated memory
- FreePool((VOID *) PixelBuffer32bit);
-
- break;
-
-
- case LCD_BITS_PER_PIXEL_16_555:
- case LCD_BITS_PER_PIXEL_16_565:
- case LCD_BITS_PER_PIXEL_12_444:
- // Allocate a temporary buffer
- PixelBuffer16bit = (UINT16 *) AllocatePool((Height * Width) * sizeof(UINT16));
-
- if (PixelBuffer16bit == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto EXIT;
- }
-
- // Access each pixel inside the source area of the Video Memory and copy it to the temp buffer
-
- SizeIn16Bits = Width * 2;
-
- for (SourcePixelY = SourceY, DestinationPixel16bit = PixelBuffer16bit;
- SourcePixelY < SourceY + Height;
- SourcePixelY++, DestinationPixel16bit += Width)
- {
- // Calculate the source address:
- SourcePixel16bit = (UINT16 *)FrameBufferBase + SourcePixelY * HorizontalResolution + SourceX;
-
- // Copy the entire line Y from Video to the temp buffer
- CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
- }
-
- // Copy from the temp buffer into the destination area of the Video Memory
-
- for (DestinationPixelY = DestinationY, SourcePixel16bit = PixelBuffer16bit;
- DestinationPixelY < DestinationY + Height;
- DestinationPixelY++, SourcePixel16bit += Width)
- {
- // Calculate the target address:
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + (DestinationPixelY * HorizontalResolution + DestinationX);
-
- // Copy the entire line Y from the temp buffer to Video
- CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
- }
-
- // Free the allocated memory
- FreePool((VOID *) PixelBuffer16bit);
-
- break;
-
-
- case LCD_BITS_PER_PIXEL_8:
- case LCD_BITS_PER_PIXEL_4:
- case LCD_BITS_PER_PIXEL_2:
- case LCD_BITS_PER_PIXEL_1:
- default:
- // Can't handle this case
- DEBUG((DEBUG_ERROR, "ArmVeGraphics_Blt: EfiBltVideoToVideo: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- // break;
-
- }
-
-EXIT:
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltVideoFill (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_PIXEL_BITMASK* PixelInformation;
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- LCD_BPP BitsPerPixel;
- VOID *FrameBufferBase;
- VOID *DestinationAddr;
- UINT16 *DestinationPixel16bit;
- UINT16 Pixel16bit;
- UINT32 DestinationPixelX;
- UINT32 DestinationLine;
- UINTN WidthInBytes;
-
- Status = EFI_SUCCESS;
- PixelInformation = &This->Mode->Info->PixelInformation;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
-
- LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
-
- switch (BitsPerPixel) {
- case LCD_BITS_PER_PIXEL_24:
- WidthInBytes = Width * 4;
-
- // Copy the SourcePixel into every pixel inside the target rectangle
- for (DestinationLine = DestinationY;
- DestinationLine < DestinationY + Height;
- DestinationLine++)
- {
- // Calculate the target address using 32bit pointer arithmetic:
- DestinationAddr = (VOID *)((UINT32 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
-
- // Fill the entire line
- SetMemN( DestinationAddr, WidthInBytes, *((UINTN *)EfiSourcePixel));
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_555:
- // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
- Pixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 7) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green << 2) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
-// | ( 0 & PixelInformation->ReservedMask )
- );
-
- // Copy the SourcePixel into every pixel inside the target rectangle
- for (DestinationLine = DestinationY;
- DestinationLine < DestinationY + Height;
- DestinationLine++)
- {
- for (DestinationPixelX = DestinationX;
- DestinationPixelX < DestinationX + Width;
- DestinationPixelX++)
- {
- // Calculate the target address:
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- *DestinationPixel16bit = Pixel16bit;
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_565:
- // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
- Pixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
- );
-
- // Copy the SourcePixel into every pixel inside the target rectangle
- for (DestinationLine = DestinationY;
- DestinationLine < DestinationY + Height;
- DestinationLine++)
- {
- for (DestinationPixelX = DestinationX;
- DestinationPixelX < DestinationX + Width;
- DestinationPixelX++)
- {
- // Calculate the target address:
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- *DestinationPixel16bit = Pixel16bit;
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_12_444:
- // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
- Pixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red >> 4) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green ) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue << 4) & PixelInformation->BlueMask )
- );
-
- // Copy the SourcePixel into every pixel inside the target rectangle
- for (DestinationLine = DestinationY;
- DestinationLine < DestinationY + Height;
- DestinationLine++)
- {
- for (DestinationPixelX = DestinationX;
- DestinationPixelX < DestinationX + Width;
- DestinationPixelX++)
- {
- // Calculate the target address:
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- *DestinationPixel16bit = Pixel16bit;
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_8:
- case LCD_BITS_PER_PIXEL_4:
- case LCD_BITS_PER_PIXEL_2:
- case LCD_BITS_PER_PIXEL_1:
- default:
- // Can't handle this case
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: EfiBltVideoFill: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
- Status = EFI_INVALID_PARAMETER;
- break;
- }
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltVideoToBltBuffer (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- LCD_BPP BitsPerPixel;
- EFI_PIXEL_BITMASK *PixelInformation;
- EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiDestinationPixel;
- VOID *FrameBufferBase;
- VOID *SourceAddr;
- VOID *DestinationAddr;
- UINT16 *SourcePixel16bit;
- UINT16 Pixel16bit;
- UINT32 SourcePixelX;
- UINT32 SourceLine;
- UINT32 DestinationPixelX;
- UINT32 DestinationLine;
- UINT32 BltBufferHorizontalResolution;
- UINTN WidthInBytes;
-
- Status = EFI_SUCCESS;
- PixelInformation = &This->Mode->Info->PixelInformation;
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
- // Delta is not zero and it is different from the width.
- // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
- BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
- } else {
- BltBufferHorizontalResolution = Width;
- }
-
- LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
-
- switch (BitsPerPixel) {
- case LCD_BITS_PER_PIXEL_24:
- WidthInBytes = Width * 4;
-
- // Access each line inside the Video Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++)
- {
- // Calculate the source and target addresses using 32bit pointer arithmetic:
- SourceAddr = (VOID *)((UINT32 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
- DestinationAddr = (VOID *)((UINT32 *)BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationX);
-
- // Copy the entire line
- CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_555:
- // Access each pixel inside the Video Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++)
- {
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
- EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
-
- // Snapshot the pixel from the video buffer once, to speed up the operation.
- // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
- Pixel16bit = *SourcePixel16bit;
-
- // Copy the pixel into the new target
- EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 7 );
- EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) >> 2);
- EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 3 );
- // EfiDestinationPixel->Reserved = (UINT8) 0;
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_565:
- // Access each pixel inside the Video Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++)
- {
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
- EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
-
- // Snapshot the pixel from the video buffer once, to speed up the operation.
- // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
- Pixel16bit = *SourcePixel16bit;
-
- // Copy the pixel into the new target
- // There is no info for the Reserved byte, so we set it to zero
- EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 8 );
- EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) >> 3);
- EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 3 );
- // EfiDestinationPixel->Reserved = (UINT8) 0;
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_12_444:
- // Access each pixel inside the Video Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++)
- {
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
- EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
-
- // Snapshot the pixel from the video buffer once, to speed up the operation.
- // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
- Pixel16bit = *SourcePixel16bit;
-
- // Copy the pixel into the new target
- EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 4 );
- EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) );
- EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 4 );
- // EfiDestinationPixel->Reserved = (UINT8) 0;
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_8:
- case LCD_BITS_PER_PIXEL_4:
- case LCD_BITS_PER_PIXEL_2:
- case LCD_BITS_PER_PIXEL_1:
- default:
- // Can't handle this case
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: EfiBltVideoToBltBuffer: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
- Status = EFI_INVALID_PARAMETER;
- break;
- }
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltBufferToVideo (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- LCD_BPP BitsPerPixel;
- EFI_PIXEL_BITMASK *PixelInformation;
- EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel;
- VOID *FrameBufferBase;
- VOID *SourceAddr;
- VOID *DestinationAddr;
- UINT16 *DestinationPixel16bit;
- UINT32 SourcePixelX;
- UINT32 SourceLine;
- UINT32 DestinationPixelX;
- UINT32 DestinationLine;
- UINT32 BltBufferHorizontalResolution;
- UINTN WidthInBytes;
-
- Status = EFI_SUCCESS;
- PixelInformation = &This->Mode->Info->PixelInformation;
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
- // Delta is not zero and it is different from the width.
- // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
- BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
- } else {
- BltBufferHorizontalResolution = Width;
- }
-
- LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
-
- switch (BitsPerPixel) {
- case LCD_BITS_PER_PIXEL_24:
- WidthInBytes = Width * 4;
-
- // Access each pixel inside the BltBuffer Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++)
- {
- // Calculate the source and target addresses using 32bit pointer arithmetic:
- SourceAddr = (VOID *)((UINT32 *)BltBuffer + SourceLine * BltBufferHorizontalResolution + SourceX );
- DestinationAddr = (VOID *)((UINT32 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
-
- // Copy the entire row Y
- CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_555:
- // Access each pixel inside the BltBuffer Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++) {
-
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- // Only the most significant bits will be copied across:
- // To convert from 8 bits to 5 bits per pixel we throw away the 3 least significant bits
- *DestinationPixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 7) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green << 2) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
- // | ( 0 & PixelInformation->ReservedMask )
- );
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_16_565:
- // Access each pixel inside the BltBuffer Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++) {
-
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- // Only the most significant bits will be copied across:
- // To convert from 8 bits to 5 or 6 bits per pixel we throw away the 3 or 2 least significant bits
- // There is no room for the Reserved byte so we ignore that completely
- *DestinationPixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
- );
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_12_444:
- // Access each pixel inside the BltBuffer Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++) {
-
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- // Only the most significant bits will be copied across:
- // To convert from 8 bits to 5 bits per pixel we throw away the 3 least significant bits
- *DestinationPixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 4) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green ) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 4) & PixelInformation->BlueMask )
- // | ( 0 & PixelInformation->ReservedMask )
- );
- }
- }
- break;
-
- case LCD_BITS_PER_PIXEL_8:
- case LCD_BITS_PER_PIXEL_4:
- case LCD_BITS_PER_PIXEL_2:
- case LCD_BITS_PER_PIXEL_1:
- default:
- // Can't handle this case
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: EfiBltBufferToVideo: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
- Status = EFI_INVALID_PARAMETER;
- break;
- }
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltVideoToVideo (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- LCD_BPP BitsPerPixel;
- VOID *FrameBufferBase;
-
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- //
- // BltVideo to BltVideo:
- //
- // Source is the Video Memory,
- // Destination is the Video Memory
-
- LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- // The UEFI spec currently states:
- // "There is no limitation on the overlapping of the source and destination rectangles"
- // Therefore, we must be careful to avoid overwriting the source data
- if( SourceY == DestinationY ) {
- // Copying within the same height, e.g. horizontal shift
- if( SourceX == DestinationX ) {
- // Nothing to do
- Status = EFI_SUCCESS;
- } else if( ((SourceX>DestinationX)?(SourceX - DestinationX):(DestinationX - SourceX)) < Width ) {
- // There is overlap
- Status = VideoCopyHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
- } else {
- // No overlap
- Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
- }
- } else {
- // Copying from different heights
- Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
- }
-
- return Status;
-}
-
-/***************************************
- * GraphicsOutput Protocol function, mapping to
- * EFI_GRAPHICS_OUTPUT_PROTOCOL.Blt
- *
- * PRESUMES: 1 pixel = 4 bytes (32bits)
- * ***************************************/
-EFI_STATUS
-EFIAPI
-LcdGraphicsBlt (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- UINT32 VerticalResolution;
- LCD_INSTANCE* Instance;
-
- Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
-
- // Setup the hardware if not already done
- if (!mDisplayInitialized) {
- Status = InitializeDisplay (Instance);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- VerticalResolution = This->Mode->Info->VerticalResolution;
-
- DEBUG((DEBUG_INFO, "LcdGraphicsBlt (BltOperation:%d,DestX:%d,DestY:%d,Width:%d,Height:%d) res(%d,%d)\n",
- BltOperation,DestinationX,DestinationY,Width,Height,HorizontalResolution,VerticalResolution));
-
- // Check we have reasonable parameters
- if (Width == 0 || Height == 0) {
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: ERROR - Invalid dimension: Zero size area.\n" ));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }
-
- if ((BltOperation == EfiBltVideoFill) || (BltOperation == EfiBltBufferToVideo) || (BltOperation == EfiBltVideoToBltBuffer)) {
- ASSERT( BltBuffer != NULL);
- }
-
- /*if ((DestinationX >= HorizontalResolution) || (DestinationY >= VerticalResolution)) {
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: ERROR - Invalid destination.\n" ));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }*/
-
- // If we are reading data out of the video buffer, check that the source area is within the display limits
- if ((BltOperation == EfiBltVideoToBltBuffer) || (BltOperation == EfiBltVideoToVideo)) {
- if ((SourceY + Height > VerticalResolution) || (SourceX + Width > HorizontalResolution)) {
- DEBUG((DEBUG_INFO, "LcdGraphicsBlt: ERROR - Invalid source resolution.\n" ));
- DEBUG((DEBUG_INFO, " - SourceY=%d + Height=%d > VerticalResolution=%d.\n", SourceY, Height, VerticalResolution ));
- DEBUG((DEBUG_INFO, " - SourceX=%d + Width=%d > HorizontalResolution=%d.\n", SourceX, Width, HorizontalResolution ));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }
- }
-
- // If we are writing data into the video buffer, that the destination area is within the display limits
- if ((BltOperation == EfiBltVideoFill) || (BltOperation == EfiBltBufferToVideo) || (BltOperation == EfiBltVideoToVideo)) {
- if ((DestinationY + Height > VerticalResolution) || (DestinationX + Width > HorizontalResolution)) {
- DEBUG((DEBUG_INFO, "LcdGraphicsBlt: ERROR - Invalid destination resolution.\n" ));
- DEBUG((DEBUG_INFO, " - DestinationY=%d + Height=%d > VerticalResolution=%d.\n", DestinationY, Height, VerticalResolution ));
- DEBUG((DEBUG_INFO, " - DestinationX=%d + Width=%d > HorizontalResolution=%d.\n", DestinationX, Width, HorizontalResolution ));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }
- }
-
- //
- // Perform the Block Transfer Operation
- //
-
- switch (BltOperation) {
- case EfiBltVideoFill:
- Status = BltVideoFill (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiBltVideoToBltBuffer:
- Status = BltVideoToBltBuffer (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiBltBufferToVideo:
- Status = BltBufferToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiBltVideoToVideo:
- Status = BltVideoToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiGraphicsOutputBltOperationMax:
- default:
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: Invalid Operation\n"));
- Status = EFI_INVALID_PARAMETER;
- break;
- }
-
-EXIT:
- return Status;
-}
+/** @file
+
+ Copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+ **/
+
+#include <PiDxe.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/MemoryAllocationLib.h>
+
+#include <Guid/GlobalVariable.h>
+
+#include "LcdGraphicsOutputDxe.h"
+
+extern BOOLEAN mDisplayInitialized;
+
+//
+// Function Definitions
+//
+
+STATIC
+EFI_STATUS
+VideoCopyNoHorizontalOverlap (
+ IN UINTN BitsPerPixel,
+ IN volatile VOID *FrameBufferBase,
+ IN UINT32 HorizontalResolution,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height
+)
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINTN SourceLine;
+ UINTN DestinationLine;
+ UINTN WidthInBytes;
+ UINTN LineCount;
+ INTN Step;
+ VOID *SourceAddr;
+ VOID *DestinationAddr;
+
+ if( DestinationY <= SourceY ) {
+ // scrolling up (or horizontally but without overlap)
+ SourceLine = SourceY;
+ DestinationLine = DestinationY;
+ Step = 1;
+ } else {
+ // scrolling down
+ SourceLine = SourceY + Height;
+ DestinationLine = DestinationY + Height;
+ Step = -1;
+ }
+
+ switch (BitsPerPixel) {
+
+ case LCD_BITS_PER_PIXEL_24:
+
+ WidthInBytes = Width * 4;
+
+ for( LineCount = 0; LineCount < Height; LineCount++ ) {
+ // Update the start addresses of source & destination using 32bit pointer arithmetic
+ SourceAddr = (VOID *)((UINT32 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
+ DestinationAddr = (VOID *)((UINT32 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
+
+ // Copy the entire line Y from video ram to the temp buffer
+ CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
+
+ // Update the line numbers
+ SourceLine += Step;
+ DestinationLine += Step;
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_555:
+ case LCD_BITS_PER_PIXEL_16_565:
+ case LCD_BITS_PER_PIXEL_12_444:
+
+ WidthInBytes = Width * 2;
+
+ for( LineCount = 0; LineCount < Height; LineCount++ ) {
+ // Update the start addresses of source & destination using 16bit pointer arithmetic
+ SourceAddr = (VOID *)((UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
+ DestinationAddr = (VOID *)((UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
+
+ // Copy the entire line Y from video ram to the temp buffer
+ CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
+
+ // Update the line numbers
+ SourceLine += Step;
+ DestinationLine += Step;
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_8:
+ case LCD_BITS_PER_PIXEL_4:
+ case LCD_BITS_PER_PIXEL_2:
+ case LCD_BITS_PER_PIXEL_1:
+ default:
+ // Can't handle this case
+ DEBUG((DEBUG_ERROR, "ArmVeGraphics_Blt: EfiBltVideoToVideo: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ // break;
+
+ }
+
+ EXIT:
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+VideoCopyHorizontalOverlap (
+ IN UINTN BitsPerPixel,
+ IN volatile VOID *FrameBufferBase,
+ UINT32 HorizontalResolution,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height
+)
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ UINT32 *PixelBuffer32bit;
+ UINT32 *SourcePixel32bit;
+ UINT32 *DestinationPixel32bit;
+
+ UINT16 *PixelBuffer16bit;
+ UINT16 *SourcePixel16bit;
+ UINT16 *DestinationPixel16bit;
+
+ UINT32 SourcePixelY;
+ UINT32 DestinationPixelY;
+ UINTN SizeIn32Bits;
+ UINTN SizeIn16Bits;
+
+ switch (BitsPerPixel) {
+
+ case LCD_BITS_PER_PIXEL_24:
+ // Allocate a temporary buffer
+
+ PixelBuffer32bit = (UINT32 *) AllocatePool((Height * Width) * sizeof(UINT32));
+
+ if (PixelBuffer32bit == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto EXIT;
+ }
+
+ SizeIn32Bits = Width * 4;
+
+ // Copy from the video ram (source region) to a temp buffer
+ for (SourcePixelY = SourceY, DestinationPixel32bit = PixelBuffer32bit;
+ SourcePixelY < SourceY + Height;
+ SourcePixelY++, DestinationPixel32bit += Width)
+ {
+ // Update the start address of line Y (source)
+ SourcePixel32bit = (UINT32 *)FrameBufferBase + SourcePixelY * HorizontalResolution + SourceX;
+
+ // Copy the entire line Y from video ram to the temp buffer
+ CopyMem( (VOID *)DestinationPixel32bit, (CONST VOID *)SourcePixel32bit, SizeIn32Bits);
+ }
+
+ // Copy from the temp buffer to the video ram (destination region)
+ for (DestinationPixelY = DestinationY, SourcePixel32bit = PixelBuffer32bit;
+ DestinationPixelY < DestinationY + Height;
+ DestinationPixelY++, SourcePixel32bit += Width)
+ {
+ // Update the start address of line Y (target)
+ DestinationPixel32bit = (UINT32 *)FrameBufferBase + DestinationPixelY * HorizontalResolution + DestinationX;
+
+ // Copy the entire line Y from the temp buffer to video ram
+ CopyMem( (VOID *)DestinationPixel32bit, (CONST VOID *)SourcePixel32bit, SizeIn32Bits);
+ }
+
+ // Free up the allocated memory
+ FreePool((VOID *) PixelBuffer32bit);
+
+ break;
+
+
+ case LCD_BITS_PER_PIXEL_16_555:
+ case LCD_BITS_PER_PIXEL_16_565:
+ case LCD_BITS_PER_PIXEL_12_444:
+ // Allocate a temporary buffer
+ PixelBuffer16bit = (UINT16 *) AllocatePool((Height * Width) * sizeof(UINT16));
+
+ if (PixelBuffer16bit == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto EXIT;
+ }
+
+ // Access each pixel inside the source area of the Video Memory and copy it to the temp buffer
+
+ SizeIn16Bits = Width * 2;
+
+ for (SourcePixelY = SourceY, DestinationPixel16bit = PixelBuffer16bit;
+ SourcePixelY < SourceY + Height;
+ SourcePixelY++, DestinationPixel16bit += Width)
+ {
+ // Calculate the source address:
+ SourcePixel16bit = (UINT16 *)FrameBufferBase + SourcePixelY * HorizontalResolution + SourceX;
+
+ // Copy the entire line Y from Video to the temp buffer
+ CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
+ }
+
+ // Copy from the temp buffer into the destination area of the Video Memory
+
+ for (DestinationPixelY = DestinationY, SourcePixel16bit = PixelBuffer16bit;
+ DestinationPixelY < DestinationY + Height;
+ DestinationPixelY++, SourcePixel16bit += Width)
+ {
+ // Calculate the target address:
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + (DestinationPixelY * HorizontalResolution + DestinationX);
+
+ // Copy the entire line Y from the temp buffer to Video
+ CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
+ }
+
+ // Free the allocated memory
+ FreePool((VOID *) PixelBuffer16bit);
+
+ break;
+
+
+ case LCD_BITS_PER_PIXEL_8:
+ case LCD_BITS_PER_PIXEL_4:
+ case LCD_BITS_PER_PIXEL_2:
+ case LCD_BITS_PER_PIXEL_1:
+ default:
+ // Can't handle this case
+ DEBUG((DEBUG_ERROR, "ArmVeGraphics_Blt: EfiBltVideoToVideo: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ // break;
+
+ }
+
+EXIT:
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltVideoFill (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_PIXEL_BITMASK* PixelInformation;
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ LCD_BPP BitsPerPixel;
+ VOID *FrameBufferBase;
+ VOID *DestinationAddr;
+ UINT16 *DestinationPixel16bit;
+ UINT16 Pixel16bit;
+ UINT32 DestinationPixelX;
+ UINT32 DestinationLine;
+ UINTN WidthInBytes;
+
+ Status = EFI_SUCCESS;
+ PixelInformation = &This->Mode->Info->PixelInformation;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+
+ LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
+
+ switch (BitsPerPixel) {
+ case LCD_BITS_PER_PIXEL_24:
+ WidthInBytes = Width * 4;
+
+ // Copy the SourcePixel into every pixel inside the target rectangle
+ for (DestinationLine = DestinationY;
+ DestinationLine < DestinationY + Height;
+ DestinationLine++)
+ {
+ // Calculate the target address using 32bit pointer arithmetic:
+ DestinationAddr = (VOID *)((UINT32 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
+
+ // Fill the entire line
+ SetMemN( DestinationAddr, WidthInBytes, *((UINT32 *)EfiSourcePixel));
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_555:
+ // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
+ Pixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 7) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green << 2) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
+// | ( 0 & PixelInformation->ReservedMask )
+ );
+
+ // Copy the SourcePixel into every pixel inside the target rectangle
+ for (DestinationLine = DestinationY;
+ DestinationLine < DestinationY + Height;
+ DestinationLine++)
+ {
+ for (DestinationPixelX = DestinationX;
+ DestinationPixelX < DestinationX + Width;
+ DestinationPixelX++)
+ {
+ // Calculate the target address:
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ *DestinationPixel16bit = Pixel16bit;
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_565:
+ // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
+ Pixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
+ );
+
+ // Copy the SourcePixel into every pixel inside the target rectangle
+ for (DestinationLine = DestinationY;
+ DestinationLine < DestinationY + Height;
+ DestinationLine++)
+ {
+ for (DestinationPixelX = DestinationX;
+ DestinationPixelX < DestinationX + Width;
+ DestinationPixelX++)
+ {
+ // Calculate the target address:
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ *DestinationPixel16bit = Pixel16bit;
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_12_444:
+ // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
+ Pixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red >> 4) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green ) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue << 4) & PixelInformation->BlueMask )
+ );
+
+ // Copy the SourcePixel into every pixel inside the target rectangle
+ for (DestinationLine = DestinationY;
+ DestinationLine < DestinationY + Height;
+ DestinationLine++)
+ {
+ for (DestinationPixelX = DestinationX;
+ DestinationPixelX < DestinationX + Width;
+ DestinationPixelX++)
+ {
+ // Calculate the target address:
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ *DestinationPixel16bit = Pixel16bit;
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_8:
+ case LCD_BITS_PER_PIXEL_4:
+ case LCD_BITS_PER_PIXEL_2:
+ case LCD_BITS_PER_PIXEL_1:
+ default:
+ // Can't handle this case
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: EfiBltVideoFill: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ }
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltVideoToBltBuffer (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ LCD_BPP BitsPerPixel;
+ EFI_PIXEL_BITMASK *PixelInformation;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiDestinationPixel;
+ VOID *FrameBufferBase;
+ VOID *SourceAddr;
+ VOID *DestinationAddr;
+ UINT16 *SourcePixel16bit;
+ UINT16 Pixel16bit;
+ UINT32 SourcePixelX;
+ UINT32 SourceLine;
+ UINT32 DestinationPixelX;
+ UINT32 DestinationLine;
+ UINT32 BltBufferHorizontalResolution;
+ UINTN WidthInBytes;
+
+ Status = EFI_SUCCESS;
+ PixelInformation = &This->Mode->Info->PixelInformation;
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
+ // Delta is not zero and it is different from the width.
+ // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
+ BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
+ } else {
+ BltBufferHorizontalResolution = Width;
+ }
+
+ LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
+
+ switch (BitsPerPixel) {
+ case LCD_BITS_PER_PIXEL_24:
+ WidthInBytes = Width * 4;
+
+ // Access each line inside the Video Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++)
+ {
+ // Calculate the source and target addresses using 32bit pointer arithmetic:
+ SourceAddr = (VOID *)((UINT32 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
+ DestinationAddr = (VOID *)((UINT32 *)BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationX);
+
+ // Copy the entire line
+ CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_555:
+ // Access each pixel inside the Video Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++)
+ {
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
+ EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
+
+ // Snapshot the pixel from the video buffer once, to speed up the operation.
+ // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
+ Pixel16bit = *SourcePixel16bit;
+
+ // Copy the pixel into the new target
+ EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 7 );
+ EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) >> 2);
+ EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 3 );
+ // EfiDestinationPixel->Reserved = (UINT8) 0;
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_565:
+ // Access each pixel inside the Video Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++)
+ {
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
+ EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
+
+ // Snapshot the pixel from the video buffer once, to speed up the operation.
+ // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
+ Pixel16bit = *SourcePixel16bit;
+
+ // Copy the pixel into the new target
+ // There is no info for the Reserved byte, so we set it to zero
+ EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 8 );
+ EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) >> 3);
+ EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 3 );
+ // EfiDestinationPixel->Reserved = (UINT8) 0;
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_12_444:
+ // Access each pixel inside the Video Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++)
+ {
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
+ EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
+
+ // Snapshot the pixel from the video buffer once, to speed up the operation.
+ // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
+ Pixel16bit = *SourcePixel16bit;
+
+ // Copy the pixel into the new target
+ EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 4 );
+ EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) );
+ EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 4 );
+ // EfiDestinationPixel->Reserved = (UINT8) 0;
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_8:
+ case LCD_BITS_PER_PIXEL_4:
+ case LCD_BITS_PER_PIXEL_2:
+ case LCD_BITS_PER_PIXEL_1:
+ default:
+ // Can't handle this case
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: EfiBltVideoToBltBuffer: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ }
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltBufferToVideo (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ LCD_BPP BitsPerPixel;
+ EFI_PIXEL_BITMASK *PixelInformation;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel;
+ VOID *FrameBufferBase;
+ VOID *SourceAddr;
+ VOID *DestinationAddr;
+ UINT16 *DestinationPixel16bit;
+ UINT32 SourcePixelX;
+ UINT32 SourceLine;
+ UINT32 DestinationPixelX;
+ UINT32 DestinationLine;
+ UINT32 BltBufferHorizontalResolution;
+ UINTN WidthInBytes;
+
+ Status = EFI_SUCCESS;
+ PixelInformation = &This->Mode->Info->PixelInformation;
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
+ // Delta is not zero and it is different from the width.
+ // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
+ BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
+ } else {
+ BltBufferHorizontalResolution = Width;
+ }
+
+ LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
+
+ switch (BitsPerPixel) {
+ case LCD_BITS_PER_PIXEL_24:
+ WidthInBytes = Width * 4;
+
+ // Access each pixel inside the BltBuffer Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++)
+ {
+ // Calculate the source and target addresses using 32bit pointer arithmetic:
+ SourceAddr = (VOID *)((UINT32 *)BltBuffer + SourceLine * BltBufferHorizontalResolution + SourceX );
+ DestinationAddr = (VOID *)((UINT32 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
+
+ // Copy the entire row Y
+ CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_555:
+ // Access each pixel inside the BltBuffer Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++) {
+
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ // Only the most significant bits will be copied across:
+ // To convert from 8 bits to 5 bits per pixel we throw away the 3 least significant bits
+ *DestinationPixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 7) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green << 2) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
+ // | ( 0 & PixelInformation->ReservedMask )
+ );
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_16_565:
+ // Access each pixel inside the BltBuffer Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++) {
+
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ // Only the most significant bits will be copied across:
+ // To convert from 8 bits to 5 or 6 bits per pixel we throw away the 3 or 2 least significant bits
+ // There is no room for the Reserved byte so we ignore that completely
+ *DestinationPixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
+ );
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_12_444:
+ // Access each pixel inside the BltBuffer Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++) {
+
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ // Only the most significant bits will be copied across:
+ // To convert from 8 bits to 5 bits per pixel we throw away the 3 least significant bits
+ *DestinationPixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 4) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green ) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 4) & PixelInformation->BlueMask )
+ // | ( 0 & PixelInformation->ReservedMask )
+ );
+ }
+ }
+ break;
+
+ case LCD_BITS_PER_PIXEL_8:
+ case LCD_BITS_PER_PIXEL_4:
+ case LCD_BITS_PER_PIXEL_2:
+ case LCD_BITS_PER_PIXEL_1:
+ default:
+ // Can't handle this case
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: EfiBltBufferToVideo: INVALID Number of Bits Per Pixel: %d\n", BitsPerPixel));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ }
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltVideoToVideo (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ LCD_BPP BitsPerPixel;
+ VOID *FrameBufferBase;
+
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ //
+ // BltVideo to BltVideo:
+ //
+ // Source is the Video Memory,
+ // Destination is the Video Memory
+
+ LcdPlatformGetBpp (This->Mode->Mode,&BitsPerPixel);
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ // The UEFI spec currently states:
+ // "There is no limitation on the overlapping of the source and destination rectangles"
+ // Therefore, we must be careful to avoid overwriting the source data
+ if( SourceY == DestinationY ) {
+ // Copying within the same height, e.g. horizontal shift
+ if( SourceX == DestinationX ) {
+ // Nothing to do
+ Status = EFI_SUCCESS;
+ } else if( ((SourceX>DestinationX)?(SourceX - DestinationX):(DestinationX - SourceX)) < Width ) {
+ // There is overlap
+ Status = VideoCopyHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
+ } else {
+ // No overlap
+ Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
+ }
+ } else {
+ // Copying from different heights
+ Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
+ }
+
+ return Status;
+}
+
+/***************************************
+ * GraphicsOutput Protocol function, mapping to
+ * EFI_GRAPHICS_OUTPUT_PROTOCOL.Blt
+ *
+ * PRESUMES: 1 pixel = 4 bytes (32bits)
+ * ***************************************/
+EFI_STATUS
+EFIAPI
+LcdGraphicsBlt (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ UINT32 VerticalResolution;
+ LCD_INSTANCE* Instance;
+
+ Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
+
+ // Setup the hardware if not already done
+ if (!mDisplayInitialized) {
+ Status = InitializeDisplay (Instance);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ VerticalResolution = This->Mode->Info->VerticalResolution;
+
+ DEBUG((DEBUG_INFO, "LcdGraphicsBlt (BltOperation:%d,DestX:%d,DestY:%d,Width:%d,Height:%d) res(%d,%d)\n",
+ BltOperation,DestinationX,DestinationY,Width,Height,HorizontalResolution,VerticalResolution));
+
+ // Check we have reasonable parameters
+ if (Width == 0 || Height == 0) {
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: ERROR - Invalid dimension: Zero size area.\n" ));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }
+
+ if ((BltOperation == EfiBltVideoFill) || (BltOperation == EfiBltBufferToVideo) || (BltOperation == EfiBltVideoToBltBuffer)) {
+ ASSERT( BltBuffer != NULL);
+ }
+
+ /*if ((DestinationX >= HorizontalResolution) || (DestinationY >= VerticalResolution)) {
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: ERROR - Invalid destination.\n" ));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }*/
+
+ // If we are reading data out of the video buffer, check that the source area is within the display limits
+ if ((BltOperation == EfiBltVideoToBltBuffer) || (BltOperation == EfiBltVideoToVideo)) {
+ if ((SourceY + Height > VerticalResolution) || (SourceX + Width > HorizontalResolution)) {
+ DEBUG((DEBUG_INFO, "LcdGraphicsBlt: ERROR - Invalid source resolution.\n" ));
+ DEBUG((DEBUG_INFO, " - SourceY=%d + Height=%d > VerticalResolution=%d.\n", SourceY, Height, VerticalResolution ));
+ DEBUG((DEBUG_INFO, " - SourceX=%d + Width=%d > HorizontalResolution=%d.\n", SourceX, Width, HorizontalResolution ));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }
+ }
+
+ // If we are writing data into the video buffer, that the destination area is within the display limits
+ if ((BltOperation == EfiBltVideoFill) || (BltOperation == EfiBltBufferToVideo) || (BltOperation == EfiBltVideoToVideo)) {
+ if ((DestinationY + Height > VerticalResolution) || (DestinationX + Width > HorizontalResolution)) {
+ DEBUG((DEBUG_INFO, "LcdGraphicsBlt: ERROR - Invalid destination resolution.\n" ));
+ DEBUG((DEBUG_INFO, " - DestinationY=%d + Height=%d > VerticalResolution=%d.\n", DestinationY, Height, VerticalResolution ));
+ DEBUG((DEBUG_INFO, " - DestinationX=%d + Width=%d > HorizontalResolution=%d.\n", DestinationX, Width, HorizontalResolution ));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }
+ }
+
+ //
+ // Perform the Block Transfer Operation
+ //
+
+ switch (BltOperation) {
+ case EfiBltVideoFill:
+ Status = BltVideoFill (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiBltVideoToBltBuffer:
+ Status = BltVideoToBltBuffer (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiBltBufferToVideo:
+ Status = BltBufferToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiBltVideoToVideo:
+ Status = BltVideoToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiGraphicsOutputBltOperationMax:
+ default:
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: Invalid Operation\n"));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ }
+
+EXIT:
+ return Status;
+}
diff --git a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c
index 229d2a6aa..34a56b3d8 100644
--- a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c
+++ b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c
@@ -1,376 +1,376 @@
-/** @file
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
- **/
-
-#include <PiDxe.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/MemoryAllocationLib.h>
-
-#include <Guid/GlobalVariable.h>
-
-#include "LcdGraphicsOutputDxe.h"
-
-/**********************************************************************
- *
- * This file implements the Graphics Output protocol on ArmVersatileExpress
- * using the Lcd controller
- *
- **********************************************************************/
-
-//
-// Global variables
-//
-
-BOOLEAN mDisplayInitialized = FALSE;
-
-LCD_INSTANCE mLcdTemplate = {
- LCD_INSTANCE_SIGNATURE,
- NULL, // Handle
- { // ModeInfo
- 0, // Version
- 0, // HorizontalResolution
- 0, // VerticalResolution
- PixelBltOnly, // PixelFormat
- 0, // PixelInformation
- 0, // PixelsPerScanLine
- },
- {
- 0, // MaxMode;
- 0, // Mode;
- NULL, // Info;
- 0, // SizeOfInfo;
- 0, // FrameBufferBase;
- 0 // FrameBufferSize;
- },
- { // Gop
- LcdGraphicsQueryMode, // QueryMode
- LcdGraphicsSetMode, // SetMode
- LcdGraphicsBlt, // Blt
- NULL // *Mode
- },
- { // DevicePath
- {
- {
- HARDWARE_DEVICE_PATH, HW_VENDOR_DP,
- (UINT8) (sizeof(VENDOR_DEVICE_PATH)),
- (UINT8) ((sizeof(VENDOR_DEVICE_PATH)) >> 8),
- },
- // Hardware Device Path for Lcd
- EFI_CALLER_ID_GUID // Use the driver's GUID
- },
-
- {
- END_DEVICE_PATH_TYPE,
- END_ENTIRE_DEVICE_PATH_SUBTYPE,
- sizeof(EFI_DEVICE_PATH_PROTOCOL),
- 0
- }
- },
- (EFI_EVENT) NULL // ExitBootServicesEvent
-};
-
-EFI_STATUS
-LcdInstanceContructor (
- OUT LCD_INSTANCE** NewInstance
- )
-{
- LCD_INSTANCE* Instance;
-
- Instance = AllocateCopyPool (sizeof(LCD_INSTANCE), &mLcdTemplate);
- if (Instance == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- Instance->Gop.Mode = &Instance->Mode;
- Instance->Gop.Mode->MaxMode = LcdPlatformGetMaxMode ();
- Instance->Mode.Info = &Instance->ModeInfo;
-
- *NewInstance = Instance;
- return EFI_SUCCESS;
-}
-
-//
-// Function Definitions
-//
-
-EFI_STATUS
-InitializeDisplay (
- IN LCD_INSTANCE* Instance
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- EFI_PHYSICAL_ADDRESS VramBaseAddress;
- UINTN VramSize;
-
- Status = LcdPlatformGetVram (&VramBaseAddress, &VramSize);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Setup the LCD
- Status = LcdInitialize (VramBaseAddress);
- if (EFI_ERROR(Status)) {
- goto EXIT_ERROR_LCD_SHUTDOWN;
- }
-
- Status = LcdPlatformInitializeDisplay (Instance->Handle);
- if (EFI_ERROR(Status)) {
- goto EXIT_ERROR_LCD_SHUTDOWN;
- }
-
- // Setup all the relevant mode information
- Instance->Gop.Mode->SizeOfInfo = sizeof(EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
- Instance->Gop.Mode->FrameBufferBase = VramBaseAddress;
- Instance->Gop.Mode->FrameBufferSize = VramSize;
-
- // Set the flag before changing the mode, to avoid infinite loops
- mDisplayInitialized = TRUE;
-
- // All is ok, so don't deal with any errors
- goto EXIT;
-
-EXIT_ERROR_LCD_SHUTDOWN:
- DEBUG((DEBUG_ERROR, "InitializeDisplay: ERROR - Can not initialise the display. Exit Status=%r\n", Status));
- LcdShutdown ();
-
-EXIT:
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsOutputDxeInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- LCD_INSTANCE* Instance;
-
- Status = LcdInstanceContructor (&Instance);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
-
- // Install the Graphics Output Protocol and the Device Path
- Status = gBS->InstallMultipleProtocolInterfaces(
- &Instance->Handle,
- &gEfiGraphicsOutputProtocolGuid, &Instance->Gop,
- &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
- NULL
- );
-
- if (EFI_ERROR(Status)) {
- DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the protocol. Exit Status=%r\n", Status));
- goto EXIT;
- }
-
- // Register for an ExitBootServicesEvent
- // When ExitBootServices starts, this function here will make sure that the graphics driver will shut down properly,
- // i.e. it will free up all allocated memory and perform any necessary hardware re-configuration.
- Status = gBS->CreateEvent (
- EVT_SIGNAL_EXIT_BOOT_SERVICES,
- TPL_NOTIFY,
- LcdGraphicsExitBootServicesEvent, NULL,
- &Instance->ExitBootServicesEvent
- );
-
- if (EFI_ERROR(Status)) {
- DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the ExitBootServicesEvent handler. Exit Status=%r\n", Status));
- goto EXIT_ERROR_UNINSTALL_PROTOCOL;
- }
-
- // To get here, everything must be fine, so just exit
- goto EXIT;
-
-EXIT_ERROR_UNINSTALL_PROTOCOL:
- /* The following function could return an error message,
- * however, to get here something must have gone wrong already,
- * so preserve the original error, i.e. don't change
- * the Status variable, even it fails to uninstall the protocol.
- */
- gBS->UninstallMultipleProtocolInterfaces (
- Instance->Handle,
- &gEfiGraphicsOutputProtocolGuid, &Instance->Gop, // Uninstall Graphics Output protocol
- &gEfiDevicePathProtocolGuid, &Instance->DevicePath, // Uninstall device path
- NULL
- );
-
-EXIT:
- return Status;
-
-}
-
-/***************************************
- * This function should be called
- * on Event: ExitBootServices
- * to free up memory, stop the driver
- * and uninstall the protocols
- ***************************************/
-VOID
-LcdGraphicsExitBootServicesEvent (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- //TODO: Implement me
-}
-
-/***************************************
- * GraphicsOutput Protocol function, mapping to
- * EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode
- ***************************************/
-EFI_STATUS
-EFIAPI
-LcdGraphicsQueryMode (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN UINT32 ModeNumber,
- OUT UINTN *SizeOfInfo,
- OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- LCD_INSTANCE *Instance;
-
- Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
-
- // Setup the hardware if not already done
- if( !mDisplayInitialized ) {
- Status = InitializeDisplay(Instance);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- // Error checking
- if ( (This == NULL) || (Info == NULL) || (SizeOfInfo == NULL) || (ModeNumber >= This->Mode->MaxMode) ) {
- DEBUG((DEBUG_ERROR, "LcdGraphicsQueryMode: ERROR - For mode number %d : Invalid Parameter.\n", ModeNumber ));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }
-
- *Info = AllocatePool (sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION));
- if (*Info == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto EXIT;
- }
-
- *SizeOfInfo = sizeof( EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
-
- Status = LcdPlatformQueryMode (ModeNumber,*Info);
- if (EFI_ERROR(Status)) {
- FreePool(*Info);
- }
-
-EXIT:
- return Status;
-}
-
-/***************************************
- * GraphicsOutput Protocol function, mapping to
- * EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode
- ***************************************/
-EFI_STATUS
-EFIAPI
-LcdGraphicsSetMode (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN UINT32 ModeNumber
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- EFI_GRAPHICS_OUTPUT_BLT_PIXEL FillColour;
- LCD_INSTANCE* Instance;
-
- Instance = LCD_INSTANCE_FROM_GOP_THIS (This);
-
- // Setup the hardware if not already done
- if(!mDisplayInitialized) {
- Status = InitializeDisplay (Instance);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- // Check if this mode is supported
- if( ModeNumber >= This->Mode->MaxMode ) {
- DEBUG((DEBUG_ERROR, "LcdGraphicsSetMode: ERROR - Unsupported mode number %d .\n", ModeNumber ));
- Status = EFI_UNSUPPORTED;
- goto EXIT;
- }
-
- // Set the oscillator frequency to support the new mode
- Status = LcdPlatformSetMode (ModeNumber);
- if (EFI_ERROR(Status)) {
- Status = EFI_DEVICE_ERROR;
- goto EXIT;
- }
-
- // Update the UEFI mode information
- This->Mode->Mode = ModeNumber;
- LcdPlatformQueryMode (ModeNumber,&Instance->ModeInfo);
-
- // Set the hardware to the new mode
- Status = LcdSetMode (ModeNumber);
- if (EFI_ERROR(Status)) {
- Status = EFI_DEVICE_ERROR;
- goto EXIT;
- }
-
- // The UEFI spec requires that we now clear the visible portions of the output display to black.
-
- // Set the fill colour to black
- SetMem (&FillColour, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);
-
- // Fill the entire visible area with the same colour.
- Status = This->Blt (
- This,
- &FillColour,
- EfiBltVideoFill,
- 0,
- 0,
- 0,
- 0,
- This->Mode->Info->HorizontalResolution,
- This->Mode->Info->VerticalResolution,
- 0);
-
-EXIT:
- return Status;
-}
-
-UINTN
-GetBytesPerPixel (
- IN LCD_BPP Bpp
- )
-{
- switch(Bpp) {
- case LCD_BITS_PER_PIXEL_24:
- return 4;
-
- case LCD_BITS_PER_PIXEL_16_565:
- case LCD_BITS_PER_PIXEL_16_555:
- case LCD_BITS_PER_PIXEL_12_444:
- return 2;
-
- case LCD_BITS_PER_PIXEL_8:
- case LCD_BITS_PER_PIXEL_4:
- case LCD_BITS_PER_PIXEL_2:
- case LCD_BITS_PER_PIXEL_1:
- return 1;
-
- default:
- return 0;
- }
-}
+/** @file
+
+ Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+ **/
+
+#include <PiDxe.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/MemoryAllocationLib.h>
+
+#include <Guid/GlobalVariable.h>
+
+#include "LcdGraphicsOutputDxe.h"
+
+/**********************************************************************
+ *
+ * This file implements the Graphics Output protocol on ArmVersatileExpress
+ * using the Lcd controller
+ *
+ **********************************************************************/
+
+//
+// Global variables
+//
+
+BOOLEAN mDisplayInitialized = FALSE;
+
+LCD_INSTANCE mLcdTemplate = {
+ LCD_INSTANCE_SIGNATURE,
+ NULL, // Handle
+ { // ModeInfo
+ 0, // Version
+ 0, // HorizontalResolution
+ 0, // VerticalResolution
+ PixelBltOnly, // PixelFormat
+ 0, // PixelInformation
+ 0, // PixelsPerScanLine
+ },
+ {
+ 0, // MaxMode;
+ 0, // Mode;
+ NULL, // Info;
+ 0, // SizeOfInfo;
+ 0, // FrameBufferBase;
+ 0 // FrameBufferSize;
+ },
+ { // Gop
+ LcdGraphicsQueryMode, // QueryMode
+ LcdGraphicsSetMode, // SetMode
+ LcdGraphicsBlt, // Blt
+ NULL // *Mode
+ },
+ { // DevicePath
+ {
+ {
+ HARDWARE_DEVICE_PATH, HW_VENDOR_DP,
+ (UINT8) (sizeof(VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof(VENDOR_DEVICE_PATH)) >> 8),
+ },
+ // Hardware Device Path for Lcd
+ EFI_CALLER_ID_GUID // Use the driver's GUID
+ },
+
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ sizeof(EFI_DEVICE_PATH_PROTOCOL),
+ 0
+ }
+ },
+ (EFI_EVENT) NULL // ExitBootServicesEvent
+};
+
+EFI_STATUS
+LcdInstanceContructor (
+ OUT LCD_INSTANCE** NewInstance
+ )
+{
+ LCD_INSTANCE* Instance;
+
+ Instance = AllocateCopyPool (sizeof(LCD_INSTANCE), &mLcdTemplate);
+ if (Instance == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Instance->Gop.Mode = &Instance->Mode;
+ Instance->Gop.Mode->MaxMode = LcdPlatformGetMaxMode ();
+ Instance->Mode.Info = &Instance->ModeInfo;
+
+ *NewInstance = Instance;
+ return EFI_SUCCESS;
+}
+
+//
+// Function Definitions
+//
+
+EFI_STATUS
+InitializeDisplay (
+ IN LCD_INSTANCE* Instance
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ EFI_PHYSICAL_ADDRESS VramBaseAddress;
+ UINTN VramSize;
+
+ Status = LcdPlatformGetVram (&VramBaseAddress, &VramSize);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Setup the LCD
+ Status = LcdInitialize (VramBaseAddress);
+ if (EFI_ERROR(Status)) {
+ goto EXIT_ERROR_LCD_SHUTDOWN;
+ }
+
+ Status = LcdPlatformInitializeDisplay (Instance->Handle);
+ if (EFI_ERROR(Status)) {
+ goto EXIT_ERROR_LCD_SHUTDOWN;
+ }
+
+ // Setup all the relevant mode information
+ Instance->Gop.Mode->SizeOfInfo = sizeof(EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
+ Instance->Gop.Mode->FrameBufferBase = VramBaseAddress;
+ Instance->Gop.Mode->FrameBufferSize = VramSize;
+
+ // Set the flag before changing the mode, to avoid infinite loops
+ mDisplayInitialized = TRUE;
+
+ // All is ok, so don't deal with any errors
+ goto EXIT;
+
+EXIT_ERROR_LCD_SHUTDOWN:
+ DEBUG((DEBUG_ERROR, "InitializeDisplay: ERROR - Can not initialise the display. Exit Status=%r\n", Status));
+ LcdShutdown ();
+
+EXIT:
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsOutputDxeInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ LCD_INSTANCE* Instance;
+
+ Status = LcdInstanceContructor (&Instance);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+
+ // Install the Graphics Output Protocol and the Device Path
+ Status = gBS->InstallMultipleProtocolInterfaces(
+ &Instance->Handle,
+ &gEfiGraphicsOutputProtocolGuid, &Instance->Gop,
+ &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
+ NULL
+ );
+
+ if (EFI_ERROR(Status)) {
+ DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the protocol. Exit Status=%r\n", Status));
+ goto EXIT;
+ }
+
+ // Register for an ExitBootServicesEvent
+ // When ExitBootServices starts, this function here will make sure that the graphics driver will shut down properly,
+ // i.e. it will free up all allocated memory and perform any necessary hardware re-configuration.
+ Status = gBS->CreateEvent (
+ EVT_SIGNAL_EXIT_BOOT_SERVICES,
+ TPL_NOTIFY,
+ LcdGraphicsExitBootServicesEvent, NULL,
+ &Instance->ExitBootServicesEvent
+ );
+
+ if (EFI_ERROR(Status)) {
+ DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the ExitBootServicesEvent handler. Exit Status=%r\n", Status));
+ goto EXIT_ERROR_UNINSTALL_PROTOCOL;
+ }
+
+ // To get here, everything must be fine, so just exit
+ goto EXIT;
+
+EXIT_ERROR_UNINSTALL_PROTOCOL:
+ /* The following function could return an error message,
+ * however, to get here something must have gone wrong already,
+ * so preserve the original error, i.e. don't change
+ * the Status variable, even it fails to uninstall the protocol.
+ */
+ gBS->UninstallMultipleProtocolInterfaces (
+ Instance->Handle,
+ &gEfiGraphicsOutputProtocolGuid, &Instance->Gop, // Uninstall Graphics Output protocol
+ &gEfiDevicePathProtocolGuid, &Instance->DevicePath, // Uninstall device path
+ NULL
+ );
+
+EXIT:
+ return Status;
+
+}
+
+/***************************************
+ * This function should be called
+ * on Event: ExitBootServices
+ * to free up memory, stop the driver
+ * and uninstall the protocols
+ ***************************************/
+VOID
+LcdGraphicsExitBootServicesEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ //TODO: Implement me
+}
+
+/***************************************
+ * GraphicsOutput Protocol function, mapping to
+ * EFI_GRAPHICS_OUTPUT_PROTOCOL.QueryMode
+ ***************************************/
+EFI_STATUS
+EFIAPI
+LcdGraphicsQueryMode (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN UINT32 ModeNumber,
+ OUT UINTN *SizeOfInfo,
+ OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ LCD_INSTANCE *Instance;
+
+ Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
+
+ // Setup the hardware if not already done
+ if( !mDisplayInitialized ) {
+ Status = InitializeDisplay(Instance);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ // Error checking
+ if ( (This == NULL) || (Info == NULL) || (SizeOfInfo == NULL) || (ModeNumber >= This->Mode->MaxMode) ) {
+ DEBUG((DEBUG_ERROR, "LcdGraphicsQueryMode: ERROR - For mode number %d : Invalid Parameter.\n", ModeNumber ));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }
+
+ *Info = AllocatePool (sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION));
+ if (*Info == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto EXIT;
+ }
+
+ *SizeOfInfo = sizeof( EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
+
+ Status = LcdPlatformQueryMode (ModeNumber,*Info);
+ if (EFI_ERROR(Status)) {
+ FreePool(*Info);
+ }
+
+EXIT:
+ return Status;
+}
+
+/***************************************
+ * GraphicsOutput Protocol function, mapping to
+ * EFI_GRAPHICS_OUTPUT_PROTOCOL.SetMode
+ ***************************************/
+EFI_STATUS
+EFIAPI
+LcdGraphicsSetMode (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN UINT32 ModeNumber
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL FillColour;
+ LCD_INSTANCE* Instance;
+
+ Instance = LCD_INSTANCE_FROM_GOP_THIS (This);
+
+ // Setup the hardware if not already done
+ if(!mDisplayInitialized) {
+ Status = InitializeDisplay (Instance);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ // Check if this mode is supported
+ if( ModeNumber >= This->Mode->MaxMode ) {
+ DEBUG((DEBUG_ERROR, "LcdGraphicsSetMode: ERROR - Unsupported mode number %d .\n", ModeNumber ));
+ Status = EFI_UNSUPPORTED;
+ goto EXIT;
+ }
+
+ // Set the oscillator frequency to support the new mode
+ Status = LcdPlatformSetMode (ModeNumber);
+ if (EFI_ERROR(Status)) {
+ Status = EFI_DEVICE_ERROR;
+ goto EXIT;
+ }
+
+ // Update the UEFI mode information
+ This->Mode->Mode = ModeNumber;
+ LcdPlatformQueryMode (ModeNumber,&Instance->ModeInfo);
+
+ // Set the hardware to the new mode
+ Status = LcdSetMode (ModeNumber);
+ if (EFI_ERROR(Status)) {
+ Status = EFI_DEVICE_ERROR;
+ goto EXIT;
+ }
+
+ // The UEFI spec requires that we now clear the visible portions of the output display to black.
+
+ // Set the fill colour to black
+ SetMem (&FillColour, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);
+
+ // Fill the entire visible area with the same colour.
+ Status = This->Blt (
+ This,
+ &FillColour,
+ EfiBltVideoFill,
+ 0,
+ 0,
+ 0,
+ 0,
+ This->Mode->Info->HorizontalResolution,
+ This->Mode->Info->VerticalResolution,
+ 0);
+
+EXIT:
+ return Status;
+}
+
+UINTN
+GetBytesPerPixel (
+ IN LCD_BPP Bpp
+ )
+{
+ switch(Bpp) {
+ case LCD_BITS_PER_PIXEL_24:
+ return 4;
+
+ case LCD_BITS_PER_PIXEL_16_565:
+ case LCD_BITS_PER_PIXEL_16_555:
+ case LCD_BITS_PER_PIXEL_12_444:
+ return 2;
+
+ case LCD_BITS_PER_PIXEL_8:
+ case LCD_BITS_PER_PIXEL_4:
+ case LCD_BITS_PER_PIXEL_2:
+ case LCD_BITS_PER_PIXEL_1:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
diff --git a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
index a267a538c..5387e53c4 100644
--- a/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
+++ b/ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/PL111LcdGraphicsOutputDxe.inf
@@ -1,56 +1,56 @@
-#/** @file
-#
-# Component description file for PL111LcdGraphicsOutputDxe module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = PL111LcdGraphicsDxe
- FILE_GUID = 407B4008-BF5B-11DF-9547-CF16E0D72085
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- ENTRY_POINT = LcdGraphicsOutputDxeInitialize
-
-[Sources.common]
- LcdGraphicsOutputDxe.c
- LcdGraphicsOutputBlt.c
- PL111Lcd.c
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- ArmLib
- UefiLib
- BaseLib
- DebugLib
- TimerLib
- UefiDriverEntryPoint
- UefiBootServicesTableLib
- IoLib
- BaseMemoryLib
- LcdPlatformLib
-
-[Protocols]
- gEfiDevicePathProtocolGuid
- gEfiGraphicsOutputProtocolGuid
-
-[FixedPcd]
- gArmPlatformTokenSpaceGuid.PcdPL111LcdBase
-
-[Depex]
- gEfiCpuArchProtocolGuid
+#/** @file
+#
+# Component description file for PL111LcdGraphicsOutputDxe module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PL111LcdGraphicsDxe
+ FILE_GUID = 407B4008-BF5B-11DF-9547-CF16E0D72085
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = LcdGraphicsOutputDxeInitialize
+
+[Sources.common]
+ LcdGraphicsOutputDxe.c
+ LcdGraphicsOutputBlt.c
+ PL111Lcd.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmVExpressPkg/ArmVExpressPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ ArmLib
+ UefiLib
+ BaseLib
+ DebugLib
+ TimerLib
+ UefiDriverEntryPoint
+ UefiBootServicesTableLib
+ IoLib
+ BaseMemoryLib
+ LcdPlatformLib
+
+[Protocols]
+ gEfiDevicePathProtocolGuid
+ gEfiGraphicsOutputProtocolGuid
+
+[FixedPcd]
+ gArmPlatformTokenSpaceGuid.PcdPL111LcdBase
+
+[Depex]
+ gEfiCpuArchProtocolGuid
diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
index d4dabeaef..21fceac1d 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
@@ -1,119 +1,119 @@
-/** @file NorFlashBlockIoDxe.c
-
- Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-
-#include "NorFlashDxe.h"
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoReset (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN BOOLEAN ExtendedVerification
- )
-{
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_BLKIO_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReset(MediaId=0x%x)\n", This->Media->MediaId));
-
- return NorFlashReset (Instance);
-}
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoReadBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- OUT VOID *Buffer
- )
-{
- NOR_FLASH_INSTANCE *Instance;
- EFI_STATUS Status;
-
- Instance = INSTANCE_FROM_BLKIO_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer));
-
- if( !This->Media->MediaPresent ) {
- Status = EFI_NO_MEDIA;
- } else if( This->Media->MediaId != MediaId ) {
- Status = EFI_MEDIA_CHANGED;
- } else {
- Status = NorFlashReadBlocks (Instance,Lba,BufferSizeInBytes,Buffer);
- }
-
- return Status;
-}
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoWriteBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- IN VOID *Buffer
- )
-{
- NOR_FLASH_INSTANCE *Instance;
- EFI_STATUS Status;
-
- Instance = INSTANCE_FROM_BLKIO_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer));
-
- if( !This->Media->MediaPresent ) {
- Status = EFI_NO_MEDIA;
- } else if( This->Media->MediaId != MediaId ) {
- Status = EFI_MEDIA_CHANGED;
- } else if( This->Media->ReadOnly ) {
- Status = EFI_WRITE_PROTECTED;
- } else {
- Status = NorFlashWriteBlocks (Instance,Lba,BufferSizeInBytes,Buffer);
- }
-
- return Status;
-}
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoFlushBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This
- )
-{
- // No Flush required for the NOR Flash driver
- // because cache operations are not permitted.
-
- DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoFlushBlocks: Function NOT IMPLEMENTED (not required).\n"));
-
- // Nothing to do so just return without error
- return EFI_SUCCESS;
-}
+/** @file NorFlashBlockIoDxe.c
+
+ Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include "NorFlashDxe.h"
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoReset (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN BOOLEAN ExtendedVerification
+ )
+{
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_BLKIO_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReset(MediaId=0x%x)\n", This->Media->MediaId));
+
+ return NorFlashReset (Instance);
+}
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoReadBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ NOR_FLASH_INSTANCE *Instance;
+ EFI_STATUS Status;
+
+ Instance = INSTANCE_FROM_BLKIO_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer));
+
+ if( !This->Media->MediaPresent ) {
+ Status = EFI_NO_MEDIA;
+ } else if( This->Media->MediaId != MediaId ) {
+ Status = EFI_MEDIA_CHANGED;
+ } else {
+ Status = NorFlashReadBlocks (Instance,Lba,BufferSizeInBytes,Buffer);
+ }
+
+ return Status;
+}
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoWriteBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+ )
+{
+ NOR_FLASH_INSTANCE *Instance;
+ EFI_STATUS Status;
+
+ Instance = INSTANCE_FROM_BLKIO_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer));
+
+ if( !This->Media->MediaPresent ) {
+ Status = EFI_NO_MEDIA;
+ } else if( This->Media->MediaId != MediaId ) {
+ Status = EFI_MEDIA_CHANGED;
+ } else if( This->Media->ReadOnly ) {
+ Status = EFI_WRITE_PROTECTED;
+ } else {
+ Status = NorFlashWriteBlocks (Instance,Lba,BufferSizeInBytes,Buffer);
+ }
+
+ return Status;
+}
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoFlushBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This
+ )
+{
+ // No Flush required for the NOR Flash driver
+ // because cache operations are not permitted.
+
+ DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoFlushBlocks: Function NOT IMPLEMENTED (not required).\n"));
+
+ // Nothing to do so just return without error
+ return EFI_SUCCESS;
+}
diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c
index 8464a98fd..d1506c721 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -1,52 +1,52 @@
-/** @file NorFlashDxe.c
-
- Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Library/UefiLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/PcdLib.h>
-
-#include "NorFlashDxe.h"
-
-
-//
-// Global variable declarations
-//
-NOR_FLASH_INSTANCE **mNorFlashInstances;
-
-NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = {
- NOR_FLASH_SIGNATURE, // Signature
- NULL, // Handle ... NEED TO BE FILLED
-
- FALSE, // Initialized
- NULL, // Initialize
-
- 0, // DeviceBaseAddress ... NEED TO BE FILLED
- 0, // RegionBaseAddress ... NEED TO BE FILLED
- 0, // Size ... NEED TO BE FILLED
- 0, // StartLba
-
+/** @file NorFlashDxe.c
+
+ Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Library/UefiLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/PcdLib.h>
+
+#include "NorFlashDxe.h"
+
+
+//
+// Global variable declarations
+//
+NOR_FLASH_INSTANCE **mNorFlashInstances;
+
+NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = {
+ NOR_FLASH_SIGNATURE, // Signature
+ NULL, // Handle ... NEED TO BE FILLED
+
+ FALSE, // Initialized
+ NULL, // Initialize
+
+ 0, // DeviceBaseAddress ... NEED TO BE FILLED
+ 0, // RegionBaseAddress ... NEED TO BE FILLED
+ 0, // Size ... NEED TO BE FILLED
+ 0, // StartLba
+
{
EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision
NULL, // Media ... NEED TO BE FILLED
NorFlashBlockIoReset, // Reset;
- NorFlashBlockIoReadBlocks, // ReadBlocks
- NorFlashBlockIoWriteBlocks, // WriteBlocks
+ NorFlashBlockIoReadBlocks, // ReadBlocks
+ NorFlashBlockIoWriteBlocks, // WriteBlocks
NorFlashBlockIoFlushBlocks // FlushBlocks
- }, // BlockIoProtocol
-
+ }, // BlockIoProtocol
+
{
0, // MediaId ... NEED TO BE FILLED
FALSE, // RemovableMedia
@@ -59,767 +59,767 @@ NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = {
0, // LastBlock ... NEED TO BE FILLED
0, // LowestAlignedLba
1, // LogicalBlocksPerPhysicalBlock
- }, //Media;
-
- FALSE, // SupportFvb ... NEED TO BE FILLED
+ }, //Media;
+
+ FALSE, // SupportFvb ... NEED TO BE FILLED
{
- FvbGetAttributes, // GetAttributes
- FvbSetAttributes, // SetAttributes
- FvbGetPhysicalAddress, // GetPhysicalAddress
- FvbGetBlockSize, // GetBlockSize
- FvbRead, // Read
- FvbWrite, // Write
+ FvbGetAttributes, // GetAttributes
+ FvbSetAttributes, // SetAttributes
+ FvbGetPhysicalAddress, // GetPhysicalAddress
+ FvbGetBlockSize, // GetBlockSize
+ FvbRead, // Read
+ FvbWrite, // Write
FvbEraseBlocks, // EraseBlocks
NULL, //ParentHandle
- }, // FvbProtoccol;
-
- {
- {
- {
- HARDWARE_DEVICE_PATH,
- HW_VENDOR_DP,
- (UINT8)( sizeof(VENDOR_DEVICE_PATH) ),
- (UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8),
- },
- { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, // GUID ... NEED TO BE FILLED
- },
- {
- END_DEVICE_PATH_TYPE,
- END_ENTIRE_DEVICE_PATH_SUBTYPE,
- sizeof (EFI_DEVICE_PATH_PROTOCOL),
- 0
- }
- } // DevicePath
-};
-
-EFI_STATUS
-NorFlashCreateInstance (
- IN UINTN NorFlashDeviceBase,
- IN UINTN NorFlashRegionBase,
- IN UINTN NorFlashSize,
- IN UINT32 MediaId,
- IN UINT32 BlockSize,
- IN BOOLEAN SupportFvb,
- IN CONST GUID *NorFlashGuid,
- OUT NOR_FLASH_INSTANCE** NorFlashInstance
- )
-{
- EFI_STATUS Status;
- NOR_FLASH_INSTANCE* Instance;
-
- ASSERT(NorFlashInstance != NULL);
-
- Instance = AllocateCopyPool (sizeof(NOR_FLASH_INSTANCE),&mNorFlashInstanceTemplate);
- if (Instance == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- Instance->DeviceBaseAddress = NorFlashDeviceBase;
- Instance->RegionBaseAddress = NorFlashRegionBase;
- Instance->Size = NorFlashSize;
-
- Instance->BlockIoProtocol.Media = &Instance->Media;
- Instance->Media.MediaId = MediaId;
- Instance->Media.BlockSize = BlockSize;
- Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1;
+ }, // FvbProtoccol;
+
+ {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ (UINT8)( sizeof(VENDOR_DEVICE_PATH) ),
+ (UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8),
+ },
+ { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }, // GUID ... NEED TO BE FILLED
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ sizeof (EFI_DEVICE_PATH_PROTOCOL),
+ 0
+ }
+ } // DevicePath
+};
+
+EFI_STATUS
+NorFlashCreateInstance (
+ IN UINTN NorFlashDeviceBase,
+ IN UINTN NorFlashRegionBase,
+ IN UINTN NorFlashSize,
+ IN UINT32 MediaId,
+ IN UINT32 BlockSize,
+ IN BOOLEAN SupportFvb,
+ IN CONST GUID *NorFlashGuid,
+ OUT NOR_FLASH_INSTANCE** NorFlashInstance
+ )
+{
+ EFI_STATUS Status;
+ NOR_FLASH_INSTANCE* Instance;
+
+ ASSERT(NorFlashInstance != NULL);
+
+ Instance = AllocateCopyPool (sizeof(NOR_FLASH_INSTANCE),&mNorFlashInstanceTemplate);
+ if (Instance == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Instance->DeviceBaseAddress = NorFlashDeviceBase;
+ Instance->RegionBaseAddress = NorFlashRegionBase;
+ Instance->Size = NorFlashSize;
+
+ Instance->BlockIoProtocol.Media = &Instance->Media;
+ Instance->Media.MediaId = MediaId;
+ Instance->Media.BlockSize = BlockSize;
+ Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1;
CopyGuid (&Instance->DevicePath.Vendor.Guid,NorFlashGuid);
-
- if (SupportFvb) {
- Instance->SupportFvb = TRUE;
- Instance->Initialize = NorFlashFvbInitialize;
-
- Status = gBS->InstallMultipleProtocolInterfaces (
- &Instance->Handle,
- &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
- &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
- &gEfiFirmwareVolumeBlockProtocolGuid, &Instance->FvbProtocol,
- NULL
- );
- if (EFI_ERROR(Status)) {
- FreePool(Instance);
- return Status;
- }
- } else {
- Instance->Initialized = TRUE;
-
- Status = gBS->InstallMultipleProtocolInterfaces (
- &Instance->Handle,
- &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
- &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
- NULL
- );
- if (EFI_ERROR(Status)) {
- FreePool(Instance);
- return Status;
- }
- }
+
+ if (SupportFvb) {
+ Instance->SupportFvb = TRUE;
+ Instance->Initialize = NorFlashFvbInitialize;
+
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Instance->Handle,
+ &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
+ &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
+ &gEfiFirmwareVolumeBlockProtocolGuid, &Instance->FvbProtocol,
+ NULL
+ );
+ if (EFI_ERROR(Status)) {
+ FreePool(Instance);
+ return Status;
+ }
+ } else {
+ Instance->Initialized = TRUE;
+
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Instance->Handle,
+ &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
+ &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
+ NULL
+ );
+ if (EFI_ERROR(Status)) {
+ FreePool(Instance);
+ return Status;
+ }
+ }
*NorFlashInstance = Instance;
- return Status;
-}
-
-UINT32
-NorFlashReadStatusRegister (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN SR_Address
- )
-{
- // Prepare to read the status register
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER);
- return MmioRead32 (Instance->DeviceBaseAddress);
-}
-
-
-BOOLEAN
-NorFlashBlockIsLocked (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN BlockAddress
- )
-{
- UINT32 LockStatus;
- BOOLEAN BlockIsLocked;
-
- BlockIsLocked = TRUE;
-
- // Send command for reading device id
- SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
-
- // Read block lock status
- LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
-
- // Decode block lock status
- LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
-
- if ((LockStatus & 0x2) != 0) {
- DEBUG((EFI_D_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n"));
- }
-
- if ((LockStatus & 0x1) == 0) {
- // This means the block is unlocked
- DEBUG((DEBUG_BLKIO, "UnlockSingleBlock: Block 0x%08x unlocked\n", BlockAddress));
- BlockIsLocked = FALSE;
- }
-
- return BlockIsLocked;
-}
-
-
-EFI_STATUS
-NorFlashUnlockSingleBlock (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN BlockAddress
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- UINT32 LockStatus;
-
- // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations
- // and to protect shared data structures.
-
- if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) {
- do {
- // Request a lock setup
- SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
-
- // Request an unlock
- SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
-
- // Send command for reading device id
- SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
-
- // Read block lock status
- LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
-
- // Decode block lock status
- LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
- } while ((LockStatus & 0x1) == 1);
- } else {
- // Request a lock setup
- SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
-
- // Request an unlock
- SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
-
- // Wait until the status register gives us the all clear
- do {
- LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress);
- } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
- }
-
- // Put device back into Read Array mode
- SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY);
-
- DEBUG((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x, Exit Status = \"%r\".\n", BlockAddress, Status));
-
- return Status;
-}
-
-
-EFI_STATUS
-NorFlashUnlockSingleBlockIfNecessary (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN BlockAddress
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
-
- if (NorFlashBlockIsLocked (Instance, BlockAddress) == TRUE) {
- Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
- }
-
- return Status;
-}
-
-
-/**
- * The following function presumes that the block has already been unlocked.
- **/
-EFI_STATUS
-NorFlashEraseSingleBlock (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN BlockAddress
- )
-{
- EFI_STATUS Status;
- UINT32 StatusRegister;
-
- Status = EFI_SUCCESS;
-
- // Request a block erase and then confirm it
- SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP);
- SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM);
-
- // Wait until the status register gives us the all clear
- do {
- StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress);
- } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-
- if (StatusRegister & P30_SR_BIT_VPP) {
- DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) {
- DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (StatusRegister & P30_SR_BIT_ERASE) {
- DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
- // The debug level message has been reduced because a device lock might happen. In this case we just retry it ...
- DEBUG((EFI_D_INFO,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress));
- Status = EFI_WRITE_PROTECTED;
- }
-
- if (EFI_ERROR(Status)) {
- // Clear the Status Register
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
- }
-
- // Put device back into Read Array mode
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
- return Status;
-}
-
-/**
- * The following function presumes that the block has already been unlocked.
- **/
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN BlockAddress
- )
-{
- EFI_STATUS Status;
- UINTN Index;
- EFI_TPL OriginalTPL;
-
- // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
- OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-
- Index = 0;
- // The block erase might fail a first time (SW bug ?). Retry it ...
- do {
- // Unlock the block if we have to
- Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
- if (!EFI_ERROR(Status)) {
- Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
- }
- Index++;
- } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
-
- if (Index == NOR_FLASH_ERASE_RETRY) {
- DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress,Index));
- }
-
- // Interruptions can resume.
- gBS->RestoreTPL (OriginalTPL);
-
- return Status;
-}
-
-
-EFI_STATUS
-NorFlashWriteSingleWord (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN WordAddress,
- IN UINT32 WriteData
- )
-{
- EFI_STATUS Status;
- UINT32 StatusRegister;
-
- Status = EFI_SUCCESS;
-
- // Request a write single word command
- SEND_NOR_COMMAND(WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP);
-
- // Store the word into NOR Flash;
- MmioWrite32 (WordAddress, WriteData);
-
- // Wait for the write to complete and then check for any errors; i.e. check the Status Register
- do {
- // Prepare to read the status register
- StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress);
- // The chip is busy while the WRITE bit is not asserted
- } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-
-
- // Perform a full status check:
- // Mask the relevant bits of Status Register.
- // Everything should be zero, if not, we have a problem
-
- if (StatusRegister & P30_SR_BIT_VPP) {
- DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n",WordAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (StatusRegister & P30_SR_BIT_PROGRAM) {
- DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n",WordAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
- DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n",WordAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (!EFI_ERROR(Status)) {
- // Clear the Status Register
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
- }
-
- // Put device back into Read Array mode
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
- return Status;
-}
-
-/*
- * Writes data to the NOR Flash using the Buffered Programming method.
- *
- * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions.
- * Therefore this function will only handle buffers up to 32 words or 128 bytes.
- * To deal with larger buffers, call this function again.
- *
- * This function presumes that both the TargetAddress and the TargetAddress+BufferSize
- * exist entirely within the NOR Flash. Therefore these conditions will not be checked here.
- *
- * In buffered programming, if the target address not at the beginning of a 32-bit word boundary,
- * then programming time is doubled and power consumption is increased.
- * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
- * i.e. the last 4 bits of the target start address must be zero: 0x......00
- */
-EFI_STATUS
-NorFlashWriteBuffer (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN TargetAddress,
- IN UINTN BufferSizeInBytes,
- IN UINT32 *Buffer
- )
-{
- EFI_STATUS Status;
- UINTN BufferSizeInWords;
- UINTN Count;
- volatile UINT32 *Data;
- UINTN WaitForBuffer;
- BOOLEAN BufferAvailable;
- UINT32 StatusRegister;
-
- WaitForBuffer = MAX_BUFFERED_PROG_ITERATIONS;
- BufferAvailable = FALSE;
-
- // Check that the target address does not cross a 32-word boundary.
- if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) {
- return EFI_INVALID_PARAMETER;
- }
-
- // Check there are some data to program
- if (BufferSizeInBytes == 0) {
- return EFI_BUFFER_TOO_SMALL;
- }
-
- // Check that the buffer size does not exceed the maximum hardware buffer size on chip.
- if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // Check that the buffer size is a multiple of 32-bit words
- if ((BufferSizeInBytes % 4) != 0) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // Pre-programming conditions checked, now start the algorithm.
-
- // Prepare the data destination address
- Data = (UINT32 *)TargetAddress;
-
- // Check the availability of the buffer
- do {
- // Issue the Buffered Program Setup command
- SEND_NOR_COMMAND(TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP);
-
- // Read back the status register bit#7 from the same address
- if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) {
- BufferAvailable = TRUE;
- }
-
- // Update the loop counter
- WaitForBuffer--;
-
- } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE));
-
- // The buffer was not available for writing
- if (WaitForBuffer == 0) {
- Status = EFI_DEVICE_ERROR;
- goto EXIT;
- }
-
- // From now on we work in 32-bit words
- BufferSizeInWords = BufferSizeInBytes / (UINTN)4;
-
- // Write the word count, which is (buffer_size_in_words - 1),
- // because word count 0 means one word.
- SEND_NOR_COMMAND(TargetAddress, 0, (BufferSizeInWords - 1));
-
- // Write the data to the NOR Flash, advancing each address by 4 bytes
- for(Count=0; Count < BufferSizeInWords; Count++, Data++, Buffer++) {
- *Data = *Buffer;
- }
-
- // Issue the Buffered Program Confirm command, to start the programming operation
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM);
-
- // Wait for the write to complete and then check for any errors; i.e. check the Status Register
- do {
- StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress);
- // The chip is busy while the WRITE bit is not asserted
- } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-
-
- // Perform a full status check:
- // Mask the relevant bits of Status Register.
- // Everything should be zero, if not, we have a problem
-
- Status = EFI_SUCCESS;
-
- if (StatusRegister & P30_SR_BIT_VPP) {
- DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (StatusRegister & P30_SR_BIT_PROGRAM) {
- DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
- DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n",TargetAddress));
- Status = EFI_DEVICE_ERROR;
- }
-
- if (!EFI_ERROR(Status)) {
- // Clear the Status Register
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
- }
-
-EXIT:
- // Put device back into Read Array mode
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
- return Status;
-}
-
-EFI_STATUS
-NorFlashWriteSingleBlock (
- IN NOR_FLASH_INSTANCE *Instance,
- IN EFI_LBA Lba,
- IN UINT32 *DataBuffer,
- IN UINT32 BlockSizeInWords
- )
-{
- EFI_STATUS Status;
- UINTN WordAddress;
- UINT32 WordIndex;
- UINTN BufferIndex;
- UINTN BlockAddress;
- UINTN BuffersInBlock;
- UINTN RemainingWords;
- EFI_TPL OriginalTPL;
-
- Status = EFI_SUCCESS;
-
- // Get the physical address of the block
- BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
-
- // Start writing from the first address at the start of the block
- WordAddress = BlockAddress;
-
- // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
- OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-
- Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
- goto EXIT;
- }
-
- // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
-
- // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
- if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
-
- // First, break the entire block into buffer-sized chunks.
- BuffersInBlock = (UINTN)BlockSizeInWords / P30_MAX_BUFFER_SIZE_IN_BYTES;
-
- // Then feed each buffer chunk to the NOR Flash
- for(BufferIndex=0;
- BufferIndex < BuffersInBlock;
- BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
- ) {
- Status = NorFlashWriteBuffer (Instance, WordAddress, P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- // Finally, finish off any remaining words that are less than the maximum size of the buffer
- RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
-
- if(RemainingWords != 0) {
- Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- } else {
- // For now, use the single word programming algorithm
- // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
- // i.e. which ends in the range 0x......01 - 0x......7F.
- for(WordIndex=0; WordIndex<BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
- Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
- }
-
-EXIT:
- // Interruptions can resume.
- gBS->RestoreTPL (OriginalTPL);
-
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
- }
- return Status;
-}
-
-
-EFI_STATUS
-NorFlashWriteBlocks (
- IN NOR_FLASH_INSTANCE *Instance,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- IN VOID *Buffer
- )
-{
- UINT32 *pWriteBuffer;
- EFI_STATUS Status = EFI_SUCCESS;
- EFI_LBA CurrentBlock;
- UINT32 BlockSizeInWords;
- UINT32 NumBlocks;
- UINT32 BlockCount;
-
- // The buffer must be valid
- if (Buffer == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- if(Instance->Media.ReadOnly == TRUE) {
- return EFI_WRITE_PROTECTED;
- }
-
- // We must have some bytes to read
- DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes));
- if(BufferSizeInBytes == 0) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // The size of the buffer must be a multiple of the block size
- DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize));
- if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // All blocks must be within the device
- NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
-
- DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba));
-
- if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
- DEBUG((EFI_D_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"));
- return EFI_INVALID_PARAMETER;
- }
-
- BlockSizeInWords = Instance->Media.BlockSize / 4;
-
- // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer
- // to a proper data type, so use *ReadBuffer
- pWriteBuffer = (UINT32 *)Buffer;
-
- CurrentBlock = Lba;
- for (BlockCount=0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) {
-
- DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock));
-
- Status = NorFlashWriteSingleBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords);
-
- if (EFI_ERROR(Status)) {
- break;
- }
- }
-
- DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status));
- return Status;
-}
-
-EFI_STATUS
-NorFlashReadBlocks (
- IN NOR_FLASH_INSTANCE *Instance,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- OUT VOID *Buffer
- )
-{
- UINT32 NumBlocks;
- UINTN StartAddress;
-
- // The buffer must be valid
- if (Buffer == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- // We must have some bytes to read
- DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: BufferSize=0x%x bytes.\n", BufferSizeInBytes));
- if(BufferSizeInBytes == 0) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // The size of the buffer must be a multiple of the block size
- DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: BlockSize=0x%x bytes.\n", Instance->Media.BlockSize));
- if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // All blocks must be within the device
- NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
-
- DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld\n", NumBlocks, Instance->Media.LastBlock, Lba));
-
- if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
- DEBUG((EFI_D_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n"));
- return EFI_INVALID_PARAMETER;
- }
-
- // Get the address to start reading from
- StartAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
- Lba,
- Instance->Media.BlockSize
- );
-
- // Put the device into Read Array mode
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
- // Readout the data
- CopyMem(Buffer, (UINTN *)StartAddress, BufferSizeInBytes);
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-NorFlashReset (
- IN NOR_FLASH_INSTANCE *Instance
- )
-{
- // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode
- SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-EFIAPI
-NorFlashInitialise (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- UINT32 Index;
- NOR_FLASH_DESCRIPTION* NorFlashDevices;
- UINT32 NorFlashDeviceCount;
- BOOLEAN ContainVariableStorage;
-
- Status = NorFlashPlatformInitialization ();
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to initialize Nor Flash devices\n"));
- return Status;
- }
-
- Status = NorFlashPlatformGetDevices (&NorFlashDevices,&NorFlashDeviceCount);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to get Nor Flash devices\n"));
- return Status;
- }
-
- mNorFlashInstances = AllocatePool (sizeof(NOR_FLASH_INSTANCE*) * NorFlashDeviceCount);
-
- for (Index = 0; Index < NorFlashDeviceCount; Index++) {
- // Check if this NOR Flash device contain the variable storage region
- ContainVariableStorage =
- (NorFlashDevices[Index].RegionBaseAddress <= PcdGet32 (PcdFlashNvStorageVariableBase)) &&
- (PcdGet32 (PcdFlashNvStorageVariableBase) + PcdGet32 (PcdFlashNvStorageVariableSize) <= NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size);
-
- Status = NorFlashCreateInstance (
- NorFlashDevices[Index].DeviceBaseAddress,
- NorFlashDevices[Index].RegionBaseAddress,
- NorFlashDevices[Index].Size,
- Index,
- NorFlashDevices[Index].BlockSize,
- ContainVariableStorage,
- &NorFlashDevices[Index].Guid,
- &mNorFlashInstances[Index]
- );
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to create instance for NorFlash[%d]\n",Index));
- }
- }
-
- return Status;
-}
+ return Status;
+}
+
+UINT32
+NorFlashReadStatusRegister (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN SR_Address
+ )
+{
+ // Prepare to read the status register
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER);
+ return MmioRead32 (Instance->DeviceBaseAddress);
+}
+
+
+BOOLEAN
+NorFlashBlockIsLocked (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ UINT32 LockStatus;
+ BOOLEAN BlockIsLocked;
+
+ BlockIsLocked = TRUE;
+
+ // Send command for reading device id
+ SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
+
+ // Read block lock status
+ LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
+
+ // Decode block lock status
+ LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
+
+ if ((LockStatus & 0x2) != 0) {
+ DEBUG((EFI_D_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n"));
+ }
+
+ if ((LockStatus & 0x1) == 0) {
+ // This means the block is unlocked
+ DEBUG((DEBUG_BLKIO, "UnlockSingleBlock: Block 0x%08x unlocked\n", BlockAddress));
+ BlockIsLocked = FALSE;
+ }
+
+ return BlockIsLocked;
+}
+
+
+EFI_STATUS
+NorFlashUnlockSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINT32 LockStatus;
+
+ // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations
+ // and to protect shared data structures.
+
+ if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) {
+ do {
+ // Request a lock setup
+ SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
+
+ // Request an unlock
+ SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
+
+ // Send command for reading device id
+ SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
+
+ // Read block lock status
+ LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
+
+ // Decode block lock status
+ LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
+ } while ((LockStatus & 0x1) == 1);
+ } else {
+ // Request a lock setup
+ SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
+
+ // Request an unlock
+ SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
+
+ // Wait until the status register gives us the all clear
+ do {
+ LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress);
+ } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+ }
+
+ // Put device back into Read Array mode
+ SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY);
+
+ DEBUG((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x, Exit Status = \"%r\".\n", BlockAddress, Status));
+
+ return Status;
+}
+
+
+EFI_STATUS
+NorFlashUnlockSingleBlockIfNecessary (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ if (NorFlashBlockIsLocked (Instance, BlockAddress) == TRUE) {
+ Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
+ }
+
+ return Status;
+}
+
+
+/**
+ * The following function presumes that the block has already been unlocked.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+ UINT32 StatusRegister;
+
+ Status = EFI_SUCCESS;
+
+ // Request a block erase and then confirm it
+ SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP);
+ SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM);
+
+ // Wait until the status register gives us the all clear
+ do {
+ StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress);
+ } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+
+ if (StatusRegister & P30_SR_BIT_VPP) {
+ DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) {
+ DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (StatusRegister & P30_SR_BIT_ERASE) {
+ DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
+ // The debug level message has been reduced because a device lock might happen. In this case we just retry it ...
+ DEBUG((EFI_D_INFO,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress));
+ Status = EFI_WRITE_PROTECTED;
+ }
+
+ if (EFI_ERROR(Status)) {
+ // Clear the Status Register
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
+ }
+
+ // Put device back into Read Array mode
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+ return Status;
+}
+
+/**
+ * The following function presumes that the block has already been unlocked.
+ **/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_TPL OriginalTPL;
+
+ // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
+ OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ Index = 0;
+ // The block erase might fail a first time (SW bug ?). Retry it ...
+ do {
+ // Unlock the block if we have to
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (!EFI_ERROR(Status)) {
+ Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+ }
+ Index++;
+ } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
+
+ if (Index == NOR_FLASH_ERASE_RETRY) {
+ DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress,Index));
+ }
+
+ // Interruptions can resume.
+ gBS->RestoreTPL (OriginalTPL);
+
+ return Status;
+}
+
+
+EFI_STATUS
+NorFlashWriteSingleWord (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN WordAddress,
+ IN UINT32 WriteData
+ )
+{
+ EFI_STATUS Status;
+ UINT32 StatusRegister;
+
+ Status = EFI_SUCCESS;
+
+ // Request a write single word command
+ SEND_NOR_COMMAND(WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP);
+
+ // Store the word into NOR Flash;
+ MmioWrite32 (WordAddress, WriteData);
+
+ // Wait for the write to complete and then check for any errors; i.e. check the Status Register
+ do {
+ // Prepare to read the status register
+ StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress);
+ // The chip is busy while the WRITE bit is not asserted
+ } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+
+
+ // Perform a full status check:
+ // Mask the relevant bits of Status Register.
+ // Everything should be zero, if not, we have a problem
+
+ if (StatusRegister & P30_SR_BIT_VPP) {
+ DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n",WordAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (StatusRegister & P30_SR_BIT_PROGRAM) {
+ DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n",WordAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
+ DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n",WordAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (!EFI_ERROR(Status)) {
+ // Clear the Status Register
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
+ }
+
+ // Put device back into Read Array mode
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+ return Status;
+}
+
+/*
+ * Writes data to the NOR Flash using the Buffered Programming method.
+ *
+ * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions.
+ * Therefore this function will only handle buffers up to 32 words or 128 bytes.
+ * To deal with larger buffers, call this function again.
+ *
+ * This function presumes that both the TargetAddress and the TargetAddress+BufferSize
+ * exist entirely within the NOR Flash. Therefore these conditions will not be checked here.
+ *
+ * In buffered programming, if the target address not at the beginning of a 32-bit word boundary,
+ * then programming time is doubled and power consumption is increased.
+ * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
+ * i.e. the last 4 bits of the target start address must be zero: 0x......00
+ */
+EFI_STATUS
+NorFlashWriteBuffer (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN TargetAddress,
+ IN UINTN BufferSizeInBytes,
+ IN UINT32 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINTN BufferSizeInWords;
+ UINTN Count;
+ volatile UINT32 *Data;
+ UINTN WaitForBuffer;
+ BOOLEAN BufferAvailable;
+ UINT32 StatusRegister;
+
+ WaitForBuffer = MAX_BUFFERED_PROG_ITERATIONS;
+ BufferAvailable = FALSE;
+
+ // Check that the target address does not cross a 32-word boundary.
+ if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Check there are some data to program
+ if (BufferSizeInBytes == 0) {
+ return EFI_BUFFER_TOO_SMALL;
+ }
+
+ // Check that the buffer size does not exceed the maximum hardware buffer size on chip.
+ if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // Check that the buffer size is a multiple of 32-bit words
+ if ((BufferSizeInBytes % 4) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // Pre-programming conditions checked, now start the algorithm.
+
+ // Prepare the data destination address
+ Data = (UINT32 *)TargetAddress;
+
+ // Check the availability of the buffer
+ do {
+ // Issue the Buffered Program Setup command
+ SEND_NOR_COMMAND(TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP);
+
+ // Read back the status register bit#7 from the same address
+ if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) {
+ BufferAvailable = TRUE;
+ }
+
+ // Update the loop counter
+ WaitForBuffer--;
+
+ } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE));
+
+ // The buffer was not available for writing
+ if (WaitForBuffer == 0) {
+ Status = EFI_DEVICE_ERROR;
+ goto EXIT;
+ }
+
+ // From now on we work in 32-bit words
+ BufferSizeInWords = BufferSizeInBytes / (UINTN)4;
+
+ // Write the word count, which is (buffer_size_in_words - 1),
+ // because word count 0 means one word.
+ SEND_NOR_COMMAND(TargetAddress, 0, (BufferSizeInWords - 1));
+
+ // Write the data to the NOR Flash, advancing each address by 4 bytes
+ for(Count=0; Count < BufferSizeInWords; Count++, Data++, Buffer++) {
+ *Data = *Buffer;
+ }
+
+ // Issue the Buffered Program Confirm command, to start the programming operation
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM);
+
+ // Wait for the write to complete and then check for any errors; i.e. check the Status Register
+ do {
+ StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress);
+ // The chip is busy while the WRITE bit is not asserted
+ } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+
+
+ // Perform a full status check:
+ // Mask the relevant bits of Status Register.
+ // Everything should be zero, if not, we have a problem
+
+ Status = EFI_SUCCESS;
+
+ if (StatusRegister & P30_SR_BIT_VPP) {
+ DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (StatusRegister & P30_SR_BIT_PROGRAM) {
+ DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
+ DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n",TargetAddress));
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (!EFI_ERROR(Status)) {
+ // Clear the Status Register
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
+ }
+
+EXIT:
+ // Put device back into Read Array mode
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+ return Status;
+}
+
+EFI_STATUS
+NorFlashWriteSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINT32 *DataBuffer,
+ IN UINT32 BlockSizeInWords
+ )
+{
+ EFI_STATUS Status;
+ UINTN WordAddress;
+ UINT32 WordIndex;
+ UINTN BufferIndex;
+ UINTN BlockAddress;
+ UINTN BuffersInBlock;
+ UINTN RemainingWords;
+ EFI_TPL OriginalTPL;
+
+ Status = EFI_SUCCESS;
+
+ // Get the physical address of the block
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
+
+ // Start writing from the first address at the start of the block
+ WordAddress = BlockAddress;
+
+ // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
+ OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
+ goto EXIT;
+ }
+
+ // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
+
+ // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
+ if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
+
+ // First, break the entire block into buffer-sized chunks.
+ BuffersInBlock = (UINTN)BlockSizeInWords / P30_MAX_BUFFER_SIZE_IN_BYTES;
+
+ // Then feed each buffer chunk to the NOR Flash
+ for(BufferIndex=0;
+ BufferIndex < BuffersInBlock;
+ BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
+ ) {
+ Status = NorFlashWriteBuffer (Instance, WordAddress, P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ // Finally, finish off any remaining words that are less than the maximum size of the buffer
+ RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
+
+ if(RemainingWords != 0) {
+ Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ } else {
+ // For now, use the single word programming algorithm
+ // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
+ // i.e. which ends in the range 0x......01 - 0x......7F.
+ for(WordIndex=0; WordIndex<BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
+ Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+ }
+
+EXIT:
+ // Interruptions can resume.
+ gBS->RestoreTPL (OriginalTPL);
+
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
+ }
+ return Status;
+}
+
+
+EFI_STATUS
+NorFlashWriteBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+ )
+{
+ UINT32 *pWriteBuffer;
+ EFI_STATUS Status = EFI_SUCCESS;
+ EFI_LBA CurrentBlock;
+ UINT32 BlockSizeInWords;
+ UINT32 NumBlocks;
+ UINT32 BlockCount;
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if(Instance->Media.ReadOnly == TRUE) {
+ return EFI_WRITE_PROTECTED;
+ }
+
+ // We must have some bytes to read
+ DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes));
+ if(BufferSizeInBytes == 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize));
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // All blocks must be within the device
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
+
+ DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba));
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG((EFI_D_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ BlockSizeInWords = Instance->Media.BlockSize / 4;
+
+ // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer
+ // to a proper data type, so use *ReadBuffer
+ pWriteBuffer = (UINT32 *)Buffer;
+
+ CurrentBlock = Lba;
+ for (BlockCount=0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) {
+
+ DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock));
+
+ Status = NorFlashWriteSingleBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords);
+
+ if (EFI_ERROR(Status)) {
+ break;
+ }
+ }
+
+ DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status));
+ return Status;
+}
+
+EFI_STATUS
+NorFlashReadBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINT32 NumBlocks;
+ UINTN StartAddress;
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // We must have some bytes to read
+ DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: BufferSize=0x%x bytes.\n", BufferSizeInBytes));
+ if(BufferSizeInBytes == 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: BlockSize=0x%x bytes.\n", Instance->Media.BlockSize));
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // All blocks must be within the device
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
+
+ DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld\n", NumBlocks, Instance->Media.LastBlock, Lba));
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG((EFI_D_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n"));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Put the device into Read Array mode
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+ // Readout the data
+ CopyMem(Buffer, (UINTN *)StartAddress, BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+NorFlashReset (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode
+ SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+NorFlashInitialise (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ UINT32 Index;
+ NOR_FLASH_DESCRIPTION* NorFlashDevices;
+ UINT32 NorFlashDeviceCount;
+ BOOLEAN ContainVariableStorage;
+
+ Status = NorFlashPlatformInitialization ();
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to initialize Nor Flash devices\n"));
+ return Status;
+ }
+
+ Status = NorFlashPlatformGetDevices (&NorFlashDevices,&NorFlashDeviceCount);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to get Nor Flash devices\n"));
+ return Status;
+ }
+
+ mNorFlashInstances = AllocatePool (sizeof(NOR_FLASH_INSTANCE*) * NorFlashDeviceCount);
+
+ for (Index = 0; Index < NorFlashDeviceCount; Index++) {
+ // Check if this NOR Flash device contain the variable storage region
+ ContainVariableStorage =
+ (NorFlashDevices[Index].RegionBaseAddress <= PcdGet32 (PcdFlashNvStorageVariableBase)) &&
+ (PcdGet32 (PcdFlashNvStorageVariableBase) + PcdGet32 (PcdFlashNvStorageVariableSize) <= NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size);
+
+ Status = NorFlashCreateInstance (
+ NorFlashDevices[Index].DeviceBaseAddress,
+ NorFlashDevices[Index].RegionBaseAddress,
+ NorFlashDevices[Index].Size,
+ Index,
+ NorFlashDevices[Index].BlockSize,
+ ContainVariableStorage,
+ &NorFlashDevices[Index].Guid,
+ &mNorFlashInstances[Index]
+ );
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to create instance for NorFlash[%d]\n",Index));
+ }
+ }
+
+ return Status;
+}
diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.h b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.h
index a284c151a..959c0c190 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.h
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.h
@@ -1,316 +1,316 @@
-/** @file NorFlashDxe.h
-
- Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __NOR_FLASH_DXE_H__
-#define __NOR_FLASH_DXE_H__
-
-
-#include <Base.h>
-#include <PiDxe.h>
-
-#include <Protocol/BlockIo.h>
-#include <Protocol/FirmwareVolumeBlock.h>
-
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/NorFlashPlatformLib.h>
-#include <Library/UefiLib.h>
-
-#define NOR_FLASH_ERASE_RETRY 10
-
-// Device access macros
-// These are necessary because we use 2 x 16bit parts to make up 32bit data
-
-#define HIGH_16_BITS 0xFFFF0000
-#define LOW_16_BITS 0x0000FFFF
-#define LOW_8_BITS 0x000000FF
-
-#define FOLD_32BIT_INTO_16BIT(value) ( ( value >> 16 ) | ( value & LOW_16_BITS ) )
-
-#define GET_LOW_BYTE(value) ( value & LOW_8_BITS )
-#define GET_HIGH_BYTE(value) ( GET_LOW_BYTE( value >> 16 ) )
-
-// Each command must be sent simultaneously to both chips,
-// i.e. at the lower 16 bits AND at the higher 16 bits
-#define CREATE_NOR_ADDRESS(BaseAddr,OffsetAddr) ((BaseAddr) + ((OffsetAddr) << 2))
-#define CREATE_DUAL_CMD(Cmd) ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) )
-#define SEND_NOR_COMMAND(BaseAddr,Offset,Cmd) MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd))
-#define GET_NOR_BLOCK_ADDRESS(BaseAddr,Lba,LbaSize)( BaseAddr + (UINTN)((Lba) * LbaSize) )
-
-// Status Register Bits
-#define P30_SR_BIT_WRITE (BIT7 << 16 | BIT7)
-#define P30_SR_BIT_ERASE_SUSPEND (BIT6 << 16 | BIT6)
-#define P30_SR_BIT_ERASE (BIT5 << 16 | BIT5)
-#define P30_SR_BIT_PROGRAM (BIT4 << 16 | BIT4)
-#define P30_SR_BIT_VPP (BIT3 << 16 | BIT3)
-#define P30_SR_BIT_PROGRAM_SUSPEND (BIT2 << 16 | BIT2)
-#define P30_SR_BIT_BLOCK_LOCKED (BIT1 << 16 | BIT1)
-#define P30_SR_BIT_BEFP (BIT0 << 16 | BIT0)
-
-// Device Commands for Intel StrataFlash(R) Embedded Memory (P30) Family
-
-// On chip buffer size for buffered programming operations
-// There are 2 chips, each chip can buffer up to 32 (16-bit)words, and each word is 2 bytes.
-// Therefore the total size of the buffer is 2 x 32 x 2 = 128 bytes
-#define P30_MAX_BUFFER_SIZE_IN_BYTES ((UINTN)128)
-#define P30_MAX_BUFFER_SIZE_IN_WORDS (P30_MAX_BUFFER_SIZE_IN_BYTES/((UINTN)4))
-#define MAX_BUFFERED_PROG_ITERATIONS 10000000
-#define BOUNDARY_OF_32_WORDS 0x7F
-
-// CFI Addresses
-#define P30_CFI_ADDR_QUERY_UNIQUE_QRY 0x10
-#define P30_CFI_ADDR_VENDOR_ID 0x13
-
-// CFI Data
-#define CFI_QRY 0x00595251
-
-// READ Commands
-#define P30_CMD_READ_DEVICE_ID 0x0090
-#define P30_CMD_READ_STATUS_REGISTER 0x0070
-#define P30_CMD_CLEAR_STATUS_REGISTER 0x0050
-#define P30_CMD_READ_ARRAY 0x00FF
-#define P30_CMD_READ_CFI_QUERY 0x0098
-
-// WRITE Commands
-#define P30_CMD_WORD_PROGRAM_SETUP 0x0040
-#define P30_CMD_ALTERNATE_WORD_PROGRAM_SETUP 0x0010
-#define P30_CMD_BUFFERED_PROGRAM_SETUP 0x00E8
-#define P30_CMD_BUFFERED_PROGRAM_CONFIRM 0x00D0
-#define P30_CMD_BEFP_SETUP 0x0080
-#define P30_CMD_BEFP_CONFIRM 0x00D0
-
-// ERASE Commands
-#define P30_CMD_BLOCK_ERASE_SETUP 0x0020
-#define P30_CMD_BLOCK_ERASE_CONFIRM 0x00D0
-
-// SUSPEND Commands
-#define P30_CMD_PROGRAM_OR_ERASE_SUSPEND 0x00B0
-#define P30_CMD_SUSPEND_RESUME 0x00D0
-
-// BLOCK LOCKING / UNLOCKING Commands
-#define P30_CMD_LOCK_BLOCK_SETUP 0x0060
-#define P30_CMD_LOCK_BLOCK 0x0001
-#define P30_CMD_UNLOCK_BLOCK 0x00D0
-#define P30_CMD_LOCK_DOWN_BLOCK 0x002F
-
-// PROTECTION Commands
-#define P30_CMD_PROGRAM_PROTECTION_REGISTER_SETUP 0x00C0
-
-// CONFIGURATION Commands
-#define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP 0x0060
-#define P30_CMD_READ_CONFIGURATION_REGISTER 0x0003
-
-#define NOR_FLASH_SIGNATURE SIGNATURE_32('n', 'o', 'r', '0')
-#define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE)
-#define INSTANCE_FROM_BLKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE)
-
-typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE;
-
-typedef EFI_STATUS (*NOR_FLASH_INITIALIZE) (NOR_FLASH_INSTANCE* Instance);
-
-typedef struct {
- VENDOR_DEVICE_PATH Vendor;
- EFI_DEVICE_PATH_PROTOCOL End;
-} NOR_FLASH_DEVICE_PATH;
-
-struct _NOR_FLASH_INSTANCE {
- UINT32 Signature;
- EFI_HANDLE Handle;
-
- BOOLEAN Initialized;
- NOR_FLASH_INITIALIZE Initialize;
-
- UINTN DeviceBaseAddress;
- UINTN RegionBaseAddress;
- UINTN Size;
- EFI_LBA StartLba;
-
- EFI_BLOCK_IO_PROTOCOL BlockIoProtocol;
- EFI_BLOCK_IO_MEDIA Media;
-
- BOOLEAN SupportFvb;
- EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL FvbProtocol;
-
- NOR_FLASH_DEVICE_PATH DevicePath;
-};
-
-EFI_STATUS
-NorFlashReadCfiData (
- IN UINTN DeviceBaseAddress,
- IN UINTN CFI_Offset,
- IN UINT32 NumberOfBytes,
- OUT UINT32 *Data
- );
-
-EFI_STATUS
-NorFlashWriteBuffer (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN TargetAddress,
- IN UINTN BufferSizeInBytes,
- IN UINT32 *Buffer
- );
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoReset (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN BOOLEAN ExtendedVerification
- );
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoReadBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- OUT VOID *Buffer
-);
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoWriteBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- IN VOID *Buffer
-);
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoFlushBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This
-);
-
-
-//
-// NorFlashFvbDxe.c
-//
-
-EFI_STATUS
-EFIAPI
-NorFlashFvbInitialize (
- IN NOR_FLASH_INSTANCE* Instance
- );
-
-EFI_STATUS
-EFIAPI
-FvbGetAttributes(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- OUT EFI_FVB_ATTRIBUTES_2 *Attributes
- );
-
-EFI_STATUS
-EFIAPI
-FvbSetAttributes(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
- );
-
-EFI_STATUS
-EFIAPI
-FvbGetPhysicalAddress(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- OUT EFI_PHYSICAL_ADDRESS *Address
- );
-
-EFI_STATUS
-EFIAPI
-FvbGetBlockSize(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN EFI_LBA Lba,
- OUT UINTN *BlockSize,
- OUT UINTN *NumberOfBlocks
- );
-
-EFI_STATUS
-EFIAPI
-FvbRead(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN EFI_LBA Lba,
- IN UINTN Offset,
- IN OUT UINTN *NumBytes,
- IN OUT UINT8 *Buffer
- );
-
-EFI_STATUS
-EFIAPI
-FvbWrite(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN EFI_LBA Lba,
- IN UINTN Offset,
- IN OUT UINTN *NumBytes,
- IN UINT8 *Buffer
- );
-
-EFI_STATUS
-EFIAPI
-FvbEraseBlocks(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- ...
- );
-
-//
-// NorFlashDxe.c
-//
-
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
- IN NOR_FLASH_INSTANCE *Instance,
- IN UINTN BlockAddress
- );
-
-EFI_STATUS
-NorFlashWriteSingleBlock (
- IN NOR_FLASH_INSTANCE *Instance,
- IN EFI_LBA Lba,
- IN UINT32 *DataBuffer,
- IN UINT32 BlockSizeInWords
- );
-
-EFI_STATUS
-NorFlashWriteBlocks (
- IN NOR_FLASH_INSTANCE *Instance,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- IN VOID *Buffer
- );
-
-EFI_STATUS
-NorFlashReadBlocks (
- IN NOR_FLASH_INSTANCE *Instance,
- IN EFI_LBA Lba,
- IN UINTN BufferSizeInBytes,
- OUT VOID *Buffer
- );
-
-EFI_STATUS
-NorFlashReset (
- IN NOR_FLASH_INSTANCE *Instance
- );
-
-#endif /* __NOR_FLASH_DXE_H__ */
+/** @file NorFlashDxe.h
+
+ Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __NOR_FLASH_DXE_H__
+#define __NOR_FLASH_DXE_H__
+
+
+#include <Base.h>
+#include <PiDxe.h>
+
+#include <Protocol/BlockIo.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/NorFlashPlatformLib.h>
+#include <Library/UefiLib.h>
+
+#define NOR_FLASH_ERASE_RETRY 10
+
+// Device access macros
+// These are necessary because we use 2 x 16bit parts to make up 32bit data
+
+#define HIGH_16_BITS 0xFFFF0000
+#define LOW_16_BITS 0x0000FFFF
+#define LOW_8_BITS 0x000000FF
+
+#define FOLD_32BIT_INTO_16BIT(value) ( ( value >> 16 ) | ( value & LOW_16_BITS ) )
+
+#define GET_LOW_BYTE(value) ( value & LOW_8_BITS )
+#define GET_HIGH_BYTE(value) ( GET_LOW_BYTE( value >> 16 ) )
+
+// Each command must be sent simultaneously to both chips,
+// i.e. at the lower 16 bits AND at the higher 16 bits
+#define CREATE_NOR_ADDRESS(BaseAddr,OffsetAddr) ((BaseAddr) + ((OffsetAddr) << 2))
+#define CREATE_DUAL_CMD(Cmd) ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) )
+#define SEND_NOR_COMMAND(BaseAddr,Offset,Cmd) MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd))
+#define GET_NOR_BLOCK_ADDRESS(BaseAddr,Lba,LbaSize)( BaseAddr + (UINTN)((Lba) * LbaSize) )
+
+// Status Register Bits
+#define P30_SR_BIT_WRITE (BIT7 << 16 | BIT7)
+#define P30_SR_BIT_ERASE_SUSPEND (BIT6 << 16 | BIT6)
+#define P30_SR_BIT_ERASE (BIT5 << 16 | BIT5)
+#define P30_SR_BIT_PROGRAM (BIT4 << 16 | BIT4)
+#define P30_SR_BIT_VPP (BIT3 << 16 | BIT3)
+#define P30_SR_BIT_PROGRAM_SUSPEND (BIT2 << 16 | BIT2)
+#define P30_SR_BIT_BLOCK_LOCKED (BIT1 << 16 | BIT1)
+#define P30_SR_BIT_BEFP (BIT0 << 16 | BIT0)
+
+// Device Commands for Intel StrataFlash(R) Embedded Memory (P30) Family
+
+// On chip buffer size for buffered programming operations
+// There are 2 chips, each chip can buffer up to 32 (16-bit)words, and each word is 2 bytes.
+// Therefore the total size of the buffer is 2 x 32 x 2 = 128 bytes
+#define P30_MAX_BUFFER_SIZE_IN_BYTES ((UINTN)128)
+#define P30_MAX_BUFFER_SIZE_IN_WORDS (P30_MAX_BUFFER_SIZE_IN_BYTES/((UINTN)4))
+#define MAX_BUFFERED_PROG_ITERATIONS 10000000
+#define BOUNDARY_OF_32_WORDS 0x7F
+
+// CFI Addresses
+#define P30_CFI_ADDR_QUERY_UNIQUE_QRY 0x10
+#define P30_CFI_ADDR_VENDOR_ID 0x13
+
+// CFI Data
+#define CFI_QRY 0x00595251
+
+// READ Commands
+#define P30_CMD_READ_DEVICE_ID 0x0090
+#define P30_CMD_READ_STATUS_REGISTER 0x0070
+#define P30_CMD_CLEAR_STATUS_REGISTER 0x0050
+#define P30_CMD_READ_ARRAY 0x00FF
+#define P30_CMD_READ_CFI_QUERY 0x0098
+
+// WRITE Commands
+#define P30_CMD_WORD_PROGRAM_SETUP 0x0040
+#define P30_CMD_ALTERNATE_WORD_PROGRAM_SETUP 0x0010
+#define P30_CMD_BUFFERED_PROGRAM_SETUP 0x00E8
+#define P30_CMD_BUFFERED_PROGRAM_CONFIRM 0x00D0
+#define P30_CMD_BEFP_SETUP 0x0080
+#define P30_CMD_BEFP_CONFIRM 0x00D0
+
+// ERASE Commands
+#define P30_CMD_BLOCK_ERASE_SETUP 0x0020
+#define P30_CMD_BLOCK_ERASE_CONFIRM 0x00D0
+
+// SUSPEND Commands
+#define P30_CMD_PROGRAM_OR_ERASE_SUSPEND 0x00B0
+#define P30_CMD_SUSPEND_RESUME 0x00D0
+
+// BLOCK LOCKING / UNLOCKING Commands
+#define P30_CMD_LOCK_BLOCK_SETUP 0x0060
+#define P30_CMD_LOCK_BLOCK 0x0001
+#define P30_CMD_UNLOCK_BLOCK 0x00D0
+#define P30_CMD_LOCK_DOWN_BLOCK 0x002F
+
+// PROTECTION Commands
+#define P30_CMD_PROGRAM_PROTECTION_REGISTER_SETUP 0x00C0
+
+// CONFIGURATION Commands
+#define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP 0x0060
+#define P30_CMD_READ_CONFIGURATION_REGISTER 0x0003
+
+#define NOR_FLASH_SIGNATURE SIGNATURE_32('n', 'o', 'r', '0')
+#define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE)
+#define INSTANCE_FROM_BLKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE)
+
+typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE;
+
+typedef EFI_STATUS (*NOR_FLASH_INITIALIZE) (NOR_FLASH_INSTANCE* Instance);
+
+typedef struct {
+ VENDOR_DEVICE_PATH Vendor;
+ EFI_DEVICE_PATH_PROTOCOL End;
+} NOR_FLASH_DEVICE_PATH;
+
+struct _NOR_FLASH_INSTANCE {
+ UINT32 Signature;
+ EFI_HANDLE Handle;
+
+ BOOLEAN Initialized;
+ NOR_FLASH_INITIALIZE Initialize;
+
+ UINTN DeviceBaseAddress;
+ UINTN RegionBaseAddress;
+ UINTN Size;
+ EFI_LBA StartLba;
+
+ EFI_BLOCK_IO_PROTOCOL BlockIoProtocol;
+ EFI_BLOCK_IO_MEDIA Media;
+
+ BOOLEAN SupportFvb;
+ EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL FvbProtocol;
+
+ NOR_FLASH_DEVICE_PATH DevicePath;
+};
+
+EFI_STATUS
+NorFlashReadCfiData (
+ IN UINTN DeviceBaseAddress,
+ IN UINTN CFI_Offset,
+ IN UINT32 NumberOfBytes,
+ OUT UINT32 *Data
+ );
+
+EFI_STATUS
+NorFlashWriteBuffer (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN TargetAddress,
+ IN UINTN BufferSizeInBytes,
+ IN UINT32 *Buffer
+ );
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoReset (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN BOOLEAN ExtendedVerification
+ );
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoReadBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+);
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoWriteBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+);
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoFlushBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This
+);
+
+
+//
+// NorFlashFvbDxe.c
+//
+
+EFI_STATUS
+EFIAPI
+NorFlashFvbInitialize (
+ IN NOR_FLASH_INSTANCE* Instance
+ );
+
+EFI_STATUS
+EFIAPI
+FvbGetAttributes(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ );
+
+EFI_STATUS
+EFIAPI
+FvbSetAttributes(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ );
+
+EFI_STATUS
+EFIAPI
+FvbGetPhysicalAddress(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ OUT EFI_PHYSICAL_ADDRESS *Address
+ );
+
+EFI_STATUS
+EFIAPI
+FvbGetBlockSize(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ OUT UINTN *BlockSize,
+ OUT UINTN *NumberOfBlocks
+ );
+
+EFI_STATUS
+EFIAPI
+FvbRead(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN OUT UINT8 *Buffer
+ );
+
+EFI_STATUS
+EFIAPI
+FvbWrite(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ );
+
+EFI_STATUS
+EFIAPI
+FvbEraseBlocks(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ ...
+ );
+
+//
+// NorFlashDxe.c
+//
+
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ );
+
+EFI_STATUS
+NorFlashWriteSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINT32 *DataBuffer,
+ IN UINT32 BlockSizeInWords
+ );
+
+EFI_STATUS
+NorFlashWriteBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+ );
+
+EFI_STATUS
+NorFlashReadBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ );
+
+EFI_STATUS
+NorFlashReset (
+ IN NOR_FLASH_INSTANCE *Instance
+ );
+
+#endif /* __NOR_FLASH_DXE_H__ */
diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
index d32f0f79d..97c66008f 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
@@ -1,68 +1,68 @@
-#/** @file
-#
-# Component description file for NorFlashDxe module
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmVeNorFlashDxe
- FILE_GUID = 93E34C7E-B50E-11DF-9223-2443DFD72085
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- ENTRY_POINT = NorFlashInitialise
-
-[Sources.common]
- NorFlashDxe.c
- NorFlashFvbDxe.c
- NorFlashBlockIoDxe.c
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- IoLib
- BaseLib
- DebugLib
- HobLib
- NorFlashPlatformLib
- UefiLib
- UefiDriverEntryPoint
- UefiBootServicesTableLib
-
-[Guids]
- gEfiSystemNvDataFvGuid
- gEfiVariableGuid
-
-[Protocols]
- gEfiBlockIoProtocolGuid
- gEfiDevicePathProtocolGuid
- gEfiFirmwareVolumeBlockProtocolGuid
-
-[Pcd.common]
- gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase
- gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
- gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase
- gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
- gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase
- gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
-
- gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked
-
-[Depex]
- #
- # NorFlashDxe must be loaded before VariableRuntimeDxe in case empty flash needs populating with default values
- #
- BEFORE gVariableRuntimeDxeFileGuid
+#/** @file
+#
+# Component description file for NorFlashDxe module
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmVeNorFlashDxe
+ FILE_GUID = 93E34C7E-B50E-11DF-9223-2443DFD72085
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = NorFlashInitialise
+
+[Sources.common]
+ NorFlashDxe.c
+ NorFlashFvbDxe.c
+ NorFlashBlockIoDxe.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ IoLib
+ BaseLib
+ DebugLib
+ HobLib
+ NorFlashPlatformLib
+ UefiLib
+ UefiDriverEntryPoint
+ UefiBootServicesTableLib
+
+[Guids]
+ gEfiSystemNvDataFvGuid
+ gEfiVariableGuid
+
+[Protocols]
+ gEfiBlockIoProtocolGuid
+ gEfiDevicePathProtocolGuid
+ gEfiFirmwareVolumeBlockProtocolGuid
+
+[Pcd.common]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
+
+ gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked
+
+[Depex]
+ #
+ # NorFlashDxe must be loaded before VariableRuntimeDxe in case empty flash needs populating with default values
+ #
+ BEFORE gVariableRuntimeDxeFileGuid
diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvbDxe.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvbDxe.c
index 29de96482..ab6304ba1 100644
--- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvbDxe.c
+++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvbDxe.c
@@ -1,812 +1,812 @@
-/*++ @file NorFlashFvbDxe.c
-
- Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
- --*/
-
-#include <PiDxe.h>
-
-#include <Library/PcdLib.h>
-#include <Library/BaseLib.h>
-#include <Library/HobLib.h>
-#include <Library/UefiLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-
-#include <Guid/VariableFormat.h>
-#include <Guid/SystemNvDataGuid.h>
-
-#include "NorFlashDxe.h"
-
-
-///
-/// The Firmware Volume Block Protocol is the low-level interface
-/// to a firmware volume. File-level access to a firmware volume
-/// should not be done using the Firmware Volume Block Protocol.
-/// Normal access to a firmware volume must use the Firmware
-/// Volume Protocol. Typically, only the file system driver that
-/// produces the Firmware Volume Protocol will bind to the
-/// Firmware Volume Block Protocol.
-///
-
-/**
- Initialises the FV Header and Variable Store Header
- to support variable operations.
-
- @param[in] Ptr - Location to initialise the headers
-
-**/
-EFI_STATUS
-InitializeFvAndVariableStoreHeaders (
- IN NOR_FLASH_INSTANCE *Instance
- )
-{
- EFI_STATUS Status;
- VOID* Headers;
- UINTN HeadersLength;
- EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;
- VARIABLE_STORE_HEADER *VariableStoreHeader;
-
- if (!Instance->Initialized && Instance->Initialize) {
- Instance->Initialize (Instance);
- }
-
- HeadersLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY) + sizeof(VARIABLE_STORE_HEADER);
- Headers = AllocateZeroPool(HeadersLength);
-
- // FirmwareVolumeHeader->FvLength is declared to have the Variable area AND the FTW working area AND the FTW Spare contiguous.
- ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) + PcdGet32(PcdFlashNvStorageVariableSize) == PcdGet32(PcdFlashNvStorageFtwWorkingBase));
- ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) == PcdGet32(PcdFlashNvStorageFtwSpareBase));
-
- // Check if the size of the area is at least one block size
- ASSERT((PcdGet32(PcdFlashNvStorageVariableSize) > 0) && (PcdGet32(PcdFlashNvStorageVariableSize) / Instance->Media.BlockSize > 0));
- ASSERT((PcdGet32(PcdFlashNvStorageFtwWorkingSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwWorkingSize) / Instance->Media.BlockSize > 0));
- ASSERT((PcdGet32(PcdFlashNvStorageFtwSpareSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwSpareSize) / Instance->Media.BlockSize > 0));
-
- // Ensure the Variable area Base Addresses are aligned on a block size boundaries
- ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) % Instance->Media.BlockSize == 0);
- ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) % Instance->Media.BlockSize == 0);
- ASSERT(PcdGet32(PcdFlashNvStorageFtwSpareBase) % Instance->Media.BlockSize == 0);
-
- //
- // EFI_FIRMWARE_VOLUME_HEADER
- //
- FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Headers;
- CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid);
- FirmwareVolumeHeader->FvLength =
- PcdGet32(PcdFlashNvStorageVariableSize) +
- PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
- PcdGet32(PcdFlashNvStorageFtwSpareSize);
- FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE;
- FirmwareVolumeHeader->Attributes = (EFI_FVB_ATTRIBUTES_2) (
- EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
- EFI_FVB2_READ_STATUS | // Reads are currently enabled
- EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
- EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
- EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1')
- EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
- EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled
- );
- FirmwareVolumeHeader->HeaderLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY);
- FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;
- FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1;
- FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize;
- FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;
- FirmwareVolumeHeader->BlockMap[1].Length = 0;
- FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16*)FirmwareVolumeHeader,FirmwareVolumeHeader->HeaderLength);
-
- //
- // VARIABLE_STORE_HEADER
- //
- VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINT32)Headers + FirmwareVolumeHeader->HeaderLength);
- CopyGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid);
- VariableStoreHeader->Size = PcdGet32(PcdFlashNvStorageVariableSize) - FirmwareVolumeHeader->HeaderLength;
- VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED;
- VariableStoreHeader->State = VARIABLE_STORE_HEALTHY;
-
- // Install the combined super-header in the NorFlash
- Status = FvbWrite (&Instance->FvbProtocol, 0, 0, &HeadersLength, Headers);
-
- FreePool (Headers);
- return Status;
-}
-
-/**
- Check the integrity of firmware volume header.
-
- @param[in] FwVolHeader - A pointer to a firmware volume header
-
- @retval EFI_SUCCESS - The firmware volume is consistent
- @retval EFI_NOT_FOUND - The firmware volume has been corrupted.
-
-**/
-EFI_STATUS
-ValidateFvHeader (
- IN NOR_FLASH_INSTANCE *Instance
- )
-{
- UINT16 Checksum;
- EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
- VARIABLE_STORE_HEADER *VariableStoreHeader;
- UINTN VariableStoreLength;
- UINTN FvLength;
-
- FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Instance->RegionBaseAddress;
-
- FvLength = PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
- PcdGet32(PcdFlashNvStorageFtwSpareSize);
-
- //
- // Verify the header revision, header signature, length
- // Length of FvBlock cannot be 2**64-1
- // HeaderLength cannot be an odd number
- //
- if ( (FwVolHeader->Revision != EFI_FVH_REVISION)
- || (FwVolHeader->Signature != EFI_FVH_SIGNATURE)
- || (FwVolHeader->FvLength != FvLength)
- )
- {
- DEBUG ((EFI_D_ERROR, "ValidateFvHeader: No Firmware Volume header present\n"));
- return EFI_NOT_FOUND;
- }
-
- // Check the Firmware Volume Guid
- if( CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid) == FALSE ) {
- DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Firmware Volume Guid non-compatible\n"));
- return EFI_NOT_FOUND;
- }
-
- // Verify the header checksum
- Checksum = CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLength);
- if (Checksum != 0) {
- DEBUG ((EFI_D_ERROR, "ValidateFvHeader: FV checksum is invalid (Checksum:0x%X)\n",Checksum));
- return EFI_NOT_FOUND;
- }
-
- VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINT32)FwVolHeader + FwVolHeader->HeaderLength);
-
- // Check the Variable Store Guid
- if( CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) == FALSE ) {
- DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Variable Store Guid non-compatible\n"));
- return EFI_NOT_FOUND;
- }
-
- VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) - FwVolHeader->HeaderLength;
- if (VariableStoreHeader->Size != VariableStoreLength) {
- DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Variable Store Length does not match\n"));
- return EFI_NOT_FOUND;
- }
-
- return EFI_SUCCESS;
-}
-
-/**
- The GetAttributes() function retrieves the attributes and
- current settings of the block.
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
-
- @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the attributes and
- current settings are returned.
- Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
-
- @retval EFI_SUCCESS The firmware volume attributes were returned.
-
- **/
-EFI_STATUS
-EFIAPI
-FvbGetAttributes(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- OUT EFI_FVB_ATTRIBUTES_2 *Attributes
- )
-{
- EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes;
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_FVB_THIS(This);
-
- FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2) (
-
- EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
- EFI_FVB2_READ_STATUS | // Reads are currently enabled
- EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
- EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
- EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1')
-
- );
-
- // Check if it is write protected
- if (Instance->Media.ReadOnly != TRUE) {
-
- FlashFvbAttributes = FlashFvbAttributes |
- EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
- EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled
- }
-
- *Attributes = FlashFvbAttributes;
-
- DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes));
-
- return EFI_SUCCESS;
-}
-
-/**
- The SetAttributes() function sets configurable firmware volume attributes
- and returns the new settings of the firmware volume.
-
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
-
- @param Attributes On input, Attributes is a pointer to EFI_FVB_ATTRIBUTES_2
- that contains the desired firmware volume settings.
- On successful return, it contains the new settings of
- the firmware volume.
- Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
-
- @retval EFI_SUCCESS The firmware volume attributes were returned.
-
- @retval EFI_INVALID_PARAMETER The attributes requested are in conflict with the capabilities
- as declared in the firmware volume header.
-
- **/
-EFI_STATUS
-EFIAPI
-FvbSetAttributes(
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
- )
-{
- DEBUG ((DEBUG_BLKIO, "FvbSetAttributes(0x%X) is not supported\n",*Attributes));
- return EFI_UNSUPPORTED;
-}
-
-/**
- The GetPhysicalAddress() function retrieves the base address of
- a memory-mapped firmware volume. This function should be called
- only for memory-mapped firmware volumes.
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
-
- @param Address Pointer to a caller-allocated
- EFI_PHYSICAL_ADDRESS that, on successful
- return from GetPhysicalAddress(), contains the
- base address of the firmware volume.
-
- @retval EFI_SUCCESS The firmware volume base address was returned.
-
- @retval EFI_NOT_SUPPORTED The firmware volume is not memory mapped.
-
- **/
-EFI_STATUS
-EFIAPI
-FvbGetPhysicalAddress (
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- OUT EFI_PHYSICAL_ADDRESS *Address
- )
-{
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_FVB_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "FvbGetPhysicalAddress(BaseAddress=0x%08x)\n", Instance->RegionBaseAddress));
-
- ASSERT(Address != NULL);
-
- *Address = PcdGet32 (PcdFlashNvStorageVariableBase);
- return EFI_SUCCESS;
-}
-
-/**
- The GetBlockSize() function retrieves the size of the requested
- block. It also returns the number of additional blocks with
- the identical size. The GetBlockSize() function is used to
- retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).
-
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
-
- @param Lba Indicates the block for which to return the size.
-
- @param BlockSize Pointer to a caller-allocated UINTN in which
- the size of the block is returned.
-
- @param NumberOfBlocks Pointer to a caller-allocated UINTN in
- which the number of consecutive blocks,
- starting with Lba, is returned. All
- blocks in this range have a size of
- BlockSize.
-
-
- @retval EFI_SUCCESS The firmware volume base address was returned.
-
- @retval EFI_INVALID_PARAMETER The requested LBA is out of range.
-
- **/
-EFI_STATUS
-EFIAPI
-FvbGetBlockSize (
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN EFI_LBA Lba,
- OUT UINTN *BlockSize,
- OUT UINTN *NumberOfBlocks
- )
-{
- EFI_STATUS Status;
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_FVB_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock));
-
- if (Lba > Instance->Media.LastBlock) {
- DEBUG ((EFI_D_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock));
- Status = EFI_INVALID_PARAMETER;
- } else {
- // This is easy because in this platform each NorFlash device has equal sized blocks.
- *BlockSize = (UINTN) Instance->Media.BlockSize;
- *NumberOfBlocks = (UINTN) (Instance->Media.LastBlock - Lba + 1);
-
- DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks));
-
- Status = EFI_SUCCESS;
- }
-
- return Status;
-}
-
-/**
- Reads the specified number of bytes into a buffer from the specified block.
-
- The Read() function reads the requested number of bytes from the
- requested block and stores them in the provided buffer.
- Implementations should be mindful that the firmware volume
- might be in the ReadDisabled state. If it is in this state,
- the Read() function must return the status code
- EFI_ACCESS_DENIED without modifying the contents of the
- buffer. The Read() function must also prevent spanning block
- boundaries. If a read is requested that would span a block
- boundary, the read must read up to the boundary but not
- beyond. The output parameter NumBytes must be set to correctly
- indicate the number of bytes actually read. The caller must be
- aware that a read may be partially completed.
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
-
- @param Lba The starting logical block index from which to read.
-
- @param Offset Offset into the block at which to begin reading.
-
- @param NumBytes Pointer to a UINTN.
- At entry, *NumBytes contains the total size of the buffer.
- At exit, *NumBytes contains the total number of bytes read.
-
- @param Buffer Pointer to a caller-allocated buffer that will be used
- to hold the data that is read.
-
- @retval EFI_SUCCESS The firmware volume was read successfully, and contents are
- in Buffer.
-
- @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA boundary.
- On output, NumBytes contains the total number of bytes
- returned in Buffer.
-
- @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state.
-
- @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be read.
-
- **/
-EFI_STATUS
-EFIAPI
-FvbRead (
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN EFI_LBA Lba,
- IN UINTN Offset,
- IN OUT UINTN *NumBytes,
- IN OUT UINT8 *Buffer
- )
-{
- EFI_STATUS Status;
- EFI_STATUS TempStatus;
- UINTN BlockSize;
- UINT8 *BlockBuffer;
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_FVB_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "FvbRead(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
-
- if (!Instance->Initialized && Instance->Initialize) {
- Instance->Initialize(Instance);
- }
-
- Status = EFI_SUCCESS;
- TempStatus = Status;
-
- // Cache the block size to avoid de-referencing pointers all the time
- BlockSize = Instance->Media.BlockSize;
-
- DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
-
- // The read must not span block boundaries.
- // We need to check each variable individually because adding two large values together overflows.
- if ((Offset >= BlockSize) ||
- (*NumBytes > BlockSize) ||
- ((Offset + *NumBytes) > BlockSize)) {
- DEBUG ((EFI_D_ERROR, "FvbRead: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // We must have some bytes to read
- if (*NumBytes == 0) {
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // FixMe: Allow an arbitrary number of bytes to be read out, not just a multiple of block size.
-
- // Allocate runtime memory to read in the NOR Flash data. Variable Services are runtime.
- BlockBuffer = AllocateRuntimePool (BlockSize);
-
- // Check if the memory allocation was successful
- if (BlockBuffer == NULL) {
- DEBUG ((EFI_D_ERROR, "FvbRead: ERROR - Could not allocate BlockBuffer @ 0x%08x.\n", BlockBuffer));
- return EFI_DEVICE_ERROR;
- }
-
- // Read NOR Flash data into shadow buffer
- TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, BlockBuffer);
- if (EFI_ERROR (TempStatus)) {
- // Return one of the pre-approved error statuses
- Status = EFI_DEVICE_ERROR;
- goto FREE_MEMORY;
- }
-
- // Put the data at the appropriate location inside the buffer area
- DEBUG ((DEBUG_BLKIO, "FvbRead: CopyMem( Dst=0x%08x, Src=0x%08x, Size=0x%x ).\n", Buffer, BlockBuffer + Offset, *NumBytes));
-
- CopyMem(Buffer, BlockBuffer + Offset, *NumBytes);
-
-FREE_MEMORY:
- FreePool(BlockBuffer);
- return Status;
-}
-
-/**
- Writes the specified number of bytes from the input buffer to the block.
-
- The Write() function writes the specified number of bytes from
- the provided buffer to the specified block and offset. If the
- firmware volume is sticky write, the caller must ensure that
- all the bits of the specified range to write are in the
- EFI_FVB_ERASE_POLARITY state before calling the Write()
- function, or else the result will be unpredictable. This
- unpredictability arises because, for a sticky-write firmware
- volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY
- state but cannot flip it back again. Before calling the
- Write() function, it is recommended for the caller to first call
- the EraseBlocks() function to erase the specified block to
- write. A block erase cycle will transition bits from the
- (NOT)EFI_FVB_ERASE_POLARITY state back to the
- EFI_FVB_ERASE_POLARITY state. Implementations should be
- mindful that the firmware volume might be in the WriteDisabled
- state. If it is in this state, the Write() function must
- return the status code EFI_ACCESS_DENIED without modifying the
- contents of the firmware volume. The Write() function must
- also prevent spanning block boundaries. If a write is
- requested that spans a block boundary, the write must store up
- to the boundary but not beyond. The output parameter NumBytes
- must be set to correctly indicate the number of bytes actually
- written. The caller must be aware that a write may be
- partially completed. All writes, partial or otherwise, must be
- fully flushed to the hardware before the Write() service
- returns.
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
-
- @param Lba The starting logical block index to write to.
-
- @param Offset Offset into the block at which to begin writing.
-
- @param NumBytes The pointer to a UINTN.
- At entry, *NumBytes contains the total size of the buffer.
- At exit, *NumBytes contains the total number of bytes actually written.
-
- @param Buffer The pointer to a caller-allocated buffer that contains the source for the write.
-
- @retval EFI_SUCCESS The firmware volume was written successfully.
-
- @retval EFI_BAD_BUFFER_SIZE The write was attempted across an LBA boundary.
- On output, NumBytes contains the total number of bytes
- actually written.
-
- @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
-
- @retval EFI_DEVICE_ERROR The block device is malfunctioning and could not be written.
-
-
- **/
-EFI_STATUS
-EFIAPI
-FvbWrite (
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- IN EFI_LBA Lba,
- IN UINTN Offset,
- IN OUT UINTN *NumBytes,
- IN UINT8 *Buffer
- )
-{
- EFI_STATUS Status;
- EFI_STATUS TempStatus;
- UINTN BlockSize;
- UINT8 *BlockBuffer;
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_FVB_THIS(This);
-
- if (!Instance->Initialized && Instance->Initialize) {
- Instance->Initialize(Instance);
- }
-
- DEBUG ((DEBUG_BLKIO, "FvbWrite(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
-
- Status = EFI_SUCCESS;
- TempStatus = Status;
-
- // Detect WriteDisabled state
- if (Instance->Media.ReadOnly == TRUE) {
- DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Can not write: Device is in WriteDisabled state.\n"));
- // It is in WriteDisabled state, return an error right away
- return EFI_ACCESS_DENIED;
- }
-
- // Cache the block size to avoid de-referencing pointers all the time
- BlockSize = Instance->Media.BlockSize;
-
- // The write must not span block boundaries.
- // We need to check each variable individually because adding two large values together overflows.
- if ( ( Offset >= BlockSize ) ||
- ( *NumBytes > BlockSize ) ||
- ( (Offset + *NumBytes) > BlockSize ) ) {
- DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // We must have some bytes to write
- if (*NumBytes == 0) {
- DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
- return EFI_BAD_BUFFER_SIZE;
- }
-
- // Allocate runtime memory to read in the NOR Flash data.
- // Since the intention is to use this with Variable Services and since these are runtime,
- // allocate the memory from the runtime pool.
- BlockBuffer = AllocateRuntimePool (BlockSize);
-
- // Check we did get some memory
- if( BlockBuffer == NULL ) {
- DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Can not allocate BlockBuffer @ 0x%08x.\n", BlockBuffer));
- return EFI_DEVICE_ERROR;
- }
-
- // Read NOR Flash data into shadow buffer
- TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, BlockBuffer);
- if (EFI_ERROR (TempStatus)) {
- // Return one of the pre-approved error statuses
- Status = EFI_DEVICE_ERROR;
- goto FREE_MEMORY;
- }
-
- // Put the data at the appropriate location inside the buffer area
- CopyMem((BlockBuffer + Offset), Buffer, *NumBytes);
-
- // Write the modified buffer back to the NorFlash
- Status = NorFlashWriteBlocks (Instance, Instance->StartLba + Lba, BlockSize, BlockBuffer);
- if (EFI_ERROR (TempStatus)) {
- // Return one of the pre-approved error statuses
- Status = EFI_DEVICE_ERROR;
- goto FREE_MEMORY;
- }
-
-FREE_MEMORY:
- FreePool(BlockBuffer);
- return Status;
-}
-
-/**
- Erases and initialises a firmware volume block.
-
- The EraseBlocks() function erases one or more blocks as denoted
- by the variable argument list. The entire parameter list of
- blocks must be verified before erasing any blocks. If a block is
- requested that does not exist within the associated firmware
- volume (it has a larger index than the last block of the
- firmware volume), the EraseBlocks() function must return the
- status code EFI_INVALID_PARAMETER without modifying the contents
- of the firmware volume. Implementations should be mindful that
- the firmware volume might be in the WriteDisabled state. If it
- is in this state, the EraseBlocks() function must return the
- status code EFI_ACCESS_DENIED without modifying the contents of
- the firmware volume. All calls to EraseBlocks() must be fully
- flushed to the hardware before the EraseBlocks() service
- returns.
-
- @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL
- instance.
-
- @param ... The variable argument list is a list of tuples.
- Each tuple describes a range of LBAs to erase
- and consists of the following:
- - An EFI_LBA that indicates the starting LBA
- - A UINTN that indicates the number of blocks to erase.
-
- The list is terminated with an EFI_LBA_LIST_TERMINATOR.
- For example, the following indicates that two ranges of blocks
- (5-7 and 10-11) are to be erased:
- EraseBlocks (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR);
-
- @retval EFI_SUCCESS The erase request successfully completed.
-
- @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
-
- @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be written.
- The firmware device may have been partially erased.
-
- @retval EFI_INVALID_PARAMETER One or more of the LBAs listed in the variable argument list do
- not exist in the firmware volume.
-
- **/
-EFI_STATUS
-EFIAPI
-FvbEraseBlocks (
- IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
- ...
- )
-{
- EFI_STATUS Status;
- VA_LIST Args;
- UINTN BlockAddress; // Physical address of Lba to erase
- EFI_LBA StartingLba; // Lba from which we start erasing
- UINTN NumOfLba; // Number of Lba blocks to erase
- NOR_FLASH_INSTANCE *Instance;
-
- Instance = INSTANCE_FROM_FVB_THIS(This);
-
- DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks()\n"));
-
- Status = EFI_SUCCESS;
-
- // Detect WriteDisabled state
- if (Instance->Media.ReadOnly == TRUE) {
- // Firmware volume is in WriteDisabled state
- DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n"));
- return EFI_ACCESS_DENIED;
- }
-
- // Before erasing, check the entire list of parameters to ensure all specified blocks are valid
-
- VA_START (Args, This);
- do {
- // Get the Lba from which we start erasing
- StartingLba = VA_ARG (Args, EFI_LBA);
-
- // Have we reached the end of the list?
- if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
- //Exit the while loop
- break;
- }
-
- // How many Lba blocks are we requested to erase?
- NumOfLba = VA_ARG (Args, UINT32);
-
- // All blocks must be within range
- DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%d - 1 ) > LastBlock=%ld.\n", Instance->StartLba + StartingLba, NumOfLba, Instance->Media.LastBlock));
- if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) {
- VA_END (Args);
- DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n"));
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }
- } while (TRUE);
- VA_END (Args);
-
- //
- // To get here, all must be ok, so start erasing
- //
- VA_START (Args, This);
- do {
- // Get the Lba from which we start erasing
- StartingLba = VA_ARG (Args, EFI_LBA);
-
- // Have we reached the end of the list?
- if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
- // Exit the while loop
- break;
- }
-
- // How many Lba blocks are we requested to erase?
- NumOfLba = VA_ARG (Args, UINT32);
-
- // Go through each one and erase it
- while (NumOfLba > 0) {
-
- // Get the physical address of Lba to erase
- BlockAddress = GET_NOR_BLOCK_ADDRESS (
- Instance->RegionBaseAddress,
- Instance->StartLba + StartingLba,
- Instance->Media.BlockSize
- );
-
- // Erase it
- DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Erasing Lba=%ld @ 0x%08x.\n", Instance->StartLba + StartingLba, BlockAddress));
- Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
- if (EFI_ERROR(Status)) {
- VA_END (Args);
- Status = EFI_DEVICE_ERROR;
- goto EXIT;
- }
-
- // Move to the next Lba
- StartingLba++;
- NumOfLba--;
- }
- } while (TRUE);
- VA_END (Args);
-
-EXIT:
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-NorFlashFvbInitialize (
- IN NOR_FLASH_INSTANCE* Instance
- )
-{
- EFI_STATUS Status;
- UINT32 FvbNumLba;
- EFI_BOOT_MODE BootMode;
-
- DEBUG((DEBUG_BLKIO,"NorFlashFvbInitialize\n"));
-
- Instance->Initialized = TRUE;
-
- // Set the index of the first LBA for the FVB
- Instance->StartLba = (PcdGet32 (PcdFlashNvStorageVariableBase) - Instance->RegionBaseAddress) / Instance->Media.BlockSize;
-
- BootMode = GetBootModeHob ();
- if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) {
- Status = EFI_INVALID_PARAMETER;
- } else {
- // Determine if there is a valid header at the beginning of the NorFlash
- Status = ValidateFvHeader (Instance);
- }
-
- // Install the Default FVB header if required
- if (EFI_ERROR(Status)) {
- // There is no valid header, so time to install one.
- DEBUG((EFI_D_ERROR,"NorFlashFvbInitialize: ERROR - The FVB Header is not valid. Installing a correct one for this volume.\n"));
-
- // Erase all the NorFlash that is reserved for variable storage
- FvbNumLba = (PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + PcdGet32(PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize;
-
- Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Install all appropriate headers
- Status = InitializeFvAndVariableStoreHeaders (Instance);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- }
- return Status;
-}
+/*++ @file NorFlashFvbDxe.c
+
+ Copyright (c) 2011-201333, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+ --*/
+
+#include <PiDxe.h>
+
+#include <Library/PcdLib.h>
+#include <Library/BaseLib.h>
+#include <Library/HobLib.h>
+#include <Library/UefiLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include <Guid/VariableFormat.h>
+#include <Guid/SystemNvDataGuid.h>
+
+#include "NorFlashDxe.h"
+
+
+///
+/// The Firmware Volume Block Protocol is the low-level interface
+/// to a firmware volume. File-level access to a firmware volume
+/// should not be done using the Firmware Volume Block Protocol.
+/// Normal access to a firmware volume must use the Firmware
+/// Volume Protocol. Typically, only the file system driver that
+/// produces the Firmware Volume Protocol will bind to the
+/// Firmware Volume Block Protocol.
+///
+
+/**
+ Initialises the FV Header and Variable Store Header
+ to support variable operations.
+
+ @param[in] Ptr - Location to initialise the headers
+
+**/
+EFI_STATUS
+InitializeFvAndVariableStoreHeaders (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ EFI_STATUS Status;
+ VOID* Headers;
+ UINTN HeadersLength;
+ EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;
+ VARIABLE_STORE_HEADER *VariableStoreHeader;
+
+ if (!Instance->Initialized && Instance->Initialize) {
+ Instance->Initialize (Instance);
+ }
+
+ HeadersLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY) + sizeof(VARIABLE_STORE_HEADER);
+ Headers = AllocateZeroPool(HeadersLength);
+
+ // FirmwareVolumeHeader->FvLength is declared to have the Variable area AND the FTW working area AND the FTW Spare contiguous.
+ ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) + PcdGet32(PcdFlashNvStorageVariableSize) == PcdGet32(PcdFlashNvStorageFtwWorkingBase));
+ ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) == PcdGet32(PcdFlashNvStorageFtwSpareBase));
+
+ // Check if the size of the area is at least one block size
+ ASSERT((PcdGet32(PcdFlashNvStorageVariableSize) > 0) && (PcdGet32(PcdFlashNvStorageVariableSize) / Instance->Media.BlockSize > 0));
+ ASSERT((PcdGet32(PcdFlashNvStorageFtwWorkingSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwWorkingSize) / Instance->Media.BlockSize > 0));
+ ASSERT((PcdGet32(PcdFlashNvStorageFtwSpareSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwSpareSize) / Instance->Media.BlockSize > 0));
+
+ // Ensure the Variable area Base Addresses are aligned on a block size boundaries
+ ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) % Instance->Media.BlockSize == 0);
+ ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) % Instance->Media.BlockSize == 0);
+ ASSERT(PcdGet32(PcdFlashNvStorageFtwSpareBase) % Instance->Media.BlockSize == 0);
+
+ //
+ // EFI_FIRMWARE_VOLUME_HEADER
+ //
+ FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Headers;
+ CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid);
+ FirmwareVolumeHeader->FvLength =
+ PcdGet32(PcdFlashNvStorageVariableSize) +
+ PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
+ PcdGet32(PcdFlashNvStorageFtwSpareSize);
+ FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE;
+ FirmwareVolumeHeader->Attributes = (EFI_FVB_ATTRIBUTES_2) (
+ EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
+ EFI_FVB2_READ_STATUS | // Reads are currently enabled
+ EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
+ EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
+ EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1')
+ EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
+ EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled
+ );
+ FirmwareVolumeHeader->HeaderLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY);
+ FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;
+ FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1;
+ FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize;
+ FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;
+ FirmwareVolumeHeader->BlockMap[1].Length = 0;
+ FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16*)FirmwareVolumeHeader,FirmwareVolumeHeader->HeaderLength);
+
+ //
+ // VARIABLE_STORE_HEADER
+ //
+ VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)Headers + FirmwareVolumeHeader->HeaderLength);
+ CopyGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid);
+ VariableStoreHeader->Size = PcdGet32(PcdFlashNvStorageVariableSize) - FirmwareVolumeHeader->HeaderLength;
+ VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED;
+ VariableStoreHeader->State = VARIABLE_STORE_HEALTHY;
+
+ // Install the combined super-header in the NorFlash
+ Status = FvbWrite (&Instance->FvbProtocol, 0, 0, &HeadersLength, Headers);
+
+ FreePool (Headers);
+ return Status;
+}
+
+/**
+ Check the integrity of firmware volume header.
+
+ @param[in] FwVolHeader - A pointer to a firmware volume header
+
+ @retval EFI_SUCCESS - The firmware volume is consistent
+ @retval EFI_NOT_FOUND - The firmware volume has been corrupted.
+
+**/
+EFI_STATUS
+ValidateFvHeader (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ UINT16 Checksum;
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ VARIABLE_STORE_HEADER *VariableStoreHeader;
+ UINTN VariableStoreLength;
+ UINTN FvLength;
+
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Instance->RegionBaseAddress;
+
+ FvLength = PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
+ PcdGet32(PcdFlashNvStorageFtwSpareSize);
+
+ //
+ // Verify the header revision, header signature, length
+ // Length of FvBlock cannot be 2**64-1
+ // HeaderLength cannot be an odd number
+ //
+ if ( (FwVolHeader->Revision != EFI_FVH_REVISION)
+ || (FwVolHeader->Signature != EFI_FVH_SIGNATURE)
+ || (FwVolHeader->FvLength != FvLength)
+ )
+ {
+ DEBUG ((EFI_D_ERROR, "ValidateFvHeader: No Firmware Volume header present\n"));
+ return EFI_NOT_FOUND;
+ }
+
+ // Check the Firmware Volume Guid
+ if( CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid) == FALSE ) {
+ DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Firmware Volume Guid non-compatible\n"));
+ return EFI_NOT_FOUND;
+ }
+
+ // Verify the header checksum
+ Checksum = CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLength);
+ if (Checksum != 0) {
+ DEBUG ((EFI_D_ERROR, "ValidateFvHeader: FV checksum is invalid (Checksum:0x%X)\n",Checksum));
+ return EFI_NOT_FOUND;
+ }
+
+ VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)FwVolHeader + FwVolHeader->HeaderLength);
+
+ // Check the Variable Store Guid
+ if( CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) == FALSE ) {
+ DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Variable Store Guid non-compatible\n"));
+ return EFI_NOT_FOUND;
+ }
+
+ VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) - FwVolHeader->HeaderLength;
+ if (VariableStoreHeader->Size != VariableStoreLength) {
+ DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Variable Store Length does not match\n"));
+ return EFI_NOT_FOUND;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The GetAttributes() function retrieves the attributes and
+ current settings of the block.
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
+
+ @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the attributes and
+ current settings are returned.
+ Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
+
+ @retval EFI_SUCCESS The firmware volume attributes were returned.
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbGetAttributes(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ )
+{
+ EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes;
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_FVB_THIS(This);
+
+ FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2) (
+
+ EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
+ EFI_FVB2_READ_STATUS | // Reads are currently enabled
+ EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
+ EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
+ EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1')
+
+ );
+
+ // Check if it is write protected
+ if (Instance->Media.ReadOnly != TRUE) {
+
+ FlashFvbAttributes = FlashFvbAttributes |
+ EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
+ EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled
+ }
+
+ *Attributes = FlashFvbAttributes;
+
+ DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The SetAttributes() function sets configurable firmware volume attributes
+ and returns the new settings of the firmware volume.
+
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
+
+ @param Attributes On input, Attributes is a pointer to EFI_FVB_ATTRIBUTES_2
+ that contains the desired firmware volume settings.
+ On successful return, it contains the new settings of
+ the firmware volume.
+ Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
+
+ @retval EFI_SUCCESS The firmware volume attributes were returned.
+
+ @retval EFI_INVALID_PARAMETER The attributes requested are in conflict with the capabilities
+ as declared in the firmware volume header.
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbSetAttributes(
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ )
+{
+ DEBUG ((DEBUG_BLKIO, "FvbSetAttributes(0x%X) is not supported\n",*Attributes));
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ The GetPhysicalAddress() function retrieves the base address of
+ a memory-mapped firmware volume. This function should be called
+ only for memory-mapped firmware volumes.
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
+
+ @param Address Pointer to a caller-allocated
+ EFI_PHYSICAL_ADDRESS that, on successful
+ return from GetPhysicalAddress(), contains the
+ base address of the firmware volume.
+
+ @retval EFI_SUCCESS The firmware volume base address was returned.
+
+ @retval EFI_NOT_SUPPORTED The firmware volume is not memory mapped.
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbGetPhysicalAddress (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ OUT EFI_PHYSICAL_ADDRESS *Address
+ )
+{
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_FVB_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "FvbGetPhysicalAddress(BaseAddress=0x%08x)\n", Instance->RegionBaseAddress));
+
+ ASSERT(Address != NULL);
+
+ *Address = PcdGet32 (PcdFlashNvStorageVariableBase);
+ return EFI_SUCCESS;
+}
+
+/**
+ The GetBlockSize() function retrieves the size of the requested
+ block. It also returns the number of additional blocks with
+ the identical size. The GetBlockSize() function is used to
+ retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).
+
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
+
+ @param Lba Indicates the block for which to return the size.
+
+ @param BlockSize Pointer to a caller-allocated UINTN in which
+ the size of the block is returned.
+
+ @param NumberOfBlocks Pointer to a caller-allocated UINTN in
+ which the number of consecutive blocks,
+ starting with Lba, is returned. All
+ blocks in this range have a size of
+ BlockSize.
+
+
+ @retval EFI_SUCCESS The firmware volume base address was returned.
+
+ @retval EFI_INVALID_PARAMETER The requested LBA is out of range.
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbGetBlockSize (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ OUT UINTN *BlockSize,
+ OUT UINTN *NumberOfBlocks
+ )
+{
+ EFI_STATUS Status;
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_FVB_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock));
+
+ if (Lba > Instance->Media.LastBlock) {
+ DEBUG ((EFI_D_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock));
+ Status = EFI_INVALID_PARAMETER;
+ } else {
+ // This is easy because in this platform each NorFlash device has equal sized blocks.
+ *BlockSize = (UINTN) Instance->Media.BlockSize;
+ *NumberOfBlocks = (UINTN) (Instance->Media.LastBlock - Lba + 1);
+
+ DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks));
+
+ Status = EFI_SUCCESS;
+ }
+
+ return Status;
+}
+
+/**
+ Reads the specified number of bytes into a buffer from the specified block.
+
+ The Read() function reads the requested number of bytes from the
+ requested block and stores them in the provided buffer.
+ Implementations should be mindful that the firmware volume
+ might be in the ReadDisabled state. If it is in this state,
+ the Read() function must return the status code
+ EFI_ACCESS_DENIED without modifying the contents of the
+ buffer. The Read() function must also prevent spanning block
+ boundaries. If a read is requested that would span a block
+ boundary, the read must read up to the boundary but not
+ beyond. The output parameter NumBytes must be set to correctly
+ indicate the number of bytes actually read. The caller must be
+ aware that a read may be partially completed.
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
+
+ @param Lba The starting logical block index from which to read.
+
+ @param Offset Offset into the block at which to begin reading.
+
+ @param NumBytes Pointer to a UINTN.
+ At entry, *NumBytes contains the total size of the buffer.
+ At exit, *NumBytes contains the total number of bytes read.
+
+ @param Buffer Pointer to a caller-allocated buffer that will be used
+ to hold the data that is read.
+
+ @retval EFI_SUCCESS The firmware volume was read successfully, and contents are
+ in Buffer.
+
+ @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA boundary.
+ On output, NumBytes contains the total number of bytes
+ returned in Buffer.
+
+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state.
+
+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be read.
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbRead (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN OUT UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ EFI_STATUS TempStatus;
+ UINTN BlockSize;
+ UINT8 *BlockBuffer;
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_FVB_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "FvbRead(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
+
+ if (!Instance->Initialized && Instance->Initialize) {
+ Instance->Initialize(Instance);
+ }
+
+ Status = EFI_SUCCESS;
+ TempStatus = Status;
+
+ // Cache the block size to avoid de-referencing pointers all the time
+ BlockSize = Instance->Media.BlockSize;
+
+ DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
+
+ // The read must not span block boundaries.
+ // We need to check each variable individually because adding two large values together overflows.
+ if ((Offset >= BlockSize) ||
+ (*NumBytes > BlockSize) ||
+ ((Offset + *NumBytes) > BlockSize)) {
+ DEBUG ((EFI_D_ERROR, "FvbRead: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // We must have some bytes to read
+ if (*NumBytes == 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // FixMe: Allow an arbitrary number of bytes to be read out, not just a multiple of block size.
+
+ // Allocate runtime memory to read in the NOR Flash data. Variable Services are runtime.
+ BlockBuffer = AllocateRuntimePool (BlockSize);
+
+ // Check if the memory allocation was successful
+ if (BlockBuffer == NULL) {
+ DEBUG ((EFI_D_ERROR, "FvbRead: ERROR - Could not allocate BlockBuffer @ 0x%08x.\n", BlockBuffer));
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Read NOR Flash data into shadow buffer
+ TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, BlockBuffer);
+ if (EFI_ERROR (TempStatus)) {
+ // Return one of the pre-approved error statuses
+ Status = EFI_DEVICE_ERROR;
+ goto FREE_MEMORY;
+ }
+
+ // Put the data at the appropriate location inside the buffer area
+ DEBUG ((DEBUG_BLKIO, "FvbRead: CopyMem( Dst=0x%08x, Src=0x%08x, Size=0x%x ).\n", Buffer, BlockBuffer + Offset, *NumBytes));
+
+ CopyMem(Buffer, BlockBuffer + Offset, *NumBytes);
+
+FREE_MEMORY:
+ FreePool(BlockBuffer);
+ return Status;
+}
+
+/**
+ Writes the specified number of bytes from the input buffer to the block.
+
+ The Write() function writes the specified number of bytes from
+ the provided buffer to the specified block and offset. If the
+ firmware volume is sticky write, the caller must ensure that
+ all the bits of the specified range to write are in the
+ EFI_FVB_ERASE_POLARITY state before calling the Write()
+ function, or else the result will be unpredictable. This
+ unpredictability arises because, for a sticky-write firmware
+ volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY
+ state but cannot flip it back again. Before calling the
+ Write() function, it is recommended for the caller to first call
+ the EraseBlocks() function to erase the specified block to
+ write. A block erase cycle will transition bits from the
+ (NOT)EFI_FVB_ERASE_POLARITY state back to the
+ EFI_FVB_ERASE_POLARITY state. Implementations should be
+ mindful that the firmware volume might be in the WriteDisabled
+ state. If it is in this state, the Write() function must
+ return the status code EFI_ACCESS_DENIED without modifying the
+ contents of the firmware volume. The Write() function must
+ also prevent spanning block boundaries. If a write is
+ requested that spans a block boundary, the write must store up
+ to the boundary but not beyond. The output parameter NumBytes
+ must be set to correctly indicate the number of bytes actually
+ written. The caller must be aware that a write may be
+ partially completed. All writes, partial or otherwise, must be
+ fully flushed to the hardware before the Write() service
+ returns.
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
+
+ @param Lba The starting logical block index to write to.
+
+ @param Offset Offset into the block at which to begin writing.
+
+ @param NumBytes The pointer to a UINTN.
+ At entry, *NumBytes contains the total size of the buffer.
+ At exit, *NumBytes contains the total number of bytes actually written.
+
+ @param Buffer The pointer to a caller-allocated buffer that contains the source for the write.
+
+ @retval EFI_SUCCESS The firmware volume was written successfully.
+
+ @retval EFI_BAD_BUFFER_SIZE The write was attempted across an LBA boundary.
+ On output, NumBytes contains the total number of bytes
+ actually written.
+
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
+
+ @retval EFI_DEVICE_ERROR The block device is malfunctioning and could not be written.
+
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbWrite (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ EFI_STATUS TempStatus;
+ UINTN BlockSize;
+ UINT8 *BlockBuffer;
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_FVB_THIS(This);
+
+ if (!Instance->Initialized && Instance->Initialize) {
+ Instance->Initialize(Instance);
+ }
+
+ DEBUG ((DEBUG_BLKIO, "FvbWrite(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
+
+ Status = EFI_SUCCESS;
+ TempStatus = Status;
+
+ // Detect WriteDisabled state
+ if (Instance->Media.ReadOnly == TRUE) {
+ DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Can not write: Device is in WriteDisabled state.\n"));
+ // It is in WriteDisabled state, return an error right away
+ return EFI_ACCESS_DENIED;
+ }
+
+ // Cache the block size to avoid de-referencing pointers all the time
+ BlockSize = Instance->Media.BlockSize;
+
+ // The write must not span block boundaries.
+ // We need to check each variable individually because adding two large values together overflows.
+ if ( ( Offset >= BlockSize ) ||
+ ( *NumBytes > BlockSize ) ||
+ ( (Offset + *NumBytes) > BlockSize ) ) {
+ DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // We must have some bytes to write
+ if (*NumBytes == 0) {
+ DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // Allocate runtime memory to read in the NOR Flash data.
+ // Since the intention is to use this with Variable Services and since these are runtime,
+ // allocate the memory from the runtime pool.
+ BlockBuffer = AllocateRuntimePool (BlockSize);
+
+ // Check we did get some memory
+ if( BlockBuffer == NULL ) {
+ DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Can not allocate BlockBuffer @ 0x%08x.\n", BlockBuffer));
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Read NOR Flash data into shadow buffer
+ TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, BlockBuffer);
+ if (EFI_ERROR (TempStatus)) {
+ // Return one of the pre-approved error statuses
+ Status = EFI_DEVICE_ERROR;
+ goto FREE_MEMORY;
+ }
+
+ // Put the data at the appropriate location inside the buffer area
+ CopyMem((BlockBuffer + Offset), Buffer, *NumBytes);
+
+ // Write the modified buffer back to the NorFlash
+ Status = NorFlashWriteBlocks (Instance, Instance->StartLba + Lba, BlockSize, BlockBuffer);
+ if (EFI_ERROR (TempStatus)) {
+ // Return one of the pre-approved error statuses
+ Status = EFI_DEVICE_ERROR;
+ goto FREE_MEMORY;
+ }
+
+FREE_MEMORY:
+ FreePool(BlockBuffer);
+ return Status;
+}
+
+/**
+ Erases and initialises a firmware volume block.
+
+ The EraseBlocks() function erases one or more blocks as denoted
+ by the variable argument list. The entire parameter list of
+ blocks must be verified before erasing any blocks. If a block is
+ requested that does not exist within the associated firmware
+ volume (it has a larger index than the last block of the
+ firmware volume), the EraseBlocks() function must return the
+ status code EFI_INVALID_PARAMETER without modifying the contents
+ of the firmware volume. Implementations should be mindful that
+ the firmware volume might be in the WriteDisabled state. If it
+ is in this state, the EraseBlocks() function must return the
+ status code EFI_ACCESS_DENIED without modifying the contents of
+ the firmware volume. All calls to EraseBlocks() must be fully
+ flushed to the hardware before the EraseBlocks() service
+ returns.
+
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL
+ instance.
+
+ @param ... The variable argument list is a list of tuples.
+ Each tuple describes a range of LBAs to erase
+ and consists of the following:
+ - An EFI_LBA that indicates the starting LBA
+ - A UINTN that indicates the number of blocks to erase.
+
+ The list is terminated with an EFI_LBA_LIST_TERMINATOR.
+ For example, the following indicates that two ranges of blocks
+ (5-7 and 10-11) are to be erased:
+ EraseBlocks (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR);
+
+ @retval EFI_SUCCESS The erase request successfully completed.
+
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
+
+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be written.
+ The firmware device may have been partially erased.
+
+ @retval EFI_INVALID_PARAMETER One or more of the LBAs listed in the variable argument list do
+ not exist in the firmware volume.
+
+ **/
+EFI_STATUS
+EFIAPI
+FvbEraseBlocks (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
+ ...
+ )
+{
+ EFI_STATUS Status;
+ VA_LIST Args;
+ UINTN BlockAddress; // Physical address of Lba to erase
+ EFI_LBA StartingLba; // Lba from which we start erasing
+ UINTN NumOfLba; // Number of Lba blocks to erase
+ NOR_FLASH_INSTANCE *Instance;
+
+ Instance = INSTANCE_FROM_FVB_THIS(This);
+
+ DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks()\n"));
+
+ Status = EFI_SUCCESS;
+
+ // Detect WriteDisabled state
+ if (Instance->Media.ReadOnly == TRUE) {
+ // Firmware volume is in WriteDisabled state
+ DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n"));
+ return EFI_ACCESS_DENIED;
+ }
+
+ // Before erasing, check the entire list of parameters to ensure all specified blocks are valid
+
+ VA_START (Args, This);
+ do {
+ // Get the Lba from which we start erasing
+ StartingLba = VA_ARG (Args, EFI_LBA);
+
+ // Have we reached the end of the list?
+ if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
+ //Exit the while loop
+ break;
+ }
+
+ // How many Lba blocks are we requested to erase?
+ NumOfLba = VA_ARG (Args, UINT32);
+
+ // All blocks must be within range
+ DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%d - 1 ) > LastBlock=%ld.\n", Instance->StartLba + StartingLba, NumOfLba, Instance->Media.LastBlock));
+ if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) {
+ VA_END (Args);
+ DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n"));
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }
+ } while (TRUE);
+ VA_END (Args);
+
+ //
+ // To get here, all must be ok, so start erasing
+ //
+ VA_START (Args, This);
+ do {
+ // Get the Lba from which we start erasing
+ StartingLba = VA_ARG (Args, EFI_LBA);
+
+ // Have we reached the end of the list?
+ if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
+ // Exit the while loop
+ break;
+ }
+
+ // How many Lba blocks are we requested to erase?
+ NumOfLba = VA_ARG (Args, UINT32);
+
+ // Go through each one and erase it
+ while (NumOfLba > 0) {
+
+ // Get the physical address of Lba to erase
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Instance->StartLba + StartingLba,
+ Instance->Media.BlockSize
+ );
+
+ // Erase it
+ DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Erasing Lba=%ld @ 0x%08x.\n", Instance->StartLba + StartingLba, BlockAddress));
+ Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR(Status)) {
+ VA_END (Args);
+ Status = EFI_DEVICE_ERROR;
+ goto EXIT;
+ }
+
+ // Move to the next Lba
+ StartingLba++;
+ NumOfLba--;
+ }
+ } while (TRUE);
+ VA_END (Args);
+
+EXIT:
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+NorFlashFvbInitialize (
+ IN NOR_FLASH_INSTANCE* Instance
+ )
+{
+ EFI_STATUS Status;
+ UINT32 FvbNumLba;
+ EFI_BOOT_MODE BootMode;
+
+ DEBUG((DEBUG_BLKIO,"NorFlashFvbInitialize\n"));
+
+ Instance->Initialized = TRUE;
+
+ // Set the index of the first LBA for the FVB
+ Instance->StartLba = (PcdGet32 (PcdFlashNvStorageVariableBase) - Instance->RegionBaseAddress) / Instance->Media.BlockSize;
+
+ BootMode = GetBootModeHob ();
+ if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) {
+ Status = EFI_INVALID_PARAMETER;
+ } else {
+ // Determine if there is a valid header at the beginning of the NorFlash
+ Status = ValidateFvHeader (Instance);
+ }
+
+ // Install the Default FVB header if required
+ if (EFI_ERROR(Status)) {
+ // There is no valid header, so time to install one.
+ DEBUG((EFI_D_ERROR,"NorFlashFvbInitialize: ERROR - The FVB Header is not valid. Installing a correct one for this volume.\n"));
+
+ // Erase all the NorFlash that is reserved for variable storage
+ FvbNumLba = (PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + PcdGet32(PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize;
+
+ Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Install all appropriate headers
+ Status = InitializeFvAndVariableStoreHeaders (Instance);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ }
+ return Status;
+}
diff --git a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c
index cb811d89d..ff05662b8 100644
--- a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c
+++ b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.c
@@ -1,344 +1,344 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-
-#include <PiDxe.h>
-
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-
-#include <Protocol/EmbeddedGpio.h>
-#include <Drivers/PL061Gpio.h>
-
-BOOLEAN mPL061Initialized = FALSE;
-
-/**
- Function implementations
-**/
-
-EFI_STATUS
-PL061Identify (
- VOID
- )
-{
- // Check if this is a PrimeCell Peripheral
- if ( (MmioRead8 (PL061_GPIO_PCELL_ID0) != 0x0D)
- || (MmioRead8 (PL061_GPIO_PCELL_ID1) != 0xF0)
- || (MmioRead8 (PL061_GPIO_PCELL_ID2) != 0x05)
- || (MmioRead8 (PL061_GPIO_PCELL_ID3) != 0xB1)) {
- return EFI_NOT_FOUND;
- }
-
- // Check if this PrimeCell Peripheral is the PL061 GPIO
- if ( (MmioRead8 (PL061_GPIO_PERIPH_ID0) != 0x61)
- || (MmioRead8 (PL061_GPIO_PERIPH_ID1) != 0x10)
- || ((MmioRead8 (PL061_GPIO_PERIPH_ID2) & 0xF) != 0x04)
- || (MmioRead8 (PL061_GPIO_PERIPH_ID3) != 0x00)) {
- return EFI_NOT_FOUND;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-PL061Initialize (
- VOID
- )
-{
- EFI_STATUS Status;
-
- // Check if the PL061 GPIO module exists on board
- Status = PL061Identify();
- if (EFI_ERROR (Status)) {
- Status = EFI_DEVICE_ERROR;
- goto EXIT;
- }
-
- // Do other hardware initialisation things here as required
-
- // Disable Interrupts
- //if (MmioRead8 (PL061_GPIO_IE_REG) != 0) {
- // // Ensure interrupts are disabled
- //}
-
- mPL061Initialized = TRUE;
-
- EXIT:
- return Status;
-}
-
-/**
-
-Routine Description:
-
- Gets the state of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin to read
- Value - state of the pin
-
-Returns:
-
- EFI_SUCCESS - GPIO state returned in Value
- EFI_INVALID_PARAMETER - Value is NULL pointer or Gpio pin is out of range
-**/
-EFI_STATUS
-EFIAPI
-Get (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- OUT UINTN *Value
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
-
- if ( (Value == NULL)
- || (Gpio > LAST_GPIO_PIN))
- {
- return EFI_INVALID_PARAMETER;
- }
-
- // Initialize the hardware if not already done
- if (!mPL061Initialized) {
- Status = PL061Initialize();
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- if (MmioRead8 (PL061_GPIO_DATA_REG) & GPIO_PIN_MASK_HIGH_8BIT(Gpio)) {
- *Value = 1;
- } else {
- *Value = 0;
- }
-
- EXIT:
- return Status;
-}
-
-/**
-
-Routine Description:
-
- Sets the state of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin to modify
- Mode - mode to set
-
-Returns:
-
- EFI_SUCCESS - GPIO set as requested
- EFI_UNSUPPORTED - Mode is not supported
- EFI_INVALID_PARAMETER - Gpio pin is out of range
-**/
-EFI_STATUS
-EFIAPI
-Set (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- IN EMBEDDED_GPIO_MODE Mode
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
-
- // Check for errors
- if (Gpio > LAST_GPIO_PIN) {
- Status = EFI_INVALID_PARAMETER;
- goto EXIT;
- }
-
- // Initialize the hardware if not already done
- if (!mPL061Initialized) {
- Status = PL061Initialize();
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
- }
-
- switch (Mode)
- {
- case GPIO_MODE_INPUT:
- // Set the corresponding direction bit to LOW for input
- MmioAnd8 (PL061_GPIO_DIR_REG, GPIO_PIN_MASK_LOW_8BIT(Gpio));
- break;
-
- case GPIO_MODE_OUTPUT_0:
- // Set the corresponding data bit to LOW for 0
- MmioAnd8 (PL061_GPIO_DATA_REG, GPIO_PIN_MASK_LOW_8BIT(Gpio));
- // Set the corresponding direction bit to HIGH for output
- MmioOr8 (PL061_GPIO_DIR_REG, GPIO_PIN_MASK_HIGH_8BIT(Gpio));
- break;
-
- case GPIO_MODE_OUTPUT_1:
- // Set the corresponding data bit to HIGH for 1
- MmioOr8 (PL061_GPIO_DATA_REG, GPIO_PIN_MASK_HIGH_8BIT(Gpio));
- // Set the corresponding direction bit to HIGH for output
- MmioOr8 (PL061_GPIO_DIR_REG, GPIO_PIN_MASK_HIGH_8BIT(Gpio));
- break;
-
- default:
- // Other modes are not supported
- return EFI_UNSUPPORTED;
- }
-
-EXIT:
- return Status;
-}
-
-/**
-
-Routine Description:
-
- Gets the mode (function) of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin
- Mode - pointer to output mode value
-
-Returns:
-
- EFI_SUCCESS - mode value retrieved
- EFI_INVALID_PARAMETER - Mode is a null pointer or Gpio pin is out of range
-
-**/
-EFI_STATUS
-EFIAPI
-GetMode (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- OUT EMBEDDED_GPIO_MODE *Mode
- )
-{
- EFI_STATUS Status;
-
- // Check for errors
- if ( (Mode == NULL)
- || (Gpio > LAST_GPIO_PIN)) {
- return EFI_INVALID_PARAMETER;
- }
-
- // Initialize the hardware if not already done
- if (!mPL061Initialized) {
- Status = PL061Initialize();
- if (EFI_ERROR(Status)) {
- return Status;
- }
- }
-
- // Check if it is input or output
- if (MmioRead8 (PL061_GPIO_DIR_REG) & GPIO_PIN_MASK_HIGH_8BIT(Gpio)) {
- // Pin set to output
- if (MmioRead8 (PL061_GPIO_DATA_REG) & GPIO_PIN_MASK_HIGH_8BIT(Gpio)) {
- *Mode = GPIO_MODE_OUTPUT_1;
- } else {
- *Mode = GPIO_MODE_OUTPUT_0;
- }
- } else {
- // Pin set to input
- *Mode = GPIO_MODE_INPUT;
- }
-
- return EFI_SUCCESS;
-}
-
-/**
-
-Routine Description:
-
- Sets the pull-up / pull-down resistor of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin
- Direction - pull-up, pull-down, or none
-
-Returns:
-
- EFI_UNSUPPORTED - Can not perform the requested operation
-
-**/
-EFI_STATUS
-EFIAPI
-SetPull (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- IN EMBEDDED_GPIO_PULL Direction
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- Protocol variable definition
- **/
-EMBEDDED_GPIO gGpio = {
- Get,
- Set,
- GetMode,
- SetPull
-};
-
-/**
- Initialize the state information for the Embedded Gpio protocol.
-
- @param ImageHandle of the loaded driver
- @param SystemTable Pointer to the System Table
-
- @retval EFI_SUCCESS Protocol registered
- @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
- @retval EFI_DEVICE_ERROR Hardware problems
-
-**/
-EFI_STATUS
-EFIAPI
-PL061InstallProtocol (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE Handle;
-
- //
- // Make sure the Gpio protocol has not been installed in the system yet.
- //
- ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEmbeddedGpioProtocolGuid);
-
- // Install the Embedded GPIO Protocol onto a new handle
- Handle = NULL;
- Status = gBS->InstallMultipleProtocolInterfaces(
- &Handle,
- &gEmbeddedGpioProtocolGuid, &gGpio,
- NULL
- );
- if (EFI_ERROR(Status)) {
- Status = EFI_OUT_OF_RESOURCES;
- }
-
- return Status;
-}
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+
+#include <PiDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+
+#include <Protocol/EmbeddedGpio.h>
+#include <Drivers/PL061Gpio.h>
+
+BOOLEAN mPL061Initialized = FALSE;
+
+/**
+ Function implementations
+**/
+
+EFI_STATUS
+PL061Identify (
+ VOID
+ )
+{
+ // Check if this is a PrimeCell Peripheral
+ if ( (MmioRead8 (PL061_GPIO_PCELL_ID0) != 0x0D)
+ || (MmioRead8 (PL061_GPIO_PCELL_ID1) != 0xF0)
+ || (MmioRead8 (PL061_GPIO_PCELL_ID2) != 0x05)
+ || (MmioRead8 (PL061_GPIO_PCELL_ID3) != 0xB1)) {
+ return EFI_NOT_FOUND;
+ }
+
+ // Check if this PrimeCell Peripheral is the PL061 GPIO
+ if ( (MmioRead8 (PL061_GPIO_PERIPH_ID0) != 0x61)
+ || (MmioRead8 (PL061_GPIO_PERIPH_ID1) != 0x10)
+ || ((MmioRead8 (PL061_GPIO_PERIPH_ID2) & 0xF) != 0x04)
+ || (MmioRead8 (PL061_GPIO_PERIPH_ID3) != 0x00)) {
+ return EFI_NOT_FOUND;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+PL061Initialize (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+
+ // Check if the PL061 GPIO module exists on board
+ Status = PL061Identify();
+ if (EFI_ERROR (Status)) {
+ Status = EFI_DEVICE_ERROR;
+ goto EXIT;
+ }
+
+ // Do other hardware initialisation things here as required
+
+ // Disable Interrupts
+ //if (MmioRead8 (PL061_GPIO_IE_REG) != 0) {
+ // // Ensure interrupts are disabled
+ //}
+
+ mPL061Initialized = TRUE;
+
+ EXIT:
+ return Status;
+}
+
+/**
+
+Routine Description:
+
+ Gets the state of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin to read
+ Value - state of the pin
+
+Returns:
+
+ EFI_SUCCESS - GPIO state returned in Value
+ EFI_INVALID_PARAMETER - Value is NULL pointer or Gpio pin is out of range
+**/
+EFI_STATUS
+EFIAPI
+Get (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ OUT UINTN *Value
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ if ( (Value == NULL)
+ || (Gpio > LAST_GPIO_PIN))
+ {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Initialize the hardware if not already done
+ if (!mPL061Initialized) {
+ Status = PL061Initialize();
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ if (MmioRead8 (PL061_GPIO_DATA_REG) & GPIO_PIN_MASK_HIGH_8BIT(Gpio)) {
+ *Value = 1;
+ } else {
+ *Value = 0;
+ }
+
+ EXIT:
+ return Status;
+}
+
+/**
+
+Routine Description:
+
+ Sets the state of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin to modify
+ Mode - mode to set
+
+Returns:
+
+ EFI_SUCCESS - GPIO set as requested
+ EFI_UNSUPPORTED - Mode is not supported
+ EFI_INVALID_PARAMETER - Gpio pin is out of range
+**/
+EFI_STATUS
+EFIAPI
+Set (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ IN EMBEDDED_GPIO_MODE Mode
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ // Check for errors
+ if (Gpio > LAST_GPIO_PIN) {
+ Status = EFI_INVALID_PARAMETER;
+ goto EXIT;
+ }
+
+ // Initialize the hardware if not already done
+ if (!mPL061Initialized) {
+ Status = PL061Initialize();
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+ }
+
+ switch (Mode)
+ {
+ case GPIO_MODE_INPUT:
+ // Set the corresponding direction bit to LOW for input
+ MmioAnd8 (PL061_GPIO_DIR_REG, GPIO_PIN_MASK_LOW_8BIT(Gpio));
+ break;
+
+ case GPIO_MODE_OUTPUT_0:
+ // Set the corresponding data bit to LOW for 0
+ MmioAnd8 (PL061_GPIO_DATA_REG, GPIO_PIN_MASK_LOW_8BIT(Gpio));
+ // Set the corresponding direction bit to HIGH for output
+ MmioOr8 (PL061_GPIO_DIR_REG, GPIO_PIN_MASK_HIGH_8BIT(Gpio));
+ break;
+
+ case GPIO_MODE_OUTPUT_1:
+ // Set the corresponding data bit to HIGH for 1
+ MmioOr8 (PL061_GPIO_DATA_REG, GPIO_PIN_MASK_HIGH_8BIT(Gpio));
+ // Set the corresponding direction bit to HIGH for output
+ MmioOr8 (PL061_GPIO_DIR_REG, GPIO_PIN_MASK_HIGH_8BIT(Gpio));
+ break;
+
+ default:
+ // Other modes are not supported
+ return EFI_UNSUPPORTED;
+ }
+
+EXIT:
+ return Status;
+}
+
+/**
+
+Routine Description:
+
+ Gets the mode (function) of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin
+ Mode - pointer to output mode value
+
+Returns:
+
+ EFI_SUCCESS - mode value retrieved
+ EFI_INVALID_PARAMETER - Mode is a null pointer or Gpio pin is out of range
+
+**/
+EFI_STATUS
+EFIAPI
+GetMode (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ OUT EMBEDDED_GPIO_MODE *Mode
+ )
+{
+ EFI_STATUS Status;
+
+ // Check for errors
+ if ( (Mode == NULL)
+ || (Gpio > LAST_GPIO_PIN)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Initialize the hardware if not already done
+ if (!mPL061Initialized) {
+ Status = PL061Initialize();
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ }
+
+ // Check if it is input or output
+ if (MmioRead8 (PL061_GPIO_DIR_REG) & GPIO_PIN_MASK_HIGH_8BIT(Gpio)) {
+ // Pin set to output
+ if (MmioRead8 (PL061_GPIO_DATA_REG) & GPIO_PIN_MASK_HIGH_8BIT(Gpio)) {
+ *Mode = GPIO_MODE_OUTPUT_1;
+ } else {
+ *Mode = GPIO_MODE_OUTPUT_0;
+ }
+ } else {
+ // Pin set to input
+ *Mode = GPIO_MODE_INPUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+
+Routine Description:
+
+ Sets the pull-up / pull-down resistor of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin
+ Direction - pull-up, pull-down, or none
+
+Returns:
+
+ EFI_UNSUPPORTED - Can not perform the requested operation
+
+**/
+EFI_STATUS
+EFIAPI
+SetPull (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ IN EMBEDDED_GPIO_PULL Direction
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Protocol variable definition
+ **/
+EMBEDDED_GPIO gGpio = {
+ Get,
+ Set,
+ GetMode,
+ SetPull
+};
+
+/**
+ Initialize the state information for the Embedded Gpio protocol.
+
+ @param ImageHandle of the loaded driver
+ @param SystemTable Pointer to the System Table
+
+ @retval EFI_SUCCESS Protocol registered
+ @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
+ @retval EFI_DEVICE_ERROR Hardware problems
+
+**/
+EFI_STATUS
+EFIAPI
+PL061InstallProtocol (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+
+ //
+ // Make sure the Gpio protocol has not been installed in the system yet.
+ //
+ ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEmbeddedGpioProtocolGuid);
+
+ // Install the Embedded GPIO Protocol onto a new handle
+ Handle = NULL;
+ Status = gBS->InstallMultipleProtocolInterfaces(
+ &Handle,
+ &gEmbeddedGpioProtocolGuid, &gGpio,
+ NULL
+ );
+ if (EFI_ERROR(Status)) {
+ Status = EFI_OUT_OF_RESOURCES;
+ }
+
+ return Status;
+}
diff --git a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061GpioDxe.inf b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061GpioDxe.inf
index b5adda3a8..49284d0a0 100644
--- a/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061GpioDxe.inf
+++ b/ArmPlatformPkg/Drivers/PL061GpioDxe/PL061GpioDxe.inf
@@ -1,50 +1,50 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = PL061GpioDxe
- FILE_GUID = 5c1997d7-8d45-4f21-af3c-2206b8ed8bec
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = PL061InstallProtocol
-[Sources.common]
- PL061Gpio.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- BaseMemoryLib
- DebugLib
- IoLib
- PcdLib
- UefiBootServicesTableLib
- UefiDriverEntryPoint
- UefiLib
- UefiRuntimeServicesTableLib
-
-[Pcd]
- gArmPlatformTokenSpaceGuid.PcdPL061GpioBase
-
-[Protocols]
- gEmbeddedGpioProtocolGuid
-
-[Depex]
- TRUE
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PL061GpioDxe
+ FILE_GUID = 5c1997d7-8d45-4f21-af3c-2206b8ed8bec
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = PL061InstallProtocol
+[Sources.common]
+ PL061Gpio.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ IoLib
+ PcdLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ UefiLib
+ UefiRuntimeServicesTableLib
+
+[Pcd]
+ gArmPlatformTokenSpaceGuid.PcdPL061GpioBase
+
+[Protocols]
+ gEmbeddedGpioProtocolGuid
+
+[Depex]
+ TRUE
diff --git a/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804Timer.c b/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804Timer.c
index 71b7a32d6..839d34d41 100644
--- a/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804Timer.c
+++ b/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804Timer.c
@@ -1,395 +1,395 @@
-/** @file
- Template for Timer Architecture Protocol driver of the ARM flavor
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
- Copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-
-#include <PiDxe.h>
-
-#include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-
-#include <Protocol/Timer.h>
-#include <Protocol/HardwareInterrupt.h>
-
-#include <Drivers/SP804Timer.h>
-
-#define SP804_TIMER_PERIODIC_BASE ((UINTN)PcdGet32 (PcdSP804TimerPeriodicBase))
-#define SP804_TIMER_METRONOME_BASE ((UINTN)PcdGet32 (PcdSP804TimerMetronomeBase))
-#define SP804_TIMER_PERFORMANCE_BASE ((UINTN)PcdGet32 (PcdSP804TimerPerformanceBase))
-
-// The notification function to call on every timer interrupt.
-EFI_TIMER_NOTIFY mTimerNotifyFunction = (EFI_TIMER_NOTIFY)NULL;
-EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
-
-// The current period of the timer interrupt
-UINT64 mTimerPeriod = 0;
-
-// Cached copy of the Hardware Interrupt protocol instance
-EFI_HARDWARE_INTERRUPT_PROTOCOL *gInterrupt = NULL;
-
-// Cached interrupt vector
-UINTN gVector;
-
-
-/**
-
- C Interrupt Handler called in the interrupt context when Source interrupt is active.
-
-
- @param Source Source of the interrupt. Hardware routing off a specific platform defines
- what source means.
-
- @param SystemContext Pointer to system register context. Mostly used by debuggers and will
- update the system context after the return from the interrupt if
- modified. Don't change these values unless you know what you are doing
-
-**/
-VOID
-EFIAPI
-TimerInterruptHandler (
- IN HARDWARE_INTERRUPT_SOURCE Source,
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- EFI_TPL OriginalTPL;
-
- //
- // DXE core uses this callback for the EFI timer tick. The DXE core uses locks
- // that raise to TPL_HIGH and then restore back to current level. Thus we need
- // to make sure TPL level is set to TPL_HIGH while we are handling the timer tick.
- //
- OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-
- // If the interrupt is shared then we must check if this interrupt source is the one associated to this Timer
- if (MmioRead32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_MSK_INT_STS_REG) != 0) {
- // Clear the periodic interrupt
- MmioWrite32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_INT_CLR_REG, 0);
-
- // Signal end of interrupt early to help avoid losing subsequent ticks from long duration handlers
- gInterrupt->EndOfInterrupt (gInterrupt, Source);
-
- if (mTimerNotifyFunction) {
- mTimerNotifyFunction (mTimerPeriod);
- }
- }
-
- gBS->RestoreTPL (OriginalTPL);
-}
-
-/**
- This function registers the handler NotifyFunction so it is called every time
- the timer interrupt fires. It also passes the amount of time since the last
- handler call to the NotifyFunction. If NotifyFunction is NULL, then the
- handler is unregistered. If the handler is registered, then EFI_SUCCESS is
- returned. If the CPU does not support registering a timer interrupt handler,
- then EFI_UNSUPPORTED is returned. If an attempt is made to register a handler
- when a handler is already registered, then EFI_ALREADY_STARTED is returned.
- If an attempt is made to unregister a handler when a handler is not registered,
- then EFI_INVALID_PARAMETER is returned. If an error occurs attempting to
- register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
- is returned.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param NotifyFunction The function to call when a timer interrupt fires. This
- function executes at TPL_HIGH_LEVEL. The DXE Core will
- register a handler for the timer interrupt, so it can know
- how much time has passed. This information is used to
- signal timer based events. NULL will unregister the handler.
- @retval EFI_SUCCESS The timer handler was registered.
- @retval EFI_UNSUPPORTED The platform does not support timer interrupts.
- @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
- registered.
- @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
- previously registered.
- @retval EFI_DEVICE_ERROR The timer handler could not be registered.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverRegisterHandler (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- IN EFI_TIMER_NOTIFY NotifyFunction
- )
-{
- if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
-
- if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
- return EFI_ALREADY_STARTED;
- }
-
- mTimerNotifyFunction = NotifyFunction;
-
- return EFI_SUCCESS;
-}
-
-/**
- Make sure all Dual Timers are disabled
-**/
-VOID
-EFIAPI
-ExitBootServicesEvent (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- // Disable 'Periodic Operation' timer if enabled
- if (MmioRead32(SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
- MmioAnd32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, 0);
- }
-
- // Disable 'Metronome/Delay' timer if enabled
- if (MmioRead32(SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
- MmioAnd32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG, 0);
- }
-
- // Disable 'Performance' timer if enabled
- if (MmioRead32(SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
- MmioAnd32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG, 0);
- }
-}
-
-/**
-
- This function adjusts the period of timer interrupts to the value specified
- by TimerPeriod. If the timer period is updated, then the selected timer
- period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
- If an error occurs while attempting to update the timer period, then the
- timer hardware will be put back in its state prior to this call, and
- EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
- is disabled. This is not the same as disabling the CPU's interrupts.
- Instead, it must either turn off the timer hardware, or it must adjust the
- interrupt controller so that a CPU interrupt is not generated when the timer
- interrupt fires.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is
- returned. If the timer is programmable, then the timer period
- will be rounded up to the nearest timer period that is supported
- by the timer hardware. If TimerPeriod is set to 0, then the
- timer interrupts will be disabled.
-
-
- @retval EFI_SUCCESS The timer period was changed.
- @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
- @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverSetTimerPeriod (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- IN UINT64 TimerPeriod
- )
-{
- EFI_STATUS Status;
- UINT64 TimerTicks;
-
- // always disable the timer
- MmioAnd32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, ~SP804_TIMER_CTRL_ENABLE);
-
- if (TimerPeriod == 0) {
- // Leave timer disabled from above, and...
-
- // Disable timer 0/1 interrupt for a TimerPeriod of 0
- Status = gInterrupt->DisableInterruptSource (gInterrupt, gVector);
- } else {
- // Convert TimerPeriod into 1MHz clock counts (us units = 100ns units * 10)
- TimerTicks = DivU64x32 (TimerPeriod, 10);
- TimerTicks = MultU64x32 (TimerTicks, PcdGet32(PcdSP804TimerFrequencyInMHz));
-
- // if it's larger than 32-bits, pin to highest value
- if (TimerTicks > 0xffffffff) {
- TimerTicks = 0xffffffff;
- }
-
- // Program the SP804 timer with the new count value
- MmioWrite32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_LOAD_REG, TimerTicks);
-
- // enable the timer
- MmioOr32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_ENABLE);
-
- // enable timer 0/1 interrupts
- Status = gInterrupt->EnableInterruptSource (gInterrupt, gVector);
- }
-
- // Save the new timer period
- mTimerPeriod = TimerPeriod;
- return Status;
-}
-
-/**
- This function retrieves the period of timer interrupts in 100 ns units,
- returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
- is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
- returned, then the timer is currently disabled.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
- 0 is returned, then the timer is currently disabled.
-
-
- @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
- @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverGetTimerPeriod (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- OUT UINT64 *TimerPeriod
- )
-{
- if (TimerPeriod == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- *TimerPeriod = mTimerPeriod;
- return EFI_SUCCESS;
-}
-
-/**
- This function generates a soft timer interrupt. If the platform does not support soft
- timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
- If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
- service, then a soft timer interrupt will be generated. If the timer interrupt is
- enabled when this service is called, then the registered handler will be invoked. The
- registered handler should not be able to distinguish a hardware-generated timer
- interrupt from a software-generated timer interrupt.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
-
- @retval EFI_SUCCESS The soft timer interrupt was generated.
- @retval EFI_UNSUPPORTED The platform does not support the generation of soft timer interrupts.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverGenerateSoftInterrupt (
- IN EFI_TIMER_ARCH_PROTOCOL *This
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- Interface structure for the Timer Architectural Protocol.
-
- @par Protocol Description:
- This protocol provides the services to initialize a periodic timer
- interrupt, and to register a handler that is called each time the timer
- interrupt fires. It may also provide a service to adjust the rate of the
- periodic timer interrupt. When a timer interrupt occurs, the handler is
- passed the amount of time that has passed since the previous timer
- interrupt.
-
- @param RegisterHandler
- Registers a handler that will be called each time the
- timer interrupt fires. TimerPeriod defines the minimum
- time between timer interrupts, so TimerPeriod will also
- be the minimum time between calls to the registered
- handler.
-
- @param SetTimerPeriod
- Sets the period of the timer interrupt in 100 nS units.
- This function is optional, and may return EFI_UNSUPPORTED.
- If this function is supported, then the timer period will
- be rounded up to the nearest supported timer period.
-
-
- @param GetTimerPeriod
- Retrieves the period of the timer interrupt in 100 nS units.
-
- @param GenerateSoftInterrupt
- Generates a soft timer interrupt that simulates the firing of
- the timer interrupt. This service can be used to invoke the registered handler if the timer interrupt has been masked for
- a period of time.
-
-**/
-EFI_TIMER_ARCH_PROTOCOL gTimer = {
- TimerDriverRegisterHandler,
- TimerDriverSetTimerPeriod,
- TimerDriverGetTimerPeriod,
- TimerDriverGenerateSoftInterrupt
-};
-
-
-/**
- Initialize the state information for the Timer Architectural Protocol and
- the Timer Debug support protocol that allows the debugger to break into a
- running program.
-
- @param ImageHandle of the loaded driver
- @param SystemTable Pointer to the System Table
-
- @retval EFI_SUCCESS Protocol registered
- @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
- @retval EFI_DEVICE_ERROR Hardware problems
-
-**/
-EFI_STATUS
-EFIAPI
-TimerInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_HANDLE Handle = NULL;
- EFI_STATUS Status;
-
- // Set the interrupt timer number
- gVector = PcdGet32(PcdSP804TimerPeriodicInterruptNum);
-
- // Find the interrupt controller protocol. ASSERT if not found.
- Status = gBS->LocateProtocol (&gHardwareInterruptProtocolGuid, NULL, (VOID **)&gInterrupt);
- ASSERT_EFI_ERROR (Status);
-
- // Disable the timer
- Status = TimerDriverSetTimerPeriod (&gTimer, 0);
- ASSERT_EFI_ERROR (Status);
-
- // Install interrupt handler
- Status = gInterrupt->RegisterInterruptSource (gInterrupt, gVector, TimerInterruptHandler);
- ASSERT_EFI_ERROR (Status);
-
- // configure timer 0 for periodic operation, 32 bits, no prescaler, and interrupt enabled
- MmioWrite32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_PERIODIC | SP804_TIMER_CTRL_32BIT | SP804_PRESCALE_DIV_1 | SP804_TIMER_CTRL_INT_ENABLE);
-
- // Set up default timer
- Status = TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod)); // TIMER_DEFAULT_PERIOD
- ASSERT_EFI_ERROR (Status);
-
- // Install the Timer Architectural Protocol onto a new handle
- Status = gBS->InstallMultipleProtocolInterfaces(
- &Handle,
- &gEfiTimerArchProtocolGuid, &gTimer,
- NULL
- );
- ASSERT_EFI_ERROR(Status);
-
- // Register for an ExitBootServicesEvent
- Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
- ASSERT_EFI_ERROR (Status);
-
- return Status;
-}
+/** @file
+ Template for Timer Architecture Protocol driver of the ARM flavor
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+ Copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+
+#include <PiDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+
+#include <Protocol/Timer.h>
+#include <Protocol/HardwareInterrupt.h>
+
+#include <Drivers/SP804Timer.h>
+
+#define SP804_TIMER_PERIODIC_BASE ((UINTN)PcdGet32 (PcdSP804TimerPeriodicBase))
+#define SP804_TIMER_METRONOME_BASE ((UINTN)PcdGet32 (PcdSP804TimerMetronomeBase))
+#define SP804_TIMER_PERFORMANCE_BASE ((UINTN)PcdGet32 (PcdSP804TimerPerformanceBase))
+
+// The notification function to call on every timer interrupt.
+EFI_TIMER_NOTIFY mTimerNotifyFunction = (EFI_TIMER_NOTIFY)NULL;
+EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
+
+// The current period of the timer interrupt
+UINT64 mTimerPeriod = 0;
+
+// Cached copy of the Hardware Interrupt protocol instance
+EFI_HARDWARE_INTERRUPT_PROTOCOL *gInterrupt = NULL;
+
+// Cached interrupt vector
+UINTN gVector;
+
+
+/**
+
+ C Interrupt Handler called in the interrupt context when Source interrupt is active.
+
+
+ @param Source Source of the interrupt. Hardware routing off a specific platform defines
+ what source means.
+
+ @param SystemContext Pointer to system register context. Mostly used by debuggers and will
+ update the system context after the return from the interrupt if
+ modified. Don't change these values unless you know what you are doing
+
+**/
+VOID
+EFIAPI
+TimerInterruptHandler (
+ IN HARDWARE_INTERRUPT_SOURCE Source,
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ EFI_TPL OriginalTPL;
+
+ //
+ // DXE core uses this callback for the EFI timer tick. The DXE core uses locks
+ // that raise to TPL_HIGH and then restore back to current level. Thus we need
+ // to make sure TPL level is set to TPL_HIGH while we are handling the timer tick.
+ //
+ OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ // If the interrupt is shared then we must check if this interrupt source is the one associated to this Timer
+ if (MmioRead32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_MSK_INT_STS_REG) != 0) {
+ // Clear the periodic interrupt
+ MmioWrite32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_INT_CLR_REG, 0);
+
+ // Signal end of interrupt early to help avoid losing subsequent ticks from long duration handlers
+ gInterrupt->EndOfInterrupt (gInterrupt, Source);
+
+ if (mTimerNotifyFunction) {
+ mTimerNotifyFunction (mTimerPeriod);
+ }
+ }
+
+ gBS->RestoreTPL (OriginalTPL);
+}
+
+/**
+ This function registers the handler NotifyFunction so it is called every time
+ the timer interrupt fires. It also passes the amount of time since the last
+ handler call to the NotifyFunction. If NotifyFunction is NULL, then the
+ handler is unregistered. If the handler is registered, then EFI_SUCCESS is
+ returned. If the CPU does not support registering a timer interrupt handler,
+ then EFI_UNSUPPORTED is returned. If an attempt is made to register a handler
+ when a handler is already registered, then EFI_ALREADY_STARTED is returned.
+ If an attempt is made to unregister a handler when a handler is not registered,
+ then EFI_INVALID_PARAMETER is returned. If an error occurs attempting to
+ register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
+ is returned.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param NotifyFunction The function to call when a timer interrupt fires. This
+ function executes at TPL_HIGH_LEVEL. The DXE Core will
+ register a handler for the timer interrupt, so it can know
+ how much time has passed. This information is used to
+ signal timer based events. NULL will unregister the handler.
+ @retval EFI_SUCCESS The timer handler was registered.
+ @retval EFI_UNSUPPORTED The platform does not support timer interrupts.
+ @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
+ registered.
+ @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
+ previously registered.
+ @retval EFI_DEVICE_ERROR The timer handler could not be registered.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverRegisterHandler (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ IN EFI_TIMER_NOTIFY NotifyFunction
+ )
+{
+ if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
+ return EFI_ALREADY_STARTED;
+ }
+
+ mTimerNotifyFunction = NotifyFunction;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Make sure all Dual Timers are disabled
+**/
+VOID
+EFIAPI
+ExitBootServicesEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ // Disable 'Periodic Operation' timer if enabled
+ if (MmioRead32(SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
+ MmioAnd32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, 0);
+ }
+
+ // Disable 'Metronome/Delay' timer if enabled
+ if (MmioRead32(SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
+ MmioAnd32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG, 0);
+ }
+
+ // Disable 'Performance' timer if enabled
+ if (MmioRead32(SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
+ MmioAnd32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG, 0);
+ }
+}
+
+/**
+
+ This function adjusts the period of timer interrupts to the value specified
+ by TimerPeriod. If the timer period is updated, then the selected timer
+ period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+ If an error occurs while attempting to update the timer period, then the
+ timer hardware will be put back in its state prior to this call, and
+ EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
+ is disabled. This is not the same as disabling the CPU's interrupts.
+ Instead, it must either turn off the timer hardware, or it must adjust the
+ interrupt controller so that a CPU interrupt is not generated when the timer
+ interrupt fires.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is
+ returned. If the timer is programmable, then the timer period
+ will be rounded up to the nearest timer period that is supported
+ by the timer hardware. If TimerPeriod is set to 0, then the
+ timer interrupts will be disabled.
+
+
+ @retval EFI_SUCCESS The timer period was changed.
+ @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
+ @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverSetTimerPeriod (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ IN UINT64 TimerPeriod
+ )
+{
+ EFI_STATUS Status;
+ UINT64 TimerTicks;
+
+ // always disable the timer
+ MmioAnd32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, ~SP804_TIMER_CTRL_ENABLE);
+
+ if (TimerPeriod == 0) {
+ // Leave timer disabled from above, and...
+
+ // Disable timer 0/1 interrupt for a TimerPeriod of 0
+ Status = gInterrupt->DisableInterruptSource (gInterrupt, gVector);
+ } else {
+ // Convert TimerPeriod into 1MHz clock counts (us units = 100ns units * 10)
+ TimerTicks = DivU64x32 (TimerPeriod, 10);
+ TimerTicks = MultU64x32 (TimerTicks, PcdGet32(PcdSP804TimerFrequencyInMHz));
+
+ // if it's larger than 32-bits, pin to highest value
+ if (TimerTicks > 0xffffffff) {
+ TimerTicks = 0xffffffff;
+ }
+
+ // Program the SP804 timer with the new count value
+ MmioWrite32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_LOAD_REG, TimerTicks);
+
+ // enable the timer
+ MmioOr32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_ENABLE);
+
+ // enable timer 0/1 interrupts
+ Status = gInterrupt->EnableInterruptSource (gInterrupt, gVector);
+ }
+
+ // Save the new timer period
+ mTimerPeriod = TimerPeriod;
+ return Status;
+}
+
+/**
+ This function retrieves the period of timer interrupts in 100 ns units,
+ returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
+ is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
+ returned, then the timer is currently disabled.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
+ 0 is returned, then the timer is currently disabled.
+
+
+ @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
+ @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGetTimerPeriod (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ OUT UINT64 *TimerPeriod
+ )
+{
+ if (TimerPeriod == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *TimerPeriod = mTimerPeriod;
+ return EFI_SUCCESS;
+}
+
+/**
+ This function generates a soft timer interrupt. If the platform does not support soft
+ timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
+ If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
+ service, then a soft timer interrupt will be generated. If the timer interrupt is
+ enabled when this service is called, then the registered handler will be invoked. The
+ registered handler should not be able to distinguish a hardware-generated timer
+ interrupt from a software-generated timer interrupt.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+
+ @retval EFI_SUCCESS The soft timer interrupt was generated.
+ @retval EFI_UNSUPPORTED The platform does not support the generation of soft timer interrupts.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGenerateSoftInterrupt (
+ IN EFI_TIMER_ARCH_PROTOCOL *This
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Interface structure for the Timer Architectural Protocol.
+
+ @par Protocol Description:
+ This protocol provides the services to initialize a periodic timer
+ interrupt, and to register a handler that is called each time the timer
+ interrupt fires. It may also provide a service to adjust the rate of the
+ periodic timer interrupt. When a timer interrupt occurs, the handler is
+ passed the amount of time that has passed since the previous timer
+ interrupt.
+
+ @param RegisterHandler
+ Registers a handler that will be called each time the
+ timer interrupt fires. TimerPeriod defines the minimum
+ time between timer interrupts, so TimerPeriod will also
+ be the minimum time between calls to the registered
+ handler.
+
+ @param SetTimerPeriod
+ Sets the period of the timer interrupt in 100 nS units.
+ This function is optional, and may return EFI_UNSUPPORTED.
+ If this function is supported, then the timer period will
+ be rounded up to the nearest supported timer period.
+
+
+ @param GetTimerPeriod
+ Retrieves the period of the timer interrupt in 100 nS units.
+
+ @param GenerateSoftInterrupt
+ Generates a soft timer interrupt that simulates the firing of
+ the timer interrupt. This service can be used to invoke the registered handler if the timer interrupt has been masked for
+ a period of time.
+
+**/
+EFI_TIMER_ARCH_PROTOCOL gTimer = {
+ TimerDriverRegisterHandler,
+ TimerDriverSetTimerPeriod,
+ TimerDriverGetTimerPeriod,
+ TimerDriverGenerateSoftInterrupt
+};
+
+
+/**
+ Initialize the state information for the Timer Architectural Protocol and
+ the Timer Debug support protocol that allows the debugger to break into a
+ running program.
+
+ @param ImageHandle of the loaded driver
+ @param SystemTable Pointer to the System Table
+
+ @retval EFI_SUCCESS Protocol registered
+ @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
+ @retval EFI_DEVICE_ERROR Hardware problems
+
+**/
+EFI_STATUS
+EFIAPI
+TimerInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_HANDLE Handle = NULL;
+ EFI_STATUS Status;
+
+ // Set the interrupt timer number
+ gVector = PcdGet32(PcdSP804TimerPeriodicInterruptNum);
+
+ // Find the interrupt controller protocol. ASSERT if not found.
+ Status = gBS->LocateProtocol (&gHardwareInterruptProtocolGuid, NULL, (VOID **)&gInterrupt);
+ ASSERT_EFI_ERROR (Status);
+
+ // Disable the timer
+ Status = TimerDriverSetTimerPeriod (&gTimer, 0);
+ ASSERT_EFI_ERROR (Status);
+
+ // Install interrupt handler
+ Status = gInterrupt->RegisterInterruptSource (gInterrupt, gVector, TimerInterruptHandler);
+ ASSERT_EFI_ERROR (Status);
+
+ // configure timer 0 for periodic operation, 32 bits, no prescaler, and interrupt enabled
+ MmioWrite32 (SP804_TIMER_PERIODIC_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_PERIODIC | SP804_TIMER_CTRL_32BIT | SP804_PRESCALE_DIV_1 | SP804_TIMER_CTRL_INT_ENABLE);
+
+ // Set up default timer
+ Status = TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod)); // TIMER_DEFAULT_PERIOD
+ ASSERT_EFI_ERROR (Status);
+
+ // Install the Timer Architectural Protocol onto a new handle
+ Status = gBS->InstallMultipleProtocolInterfaces(
+ &Handle,
+ &gEfiTimerArchProtocolGuid, &gTimer,
+ NULL
+ );
+ ASSERT_EFI_ERROR(Status);
+
+ // Register for an ExitBootServicesEvent
+ Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
diff --git a/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf b/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf
index 405563b86..8e87adcf0 100644
--- a/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf
+++ b/ArmPlatformPkg/Drivers/SP804TimerDxe/SP804TimerDxe.inf
@@ -1,59 +1,59 @@
-#/** @file
-#
-# Component description file for Timer module
-#
-# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmVeTimerDxe
- FILE_GUID = a73d663d-a491-4278-9a69-9521be3379f2
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = TimerInitialize
-
-[Sources.common]
- SP804Timer.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- UefiRuntimeServicesTableLib
- UefiLib
- UefiBootServicesTableLib
- BaseMemoryLib
- DebugLib
- UefiDriverEntryPoint
- IoLib
-
-[Guids]
-
-[Protocols]
- gEfiTimerArchProtocolGuid
- gHardwareInterruptProtocolGuid
-
-[Pcd.common]
- gArmPlatformTokenSpaceGuid.PcdSP804TimerFrequencyInMHz
- gArmPlatformTokenSpaceGuid.PcdSP804TimerPeriodicInterruptNum
- gArmPlatformTokenSpaceGuid.PcdSP804TimerPeriodicBase
- gArmPlatformTokenSpaceGuid.PcdSP804TimerPerformanceBase
- gArmPlatformTokenSpaceGuid.PcdSP804TimerMetronomeBase
- gEmbeddedTokenSpaceGuid.PcdTimerPeriod
-
-[Depex]
- gHardwareInterruptProtocolGuid
+#/** @file
+#
+# Component description file for Timer module
+#
+# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmVeTimerDxe
+ FILE_GUID = a73d663d-a491-4278-9a69-9521be3379f2
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = TimerInitialize
+
+[Sources.common]
+ SP804Timer.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ UefiRuntimeServicesTableLib
+ UefiLib
+ UefiBootServicesTableLib
+ BaseMemoryLib
+ DebugLib
+ UefiDriverEntryPoint
+ IoLib
+
+[Guids]
+
+[Protocols]
+ gEfiTimerArchProtocolGuid
+ gHardwareInterruptProtocolGuid
+
+[Pcd.common]
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerFrequencyInMHz
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerPeriodicInterruptNum
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerPeriodicBase
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerPerformanceBase
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerMetronomeBase
+ gEmbeddedTokenSpaceGuid.PcdTimerPeriod
+
+[Depex]
+ gHardwareInterruptProtocolGuid
diff --git a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c
index 5b78b2b3f..d1da60b5a 100644
--- a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c
+++ b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c
@@ -1,387 +1,387 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-
-#include <PiDxe.h>
-
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/UefiLib.h>
-
-#include <Protocol/WatchdogTimer.h>
-#include <Drivers/SP805Watchdog.h>
-
-EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
-
-/**
- Make sure the SP805 registers are unlocked for writing.
-
- Note: The SP805 Watchdog Timer supports locking of its registers,
- i.e. it inhibits all writes to avoid rogue software accidentally
- corrupting their contents.
-**/
-inline
-VOID
-SP805Unlock (
- VOID
- )
-{
- if( MmioRead32(SP805_WDOG_LOCK_REG) == SP805_WDOG_LOCK_IS_LOCKED ) {
- MmioWrite32(SP805_WDOG_LOCK_REG, SP805_WDOG_SPECIAL_UNLOCK_CODE);
- }
-}
-
-/**
- Make sure the SP805 registers are locked and can not be overwritten.
-
- Note: The SP805 Watchdog Timer supports locking of its registers,
- i.e. it inhibits all writes to avoid rogue software accidentally
- corrupting their contents.
-**/
-inline
-VOID
-SP805Lock (
- VOID
- )
-{
- if( MmioRead32(SP805_WDOG_LOCK_REG) == SP805_WDOG_LOCK_IS_UNLOCKED ) {
- // To lock it, just write in any number (except the special unlock code).
- MmioWrite32(SP805_WDOG_LOCK_REG, SP805_WDOG_LOCK_IS_LOCKED);
- }
-}
-
-/**
- Stop the SP805 watchdog timer from counting down by disabling interrupts.
-**/
-inline
-VOID
-SP805Stop (
- VOID
- )
-{
- // Disable interrupts
- if ( (MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) != 0 ) {
- MmioAnd32(SP805_WDOG_CONTROL_REG, ~SP805_WDOG_CTRL_INTEN);
- }
-}
-
-/**
- Starts the SP805 counting down by enabling interrupts.
- The count down will start from the value stored in the Load register,
- not from the value where it was previously stopped.
-**/
-inline
-VOID
-SP805Start (
- VOID
- )
-{
- // Enable interrupts
- if ( (MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) == 0 ) {
- MmioOr32(SP805_WDOG_CONTROL_REG, SP805_WDOG_CTRL_INTEN);
- }
-}
-
-/**
- On exiting boot services we must make sure the SP805 Watchdog Timer
- is stopped.
-**/
-VOID
-EFIAPI
-ExitBootServicesEvent (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- SP805Unlock();
- SP805Stop();
- SP805Lock();
-}
-
-/**
- This function registers the handler NotifyFunction so it is called every time
- the watchdog timer expires. It also passes the amount of time since the last
- handler call to the NotifyFunction.
- If NotifyFunction is not NULL and a handler is not already registered,
- then the new handler is registered and EFI_SUCCESS is returned.
- If NotifyFunction is NULL, and a handler is already registered,
- then that handler is unregistered.
- If an attempt is made to register a handler when a handler is already registered,
- then EFI_ALREADY_STARTED is returned.
- If an attempt is made to unregister a handler when a handler is not registered,
- then EFI_INVALID_PARAMETER is returned.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param NotifyFunction The function to call when a timer interrupt fires. This
- function executes at TPL_HIGH_LEVEL. The DXE Core will
- register a handler for the timer interrupt, so it can know
- how much time has passed. This information is used to
- signal timer based events. NULL will unregister the handler.
-
- @retval EFI_SUCCESS The watchdog timer handler was registered.
- @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
- registered.
- @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
- previously registered.
-
-**/
-EFI_STATUS
-EFIAPI
-SP805RegisterHandler (
- IN CONST EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *This,
- IN EFI_WATCHDOG_TIMER_NOTIFY NotifyFunction
- )
-{
- // ERROR: This function is not supported.
- // The hardware watchdog will reset the board
- return EFI_INVALID_PARAMETER;
-}
-
-/**
-
- This function adjusts the period of timer interrupts to the value specified
- by TimerPeriod. If the timer period is updated, then the selected timer
- period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
- If an error occurs while attempting to update the timer period, then the
- timer hardware will be put back in its state prior to this call, and
- EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
- is disabled. This is not the same as disabling the CPU's interrupts.
- Instead, it must either turn off the timer hardware, or it must adjust the
- interrupt controller so that a CPU interrupt is not generated when the timer
- interrupt fires.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is
- returned. If the timer is programmable, then the timer period
- will be rounded up to the nearest timer period that is supported
- by the timer hardware. If TimerPeriod is set to 0, then the
- timer interrupts will be disabled.
-
-
- @retval EFI_SUCCESS The timer period was changed.
- @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
- @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
-
-**/
-EFI_STATUS
-EFIAPI
-SP805SetTimerPeriod (
- IN CONST EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *This,
- IN UINT64 TimerPeriod // In 100ns units
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- UINT64 Ticks64bit;
-
- SP805Unlock();
-
- if( TimerPeriod == 0 ) {
- // This is a watchdog stop request
- SP805Stop();
- goto EXIT;
- } else {
- // Calculate the Watchdog ticks required for a delay of (TimerTicks * 100) nanoseconds
- // The SP805 will count down to ZERO once, generate an interrupt and
- // then it will again reload the initial value and start again.
- // On the second time when it reaches ZERO, it will actually reset the board.
- // Therefore, we need to load half the required delay.
- //
- // WatchdogTicks = ((TimerPeriod * 100 * SP805_CLOCK_FREQUENCY) / 1GHz) / 2 ;
- //
- // i.e.:
- //
- // WatchdogTicks = (TimerPeriod * SP805_CLOCK_FREQUENCY) / 20 MHz ;
-
- Ticks64bit = DivU64x32(MultU64x32(TimerPeriod, (UINTN)PcdGet32(PcdSP805WatchdogClockFrequencyInHz)), 20000000);
-
- // The registers in the SP805 are only 32 bits
- if(Ticks64bit > (UINT64)0xFFFFFFFF) {
- // We could load the watchdog with the maximum supported value but
- // if a smaller value was requested, this could have the watchdog
- // triggering before it was intended.
- // Better generate an error to let the caller know.
- Status = EFI_DEVICE_ERROR;
- goto EXIT;
- }
-
- // Update the watchdog with a 32-bit value.
- MmioWrite32(SP805_WDOG_LOAD_REG, (UINT32)Ticks64bit);
-
- // Start the watchdog
- SP805Start();
- }
-
- EXIT:
- // Ensure the watchdog is locked before exiting.
- SP805Lock();
- return Status;
-}
-
-/**
- This function retrieves the period of timer interrupts in 100 ns units,
- returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
- is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
- returned, then the timer is currently disabled.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
- 0 is returned, then the timer is currently disabled.
-
-
- @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
- @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-SP805GetTimerPeriod (
- IN CONST EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *This,
- OUT UINT64 *TimerPeriod
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- UINT64 ReturnValue;
-
- if (TimerPeriod == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- // Check if the watchdog is stopped
- if ( (MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) == 0 ) {
- // It is stopped, so return zero.
- ReturnValue = 0;
- } else {
- // Convert the Watchdog ticks into TimerPeriod
- // Ensure 64bit arithmetic throughout because the Watchdog ticks may already
- // be at the maximum 32 bit value and we still need to multiply that by 600.
- ReturnValue = MultU64x32( MmioRead32(SP805_WDOG_LOAD_REG), 600 );
- }
-
- *TimerPeriod = ReturnValue;
-
- return Status;
-}
-
-/**
- Interface structure for the Watchdog Architectural Protocol.
-
- @par Protocol Description:
- This protocol provides a service to set the amount of time to wait
- before firing the watchdog timer, and it also provides a service to
- register a handler that is invoked when the watchdog timer fires.
-
- @par When the watchdog timer fires, control will be passed to a handler
- if one has been registered. If no handler has been registered,
- or the registered handler returns, then the system will be
- reset by calling the Runtime Service ResetSystem().
-
- @param RegisterHandler
- Registers a handler that will be called each time the
- watchdogtimer interrupt fires. TimerPeriod defines the minimum
- time between timer interrupts, so TimerPeriod will also
- be the minimum time between calls to the registered
- handler.
- NOTE: If the watchdog resets the system in hardware, then
- this function will not have any chance of executing.
-
- @param SetTimerPeriod
- Sets the period of the timer interrupt in 100 nS units.
- This function is optional, and may return EFI_UNSUPPORTED.
- If this function is supported, then the timer period will
- be rounded up to the nearest supported timer period.
-
- @param GetTimerPeriod
- Retrieves the period of the timer interrupt in 100 nS units.
-
-**/
-EFI_WATCHDOG_TIMER_ARCH_PROTOCOL gWatchdogTimer = {
- (EFI_WATCHDOG_TIMER_REGISTER_HANDLER) SP805RegisterHandler,
- (EFI_WATCHDOG_TIMER_SET_TIMER_PERIOD) SP805SetTimerPeriod,
- (EFI_WATCHDOG_TIMER_GET_TIMER_PERIOD) SP805GetTimerPeriod
-};
-
-/**
- Initialize the state information for the Watchdog Timer Architectural Protocol.
-
- @param ImageHandle of the loaded driver
- @param SystemTable Pointer to the System Table
-
- @retval EFI_SUCCESS Protocol registered
- @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
- @retval EFI_DEVICE_ERROR Hardware problems
-
-**/
-EFI_STATUS
-EFIAPI
-SP805Initialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE Handle;
-
- // Unlock access to the SP805 registers
- SP805Unlock ();
-
- // Stop the watchdog from triggering unexpectedly
- SP805Stop ();
-
- // Set the watchdog to reset the board when triggered
- if ((MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_RESEN) == 0) {
- MmioOr32 (SP805_WDOG_CONTROL_REG, SP805_WDOG_CTRL_RESEN);
- }
-
- // Prohibit any rogue access to SP805 registers
- SP805Lock();
-
- //
- // Make sure the Watchdog Timer Architectural Protocol has not been installed in the system yet.
- // This will avoid conflicts with the universal watchdog
- //
- ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiWatchdogTimerArchProtocolGuid);
-
- // Register for an ExitBootServicesEvent
- Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
- if (EFI_ERROR(Status)) {
- Status = EFI_OUT_OF_RESOURCES;
- goto EXIT;
- }
-
- // Install the Timer Architectural Protocol onto a new handle
- Handle = NULL;
- Status = gBS->InstallMultipleProtocolInterfaces(
- &Handle,
- &gEfiWatchdogTimerArchProtocolGuid, &gWatchdogTimer,
- NULL
- );
- if (EFI_ERROR(Status)) {
- Status = EFI_OUT_OF_RESOURCES;
- goto EXIT;
- }
-
-EXIT:
- if(EFI_ERROR(Status)) {
- // The watchdog failed to initialize
- ASSERT(FALSE);
- }
- return Status;
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+
+#include <PiDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/UefiLib.h>
+
+#include <Protocol/WatchdogTimer.h>
+#include <Drivers/SP805Watchdog.h>
+
+EFI_EVENT EfiExitBootServicesEvent = (EFI_EVENT)NULL;
+
+/**
+ Make sure the SP805 registers are unlocked for writing.
+
+ Note: The SP805 Watchdog Timer supports locking of its registers,
+ i.e. it inhibits all writes to avoid rogue software accidentally
+ corrupting their contents.
+**/
+inline
+VOID
+SP805Unlock (
+ VOID
+ )
+{
+ if( MmioRead32(SP805_WDOG_LOCK_REG) == SP805_WDOG_LOCK_IS_LOCKED ) {
+ MmioWrite32(SP805_WDOG_LOCK_REG, SP805_WDOG_SPECIAL_UNLOCK_CODE);
+ }
+}
+
+/**
+ Make sure the SP805 registers are locked and can not be overwritten.
+
+ Note: The SP805 Watchdog Timer supports locking of its registers,
+ i.e. it inhibits all writes to avoid rogue software accidentally
+ corrupting their contents.
+**/
+inline
+VOID
+SP805Lock (
+ VOID
+ )
+{
+ if( MmioRead32(SP805_WDOG_LOCK_REG) == SP805_WDOG_LOCK_IS_UNLOCKED ) {
+ // To lock it, just write in any number (except the special unlock code).
+ MmioWrite32(SP805_WDOG_LOCK_REG, SP805_WDOG_LOCK_IS_LOCKED);
+ }
+}
+
+/**
+ Stop the SP805 watchdog timer from counting down by disabling interrupts.
+**/
+inline
+VOID
+SP805Stop (
+ VOID
+ )
+{
+ // Disable interrupts
+ if ( (MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) != 0 ) {
+ MmioAnd32(SP805_WDOG_CONTROL_REG, ~SP805_WDOG_CTRL_INTEN);
+ }
+}
+
+/**
+ Starts the SP805 counting down by enabling interrupts.
+ The count down will start from the value stored in the Load register,
+ not from the value where it was previously stopped.
+**/
+inline
+VOID
+SP805Start (
+ VOID
+ )
+{
+ // Enable interrupts
+ if ( (MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) == 0 ) {
+ MmioOr32(SP805_WDOG_CONTROL_REG, SP805_WDOG_CTRL_INTEN);
+ }
+}
+
+/**
+ On exiting boot services we must make sure the SP805 Watchdog Timer
+ is stopped.
+**/
+VOID
+EFIAPI
+ExitBootServicesEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ SP805Unlock();
+ SP805Stop();
+ SP805Lock();
+}
+
+/**
+ This function registers the handler NotifyFunction so it is called every time
+ the watchdog timer expires. It also passes the amount of time since the last
+ handler call to the NotifyFunction.
+ If NotifyFunction is not NULL and a handler is not already registered,
+ then the new handler is registered and EFI_SUCCESS is returned.
+ If NotifyFunction is NULL, and a handler is already registered,
+ then that handler is unregistered.
+ If an attempt is made to register a handler when a handler is already registered,
+ then EFI_ALREADY_STARTED is returned.
+ If an attempt is made to unregister a handler when a handler is not registered,
+ then EFI_INVALID_PARAMETER is returned.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param NotifyFunction The function to call when a timer interrupt fires. This
+ function executes at TPL_HIGH_LEVEL. The DXE Core will
+ register a handler for the timer interrupt, so it can know
+ how much time has passed. This information is used to
+ signal timer based events. NULL will unregister the handler.
+
+ @retval EFI_SUCCESS The watchdog timer handler was registered.
+ @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
+ registered.
+ @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
+ previously registered.
+
+**/
+EFI_STATUS
+EFIAPI
+SP805RegisterHandler (
+ IN CONST EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *This,
+ IN EFI_WATCHDOG_TIMER_NOTIFY NotifyFunction
+ )
+{
+ // ERROR: This function is not supported.
+ // The hardware watchdog will reset the board
+ return EFI_INVALID_PARAMETER;
+}
+
+/**
+
+ This function adjusts the period of timer interrupts to the value specified
+ by TimerPeriod. If the timer period is updated, then the selected timer
+ period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+ If an error occurs while attempting to update the timer period, then the
+ timer hardware will be put back in its state prior to this call, and
+ EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
+ is disabled. This is not the same as disabling the CPU's interrupts.
+ Instead, it must either turn off the timer hardware, or it must adjust the
+ interrupt controller so that a CPU interrupt is not generated when the timer
+ interrupt fires.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is
+ returned. If the timer is programmable, then the timer period
+ will be rounded up to the nearest timer period that is supported
+ by the timer hardware. If TimerPeriod is set to 0, then the
+ timer interrupts will be disabled.
+
+
+ @retval EFI_SUCCESS The timer period was changed.
+ @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
+ @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
+
+**/
+EFI_STATUS
+EFIAPI
+SP805SetTimerPeriod (
+ IN CONST EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *This,
+ IN UINT64 TimerPeriod // In 100ns units
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINT64 Ticks64bit;
+
+ SP805Unlock();
+
+ if( TimerPeriod == 0 ) {
+ // This is a watchdog stop request
+ SP805Stop();
+ goto EXIT;
+ } else {
+ // Calculate the Watchdog ticks required for a delay of (TimerTicks * 100) nanoseconds
+ // The SP805 will count down to ZERO once, generate an interrupt and
+ // then it will again reload the initial value and start again.
+ // On the second time when it reaches ZERO, it will actually reset the board.
+ // Therefore, we need to load half the required delay.
+ //
+ // WatchdogTicks = ((TimerPeriod * 100 * SP805_CLOCK_FREQUENCY) / 1GHz) / 2 ;
+ //
+ // i.e.:
+ //
+ // WatchdogTicks = (TimerPeriod * SP805_CLOCK_FREQUENCY) / 20 MHz ;
+
+ Ticks64bit = DivU64x32(MultU64x32(TimerPeriod, (UINTN)PcdGet32(PcdSP805WatchdogClockFrequencyInHz)), 20000000);
+
+ // The registers in the SP805 are only 32 bits
+ if(Ticks64bit > (UINT64)0xFFFFFFFF) {
+ // We could load the watchdog with the maximum supported value but
+ // if a smaller value was requested, this could have the watchdog
+ // triggering before it was intended.
+ // Better generate an error to let the caller know.
+ Status = EFI_DEVICE_ERROR;
+ goto EXIT;
+ }
+
+ // Update the watchdog with a 32-bit value.
+ MmioWrite32(SP805_WDOG_LOAD_REG, (UINT32)Ticks64bit);
+
+ // Start the watchdog
+ SP805Start();
+ }
+
+ EXIT:
+ // Ensure the watchdog is locked before exiting.
+ SP805Lock();
+ return Status;
+}
+
+/**
+ This function retrieves the period of timer interrupts in 100 ns units,
+ returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
+ is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
+ returned, then the timer is currently disabled.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
+ 0 is returned, then the timer is currently disabled.
+
+
+ @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
+ @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+SP805GetTimerPeriod (
+ IN CONST EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *This,
+ OUT UINT64 *TimerPeriod
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINT64 ReturnValue;
+
+ if (TimerPeriod == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Check if the watchdog is stopped
+ if ( (MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_INTEN) == 0 ) {
+ // It is stopped, so return zero.
+ ReturnValue = 0;
+ } else {
+ // Convert the Watchdog ticks into TimerPeriod
+ // Ensure 64bit arithmetic throughout because the Watchdog ticks may already
+ // be at the maximum 32 bit value and we still need to multiply that by 600.
+ ReturnValue = MultU64x32( MmioRead32(SP805_WDOG_LOAD_REG), 600 );
+ }
+
+ *TimerPeriod = ReturnValue;
+
+ return Status;
+}
+
+/**
+ Interface structure for the Watchdog Architectural Protocol.
+
+ @par Protocol Description:
+ This protocol provides a service to set the amount of time to wait
+ before firing the watchdog timer, and it also provides a service to
+ register a handler that is invoked when the watchdog timer fires.
+
+ @par When the watchdog timer fires, control will be passed to a handler
+ if one has been registered. If no handler has been registered,
+ or the registered handler returns, then the system will be
+ reset by calling the Runtime Service ResetSystem().
+
+ @param RegisterHandler
+ Registers a handler that will be called each time the
+ watchdogtimer interrupt fires. TimerPeriod defines the minimum
+ time between timer interrupts, so TimerPeriod will also
+ be the minimum time between calls to the registered
+ handler.
+ NOTE: If the watchdog resets the system in hardware, then
+ this function will not have any chance of executing.
+
+ @param SetTimerPeriod
+ Sets the period of the timer interrupt in 100 nS units.
+ This function is optional, and may return EFI_UNSUPPORTED.
+ If this function is supported, then the timer period will
+ be rounded up to the nearest supported timer period.
+
+ @param GetTimerPeriod
+ Retrieves the period of the timer interrupt in 100 nS units.
+
+**/
+EFI_WATCHDOG_TIMER_ARCH_PROTOCOL gWatchdogTimer = {
+ (EFI_WATCHDOG_TIMER_REGISTER_HANDLER) SP805RegisterHandler,
+ (EFI_WATCHDOG_TIMER_SET_TIMER_PERIOD) SP805SetTimerPeriod,
+ (EFI_WATCHDOG_TIMER_GET_TIMER_PERIOD) SP805GetTimerPeriod
+};
+
+/**
+ Initialize the state information for the Watchdog Timer Architectural Protocol.
+
+ @param ImageHandle of the loaded driver
+ @param SystemTable Pointer to the System Table
+
+ @retval EFI_SUCCESS Protocol registered
+ @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
+ @retval EFI_DEVICE_ERROR Hardware problems
+
+**/
+EFI_STATUS
+EFIAPI
+SP805Initialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+
+ // Unlock access to the SP805 registers
+ SP805Unlock ();
+
+ // Stop the watchdog from triggering unexpectedly
+ SP805Stop ();
+
+ // Set the watchdog to reset the board when triggered
+ if ((MmioRead32(SP805_WDOG_CONTROL_REG) & SP805_WDOG_CTRL_RESEN) == 0) {
+ MmioOr32 (SP805_WDOG_CONTROL_REG, SP805_WDOG_CTRL_RESEN);
+ }
+
+ // Prohibit any rogue access to SP805 registers
+ SP805Lock();
+
+ //
+ // Make sure the Watchdog Timer Architectural Protocol has not been installed in the system yet.
+ // This will avoid conflicts with the universal watchdog
+ //
+ ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiWatchdogTimerArchProtocolGuid);
+
+ // Register for an ExitBootServicesEvent
+ Status = gBS->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, &EfiExitBootServicesEvent);
+ if (EFI_ERROR(Status)) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto EXIT;
+ }
+
+ // Install the Timer Architectural Protocol onto a new handle
+ Handle = NULL;
+ Status = gBS->InstallMultipleProtocolInterfaces(
+ &Handle,
+ &gEfiWatchdogTimerArchProtocolGuid, &gWatchdogTimer,
+ NULL
+ );
+ if (EFI_ERROR(Status)) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto EXIT;
+ }
+
+EXIT:
+ if(EFI_ERROR(Status)) {
+ // The watchdog failed to initialize
+ ASSERT(FALSE);
+ }
+ return Status;
+}
diff --git a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
index ffcd501aa..5ec35188c 100644
--- a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
+++ b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf
@@ -1,52 +1,52 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = SP805WatchdogDxe
- FILE_GUID = ebd705fb-fa92-46a7-b32b-7f566d944614
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = SP805Initialize
-
-[Sources.common]
- SP805Watchdog.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- BaseMemoryLib
- DebugLib
- IoLib
- PcdLib
- UefiLib
- UefiBootServicesTableLib
- UefiDriverEntryPoint
- UefiRuntimeServicesTableLib
-
-[Pcd]
- gArmPlatformTokenSpaceGuid.PcdSP805WatchdogBase
- gArmPlatformTokenSpaceGuid.PcdSP805WatchdogClockFrequencyInHz
-
-[Protocols]
- gEfiWatchdogTimerArchProtocolGuid
-
-[Depex]
- TRUE
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SP805WatchdogDxe
+ FILE_GUID = ebd705fb-fa92-46a7-b32b-7f566d944614
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = SP805Initialize
+
+[Sources.common]
+ SP805Watchdog.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ IoLib
+ PcdLib
+ UefiLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ UefiRuntimeServicesTableLib
+
+[Pcd]
+ gArmPlatformTokenSpaceGuid.PcdSP805WatchdogBase
+ gArmPlatformTokenSpaceGuid.PcdSP805WatchdogClockFrequencyInHz
+
+[Protocols]
+ gEfiWatchdogTimerArchProtocolGuid
+
+[Depex]
+ TRUE
diff --git a/ArmPlatformPkg/Include/Drivers/PL111Lcd.h b/ArmPlatformPkg/Include/Drivers/PL111Lcd.h
index d68acd83b..8c1c29de6 100644
--- a/ArmPlatformPkg/Include/Drivers/PL111Lcd.h
+++ b/ArmPlatformPkg/Include/Drivers/PL111Lcd.h
@@ -1,140 +1,140 @@
-/** @file PL111Lcd.h
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
- **/
-
-#ifndef _PL111LCD_H__
-#define _PL111LCD_H__
-
-/**********************************************************************
- *
- * This header file contains all the bits of the PL111 that are
- * platform independent.
- *
- **********************************************************************/
-
-// Controller Register Offsets
-#define PL111_REG_LCD_TIMING_0 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x000)
-#define PL111_REG_LCD_TIMING_1 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x004)
-#define PL111_REG_LCD_TIMING_2 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x008)
-#define PL111_REG_LCD_TIMING_3 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x00C)
-#define PL111_REG_LCD_UP_BASE ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x010)
-#define PL111_REG_LCD_LP_BASE ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x014)
-#define PL111_REG_LCD_CONTROL ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x018)
-#define PL111_REG_LCD_IMSC ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x01C)
-#define PL111_REG_LCD_RIS ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x020)
-#define PL111_REG_LCD_MIS ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x024)
-#define PL111_REG_LCD_ICR ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x028)
-#define PL111_REG_LCD_UP_CURR ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x02C)
-#define PL111_REG_LCD_LP_CURR ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x030)
-#define PL111_REG_LCD_PALETTE ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x200)
-
-// Identification Register Offsets
-#define PL111_REG_CLCD_PERIPH_ID_0 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFE0)
-#define PL111_REG_CLCD_PERIPH_ID_1 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFE4)
-#define PL111_REG_CLCD_PERIPH_ID_2 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFE8)
-#define PL111_REG_CLCD_PERIPH_ID_3 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFEC)
-#define PL111_REG_CLCD_P_CELL_ID_0 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFF0)
-#define PL111_REG_CLCD_P_CELL_ID_1 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFF4)
-#define PL111_REG_CLCD_P_CELL_ID_2 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFF8)
-#define PL111_REG_CLCD_P_CELL_ID_3 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFFC)
-
-/**********************************************************************/
-
-// Register components (register bits)
-
-// This should make life easier to program specific settings in the different registers
-// by simplifying the setting up of the individual bits of each register
-// and then assembling the final register value.
-
-/**********************************************************************/
-
-// Register: PL111_REG_LCD_TIMING_0
-#define HOR_AXIS_PANEL(hbp,hfp,hsw,hor_res) (UINT32)(((UINT32)(hbp) << 24) | ((UINT32)(hfp) << 16) | ((UINT32)(hsw) << 8) | (((UINT32)((hor_res)/16)-1) << 2))
-
-// Register: PL111_REG_LCD_TIMING_1
-#define VER_AXIS_PANEL(vbp,vfp,vsw,ver_res) (UINT32)(((UINT32)(vbp) << 24) | ((UINT32)(vfp) << 16) | ((UINT32)(vsw) << 10) | ((ver_res)-1))
-
-// Register: PL111_REG_LCD_TIMING_2
-#define PL111_BIT_SHIFT_PCD_HI 27
-#define PL111_BIT_SHIFT_BCD 26
-#define PL111_BIT_SHIFT_CPL 16
-#define PL111_BIT_SHIFT_IOE 14
-#define PL111_BIT_SHIFT_IPC 13
-#define PL111_BIT_SHIFT_IHS 12
-#define PL111_BIT_SHIFT_IVS 11
-#define PL111_BIT_SHIFT_ACB 6
-#define PL111_BIT_SHIFT_CLKSEL 5
-#define PL111_BIT_SHIFT_PCD_LO 0
-
-#define PL111_BCD (1 << 26)
-#define PL111_IPC (1 << 13)
-#define PL111_IHS (1 << 12)
-#define PL111_IVS (1 << 11)
-
-#define CLK_SIG_POLARITY(hor_res) (UINT32)(PL111_BCD | PL111_IPC | PL111_IHS | PL111_IVS | (((hor_res)-1) << 16))
-
-// Register: PL111_REG_LCD_TIMING_3
-#define PL111_BIT_SHIFT_LEE 16
-#define PL111_BIT_SHIFT_LED 0
-
-#define PL111_CTRL_WATERMARK (1 << 16)
-#define PL111_CTRL_LCD_V_COMP (1 << 12)
-#define PL111_CTRL_LCD_PWR (1 << 11)
-#define PL111_CTRL_BEPO (1 << 10)
-#define PL111_CTRL_BEBO (1 << 9)
-#define PL111_CTRL_BGR (1 << 8)
-#define PL111_CTRL_LCD_DUAL (1 << 7)
-#define PL111_CTRL_LCD_MONO_8 (1 << 6)
-#define PL111_CTRL_LCD_TFT (1 << 5)
-#define PL111_CTRL_LCD_BW (1 << 4)
-#define PL111_CTRL_LCD_1BPP (0 << 1)
-#define PL111_CTRL_LCD_2BPP (1 << 1)
-#define PL111_CTRL_LCD_4BPP (2 << 1)
-#define PL111_CTRL_LCD_8BPP (3 << 1)
-#define PL111_CTRL_LCD_16BPP (4 << 1)
-#define PL111_CTRL_LCD_24BPP (5 << 1)
-#define PL111_CTRL_LCD_16BPP_565 (6 << 1)
-#define PL111_CTRL_LCD_12BPP_444 (7 << 1)
-#define PL111_CTRL_LCD_BPP(Bpp) ((Bpp) << 1)
-#define PL111_CTRL_LCD_EN 1
-
-/**********************************************************************/
-
-// Register: PL111_REG_LCD_TIMING_0
-#define PL111_LCD_TIMING_0_HBP(hbp) (((hbp) & 0xFF) << 24)
-#define PL111_LCD_TIMING_0_HFP(hfp) (((hfp) & 0xFF) << 16)
-#define PL111_LCD_TIMING_0_HSW(hsw) (((hsw) & 0xFF) << 8)
-#define PL111_LCD_TIMING_0_PPL(ppl) (((hsw) & 0x3F) << 2)
-
-// Register: PL111_REG_LCD_TIMING_1
-#define PL111_LCD_TIMING_1_VBP(vbp) (((vbp) & 0xFF) << 24)
-#define PL111_LCD_TIMING_1_VFP(vfp) (((vfp) & 0xFF) << 16)
-#define PL111_LCD_TIMING_1_VSW(vsw) (((vsw) & 0x3F) << 10)
-#define PL111_LCD_TIMING_1_LPP(lpp) ((lpp) & 0xFC)
-
-// Register: PL111_REG_LCD_TIMING_2
-#define PL111_BIT_MASK_PCD_HI 0xF8000000
-#define PL111_BIT_MASK_BCD 0x04000000
-#define PL111_BIT_MASK_CPL 0x03FF0000
-#define PL111_BIT_MASK_IOE 0x00004000
-#define PL111_BIT_MASK_IPC 0x00002000
-#define PL111_BIT_MASK_IHS 0x00001000
-#define PL111_BIT_MASK_IVS 0x00000800
-#define PL111_BIT_MASK_ACB 0x000007C0
-#define PL111_BIT_MASK_CLKSEL 0x00000020
-#define PL111_BIT_MASK_PCD_LO 0x0000001F
-
-// Register: PL111_REG_LCD_TIMING_3
-#define PL111_BIT_MASK_LEE 0x00010000
-#define PL111_BIT_MASK_LED 0x0000007F
-
-#endif /* _PL111LCD_H__ */
+/** @file PL111Lcd.h
+
+ Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+ **/
+
+#ifndef _PL111LCD_H__
+#define _PL111LCD_H__
+
+/**********************************************************************
+ *
+ * This header file contains all the bits of the PL111 that are
+ * platform independent.
+ *
+ **********************************************************************/
+
+// Controller Register Offsets
+#define PL111_REG_LCD_TIMING_0 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x000)
+#define PL111_REG_LCD_TIMING_1 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x004)
+#define PL111_REG_LCD_TIMING_2 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x008)
+#define PL111_REG_LCD_TIMING_3 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x00C)
+#define PL111_REG_LCD_UP_BASE ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x010)
+#define PL111_REG_LCD_LP_BASE ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x014)
+#define PL111_REG_LCD_CONTROL ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x018)
+#define PL111_REG_LCD_IMSC ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x01C)
+#define PL111_REG_LCD_RIS ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x020)
+#define PL111_REG_LCD_MIS ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x024)
+#define PL111_REG_LCD_ICR ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x028)
+#define PL111_REG_LCD_UP_CURR ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x02C)
+#define PL111_REG_LCD_LP_CURR ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x030)
+#define PL111_REG_LCD_PALETTE ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0x200)
+
+// Identification Register Offsets
+#define PL111_REG_CLCD_PERIPH_ID_0 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFE0)
+#define PL111_REG_CLCD_PERIPH_ID_1 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFE4)
+#define PL111_REG_CLCD_PERIPH_ID_2 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFE8)
+#define PL111_REG_CLCD_PERIPH_ID_3 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFEC)
+#define PL111_REG_CLCD_P_CELL_ID_0 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFF0)
+#define PL111_REG_CLCD_P_CELL_ID_1 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFF4)
+#define PL111_REG_CLCD_P_CELL_ID_2 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFF8)
+#define PL111_REG_CLCD_P_CELL_ID_3 ((UINTN)PcdGet32 (PcdPL111LcdBase) + 0xFFC)
+
+/**********************************************************************/
+
+// Register components (register bits)
+
+// This should make life easier to program specific settings in the different registers
+// by simplifying the setting up of the individual bits of each register
+// and then assembling the final register value.
+
+/**********************************************************************/
+
+// Register: PL111_REG_LCD_TIMING_0
+#define HOR_AXIS_PANEL(hbp,hfp,hsw,hor_res) (UINT32)(((UINT32)(hbp) << 24) | ((UINT32)(hfp) << 16) | ((UINT32)(hsw) << 8) | (((UINT32)((hor_res)/16)-1) << 2))
+
+// Register: PL111_REG_LCD_TIMING_1
+#define VER_AXIS_PANEL(vbp,vfp,vsw,ver_res) (UINT32)(((UINT32)(vbp) << 24) | ((UINT32)(vfp) << 16) | ((UINT32)(vsw) << 10) | ((ver_res)-1))
+
+// Register: PL111_REG_LCD_TIMING_2
+#define PL111_BIT_SHIFT_PCD_HI 27
+#define PL111_BIT_SHIFT_BCD 26
+#define PL111_BIT_SHIFT_CPL 16
+#define PL111_BIT_SHIFT_IOE 14
+#define PL111_BIT_SHIFT_IPC 13
+#define PL111_BIT_SHIFT_IHS 12
+#define PL111_BIT_SHIFT_IVS 11
+#define PL111_BIT_SHIFT_ACB 6
+#define PL111_BIT_SHIFT_CLKSEL 5
+#define PL111_BIT_SHIFT_PCD_LO 0
+
+#define PL111_BCD (1 << 26)
+#define PL111_IPC (1 << 13)
+#define PL111_IHS (1 << 12)
+#define PL111_IVS (1 << 11)
+
+#define CLK_SIG_POLARITY(hor_res) (UINT32)(PL111_BCD | PL111_IPC | PL111_IHS | PL111_IVS | (((hor_res)-1) << 16))
+
+// Register: PL111_REG_LCD_TIMING_3
+#define PL111_BIT_SHIFT_LEE 16
+#define PL111_BIT_SHIFT_LED 0
+
+#define PL111_CTRL_WATERMARK (1 << 16)
+#define PL111_CTRL_LCD_V_COMP (1 << 12)
+#define PL111_CTRL_LCD_PWR (1 << 11)
+#define PL111_CTRL_BEPO (1 << 10)
+#define PL111_CTRL_BEBO (1 << 9)
+#define PL111_CTRL_BGR (1 << 8)
+#define PL111_CTRL_LCD_DUAL (1 << 7)
+#define PL111_CTRL_LCD_MONO_8 (1 << 6)
+#define PL111_CTRL_LCD_TFT (1 << 5)
+#define PL111_CTRL_LCD_BW (1 << 4)
+#define PL111_CTRL_LCD_1BPP (0 << 1)
+#define PL111_CTRL_LCD_2BPP (1 << 1)
+#define PL111_CTRL_LCD_4BPP (2 << 1)
+#define PL111_CTRL_LCD_8BPP (3 << 1)
+#define PL111_CTRL_LCD_16BPP (4 << 1)
+#define PL111_CTRL_LCD_24BPP (5 << 1)
+#define PL111_CTRL_LCD_16BPP_565 (6 << 1)
+#define PL111_CTRL_LCD_12BPP_444 (7 << 1)
+#define PL111_CTRL_LCD_BPP(Bpp) ((Bpp) << 1)
+#define PL111_CTRL_LCD_EN 1
+
+/**********************************************************************/
+
+// Register: PL111_REG_LCD_TIMING_0
+#define PL111_LCD_TIMING_0_HBP(hbp) (((hbp) & 0xFF) << 24)
+#define PL111_LCD_TIMING_0_HFP(hfp) (((hfp) & 0xFF) << 16)
+#define PL111_LCD_TIMING_0_HSW(hsw) (((hsw) & 0xFF) << 8)
+#define PL111_LCD_TIMING_0_PPL(ppl) (((hsw) & 0x3F) << 2)
+
+// Register: PL111_REG_LCD_TIMING_1
+#define PL111_LCD_TIMING_1_VBP(vbp) (((vbp) & 0xFF) << 24)
+#define PL111_LCD_TIMING_1_VFP(vfp) (((vfp) & 0xFF) << 16)
+#define PL111_LCD_TIMING_1_VSW(vsw) (((vsw) & 0x3F) << 10)
+#define PL111_LCD_TIMING_1_LPP(lpp) ((lpp) & 0xFC)
+
+// Register: PL111_REG_LCD_TIMING_2
+#define PL111_BIT_MASK_PCD_HI 0xF8000000
+#define PL111_BIT_MASK_BCD 0x04000000
+#define PL111_BIT_MASK_CPL 0x03FF0000
+#define PL111_BIT_MASK_IOE 0x00004000
+#define PL111_BIT_MASK_IPC 0x00002000
+#define PL111_BIT_MASK_IHS 0x00001000
+#define PL111_BIT_MASK_IVS 0x00000800
+#define PL111_BIT_MASK_ACB 0x000007C0
+#define PL111_BIT_MASK_CLKSEL 0x00000020
+#define PL111_BIT_MASK_PCD_LO 0x0000001F
+
+// Register: PL111_REG_LCD_TIMING_3
+#define PL111_BIT_MASK_LEE 0x00010000
+#define PL111_BIT_MASK_LED 0x0000007F
+
+#endif /* _PL111LCD_H__ */
diff --git a/ArmPlatformPkg/Include/Drivers/PL301Axi.h b/ArmPlatformPkg/Include/Drivers/PL301Axi.h
index 1bf936ff7..ae941839f 100644
--- a/ArmPlatformPkg/Include/Drivers/PL301Axi.h
+++ b/ArmPlatformPkg/Include/Drivers/PL301Axi.h
@@ -1,21 +1,21 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef PL301AXI_H_
-#define PL301AXI_H_
-
-VOID PL301AxiInit(UINTN FAxiBase);
-
-
-#endif /* PL301AXI_H_ */
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef PL301AXI_H_
+#define PL301AXI_H_
+
+VOID PL301AxiInit(UINTN FAxiBase);
+
+
+#endif /* PL301AXI_H_ */
diff --git a/ArmPlatformPkg/Include/Drivers/PL341Dmc.h b/ArmPlatformPkg/Include/Drivers/PL341Dmc.h
index 0227ced45..268b6da5c 100644
--- a/ArmPlatformPkg/Include/Drivers/PL341Dmc.h
+++ b/ArmPlatformPkg/Include/Drivers/PL341Dmc.h
@@ -1,336 +1,336 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef _PL341DMC_H_
-#define _PL341DMC_H_
-
-
-typedef struct {
- UINTN HasQos; // has QoS registers
- UINTN MaxChip; // number of memory chips accessible
- BOOLEAN IsUserCfg;
- UINT32 User0Cfg;
- UINT32 User2Cfg;
- UINT32 RefreshPeriod;
- UINT32 CasLatency;
- UINT32 WriteLatency;
- UINT32 t_mrd;
- UINT32 t_ras;
- UINT32 t_rc;
- UINT32 t_rcd;
- UINT32 t_rfc;
- UINT32 t_rp;
- UINT32 t_rrd;
- UINT32 t_wr;
- UINT32 t_wtr;
- UINT32 t_xp;
- UINT32 t_xsr;
- UINT32 t_esr;
- UINT32 MemoryCfg;
- UINT32 MemoryCfg2;
- UINT32 MemoryCfg3;
- UINT32 ChipCfg0;
- UINT32 ChipCfg1;
- UINT32 ChipCfg2;
- UINT32 ChipCfg3;
- UINT32 t_faw;
- UINT32 t_data_en;
- UINT32 t_wdata_en;
- UINT32 ModeReg;
- UINT32 ExtModeReg;
-} PL341_DMC_CONFIG;
-
-/* Memory config bit fields */
-#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_9 0x1
-#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_10 0x2
-#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_11 0x3
-#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_12 0x4
-#define DMC_MEMORY_CONFIG_ROW_ADDRESS_11 (0x0 << 3)
-#define DMC_MEMORY_CONFIG_ROW_ADDRESS_12 (0x1 << 3)
-#define DMC_MEMORY_CONFIG_ROW_ADDRESS_13 (0x2 << 3)
-#define DMC_MEMORY_CONFIG_ROW_ADDRESS_14 (0x3 << 3)
-#define DMC_MEMORY_CONFIG_ROW_ADDRESS_15 (0x4 << 3)
-#define DMC_MEMORY_CONFIG_ROW_ADDRESS_16 (0x5 << 3)
-#define DMC_MEMORY_CONFIG_BURST_2 (0x1 << 15)
-#define DMC_MEMORY_CONFIG_BURST_4 (0x2 << 15)
-#define DMC_MEMORY_CONFIG_BURST_8 (0x3 << 15)
-#define DMC_MEMORY_CONFIG_BURST_16 (0x4 << 15)
-#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_1 (0x0 << 21)
-#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_2 (0x1 << 21)
-#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_3 (0x2 << 21)
-#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_4 (0x3 << 21)
-
-#define DMC_MEMORY_CFG2_CLK_ASYNC (0x0 << 0)
-#define DMC_MEMORY_CFG2_CLK_SYNC (0x1 << 0)
-#define DMC_MEMORY_CFG2_DQM_INIT (0x1 << 2)
-#define DMC_MEMORY_CFG2_CKE_INIT (0x1 << 3)
-#define DMC_MEMORY_CFG2_BANK_BITS_2 (0x0 << 4)
-#define DMC_MEMORY_CFG2_BANK_BITS_3 (0x3 << 4)
-#define DMC_MEMORY_CFG2_MEM_WIDTH_16 (0x0 << 6)
-#define DMC_MEMORY_CFG2_MEM_WIDTH_32 (0x1 << 6)
-#define DMC_MEMORY_CFG2_MEM_WIDTH_64 (0x2 << 6)
-#define DMC_MEMORY_CFG2_MEM_WIDTH_RESERVED (0x3 << 6)
-
-//
-// DMC Configuration Register Map
-//
-#define DMC_STATUS_REG 0x00
-#define DMC_COMMAND_REG 0x04
-#define DMC_DIRECT_CMD_REG 0x08
-#define DMC_MEMORY_CONFIG_REG 0x0C
-#define DMC_REFRESH_PRD_REG 0x10
-#define DMC_CAS_LATENCY_REG 0x14
-#define DMC_WRITE_LATENCY_REG 0x18
-#define DMC_T_MRD_REG 0x1C
-#define DMC_T_RAS_REG 0x20
-#define DMC_T_RC_REG 0x24
-#define DMC_T_RCD_REG 0x28
-#define DMC_T_RFC_REG 0x2C
-#define DMC_T_RP_REG 0x30
-#define DMC_T_RRD_REG 0x34
-#define DMC_T_WR_REG 0x38
-#define DMC_T_WTR_REG 0x3C
-#define DMC_T_XP_REG 0x40
-#define DMC_T_XSR_REG 0x44
-#define DMC_T_ESR_REG 0x48
-#define DMC_MEMORY_CFG2_REG 0x4C
-#define DMC_MEMORY_CFG3_REG 0x50
-#define DMC_T_FAW_REG 0x54
-#define DMC_T_RDATA_EN 0x5C /* DFI read data enable register */
-#define DMC_T_WRLAT_DIFF 0x60 /* DFI write data enable register */
-
-// Returns the state of the memory controller:
-#define DMC_STATUS_CONFIG 0x0
-#define DMC_STATUS_READY 0x1
-#define DMC_STATUS_PAUSED 0x2
-#define DMC_STATUS_LOWPOWER 0x3
-
-// Changes the state of the memory controller:
-#define DMC_COMMAND_GO 0x0
-#define DMC_COMMAND_SLEEP 0x1
-#define DMC_COMMAND_WAKEUP 0x2
-#define DMC_COMMAND_PAUSE 0x3
-#define DMC_COMMAND_CONFIGURE 0x4
-#define DMC_COMMAND_ACTIVEPAUSE 0x7
-
-// Determines the command required
-#define DMC_DIRECT_CMD_MEMCMD_PRECHARGEALL 0x0
-#define DMC_DIRECT_CMD_MEMCMD_AUTOREFRESH (0x1 << 18)
-#define DMC_DIRECT_CMD_MEMCMD_MODEREG (0x2 << 18)
-#define DMC_DIRECT_CMD_MEMCMD_EXTMODEREG (0x2 << 18)
-#define DMC_DIRECT_CMD_MEMCMD_NOP (0x3 << 18)
-#define DMC_DIRECT_CMD_MEMCMD_DPD (0x1 << 22)
-#define DMC_DIRECT_CMD_BANKADDR(n) ((n & 0x3) << 16)
-#define DMC_DIRECT_CMD_CHIP_ADDR(n) ((n & 0x3) << 20)
-
-
-//
-// AXI ID configuration register map
-//
-#define DMC_ID_0_CFG_REG 0x100
-#define DMC_ID_1_CFG_REG 0x104
-#define DMC_ID_2_CFG_REG 0x108
-#define DMC_ID_3_CFG_REG 0x10C
-#define DMC_ID_4_CFG_REG 0x110
-#define DMC_ID_5_CFG_REG 0x114
-#define DMC_ID_6_CFG_REG 0x118
-#define DMC_ID_7_CFG_REG 0x11C
-#define DMC_ID_8_CFG_REG 0x120
-#define DMC_ID_9_CFG_REG 0x124
-#define DMC_ID_10_CFG_REG 0x128
-#define DMC_ID_11_CFG_REG 0x12C
-#define DMC_ID_12_CFG_REG 0x130
-#define DMC_ID_13_CFG_REG 0x134
-#define DMC_ID_14_CFG_REG 0x138
-#define DMC_ID_15_CFG_REG 0x13C
-
-// Set the QoS
-#define DMC_ID_CFG_QOS_DISABLE 0
-#define DMC_ID_CFG_QOS_ENABLE 1
-#define DMC_ID_CFG_QOS_MIN 2
-
-
-//
-// Chip configuration register map
-//
-#define DMC_CHIP_0_CFG_REG 0x200
-#define DMC_CHIP_1_CFG_REG 0x204
-#define DMC_CHIP_2_CFG_REG 0x208
-#define DMC_CHIP_3_CFG_REG 0x20C
-
-//
-// User Defined Pins
-//
-#define DMC_USER_STATUS_REG 0x300
-#define DMC_USER_0_CFG_REG 0x304
-#define DMC_USER_1_CFG_REG 0x308
-#define DMC_FEATURE_CRTL_REG 0x30C
-#define DMC_USER_2_CFG_REG 0x310
-
-
-//
-// PHY Register Settings
-//
-#define PHY_PTM_DFI_CLK_RANGE 0xE00 // DDR2 PHY PTM register offset
-#define PHY_PTM_IOTERM 0xE04
-#define PHY_PTM_PLL_EN 0xe0c
-#define PHY_PTM_PLL_RANGE 0xe18
-#define PHY_PTM_FEEBACK_DIV 0xe1c
-#define PHY_PTM_RCLK_DIV 0xe20
-#define PHY_PTM_LOCK_STATUS 0xe28
-#define PHY_PTM_INIT_DONE 0xe34
-#define PHY_PTM_ADDCOM_IOSTR_OFF 0xec8
-#define PHY_PTM_SQU_TRAINING 0xee8
-#define PHY_PTM_SQU_STAT 0xeec
-
-// ==============================================================================
-// PIPD 40G DDR2/DDR3 PHY Register definitions
-//
-// Offsets from APB Base Address
-// ==============================================================================
-#define PHY_BYTE0_OFFSET 0x000
-#define PHY_BYTE1_OFFSET 0x200
-#define PHY_BYTE2_OFFSET 0x400
-#define PHY_BYTE3_OFFSET 0x600
-
-#define PHY_BYTE0_COARSE_SQADJ_INIT 0x064 ;// Coarse squelch adjust
-#define PHY_BYTE1_COARSE_SQADJ_INIT 0x264 ;// Coarse squelch adjust
-#define PHY_BYTE2_COARSE_SQADJ_INIT 0x464 ;// Coarse squelch adjust
-#define PHY_BYTE3_COARSE_SQADJ_INIT 0x664 ;// Coarse squelch adjust
-
-#define PHY_BYTE0_IOSTR_OFFSET 0x004
-#define PHY_BYTE1_IOSTR_OFFSET 0x204
-#define PHY_BYTE2_IOSTR_OFFSET 0x404
-#define PHY_BYTE3_IOSTR_OFFSET 0x604
-
-
-;//--------------------------------------------------------------------------
-
-// DFI Clock ranges:
-
-#define PHY_PTM_DFI_CLK_RANGE_200MHz 0x0
-#define PHY_PTM_DFI_CLK_RANGE_201_267MHz 0x1
-#define PHY_PTM_DFI_CLK_RANGE_268_333MHz 0x2
-#define PHY_PTM_DFI_CLK_RANGE_334_400MHz 0x3
-#define PHY_PTM_DFI_CLK_RANGE_401_533MHz 0x4
-#define PHY_PTM_DFI_CLK_RANGE_534_667MHz 0x5
-#define PHY_PTM_DFI_CLK_RANGE_668_800MHz 0x6
-
-
-
-#define PHY_PTM_DFI_CLK_RANGE_VAL PHY_PTM_DFI_CLK_RANGE_334_400MHz
-
-//--------------------------------------------------------------------------
-
-
-// PLL Range
-
-#define PHY_PTM_PLL_RANGE_200_400MHz 0x0 // b0 = frequency >= 200 MHz and < 400 MHz
-#define PHY_PTM_PLL_RANGE_400_800MHz 0x1 // b1 = frequency >= 400 MHz.
-#define PHY_PTM_FEEBACK_DIV_200_400MHz 0x0 // b0 = frequency >= 200 MHz and < 400 MHz
-#define PHY_PTM_FEEBACK_DIV_400_800MHz 0x1 // b1 = frequency >= 400 MHz.
-#define PHY_PTM_REFCLK_DIV_200_400MHz 0x0
-#define PHY_PTM_REFCLK_DIV_400_800MHz 0x1
-
-#define TC_UIOLHNC_MASK 0x000003C0
-#define TC_UIOLHNC_SHIFT 0x6
-#define TC_UIOLHPC_MASK 0x0000003F
-#define TC_UIOLHPC_SHIFT 0x2
-#define TC_UIOHOCT_MASK 0x2
-#define TC_UIOHOCT_SHIFT 0x1
-#define TC_UIOHSTOP_SHIFT 0x0
-#define TC_UIOLHXC_VALUE 0x4
-
-#define PHY_PTM_SQU_TRAINING_ENABLE 0x1
-#define PHY_PTM_SQU_TRAINING_DISABLE 0x0
-
-
-//--------------------------------------
-// JEDEC DDR2 Device Register definitions and settings
-//--------------------------------------
-#define DDR_MODESET_SHFT 14
-#define DDR_MODESET_MR 0x0 ;// Mode register
-#define DDR_MODESET_EMR 0x1 ;// Extended Mode register
-#define DDR_MODESET_EMR2 0x2
-#define DDR_MODESET_EMR3 0x3
-
-//
-// Extended Mode Register settings
-//
-#define DDR_EMR_OCD_MASK 0x0000380
-#define DDR_EMR_OCD_SHIFT 0x7
-#define DDR_EMR_RTT_MASK 0x00000044 // DDR2 Device RTT (ODT) settings
-#define DDR_EMR_RTT_SHIFT 0x2
-#define DDR_EMR_ODS_MASK 0x00000002 // DDR2 Output Drive Strength
-#define DDR_EMR_ODS_SHIFT 0x0001
-
-// Termination Values:
-#define DDR_EMR_RTT_50R 0x00000044 // DDR2 50 Ohm termination
-#define DDR_EMR_RTT_75R 0x00000004 // DDR2 75 Ohm termination
-#define DDR_EMR_RTT_150 0x00000040 // DDR2 150 Ohm termination
-
-// Output Drive Strength Values:
-#define DDR_EMR_ODS_FULL 0x0 // DDR2 Full Drive Strength
-#define DDR_EMR_ODS_HALF 0x1 // DDR2 Half Drive Strength
-
-// OCD values
-#define DDR_EMR_OCD_DEFAULT 0x7
-#define DDR_EMR_OCD_NS 0x0
-
-#define DDR_EMR_ODS_VAL DDR_EMR_ODS_FULL
-
-#define DDR_SDRAM_START_ADDR 0x10000000
-
-
-// ----------------------------------------
-// PHY IOTERM values
-// ----------------------------------------
-#define PHY_PTM_IOTERM_OFF 0x0
-#define PHY_PTM_IOTERM_150R 0x1
-#define PHY_PTM_IOTERM_75R 0x2
-#define PHY_PTM_IOTERM_50R 0x3
-
-#define PHY_BYTE_IOSTR_60OHM 0x0
-#define PHY_BYTE_IOSTR_40OHM 0x1
-#define PHY_BYTE_IOSTR_30OHM 0x2
-#define PHY_BYTE_IOSTR_30AOHM 0x3
-
-#define DDR2_MR_BURST_LENGTH_4 (2)
-#define DDR2_MR_BURST_LENGTH_8 (3)
-#define DDR2_MR_DLL_RESET (1 << 8)
-#define DDR2_MR_CAS_LATENCY_4 (4 << 4)
-#define DDR2_MR_CAS_LATENCY_5 (5 << 4)
-#define DDR2_MR_CAS_LATENCY_6 (6 << 4)
-#define DDR2_MR_WR_CYCLES_2 (1 << 9)
-#define DDR2_MR_WR_CYCLES_3 (2 << 9)
-#define DDR2_MR_WR_CYCLES_4 (3 << 9)
-#define DDR2_MR_WR_CYCLES_5 (4 << 9)
-#define DDR2_MR_WR_CYCLES_6 (5 << 9)
-
-
-VOID
-PL341DmcInit (
- IN UINTN DmcBase,
- IN PL341_DMC_CONFIG* DmcConfig
- );
-
-VOID PL341DmcPhyInit (
- IN UINTN DmcPhyBase
- );
-
-VOID PL341DmcTrainPHY (
- IN UINTN DmcPhyBase
- );
-
-#endif /* _PL341DMC_H_ */
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef _PL341DMC_H_
+#define _PL341DMC_H_
+
+
+typedef struct {
+ UINTN HasQos; // has QoS registers
+ UINTN MaxChip; // number of memory chips accessible
+ BOOLEAN IsUserCfg;
+ UINT32 User0Cfg;
+ UINT32 User2Cfg;
+ UINT32 RefreshPeriod;
+ UINT32 CasLatency;
+ UINT32 WriteLatency;
+ UINT32 t_mrd;
+ UINT32 t_ras;
+ UINT32 t_rc;
+ UINT32 t_rcd;
+ UINT32 t_rfc;
+ UINT32 t_rp;
+ UINT32 t_rrd;
+ UINT32 t_wr;
+ UINT32 t_wtr;
+ UINT32 t_xp;
+ UINT32 t_xsr;
+ UINT32 t_esr;
+ UINT32 MemoryCfg;
+ UINT32 MemoryCfg2;
+ UINT32 MemoryCfg3;
+ UINT32 ChipCfg0;
+ UINT32 ChipCfg1;
+ UINT32 ChipCfg2;
+ UINT32 ChipCfg3;
+ UINT32 t_faw;
+ UINT32 t_data_en;
+ UINT32 t_wdata_en;
+ UINT32 ModeReg;
+ UINT32 ExtModeReg;
+} PL341_DMC_CONFIG;
+
+/* Memory config bit fields */
+#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_9 0x1
+#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_10 0x2
+#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_11 0x3
+#define DMC_MEMORY_CONFIG_COLUMN_ADDRESS_12 0x4
+#define DMC_MEMORY_CONFIG_ROW_ADDRESS_11 (0x0 << 3)
+#define DMC_MEMORY_CONFIG_ROW_ADDRESS_12 (0x1 << 3)
+#define DMC_MEMORY_CONFIG_ROW_ADDRESS_13 (0x2 << 3)
+#define DMC_MEMORY_CONFIG_ROW_ADDRESS_14 (0x3 << 3)
+#define DMC_MEMORY_CONFIG_ROW_ADDRESS_15 (0x4 << 3)
+#define DMC_MEMORY_CONFIG_ROW_ADDRESS_16 (0x5 << 3)
+#define DMC_MEMORY_CONFIG_BURST_2 (0x1 << 15)
+#define DMC_MEMORY_CONFIG_BURST_4 (0x2 << 15)
+#define DMC_MEMORY_CONFIG_BURST_8 (0x3 << 15)
+#define DMC_MEMORY_CONFIG_BURST_16 (0x4 << 15)
+#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_1 (0x0 << 21)
+#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_2 (0x1 << 21)
+#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_3 (0x2 << 21)
+#define DMC_MEMORY_CONFIG_ACTIVE_CHIP_4 (0x3 << 21)
+
+#define DMC_MEMORY_CFG2_CLK_ASYNC (0x0 << 0)
+#define DMC_MEMORY_CFG2_CLK_SYNC (0x1 << 0)
+#define DMC_MEMORY_CFG2_DQM_INIT (0x1 << 2)
+#define DMC_MEMORY_CFG2_CKE_INIT (0x1 << 3)
+#define DMC_MEMORY_CFG2_BANK_BITS_2 (0x0 << 4)
+#define DMC_MEMORY_CFG2_BANK_BITS_3 (0x3 << 4)
+#define DMC_MEMORY_CFG2_MEM_WIDTH_16 (0x0 << 6)
+#define DMC_MEMORY_CFG2_MEM_WIDTH_32 (0x1 << 6)
+#define DMC_MEMORY_CFG2_MEM_WIDTH_64 (0x2 << 6)
+#define DMC_MEMORY_CFG2_MEM_WIDTH_RESERVED (0x3 << 6)
+
+//
+// DMC Configuration Register Map
+//
+#define DMC_STATUS_REG 0x00
+#define DMC_COMMAND_REG 0x04
+#define DMC_DIRECT_CMD_REG 0x08
+#define DMC_MEMORY_CONFIG_REG 0x0C
+#define DMC_REFRESH_PRD_REG 0x10
+#define DMC_CAS_LATENCY_REG 0x14
+#define DMC_WRITE_LATENCY_REG 0x18
+#define DMC_T_MRD_REG 0x1C
+#define DMC_T_RAS_REG 0x20
+#define DMC_T_RC_REG 0x24
+#define DMC_T_RCD_REG 0x28
+#define DMC_T_RFC_REG 0x2C
+#define DMC_T_RP_REG 0x30
+#define DMC_T_RRD_REG 0x34
+#define DMC_T_WR_REG 0x38
+#define DMC_T_WTR_REG 0x3C
+#define DMC_T_XP_REG 0x40
+#define DMC_T_XSR_REG 0x44
+#define DMC_T_ESR_REG 0x48
+#define DMC_MEMORY_CFG2_REG 0x4C
+#define DMC_MEMORY_CFG3_REG 0x50
+#define DMC_T_FAW_REG 0x54
+#define DMC_T_RDATA_EN 0x5C /* DFI read data enable register */
+#define DMC_T_WRLAT_DIFF 0x60 /* DFI write data enable register */
+
+// Returns the state of the memory controller:
+#define DMC_STATUS_CONFIG 0x0
+#define DMC_STATUS_READY 0x1
+#define DMC_STATUS_PAUSED 0x2
+#define DMC_STATUS_LOWPOWER 0x3
+
+// Changes the state of the memory controller:
+#define DMC_COMMAND_GO 0x0
+#define DMC_COMMAND_SLEEP 0x1
+#define DMC_COMMAND_WAKEUP 0x2
+#define DMC_COMMAND_PAUSE 0x3
+#define DMC_COMMAND_CONFIGURE 0x4
+#define DMC_COMMAND_ACTIVEPAUSE 0x7
+
+// Determines the command required
+#define DMC_DIRECT_CMD_MEMCMD_PRECHARGEALL 0x0
+#define DMC_DIRECT_CMD_MEMCMD_AUTOREFRESH (0x1 << 18)
+#define DMC_DIRECT_CMD_MEMCMD_MODEREG (0x2 << 18)
+#define DMC_DIRECT_CMD_MEMCMD_EXTMODEREG (0x2 << 18)
+#define DMC_DIRECT_CMD_MEMCMD_NOP (0x3 << 18)
+#define DMC_DIRECT_CMD_MEMCMD_DPD (0x1 << 22)
+#define DMC_DIRECT_CMD_BANKADDR(n) ((n & 0x3) << 16)
+#define DMC_DIRECT_CMD_CHIP_ADDR(n) ((n & 0x3) << 20)
+
+
+//
+// AXI ID configuration register map
+//
+#define DMC_ID_0_CFG_REG 0x100
+#define DMC_ID_1_CFG_REG 0x104
+#define DMC_ID_2_CFG_REG 0x108
+#define DMC_ID_3_CFG_REG 0x10C
+#define DMC_ID_4_CFG_REG 0x110
+#define DMC_ID_5_CFG_REG 0x114
+#define DMC_ID_6_CFG_REG 0x118
+#define DMC_ID_7_CFG_REG 0x11C
+#define DMC_ID_8_CFG_REG 0x120
+#define DMC_ID_9_CFG_REG 0x124
+#define DMC_ID_10_CFG_REG 0x128
+#define DMC_ID_11_CFG_REG 0x12C
+#define DMC_ID_12_CFG_REG 0x130
+#define DMC_ID_13_CFG_REG 0x134
+#define DMC_ID_14_CFG_REG 0x138
+#define DMC_ID_15_CFG_REG 0x13C
+
+// Set the QoS
+#define DMC_ID_CFG_QOS_DISABLE 0
+#define DMC_ID_CFG_QOS_ENABLE 1
+#define DMC_ID_CFG_QOS_MIN 2
+
+
+//
+// Chip configuration register map
+//
+#define DMC_CHIP_0_CFG_REG 0x200
+#define DMC_CHIP_1_CFG_REG 0x204
+#define DMC_CHIP_2_CFG_REG 0x208
+#define DMC_CHIP_3_CFG_REG 0x20C
+
+//
+// User Defined Pins
+//
+#define DMC_USER_STATUS_REG 0x300
+#define DMC_USER_0_CFG_REG 0x304
+#define DMC_USER_1_CFG_REG 0x308
+#define DMC_FEATURE_CRTL_REG 0x30C
+#define DMC_USER_2_CFG_REG 0x310
+
+
+//
+// PHY Register Settings
+//
+#define PHY_PTM_DFI_CLK_RANGE 0xE00 // DDR2 PHY PTM register offset
+#define PHY_PTM_IOTERM 0xE04
+#define PHY_PTM_PLL_EN 0xe0c
+#define PHY_PTM_PLL_RANGE 0xe18
+#define PHY_PTM_FEEBACK_DIV 0xe1c
+#define PHY_PTM_RCLK_DIV 0xe20
+#define PHY_PTM_LOCK_STATUS 0xe28
+#define PHY_PTM_INIT_DONE 0xe34
+#define PHY_PTM_ADDCOM_IOSTR_OFF 0xec8
+#define PHY_PTM_SQU_TRAINING 0xee8
+#define PHY_PTM_SQU_STAT 0xeec
+
+// ==============================================================================
+// PIPD 40G DDR2/DDR3 PHY Register definitions
+//
+// Offsets from APB Base Address
+// ==============================================================================
+#define PHY_BYTE0_OFFSET 0x000
+#define PHY_BYTE1_OFFSET 0x200
+#define PHY_BYTE2_OFFSET 0x400
+#define PHY_BYTE3_OFFSET 0x600
+
+#define PHY_BYTE0_COARSE_SQADJ_INIT 0x064 ;// Coarse squelch adjust
+#define PHY_BYTE1_COARSE_SQADJ_INIT 0x264 ;// Coarse squelch adjust
+#define PHY_BYTE2_COARSE_SQADJ_INIT 0x464 ;// Coarse squelch adjust
+#define PHY_BYTE3_COARSE_SQADJ_INIT 0x664 ;// Coarse squelch adjust
+
+#define PHY_BYTE0_IOSTR_OFFSET 0x004
+#define PHY_BYTE1_IOSTR_OFFSET 0x204
+#define PHY_BYTE2_IOSTR_OFFSET 0x404
+#define PHY_BYTE3_IOSTR_OFFSET 0x604
+
+
+;//--------------------------------------------------------------------------
+
+// DFI Clock ranges:
+
+#define PHY_PTM_DFI_CLK_RANGE_200MHz 0x0
+#define PHY_PTM_DFI_CLK_RANGE_201_267MHz 0x1
+#define PHY_PTM_DFI_CLK_RANGE_268_333MHz 0x2
+#define PHY_PTM_DFI_CLK_RANGE_334_400MHz 0x3
+#define PHY_PTM_DFI_CLK_RANGE_401_533MHz 0x4
+#define PHY_PTM_DFI_CLK_RANGE_534_667MHz 0x5
+#define PHY_PTM_DFI_CLK_RANGE_668_800MHz 0x6
+
+
+
+#define PHY_PTM_DFI_CLK_RANGE_VAL PHY_PTM_DFI_CLK_RANGE_334_400MHz
+
+//--------------------------------------------------------------------------
+
+
+// PLL Range
+
+#define PHY_PTM_PLL_RANGE_200_400MHz 0x0 // b0 = frequency >= 200 MHz and < 400 MHz
+#define PHY_PTM_PLL_RANGE_400_800MHz 0x1 // b1 = frequency >= 400 MHz.
+#define PHY_PTM_FEEBACK_DIV_200_400MHz 0x0 // b0 = frequency >= 200 MHz and < 400 MHz
+#define PHY_PTM_FEEBACK_DIV_400_800MHz 0x1 // b1 = frequency >= 400 MHz.
+#define PHY_PTM_REFCLK_DIV_200_400MHz 0x0
+#define PHY_PTM_REFCLK_DIV_400_800MHz 0x1
+
+#define TC_UIOLHNC_MASK 0x000003C0
+#define TC_UIOLHNC_SHIFT 0x6
+#define TC_UIOLHPC_MASK 0x0000003F
+#define TC_UIOLHPC_SHIFT 0x2
+#define TC_UIOHOCT_MASK 0x2
+#define TC_UIOHOCT_SHIFT 0x1
+#define TC_UIOHSTOP_SHIFT 0x0
+#define TC_UIOLHXC_VALUE 0x4
+
+#define PHY_PTM_SQU_TRAINING_ENABLE 0x1
+#define PHY_PTM_SQU_TRAINING_DISABLE 0x0
+
+
+//--------------------------------------
+// JEDEC DDR2 Device Register definitions and settings
+//--------------------------------------
+#define DDR_MODESET_SHFT 14
+#define DDR_MODESET_MR 0x0 ;// Mode register
+#define DDR_MODESET_EMR 0x1 ;// Extended Mode register
+#define DDR_MODESET_EMR2 0x2
+#define DDR_MODESET_EMR3 0x3
+
+//
+// Extended Mode Register settings
+//
+#define DDR_EMR_OCD_MASK 0x0000380
+#define DDR_EMR_OCD_SHIFT 0x7
+#define DDR_EMR_RTT_MASK 0x00000044 // DDR2 Device RTT (ODT) settings
+#define DDR_EMR_RTT_SHIFT 0x2
+#define DDR_EMR_ODS_MASK 0x00000002 // DDR2 Output Drive Strength
+#define DDR_EMR_ODS_SHIFT 0x0001
+
+// Termination Values:
+#define DDR_EMR_RTT_50R 0x00000044 // DDR2 50 Ohm termination
+#define DDR_EMR_RTT_75R 0x00000004 // DDR2 75 Ohm termination
+#define DDR_EMR_RTT_150 0x00000040 // DDR2 150 Ohm termination
+
+// Output Drive Strength Values:
+#define DDR_EMR_ODS_FULL 0x0 // DDR2 Full Drive Strength
+#define DDR_EMR_ODS_HALF 0x1 // DDR2 Half Drive Strength
+
+// OCD values
+#define DDR_EMR_OCD_DEFAULT 0x7
+#define DDR_EMR_OCD_NS 0x0
+
+#define DDR_EMR_ODS_VAL DDR_EMR_ODS_FULL
+
+#define DDR_SDRAM_START_ADDR 0x10000000
+
+
+// ----------------------------------------
+// PHY IOTERM values
+// ----------------------------------------
+#define PHY_PTM_IOTERM_OFF 0x0
+#define PHY_PTM_IOTERM_150R 0x1
+#define PHY_PTM_IOTERM_75R 0x2
+#define PHY_PTM_IOTERM_50R 0x3
+
+#define PHY_BYTE_IOSTR_60OHM 0x0
+#define PHY_BYTE_IOSTR_40OHM 0x1
+#define PHY_BYTE_IOSTR_30OHM 0x2
+#define PHY_BYTE_IOSTR_30AOHM 0x3
+
+#define DDR2_MR_BURST_LENGTH_4 (2)
+#define DDR2_MR_BURST_LENGTH_8 (3)
+#define DDR2_MR_DLL_RESET (1 << 8)
+#define DDR2_MR_CAS_LATENCY_4 (4 << 4)
+#define DDR2_MR_CAS_LATENCY_5 (5 << 4)
+#define DDR2_MR_CAS_LATENCY_6 (6 << 4)
+#define DDR2_MR_WR_CYCLES_2 (1 << 9)
+#define DDR2_MR_WR_CYCLES_3 (2 << 9)
+#define DDR2_MR_WR_CYCLES_4 (3 << 9)
+#define DDR2_MR_WR_CYCLES_5 (4 << 9)
+#define DDR2_MR_WR_CYCLES_6 (5 << 9)
+
+
+VOID
+PL341DmcInit (
+ IN UINTN DmcBase,
+ IN PL341_DMC_CONFIG* DmcConfig
+ );
+
+VOID PL341DmcPhyInit (
+ IN UINTN DmcPhyBase
+ );
+
+VOID PL341DmcTrainPHY (
+ IN UINTN DmcPhyBase
+ );
+
+#endif /* _PL341DMC_H_ */
diff --git a/ArmPlatformPkg/Include/Guid/ArmGlobalVariableHob.h b/ArmPlatformPkg/Include/Guid/ArmGlobalVariableHob.h
index 7414b1005..f61036840 100644
--- a/ArmPlatformPkg/Include/Guid/ArmGlobalVariableHob.h
+++ b/ArmPlatformPkg/Include/Guid/ArmGlobalVariableHob.h
@@ -1,48 +1,48 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef __ARM_GLOBAL_VARIABLE_GUID_H__
-#define __ARM_GLOBAL_VARIABLE_GUID_H__
-
-#define ARM_HOB_GLOBAL_VARIABLE_GUID \
- { 0xc3253c90, 0xa24f, 0x4599, { 0xa6, 0x64, 0x1f, 0x88, 0x13, 0x77, 0x8f, 0xc9} };
-
-extern EFI_GUID gArmGlobalVariableGuid;
-
-///
-/// Describes all memory ranges used during the HOB producer
-/// phase that exist outside the HOB list. This HOB type
-/// describes how memory is used, not the physical attributes of memory.
-///
-typedef struct {
- ///
- /// The Guid HOB header. Header.HobType = EFI_HOB_TYPE_GUID_EXTENSION
- /// and Header.Name = gArmGlobalVariableGuid
- ///
- EFI_HOB_GUID_TYPE Header;
-
- ///
- /// The base address of memory allocated by this HOB. Type
- /// EFI_PHYSICAL_ADDRESS is defined in AllocatePages() in the UEFI 2.0
- /// specification.
- ///
- EFI_PHYSICAL_ADDRESS GlobalVariableBase;
-
- ///
- /// The length in bytes of memory allocated by this HOB.
- ///
- UINT32 GlobalVariableSize;
-} ARM_HOB_GLOBAL_VARIABLE;
-
-#endif
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef __ARM_GLOBAL_VARIABLE_GUID_H__
+#define __ARM_GLOBAL_VARIABLE_GUID_H__
+
+#define ARM_HOB_GLOBAL_VARIABLE_GUID \
+ { 0xc3253c90, 0xa24f, 0x4599, { 0xa6, 0x64, 0x1f, 0x88, 0x13, 0x77, 0x8f, 0xc9} };
+
+extern EFI_GUID gArmGlobalVariableGuid;
+
+///
+/// Describes all memory ranges used during the HOB producer
+/// phase that exist outside the HOB list. This HOB type
+/// describes how memory is used, not the physical attributes of memory.
+///
+typedef struct {
+ ///
+ /// The Guid HOB header. Header.HobType = EFI_HOB_TYPE_GUID_EXTENSION
+ /// and Header.Name = gArmGlobalVariableGuid
+ ///
+ EFI_HOB_GUID_TYPE Header;
+
+ ///
+ /// The base address of memory allocated by this HOB. Type
+ /// EFI_PHYSICAL_ADDRESS is defined in AllocatePages() in the UEFI 2.0
+ /// specification.
+ ///
+ EFI_PHYSICAL_ADDRESS GlobalVariableBase;
+
+ ///
+ /// The length in bytes of memory allocated by this HOB.
+ ///
+ UINT32 GlobalVariableSize;
+} ARM_HOB_GLOBAL_VARIABLE;
+
+#endif
diff --git a/ArmPlatformPkg/Include/Library/ArmPlatformGlobalVariableLib.h b/ArmPlatformPkg/Include/Library/ArmPlatformGlobalVariableLib.h
index 02ef1ea83..b1a080c00 100644
--- a/ArmPlatformPkg/Include/Library/ArmPlatformGlobalVariableLib.h
+++ b/ArmPlatformPkg/Include/Library/ArmPlatformGlobalVariableLib.h
@@ -1,38 +1,38 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef __ARM_PLATFORM_GLOBAL_VARIABLE_LIB_H_
-#define __ARM_PLATFORM_GLOBAL_VARIABLE_LIB_H_
-
-VOID
-ArmPlatformGetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- );
-
-VOID
-ArmPlatformSetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- );
-
-VOID*
-ArmPlatformGetGlobalVariableAddress (
- IN UINTN VariableOffset
- );
-
-#endif
-
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef __ARM_PLATFORM_GLOBAL_VARIABLE_LIB_H_
+#define __ARM_PLATFORM_GLOBAL_VARIABLE_LIB_H_
+
+VOID
+ArmPlatformGetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ );
+
+VOID
+ArmPlatformSetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ );
+
+VOID*
+ArmPlatformGetGlobalVariableAddress (
+ IN UINTN VariableOffset
+ );
+
+#endif
+
diff --git a/ArmPlatformPkg/Include/Library/ArmPlatformLib.h b/ArmPlatformPkg/Include/Library/ArmPlatformLib.h
index 9f2de60a4..7bbd96647 100644
--- a/ArmPlatformPkg/Include/Library/ArmPlatformLib.h
+++ b/ArmPlatformPkg/Include/Library/ArmPlatformLib.h
@@ -1,131 +1,131 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef _ARMPLATFORMLIB_H_
-#define _ARMPLATFORMLIB_H_
-
-//
-// The package level header files this module uses
-//
-#include <PiPei.h>
-//
-// The protocols, PPI and GUID defintions for this module
-//
-#include <Ppi/MasterBootMode.h>
-#include <Ppi/BootInRecoveryMode.h>
-#include <Guid/MemoryTypeInformation.h>
-
-#include <Library/ArmLib.h>
-
-/**
- This structure is used to describe a region of the EFI memory map
-
- Every EFI regions of the system memory described by their physical start address and their size
- can have different attributes. Some regions can be tested and other untested.
-
-**/
-typedef struct {
- EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute;
- EFI_PHYSICAL_ADDRESS PhysicalStart;
- UINT64 NumberOfBytes;
-} ARM_SYSTEM_MEMORY_REGION_DESCRIPTOR;
-
-UINTN
-ArmPlatformGetCorePosition (
- IN UINTN MpId
- );
-
-/**
- Return the current Boot Mode
-
- This function returns the boot reason on the platform
-
- @return Return the current Boot Mode of the platform
-
-**/
-EFI_BOOT_MODE
-ArmPlatformGetBootMode (
- VOID
- );
-
-/**
- Initialize controllers that must setup in the normal world
-
- This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
- in the PEI phase.
-
-**/
-RETURN_STATUS
-ArmPlatformInitialize (
- IN UINTN MpId
- );
-
-/**
- Initialize the system (or sometimes called permanent) memory
-
- This memory is generally represented by the DRAM.
-
-**/
-VOID
-ArmPlatformInitializeSystemMemory (
- VOID
- );
-
-/**
- Return the Virtual Memory Map of your platform
-
- This Virtual Memory Map is used by MemoryInitPei Module to initialize the MMU on your platform.
-
- @param[out] VirtualMemoryMap Array of ARM_MEMORY_REGION_DESCRIPTOR describing a Physical-to-
- Virtual Memory mapping. This array must be ended by a zero-filled
- entry
-
-**/
-VOID
-ArmPlatformGetVirtualMemoryMap (
- OUT ARM_MEMORY_REGION_DESCRIPTOR** VirtualMemoryMap
- );
-
-/**
- Return the EFI Memory Map of your platform
-
- This EFI Memory Map of the System Memory is used by MemoryInitPei module to create the Resource
- Descriptor HOBs used by DXE core.
-
- @param[out] EfiMemoryMap Array of ARM_SYSTEM_MEMORY_REGION_DESCRIPTOR describing an
- EFI Memory region. This array must be ended by a zero-filled entry
-
-**/
-EFI_STATUS
-ArmPlatformGetAdditionalSystemMemory (
- OUT ARM_SYSTEM_MEMORY_REGION_DESCRIPTOR** EfiMemoryMap
- );
-
-/**
- Return the Platform specific PPIs
-
- This function exposes the Platform Specific PPIs. They can be used by any PrePi modules or passed
- to the PeiCore by PrePeiCore.
-
- @param[out] PpiListSize Size in Bytes of the Platform PPI List
- @param[out] PpiList Platform PPI List
-
-**/
-VOID
-ArmPlatformGetPlatformPpiList (
- OUT UINTN *PpiListSize,
- OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
- );
-
-#endif
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef _ARMPLATFORMLIB_H_
+#define _ARMPLATFORMLIB_H_
+
+//
+// The package level header files this module uses
+//
+#include <PiPei.h>
+//
+// The protocols, PPI and GUID defintions for this module
+//
+#include <Ppi/MasterBootMode.h>
+#include <Ppi/BootInRecoveryMode.h>
+#include <Guid/MemoryTypeInformation.h>
+
+#include <Library/ArmLib.h>
+
+/**
+ This structure is used to describe a region of the EFI memory map
+
+ Every EFI regions of the system memory described by their physical start address and their size
+ can have different attributes. Some regions can be tested and other untested.
+
+**/
+typedef struct {
+ EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute;
+ EFI_PHYSICAL_ADDRESS PhysicalStart;
+ UINT64 NumberOfBytes;
+} ARM_SYSTEM_MEMORY_REGION_DESCRIPTOR;
+
+UINTN
+ArmPlatformGetCorePosition (
+ IN UINTN MpId
+ );
+
+/**
+ Return the current Boot Mode
+
+ This function returns the boot reason on the platform
+
+ @return Return the current Boot Mode of the platform
+
+**/
+EFI_BOOT_MODE
+ArmPlatformGetBootMode (
+ VOID
+ );
+
+/**
+ Initialize controllers that must setup in the normal world
+
+ This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
+ in the PEI phase.
+
+**/
+RETURN_STATUS
+ArmPlatformInitialize (
+ IN UINTN MpId
+ );
+
+/**
+ Initialize the system (or sometimes called permanent) memory
+
+ This memory is generally represented by the DRAM.
+
+**/
+VOID
+ArmPlatformInitializeSystemMemory (
+ VOID
+ );
+
+/**
+ Return the Virtual Memory Map of your platform
+
+ This Virtual Memory Map is used by MemoryInitPei Module to initialize the MMU on your platform.
+
+ @param[out] VirtualMemoryMap Array of ARM_MEMORY_REGION_DESCRIPTOR describing a Physical-to-
+ Virtual Memory mapping. This array must be ended by a zero-filled
+ entry
+
+**/
+VOID
+ArmPlatformGetVirtualMemoryMap (
+ OUT ARM_MEMORY_REGION_DESCRIPTOR** VirtualMemoryMap
+ );
+
+/**
+ Return the EFI Memory Map of your platform
+
+ This EFI Memory Map of the System Memory is used by MemoryInitPei module to create the Resource
+ Descriptor HOBs used by DXE core.
+
+ @param[out] EfiMemoryMap Array of ARM_SYSTEM_MEMORY_REGION_DESCRIPTOR describing an
+ EFI Memory region. This array must be ended by a zero-filled entry
+
+**/
+EFI_STATUS
+ArmPlatformGetAdditionalSystemMemory (
+ OUT ARM_SYSTEM_MEMORY_REGION_DESCRIPTOR** EfiMemoryMap
+ );
+
+/**
+ Return the Platform specific PPIs
+
+ This function exposes the Platform Specific PPIs. They can be used by any PrePi modules or passed
+ to the PeiCore by PrePeiCore.
+
+ @param[out] PpiListSize Size in Bytes of the Platform PPI List
+ @param[out] PpiList Platform PPI List
+
+**/
+VOID
+ArmPlatformGetPlatformPpiList (
+ OUT UINTN *PpiListSize,
+ OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
+ );
+
+#endif
diff --git a/ArmPlatformPkg/Include/Library/ArmPlatformSecLib.h b/ArmPlatformPkg/Include/Library/ArmPlatformSecLib.h
index 32f1eb508..ece806490 100644
--- a/ArmPlatformPkg/Include/Library/ArmPlatformSecLib.h
+++ b/ArmPlatformPkg/Include/Library/ArmPlatformSecLib.h
@@ -1,88 +1,88 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef _ARMPLATFORMSECLIB_H_
-#define _ARMPLATFORMSECLIB_H_
-
-#define ARM_SEC_BOOT_MASK ~0
-#define ARM_SEC_COLD_BOOT (1 << 0)
-#define ARM_SEC_SECONDARY_COLD_BOOT (1 << 1)
-
-/**
- Initialize the memory where the initial stacks will reside
-
- This memory can contain the initial stacks (Secure and Secure Monitor stacks).
- In some platform, this region is already initialized and the implementation of this function can
- do nothing. This memory can also represent the Secure RAM.
- This function is called before the satck has been set up. Its implementation must ensure the stack
- pointer is not used (probably required to use assembly language)
-
-**/
-VOID
-ArmPlatformSecBootMemoryInit (
- VOID
- );
-
-/**
- Call at the beginning of the platform boot up
-
- This function allows the firmware platform to do extra actions at the early
- stage of the platform power up.
-
- Note: This function must be implemented in assembler as there is no stack set up yet
-
-**/
-VOID
-ArmPlatformSecBootAction (
- VOID
- );
-
-/**
- Initialize controllers that must setup at the early stage
-
- Some peripherals must be initialized in Secure World.
- For example: Some L2 controller, interconnect, clock, DMC, etc
-
-**/
-RETURN_STATUS
-ArmPlatformSecInitialize (
- IN UINTN MpId
- );
-
-/**
- Call before jumping to Normal World
-
- This function allows the firmware platform to do extra actions before
- jumping to the Normal World
-
-**/
-VOID
-ArmPlatformSecExtraAction (
- IN UINTN MpId,
- OUT UINTN* JumpAddress
- );
-
-/**
- Initialize the Secure peripherals and memory regions
-
- If Trustzone is supported by your platform then this function makes the required initialization
- of the secure peripherals and memory regions.
-
-**/
-VOID
-ArmPlatformSecTrustzoneInit (
- IN UINTN MpId
- );
-
-#endif
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef _ARMPLATFORMSECLIB_H_
+#define _ARMPLATFORMSECLIB_H_
+
+#define ARM_SEC_BOOT_MASK ~0
+#define ARM_SEC_COLD_BOOT (1 << 0)
+#define ARM_SEC_SECONDARY_COLD_BOOT (1 << 1)
+
+/**
+ Initialize the memory where the initial stacks will reside
+
+ This memory can contain the initial stacks (Secure and Secure Monitor stacks).
+ In some platform, this region is already initialized and the implementation of this function can
+ do nothing. This memory can also represent the Secure RAM.
+ This function is called before the satck has been set up. Its implementation must ensure the stack
+ pointer is not used (probably required to use assembly language)
+
+**/
+VOID
+ArmPlatformSecBootMemoryInit (
+ VOID
+ );
+
+/**
+ Call at the beginning of the platform boot up
+
+ This function allows the firmware platform to do extra actions at the early
+ stage of the platform power up.
+
+ Note: This function must be implemented in assembler as there is no stack set up yet
+
+**/
+VOID
+ArmPlatformSecBootAction (
+ VOID
+ );
+
+/**
+ Initialize controllers that must setup at the early stage
+
+ Some peripherals must be initialized in Secure World.
+ For example: Some L2 controller, interconnect, clock, DMC, etc
+
+**/
+RETURN_STATUS
+ArmPlatformSecInitialize (
+ IN UINTN MpId
+ );
+
+/**
+ Call before jumping to Normal World
+
+ This function allows the firmware platform to do extra actions before
+ jumping to the Normal World
+
+**/
+VOID
+ArmPlatformSecExtraAction (
+ IN UINTN MpId,
+ OUT UINTN* JumpAddress
+ );
+
+/**
+ Initialize the Secure peripherals and memory regions
+
+ If Trustzone is supported by your platform then this function makes the required initialization
+ of the secure peripherals and memory regions.
+
+**/
+VOID
+ArmPlatformSecTrustzoneInit (
+ IN UINTN MpId
+ );
+
+#endif
diff --git a/ArmPlatformPkg/Include/Library/ArmPlatformSysConfigLib.h b/ArmPlatformPkg/Include/Library/ArmPlatformSysConfigLib.h
index 3c59bcc39..39a0cc7f7 100644
--- a/ArmPlatformPkg/Include/Library/ArmPlatformSysConfigLib.h
+++ b/ArmPlatformPkg/Include/Library/ArmPlatformSysConfigLib.h
@@ -1,63 +1,63 @@
-/** @file ArmPlatformSysConfigLib.h
-
- Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __ARM_PLATFORM_SYS_CONFIG_H__
-#define __ARM_PLATFORM_SYS_CONFIG_H__
-
-#include <Base.h>
-
-/* This header file makes it easier to access the System Configuration Registers
- * in the ARM Versatile Express motherboard.
- */
-
-//
-// Typedef
-//
-typedef UINT32 SYS_CONFIG_FUNCTION;
-
-//
-// Functions
-//
-RETURN_STATUS
-ArmPlatformSysConfigInitialize (
- VOID
- );
-
-RETURN_STATUS
-ArmPlatformSysConfigGet (
- IN SYS_CONFIG_FUNCTION Function,
- OUT UINT32* Value
- );
-
-RETURN_STATUS
-ArmPlatformSysConfigGetValues (
- IN SYS_CONFIG_FUNCTION Function,
- IN UINTN Size,
- OUT UINT32* Values
- );
-
-RETURN_STATUS
-ArmPlatformSysConfigSet (
- IN SYS_CONFIG_FUNCTION Function,
- IN UINT32 Value
- );
-
-RETURN_STATUS
-ArmPlatformSysConfigSetDevice (
- IN SYS_CONFIG_FUNCTION Function,
- IN UINT32 Device,
- IN UINT32 Value
- );
-
-#endif /* __SYS_CFG_REGISTERS_H__ */
+/** @file ArmPlatformSysConfigLib.h
+
+ Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __ARM_PLATFORM_SYS_CONFIG_H__
+#define __ARM_PLATFORM_SYS_CONFIG_H__
+
+#include <Base.h>
+
+/* This header file makes it easier to access the System Configuration Registers
+ * in the ARM Versatile Express motherboard.
+ */
+
+//
+// Typedef
+//
+typedef UINT32 SYS_CONFIG_FUNCTION;
+
+//
+// Functions
+//
+RETURN_STATUS
+ArmPlatformSysConfigInitialize (
+ VOID
+ );
+
+RETURN_STATUS
+ArmPlatformSysConfigGet (
+ IN SYS_CONFIG_FUNCTION Function,
+ OUT UINT32* Value
+ );
+
+RETURN_STATUS
+ArmPlatformSysConfigGetValues (
+ IN SYS_CONFIG_FUNCTION Function,
+ IN UINTN Size,
+ OUT UINT32* Values
+ );
+
+RETURN_STATUS
+ArmPlatformSysConfigSet (
+ IN SYS_CONFIG_FUNCTION Function,
+ IN UINT32 Value
+ );
+
+RETURN_STATUS
+ArmPlatformSysConfigSetDevice (
+ IN SYS_CONFIG_FUNCTION Function,
+ IN UINT32 Device,
+ IN UINT32 Value
+ );
+
+#endif /* __SYS_CFG_REGISTERS_H__ */
diff --git a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.c b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.c
index 278138759..511d0f69d 100644
--- a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.c
+++ b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.c
@@ -1,76 +1,76 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <PiDxe.h>
-#include <Library/ArmPlatformGlobalVariableLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DebugLib.h>
-#include <Library/HobLib.h>
-#include <Library/PcdLib.h>
-
-#include <Guid/ArmGlobalVariableHob.h>
-
-UINTN mGlobalVariableBase = 0;
-
-RETURN_STATUS
-EFIAPI
-ArmPlatformGlobalVariableConstructor (
- VOID
- )
-{
- ARM_HOB_GLOBAL_VARIABLE *Hob;
-
- Hob = GetFirstGuidHob (&gArmGlobalVariableGuid);
- ASSERT (Hob != NULL);
-
- mGlobalVariableBase = Hob->GlobalVariableBase;
-
- return EFI_SUCCESS;
-}
-
-VOID
-ArmPlatformGetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- if (mGlobalVariableBase == 0) {
- ArmPlatformGlobalVariableConstructor ();
- }
-
- CopyMem (Variable, (VOID*)(mGlobalVariableBase + VariableOffset), VariableSize);
-}
-
-VOID
-ArmPlatformSetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- if (mGlobalVariableBase == 0) {
- ArmPlatformGlobalVariableConstructor ();
- }
-
- CopyMem ((VOID*)(mGlobalVariableBase + VariableOffset), Variable, VariableSize);
-}
-
-VOID*
-ArmPlatformGetGlobalVariableAddress (
- IN UINTN VariableOffset
- )
-{
- return (VOID*)(mGlobalVariableBase + VariableOffset);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <PiDxe.h>
+#include <Library/ArmPlatformGlobalVariableLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/PcdLib.h>
+
+#include <Guid/ArmGlobalVariableHob.h>
+
+UINTN mGlobalVariableBase = 0;
+
+RETURN_STATUS
+EFIAPI
+ArmPlatformGlobalVariableConstructor (
+ VOID
+ )
+{
+ ARM_HOB_GLOBAL_VARIABLE *Hob;
+
+ Hob = GetFirstGuidHob (&gArmGlobalVariableGuid);
+ ASSERT (Hob != NULL);
+
+ mGlobalVariableBase = Hob->GlobalVariableBase;
+
+ return EFI_SUCCESS;
+}
+
+VOID
+ArmPlatformGetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ if (mGlobalVariableBase == 0) {
+ ArmPlatformGlobalVariableConstructor ();
+ }
+
+ CopyMem (Variable, (VOID*)(mGlobalVariableBase + VariableOffset), VariableSize);
+}
+
+VOID
+ArmPlatformSetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ if (mGlobalVariableBase == 0) {
+ ArmPlatformGlobalVariableConstructor ();
+ }
+
+ CopyMem ((VOID*)(mGlobalVariableBase + VariableOffset), Variable, VariableSize);
+}
+
+VOID*
+ArmPlatformGetGlobalVariableAddress (
+ IN UINTN VariableOffset
+ )
+{
+ return (VOID*)(mGlobalVariableBase + VariableOffset);
+}
diff --git a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
index f2284ce4c..a0835d25f 100644
--- a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
+++ b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Dxe/DxeArmPlatformGlobalVariableLib.inf
@@ -1,44 +1,44 @@
-#/** @file
-# Timer library implementation
-#
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = DxeArmPlatformGlobalVariableLib
- FILE_GUID = 53fa3cc3-23b7-4ec2-9bfa-30257d7e1135
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformGlobalVariableLib
-
- CONSTRUCTOR = ArmPlatformGlobalVariableConstructor
-
-[Sources.common]
- DxeArmPlatformGlobalVariableLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- HobLib
-
-[Guids]
- gArmGlobalVariableGuid
-
-[FixedPcd]
- gArmPlatformTokenSpaceGuid.PcdPeiGlobalVariableSize
-
+#/** @file
+# Timer library implementation
+#
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DxeArmPlatformGlobalVariableLib
+ FILE_GUID = 53fa3cc3-23b7-4ec2-9bfa-30257d7e1135
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformGlobalVariableLib
+
+ CONSTRUCTOR = ArmPlatformGlobalVariableConstructor
+
+[Sources.common]
+ DxeArmPlatformGlobalVariableLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ HobLib
+
+[Guids]
+ gArmGlobalVariableGuid
+
+[FixedPcd]
+ gArmPlatformTokenSpaceGuid.PcdPeiGlobalVariableSize
+
diff --git a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.c b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.c
index 63aa3199f..df3e12944 100644
--- a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.c
+++ b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.c
@@ -1,84 +1,84 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Uefi.h>
-#include <Library/ArmPlatformGlobalVariableLib.h>
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/PcdLib.h>
-#include <Library/DebugLib.h>
-
-// Declared by ArmPlatformPkg/PrePi Module
-extern UINTN mGlobalVariableBase;
-
-VOID
-ArmPlatformGetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
-
- GlobalVariableBase = PcdGet32 (PcdCPUCoresStackBase) + PcdGet32 (PcdCPUCorePrimaryStackSize) - PcdGet32 (PcdPeiGlobalVariableSize);
-
- if (VariableSize == 4) {
- *(UINT32*)Variable = ReadUnaligned32 ((CONST UINT32*)(GlobalVariableBase + VariableOffset));
- } else if (VariableSize == 8) {
- *(UINT64*)Variable = ReadUnaligned64 ((CONST UINT64*)(GlobalVariableBase + VariableOffset));
- } else {
- CopyMem (Variable, (VOID*)(GlobalVariableBase + VariableOffset), VariableSize);
- }
-}
-
-VOID
-ArmPlatformSetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
-
- GlobalVariableBase = PcdGet32 (PcdCPUCoresStackBase) + PcdGet32 (PcdCPUCorePrimaryStackSize) - PcdGet32 (PcdPeiGlobalVariableSize);
-
- if (VariableSize == 4) {
- WriteUnaligned32 ((UINT32*)(GlobalVariableBase + VariableOffset), *(UINT32*)Variable);
- } else if (VariableSize == 8) {
- WriteUnaligned64 ((UINT64*)(GlobalVariableBase + VariableOffset), *(UINT64*)Variable);
- } else {
- CopyMem ((VOID*)(GlobalVariableBase + VariableOffset), Variable, VariableSize);
- }
-}
-
-VOID*
-ArmPlatformGetGlobalVariableAddress (
- IN UINTN VariableOffset
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
-
- GlobalVariableBase = PcdGet32 (PcdCPUCoresStackBase) + PcdGet32 (PcdCPUCorePrimaryStackSize) - PcdGet32 (PcdPeiGlobalVariableSize);
-
- return (VOID*)(GlobalVariableBase + VariableOffset);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Uefi.h>
+#include <Library/ArmPlatformGlobalVariableLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+
+// Declared by ArmPlatformPkg/PrePi Module
+extern UINTN mGlobalVariableBase;
+
+VOID
+ArmPlatformGetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
+
+ GlobalVariableBase = PcdGet32 (PcdCPUCoresStackBase) + PcdGet32 (PcdCPUCorePrimaryStackSize) - PcdGet32 (PcdPeiGlobalVariableSize);
+
+ if (VariableSize == 4) {
+ *(UINT32*)Variable = ReadUnaligned32 ((CONST UINT32*)(GlobalVariableBase + VariableOffset));
+ } else if (VariableSize == 8) {
+ *(UINT64*)Variable = ReadUnaligned64 ((CONST UINT64*)(GlobalVariableBase + VariableOffset));
+ } else {
+ CopyMem (Variable, (VOID*)(GlobalVariableBase + VariableOffset), VariableSize);
+ }
+}
+
+VOID
+ArmPlatformSetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
+
+ GlobalVariableBase = PcdGet32 (PcdCPUCoresStackBase) + PcdGet32 (PcdCPUCorePrimaryStackSize) - PcdGet32 (PcdPeiGlobalVariableSize);
+
+ if (VariableSize == 4) {
+ WriteUnaligned32 ((UINT32*)(GlobalVariableBase + VariableOffset), *(UINT32*)Variable);
+ } else if (VariableSize == 8) {
+ WriteUnaligned64 ((UINT64*)(GlobalVariableBase + VariableOffset), *(UINT64*)Variable);
+ } else {
+ CopyMem ((VOID*)(GlobalVariableBase + VariableOffset), Variable, VariableSize);
+ }
+}
+
+VOID*
+ArmPlatformGetGlobalVariableAddress (
+ IN UINTN VariableOffset
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
+
+ GlobalVariableBase = PcdGet32 (PcdCPUCoresStackBase) + PcdGet32 (PcdCPUCorePrimaryStackSize) - PcdGet32 (PcdPeiGlobalVariableSize);
+
+ return (VOID*)(GlobalVariableBase + VariableOffset);
+}
diff --git a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.inf b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.inf
index a14f93322..8eea9d382 100644
--- a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.inf
+++ b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Pei/PeiArmPlatformGlobalVariableLib.inf
@@ -1,40 +1,40 @@
-#/** @file
-# ArmPlatformGlobalVariableLib library implementation
-#
-# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = PeiArmPlatformGlobalVariableLib
- FILE_GUID = 3e03daf2-b7b4-45f7-80b2-12aba043391f
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformGlobalVariableLib
-
-[Sources.common]
- PeiArmPlatformGlobalVariableLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- PcdLib
-
-[FixedPcd]
- gArmPlatformTokenSpaceGuid.PcdCPUCoresStackBase
- gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize
- gArmPlatformTokenSpaceGuid.PcdPeiGlobalVariableSize
-
+#/** @file
+# ArmPlatformGlobalVariableLib library implementation
+#
+# Copyright (c) 2011-2012, ARM Ltd. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = PeiArmPlatformGlobalVariableLib
+ FILE_GUID = 3e03daf2-b7b4-45f7-80b2-12aba043391f
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformGlobalVariableLib
+
+[Sources.common]
+ PeiArmPlatformGlobalVariableLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ PcdLib
+
+[FixedPcd]
+ gArmPlatformTokenSpaceGuid.PcdCPUCoresStackBase
+ gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize
+ gArmPlatformTokenSpaceGuid.PcdPeiGlobalVariableSize
+
diff --git a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.c b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.c
index 563e405f6..47430e302 100644
--- a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.c
+++ b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/PrePi/PrePiArmPlatformGlobalVariableLib.c
@@ -1,105 +1,105 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Uefi.h>
-#include <Library/ArmPlatformGlobalVariableLib.h>
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/PcdLib.h>
-#include <Library/DebugLib.h>
-
-#define IS_XIP() (((UINT32)PcdGet32 (PcdFdBaseAddress) > (UINT32)(PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize))) || \
- ((PcdGet32 (PcdFdBaseAddress) + PcdGet32 (PcdFdSize)) < PcdGet32 (PcdSystemMemoryBase)))
-
-// Declared by ArmPlatformPkg/PrePi Module
-extern UINTN mGlobalVariableBase;
-
-VOID
-ArmPlatformGetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
-
- if (IS_XIP()) {
- // In Case of XIP, we expect the Primary Stack at the top of the System Memory
- // The size must be 64bit aligned to allow 64bit variable to be aligned
- GlobalVariableBase = PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize) - ALIGN_VALUE(PcdGet32 (PcdPeiGlobalVariableSize),0x8);
- } else {
- GlobalVariableBase = mGlobalVariableBase;
- }
-
- if (VariableSize == 4) {
- *(UINT32*)Variable = ReadUnaligned32 ((CONST UINT32*)(GlobalVariableBase + VariableOffset));
- } else if (VariableSize == 8) {
- *(UINT64*)Variable = ReadUnaligned64 ((CONST UINT64*)(GlobalVariableBase + VariableOffset));
- } else {
- CopyMem (Variable, (VOID*)(GlobalVariableBase + VariableOffset), VariableSize);
- }
-}
-
-VOID
-ArmPlatformSetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
-
- if (IS_XIP()) {
- // In Case of XIP, we expect the Primary Stack at the top of the System Memory
- // The size must be 64bit aligned to allow 64bit variable to be aligned
- GlobalVariableBase = PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize) - ALIGN_VALUE(PcdGet32 (PcdPeiGlobalVariableSize),0x8);
- } else {
- GlobalVariableBase = mGlobalVariableBase;
- }
-
- if (VariableSize == 4) {
- WriteUnaligned32 ((UINT32*)(GlobalVariableBase + VariableOffset), *(UINT32*)Variable);
- } else if (VariableSize == 8) {
- WriteUnaligned64 ((UINT64*)(GlobalVariableBase + VariableOffset), *(UINT64*)Variable);
- } else {
- CopyMem ((VOID*)(GlobalVariableBase + VariableOffset), Variable, VariableSize);
- }
-}
-
-VOID*
-ArmPlatformGetGlobalVariableAddress (
- IN UINTN VariableOffset
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
-
- if (IS_XIP()) {
- // In Case of XIP, we expect the Primary Stack at the top of the System Memory
- // The size must be 64bit aligned to allow 64bit variable to be aligned
- GlobalVariableBase = PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize) - ALIGN_VALUE(PcdGet32 (PcdPeiGlobalVariableSize),0x8);
- } else {
- GlobalVariableBase = mGlobalVariableBase;
- }
-
- return (VOID*)(GlobalVariableBase + VariableOffset);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Uefi.h>
+#include <Library/ArmPlatformGlobalVariableLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+
+#define IS_XIP() (((UINT32)PcdGet32 (PcdFdBaseAddress) > (UINT32)(PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize))) || \
+ ((PcdGet32 (PcdFdBaseAddress) + PcdGet32 (PcdFdSize)) < PcdGet32 (PcdSystemMemoryBase)))
+
+// Declared by ArmPlatformPkg/PrePi Module
+extern UINTN mGlobalVariableBase;
+
+VOID
+ArmPlatformGetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
+
+ if (IS_XIP()) {
+ // In Case of XIP, we expect the Primary Stack at the top of the System Memory
+ // The size must be 64bit aligned to allow 64bit variable to be aligned
+ GlobalVariableBase = PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize) - ALIGN_VALUE(PcdGet32 (PcdPeiGlobalVariableSize),0x8);
+ } else {
+ GlobalVariableBase = mGlobalVariableBase;
+ }
+
+ if (VariableSize == 4) {
+ *(UINT32*)Variable = ReadUnaligned32 ((CONST UINT32*)(GlobalVariableBase + VariableOffset));
+ } else if (VariableSize == 8) {
+ *(UINT64*)Variable = ReadUnaligned64 ((CONST UINT64*)(GlobalVariableBase + VariableOffset));
+ } else {
+ CopyMem (Variable, (VOID*)(GlobalVariableBase + VariableOffset), VariableSize);
+ }
+}
+
+VOID
+ArmPlatformSetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
+
+ if (IS_XIP()) {
+ // In Case of XIP, we expect the Primary Stack at the top of the System Memory
+ // The size must be 64bit aligned to allow 64bit variable to be aligned
+ GlobalVariableBase = PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize) - ALIGN_VALUE(PcdGet32 (PcdPeiGlobalVariableSize),0x8);
+ } else {
+ GlobalVariableBase = mGlobalVariableBase;
+ }
+
+ if (VariableSize == 4) {
+ WriteUnaligned32 ((UINT32*)(GlobalVariableBase + VariableOffset), *(UINT32*)Variable);
+ } else if (VariableSize == 8) {
+ WriteUnaligned64 ((UINT64*)(GlobalVariableBase + VariableOffset), *(UINT64*)Variable);
+ } else {
+ CopyMem ((VOID*)(GlobalVariableBase + VariableOffset), Variable, VariableSize);
+ }
+}
+
+VOID*
+ArmPlatformGetGlobalVariableAddress (
+ IN UINTN VariableOffset
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdPeiGlobalVariableSize));
+
+ if (IS_XIP()) {
+ // In Case of XIP, we expect the Primary Stack at the top of the System Memory
+ // The size must be 64bit aligned to allow 64bit variable to be aligned
+ GlobalVariableBase = PcdGet32 (PcdSystemMemoryBase) + PcdGet32 (PcdSystemMemorySize) - ALIGN_VALUE(PcdGet32 (PcdPeiGlobalVariableSize),0x8);
+ } else {
+ GlobalVariableBase = mGlobalVariableBase;
+ }
+
+ return (VOID*)(GlobalVariableBase + VariableOffset);
+}
diff --git a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Sec/SecArmPlatformGlobalVariableLib.c b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Sec/SecArmPlatformGlobalVariableLib.c
index 42d903f3d..978ba3336 100644
--- a/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Sec/SecArmPlatformGlobalVariableLib.c
+++ b/ArmPlatformPkg/Library/ArmPlatformGlobalVariableLib/Sec/SecArmPlatformGlobalVariableLib.c
@@ -1,81 +1,81 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Uefi.h>
-#include <Library/ArmPlatformGlobalVariableLib.h>
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/PcdLib.h>
-#include <Library/DebugLib.h>
-
-VOID
-ArmPlatformGetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdSecGlobalVariableSize));
-
- GlobalVariableBase = PcdGet32 (PcdCPUCoresSecStackBase) + PcdGet32 (PcdCPUCoreSecPrimaryStackSize) - PcdGet32 (PcdSecGlobalVariableSize);
-
- if (VariableSize == 4) {
- *(UINT32*)Variable = ReadUnaligned32 ((CONST UINT32*)(GlobalVariableBase + VariableOffset));
- } else if (VariableSize == 8) {
- *(UINT64*)Variable = ReadUnaligned64 ((CONST UINT64*)(GlobalVariableBase + VariableOffset));
- } else {
- CopyMem (Variable, (VOID*)(GlobalVariableBase + VariableOffset), VariableSize);
- }
-}
-
-VOID
-ArmPlatformSetGlobalVariable (
- IN UINTN VariableOffset,
- IN UINTN VariableSize,
- OUT VOID* Variable
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdSecGlobalVariableSize));
-
- GlobalVariableBase = PcdGet32 (PcdCPUCoresSecStackBase) + PcdGet32 (PcdCPUCoreSecPrimaryStackSize) - PcdGet32 (PcdSecGlobalVariableSize);
-
- if (VariableSize == 4) {
- WriteUnaligned32 ((UINT32*)(GlobalVariableBase + VariableOffset), *(UINT32*)Variable);
- } else if (VariableSize == 8) {
- WriteUnaligned64 ((UINT64*)(GlobalVariableBase + VariableOffset), *(UINT64*)Variable);
- } else {
- CopyMem ((VOID*)(GlobalVariableBase + VariableOffset), Variable, VariableSize);
- }
-}
-
-VOID*
-ArmPlatformGetGlobalVariableAddress (
- IN UINTN VariableOffset
- )
-{
- UINTN GlobalVariableBase;
-
- // Ensure the Global Variable Size have been initialized
- ASSERT (VariableOffset < PcdGet32 (PcdSecGlobalVariableSize));
-
- GlobalVariableBase = PcdGet32 (PcdCPUCoresSecStackBase) + PcdGet32 (PcdCPUCoreSecPrimaryStackSize) - PcdGet32 (PcdSecGlobalVariableSize);
-
- return (VOID*)(GlobalVariableBase + VariableOffset);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Uefi.h>
+#include <Library/ArmPlatformGlobalVariableLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+
+VOID
+ArmPlatformGetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdSecGlobalVariableSize));
+
+ GlobalVariableBase = PcdGet32 (PcdCPUCoresSecStackBase) + PcdGet32 (PcdCPUCoreSecPrimaryStackSize) - PcdGet32 (PcdSecGlobalVariableSize);
+
+ if (VariableSize == 4) {
+ *(UINT32*)Variable = ReadUnaligned32 ((CONST UINT32*)(GlobalVariableBase + VariableOffset));
+ } else if (VariableSize == 8) {
+ *(UINT64*)Variable = ReadUnaligned64 ((CONST UINT64*)(GlobalVariableBase + VariableOffset));
+ } else {
+ CopyMem (Variable, (VOID*)(GlobalVariableBase + VariableOffset), VariableSize);
+ }
+}
+
+VOID
+ArmPlatformSetGlobalVariable (
+ IN UINTN VariableOffset,
+ IN UINTN VariableSize,
+ OUT VOID* Variable
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdSecGlobalVariableSize));
+
+ GlobalVariableBase = PcdGet32 (PcdCPUCoresSecStackBase) + PcdGet32 (PcdCPUCoreSecPrimaryStackSize) - PcdGet32 (PcdSecGlobalVariableSize);
+
+ if (VariableSize == 4) {
+ WriteUnaligned32 ((UINT32*)(GlobalVariableBase + VariableOffset), *(UINT32*)Variable);
+ } else if (VariableSize == 8) {
+ WriteUnaligned64 ((UINT64*)(GlobalVariableBase + VariableOffset), *(UINT64*)Variable);
+ } else {
+ CopyMem ((VOID*)(GlobalVariableBase + VariableOffset), Variable, VariableSize);
+ }
+}
+
+VOID*
+ArmPlatformGetGlobalVariableAddress (
+ IN UINTN VariableOffset
+ )
+{
+ UINTN GlobalVariableBase;
+
+ // Ensure the Global Variable Size have been initialized
+ ASSERT (VariableOffset < PcdGet32 (PcdSecGlobalVariableSize));
+
+ GlobalVariableBase = PcdGet32 (PcdCPUCoresSecStackBase) + PcdGet32 (PcdCPUCoreSecPrimaryStackSize) - PcdGet32 (PcdSecGlobalVariableSize);
+
+ return (VOID*)(GlobalVariableBase + VariableOffset);
+}
diff --git a/ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.S b/ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.S
new file mode 100644
index 000000000..286327956
--- /dev/null
+++ b/ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.S
@@ -0,0 +1,30 @@
+//
+// Copyright (c) 2012, ARM Limited. All rights reserved.
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//
+
+#include <Library/ArmLib.h>
+
+.text
+.align 3
+
+GCC_ASM_EXPORT(ArmPlatformGetCorePosition)
+
+//UINTN
+//ArmPlatformGetCorePosition (
+// IN UINTN MpId
+// );
+ASM_PFX(ArmPlatformGetCorePosition):
+ and r1, r0, #ARM_CORE_MASK
+ and r0, r0, #ARM_CLUSTER_MASK
+ add r0, r1, r0, LSR #7
+ bx lr
+
diff --git a/ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.asm b/ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.asm
new file mode 100644
index 000000000..25ffbcf9c
--- /dev/null
+++ b/ArmPlatformPkg/Library/ArmPlatformLibNull/Arm/ArmPlatformHelper.asm
@@ -0,0 +1,35 @@
+//
+// Copyright (c) 2012, ARM Limited. All rights reserved.
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//
+
+#include <Library/ArmLib.h>
+
+ INCLUDE AsmMacroIoLib.inc
+
+ EXPORT ArmPlatformGetCorePosition
+
+ PRESERVE8
+ AREA ArmPlatformNullHelper, CODE, READONLY
+
+//UINTN
+//ArmPlatformGetCorePosition (
+// IN UINTN MpId
+// );
+ArmPlatformGetCorePosition FUNCTION
+ and r1, r0, #ARM_CORE_MASK
+ and r0, r0, #ARM_CLUSTER_MASK
+ add r0, r1, r0, LSR #7
+ bx lr
+ ENDFUNC
+
+ END
+
diff --git a/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.c b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.c
index 235eb673f..f3a7efcae 100644
--- a/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.c
+++ b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.c
@@ -1,164 +1,164 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/ArmLib.h>
-#include <Library/ArmPlatformLib.h>
-
-#include <Ppi/ArmMpCoreInfo.h>
-
-
-ARM_CORE_INFO mArmPlatformNullMpCoreInfoTable[] = {
- {
- // Cluster 0, Core 0
- 0x0, 0x0,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 1
- 0x0, 0x1,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 2
- 0x0, 0x2,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (UINT64)0xFFFFFFFF
- },
- {
- // Cluster 0, Core 3
- 0x0, 0x3,
-
- // MP Core MailBox Set/Get/Clear Addresses and Clear Value
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (EFI_PHYSICAL_ADDRESS)0,
- (UINT64)0xFFFFFFFF
- }
-};
-
-// This function should be better located into TimerLib implementation
-RETURN_STATUS
-EFIAPI
-TimerConstructor (
- VOID
- )
-{
- return EFI_SUCCESS;
-}
-
-/**
- Return the current Boot Mode
-
- This function returns the boot reason on the platform
-
-**/
-EFI_BOOT_MODE
-ArmPlatformGetBootMode (
- VOID
- )
-{
- return BOOT_WITH_FULL_CONFIGURATION;
-}
-
-/**
- Initialize controllers that must setup in the normal world
-
- This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
- in the PEI phase.
-
-**/
-RETURN_STATUS
-ArmPlatformInitialize (
- IN UINTN MpId
- )
-{
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- //TODO: Implement me
-
- return RETURN_SUCCESS;
-}
-
-/**
- Initialize the system (or sometimes called permanent) memory
-
- This memory is generally represented by the DRAM.
-
-**/
-VOID
-ArmPlatformInitializeSystemMemory (
- VOID
- )
-{
- //TODO: Implement me
-}
-
-EFI_STATUS
-PrePeiCoreGetMpCoreInfo (
- OUT UINTN *CoreCount,
- OUT ARM_CORE_INFO **ArmCoreTable
- )
-{
- if (ArmIsMpCore()) {
- *CoreCount = sizeof(mArmPlatformNullMpCoreInfoTable) / sizeof(ARM_CORE_INFO);
- *ArmCoreTable = mArmPlatformNullMpCoreInfoTable;
- return EFI_SUCCESS;
- } else {
- return EFI_UNSUPPORTED;
- }
-}
-
-// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
-EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
-ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
-
-EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
- {
- EFI_PEI_PPI_DESCRIPTOR_PPI,
- &mArmMpCoreInfoPpiGuid,
- &mMpCoreInfoPpi
- }
-};
-
-VOID
-ArmPlatformGetPlatformPpiList (
- OUT UINTN *PpiListSize,
- OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
- )
-{
- if (ArmIsMpCore()) {
- *PpiListSize = sizeof(gPlatformPpiTable);
- *PpiList = gPlatformPpiTable;
- } else {
- *PpiListSize = 0;
- *PpiList = NULL;
- }
-}
-
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/ArmLib.h>
+#include <Library/ArmPlatformLib.h>
+
+#include <Ppi/ArmMpCoreInfo.h>
+
+
+ARM_CORE_INFO mArmPlatformNullMpCoreInfoTable[] = {
+ {
+ // Cluster 0, Core 0
+ 0x0, 0x0,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 1
+ 0x0, 0x1,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 2
+ 0x0, 0x2,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (UINT64)0xFFFFFFFF
+ },
+ {
+ // Cluster 0, Core 3
+ 0x0, 0x3,
+
+ // MP Core MailBox Set/Get/Clear Addresses and Clear Value
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (EFI_PHYSICAL_ADDRESS)0,
+ (UINT64)0xFFFFFFFF
+ }
+};
+
+// This function should be better located into TimerLib implementation
+RETURN_STATUS
+EFIAPI
+TimerConstructor (
+ VOID
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Return the current Boot Mode
+
+ This function returns the boot reason on the platform
+
+**/
+EFI_BOOT_MODE
+ArmPlatformGetBootMode (
+ VOID
+ )
+{
+ return BOOT_WITH_FULL_CONFIGURATION;
+}
+
+/**
+ Initialize controllers that must setup in the normal world
+
+ This function is called by the ArmPlatformPkg/PrePi or ArmPlatformPkg/PlatformPei
+ in the PEI phase.
+
+**/
+RETURN_STATUS
+ArmPlatformInitialize (
+ IN UINTN MpId
+ )
+{
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ //TODO: Implement me
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Initialize the system (or sometimes called permanent) memory
+
+ This memory is generally represented by the DRAM.
+
+**/
+VOID
+ArmPlatformInitializeSystemMemory (
+ VOID
+ )
+{
+ //TODO: Implement me
+}
+
+EFI_STATUS
+PrePeiCoreGetMpCoreInfo (
+ OUT UINTN *CoreCount,
+ OUT ARM_CORE_INFO **ArmCoreTable
+ )
+{
+ if (ArmIsMpCore()) {
+ *CoreCount = sizeof(mArmPlatformNullMpCoreInfoTable) / sizeof(ARM_CORE_INFO);
+ *ArmCoreTable = mArmPlatformNullMpCoreInfoTable;
+ return EFI_SUCCESS;
+ } else {
+ return EFI_UNSUPPORTED;
+ }
+}
+
+// Needs to be declared in the file. Otherwise gArmMpCoreInfoPpiGuid is undefined in the contect of PrePeiCore
+EFI_GUID mArmMpCoreInfoPpiGuid = ARM_MP_CORE_INFO_PPI_GUID;
+ARM_MP_CORE_INFO_PPI mMpCoreInfoPpi = { PrePeiCoreGetMpCoreInfo };
+
+EFI_PEI_PPI_DESCRIPTOR gPlatformPpiTable[] = {
+ {
+ EFI_PEI_PPI_DESCRIPTOR_PPI,
+ &mArmMpCoreInfoPpiGuid,
+ &mMpCoreInfoPpi
+ }
+};
+
+VOID
+ArmPlatformGetPlatformPpiList (
+ OUT UINTN *PpiListSize,
+ OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
+ )
+{
+ if (ArmIsMpCore()) {
+ *PpiListSize = sizeof(gPlatformPpiTable);
+ *PpiList = gPlatformPpiTable;
+ } else {
+ *PpiListSize = 0;
+ *PpiList = NULL;
+ }
+}
+
diff --git a/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf
index 13c62a60c..a6c2e8f48 100644
--- a/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf
+++ b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf
@@ -33,6 +33,10 @@
ArmPlatformLibNull.c
ArmPlatformLibNullMem.c
+[Sources.Arm]
+ Arm/ArmPlatformHelper.S | GCC
+ Arm/ArmPlatformHelper.asm | RVCT
+
[FixedPcd]
gArmTokenSpaceGuid.PcdSystemMemoryBase
gArmTokenSpaceGuid.PcdSystemMemorySize
diff --git a/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNullSec.inf b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNullSec.inf
new file mode 100644
index 000000000..128b0b59e
--- /dev/null
+++ b/ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNullSec.inf
@@ -0,0 +1,44 @@
+#/* @file
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#*/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmPlatformLibNull
+ FILE_GUID = cb494bad-23ff-427e-8608-d7e138d3363b
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ ArmLib
+ DebugLib
+
+[Sources.common]
+ ArmPlatformLibNull.c
+
+[Sources.Arm]
+ Arm/ArmPlatformHelper.S | GCC
+ Arm/ArmPlatformHelper.asm | RVCT
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdSystemMemoryBase
+ gArmTokenSpaceGuid.PcdSystemMemorySize
+
+ gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
+ gArmTokenSpaceGuid.PcdArmPrimaryCore
diff --git a/ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c b/ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c
index c548d8b3f..1a8388203 100644
--- a/ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c
+++ b/ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNullSec.c
@@ -1,74 +1,74 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/ArmPlatformLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-
-/**
- Initialize the Secure peripherals and memory regions
-
- If Trustzone is supported by your platform then this function makes the required initialization
- of the secure peripherals and memory regions.
-
-**/
-VOID
-ArmPlatformSecTrustzoneInit (
- IN UINTN MpId
- )
-{
- // Secondary cores might have to set the Secure SGIs into the GICD_IGROUPR0
- if (!IS_PRIMARY_CORE(MpId)) {
- return;
- }
-
- ASSERT(FALSE);
-}
-
-/**
- Initialize controllers that must setup at the early stage
-
- Some peripherals must be initialized in Secure World.
- For example, some L2x0 requires to be initialized in Secure World
-
-**/
-RETURN_STATUS
-ArmPlatformSecInitialize (
- IN UINTN MpId
- )
-{
- // If it is not the primary core then there is nothing to do
- if (!IS_PRIMARY_CORE(MpId)) {
- return RETURN_SUCCESS;
- }
-
- // Do nothing yet
- return RETURN_SUCCESS;
-}
-
-/**
- Call before jumping to Normal World
-
- This function allows the firmware platform to do extra actions before
- jumping to the Normal World
-
-**/
-VOID
-ArmPlatformSecExtraAction (
- IN UINTN MpId,
- OUT UINTN* JumpAddress
- )
-{
- *JumpAddress = PcdGet32(PcdFvBaseAddress);
-}
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/ArmPlatformLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+
+/**
+ Initialize the Secure peripherals and memory regions
+
+ If Trustzone is supported by your platform then this function makes the required initialization
+ of the secure peripherals and memory regions.
+
+**/
+VOID
+ArmPlatformSecTrustzoneInit (
+ IN UINTN MpId
+ )
+{
+ // Secondary cores might have to set the Secure SGIs into the GICD_IGROUPR0
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return;
+ }
+
+ ASSERT(FALSE);
+}
+
+/**
+ Initialize controllers that must setup at the early stage
+
+ Some peripherals must be initialized in Secure World.
+ For example, some L2x0 requires to be initialized in Secure World
+
+**/
+RETURN_STATUS
+ArmPlatformSecInitialize (
+ IN UINTN MpId
+ )
+{
+ // If it is not the primary core then there is nothing to do
+ if (!IS_PRIMARY_CORE(MpId)) {
+ return RETURN_SUCCESS;
+ }
+
+ // Do nothing yet
+ return RETURN_SUCCESS;
+}
+
+/**
+ Call before jumping to Normal World
+
+ This function allows the firmware platform to do extra actions before
+ jumping to the Normal World
+
+**/
+VOID
+ArmPlatformSecExtraAction (
+ IN UINTN MpId,
+ OUT UINTN* JumpAddress
+ )
+{
+ *JumpAddress = PcdGet32(PcdFvBaseAddress);
+}
diff --git a/ArmPlatformPkg/Library/ArmTrustedMonitorLibNull/ArmTrustedMonitorLibNull.c b/ArmPlatformPkg/Library/ArmTrustedMonitorLibNull/ArmTrustedMonitorLibNull.c
index 6d3250e3a..e82584e6d 100644
--- a/ArmPlatformPkg/Library/ArmTrustedMonitorLibNull/ArmTrustedMonitorLibNull.c
+++ b/ArmPlatformPkg/Library/ArmTrustedMonitorLibNull/ArmTrustedMonitorLibNull.c
@@ -1,7 +1,7 @@
/** @file
* Main file supporting the Monitor World on ARM PLatforms
*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+* Copyright (c) 2011-2013, ARM Limited. All rights reserved.
*
* This program and the accompanying materials
* are licensed and made available under the terms and conditions of the BSD License
@@ -33,5 +33,5 @@ ArmSecureMonitorWorldInitialize (
ASSERT (IS_ALIGNED(MonitorVectorTable, BIT5));
// Write the Monitor Mode Vector Table Address
- ArmWriteMVBar ((UINT32) &MonitorVectorTable);
+ ArmWriteMVBar ((UINTN) &MonitorVectorTable);
}
diff --git a/ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf b/ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf
index 2962ffe5d..26afb34b2 100755
--- a/ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf
+++ b/ArmPlatformPkg/Library/DebugSecExtraActionLib/DebugSecExtraActionLib.inf
@@ -1,55 +1,55 @@
-#/* @file
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#*/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = DebugSecExtraActionLib
- FILE_GUID = 8fff7a60-a6f8-11e0-990a-0002a5d5c51b
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformSecExtraActionLib
-
-#
-# The following information is for reference only and not required by the build tools.
-#
-# VALID_ARCHITECTURES = ARM
-#
-
-[Sources.common]
- DebugSecExtraActionLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- DebugLib
- PcdLib
- ArmGicLib
- PrintLib
- SerialPortLib
-
-[FeaturePcd]
- gArmPlatformTokenSpaceGuid.PcdStandalone
- gArmPlatformTokenSpaceGuid.PcdSystemMemoryInitializeInSec
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdFvBaseAddress
-
- gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
- gArmTokenSpaceGuid.PcdArmPrimaryCore
-
- gArmTokenSpaceGuid.PcdGicDistributorBase
- gArmTokenSpaceGuid.PcdGicInterruptInterfaceBase
- gArmTokenSpaceGuid.PcdGicSgiIntId
+#/* @file
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#*/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DebugSecExtraActionLib
+ FILE_GUID = 8fff7a60-a6f8-11e0-990a-0002a5d5c51b
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformSecExtraActionLib
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = ARM
+#
+
+[Sources.common]
+ DebugSecExtraActionLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ PcdLib
+ ArmGicLib
+ PrintLib
+ SerialPortLib
+
+[FeaturePcd]
+ gArmPlatformTokenSpaceGuid.PcdStandalone
+ gArmPlatformTokenSpaceGuid.PcdSystemMemoryInitializeInSec
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdFvBaseAddress
+
+ gArmTokenSpaceGuid.PcdArmPrimaryCoreMask
+ gArmTokenSpaceGuid.PcdArmPrimaryCore
+
+ gArmTokenSpaceGuid.PcdGicDistributorBase
+ gArmTokenSpaceGuid.PcdGicInterruptInterfaceBase
+ gArmTokenSpaceGuid.PcdGicSgiIntId
diff --git a/ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.c b/ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.c
index 8f7ea65e7..b45e85d9a 100644
--- a/ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.c
+++ b/ArmPlatformPkg/Library/EblCmdLib/EblCmdLib.c
@@ -1,6 +1,6 @@
/** @file
*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+* Copyright (c) 2011-2013, ARM Limited. All rights reserved.
*
* This program and the accompanying materials
* are licensed and made available under the terms and conditions of the BSD License
@@ -101,7 +101,7 @@ EblSymbolTable (
for (Entry = 0; Entry < DebugImageTableHeader->TableSize; Entry++, DebugTable++) {
if (DebugTable->NormalImage != NULL) {
if ((DebugTable->NormalImage->ImageInfoType == EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL) && (DebugTable->NormalImage->LoadedImageProtocolInstance != NULL)) {
- ImageBase = (UINT32)DebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase;
+ ImageBase = (UINTN)DebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase;
PeCoffSizeOfHeaders = PeCoffGetSizeOfHeaders ((VOID *)(UINTN)ImageBase);
Pdb = PeCoffLoaderGetPdbPointer (DebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase);
if (Pdb != NULL) {
@@ -389,7 +389,7 @@ EblDevicePaths (
for (Index = 0; Index < HandleCount; Index++) {
Status = gBS->HandleProtocol (HandleBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathProtocol);
String = DevicePathToTextProtocol->ConvertDevicePathToText(DevicePathProtocol,TRUE,TRUE);
- Print (L"[0x%X] %s\n",(UINT32)HandleBuffer[Index], String);
+ Print (L"[0x%X] %s\n",(UINTN)HandleBuffer[Index], String);
}
return EFI_SUCCESS;
diff --git a/ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.c b/ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.c
index 7ccd09bd4..20e888271 100644
--- a/ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.c
+++ b/ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.c
@@ -1,184 +1,184 @@
-/** @file
- Serial I/O Port library functions with no library constructor/destructor
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
- Copyright (c) 2012, ARM Ltd. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Base.h>
-
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/SerialPortLib.h>
-#include <Library/SerialPortExtLib.h>
-
-#include <Drivers/PL011Uart.h>
-
-
-/**
-
- Programmed hardware of Serial port.
-
- @return Always return RETURN_UNSUPPORTED.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortInitialize (
- VOID
- )
-{
- return PL011UartInitializePort (
- (UINTN)PcdGet64 (PcdSerialRegisterBase),
- (UINTN)PcdGet64 (PcdUartDefaultBaudRate),
- 0, // Use the default value for Fifo depth
- (EFI_PARITY_TYPE)PcdGet8 (PcdUartDefaultParity),
- PcdGet8 (PcdUartDefaultDataBits),
- (EFI_STOP_BITS_TYPE) PcdGet8 (PcdUartDefaultStopBits));
-}
-
-/**
- Write data to serial device.
-
- @param Buffer Point of data buffer which need to be written.
- @param NumberOfBytes Number of output bytes which are cached in Buffer.
-
- @retval 0 Write data failed.
- @retval !0 Actual number of bytes written to serial device.
-
-**/
-UINTN
-EFIAPI
-SerialPortWrite (
- IN UINT8 *Buffer,
- IN UINTN NumberOfBytes
- )
-{
- return PL011UartWrite ((UINTN)PcdGet64 (PcdSerialRegisterBase), Buffer, NumberOfBytes);
-}
-
-/**
- Read data from serial device and save the data in buffer.
-
- @param Buffer Point of data buffer which need to be written.
- @param NumberOfBytes Number of output bytes which are cached in Buffer.
-
- @retval 0 Read data failed.
- @retval !0 Actual number of bytes read from serial device.
-
-**/
-UINTN
-EFIAPI
-SerialPortRead (
- OUT UINT8 *Buffer,
- IN UINTN NumberOfBytes
-)
-{
- return PL011UartRead ((UINTN)PcdGet64 (PcdSerialRegisterBase), Buffer, NumberOfBytes);
-}
-
-/**
- Check to see if any data is available to be read from the debug device.
-
- @retval EFI_SUCCESS At least one byte of data is available to be read
- @retval EFI_NOT_READY No data is available to be read
- @retval EFI_DEVICE_ERROR The serial device is not functioning properly
-
-**/
-BOOLEAN
-EFIAPI
-SerialPortPoll (
- VOID
- )
-{
- return PL011UartPoll ((UINTN)PcdGet64 (PcdSerialRegisterBase));
-}
-
-/**
- Set new attributes to PL011.
-
- @param BaudRate The baud rate of the serial device. If the baud rate is not supported,
- the speed will be reduced down to the nearest supported one and the
- variable's value will be updated accordingly.
- @param ReceiveFifoDepth The number of characters the device will buffer on input. If the specified
- value is not supported, the variable's value will be reduced down to the
- nearest supported one.
- @param Timeout If applicable, the number of microseconds the device will wait
- before timing out a Read or a Write operation.
- @param Parity If applicable, this is the EFI_PARITY_TYPE that is computer or checked
- as each character is transmitted or received. If the device does not
- support parity, the value is the default parity value.
- @param DataBits The number of data bits in each character
- @param StopBits If applicable, the EFI_STOP_BITS_TYPE number of stop bits per character.
- If the device does not support stop bits, the value is the default stop
- bit value.
-
- @retval EFI_SUCCESS All attributes were set correctly on the serial device.
- @retval EFI_INVALID_PARAMETERS One or more of the attributes has an unsupported value.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortSetAttributes (
- IN UINT64 BaudRate,
- IN UINT32 ReceiveFifoDepth,
- IN UINT32 Timeout,
- IN EFI_PARITY_TYPE Parity,
- IN UINT8 DataBits,
- IN EFI_STOP_BITS_TYPE StopBits
- )
-{
- return PL011UartInitializePort (
- (UINTN)PcdGet64 (PcdSerialRegisterBase),
- BaudRate,
- ReceiveFifoDepth,
- Parity,
- DataBits,
- StopBits);
-}
-
-/**
- Set the serial device control bits.
-
- @param Control Control bits which are to be set on the serial device.
-
- @retval EFI_SUCCESS The new control bits were set on the serial device.
- @retval EFI_UNSUPPORTED The serial device does not support this operation.
- @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortSetControl (
- IN UINT32 Control
- )
-{
- return PL011UartSetControl((UINTN)PcdGet64 (PcdSerialRegisterBase), Control);
-}
-
-/**
- Get the serial device control bits.
-
- @param Control Control signals read from the serial device.
-
- @retval EFI_SUCCESS The control bits were read from the serial device.
- @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortGetControl (
- OUT UINT32 *Control
- )
-{
- return PL011UartGetControl((UINTN)PcdGet64 (PcdSerialRegisterBase), Control);
-}
+/** @file
+ Serial I/O Port library functions with no library constructor/destructor
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+ Copyright (c) 2012, ARM Ltd. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Base.h>
+
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/SerialPortLib.h>
+#include <Library/SerialPortExtLib.h>
+
+#include <Drivers/PL011Uart.h>
+
+
+/**
+
+ Programmed hardware of Serial port.
+
+ @return Always return RETURN_UNSUPPORTED.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortInitialize (
+ VOID
+ )
+{
+ return PL011UartInitializePort (
+ (UINTN)PcdGet64 (PcdSerialRegisterBase),
+ (UINTN)PcdGet64 (PcdUartDefaultBaudRate),
+ 0, // Use the default value for Fifo depth
+ (EFI_PARITY_TYPE)PcdGet8 (PcdUartDefaultParity),
+ PcdGet8 (PcdUartDefaultDataBits),
+ (EFI_STOP_BITS_TYPE) PcdGet8 (PcdUartDefaultStopBits));
+}
+
+/**
+ Write data to serial device.
+
+ @param Buffer Point of data buffer which need to be written.
+ @param NumberOfBytes Number of output bytes which are cached in Buffer.
+
+ @retval 0 Write data failed.
+ @retval !0 Actual number of bytes written to serial device.
+
+**/
+UINTN
+EFIAPI
+SerialPortWrite (
+ IN UINT8 *Buffer,
+ IN UINTN NumberOfBytes
+ )
+{
+ return PL011UartWrite ((UINTN)PcdGet64 (PcdSerialRegisterBase), Buffer, NumberOfBytes);
+}
+
+/**
+ Read data from serial device and save the data in buffer.
+
+ @param Buffer Point of data buffer which need to be written.
+ @param NumberOfBytes Number of output bytes which are cached in Buffer.
+
+ @retval 0 Read data failed.
+ @retval !0 Actual number of bytes read from serial device.
+
+**/
+UINTN
+EFIAPI
+SerialPortRead (
+ OUT UINT8 *Buffer,
+ IN UINTN NumberOfBytes
+)
+{
+ return PL011UartRead ((UINTN)PcdGet64 (PcdSerialRegisterBase), Buffer, NumberOfBytes);
+}
+
+/**
+ Check to see if any data is available to be read from the debug device.
+
+ @retval EFI_SUCCESS At least one byte of data is available to be read
+ @retval EFI_NOT_READY No data is available to be read
+ @retval EFI_DEVICE_ERROR The serial device is not functioning properly
+
+**/
+BOOLEAN
+EFIAPI
+SerialPortPoll (
+ VOID
+ )
+{
+ return PL011UartPoll ((UINTN)PcdGet64 (PcdSerialRegisterBase));
+}
+
+/**
+ Set new attributes to PL011.
+
+ @param BaudRate The baud rate of the serial device. If the baud rate is not supported,
+ the speed will be reduced down to the nearest supported one and the
+ variable's value will be updated accordingly.
+ @param ReceiveFifoDepth The number of characters the device will buffer on input. If the specified
+ value is not supported, the variable's value will be reduced down to the
+ nearest supported one.
+ @param Timeout If applicable, the number of microseconds the device will wait
+ before timing out a Read or a Write operation.
+ @param Parity If applicable, this is the EFI_PARITY_TYPE that is computer or checked
+ as each character is transmitted or received. If the device does not
+ support parity, the value is the default parity value.
+ @param DataBits The number of data bits in each character
+ @param StopBits If applicable, the EFI_STOP_BITS_TYPE number of stop bits per character.
+ If the device does not support stop bits, the value is the default stop
+ bit value.
+
+ @retval EFI_SUCCESS All attributes were set correctly on the serial device.
+ @retval EFI_INVALID_PARAMETERS One or more of the attributes has an unsupported value.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortSetAttributes (
+ IN UINT64 BaudRate,
+ IN UINT32 ReceiveFifoDepth,
+ IN UINT32 Timeout,
+ IN EFI_PARITY_TYPE Parity,
+ IN UINT8 DataBits,
+ IN EFI_STOP_BITS_TYPE StopBits
+ )
+{
+ return PL011UartInitializePort (
+ (UINTN)PcdGet64 (PcdSerialRegisterBase),
+ BaudRate,
+ ReceiveFifoDepth,
+ Parity,
+ DataBits,
+ StopBits);
+}
+
+/**
+ Set the serial device control bits.
+
+ @param Control Control bits which are to be set on the serial device.
+
+ @retval EFI_SUCCESS The new control bits were set on the serial device.
+ @retval EFI_UNSUPPORTED The serial device does not support this operation.
+ @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortSetControl (
+ IN UINT32 Control
+ )
+{
+ return PL011UartSetControl((UINTN)PcdGet64 (PcdSerialRegisterBase), Control);
+}
+
+/**
+ Get the serial device control bits.
+
+ @param Control Control signals read from the serial device.
+
+ @retval EFI_SUCCESS The control bits were read from the serial device.
+ @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortGetControl (
+ OUT UINT32 *Control
+ )
+{
+ return PL011UartGetControl((UINTN)PcdGet64 (PcdSerialRegisterBase), Control);
+}
diff --git a/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c b/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c
index ec3091b9e..b7dba087f 100644
--- a/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c
+++ b/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c
@@ -4,6 +4,7 @@
Currently this driver does not support runtime virtual calling.
Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+ Copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -33,9 +34,9 @@
#include <ArmPlatform.h>
-CHAR16 mTimeZoneVariableName[] = L"PL031_TimeZone";
-CHAR16 mDaylightVariableName[] = L"PL031_Daylight";
-BOOLEAN mPL031Initialized = FALSE;
+STATIC CONST CHAR16 mTimeZoneVariableName[] = L"PL031RtcTimeZone";
+STATIC CONST CHAR16 mDaylightVariableName[] = L"PL031RtcDaylight";
+STATIC BOOLEAN mPL031Initialized = FALSE;
EFI_STATUS
IdentifyPL031 (
@@ -128,10 +129,6 @@ EpochToEfiTime (
UINTN ss;
UINTN J;
- if (Time->Daylight == TRUE) {
-
- }
-
J = (EpochSeconds / 86400) + 2440588;
j = J + 32044;
g = j / 146097;
@@ -233,13 +230,14 @@ DayValid (
Returns the current time and date information, and the time-keeping capabilities
of the hardware platform.
- @param Time A pointer to storage to receive a snapshot of the current time.
- @param Capabilities An optional pointer to a buffer to receive the real time clock
- device's capabilities.
+ @param Time A pointer to storage to receive a snapshot of the current time.
+ @param Capabilities An optional pointer to a buffer to receive the real time clock
+ device's capabilities.
- @retval EFI_SUCCESS The operation completed successfully.
- @retval EFI_INVALID_PARAMETER Time is NULL.
- @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error.
+ @retval EFI_SUCCESS The operation completed successfully.
+ @retval EFI_INVALID_PARAMETER Time is NULL.
+ @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error.
+ @retval EFI_SECURITY_VIOLATION The time could not be retrieved due to an authentication failure.
**/
EFI_STATUS
@@ -250,9 +248,10 @@ LibGetTime (
)
{
EFI_STATUS Status = EFI_SUCCESS;
- UINTN EpochSeconds;
- INT16 *TimeZone = 0;
- UINTN *Daylight = 0;
+ UINT32 EpochSeconds;
+ INT16 TimeZone;
+ UINT8 Daylight;
+ UINTN Size;
// Initialize the hardware if not already done
if (!mPL031Initialized) {
@@ -286,27 +285,44 @@ LibGetTime (
}
// Get the current time zone information from non-volatile storage
- TimeZone = (INT16 *)GetVariable(mTimeZoneVariableName, &gEfiGlobalVariableGuid);
+ Size = sizeof (TimeZone);
+ Status = gRT->GetVariable (
+ (CHAR16 *)mTimeZoneVariableName,
+ &gEfiCallerIdGuid,
+ NULL,
+ &Size,
+ (VOID *)&TimeZone
+ );
+
+ if (EFI_ERROR (Status)) {
+ ASSERT(Status != EFI_INVALID_PARAMETER);
+ ASSERT(Status != EFI_BUFFER_TOO_SMALL);
+
+ if (Status != EFI_NOT_FOUND)
+ goto EXIT;
- if (TimeZone == NULL) {
// The time zone variable does not exist in non-volatile storage, so create it.
Time->TimeZone = EFI_UNSPECIFIED_TIMEZONE;
// Store it
Status = gRT->SetVariable (
- mTimeZoneVariableName,
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- sizeof(Time->TimeZone),
- &(Time->TimeZone)
- );
+ (CHAR16 *)mTimeZoneVariableName,
+ &gEfiCallerIdGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ Size,
+ (VOID *)&(Time->TimeZone)
+ );
if (EFI_ERROR (Status)) {
- DEBUG((EFI_D_ERROR,"LibGetTime: ERROR: TimeZone\n"));
+ DEBUG ((
+ EFI_D_ERROR,
+ "LibGetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
+ mTimeZoneVariableName,
+ Status
+ ));
goto EXIT;
}
} else {
// Got the time zone
- Time->TimeZone = *TimeZone;
- FreePool(TimeZone);
+ Time->TimeZone = TimeZone;
// Check TimeZone bounds: -1440 to 1440 or 2047
if (((Time->TimeZone < -1440) || (Time->TimeZone > 1440))
@@ -321,27 +337,44 @@ LibGetTime (
}
// Get the current daylight information from non-volatile storage
- Daylight = (UINTN *)GetVariable(mDaylightVariableName, &gEfiGlobalVariableGuid);
+ Size = sizeof (Daylight);
+ Status = gRT->GetVariable (
+ (CHAR16 *)mDaylightVariableName,
+ &gEfiCallerIdGuid,
+ NULL,
+ &Size,
+ (VOID *)&Daylight
+ );
+
+ if (EFI_ERROR (Status)) {
+ ASSERT(Status != EFI_INVALID_PARAMETER);
+ ASSERT(Status != EFI_BUFFER_TOO_SMALL);
+
+ if (Status != EFI_NOT_FOUND)
+ goto EXIT;
- if (Daylight == NULL) {
// The daylight variable does not exist in non-volatile storage, so create it.
Time->Daylight = 0;
// Store it
Status = gRT->SetVariable (
- mDaylightVariableName,
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- sizeof(Time->Daylight),
- &(Time->Daylight)
- );
+ (CHAR16 *)mDaylightVariableName,
+ &gEfiCallerIdGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ Size,
+ (VOID *)&(Time->Daylight)
+ );
if (EFI_ERROR (Status)) {
- DEBUG((EFI_D_ERROR,"LibGetTime: ERROR: Daylight\n"));
+ DEBUG ((
+ EFI_D_ERROR,
+ "LibGetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
+ mDaylightVariableName,
+ Status
+ ));
goto EXIT;
}
} else {
// Got the daylight information
- Time->Daylight = *Daylight;
- FreePool(Daylight);
+ Time->Daylight = Daylight;
// Adjust for the correct period
if ((Time->Daylight & EFI_TIME_IN_DAYLIGHT) == EFI_TIME_IN_DAYLIGHT) {
@@ -456,27 +489,37 @@ LibSetTime (
// Save the current time zone information into non-volatile storage
Status = gRT->SetVariable (
- mTimeZoneVariableName,
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- sizeof(Time->TimeZone),
- &(Time->TimeZone)
- );
+ (CHAR16 *)mTimeZoneVariableName,
+ &gEfiCallerIdGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ sizeof (Time->TimeZone),
+ (VOID *)&(Time->TimeZone)
+ );
if (EFI_ERROR (Status)) {
- DEBUG((EFI_D_ERROR,"LibSetTime: ERROR: TimeZone\n"));
+ DEBUG ((
+ EFI_D_ERROR,
+ "LibSetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
+ mTimeZoneVariableName,
+ Status
+ ));
goto EXIT;
}
// Save the current daylight information into non-volatile storage
Status = gRT->SetVariable (
- mDaylightVariableName,
- &gEfiGlobalVariableGuid,
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
- sizeof(Time->Daylight),
- &(Time->Daylight)
- );
+ (CHAR16 *)mDaylightVariableName,
+ &gEfiCallerIdGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+ sizeof(Time->Daylight),
+ (VOID *)&(Time->Daylight)
+ );
if (EFI_ERROR (Status)) {
- DEBUG((EFI_D_ERROR,"LibSetTime: ERROR: Daylight\n"));
+ DEBUG ((
+ EFI_D_ERROR,
+ "LibSetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
+ mDaylightVariableName,
+ Status
+ ));
goto EXIT;
}
diff --git a/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.inf b/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.inf
index 24c74d2d1..add982ce8 100644
--- a/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.inf
+++ b/ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.inf
@@ -1,8 +1,7 @@
#/** @file
-# Memory Status Code Library for UEFI drivers
#
-# Lib to provide memory journal status code reporting Routines
# Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -25,7 +24,6 @@
[Sources.common]
PL031RealTimeClockLib.c
-
[Packages]
MdePkg/MdePkg.dec
EmbeddedPkg/EmbeddedPkg.dec
@@ -37,7 +35,7 @@
DebugLib
PcdLib
ArmPlatformSysConfigLib
-
+
[Pcd]
gArmPlatformTokenSpaceGuid.PcdPL031RtcBase
gArmPlatformTokenSpaceGuid.PcdPL031RtcPpmAccuracy
diff --git a/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.c b/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.c
index fcaa23edd..a042dac9a 100644
--- a/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.c
+++ b/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.c
@@ -1,260 +1,260 @@
-/** @file
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
- Copyright (c) 2011, ARM Limited. All rights reserved.
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Base.h>
-
-#include <Library/BaseLib.h>
-#include <Library/TimerLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-#include <Drivers/SP804Timer.h>
-
-#define SP804_TIMER_METRONOME_BASE ((UINTN)PcdGet32 (PcdSP804TimerMetronomeBase))
-#define SP804_TIMER_PERFORMANCE_BASE ((UINTN)PcdGet32 (PcdSP804TimerPerformanceBase))
-
-// Setup SP810's Timer2 for managing delay functions. And Timer3 for Performance counter
-// Note: ArmVE's Timer0 and Timer1 are used by TimerDxe.
-RETURN_STATUS
-EFIAPI
-TimerConstructor (
- VOID
- )
-{
- // Check if the Metronome Timer is already initialized
- if (MmioRead32(SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
- return RETURN_SUCCESS;
- } else {
- // Configure the Metronome Timer for free running operation, 32 bits, no prescaler, and interrupt disabled
- MmioWrite32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_32BIT | SP804_PRESCALE_DIV_1);
-
- // Start the Metronome Timer ticking
- MmioOr32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_ENABLE);
- }
-
- // Check if the Performance Timer is already initialized
- if (MmioRead32(SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
- return RETURN_SUCCESS;
- } else {
- // Configure the Performance timer for free running operation, 32 bits, no prescaler, interrupt disabled
- MmioWrite32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_32BIT | SP804_PRESCALE_DIV_1);
-
- // Start the Performance Timer ticking
- MmioOr32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_ENABLE);
- }
-
- return RETURN_SUCCESS;
-}
-
-/**
- Stalls the CPU for at least the given number of microseconds.
-
- Stalls the CPU for the number of microseconds specified by MicroSeconds.
- The hardware timer is 32 bits.
- The maximum possible delay is (0xFFFFFFFF / TimerFrequencyMHz), i.e. ([32bits] / FreqInMHz)
- For example:
- +----------------+------------+----------+----------+
- | TimerFrequency | MaxDelay | MaxDelay | MaxDelay |
- | (MHz) | (us) | (s) | (min) |
- +----------------+------------+----------+----------+
- | 1 | 0xFFFFFFFF | 4294 | 71.5 |
- | 5 | 0x33333333 | 859 | 14.3 |
- | 10 | 0x19999999 | 429 | 7.2 |
- | 50 | 0x051EB851 | 86 | 1.4 |
- +----------------+------------+----------+----------+
- If it becomes necessary to support higher delays, then consider using the
- real time clock.
-
- During this delay, the cpu is not yielded to any other process, with one exception:
- events that are triggered off a timer and which execute at a higher TPL than
- this function. These events may call MicroSecondDelay (or NanoSecondDelay) to
- fulfil their own needs.
- Therefore, this function must be re-entrant, as it may be interrupted and re-started.
-
- @param MicroSeconds The minimum number of microseconds to delay.
-
- @return The value of MicroSeconds inputted.
-
-**/
-UINTN
-EFIAPI
-MicroSecondDelay (
- IN UINTN MicroSeconds
- )
-{
- UINT64 DelayTicks64; // Convert from microseconds to timer ticks, more bits to detect over-range conditions.
- UINTN DelayTicks; // Convert from microseconds to timer ticks, native size for general calculations.
- UINTN StartTicks; // Timer value snapshot at the start of the delay
- UINTN TargetTicks; // Timer value to signal the end of the delay
- UINTN CurrentTicks; // Current value of the 64-bit timer value at any given moment
-
- // If we snapshot the timer at the start of the delay function then we minimise unaccounted overheads.
- StartTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
-
- // We are operating at the limit of 32bits. For the range checking work in 64 bits to avoid overflows.
- DelayTicks64 = MultU64x32((UINT64)MicroSeconds, PcdGet32(PcdSP804TimerFrequencyInMHz));
-
- // We are limited to 32 bits.
- // If the specified delay is exactly equal to the max range of the timer,
- // then the start will be equal to the stop plus one timer overflow (wrap-around).
- // To avoid having to check for that, reduce the maximum acceptable range by 1 tick,
- // i.e. reject delays equal or greater than the max range of the timer.
- if (DelayTicks64 >= (UINT64)SP804_MAX_TICKS) {
- DEBUG((EFI_D_ERROR,"MicroSecondDelay: ERROR: MicroSeconds=%d exceed SP804 count range. Max MicroSeconds=%d\n",
- MicroSeconds,
- ((UINTN)SP804_MAX_TICKS/PcdGet32(PcdSP804TimerFrequencyInMHz))));
- }
- ASSERT(DelayTicks64 < (UINT64)SP804_MAX_TICKS);
-
- // From now on do calculations only in native bit size.
- DelayTicks = (UINTN)DelayTicks64;
-
- // Calculate the target value of the timer.
-
- //Note: SP804 timer is counting down
- if (StartTicks >= DelayTicks) {
- // In this case we do not expect a wrap-around of the timer to occur.
- // CurrentTicks must be less than StartTicks and higher than TargetTicks.
- // If this is not the case, then the delay has been reached and may even have been exceeded if this
- // function was suspended by a higher priority interrupt.
-
- TargetTicks = StartTicks - DelayTicks;
-
- do {
- CurrentTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
- } while ((CurrentTicks > TargetTicks) && (CurrentTicks <= StartTicks));
-
- } else {
- // In this case TargetTicks is larger than StartTicks.
- // This means we expect a wrap-around of the timer to occur and we must wait for it.
- // Before the wrap-around, CurrentTicks must be less than StartTicks and less than TargetTicks.
- // After the wrap-around, CurrentTicks must be larger than StartTicks and larger than TargetTicks.
- // If this is not the case, then the delay has been reached and may even have been exceeded if this
- // function was suspended by a higher priority interrupt.
-
- // The order of operations is essential to avoid arithmetic overflow problems
- TargetTicks = ((UINTN)SP804_MAX_TICKS - DelayTicks) + StartTicks;
-
- // First wait for the wrap-around to occur
- do {
- CurrentTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
- } while (CurrentTicks <= StartTicks);
-
- // Then wait for the target
- do {
- CurrentTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
- } while (CurrentTicks > TargetTicks);
- }
-
- return MicroSeconds;
-}
-
-/**
- Stalls the CPU for at least the given number of nanoseconds.
-
- Stalls the CPU for the number of nanoseconds specified by NanoSeconds.
-
- When the timer frequency is 1MHz, each tick corresponds to 1 microsecond.
- Therefore, the nanosecond delay will be rounded up to the nearest 1 microsecond.
-
- @param NanoSeconds The minimum number of nanoseconds to delay.
-
- @return The value of NanoSeconds inputted.
-
-**/
-UINTN
-EFIAPI
-NanoSecondDelay (
- IN UINTN NanoSeconds
- )
-{
- UINTN MicroSeconds;
-
- // Round up to 1us Tick Number
- MicroSeconds = NanoSeconds / 1000;
- MicroSeconds += ((NanoSeconds % 1000) == 0) ? 0 : 1;
-
- MicroSecondDelay (MicroSeconds);
-
- return NanoSeconds;
-}
-
-/**
- Retrieves the current value of a 64-bit free running performance counter.
-
- The counter can either count up by 1 or count down by 1. If the physical
- performance counter counts by a larger increment, then the counter values
- must be translated. The properties of the counter can be retrieved from
- GetPerformanceCounterProperties().
-
- @return The current value of the free running performance counter.
-
-**/
-UINT64
-EFIAPI
-GetPerformanceCounter (
- VOID
- )
-{
- // Free running 64-bit/32-bit counter is needed here.
- // Don't think we need this to boot, just to do performance profile
- UINT64 Value;
- Value = MmioRead32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CURRENT_REG);
- return Value;
-}
-
-
-/**
- Retrieves the 64-bit frequency in Hz and the range of performance counter
- values.
-
- If StartValue is not NULL, then the value that the performance counter starts
- with immediately after is it rolls over is returned in StartValue. If
- EndValue is not NULL, then the value that the performance counter end with
- immediately before it rolls over is returned in EndValue. The 64-bit
- frequency of the performance counter in Hz is always returned. If StartValue
- is less than EndValue, then the performance counter counts up. If StartValue
- is greater than EndValue, then the performance counter counts down. For
- example, a 64-bit free running counter that counts up would have a StartValue
- of 0 and an EndValue of 0xFFFFFFFFFFFFFFFF. A 24-bit free running counter
- that counts down would have a StartValue of 0xFFFFFF and an EndValue of 0.
-
- @param StartValue The value the performance counter starts with when it
- rolls over.
- @param EndValue The value that the performance counter ends with before
- it rolls over.
-
- @return The frequency in Hz.
-
-**/
-UINT64
-EFIAPI
-GetPerformanceCounterProperties (
- OUT UINT64 *StartValue, OPTIONAL
- OUT UINT64 *EndValue OPTIONAL
- )
-{
- if (StartValue != NULL) {
- // Timer starts with the reload value
- *StartValue = 0xFFFFFFFF;
- }
-
- if (EndValue != NULL) {
- // Timer counts down to 0x0
- *EndValue = (UINT64)0ULL;
- }
-
- return PcdGet64 (PcdEmbeddedPerformanceCounterFrequencyInHz);
-}
+/** @file
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+ Copyright (c) 2011, ARM Limited. All rights reserved.
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Base.h>
+
+#include <Library/BaseLib.h>
+#include <Library/TimerLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+#include <Drivers/SP804Timer.h>
+
+#define SP804_TIMER_METRONOME_BASE ((UINTN)PcdGet32 (PcdSP804TimerMetronomeBase))
+#define SP804_TIMER_PERFORMANCE_BASE ((UINTN)PcdGet32 (PcdSP804TimerPerformanceBase))
+
+// Setup SP810's Timer2 for managing delay functions. And Timer3 for Performance counter
+// Note: ArmVE's Timer0 and Timer1 are used by TimerDxe.
+RETURN_STATUS
+EFIAPI
+TimerConstructor (
+ VOID
+ )
+{
+ // Check if the Metronome Timer is already initialized
+ if (MmioRead32(SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
+ return RETURN_SUCCESS;
+ } else {
+ // Configure the Metronome Timer for free running operation, 32 bits, no prescaler, and interrupt disabled
+ MmioWrite32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_32BIT | SP804_PRESCALE_DIV_1);
+
+ // Start the Metronome Timer ticking
+ MmioOr32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_ENABLE);
+ }
+
+ // Check if the Performance Timer is already initialized
+ if (MmioRead32(SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG) & SP804_TIMER_CTRL_ENABLE) {
+ return RETURN_SUCCESS;
+ } else {
+ // Configure the Performance timer for free running operation, 32 bits, no prescaler, interrupt disabled
+ MmioWrite32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_32BIT | SP804_PRESCALE_DIV_1);
+
+ // Start the Performance Timer ticking
+ MmioOr32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CONTROL_REG, SP804_TIMER_CTRL_ENABLE);
+ }
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Stalls the CPU for at least the given number of microseconds.
+
+ Stalls the CPU for the number of microseconds specified by MicroSeconds.
+ The hardware timer is 32 bits.
+ The maximum possible delay is (0xFFFFFFFF / TimerFrequencyMHz), i.e. ([32bits] / FreqInMHz)
+ For example:
+ +----------------+------------+----------+----------+
+ | TimerFrequency | MaxDelay | MaxDelay | MaxDelay |
+ | (MHz) | (us) | (s) | (min) |
+ +----------------+------------+----------+----------+
+ | 1 | 0xFFFFFFFF | 4294 | 71.5 |
+ | 5 | 0x33333333 | 859 | 14.3 |
+ | 10 | 0x19999999 | 429 | 7.2 |
+ | 50 | 0x051EB851 | 86 | 1.4 |
+ +----------------+------------+----------+----------+
+ If it becomes necessary to support higher delays, then consider using the
+ real time clock.
+
+ During this delay, the cpu is not yielded to any other process, with one exception:
+ events that are triggered off a timer and which execute at a higher TPL than
+ this function. These events may call MicroSecondDelay (or NanoSecondDelay) to
+ fulfil their own needs.
+ Therefore, this function must be re-entrant, as it may be interrupted and re-started.
+
+ @param MicroSeconds The minimum number of microseconds to delay.
+
+ @return The value of MicroSeconds inputted.
+
+**/
+UINTN
+EFIAPI
+MicroSecondDelay (
+ IN UINTN MicroSeconds
+ )
+{
+ UINT64 DelayTicks64; // Convert from microseconds to timer ticks, more bits to detect over-range conditions.
+ UINTN DelayTicks; // Convert from microseconds to timer ticks, native size for general calculations.
+ UINTN StartTicks; // Timer value snapshot at the start of the delay
+ UINTN TargetTicks; // Timer value to signal the end of the delay
+ UINTN CurrentTicks; // Current value of the 64-bit timer value at any given moment
+
+ // If we snapshot the timer at the start of the delay function then we minimise unaccounted overheads.
+ StartTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
+
+ // We are operating at the limit of 32bits. For the range checking work in 64 bits to avoid overflows.
+ DelayTicks64 = MultU64x32((UINT64)MicroSeconds, PcdGet32(PcdSP804TimerFrequencyInMHz));
+
+ // We are limited to 32 bits.
+ // If the specified delay is exactly equal to the max range of the timer,
+ // then the start will be equal to the stop plus one timer overflow (wrap-around).
+ // To avoid having to check for that, reduce the maximum acceptable range by 1 tick,
+ // i.e. reject delays equal or greater than the max range of the timer.
+ if (DelayTicks64 >= (UINT64)SP804_MAX_TICKS) {
+ DEBUG((EFI_D_ERROR,"MicroSecondDelay: ERROR: MicroSeconds=%d exceed SP804 count range. Max MicroSeconds=%d\n",
+ MicroSeconds,
+ ((UINTN)SP804_MAX_TICKS/PcdGet32(PcdSP804TimerFrequencyInMHz))));
+ }
+ ASSERT(DelayTicks64 < (UINT64)SP804_MAX_TICKS);
+
+ // From now on do calculations only in native bit size.
+ DelayTicks = (UINTN)DelayTicks64;
+
+ // Calculate the target value of the timer.
+
+ //Note: SP804 timer is counting down
+ if (StartTicks >= DelayTicks) {
+ // In this case we do not expect a wrap-around of the timer to occur.
+ // CurrentTicks must be less than StartTicks and higher than TargetTicks.
+ // If this is not the case, then the delay has been reached and may even have been exceeded if this
+ // function was suspended by a higher priority interrupt.
+
+ TargetTicks = StartTicks - DelayTicks;
+
+ do {
+ CurrentTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
+ } while ((CurrentTicks > TargetTicks) && (CurrentTicks <= StartTicks));
+
+ } else {
+ // In this case TargetTicks is larger than StartTicks.
+ // This means we expect a wrap-around of the timer to occur and we must wait for it.
+ // Before the wrap-around, CurrentTicks must be less than StartTicks and less than TargetTicks.
+ // After the wrap-around, CurrentTicks must be larger than StartTicks and larger than TargetTicks.
+ // If this is not the case, then the delay has been reached and may even have been exceeded if this
+ // function was suspended by a higher priority interrupt.
+
+ // The order of operations is essential to avoid arithmetic overflow problems
+ TargetTicks = ((UINTN)SP804_MAX_TICKS - DelayTicks) + StartTicks;
+
+ // First wait for the wrap-around to occur
+ do {
+ CurrentTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
+ } while (CurrentTicks <= StartTicks);
+
+ // Then wait for the target
+ do {
+ CurrentTicks = MmioRead32 (SP804_TIMER_METRONOME_BASE + SP804_TIMER_CURRENT_REG);
+ } while (CurrentTicks > TargetTicks);
+ }
+
+ return MicroSeconds;
+}
+
+/**
+ Stalls the CPU for at least the given number of nanoseconds.
+
+ Stalls the CPU for the number of nanoseconds specified by NanoSeconds.
+
+ When the timer frequency is 1MHz, each tick corresponds to 1 microsecond.
+ Therefore, the nanosecond delay will be rounded up to the nearest 1 microsecond.
+
+ @param NanoSeconds The minimum number of nanoseconds to delay.
+
+ @return The value of NanoSeconds inputted.
+
+**/
+UINTN
+EFIAPI
+NanoSecondDelay (
+ IN UINTN NanoSeconds
+ )
+{
+ UINTN MicroSeconds;
+
+ // Round up to 1us Tick Number
+ MicroSeconds = NanoSeconds / 1000;
+ MicroSeconds += ((NanoSeconds % 1000) == 0) ? 0 : 1;
+
+ MicroSecondDelay (MicroSeconds);
+
+ return NanoSeconds;
+}
+
+/**
+ Retrieves the current value of a 64-bit free running performance counter.
+
+ The counter can either count up by 1 or count down by 1. If the physical
+ performance counter counts by a larger increment, then the counter values
+ must be translated. The properties of the counter can be retrieved from
+ GetPerformanceCounterProperties().
+
+ @return The current value of the free running performance counter.
+
+**/
+UINT64
+EFIAPI
+GetPerformanceCounter (
+ VOID
+ )
+{
+ // Free running 64-bit/32-bit counter is needed here.
+ // Don't think we need this to boot, just to do performance profile
+ UINT64 Value;
+ Value = MmioRead32 (SP804_TIMER_PERFORMANCE_BASE + SP804_TIMER_CURRENT_REG);
+ return Value;
+}
+
+
+/**
+ Retrieves the 64-bit frequency in Hz and the range of performance counter
+ values.
+
+ If StartValue is not NULL, then the value that the performance counter starts
+ with immediately after is it rolls over is returned in StartValue. If
+ EndValue is not NULL, then the value that the performance counter end with
+ immediately before it rolls over is returned in EndValue. The 64-bit
+ frequency of the performance counter in Hz is always returned. If StartValue
+ is less than EndValue, then the performance counter counts up. If StartValue
+ is greater than EndValue, then the performance counter counts down. For
+ example, a 64-bit free running counter that counts up would have a StartValue
+ of 0 and an EndValue of 0xFFFFFFFFFFFFFFFF. A 24-bit free running counter
+ that counts down would have a StartValue of 0xFFFFFF and an EndValue of 0.
+
+ @param StartValue The value the performance counter starts with when it
+ rolls over.
+ @param EndValue The value that the performance counter ends with before
+ it rolls over.
+
+ @return The frequency in Hz.
+
+**/
+UINT64
+EFIAPI
+GetPerformanceCounterProperties (
+ OUT UINT64 *StartValue, OPTIONAL
+ OUT UINT64 *EndValue OPTIONAL
+ )
+{
+ if (StartValue != NULL) {
+ // Timer starts with the reload value
+ *StartValue = 0xFFFFFFFF;
+ }
+
+ if (EndValue != NULL) {
+ // Timer counts down to 0x0
+ *EndValue = (UINT64)0ULL;
+ }
+
+ return PcdGet64 (PcdEmbeddedPerformanceCounterFrequencyInHz);
+}
diff --git a/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.inf b/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.inf
index 0928cae53..d9bce48b9 100644
--- a/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.inf
+++ b/ArmPlatformPkg/Library/SP804TimerLib/SP804TimerLib.inf
@@ -1,44 +1,44 @@
-#/** @file
-# Timer library implementation
-#
-#
-# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = SP804TimerLib
- FILE_GUID = 09cefa99-0d07-487f-a651-fb44f094b1c7
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = TimerLib
-
- CONSTRUCTOR = TimerConstructor
-
-[Sources.common]
- SP804TimerLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
-
-[LibraryClasses]
- DebugLib
- IoLib
- BaseLib
-
-[Pcd]
- gArmPlatformTokenSpaceGuid.PcdSP804TimerFrequencyInMHz
- gArmPlatformTokenSpaceGuid.PcdSP804TimerPerformanceBase
- gArmPlatformTokenSpaceGuid.PcdSP804TimerMetronomeBase
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterFrequencyInHz
+#/** @file
+# Timer library implementation
+#
+#
+# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SP804TimerLib
+ FILE_GUID = 09cefa99-0d07-487f-a651-fb44f094b1c7
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = TimerLib
+
+ CONSTRUCTOR = TimerConstructor
+
+[Sources.common]
+ SP804TimerLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ IoLib
+ BaseLib
+
+[Pcd]
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerFrequencyInMHz
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerPerformanceBase
+ gArmPlatformTokenSpaceGuid.PcdSP804TimerMetronomeBase
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterFrequencyInHz
diff --git a/ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf b/ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf
index 8c8d61088..fb77e4db5 100755
--- a/ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf
+++ b/ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf
@@ -1,66 +1,66 @@
-#/** @file
-#
-# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmMemoryInitPeiLib
- FILE_GUID = 55ddb6e0-70b5-11e0-b33e-0002a5d5c51b
- MODULE_TYPE = SEC
- VERSION_STRING = 1.0
- LIBRARY_CLASS = PlatformPeiLib
-
-[Sources]
- MemoryInitPeiLib.c
-
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- DebugLib
- HobLib
- ArmLib
- ArmPlatformLib
-
-[Guids]
- gEfiMemoryTypeInformationGuid
-
-[Ppis]
-
-[FeaturePcd]
- gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdFdBaseAddress
- gArmTokenSpaceGuid.PcdFdSize
-
- gArmTokenSpaceGuid.PcdSystemMemoryBase
- gArmTokenSpaceGuid.PcdSystemMemorySize
- gArmPlatformTokenSpaceGuid.PcdSystemMemoryUefiRegionSize
-
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData
-
-[depex]
- TRUE
+#/** @file
+#
+# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmMemoryInitPeiLib
+ FILE_GUID = 55ddb6e0-70b5-11e0-b33e-0002a5d5c51b
+ MODULE_TYPE = SEC
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = PlatformPeiLib
+
+[Sources]
+ MemoryInitPeiLib.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ HobLib
+ ArmLib
+ ArmPlatformLib
+
+[Guids]
+ gEfiMemoryTypeInformationGuid
+
+[Ppis]
+
+[FeaturePcd]
+ gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdFdBaseAddress
+ gArmTokenSpaceGuid.PcdFdSize
+
+ gArmTokenSpaceGuid.PcdSystemMemoryBase
+ gArmTokenSpaceGuid.PcdSystemMemorySize
+ gArmPlatformTokenSpaceGuid.PcdSystemMemoryUefiRegionSize
+
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData
+
+[depex]
+ TRUE
diff --git a/ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf b/ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf
index 01f935952..5cddeccb6 100755
--- a/ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf
+++ b/ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf
@@ -1,53 +1,53 @@
-#/** @file
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = ArmPlatformPeiLib
- FILE_GUID = 49d37060-70b5-11e0-aa2d-0002a5d5c51b
- MODULE_TYPE = SEC
- VERSION_STRING = 1.0
- LIBRARY_CLASS = PlatformPeiLib
-
-[Sources]
- PlatformPeiLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
-
-[LibraryClasses]
- DebugLib
- HobLib
- ArmPlatformLib
-
-[Ppis]
- gEfiPeiMasterBootModePpiGuid # PPI ALWAYS_PRODUCED
- gEfiPeiBootInRecoveryModePpiGuid # PPI SOMETIMES_PRODUCED
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdFdBaseAddress
- gArmTokenSpaceGuid.PcdFdSize
-
- gArmTokenSpaceGuid.PcdFvBaseAddress
- gArmTokenSpaceGuid.PcdFvSize
-
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize
-
-[depex]
- TRUE
+#/** @file
+#
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = ArmPlatformPeiLib
+ FILE_GUID = 49d37060-70b5-11e0-aa2d-0002a5d5c51b
+ MODULE_TYPE = SEC
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = PlatformPeiLib
+
+[Sources]
+ PlatformPeiLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ HobLib
+ ArmPlatformLib
+
+[Ppis]
+ gEfiPeiMasterBootModePpiGuid # PPI ALWAYS_PRODUCED
+ gEfiPeiBootInRecoveryModePpiGuid # PPI SOMETIMES_PRODUCED
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdFdBaseAddress
+ gArmTokenSpaceGuid.PcdFdSize
+
+ gArmTokenSpaceGuid.PcdFvBaseAddress
+ gArmTokenSpaceGuid.PcdFvSize
+
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize
+
+[depex]
+ TRUE
diff --git a/ArmPlatformPkg/PrePi/ModuleEntryPoint.S b/ArmPlatformPkg/PrePi/ModuleEntryPoint.S
index 9215198d9..c0c20a920 100755
--- a/ArmPlatformPkg/PrePi/ModuleEntryPoint.S
+++ b/ArmPlatformPkg/PrePi/ModuleEntryPoint.S
@@ -1,5 +1,5 @@
//
-// Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+// Copyright (c) 2011-2013, ARM Limited. All rights reserved.
//
// This program and the accompanying materials
// are licensed and made available under the terms and conditions of the BSD License
@@ -16,6 +16,8 @@
#include <Library/PcdLib.h>
#include <AutoGen.h>
+#include <Chipset/ArmV7.h>
+
.text
.align 3
@@ -35,8 +37,7 @@ ASM_PFX(_ModuleEntryPoint):
_SetSVCMode:
// Enter SVC mode, Disable FIQ and IRQ
- //TODO: remove hardcoded values
- mov r1, #0x13|0x80|0x40
+ mov r1, #(CPSR_MODE_SVC | CPSR_IRQ | CPSR_FIQ)
msr CPSR_c, r1
// Check if we can install the stack at the top of the System Memory or if we need
diff --git a/ArmPlatformPkg/PrePi/ModuleEntryPoint.asm b/ArmPlatformPkg/PrePi/ModuleEntryPoint.asm
index 0dea1c327..5efdb532a 100644
--- a/ArmPlatformPkg/PrePi/ModuleEntryPoint.asm
+++ b/ArmPlatformPkg/PrePi/ModuleEntryPoint.asm
@@ -1,5 +1,5 @@
//
-// Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+// Copyright (c) 2011-2013, ARM Limited. All rights reserved.
//
// This program and the accompanying materials
// are licensed and made available under the terms and conditions of the BSD License
@@ -16,6 +16,8 @@
#include <Library/PcdLib.h>
#include <AutoGen.h>
+#include <Chipset/ArmV7.h>
+
INCLUDE AsmMacroIoLib.inc
IMPORT CEntryPoint
@@ -37,8 +39,7 @@ _ModuleEntryPoint
_SetSVCMode
// Enter SVC mode, Disable FIQ and IRQ
- //TODO: remove hardcoded values
- mov r1, #0x13 :OR: 0x80 :OR: 0x40
+ mov r1, #(CPSR_MODE_SVC :OR: CPSR_IRQ :OR: CPSR_FIQ)
msr CPSR_c, r1
// Check if we can install the stack at the top of the System Memory or if we need
diff --git a/ArmPlatformPkg/Scripts/Ds5/build_report.py b/ArmPlatformPkg/Scripts/Ds5/build_report.py
index 3805c0b43..e59230090 100644
--- a/ArmPlatformPkg/Scripts/Ds5/build_report.py
+++ b/ArmPlatformPkg/Scripts/Ds5/build_report.py
@@ -1,54 +1,54 @@
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-import re
-
-class BuildReport:
- PCDs = {}
-
- def parse_platform_summary(self, file):
- pass
-
- def parse_pcd_report(self, report_file):
- pcd_reg = re.compile(" (\*P|\*F|\*M| ) (\w+)(\ +)\: (.*) \((\w+)\) = (.*)\n")
-
- for line in report_file.xreadlines():
- stripped_line = line.strip()
- if re.match("\<=+\>", stripped_line):
- return
- elif re.match("g.*Guid", stripped_line):
- guid = stripped_line
- self.PCDs[guid] = {}
- else:
- m = pcd_reg.match(line)
- if m:
- self.PCDs[guid][m.group(2)] = (m.group(6).strip(),m.group(5))
-
- def parse_firmware_device(self, file):
- pass
-
- def parse_module_summary(self, file):
- #print "Module Summary"
- pass
-
- CONST_SECTION_HEADERS = [('Platform Summary', parse_platform_summary),
- ('Platform Configuration Database Report',parse_pcd_report),
- ('Firmware Device (FD)',parse_firmware_device),
- ('Module Summary',parse_module_summary)]
-
- def __init__(self, filename = 'report.log'):
- report_file = open(filename, 'r')
- for line in report_file.xreadlines():
- for section_header in BuildReport.CONST_SECTION_HEADERS:
- if line.strip() == section_header[0]:
- section_header[1](self, report_file)
- #print self.PCDs
+#
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+import re
+
+class BuildReport:
+ PCDs = {}
+
+ def parse_platform_summary(self, file):
+ pass
+
+ def parse_pcd_report(self, report_file):
+ pcd_reg = re.compile(" (\*P|\*F|\*M| ) (\w+)(\ +)\: (.*) \((\w+)\) = (.*)\n")
+
+ for line in report_file.xreadlines():
+ stripped_line = line.strip()
+ if re.match("\<=+\>", stripped_line):
+ return
+ elif re.match("g.*Guid", stripped_line):
+ guid = stripped_line
+ self.PCDs[guid] = {}
+ else:
+ m = pcd_reg.match(line)
+ if m:
+ self.PCDs[guid][m.group(2)] = (m.group(6).strip(),m.group(5))
+
+ def parse_firmware_device(self, file):
+ pass
+
+ def parse_module_summary(self, file):
+ #print "Module Summary"
+ pass
+
+ CONST_SECTION_HEADERS = [('Platform Summary', parse_platform_summary),
+ ('Platform Configuration Database Report',parse_pcd_report),
+ ('Firmware Device (FD)',parse_firmware_device),
+ ('Module Summary',parse_module_summary)]
+
+ def __init__(self, filename = 'report.log'):
+ report_file = open(filename, 'r')
+ for line in report_file.xreadlines():
+ for section_header in BuildReport.CONST_SECTION_HEADERS:
+ if line.strip() == section_header[0]:
+ section_header[1](self, report_file)
+ #print self.PCDs
diff --git a/ArmPlatformPkg/Scripts/Ds5/cmd_load_symbols.py b/ArmPlatformPkg/Scripts/Ds5/cmd_load_symbols.py
index 424eb63cb..994a475cb 100644
--- a/ArmPlatformPkg/Scripts/Ds5/cmd_load_symbols.py
+++ b/ArmPlatformPkg/Scripts/Ds5/cmd_load_symbols.py
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -21,16 +21,18 @@ import edk2_debugger
reload(edk2_debugger)
def usage():
+ print "-v,--verbose"
print "-a,--all: Load all symbols"
print "-l,--report=: Filename for the EDK2 report log"
print "-m,--sysmem=(base,size): System Memory region"
print "-f,--fv=(base,size): Firmware region"
print "-r,--rom=(base,size): ROM region"
+verbose = False
load_all = False
report_file = None
regions = []
-opts,args = getopt.getopt(sys.argv[1:], "har:vm:vr:vf:v", ["help","all","report=","sysmem=","rom=","fv="])
+opts,args = getopt.getopt(sys.argv[1:], "hvar:vm:vr:vf:v", ["help","verbose","all","report=","sysmem=","rom=","fv="])
if (opts is None) or (not opts):
report_file = '../../../report.log'
else:
@@ -44,6 +46,8 @@ else:
if o in ("-h","--help"):
usage()
sys.exit()
+ elif o in ("-v","--verbose"):
+ verbose = True
elif o in ("-a","--all"):
load_all = True
elif o in ("-l","--report"):
@@ -58,7 +62,7 @@ else:
region_type = edk2_debugger.ArmPlatformDebugger.REGION_TYPE_ROM
regex = region_reg
else:
- assert False, "Unhandled option"
+ assert False, "Unhandled option (%s)" % o
if region_type:
m = regex.match(a)
@@ -83,10 +87,8 @@ ec.getExecutionService().waitForStop()
# in case the execution context reference is out of date
ec = debugger.getExecutionContext(0)
-armplatform_debugger = edk2_debugger.ArmPlatformDebugger(ec, report_file, regions)
-
try:
- armplatform_debugger = edk2_debugger.ArmPlatformDebugger(ec, report_file, regions)
+ armplatform_debugger = edk2_debugger.ArmPlatformDebugger(ec, report_file, regions, verbose)
if load_all:
armplatform_debugger.load_all_symbols()
diff --git a/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py b/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py
index 71e5a3ccd..4867af193 100644
--- a/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py
+++ b/ArmPlatformPkg/Scripts/Ds5/edk2_debugger.py
@@ -1,217 +1,221 @@
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-import os
-
-import firmware_volume
-import build_report
-import system_table
-
-# Reload external classes
-reload(firmware_volume)
-reload(build_report)
-reload(system_table)
-
-def readMem32(executionContext, address):
- bytes = executionContext.getMemoryService().read(address, 4, 32)
- return struct.unpack('<I',bytes)[0]
-
-def dump_fv(ec, fv_base, fv_size):
- fv = firmware_volume.FirmwareVolume(ec,
- int(build.PCDs['gArmTokenSpaceGuid']['PcdFvBaseAddress'][0],16),
- int(build.PCDs['gArmTokenSpaceGuid']['PcdFvSize'][0],16))
-
- ffs = fv.get_next_ffs()
- while ffs != None:
- print "# %s" % ffs
-
- section = ffs.get_next_section()
- while section != None:
- print "\t%s" % section
- try:
- print "\t\t- %s" % section.get_debug_filepath()
- except Exception:
- pass
- section = ffs.get_next_section(section)
-
- ffs = fv.get_next_ffs(ffs)
-
-def dump_system_table(ec, mem_base, mem_size):
- st = system_table.SystemTable(ec, mem_base, mem_size)
-
- debug_info_table_base = st.get_configuration_table(system_table.DebugInfoTable.CONST_DEBUG_INFO_TABLE_GUID)
-
- debug_info_table = system_table.DebugInfoTable(ec, debug_info_table_base)
- debug_info_table.dump()
-
-def load_symbol_from_file(ec, filename, address):
- try:
- ec.getImageService().addSymbols(filename, address)
- except:
- try:
- # We could get an exception if the symbols are already loaded
- ec.getImageService().unloadSymbols(filename)
- ec.getImageService().addSymbols(filename, address)
- except:
- print "Warning: not possible to load symbols from %s" % filename
- pass
-
-class ArmPlatform:
- def __init__(self, sysmembase=None, sysmemsize=None, fvs={}):
- self.sysmembase = sysmembase
- self.sysmemsize = sysmemsize
- self.fvs = fvs
-
-class ArmPlatformDebugger:
- system_table = None
- firmware_volumes = {}
-
- REGION_TYPE_SYSMEM = 1
- REGION_TYPE_ROM = 2
- REGION_TYPE_FV = 3
-
- def __init__(self, ec, report_log, regions):
- self.ec = ec
- fvs = []
- sysmem_base = None
- sysmem_size = None
-
- if report_log and os.path.isfile(report_log):
- try:
- self.build = build_report.BuildReport(report_log)
- except IOError:
- raise IOError(2, 'Report \'%s\' isnot valid' % report_log)
-
- # Generate list of supported Firmware Volumes
- if self.build.PCDs['gArmTokenSpaceGuid'].has_key('PcdFvSize') and int(self.build.PCDs['gArmTokenSpaceGuid']['PcdFvSize'][0],16) != 0:
- fvs.append((int(self.build.PCDs['gArmTokenSpaceGuid']['PcdFvBaseAddress'][0],16),int(self.build.PCDs['gArmTokenSpaceGuid']['PcdFvSize'][0],16)))
- if self.build.PCDs['gArmTokenSpaceGuid'].has_key('PcdSecureFvSize') and int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSecureFvSize'][0],16) != 0:
- fvs.append((int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSecureFvBaseAddress'][0],16),int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSecureFvSize'][0],16)))
- if self.build.PCDs['gArmTokenSpaceGuid'].has_key('PcdHypFvSize') and int(self.build.PCDs['gArmTokenSpaceGuid']['PcdHypFvSize'][0],16) != 0:
- fvs.append((int(self.build.PCDs['gArmTokenSpaceGuid']['PcdHypFvBaseAddress'][0],16),int(self.build.PCDs['gArmTokenSpaceGuid']['PcdHypFvSize'][0],16)))
-
- sysmem_base = int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSystemMemoryBase'][0],16)
- sysmem_size = int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSystemMemorySize'][0],16)
- else:
- for region in regions:
- if region[0] == ArmPlatformDebugger.REGION_TYPE_SYSMEM:
- sysmem_base = region[1]
- sysmem_size = region[2]
- elif region[0] == ArmPlatformDebugger.REGION_TYPE_FV:
- fvs.append((region[1],region[2]))
- elif region[0] == ArmPlatformDebugger.REGION_TYPE_ROM:
- for base in xrange(region[1], region[1] + region[2], 0x400000):
- signature = struct.unpack("cccc", self.ec.getMemoryService().read(base, 4, 32))
- if signature == FirmwareVolume.CONST_FV_SIGNATURE:
- fvs.append((base,0))
- else:
- print "Region type '%d' Not Supported" % region[0]
-
- self.platform = ArmPlatform(sysmem_base, sysmem_size, fvs)
-
- def in_sysmem(self, addr):
- return (self.platform.sysmembase is not None) and (self.platform.sysmembase <= addr) and (addr < self.platform.sysmembase + self.platform.sysmemsize)
-
- def in_fv(self, addr):
- return (self.get_fv_at(addr) != None)
-
- def get_fv_at(self, addr):
- for fv in self.platform.fvs:
- if (fv[0] <= addr) and (addr < fv[0] + fv[1]):
- return fv
- return None
-
- def load_current_symbols(self):
- pc = int(self.ec.getRegisterService().getValue('PC')) & 0xFFFFFFFF
- if self.in_fv(pc):
- debug_infos = []
-
- (fv_base, fv_size) = self.get_fv_at(pc)
-
- if self.firmware_volumes.has_key(fv_base) == False:
- self.firmware_volumes[fv_base] = firmware_volume.FirmwareVolume(self.ec, fv_base, fv_size)
-
- stack_frame = self.ec.getTopLevelStackFrame()
- info = self.firmware_volumes[fv_base].load_symbols_at(int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF)
- debug_infos.append(info)
- while stack_frame.next() is not None:
- stack_frame = stack_frame.next()
-
- # Stack frame attached to 'PC'
- pc = int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF
-
- # Check if the symbols for this stack frame have already been loaded
- found = False
- for debug_info in debug_infos:
- if (pc >= debug_info[0]) and (pc < debug_info[0] + debug_info[1]):
- found = True
- if found == False:
- info = self.firmware_volumes[fv_base].load_symbols_at(pc)
- debug_infos.append(info)
-
- #self.firmware_volumes[fv_base].load_symbols_at(pc)
- elif self.in_sysmem(pc):
- debug_infos = []
-
- if self.system_table is None:
- # Find the System Table
- self.system_table = system_table.SystemTable(self.ec, self.platform.sysmembase, self.platform.sysmemsize)
-
- # Find the Debug Info Table
- debug_info_table_base = self.system_table.get_configuration_table(system_table.DebugInfoTable.CONST_DEBUG_INFO_TABLE_GUID)
- self.debug_info_table = system_table.DebugInfoTable(self.ec, debug_info_table_base)
-
- stack_frame = self.ec.getTopLevelStackFrame()
- info = self.debug_info_table.load_symbols_at(int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF)
- debug_infos.append(info)
- while stack_frame.next() is not None:
- stack_frame = stack_frame.next()
-
- # Stack frame attached to 'PC'
- pc = int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF
-
- # Check if the symbols for this stack frame have already been loaded
- found = False
- for debug_info in debug_infos:
- if (pc >= debug_info[0]) and (pc < debug_info[0] + debug_info[1]):
- found = True
- if found == False:
- info = self.debug_info_table.load_symbols_at(pc)
- debug_infos.append(info)
-
- #self.debug_info_table.load_symbols_at(pc)
- else:
- raise Exception('ArmPlatformDebugger', "Not supported region")
-
- def load_all_symbols(self):
- # Load all the XIP symbols attached to the Firmware Volume
- for (fv_base, fv_size) in self.platform.fvs:
- if self.firmware_volumes.has_key(fv_base) == False:
- self.firmware_volumes[fv_base] = firmware_volume.FirmwareVolume(self.ec, fv_base, fv_size)
- self.firmware_volumes[fv_base].load_all_symbols()
-
- try:
- # Load all symbols of module loaded into System Memory
- if self.system_table is None:
- # Find the System Table
- self.system_table = system_table.SystemTable(self.ec, self.platform.sysmembase, self.platform.sysmemsize)
-
-
- # Find the Debug Info Table
- debug_info_table_base = self.system_table.get_configuration_table(system_table.DebugInfoTable.CONST_DEBUG_INFO_TABLE_GUID)
- self.debug_info_table = system_table.DebugInfoTable(self.ec, debug_info_table_base)
-
- self.debug_info_table.load_all_symbols()
- except:
- # Debugger exception could be excepted if DRAM has not been initialized or if we have not started to run from DRAM yet
- print "Note: no symbols have been found in System Memory (possible cause: the UEFI permanent memory has been installed yet)"
- pass
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+import os
+
+import firmware_volume
+import build_report
+import system_table
+
+# Reload external classes
+reload(firmware_volume)
+reload(build_report)
+reload(system_table)
+
+def readMem32(executionContext, address):
+ bytes = executionContext.getMemoryService().read(address, 4, 32)
+ return struct.unpack('<I',bytes)[0]
+
+def dump_fv(ec, fv_base, fv_size):
+ fv = firmware_volume.FirmwareVolume(ec,
+ int(build.PCDs['gArmTokenSpaceGuid']['PcdFvBaseAddress'][0],16),
+ int(build.PCDs['gArmTokenSpaceGuid']['PcdFvSize'][0],16))
+
+ ffs = fv.get_next_ffs()
+ while ffs != None:
+ print "# %s" % ffs
+
+ section = ffs.get_next_section()
+ while section != None:
+ print "\t%s" % section
+ try:
+ print "\t\t- %s" % section.get_debug_filepath()
+ except Exception:
+ pass
+ section = ffs.get_next_section(section)
+
+ ffs = fv.get_next_ffs(ffs)
+
+def dump_system_table(ec, mem_base, mem_size):
+ st = system_table.SystemTable(ec, mem_base, mem_size)
+
+ debug_info_table_base = st.get_configuration_table(system_table.DebugInfoTable.CONST_DEBUG_INFO_TABLE_GUID)
+
+ debug_info_table = system_table.DebugInfoTable(ec, debug_info_table_base)
+ debug_info_table.dump()
+
+def load_symbol_from_file(ec, filename, address, verbose = False):
+ if verbose:
+ print "Add symbols of %s at 0x%x" % (filename, address)
+
+ try:
+ ec.getImageService().addSymbols(filename, address)
+ except:
+ try:
+ # We could get an exception if the symbols are already loaded
+ ec.getImageService().unloadSymbols(filename)
+ ec.getImageService().addSymbols(filename, address)
+ except:
+ print "Warning: not possible to load symbols from %s at 0x%x" % (filename, address)
+ pass
+
+class ArmPlatform:
+ def __init__(self, sysmembase=None, sysmemsize=None, fvs={}):
+ self.sysmembase = sysmembase
+ self.sysmemsize = sysmemsize
+ self.fvs = fvs
+
+class ArmPlatformDebugger:
+ system_table = None
+ firmware_volumes = {}
+
+ REGION_TYPE_SYSMEM = 1
+ REGION_TYPE_ROM = 2
+ REGION_TYPE_FV = 3
+
+ def __init__(self, ec, report_log, regions, verbose = False):
+ self.ec = ec
+ self.verbose = verbose
+ fvs = []
+ sysmem_base = None
+ sysmem_size = None
+
+ if report_log and os.path.isfile(report_log):
+ try:
+ self.build = build_report.BuildReport(report_log)
+ except IOError:
+ raise IOError(2, 'Report \'%s\' is not valid' % report_log)
+
+ # Generate list of supported Firmware Volumes
+ if self.build.PCDs['gArmTokenSpaceGuid'].has_key('PcdFvSize') and int(self.build.PCDs['gArmTokenSpaceGuid']['PcdFvSize'][0],16) != 0:
+ fvs.append((int(self.build.PCDs['gArmTokenSpaceGuid']['PcdFvBaseAddress'][0],16),int(self.build.PCDs['gArmTokenSpaceGuid']['PcdFvSize'][0],16)))
+ if self.build.PCDs['gArmTokenSpaceGuid'].has_key('PcdSecureFvSize') and int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSecureFvSize'][0],16) != 0:
+ fvs.append((int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSecureFvBaseAddress'][0],16),int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSecureFvSize'][0],16)))
+ if self.build.PCDs['gArmTokenSpaceGuid'].has_key('PcdHypFvSize') and int(self.build.PCDs['gArmTokenSpaceGuid']['PcdHypFvSize'][0],16) != 0:
+ fvs.append((int(self.build.PCDs['gArmTokenSpaceGuid']['PcdHypFvBaseAddress'][0],16),int(self.build.PCDs['gArmTokenSpaceGuid']['PcdHypFvSize'][0],16)))
+
+ sysmem_base = int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSystemMemoryBase'][0],16)
+ sysmem_size = int(self.build.PCDs['gArmTokenSpaceGuid']['PcdSystemMemorySize'][0],16)
+ else:
+ for region in regions:
+ if region[0] == ArmPlatformDebugger.REGION_TYPE_SYSMEM:
+ sysmem_base = region[1]
+ sysmem_size = region[2]
+ elif region[0] == ArmPlatformDebugger.REGION_TYPE_FV:
+ fvs.append((region[1],region[2]))
+ elif region[0] == ArmPlatformDebugger.REGION_TYPE_ROM:
+ for base in xrange(region[1], region[1] + region[2], 0x400000):
+ signature = struct.unpack("cccc", self.ec.getMemoryService().read(base, 4, 32))
+ if signature == FirmwareVolume.CONST_FV_SIGNATURE:
+ fvs.append((base,0))
+ else:
+ print "Region type '%d' Not Supported" % region[0]
+
+ self.platform = ArmPlatform(sysmem_base, sysmem_size, fvs)
+
+ def in_sysmem(self, addr):
+ return (self.platform.sysmembase is not None) and (self.platform.sysmembase <= addr) and (addr < self.platform.sysmembase + self.platform.sysmemsize)
+
+ def in_fv(self, addr):
+ return (self.get_fv_at(addr) != None)
+
+ def get_fv_at(self, addr):
+ for fv in self.platform.fvs:
+ if (fv[0] <= addr) and (addr < fv[0] + fv[1]):
+ return fv
+ return None
+
+ def load_current_symbols(self):
+ pc = int(self.ec.getRegisterService().getValue('PC')) & 0xFFFFFFFF
+ if self.in_fv(pc):
+ debug_infos = []
+
+ (fv_base, fv_size) = self.get_fv_at(pc)
+
+ if self.firmware_volumes.has_key(fv_base) == False:
+ self.firmware_volumes[fv_base] = firmware_volume.FirmwareVolume(self.ec, fv_base, fv_size)
+
+ stack_frame = self.ec.getTopLevelStackFrame()
+ info = self.firmware_volumes[fv_base].load_symbols_at(int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF, self.verbose)
+ debug_infos.append(info)
+ while stack_frame.next() is not None:
+ stack_frame = stack_frame.next()
+
+ # Stack frame attached to 'PC'
+ pc = int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF
+
+ # Check if the symbols for this stack frame have already been loaded
+ found = False
+ for debug_info in debug_infos:
+ if (pc >= debug_info[0]) and (pc < debug_info[0] + debug_info[1]):
+ found = True
+ if found == False:
+ info = self.firmware_volumes[fv_base].load_symbols_at(pc)
+ debug_infos.append(info)
+
+ #self.firmware_volumes[fv_base].load_symbols_at(pc)
+ elif self.in_sysmem(pc):
+ debug_infos = []
+
+ if self.system_table is None:
+ # Find the System Table
+ self.system_table = system_table.SystemTable(self.ec, self.platform.sysmembase, self.platform.sysmemsize)
+
+ # Find the Debug Info Table
+ debug_info_table_base = self.system_table.get_configuration_table(system_table.DebugInfoTable.CONST_DEBUG_INFO_TABLE_GUID)
+ self.debug_info_table = system_table.DebugInfoTable(self.ec, debug_info_table_base)
+
+ stack_frame = self.ec.getTopLevelStackFrame()
+ info = self.debug_info_table.load_symbols_at(int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF, self.verbose)
+ debug_infos.append(info)
+ while stack_frame.next() is not None:
+ stack_frame = stack_frame.next()
+
+ # Stack frame attached to 'PC'
+ pc = int(stack_frame.getRegisterService().getValue('PC')) & 0xFFFFFFFF
+
+ # Check if the symbols for this stack frame have already been loaded
+ found = False
+ for debug_info in debug_infos:
+ if (pc >= debug_info[0]) and (pc < debug_info[0] + debug_info[1]):
+ found = True
+ if found == False:
+ info = self.debug_info_table.load_symbols_at(pc)
+ debug_infos.append(info)
+
+ #self.debug_info_table.load_symbols_at(pc)
+ else:
+ raise Exception('ArmPlatformDebugger', "Not supported region")
+
+ def load_all_symbols(self):
+ # Load all the XIP symbols attached to the Firmware Volume
+ for (fv_base, fv_size) in self.platform.fvs:
+ if self.firmware_volumes.has_key(fv_base) == False:
+ self.firmware_volumes[fv_base] = firmware_volume.FirmwareVolume(self.ec, fv_base, fv_size)
+ self.firmware_volumes[fv_base].load_all_symbols(self.verbose)
+
+ try:
+ # Load all symbols of module loaded into System Memory
+ if self.system_table is None:
+ # Find the System Table
+ self.system_table = system_table.SystemTable(self.ec, self.platform.sysmembase, self.platform.sysmemsize)
+
+
+ # Find the Debug Info Table
+ debug_info_table_base = self.system_table.get_configuration_table(system_table.DebugInfoTable.CONST_DEBUG_INFO_TABLE_GUID)
+ self.debug_info_table = system_table.DebugInfoTable(self.ec, debug_info_table_base)
+
+ self.debug_info_table.load_all_symbols(self.verbose)
+ except:
+ # Debugger exception could be excepted if DRAM has not been initialized or if we have not started to run from DRAM yet
+ print "Note: no symbols have been found in System Memory (possible cause: the UEFI permanent memory has been installed yet)"
+ pass
diff --git a/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py b/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py
index c4e02ece2..651c748a1 100644
--- a/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py
+++ b/ArmPlatformPkg/Scripts/Ds5/firmware_volume.py
@@ -1,301 +1,312 @@
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-from arm_ds.debugger_v1 import DebugException
-
-import struct
-import string
-
-import edk2_debugger
-
-class EfiFileSection(object):
- EFI_SECTION_PE32 = 0x10
- EFI_SECTION_PIC = 0x11
- EFI_SECTION_TE = 0x12
-
- EFI_IMAGE_DEBUG_TYPE_CODEVIEW = 0x2
-
- SIZEOF_EFI_FFS_FILE_HEADER = 0x28
-
- def __init__(self, ec, base):
- self.base = base
- self.ec = ec
-
- def __str__(self):
- return "FileSection(type:0x%X, size:0x%x)" % (self.get_type(), self.get_size())
-
- def get_base(self):
- return self.base
-
- def get_type(self):
- return struct.unpack("B", self.ec.getMemoryService().read(self.base + 0x3, 1, 8))[0]
-
- def get_size(self):
- return (struct.unpack("<I", self.ec.getMemoryService().read(self.base, 4, 32))[0] & 0x00ffffff)
-
- def get_debug_filepath(self):
- type = self.get_type()
- if type == EfiFileSection.EFI_SECTION_TE:
- section = EfiSectionTE(self, ec, self.base + 0x4)
- elif type == EfiFileSection.EFI_SECTION_PE32:
- section = EfiSectionPE32(self, ec, self.base + 0x4)
- else:
- raise Exception("EfiFileSection", "No debug section")
- return section.get_debug_filepath()
-
-class EfiSectionTE:
- SIZEOF_EFI_TE_IMAGE_HEADER = 0x28
- EFI_TE_IMAGE_SIGNATURE = ('V','Z')
-
- def __init__(self, ec, base_te):
- self.ec = ec
- self.base_te = int(base_te)
- te_sig = struct.unpack("cc", self.ec.getMemoryService().read(self.base_te, 2, 32))
- if te_sig != EfiSectionTE.EFI_TE_IMAGE_SIGNATURE:
- raise Exception("EfiFileSectionTE","TE Signature incorrect")
-
- def get_debug_filepath(self):
- stripped_size = struct.unpack("<H", self.ec.getMemoryService().read(self.base_te + 0x6, 2, 32))[0]
- stripped_size -= EfiSectionTE.SIZEOF_EFI_TE_IMAGE_HEADER
-
- debug_dir_entry_rva = self.ec.getMemoryService().readMemory32(self.base_te + 0x20)
- if debug_dir_entry_rva == 0:
- raise Exception("EfiFileSectionTE","No debug directory for image")
- debug_dir_entry_rva -= stripped_size
-
- debug_type = self.ec.getMemoryService().readMemory32(self.base_te + debug_dir_entry_rva + 0xC)
- if (debug_type != 0xdf) and (debug_type != EfiFileSection.EFI_IMAGE_DEBUG_TYPE_CODEVIEW):
- raise Exception("EfiFileSectionTE","Debug type is not dwarf")
-
- debug_rva = self.ec.getMemoryService().readMemory32(self.base_te + debug_dir_entry_rva + 0x14)
- debug_rva -= stripped_size
-
- dwarf_sig = struct.unpack("cccc", self.ec.getMemoryService().read(self.base_te + debug_rva, 4, 32))
- if (dwarf_sig != 0x66727764) and (dwarf_sig != FirmwareFile.CONST_NB10_SIGNATURE):
- raise Exception("EfiFileSectionTE","Dwarf debug signature not found")
-
- if dwarf_sig == 0x66727764:
- filename = self.base_te + debug_rva + 0xc
- else:
- filename = self.base_te + debug_rva + 0x10
- filename = struct.unpack("200s", self.ec.getMemoryService().read(filename, 200, 32))[0]
- return filename[0:string.find(filename,'\0')]
-
- def get_debug_elfbase(self):
- stripped_size = struct.unpack("<H", self.ec.getMemoryService().read(self.base_te + 0x6, 2, 32))[0]
- stripped_size -= EfiSectionTE.SIZEOF_EFI_TE_IMAGE_HEADER
-
- base_of_code = self.ec.getMemoryService().readMemory32(self.base_te + 0xC)
-
- return self.base_te + base_of_code - stripped_size
-
-class EfiSectionPE32:
- def __init__(self, ec, base_pe32):
- self.ec = ec
- self.base_pe32 = base_pe32
-
- def get_debug_filepath(self):
- # Offset from dos hdr to PE file hdr
- file_header_offset = self.ec.getMemoryService().readMemory32(self.base_pe32 + 0x3C)
-
- # Offset to debug dir in PE hdrs
- debug_dir_entry_rva = self.ec.getMemoryService().readMemory32(self.base_pe32 + file_header_offset + 0xA8)
- if debug_dir_entry_rva == 0:
- raise Exception("EfiFileSectionPE32","No Debug Directory")
-
- debug_type = self.ec.getMemoryService().readMemory32(self.base_pe32 + debug_dir_entry_rva + 0xC)
- if (debug_type != 0xdf) and (debug_type != EfiFileSection.EFI_IMAGE_DEBUG_TYPE_CODEVIEW):
- raise Exception("EfiFileSectionPE32","Debug type is not dwarf")
-
-
- debug_rva = self.ec.getMemoryService().readMemory32(self.base_pe32 + debug_dir_entry_rva + 0x14)
-
- dwarf_sig = struct.unpack("cccc", self.ec.getMemoryService().read(str(self.base_pe32 + debug_rva), 4, 32))
- if (dwarf_sig != 0x66727764) and (dwarf_sig != FirmwareFile.CONST_NB10_SIGNATURE):
- raise Exception("EfiFileSectionPE32","Dwarf debug signature not found")
-
- if dwarf_sig == 0x66727764:
- filename = self.base_pe32 + debug_rva + 0xc
- else:
- filename = self.base_pe32 + debug_rva + 0x10
- filename = struct.unpack("200s", self.ec.getMemoryService().read(str(filename), 200, 32))[0]
- return filename[0:string.find(filename,'\0')]
-
- def get_debug_elfbase(self):
- # Offset from dos hdr to PE file hdr
- pe_file_header = self.base_pe32 + self.ec.getMemoryService().readMemory32(self.base_pe32 + 0x3C)
-
- base_of_code = self.base_pe32 + self.ec.getMemoryService().readMemory32(pe_file_header + 0x28)
- base_of_data = self.base_pe32 + self.ec.getMemoryService().readMemory32(pe_file_header + 0x2C)
-
- if (base_of_code < base_of_data) and (base_of_code != 0):
- return base_of_code
- else:
- return base_of_data
-
-class FirmwareFile:
- EFI_FV_FILETYPE_RAW = 0x01
- EFI_FV_FILETYPE_FREEFORM = 0x02
- EFI_FV_FILETYPE_SECURITY_CORE = 0x03
- EFI_FV_FILETYPE_PEI_CORE = 0x04
- EFI_FV_FILETYPE_DXE_CORE = 0x05
- EFI_FV_FILETYPE_PEIM = 0x06
- EFI_FV_FILETYPE_DRIVER = 0x07
- EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER = 0x08
- EFI_FV_FILETYPE_APPLICATION = 0x09
- EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE = 0x0B
- EFI_FV_FILETYPE_FFS_MIN = 0xF0
-
- CONST_NB10_SIGNATURE = ('N','B','1','0')
-
- def __init__(self, fv, base, ec):
- self.fv = fv
- self.base = base
- self.ec = ec
-
- def __str__(self):
- return "FFS(state:0x%x, type:0x%X, size:0x%x)" % (self.get_state(), self.get_type(), self.get_size())
-
- def get_base(self):
- return self.base
-
- def get_size(self):
- size = (self.ec.getMemoryService().readMemory32(self.base + 0x14) & 0x00ffffff)
-
- # Occupied size is the size considering the alignment
- return size + ((0x8 - (size & 0x7)) & 0x7)
-
- def get_type(self):
- return self.ec.getMemoryService().readMemory8(self.base + 0x12)
-
- def get_state(self):
- state = self.ec.getMemoryService().readMemory8(self.base + 0x17)
-
- polarity = self.fv.get_polarity()
- if polarity:
- state = ~state
-
- highest_bit = 0x80;
- while (highest_bit != 0) and ((highest_bit & state) == 0):
- highest_bit >>= 1
-
- return highest_bit
-
- def get_next_section(self, section=None):
- if section == None:
- if self.get_type() != FirmwareFile.EFI_FV_FILETYPE_FFS_MIN:
- section_base = self.get_base() + 0x18;
- else:
- return None
- else:
- section_base = int(section.get_base() + section.get_size())
-
- # Align to next 4 byte boundary
- if (section_base & 0x3) != 0:
- section_base = section_base + 0x4 - (section_base & 0x3)
-
- if section_base < self.get_base() + self.get_size():
- return EfiFileSection(self.ec, section_base)
- else:
- return None
-
-class FirmwareVolume:
- CONST_FV_SIGNATURE = ('_','F','V','H')
- EFI_FVB2_ERASE_POLARITY = 0x800
-
- DebugInfos = []
-
- def __init__(self, ec, fv_base, fv_size):
- self.ec = ec
- self.fv_base = fv_base
- self.fv_size = fv_size
-
- try:
- signature = struct.unpack("cccc", self.ec.getMemoryService().read(fv_base + 0x28, 4, 32))
- except DebugException:
- raise Exception("FirmwareVolume", "Not possible to access the defined firmware volume at [0x%X,0x%X]. Could be the used build report does not correspond to your current debugging context." % (int(fv_base),int(fv_base+fv_size)))
- if signature != FirmwareVolume.CONST_FV_SIGNATURE:
- raise Exception("FirmwareVolume", "This is not a valid firmware volume")
-
- def get_size(self):
- return self.ec.getMemoryService().readMemory32(self.fv_base + 0x20)
-
- def get_attributes(self):
- return self.ec.getMemoryService().readMemory32(self.fv_base + 0x2C)
-
- def get_polarity(self):
- attributes = self.get_attributes()
- if attributes & FirmwareVolume.EFI_FVB2_ERASE_POLARITY:
- return 1
- else:
- return 0
-
- def get_next_ffs(self, ffs=None):
- if ffs == None:
- # Get the offset of the first FFS file from the FV header
- ffs_base = self.fv_base + self.ec.getMemoryService().readMemory16(self.fv_base + 0x30)
- else:
- # Goto the next FFS file
- ffs_base = int(ffs.get_base() + ffs.get_size())
-
- # Align to next 8 byte boundary
- if (ffs_base & 0x7) != 0:
- ffs_base = ffs_base + 0x8 - (ffs_base & 0x7)
-
- if ffs_base < self.fv_base + self.get_size():
- return FirmwareFile(self, ffs_base, self.ec)
- else:
- return None
-
- def get_debug_info(self):
- self.DebugInfos = []
-
- ffs = self.get_next_ffs()
- while ffs != None:
- section = ffs.get_next_section()
- while section != None:
- type = section.get_type()
- if (type == EfiFileSection.EFI_SECTION_TE) or (type == EfiFileSection.EFI_SECTION_PE32):
- self.DebugInfos.append((section.get_base(), section.get_size(), section.get_type()))
- section = ffs.get_next_section(section)
- ffs = self.get_next_ffs(ffs)
-
- def load_symbols_at(self, addr):
- if self.DebugInfos == []:
- self.get_debug_info()
-
- for debug_info in self.DebugInfos:
- if (addr >= debug_info[0]) and (addr < debug_info[0] + debug_info[1]):
- if debug_info[2] == EfiFileSection.EFI_SECTION_TE:
- section = EfiSectionTE(self.ec, debug_info[0] + 0x4)
- elif debug_info[2] == EfiFileSection.EFI_SECTION_PE32:
- section = EfiSectionPE32(self.ec, debug_info[0] + 0x4)
- else:
- raise Exception('FirmwareVolume','Section Type not supported')
-
- edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase())
-
- return debug_info
-
- def load_all_symbols(self):
- if self.DebugInfos == []:
- self.get_debug_info()
-
- for debug_info in self.DebugInfos:
- if debug_info[2] == EfiFileSection.EFI_SECTION_TE:
- section = EfiSectionTE(self.ec, debug_info[0] + 0x4)
- elif debug_info[2] == EfiFileSection.EFI_SECTION_PE32:
- section = EfiSectionPE32(self.ec, debug_info[0] + 0x4)
- else:
- continue
-
- edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase())
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+from arm_ds.debugger_v1 import DebugException
+
+import struct
+import string
+
+import edk2_debugger
+
+class EfiFileSection(object):
+ EFI_SECTION_PE32 = 0x10
+ EFI_SECTION_PIC = 0x11
+ EFI_SECTION_TE = 0x12
+
+ EFI_IMAGE_DEBUG_TYPE_CODEVIEW = 0x2
+
+ SIZEOF_EFI_FFS_FILE_HEADER = 0x28
+
+ def __init__(self, ec, base):
+ self.base = base
+ self.ec = ec
+
+ def __str__(self):
+ return "FileSection(type:0x%X, size:0x%x)" % (self.get_type(), self.get_size())
+
+ def get_base(self):
+ return self.base
+
+ def get_type(self):
+ return struct.unpack("B", self.ec.getMemoryService().read(self.base + 0x3, 1, 8))[0]
+
+ def get_size(self):
+ return (struct.unpack("<I", self.ec.getMemoryService().read(self.base, 4, 32))[0] & 0x00ffffff)
+
+ def get_debug_filepath(self):
+ type = self.get_type()
+ if type == EfiFileSection.EFI_SECTION_TE:
+ section = EfiSectionTE(self, ec, self.base + 0x4)
+ elif type == EfiFileSection.EFI_SECTION_PE32:
+ section = EfiSectionPE32(self, ec, self.base + 0x4)
+ else:
+ raise Exception("EfiFileSection", "No debug section")
+ return section.get_debug_filepath()
+
+class EfiSectionTE:
+ SIZEOF_EFI_TE_IMAGE_HEADER = 0x28
+ EFI_TE_IMAGE_SIGNATURE = ('V','Z')
+
+ def __init__(self, ec, base_te):
+ self.ec = ec
+ self.base_te = int(base_te)
+ te_sig = struct.unpack("cc", self.ec.getMemoryService().read(self.base_te, 2, 32))
+ if te_sig != EfiSectionTE.EFI_TE_IMAGE_SIGNATURE:
+ raise Exception("EfiFileSectionTE","TE Signature incorrect")
+
+ def get_debug_filepath(self):
+ stripped_size = struct.unpack("<H", self.ec.getMemoryService().read(self.base_te + 0x6, 2, 32))[0]
+ stripped_size -= EfiSectionTE.SIZEOF_EFI_TE_IMAGE_HEADER
+
+ debug_dir_entry_rva = self.ec.getMemoryService().readMemory32(self.base_te + 0x20)
+ if debug_dir_entry_rva == 0:
+ raise Exception("EfiFileSectionTE","No debug directory for image")
+ debug_dir_entry_rva -= stripped_size
+
+ debug_type = self.ec.getMemoryService().readMemory32(self.base_te + debug_dir_entry_rva + 0xC)
+ if (debug_type != 0xdf) and (debug_type != EfiFileSection.EFI_IMAGE_DEBUG_TYPE_CODEVIEW):
+ raise Exception("EfiFileSectionTE","Debug type is not dwarf")
+
+ debug_rva = self.ec.getMemoryService().readMemory32(self.base_te + debug_dir_entry_rva + 0x14)
+ debug_rva -= stripped_size
+
+ dwarf_sig = struct.unpack("cccc", self.ec.getMemoryService().read(self.base_te + debug_rva, 4, 32))
+ if (dwarf_sig != 0x66727764) and (dwarf_sig != FirmwareFile.CONST_NB10_SIGNATURE):
+ raise Exception("EfiFileSectionTE","Dwarf debug signature not found")
+
+ if dwarf_sig == 0x66727764:
+ filename = self.base_te + debug_rva + 0xc
+ else:
+ filename = self.base_te + debug_rva + 0x10
+ filename = struct.unpack("200s", self.ec.getMemoryService().read(filename, 200, 32))[0]
+ return filename[0:string.find(filename,'\0')]
+
+ def get_debug_elfbase(self):
+ stripped_size = struct.unpack("<H", self.ec.getMemoryService().read(self.base_te + 0x6, 2, 32))[0]
+ stripped_size -= EfiSectionTE.SIZEOF_EFI_TE_IMAGE_HEADER
+
+ base_of_code = self.ec.getMemoryService().readMemory32(self.base_te + 0xC)
+
+ return self.base_te + base_of_code - stripped_size
+
+class EfiSectionPE32:
+ def __init__(self, ec, base_pe32):
+ self.ec = ec
+ self.base_pe32 = base_pe32
+
+ def get_debug_filepath(self):
+ # Offset from dos hdr to PE file hdr
+ file_header_offset = self.ec.getMemoryService().readMemory32(self.base_pe32 + 0x3C)
+
+ # Offset to debug dir in PE hdrs
+ debug_dir_entry_rva = self.ec.getMemoryService().readMemory32(self.base_pe32 + file_header_offset + 0xA8)
+ if debug_dir_entry_rva == 0:
+ raise Exception("EfiFileSectionPE32","No Debug Directory")
+
+ debug_type = self.ec.getMemoryService().readMemory32(self.base_pe32 + debug_dir_entry_rva + 0xC)
+ if (debug_type != 0xdf) and (debug_type != EfiFileSection.EFI_IMAGE_DEBUG_TYPE_CODEVIEW):
+ raise Exception("EfiFileSectionPE32","Debug type is not dwarf")
+
+
+ debug_rva = self.ec.getMemoryService().readMemory32(self.base_pe32 + debug_dir_entry_rva + 0x14)
+
+ dwarf_sig = struct.unpack("cccc", self.ec.getMemoryService().read(str(self.base_pe32 + debug_rva), 4, 32))
+ if (dwarf_sig != 0x66727764) and (dwarf_sig != FirmwareFile.CONST_NB10_SIGNATURE):
+ raise Exception("EfiFileSectionPE32","Dwarf debug signature not found")
+
+ if dwarf_sig == 0x66727764:
+ filename = self.base_pe32 + debug_rva + 0xc
+ else:
+ filename = self.base_pe32 + debug_rva + 0x10
+ filename = struct.unpack("200s", self.ec.getMemoryService().read(str(filename), 200, 32))[0]
+ return filename[0:string.find(filename,'\0')]
+
+ def get_debug_elfbase(self):
+ # Offset from dos hdr to PE file hdr
+ pe_file_header = self.base_pe32 + self.ec.getMemoryService().readMemory32(self.base_pe32 + 0x3C)
+
+ base_of_code = self.base_pe32 + self.ec.getMemoryService().readMemory32(pe_file_header + 0x28)
+ base_of_data = self.base_pe32 + self.ec.getMemoryService().readMemory32(pe_file_header + 0x2C)
+
+ if (base_of_code < base_of_data) and (base_of_code != 0):
+ return base_of_code
+ else:
+ return base_of_data
+
+class FirmwareFile:
+ EFI_FV_FILETYPE_RAW = 0x01
+ EFI_FV_FILETYPE_FREEFORM = 0x02
+ EFI_FV_FILETYPE_SECURITY_CORE = 0x03
+ EFI_FV_FILETYPE_PEI_CORE = 0x04
+ EFI_FV_FILETYPE_DXE_CORE = 0x05
+ EFI_FV_FILETYPE_PEIM = 0x06
+ EFI_FV_FILETYPE_DRIVER = 0x07
+ EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER = 0x08
+ EFI_FV_FILETYPE_APPLICATION = 0x09
+ EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE = 0x0B
+ EFI_FV_FILETYPE_FFS_MIN = 0xF0
+
+ CONST_NB10_SIGNATURE = ('N','B','1','0')
+
+ def __init__(self, fv, base, ec):
+ self.fv = fv
+ self.base = base
+ self.ec = ec
+
+ def __str__(self):
+ return "FFS(state:0x%x, type:0x%X, size:0x%x)" % (self.get_state(), self.get_type(), self.get_size())
+
+ def get_base(self):
+ return self.base
+
+ def get_size(self):
+ size = (self.ec.getMemoryService().readMemory32(self.base + 0x14) & 0x00ffffff)
+
+ # Occupied size is the size considering the alignment
+ return size + ((0x8 - (size & 0x7)) & 0x7)
+
+ def get_type(self):
+ return self.ec.getMemoryService().readMemory8(self.base + 0x12)
+
+ def get_state(self):
+ state = self.ec.getMemoryService().readMemory8(self.base + 0x17)
+
+ polarity = self.fv.get_polarity()
+ if polarity:
+ state = ~state
+
+ highest_bit = 0x80;
+ while (highest_bit != 0) and ((highest_bit & state) == 0):
+ highest_bit >>= 1
+
+ return highest_bit
+
+ def get_next_section(self, section=None):
+ if section == None:
+ if self.get_type() != FirmwareFile.EFI_FV_FILETYPE_FFS_MIN:
+ section_base = self.get_base() + 0x18;
+ else:
+ return None
+ else:
+ section_base = int(section.get_base() + section.get_size())
+
+ # Align to next 4 byte boundary
+ if (section_base & 0x3) != 0:
+ section_base = section_base + 0x4 - (section_base & 0x3)
+
+ if section_base < self.get_base() + self.get_size():
+ return EfiFileSection(self.ec, section_base)
+ else:
+ return None
+
+class FirmwareVolume:
+ CONST_FV_SIGNATURE = ('_','F','V','H')
+ EFI_FVB2_ERASE_POLARITY = 0x800
+
+ DebugInfos = []
+
+ def __init__(self, ec, fv_base, fv_size):
+ self.ec = ec
+ self.fv_base = fv_base
+ self.fv_size = fv_size
+
+ try:
+ signature = struct.unpack("cccc", self.ec.getMemoryService().read(fv_base + 0x28, 4, 32))
+ except DebugException:
+ raise Exception("FirmwareVolume", "Not possible to access the defined firmware volume at [0x%X,0x%X]. Could be the used build report does not correspond to your current debugging context." % (int(fv_base),int(fv_base+fv_size)))
+ if signature != FirmwareVolume.CONST_FV_SIGNATURE:
+ raise Exception("FirmwareVolume", "This is not a valid firmware volume")
+
+ def get_size(self):
+ return self.ec.getMemoryService().readMemory32(self.fv_base + 0x20)
+
+ def get_attributes(self):
+ return self.ec.getMemoryService().readMemory32(self.fv_base + 0x2C)
+
+ def get_polarity(self):
+ attributes = self.get_attributes()
+ if attributes & FirmwareVolume.EFI_FVB2_ERASE_POLARITY:
+ return 1
+ else:
+ return 0
+
+ def get_next_ffs(self, ffs=None):
+ if ffs == None:
+ # Get the offset of the first FFS file from the FV header
+ ffs_base = self.fv_base + self.ec.getMemoryService().readMemory16(self.fv_base + 0x30)
+ else:
+ # Goto the next FFS file
+ ffs_base = int(ffs.get_base() + ffs.get_size())
+
+ # Align to next 8 byte boundary
+ if (ffs_base & 0x7) != 0:
+ ffs_base = ffs_base + 0x8 - (ffs_base & 0x7)
+
+ if ffs_base < self.fv_base + self.get_size():
+ return FirmwareFile(self, ffs_base, self.ec)
+ else:
+ return None
+
+ def get_debug_info(self):
+ self.DebugInfos = []
+
+ ffs = self.get_next_ffs()
+ while ffs != None:
+ section = ffs.get_next_section()
+ while section != None:
+ type = section.get_type()
+ if (type == EfiFileSection.EFI_SECTION_TE) or (type == EfiFileSection.EFI_SECTION_PE32):
+ self.DebugInfos.append((section.get_base(), section.get_size(), section.get_type()))
+ section = ffs.get_next_section(section)
+ ffs = self.get_next_ffs(ffs)
+
+ def load_symbols_at(self, addr, verbose = False):
+ if self.DebugInfos == []:
+ self.get_debug_info()
+
+ for debug_info in self.DebugInfos:
+ if (addr >= debug_info[0]) and (addr < debug_info[0] + debug_info[1]):
+ if debug_info[2] == EfiFileSection.EFI_SECTION_TE:
+ section = EfiSectionTE(self.ec, debug_info[0] + 0x4)
+ elif debug_info[2] == EfiFileSection.EFI_SECTION_PE32:
+ section = EfiSectionPE32(self.ec, debug_info[0] + 0x4)
+ else:
+ raise Exception('FirmwareVolume','Section Type not supported')
+
+ try:
+ edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase(), verbose)
+ except Exception, (ErrorClass, ErrorMessage):
+ if verbose:
+ print "Error while loading a symbol file (%s: %s)" % (ErrorClass, ErrorMessage)
+ pass
+
+ return debug_info
+
+ def load_all_symbols(self, verbose = False):
+ if self.DebugInfos == []:
+ self.get_debug_info()
+
+ for debug_info in self.DebugInfos:
+ if debug_info[2] == EfiFileSection.EFI_SECTION_TE:
+ section = EfiSectionTE(self.ec, debug_info[0] + 0x4)
+ elif debug_info[2] == EfiFileSection.EFI_SECTION_PE32:
+ section = EfiSectionPE32(self.ec, debug_info[0] + 0x4)
+ else:
+ continue
+
+ try:
+ edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase(), verbose)
+ except Exception, (ErrorClass, ErrorMessage):
+ if verbose:
+ print "Error while loading a symbol file (%s: %s)" % (ErrorClass, ErrorMessage)
+ pass
+
diff --git a/ArmPlatformPkg/Scripts/Ds5/system_table.py b/ArmPlatformPkg/Scripts/Ds5/system_table.py
index f489e466a..3e7f6ab01 100644
--- a/ArmPlatformPkg/Scripts/Ds5/system_table.py
+++ b/ArmPlatformPkg/Scripts/Ds5/system_table.py
@@ -1,129 +1,139 @@
-#
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-from arm_ds.debugger_v1 import DebugException
-
-import struct
-
-import edk2_debugger
-import firmware_volume
-
-class DebugInfoTable:
- CONST_DEBUG_INFO_TABLE_GUID = ( 0x49152E77L, 0x47641ADAL, 0xFE7AA2B7L, 0x8B5ED9FEL)
-
- DebugInfos = []
-
- def __init__(self, ec, debug_info_table_header_offset):
- self.ec = ec
- self.base = debug_info_table_header_offset
-
- def get_debug_info(self):
- count = self.ec.getMemoryService().readMemory32(self.base + 0x4)
- debug_info_table_base = self.ec.getMemoryService().readMemory32(self.base + 0x8)
-
- self.DebugInfos = []
-
- for i in range(0, count):
- # Get the address of the structure EFI_DEBUG_IMAGE_INFO
- debug_info = self.ec.getMemoryService().readMemory32(debug_info_table_base + (i * 4))
- if debug_info:
- debug_info_type = self.ec.getMemoryService().readMemory32(debug_info)
- # Normal Debug Info Type
- if debug_info_type == 1:
- # Get the base address of the structure EFI_LOADED_IMAGE_PROTOCOL
- loaded_image_protocol = self.ec.getMemoryService().readMemory32(debug_info + 0x4)
-
- image_base = self.ec.getMemoryService().readMemory32(loaded_image_protocol + 0x20)
- image_size = self.ec.getMemoryService().readMemory32(loaded_image_protocol + 0x28)
-
- self.DebugInfos.append((image_base,image_size))
-
- # Return (base, size)
- def load_symbols_at(self, addr):
- if self.DebugInfos == []:
- self.get_debug_info()
-
- found = False
- for debug_info in self.DebugInfos:
- if (addr >= debug_info[0]) and (addr < debug_info[0] + debug_info[1]):
- section = firmware_volume.EfiSectionPE32(self.ec, debug_info[0])
-
- edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase())
-
- found = True
- return debug_info
-
- if found == False:
- raise Exception('DebugInfoTable','No symbol found at 0x%x' % addr)
-
- def load_all_symbols(self):
- if self.DebugInfos == []:
- self.get_debug_info()
-
- for debug_info in self.DebugInfos:
- section = firmware_volume.EfiSectionPE32(self.ec, debug_info[0])
-
- edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase())
-
- def dump(self):
- self.get_debug_info()
- for debug_info in self.DebugInfos:
- base_pe32 = debug_info[0]
- section = firmware_volume.EfiSectionPE32(self.ec, base_pe32)
- print section.get_debug_filepath()
-
-class SystemTable:
- CONST_ST_SIGNATURE = ('I','B','I',' ','S','Y','S','T')
-
- def __init__(self, ec, membase, memsize):
- self.membase = membase
- self.memsize = memsize
- self.ec = ec
-
- found = False
-
- # Start from the top of the memory
- offset = self.membase + self.memsize
- # Align to highest 4MB boundary
- offset = offset & ~0x3FFFFF
- # We should not have a System Table at the top of the System Memory
- offset = offset - 0x400000
-
- # Start at top and look on 4MB boundaries for system table ptr structure
- while offset > self.membase:
- try:
- signature = struct.unpack("cccccccc", self.ec.getMemoryService().read(str(offset), 8, 32))
- except DebugException:
- raise Exception('SystemTable','Fail to access System Memory. Ensure all the memory in the region [0x%x;0x%X] is accessible.' % (membase,membase+memsize))
- if signature == SystemTable.CONST_ST_SIGNATURE:
- found = True
- self.system_table_base = self.ec.getMemoryService().readMemory32(offset + 0x8)
- break
- offset = offset - 0x400000
-
- if not found:
- raise Exception('SystemTable','System Table not found in System Memory [0x%x;0x%X]' % (membase,membase+memsize))
-
- def get_configuration_table(self, conf_table_guid):
- # Number of configuration Table entry
- conf_table_entry_count = self.ec.getMemoryService().readMemory32(self.system_table_base + 0x40)
-
- # Get location of the Configuration Table entries
- conf_table_offset = self.ec.getMemoryService().readMemory32(self.system_table_base + 0x44)
-
- for i in range(0, conf_table_entry_count):
- offset = conf_table_offset + (i * 0x14)
- guid = struct.unpack("<IIII", self.ec.getMemoryService().read(str(offset), 16, 32))
- if guid == conf_table_guid:
- return self.ec.getMemoryService().readMemory32(offset + 0x10)
-
- raise Exception('SystemTable','Configuration Table not found')
+#
+# Copyright (c) 2011-2013, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+from arm_ds.debugger_v1 import DebugException
+
+import struct
+
+import edk2_debugger
+import firmware_volume
+
+class DebugInfoTable:
+ CONST_DEBUG_INFO_TABLE_GUID = ( 0x49152E77L, 0x47641ADAL, 0xFE7AA2B7L, 0x8B5ED9FEL)
+
+ DebugInfos = []
+
+ def __init__(self, ec, debug_info_table_header_offset):
+ self.ec = ec
+ self.base = debug_info_table_header_offset
+
+ def get_debug_info(self):
+ count = self.ec.getMemoryService().readMemory32(self.base + 0x4)
+ debug_info_table_base = self.ec.getMemoryService().readMemory32(self.base + 0x8)
+
+ self.DebugInfos = []
+
+ for i in range(0, count):
+ # Get the address of the structure EFI_DEBUG_IMAGE_INFO
+ debug_info = self.ec.getMemoryService().readMemory32(debug_info_table_base + (i * 4))
+ if debug_info:
+ debug_info_type = self.ec.getMemoryService().readMemory32(debug_info)
+ # Normal Debug Info Type
+ if debug_info_type == 1:
+ # Get the base address of the structure EFI_LOADED_IMAGE_PROTOCOL
+ loaded_image_protocol = self.ec.getMemoryService().readMemory32(debug_info + 0x4)
+
+ image_base = self.ec.getMemoryService().readMemory32(loaded_image_protocol + 0x20)
+ image_size = self.ec.getMemoryService().readMemory32(loaded_image_protocol + 0x28)
+
+ self.DebugInfos.append((image_base,image_size))
+
+ # Return (base, size)
+ def load_symbols_at(self, addr, verbose = False):
+ if self.DebugInfos == []:
+ self.get_debug_info()
+
+ found = False
+ for debug_info in self.DebugInfos:
+ if (addr >= debug_info[0]) and (addr < debug_info[0] + debug_info[1]):
+ section = firmware_volume.EfiSectionPE32(self.ec, debug_info[0])
+
+ try:
+ edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase(), verbose)
+ except Exception, (ErrorClass, ErrorMessage):
+ if verbose:
+ print "Error while loading a symbol file (%s: %s)" % (ErrorClass, ErrorMessage)
+ pass
+
+ found = True
+ return debug_info
+
+ if found == False:
+ raise Exception('DebugInfoTable','No symbol found at 0x%x' % addr)
+
+ def load_all_symbols(self, verbose = False):
+ if self.DebugInfos == []:
+ self.get_debug_info()
+
+ for debug_info in self.DebugInfos:
+ section = firmware_volume.EfiSectionPE32(self.ec, debug_info[0])
+
+ try:
+ edk2_debugger.load_symbol_from_file(self.ec, section.get_debug_filepath(), section.get_debug_elfbase(), verbose)
+ except Exception, (ErrorClass, ErrorMessage):
+ if verbose:
+ print "Error while loading a symbol file (%s: %s)" % (ErrorClass, ErrorMessage)
+ pass
+
+ def dump(self):
+ self.get_debug_info()
+ for debug_info in self.DebugInfos:
+ base_pe32 = debug_info[0]
+ section = firmware_volume.EfiSectionPE32(self.ec, base_pe32)
+ print section.get_debug_filepath()
+
+class SystemTable:
+ CONST_ST_SIGNATURE = ('I','B','I',' ','S','Y','S','T')
+
+ def __init__(self, ec, membase, memsize):
+ self.membase = membase
+ self.memsize = memsize
+ self.ec = ec
+
+ found = False
+
+ # Start from the top of the memory
+ offset = self.membase + self.memsize
+ # Align to highest 4MB boundary
+ offset = offset & ~0x3FFFFF
+ # We should not have a System Table at the top of the System Memory
+ offset = offset - 0x400000
+
+ # Start at top and look on 4MB boundaries for system table ptr structure
+ while offset > self.membase:
+ try:
+ signature = struct.unpack("cccccccc", self.ec.getMemoryService().read(str(offset), 8, 32))
+ except DebugException:
+ raise Exception('SystemTable','Fail to access System Memory. Ensure all the memory in the region [0x%x;0x%X] is accessible.' % (membase,membase+memsize))
+ if signature == SystemTable.CONST_ST_SIGNATURE:
+ found = True
+ self.system_table_base = self.ec.getMemoryService().readMemory32(offset + 0x8)
+ break
+ offset = offset - 0x400000
+
+ if not found:
+ raise Exception('SystemTable','System Table not found in System Memory [0x%x;0x%X]' % (membase,membase+memsize))
+
+ def get_configuration_table(self, conf_table_guid):
+ # Number of configuration Table entry
+ conf_table_entry_count = self.ec.getMemoryService().readMemory32(self.system_table_base + 0x40)
+
+ # Get location of the Configuration Table entries
+ conf_table_offset = self.ec.getMemoryService().readMemory32(self.system_table_base + 0x44)
+
+ for i in range(0, conf_table_entry_count):
+ offset = conf_table_offset + (i * 0x14)
+ guid = struct.unpack("<IIII", self.ec.getMemoryService().read(str(offset), 16, 32))
+ if guid == conf_table_guid:
+ return self.ec.getMemoryService().readMemory32(offset + 0x10)
+
+ raise Exception('SystemTable','Configuration Table not found')
diff --git a/ArmPlatformPkg/Sec/Sec.c b/ArmPlatformPkg/Sec/Sec.c
index 55807ec9d..be165442b 100644
--- a/ArmPlatformPkg/Sec/Sec.c
+++ b/ArmPlatformPkg/Sec/Sec.c
@@ -1,195 +1,195 @@
-/** @file
-* Main file supporting the SEC Phase on ARM Platforms
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/ArmTrustedMonitorLib.h>
-#include <Library/DebugAgentLib.h>
-#include <Library/PrintLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/SerialPortLib.h>
-#include <Library/ArmGicLib.h>
-
-#include "SecInternal.h"
-
-#define SerialPrint(txt) SerialPortWrite ((UINT8*)txt, AsciiStrLen(txt)+1);
-
-VOID
-CEntryPoint (
- IN UINTN MpId,
- IN UINTN SecBootMode
- )
-{
- CHAR8 Buffer[100];
- UINTN CharCount;
- UINTN JumpAddress;
-
- // Invalidate the data cache. Doesn't have to do the Data cache clean.
- ArmInvalidateDataCache();
-
- // Invalidate Instruction Cache
- ArmInvalidateInstructionCache();
-
- // Invalidate I & D TLBs
- ArmInvalidateInstructionAndDataTlb();
-
- // CPU specific settings
- ArmCpuSetup (MpId);
-
- // Enable Floating Point Coprocessor if supported by the platform
- if (FixedPcdGet32 (PcdVFPEnabled)) {
- ArmEnableVFP();
- }
-
- // Initialize peripherals that must be done at the early stage
- // Example: Some L2 controller, interconnect, clock, DMC, etc
- ArmPlatformSecInitialize (MpId);
-
- // Primary CPU clears out the SCU tag RAMs, secondaries wait
- if (IS_PRIMARY_CORE(MpId) && (SecBootMode == ARM_SEC_COLD_BOOT)) {
- if (ArmIsMpCore()) {
- // Signal for the initial memory is configured (event: BOOT_MEM_INIT)
- ArmCallSEV ();
- }
-
- // SEC phase needs to run library constructors by hand. This assumes we are linked against the SerialLib
- // In non SEC modules the init call is in autogenerated code.
- SerialPortInitialize ();
-
- // Start talking
- if (FixedPcdGetBool (PcdTrustzoneSupport)) {
- CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Secure firmware (version %s built at %a on %a)\n\r",
- (CHAR16*)PcdGetPtr(PcdFirmwareVersionString), __TIME__, __DATE__);
- } else {
- CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Boot firmware (version %s built at %a on %a)\n\r",
- (CHAR16*)PcdGetPtr(PcdFirmwareVersionString), __TIME__, __DATE__);
- }
- SerialPortWrite ((UINT8 *) Buffer, CharCount);
-
- // Initialize the Debug Agent for Source Level Debugging
- InitializeDebugAgent (DEBUG_AGENT_INIT_PREMEM_SEC, NULL, NULL);
- SaveAndSetDebugTimerInterrupt (TRUE);
-
- // Enable the GIC distributor and CPU Interface
- // - no other Interrupts are enabled, doesn't have to worry about the priority.
- // - all the cores are in secure state, use secure SGI's
- ArmGicEnableDistributor (PcdGet32(PcdGicDistributorBase));
- ArmGicEnableInterruptInterface (PcdGet32(PcdGicInterruptInterfaceBase));
- } else {
- // Enable the GIC CPU Interface
- ArmGicEnableInterruptInterface (PcdGet32(PcdGicInterruptInterfaceBase));
- }
-
- // Enable Full Access to CoProcessors
- ArmWriteCpacr (CPACR_CP_FULL_ACCESS);
-
- // Test if Trustzone is supported on this platform
- if (FixedPcdGetBool (PcdTrustzoneSupport)) {
- if (ArmIsMpCore()) {
- // Setup SMP in Non Secure world
- ArmCpuSetupSmpNonSecure (GET_CORE_ID(MpId));
- }
-
- // Either we use the Secure Stacks for Secure Monitor (in this case (Base == 0) && (Size == 0))
- // Or we use separate Secure Monitor stacks (but (Base != 0) && (Size != 0))
- ASSERT (((PcdGet32(PcdCPUCoresSecMonStackBase) == 0) && (PcdGet32(PcdCPUCoreSecMonStackSize) == 0)) ||
- ((PcdGet32(PcdCPUCoresSecMonStackBase) != 0) && (PcdGet32(PcdCPUCoreSecMonStackSize) != 0)));
-
- // Enter Monitor Mode
- enter_monitor_mode ((UINTN)TrustedWorldInitialization, MpId, SecBootMode, (VOID*)(PcdGet32(PcdCPUCoresSecMonStackBase) + (PcdGet32(PcdCPUCoreSecMonStackSize) * (GET_CORE_POS(MpId) + 1))));
- } else {
- if (IS_PRIMARY_CORE(MpId)) {
- SerialPrint ("Trust Zone Configuration is disabled\n\r");
- }
-
- // With Trustzone support the transition from Sec to Normal world is done by return_from_exception().
- // If we want to keep this function call we need to ensure the SVC's SPSR point to the same Program
- // Status Register as the the current one (CPSR).
- copy_cpsr_into_spsr ();
-
- // Call the Platform specific function to execute additional actions if required
- JumpAddress = PcdGet32 (PcdFvBaseAddress);
- ArmPlatformSecExtraAction (MpId, &JumpAddress);
-
- NonTrustedWorldTransition (MpId, JumpAddress);
- }
- ASSERT (0); // We must never return from the above function
-}
-
-VOID
-TrustedWorldInitialization (
- IN UINTN MpId,
- IN UINTN SecBootMode
- )
-{
- UINTN JumpAddress;
-
- //-------------------- Monitor Mode ---------------------
-
- // Set up Monitor World (Vector Table, etc)
- ArmSecureMonitorWorldInitialize ();
-
- // Transfer the interrupt to Non-secure World
- ArmGicSetupNonSecure (MpId, PcdGet32(PcdGicDistributorBase), PcdGet32(PcdGicInterruptInterfaceBase));
-
- // Initialize platform specific security policy
- ArmPlatformSecTrustzoneInit (MpId);
-
- // Setup the Trustzone Chipsets
- if (SecBootMode == ARM_SEC_COLD_BOOT) {
- if (IS_PRIMARY_CORE(MpId)) {
- if (ArmIsMpCore()) {
- // Signal the secondary core the Security settings is done (event: EVENT_SECURE_INIT)
- ArmCallSEV ();
- }
- } else {
- // The secondary cores need to wait until the Trustzone chipsets configuration is done
- // before switching to Non Secure World
-
- // Wait for the Primary Core to finish the initialization of the Secure World (event: EVENT_SECURE_INIT)
- ArmCallWFE ();
- }
- }
-
- // Call the Platform specific function to execute additional actions if required
- JumpAddress = PcdGet32 (PcdFvBaseAddress);
- ArmPlatformSecExtraAction (MpId, &JumpAddress);
-
- // Write to CP15 Non-secure Access Control Register
- ArmWriteNsacr (PcdGet32 (PcdArmNsacr));
-
- // CP15 Secure Configuration Register
- ArmWriteScr (PcdGet32 (PcdArmScr));
-
- NonTrustedWorldTransition (MpId, JumpAddress);
-}
-
-VOID
-NonTrustedWorldTransition (
- IN UINTN MpId,
- IN UINTN JumpAddress
- )
-{
- // If PcdArmNonSecModeTransition is defined then set this specific mode to CPSR before the transition
- // By not set, the mode for Non Secure World is SVC
- if (PcdGet32 (PcdArmNonSecModeTransition) != 0) {
- set_non_secure_mode ((ARM_PROCESSOR_MODE)PcdGet32 (PcdArmNonSecModeTransition));
- }
-
- return_from_exception (JumpAddress);
- //-------------------- Non Secure Mode ---------------------
-
- // PEI Core should always load and never return
- ASSERT (FALSE);
-}
-
+/** @file
+* Main file supporting the SEC Phase on ARM Platforms
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/ArmTrustedMonitorLib.h>
+#include <Library/DebugAgentLib.h>
+#include <Library/PrintLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/SerialPortLib.h>
+#include <Library/ArmGicLib.h>
+
+#include "SecInternal.h"
+
+#define SerialPrint(txt) SerialPortWrite ((UINT8*)txt, AsciiStrLen(txt)+1);
+
+VOID
+CEntryPoint (
+ IN UINTN MpId,
+ IN UINTN SecBootMode
+ )
+{
+ CHAR8 Buffer[100];
+ UINTN CharCount;
+ UINTN JumpAddress;
+
+ // Invalidate the data cache. Doesn't have to do the Data cache clean.
+ ArmInvalidateDataCache();
+
+ // Invalidate Instruction Cache
+ ArmInvalidateInstructionCache();
+
+ // Invalidate I & D TLBs
+ ArmInvalidateInstructionAndDataTlb();
+
+ // CPU specific settings
+ ArmCpuSetup (MpId);
+
+ // Enable Floating Point Coprocessor if supported by the platform
+ if (FixedPcdGet32 (PcdVFPEnabled)) {
+ ArmEnableVFP();
+ }
+
+ // Initialize peripherals that must be done at the early stage
+ // Example: Some L2 controller, interconnect, clock, DMC, etc
+ ArmPlatformSecInitialize (MpId);
+
+ // Primary CPU clears out the SCU tag RAMs, secondaries wait
+ if (IS_PRIMARY_CORE(MpId) && (SecBootMode == ARM_SEC_COLD_BOOT)) {
+ if (ArmIsMpCore()) {
+ // Signal for the initial memory is configured (event: BOOT_MEM_INIT)
+ ArmCallSEV ();
+ }
+
+ // SEC phase needs to run library constructors by hand. This assumes we are linked against the SerialLib
+ // In non SEC modules the init call is in autogenerated code.
+ SerialPortInitialize ();
+
+ // Start talking
+ if (FixedPcdGetBool (PcdTrustzoneSupport)) {
+ CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Secure firmware (version %s built at %a on %a)\n\r",
+ (CHAR16*)PcdGetPtr(PcdFirmwareVersionString), __TIME__, __DATE__);
+ } else {
+ CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Boot firmware (version %s built at %a on %a)\n\r",
+ (CHAR16*)PcdGetPtr(PcdFirmwareVersionString), __TIME__, __DATE__);
+ }
+ SerialPortWrite ((UINT8 *) Buffer, CharCount);
+
+ // Initialize the Debug Agent for Source Level Debugging
+ InitializeDebugAgent (DEBUG_AGENT_INIT_PREMEM_SEC, NULL, NULL);
+ SaveAndSetDebugTimerInterrupt (TRUE);
+
+ // Enable the GIC distributor and CPU Interface
+ // - no other Interrupts are enabled, doesn't have to worry about the priority.
+ // - all the cores are in secure state, use secure SGI's
+ ArmGicEnableDistributor (PcdGet32(PcdGicDistributorBase));
+ ArmGicEnableInterruptInterface (PcdGet32(PcdGicInterruptInterfaceBase));
+ } else {
+ // Enable the GIC CPU Interface
+ ArmGicEnableInterruptInterface (PcdGet32(PcdGicInterruptInterfaceBase));
+ }
+
+ // Enable Full Access to CoProcessors
+ ArmWriteCpacr (CPACR_CP_FULL_ACCESS);
+
+ // Test if Trustzone is supported on this platform
+ if (FixedPcdGetBool (PcdTrustzoneSupport)) {
+ if (ArmIsMpCore()) {
+ // Setup SMP in Non Secure world
+ ArmCpuSetupSmpNonSecure (GET_CORE_ID(MpId));
+ }
+
+ // Either we use the Secure Stacks for Secure Monitor (in this case (Base == 0) && (Size == 0))
+ // Or we use separate Secure Monitor stacks (but (Base != 0) && (Size != 0))
+ ASSERT (((PcdGet32(PcdCPUCoresSecMonStackBase) == 0) && (PcdGet32(PcdCPUCoreSecMonStackSize) == 0)) ||
+ ((PcdGet32(PcdCPUCoresSecMonStackBase) != 0) && (PcdGet32(PcdCPUCoreSecMonStackSize) != 0)));
+
+ // Enter Monitor Mode
+ enter_monitor_mode ((UINTN)TrustedWorldInitialization, MpId, SecBootMode, (VOID*)(PcdGet32(PcdCPUCoresSecMonStackBase) + (PcdGet32(PcdCPUCoreSecMonStackSize) * (GET_CORE_POS(MpId) + 1))));
+ } else {
+ if (IS_PRIMARY_CORE(MpId)) {
+ SerialPrint ("Trust Zone Configuration is disabled\n\r");
+ }
+
+ // With Trustzone support the transition from Sec to Normal world is done by return_from_exception().
+ // If we want to keep this function call we need to ensure the SVC's SPSR point to the same Program
+ // Status Register as the the current one (CPSR).
+ copy_cpsr_into_spsr ();
+
+ // Call the Platform specific function to execute additional actions if required
+ JumpAddress = PcdGet32 (PcdFvBaseAddress);
+ ArmPlatformSecExtraAction (MpId, &JumpAddress);
+
+ NonTrustedWorldTransition (MpId, JumpAddress);
+ }
+ ASSERT (0); // We must never return from the above function
+}
+
+VOID
+TrustedWorldInitialization (
+ IN UINTN MpId,
+ IN UINTN SecBootMode
+ )
+{
+ UINTN JumpAddress;
+
+ //-------------------- Monitor Mode ---------------------
+
+ // Set up Monitor World (Vector Table, etc)
+ ArmSecureMonitorWorldInitialize ();
+
+ // Transfer the interrupt to Non-secure World
+ ArmGicSetupNonSecure (MpId, PcdGet32(PcdGicDistributorBase), PcdGet32(PcdGicInterruptInterfaceBase));
+
+ // Initialize platform specific security policy
+ ArmPlatformSecTrustzoneInit (MpId);
+
+ // Setup the Trustzone Chipsets
+ if (SecBootMode == ARM_SEC_COLD_BOOT) {
+ if (IS_PRIMARY_CORE(MpId)) {
+ if (ArmIsMpCore()) {
+ // Signal the secondary core the Security settings is done (event: EVENT_SECURE_INIT)
+ ArmCallSEV ();
+ }
+ } else {
+ // The secondary cores need to wait until the Trustzone chipsets configuration is done
+ // before switching to Non Secure World
+
+ // Wait for the Primary Core to finish the initialization of the Secure World (event: EVENT_SECURE_INIT)
+ ArmCallWFE ();
+ }
+ }
+
+ // Call the Platform specific function to execute additional actions if required
+ JumpAddress = PcdGet32 (PcdFvBaseAddress);
+ ArmPlatformSecExtraAction (MpId, &JumpAddress);
+
+ // Write to CP15 Non-secure Access Control Register
+ ArmWriteNsacr (PcdGet32 (PcdArmNsacr));
+
+ // CP15 Secure Configuration Register
+ ArmWriteScr (PcdGet32 (PcdArmScr));
+
+ NonTrustedWorldTransition (MpId, JumpAddress);
+}
+
+VOID
+NonTrustedWorldTransition (
+ IN UINTN MpId,
+ IN UINTN JumpAddress
+ )
+{
+ // If PcdArmNonSecModeTransition is defined then set this specific mode to CPSR before the transition
+ // By not set, the mode for Non Secure World is SVC
+ if (PcdGet32 (PcdArmNonSecModeTransition) != 0) {
+ set_non_secure_mode ((ARM_PROCESSOR_MODE)PcdGet32 (PcdArmNonSecModeTransition));
+ }
+
+ return_from_exception (JumpAddress);
+ //-------------------- Non Secure Mode ---------------------
+
+ // PEI Core should always load and never return
+ ASSERT (FALSE);
+}
+
diff --git a/ArmPlatformPkg/Sec/SecInternal.h b/ArmPlatformPkg/Sec/SecInternal.h
index 8bc21389e..eeaf40c0c 100644
--- a/ArmPlatformPkg/Sec/SecInternal.h
+++ b/ArmPlatformPkg/Sec/SecInternal.h
@@ -1,7 +1,7 @@
/** @file
* Main file supporting the SEC Phase on ARM PLatforms
*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+* Copyright (c) 2011-2013, ARM Limited. All rights reserved.
*
* This program and the accompanying materials
* are licensed and made available under the terms and conditions of the BSD License
@@ -70,7 +70,7 @@ set_non_secure_mode (
VOID
SecCommonExceptionEntry (
IN UINT32 Entry,
- IN UINT32 LR
+ IN UINTN LR
);
#endif
diff --git a/BaseTools/Source/C/VfrCompile/VfrError.cpp b/BaseTools/Source/C/VfrCompile/VfrError.cpp
index b0f9197e3..ba1bec06e 100644
--- a/BaseTools/Source/C/VfrCompile/VfrError.cpp
+++ b/BaseTools/Source/C/VfrCompile/VfrError.cpp
@@ -2,7 +2,7 @@
VfrCompiler error handler.
-Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -45,6 +45,7 @@ static SVFR_ERROR_HANDLE VFR_ERROR_HANDLE_TABLE [] = {
{ VFR_RETURN_DATA_STRING_ERROR, ": data field string error or not support"},
{ VFR_RETURN_DEFAULT_VALUE_REDEFINED, ": default value re-defined with different value"},
{ VFR_RETURN_CONSTANT_ONLY, ": only constant is allowed in the expression"},
+ { VFR_RETURN_VARSTORE_NAME_REDEFINED_ERROR, ": Varstore name is defined by more than one varstores, it can't be referred as varstore, only varstore strucure name could be used."},
{ VFR_RETURN_CODEUNDEFINED, ": undefined Error Code" }
};
diff --git a/BaseTools/Source/C/VfrCompile/VfrError.h b/BaseTools/Source/C/VfrCompile/VfrError.h
index 258ae9b8a..4a4af172e 100644
--- a/BaseTools/Source/C/VfrCompile/VfrError.h
+++ b/BaseTools/Source/C/VfrCompile/VfrError.h
@@ -2,7 +2,7 @@
VfrCompiler Error definition
-Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -43,6 +43,7 @@ typedef enum {
VFR_RETURN_DATA_STRING_ERROR,
VFR_RETURN_DEFAULT_VALUE_REDEFINED,
VFR_RETURN_CONSTANT_ONLY,
+ VFR_RETURN_VARSTORE_NAME_REDEFINED_ERROR,
VFR_RETURN_CODEUNDEFINED
} EFI_VFR_RETURN_CODE;
diff --git a/BaseTools/Source/C/VfrCompile/VfrFormPkg.cpp b/BaseTools/Source/C/VfrCompile/VfrFormPkg.cpp
index 867f9cafd..8985ddefc 100644
--- a/BaseTools/Source/C/VfrCompile/VfrFormPkg.cpp
+++ b/BaseTools/Source/C/VfrCompile/VfrFormPkg.cpp
@@ -2,7 +2,7 @@
The definition of CFormPkg's member function
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -805,6 +805,7 @@ CFormPkg::DeclarePendingQuestion (
CHAR8 *NewStr;
EFI_VFR_RETURN_CODE ReturnCode;
EFI_VFR_VARSTORE_TYPE VarStoreType = EFI_VFR_VARSTORE_INVALID;
+ EFI_VARSTORE_ID VarStoreId = EFI_VARSTORE_ID_INVALID;
//
// Declare all questions as Numeric in DisableIf True
@@ -852,7 +853,7 @@ CFormPkg::DeclarePendingQuestion (
//
// Get VarStoreType
//
- ReturnCode = lCVfrDataStorage.GetVarStoreType (FName, VarStoreType);
+ ReturnCode = lCVfrDataStorage.GetVarStoreId (FName, &Info.mVarStoreId);
if (ReturnCode == VFR_RETURN_UNDEFINED) {
lCVfrDataStorage.DeclareBufferVarStore (
FName,
@@ -862,18 +863,13 @@ CFormPkg::DeclarePendingQuestion (
EFI_VARSTORE_ID_INVALID,
FALSE
);
- ReturnCode = lCVfrDataStorage.GetVarStoreType (FName, VarStoreType);
+ ReturnCode = lCVfrDataStorage.GetVarStoreId (FName, &Info.mVarStoreId, LocalFormSetGuid);
}
if (ReturnCode != VFR_RETURN_SUCCESS) {
gCVfrErrorHandle.PrintMsg (pNode->mLineNo, FName, "Error", "Var Store Type is not defined");
return ReturnCode;
}
-
- ReturnCode = lCVfrDataStorage.GetVarStoreId (FName, &Info.mVarStoreId);
- if (ReturnCode != VFR_RETURN_SUCCESS) {
- gCVfrErrorHandle.PrintMsg (pNode->mLineNo, FName, "Error", "Var Store Type is not defined");
- return ReturnCode;
- }
+ VarStoreType = lCVfrDataStorage.GetVarStoreType (Info.mVarStoreId);
if (*VarStr == '\0' && ArrayIdx != INVALID_ARRAY_INDEX) {
ReturnCode = lCVfrDataStorage.GetNameVarStoreInfo (&Info, ArrayIdx);
@@ -883,7 +879,7 @@ CFormPkg::DeclarePendingQuestion (
} else if (VarStoreType == EFI_VFR_VARSTORE_BUFFER) {
VarStr = pNode->mKey;
//convert VarStr with store name to VarStr with structure name
- ReturnCode = lCVfrDataStorage.GetBufferVarStoreDataTypeName (FName, &SName);
+ ReturnCode = lCVfrDataStorage.GetBufferVarStoreDataTypeName (Info.mVarStoreId, &SName);
if (ReturnCode == VFR_RETURN_SUCCESS) {
NewStr = new CHAR8[strlen (VarStr) + strlen (SName) + 1];
NewStr[0] = '\0';
diff --git a/BaseTools/Source/C/VfrCompile/VfrSyntax.g b/BaseTools/Source/C/VfrCompile/VfrSyntax.g
index 76d15790c..e6e69bca0 100644
--- a/BaseTools/Source/C/VfrCompile/VfrSyntax.g
+++ b/BaseTools/Source/C/VfrCompile/VfrSyntax.g
@@ -894,7 +894,7 @@ vfrStatementVarStoreLinear :
VarStoreId
), LineNum);
VSObj.SetGuid (&Guid);
- _PCATCH(mCVfrDataStorage.GetVarStoreId(StoreName, &VarStoreId), SN);
+ _PCATCH(mCVfrDataStorage.GetVarStoreId(StoreName, &VarStoreId, &Guid), SN);
VSObj.SetVarStoreId (VarStoreId);
_PCATCH(gCVfrVarDataTypeDB.GetDataTypeSize(TypeName, &Size), LineNum);
VSObj.SetSize ((UINT16) Size);
@@ -980,7 +980,7 @@ vfrStatementVarStoreEfi :
TypeName,
VarStoreId
), LineNum);
- _PCATCH(mCVfrDataStorage.GetVarStoreId(StoreName, &VarStoreId), SN);
+ _PCATCH(mCVfrDataStorage.GetVarStoreId(StoreName, &VarStoreId, &Guid), SN);
_PCATCH(gCVfrVarDataTypeDB.GetDataTypeSize(TypeName, &Size), LineNum);
} else {
_PCATCH(mCVfrDataStorage.DeclareBufferVarStore (
@@ -990,7 +990,7 @@ vfrStatementVarStoreEfi :
TypeName,
VarStoreId
), LineNum);
- _PCATCH(mCVfrDataStorage.GetVarStoreId(TN->getText(), &VarStoreId), VN);
+ _PCATCH(mCVfrDataStorage.GetVarStoreId(TN->getText(), &VarStoreId, &Guid), VN);
_PCATCH(gCVfrVarDataTypeDB.GetDataTypeSize(TypeName, &Size), N->getLine());
}
VSEObj.SetGuid (&Guid);
@@ -1023,7 +1023,7 @@ vfrStatementVarStoreNameValue :
Uuid "=" guidDefinition[Guid] << _PCATCH(mCVfrDataStorage.DeclareNameVarStoreEnd (&Guid), SN); >>
<<
VSNVObj.SetGuid (&Guid);
- _PCATCH(mCVfrDataStorage.GetVarStoreId(SN->getText(), &VarStoreId), SN);
+ _PCATCH(mCVfrDataStorage.GetVarStoreId(SN->getText(), &VarStoreId, &Guid), SN);
VSNVObj.SetVarStoreId (VarStoreId);
>>
";"
@@ -1097,6 +1097,10 @@ vfrStatementHeader[CIfrStatementHeader *SHObj] :
vfrQuestionHeader[CIfrQuestionHeader & QHObj, EFI_QUESION_TYPE QType = QUESTION_NORMAL]:
<<
EFI_VARSTORE_INFO Info;
+ Info.mVarType = EFI_IFR_TYPE_OTHER;
+ Info.mVarTotalSize = 0;
+ Info.mInfo.mVarOffset = EFI_VAROFFSET_INVALID;
+ Info.mVarStoreId = EFI_VARSTORE_ID_INVALID;
EFI_QUESTION_ID QId = EFI_QUESTION_ID_INVALID;
CHAR8 *QName = NULL;
CHAR8 *VarIdStr = NULL;
@@ -1147,8 +1151,8 @@ vfrQuestionHeader[CIfrQuestionHeader & QHObj, EFI_QUESION_TYPE QType = QUESTION_
<<
if (VarIdStr != NULL) {
delete VarIdStr;
- _SAVE_CURRQEST_VARINFO (Info);
}
+ _SAVE_CURRQEST_VARINFO (Info);
>>
;
@@ -1172,6 +1176,7 @@ vfrStorageVarId[EFI_VARSTORE_INFO & Info, CHAR8 *&QuestVarIdStr, BOOLEAN CheckFl
CHAR8 *TName = NULL;
EFI_VFR_RETURN_CODE VfrReturnCode = VFR_RETURN_SUCCESS;
EFI_IFR_TYPE_VALUE Dummy = gZeroEfiIfrTypeValue;
+ EFI_GUID *VarGuid = NULL;
>>
(
SN1:StringIdentifier << SName = SN1->getText(); _STRCAT(&VarIdStr, SN1->getText()); >>
@@ -1182,7 +1187,7 @@ vfrStorageVarId[EFI_VARSTORE_INFO & Info, CHAR8 *&QuestVarIdStr, BOOLEAN CheckFl
_STRCAT(&VarIdStr, "]");
>>
<<
- VfrReturnCode = mCVfrDataStorage.GetVarStoreType (SName, VarStoreType);
+ VfrReturnCode = mCVfrDataStorage.GetVarStoreId(SName, &$Info.mVarStoreId);
if (mCompatibleMode && VfrReturnCode == VFR_RETURN_UNDEFINED) {
mCVfrDataStorage.DeclareBufferVarStore (
SName,
@@ -1192,11 +1197,10 @@ vfrStorageVarId[EFI_VARSTORE_INFO & Info, CHAR8 *&QuestVarIdStr, BOOLEAN CheckFl
EFI_VARSTORE_ID_INVALID,
FALSE
);
- VfrReturnCode = mCVfrDataStorage.GetVarStoreType (SName, VarStoreType);
+ VfrReturnCode = mCVfrDataStorage.GetVarStoreId(SName, &$Info.mVarStoreId, &mFormsetGuid);
}
if (CheckFlag || VfrReturnCode == VFR_RETURN_SUCCESS) {
_PCATCH(VfrReturnCode, SN1);
- _PCATCH(mCVfrDataStorage.GetVarStoreId (SName, &$Info.mVarStoreId), SN1);
_PCATCH(mCVfrDataStorage.GetNameVarStoreInfo (&$Info, Idx), SN1);
}
@@ -1207,7 +1211,7 @@ vfrStorageVarId[EFI_VARSTORE_INFO & Info, CHAR8 *&QuestVarIdStr, BOOLEAN CheckFl
(
SN2:StringIdentifier << SName = SN2->getText(); _STRCAT(&VarIdStr, SName); >>
<<
- VfrReturnCode = mCVfrDataStorage.GetVarStoreType (SName, VarStoreType);
+ VfrReturnCode = mCVfrDataStorage.GetVarStoreId(SName, &$Info.mVarStoreId);
if (mCompatibleMode && VfrReturnCode == VFR_RETURN_UNDEFINED) {
mCVfrDataStorage.DeclareBufferVarStore (
SName,
@@ -1217,13 +1221,13 @@ vfrStorageVarId[EFI_VARSTORE_INFO & Info, CHAR8 *&QuestVarIdStr, BOOLEAN CheckFl
EFI_VARSTORE_ID_INVALID,
FALSE
);
- VfrReturnCode = mCVfrDataStorage.GetVarStoreType (SName, VarStoreType);
+ VfrReturnCode = mCVfrDataStorage.GetVarStoreId(SName, &$Info.mVarStoreId, &mFormsetGuid);
}
if (CheckFlag || VfrReturnCode == VFR_RETURN_SUCCESS) {
_PCATCH(VfrReturnCode, SN2);
- _PCATCH(mCVfrDataStorage.GetVarStoreId (SName, &$Info.mVarStoreId), SN2);
+ VarStoreType = mCVfrDataStorage.GetVarStoreType ($Info.mVarStoreId);
if (VarStoreType == EFI_VFR_VARSTORE_BUFFER) {
- _PCATCH(mCVfrDataStorage.GetBufferVarStoreDataTypeName(SName, &TName), SN2);
+ _PCATCH(mCVfrDataStorage.GetBufferVarStoreDataTypeName(Info.mVarStoreId, &TName), SN2);
_STRCAT(&VarStr, TName);
}
}
@@ -1262,13 +1266,16 @@ vfrStorageVarId[EFI_VARSTORE_INFO & Info, CHAR8 *&QuestVarIdStr, BOOLEAN CheckFl
break;
case EFI_VFR_VARSTORE_BUFFER:
_PCATCH(gCVfrVarDataTypeDB.GetDataFieldInfo (VarStr, $Info.mInfo.mVarOffset, $Info.mVarType, $Info.mVarTotalSize), SN2->getLine(), VarStr);
+ VarGuid = mCVfrDataStorage.GetVarStoreGuid($Info.mVarStoreId);
_PCATCH((EFI_VFR_RETURN_CODE)gCVfrBufferConfig.Register (
SName,
+ VarGuid,
NULL),
SN2->getLine());
_PCATCH((EFI_VFR_RETURN_CODE)gCVfrBufferConfig.Write (
'a',
SName,
+ VarGuid,
NULL,
$Info.mVarType,
$Info.mInfo.mVarOffset,
@@ -1472,8 +1479,8 @@ vfrStatementDefault :
EFI_DEFAULT_ID DefaultId = EFI_HII_DEFAULT_CLASS_STANDARD;
CHAR8 *VarStoreName = NULL;
EFI_VFR_VARSTORE_TYPE VarStoreType = EFI_VFR_VARSTORE_INVALID;
- UINT8 Size = 0;
- BOOLEAN TypeError = FALSE;
+ UINT32 Size = 0;
+ EFI_GUID *VarGuid = NULL;
>>
D:Default
(
@@ -1486,53 +1493,14 @@ vfrStatementDefault :
_PCATCH (VFR_RETURN_INVALID_PARAMETER, D->getLine(), "Numeric default value must be between MinValue and MaxValue.");
}
}
- switch (_GET_CURRQEST_DATATYPE()) {
- case EFI_IFR_TYPE_NUM_SIZE_8:
- Size = 1;
- break;
-
- case EFI_IFR_TYPE_NUM_SIZE_16:
- Size = 2;
- break;
-
- case EFI_IFR_TYPE_NUM_SIZE_32:
- Size = 4;
- break;
-
- case EFI_IFR_TYPE_NUM_SIZE_64:
- Size = 8;
- break;
-
- case EFI_IFR_TYPE_DATE:
- Size = 4;
- break;
-
- case EFI_IFR_TYPE_TIME:
- Size = 3;
- break;
-
- case EFI_IFR_TYPE_REF:
- Size = 22;
- break;
-
- case EFI_IFR_TYPE_STRING:
- Size = 2;
- break;
-
- case EFI_IFR_TYPE_BOOLEAN:
- Size = 1;
- break;
-
- default:
- TypeError = TRUE;
- Size = sizeof (EFI_IFR_TYPE_VALUE);
- break;
- }
- if (TypeError) {
+ if (_GET_CURRQEST_DATATYPE() == EFI_IFR_TYPE_OTHER) {
_PCATCH (VFR_RETURN_FATAL_ERROR, D->getLine(), "Default data type error.");
+ Size = sizeof (EFI_IFR_TYPE_VALUE);
+ } else {
+ _PCATCH (gCVfrVarDataTypeDB.GetDataTypeSize (_GET_CURRQEST_DATATYPE(), &Size), D->getLine());
}
Size += OFFSET_OF (EFI_IFR_DEFAULT, Value);
- DObj = new CIfrDefault (Size);
+ DObj = new CIfrDefault ((UINT8)Size);
DObj->SetLineNo(D->getLine());
DObj->SetType (_GET_CURRQEST_DATATYPE());
DObj->SetValue(Val);
@@ -1553,19 +1521,22 @@ vfrStatementDefault :
>>
}
<<
+ if (_GET_CURRQEST_VARTINFO().mVarStoreId != EFI_VARSTORE_ID_INVALID) {
_PCATCH(mCVfrDataStorage.GetVarStoreName (_GET_CURRQEST_VARTINFO().mVarStoreId, &VarStoreName), D->getLine());
- _PCATCH(mCVfrDataStorage.GetVarStoreType (VarStoreName, VarStoreType), D->getLine());
+ VarGuid = mCVfrDataStorage.GetVarStoreGuid(_GET_CURRQEST_VARTINFO().mVarStoreId);
+ VarStoreType = mCVfrDataStorage.GetVarStoreType (_GET_CURRQEST_VARTINFO().mVarStoreId);
if ((IsExp == FALSE) && (VarStoreType == EFI_VFR_VARSTORE_BUFFER)) {
_PCATCH(mCVfrDefaultStore.BufferVarStoreAltConfigAdd (
DefaultId,
_GET_CURRQEST_VARTINFO(),
VarStoreName,
+ VarGuid,
_GET_CURRQEST_DATATYPE (),
- Val),
- D->getLine()
- );
+ Val),
+ D->getLine()
+ );
+ }
}
-
if (DObj != NULL) {delete DObj;}
if (DObj2 != NULL) {delete DObj2;}
>>
@@ -1832,7 +1803,11 @@ vfrStatementGoto :
default: break;
}
>>
- vfrQuestionHeader[*QHObj, QUESTION_REF]
+ vfrQuestionHeader[*QHObj, QUESTION_REF] <<
+ if (_GET_CURRQEST_DATATYPE() == EFI_IFR_TYPE_OTHER) {
+ _GET_CURRQEST_VARTINFO().mVarType = EFI_IFR_TYPE_REF;
+ }
+ >>
{ "," F:FLAGS "=" vfrGotoFlags[QHObj, F->getLine()] }
{
"," Key "=" KN:Number << AssignQuestionKey (*QHObj, KN); >>
@@ -1901,9 +1876,13 @@ vfrStatementCheckBox :
EFI_IFR_TYPE_VALUE Val = gZeroEfiIfrTypeValue;
CHAR8 *VarStoreName = NULL;
UINT32 DataTypeSize;
+ EFI_GUID *VarStoreGuid = NULL;
>>
L:CheckBox << CBObj.SetLineNo(L->getLine()); >>
vfrQuestionHeader[CBObj] "," << //check data type
+ if (_GET_CURRQEST_DATATYPE() == EFI_IFR_TYPE_OTHER) {
+ _GET_CURRQEST_VARTINFO().mVarType = EFI_IFR_TYPE_BOOLEAN;
+ }
_PCATCH (gCVfrVarDataTypeDB.GetDataTypeSize (_GET_CURRQEST_DATATYPE(), &DataTypeSize), L->getLine(), "CheckBox varid is not the valid data type");
if (DataTypeSize != 0 && DataTypeSize != _GET_CURRQEST_VARSIZE()) {
_PCATCH (VFR_RETURN_INVALID_PARAMETER, L->getLine(), "CheckBox varid doesn't support array");
@@ -1916,6 +1895,7 @@ vfrStatementCheckBox :
F:FLAGS "=" vfrCheckBoxFlags[CBObj, F->getLine()] ","
<<
_PCATCH(mCVfrDataStorage.GetVarStoreName (_GET_CURRQEST_VARTINFO().mVarStoreId, &VarStoreName), VFR_RETURN_SUCCESS, L, "Failed to retrieve varstore name");
+ VarStoreGuid = mCVfrDataStorage.GetVarStoreGuid(_GET_CURRQEST_VARTINFO().mVarStoreId);
Val.b = TRUE;
if (CBObj.GetFlags () & 0x01) {
_PCATCH(
@@ -1923,6 +1903,7 @@ vfrStatementCheckBox :
EFI_HII_DEFAULT_CLASS_STANDARD,
_GET_CURRQEST_VARTINFO(),
VarStoreName,
+ VarStoreGuid,
_GET_CURRQEST_DATATYPE (),
Val
),
@@ -1937,6 +1918,7 @@ vfrStatementCheckBox :
EFI_HII_DEFAULT_CLASS_MANUFACTURING,
_GET_CURRQEST_VARTINFO(),
VarStoreName,
+ VarStoreGuid,
_GET_CURRQEST_DATATYPE (),
Val
),
@@ -2044,7 +2026,11 @@ vfrStatementDate :
L:Date << DObj.SetLineNo(L->getLine()); >>
(
(
- vfrQuestionHeader[DObj, QUESTION_DATE] ","
+ vfrQuestionHeader[DObj, QUESTION_DATE] "," <<
+ if (_GET_CURRQEST_DATATYPE() == EFI_IFR_TYPE_OTHER) {
+ _GET_CURRQEST_VARTINFO().mVarType = EFI_IFR_TYPE_DATE;
+ }
+ >>
{ F:FLAGS "=" vfrDateFlags[DObj, F->getLine()] "," }
vfrStatementQuestionOptionList
)
@@ -2517,7 +2503,11 @@ vfrStatementTime :
L:Time << TObj.SetLineNo(L->getLine()); >>
(
(
- vfrQuestionHeader[TObj, QUESTION_TIME] ","
+ vfrQuestionHeader[TObj, QUESTION_TIME] "," <<
+ if (_GET_CURRQEST_DATATYPE() == EFI_IFR_TYPE_OTHER) {
+ _GET_CURRQEST_VARTINFO().mVarType = EFI_IFR_TYPE_TIME;
+ }
+ >>
{ F:FLAGS "=" vfrTimeFlags[TObj, F->getLine()] "," }
vfrStatementQuestionOptionList
)
@@ -2866,32 +2856,29 @@ vfrStatementOneOfOption :
<<
EFI_IFR_TYPE_VALUE Val = gZeroEfiIfrTypeValue;
CHAR8 *VarStoreName = NULL;
+ UINT32 Size = 0;
BOOLEAN TypeError = FALSE;
- UINT8 Size = 0;
-
- switch (_GET_CURRQEST_DATATYPE()) {
- case EFI_IFR_TYPE_NUM_SIZE_8: Size = 1; break;
- case EFI_IFR_TYPE_NUM_SIZE_16: Size = 2; break;
- case EFI_IFR_TYPE_NUM_SIZE_32: Size = 4; break;
- case EFI_IFR_TYPE_NUM_SIZE_64: Size = 8; break;
- case EFI_IFR_TYPE_DATE: Size = 4; break;
- case EFI_IFR_TYPE_TIME: Size = 3; break;
- case EFI_IFR_TYPE_REF: Size = 22;break;
- case EFI_IFR_TYPE_STRING: Size = 2; break;
- case EFI_IFR_TYPE_BOOLEAN: Size = 1; break;
- default:
+ EFI_VFR_RETURN_CODE ReturnCode = VFR_RETURN_SUCCESS;
+ EFI_GUID *VarStoreGuid = NULL;
+
+ if (_GET_CURRQEST_DATATYPE() == EFI_IFR_TYPE_OTHER) {
TypeError = TRUE;
Size = sizeof (EFI_IFR_TYPE_VALUE);
- break;
+ } else {
+ ReturnCode = gCVfrVarDataTypeDB.GetDataTypeSize (_GET_CURRQEST_DATATYPE(), &Size);
}
+
Size += OFFSET_OF (EFI_IFR_ONE_OF_OPTION, Value);
- CIfrOneOfOption OOOObj (Size);
+ CIfrOneOfOption OOOObj ((UINT8)Size);
>>
- L:Option <<
+ L:Option <<
OOOObj.SetLineNo(L->getLine());
if (TypeError) {
_PCATCH (VFR_RETURN_FATAL_ERROR, L->getLine(), "Get data type error.");
}
+ if (ReturnCode != VFR_RETURN_SUCCESS) {
+ _PCATCH (ReturnCode, L->getLine());
+ }
>>
Text "=" "STRING_TOKEN" "\(" S:Number "\)" "," << OOOObj.SetOption (_STOSID(S->getText())); >>
Value "=" vfrConstantValueField[_GET_CURRQEST_DATATYPE()] >[Val] ","
@@ -2922,11 +2909,13 @@ vfrStatementOneOfOption :
F:FLAGS "=" vfrOneOfOptionFlags[OOOObj, F->getLine()]
<<
_PCATCH(mCVfrDataStorage.GetVarStoreName (_GET_CURRQEST_VARTINFO().mVarStoreId, &VarStoreName), L->getLine());
+ VarStoreGuid = mCVfrDataStorage.GetVarStoreGuid(_GET_CURRQEST_VARTINFO().mVarStoreId);
if (OOOObj.GetFlags () & 0x10) {
_PCATCH(mCVfrDefaultStore.BufferVarStoreAltConfigAdd (
EFI_HII_DEFAULT_CLASS_STANDARD,
_GET_CURRQEST_VARTINFO(),
VarStoreName,
+ VarStoreGuid,
_GET_CURRQEST_DATATYPE (),
Val
), L->getLine());
@@ -2936,6 +2925,7 @@ vfrStatementOneOfOption :
EFI_HII_DEFAULT_CLASS_MANUFACTURING,
_GET_CURRQEST_VARTINFO(),
VarStoreName,
+ VarStoreGuid,
_GET_CURRQEST_DATATYPE (),
Val
), L->getLine());
@@ -3351,8 +3341,8 @@ vareqvalExp [UINT32 & RootLevel, UINT32 & ExpOpCount] :
UINT16 ConstVal;
CHAR8 *VarIdStr;
UINT32 LineNo;
- EFI_VFR_VARSTORE_TYPE VarStoreType = EFI_VFR_VARSTORE_INVALID;
EFI_VFR_RETURN_CODE VfrReturnCode = VFR_RETURN_SUCCESS;
+ EFI_VARSTORE_ID VarStoreId = EFI_VARSTORE_ID_INVALID;
>>
L:VarEqVal <<
if (!mCompatibleMode) {
@@ -3363,7 +3353,7 @@ vareqvalExp [UINT32 & RootLevel, UINT32 & ExpOpCount] :
OpenParen
VN:Number <<
VarIdStr = NULL; _STRCAT(&VarIdStr, VK->getText()); _STRCAT(&VarIdStr, VN->getText());
- VfrReturnCode = mCVfrDataStorage.GetVarStoreType (VarIdStr, VarStoreType);
+ VfrReturnCode = mCVfrDataStorage.GetVarStoreId (VarIdStr, &VarStoreId);
if (VfrReturnCode == VFR_RETURN_UNDEFINED) {
_PCATCH (mCVfrDataStorage.DeclareEfiVarStore (
VarIdStr,
@@ -4600,7 +4590,7 @@ EfiVfrParser::_DeclareDefaultLinearVarStore (
TypeNameList[Index],
EFI_VARSTORE_ID_INVALID
);
- mCVfrDataStorage.GetVarStoreId(TypeNameList[Index], &VarStoreId);
+ mCVfrDataStorage.GetVarStoreId(TypeNameList[Index], &VarStoreId, &mFormsetGuid);
VSObj.SetVarStoreId (VarStoreId);
gCVfrVarDataTypeDB.GetDataTypeSize(TypeNameList[Index], &Size);
VSObj.SetSize ((UINT16) Size);
@@ -4625,7 +4615,7 @@ EfiVfrParser::_DeclareDefaultLinearVarStore (
(CHAR8 *) DateType,
EFI_VARSTORE_ID_INVALID
);
- mCVfrDataStorage.GetVarStoreId((CHAR8 *) DateName, &VarStoreId);
+ mCVfrDataStorage.GetVarStoreId((CHAR8 *) DateName, &VarStoreId, &mFormsetGuid);
VSObj.SetVarStoreId (VarStoreId);
gCVfrVarDataTypeDB.GetDataTypeSize((CHAR8 *) DateType, &Size);
VSObj.SetSize ((UINT16) Size);
@@ -4646,7 +4636,7 @@ EfiVfrParser::_DeclareDefaultLinearVarStore (
(CHAR8 *) TimeType,
EFI_VARSTORE_ID_INVALID
);
- mCVfrDataStorage.GetVarStoreId((CHAR8 *) TimeName, &VarStoreId);
+ mCVfrDataStorage.GetVarStoreId((CHAR8 *) TimeName, &VarStoreId, &mFormsetGuid);
VSObj.SetVarStoreId (VarStoreId);
gCVfrVarDataTypeDB.GetDataTypeSize((CHAR8 *) TimeType, &Size);
VSObj.SetSize ((UINT16) Size);
diff --git a/BaseTools/Source/C/VfrCompile/VfrUtilityLib.cpp b/BaseTools/Source/C/VfrCompile/VfrUtilityLib.cpp
index 0444677e8..f42df6e34 100644
--- a/BaseTools/Source/C/VfrCompile/VfrUtilityLib.cpp
+++ b/BaseTools/Source/C/VfrCompile/VfrUtilityLib.cpp
@@ -2,7 +2,7 @@
Vfr common library functions.
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -123,11 +123,13 @@ SConfigInfo::~SConfigInfo (
SConfigItem::SConfigItem (
IN CHAR8 *Name,
+ IN EFI_GUID *Guid,
IN CHAR8 *Id
)
{
mName = NULL;
- mId = 0;
+ mGuid = NULL;
+ mId = NULL;
mInfoStrList = NULL;
mNext = NULL;
@@ -137,6 +139,12 @@ SConfigItem::SConfigItem (
}
}
+ if (Guid != NULL) {
+ if ((mGuid = (EFI_GUID *) new CHAR8[sizeof (EFI_GUID)]) != NULL) {
+ memcpy (mGuid, Guid, sizeof (EFI_GUID));
+ }
+ }
+
if (Id != NULL) {
if ((mId = new CHAR8[strlen (Id) + 1]) != NULL) {
strcpy (mId, Id);
@@ -146,6 +154,7 @@ SConfigItem::SConfigItem (
SConfigItem::SConfigItem (
IN CHAR8 *Name,
+ IN EFI_GUID *Guid,
IN CHAR8 *Id,
IN UINT8 Type,
IN UINT16 Offset,
@@ -154,6 +163,7 @@ SConfigItem::SConfigItem (
)
{
mName = NULL;
+ mGuid = NULL;
mId = NULL;
mInfoStrList = NULL;
mNext = NULL;
@@ -164,6 +174,12 @@ SConfigItem::SConfigItem (
}
}
+ if (Guid != NULL) {
+ if ((mGuid = (EFI_GUID *) new CHAR8[sizeof (EFI_GUID)]) != NULL) {
+ memcpy (mGuid, Guid, sizeof (EFI_GUID));
+ }
+ }
+
if (Id != NULL) {
if ((mId = new CHAR8[strlen (Id) + 1]) != NULL) {
strcpy (mId, Id);
@@ -180,6 +196,7 @@ SConfigItem::~SConfigItem (
SConfigInfo *Info;
BUFFER_SAFE_FREE (mName);
+ BUFFER_SAFE_FREE (mGuid);
BUFFER_SAFE_FREE (mId);
while (mInfoStrList != NULL) {
Info = mInfoStrList;
@@ -192,18 +209,20 @@ SConfigItem::~SConfigItem (
UINT8
CVfrBufferConfig::Register (
IN CHAR8 *Name,
+ IN EFI_GUID *Guid,
IN CHAR8 *Id
)
{
SConfigItem *pNew;
- if (Select (Name) == 0) {
+ if (Select (Name, Guid) == 0) {
return 1;
}
- if ((pNew = new SConfigItem (Name, Id)) == NULL) {
+ if ((pNew = new SConfigItem (Name, Guid, Id)) == NULL) {
return 2;
}
+
if (mItemListHead == NULL) {
mItemListHead = pNew;
mItemListTail = pNew;
@@ -234,18 +253,19 @@ CVfrBufferConfig::Eof(
UINT8
CVfrBufferConfig::Select (
- IN CHAR8 *Name,
- IN CHAR8 *Id
+ IN CHAR8 *Name,
+ IN EFI_GUID *Guid,
+ IN CHAR8 *Id
)
{
SConfigItem *p;
- if (Name == NULL) {
+ if (Name == NULL || Guid == NULL) {
mItemListPos = mItemListHead;
return 0;
} else {
for (p = mItemListHead; p != NULL; p = p->mNext) {
- if (strcmp (p->mName, Name) != 0) {
+ if ((strcmp (p->mName, Name) != 0) || (memcmp (p->mGuid, Guid, sizeof (EFI_GUID)) != 0)) {
continue;
}
@@ -269,6 +289,7 @@ UINT8
CVfrBufferConfig::Write (
IN CONST CHAR8 Mode,
IN CHAR8 *Name,
+ IN EFI_GUID *Guid,
IN CHAR8 *Id,
IN UINT8 Type,
IN UINT16 Offset,
@@ -280,14 +301,14 @@ CVfrBufferConfig::Write (
SConfigItem *pItem;
SConfigInfo *pInfo;
- if ((Ret = Select (Name)) != 0) {
+ if ((Ret = Select (Name, Guid)) != 0) {
return Ret;
}
switch (Mode) {
case 'a' : // add
- if (Select (Name, Id) != 0) {
- if ((pItem = new SConfigItem (Name, Id, Type, Offset, (UINT16) Width, Value)) == NULL) {
+ if (Select (Name, Guid, Id) != 0) {
+ if ((pItem = new SConfigItem (Name, Guid, Id, Type, Offset, (UINT16) Width, Value)) == NULL) {
return 2;
}
if (mItemListHead == NULL) {
@@ -1578,7 +1599,7 @@ CVfrDataStorage::DeclareEfiVarStore (
return VFR_RETURN_EFIVARSTORE_SIZE_ERROR;
}
- if (GetVarStoreId (StoreName, &VarStoreId) == VFR_RETURN_SUCCESS) {
+ if (GetVarStoreId (StoreName, &VarStoreId, Guid) == VFR_RETURN_SUCCESS) {
return VFR_RETURN_REDEFINED;
}
@@ -1611,7 +1632,7 @@ CVfrDataStorage::DeclareBufferVarStore (
return VFR_RETURN_FATAL_ERROR;
}
- if (GetVarStoreId (StoreName, &TempVarStoreId) == VFR_RETURN_SUCCESS) {
+ if (GetVarStoreId (StoreName, &TempVarStoreId, Guid) == VFR_RETURN_SUCCESS) {
return VFR_RETURN_REDEFINED;
}
@@ -1633,7 +1654,7 @@ CVfrDataStorage::DeclareBufferVarStore (
pNew->mNext = mBufferVarStoreList;
mBufferVarStoreList = pNew;
- if (gCVfrBufferConfig.Register(StoreName) != 0) {
+ if (gCVfrBufferConfig.Register(StoreName, Guid) != 0) {
return VFR_RETURN_FATAL_ERROR;
}
@@ -1643,7 +1664,8 @@ CVfrDataStorage::DeclareBufferVarStore (
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetVarStoreByDataType (
IN CHAR8 *DataTypeName,
- OUT SVfrVarStorageNode **VarNode
+ OUT SVfrVarStorageNode **VarNode,
+ IN EFI_GUID *VarGuid
)
{
SVfrVarStorageNode *pNode;
@@ -1658,7 +1680,16 @@ CVfrDataStorage::GetVarStoreByDataType (
MatchNode = NULL;
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
- if (strcmp (pNode->mStorageInfo.mDataType->mTypeName, DataTypeName) == 0) {
+ if (strcmp (pNode->mStorageInfo.mDataType->mTypeName, DataTypeName) != 0) {
+ continue;
+ }
+
+ if ((VarGuid != NULL)) {
+ if (memcmp (VarGuid, &pNode->mGuid, sizeof (EFI_GUID)) == 0) {
+ *VarNode = pNode;
+ return VFR_RETURN_SUCCESS;
+ }
+ } else {
if (MatchNode == NULL) {
MatchNode = pNode;
} else {
@@ -1678,46 +1709,108 @@ CVfrDataStorage::GetVarStoreByDataType (
return VFR_RETURN_SUCCESS;
}
+EFI_VARSTORE_ID
+CVfrDataStorage::CheckGuidField (
+ IN SVfrVarStorageNode *pNode,
+ IN EFI_GUID *StoreGuid,
+ IN BOOLEAN *HasFoundOne,
+ OUT EFI_VFR_RETURN_CODE *ReturnCode
+ )
+{
+ if (StoreGuid != NULL) {
+ //
+ // If has guid info, compare the guid filed.
+ //
+ if (memcmp (StoreGuid, &pNode->mGuid, sizeof (EFI_GUID)) == 0) {
+ //
+ // Both name and guid are same, this this varstore.
+ //
+ mCurrVarStorageNode = pNode;
+ *ReturnCode = VFR_RETURN_SUCCESS;
+ return TRUE;
+ }
+ } else {
+ //
+ // Not has Guid field, check whether this name is the only one.
+ //
+ if (*HasFoundOne) {
+ //
+ // The name has conflict, return name redefined.
+ //
+ *ReturnCode = VFR_RETURN_VARSTORE_NAME_REDEFINED_ERROR;
+ return TRUE;
+ }
+
+ *HasFoundOne = TRUE;
+ mCurrVarStorageNode = pNode;
+ }
+
+ return FALSE;
+}
+
+/**
+ Base on the input store name and guid to find the varstore id.
+
+ If both name and guid are inputed, base on the name and guid to
+ found the varstore. If only name inputed, base on the name to
+ found the varstore and go on to check whether more than one varstore
+ has the same name. If only has found one varstore, return this
+ varstore; if more than one varstore has same name, return varstore
+ name redefined error. If no varstore found by varstore name, call
+ function GetVarStoreByDataType and use inputed varstore name as
+ data type name to search.
+**/
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetVarStoreId (
IN CHAR8 *StoreName,
- OUT EFI_VARSTORE_ID *VarStoreId
+ OUT EFI_VARSTORE_ID *VarStoreId,
+ IN EFI_GUID *StoreGuid
)
{
EFI_VFR_RETURN_CODE ReturnCode;
SVfrVarStorageNode *pNode;
+ BOOLEAN HasFoundOne = FALSE;
+
+ mCurrVarStorageNode = NULL;
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
- mCurrVarStorageNode = pNode;
- *VarStoreId = pNode->mVarStoreId;
- return VFR_RETURN_SUCCESS;
+ if (CheckGuidField(pNode, StoreGuid, &HasFoundOne, &ReturnCode)) {
+ *VarStoreId = mCurrVarStorageNode->mVarStoreId;
+ return ReturnCode;
+ }
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
- mCurrVarStorageNode = pNode;
- *VarStoreId = pNode->mVarStoreId;
- return VFR_RETURN_SUCCESS;
+ if (CheckGuidField(pNode, StoreGuid, &HasFoundOne, &ReturnCode)) {
+ *VarStoreId = mCurrVarStorageNode->mVarStoreId;
+ return ReturnCode;
+ }
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
- mCurrVarStorageNode = pNode;
- *VarStoreId = pNode->mVarStoreId;
- return VFR_RETURN_SUCCESS;
+ if (CheckGuidField(pNode, StoreGuid, &HasFoundOne, &ReturnCode)) {
+ *VarStoreId = mCurrVarStorageNode->mVarStoreId;
+ return ReturnCode;
+ }
}
}
- mCurrVarStorageNode = NULL;
+ if (HasFoundOne) {
+ *VarStoreId = mCurrVarStorageNode->mVarStoreId;
+ return VFR_RETURN_SUCCESS;
+ }
+
*VarStoreId = EFI_VARSTORE_ID_INVALID;
//
// Assume that Data strucutre name is used as StoreName, and check again.
//
- ReturnCode = GetVarStoreByDataType (StoreName, &pNode);
+ ReturnCode = GetVarStoreByDataType (StoreName, &pNode, StoreGuid);
if (pNode != NULL) {
mCurrVarStorageNode = pNode;
*VarStoreId = pNode->mVarStoreId;
@@ -1728,126 +1821,100 @@ CVfrDataStorage::GetVarStoreId (
EFI_VFR_RETURN_CODE
CVfrDataStorage::GetBufferVarStoreDataTypeName (
- IN CHAR8 *StoreName,
+ IN EFI_VARSTORE_ID VarStoreId,
OUT CHAR8 **DataTypeName
)
{
SVfrVarStorageNode *pNode;
- EFI_VFR_RETURN_CODE ReturnCode;
- if ((StoreName == NULL) || (DataTypeName == NULL)) {
+ if (VarStoreId == EFI_VARSTORE_ID_INVALID) {
return VFR_RETURN_FATAL_ERROR;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
- if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
- break;
+ if (pNode->mVarStoreId == VarStoreId) {
+ *DataTypeName = pNode->mStorageInfo.mDataType->mTypeName;
+ return VFR_RETURN_SUCCESS;
}
}
- ReturnCode = VFR_RETURN_UNDEFINED;
- //
- // Assume that Data strucutre name is used as StoreName, and check again.
- //
- if (pNode == NULL) {
- ReturnCode = GetVarStoreByDataType (StoreName, &pNode);
- }
-
- if (pNode == NULL) {
- return ReturnCode;
- }
-
- if (pNode->mStorageInfo.mDataType == NULL) {
- return VFR_RETURN_FATAL_ERROR;
- }
-
- *DataTypeName = pNode->mStorageInfo.mDataType->mTypeName;
- return VFR_RETURN_SUCCESS;
+ return VFR_RETURN_UNDEFINED;
}
-EFI_VFR_RETURN_CODE
+EFI_VFR_VARSTORE_TYPE
CVfrDataStorage::GetVarStoreType (
- IN CHAR8 *StoreName,
- OUT EFI_VFR_VARSTORE_TYPE &VarStoreType
+ IN EFI_VARSTORE_ID VarStoreId
)
{
SVfrVarStorageNode *pNode;
- EFI_VFR_RETURN_CODE ReturnCode;
+ EFI_VFR_VARSTORE_TYPE VarStoreType;
- if (StoreName == NULL) {
- return VFR_RETURN_FATAL_ERROR;
+ VarStoreType = EFI_VFR_VARSTORE_INVALID;
+
+ if (VarStoreId == EFI_VARSTORE_ID_INVALID) {
+ return VarStoreType;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
- if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
+ if (pNode->mVarStoreId == VarStoreId) {
VarStoreType = pNode->mVarStoreType;
- return VFR_RETURN_SUCCESS;
+ return VarStoreType;
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
- if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
+ if (pNode->mVarStoreId == VarStoreId) {
VarStoreType = pNode->mVarStoreType;
- return VFR_RETURN_SUCCESS;
+ return VarStoreType;
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
- if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
+ if (pNode->mVarStoreId == VarStoreId) {
VarStoreType = pNode->mVarStoreType;
- return VFR_RETURN_SUCCESS;
+ return VarStoreType;
}
}
- VarStoreType = EFI_VFR_VARSTORE_INVALID;
-
- //
- // Assume that Data strucutre name is used as StoreName, and check again.
- //
- ReturnCode = GetVarStoreByDataType (StoreName, &pNode);
- if (pNode != NULL) {
- VarStoreType = pNode->mVarStoreType;
- }
-
- return ReturnCode;
+ return VarStoreType;
}
-EFI_VFR_VARSTORE_TYPE
-CVfrDataStorage::GetVarStoreType (
+EFI_GUID *
+CVfrDataStorage::GetVarStoreGuid (
IN EFI_VARSTORE_ID VarStoreId
)
{
SVfrVarStorageNode *pNode;
- EFI_VFR_VARSTORE_TYPE VarStoreType;
+ EFI_GUID *VarGuid;
- VarStoreType = EFI_VFR_VARSTORE_INVALID;
+ VarGuid = NULL;
if (VarStoreId == EFI_VARSTORE_ID_INVALID) {
- return VarStoreType;
+ return VarGuid;
}
for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
- VarStoreType = pNode->mVarStoreType;
- return VarStoreType;
+ VarGuid = &pNode->mGuid;
+ return VarGuid;
}
}
for (pNode = mEfiVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
- VarStoreType = pNode->mVarStoreType;
- return VarStoreType;
+ VarGuid = &pNode->mGuid;
+ return VarGuid;
}
}
for (pNode = mNameVarStoreList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mVarStoreId == VarStoreId) {
- VarStoreType = pNode->mVarStoreType;
- return VarStoreType;
+ VarGuid = &pNode->mGuid;
+ return VarGuid;
}
}
- return VarStoreType;
+ return VarGuid;
}
EFI_VFR_RETURN_CODE
@@ -1951,44 +2018,6 @@ CVfrDataStorage::GetNameVarStoreInfo (
return VFR_RETURN_SUCCESS;
}
-EFI_VFR_RETURN_CODE
-CVfrDataStorage::BufferVarStoreRequestElementAdd (
- IN CHAR8 *StoreName,
- IN EFI_VARSTORE_INFO &Info
- )
-{
- SVfrVarStorageNode *pNode = NULL;
- EFI_IFR_TYPE_VALUE Value = gZeroEfiIfrTypeValue;
- EFI_VFR_RETURN_CODE ReturnCode;
-
- for (pNode = mBufferVarStoreList; pNode != NULL; pNode = pNode->mNext) {
- if (strcmp (pNode->mVarStoreName, StoreName) == 0) {
- break;
- }
- }
-
- ReturnCode = VFR_RETURN_UNDEFINED;
- //
- // Assume that Data strucutre name is used as StoreName, and check again.
- //
- if (pNode == NULL) {
- ReturnCode = GetVarStoreByDataType (StoreName, &pNode);
- }
-
- if (pNode == NULL) {
- return ReturnCode;
- }
-
- gCVfrBufferConfig.Open ();
- Value.u8 = 0;
- if (gCVfrBufferConfig.Write ('a', StoreName, NULL, EFI_IFR_TYPE_NUM_SIZE_8, Info.mInfo.mVarOffset, Info.mVarTotalSize, Value) != 0) {
- return VFR_RETURN_FATAL_ERROR;
- }
- gCVfrBufferConfig.Close ();
-
- return VFR_RETURN_SUCCESS;
-}
-
SVfrDefaultStoreNode::SVfrDefaultStoreNode (
IN EFI_IFR_DEFAULTSTORE *ObjBinAddr,
IN CHAR8 *RefName,
@@ -2155,6 +2184,7 @@ CVfrDefaultStore::BufferVarStoreAltConfigAdd (
IN EFI_VARSTORE_ID DefaultId,
IN EFI_VARSTORE_INFO &Info,
IN CHAR8 *VarStoreName,
+ IN EFI_GUID *VarStoreGuid,
IN UINT8 Type,
IN EFI_IFR_TYPE_VALUE Value
)
@@ -2180,8 +2210,8 @@ CVfrDefaultStore::BufferVarStoreAltConfigAdd (
gCVfrBufferConfig.Open ();
sprintf (NewAltCfg, "%04x", pNode->mDefaultId);
- if ((Returnvalue = gCVfrBufferConfig.Select(VarStoreName)) == 0) {
- if ((Returnvalue = gCVfrBufferConfig.Write ('a', VarStoreName, NewAltCfg, Type, Info.mInfo.mVarOffset, Info.mVarTotalSize, Value)) != 0) {
+ if ((Returnvalue = gCVfrBufferConfig.Select(VarStoreName, VarStoreGuid)) == 0) {
+ if ((Returnvalue = gCVfrBufferConfig.Write ('a', VarStoreName, VarStoreGuid, NewAltCfg, Type, Info.mInfo.mVarOffset, Info.mVarTotalSize, Value)) != 0) {
goto WriteError;
}
}
@@ -2592,26 +2622,46 @@ CVfrQuestionDB::RegisterNewDateQuestion (
CHAR8 *VarIdStr[3] = {NULL, };
CHAR8 Index;
- if (BaseVarId == NULL) {
+ if (BaseVarId == NULL && Name == NULL) {
return;
}
- Len = strlen (BaseVarId);
+ if (BaseVarId != NULL) {
+ Len = strlen (BaseVarId);
- VarIdStr[0] = new CHAR8[Len + strlen (".Year") + 1];
- if (VarIdStr[0] != NULL) {
- strcpy (VarIdStr[0], BaseVarId);
- strcat (VarIdStr[0], ".Year");
- }
- VarIdStr[1] = new CHAR8[Len + strlen (".Month") + 1];
- if (VarIdStr[1] != NULL) {
- strcpy (VarIdStr[1], BaseVarId);
- strcat (VarIdStr[1], ".Month");
- }
- VarIdStr[2] = new CHAR8[Len + strlen (".Day") + 1];
- if (VarIdStr[2] != NULL) {
- strcpy (VarIdStr[2], BaseVarId);
- strcat (VarIdStr[2], ".Day");
+ VarIdStr[0] = new CHAR8[Len + strlen (".Year") + 1];
+ if (VarIdStr[0] != NULL) {
+ strcpy (VarIdStr[0], BaseVarId);
+ strcat (VarIdStr[0], ".Year");
+ }
+ VarIdStr[1] = new CHAR8[Len + strlen (".Month") + 1];
+ if (VarIdStr[1] != NULL) {
+ strcpy (VarIdStr[1], BaseVarId);
+ strcat (VarIdStr[1], ".Month");
+ }
+ VarIdStr[2] = new CHAR8[Len + strlen (".Day") + 1];
+ if (VarIdStr[2] != NULL) {
+ strcpy (VarIdStr[2], BaseVarId);
+ strcat (VarIdStr[2], ".Day");
+ }
+ } else {
+ Len = strlen (Name);
+
+ VarIdStr[0] = new CHAR8[Len + strlen (".Year") + 1];
+ if (VarIdStr[0] != NULL) {
+ strcpy (VarIdStr[0], Name);
+ strcat (VarIdStr[0], ".Year");
+ }
+ VarIdStr[1] = new CHAR8[Len + strlen (".Month") + 1];
+ if (VarIdStr[1] != NULL) {
+ strcpy (VarIdStr[1], Name);
+ strcat (VarIdStr[1], ".Month");
+ }
+ VarIdStr[2] = new CHAR8[Len + strlen (".Day") + 1];
+ if (VarIdStr[2] != NULL) {
+ strcpy (VarIdStr[2], Name);
+ strcat (VarIdStr[2], ".Day");
+ }
}
if ((pNode[0] = new SVfrQuestionNode (Name, VarIdStr[0], DATE_YEAR_BITMASK)) == NULL) {
@@ -2740,26 +2790,46 @@ CVfrQuestionDB::RegisterNewTimeQuestion (
CHAR8 *VarIdStr[3] = {NULL, };
CHAR8 Index;
- if (BaseVarId == NULL) {
+ if (BaseVarId == NULL && Name == NULL) {
return;
}
- Len = strlen (BaseVarId);
+ if (BaseVarId != NULL) {
+ Len = strlen (BaseVarId);
- VarIdStr[0] = new CHAR8[Len + strlen (".Hour") + 1];
- if (VarIdStr[0] != NULL) {
- strcpy (VarIdStr[0], BaseVarId);
- strcat (VarIdStr[0], ".Hour");
- }
- VarIdStr[1] = new CHAR8[Len + strlen (".Minute") + 1];
- if (VarIdStr[1] != NULL) {
- strcpy (VarIdStr[1], BaseVarId);
- strcat (VarIdStr[1], ".Minute");
- }
- VarIdStr[2] = new CHAR8[Len + strlen (".Second") + 1];
- if (VarIdStr[2] != NULL) {
- strcpy (VarIdStr[2], BaseVarId);
- strcat (VarIdStr[2], ".Second");
+ VarIdStr[0] = new CHAR8[Len + strlen (".Hour") + 1];
+ if (VarIdStr[0] != NULL) {
+ strcpy (VarIdStr[0], BaseVarId);
+ strcat (VarIdStr[0], ".Hour");
+ }
+ VarIdStr[1] = new CHAR8[Len + strlen (".Minute") + 1];
+ if (VarIdStr[1] != NULL) {
+ strcpy (VarIdStr[1], BaseVarId);
+ strcat (VarIdStr[1], ".Minute");
+ }
+ VarIdStr[2] = new CHAR8[Len + strlen (".Second") + 1];
+ if (VarIdStr[2] != NULL) {
+ strcpy (VarIdStr[2], BaseVarId);
+ strcat (VarIdStr[2], ".Second");
+ }
+ } else {
+ Len = strlen (Name);
+
+ VarIdStr[0] = new CHAR8[Len + strlen (".Hour") + 1];
+ if (VarIdStr[0] != NULL) {
+ strcpy (VarIdStr[0], Name);
+ strcat (VarIdStr[0], ".Hour");
+ }
+ VarIdStr[1] = new CHAR8[Len + strlen (".Minute") + 1];
+ if (VarIdStr[1] != NULL) {
+ strcpy (VarIdStr[1], Name);
+ strcat (VarIdStr[1], ".Minute");
+ }
+ VarIdStr[2] = new CHAR8[Len + strlen (".Second") + 1];
+ if (VarIdStr[2] != NULL) {
+ strcpy (VarIdStr[2], Name);
+ strcat (VarIdStr[2], ".Second");
+ }
}
if ((pNode[0] = new SVfrQuestionNode (Name, VarIdStr[0], TIME_HOUR_BITMASK)) == NULL) {
@@ -2828,31 +2898,56 @@ CVfrQuestionDB::RegisterRefQuestion (
CHAR8 *VarIdStr[4] = {NULL, };
CHAR8 Index;
- if (BaseVarId == NULL) {
+ if (BaseVarId == NULL && Name == NULL) {
return;
}
- Len = strlen (BaseVarId);
+ if (BaseVarId != NULL) {
+ Len = strlen (BaseVarId);
- VarIdStr[0] = new CHAR8[Len + strlen (".QuestionId") + 1];
- if (VarIdStr[0] != NULL) {
- strcpy (VarIdStr[0], BaseVarId);
- strcat (VarIdStr[0], ".QuestionId");
- }
- VarIdStr[1] = new CHAR8[Len + strlen (".FormId") + 1];
- if (VarIdStr[1] != NULL) {
- strcpy (VarIdStr[1], BaseVarId);
- strcat (VarIdStr[1], ".FormId");
- }
- VarIdStr[2] = new CHAR8[Len + strlen (".FormSetGuid") + 1];
- if (VarIdStr[2] != NULL) {
- strcpy (VarIdStr[2], BaseVarId);
- strcat (VarIdStr[2], ".FormSetGuid");
- }
- VarIdStr[3] = new CHAR8[Len + strlen (".DevicePath") + 1];
- if (VarIdStr[3] != NULL) {
- strcpy (VarIdStr[3], BaseVarId);
- strcat (VarIdStr[3], ".DevicePath");
+ VarIdStr[0] = new CHAR8[Len + strlen (".QuestionId") + 1];
+ if (VarIdStr[0] != NULL) {
+ strcpy (VarIdStr[0], BaseVarId);
+ strcat (VarIdStr[0], ".QuestionId");
+ }
+ VarIdStr[1] = new CHAR8[Len + strlen (".FormId") + 1];
+ if (VarIdStr[1] != NULL) {
+ strcpy (VarIdStr[1], BaseVarId);
+ strcat (VarIdStr[1], ".FormId");
+ }
+ VarIdStr[2] = new CHAR8[Len + strlen (".FormSetGuid") + 1];
+ if (VarIdStr[2] != NULL) {
+ strcpy (VarIdStr[2], BaseVarId);
+ strcat (VarIdStr[2], ".FormSetGuid");
+ }
+ VarIdStr[3] = new CHAR8[Len + strlen (".DevicePath") + 1];
+ if (VarIdStr[3] != NULL) {
+ strcpy (VarIdStr[3], BaseVarId);
+ strcat (VarIdStr[3], ".DevicePath");
+ }
+ } else {
+ Len = strlen (Name);
+
+ VarIdStr[0] = new CHAR8[Len + strlen (".QuestionId") + 1];
+ if (VarIdStr[0] != NULL) {
+ strcpy (VarIdStr[0], Name);
+ strcat (VarIdStr[0], ".QuestionId");
+ }
+ VarIdStr[1] = new CHAR8[Len + strlen (".FormId") + 1];
+ if (VarIdStr[1] != NULL) {
+ strcpy (VarIdStr[1], Name);
+ strcat (VarIdStr[1], ".FormId");
+ }
+ VarIdStr[2] = new CHAR8[Len + strlen (".FormSetGuid") + 1];
+ if (VarIdStr[2] != NULL) {
+ strcpy (VarIdStr[2], Name);
+ strcat (VarIdStr[2], ".FormSetGuid");
+ }
+ VarIdStr[3] = new CHAR8[Len + strlen (".DevicePath") + 1];
+ if (VarIdStr[3] != NULL) {
+ strcpy (VarIdStr[3], Name);
+ strcat (VarIdStr[3], ".DevicePath");
+ }
}
if ((pNode[0] = new SVfrQuestionNode (Name, VarIdStr[0])) == NULL) {
diff --git a/BaseTools/Source/C/VfrCompile/VfrUtilityLib.h b/BaseTools/Source/C/VfrCompile/VfrUtilityLib.h
index 2c0ed7bd5..2847a74a7 100644
--- a/BaseTools/Source/C/VfrCompile/VfrUtilityLib.h
+++ b/BaseTools/Source/C/VfrCompile/VfrUtilityLib.h
@@ -2,7 +2,7 @@
Vfr common library functions.
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -57,13 +57,14 @@ struct SConfigInfo {
struct SConfigItem {
CHAR8 *mName; // varstore name
- CHAR8 *mId; // varstore ID
+ EFI_GUID *mGuid; // varstore guid, varstore name + guid deside one varstore
+ CHAR8 *mId; // default ID
SConfigInfo *mInfoStrList; // list of Offset/Value in the varstore
SConfigItem *mNext;
public:
- SConfigItem (IN CHAR8 *, IN CHAR8 *);
- SConfigItem (IN CHAR8 *, IN CHAR8 *, IN UINT8, IN UINT16, IN UINT16, IN EFI_IFR_TYPE_VALUE);
+ SConfigItem (IN CHAR8 *, IN EFI_GUID *, IN CHAR8 *);
+ SConfigItem (IN CHAR8 *, IN EFI_GUID *, IN CHAR8 *, IN UINT8, IN UINT16, IN UINT16, IN EFI_IFR_TYPE_VALUE);
virtual ~SConfigItem ();
};
@@ -77,11 +78,11 @@ public:
CVfrBufferConfig (VOID);
virtual ~CVfrBufferConfig (VOID);
- virtual UINT8 Register (IN CHAR8 *, IN CHAR8 *Info = NULL);
+ virtual UINT8 Register (IN CHAR8 *, IN EFI_GUID *,IN CHAR8 *Info = NULL);
virtual VOID Open (VOID);
virtual BOOLEAN Eof(VOID);
- virtual UINT8 Select (IN CHAR8 *, IN CHAR8 *Info = NULL);
- virtual UINT8 Write (IN CONST CHAR8, IN CHAR8 *, IN CHAR8 *, IN UINT8, IN UINT16, IN UINT32, IN EFI_IFR_TYPE_VALUE);
+ virtual UINT8 Select (IN CHAR8 *, IN EFI_GUID *, IN CHAR8 *Info = NULL);
+ virtual UINT8 Write (IN CONST CHAR8, IN CHAR8 *, IN EFI_GUID *, IN CHAR8 *, IN UINT8, IN UINT16, IN UINT32, IN EFI_IFR_TYPE_VALUE);
#if 0
virtual UINT8 Read (OUT CHAR8 **, OUT CHAR8 **, OUT CHAR8 **, OUT CHAR8 **, OUT CHAR8 **);
#endif
@@ -284,6 +285,10 @@ private:
BOOLEAN ChekVarStoreIdFree (IN EFI_VARSTORE_ID);
VOID MarkVarStoreIdUsed (IN EFI_VARSTORE_ID);
VOID MarkVarStoreIdUnused (IN EFI_VARSTORE_ID);
+ EFI_VARSTORE_ID CheckGuidField (IN SVfrVarStorageNode *,
+ IN EFI_GUID *,
+ IN BOOLEAN *,
+ OUT EFI_VFR_RETURN_CODE *);
public:
CVfrDataStorage ();
@@ -303,17 +308,15 @@ public:
EFI_VFR_RETURN_CODE DeclareBufferVarStore (IN CHAR8 *, IN EFI_GUID *, IN CVfrVarDataTypeDB *, IN CHAR8 *, IN EFI_VARSTORE_ID, IN BOOLEAN Flag = TRUE);
- EFI_VFR_RETURN_CODE GetVarStoreId (IN CHAR8 *, OUT EFI_VARSTORE_ID *);
- EFI_VFR_RETURN_CODE GetVarStoreType (IN CHAR8 *, OUT EFI_VFR_VARSTORE_TYPE &);
+ EFI_VFR_RETURN_CODE GetVarStoreId (IN CHAR8 *, OUT EFI_VARSTORE_ID *, IN EFI_GUID *VarGuid = NULL);
EFI_VFR_VARSTORE_TYPE GetVarStoreType (IN EFI_VARSTORE_ID);
+ EFI_GUID * GetVarStoreGuid (IN EFI_VARSTORE_ID);
EFI_VFR_RETURN_CODE GetVarStoreName (IN EFI_VARSTORE_ID, OUT CHAR8 **);
- EFI_VFR_RETURN_CODE GetVarStoreByDataType (IN CHAR8 *, OUT SVfrVarStorageNode **);
+ EFI_VFR_RETURN_CODE GetVarStoreByDataType (IN CHAR8 *, OUT SVfrVarStorageNode **, IN EFI_GUID *VarGuid = NULL);
- EFI_VFR_RETURN_CODE GetBufferVarStoreDataTypeName (IN CHAR8 *, OUT CHAR8 **);
+ EFI_VFR_RETURN_CODE GetBufferVarStoreDataTypeName (IN EFI_VARSTORE_ID, OUT CHAR8 **);
EFI_VFR_RETURN_CODE GetEfiVarStoreInfo (IN EFI_VARSTORE_INFO *);
EFI_VFR_RETURN_CODE GetNameVarStoreInfo (IN EFI_VARSTORE_INFO *, IN UINT32);
-
- EFI_VFR_RETURN_CODE BufferVarStoreRequestElementAdd (IN CHAR8 *, IN EFI_VARSTORE_INFO &);
};
#define EFI_QUESTION_ID_MAX 0xFFFF
@@ -396,7 +399,7 @@ public:
EFI_VFR_RETURN_CODE ReRegisterDefaultStoreById (IN UINT16, IN CHAR8 *, IN EFI_STRING_ID);
BOOLEAN DefaultIdRegistered (IN UINT16);
EFI_VFR_RETURN_CODE GetDefaultId (IN CHAR8 *, OUT UINT16 *);
- EFI_VFR_RETURN_CODE BufferVarStoreAltConfigAdd (IN EFI_VARSTORE_ID, IN EFI_VARSTORE_INFO &, IN CHAR8 *, IN UINT8, IN EFI_IFR_TYPE_VALUE);
+ EFI_VFR_RETURN_CODE BufferVarStoreAltConfigAdd (IN EFI_VARSTORE_ID, IN EFI_VARSTORE_INFO &, IN CHAR8 *, IN EFI_GUID *, IN UINT8, IN EFI_IFR_TYPE_VALUE);
};
#define EFI_RULE_ID_START 0x01
diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source/Python/GenFds/FdfParser.py
index c9c620d85..547271d53 100644
--- a/BaseTools/Source/Python/GenFds/FdfParser.py
+++ b/BaseTools/Source/Python/GenFds/FdfParser.py
@@ -2503,16 +2503,16 @@ class FdfParser:
self.__GetFileOpts( FfsFileObj)
if not self.__IsToken("{"):
-# if self.__IsKeyword('RELOCS_STRIPPED') or self.__IsKeyword('RELOCS_RETAINED'):
-# if self.__FileCouldHaveRelocFlag(FfsFileObj.FvFileType):
-# if self.__Token == 'RELOCS_STRIPPED':
-# FfsFileObj.KeepReloc = False
-# else:
-# FfsFileObj.KeepReloc = True
-# else:
-# raise Warning("File type %s could not have reloc strip flag%d" % (FfsFileObj.FvFileType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
-#
-# if not self.__IsToken("{"):
+ if self.__IsKeyword('RELOCS_STRIPPED') or self.__IsKeyword('RELOCS_RETAINED'):
+ if self.__FileCouldHaveRelocFlag(FfsFileObj.FvFileType):
+ if self.__Token == 'RELOCS_STRIPPED':
+ FfsFileObj.KeepReloc = False
+ else:
+ FfsFileObj.KeepReloc = True
+ else:
+ raise Warning("File type %s could not have reloc strip flag%d" % (FfsFileObj.FvFileType, self.CurrentLineNumber), self.FileName, self.CurrentLineNumber)
+
+ if not self.__IsToken("{"):
raise Warning("expected '{'", self.FileName, self.CurrentLineNumber)
if not self.__GetNextToken():
diff --git a/BaseTools/Source/Python/GenFds/FfsFileStatement.py b/BaseTools/Source/Python/GenFds/FfsFileStatement.py
index 04527fe00..d0dec380f 100755
--- a/BaseTools/Source/Python/GenFds/FfsFileStatement.py
+++ b/BaseTools/Source/Python/GenFds/FfsFileStatement.py
@@ -110,6 +110,8 @@ class FileStatement (FileStatementClassObject) :
if FvParentAddr != None and isinstance(section, GuidSection):
section.FvParentAddr = FvParentAddr
+ if self.KeepReloc == False:
+ section.KeepReloc = False
sectList, align = section.GenSection(OutputDir, self.NameGuid, SecIndex, self.KeyStringList, None, Dict)
if sectList != []:
for sect in sectList:
diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py
index b45793762..2d32f0576 100644
--- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py
+++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py
@@ -345,7 +345,7 @@ class GenFdsGlobalVariable:
@staticmethod
def GenerateSection(Output, Input, Type=None, CompressionType=None, Guid=None,
- GuidHdrLen=None, GuidAttr=[], Ui=None, Ver=None, InputAlign=None):
+ GuidHdrLen=None, GuidAttr=[], Ui=None, Ver=None, InputAlign=None, BuildNumber=None):
Cmd = ["GenSec"]
if Type not in [None, '']:
Cmd += ["-s", Type]
@@ -374,14 +374,11 @@ class GenFdsGlobalVariable:
GenFdsGlobalVariable.SectionHeader.pack_into(SectionData, 0, Len & 0xff, (Len >> 8) & 0xff, (Len >> 16) & 0xff, 0x15)
SaveFileOnChange(Output, SectionData.tostring())
elif Ver not in [None, '']:
- #Cmd += ["-j", Ver]
- SectionData = array.array('B', [0,0,0,0])
- SectionData.fromstring(Ver.encode("utf_16_le"))
- SectionData.append(0)
- SectionData.append(0)
- Len = len(SectionData)
- GenFdsGlobalVariable.SectionHeader.pack_into(SectionData, 0, Len & 0xff, (Len >> 8) & 0xff, (Len >> 16) & 0xff, 0x14)
- SaveFileOnChange(Output, SectionData.tostring())
+ Cmd += ["-n", Ver]
+ if BuildNumber:
+ Cmd += ["-j", BuildNumber]
+ Cmd += ["-o", Output]
+ GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate section")
else:
Cmd += ["-o", Output]
Cmd += Input
diff --git a/BaseTools/Source/Python/GenFds/VerSection.py b/BaseTools/Source/Python/GenFds/VerSection.py
index 3fca4064f..8f6da9624 100644
--- a/BaseTools/Source/Python/GenFds/VerSection.py
+++ b/BaseTools/Source/Python/GenFds/VerSection.py
@@ -76,7 +76,7 @@ class VerSection (VerSectionClassObject):
StringData = ''
GenFdsGlobalVariable.GenerateSection(OutputFile, None, 'EFI_SECTION_VERSION',
- Ui=StringData, Ver=self.BuildNum)
+ Ver=StringData, BuildNumber=self.BuildNum)
OutputFileList = []
OutputFileList.append(OutputFile)
return OutputFileList, self.Alignment
diff --git a/BeagleBoardPkg/BeagleBoardPkg.dec b/BeagleBoardPkg/BeagleBoardPkg.dec
index a6ee2740b..496442a62 100644
--- a/BeagleBoardPkg/BeagleBoardPkg.dec
+++ b/BeagleBoardPkg/BeagleBoardPkg.dec
@@ -1,36 +1,36 @@
-#/** @file
-# Beagle board package.
-#
-# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials are licensed and made available under
-# the terms and conditions of the BSD License which accompanies this distribution.
-# The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- DEC_SPECIFICATION = 0x00010005
- PACKAGE_NAME = BeagleBoardPkg
- PACKAGE_GUID = 6eba6648-d853-4eb3-9761-528b82d5ab04
- PACKAGE_VERSION = 0.1
-
-################################################################################
-#
-# Include Section - list of Include Paths that are provided by this package.
-# Comments are used for Keywords and Module Types.
-#
-# Supported Module Types:
-# BASE SEC PEI_CORE PEIM DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER DXE_SAL_DRIVER UEFI_DRIVER UEFI_APPLICATION
-#
-################################################################################
-[Includes.common]
- Include # Root include for the package
-
-[Guids.common]
- gBeagleBoardTokenSpaceGuid = { 0x6834fe45, 0x4aee, 0x4fc6, { 0xbc, 0xb5, 0xff, 0x45, 0xb7, 0xa8, 0x71, 0xe2 } }
-
+#/** @file
+# Beagle board package.
+#
+# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials are licensed and made available under
+# the terms and conditions of the BSD License which accompanies this distribution.
+# The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ DEC_SPECIFICATION = 0x00010005
+ PACKAGE_NAME = BeagleBoardPkg
+ PACKAGE_GUID = 6eba6648-d853-4eb3-9761-528b82d5ab04
+ PACKAGE_VERSION = 0.1
+
+################################################################################
+#
+# Include Section - list of Include Paths that are provided by this package.
+# Comments are used for Keywords and Module Types.
+#
+# Supported Module Types:
+# BASE SEC PEI_CORE PEIM DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER DXE_SAL_DRIVER UEFI_DRIVER UEFI_APPLICATION
+#
+################################################################################
+[Includes.common]
+ Include # Root include for the package
+
+[Guids.common]
+ gBeagleBoardTokenSpaceGuid = { 0x6834fe45, 0x4aee, 0x4fc6, { 0xbc, 0xb5, 0xff, 0x45, 0xb7, 0xa8, 0x71, 0xe2 } }
+
diff --git a/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoard.c b/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoard.c
index ff4c55687..4e58f3604 100755
--- a/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoard.c
+++ b/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoard.c
@@ -1,135 +1,135 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Library/IoLib.h>
-#include <Library/ArmPlatformLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-
-#include <Omap3530/Omap3530.h>
-#include <BeagleBoard.h>
-
-VOID
-PadConfiguration (
- BEAGLEBOARD_REVISION Revision
- );
-
-VOID
-ClockInit (
- VOID
- );
-
-/**
- Detect board revision
-
- @return Board revision
-**/
-BEAGLEBOARD_REVISION
-BeagleBoardGetRevision (
- VOID
- )
-{
- UINT32 OldPinDir;
- UINT32 Revision;
-
- // Read GPIO 171, 172, 173
- OldPinDir = MmioRead32 (GPIO6_BASE + GPIO_OE);
- MmioWrite32(GPIO6_BASE + GPIO_OE, (OldPinDir | BIT11 | BIT12 | BIT13));
- Revision = MmioRead32 (GPIO6_BASE + GPIO_DATAIN);
-
- // Restore I/O settings
- MmioWrite32 (GPIO6_BASE + GPIO_OE, OldPinDir);
-
- return (BEAGLEBOARD_REVISION)((Revision >> 11) & 0x7);
-}
-
-/**
- Return the current Boot Mode
-
- This function returns the boot reason on the platform
-
-**/
-EFI_BOOT_MODE
-ArmPlatformGetBootMode (
- VOID
- )
-{
- return BOOT_WITH_FULL_CONFIGURATION;
-}
-
-/**
- Initialize controllers that must setup at the early stage
-
- Some peripherals must be initialized in Secure World.
- For example, some L2x0 requires to be initialized in Secure World
-
-**/
-RETURN_STATUS
-ArmPlatformInitialize (
- IN UINTN MpId
- )
-{
- BEAGLEBOARD_REVISION Revision;
-
- Revision = BeagleBoardGetRevision();
-
- // Set up Pin muxing.
- PadConfiguration (Revision);
-
- // Set up system clocking
- ClockInit ();
-
- // Turn off the functional clock for Timer 3
- MmioAnd32 (CM_FCLKEN_PER, 0xFFFFFFFF ^ CM_ICLKEN_PER_EN_GPT3_ENABLE );
- ArmDataSyncronizationBarrier ();
-
- // Clear IRQs
- MmioWrite32 (INTCPS_CONTROL, INTCPS_CONTROL_NEWIRQAGR);
- ArmDataSyncronizationBarrier ();
-
- return RETURN_SUCCESS;
-}
-
-/**
- Initialize the system (or sometimes called permanent) memory
-
- This memory is generally represented by the DRAM.
-
-**/
-VOID
-ArmPlatformInitializeSystemMemory (
- VOID
- )
-{
- // We do not need to initialize the System Memory on RTSM
-}
-
-VOID
-ArmPlatformGetPlatformPpiList (
- OUT UINTN *PpiListSize,
- OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
- )
-{
- *PpiListSize = 0;
- *PpiList = NULL;
-}
-
-UINTN
-ArmPlatformGetCorePosition (
- IN UINTN MpId
- )
-{
- return 1;
-}
-
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Library/IoLib.h>
+#include <Library/ArmPlatformLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+
+#include <Omap3530/Omap3530.h>
+#include <BeagleBoard.h>
+
+VOID
+PadConfiguration (
+ BEAGLEBOARD_REVISION Revision
+ );
+
+VOID
+ClockInit (
+ VOID
+ );
+
+/**
+ Detect board revision
+
+ @return Board revision
+**/
+BEAGLEBOARD_REVISION
+BeagleBoardGetRevision (
+ VOID
+ )
+{
+ UINT32 OldPinDir;
+ UINT32 Revision;
+
+ // Read GPIO 171, 172, 173
+ OldPinDir = MmioRead32 (GPIO6_BASE + GPIO_OE);
+ MmioWrite32(GPIO6_BASE + GPIO_OE, (OldPinDir | BIT11 | BIT12 | BIT13));
+ Revision = MmioRead32 (GPIO6_BASE + GPIO_DATAIN);
+
+ // Restore I/O settings
+ MmioWrite32 (GPIO6_BASE + GPIO_OE, OldPinDir);
+
+ return (BEAGLEBOARD_REVISION)((Revision >> 11) & 0x7);
+}
+
+/**
+ Return the current Boot Mode
+
+ This function returns the boot reason on the platform
+
+**/
+EFI_BOOT_MODE
+ArmPlatformGetBootMode (
+ VOID
+ )
+{
+ return BOOT_WITH_FULL_CONFIGURATION;
+}
+
+/**
+ Initialize controllers that must setup at the early stage
+
+ Some peripherals must be initialized in Secure World.
+ For example, some L2x0 requires to be initialized in Secure World
+
+**/
+RETURN_STATUS
+ArmPlatformInitialize (
+ IN UINTN MpId
+ )
+{
+ BEAGLEBOARD_REVISION Revision;
+
+ Revision = BeagleBoardGetRevision();
+
+ // Set up Pin muxing.
+ PadConfiguration (Revision);
+
+ // Set up system clocking
+ ClockInit ();
+
+ // Turn off the functional clock for Timer 3
+ MmioAnd32 (CM_FCLKEN_PER, 0xFFFFFFFF ^ CM_ICLKEN_PER_EN_GPT3_ENABLE );
+ ArmDataSyncronizationBarrier ();
+
+ // Clear IRQs
+ MmioWrite32 (INTCPS_CONTROL, INTCPS_CONTROL_NEWIRQAGR);
+ ArmDataSyncronizationBarrier ();
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Initialize the system (or sometimes called permanent) memory
+
+ This memory is generally represented by the DRAM.
+
+**/
+VOID
+ArmPlatformInitializeSystemMemory (
+ VOID
+ )
+{
+ // We do not need to initialize the System Memory on RTSM
+}
+
+VOID
+ArmPlatformGetPlatformPpiList (
+ OUT UINTN *PpiListSize,
+ OUT EFI_PEI_PPI_DESCRIPTOR **PpiList
+ )
+{
+ *PpiListSize = 0;
+ *PpiList = NULL;
+}
+
+UINTN
+ArmPlatformGetCorePosition (
+ IN UINTN MpId
+ )
+{
+ return 1;
+}
+
diff --git a/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoardLib.inf b/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoardLib.inf
index e076500b8..7ca98c2bb 100755
--- a/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoardLib.inf
+++ b/BeagleBoardPkg/Library/BeagleBoardLib/BeagleBoardLib.inf
@@ -1,53 +1,53 @@
-#/* @file
-# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#*/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = BeagleBoardLib
- FILE_GUID = 736343a0-1d96-11e0-aaaa-0002a5d5c51b
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = ArmPlatformLib
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
- BeagleBoardPkg/BeagleBoardPkg.dec
-
-[LibraryClasses]
- IoLib
- ArmLib
-# OmapLib
- MemoryAllocationLib
-
-[Sources.common]
- BeagleBoard.c
- BeagleBoardMem.c
- PadConfiguration.c
- Clock.c
-
-[Protocols]
-
-[FeaturePcd]
- gEmbeddedTokenSpaceGuid.PcdCacheEnable
-
-[FixedPcd]
- gArmTokenSpaceGuid.PcdFdBaseAddress
- gArmTokenSpaceGuid.PcdFdSize
-
- gArmTokenSpaceGuid.PcdSystemMemoryBase
- gArmTokenSpaceGuid.PcdSystemMemorySize
+#/* @file
+# Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#*/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = BeagleBoardLib
+ FILE_GUID = 736343a0-1d96-11e0-aaaa-0002a5d5c51b
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = ArmPlatformLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+ BeagleBoardPkg/BeagleBoardPkg.dec
+
+[LibraryClasses]
+ IoLib
+ ArmLib
+# OmapLib
+ MemoryAllocationLib
+
+[Sources.common]
+ BeagleBoard.c
+ BeagleBoardMem.c
+ PadConfiguration.c
+ Clock.c
+
+[Protocols]
+
+[FeaturePcd]
+ gEmbeddedTokenSpaceGuid.PcdCacheEnable
+
+[FixedPcd]
+ gArmTokenSpaceGuid.PcdFdBaseAddress
+ gArmTokenSpaceGuid.PcdFdSize
+
+ gArmTokenSpaceGuid.PcdSystemMemoryBase
+ gArmTokenSpaceGuid.PcdSystemMemorySize
diff --git a/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.c b/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.c
index 2f9a3202e..7634ee174 100644
--- a/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.c
+++ b/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.c
@@ -1,103 +1,103 @@
-/** @file
- Basic serial IO abstaction for GDB
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Uefi.h>
-#include <Library/GdbSerialLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-#include <Library/DebugLib.h>
-#include <Library/OmapLib.h>
-#include <Omap3530/Omap3530.h>
-
-RETURN_STATUS
-EFIAPI
-GdbSerialLibConstructor (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- return RETURN_SUCCESS;
-}
-
-RETURN_STATUS
-EFIAPI
-GdbSerialInit (
- IN UINT64 BaudRate,
- IN UINT8 Parity,
- IN UINT8 DataBits,
- IN UINT8 StopBits
- )
-{
- return RETURN_SUCCESS;
-}
-
-BOOLEAN
-EFIAPI
-GdbIsCharAvailable (
- VOID
- )
-{
- UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
-
- if ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_NOT_EMPTY) {
- return TRUE;
- } else {
- return FALSE;
- }
-}
-
-CHAR8
-EFIAPI
-GdbGetChar (
- VOID
- )
-{
- UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
- UINT32 RBR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_RBR_REG;
- CHAR8 Char;
-
- while ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_EMPTY);
- Char = MmioRead8(RBR);
-
- return Char;
-}
-
-VOID
-EFIAPI
-GdbPutChar (
- IN CHAR8 Char
- )
-{
- UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
- UINT32 THR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_THR_REG;
-
- while ((MmioRead8(LSR) & UART_LSR_TX_FIFO_E_MASK) == UART_LSR_TX_FIFO_E_NOT_EMPTY);
- MmioWrite8(THR, Char);
-}
-
-VOID
-GdbPutString (
- IN CHAR8 *String
- )
-{
- while (*String != '\0') {
- GdbPutChar (*String);
- String++;
- }
-}
-
-
-
-
+/** @file
+ Basic serial IO abstaction for GDB
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Uefi.h>
+#include <Library/GdbSerialLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+#include <Library/DebugLib.h>
+#include <Library/OmapLib.h>
+#include <Omap3530/Omap3530.h>
+
+RETURN_STATUS
+EFIAPI
+GdbSerialLibConstructor (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ return RETURN_SUCCESS;
+}
+
+RETURN_STATUS
+EFIAPI
+GdbSerialInit (
+ IN UINT64 BaudRate,
+ IN UINT8 Parity,
+ IN UINT8 DataBits,
+ IN UINT8 StopBits
+ )
+{
+ return RETURN_SUCCESS;
+}
+
+BOOLEAN
+EFIAPI
+GdbIsCharAvailable (
+ VOID
+ )
+{
+ UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
+
+ if ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_NOT_EMPTY) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+CHAR8
+EFIAPI
+GdbGetChar (
+ VOID
+ )
+{
+ UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
+ UINT32 RBR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_RBR_REG;
+ CHAR8 Char;
+
+ while ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_EMPTY);
+ Char = MmioRead8(RBR);
+
+ return Char;
+}
+
+VOID
+EFIAPI
+GdbPutChar (
+ IN CHAR8 Char
+ )
+{
+ UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
+ UINT32 THR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_THR_REG;
+
+ while ((MmioRead8(LSR) & UART_LSR_TX_FIFO_E_MASK) == UART_LSR_TX_FIFO_E_NOT_EMPTY);
+ MmioWrite8(THR, Char);
+}
+
+VOID
+GdbPutString (
+ IN CHAR8 *String
+ )
+{
+ while (*String != '\0') {
+ GdbPutChar (*String);
+ String++;
+ }
+}
+
+
+
+
diff --git a/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.inf b/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.inf
index 8627442ee..df96e8b75 100644
--- a/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.inf
+++ b/BeagleBoardPkg/Library/GdbSerialLib/GdbSerialLib.inf
@@ -1,41 +1,41 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = GdbSerialLib
- FILE_GUID = E2423349-EF5D-439B-95F5-8B8D8E3B443F
- MODULE_TYPE = UEFI_DRIVER
- VERSION_STRING = 1.0
- LIBRARY_CLASS = GdbSerialLib
-
- CONSTRUCTOR = GdbSerialLibConstructor
-
-
-[Sources.common]
- GdbSerialLib.c
-
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- DebugLib
- IoLib
- OmapLib
-
-[FixedPcd]
- gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart
-
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = GdbSerialLib
+ FILE_GUID = E2423349-EF5D-439B-95F5-8B8D8E3B443F
+ MODULE_TYPE = UEFI_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = GdbSerialLib
+
+ CONSTRUCTOR = GdbSerialLibConstructor
+
+
+[Sources.common]
+ GdbSerialLib.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ IoLib
+ OmapLib
+
+[FixedPcd]
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart
+
diff --git a/BeagleBoardPkg/Sec/Cache.c b/BeagleBoardPkg/Sec/Cache.c
index 4256b0e99..193004a8e 100644
--- a/BeagleBoardPkg/Sec/Cache.c
+++ b/BeagleBoardPkg/Sec/Cache.c
@@ -75,5 +75,5 @@ InitCache (
ArmConfigureMmu (MemoryTable, &TranslationTableBase, &TranslationTableSize);
- BuildMemoryAllocationHob((EFI_PHYSICAL_ADDRESS)(UINTN)TranslationTableBase, TranslationTableSize, EfiBootServicesData);
+ BuildMemoryAllocationHob((EFI_PHYSICAL_ADDRESS)(UINTN)TranslationTableBase, TranslationTableSize, EfiBootServicesData);
}
diff --git a/BeagleBoardPkg/Sec/Sec.inf b/BeagleBoardPkg/Sec/Sec.inf
index a3fc192c2..7fc4ec12d 100644
--- a/BeagleBoardPkg/Sec/Sec.inf
+++ b/BeagleBoardPkg/Sec/Sec.inf
@@ -1,73 +1,73 @@
-
-#/** @file
-# SEC - Reset vector code that jumps to C and loads DXE core
-#
-# Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = BeagleBoardSec
- FILE_GUID = d959e387-7b91-452c-90e0-a1dbac90ddb8
- MODULE_TYPE = SEC
- VERSION_STRING = 1.0
-
-
-[Sources.ARM]
- Arm/ModuleEntryPoint.S | GCC
- Arm/ModuleEntryPoint.asm | RVCT
-
-[Sources.ARM]
- Sec.c
- Cache.c
- PadConfiguration.c
- Clock.c
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
- IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
-
-[LibraryClasses]
- BaseLib
- DebugLib
- ArmLib
- IoLib
- ExtractGuidedSectionLib
- LzmaDecompressLib
- OmapLib
- PeCoffGetEntryPointLib
- DebugAgentLib
- MemoryAllocationLib
- PrePiHobListPointerLib
-
-[FeaturePcd]
- gEmbeddedTokenSpaceGuid.PcdCacheEnable
-
-[FixedPcd]
- gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate
- gEmbeddedTokenSpaceGuid.PcdEmbeddedFdBaseAddress
- gEmbeddedTokenSpaceGuid.PcdEmbeddedFdSize
- gEmbeddedTokenSpaceGuid.PcdFlashFvMainBase
- gEmbeddedTokenSpaceGuid.PcdFlashFvMainSize
- gEmbeddedTokenSpaceGuid.PcdPrePiStackSize
- gEmbeddedTokenSpaceGuid.PcdPrePiStackBase
- gEmbeddedTokenSpaceGuid.PcdMemoryBase
- gEmbeddedTokenSpaceGuid.PcdMemorySize
-
- gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart
- gOmap35xxTokenSpaceGuid.PcdOmap35xxFreeTimer
-
- gArmTokenSpaceGuid.PcdCpuVectorBaseAddress
-
+
+#/** @file
+# SEC - Reset vector code that jumps to C and loads DXE core
+#
+# Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = BeagleBoardSec
+ FILE_GUID = d959e387-7b91-452c-90e0-a1dbac90ddb8
+ MODULE_TYPE = SEC
+ VERSION_STRING = 1.0
+
+
+[Sources.ARM]
+ Arm/ModuleEntryPoint.S | GCC
+ Arm/ModuleEntryPoint.asm | RVCT
+
+[Sources.ARM]
+ Sec.c
+ Cache.c
+ PadConfiguration.c
+ Clock.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+ IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ ArmLib
+ IoLib
+ ExtractGuidedSectionLib
+ LzmaDecompressLib
+ OmapLib
+ PeCoffGetEntryPointLib
+ DebugAgentLib
+ MemoryAllocationLib
+ PrePiHobListPointerLib
+
+[FeaturePcd]
+ gEmbeddedTokenSpaceGuid.PcdCacheEnable
+
+[FixedPcd]
+ gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedFdBaseAddress
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedFdSize
+ gEmbeddedTokenSpaceGuid.PcdFlashFvMainBase
+ gEmbeddedTokenSpaceGuid.PcdFlashFvMainSize
+ gEmbeddedTokenSpaceGuid.PcdPrePiStackSize
+ gEmbeddedTokenSpaceGuid.PcdPrePiStackBase
+ gEmbeddedTokenSpaceGuid.PcdMemoryBase
+ gEmbeddedTokenSpaceGuid.PcdMemorySize
+
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxFreeTimer
+
+ gArmTokenSpaceGuid.PcdCpuVectorBaseAddress
+
diff --git a/BeagleBoardPkg/Tools/generate_image.c b/BeagleBoardPkg/Tools/generate_image.c
index fa4cdcc49..9426ca333 100644
--- a/BeagleBoardPkg/Tools/generate_image.c
+++ b/BeagleBoardPkg/Tools/generate_image.c
@@ -1,408 +1,408 @@
-/** @file
- The data structures in this code come from:
- OMAP35x Applications Processor Technical Reference Manual chapter 25
- OMAP34xx Multimedia Device Technical Reference Manual chapter 26.4.8.
-
- You should use the OMAP35x manual when possible. Some things, like SectionKey,
- are not defined in the OMAP35x manual and you have to use the OMAP34xx manual
- to find the data.
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-
-
-//TOC structure as defined by OMAP35XX TRM.
-typedef struct {
- unsigned int Start;
- unsigned int Size;
- unsigned int Reserved1;
- unsigned int Reserved2;
- unsigned int Reserved3;
- unsigned char Filename[12];
-} TOC_DATA;
-
-//NOTE: OMAP3430 TRM has CHSETTINGS and CHRAM structures.
-typedef struct {
- unsigned int SectionKey;
- unsigned char Valid;
- unsigned char Version;
- unsigned short Reserved;
- unsigned int Flags;
- unsigned int PRM_CLKSRC_CTRL;
- unsigned int PRM_CLKSEL;
- unsigned int CM_CLKSEL1_EMU;
- unsigned int CM_CLKSEL_CORE;
- unsigned int CM_CLKSEL_WKUP;
- unsigned int CM_CLKEN_PLL_DPLL3;
- unsigned int CM_AUTOIDLE_PLL_DPLL3;
- unsigned int CM_CLKSEL1_PLL;
- unsigned int CM_CLKEN_PLL_DPLL4;
- unsigned int CM_AUTOIDLE_PLL_DPLL4;
- unsigned int CM_CLKSEL2_PLL;
- unsigned int CM_CLKSEL3_PLL;
- unsigned int CM_CLKEN_PLL_MPU;
- unsigned int CM_AUTOIDLE_PLL_MPU;
- unsigned int CM_CLKSEL1_PLL_MPU;
- unsigned int CM_CLKSEL2_PLL_MPU;
- unsigned int CM_CLKSTCTRL_MPU;
-} CHSETTINGS_DATA;
-
-typedef struct {
- unsigned int SectionKey;
- unsigned char Valid;
- unsigned char Reserved1;
- unsigned char Reserved2;
- unsigned char Reserved3;
- unsigned short SDRC_SYSCONFIG_LSB;
- unsigned short SDRC_CS_CFG_LSB;
- unsigned short SDRC_SHARING_LSB;
- unsigned short SDRC_ERR_TYPE_LSB;
- unsigned int SDRC_DLLA_CTRL;
- unsigned short Reserved4;
- unsigned short Reserved5;
- unsigned int SDRC_POWER;
- unsigned short MEMORY_TYPE_CS0;
- unsigned short Reserved6;
- unsigned int SDRC_MCFG_0;
- unsigned short SDRC_MR_0_LSB;
- unsigned short SDRC_EMR1_0_LSB;
- unsigned short SDRC_EMR2_0_LSB;
- unsigned short SDRC_EMR3_0_LSB;
- unsigned int SDRC_ACTIM_CTRLA_0;
- unsigned int SDRC_ACTIM_CTRLB_0;
- unsigned int SDRC_RFRCTRL_0;
- unsigned short MEMORY_TYPE_CS1;
- unsigned short Reserved7;
- unsigned int SDRC_MCFG_1;
- unsigned short SDRC_MR_1_LSB;
- unsigned short SDRC_EMR1_1_LSB;
- unsigned short SDRC_EMR2_1_LSB;
- unsigned short SDRC_EMR3_1_LSB;
- unsigned int SDRC_ACTIM_CTRLA_1;
- unsigned int SDRC_ACTIM_CTRLB_1;
- unsigned int SDRC_RFRCTRL_1;
- unsigned int Reserved8;
- unsigned short Flags;
- unsigned short Reserved9;
-} CHRAM_DATA;
-
-#define CHSETTINGS_START 0xA0
-#define CHSETTINGS_SIZE 0x50
-#define CHRAM_START 0xF0
-#define CHRAM_SIZE 0x5C
-#define CLOSING_TOC_ITEM_SIZE 4
-
-unsigned char gConfigurationHeader[512];
-unsigned int gImageExecutionAddress;
-char *gInputImageFile = NULL;
-char *gOutputImageFile = NULL;
-char *gDataFile = NULL;
-
-static
-void
-PrintUsage (
- void
- )
-{
- printf("Usage..\n");
-}
-
-static
-void
-PopulateCHSETTINGSData (
- FILE *DataFile,
- CHSETTINGS_DATA *CHSETTINGSData
- )
-{
- unsigned int Value;
-
- CHSETTINGSData->SectionKey = 0xC0C0C0C1;
- CHSETTINGSData->Valid = 0x1;
- CHSETTINGSData->Version = 0x1;
- CHSETTINGSData->Reserved = 0x00;
- CHSETTINGSData->Flags = 0x050001FD;
-
- //General clock settings.
- fscanf(DataFile, "PRM_CLKSRC_CTRL=0x%08x\n", &Value);
- CHSETTINGSData->PRM_CLKSRC_CTRL = Value;
- fscanf(DataFile, "PRM_CLKSEL=0x%08x\n", &Value);
- CHSETTINGSData->PRM_CLKSEL = Value;
- fscanf(DataFile, "CM_CLKSEL1_EMU=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL1_EMU = Value;
-
- //Clock configuration
- fscanf(DataFile, "CM_CLKSEL_CORE=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL_CORE = Value;
- fscanf(DataFile, "CM_CLKSEL_WKUP=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL_WKUP = Value;
-
- //DPLL3 (Core) settings
- fscanf(DataFile, "CM_CLKEN_PLL_DPLL3=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKEN_PLL_DPLL3 = Value;
- fscanf(DataFile, "CM_AUTOIDLE_PLL_DPLL3=0x%08x\n", &Value);
- CHSETTINGSData->CM_AUTOIDLE_PLL_DPLL3 = Value;
- fscanf(DataFile, "CM_CLKSEL1_PLL=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL1_PLL = Value;
-
- //DPLL4 (Peripheral) settings
- fscanf(DataFile, "CM_CLKEN_PLL_DPLL4=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKEN_PLL_DPLL4 = Value;
- fscanf(DataFile, "CM_AUTOIDLE_PLL_DPLL4=0x%08x\n", &Value);
- CHSETTINGSData->CM_AUTOIDLE_PLL_DPLL4 = Value;
- fscanf(DataFile, "CM_CLKSEL2_PLL=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL2_PLL = Value;
- fscanf(DataFile, "CM_CLKSEL3_PLL=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL3_PLL = Value;
-
- //DPLL1 (MPU) settings
- fscanf(DataFile, "CM_CLKEN_PLL_MPU=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKEN_PLL_MPU = Value;
- fscanf(DataFile, "CM_AUTOIDLE_PLL_MPU=0x%08x\n", &Value);
- CHSETTINGSData->CM_AUTOIDLE_PLL_MPU = Value;
- fscanf(DataFile, "CM_CLKSEL1_PLL_MPU=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL1_PLL_MPU = Value;
- fscanf(DataFile, "CM_CLKSEL2_PLL_MPU=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSEL2_PLL_MPU = Value;
- fscanf(DataFile, "CM_CLKSTCTRL_MPU=0x%08x\n", &Value);
- CHSETTINGSData->CM_CLKSTCTRL_MPU = Value;
-}
-
-static
-void
-PopulateCHRAMData (
- FILE *DataFile,
- CHRAM_DATA *CHRAMData
- )
-{
- unsigned int Value;
-
- CHRAMData->SectionKey = 0xC0C0C0C2;
- CHRAMData->Valid = 0x1;
-
- fscanf(DataFile, "SDRC_SYSCONFIG_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_SYSCONFIG_LSB = Value;
- fscanf(DataFile, "SDRC_CS_CFG_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_CS_CFG_LSB = Value;
- fscanf(DataFile, "SDRC_SHARING_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_SHARING_LSB = Value;
- fscanf(DataFile, "SDRC_ERR_TYPE_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_ERR_TYPE_LSB = Value;
- fscanf(DataFile, "SDRC_DLLA_CTRL=0x%08x\n", &Value);
- CHRAMData->SDRC_DLLA_CTRL = Value;
- fscanf(DataFile, "SDRC_POWER=0x%08x\n", &Value);
- CHRAMData->SDRC_POWER = Value;
- fscanf(DataFile, "MEMORY_TYPE_CS0=0x%04x\n", &Value);
- CHRAMData->MEMORY_TYPE_CS0 = Value;
- fscanf(DataFile, "SDRC_MCFG_0=0x%08x\n", &Value);
- CHRAMData->SDRC_MCFG_0 = Value;
- fscanf(DataFile, "SDRC_MR_0_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_MR_0_LSB = Value;
- fscanf(DataFile, "SDRC_EMR1_0_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_EMR1_0_LSB = Value;
- fscanf(DataFile, "SDRC_EMR2_0_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_EMR2_0_LSB = Value;
- fscanf(DataFile, "SDRC_EMR3_0_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_EMR3_0_LSB = Value;
- fscanf(DataFile, "SDRC_ACTIM_CTRLA_0=0x%08x\n", &Value);
- CHRAMData->SDRC_ACTIM_CTRLA_0 = Value;
- fscanf(DataFile, "SDRC_ACTIM_CTRLB_0=0x%08x\n", &Value);
- CHRAMData->SDRC_ACTIM_CTRLB_0 = Value;
- fscanf(DataFile, "SDRC_RFRCTRL_0=0x%08x\n", &Value);
- CHRAMData->SDRC_RFRCTRL_0 = Value;
- fscanf(DataFile, "MEMORY_TYPE_CS1=0x%04x\n", &Value);
- CHRAMData->MEMORY_TYPE_CS1 = Value;
- fscanf(DataFile, "SDRC_MCFG_1=0x%08x\n", &Value);
- CHRAMData->SDRC_MCFG_1 = Value;
- fscanf(DataFile, "SDRC_MR_1_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_MR_1_LSB = Value;
- fscanf(DataFile, "SDRC_EMR1_1_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_EMR1_1_LSB = Value;
- fscanf(DataFile, "SDRC_EMR2_1_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_EMR2_1_LSB = Value;
- fscanf(DataFile, "SDRC_EMR3_1_LSB=0x%04x\n", &Value);
- CHRAMData->SDRC_EMR3_1_LSB = Value;
- fscanf(DataFile, "SDRC_ACTIM_CTRLA_1=0x%08x\n", &Value);
- CHRAMData->SDRC_ACTIM_CTRLA_1 = Value;
- fscanf(DataFile, "SDRC_ACTIM_CTRLB_1=0x%08x\n", &Value);
- CHRAMData->SDRC_ACTIM_CTRLB_1 = Value;
- fscanf(DataFile, "SDRC_RFRCTRL_1=0x%08x\n", &Value);
- CHRAMData->SDRC_RFRCTRL_1 = Value;
-
- CHRAMData->Flags = 0x0003;
-}
-
-static
-void
-PrepareConfigurationHeader (
- void
- )
-{
- TOC_DATA Toc;
- CHSETTINGS_DATA CHSETTINGSData;
- CHRAM_DATA CHRAMData;
- unsigned int ConfigurationHdrOffset = 0;
- FILE *DataFile;
-
- // Open data file
- DataFile = fopen(gDataFile, "rb");
- if (DataFile == NULL) {
- fprintf(stderr, "Can't open data file %s.\n", gDataFile);
- exit(1);
- }
-
- //Initialize configuration header.
- memset(gConfigurationHeader, 0x00, sizeof(gConfigurationHeader));
-
- //CHSETTINGS TOC
- memset(&Toc, 0x00, sizeof(TOC_DATA));
- Toc.Start = CHSETTINGS_START;
- Toc.Size = CHSETTINGS_SIZE;
- strcpy((char *)Toc.Filename, (const char *)"CHSETTINGS");
- memcpy(gConfigurationHeader + ConfigurationHdrOffset, &Toc, sizeof(TOC_DATA));
-
- //Populate CHSETTINGS Data
- memset(&CHSETTINGSData, 0x00, sizeof(CHSETTINGS_DATA));
- PopulateCHSETTINGSData(DataFile, &CHSETTINGSData);
- memcpy(gConfigurationHeader + Toc.Start, &CHSETTINGSData, Toc.Size);
-
- //Adjust ConfigurationHdrOffset to point to next TOC
- ConfigurationHdrOffset += sizeof(TOC_DATA);
-
- //CHRAM TOC
- memset(&Toc, 0x00, sizeof(TOC_DATA));
- Toc.Start = CHRAM_START;
- Toc.Size = CHRAM_SIZE;
- strcpy((char *)Toc.Filename, (const char *)"CHRAM");
- memcpy(gConfigurationHeader + ConfigurationHdrOffset, &Toc, sizeof(TOC_DATA));
-
- //Populate CHRAM Data
- memset(&CHRAMData, 0x00, sizeof(CHRAM_DATA));
- PopulateCHRAMData(DataFile, &CHRAMData);
- memcpy(gConfigurationHeader + Toc.Start, &CHRAMData, Toc.Size);
-
- //Adjust ConfigurationHdrOffset to point to next TOC
- ConfigurationHdrOffset += sizeof(TOC_DATA);
-
- //Closing TOC item
- memset(gConfigurationHeader + ConfigurationHdrOffset, 0xFF, CLOSING_TOC_ITEM_SIZE);
- ConfigurationHdrOffset += CLOSING_TOC_ITEM_SIZE;
-
- // Close data file
- fclose(DataFile);
-}
-
-static
-void
-ConstructImage (
- void
- )
-{
- FILE *InputFile;
- FILE *OutputFile;
- unsigned int InputImageFileSize;
- struct stat FileStat;
- char Ch;
- unsigned int i;
-
- InputFile = fopen(gInputImageFile, "rb");
- if (InputFile == NULL) {
- fprintf(stderr, "Can't open input file.\n");
- exit(0);
- }
-
- // Get the size of the input image.
- fstat(fileno(InputFile), &FileStat);
- InputImageFileSize = FileStat.st_size;
-
- OutputFile = fopen(gOutputImageFile, "wb");
- if (OutputFile == NULL) {
- fprintf(stderr, "Can't open output file %s.\n", gOutputImageFile);
- exit(0);
- }
-
- // Write Configuration header
- fwrite(gConfigurationHeader, 1, sizeof(gConfigurationHeader), OutputFile);
-
- // Write image header (Input image size, execution address)
- fwrite(&InputImageFileSize, 1, 4, OutputFile);
- fwrite(&gImageExecutionAddress, 1, 4, OutputFile);
-
- // Copy input image to the output file.
- for (i = 0; i < InputImageFileSize; i++) {
- fread(&Ch, 1, 1, InputFile);
- fwrite(&Ch, 1, 1, OutputFile);
- }
-
- fclose(InputFile);
- fclose(OutputFile);
-}
-
-
-int
-main (
- int argc,
- char** argv
- )
-{
- char Ch;
- unsigned char *ptr;
- int i;
- int TwoArg;
-
- if (argc == 1) {
- PrintUsage ();
- exit(1);
- }
-
- for (i=1; i < argc; i++) {
- if (argv[i][0] == '-') {
- // TwoArg TRUE -E 0x123, FALSE -E0x1234
- TwoArg = (argv[i][2] != ' ');
- switch (argv[i][1]) {
- case 'E': /* Image execution address */
- gImageExecutionAddress = strtoul (TwoArg ? argv[i+1] : &argv[i][2], (char **)&ptr, 16);
- break;
-
- case 'I': /* Input image file */
- gInputImageFile = TwoArg ? argv[i+1] : &argv[i][2];
- break;
-
- case 'O': /* Output image file */
- gOutputImageFile = TwoArg ? argv[i+1] : &argv[i][2];
- break;
-
- case 'D': /* Data file */
- gDataFile = TwoArg ? argv[i+1] : &argv[i][2];
- break;
-
- default:
- abort ();
- }
- }
- }
-
-
- //Prepare configuration header
- PrepareConfigurationHeader ();
-
- //Build image with configuration header + image header + image
- ConstructImage ();
-
- return 0;
-}
+/** @file
+ The data structures in this code come from:
+ OMAP35x Applications Processor Technical Reference Manual chapter 25
+ OMAP34xx Multimedia Device Technical Reference Manual chapter 26.4.8.
+
+ You should use the OMAP35x manual when possible. Some things, like SectionKey,
+ are not defined in the OMAP35x manual and you have to use the OMAP34xx manual
+ to find the data.
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+
+
+//TOC structure as defined by OMAP35XX TRM.
+typedef struct {
+ unsigned int Start;
+ unsigned int Size;
+ unsigned int Reserved1;
+ unsigned int Reserved2;
+ unsigned int Reserved3;
+ unsigned char Filename[12];
+} TOC_DATA;
+
+//NOTE: OMAP3430 TRM has CHSETTINGS and CHRAM structures.
+typedef struct {
+ unsigned int SectionKey;
+ unsigned char Valid;
+ unsigned char Version;
+ unsigned short Reserved;
+ unsigned int Flags;
+ unsigned int PRM_CLKSRC_CTRL;
+ unsigned int PRM_CLKSEL;
+ unsigned int CM_CLKSEL1_EMU;
+ unsigned int CM_CLKSEL_CORE;
+ unsigned int CM_CLKSEL_WKUP;
+ unsigned int CM_CLKEN_PLL_DPLL3;
+ unsigned int CM_AUTOIDLE_PLL_DPLL3;
+ unsigned int CM_CLKSEL1_PLL;
+ unsigned int CM_CLKEN_PLL_DPLL4;
+ unsigned int CM_AUTOIDLE_PLL_DPLL4;
+ unsigned int CM_CLKSEL2_PLL;
+ unsigned int CM_CLKSEL3_PLL;
+ unsigned int CM_CLKEN_PLL_MPU;
+ unsigned int CM_AUTOIDLE_PLL_MPU;
+ unsigned int CM_CLKSEL1_PLL_MPU;
+ unsigned int CM_CLKSEL2_PLL_MPU;
+ unsigned int CM_CLKSTCTRL_MPU;
+} CHSETTINGS_DATA;
+
+typedef struct {
+ unsigned int SectionKey;
+ unsigned char Valid;
+ unsigned char Reserved1;
+ unsigned char Reserved2;
+ unsigned char Reserved3;
+ unsigned short SDRC_SYSCONFIG_LSB;
+ unsigned short SDRC_CS_CFG_LSB;
+ unsigned short SDRC_SHARING_LSB;
+ unsigned short SDRC_ERR_TYPE_LSB;
+ unsigned int SDRC_DLLA_CTRL;
+ unsigned short Reserved4;
+ unsigned short Reserved5;
+ unsigned int SDRC_POWER;
+ unsigned short MEMORY_TYPE_CS0;
+ unsigned short Reserved6;
+ unsigned int SDRC_MCFG_0;
+ unsigned short SDRC_MR_0_LSB;
+ unsigned short SDRC_EMR1_0_LSB;
+ unsigned short SDRC_EMR2_0_LSB;
+ unsigned short SDRC_EMR3_0_LSB;
+ unsigned int SDRC_ACTIM_CTRLA_0;
+ unsigned int SDRC_ACTIM_CTRLB_0;
+ unsigned int SDRC_RFRCTRL_0;
+ unsigned short MEMORY_TYPE_CS1;
+ unsigned short Reserved7;
+ unsigned int SDRC_MCFG_1;
+ unsigned short SDRC_MR_1_LSB;
+ unsigned short SDRC_EMR1_1_LSB;
+ unsigned short SDRC_EMR2_1_LSB;
+ unsigned short SDRC_EMR3_1_LSB;
+ unsigned int SDRC_ACTIM_CTRLA_1;
+ unsigned int SDRC_ACTIM_CTRLB_1;
+ unsigned int SDRC_RFRCTRL_1;
+ unsigned int Reserved8;
+ unsigned short Flags;
+ unsigned short Reserved9;
+} CHRAM_DATA;
+
+#define CHSETTINGS_START 0xA0
+#define CHSETTINGS_SIZE 0x50
+#define CHRAM_START 0xF0
+#define CHRAM_SIZE 0x5C
+#define CLOSING_TOC_ITEM_SIZE 4
+
+unsigned char gConfigurationHeader[512];
+unsigned int gImageExecutionAddress;
+char *gInputImageFile = NULL;
+char *gOutputImageFile = NULL;
+char *gDataFile = NULL;
+
+static
+void
+PrintUsage (
+ void
+ )
+{
+ printf("Usage..\n");
+}
+
+static
+void
+PopulateCHSETTINGSData (
+ FILE *DataFile,
+ CHSETTINGS_DATA *CHSETTINGSData
+ )
+{
+ unsigned int Value;
+
+ CHSETTINGSData->SectionKey = 0xC0C0C0C1;
+ CHSETTINGSData->Valid = 0x1;
+ CHSETTINGSData->Version = 0x1;
+ CHSETTINGSData->Reserved = 0x00;
+ CHSETTINGSData->Flags = 0x050001FD;
+
+ //General clock settings.
+ fscanf(DataFile, "PRM_CLKSRC_CTRL=0x%08x\n", &Value);
+ CHSETTINGSData->PRM_CLKSRC_CTRL = Value;
+ fscanf(DataFile, "PRM_CLKSEL=0x%08x\n", &Value);
+ CHSETTINGSData->PRM_CLKSEL = Value;
+ fscanf(DataFile, "CM_CLKSEL1_EMU=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL1_EMU = Value;
+
+ //Clock configuration
+ fscanf(DataFile, "CM_CLKSEL_CORE=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL_CORE = Value;
+ fscanf(DataFile, "CM_CLKSEL_WKUP=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL_WKUP = Value;
+
+ //DPLL3 (Core) settings
+ fscanf(DataFile, "CM_CLKEN_PLL_DPLL3=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKEN_PLL_DPLL3 = Value;
+ fscanf(DataFile, "CM_AUTOIDLE_PLL_DPLL3=0x%08x\n", &Value);
+ CHSETTINGSData->CM_AUTOIDLE_PLL_DPLL3 = Value;
+ fscanf(DataFile, "CM_CLKSEL1_PLL=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL1_PLL = Value;
+
+ //DPLL4 (Peripheral) settings
+ fscanf(DataFile, "CM_CLKEN_PLL_DPLL4=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKEN_PLL_DPLL4 = Value;
+ fscanf(DataFile, "CM_AUTOIDLE_PLL_DPLL4=0x%08x\n", &Value);
+ CHSETTINGSData->CM_AUTOIDLE_PLL_DPLL4 = Value;
+ fscanf(DataFile, "CM_CLKSEL2_PLL=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL2_PLL = Value;
+ fscanf(DataFile, "CM_CLKSEL3_PLL=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL3_PLL = Value;
+
+ //DPLL1 (MPU) settings
+ fscanf(DataFile, "CM_CLKEN_PLL_MPU=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKEN_PLL_MPU = Value;
+ fscanf(DataFile, "CM_AUTOIDLE_PLL_MPU=0x%08x\n", &Value);
+ CHSETTINGSData->CM_AUTOIDLE_PLL_MPU = Value;
+ fscanf(DataFile, "CM_CLKSEL1_PLL_MPU=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL1_PLL_MPU = Value;
+ fscanf(DataFile, "CM_CLKSEL2_PLL_MPU=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSEL2_PLL_MPU = Value;
+ fscanf(DataFile, "CM_CLKSTCTRL_MPU=0x%08x\n", &Value);
+ CHSETTINGSData->CM_CLKSTCTRL_MPU = Value;
+}
+
+static
+void
+PopulateCHRAMData (
+ FILE *DataFile,
+ CHRAM_DATA *CHRAMData
+ )
+{
+ unsigned int Value;
+
+ CHRAMData->SectionKey = 0xC0C0C0C2;
+ CHRAMData->Valid = 0x1;
+
+ fscanf(DataFile, "SDRC_SYSCONFIG_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_SYSCONFIG_LSB = Value;
+ fscanf(DataFile, "SDRC_CS_CFG_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_CS_CFG_LSB = Value;
+ fscanf(DataFile, "SDRC_SHARING_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_SHARING_LSB = Value;
+ fscanf(DataFile, "SDRC_ERR_TYPE_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_ERR_TYPE_LSB = Value;
+ fscanf(DataFile, "SDRC_DLLA_CTRL=0x%08x\n", &Value);
+ CHRAMData->SDRC_DLLA_CTRL = Value;
+ fscanf(DataFile, "SDRC_POWER=0x%08x\n", &Value);
+ CHRAMData->SDRC_POWER = Value;
+ fscanf(DataFile, "MEMORY_TYPE_CS0=0x%04x\n", &Value);
+ CHRAMData->MEMORY_TYPE_CS0 = Value;
+ fscanf(DataFile, "SDRC_MCFG_0=0x%08x\n", &Value);
+ CHRAMData->SDRC_MCFG_0 = Value;
+ fscanf(DataFile, "SDRC_MR_0_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_MR_0_LSB = Value;
+ fscanf(DataFile, "SDRC_EMR1_0_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_EMR1_0_LSB = Value;
+ fscanf(DataFile, "SDRC_EMR2_0_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_EMR2_0_LSB = Value;
+ fscanf(DataFile, "SDRC_EMR3_0_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_EMR3_0_LSB = Value;
+ fscanf(DataFile, "SDRC_ACTIM_CTRLA_0=0x%08x\n", &Value);
+ CHRAMData->SDRC_ACTIM_CTRLA_0 = Value;
+ fscanf(DataFile, "SDRC_ACTIM_CTRLB_0=0x%08x\n", &Value);
+ CHRAMData->SDRC_ACTIM_CTRLB_0 = Value;
+ fscanf(DataFile, "SDRC_RFRCTRL_0=0x%08x\n", &Value);
+ CHRAMData->SDRC_RFRCTRL_0 = Value;
+ fscanf(DataFile, "MEMORY_TYPE_CS1=0x%04x\n", &Value);
+ CHRAMData->MEMORY_TYPE_CS1 = Value;
+ fscanf(DataFile, "SDRC_MCFG_1=0x%08x\n", &Value);
+ CHRAMData->SDRC_MCFG_1 = Value;
+ fscanf(DataFile, "SDRC_MR_1_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_MR_1_LSB = Value;
+ fscanf(DataFile, "SDRC_EMR1_1_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_EMR1_1_LSB = Value;
+ fscanf(DataFile, "SDRC_EMR2_1_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_EMR2_1_LSB = Value;
+ fscanf(DataFile, "SDRC_EMR3_1_LSB=0x%04x\n", &Value);
+ CHRAMData->SDRC_EMR3_1_LSB = Value;
+ fscanf(DataFile, "SDRC_ACTIM_CTRLA_1=0x%08x\n", &Value);
+ CHRAMData->SDRC_ACTIM_CTRLA_1 = Value;
+ fscanf(DataFile, "SDRC_ACTIM_CTRLB_1=0x%08x\n", &Value);
+ CHRAMData->SDRC_ACTIM_CTRLB_1 = Value;
+ fscanf(DataFile, "SDRC_RFRCTRL_1=0x%08x\n", &Value);
+ CHRAMData->SDRC_RFRCTRL_1 = Value;
+
+ CHRAMData->Flags = 0x0003;
+}
+
+static
+void
+PrepareConfigurationHeader (
+ void
+ )
+{
+ TOC_DATA Toc;
+ CHSETTINGS_DATA CHSETTINGSData;
+ CHRAM_DATA CHRAMData;
+ unsigned int ConfigurationHdrOffset = 0;
+ FILE *DataFile;
+
+ // Open data file
+ DataFile = fopen(gDataFile, "rb");
+ if (DataFile == NULL) {
+ fprintf(stderr, "Can't open data file %s.\n", gDataFile);
+ exit(1);
+ }
+
+ //Initialize configuration header.
+ memset(gConfigurationHeader, 0x00, sizeof(gConfigurationHeader));
+
+ //CHSETTINGS TOC
+ memset(&Toc, 0x00, sizeof(TOC_DATA));
+ Toc.Start = CHSETTINGS_START;
+ Toc.Size = CHSETTINGS_SIZE;
+ strcpy((char *)Toc.Filename, (const char *)"CHSETTINGS");
+ memcpy(gConfigurationHeader + ConfigurationHdrOffset, &Toc, sizeof(TOC_DATA));
+
+ //Populate CHSETTINGS Data
+ memset(&CHSETTINGSData, 0x00, sizeof(CHSETTINGS_DATA));
+ PopulateCHSETTINGSData(DataFile, &CHSETTINGSData);
+ memcpy(gConfigurationHeader + Toc.Start, &CHSETTINGSData, Toc.Size);
+
+ //Adjust ConfigurationHdrOffset to point to next TOC
+ ConfigurationHdrOffset += sizeof(TOC_DATA);
+
+ //CHRAM TOC
+ memset(&Toc, 0x00, sizeof(TOC_DATA));
+ Toc.Start = CHRAM_START;
+ Toc.Size = CHRAM_SIZE;
+ strcpy((char *)Toc.Filename, (const char *)"CHRAM");
+ memcpy(gConfigurationHeader + ConfigurationHdrOffset, &Toc, sizeof(TOC_DATA));
+
+ //Populate CHRAM Data
+ memset(&CHRAMData, 0x00, sizeof(CHRAM_DATA));
+ PopulateCHRAMData(DataFile, &CHRAMData);
+ memcpy(gConfigurationHeader + Toc.Start, &CHRAMData, Toc.Size);
+
+ //Adjust ConfigurationHdrOffset to point to next TOC
+ ConfigurationHdrOffset += sizeof(TOC_DATA);
+
+ //Closing TOC item
+ memset(gConfigurationHeader + ConfigurationHdrOffset, 0xFF, CLOSING_TOC_ITEM_SIZE);
+ ConfigurationHdrOffset += CLOSING_TOC_ITEM_SIZE;
+
+ // Close data file
+ fclose(DataFile);
+}
+
+static
+void
+ConstructImage (
+ void
+ )
+{
+ FILE *InputFile;
+ FILE *OutputFile;
+ unsigned int InputImageFileSize;
+ struct stat FileStat;
+ char Ch;
+ unsigned int i;
+
+ InputFile = fopen(gInputImageFile, "rb");
+ if (InputFile == NULL) {
+ fprintf(stderr, "Can't open input file.\n");
+ exit(0);
+ }
+
+ // Get the size of the input image.
+ fstat(fileno(InputFile), &FileStat);
+ InputImageFileSize = FileStat.st_size;
+
+ OutputFile = fopen(gOutputImageFile, "wb");
+ if (OutputFile == NULL) {
+ fprintf(stderr, "Can't open output file %s.\n", gOutputImageFile);
+ exit(0);
+ }
+
+ // Write Configuration header
+ fwrite(gConfigurationHeader, 1, sizeof(gConfigurationHeader), OutputFile);
+
+ // Write image header (Input image size, execution address)
+ fwrite(&InputImageFileSize, 1, 4, OutputFile);
+ fwrite(&gImageExecutionAddress, 1, 4, OutputFile);
+
+ // Copy input image to the output file.
+ for (i = 0; i < InputImageFileSize; i++) {
+ fread(&Ch, 1, 1, InputFile);
+ fwrite(&Ch, 1, 1, OutputFile);
+ }
+
+ fclose(InputFile);
+ fclose(OutputFile);
+}
+
+
+int
+main (
+ int argc,
+ char** argv
+ )
+{
+ char Ch;
+ unsigned char *ptr;
+ int i;
+ int TwoArg;
+
+ if (argc == 1) {
+ PrintUsage ();
+ exit(1);
+ }
+
+ for (i=1; i < argc; i++) {
+ if (argv[i][0] == '-') {
+ // TwoArg TRUE -E 0x123, FALSE -E0x1234
+ TwoArg = (argv[i][2] != ' ');
+ switch (argv[i][1]) {
+ case 'E': /* Image execution address */
+ gImageExecutionAddress = strtoul (TwoArg ? argv[i+1] : &argv[i][2], (char **)&ptr, 16);
+ break;
+
+ case 'I': /* Input image file */
+ gInputImageFile = TwoArg ? argv[i+1] : &argv[i][2];
+ break;
+
+ case 'O': /* Output image file */
+ gOutputImageFile = TwoArg ? argv[i+1] : &argv[i][2];
+ break;
+
+ case 'D': /* Data file */
+ gDataFile = TwoArg ? argv[i+1] : &argv[i][2];
+ break;
+
+ default:
+ abort ();
+ }
+ }
+ }
+
+
+ //Prepare configuration header
+ PrepareConfigurationHeader ();
+
+ //Build image with configuration header + image header + image
+ ConstructImage ();
+
+ return 0;
+}
diff --git a/EmbeddedPkg/Ebl/Ebl.h b/EmbeddedPkg/Ebl/Ebl.h
index 03b4ba29f..44c44fb0f 100644
--- a/EmbeddedPkg/Ebl/Ebl.h
+++ b/EmbeddedPkg/Ebl/Ebl.h
@@ -1,207 +1,207 @@
-/** @file
- Include file for basic command line parser for EBL (Embedded Boot Loader)
-
- Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
- Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __EBL_H__
-#define __EBL_H__
-
-#include <PiDxe.h>
-#include <Protocol/BlockIo.h>
-#include <Protocol/SimpleFileSystem.h>
-#include <Protocol/FirmwareVolume2.h>
-#include <Protocol/LoadFile.h>
-#include <Protocol/FirmwareVolumeBlock.h>
-#include <Protocol/PxeBaseCode.h>
-#include <Protocol/LoadedImage.h>
-#include <Protocol/EblAddCommand.h>
-#include <Protocol/PciIo.h>
-#include <Protocol/DevicePath.h>
-
-#include <Guid/FileInfo.h>
-#include <Guid/DxeServices.h>
-#include <Guid/MemoryTypeInformation.h>
-#include <Guid/MemoryAllocationHob.h>
-#include <Library/BaseLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/PrintLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/DebugLib.h>
-#include <Library/EfiFileLib.h>
-#include <Library/HobLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/EblCmdLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/UefiLib.h>
-#include <Library/EblNetworkLib.h>
-#include <Library/TimerLib.h>
-
-#include <IndustryStandard/Pci.h>
-
-//
-// Prompt for the command line
-//
-#define CMD_SEPARATOR ';'
-#define EBL_MAX_COMMAND_COUNT 0x100
-#define MAX_CMD_HISTORY 16
-#define MAX_CMD_LINE 256
-#define MAX_ARGS 32
-
-#define EBL_CR 0x0a
-#define EBL_LF 0x0d
-
-#define EFI_SET_TIMER_TO_SECOND 10000000
-
-
-
-EBL_COMMAND_TABLE *
-EblGetCommand (
- IN CHAR8 *CommandName
- );
-
-
-EFI_STATUS
-EblPathToDevice (
- IN CHAR8 *Path,
- OUT EFI_HANDLE *DeviceHandle,
- OUT EFI_DEVICE_PATH_PROTOCOL **PathDevicePath,
- OUT VOID **Buffer,
- OUT UINTN *BufferSize
- );
-
-BOOLEAN
-EblAnyKeyToContinueQtoQuit (
- IN UINTN *CurrentRow,
- IN BOOLEAN PrefixNewline
- );
-
-VOID
-EblUpdateDeviceLists (
- VOID
- );
-
-VOID
-EblInitializeCmdTable (
- VOID
- );
-
-VOID
-EblShutdownExternalCmdTable (
- VOID
- );
-
-VOID
-EblSetTextColor (
- UINTN Attribute
- );
-
-
-EFI_STATUS
-EblGetCharKey (
- IN OUT EFI_INPUT_KEY *Key,
- IN UINTN TimoutInSec,
- IN EBL_GET_CHAR_CALL_BACK CallBack OPTIONAL
- );
-
-// BugBug: Move me to a library
-INTN
-EFIAPI
-AsciiStrniCmp (
- IN CONST CHAR8 *FirstString,
- IN CONST CHAR8 *SecondString,
- IN UINTN Length
- );
-
-
-VOID
-EblInitializeDeviceCmd (
- VOID
- );
-
-VOID
-EblInitializemdHwDebugCmds (
- VOID
- );
-
-VOID
-EblInitializeDirCmd (
- VOID
- );
-
-VOID
-EblInitializeHobCmd (
- VOID
- );
-
-VOID
-EblInitializemdHwIoDebugCmds (
- VOID
- );
-
-VOID
-EblInitializeScriptCmd (
- VOID
- );
-
-VOID
-EblInitializeNetworkCmd (
- VOID
- );
-
-VOID
-EblInitializeVariableCmds (
- VOID
- );
-
-CHAR8 *
-ParseArguments (
- IN CHAR8 *CmdLine,
- OUT UINTN *Argc,
- OUT CHAR8 **Argv
- );
-
-EFI_STATUS
-ProcessCmdLine (
- IN CHAR8 *CmdLine,
- IN UINTN MaxCmdLineSize
- );
-
-EFI_STATUS
-OutputData (
- IN UINT8 *Address,
- IN UINTN Length,
- IN UINTN Width,
- IN UINTN Offset
- );
-
-UINTN
-WidthFromCommandName (
- IN CHAR8 *Argv,
- IN UINTN Default
- );
-
-
-extern UINTN gScreenColumns;
-extern UINTN gScreenRows;
-extern BOOLEAN gPageBreak;
-extern CHAR8 *gMemMapType[];
-
-#endif
-
+/** @file
+ Include file for basic command line parser for EBL (Embedded Boot Loader)
+
+ Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
+ Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __EBL_H__
+#define __EBL_H__
+
+#include <PiDxe.h>
+#include <Protocol/BlockIo.h>
+#include <Protocol/SimpleFileSystem.h>
+#include <Protocol/FirmwareVolume2.h>
+#include <Protocol/LoadFile.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+#include <Protocol/PxeBaseCode.h>
+#include <Protocol/LoadedImage.h>
+#include <Protocol/EblAddCommand.h>
+#include <Protocol/PciIo.h>
+#include <Protocol/DevicePath.h>
+
+#include <Guid/FileInfo.h>
+#include <Guid/DxeServices.h>
+#include <Guid/MemoryTypeInformation.h>
+#include <Guid/MemoryAllocationHob.h>
+#include <Library/BaseLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/PrintLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/DebugLib.h>
+#include <Library/EfiFileLib.h>
+#include <Library/HobLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/EblCmdLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/UefiLib.h>
+#include <Library/EblNetworkLib.h>
+#include <Library/TimerLib.h>
+
+#include <IndustryStandard/Pci.h>
+
+//
+// Prompt for the command line
+//
+#define CMD_SEPARATOR ';'
+#define EBL_MAX_COMMAND_COUNT 0x100
+#define MAX_CMD_HISTORY 16
+#define MAX_CMD_LINE 256
+#define MAX_ARGS 32
+
+#define EBL_CR 0x0a
+#define EBL_LF 0x0d
+
+#define EFI_SET_TIMER_TO_SECOND 10000000
+
+
+
+EBL_COMMAND_TABLE *
+EblGetCommand (
+ IN CHAR8 *CommandName
+ );
+
+
+EFI_STATUS
+EblPathToDevice (
+ IN CHAR8 *Path,
+ OUT EFI_HANDLE *DeviceHandle,
+ OUT EFI_DEVICE_PATH_PROTOCOL **PathDevicePath,
+ OUT VOID **Buffer,
+ OUT UINTN *BufferSize
+ );
+
+BOOLEAN
+EblAnyKeyToContinueQtoQuit (
+ IN UINTN *CurrentRow,
+ IN BOOLEAN PrefixNewline
+ );
+
+VOID
+EblUpdateDeviceLists (
+ VOID
+ );
+
+VOID
+EblInitializeCmdTable (
+ VOID
+ );
+
+VOID
+EblShutdownExternalCmdTable (
+ VOID
+ );
+
+VOID
+EblSetTextColor (
+ UINTN Attribute
+ );
+
+
+EFI_STATUS
+EblGetCharKey (
+ IN OUT EFI_INPUT_KEY *Key,
+ IN UINTN TimoutInSec,
+ IN EBL_GET_CHAR_CALL_BACK CallBack OPTIONAL
+ );
+
+// BugBug: Move me to a library
+INTN
+EFIAPI
+AsciiStrniCmp (
+ IN CONST CHAR8 *FirstString,
+ IN CONST CHAR8 *SecondString,
+ IN UINTN Length
+ );
+
+
+VOID
+EblInitializeDeviceCmd (
+ VOID
+ );
+
+VOID
+EblInitializemdHwDebugCmds (
+ VOID
+ );
+
+VOID
+EblInitializeDirCmd (
+ VOID
+ );
+
+VOID
+EblInitializeHobCmd (
+ VOID
+ );
+
+VOID
+EblInitializemdHwIoDebugCmds (
+ VOID
+ );
+
+VOID
+EblInitializeScriptCmd (
+ VOID
+ );
+
+VOID
+EblInitializeNetworkCmd (
+ VOID
+ );
+
+VOID
+EblInitializeVariableCmds (
+ VOID
+ );
+
+CHAR8 *
+ParseArguments (
+ IN CHAR8 *CmdLine,
+ OUT UINTN *Argc,
+ OUT CHAR8 **Argv
+ );
+
+EFI_STATUS
+ProcessCmdLine (
+ IN CHAR8 *CmdLine,
+ IN UINTN MaxCmdLineSize
+ );
+
+EFI_STATUS
+OutputData (
+ IN UINT8 *Address,
+ IN UINTN Length,
+ IN UINTN Width,
+ IN UINTN Offset
+ );
+
+UINTN
+WidthFromCommandName (
+ IN CHAR8 *Argv,
+ IN UINTN Default
+ );
+
+
+extern UINTN gScreenColumns;
+extern UINTN gScreenRows;
+extern BOOLEAN gPageBreak;
+extern CHAR8 *gMemMapType[];
+
+#endif
+
diff --git a/EmbeddedPkg/EmbeddedPkg.dsc b/EmbeddedPkg/EmbeddedPkg.dsc
index 8862f3d1e..e1a4c225e 100644
--- a/EmbeddedPkg/EmbeddedPkg.dsc
+++ b/EmbeddedPkg/EmbeddedPkg.dsc
@@ -1,262 +1,262 @@
-#/** @file
-# Embedded Package
-#
-#
-# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-################################################################################
-#
-# Defines Section - statements that will be processed to create a Makefile.
-#
-################################################################################
-[Defines]
- PLATFORM_NAME = Embedded
- PLATFORM_GUID = 8DBB580B-CF89-4D57-95C6-DFE96C44686E
- PLATFORM_VERSION = 0.1
- DSC_SPECIFICATION = 0x00010005
- OUTPUT_DIRECTORY = Build/Embedded
- SUPPORTED_ARCHITECTURES = IA32|X64|IPF|ARM
- BUILD_TARGETS = DEBUG|RELEASE
- SKUID_IDENTIFIER = DEFAULT
- FLASH_DEFINITION = EmbeddedPkg/EmbeddedPkg.fdf
-
-
-################################################################################
-#
-# SKU Identification section - list of all SKU IDs supported by this
-# Platform.
-#
-################################################################################
-[SkuIds]
- 0|DEFAULT # The entry: 0|DEFAULT is reserved and always required.
-
-################################################################################
-#
-# Library Class section - list of all Library Classes needed by this Platform.
-#
-################################################################################
-[LibraryClasses.common]
-# DebugLib|MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf
- DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
-
-
- BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
- BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
- PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
- PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
- PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
- UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
- EfiFileLib|EmbeddedPkg/Library/EfiFileLib/EfiFileLib.inf
-
- TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
-
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf
-
- PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
- PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
- PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
- CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf
- PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
-
- SerialPortLib|EmbeddedPkg/Library/TemplateSerialPortLib/TemplateSerialPortLib.inf
- RealTimeClockLib|EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
- EfiResetSystemLib|EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
- GdbSerialLib|EmbeddedPkg/Library/GdbSerialLib/GdbSerialLib.inf
-
-
- #
- # Need to change this for IPF
- #
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
-
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
- UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
- HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
- UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
- DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
- UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
- ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
-
- DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
- UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
- UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
-
-
- PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
- EblCmdLib|EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
-
- EblNetworkLib|EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
-
-
-[LibraryClasses.common.DXE_DRIVER]
- PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
-
-
-[LibraryClasses.common.UEFI_APPLICATION]
- PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
-
-[LibraryClasses.common.UEFI_DRIVER]
- PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
- ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
-
-[LibraryClasses.common.SEC]
- ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
-
-[LibraryClasses.ARM]
- SemihostLib|ArmPkg/Library/SemihostLib/SemihostLib.inf
-
-[LibraryClasses.ARM]
- NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
-
-
-################################################################################
-#
-# Pcd Section - list of all PCD Entries defined by this Platform
-#
-################################################################################
-
-[PcdsFeatureFlag.common]
- gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|FALSE
- gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnosticsDisable|FALSE
- gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|FALSE
- gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|FALSE
-
- #
- # Control what commands are supported from the UI
- # Turn these on and off to add features or save size
- #
- gEmbeddedTokenSpaceGuid.PcdEmbeddedMacBoot|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedDirCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedHobCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedHwDebugCmd|TRUE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedIoEnable|FALSE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedScriptCmd|FALSE
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPciDebugCmd|TRUE
-
- gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob|FALSE
-
-
-[PcdsFixedAtBuild.common]
- gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000
- gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000
- gEfiMdePkgTokenSpaceGuid.PcdMaximumLinkedListLength|1000000
- gEfiMdePkgTokenSpaceGuid.PcdSpinLockTimeout|10000000
- gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x0f
- gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000
- gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x06
- gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue|0xAF
- gEfiMdePkgTokenSpaceGuid.PcdPerformanceLibraryPropertyMask|0
- gEfiMdePkgTokenSpaceGuid.PcdPostCodePropertyMask|0
- gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000
- gEfiMdePkgTokenSpaceGuid.PcdFSBClock|200000000
- gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|320
- gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000
- gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000
- gEfiMdePkgTokenSpaceGuid.PcdFSBClock|200000000
- gEmbeddedTokenSpaceGuid.PcdEmbeddedAutomaticBootCommand|L""|VOID*|2
- gEmbeddedTokenSpaceGuid.PcdEmbeddedDefaultTextColor|0x07
- gEmbeddedTokenSpaceGuid.PcdEmbeddedMemVariableStoreSize|0x10000
-
- gEmbeddedTokenSpaceGuid.PcdPrePiHobBase|0
- gEmbeddedTokenSpaceGuid.PcdPrePiStackBase|0
- gEmbeddedTokenSpaceGuid.PcdPrePiStackSize|0
-
-#
-# Optinal feature to help prevent EFI memory map fragments
-# Turned on and off via: PcdPrePiProduceMemoryTypeInformationHob
-# Values are in EFI Pages (4K). DXE Core will make sure that
-# at least this much of each type of memory can be allocated
-# from a single memory range. This way you only end up with
-# maximum of two fragements for each type in the memory map
-# (the memory used, and the free memory that was prereserved
-# but not used).
-#
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|0
- gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0
-
-#
-# Timer config for this platform
-#
- gEmbeddedTokenSpaceGuid.PcdTimerBaseAddress|0x3c700000
- gEmbeddedTokenSpaceGuid.PcdTimerVector|7
- gEmbeddedTokenSpaceGuid.PcdTimerPeriod|100000
-
-
-[PcdsFixedAtBuild.ARM]
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|32
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|0
-
-[PcdsFixedAtBuild.IA32]
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|36
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16
-
-[PcdsFixedAtBuild.X64]
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|52
- gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16
-
-
-
-[PcdsFixedAtBuild.IPF]
- gEfiMdePkgTokenSpaceGuid.PcdIoBlockBaseAddressForIpf|0x0ffffc000000
-
-#
-# This makes it so you can source level debug with NT32. VC++ debugger limitiation!
-#
-#[BuildOptions]
-# DEBUG_*_IA32_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /ALIGN:4096 /SUBSYSTEM:CONSOLE
-# RELEASE_*_IA32_DLINK_FLAGS = /ALIGN:4096
-# *_*_IA32_CC_FLAGS = /D EFI_SPECIFICATION_VERSION=0x0002000A /D TIANO_RELEASE_VERSION=0x00080006
-
-
-################################################################################
-#
-# Components Section - list of all Modules needed by this Platform
-#
-################################################################################
-[Components.common]
- EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
- EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
- EmbeddedPkg/Library/EfiFileLib/EfiFileLib.inf
- EmbeddedPkg/Library/GdbSerialDebugPortLib/GdbSerialDebugPortLib.inf
- EmbeddedPkg/Library/GdbSerialLib/GdbSerialLib.inf
- EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
- EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
- EmbeddedPkg/Library/TemplateSerialPortLib/TemplateSerialPortLib.inf
- EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
- EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
- EmbeddedPkg/Library/LzmaHobCustomDecompressLib/LzmaHobCustomDecompressLib.inf
- EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf
-
- EmbeddedPkg/Ebl/Ebl.inf
-#### EmbeddedPkg/EblExternCmd/EblExternCmd.inf
- EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
- EmbeddedPkg/GdbStub/GdbStub.inf
- EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
- EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
- EmbeddedPkg/SerialDxe/SerialDxe.inf
- EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
- EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
-
- EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
-
-
-
+#/** @file
+# Embedded Package
+#
+#
+# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+ PLATFORM_NAME = Embedded
+ PLATFORM_GUID = 8DBB580B-CF89-4D57-95C6-DFE96C44686E
+ PLATFORM_VERSION = 0.1
+ DSC_SPECIFICATION = 0x00010005
+ OUTPUT_DIRECTORY = Build/Embedded
+ SUPPORTED_ARCHITECTURES = IA32|X64|IPF|ARM
+ BUILD_TARGETS = DEBUG|RELEASE
+ SKUID_IDENTIFIER = DEFAULT
+ FLASH_DEFINITION = EmbeddedPkg/EmbeddedPkg.fdf
+
+
+################################################################################
+#
+# SKU Identification section - list of all SKU IDs supported by this
+# Platform.
+#
+################################################################################
+[SkuIds]
+ 0|DEFAULT # The entry: 0|DEFAULT is reserved and always required.
+
+################################################################################
+#
+# Library Class section - list of all Library Classes needed by this Platform.
+#
+################################################################################
+[LibraryClasses.common]
+# DebugLib|MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf
+ DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
+
+
+ BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+ PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
+ PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+ UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
+ EfiFileLib|EmbeddedPkg/Library/EfiFileLib/EfiFileLib.inf
+
+ TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
+
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf
+
+ PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+ PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+ PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
+ CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf
+ PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
+
+ SerialPortLib|EmbeddedPkg/Library/TemplateSerialPortLib/TemplateSerialPortLib.inf
+ RealTimeClockLib|EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
+ EfiResetSystemLib|EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
+ GdbSerialLib|EmbeddedPkg/Library/GdbSerialLib/GdbSerialLib.inf
+
+
+ #
+ # Need to change this for IPF
+ #
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
+ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+ UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
+ ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
+
+ DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
+ UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
+ UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
+
+
+ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+ EblCmdLib|EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
+
+ EblNetworkLib|EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
+
+
+[LibraryClasses.common.DXE_DRIVER]
+ PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+
+
+[LibraryClasses.common.UEFI_APPLICATION]
+ PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+
+[LibraryClasses.common.UEFI_DRIVER]
+ PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+ ReportStatusCodeLib|IntelFrameworkModulePkg/Library/DxeReportStatusCodeLibFramework/DxeReportStatusCodeLib.inf
+
+[LibraryClasses.common.SEC]
+ ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
+
+[LibraryClasses.ARM]
+ SemihostLib|ArmPkg/Library/SemihostLib/SemihostLib.inf
+
+[LibraryClasses.ARM]
+ NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
+
+
+################################################################################
+#
+# Pcd Section - list of all PCD Entries defined by this Platform
+#
+################################################################################
+
+[PcdsFeatureFlag.common]
+ gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|FALSE
+ gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnosticsDisable|FALSE
+ gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|FALSE
+ gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|FALSE
+
+ #
+ # Control what commands are supported from the UI
+ # Turn these on and off to add features or save size
+ #
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedMacBoot|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedDirCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedHobCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedHwDebugCmd|TRUE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedIoEnable|FALSE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedScriptCmd|FALSE
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPciDebugCmd|TRUE
+
+ gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob|FALSE
+
+
+[PcdsFixedAtBuild.common]
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumLinkedListLength|1000000
+ gEfiMdePkgTokenSpaceGuid.PcdSpinLockTimeout|10000000
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x0f
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000
+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x06
+ gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue|0xAF
+ gEfiMdePkgTokenSpaceGuid.PcdPerformanceLibraryPropertyMask|0
+ gEfiMdePkgTokenSpaceGuid.PcdPostCodePropertyMask|0
+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000
+ gEfiMdePkgTokenSpaceGuid.PcdFSBClock|200000000
+ gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|320
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000
+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000
+ gEfiMdePkgTokenSpaceGuid.PcdFSBClock|200000000
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedAutomaticBootCommand|L""|VOID*|2
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedDefaultTextColor|0x07
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedMemVariableStoreSize|0x10000
+
+ gEmbeddedTokenSpaceGuid.PcdPrePiHobBase|0
+ gEmbeddedTokenSpaceGuid.PcdPrePiStackBase|0
+ gEmbeddedTokenSpaceGuid.PcdPrePiStackSize|0
+
+#
+# Optinal feature to help prevent EFI memory map fragments
+# Turned on and off via: PcdPrePiProduceMemoryTypeInformationHob
+# Values are in EFI Pages (4K). DXE Core will make sure that
+# at least this much of each type of memory can be allocated
+# from a single memory range. This way you only end up with
+# maximum of two fragements for each type in the memory map
+# (the memory used, and the free memory that was prereserved
+# but not used).
+#
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|0
+ gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0
+
+#
+# Timer config for this platform
+#
+ gEmbeddedTokenSpaceGuid.PcdTimerBaseAddress|0x3c700000
+ gEmbeddedTokenSpaceGuid.PcdTimerVector|7
+ gEmbeddedTokenSpaceGuid.PcdTimerPeriod|100000
+
+
+[PcdsFixedAtBuild.ARM]
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|32
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|0
+
+[PcdsFixedAtBuild.IA32]
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|36
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16
+
+[PcdsFixedAtBuild.X64]
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuMemorySize|52
+ gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16
+
+
+
+[PcdsFixedAtBuild.IPF]
+ gEfiMdePkgTokenSpaceGuid.PcdIoBlockBaseAddressForIpf|0x0ffffc000000
+
+#
+# This makes it so you can source level debug with NT32. VC++ debugger limitiation!
+#
+#[BuildOptions]
+# DEBUG_*_IA32_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /ALIGN:4096 /SUBSYSTEM:CONSOLE
+# RELEASE_*_IA32_DLINK_FLAGS = /ALIGN:4096
+# *_*_IA32_CC_FLAGS = /D EFI_SPECIFICATION_VERSION=0x0002000A /D TIANO_RELEASE_VERSION=0x00080006
+
+
+################################################################################
+#
+# Components Section - list of all Modules needed by this Platform
+#
+################################################################################
+[Components.common]
+ EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
+ EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
+ EmbeddedPkg/Library/EfiFileLib/EfiFileLib.inf
+ EmbeddedPkg/Library/GdbSerialDebugPortLib/GdbSerialDebugPortLib.inf
+ EmbeddedPkg/Library/GdbSerialLib/GdbSerialLib.inf
+ EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
+ EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
+ EmbeddedPkg/Library/TemplateSerialPortLib/TemplateSerialPortLib.inf
+ EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
+ EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
+ EmbeddedPkg/Library/LzmaHobCustomDecompressLib/LzmaHobCustomDecompressLib.inf
+ EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf
+
+ EmbeddedPkg/Ebl/Ebl.inf
+#### EmbeddedPkg/EblExternCmd/EblExternCmd.inf
+ EmbeddedPkg/EmbeddedMonotonicCounter/EmbeddedMonotonicCounter.inf
+ EmbeddedPkg/GdbStub/GdbStub.inf
+ EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
+ EmbeddedPkg/ResetRuntimeDxe/ResetRuntimeDxe.inf
+ EmbeddedPkg/SerialDxe/SerialDxe.inf
+ EmbeddedPkg/SimpleTextInOutSerial/SimpleTextInOutSerial.inf
+ EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
+
+ EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
+
+
+
diff --git a/EmbeddedPkg/GdbStub/GdbStub.c b/EmbeddedPkg/GdbStub/GdbStub.c
index 742de505c..8a13cc8a1 100644
--- a/EmbeddedPkg/GdbStub/GdbStub.c
+++ b/EmbeddedPkg/GdbStub/GdbStub.c
@@ -1,1263 +1,1263 @@
-/** @file
- UEFI driver that implements a GDB stub
-
- Note: Any code in the path of the Serial IO output can not call DEBUG as will
- will blow out the stack. Serial IO calls DEBUG, debug calls Serail IO, ...
-
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <GdbStubInternal.h>
-#include <Protocol/DebugPort.h>
-
-
-UINTN gMaxProcessorIndex = 0;
-
-//
-// Buffers for basic gdb communication
-//
-CHAR8 gInBuffer[MAX_BUF_SIZE];
-CHAR8 gOutBuffer[MAX_BUF_SIZE];
-
-// Assume gdb does a "qXfer:libraries:read::offset,length" when it connects so we can default
-// this value to FALSE. Since gdb can reconnect its self a global default is not good enough
-BOOLEAN gSymbolTableUpdate = FALSE;
-EFI_EVENT gEvent;
-VOID *gGdbSymbolEventHandlerRegistration = NULL;
-
-//
-// Globals for returning XML from qXfer:libraries:read packet
-//
-UINTN gPacketqXferLibraryOffset = 0;
-UINTN gEfiDebugImageTableEntry = 0;
-EFI_DEBUG_IMAGE_INFO_TABLE_HEADER *gDebugImageTableHeader = NULL;
-EFI_DEBUG_IMAGE_INFO *gDebugTable = NULL;
-CHAR8 gXferLibraryBuffer[2000];
-
-GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 mHexToStr[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
-
-
-VOID
-EFIAPI
-GdbSymbolEventHandler (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
-}
-
-
-/**
- The user Entry Point for Application. The user code starts with this function
- as the real entry point for the image goes into a library that calls this
- function.
-
- @param[in] ImageHandle The firmware allocated handle for the EFI image.
- @param[in] SystemTable A pointer to the EFI System Table.
-
- @retval EFI_SUCCESS The entry point is executed successfully.
- @retval other Some error occurs when executing this entry point.
-
-**/
-EFI_STATUS
-EFIAPI
-GdbStubEntry (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-
-{
- EFI_STATUS Status;
- EFI_DEBUG_SUPPORT_PROTOCOL *DebugSupport;
- UINTN HandleCount;
- EFI_HANDLE *Handles;
- UINTN Index;
- UINTN Processor;
- BOOLEAN IsaSupported;
-
-
- Status = EfiGetSystemConfigurationTable (&gEfiDebugImageInfoTableGuid, (VOID **)&gDebugImageTableHeader);
- if (EFI_ERROR (Status)) {
- gDebugImageTableHeader = NULL;
- }
-
- Status = gBS->LocateHandleBuffer (
- ByProtocol,
- &gEfiDebugSupportProtocolGuid,
- NULL,
- &HandleCount,
- &Handles
- );
- if (EFI_ERROR (Status)) {
- DEBUG ((EFI_D_ERROR, "Debug Support Protocol not found\n"));
-
- return Status;
- }
-
- DebugSupport = NULL;
- IsaSupported = FALSE;
- do {
- HandleCount--;
- Status = gBS->HandleProtocol (
- Handles[HandleCount],
- &gEfiDebugSupportProtocolGuid,
- (VOID **) &DebugSupport
- );
- if (!EFI_ERROR (Status)) {
- if (CheckIsa (DebugSupport->Isa)) {
- // We found what we are looking for so break out of the loop
- IsaSupported = TRUE;
- break;
- }
- }
- } while (HandleCount > 0);
- FreePool (Handles);
-
- if (!IsaSupported) {
- DEBUG ((EFI_D_ERROR, "Debug Support Protocol does not support our ISA\n"));
-
- return EFI_NOT_FOUND;
- }
-
- Status = DebugSupport->GetMaximumProcessorIndex (DebugSupport, &gMaxProcessorIndex);
- ASSERT_EFI_ERROR (Status);
-
- DEBUG ((EFI_D_INFO, "Debug Support Protocol ISA %x\n", DebugSupport->Isa));
- DEBUG ((EFI_D_INFO, "Debug Support Protocol Processor Index %d\n", gMaxProcessorIndex));
-
- // Call processor-specific init routine
- InitializeProcessor();
-
- for (Processor = 0; Processor <= gMaxProcessorIndex; Processor++) {
-
- for (Index = 0; Index < MaxEfiException (); Index++) {
- Status = DebugSupport->RegisterExceptionCallback (DebugSupport, Processor, GdbExceptionHandler, gExceptionType[Index].Exception);
- ASSERT_EFI_ERROR (Status);
- }
- //
- // Current edk2 DebugPort is not interrupt context safe so we can not use it
- //
- Status = DebugSupport->RegisterPeriodicCallback (DebugSupport, Processor, GdbPeriodicCallBack);
- ASSERT_EFI_ERROR (Status);
- }
-
- //
- // This even fires every time an image is added. This allows the stub to know when gdb needs
- // to update the symbol table.
- //
- Status = gBS->CreateEvent (
- EVT_NOTIFY_SIGNAL,
- TPL_CALLBACK,
- GdbSymbolEventHandler,
- NULL,
- &gEvent
- );
- ASSERT_EFI_ERROR (Status);
-
- //
- // Register for protocol notifactions on this event
- //
- Status = gBS->RegisterProtocolNotify (
- &gEfiLoadedImageProtocolGuid,
- gEvent,
- &gGdbSymbolEventHandlerRegistration
- );
- ASSERT_EFI_ERROR (Status);
-
-
- if (PcdGetBool (PcdGdbSerial)) {
- GdbInitializeSerialConsole ();
- }
-
- return EFI_SUCCESS;
-}
-
-
-
-/**
- Transfer length bytes of input buffer, starting at Address, to memory.
-
- @param length the number of the bytes to be transferred/written
- @param *address the start address of the transferring/writing the memory
- @param *new_data the new data to be written to memory
- **/
-
-VOID
-TransferFromInBufToMem (
- IN UINTN Length,
- IN unsigned char *Address,
- IN CHAR8 *NewData
- )
-{
- CHAR8 c1;
- CHAR8 c2;
-
- while (Length-- > 0) {
- c1 = (CHAR8)HexCharToInt (*NewData++);
- c2 = (CHAR8)HexCharToInt (*NewData++);
-
- if ((c1 < 0) || (c2 < 0)) {
- Print ((CHAR16 *)L"Bad message from write to memory..\n");
- SendError (GDB_EBADMEMDATA);
- return;
- }
- *Address++ = (UINT8)((c1 << 4) + c2);
- }
-
- SendSuccess();
-}
-
-
-/**
- Transfer Length bytes of memory starting at Address to an output buffer, OutBuffer. This function will finally send the buffer
- as a packet.
-
- @param Length the number of the bytes to be transferred/read
- @param *address pointer to the start address of the transferring/reading the memory
- **/
-
-VOID
-TransferFromMemToOutBufAndSend (
- IN UINTN Length,
- IN unsigned char *Address
- )
-{
- // there are Length bytes and every byte is represented as 2 hex chars
- CHAR8 OutBuffer[MAX_BUF_SIZE];
- CHAR8 *OutBufPtr; // pointer to the output buffer
- CHAR8 Char;
-
- if (ValidateAddress(Address) == FALSE) {
- SendError(14);
- return;
- }
-
- OutBufPtr = OutBuffer;
- while (Length > 0) {
-
- Char = mHexToStr[*Address >> 4];
- if ((Char >= 'A') && (Char <= 'F')) {
- Char = Char - 'A' + 'a';
- }
- *OutBufPtr++ = Char;
-
- Char = mHexToStr[*Address & 0x0f];
- if ((Char >= 'A') && (Char <= 'F')) {
- Char = Char - 'A' + 'a';
- }
- *OutBufPtr++ = Char;
-
- Address++;
- Length--;
- }
-
- *OutBufPtr = '\0' ; // the end of the buffer
- SendPacket (OutBuffer);
-}
-
-
-
-/**
- Send a GDB Remote Serial Protocol Packet
-
- $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
- the packet teminating character '#' and the two digit checksum.
-
- If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
- in an infinit loop. This is so if you unplug the debugger code just keeps running
-
- @param PacketData Payload data for the packet
-
-
- @retval Number of bytes of packet data sent.
-
-**/
-UINTN
-SendPacket (
- IN CHAR8 *PacketData
- )
-{
- UINT8 CheckSum;
- UINTN Timeout;
- CHAR8 *Ptr;
- CHAR8 TestChar;
- UINTN Count;
-
- Timeout = PcdGet32 (PcdGdbMaxPacketRetryCount);
-
- Count = 0;
- do {
-
- Ptr = PacketData;
-
- if (Timeout-- == 0) {
- // Only try a finite number of times so we don't get stuck in the loop
- return Count;
- }
-
- // Packet prefix
- GdbPutChar ('$');
-
- for (CheckSum = 0, Count =0 ; *Ptr != '\0'; Ptr++, Count++) {
- GdbPutChar (*Ptr);
- CheckSum = CheckSum + *Ptr;
- }
-
- // Packet terminating character and checksum
- GdbPutChar ('#');
- GdbPutChar (mHexToStr[CheckSum >> 4]);
- GdbPutChar (mHexToStr[CheckSum & 0x0F]);
-
- TestChar = GdbGetChar ();
- } while (TestChar != '+');
-
- return Count;
-}
-
-/**
- Receive a GDB Remote Serial Protocol Packet
-
- $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
- the packet teminating character '#' and the two digit checksum.
-
- If host re-starts sending a packet without ending the previous packet, only the last valid packet is proccessed.
- (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
-
- If an ack '+' is not sent resend the packet
-
- @param PacketData Payload data for the packet
-
- @retval Number of bytes of packet data received.
-
-**/
-UINTN
-ReceivePacket (
- OUT CHAR8 *PacketData,
- IN UINTN PacketDataSize
- )
-{
- UINT8 CheckSum;
- UINTN Index;
- CHAR8 Char;
- CHAR8 SumString[3];
- CHAR8 TestChar;
-
- ZeroMem (PacketData, PacketDataSize);
-
- for (;;) {
- // wait for the start of a packet
- TestChar = GdbGetChar ();
- while (TestChar != '$') {
- TestChar = GdbGetChar ();
- };
-
- retry:
- for (Index = 0, CheckSum = 0; Index < (PacketDataSize - 1); Index++) {
- Char = GdbGetChar ();
- if (Char == '$') {
- goto retry;
- }
- if (Char == '#') {
- break;
- }
-
- PacketData[Index] = Char;
- CheckSum = CheckSum + Char;
- }
- PacketData[Index] = '\0';
-
- if (Index == PacketDataSize) {
- continue;
- }
-
- SumString[0] = GdbGetChar ();
- SumString[1] = GdbGetChar ();
- SumString[2] = '\0';
-
- if (AsciiStrHexToUintn (SumString) == CheckSum) {
- // Ack: Success
- GdbPutChar ('+');
-
- // Null terminate the callers string
- PacketData[Index] = '\0';
- return Index;
- } else {
- // Ack: Failure
- GdbPutChar ('-');
- }
- }
-
- //return 0;
-}
-
-
-/**
- Empties the given buffer
- @param Buf pointer to the first element in buffer to be emptied
- **/
-VOID
-EmptyBuffer (
- IN CHAR8 *Buf
- )
-{
- *Buf = '\0';
-}
-
-
-/**
- Converts an 8-bit Hex Char into a INTN.
-
- @param Char the hex character to be converted into UINTN
- @retval a INTN, from 0 to 15, that corressponds to Char
- -1 if Char is not a hex character
- **/
-INTN
-HexCharToInt (
- IN CHAR8 Char
- )
-{
- if ((Char >= 'A') && (Char <= 'F')) {
- return Char - 'A' + 10;
- } else if ((Char >= 'a') && (Char <= 'f')) {
- return Char - 'a' + 10;
- } else if ((Char >= '0') && (Char <= '9')) {
- return Char - '0';
- } else { // if not a hex value, return a negative value
- return -1;
- }
-}
-
- // 'E' + the biggest error number is 255, so its 2 hex digits + buffer end
-CHAR8 *gError = "E__";
-
-/** 'E NN'
- Send an error with the given error number after converting to hex.
- The error number is put into the buffer in hex. '255' is the biggest errno we can send.
- ex: 162 will be sent as A2.
-
- @param errno the error number that will be sent
- **/
-VOID
-EFIAPI
-SendError (
- IN UINT8 ErrorNum
- )
-{
- //
- // Replace _, or old data, with current errno
- //
- gError[1] = mHexToStr [ErrorNum >> 4];
- gError[2] = mHexToStr [ErrorNum & 0x0f];
-
- SendPacket (gError); // send buffer
-}
-
-
-
-/**
- Send 'OK' when the function is done executing successfully.
- **/
-VOID
-EFIAPI
-SendSuccess (
- VOID
- )
-{
- SendPacket ("OK"); // send buffer
-}
-
-
-/**
- Send empty packet to specify that particular command/functionality is not supported.
- **/
-VOID
-EFIAPI
-SendNotSupported (
- VOID
- )
-{
- SendPacket ("");
-}
-
-
-
-/**
- Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
-
- @param SystemContext Register content at time of the exception
- @param GdbExceptionType GDB exception type
- **/
-VOID
-GdbSendTSignal (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINT8 GdbExceptionType
- )
-{
- CHAR8 TSignalBuffer[128];
- CHAR8 *TSignalPtr;
- UINTN BreakpointDetected;
- BREAK_TYPE BreakType;
- UINTN DataAddress;
- CHAR8 *WatchStrPtr = NULL;
- UINTN RegSize;
-
- TSignalPtr = &TSignalBuffer[0];
-
- //Construct TSignal packet
- *TSignalPtr++ = 'T';
-
- //
- // replace _, or previous value, with Exception type
- //
- *TSignalPtr++ = mHexToStr [GdbExceptionType >> 4];
- *TSignalPtr++ = mHexToStr [GdbExceptionType & 0x0f];
-
- if (GdbExceptionType == GDB_SIGTRAP) {
- if (gSymbolTableUpdate) {
- //
- // We can only send back on reason code. So if the flag is set it means the breakpoint is from our event handler
- //
- WatchStrPtr = "library:;";
- while (*WatchStrPtr != '\0') {
- *TSignalPtr++ = *WatchStrPtr++;
- }
- gSymbolTableUpdate = FALSE;
- } else {
-
-
- //
- // possible n:r pairs
- //
-
- //Retrieve the breakpoint number
- BreakpointDetected = GetBreakpointDetected (SystemContext);
-
- //Figure out if the exception is happend due to watch, rwatch or awatch.
- BreakType = GetBreakpointType (SystemContext, BreakpointDetected);
-
- //INFO: rwatch is not supported due to the way IA32 debug registers work
- if ((BreakType == DataWrite) || (BreakType == DataRead) || (BreakType == DataReadWrite)) {
-
- //Construct n:r pair
- DataAddress = GetBreakpointDataAddress (SystemContext, BreakpointDetected);
-
- //Assign appropriate buffer to print particular watchpoint type
- if (BreakType == DataWrite) {
- WatchStrPtr = "watch";
- } else if (BreakType == DataRead) {
- WatchStrPtr = "rwatch";
- } else if (BreakType == DataReadWrite) {
- WatchStrPtr = "awatch";
- }
-
- while (*WatchStrPtr != '\0') {
- *TSignalPtr++ = *WatchStrPtr++;
- }
-
- *TSignalPtr++ = ':';
-
- //Set up series of bytes in big-endian byte order. "awatch" won't work with little-endian byte order.
- RegSize = REG_SIZE;
- while (RegSize > 0) {
- RegSize = RegSize-4;
- *TSignalPtr++ = mHexToStr[(UINT8)(DataAddress >> RegSize) & 0xf];
- }
-
- //Always end n:r pair with ';'
- *TSignalPtr++ = ';';
- }
- }
- }
-
- *TSignalPtr = '\0';
-
- SendPacket (TSignalBuffer);
-}
-
-
-/**
- Translates the EFI mapping to GDB mapping
-
- @param EFIExceptionType EFI Exception that is being processed
- @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
- **/
-UINT8
-ConvertEFItoGDBtype (
- IN EFI_EXCEPTION_TYPE EFIExceptionType
- )
-{
- UINTN i;
-
- for (i=0; i < MaxEfiException() ; i++) {
- if (gExceptionType[i].Exception == EFIExceptionType) {
- return gExceptionType[i].SignalNo;
- }
- }
- return GDB_SIGTRAP; // this is a GDB trap
-}
-
-
-/** "m addr,length"
- Find the Length of the area to read and the start addres. Finally, pass them to
- another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
- send it as a packet.
- **/
-
-VOID
-EFIAPI
-ReadFromMemory (
- CHAR8 *PacketData
- )
-{
- UINTN Address;
- UINTN Length;
- CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the address in hex chars
- CHAR8 *AddrBufPtr; // pointer to the address buffer
- CHAR8 *InBufPtr; /// pointer to the input buffer
-
- AddrBufPtr = AddressBuffer;
- InBufPtr = &PacketData[1];
- while (*InBufPtr != ',') {
- *AddrBufPtr++ = *InBufPtr++;
- }
- *AddrBufPtr = '\0';
-
- InBufPtr++; // this skips ',' in the buffer
-
- /* Error checking */
- if (AsciiStrLen(AddressBuffer) >= MAX_ADDR_SIZE) {
- Print((CHAR16 *)L"Address is too long\n");
- SendError (GDB_EBADMEMADDRBUFSIZE);
- return;
- }
-
- // 2 = 'm' + ','
- if (AsciiStrLen(PacketData) - AsciiStrLen(AddressBuffer) - 2 >= MAX_LENGTH_SIZE) {
- Print((CHAR16 *)L"Length is too long\n");
- SendError (GDB_EBADMEMLENGTH);
- return;
- }
-
- Address = AsciiStrHexToUintn (AddressBuffer);
- Length = AsciiStrHexToUintn (InBufPtr);
-
- TransferFromMemToOutBufAndSend (Length, (unsigned char *)Address);
-}
-
-
-/** "M addr,length :XX..."
- Find the Length of the area in bytes to write and the start addres. Finally, pass them to
- another function, TransferFromInBufToMem, that will write to that memory space the info in
- the input buffer.
- **/
-VOID
-EFIAPI
-WriteToMemory (
- IN CHAR8 *PacketData
- )
-{
- UINTN Address;
- UINTN Length;
- UINTN MessageLength;
- CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the Address in hex chars
- CHAR8 LengthBuffer[MAX_LENGTH_SIZE]; // the buffer that will hold the Length in hex chars
- CHAR8 *AddrBufPtr; // pointer to the Address buffer
- CHAR8 *LengthBufPtr; // pointer to the Length buffer
- CHAR8 *InBufPtr; /// pointer to the input buffer
-
- AddrBufPtr = AddressBuffer;
- LengthBufPtr = LengthBuffer;
- InBufPtr = &PacketData[1];
-
- while (*InBufPtr != ',') {
- *AddrBufPtr++ = *InBufPtr++;
- }
- *AddrBufPtr = '\0';
-
- InBufPtr++; // this skips ',' in the buffer
-
- while (*InBufPtr != ':') {
- *LengthBufPtr++ = *InBufPtr++;
- }
- *LengthBufPtr = '\0';
-
- InBufPtr++; // this skips ':' in the buffer
-
- Address = AsciiStrHexToUintn (AddressBuffer);
- Length = AsciiStrHexToUintn (LengthBuffer);
-
- /* Error checking */
-
- //Check if Address is not too long.
- if (AsciiStrLen(AddressBuffer) >= MAX_ADDR_SIZE) {
- Print ((CHAR16 *)L"Address too long..\n");
- SendError (GDB_EBADMEMADDRBUFSIZE);
- return;
- }
-
- //Check if message length is not too long
- if (AsciiStrLen(LengthBuffer) >= MAX_LENGTH_SIZE) {
- Print ((CHAR16 *)L"Length too long..\n");
- SendError (GDB_EBADMEMLENGBUFSIZE);
- return;
- }
-
- // Check if Message is not too long/short.
- // 3 = 'M' + ',' + ':'
- MessageLength = (AsciiStrLen(PacketData) - AsciiStrLen(AddressBuffer) - AsciiStrLen(LengthBuffer) - 3);
- if (MessageLength != (2*Length)) {
- //Message too long/short. New data is not the right size.
- SendError (GDB_EBADMEMDATASIZE);
- return;
- }
- TransferFromInBufToMem (Length, (unsigned char *)Address, InBufPtr);
-}
-
-/**
- Parses breakpoint packet data and captures Breakpoint type, Address and length.
- In case of an error, function returns particular error code. Returning 0 meaning
- no error.
-
- @param PacketData Pointer to the payload data for the packet.
- @param Type Breakpoint type
- @param Address Breakpoint address
- @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
-
- @retval 1 Success
- @retval {other} Particular error code
-
-**/
-UINTN
-ParseBreakpointPacket (
- IN CHAR8 *PacketData,
- OUT UINTN *Type,
- OUT UINTN *Address,
- OUT UINTN *Length
- )
-{
- CHAR8 AddressBuffer[MAX_ADDR_SIZE];
- CHAR8 *AddressBufferPtr;
- CHAR8 *PacketDataPtr;
-
- PacketDataPtr = &PacketData[1];
- AddressBufferPtr = AddressBuffer;
-
- *Type = AsciiStrHexToUintn (PacketDataPtr);
-
- //Breakpoint/watchpoint type should be between 0 to 4
- if (*Type > 4) {
- Print ((CHAR16 *)L"Type is invalid\n");
- return 22; //EINVAL: Invalid argument.
- }
-
- //Skip ',' in the buffer.
- while (*PacketDataPtr++ != ',');
-
- //Parse Address information
- while (*PacketDataPtr != ',') {
- *AddressBufferPtr++ = *PacketDataPtr++;
- }
- *AddressBufferPtr = '\0';
-
- //Check if Address is not too long.
- if (AsciiStrLen(AddressBuffer) >= MAX_ADDR_SIZE) {
- Print ((CHAR16 *)L"Address too long..\n");
- return 40; //EMSGSIZE: Message size too long.
- }
-
- *Address = AsciiStrHexToUintn (AddressBuffer);
-
- PacketDataPtr++; //This skips , in the buffer
-
- //Parse Length information
- *Length = AsciiStrHexToUintn (PacketDataPtr);
-
- //Length should be 1, 2 or 4 bytes
- if (*Length > 4) {
- Print ((CHAR16 *)L"Length is invalid\n");
- return 22; //EINVAL: Invalid argument
- }
-
- return 0; //0 = No error
-}
-
-UINTN
-gXferObjectReadResponse (
- IN CHAR8 Type,
- IN CHAR8 *Str
- )
-{
- CHAR8 *OutBufPtr; // pointer to the output buffer
- CHAR8 Char;
- UINTN Count;
-
- // responce starts with 'm' or 'l' if it is the end
- OutBufPtr = gOutBuffer;
- *OutBufPtr++ = Type;
- Count = 1;
-
- // Binary data encoding
- OutBufPtr = gOutBuffer;
- while (*Str != '\0') {
- Char = *Str++;
- if ((Char == 0x7d) || (Char == 0x23) || (Char == 0x24) || (Char == 0x2a)) {
- // escape character
- *OutBufPtr++ = 0x7d;
-
- Char ^= 0x20;
- }
- *OutBufPtr++ = Char;
- Count++;
- }
-
- *OutBufPtr = '\0' ; // the end of the buffer
- SendPacket (gOutBuffer);
-
- return Count;
-}
-
-
-/**
- Note: This should be a library function. In the Apple case you have to add
- the size of the PE/COFF header into the starting address to make things work
- right as there is no way to pad the Mach-O for the size of the PE/COFF header.
-
-
- Returns a pointer to the PDB file name for a PE/COFF image that has been
- loaded into system memory with the PE/COFF Loader Library functions.
-
- Returns the PDB file name for the PE/COFF image specified by Pe32Data. If
- the PE/COFF image specified by Pe32Data is not a valid, then NULL is
- returned. If the PE/COFF image specified by Pe32Data does not contain a
- debug directory entry, then NULL is returned. If the debug directory entry
- in the PE/COFF image specified by Pe32Data does not contain a PDB file name,
- then NULL is returned.
- If Pe32Data is NULL, then ASSERT().
-
- @param Pe32Data Pointer to the PE/COFF image that is loaded in system
- memory.
- @param DebugBase Address that the debugger would use as the base of the image
-
- @return The PDB file name for the PE/COFF image specified by Pe32Data or NULL
- if it cannot be retrieved. DebugBase is only valid if PDB file name is
- valid.
-
-**/
-VOID *
-EFIAPI
-PeCoffLoaderGetDebuggerInfo (
- IN VOID *Pe32Data,
- OUT VOID **DebugBase
- )
-{
- EFI_IMAGE_DOS_HEADER *DosHdr;
- EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
- EFI_IMAGE_DATA_DIRECTORY *DirectoryEntry;
- EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *DebugEntry;
- UINTN DirCount;
- VOID *CodeViewEntryPointer;
- INTN TEImageAdjust;
- UINT32 NumberOfRvaAndSizes;
- UINT16 Magic;
- UINTN SizeOfHeaders;
-
- ASSERT (Pe32Data != NULL);
-
- TEImageAdjust = 0;
- DirectoryEntry = NULL;
- DebugEntry = NULL;
- NumberOfRvaAndSizes = 0;
- SizeOfHeaders = 0;
-
- DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data;
- if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
- //
- // DOS image header is present, so read the PE header after the DOS image header.
- //
- Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff));
- } else {
- //
- // DOS image header is not present, so PE header is at the image base.
- //
- Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data;
- }
-
- if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
- if (Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress != 0) {
- DirectoryEntry = &Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG];
- TEImageAdjust = sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize;
- DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)((UINTN) Hdr.Te +
- Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress +
- TEImageAdjust);
- }
- SizeOfHeaders = sizeof (EFI_TE_IMAGE_HEADER) + (UINTN)Hdr.Te->BaseOfCode - (UINTN)Hdr.Te->StrippedSize;
-
- // __APPLE__ check this math...
- *DebugBase = ((CHAR8 *)Pe32Data) - TEImageAdjust;
- } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) {
-
- *DebugBase = Pe32Data;
-
-
- //
- // NOTE: We use Machine field to identify PE32/PE32+, instead of Magic.
- // It is due to backward-compatibility, for some system might
- // generate PE32+ image with PE32 Magic.
- //
- switch (Hdr.Pe32->FileHeader.Machine) {
- case EFI_IMAGE_MACHINE_IA32:
- //
- // Assume PE32 image with IA32 Machine field.
- //
- Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
- break;
- case EFI_IMAGE_MACHINE_X64:
- case EFI_IMAGE_MACHINE_IA64:
- //
- // Assume PE32+ image with X64 or IPF Machine field
- //
- Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
- break;
- default:
- //
- // For unknow Machine field, use Magic in optional Header
- //
- Magic = Hdr.Pe32->OptionalHeader.Magic;
- }
-
- if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
- //
- // Use PE32 offset get Debug Directory Entry
- //
- SizeOfHeaders = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
- NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
- DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
- DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) ((UINTN) Pe32Data + DirectoryEntry->VirtualAddress);
- } else if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
- //
- // Use PE32+ offset get Debug Directory Entry
- //
- SizeOfHeaders = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
- NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
- DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
- DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) ((UINTN) Pe32Data + DirectoryEntry->VirtualAddress);
- }
-
- if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
- DirectoryEntry = NULL;
- DebugEntry = NULL;
- }
- } else {
- return NULL;
- }
-
- if (DebugEntry == NULL || DirectoryEntry == NULL) {
- return NULL;
- }
-
- for (DirCount = 0; DirCount < DirectoryEntry->Size; DirCount += sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY), DebugEntry++) {
- if (DebugEntry->Type == EFI_IMAGE_DEBUG_TYPE_CODEVIEW) {
- if (DebugEntry->SizeOfData > 0) {
- CodeViewEntryPointer = (VOID *) ((UINTN) DebugEntry->RVA + ((UINTN)Pe32Data) + (UINTN)TEImageAdjust);
- switch (* (UINT32 *) CodeViewEntryPointer) {
- case CODEVIEW_SIGNATURE_NB10:
- return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY));
- case CODEVIEW_SIGNATURE_RSDS:
- return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY));
- case CODEVIEW_SIGNATURE_MTOC:
- *DebugBase = (VOID *)(UINTN)((UINTN)DebugBase - SizeOfHeaders);
- return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY));
- default:
- break;
- }
- }
- }
- }
-
- (void)SizeOfHeaders;
- return NULL;
-}
-
-
-
-/**
- Process "qXfer:object:read:annex:offset,length" request.
-
- Returns an XML document that contains loaded libraries. In our case it is
- infomration in the EFI Debug Inmage Table converted into an XML document.
-
- GDB will call with an arbitrary length (it can't know the real length and
- will reply with chunks of XML that are easy for us to deal with. Gdb will
- keep calling until we say we are done. XML doc looks like:
-
- <library-list>
- <library name="/a/a/c/d.dSYM"><segment address="0x10000000"/></library>
- <library name="/a/m/e/e.pdb"><segment address="0x20000000"/></library>
- <library name="/a/l/f/f.dll"><segment address="0x30000000"/></library>
- </library-list>
-
- Since we can not allocate memory in interupt context this module has
- assumptions about how it will get called:
- 1) Length will generally be max remote packet size (big enough)
- 2) First Offset of an XML document read needs to be 0
- 3) This code will return back small chunks of the XML document on every read.
- Each subseqent call will ask for the next availble part of the document.
-
- Note: The only variable size element in the XML is:
- " <library name=\"%s\"><segment address=\"%p\"/></library>\n" and it is
- based on the file path and name of the symbol file. If the symbol file name
- is bigger than the max gdb remote packet size we could update this code
- to respond back in chunks.
-
- @param Offset offset into special data area
- @param Length number of bytes to read starting at Offset
-
- **/
-VOID
-QxferLibrary (
- IN UINTN Offset,
- IN UINTN Length
- )
-{
- VOID *LoadAddress;
- CHAR8 *Pdb;
- UINTN Size;
-
- if (Offset != gPacketqXferLibraryOffset) {
- SendError (GDB_EINVALIDARG);
- Print (L"\nqXferLibrary (%d, %d) != %d\n", Offset, Length, gPacketqXferLibraryOffset);
-
- // Force a retry from the beginning
- gPacketqXferLibraryOffset = 0;
- return;
- }
-
- if (Offset == 0) {
- gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', "<library-list>\n");
-
- // The owner of the table may have had to ralloc it so grab a fresh copy every time
- // we assume qXferLibrary will get called over and over again until the entire XML table is
- // returned in a tight loop. Since we are in the debugger the table should not get updated
- gDebugTable = gDebugImageTableHeader->EfiDebugImageInfoTable;
- gEfiDebugImageTableEntry = 0;
- return;
- }
-
- if (gDebugTable != NULL) {
- for (; gEfiDebugImageTableEntry < gDebugImageTableHeader->TableSize; gEfiDebugImageTableEntry++, gDebugTable++) {
- if (gDebugTable->NormalImage != NULL) {
- if ((gDebugTable->NormalImage->ImageInfoType == EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL) &&
- (gDebugTable->NormalImage->LoadedImageProtocolInstance != NULL)) {
- Pdb = PeCoffLoaderGetDebuggerInfo (
- gDebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase,
- &LoadAddress
- );
- if (Pdb != NULL) {
- Size = AsciiSPrint (
- gXferLibraryBuffer,
- sizeof (gXferLibraryBuffer),
- " <library name=\"%a\"><segment address=\"0x%p\"/></library>\n",
- Pdb,
- LoadAddress
- );
- if ((Size != 0) && (Size != (sizeof (gXferLibraryBuffer) - 1))) {
- gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', gXferLibraryBuffer);
-
- // Update loop variables so we are in the right place when we get back
- gEfiDebugImageTableEntry++;
- gDebugTable++;
- return;
- } else {
- // We could handle <library> entires larger than sizeof (gXferLibraryBuffer) here if
- // needed by breaking up into N packets
- // "<library name=\"%s
- // the rest of the string (as many packets as required
- // \"><segment address=\"%d\"/></library> (fixed size)
- //
- // But right now we just skip any entry that is too big
- }
- }
- }
- }
- }
- }
-
-
- gXferObjectReadResponse ('l', "</library-list>\n");
- gPacketqXferLibraryOffset = 0;
- return;
-}
-
-
-/**
- Exception Hanldler for GDB. It will be called for all exceptions
- registered via the gExceptionType[] array.
-
- @param ExceptionType Exception that is being processed
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-GdbExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType,
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- UINT8 GdbExceptionType;
- CHAR8 *Ptr;
-
-
- if (ValidateException(ExceptionType, SystemContext) == FALSE) {
- return;
- }
-
- RemoveSingleStep (SystemContext);
-
- GdbExceptionType = ConvertEFItoGDBtype (ExceptionType);
- GdbSendTSignal (SystemContext, GdbExceptionType);
-
- for( ; ; ) {
- ReceivePacket (gInBuffer, MAX_BUF_SIZE);
-
- switch (gInBuffer[0]) {
- case '?':
- GdbSendTSignal (SystemContext, GdbExceptionType);
- break;
-
- case 'c':
- ContinueAtAddress (SystemContext, gInBuffer);
- return;
-
- case 'g':
- ReadGeneralRegisters (SystemContext);
- break;
-
- case 'G':
- WriteGeneralRegisters (SystemContext, gInBuffer);
- break;
-
- case 'H':
- //Return "OK" packet since we don't have more than one thread.
- SendSuccess ();
- break;
-
- case 'm':
- ReadFromMemory (gInBuffer);
- break;
-
- case 'M':
- WriteToMemory (gInBuffer);
- break;
-
- case 'P':
- WriteNthRegister (SystemContext, gInBuffer);
- break;
-
- //
- // Still debugging this code. Not used in Darwin
- //
- case 'q':
- // General Query Packets
- if (AsciiStrnCmp (gInBuffer, "qSupported", 10) == 0) {
- // return what we currently support, we don't parse what gdb suports
- AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "qXfer:libraries:read+;PacketSize=%d", MAX_BUF_SIZE);
- SendPacket (gOutBuffer);
- } else if (AsciiStrnCmp (gInBuffer, "qXfer:libraries:read::", 22) == 0) {
- // ‘qXfer:libraries:read::offset,length
- // gInBuffer[22] is offset string, ++Ptr is length string’
- for (Ptr = &gInBuffer[22]; *Ptr != ','; Ptr++);
-
- // Not sure if multi-radix support is required. Currently only support decimal
- QxferLibrary (AsciiStrHexToUintn (&gInBuffer[22]), AsciiStrHexToUintn (++Ptr));
- } if (AsciiStrnCmp (gInBuffer, "qOffsets", 10) == 0) {
- AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "Text=1000;Data=f000;Bss=f000");
- SendPacket (gOutBuffer);
- } else {
- //Send empty packet
- SendNotSupported ();
- }
- break;
-
- case 's':
- SingleStep (SystemContext, gInBuffer);
- return;
-
- case 'z':
- RemoveBreakPoint (SystemContext, gInBuffer);
- break;
-
- case 'Z':
- InsertBreakPoint (SystemContext, gInBuffer);
- break;
-
- default:
- //Send empty packet
- SendNotSupported ();
- break;
- }
- }
-}
-
-
-/**
- Periodic callback for GDB. This function is used to catch a ctrl-c or other
- break in type command from GDB.
-
- @param SystemContext Register content at time of the call
- **/
-VOID
-EFIAPI
-GdbPeriodicCallBack (
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- //
- // gCtrlCBreakFlag may have been set from a previous F response package
- // and we set the global as we need to process it at a point where we
- // can update the system context. If we are in the middle of processing
- // a F Packet it is not safe to read the GDB serial stream so we need
- // to skip it on this check
- //
- if (!gCtrlCBreakFlag && !gProcessingFPacket) {
- //
- // Ctrl-C was not pending so grab any pending characters and see if they
- // are a Ctrl-c (0x03). If so set the Ctrl-C global.
- //
- while (TRUE) {
- if (!GdbIsCharAvailable ()) {
- //
- // No characters are pending so exit the loop
- //
- break;
- }
-
- if (GdbGetChar () == 0x03) {
- gCtrlCBreakFlag = TRUE;
- //
- // We have a ctrl-c so exit the loop
- //
- break;
- }
- }
- }
-
- if (gCtrlCBreakFlag) {
- //
- // Update the context to force a single step trap when we exit the GDB
- // stub. This will trasfer control to GdbExceptionHandler () and let
- // us break into the program. We don't want to break into the GDB stub.
- //
- AddSingleStep (SystemContext);
- gCtrlCBreakFlag = FALSE;
- }
-}
+/** @file
+ UEFI driver that implements a GDB stub
+
+ Note: Any code in the path of the Serial IO output can not call DEBUG as will
+ will blow out the stack. Serial IO calls DEBUG, debug calls Serail IO, ...
+
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <GdbStubInternal.h>
+#include <Protocol/DebugPort.h>
+
+
+UINTN gMaxProcessorIndex = 0;
+
+//
+// Buffers for basic gdb communication
+//
+CHAR8 gInBuffer[MAX_BUF_SIZE];
+CHAR8 gOutBuffer[MAX_BUF_SIZE];
+
+// Assume gdb does a "qXfer:libraries:read::offset,length" when it connects so we can default
+// this value to FALSE. Since gdb can reconnect its self a global default is not good enough
+BOOLEAN gSymbolTableUpdate = FALSE;
+EFI_EVENT gEvent;
+VOID *gGdbSymbolEventHandlerRegistration = NULL;
+
+//
+// Globals for returning XML from qXfer:libraries:read packet
+//
+UINTN gPacketqXferLibraryOffset = 0;
+UINTN gEfiDebugImageTableEntry = 0;
+EFI_DEBUG_IMAGE_INFO_TABLE_HEADER *gDebugImageTableHeader = NULL;
+EFI_DEBUG_IMAGE_INFO *gDebugTable = NULL;
+CHAR8 gXferLibraryBuffer[2000];
+
+GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 mHexToStr[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
+
+
+VOID
+EFIAPI
+GdbSymbolEventHandler (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+}
+
+
+/**
+ The user Entry Point for Application. The user code starts with this function
+ as the real entry point for the image goes into a library that calls this
+ function.
+
+ @param[in] ImageHandle The firmware allocated handle for the EFI image.
+ @param[in] SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+ @retval other Some error occurs when executing this entry point.
+
+**/
+EFI_STATUS
+EFIAPI
+GdbStubEntry (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+
+{
+ EFI_STATUS Status;
+ EFI_DEBUG_SUPPORT_PROTOCOL *DebugSupport;
+ UINTN HandleCount;
+ EFI_HANDLE *Handles;
+ UINTN Index;
+ UINTN Processor;
+ BOOLEAN IsaSupported;
+
+
+ Status = EfiGetSystemConfigurationTable (&gEfiDebugImageInfoTableGuid, (VOID **)&gDebugImageTableHeader);
+ if (EFI_ERROR (Status)) {
+ gDebugImageTableHeader = NULL;
+ }
+
+ Status = gBS->LocateHandleBuffer (
+ ByProtocol,
+ &gEfiDebugSupportProtocolGuid,
+ NULL,
+ &HandleCount,
+ &Handles
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((EFI_D_ERROR, "Debug Support Protocol not found\n"));
+
+ return Status;
+ }
+
+ DebugSupport = NULL;
+ IsaSupported = FALSE;
+ do {
+ HandleCount--;
+ Status = gBS->HandleProtocol (
+ Handles[HandleCount],
+ &gEfiDebugSupportProtocolGuid,
+ (VOID **) &DebugSupport
+ );
+ if (!EFI_ERROR (Status)) {
+ if (CheckIsa (DebugSupport->Isa)) {
+ // We found what we are looking for so break out of the loop
+ IsaSupported = TRUE;
+ break;
+ }
+ }
+ } while (HandleCount > 0);
+ FreePool (Handles);
+
+ if (!IsaSupported) {
+ DEBUG ((EFI_D_ERROR, "Debug Support Protocol does not support our ISA\n"));
+
+ return EFI_NOT_FOUND;
+ }
+
+ Status = DebugSupport->GetMaximumProcessorIndex (DebugSupport, &gMaxProcessorIndex);
+ ASSERT_EFI_ERROR (Status);
+
+ DEBUG ((EFI_D_INFO, "Debug Support Protocol ISA %x\n", DebugSupport->Isa));
+ DEBUG ((EFI_D_INFO, "Debug Support Protocol Processor Index %d\n", gMaxProcessorIndex));
+
+ // Call processor-specific init routine
+ InitializeProcessor();
+
+ for (Processor = 0; Processor <= gMaxProcessorIndex; Processor++) {
+
+ for (Index = 0; Index < MaxEfiException (); Index++) {
+ Status = DebugSupport->RegisterExceptionCallback (DebugSupport, Processor, GdbExceptionHandler, gExceptionType[Index].Exception);
+ ASSERT_EFI_ERROR (Status);
+ }
+ //
+ // Current edk2 DebugPort is not interrupt context safe so we can not use it
+ //
+ Status = DebugSupport->RegisterPeriodicCallback (DebugSupport, Processor, GdbPeriodicCallBack);
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ //
+ // This even fires every time an image is added. This allows the stub to know when gdb needs
+ // to update the symbol table.
+ //
+ Status = gBS->CreateEvent (
+ EVT_NOTIFY_SIGNAL,
+ TPL_CALLBACK,
+ GdbSymbolEventHandler,
+ NULL,
+ &gEvent
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Register for protocol notifactions on this event
+ //
+ Status = gBS->RegisterProtocolNotify (
+ &gEfiLoadedImageProtocolGuid,
+ gEvent,
+ &gGdbSymbolEventHandlerRegistration
+ );
+ ASSERT_EFI_ERROR (Status);
+
+
+ if (PcdGetBool (PcdGdbSerial)) {
+ GdbInitializeSerialConsole ();
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+
+/**
+ Transfer length bytes of input buffer, starting at Address, to memory.
+
+ @param length the number of the bytes to be transferred/written
+ @param *address the start address of the transferring/writing the memory
+ @param *new_data the new data to be written to memory
+ **/
+
+VOID
+TransferFromInBufToMem (
+ IN UINTN Length,
+ IN unsigned char *Address,
+ IN CHAR8 *NewData
+ )
+{
+ CHAR8 c1;
+ CHAR8 c2;
+
+ while (Length-- > 0) {
+ c1 = (CHAR8)HexCharToInt (*NewData++);
+ c2 = (CHAR8)HexCharToInt (*NewData++);
+
+ if ((c1 < 0) || (c2 < 0)) {
+ Print ((CHAR16 *)L"Bad message from write to memory..\n");
+ SendError (GDB_EBADMEMDATA);
+ return;
+ }
+ *Address++ = (UINT8)((c1 << 4) + c2);
+ }
+
+ SendSuccess();
+}
+
+
+/**
+ Transfer Length bytes of memory starting at Address to an output buffer, OutBuffer. This function will finally send the buffer
+ as a packet.
+
+ @param Length the number of the bytes to be transferred/read
+ @param *address pointer to the start address of the transferring/reading the memory
+ **/
+
+VOID
+TransferFromMemToOutBufAndSend (
+ IN UINTN Length,
+ IN unsigned char *Address
+ )
+{
+ // there are Length bytes and every byte is represented as 2 hex chars
+ CHAR8 OutBuffer[MAX_BUF_SIZE];
+ CHAR8 *OutBufPtr; // pointer to the output buffer
+ CHAR8 Char;
+
+ if (ValidateAddress(Address) == FALSE) {
+ SendError(14);
+ return;
+ }
+
+ OutBufPtr = OutBuffer;
+ while (Length > 0) {
+
+ Char = mHexToStr[*Address >> 4];
+ if ((Char >= 'A') && (Char <= 'F')) {
+ Char = Char - 'A' + 'a';
+ }
+ *OutBufPtr++ = Char;
+
+ Char = mHexToStr[*Address & 0x0f];
+ if ((Char >= 'A') && (Char <= 'F')) {
+ Char = Char - 'A' + 'a';
+ }
+ *OutBufPtr++ = Char;
+
+ Address++;
+ Length--;
+ }
+
+ *OutBufPtr = '\0' ; // the end of the buffer
+ SendPacket (OutBuffer);
+}
+
+
+
+/**
+ Send a GDB Remote Serial Protocol Packet
+
+ $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
+ the packet teminating character '#' and the two digit checksum.
+
+ If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
+ in an infinit loop. This is so if you unplug the debugger code just keeps running
+
+ @param PacketData Payload data for the packet
+
+
+ @retval Number of bytes of packet data sent.
+
+**/
+UINTN
+SendPacket (
+ IN CHAR8 *PacketData
+ )
+{
+ UINT8 CheckSum;
+ UINTN Timeout;
+ CHAR8 *Ptr;
+ CHAR8 TestChar;
+ UINTN Count;
+
+ Timeout = PcdGet32 (PcdGdbMaxPacketRetryCount);
+
+ Count = 0;
+ do {
+
+ Ptr = PacketData;
+
+ if (Timeout-- == 0) {
+ // Only try a finite number of times so we don't get stuck in the loop
+ return Count;
+ }
+
+ // Packet prefix
+ GdbPutChar ('$');
+
+ for (CheckSum = 0, Count =0 ; *Ptr != '\0'; Ptr++, Count++) {
+ GdbPutChar (*Ptr);
+ CheckSum = CheckSum + *Ptr;
+ }
+
+ // Packet terminating character and checksum
+ GdbPutChar ('#');
+ GdbPutChar (mHexToStr[CheckSum >> 4]);
+ GdbPutChar (mHexToStr[CheckSum & 0x0F]);
+
+ TestChar = GdbGetChar ();
+ } while (TestChar != '+');
+
+ return Count;
+}
+
+/**
+ Receive a GDB Remote Serial Protocol Packet
+
+ $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
+ the packet teminating character '#' and the two digit checksum.
+
+ If host re-starts sending a packet without ending the previous packet, only the last valid packet is proccessed.
+ (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
+
+ If an ack '+' is not sent resend the packet
+
+ @param PacketData Payload data for the packet
+
+ @retval Number of bytes of packet data received.
+
+**/
+UINTN
+ReceivePacket (
+ OUT CHAR8 *PacketData,
+ IN UINTN PacketDataSize
+ )
+{
+ UINT8 CheckSum;
+ UINTN Index;
+ CHAR8 Char;
+ CHAR8 SumString[3];
+ CHAR8 TestChar;
+
+ ZeroMem (PacketData, PacketDataSize);
+
+ for (;;) {
+ // wait for the start of a packet
+ TestChar = GdbGetChar ();
+ while (TestChar != '$') {
+ TestChar = GdbGetChar ();
+ };
+
+ retry:
+ for (Index = 0, CheckSum = 0; Index < (PacketDataSize - 1); Index++) {
+ Char = GdbGetChar ();
+ if (Char == '$') {
+ goto retry;
+ }
+ if (Char == '#') {
+ break;
+ }
+
+ PacketData[Index] = Char;
+ CheckSum = CheckSum + Char;
+ }
+ PacketData[Index] = '\0';
+
+ if (Index == PacketDataSize) {
+ continue;
+ }
+
+ SumString[0] = GdbGetChar ();
+ SumString[1] = GdbGetChar ();
+ SumString[2] = '\0';
+
+ if (AsciiStrHexToUintn (SumString) == CheckSum) {
+ // Ack: Success
+ GdbPutChar ('+');
+
+ // Null terminate the callers string
+ PacketData[Index] = '\0';
+ return Index;
+ } else {
+ // Ack: Failure
+ GdbPutChar ('-');
+ }
+ }
+
+ //return 0;
+}
+
+
+/**
+ Empties the given buffer
+ @param Buf pointer to the first element in buffer to be emptied
+ **/
+VOID
+EmptyBuffer (
+ IN CHAR8 *Buf
+ )
+{
+ *Buf = '\0';
+}
+
+
+/**
+ Converts an 8-bit Hex Char into a INTN.
+
+ @param Char the hex character to be converted into UINTN
+ @retval a INTN, from 0 to 15, that corressponds to Char
+ -1 if Char is not a hex character
+ **/
+INTN
+HexCharToInt (
+ IN CHAR8 Char
+ )
+{
+ if ((Char >= 'A') && (Char <= 'F')) {
+ return Char - 'A' + 10;
+ } else if ((Char >= 'a') && (Char <= 'f')) {
+ return Char - 'a' + 10;
+ } else if ((Char >= '0') && (Char <= '9')) {
+ return Char - '0';
+ } else { // if not a hex value, return a negative value
+ return -1;
+ }
+}
+
+ // 'E' + the biggest error number is 255, so its 2 hex digits + buffer end
+CHAR8 *gError = "E__";
+
+/** 'E NN'
+ Send an error with the given error number after converting to hex.
+ The error number is put into the buffer in hex. '255' is the biggest errno we can send.
+ ex: 162 will be sent as A2.
+
+ @param errno the error number that will be sent
+ **/
+VOID
+EFIAPI
+SendError (
+ IN UINT8 ErrorNum
+ )
+{
+ //
+ // Replace _, or old data, with current errno
+ //
+ gError[1] = mHexToStr [ErrorNum >> 4];
+ gError[2] = mHexToStr [ErrorNum & 0x0f];
+
+ SendPacket (gError); // send buffer
+}
+
+
+
+/**
+ Send 'OK' when the function is done executing successfully.
+ **/
+VOID
+EFIAPI
+SendSuccess (
+ VOID
+ )
+{
+ SendPacket ("OK"); // send buffer
+}
+
+
+/**
+ Send empty packet to specify that particular command/functionality is not supported.
+ **/
+VOID
+EFIAPI
+SendNotSupported (
+ VOID
+ )
+{
+ SendPacket ("");
+}
+
+
+
+/**
+ Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
+
+ @param SystemContext Register content at time of the exception
+ @param GdbExceptionType GDB exception type
+ **/
+VOID
+GdbSendTSignal (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINT8 GdbExceptionType
+ )
+{
+ CHAR8 TSignalBuffer[128];
+ CHAR8 *TSignalPtr;
+ UINTN BreakpointDetected;
+ BREAK_TYPE BreakType;
+ UINTN DataAddress;
+ CHAR8 *WatchStrPtr = NULL;
+ UINTN RegSize;
+
+ TSignalPtr = &TSignalBuffer[0];
+
+ //Construct TSignal packet
+ *TSignalPtr++ = 'T';
+
+ //
+ // replace _, or previous value, with Exception type
+ //
+ *TSignalPtr++ = mHexToStr [GdbExceptionType >> 4];
+ *TSignalPtr++ = mHexToStr [GdbExceptionType & 0x0f];
+
+ if (GdbExceptionType == GDB_SIGTRAP) {
+ if (gSymbolTableUpdate) {
+ //
+ // We can only send back on reason code. So if the flag is set it means the breakpoint is from our event handler
+ //
+ WatchStrPtr = "library:;";
+ while (*WatchStrPtr != '\0') {
+ *TSignalPtr++ = *WatchStrPtr++;
+ }
+ gSymbolTableUpdate = FALSE;
+ } else {
+
+
+ //
+ // possible n:r pairs
+ //
+
+ //Retrieve the breakpoint number
+ BreakpointDetected = GetBreakpointDetected (SystemContext);
+
+ //Figure out if the exception is happend due to watch, rwatch or awatch.
+ BreakType = GetBreakpointType (SystemContext, BreakpointDetected);
+
+ //INFO: rwatch is not supported due to the way IA32 debug registers work
+ if ((BreakType == DataWrite) || (BreakType == DataRead) || (BreakType == DataReadWrite)) {
+
+ //Construct n:r pair
+ DataAddress = GetBreakpointDataAddress (SystemContext, BreakpointDetected);
+
+ //Assign appropriate buffer to print particular watchpoint type
+ if (BreakType == DataWrite) {
+ WatchStrPtr = "watch";
+ } else if (BreakType == DataRead) {
+ WatchStrPtr = "rwatch";
+ } else if (BreakType == DataReadWrite) {
+ WatchStrPtr = "awatch";
+ }
+
+ while (*WatchStrPtr != '\0') {
+ *TSignalPtr++ = *WatchStrPtr++;
+ }
+
+ *TSignalPtr++ = ':';
+
+ //Set up series of bytes in big-endian byte order. "awatch" won't work with little-endian byte order.
+ RegSize = REG_SIZE;
+ while (RegSize > 0) {
+ RegSize = RegSize-4;
+ *TSignalPtr++ = mHexToStr[(UINT8)(DataAddress >> RegSize) & 0xf];
+ }
+
+ //Always end n:r pair with ';'
+ *TSignalPtr++ = ';';
+ }
+ }
+ }
+
+ *TSignalPtr = '\0';
+
+ SendPacket (TSignalBuffer);
+}
+
+
+/**
+ Translates the EFI mapping to GDB mapping
+
+ @param EFIExceptionType EFI Exception that is being processed
+ @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
+ **/
+UINT8
+ConvertEFItoGDBtype (
+ IN EFI_EXCEPTION_TYPE EFIExceptionType
+ )
+{
+ UINTN i;
+
+ for (i=0; i < MaxEfiException() ; i++) {
+ if (gExceptionType[i].Exception == EFIExceptionType) {
+ return gExceptionType[i].SignalNo;
+ }
+ }
+ return GDB_SIGTRAP; // this is a GDB trap
+}
+
+
+/** "m addr,length"
+ Find the Length of the area to read and the start addres. Finally, pass them to
+ another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
+ send it as a packet.
+ **/
+
+VOID
+EFIAPI
+ReadFromMemory (
+ CHAR8 *PacketData
+ )
+{
+ UINTN Address;
+ UINTN Length;
+ CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the address in hex chars
+ CHAR8 *AddrBufPtr; // pointer to the address buffer
+ CHAR8 *InBufPtr; /// pointer to the input buffer
+
+ AddrBufPtr = AddressBuffer;
+ InBufPtr = &PacketData[1];
+ while (*InBufPtr != ',') {
+ *AddrBufPtr++ = *InBufPtr++;
+ }
+ *AddrBufPtr = '\0';
+
+ InBufPtr++; // this skips ',' in the buffer
+
+ /* Error checking */
+ if (AsciiStrLen(AddressBuffer) >= MAX_ADDR_SIZE) {
+ Print((CHAR16 *)L"Address is too long\n");
+ SendError (GDB_EBADMEMADDRBUFSIZE);
+ return;
+ }
+
+ // 2 = 'm' + ','
+ if (AsciiStrLen(PacketData) - AsciiStrLen(AddressBuffer) - 2 >= MAX_LENGTH_SIZE) {
+ Print((CHAR16 *)L"Length is too long\n");
+ SendError (GDB_EBADMEMLENGTH);
+ return;
+ }
+
+ Address = AsciiStrHexToUintn (AddressBuffer);
+ Length = AsciiStrHexToUintn (InBufPtr);
+
+ TransferFromMemToOutBufAndSend (Length, (unsigned char *)Address);
+}
+
+
+/** "M addr,length :XX..."
+ Find the Length of the area in bytes to write and the start addres. Finally, pass them to
+ another function, TransferFromInBufToMem, that will write to that memory space the info in
+ the input buffer.
+ **/
+VOID
+EFIAPI
+WriteToMemory (
+ IN CHAR8 *PacketData
+ )
+{
+ UINTN Address;
+ UINTN Length;
+ UINTN MessageLength;
+ CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the Address in hex chars
+ CHAR8 LengthBuffer[MAX_LENGTH_SIZE]; // the buffer that will hold the Length in hex chars
+ CHAR8 *AddrBufPtr; // pointer to the Address buffer
+ CHAR8 *LengthBufPtr; // pointer to the Length buffer
+ CHAR8 *InBufPtr; /// pointer to the input buffer
+
+ AddrBufPtr = AddressBuffer;
+ LengthBufPtr = LengthBuffer;
+ InBufPtr = &PacketData[1];
+
+ while (*InBufPtr != ',') {
+ *AddrBufPtr++ = *InBufPtr++;
+ }
+ *AddrBufPtr = '\0';
+
+ InBufPtr++; // this skips ',' in the buffer
+
+ while (*InBufPtr != ':') {
+ *LengthBufPtr++ = *InBufPtr++;
+ }
+ *LengthBufPtr = '\0';
+
+ InBufPtr++; // this skips ':' in the buffer
+
+ Address = AsciiStrHexToUintn (AddressBuffer);
+ Length = AsciiStrHexToUintn (LengthBuffer);
+
+ /* Error checking */
+
+ //Check if Address is not too long.
+ if (AsciiStrLen(AddressBuffer) >= MAX_ADDR_SIZE) {
+ Print ((CHAR16 *)L"Address too long..\n");
+ SendError (GDB_EBADMEMADDRBUFSIZE);
+ return;
+ }
+
+ //Check if message length is not too long
+ if (AsciiStrLen(LengthBuffer) >= MAX_LENGTH_SIZE) {
+ Print ((CHAR16 *)L"Length too long..\n");
+ SendError (GDB_EBADMEMLENGBUFSIZE);
+ return;
+ }
+
+ // Check if Message is not too long/short.
+ // 3 = 'M' + ',' + ':'
+ MessageLength = (AsciiStrLen(PacketData) - AsciiStrLen(AddressBuffer) - AsciiStrLen(LengthBuffer) - 3);
+ if (MessageLength != (2*Length)) {
+ //Message too long/short. New data is not the right size.
+ SendError (GDB_EBADMEMDATASIZE);
+ return;
+ }
+ TransferFromInBufToMem (Length, (unsigned char *)Address, InBufPtr);
+}
+
+/**
+ Parses breakpoint packet data and captures Breakpoint type, Address and length.
+ In case of an error, function returns particular error code. Returning 0 meaning
+ no error.
+
+ @param PacketData Pointer to the payload data for the packet.
+ @param Type Breakpoint type
+ @param Address Breakpoint address
+ @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
+
+ @retval 1 Success
+ @retval {other} Particular error code
+
+**/
+UINTN
+ParseBreakpointPacket (
+ IN CHAR8 *PacketData,
+ OUT UINTN *Type,
+ OUT UINTN *Address,
+ OUT UINTN *Length
+ )
+{
+ CHAR8 AddressBuffer[MAX_ADDR_SIZE];
+ CHAR8 *AddressBufferPtr;
+ CHAR8 *PacketDataPtr;
+
+ PacketDataPtr = &PacketData[1];
+ AddressBufferPtr = AddressBuffer;
+
+ *Type = AsciiStrHexToUintn (PacketDataPtr);
+
+ //Breakpoint/watchpoint type should be between 0 to 4
+ if (*Type > 4) {
+ Print ((CHAR16 *)L"Type is invalid\n");
+ return 22; //EINVAL: Invalid argument.
+ }
+
+ //Skip ',' in the buffer.
+ while (*PacketDataPtr++ != ',');
+
+ //Parse Address information
+ while (*PacketDataPtr != ',') {
+ *AddressBufferPtr++ = *PacketDataPtr++;
+ }
+ *AddressBufferPtr = '\0';
+
+ //Check if Address is not too long.
+ if (AsciiStrLen(AddressBuffer) >= MAX_ADDR_SIZE) {
+ Print ((CHAR16 *)L"Address too long..\n");
+ return 40; //EMSGSIZE: Message size too long.
+ }
+
+ *Address = AsciiStrHexToUintn (AddressBuffer);
+
+ PacketDataPtr++; //This skips , in the buffer
+
+ //Parse Length information
+ *Length = AsciiStrHexToUintn (PacketDataPtr);
+
+ //Length should be 1, 2 or 4 bytes
+ if (*Length > 4) {
+ Print ((CHAR16 *)L"Length is invalid\n");
+ return 22; //EINVAL: Invalid argument
+ }
+
+ return 0; //0 = No error
+}
+
+UINTN
+gXferObjectReadResponse (
+ IN CHAR8 Type,
+ IN CHAR8 *Str
+ )
+{
+ CHAR8 *OutBufPtr; // pointer to the output buffer
+ CHAR8 Char;
+ UINTN Count;
+
+ // responce starts with 'm' or 'l' if it is the end
+ OutBufPtr = gOutBuffer;
+ *OutBufPtr++ = Type;
+ Count = 1;
+
+ // Binary data encoding
+ OutBufPtr = gOutBuffer;
+ while (*Str != '\0') {
+ Char = *Str++;
+ if ((Char == 0x7d) || (Char == 0x23) || (Char == 0x24) || (Char == 0x2a)) {
+ // escape character
+ *OutBufPtr++ = 0x7d;
+
+ Char ^= 0x20;
+ }
+ *OutBufPtr++ = Char;
+ Count++;
+ }
+
+ *OutBufPtr = '\0' ; // the end of the buffer
+ SendPacket (gOutBuffer);
+
+ return Count;
+}
+
+
+/**
+ Note: This should be a library function. In the Apple case you have to add
+ the size of the PE/COFF header into the starting address to make things work
+ right as there is no way to pad the Mach-O for the size of the PE/COFF header.
+
+
+ Returns a pointer to the PDB file name for a PE/COFF image that has been
+ loaded into system memory with the PE/COFF Loader Library functions.
+
+ Returns the PDB file name for the PE/COFF image specified by Pe32Data. If
+ the PE/COFF image specified by Pe32Data is not a valid, then NULL is
+ returned. If the PE/COFF image specified by Pe32Data does not contain a
+ debug directory entry, then NULL is returned. If the debug directory entry
+ in the PE/COFF image specified by Pe32Data does not contain a PDB file name,
+ then NULL is returned.
+ If Pe32Data is NULL, then ASSERT().
+
+ @param Pe32Data Pointer to the PE/COFF image that is loaded in system
+ memory.
+ @param DebugBase Address that the debugger would use as the base of the image
+
+ @return The PDB file name for the PE/COFF image specified by Pe32Data or NULL
+ if it cannot be retrieved. DebugBase is only valid if PDB file name is
+ valid.
+
+**/
+VOID *
+EFIAPI
+PeCoffLoaderGetDebuggerInfo (
+ IN VOID *Pe32Data,
+ OUT VOID **DebugBase
+ )
+{
+ EFI_IMAGE_DOS_HEADER *DosHdr;
+ EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
+ EFI_IMAGE_DATA_DIRECTORY *DirectoryEntry;
+ EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *DebugEntry;
+ UINTN DirCount;
+ VOID *CodeViewEntryPointer;
+ INTN TEImageAdjust;
+ UINT32 NumberOfRvaAndSizes;
+ UINT16 Magic;
+ UINTN SizeOfHeaders;
+
+ ASSERT (Pe32Data != NULL);
+
+ TEImageAdjust = 0;
+ DirectoryEntry = NULL;
+ DebugEntry = NULL;
+ NumberOfRvaAndSizes = 0;
+ SizeOfHeaders = 0;
+
+ DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data;
+ if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
+ //
+ // DOS image header is present, so read the PE header after the DOS image header.
+ //
+ Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff));
+ } else {
+ //
+ // DOS image header is not present, so PE header is at the image base.
+ //
+ Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data;
+ }
+
+ if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
+ if (Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress != 0) {
+ DirectoryEntry = &Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG];
+ TEImageAdjust = sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize;
+ DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)((UINTN) Hdr.Te +
+ Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress +
+ TEImageAdjust);
+ }
+ SizeOfHeaders = sizeof (EFI_TE_IMAGE_HEADER) + (UINTN)Hdr.Te->BaseOfCode - (UINTN)Hdr.Te->StrippedSize;
+
+ // __APPLE__ check this math...
+ *DebugBase = ((CHAR8 *)Pe32Data) - TEImageAdjust;
+ } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) {
+
+ *DebugBase = Pe32Data;
+
+
+ //
+ // NOTE: We use Machine field to identify PE32/PE32+, instead of Magic.
+ // It is due to backward-compatibility, for some system might
+ // generate PE32+ image with PE32 Magic.
+ //
+ switch (Hdr.Pe32->FileHeader.Machine) {
+ case EFI_IMAGE_MACHINE_IA32:
+ //
+ // Assume PE32 image with IA32 Machine field.
+ //
+ Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
+ break;
+ case EFI_IMAGE_MACHINE_X64:
+ case EFI_IMAGE_MACHINE_IA64:
+ //
+ // Assume PE32+ image with X64 or IPF Machine field
+ //
+ Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
+ break;
+ default:
+ //
+ // For unknow Machine field, use Magic in optional Header
+ //
+ Magic = Hdr.Pe32->OptionalHeader.Magic;
+ }
+
+ if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset get Debug Directory Entry
+ //
+ SizeOfHeaders = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
+ NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
+ DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
+ DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) ((UINTN) Pe32Data + DirectoryEntry->VirtualAddress);
+ } else if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
+ //
+ // Use PE32+ offset get Debug Directory Entry
+ //
+ SizeOfHeaders = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
+ NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
+ DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
+ DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) ((UINTN) Pe32Data + DirectoryEntry->VirtualAddress);
+ }
+
+ if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
+ DirectoryEntry = NULL;
+ DebugEntry = NULL;
+ }
+ } else {
+ return NULL;
+ }
+
+ if (DebugEntry == NULL || DirectoryEntry == NULL) {
+ return NULL;
+ }
+
+ for (DirCount = 0; DirCount < DirectoryEntry->Size; DirCount += sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY), DebugEntry++) {
+ if (DebugEntry->Type == EFI_IMAGE_DEBUG_TYPE_CODEVIEW) {
+ if (DebugEntry->SizeOfData > 0) {
+ CodeViewEntryPointer = (VOID *) ((UINTN) DebugEntry->RVA + ((UINTN)Pe32Data) + (UINTN)TEImageAdjust);
+ switch (* (UINT32 *) CodeViewEntryPointer) {
+ case CODEVIEW_SIGNATURE_NB10:
+ return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY));
+ case CODEVIEW_SIGNATURE_RSDS:
+ return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY));
+ case CODEVIEW_SIGNATURE_MTOC:
+ *DebugBase = (VOID *)(UINTN)((UINTN)DebugBase - SizeOfHeaders);
+ return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY));
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+ (void)SizeOfHeaders;
+ return NULL;
+}
+
+
+
+/**
+ Process "qXfer:object:read:annex:offset,length" request.
+
+ Returns an XML document that contains loaded libraries. In our case it is
+ infomration in the EFI Debug Inmage Table converted into an XML document.
+
+ GDB will call with an arbitrary length (it can't know the real length and
+ will reply with chunks of XML that are easy for us to deal with. Gdb will
+ keep calling until we say we are done. XML doc looks like:
+
+ <library-list>
+ <library name="/a/a/c/d.dSYM"><segment address="0x10000000"/></library>
+ <library name="/a/m/e/e.pdb"><segment address="0x20000000"/></library>
+ <library name="/a/l/f/f.dll"><segment address="0x30000000"/></library>
+ </library-list>
+
+ Since we can not allocate memory in interupt context this module has
+ assumptions about how it will get called:
+ 1) Length will generally be max remote packet size (big enough)
+ 2) First Offset of an XML document read needs to be 0
+ 3) This code will return back small chunks of the XML document on every read.
+ Each subseqent call will ask for the next availble part of the document.
+
+ Note: The only variable size element in the XML is:
+ " <library name=\"%s\"><segment address=\"%p\"/></library>\n" and it is
+ based on the file path and name of the symbol file. If the symbol file name
+ is bigger than the max gdb remote packet size we could update this code
+ to respond back in chunks.
+
+ @param Offset offset into special data area
+ @param Length number of bytes to read starting at Offset
+
+ **/
+VOID
+QxferLibrary (
+ IN UINTN Offset,
+ IN UINTN Length
+ )
+{
+ VOID *LoadAddress;
+ CHAR8 *Pdb;
+ UINTN Size;
+
+ if (Offset != gPacketqXferLibraryOffset) {
+ SendError (GDB_EINVALIDARG);
+ Print (L"\nqXferLibrary (%d, %d) != %d\n", Offset, Length, gPacketqXferLibraryOffset);
+
+ // Force a retry from the beginning
+ gPacketqXferLibraryOffset = 0;
+ return;
+ }
+
+ if (Offset == 0) {
+ gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', "<library-list>\n");
+
+ // The owner of the table may have had to ralloc it so grab a fresh copy every time
+ // we assume qXferLibrary will get called over and over again until the entire XML table is
+ // returned in a tight loop. Since we are in the debugger the table should not get updated
+ gDebugTable = gDebugImageTableHeader->EfiDebugImageInfoTable;
+ gEfiDebugImageTableEntry = 0;
+ return;
+ }
+
+ if (gDebugTable != NULL) {
+ for (; gEfiDebugImageTableEntry < gDebugImageTableHeader->TableSize; gEfiDebugImageTableEntry++, gDebugTable++) {
+ if (gDebugTable->NormalImage != NULL) {
+ if ((gDebugTable->NormalImage->ImageInfoType == EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL) &&
+ (gDebugTable->NormalImage->LoadedImageProtocolInstance != NULL)) {
+ Pdb = PeCoffLoaderGetDebuggerInfo (
+ gDebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase,
+ &LoadAddress
+ );
+ if (Pdb != NULL) {
+ Size = AsciiSPrint (
+ gXferLibraryBuffer,
+ sizeof (gXferLibraryBuffer),
+ " <library name=\"%a\"><segment address=\"0x%p\"/></library>\n",
+ Pdb,
+ LoadAddress
+ );
+ if ((Size != 0) && (Size != (sizeof (gXferLibraryBuffer) - 1))) {
+ gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', gXferLibraryBuffer);
+
+ // Update loop variables so we are in the right place when we get back
+ gEfiDebugImageTableEntry++;
+ gDebugTable++;
+ return;
+ } else {
+ // We could handle <library> entires larger than sizeof (gXferLibraryBuffer) here if
+ // needed by breaking up into N packets
+ // "<library name=\"%s
+ // the rest of the string (as many packets as required
+ // \"><segment address=\"%d\"/></library> (fixed size)
+ //
+ // But right now we just skip any entry that is too big
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ gXferObjectReadResponse ('l', "</library-list>\n");
+ gPacketqXferLibraryOffset = 0;
+ return;
+}
+
+
+/**
+ Exception Hanldler for GDB. It will be called for all exceptions
+ registered via the gExceptionType[] array.
+
+ @param ExceptionType Exception that is being processed
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+GdbExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ UINT8 GdbExceptionType;
+ CHAR8 *Ptr;
+
+
+ if (ValidateException(ExceptionType, SystemContext) == FALSE) {
+ return;
+ }
+
+ RemoveSingleStep (SystemContext);
+
+ GdbExceptionType = ConvertEFItoGDBtype (ExceptionType);
+ GdbSendTSignal (SystemContext, GdbExceptionType);
+
+ for( ; ; ) {
+ ReceivePacket (gInBuffer, MAX_BUF_SIZE);
+
+ switch (gInBuffer[0]) {
+ case '?':
+ GdbSendTSignal (SystemContext, GdbExceptionType);
+ break;
+
+ case 'c':
+ ContinueAtAddress (SystemContext, gInBuffer);
+ return;
+
+ case 'g':
+ ReadGeneralRegisters (SystemContext);
+ break;
+
+ case 'G':
+ WriteGeneralRegisters (SystemContext, gInBuffer);
+ break;
+
+ case 'H':
+ //Return "OK" packet since we don't have more than one thread.
+ SendSuccess ();
+ break;
+
+ case 'm':
+ ReadFromMemory (gInBuffer);
+ break;
+
+ case 'M':
+ WriteToMemory (gInBuffer);
+ break;
+
+ case 'P':
+ WriteNthRegister (SystemContext, gInBuffer);
+ break;
+
+ //
+ // Still debugging this code. Not used in Darwin
+ //
+ case 'q':
+ // General Query Packets
+ if (AsciiStrnCmp (gInBuffer, "qSupported", 10) == 0) {
+ // return what we currently support, we don't parse what gdb suports
+ AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "qXfer:libraries:read+;PacketSize=%d", MAX_BUF_SIZE);
+ SendPacket (gOutBuffer);
+ } else if (AsciiStrnCmp (gInBuffer, "qXfer:libraries:read::", 22) == 0) {
+ // ‘qXfer:libraries:read::offset,length
+ // gInBuffer[22] is offset string, ++Ptr is length string’
+ for (Ptr = &gInBuffer[22]; *Ptr != ','; Ptr++);
+
+ // Not sure if multi-radix support is required. Currently only support decimal
+ QxferLibrary (AsciiStrHexToUintn (&gInBuffer[22]), AsciiStrHexToUintn (++Ptr));
+ } if (AsciiStrnCmp (gInBuffer, "qOffsets", 10) == 0) {
+ AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "Text=1000;Data=f000;Bss=f000");
+ SendPacket (gOutBuffer);
+ } else {
+ //Send empty packet
+ SendNotSupported ();
+ }
+ break;
+
+ case 's':
+ SingleStep (SystemContext, gInBuffer);
+ return;
+
+ case 'z':
+ RemoveBreakPoint (SystemContext, gInBuffer);
+ break;
+
+ case 'Z':
+ InsertBreakPoint (SystemContext, gInBuffer);
+ break;
+
+ default:
+ //Send empty packet
+ SendNotSupported ();
+ break;
+ }
+ }
+}
+
+
+/**
+ Periodic callback for GDB. This function is used to catch a ctrl-c or other
+ break in type command from GDB.
+
+ @param SystemContext Register content at time of the call
+ **/
+VOID
+EFIAPI
+GdbPeriodicCallBack (
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ //
+ // gCtrlCBreakFlag may have been set from a previous F response package
+ // and we set the global as we need to process it at a point where we
+ // can update the system context. If we are in the middle of processing
+ // a F Packet it is not safe to read the GDB serial stream so we need
+ // to skip it on this check
+ //
+ if (!gCtrlCBreakFlag && !gProcessingFPacket) {
+ //
+ // Ctrl-C was not pending so grab any pending characters and see if they
+ // are a Ctrl-c (0x03). If so set the Ctrl-C global.
+ //
+ while (TRUE) {
+ if (!GdbIsCharAvailable ()) {
+ //
+ // No characters are pending so exit the loop
+ //
+ break;
+ }
+
+ if (GdbGetChar () == 0x03) {
+ gCtrlCBreakFlag = TRUE;
+ //
+ // We have a ctrl-c so exit the loop
+ //
+ break;
+ }
+ }
+ }
+
+ if (gCtrlCBreakFlag) {
+ //
+ // Update the context to force a single step trap when we exit the GDB
+ // stub. This will trasfer control to GdbExceptionHandler () and let
+ // us break into the program. We don't want to break into the GDB stub.
+ //
+ AddSingleStep (SystemContext);
+ gCtrlCBreakFlag = FALSE;
+ }
+}
diff --git a/EmbeddedPkg/GdbStub/GdbStubInternal.h b/EmbeddedPkg/GdbStub/GdbStubInternal.h
index ac04d7b9a..5f15420f0 100644
--- a/EmbeddedPkg/GdbStub/GdbStubInternal.h
+++ b/EmbeddedPkg/GdbStub/GdbStubInternal.h
@@ -1,746 +1,746 @@
-/** @file
- Private include file for GDB stub
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __GDB_STUB_INTERNAL__
-#define __GDB_STUB_INTERNAL__
-
-#include <Uefi.h>
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-#include <Library/UefiLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/PcdLib.h>
-#include <Library/GdbSerialLib.h>
-#include <Library/PrintLib.h>
-
-#include <Protocol/DebugSupport.h>
-#include <Protocol/SerialIo.h>
-#include <Protocol/LoadedImage.h>
-#include <Protocol/LoadedImage.h>
-#include <Guid/DebugImageInfoTable.h>
-#include <IndustryStandard/PeImage.h>
-
-extern CONST CHAR8 mHexToStr[];
-
-// maximum size of input and output buffers
-// This value came from the show remote command of the gdb we tested against
-#define MAX_BUF_SIZE 2000
-
-// maximum size of address buffer
-#define MAX_ADDR_SIZE 32
-
-// maximum size of register number buffer
-#define MAX_REG_NUM_BUF_SIZE 32
-
-// maximum size of length buffer
-#define MAX_LENGTH_SIZE 32
-
-// maximum size of T signal members
-#define MAX_T_SIGNAL_SIZE 64
-
-// the mask used to clear all the cache
-#define TF_BIT 0x00000100
-
-
-//
-// GDB Signal definitions - generic names for interrupts
-//
-#define GDB_SIGILL 4 // Illegal instruction
-#define GDB_SIGTRAP 5 // Trace Trap (Breakpoint and SingleStep)
-#define GDB_SIGEMT 7 // Emulator Trap
-#define GDB_SIGFPE 8 // Floating point exception
-#define GDB_SIGSEGV 11 // Setgment violation, page fault
-
-
-//
-// GDB File I/O Error values, zero means no error
-// Includes all general GDB Unix like error values
-//
-#define GDB_EBADMEMADDRBUFSIZE 11 // the buffer that stores memory Address to be read from/written to is not the right size
-#define GDB_EBADMEMLENGBUFSIZE 12 // the buffer that stores Length is not the right size
-#define GDB_EBADMEMLENGTH 13 // Length, the given number of bytes to read or write, is not the right size
-#define GDB_EBADMEMDATA 14 // one of the bytes or nibbles of the memory is leess than 0
-#define GDB_EBADMEMDATASIZE 15 // the memory data, 'XX..', is too short or too long
-#define GDB_EBADBUFSIZE 21 // the buffer created is not the correct size
-#define GDB_EINVALIDARG 31 // argument is invalid
-#define GDB_ENOSPACE 41 //
-#define GDB_EINVALIDBRKPOINTTYPE 51 // the breakpoint type is not recognized
-#define GDB_EINVALIDREGNUM 61 // given register number is not valid: either <0 or >=Number of Registers
-#define GDB_EUNKNOWN 255 // unknown
-
-
-//
-// These devices are open by GDB so we can just read and write to them
-//
-#define GDB_STDIN 0x00
-#define GDB_STDOUT 0x01
-#define GDB_STDERR 0x02
-
-//
-//Define Register size for different architectures
-//
-#if defined (MDE_CPU_IA32)
-#define REG_SIZE 32
-#elif defined (MDE_CPU_X64)
-#define REG_SIZE 64
-#elif defined (MDE_CPU_ARM)
-#define REG_SIZE 32
-#endif
-
-#define GDB_SERIAL_DEV_SIGNATURE SIGNATURE_32 ('g', 'd', 'b', 's')
-
-typedef struct {
- VENDOR_DEVICE_PATH VendorDevice;
- UINT32 Index; // Suport more than one
- EFI_DEVICE_PATH_PROTOCOL End;
-} GDB_SERIAL_DEVICE_PATH;
-
-//
-// Name: SERIAL_DEV
-// Purpose: To provide device specific information
-// Fields:
-// Signature UINTN: The identity of the serial device
-// SerialIo SERIAL_IO_PROTOCOL: Serial I/O protocol interface
-// SerialMode SERIAL_IO_MODE:
-// DevicePath EFI_DEVICE_PATH_PROTOCOL *: Device path of the serial device
-//
-typedef struct {
- UINTN Signature;
- EFI_HANDLE Handle;
- EFI_SERIAL_IO_PROTOCOL SerialIo;
- EFI_SERIAL_IO_MODE SerialMode;
- GDB_SERIAL_DEVICE_PATH DevicePath;
- INTN InFileDescriptor;
- INTN OutFileDescriptor;
-} GDB_SERIAL_DEV;
-
-
-#define GDB_SERIAL_DEV_FROM_THIS(a) CR (a, GDB_SERIAL_DEV, SerialIo, GDB_SERIAL_DEV_SIGNATURE)
-
-
-typedef struct {
- EFI_EXCEPTION_TYPE Exception;
- UINT8 SignalNo;
-} EFI_EXCEPTION_TYPE_ENTRY;
-
-
-#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
-
-//
-// Byte packed structure for DR6
-// 32-bits on IA-32
-// 64-bits on X64. The upper 32-bits on X64 are reserved
-//
-typedef union {
- struct {
- UINT32 B0:1; // Breakpoint condition detected
- UINT32 B1:1; // Breakpoint condition detected
- UINT32 B2:1; // Breakpoint condition detected
- UINT32 B3:1; // Breakpoint condition detected
- UINT32 Reserved_1:9; // Reserved
- UINT32 BD:1; // Debug register access detected
- UINT32 BS:1; // Single step
- UINT32 BT:1; // Task switch
- UINT32 Reserved_2:16; // Reserved
- } Bits;
- UINTN UintN;
-} IA32_DR6;
-
-//
-// Byte packed structure for DR7
-// 32-bits on IA-32
-// 64-bits on X64. The upper 32-bits on X64 are reserved
-//
-typedef union {
- struct {
- UINT32 L0:1; // Local breakpoint enable
- UINT32 G0:1; // Global breakpoint enable
- UINT32 L1:1; // Local breakpoint enable
- UINT32 G1:1; // Global breakpoint enable
- UINT32 L2:1; // Local breakpoint enable
- UINT32 G2:1; // Global breakpoint enable
- UINT32 L3:1; // Local breakpoint enable
- UINT32 G3:1; // Global breakpoint enable
- UINT32 LE:1; // Local exact breakpoint enable
- UINT32 GE:1; // Global exact breakpoint enable
- UINT32 Reserved_1:3; // Reserved
- UINT32 GD:1; // Global detect enable
- UINT32 Reserved_2:2; // Reserved
- UINT32 RW0:2; // Read/Write field
- UINT32 LEN0:2; // Length field
- UINT32 RW1:2; // Read/Write field
- UINT32 LEN1:2; // Length field
- UINT32 RW2:2; // Read/Write field
- UINT32 LEN2:2; // Length field
- UINT32 RW3:2; // Read/Write field
- UINT32 LEN3:2; // Length field
- } Bits;
- UINTN UintN;
-} IA32_DR7;
-
-#endif /* if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64) */
-
-typedef enum {
- InstructionExecution, //Hardware breakpoint
- DataWrite, //watch
- DataRead, //rwatch
- DataReadWrite, //awatch
- SoftwareBreakpoint, //Software breakpoint
- NotSupported
-} BREAK_TYPE;
-
-//
-// Array of exception types that need to be hooked by the debugger
-//
-extern EFI_EXCEPTION_TYPE_ENTRY gExceptionType[];
-
-//
-// Set TRUE if F Reply package signals a ctrl-c. We can not process the Ctrl-c
-// here we need to wait for the periodic callback to do this.
-//
-extern BOOLEAN gCtrlCBreakFlag;
-
-//
-// If the periodic callback is called while we are processing an F packet we need
-// to let the callback know to not read from the serail stream as it could steal
-// characters from the F reponse packet
-//
-extern BOOLEAN gProcessingFPacket;
-
-
-// The offsets of registers SystemContext.
-// The fields in the array are in the gdb ordering.
-//
-extern UINTN gRegisterOffsets[];
-
-/**
- Return the number of entries in the gExceptionType[]
-
- @retval UINTN, the number of entries in the gExceptionType[] array.
- **/
-UINTN
-MaxEfiException (
- VOID
- );
-
-
-/**
- Return the number of entries in the gRegisters[]
-
- @retval UINTN, the number of entries (registers) in the gRegisters[] array.
- **/
-UINTN
-MaxRegisterCount (
- VOID
- );
-
-
-/**
- Check to see if the ISA is supported.
- ISA = Instruction Set Architecture
-
- @retval TRUE if Isa is supported,
- FALSE otherwise.
- **/
-BOOLEAN
-CheckIsa (
- IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
- );
-
-
-/**
- Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
-
- @param SystemContext Register content at time of the exception
- @param GdbExceptionType GDB exception type
- **/
-
-VOID
-GdbSendTSignal (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINT8 GdbExceptionType
- );
-
-
-/**
- Translates the EFI mapping to GDB mapping
-
- @param EFIExceptionType EFI Exception that is being processed
- @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
- **/
-UINT8
-ConvertEFItoGDBtype (
- IN EFI_EXCEPTION_TYPE EFIExceptionType
- );
-
-
-/**
- Empties the given buffer
- @param *Buf pointer to the first element in buffer to be emptied
- **/
-VOID
-EmptyBuffer (
- IN CHAR8 *Buf
- );
-
-
-/**
- Converts an 8-bit Hex Char into a INTN.
-
- @param Char - the hex character to be converted into UINTN
- @retval a INTN, from 0 to 15, that corressponds to Char
- -1 if Char is not a hex character
- **/
-INTN
-HexCharToInt (
- IN CHAR8 Char
- );
-
-
-/** 'E NN'
- Send an error with the given error number after converting to hex.
- The error number is put into the buffer in hex. '255' is the biggest errno we can send.
- ex: 162 will be sent as A2.
-
- @param errno the error number that will be sent
- **/
-VOID
-EFIAPI
-SendError (
- IN UINT8 ErrorNum
- );
-
-
-/**
- Send 'OK' when the function is done executing successfully.
- **/
-VOID
-SendSuccess (
- VOID
- );
-
-
-/**
- Send empty packet to specify that particular command/functionality is not supported.
- **/
-VOID
-SendNotSupported (
- VOID
- );
-
-/** ‘p n’
- Reads the n-th register's value into an output buffer and sends it as a packet
- @param SystemContext Register content at time of the exception
- @param InBuffer This is the input buffer received from gdb server
- **/
-VOID
-ReadNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- );
-
-
-/** ‘g’
- Reads the general registers into an output buffer and sends it as a packet
- @param SystemContext Register content at time of the exception
- **/
-VOID
-ReadGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/** ‘P n...=r...’
- Writes the new value of n-th register received into the input buffer to the n-th register
- @param SystemContext Register content at time of the exception
- @param InBuffer This is the input buffer received from gdb server
- **/
-VOID
-WriteNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- );
-
-
-/** ‘G XX...’
- Writes the new values received into the input buffer to the general registers
- @param SystemContext Register content at time of the exception
- @param InBuffer Pointer to the input buffer received from gdb server
- **/
-
-VOID
-WriteGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- );
-
-
-/** ‘m addr,length ’
- Find the Length of the area to read and the start addres. Finally, pass them to
- another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
- send it as a packet.
-
- @param *PacketData Pointer to Payload data for the packet
- **/
-VOID
-ReadFromMemory (
- IN CHAR8 *PacketData
- );
-
-
-/** ‘M addr,length :XX...’
- Find the Length of the area in bytes to write and the start addres. Finally, pass them to
- another function, TransferFromInBufToMem, that will write to that memory space the info in
- the input buffer.
-
- @param PacketData Pointer to Payload data for the packet
- **/
-VOID
-WriteToMemory (
- IN CHAR8 *PacketData
- );
-
-
-/** ‘c [addr ]’
- Continue. addr is Address to resume. If addr is omitted, resume at current
- Address.
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to PacketData
- **/
-
-VOID
-ContinueAtAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-
-/** ‘s [addr ]’
- Single step. addr is the Address at which to resume. If addr is omitted, resume
- at same Address.
-
- @param SystemContext Register content at time of the exception
- @param PacketData Pointer to Payload data for the packet
- **/
-VOID
-SingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-/**
- Insert Single Step in the SystemContext
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-AddSingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-/**
- Remove Single Step in the SystemContext
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-RemoveSingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/**
- ‘Z1, [addr], [length]’
- ‘Z2, [addr], [length]’
- ‘Z3, [addr], [length]’
- ‘Z4, [addr], [length]’
-
- Insert hardware breakpoint/watchpoint at address addr of size length
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-InsertBreakPoint(
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-
-/**
- ‘z1, [addr], [length]’
- ‘z2, [addr], [length]’
- ‘z3, [addr], [length]’
- ‘z4, [addr], [length]’
-
- Remove hardware breakpoint/watchpoint at address addr of size length
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-RemoveBreakPoint(
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-
-/**
- Exception Hanldler for GDB. It will be called for all exceptions
- registered via the gExceptionType[] array.
-
- @param ExceptionType Exception that is being processed
- @param SystemContext Register content at time of the exception
-
- **/
-VOID
-EFIAPI
-GdbExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType,
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/**
- Periodic callback for GDB. This function is used to catch a ctrl-c or other
- break in type command from GDB.
-
- @param SystemContext Register content at time of the call
-
- **/
-VOID
-EFIAPI
-GdbPeriodicCallBack (
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/**
- Make two serail consoles: 1) StdIn and StdOut via GDB. 2) StdErr via GDB.
-
- These console show up on the remote system running GDB
-
-**/
-
-VOID
-GdbInitializeSerialConsole (
- VOID
- );
-
-
-/**
- Send a GDB Remote Serial Protocol Packet
-
- $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
- the packet teminating character '#' and the two digit checksum.
-
- If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
- in an infinit loop. This is so if you unplug the debugger code just keeps running
-
- @param PacketData Payload data for the packet
-
- @retval Number of bytes of packet data sent.
-
-**/
-UINTN
-SendPacket (
- IN CHAR8 *PacketData
- );
-
-
-/**
- Receive a GDB Remote Serial Protocol Packet
-
- $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
- the packet teminating character '#' and the two digit checksum.
-
- If host re-starts sending a packet without ending the previous packet, only the last valid packet is proccessed.
- (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
-
- If an ack '+' is not sent resend the packet
-
- @param PacketData Payload data for the packet
-
- @retval Number of bytes of packet data received.
-
- **/
-UINTN
-ReceivePacket (
- OUT CHAR8 *PacketData,
- IN UINTN PacketDataSize
- );
-
-
-/**
- Read data from a FileDescriptor. On success number of bytes read is returned. Zero indicates
- the end of a file. On error -1 is returned. If count is zero, GdbRead returns zero.
-
- @param FileDescriptor Device to talk to.
- @param Buffer Buffer to hold Count bytes that were read
- @param Count Number of bytes to transfer.
-
- @retval -1 Error
- @retval {other} Number of bytes read.
-
-**/
-INTN
-GdbRead (
- IN INTN FileDescriptor,
- OUT VOID *Buffer,
- IN UINTN Count
- );
-
-
-/**
- Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
- nothing was written. On error -1 is returned.
-
- @param FileDescriptor Device to talk to.
- @param Buffer Buffer to hold Count bytes that are to be written
- @param Count Number of bytes to transfer.
-
- @retval -1 Error
- @retval {other} Number of bytes written.
-
-**/
-INTN
-GdbWrite (
- IN INTN FileDescriptor,
- OUT CONST VOID *Buffer,
- IN UINTN Count
- );
-
-UINTN *
-FindPointerToRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber
- );
-
-CHAR8 *
-BasicReadRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *OutBufPtr
- );
-
-VOID
-TransferFromInBufToMem (
- IN UINTN Length,
- IN UINT8 *Address,
- IN CHAR8 *NewData
- );
-
-VOID
-TransferFromMemToOutBufAndSend (
- IN UINTN Length,
- IN UINT8 *Address
- );
-
-CHAR8 *
-BasicWriteRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *InBufPtr
- );
-
-VOID
-PrintReg (
- EFI_SYSTEM_CONTEXT SystemContext
- );
-
-UINTN
-ParseBreakpointPacket (
- IN CHAR8 *PacketData,
- OUT UINTN *Type,
- OUT UINTN *Address,
- OUT UINTN *Length
- );
-
-UINTN
-GetBreakpointDataAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- );
-
-UINTN
-GetBreakpointDetected (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-BREAK_TYPE
-GetBreakpointType (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- );
-
-UINTN
-ConvertLengthData (
- IN UINTN Length
- );
-
-EFI_STATUS
-FindNextFreeDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- OUT UINTN *Register
- );
-
-EFI_STATUS
-EnableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type
- );
-
-EFI_STATUS
-FindMatchingDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type,
- OUT UINTN *Register
- );
-
-EFI_STATUS
-DisableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register
- );
-
-VOID
-InitializeProcessor (
- VOID
- );
-
-BOOLEAN
-ValidateAddress (
- IN VOID *Address
- );
-
-BOOLEAN
-ValidateException (
- IN EFI_EXCEPTION_TYPE ExceptionType,
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-#endif
+/** @file
+ Private include file for GDB stub
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __GDB_STUB_INTERNAL__
+#define __GDB_STUB_INTERNAL__
+
+#include <Uefi.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/PcdLib.h>
+#include <Library/GdbSerialLib.h>
+#include <Library/PrintLib.h>
+
+#include <Protocol/DebugSupport.h>
+#include <Protocol/SerialIo.h>
+#include <Protocol/LoadedImage.h>
+#include <Protocol/LoadedImage.h>
+#include <Guid/DebugImageInfoTable.h>
+#include <IndustryStandard/PeImage.h>
+
+extern CONST CHAR8 mHexToStr[];
+
+// maximum size of input and output buffers
+// This value came from the show remote command of the gdb we tested against
+#define MAX_BUF_SIZE 2000
+
+// maximum size of address buffer
+#define MAX_ADDR_SIZE 32
+
+// maximum size of register number buffer
+#define MAX_REG_NUM_BUF_SIZE 32
+
+// maximum size of length buffer
+#define MAX_LENGTH_SIZE 32
+
+// maximum size of T signal members
+#define MAX_T_SIGNAL_SIZE 64
+
+// the mask used to clear all the cache
+#define TF_BIT 0x00000100
+
+
+//
+// GDB Signal definitions - generic names for interrupts
+//
+#define GDB_SIGILL 4 // Illegal instruction
+#define GDB_SIGTRAP 5 // Trace Trap (Breakpoint and SingleStep)
+#define GDB_SIGEMT 7 // Emulator Trap
+#define GDB_SIGFPE 8 // Floating point exception
+#define GDB_SIGSEGV 11 // Setgment violation, page fault
+
+
+//
+// GDB File I/O Error values, zero means no error
+// Includes all general GDB Unix like error values
+//
+#define GDB_EBADMEMADDRBUFSIZE 11 // the buffer that stores memory Address to be read from/written to is not the right size
+#define GDB_EBADMEMLENGBUFSIZE 12 // the buffer that stores Length is not the right size
+#define GDB_EBADMEMLENGTH 13 // Length, the given number of bytes to read or write, is not the right size
+#define GDB_EBADMEMDATA 14 // one of the bytes or nibbles of the memory is leess than 0
+#define GDB_EBADMEMDATASIZE 15 // the memory data, 'XX..', is too short or too long
+#define GDB_EBADBUFSIZE 21 // the buffer created is not the correct size
+#define GDB_EINVALIDARG 31 // argument is invalid
+#define GDB_ENOSPACE 41 //
+#define GDB_EINVALIDBRKPOINTTYPE 51 // the breakpoint type is not recognized
+#define GDB_EINVALIDREGNUM 61 // given register number is not valid: either <0 or >=Number of Registers
+#define GDB_EUNKNOWN 255 // unknown
+
+
+//
+// These devices are open by GDB so we can just read and write to them
+//
+#define GDB_STDIN 0x00
+#define GDB_STDOUT 0x01
+#define GDB_STDERR 0x02
+
+//
+//Define Register size for different architectures
+//
+#if defined (MDE_CPU_IA32)
+#define REG_SIZE 32
+#elif defined (MDE_CPU_X64)
+#define REG_SIZE 64
+#elif defined (MDE_CPU_ARM)
+#define REG_SIZE 32
+#endif
+
+#define GDB_SERIAL_DEV_SIGNATURE SIGNATURE_32 ('g', 'd', 'b', 's')
+
+typedef struct {
+ VENDOR_DEVICE_PATH VendorDevice;
+ UINT32 Index; // Suport more than one
+ EFI_DEVICE_PATH_PROTOCOL End;
+} GDB_SERIAL_DEVICE_PATH;
+
+//
+// Name: SERIAL_DEV
+// Purpose: To provide device specific information
+// Fields:
+// Signature UINTN: The identity of the serial device
+// SerialIo SERIAL_IO_PROTOCOL: Serial I/O protocol interface
+// SerialMode SERIAL_IO_MODE:
+// DevicePath EFI_DEVICE_PATH_PROTOCOL *: Device path of the serial device
+//
+typedef struct {
+ UINTN Signature;
+ EFI_HANDLE Handle;
+ EFI_SERIAL_IO_PROTOCOL SerialIo;
+ EFI_SERIAL_IO_MODE SerialMode;
+ GDB_SERIAL_DEVICE_PATH DevicePath;
+ INTN InFileDescriptor;
+ INTN OutFileDescriptor;
+} GDB_SERIAL_DEV;
+
+
+#define GDB_SERIAL_DEV_FROM_THIS(a) CR (a, GDB_SERIAL_DEV, SerialIo, GDB_SERIAL_DEV_SIGNATURE)
+
+
+typedef struct {
+ EFI_EXCEPTION_TYPE Exception;
+ UINT8 SignalNo;
+} EFI_EXCEPTION_TYPE_ENTRY;
+
+
+#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
+
+//
+// Byte packed structure for DR6
+// 32-bits on IA-32
+// 64-bits on X64. The upper 32-bits on X64 are reserved
+//
+typedef union {
+ struct {
+ UINT32 B0:1; // Breakpoint condition detected
+ UINT32 B1:1; // Breakpoint condition detected
+ UINT32 B2:1; // Breakpoint condition detected
+ UINT32 B3:1; // Breakpoint condition detected
+ UINT32 Reserved_1:9; // Reserved
+ UINT32 BD:1; // Debug register access detected
+ UINT32 BS:1; // Single step
+ UINT32 BT:1; // Task switch
+ UINT32 Reserved_2:16; // Reserved
+ } Bits;
+ UINTN UintN;
+} IA32_DR6;
+
+//
+// Byte packed structure for DR7
+// 32-bits on IA-32
+// 64-bits on X64. The upper 32-bits on X64 are reserved
+//
+typedef union {
+ struct {
+ UINT32 L0:1; // Local breakpoint enable
+ UINT32 G0:1; // Global breakpoint enable
+ UINT32 L1:1; // Local breakpoint enable
+ UINT32 G1:1; // Global breakpoint enable
+ UINT32 L2:1; // Local breakpoint enable
+ UINT32 G2:1; // Global breakpoint enable
+ UINT32 L3:1; // Local breakpoint enable
+ UINT32 G3:1; // Global breakpoint enable
+ UINT32 LE:1; // Local exact breakpoint enable
+ UINT32 GE:1; // Global exact breakpoint enable
+ UINT32 Reserved_1:3; // Reserved
+ UINT32 GD:1; // Global detect enable
+ UINT32 Reserved_2:2; // Reserved
+ UINT32 RW0:2; // Read/Write field
+ UINT32 LEN0:2; // Length field
+ UINT32 RW1:2; // Read/Write field
+ UINT32 LEN1:2; // Length field
+ UINT32 RW2:2; // Read/Write field
+ UINT32 LEN2:2; // Length field
+ UINT32 RW3:2; // Read/Write field
+ UINT32 LEN3:2; // Length field
+ } Bits;
+ UINTN UintN;
+} IA32_DR7;
+
+#endif /* if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64) */
+
+typedef enum {
+ InstructionExecution, //Hardware breakpoint
+ DataWrite, //watch
+ DataRead, //rwatch
+ DataReadWrite, //awatch
+ SoftwareBreakpoint, //Software breakpoint
+ NotSupported
+} BREAK_TYPE;
+
+//
+// Array of exception types that need to be hooked by the debugger
+//
+extern EFI_EXCEPTION_TYPE_ENTRY gExceptionType[];
+
+//
+// Set TRUE if F Reply package signals a ctrl-c. We can not process the Ctrl-c
+// here we need to wait for the periodic callback to do this.
+//
+extern BOOLEAN gCtrlCBreakFlag;
+
+//
+// If the periodic callback is called while we are processing an F packet we need
+// to let the callback know to not read from the serail stream as it could steal
+// characters from the F reponse packet
+//
+extern BOOLEAN gProcessingFPacket;
+
+
+// The offsets of registers SystemContext.
+// The fields in the array are in the gdb ordering.
+//
+extern UINTN gRegisterOffsets[];
+
+/**
+ Return the number of entries in the gExceptionType[]
+
+ @retval UINTN, the number of entries in the gExceptionType[] array.
+ **/
+UINTN
+MaxEfiException (
+ VOID
+ );
+
+
+/**
+ Return the number of entries in the gRegisters[]
+
+ @retval UINTN, the number of entries (registers) in the gRegisters[] array.
+ **/
+UINTN
+MaxRegisterCount (
+ VOID
+ );
+
+
+/**
+ Check to see if the ISA is supported.
+ ISA = Instruction Set Architecture
+
+ @retval TRUE if Isa is supported,
+ FALSE otherwise.
+ **/
+BOOLEAN
+CheckIsa (
+ IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
+ );
+
+
+/**
+ Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
+
+ @param SystemContext Register content at time of the exception
+ @param GdbExceptionType GDB exception type
+ **/
+
+VOID
+GdbSendTSignal (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINT8 GdbExceptionType
+ );
+
+
+/**
+ Translates the EFI mapping to GDB mapping
+
+ @param EFIExceptionType EFI Exception that is being processed
+ @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
+ **/
+UINT8
+ConvertEFItoGDBtype (
+ IN EFI_EXCEPTION_TYPE EFIExceptionType
+ );
+
+
+/**
+ Empties the given buffer
+ @param *Buf pointer to the first element in buffer to be emptied
+ **/
+VOID
+EmptyBuffer (
+ IN CHAR8 *Buf
+ );
+
+
+/**
+ Converts an 8-bit Hex Char into a INTN.
+
+ @param Char - the hex character to be converted into UINTN
+ @retval a INTN, from 0 to 15, that corressponds to Char
+ -1 if Char is not a hex character
+ **/
+INTN
+HexCharToInt (
+ IN CHAR8 Char
+ );
+
+
+/** 'E NN'
+ Send an error with the given error number after converting to hex.
+ The error number is put into the buffer in hex. '255' is the biggest errno we can send.
+ ex: 162 will be sent as A2.
+
+ @param errno the error number that will be sent
+ **/
+VOID
+EFIAPI
+SendError (
+ IN UINT8 ErrorNum
+ );
+
+
+/**
+ Send 'OK' when the function is done executing successfully.
+ **/
+VOID
+SendSuccess (
+ VOID
+ );
+
+
+/**
+ Send empty packet to specify that particular command/functionality is not supported.
+ **/
+VOID
+SendNotSupported (
+ VOID
+ );
+
+/** ‘p n’
+ Reads the n-th register's value into an output buffer and sends it as a packet
+ @param SystemContext Register content at time of the exception
+ @param InBuffer This is the input buffer received from gdb server
+ **/
+VOID
+ReadNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ );
+
+
+/** ‘g’
+ Reads the general registers into an output buffer and sends it as a packet
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+ReadGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/** ‘P n...=r...’
+ Writes the new value of n-th register received into the input buffer to the n-th register
+ @param SystemContext Register content at time of the exception
+ @param InBuffer This is the input buffer received from gdb server
+ **/
+VOID
+WriteNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ );
+
+
+/** ‘G XX...’
+ Writes the new values received into the input buffer to the general registers
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Pointer to the input buffer received from gdb server
+ **/
+
+VOID
+WriteGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ );
+
+
+/** ‘m addr,length ’
+ Find the Length of the area to read and the start addres. Finally, pass them to
+ another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
+ send it as a packet.
+
+ @param *PacketData Pointer to Payload data for the packet
+ **/
+VOID
+ReadFromMemory (
+ IN CHAR8 *PacketData
+ );
+
+
+/** ‘M addr,length :XX...’
+ Find the Length of the area in bytes to write and the start addres. Finally, pass them to
+ another function, TransferFromInBufToMem, that will write to that memory space the info in
+ the input buffer.
+
+ @param PacketData Pointer to Payload data for the packet
+ **/
+VOID
+WriteToMemory (
+ IN CHAR8 *PacketData
+ );
+
+
+/** ‘c [addr ]’
+ Continue. addr is Address to resume. If addr is omitted, resume at current
+ Address.
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to PacketData
+ **/
+
+VOID
+ContinueAtAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+
+/** ‘s [addr ]’
+ Single step. addr is the Address at which to resume. If addr is omitted, resume
+ at same Address.
+
+ @param SystemContext Register content at time of the exception
+ @param PacketData Pointer to Payload data for the packet
+ **/
+VOID
+SingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+/**
+ Insert Single Step in the SystemContext
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+AddSingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+/**
+ Remove Single Step in the SystemContext
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+RemoveSingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/**
+ ‘Z1, [addr], [length]’
+ ‘Z2, [addr], [length]’
+ ‘Z3, [addr], [length]’
+ ‘Z4, [addr], [length]’
+
+ Insert hardware breakpoint/watchpoint at address addr of size length
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+InsertBreakPoint(
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+
+/**
+ ‘z1, [addr], [length]’
+ ‘z2, [addr], [length]’
+ ‘z3, [addr], [length]’
+ ‘z4, [addr], [length]’
+
+ Remove hardware breakpoint/watchpoint at address addr of size length
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+RemoveBreakPoint(
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+
+/**
+ Exception Hanldler for GDB. It will be called for all exceptions
+ registered via the gExceptionType[] array.
+
+ @param ExceptionType Exception that is being processed
+ @param SystemContext Register content at time of the exception
+
+ **/
+VOID
+EFIAPI
+GdbExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/**
+ Periodic callback for GDB. This function is used to catch a ctrl-c or other
+ break in type command from GDB.
+
+ @param SystemContext Register content at time of the call
+
+ **/
+VOID
+EFIAPI
+GdbPeriodicCallBack (
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/**
+ Make two serail consoles: 1) StdIn and StdOut via GDB. 2) StdErr via GDB.
+
+ These console show up on the remote system running GDB
+
+**/
+
+VOID
+GdbInitializeSerialConsole (
+ VOID
+ );
+
+
+/**
+ Send a GDB Remote Serial Protocol Packet
+
+ $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
+ the packet teminating character '#' and the two digit checksum.
+
+ If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
+ in an infinit loop. This is so if you unplug the debugger code just keeps running
+
+ @param PacketData Payload data for the packet
+
+ @retval Number of bytes of packet data sent.
+
+**/
+UINTN
+SendPacket (
+ IN CHAR8 *PacketData
+ );
+
+
+/**
+ Receive a GDB Remote Serial Protocol Packet
+
+ $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
+ the packet teminating character '#' and the two digit checksum.
+
+ If host re-starts sending a packet without ending the previous packet, only the last valid packet is proccessed.
+ (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
+
+ If an ack '+' is not sent resend the packet
+
+ @param PacketData Payload data for the packet
+
+ @retval Number of bytes of packet data received.
+
+ **/
+UINTN
+ReceivePacket (
+ OUT CHAR8 *PacketData,
+ IN UINTN PacketDataSize
+ );
+
+
+/**
+ Read data from a FileDescriptor. On success number of bytes read is returned. Zero indicates
+ the end of a file. On error -1 is returned. If count is zero, GdbRead returns zero.
+
+ @param FileDescriptor Device to talk to.
+ @param Buffer Buffer to hold Count bytes that were read
+ @param Count Number of bytes to transfer.
+
+ @retval -1 Error
+ @retval {other} Number of bytes read.
+
+**/
+INTN
+GdbRead (
+ IN INTN FileDescriptor,
+ OUT VOID *Buffer,
+ IN UINTN Count
+ );
+
+
+/**
+ Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
+ nothing was written. On error -1 is returned.
+
+ @param FileDescriptor Device to talk to.
+ @param Buffer Buffer to hold Count bytes that are to be written
+ @param Count Number of bytes to transfer.
+
+ @retval -1 Error
+ @retval {other} Number of bytes written.
+
+**/
+INTN
+GdbWrite (
+ IN INTN FileDescriptor,
+ OUT CONST VOID *Buffer,
+ IN UINTN Count
+ );
+
+UINTN *
+FindPointerToRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber
+ );
+
+CHAR8 *
+BasicReadRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *OutBufPtr
+ );
+
+VOID
+TransferFromInBufToMem (
+ IN UINTN Length,
+ IN UINT8 *Address,
+ IN CHAR8 *NewData
+ );
+
+VOID
+TransferFromMemToOutBufAndSend (
+ IN UINTN Length,
+ IN UINT8 *Address
+ );
+
+CHAR8 *
+BasicWriteRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *InBufPtr
+ );
+
+VOID
+PrintReg (
+ EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+UINTN
+ParseBreakpointPacket (
+ IN CHAR8 *PacketData,
+ OUT UINTN *Type,
+ OUT UINTN *Address,
+ OUT UINTN *Length
+ );
+
+UINTN
+GetBreakpointDataAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ );
+
+UINTN
+GetBreakpointDetected (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+BREAK_TYPE
+GetBreakpointType (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ );
+
+UINTN
+ConvertLengthData (
+ IN UINTN Length
+ );
+
+EFI_STATUS
+FindNextFreeDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ OUT UINTN *Register
+ );
+
+EFI_STATUS
+EnableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type
+ );
+
+EFI_STATUS
+FindMatchingDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type,
+ OUT UINTN *Register
+ );
+
+EFI_STATUS
+DisableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register
+ );
+
+VOID
+InitializeProcessor (
+ VOID
+ );
+
+BOOLEAN
+ValidateAddress (
+ IN VOID *Address
+ );
+
+BOOLEAN
+ValidateException (
+ IN EFI_EXCEPTION_TYPE ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+#endif
diff --git a/EmbeddedPkg/GdbStub/Ia32/Processor.c b/EmbeddedPkg/GdbStub/Ia32/Processor.c
index 442faea02..a6aceaef9 100644
--- a/EmbeddedPkg/GdbStub/Ia32/Processor.c
+++ b/EmbeddedPkg/GdbStub/Ia32/Processor.c
@@ -1,993 +1,993 @@
-/** @file
- Processor specific parts of the GDB stub
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <GdbStubInternal.h>
-
-//
-// Array of exception types that need to be hooked by the debugger
-// {EFI mapping, GDB mapping}
-//
-EFI_EXCEPTION_TYPE_ENTRY gExceptionType[] = {
- { EXCEPT_IA32_DIVIDE_ERROR, GDB_SIGFPE },
- { EXCEPT_IA32_DEBUG, GDB_SIGTRAP },
- { EXCEPT_IA32_NMI, GDB_SIGEMT },
- { EXCEPT_IA32_BREAKPOINT, GDB_SIGTRAP },
- { EXCEPT_IA32_OVERFLOW, GDB_SIGSEGV },
- { EXCEPT_IA32_BOUND, GDB_SIGSEGV },
- { EXCEPT_IA32_INVALID_OPCODE, GDB_SIGILL },
- { EXCEPT_IA32_DOUBLE_FAULT, GDB_SIGEMT },
- { EXCEPT_IA32_STACK_FAULT, GDB_SIGSEGV },
- { EXCEPT_IA32_GP_FAULT, GDB_SIGSEGV },
- { EXCEPT_IA32_PAGE_FAULT, GDB_SIGSEGV },
- { EXCEPT_IA32_FP_ERROR, GDB_SIGEMT },
- { EXCEPT_IA32_ALIGNMENT_CHECK, GDB_SIGEMT },
- { EXCEPT_IA32_MACHINE_CHECK, GDB_SIGEMT }
-};
-
-
-// The offsets of registers SystemContext.
-// The fields in the array are in the gdb ordering.
-//
-//16 regs
-UINTN gRegisterOffsets[] = {
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eax),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ecx),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edx),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebx),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esp),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebp),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esi),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edi),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eip),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eflags),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Cs),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ss),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ds),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Es),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Fs),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Gs)
-};
-
-
-//Debug only..
-VOID
-PrintReg (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- Print ((CHAR16 *)L"EAX: %x ", SystemContext.SystemContextIa32->Eax);
- Print ((CHAR16 *)L"ECX: %x ", SystemContext.SystemContextIa32->Ecx);
- Print ((CHAR16 *)L"EDX: %x ", SystemContext.SystemContextIa32->Edx);
- Print ((CHAR16 *)L"EBX: %x ", SystemContext.SystemContextIa32->Ebx);
- Print ((CHAR16 *)L"ESP: %x ", SystemContext.SystemContextIa32->Esp);
- Print ((CHAR16 *)L"EBP: %x ", SystemContext.SystemContextIa32->Ebp);
- Print ((CHAR16 *)L"ESI: %x ", SystemContext.SystemContextIa32->Esi);
- Print ((CHAR16 *)L"EDI: %x ", SystemContext.SystemContextIa32->Edi);
- Print ((CHAR16 *)L"EIP: %x\n", SystemContext.SystemContextIa32->Eip);
- Print ((CHAR16 *)L"EFlags: %x\n", SystemContext.SystemContextIa32->Eflags);
-}
-
-//Debug only..
-VOID
-PrintDRreg (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- Print ((CHAR16 *)L"DR0: %x ", SystemContext.SystemContextIa32->Dr0);
- Print ((CHAR16 *)L"DR1: %x ", SystemContext.SystemContextIa32->Dr1);
- Print ((CHAR16 *)L"DR2: %x ", SystemContext.SystemContextIa32->Dr2);
- Print ((CHAR16 *)L"DR3: %x ", SystemContext.SystemContextIa32->Dr3);
- Print ((CHAR16 *)L"DR6: %x ", SystemContext.SystemContextIa32->Dr6);
- Print ((CHAR16 *)L"DR7: %x\n", SystemContext.SystemContextIa32->Dr7);
-}
-
-
-/**
- Return the number of entries in the gExceptionType[]
-
- @retval UINTN, the number of entries in the gExceptionType[] array.
- **/
-UINTN
-MaxEfiException (
- VOID
- )
-{
- return sizeof (gExceptionType)/sizeof (EFI_EXCEPTION_TYPE_ENTRY);
-}
-
-
-/**
- Return the number of entries in the gRegisters[]
-
- @retval UINTN, the number of entries (registers) in the gRegisters[] array.
- **/
-UINTN
-MaxRegisterCount (
- VOID
- )
-{
- return sizeof (gRegisterOffsets)/sizeof (UINTN);
-}
-
-
-/**
- Check to see if the ISA is supported.
- ISA = Instruction Set Architecture
-
- @retval TRUE if Isa is supported,
- FALSE otherwise.
-**/
-BOOLEAN
-CheckIsa (
- IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
- )
-{
- return (BOOLEAN)(Isa == IsaIa32);
-}
-
-
-/**
- This takes in the register number and the System Context, and returns a pointer to the RegNumber-th register in gdb ordering
- It is, by default, set to find the register pointer of the IA32 member
-
- @param SystemContext Register content at time of the exception
- @param RegNumber The register to which we want to find a pointer
- @retval the pointer to the RegNumber-th pointer
- **/
-UINTN *
-FindPointerToRegister(
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber
- )
-{
- UINT8 *TempPtr;
- TempPtr = ((UINT8 *)SystemContext.SystemContextIa32) + gRegisterOffsets[RegNumber];
- return (UINTN *)TempPtr;
-}
-
-
-/**
- Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
-
- @param SystemContext Register content at time of the exception
- @param RegNumber the number of the register that we want to read
- @param OutBufPtr pointer to the output buffer's end. the new data will be added from this point on.
- @retval the pointer to the next character of the output buffer that is available to be written on.
- **/
-CHAR8 *
-BasicReadRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *OutBufPtr
- )
-{
- UINTN RegSize;
-
- RegSize = 0;
- while (RegSize < REG_SIZE) {
- *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> (RegSize+4)) & 0xf)];
- *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> RegSize) & 0xf)];
- RegSize = RegSize + 8;
- }
- return OutBufPtr;
-}
-
-
-/** ‘p n’
- Reads the n-th register's value into an output buffer and sends it as a packet
-
- @param SystemContext Register content at time of the exception
- @param InBuffer Pointer to the input buffer received from gdb server
- **/
-VOID
-EFIAPI
-ReadNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- )
-{
- UINTN RegNumber;
- CHAR8 OutBuffer[9]; // 1 reg=8 hex chars, and the end '\0' (escape seq)
- CHAR8 *OutBufPtr; // pointer to the output buffer
-
- RegNumber = AsciiStrHexToUintn (&InBuffer[1]);
-
- if ((RegNumber < 0) || (RegNumber >= MaxRegisterCount())) {
- SendError (GDB_EINVALIDREGNUM);
- return;
- }
-
- OutBufPtr = OutBuffer;
- OutBufPtr = BasicReadRegister(SystemContext, RegNumber, OutBufPtr);
-
- *OutBufPtr = '\0'; // the end of the buffer
- SendPacket(OutBuffer);
-}
-
-
-/** ‘g’
- Reads the general registers into an output buffer and sends it as a packet
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-ReadGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- UINTN i;
- CHAR8 OutBuffer[129]; // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
- CHAR8 *OutBufPtr; // pointer to the output buffer
-
- OutBufPtr = OutBuffer;
- for(i = 0 ; i < MaxRegisterCount() ; i++) { // there are only 16 registers to read
- OutBufPtr = BasicReadRegister(SystemContext, i, OutBufPtr);
- }
-
- *OutBufPtr = '\0'; // the end of the buffer
- SendPacket(OutBuffer);
-}
-
-
-/**
- Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
-
- @param SystemContext Register content at time of the exception
- @param RegNumber the number of the register that we want to write
- @param InBufPtr pointer to the output buffer. the new data will be extracted from the input buffer from this point on.
- @retval the pointer to the next character of the input buffer that can be used
- **/
-CHAR8 *
-BasicWriteRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *InBufPtr
- )
-{
- UINTN RegSize;
- UINTN TempValue; // the value transferred from a hex char
- UINT32 NewValue; // the new value of the RegNumber-th Register
-
- NewValue = 0;
- RegSize = 0;
- while (RegSize < REG_SIZE) {
- TempValue = HexCharToInt(*InBufPtr++);
-
- if (TempValue < 0) {
- SendError (GDB_EBADMEMDATA);
- return NULL;
- }
-
- NewValue += (TempValue << (RegSize+4));
- TempValue = HexCharToInt(*InBufPtr++);
-
- if (TempValue < 0) {
- SendError (GDB_EBADMEMDATA);
- return NULL;
- }
-
- NewValue += (TempValue << RegSize);
- RegSize = RegSize + 8;
- }
- *(FindPointerToRegister(SystemContext, RegNumber)) = NewValue;
- return InBufPtr;
-}
-
-
-/** ‘P n...=r...’
- Writes the new value of n-th register received into the input buffer to the n-th register
-
- @param SystemContext Register content at time of the exception
- @param InBuffer Ponter to the input buffer received from gdb server
- **/
-VOID
-EFIAPI
-WriteNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- )
-{
- UINTN RegNumber;
- CHAR8 RegNumBuffer[MAX_REG_NUM_BUF_SIZE]; // put the 'n..' part of the message into this array
- CHAR8 *RegNumBufPtr;
- CHAR8 *InBufPtr; // pointer to the input buffer
-
- // find the register number to write
- InBufPtr = &InBuffer[1];
- RegNumBufPtr = RegNumBuffer;
- while (*InBufPtr != '=') {
- *RegNumBufPtr++ = *InBufPtr++;
- }
- *RegNumBufPtr = '\0';
- RegNumber = AsciiStrHexToUintn (RegNumBuffer);
-
- // check if this is a valid Register Number
- if ((RegNumber < 0) || (RegNumber >= MaxRegisterCount())) {
- SendError (GDB_EINVALIDREGNUM);
- return;
- }
- InBufPtr++; // skips the '=' character
- BasicWriteRegister (SystemContext, RegNumber, InBufPtr);
- SendSuccess();
-}
-
-
-/** ‘G XX...’
- Writes the new values received into the input buffer to the general registers
-
- @param SystemContext Register content at time of the exception
- @param InBuffer Pointer to the input buffer received from gdb server
- **/
-VOID
-EFIAPI
-WriteGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- )
-{
- UINTN i;
- CHAR8 *InBufPtr; /// pointer to the input buffer
-
- // check to see if the buffer is the right size which is
- // 1 (for 'G') + 16 (for 16 registers) * 8 ( for 8 hex chars each) = 129
- if (AsciiStrLen(InBuffer) != 129) { // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
- //Bad message. Message is not the right length
- SendError (GDB_EBADBUFSIZE);
- return;
- }
-
- InBufPtr = &InBuffer[1];
-
- // Read the new values for the registers from the input buffer to an array, NewValueArray.
- // The values in the array are in the gdb ordering
- for(i=0; i < MaxRegisterCount(); i++) { // there are only 16 registers to write
- InBufPtr = BasicWriteRegister(SystemContext, i, InBufPtr);
- }
-
- SendSuccess();
-}
-
-
-/**
- Insert Single Step in the SystemContext
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-AddSingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- SystemContext.SystemContextIa32->Eflags |= TF_BIT; //Setting the TF bit.
-}
-
-
-/**
- Remove Single Step in the SystemContext
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-RemoveSingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- SystemContext.SystemContextIa32->Eflags &= ~TF_BIT; // clearing the TF bit.
-}
-
-
-
-/** ‘c [addr ]’
- Continue. addr is Address to resume. If addr is omitted, resume at current
- Address.
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-ContinueAtAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- if (PacketData[1] != '\0') {
- SystemContext.SystemContextIa32->Eip = AsciiStrHexToUintn (&PacketData[1]);
- }
-}
-
-
-/** ‘s [addr ]’
- Single step. addr is the Address at which to resume. If addr is omitted, resume
- at same Address.
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-SingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- if (PacketData[1] != '\0') {
- SystemContext.SystemContextIa32->Eip = AsciiStrHexToUintn (&PacketData[1]);
- }
-
- AddSingleStep (SystemContext);
-}
-
-
-/**
- Returns breakpoint data address from DR0-DR3 based on the input breakpoint number
-
- @param SystemContext Register content at time of the exception
- @param BreakpointNumber Breakpoint number
-
- @retval Address Data address from DR0-DR3 based on the breakpoint number.
-
-**/
-UINTN
-GetBreakpointDataAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- )
-{
- UINTN Address;
-
- if (BreakpointNumber == 1) {
- Address = SystemContext.SystemContextIa32->Dr0;
- } else if (BreakpointNumber == 2) {
- Address = SystemContext.SystemContextIa32->Dr1;
- } else if (BreakpointNumber == 3) {
- Address = SystemContext.SystemContextIa32->Dr2;
- } else if (BreakpointNumber == 4) {
- Address = SystemContext.SystemContextIa32->Dr3;
- } else {
- Address = 0;
- }
-
- return Address;
-}
-
-
-/**
- Returns currently detected breakpoint value based on the register DR6 B0-B3 field.
- If no breakpoint is detected then it returns 0.
-
- @param SystemContext Register content at time of the exception
-
- @retval {1-4} Currently detected breakpoint value
- @retval 0 No breakpoint detected.
-
-**/
-UINTN
-GetBreakpointDetected (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- IA32_DR6 Dr6;
- UINTN BreakpointNumber;
-
- Dr6.UintN = SystemContext.SystemContextIa32->Dr6;
-
- if (Dr6.Bits.B0 == 1) {
- BreakpointNumber = 1;
- } else if (Dr6.Bits.B1 == 1) {
- BreakpointNumber = 2;
- } else if (Dr6.Bits.B2 == 1) {
- BreakpointNumber = 3;
- } else if (Dr6.Bits.B3 == 1) {
- BreakpointNumber = 4;
- } else {
- BreakpointNumber = 0; //No breakpoint detected
- }
-
- return BreakpointNumber;
-}
-
-
-/**
- Returns Breakpoint type (InstructionExecution, DataWrite, DataRead or DataReadWrite)
- based on the Breakpoint number
-
- @param SystemContext Register content at time of the exception
- @param BreakpointNumber Breakpoint number
-
- @retval BREAK_TYPE Breakpoint type value read from register DR7 RWn field
- For unknown value, it returns NotSupported.
-
-**/
-BREAK_TYPE
-GetBreakpointType (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- )
-{
- IA32_DR7 Dr7;
- BREAK_TYPE Type = NotSupported; //Default is NotSupported type
-
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (BreakpointNumber == 1) {
- Type = (BREAK_TYPE) Dr7.Bits.RW0;
- } else if (BreakpointNumber == 2) {
- Type = (BREAK_TYPE) Dr7.Bits.RW1;
- } else if (BreakpointNumber == 3) {
- Type = (BREAK_TYPE) Dr7.Bits.RW2;
- } else if (BreakpointNumber == 4) {
- Type = (BREAK_TYPE) Dr7.Bits.RW3;
- }
-
- return Type;
-}
-
-
-/**
- Parses Length and returns the length which DR7 LENn field accepts.
- For example: If we receive 1-Byte length then we should return 0.
- Zero gets written to DR7 LENn field.
-
- @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
-
- @retval Length Appropriate converted values which DR7 LENn field accepts.
-
-**/
-UINTN
-ConvertLengthData (
- IN UINTN Length
- )
-{
- if (Length == 1) { //1-Byte length
- return 0;
- } else if (Length == 2) { //2-Byte length
- return 1;
- } else if (Length == 4) { //4-Byte length
- return 3;
- } else { //Undefined or 8-byte length
- return 2;
- }
-}
-
-
-/**
- Finds the next free debug register. If all the registers are occupied then
- EFI_OUT_OF_RESOURCES is returned.
-
- @param SystemContext Register content at time of the exception
- @param Register Register value (0 - 3 for the first free debug register)
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-FindNextFreeDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- OUT UINTN *Register
- )
-{
- IA32_DR7 Dr7;
-
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (Dr7.Bits.G0 == 0) {
- *Register = 0;
- } else if (Dr7.Bits.G1 == 0) {
- *Register = 1;
- } else if (Dr7.Bits.G2 == 0) {
- *Register = 2;
- } else if (Dr7.Bits.G3 == 0) {
- *Register = 3;
- } else {
- return EFI_OUT_OF_RESOURCES;
- }
-
- return EFI_SUCCESS;
-}
-
-
-/**
- Enables the debug register. Writes Address value to appropriate DR0-3 register.
- Sets LENn, Gn, RWn bits in DR7 register.
-
- @param SystemContext Register content at time of the exception
- @param Register Register value (0 - 3)
- @param Address Breakpoint address value
- @param Type Breakpoint type (Instruction, Data write, Data read
- or write etc.)
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-EnableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type
- )
-{
- IA32_DR7 Dr7;
-
- //Convert length data
- Length = ConvertLengthData (Length);
-
- //For Instruction execution, length should be 0
- //(Ref. Intel reference manual 18.2.4)
- if ((Type == 0) && (Length != 0)) {
- return EFI_INVALID_PARAMETER;
- }
-
- //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
- //software breakpoint. We should send empty packet in both these cases.
- if ((Type == (BREAK_TYPE)DataRead) ||
- (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
- return EFI_UNSUPPORTED;
- }
-
- //Read DR7 so appropriate Gn, RWn and LENn bits can be modified.
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (Register == 0) {
- SystemContext.SystemContextIa32->Dr0 = Address;
- Dr7.Bits.G0 = 1;
- Dr7.Bits.RW0 = Type;
- Dr7.Bits.LEN0 = Length;
- } else if (Register == 1) {
- SystemContext.SystemContextIa32->Dr1 = Address;
- Dr7.Bits.G1 = 1;
- Dr7.Bits.RW1 = Type;
- Dr7.Bits.LEN1 = Length;
- } else if (Register == 2) {
- SystemContext.SystemContextIa32->Dr2 = Address;
- Dr7.Bits.G2 = 1;
- Dr7.Bits.RW2 = Type;
- Dr7.Bits.LEN2 = Length;
- } else if (Register == 3) {
- SystemContext.SystemContextIa32->Dr3 = Address;
- Dr7.Bits.G3 = 1;
- Dr7.Bits.RW3 = Type;
- Dr7.Bits.LEN3 = Length;
- } else {
- return EFI_INVALID_PARAMETER;
- }
-
- //Update Dr7 with appropriate Gn, RWn and LENn bits
- SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
-
- return EFI_SUCCESS;
-}
-
-
-/**
- Returns register number 0 - 3 for the maching debug register.
- This function compares incoming Address, Type, Length and
- if there is a match then it returns the appropriate register number.
- In case of mismatch, function returns EFI_NOT_FOUND message.
-
- @param SystemContext Register content at time of the exception
- @param Address Breakpoint address value
- @param Length Breakpoint length value
- @param Type Breakpoint type (Instruction, Data write,
- Data read or write etc.)
- @param Register Register value to be returned
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-FindMatchingDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type,
- OUT UINTN *Register
- )
-{
- IA32_DR7 Dr7;
-
- //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
- //software breakpoint. We should send empty packet in both these cases.
- if ((Type == (BREAK_TYPE)DataRead) ||
- (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
- return EFI_UNSUPPORTED;
- }
-
- //Convert length data
- Length = ConvertLengthData(Length);
-
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if ((Dr7.Bits.G0 == 1) &&
- (Dr7.Bits.LEN0 == Length) &&
- (Dr7.Bits.RW0 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr0)) {
- *Register = 0;
- } else if ((Dr7.Bits.G1 == 1) &&
- (Dr7.Bits.LEN1 == Length) &&
- (Dr7.Bits.RW1 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr1)) {
- *Register = 1;
- } else if ((Dr7.Bits.G2 == 1) &&
- (Dr7.Bits.LEN2 == Length) &&
- (Dr7.Bits.RW2 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr2)) {
- *Register = 2;
- } else if ((Dr7.Bits.G3 == 1) &&
- (Dr7.Bits.LEN3 == Length) &&
- (Dr7.Bits.RW3 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr3)) {
- *Register = 3;
- } else {
- Print ((CHAR16 *)L"No match found..\n");
- return EFI_NOT_FOUND;
- }
-
- return EFI_SUCCESS;
-}
-
-
-/**
- Disables the particular debug register.
-
- @param SystemContext Register content at time of the exception
- @param Register Register to be disabled
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-DisableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register
- )
-{
- IA32_DR7 Dr7;
- UINTN Address = 0;
-
- //Read DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (Register == 0) {
- SystemContext.SystemContextIa32->Dr0 = Address;
- Dr7.Bits.G0 = 0;
- Dr7.Bits.RW0 = 0;
- Dr7.Bits.LEN0 = 0;
- } else if (Register == 1) {
- SystemContext.SystemContextIa32->Dr1 = Address;
- Dr7.Bits.G1 = 0;
- Dr7.Bits.RW1 = 0;
- Dr7.Bits.LEN1 = 0;
- } else if (Register == 2) {
- SystemContext.SystemContextIa32->Dr2 = Address;
- Dr7.Bits.G2 = 0;
- Dr7.Bits.RW2 = 0;
- Dr7.Bits.LEN2 = 0;
- } else if (Register == 3) {
- SystemContext.SystemContextIa32->Dr3 = Address;
- Dr7.Bits.G3 = 0;
- Dr7.Bits.RW3 = 0;
- Dr7.Bits.LEN3 = 0;
- } else {
- return EFI_INVALID_PARAMETER;
- }
-
- //Update DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
- SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
-
- return EFI_SUCCESS;
-}
-
-
-/**
- ‘Z1, [addr], [length]’
- ‘Z2, [addr], [length]’
- ‘Z3, [addr], [length]’
- ‘Z4, [addr], [length]’
-
- Insert hardware breakpoint/watchpoint at address addr of size length
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-InsertBreakPoint (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- UINTN Type;
- UINTN Address;
- UINTN Length;
- UINTN Register;
- EFI_STATUS Status;
- BREAK_TYPE BreakType = NotSupported;
- UINTN ErrorCode;
-
- ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
- if (ErrorCode > 0) {
- SendError ((UINT8)ErrorCode);
- return;
- }
-
- switch (Type) {
-
- case 0: //Software breakpoint
- BreakType = SoftwareBreakpoint;
- break;
-
- case 1: //Hardware breakpoint
- BreakType = InstructionExecution;
- break;
-
- case 2: //Write watchpoint
- BreakType = DataWrite;
- break;
-
- case 3: //Read watchpoint
- BreakType = DataRead;
- break;
-
- case 4: //Access watchpoint
- BreakType = DataReadWrite;
- break;
-
- default :
- Print ((CHAR16 *)L"Insert breakpoint default: %x\n", Type);
- SendError (GDB_EINVALIDBRKPOINTTYPE);
- return;
- }
-
- // Find next free debug register
- Status = FindNextFreeDebugRegister (SystemContext, &Register);
- if (EFI_ERROR(Status)) {
- Print ((CHAR16 *)L"No space left on device\n");
- SendError (GDB_ENOSPACE);
- return;
- }
-
- // Write Address, length data at particular DR register
- Status = EnableDebugRegister (SystemContext, Register, Address, Length, (UINTN)BreakType);
- if (EFI_ERROR(Status)) {
-
- if (Status == EFI_UNSUPPORTED) {
- Print ((CHAR16 *)L"Not supported\n");
- SendNotSupported();
- return;
- }
-
- Print ((CHAR16 *)L"Invalid argument\n");
- SendError (GDB_EINVALIDARG);
- return;
- }
-
- SendSuccess ();
-}
-
-
-/**
- ‘z1, [addr], [length]’
- ‘z2, [addr], [length]’
- ‘z3, [addr], [length]’
- ‘z4, [addr], [length]’
-
- Remove hardware breakpoint/watchpoint at address addr of size length
-
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-RemoveBreakPoint (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- UINTN Type;
- UINTN Address;
- UINTN Length;
- UINTN Register;
- BREAK_TYPE BreakType = NotSupported;
- EFI_STATUS Status;
- UINTN ErrorCode;
-
- //Parse breakpoint packet data
- ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
- if (ErrorCode > 0) {
- SendError ((UINT8)ErrorCode);
- return;
- }
-
- switch (Type) {
-
- case 0: //Software breakpoint
- BreakType = SoftwareBreakpoint;
- break;
-
- case 1: //Hardware breakpoint
- BreakType = InstructionExecution;
- break;
-
- case 2: //Write watchpoint
- BreakType = DataWrite;
- break;
-
- case 3: //Read watchpoint
- BreakType = DataRead;
- break;
-
- case 4: //Access watchpoint
- BreakType = DataReadWrite;
- break;
-
- default :
- SendError (GDB_EINVALIDBRKPOINTTYPE);
- return;
- }
-
- //Find matching debug register
- Status = FindMatchingDebugRegister (SystemContext, Address, Length, (UINTN)BreakType, &Register);
- if (EFI_ERROR(Status)) {
-
- if (Status == EFI_UNSUPPORTED) {
- Print ((CHAR16 *)L"Not supported.\n");
- SendNotSupported();
- return;
- }
-
- Print ((CHAR16 *)L"No matching register found.\n");
- SendError (GDB_ENOSPACE);
- return;
- }
-
- //Remove breakpoint
- Status = DisableDebugRegister(SystemContext, Register);
- if (EFI_ERROR(Status)) {
- Print ((CHAR16 *)L"Invalid argument.\n");
- SendError (GDB_EINVALIDARG);
- return;
- }
-
- SendSuccess ();
-}
-
-
-VOID
-InitializeProcessor (
- VOID
- )
-{
-}
-
-BOOLEAN
-ValidateAddress (
- IN VOID *Address
- )
-{
- return TRUE;
-}
-
-BOOLEAN
-ValidateException (
- IN EFI_EXCEPTION_TYPE ExceptionType,
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- return TRUE;
-}
-
+/** @file
+ Processor specific parts of the GDB stub
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <GdbStubInternal.h>
+
+//
+// Array of exception types that need to be hooked by the debugger
+// {EFI mapping, GDB mapping}
+//
+EFI_EXCEPTION_TYPE_ENTRY gExceptionType[] = {
+ { EXCEPT_IA32_DIVIDE_ERROR, GDB_SIGFPE },
+ { EXCEPT_IA32_DEBUG, GDB_SIGTRAP },
+ { EXCEPT_IA32_NMI, GDB_SIGEMT },
+ { EXCEPT_IA32_BREAKPOINT, GDB_SIGTRAP },
+ { EXCEPT_IA32_OVERFLOW, GDB_SIGSEGV },
+ { EXCEPT_IA32_BOUND, GDB_SIGSEGV },
+ { EXCEPT_IA32_INVALID_OPCODE, GDB_SIGILL },
+ { EXCEPT_IA32_DOUBLE_FAULT, GDB_SIGEMT },
+ { EXCEPT_IA32_STACK_FAULT, GDB_SIGSEGV },
+ { EXCEPT_IA32_GP_FAULT, GDB_SIGSEGV },
+ { EXCEPT_IA32_PAGE_FAULT, GDB_SIGSEGV },
+ { EXCEPT_IA32_FP_ERROR, GDB_SIGEMT },
+ { EXCEPT_IA32_ALIGNMENT_CHECK, GDB_SIGEMT },
+ { EXCEPT_IA32_MACHINE_CHECK, GDB_SIGEMT }
+};
+
+
+// The offsets of registers SystemContext.
+// The fields in the array are in the gdb ordering.
+//
+//16 regs
+UINTN gRegisterOffsets[] = {
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eax),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ecx),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edx),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebx),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esp),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebp),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esi),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edi),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eip),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eflags),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Cs),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ss),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ds),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Es),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Fs),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Gs)
+};
+
+
+//Debug only..
+VOID
+PrintReg (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ Print ((CHAR16 *)L"EAX: %x ", SystemContext.SystemContextIa32->Eax);
+ Print ((CHAR16 *)L"ECX: %x ", SystemContext.SystemContextIa32->Ecx);
+ Print ((CHAR16 *)L"EDX: %x ", SystemContext.SystemContextIa32->Edx);
+ Print ((CHAR16 *)L"EBX: %x ", SystemContext.SystemContextIa32->Ebx);
+ Print ((CHAR16 *)L"ESP: %x ", SystemContext.SystemContextIa32->Esp);
+ Print ((CHAR16 *)L"EBP: %x ", SystemContext.SystemContextIa32->Ebp);
+ Print ((CHAR16 *)L"ESI: %x ", SystemContext.SystemContextIa32->Esi);
+ Print ((CHAR16 *)L"EDI: %x ", SystemContext.SystemContextIa32->Edi);
+ Print ((CHAR16 *)L"EIP: %x\n", SystemContext.SystemContextIa32->Eip);
+ Print ((CHAR16 *)L"EFlags: %x\n", SystemContext.SystemContextIa32->Eflags);
+}
+
+//Debug only..
+VOID
+PrintDRreg (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ Print ((CHAR16 *)L"DR0: %x ", SystemContext.SystemContextIa32->Dr0);
+ Print ((CHAR16 *)L"DR1: %x ", SystemContext.SystemContextIa32->Dr1);
+ Print ((CHAR16 *)L"DR2: %x ", SystemContext.SystemContextIa32->Dr2);
+ Print ((CHAR16 *)L"DR3: %x ", SystemContext.SystemContextIa32->Dr3);
+ Print ((CHAR16 *)L"DR6: %x ", SystemContext.SystemContextIa32->Dr6);
+ Print ((CHAR16 *)L"DR7: %x\n", SystemContext.SystemContextIa32->Dr7);
+}
+
+
+/**
+ Return the number of entries in the gExceptionType[]
+
+ @retval UINTN, the number of entries in the gExceptionType[] array.
+ **/
+UINTN
+MaxEfiException (
+ VOID
+ )
+{
+ return sizeof (gExceptionType)/sizeof (EFI_EXCEPTION_TYPE_ENTRY);
+}
+
+
+/**
+ Return the number of entries in the gRegisters[]
+
+ @retval UINTN, the number of entries (registers) in the gRegisters[] array.
+ **/
+UINTN
+MaxRegisterCount (
+ VOID
+ )
+{
+ return sizeof (gRegisterOffsets)/sizeof (UINTN);
+}
+
+
+/**
+ Check to see if the ISA is supported.
+ ISA = Instruction Set Architecture
+
+ @retval TRUE if Isa is supported,
+ FALSE otherwise.
+**/
+BOOLEAN
+CheckIsa (
+ IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
+ )
+{
+ return (BOOLEAN)(Isa == IsaIa32);
+}
+
+
+/**
+ This takes in the register number and the System Context, and returns a pointer to the RegNumber-th register in gdb ordering
+ It is, by default, set to find the register pointer of the IA32 member
+
+ @param SystemContext Register content at time of the exception
+ @param RegNumber The register to which we want to find a pointer
+ @retval the pointer to the RegNumber-th pointer
+ **/
+UINTN *
+FindPointerToRegister(
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber
+ )
+{
+ UINT8 *TempPtr;
+ TempPtr = ((UINT8 *)SystemContext.SystemContextIa32) + gRegisterOffsets[RegNumber];
+ return (UINTN *)TempPtr;
+}
+
+
+/**
+ Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
+
+ @param SystemContext Register content at time of the exception
+ @param RegNumber the number of the register that we want to read
+ @param OutBufPtr pointer to the output buffer's end. the new data will be added from this point on.
+ @retval the pointer to the next character of the output buffer that is available to be written on.
+ **/
+CHAR8 *
+BasicReadRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *OutBufPtr
+ )
+{
+ UINTN RegSize;
+
+ RegSize = 0;
+ while (RegSize < REG_SIZE) {
+ *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> (RegSize+4)) & 0xf)];
+ *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> RegSize) & 0xf)];
+ RegSize = RegSize + 8;
+ }
+ return OutBufPtr;
+}
+
+
+/** ‘p n’
+ Reads the n-th register's value into an output buffer and sends it as a packet
+
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Pointer to the input buffer received from gdb server
+ **/
+VOID
+EFIAPI
+ReadNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ )
+{
+ UINTN RegNumber;
+ CHAR8 OutBuffer[9]; // 1 reg=8 hex chars, and the end '\0' (escape seq)
+ CHAR8 *OutBufPtr; // pointer to the output buffer
+
+ RegNumber = AsciiStrHexToUintn (&InBuffer[1]);
+
+ if ((RegNumber < 0) || (RegNumber >= MaxRegisterCount())) {
+ SendError (GDB_EINVALIDREGNUM);
+ return;
+ }
+
+ OutBufPtr = OutBuffer;
+ OutBufPtr = BasicReadRegister(SystemContext, RegNumber, OutBufPtr);
+
+ *OutBufPtr = '\0'; // the end of the buffer
+ SendPacket(OutBuffer);
+}
+
+
+/** ‘g’
+ Reads the general registers into an output buffer and sends it as a packet
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+ReadGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ UINTN i;
+ CHAR8 OutBuffer[129]; // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
+ CHAR8 *OutBufPtr; // pointer to the output buffer
+
+ OutBufPtr = OutBuffer;
+ for(i = 0 ; i < MaxRegisterCount() ; i++) { // there are only 16 registers to read
+ OutBufPtr = BasicReadRegister(SystemContext, i, OutBufPtr);
+ }
+
+ *OutBufPtr = '\0'; // the end of the buffer
+ SendPacket(OutBuffer);
+}
+
+
+/**
+ Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
+
+ @param SystemContext Register content at time of the exception
+ @param RegNumber the number of the register that we want to write
+ @param InBufPtr pointer to the output buffer. the new data will be extracted from the input buffer from this point on.
+ @retval the pointer to the next character of the input buffer that can be used
+ **/
+CHAR8 *
+BasicWriteRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *InBufPtr
+ )
+{
+ UINTN RegSize;
+ UINTN TempValue; // the value transferred from a hex char
+ UINT32 NewValue; // the new value of the RegNumber-th Register
+
+ NewValue = 0;
+ RegSize = 0;
+ while (RegSize < REG_SIZE) {
+ TempValue = HexCharToInt(*InBufPtr++);
+
+ if (TempValue < 0) {
+ SendError (GDB_EBADMEMDATA);
+ return NULL;
+ }
+
+ NewValue += (TempValue << (RegSize+4));
+ TempValue = HexCharToInt(*InBufPtr++);
+
+ if (TempValue < 0) {
+ SendError (GDB_EBADMEMDATA);
+ return NULL;
+ }
+
+ NewValue += (TempValue << RegSize);
+ RegSize = RegSize + 8;
+ }
+ *(FindPointerToRegister(SystemContext, RegNumber)) = NewValue;
+ return InBufPtr;
+}
+
+
+/** ‘P n...=r...’
+ Writes the new value of n-th register received into the input buffer to the n-th register
+
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Ponter to the input buffer received from gdb server
+ **/
+VOID
+EFIAPI
+WriteNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ )
+{
+ UINTN RegNumber;
+ CHAR8 RegNumBuffer[MAX_REG_NUM_BUF_SIZE]; // put the 'n..' part of the message into this array
+ CHAR8 *RegNumBufPtr;
+ CHAR8 *InBufPtr; // pointer to the input buffer
+
+ // find the register number to write
+ InBufPtr = &InBuffer[1];
+ RegNumBufPtr = RegNumBuffer;
+ while (*InBufPtr != '=') {
+ *RegNumBufPtr++ = *InBufPtr++;
+ }
+ *RegNumBufPtr = '\0';
+ RegNumber = AsciiStrHexToUintn (RegNumBuffer);
+
+ // check if this is a valid Register Number
+ if ((RegNumber < 0) || (RegNumber >= MaxRegisterCount())) {
+ SendError (GDB_EINVALIDREGNUM);
+ return;
+ }
+ InBufPtr++; // skips the '=' character
+ BasicWriteRegister (SystemContext, RegNumber, InBufPtr);
+ SendSuccess();
+}
+
+
+/** ‘G XX...’
+ Writes the new values received into the input buffer to the general registers
+
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Pointer to the input buffer received from gdb server
+ **/
+VOID
+EFIAPI
+WriteGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ )
+{
+ UINTN i;
+ CHAR8 *InBufPtr; /// pointer to the input buffer
+
+ // check to see if the buffer is the right size which is
+ // 1 (for 'G') + 16 (for 16 registers) * 8 ( for 8 hex chars each) = 129
+ if (AsciiStrLen(InBuffer) != 129) { // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
+ //Bad message. Message is not the right length
+ SendError (GDB_EBADBUFSIZE);
+ return;
+ }
+
+ InBufPtr = &InBuffer[1];
+
+ // Read the new values for the registers from the input buffer to an array, NewValueArray.
+ // The values in the array are in the gdb ordering
+ for(i=0; i < MaxRegisterCount(); i++) { // there are only 16 registers to write
+ InBufPtr = BasicWriteRegister(SystemContext, i, InBufPtr);
+ }
+
+ SendSuccess();
+}
+
+
+/**
+ Insert Single Step in the SystemContext
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+AddSingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ SystemContext.SystemContextIa32->Eflags |= TF_BIT; //Setting the TF bit.
+}
+
+
+/**
+ Remove Single Step in the SystemContext
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+RemoveSingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ SystemContext.SystemContextIa32->Eflags &= ~TF_BIT; // clearing the TF bit.
+}
+
+
+
+/** ‘c [addr ]’
+ Continue. addr is Address to resume. If addr is omitted, resume at current
+ Address.
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+ContinueAtAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ if (PacketData[1] != '\0') {
+ SystemContext.SystemContextIa32->Eip = AsciiStrHexToUintn (&PacketData[1]);
+ }
+}
+
+
+/** ‘s [addr ]’
+ Single step. addr is the Address at which to resume. If addr is omitted, resume
+ at same Address.
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+SingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ if (PacketData[1] != '\0') {
+ SystemContext.SystemContextIa32->Eip = AsciiStrHexToUintn (&PacketData[1]);
+ }
+
+ AddSingleStep (SystemContext);
+}
+
+
+/**
+ Returns breakpoint data address from DR0-DR3 based on the input breakpoint number
+
+ @param SystemContext Register content at time of the exception
+ @param BreakpointNumber Breakpoint number
+
+ @retval Address Data address from DR0-DR3 based on the breakpoint number.
+
+**/
+UINTN
+GetBreakpointDataAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ )
+{
+ UINTN Address;
+
+ if (BreakpointNumber == 1) {
+ Address = SystemContext.SystemContextIa32->Dr0;
+ } else if (BreakpointNumber == 2) {
+ Address = SystemContext.SystemContextIa32->Dr1;
+ } else if (BreakpointNumber == 3) {
+ Address = SystemContext.SystemContextIa32->Dr2;
+ } else if (BreakpointNumber == 4) {
+ Address = SystemContext.SystemContextIa32->Dr3;
+ } else {
+ Address = 0;
+ }
+
+ return Address;
+}
+
+
+/**
+ Returns currently detected breakpoint value based on the register DR6 B0-B3 field.
+ If no breakpoint is detected then it returns 0.
+
+ @param SystemContext Register content at time of the exception
+
+ @retval {1-4} Currently detected breakpoint value
+ @retval 0 No breakpoint detected.
+
+**/
+UINTN
+GetBreakpointDetected (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ IA32_DR6 Dr6;
+ UINTN BreakpointNumber;
+
+ Dr6.UintN = SystemContext.SystemContextIa32->Dr6;
+
+ if (Dr6.Bits.B0 == 1) {
+ BreakpointNumber = 1;
+ } else if (Dr6.Bits.B1 == 1) {
+ BreakpointNumber = 2;
+ } else if (Dr6.Bits.B2 == 1) {
+ BreakpointNumber = 3;
+ } else if (Dr6.Bits.B3 == 1) {
+ BreakpointNumber = 4;
+ } else {
+ BreakpointNumber = 0; //No breakpoint detected
+ }
+
+ return BreakpointNumber;
+}
+
+
+/**
+ Returns Breakpoint type (InstructionExecution, DataWrite, DataRead or DataReadWrite)
+ based on the Breakpoint number
+
+ @param SystemContext Register content at time of the exception
+ @param BreakpointNumber Breakpoint number
+
+ @retval BREAK_TYPE Breakpoint type value read from register DR7 RWn field
+ For unknown value, it returns NotSupported.
+
+**/
+BREAK_TYPE
+GetBreakpointType (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ )
+{
+ IA32_DR7 Dr7;
+ BREAK_TYPE Type = NotSupported; //Default is NotSupported type
+
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (BreakpointNumber == 1) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW0;
+ } else if (BreakpointNumber == 2) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW1;
+ } else if (BreakpointNumber == 3) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW2;
+ } else if (BreakpointNumber == 4) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW3;
+ }
+
+ return Type;
+}
+
+
+/**
+ Parses Length and returns the length which DR7 LENn field accepts.
+ For example: If we receive 1-Byte length then we should return 0.
+ Zero gets written to DR7 LENn field.
+
+ @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
+
+ @retval Length Appropriate converted values which DR7 LENn field accepts.
+
+**/
+UINTN
+ConvertLengthData (
+ IN UINTN Length
+ )
+{
+ if (Length == 1) { //1-Byte length
+ return 0;
+ } else if (Length == 2) { //2-Byte length
+ return 1;
+ } else if (Length == 4) { //4-Byte length
+ return 3;
+ } else { //Undefined or 8-byte length
+ return 2;
+ }
+}
+
+
+/**
+ Finds the next free debug register. If all the registers are occupied then
+ EFI_OUT_OF_RESOURCES is returned.
+
+ @param SystemContext Register content at time of the exception
+ @param Register Register value (0 - 3 for the first free debug register)
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+FindNextFreeDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ OUT UINTN *Register
+ )
+{
+ IA32_DR7 Dr7;
+
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (Dr7.Bits.G0 == 0) {
+ *Register = 0;
+ } else if (Dr7.Bits.G1 == 0) {
+ *Register = 1;
+ } else if (Dr7.Bits.G2 == 0) {
+ *Register = 2;
+ } else if (Dr7.Bits.G3 == 0) {
+ *Register = 3;
+ } else {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Enables the debug register. Writes Address value to appropriate DR0-3 register.
+ Sets LENn, Gn, RWn bits in DR7 register.
+
+ @param SystemContext Register content at time of the exception
+ @param Register Register value (0 - 3)
+ @param Address Breakpoint address value
+ @param Type Breakpoint type (Instruction, Data write, Data read
+ or write etc.)
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+EnableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type
+ )
+{
+ IA32_DR7 Dr7;
+
+ //Convert length data
+ Length = ConvertLengthData (Length);
+
+ //For Instruction execution, length should be 0
+ //(Ref. Intel reference manual 18.2.4)
+ if ((Type == 0) && (Length != 0)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
+ //software breakpoint. We should send empty packet in both these cases.
+ if ((Type == (BREAK_TYPE)DataRead) ||
+ (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //Read DR7 so appropriate Gn, RWn and LENn bits can be modified.
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (Register == 0) {
+ SystemContext.SystemContextIa32->Dr0 = Address;
+ Dr7.Bits.G0 = 1;
+ Dr7.Bits.RW0 = Type;
+ Dr7.Bits.LEN0 = Length;
+ } else if (Register == 1) {
+ SystemContext.SystemContextIa32->Dr1 = Address;
+ Dr7.Bits.G1 = 1;
+ Dr7.Bits.RW1 = Type;
+ Dr7.Bits.LEN1 = Length;
+ } else if (Register == 2) {
+ SystemContext.SystemContextIa32->Dr2 = Address;
+ Dr7.Bits.G2 = 1;
+ Dr7.Bits.RW2 = Type;
+ Dr7.Bits.LEN2 = Length;
+ } else if (Register == 3) {
+ SystemContext.SystemContextIa32->Dr3 = Address;
+ Dr7.Bits.G3 = 1;
+ Dr7.Bits.RW3 = Type;
+ Dr7.Bits.LEN3 = Length;
+ } else {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Update Dr7 with appropriate Gn, RWn and LENn bits
+ SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Returns register number 0 - 3 for the maching debug register.
+ This function compares incoming Address, Type, Length and
+ if there is a match then it returns the appropriate register number.
+ In case of mismatch, function returns EFI_NOT_FOUND message.
+
+ @param SystemContext Register content at time of the exception
+ @param Address Breakpoint address value
+ @param Length Breakpoint length value
+ @param Type Breakpoint type (Instruction, Data write,
+ Data read or write etc.)
+ @param Register Register value to be returned
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+FindMatchingDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type,
+ OUT UINTN *Register
+ )
+{
+ IA32_DR7 Dr7;
+
+ //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
+ //software breakpoint. We should send empty packet in both these cases.
+ if ((Type == (BREAK_TYPE)DataRead) ||
+ (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //Convert length data
+ Length = ConvertLengthData(Length);
+
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if ((Dr7.Bits.G0 == 1) &&
+ (Dr7.Bits.LEN0 == Length) &&
+ (Dr7.Bits.RW0 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr0)) {
+ *Register = 0;
+ } else if ((Dr7.Bits.G1 == 1) &&
+ (Dr7.Bits.LEN1 == Length) &&
+ (Dr7.Bits.RW1 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr1)) {
+ *Register = 1;
+ } else if ((Dr7.Bits.G2 == 1) &&
+ (Dr7.Bits.LEN2 == Length) &&
+ (Dr7.Bits.RW2 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr2)) {
+ *Register = 2;
+ } else if ((Dr7.Bits.G3 == 1) &&
+ (Dr7.Bits.LEN3 == Length) &&
+ (Dr7.Bits.RW3 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr3)) {
+ *Register = 3;
+ } else {
+ Print ((CHAR16 *)L"No match found..\n");
+ return EFI_NOT_FOUND;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Disables the particular debug register.
+
+ @param SystemContext Register content at time of the exception
+ @param Register Register to be disabled
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+DisableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register
+ )
+{
+ IA32_DR7 Dr7;
+ UINTN Address = 0;
+
+ //Read DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (Register == 0) {
+ SystemContext.SystemContextIa32->Dr0 = Address;
+ Dr7.Bits.G0 = 0;
+ Dr7.Bits.RW0 = 0;
+ Dr7.Bits.LEN0 = 0;
+ } else if (Register == 1) {
+ SystemContext.SystemContextIa32->Dr1 = Address;
+ Dr7.Bits.G1 = 0;
+ Dr7.Bits.RW1 = 0;
+ Dr7.Bits.LEN1 = 0;
+ } else if (Register == 2) {
+ SystemContext.SystemContextIa32->Dr2 = Address;
+ Dr7.Bits.G2 = 0;
+ Dr7.Bits.RW2 = 0;
+ Dr7.Bits.LEN2 = 0;
+ } else if (Register == 3) {
+ SystemContext.SystemContextIa32->Dr3 = Address;
+ Dr7.Bits.G3 = 0;
+ Dr7.Bits.RW3 = 0;
+ Dr7.Bits.LEN3 = 0;
+ } else {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Update DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
+ SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ ‘Z1, [addr], [length]’
+ ‘Z2, [addr], [length]’
+ ‘Z3, [addr], [length]’
+ ‘Z4, [addr], [length]’
+
+ Insert hardware breakpoint/watchpoint at address addr of size length
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+InsertBreakPoint (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ UINTN Type;
+ UINTN Address;
+ UINTN Length;
+ UINTN Register;
+ EFI_STATUS Status;
+ BREAK_TYPE BreakType = NotSupported;
+ UINTN ErrorCode;
+
+ ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
+ if (ErrorCode > 0) {
+ SendError ((UINT8)ErrorCode);
+ return;
+ }
+
+ switch (Type) {
+
+ case 0: //Software breakpoint
+ BreakType = SoftwareBreakpoint;
+ break;
+
+ case 1: //Hardware breakpoint
+ BreakType = InstructionExecution;
+ break;
+
+ case 2: //Write watchpoint
+ BreakType = DataWrite;
+ break;
+
+ case 3: //Read watchpoint
+ BreakType = DataRead;
+ break;
+
+ case 4: //Access watchpoint
+ BreakType = DataReadWrite;
+ break;
+
+ default :
+ Print ((CHAR16 *)L"Insert breakpoint default: %x\n", Type);
+ SendError (GDB_EINVALIDBRKPOINTTYPE);
+ return;
+ }
+
+ // Find next free debug register
+ Status = FindNextFreeDebugRegister (SystemContext, &Register);
+ if (EFI_ERROR(Status)) {
+ Print ((CHAR16 *)L"No space left on device\n");
+ SendError (GDB_ENOSPACE);
+ return;
+ }
+
+ // Write Address, length data at particular DR register
+ Status = EnableDebugRegister (SystemContext, Register, Address, Length, (UINTN)BreakType);
+ if (EFI_ERROR(Status)) {
+
+ if (Status == EFI_UNSUPPORTED) {
+ Print ((CHAR16 *)L"Not supported\n");
+ SendNotSupported();
+ return;
+ }
+
+ Print ((CHAR16 *)L"Invalid argument\n");
+ SendError (GDB_EINVALIDARG);
+ return;
+ }
+
+ SendSuccess ();
+}
+
+
+/**
+ ‘z1, [addr], [length]’
+ ‘z2, [addr], [length]’
+ ‘z3, [addr], [length]’
+ ‘z4, [addr], [length]’
+
+ Remove hardware breakpoint/watchpoint at address addr of size length
+
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+RemoveBreakPoint (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ UINTN Type;
+ UINTN Address;
+ UINTN Length;
+ UINTN Register;
+ BREAK_TYPE BreakType = NotSupported;
+ EFI_STATUS Status;
+ UINTN ErrorCode;
+
+ //Parse breakpoint packet data
+ ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
+ if (ErrorCode > 0) {
+ SendError ((UINT8)ErrorCode);
+ return;
+ }
+
+ switch (Type) {
+
+ case 0: //Software breakpoint
+ BreakType = SoftwareBreakpoint;
+ break;
+
+ case 1: //Hardware breakpoint
+ BreakType = InstructionExecution;
+ break;
+
+ case 2: //Write watchpoint
+ BreakType = DataWrite;
+ break;
+
+ case 3: //Read watchpoint
+ BreakType = DataRead;
+ break;
+
+ case 4: //Access watchpoint
+ BreakType = DataReadWrite;
+ break;
+
+ default :
+ SendError (GDB_EINVALIDBRKPOINTTYPE);
+ return;
+ }
+
+ //Find matching debug register
+ Status = FindMatchingDebugRegister (SystemContext, Address, Length, (UINTN)BreakType, &Register);
+ if (EFI_ERROR(Status)) {
+
+ if (Status == EFI_UNSUPPORTED) {
+ Print ((CHAR16 *)L"Not supported.\n");
+ SendNotSupported();
+ return;
+ }
+
+ Print ((CHAR16 *)L"No matching register found.\n");
+ SendError (GDB_ENOSPACE);
+ return;
+ }
+
+ //Remove breakpoint
+ Status = DisableDebugRegister(SystemContext, Register);
+ if (EFI_ERROR(Status)) {
+ Print ((CHAR16 *)L"Invalid argument.\n");
+ SendError (GDB_EINVALIDARG);
+ return;
+ }
+
+ SendSuccess ();
+}
+
+
+VOID
+InitializeProcessor (
+ VOID
+ )
+{
+}
+
+BOOLEAN
+ValidateAddress (
+ IN VOID *Address
+ )
+{
+ return TRUE;
+}
+
+BOOLEAN
+ValidateException (
+ IN EFI_EXCEPTION_TYPE ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ return TRUE;
+}
+
diff --git a/EmbeddedPkg/GdbStub/SerialIo.c b/EmbeddedPkg/GdbStub/SerialIo.c
index 8fb861087..2df967a52 100644
--- a/EmbeddedPkg/GdbStub/SerialIo.c
+++ b/EmbeddedPkg/GdbStub/SerialIo.c
@@ -1,551 +1,551 @@
-/** @file
- Serial IO Abstraction for GDB stub. This allows an EFI consoles that shows up on the system
- running GDB. One consle for error information and another console for user input/output.
-
- Basic packet format is $packet-data#checksum. So every comand has 4 bytes of overhead: $,
- #, 0, 0. The 0 and 0 are the ascii characters for the checksum.
-
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <GdbStubInternal.h>
-
-//
-// Set TRUE if F Reply package signals a ctrl-c. We can not process the Ctrl-c
-// here we need to wait for the periodic callback to do this.
-//
-BOOLEAN gCtrlCBreakFlag = FALSE;
-
-//
-// If the periodic callback is called while we are processing an F packet we need
-// to let the callback know to not read from the serail stream as it could steal
-// characters from the F reponse packet
-//
-BOOLEAN gProcessingFPacket = FALSE;
-
-/**
- Process a control-C break message.
-
- Currently a place holder, remove the ASSERT when it gets implemented.
-
- @param ErrNo Error infomration from the F reply packet or other source
-
-**/
-
-VOID
-GdbCtrlCBreakMessage (
- IN UINTN ErrNo
- )
-{
- // See D.10.5 of gdb.pdf
- // This should look like a break message. Should look like SIGINT
-
- /* TODO: Make sure if we should do anything with ErrNo */
- //Turn on the global Ctrl-C flag.
- gCtrlCBreakFlag = TRUE;
-}
-
-
-/**
- Parse the F reply packet and extract the return value and an ErrNo if it exists.
-
- @param Packet Packet to parse like an F reply packet
- @param ErrNo Buffer to hold Count bytes that were read
-
- @retval -1 Error, not a valid F reply packet
- @retval other Return the return code from the F reply packet
-
-**/
-INTN
-GdbParseFReplyPacket (
- IN CHAR8 *Packet,
- OUT UINTN *ErrNo
- )
-{
- INTN RetCode;
-
- if (Packet[0] != 'F') {
- // A valid responce would be an F packet
- return -1;
- }
-
- RetCode = AsciiStrHexToUintn (&Packet[1]);
-
- // Find 1st comma
- for (;*Packet != '\0' && *Packet != ','; Packet++);
- if (*Packet == '\0') {
- *ErrNo = 0;
- return RetCode;
- }
-
- *ErrNo = AsciiStrHexToUintn (++Packet);
-
- // Find 2nd comma
- for (;*Packet != '\0' && *Packet != ','; Packet++);
- if (*Packet == '\0') {
- return RetCode;
- }
-
- if (*(++Packet) == 'C') {
- GdbCtrlCBreakMessage (*ErrNo);
- }
-
- return RetCode;
-}
-
-
-/**
- Read data from a FileDescriptor. On success number of bytes read is returned. Zero indicates
- the end of a file. On error -1 is returned. If count is zero, GdbRead returns zero.
-
- @param FileDescriptor Device to talk to.
- @param Buffer Buffer to hold Count bytes that were read
- @param Count Number of bytes to transfer.
-
- @retval -1 Error
- @retval {other} Number of bytes read.
-
-**/
-INTN
-GdbRead (
- IN INTN FileDescriptor,
- OUT VOID *Buffer,
- IN UINTN Count
- )
-{
- CHAR8 Packet[128];
- UINTN Size;
- INTN RetCode;
- UINTN ErrNo;
- BOOLEAN ReceiveDone = FALSE;
-
- // Send:
- // "Fread,XX,YYYYYYYY,XX
- //
- // XX - FileDescriptor in ASCII
- // YYYYYYYY - Buffer address in ASCII
- // XX - Count in ASCII
- // SS - check sum
- //
- Size = AsciiSPrint (Packet, sizeof (Packet), "Fread,%x,%x,%x", FileDescriptor, Buffer, Count);
- // Packet array is too small if you got this ASSERT
- ASSERT (Size < sizeof (Packet));
-
- gProcessingFPacket = TRUE;
- SendPacket (Packet);
- Print ((CHAR16 *)L"Packet sent..\n");
-
- do {
- // Reply:
- ReceivePacket (Packet, sizeof (Packet));
- Print ((CHAR16 *)L"Command received..%c\n", Packet[0]);
-
- // Process GDB commands
- switch (Packet[0]) {
- //Write memory command.
- //M addr,length:XX...
- case 'M':
- WriteToMemory (Packet);
- break;
-
- //Fretcode, errno, Ctrl-C flag
- //retcode - Count read
- case 'F':
- //Once target receives F reply packet that means the previous
- //transactions are finished.
- ReceiveDone = TRUE;
- break;
-
- //Send empty buffer
- default :
- SendNotSupported();
- break;
- }
- } while (ReceiveDone == FALSE);
-
- RetCode = GdbParseFReplyPacket (Packet, &ErrNo);
- Print ((CHAR16 *)L"RetCode: %x..ErrNo: %x..\n", RetCode, ErrNo);
-
- if (ErrNo > 0) {
- //Send error to the host if there is any.
- SendError ((UINT8)ErrNo);
- }
-
- gProcessingFPacket = FALSE;
-
- return RetCode;
-}
-
-
-/**
- Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
- nothing was written. On error -1 is returned.
-
- @param FileDescriptor Device to talk to.
- @param Buffer Buffer to hold Count bytes that are to be written
- @param Count Number of bytes to transfer.
-
- @retval -1 Error
- @retval {other} Number of bytes written.
-
-**/
-INTN
-GdbWrite (
- IN INTN FileDescriptor,
- OUT CONST VOID *Buffer,
- IN UINTN Count
- )
-{
- CHAR8 Packet[128];
- UINTN Size;
- INTN RetCode;
- UINTN ErrNo;
- BOOLEAN ReceiveDone = FALSE;
-
- // Send:
- // #Fwrite,XX,YYYYYYYY,XX$SS
- //
- // XX - FileDescriptor in ASCII
- // YYYYYYYY - Buffer address in ASCII
- // XX - Count in ASCII
- // SS - check sum
- //
- Size = AsciiSPrint (Packet, sizeof (Packet), "Fwrite,%x,%x,%x", FileDescriptor, Buffer, Count);
- // Packet array is too small if you got this ASSERT
- ASSERT (Size < sizeof (Packet));
-
- SendPacket (Packet);
- Print ((CHAR16 *)L"Packet sent..\n");
-
- do {
- // Reply:
- ReceivePacket (Packet, sizeof (Packet));
- Print ((CHAR16 *)L"Command received..%c\n", Packet[0]);
-
- // Process GDB commands
- switch (Packet[0]) {
- //Read memory command.
- //m addr,length.
- case 'm':
- ReadFromMemory (Packet);
- break;
-
- //Fretcode, errno, Ctrl-C flag
- //retcode - Count read
- case 'F':
- //Once target receives F reply packet that means the previous
- //transactions are finished.
- ReceiveDone = TRUE;
- break;
-
- //Send empty buffer
- default :
- SendNotSupported();
- break;
- }
- } while (ReceiveDone == FALSE);
-
- RetCode = GdbParseFReplyPacket (Packet, &ErrNo);
- Print ((CHAR16 *)L"RetCode: %x..ErrNo: %x..\n", RetCode, ErrNo);
-
- //Send error to the host if there is any.
- if (ErrNo > 0) {
- SendError((UINT8)ErrNo);
- }
-
- return RetCode;
-}
-
-
-/**
- Reset the serial device.
-
- @param This Protocol instance pointer.
-
- @retval EFI_SUCCESS The device was reset.
- @retval EFI_DEVICE_ERROR The serial device could not be reset.
-
-**/
-EFI_STATUS
-EFIAPI
-GdbSerialReset (
- IN EFI_SERIAL_IO_PROTOCOL *This
- )
-{
- return EFI_SUCCESS;
-}
-
-
-/**
- Sets the baud rate, receive FIFO depth, transmit/receice time out, parity,
- data buts, and stop bits on a serial device.
-
- @param This Protocol instance pointer.
- @param BaudRate The requested baud rate. A BaudRate value of 0 will use the the
- device's default interface speed.
- @param ReveiveFifoDepth The requested depth of the FIFO on the receive side of the
- serial interface. A ReceiveFifoDepth value of 0 will use
- the device's dfault FIFO depth.
- @param Timeout The requested time out for a single character in microseconds.
- This timeout applies to both the transmit and receive side of the
- interface. A Timeout value of 0 will use the device's default time
- out value.
- @param Parity The type of parity to use on this serial device. A Parity value of
- DefaultParity will use the device's default parity value.
- @param DataBits The number of data bits to use on the serial device. A DataBits
- vaule of 0 will use the device's default data bit setting.
- @param StopBits The number of stop bits to use on this serial device. A StopBits
- value of DefaultStopBits will use the device's default number of
- stop bits.
-
- @retval EFI_SUCCESS The device was reset.
- @retval EFI_DEVICE_ERROR The serial device could not be reset.
-
-**/
-EFI_STATUS
-EFIAPI
-GdbSerialSetAttributes (
- IN EFI_SERIAL_IO_PROTOCOL *This,
- IN UINT64 BaudRate,
- IN UINT32 ReceiveFifoDepth,
- IN UINT32 Timeout,
- IN EFI_PARITY_TYPE Parity,
- IN UINT8 DataBits,
- IN EFI_STOP_BITS_TYPE StopBits
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-
-/**
- Set the control bits on a serial device
-
- @param This Protocol instance pointer.
- @param Control Set the bits of Control that are settable.
-
- @retval EFI_SUCCESS The new control bits were set on the serial device.
- @retval EFI_UNSUPPORTED The serial device does not support this operation.
- @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
-
-**/
-EFI_STATUS
-EFIAPI
-GdbSerialSetControl (
- IN EFI_SERIAL_IO_PROTOCOL *This,
- IN UINT32 Control
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-
-/**
- Retrieves the status of thecontrol bits on a serial device
-
- @param This Protocol instance pointer.
- @param Control A pointer to return the current Control signals from the serial device.
-
- @retval EFI_SUCCESS The control bits were read from the serial device.
- @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
-
-**/
-EFI_STATUS
-EFIAPI
-GdbSerialGetControl (
- IN EFI_SERIAL_IO_PROTOCOL *This,
- OUT UINT32 *Control
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-
-/**
- Writes data to a serial device.
-
- @param This Protocol instance pointer.
- @param BufferSize On input, the size of the Buffer. On output, the amount of
- data actually written.
- @param Buffer The buffer of data to write
-
- @retval EFI_SUCCESS The data was written.
- @retval EFI_DEVICE_ERROR The device reported an error.
- @retval EFI_TIMEOUT The data write was stopped due to a timeout.
-
-**/
-EFI_STATUS
-EFIAPI
-GdbSerialWrite (
- IN EFI_SERIAL_IO_PROTOCOL *This,
- IN OUT UINTN *BufferSize,
- IN VOID *Buffer
- )
-{
- GDB_SERIAL_DEV *SerialDev;
- UINTN Return;
-
- SerialDev = GDB_SERIAL_DEV_FROM_THIS (This);
-
- Return = GdbWrite (SerialDev->OutFileDescriptor, Buffer, *BufferSize);
- if (Return == (UINTN)-1) {
- return EFI_DEVICE_ERROR;
- }
-
- if (Return != *BufferSize) {
- *BufferSize = Return;
- }
-
- return EFI_SUCCESS;
-}
-
-/**
- Writes data to a serial device.
-
- @param This Protocol instance pointer.
- @param BufferSize On input, the size of the Buffer. On output, the amount of
- data returned in Buffer.
- @param Buffer The buffer to return the data into.
-
- @retval EFI_SUCCESS The data was read.
- @retval EFI_DEVICE_ERROR The device reported an error.
- @retval EFI_TIMEOUT The data write was stopped due to a timeout.
-
-**/
-
-EFI_STATUS
-EFIAPI
-GdbSerialRead (
- IN EFI_SERIAL_IO_PROTOCOL *This,
- IN OUT UINTN *BufferSize,
- OUT VOID *Buffer
- )
-{
- GDB_SERIAL_DEV *SerialDev;
- UINTN Return;
-
- SerialDev = GDB_SERIAL_DEV_FROM_THIS (This);
-
- Return = GdbRead (SerialDev->InFileDescriptor, Buffer, *BufferSize);
- if (Return == (UINTN)-1) {
- return EFI_DEVICE_ERROR;
- }
-
- if (Return != *BufferSize) {
- *BufferSize = Return;
- }
-
- return EFI_SUCCESS;
-}
-
-
-//
-// Template used to initailize the GDB Serial IO protocols
-//
-GDB_SERIAL_DEV gdbSerialDevTemplate = {
- GDB_SERIAL_DEV_SIGNATURE,
- NULL,
-
- { // SerialIo
- SERIAL_IO_INTERFACE_REVISION,
- GdbSerialReset,
- GdbSerialSetAttributes,
- GdbSerialSetControl,
- GdbSerialGetControl,
- GdbSerialWrite,
- GdbSerialRead,
- NULL
- },
- { // SerialMode
- 0, // ControlMask
- 0, // Timeout
- 0, // BaudRate
- 1, // RceiveFifoDepth
- 0, // DataBits
- 0, // Parity
- 0 // StopBits
- },
- {
- {
- HARDWARE_DEVICE_PATH,
- HW_VENDOR_DP,
- {
- (UINT8) (sizeof (VENDOR_DEVICE_PATH) + sizeof (UINT32)),
- (UINT8) ((sizeof (VENDOR_DEVICE_PATH) + sizeof (UINT32)) >> 8)
- },
- EFI_SERIAL_IO_PROTOCOL_GUID,
- },
- 0,
- {
- END_DEVICE_PATH_TYPE,
- END_ENTIRE_DEVICE_PATH_SUBTYPE,
- {
- (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL)),
- (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL) >> 8)
- }
- },
- },
- GDB_STDIN,
- GDB_STDOUT
-};
-
-
-/**
- Make two serial consoles: 1) StdIn and StdOut via GDB. 2) StdErr via GDB.
-
- These console show up on the remote system running GDB
-
-**/
-VOID
-GdbInitializeSerialConsole (
- VOID
- )
-{
- EFI_STATUS Status;
- GDB_SERIAL_DEV *StdOutSerialDev;
- GDB_SERIAL_DEV *StdErrSerialDev;
-
- // Use the template to make a copy of the Serial Console private data structure.
- StdOutSerialDev = AllocateCopyPool (sizeof (GDB_SERIAL_DEV), &gdbSerialDevTemplate);
- ASSERT (StdOutSerialDev != NULL);
-
- // Fixup pointer after the copy
- StdOutSerialDev->SerialIo.Mode = &StdOutSerialDev->SerialMode;
-
- StdErrSerialDev = AllocateCopyPool (sizeof (GDB_SERIAL_DEV), &gdbSerialDevTemplate);
- ASSERT (StdErrSerialDev != NULL);
-
- // Fixup pointer and modify stuff that is different for StdError
- StdErrSerialDev->SerialIo.Mode = &StdErrSerialDev->SerialMode;
- StdErrSerialDev->DevicePath.Index = 1;
- StdErrSerialDev->OutFileDescriptor = GDB_STDERR;
-
- // Make a new handle with Serial IO protocol and its device path on it.
- Status = gBS->InstallMultipleProtocolInterfaces (
- &StdOutSerialDev->Handle,
- &gEfiSerialIoProtocolGuid, &StdOutSerialDev->SerialIo,
- &gEfiDevicePathProtocolGuid, &StdOutSerialDev->DevicePath,
- NULL
- );
- ASSERT_EFI_ERROR (Status);
-
- // Make a new handle with Serial IO protocol and its device path on it.
- Status = gBS->InstallMultipleProtocolInterfaces (
- &StdErrSerialDev->Handle,
- &gEfiSerialIoProtocolGuid, &StdErrSerialDev->SerialIo,
- &gEfiDevicePathProtocolGuid, &StdErrSerialDev->DevicePath,
- NULL
- );
- ASSERT_EFI_ERROR (Status);
-}
-
+/** @file
+ Serial IO Abstraction for GDB stub. This allows an EFI consoles that shows up on the system
+ running GDB. One consle for error information and another console for user input/output.
+
+ Basic packet format is $packet-data#checksum. So every comand has 4 bytes of overhead: $,
+ #, 0, 0. The 0 and 0 are the ascii characters for the checksum.
+
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <GdbStubInternal.h>
+
+//
+// Set TRUE if F Reply package signals a ctrl-c. We can not process the Ctrl-c
+// here we need to wait for the periodic callback to do this.
+//
+BOOLEAN gCtrlCBreakFlag = FALSE;
+
+//
+// If the periodic callback is called while we are processing an F packet we need
+// to let the callback know to not read from the serail stream as it could steal
+// characters from the F reponse packet
+//
+BOOLEAN gProcessingFPacket = FALSE;
+
+/**
+ Process a control-C break message.
+
+ Currently a place holder, remove the ASSERT when it gets implemented.
+
+ @param ErrNo Error infomration from the F reply packet or other source
+
+**/
+
+VOID
+GdbCtrlCBreakMessage (
+ IN UINTN ErrNo
+ )
+{
+ // See D.10.5 of gdb.pdf
+ // This should look like a break message. Should look like SIGINT
+
+ /* TODO: Make sure if we should do anything with ErrNo */
+ //Turn on the global Ctrl-C flag.
+ gCtrlCBreakFlag = TRUE;
+}
+
+
+/**
+ Parse the F reply packet and extract the return value and an ErrNo if it exists.
+
+ @param Packet Packet to parse like an F reply packet
+ @param ErrNo Buffer to hold Count bytes that were read
+
+ @retval -1 Error, not a valid F reply packet
+ @retval other Return the return code from the F reply packet
+
+**/
+INTN
+GdbParseFReplyPacket (
+ IN CHAR8 *Packet,
+ OUT UINTN *ErrNo
+ )
+{
+ INTN RetCode;
+
+ if (Packet[0] != 'F') {
+ // A valid responce would be an F packet
+ return -1;
+ }
+
+ RetCode = AsciiStrHexToUintn (&Packet[1]);
+
+ // Find 1st comma
+ for (;*Packet != '\0' && *Packet != ','; Packet++);
+ if (*Packet == '\0') {
+ *ErrNo = 0;
+ return RetCode;
+ }
+
+ *ErrNo = AsciiStrHexToUintn (++Packet);
+
+ // Find 2nd comma
+ for (;*Packet != '\0' && *Packet != ','; Packet++);
+ if (*Packet == '\0') {
+ return RetCode;
+ }
+
+ if (*(++Packet) == 'C') {
+ GdbCtrlCBreakMessage (*ErrNo);
+ }
+
+ return RetCode;
+}
+
+
+/**
+ Read data from a FileDescriptor. On success number of bytes read is returned. Zero indicates
+ the end of a file. On error -1 is returned. If count is zero, GdbRead returns zero.
+
+ @param FileDescriptor Device to talk to.
+ @param Buffer Buffer to hold Count bytes that were read
+ @param Count Number of bytes to transfer.
+
+ @retval -1 Error
+ @retval {other} Number of bytes read.
+
+**/
+INTN
+GdbRead (
+ IN INTN FileDescriptor,
+ OUT VOID *Buffer,
+ IN UINTN Count
+ )
+{
+ CHAR8 Packet[128];
+ UINTN Size;
+ INTN RetCode;
+ UINTN ErrNo;
+ BOOLEAN ReceiveDone = FALSE;
+
+ // Send:
+ // "Fread,XX,YYYYYYYY,XX
+ //
+ // XX - FileDescriptor in ASCII
+ // YYYYYYYY - Buffer address in ASCII
+ // XX - Count in ASCII
+ // SS - check sum
+ //
+ Size = AsciiSPrint (Packet, sizeof (Packet), "Fread,%x,%x,%x", FileDescriptor, Buffer, Count);
+ // Packet array is too small if you got this ASSERT
+ ASSERT (Size < sizeof (Packet));
+
+ gProcessingFPacket = TRUE;
+ SendPacket (Packet);
+ Print ((CHAR16 *)L"Packet sent..\n");
+
+ do {
+ // Reply:
+ ReceivePacket (Packet, sizeof (Packet));
+ Print ((CHAR16 *)L"Command received..%c\n", Packet[0]);
+
+ // Process GDB commands
+ switch (Packet[0]) {
+ //Write memory command.
+ //M addr,length:XX...
+ case 'M':
+ WriteToMemory (Packet);
+ break;
+
+ //Fretcode, errno, Ctrl-C flag
+ //retcode - Count read
+ case 'F':
+ //Once target receives F reply packet that means the previous
+ //transactions are finished.
+ ReceiveDone = TRUE;
+ break;
+
+ //Send empty buffer
+ default :
+ SendNotSupported();
+ break;
+ }
+ } while (ReceiveDone == FALSE);
+
+ RetCode = GdbParseFReplyPacket (Packet, &ErrNo);
+ Print ((CHAR16 *)L"RetCode: %x..ErrNo: %x..\n", RetCode, ErrNo);
+
+ if (ErrNo > 0) {
+ //Send error to the host if there is any.
+ SendError ((UINT8)ErrNo);
+ }
+
+ gProcessingFPacket = FALSE;
+
+ return RetCode;
+}
+
+
+/**
+ Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
+ nothing was written. On error -1 is returned.
+
+ @param FileDescriptor Device to talk to.
+ @param Buffer Buffer to hold Count bytes that are to be written
+ @param Count Number of bytes to transfer.
+
+ @retval -1 Error
+ @retval {other} Number of bytes written.
+
+**/
+INTN
+GdbWrite (
+ IN INTN FileDescriptor,
+ OUT CONST VOID *Buffer,
+ IN UINTN Count
+ )
+{
+ CHAR8 Packet[128];
+ UINTN Size;
+ INTN RetCode;
+ UINTN ErrNo;
+ BOOLEAN ReceiveDone = FALSE;
+
+ // Send:
+ // #Fwrite,XX,YYYYYYYY,XX$SS
+ //
+ // XX - FileDescriptor in ASCII
+ // YYYYYYYY - Buffer address in ASCII
+ // XX - Count in ASCII
+ // SS - check sum
+ //
+ Size = AsciiSPrint (Packet, sizeof (Packet), "Fwrite,%x,%x,%x", FileDescriptor, Buffer, Count);
+ // Packet array is too small if you got this ASSERT
+ ASSERT (Size < sizeof (Packet));
+
+ SendPacket (Packet);
+ Print ((CHAR16 *)L"Packet sent..\n");
+
+ do {
+ // Reply:
+ ReceivePacket (Packet, sizeof (Packet));
+ Print ((CHAR16 *)L"Command received..%c\n", Packet[0]);
+
+ // Process GDB commands
+ switch (Packet[0]) {
+ //Read memory command.
+ //m addr,length.
+ case 'm':
+ ReadFromMemory (Packet);
+ break;
+
+ //Fretcode, errno, Ctrl-C flag
+ //retcode - Count read
+ case 'F':
+ //Once target receives F reply packet that means the previous
+ //transactions are finished.
+ ReceiveDone = TRUE;
+ break;
+
+ //Send empty buffer
+ default :
+ SendNotSupported();
+ break;
+ }
+ } while (ReceiveDone == FALSE);
+
+ RetCode = GdbParseFReplyPacket (Packet, &ErrNo);
+ Print ((CHAR16 *)L"RetCode: %x..ErrNo: %x..\n", RetCode, ErrNo);
+
+ //Send error to the host if there is any.
+ if (ErrNo > 0) {
+ SendError((UINT8)ErrNo);
+ }
+
+ return RetCode;
+}
+
+
+/**
+ Reset the serial device.
+
+ @param This Protocol instance pointer.
+
+ @retval EFI_SUCCESS The device was reset.
+ @retval EFI_DEVICE_ERROR The serial device could not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+GdbSerialReset (
+ IN EFI_SERIAL_IO_PROTOCOL *This
+ )
+{
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Sets the baud rate, receive FIFO depth, transmit/receice time out, parity,
+ data buts, and stop bits on a serial device.
+
+ @param This Protocol instance pointer.
+ @param BaudRate The requested baud rate. A BaudRate value of 0 will use the the
+ device's default interface speed.
+ @param ReveiveFifoDepth The requested depth of the FIFO on the receive side of the
+ serial interface. A ReceiveFifoDepth value of 0 will use
+ the device's dfault FIFO depth.
+ @param Timeout The requested time out for a single character in microseconds.
+ This timeout applies to both the transmit and receive side of the
+ interface. A Timeout value of 0 will use the device's default time
+ out value.
+ @param Parity The type of parity to use on this serial device. A Parity value of
+ DefaultParity will use the device's default parity value.
+ @param DataBits The number of data bits to use on the serial device. A DataBits
+ vaule of 0 will use the device's default data bit setting.
+ @param StopBits The number of stop bits to use on this serial device. A StopBits
+ value of DefaultStopBits will use the device's default number of
+ stop bits.
+
+ @retval EFI_SUCCESS The device was reset.
+ @retval EFI_DEVICE_ERROR The serial device could not be reset.
+
+**/
+EFI_STATUS
+EFIAPI
+GdbSerialSetAttributes (
+ IN EFI_SERIAL_IO_PROTOCOL *This,
+ IN UINT64 BaudRate,
+ IN UINT32 ReceiveFifoDepth,
+ IN UINT32 Timeout,
+ IN EFI_PARITY_TYPE Parity,
+ IN UINT8 DataBits,
+ IN EFI_STOP_BITS_TYPE StopBits
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+
+/**
+ Set the control bits on a serial device
+
+ @param This Protocol instance pointer.
+ @param Control Set the bits of Control that are settable.
+
+ @retval EFI_SUCCESS The new control bits were set on the serial device.
+ @retval EFI_UNSUPPORTED The serial device does not support this operation.
+ @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+EFI_STATUS
+EFIAPI
+GdbSerialSetControl (
+ IN EFI_SERIAL_IO_PROTOCOL *This,
+ IN UINT32 Control
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+
+/**
+ Retrieves the status of thecontrol bits on a serial device
+
+ @param This Protocol instance pointer.
+ @param Control A pointer to return the current Control signals from the serial device.
+
+ @retval EFI_SUCCESS The control bits were read from the serial device.
+ @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+EFI_STATUS
+EFIAPI
+GdbSerialGetControl (
+ IN EFI_SERIAL_IO_PROTOCOL *This,
+ OUT UINT32 *Control
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+
+/**
+ Writes data to a serial device.
+
+ @param This Protocol instance pointer.
+ @param BufferSize On input, the size of the Buffer. On output, the amount of
+ data actually written.
+ @param Buffer The buffer of data to write
+
+ @retval EFI_SUCCESS The data was written.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+ @retval EFI_TIMEOUT The data write was stopped due to a timeout.
+
+**/
+EFI_STATUS
+EFIAPI
+GdbSerialWrite (
+ IN EFI_SERIAL_IO_PROTOCOL *This,
+ IN OUT UINTN *BufferSize,
+ IN VOID *Buffer
+ )
+{
+ GDB_SERIAL_DEV *SerialDev;
+ UINTN Return;
+
+ SerialDev = GDB_SERIAL_DEV_FROM_THIS (This);
+
+ Return = GdbWrite (SerialDev->OutFileDescriptor, Buffer, *BufferSize);
+ if (Return == (UINTN)-1) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (Return != *BufferSize) {
+ *BufferSize = Return;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Writes data to a serial device.
+
+ @param This Protocol instance pointer.
+ @param BufferSize On input, the size of the Buffer. On output, the amount of
+ data returned in Buffer.
+ @param Buffer The buffer to return the data into.
+
+ @retval EFI_SUCCESS The data was read.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+ @retval EFI_TIMEOUT The data write was stopped due to a timeout.
+
+**/
+
+EFI_STATUS
+EFIAPI
+GdbSerialRead (
+ IN EFI_SERIAL_IO_PROTOCOL *This,
+ IN OUT UINTN *BufferSize,
+ OUT VOID *Buffer
+ )
+{
+ GDB_SERIAL_DEV *SerialDev;
+ UINTN Return;
+
+ SerialDev = GDB_SERIAL_DEV_FROM_THIS (This);
+
+ Return = GdbRead (SerialDev->InFileDescriptor, Buffer, *BufferSize);
+ if (Return == (UINTN)-1) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (Return != *BufferSize) {
+ *BufferSize = Return;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+//
+// Template used to initailize the GDB Serial IO protocols
+//
+GDB_SERIAL_DEV gdbSerialDevTemplate = {
+ GDB_SERIAL_DEV_SIGNATURE,
+ NULL,
+
+ { // SerialIo
+ SERIAL_IO_INTERFACE_REVISION,
+ GdbSerialReset,
+ GdbSerialSetAttributes,
+ GdbSerialSetControl,
+ GdbSerialGetControl,
+ GdbSerialWrite,
+ GdbSerialRead,
+ NULL
+ },
+ { // SerialMode
+ 0, // ControlMask
+ 0, // Timeout
+ 0, // BaudRate
+ 1, // RceiveFifoDepth
+ 0, // DataBits
+ 0, // Parity
+ 0 // StopBits
+ },
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ {
+ (UINT8) (sizeof (VENDOR_DEVICE_PATH) + sizeof (UINT32)),
+ (UINT8) ((sizeof (VENDOR_DEVICE_PATH) + sizeof (UINT32)) >> 8)
+ },
+ EFI_SERIAL_IO_PROTOCOL_GUID,
+ },
+ 0,
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL)),
+ (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL) >> 8)
+ }
+ },
+ },
+ GDB_STDIN,
+ GDB_STDOUT
+};
+
+
+/**
+ Make two serial consoles: 1) StdIn and StdOut via GDB. 2) StdErr via GDB.
+
+ These console show up on the remote system running GDB
+
+**/
+VOID
+GdbInitializeSerialConsole (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ GDB_SERIAL_DEV *StdOutSerialDev;
+ GDB_SERIAL_DEV *StdErrSerialDev;
+
+ // Use the template to make a copy of the Serial Console private data structure.
+ StdOutSerialDev = AllocateCopyPool (sizeof (GDB_SERIAL_DEV), &gdbSerialDevTemplate);
+ ASSERT (StdOutSerialDev != NULL);
+
+ // Fixup pointer after the copy
+ StdOutSerialDev->SerialIo.Mode = &StdOutSerialDev->SerialMode;
+
+ StdErrSerialDev = AllocateCopyPool (sizeof (GDB_SERIAL_DEV), &gdbSerialDevTemplate);
+ ASSERT (StdErrSerialDev != NULL);
+
+ // Fixup pointer and modify stuff that is different for StdError
+ StdErrSerialDev->SerialIo.Mode = &StdErrSerialDev->SerialMode;
+ StdErrSerialDev->DevicePath.Index = 1;
+ StdErrSerialDev->OutFileDescriptor = GDB_STDERR;
+
+ // Make a new handle with Serial IO protocol and its device path on it.
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &StdOutSerialDev->Handle,
+ &gEfiSerialIoProtocolGuid, &StdOutSerialDev->SerialIo,
+ &gEfiDevicePathProtocolGuid, &StdOutSerialDev->DevicePath,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ // Make a new handle with Serial IO protocol and its device path on it.
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &StdErrSerialDev->Handle,
+ &gEfiSerialIoProtocolGuid, &StdErrSerialDev->SerialIo,
+ &gEfiDevicePathProtocolGuid, &StdErrSerialDev->DevicePath,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+}
+
diff --git a/EmbeddedPkg/Include/Library/DebugAgentTimerLib.h b/EmbeddedPkg/Include/Library/DebugAgentTimerLib.h
index 6a363e000..1b9769509 100755
--- a/EmbeddedPkg/Include/Library/DebugAgentTimerLib.h
+++ b/EmbeddedPkg/Include/Library/DebugAgentTimerLib.h
@@ -60,4 +60,4 @@ DebugAgentTimerEndOfInterrupt (
#endif
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/EmbeddedPkg/Include/Library/DmaLib.h b/EmbeddedPkg/Include/Library/DmaLib.h
index badaf2136..6e876dd26 100755
--- a/EmbeddedPkg/Include/Library/DmaLib.h
+++ b/EmbeddedPkg/Include/Library/DmaLib.h
@@ -1,45 +1,45 @@
-/** @file
- DMA abstraction library APIs. Based on UEFI PCI IO protocol DMA abstractions.
- At some point these functions will probably end up in a non PCI protocol
- for embedded systems.
-
+/** @file
+ DMA abstraction library APIs. Based on UEFI PCI IO protocol DMA abstractions.
+ At some point these functions will probably end up in a non PCI protocol
+ for embedded systems.
+
DMA Bus Master Read Operation:
- Call DmaMap() for MapOperationBusMasterRead.
- Program the DMA Bus Master with the DeviceAddress returned by DmaMap().
- Start the DMA Bus Master.
- Wait for DMA Bus Master to complete the read operation.
- Call DmaUnmap().
-
- DMA Bus Master Write Operation:
+ Call DmaMap() for MapOperationBusMasterRead.
+ Program the DMA Bus Master with the DeviceAddress returned by DmaMap().
+ Start the DMA Bus Master.
+ Wait for DMA Bus Master to complete the read operation.
+ Call DmaUnmap().
+
+ DMA Bus Master Write Operation:
Call DmaMap() for MapOperationBusMasterWrite.
Program the DMA Bus Master with the DeviceAddress returned by DmaMap().
Start the DMA Bus Master.
Wait for DMA Bus Master to complete the write operation.
- Call DmaUnmap().
-
- DMA Bus Master Common Buffer Operation:
- Call DmaAllocateBuffer() to allocate a common buffer.
- Call DmaMap() for MapOperationBusMasterCommonBuffer.
- Program the DMA Bus Master with the DeviceAddress returned by DmaMap().
- The common buffer can now be accessed equally by the processor and the DMA bus master.
- Call DmaUnmap().
- Call DmaFreeBuffer().
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __DMA_LIB_H__
-#define __DMA_LIB_H__
-
+ Call DmaUnmap().
+
+ DMA Bus Master Common Buffer Operation:
+ Call DmaAllocateBuffer() to allocate a common buffer.
+ Call DmaMap() for MapOperationBusMasterCommonBuffer.
+ Program the DMA Bus Master with the DeviceAddress returned by DmaMap().
+ The common buffer can now be accessed equally by the processor and the DMA bus master.
+ Call DmaUnmap().
+ Call DmaFreeBuffer().
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __DMA_LIB_H__
+#define __DMA_LIB_H__
+
typedef enum {
///
/// A read operation from system memory by a bus master.
@@ -56,10 +56,10 @@ typedef enum {
MapOperationBusMasterCommonBuffer,
MapOperationMaximum
} DMA_MAP_OPERATION;
-
-
-
-
+
+
+
+
/**
Provides the DMA controller-specific addresses needed to access system memory.
@@ -79,20 +79,20 @@ typedef enum {
@retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources.
@retval EFI_DEVICE_ERROR The system hardware could not map the requested address.
-**/
-EFI_STATUS
-EFIAPI
-DmaMap (
- IN DMA_MAP_OPERATION Operation,
+**/
+EFI_STATUS
+EFIAPI
+DmaMap (
+ IN DMA_MAP_OPERATION Operation,
IN VOID *HostAddress,
IN OUT UINTN *NumberOfBytes,
OUT PHYSICAL_ADDRESS *DeviceAddress,
OUT VOID **Mapping
- );
-
-
-
-
+ );
+
+
+
+
/**
Completes the DmaMapBusMasterRead, DmaMapBusMasterWrite, or DmaMapBusMasterCommonBuffer
operation and releases any corresponding resources.
@@ -102,14 +102,14 @@ DmaMap (
@retval EFI_SUCCESS The range was unmapped.
@retval EFI_DEVICE_ERROR The data was not committed to the target system memory.
-**/
-EFI_STATUS
-EFIAPI
-DmaUnmap (
+**/
+EFI_STATUS
+EFIAPI
+DmaUnmap (
IN VOID *Mapping
- );
-
-
+ );
+
+
/**
Allocates pages that are suitable for an DmaMap() of type MapOperationBusMasterCommonBuffer.
mapping.
@@ -126,16 +126,16 @@ DmaUnmap (
@retval EFI_INVALID_PARAMETER One or more parameters are invalid.
@retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated.
-**/
-EFI_STATUS
-EFIAPI
-DmaAllocateBuffer (
- IN EFI_MEMORY_TYPE MemoryType,
+**/
+EFI_STATUS
+EFIAPI
+DmaAllocateBuffer (
+ IN EFI_MEMORY_TYPE MemoryType,
IN UINTN Pages,
OUT VOID **HostAddress
);
-
-
+
+
/**
Frees memory that was allocated with DmaAllocateBuffer().
@@ -147,13 +147,13 @@ DmaAllocateBuffer (
was not allocated with DmaAllocateBuffer().
**/
-EFI_STATUS
-EFIAPI
-DmaFreeBuffer (
+EFI_STATUS
+EFIAPI
+DmaFreeBuffer (
IN UINTN Pages,
IN VOID *HostAddress
);
-
-
-#endif
-
+
+
+#endif
+
diff --git a/EmbeddedPkg/Include/Library/EblAddExternalCommandLib.h b/EmbeddedPkg/Include/Library/EblAddExternalCommandLib.h
index c00d04f4d..f760f8e2a 100644
--- a/EmbeddedPkg/Include/Library/EblAddExternalCommandLib.h
+++ b/EmbeddedPkg/Include/Library/EblAddExternalCommandLib.h
@@ -1,122 +1,122 @@
-/** @file
- Include file for basic command line parser for EBL (Embedded Boot Loader)
-
- Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
- Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __EBL_ADD_EXTERNAL_COMMAND_LIB_H__
-#define __EBL_ADD_EXTERNAL_COMMAND_LIB_H__
-
-#include <PiDxe.h>
-#include <Protocol/EblAddCommand.h>
-
-
-EFI_STATUS
-EFIAPI
-EblAddExternalCommands (
- IN const EBL_COMMAND_TABLE *EntryArray,
- IN UINTN ArrayCount
- );
-
-/**
-
- Return a keypress or optionally timeout if a timeout value was passed in.
-
- An optional callback function is called every second when waiting for a
-
- timeout.
-
-
-
- @param Key EFI Key information returned
-
- @param TimeoutInSec Number of seconds to wait to timeout
-
- @param CallBack Callback called every second during the timeout wait
-
-
-
- @return EFI_SUCCESS Key was returned
-
- @return EFI_TIMEOUT If the TimoutInSec expired
-
-
-
-**/
-
-EFI_STATUS
-
-EFIAPI
-
-EblGetCharKey (
-
- IN OUT EFI_INPUT_KEY *Key,
-
- IN UINTN TimeoutInSec,
-
- IN EBL_GET_CHAR_CALL_BACK CallBack OPTIONAL
-
- );
-
-
-
-
-
-/**
-
- This routine is used prevent command output data from scrolling off the end
-
- of the screen. The global gPageBreak is used to turn on or off this feature.
-
- If the CurrentRow is near the end of the screen pause and print out a prompt
-
- If the use hits Q to quit return TRUE else for any other key return FALSE.
-
- PrefixNewline is used to figure out if a newline is needed before the prompt
-
- string. This depends on the last print done before calling this function.
-
- CurrentRow is updated by one on a call or set back to zero if a prompt is
-
- needed.
-
-
-
- @param CurrentRow Used to figure out if its the end of the page and updated
-
- @param PrefixNewline Did previous print issue a newline
-
-
-
- @return TRUE if Q was hit to quit, FALSE in all other cases.
-
-
-
-**/
-
-BOOLEAN
-
-EFIAPI
-
-EblAnyKeyToContinueQtoQuit (
-
- IN UINTN *CurrentRow,
-
- IN BOOLEAN PrefixNewline
-
- );
-
-
-
-#endif
-
+/** @file
+ Include file for basic command line parser for EBL (Embedded Boot Loader)
+
+ Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
+ Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __EBL_ADD_EXTERNAL_COMMAND_LIB_H__
+#define __EBL_ADD_EXTERNAL_COMMAND_LIB_H__
+
+#include <PiDxe.h>
+#include <Protocol/EblAddCommand.h>
+
+
+EFI_STATUS
+EFIAPI
+EblAddExternalCommands (
+ IN const EBL_COMMAND_TABLE *EntryArray,
+ IN UINTN ArrayCount
+ );
+
+/**
+
+ Return a keypress or optionally timeout if a timeout value was passed in.
+
+ An optional callback function is called every second when waiting for a
+
+ timeout.
+
+
+
+ @param Key EFI Key information returned
+
+ @param TimeoutInSec Number of seconds to wait to timeout
+
+ @param CallBack Callback called every second during the timeout wait
+
+
+
+ @return EFI_SUCCESS Key was returned
+
+ @return EFI_TIMEOUT If the TimoutInSec expired
+
+
+
+**/
+
+EFI_STATUS
+
+EFIAPI
+
+EblGetCharKey (
+
+ IN OUT EFI_INPUT_KEY *Key,
+
+ IN UINTN TimeoutInSec,
+
+ IN EBL_GET_CHAR_CALL_BACK CallBack OPTIONAL
+
+ );
+
+
+
+
+
+/**
+
+ This routine is used prevent command output data from scrolling off the end
+
+ of the screen. The global gPageBreak is used to turn on or off this feature.
+
+ If the CurrentRow is near the end of the screen pause and print out a prompt
+
+ If the use hits Q to quit return TRUE else for any other key return FALSE.
+
+ PrefixNewline is used to figure out if a newline is needed before the prompt
+
+ string. This depends on the last print done before calling this function.
+
+ CurrentRow is updated by one on a call or set back to zero if a prompt is
+
+ needed.
+
+
+
+ @param CurrentRow Used to figure out if its the end of the page and updated
+
+ @param PrefixNewline Did previous print issue a newline
+
+
+
+ @return TRUE if Q was hit to quit, FALSE in all other cases.
+
+
+
+**/
+
+BOOLEAN
+
+EFIAPI
+
+EblAnyKeyToContinueQtoQuit (
+
+ IN UINTN *CurrentRow,
+
+ IN BOOLEAN PrefixNewline
+
+ );
+
+
+
+#endif
+
diff --git a/EmbeddedPkg/Include/Library/EblCmdLib.h b/EmbeddedPkg/Include/Library/EblCmdLib.h
index 8974463c8..5c21d05f0 100644
--- a/EmbeddedPkg/Include/Library/EblCmdLib.h
+++ b/EmbeddedPkg/Include/Library/EblCmdLib.h
@@ -1,48 +1,48 @@
-/** @file
- Include file for basic command line parser for EBL (Embedded Boot Loader)
-
- Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
- Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __EBL_LIB_H__
-#define __EBL_LIB_H__
-
-#include <PiDxe.h>
-#include <Protocol/EblAddCommand.h>
-
-
-VOID
-EblAddCommand (
- IN const EBL_COMMAND_TABLE *Entry
- );
-
-VOID
-EblAddCommands (
- IN const EBL_COMMAND_TABLE *EntryArray,
- IN UINTN ArrayCount
- );
-
-
-//
-// LIbrary constructor called directly from Ebl Code.
-// This module calls EblAddCommand () or EblAddCommands () to register new commands
-//
-VOID
-EblInitializeExternalCmd (
- VOID
- );
-
-
-
-#endif
-
+/** @file
+ Include file for basic command line parser for EBL (Embedded Boot Loader)
+
+ Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
+ Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __EBL_LIB_H__
+#define __EBL_LIB_H__
+
+#include <PiDxe.h>
+#include <Protocol/EblAddCommand.h>
+
+
+VOID
+EblAddCommand (
+ IN const EBL_COMMAND_TABLE *Entry
+ );
+
+VOID
+EblAddCommands (
+ IN const EBL_COMMAND_TABLE *EntryArray,
+ IN UINTN ArrayCount
+ );
+
+
+//
+// LIbrary constructor called directly from Ebl Code.
+// This module calls EblAddCommand () or EblAddCommands () to register new commands
+//
+VOID
+EblInitializeExternalCmd (
+ VOID
+ );
+
+
+
+#endif
+
diff --git a/EmbeddedPkg/Include/Library/EblNetworkLib.h b/EmbeddedPkg/Include/Library/EblNetworkLib.h
index c72973b75..9292cf9b0 100644
--- a/EmbeddedPkg/Include/Library/EblNetworkLib.h
+++ b/EmbeddedPkg/Include/Library/EblNetworkLib.h
@@ -1,68 +1,68 @@
-/** @file
- Abstractions for Ebl network accesses.
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __EBL_NETWORK_LIB_H__
-#define __EBL_NETWORK_LIB_H__
-
-#include <Protocol/PxeBaseCode.h>
-
-
-EFI_STATUS
-EFIAPI
-EblGetCurrentIpAddress (
- IN OUT EFI_IP_ADDRESS *Ip
- );
-
-EFI_STATUS
-EFIAPI
-EblGetCurrentMacAddress (
- IN OUT EFI_MAC_ADDRESS *Mac
- );
-
-CHAR8 *
-EFIAPI
-EblLoadFileBootTypeString (
- IN EFI_HANDLE Handle
- );
-
-EFI_STATUS
-EFIAPI
-EblPerformDHCP (
- IN BOOLEAN SortOffers
- );
-
-EFI_STATUS
-EFIAPI
-EblSetStationIp (
- IN EFI_IP_ADDRESS *NewStationIp, OPTIONAL
- IN EFI_IP_ADDRESS *NewSubnetMask OPTIONAL
- );
-
-EFI_STATUS
-EFIAPI
-EblMtftp (
- IN EFI_PXE_BASE_CODE_TFTP_OPCODE Operation,
- IN OUT VOID *BufferPtr OPTIONAL,
- IN BOOLEAN Overwrite,
- IN OUT UINT64 *BufferSize,
- IN UINTN *BlockSize OPTIONAL,
- IN EFI_IP_ADDRESS *ServerIp,
- IN UINT8 *Filename OPTIONAL,
- IN EFI_PXE_BASE_CODE_MTFTP_INFO *Info OPTIONAL,
- IN BOOLEAN DontUseBuffer
- );
-
-#endif
-
+/** @file
+ Abstractions for Ebl network accesses.
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __EBL_NETWORK_LIB_H__
+#define __EBL_NETWORK_LIB_H__
+
+#include <Protocol/PxeBaseCode.h>
+
+
+EFI_STATUS
+EFIAPI
+EblGetCurrentIpAddress (
+ IN OUT EFI_IP_ADDRESS *Ip
+ );
+
+EFI_STATUS
+EFIAPI
+EblGetCurrentMacAddress (
+ IN OUT EFI_MAC_ADDRESS *Mac
+ );
+
+CHAR8 *
+EFIAPI
+EblLoadFileBootTypeString (
+ IN EFI_HANDLE Handle
+ );
+
+EFI_STATUS
+EFIAPI
+EblPerformDHCP (
+ IN BOOLEAN SortOffers
+ );
+
+EFI_STATUS
+EFIAPI
+EblSetStationIp (
+ IN EFI_IP_ADDRESS *NewStationIp, OPTIONAL
+ IN EFI_IP_ADDRESS *NewSubnetMask OPTIONAL
+ );
+
+EFI_STATUS
+EFIAPI
+EblMtftp (
+ IN EFI_PXE_BASE_CODE_TFTP_OPCODE Operation,
+ IN OUT VOID *BufferPtr OPTIONAL,
+ IN BOOLEAN Overwrite,
+ IN OUT UINT64 *BufferSize,
+ IN UINTN *BlockSize OPTIONAL,
+ IN EFI_IP_ADDRESS *ServerIp,
+ IN UINT8 *Filename OPTIONAL,
+ IN EFI_PXE_BASE_CODE_MTFTP_INFO *Info OPTIONAL,
+ IN BOOLEAN DontUseBuffer
+ );
+
+#endif
+
diff --git a/EmbeddedPkg/Include/Library/GdbSerialLib.h b/EmbeddedPkg/Include/Library/GdbSerialLib.h
index 55800b9fc..6e8eeb4e6 100644
--- a/EmbeddedPkg/Include/Library/GdbSerialLib.h
+++ b/EmbeddedPkg/Include/Library/GdbSerialLib.h
@@ -1,107 +1,107 @@
-/** @file
- Basic serial IO abstaction for GDB
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __GDB_SERIAL_LIB_H__
-#define __GDB_SERIAL_LIB_H__
-
-
-
-/**
- Sets the baud rate, receive FIFO depth, transmit/receice time out, parity,
- data buts, and stop bits on a serial device. This call is optional as the serial
- port will be set up with defaults base on PCD values.
-
- @param BaudRate The requested baud rate. A BaudRate value of 0 will use the the
- device's default interface speed.
- @param Parity The type of parity to use on this serial device. A Parity value of
- DefaultParity will use the device's default parity value.
- @param DataBits The number of data bits to use on the serial device. A DataBits
- vaule of 0 will use the device's default data bit setting.
- @param StopBits The number of stop bits to use on this serial device. A StopBits
- value of DefaultStopBits will use the device's default number of
- stop bits.
-
- @retval EFI_SUCCESS The device was configured.
- @retval EFI_DEVICE_ERROR The serial device could not be coonfigured.
-
-**/
-RETURN_STATUS
-EFIAPI
-GdbSerialInit (
- IN UINT64 BaudRate,
- IN UINT8 Parity,
- IN UINT8 DataBits,
- IN UINT8 StopBits
- );
-
-
-/**
- Check to see if a character is available from GDB. Do not read the character as that is
- done via GdbGetChar().
-
- @return TRUE - Character availible
- @return FALSE - Character not availible
-
-**/
-BOOLEAN
-EFIAPI
-GdbIsCharAvailable (
- VOID
- );
-
-/**
- Get a character from GDB. This function must be able to run in interrupt context.
-
- @return A character from GDB
-
-**/
-CHAR8
-EFIAPI
-GdbGetChar (
- VOID
- );
-
-
-/**
- Send a character to GDB. This function must be able to run in interrupt context.
-
-
- @param Char Send a character to GDB
-
-**/
-
-VOID
-EFIAPI
-GdbPutChar (
- IN CHAR8 Char
- );
-
-
-/**
- Send an ASCII string to GDB. This function must be able to run in interrupt context.
-
-
- @param String Send a string to GDB
-
-**/
-
-VOID
-GdbPutString (
- IN CHAR8 *String
- );
-
-
-#endif
-
+/** @file
+ Basic serial IO abstaction for GDB
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __GDB_SERIAL_LIB_H__
+#define __GDB_SERIAL_LIB_H__
+
+
+
+/**
+ Sets the baud rate, receive FIFO depth, transmit/receice time out, parity,
+ data buts, and stop bits on a serial device. This call is optional as the serial
+ port will be set up with defaults base on PCD values.
+
+ @param BaudRate The requested baud rate. A BaudRate value of 0 will use the the
+ device's default interface speed.
+ @param Parity The type of parity to use on this serial device. A Parity value of
+ DefaultParity will use the device's default parity value.
+ @param DataBits The number of data bits to use on the serial device. A DataBits
+ vaule of 0 will use the device's default data bit setting.
+ @param StopBits The number of stop bits to use on this serial device. A StopBits
+ value of DefaultStopBits will use the device's default number of
+ stop bits.
+
+ @retval EFI_SUCCESS The device was configured.
+ @retval EFI_DEVICE_ERROR The serial device could not be coonfigured.
+
+**/
+RETURN_STATUS
+EFIAPI
+GdbSerialInit (
+ IN UINT64 BaudRate,
+ IN UINT8 Parity,
+ IN UINT8 DataBits,
+ IN UINT8 StopBits
+ );
+
+
+/**
+ Check to see if a character is available from GDB. Do not read the character as that is
+ done via GdbGetChar().
+
+ @return TRUE - Character availible
+ @return FALSE - Character not availible
+
+**/
+BOOLEAN
+EFIAPI
+GdbIsCharAvailable (
+ VOID
+ );
+
+/**
+ Get a character from GDB. This function must be able to run in interrupt context.
+
+ @return A character from GDB
+
+**/
+CHAR8
+EFIAPI
+GdbGetChar (
+ VOID
+ );
+
+
+/**
+ Send a character to GDB. This function must be able to run in interrupt context.
+
+
+ @param Char Send a character to GDB
+
+**/
+
+VOID
+EFIAPI
+GdbPutChar (
+ IN CHAR8 Char
+ );
+
+
+/**
+ Send an ASCII string to GDB. This function must be able to run in interrupt context.
+
+
+ @param String Send a string to GDB
+
+**/
+
+VOID
+GdbPutString (
+ IN CHAR8 *String
+ );
+
+
+#endif
+
diff --git a/EmbeddedPkg/Include/Library/PrePiLib.h b/EmbeddedPkg/Include/Library/PrePiLib.h
index 444d7e288..6144513a8 100644
--- a/EmbeddedPkg/Include/Library/PrePiLib.h
+++ b/EmbeddedPkg/Include/Library/PrePiLib.h
@@ -1,790 +1,790 @@
-/** @file
- Library that helps implement monolithic PEI. (SEC goes to DXE)
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __PRE_PI_LIB_H__
-#define __PRE_PI_LIB_H__
-
-#include <Guid/ExtractSection.h>
-
-/**
- This service enables discovery of additional firmware volumes.
-
- @param Instance This instance of the firmware volume to find. The value 0 is the
- Boot Firmware Volume (BFV).
- @param FwVolHeader Pointer to the firmware volume header of the volume to return.
-
- @retval EFI_SUCCESS The volume was found.
- @retval EFI_NOT_FOUND The volume was not found.
- @retval EFI_INVALID_PARAMETER FwVolHeader is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindNextVolume (
- IN UINTN Instance,
- IN OUT EFI_PEI_FV_HANDLE *VolumeHandle
- );
-
-
-/**
- This service enables discovery of additional firmware files.
-
- @param SearchType A filter to find files only of this type.
- @param FwVolHeader Pointer to the firmware volume header of the volume to search.
- This parameter must point to a valid FFS volume.
- @param FileHeader Pointer to the current file from which to begin searching.
-
- @retval EFI_SUCCESS The file was found.
- @retval EFI_NOT_FOUND The file was not found.
- @retval EFI_NOT_FOUND The header checksum was not zero.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindNextFile (
- IN EFI_FV_FILETYPE SearchType,
- IN EFI_PEI_FV_HANDLE VolumeHandle,
- IN OUT EFI_PEI_FILE_HANDLE *FileHandle
- );
-
-
-/**
- This service enables discovery sections of a given type within a valid FFS file.
-
- @param SearchType The value of the section type to find.
- @param FfsFileHeader A pointer to the file header that contains the set of sections to
- be searched.
- @param SectionData A pointer to the discovered section, if successful.
-
- @retval EFI_SUCCESS The section was found.
- @retval EFI_NOT_FOUND The section was not found.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindSectionData (
- IN EFI_SECTION_TYPE SectionType,
- IN EFI_PEI_FILE_HANDLE FileHandle,
- OUT VOID **SectionData
- );
-
-
-/**
- Find a file in the volume by name
-
- @param FileName A pointer to the name of the file to
- find within the firmware volume.
-
- @param VolumeHandle The firmware volume to search FileHandle
- Upon exit, points to the found file's
- handle or NULL if it could not be found.
-
- @retval EFI_SUCCESS File was found.
-
- @retval EFI_NOT_FOUND File was not found.
-
- @retval EFI_INVALID_PARAMETER VolumeHandle or FileHandle or
- FileName was NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindByName (
- IN CONST EFI_GUID *FileName,
- IN CONST EFI_PEI_FV_HANDLE VolumeHandle,
- OUT EFI_PEI_FILE_HANDLE *FileHandle
- );
-
-
-/**
- Get information about the file by name.
-
- @param FileHandle Handle of the file.
-
- @param FileInfo Upon exit, points to the file's
- information.
-
- @retval EFI_SUCCESS File information returned.
-
- @retval EFI_INVALID_PARAMETER If FileHandle does not
- represent a valid file.
-
- @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsGetFileInfo (
- IN CONST EFI_PEI_FILE_HANDLE FileHandle,
- OUT EFI_FV_FILE_INFO *FileInfo
- );
-
-
-/**
- Get Information about the volume by name
-
- @param VolumeHandle Handle of the volume.
-
- @param VolumeInfo Upon exit, points to the volume's
- information.
-
- @retval EFI_SUCCESS File information returned.
-
- @retval EFI_INVALID_PARAMETER If FileHandle does not
- represent a valid file.
-
- @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsGetVolumeInfo (
- IN EFI_PEI_FV_HANDLE VolumeHandle,
- OUT EFI_FV_INFO *VolumeInfo
- );
-
-
-
-/**
- Get Fv image from the FV type file, then add FV & FV2 Hob.
-
- @param FileHandle File handle of a Fv type file.
-
-
- @retval EFI_NOT_FOUND FV image can't be found.
- @retval EFI_SUCCESS Successfully to process it.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsProcessFvFile (
- IN EFI_PEI_FILE_HANDLE FvFileHandle
- );
-
-
-/**
- Search through every FV until you find a file of type FileType
-
- @param FileType File handle of a Fv type file.
- @param Volumehandle On succes Volume Handle of the match
- @param FileHandle On success File Handle of the match
-
- @retval EFI_NOT_FOUND FV image can't be found.
- @retval EFI_SUCCESS Successfully found FileType
-
-**/
-EFI_STATUS
-EFIAPI
-FfsAnyFvFindFirstFile (
- IN EFI_FV_FILETYPE FileType,
- OUT EFI_PEI_FV_HANDLE *VolumeHandle,
- OUT EFI_PEI_FILE_HANDLE *FileHandle
- );
-
-
-/**
- Get Fv image from the FV type file, then add FV & FV2 Hob.
-
- @param FileHandle File handle of a Fv type file.
-
-
- @retval EFI_NOT_FOUND FV image can't be found.
- @retval EFI_SUCCESS Successfully to process it.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsProcessFvFile (
- IN EFI_PEI_FILE_HANDLE FvFileHandle
- );
-
-
-/**
- This service enables PEIMs to ascertain the present value of the boot mode.
-
-
- @retval BootMode
-
-**/
-EFI_BOOT_MODE
-EFIAPI
-GetBootMode (
- VOID
- );
-
-
-/**
- This service enables PEIMs to update the boot mode variable.
-
- @param BootMode The value of the boot mode to set.
-
- @retval EFI_SUCCESS The value was successfully updated
-
-**/
-EFI_STATUS
-EFIAPI
-SetBootMode (
- IN EFI_BOOT_MODE BootMode
- );
-
-/**
- This service enables a PEIM to ascertain the address of the list of HOBs in memory.
-
- @param HobList A pointer to the list of HOBs that the PEI Foundation will initialize.
-
- @retval EFI_SUCCESS The list was successfully returned.
- @retval EFI_NOT_AVAILABLE_YET The HOB list is not yet published.
-
-**/
-VOID *
-EFIAPI
-GetHobList (
- VOID
- );
-
-
-/**
- Updates the pointer to the HOB list.
-
- @param HobList Hob list pointer to store
-
-**/
-EFI_STATUS
-EFIAPI
-SetHobList (
- IN VOID *HobList
- );
-
-EFI_HOB_HANDOFF_INFO_TABLE*
-HobConstructor (
- IN VOID *EfiMemoryBegin,
- IN UINTN EfiMemoryLength,
- IN VOID *EfiFreeMemoryBottom,
- IN VOID *EfiFreeMemoryTop
- );
-
-/**
- Retrieves the magic value from the PE/COFF header.
-
- @param Hdr The buffer in which to return the PE32, PE32+, or TE header.
-
- @return EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC - Image is PE32
- @return EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC - Image is PE32+
-
-**/
-VOID
-CreateHobList (
- IN VOID *MemoryBegin,
- IN UINTN MemoryLength,
- IN VOID *HobBase,
- IN VOID *StackBase
- );
-
-
-/**
- This service enables PEIMs to create various types of HOBs.
-
- @param Type The type of HOB to be installed.
- @param Length The length of the HOB to be added.
-
- @retval !NULL The HOB was successfully created.
- @retval NULL There is no additional space for HOB creation.
-
-**/
-VOID *
-CreateHob (
- IN UINT16 HobType,
- IN UINT16 HobLenght
- );
-
-
-/**
- Returns the next instance of a HOB type from the starting HOB.
-
- This function searches the first instance of a HOB type from the starting HOB pointer.
- If there does not exist such HOB type from the starting HOB pointer, it will return NULL.
- In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
- unconditionally: it returns HobStart back if HobStart itself meets the requirement;
- caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
- If HobStart is NULL, then ASSERT().
-
- @param Type The HOB type to return.
- @param HobStart The starting HOB pointer to search from.
-
- @return The next instance of a HOB type from the starting HOB.
-
-**/
-VOID *
-EFIAPI
-GetNextHob (
- IN UINT16 Type,
- IN CONST VOID *HobStart
- );
-
-/**
- Returns the first instance of a HOB type among the whole HOB list.
-
- This function searches the first instance of a HOB type among the whole HOB list.
- If there does not exist such HOB type in the HOB list, it will return NULL.
-
- @param Type The HOB type to return.
-
- @return The next instance of a HOB type from the starting HOB.
-
-**/
-VOID *
-EFIAPI
-GetFirstHob (
- IN UINT16 Type
- );
-
-/**
- This function searches the first instance of a HOB from the starting HOB pointer.
- Such HOB should satisfy two conditions:
- its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
- If there does not exist such HOB from the starting HOB pointer, it will return NULL.
- Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
- to extract the data section and its size info respectively.
- In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
- unconditionally: it returns HobStart back if HobStart itself meets the requirement;
- caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
- If Guid is NULL, then ASSERT().
- If HobStart is NULL, then ASSERT().
-
- @param Guid The GUID to match with in the HOB list.
- @param HobStart A pointer to a Guid.
-
- @return The next instance of the matched GUID HOB from the starting HOB.
-
-**/
-VOID *
-EFIAPI
-GetNextGuidHob (
- IN CONST EFI_GUID *Guid,
- IN CONST VOID *HobStart
- );
-
-/**
- This function searches the first instance of a HOB among the whole HOB list.
- Such HOB should satisfy two conditions:
- its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
- If there does not exist such HOB from the starting HOB pointer, it will return NULL.
- Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
- to extract the data section and its size info respectively.
- If Guid is NULL, then ASSERT().
-
- @param Guid The GUID to match with in the HOB list.
-
- @return The first instance of the matched GUID HOB among the whole HOB list.
-
-**/
-VOID *
-EFIAPI
-GetFirstGuidHob (
- IN CONST EFI_GUID *Guid
- );
-
-
-/**
- Builds a HOB for a loaded PE32 module.
-
- This function builds a HOB for a loaded PE32 module.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If ModuleName is NULL, then ASSERT().
- If there is no additional space for HOB creation, then ASSERT().
-
- @param ModuleName The GUID File Name of the module.
- @param MemoryAllocationModule The 64 bit physical address of the module.
- @param ModuleLength The length of the module in bytes.
- @param EntryPoint The 64 bit physical address of the module entry point.
-
-**/
-VOID
-EFIAPI
-BuildModuleHob (
- IN CONST EFI_GUID *ModuleName,
- IN EFI_PHYSICAL_ADDRESS MemoryAllocationModule,
- IN UINT64 ModuleLength,
- IN EFI_PHYSICAL_ADDRESS EntryPoint
- );
-
-/**
- Builds a HOB that describes a chunk of system memory.
-
- This function builds a HOB that describes a chunk of system memory.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param ResourceType The type of resource described by this HOB.
- @param ResourceAttribute The resource attributes of the memory described by this HOB.
- @param PhysicalStart The 64 bit physical address of memory described by this HOB.
- @param NumberOfBytes The length of the memory described by this HOB in bytes.
-
-**/
-VOID
-EFIAPI
-BuildResourceDescriptorHob (
- IN EFI_RESOURCE_TYPE ResourceType,
- IN EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute,
- IN EFI_PHYSICAL_ADDRESS PhysicalStart,
- IN UINT64 NumberOfBytes
- );
-
-/**
- Builds a GUID HOB with a certain data length.
-
- This function builds a customized HOB tagged with a GUID for identification
- and returns the start address of GUID HOB data so that caller can fill the customized data.
- The HOB Header and Name field is already stripped.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If Guid is NULL, then ASSERT().
- If there is no additional space for HOB creation, then ASSERT().
- If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
-
- @param Guid The GUID to tag the customized HOB.
- @param DataLength The size of the data payload for the GUID HOB.
-
- @return The start address of GUID HOB data.
-
-**/
-VOID *
-EFIAPI
-BuildGuidHob (
- IN CONST EFI_GUID *Guid,
- IN UINTN DataLength
- );
-
-/**
- Copies a data buffer to a newly-built HOB.
-
- This function builds a customized HOB tagged with a GUID for identification,
- copies the input data to the HOB data field and returns the start address of the GUID HOB data.
- The HOB Header and Name field is already stripped.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If Guid is NULL, then ASSERT().
- If Data is NULL and DataLength > 0, then ASSERT().
- If there is no additional space for HOB creation, then ASSERT().
- If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
-
- @param Guid The GUID to tag the customized HOB.
- @param Data The data to be copied into the data field of the GUID HOB.
- @param DataLength The size of the data payload for the GUID HOB.
-
- @return The start address of GUID HOB data.
-
-**/
-VOID *
-EFIAPI
-BuildGuidDataHob (
- IN CONST EFI_GUID *Guid,
- IN VOID *Data,
- IN UINTN DataLength
- );
-
-/**
- Builds a Firmware Volume HOB.
-
- This function builds a Firmware Volume HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Firmware Volume.
- @param Length The size of the Firmware Volume in bytes.
-
-**/
-VOID
-EFIAPI
-BuildFvHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- );
-
-/**
- Builds a Firmware Volume HOB and a resrouce descriptor hob
-
- This function builds a Firmware Volume HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Firmware Volume.
- @param Length The size of the Firmware Volume in bytes.
-
-**/
-VOID
-EFIAPI
-BuildFvHobs (
- IN EFI_PHYSICAL_ADDRESS PhysicalStart,
- IN UINT64 NumberOfBytes,
- IN EFI_RESOURCE_ATTRIBUTE_TYPE *ResourceAttribute OPTIONAL
- );
-
-
-/**
- Builds a EFI_HOB_TYPE_FV2 HOB.
-
- This function builds a EFI_HOB_TYPE_FV2 HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Firmware Volume.
- @param Length The size of the Firmware Volume in bytes.
- @param FvName The name of the Firmware Volume.
- @param FileName The name of the file.
-
-**/
-VOID
-EFIAPI
-BuildFv2Hob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length,
- IN CONST EFI_GUID *FvName,
- IN CONST EFI_GUID *FileName
- );
-
-/**
- Builds a Capsule Volume HOB.
-
- This function builds a Capsule Volume HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Capsule Volume.
- @param Length The size of the Capsule Volume in bytes.
-
-**/
-VOID
-EFIAPI
-BuildCvHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- );
-
-/**
- Builds a HOB for the CPU.
-
- This function builds a HOB for the CPU.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param SizeOfMemorySpace The maximum physical memory addressability of the processor.
- @param SizeOfIoSpace The maximum physical I/O addressability of the processor.
-
-**/
-VOID
-EFIAPI
-BuildCpuHob (
- IN UINT8 SizeOfMemorySpace,
- IN UINT8 SizeOfIoSpace
- );
-
-/**
- Builds a HOB for the Stack.
-
- This function builds a HOB for the stack.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The 64 bit physical address of the Stack.
- @param Length The length of the stack in bytes.
-
-**/
-VOID
-EFIAPI
-BuildStackHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- );
-
-/**
- Update the Stack Hob if the stack has been moved
-
- @param BaseAddress The 64 bit physical address of the Stack.
- @param Length The length of the stack in bytes.
-
-**/
-VOID
-UpdateStackHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- );
-
-
-/**
- Builds a HOB for the BSP store.
-
- This function builds a HOB for BSP store.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The 64 bit physical address of the BSP.
- @param Length The length of the BSP store in bytes.
- @param MemoryType Type of memory allocated by this HOB.
-
-**/
-VOID
-EFIAPI
-BuildBspStoreHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length,
- IN EFI_MEMORY_TYPE MemoryType
- );
-
-/**
- Builds a HOB for the memory allocation.
-
- This function builds a HOB for the memory allocation.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The 64 bit physical address of the memory.
- @param Length The length of the memory allocation in bytes.
- @param MemoryType Type of memory allocated by this HOB.
-
-**/
-VOID
-EFIAPI
-BuildMemoryAllocationHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length,
- IN EFI_MEMORY_TYPE MemoryType
- );
-
-
-VOID
-EFIAPI
-BuildExtractSectionHob (
- IN EFI_GUID *Guid,
- IN EXTRACT_GUIDED_SECTION_GET_INFO_HANDLER SectionGetInfo,
- IN EXTRACT_GUIDED_SECTION_DECODE_HANDLER SectionExtraction
- );
-
-VOID
-EFIAPI
-BuildPeCoffLoaderHob (
- VOID
- );
-
-
-/**
- Allocates one or more 4KB pages of type EfiBootServicesData.
-
- Allocates the number of 4KB pages of MemoryType and returns a pointer to the
- allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
- is returned. If there is not enough memory remaining to satisfy the request, then NULL is
- returned.
-
- @param Pages The number of 4 KB pages to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-AllocatePages (
- IN UINTN Pages
- );
-
-/**
- Allocates a buffer of type EfiBootServicesData.
-
- Allocates the number bytes specified by AllocationSize of type EfiBootServicesData and returns a
- pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
- returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
-
- @param AllocationSize The number of bytes to allocate.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-AllocatePool (
- IN UINTN AllocationSize
- );
-
-
-/**
- Allocates one or more 4KB pages of type EfiBootServicesData at a specified alignment.
-
- Allocates the number of 4KB pages specified by Pages of type EfiBootServicesData with an
- alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
- returned. If there is not enough memory at the specified alignment remaining to satisfy the
- request, then NULL is returned.
- If Alignment is not a power of two and Alignment is not zero, then ASSERT().
-
- @param Pages The number of 4 KB pages to allocate.
- @param Alignment The requested alignment of the allocation. Must be a power of two.
- If Alignment is zero, then byte alignment is used.
-
- @return A pointer to the allocated buffer or NULL if allocation fails.
-
-**/
-VOID *
-EFIAPI
-AllocateAlignedPages (
- IN UINTN Pages,
- IN UINTN Alignment
- );
-
-
-EFI_STATUS
-EFIAPI
-LoadPeCoffImage (
- IN VOID *PeCoffImage,
- OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
- OUT UINT64 *ImageSize,
- OUT EFI_PHYSICAL_ADDRESS *EntryPoint
- );
-
-EFI_STATUS
-EFIAPI
-LoadDxeCoreFromFfsFile (
- IN EFI_PEI_FILE_HANDLE FileHandle,
- IN UINTN StackSize
- );
-
-EFI_STATUS
-EFIAPI
-LoadDxeCoreFromFv (
- IN UINTN *FvInstance, OPTIONAL
- IN UINTN StackSize
- );
-
-EFI_STATUS
-EFIAPI
-DecompressFirstFv (
- VOID
- );
-
-VOID
-EFIAPI
-AddDxeCoreReportStatusCodeCallback (
- VOID
- );
-
-
-#endif
+/** @file
+ Library that helps implement monolithic PEI. (SEC goes to DXE)
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __PRE_PI_LIB_H__
+#define __PRE_PI_LIB_H__
+
+#include <Guid/ExtractSection.h>
+
+/**
+ This service enables discovery of additional firmware volumes.
+
+ @param Instance This instance of the firmware volume to find. The value 0 is the
+ Boot Firmware Volume (BFV).
+ @param FwVolHeader Pointer to the firmware volume header of the volume to return.
+
+ @retval EFI_SUCCESS The volume was found.
+ @retval EFI_NOT_FOUND The volume was not found.
+ @retval EFI_INVALID_PARAMETER FwVolHeader is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindNextVolume (
+ IN UINTN Instance,
+ IN OUT EFI_PEI_FV_HANDLE *VolumeHandle
+ );
+
+
+/**
+ This service enables discovery of additional firmware files.
+
+ @param SearchType A filter to find files only of this type.
+ @param FwVolHeader Pointer to the firmware volume header of the volume to search.
+ This parameter must point to a valid FFS volume.
+ @param FileHeader Pointer to the current file from which to begin searching.
+
+ @retval EFI_SUCCESS The file was found.
+ @retval EFI_NOT_FOUND The file was not found.
+ @retval EFI_NOT_FOUND The header checksum was not zero.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindNextFile (
+ IN EFI_FV_FILETYPE SearchType,
+ IN EFI_PEI_FV_HANDLE VolumeHandle,
+ IN OUT EFI_PEI_FILE_HANDLE *FileHandle
+ );
+
+
+/**
+ This service enables discovery sections of a given type within a valid FFS file.
+
+ @param SearchType The value of the section type to find.
+ @param FfsFileHeader A pointer to the file header that contains the set of sections to
+ be searched.
+ @param SectionData A pointer to the discovered section, if successful.
+
+ @retval EFI_SUCCESS The section was found.
+ @retval EFI_NOT_FOUND The section was not found.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindSectionData (
+ IN EFI_SECTION_TYPE SectionType,
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ OUT VOID **SectionData
+ );
+
+
+/**
+ Find a file in the volume by name
+
+ @param FileName A pointer to the name of the file to
+ find within the firmware volume.
+
+ @param VolumeHandle The firmware volume to search FileHandle
+ Upon exit, points to the found file's
+ handle or NULL if it could not be found.
+
+ @retval EFI_SUCCESS File was found.
+
+ @retval EFI_NOT_FOUND File was not found.
+
+ @retval EFI_INVALID_PARAMETER VolumeHandle or FileHandle or
+ FileName was NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindByName (
+ IN CONST EFI_GUID *FileName,
+ IN CONST EFI_PEI_FV_HANDLE VolumeHandle,
+ OUT EFI_PEI_FILE_HANDLE *FileHandle
+ );
+
+
+/**
+ Get information about the file by name.
+
+ @param FileHandle Handle of the file.
+
+ @param FileInfo Upon exit, points to the file's
+ information.
+
+ @retval EFI_SUCCESS File information returned.
+
+ @retval EFI_INVALID_PARAMETER If FileHandle does not
+ represent a valid file.
+
+ @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsGetFileInfo (
+ IN CONST EFI_PEI_FILE_HANDLE FileHandle,
+ OUT EFI_FV_FILE_INFO *FileInfo
+ );
+
+
+/**
+ Get Information about the volume by name
+
+ @param VolumeHandle Handle of the volume.
+
+ @param VolumeInfo Upon exit, points to the volume's
+ information.
+
+ @retval EFI_SUCCESS File information returned.
+
+ @retval EFI_INVALID_PARAMETER If FileHandle does not
+ represent a valid file.
+
+ @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsGetVolumeInfo (
+ IN EFI_PEI_FV_HANDLE VolumeHandle,
+ OUT EFI_FV_INFO *VolumeInfo
+ );
+
+
+
+/**
+ Get Fv image from the FV type file, then add FV & FV2 Hob.
+
+ @param FileHandle File handle of a Fv type file.
+
+
+ @retval EFI_NOT_FOUND FV image can't be found.
+ @retval EFI_SUCCESS Successfully to process it.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsProcessFvFile (
+ IN EFI_PEI_FILE_HANDLE FvFileHandle
+ );
+
+
+/**
+ Search through every FV until you find a file of type FileType
+
+ @param FileType File handle of a Fv type file.
+ @param Volumehandle On succes Volume Handle of the match
+ @param FileHandle On success File Handle of the match
+
+ @retval EFI_NOT_FOUND FV image can't be found.
+ @retval EFI_SUCCESS Successfully found FileType
+
+**/
+EFI_STATUS
+EFIAPI
+FfsAnyFvFindFirstFile (
+ IN EFI_FV_FILETYPE FileType,
+ OUT EFI_PEI_FV_HANDLE *VolumeHandle,
+ OUT EFI_PEI_FILE_HANDLE *FileHandle
+ );
+
+
+/**
+ Get Fv image from the FV type file, then add FV & FV2 Hob.
+
+ @param FileHandle File handle of a Fv type file.
+
+
+ @retval EFI_NOT_FOUND FV image can't be found.
+ @retval EFI_SUCCESS Successfully to process it.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsProcessFvFile (
+ IN EFI_PEI_FILE_HANDLE FvFileHandle
+ );
+
+
+/**
+ This service enables PEIMs to ascertain the present value of the boot mode.
+
+
+ @retval BootMode
+
+**/
+EFI_BOOT_MODE
+EFIAPI
+GetBootMode (
+ VOID
+ );
+
+
+/**
+ This service enables PEIMs to update the boot mode variable.
+
+ @param BootMode The value of the boot mode to set.
+
+ @retval EFI_SUCCESS The value was successfully updated
+
+**/
+EFI_STATUS
+EFIAPI
+SetBootMode (
+ IN EFI_BOOT_MODE BootMode
+ );
+
+/**
+ This service enables a PEIM to ascertain the address of the list of HOBs in memory.
+
+ @param HobList A pointer to the list of HOBs that the PEI Foundation will initialize.
+
+ @retval EFI_SUCCESS The list was successfully returned.
+ @retval EFI_NOT_AVAILABLE_YET The HOB list is not yet published.
+
+**/
+VOID *
+EFIAPI
+GetHobList (
+ VOID
+ );
+
+
+/**
+ Updates the pointer to the HOB list.
+
+ @param HobList Hob list pointer to store
+
+**/
+EFI_STATUS
+EFIAPI
+SetHobList (
+ IN VOID *HobList
+ );
+
+EFI_HOB_HANDOFF_INFO_TABLE*
+HobConstructor (
+ IN VOID *EfiMemoryBegin,
+ IN UINTN EfiMemoryLength,
+ IN VOID *EfiFreeMemoryBottom,
+ IN VOID *EfiFreeMemoryTop
+ );
+
+/**
+ Retrieves the magic value from the PE/COFF header.
+
+ @param Hdr The buffer in which to return the PE32, PE32+, or TE header.
+
+ @return EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC - Image is PE32
+ @return EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC - Image is PE32+
+
+**/
+VOID
+CreateHobList (
+ IN VOID *MemoryBegin,
+ IN UINTN MemoryLength,
+ IN VOID *HobBase,
+ IN VOID *StackBase
+ );
+
+
+/**
+ This service enables PEIMs to create various types of HOBs.
+
+ @param Type The type of HOB to be installed.
+ @param Length The length of the HOB to be added.
+
+ @retval !NULL The HOB was successfully created.
+ @retval NULL There is no additional space for HOB creation.
+
+**/
+VOID *
+CreateHob (
+ IN UINT16 HobType,
+ IN UINT16 HobLenght
+ );
+
+
+/**
+ Returns the next instance of a HOB type from the starting HOB.
+
+ This function searches the first instance of a HOB type from the starting HOB pointer.
+ If there does not exist such HOB type from the starting HOB pointer, it will return NULL.
+ In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
+ unconditionally: it returns HobStart back if HobStart itself meets the requirement;
+ caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
+ If HobStart is NULL, then ASSERT().
+
+ @param Type The HOB type to return.
+ @param HobStart The starting HOB pointer to search from.
+
+ @return The next instance of a HOB type from the starting HOB.
+
+**/
+VOID *
+EFIAPI
+GetNextHob (
+ IN UINT16 Type,
+ IN CONST VOID *HobStart
+ );
+
+/**
+ Returns the first instance of a HOB type among the whole HOB list.
+
+ This function searches the first instance of a HOB type among the whole HOB list.
+ If there does not exist such HOB type in the HOB list, it will return NULL.
+
+ @param Type The HOB type to return.
+
+ @return The next instance of a HOB type from the starting HOB.
+
+**/
+VOID *
+EFIAPI
+GetFirstHob (
+ IN UINT16 Type
+ );
+
+/**
+ This function searches the first instance of a HOB from the starting HOB pointer.
+ Such HOB should satisfy two conditions:
+ its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
+ If there does not exist such HOB from the starting HOB pointer, it will return NULL.
+ Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
+ to extract the data section and its size info respectively.
+ In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
+ unconditionally: it returns HobStart back if HobStart itself meets the requirement;
+ caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
+ If Guid is NULL, then ASSERT().
+ If HobStart is NULL, then ASSERT().
+
+ @param Guid The GUID to match with in the HOB list.
+ @param HobStart A pointer to a Guid.
+
+ @return The next instance of the matched GUID HOB from the starting HOB.
+
+**/
+VOID *
+EFIAPI
+GetNextGuidHob (
+ IN CONST EFI_GUID *Guid,
+ IN CONST VOID *HobStart
+ );
+
+/**
+ This function searches the first instance of a HOB among the whole HOB list.
+ Such HOB should satisfy two conditions:
+ its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
+ If there does not exist such HOB from the starting HOB pointer, it will return NULL.
+ Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
+ to extract the data section and its size info respectively.
+ If Guid is NULL, then ASSERT().
+
+ @param Guid The GUID to match with in the HOB list.
+
+ @return The first instance of the matched GUID HOB among the whole HOB list.
+
+**/
+VOID *
+EFIAPI
+GetFirstGuidHob (
+ IN CONST EFI_GUID *Guid
+ );
+
+
+/**
+ Builds a HOB for a loaded PE32 module.
+
+ This function builds a HOB for a loaded PE32 module.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If ModuleName is NULL, then ASSERT().
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param ModuleName The GUID File Name of the module.
+ @param MemoryAllocationModule The 64 bit physical address of the module.
+ @param ModuleLength The length of the module in bytes.
+ @param EntryPoint The 64 bit physical address of the module entry point.
+
+**/
+VOID
+EFIAPI
+BuildModuleHob (
+ IN CONST EFI_GUID *ModuleName,
+ IN EFI_PHYSICAL_ADDRESS MemoryAllocationModule,
+ IN UINT64 ModuleLength,
+ IN EFI_PHYSICAL_ADDRESS EntryPoint
+ );
+
+/**
+ Builds a HOB that describes a chunk of system memory.
+
+ This function builds a HOB that describes a chunk of system memory.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param ResourceType The type of resource described by this HOB.
+ @param ResourceAttribute The resource attributes of the memory described by this HOB.
+ @param PhysicalStart The 64 bit physical address of memory described by this HOB.
+ @param NumberOfBytes The length of the memory described by this HOB in bytes.
+
+**/
+VOID
+EFIAPI
+BuildResourceDescriptorHob (
+ IN EFI_RESOURCE_TYPE ResourceType,
+ IN EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute,
+ IN EFI_PHYSICAL_ADDRESS PhysicalStart,
+ IN UINT64 NumberOfBytes
+ );
+
+/**
+ Builds a GUID HOB with a certain data length.
+
+ This function builds a customized HOB tagged with a GUID for identification
+ and returns the start address of GUID HOB data so that caller can fill the customized data.
+ The HOB Header and Name field is already stripped.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If Guid is NULL, then ASSERT().
+ If there is no additional space for HOB creation, then ASSERT().
+ If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
+
+ @param Guid The GUID to tag the customized HOB.
+ @param DataLength The size of the data payload for the GUID HOB.
+
+ @return The start address of GUID HOB data.
+
+**/
+VOID *
+EFIAPI
+BuildGuidHob (
+ IN CONST EFI_GUID *Guid,
+ IN UINTN DataLength
+ );
+
+/**
+ Copies a data buffer to a newly-built HOB.
+
+ This function builds a customized HOB tagged with a GUID for identification,
+ copies the input data to the HOB data field and returns the start address of the GUID HOB data.
+ The HOB Header and Name field is already stripped.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If Guid is NULL, then ASSERT().
+ If Data is NULL and DataLength > 0, then ASSERT().
+ If there is no additional space for HOB creation, then ASSERT().
+ If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
+
+ @param Guid The GUID to tag the customized HOB.
+ @param Data The data to be copied into the data field of the GUID HOB.
+ @param DataLength The size of the data payload for the GUID HOB.
+
+ @return The start address of GUID HOB data.
+
+**/
+VOID *
+EFIAPI
+BuildGuidDataHob (
+ IN CONST EFI_GUID *Guid,
+ IN VOID *Data,
+ IN UINTN DataLength
+ );
+
+/**
+ Builds a Firmware Volume HOB.
+
+ This function builds a Firmware Volume HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Firmware Volume.
+ @param Length The size of the Firmware Volume in bytes.
+
+**/
+VOID
+EFIAPI
+BuildFvHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ );
+
+/**
+ Builds a Firmware Volume HOB and a resrouce descriptor hob
+
+ This function builds a Firmware Volume HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Firmware Volume.
+ @param Length The size of the Firmware Volume in bytes.
+
+**/
+VOID
+EFIAPI
+BuildFvHobs (
+ IN EFI_PHYSICAL_ADDRESS PhysicalStart,
+ IN UINT64 NumberOfBytes,
+ IN EFI_RESOURCE_ATTRIBUTE_TYPE *ResourceAttribute OPTIONAL
+ );
+
+
+/**
+ Builds a EFI_HOB_TYPE_FV2 HOB.
+
+ This function builds a EFI_HOB_TYPE_FV2 HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Firmware Volume.
+ @param Length The size of the Firmware Volume in bytes.
+ @param FvName The name of the Firmware Volume.
+ @param FileName The name of the file.
+
+**/
+VOID
+EFIAPI
+BuildFv2Hob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length,
+ IN CONST EFI_GUID *FvName,
+ IN CONST EFI_GUID *FileName
+ );
+
+/**
+ Builds a Capsule Volume HOB.
+
+ This function builds a Capsule Volume HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Capsule Volume.
+ @param Length The size of the Capsule Volume in bytes.
+
+**/
+VOID
+EFIAPI
+BuildCvHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ );
+
+/**
+ Builds a HOB for the CPU.
+
+ This function builds a HOB for the CPU.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param SizeOfMemorySpace The maximum physical memory addressability of the processor.
+ @param SizeOfIoSpace The maximum physical I/O addressability of the processor.
+
+**/
+VOID
+EFIAPI
+BuildCpuHob (
+ IN UINT8 SizeOfMemorySpace,
+ IN UINT8 SizeOfIoSpace
+ );
+
+/**
+ Builds a HOB for the Stack.
+
+ This function builds a HOB for the stack.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The 64 bit physical address of the Stack.
+ @param Length The length of the stack in bytes.
+
+**/
+VOID
+EFIAPI
+BuildStackHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ );
+
+/**
+ Update the Stack Hob if the stack has been moved
+
+ @param BaseAddress The 64 bit physical address of the Stack.
+ @param Length The length of the stack in bytes.
+
+**/
+VOID
+UpdateStackHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ );
+
+
+/**
+ Builds a HOB for the BSP store.
+
+ This function builds a HOB for BSP store.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The 64 bit physical address of the BSP.
+ @param Length The length of the BSP store in bytes.
+ @param MemoryType Type of memory allocated by this HOB.
+
+**/
+VOID
+EFIAPI
+BuildBspStoreHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length,
+ IN EFI_MEMORY_TYPE MemoryType
+ );
+
+/**
+ Builds a HOB for the memory allocation.
+
+ This function builds a HOB for the memory allocation.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The 64 bit physical address of the memory.
+ @param Length The length of the memory allocation in bytes.
+ @param MemoryType Type of memory allocated by this HOB.
+
+**/
+VOID
+EFIAPI
+BuildMemoryAllocationHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length,
+ IN EFI_MEMORY_TYPE MemoryType
+ );
+
+
+VOID
+EFIAPI
+BuildExtractSectionHob (
+ IN EFI_GUID *Guid,
+ IN EXTRACT_GUIDED_SECTION_GET_INFO_HANDLER SectionGetInfo,
+ IN EXTRACT_GUIDED_SECTION_DECODE_HANDLER SectionExtraction
+ );
+
+VOID
+EFIAPI
+BuildPeCoffLoaderHob (
+ VOID
+ );
+
+
+/**
+ Allocates one or more 4KB pages of type EfiBootServicesData.
+
+ Allocates the number of 4KB pages of MemoryType and returns a pointer to the
+ allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
+ is returned. If there is not enough memory remaining to satisfy the request, then NULL is
+ returned.
+
+ @param Pages The number of 4 KB pages to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+AllocatePages (
+ IN UINTN Pages
+ );
+
+/**
+ Allocates a buffer of type EfiBootServicesData.
+
+ Allocates the number bytes specified by AllocationSize of type EfiBootServicesData and returns a
+ pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is
+ returned. If there is not enough memory remaining to satisfy the request, then NULL is returned.
+
+ @param AllocationSize The number of bytes to allocate.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+AllocatePool (
+ IN UINTN AllocationSize
+ );
+
+
+/**
+ Allocates one or more 4KB pages of type EfiBootServicesData at a specified alignment.
+
+ Allocates the number of 4KB pages specified by Pages of type EfiBootServicesData with an
+ alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is
+ returned. If there is not enough memory at the specified alignment remaining to satisfy the
+ request, then NULL is returned.
+ If Alignment is not a power of two and Alignment is not zero, then ASSERT().
+
+ @param Pages The number of 4 KB pages to allocate.
+ @param Alignment The requested alignment of the allocation. Must be a power of two.
+ If Alignment is zero, then byte alignment is used.
+
+ @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+AllocateAlignedPages (
+ IN UINTN Pages,
+ IN UINTN Alignment
+ );
+
+
+EFI_STATUS
+EFIAPI
+LoadPeCoffImage (
+ IN VOID *PeCoffImage,
+ OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
+ OUT UINT64 *ImageSize,
+ OUT EFI_PHYSICAL_ADDRESS *EntryPoint
+ );
+
+EFI_STATUS
+EFIAPI
+LoadDxeCoreFromFfsFile (
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ IN UINTN StackSize
+ );
+
+EFI_STATUS
+EFIAPI
+LoadDxeCoreFromFv (
+ IN UINTN *FvInstance, OPTIONAL
+ IN UINTN StackSize
+ );
+
+EFI_STATUS
+EFIAPI
+DecompressFirstFv (
+ VOID
+ );
+
+VOID
+EFIAPI
+AddDxeCoreReportStatusCodeCallback (
+ VOID
+ );
+
+
+#endif
diff --git a/EmbeddedPkg/Include/Library/SerialPortExtLib.h b/EmbeddedPkg/Include/Library/SerialPortExtLib.h
index 74f5e4c58..a12847ca9 100644
--- a/EmbeddedPkg/Include/Library/SerialPortExtLib.h
+++ b/EmbeddedPkg/Include/Library/SerialPortExtLib.h
@@ -1,66 +1,66 @@
-/** @file
-
- Copyright (c) 2012, ARM Ltd. All rights reserved.
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __SERIAL_PORT_EXT_LIB_H__
-#define __SERIAL_PORT_EXT_LIB_H__
-
-#include <Uefi/UefiBaseType.h>
-#include <Protocol/SerialIo.h>
-
-/**
- Set the serial device control bits.
-
- @return Always return EFI_UNSUPPORTED.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortSetControl (
- IN UINT32 Control
- );
-
-/**
- Get the serial device control bits.
-
- @param Control Control signals read from the serial device.
-
- @retval EFI_SUCCESS The control bits were read from the serial device.
- @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortGetControl (
- OUT UINT32 *Control
- );
-
-/**
- Set the serial device attributes.
-
- @return Always return EFI_UNSUPPORTED.
-
-**/
-RETURN_STATUS
-EFIAPI
-SerialPortSetAttributes (
- IN UINT64 BaudRate,
- IN UINT32 ReceiveFifoDepth,
- IN UINT32 Timeout,
- IN EFI_PARITY_TYPE Parity,
- IN UINT8 DataBits,
- IN EFI_STOP_BITS_TYPE StopBits
- );
-
-#endif
-
+/** @file
+
+ Copyright (c) 2012, ARM Ltd. All rights reserved.
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __SERIAL_PORT_EXT_LIB_H__
+#define __SERIAL_PORT_EXT_LIB_H__
+
+#include <Uefi/UefiBaseType.h>
+#include <Protocol/SerialIo.h>
+
+/**
+ Set the serial device control bits.
+
+ @return Always return EFI_UNSUPPORTED.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortSetControl (
+ IN UINT32 Control
+ );
+
+/**
+ Get the serial device control bits.
+
+ @param Control Control signals read from the serial device.
+
+ @retval EFI_SUCCESS The control bits were read from the serial device.
+ @retval EFI_DEVICE_ERROR The serial device is not functioning correctly.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortGetControl (
+ OUT UINT32 *Control
+ );
+
+/**
+ Set the serial device attributes.
+
+ @return Always return EFI_UNSUPPORTED.
+
+**/
+RETURN_STATUS
+EFIAPI
+SerialPortSetAttributes (
+ IN UINT64 BaudRate,
+ IN UINT32 ReceiveFifoDepth,
+ IN UINT32 Timeout,
+ IN EFI_PARITY_TYPE Parity,
+ IN UINT8 DataBits,
+ IN EFI_STOP_BITS_TYPE StopBits
+ );
+
+#endif
+
diff --git a/EmbeddedPkg/Include/Protocol/EblAddCommand.h b/EmbeddedPkg/Include/Protocol/EblAddCommand.h
index 1ce5a8f3b..a7809b27b 100644
--- a/EmbeddedPkg/Include/Protocol/EblAddCommand.h
+++ b/EmbeddedPkg/Include/Protocol/EblAddCommand.h
@@ -73,11 +73,11 @@ VOID
);
-typedef
-VOID
-(EFIAPI *EBL_GET_CHAR_CALL_BACK) (
- IN UINTN ElapsedTime
- );
+typedef
+VOID
+(EFIAPI *EBL_GET_CHAR_CALL_BACK) (
+ IN UINTN ElapsedTime
+ );
/**
Return a keypress or optionally timeout if a timeout value was passed in.
diff --git a/EmbeddedPkg/Include/Protocol/EmbeddedExternalDevice.h b/EmbeddedPkg/Include/Protocol/EmbeddedExternalDevice.h
index 17188f04a..603dc5ed8 100644
--- a/EmbeddedPkg/Include/Protocol/EmbeddedExternalDevice.h
+++ b/EmbeddedPkg/Include/Protocol/EmbeddedExternalDevice.h
@@ -1,94 +1,94 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __EMBEDDED_EXTERNAL_DEVICE_H__
-#define __EMBEDDED_EXTERNAL_DEVICE_H__
-
-//
-// Protocol GUID
-//
-#define EMBEDDED_EXTERNAL_DEVICE_PROTOCOL_GUID { 0x735F8C64, 0xD696, 0x44D0, { 0xBD, 0xF2, 0x44, 0x7F, 0xD0, 0x5A, 0x54, 0x06 }}
-
-//
-// Protocol interface structure
-//
-typedef struct _EMBEDDED_EXTERNAL_DEVICE EMBEDDED_EXTERNAL_DEVICE;
-
-//
-// Function Prototypes
-//
-typedef
-EFI_STATUS
-(EFIAPI *EMBEDDED_EXTERNAL_DEVICE_READ) (
- IN EMBEDDED_EXTERNAL_DEVICE *This,
- IN UINTN Register,
- IN UINTN Length,
- OUT VOID *Buffer
- )
-/*++
-
-Routine Description:
-
- Read a set of contiguous external device registers.
-
-Arguments:
-
- This - pointer to protocol
- Offset - starting register number
- Length - number of bytes to read
- Buffer - destination buffer
-
-Returns:
-
- EFI_SUCCESS - registers read successfully
-
---*/
-;
-
-typedef
-EFI_STATUS
-(EFIAPI *EMBEDDED_EXTERNAL_DEVICE_WRITE) (
- IN EMBEDDED_EXTERNAL_DEVICE *This,
- IN UINTN Register,
- IN UINTN Length,
- IN VOID *Buffer
- )
-/*++
-
-Routine Description:
-
- Write to a set of contiguous external device registers.
-
-Arguments:
-
- This - pointer to protocol
- Offset - starting register number
- Length - number of bytes to write
- Buffer - source buffer
-
-Returns:
-
- EFI_SUCCESS - registers written successfully
-
---*/
-;
-
-struct _EMBEDDED_EXTERNAL_DEVICE {
- EMBEDDED_EXTERNAL_DEVICE_READ Read;
- EMBEDDED_EXTERNAL_DEVICE_WRITE Write;
-};
-
-extern EFI_GUID gEmbeddedExternalDeviceProtocolGuid;
-
-#endif // __EMBEDDED_EXTERNAL_DEVICE_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __EMBEDDED_EXTERNAL_DEVICE_H__
+#define __EMBEDDED_EXTERNAL_DEVICE_H__
+
+//
+// Protocol GUID
+//
+#define EMBEDDED_EXTERNAL_DEVICE_PROTOCOL_GUID { 0x735F8C64, 0xD696, 0x44D0, { 0xBD, 0xF2, 0x44, 0x7F, 0xD0, 0x5A, 0x54, 0x06 }}
+
+//
+// Protocol interface structure
+//
+typedef struct _EMBEDDED_EXTERNAL_DEVICE EMBEDDED_EXTERNAL_DEVICE;
+
+//
+// Function Prototypes
+//
+typedef
+EFI_STATUS
+(EFIAPI *EMBEDDED_EXTERNAL_DEVICE_READ) (
+ IN EMBEDDED_EXTERNAL_DEVICE *This,
+ IN UINTN Register,
+ IN UINTN Length,
+ OUT VOID *Buffer
+ )
+/*++
+
+Routine Description:
+
+ Read a set of contiguous external device registers.
+
+Arguments:
+
+ This - pointer to protocol
+ Offset - starting register number
+ Length - number of bytes to read
+ Buffer - destination buffer
+
+Returns:
+
+ EFI_SUCCESS - registers read successfully
+
+--*/
+;
+
+typedef
+EFI_STATUS
+(EFIAPI *EMBEDDED_EXTERNAL_DEVICE_WRITE) (
+ IN EMBEDDED_EXTERNAL_DEVICE *This,
+ IN UINTN Register,
+ IN UINTN Length,
+ IN VOID *Buffer
+ )
+/*++
+
+Routine Description:
+
+ Write to a set of contiguous external device registers.
+
+Arguments:
+
+ This - pointer to protocol
+ Offset - starting register number
+ Length - number of bytes to write
+ Buffer - source buffer
+
+Returns:
+
+ EFI_SUCCESS - registers written successfully
+
+--*/
+;
+
+struct _EMBEDDED_EXTERNAL_DEVICE {
+ EMBEDDED_EXTERNAL_DEVICE_READ Read;
+ EMBEDDED_EXTERNAL_DEVICE_WRITE Write;
+};
+
+extern EFI_GUID gEmbeddedExternalDeviceProtocolGuid;
+
+#endif // __EMBEDDED_EXTERNAL_DEVICE_H__
diff --git a/EmbeddedPkg/Include/Protocol/EmbeddedGpio.h b/EmbeddedPkg/Include/Protocol/EmbeddedGpio.h
index 97a9a8bd9..77ea7ad03 100644
--- a/EmbeddedPkg/Include/Protocol/EmbeddedGpio.h
+++ b/EmbeddedPkg/Include/Protocol/EmbeddedGpio.h
@@ -1,167 +1,167 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __EMBEDDED_GPIO_H__
-#define __EMBEDDED_GPIO_H__
-
-//
-// Protocol interface structure
-//
-typedef struct _EMBEDDED_GPIO EMBEDDED_GPIO;
-
-//
-// Data Types
-//
-typedef UINTN EMBEDDED_GPIO_PIN;
-
-#define GPIO(Port, Pin) ((EMBEDDED_GPIO_PIN)(((Port) << (16)) | (Pin)))
-#define GPIO_PIN(x) ((EMBEDDED_GPIO_PIN)(x) & (0xFFFF))
-#define GPIO_PORT(x) ((EMBEDDED_GPIO_PIN)(x) >> (16))
-
-typedef enum {
- GPIO_MODE_INPUT = 0x00,
- GPIO_MODE_OUTPUT_0 = 0x0E,
- GPIO_MODE_OUTPUT_1 = 0x0F,
- GPIO_MODE_SPECIAL_FUNCTION_2 = 0x02,
- GPIO_MODE_SPECIAL_FUNCTION_3 = 0x03,
- GPIO_MODE_SPECIAL_FUNCTION_4 = 0x04,
- GPIO_MODE_SPECIAL_FUNCTION_5 = 0x05,
- GPIO_MODE_SPECIAL_FUNCTION_6 = 0x06,
- GPIO_MODE_SPECIAL_FUNCTION_7 = 0x07
-} EMBEDDED_GPIO_MODE;
-
-typedef enum {
- GPIO_PULL_NONE,
- GPIO_PULL_UP,
- GPIO_PULL_DOWN
-} EMBEDDED_GPIO_PULL;
-
-//
-// Function Prototypes
-//
-typedef
-EFI_STATUS
-(EFIAPI *EMBEDDED_GPIO_GET) (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- OUT UINTN *Value
- );
-/*++
-
-Routine Description:
-
- Gets the state of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin to read
- Value - state of the pin
-
-Returns:
-
- EFI_SUCCESS - GPIO state returned in Value
-
---*/
-
-
-typedef
-EFI_STATUS
-(EFIAPI *EMBEDDED_GPIO_SET) (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- IN EMBEDDED_GPIO_MODE Mode
- );
-/*++
-
-Routine Description:
-
- Sets the state of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin to modify
- Mode - mode to set
-
-Returns:
-
- EFI_SUCCESS - GPIO set as requested
-
---*/
-
-
-typedef
-EFI_STATUS
-(EFIAPI *EMBEDDED_GPIO_GET_MODE) (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- OUT EMBEDDED_GPIO_MODE *Mode
- );
-/*++
-
-Routine Description:
-
- Gets the mode (function) of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin
- Mode - pointer to output mode value
-
-Returns:
-
- EFI_SUCCESS - mode value retrieved
-
---*/
-
-
-typedef
-EFI_STATUS
-(EFIAPI *EMBEDDED_GPIO_SET_PULL) (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- IN EMBEDDED_GPIO_PULL Direction
- );
-/*++
-
-Routine Description:
-
- Sets the pull-up / pull-down resistor of a GPIO pin
-
-Arguments:
-
- This - pointer to protocol
- Gpio - which pin
- Direction - pull-up, pull-down, or none
-
-Returns:
-
- EFI_SUCCESS - pin was set
-
---*/
-
-
-
-struct _EMBEDDED_GPIO {
- EMBEDDED_GPIO_GET Get;
- EMBEDDED_GPIO_SET Set;
- EMBEDDED_GPIO_GET_MODE GetMode;
- EMBEDDED_GPIO_SET_PULL SetPull;
-};
-
-extern EFI_GUID gEmbeddedGpioProtocolGuid;
-
-#endif
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __EMBEDDED_GPIO_H__
+#define __EMBEDDED_GPIO_H__
+
+//
+// Protocol interface structure
+//
+typedef struct _EMBEDDED_GPIO EMBEDDED_GPIO;
+
+//
+// Data Types
+//
+typedef UINTN EMBEDDED_GPIO_PIN;
+
+#define GPIO(Port, Pin) ((EMBEDDED_GPIO_PIN)(((Port) << (16)) | (Pin)))
+#define GPIO_PIN(x) ((EMBEDDED_GPIO_PIN)(x) & (0xFFFF))
+#define GPIO_PORT(x) ((EMBEDDED_GPIO_PIN)(x) >> (16))
+
+typedef enum {
+ GPIO_MODE_INPUT = 0x00,
+ GPIO_MODE_OUTPUT_0 = 0x0E,
+ GPIO_MODE_OUTPUT_1 = 0x0F,
+ GPIO_MODE_SPECIAL_FUNCTION_2 = 0x02,
+ GPIO_MODE_SPECIAL_FUNCTION_3 = 0x03,
+ GPIO_MODE_SPECIAL_FUNCTION_4 = 0x04,
+ GPIO_MODE_SPECIAL_FUNCTION_5 = 0x05,
+ GPIO_MODE_SPECIAL_FUNCTION_6 = 0x06,
+ GPIO_MODE_SPECIAL_FUNCTION_7 = 0x07
+} EMBEDDED_GPIO_MODE;
+
+typedef enum {
+ GPIO_PULL_NONE,
+ GPIO_PULL_UP,
+ GPIO_PULL_DOWN
+} EMBEDDED_GPIO_PULL;
+
+//
+// Function Prototypes
+//
+typedef
+EFI_STATUS
+(EFIAPI *EMBEDDED_GPIO_GET) (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ OUT UINTN *Value
+ );
+/*++
+
+Routine Description:
+
+ Gets the state of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin to read
+ Value - state of the pin
+
+Returns:
+
+ EFI_SUCCESS - GPIO state returned in Value
+
+--*/
+
+
+typedef
+EFI_STATUS
+(EFIAPI *EMBEDDED_GPIO_SET) (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ IN EMBEDDED_GPIO_MODE Mode
+ );
+/*++
+
+Routine Description:
+
+ Sets the state of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin to modify
+ Mode - mode to set
+
+Returns:
+
+ EFI_SUCCESS - GPIO set as requested
+
+--*/
+
+
+typedef
+EFI_STATUS
+(EFIAPI *EMBEDDED_GPIO_GET_MODE) (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ OUT EMBEDDED_GPIO_MODE *Mode
+ );
+/*++
+
+Routine Description:
+
+ Gets the mode (function) of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin
+ Mode - pointer to output mode value
+
+Returns:
+
+ EFI_SUCCESS - mode value retrieved
+
+--*/
+
+
+typedef
+EFI_STATUS
+(EFIAPI *EMBEDDED_GPIO_SET_PULL) (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ IN EMBEDDED_GPIO_PULL Direction
+ );
+/*++
+
+Routine Description:
+
+ Sets the pull-up / pull-down resistor of a GPIO pin
+
+Arguments:
+
+ This - pointer to protocol
+ Gpio - which pin
+ Direction - pull-up, pull-down, or none
+
+Returns:
+
+ EFI_SUCCESS - pin was set
+
+--*/
+
+
+
+struct _EMBEDDED_GPIO {
+ EMBEDDED_GPIO_GET Get;
+ EMBEDDED_GPIO_SET Set;
+ EMBEDDED_GPIO_GET_MODE GetMode;
+ EMBEDDED_GPIO_SET_PULL SetPull;
+};
+
+extern EFI_GUID gEmbeddedGpioProtocolGuid;
+
+#endif
diff --git a/EmbeddedPkg/Include/fdt.h b/EmbeddedPkg/Include/fdt.h
index 6e7a8b397..3b7c37102 100644
--- a/EmbeddedPkg/Include/fdt.h
+++ b/EmbeddedPkg/Include/fdt.h
@@ -1,74 +1,74 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef _FDT_H
-#define _FDT_H
-
-#ifndef __ASSEMBLY__
-
-struct fdt_header {
- uint32_t magic; /* magic word FDT_MAGIC */
- uint32_t totalsize; /* total size of DT block */
- uint32_t off_dt_struct; /* offset to structure */
- uint32_t off_dt_strings; /* offset to strings */
- uint32_t off_mem_rsvmap; /* offset to memory reserve map */
- uint32_t version; /* format version */
- uint32_t last_comp_version; /* last compatible version */
-
- /* version 2 fields below */
- uint32_t boot_cpuid_phys; /* Which physical CPU id we're
- booting on */
- /* version 3 fields below */
- uint32_t size_dt_strings; /* size of the strings block */
-
- /* version 17 fields below */
- uint32_t size_dt_struct; /* size of the structure block */
-};
-
-struct fdt_reserve_entry {
- uint64_t address;
- uint64_t size;
-};
-
-struct fdt_node_header {
- uint32_t tag;
- char name[0];
-};
-
-struct fdt_property {
- uint32_t tag;
- uint32_t len;
- uint32_t nameoff;
- char data[0];
-};
-
-#endif /* !__ASSEMBLY */
-
-#define FDT_MAGIC 0xd00dfeed /* 4: version, 4: total size */
-#define FDT_TAGSIZE sizeof(uint32_t)
-
-#define FDT_BEGIN_NODE 0x1 /* Start node: full name */
-#define FDT_END_NODE 0x2 /* End node */
-#define FDT_PROP 0x3 /* Property: name off,
- size, content */
-#define FDT_NOP 0x4 /* nop */
-#define FDT_END 0x9
-
-#define FDT_V1_SIZE (7*sizeof(uint32_t))
-#define FDT_V2_SIZE (FDT_V1_SIZE + sizeof(uint32_t))
-#define FDT_V3_SIZE (FDT_V2_SIZE + sizeof(uint32_t))
-#define FDT_V16_SIZE FDT_V3_SIZE
-#define FDT_V17_SIZE (FDT_V16_SIZE + sizeof(uint32_t))
-
-#endif /* _FDT_H */
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef _FDT_H
+#define _FDT_H
+
+#ifndef __ASSEMBLY__
+
+struct fdt_header {
+ uint32_t magic; /* magic word FDT_MAGIC */
+ uint32_t totalsize; /* total size of DT block */
+ uint32_t off_dt_struct; /* offset to structure */
+ uint32_t off_dt_strings; /* offset to strings */
+ uint32_t off_mem_rsvmap; /* offset to memory reserve map */
+ uint32_t version; /* format version */
+ uint32_t last_comp_version; /* last compatible version */
+
+ /* version 2 fields below */
+ uint32_t boot_cpuid_phys; /* Which physical CPU id we're
+ booting on */
+ /* version 3 fields below */
+ uint32_t size_dt_strings; /* size of the strings block */
+
+ /* version 17 fields below */
+ uint32_t size_dt_struct; /* size of the structure block */
+};
+
+struct fdt_reserve_entry {
+ uint64_t address;
+ uint64_t size;
+};
+
+struct fdt_node_header {
+ uint32_t tag;
+ char name[0];
+};
+
+struct fdt_property {
+ uint32_t tag;
+ uint32_t len;
+ uint32_t nameoff;
+ char data[0];
+};
+
+#endif /* !__ASSEMBLY */
+
+#define FDT_MAGIC 0xd00dfeed /* 4: version, 4: total size */
+#define FDT_TAGSIZE sizeof(uint32_t)
+
+#define FDT_BEGIN_NODE 0x1 /* Start node: full name */
+#define FDT_END_NODE 0x2 /* End node */
+#define FDT_PROP 0x3 /* Property: name off,
+ size, content */
+#define FDT_NOP 0x4 /* nop */
+#define FDT_END 0x9
+
+#define FDT_V1_SIZE (7*sizeof(uint32_t))
+#define FDT_V2_SIZE (FDT_V1_SIZE + sizeof(uint32_t))
+#define FDT_V3_SIZE (FDT_V2_SIZE + sizeof(uint32_t))
+#define FDT_V16_SIZE FDT_V3_SIZE
+#define FDT_V17_SIZE (FDT_V16_SIZE + sizeof(uint32_t))
+
+#endif /* _FDT_H */
diff --git a/EmbeddedPkg/Include/libfdt.h b/EmbeddedPkg/Include/libfdt.h
index 73f49759a..85fe324c4 100644
--- a/EmbeddedPkg/Include/libfdt.h
+++ b/EmbeddedPkg/Include/libfdt.h
@@ -1,1478 +1,1478 @@
-#ifndef _LIBFDT_H
-#define _LIBFDT_H
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <libfdt_env.h>
-#include <fdt.h>
-
-#define FDT_FIRST_SUPPORTED_VERSION 0x10
-#define FDT_LAST_SUPPORTED_VERSION 0x11
-
-/* Error codes: informative error codes */
-#define FDT_ERR_NOTFOUND 1
- /* FDT_ERR_NOTFOUND: The requested node or property does not exist */
-#define FDT_ERR_EXISTS 2
- /* FDT_ERR_EXISTS: Attemped to create a node or property which
- * already exists */
-#define FDT_ERR_NOSPACE 3
- /* FDT_ERR_NOSPACE: Operation needed to expand the device
- * tree, but its buffer did not have sufficient space to
- * contain the expanded tree. Use fdt_open_into() to move the
- * device tree to a buffer with more space. */
-
-/* Error codes: codes for bad parameters */
-#define FDT_ERR_BADOFFSET 4
- /* FDT_ERR_BADOFFSET: Function was passed a structure block
- * offset which is out-of-bounds, or which points to an
- * unsuitable part of the structure for the operation. */
-#define FDT_ERR_BADPATH 5
- /* FDT_ERR_BADPATH: Function was passed a badly formatted path
- * (e.g. missing a leading / for a function which requires an
- * absolute path) */
-#define FDT_ERR_BADPHANDLE 6
- /* FDT_ERR_BADPHANDLE: Function was passed an invalid phandle
- * value. phandle values of 0 and -1 are not permitted. */
-#define FDT_ERR_BADSTATE 7
- /* FDT_ERR_BADSTATE: Function was passed an incomplete device
- * tree created by the sequential-write functions, which is
- * not sufficiently complete for the requested operation. */
-
-/* Error codes: codes for bad device tree blobs */
-#define FDT_ERR_TRUNCATED 8
- /* FDT_ERR_TRUNCATED: Structure block of the given device tree
- * ends without an FDT_END tag. */
-#define FDT_ERR_BADMAGIC 9
- /* FDT_ERR_BADMAGIC: Given "device tree" appears not to be a
- * device tree at all - it is missing the flattened device
- * tree magic number. */
-#define FDT_ERR_BADVERSION 10
- /* FDT_ERR_BADVERSION: Given device tree has a version which
- * can't be handled by the requested operation. For
- * read-write functions, this may mean that fdt_open_into() is
- * required to convert the tree to the expected version. */
-#define FDT_ERR_BADSTRUCTURE 11
- /* FDT_ERR_BADSTRUCTURE: Given device tree has a corrupt
- * structure block or other serious error (e.g. misnested
- * nodes, or subnodes preceding properties). */
-#define FDT_ERR_BADLAYOUT 12
- /* FDT_ERR_BADLAYOUT: For read-write functions, the given
- * device tree has it's sub-blocks in an order that the
- * function can't handle (memory reserve map, then structure,
- * then strings). Use fdt_open_into() to reorganize the tree
- * into a form suitable for the read-write operations. */
-
-/* "Can't happen" error indicating a bug in libfdt */
-#define FDT_ERR_INTERNAL 13
- /* FDT_ERR_INTERNAL: libfdt has failed an internal assertion.
- * Should never be returned, if it is, it indicates a bug in
- * libfdt itself. */
-
-#define FDT_ERR_MAX 13
-
-/**********************************************************************/
-/* Low-level functions (you probably don't need these) */
-/**********************************************************************/
-
-const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int checklen);
-static inline void *fdt_offset_ptr_w(void *fdt, int offset, int checklen)
-{
- return (void *)(uintptr_t)fdt_offset_ptr(fdt, offset, checklen);
-}
-
-uint32_t fdt_next_tag(const void *fdt, int offset, int *nextoffset);
-
-/**********************************************************************/
-/* Traversal functions */
-/**********************************************************************/
-
-int fdt_next_node(const void *fdt, int offset, int *depth);
-
-/**********************************************************************/
-/* General functions */
-/**********************************************************************/
-
-#define fdt_get_header(fdt, field) \
- (fdt32_to_cpu(((const struct fdt_header *)(fdt))->field))
-#define fdt_magic(fdt) (fdt_get_header(fdt, magic))
-#define fdt_totalsize(fdt) (fdt_get_header(fdt, totalsize))
-#define fdt_off_dt_struct(fdt) (fdt_get_header(fdt, off_dt_struct))
-#define fdt_off_dt_strings(fdt) (fdt_get_header(fdt, off_dt_strings))
-#define fdt_off_mem_rsvmap(fdt) (fdt_get_header(fdt, off_mem_rsvmap))
-#define fdt_version(fdt) (fdt_get_header(fdt, version))
-#define fdt_last_comp_version(fdt) (fdt_get_header(fdt, last_comp_version))
-#define fdt_boot_cpuid_phys(fdt) (fdt_get_header(fdt, boot_cpuid_phys))
-#define fdt_size_dt_strings(fdt) (fdt_get_header(fdt, size_dt_strings))
-#define fdt_size_dt_struct(fdt) (fdt_get_header(fdt, size_dt_struct))
-
-#define __fdt_set_hdr(name) \
- static inline void fdt_set_##name(void *fdt, uint32_t val) \
- { \
- struct fdt_header *fdth = (struct fdt_header*)fdt; \
- fdth->name = cpu_to_fdt32(val); \
- }
-__fdt_set_hdr(magic);
-__fdt_set_hdr(totalsize);
-__fdt_set_hdr(off_dt_struct);
-__fdt_set_hdr(off_dt_strings);
-__fdt_set_hdr(off_mem_rsvmap);
-__fdt_set_hdr(version);
-__fdt_set_hdr(last_comp_version);
-__fdt_set_hdr(boot_cpuid_phys);
-__fdt_set_hdr(size_dt_strings);
-__fdt_set_hdr(size_dt_struct);
-#undef __fdt_set_hdr
-
-/**
- * fdt_check_header - sanity check a device tree or possible device tree
- * @fdt: pointer to data which might be a flattened device tree
- *
- * fdt_check_header() checks that the given buffer contains what
- * appears to be a flattened device tree with sane information in its
- * header.
- *
- * returns:
- * 0, if the buffer appears to contain a valid device tree
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE, standard meanings, as above
- */
-int fdt_check_header(const void *fdt);
-
-/**
- * fdt_move - move a device tree around in memory
- * @fdt: pointer to the device tree to move
- * @buf: pointer to memory where the device is to be moved
- * @bufsize: size of the memory space at buf
- *
- * fdt_move() relocates, if possible, the device tree blob located at
- * fdt to the buffer at buf of size bufsize. The buffer may overlap
- * with the existing device tree blob at fdt. Therefore,
- * fdt_move(fdt, fdt, fdt_totalsize(fdt))
- * should always succeed.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, bufsize is insufficient to contain the device tree
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE, standard meanings
- */
-int fdt_move(const void *fdt, void *buf, int bufsize);
-
-/**********************************************************************/
-/* Read-only functions */
-/**********************************************************************/
-
-/**
- * fdt_string - retrieve a string from the strings block of a device tree
- * @fdt: pointer to the device tree blob
- * @stroffset: offset of the string within the strings block (native endian)
- *
- * fdt_string() retrieves a pointer to a single string from the
- * strings block of the device tree blob at fdt.
- *
- * returns:
- * a pointer to the string, on success
- * NULL, if stroffset is out of bounds
- */
-const char *fdt_string(const void *fdt, int stroffset);
-
-/**
- * fdt_num_mem_rsv - retrieve the number of memory reserve map entries
- * @fdt: pointer to the device tree blob
- *
- * Returns the number of entries in the device tree blob's memory
- * reservation map. This does not include the terminating 0,0 entry
- * or any other (0,0) entries reserved for expansion.
- *
- * returns:
- * the number of entries
- */
-int fdt_num_mem_rsv(const void *fdt);
-
-/**
- * fdt_get_mem_rsv - retrieve one memory reserve map entry
- * @fdt: pointer to the device tree blob
- * @address, @size: pointers to 64-bit variables
- *
- * On success, *address and *size will contain the address and size of
- * the n-th reserve map entry from the device tree blob, in
- * native-endian format.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE, standard meanings
- */
-int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);
-
-/**
- * fdt_subnode_offset_namelen - find a subnode based on substring
- * @fdt: pointer to the device tree blob
- * @parentoffset: structure block offset of a node
- * @name: name of the subnode to locate
- * @namelen: number of characters of name to consider
- *
- * Identical to fdt_subnode_offset(), but only examine the first
- * namelen characters of name for matching the subnode name. This is
- * useful for finding subnodes based on a portion of a larger string,
- * such as a full path.
- */
-int fdt_subnode_offset_namelen(const void *fdt, int parentoffset,
- const char *name, int namelen);
-/**
- * fdt_subnode_offset - find a subnode of a given node
- * @fdt: pointer to the device tree blob
- * @parentoffset: structure block offset of a node
- * @name: name of the subnode to locate
- *
- * fdt_subnode_offset() finds a subnode of the node at structure block
- * offset parentoffset with the given name. name may include a unit
- * address, in which case fdt_subnode_offset() will find the subnode
- * with that unit address, or the unit address may be omitted, in
- * which case fdt_subnode_offset() will find an arbitrary subnode
- * whose name excluding unit address matches the given name.
- *
- * returns:
- * structure block offset of the requested subnode (>=0), on success
- * -FDT_ERR_NOTFOUND, if the requested subnode does not exist
- * -FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings.
- */
-int fdt_subnode_offset(const void *fdt, int parentoffset, const char *name);
-
-/**
- * fdt_path_offset - find a tree node by its full path
- * @fdt: pointer to the device tree blob
- * @path: full path of the node to locate
- *
- * fdt_path_offset() finds a node of a given path in the device tree.
- * Each path component may omit the unit address portion, but the
- * results of this are undefined if any such path component is
- * ambiguous (that is if there are multiple nodes at the relevant
- * level matching the given component, differentiated only by unit
- * address).
- *
- * returns:
- * structure block offset of the node with the requested path (>=0), on success
- * -FDT_ERR_BADPATH, given path does not begin with '/' or is invalid
- * -FDT_ERR_NOTFOUND, if the requested node does not exist
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings.
- */
-int fdt_path_offset(const void *fdt, const char *path);
-
-/**
- * fdt_get_name - retrieve the name of a given node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: structure block offset of the starting node
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * fdt_get_name() retrieves the name (including unit address) of the
- * device tree node at structure block offset nodeoffset. If lenp is
- * non-NULL, the length of this name is also returned, in the integer
- * pointed to by lenp.
- *
- * returns:
- * pointer to the node's name, on success
- * If lenp is non-NULL, *lenp contains the length of that name (>=0)
- * NULL, on error
- * if lenp is non-NULL *lenp contains an error code (<0):
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE, standard meanings
- */
-const char *fdt_get_name(const void *fdt, int nodeoffset, int *lenp);
-
-/**
- * fdt_first_property_offset - find the offset of a node's first property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: structure block offset of a node
- *
- * fdt_first_property_offset() finds the first property of the node at
- * the given structure block offset.
- *
- * returns:
- * structure block offset of the property (>=0), on success
- * -FDT_ERR_NOTFOUND, if the requested node has no properties
- * -FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings.
- */
-int fdt_first_property_offset(const void *fdt, int nodeoffset);
-
-/**
- * fdt_next_property_offset - step through a node's properties
- * @fdt: pointer to the device tree blob
- * @offset: structure block offset of a property
- *
- * fdt_next_property_offset() finds the property immediately after the
- * one at the given structure block offset. This will be a property
- * of the same node as the given property.
- *
- * returns:
- * structure block offset of the next property (>=0), on success
- * -FDT_ERR_NOTFOUND, if the given property is the last in its node
- * -FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_PROP tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings.
- */
-int fdt_next_property_offset(const void *fdt, int offset);
-
-/**
- * fdt_get_property_by_offset - retrieve the property at a given offset
- * @fdt: pointer to the device tree blob
- * @offset: offset of the property to retrieve
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * fdt_get_property_by_offset() retrieves a pointer to the
- * fdt_property structure within the device tree blob at the given
- * offset. If lenp is non-NULL, the length of the property value is
- * also returned, in the integer pointed to by lenp.
- *
- * returns:
- * pointer to the structure representing the property
- * if lenp is non-NULL, *lenp contains the length of the property
- * value (>=0)
- * NULL, on error
- * if lenp is non-NULL, *lenp contains an error code (<0):
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-const struct fdt_property *fdt_get_property_by_offset(const void *fdt,
- int offset,
- int *lenp);
-
-/**
- * fdt_get_property_namelen - find a property based on substring
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to find
- * @name: name of the property to find
- * @namelen: number of characters of name to consider
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * Identical to fdt_get_property_namelen(), but only examine the first
- * namelen characters of name for matching the property name.
- */
-const struct fdt_property *fdt_get_property_namelen(const void *fdt,
- int nodeoffset,
- const char *name,
- int namelen, int *lenp);
-
-/**
- * fdt_get_property - find a given property in a given node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to find
- * @name: name of the property to find
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * fdt_get_property() retrieves a pointer to the fdt_property
- * structure within the device tree blob corresponding to the property
- * named 'name' of the node at offset nodeoffset. If lenp is
- * non-NULL, the length of the property value is also returned, in the
- * integer pointed to by lenp.
- *
- * returns:
- * pointer to the structure representing the property
- * if lenp is non-NULL, *lenp contains the length of the property
- * value (>=0)
- * NULL, on error
- * if lenp is non-NULL, *lenp contains an error code (<0):
- * -FDT_ERR_NOTFOUND, node does not have named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-const struct fdt_property *fdt_get_property(const void *fdt, int nodeoffset,
- const char *name, int *lenp);
-static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
- const char *name,
- int *lenp)
-{
- return (struct fdt_property *)(uintptr_t)
- fdt_get_property(fdt, nodeoffset, name, lenp);
-}
-
-/**
- * fdt_getprop_by_offset - retrieve the value of a property at a given offset
- * @fdt: pointer to the device tree blob
- * @ffset: offset of the property to read
- * @namep: pointer to a string variable (will be overwritten) or NULL
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * fdt_getprop_by_offset() retrieves a pointer to the value of the
- * property at structure block offset 'offset' (this will be a pointer
- * to within the device blob itself, not a copy of the value). If
- * lenp is non-NULL, the length of the property value is also
- * returned, in the integer pointed to by lenp. If namep is non-NULL,
- * the property's namne will also be returned in the char * pointed to
- * by namep (this will be a pointer to within the device tree's string
- * block, not a new copy of the name).
- *
- * returns:
- * pointer to the property's value
- * if lenp is non-NULL, *lenp contains the length of the property
- * value (>=0)
- * if namep is non-NULL *namep contiains a pointer to the property
- * name.
- * NULL, on error
- * if lenp is non-NULL, *lenp contains an error code (<0):
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-const void *fdt_getprop_by_offset(const void *fdt, int offset,
- const char **namep, int *lenp);
-
-/**
- * fdt_getprop_namelen - get property value based on substring
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to find
- * @name: name of the property to find
- * @namelen: number of characters of name to consider
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * Identical to fdt_getprop(), but only examine the first namelen
- * characters of name for matching the property name.
- */
-const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
- const char *name, int namelen, int *lenp);
-
-/**
- * fdt_getprop - retrieve the value of a given property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to find
- * @name: name of the property to find
- * @lenp: pointer to an integer variable (will be overwritten) or NULL
- *
- * fdt_getprop() retrieves a pointer to the value of the property
- * named 'name' of the node at offset nodeoffset (this will be a
- * pointer to within the device blob itself, not a copy of the value).
- * If lenp is non-NULL, the length of the property value is also
- * returned, in the integer pointed to by lenp.
- *
- * returns:
- * pointer to the property's value
- * if lenp is non-NULL, *lenp contains the length of the property
- * value (>=0)
- * NULL, on error
- * if lenp is non-NULL, *lenp contains an error code (<0):
- * -FDT_ERR_NOTFOUND, node does not have named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-const void *fdt_getprop(const void *fdt, int nodeoffset,
- const char *name, int *lenp);
-static inline void *fdt_getprop_w(void *fdt, int nodeoffset,
- const char *name, int *lenp)
-{
- return (void *)(uintptr_t)fdt_getprop(fdt, nodeoffset, name, lenp);
-}
-
-/**
- * fdt_get_phandle - retrieve the phandle of a given node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: structure block offset of the node
- *
- * fdt_get_phandle() retrieves the phandle of the device tree node at
- * structure block offset nodeoffset.
- *
- * returns:
- * the phandle of the node at nodeoffset, on success (!= 0, != -1)
- * 0, if the node has no phandle, or another error occurs
- */
-uint32_t fdt_get_phandle(const void *fdt, int nodeoffset);
-
-/**
- * fdt_get_alias_namelen - get alias based on substring
- * @fdt: pointer to the device tree blob
- * @name: name of the alias th look up
- * @namelen: number of characters of name to consider
- *
- * Identical to fdt_get_alias(), but only examine the first namelen
- * characters of name for matching the alias name.
- */
-const char *fdt_get_alias_namelen(const void *fdt,
- const char *name, int namelen);
-
-/**
- * fdt_get_alias - retreive the path referenced by a given alias
- * @fdt: pointer to the device tree blob
- * @name: name of the alias th look up
- *
- * fdt_get_alias() retrieves the value of a given alias. That is, the
- * value of the property named 'name' in the node /aliases.
- *
- * returns:
- * a pointer to the expansion of the alias named 'name', of it exists
- * NULL, if the given alias or the /aliases node does not exist
- */
-const char *fdt_get_alias(const void *fdt, const char *name);
-
-/**
- * fdt_get_path - determine the full path of a node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose path to find
- * @buf: character buffer to contain the returned path (will be overwritten)
- * @buflen: size of the character buffer at buf
- *
- * fdt_get_path() computes the full path of the node at offset
- * nodeoffset, and records that path in the buffer at buf.
- *
- * NOTE: This function is expensive, as it must scan the device tree
- * structure from the start to nodeoffset.
- *
- * returns:
- * 0, on success
- * buf contains the absolute path of the node at
- * nodeoffset, as a NUL-terminated string.
- * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
- * -FDT_ERR_NOSPACE, the path of the given node is longer than (bufsize-1)
- * characters and will not fit in the given buffer.
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);
-
-/**
- * fdt_supernode_atdepth_offset - find a specific ancestor of a node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose parent to find
- * @supernodedepth: depth of the ancestor to find
- * @nodedepth: pointer to an integer variable (will be overwritten) or NULL
- *
- * fdt_supernode_atdepth_offset() finds an ancestor of the given node
- * at a specific depth from the root (where the root itself has depth
- * 0, its immediate subnodes depth 1 and so forth). So
- * fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
- * will always return 0, the offset of the root node. If the node at
- * nodeoffset has depth D, then:
- * fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
- * will return nodeoffset itself.
- *
- * NOTE: This function is expensive, as it must scan the device tree
- * structure from the start to nodeoffset.
- *
- * returns:
-
- * structure block offset of the node at node offset's ancestor
- * of depth supernodedepth (>=0), on success
- * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
-* -FDT_ERR_NOTFOUND, supernodedepth was greater than the depth of nodeoffset
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
- int supernodedepth, int *nodedepth);
-
-/**
- * fdt_node_depth - find the depth of a given node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose parent to find
- *
- * fdt_node_depth() finds the depth of a given node. The root node
- * has depth 0, its immediate subnodes depth 1 and so forth.
- *
- * NOTE: This function is expensive, as it must scan the device tree
- * structure from the start to nodeoffset.
- *
- * returns:
- * depth of the node at nodeoffset (>=0), on success
- * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_node_depth(const void *fdt, int nodeoffset);
-
-/**
- * fdt_parent_offset - find the parent of a given node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose parent to find
- *
- * fdt_parent_offset() locates the parent node of a given node (that
- * is, it finds the offset of the node which contains the node at
- * nodeoffset as a subnode).
- *
- * NOTE: This function is expensive, as it must scan the device tree
- * structure from the start to nodeoffset, *twice*.
- *
- * returns:
- * structure block offset of the parent of the node at nodeoffset
- * (>=0), on success
- * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_parent_offset(const void *fdt, int nodeoffset);
-
-/**
- * fdt_node_offset_by_prop_value - find nodes with a given property value
- * @fdt: pointer to the device tree blob
- * @startoffset: only find nodes after this offset
- * @propname: property name to check
- * @propval: property value to search for
- * @proplen: length of the value in propval
- *
- * fdt_node_offset_by_prop_value() returns the offset of the first
- * node after startoffset, which has a property named propname whose
- * value is of length proplen and has value equal to propval; or if
- * startoffset is -1, the very first such node in the tree.
- *
- * To iterate through all nodes matching the criterion, the following
- * idiom can be used:
- * offset = fdt_node_offset_by_prop_value(fdt, -1, propname,
- * propval, proplen);
- * while (offset != -FDT_ERR_NOTFOUND) {
- * // other code here
- * offset = fdt_node_offset_by_prop_value(fdt, offset, propname,
- * propval, proplen);
- * }
- *
- * Note the -1 in the first call to the function, if 0 is used here
- * instead, the function will never locate the root node, even if it
- * matches the criterion.
- *
- * returns:
- * structure block offset of the located node (>= 0, >startoffset),
- * on success
- * -FDT_ERR_NOTFOUND, no node matching the criterion exists in the
- * tree after startoffset
- * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_node_offset_by_prop_value(const void *fdt, int startoffset,
- const char *propname,
- const void *propval, int proplen);
-
-/**
- * fdt_node_offset_by_phandle - find the node with a given phandle
- * @fdt: pointer to the device tree blob
- * @phandle: phandle value
- *
- * fdt_node_offset_by_phandle() returns the offset of the node
- * which has the given phandle value. If there is more than one node
- * in the tree with the given phandle (an invalid tree), results are
- * undefined.
- *
- * returns:
- * structure block offset of the located node (>= 0), on success
- * -FDT_ERR_NOTFOUND, no node with that phandle exists
- * -FDT_ERR_BADPHANDLE, given phandle value was invalid (0 or -1)
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle);
-
-/**
- * fdt_node_check_compatible: check a node's compatible property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of a tree node
- * @compatible: string to match against
- *
- *
- * fdt_node_check_compatible() returns 0 if the given node contains a
- * 'compatible' property with the given string as one of its elements,
- * it returns non-zero otherwise, or on error.
- *
- * returns:
- * 0, if the node has a 'compatible' property listing the given string
- * 1, if the node has a 'compatible' property, but it does not list
- * the given string
- * -FDT_ERR_NOTFOUND, if the given node has no 'compatible' property
- * -FDT_ERR_BADOFFSET, if nodeoffset does not refer to a BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_node_check_compatible(const void *fdt, int nodeoffset,
- const char *compatible);
-
-/**
- * fdt_node_offset_by_compatible - find nodes with a given 'compatible' value
- * @fdt: pointer to the device tree blob
- * @startoffset: only find nodes after this offset
- * @compatible: 'compatible' string to match against
- *
- * fdt_node_offset_by_compatible() returns the offset of the first
- * node after startoffset, which has a 'compatible' property which
- * lists the given compatible string; or if startoffset is -1, the
- * very first such node in the tree.
- *
- * To iterate through all nodes matching the criterion, the following
- * idiom can be used:
- * offset = fdt_node_offset_by_compatible(fdt, -1, compatible);
- * while (offset != -FDT_ERR_NOTFOUND) {
- * // other code here
- * offset = fdt_node_offset_by_compatible(fdt, offset, compatible);
- * }
- *
- * Note the -1 in the first call to the function, if 0 is used here
- * instead, the function will never locate the root node, even if it
- * matches the criterion.
- *
- * returns:
- * structure block offset of the located node (>= 0, >startoffset),
- * on success
- * -FDT_ERR_NOTFOUND, no node matching the criterion exists in the
- * tree after startoffset
- * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE, standard meanings
- */
-int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
- const char *compatible);
-
-/**********************************************************************/
-/* Write-in-place functions */
-/**********************************************************************/
-
-/**
- * fdt_setprop_inplace - change a property's value, but not its size
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: pointer to data to replace the property value with
- * @len: length of the property value
- *
- * fdt_setprop_inplace() replaces the value of a given property with
- * the data in val, of length len. This function cannot change the
- * size of a property, and so will only work if len is equal to the
- * current length of the property.
- *
- * This function will alter only the bytes in the blob which contain
- * the given property value, and will not alter or move any other part
- * of the tree.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, if len is not equal to the property's current length
- * -FDT_ERR_NOTFOUND, node does not have the named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
- const void *val, int len);
-
-/**
- * fdt_setprop_inplace_u32 - change the value of a 32-bit integer property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: 32-bit integer value to replace the property with
- *
- * fdt_setprop_inplace_u32() replaces the value of a given property
- * with the 32-bit integer value in val, converting val to big-endian
- * if necessary. This function cannot change the size of a property,
- * and so will only work if the property already exists and has length
- * 4.
- *
- * This function will alter only the bytes in the blob which contain
- * the given property value, and will not alter or move any other part
- * of the tree.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, if the property's length is not equal to 4
- * -FDT_ERR_NOTFOUND, node does not have the named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-static inline int fdt_setprop_inplace_u32(void *fdt, int nodeoffset,
- const char *name, uint32_t val)
-{
- val = cpu_to_fdt32(val);
- return fdt_setprop_inplace(fdt, nodeoffset, name, &val, sizeof(val));
-}
-
-/**
- * fdt_setprop_inplace_u64 - change the value of a 64-bit integer property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: 64-bit integer value to replace the property with
- *
- * fdt_setprop_inplace_u64() replaces the value of a given property
- * with the 64-bit integer value in val, converting val to big-endian
- * if necessary. This function cannot change the size of a property,
- * and so will only work if the property already exists and has length
- * 8.
- *
- * This function will alter only the bytes in the blob which contain
- * the given property value, and will not alter or move any other part
- * of the tree.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, if the property's length is not equal to 8
- * -FDT_ERR_NOTFOUND, node does not have the named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-static inline int fdt_setprop_inplace_u64(void *fdt, int nodeoffset,
- const char *name, uint64_t val)
-{
- val = cpu_to_fdt64(val);
- return fdt_setprop_inplace(fdt, nodeoffset, name, &val, sizeof(val));
-}
-
-/**
- * fdt_setprop_inplace_cell - change the value of a single-cell property
- *
- * This is an alternative name for fdt_setprop_inplace_u32()
- */
-static inline int fdt_setprop_inplace_cell(void *fdt, int nodeoffset,
- const char *name, uint32_t val)
-{
- return fdt_setprop_inplace_u32(fdt, nodeoffset, name, val);
-}
-
-/**
- * fdt_nop_property - replace a property with nop tags
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to nop
- * @name: name of the property to nop
- *
- * fdt_nop_property() will replace a given property's representation
- * in the blob with FDT_NOP tags, effectively removing it from the
- * tree.
- *
- * This function will alter only the bytes in the blob which contain
- * the property, and will not alter or move any other part of the
- * tree.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOTFOUND, node does not have the named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_nop_property(void *fdt, int nodeoffset, const char *name);
-
-/**
- * fdt_nop_node - replace a node (subtree) with nop tags
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node to nop
- *
- * fdt_nop_node() will replace a given node's representation in the
- * blob, including all its subnodes, if any, with FDT_NOP tags,
- * effectively removing it from the tree.
- *
- * This function will alter only the bytes in the blob which contain
- * the node and its properties and subnodes, and will not alter or
- * move any other part of the tree.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_nop_node(void *fdt, int nodeoffset);
-
-/**********************************************************************/
-/* Sequential write functions */
-/**********************************************************************/
-
-int fdt_create(void *buf, int bufsize);
-int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size);
-int fdt_finish_reservemap(void *fdt);
-int fdt_begin_node(void *fdt, const char *name);
-int fdt_property(void *fdt, const char *name, const void *val, int len);
-static inline int fdt_property_u32(void *fdt, const char *name, uint32_t val)
-{
- val = cpu_to_fdt32(val);
- return fdt_property(fdt, name, &val, sizeof(val));
-}
-static inline int fdt_property_u64(void *fdt, const char *name, uint64_t val)
-{
- val = cpu_to_fdt64(val);
- return fdt_property(fdt, name, &val, sizeof(val));
-}
-static inline int fdt_property_cell(void *fdt, const char *name, uint32_t val)
-{
- return fdt_property_u32(fdt, name, val);
-}
-#define fdt_property_string(fdt, name, str) \
- fdt_property(fdt, name, str, strlen(str)+1)
-int fdt_end_node(void *fdt);
-int fdt_finish(void *fdt);
-
-/**********************************************************************/
-/* Read-write functions */
-/**********************************************************************/
-
-int fdt_create_empty_tree(void *buf, int bufsize);
-int fdt_open_into(const void *fdt, void *buf, int bufsize);
-int fdt_pack(void *fdt);
-
-/**
- * fdt_add_mem_rsv - add one memory reserve map entry
- * @fdt: pointer to the device tree blob
- * @address, @size: 64-bit values (native endian)
- *
- * Adds a reserve map entry to the given blob reserving a region at
- * address address of length size.
- *
- * This function will insert data into the reserve map and will
- * therefore change the indexes of some entries in the table.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new reservation entry
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size);
-
-/**
- * fdt_del_mem_rsv - remove a memory reserve map entry
- * @fdt: pointer to the device tree blob
- * @n: entry to remove
- *
- * fdt_del_mem_rsv() removes the n-th memory reserve map entry from
- * the blob.
- *
- * This function will delete data from the reservation table and will
- * therefore change the indexes of some entries in the table.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOTFOUND, there is no entry of the given index (i.e. there
- * are less than n+1 reserve map entries)
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_del_mem_rsv(void *fdt, int n);
-
-/**
- * fdt_set_name - change the name of a given node
- * @fdt: pointer to the device tree blob
- * @nodeoffset: structure block offset of a node
- * @name: name to give the node
- *
- * fdt_set_name() replaces the name (including unit address, if any)
- * of the given node with the given string. NOTE: this function can't
- * efficiently check if the new name is unique amongst the given
- * node's siblings; results are undefined if this function is invoked
- * with a name equal to one of the given node's siblings.
- *
- * This function may insert or delete data from the blob, and will
- * therefore change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob
- * to contain the new name
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE, standard meanings
- */
-int fdt_set_name(void *fdt, int nodeoffset, const char *name);
-
-/**
- * fdt_setprop - create or change a property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: pointer to data to set the property value to
- * @len: length of the property value
- *
- * fdt_setprop() sets the value of the named property in the given
- * node to the given value and length, creating the property if it
- * does not already exist.
- *
- * This function may insert or delete data from the blob, and will
- * therefore change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_setprop(void *fdt, int nodeoffset, const char *name,
- const void *val, int len);
-
-/**
- * fdt_setprop_u32 - set a property to a 32-bit integer
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: 32-bit integer value for the property (native endian)
- *
- * fdt_setprop_u32() sets the value of the named property in the given
- * node to the given 32-bit integer value (converting to big-endian if
- * necessary), or creates a new property with that value if it does
- * not already exist.
- *
- * This function may insert or delete data from the blob, and will
- * therefore change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-static inline int fdt_setprop_u32(void *fdt, int nodeoffset, const char *name,
- uint32_t val)
-{
- val = cpu_to_fdt32(val);
- return fdt_setprop(fdt, nodeoffset, name, &val, sizeof(val));
-}
-
-/**
- * fdt_setprop_u64 - set a property to a 64-bit integer
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: 64-bit integer value for the property (native endian)
- *
- * fdt_setprop_u64() sets the value of the named property in the given
- * node to the given 64-bit integer value (converting to big-endian if
- * necessary), or creates a new property with that value if it does
- * not already exist.
- *
- * This function may insert or delete data from the blob, and will
- * therefore change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-static inline int fdt_setprop_u64(void *fdt, int nodeoffset, const char *name,
- uint64_t val)
-{
- val = cpu_to_fdt64(val);
- return fdt_setprop(fdt, nodeoffset, name, &val, sizeof(val));
-}
-
-/**
- * fdt_setprop_cell - set a property to a single cell value
- *
- * This is an alternative name for fdt_setprop_u32()
- */
-static inline int fdt_setprop_cell(void *fdt, int nodeoffset, const char *name,
- uint32_t val)
-{
- return fdt_setprop_u32(fdt, nodeoffset, name, val);
-}
-
-/**
- * fdt_setprop_string - set a property to a string value
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @str: string value for the property
- *
- * fdt_setprop_string() sets the value of the named property in the
- * given node to the given string value (using the length of the
- * string to determine the new length of the property), or creates a
- * new property with that value if it does not already exist.
- *
- * This function may insert or delete data from the blob, and will
- * therefore change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-#define fdt_setprop_string(fdt, nodeoffset, name, str) \
- fdt_setprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)
-
-/**
- * fdt_appendprop - append to or create a property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to append to
- * @val: pointer to data to append to the property value
- * @len: length of the data to append to the property value
- *
- * fdt_appendprop() appends the value to the named property in the
- * given node, creating the property if it does not already exist.
- *
- * This function may insert data into the blob, and will therefore
- * change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
- const void *val, int len);
-
-/**
- * fdt_appendprop_u32 - append a 32-bit integer value to a property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: 32-bit integer value to append to the property (native endian)
- *
- * fdt_appendprop_u32() appends the given 32-bit integer value
- * (converting to big-endian if necessary) to the value of the named
- * property in the given node, or creates a new property with that
- * value if it does not already exist.
- *
- * This function may insert data into the blob, and will therefore
- * change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-static inline int fdt_appendprop_u32(void *fdt, int nodeoffset,
- const char *name, uint32_t val)
-{
- val = cpu_to_fdt32(val);
- return fdt_appendprop(fdt, nodeoffset, name, &val, sizeof(val));
-}
-
-/**
- * fdt_appendprop_u64 - append a 64-bit integer value to a property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @val: 64-bit integer value to append to the property (native endian)
- *
- * fdt_appendprop_u64() appends the given 64-bit integer value
- * (converting to big-endian if necessary) to the value of the named
- * property in the given node, or creates a new property with that
- * value if it does not already exist.
- *
- * This function may insert data into the blob, and will therefore
- * change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-static inline int fdt_appendprop_u64(void *fdt, int nodeoffset,
- const char *name, uint64_t val)
-{
- val = cpu_to_fdt64(val);
- return fdt_appendprop(fdt, nodeoffset, name, &val, sizeof(val));
-}
-
-/**
- * fdt_appendprop_cell - append a single cell value to a property
- *
- * This is an alternative name for fdt_appendprop_u32()
- */
-static inline int fdt_appendprop_cell(void *fdt, int nodeoffset,
- const char *name, uint32_t val)
-{
- return fdt_appendprop_u32(fdt, nodeoffset, name, val);
-}
-
-/**
- * fdt_appendprop_string - append a string to a property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to change
- * @name: name of the property to change
- * @str: string value to append to the property
- *
- * fdt_appendprop_string() appends the given string to the value of
- * the named property in the given node, or creates a new property
- * with that value if it does not already exist.
- *
- * This function may insert data into the blob, and will therefore
- * change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
- * contain the new property value
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-#define fdt_appendprop_string(fdt, nodeoffset, name, str) \
- fdt_appendprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)
-
-/**
- * fdt_delprop - delete a property
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node whose property to nop
- * @name: name of the property to nop
- *
- * fdt_del_property() will delete the given property.
- *
- * This function will delete data from the blob, and will therefore
- * change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_NOTFOUND, node does not have the named property
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_delprop(void *fdt, int nodeoffset, const char *name);
-
-/**
- * fdt_add_subnode_namelen - creates a new node based on substring
- * @fdt: pointer to the device tree blob
- * @parentoffset: structure block offset of a node
- * @name: name of the subnode to locate
- * @namelen: number of characters of name to consider
- *
- * Identical to fdt_add_subnode(), but use only the first namelen
- * characters of name as the name of the new node. This is useful for
- * creating subnodes based on a portion of a larger string, such as a
- * full path.
- */
-int fdt_add_subnode_namelen(void *fdt, int parentoffset,
- const char *name, int namelen);
-
-/**
- * fdt_add_subnode - creates a new node
- * @fdt: pointer to the device tree blob
- * @parentoffset: structure block offset of a node
- * @name: name of the subnode to locate
- *
- * fdt_add_subnode() creates a new node as a subnode of the node at
- * structure block offset parentoffset, with the given name (which
- * should include the unit address, if any).
- *
- * This function will insert data into the blob, and will therefore
- * change the offsets of some existing nodes.
-
- * returns:
- * structure block offset of the created nodeequested subnode (>=0), on success
- * -FDT_ERR_NOTFOUND, if the requested subnode does not exist
- * -FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
- * -FDT_ERR_EXISTS, if the node at parentoffset already has a subnode of
- * the given name
- * -FDT_ERR_NOSPACE, if there is insufficient free space in the
- * blob to contain the new node
- * -FDT_ERR_NOSPACE
- * -FDT_ERR_BADLAYOUT
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings.
- */
-int fdt_add_subnode(void *fdt, int parentoffset, const char *name);
-
-/**
- * fdt_del_node - delete a node (subtree)
- * @fdt: pointer to the device tree blob
- * @nodeoffset: offset of the node to nop
- *
- * fdt_del_node() will remove the given node, including all its
- * subnodes if any, from the blob.
- *
- * This function will delete data from the blob, and will therefore
- * change the offsets of some existing nodes.
- *
- * returns:
- * 0, on success
- * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
- * -FDT_ERR_BADLAYOUT,
- * -FDT_ERR_BADMAGIC,
- * -FDT_ERR_BADVERSION,
- * -FDT_ERR_BADSTATE,
- * -FDT_ERR_BADSTRUCTURE,
- * -FDT_ERR_TRUNCATED, standard meanings
- */
-int fdt_del_node(void *fdt, int nodeoffset);
-
-/**********************************************************************/
-/* Debugging / informational functions */
-/**********************************************************************/
-
-const char *fdt_strerror(int errval);
-
-#endif /* _LIBFDT_H */
+#ifndef _LIBFDT_H
+#define _LIBFDT_H
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <libfdt_env.h>
+#include <fdt.h>
+
+#define FDT_FIRST_SUPPORTED_VERSION 0x10
+#define FDT_LAST_SUPPORTED_VERSION 0x11
+
+/* Error codes: informative error codes */
+#define FDT_ERR_NOTFOUND 1
+ /* FDT_ERR_NOTFOUND: The requested node or property does not exist */
+#define FDT_ERR_EXISTS 2
+ /* FDT_ERR_EXISTS: Attemped to create a node or property which
+ * already exists */
+#define FDT_ERR_NOSPACE 3
+ /* FDT_ERR_NOSPACE: Operation needed to expand the device
+ * tree, but its buffer did not have sufficient space to
+ * contain the expanded tree. Use fdt_open_into() to move the
+ * device tree to a buffer with more space. */
+
+/* Error codes: codes for bad parameters */
+#define FDT_ERR_BADOFFSET 4
+ /* FDT_ERR_BADOFFSET: Function was passed a structure block
+ * offset which is out-of-bounds, or which points to an
+ * unsuitable part of the structure for the operation. */
+#define FDT_ERR_BADPATH 5
+ /* FDT_ERR_BADPATH: Function was passed a badly formatted path
+ * (e.g. missing a leading / for a function which requires an
+ * absolute path) */
+#define FDT_ERR_BADPHANDLE 6
+ /* FDT_ERR_BADPHANDLE: Function was passed an invalid phandle
+ * value. phandle values of 0 and -1 are not permitted. */
+#define FDT_ERR_BADSTATE 7
+ /* FDT_ERR_BADSTATE: Function was passed an incomplete device
+ * tree created by the sequential-write functions, which is
+ * not sufficiently complete for the requested operation. */
+
+/* Error codes: codes for bad device tree blobs */
+#define FDT_ERR_TRUNCATED 8
+ /* FDT_ERR_TRUNCATED: Structure block of the given device tree
+ * ends without an FDT_END tag. */
+#define FDT_ERR_BADMAGIC 9
+ /* FDT_ERR_BADMAGIC: Given "device tree" appears not to be a
+ * device tree at all - it is missing the flattened device
+ * tree magic number. */
+#define FDT_ERR_BADVERSION 10
+ /* FDT_ERR_BADVERSION: Given device tree has a version which
+ * can't be handled by the requested operation. For
+ * read-write functions, this may mean that fdt_open_into() is
+ * required to convert the tree to the expected version. */
+#define FDT_ERR_BADSTRUCTURE 11
+ /* FDT_ERR_BADSTRUCTURE: Given device tree has a corrupt
+ * structure block or other serious error (e.g. misnested
+ * nodes, or subnodes preceding properties). */
+#define FDT_ERR_BADLAYOUT 12
+ /* FDT_ERR_BADLAYOUT: For read-write functions, the given
+ * device tree has it's sub-blocks in an order that the
+ * function can't handle (memory reserve map, then structure,
+ * then strings). Use fdt_open_into() to reorganize the tree
+ * into a form suitable for the read-write operations. */
+
+/* "Can't happen" error indicating a bug in libfdt */
+#define FDT_ERR_INTERNAL 13
+ /* FDT_ERR_INTERNAL: libfdt has failed an internal assertion.
+ * Should never be returned, if it is, it indicates a bug in
+ * libfdt itself. */
+
+#define FDT_ERR_MAX 13
+
+/**********************************************************************/
+/* Low-level functions (you probably don't need these) */
+/**********************************************************************/
+
+const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int checklen);
+static inline void *fdt_offset_ptr_w(void *fdt, int offset, int checklen)
+{
+ return (void *)(uintptr_t)fdt_offset_ptr(fdt, offset, checklen);
+}
+
+uint32_t fdt_next_tag(const void *fdt, int offset, int *nextoffset);
+
+/**********************************************************************/
+/* Traversal functions */
+/**********************************************************************/
+
+int fdt_next_node(const void *fdt, int offset, int *depth);
+
+/**********************************************************************/
+/* General functions */
+/**********************************************************************/
+
+#define fdt_get_header(fdt, field) \
+ (fdt32_to_cpu(((const struct fdt_header *)(fdt))->field))
+#define fdt_magic(fdt) (fdt_get_header(fdt, magic))
+#define fdt_totalsize(fdt) (fdt_get_header(fdt, totalsize))
+#define fdt_off_dt_struct(fdt) (fdt_get_header(fdt, off_dt_struct))
+#define fdt_off_dt_strings(fdt) (fdt_get_header(fdt, off_dt_strings))
+#define fdt_off_mem_rsvmap(fdt) (fdt_get_header(fdt, off_mem_rsvmap))
+#define fdt_version(fdt) (fdt_get_header(fdt, version))
+#define fdt_last_comp_version(fdt) (fdt_get_header(fdt, last_comp_version))
+#define fdt_boot_cpuid_phys(fdt) (fdt_get_header(fdt, boot_cpuid_phys))
+#define fdt_size_dt_strings(fdt) (fdt_get_header(fdt, size_dt_strings))
+#define fdt_size_dt_struct(fdt) (fdt_get_header(fdt, size_dt_struct))
+
+#define __fdt_set_hdr(name) \
+ static inline void fdt_set_##name(void *fdt, uint32_t val) \
+ { \
+ struct fdt_header *fdth = (struct fdt_header*)fdt; \
+ fdth->name = cpu_to_fdt32(val); \
+ }
+__fdt_set_hdr(magic);
+__fdt_set_hdr(totalsize);
+__fdt_set_hdr(off_dt_struct);
+__fdt_set_hdr(off_dt_strings);
+__fdt_set_hdr(off_mem_rsvmap);
+__fdt_set_hdr(version);
+__fdt_set_hdr(last_comp_version);
+__fdt_set_hdr(boot_cpuid_phys);
+__fdt_set_hdr(size_dt_strings);
+__fdt_set_hdr(size_dt_struct);
+#undef __fdt_set_hdr
+
+/**
+ * fdt_check_header - sanity check a device tree or possible device tree
+ * @fdt: pointer to data which might be a flattened device tree
+ *
+ * fdt_check_header() checks that the given buffer contains what
+ * appears to be a flattened device tree with sane information in its
+ * header.
+ *
+ * returns:
+ * 0, if the buffer appears to contain a valid device tree
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE, standard meanings, as above
+ */
+int fdt_check_header(const void *fdt);
+
+/**
+ * fdt_move - move a device tree around in memory
+ * @fdt: pointer to the device tree to move
+ * @buf: pointer to memory where the device is to be moved
+ * @bufsize: size of the memory space at buf
+ *
+ * fdt_move() relocates, if possible, the device tree blob located at
+ * fdt to the buffer at buf of size bufsize. The buffer may overlap
+ * with the existing device tree blob at fdt. Therefore,
+ * fdt_move(fdt, fdt, fdt_totalsize(fdt))
+ * should always succeed.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, bufsize is insufficient to contain the device tree
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE, standard meanings
+ */
+int fdt_move(const void *fdt, void *buf, int bufsize);
+
+/**********************************************************************/
+/* Read-only functions */
+/**********************************************************************/
+
+/**
+ * fdt_string - retrieve a string from the strings block of a device tree
+ * @fdt: pointer to the device tree blob
+ * @stroffset: offset of the string within the strings block (native endian)
+ *
+ * fdt_string() retrieves a pointer to a single string from the
+ * strings block of the device tree blob at fdt.
+ *
+ * returns:
+ * a pointer to the string, on success
+ * NULL, if stroffset is out of bounds
+ */
+const char *fdt_string(const void *fdt, int stroffset);
+
+/**
+ * fdt_num_mem_rsv - retrieve the number of memory reserve map entries
+ * @fdt: pointer to the device tree blob
+ *
+ * Returns the number of entries in the device tree blob's memory
+ * reservation map. This does not include the terminating 0,0 entry
+ * or any other (0,0) entries reserved for expansion.
+ *
+ * returns:
+ * the number of entries
+ */
+int fdt_num_mem_rsv(const void *fdt);
+
+/**
+ * fdt_get_mem_rsv - retrieve one memory reserve map entry
+ * @fdt: pointer to the device tree blob
+ * @address, @size: pointers to 64-bit variables
+ *
+ * On success, *address and *size will contain the address and size of
+ * the n-th reserve map entry from the device tree blob, in
+ * native-endian format.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE, standard meanings
+ */
+int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);
+
+/**
+ * fdt_subnode_offset_namelen - find a subnode based on substring
+ * @fdt: pointer to the device tree blob
+ * @parentoffset: structure block offset of a node
+ * @name: name of the subnode to locate
+ * @namelen: number of characters of name to consider
+ *
+ * Identical to fdt_subnode_offset(), but only examine the first
+ * namelen characters of name for matching the subnode name. This is
+ * useful for finding subnodes based on a portion of a larger string,
+ * such as a full path.
+ */
+int fdt_subnode_offset_namelen(const void *fdt, int parentoffset,
+ const char *name, int namelen);
+/**
+ * fdt_subnode_offset - find a subnode of a given node
+ * @fdt: pointer to the device tree blob
+ * @parentoffset: structure block offset of a node
+ * @name: name of the subnode to locate
+ *
+ * fdt_subnode_offset() finds a subnode of the node at structure block
+ * offset parentoffset with the given name. name may include a unit
+ * address, in which case fdt_subnode_offset() will find the subnode
+ * with that unit address, or the unit address may be omitted, in
+ * which case fdt_subnode_offset() will find an arbitrary subnode
+ * whose name excluding unit address matches the given name.
+ *
+ * returns:
+ * structure block offset of the requested subnode (>=0), on success
+ * -FDT_ERR_NOTFOUND, if the requested subnode does not exist
+ * -FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings.
+ */
+int fdt_subnode_offset(const void *fdt, int parentoffset, const char *name);
+
+/**
+ * fdt_path_offset - find a tree node by its full path
+ * @fdt: pointer to the device tree blob
+ * @path: full path of the node to locate
+ *
+ * fdt_path_offset() finds a node of a given path in the device tree.
+ * Each path component may omit the unit address portion, but the
+ * results of this are undefined if any such path component is
+ * ambiguous (that is if there are multiple nodes at the relevant
+ * level matching the given component, differentiated only by unit
+ * address).
+ *
+ * returns:
+ * structure block offset of the node with the requested path (>=0), on success
+ * -FDT_ERR_BADPATH, given path does not begin with '/' or is invalid
+ * -FDT_ERR_NOTFOUND, if the requested node does not exist
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings.
+ */
+int fdt_path_offset(const void *fdt, const char *path);
+
+/**
+ * fdt_get_name - retrieve the name of a given node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: structure block offset of the starting node
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * fdt_get_name() retrieves the name (including unit address) of the
+ * device tree node at structure block offset nodeoffset. If lenp is
+ * non-NULL, the length of this name is also returned, in the integer
+ * pointed to by lenp.
+ *
+ * returns:
+ * pointer to the node's name, on success
+ * If lenp is non-NULL, *lenp contains the length of that name (>=0)
+ * NULL, on error
+ * if lenp is non-NULL *lenp contains an error code (<0):
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE, standard meanings
+ */
+const char *fdt_get_name(const void *fdt, int nodeoffset, int *lenp);
+
+/**
+ * fdt_first_property_offset - find the offset of a node's first property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: structure block offset of a node
+ *
+ * fdt_first_property_offset() finds the first property of the node at
+ * the given structure block offset.
+ *
+ * returns:
+ * structure block offset of the property (>=0), on success
+ * -FDT_ERR_NOTFOUND, if the requested node has no properties
+ * -FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings.
+ */
+int fdt_first_property_offset(const void *fdt, int nodeoffset);
+
+/**
+ * fdt_next_property_offset - step through a node's properties
+ * @fdt: pointer to the device tree blob
+ * @offset: structure block offset of a property
+ *
+ * fdt_next_property_offset() finds the property immediately after the
+ * one at the given structure block offset. This will be a property
+ * of the same node as the given property.
+ *
+ * returns:
+ * structure block offset of the next property (>=0), on success
+ * -FDT_ERR_NOTFOUND, if the given property is the last in its node
+ * -FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_PROP tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings.
+ */
+int fdt_next_property_offset(const void *fdt, int offset);
+
+/**
+ * fdt_get_property_by_offset - retrieve the property at a given offset
+ * @fdt: pointer to the device tree blob
+ * @offset: offset of the property to retrieve
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * fdt_get_property_by_offset() retrieves a pointer to the
+ * fdt_property structure within the device tree blob at the given
+ * offset. If lenp is non-NULL, the length of the property value is
+ * also returned, in the integer pointed to by lenp.
+ *
+ * returns:
+ * pointer to the structure representing the property
+ * if lenp is non-NULL, *lenp contains the length of the property
+ * value (>=0)
+ * NULL, on error
+ * if lenp is non-NULL, *lenp contains an error code (<0):
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+const struct fdt_property *fdt_get_property_by_offset(const void *fdt,
+ int offset,
+ int *lenp);
+
+/**
+ * fdt_get_property_namelen - find a property based on substring
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to find
+ * @name: name of the property to find
+ * @namelen: number of characters of name to consider
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * Identical to fdt_get_property_namelen(), but only examine the first
+ * namelen characters of name for matching the property name.
+ */
+const struct fdt_property *fdt_get_property_namelen(const void *fdt,
+ int nodeoffset,
+ const char *name,
+ int namelen, int *lenp);
+
+/**
+ * fdt_get_property - find a given property in a given node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to find
+ * @name: name of the property to find
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * fdt_get_property() retrieves a pointer to the fdt_property
+ * structure within the device tree blob corresponding to the property
+ * named 'name' of the node at offset nodeoffset. If lenp is
+ * non-NULL, the length of the property value is also returned, in the
+ * integer pointed to by lenp.
+ *
+ * returns:
+ * pointer to the structure representing the property
+ * if lenp is non-NULL, *lenp contains the length of the property
+ * value (>=0)
+ * NULL, on error
+ * if lenp is non-NULL, *lenp contains an error code (<0):
+ * -FDT_ERR_NOTFOUND, node does not have named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+const struct fdt_property *fdt_get_property(const void *fdt, int nodeoffset,
+ const char *name, int *lenp);
+static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
+ const char *name,
+ int *lenp)
+{
+ return (struct fdt_property *)(uintptr_t)
+ fdt_get_property(fdt, nodeoffset, name, lenp);
+}
+
+/**
+ * fdt_getprop_by_offset - retrieve the value of a property at a given offset
+ * @fdt: pointer to the device tree blob
+ * @ffset: offset of the property to read
+ * @namep: pointer to a string variable (will be overwritten) or NULL
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * fdt_getprop_by_offset() retrieves a pointer to the value of the
+ * property at structure block offset 'offset' (this will be a pointer
+ * to within the device blob itself, not a copy of the value). If
+ * lenp is non-NULL, the length of the property value is also
+ * returned, in the integer pointed to by lenp. If namep is non-NULL,
+ * the property's namne will also be returned in the char * pointed to
+ * by namep (this will be a pointer to within the device tree's string
+ * block, not a new copy of the name).
+ *
+ * returns:
+ * pointer to the property's value
+ * if lenp is non-NULL, *lenp contains the length of the property
+ * value (>=0)
+ * if namep is non-NULL *namep contiains a pointer to the property
+ * name.
+ * NULL, on error
+ * if lenp is non-NULL, *lenp contains an error code (<0):
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+const void *fdt_getprop_by_offset(const void *fdt, int offset,
+ const char **namep, int *lenp);
+
+/**
+ * fdt_getprop_namelen - get property value based on substring
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to find
+ * @name: name of the property to find
+ * @namelen: number of characters of name to consider
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * Identical to fdt_getprop(), but only examine the first namelen
+ * characters of name for matching the property name.
+ */
+const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
+ const char *name, int namelen, int *lenp);
+
+/**
+ * fdt_getprop - retrieve the value of a given property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to find
+ * @name: name of the property to find
+ * @lenp: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * fdt_getprop() retrieves a pointer to the value of the property
+ * named 'name' of the node at offset nodeoffset (this will be a
+ * pointer to within the device blob itself, not a copy of the value).
+ * If lenp is non-NULL, the length of the property value is also
+ * returned, in the integer pointed to by lenp.
+ *
+ * returns:
+ * pointer to the property's value
+ * if lenp is non-NULL, *lenp contains the length of the property
+ * value (>=0)
+ * NULL, on error
+ * if lenp is non-NULL, *lenp contains an error code (<0):
+ * -FDT_ERR_NOTFOUND, node does not have named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+const void *fdt_getprop(const void *fdt, int nodeoffset,
+ const char *name, int *lenp);
+static inline void *fdt_getprop_w(void *fdt, int nodeoffset,
+ const char *name, int *lenp)
+{
+ return (void *)(uintptr_t)fdt_getprop(fdt, nodeoffset, name, lenp);
+}
+
+/**
+ * fdt_get_phandle - retrieve the phandle of a given node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: structure block offset of the node
+ *
+ * fdt_get_phandle() retrieves the phandle of the device tree node at
+ * structure block offset nodeoffset.
+ *
+ * returns:
+ * the phandle of the node at nodeoffset, on success (!= 0, != -1)
+ * 0, if the node has no phandle, or another error occurs
+ */
+uint32_t fdt_get_phandle(const void *fdt, int nodeoffset);
+
+/**
+ * fdt_get_alias_namelen - get alias based on substring
+ * @fdt: pointer to the device tree blob
+ * @name: name of the alias th look up
+ * @namelen: number of characters of name to consider
+ *
+ * Identical to fdt_get_alias(), but only examine the first namelen
+ * characters of name for matching the alias name.
+ */
+const char *fdt_get_alias_namelen(const void *fdt,
+ const char *name, int namelen);
+
+/**
+ * fdt_get_alias - retreive the path referenced by a given alias
+ * @fdt: pointer to the device tree blob
+ * @name: name of the alias th look up
+ *
+ * fdt_get_alias() retrieves the value of a given alias. That is, the
+ * value of the property named 'name' in the node /aliases.
+ *
+ * returns:
+ * a pointer to the expansion of the alias named 'name', of it exists
+ * NULL, if the given alias or the /aliases node does not exist
+ */
+const char *fdt_get_alias(const void *fdt, const char *name);
+
+/**
+ * fdt_get_path - determine the full path of a node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose path to find
+ * @buf: character buffer to contain the returned path (will be overwritten)
+ * @buflen: size of the character buffer at buf
+ *
+ * fdt_get_path() computes the full path of the node at offset
+ * nodeoffset, and records that path in the buffer at buf.
+ *
+ * NOTE: This function is expensive, as it must scan the device tree
+ * structure from the start to nodeoffset.
+ *
+ * returns:
+ * 0, on success
+ * buf contains the absolute path of the node at
+ * nodeoffset, as a NUL-terminated string.
+ * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ * -FDT_ERR_NOSPACE, the path of the given node is longer than (bufsize-1)
+ * characters and will not fit in the given buffer.
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);
+
+/**
+ * fdt_supernode_atdepth_offset - find a specific ancestor of a node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose parent to find
+ * @supernodedepth: depth of the ancestor to find
+ * @nodedepth: pointer to an integer variable (will be overwritten) or NULL
+ *
+ * fdt_supernode_atdepth_offset() finds an ancestor of the given node
+ * at a specific depth from the root (where the root itself has depth
+ * 0, its immediate subnodes depth 1 and so forth). So
+ * fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
+ * will always return 0, the offset of the root node. If the node at
+ * nodeoffset has depth D, then:
+ * fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
+ * will return nodeoffset itself.
+ *
+ * NOTE: This function is expensive, as it must scan the device tree
+ * structure from the start to nodeoffset.
+ *
+ * returns:
+
+ * structure block offset of the node at node offset's ancestor
+ * of depth supernodedepth (>=0), on success
+ * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+* -FDT_ERR_NOTFOUND, supernodedepth was greater than the depth of nodeoffset
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
+ int supernodedepth, int *nodedepth);
+
+/**
+ * fdt_node_depth - find the depth of a given node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose parent to find
+ *
+ * fdt_node_depth() finds the depth of a given node. The root node
+ * has depth 0, its immediate subnodes depth 1 and so forth.
+ *
+ * NOTE: This function is expensive, as it must scan the device tree
+ * structure from the start to nodeoffset.
+ *
+ * returns:
+ * depth of the node at nodeoffset (>=0), on success
+ * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_node_depth(const void *fdt, int nodeoffset);
+
+/**
+ * fdt_parent_offset - find the parent of a given node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose parent to find
+ *
+ * fdt_parent_offset() locates the parent node of a given node (that
+ * is, it finds the offset of the node which contains the node at
+ * nodeoffset as a subnode).
+ *
+ * NOTE: This function is expensive, as it must scan the device tree
+ * structure from the start to nodeoffset, *twice*.
+ *
+ * returns:
+ * structure block offset of the parent of the node at nodeoffset
+ * (>=0), on success
+ * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_parent_offset(const void *fdt, int nodeoffset);
+
+/**
+ * fdt_node_offset_by_prop_value - find nodes with a given property value
+ * @fdt: pointer to the device tree blob
+ * @startoffset: only find nodes after this offset
+ * @propname: property name to check
+ * @propval: property value to search for
+ * @proplen: length of the value in propval
+ *
+ * fdt_node_offset_by_prop_value() returns the offset of the first
+ * node after startoffset, which has a property named propname whose
+ * value is of length proplen and has value equal to propval; or if
+ * startoffset is -1, the very first such node in the tree.
+ *
+ * To iterate through all nodes matching the criterion, the following
+ * idiom can be used:
+ * offset = fdt_node_offset_by_prop_value(fdt, -1, propname,
+ * propval, proplen);
+ * while (offset != -FDT_ERR_NOTFOUND) {
+ * // other code here
+ * offset = fdt_node_offset_by_prop_value(fdt, offset, propname,
+ * propval, proplen);
+ * }
+ *
+ * Note the -1 in the first call to the function, if 0 is used here
+ * instead, the function will never locate the root node, even if it
+ * matches the criterion.
+ *
+ * returns:
+ * structure block offset of the located node (>= 0, >startoffset),
+ * on success
+ * -FDT_ERR_NOTFOUND, no node matching the criterion exists in the
+ * tree after startoffset
+ * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_node_offset_by_prop_value(const void *fdt, int startoffset,
+ const char *propname,
+ const void *propval, int proplen);
+
+/**
+ * fdt_node_offset_by_phandle - find the node with a given phandle
+ * @fdt: pointer to the device tree blob
+ * @phandle: phandle value
+ *
+ * fdt_node_offset_by_phandle() returns the offset of the node
+ * which has the given phandle value. If there is more than one node
+ * in the tree with the given phandle (an invalid tree), results are
+ * undefined.
+ *
+ * returns:
+ * structure block offset of the located node (>= 0), on success
+ * -FDT_ERR_NOTFOUND, no node with that phandle exists
+ * -FDT_ERR_BADPHANDLE, given phandle value was invalid (0 or -1)
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle);
+
+/**
+ * fdt_node_check_compatible: check a node's compatible property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of a tree node
+ * @compatible: string to match against
+ *
+ *
+ * fdt_node_check_compatible() returns 0 if the given node contains a
+ * 'compatible' property with the given string as one of its elements,
+ * it returns non-zero otherwise, or on error.
+ *
+ * returns:
+ * 0, if the node has a 'compatible' property listing the given string
+ * 1, if the node has a 'compatible' property, but it does not list
+ * the given string
+ * -FDT_ERR_NOTFOUND, if the given node has no 'compatible' property
+ * -FDT_ERR_BADOFFSET, if nodeoffset does not refer to a BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_node_check_compatible(const void *fdt, int nodeoffset,
+ const char *compatible);
+
+/**
+ * fdt_node_offset_by_compatible - find nodes with a given 'compatible' value
+ * @fdt: pointer to the device tree blob
+ * @startoffset: only find nodes after this offset
+ * @compatible: 'compatible' string to match against
+ *
+ * fdt_node_offset_by_compatible() returns the offset of the first
+ * node after startoffset, which has a 'compatible' property which
+ * lists the given compatible string; or if startoffset is -1, the
+ * very first such node in the tree.
+ *
+ * To iterate through all nodes matching the criterion, the following
+ * idiom can be used:
+ * offset = fdt_node_offset_by_compatible(fdt, -1, compatible);
+ * while (offset != -FDT_ERR_NOTFOUND) {
+ * // other code here
+ * offset = fdt_node_offset_by_compatible(fdt, offset, compatible);
+ * }
+ *
+ * Note the -1 in the first call to the function, if 0 is used here
+ * instead, the function will never locate the root node, even if it
+ * matches the criterion.
+ *
+ * returns:
+ * structure block offset of the located node (>= 0, >startoffset),
+ * on success
+ * -FDT_ERR_NOTFOUND, no node matching the criterion exists in the
+ * tree after startoffset
+ * -FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE, standard meanings
+ */
+int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
+ const char *compatible);
+
+/**********************************************************************/
+/* Write-in-place functions */
+/**********************************************************************/
+
+/**
+ * fdt_setprop_inplace - change a property's value, but not its size
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: pointer to data to replace the property value with
+ * @len: length of the property value
+ *
+ * fdt_setprop_inplace() replaces the value of a given property with
+ * the data in val, of length len. This function cannot change the
+ * size of a property, and so will only work if len is equal to the
+ * current length of the property.
+ *
+ * This function will alter only the bytes in the blob which contain
+ * the given property value, and will not alter or move any other part
+ * of the tree.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, if len is not equal to the property's current length
+ * -FDT_ERR_NOTFOUND, node does not have the named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
+ const void *val, int len);
+
+/**
+ * fdt_setprop_inplace_u32 - change the value of a 32-bit integer property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: 32-bit integer value to replace the property with
+ *
+ * fdt_setprop_inplace_u32() replaces the value of a given property
+ * with the 32-bit integer value in val, converting val to big-endian
+ * if necessary. This function cannot change the size of a property,
+ * and so will only work if the property already exists and has length
+ * 4.
+ *
+ * This function will alter only the bytes in the blob which contain
+ * the given property value, and will not alter or move any other part
+ * of the tree.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, if the property's length is not equal to 4
+ * -FDT_ERR_NOTFOUND, node does not have the named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+static inline int fdt_setprop_inplace_u32(void *fdt, int nodeoffset,
+ const char *name, uint32_t val)
+{
+ val = cpu_to_fdt32(val);
+ return fdt_setprop_inplace(fdt, nodeoffset, name, &val, sizeof(val));
+}
+
+/**
+ * fdt_setprop_inplace_u64 - change the value of a 64-bit integer property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: 64-bit integer value to replace the property with
+ *
+ * fdt_setprop_inplace_u64() replaces the value of a given property
+ * with the 64-bit integer value in val, converting val to big-endian
+ * if necessary. This function cannot change the size of a property,
+ * and so will only work if the property already exists and has length
+ * 8.
+ *
+ * This function will alter only the bytes in the blob which contain
+ * the given property value, and will not alter or move any other part
+ * of the tree.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, if the property's length is not equal to 8
+ * -FDT_ERR_NOTFOUND, node does not have the named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+static inline int fdt_setprop_inplace_u64(void *fdt, int nodeoffset,
+ const char *name, uint64_t val)
+{
+ val = cpu_to_fdt64(val);
+ return fdt_setprop_inplace(fdt, nodeoffset, name, &val, sizeof(val));
+}
+
+/**
+ * fdt_setprop_inplace_cell - change the value of a single-cell property
+ *
+ * This is an alternative name for fdt_setprop_inplace_u32()
+ */
+static inline int fdt_setprop_inplace_cell(void *fdt, int nodeoffset,
+ const char *name, uint32_t val)
+{
+ return fdt_setprop_inplace_u32(fdt, nodeoffset, name, val);
+}
+
+/**
+ * fdt_nop_property - replace a property with nop tags
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to nop
+ * @name: name of the property to nop
+ *
+ * fdt_nop_property() will replace a given property's representation
+ * in the blob with FDT_NOP tags, effectively removing it from the
+ * tree.
+ *
+ * This function will alter only the bytes in the blob which contain
+ * the property, and will not alter or move any other part of the
+ * tree.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOTFOUND, node does not have the named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_nop_property(void *fdt, int nodeoffset, const char *name);
+
+/**
+ * fdt_nop_node - replace a node (subtree) with nop tags
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node to nop
+ *
+ * fdt_nop_node() will replace a given node's representation in the
+ * blob, including all its subnodes, if any, with FDT_NOP tags,
+ * effectively removing it from the tree.
+ *
+ * This function will alter only the bytes in the blob which contain
+ * the node and its properties and subnodes, and will not alter or
+ * move any other part of the tree.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_nop_node(void *fdt, int nodeoffset);
+
+/**********************************************************************/
+/* Sequential write functions */
+/**********************************************************************/
+
+int fdt_create(void *buf, int bufsize);
+int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size);
+int fdt_finish_reservemap(void *fdt);
+int fdt_begin_node(void *fdt, const char *name);
+int fdt_property(void *fdt, const char *name, const void *val, int len);
+static inline int fdt_property_u32(void *fdt, const char *name, uint32_t val)
+{
+ val = cpu_to_fdt32(val);
+ return fdt_property(fdt, name, &val, sizeof(val));
+}
+static inline int fdt_property_u64(void *fdt, const char *name, uint64_t val)
+{
+ val = cpu_to_fdt64(val);
+ return fdt_property(fdt, name, &val, sizeof(val));
+}
+static inline int fdt_property_cell(void *fdt, const char *name, uint32_t val)
+{
+ return fdt_property_u32(fdt, name, val);
+}
+#define fdt_property_string(fdt, name, str) \
+ fdt_property(fdt, name, str, strlen(str)+1)
+int fdt_end_node(void *fdt);
+int fdt_finish(void *fdt);
+
+/**********************************************************************/
+/* Read-write functions */
+/**********************************************************************/
+
+int fdt_create_empty_tree(void *buf, int bufsize);
+int fdt_open_into(const void *fdt, void *buf, int bufsize);
+int fdt_pack(void *fdt);
+
+/**
+ * fdt_add_mem_rsv - add one memory reserve map entry
+ * @fdt: pointer to the device tree blob
+ * @address, @size: 64-bit values (native endian)
+ *
+ * Adds a reserve map entry to the given blob reserving a region at
+ * address address of length size.
+ *
+ * This function will insert data into the reserve map and will
+ * therefore change the indexes of some entries in the table.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new reservation entry
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size);
+
+/**
+ * fdt_del_mem_rsv - remove a memory reserve map entry
+ * @fdt: pointer to the device tree blob
+ * @n: entry to remove
+ *
+ * fdt_del_mem_rsv() removes the n-th memory reserve map entry from
+ * the blob.
+ *
+ * This function will delete data from the reservation table and will
+ * therefore change the indexes of some entries in the table.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOTFOUND, there is no entry of the given index (i.e. there
+ * are less than n+1 reserve map entries)
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_del_mem_rsv(void *fdt, int n);
+
+/**
+ * fdt_set_name - change the name of a given node
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: structure block offset of a node
+ * @name: name to give the node
+ *
+ * fdt_set_name() replaces the name (including unit address, if any)
+ * of the given node with the given string. NOTE: this function can't
+ * efficiently check if the new name is unique amongst the given
+ * node's siblings; results are undefined if this function is invoked
+ * with a name equal to one of the given node's siblings.
+ *
+ * This function may insert or delete data from the blob, and will
+ * therefore change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob
+ * to contain the new name
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE, standard meanings
+ */
+int fdt_set_name(void *fdt, int nodeoffset, const char *name);
+
+/**
+ * fdt_setprop - create or change a property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: pointer to data to set the property value to
+ * @len: length of the property value
+ *
+ * fdt_setprop() sets the value of the named property in the given
+ * node to the given value and length, creating the property if it
+ * does not already exist.
+ *
+ * This function may insert or delete data from the blob, and will
+ * therefore change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_setprop(void *fdt, int nodeoffset, const char *name,
+ const void *val, int len);
+
+/**
+ * fdt_setprop_u32 - set a property to a 32-bit integer
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: 32-bit integer value for the property (native endian)
+ *
+ * fdt_setprop_u32() sets the value of the named property in the given
+ * node to the given 32-bit integer value (converting to big-endian if
+ * necessary), or creates a new property with that value if it does
+ * not already exist.
+ *
+ * This function may insert or delete data from the blob, and will
+ * therefore change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+static inline int fdt_setprop_u32(void *fdt, int nodeoffset, const char *name,
+ uint32_t val)
+{
+ val = cpu_to_fdt32(val);
+ return fdt_setprop(fdt, nodeoffset, name, &val, sizeof(val));
+}
+
+/**
+ * fdt_setprop_u64 - set a property to a 64-bit integer
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: 64-bit integer value for the property (native endian)
+ *
+ * fdt_setprop_u64() sets the value of the named property in the given
+ * node to the given 64-bit integer value (converting to big-endian if
+ * necessary), or creates a new property with that value if it does
+ * not already exist.
+ *
+ * This function may insert or delete data from the blob, and will
+ * therefore change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+static inline int fdt_setprop_u64(void *fdt, int nodeoffset, const char *name,
+ uint64_t val)
+{
+ val = cpu_to_fdt64(val);
+ return fdt_setprop(fdt, nodeoffset, name, &val, sizeof(val));
+}
+
+/**
+ * fdt_setprop_cell - set a property to a single cell value
+ *
+ * This is an alternative name for fdt_setprop_u32()
+ */
+static inline int fdt_setprop_cell(void *fdt, int nodeoffset, const char *name,
+ uint32_t val)
+{
+ return fdt_setprop_u32(fdt, nodeoffset, name, val);
+}
+
+/**
+ * fdt_setprop_string - set a property to a string value
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @str: string value for the property
+ *
+ * fdt_setprop_string() sets the value of the named property in the
+ * given node to the given string value (using the length of the
+ * string to determine the new length of the property), or creates a
+ * new property with that value if it does not already exist.
+ *
+ * This function may insert or delete data from the blob, and will
+ * therefore change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+#define fdt_setprop_string(fdt, nodeoffset, name, str) \
+ fdt_setprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)
+
+/**
+ * fdt_appendprop - append to or create a property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to append to
+ * @val: pointer to data to append to the property value
+ * @len: length of the data to append to the property value
+ *
+ * fdt_appendprop() appends the value to the named property in the
+ * given node, creating the property if it does not already exist.
+ *
+ * This function may insert data into the blob, and will therefore
+ * change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
+ const void *val, int len);
+
+/**
+ * fdt_appendprop_u32 - append a 32-bit integer value to a property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: 32-bit integer value to append to the property (native endian)
+ *
+ * fdt_appendprop_u32() appends the given 32-bit integer value
+ * (converting to big-endian if necessary) to the value of the named
+ * property in the given node, or creates a new property with that
+ * value if it does not already exist.
+ *
+ * This function may insert data into the blob, and will therefore
+ * change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+static inline int fdt_appendprop_u32(void *fdt, int nodeoffset,
+ const char *name, uint32_t val)
+{
+ val = cpu_to_fdt32(val);
+ return fdt_appendprop(fdt, nodeoffset, name, &val, sizeof(val));
+}
+
+/**
+ * fdt_appendprop_u64 - append a 64-bit integer value to a property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @val: 64-bit integer value to append to the property (native endian)
+ *
+ * fdt_appendprop_u64() appends the given 64-bit integer value
+ * (converting to big-endian if necessary) to the value of the named
+ * property in the given node, or creates a new property with that
+ * value if it does not already exist.
+ *
+ * This function may insert data into the blob, and will therefore
+ * change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+static inline int fdt_appendprop_u64(void *fdt, int nodeoffset,
+ const char *name, uint64_t val)
+{
+ val = cpu_to_fdt64(val);
+ return fdt_appendprop(fdt, nodeoffset, name, &val, sizeof(val));
+}
+
+/**
+ * fdt_appendprop_cell - append a single cell value to a property
+ *
+ * This is an alternative name for fdt_appendprop_u32()
+ */
+static inline int fdt_appendprop_cell(void *fdt, int nodeoffset,
+ const char *name, uint32_t val)
+{
+ return fdt_appendprop_u32(fdt, nodeoffset, name, val);
+}
+
+/**
+ * fdt_appendprop_string - append a string to a property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to change
+ * @name: name of the property to change
+ * @str: string value to append to the property
+ *
+ * fdt_appendprop_string() appends the given string to the value of
+ * the named property in the given node, or creates a new property
+ * with that value if it does not already exist.
+ *
+ * This function may insert data into the blob, and will therefore
+ * change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOSPACE, there is insufficient free space in the blob to
+ * contain the new property value
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+#define fdt_appendprop_string(fdt, nodeoffset, name, str) \
+ fdt_appendprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)
+
+/**
+ * fdt_delprop - delete a property
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node whose property to nop
+ * @name: name of the property to nop
+ *
+ * fdt_del_property() will delete the given property.
+ *
+ * This function will delete data from the blob, and will therefore
+ * change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_NOTFOUND, node does not have the named property
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_delprop(void *fdt, int nodeoffset, const char *name);
+
+/**
+ * fdt_add_subnode_namelen - creates a new node based on substring
+ * @fdt: pointer to the device tree blob
+ * @parentoffset: structure block offset of a node
+ * @name: name of the subnode to locate
+ * @namelen: number of characters of name to consider
+ *
+ * Identical to fdt_add_subnode(), but use only the first namelen
+ * characters of name as the name of the new node. This is useful for
+ * creating subnodes based on a portion of a larger string, such as a
+ * full path.
+ */
+int fdt_add_subnode_namelen(void *fdt, int parentoffset,
+ const char *name, int namelen);
+
+/**
+ * fdt_add_subnode - creates a new node
+ * @fdt: pointer to the device tree blob
+ * @parentoffset: structure block offset of a node
+ * @name: name of the subnode to locate
+ *
+ * fdt_add_subnode() creates a new node as a subnode of the node at
+ * structure block offset parentoffset, with the given name (which
+ * should include the unit address, if any).
+ *
+ * This function will insert data into the blob, and will therefore
+ * change the offsets of some existing nodes.
+
+ * returns:
+ * structure block offset of the created nodeequested subnode (>=0), on success
+ * -FDT_ERR_NOTFOUND, if the requested subnode does not exist
+ * -FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
+ * -FDT_ERR_EXISTS, if the node at parentoffset already has a subnode of
+ * the given name
+ * -FDT_ERR_NOSPACE, if there is insufficient free space in the
+ * blob to contain the new node
+ * -FDT_ERR_NOSPACE
+ * -FDT_ERR_BADLAYOUT
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings.
+ */
+int fdt_add_subnode(void *fdt, int parentoffset, const char *name);
+
+/**
+ * fdt_del_node - delete a node (subtree)
+ * @fdt: pointer to the device tree blob
+ * @nodeoffset: offset of the node to nop
+ *
+ * fdt_del_node() will remove the given node, including all its
+ * subnodes if any, from the blob.
+ *
+ * This function will delete data from the blob, and will therefore
+ * change the offsets of some existing nodes.
+ *
+ * returns:
+ * 0, on success
+ * -FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
+ * -FDT_ERR_BADLAYOUT,
+ * -FDT_ERR_BADMAGIC,
+ * -FDT_ERR_BADVERSION,
+ * -FDT_ERR_BADSTATE,
+ * -FDT_ERR_BADSTRUCTURE,
+ * -FDT_ERR_TRUNCATED, standard meanings
+ */
+int fdt_del_node(void *fdt, int nodeoffset);
+
+/**********************************************************************/
+/* Debugging / informational functions */
+/**********************************************************************/
+
+const char *fdt_strerror(int errval);
+
+#endif /* _LIBFDT_H */
diff --git a/EmbeddedPkg/Include/libfdt_env.h b/EmbeddedPkg/Include/libfdt_env.h
index d35b8692c..6cc311fe7 100644
--- a/EmbeddedPkg/Include/libfdt_env.h
+++ b/EmbeddedPkg/Include/libfdt_env.h
@@ -1,77 +1,77 @@
-/** @file
-*
-* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef _LIBFDT_ENV_H
-#define _LIBFDT_ENV_H
-
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-
-typedef UINT8 uint8_t;
-typedef UINT16 uint16_t;
-typedef UINT32 uint32_t;
-typedef UINT64 uint64_t;
-typedef UINTN uintptr_t;
-typedef UINTN size_t;
-
-static inline uint16_t fdt16_to_cpu(uint16_t x)
-{
- return SwapBytes16 (x);
-}
-#define cpu_to_fdt16(x) fdt16_to_cpu(x)
-
-static inline uint32_t fdt32_to_cpu(uint32_t x)
-{
- return SwapBytes32 (x);
-}
-#define cpu_to_fdt32(x) fdt32_to_cpu(x)
-
-static inline uint64_t fdt64_to_cpu(uint64_t x)
-{
- return SwapBytes64 (x);
-}
-#define cpu_to_fdt64(x) fdt64_to_cpu(x)
-
-static inline void* memcpy(void* dest, const void* src, size_t len) {
- return CopyMem (dest, src, len);
-}
-
-static inline void *memmove(void *dest, const void *src, size_t n) {
- return CopyMem (dest, src, n);
-}
-
-static inline void *memset(void *s, int c, size_t n) {
- return SetMem (s, n, c);
-}
-
-static inline int memcmp(const void* dest, const void* src, int len) {
- return CompareMem (dest, src, len);
-}
-
-static inline void *memchr(const void *s, int c, size_t n) {
- return ScanMem8 (s, n, c);
-}
-
-static inline size_t strlen (const char* str) {
- return AsciiStrLen (str);
-}
-
-static inline char *strchr(const char *s, int c) {
- char pattern[2];
- pattern[0] = c;
- pattern[1] = 0;
- return AsciiStrStr (s, pattern);
-}
-
-#endif /* _LIBFDT_ENV_H */
+/** @file
+*
+* Copyright (c) 2011-2012, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef _LIBFDT_ENV_H
+#define _LIBFDT_ENV_H
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+
+typedef UINT8 uint8_t;
+typedef UINT16 uint16_t;
+typedef UINT32 uint32_t;
+typedef UINT64 uint64_t;
+typedef UINTN uintptr_t;
+typedef UINTN size_t;
+
+static inline uint16_t fdt16_to_cpu(uint16_t x)
+{
+ return SwapBytes16 (x);
+}
+#define cpu_to_fdt16(x) fdt16_to_cpu(x)
+
+static inline uint32_t fdt32_to_cpu(uint32_t x)
+{
+ return SwapBytes32 (x);
+}
+#define cpu_to_fdt32(x) fdt32_to_cpu(x)
+
+static inline uint64_t fdt64_to_cpu(uint64_t x)
+{
+ return SwapBytes64 (x);
+}
+#define cpu_to_fdt64(x) fdt64_to_cpu(x)
+
+static inline void* memcpy(void* dest, const void* src, size_t len) {
+ return CopyMem (dest, src, len);
+}
+
+static inline void *memmove(void *dest, const void *src, size_t n) {
+ return CopyMem (dest, src, n);
+}
+
+static inline void *memset(void *s, int c, size_t n) {
+ return SetMem (s, n, c);
+}
+
+static inline int memcmp(const void* dest, const void* src, int len) {
+ return CompareMem (dest, src, len);
+}
+
+static inline void *memchr(const void *s, int c, size_t n) {
+ return ScanMem8 (s, n, c);
+}
+
+static inline size_t strlen (const char* str) {
+ return AsciiStrLen (str);
+}
+
+static inline char *strchr(const char *s, int c) {
+ char pattern[2];
+ pattern[0] = c;
+ pattern[1] = 0;
+ return AsciiStrStr (s, pattern);
+}
+
+#endif /* _LIBFDT_ENV_H */
diff --git a/EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLib.c b/EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLib.c
index 7ee5609c5..7fab09bad 100755
--- a/EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLib.c
+++ b/EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLib.c
@@ -61,4 +61,4 @@ DebugAgentTimerEndOfInterrupt (
{
}
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf b/EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
index 1429c37f2..03258751c 100644
--- a/EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
+++ b/EmbeddedPkg/Library/EblAddExternalCommandLib/EblAddExternalCommandLib.inf
@@ -45,4 +45,4 @@
gEfiEblAddCommandProtocolGuid
[Guids]
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf b/EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
index 3fd8e92dc..52e343997 100644
--- a/EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
+++ b/EmbeddedPkg/Library/EblCmdLibNull/EblCmdLibNull.inf
@@ -41,4 +41,4 @@
[Protocols]
[Guids]
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.c b/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.c
index 0edd5d018..3b0f6a1c7 100644
--- a/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.c
+++ b/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.c
@@ -1,173 +1,173 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Uefi.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DebugLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-
-#include <Protocol/SimpleNetwork.h>
-#include <Protocol/PxeBaseCode.h>
-
-
-BOOLEAN gUseIpv6 = FALSE;
-
-EFI_STATUS
-EFIAPI
-EblGetCurrentIpAddress (
- IN OUT EFI_IP_ADDRESS *Ip
- )
-{
- EFI_STATUS Status;
- EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
-
- Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Status = Pxe->Start (Pxe, gUseIpv6);
- if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
- return Status;
- }
-
- CopyMem (Ip, &Pxe->Mode->StationIp, sizeof (EFI_IP_ADDRESS));
-
- return EFI_SUCCESS;
-}
-
-
-EFI_STATUS
-EFIAPI
-EblGetCurrentMacAddress (
- IN OUT EFI_MAC_ADDRESS *Mac
- )
-{
- EFI_STATUS Status;
- EFI_SIMPLE_NETWORK_PROTOCOL *SimpleNet;
-
- Status = gBS->LocateProtocol (&gEfiSimpleNetworkProtocolGuid, NULL, (VOID **)&SimpleNet);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- CopyMem (Mac, SimpleNet->Mode->CurrentAddress.Addr, sizeof (EFI_MAC_ADDRESS));
- return Status;
-}
-
-
-CHAR8 *
-EFIAPI
-EblLoadFileBootTypeString (
- IN EFI_HANDLE Handle
- )
-{
- EFI_STATUS Status;
- VOID *NullPtr;
-
- Status = gBS->HandleProtocol (Handle, &gEfiPxeBaseCodeProtocolGuid, &NullPtr);
- if (!EFI_ERROR (Status)) {
- return "EFI PXE Network Boot";
- }
-
- return "";
-}
-
-EFI_STATUS
-EFIAPI
-EblPerformDHCP (
- IN BOOLEAN SortOffers
- )
-{
- EFI_STATUS Status;
- EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
-
- Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Status = Pxe->Start (Pxe, gUseIpv6);
- if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
- return Status;
- }
-
- Status = Pxe->Dhcp(Pxe, TRUE);
- return Status;
-}
-
-
-EFI_STATUS
-EFIAPI
-EblSetStationIp (
- IN EFI_IP_ADDRESS *NewStationIp, OPTIONAL
- IN EFI_IP_ADDRESS *NewSubnetMask OPTIONAL
- )
-{
- EFI_STATUS Status;
- EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
-
- Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Status = Pxe->Start (Pxe, gUseIpv6);
- if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
- return Status;
- }
-
- Status = Pxe->SetStationIp (Pxe, NewStationIp, NewSubnetMask);
- return Status;
-}
-
-
-EFI_STATUS
-EFIAPI
-EblMtftp (
- IN EFI_PXE_BASE_CODE_TFTP_OPCODE Operation,
- IN OUT VOID *BufferPtr OPTIONAL,
- IN BOOLEAN Overwrite,
- IN OUT UINT64 *BufferSize,
- IN UINTN *BlockSize OPTIONAL,
- IN EFI_IP_ADDRESS *ServerIp,
- IN UINT8 *Filename OPTIONAL,
- IN EFI_PXE_BASE_CODE_MTFTP_INFO *Info OPTIONAL,
- IN BOOLEAN DontUseBuffer
- )
-{
- EFI_STATUS Status;
- EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
-
- Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- Status = Pxe->Mtftp (
- Pxe,
- Operation,
- BufferPtr,
- Overwrite,
- BufferSize,
- BlockSize,
- ServerIp,
- Filename,
- Info,
- DontUseBuffer
- );
- return Status;
-}
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include <Protocol/SimpleNetwork.h>
+#include <Protocol/PxeBaseCode.h>
+
+
+BOOLEAN gUseIpv6 = FALSE;
+
+EFI_STATUS
+EFIAPI
+EblGetCurrentIpAddress (
+ IN OUT EFI_IP_ADDRESS *Ip
+ )
+{
+ EFI_STATUS Status;
+ EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
+
+ Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status = Pxe->Start (Pxe, gUseIpv6);
+ if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
+ return Status;
+ }
+
+ CopyMem (Ip, &Pxe->Mode->StationIp, sizeof (EFI_IP_ADDRESS));
+
+ return EFI_SUCCESS;
+}
+
+
+EFI_STATUS
+EFIAPI
+EblGetCurrentMacAddress (
+ IN OUT EFI_MAC_ADDRESS *Mac
+ )
+{
+ EFI_STATUS Status;
+ EFI_SIMPLE_NETWORK_PROTOCOL *SimpleNet;
+
+ Status = gBS->LocateProtocol (&gEfiSimpleNetworkProtocolGuid, NULL, (VOID **)&SimpleNet);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ CopyMem (Mac, SimpleNet->Mode->CurrentAddress.Addr, sizeof (EFI_MAC_ADDRESS));
+ return Status;
+}
+
+
+CHAR8 *
+EFIAPI
+EblLoadFileBootTypeString (
+ IN EFI_HANDLE Handle
+ )
+{
+ EFI_STATUS Status;
+ VOID *NullPtr;
+
+ Status = gBS->HandleProtocol (Handle, &gEfiPxeBaseCodeProtocolGuid, &NullPtr);
+ if (!EFI_ERROR (Status)) {
+ return "EFI PXE Network Boot";
+ }
+
+ return "";
+}
+
+EFI_STATUS
+EFIAPI
+EblPerformDHCP (
+ IN BOOLEAN SortOffers
+ )
+{
+ EFI_STATUS Status;
+ EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
+
+ Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status = Pxe->Start (Pxe, gUseIpv6);
+ if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
+ return Status;
+ }
+
+ Status = Pxe->Dhcp(Pxe, TRUE);
+ return Status;
+}
+
+
+EFI_STATUS
+EFIAPI
+EblSetStationIp (
+ IN EFI_IP_ADDRESS *NewStationIp, OPTIONAL
+ IN EFI_IP_ADDRESS *NewSubnetMask OPTIONAL
+ )
+{
+ EFI_STATUS Status;
+ EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
+
+ Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status = Pxe->Start (Pxe, gUseIpv6);
+ if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) {
+ return Status;
+ }
+
+ Status = Pxe->SetStationIp (Pxe, NewStationIp, NewSubnetMask);
+ return Status;
+}
+
+
+EFI_STATUS
+EFIAPI
+EblMtftp (
+ IN EFI_PXE_BASE_CODE_TFTP_OPCODE Operation,
+ IN OUT VOID *BufferPtr OPTIONAL,
+ IN BOOLEAN Overwrite,
+ IN OUT UINT64 *BufferSize,
+ IN UINTN *BlockSize OPTIONAL,
+ IN EFI_IP_ADDRESS *ServerIp,
+ IN UINT8 *Filename OPTIONAL,
+ IN EFI_PXE_BASE_CODE_MTFTP_INFO *Info OPTIONAL,
+ IN BOOLEAN DontUseBuffer
+ )
+{
+ EFI_STATUS Status;
+ EFI_PXE_BASE_CODE_PROTOCOL *Pxe;
+
+ Status = gBS->LocateProtocol (&gEfiPxeBaseCodeProtocolGuid, NULL, (VOID **)&Pxe);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status = Pxe->Mtftp (
+ Pxe,
+ Operation,
+ BufferPtr,
+ Overwrite,
+ BufferSize,
+ BlockSize,
+ ServerIp,
+ Filename,
+ Info,
+ DontUseBuffer
+ );
+ return Status;
+}
+
diff --git a/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf b/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
index b0d6e80ae..4d66bacb8 100644
--- a/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
+++ b/EmbeddedPkg/Library/EblNetworkLib/EblNetworkLib.inf
@@ -31,4 +31,4 @@
gEfiPxeBaseCodeProtocolGuid
[Depex]
- TRUE \ No newline at end of file
+ TRUE \ No newline at end of file
diff --git a/EmbeddedPkg/Library/EfiFileLib/EfiFileLib.c b/EmbeddedPkg/Library/EfiFileLib/EfiFileLib.c
index 5e0f9ca11..83a3b7841 100644
--- a/EmbeddedPkg/Library/EfiFileLib/EfiFileLib.c
+++ b/EmbeddedPkg/Library/EfiFileLib/EfiFileLib.c
@@ -1,1778 +1,1778 @@
-/** @file
-File IO routines inspired by Streams with an EFI flavor
-
-Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
-Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution. The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
-
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-Basic support for opening files on different device types. The device string
-is in the form of DevType:Path. Current DevType is required as there is no
-current mounted device concept of current working directory concept implement
-by this library.
-
-Device names are case insensitive and only check the leading characters for
-unique matches. Thus the following are all the same:
-LoadFile0:
-l0:
-L0:
-Lo0:
-
-Supported Device Names:
-A0x1234:0x12 - A memory buffer starting at address 0x1234 for 0x12 bytes
-l1: - EFI LoadFile device one.
-B0: - EFI BlockIo zero.
-fs3: - EFI Simple File System device 3
-Fv2: - EFI Firmware VOlume device 2
-10.0.1.102: - TFTP service IP followed by the file name
-**/
-
-#include <PiDxe.h>
-#include <Protocol/BlockIo.h>
-#include <Protocol/DiskIo.h>
-#include <Protocol/SimpleFileSystem.h>
-#include <Protocol/FirmwareVolume2.h>
-#include <Protocol/LoadFile.h>
-#include <Protocol/FirmwareVolumeBlock.h>
-#include <Guid/FileInfo.h>
-#include <Library/BaseLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/PrintLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/DebugLib.h>
-#include <Library/EfiFileLib.h>
-#include <Library/PcdLib.h>
-#include <Library/EblNetworkLib.h>
-
-
-CHAR8 *gCwd = NULL;
-
-CONST EFI_GUID gZeroGuid = { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } };
-
-#define EFI_OPEN_FILE_GUARD_HEADER 0x4B4D4641
-#define EFI_OPEN_FILE_GUARD_FOOTER 0x444D5A56
-
-// Need to defend against this overflowing
-#define MAX_CMD_LINE 0x200
-
-typedef struct {
- UINT32 Header;
- EFI_OPEN_FILE File;
- UINT32 Footer;
-} EFI_OPEN_FILE_GUARD;
-
-
-// globals to store current open device info
-EFI_HANDLE *mBlkIo = NULL;
-UINTN mBlkIoCount = 0;
-
-EFI_HANDLE *mFs = NULL;
-UINTN mFsCount = 0;
-// mFsInfo[] array entries must match mFs[] handles
-EFI_FILE_SYSTEM_INFO **mFsInfo = NULL;
-
-EFI_HANDLE *mFv = NULL;
-UINTN mFvCount = 0;
-EFI_HANDLE *mLoadFile = NULL;
-UINTN mLoadFileCount = 0;
-
-
-
-/**
-Internal worker function to validate a File handle.
-
-@param File Open File Handle
-
-@return TRUE File is valid
-@return FALSE File is not valid
-
-
-**/
-BOOLEAN
-FileHandleValid (
- IN EFI_OPEN_FILE *File
- )
-{
- EFI_OPEN_FILE_GUARD *GuardFile;
-
- // Look right before and after file structure for the correct signatures
- GuardFile = BASE_CR (File, EFI_OPEN_FILE_GUARD, File);
- if ((GuardFile->Header != EFI_OPEN_FILE_GUARD_HEADER) ||
- (GuardFile->Footer != EFI_OPEN_FILE_GUARD_FOOTER) ) {
- return FALSE;
- }
-
- return TRUE;
-}
-
-/**
-Internal worker function. If Buffer is not NULL free it.
-
-@param Buffer Buffer to FreePool()
-
-**/
-VOID
-EblFreePool (
- IN VOID *Buffer
- )
-{
- if (Buffer != NULL) {
- FreePool (Buffer);
- }
-}
-
-/**
-Update Device List Global Variables
-
-**/
-VOID
-EblUpdateDeviceLists (
- VOID
- )
-{
- EFI_STATUS Status;
- UINTN Size;
- EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs;
- EFI_FILE_HANDLE Root;
- UINTN Index;
-
- if (mBlkIo != NULL) {
- FreePool (mBlkIo);
- }
- gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &mBlkIoCount, &mBlkIo);
-
-
-
- if (mFv != NULL) {
- FreePool (mFv);
- }
- gBS->LocateHandleBuffer (ByProtocol, &gEfiFirmwareVolume2ProtocolGuid, NULL, &mFvCount, &mFv);
-
- if (mLoadFile != NULL) {
- FreePool (mLoadFile);
- }
- gBS->LocateHandleBuffer (ByProtocol, &gEfiLoadFileProtocolGuid, NULL, &mLoadFileCount, &mLoadFile);
-
- if (mFs != NULL) {
- FreePool (mFs);
- }
-
- if (&mFsInfo[0] != NULL) {
- // Need to Free the mFsInfo prior to recalculating mFsCount so don't move this code
- for (Index = 0; Index < mFsCount; Index++) {
- if (mFsInfo[Index] != NULL) {
- FreePool (mFsInfo[Index]);
- }
- }
- FreePool (mFsInfo);
- }
-
- gBS->LocateHandleBuffer (ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &mFsCount, &mFs);
-
-
- mFsInfo = AllocateZeroPool (mFsCount * sizeof (EFI_FILE_SYSTEM_INFO *));
- if (mFsInfo == NULL) {
- // If we can't do this then we can't support file system entries
- mFsCount = 0;
- } else {
- // Loop through all the file system structures and cache the file system info data
- for (Index =0; Index < mFsCount; Index++) {
- Status = gBS->HandleProtocol (mFs[Index], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs);
- if (!EFI_ERROR (Status)) {
- Status = Fs->OpenVolume (Fs, &Root);
- if (!EFI_ERROR (Status)) {
- // Get information about the volume
- Size = 0;
- Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, mFsInfo[Index]);
- if (Status == EFI_BUFFER_TOO_SMALL) {
- mFsInfo[Index] = AllocatePool (Size);
- Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, mFsInfo[Index]);
- }
-
- Root->Close (Root);
- }
- }
- }
- }
-}
-
-
-/**
-PathName is in the form <device name>:<path> for example fs1:\ or ROOT:\.
-Return TRUE if the <devce name> prefix of PathName matches a file system
-Volume Name. MatchIndex is the array index in mFsInfo[] of the match,
-and it can be used with mFs[] to find the handle that needs to be opened
-
-@param PathName PathName to check
-@param FileStart Index of the first character of the <path>
-@param MatchIndex Index in mFsInfo[] that matches
-
-@return TRUE PathName matches a Volume Label and MatchIndex is valid
-@return FALSE PathName does not match a Volume Label MatchIndex undefined
-
-**/
-BOOLEAN
-EblMatchVolumeName (
- IN CHAR8 *PathName,
- IN UINTN FileStart,
- OUT UINTN *MatchIndex
- )
-{
- UINTN Index;
- UINTN Compare;
- UINTN VolStrLen;
- BOOLEAN Match;
-
- for (Index =0; Index < mFsCount; Index++) {
- if (mFsInfo[Index] == NULL) {
- // FsInfo is not valid so skip it
- continue;
- }
- VolStrLen = StrLen (mFsInfo[Index]->VolumeLabel);
- for (Compare = 0, Match = TRUE; Compare < (FileStart - 1); Compare++) {
- if (Compare > VolStrLen) {
- Match = FALSE;
- break;
- }
- if (PathName[Compare] != (CHAR8)mFsInfo[Index]->VolumeLabel[Compare]) {
- // If the VolumeLabel has a space allow a _ to match with it in addition to ' '
- if (!((PathName[Compare] == '_') && (mFsInfo[Index]->VolumeLabel[Compare] == L' '))) {
- Match = FALSE;
- break;
- }
- }
- }
- if (Match) {
- *MatchIndex = Index;
- return TRUE;
- }
- }
-
- return FALSE;
-}
-
-
-/**
-Return the number of devices of the current type active in the system
-
-@param Type Device type to check
-
-@return 0 Invalid type
-
-**/
-UINTN
-EfiGetDeviceCounts (
- IN EFI_OPEN_FILE_TYPE DeviceType
- )
-{
- switch (DeviceType) {
- case EfiOpenLoadFile:
- return mLoadFileCount;
- case EfiOpenFirmwareVolume:
- return mFvCount;
- case EfiOpenFileSystem:
- return mFsCount;
- case EfiOpenBlockIo:
- return mBlkIoCount;
- default:
- return 0;
- }
-}
-
-EFI_STATUS
-ConvertIpStringToEfiIp (
- IN CHAR8 *PathName,
- OUT EFI_IP_ADDRESS *ServerIp
- )
-{
- CHAR8 *Str;
-
- Str = PathName;
- ServerIp->v4.Addr[0] = (UINT8)AsciiStrDecimalToUintn (Str);
-
- Str = AsciiStrStr (Str, ".");
- if (Str == NULL) {
- return EFI_DEVICE_ERROR;
- }
-
- ServerIp->v4.Addr[1] = (UINT8)AsciiStrDecimalToUintn (++Str);
-
- Str = AsciiStrStr (Str, ".");
- if (Str == NULL) {
- return EFI_DEVICE_ERROR;
- }
-
- ServerIp->v4.Addr[2] = (UINT8)AsciiStrDecimalToUintn (++Str);
-
- Str = AsciiStrStr (Str, ".");
- if (Str == NULL) {
- return EFI_DEVICE_ERROR;
- }
-
- ServerIp->v4.Addr[3] = (UINT8)AsciiStrDecimalToUintn (++Str);
-
- return EFI_SUCCESS;
-}
-
-
-/**
-Internal work function to extract a device number from a string skipping
-text. Easy way to extract numbers from strings like blk7:.
-
-@param Str String to extract device number form
-
-@return -1 Device string is not valid
-@return Device #
-
-**/
-UINTN
-EblConvertDevStringToNumber (
- IN CHAR8 *Str
- )
-{
- UINTN Max;
- UINTN Index;
-
-
- // Find the first digit
- Max = AsciiStrLen (Str);
- for (Index = 0; !((*Str >= '0') && (*Str <= '9')) && (Index < Max); Index++) {
- Str++;
- }
- if (Index == Max) {
- return (UINTN)-1;
- }
-
- return AsciiStrDecimalToUintn (Str);
-}
-
-
-/**
-Internal work function to fill in EFI_OPEN_FILE information for the Fs and BlkIo
-
-@param File Open file handle
-@param FileName Name of file after device stripped off
-
-
-**/
-EFI_STATUS
-EblFileDevicePath (
- IN OUT EFI_OPEN_FILE *File,
- IN CHAR8 *FileName,
- IN CONST UINT64 OpenMode
- )
-{
- EFI_STATUS Status;
- UINTN Size;
- FILEPATH_DEVICE_PATH *FilePath;
- EFI_DEVICE_PATH_PROTOCOL *FileDevicePath;
- CHAR16 UnicodeFileName[MAX_PATHNAME];
- EFI_BLOCK_IO_PROTOCOL *BlkIo;
- EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs;
- EFI_FILE_HANDLE Root;
-
-
- if ( *FileName != 0 ) {
- AsciiStrToUnicodeStr (FileName, UnicodeFileName);
- } else {
- AsciiStrToUnicodeStr ("\\", UnicodeFileName);
- }
-
- Size = StrSize (UnicodeFileName);
- FileDevicePath = AllocatePool (Size + SIZE_OF_FILEPATH_DEVICE_PATH + sizeof (EFI_DEVICE_PATH_PROTOCOL));
- if (FileDevicePath != NULL) {
- FilePath = (FILEPATH_DEVICE_PATH *) FileDevicePath;
- FilePath->Header.Type = MEDIA_DEVICE_PATH;
- FilePath->Header.SubType = MEDIA_FILEPATH_DP;
- CopyMem (&FilePath->PathName, UnicodeFileName, Size);
- SetDevicePathNodeLength (&FilePath->Header, Size + SIZE_OF_FILEPATH_DEVICE_PATH);
- SetDevicePathEndNode (NextDevicePathNode (&FilePath->Header));
-
- if (File->EfiHandle != NULL) {
- File->DevicePath = DevicePathFromHandle (File->EfiHandle);
- }
-
- File->DevicePath = AppendDevicePath (File->DevicePath, FileDevicePath);
- FreePool (FileDevicePath);
- }
-
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiBlockIoProtocolGuid, (VOID **)&BlkIo);
- if (!EFI_ERROR (Status)) {
- File->FsBlockIoMedia = BlkIo->Media;
- File->FsBlockIo = BlkIo;
-
- // If we are not opening the device this will get over written with file info
- File->MaxPosition = MultU64x32 (BlkIo->Media->LastBlock + 1, BlkIo->Media->BlockSize);
- }
-
- if (File->Type == EfiOpenFileSystem) {
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs);
- if (!EFI_ERROR (Status)) {
- Status = Fs->OpenVolume (Fs, &Root);
- if (!EFI_ERROR (Status)) {
- // Get information about the volume
- Size = 0;
- Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, File->FsInfo);
- if (Status == EFI_BUFFER_TOO_SMALL) {
- File->FsInfo = AllocatePool (Size);
- Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, File->FsInfo);
- }
-
- // Get information about the file
- Status = Root->Open (Root, &File->FsFileHandle, UnicodeFileName, OpenMode, 0);
- if (!EFI_ERROR (Status)) {
- Size = 0;
- Status = File->FsFileHandle->GetInfo (File->FsFileHandle, &gEfiFileInfoGuid, &Size, NULL);
- if (Status == EFI_BUFFER_TOO_SMALL) {
- File->FsFileInfo = AllocatePool (Size);
- Status = File->FsFileHandle->GetInfo (File->FsFileHandle, &gEfiFileInfoGuid, &Size, File->FsFileInfo);
- if (!EFI_ERROR (Status)) {
- File->Size = (UINTN)File->FsFileInfo->FileSize;
- File->MaxPosition = (UINT64)File->Size;
- }
- }
- }
-
- Root->Close (Root);
- }
- }
- } else if (File->Type == EfiOpenBlockIo) {
- File->Size = (UINTN)File->MaxPosition;
- }
-
- return Status;
-}
-
-#define ToUpper(a) ((((a) >= 'a') && ((a) <= 'z')) ? ((a) - 'a' + 'A') : (a))
-
-EFI_STATUS
-CompareGuidToString (
- IN EFI_GUID *Guid,
- IN CHAR8 *String
- )
-{
- CHAR8 AsciiGuid[64];
- CHAR8 *StringPtr;
- CHAR8 *GuidPtr;
-
- AsciiSPrint (AsciiGuid, sizeof(AsciiGuid), "%g", Guid);
-
- StringPtr = String;
- GuidPtr = AsciiGuid;
-
- while ((*StringPtr != '\0') && (*GuidPtr != '\0')) {
- // Skip dashes
- if (*StringPtr == '-') {
- StringPtr++;
- continue;
- }
-
- if (*GuidPtr == '-') {
- GuidPtr++;
- continue;
- }
-
- if (ToUpper(*StringPtr) != ToUpper(*GuidPtr)) {
- return EFI_NOT_FOUND;
- }
-
- StringPtr++;
- GuidPtr++;
- }
-
- return EFI_SUCCESS;
-}
-
-
-/**
-Internal work function to fill in EFI_OPEN_FILE information for the FV
-
-@param File Open file handle
-@param FileName Name of file after device stripped off
-
-
-**/
-EFI_STATUS
-EblFvFileDevicePath (
- IN OUT EFI_OPEN_FILE *File,
- IN CHAR8 *FileName,
- IN CONST UINT64 OpenMode
- )
-{
- EFI_STATUS Status;
- EFI_STATUS GetNextFileStatus;
- MEDIA_FW_VOL_FILEPATH_DEVICE_PATH DevicePathNode;
- EFI_DEVICE_PATH_PROTOCOL *DevicePath;
- UINTN Key;
- UINT32 AuthenticationStatus;
- CHAR8 AsciiSection[MAX_PATHNAME];
- VOID *Section;
- UINTN SectionSize;
- EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
- EFI_LBA Lba;
- UINTN BlockSize;
- UINTN NumberOfBlocks;
- EFI_FIRMWARE_VOLUME_HEADER *FvHeader = NULL;
- UINTN Index;
-
-
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **)&File->Fv);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- // Get FVB Info about the handle
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiFirmwareVolumeBlockProtocolGuid, (VOID **)&Fvb);
- if (!EFI_ERROR (Status)) {
- Status = Fvb->GetPhysicalAddress (Fvb, &File->FvStart);
- if (!EFI_ERROR (Status)) {
- FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)File->FvStart;
- File->FvHeaderSize = sizeof (EFI_FIRMWARE_VOLUME_HEADER);
- for (Index = 0; FvHeader->BlockMap[Index].Length !=0; Index++) {
- File->FvHeaderSize += sizeof (EFI_FV_BLOCK_MAP_ENTRY);
- }
-
- for (Lba = 0, File->FvSize = 0, NumberOfBlocks = 0; ; File->FvSize += (BlockSize * NumberOfBlocks), Lba += NumberOfBlocks) {
- Status = Fvb->GetBlockSize (Fvb, Lba, &BlockSize, &NumberOfBlocks);
- if (EFI_ERROR (Status)) {
- break;
- }
- }
- }
- }
-
-
- DevicePath = DevicePathFromHandle (File->EfiHandle);
-
- if (*FileName == '\0') {
- File->DevicePath = DuplicateDevicePath (DevicePath);
- File->Size = File->FvSize;
- File->MaxPosition = File->Size;
- } else {
- Key = 0;
- do {
- File->FvType = EFI_FV_FILETYPE_ALL;
- GetNextFileStatus = File->Fv->GetNextFile (
- File->Fv,
- &Key,
- &File->FvType,
- &File->FvNameGuid,
- &File->FvAttributes,
- &File->Size
- );
- if (!EFI_ERROR (GetNextFileStatus)) {
- // Compare GUID first
- Status = CompareGuidToString (&File->FvNameGuid, FileName);
- if (!EFI_ERROR(Status)) {
- break;
- }
-
- Section = NULL;
- Status = File->Fv->ReadSection (
- File->Fv,
- &File->FvNameGuid,
- EFI_SECTION_USER_INTERFACE,
- 0,
- &Section,
- &SectionSize,
- &AuthenticationStatus
- );
- if (!EFI_ERROR (Status)) {
- UnicodeStrToAsciiStr (Section, AsciiSection);
- if (AsciiStriCmp (FileName, AsciiSection) == 0) {
- FreePool (Section);
- break;
- }
- FreePool (Section);
- }
- }
- } while (!EFI_ERROR (GetNextFileStatus));
-
- if (EFI_ERROR (GetNextFileStatus)) {
- return GetNextFileStatus;
- }
-
- if (OpenMode != EFI_SECTION_ALL) {
- // Calculate the size of the section we are targeting
- Section = NULL;
- File->Size = 0;
- Status = File->Fv->ReadSection (
- File->Fv,
- &File->FvNameGuid,
- (EFI_SECTION_TYPE)OpenMode,
- 0,
- &Section,
- &File->Size,
- &AuthenticationStatus
- );
- if (EFI_ERROR (Status)) {
- return Status;
- }
- }
-
- File->MaxPosition = File->Size;
- EfiInitializeFwVolDevicepathNode (&DevicePathNode, &File->FvNameGuid);
- File->DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&DevicePathNode);
- }
-
-
- // FVB not required if FV was soft loaded...
- return EFI_SUCCESS;
-}
-
-
-
-
-/**
-Open a device named by PathName. The PathName includes a device name and
-path separated by a :. See file header for more details on the PathName
-syntax. There is no checking to prevent a file from being opened more than
-one type.
-
-SectionType is only used to open an FV. Each file in an FV contains multiple
-sections and only the SectionType section is opened.
-
-For any file that is opened with EfiOpen() must be closed with EfiClose().
-
-@param PathName Path to parse to open
-@param OpenMode Same as EFI_FILE.Open()
-@param SectionType Section in FV to open.
-
-@return NULL Open failed
-@return Valid EFI_OPEN_FILE handle
-
-**/
-EFI_OPEN_FILE *
-EfiOpen (
- IN CHAR8 *PathName,
- IN CONST UINT64 OpenMode,
- IN CONST EFI_SECTION_TYPE SectionType
- )
-{
- EFI_STATUS Status;
- EFI_OPEN_FILE *File;
- EFI_OPEN_FILE FileData;
- UINTN StrLen;
- UINTN FileStart;
- UINTN DevNumber = 0;
- EFI_OPEN_FILE_GUARD *GuardFile;
- BOOLEAN VolumeNameMatch;
- EFI_DEVICE_PATH_PROTOCOL *DevicePath;
- UINTN Size;
- EFI_IP_ADDRESS Ip;
- CHAR8 *CwdPlusPathName;
- UINTN Index;
- EFI_SECTION_TYPE ModifiedSectionType;
-
- EblUpdateDeviceLists ();
-
- File = &FileData;
- ZeroMem (File, sizeof (EFI_OPEN_FILE));
-
- StrLen = AsciiStrSize (PathName);
- if (StrLen <= 1) {
- // Smallest valid path is 1 char and a null
- return NULL;
- }
-
- for (FileStart = 0; FileStart < StrLen; FileStart++) {
- if (PathName[FileStart] == ':') {
- FileStart++;
- break;
- }
- }
-
- //
- // Matching volume name has precedence over handle based names
- //
- VolumeNameMatch = EblMatchVolumeName (PathName, FileStart, &DevNumber);
- if (!VolumeNameMatch) {
- if (FileStart == StrLen) {
- // No Volume name or device name, so try Current Working Directory
- if (gCwd == NULL) {
- // No CWD
- return NULL;
- }
-
- // We could add a current working directory concept
- CwdPlusPathName = AllocatePool (AsciiStrSize (gCwd) + AsciiStrSize (PathName));
- if (CwdPlusPathName == NULL) {
- return NULL;
- }
-
- if ((PathName[0] == '/') || (PathName[0] == '\\')) {
- // PathName starts in / so this means we go to the root of the device in the CWD.
- CwdPlusPathName[0] = '\0';
- for (FileStart = 0; gCwd[FileStart] != '\0'; FileStart++) {
- CwdPlusPathName[FileStart] = gCwd[FileStart];
- if (gCwd[FileStart] == ':') {
- FileStart++;
- CwdPlusPathName[FileStart] = '\0';
- break;
- }
- }
- } else {
- AsciiStrCpy (CwdPlusPathName, gCwd);
- StrLen = AsciiStrLen (gCwd);
- if ((*PathName != '/') && (*PathName != '\\') && (gCwd[StrLen-1] != '/') && (gCwd[StrLen-1] != '\\')) {
- AsciiStrCat (CwdPlusPathName, "\\");
- }
- }
-
- AsciiStrCat (CwdPlusPathName, PathName);
- if (AsciiStrStr (CwdPlusPathName, ":") == NULL) {
- // Extra error check to make sure we don't recurse and blow stack
- return NULL;
- }
-
- File = EfiOpen (CwdPlusPathName, OpenMode, SectionType);
- FreePool (CwdPlusPathName);
- return File;
- }
-
- DevNumber = EblConvertDevStringToNumber ((CHAR8 *)PathName);
- }
-
- File->DeviceName = AllocatePool (StrLen);
- AsciiStrCpy (File->DeviceName, PathName);
- File->DeviceName[FileStart - 1] = '\0';
- File->FileName = &File->DeviceName[FileStart];
- if (File->FileName[0] == '\0') {
- // if it is just a file name use / as root
- File->FileName = "\\";
- }
-
- //
- // Use best match algorithm on the dev names so we only need to look at the
- // first few charters to match the full device name. Short name forms are
- // legal from the caller.
- //
- Status = EFI_SUCCESS;
- if (*PathName == 'f' || *PathName == 'F' || VolumeNameMatch) {
- if (PathName[1] == 's' || PathName[1] == 'S' || VolumeNameMatch) {
- if (DevNumber >= mFsCount) {
- goto ErrorExit;
- }
- File->Type = EfiOpenFileSystem;
- File->EfiHandle = mFs[DevNumber];
- Status = EblFileDevicePath (File, &PathName[FileStart], OpenMode);
-
- } else if (PathName[1] == 'v' || PathName[1] == 'V') {
- if (DevNumber >= mFvCount) {
- goto ErrorExit;
- }
- File->Type = EfiOpenFirmwareVolume;
- File->EfiHandle = mFv[DevNumber];
-
- if ((PathName[FileStart] == '/') || (PathName[FileStart] == '\\')) {
- // Skip leading / as its not really needed for the FV since no directories are supported
- FileStart++;
- }
-
- // Check for 2nd :
- ModifiedSectionType = SectionType;
- for (Index = FileStart; PathName[Index] != '\0'; Index++) {
- if (PathName[Index] == ':') {
- // Support fv0:\DxeCore:0x10
- // This means open the PE32 Section of the file
- ModifiedSectionType = (EFI_SECTION_TYPE)AsciiStrHexToUintn (&PathName[Index + 1]);
- PathName[Index] = '\0';
- }
- }
- File->FvSectionType = ModifiedSectionType;
- Status = EblFvFileDevicePath (File, &PathName[FileStart], ModifiedSectionType);
- }
- } else if ((*PathName == 'A') || (*PathName == 'a')) {
- // Handle a:0x10000000:0x1234 address form a:ADDRESS:SIZE
- File->Type = EfiOpenMemoryBuffer;
- // 1st colon is at PathName[FileStart - 1]
- File->Buffer = (VOID *)AsciiStrHexToUintn (&PathName[FileStart]);
-
- // Find 2nd colon
- while ((PathName[FileStart] != ':') && (PathName[FileStart] != '\0')) {
- FileStart++;
- }
-
- // If we ran out of string, there's no extra data
- if (PathName[FileStart] == '\0') {
- File->Size = 0;
- } else {
- File->Size = AsciiStrHexToUintn (&PathName[FileStart + 1]);
- }
-
- // if there's no number after the second colon, default
- // the end of memory
- if (File->Size == 0) {
- File->Size = (UINTN)(0 - (UINTN)File->Buffer);
- }
-
- File->MaxPosition = File->Size;
- File->BaseOffset = (UINTN)File->Buffer;
-
- } else if (*PathName== 'l' || *PathName == 'L') {
- if (DevNumber >= mLoadFileCount) {
- goto ErrorExit;
- }
- File->Type = EfiOpenLoadFile;
- File->EfiHandle = mLoadFile[DevNumber];
-
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiLoadFileProtocolGuid, (VOID **)&File->LoadFile);
- if (EFI_ERROR (Status)) {
- goto ErrorExit;
- }
-
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePath);
- if (EFI_ERROR (Status)) {
- goto ErrorExit;
- }
- File->DevicePath = DuplicateDevicePath (DevicePath);
-
- } else if (*PathName == 'b' || *PathName == 'B') {
- // Handle b#:0x10000000:0x1234 address form b#:ADDRESS:SIZE
- if (DevNumber >= mBlkIoCount) {
- goto ErrorExit;
- }
- File->Type = EfiOpenBlockIo;
- File->EfiHandle = mBlkIo[DevNumber];
- EblFileDevicePath (File, "", OpenMode);
-
- // 1st colon is at PathName[FileStart - 1]
- File->DiskOffset = AsciiStrHexToUintn (&PathName[FileStart]);
-
- // Find 2nd colon
- while ((PathName[FileStart] != ':') && (PathName[FileStart] != '\0')) {
- FileStart++;
- }
-
- // If we ran out of string, there's no extra data
- if (PathName[FileStart] == '\0') {
- Size = 0;
- } else {
- Size = AsciiStrHexToUintn (&PathName[FileStart + 1]);
- }
-
- // if a zero size is passed in (or the size is left out entirely),
- // go to the end of the device.
- if (Size == 0) {
- File->Size = File->Size - File->DiskOffset;
- } else {
- File->Size = Size;
- }
-
- File->MaxPosition = File->Size;
- File->BaseOffset = File->DiskOffset;
- } else if ((*PathName) >= '0' && (*PathName <= '9')) {
-
- // Get current IP address
- Status = EblGetCurrentIpAddress (&Ip);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Device IP Address is not configured.\n");
- goto ErrorExit;
- }
-
-
- // Parse X.X.X.X:Filename, only support IPv4 TFTP for now...
- File->Type = EfiOpenTftp;
- File->IsDirty = FALSE;
- File->IsBufferValid = FALSE;
-
- Status = ConvertIpStringToEfiIp (PathName, &File->ServerIp);
- }
-
- if (EFI_ERROR (Status)) {
- goto ErrorExit;
- }
-
- GuardFile = (EFI_OPEN_FILE_GUARD *)AllocateZeroPool (sizeof (EFI_OPEN_FILE_GUARD));
- if (GuardFile == NULL) {
- goto ErrorExit;
- }
-
- GuardFile->Header = EFI_OPEN_FILE_GUARD_HEADER;
- CopyMem (&(GuardFile->File), &FileData, sizeof (EFI_OPEN_FILE));
- GuardFile->Footer = EFI_OPEN_FILE_GUARD_FOOTER;
-
- return &(GuardFile->File);
-
-ErrorExit:
- FreePool (File->DeviceName);
- return NULL;
-}
-
-#define FILE_COPY_CHUNK 0x01000000
-
-EFI_STATUS
-EfiCopyFile (
- IN CHAR8 *DestinationFile,
- IN CHAR8 *SourceFile
- )
-{
- EFI_OPEN_FILE *Source = NULL;
- EFI_OPEN_FILE *Destination = NULL;
- EFI_STATUS Status = EFI_SUCCESS;
- VOID *Buffer = NULL;
- UINTN Size;
- UINTN Offset;
- UINTN Chunk = FILE_COPY_CHUNK;
-
- Source = EfiOpen (SourceFile, EFI_FILE_MODE_READ, 0);
- if (Source == NULL) {
- AsciiPrint("Source file open error.\n");
- Status = EFI_NOT_FOUND;
- goto Exit;
- }
-
- Destination = EfiOpen (DestinationFile, EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, 0);
- if (Destination == NULL) {
- AsciiPrint("Destination file open error.\n");
- Status = EFI_NOT_FOUND;
- goto Exit;
- }
-
- Buffer = AllocatePool(FILE_COPY_CHUNK);
- if (Buffer == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto Exit;
- }
-
- Size = EfiTell(Source, NULL);
-
- for (Offset = 0; Offset + FILE_COPY_CHUNK <= Size; Offset += Chunk) {
- Chunk = FILE_COPY_CHUNK;
-
- Status = EfiRead(Source, Buffer, &Chunk);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Read file error %r\n", Status);
- goto Exit;
- }
-
- Status = EfiWrite(Destination, Buffer, &Chunk);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Write file error %r\n", Status);
- goto Exit;
- }
- }
-
- // Any left over?
- if (Offset < Size) {
- Chunk = Size - Offset;
-
- Status = EfiRead(Source, Buffer, &Chunk);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Read file error\n");
- goto Exit;
- }
-
- Status = EfiWrite(Destination, Buffer, &Chunk);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Write file error\n");
- goto Exit;
- }
- }
-
-Exit:
- if (Source != NULL) {
- Status = EfiClose(Source);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Source close error");
- }
- }
-
- if (Destination != NULL) {
- Status = EfiClose(Destination);
- if (EFI_ERROR(Status)) {
- AsciiPrint("Destination close error");
- }
- }
-
- if (Buffer != NULL) {
- FreePool(Buffer);
- }
-
- return Status;
-}
-
-/**
-Use DeviceType and Index to form a valid PathName and try and open it.
-
-@param DeviceType Device type to open
-@param Index Device Index to use. Zero relative.
-
-@return NULL Open failed
-@return Valid EFI_OPEN_FILE handle
-
-**/
-EFI_OPEN_FILE *
-EfiDeviceOpenByType (
- IN EFI_OPEN_FILE_TYPE DeviceType,
- IN UINTN Index
- )
-{
- CHAR8 *DevStr;
- CHAR8 Path[MAX_CMD_LINE];
-
- switch (DeviceType) {
- case EfiOpenLoadFile:
- DevStr = "loadfile%d:";
- break;
- case EfiOpenFirmwareVolume:
- DevStr = "fv%d:";
- break;
- case EfiOpenFileSystem:
- DevStr = "fs%d:";
- break;
- case EfiOpenBlockIo:
- DevStr = "blk%d:";
- break;
- case EfiOpenMemoryBuffer:
- DevStr = "a%d:";
- break;
- default:
- return NULL;
- }
-
- AsciiSPrint (Path, MAX_PATHNAME, DevStr, Index);
-
- return EfiOpen (Path, EFI_FILE_MODE_READ, 0);
-}
-
-
-/**
-Close a file handle opened by EfiOpen() and free all resources allocated by
-EfiOpen().
-
-@param Stream Open File Handle
-
-@return EFI_INVALID_PARAMETER Stream is not an Open File
-@return EFI_SUCCESS Steam closed
-
-**/
-EFI_STATUS
-EfiClose (
- IN EFI_OPEN_FILE *File
- )
-{
- EFI_STATUS Status;
- UINT64 TftpBufferSize;
-
- if (!FileHandleValid (File)) {
- return EFI_INVALID_PARAMETER;
- }
-
- //Write the buffer contents to TFTP file.
- if ((File->Type == EfiOpenTftp) && (File->IsDirty)) {
-
- TftpBufferSize = File->Size;
- Status = EblMtftp (
- EFI_PXE_BASE_CODE_TFTP_WRITE_FILE,
- File->Buffer,
- TRUE,
- &TftpBufferSize,
- NULL,
- &File->ServerIp,
- (UINT8 *)File->FileName,
- NULL,
- FALSE
- );
- if (EFI_ERROR(Status)) {
- AsciiPrint("TFTP error during APPLE_NSP_TFTP_WRITE_FILE: %r\n", Status);
- return Status;
- }
- }
-
- if ((File->Type == EfiOpenLoadFile) ||
- ((File->Type == EfiOpenTftp) && (File->IsBufferValid == TRUE)) ||
- ((File->Type == EfiOpenFirmwareVolume) && (File->IsBufferValid == TRUE))) {
- EblFreePool(File->Buffer);
- }
-
- EblFreePool (File->DevicePath);
- EblFreePool (File->DeviceName);
- EblFreePool (File->FsFileInfo);
- EblFreePool (File->FsInfo);
-
- if (File->FsFileHandle != NULL) {
- File->FsFileHandle->Close (File->FsFileHandle);
- }
-
- // Need to free File and it's Guard structures
- EblFreePool (BASE_CR (File, EFI_OPEN_FILE_GUARD, File));
- return EFI_SUCCESS;
-}
-
-
-/**
-Return the size of the file represented by Stream. Also return the current
-Seek position. Opening a file will enable a valid file size to be returned.
-LoadFile is an exception as a load file size is set to zero.
-
-@param Stream Open File Handle
-
-@return 0 Stream is not an Open File or a valid LoadFile handle
-
-**/
-UINTN
-EfiTell (
- IN EFI_OPEN_FILE *File,
- OUT EFI_LBA *CurrentPosition OPTIONAL
- )
-{
- EFI_STATUS Status;
- UINT64 BufferSize = 0;
-
- if (!FileHandleValid (File)) {
- return 0;
- }
-
- if (CurrentPosition != NULL) {
- *CurrentPosition = File->CurrentPosition;
- }
-
- if (File->Type == EfiOpenLoadFile) {
- // Figure out the File->Size
- File->Buffer = NULL;
- File->Size = 0;
- Status = File->LoadFile->LoadFile (File->LoadFile, File->DevicePath, FALSE, &File->Size, File->Buffer);
- if (Status != EFI_BUFFER_TOO_SMALL) {
- return 0;
- }
-
- File->MaxPosition = (UINT64)File->Size;
- } else if (File->Type == EfiOpenTftp) {
-
- Status = EblMtftp (
- EFI_PXE_BASE_CODE_TFTP_GET_FILE_SIZE,
- NULL,
- FALSE,
- &BufferSize,
- NULL,
- &File->ServerIp,
- (UINT8 *)File->FileName,
- NULL,
- TRUE
- );
- if (EFI_ERROR(Status)) {
- AsciiPrint("TFTP error during APPLE_NSP_TFTP_GET_FILE_SIZE: %r\n", Status);
- return 0;
- }
-
- File->Size = (UINTN)BufferSize;
- File->MaxPosition = File->Size;
- }
-
- return File->Size;
-}
-
-
-/**
-Seek to the Offset location in the file. LoadFile and FV device types do
-not support EfiSeek(). It is not possible to grow the file size using
-EfiSeek().
-
-SeekType defines how use Offset to calculate the new file position:
-EfiSeekStart : Position = Offset
-EfiSeekCurrent: Position is Offset bytes from the current position
-EfiSeekEnd : Only supported if Offset is zero to seek to end of file.
-
-@param Stream Open File Handle
-@param Offset Offset to seek too.
-@param SeekType Type of seek to perform
-
-
-@return EFI_INVALID_PARAMETER Stream is not an Open File
-@return EFI_UNSUPPORTED LoadFile and FV do not support Seek
-@return EFI_NOT_FOUND Seek past the end of the file.
-@return EFI_SUCCESS Steam closed
-
-**/
-EFI_STATUS
-EfiSeek (
- IN EFI_OPEN_FILE *File,
- IN EFI_LBA Offset,
- IN EFI_SEEK_TYPE SeekType
- )
-{
- EFI_STATUS Status;
- UINT64 CurrentPosition;
-
- if (!FileHandleValid (File)) {
- return EFI_INVALID_PARAMETER;
- }
-
- if (File->Type == EfiOpenLoadFile) {
- // LoadFile does not support Seek
- return EFI_UNSUPPORTED;
- }
-
- CurrentPosition = File->CurrentPosition;
- switch (SeekType) {
- case EfiSeekStart:
- if (Offset > File->MaxPosition) {
- return EFI_NOT_FOUND;
- }
- CurrentPosition = Offset;
- break;
-
- case EfiSeekCurrent:
- if ((File->CurrentPosition + Offset) > File->MaxPosition) {
- return EFI_NOT_FOUND;
- }
- CurrentPosition += Offset;
- break;
-
- case EfiSeekEnd:
- if (Offset != 0) {
- // We don't support growing file size via seeking past end of file
- return EFI_UNSUPPORTED;
- }
- CurrentPosition = File->MaxPosition;
- break;
-
- default:
- return EFI_NOT_FOUND;
- }
-
- Status = EFI_SUCCESS;
- if (File->FsFileHandle != NULL) {
- Status = File->FsFileHandle->SetPosition (File->FsFileHandle, CurrentPosition);
- }
-
- if (!EFI_ERROR (Status)) {
- File->CurrentPosition = CurrentPosition;
- }
-
- return Status;
-}
-
-EFI_STATUS
-CacheTftpFile (
- IN OUT EFI_OPEN_FILE *File
- )
-{
- EFI_STATUS Status;
- UINT64 TftpBufferSize;
-
- if (File->IsBufferValid) {
- return EFI_SUCCESS;
- }
-
- // Make sure the file size is set.
- EfiTell (File, NULL);
-
- //Allocate a buffer to hold the whole file.
- File->Buffer = AllocatePool(File->Size);
- if (File->Buffer == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- TftpBufferSize = File->Size;
-
- Status = EblMtftp (
- EFI_PXE_BASE_CODE_TFTP_READ_FILE,
- File->Buffer,
- FALSE,
- &TftpBufferSize,
- NULL,
- &File->ServerIp,
- (UINT8 *)File->FileName,
- NULL,
- FALSE);
- if (EFI_ERROR(Status)) {
- AsciiPrint("TFTP error during APPLE_NSP_TFTP_READ_FILE: %r\n", Status);
- FreePool(File->Buffer);
- return Status;
- }
-
- // Set the buffer valid flag.
- File->IsBufferValid = TRUE;
-
- return Status;
-}
-
-/**
-Read BufferSize bytes from the current location in the file. For load file,
-FV, and TFTP case you must read the entire file.
-
-@param Stream Open File Handle
-@param Buffer Caller allocated buffer.
-@param BufferSize Size of buffer in bytes.
-
-
-@return EFI_SUCCESS Stream is not an Open File
-@return EFI_END_OF_FILE Tried to read past the end of the file
-@return EFI_INVALID_PARAMETER Stream is not an open file handle
-@return EFI_BUFFER_TOO_SMALL Buffer is not big enough to do the read
-@return "other" Error returned from device read
-
-**/
-EFI_STATUS
-EfiRead (
- IN EFI_OPEN_FILE *File,
- OUT VOID *Buffer,
- OUT UINTN *BufferSize
- )
-{
- EFI_STATUS Status;
- UINT32 AuthenticationStatus;
- EFI_DISK_IO_PROTOCOL *DiskIo;
-
- if (!FileHandleValid (File)) {
- return EFI_INVALID_PARAMETER;
- }
-
- // Don't read past the end of the file.
- if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
- return EFI_END_OF_FILE;
- }
-
- switch (File->Type) {
- case EfiOpenLoadFile:
- // Figure out the File->Size
- EfiTell (File, NULL);
-
- Status = File->LoadFile->LoadFile (File->LoadFile, File->DevicePath, FALSE, BufferSize, Buffer);
- break;
-
- case EfiOpenFirmwareVolume:
- if (CompareGuid (&File->FvNameGuid, &gZeroGuid)) {
- // This is the entire FV device, so treat like a memory buffer
- CopyMem (Buffer, (VOID *)(UINTN)(File->FvStart + File->CurrentPosition), *BufferSize);
- File->CurrentPosition += *BufferSize;
- Status = EFI_SUCCESS;
- } else {
- if (File->Buffer == NULL) {
- if (File->FvSectionType == EFI_SECTION_ALL) {
- Status = File->Fv->ReadFile (
- File->Fv,
- &File->FvNameGuid,
- (VOID **)&File->Buffer,
- &File->Size,
- &File->FvType,
- &File->FvAttributes,
- &AuthenticationStatus
- );
- } else {
- Status = File->Fv->ReadSection (
- File->Fv,
- &File->FvNameGuid,
- File->FvSectionType,
- 0,
- (VOID **)&File->Buffer,
- &File->Size,
- &AuthenticationStatus
- );
- }
- if (EFI_ERROR (Status)) {
- return Status;
- }
- File->IsBufferValid = TRUE;
- }
- // Operate on the cached buffer so Seek will work
- CopyMem (Buffer, File->Buffer + File->CurrentPosition, *BufferSize);
- File->CurrentPosition += *BufferSize;
- Status = EFI_SUCCESS;
- }
- break;
-
- case EfiOpenMemoryBuffer:
- CopyMem (Buffer, File->Buffer + File->CurrentPosition, *BufferSize);
- File->CurrentPosition += *BufferSize;
- Status = EFI_SUCCESS;
- break;
-
- case EfiOpenFileSystem:
- Status = File->FsFileHandle->Read (File->FsFileHandle, BufferSize, Buffer);
- File->CurrentPosition += *BufferSize;
- break;
-
- case EfiOpenBlockIo:
- Status = gBS->HandleProtocol(File->EfiHandle, &gEfiDiskIoProtocolGuid, (VOID **)&DiskIo);
- if (!EFI_ERROR(Status)) {
- Status = DiskIo->ReadDisk(DiskIo, File->FsBlockIoMedia->MediaId, File->DiskOffset + File->CurrentPosition, *BufferSize, Buffer);
- }
- File->CurrentPosition += *BufferSize;
- break;
-
- case EfiOpenTftp:
- // Cache the file if it hasn't been cached yet.
- if (File->IsBufferValid == FALSE) {
- Status = CacheTftpFile (File);
- if (EFI_ERROR (Status)) {
- return Status;
- }
- }
-
- // Copy out the requested data
- CopyMem (Buffer, File->Buffer + File->CurrentPosition, *BufferSize);
- File->CurrentPosition += *BufferSize;
-
- Status = EFI_SUCCESS;
- break;
-
- default:
- return EFI_INVALID_PARAMETER;
- };
-
- return Status;
-}
-
-
-/**
-Read the entire file into a buffer. This routine allocates the buffer and
-returns it to the user full of the read data.
-
-This is very useful for load file where it's hard to know how big the buffer
-must be.
-
-@param Stream Open File Handle
-@param Buffer Pointer to buffer to return.
-@param BufferSize Pointer to Size of buffer return..
-
-
-@return EFI_SUCCESS Stream is not an Open File
-@return EFI_END_OF_FILE Tried to read past the end of the file
-@return EFI_INVALID_PARAMETER Stream is not an open file handle
-@return EFI_BUFFER_TOO_SMALL Buffer is not big enough to do the read
-@return "other" Error returned from device read
-
-**/
-EFI_STATUS
-EfiReadAllocatePool (
- IN EFI_OPEN_FILE *File,
- OUT VOID **Buffer,
- OUT UINTN *BufferSize
- )
-{
- if (!FileHandleValid (File)) {
- return EFI_INVALID_PARAMETER;
- }
-
- // Loadfile defers file size determination on Open so use tell to find it
- EfiTell (File, NULL);
-
- *BufferSize = File->Size;
- *Buffer = AllocatePool (*BufferSize);
- if (*Buffer == NULL) {
- return EFI_NOT_FOUND;
- }
-
- return EfiRead (File, *Buffer, BufferSize);
-}
-
-
-/**
-Write data back to the file. For TFTP case you must write the entire file.
-
-@param Stream Open File Handle
-@param Buffer Pointer to buffer to return.
-@param BufferSize Pointer to Size of buffer return..
-
-
-@return EFI_SUCCESS Stream is not an Open File
-@return EFI_END_OF_FILE Tried to read past the end of the file
-@return EFI_INVALID_PARAMETER Stream is not an open file handle
-@return EFI_BUFFER_TOO_SMALL Buffer is not big enough to do the read
-@return "other" Error returned from device write
-
-**/
-EFI_STATUS
-EfiWrite (
- IN EFI_OPEN_FILE *File,
- OUT VOID *Buffer,
- OUT UINTN *BufferSize
- )
-{
- EFI_STATUS Status;
- EFI_FV_WRITE_FILE_DATA FileData;
- EFI_DISK_IO_PROTOCOL *DiskIo;
-
- if (!FileHandleValid (File)) {
- return EFI_INVALID_PARAMETER;
- }
-
- switch (File->Type) {
- case EfiOpenMemoryBuffer:
- if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
- return EFI_END_OF_FILE;
- }
-
- CopyMem (File->Buffer + File->CurrentPosition, Buffer, *BufferSize);
- File->CurrentPosition += *BufferSize;
- Status = EFI_SUCCESS;
-
- case EfiOpenLoadFile:
- // LoadFile device is read only be definition
- Status = EFI_UNSUPPORTED;
-
- case EfiOpenFirmwareVolume:
- if (File->FvSectionType != EFI_SECTION_ALL) {
- // Writes not support to a specific section. You have to update entire file
- return EFI_UNSUPPORTED;
- }
-
- FileData.NameGuid = &(File->FvNameGuid);
- FileData.Type = File->FvType;
- FileData.FileAttributes = File->FvAttributes;
- FileData.Buffer = Buffer;
- FileData.BufferSize = (UINT32)*BufferSize;
- Status = File->Fv->WriteFile (File->Fv, 1, EFI_FV_UNRELIABLE_WRITE, &FileData);
- break;
-
- case EfiOpenFileSystem:
- Status = File->FsFileHandle->Write (File->FsFileHandle, BufferSize, Buffer);
- File->CurrentPosition += *BufferSize;
- break;
-
- case EfiOpenBlockIo:
- if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
- return EFI_END_OF_FILE;
- }
-
- Status = gBS->HandleProtocol (File->EfiHandle, &gEfiDiskIoProtocolGuid, (VOID **)&DiskIo);
- if (!EFI_ERROR(Status)) {
- Status = DiskIo->WriteDisk (DiskIo, File->FsBlockIoMedia->MediaId, File->DiskOffset + File->CurrentPosition, *BufferSize, Buffer);
- }
- File->CurrentPosition += *BufferSize;
- break;
-
- case EfiOpenTftp:
- // Cache the file if it hasn't been cached yet.
- if (File->IsBufferValid == FALSE) {
- Status = CacheTftpFile(File);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- }
-
- // Don't overwrite the buffer
- if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
- UINT8 *TempBuffer;
-
- TempBuffer = File->Buffer;
-
- File->Buffer = AllocatePool ((UINTN)(File->CurrentPosition + *BufferSize));
- if (File->Buffer == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- CopyMem (File->Buffer, TempBuffer, File->Size);
-
- FreePool (TempBuffer);
-
- File->Size = (UINTN)(File->CurrentPosition + *BufferSize);
- File->MaxPosition = (UINT64)File->Size;
- }
-
- // Copy in the requested data
- CopyMem (File->Buffer + File->CurrentPosition, Buffer, *BufferSize);
- File->CurrentPosition += *BufferSize;
-
- // Mark the file dirty
- File->IsDirty = TRUE;
-
- Status = EFI_SUCCESS;
- break;
-
- default:
- Status = EFI_INVALID_PARAMETER;
- };
-
- return Status;
-}
-
-
-/**
-Given Cwd expand Path to remove .. and replace them with real
-directory names.
-
-@param Cwd Current Working Directory
-@param Path Path to expand
-
-@return NULL Cwd or Path are not valid
-@return 'other' Path with .. expanded
-
-**/
-CHAR8 *
-ExpandPath (
- IN CHAR8 *Cwd,
- IN CHAR8 *Path
- )
-{
- CHAR8 *NewPath;
- CHAR8 *Work, *Start, *End;
- UINTN StrLen;
- INTN i;
-
- if (Cwd == NULL || Path == NULL) {
- return NULL;
- }
-
- StrLen = AsciiStrSize (Cwd);
- if (StrLen <= 2) {
- // Smallest valid path is 1 char and a null
- return NULL;
- }
-
- StrLen = AsciiStrSize (Path);
- NewPath = AllocatePool (AsciiStrSize (Cwd) + StrLen + 1);
- if (NewPath == NULL) {
- return NULL;
- }
- AsciiStrCpy (NewPath, Cwd);
-
- End = Path + StrLen;
- for (Start = Path ;;) {
- Work = AsciiStrStr (Start, "..") ;
- if (Work == NULL) {
- // Remaining part of Path contains no more ..
- break;
- }
-
- // append path prior to ..
- AsciiStrnCat (NewPath, Start, Work - Start);
- StrLen = AsciiStrLen (NewPath);
- for (i = StrLen; i >= 0; i--) {
- if (NewPath[i] == ':') {
- // too many ..
- return NULL;
- }
- if (NewPath[i] == '/' || NewPath[i] == '\\') {
- if ((i > 0) && (NewPath[i-1] == ':')) {
- // leave the / before a :
- NewPath[i+1] = '\0';
- } else {
- // replace / will Null to remove trailing file/dir reference
- NewPath[i] = '\0';
- }
- break;
- }
- }
-
- Start = Work + 3;
- }
-
- // Handle the path that remains after the ..
- AsciiStrnCat (NewPath, Start, End - Start);
-
- return NewPath;
-}
-
-
-/**
-Set the Current Working Directory (CWD). If a call is made to EfiOpen () and
-the path does not contain a device name, The CWD is prepended to the path.
-
-@param Cwd Current Working Directory to set
-
-
-@return EFI_SUCCESS CWD is set
-@return EFI_INVALID_PARAMETER Cwd is not a valid device:path
-
-**/
-EFI_STATUS
-EfiSetCwd (
- IN CHAR8 *Cwd
- )
-{
- EFI_OPEN_FILE *File;
- UINTN Len;
- CHAR8 *Path;
-
- if (Cwd == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- if (AsciiStrCmp (Cwd, ".") == 0) {
- // cd . is a no-op
- return EFI_SUCCESS;
- }
-
- Path = Cwd;
- if (AsciiStrStr (Cwd, "..") != NULL) {
- if (gCwd == NULL) {
- // no parent
- return EFI_SUCCESS;
- }
-
- Len = AsciiStrLen (gCwd);
- if ((gCwd[Len-2] == ':') && ((gCwd[Len-1] == '/') || (gCwd[Len-1] == '\\'))) {
- // parent is device so nothing to do
- return EFI_SUCCESS;
- }
-
- // Expand .. in Cwd, given we know current working directory
- Path = ExpandPath (gCwd, Cwd);
- if (Path == NULL) {
- return EFI_NOT_FOUND;
- }
- }
-
- File = EfiOpen (Path, EFI_FILE_MODE_READ, 0);
- if (File == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- if (gCwd != NULL) {
- FreePool (gCwd);
- }
-
- // Use the info returned from EfiOpen as it can add in CWD if needed. So Cwd could be
- // relative to the current gCwd or not.
- gCwd = AllocatePool (AsciiStrSize (File->DeviceName) + AsciiStrSize (File->FileName) + 10);
- if (gCwd == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- AsciiStrCpy (gCwd, File->DeviceName);
- if (File->FileName == NULL) {
- AsciiStrCat (gCwd, ":\\");
- } else {
- AsciiStrCat (gCwd, ":");
- AsciiStrCat (gCwd, File->FileName);
- }
-
-
- EfiClose (File);
- if (Path != Cwd) {
- FreePool (Path);
- }
- return EFI_SUCCESS;
-}
-
-
-/**
-Set the Current Working Directory (CWD). If a call is made to EfiOpen () and
-the path does not contain a device name, The CWD is prepended to the path.
-The CWD buffer is only valid until a new call is made to EfiSetCwd(). After
-a call to EfiSetCwd() it is not legal to use the pointer returned by
-this function.
-
-@param Cwd Current Working Directory
-
-
-@return "" No CWD set
-@return 'other' Returns buffer that contains CWD.
-
-**/
-CHAR8 *
-EfiGetCwd (
- VOID
- )
-{
- if (gCwd == NULL) {
- return "";
- }
- return gCwd;
-}
-
-
+/** @file
+File IO routines inspired by Streams with an EFI flavor
+
+Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
+Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+Basic support for opening files on different device types. The device string
+is in the form of DevType:Path. Current DevType is required as there is no
+current mounted device concept of current working directory concept implement
+by this library.
+
+Device names are case insensitive and only check the leading characters for
+unique matches. Thus the following are all the same:
+LoadFile0:
+l0:
+L0:
+Lo0:
+
+Supported Device Names:
+A0x1234:0x12 - A memory buffer starting at address 0x1234 for 0x12 bytes
+l1: - EFI LoadFile device one.
+B0: - EFI BlockIo zero.
+fs3: - EFI Simple File System device 3
+Fv2: - EFI Firmware VOlume device 2
+10.0.1.102: - TFTP service IP followed by the file name
+**/
+
+#include <PiDxe.h>
+#include <Protocol/BlockIo.h>
+#include <Protocol/DiskIo.h>
+#include <Protocol/SimpleFileSystem.h>
+#include <Protocol/FirmwareVolume2.h>
+#include <Protocol/LoadFile.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+#include <Guid/FileInfo.h>
+#include <Library/BaseLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/PrintLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/DebugLib.h>
+#include <Library/EfiFileLib.h>
+#include <Library/PcdLib.h>
+#include <Library/EblNetworkLib.h>
+
+
+CHAR8 *gCwd = NULL;
+
+CONST EFI_GUID gZeroGuid = { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } };
+
+#define EFI_OPEN_FILE_GUARD_HEADER 0x4B4D4641
+#define EFI_OPEN_FILE_GUARD_FOOTER 0x444D5A56
+
+// Need to defend against this overflowing
+#define MAX_CMD_LINE 0x200
+
+typedef struct {
+ UINT32 Header;
+ EFI_OPEN_FILE File;
+ UINT32 Footer;
+} EFI_OPEN_FILE_GUARD;
+
+
+// globals to store current open device info
+EFI_HANDLE *mBlkIo = NULL;
+UINTN mBlkIoCount = 0;
+
+EFI_HANDLE *mFs = NULL;
+UINTN mFsCount = 0;
+// mFsInfo[] array entries must match mFs[] handles
+EFI_FILE_SYSTEM_INFO **mFsInfo = NULL;
+
+EFI_HANDLE *mFv = NULL;
+UINTN mFvCount = 0;
+EFI_HANDLE *mLoadFile = NULL;
+UINTN mLoadFileCount = 0;
+
+
+
+/**
+Internal worker function to validate a File handle.
+
+@param File Open File Handle
+
+@return TRUE File is valid
+@return FALSE File is not valid
+
+
+**/
+BOOLEAN
+FileHandleValid (
+ IN EFI_OPEN_FILE *File
+ )
+{
+ EFI_OPEN_FILE_GUARD *GuardFile;
+
+ // Look right before and after file structure for the correct signatures
+ GuardFile = BASE_CR (File, EFI_OPEN_FILE_GUARD, File);
+ if ((GuardFile->Header != EFI_OPEN_FILE_GUARD_HEADER) ||
+ (GuardFile->Footer != EFI_OPEN_FILE_GUARD_FOOTER) ) {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/**
+Internal worker function. If Buffer is not NULL free it.
+
+@param Buffer Buffer to FreePool()
+
+**/
+VOID
+EblFreePool (
+ IN VOID *Buffer
+ )
+{
+ if (Buffer != NULL) {
+ FreePool (Buffer);
+ }
+}
+
+/**
+Update Device List Global Variables
+
+**/
+VOID
+EblUpdateDeviceLists (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN Size;
+ EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs;
+ EFI_FILE_HANDLE Root;
+ UINTN Index;
+
+ if (mBlkIo != NULL) {
+ FreePool (mBlkIo);
+ }
+ gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &mBlkIoCount, &mBlkIo);
+
+
+
+ if (mFv != NULL) {
+ FreePool (mFv);
+ }
+ gBS->LocateHandleBuffer (ByProtocol, &gEfiFirmwareVolume2ProtocolGuid, NULL, &mFvCount, &mFv);
+
+ if (mLoadFile != NULL) {
+ FreePool (mLoadFile);
+ }
+ gBS->LocateHandleBuffer (ByProtocol, &gEfiLoadFileProtocolGuid, NULL, &mLoadFileCount, &mLoadFile);
+
+ if (mFs != NULL) {
+ FreePool (mFs);
+ }
+
+ if (&mFsInfo[0] != NULL) {
+ // Need to Free the mFsInfo prior to recalculating mFsCount so don't move this code
+ for (Index = 0; Index < mFsCount; Index++) {
+ if (mFsInfo[Index] != NULL) {
+ FreePool (mFsInfo[Index]);
+ }
+ }
+ FreePool (mFsInfo);
+ }
+
+ gBS->LocateHandleBuffer (ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &mFsCount, &mFs);
+
+
+ mFsInfo = AllocateZeroPool (mFsCount * sizeof (EFI_FILE_SYSTEM_INFO *));
+ if (mFsInfo == NULL) {
+ // If we can't do this then we can't support file system entries
+ mFsCount = 0;
+ } else {
+ // Loop through all the file system structures and cache the file system info data
+ for (Index =0; Index < mFsCount; Index++) {
+ Status = gBS->HandleProtocol (mFs[Index], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs);
+ if (!EFI_ERROR (Status)) {
+ Status = Fs->OpenVolume (Fs, &Root);
+ if (!EFI_ERROR (Status)) {
+ // Get information about the volume
+ Size = 0;
+ Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, mFsInfo[Index]);
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ mFsInfo[Index] = AllocatePool (Size);
+ Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, mFsInfo[Index]);
+ }
+
+ Root->Close (Root);
+ }
+ }
+ }
+ }
+}
+
+
+/**
+PathName is in the form <device name>:<path> for example fs1:\ or ROOT:\.
+Return TRUE if the <devce name> prefix of PathName matches a file system
+Volume Name. MatchIndex is the array index in mFsInfo[] of the match,
+and it can be used with mFs[] to find the handle that needs to be opened
+
+@param PathName PathName to check
+@param FileStart Index of the first character of the <path>
+@param MatchIndex Index in mFsInfo[] that matches
+
+@return TRUE PathName matches a Volume Label and MatchIndex is valid
+@return FALSE PathName does not match a Volume Label MatchIndex undefined
+
+**/
+BOOLEAN
+EblMatchVolumeName (
+ IN CHAR8 *PathName,
+ IN UINTN FileStart,
+ OUT UINTN *MatchIndex
+ )
+{
+ UINTN Index;
+ UINTN Compare;
+ UINTN VolStrLen;
+ BOOLEAN Match;
+
+ for (Index =0; Index < mFsCount; Index++) {
+ if (mFsInfo[Index] == NULL) {
+ // FsInfo is not valid so skip it
+ continue;
+ }
+ VolStrLen = StrLen (mFsInfo[Index]->VolumeLabel);
+ for (Compare = 0, Match = TRUE; Compare < (FileStart - 1); Compare++) {
+ if (Compare > VolStrLen) {
+ Match = FALSE;
+ break;
+ }
+ if (PathName[Compare] != (CHAR8)mFsInfo[Index]->VolumeLabel[Compare]) {
+ // If the VolumeLabel has a space allow a _ to match with it in addition to ' '
+ if (!((PathName[Compare] == '_') && (mFsInfo[Index]->VolumeLabel[Compare] == L' '))) {
+ Match = FALSE;
+ break;
+ }
+ }
+ }
+ if (Match) {
+ *MatchIndex = Index;
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+
+/**
+Return the number of devices of the current type active in the system
+
+@param Type Device type to check
+
+@return 0 Invalid type
+
+**/
+UINTN
+EfiGetDeviceCounts (
+ IN EFI_OPEN_FILE_TYPE DeviceType
+ )
+{
+ switch (DeviceType) {
+ case EfiOpenLoadFile:
+ return mLoadFileCount;
+ case EfiOpenFirmwareVolume:
+ return mFvCount;
+ case EfiOpenFileSystem:
+ return mFsCount;
+ case EfiOpenBlockIo:
+ return mBlkIoCount;
+ default:
+ return 0;
+ }
+}
+
+EFI_STATUS
+ConvertIpStringToEfiIp (
+ IN CHAR8 *PathName,
+ OUT EFI_IP_ADDRESS *ServerIp
+ )
+{
+ CHAR8 *Str;
+
+ Str = PathName;
+ ServerIp->v4.Addr[0] = (UINT8)AsciiStrDecimalToUintn (Str);
+
+ Str = AsciiStrStr (Str, ".");
+ if (Str == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ ServerIp->v4.Addr[1] = (UINT8)AsciiStrDecimalToUintn (++Str);
+
+ Str = AsciiStrStr (Str, ".");
+ if (Str == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ ServerIp->v4.Addr[2] = (UINT8)AsciiStrDecimalToUintn (++Str);
+
+ Str = AsciiStrStr (Str, ".");
+ if (Str == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ ServerIp->v4.Addr[3] = (UINT8)AsciiStrDecimalToUintn (++Str);
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+Internal work function to extract a device number from a string skipping
+text. Easy way to extract numbers from strings like blk7:.
+
+@param Str String to extract device number form
+
+@return -1 Device string is not valid
+@return Device #
+
+**/
+UINTN
+EblConvertDevStringToNumber (
+ IN CHAR8 *Str
+ )
+{
+ UINTN Max;
+ UINTN Index;
+
+
+ // Find the first digit
+ Max = AsciiStrLen (Str);
+ for (Index = 0; !((*Str >= '0') && (*Str <= '9')) && (Index < Max); Index++) {
+ Str++;
+ }
+ if (Index == Max) {
+ return (UINTN)-1;
+ }
+
+ return AsciiStrDecimalToUintn (Str);
+}
+
+
+/**
+Internal work function to fill in EFI_OPEN_FILE information for the Fs and BlkIo
+
+@param File Open file handle
+@param FileName Name of file after device stripped off
+
+
+**/
+EFI_STATUS
+EblFileDevicePath (
+ IN OUT EFI_OPEN_FILE *File,
+ IN CHAR8 *FileName,
+ IN CONST UINT64 OpenMode
+ )
+{
+ EFI_STATUS Status;
+ UINTN Size;
+ FILEPATH_DEVICE_PATH *FilePath;
+ EFI_DEVICE_PATH_PROTOCOL *FileDevicePath;
+ CHAR16 UnicodeFileName[MAX_PATHNAME];
+ EFI_BLOCK_IO_PROTOCOL *BlkIo;
+ EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs;
+ EFI_FILE_HANDLE Root;
+
+
+ if ( *FileName != 0 ) {
+ AsciiStrToUnicodeStr (FileName, UnicodeFileName);
+ } else {
+ AsciiStrToUnicodeStr ("\\", UnicodeFileName);
+ }
+
+ Size = StrSize (UnicodeFileName);
+ FileDevicePath = AllocatePool (Size + SIZE_OF_FILEPATH_DEVICE_PATH + sizeof (EFI_DEVICE_PATH_PROTOCOL));
+ if (FileDevicePath != NULL) {
+ FilePath = (FILEPATH_DEVICE_PATH *) FileDevicePath;
+ FilePath->Header.Type = MEDIA_DEVICE_PATH;
+ FilePath->Header.SubType = MEDIA_FILEPATH_DP;
+ CopyMem (&FilePath->PathName, UnicodeFileName, Size);
+ SetDevicePathNodeLength (&FilePath->Header, Size + SIZE_OF_FILEPATH_DEVICE_PATH);
+ SetDevicePathEndNode (NextDevicePathNode (&FilePath->Header));
+
+ if (File->EfiHandle != NULL) {
+ File->DevicePath = DevicePathFromHandle (File->EfiHandle);
+ }
+
+ File->DevicePath = AppendDevicePath (File->DevicePath, FileDevicePath);
+ FreePool (FileDevicePath);
+ }
+
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiBlockIoProtocolGuid, (VOID **)&BlkIo);
+ if (!EFI_ERROR (Status)) {
+ File->FsBlockIoMedia = BlkIo->Media;
+ File->FsBlockIo = BlkIo;
+
+ // If we are not opening the device this will get over written with file info
+ File->MaxPosition = MultU64x32 (BlkIo->Media->LastBlock + 1, BlkIo->Media->BlockSize);
+ }
+
+ if (File->Type == EfiOpenFileSystem) {
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs);
+ if (!EFI_ERROR (Status)) {
+ Status = Fs->OpenVolume (Fs, &Root);
+ if (!EFI_ERROR (Status)) {
+ // Get information about the volume
+ Size = 0;
+ Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, File->FsInfo);
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ File->FsInfo = AllocatePool (Size);
+ Status = Root->GetInfo (Root, &gEfiFileSystemInfoGuid, &Size, File->FsInfo);
+ }
+
+ // Get information about the file
+ Status = Root->Open (Root, &File->FsFileHandle, UnicodeFileName, OpenMode, 0);
+ if (!EFI_ERROR (Status)) {
+ Size = 0;
+ Status = File->FsFileHandle->GetInfo (File->FsFileHandle, &gEfiFileInfoGuid, &Size, NULL);
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ File->FsFileInfo = AllocatePool (Size);
+ Status = File->FsFileHandle->GetInfo (File->FsFileHandle, &gEfiFileInfoGuid, &Size, File->FsFileInfo);
+ if (!EFI_ERROR (Status)) {
+ File->Size = (UINTN)File->FsFileInfo->FileSize;
+ File->MaxPosition = (UINT64)File->Size;
+ }
+ }
+ }
+
+ Root->Close (Root);
+ }
+ }
+ } else if (File->Type == EfiOpenBlockIo) {
+ File->Size = (UINTN)File->MaxPosition;
+ }
+
+ return Status;
+}
+
+#define ToUpper(a) ((((a) >= 'a') && ((a) <= 'z')) ? ((a) - 'a' + 'A') : (a))
+
+EFI_STATUS
+CompareGuidToString (
+ IN EFI_GUID *Guid,
+ IN CHAR8 *String
+ )
+{
+ CHAR8 AsciiGuid[64];
+ CHAR8 *StringPtr;
+ CHAR8 *GuidPtr;
+
+ AsciiSPrint (AsciiGuid, sizeof(AsciiGuid), "%g", Guid);
+
+ StringPtr = String;
+ GuidPtr = AsciiGuid;
+
+ while ((*StringPtr != '\0') && (*GuidPtr != '\0')) {
+ // Skip dashes
+ if (*StringPtr == '-') {
+ StringPtr++;
+ continue;
+ }
+
+ if (*GuidPtr == '-') {
+ GuidPtr++;
+ continue;
+ }
+
+ if (ToUpper(*StringPtr) != ToUpper(*GuidPtr)) {
+ return EFI_NOT_FOUND;
+ }
+
+ StringPtr++;
+ GuidPtr++;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+Internal work function to fill in EFI_OPEN_FILE information for the FV
+
+@param File Open file handle
+@param FileName Name of file after device stripped off
+
+
+**/
+EFI_STATUS
+EblFvFileDevicePath (
+ IN OUT EFI_OPEN_FILE *File,
+ IN CHAR8 *FileName,
+ IN CONST UINT64 OpenMode
+ )
+{
+ EFI_STATUS Status;
+ EFI_STATUS GetNextFileStatus;
+ MEDIA_FW_VOL_FILEPATH_DEVICE_PATH DevicePathNode;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ UINTN Key;
+ UINT32 AuthenticationStatus;
+ CHAR8 AsciiSection[MAX_PATHNAME];
+ VOID *Section;
+ UINTN SectionSize;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
+ EFI_LBA Lba;
+ UINTN BlockSize;
+ UINTN NumberOfBlocks;
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader = NULL;
+ UINTN Index;
+
+
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **)&File->Fv);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ // Get FVB Info about the handle
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiFirmwareVolumeBlockProtocolGuid, (VOID **)&Fvb);
+ if (!EFI_ERROR (Status)) {
+ Status = Fvb->GetPhysicalAddress (Fvb, &File->FvStart);
+ if (!EFI_ERROR (Status)) {
+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)File->FvStart;
+ File->FvHeaderSize = sizeof (EFI_FIRMWARE_VOLUME_HEADER);
+ for (Index = 0; FvHeader->BlockMap[Index].Length !=0; Index++) {
+ File->FvHeaderSize += sizeof (EFI_FV_BLOCK_MAP_ENTRY);
+ }
+
+ for (Lba = 0, File->FvSize = 0, NumberOfBlocks = 0; ; File->FvSize += (BlockSize * NumberOfBlocks), Lba += NumberOfBlocks) {
+ Status = Fvb->GetBlockSize (Fvb, Lba, &BlockSize, &NumberOfBlocks);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+ }
+ }
+
+
+ DevicePath = DevicePathFromHandle (File->EfiHandle);
+
+ if (*FileName == '\0') {
+ File->DevicePath = DuplicateDevicePath (DevicePath);
+ File->Size = File->FvSize;
+ File->MaxPosition = File->Size;
+ } else {
+ Key = 0;
+ do {
+ File->FvType = EFI_FV_FILETYPE_ALL;
+ GetNextFileStatus = File->Fv->GetNextFile (
+ File->Fv,
+ &Key,
+ &File->FvType,
+ &File->FvNameGuid,
+ &File->FvAttributes,
+ &File->Size
+ );
+ if (!EFI_ERROR (GetNextFileStatus)) {
+ // Compare GUID first
+ Status = CompareGuidToString (&File->FvNameGuid, FileName);
+ if (!EFI_ERROR(Status)) {
+ break;
+ }
+
+ Section = NULL;
+ Status = File->Fv->ReadSection (
+ File->Fv,
+ &File->FvNameGuid,
+ EFI_SECTION_USER_INTERFACE,
+ 0,
+ &Section,
+ &SectionSize,
+ &AuthenticationStatus
+ );
+ if (!EFI_ERROR (Status)) {
+ UnicodeStrToAsciiStr (Section, AsciiSection);
+ if (AsciiStriCmp (FileName, AsciiSection) == 0) {
+ FreePool (Section);
+ break;
+ }
+ FreePool (Section);
+ }
+ }
+ } while (!EFI_ERROR (GetNextFileStatus));
+
+ if (EFI_ERROR (GetNextFileStatus)) {
+ return GetNextFileStatus;
+ }
+
+ if (OpenMode != EFI_SECTION_ALL) {
+ // Calculate the size of the section we are targeting
+ Section = NULL;
+ File->Size = 0;
+ Status = File->Fv->ReadSection (
+ File->Fv,
+ &File->FvNameGuid,
+ (EFI_SECTION_TYPE)OpenMode,
+ 0,
+ &Section,
+ &File->Size,
+ &AuthenticationStatus
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ File->MaxPosition = File->Size;
+ EfiInitializeFwVolDevicepathNode (&DevicePathNode, &File->FvNameGuid);
+ File->DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&DevicePathNode);
+ }
+
+
+ // FVB not required if FV was soft loaded...
+ return EFI_SUCCESS;
+}
+
+
+
+
+/**
+Open a device named by PathName. The PathName includes a device name and
+path separated by a :. See file header for more details on the PathName
+syntax. There is no checking to prevent a file from being opened more than
+one type.
+
+SectionType is only used to open an FV. Each file in an FV contains multiple
+sections and only the SectionType section is opened.
+
+For any file that is opened with EfiOpen() must be closed with EfiClose().
+
+@param PathName Path to parse to open
+@param OpenMode Same as EFI_FILE.Open()
+@param SectionType Section in FV to open.
+
+@return NULL Open failed
+@return Valid EFI_OPEN_FILE handle
+
+**/
+EFI_OPEN_FILE *
+EfiOpen (
+ IN CHAR8 *PathName,
+ IN CONST UINT64 OpenMode,
+ IN CONST EFI_SECTION_TYPE SectionType
+ )
+{
+ EFI_STATUS Status;
+ EFI_OPEN_FILE *File;
+ EFI_OPEN_FILE FileData;
+ UINTN StrLen;
+ UINTN FileStart;
+ UINTN DevNumber = 0;
+ EFI_OPEN_FILE_GUARD *GuardFile;
+ BOOLEAN VolumeNameMatch;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ UINTN Size;
+ EFI_IP_ADDRESS Ip;
+ CHAR8 *CwdPlusPathName;
+ UINTN Index;
+ EFI_SECTION_TYPE ModifiedSectionType;
+
+ EblUpdateDeviceLists ();
+
+ File = &FileData;
+ ZeroMem (File, sizeof (EFI_OPEN_FILE));
+
+ StrLen = AsciiStrSize (PathName);
+ if (StrLen <= 1) {
+ // Smallest valid path is 1 char and a null
+ return NULL;
+ }
+
+ for (FileStart = 0; FileStart < StrLen; FileStart++) {
+ if (PathName[FileStart] == ':') {
+ FileStart++;
+ break;
+ }
+ }
+
+ //
+ // Matching volume name has precedence over handle based names
+ //
+ VolumeNameMatch = EblMatchVolumeName (PathName, FileStart, &DevNumber);
+ if (!VolumeNameMatch) {
+ if (FileStart == StrLen) {
+ // No Volume name or device name, so try Current Working Directory
+ if (gCwd == NULL) {
+ // No CWD
+ return NULL;
+ }
+
+ // We could add a current working directory concept
+ CwdPlusPathName = AllocatePool (AsciiStrSize (gCwd) + AsciiStrSize (PathName));
+ if (CwdPlusPathName == NULL) {
+ return NULL;
+ }
+
+ if ((PathName[0] == '/') || (PathName[0] == '\\')) {
+ // PathName starts in / so this means we go to the root of the device in the CWD.
+ CwdPlusPathName[0] = '\0';
+ for (FileStart = 0; gCwd[FileStart] != '\0'; FileStart++) {
+ CwdPlusPathName[FileStart] = gCwd[FileStart];
+ if (gCwd[FileStart] == ':') {
+ FileStart++;
+ CwdPlusPathName[FileStart] = '\0';
+ break;
+ }
+ }
+ } else {
+ AsciiStrCpy (CwdPlusPathName, gCwd);
+ StrLen = AsciiStrLen (gCwd);
+ if ((*PathName != '/') && (*PathName != '\\') && (gCwd[StrLen-1] != '/') && (gCwd[StrLen-1] != '\\')) {
+ AsciiStrCat (CwdPlusPathName, "\\");
+ }
+ }
+
+ AsciiStrCat (CwdPlusPathName, PathName);
+ if (AsciiStrStr (CwdPlusPathName, ":") == NULL) {
+ // Extra error check to make sure we don't recurse and blow stack
+ return NULL;
+ }
+
+ File = EfiOpen (CwdPlusPathName, OpenMode, SectionType);
+ FreePool (CwdPlusPathName);
+ return File;
+ }
+
+ DevNumber = EblConvertDevStringToNumber ((CHAR8 *)PathName);
+ }
+
+ File->DeviceName = AllocatePool (StrLen);
+ AsciiStrCpy (File->DeviceName, PathName);
+ File->DeviceName[FileStart - 1] = '\0';
+ File->FileName = &File->DeviceName[FileStart];
+ if (File->FileName[0] == '\0') {
+ // if it is just a file name use / as root
+ File->FileName = "\\";
+ }
+
+ //
+ // Use best match algorithm on the dev names so we only need to look at the
+ // first few charters to match the full device name. Short name forms are
+ // legal from the caller.
+ //
+ Status = EFI_SUCCESS;
+ if (*PathName == 'f' || *PathName == 'F' || VolumeNameMatch) {
+ if (PathName[1] == 's' || PathName[1] == 'S' || VolumeNameMatch) {
+ if (DevNumber >= mFsCount) {
+ goto ErrorExit;
+ }
+ File->Type = EfiOpenFileSystem;
+ File->EfiHandle = mFs[DevNumber];
+ Status = EblFileDevicePath (File, &PathName[FileStart], OpenMode);
+
+ } else if (PathName[1] == 'v' || PathName[1] == 'V') {
+ if (DevNumber >= mFvCount) {
+ goto ErrorExit;
+ }
+ File->Type = EfiOpenFirmwareVolume;
+ File->EfiHandle = mFv[DevNumber];
+
+ if ((PathName[FileStart] == '/') || (PathName[FileStart] == '\\')) {
+ // Skip leading / as its not really needed for the FV since no directories are supported
+ FileStart++;
+ }
+
+ // Check for 2nd :
+ ModifiedSectionType = SectionType;
+ for (Index = FileStart; PathName[Index] != '\0'; Index++) {
+ if (PathName[Index] == ':') {
+ // Support fv0:\DxeCore:0x10
+ // This means open the PE32 Section of the file
+ ModifiedSectionType = (EFI_SECTION_TYPE)AsciiStrHexToUintn (&PathName[Index + 1]);
+ PathName[Index] = '\0';
+ }
+ }
+ File->FvSectionType = ModifiedSectionType;
+ Status = EblFvFileDevicePath (File, &PathName[FileStart], ModifiedSectionType);
+ }
+ } else if ((*PathName == 'A') || (*PathName == 'a')) {
+ // Handle a:0x10000000:0x1234 address form a:ADDRESS:SIZE
+ File->Type = EfiOpenMemoryBuffer;
+ // 1st colon is at PathName[FileStart - 1]
+ File->Buffer = (VOID *)AsciiStrHexToUintn (&PathName[FileStart]);
+
+ // Find 2nd colon
+ while ((PathName[FileStart] != ':') && (PathName[FileStart] != '\0')) {
+ FileStart++;
+ }
+
+ // If we ran out of string, there's no extra data
+ if (PathName[FileStart] == '\0') {
+ File->Size = 0;
+ } else {
+ File->Size = AsciiStrHexToUintn (&PathName[FileStart + 1]);
+ }
+
+ // if there's no number after the second colon, default
+ // the end of memory
+ if (File->Size == 0) {
+ File->Size = (UINTN)(0 - (UINTN)File->Buffer);
+ }
+
+ File->MaxPosition = File->Size;
+ File->BaseOffset = (UINTN)File->Buffer;
+
+ } else if (*PathName== 'l' || *PathName == 'L') {
+ if (DevNumber >= mLoadFileCount) {
+ goto ErrorExit;
+ }
+ File->Type = EfiOpenLoadFile;
+ File->EfiHandle = mLoadFile[DevNumber];
+
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiLoadFileProtocolGuid, (VOID **)&File->LoadFile);
+ if (EFI_ERROR (Status)) {
+ goto ErrorExit;
+ }
+
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePath);
+ if (EFI_ERROR (Status)) {
+ goto ErrorExit;
+ }
+ File->DevicePath = DuplicateDevicePath (DevicePath);
+
+ } else if (*PathName == 'b' || *PathName == 'B') {
+ // Handle b#:0x10000000:0x1234 address form b#:ADDRESS:SIZE
+ if (DevNumber >= mBlkIoCount) {
+ goto ErrorExit;
+ }
+ File->Type = EfiOpenBlockIo;
+ File->EfiHandle = mBlkIo[DevNumber];
+ EblFileDevicePath (File, "", OpenMode);
+
+ // 1st colon is at PathName[FileStart - 1]
+ File->DiskOffset = AsciiStrHexToUintn (&PathName[FileStart]);
+
+ // Find 2nd colon
+ while ((PathName[FileStart] != ':') && (PathName[FileStart] != '\0')) {
+ FileStart++;
+ }
+
+ // If we ran out of string, there's no extra data
+ if (PathName[FileStart] == '\0') {
+ Size = 0;
+ } else {
+ Size = AsciiStrHexToUintn (&PathName[FileStart + 1]);
+ }
+
+ // if a zero size is passed in (or the size is left out entirely),
+ // go to the end of the device.
+ if (Size == 0) {
+ File->Size = File->Size - File->DiskOffset;
+ } else {
+ File->Size = Size;
+ }
+
+ File->MaxPosition = File->Size;
+ File->BaseOffset = File->DiskOffset;
+ } else if ((*PathName) >= '0' && (*PathName <= '9')) {
+
+ // Get current IP address
+ Status = EblGetCurrentIpAddress (&Ip);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Device IP Address is not configured.\n");
+ goto ErrorExit;
+ }
+
+
+ // Parse X.X.X.X:Filename, only support IPv4 TFTP for now...
+ File->Type = EfiOpenTftp;
+ File->IsDirty = FALSE;
+ File->IsBufferValid = FALSE;
+
+ Status = ConvertIpStringToEfiIp (PathName, &File->ServerIp);
+ }
+
+ if (EFI_ERROR (Status)) {
+ goto ErrorExit;
+ }
+
+ GuardFile = (EFI_OPEN_FILE_GUARD *)AllocateZeroPool (sizeof (EFI_OPEN_FILE_GUARD));
+ if (GuardFile == NULL) {
+ goto ErrorExit;
+ }
+
+ GuardFile->Header = EFI_OPEN_FILE_GUARD_HEADER;
+ CopyMem (&(GuardFile->File), &FileData, sizeof (EFI_OPEN_FILE));
+ GuardFile->Footer = EFI_OPEN_FILE_GUARD_FOOTER;
+
+ return &(GuardFile->File);
+
+ErrorExit:
+ FreePool (File->DeviceName);
+ return NULL;
+}
+
+#define FILE_COPY_CHUNK 0x01000000
+
+EFI_STATUS
+EfiCopyFile (
+ IN CHAR8 *DestinationFile,
+ IN CHAR8 *SourceFile
+ )
+{
+ EFI_OPEN_FILE *Source = NULL;
+ EFI_OPEN_FILE *Destination = NULL;
+ EFI_STATUS Status = EFI_SUCCESS;
+ VOID *Buffer = NULL;
+ UINTN Size;
+ UINTN Offset;
+ UINTN Chunk = FILE_COPY_CHUNK;
+
+ Source = EfiOpen (SourceFile, EFI_FILE_MODE_READ, 0);
+ if (Source == NULL) {
+ AsciiPrint("Source file open error.\n");
+ Status = EFI_NOT_FOUND;
+ goto Exit;
+ }
+
+ Destination = EfiOpen (DestinationFile, EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, 0);
+ if (Destination == NULL) {
+ AsciiPrint("Destination file open error.\n");
+ Status = EFI_NOT_FOUND;
+ goto Exit;
+ }
+
+ Buffer = AllocatePool(FILE_COPY_CHUNK);
+ if (Buffer == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto Exit;
+ }
+
+ Size = EfiTell(Source, NULL);
+
+ for (Offset = 0; Offset + FILE_COPY_CHUNK <= Size; Offset += Chunk) {
+ Chunk = FILE_COPY_CHUNK;
+
+ Status = EfiRead(Source, Buffer, &Chunk);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Read file error %r\n", Status);
+ goto Exit;
+ }
+
+ Status = EfiWrite(Destination, Buffer, &Chunk);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Write file error %r\n", Status);
+ goto Exit;
+ }
+ }
+
+ // Any left over?
+ if (Offset < Size) {
+ Chunk = Size - Offset;
+
+ Status = EfiRead(Source, Buffer, &Chunk);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Read file error\n");
+ goto Exit;
+ }
+
+ Status = EfiWrite(Destination, Buffer, &Chunk);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Write file error\n");
+ goto Exit;
+ }
+ }
+
+Exit:
+ if (Source != NULL) {
+ Status = EfiClose(Source);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Source close error");
+ }
+ }
+
+ if (Destination != NULL) {
+ Status = EfiClose(Destination);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("Destination close error");
+ }
+ }
+
+ if (Buffer != NULL) {
+ FreePool(Buffer);
+ }
+
+ return Status;
+}
+
+/**
+Use DeviceType and Index to form a valid PathName and try and open it.
+
+@param DeviceType Device type to open
+@param Index Device Index to use. Zero relative.
+
+@return NULL Open failed
+@return Valid EFI_OPEN_FILE handle
+
+**/
+EFI_OPEN_FILE *
+EfiDeviceOpenByType (
+ IN EFI_OPEN_FILE_TYPE DeviceType,
+ IN UINTN Index
+ )
+{
+ CHAR8 *DevStr;
+ CHAR8 Path[MAX_CMD_LINE];
+
+ switch (DeviceType) {
+ case EfiOpenLoadFile:
+ DevStr = "loadfile%d:";
+ break;
+ case EfiOpenFirmwareVolume:
+ DevStr = "fv%d:";
+ break;
+ case EfiOpenFileSystem:
+ DevStr = "fs%d:";
+ break;
+ case EfiOpenBlockIo:
+ DevStr = "blk%d:";
+ break;
+ case EfiOpenMemoryBuffer:
+ DevStr = "a%d:";
+ break;
+ default:
+ return NULL;
+ }
+
+ AsciiSPrint (Path, MAX_PATHNAME, DevStr, Index);
+
+ return EfiOpen (Path, EFI_FILE_MODE_READ, 0);
+}
+
+
+/**
+Close a file handle opened by EfiOpen() and free all resources allocated by
+EfiOpen().
+
+@param Stream Open File Handle
+
+@return EFI_INVALID_PARAMETER Stream is not an Open File
+@return EFI_SUCCESS Steam closed
+
+**/
+EFI_STATUS
+EfiClose (
+ IN EFI_OPEN_FILE *File
+ )
+{
+ EFI_STATUS Status;
+ UINT64 TftpBufferSize;
+
+ if (!FileHandleValid (File)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Write the buffer contents to TFTP file.
+ if ((File->Type == EfiOpenTftp) && (File->IsDirty)) {
+
+ TftpBufferSize = File->Size;
+ Status = EblMtftp (
+ EFI_PXE_BASE_CODE_TFTP_WRITE_FILE,
+ File->Buffer,
+ TRUE,
+ &TftpBufferSize,
+ NULL,
+ &File->ServerIp,
+ (UINT8 *)File->FileName,
+ NULL,
+ FALSE
+ );
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("TFTP error during APPLE_NSP_TFTP_WRITE_FILE: %r\n", Status);
+ return Status;
+ }
+ }
+
+ if ((File->Type == EfiOpenLoadFile) ||
+ ((File->Type == EfiOpenTftp) && (File->IsBufferValid == TRUE)) ||
+ ((File->Type == EfiOpenFirmwareVolume) && (File->IsBufferValid == TRUE))) {
+ EblFreePool(File->Buffer);
+ }
+
+ EblFreePool (File->DevicePath);
+ EblFreePool (File->DeviceName);
+ EblFreePool (File->FsFileInfo);
+ EblFreePool (File->FsInfo);
+
+ if (File->FsFileHandle != NULL) {
+ File->FsFileHandle->Close (File->FsFileHandle);
+ }
+
+ // Need to free File and it's Guard structures
+ EblFreePool (BASE_CR (File, EFI_OPEN_FILE_GUARD, File));
+ return EFI_SUCCESS;
+}
+
+
+/**
+Return the size of the file represented by Stream. Also return the current
+Seek position. Opening a file will enable a valid file size to be returned.
+LoadFile is an exception as a load file size is set to zero.
+
+@param Stream Open File Handle
+
+@return 0 Stream is not an Open File or a valid LoadFile handle
+
+**/
+UINTN
+EfiTell (
+ IN EFI_OPEN_FILE *File,
+ OUT EFI_LBA *CurrentPosition OPTIONAL
+ )
+{
+ EFI_STATUS Status;
+ UINT64 BufferSize = 0;
+
+ if (!FileHandleValid (File)) {
+ return 0;
+ }
+
+ if (CurrentPosition != NULL) {
+ *CurrentPosition = File->CurrentPosition;
+ }
+
+ if (File->Type == EfiOpenLoadFile) {
+ // Figure out the File->Size
+ File->Buffer = NULL;
+ File->Size = 0;
+ Status = File->LoadFile->LoadFile (File->LoadFile, File->DevicePath, FALSE, &File->Size, File->Buffer);
+ if (Status != EFI_BUFFER_TOO_SMALL) {
+ return 0;
+ }
+
+ File->MaxPosition = (UINT64)File->Size;
+ } else if (File->Type == EfiOpenTftp) {
+
+ Status = EblMtftp (
+ EFI_PXE_BASE_CODE_TFTP_GET_FILE_SIZE,
+ NULL,
+ FALSE,
+ &BufferSize,
+ NULL,
+ &File->ServerIp,
+ (UINT8 *)File->FileName,
+ NULL,
+ TRUE
+ );
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("TFTP error during APPLE_NSP_TFTP_GET_FILE_SIZE: %r\n", Status);
+ return 0;
+ }
+
+ File->Size = (UINTN)BufferSize;
+ File->MaxPosition = File->Size;
+ }
+
+ return File->Size;
+}
+
+
+/**
+Seek to the Offset location in the file. LoadFile and FV device types do
+not support EfiSeek(). It is not possible to grow the file size using
+EfiSeek().
+
+SeekType defines how use Offset to calculate the new file position:
+EfiSeekStart : Position = Offset
+EfiSeekCurrent: Position is Offset bytes from the current position
+EfiSeekEnd : Only supported if Offset is zero to seek to end of file.
+
+@param Stream Open File Handle
+@param Offset Offset to seek too.
+@param SeekType Type of seek to perform
+
+
+@return EFI_INVALID_PARAMETER Stream is not an Open File
+@return EFI_UNSUPPORTED LoadFile and FV do not support Seek
+@return EFI_NOT_FOUND Seek past the end of the file.
+@return EFI_SUCCESS Steam closed
+
+**/
+EFI_STATUS
+EfiSeek (
+ IN EFI_OPEN_FILE *File,
+ IN EFI_LBA Offset,
+ IN EFI_SEEK_TYPE SeekType
+ )
+{
+ EFI_STATUS Status;
+ UINT64 CurrentPosition;
+
+ if (!FileHandleValid (File)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (File->Type == EfiOpenLoadFile) {
+ // LoadFile does not support Seek
+ return EFI_UNSUPPORTED;
+ }
+
+ CurrentPosition = File->CurrentPosition;
+ switch (SeekType) {
+ case EfiSeekStart:
+ if (Offset > File->MaxPosition) {
+ return EFI_NOT_FOUND;
+ }
+ CurrentPosition = Offset;
+ break;
+
+ case EfiSeekCurrent:
+ if ((File->CurrentPosition + Offset) > File->MaxPosition) {
+ return EFI_NOT_FOUND;
+ }
+ CurrentPosition += Offset;
+ break;
+
+ case EfiSeekEnd:
+ if (Offset != 0) {
+ // We don't support growing file size via seeking past end of file
+ return EFI_UNSUPPORTED;
+ }
+ CurrentPosition = File->MaxPosition;
+ break;
+
+ default:
+ return EFI_NOT_FOUND;
+ }
+
+ Status = EFI_SUCCESS;
+ if (File->FsFileHandle != NULL) {
+ Status = File->FsFileHandle->SetPosition (File->FsFileHandle, CurrentPosition);
+ }
+
+ if (!EFI_ERROR (Status)) {
+ File->CurrentPosition = CurrentPosition;
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+CacheTftpFile (
+ IN OUT EFI_OPEN_FILE *File
+ )
+{
+ EFI_STATUS Status;
+ UINT64 TftpBufferSize;
+
+ if (File->IsBufferValid) {
+ return EFI_SUCCESS;
+ }
+
+ // Make sure the file size is set.
+ EfiTell (File, NULL);
+
+ //Allocate a buffer to hold the whole file.
+ File->Buffer = AllocatePool(File->Size);
+ if (File->Buffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ TftpBufferSize = File->Size;
+
+ Status = EblMtftp (
+ EFI_PXE_BASE_CODE_TFTP_READ_FILE,
+ File->Buffer,
+ FALSE,
+ &TftpBufferSize,
+ NULL,
+ &File->ServerIp,
+ (UINT8 *)File->FileName,
+ NULL,
+ FALSE);
+ if (EFI_ERROR(Status)) {
+ AsciiPrint("TFTP error during APPLE_NSP_TFTP_READ_FILE: %r\n", Status);
+ FreePool(File->Buffer);
+ return Status;
+ }
+
+ // Set the buffer valid flag.
+ File->IsBufferValid = TRUE;
+
+ return Status;
+}
+
+/**
+Read BufferSize bytes from the current location in the file. For load file,
+FV, and TFTP case you must read the entire file.
+
+@param Stream Open File Handle
+@param Buffer Caller allocated buffer.
+@param BufferSize Size of buffer in bytes.
+
+
+@return EFI_SUCCESS Stream is not an Open File
+@return EFI_END_OF_FILE Tried to read past the end of the file
+@return EFI_INVALID_PARAMETER Stream is not an open file handle
+@return EFI_BUFFER_TOO_SMALL Buffer is not big enough to do the read
+@return "other" Error returned from device read
+
+**/
+EFI_STATUS
+EfiRead (
+ IN EFI_OPEN_FILE *File,
+ OUT VOID *Buffer,
+ OUT UINTN *BufferSize
+ )
+{
+ EFI_STATUS Status;
+ UINT32 AuthenticationStatus;
+ EFI_DISK_IO_PROTOCOL *DiskIo;
+
+ if (!FileHandleValid (File)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Don't read past the end of the file.
+ if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
+ return EFI_END_OF_FILE;
+ }
+
+ switch (File->Type) {
+ case EfiOpenLoadFile:
+ // Figure out the File->Size
+ EfiTell (File, NULL);
+
+ Status = File->LoadFile->LoadFile (File->LoadFile, File->DevicePath, FALSE, BufferSize, Buffer);
+ break;
+
+ case EfiOpenFirmwareVolume:
+ if (CompareGuid (&File->FvNameGuid, &gZeroGuid)) {
+ // This is the entire FV device, so treat like a memory buffer
+ CopyMem (Buffer, (VOID *)(UINTN)(File->FvStart + File->CurrentPosition), *BufferSize);
+ File->CurrentPosition += *BufferSize;
+ Status = EFI_SUCCESS;
+ } else {
+ if (File->Buffer == NULL) {
+ if (File->FvSectionType == EFI_SECTION_ALL) {
+ Status = File->Fv->ReadFile (
+ File->Fv,
+ &File->FvNameGuid,
+ (VOID **)&File->Buffer,
+ &File->Size,
+ &File->FvType,
+ &File->FvAttributes,
+ &AuthenticationStatus
+ );
+ } else {
+ Status = File->Fv->ReadSection (
+ File->Fv,
+ &File->FvNameGuid,
+ File->FvSectionType,
+ 0,
+ (VOID **)&File->Buffer,
+ &File->Size,
+ &AuthenticationStatus
+ );
+ }
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ File->IsBufferValid = TRUE;
+ }
+ // Operate on the cached buffer so Seek will work
+ CopyMem (Buffer, File->Buffer + File->CurrentPosition, *BufferSize);
+ File->CurrentPosition += *BufferSize;
+ Status = EFI_SUCCESS;
+ }
+ break;
+
+ case EfiOpenMemoryBuffer:
+ CopyMem (Buffer, File->Buffer + File->CurrentPosition, *BufferSize);
+ File->CurrentPosition += *BufferSize;
+ Status = EFI_SUCCESS;
+ break;
+
+ case EfiOpenFileSystem:
+ Status = File->FsFileHandle->Read (File->FsFileHandle, BufferSize, Buffer);
+ File->CurrentPosition += *BufferSize;
+ break;
+
+ case EfiOpenBlockIo:
+ Status = gBS->HandleProtocol(File->EfiHandle, &gEfiDiskIoProtocolGuid, (VOID **)&DiskIo);
+ if (!EFI_ERROR(Status)) {
+ Status = DiskIo->ReadDisk(DiskIo, File->FsBlockIoMedia->MediaId, File->DiskOffset + File->CurrentPosition, *BufferSize, Buffer);
+ }
+ File->CurrentPosition += *BufferSize;
+ break;
+
+ case EfiOpenTftp:
+ // Cache the file if it hasn't been cached yet.
+ if (File->IsBufferValid == FALSE) {
+ Status = CacheTftpFile (File);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+
+ // Copy out the requested data
+ CopyMem (Buffer, File->Buffer + File->CurrentPosition, *BufferSize);
+ File->CurrentPosition += *BufferSize;
+
+ Status = EFI_SUCCESS;
+ break;
+
+ default:
+ return EFI_INVALID_PARAMETER;
+ };
+
+ return Status;
+}
+
+
+/**
+Read the entire file into a buffer. This routine allocates the buffer and
+returns it to the user full of the read data.
+
+This is very useful for load file where it's hard to know how big the buffer
+must be.
+
+@param Stream Open File Handle
+@param Buffer Pointer to buffer to return.
+@param BufferSize Pointer to Size of buffer return..
+
+
+@return EFI_SUCCESS Stream is not an Open File
+@return EFI_END_OF_FILE Tried to read past the end of the file
+@return EFI_INVALID_PARAMETER Stream is not an open file handle
+@return EFI_BUFFER_TOO_SMALL Buffer is not big enough to do the read
+@return "other" Error returned from device read
+
+**/
+EFI_STATUS
+EfiReadAllocatePool (
+ IN EFI_OPEN_FILE *File,
+ OUT VOID **Buffer,
+ OUT UINTN *BufferSize
+ )
+{
+ if (!FileHandleValid (File)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Loadfile defers file size determination on Open so use tell to find it
+ EfiTell (File, NULL);
+
+ *BufferSize = File->Size;
+ *Buffer = AllocatePool (*BufferSize);
+ if (*Buffer == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ return EfiRead (File, *Buffer, BufferSize);
+}
+
+
+/**
+Write data back to the file. For TFTP case you must write the entire file.
+
+@param Stream Open File Handle
+@param Buffer Pointer to buffer to return.
+@param BufferSize Pointer to Size of buffer return..
+
+
+@return EFI_SUCCESS Stream is not an Open File
+@return EFI_END_OF_FILE Tried to read past the end of the file
+@return EFI_INVALID_PARAMETER Stream is not an open file handle
+@return EFI_BUFFER_TOO_SMALL Buffer is not big enough to do the read
+@return "other" Error returned from device write
+
+**/
+EFI_STATUS
+EfiWrite (
+ IN EFI_OPEN_FILE *File,
+ OUT VOID *Buffer,
+ OUT UINTN *BufferSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_FV_WRITE_FILE_DATA FileData;
+ EFI_DISK_IO_PROTOCOL *DiskIo;
+
+ if (!FileHandleValid (File)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ switch (File->Type) {
+ case EfiOpenMemoryBuffer:
+ if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
+ return EFI_END_OF_FILE;
+ }
+
+ CopyMem (File->Buffer + File->CurrentPosition, Buffer, *BufferSize);
+ File->CurrentPosition += *BufferSize;
+ Status = EFI_SUCCESS;
+
+ case EfiOpenLoadFile:
+ // LoadFile device is read only be definition
+ Status = EFI_UNSUPPORTED;
+
+ case EfiOpenFirmwareVolume:
+ if (File->FvSectionType != EFI_SECTION_ALL) {
+ // Writes not support to a specific section. You have to update entire file
+ return EFI_UNSUPPORTED;
+ }
+
+ FileData.NameGuid = &(File->FvNameGuid);
+ FileData.Type = File->FvType;
+ FileData.FileAttributes = File->FvAttributes;
+ FileData.Buffer = Buffer;
+ FileData.BufferSize = (UINT32)*BufferSize;
+ Status = File->Fv->WriteFile (File->Fv, 1, EFI_FV_UNRELIABLE_WRITE, &FileData);
+ break;
+
+ case EfiOpenFileSystem:
+ Status = File->FsFileHandle->Write (File->FsFileHandle, BufferSize, Buffer);
+ File->CurrentPosition += *BufferSize;
+ break;
+
+ case EfiOpenBlockIo:
+ if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
+ return EFI_END_OF_FILE;
+ }
+
+ Status = gBS->HandleProtocol (File->EfiHandle, &gEfiDiskIoProtocolGuid, (VOID **)&DiskIo);
+ if (!EFI_ERROR(Status)) {
+ Status = DiskIo->WriteDisk (DiskIo, File->FsBlockIoMedia->MediaId, File->DiskOffset + File->CurrentPosition, *BufferSize, Buffer);
+ }
+ File->CurrentPosition += *BufferSize;
+ break;
+
+ case EfiOpenTftp:
+ // Cache the file if it hasn't been cached yet.
+ if (File->IsBufferValid == FALSE) {
+ Status = CacheTftpFile(File);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ }
+
+ // Don't overwrite the buffer
+ if ((File->CurrentPosition + *BufferSize) > File->MaxPosition) {
+ UINT8 *TempBuffer;
+
+ TempBuffer = File->Buffer;
+
+ File->Buffer = AllocatePool ((UINTN)(File->CurrentPosition + *BufferSize));
+ if (File->Buffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ CopyMem (File->Buffer, TempBuffer, File->Size);
+
+ FreePool (TempBuffer);
+
+ File->Size = (UINTN)(File->CurrentPosition + *BufferSize);
+ File->MaxPosition = (UINT64)File->Size;
+ }
+
+ // Copy in the requested data
+ CopyMem (File->Buffer + File->CurrentPosition, Buffer, *BufferSize);
+ File->CurrentPosition += *BufferSize;
+
+ // Mark the file dirty
+ File->IsDirty = TRUE;
+
+ Status = EFI_SUCCESS;
+ break;
+
+ default:
+ Status = EFI_INVALID_PARAMETER;
+ };
+
+ return Status;
+}
+
+
+/**
+Given Cwd expand Path to remove .. and replace them with real
+directory names.
+
+@param Cwd Current Working Directory
+@param Path Path to expand
+
+@return NULL Cwd or Path are not valid
+@return 'other' Path with .. expanded
+
+**/
+CHAR8 *
+ExpandPath (
+ IN CHAR8 *Cwd,
+ IN CHAR8 *Path
+ )
+{
+ CHAR8 *NewPath;
+ CHAR8 *Work, *Start, *End;
+ UINTN StrLen;
+ INTN i;
+
+ if (Cwd == NULL || Path == NULL) {
+ return NULL;
+ }
+
+ StrLen = AsciiStrSize (Cwd);
+ if (StrLen <= 2) {
+ // Smallest valid path is 1 char and a null
+ return NULL;
+ }
+
+ StrLen = AsciiStrSize (Path);
+ NewPath = AllocatePool (AsciiStrSize (Cwd) + StrLen + 1);
+ if (NewPath == NULL) {
+ return NULL;
+ }
+ AsciiStrCpy (NewPath, Cwd);
+
+ End = Path + StrLen;
+ for (Start = Path ;;) {
+ Work = AsciiStrStr (Start, "..") ;
+ if (Work == NULL) {
+ // Remaining part of Path contains no more ..
+ break;
+ }
+
+ // append path prior to ..
+ AsciiStrnCat (NewPath, Start, Work - Start);
+ StrLen = AsciiStrLen (NewPath);
+ for (i = StrLen; i >= 0; i--) {
+ if (NewPath[i] == ':') {
+ // too many ..
+ return NULL;
+ }
+ if (NewPath[i] == '/' || NewPath[i] == '\\') {
+ if ((i > 0) && (NewPath[i-1] == ':')) {
+ // leave the / before a :
+ NewPath[i+1] = '\0';
+ } else {
+ // replace / will Null to remove trailing file/dir reference
+ NewPath[i] = '\0';
+ }
+ break;
+ }
+ }
+
+ Start = Work + 3;
+ }
+
+ // Handle the path that remains after the ..
+ AsciiStrnCat (NewPath, Start, End - Start);
+
+ return NewPath;
+}
+
+
+/**
+Set the Current Working Directory (CWD). If a call is made to EfiOpen () and
+the path does not contain a device name, The CWD is prepended to the path.
+
+@param Cwd Current Working Directory to set
+
+
+@return EFI_SUCCESS CWD is set
+@return EFI_INVALID_PARAMETER Cwd is not a valid device:path
+
+**/
+EFI_STATUS
+EfiSetCwd (
+ IN CHAR8 *Cwd
+ )
+{
+ EFI_OPEN_FILE *File;
+ UINTN Len;
+ CHAR8 *Path;
+
+ if (Cwd == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (AsciiStrCmp (Cwd, ".") == 0) {
+ // cd . is a no-op
+ return EFI_SUCCESS;
+ }
+
+ Path = Cwd;
+ if (AsciiStrStr (Cwd, "..") != NULL) {
+ if (gCwd == NULL) {
+ // no parent
+ return EFI_SUCCESS;
+ }
+
+ Len = AsciiStrLen (gCwd);
+ if ((gCwd[Len-2] == ':') && ((gCwd[Len-1] == '/') || (gCwd[Len-1] == '\\'))) {
+ // parent is device so nothing to do
+ return EFI_SUCCESS;
+ }
+
+ // Expand .. in Cwd, given we know current working directory
+ Path = ExpandPath (gCwd, Cwd);
+ if (Path == NULL) {
+ return EFI_NOT_FOUND;
+ }
+ }
+
+ File = EfiOpen (Path, EFI_FILE_MODE_READ, 0);
+ if (File == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (gCwd != NULL) {
+ FreePool (gCwd);
+ }
+
+ // Use the info returned from EfiOpen as it can add in CWD if needed. So Cwd could be
+ // relative to the current gCwd or not.
+ gCwd = AllocatePool (AsciiStrSize (File->DeviceName) + AsciiStrSize (File->FileName) + 10);
+ if (gCwd == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ AsciiStrCpy (gCwd, File->DeviceName);
+ if (File->FileName == NULL) {
+ AsciiStrCat (gCwd, ":\\");
+ } else {
+ AsciiStrCat (gCwd, ":");
+ AsciiStrCat (gCwd, File->FileName);
+ }
+
+
+ EfiClose (File);
+ if (Path != Cwd) {
+ FreePool (Path);
+ }
+ return EFI_SUCCESS;
+}
+
+
+/**
+Set the Current Working Directory (CWD). If a call is made to EfiOpen () and
+the path does not contain a device name, The CWD is prepended to the path.
+The CWD buffer is only valid until a new call is made to EfiSetCwd(). After
+a call to EfiSetCwd() it is not legal to use the pointer returned by
+this function.
+
+@param Cwd Current Working Directory
+
+
+@return "" No CWD set
+@return 'other' Returns buffer that contains CWD.
+
+**/
+CHAR8 *
+EfiGetCwd (
+ VOID
+ )
+{
+ if (gCwd == NULL) {
+ return "";
+ }
+ return gCwd;
+}
+
+
diff --git a/EmbeddedPkg/Library/FdtLib/fdt.c b/EmbeddedPkg/Library/FdtLib/fdt.c
index e56833ae9..151fcb2ab 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt.c
@@ -1,222 +1,222 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-int fdt_check_header(const void *fdt)
-{
- if (fdt_magic(fdt) == FDT_MAGIC) {
- /* Complete tree */
- if (fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION)
- return -FDT_ERR_BADVERSION;
- if (fdt_last_comp_version(fdt) > FDT_LAST_SUPPORTED_VERSION)
- return -FDT_ERR_BADVERSION;
- } else if (fdt_magic(fdt) == FDT_SW_MAGIC) {
- /* Unfinished sequential-write blob */
- if (fdt_size_dt_struct(fdt) == 0)
- return -FDT_ERR_BADSTATE;
- } else {
- return -FDT_ERR_BADMAGIC;
- }
-
- return 0;
-}
-
-const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
-{
- const char *p;
-
- if (fdt_version(fdt) >= 0x11)
- if (((offset + len) < offset)
- || ((offset + len) > fdt_size_dt_struct(fdt)))
- return NULL;
-
- p = _fdt_offset_ptr(fdt, offset);
-
- if (p + len < p)
- return NULL;
- return p;
-}
-
-uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
-{
- const uint32_t *tagp, *lenp;
- uint32_t tag;
- int offset = startoffset;
- const char *p;
-
- *nextoffset = -FDT_ERR_TRUNCATED;
- tagp = fdt_offset_ptr(fdt, offset, FDT_TAGSIZE);
- if (!tagp)
- return FDT_END; /* premature end */
- tag = fdt32_to_cpu(*tagp);
- offset += FDT_TAGSIZE;
-
- *nextoffset = -FDT_ERR_BADSTRUCTURE;
- switch (tag) {
- case FDT_BEGIN_NODE:
- /* skip name */
- do {
- p = fdt_offset_ptr(fdt, offset++, 1);
- } while (p && (*p != '\0'));
- if (!p)
- return FDT_END; /* premature end */
- break;
-
- case FDT_PROP:
- lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
- if (!lenp)
- return FDT_END; /* premature end */
- /* skip-name offset, length and value */
- offset += sizeof(struct fdt_property) - FDT_TAGSIZE
- + fdt32_to_cpu(*lenp);
- break;
-
- case FDT_END:
- case FDT_END_NODE:
- case FDT_NOP:
- break;
-
- default:
- return FDT_END;
- }
-
- if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
- return FDT_END; /* premature end */
-
- *nextoffset = FDT_TAGALIGN(offset);
- return tag;
-}
-
-int _fdt_check_node_offset(const void *fdt, int offset)
-{
- if ((offset < 0) || (offset % FDT_TAGSIZE)
- || (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE))
- return -FDT_ERR_BADOFFSET;
-
- return offset;
-}
-
-int _fdt_check_prop_offset(const void *fdt, int offset)
-{
- if ((offset < 0) || (offset % FDT_TAGSIZE)
- || (fdt_next_tag(fdt, offset, &offset) != FDT_PROP))
- return -FDT_ERR_BADOFFSET;
-
- return offset;
-}
-
-int fdt_next_node(const void *fdt, int offset, int *depth)
-{
- int nextoffset = 0;
- uint32_t tag;
-
- if (offset >= 0)
- if ((nextoffset = _fdt_check_node_offset(fdt, offset)) < 0)
- return nextoffset;
-
- do {
- offset = nextoffset;
- tag = fdt_next_tag(fdt, offset, &nextoffset);
-
- switch (tag) {
- case FDT_PROP:
- case FDT_NOP:
- break;
-
- case FDT_BEGIN_NODE:
- if (depth)
- (*depth)++;
- break;
-
- case FDT_END_NODE:
- if (depth && ((--(*depth)) < 0))
- return nextoffset;
- break;
-
- case FDT_END:
- if ((nextoffset >= 0)
- || ((nextoffset == -FDT_ERR_TRUNCATED) && !depth))
- return -FDT_ERR_NOTFOUND;
- else
- return nextoffset;
- }
- } while (tag != FDT_BEGIN_NODE);
-
- return offset;
-}
-
-const char *_fdt_find_string(const char *strtab, int tabsize, const char *s)
-{
- int len = strlen(s) + 1;
- const char *last = strtab + tabsize - len;
- const char *p;
-
- for (p = strtab; p <= last; p++)
- if (memcmp(p, s, len) == 0)
- return p;
- return NULL;
-}
-
-int fdt_move(const void *fdt, void *buf, int bufsize)
-{
- FDT_CHECK_HEADER(fdt);
-
- if (fdt_totalsize(fdt) > bufsize)
- return -FDT_ERR_NOSPACE;
-
- memmove(buf, fdt, fdt_totalsize(fdt));
- return 0;
-}
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+int fdt_check_header(const void *fdt)
+{
+ if (fdt_magic(fdt) == FDT_MAGIC) {
+ /* Complete tree */
+ if (fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION)
+ return -FDT_ERR_BADVERSION;
+ if (fdt_last_comp_version(fdt) > FDT_LAST_SUPPORTED_VERSION)
+ return -FDT_ERR_BADVERSION;
+ } else if (fdt_magic(fdt) == FDT_SW_MAGIC) {
+ /* Unfinished sequential-write blob */
+ if (fdt_size_dt_struct(fdt) == 0)
+ return -FDT_ERR_BADSTATE;
+ } else {
+ return -FDT_ERR_BADMAGIC;
+ }
+
+ return 0;
+}
+
+const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
+{
+ const char *p;
+
+ if (fdt_version(fdt) >= 0x11)
+ if (((offset + len) < offset)
+ || ((offset + len) > fdt_size_dt_struct(fdt)))
+ return NULL;
+
+ p = _fdt_offset_ptr(fdt, offset);
+
+ if (p + len < p)
+ return NULL;
+ return p;
+}
+
+uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
+{
+ const uint32_t *tagp, *lenp;
+ uint32_t tag;
+ int offset = startoffset;
+ const char *p;
+
+ *nextoffset = -FDT_ERR_TRUNCATED;
+ tagp = fdt_offset_ptr(fdt, offset, FDT_TAGSIZE);
+ if (!tagp)
+ return FDT_END; /* premature end */
+ tag = fdt32_to_cpu(*tagp);
+ offset += FDT_TAGSIZE;
+
+ *nextoffset = -FDT_ERR_BADSTRUCTURE;
+ switch (tag) {
+ case FDT_BEGIN_NODE:
+ /* skip name */
+ do {
+ p = fdt_offset_ptr(fdt, offset++, 1);
+ } while (p && (*p != '\0'));
+ if (!p)
+ return FDT_END; /* premature end */
+ break;
+
+ case FDT_PROP:
+ lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
+ if (!lenp)
+ return FDT_END; /* premature end */
+ /* skip-name offset, length and value */
+ offset += sizeof(struct fdt_property) - FDT_TAGSIZE
+ + fdt32_to_cpu(*lenp);
+ break;
+
+ case FDT_END:
+ case FDT_END_NODE:
+ case FDT_NOP:
+ break;
+
+ default:
+ return FDT_END;
+ }
+
+ if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
+ return FDT_END; /* premature end */
+
+ *nextoffset = FDT_TAGALIGN(offset);
+ return tag;
+}
+
+int _fdt_check_node_offset(const void *fdt, int offset)
+{
+ if ((offset < 0) || (offset % FDT_TAGSIZE)
+ || (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE))
+ return -FDT_ERR_BADOFFSET;
+
+ return offset;
+}
+
+int _fdt_check_prop_offset(const void *fdt, int offset)
+{
+ if ((offset < 0) || (offset % FDT_TAGSIZE)
+ || (fdt_next_tag(fdt, offset, &offset) != FDT_PROP))
+ return -FDT_ERR_BADOFFSET;
+
+ return offset;
+}
+
+int fdt_next_node(const void *fdt, int offset, int *depth)
+{
+ int nextoffset = 0;
+ uint32_t tag;
+
+ if (offset >= 0)
+ if ((nextoffset = _fdt_check_node_offset(fdt, offset)) < 0)
+ return nextoffset;
+
+ do {
+ offset = nextoffset;
+ tag = fdt_next_tag(fdt, offset, &nextoffset);
+
+ switch (tag) {
+ case FDT_PROP:
+ case FDT_NOP:
+ break;
+
+ case FDT_BEGIN_NODE:
+ if (depth)
+ (*depth)++;
+ break;
+
+ case FDT_END_NODE:
+ if (depth && ((--(*depth)) < 0))
+ return nextoffset;
+ break;
+
+ case FDT_END:
+ if ((nextoffset >= 0)
+ || ((nextoffset == -FDT_ERR_TRUNCATED) && !depth))
+ return -FDT_ERR_NOTFOUND;
+ else
+ return nextoffset;
+ }
+ } while (tag != FDT_BEGIN_NODE);
+
+ return offset;
+}
+
+const char *_fdt_find_string(const char *strtab, int tabsize, const char *s)
+{
+ int len = strlen(s) + 1;
+ const char *last = strtab + tabsize - len;
+ const char *p;
+
+ for (p = strtab; p <= last; p++)
+ if (memcmp(p, s, len) == 0)
+ return p;
+ return NULL;
+}
+
+int fdt_move(const void *fdt, void *buf, int bufsize)
+{
+ FDT_CHECK_HEADER(fdt);
+
+ if (fdt_totalsize(fdt) > bufsize)
+ return -FDT_ERR_NOSPACE;
+
+ memmove(buf, fdt, fdt_totalsize(fdt));
+ return 0;
+}
diff --git a/EmbeddedPkg/Library/FdtLib/fdt_empty_tree.c b/EmbeddedPkg/Library/FdtLib/fdt_empty_tree.c
index f72d13b1d..f00a8991d 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt_empty_tree.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt_empty_tree.c
@@ -1,84 +1,84 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2012 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-int fdt_create_empty_tree(void *buf, int bufsize)
-{
- int err;
-
- err = fdt_create(buf, bufsize);
- if (err)
- return err;
-
- err = fdt_finish_reservemap(buf);
- if (err)
- return err;
-
- err = fdt_begin_node(buf, "");
- if (err)
- return err;
-
- err = fdt_end_node(buf);
- if (err)
- return err;
-
- err = fdt_finish(buf);
- if (err)
- return err;
-
- return fdt_open_into(buf, buf, bufsize);
-}
-
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2012 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+int fdt_create_empty_tree(void *buf, int bufsize)
+{
+ int err;
+
+ err = fdt_create(buf, bufsize);
+ if (err)
+ return err;
+
+ err = fdt_finish_reservemap(buf);
+ if (err)
+ return err;
+
+ err = fdt_begin_node(buf, "");
+ if (err)
+ return err;
+
+ err = fdt_end_node(buf);
+ if (err)
+ return err;
+
+ err = fdt_finish(buf);
+ if (err)
+ return err;
+
+ return fdt_open_into(buf, buf, bufsize);
+}
+
diff --git a/EmbeddedPkg/Library/FdtLib/fdt_ro.c b/EmbeddedPkg/Library/FdtLib/fdt_ro.c
index 95fdbeadd..9ae6b5ecc 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt_ro.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt_ro.c
@@ -1,575 +1,575 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-static int _fdt_nodename_eq(const void *fdt, int offset,
- const char *s, int len)
-{
- const char *p = fdt_offset_ptr(fdt, offset + FDT_TAGSIZE, len+1);
-
- if (! p)
- /* short match */
- return 0;
-
- if (memcmp(p, s, len) != 0)
- return 0;
-
- if (p[len] == '\0')
- return 1;
- else if (!memchr(s, '@', len) && (p[len] == '@'))
- return 1;
- else
- return 0;
-}
-
-const char *fdt_string(const void *fdt, int stroffset)
-{
- return (const char *)fdt + fdt_off_dt_strings(fdt) + stroffset;
-}
-
-static int _fdt_string_eq(const void *fdt, int stroffset,
- const char *s, int len)
-{
- const char *p = fdt_string(fdt, stroffset);
-
- return (strlen(p) == len) && (memcmp(p, s, len) == 0);
-}
-
-int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size)
-{
- FDT_CHECK_HEADER(fdt);
- *address = fdt64_to_cpu(_fdt_mem_rsv(fdt, n)->address);
- *size = fdt64_to_cpu(_fdt_mem_rsv(fdt, n)->size);
- return 0;
-}
-
-int fdt_num_mem_rsv(const void *fdt)
-{
- int i = 0;
-
- while (fdt64_to_cpu(_fdt_mem_rsv(fdt, i)->size) != 0)
- i++;
- return i;
-}
-
-static int _nextprop(const void *fdt, int offset)
-{
- uint32_t tag;
- int nextoffset;
-
- do {
- tag = fdt_next_tag(fdt, offset, &nextoffset);
-
- switch (tag) {
- case FDT_END:
- if (nextoffset >= 0)
- return -FDT_ERR_BADSTRUCTURE;
- else
- return nextoffset;
-
- case FDT_PROP:
- return offset;
- }
- offset = nextoffset;
- } while (tag == FDT_NOP);
-
- return -FDT_ERR_NOTFOUND;
-}
-
-int fdt_subnode_offset_namelen(const void *fdt, int offset,
- const char *name, int namelen)
-{
- int depth;
-
- FDT_CHECK_HEADER(fdt);
-
- for (depth = 0;
- (offset >= 0) && (depth >= 0);
- offset = fdt_next_node(fdt, offset, &depth))
- if ((depth == 1)
- && _fdt_nodename_eq(fdt, offset, name, namelen))
- return offset;
-
- if (depth < 0)
- return -FDT_ERR_NOTFOUND;
- return offset; /* error */
-}
-
-int fdt_subnode_offset(const void *fdt, int parentoffset,
- const char *name)
-{
- return fdt_subnode_offset_namelen(fdt, parentoffset, name, strlen(name));
-}
-
-int fdt_path_offset(const void *fdt, const char *path)
-{
- const char *end = path + strlen(path);
- const char *p = path;
- int offset = 0;
-
- FDT_CHECK_HEADER(fdt);
-
- /* see if we have an alias */
- if (*path != '/') {
- const char *q = strchr(path, '/');
-
- if (!q)
- q = end;
-
- p = fdt_get_alias_namelen(fdt, p, q - p);
- if (!p)
- return -FDT_ERR_BADPATH;
- offset = fdt_path_offset(fdt, p);
-
- p = q;
- }
-
- while (*p) {
- const char *q;
-
- while (*p == '/')
- p++;
- if (! *p)
- return offset;
- q = strchr(p, '/');
- if (! q)
- q = end;
-
- offset = fdt_subnode_offset_namelen(fdt, offset, p, q-p);
- if (offset < 0)
- return offset;
-
- p = q;
- }
-
- return offset;
-}
-
-const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
-{
- const struct fdt_node_header *nh = _fdt_offset_ptr(fdt, nodeoffset);
- int err;
-
- if (((err = fdt_check_header(fdt)) != 0)
- || ((err = _fdt_check_node_offset(fdt, nodeoffset)) < 0))
- goto fail;
-
- if (len)
- *len = strlen(nh->name);
-
- return nh->name;
-
- fail:
- if (len)
- *len = err;
- return NULL;
-}
-
-int fdt_first_property_offset(const void *fdt, int nodeoffset)
-{
- int offset;
-
- if ((offset = _fdt_check_node_offset(fdt, nodeoffset)) < 0)
- return offset;
-
- return _nextprop(fdt, offset);
-}
-
-int fdt_next_property_offset(const void *fdt, int offset)
-{
- if ((offset = _fdt_check_prop_offset(fdt, offset)) < 0)
- return offset;
-
- return _nextprop(fdt, offset);
-}
-
-const struct fdt_property *fdt_get_property_by_offset(const void *fdt,
- int offset,
- int *lenp)
-{
- int err;
- const struct fdt_property *prop;
-
- if ((err = _fdt_check_prop_offset(fdt, offset)) < 0) {
- if (lenp)
- *lenp = err;
- return NULL;
- }
-
- prop = _fdt_offset_ptr(fdt, offset);
-
- if (lenp)
- *lenp = fdt32_to_cpu(prop->len);
-
- return prop;
-}
-
-const struct fdt_property *fdt_get_property_namelen(const void *fdt,
- int offset,
- const char *name,
- int namelen, int *lenp)
-{
- for (offset = fdt_first_property_offset(fdt, offset);
- (offset >= 0);
- (offset = fdt_next_property_offset(fdt, offset))) {
- const struct fdt_property *prop;
-
- prop = fdt_get_property_by_offset(fdt, offset, lenp);
- if (!prop) {
- offset = -FDT_ERR_INTERNAL;
- break;
- }
- if (_fdt_string_eq(fdt, fdt32_to_cpu(prop->nameoff),
- name, namelen))
- return prop;
- }
-
- if (lenp)
- *lenp = offset;
- return NULL;
-}
-
-const struct fdt_property *fdt_get_property(const void *fdt,
- int nodeoffset,
- const char *name, int *lenp)
-{
- return fdt_get_property_namelen(fdt, nodeoffset, name,
- strlen(name), lenp);
-}
-
-const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
- const char *name, int namelen, int *lenp)
-{
- const struct fdt_property *prop;
-
- prop = fdt_get_property_namelen(fdt, nodeoffset, name, namelen, lenp);
- if (! prop)
- return NULL;
-
- return prop->data;
-}
-
-const void *fdt_getprop_by_offset(const void *fdt, int offset,
- const char **namep, int *lenp)
-{
- const struct fdt_property *prop;
-
- prop = fdt_get_property_by_offset(fdt, offset, lenp);
- if (!prop)
- return NULL;
- if (namep)
- *namep = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
- return prop->data;
-}
-
-const void *fdt_getprop(const void *fdt, int nodeoffset,
- const char *name, int *lenp)
-{
- return fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp);
-}
-
-uint32_t fdt_get_phandle(const void *fdt, int nodeoffset)
-{
- const uint32_t *php;
- int len;
-
- /* FIXME: This is a bit sub-optimal, since we potentially scan
- * over all the properties twice. */
- php = fdt_getprop(fdt, nodeoffset, "phandle", &len);
- if (!php || (len != sizeof(*php))) {
- php = fdt_getprop(fdt, nodeoffset, "linux,phandle", &len);
- if (!php || (len != sizeof(*php)))
- return 0;
- }
-
- return fdt32_to_cpu(*php);
-}
-
-const char *fdt_get_alias_namelen(const void *fdt,
- const char *name, int namelen)
-{
- int aliasoffset;
-
- aliasoffset = fdt_path_offset(fdt, "/aliases");
- if (aliasoffset < 0)
- return NULL;
-
- return fdt_getprop_namelen(fdt, aliasoffset, name, namelen, NULL);
-}
-
-const char *fdt_get_alias(const void *fdt, const char *name)
-{
- return fdt_get_alias_namelen(fdt, name, strlen(name));
-}
-
-int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
-{
- int pdepth = 0, p = 0;
- int offset, depth, namelen;
- const char *name;
-
- FDT_CHECK_HEADER(fdt);
-
- if (buflen < 2)
- return -FDT_ERR_NOSPACE;
-
- for (offset = 0, depth = 0;
- (offset >= 0) && (offset <= nodeoffset);
- offset = fdt_next_node(fdt, offset, &depth)) {
- while (pdepth > depth) {
- do {
- p--;
- } while (buf[p-1] != '/');
- pdepth--;
- }
-
- if (pdepth >= depth) {
- name = fdt_get_name(fdt, offset, &namelen);
- if (!name)
- return namelen;
- if ((p + namelen + 1) <= buflen) {
- memcpy(buf + p, name, namelen);
- p += namelen;
- buf[p++] = '/';
- pdepth++;
- }
- }
-
- if (offset == nodeoffset) {
- if (pdepth < (depth + 1))
- return -FDT_ERR_NOSPACE;
-
- if (p > 1) /* special case so that root path is "/", not "" */
- p--;
- buf[p] = '\0';
- return 0;
- }
- }
-
- if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))
- return -FDT_ERR_BADOFFSET;
- else if (offset == -FDT_ERR_BADOFFSET)
- return -FDT_ERR_BADSTRUCTURE;
-
- return offset; /* error from fdt_next_node() */
-}
-
-int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
- int supernodedepth, int *nodedepth)
-{
- int offset, depth;
- int supernodeoffset = -FDT_ERR_INTERNAL;
-
- FDT_CHECK_HEADER(fdt);
-
- if (supernodedepth < 0)
- return -FDT_ERR_NOTFOUND;
-
- for (offset = 0, depth = 0;
- (offset >= 0) && (offset <= nodeoffset);
- offset = fdt_next_node(fdt, offset, &depth)) {
- if (depth == supernodedepth)
- supernodeoffset = offset;
-
- if (offset == nodeoffset) {
- if (nodedepth)
- *nodedepth = depth;
-
- if (supernodedepth > depth)
- return -FDT_ERR_NOTFOUND;
- else
- return supernodeoffset;
- }
- }
-
- if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))
- return -FDT_ERR_BADOFFSET;
- else if (offset == -FDT_ERR_BADOFFSET)
- return -FDT_ERR_BADSTRUCTURE;
-
- return offset; /* error from fdt_next_node() */
-}
-
-int fdt_node_depth(const void *fdt, int nodeoffset)
-{
- int nodedepth;
- int err;
-
- err = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);
- if (err)
- return (err < 0) ? err : -FDT_ERR_INTERNAL;
- return nodedepth;
-}
-
-int fdt_parent_offset(const void *fdt, int nodeoffset)
-{
- int nodedepth = fdt_node_depth(fdt, nodeoffset);
-
- if (nodedepth < 0)
- return nodedepth;
- return fdt_supernode_atdepth_offset(fdt, nodeoffset,
- nodedepth - 1, NULL);
-}
-
-int fdt_node_offset_by_prop_value(const void *fdt, int startoffset,
- const char *propname,
- const void *propval, int proplen)
-{
- int offset;
- const void *val;
- int len;
-
- FDT_CHECK_HEADER(fdt);
-
- /* FIXME: The algorithm here is pretty horrible: we scan each
- * property of a node in fdt_getprop(), then if that didn't
- * find what we want, we scan over them again making our way
- * to the next node. Still it's the easiest to implement
- * approach; performance can come later. */
- for (offset = fdt_next_node(fdt, startoffset, NULL);
- offset >= 0;
- offset = fdt_next_node(fdt, offset, NULL)) {
- val = fdt_getprop(fdt, offset, propname, &len);
- if (val && (len == proplen)
- && (memcmp(val, propval, len) == 0))
- return offset;
- }
-
- return offset; /* error from fdt_next_node() */
-}
-
-int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle)
-{
- int offset;
-
- if ((phandle == 0) || (phandle == (uint32_t)-1))
- return -FDT_ERR_BADPHANDLE;
-
- FDT_CHECK_HEADER(fdt);
-
- /* FIXME: The algorithm here is pretty horrible: we
- * potentially scan each property of a node in
- * fdt_get_phandle(), then if that didn't find what
- * we want, we scan over them again making our way to the next
- * node. Still it's the easiest to implement approach;
- * performance can come later. */
- for (offset = fdt_next_node(fdt, -1, NULL);
- offset >= 0;
- offset = fdt_next_node(fdt, offset, NULL)) {
- if (fdt_get_phandle(fdt, offset) == phandle)
- return offset;
- }
-
- return offset; /* error from fdt_next_node() */
-}
-
-static int _fdt_stringlist_contains(const char *strlist, int listlen,
- const char *str)
-{
- int len = strlen(str);
- const char *p;
-
- while (listlen >= len) {
- if (memcmp(str, strlist, len+1) == 0)
- return 1;
- p = memchr(strlist, '\0', listlen);
- if (!p)
- return 0; /* malformed strlist.. */
- listlen -= (p-strlist) + 1;
- strlist = p + 1;
- }
- return 0;
-}
-
-int fdt_node_check_compatible(const void *fdt, int nodeoffset,
- const char *compatible)
-{
- const void *prop;
- int len;
-
- prop = fdt_getprop(fdt, nodeoffset, "compatible", &len);
- if (!prop)
- return len;
- if (_fdt_stringlist_contains(prop, len, compatible))
- return 0;
- else
- return 1;
-}
-
-int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
- const char *compatible)
-{
- int offset, err;
-
- FDT_CHECK_HEADER(fdt);
-
- /* FIXME: The algorithm here is pretty horrible: we scan each
- * property of a node in fdt_node_check_compatible(), then if
- * that didn't find what we want, we scan over them again
- * making our way to the next node. Still it's the easiest to
- * implement approach; performance can come later. */
- for (offset = fdt_next_node(fdt, startoffset, NULL);
- offset >= 0;
- offset = fdt_next_node(fdt, offset, NULL)) {
- err = fdt_node_check_compatible(fdt, offset, compatible);
- if ((err < 0) && (err != -FDT_ERR_NOTFOUND))
- return err;
- else if (err == 0)
- return offset;
- }
-
- return offset; /* error from fdt_next_node() */
-}
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+static int _fdt_nodename_eq(const void *fdt, int offset,
+ const char *s, int len)
+{
+ const char *p = fdt_offset_ptr(fdt, offset + FDT_TAGSIZE, len+1);
+
+ if (! p)
+ /* short match */
+ return 0;
+
+ if (memcmp(p, s, len) != 0)
+ return 0;
+
+ if (p[len] == '\0')
+ return 1;
+ else if (!memchr(s, '@', len) && (p[len] == '@'))
+ return 1;
+ else
+ return 0;
+}
+
+const char *fdt_string(const void *fdt, int stroffset)
+{
+ return (const char *)fdt + fdt_off_dt_strings(fdt) + stroffset;
+}
+
+static int _fdt_string_eq(const void *fdt, int stroffset,
+ const char *s, int len)
+{
+ const char *p = fdt_string(fdt, stroffset);
+
+ return (strlen(p) == len) && (memcmp(p, s, len) == 0);
+}
+
+int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size)
+{
+ FDT_CHECK_HEADER(fdt);
+ *address = fdt64_to_cpu(_fdt_mem_rsv(fdt, n)->address);
+ *size = fdt64_to_cpu(_fdt_mem_rsv(fdt, n)->size);
+ return 0;
+}
+
+int fdt_num_mem_rsv(const void *fdt)
+{
+ int i = 0;
+
+ while (fdt64_to_cpu(_fdt_mem_rsv(fdt, i)->size) != 0)
+ i++;
+ return i;
+}
+
+static int _nextprop(const void *fdt, int offset)
+{
+ uint32_t tag;
+ int nextoffset;
+
+ do {
+ tag = fdt_next_tag(fdt, offset, &nextoffset);
+
+ switch (tag) {
+ case FDT_END:
+ if (nextoffset >= 0)
+ return -FDT_ERR_BADSTRUCTURE;
+ else
+ return nextoffset;
+
+ case FDT_PROP:
+ return offset;
+ }
+ offset = nextoffset;
+ } while (tag == FDT_NOP);
+
+ return -FDT_ERR_NOTFOUND;
+}
+
+int fdt_subnode_offset_namelen(const void *fdt, int offset,
+ const char *name, int namelen)
+{
+ int depth;
+
+ FDT_CHECK_HEADER(fdt);
+
+ for (depth = 0;
+ (offset >= 0) && (depth >= 0);
+ offset = fdt_next_node(fdt, offset, &depth))
+ if ((depth == 1)
+ && _fdt_nodename_eq(fdt, offset, name, namelen))
+ return offset;
+
+ if (depth < 0)
+ return -FDT_ERR_NOTFOUND;
+ return offset; /* error */
+}
+
+int fdt_subnode_offset(const void *fdt, int parentoffset,
+ const char *name)
+{
+ return fdt_subnode_offset_namelen(fdt, parentoffset, name, strlen(name));
+}
+
+int fdt_path_offset(const void *fdt, const char *path)
+{
+ const char *end = path + strlen(path);
+ const char *p = path;
+ int offset = 0;
+
+ FDT_CHECK_HEADER(fdt);
+
+ /* see if we have an alias */
+ if (*path != '/') {
+ const char *q = strchr(path, '/');
+
+ if (!q)
+ q = end;
+
+ p = fdt_get_alias_namelen(fdt, p, q - p);
+ if (!p)
+ return -FDT_ERR_BADPATH;
+ offset = fdt_path_offset(fdt, p);
+
+ p = q;
+ }
+
+ while (*p) {
+ const char *q;
+
+ while (*p == '/')
+ p++;
+ if (! *p)
+ return offset;
+ q = strchr(p, '/');
+ if (! q)
+ q = end;
+
+ offset = fdt_subnode_offset_namelen(fdt, offset, p, q-p);
+ if (offset < 0)
+ return offset;
+
+ p = q;
+ }
+
+ return offset;
+}
+
+const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
+{
+ const struct fdt_node_header *nh = _fdt_offset_ptr(fdt, nodeoffset);
+ int err;
+
+ if (((err = fdt_check_header(fdt)) != 0)
+ || ((err = _fdt_check_node_offset(fdt, nodeoffset)) < 0))
+ goto fail;
+
+ if (len)
+ *len = strlen(nh->name);
+
+ return nh->name;
+
+ fail:
+ if (len)
+ *len = err;
+ return NULL;
+}
+
+int fdt_first_property_offset(const void *fdt, int nodeoffset)
+{
+ int offset;
+
+ if ((offset = _fdt_check_node_offset(fdt, nodeoffset)) < 0)
+ return offset;
+
+ return _nextprop(fdt, offset);
+}
+
+int fdt_next_property_offset(const void *fdt, int offset)
+{
+ if ((offset = _fdt_check_prop_offset(fdt, offset)) < 0)
+ return offset;
+
+ return _nextprop(fdt, offset);
+}
+
+const struct fdt_property *fdt_get_property_by_offset(const void *fdt,
+ int offset,
+ int *lenp)
+{
+ int err;
+ const struct fdt_property *prop;
+
+ if ((err = _fdt_check_prop_offset(fdt, offset)) < 0) {
+ if (lenp)
+ *lenp = err;
+ return NULL;
+ }
+
+ prop = _fdt_offset_ptr(fdt, offset);
+
+ if (lenp)
+ *lenp = fdt32_to_cpu(prop->len);
+
+ return prop;
+}
+
+const struct fdt_property *fdt_get_property_namelen(const void *fdt,
+ int offset,
+ const char *name,
+ int namelen, int *lenp)
+{
+ for (offset = fdt_first_property_offset(fdt, offset);
+ (offset >= 0);
+ (offset = fdt_next_property_offset(fdt, offset))) {
+ const struct fdt_property *prop;
+
+ prop = fdt_get_property_by_offset(fdt, offset, lenp);
+ if (!prop) {
+ offset = -FDT_ERR_INTERNAL;
+ break;
+ }
+ if (_fdt_string_eq(fdt, fdt32_to_cpu(prop->nameoff),
+ name, namelen))
+ return prop;
+ }
+
+ if (lenp)
+ *lenp = offset;
+ return NULL;
+}
+
+const struct fdt_property *fdt_get_property(const void *fdt,
+ int nodeoffset,
+ const char *name, int *lenp)
+{
+ return fdt_get_property_namelen(fdt, nodeoffset, name,
+ strlen(name), lenp);
+}
+
+const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
+ const char *name, int namelen, int *lenp)
+{
+ const struct fdt_property *prop;
+
+ prop = fdt_get_property_namelen(fdt, nodeoffset, name, namelen, lenp);
+ if (! prop)
+ return NULL;
+
+ return prop->data;
+}
+
+const void *fdt_getprop_by_offset(const void *fdt, int offset,
+ const char **namep, int *lenp)
+{
+ const struct fdt_property *prop;
+
+ prop = fdt_get_property_by_offset(fdt, offset, lenp);
+ if (!prop)
+ return NULL;
+ if (namep)
+ *namep = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
+ return prop->data;
+}
+
+const void *fdt_getprop(const void *fdt, int nodeoffset,
+ const char *name, int *lenp)
+{
+ return fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp);
+}
+
+uint32_t fdt_get_phandle(const void *fdt, int nodeoffset)
+{
+ const uint32_t *php;
+ int len;
+
+ /* FIXME: This is a bit sub-optimal, since we potentially scan
+ * over all the properties twice. */
+ php = fdt_getprop(fdt, nodeoffset, "phandle", &len);
+ if (!php || (len != sizeof(*php))) {
+ php = fdt_getprop(fdt, nodeoffset, "linux,phandle", &len);
+ if (!php || (len != sizeof(*php)))
+ return 0;
+ }
+
+ return fdt32_to_cpu(*php);
+}
+
+const char *fdt_get_alias_namelen(const void *fdt,
+ const char *name, int namelen)
+{
+ int aliasoffset;
+
+ aliasoffset = fdt_path_offset(fdt, "/aliases");
+ if (aliasoffset < 0)
+ return NULL;
+
+ return fdt_getprop_namelen(fdt, aliasoffset, name, namelen, NULL);
+}
+
+const char *fdt_get_alias(const void *fdt, const char *name)
+{
+ return fdt_get_alias_namelen(fdt, name, strlen(name));
+}
+
+int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
+{
+ int pdepth = 0, p = 0;
+ int offset, depth, namelen;
+ const char *name;
+
+ FDT_CHECK_HEADER(fdt);
+
+ if (buflen < 2)
+ return -FDT_ERR_NOSPACE;
+
+ for (offset = 0, depth = 0;
+ (offset >= 0) && (offset <= nodeoffset);
+ offset = fdt_next_node(fdt, offset, &depth)) {
+ while (pdepth > depth) {
+ do {
+ p--;
+ } while (buf[p-1] != '/');
+ pdepth--;
+ }
+
+ if (pdepth >= depth) {
+ name = fdt_get_name(fdt, offset, &namelen);
+ if (!name)
+ return namelen;
+ if ((p + namelen + 1) <= buflen) {
+ memcpy(buf + p, name, namelen);
+ p += namelen;
+ buf[p++] = '/';
+ pdepth++;
+ }
+ }
+
+ if (offset == nodeoffset) {
+ if (pdepth < (depth + 1))
+ return -FDT_ERR_NOSPACE;
+
+ if (p > 1) /* special case so that root path is "/", not "" */
+ p--;
+ buf[p] = '\0';
+ return 0;
+ }
+ }
+
+ if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))
+ return -FDT_ERR_BADOFFSET;
+ else if (offset == -FDT_ERR_BADOFFSET)
+ return -FDT_ERR_BADSTRUCTURE;
+
+ return offset; /* error from fdt_next_node() */
+}
+
+int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
+ int supernodedepth, int *nodedepth)
+{
+ int offset, depth;
+ int supernodeoffset = -FDT_ERR_INTERNAL;
+
+ FDT_CHECK_HEADER(fdt);
+
+ if (supernodedepth < 0)
+ return -FDT_ERR_NOTFOUND;
+
+ for (offset = 0, depth = 0;
+ (offset >= 0) && (offset <= nodeoffset);
+ offset = fdt_next_node(fdt, offset, &depth)) {
+ if (depth == supernodedepth)
+ supernodeoffset = offset;
+
+ if (offset == nodeoffset) {
+ if (nodedepth)
+ *nodedepth = depth;
+
+ if (supernodedepth > depth)
+ return -FDT_ERR_NOTFOUND;
+ else
+ return supernodeoffset;
+ }
+ }
+
+ if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))
+ return -FDT_ERR_BADOFFSET;
+ else if (offset == -FDT_ERR_BADOFFSET)
+ return -FDT_ERR_BADSTRUCTURE;
+
+ return offset; /* error from fdt_next_node() */
+}
+
+int fdt_node_depth(const void *fdt, int nodeoffset)
+{
+ int nodedepth;
+ int err;
+
+ err = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);
+ if (err)
+ return (err < 0) ? err : -FDT_ERR_INTERNAL;
+ return nodedepth;
+}
+
+int fdt_parent_offset(const void *fdt, int nodeoffset)
+{
+ int nodedepth = fdt_node_depth(fdt, nodeoffset);
+
+ if (nodedepth < 0)
+ return nodedepth;
+ return fdt_supernode_atdepth_offset(fdt, nodeoffset,
+ nodedepth - 1, NULL);
+}
+
+int fdt_node_offset_by_prop_value(const void *fdt, int startoffset,
+ const char *propname,
+ const void *propval, int proplen)
+{
+ int offset;
+ const void *val;
+ int len;
+
+ FDT_CHECK_HEADER(fdt);
+
+ /* FIXME: The algorithm here is pretty horrible: we scan each
+ * property of a node in fdt_getprop(), then if that didn't
+ * find what we want, we scan over them again making our way
+ * to the next node. Still it's the easiest to implement
+ * approach; performance can come later. */
+ for (offset = fdt_next_node(fdt, startoffset, NULL);
+ offset >= 0;
+ offset = fdt_next_node(fdt, offset, NULL)) {
+ val = fdt_getprop(fdt, offset, propname, &len);
+ if (val && (len == proplen)
+ && (memcmp(val, propval, len) == 0))
+ return offset;
+ }
+
+ return offset; /* error from fdt_next_node() */
+}
+
+int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle)
+{
+ int offset;
+
+ if ((phandle == 0) || (phandle == (uint32_t)-1))
+ return -FDT_ERR_BADPHANDLE;
+
+ FDT_CHECK_HEADER(fdt);
+
+ /* FIXME: The algorithm here is pretty horrible: we
+ * potentially scan each property of a node in
+ * fdt_get_phandle(), then if that didn't find what
+ * we want, we scan over them again making our way to the next
+ * node. Still it's the easiest to implement approach;
+ * performance can come later. */
+ for (offset = fdt_next_node(fdt, -1, NULL);
+ offset >= 0;
+ offset = fdt_next_node(fdt, offset, NULL)) {
+ if (fdt_get_phandle(fdt, offset) == phandle)
+ return offset;
+ }
+
+ return offset; /* error from fdt_next_node() */
+}
+
+static int _fdt_stringlist_contains(const char *strlist, int listlen,
+ const char *str)
+{
+ int len = strlen(str);
+ const char *p;
+
+ while (listlen >= len) {
+ if (memcmp(str, strlist, len+1) == 0)
+ return 1;
+ p = memchr(strlist, '\0', listlen);
+ if (!p)
+ return 0; /* malformed strlist.. */
+ listlen -= (p-strlist) + 1;
+ strlist = p + 1;
+ }
+ return 0;
+}
+
+int fdt_node_check_compatible(const void *fdt, int nodeoffset,
+ const char *compatible)
+{
+ const void *prop;
+ int len;
+
+ prop = fdt_getprop(fdt, nodeoffset, "compatible", &len);
+ if (!prop)
+ return len;
+ if (_fdt_stringlist_contains(prop, len, compatible))
+ return 0;
+ else
+ return 1;
+}
+
+int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
+ const char *compatible)
+{
+ int offset, err;
+
+ FDT_CHECK_HEADER(fdt);
+
+ /* FIXME: The algorithm here is pretty horrible: we scan each
+ * property of a node in fdt_node_check_compatible(), then if
+ * that didn't find what we want, we scan over them again
+ * making our way to the next node. Still it's the easiest to
+ * implement approach; performance can come later. */
+ for (offset = fdt_next_node(fdt, startoffset, NULL);
+ offset >= 0;
+ offset = fdt_next_node(fdt, offset, NULL)) {
+ err = fdt_node_check_compatible(fdt, offset, compatible);
+ if ((err < 0) && (err != -FDT_ERR_NOTFOUND))
+ return err;
+ else if (err == 0)
+ return offset;
+ }
+
+ return offset; /* error from fdt_next_node() */
+}
diff --git a/EmbeddedPkg/Library/FdtLib/fdt_rw.c b/EmbeddedPkg/Library/FdtLib/fdt_rw.c
index 878a775a7..1d95a73ec 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt_rw.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt_rw.c
@@ -1,495 +1,495 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-static int _fdt_blocks_misordered(const void *fdt,
- int mem_rsv_size, int struct_size)
-{
- return (fdt_off_mem_rsvmap(fdt) < FDT_ALIGN(sizeof(struct fdt_header), 8))
- || (fdt_off_dt_struct(fdt) <
- (fdt_off_mem_rsvmap(fdt) + mem_rsv_size))
- || (fdt_off_dt_strings(fdt) <
- (fdt_off_dt_struct(fdt) + struct_size))
- || (fdt_totalsize(fdt) <
- (fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt)));
-}
-
-static int _fdt_rw_check_header(void *fdt)
-{
- FDT_CHECK_HEADER(fdt);
-
- if (fdt_version(fdt) < 17)
- return -FDT_ERR_BADVERSION;
- if (_fdt_blocks_misordered(fdt, sizeof(struct fdt_reserve_entry),
- fdt_size_dt_struct(fdt)))
- return -FDT_ERR_BADLAYOUT;
- if (fdt_version(fdt) > 17)
- fdt_set_version(fdt, 17);
-
- return 0;
-}
-
-#define FDT_RW_CHECK_HEADER(fdt) \
- { \
- int err; \
- if ((err = _fdt_rw_check_header(fdt)) != 0) \
- return err; \
- }
-
-static inline int _fdt_data_size(void *fdt)
-{
- return fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);
-}
-
-static int _fdt_splice(void *fdt, void *splicepoint, int oldlen, int newlen)
-{
- char *p = splicepoint;
- char *end = (char *)fdt + _fdt_data_size(fdt);
-
- if (((p + oldlen) < p) || ((p + oldlen) > end))
- return -FDT_ERR_BADOFFSET;
- if ((end - oldlen + newlen) > ((char *)fdt + fdt_totalsize(fdt)))
- return -FDT_ERR_NOSPACE;
- memmove(p + newlen, p + oldlen, end - p - oldlen);
- return 0;
-}
-
-static int _fdt_splice_mem_rsv(void *fdt, struct fdt_reserve_entry *p,
- int oldn, int newn)
-{
- int delta = (newn - oldn) * sizeof(*p);
- int err;
- err = _fdt_splice(fdt, p, oldn * sizeof(*p), newn * sizeof(*p));
- if (err)
- return err;
- fdt_set_off_dt_struct(fdt, fdt_off_dt_struct(fdt) + delta);
- fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);
- return 0;
-}
-
-static int _fdt_splice_struct(void *fdt, void *p,
- int oldlen, int newlen)
-{
- int delta = newlen - oldlen;
- int err;
-
- err = _fdt_splice(fdt, p, oldlen, newlen);
- if (err)
- return err;
-
- fdt_set_size_dt_struct(fdt, fdt_size_dt_struct(fdt) + delta);
- fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);
- return 0;
-}
-
-static int _fdt_splice_string(void *fdt, int newlen)
-{
- void *p = (char *)fdt
- + fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);
- int err;
-
- err = _fdt_splice(fdt, p, 0, newlen);
- if (err)
- return err;
-
- fdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) + newlen);
- return 0;
-}
-
-static int _fdt_find_add_string(void *fdt, const char *s)
-{
- char *strtab = (char *)fdt + fdt_off_dt_strings(fdt);
- const char *p;
- char *new;
- int len = strlen(s) + 1;
- int err;
-
- p = _fdt_find_string(strtab, fdt_size_dt_strings(fdt), s);
- if (p)
- /* found it */
- return (p - strtab);
-
- new = strtab + fdt_size_dt_strings(fdt);
- err = _fdt_splice_string(fdt, len);
- if (err)
- return err;
-
- memcpy(new, s, len);
- return (new - strtab);
-}
-
-int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size)
-{
- struct fdt_reserve_entry *re;
- int err;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- re = _fdt_mem_rsv_w(fdt, fdt_num_mem_rsv(fdt));
- err = _fdt_splice_mem_rsv(fdt, re, 0, 1);
- if (err)
- return err;
-
- re->address = cpu_to_fdt64(address);
- re->size = cpu_to_fdt64(size);
- return 0;
-}
-
-int fdt_del_mem_rsv(void *fdt, int n)
-{
- struct fdt_reserve_entry *re = _fdt_mem_rsv_w(fdt, n);
- int err;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- if (n >= fdt_num_mem_rsv(fdt))
- return -FDT_ERR_NOTFOUND;
-
- err = _fdt_splice_mem_rsv(fdt, re, 1, 0);
- if (err)
- return err;
- return 0;
-}
-
-static int _fdt_resize_property(void *fdt, int nodeoffset, const char *name,
- int len, struct fdt_property **prop)
-{
- int oldlen;
- int err;
-
- *prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
- if (! (*prop))
- return oldlen;
-
- err = _fdt_splice_struct(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
- FDT_TAGALIGN(len));
- if (err)
- return err;
-
- (*prop)->len = cpu_to_fdt32(len);
- return 0;
-}
-
-static int _fdt_add_property(void *fdt, int nodeoffset, const char *name,
- int len, struct fdt_property **prop)
-{
- int proplen;
- int nextoffset;
- int namestroff;
- int err;
-
- if ((nextoffset = _fdt_check_node_offset(fdt, nodeoffset)) < 0)
- return nextoffset;
-
- namestroff = _fdt_find_add_string(fdt, name);
- if (namestroff < 0)
- return namestroff;
-
- *prop = _fdt_offset_ptr_w(fdt, nextoffset);
- proplen = sizeof(**prop) + FDT_TAGALIGN(len);
-
- err = _fdt_splice_struct(fdt, *prop, 0, proplen);
- if (err)
- return err;
-
- (*prop)->tag = cpu_to_fdt32(FDT_PROP);
- (*prop)->nameoff = cpu_to_fdt32(namestroff);
- (*prop)->len = cpu_to_fdt32(len);
- return 0;
-}
-
-int fdt_set_name(void *fdt, int nodeoffset, const char *name)
-{
- char *namep;
- int oldlen, newlen;
- int err;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- namep = (char *)(uintptr_t)fdt_get_name(fdt, nodeoffset, &oldlen);
- if (!namep)
- return oldlen;
-
- newlen = strlen(name);
-
- err = _fdt_splice_struct(fdt, namep, FDT_TAGALIGN(oldlen+1),
- FDT_TAGALIGN(newlen+1));
- if (err)
- return err;
-
- memcpy(namep, name, newlen+1);
- return 0;
-}
-
-int fdt_setprop(void *fdt, int nodeoffset, const char *name,
- const void *val, int len)
-{
- struct fdt_property *prop;
- int err;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- err = _fdt_resize_property(fdt, nodeoffset, name, len, &prop);
- if (err == -FDT_ERR_NOTFOUND)
- err = _fdt_add_property(fdt, nodeoffset, name, len, &prop);
- if (err)
- return err;
-
- memcpy(prop->data, val, len);
- return 0;
-}
-
-int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
- const void *val, int len)
-{
- struct fdt_property *prop;
- int err, oldlen, newlen;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
- if (prop) {
- newlen = len + oldlen;
- err = _fdt_splice_struct(fdt, prop->data,
- FDT_TAGALIGN(oldlen),
- FDT_TAGALIGN(newlen));
- if (err)
- return err;
- prop->len = cpu_to_fdt32(newlen);
- memcpy(prop->data + oldlen, val, len);
- } else {
- err = _fdt_add_property(fdt, nodeoffset, name, len, &prop);
- if (err)
- return err;
- memcpy(prop->data, val, len);
- }
- return 0;
-}
-
-int fdt_delprop(void *fdt, int nodeoffset, const char *name)
-{
- struct fdt_property *prop;
- int len, proplen;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
- if (! prop)
- return len;
-
- proplen = sizeof(*prop) + FDT_TAGALIGN(len);
- return _fdt_splice_struct(fdt, prop, proplen, 0);
-}
-
-int fdt_add_subnode_namelen(void *fdt, int parentoffset,
- const char *name, int namelen)
-{
- struct fdt_node_header *nh;
- int offset, nextoffset;
- int nodelen;
- int err;
- uint32_t tag;
- uint32_t *endtag;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
- if (offset >= 0)
- return -FDT_ERR_EXISTS;
- else if (offset != -FDT_ERR_NOTFOUND)
- return offset;
-
- /* Try to place the new node after the parent's properties */
- fdt_next_tag(fdt, parentoffset, &nextoffset); /* skip the BEGIN_NODE */
- do {
- offset = nextoffset;
- tag = fdt_next_tag(fdt, offset, &nextoffset);
- } while ((tag == FDT_PROP) || (tag == FDT_NOP));
-
- nh = _fdt_offset_ptr_w(fdt, offset);
- nodelen = sizeof(*nh) + FDT_TAGALIGN(namelen+1) + FDT_TAGSIZE;
-
- err = _fdt_splice_struct(fdt, nh, 0, nodelen);
- if (err)
- return err;
-
- nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
- memset(nh->name, 0, FDT_TAGALIGN(namelen+1));
- memcpy(nh->name, name, namelen);
- endtag = (uint32_t *)((char *)nh + nodelen - FDT_TAGSIZE);
- *endtag = cpu_to_fdt32(FDT_END_NODE);
-
- return offset;
-}
-
-int fdt_add_subnode(void *fdt, int parentoffset, const char *name)
-{
- return fdt_add_subnode_namelen(fdt, parentoffset, name, strlen(name));
-}
-
-int fdt_del_node(void *fdt, int nodeoffset)
-{
- int endoffset;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- endoffset = _fdt_node_end_offset(fdt, nodeoffset);
- if (endoffset < 0)
- return endoffset;
-
- return _fdt_splice_struct(fdt, _fdt_offset_ptr_w(fdt, nodeoffset),
- endoffset - nodeoffset, 0);
-}
-
-static void _fdt_packblocks(const char *old, char *new,
- int mem_rsv_size, int struct_size)
-{
- int mem_rsv_off, struct_off, strings_off;
-
- mem_rsv_off = FDT_ALIGN(sizeof(struct fdt_header), 8);
- struct_off = mem_rsv_off + mem_rsv_size;
- strings_off = struct_off + struct_size;
-
- memmove(new + mem_rsv_off, old + fdt_off_mem_rsvmap(old), mem_rsv_size);
- fdt_set_off_mem_rsvmap(new, mem_rsv_off);
-
- memmove(new + struct_off, old + fdt_off_dt_struct(old), struct_size);
- fdt_set_off_dt_struct(new, struct_off);
- fdt_set_size_dt_struct(new, struct_size);
-
- memmove(new + strings_off, old + fdt_off_dt_strings(old),
- fdt_size_dt_strings(old));
- fdt_set_off_dt_strings(new, strings_off);
- fdt_set_size_dt_strings(new, fdt_size_dt_strings(old));
-}
-
-int fdt_open_into(const void *fdt, void *buf, int bufsize)
-{
- int err;
- int mem_rsv_size, struct_size;
- int newsize;
- const char *fdtstart = fdt;
- const char *fdtend = fdtstart + fdt_totalsize(fdt);
- char *tmp;
-
- FDT_CHECK_HEADER(fdt);
-
- mem_rsv_size = (fdt_num_mem_rsv(fdt)+1)
- * sizeof(struct fdt_reserve_entry);
-
- if (fdt_version(fdt) >= 17) {
- struct_size = fdt_size_dt_struct(fdt);
- } else {
- struct_size = 0;
- while (fdt_next_tag(fdt, struct_size, &struct_size) != FDT_END)
- ;
- if (struct_size < 0)
- return struct_size;
- }
-
- if (!_fdt_blocks_misordered(fdt, mem_rsv_size, struct_size)) {
- /* no further work necessary */
- err = fdt_move(fdt, buf, bufsize);
- if (err)
- return err;
- fdt_set_version(buf, 17);
- fdt_set_size_dt_struct(buf, struct_size);
- fdt_set_totalsize(buf, bufsize);
- return 0;
- }
-
- /* Need to reorder */
- newsize = FDT_ALIGN(sizeof(struct fdt_header), 8) + mem_rsv_size
- + struct_size + fdt_size_dt_strings(fdt);
-
- if (bufsize < newsize)
- return -FDT_ERR_NOSPACE;
-
- /* First attempt to build converted tree at beginning of buffer */
- tmp = buf;
- /* But if that overlaps with the old tree... */
- if (((tmp + newsize) > fdtstart) && (tmp < fdtend)) {
- /* Try right after the old tree instead */
- tmp = (char *)(uintptr_t)fdtend;
- if ((tmp + newsize) > ((char *)buf + bufsize))
- return -FDT_ERR_NOSPACE;
- }
-
- _fdt_packblocks(fdt, tmp, mem_rsv_size, struct_size);
- memmove(buf, tmp, newsize);
-
- fdt_set_magic(buf, FDT_MAGIC);
- fdt_set_totalsize(buf, bufsize);
- fdt_set_version(buf, 17);
- fdt_set_last_comp_version(buf, 16);
- fdt_set_boot_cpuid_phys(buf, fdt_boot_cpuid_phys(fdt));
-
- return 0;
-}
-
-int fdt_pack(void *fdt)
-{
- int mem_rsv_size;
-
- FDT_RW_CHECK_HEADER(fdt);
-
- mem_rsv_size = (fdt_num_mem_rsv(fdt)+1)
- * sizeof(struct fdt_reserve_entry);
- _fdt_packblocks(fdt, fdt, mem_rsv_size, fdt_size_dt_struct(fdt));
- fdt_set_totalsize(fdt, _fdt_data_size(fdt));
-
- return 0;
-}
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+static int _fdt_blocks_misordered(const void *fdt,
+ int mem_rsv_size, int struct_size)
+{
+ return (fdt_off_mem_rsvmap(fdt) < FDT_ALIGN(sizeof(struct fdt_header), 8))
+ || (fdt_off_dt_struct(fdt) <
+ (fdt_off_mem_rsvmap(fdt) + mem_rsv_size))
+ || (fdt_off_dt_strings(fdt) <
+ (fdt_off_dt_struct(fdt) + struct_size))
+ || (fdt_totalsize(fdt) <
+ (fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt)));
+}
+
+static int _fdt_rw_check_header(void *fdt)
+{
+ FDT_CHECK_HEADER(fdt);
+
+ if (fdt_version(fdt) < 17)
+ return -FDT_ERR_BADVERSION;
+ if (_fdt_blocks_misordered(fdt, sizeof(struct fdt_reserve_entry),
+ fdt_size_dt_struct(fdt)))
+ return -FDT_ERR_BADLAYOUT;
+ if (fdt_version(fdt) > 17)
+ fdt_set_version(fdt, 17);
+
+ return 0;
+}
+
+#define FDT_RW_CHECK_HEADER(fdt) \
+ { \
+ int err; \
+ if ((err = _fdt_rw_check_header(fdt)) != 0) \
+ return err; \
+ }
+
+static inline int _fdt_data_size(void *fdt)
+{
+ return fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);
+}
+
+static int _fdt_splice(void *fdt, void *splicepoint, int oldlen, int newlen)
+{
+ char *p = splicepoint;
+ char *end = (char *)fdt + _fdt_data_size(fdt);
+
+ if (((p + oldlen) < p) || ((p + oldlen) > end))
+ return -FDT_ERR_BADOFFSET;
+ if ((end - oldlen + newlen) > ((char *)fdt + fdt_totalsize(fdt)))
+ return -FDT_ERR_NOSPACE;
+ memmove(p + newlen, p + oldlen, end - p - oldlen);
+ return 0;
+}
+
+static int _fdt_splice_mem_rsv(void *fdt, struct fdt_reserve_entry *p,
+ int oldn, int newn)
+{
+ int delta = (newn - oldn) * sizeof(*p);
+ int err;
+ err = _fdt_splice(fdt, p, oldn * sizeof(*p), newn * sizeof(*p));
+ if (err)
+ return err;
+ fdt_set_off_dt_struct(fdt, fdt_off_dt_struct(fdt) + delta);
+ fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);
+ return 0;
+}
+
+static int _fdt_splice_struct(void *fdt, void *p,
+ int oldlen, int newlen)
+{
+ int delta = newlen - oldlen;
+ int err;
+
+ err = _fdt_splice(fdt, p, oldlen, newlen);
+ if (err)
+ return err;
+
+ fdt_set_size_dt_struct(fdt, fdt_size_dt_struct(fdt) + delta);
+ fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);
+ return 0;
+}
+
+static int _fdt_splice_string(void *fdt, int newlen)
+{
+ void *p = (char *)fdt
+ + fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);
+ int err;
+
+ err = _fdt_splice(fdt, p, 0, newlen);
+ if (err)
+ return err;
+
+ fdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) + newlen);
+ return 0;
+}
+
+static int _fdt_find_add_string(void *fdt, const char *s)
+{
+ char *strtab = (char *)fdt + fdt_off_dt_strings(fdt);
+ const char *p;
+ char *new;
+ int len = strlen(s) + 1;
+ int err;
+
+ p = _fdt_find_string(strtab, fdt_size_dt_strings(fdt), s);
+ if (p)
+ /* found it */
+ return (p - strtab);
+
+ new = strtab + fdt_size_dt_strings(fdt);
+ err = _fdt_splice_string(fdt, len);
+ if (err)
+ return err;
+
+ memcpy(new, s, len);
+ return (new - strtab);
+}
+
+int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size)
+{
+ struct fdt_reserve_entry *re;
+ int err;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ re = _fdt_mem_rsv_w(fdt, fdt_num_mem_rsv(fdt));
+ err = _fdt_splice_mem_rsv(fdt, re, 0, 1);
+ if (err)
+ return err;
+
+ re->address = cpu_to_fdt64(address);
+ re->size = cpu_to_fdt64(size);
+ return 0;
+}
+
+int fdt_del_mem_rsv(void *fdt, int n)
+{
+ struct fdt_reserve_entry *re = _fdt_mem_rsv_w(fdt, n);
+ int err;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ if (n >= fdt_num_mem_rsv(fdt))
+ return -FDT_ERR_NOTFOUND;
+
+ err = _fdt_splice_mem_rsv(fdt, re, 1, 0);
+ if (err)
+ return err;
+ return 0;
+}
+
+static int _fdt_resize_property(void *fdt, int nodeoffset, const char *name,
+ int len, struct fdt_property **prop)
+{
+ int oldlen;
+ int err;
+
+ *prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
+ if (! (*prop))
+ return oldlen;
+
+ err = _fdt_splice_struct(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
+ FDT_TAGALIGN(len));
+ if (err)
+ return err;
+
+ (*prop)->len = cpu_to_fdt32(len);
+ return 0;
+}
+
+static int _fdt_add_property(void *fdt, int nodeoffset, const char *name,
+ int len, struct fdt_property **prop)
+{
+ int proplen;
+ int nextoffset;
+ int namestroff;
+ int err;
+
+ if ((nextoffset = _fdt_check_node_offset(fdt, nodeoffset)) < 0)
+ return nextoffset;
+
+ namestroff = _fdt_find_add_string(fdt, name);
+ if (namestroff < 0)
+ return namestroff;
+
+ *prop = _fdt_offset_ptr_w(fdt, nextoffset);
+ proplen = sizeof(**prop) + FDT_TAGALIGN(len);
+
+ err = _fdt_splice_struct(fdt, *prop, 0, proplen);
+ if (err)
+ return err;
+
+ (*prop)->tag = cpu_to_fdt32(FDT_PROP);
+ (*prop)->nameoff = cpu_to_fdt32(namestroff);
+ (*prop)->len = cpu_to_fdt32(len);
+ return 0;
+}
+
+int fdt_set_name(void *fdt, int nodeoffset, const char *name)
+{
+ char *namep;
+ int oldlen, newlen;
+ int err;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ namep = (char *)(uintptr_t)fdt_get_name(fdt, nodeoffset, &oldlen);
+ if (!namep)
+ return oldlen;
+
+ newlen = strlen(name);
+
+ err = _fdt_splice_struct(fdt, namep, FDT_TAGALIGN(oldlen+1),
+ FDT_TAGALIGN(newlen+1));
+ if (err)
+ return err;
+
+ memcpy(namep, name, newlen+1);
+ return 0;
+}
+
+int fdt_setprop(void *fdt, int nodeoffset, const char *name,
+ const void *val, int len)
+{
+ struct fdt_property *prop;
+ int err;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ err = _fdt_resize_property(fdt, nodeoffset, name, len, &prop);
+ if (err == -FDT_ERR_NOTFOUND)
+ err = _fdt_add_property(fdt, nodeoffset, name, len, &prop);
+ if (err)
+ return err;
+
+ memcpy(prop->data, val, len);
+ return 0;
+}
+
+int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
+ const void *val, int len)
+{
+ struct fdt_property *prop;
+ int err, oldlen, newlen;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
+ if (prop) {
+ newlen = len + oldlen;
+ err = _fdt_splice_struct(fdt, prop->data,
+ FDT_TAGALIGN(oldlen),
+ FDT_TAGALIGN(newlen));
+ if (err)
+ return err;
+ prop->len = cpu_to_fdt32(newlen);
+ memcpy(prop->data + oldlen, val, len);
+ } else {
+ err = _fdt_add_property(fdt, nodeoffset, name, len, &prop);
+ if (err)
+ return err;
+ memcpy(prop->data, val, len);
+ }
+ return 0;
+}
+
+int fdt_delprop(void *fdt, int nodeoffset, const char *name)
+{
+ struct fdt_property *prop;
+ int len, proplen;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
+ if (! prop)
+ return len;
+
+ proplen = sizeof(*prop) + FDT_TAGALIGN(len);
+ return _fdt_splice_struct(fdt, prop, proplen, 0);
+}
+
+int fdt_add_subnode_namelen(void *fdt, int parentoffset,
+ const char *name, int namelen)
+{
+ struct fdt_node_header *nh;
+ int offset, nextoffset;
+ int nodelen;
+ int err;
+ uint32_t tag;
+ uint32_t *endtag;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
+ if (offset >= 0)
+ return -FDT_ERR_EXISTS;
+ else if (offset != -FDT_ERR_NOTFOUND)
+ return offset;
+
+ /* Try to place the new node after the parent's properties */
+ fdt_next_tag(fdt, parentoffset, &nextoffset); /* skip the BEGIN_NODE */
+ do {
+ offset = nextoffset;
+ tag = fdt_next_tag(fdt, offset, &nextoffset);
+ } while ((tag == FDT_PROP) || (tag == FDT_NOP));
+
+ nh = _fdt_offset_ptr_w(fdt, offset);
+ nodelen = sizeof(*nh) + FDT_TAGALIGN(namelen+1) + FDT_TAGSIZE;
+
+ err = _fdt_splice_struct(fdt, nh, 0, nodelen);
+ if (err)
+ return err;
+
+ nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
+ memset(nh->name, 0, FDT_TAGALIGN(namelen+1));
+ memcpy(nh->name, name, namelen);
+ endtag = (uint32_t *)((char *)nh + nodelen - FDT_TAGSIZE);
+ *endtag = cpu_to_fdt32(FDT_END_NODE);
+
+ return offset;
+}
+
+int fdt_add_subnode(void *fdt, int parentoffset, const char *name)
+{
+ return fdt_add_subnode_namelen(fdt, parentoffset, name, strlen(name));
+}
+
+int fdt_del_node(void *fdt, int nodeoffset)
+{
+ int endoffset;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ endoffset = _fdt_node_end_offset(fdt, nodeoffset);
+ if (endoffset < 0)
+ return endoffset;
+
+ return _fdt_splice_struct(fdt, _fdt_offset_ptr_w(fdt, nodeoffset),
+ endoffset - nodeoffset, 0);
+}
+
+static void _fdt_packblocks(const char *old, char *new,
+ int mem_rsv_size, int struct_size)
+{
+ int mem_rsv_off, struct_off, strings_off;
+
+ mem_rsv_off = FDT_ALIGN(sizeof(struct fdt_header), 8);
+ struct_off = mem_rsv_off + mem_rsv_size;
+ strings_off = struct_off + struct_size;
+
+ memmove(new + mem_rsv_off, old + fdt_off_mem_rsvmap(old), mem_rsv_size);
+ fdt_set_off_mem_rsvmap(new, mem_rsv_off);
+
+ memmove(new + struct_off, old + fdt_off_dt_struct(old), struct_size);
+ fdt_set_off_dt_struct(new, struct_off);
+ fdt_set_size_dt_struct(new, struct_size);
+
+ memmove(new + strings_off, old + fdt_off_dt_strings(old),
+ fdt_size_dt_strings(old));
+ fdt_set_off_dt_strings(new, strings_off);
+ fdt_set_size_dt_strings(new, fdt_size_dt_strings(old));
+}
+
+int fdt_open_into(const void *fdt, void *buf, int bufsize)
+{
+ int err;
+ int mem_rsv_size, struct_size;
+ int newsize;
+ const char *fdtstart = fdt;
+ const char *fdtend = fdtstart + fdt_totalsize(fdt);
+ char *tmp;
+
+ FDT_CHECK_HEADER(fdt);
+
+ mem_rsv_size = (fdt_num_mem_rsv(fdt)+1)
+ * sizeof(struct fdt_reserve_entry);
+
+ if (fdt_version(fdt) >= 17) {
+ struct_size = fdt_size_dt_struct(fdt);
+ } else {
+ struct_size = 0;
+ while (fdt_next_tag(fdt, struct_size, &struct_size) != FDT_END)
+ ;
+ if (struct_size < 0)
+ return struct_size;
+ }
+
+ if (!_fdt_blocks_misordered(fdt, mem_rsv_size, struct_size)) {
+ /* no further work necessary */
+ err = fdt_move(fdt, buf, bufsize);
+ if (err)
+ return err;
+ fdt_set_version(buf, 17);
+ fdt_set_size_dt_struct(buf, struct_size);
+ fdt_set_totalsize(buf, bufsize);
+ return 0;
+ }
+
+ /* Need to reorder */
+ newsize = FDT_ALIGN(sizeof(struct fdt_header), 8) + mem_rsv_size
+ + struct_size + fdt_size_dt_strings(fdt);
+
+ if (bufsize < newsize)
+ return -FDT_ERR_NOSPACE;
+
+ /* First attempt to build converted tree at beginning of buffer */
+ tmp = buf;
+ /* But if that overlaps with the old tree... */
+ if (((tmp + newsize) > fdtstart) && (tmp < fdtend)) {
+ /* Try right after the old tree instead */
+ tmp = (char *)(uintptr_t)fdtend;
+ if ((tmp + newsize) > ((char *)buf + bufsize))
+ return -FDT_ERR_NOSPACE;
+ }
+
+ _fdt_packblocks(fdt, tmp, mem_rsv_size, struct_size);
+ memmove(buf, tmp, newsize);
+
+ fdt_set_magic(buf, FDT_MAGIC);
+ fdt_set_totalsize(buf, bufsize);
+ fdt_set_version(buf, 17);
+ fdt_set_last_comp_version(buf, 16);
+ fdt_set_boot_cpuid_phys(buf, fdt_boot_cpuid_phys(fdt));
+
+ return 0;
+}
+
+int fdt_pack(void *fdt)
+{
+ int mem_rsv_size;
+
+ FDT_RW_CHECK_HEADER(fdt);
+
+ mem_rsv_size = (fdt_num_mem_rsv(fdt)+1)
+ * sizeof(struct fdt_reserve_entry);
+ _fdt_packblocks(fdt, fdt, mem_rsv_size, fdt_size_dt_struct(fdt));
+ fdt_set_totalsize(fdt, _fdt_data_size(fdt));
+
+ return 0;
+}
diff --git a/EmbeddedPkg/Library/FdtLib/fdt_strerror.c b/EmbeddedPkg/Library/FdtLib/fdt_strerror.c
index e6c3ceee8..a49793d93 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt_strerror.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt_strerror.c
@@ -1,96 +1,96 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-struct fdt_errtabent {
- const char *str;
-};
-
-#define FDT_ERRTABENT(val) \
- [(val)] = { .str = #val, }
-
-static struct fdt_errtabent fdt_errtable[] = {
- FDT_ERRTABENT(FDT_ERR_NOTFOUND),
- FDT_ERRTABENT(FDT_ERR_EXISTS),
- FDT_ERRTABENT(FDT_ERR_NOSPACE),
-
- FDT_ERRTABENT(FDT_ERR_BADOFFSET),
- FDT_ERRTABENT(FDT_ERR_BADPATH),
- FDT_ERRTABENT(FDT_ERR_BADSTATE),
-
- FDT_ERRTABENT(FDT_ERR_TRUNCATED),
- FDT_ERRTABENT(FDT_ERR_BADMAGIC),
- FDT_ERRTABENT(FDT_ERR_BADVERSION),
- FDT_ERRTABENT(FDT_ERR_BADSTRUCTURE),
- FDT_ERRTABENT(FDT_ERR_BADLAYOUT),
-};
-#define FDT_ERRTABSIZE (sizeof(fdt_errtable) / sizeof(fdt_errtable[0]))
-
-const char *fdt_strerror(int errval)
-{
- if (errval > 0)
- return "<valid offset/length>";
- else if (errval == 0)
- return "<no error>";
- else if (errval > -FDT_ERRTABSIZE) {
- const char *s = fdt_errtable[-errval].str;
-
- if (s)
- return s;
- }
-
- return "<unknown error>";
-}
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+struct fdt_errtabent {
+ const char *str;
+};
+
+#define FDT_ERRTABENT(val) \
+ [(val)] = { .str = #val, }
+
+static struct fdt_errtabent fdt_errtable[] = {
+ FDT_ERRTABENT(FDT_ERR_NOTFOUND),
+ FDT_ERRTABENT(FDT_ERR_EXISTS),
+ FDT_ERRTABENT(FDT_ERR_NOSPACE),
+
+ FDT_ERRTABENT(FDT_ERR_BADOFFSET),
+ FDT_ERRTABENT(FDT_ERR_BADPATH),
+ FDT_ERRTABENT(FDT_ERR_BADSTATE),
+
+ FDT_ERRTABENT(FDT_ERR_TRUNCATED),
+ FDT_ERRTABENT(FDT_ERR_BADMAGIC),
+ FDT_ERRTABENT(FDT_ERR_BADVERSION),
+ FDT_ERRTABENT(FDT_ERR_BADSTRUCTURE),
+ FDT_ERRTABENT(FDT_ERR_BADLAYOUT),
+};
+#define FDT_ERRTABSIZE (sizeof(fdt_errtable) / sizeof(fdt_errtable[0]))
+
+const char *fdt_strerror(int errval)
+{
+ if (errval > 0)
+ return "<valid offset/length>";
+ else if (errval == 0)
+ return "<no error>";
+ else if (errval > -FDT_ERRTABSIZE) {
+ const char *s = fdt_errtable[-errval].str;
+
+ if (s)
+ return s;
+ }
+
+ return "<unknown error>";
+}
diff --git a/EmbeddedPkg/Library/FdtLib/fdt_sw.c b/EmbeddedPkg/Library/FdtLib/fdt_sw.c
index 55ebebf1e..240fabc55 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt_sw.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt_sw.c
@@ -1,256 +1,256 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-static int _fdt_sw_check_header(void *fdt)
-{
- if (fdt_magic(fdt) != FDT_SW_MAGIC)
- return -FDT_ERR_BADMAGIC;
- /* FIXME: should check more details about the header state */
- return 0;
-}
-
-#define FDT_SW_CHECK_HEADER(fdt) \
- { \
- int err; \
- if ((err = _fdt_sw_check_header(fdt)) != 0) \
- return err; \
- }
-
-static void *_fdt_grab_space(void *fdt, size_t len)
-{
- int offset = fdt_size_dt_struct(fdt);
- int spaceleft;
-
- spaceleft = fdt_totalsize(fdt) - fdt_off_dt_struct(fdt)
- - fdt_size_dt_strings(fdt);
-
- if ((offset + len < offset) || (offset + len > spaceleft))
- return NULL;
-
- fdt_set_size_dt_struct(fdt, offset + len);
- return _fdt_offset_ptr_w(fdt, offset);
-}
-
-int fdt_create(void *buf, int bufsize)
-{
- void *fdt = buf;
-
- if (bufsize < sizeof(struct fdt_header))
- return -FDT_ERR_NOSPACE;
-
- memset(buf, 0, bufsize);
-
- fdt_set_magic(fdt, FDT_SW_MAGIC);
- fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
- fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
- fdt_set_totalsize(fdt, bufsize);
-
- fdt_set_off_mem_rsvmap(fdt, FDT_ALIGN(sizeof(struct fdt_header),
- sizeof(struct fdt_reserve_entry)));
- fdt_set_off_dt_struct(fdt, fdt_off_mem_rsvmap(fdt));
- fdt_set_off_dt_strings(fdt, bufsize);
-
- return 0;
-}
-
-int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size)
-{
- struct fdt_reserve_entry *re;
- int offset;
-
- FDT_SW_CHECK_HEADER(fdt);
-
- if (fdt_size_dt_struct(fdt))
- return -FDT_ERR_BADSTATE;
-
- offset = fdt_off_dt_struct(fdt);
- if ((offset + sizeof(*re)) > fdt_totalsize(fdt))
- return -FDT_ERR_NOSPACE;
-
- re = (struct fdt_reserve_entry *)((char *)fdt + offset);
- re->address = cpu_to_fdt64(addr);
- re->size = cpu_to_fdt64(size);
-
- fdt_set_off_dt_struct(fdt, offset + sizeof(*re));
-
- return 0;
-}
-
-int fdt_finish_reservemap(void *fdt)
-{
- return fdt_add_reservemap_entry(fdt, 0, 0);
-}
-
-int fdt_begin_node(void *fdt, const char *name)
-{
- struct fdt_node_header *nh;
- int namelen = strlen(name) + 1;
-
- FDT_SW_CHECK_HEADER(fdt);
-
- nh = _fdt_grab_space(fdt, sizeof(*nh) + FDT_TAGALIGN(namelen));
- if (! nh)
- return -FDT_ERR_NOSPACE;
-
- nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
- memcpy(nh->name, name, namelen);
- return 0;
-}
-
-int fdt_end_node(void *fdt)
-{
- uint32_t *en;
-
- FDT_SW_CHECK_HEADER(fdt);
-
- en = _fdt_grab_space(fdt, FDT_TAGSIZE);
- if (! en)
- return -FDT_ERR_NOSPACE;
-
- *en = cpu_to_fdt32(FDT_END_NODE);
- return 0;
-}
-
-static int _fdt_find_add_string(void *fdt, const char *s)
-{
- char *strtab = (char *)fdt + fdt_totalsize(fdt);
- const char *p;
- int strtabsize = fdt_size_dt_strings(fdt);
- int len = strlen(s) + 1;
- int struct_top, offset;
-
- p = _fdt_find_string(strtab - strtabsize, strtabsize, s);
- if (p)
- return p - strtab;
-
- /* Add it */
- offset = -strtabsize - len;
- struct_top = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);
- if (fdt_totalsize(fdt) + offset < struct_top)
- return 0; /* no more room :( */
-
- memcpy(strtab + offset, s, len);
- fdt_set_size_dt_strings(fdt, strtabsize + len);
- return offset;
-}
-
-int fdt_property(void *fdt, const char *name, const void *val, int len)
-{
- struct fdt_property *prop;
- int nameoff;
-
- FDT_SW_CHECK_HEADER(fdt);
-
- nameoff = _fdt_find_add_string(fdt, name);
- if (nameoff == 0)
- return -FDT_ERR_NOSPACE;
-
- prop = _fdt_grab_space(fdt, sizeof(*prop) + FDT_TAGALIGN(len));
- if (! prop)
- return -FDT_ERR_NOSPACE;
-
- prop->tag = cpu_to_fdt32(FDT_PROP);
- prop->nameoff = cpu_to_fdt32(nameoff);
- prop->len = cpu_to_fdt32(len);
- memcpy(prop->data, val, len);
- return 0;
-}
-
-int fdt_finish(void *fdt)
-{
- char *p = (char *)fdt;
- uint32_t *end;
- int oldstroffset, newstroffset;
- uint32_t tag;
- int offset, nextoffset;
-
- FDT_SW_CHECK_HEADER(fdt);
-
- /* Add terminator */
- end = _fdt_grab_space(fdt, sizeof(*end));
- if (! end)
- return -FDT_ERR_NOSPACE;
- *end = cpu_to_fdt32(FDT_END);
-
- /* Relocate the string table */
- oldstroffset = fdt_totalsize(fdt) - fdt_size_dt_strings(fdt);
- newstroffset = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);
- memmove(p + newstroffset, p + oldstroffset, fdt_size_dt_strings(fdt));
- fdt_set_off_dt_strings(fdt, newstroffset);
-
- /* Walk the structure, correcting string offsets */
- offset = 0;
- while ((tag = fdt_next_tag(fdt, offset, &nextoffset)) != FDT_END) {
- if (tag == FDT_PROP) {
- struct fdt_property *prop =
- _fdt_offset_ptr_w(fdt, offset);
- int nameoff;
-
- nameoff = fdt32_to_cpu(prop->nameoff);
- nameoff += fdt_size_dt_strings(fdt);
- prop->nameoff = cpu_to_fdt32(nameoff);
- }
- offset = nextoffset;
- }
- if (nextoffset < 0)
- return nextoffset;
-
- /* Finally, adjust the header */
- fdt_set_totalsize(fdt, newstroffset + fdt_size_dt_strings(fdt));
- fdt_set_magic(fdt, FDT_MAGIC);
- return 0;
-}
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+static int _fdt_sw_check_header(void *fdt)
+{
+ if (fdt_magic(fdt) != FDT_SW_MAGIC)
+ return -FDT_ERR_BADMAGIC;
+ /* FIXME: should check more details about the header state */
+ return 0;
+}
+
+#define FDT_SW_CHECK_HEADER(fdt) \
+ { \
+ int err; \
+ if ((err = _fdt_sw_check_header(fdt)) != 0) \
+ return err; \
+ }
+
+static void *_fdt_grab_space(void *fdt, size_t len)
+{
+ int offset = fdt_size_dt_struct(fdt);
+ int spaceleft;
+
+ spaceleft = fdt_totalsize(fdt) - fdt_off_dt_struct(fdt)
+ - fdt_size_dt_strings(fdt);
+
+ if ((offset + len < offset) || (offset + len > spaceleft))
+ return NULL;
+
+ fdt_set_size_dt_struct(fdt, offset + len);
+ return _fdt_offset_ptr_w(fdt, offset);
+}
+
+int fdt_create(void *buf, int bufsize)
+{
+ void *fdt = buf;
+
+ if (bufsize < sizeof(struct fdt_header))
+ return -FDT_ERR_NOSPACE;
+
+ memset(buf, 0, bufsize);
+
+ fdt_set_magic(fdt, FDT_SW_MAGIC);
+ fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
+ fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
+ fdt_set_totalsize(fdt, bufsize);
+
+ fdt_set_off_mem_rsvmap(fdt, FDT_ALIGN(sizeof(struct fdt_header),
+ sizeof(struct fdt_reserve_entry)));
+ fdt_set_off_dt_struct(fdt, fdt_off_mem_rsvmap(fdt));
+ fdt_set_off_dt_strings(fdt, bufsize);
+
+ return 0;
+}
+
+int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size)
+{
+ struct fdt_reserve_entry *re;
+ int offset;
+
+ FDT_SW_CHECK_HEADER(fdt);
+
+ if (fdt_size_dt_struct(fdt))
+ return -FDT_ERR_BADSTATE;
+
+ offset = fdt_off_dt_struct(fdt);
+ if ((offset + sizeof(*re)) > fdt_totalsize(fdt))
+ return -FDT_ERR_NOSPACE;
+
+ re = (struct fdt_reserve_entry *)((char *)fdt + offset);
+ re->address = cpu_to_fdt64(addr);
+ re->size = cpu_to_fdt64(size);
+
+ fdt_set_off_dt_struct(fdt, offset + sizeof(*re));
+
+ return 0;
+}
+
+int fdt_finish_reservemap(void *fdt)
+{
+ return fdt_add_reservemap_entry(fdt, 0, 0);
+}
+
+int fdt_begin_node(void *fdt, const char *name)
+{
+ struct fdt_node_header *nh;
+ int namelen = strlen(name) + 1;
+
+ FDT_SW_CHECK_HEADER(fdt);
+
+ nh = _fdt_grab_space(fdt, sizeof(*nh) + FDT_TAGALIGN(namelen));
+ if (! nh)
+ return -FDT_ERR_NOSPACE;
+
+ nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
+ memcpy(nh->name, name, namelen);
+ return 0;
+}
+
+int fdt_end_node(void *fdt)
+{
+ uint32_t *en;
+
+ FDT_SW_CHECK_HEADER(fdt);
+
+ en = _fdt_grab_space(fdt, FDT_TAGSIZE);
+ if (! en)
+ return -FDT_ERR_NOSPACE;
+
+ *en = cpu_to_fdt32(FDT_END_NODE);
+ return 0;
+}
+
+static int _fdt_find_add_string(void *fdt, const char *s)
+{
+ char *strtab = (char *)fdt + fdt_totalsize(fdt);
+ const char *p;
+ int strtabsize = fdt_size_dt_strings(fdt);
+ int len = strlen(s) + 1;
+ int struct_top, offset;
+
+ p = _fdt_find_string(strtab - strtabsize, strtabsize, s);
+ if (p)
+ return p - strtab;
+
+ /* Add it */
+ offset = -strtabsize - len;
+ struct_top = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);
+ if (fdt_totalsize(fdt) + offset < struct_top)
+ return 0; /* no more room :( */
+
+ memcpy(strtab + offset, s, len);
+ fdt_set_size_dt_strings(fdt, strtabsize + len);
+ return offset;
+}
+
+int fdt_property(void *fdt, const char *name, const void *val, int len)
+{
+ struct fdt_property *prop;
+ int nameoff;
+
+ FDT_SW_CHECK_HEADER(fdt);
+
+ nameoff = _fdt_find_add_string(fdt, name);
+ if (nameoff == 0)
+ return -FDT_ERR_NOSPACE;
+
+ prop = _fdt_grab_space(fdt, sizeof(*prop) + FDT_TAGALIGN(len));
+ if (! prop)
+ return -FDT_ERR_NOSPACE;
+
+ prop->tag = cpu_to_fdt32(FDT_PROP);
+ prop->nameoff = cpu_to_fdt32(nameoff);
+ prop->len = cpu_to_fdt32(len);
+ memcpy(prop->data, val, len);
+ return 0;
+}
+
+int fdt_finish(void *fdt)
+{
+ char *p = (char *)fdt;
+ uint32_t *end;
+ int oldstroffset, newstroffset;
+ uint32_t tag;
+ int offset, nextoffset;
+
+ FDT_SW_CHECK_HEADER(fdt);
+
+ /* Add terminator */
+ end = _fdt_grab_space(fdt, sizeof(*end));
+ if (! end)
+ return -FDT_ERR_NOSPACE;
+ *end = cpu_to_fdt32(FDT_END);
+
+ /* Relocate the string table */
+ oldstroffset = fdt_totalsize(fdt) - fdt_size_dt_strings(fdt);
+ newstroffset = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);
+ memmove(p + newstroffset, p + oldstroffset, fdt_size_dt_strings(fdt));
+ fdt_set_off_dt_strings(fdt, newstroffset);
+
+ /* Walk the structure, correcting string offsets */
+ offset = 0;
+ while ((tag = fdt_next_tag(fdt, offset, &nextoffset)) != FDT_END) {
+ if (tag == FDT_PROP) {
+ struct fdt_property *prop =
+ _fdt_offset_ptr_w(fdt, offset);
+ int nameoff;
+
+ nameoff = fdt32_to_cpu(prop->nameoff);
+ nameoff += fdt_size_dt_strings(fdt);
+ prop->nameoff = cpu_to_fdt32(nameoff);
+ }
+ offset = nextoffset;
+ }
+ if (nextoffset < 0)
+ return nextoffset;
+
+ /* Finally, adjust the header */
+ fdt_set_totalsize(fdt, newstroffset + fdt_size_dt_strings(fdt));
+ fdt_set_magic(fdt, FDT_MAGIC);
+ return 0;
+}
diff --git a/EmbeddedPkg/Library/FdtLib/fdt_wip.c b/EmbeddedPkg/Library/FdtLib/fdt_wip.c
index 6025fa1fe..e009a88f5 100644
--- a/EmbeddedPkg/Library/FdtLib/fdt_wip.c
+++ b/EmbeddedPkg/Library/FdtLib/fdt_wip.c
@@ -1,118 +1,118 @@
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "libfdt_env.h"
-
-#include <fdt.h>
-#include <libfdt.h>
-
-#include "libfdt_internal.h"
-
-int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
- const void *val, int len)
-{
- void *propval;
- int proplen;
-
- propval = fdt_getprop_w(fdt, nodeoffset, name, &proplen);
- if (! propval)
- return proplen;
-
- if (proplen != len)
- return -FDT_ERR_NOSPACE;
-
- memcpy(propval, val, len);
- return 0;
-}
-
-static void _fdt_nop_region(void *start, int len)
-{
- uint32_t *p;
-
- for (p = start; (char *)p < ((char *)start + len); p++)
- *p = cpu_to_fdt32(FDT_NOP);
-}
-
-int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
-{
- struct fdt_property *prop;
- int len;
-
- prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
- if (! prop)
- return len;
-
- _fdt_nop_region(prop, len + sizeof(*prop));
-
- return 0;
-}
-
-int _fdt_node_end_offset(void *fdt, int offset)
-{
- int depth = 0;
-
- while ((offset >= 0) && (depth >= 0))
- offset = fdt_next_node(fdt, offset, &depth);
-
- return offset;
-}
-
-int fdt_nop_node(void *fdt, int nodeoffset)
-{
- int endoffset;
-
- endoffset = _fdt_node_end_offset(fdt, nodeoffset);
- if (endoffset < 0)
- return endoffset;
-
- _fdt_nop_region(fdt_offset_ptr_w(fdt, nodeoffset, 0),
- endoffset - nodeoffset);
- return 0;
-}
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "libfdt_env.h"
+
+#include <fdt.h>
+#include <libfdt.h>
+
+#include "libfdt_internal.h"
+
+int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
+ const void *val, int len)
+{
+ void *propval;
+ int proplen;
+
+ propval = fdt_getprop_w(fdt, nodeoffset, name, &proplen);
+ if (! propval)
+ return proplen;
+
+ if (proplen != len)
+ return -FDT_ERR_NOSPACE;
+
+ memcpy(propval, val, len);
+ return 0;
+}
+
+static void _fdt_nop_region(void *start, int len)
+{
+ uint32_t *p;
+
+ for (p = start; (char *)p < ((char *)start + len); p++)
+ *p = cpu_to_fdt32(FDT_NOP);
+}
+
+int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
+{
+ struct fdt_property *prop;
+ int len;
+
+ prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
+ if (! prop)
+ return len;
+
+ _fdt_nop_region(prop, len + sizeof(*prop));
+
+ return 0;
+}
+
+int _fdt_node_end_offset(void *fdt, int offset)
+{
+ int depth = 0;
+
+ while ((offset >= 0) && (depth >= 0))
+ offset = fdt_next_node(fdt, offset, &depth);
+
+ return offset;
+}
+
+int fdt_nop_node(void *fdt, int nodeoffset)
+{
+ int endoffset;
+
+ endoffset = _fdt_node_end_offset(fdt, nodeoffset);
+ if (endoffset < 0)
+ return endoffset;
+
+ _fdt_nop_region(fdt_offset_ptr_w(fdt, nodeoffset, 0),
+ endoffset - nodeoffset);
+ return 0;
+}
diff --git a/EmbeddedPkg/Library/FdtLib/libfdt_internal.h b/EmbeddedPkg/Library/FdtLib/libfdt_internal.h
index 381133ba8..15456110a 100644
--- a/EmbeddedPkg/Library/FdtLib/libfdt_internal.h
+++ b/EmbeddedPkg/Library/FdtLib/libfdt_internal.h
@@ -1,95 +1,95 @@
-#ifndef _LIBFDT_INTERNAL_H
-#define _LIBFDT_INTERNAL_H
-/*
- * libfdt - Flat Device Tree manipulation
- * Copyright (C) 2006 David Gibson, IBM Corporation.
- *
- * libfdt is dual licensed: you can use it either under the terms of
- * the GPL, or the BSD license, at your option.
- *
- * a) This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of the
- * License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this library; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
- * MA 02110-1301 USA
- *
- * Alternatively,
- *
- * b) Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
- * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include <fdt.h>
-
-#define FDT_ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
-#define FDT_TAGALIGN(x) (FDT_ALIGN((x), FDT_TAGSIZE))
-
-#define FDT_CHECK_HEADER(fdt) \
- { \
- int err; \
- if ((err = fdt_check_header(fdt)) != 0) \
- return err; \
- }
-
-int _fdt_check_node_offset(const void *fdt, int offset);
-int _fdt_check_prop_offset(const void *fdt, int offset);
-const char *_fdt_find_string(const char *strtab, int tabsize, const char *s);
-int _fdt_node_end_offset(void *fdt, int nodeoffset);
-
-static inline const void *_fdt_offset_ptr(const void *fdt, int offset)
-{
- return (const char *)fdt + fdt_off_dt_struct(fdt) + offset;
-}
-
-static inline void *_fdt_offset_ptr_w(void *fdt, int offset)
-{
- return (void *)(uintptr_t)_fdt_offset_ptr(fdt, offset);
-}
-
-static inline const struct fdt_reserve_entry *_fdt_mem_rsv(const void *fdt, int n)
-{
- const struct fdt_reserve_entry *rsv_table =
- (const struct fdt_reserve_entry *)
- ((const char *)fdt + fdt_off_mem_rsvmap(fdt));
-
- return rsv_table + n;
-}
-static inline struct fdt_reserve_entry *_fdt_mem_rsv_w(void *fdt, int n)
-{
- return (void *)(uintptr_t)_fdt_mem_rsv(fdt, n);
-}
-
-#define FDT_SW_MAGIC (~FDT_MAGIC)
-
-#endif /* _LIBFDT_INTERNAL_H */
+#ifndef _LIBFDT_INTERNAL_H
+#define _LIBFDT_INTERNAL_H
+/*
+ * libfdt - Flat Device Tree manipulation
+ * Copyright (C) 2006 David Gibson, IBM Corporation.
+ *
+ * libfdt is dual licensed: you can use it either under the terms of
+ * the GPL, or the BSD license, at your option.
+ *
+ * a) This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 2 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
+ * MA 02110-1301 USA
+ *
+ * Alternatively,
+ *
+ * b) Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <fdt.h>
+
+#define FDT_ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
+#define FDT_TAGALIGN(x) (FDT_ALIGN((x), FDT_TAGSIZE))
+
+#define FDT_CHECK_HEADER(fdt) \
+ { \
+ int err; \
+ if ((err = fdt_check_header(fdt)) != 0) \
+ return err; \
+ }
+
+int _fdt_check_node_offset(const void *fdt, int offset);
+int _fdt_check_prop_offset(const void *fdt, int offset);
+const char *_fdt_find_string(const char *strtab, int tabsize, const char *s);
+int _fdt_node_end_offset(void *fdt, int nodeoffset);
+
+static inline const void *_fdt_offset_ptr(const void *fdt, int offset)
+{
+ return (const char *)fdt + fdt_off_dt_struct(fdt) + offset;
+}
+
+static inline void *_fdt_offset_ptr_w(void *fdt, int offset)
+{
+ return (void *)(uintptr_t)_fdt_offset_ptr(fdt, offset);
+}
+
+static inline const struct fdt_reserve_entry *_fdt_mem_rsv(const void *fdt, int n)
+{
+ const struct fdt_reserve_entry *rsv_table =
+ (const struct fdt_reserve_entry *)
+ ((const char *)fdt + fdt_off_mem_rsvmap(fdt));
+
+ return rsv_table + n;
+}
+static inline struct fdt_reserve_entry *_fdt_mem_rsv_w(void *fdt, int n)
+{
+ return (void *)(uintptr_t)_fdt_mem_rsv(fdt, n);
+}
+
+#define FDT_SW_MAGIC (~FDT_MAGIC)
+
+#endif /* _LIBFDT_INTERNAL_H */
diff --git a/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.S b/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.S
index f8c4e296c..9c3cc3ce3 100755
--- a/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.S
+++ b/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.S
@@ -1,258 +1,258 @@
-#------------------------------------------------------------------------------
-#
-# Use ARMv6 instruction to operate on a single stack
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#------------------------------------------------------------------------------
-
-/*
-
-This is the stack constructed by the exception handler (low address to high address)
- # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
- Reg Offset
- === ======
- R0 0x00 # stmfd SP!,{R0-R12}
- R1 0x04
- R2 0x08
- R3 0x0c
- R4 0x10
- R5 0x14
- R6 0x18
- R7 0x1c
- R8 0x20
- R9 0x24
- R10 0x28
- R11 0x2c
- R12 0x30
- SP 0x34 # reserved via adding 0x20 (32) to the SP
- LR 0x38
- PC 0x3c
- CPSR 0x40
- DFSR 0x44
- DFAR 0x48
- IFSR 0x4c
- IFAR 0x50
-
- LR 0x54 # SVC Link register (we need to restore it)
-
- LR 0x58 # pushed by srsfd
- CPSR 0x5c
-
- */
-
-
-GCC_ASM_EXPORT(ExceptionHandlersStart)
-GCC_ASM_EXPORT(ExceptionHandlersEnd)
-GCC_ASM_EXPORT(CommonExceptionEntry)
-GCC_ASM_EXPORT(AsmCommonExceptionEntry)
-GCC_ASM_EXPORT(GdbExceptionHandler)
-
-.text
-.align 3
-
-
-//
-// This code gets copied to the ARM vector table
-// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
-//
-ASM_PFX(ExceptionHandlersStart):
-
-ASM_PFX(Reset):
- b ASM_PFX(Reset)
-
-ASM_PFX(UndefinedInstruction):
- b ASM_PFX(UndefinedInstructionEntry)
-
-ASM_PFX(SoftwareInterrupt):
- b ASM_PFX(SoftwareInterruptEntry)
-
-ASM_PFX(PrefetchAbort):
- b ASM_PFX(PrefetchAbortEntry)
-
-ASM_PFX(DataAbort):
- b ASM_PFX(DataAbortEntry)
-
-ASM_PFX(ReservedException):
- b ASM_PFX(ReservedExceptionEntry)
-
-ASM_PFX(Irq):
- b ASM_PFX(Irq)
-
-ASM_PFX(Fiq):
- b ASM_PFX(FiqEntry)
-
-
-ASM_PFX(UndefinedInstructionEntry):
- sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
- srsdb #0x13! @ Store return state on SVC stack
- cpsid f,#0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#1 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(SoftwareInterruptEntry):
- sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
- srsdb #0x13! @ Store return state on SVC stack
- cpsid f @ We are already in SVC mode
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#2 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(PrefetchAbortEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cpsid f,#0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#3 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(DataAbortEntry):
- sub LR,LR,#8
- srsdb #0x13! @ Store return state on SVC stack
- cpsid f,#0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#4
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(ReservedExceptionEntry):
- srsdb #0x13! @ Store return state on SVC stack
- cpsid f,#0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
-
- mov R0,#5
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-ASM_PFX(FiqEntry):
- sub LR,LR,#4
- srsdb #0x13! @ Store return state on SVC stack
- cps #0x13 @ Switch to SVC for common stack
- stmfd SP!,{LR} @ Store the link register for the current mode
- sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} @ Store the register state
- @ Since we have already switch to SVC R8_fiq - R12_fiq
- @ never get used or saved
- mov R0,#7 @ ExceptionType
- ldr R1,ASM_PFX(CommonExceptionEntry)
- bx R1
-
-//
-// This gets patched by the C code that patches in the vector table
-//
-ASM_PFX(CommonExceptionEntry):
- .byte 0x12
- .byte 0x34
- .byte 0x56
- .byte 0x78
-
-ASM_PFX(ExceptionHandlersEnd):
-
-//
-// This code runs from CpuDxe driver loaded address. It is patched into
-// CommonExceptionEntry.
-//
-ASM_PFX(AsmCommonExceptionEntry):
- mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
- str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
-
- mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
- str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
-
- mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
- str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
-
- mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
- str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
-
- ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
- str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
-
- add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R3, R1, #0x1f @ Check CPSR to see if User or System Mode
- cmp R3, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1df))
- cmpne R3, #0x10 @
- stmeqed R2, {lr}^ @ save unbanked lr
- @ else
- stmneed R2, {lr} @ save SVC lr
-
-
- ldr R5, [SP, #0x58] @ PC is the LR pushed by srsfd
- @ Check to see if we have to adjust for Thumb entry
- sub r4, r0, #1 @ if (ExceptionType == 1 || ExceptionType ==2)) {
- cmp r4, #1 @ // UND & SVC have differnt LR adjust for Thumb
- bhi NoAdjustNeeded
-
- tst r1, #0x20 @ if ((CPSR & T)) == T) { // Thumb Mode on entry
- addne R5, R5, #2 @ PC += 2@
- str R5,[SP,#0x58] @ Update LR value pused by srsfd
-
-NoAdjustNeeded:
-
- str R5, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
-
- sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
- str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
-
- @ R0 is ExceptionType
- mov R1,SP @ R1 is SystemContext
-
-/*
-VOID
-EFIAPI
-GdbExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType, R0
- IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
- )
-
-*/
- blx ASM_PFX(GdbExceptionHandler) @ Call exception handler
-
- ldr R1,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
- str R1,[SP,#0x58] @ Store it back to srsfd stack slot so it can be restored
-
- ldr R1,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
- str R1,[SP,#0x5c] @ Store it back to srsfd stack slot so it can be restored
-
- add R3, SP, #0x54 @ Make R3 point to SVC LR saved on entry
- add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R1, R1, #0x1f @ Check to see if User or System Mode
- cmp R1, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1f))
- cmpne R1, #0x10 @
- ldmeqed R2, {lr}^ @ restore unbanked lr
- @ else
- ldmneed R3, {lr} @ restore SVC lr, via ldmfd SP!, {LR}
-
- ldmfd SP!,{R0-R12} @ Restore general purpose registers
- @ Exception handler can not change SP
-
- add SP,SP,#0x20 @ Clear out the remaining stack space
- ldmfd SP!,{LR} @ restore the link register for this context
- rfefd SP! @ return from exception via srsfd stack slot
-
+#------------------------------------------------------------------------------
+#
+# Use ARMv6 instruction to operate on a single stack
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#------------------------------------------------------------------------------
+
+/*
+
+This is the stack constructed by the exception handler (low address to high address)
+ # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
+ Reg Offset
+ === ======
+ R0 0x00 # stmfd SP!,{R0-R12}
+ R1 0x04
+ R2 0x08
+ R3 0x0c
+ R4 0x10
+ R5 0x14
+ R6 0x18
+ R7 0x1c
+ R8 0x20
+ R9 0x24
+ R10 0x28
+ R11 0x2c
+ R12 0x30
+ SP 0x34 # reserved via adding 0x20 (32) to the SP
+ LR 0x38
+ PC 0x3c
+ CPSR 0x40
+ DFSR 0x44
+ DFAR 0x48
+ IFSR 0x4c
+ IFAR 0x50
+
+ LR 0x54 # SVC Link register (we need to restore it)
+
+ LR 0x58 # pushed by srsfd
+ CPSR 0x5c
+
+ */
+
+
+GCC_ASM_EXPORT(ExceptionHandlersStart)
+GCC_ASM_EXPORT(ExceptionHandlersEnd)
+GCC_ASM_EXPORT(CommonExceptionEntry)
+GCC_ASM_EXPORT(AsmCommonExceptionEntry)
+GCC_ASM_EXPORT(GdbExceptionHandler)
+
+.text
+.align 3
+
+
+//
+// This code gets copied to the ARM vector table
+// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
+//
+ASM_PFX(ExceptionHandlersStart):
+
+ASM_PFX(Reset):
+ b ASM_PFX(Reset)
+
+ASM_PFX(UndefinedInstruction):
+ b ASM_PFX(UndefinedInstructionEntry)
+
+ASM_PFX(SoftwareInterrupt):
+ b ASM_PFX(SoftwareInterruptEntry)
+
+ASM_PFX(PrefetchAbort):
+ b ASM_PFX(PrefetchAbortEntry)
+
+ASM_PFX(DataAbort):
+ b ASM_PFX(DataAbortEntry)
+
+ASM_PFX(ReservedException):
+ b ASM_PFX(ReservedExceptionEntry)
+
+ASM_PFX(Irq):
+ b ASM_PFX(Irq)
+
+ASM_PFX(Fiq):
+ b ASM_PFX(FiqEntry)
+
+
+ASM_PFX(UndefinedInstructionEntry):
+ sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsdb #0x13! @ Store return state on SVC stack
+ cpsid f,#0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#1 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(SoftwareInterruptEntry):
+ sub LR, LR, #4 @ Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsdb #0x13! @ Store return state on SVC stack
+ cpsid f @ We are already in SVC mode
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#2 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(PrefetchAbortEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cpsid f,#0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#3 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(DataAbortEntry):
+ sub LR,LR,#8
+ srsdb #0x13! @ Store return state on SVC stack
+ cpsid f,#0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#4
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(ReservedExceptionEntry):
+ srsdb #0x13! @ Store return state on SVC stack
+ cpsid f,#0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+
+ mov R0,#5
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+ASM_PFX(FiqEntry):
+ sub LR,LR,#4
+ srsdb #0x13! @ Store return state on SVC stack
+ cps #0x13 @ Switch to SVC for common stack
+ stmfd SP!,{LR} @ Store the link register for the current mode
+ sub SP,SP,#0x20 @ Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} @ Store the register state
+ @ Since we have already switch to SVC R8_fiq - R12_fiq
+ @ never get used or saved
+ mov R0,#7 @ ExceptionType
+ ldr R1,ASM_PFX(CommonExceptionEntry)
+ bx R1
+
+//
+// This gets patched by the C code that patches in the vector table
+//
+ASM_PFX(CommonExceptionEntry):
+ .byte 0x12
+ .byte 0x34
+ .byte 0x56
+ .byte 0x78
+
+ASM_PFX(ExceptionHandlersEnd):
+
+//
+// This code runs from CpuDxe driver loaded address. It is patched into
+// CommonExceptionEntry.
+//
+ASM_PFX(AsmCommonExceptionEntry):
+ mrc p15, 0, R1, c6, c0, 2 @ Read IFAR
+ str R1, [SP, #0x50] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
+
+ mrc p15, 0, R1, c5, c0, 1 @ Read IFSR
+ str R1, [SP, #0x4c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
+
+ mrc p15, 0, R1, c6, c0, 0 @ Read DFAR
+ str R1, [SP, #0x48] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
+
+ mrc p15, 0, R1, c5, c0, 0 @ Read DFSR
+ str R1, [SP, #0x44] @ Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
+
+ ldr R1, [SP, #0x5c] @ srsdb saved pre-exception CPSR on the stack
+ str R1, [SP, #0x40] @ Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
+
+ add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R3, R1, #0x1f @ Check CPSR to see if User or System Mode
+ cmp R3, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1df))
+ cmpne R3, #0x10 @
+ stmeqed R2, {lr}^ @ save unbanked lr
+ @ else
+ stmneed R2, {lr} @ save SVC lr
+
+
+ ldr R5, [SP, #0x58] @ PC is the LR pushed by srsfd
+ @ Check to see if we have to adjust for Thumb entry
+ sub r4, r0, #1 @ if (ExceptionType == 1 || ExceptionType ==2)) {
+ cmp r4, #1 @ // UND & SVC have differnt LR adjust for Thumb
+ bhi NoAdjustNeeded
+
+ tst r1, #0x20 @ if ((CPSR & T)) == T) { // Thumb Mode on entry
+ addne R5, R5, #2 @ PC += 2@
+ str R5,[SP,#0x58] @ Update LR value pused by srsfd
+
+NoAdjustNeeded:
+
+ str R5, [SP, #0x3c] @ Store it in EFI_SYSTEM_CONTEXT_ARM.PC
+
+ sub R1, SP, #0x60 @ We pused 0x60 bytes on the stack
+ str R1, [SP, #0x34] @ Store it in EFI_SYSTEM_CONTEXT_ARM.SP
+
+ @ R0 is ExceptionType
+ mov R1,SP @ R1 is SystemContext
+
+/*
+VOID
+EFIAPI
+GdbExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType, R0
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
+ )
+
+*/
+ blx ASM_PFX(GdbExceptionHandler) @ Call exception handler
+
+ ldr R1,[SP,#0x3c] @ EFI_SYSTEM_CONTEXT_ARM.PC
+ str R1,[SP,#0x58] @ Store it back to srsfd stack slot so it can be restored
+
+ ldr R1,[SP,#0x40] @ EFI_SYSTEM_CONTEXT_ARM.CPSR
+ str R1,[SP,#0x5c] @ Store it back to srsfd stack slot so it can be restored
+
+ add R3, SP, #0x54 @ Make R3 point to SVC LR saved on entry
+ add R2, SP, #0x38 @ Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R1, R1, #0x1f @ Check to see if User or System Mode
+ cmp R1, #0x1f @ if ((CPSR == 0x10) || (CPSR == 0x1f))
+ cmpne R1, #0x10 @
+ ldmeqed R2, {lr}^ @ restore unbanked lr
+ @ else
+ ldmneed R3, {lr} @ restore SVC lr, via ldmfd SP!, {LR}
+
+ ldmfd SP!,{R0-R12} @ Restore general purpose registers
+ @ Exception handler can not change SP
+
+ add SP,SP,#0x20 @ Clear out the remaining stack space
+ ldmfd SP!,{LR} @ restore the link register for this context
+ rfefd SP! @ return from exception via srsfd stack slot
+
diff --git a/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.asm b/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.asm
index c133073f4..c70fb9248 100755
--- a/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.asm
+++ b/EmbeddedPkg/Library/GdbDebugAgent/Arm/ExceptionSupport.ARMv6.asm
@@ -1,259 +1,259 @@
-//------------------------------------------------------------------------------
-//
-// Use ARMv6 instruction to operate on a single stack
-//
-// Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-//
-// This program and the accompanying materials
-// are licensed and made available under the terms and conditions of the BSD License
-// which accompanies this distribution. The full text of the license may be found at
-// http://opensource.org/licenses/bsd-license.php
-//
-// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-//
-//------------------------------------------------------------------------------
-
-
-
-/*
-
-This is the stack constructed by the exception handler (low address to high address)
- # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
- Reg Offset
- === ======
- R0 0x00 # stmfd SP!,{R0-R12}
- R1 0x04
- R2 0x08
- R3 0x0c
- R4 0x10
- R5 0x14
- R6 0x18
- R7 0x1c
- R8 0x20
- R9 0x24
- R10 0x28
- R11 0x2c
- R12 0x30
- SP 0x34 # reserved via adding 0x20 (32) to the SP
- LR 0x38
- PC 0x3c
- CPSR 0x40
- DFSR 0x44
- DFAR 0x48
- IFSR 0x4c
- IFAR 0x50
-
- LR 0x54 # SVC Link register (we need to restore it)
-
- LR 0x58 # pushed by srsfd
- CPSR 0x5c
-
- */
-
-
- EXPORT ExceptionHandlersStart
- EXPORT ExceptionHandlersEnd
- EXPORT CommonExceptionEntry
- EXPORT AsmCommonExceptionEntry
- IMPORT GdbExceptionHandler
-
- PRESERVE8
- AREA DxeExceptionHandlers, CODE, READONLY
-
-//
-// This code gets copied to the ARM vector table
-// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
-//
-ExceptionHandlersStart
-
-Reset
- b Reset
-
-UndefinedInstruction
- b UndefinedInstructionEntry
-
-SoftwareInterrupt
- b SoftwareInterruptEntry
-
-PrefetchAbort
- b PrefetchAbortEntry
-
-DataAbort
- b DataAbortEntry
-
-ReservedException
- b ReservedExceptionEntry
-
-Irq
- b Irq
-
-Fiq
- b FiqEntry
-
-
-UndefinedInstructionEntry
- sub LR, LR, #4 ; Only -2 for Thumb, adjust in CommonExceptionEntry
- srsfd #0x13! ; Store return state on SVC stack
- cpsid f, #0x13 ; Switch to SVC for common stack
- stmfd SP!,{LR} ; Store the link register for the current mode
- sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} ; Store the register state
-
- mov R0,#1 ; ExceptionType
- ldr R1,CommonExceptionEntry;
- bx R1
-
-SoftwareInterruptEntry
- sub LR, LR, #4 ; Only -2 for Thumb, adjust in CommonExceptionEntry
- srsfd #0x13! ; Store return state on SVC stack
- cpsid f ; We are already in SVC mode
- stmfd SP!,{LR} ; Store the link register for the current mode
- sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} ; Store the register state
-
- mov R0,#2 ; ExceptionType
- ldr R1,CommonExceptionEntry
- bx R1
-
-PrefetchAbortEntry
- sub LR,LR,#4
- srsfd #0x13! ; Store return state on SVC stack
- cpsid f, #0x13 ; Switch to SVC for common stack
- stmfd SP!,{LR} ; Store the link register for the current mode
- sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} ; Store the register state
-
- mov R0,#3 ; ExceptionType
- ldr R1,CommonExceptionEntry
- bx R1
-
-DataAbortEntry
- sub LR,LR,#8
- srsfd #0x13! ; Store return state on SVC stack
- cpsid f, #0x13 ; Switch to SVC for common stack
- stmfd SP!,{LR} ; Store the link register for the current mode
- sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} ; Store the register state
-
- mov R0,#4 ; ExceptionType
- ldr R1,CommonExceptionEntry
- bx R1
-
-ReservedExceptionEntry
- srsfd #0x13! ; Store return state on SVC stack
- cpsid f, #0x13 ; Switch to SVC for common stack
- stmfd SP!,{LR} ; Store the link register for the current mode
- sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} ; Store the register state
-
- mov R0,#5 ; ExceptionType
- ldr R1,CommonExceptionEntry
- bx R1
-
-FiqEntry
- sub LR,LR,#4
- srsfd #0x13! ; Store return state on SVC stack
- cps #0x13 ; Switch to SVC for common stack
- stmfd SP!,{LR} ; Store the link register for the current mode
- sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
- stmfd SP!,{R0-R12} ; Store the register state
- ; Since we have already switch to SVC R8_fiq - R12_fiq
- ; never get used or saved
- mov R0,#7 ; ExceptionType
- ldr R1,CommonExceptionEntry
- bx R1
-
-//
-// This gets patched by the C code that patches in the vector table
-//
-CommonExceptionEntry
- dcd 0x12345678
-
-ExceptionHandlersEnd
-
-//
-// This code runs from CpuDxe driver loaded address. It is patched into
-// CommonExceptionEntry.
-//
-AsmCommonExceptionEntry
- mrc p15, 0, R1, c6, c0, 2 ; Read IFAR
- str R1, [SP, #0x50] ; Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
-
- mrc p15, 0, R1, c5, c0, 1 ; Read IFSR
- str R1, [SP, #0x4c] ; Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
-
- mrc p15, 0, R1, c6, c0, 0 ; Read DFAR
- str R1, [SP, #0x48] ; Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
-
- mrc p15, 0, R1, c5, c0, 0 ; Read DFSR
- str R1, [SP, #0x44] ; Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
-
- ldr R1, [SP, #0x5c] ; srsfd saved pre-exception CPSR on the stack
- str R1, [SP, #0x40] ; Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
-
- add R2, SP, #0x38 ; Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R3, R1, #0x1f ; Check CPSR to see if User or System Mode
- cmp R3, #0x1f ; if ((CPSR == 0x10) || (CPSR == 0x1df))
- cmpne R3, #0x10 ;
- stmeqed R2, {lr}^ ; save unbanked lr
- ; else
- stmneed R2, {lr} ; save SVC lr
-
-
- ldr R5, [SP, #0x58] ; PC is the LR pushed by srsfd
- ; Check to see if we have to adjust for Thumb entry
- sub r4, r0, #1 ; if (ExceptionType == 1 || ExceptionType ==2)) {
- cmp r4, #1 ; // UND & SVC have differnt LR adjust for Thumb
- bhi NoAdjustNeeded
-
- tst r1, #0x20 ; if ((CPSR & T)) == T) { // Thumb Mode on entry
- addne R5, R5, #2 ; PC += 2;
- str R5,[SP,#0x58] ; Update LR value pused by srsfd
-
-NoAdjustNeeded
-
- str R5, [SP, #0x3c] ; Store it in EFI_SYSTEM_CONTEXT_ARM.PC
-
- sub R1, SP, #0x60 ; We pused 0x60 bytes on the stack
- str R1, [SP, #0x34] ; Store it in EFI_SYSTEM_CONTEXT_ARM.SP
-
- ; R0 is ExceptionType
- mov R1,SP ; R1 is SystemContext
-
-/*
-VOID
-EFIAPI
-GdbExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType, R0
- IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
- )
-
-*/
- blx GdbExceptionHandler ; Call exception handler
-
- ldr R1,[SP,#0x3c] ; EFI_SYSTEM_CONTEXT_ARM.PC
- str R1,[SP,#0x58] ; Store it back to srsfd stack slot so it can be restored
-
- ldr R1,[SP,#0x40] ; EFI_SYSTEM_CONTEXT_ARM.CPSR
- str R1,[SP,#0x5c] ; Store it back to srsfd stack slot so it can be restored
-
- add R3, SP, #0x54 ; Make R3 point to SVC LR saved on entry
- add R2, SP, #0x38 ; Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
- and R1, R1, #0x1f ; Check to see if User or System Mode
- cmp R1, #0x1f ; if ((CPSR == 0x10) || (CPSR == 0x1f))
- cmpne R1, #0x10 ;
- ldmeqed R2, {lr}^ ; restore unbanked lr
- ; else
- ldmneed R3, {lr} ; restore SVC lr, via ldmfd SP!, {LR}
-
- ldmfd SP!,{R0-R12} ; Restore general purpose registers
- ; Exception handler can not change SP
-
- add SP,SP,#0x20 ; Clear out the remaining stack space
- ldmfd SP!,{LR} ; restore the link register for this context
- rfefd SP! ; return from exception via srsfd stack slot
-
- END
-
-
+//------------------------------------------------------------------------------
+//
+// Use ARMv6 instruction to operate on a single stack
+//
+// Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+//
+// This program and the accompanying materials
+// are licensed and made available under the terms and conditions of the BSD License
+// which accompanies this distribution. The full text of the license may be found at
+// http://opensource.org/licenses/bsd-license.php
+//
+// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+//
+//------------------------------------------------------------------------------
+
+
+
+/*
+
+This is the stack constructed by the exception handler (low address to high address)
+ # R0 - IFAR is EFI_SYSTEM_CONTEXT for ARM
+ Reg Offset
+ === ======
+ R0 0x00 # stmfd SP!,{R0-R12}
+ R1 0x04
+ R2 0x08
+ R3 0x0c
+ R4 0x10
+ R5 0x14
+ R6 0x18
+ R7 0x1c
+ R8 0x20
+ R9 0x24
+ R10 0x28
+ R11 0x2c
+ R12 0x30
+ SP 0x34 # reserved via adding 0x20 (32) to the SP
+ LR 0x38
+ PC 0x3c
+ CPSR 0x40
+ DFSR 0x44
+ DFAR 0x48
+ IFSR 0x4c
+ IFAR 0x50
+
+ LR 0x54 # SVC Link register (we need to restore it)
+
+ LR 0x58 # pushed by srsfd
+ CPSR 0x5c
+
+ */
+
+
+ EXPORT ExceptionHandlersStart
+ EXPORT ExceptionHandlersEnd
+ EXPORT CommonExceptionEntry
+ EXPORT AsmCommonExceptionEntry
+ IMPORT GdbExceptionHandler
+
+ PRESERVE8
+ AREA DxeExceptionHandlers, CODE, READONLY
+
+//
+// This code gets copied to the ARM vector table
+// ExceptionHandlersStart - ExceptionHandlersEnd gets copied
+//
+ExceptionHandlersStart
+
+Reset
+ b Reset
+
+UndefinedInstruction
+ b UndefinedInstructionEntry
+
+SoftwareInterrupt
+ b SoftwareInterruptEntry
+
+PrefetchAbort
+ b PrefetchAbortEntry
+
+DataAbort
+ b DataAbortEntry
+
+ReservedException
+ b ReservedExceptionEntry
+
+Irq
+ b Irq
+
+Fiq
+ b FiqEntry
+
+
+UndefinedInstructionEntry
+ sub LR, LR, #4 ; Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsfd #0x13! ; Store return state on SVC stack
+ cpsid f, #0x13 ; Switch to SVC for common stack
+ stmfd SP!,{LR} ; Store the link register for the current mode
+ sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} ; Store the register state
+
+ mov R0,#1 ; ExceptionType
+ ldr R1,CommonExceptionEntry;
+ bx R1
+
+SoftwareInterruptEntry
+ sub LR, LR, #4 ; Only -2 for Thumb, adjust in CommonExceptionEntry
+ srsfd #0x13! ; Store return state on SVC stack
+ cpsid f ; We are already in SVC mode
+ stmfd SP!,{LR} ; Store the link register for the current mode
+ sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} ; Store the register state
+
+ mov R0,#2 ; ExceptionType
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+PrefetchAbortEntry
+ sub LR,LR,#4
+ srsfd #0x13! ; Store return state on SVC stack
+ cpsid f, #0x13 ; Switch to SVC for common stack
+ stmfd SP!,{LR} ; Store the link register for the current mode
+ sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} ; Store the register state
+
+ mov R0,#3 ; ExceptionType
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+DataAbortEntry
+ sub LR,LR,#8
+ srsfd #0x13! ; Store return state on SVC stack
+ cpsid f, #0x13 ; Switch to SVC for common stack
+ stmfd SP!,{LR} ; Store the link register for the current mode
+ sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} ; Store the register state
+
+ mov R0,#4 ; ExceptionType
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+ReservedExceptionEntry
+ srsfd #0x13! ; Store return state on SVC stack
+ cpsid f, #0x13 ; Switch to SVC for common stack
+ stmfd SP!,{LR} ; Store the link register for the current mode
+ sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} ; Store the register state
+
+ mov R0,#5 ; ExceptionType
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+FiqEntry
+ sub LR,LR,#4
+ srsfd #0x13! ; Store return state on SVC stack
+ cps #0x13 ; Switch to SVC for common stack
+ stmfd SP!,{LR} ; Store the link register for the current mode
+ sub SP,SP,#0x20 ; Save space for SP, LR, PC, IFAR - CPSR
+ stmfd SP!,{R0-R12} ; Store the register state
+ ; Since we have already switch to SVC R8_fiq - R12_fiq
+ ; never get used or saved
+ mov R0,#7 ; ExceptionType
+ ldr R1,CommonExceptionEntry
+ bx R1
+
+//
+// This gets patched by the C code that patches in the vector table
+//
+CommonExceptionEntry
+ dcd 0x12345678
+
+ExceptionHandlersEnd
+
+//
+// This code runs from CpuDxe driver loaded address. It is patched into
+// CommonExceptionEntry.
+//
+AsmCommonExceptionEntry
+ mrc p15, 0, R1, c6, c0, 2 ; Read IFAR
+ str R1, [SP, #0x50] ; Store it in EFI_SYSTEM_CONTEXT_ARM.IFAR
+
+ mrc p15, 0, R1, c5, c0, 1 ; Read IFSR
+ str R1, [SP, #0x4c] ; Store it in EFI_SYSTEM_CONTEXT_ARM.IFSR
+
+ mrc p15, 0, R1, c6, c0, 0 ; Read DFAR
+ str R1, [SP, #0x48] ; Store it in EFI_SYSTEM_CONTEXT_ARM.DFAR
+
+ mrc p15, 0, R1, c5, c0, 0 ; Read DFSR
+ str R1, [SP, #0x44] ; Store it in EFI_SYSTEM_CONTEXT_ARM.DFSR
+
+ ldr R1, [SP, #0x5c] ; srsfd saved pre-exception CPSR on the stack
+ str R1, [SP, #0x40] ; Store it in EFI_SYSTEM_CONTEXT_ARM.CPSR
+
+ add R2, SP, #0x38 ; Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R3, R1, #0x1f ; Check CPSR to see if User or System Mode
+ cmp R3, #0x1f ; if ((CPSR == 0x10) || (CPSR == 0x1df))
+ cmpne R3, #0x10 ;
+ stmeqed R2, {lr}^ ; save unbanked lr
+ ; else
+ stmneed R2, {lr} ; save SVC lr
+
+
+ ldr R5, [SP, #0x58] ; PC is the LR pushed by srsfd
+ ; Check to see if we have to adjust for Thumb entry
+ sub r4, r0, #1 ; if (ExceptionType == 1 || ExceptionType ==2)) {
+ cmp r4, #1 ; // UND & SVC have differnt LR adjust for Thumb
+ bhi NoAdjustNeeded
+
+ tst r1, #0x20 ; if ((CPSR & T)) == T) { // Thumb Mode on entry
+ addne R5, R5, #2 ; PC += 2;
+ str R5,[SP,#0x58] ; Update LR value pused by srsfd
+
+NoAdjustNeeded
+
+ str R5, [SP, #0x3c] ; Store it in EFI_SYSTEM_CONTEXT_ARM.PC
+
+ sub R1, SP, #0x60 ; We pused 0x60 bytes on the stack
+ str R1, [SP, #0x34] ; Store it in EFI_SYSTEM_CONTEXT_ARM.SP
+
+ ; R0 is ExceptionType
+ mov R1,SP ; R1 is SystemContext
+
+/*
+VOID
+EFIAPI
+GdbExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType, R0
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext R1
+ )
+
+*/
+ blx GdbExceptionHandler ; Call exception handler
+
+ ldr R1,[SP,#0x3c] ; EFI_SYSTEM_CONTEXT_ARM.PC
+ str R1,[SP,#0x58] ; Store it back to srsfd stack slot so it can be restored
+
+ ldr R1,[SP,#0x40] ; EFI_SYSTEM_CONTEXT_ARM.CPSR
+ str R1,[SP,#0x5c] ; Store it back to srsfd stack slot so it can be restored
+
+ add R3, SP, #0x54 ; Make R3 point to SVC LR saved on entry
+ add R2, SP, #0x38 ; Make R2 point to EFI_SYSTEM_CONTEXT_ARM.LR
+ and R1, R1, #0x1f ; Check to see if User or System Mode
+ cmp R1, #0x1f ; if ((CPSR == 0x10) || (CPSR == 0x1f))
+ cmpne R1, #0x10 ;
+ ldmeqed R2, {lr}^ ; restore unbanked lr
+ ; else
+ ldmneed R3, {lr} ; restore SVC lr, via ldmfd SP!, {LR}
+
+ ldmfd SP!,{R0-R12} ; Restore general purpose registers
+ ; Exception handler can not change SP
+
+ add SP,SP,#0x20 ; Clear out the remaining stack space
+ ldmfd SP!,{LR} ; restore the link register for this context
+ rfefd SP! ; return from exception via srsfd stack slot
+
+ END
+
+
diff --git a/EmbeddedPkg/Library/GdbDebugAgent/Arm/Processor.c b/EmbeddedPkg/Library/GdbDebugAgent/Arm/Processor.c
index e6aabf940..f22a19dde 100755
--- a/EmbeddedPkg/Library/GdbDebugAgent/Arm/Processor.c
+++ b/EmbeddedPkg/Library/GdbDebugAgent/Arm/Processor.c
@@ -447,23 +447,23 @@ RemoveBreakPoint (
}
-/**
- Send the T signal with the given exception type (in gdb order) and possibly
- with n:r pairs related to the watchpoints
-
- @param SystemContext Register content at time of the exception
- @param GdbExceptionType GDB exception type
- **/
-VOID
-ProcessorSendTSignal (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINT8 GdbExceptionType,
- IN OUT CHAR8 *TSignalPtr,
- IN UINTN SizeOfBuffer
- )
-{
- *TSignalPtr = '\0';
-}
+/**
+ Send the T signal with the given exception type (in gdb order) and possibly
+ with n:r pairs related to the watchpoints
+
+ @param SystemContext Register content at time of the exception
+ @param GdbExceptionType GDB exception type
+ **/
+VOID
+ProcessorSendTSignal (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINT8 GdbExceptionType,
+ IN OUT CHAR8 *TSignalPtr,
+ IN UINTN SizeOfBuffer
+ )
+{
+ *TSignalPtr = '\0';
+}
/**
FIQ state is only changed by FIQ exception. We don't want to take FIQ
@@ -475,21 +475,21 @@ ProcessorSendTSignal (
@return TRUE We are in the GDB stub exception preamble
@return FALSE We are not in GDB stub code
- **/
-BOOLEAN
-InFiqCrack (
- IN UINT32 PC
- )
-{
- UINT32 VectorBase = PcdGet32 (PcdCpuVectorBaseAddress);
- UINT32 Length = (UINTN)ExceptionHandlersEnd - (UINTN)ExceptionHandlersStart;
-
- if ((PC >= VectorBase) && (PC <= (VectorBase + Length))) {
- return TRUE;
- }
-
- return FALSE;
-}
+ **/
+BOOLEAN
+InFiqCrack (
+ IN UINT32 PC
+ )
+{
+ UINT32 VectorBase = PcdGet32 (PcdCpuVectorBaseAddress);
+ UINT32 Length = (UINTN)ExceptionHandlersEnd - (UINTN)ExceptionHandlersStart;
+
+ if ((PC >= VectorBase) && (PC <= (VectorBase + Length))) {
+ return TRUE;
+ }
+
+ return FALSE;
+}
/**
@@ -526,24 +526,24 @@ ProcessorControlC (
return FALSE;
}
- while (TRUE) {
- if (!GdbIsCharAvailable ()) {
- //
- // No characters are pending so exit the loop
- //
- Return = TRUE;
- break;
- }
-
- Char = GdbGetChar ();
- if (Char == 0x03) {
- //
- // We have a ctrl-c so exit and process exception for ctrl-c
- //
- Return = FALSE;
- break;
- }
- }
+ while (TRUE) {
+ if (!GdbIsCharAvailable ()) {
+ //
+ // No characters are pending so exit the loop
+ //
+ Return = TRUE;
+ break;
+ }
+
+ Char = GdbGetChar ();
+ if (Char == 0x03) {
+ //
+ // We have a ctrl-c so exit and process exception for ctrl-c
+ //
+ Return = FALSE;
+ break;
+ }
+ }
DebugAgentTimerEndOfInterrupt ();
@@ -622,13 +622,13 @@ InitializeDebugAgent (
IN VOID *Context, OPTIONAL
IN DEBUG_AGENT_CONTINUE Function OPTIONAL
)
-{
+{
UINTN Offset;
UINTN Length;
BOOLEAN IrqEnabled;
UINT32 *VectorBase;
-
+
//
// Disable interrupts
//
diff --git a/EmbeddedPkg/Library/GdbDebugAgent/GdbDebugAgent.h b/EmbeddedPkg/Library/GdbDebugAgent/GdbDebugAgent.h
index 2d0570e3d..44c82f347 100755
--- a/EmbeddedPkg/Library/GdbDebugAgent/GdbDebugAgent.h
+++ b/EmbeddedPkg/Library/GdbDebugAgent/GdbDebugAgent.h
@@ -1,697 +1,697 @@
-/** @file
- Private include file for GDB stub
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __GCC_DEBUG_AGENT_INTERNAL__
-#define __GCC_DEBUG_AGENT_INTERNAL__
-
-#include <Uefi.h>
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PcdLib.h>
-#include <Library/GdbSerialLib.h>
-#include <Library/PrintLib.h>
-#include <Library/CacheMaintenanceLib.h>
-#include <Library/DebugAgentTimerLib.h>
+/** @file
+ Private include file for GDB stub
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __GCC_DEBUG_AGENT_INTERNAL__
+#define __GCC_DEBUG_AGENT_INTERNAL__
+
+#include <Uefi.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+#include <Library/GdbSerialLib.h>
+#include <Library/PrintLib.h>
+#include <Library/CacheMaintenanceLib.h>
+#include <Library/DebugAgentTimerLib.h>
#include <Library/DebugAgentLib.h>
-
-#include <IndustryStandard/PeImage.h>
-#include <Protocol/DebugSupport.h>
-
-extern CONST CHAR8 mHexToStr[];
-
-// maximum size of input and output buffers
-// This value came from the show remote command of the gdb we tested against
-#define MAX_BUF_SIZE 2000
-
-// maximum size of address buffer
-#define MAX_ADDR_SIZE 32
-
-// maximum size of register number buffer
-#define MAX_REG_NUM_BUF_SIZE 32
-
-// maximum size of length buffer
-#define MAX_LENGTH_SIZE 32
-
-// maximum size of T signal members
-#define MAX_T_SIGNAL_SIZE 64
-
-// the mask used to clear all the cache
-#define TF_BIT 0x00000100
-
-
-//
-// GDB Signal definitions - generic names for interrupts
-//
-#define GDB_SIGINT 2 // Interrupt process via ctrl-c
-#define GDB_SIGILL 4 // Illegal instruction
-#define GDB_SIGTRAP 5 // Trace Trap (Breakpoint and SingleStep)
-#define GDB_SIGEMT 7 // Emulator Trap
-#define GDB_SIGFPE 8 // Floating point exception
-#define GDB_SIGSEGV 11 // Setgment violation, page fault
-
-
-//
-// GDB File I/O Error values, zero means no error
-// Includes all general GDB Unix like error values
-//
-#define GDB_EBADMEMADDRBUFSIZE 11 // the buffer that stores memory Address to be read from/written to is not the right size
-#define GDB_EBADMEMLENGBUFSIZE 12 // the buffer that stores Length is not the right size
-#define GDB_EBADMEMLENGTH 13 // Length, the given number of bytes to read or write, is not the right size
-#define GDB_EBADMEMDATA 14 // one of the bytes or nibbles of the memory is leess than 0
-#define GDB_EBADMEMDATASIZE 15 // the memory data, 'XX..', is too short or too long
-#define GDB_EBADBUFSIZE 21 // the buffer created is not the correct size
-#define GDB_EINVALIDARG 31 // argument is invalid
-#define GDB_ENOSPACE 41 //
-#define GDB_EINVALIDBRKPOINTTYPE 51 // the breakpoint type is not recognized
-#define GDB_EINVALIDREGNUM 61 // given register number is not valid: either <0 or >=Number of Registers
-#define GDB_EUNKNOWN 255 // unknown
-
-
-//
-// These devices are open by GDB so we can just read and write to them
-//
-#define GDB_STDIN 0x00
-#define GDB_STDOUT 0x01
-#define GDB_STDERR 0x02
-
-//
-//Define Register size for different architectures
-//
-#if defined (MDE_CPU_IA32)
-#define REG_SIZE 32
-#elif defined (MDE_CPU_X64)
-#define REG_SIZE 64
-#elif defined (MDE_CPU_ARM)
-#define REG_SIZE 32
-#endif
-
-
-typedef struct {
- EFI_EXCEPTION_TYPE Exception;
- UINT8 SignalNo;
-} EFI_EXCEPTION_TYPE_ENTRY;
-
-
-#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
-
-//
-// Byte packed structure for DR6
-// 32-bits on IA-32
-// 64-bits on X64. The upper 32-bits on X64 are reserved
-//
-typedef union {
- struct {
- UINT32 B0:1; // Breakpoint condition detected
- UINT32 B1:1; // Breakpoint condition detected
- UINT32 B2:1; // Breakpoint condition detected
- UINT32 B3:1; // Breakpoint condition detected
- UINT32 Reserved_1:9; // Reserved
- UINT32 BD:1; // Debug register access detected
- UINT32 BS:1; // Single step
- UINT32 BT:1; // Task switch
- UINT32 Reserved_2:16; // Reserved
- } Bits;
- UINTN UintN;
-} IA32_DR6;
-
-//
-// Byte packed structure for DR7
-// 32-bits on IA-32
-// 64-bits on X64. The upper 32-bits on X64 are reserved
-//
-typedef union {
- struct {
- UINT32 L0:1; // Local breakpoint enable
- UINT32 G0:1; // Global breakpoint enable
- UINT32 L1:1; // Local breakpoint enable
- UINT32 G1:1; // Global breakpoint enable
- UINT32 L2:1; // Local breakpoint enable
- UINT32 G2:1; // Global breakpoint enable
- UINT32 L3:1; // Local breakpoint enable
- UINT32 G3:1; // Global breakpoint enable
- UINT32 LE:1; // Local exact breakpoint enable
- UINT32 GE:1; // Global exact breakpoint enable
- UINT32 Reserved_1:3; // Reserved
- UINT32 GD:1; // Global detect enable
- UINT32 Reserved_2:2; // Reserved
- UINT32 RW0:2; // Read/Write field
- UINT32 LEN0:2; // Length field
- UINT32 RW1:2; // Read/Write field
- UINT32 LEN1:2; // Length field
- UINT32 RW2:2; // Read/Write field
- UINT32 LEN2:2; // Length field
- UINT32 RW3:2; // Read/Write field
- UINT32 LEN3:2; // Length field
- } Bits;
- UINTN UintN;
-} IA32_DR7;
-
-#endif /* if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64) */
-
-typedef enum {
- InstructionExecution, //Hardware breakpoint
- DataWrite, //watch
- DataRead, //rwatch
- DataReadWrite, //awatch
- SoftwareBreakpoint, //Software breakpoint
- NotSupported
-} BREAK_TYPE;
-
-//
-// Array of exception types that need to be hooked by the debugger
-//
-extern EFI_EXCEPTION_TYPE_ENTRY gExceptionType[];
-
-//
-// If the periodic callback is called while we are processing an F packet we need
-// to let the callback know to not read from the serail stream as it could steal
-// characters from the F reponse packet
-//
-extern BOOLEAN gProcessingFPacket;
-
-
-/**
- Return the number of entries in the gExceptionType[]
-
- @retval UINTN, the number of entries in the gExceptionType[] array.
- **/
-UINTN
-MaxEfiException (
- VOID
- );
-
-
-/**
- Check to see if the ISA is supported.
- ISA = Instruction Set Architecture
-
- @retval TRUE if Isa is supported,
- FALSE otherwise.
- **/
-BOOLEAN
-CheckIsa (
- IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
- );
-
-
-/**
- Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
-
- @param SystemContext Register content at time of the exception
- @param GdbExceptionType GDB exception type
- **/
-
-VOID
-GdbSendTSignal (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINT8 GdbExceptionType
- );
-
-
-/**
- Translates the EFI mapping to GDB mapping
-
- @param EFIExceptionType EFI Exception that is being processed
- @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
- **/
-UINT8
-ConvertEFItoGDBtype (
- IN EFI_EXCEPTION_TYPE EFIExceptionType
- );
-
-
-/**
- Empties the given buffer
- @param *Buf pointer to the first element in buffer to be emptied
- **/
-VOID
-EmptyBuffer (
- IN CHAR8 *Buf
- );
-
-
-/**
- Converts an 8-bit Hex Char into a INTN.
-
- @param Char - the hex character to be converted into UINTN
- @retval a INTN, from 0 to 15, that corressponds to Char
- -1 if Char is not a hex character
- **/
-INTN
-HexCharToInt (
- IN CHAR8 Char
- );
-
-
-/** 'E NN'
- Send an error with the given error number after converting to hex.
- The error number is put into the buffer in hex. '255' is the biggest errno we can send.
- ex: 162 will be sent as A2.
-
- @param errno the error number that will be sent
- **/
-VOID
-EFIAPI
-SendError (
- IN UINT8 ErrorNum
- );
-
-
-/**
- Send 'OK' when the function is done executing successfully.
- **/
-VOID
-SendSuccess (
- VOID
- );
-
-
-/**
- Send empty packet to specify that particular command/functionality is not supported.
- **/
-VOID
-SendNotSupported (
- VOID
- );
-
-/** ‘p n’
- Reads the n-th register's value into an output buffer and sends it as a packet
- @param SystemContext Register content at time of the exception
- @param InBuffer This is the input buffer received from gdb server
- **/
-VOID
-ReadNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- );
-
-
-/** ‘g’
- Reads the general registers into an output buffer and sends it as a packet
- @param SystemContext Register content at time of the exception
- **/
-VOID
-ReadGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/** ‘P n...=r...’
- Writes the new value of n-th register received into the input buffer to the n-th register
- @param SystemContext Register content at time of the exception
- @param InBuffer This is the input buffer received from gdb server
- **/
-VOID
-WriteNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- );
-
-
-/** ‘G XX...’
- Writes the new values received into the input buffer to the general registers
- @param SystemContext Register content at time of the exception
- @param InBuffer Pointer to the input buffer received from gdb server
- **/
-
-VOID
-WriteGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- );
-
-
-/** ‘m addr,length ’
- Find the Length of the area to read and the start addres. Finally, pass them to
- another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
- send it as a packet.
-
- @param *PacketData Pointer to Payload data for the packet
- **/
-VOID
-ReadFromMemory (
- IN CHAR8 *PacketData
- );
-
-
-/** ‘M addr,length :XX...’
- Find the Length of the area in bytes to write and the start addres. Finally, pass them to
- another function, TransferFromInBufToMem, that will write to that memory space the info in
- the input buffer.
-
- @param PacketData Pointer to Payload data for the packet
- **/
-VOID
-WriteToMemory (
- IN CHAR8 *PacketData
- );
-
-
-/** ‘c [addr ]’
- Continue. addr is Address to resume. If addr is omitted, resume at current
- Address.
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to PacketData
- **/
-
-VOID
-ContinueAtAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-
-/** ‘s [addr ]’
- Single step. addr is the Address at which to resume. If addr is omitted, resume
- at same Address.
-
- @param SystemContext Register content at time of the exception
- @param PacketData Pointer to Payload data for the packet
- **/
-VOID
-SingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-/**
- Insert Single Step in the SystemContext
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-AddSingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-/**
- Remove Single Step in the SystemContext
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-RemoveSingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/**
- ‘Z1, [addr], [length]’
- ‘Z2, [addr], [length]’
- ‘Z3, [addr], [length]’
- ‘Z4, [addr], [length]’
-
- Insert hardware breakpoint/watchpoint at address addr of size length
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-InsertBreakPoint(
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-
-/**
- ‘z1, [addr], [length]’
- ‘z2, [addr], [length]’
- ‘z3, [addr], [length]’
- ‘z4, [addr], [length]’
-
- Remove hardware breakpoint/watchpoint at address addr of size length
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-RemoveBreakPoint(
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- );
-
-
-/**
- Exception Hanldler for GDB. It will be called for all exceptions
- registered via the gExceptionType[] array.
-
- @param ExceptionType Exception that is being processed
- @param SystemContext Register content at time of the exception
-
- **/
-VOID
-EFIAPI
-GdbExceptionHandler (
- IN EFI_EXCEPTION_TYPE ExceptionType,
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/**
- Periodic callback for GDB. This function is used to catch a ctrl-c or other
- break in type command from GDB.
-
- @param SystemContext Register content at time of the call
-
- **/
-VOID
-EFIAPI
-GdbPeriodicCallBack (
- IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
-/**
- Make two serail consoles: 1) StdIn and StdOut via GDB. 2) StdErr via GDB.
-
- These console show up on the remote system running GDB
-
-**/
-
-VOID
-GdbInitializeSerialConsole (
- VOID
- );
-
-
-/**
- Send a GDB Remote Serial Protocol Packet
-
- $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
- the packet teminating character '#' and the two digit checksum.
-
- If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
- in an infinit loop. This is so if you unplug the debugger code just keeps running
-
- @param PacketData Payload data for the packet
-
- @retval Number of bytes of packet data sent.
-
-**/
-UINTN
-SendPacket (
- IN CHAR8 *PacketData
- );
-
-
-/**
- Receive a GDB Remote Serial Protocol Packet
-
- $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
- the packet teminating character '#' and the two digit checksum.
-
- If host re-starts sending a packet without ending the previous packet, only the last valid packet is proccessed.
- (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
-
- If an ack '+' is not sent resend the packet
-
- @param PacketData Payload data for the packet
-
- @retval Number of bytes of packet data received.
-
- **/
-UINTN
-ReceivePacket (
- OUT CHAR8 *PacketData,
- IN UINTN PacketDataSize
- );
-
-
-/**
- Read data from a FileDescriptor. On success number of bytes read is returned. Zero indicates
- the end of a file. On error -1 is returned. If count is zero, GdbRead returns zero.
-
- @param FileDescriptor Device to talk to.
- @param Buffer Buffer to hold Count bytes that were read
- @param Count Number of bytes to transfer.
-
- @retval -1 Error
- @retval {other} Number of bytes read.
-
-**/
-INTN
-GdbRead (
- IN INTN FileDescriptor,
- OUT VOID *Buffer,
- IN UINTN Count
- );
-
-
-/**
- Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
- nothing was written. On error -1 is returned.
-
- @param FileDescriptor Device to talk to.
- @param Buffer Buffer to hold Count bytes that are to be written
- @param Count Number of bytes to transfer.
-
- @retval -1 Error
- @retval {other} Number of bytes written.
-
-**/
-INTN
-GdbWrite (
- IN INTN FileDescriptor,
- OUT CONST VOID *Buffer,
- IN UINTN Count
- );
-
-UINTN *
-FindPointerToRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber
- );
-
-CHAR8 *
-BasicReadRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *OutBufPtr
- );
-
-VOID
-TransferFromInBufToMem (
- IN UINTN Length,
- IN UINT8 *Address,
- IN CHAR8 *NewData
- );
-
-VOID
-TransferFromMemToOutBufAndSend (
- IN UINTN Length,
- IN UINT8 *Address
- );
-
-CHAR8 *
-BasicWriteRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *InBufPtr
- );
-
-VOID
-PrintReg (
- EFI_SYSTEM_CONTEXT SystemContext
- );
-
-UINTN
-ParseBreakpointPacket (
- IN CHAR8 *PacketData,
- OUT UINTN *Type,
- OUT UINTN *Address,
- OUT UINTN *Length
- );
-
-UINTN
-GetBreakpointDataAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- );
-
-UINTN
-GetBreakpointDetected (
- IN EFI_SYSTEM_CONTEXT SystemContext
- );
-
-BREAK_TYPE
-GetBreakpointType (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- );
-
-UINTN
-ConvertLengthData (
- IN UINTN Length
- );
-
-EFI_STATUS
-FindNextFreeDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- OUT UINTN *Register
- );
-
-EFI_STATUS
-EnableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type
- );
-
-EFI_STATUS
-FindMatchingDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type,
- OUT UINTN *Register
- );
-
-EFI_STATUS
-DisableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register
- );
-
-VOID
-InitializeProcessor (
- VOID
- );
-
-/**
- Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
-
- @param SystemContext Register content at time of the exception
- @param GdbExceptionType GDB exception type
- **/
-VOID
-ProcessorSendTSignal (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINT8 GdbExceptionType,
- IN OUT CHAR8 *TSignalPtr,
- IN UINTN SizeOfBuffer
- );
-
+
+#include <IndustryStandard/PeImage.h>
+#include <Protocol/DebugSupport.h>
+
+extern CONST CHAR8 mHexToStr[];
+
+// maximum size of input and output buffers
+// This value came from the show remote command of the gdb we tested against
+#define MAX_BUF_SIZE 2000
+
+// maximum size of address buffer
+#define MAX_ADDR_SIZE 32
+
+// maximum size of register number buffer
+#define MAX_REG_NUM_BUF_SIZE 32
+
+// maximum size of length buffer
+#define MAX_LENGTH_SIZE 32
+
+// maximum size of T signal members
+#define MAX_T_SIGNAL_SIZE 64
+
+// the mask used to clear all the cache
+#define TF_BIT 0x00000100
+
+
+//
+// GDB Signal definitions - generic names for interrupts
+//
+#define GDB_SIGINT 2 // Interrupt process via ctrl-c
+#define GDB_SIGILL 4 // Illegal instruction
+#define GDB_SIGTRAP 5 // Trace Trap (Breakpoint and SingleStep)
+#define GDB_SIGEMT 7 // Emulator Trap
+#define GDB_SIGFPE 8 // Floating point exception
+#define GDB_SIGSEGV 11 // Setgment violation, page fault
+
+
+//
+// GDB File I/O Error values, zero means no error
+// Includes all general GDB Unix like error values
+//
+#define GDB_EBADMEMADDRBUFSIZE 11 // the buffer that stores memory Address to be read from/written to is not the right size
+#define GDB_EBADMEMLENGBUFSIZE 12 // the buffer that stores Length is not the right size
+#define GDB_EBADMEMLENGTH 13 // Length, the given number of bytes to read or write, is not the right size
+#define GDB_EBADMEMDATA 14 // one of the bytes or nibbles of the memory is leess than 0
+#define GDB_EBADMEMDATASIZE 15 // the memory data, 'XX..', is too short or too long
+#define GDB_EBADBUFSIZE 21 // the buffer created is not the correct size
+#define GDB_EINVALIDARG 31 // argument is invalid
+#define GDB_ENOSPACE 41 //
+#define GDB_EINVALIDBRKPOINTTYPE 51 // the breakpoint type is not recognized
+#define GDB_EINVALIDREGNUM 61 // given register number is not valid: either <0 or >=Number of Registers
+#define GDB_EUNKNOWN 255 // unknown
+
+
+//
+// These devices are open by GDB so we can just read and write to them
+//
+#define GDB_STDIN 0x00
+#define GDB_STDOUT 0x01
+#define GDB_STDERR 0x02
+
+//
+//Define Register size for different architectures
+//
+#if defined (MDE_CPU_IA32)
+#define REG_SIZE 32
+#elif defined (MDE_CPU_X64)
+#define REG_SIZE 64
+#elif defined (MDE_CPU_ARM)
+#define REG_SIZE 32
+#endif
+
+
+typedef struct {
+ EFI_EXCEPTION_TYPE Exception;
+ UINT8 SignalNo;
+} EFI_EXCEPTION_TYPE_ENTRY;
+
+
+#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
+
+//
+// Byte packed structure for DR6
+// 32-bits on IA-32
+// 64-bits on X64. The upper 32-bits on X64 are reserved
+//
+typedef union {
+ struct {
+ UINT32 B0:1; // Breakpoint condition detected
+ UINT32 B1:1; // Breakpoint condition detected
+ UINT32 B2:1; // Breakpoint condition detected
+ UINT32 B3:1; // Breakpoint condition detected
+ UINT32 Reserved_1:9; // Reserved
+ UINT32 BD:1; // Debug register access detected
+ UINT32 BS:1; // Single step
+ UINT32 BT:1; // Task switch
+ UINT32 Reserved_2:16; // Reserved
+ } Bits;
+ UINTN UintN;
+} IA32_DR6;
+
+//
+// Byte packed structure for DR7
+// 32-bits on IA-32
+// 64-bits on X64. The upper 32-bits on X64 are reserved
+//
+typedef union {
+ struct {
+ UINT32 L0:1; // Local breakpoint enable
+ UINT32 G0:1; // Global breakpoint enable
+ UINT32 L1:1; // Local breakpoint enable
+ UINT32 G1:1; // Global breakpoint enable
+ UINT32 L2:1; // Local breakpoint enable
+ UINT32 G2:1; // Global breakpoint enable
+ UINT32 L3:1; // Local breakpoint enable
+ UINT32 G3:1; // Global breakpoint enable
+ UINT32 LE:1; // Local exact breakpoint enable
+ UINT32 GE:1; // Global exact breakpoint enable
+ UINT32 Reserved_1:3; // Reserved
+ UINT32 GD:1; // Global detect enable
+ UINT32 Reserved_2:2; // Reserved
+ UINT32 RW0:2; // Read/Write field
+ UINT32 LEN0:2; // Length field
+ UINT32 RW1:2; // Read/Write field
+ UINT32 LEN1:2; // Length field
+ UINT32 RW2:2; // Read/Write field
+ UINT32 LEN2:2; // Length field
+ UINT32 RW3:2; // Read/Write field
+ UINT32 LEN3:2; // Length field
+ } Bits;
+ UINTN UintN;
+} IA32_DR7;
+
+#endif /* if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64) */
+
+typedef enum {
+ InstructionExecution, //Hardware breakpoint
+ DataWrite, //watch
+ DataRead, //rwatch
+ DataReadWrite, //awatch
+ SoftwareBreakpoint, //Software breakpoint
+ NotSupported
+} BREAK_TYPE;
+
+//
+// Array of exception types that need to be hooked by the debugger
+//
+extern EFI_EXCEPTION_TYPE_ENTRY gExceptionType[];
+
+//
+// If the periodic callback is called while we are processing an F packet we need
+// to let the callback know to not read from the serail stream as it could steal
+// characters from the F reponse packet
+//
+extern BOOLEAN gProcessingFPacket;
+
+
+/**
+ Return the number of entries in the gExceptionType[]
+
+ @retval UINTN, the number of entries in the gExceptionType[] array.
+ **/
+UINTN
+MaxEfiException (
+ VOID
+ );
+
+
+/**
+ Check to see if the ISA is supported.
+ ISA = Instruction Set Architecture
+
+ @retval TRUE if Isa is supported,
+ FALSE otherwise.
+ **/
+BOOLEAN
+CheckIsa (
+ IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
+ );
+
+
+/**
+ Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
+
+ @param SystemContext Register content at time of the exception
+ @param GdbExceptionType GDB exception type
+ **/
+
+VOID
+GdbSendTSignal (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINT8 GdbExceptionType
+ );
+
+
+/**
+ Translates the EFI mapping to GDB mapping
+
+ @param EFIExceptionType EFI Exception that is being processed
+ @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
+ **/
+UINT8
+ConvertEFItoGDBtype (
+ IN EFI_EXCEPTION_TYPE EFIExceptionType
+ );
+
+
+/**
+ Empties the given buffer
+ @param *Buf pointer to the first element in buffer to be emptied
+ **/
+VOID
+EmptyBuffer (
+ IN CHAR8 *Buf
+ );
+
+
+/**
+ Converts an 8-bit Hex Char into a INTN.
+
+ @param Char - the hex character to be converted into UINTN
+ @retval a INTN, from 0 to 15, that corressponds to Char
+ -1 if Char is not a hex character
+ **/
+INTN
+HexCharToInt (
+ IN CHAR8 Char
+ );
+
+
+/** 'E NN'
+ Send an error with the given error number after converting to hex.
+ The error number is put into the buffer in hex. '255' is the biggest errno we can send.
+ ex: 162 will be sent as A2.
+
+ @param errno the error number that will be sent
+ **/
+VOID
+EFIAPI
+SendError (
+ IN UINT8 ErrorNum
+ );
+
+
+/**
+ Send 'OK' when the function is done executing successfully.
+ **/
+VOID
+SendSuccess (
+ VOID
+ );
+
+
+/**
+ Send empty packet to specify that particular command/functionality is not supported.
+ **/
+VOID
+SendNotSupported (
+ VOID
+ );
+
+/** ‘p n’
+ Reads the n-th register's value into an output buffer and sends it as a packet
+ @param SystemContext Register content at time of the exception
+ @param InBuffer This is the input buffer received from gdb server
+ **/
+VOID
+ReadNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ );
+
+
+/** ‘g’
+ Reads the general registers into an output buffer and sends it as a packet
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+ReadGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/** ‘P n...=r...’
+ Writes the new value of n-th register received into the input buffer to the n-th register
+ @param SystemContext Register content at time of the exception
+ @param InBuffer This is the input buffer received from gdb server
+ **/
+VOID
+WriteNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ );
+
+
+/** ‘G XX...’
+ Writes the new values received into the input buffer to the general registers
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Pointer to the input buffer received from gdb server
+ **/
+
+VOID
+WriteGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ );
+
+
+/** ‘m addr,length ’
+ Find the Length of the area to read and the start addres. Finally, pass them to
+ another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
+ send it as a packet.
+
+ @param *PacketData Pointer to Payload data for the packet
+ **/
+VOID
+ReadFromMemory (
+ IN CHAR8 *PacketData
+ );
+
+
+/** ‘M addr,length :XX...’
+ Find the Length of the area in bytes to write and the start addres. Finally, pass them to
+ another function, TransferFromInBufToMem, that will write to that memory space the info in
+ the input buffer.
+
+ @param PacketData Pointer to Payload data for the packet
+ **/
+VOID
+WriteToMemory (
+ IN CHAR8 *PacketData
+ );
+
+
+/** ‘c [addr ]’
+ Continue. addr is Address to resume. If addr is omitted, resume at current
+ Address.
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to PacketData
+ **/
+
+VOID
+ContinueAtAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+
+/** ‘s [addr ]’
+ Single step. addr is the Address at which to resume. If addr is omitted, resume
+ at same Address.
+
+ @param SystemContext Register content at time of the exception
+ @param PacketData Pointer to Payload data for the packet
+ **/
+VOID
+SingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+/**
+ Insert Single Step in the SystemContext
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+AddSingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+/**
+ Remove Single Step in the SystemContext
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+RemoveSingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/**
+ ‘Z1, [addr], [length]’
+ ‘Z2, [addr], [length]’
+ ‘Z3, [addr], [length]’
+ ‘Z4, [addr], [length]’
+
+ Insert hardware breakpoint/watchpoint at address addr of size length
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+InsertBreakPoint(
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+
+/**
+ ‘z1, [addr], [length]’
+ ‘z2, [addr], [length]’
+ ‘z3, [addr], [length]’
+ ‘z4, [addr], [length]’
+
+ Remove hardware breakpoint/watchpoint at address addr of size length
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+RemoveBreakPoint(
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ );
+
+
+/**
+ Exception Hanldler for GDB. It will be called for all exceptions
+ registered via the gExceptionType[] array.
+
+ @param ExceptionType Exception that is being processed
+ @param SystemContext Register content at time of the exception
+
+ **/
+VOID
+EFIAPI
+GdbExceptionHandler (
+ IN EFI_EXCEPTION_TYPE ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/**
+ Periodic callback for GDB. This function is used to catch a ctrl-c or other
+ break in type command from GDB.
+
+ @param SystemContext Register content at time of the call
+
+ **/
+VOID
+EFIAPI
+GdbPeriodicCallBack (
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+
+/**
+ Make two serail consoles: 1) StdIn and StdOut via GDB. 2) StdErr via GDB.
+
+ These console show up on the remote system running GDB
+
+**/
+
+VOID
+GdbInitializeSerialConsole (
+ VOID
+ );
+
+
+/**
+ Send a GDB Remote Serial Protocol Packet
+
+ $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
+ the packet teminating character '#' and the two digit checksum.
+
+ If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
+ in an infinit loop. This is so if you unplug the debugger code just keeps running
+
+ @param PacketData Payload data for the packet
+
+ @retval Number of bytes of packet data sent.
+
+**/
+UINTN
+SendPacket (
+ IN CHAR8 *PacketData
+ );
+
+
+/**
+ Receive a GDB Remote Serial Protocol Packet
+
+ $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
+ the packet teminating character '#' and the two digit checksum.
+
+ If host re-starts sending a packet without ending the previous packet, only the last valid packet is proccessed.
+ (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
+
+ If an ack '+' is not sent resend the packet
+
+ @param PacketData Payload data for the packet
+
+ @retval Number of bytes of packet data received.
+
+ **/
+UINTN
+ReceivePacket (
+ OUT CHAR8 *PacketData,
+ IN UINTN PacketDataSize
+ );
+
+
+/**
+ Read data from a FileDescriptor. On success number of bytes read is returned. Zero indicates
+ the end of a file. On error -1 is returned. If count is zero, GdbRead returns zero.
+
+ @param FileDescriptor Device to talk to.
+ @param Buffer Buffer to hold Count bytes that were read
+ @param Count Number of bytes to transfer.
+
+ @retval -1 Error
+ @retval {other} Number of bytes read.
+
+**/
+INTN
+GdbRead (
+ IN INTN FileDescriptor,
+ OUT VOID *Buffer,
+ IN UINTN Count
+ );
+
+
+/**
+ Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
+ nothing was written. On error -1 is returned.
+
+ @param FileDescriptor Device to talk to.
+ @param Buffer Buffer to hold Count bytes that are to be written
+ @param Count Number of bytes to transfer.
+
+ @retval -1 Error
+ @retval {other} Number of bytes written.
+
+**/
+INTN
+GdbWrite (
+ IN INTN FileDescriptor,
+ OUT CONST VOID *Buffer,
+ IN UINTN Count
+ );
+
+UINTN *
+FindPointerToRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber
+ );
+
+CHAR8 *
+BasicReadRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *OutBufPtr
+ );
+
+VOID
+TransferFromInBufToMem (
+ IN UINTN Length,
+ IN UINT8 *Address,
+ IN CHAR8 *NewData
+ );
+
+VOID
+TransferFromMemToOutBufAndSend (
+ IN UINTN Length,
+ IN UINT8 *Address
+ );
+
+CHAR8 *
+BasicWriteRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *InBufPtr
+ );
+
+VOID
+PrintReg (
+ EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+UINTN
+ParseBreakpointPacket (
+ IN CHAR8 *PacketData,
+ OUT UINTN *Type,
+ OUT UINTN *Address,
+ OUT UINTN *Length
+ );
+
+UINTN
+GetBreakpointDataAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ );
+
+UINTN
+GetBreakpointDetected (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ );
+
+BREAK_TYPE
+GetBreakpointType (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ );
+
+UINTN
+ConvertLengthData (
+ IN UINTN Length
+ );
+
+EFI_STATUS
+FindNextFreeDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ OUT UINTN *Register
+ );
+
+EFI_STATUS
+EnableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type
+ );
+
+EFI_STATUS
+FindMatchingDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type,
+ OUT UINTN *Register
+ );
+
+EFI_STATUS
+DisableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register
+ );
+
+VOID
+InitializeProcessor (
+ VOID
+ );
+
+/**
+ Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
+
+ @param SystemContext Register content at time of the exception
+ @param GdbExceptionType GDB exception type
+ **/
+VOID
+ProcessorSendTSignal (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINT8 GdbExceptionType,
+ IN OUT CHAR8 *TSignalPtr,
+ IN UINTN SizeOfBuffer
+ );
+
/**
Check to see if this exception is related to ctrl-c handling.
@@ -705,9 +705,9 @@ BOOLEAN
ProcessorControlC (
IN EFI_EXCEPTION_TYPE ExceptionType,
IN OUT EFI_SYSTEM_CONTEXT SystemContext
- );
-
-
+ );
+
+
/**
Initialize debug agent.
@@ -723,6 +723,6 @@ DebugAgentHookExceptions (
IN UINT32 InitFlag,
IN VOID *Context OPTIONAL
);
-
-
-#endif
+
+
+#endif
diff --git a/EmbeddedPkg/Library/GdbDebugAgent/Ia32/Processor.c b/EmbeddedPkg/Library/GdbDebugAgent/Ia32/Processor.c
index 96a1a596f..4e4350a0f 100755
--- a/EmbeddedPkg/Library/GdbDebugAgent/Ia32/Processor.c
+++ b/EmbeddedPkg/Library/GdbDebugAgent/Ia32/Processor.c
@@ -1,917 +1,917 @@
-/** @file
- Processor specific parts of the GDB stub
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
+/** @file
+ Processor specific parts of the GDB stub
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
#include <GdbDebugAgent.h>
-
-//
-// Array of exception types that need to be hooked by the debugger
-// {EFI mapping, GDB mapping}
-//
-EFI_EXCEPTION_TYPE_ENTRY gExceptionType[] = {
- { EXCEPT_IA32_DIVIDE_ERROR, GDB_SIGFPE },
- { EXCEPT_IA32_DEBUG, GDB_SIGTRAP },
- { EXCEPT_IA32_NMI, GDB_SIGEMT },
- { EXCEPT_IA32_BREAKPOINT, GDB_SIGTRAP },
- { EXCEPT_IA32_OVERFLOW, GDB_SIGSEGV },
- { EXCEPT_IA32_BOUND, GDB_SIGSEGV },
- { EXCEPT_IA32_INVALID_OPCODE, GDB_SIGILL },
- { EXCEPT_IA32_DOUBLE_FAULT, GDB_SIGEMT },
- { EXCEPT_IA32_STACK_FAULT, GDB_SIGSEGV },
- { EXCEPT_IA32_GP_FAULT, GDB_SIGSEGV },
- { EXCEPT_IA32_PAGE_FAULT, GDB_SIGSEGV },
- { EXCEPT_IA32_FP_ERROR, GDB_SIGEMT },
- { EXCEPT_IA32_ALIGNMENT_CHECK, GDB_SIGEMT },
- { EXCEPT_IA32_MACHINE_CHECK, GDB_SIGEMT }
-};
-
-
-// The offsets of registers SystemContext.
-// The fields in the array are in the gdb ordering.
-//
-//16 regs
-UINTN gRegisterOffsets[] = {
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eax),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ecx),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edx),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebx),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esp),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebp),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esi),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edi),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eip),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eflags),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Cs),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ss),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ds),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Es),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Fs),
- OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Gs)
-};
-
-
-//Debug only..
-VOID
-PrintReg (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- Print ((CHAR16 *)L"EAX: %x ", SystemContext.SystemContextIa32->Eax);
- Print ((CHAR16 *)L"ECX: %x ", SystemContext.SystemContextIa32->Ecx);
- Print ((CHAR16 *)L"EDX: %x ", SystemContext.SystemContextIa32->Edx);
- Print ((CHAR16 *)L"EBX: %x ", SystemContext.SystemContextIa32->Ebx);
- Print ((CHAR16 *)L"ESP: %x ", SystemContext.SystemContextIa32->Esp);
- Print ((CHAR16 *)L"EBP: %x ", SystemContext.SystemContextIa32->Ebp);
- Print ((CHAR16 *)L"ESI: %x ", SystemContext.SystemContextIa32->Esi);
- Print ((CHAR16 *)L"EDI: %x ", SystemContext.SystemContextIa32->Edi);
- Print ((CHAR16 *)L"EIP: %x\n", SystemContext.SystemContextIa32->Eip);
- Print ((CHAR16 *)L"EFlags: %x\n", SystemContext.SystemContextIa32->Eflags);
-}
-
-//Debug only..
-VOID
-PrintDRreg (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- Print ((CHAR16 *)L"DR0: %x ", SystemContext.SystemContextIa32->Dr0);
- Print ((CHAR16 *)L"DR1: %x ", SystemContext.SystemContextIa32->Dr1);
- Print ((CHAR16 *)L"DR2: %x ", SystemContext.SystemContextIa32->Dr2);
- Print ((CHAR16 *)L"DR3: %x ", SystemContext.SystemContextIa32->Dr3);
- Print ((CHAR16 *)L"DR6: %x ", SystemContext.SystemContextIa32->Dr6);
- Print ((CHAR16 *)L"DR7: %x\n", SystemContext.SystemContextIa32->Dr7);
-}
-
-
-/**
- Return the number of entries in the gExceptionType[]
-
- @retval UINTN, the number of entries in the gExceptionType[] array.
- **/
-UINTN
-MaxEfiException (
- VOID
- )
-{
- return sizeof (gExceptionType)/sizeof (EFI_EXCEPTION_TYPE_ENTRY);
-}
-
-
-/**
- Check to see if the ISA is supported.
- ISA = Instruction Set Architecture
-
- @retval TRUE if Isa is supported,
- FALSE otherwise.
-**/
-BOOLEAN
-CheckIsa (
- IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
- )
-{
- return (BOOLEAN)(Isa == IsaIa32);
-}
-
-
-/**
- This takes in the register number and the System Context, and returns a pointer to the RegNumber-th register in gdb ordering
- It is, by default, set to find the register pointer of the IA32 member
-
- @param SystemContext Register content at time of the exception
- @param RegNumber The register to which we want to find a pointer
- @retval the pointer to the RegNumber-th pointer
- **/
-UINTN *
-FindPointerToRegister(
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber
- )
-{
- UINT8 *TempPtr;
- TempPtr = ((UINT8 *)SystemContext.SystemContextIa32) + gRegisterOffsets[RegNumber];
- return (UINTN *)TempPtr;
-}
-
-
-/**
- Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
-
- @param SystemContext Register content at time of the exception
- @param RegNumber the number of the register that we want to read
- @param OutBufPtr pointer to the output buffer's end. the new data will be added from this point on.
- @retval the pointer to the next character of the output buffer that is available to be written on.
- **/
-CHAR8 *
-BasicReadRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *OutBufPtr
- )
-{
- UINTN RegSize;
-
- RegSize = 0;
- while (RegSize < REG_SIZE) {
- *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> (RegSize+4)) & 0xf)];
- *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> RegSize) & 0xf)];
- RegSize = RegSize + 8;
- }
- return OutBufPtr;
-}
-
-
-/** ‘p n’
- Reads the n-th register's value into an output buffer and sends it as a packet
-
- @param SystemContext Register content at time of the exception
- @param InBuffer Pointer to the input buffer received from gdb server
- **/
-VOID
-EFIAPI
-ReadNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- )
-{
- UINTN RegNumber;
- CHAR8 OutBuffer[9]; // 1 reg=8 hex chars, and the end '\0' (escape seq)
- CHAR8 *OutBufPtr; // pointer to the output buffer
-
- RegNumber = AsciiStrHexToUintn (&InBuffer[1]);
-
- if ((RegNumber < 0) || (RegNumber >= sizeof (gRegisterOffsets)/sizeof (UINTN))) {
- SendError (GDB_EINVALIDREGNUM);
- return;
- }
-
- OutBufPtr = OutBuffer;
- OutBufPtr = BasicReadRegister(SystemContext, RegNumber, OutBufPtr);
-
- *OutBufPtr = '\0'; // the end of the buffer
- SendPacket(OutBuffer);
-}
-
-
-/** ‘g’
- Reads the general registers into an output buffer and sends it as a packet
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-ReadGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- UINTN i;
- CHAR8 OutBuffer[129]; // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
- CHAR8 *OutBufPtr; // pointer to the output buffer
-
- OutBufPtr = OutBuffer;
- for(i = 0 ; i < sizeof (gRegisterOffsets)/sizeof (UINTN) ; i++) { // there are only 16 registers to read
- OutBufPtr = BasicReadRegister(SystemContext, i, OutBufPtr);
- }
-
- *OutBufPtr = '\0'; // the end of the buffer
- SendPacket(OutBuffer);
-}
-
-
-/**
- Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
-
- @param SystemContext Register content at time of the exception
- @param RegNumber the number of the register that we want to write
- @param InBufPtr pointer to the output buffer. the new data will be extracted from the input buffer from this point on.
- @retval the pointer to the next character of the input buffer that can be used
- **/
-CHAR8 *
-BasicWriteRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN RegNumber,
- IN CHAR8 *InBufPtr
- )
-{
- UINTN RegSize;
- UINTN TempValue; // the value transferred from a hex char
- UINT32 NewValue; // the new value of the RegNumber-th Register
-
- NewValue = 0;
- RegSize = 0;
- while (RegSize < REG_SIZE) {
- TempValue = HexCharToInt(*InBufPtr++);
-
- if (TempValue < 0) {
- SendError (GDB_EBADMEMDATA);
- return NULL;
- }
-
- NewValue += (TempValue << (RegSize+4));
- TempValue = HexCharToInt(*InBufPtr++);
-
- if (TempValue < 0) {
- SendError (GDB_EBADMEMDATA);
- return NULL;
- }
-
- NewValue += (TempValue << RegSize);
- RegSize = RegSize + 8;
- }
- *(FindPointerToRegister(SystemContext, RegNumber)) = NewValue;
- return InBufPtr;
-}
-
-
-/** ‘P n...=r...’
- Writes the new value of n-th register received into the input buffer to the n-th register
-
- @param SystemContext Register content at time of the exception
- @param InBuffer Ponter to the input buffer received from gdb server
- **/
-VOID
-EFIAPI
-WriteNthRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- )
-{
- UINTN RegNumber;
- CHAR8 RegNumBuffer[MAX_REG_NUM_BUF_SIZE]; // put the 'n..' part of the message into this array
- CHAR8 *RegNumBufPtr;
- CHAR8 *InBufPtr; // pointer to the input buffer
-
- // find the register number to write
- InBufPtr = &InBuffer[1];
- RegNumBufPtr = RegNumBuffer;
- while (*InBufPtr != '=') {
- *RegNumBufPtr++ = *InBufPtr++;
- }
- *RegNumBufPtr = '\0';
- RegNumber = AsciiStrHexToUintn (RegNumBuffer);
-
- // check if this is a valid Register Number
- if ((RegNumber < 0) || (RegNumber >= sizeof (gRegisterOffsets)/sizeof (UINTN))) {
- SendError (GDB_EINVALIDREGNUM);
- return;
- }
- InBufPtr++; // skips the '=' character
- BasicWriteRegister (SystemContext, RegNumber, InBufPtr);
- SendSuccess();
-}
-
-
-/** ‘G XX...’
- Writes the new values received into the input buffer to the general registers
-
- @param SystemContext Register content at time of the exception
- @param InBuffer Pointer to the input buffer received from gdb server
- **/
-VOID
-EFIAPI
-WriteGeneralRegisters (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *InBuffer
- )
-{
- UINTN i;
- CHAR8 *InBufPtr; /// pointer to the input buffer
-
- // check to see if the buffer is the right size which is
- // 1 (for 'G') + 16 (for 16 registers) * 8 ( for 8 hex chars each) = 129
- if (AsciiStrLen(InBuffer) != 129) { // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
- //Bad message. Message is not the right length
- SendError (GDB_EBADBUFSIZE);
- return;
- }
-
- InBufPtr = &InBuffer[1];
-
- // Read the new values for the registers from the input buffer to an array, NewValueArray.
- // The values in the array are in the gdb ordering
- for(i=0; i < sizeof (gRegisterOffsets)/sizeof (UINTN); i++) { // there are only 16 registers to write
- InBufPtr = BasicWriteRegister(SystemContext, i, InBufPtr);
- }
-
- SendSuccess();
-}
-
-/** ‘c [addr ]’
- Continue. addr is Address to resume. If addr is omitted, resume at current
- Address.
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-ContinueAtAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- if (PacketData[1] != '\0') {
- SystemContext.SystemContextIa32->Eip = AsciiStrHexToUintn (&PacketData[1]);
- }
-}
-
-
-/** ‘s [addr ]’
- Single step. addr is the Address at which to resume. If addr is omitted, resume
- at same Address.
-
- @param SystemContext Register content at time of the exception
- **/
-VOID
-EFIAPI
-SingleStep (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
+
+//
+// Array of exception types that need to be hooked by the debugger
+// {EFI mapping, GDB mapping}
+//
+EFI_EXCEPTION_TYPE_ENTRY gExceptionType[] = {
+ { EXCEPT_IA32_DIVIDE_ERROR, GDB_SIGFPE },
+ { EXCEPT_IA32_DEBUG, GDB_SIGTRAP },
+ { EXCEPT_IA32_NMI, GDB_SIGEMT },
+ { EXCEPT_IA32_BREAKPOINT, GDB_SIGTRAP },
+ { EXCEPT_IA32_OVERFLOW, GDB_SIGSEGV },
+ { EXCEPT_IA32_BOUND, GDB_SIGSEGV },
+ { EXCEPT_IA32_INVALID_OPCODE, GDB_SIGILL },
+ { EXCEPT_IA32_DOUBLE_FAULT, GDB_SIGEMT },
+ { EXCEPT_IA32_STACK_FAULT, GDB_SIGSEGV },
+ { EXCEPT_IA32_GP_FAULT, GDB_SIGSEGV },
+ { EXCEPT_IA32_PAGE_FAULT, GDB_SIGSEGV },
+ { EXCEPT_IA32_FP_ERROR, GDB_SIGEMT },
+ { EXCEPT_IA32_ALIGNMENT_CHECK, GDB_SIGEMT },
+ { EXCEPT_IA32_MACHINE_CHECK, GDB_SIGEMT }
+};
+
+
+// The offsets of registers SystemContext.
+// The fields in the array are in the gdb ordering.
+//
+//16 regs
+UINTN gRegisterOffsets[] = {
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eax),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ecx),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edx),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebx),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esp),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ebp),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Esi),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Edi),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eip),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Eflags),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Cs),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ss),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Ds),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Es),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Fs),
+ OFFSET_OF(EFI_SYSTEM_CONTEXT_IA32, Gs)
+};
+
+
+//Debug only..
+VOID
+PrintReg (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ Print ((CHAR16 *)L"EAX: %x ", SystemContext.SystemContextIa32->Eax);
+ Print ((CHAR16 *)L"ECX: %x ", SystemContext.SystemContextIa32->Ecx);
+ Print ((CHAR16 *)L"EDX: %x ", SystemContext.SystemContextIa32->Edx);
+ Print ((CHAR16 *)L"EBX: %x ", SystemContext.SystemContextIa32->Ebx);
+ Print ((CHAR16 *)L"ESP: %x ", SystemContext.SystemContextIa32->Esp);
+ Print ((CHAR16 *)L"EBP: %x ", SystemContext.SystemContextIa32->Ebp);
+ Print ((CHAR16 *)L"ESI: %x ", SystemContext.SystemContextIa32->Esi);
+ Print ((CHAR16 *)L"EDI: %x ", SystemContext.SystemContextIa32->Edi);
+ Print ((CHAR16 *)L"EIP: %x\n", SystemContext.SystemContextIa32->Eip);
+ Print ((CHAR16 *)L"EFlags: %x\n", SystemContext.SystemContextIa32->Eflags);
+}
+
+//Debug only..
+VOID
+PrintDRreg (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ Print ((CHAR16 *)L"DR0: %x ", SystemContext.SystemContextIa32->Dr0);
+ Print ((CHAR16 *)L"DR1: %x ", SystemContext.SystemContextIa32->Dr1);
+ Print ((CHAR16 *)L"DR2: %x ", SystemContext.SystemContextIa32->Dr2);
+ Print ((CHAR16 *)L"DR3: %x ", SystemContext.SystemContextIa32->Dr3);
+ Print ((CHAR16 *)L"DR6: %x ", SystemContext.SystemContextIa32->Dr6);
+ Print ((CHAR16 *)L"DR7: %x\n", SystemContext.SystemContextIa32->Dr7);
+}
+
+
+/**
+ Return the number of entries in the gExceptionType[]
+
+ @retval UINTN, the number of entries in the gExceptionType[] array.
+ **/
+UINTN
+MaxEfiException (
+ VOID
+ )
+{
+ return sizeof (gExceptionType)/sizeof (EFI_EXCEPTION_TYPE_ENTRY);
+}
+
+
+/**
+ Check to see if the ISA is supported.
+ ISA = Instruction Set Architecture
+
+ @retval TRUE if Isa is supported,
+ FALSE otherwise.
+**/
+BOOLEAN
+CheckIsa (
+ IN EFI_INSTRUCTION_SET_ARCHITECTURE Isa
+ )
+{
+ return (BOOLEAN)(Isa == IsaIa32);
+}
+
+
+/**
+ This takes in the register number and the System Context, and returns a pointer to the RegNumber-th register in gdb ordering
+ It is, by default, set to find the register pointer of the IA32 member
+
+ @param SystemContext Register content at time of the exception
+ @param RegNumber The register to which we want to find a pointer
+ @retval the pointer to the RegNumber-th pointer
+ **/
+UINTN *
+FindPointerToRegister(
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber
+ )
+{
+ UINT8 *TempPtr;
+ TempPtr = ((UINT8 *)SystemContext.SystemContextIa32) + gRegisterOffsets[RegNumber];
+ return (UINTN *)TempPtr;
+}
+
+
+/**
+ Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
+
+ @param SystemContext Register content at time of the exception
+ @param RegNumber the number of the register that we want to read
+ @param OutBufPtr pointer to the output buffer's end. the new data will be added from this point on.
+ @retval the pointer to the next character of the output buffer that is available to be written on.
+ **/
+CHAR8 *
+BasicReadRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *OutBufPtr
+ )
+{
+ UINTN RegSize;
+
+ RegSize = 0;
+ while (RegSize < REG_SIZE) {
+ *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> (RegSize+4)) & 0xf)];
+ *OutBufPtr++ = mHexToStr[((*FindPointerToRegister(SystemContext, RegNumber) >> RegSize) & 0xf)];
+ RegSize = RegSize + 8;
+ }
+ return OutBufPtr;
+}
+
+
+/** ‘p n’
+ Reads the n-th register's value into an output buffer and sends it as a packet
+
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Pointer to the input buffer received from gdb server
+ **/
+VOID
+EFIAPI
+ReadNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ )
+{
+ UINTN RegNumber;
+ CHAR8 OutBuffer[9]; // 1 reg=8 hex chars, and the end '\0' (escape seq)
+ CHAR8 *OutBufPtr; // pointer to the output buffer
+
+ RegNumber = AsciiStrHexToUintn (&InBuffer[1]);
+
+ if ((RegNumber < 0) || (RegNumber >= sizeof (gRegisterOffsets)/sizeof (UINTN))) {
+ SendError (GDB_EINVALIDREGNUM);
+ return;
+ }
+
+ OutBufPtr = OutBuffer;
+ OutBufPtr = BasicReadRegister(SystemContext, RegNumber, OutBufPtr);
+
+ *OutBufPtr = '\0'; // the end of the buffer
+ SendPacket(OutBuffer);
+}
+
+
+/** ‘g’
+ Reads the general registers into an output buffer and sends it as a packet
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+ReadGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ UINTN i;
+ CHAR8 OutBuffer[129]; // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
+ CHAR8 *OutBufPtr; // pointer to the output buffer
+
+ OutBufPtr = OutBuffer;
+ for(i = 0 ; i < sizeof (gRegisterOffsets)/sizeof (UINTN) ; i++) { // there are only 16 registers to read
+ OutBufPtr = BasicReadRegister(SystemContext, i, OutBufPtr);
+ }
+
+ *OutBufPtr = '\0'; // the end of the buffer
+ SendPacket(OutBuffer);
+}
+
+
+/**
+ Adds the RegNumber-th register's value to the output buffer, starting at the given OutBufPtr
+
+ @param SystemContext Register content at time of the exception
+ @param RegNumber the number of the register that we want to write
+ @param InBufPtr pointer to the output buffer. the new data will be extracted from the input buffer from this point on.
+ @retval the pointer to the next character of the input buffer that can be used
+ **/
+CHAR8 *
+BasicWriteRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN RegNumber,
+ IN CHAR8 *InBufPtr
+ )
+{
+ UINTN RegSize;
+ UINTN TempValue; // the value transferred from a hex char
+ UINT32 NewValue; // the new value of the RegNumber-th Register
+
+ NewValue = 0;
+ RegSize = 0;
+ while (RegSize < REG_SIZE) {
+ TempValue = HexCharToInt(*InBufPtr++);
+
+ if (TempValue < 0) {
+ SendError (GDB_EBADMEMDATA);
+ return NULL;
+ }
+
+ NewValue += (TempValue << (RegSize+4));
+ TempValue = HexCharToInt(*InBufPtr++);
+
+ if (TempValue < 0) {
+ SendError (GDB_EBADMEMDATA);
+ return NULL;
+ }
+
+ NewValue += (TempValue << RegSize);
+ RegSize = RegSize + 8;
+ }
+ *(FindPointerToRegister(SystemContext, RegNumber)) = NewValue;
+ return InBufPtr;
+}
+
+
+/** ‘P n...=r...’
+ Writes the new value of n-th register received into the input buffer to the n-th register
+
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Ponter to the input buffer received from gdb server
+ **/
+VOID
+EFIAPI
+WriteNthRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ )
+{
+ UINTN RegNumber;
+ CHAR8 RegNumBuffer[MAX_REG_NUM_BUF_SIZE]; // put the 'n..' part of the message into this array
+ CHAR8 *RegNumBufPtr;
+ CHAR8 *InBufPtr; // pointer to the input buffer
+
+ // find the register number to write
+ InBufPtr = &InBuffer[1];
+ RegNumBufPtr = RegNumBuffer;
+ while (*InBufPtr != '=') {
+ *RegNumBufPtr++ = *InBufPtr++;
+ }
+ *RegNumBufPtr = '\0';
+ RegNumber = AsciiStrHexToUintn (RegNumBuffer);
+
+ // check if this is a valid Register Number
+ if ((RegNumber < 0) || (RegNumber >= sizeof (gRegisterOffsets)/sizeof (UINTN))) {
+ SendError (GDB_EINVALIDREGNUM);
+ return;
+ }
+ InBufPtr++; // skips the '=' character
+ BasicWriteRegister (SystemContext, RegNumber, InBufPtr);
+ SendSuccess();
+}
+
+
+/** ‘G XX...’
+ Writes the new values received into the input buffer to the general registers
+
+ @param SystemContext Register content at time of the exception
+ @param InBuffer Pointer to the input buffer received from gdb server
+ **/
+VOID
+EFIAPI
+WriteGeneralRegisters (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *InBuffer
+ )
+{
+ UINTN i;
+ CHAR8 *InBufPtr; /// pointer to the input buffer
+
+ // check to see if the buffer is the right size which is
+ // 1 (for 'G') + 16 (for 16 registers) * 8 ( for 8 hex chars each) = 129
+ if (AsciiStrLen(InBuffer) != 129) { // 16 regs, 8 hex chars each, and the end '\0' (escape seq)
+ //Bad message. Message is not the right length
+ SendError (GDB_EBADBUFSIZE);
+ return;
+ }
+
+ InBufPtr = &InBuffer[1];
+
+ // Read the new values for the registers from the input buffer to an array, NewValueArray.
+ // The values in the array are in the gdb ordering
+ for(i=0; i < sizeof (gRegisterOffsets)/sizeof (UINTN); i++) { // there are only 16 registers to write
+ InBufPtr = BasicWriteRegister(SystemContext, i, InBufPtr);
+ }
+
+ SendSuccess();
+}
+
+/** ‘c [addr ]’
+ Continue. addr is Address to resume. If addr is omitted, resume at current
+ Address.
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+ContinueAtAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ if (PacketData[1] != '\0') {
+ SystemContext.SystemContextIa32->Eip = AsciiStrHexToUintn (&PacketData[1]);
+ }
+}
+
+
+/** ‘s [addr ]’
+ Single step. addr is the Address at which to resume. If addr is omitted, resume
+ at same Address.
+
+ @param SystemContext Register content at time of the exception
+ **/
+VOID
+EFIAPI
+SingleStep (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
SendNotSupported();
-}
-
-
-/**
- Returns breakpoint data address from DR0-DR3 based on the input breakpoint number
-
- @param SystemContext Register content at time of the exception
- @param BreakpointNumber Breakpoint number
-
- @retval Address Data address from DR0-DR3 based on the breakpoint number.
-
-**/
-UINTN
-GetBreakpointDataAddress (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- )
-{
- UINTN Address;
-
- if (BreakpointNumber == 1) {
- Address = SystemContext.SystemContextIa32->Dr0;
- } else if (BreakpointNumber == 2) {
- Address = SystemContext.SystemContextIa32->Dr1;
- } else if (BreakpointNumber == 3) {
- Address = SystemContext.SystemContextIa32->Dr2;
- } else if (BreakpointNumber == 4) {
- Address = SystemContext.SystemContextIa32->Dr3;
- } else {
- Address = 0;
- }
-
- return Address;
-}
-
-
-/**
- Returns currently detected breakpoint value based on the register DR6 B0-B3 field.
- If no breakpoint is detected then it returns 0.
-
- @param SystemContext Register content at time of the exception
-
- @retval {1-4} Currently detected breakpoint value
- @retval 0 No breakpoint detected.
-
-**/
-UINTN
-GetBreakpointDetected (
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- IA32_DR6 Dr6;
- UINTN BreakpointNumber;
-
- Dr6.UintN = SystemContext.SystemContextIa32->Dr6;
-
- if (Dr6.Bits.B0 == 1) {
- BreakpointNumber = 1;
- } else if (Dr6.Bits.B1 == 1) {
- BreakpointNumber = 2;
- } else if (Dr6.Bits.B2 == 1) {
- BreakpointNumber = 3;
- } else if (Dr6.Bits.B3 == 1) {
- BreakpointNumber = 4;
- } else {
- BreakpointNumber = 0; //No breakpoint detected
- }
-
- return BreakpointNumber;
-}
-
-
-/**
- Returns Breakpoint type (InstructionExecution, DataWrite, DataRead or DataReadWrite)
- based on the Breakpoint number
-
- @param SystemContext Register content at time of the exception
- @param BreakpointNumber Breakpoint number
-
- @retval BREAK_TYPE Breakpoint type value read from register DR7 RWn field
- For unknown value, it returns NotSupported.
-
-**/
-BREAK_TYPE
-GetBreakpointType (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN BreakpointNumber
- )
-{
- IA32_DR7 Dr7;
- BREAK_TYPE Type = NotSupported; //Default is NotSupported type
-
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (BreakpointNumber == 1) {
- Type = (BREAK_TYPE) Dr7.Bits.RW0;
- } else if (BreakpointNumber == 2) {
- Type = (BREAK_TYPE) Dr7.Bits.RW1;
- } else if (BreakpointNumber == 3) {
- Type = (BREAK_TYPE) Dr7.Bits.RW2;
- } else if (BreakpointNumber == 4) {
- Type = (BREAK_TYPE) Dr7.Bits.RW3;
- }
-
- return Type;
-}
-
-
-/**
- Parses Length and returns the length which DR7 LENn field accepts.
- For example: If we receive 1-Byte length then we should return 0.
- Zero gets written to DR7 LENn field.
-
- @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
-
- @retval Length Appropriate converted values which DR7 LENn field accepts.
-
-**/
-UINTN
-ConvertLengthData (
- IN UINTN Length
- )
-{
- if (Length == 1) { //1-Byte length
- return 0;
- } else if (Length == 2) { //2-Byte length
- return 1;
- } else if (Length == 4) { //4-Byte length
- return 3;
- } else { //Undefined or 8-byte length
- return 2;
- }
-}
-
-
-/**
- Finds the next free debug register. If all the registers are occupied then
- EFI_OUT_OF_RESOURCES is returned.
-
- @param SystemContext Register content at time of the exception
- @param Register Register value (0 - 3 for the first free debug register)
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-FindNextFreeDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- OUT UINTN *Register
- )
-{
- IA32_DR7 Dr7;
-
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (Dr7.Bits.G0 == 0) {
- *Register = 0;
- } else if (Dr7.Bits.G1 == 0) {
- *Register = 1;
- } else if (Dr7.Bits.G2 == 0) {
- *Register = 2;
- } else if (Dr7.Bits.G3 == 0) {
- *Register = 3;
- } else {
- return EFI_OUT_OF_RESOURCES;
- }
-
- return EFI_SUCCESS;
-}
-
-
-/**
- Enables the debug register. Writes Address value to appropriate DR0-3 register.
- Sets LENn, Gn, RWn bits in DR7 register.
-
- @param SystemContext Register content at time of the exception
- @param Register Register value (0 - 3)
- @param Address Breakpoint address value
- @param Type Breakpoint type (Instruction, Data write, Data read
- or write etc.)
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-EnableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type
- )
-{
- IA32_DR7 Dr7;
-
- //Convert length data
- Length = ConvertLengthData (Length);
-
- //For Instruction execution, length should be 0
- //(Ref. Intel reference manual 18.2.4)
- if ((Type == 0) && (Length != 0)) {
- return EFI_INVALID_PARAMETER;
- }
-
- //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
- //software breakpoint. We should send empty packet in both these cases.
- if ((Type == (BREAK_TYPE)DataRead) ||
- (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
- return EFI_UNSUPPORTED;
- }
-
- //Read DR7 so appropriate Gn, RWn and LENn bits can be modified.
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (Register == 0) {
- SystemContext.SystemContextIa32->Dr0 = Address;
- Dr7.Bits.G0 = 1;
- Dr7.Bits.RW0 = Type;
- Dr7.Bits.LEN0 = Length;
- } else if (Register == 1) {
- SystemContext.SystemContextIa32->Dr1 = Address;
- Dr7.Bits.G1 = 1;
- Dr7.Bits.RW1 = Type;
- Dr7.Bits.LEN1 = Length;
- } else if (Register == 2) {
- SystemContext.SystemContextIa32->Dr2 = Address;
- Dr7.Bits.G2 = 1;
- Dr7.Bits.RW2 = Type;
- Dr7.Bits.LEN2 = Length;
- } else if (Register == 3) {
- SystemContext.SystemContextIa32->Dr3 = Address;
- Dr7.Bits.G3 = 1;
- Dr7.Bits.RW3 = Type;
- Dr7.Bits.LEN3 = Length;
- } else {
- return EFI_INVALID_PARAMETER;
- }
-
- //Update Dr7 with appropriate Gn, RWn and LENn bits
- SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
-
- return EFI_SUCCESS;
-}
-
-
-/**
- Returns register number 0 - 3 for the maching debug register.
- This function compares incoming Address, Type, Length and
- if there is a match then it returns the appropriate register number.
- In case of mismatch, function returns EFI_NOT_FOUND message.
-
- @param SystemContext Register content at time of the exception
- @param Address Breakpoint address value
- @param Length Breakpoint length value
- @param Type Breakpoint type (Instruction, Data write,
- Data read or write etc.)
- @param Register Register value to be returned
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-FindMatchingDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Address,
- IN UINTN Length,
- IN UINTN Type,
- OUT UINTN *Register
- )
-{
- IA32_DR7 Dr7;
-
- //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
- //software breakpoint. We should send empty packet in both these cases.
- if ((Type == (BREAK_TYPE)DataRead) ||
- (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
- return EFI_UNSUPPORTED;
- }
-
- //Convert length data
- Length = ConvertLengthData(Length);
-
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if ((Dr7.Bits.G0 == 1) &&
- (Dr7.Bits.LEN0 == Length) &&
- (Dr7.Bits.RW0 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr0)) {
- *Register = 0;
- } else if ((Dr7.Bits.G1 == 1) &&
- (Dr7.Bits.LEN1 == Length) &&
- (Dr7.Bits.RW1 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr1)) {
- *Register = 1;
- } else if ((Dr7.Bits.G2 == 1) &&
- (Dr7.Bits.LEN2 == Length) &&
- (Dr7.Bits.RW2 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr2)) {
- *Register = 2;
- } else if ((Dr7.Bits.G3 == 1) &&
- (Dr7.Bits.LEN3 == Length) &&
- (Dr7.Bits.RW3 == Type) &&
- (Address == SystemContext.SystemContextIa32->Dr3)) {
- *Register = 3;
- } else {
- Print ((CHAR16 *)L"No match found..\n");
- return EFI_NOT_FOUND;
- }
-
- return EFI_SUCCESS;
-}
-
-
-/**
- Disables the particular debug register.
-
- @param SystemContext Register content at time of the exception
- @param Register Register to be disabled
-
- @retval EFI_STATUS Appropriate status value.
-
-**/
-EFI_STATUS
-DisableDebugRegister (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN UINTN Register
- )
-{
- IA32_DR7 Dr7;
- UINTN Address = 0;
-
- //Read DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
- Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
-
- if (Register == 0) {
- SystemContext.SystemContextIa32->Dr0 = Address;
- Dr7.Bits.G0 = 0;
- Dr7.Bits.RW0 = 0;
- Dr7.Bits.LEN0 = 0;
- } else if (Register == 1) {
- SystemContext.SystemContextIa32->Dr1 = Address;
- Dr7.Bits.G1 = 0;
- Dr7.Bits.RW1 = 0;
- Dr7.Bits.LEN1 = 0;
- } else if (Register == 2) {
- SystemContext.SystemContextIa32->Dr2 = Address;
- Dr7.Bits.G2 = 0;
- Dr7.Bits.RW2 = 0;
- Dr7.Bits.LEN2 = 0;
- } else if (Register == 3) {
- SystemContext.SystemContextIa32->Dr3 = Address;
- Dr7.Bits.G3 = 0;
- Dr7.Bits.RW3 = 0;
- Dr7.Bits.LEN3 = 0;
- } else {
- return EFI_INVALID_PARAMETER;
- }
-
- //Update DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
- SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
-
- return EFI_SUCCESS;
-}
-
-
-/**
- ‘Z1, [addr], [length]’
- ‘Z2, [addr], [length]’
- ‘Z3, [addr], [length]’
- ‘Z4, [addr], [length]’
-
- Insert hardware breakpoint/watchpoint at address addr of size length
-
- @param SystemContext Register content at time of the exception
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-InsertBreakPoint (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- UINTN Type;
- UINTN Address;
- UINTN Length;
- UINTN Register;
- EFI_STATUS Status;
- BREAK_TYPE BreakType = NotSupported;
- UINTN ErrorCode;
-
- ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
- if (ErrorCode > 0) {
- SendError ((UINT8)ErrorCode);
- return;
- }
-
- switch (Type) {
-
- case 0: //Software breakpoint
- BreakType = SoftwareBreakpoint;
- break;
-
- case 1: //Hardware breakpoint
- BreakType = InstructionExecution;
- break;
-
- case 2: //Write watchpoint
- BreakType = DataWrite;
- break;
-
- case 3: //Read watchpoint
- BreakType = DataRead;
- break;
-
- case 4: //Access watchpoint
- BreakType = DataReadWrite;
- break;
-
- default :
- Print ((CHAR16 *)L"Insert breakpoint default: %x\n", Type);
- SendError (GDB_EINVALIDBRKPOINTTYPE);
- return;
- }
-
- // Find next free debug register
- Status = FindNextFreeDebugRegister (SystemContext, &Register);
- if (EFI_ERROR(Status)) {
- Print ((CHAR16 *)L"No space left on device\n");
- SendError (GDB_ENOSPACE);
- return;
- }
-
- // Write Address, length data at particular DR register
- Status = EnableDebugRegister (SystemContext, Register, Address, Length, (UINTN)BreakType);
- if (EFI_ERROR(Status)) {
- if (Status == EFI_UNSUPPORTED) {
- SendNotSupported();
- return;
- }
-
- SendError (GDB_EINVALIDARG);
- return;
- }
-
- SendSuccess ();
-}
-
-
-/**
- ‘z1, [addr], [length]’
- ‘z2, [addr], [length]’
- ‘z3, [addr], [length]’
- ‘z4, [addr], [length]’
-
- Remove hardware breakpoint/watchpoint at address addr of size length
-
- @param *PacketData Pointer to the Payload data for the packet
-
-**/
-VOID
-EFIAPI
-RemoveBreakPoint (
- IN EFI_SYSTEM_CONTEXT SystemContext,
- IN CHAR8 *PacketData
- )
-{
- UINTN Type;
- UINTN Address;
- UINTN Length;
- UINTN Register;
- BREAK_TYPE BreakType = NotSupported;
- EFI_STATUS Status;
- UINTN ErrorCode;
-
- //Parse breakpoint packet data
- ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
- if (ErrorCode > 0) {
- SendError ((UINT8)ErrorCode);
- return;
- }
-
- switch (Type) {
-
- case 0: //Software breakpoint
- BreakType = SoftwareBreakpoint;
- break;
-
- case 1: //Hardware breakpoint
- BreakType = InstructionExecution;
- break;
-
- case 2: //Write watchpoint
- BreakType = DataWrite;
- break;
-
- case 3: //Read watchpoint
- BreakType = DataRead;
- break;
-
- case 4: //Access watchpoint
- BreakType = DataReadWrite;
- break;
-
- default :
- SendError (GDB_EINVALIDBRKPOINTTYPE);
- return;
- }
-
- //Find matching debug register
- Status = FindMatchingDebugRegister (SystemContext, Address, Length, (UINTN)BreakType, &Register);
- if (EFI_ERROR(Status)) {
- if (Status == EFI_UNSUPPORTED) {
- SendNotSupported();
- return;
- }
-
- SendError (GDB_ENOSPACE);
- return;
- }
-
- //Remove breakpoint
- Status = DisableDebugRegister(SystemContext, Register);
- if (EFI_ERROR(Status)) {
- SendError (GDB_EINVALIDARG);
- return;
- }
-
- SendSuccess ();
-}
-
-
+}
+
+
+/**
+ Returns breakpoint data address from DR0-DR3 based on the input breakpoint number
+
+ @param SystemContext Register content at time of the exception
+ @param BreakpointNumber Breakpoint number
+
+ @retval Address Data address from DR0-DR3 based on the breakpoint number.
+
+**/
+UINTN
+GetBreakpointDataAddress (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ )
+{
+ UINTN Address;
+
+ if (BreakpointNumber == 1) {
+ Address = SystemContext.SystemContextIa32->Dr0;
+ } else if (BreakpointNumber == 2) {
+ Address = SystemContext.SystemContextIa32->Dr1;
+ } else if (BreakpointNumber == 3) {
+ Address = SystemContext.SystemContextIa32->Dr2;
+ } else if (BreakpointNumber == 4) {
+ Address = SystemContext.SystemContextIa32->Dr3;
+ } else {
+ Address = 0;
+ }
+
+ return Address;
+}
+
+
+/**
+ Returns currently detected breakpoint value based on the register DR6 B0-B3 field.
+ If no breakpoint is detected then it returns 0.
+
+ @param SystemContext Register content at time of the exception
+
+ @retval {1-4} Currently detected breakpoint value
+ @retval 0 No breakpoint detected.
+
+**/
+UINTN
+GetBreakpointDetected (
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ IA32_DR6 Dr6;
+ UINTN BreakpointNumber;
+
+ Dr6.UintN = SystemContext.SystemContextIa32->Dr6;
+
+ if (Dr6.Bits.B0 == 1) {
+ BreakpointNumber = 1;
+ } else if (Dr6.Bits.B1 == 1) {
+ BreakpointNumber = 2;
+ } else if (Dr6.Bits.B2 == 1) {
+ BreakpointNumber = 3;
+ } else if (Dr6.Bits.B3 == 1) {
+ BreakpointNumber = 4;
+ } else {
+ BreakpointNumber = 0; //No breakpoint detected
+ }
+
+ return BreakpointNumber;
+}
+
+
+/**
+ Returns Breakpoint type (InstructionExecution, DataWrite, DataRead or DataReadWrite)
+ based on the Breakpoint number
+
+ @param SystemContext Register content at time of the exception
+ @param BreakpointNumber Breakpoint number
+
+ @retval BREAK_TYPE Breakpoint type value read from register DR7 RWn field
+ For unknown value, it returns NotSupported.
+
+**/
+BREAK_TYPE
+GetBreakpointType (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN BreakpointNumber
+ )
+{
+ IA32_DR7 Dr7;
+ BREAK_TYPE Type = NotSupported; //Default is NotSupported type
+
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (BreakpointNumber == 1) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW0;
+ } else if (BreakpointNumber == 2) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW1;
+ } else if (BreakpointNumber == 3) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW2;
+ } else if (BreakpointNumber == 4) {
+ Type = (BREAK_TYPE) Dr7.Bits.RW3;
+ }
+
+ return Type;
+}
+
+
+/**
+ Parses Length and returns the length which DR7 LENn field accepts.
+ For example: If we receive 1-Byte length then we should return 0.
+ Zero gets written to DR7 LENn field.
+
+ @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
+
+ @retval Length Appropriate converted values which DR7 LENn field accepts.
+
+**/
+UINTN
+ConvertLengthData (
+ IN UINTN Length
+ )
+{
+ if (Length == 1) { //1-Byte length
+ return 0;
+ } else if (Length == 2) { //2-Byte length
+ return 1;
+ } else if (Length == 4) { //4-Byte length
+ return 3;
+ } else { //Undefined or 8-byte length
+ return 2;
+ }
+}
+
+
+/**
+ Finds the next free debug register. If all the registers are occupied then
+ EFI_OUT_OF_RESOURCES is returned.
+
+ @param SystemContext Register content at time of the exception
+ @param Register Register value (0 - 3 for the first free debug register)
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+FindNextFreeDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ OUT UINTN *Register
+ )
+{
+ IA32_DR7 Dr7;
+
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (Dr7.Bits.G0 == 0) {
+ *Register = 0;
+ } else if (Dr7.Bits.G1 == 0) {
+ *Register = 1;
+ } else if (Dr7.Bits.G2 == 0) {
+ *Register = 2;
+ } else if (Dr7.Bits.G3 == 0) {
+ *Register = 3;
+ } else {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Enables the debug register. Writes Address value to appropriate DR0-3 register.
+ Sets LENn, Gn, RWn bits in DR7 register.
+
+ @param SystemContext Register content at time of the exception
+ @param Register Register value (0 - 3)
+ @param Address Breakpoint address value
+ @param Type Breakpoint type (Instruction, Data write, Data read
+ or write etc.)
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+EnableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type
+ )
+{
+ IA32_DR7 Dr7;
+
+ //Convert length data
+ Length = ConvertLengthData (Length);
+
+ //For Instruction execution, length should be 0
+ //(Ref. Intel reference manual 18.2.4)
+ if ((Type == 0) && (Length != 0)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
+ //software breakpoint. We should send empty packet in both these cases.
+ if ((Type == (BREAK_TYPE)DataRead) ||
+ (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //Read DR7 so appropriate Gn, RWn and LENn bits can be modified.
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (Register == 0) {
+ SystemContext.SystemContextIa32->Dr0 = Address;
+ Dr7.Bits.G0 = 1;
+ Dr7.Bits.RW0 = Type;
+ Dr7.Bits.LEN0 = Length;
+ } else if (Register == 1) {
+ SystemContext.SystemContextIa32->Dr1 = Address;
+ Dr7.Bits.G1 = 1;
+ Dr7.Bits.RW1 = Type;
+ Dr7.Bits.LEN1 = Length;
+ } else if (Register == 2) {
+ SystemContext.SystemContextIa32->Dr2 = Address;
+ Dr7.Bits.G2 = 1;
+ Dr7.Bits.RW2 = Type;
+ Dr7.Bits.LEN2 = Length;
+ } else if (Register == 3) {
+ SystemContext.SystemContextIa32->Dr3 = Address;
+ Dr7.Bits.G3 = 1;
+ Dr7.Bits.RW3 = Type;
+ Dr7.Bits.LEN3 = Length;
+ } else {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Update Dr7 with appropriate Gn, RWn and LENn bits
+ SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Returns register number 0 - 3 for the maching debug register.
+ This function compares incoming Address, Type, Length and
+ if there is a match then it returns the appropriate register number.
+ In case of mismatch, function returns EFI_NOT_FOUND message.
+
+ @param SystemContext Register content at time of the exception
+ @param Address Breakpoint address value
+ @param Length Breakpoint length value
+ @param Type Breakpoint type (Instruction, Data write,
+ Data read or write etc.)
+ @param Register Register value to be returned
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+FindMatchingDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Address,
+ IN UINTN Length,
+ IN UINTN Type,
+ OUT UINTN *Register
+ )
+{
+ IA32_DR7 Dr7;
+
+ //Hardware doesn't support ReadWatch (z3 packet) type. GDB can handle
+ //software breakpoint. We should send empty packet in both these cases.
+ if ((Type == (BREAK_TYPE)DataRead) ||
+ (Type == (BREAK_TYPE)SoftwareBreakpoint)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //Convert length data
+ Length = ConvertLengthData(Length);
+
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if ((Dr7.Bits.G0 == 1) &&
+ (Dr7.Bits.LEN0 == Length) &&
+ (Dr7.Bits.RW0 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr0)) {
+ *Register = 0;
+ } else if ((Dr7.Bits.G1 == 1) &&
+ (Dr7.Bits.LEN1 == Length) &&
+ (Dr7.Bits.RW1 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr1)) {
+ *Register = 1;
+ } else if ((Dr7.Bits.G2 == 1) &&
+ (Dr7.Bits.LEN2 == Length) &&
+ (Dr7.Bits.RW2 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr2)) {
+ *Register = 2;
+ } else if ((Dr7.Bits.G3 == 1) &&
+ (Dr7.Bits.LEN3 == Length) &&
+ (Dr7.Bits.RW3 == Type) &&
+ (Address == SystemContext.SystemContextIa32->Dr3)) {
+ *Register = 3;
+ } else {
+ Print ((CHAR16 *)L"No match found..\n");
+ return EFI_NOT_FOUND;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Disables the particular debug register.
+
+ @param SystemContext Register content at time of the exception
+ @param Register Register to be disabled
+
+ @retval EFI_STATUS Appropriate status value.
+
+**/
+EFI_STATUS
+DisableDebugRegister (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN UINTN Register
+ )
+{
+ IA32_DR7 Dr7;
+ UINTN Address = 0;
+
+ //Read DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
+ Dr7.UintN = SystemContext.SystemContextIa32->Dr7;
+
+ if (Register == 0) {
+ SystemContext.SystemContextIa32->Dr0 = Address;
+ Dr7.Bits.G0 = 0;
+ Dr7.Bits.RW0 = 0;
+ Dr7.Bits.LEN0 = 0;
+ } else if (Register == 1) {
+ SystemContext.SystemContextIa32->Dr1 = Address;
+ Dr7.Bits.G1 = 0;
+ Dr7.Bits.RW1 = 0;
+ Dr7.Bits.LEN1 = 0;
+ } else if (Register == 2) {
+ SystemContext.SystemContextIa32->Dr2 = Address;
+ Dr7.Bits.G2 = 0;
+ Dr7.Bits.RW2 = 0;
+ Dr7.Bits.LEN2 = 0;
+ } else if (Register == 3) {
+ SystemContext.SystemContextIa32->Dr3 = Address;
+ Dr7.Bits.G3 = 0;
+ Dr7.Bits.RW3 = 0;
+ Dr7.Bits.LEN3 = 0;
+ } else {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //Update DR7 register so appropriate Gn, RWn and LENn bits can be turned off.
+ SystemContext.SystemContextIa32->Dr7 = Dr7.UintN;
+
+ return EFI_SUCCESS;
+}
+
+
+/**
+ ‘Z1, [addr], [length]’
+ ‘Z2, [addr], [length]’
+ ‘Z3, [addr], [length]’
+ ‘Z4, [addr], [length]’
+
+ Insert hardware breakpoint/watchpoint at address addr of size length
+
+ @param SystemContext Register content at time of the exception
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+InsertBreakPoint (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ UINTN Type;
+ UINTN Address;
+ UINTN Length;
+ UINTN Register;
+ EFI_STATUS Status;
+ BREAK_TYPE BreakType = NotSupported;
+ UINTN ErrorCode;
+
+ ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
+ if (ErrorCode > 0) {
+ SendError ((UINT8)ErrorCode);
+ return;
+ }
+
+ switch (Type) {
+
+ case 0: //Software breakpoint
+ BreakType = SoftwareBreakpoint;
+ break;
+
+ case 1: //Hardware breakpoint
+ BreakType = InstructionExecution;
+ break;
+
+ case 2: //Write watchpoint
+ BreakType = DataWrite;
+ break;
+
+ case 3: //Read watchpoint
+ BreakType = DataRead;
+ break;
+
+ case 4: //Access watchpoint
+ BreakType = DataReadWrite;
+ break;
+
+ default :
+ Print ((CHAR16 *)L"Insert breakpoint default: %x\n", Type);
+ SendError (GDB_EINVALIDBRKPOINTTYPE);
+ return;
+ }
+
+ // Find next free debug register
+ Status = FindNextFreeDebugRegister (SystemContext, &Register);
+ if (EFI_ERROR(Status)) {
+ Print ((CHAR16 *)L"No space left on device\n");
+ SendError (GDB_ENOSPACE);
+ return;
+ }
+
+ // Write Address, length data at particular DR register
+ Status = EnableDebugRegister (SystemContext, Register, Address, Length, (UINTN)BreakType);
+ if (EFI_ERROR(Status)) {
+ if (Status == EFI_UNSUPPORTED) {
+ SendNotSupported();
+ return;
+ }
+
+ SendError (GDB_EINVALIDARG);
+ return;
+ }
+
+ SendSuccess ();
+}
+
+
+/**
+ ‘z1, [addr], [length]’
+ ‘z2, [addr], [length]’
+ ‘z3, [addr], [length]’
+ ‘z4, [addr], [length]’
+
+ Remove hardware breakpoint/watchpoint at address addr of size length
+
+ @param *PacketData Pointer to the Payload data for the packet
+
+**/
+VOID
+EFIAPI
+RemoveBreakPoint (
+ IN EFI_SYSTEM_CONTEXT SystemContext,
+ IN CHAR8 *PacketData
+ )
+{
+ UINTN Type;
+ UINTN Address;
+ UINTN Length;
+ UINTN Register;
+ BREAK_TYPE BreakType = NotSupported;
+ EFI_STATUS Status;
+ UINTN ErrorCode;
+
+ //Parse breakpoint packet data
+ ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
+ if (ErrorCode > 0) {
+ SendError ((UINT8)ErrorCode);
+ return;
+ }
+
+ switch (Type) {
+
+ case 0: //Software breakpoint
+ BreakType = SoftwareBreakpoint;
+ break;
+
+ case 1: //Hardware breakpoint
+ BreakType = InstructionExecution;
+ break;
+
+ case 2: //Write watchpoint
+ BreakType = DataWrite;
+ break;
+
+ case 3: //Read watchpoint
+ BreakType = DataRead;
+ break;
+
+ case 4: //Access watchpoint
+ BreakType = DataReadWrite;
+ break;
+
+ default :
+ SendError (GDB_EINVALIDBRKPOINTTYPE);
+ return;
+ }
+
+ //Find matching debug register
+ Status = FindMatchingDebugRegister (SystemContext, Address, Length, (UINTN)BreakType, &Register);
+ if (EFI_ERROR(Status)) {
+ if (Status == EFI_UNSUPPORTED) {
+ SendNotSupported();
+ return;
+ }
+
+ SendError (GDB_ENOSPACE);
+ return;
+ }
+
+ //Remove breakpoint
+ Status = DisableDebugRegister(SystemContext, Register);
+ if (EFI_ERROR(Status)) {
+ SendError (GDB_EINVALIDARG);
+ return;
+ }
+
+ SendSuccess ();
+}
+
+
/**
Initialize debug agent.
diff --git a/EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf b/EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf
index 4897a8a96..8e8ccaee3 100755
--- a/EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf
+++ b/EmbeddedPkg/Library/NullDmaLib/NullDmaLib.inf
@@ -38,4 +38,4 @@
[Pcd]
[Depex]
- TRUE \ No newline at end of file
+ TRUE \ No newline at end of file
diff --git a/EmbeddedPkg/Library/PrePiHobLib/Hob.c b/EmbeddedPkg/Library/PrePiHobLib/Hob.c
index a92a1de52..320dddfc2 100644
--- a/EmbeddedPkg/Library/PrePiHobLib/Hob.c
+++ b/EmbeddedPkg/Library/PrePiHobLib/Hob.c
@@ -1,852 +1,852 @@
-/** @file
-
- Copyright (c) 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <PiPei.h>
-
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DebugLib.h>
-#include <Library/PeCoffLib.h>
-#include <Library/HobLib.h>
-#include <Library/PcdLib.h>
-#include <Library/PrePiHobListPointerLib.h>
-
-#include <Protocol/PeCoffLoader.h>
-#include <Guid/ExtractSection.h>
-#include <Guid/MemoryTypeInformation.h>
-#include <Guid/MemoryAllocationHob.h>
-
-VOID
-BuildMemoryTypeInformationHob (
- VOID
- );
-
-/**
- Returns the pointer to the HOB list.
-
- This function returns the pointer to first HOB in the list.
-
- @return The pointer to the HOB list.
-
-**/
-VOID *
-EFIAPI
-GetHobList (
- VOID
- )
-{
- return PrePeiGetHobList ();
-}
-
-
-
-/**
- Updates the pointer to the HOB list.
-
- @param HobList Hob list pointer to store
-
-**/
-EFI_STATUS
-EFIAPI
-SetHobList (
- IN VOID *HobList
- )
-{
- return PrePeiSetHobList (HobList);
-}
-
-/**
-
-
-**/
-EFI_HOB_HANDOFF_INFO_TABLE*
-HobConstructor (
- IN VOID *EfiMemoryBegin,
- IN UINTN EfiMemoryLength,
- IN VOID *EfiFreeMemoryBottom,
- IN VOID *EfiFreeMemoryTop
- )
-{
- EFI_HOB_HANDOFF_INFO_TABLE *Hob;
- EFI_HOB_GENERIC_HEADER *HobEnd;
-
- Hob = EfiFreeMemoryBottom;
- HobEnd = (EFI_HOB_GENERIC_HEADER *)(Hob+1);
-
- Hob->Header.HobType = EFI_HOB_TYPE_HANDOFF;
- Hob->Header.HobLength = sizeof(EFI_HOB_HANDOFF_INFO_TABLE);
- Hob->Header.Reserved = 0;
-
- HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST;
- HobEnd->HobLength = sizeof(EFI_HOB_GENERIC_HEADER);
- HobEnd->Reserved = 0;
-
- Hob->Version = EFI_HOB_HANDOFF_TABLE_VERSION;
- Hob->BootMode = BOOT_WITH_FULL_CONFIGURATION;
-
- Hob->EfiMemoryTop = (UINTN)EfiMemoryBegin + EfiMemoryLength;
- Hob->EfiMemoryBottom = (UINTN)EfiMemoryBegin;
- Hob->EfiFreeMemoryTop = (UINTN)EfiFreeMemoryTop;
- Hob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS)(UINTN)(HobEnd+1);
- Hob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd;
-
- return Hob;
-}
-
-VOID *
-CreateHob (
- IN UINT16 HobType,
- IN UINT16 HobLength
- )
-{
- EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob;
- EFI_HOB_GENERIC_HEADER *HobEnd;
- EFI_PHYSICAL_ADDRESS FreeMemory;
- VOID *Hob;
-
- HandOffHob = GetHobList ();
-
- HobLength = (UINT16)((HobLength + 0x7) & (~0x7));
-
- FreeMemory = HandOffHob->EfiFreeMemoryTop - HandOffHob->EfiFreeMemoryBottom;
-
- if (FreeMemory < HobLength) {
- return NULL;
- }
-
- Hob = (VOID*) (UINTN) HandOffHob->EfiEndOfHobList;
- ((EFI_HOB_GENERIC_HEADER*) Hob)->HobType = HobType;
- ((EFI_HOB_GENERIC_HEADER*) Hob)->HobLength = HobLength;
- ((EFI_HOB_GENERIC_HEADER*) Hob)->Reserved = 0;
-
- HobEnd = (EFI_HOB_GENERIC_HEADER*) ((UINTN)Hob + HobLength);
- HandOffHob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd;
-
- HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST;
- HobEnd->HobLength = sizeof(EFI_HOB_GENERIC_HEADER);
- HobEnd->Reserved = 0;
- HobEnd++;
- HandOffHob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd;
-
- return Hob;
-}
-
-/**
- Builds a HOB that describes a chunk of system memory.
-
- This function builds a HOB that describes a chunk of system memory.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param ResourceType The type of resource described by this HOB.
- @param ResourceAttribute The resource attributes of the memory described by this HOB.
- @param PhysicalStart The 64 bit physical address of memory described by this HOB.
- @param NumberOfBytes The length of the memory described by this HOB in bytes.
-
-**/
-VOID
-EFIAPI
-BuildResourceDescriptorHob (
- IN EFI_RESOURCE_TYPE ResourceType,
- IN EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute,
- IN EFI_PHYSICAL_ADDRESS PhysicalStart,
- IN UINT64 NumberOfBytes
- )
-{
- EFI_HOB_RESOURCE_DESCRIPTOR *Hob;
-
- Hob = CreateHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, sizeof (EFI_HOB_RESOURCE_DESCRIPTOR));
- ASSERT(Hob != NULL);
-
- Hob->ResourceType = ResourceType;
- Hob->ResourceAttribute = ResourceAttribute;
- Hob->PhysicalStart = PhysicalStart;
- Hob->ResourceLength = NumberOfBytes;
-}
-
-/**
-
-
-**/
-VOID
-CreateHobList (
- IN VOID *MemoryBegin,
- IN UINTN MemoryLength,
- IN VOID *HobBase,
- IN VOID *StackBase
- )
-{
- EFI_HOB_HANDOFF_INFO_TABLE *Hob;
- EFI_RESOURCE_ATTRIBUTE_TYPE Attributes;
-
- Hob = HobConstructor (MemoryBegin,MemoryLength,HobBase,StackBase);
- SetHobList (Hob);
-
- BuildCpuHob (PcdGet8 (PcdPrePiCpuMemorySize), PcdGet8 (PcdPrePiCpuIoSize));
-
- Attributes =(
- EFI_RESOURCE_ATTRIBUTE_PRESENT |
- EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
- EFI_RESOURCE_ATTRIBUTE_TESTED |
- EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |
- EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |
- EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |
- EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE
- );
-
- BuildResourceDescriptorHob (EFI_RESOURCE_SYSTEM_MEMORY, Attributes, (UINTN)MemoryBegin, MemoryLength);
-
- BuildStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)StackBase, ((UINTN)MemoryBegin + MemoryLength) - (UINTN)StackBase);
-
- if (FeaturePcdGet (PcdPrePiProduceMemoryTypeInformationHob)) {
- // Optional feature that helps prevent EFI memory map fragmentation.
- BuildMemoryTypeInformationHob ();
- }
-}
-
-
-VOID
-EFIAPI
-BuildFvHobs (
- IN EFI_PHYSICAL_ADDRESS PhysicalStart,
- IN UINT64 NumberOfBytes,
- IN EFI_RESOURCE_ATTRIBUTE_TYPE *ResourceAttribute
- )
-{
-
- EFI_RESOURCE_ATTRIBUTE_TYPE Resource;
-
- BuildFvHob (PhysicalStart, NumberOfBytes);
-
- if (ResourceAttribute == NULL) {
- Resource = (EFI_RESOURCE_ATTRIBUTE_PRESENT |
- EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
- EFI_RESOURCE_ATTRIBUTE_TESTED |
- EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE);
- } else {
- Resource = *ResourceAttribute;
- }
-
- BuildResourceDescriptorHob (EFI_RESOURCE_FIRMWARE_DEVICE, Resource, PhysicalStart, NumberOfBytes);
-}
-
-/**
- Returns the next instance of a HOB type from the starting HOB.
-
- This function searches the first instance of a HOB type from the starting HOB pointer.
- If there does not exist such HOB type from the starting HOB pointer, it will return NULL.
- In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
- unconditionally: it returns HobStart back if HobStart itself meets the requirement;
- caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
- If HobStart is NULL, then ASSERT().
-
- @param Type The HOB type to return.
- @param HobStart The starting HOB pointer to search from.
-
- @return The next instance of a HOB type from the starting HOB.
-
-**/
-VOID *
-EFIAPI
-GetNextHob (
- IN UINT16 Type,
- IN CONST VOID *HobStart
- )
-{
- EFI_PEI_HOB_POINTERS Hob;
-
- ASSERT (HobStart != NULL);
-
- Hob.Raw = (UINT8 *) HobStart;
- //
- // Parse the HOB list until end of list or matching type is found.
- //
- while (!END_OF_HOB_LIST (Hob)) {
- if (Hob.Header->HobType == Type) {
- return Hob.Raw;
- }
- Hob.Raw = GET_NEXT_HOB (Hob);
- }
- return NULL;
-}
-
-
-
-/**
- Returns the first instance of a HOB type among the whole HOB list.
-
- This function searches the first instance of a HOB type among the whole HOB list.
- If there does not exist such HOB type in the HOB list, it will return NULL.
-
- @param Type The HOB type to return.
-
- @return The next instance of a HOB type from the starting HOB.
-
-**/
-VOID *
-EFIAPI
-GetFirstHob (
- IN UINT16 Type
- )
-{
- VOID *HobList;
-
- HobList = GetHobList ();
- return GetNextHob (Type, HobList);
-}
-
-
-/**
- This function searches the first instance of a HOB from the starting HOB pointer.
- Such HOB should satisfy two conditions:
- its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
- If there does not exist such HOB from the starting HOB pointer, it will return NULL.
- Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
- to extract the data section and its size info respectively.
- In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
- unconditionally: it returns HobStart back if HobStart itself meets the requirement;
- caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
- If Guid is NULL, then ASSERT().
- If HobStart is NULL, then ASSERT().
-
- @param Guid The GUID to match with in the HOB list.
- @param HobStart A pointer to a Guid.
-
- @return The next instance of the matched GUID HOB from the starting HOB.
-
-**/
-VOID *
-EFIAPI
-GetNextGuidHob (
- IN CONST EFI_GUID *Guid,
- IN CONST VOID *HobStart
- ){
- EFI_PEI_HOB_POINTERS GuidHob;
-
- GuidHob.Raw = (UINT8 *) HobStart;
- while ((GuidHob.Raw = GetNextHob (EFI_HOB_TYPE_GUID_EXTENSION, GuidHob.Raw)) != NULL) {
- if (CompareGuid (Guid, &GuidHob.Guid->Name)) {
- break;
- }
- GuidHob.Raw = GET_NEXT_HOB (GuidHob);
- }
- return GuidHob.Raw;
-}
-
-
-/**
- This function searches the first instance of a HOB among the whole HOB list.
- Such HOB should satisfy two conditions:
- its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
- If there does not exist such HOB from the starting HOB pointer, it will return NULL.
- Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
- to extract the data section and its size info respectively.
- If Guid is NULL, then ASSERT().
-
- @param Guid The GUID to match with in the HOB list.
-
- @return The first instance of the matched GUID HOB among the whole HOB list.
-
-**/
-VOID *
-EFIAPI
-GetFirstGuidHob (
- IN CONST EFI_GUID *Guid
- )
-{
- VOID *HobList;
-
- HobList = GetHobList ();
- return GetNextGuidHob (Guid, HobList);
-}
-
-
-/**
- Get the Boot Mode from the HOB list.
-
- This function returns the system boot mode information from the
- PHIT HOB in HOB list.
-
- @param VOID
-
- @return The Boot Mode.
-
-**/
-EFI_BOOT_MODE
-EFIAPI
-GetBootMode (
- VOID
- )
-{
- EFI_PEI_HOB_POINTERS Hob;
-
- Hob.Raw = GetHobList ();
- return Hob.HandoffInformationTable->BootMode;
-}
-
-
-/**
- Get the Boot Mode from the HOB list.
-
- This function returns the system boot mode information from the
- PHIT HOB in HOB list.
-
- @param VOID
-
- @return The Boot Mode.
-
-**/
-EFI_STATUS
-EFIAPI
-SetBootMode (
- IN EFI_BOOT_MODE BootMode
- )
-{
- EFI_PEI_HOB_POINTERS Hob;
-
- Hob.Raw = GetHobList ();
- Hob.HandoffInformationTable->BootMode = BootMode;
- return BootMode;
-}
-
-/**
- Builds a HOB for a loaded PE32 module.
-
- This function builds a HOB for a loaded PE32 module.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If ModuleName is NULL, then ASSERT().
- If there is no additional space for HOB creation, then ASSERT().
-
- @param ModuleName The GUID File Name of the module.
- @param MemoryAllocationModule The 64 bit physical address of the module.
- @param ModuleLength The length of the module in bytes.
- @param EntryPoint The 64 bit physical address of the module entry point.
-
-**/
-VOID
-EFIAPI
-BuildModuleHob (
- IN CONST EFI_GUID *ModuleName,
- IN EFI_PHYSICAL_ADDRESS MemoryAllocationModule,
- IN UINT64 ModuleLength,
- IN EFI_PHYSICAL_ADDRESS EntryPoint
- )
-{
- EFI_HOB_MEMORY_ALLOCATION_MODULE *Hob;
-
- ASSERT (((MemoryAllocationModule & (EFI_PAGE_SIZE - 1)) == 0) &&
- ((ModuleLength & (EFI_PAGE_SIZE - 1)) == 0));
-
- Hob = CreateHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION_MODULE));
-
- CopyGuid (&(Hob->MemoryAllocationHeader.Name), &gEfiHobMemoryAllocModuleGuid);
- Hob->MemoryAllocationHeader.MemoryBaseAddress = MemoryAllocationModule;
- Hob->MemoryAllocationHeader.MemoryLength = ModuleLength;
- Hob->MemoryAllocationHeader.MemoryType = EfiBootServicesCode;
-
- //
- // Zero the reserved space to match HOB spec
- //
- ZeroMem (Hob->MemoryAllocationHeader.Reserved, sizeof (Hob->MemoryAllocationHeader.Reserved));
-
- CopyGuid (&Hob->ModuleName, ModuleName);
- Hob->EntryPoint = EntryPoint;
-}
-
-/**
- Builds a GUID HOB with a certain data length.
-
- This function builds a customized HOB tagged with a GUID for identification
- and returns the start address of GUID HOB data so that caller can fill the customized data.
- The HOB Header and Name field is already stripped.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If Guid is NULL, then ASSERT().
- If there is no additional space for HOB creation, then ASSERT().
- If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
-
- @param Guid The GUID to tag the customized HOB.
- @param DataLength The size of the data payload for the GUID HOB.
-
- @return The start address of GUID HOB data.
-
-**/
-VOID *
-EFIAPI
-BuildGuidHob (
- IN CONST EFI_GUID *Guid,
- IN UINTN DataLength
- )
-{
- EFI_HOB_GUID_TYPE *Hob;
-
- //
- // Make sure that data length is not too long.
- //
- ASSERT (DataLength <= (0xffff - sizeof (EFI_HOB_GUID_TYPE)));
-
- Hob = CreateHob (EFI_HOB_TYPE_GUID_EXTENSION, (UINT16) (sizeof (EFI_HOB_GUID_TYPE) + DataLength));
- CopyGuid (&Hob->Name, Guid);
- return Hob + 1;
-}
-
-
-/**
- Copies a data buffer to a newly-built HOB.
-
- This function builds a customized HOB tagged with a GUID for identification,
- copies the input data to the HOB data field and returns the start address of the GUID HOB data.
- The HOB Header and Name field is already stripped.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If Guid is NULL, then ASSERT().
- If Data is NULL and DataLength > 0, then ASSERT().
- If there is no additional space for HOB creation, then ASSERT().
- If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
-
- @param Guid The GUID to tag the customized HOB.
- @param Data The data to be copied into the data field of the GUID HOB.
- @param DataLength The size of the data payload for the GUID HOB.
-
- @return The start address of GUID HOB data.
-
-**/
-VOID *
-EFIAPI
-BuildGuidDataHob (
- IN CONST EFI_GUID *Guid,
- IN VOID *Data,
- IN UINTN DataLength
- )
-{
- VOID *HobData;
-
- ASSERT (Data != NULL || DataLength == 0);
-
- HobData = BuildGuidHob (Guid, DataLength);
-
- return CopyMem (HobData, Data, DataLength);
-}
-
-
-/**
- Builds a Firmware Volume HOB.
-
- This function builds a Firmware Volume HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Firmware Volume.
- @param Length The size of the Firmware Volume in bytes.
-
-**/
-VOID
-EFIAPI
-BuildFvHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- )
-{
- EFI_HOB_FIRMWARE_VOLUME *Hob;
-
- Hob = CreateHob (EFI_HOB_TYPE_FV, sizeof (EFI_HOB_FIRMWARE_VOLUME));
-
- Hob->BaseAddress = BaseAddress;
- Hob->Length = Length;
-}
-
-
-/**
- Builds a EFI_HOB_TYPE_FV2 HOB.
-
- This function builds a EFI_HOB_TYPE_FV2 HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Firmware Volume.
- @param Length The size of the Firmware Volume in bytes.
- @param FvName The name of the Firmware Volume.
- @param FileName The name of the file.
-
-**/
-VOID
-EFIAPI
-BuildFv2Hob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length,
- IN CONST EFI_GUID *FvName,
- IN CONST EFI_GUID *FileName
- )
-{
- EFI_HOB_FIRMWARE_VOLUME2 *Hob;
-
- Hob = CreateHob (EFI_HOB_TYPE_FV2, sizeof (EFI_HOB_FIRMWARE_VOLUME2));
-
- Hob->BaseAddress = BaseAddress;
- Hob->Length = Length;
- CopyGuid (&Hob->FvName, FvName);
- CopyGuid (&Hob->FileName, FileName);
-}
-
-
-
-/**
- Builds a Capsule Volume HOB.
-
- This function builds a Capsule Volume HOB.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The base address of the Capsule Volume.
- @param Length The size of the Capsule Volume in bytes.
-
-**/
-VOID
-EFIAPI
-BuildCvHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- )
-{
- ASSERT (FALSE);
-}
-
-
-/**
- Builds a HOB for the CPU.
-
- This function builds a HOB for the CPU.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param SizeOfMemorySpace The maximum physical memory addressability of the processor.
- @param SizeOfIoSpace The maximum physical I/O addressability of the processor.
-
-**/
-VOID
-EFIAPI
-BuildCpuHob (
- IN UINT8 SizeOfMemorySpace,
- IN UINT8 SizeOfIoSpace
- )
-{
- EFI_HOB_CPU *Hob;
-
- Hob = CreateHob (EFI_HOB_TYPE_CPU, sizeof (EFI_HOB_CPU));
-
- Hob->SizeOfMemorySpace = SizeOfMemorySpace;
- Hob->SizeOfIoSpace = SizeOfIoSpace;
-
- //
- // Zero the reserved space to match HOB spec
- //
- ZeroMem (Hob->Reserved, sizeof (Hob->Reserved));
-}
-
-
-/**
- Builds a HOB for the Stack.
-
- This function builds a HOB for the stack.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The 64 bit physical address of the Stack.
- @param Length The length of the stack in bytes.
-
-**/
-VOID
-EFIAPI
-BuildStackHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- )
-{
- EFI_HOB_MEMORY_ALLOCATION_STACK *Hob;
-
- ASSERT (((BaseAddress & (EFI_PAGE_SIZE - 1)) == 0) &&
- ((Length & (EFI_PAGE_SIZE - 1)) == 0));
-
- Hob = CreateHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION_STACK));
-
- CopyGuid (&(Hob->AllocDescriptor.Name), &gEfiHobMemoryAllocStackGuid);
- Hob->AllocDescriptor.MemoryBaseAddress = BaseAddress;
- Hob->AllocDescriptor.MemoryLength = Length;
- Hob->AllocDescriptor.MemoryType = EfiBootServicesData;
-
- //
- // Zero the reserved space to match HOB spec
- //
- ZeroMem (Hob->AllocDescriptor.Reserved, sizeof (Hob->AllocDescriptor.Reserved));
-}
-
-
-/**
- Update the Stack Hob if the stack has been moved
-
- @param BaseAddress The 64 bit physical address of the Stack.
- @param Length The length of the stack in bytes.
-
-**/
-VOID
-UpdateStackHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length
- )
-{
- EFI_PEI_HOB_POINTERS Hob;
-
- Hob.Raw = GetHobList ();
- while ((Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw)) != NULL) {
- if (CompareGuid (&gEfiHobMemoryAllocStackGuid, &(Hob.MemoryAllocationStack->AllocDescriptor.Name))) {
- //
- // Build a new memory allocation HOB with old stack info with EfiConventionalMemory type
- // to be reclaimed by DXE core.
- //
- BuildMemoryAllocationHob (
- Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress,
- Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength,
- EfiConventionalMemory
- );
- //
- // Update the BSP Stack Hob to reflect the new stack info.
- //
- Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress = BaseAddress;
- Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength = Length;
- break;
- }
- Hob.Raw = GET_NEXT_HOB (Hob);
- }
-}
-
-
-
-/**
- Builds a HOB for the memory allocation.
-
- This function builds a HOB for the memory allocation.
- It can only be invoked during PEI phase;
- for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
- If there is no additional space for HOB creation, then ASSERT().
-
- @param BaseAddress The 64 bit physical address of the memory.
- @param Length The length of the memory allocation in bytes.
- @param MemoryType Type of memory allocated by this HOB.
-
-**/
-VOID
-EFIAPI
-BuildMemoryAllocationHob (
- IN EFI_PHYSICAL_ADDRESS BaseAddress,
- IN UINT64 Length,
- IN EFI_MEMORY_TYPE MemoryType
- )
-{
- EFI_HOB_MEMORY_ALLOCATION *Hob;
-
- ASSERT (((BaseAddress & (EFI_PAGE_SIZE - 1)) == 0) &&
- ((Length & (EFI_PAGE_SIZE - 1)) == 0));
-
- Hob = CreateHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION));
-
- ZeroMem (&(Hob->AllocDescriptor.Name), sizeof (EFI_GUID));
- Hob->AllocDescriptor.MemoryBaseAddress = BaseAddress;
- Hob->AllocDescriptor.MemoryLength = Length;
- Hob->AllocDescriptor.MemoryType = MemoryType;
- //
- // Zero the reserved space to match HOB spec
- //
- ZeroMem (Hob->AllocDescriptor.Reserved, sizeof (Hob->AllocDescriptor.Reserved));
-}
-
-
-
-VOID
-EFIAPI
-BuildExtractSectionHob (
- IN EFI_GUID *Guid,
- IN EXTRACT_GUIDED_SECTION_GET_INFO_HANDLER SectionGetInfo,
- IN EXTRACT_GUIDED_SECTION_DECODE_HANDLER SectionExtraction
- )
-{
- EXTRACT_SECTION_DATA Data;
-
- Data.SectionGetInfo = SectionGetInfo;
- Data.SectionExtraction = SectionExtraction;
- BuildGuidDataHob (Guid, &Data, sizeof (Data));
-}
-
-PE_COFF_LOADER_PROTOCOL gPeCoffProtocol = {
- PeCoffLoaderGetImageInfo,
- PeCoffLoaderLoadImage,
- PeCoffLoaderRelocateImage,
- PeCoffLoaderImageReadFromMemory,
- PeCoffLoaderRelocateImageForRuntime,
- PeCoffLoaderUnloadImage
-};
-
-
-
-VOID
-EFIAPI
-BuildPeCoffLoaderHob (
- VOID
- )
-{
- VOID *Ptr;
-
- Ptr = &gPeCoffProtocol;
- BuildGuidDataHob (&gPeCoffLoaderProtocolGuid, &Ptr, sizeof (VOID *));
-}
-
-// May want to put this into a library so you only need the PCD setings if you are using the feature?
-VOID
-BuildMemoryTypeInformationHob (
- VOID
- )
-{
- EFI_MEMORY_TYPE_INFORMATION Info[10];
-
- Info[0].Type = EfiACPIReclaimMemory;
- Info[0].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiACPIReclaimMemory);
- Info[1].Type = EfiACPIMemoryNVS;
- Info[1].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiACPIMemoryNVS);
- Info[2].Type = EfiReservedMemoryType;
- Info[2].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiReservedMemoryType);
- Info[3].Type = EfiRuntimeServicesData;
- Info[3].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiRuntimeServicesData);
- Info[4].Type = EfiRuntimeServicesCode;
- Info[4].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiRuntimeServicesCode);
- Info[5].Type = EfiBootServicesCode;
- Info[5].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiBootServicesCode);
- Info[6].Type = EfiBootServicesData;
- Info[6].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiBootServicesData);
- Info[7].Type = EfiLoaderCode;
- Info[7].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiLoaderCode);
- Info[8].Type = EfiLoaderData;
- Info[8].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiLoaderData);
-
- // Terminator for the list
- Info[9].Type = EfiMaxMemoryType;
- Info[9].NumberOfPages = 0;
-
-
- BuildGuidDataHob (&gEfiMemoryTypeInformationGuid, &Info, sizeof (Info));
-}
-
+/** @file
+
+ Copyright (c) 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PiPei.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PeCoffLib.h>
+#include <Library/HobLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PrePiHobListPointerLib.h>
+
+#include <Protocol/PeCoffLoader.h>
+#include <Guid/ExtractSection.h>
+#include <Guid/MemoryTypeInformation.h>
+#include <Guid/MemoryAllocationHob.h>
+
+VOID
+BuildMemoryTypeInformationHob (
+ VOID
+ );
+
+/**
+ Returns the pointer to the HOB list.
+
+ This function returns the pointer to first HOB in the list.
+
+ @return The pointer to the HOB list.
+
+**/
+VOID *
+EFIAPI
+GetHobList (
+ VOID
+ )
+{
+ return PrePeiGetHobList ();
+}
+
+
+
+/**
+ Updates the pointer to the HOB list.
+
+ @param HobList Hob list pointer to store
+
+**/
+EFI_STATUS
+EFIAPI
+SetHobList (
+ IN VOID *HobList
+ )
+{
+ return PrePeiSetHobList (HobList);
+}
+
+/**
+
+
+**/
+EFI_HOB_HANDOFF_INFO_TABLE*
+HobConstructor (
+ IN VOID *EfiMemoryBegin,
+ IN UINTN EfiMemoryLength,
+ IN VOID *EfiFreeMemoryBottom,
+ IN VOID *EfiFreeMemoryTop
+ )
+{
+ EFI_HOB_HANDOFF_INFO_TABLE *Hob;
+ EFI_HOB_GENERIC_HEADER *HobEnd;
+
+ Hob = EfiFreeMemoryBottom;
+ HobEnd = (EFI_HOB_GENERIC_HEADER *)(Hob+1);
+
+ Hob->Header.HobType = EFI_HOB_TYPE_HANDOFF;
+ Hob->Header.HobLength = sizeof(EFI_HOB_HANDOFF_INFO_TABLE);
+ Hob->Header.Reserved = 0;
+
+ HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST;
+ HobEnd->HobLength = sizeof(EFI_HOB_GENERIC_HEADER);
+ HobEnd->Reserved = 0;
+
+ Hob->Version = EFI_HOB_HANDOFF_TABLE_VERSION;
+ Hob->BootMode = BOOT_WITH_FULL_CONFIGURATION;
+
+ Hob->EfiMemoryTop = (UINTN)EfiMemoryBegin + EfiMemoryLength;
+ Hob->EfiMemoryBottom = (UINTN)EfiMemoryBegin;
+ Hob->EfiFreeMemoryTop = (UINTN)EfiFreeMemoryTop;
+ Hob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS)(UINTN)(HobEnd+1);
+ Hob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd;
+
+ return Hob;
+}
+
+VOID *
+CreateHob (
+ IN UINT16 HobType,
+ IN UINT16 HobLength
+ )
+{
+ EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob;
+ EFI_HOB_GENERIC_HEADER *HobEnd;
+ EFI_PHYSICAL_ADDRESS FreeMemory;
+ VOID *Hob;
+
+ HandOffHob = GetHobList ();
+
+ HobLength = (UINT16)((HobLength + 0x7) & (~0x7));
+
+ FreeMemory = HandOffHob->EfiFreeMemoryTop - HandOffHob->EfiFreeMemoryBottom;
+
+ if (FreeMemory < HobLength) {
+ return NULL;
+ }
+
+ Hob = (VOID*) (UINTN) HandOffHob->EfiEndOfHobList;
+ ((EFI_HOB_GENERIC_HEADER*) Hob)->HobType = HobType;
+ ((EFI_HOB_GENERIC_HEADER*) Hob)->HobLength = HobLength;
+ ((EFI_HOB_GENERIC_HEADER*) Hob)->Reserved = 0;
+
+ HobEnd = (EFI_HOB_GENERIC_HEADER*) ((UINTN)Hob + HobLength);
+ HandOffHob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd;
+
+ HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST;
+ HobEnd->HobLength = sizeof(EFI_HOB_GENERIC_HEADER);
+ HobEnd->Reserved = 0;
+ HobEnd++;
+ HandOffHob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd;
+
+ return Hob;
+}
+
+/**
+ Builds a HOB that describes a chunk of system memory.
+
+ This function builds a HOB that describes a chunk of system memory.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param ResourceType The type of resource described by this HOB.
+ @param ResourceAttribute The resource attributes of the memory described by this HOB.
+ @param PhysicalStart The 64 bit physical address of memory described by this HOB.
+ @param NumberOfBytes The length of the memory described by this HOB in bytes.
+
+**/
+VOID
+EFIAPI
+BuildResourceDescriptorHob (
+ IN EFI_RESOURCE_TYPE ResourceType,
+ IN EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute,
+ IN EFI_PHYSICAL_ADDRESS PhysicalStart,
+ IN UINT64 NumberOfBytes
+ )
+{
+ EFI_HOB_RESOURCE_DESCRIPTOR *Hob;
+
+ Hob = CreateHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, sizeof (EFI_HOB_RESOURCE_DESCRIPTOR));
+ ASSERT(Hob != NULL);
+
+ Hob->ResourceType = ResourceType;
+ Hob->ResourceAttribute = ResourceAttribute;
+ Hob->PhysicalStart = PhysicalStart;
+ Hob->ResourceLength = NumberOfBytes;
+}
+
+/**
+
+
+**/
+VOID
+CreateHobList (
+ IN VOID *MemoryBegin,
+ IN UINTN MemoryLength,
+ IN VOID *HobBase,
+ IN VOID *StackBase
+ )
+{
+ EFI_HOB_HANDOFF_INFO_TABLE *Hob;
+ EFI_RESOURCE_ATTRIBUTE_TYPE Attributes;
+
+ Hob = HobConstructor (MemoryBegin,MemoryLength,HobBase,StackBase);
+ SetHobList (Hob);
+
+ BuildCpuHob (PcdGet8 (PcdPrePiCpuMemorySize), PcdGet8 (PcdPrePiCpuIoSize));
+
+ Attributes =(
+ EFI_RESOURCE_ATTRIBUTE_PRESENT |
+ EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
+ EFI_RESOURCE_ATTRIBUTE_TESTED |
+ EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |
+ EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |
+ EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |
+ EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE
+ );
+
+ BuildResourceDescriptorHob (EFI_RESOURCE_SYSTEM_MEMORY, Attributes, (UINTN)MemoryBegin, MemoryLength);
+
+ BuildStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)StackBase, ((UINTN)MemoryBegin + MemoryLength) - (UINTN)StackBase);
+
+ if (FeaturePcdGet (PcdPrePiProduceMemoryTypeInformationHob)) {
+ // Optional feature that helps prevent EFI memory map fragmentation.
+ BuildMemoryTypeInformationHob ();
+ }
+}
+
+
+VOID
+EFIAPI
+BuildFvHobs (
+ IN EFI_PHYSICAL_ADDRESS PhysicalStart,
+ IN UINT64 NumberOfBytes,
+ IN EFI_RESOURCE_ATTRIBUTE_TYPE *ResourceAttribute
+ )
+{
+
+ EFI_RESOURCE_ATTRIBUTE_TYPE Resource;
+
+ BuildFvHob (PhysicalStart, NumberOfBytes);
+
+ if (ResourceAttribute == NULL) {
+ Resource = (EFI_RESOURCE_ATTRIBUTE_PRESENT |
+ EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
+ EFI_RESOURCE_ATTRIBUTE_TESTED |
+ EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE);
+ } else {
+ Resource = *ResourceAttribute;
+ }
+
+ BuildResourceDescriptorHob (EFI_RESOURCE_FIRMWARE_DEVICE, Resource, PhysicalStart, NumberOfBytes);
+}
+
+/**
+ Returns the next instance of a HOB type from the starting HOB.
+
+ This function searches the first instance of a HOB type from the starting HOB pointer.
+ If there does not exist such HOB type from the starting HOB pointer, it will return NULL.
+ In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
+ unconditionally: it returns HobStart back if HobStart itself meets the requirement;
+ caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
+ If HobStart is NULL, then ASSERT().
+
+ @param Type The HOB type to return.
+ @param HobStart The starting HOB pointer to search from.
+
+ @return The next instance of a HOB type from the starting HOB.
+
+**/
+VOID *
+EFIAPI
+GetNextHob (
+ IN UINT16 Type,
+ IN CONST VOID *HobStart
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+
+ ASSERT (HobStart != NULL);
+
+ Hob.Raw = (UINT8 *) HobStart;
+ //
+ // Parse the HOB list until end of list or matching type is found.
+ //
+ while (!END_OF_HOB_LIST (Hob)) {
+ if (Hob.Header->HobType == Type) {
+ return Hob.Raw;
+ }
+ Hob.Raw = GET_NEXT_HOB (Hob);
+ }
+ return NULL;
+}
+
+
+
+/**
+ Returns the first instance of a HOB type among the whole HOB list.
+
+ This function searches the first instance of a HOB type among the whole HOB list.
+ If there does not exist such HOB type in the HOB list, it will return NULL.
+
+ @param Type The HOB type to return.
+
+ @return The next instance of a HOB type from the starting HOB.
+
+**/
+VOID *
+EFIAPI
+GetFirstHob (
+ IN UINT16 Type
+ )
+{
+ VOID *HobList;
+
+ HobList = GetHobList ();
+ return GetNextHob (Type, HobList);
+}
+
+
+/**
+ This function searches the first instance of a HOB from the starting HOB pointer.
+ Such HOB should satisfy two conditions:
+ its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
+ If there does not exist such HOB from the starting HOB pointer, it will return NULL.
+ Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
+ to extract the data section and its size info respectively.
+ In contrast with macro GET_NEXT_HOB(), this function does not skip the starting HOB pointer
+ unconditionally: it returns HobStart back if HobStart itself meets the requirement;
+ caller is required to use GET_NEXT_HOB() if it wishes to skip current HobStart.
+ If Guid is NULL, then ASSERT().
+ If HobStart is NULL, then ASSERT().
+
+ @param Guid The GUID to match with in the HOB list.
+ @param HobStart A pointer to a Guid.
+
+ @return The next instance of the matched GUID HOB from the starting HOB.
+
+**/
+VOID *
+EFIAPI
+GetNextGuidHob (
+ IN CONST EFI_GUID *Guid,
+ IN CONST VOID *HobStart
+ ){
+ EFI_PEI_HOB_POINTERS GuidHob;
+
+ GuidHob.Raw = (UINT8 *) HobStart;
+ while ((GuidHob.Raw = GetNextHob (EFI_HOB_TYPE_GUID_EXTENSION, GuidHob.Raw)) != NULL) {
+ if (CompareGuid (Guid, &GuidHob.Guid->Name)) {
+ break;
+ }
+ GuidHob.Raw = GET_NEXT_HOB (GuidHob);
+ }
+ return GuidHob.Raw;
+}
+
+
+/**
+ This function searches the first instance of a HOB among the whole HOB list.
+ Such HOB should satisfy two conditions:
+ its HOB type is EFI_HOB_TYPE_GUID_EXTENSION and its GUID Name equals to the input Guid.
+ If there does not exist such HOB from the starting HOB pointer, it will return NULL.
+ Caller is required to apply GET_GUID_HOB_DATA () and GET_GUID_HOB_DATA_SIZE ()
+ to extract the data section and its size info respectively.
+ If Guid is NULL, then ASSERT().
+
+ @param Guid The GUID to match with in the HOB list.
+
+ @return The first instance of the matched GUID HOB among the whole HOB list.
+
+**/
+VOID *
+EFIAPI
+GetFirstGuidHob (
+ IN CONST EFI_GUID *Guid
+ )
+{
+ VOID *HobList;
+
+ HobList = GetHobList ();
+ return GetNextGuidHob (Guid, HobList);
+}
+
+
+/**
+ Get the Boot Mode from the HOB list.
+
+ This function returns the system boot mode information from the
+ PHIT HOB in HOB list.
+
+ @param VOID
+
+ @return The Boot Mode.
+
+**/
+EFI_BOOT_MODE
+EFIAPI
+GetBootMode (
+ VOID
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+
+ Hob.Raw = GetHobList ();
+ return Hob.HandoffInformationTable->BootMode;
+}
+
+
+/**
+ Get the Boot Mode from the HOB list.
+
+ This function returns the system boot mode information from the
+ PHIT HOB in HOB list.
+
+ @param VOID
+
+ @return The Boot Mode.
+
+**/
+EFI_STATUS
+EFIAPI
+SetBootMode (
+ IN EFI_BOOT_MODE BootMode
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+
+ Hob.Raw = GetHobList ();
+ Hob.HandoffInformationTable->BootMode = BootMode;
+ return BootMode;
+}
+
+/**
+ Builds a HOB for a loaded PE32 module.
+
+ This function builds a HOB for a loaded PE32 module.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If ModuleName is NULL, then ASSERT().
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param ModuleName The GUID File Name of the module.
+ @param MemoryAllocationModule The 64 bit physical address of the module.
+ @param ModuleLength The length of the module in bytes.
+ @param EntryPoint The 64 bit physical address of the module entry point.
+
+**/
+VOID
+EFIAPI
+BuildModuleHob (
+ IN CONST EFI_GUID *ModuleName,
+ IN EFI_PHYSICAL_ADDRESS MemoryAllocationModule,
+ IN UINT64 ModuleLength,
+ IN EFI_PHYSICAL_ADDRESS EntryPoint
+ )
+{
+ EFI_HOB_MEMORY_ALLOCATION_MODULE *Hob;
+
+ ASSERT (((MemoryAllocationModule & (EFI_PAGE_SIZE - 1)) == 0) &&
+ ((ModuleLength & (EFI_PAGE_SIZE - 1)) == 0));
+
+ Hob = CreateHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION_MODULE));
+
+ CopyGuid (&(Hob->MemoryAllocationHeader.Name), &gEfiHobMemoryAllocModuleGuid);
+ Hob->MemoryAllocationHeader.MemoryBaseAddress = MemoryAllocationModule;
+ Hob->MemoryAllocationHeader.MemoryLength = ModuleLength;
+ Hob->MemoryAllocationHeader.MemoryType = EfiBootServicesCode;
+
+ //
+ // Zero the reserved space to match HOB spec
+ //
+ ZeroMem (Hob->MemoryAllocationHeader.Reserved, sizeof (Hob->MemoryAllocationHeader.Reserved));
+
+ CopyGuid (&Hob->ModuleName, ModuleName);
+ Hob->EntryPoint = EntryPoint;
+}
+
+/**
+ Builds a GUID HOB with a certain data length.
+
+ This function builds a customized HOB tagged with a GUID for identification
+ and returns the start address of GUID HOB data so that caller can fill the customized data.
+ The HOB Header and Name field is already stripped.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If Guid is NULL, then ASSERT().
+ If there is no additional space for HOB creation, then ASSERT().
+ If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
+
+ @param Guid The GUID to tag the customized HOB.
+ @param DataLength The size of the data payload for the GUID HOB.
+
+ @return The start address of GUID HOB data.
+
+**/
+VOID *
+EFIAPI
+BuildGuidHob (
+ IN CONST EFI_GUID *Guid,
+ IN UINTN DataLength
+ )
+{
+ EFI_HOB_GUID_TYPE *Hob;
+
+ //
+ // Make sure that data length is not too long.
+ //
+ ASSERT (DataLength <= (0xffff - sizeof (EFI_HOB_GUID_TYPE)));
+
+ Hob = CreateHob (EFI_HOB_TYPE_GUID_EXTENSION, (UINT16) (sizeof (EFI_HOB_GUID_TYPE) + DataLength));
+ CopyGuid (&Hob->Name, Guid);
+ return Hob + 1;
+}
+
+
+/**
+ Copies a data buffer to a newly-built HOB.
+
+ This function builds a customized HOB tagged with a GUID for identification,
+ copies the input data to the HOB data field and returns the start address of the GUID HOB data.
+ The HOB Header and Name field is already stripped.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If Guid is NULL, then ASSERT().
+ If Data is NULL and DataLength > 0, then ASSERT().
+ If there is no additional space for HOB creation, then ASSERT().
+ If DataLength >= (0x10000 - sizeof (EFI_HOB_GUID_TYPE)), then ASSERT().
+
+ @param Guid The GUID to tag the customized HOB.
+ @param Data The data to be copied into the data field of the GUID HOB.
+ @param DataLength The size of the data payload for the GUID HOB.
+
+ @return The start address of GUID HOB data.
+
+**/
+VOID *
+EFIAPI
+BuildGuidDataHob (
+ IN CONST EFI_GUID *Guid,
+ IN VOID *Data,
+ IN UINTN DataLength
+ )
+{
+ VOID *HobData;
+
+ ASSERT (Data != NULL || DataLength == 0);
+
+ HobData = BuildGuidHob (Guid, DataLength);
+
+ return CopyMem (HobData, Data, DataLength);
+}
+
+
+/**
+ Builds a Firmware Volume HOB.
+
+ This function builds a Firmware Volume HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Firmware Volume.
+ @param Length The size of the Firmware Volume in bytes.
+
+**/
+VOID
+EFIAPI
+BuildFvHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ )
+{
+ EFI_HOB_FIRMWARE_VOLUME *Hob;
+
+ Hob = CreateHob (EFI_HOB_TYPE_FV, sizeof (EFI_HOB_FIRMWARE_VOLUME));
+
+ Hob->BaseAddress = BaseAddress;
+ Hob->Length = Length;
+}
+
+
+/**
+ Builds a EFI_HOB_TYPE_FV2 HOB.
+
+ This function builds a EFI_HOB_TYPE_FV2 HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Firmware Volume.
+ @param Length The size of the Firmware Volume in bytes.
+ @param FvName The name of the Firmware Volume.
+ @param FileName The name of the file.
+
+**/
+VOID
+EFIAPI
+BuildFv2Hob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length,
+ IN CONST EFI_GUID *FvName,
+ IN CONST EFI_GUID *FileName
+ )
+{
+ EFI_HOB_FIRMWARE_VOLUME2 *Hob;
+
+ Hob = CreateHob (EFI_HOB_TYPE_FV2, sizeof (EFI_HOB_FIRMWARE_VOLUME2));
+
+ Hob->BaseAddress = BaseAddress;
+ Hob->Length = Length;
+ CopyGuid (&Hob->FvName, FvName);
+ CopyGuid (&Hob->FileName, FileName);
+}
+
+
+
+/**
+ Builds a Capsule Volume HOB.
+
+ This function builds a Capsule Volume HOB.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The base address of the Capsule Volume.
+ @param Length The size of the Capsule Volume in bytes.
+
+**/
+VOID
+EFIAPI
+BuildCvHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ )
+{
+ ASSERT (FALSE);
+}
+
+
+/**
+ Builds a HOB for the CPU.
+
+ This function builds a HOB for the CPU.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param SizeOfMemorySpace The maximum physical memory addressability of the processor.
+ @param SizeOfIoSpace The maximum physical I/O addressability of the processor.
+
+**/
+VOID
+EFIAPI
+BuildCpuHob (
+ IN UINT8 SizeOfMemorySpace,
+ IN UINT8 SizeOfIoSpace
+ )
+{
+ EFI_HOB_CPU *Hob;
+
+ Hob = CreateHob (EFI_HOB_TYPE_CPU, sizeof (EFI_HOB_CPU));
+
+ Hob->SizeOfMemorySpace = SizeOfMemorySpace;
+ Hob->SizeOfIoSpace = SizeOfIoSpace;
+
+ //
+ // Zero the reserved space to match HOB spec
+ //
+ ZeroMem (Hob->Reserved, sizeof (Hob->Reserved));
+}
+
+
+/**
+ Builds a HOB for the Stack.
+
+ This function builds a HOB for the stack.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The 64 bit physical address of the Stack.
+ @param Length The length of the stack in bytes.
+
+**/
+VOID
+EFIAPI
+BuildStackHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ )
+{
+ EFI_HOB_MEMORY_ALLOCATION_STACK *Hob;
+
+ ASSERT (((BaseAddress & (EFI_PAGE_SIZE - 1)) == 0) &&
+ ((Length & (EFI_PAGE_SIZE - 1)) == 0));
+
+ Hob = CreateHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION_STACK));
+
+ CopyGuid (&(Hob->AllocDescriptor.Name), &gEfiHobMemoryAllocStackGuid);
+ Hob->AllocDescriptor.MemoryBaseAddress = BaseAddress;
+ Hob->AllocDescriptor.MemoryLength = Length;
+ Hob->AllocDescriptor.MemoryType = EfiBootServicesData;
+
+ //
+ // Zero the reserved space to match HOB spec
+ //
+ ZeroMem (Hob->AllocDescriptor.Reserved, sizeof (Hob->AllocDescriptor.Reserved));
+}
+
+
+/**
+ Update the Stack Hob if the stack has been moved
+
+ @param BaseAddress The 64 bit physical address of the Stack.
+ @param Length The length of the stack in bytes.
+
+**/
+VOID
+UpdateStackHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+
+ Hob.Raw = GetHobList ();
+ while ((Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw)) != NULL) {
+ if (CompareGuid (&gEfiHobMemoryAllocStackGuid, &(Hob.MemoryAllocationStack->AllocDescriptor.Name))) {
+ //
+ // Build a new memory allocation HOB with old stack info with EfiConventionalMemory type
+ // to be reclaimed by DXE core.
+ //
+ BuildMemoryAllocationHob (
+ Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress,
+ Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength,
+ EfiConventionalMemory
+ );
+ //
+ // Update the BSP Stack Hob to reflect the new stack info.
+ //
+ Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress = BaseAddress;
+ Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength = Length;
+ break;
+ }
+ Hob.Raw = GET_NEXT_HOB (Hob);
+ }
+}
+
+
+
+/**
+ Builds a HOB for the memory allocation.
+
+ This function builds a HOB for the memory allocation.
+ It can only be invoked during PEI phase;
+ for DXE phase, it will ASSERT() since PEI HOB is read-only for DXE phase.
+ If there is no additional space for HOB creation, then ASSERT().
+
+ @param BaseAddress The 64 bit physical address of the memory.
+ @param Length The length of the memory allocation in bytes.
+ @param MemoryType Type of memory allocated by this HOB.
+
+**/
+VOID
+EFIAPI
+BuildMemoryAllocationHob (
+ IN EFI_PHYSICAL_ADDRESS BaseAddress,
+ IN UINT64 Length,
+ IN EFI_MEMORY_TYPE MemoryType
+ )
+{
+ EFI_HOB_MEMORY_ALLOCATION *Hob;
+
+ ASSERT (((BaseAddress & (EFI_PAGE_SIZE - 1)) == 0) &&
+ ((Length & (EFI_PAGE_SIZE - 1)) == 0));
+
+ Hob = CreateHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, sizeof (EFI_HOB_MEMORY_ALLOCATION));
+
+ ZeroMem (&(Hob->AllocDescriptor.Name), sizeof (EFI_GUID));
+ Hob->AllocDescriptor.MemoryBaseAddress = BaseAddress;
+ Hob->AllocDescriptor.MemoryLength = Length;
+ Hob->AllocDescriptor.MemoryType = MemoryType;
+ //
+ // Zero the reserved space to match HOB spec
+ //
+ ZeroMem (Hob->AllocDescriptor.Reserved, sizeof (Hob->AllocDescriptor.Reserved));
+}
+
+
+
+VOID
+EFIAPI
+BuildExtractSectionHob (
+ IN EFI_GUID *Guid,
+ IN EXTRACT_GUIDED_SECTION_GET_INFO_HANDLER SectionGetInfo,
+ IN EXTRACT_GUIDED_SECTION_DECODE_HANDLER SectionExtraction
+ )
+{
+ EXTRACT_SECTION_DATA Data;
+
+ Data.SectionGetInfo = SectionGetInfo;
+ Data.SectionExtraction = SectionExtraction;
+ BuildGuidDataHob (Guid, &Data, sizeof (Data));
+}
+
+PE_COFF_LOADER_PROTOCOL gPeCoffProtocol = {
+ PeCoffLoaderGetImageInfo,
+ PeCoffLoaderLoadImage,
+ PeCoffLoaderRelocateImage,
+ PeCoffLoaderImageReadFromMemory,
+ PeCoffLoaderRelocateImageForRuntime,
+ PeCoffLoaderUnloadImage
+};
+
+
+
+VOID
+EFIAPI
+BuildPeCoffLoaderHob (
+ VOID
+ )
+{
+ VOID *Ptr;
+
+ Ptr = &gPeCoffProtocol;
+ BuildGuidDataHob (&gPeCoffLoaderProtocolGuid, &Ptr, sizeof (VOID *));
+}
+
+// May want to put this into a library so you only need the PCD setings if you are using the feature?
+VOID
+BuildMemoryTypeInformationHob (
+ VOID
+ )
+{
+ EFI_MEMORY_TYPE_INFORMATION Info[10];
+
+ Info[0].Type = EfiACPIReclaimMemory;
+ Info[0].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiACPIReclaimMemory);
+ Info[1].Type = EfiACPIMemoryNVS;
+ Info[1].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiACPIMemoryNVS);
+ Info[2].Type = EfiReservedMemoryType;
+ Info[2].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiReservedMemoryType);
+ Info[3].Type = EfiRuntimeServicesData;
+ Info[3].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiRuntimeServicesData);
+ Info[4].Type = EfiRuntimeServicesCode;
+ Info[4].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiRuntimeServicesCode);
+ Info[5].Type = EfiBootServicesCode;
+ Info[5].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiBootServicesCode);
+ Info[6].Type = EfiBootServicesData;
+ Info[6].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiBootServicesData);
+ Info[7].Type = EfiLoaderCode;
+ Info[7].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiLoaderCode);
+ Info[8].Type = EfiLoaderData;
+ Info[8].NumberOfPages = PcdGet32 (PcdMemoryTypeEfiLoaderData);
+
+ // Terminator for the list
+ Info[9].Type = EfiMaxMemoryType;
+ Info[9].NumberOfPages = 0;
+
+
+ BuildGuidDataHob (&gEfiMemoryTypeInformationGuid, &Info, sizeof (Info));
+}
+
diff --git a/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c b/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c
index 9f9e9c7d4..bf4f80f4e 100644
--- a/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c
+++ b/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c
@@ -17,11 +17,11 @@
#include <Library/DebugLib.h>
#include <Library/PcdLib.h>
-//
-// Have to use build system to set the original value in case we are running
-// from FLASH and globals don't work. So if you do a GetHobList() and gHobList
-// and gHobList is NULL the PCD default values are used.
-//
+//
+// Have to use build system to set the original value in case we are running
+// from FLASH and globals don't work. So if you do a GetHobList() and gHobList
+// and gHobList is NULL the PCD default values are used.
+//
VOID *gHobList = NULL;
diff --git a/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf b/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
index 1ba976780..fea8f4368 100644
--- a/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
+++ b/EmbeddedPkg/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf
@@ -36,4 +36,4 @@
[FixedPcd.common]
gEmbeddedTokenSpaceGuid.PcdPrePiHobBase
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/EmbeddedPkg/Library/PrePiLib/FwVol.c b/EmbeddedPkg/Library/PrePiLib/FwVol.c
index 75d28a725..9e4cdd002 100644
--- a/EmbeddedPkg/Library/PrePiLib/FwVol.c
+++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c
@@ -1,842 +1,842 @@
-/** @file
- Implementation of the 6 PEI Ffs (FV) APIs in library form.
-
- This code only knows about a FV if it has a EFI_HOB_TYPE_FV entry in the HOB list
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <PrePi.h>
-#include <Library/ExtractGuidedSectionLib.h>
-
-
-#define GET_OCCUPIED_SIZE(ActualSize, Alignment) \
- (ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) & ((Alignment) - 1))
-
-
-/**
- Returns the highest bit set of the State field
-
- @param ErasePolarity Erase Polarity as defined by EFI_FVB2_ERASE_POLARITY
- in the Attributes field.
- @param FfsHeader Pointer to FFS File Header
-
-
- @retval the highest bit in the State field
-
-**/
-STATIC
-EFI_FFS_FILE_STATE
-GetFileState(
- IN UINT8 ErasePolarity,
- IN EFI_FFS_FILE_HEADER *FfsHeader
- )
-{
- EFI_FFS_FILE_STATE FileState;
- EFI_FFS_FILE_STATE HighestBit;
-
- FileState = FfsHeader->State;
-
- if (ErasePolarity != 0) {
- FileState = (EFI_FFS_FILE_STATE)~FileState;
- }
-
- HighestBit = 0x80;
- while (HighestBit != 0 && (HighestBit & FileState) == 0) {
- HighestBit >>= 1;
- }
-
- return HighestBit;
-}
-
-
-/**
- Calculates the checksum of the header of a file.
- The header is a zero byte checksum, so zero means header is good
-
- @param FfsHeader Pointer to FFS File Header
-
- @retval Checksum of the header
-
-**/
-STATIC
-UINT8
-CalculateHeaderChecksum (
- IN EFI_FFS_FILE_HEADER *FileHeader
- )
-{
- UINT8 *Ptr;
- UINTN Index;
- UINT8 Sum;
-
- Sum = 0;
- Ptr = (UINT8 *)FileHeader;
-
- for (Index = 0; Index < sizeof(EFI_FFS_FILE_HEADER) - 3; Index += 4) {
- Sum = (UINT8)(Sum + Ptr[Index]);
- Sum = (UINT8)(Sum + Ptr[Index+1]);
- Sum = (UINT8)(Sum + Ptr[Index+2]);
- Sum = (UINT8)(Sum + Ptr[Index+3]);
- }
-
- for (; Index < sizeof(EFI_FFS_FILE_HEADER); Index++) {
- Sum = (UINT8)(Sum + Ptr[Index]);
- }
-
- //
- // State field (since this indicates the different state of file).
- //
- Sum = (UINT8)(Sum - FileHeader->State);
- //
- // Checksum field of the file is not part of the header checksum.
- //
- Sum = (UINT8)(Sum - FileHeader->IntegrityCheck.Checksum.File);
-
- return Sum;
-}
-
-
-/**
- Given a FileHandle return the VolumeHandle
-
- @param FileHandle File handle to look up
- @param VolumeHandle Match for FileHandle
-
- @retval TRUE VolumeHandle is valid
-
-**/
-STATIC
-BOOLEAN
-EFIAPI
-FileHandleToVolume (
- IN EFI_PEI_FILE_HANDLE FileHandle,
- OUT EFI_PEI_FV_HANDLE *VolumeHandle
- )
-{
- EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
- EFI_PEI_HOB_POINTERS Hob;
-
- Hob.Raw = GetHobList ();
- if (Hob.Raw == NULL) {
- return FALSE;
- }
-
- do {
- Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, Hob.Raw);
- if (Hob.Raw != NULL) {
- FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(Hob.FirmwareVolume->BaseAddress);
- if (((UINT64) (UINTN) FileHandle > (UINT64) (UINTN) FwVolHeader ) && \
- ((UINT64) (UINTN) FileHandle <= ((UINT64) (UINTN) FwVolHeader + FwVolHeader->FvLength - 1))) {
- *VolumeHandle = (EFI_PEI_FV_HANDLE)FwVolHeader;
- return TRUE;
- }
-
- Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, GET_NEXT_HOB (Hob));
- }
- } while (Hob.Raw != NULL);
-
- return FALSE;
-}
-
-
-
-/**
- Given the input file pointer, search for the next matching file in the
- FFS volume as defined by SearchType. The search starts from FileHeader inside
- the Firmware Volume defined by FwVolHeader.
-
- @param FileHandle File handle to look up
- @param VolumeHandle Match for FileHandle
-
-
-**/
-EFI_STATUS
-FindFileEx (
- IN CONST EFI_PEI_FV_HANDLE FvHandle,
- IN CONST EFI_GUID *FileName, OPTIONAL
- IN EFI_FV_FILETYPE SearchType,
- IN OUT EFI_PEI_FILE_HANDLE *FileHandle
- )
-{
- EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
- EFI_FFS_FILE_HEADER **FileHeader;
- EFI_FFS_FILE_HEADER *FfsFileHeader;
- EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExHeaderInfo;
- UINT32 FileLength;
- UINT32 FileOccupiedSize;
- UINT32 FileOffset;
- UINT64 FvLength;
- UINT8 ErasePolarity;
- UINT8 FileState;
-
- FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)FvHandle;
- FileHeader = (EFI_FFS_FILE_HEADER **)FileHandle;
-
- FvLength = FwVolHeader->FvLength;
- if (FwVolHeader->Attributes & EFI_FVB2_ERASE_POLARITY) {
- ErasePolarity = 1;
- } else {
- ErasePolarity = 0;
- }
-
- //
- // If FileHeader is not specified (NULL) or FileName is not NULL,
- // start with the first file in the firmware volume. Otherwise,
- // start from the FileHeader.
- //
- if ((*FileHeader == NULL) || (FileName != NULL)) {
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FwVolHeader + FwVolHeader->HeaderLength);
- if (FwVolHeader->ExtHeaderOffset != 0) {
- FwVolExHeaderInfo = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(((UINT8 *)FwVolHeader) + FwVolHeader->ExtHeaderOffset);
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)(((UINT8 *)FwVolExHeaderInfo) + FwVolExHeaderInfo->ExtHeaderSize);
- }
- } else {
- //
- // Length is 24 bits wide so mask upper 8 bits
- // FileLength is adjusted to FileOccupiedSize as it is 8 byte aligned.
- //
- FileLength = *(UINT32 *)(*FileHeader)->Size & 0x00FFFFFF;
- FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8);
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)*FileHeader + FileOccupiedSize);
- }
-
- FileOffset = (UINT32) ((UINT8 *)FfsFileHeader - (UINT8 *)FwVolHeader);
- ASSERT (FileOffset <= 0xFFFFFFFF);
-
- while (FileOffset < (FvLength - sizeof (EFI_FFS_FILE_HEADER))) {
- //
- // Get FileState which is the highest bit of the State
- //
- FileState = GetFileState (ErasePolarity, FfsFileHeader);
-
- switch (FileState) {
-
- case EFI_FILE_HEADER_INVALID:
- FileOffset += sizeof(EFI_FFS_FILE_HEADER);
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + sizeof(EFI_FFS_FILE_HEADER));
- break;
-
- case EFI_FILE_DATA_VALID:
- case EFI_FILE_MARKED_FOR_UPDATE:
- if (CalculateHeaderChecksum (FfsFileHeader) != 0) {
- ASSERT (FALSE);
- *FileHeader = NULL;
- return EFI_NOT_FOUND;
- }
-
- FileLength = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
- FileOccupiedSize = GET_OCCUPIED_SIZE(FileLength, 8);
-
- if (FileName != NULL) {
- if (CompareGuid (&FfsFileHeader->Name, (EFI_GUID*)FileName)) {
- *FileHeader = FfsFileHeader;
- return EFI_SUCCESS;
- }
- } else if (((SearchType == FfsFileHeader->Type) || (SearchType == EFI_FV_FILETYPE_ALL)) &&
- (FfsFileHeader->Type != EFI_FV_FILETYPE_FFS_PAD)) {
- *FileHeader = FfsFileHeader;
- return EFI_SUCCESS;
- }
-
- FileOffset += FileOccupiedSize;
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize);
- break;
-
- case EFI_FILE_DELETED:
- FileLength = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
- FileOccupiedSize = GET_OCCUPIED_SIZE(FileLength, 8);
- FileOffset += FileOccupiedSize;
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize);
- break;
-
- default:
- *FileHeader = NULL;
- return EFI_NOT_FOUND;
- }
- }
-
-
- *FileHeader = NULL;
- return EFI_NOT_FOUND;
-}
-
-
-/**
- Go through the file to search SectionType section,
- when meeting an encapsuled section.
-
- @param SectionType - Filter to find only section of this type.
- @param Section - From where to search.
- @param SectionSize - The file size to search.
- @param OutputBuffer - Pointer to the section to search.
-
- @retval EFI_SUCCESS
-**/
-EFI_STATUS
-FfsProcessSection (
- IN EFI_SECTION_TYPE SectionType,
- IN EFI_COMMON_SECTION_HEADER *Section,
- IN UINTN SectionSize,
- OUT VOID **OutputBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 SectionLength;
- UINT32 ParsedLength;
- EFI_COMPRESSION_SECTION *CompressionSection;
- UINTN DstBufferSize;
- VOID *ScratchBuffer;
- UINT32 ScratchBufferSize;
- VOID *DstBuffer;
- UINT16 SectionAttribute;
- UINT32 AuthenticationStatus;
-
-
- *OutputBuffer = NULL;
- ParsedLength = 0;
- Status = EFI_NOT_FOUND;
- while (ParsedLength < SectionSize) {
- if (Section->Type == SectionType) {
- *OutputBuffer = (VOID *)(Section + 1);
-
- return EFI_SUCCESS;
- } else if ((Section->Type == EFI_SECTION_COMPRESSION) || (Section->Type == EFI_SECTION_GUID_DEFINED)) {
-
- if (Section->Type == EFI_SECTION_COMPRESSION) {
- CompressionSection = (EFI_COMPRESSION_SECTION *) Section;
- SectionLength = *(UINT32 *)Section->Size & 0x00FFFFFF;
-
- if (CompressionSection->CompressionType != EFI_STANDARD_COMPRESSION) {
- return EFI_UNSUPPORTED;
- }
-
- Status = UefiDecompressGetInfo (
- (UINT8 *) ((EFI_COMPRESSION_SECTION *) Section + 1),
- (UINT32) SectionLength - sizeof (EFI_COMPRESSION_SECTION),
- (UINT32 *) &DstBufferSize,
- &ScratchBufferSize
- );
- } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
- Status = ExtractGuidedSectionGetInfo (
- Section,
- (UINT32 *) &DstBufferSize,
- &ScratchBufferSize,
- &SectionAttribute
- );
- }
-
- if (EFI_ERROR (Status)) {
- //
- // GetInfo failed
- //
- DEBUG ((EFI_D_ERROR, "Decompress GetInfo Failed - %r\n", Status));
- return EFI_NOT_FOUND;
- }
- //
- // Allocate scratch buffer
- //
- ScratchBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (ScratchBufferSize));
- if (ScratchBuffer == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
- //
- // Allocate destination buffer, extra one page for adjustment
- //
- DstBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize) + 1);
- if (DstBuffer == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
- //
- // DstBuffer still is one section. Adjust DstBuffer offset, skip EFI section header
- // to make section data at page alignment.
- //
- DstBuffer = (UINT8 *)DstBuffer + EFI_PAGE_SIZE - sizeof (EFI_COMMON_SECTION_HEADER);
- //
- // Call decompress function
- //
- if (Section->Type == EFI_SECTION_COMPRESSION) {
- Status = UefiDecompress (
- (CHAR8 *) ((EFI_COMPRESSION_SECTION *) Section + 1),
- DstBuffer,
- ScratchBuffer
- );
- } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
- Status = ExtractGuidedSectionDecode (
- Section,
- &DstBuffer,
- ScratchBuffer,
- &AuthenticationStatus
- );
- }
-
- if (EFI_ERROR (Status)) {
- //
- // Decompress failed
- //
- DEBUG ((EFI_D_ERROR, "Decompress Failed - %r\n", Status));
- return EFI_NOT_FOUND;
- } else {
- return FfsProcessSection (
- SectionType,
- DstBuffer,
- DstBufferSize,
- OutputBuffer
- );
- }
- }
-
- //
- // Size is 24 bits wide so mask upper 8 bits.
- // SectionLength is adjusted it is 4 byte aligned.
- // Go to the next section
- //
- SectionLength = *(UINT32 *)Section->Size & 0x00FFFFFF;
- SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4);
- ASSERT (SectionLength != 0);
- ParsedLength += SectionLength;
- Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength);
- }
-
- return EFI_NOT_FOUND;
-}
-
-
-
-/**
- This service enables discovery sections of a given type within a valid FFS file.
-
- @param SearchType The value of the section type to find.
- @param FfsFileHeader A pointer to the file header that contains the set of sections to
- be searched.
- @param SectionData A pointer to the discovered section, if successful.
-
- @retval EFI_SUCCESS The section was found.
- @retval EFI_NOT_FOUND The section was not found.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindSectionData (
- IN EFI_SECTION_TYPE SectionType,
- IN EFI_PEI_FILE_HANDLE FileHandle,
- OUT VOID **SectionData
- )
-{
- EFI_FFS_FILE_HEADER *FfsFileHeader;
- UINT32 FileSize;
- EFI_COMMON_SECTION_HEADER *Section;
-
- FfsFileHeader = (EFI_FFS_FILE_HEADER *)(FileHandle);
-
- //
- // Size is 24 bits wide so mask upper 8 bits.
- // Does not include FfsFileHeader header size
- // FileSize is adjusted to FileOccupiedSize as it is 8 byte aligned.
- //
- Section = (EFI_COMMON_SECTION_HEADER *)(FfsFileHeader + 1);
- FileSize = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
- FileSize -= sizeof (EFI_FFS_FILE_HEADER);
-
- return FfsProcessSection (
- SectionType,
- Section,
- FileSize,
- SectionData
- );
-}
-
-
-
-
-
-
-/**
- This service enables discovery of additional firmware files.
-
- @param SearchType A filter to find files only of this type.
- @param FwVolHeader Pointer to the firmware volume header of the volume to search.
- This parameter must point to a valid FFS volume.
- @param FileHeader Pointer to the current file from which to begin searching.
-
- @retval EFI_SUCCESS The file was found.
- @retval EFI_NOT_FOUND The file was not found.
- @retval EFI_NOT_FOUND The header checksum was not zero.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindNextFile (
- IN UINT8 SearchType,
- IN EFI_PEI_FV_HANDLE VolumeHandle,
- IN OUT EFI_PEI_FILE_HANDLE *FileHandle
- )
-{
- return FindFileEx (VolumeHandle, NULL, SearchType, FileHandle);
-}
-
-
-/**
- This service enables discovery of additional firmware volumes.
-
- @param Instance This instance of the firmware volume to find. The value 0 is the
- Boot Firmware Volume (BFV).
- @param FwVolHeader Pointer to the firmware volume header of the volume to return.
-
- @retval EFI_SUCCESS The volume was found.
- @retval EFI_NOT_FOUND The volume was not found.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindNextVolume (
- IN UINTN Instance,
- IN OUT EFI_PEI_FV_HANDLE *VolumeHandle
- )
-{
- EFI_PEI_HOB_POINTERS Hob;
-
-
- Hob.Raw = GetHobList ();
- if (Hob.Raw == NULL) {
- return EFI_NOT_FOUND;
- }
-
- do {
- Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, Hob.Raw);
- if (Hob.Raw != NULL) {
- if (Instance-- == 0) {
- *VolumeHandle = (EFI_PEI_FV_HANDLE)(UINTN)(Hob.FirmwareVolume->BaseAddress);
- return EFI_SUCCESS;
- }
-
- Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, GET_NEXT_HOB (Hob));
- }
- } while (Hob.Raw != NULL);
-
- return EFI_NOT_FOUND;
-
-}
-
-
-/**
- Find a file in the volume by name
-
- @param FileName A pointer to the name of the file to
- find within the firmware volume.
-
- @param VolumeHandle The firmware volume to search FileHandle
- Upon exit, points to the found file's
- handle or NULL if it could not be found.
-
- @retval EFI_SUCCESS File was found.
-
- @retval EFI_NOT_FOUND File was not found.
-
- @retval EFI_INVALID_PARAMETER VolumeHandle or FileHandle or
- FileName was NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsFindFileByName (
- IN CONST EFI_GUID *FileName,
- IN EFI_PEI_FV_HANDLE VolumeHandle,
- OUT EFI_PEI_FILE_HANDLE *FileHandle
- )
-{
- EFI_STATUS Status;
- if ((VolumeHandle == NULL) || (FileName == NULL) || (FileHandle == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
- Status = FindFileEx (VolumeHandle, FileName, 0, FileHandle);
- if (Status == EFI_NOT_FOUND) {
- *FileHandle = NULL;
- }
- return Status;
-}
-
-
-
-
-/**
- Get information about the file by name.
-
- @param FileHandle Handle of the file.
-
- @param FileInfo Upon exit, points to the file's
- information.
-
- @retval EFI_SUCCESS File information returned.
-
- @retval EFI_INVALID_PARAMETER If FileHandle does not
- represent a valid file.
-
- @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsGetFileInfo (
- IN EFI_PEI_FILE_HANDLE FileHandle,
- OUT EFI_FV_FILE_INFO *FileInfo
- )
-{
- UINT8 FileState;
- UINT8 ErasePolarity;
- EFI_FFS_FILE_HEADER *FileHeader;
- EFI_PEI_FV_HANDLE VolumeHandle;
-
- if ((FileHandle == NULL) || (FileInfo == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
-
- VolumeHandle = 0;
- //
- // Retrieve the FirmwareVolume which the file resides in.
- //
- if (!FileHandleToVolume(FileHandle, &VolumeHandle)) {
- return EFI_INVALID_PARAMETER;
- }
-
- if (((EFI_FIRMWARE_VOLUME_HEADER*)VolumeHandle)->Attributes & EFI_FVB2_ERASE_POLARITY) {
- ErasePolarity = 1;
- } else {
- ErasePolarity = 0;
- }
-
- //
- // Get FileState which is the highest bit of the State
- //
- FileState = GetFileState (ErasePolarity, (EFI_FFS_FILE_HEADER*)FileHandle);
-
- switch (FileState) {
- case EFI_FILE_DATA_VALID:
- case EFI_FILE_MARKED_FOR_UPDATE:
- break;
- default:
- return EFI_INVALID_PARAMETER;
- }
-
- FileHeader = (EFI_FFS_FILE_HEADER *)FileHandle;
- CopyMem (&FileInfo->FileName, &FileHeader->Name, sizeof(EFI_GUID));
- FileInfo->FileType = FileHeader->Type;
- FileInfo->FileAttributes = FileHeader->Attributes;
- FileInfo->BufferSize = ((*(UINT32 *)FileHeader->Size) & 0x00FFFFFF) - sizeof (EFI_FFS_FILE_HEADER);
- FileInfo->Buffer = (FileHeader + 1);
- return EFI_SUCCESS;
-}
-
-
-/**
- Get Information about the volume by name
-
- @param VolumeHandle Handle of the volume.
-
- @param VolumeInfo Upon exit, points to the volume's
- information.
-
- @retval EFI_SUCCESS File information returned.
-
- @retval EFI_INVALID_PARAMETER If FileHandle does not
- represent a valid file.
-
- @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsGetVolumeInfo (
- IN EFI_PEI_FV_HANDLE VolumeHandle,
- OUT EFI_FV_INFO *VolumeInfo
- )
-{
- EFI_FIRMWARE_VOLUME_HEADER FwVolHeader;
- EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExHeaderInfo;
-
- if (VolumeInfo == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- //
- // VolumeHandle may not align at 8 byte,
- // but FvLength is UINT64 type, which requires FvHeader align at least 8 byte.
- // So, Copy FvHeader into the local FvHeader structure.
- //
- CopyMem (&FwVolHeader, VolumeHandle, sizeof (EFI_FIRMWARE_VOLUME_HEADER));
- //
- // Check Fv Image Signature
- //
- if (FwVolHeader.Signature != EFI_FVH_SIGNATURE) {
- return EFI_INVALID_PARAMETER;
- }
- VolumeInfo->FvAttributes = FwVolHeader.Attributes;
- VolumeInfo->FvStart = (VOID *) VolumeHandle;
- VolumeInfo->FvSize = FwVolHeader.FvLength;
- CopyMem (&VolumeInfo->FvFormat, &FwVolHeader.FileSystemGuid, sizeof(EFI_GUID));
-
- if (FwVolHeader.ExtHeaderOffset != 0) {
- FwVolExHeaderInfo = (EFI_FIRMWARE_VOLUME_EXT_HEADER*)(((UINT8 *)VolumeHandle) + FwVolHeader.ExtHeaderOffset);
- CopyMem (&VolumeInfo->FvName, &FwVolExHeaderInfo->FvName, sizeof(EFI_GUID));
- }
- return EFI_SUCCESS;
-}
-
-
-
-/**
- Search through every FV until you find a file of type FileType
-
- @param FileType File handle of a Fv type file.
- @param Volumehandle On succes Volume Handle of the match
- @param FileHandle On success File Handle of the match
-
- @retval EFI_NOT_FOUND FV image can't be found.
- @retval EFI_SUCCESS Successfully found FileType
-
-**/
-EFI_STATUS
-EFIAPI
-FfsAnyFvFindFirstFile (
- IN EFI_FV_FILETYPE FileType,
- OUT EFI_PEI_FV_HANDLE *VolumeHandle,
- OUT EFI_PEI_FILE_HANDLE *FileHandle
- )
-{
- EFI_STATUS Status;
- UINTN Instance;
-
- //
- // Search every FV for the DXE Core
- //
- Instance = 0;
- *FileHandle = NULL;
-
- while (1)
- {
- Status = FfsFindNextVolume (Instance++, VolumeHandle);
- if (EFI_ERROR (Status))
- {
- break;
- }
-
- Status = FfsFindNextFile (FileType, *VolumeHandle, FileHandle);
- if (!EFI_ERROR (Status))
- {
- break;
- }
- }
-
- return Status;
-}
-
-
-
-/**
- Get Fv image from the FV type file, then add FV & FV2 Hob.
-
- @param FileHandle File handle of a Fv type file.
-
-
- @retval EFI_NOT_FOUND FV image can't be found.
- @retval EFI_SUCCESS Successfully to process it.
-
-**/
-EFI_STATUS
-EFIAPI
-FfsProcessFvFile (
- IN EFI_PEI_FILE_HANDLE FvFileHandle
- )
-{
- EFI_STATUS Status;
- EFI_PEI_FV_HANDLE FvImageHandle;
- EFI_FV_INFO FvImageInfo;
- UINT32 FvAlignment;
- VOID *FvBuffer;
- EFI_PEI_HOB_POINTERS HobFv2;
-
- FvBuffer = NULL;
-
-
- //
- // Check if this EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE file has already
- // been extracted.
- //
- HobFv2.Raw = GetHobList ();
- while ((HobFv2.Raw = GetNextHob (EFI_HOB_TYPE_FV2, HobFv2.Raw)) != NULL) {
- if (CompareGuid (&(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name), &HobFv2.FirmwareVolume2->FileName)) {
- //
- // this FILE has been dispatched, it will not be dispatched again.
- //
- return EFI_SUCCESS;
- }
- HobFv2.Raw = GET_NEXT_HOB (HobFv2);
- }
-
- //
- // Find FvImage in FvFile
- //
- Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, FvFileHandle, (VOID **)&FvImageHandle);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- //
- // Collect FvImage Info.
- //
- ZeroMem (&FvImageInfo, sizeof (FvImageInfo));
- Status = FfsGetVolumeInfo (FvImageHandle, &FvImageInfo);
- ASSERT_EFI_ERROR (Status);
-
- //
- // FvAlignment must be more than 8 bytes required by FvHeader structure.
- //
- FvAlignment = 1 << ((FvImageInfo.FvAttributes & EFI_FVB2_ALIGNMENT) >> 16);
- if (FvAlignment < 8) {
- FvAlignment = 8;
- }
-
- //
- // Check FvImage
- //
- if ((UINTN) FvImageInfo.FvStart % FvAlignment != 0) {
- FvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32) FvImageInfo.FvSize), FvAlignment);
- if (FvBuffer == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
- CopyMem (FvBuffer, FvImageInfo.FvStart, (UINTN) FvImageInfo.FvSize);
- //
- // Update FvImageInfo after reload FvImage to new aligned memory
- //
- FfsGetVolumeInfo ((EFI_PEI_FV_HANDLE) FvBuffer, &FvImageInfo);
- }
-
-
- //
- // Inform HOB consumer phase, i.e. DXE core, the existance of this FV
- //
- BuildFvHob ((EFI_PHYSICAL_ADDRESS) (UINTN) FvImageInfo.FvStart, FvImageInfo.FvSize);
-
- //
- // Makes the encapsulated volume show up in DXE phase to skip processing of
- // encapsulated file again.
- //
- BuildFv2Hob (
- (EFI_PHYSICAL_ADDRESS) (UINTN) FvImageInfo.FvStart,
- FvImageInfo.FvSize,
- &FvImageInfo.FvName,
- &(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name)
- );
-
- return EFI_SUCCESS;
-}
-
-
+/** @file
+ Implementation of the 6 PEI Ffs (FV) APIs in library form.
+
+ This code only knows about a FV if it has a EFI_HOB_TYPE_FV entry in the HOB list
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PrePi.h>
+#include <Library/ExtractGuidedSectionLib.h>
+
+
+#define GET_OCCUPIED_SIZE(ActualSize, Alignment) \
+ (ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) & ((Alignment) - 1))
+
+
+/**
+ Returns the highest bit set of the State field
+
+ @param ErasePolarity Erase Polarity as defined by EFI_FVB2_ERASE_POLARITY
+ in the Attributes field.
+ @param FfsHeader Pointer to FFS File Header
+
+
+ @retval the highest bit in the State field
+
+**/
+STATIC
+EFI_FFS_FILE_STATE
+GetFileState(
+ IN UINT8 ErasePolarity,
+ IN EFI_FFS_FILE_HEADER *FfsHeader
+ )
+{
+ EFI_FFS_FILE_STATE FileState;
+ EFI_FFS_FILE_STATE HighestBit;
+
+ FileState = FfsHeader->State;
+
+ if (ErasePolarity != 0) {
+ FileState = (EFI_FFS_FILE_STATE)~FileState;
+ }
+
+ HighestBit = 0x80;
+ while (HighestBit != 0 && (HighestBit & FileState) == 0) {
+ HighestBit >>= 1;
+ }
+
+ return HighestBit;
+}
+
+
+/**
+ Calculates the checksum of the header of a file.
+ The header is a zero byte checksum, so zero means header is good
+
+ @param FfsHeader Pointer to FFS File Header
+
+ @retval Checksum of the header
+
+**/
+STATIC
+UINT8
+CalculateHeaderChecksum (
+ IN EFI_FFS_FILE_HEADER *FileHeader
+ )
+{
+ UINT8 *Ptr;
+ UINTN Index;
+ UINT8 Sum;
+
+ Sum = 0;
+ Ptr = (UINT8 *)FileHeader;
+
+ for (Index = 0; Index < sizeof(EFI_FFS_FILE_HEADER) - 3; Index += 4) {
+ Sum = (UINT8)(Sum + Ptr[Index]);
+ Sum = (UINT8)(Sum + Ptr[Index+1]);
+ Sum = (UINT8)(Sum + Ptr[Index+2]);
+ Sum = (UINT8)(Sum + Ptr[Index+3]);
+ }
+
+ for (; Index < sizeof(EFI_FFS_FILE_HEADER); Index++) {
+ Sum = (UINT8)(Sum + Ptr[Index]);
+ }
+
+ //
+ // State field (since this indicates the different state of file).
+ //
+ Sum = (UINT8)(Sum - FileHeader->State);
+ //
+ // Checksum field of the file is not part of the header checksum.
+ //
+ Sum = (UINT8)(Sum - FileHeader->IntegrityCheck.Checksum.File);
+
+ return Sum;
+}
+
+
+/**
+ Given a FileHandle return the VolumeHandle
+
+ @param FileHandle File handle to look up
+ @param VolumeHandle Match for FileHandle
+
+ @retval TRUE VolumeHandle is valid
+
+**/
+STATIC
+BOOLEAN
+EFIAPI
+FileHandleToVolume (
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ OUT EFI_PEI_FV_HANDLE *VolumeHandle
+ )
+{
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_PEI_HOB_POINTERS Hob;
+
+ Hob.Raw = GetHobList ();
+ if (Hob.Raw == NULL) {
+ return FALSE;
+ }
+
+ do {
+ Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, Hob.Raw);
+ if (Hob.Raw != NULL) {
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(Hob.FirmwareVolume->BaseAddress);
+ if (((UINT64) (UINTN) FileHandle > (UINT64) (UINTN) FwVolHeader ) && \
+ ((UINT64) (UINTN) FileHandle <= ((UINT64) (UINTN) FwVolHeader + FwVolHeader->FvLength - 1))) {
+ *VolumeHandle = (EFI_PEI_FV_HANDLE)FwVolHeader;
+ return TRUE;
+ }
+
+ Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, GET_NEXT_HOB (Hob));
+ }
+ } while (Hob.Raw != NULL);
+
+ return FALSE;
+}
+
+
+
+/**
+ Given the input file pointer, search for the next matching file in the
+ FFS volume as defined by SearchType. The search starts from FileHeader inside
+ the Firmware Volume defined by FwVolHeader.
+
+ @param FileHandle File handle to look up
+ @param VolumeHandle Match for FileHandle
+
+
+**/
+EFI_STATUS
+FindFileEx (
+ IN CONST EFI_PEI_FV_HANDLE FvHandle,
+ IN CONST EFI_GUID *FileName, OPTIONAL
+ IN EFI_FV_FILETYPE SearchType,
+ IN OUT EFI_PEI_FILE_HANDLE *FileHandle
+ )
+{
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
+ EFI_FFS_FILE_HEADER **FileHeader;
+ EFI_FFS_FILE_HEADER *FfsFileHeader;
+ EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExHeaderInfo;
+ UINT32 FileLength;
+ UINT32 FileOccupiedSize;
+ UINT32 FileOffset;
+ UINT64 FvLength;
+ UINT8 ErasePolarity;
+ UINT8 FileState;
+
+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)FvHandle;
+ FileHeader = (EFI_FFS_FILE_HEADER **)FileHandle;
+
+ FvLength = FwVolHeader->FvLength;
+ if (FwVolHeader->Attributes & EFI_FVB2_ERASE_POLARITY) {
+ ErasePolarity = 1;
+ } else {
+ ErasePolarity = 0;
+ }
+
+ //
+ // If FileHeader is not specified (NULL) or FileName is not NULL,
+ // start with the first file in the firmware volume. Otherwise,
+ // start from the FileHeader.
+ //
+ if ((*FileHeader == NULL) || (FileName != NULL)) {
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FwVolHeader + FwVolHeader->HeaderLength);
+ if (FwVolHeader->ExtHeaderOffset != 0) {
+ FwVolExHeaderInfo = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(((UINT8 *)FwVolHeader) + FwVolHeader->ExtHeaderOffset);
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)(((UINT8 *)FwVolExHeaderInfo) + FwVolExHeaderInfo->ExtHeaderSize);
+ }
+ } else {
+ //
+ // Length is 24 bits wide so mask upper 8 bits
+ // FileLength is adjusted to FileOccupiedSize as it is 8 byte aligned.
+ //
+ FileLength = *(UINT32 *)(*FileHeader)->Size & 0x00FFFFFF;
+ FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8);
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)*FileHeader + FileOccupiedSize);
+ }
+
+ FileOffset = (UINT32) ((UINT8 *)FfsFileHeader - (UINT8 *)FwVolHeader);
+ ASSERT (FileOffset <= 0xFFFFFFFF);
+
+ while (FileOffset < (FvLength - sizeof (EFI_FFS_FILE_HEADER))) {
+ //
+ // Get FileState which is the highest bit of the State
+ //
+ FileState = GetFileState (ErasePolarity, FfsFileHeader);
+
+ switch (FileState) {
+
+ case EFI_FILE_HEADER_INVALID:
+ FileOffset += sizeof(EFI_FFS_FILE_HEADER);
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + sizeof(EFI_FFS_FILE_HEADER));
+ break;
+
+ case EFI_FILE_DATA_VALID:
+ case EFI_FILE_MARKED_FOR_UPDATE:
+ if (CalculateHeaderChecksum (FfsFileHeader) != 0) {
+ ASSERT (FALSE);
+ *FileHeader = NULL;
+ return EFI_NOT_FOUND;
+ }
+
+ FileLength = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
+ FileOccupiedSize = GET_OCCUPIED_SIZE(FileLength, 8);
+
+ if (FileName != NULL) {
+ if (CompareGuid (&FfsFileHeader->Name, (EFI_GUID*)FileName)) {
+ *FileHeader = FfsFileHeader;
+ return EFI_SUCCESS;
+ }
+ } else if (((SearchType == FfsFileHeader->Type) || (SearchType == EFI_FV_FILETYPE_ALL)) &&
+ (FfsFileHeader->Type != EFI_FV_FILETYPE_FFS_PAD)) {
+ *FileHeader = FfsFileHeader;
+ return EFI_SUCCESS;
+ }
+
+ FileOffset += FileOccupiedSize;
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize);
+ break;
+
+ case EFI_FILE_DELETED:
+ FileLength = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
+ FileOccupiedSize = GET_OCCUPIED_SIZE(FileLength, 8);
+ FileOffset += FileOccupiedSize;
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize);
+ break;
+
+ default:
+ *FileHeader = NULL;
+ return EFI_NOT_FOUND;
+ }
+ }
+
+
+ *FileHeader = NULL;
+ return EFI_NOT_FOUND;
+}
+
+
+/**
+ Go through the file to search SectionType section,
+ when meeting an encapsuled section.
+
+ @param SectionType - Filter to find only section of this type.
+ @param Section - From where to search.
+ @param SectionSize - The file size to search.
+ @param OutputBuffer - Pointer to the section to search.
+
+ @retval EFI_SUCCESS
+**/
+EFI_STATUS
+FfsProcessSection (
+ IN EFI_SECTION_TYPE SectionType,
+ IN EFI_COMMON_SECTION_HEADER *Section,
+ IN UINTN SectionSize,
+ OUT VOID **OutputBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 SectionLength;
+ UINT32 ParsedLength;
+ EFI_COMPRESSION_SECTION *CompressionSection;
+ UINTN DstBufferSize;
+ VOID *ScratchBuffer;
+ UINT32 ScratchBufferSize;
+ VOID *DstBuffer;
+ UINT16 SectionAttribute;
+ UINT32 AuthenticationStatus;
+
+
+ *OutputBuffer = NULL;
+ ParsedLength = 0;
+ Status = EFI_NOT_FOUND;
+ while (ParsedLength < SectionSize) {
+ if (Section->Type == SectionType) {
+ *OutputBuffer = (VOID *)(Section + 1);
+
+ return EFI_SUCCESS;
+ } else if ((Section->Type == EFI_SECTION_COMPRESSION) || (Section->Type == EFI_SECTION_GUID_DEFINED)) {
+
+ if (Section->Type == EFI_SECTION_COMPRESSION) {
+ CompressionSection = (EFI_COMPRESSION_SECTION *) Section;
+ SectionLength = *(UINT32 *)Section->Size & 0x00FFFFFF;
+
+ if (CompressionSection->CompressionType != EFI_STANDARD_COMPRESSION) {
+ return EFI_UNSUPPORTED;
+ }
+
+ Status = UefiDecompressGetInfo (
+ (UINT8 *) ((EFI_COMPRESSION_SECTION *) Section + 1),
+ (UINT32) SectionLength - sizeof (EFI_COMPRESSION_SECTION),
+ (UINT32 *) &DstBufferSize,
+ &ScratchBufferSize
+ );
+ } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
+ Status = ExtractGuidedSectionGetInfo (
+ Section,
+ (UINT32 *) &DstBufferSize,
+ &ScratchBufferSize,
+ &SectionAttribute
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ //
+ // GetInfo failed
+ //
+ DEBUG ((EFI_D_ERROR, "Decompress GetInfo Failed - %r\n", Status));
+ return EFI_NOT_FOUND;
+ }
+ //
+ // Allocate scratch buffer
+ //
+ ScratchBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (ScratchBufferSize));
+ if (ScratchBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // Allocate destination buffer, extra one page for adjustment
+ //
+ DstBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize) + 1);
+ if (DstBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ //
+ // DstBuffer still is one section. Adjust DstBuffer offset, skip EFI section header
+ // to make section data at page alignment.
+ //
+ DstBuffer = (UINT8 *)DstBuffer + EFI_PAGE_SIZE - sizeof (EFI_COMMON_SECTION_HEADER);
+ //
+ // Call decompress function
+ //
+ if (Section->Type == EFI_SECTION_COMPRESSION) {
+ Status = UefiDecompress (
+ (CHAR8 *) ((EFI_COMPRESSION_SECTION *) Section + 1),
+ DstBuffer,
+ ScratchBuffer
+ );
+ } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
+ Status = ExtractGuidedSectionDecode (
+ Section,
+ &DstBuffer,
+ ScratchBuffer,
+ &AuthenticationStatus
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ //
+ // Decompress failed
+ //
+ DEBUG ((EFI_D_ERROR, "Decompress Failed - %r\n", Status));
+ return EFI_NOT_FOUND;
+ } else {
+ return FfsProcessSection (
+ SectionType,
+ DstBuffer,
+ DstBufferSize,
+ OutputBuffer
+ );
+ }
+ }
+
+ //
+ // Size is 24 bits wide so mask upper 8 bits.
+ // SectionLength is adjusted it is 4 byte aligned.
+ // Go to the next section
+ //
+ SectionLength = *(UINT32 *)Section->Size & 0x00FFFFFF;
+ SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4);
+ ASSERT (SectionLength != 0);
+ ParsedLength += SectionLength;
+ Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength);
+ }
+
+ return EFI_NOT_FOUND;
+}
+
+
+
+/**
+ This service enables discovery sections of a given type within a valid FFS file.
+
+ @param SearchType The value of the section type to find.
+ @param FfsFileHeader A pointer to the file header that contains the set of sections to
+ be searched.
+ @param SectionData A pointer to the discovered section, if successful.
+
+ @retval EFI_SUCCESS The section was found.
+ @retval EFI_NOT_FOUND The section was not found.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindSectionData (
+ IN EFI_SECTION_TYPE SectionType,
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ OUT VOID **SectionData
+ )
+{
+ EFI_FFS_FILE_HEADER *FfsFileHeader;
+ UINT32 FileSize;
+ EFI_COMMON_SECTION_HEADER *Section;
+
+ FfsFileHeader = (EFI_FFS_FILE_HEADER *)(FileHandle);
+
+ //
+ // Size is 24 bits wide so mask upper 8 bits.
+ // Does not include FfsFileHeader header size
+ // FileSize is adjusted to FileOccupiedSize as it is 8 byte aligned.
+ //
+ Section = (EFI_COMMON_SECTION_HEADER *)(FfsFileHeader + 1);
+ FileSize = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
+ FileSize -= sizeof (EFI_FFS_FILE_HEADER);
+
+ return FfsProcessSection (
+ SectionType,
+ Section,
+ FileSize,
+ SectionData
+ );
+}
+
+
+
+
+
+
+/**
+ This service enables discovery of additional firmware files.
+
+ @param SearchType A filter to find files only of this type.
+ @param FwVolHeader Pointer to the firmware volume header of the volume to search.
+ This parameter must point to a valid FFS volume.
+ @param FileHeader Pointer to the current file from which to begin searching.
+
+ @retval EFI_SUCCESS The file was found.
+ @retval EFI_NOT_FOUND The file was not found.
+ @retval EFI_NOT_FOUND The header checksum was not zero.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindNextFile (
+ IN UINT8 SearchType,
+ IN EFI_PEI_FV_HANDLE VolumeHandle,
+ IN OUT EFI_PEI_FILE_HANDLE *FileHandle
+ )
+{
+ return FindFileEx (VolumeHandle, NULL, SearchType, FileHandle);
+}
+
+
+/**
+ This service enables discovery of additional firmware volumes.
+
+ @param Instance This instance of the firmware volume to find. The value 0 is the
+ Boot Firmware Volume (BFV).
+ @param FwVolHeader Pointer to the firmware volume header of the volume to return.
+
+ @retval EFI_SUCCESS The volume was found.
+ @retval EFI_NOT_FOUND The volume was not found.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindNextVolume (
+ IN UINTN Instance,
+ IN OUT EFI_PEI_FV_HANDLE *VolumeHandle
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+
+
+ Hob.Raw = GetHobList ();
+ if (Hob.Raw == NULL) {
+ return EFI_NOT_FOUND;
+ }
+
+ do {
+ Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, Hob.Raw);
+ if (Hob.Raw != NULL) {
+ if (Instance-- == 0) {
+ *VolumeHandle = (EFI_PEI_FV_HANDLE)(UINTN)(Hob.FirmwareVolume->BaseAddress);
+ return EFI_SUCCESS;
+ }
+
+ Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV, GET_NEXT_HOB (Hob));
+ }
+ } while (Hob.Raw != NULL);
+
+ return EFI_NOT_FOUND;
+
+}
+
+
+/**
+ Find a file in the volume by name
+
+ @param FileName A pointer to the name of the file to
+ find within the firmware volume.
+
+ @param VolumeHandle The firmware volume to search FileHandle
+ Upon exit, points to the found file's
+ handle or NULL if it could not be found.
+
+ @retval EFI_SUCCESS File was found.
+
+ @retval EFI_NOT_FOUND File was not found.
+
+ @retval EFI_INVALID_PARAMETER VolumeHandle or FileHandle or
+ FileName was NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsFindFileByName (
+ IN CONST EFI_GUID *FileName,
+ IN EFI_PEI_FV_HANDLE VolumeHandle,
+ OUT EFI_PEI_FILE_HANDLE *FileHandle
+ )
+{
+ EFI_STATUS Status;
+ if ((VolumeHandle == NULL) || (FileName == NULL) || (FileHandle == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+ Status = FindFileEx (VolumeHandle, FileName, 0, FileHandle);
+ if (Status == EFI_NOT_FOUND) {
+ *FileHandle = NULL;
+ }
+ return Status;
+}
+
+
+
+
+/**
+ Get information about the file by name.
+
+ @param FileHandle Handle of the file.
+
+ @param FileInfo Upon exit, points to the file's
+ information.
+
+ @retval EFI_SUCCESS File information returned.
+
+ @retval EFI_INVALID_PARAMETER If FileHandle does not
+ represent a valid file.
+
+ @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsGetFileInfo (
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ OUT EFI_FV_FILE_INFO *FileInfo
+ )
+{
+ UINT8 FileState;
+ UINT8 ErasePolarity;
+ EFI_FFS_FILE_HEADER *FileHeader;
+ EFI_PEI_FV_HANDLE VolumeHandle;
+
+ if ((FileHandle == NULL) || (FileInfo == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ VolumeHandle = 0;
+ //
+ // Retrieve the FirmwareVolume which the file resides in.
+ //
+ if (!FileHandleToVolume(FileHandle, &VolumeHandle)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (((EFI_FIRMWARE_VOLUME_HEADER*)VolumeHandle)->Attributes & EFI_FVB2_ERASE_POLARITY) {
+ ErasePolarity = 1;
+ } else {
+ ErasePolarity = 0;
+ }
+
+ //
+ // Get FileState which is the highest bit of the State
+ //
+ FileState = GetFileState (ErasePolarity, (EFI_FFS_FILE_HEADER*)FileHandle);
+
+ switch (FileState) {
+ case EFI_FILE_DATA_VALID:
+ case EFI_FILE_MARKED_FOR_UPDATE:
+ break;
+ default:
+ return EFI_INVALID_PARAMETER;
+ }
+
+ FileHeader = (EFI_FFS_FILE_HEADER *)FileHandle;
+ CopyMem (&FileInfo->FileName, &FileHeader->Name, sizeof(EFI_GUID));
+ FileInfo->FileType = FileHeader->Type;
+ FileInfo->FileAttributes = FileHeader->Attributes;
+ FileInfo->BufferSize = ((*(UINT32 *)FileHeader->Size) & 0x00FFFFFF) - sizeof (EFI_FFS_FILE_HEADER);
+ FileInfo->Buffer = (FileHeader + 1);
+ return EFI_SUCCESS;
+}
+
+
+/**
+ Get Information about the volume by name
+
+ @param VolumeHandle Handle of the volume.
+
+ @param VolumeInfo Upon exit, points to the volume's
+ information.
+
+ @retval EFI_SUCCESS File information returned.
+
+ @retval EFI_INVALID_PARAMETER If FileHandle does not
+ represent a valid file.
+
+ @retval EFI_INVALID_PARAMETER If FileInfo is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsGetVolumeInfo (
+ IN EFI_PEI_FV_HANDLE VolumeHandle,
+ OUT EFI_FV_INFO *VolumeInfo
+ )
+{
+ EFI_FIRMWARE_VOLUME_HEADER FwVolHeader;
+ EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExHeaderInfo;
+
+ if (VolumeInfo == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // VolumeHandle may not align at 8 byte,
+ // but FvLength is UINT64 type, which requires FvHeader align at least 8 byte.
+ // So, Copy FvHeader into the local FvHeader structure.
+ //
+ CopyMem (&FwVolHeader, VolumeHandle, sizeof (EFI_FIRMWARE_VOLUME_HEADER));
+ //
+ // Check Fv Image Signature
+ //
+ if (FwVolHeader.Signature != EFI_FVH_SIGNATURE) {
+ return EFI_INVALID_PARAMETER;
+ }
+ VolumeInfo->FvAttributes = FwVolHeader.Attributes;
+ VolumeInfo->FvStart = (VOID *) VolumeHandle;
+ VolumeInfo->FvSize = FwVolHeader.FvLength;
+ CopyMem (&VolumeInfo->FvFormat, &FwVolHeader.FileSystemGuid, sizeof(EFI_GUID));
+
+ if (FwVolHeader.ExtHeaderOffset != 0) {
+ FwVolExHeaderInfo = (EFI_FIRMWARE_VOLUME_EXT_HEADER*)(((UINT8 *)VolumeHandle) + FwVolHeader.ExtHeaderOffset);
+ CopyMem (&VolumeInfo->FvName, &FwVolExHeaderInfo->FvName, sizeof(EFI_GUID));
+ }
+ return EFI_SUCCESS;
+}
+
+
+
+/**
+ Search through every FV until you find a file of type FileType
+
+ @param FileType File handle of a Fv type file.
+ @param Volumehandle On succes Volume Handle of the match
+ @param FileHandle On success File Handle of the match
+
+ @retval EFI_NOT_FOUND FV image can't be found.
+ @retval EFI_SUCCESS Successfully found FileType
+
+**/
+EFI_STATUS
+EFIAPI
+FfsAnyFvFindFirstFile (
+ IN EFI_FV_FILETYPE FileType,
+ OUT EFI_PEI_FV_HANDLE *VolumeHandle,
+ OUT EFI_PEI_FILE_HANDLE *FileHandle
+ )
+{
+ EFI_STATUS Status;
+ UINTN Instance;
+
+ //
+ // Search every FV for the DXE Core
+ //
+ Instance = 0;
+ *FileHandle = NULL;
+
+ while (1)
+ {
+ Status = FfsFindNextVolume (Instance++, VolumeHandle);
+ if (EFI_ERROR (Status))
+ {
+ break;
+ }
+
+ Status = FfsFindNextFile (FileType, *VolumeHandle, FileHandle);
+ if (!EFI_ERROR (Status))
+ {
+ break;
+ }
+ }
+
+ return Status;
+}
+
+
+
+/**
+ Get Fv image from the FV type file, then add FV & FV2 Hob.
+
+ @param FileHandle File handle of a Fv type file.
+
+
+ @retval EFI_NOT_FOUND FV image can't be found.
+ @retval EFI_SUCCESS Successfully to process it.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsProcessFvFile (
+ IN EFI_PEI_FILE_HANDLE FvFileHandle
+ )
+{
+ EFI_STATUS Status;
+ EFI_PEI_FV_HANDLE FvImageHandle;
+ EFI_FV_INFO FvImageInfo;
+ UINT32 FvAlignment;
+ VOID *FvBuffer;
+ EFI_PEI_HOB_POINTERS HobFv2;
+
+ FvBuffer = NULL;
+
+
+ //
+ // Check if this EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE file has already
+ // been extracted.
+ //
+ HobFv2.Raw = GetHobList ();
+ while ((HobFv2.Raw = GetNextHob (EFI_HOB_TYPE_FV2, HobFv2.Raw)) != NULL) {
+ if (CompareGuid (&(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name), &HobFv2.FirmwareVolume2->FileName)) {
+ //
+ // this FILE has been dispatched, it will not be dispatched again.
+ //
+ return EFI_SUCCESS;
+ }
+ HobFv2.Raw = GET_NEXT_HOB (HobFv2);
+ }
+
+ //
+ // Find FvImage in FvFile
+ //
+ Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, FvFileHandle, (VOID **)&FvImageHandle);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Collect FvImage Info.
+ //
+ ZeroMem (&FvImageInfo, sizeof (FvImageInfo));
+ Status = FfsGetVolumeInfo (FvImageHandle, &FvImageInfo);
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // FvAlignment must be more than 8 bytes required by FvHeader structure.
+ //
+ FvAlignment = 1 << ((FvImageInfo.FvAttributes & EFI_FVB2_ALIGNMENT) >> 16);
+ if (FvAlignment < 8) {
+ FvAlignment = 8;
+ }
+
+ //
+ // Check FvImage
+ //
+ if ((UINTN) FvImageInfo.FvStart % FvAlignment != 0) {
+ FvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32) FvImageInfo.FvSize), FvAlignment);
+ if (FvBuffer == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ CopyMem (FvBuffer, FvImageInfo.FvStart, (UINTN) FvImageInfo.FvSize);
+ //
+ // Update FvImageInfo after reload FvImage to new aligned memory
+ //
+ FfsGetVolumeInfo ((EFI_PEI_FV_HANDLE) FvBuffer, &FvImageInfo);
+ }
+
+
+ //
+ // Inform HOB consumer phase, i.e. DXE core, the existance of this FV
+ //
+ BuildFvHob ((EFI_PHYSICAL_ADDRESS) (UINTN) FvImageInfo.FvStart, FvImageInfo.FvSize);
+
+ //
+ // Makes the encapsulated volume show up in DXE phase to skip processing of
+ // encapsulated file again.
+ //
+ BuildFv2Hob (
+ (EFI_PHYSICAL_ADDRESS) (UINTN) FvImageInfo.FvStart,
+ FvImageInfo.FvSize,
+ &FvImageInfo.FvName,
+ &(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name)
+ );
+
+ return EFI_SUCCESS;
+}
+
+
diff --git a/EmbeddedPkg/Library/PrePiLib/PrePi.h b/EmbeddedPkg/Library/PrePiLib/PrePi.h
index 77fe32898..d637277d2 100644
--- a/EmbeddedPkg/Library/PrePiLib/PrePi.h
+++ b/EmbeddedPkg/Library/PrePiLib/PrePi.h
@@ -1,46 +1,46 @@
-/** @file
- Library that helps implement monolithic PEI (i.e. PEI part of SEC)
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef _PI_PEI_H_
-#define _PI_PEI_H_
-
-#include <PiPei.h>
-
-#include <Library/BaseLib.h>
-#include <Library/PrePiLib.h>
-#include <Library/PcdLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiDecompressLib.h>
-#include <Library/PeCoffLib.h>
-#include <Library/CacheMaintenanceLib.h>
-#include <Library/TimerLib.h>
-#include <Library/PerformanceLib.h>
-
-#include <Guid/MemoryAllocationHob.h>
-
-
-#define GET_HOB_TYPE(Hob) ((Hob).Header->HobType)
-#define GET_HOB_LENGTH(Hob) ((Hob).Header->HobLength)
-#define GET_NEXT_HOB(Hob) ((Hob).Raw + GET_HOB_LENGTH (Hob))
-#define END_OF_HOB_LIST(Hob) (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_END_OF_HOB_LIST)
-
-//
-// Get the data and data size field of GUID
-//
-#define GET_GUID_HOB_DATA(GuidHob) ((VOID *) (((UINT8 *) &((GuidHob)->Name)) + sizeof (EFI_GUID)))
-#define GET_GUID_HOB_DATA_SIZE(GuidHob) (((GuidHob)->Header).HobLength - sizeof (EFI_HOB_GUID_TYPE))
-
-#endif
+/** @file
+ Library that helps implement monolithic PEI (i.e. PEI part of SEC)
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef _PI_PEI_H_
+#define _PI_PEI_H_
+
+#include <PiPei.h>
+
+#include <Library/BaseLib.h>
+#include <Library/PrePiLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiDecompressLib.h>
+#include <Library/PeCoffLib.h>
+#include <Library/CacheMaintenanceLib.h>
+#include <Library/TimerLib.h>
+#include <Library/PerformanceLib.h>
+
+#include <Guid/MemoryAllocationHob.h>
+
+
+#define GET_HOB_TYPE(Hob) ((Hob).Header->HobType)
+#define GET_HOB_LENGTH(Hob) ((Hob).Header->HobLength)
+#define GET_NEXT_HOB(Hob) ((Hob).Raw + GET_HOB_LENGTH (Hob))
+#define END_OF_HOB_LIST(Hob) (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_END_OF_HOB_LIST)
+
+//
+// Get the data and data size field of GUID
+//
+#define GET_GUID_HOB_DATA(GuidHob) ((VOID *) (((UINT8 *) &((GuidHob)->Name)) + sizeof (EFI_GUID)))
+#define GET_GUID_HOB_DATA_SIZE(GuidHob) (((GuidHob)->Header).HobLength - sizeof (EFI_HOB_GUID_TYPE))
+
+#endif
diff --git a/EmbeddedPkg/Library/PrePiLib/PrePiLib.c b/EmbeddedPkg/Library/PrePiLib/PrePiLib.c
index e46cafec3..4cc974f1a 100644
--- a/EmbeddedPkg/Library/PrePiLib/PrePiLib.c
+++ b/EmbeddedPkg/Library/PrePiLib/PrePiLib.c
@@ -1,226 +1,226 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <PrePi.h>
-
-//
-// Hack to work in NT32
-//
-EFI_STATUS
-
-EFIAPI
-
-SecWinNtPeiLoadFile (
- IN VOID *Pe32Data,
- IN EFI_PHYSICAL_ADDRESS *ImageAddress,
- IN UINT64 *ImageSize,
- IN EFI_PHYSICAL_ADDRESS *EntryPoint
- );
-
-
-EFI_STATUS
-EFIAPI
-LoadPeCoffImage (
- IN VOID *PeCoffImage,
- OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
- OUT UINT64 *ImageSize,
- OUT EFI_PHYSICAL_ADDRESS *EntryPoint
- )
-{
- RETURN_STATUS Status;
- PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
- VOID *Buffer;
-
- ZeroMem (&ImageContext, sizeof (ImageContext));
-
- ImageContext.Handle = PeCoffImage;
- ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
-
- Status = PeCoffLoaderGetImageInfo (&ImageContext);
- ASSERT_EFI_ERROR (Status);
-
-
- //
- // Allocate Memory for the image
- //
- Buffer = AllocatePages (EFI_SIZE_TO_PAGES((UINT32)ImageContext.ImageSize));
- ASSERT (Buffer != 0);
-
-
- ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer;
-
- //
- // Load the image to our new buffer
- //
- Status = PeCoffLoaderLoadImage (&ImageContext);
- ASSERT_EFI_ERROR (Status);
-
- //
- // Relocate the image in our new buffer
- //
- Status = PeCoffLoaderRelocateImage (&ImageContext);
- ASSERT_EFI_ERROR (Status);
-
-
- *ImageAddress = ImageContext.ImageAddress;
- *ImageSize = ImageContext.ImageSize;
- *EntryPoint = ImageContext.EntryPoint;
-
- //
- // Flush not needed for all architectures. We could have a processor specific
- // function in this library that does the no-op if needed.
- //
- InvalidateInstructionCacheRange ((VOID *)(UINTN)*ImageAddress, (UINTN)*ImageSize);
-
- return Status;
-}
-
-
-
-typedef
-VOID
-(EFIAPI *DXE_CORE_ENTRY_POINT) (
- IN VOID *HobStart
- );
-
-EFI_STATUS
-EFIAPI
-LoadDxeCoreFromFfsFile (
- IN EFI_PEI_FILE_HANDLE FileHandle,
- IN UINTN StackSize
- )
-{
- EFI_STATUS Status;
- VOID *PeCoffImage;
- EFI_PHYSICAL_ADDRESS ImageAddress;
- UINT64 ImageSize;
- EFI_PHYSICAL_ADDRESS EntryPoint;
- VOID *BaseOfStack;
- VOID *TopOfStack;
- VOID *Hob;
- EFI_FV_FILE_INFO FvFileInfo;
-
- Status = FfsFindSectionData (EFI_SECTION_PE32, FileHandle, &PeCoffImage);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
-
- Status = LoadPeCoffImage (PeCoffImage, &ImageAddress, &ImageSize, &EntryPoint);
-// For NT32 Debug Status = SecWinNtPeiLoadFile (PeCoffImage, &ImageAddress, &ImageSize, &EntryPoint);
- ASSERT_EFI_ERROR (Status);
-
- //
- // Extract the DxeCore GUID file name.
- //
- Status = FfsGetFileInfo (FileHandle, &FvFileInfo);
- ASSERT_EFI_ERROR (Status);
-
- BuildModuleHob (&FvFileInfo.FileName, (EFI_PHYSICAL_ADDRESS)(UINTN)ImageAddress, EFI_SIZE_TO_PAGES ((UINT32) ImageSize) * EFI_PAGE_SIZE, EntryPoint);
-
- DEBUG ((EFI_D_INFO | EFI_D_LOAD, "Loading DxeCore at 0x%10p EntryPoint=0x%10p\n", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)EntryPoint));
-
- Hob = GetHobList ();
- if (StackSize == 0) {
- // User the current stack
-
- ((DXE_CORE_ENTRY_POINT)(UINTN)EntryPoint) (Hob);
- } else {
-
- //
- // Allocate 128KB for the Stack
- //
- BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (StackSize));
- ASSERT (BaseOfStack != NULL);
-
- //
- // Compute the top of the stack we were allocated. Pre-allocate a UINTN
- // for safety.
- //
- TopOfStack = (VOID *) ((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (StackSize) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT);
- TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
-
- //
- // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore.
- //
- UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, StackSize);
-
- SwitchStack (
- (SWITCH_STACK_ENTRY_POINT)(UINTN)EntryPoint,
- Hob,
- NULL,
- TopOfStack
- );
-
- }
-
- // Should never get here as DXE Core does not return
- DEBUG ((EFI_D_ERROR, "DxeCore returned\n"));
- ASSERT (FALSE);
-
- return EFI_DEVICE_ERROR;
-}
-
-
-
-EFI_STATUS
-EFIAPI
-LoadDxeCoreFromFv (
- IN UINTN *FvInstance, OPTIONAL
- IN UINTN StackSize
- )
-{
- EFI_STATUS Status;
- EFI_PEI_FV_HANDLE VolumeHandle;
- EFI_PEI_FILE_HANDLE FileHandle = NULL;
-
- if (FvInstance != NULL) {
- //
- // Caller passed in a specific FV to try, so only try that one
- //
- Status = FfsFindNextVolume (*FvInstance, &VolumeHandle);
- if (!EFI_ERROR (Status)) {
- Status = FfsFindNextFile (EFI_FV_FILETYPE_DXE_CORE, VolumeHandle, &FileHandle);
- }
- } else {
- Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_DXE_CORE, &VolumeHandle, &FileHandle);
- }
-
- if (!EFI_ERROR (Status)) {
- return LoadDxeCoreFromFfsFile (FileHandle, StackSize);
- }
-
- return Status;
-}
-
-
-EFI_STATUS
-EFIAPI
-DecompressFirstFv (
- VOID
- )
-{
- EFI_STATUS Status;
- EFI_PEI_FV_HANDLE VolumeHandle;
- EFI_PEI_FILE_HANDLE FileHandle;
-
- Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, &VolumeHandle, &FileHandle);
- if (!EFI_ERROR (Status)) {
- Status = FfsProcessFvFile (FileHandle);
- }
-
- return Status;
-}
-
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PrePi.h>
+
+//
+// Hack to work in NT32
+//
+EFI_STATUS
+
+EFIAPI
+
+SecWinNtPeiLoadFile (
+ IN VOID *Pe32Data,
+ IN EFI_PHYSICAL_ADDRESS *ImageAddress,
+ IN UINT64 *ImageSize,
+ IN EFI_PHYSICAL_ADDRESS *EntryPoint
+ );
+
+
+EFI_STATUS
+EFIAPI
+LoadPeCoffImage (
+ IN VOID *PeCoffImage,
+ OUT EFI_PHYSICAL_ADDRESS *ImageAddress,
+ OUT UINT64 *ImageSize,
+ OUT EFI_PHYSICAL_ADDRESS *EntryPoint
+ )
+{
+ RETURN_STATUS Status;
+ PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
+ VOID *Buffer;
+
+ ZeroMem (&ImageContext, sizeof (ImageContext));
+
+ ImageContext.Handle = PeCoffImage;
+ ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
+
+ Status = PeCoffLoaderGetImageInfo (&ImageContext);
+ ASSERT_EFI_ERROR (Status);
+
+
+ //
+ // Allocate Memory for the image
+ //
+ Buffer = AllocatePages (EFI_SIZE_TO_PAGES((UINT32)ImageContext.ImageSize));
+ ASSERT (Buffer != 0);
+
+
+ ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer;
+
+ //
+ // Load the image to our new buffer
+ //
+ Status = PeCoffLoaderLoadImage (&ImageContext);
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Relocate the image in our new buffer
+ //
+ Status = PeCoffLoaderRelocateImage (&ImageContext);
+ ASSERT_EFI_ERROR (Status);
+
+
+ *ImageAddress = ImageContext.ImageAddress;
+ *ImageSize = ImageContext.ImageSize;
+ *EntryPoint = ImageContext.EntryPoint;
+
+ //
+ // Flush not needed for all architectures. We could have a processor specific
+ // function in this library that does the no-op if needed.
+ //
+ InvalidateInstructionCacheRange ((VOID *)(UINTN)*ImageAddress, (UINTN)*ImageSize);
+
+ return Status;
+}
+
+
+
+typedef
+VOID
+(EFIAPI *DXE_CORE_ENTRY_POINT) (
+ IN VOID *HobStart
+ );
+
+EFI_STATUS
+EFIAPI
+LoadDxeCoreFromFfsFile (
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ IN UINTN StackSize
+ )
+{
+ EFI_STATUS Status;
+ VOID *PeCoffImage;
+ EFI_PHYSICAL_ADDRESS ImageAddress;
+ UINT64 ImageSize;
+ EFI_PHYSICAL_ADDRESS EntryPoint;
+ VOID *BaseOfStack;
+ VOID *TopOfStack;
+ VOID *Hob;
+ EFI_FV_FILE_INFO FvFileInfo;
+
+ Status = FfsFindSectionData (EFI_SECTION_PE32, FileHandle, &PeCoffImage);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+
+ Status = LoadPeCoffImage (PeCoffImage, &ImageAddress, &ImageSize, &EntryPoint);
+// For NT32 Debug Status = SecWinNtPeiLoadFile (PeCoffImage, &ImageAddress, &ImageSize, &EntryPoint);
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Extract the DxeCore GUID file name.
+ //
+ Status = FfsGetFileInfo (FileHandle, &FvFileInfo);
+ ASSERT_EFI_ERROR (Status);
+
+ BuildModuleHob (&FvFileInfo.FileName, (EFI_PHYSICAL_ADDRESS)(UINTN)ImageAddress, EFI_SIZE_TO_PAGES ((UINT32) ImageSize) * EFI_PAGE_SIZE, EntryPoint);
+
+ DEBUG ((EFI_D_INFO | EFI_D_LOAD, "Loading DxeCore at 0x%10p EntryPoint=0x%10p\n", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)EntryPoint));
+
+ Hob = GetHobList ();
+ if (StackSize == 0) {
+ // User the current stack
+
+ ((DXE_CORE_ENTRY_POINT)(UINTN)EntryPoint) (Hob);
+ } else {
+
+ //
+ // Allocate 128KB for the Stack
+ //
+ BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (StackSize));
+ ASSERT (BaseOfStack != NULL);
+
+ //
+ // Compute the top of the stack we were allocated. Pre-allocate a UINTN
+ // for safety.
+ //
+ TopOfStack = (VOID *) ((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (StackSize) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT);
+ TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
+
+ //
+ // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore.
+ //
+ UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, StackSize);
+
+ SwitchStack (
+ (SWITCH_STACK_ENTRY_POINT)(UINTN)EntryPoint,
+ Hob,
+ NULL,
+ TopOfStack
+ );
+
+ }
+
+ // Should never get here as DXE Core does not return
+ DEBUG ((EFI_D_ERROR, "DxeCore returned\n"));
+ ASSERT (FALSE);
+
+ return EFI_DEVICE_ERROR;
+}
+
+
+
+EFI_STATUS
+EFIAPI
+LoadDxeCoreFromFv (
+ IN UINTN *FvInstance, OPTIONAL
+ IN UINTN StackSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_PEI_FV_HANDLE VolumeHandle;
+ EFI_PEI_FILE_HANDLE FileHandle = NULL;
+
+ if (FvInstance != NULL) {
+ //
+ // Caller passed in a specific FV to try, so only try that one
+ //
+ Status = FfsFindNextVolume (*FvInstance, &VolumeHandle);
+ if (!EFI_ERROR (Status)) {
+ Status = FfsFindNextFile (EFI_FV_FILETYPE_DXE_CORE, VolumeHandle, &FileHandle);
+ }
+ } else {
+ Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_DXE_CORE, &VolumeHandle, &FileHandle);
+ }
+
+ if (!EFI_ERROR (Status)) {
+ return LoadDxeCoreFromFfsFile (FileHandle, StackSize);
+ }
+
+ return Status;
+}
+
+
+EFI_STATUS
+EFIAPI
+DecompressFirstFv (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_PEI_FV_HANDLE VolumeHandle;
+ EFI_PEI_FILE_HANDLE FileHandle;
+
+ Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, &VolumeHandle, &FileHandle);
+ if (!EFI_ERROR (Status)) {
+ Status = FfsProcessFvFile (FileHandle);
+ }
+
+ return Status;
+}
+
+
diff --git a/EmbeddedPkg/Library/PrePiLib/ReportStatusCode.c b/EmbeddedPkg/Library/PrePiLib/ReportStatusCode.c
index f898808de..8d60d5ab5 100644
--- a/EmbeddedPkg/Library/PrePiLib/ReportStatusCode.c
+++ b/EmbeddedPkg/Library/PrePiLib/ReportStatusCode.c
@@ -1,327 +1,327 @@
-/** @file
- Library that helps implement monolithic PEI
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <PrePi.h>
-#include <Library/ReportStatusCodeLib.h>
-#include <Library/SerialPortLib.h>
-#include <Library/PrintLib.h>
-
-#include <Protocol/StatusCode.h>
-#include <Guid/StatusCodeDataTypeId.h>
-#include <Guid/StatusCodeDataTypeDebug.h>
-#include <FrameworkPei.h>
-
-#define EFI_STATUS_CODE_DATA_MAX_SIZE 200
-
-EFI_STATUS
-EFIAPI
-SerialReportStatusCode (
- IN EFI_STATUS_CODE_TYPE CodeType,
- IN EFI_STATUS_CODE_VALUE Value,
- IN UINT32 Instance,
- IN CONST EFI_GUID *CallerId,
- IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
- );
-
-
-EFI_STATUS_CODE_PROTOCOL gStatusCode = {
- (EFI_REPORT_STATUS_CODE)SerialReportStatusCode
-};
-
-/**
- Extracts ASSERT() information from a status code structure.
-
- Converts the status code specified by CodeType, Value, and Data to the ASSERT()
- arguments specified by Filename, Description, and LineNumber. If CodeType is
- an EFI_ERROR_CODE, and CodeType has a severity of EFI_ERROR_UNRECOVERED, and
- Value has an operation mask of EFI_SW_EC_ILLEGAL_SOFTWARE_STATE, extract
- Filename, Description, and LineNumber from the optional data area of the
- status code buffer specified by Data. The optional data area of Data contains
- a Null-terminated ASCII string for the FileName, followed by a Null-terminated
- ASCII string for the Description, followed by a 32-bit LineNumber. If the
- ASSERT() information could be extracted from Data, then return TRUE.
- Otherwise, FALSE is returned.
-
- If Data is NULL, then ASSERT().
- If Filename is NULL, then ASSERT().
- If Description is NULL, then ASSERT().
- If LineNumber is NULL, then ASSERT().
-
- @param CodeType The type of status code being converted.
- @param Value The status code value being converted.
- @param Data Pointer to status code data buffer.
- @param Filename Pointer to the source file name that generated the ASSERT().
- @param Description Pointer to the description of the ASSERT().
- @param LineNumber Pointer to source line number that generated the ASSERT().
-
- @retval TRUE The status code specified by CodeType, Value, and Data was
- converted ASSERT() arguments specified by Filename, Description,
- and LineNumber.
- @retval FALSE The status code specified by CodeType, Value, and Data could
- not be converted to ASSERT() arguments.
-
-**/
-BOOLEAN
-EFIAPI
-ReportStatusCodeExtractAssertInfo (
- IN EFI_STATUS_CODE_TYPE CodeType,
- IN EFI_STATUS_CODE_VALUE Value,
- IN CONST EFI_STATUS_CODE_DATA *Data,
- OUT CHAR8 **Filename,
- OUT CHAR8 **Description,
- OUT UINT32 *LineNumber
- )
-{
- EFI_DEBUG_ASSERT_DATA *AssertData;
-
- ASSERT (Data != NULL);
- ASSERT (Filename != NULL);
- ASSERT (Description != NULL);
- ASSERT (LineNumber != NULL);
-
- if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
- ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) &&
- ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) {
- AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1);
- *Filename = (CHAR8 *)(AssertData + 1);
- *Description = *Filename + AsciiStrLen (*Filename) + 1;
- *LineNumber = AssertData->LineNumber;
- return TRUE;
- }
- return FALSE;
-}
-
-
-/**
- Extracts DEBUG() information from a status code structure.
-
- Converts the status code specified by Data to the DEBUG() arguments specified
- by ErrorLevel, Marker, and Format. If type GUID in Data is
- EFI_STATUS_CODE_DATA_TYPE_DEBUG_GUID, then extract ErrorLevel, Marker, and
- Format from the optional data area of the status code buffer specified by Data.
- The optional data area of Data contains a 32-bit ErrorLevel followed by Marker
- which is 12 UINTN parameters, followed by a Null-terminated ASCII string for
- the Format. If the DEBUG() information could be extracted from Data, then
- return TRUE. Otherwise, FALSE is returned.
-
- If Data is NULL, then ASSERT().
- If ErrorLevel is NULL, then ASSERT().
- If Marker is NULL, then ASSERT().
- If Format is NULL, then ASSERT().
-
- @param Data Pointer to status code data buffer.
- @param ErrorLevel Pointer to error level mask for a debug message.
- @param Marker Pointer to the variable argument list associated with Format.
- @param Format Pointer to a Null-terminated ASCII format string of a
- debug message.
-
- @retval TRUE The status code specified by Data was converted DEBUG() arguments
- specified by ErrorLevel, Marker, and Format.
- @retval FALSE The status code specified by Data could not be converted to
- DEBUG() arguments.
-
-**/
-BOOLEAN
-EFIAPI
-ReportStatusCodeExtractDebugInfo (
- IN CONST EFI_STATUS_CODE_DATA *Data,
- OUT UINT32 *ErrorLevel,
- OUT BASE_LIST *Marker,
- OUT CHAR8 **Format
- )
-{
- EFI_DEBUG_INFO *DebugInfo;
-
- ASSERT (Data != NULL);
- ASSERT (ErrorLevel != NULL);
- ASSERT (Marker != NULL);
- ASSERT (Format != NULL);
-
- //
- // If the GUID type is not EFI_STATUS_CODE_DATA_TYPE_DEBUG_GUID then return FALSE
- //
- if (!CompareGuid (&Data->Type, &gEfiStatusCodeDataTypeDebugGuid)) {
- return FALSE;
- }
-
- //
- // Retrieve the debug information from the status code record
- //
- DebugInfo = (EFI_DEBUG_INFO *)(Data + 1);
-
- *ErrorLevel = DebugInfo->ErrorLevel;
-
- //
- // The first 12 * UINTN bytes of the string are really an
- // argument stack to support varargs on the Format string.
- //
- *Marker = (BASE_LIST) (DebugInfo + 1);
- *Format = (CHAR8 *)(((UINT64 *)*Marker) + 12);
-
- return TRUE;
-}
-
-
-
-
-EFI_STATUS
-EFIAPI
-SerialReportStatusCode (
- IN EFI_STATUS_CODE_TYPE CodeType,
- IN EFI_STATUS_CODE_VALUE Value,
- IN UINT32 Instance,
- IN CONST EFI_GUID *CallerId,
- IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
- )
-{
- CHAR8 *Filename;
- CHAR8 *Description;
- CHAR8 *Format;
- CHAR8 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];
- UINT32 ErrorLevel;
- UINT32 LineNumber;
- UINTN CharCount;
- BASE_LIST Marker;
- EFI_DEBUG_INFO *DebugInfo;
-
- Buffer[0] = '\0';
-
-
- if (Data != NULL &&
- ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
-
- //
- // Print ASSERT() information into output buffer.
- //
- CharCount = AsciiSPrint (
- Buffer,
- EFI_STATUS_CODE_DATA_MAX_SIZE,
- "\n\rASSERT!: %a (%d): %a\n\r",
- Filename,
- LineNumber,
- Description
- );
-
-
- //
- // Callout to standard output.
- //
- SerialPortWrite ((UINT8 *)Buffer, CharCount);
- return EFI_SUCCESS;
-
- } else if (Data != NULL &&
- ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
-
- //
- // Print DEBUG() information into output buffer.
- //
- CharCount = AsciiBSPrint (
- Buffer,
- EFI_STATUS_CODE_DATA_MAX_SIZE,
- Format,
- Marker
- );
-
- } else if (Data != NULL &&
- CompareGuid (&Data->Type, &gEfiStatusCodeSpecificDataGuid) &&
- (CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
-
- //
- // Print specific data into output buffer.
- //
- DebugInfo = (EFI_DEBUG_INFO *) (Data + 1);
- Marker = (BASE_LIST) (DebugInfo + 1);
- Format = (CHAR8 *) (((UINT64 *) (DebugInfo + 1)) + 12);
-
- CharCount = AsciiBSPrint (Buffer, EFI_STATUS_CODE_DATA_MAX_SIZE, Format, Marker);
-
- } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
- //
- // Print ERROR information into output buffer.
- //
-
- CharCount = AsciiSPrint (
- Buffer,
- EFI_STATUS_CODE_DATA_MAX_SIZE,
- "ERROR: C%x:V%x I%x",
- CodeType,
- Value,
- Instance
- );
-
- //
- // Make sure we don't try to print values that weren't intended to be printed, especially NULL GUID pointers.
- //
- if (CallerId != NULL) {
- CharCount += AsciiSPrint (
- &Buffer[CharCount - 1],
- (EFI_STATUS_CODE_DATA_MAX_SIZE - (sizeof (Buffer[0]) * CharCount)),
- " %g",
- CallerId
- );
- }
-
- if (Data != NULL) {
- CharCount += AsciiSPrint (
- &Buffer[CharCount - 1],
- (EFI_STATUS_CODE_DATA_MAX_SIZE - (sizeof (Buffer[0]) * CharCount)),
- " %x",
- Data
- );
-
- }
-
-
- CharCount += AsciiSPrint (
- &Buffer[CharCount - 1],
- (EFI_STATUS_CODE_DATA_MAX_SIZE - (sizeof (Buffer[0]) * CharCount)),
- "\n\r"
- );
-
- } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
- CharCount = AsciiSPrint (
- Buffer,
- EFI_STATUS_CODE_DATA_MAX_SIZE,
- "PROGRESS CODE: V%x I%x\n\r",
- Value,
- Instance
- );
- } else {
- CharCount = AsciiSPrint (
- Buffer,
- EFI_STATUS_CODE_DATA_MAX_SIZE,
- "Undefined: C%x:V%x I%x\n\r",
- CodeType,
- Value,
- Instance
- );
-
- }
-
- SerialPortWrite ((UINT8 *)Buffer, CharCount);
- return EFI_SUCCESS;
-
-}
-
-
-VOID
-EFIAPI
-AddDxeCoreReportStatusCodeCallback (
- VOID
- )
-{
- BuildGuidDataHob (&gEfiStatusCodeRuntimeProtocolGuid, &gStatusCode, sizeof(VOID *));
-}
-
+/** @file
+ Library that helps implement monolithic PEI
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PrePi.h>
+#include <Library/ReportStatusCodeLib.h>
+#include <Library/SerialPortLib.h>
+#include <Library/PrintLib.h>
+
+#include <Protocol/StatusCode.h>
+#include <Guid/StatusCodeDataTypeId.h>
+#include <Guid/StatusCodeDataTypeDebug.h>
+#include <FrameworkPei.h>
+
+#define EFI_STATUS_CODE_DATA_MAX_SIZE 200
+
+EFI_STATUS
+EFIAPI
+SerialReportStatusCode (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN CONST EFI_GUID *CallerId,
+ IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
+ );
+
+
+EFI_STATUS_CODE_PROTOCOL gStatusCode = {
+ (EFI_REPORT_STATUS_CODE)SerialReportStatusCode
+};
+
+/**
+ Extracts ASSERT() information from a status code structure.
+
+ Converts the status code specified by CodeType, Value, and Data to the ASSERT()
+ arguments specified by Filename, Description, and LineNumber. If CodeType is
+ an EFI_ERROR_CODE, and CodeType has a severity of EFI_ERROR_UNRECOVERED, and
+ Value has an operation mask of EFI_SW_EC_ILLEGAL_SOFTWARE_STATE, extract
+ Filename, Description, and LineNumber from the optional data area of the
+ status code buffer specified by Data. The optional data area of Data contains
+ a Null-terminated ASCII string for the FileName, followed by a Null-terminated
+ ASCII string for the Description, followed by a 32-bit LineNumber. If the
+ ASSERT() information could be extracted from Data, then return TRUE.
+ Otherwise, FALSE is returned.
+
+ If Data is NULL, then ASSERT().
+ If Filename is NULL, then ASSERT().
+ If Description is NULL, then ASSERT().
+ If LineNumber is NULL, then ASSERT().
+
+ @param CodeType The type of status code being converted.
+ @param Value The status code value being converted.
+ @param Data Pointer to status code data buffer.
+ @param Filename Pointer to the source file name that generated the ASSERT().
+ @param Description Pointer to the description of the ASSERT().
+ @param LineNumber Pointer to source line number that generated the ASSERT().
+
+ @retval TRUE The status code specified by CodeType, Value, and Data was
+ converted ASSERT() arguments specified by Filename, Description,
+ and LineNumber.
+ @retval FALSE The status code specified by CodeType, Value, and Data could
+ not be converted to ASSERT() arguments.
+
+**/
+BOOLEAN
+EFIAPI
+ReportStatusCodeExtractAssertInfo (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN CONST EFI_STATUS_CODE_DATA *Data,
+ OUT CHAR8 **Filename,
+ OUT CHAR8 **Description,
+ OUT UINT32 *LineNumber
+ )
+{
+ EFI_DEBUG_ASSERT_DATA *AssertData;
+
+ ASSERT (Data != NULL);
+ ASSERT (Filename != NULL);
+ ASSERT (Description != NULL);
+ ASSERT (LineNumber != NULL);
+
+ if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) &&
+ ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) &&
+ ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) {
+ AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1);
+ *Filename = (CHAR8 *)(AssertData + 1);
+ *Description = *Filename + AsciiStrLen (*Filename) + 1;
+ *LineNumber = AssertData->LineNumber;
+ return TRUE;
+ }
+ return FALSE;
+}
+
+
+/**
+ Extracts DEBUG() information from a status code structure.
+
+ Converts the status code specified by Data to the DEBUG() arguments specified
+ by ErrorLevel, Marker, and Format. If type GUID in Data is
+ EFI_STATUS_CODE_DATA_TYPE_DEBUG_GUID, then extract ErrorLevel, Marker, and
+ Format from the optional data area of the status code buffer specified by Data.
+ The optional data area of Data contains a 32-bit ErrorLevel followed by Marker
+ which is 12 UINTN parameters, followed by a Null-terminated ASCII string for
+ the Format. If the DEBUG() information could be extracted from Data, then
+ return TRUE. Otherwise, FALSE is returned.
+
+ If Data is NULL, then ASSERT().
+ If ErrorLevel is NULL, then ASSERT().
+ If Marker is NULL, then ASSERT().
+ If Format is NULL, then ASSERT().
+
+ @param Data Pointer to status code data buffer.
+ @param ErrorLevel Pointer to error level mask for a debug message.
+ @param Marker Pointer to the variable argument list associated with Format.
+ @param Format Pointer to a Null-terminated ASCII format string of a
+ debug message.
+
+ @retval TRUE The status code specified by Data was converted DEBUG() arguments
+ specified by ErrorLevel, Marker, and Format.
+ @retval FALSE The status code specified by Data could not be converted to
+ DEBUG() arguments.
+
+**/
+BOOLEAN
+EFIAPI
+ReportStatusCodeExtractDebugInfo (
+ IN CONST EFI_STATUS_CODE_DATA *Data,
+ OUT UINT32 *ErrorLevel,
+ OUT BASE_LIST *Marker,
+ OUT CHAR8 **Format
+ )
+{
+ EFI_DEBUG_INFO *DebugInfo;
+
+ ASSERT (Data != NULL);
+ ASSERT (ErrorLevel != NULL);
+ ASSERT (Marker != NULL);
+ ASSERT (Format != NULL);
+
+ //
+ // If the GUID type is not EFI_STATUS_CODE_DATA_TYPE_DEBUG_GUID then return FALSE
+ //
+ if (!CompareGuid (&Data->Type, &gEfiStatusCodeDataTypeDebugGuid)) {
+ return FALSE;
+ }
+
+ //
+ // Retrieve the debug information from the status code record
+ //
+ DebugInfo = (EFI_DEBUG_INFO *)(Data + 1);
+
+ *ErrorLevel = DebugInfo->ErrorLevel;
+
+ //
+ // The first 12 * UINTN bytes of the string are really an
+ // argument stack to support varargs on the Format string.
+ //
+ *Marker = (BASE_LIST) (DebugInfo + 1);
+ *Format = (CHAR8 *)(((UINT64 *)*Marker) + 12);
+
+ return TRUE;
+}
+
+
+
+
+EFI_STATUS
+EFIAPI
+SerialReportStatusCode (
+ IN EFI_STATUS_CODE_TYPE CodeType,
+ IN EFI_STATUS_CODE_VALUE Value,
+ IN UINT32 Instance,
+ IN CONST EFI_GUID *CallerId,
+ IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL
+ )
+{
+ CHAR8 *Filename;
+ CHAR8 *Description;
+ CHAR8 *Format;
+ CHAR8 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE];
+ UINT32 ErrorLevel;
+ UINT32 LineNumber;
+ UINTN CharCount;
+ BASE_LIST Marker;
+ EFI_DEBUG_INFO *DebugInfo;
+
+ Buffer[0] = '\0';
+
+
+ if (Data != NULL &&
+ ReportStatusCodeExtractAssertInfo (CodeType, Value, Data, &Filename, &Description, &LineNumber)) {
+
+ //
+ // Print ASSERT() information into output buffer.
+ //
+ CharCount = AsciiSPrint (
+ Buffer,
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ "\n\rASSERT!: %a (%d): %a\n\r",
+ Filename,
+ LineNumber,
+ Description
+ );
+
+
+ //
+ // Callout to standard output.
+ //
+ SerialPortWrite ((UINT8 *)Buffer, CharCount);
+ return EFI_SUCCESS;
+
+ } else if (Data != NULL &&
+ ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
+
+ //
+ // Print DEBUG() information into output buffer.
+ //
+ CharCount = AsciiBSPrint (
+ Buffer,
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ Format,
+ Marker
+ );
+
+ } else if (Data != NULL &&
+ CompareGuid (&Data->Type, &gEfiStatusCodeSpecificDataGuid) &&
+ (CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
+
+ //
+ // Print specific data into output buffer.
+ //
+ DebugInfo = (EFI_DEBUG_INFO *) (Data + 1);
+ Marker = (BASE_LIST) (DebugInfo + 1);
+ Format = (CHAR8 *) (((UINT64 *) (DebugInfo + 1)) + 12);
+
+ CharCount = AsciiBSPrint (Buffer, EFI_STATUS_CODE_DATA_MAX_SIZE, Format, Marker);
+
+ } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
+ //
+ // Print ERROR information into output buffer.
+ //
+
+ CharCount = AsciiSPrint (
+ Buffer,
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ "ERROR: C%x:V%x I%x",
+ CodeType,
+ Value,
+ Instance
+ );
+
+ //
+ // Make sure we don't try to print values that weren't intended to be printed, especially NULL GUID pointers.
+ //
+ if (CallerId != NULL) {
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount - 1],
+ (EFI_STATUS_CODE_DATA_MAX_SIZE - (sizeof (Buffer[0]) * CharCount)),
+ " %g",
+ CallerId
+ );
+ }
+
+ if (Data != NULL) {
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount - 1],
+ (EFI_STATUS_CODE_DATA_MAX_SIZE - (sizeof (Buffer[0]) * CharCount)),
+ " %x",
+ Data
+ );
+
+ }
+
+
+ CharCount += AsciiSPrint (
+ &Buffer[CharCount - 1],
+ (EFI_STATUS_CODE_DATA_MAX_SIZE - (sizeof (Buffer[0]) * CharCount)),
+ "\n\r"
+ );
+
+ } else if ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
+ CharCount = AsciiSPrint (
+ Buffer,
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ "PROGRESS CODE: V%x I%x\n\r",
+ Value,
+ Instance
+ );
+ } else {
+ CharCount = AsciiSPrint (
+ Buffer,
+ EFI_STATUS_CODE_DATA_MAX_SIZE,
+ "Undefined: C%x:V%x I%x\n\r",
+ CodeType,
+ Value,
+ Instance
+ );
+
+ }
+
+ SerialPortWrite ((UINT8 *)Buffer, CharCount);
+ return EFI_SUCCESS;
+
+}
+
+
+VOID
+EFIAPI
+AddDxeCoreReportStatusCodeCallback (
+ VOID
+ )
+{
+ BuildGuidDataHob (&gEfiStatusCodeRuntimeProtocolGuid, &gStatusCode, sizeof(VOID *));
+}
+
diff --git a/EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf b/EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
index b88d9abf5..ce0d13257 100644
--- a/EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
+++ b/EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
@@ -34,4 +34,4 @@
[LibraryClasses]
IoLib
DebugLib
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf b/EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
index 446c56b39..375cb4942 100644
--- a/EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
+++ b/EmbeddedPkg/Library/TemplateResetSystemLib/TemplateResetSystemLib.inf
@@ -32,4 +32,4 @@
[LibraryClasses]
IoLib
- DebugLib \ No newline at end of file
+ DebugLib \ No newline at end of file
diff --git a/EmbeddedPkg/TemplateSec/TemplateSec.inf b/EmbeddedPkg/TemplateSec/TemplateSec.inf
index a7dad5e32..81f4ac761 100644
--- a/EmbeddedPkg/TemplateSec/TemplateSec.inf
+++ b/EmbeddedPkg/TemplateSec/TemplateSec.inf
@@ -1,65 +1,65 @@
-#/** @file
-#
-# Component description file for DxeIpl module
-#
-# The responsibility of this module is to load the DXE Core from a Firmware Volume. This implementation i used to load a 32-bit DXE Core.
-#
-# Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = TemplateSec
- FILE_GUID = 1D6F730F-5A55-4078-869B-E0A18324BDC8
- MODULE_TYPE = SEC
- VERSION_STRING = 1.0
-
-
-#
-# The following information is for reference only and not required by the build tools.
-#
-# VALID_ARCHITECTURES = IA32 X64 ARM
-#
-
-[Sources.common]
- TemplateSec.c
-
-[Sources.Ia32]
-# Ia32/ResetVector.asm | MSFT
-# Ia32/ResetVector.S | GCC
-
-[Sources.X64]
-# X64/ResetVector.asm | MSFT
-# X64/ResetVector.S | GCC
-
-[Sources.ARM]
-# Arm/ResetVector.asm | RVCT
-# Arm/ResetVector.S | GCC
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
-
-
-[LibraryClasses]
- BaseLib
- DebugLib
- BaseMemoryLib
- UefiDecompressLib
- PeCoffLib
- CacheMaintenanceLib
- PrePiLib
-
-[Pcd]
- gEmbeddedTokenSpaceGuid.PcdEmbeddedFdBaseAddress
- gEmbeddedTokenSpaceGuid.PcdEmbeddedFdSize
-
+#/** @file
+#
+# Component description file for DxeIpl module
+#
+# The responsibility of this module is to load the DXE Core from a Firmware Volume. This implementation i used to load a 32-bit DXE Core.
+#
+# Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = TemplateSec
+ FILE_GUID = 1D6F730F-5A55-4078-869B-E0A18324BDC8
+ MODULE_TYPE = SEC
+ VERSION_STRING = 1.0
+
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64 ARM
+#
+
+[Sources.common]
+ TemplateSec.c
+
+[Sources.Ia32]
+# Ia32/ResetVector.asm | MSFT
+# Ia32/ResetVector.S | GCC
+
+[Sources.X64]
+# X64/ResetVector.asm | MSFT
+# X64/ResetVector.S | GCC
+
+[Sources.ARM]
+# Arm/ResetVector.asm | RVCT
+# Arm/ResetVector.S | GCC
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ BaseMemoryLib
+ UefiDecompressLib
+ PeCoffLib
+ CacheMaintenanceLib
+ PrePiLib
+
+[Pcd]
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedFdBaseAddress
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedFdSize
+
diff --git a/EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf b/EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
index 4a21fb495..9deceea9c 100644
--- a/EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
+++ b/EmbeddedPkg/Universal/MmcDxe/MmcDxe.inf
@@ -47,4 +47,4 @@
gEfiDriverDiagnostics2ProtocolGuid
[Depex]
- TRUE \ No newline at end of file
+ TRUE \ No newline at end of file
diff --git a/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/BiosVideo.c b/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/BiosVideo.c
index 21b3e8726..fc9672651 100644
--- a/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/BiosVideo.c
+++ b/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/BiosVideo.c
@@ -1,7 +1,7 @@
/** @file
ConsoleOut Routines that speak VGA.
-Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -1129,49 +1129,79 @@ ParseEdidData (
((EdidDataBlock->EstablishedTimings[2] & 0x80) << 9) ;
for (Index = 0; Index < VESA_BIOS_EXTENSIONS_EDID_ESTABLISHED_TIMING_MAX_NUMBER; Index ++) {
if ((TimingBits & 0x1) != 0) {
+ DEBUG ((EFI_D_INFO, "Established Timing: %d x %d\n",
+ mEstablishedEdidTiming[Index].HorizontalResolution, mEstablishedEdidTiming[Index].VerticalResolution));
ValidEdidTiming->Key[ValidNumber] = CalculateEdidKey (&mEstablishedEdidTiming[Index]);
ValidNumber ++;
}
TimingBits = TimingBits >> 1;
}
- } else {
+ }
+
+ //
+ // Parse the standard timing data
+ //
+ BufferIndex = &EdidDataBlock->StandardTimingIdentification[0];
+ for (Index = 0; Index < 8; Index ++) {
//
- // If no Established timing data, read the standard timing data
+ // Check if this is a valid Standard Timing entry
+ // VESA documents unused fields should be set to 01h
//
- BufferIndex = &EdidDataBlock->StandardTimingIdentification[0];
- for (Index = 0; Index < 8; Index ++) {
- if ((BufferIndex[0] != 0x1) && (BufferIndex[1] != 0x1)){
- //
- // A valid Standard Timing
- //
- HorizontalResolution = (UINT16) (BufferIndex[0] * 8 + 248);
- AspectRatio = (UINT8) (BufferIndex[1] >> 6);
- switch (AspectRatio) {
- case 0:
- VerticalResolution = (UINT16) (HorizontalResolution / 16 * 10);
- break;
- case 1:
- VerticalResolution = (UINT16) (HorizontalResolution / 4 * 3);
- break;
- case 2:
- VerticalResolution = (UINT16) (HorizontalResolution / 5 * 4);
- break;
- case 3:
- VerticalResolution = (UINT16) (HorizontalResolution / 16 * 9);
- break;
- default:
- VerticalResolution = (UINT16) (HorizontalResolution / 4 * 3);
- break;
- }
- RefreshRate = (UINT8) ((BufferIndex[1] & 0x1f) + 60);
- TempTiming.HorizontalResolution = HorizontalResolution;
- TempTiming.VerticalResolution = VerticalResolution;
- TempTiming.RefreshRate = RefreshRate;
- ValidEdidTiming->Key[ValidNumber] = CalculateEdidKey (&TempTiming);
- ValidNumber ++;
+ if ((BufferIndex[0] != 0x1) && (BufferIndex[1] != 0x1)){
+ //
+ // A valid Standard Timing
+ //
+ HorizontalResolution = (UINT16) (BufferIndex[0] * 8 + 248);
+ AspectRatio = (UINT8) (BufferIndex[1] >> 6);
+ switch (AspectRatio) {
+ case 0:
+ VerticalResolution = (UINT16) (HorizontalResolution / 16 * 10);
+ break;
+ case 1:
+ VerticalResolution = (UINT16) (HorizontalResolution / 4 * 3);
+ break;
+ case 2:
+ VerticalResolution = (UINT16) (HorizontalResolution / 5 * 4);
+ break;
+ case 3:
+ VerticalResolution = (UINT16) (HorizontalResolution / 16 * 9);
+ break;
+ default:
+ VerticalResolution = (UINT16) (HorizontalResolution / 4 * 3);
+ break;
}
- BufferIndex += 2;
+ RefreshRate = (UINT8) ((BufferIndex[1] & 0x1f) + 60);
+ DEBUG ((EFI_D_INFO, "Standard Timing: %d x %d\n", HorizontalResolution, VerticalResolution));
+ TempTiming.HorizontalResolution = HorizontalResolution;
+ TempTiming.VerticalResolution = VerticalResolution;
+ TempTiming.RefreshRate = RefreshRate;
+ ValidEdidTiming->Key[ValidNumber] = CalculateEdidKey (&TempTiming);
+ ValidNumber ++;
}
+ BufferIndex += 2;
+ }
+
+ //
+ // Parse the Detailed Timing data
+ //
+ BufferIndex = &EdidDataBlock->DetailedTimingDescriptions[0];
+ for (Index = 0; Index < 4; Index ++, BufferIndex += VESA_BIOS_EXTENSIONS_DETAILED_TIMING_EACH_DESCRIPTOR_SIZE) {
+ if ((BufferIndex[0] == 0x0) && (BufferIndex[1] == 0x0)) {
+ //
+ // Check if this is a valid Detailed Timing Descriptor
+ // If first 2 bytes are zero, it is monitor descriptor other than detailed timing descriptor
+ //
+ continue;
+ }
+ //
+ // Calculate Horizontal and Vertical resolution
+ //
+ TempTiming.HorizontalResolution = ((UINT16)(BufferIndex[4] & 0xF0) << 4) | (BufferIndex[2]);
+ TempTiming.VerticalResolution = ((UINT16)(BufferIndex[7] & 0xF0) << 4) | (BufferIndex[5]);
+ DEBUG ((EFI_D_INFO, "Detailed Timing %d: %d x %d\n",
+ Index, TempTiming.HorizontalResolution, TempTiming.VerticalResolution));
+ ValidEdidTiming->Key[ValidNumber] = CalculateEdidKey (&TempTiming);
+ ValidNumber ++;
}
ValidEdidTiming->ValidNumber = ValidNumber;
@@ -1550,6 +1580,9 @@ BiosVideoCheckForVbe (
continue;
}
+ DEBUG ((EFI_D_INFO, "Video Controller Mode 0x%x: %d x %d\n",
+ VbeModeNumber, BiosVideoPrivate->VbeModeInformationBlock->XResolution, BiosVideoPrivate->VbeModeInformationBlock->YResolution));
+
if (EdidFound && (ValidEdidTiming.ValidNumber > 0)) {
//
// EDID exist, check whether this mode match with any mode in EDID
@@ -1593,8 +1626,9 @@ BiosVideoCheckForVbe (
//
// Record the highest resolution mode to set later
//
- if ((BiosVideoPrivate->VbeModeInformationBlock->XResolution >= HighestHorizontalResolution) &&
- (BiosVideoPrivate->VbeModeInformationBlock->YResolution >= HighestVerticalResolution)) {
+ if ((BiosVideoPrivate->VbeModeInformationBlock->XResolution > HighestHorizontalResolution) ||
+ ((BiosVideoPrivate->VbeModeInformationBlock->XResolution == HighestHorizontalResolution) &&
+ (BiosVideoPrivate->VbeModeInformationBlock->YResolution > HighestVerticalResolution))) {
HighestHorizontalResolution = BiosVideoPrivate->VbeModeInformationBlock->XResolution;
HighestVerticalResolution = BiosVideoPrivate->VbeModeInformationBlock->YResolution;
HighestResolutionMode = ModeNumber;
diff --git a/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VesaBiosExtensions.h b/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VesaBiosExtensions.h
index dcda3fcd5..25eee6921 100644
--- a/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VesaBiosExtensions.h
+++ b/IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VesaBiosExtensions.h
@@ -1,6 +1,6 @@
/** @file
-Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -168,6 +168,21 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#define VESA_BIOS_EXTENSIONS_EDID_BLOCK_SIZE 128
#define VESA_BIOS_EXTENSIONS_EDID_ESTABLISHED_TIMING_MAX_NUMBER 17
+//
+// Established Timings: 24 possible resolutions
+// Standard Timings: 8 possible resolutions
+// Detailed Timings: 4 possible resolutions
+//
+#define VESA_BIOS_EXTENSIONS_EDID_TIMING_MAX_NUMBER 36
+
+//
+// Timing data size for Established Timings, Standard Timings and Detailed Timings
+//
+#define VESA_BIOS_EXTENSIONS_ESTABLISHED_TIMING_SIZE 3
+#define VESA_BIOS_EXTENSIONS_STANDARD_TIMING_SIZE 16
+#define VESA_BIOS_EXTENSIONS_DETAILED_TIMING_EACH_DESCRIPTOR_SIZE 18
+#define VESA_BIOS_EXTENSIONS_DETAILED_TIMING_DESCRIPTOR_MAX_SIZE 72
+
typedef struct {
UINT16 HorizontalResolution;
UINT16 VerticalResolution;
@@ -176,7 +191,7 @@ typedef struct {
typedef struct {
UINT32 ValidNumber;
- UINT32 Key[VESA_BIOS_EXTENSIONS_EDID_ESTABLISHED_TIMING_MAX_NUMBER];
+ UINT32 Key[VESA_BIOS_EXTENSIONS_EDID_TIMING_MAX_NUMBER];
} VESA_BIOS_EXTENSIONS_VALID_EDID_TIMING;
typedef struct {
@@ -203,9 +218,9 @@ typedef struct {
UINT8 BlueY; //Blue-y Bits 9 - 2
UINT8 WhiteX; //White-x Bits 9 - 2
UINT8 WhiteY; //White-x Bits 9 - 2
- UINT8 EstablishedTimings[3];
- UINT8 StandardTimingIdentification[16];
- UINT8 DetailedTimingDescriptions[72];
+ UINT8 EstablishedTimings[VESA_BIOS_EXTENSIONS_ESTABLISHED_TIMING_SIZE];
+ UINT8 StandardTimingIdentification[VESA_BIOS_EXTENSIONS_STANDARD_TIMING_SIZE];
+ UINT8 DetailedTimingDescriptions[VESA_BIOS_EXTENSIONS_DETAILED_TIMING_DESCRIPTOR_MAX_SIZE];
UINT8 ExtensionFlag; //Number of (optional) 128-byte EDID extension blocks to follow
UINT8 Checksum;
} VESA_BIOS_EXTENSIONS_EDID_DATA_BLOCK;
diff --git a/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c b/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c
index 38226d0dc..08c6cad6f 100644
--- a/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c
+++ b/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiS3Save.c
@@ -2,7 +2,7 @@
This is an implementation of the ACPI S3 Save protocol. This is defined in
S3 boot path specification 0.9.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -74,8 +74,8 @@ EFI_GUID mAcpiS3IdtrProfileGuid = {
**/
VOID*
AllocateMemoryBelow4G (
- IN UINTN MemoryType,
- IN UINTN Size
+ IN EFI_MEMORY_TYPE MemoryType,
+ IN UINTN Size
)
{
UINTN Pages;
diff --git a/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c b/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c
index e2cfdbcb6..641a0ae0c 100644
--- a/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c
+++ b/IntelFrameworkModulePkg/Universal/Acpi/AcpiS3SaveDxe/AcpiVariableThunkPlatform.c
@@ -1,7 +1,7 @@
/** @file
This is an implementation of the AcpiVariable platform field for ECP platform.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -59,8 +59,8 @@ ACPI_VARIABLE_SET_COMPATIBILITY *mAcpiVariableSetCompatibility = N
**/
VOID*
AllocateMemoryBelow4G (
- IN UINTN MemoryType,
- IN UINTN Size
+ IN EFI_MEMORY_TYPE MemoryType,
+ IN UINTN Size
);
/**
diff --git a/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c b/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c
index 5486a5c53..f9b83a449 100644
--- a/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c
+++ b/IntelFrameworkModulePkg/Universal/BdsDxe/BdsEntry.c
@@ -5,7 +5,7 @@
After DxeCore finish DXE phase, gEfiBdsArchProtocolGuid->BdsEntry will be invoked
to enter BDS phase.
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -486,6 +486,7 @@ BdsEntry (
//
// Fixup Tasble CRC after we updated Firmware Vendor and Revision
//
+ gST->Hdr.CRC32 = 0;
gBS->CalculateCrc32 ((VOID *)gST, sizeof(EFI_SYSTEM_TABLE), &gST->Hdr.CRC32);
//
diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c
index c6fe51bf5..76e35ff03 100644
--- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c
+++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c
@@ -1,7 +1,7 @@
/** @file
PCI eunmeration implementation on entire PCI bus system for PCI Bus module.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -1035,6 +1035,11 @@ PciHostBridgeAdjustAllocation (
//
Status = RejectPciDevice (PciResNode->PciDev);
if (Status == EFI_SUCCESS) {
+ DEBUG ((
+ EFI_D_ERROR,
+ "PciBus: [%02x|%02x|%02x] was rejected due to resource confliction.\n",
+ PciResNode->PciDev->BusNumber, PciResNode->PciDev->DeviceNumber, PciResNode->PciDev->FunctionNumber
+ ));
//
// Raise the EFI_IOB_EC_RESOURCE_CONFLICT status code
@@ -1867,7 +1872,7 @@ NotifyPhase (
);
}
- return EFI_SUCCESS;
+ return Status;
}
/**
diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c
index 4e73b8f56..9e1184e00 100644
--- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c
+++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c
@@ -1,7 +1,7 @@
/** @file
Internal library implementation for PCI Bus module.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -568,6 +568,12 @@ PciHostBridgeResourceAllocator (
RootBridgeDev->Handle,
AcpiConfig
);
+ //
+ // If SubmitResources returns error, PciBus isn't able to start.
+ // It's a fatal error so assertion is added.
+ //
+ DEBUG ((EFI_D_INFO, "PciBus: HostBridge->SubmitResources() - %r\n", Status));
+ ASSERT_EFI_ERROR (Status);
}
//
@@ -598,6 +604,7 @@ PciHostBridgeResourceAllocator (
// Notify platform to start to program the resource
//
Status = NotifyPhase (PciResAlloc, EfiPciHostBridgeAllocateResources);
+ DEBUG ((EFI_D_INFO, "PciBus: HostBridge->NotifyPhase(AllocateResources) - %r\n", Status));
if (!FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) {
//
// If Hot Plug is not supported
diff --git a/MdeModulePkg/Core/Pei/Image/Image.c b/MdeModulePkg/Core/Pei/Image/Image.c
index 41069e7a3..045d8331d 100644
--- a/MdeModulePkg/Core/Pei/Image/Image.c
+++ b/MdeModulePkg/Core/Pei/Image/Image.c
@@ -348,6 +348,7 @@ LoadAndRelocatePeCoffImage (
EFI_STATUS Status;
PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
PEI_CORE_INSTANCE *Private;
+ UINT64 AlignImageSize;
Private = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ());
@@ -377,6 +378,19 @@ LoadAndRelocatePeCoffImage (
// Allocate Memory for the image when memory is ready, boot mode is not S3, and image is relocatable.
//
if ((!ImageContext.RelocationsStripped) && (Private->PeiMemoryInstalled) && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) {
+ //
+ // Allocate more buffer to avoid buffer overflow.
+ //
+ if (ImageContext.IsTeImage) {
+ AlignImageSize = ImageContext.ImageSize + ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER);
+ } else {
+ AlignImageSize = ImageContext.ImageSize;
+ }
+
+ if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) {
+ AlignImageSize += ImageContext.SectionAlignment;
+ }
+
if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
Status = GetPeCoffImageFixLoadingAssignedAddress(&ImageContext, Private);
if (EFI_ERROR (Status)){
@@ -384,10 +398,10 @@ LoadAndRelocatePeCoffImage (
//
// The PEIM is not assiged valid address, try to allocate page to load it.
//
- ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocatePages (EFI_SIZE_TO_PAGES ((UINT32) ImageContext.ImageSize));
+ ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocatePages (EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize));
}
} else {
- ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocatePages (EFI_SIZE_TO_PAGES ((UINT32) ImageContext.ImageSize));
+ ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocatePages (EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize));
}
ASSERT (ImageContext.ImageAddress != 0);
if (ImageContext.ImageAddress == 0) {
@@ -395,6 +409,15 @@ LoadAndRelocatePeCoffImage (
}
//
+ // If necessary, adjust the Image Address to make sure it is section alignment.
+ //
+ if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) {
+ ImageContext.ImageAddress =
+ (ImageContext.ImageAddress + ImageContext.SectionAlignment - 1) &
+ ~((UINTN)ImageContext.SectionAlignment - 1);
+ }
+ //
+ // Fix alignment requirement when Load IPF TeImage into memory.
// Skip the reserved space for the stripped PeHeader when load TeImage into memory.
//
if (ImageContext.IsTeImage) {
diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c
index afb4c1077..cba331a3b 100644
--- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c
+++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c
@@ -1,7 +1,7 @@
/** @file
Interpret and execute the S3 data in S3 boot script.
- Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -1176,7 +1176,7 @@ BootScriptExecuteMemPoll (
}
for (LoopTimes = 0; LoopTimes < MemPoll.LoopTimes; LoopTimes++) {
- NanoSecondDelay ((UINTN)MemPoll.Duration);
+ MicroSecondDelay ((UINTN)MemPoll.Duration);
Data = 0;
Status = ScriptMemoryRead (
diff --git a/MdeModulePkg/Library/UefiHiiLib/HiiLib.c b/MdeModulePkg/Library/UefiHiiLib/HiiLib.c
index ba74d0f88..0e7ddee35 100644
--- a/MdeModulePkg/Library/UefiHiiLib/HiiLib.c
+++ b/MdeModulePkg/Library/UefiHiiLib/HiiLib.c
@@ -946,7 +946,7 @@ InternalHiiValidateCurrentSetting (
UINT16 Offset;
UINT16 Width;
UINT64 VarValue;
- UINT64 TmpValue;
+ EFI_IFR_TYPE_VALUE TmpValue;
LIST_ENTRY *Link;
UINT8 *VarBuffer;
UINTN MaxBufferSize;
@@ -1511,9 +1511,10 @@ InternalHiiValidateCurrentSetting (
//
// Check current value is the value of one of option.
//
- TmpValue = 0;
+ ASSERT (IfrOneOfOption->Type <= EFI_IFR_TYPE_NUM_SIZE_64);
+ ZeroMem (&TmpValue, sizeof (EFI_IFR_TYPE_VALUE));
CopyMem (&TmpValue, &IfrOneOfOption->Value, IfrOneOfOption->Header.Length - OFFSET_OF (EFI_IFR_ONE_OF_OPTION, Value));
- if (VarValue == TmpValue) {
+ if (VarValue == TmpValue.u64) {
//
// The value is one of option value.
// Set OpCode to Zero, don't need check again.
diff --git a/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c b/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c
index 54ea20aa7..a8944e600 100644
--- a/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c
+++ b/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c
@@ -3,7 +3,7 @@
Set a IDT entry for interrupt vector 3 for debug purpose for x64 platform
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -48,6 +48,7 @@ HookPageFaultHandler (
{
UINT32 RegEax;
UINT32 RegEdx;
+ UINTN PageFaultHandlerHookAddress;
AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL);
mPhyMask = LShiftU64 (1, (UINT8)RegEax) - 1;
@@ -67,13 +68,14 @@ HookPageFaultHandler (
//
// Set Page Fault entry to catch >4G access
//
+ PageFaultHandlerHookAddress = (UINTN)PageFaultHandlerHook;
mOriginalHandler = (VOID *)(UINTN)(LShiftU64 (IdtEntry->Bits.OffsetUpper, 32) + IdtEntry->Bits.OffsetLow + (IdtEntry->Bits.OffsetHigh << 16));
- IdtEntry->Bits.OffsetLow = (UINT16)((UINTN)PageFaultHandlerHook);
+ IdtEntry->Bits.OffsetLow = (UINT16)PageFaultHandlerHookAddress;
IdtEntry->Bits.Selector = (UINT16)AsmReadCs ();
IdtEntry->Bits.Reserved_0 = 0;
IdtEntry->Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
- IdtEntry->Bits.OffsetHigh = (UINT16)((UINTN)PageFaultHandlerHook >> 16);
- IdtEntry->Bits.OffsetUpper = (UINT32)((UINTN)PageFaultHandlerHook >> 32);
+ IdtEntry->Bits.OffsetHigh = (UINT16)(PageFaultHandlerHookAddress >> 16);
+ IdtEntry->Bits.OffsetUpper = (UINT32)(PageFaultHandlerHookAddress >> 32);
IdtEntry->Bits.Reserved_1 = 0;
if (mPage1GSupport) {
diff --git a/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveState.c b/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveState.c
index 249fb8caf..60cd9b1b3 100644
--- a/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveState.c
+++ b/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveState.c
@@ -1,7 +1,7 @@
/** @file
Implementation for S3 Boot Script Saver state driver.
- Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -344,16 +344,33 @@ BootScriptWriteMemPoll (
VOID *Data;
VOID *DataMask;
UINTN Delay;
-
+ UINTN LoopTimes;
+ UINT32 Remainder;
+
Width = VA_ARG (Marker, S3_BOOT_SCRIPT_LIB_WIDTH);
Address = VA_ARG (Marker, UINT64);
Data = VA_ARG (Marker, VOID *);
DataMask = VA_ARG (Marker, VOID *);
Delay = (UINTN)VA_ARG (Marker, UINT64);
//
- // According to the spec, the interval between 2 pools is 100ns
- //
- return S3BootScriptSaveMemPoll (Width, Address, DataMask, Data, 100, Delay);
+ // According to the spec, the interval between 2 polls is 100ns,
+ // but the unit of Duration for S3BootScriptSaveMemPoll() is microsecond(1000ns).
+ // Duration * 1000ns * LoopTimes = Delay * 100ns
+ // Duration will be minimum 1(microsecond) to be minimum deviation,
+ // so LoopTimes = Delay / 10.
+ //
+ LoopTimes = (UINTN) DivU64x32Remainder (
+ Delay,
+ 10,
+ &Remainder
+ );
+ if (Remainder != 0) {
+ //
+ // If Remainder is not zero, LoopTimes will be rounded up by 1.
+ //
+ LoopTimes +=1;
+ }
+ return S3BootScriptSaveMemPoll (Width, Address, DataMask, Data, 1, LoopTimes);
}
diff --git a/MdeModulePkg/Universal/Acpi/SmmS3SaveState/SmmS3SaveState.c b/MdeModulePkg/Universal/Acpi/SmmS3SaveState/SmmS3SaveState.c
index d0652d3fd..e4227282c 100644
--- a/MdeModulePkg/Universal/Acpi/SmmS3SaveState/SmmS3SaveState.c
+++ b/MdeModulePkg/Universal/Acpi/SmmS3SaveState/SmmS3SaveState.c
@@ -1,7 +1,7 @@
/** @file
Implementation for S3 SMM Boot Script Saver state driver.
- Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
@@ -343,16 +343,33 @@ BootScriptWriteMemPoll (
VOID *Data;
VOID *DataMask;
UINTN Delay;
-
+ UINTN LoopTimes;
+ UINT32 Remainder;
+
Width = VA_ARG (Marker, S3_BOOT_SCRIPT_LIB_WIDTH);
Address = VA_ARG (Marker, UINT64);
Data = VA_ARG (Marker, VOID *);
DataMask = VA_ARG (Marker, VOID *);
Delay = (UINTN)VA_ARG (Marker, UINT64);
//
- // According to the spec, the interval between 2 pools is 100ns
- //
- return S3BootScriptSaveMemPoll (Width, Address, DataMask, Data, 100, Delay);
+ // According to the spec, the interval between 2 polls is 100ns,
+ // but the unit of Duration for S3BootScriptSaveMemPoll() is microsecond(1000ns).
+ // Duration * 1000ns * LoopTimes = Delay * 100ns
+ // Duration will be minimum 1(microsecond) to be minimum deviation,
+ // so LoopTimes = Delay / 10.
+ //
+ LoopTimes = (UINTN) DivU64x32Remainder (
+ Delay,
+ 10,
+ &Remainder
+ );
+ if (Remainder != 0) {
+ //
+ // If Remainder is not zero, LoopTimes will be rounded up by 1.
+ //
+ LoopTimes +=1;
+ }
+ return S3BootScriptSaveMemPoll (Width, Address, DataMask, Data, 1, LoopTimes);
}
diff --git a/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsole.c b/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsole.c
index 212564a5c..09e82b091 100644
--- a/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsole.c
+++ b/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsole.c
@@ -1,7 +1,7 @@
/** @file
This is the main routine for initializing the Graphics Console support routines.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -453,8 +453,8 @@ GraphicsConsoleControllerDriverStart (
&Info
);
if (!EFI_ERROR (Status)) {
- if ((Info->HorizontalResolution >= HorizontalResolution) &&
- (Info->VerticalResolution >= VerticalResolution)) {
+ if ((Info->HorizontalResolution > HorizontalResolution) ||
+ ((Info->HorizontalResolution == HorizontalResolution) && (Info->VerticalResolution > VerticalResolution))) {
HorizontalResolution = Info->HorizontalResolution;
VerticalResolution = Info->VerticalResolution;
ModeNumber = ModeIndex;
diff --git a/MdeModulePkg/Universal/Disk/PartitionDxe/Mbr.c b/MdeModulePkg/Universal/Disk/PartitionDxe/Mbr.c
index 4c6466374..f8416d16c 100644
--- a/MdeModulePkg/Universal/Disk/PartitionDxe/Mbr.c
+++ b/MdeModulePkg/Universal/Disk/PartitionDxe/Mbr.c
@@ -155,6 +155,15 @@ PartitionInstallMbrChildHandles (
BlockSize,
Mbr
);
+
+ // RMH - hack - Linaro's development boards use SD cards, currently we have
+ // a problem where each unique SD card has a different UUID when created
+ // with linaro-media-create / linaro-android-media create.
+ // This means that no one Boot Device configuration can boot Linaro images
+ // without some manual intervention from the user.
+ // This hack will zero the signature (UUID) read from the card.
+ ZeroMem(&(Mbr->UniqueMbrSignature[0]), sizeof (Mbr->UniqueMbrSignature));
+
if (EFI_ERROR (Status)) {
Found = Status;
goto Done;
diff --git a/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.c b/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.c
index 854a5a729..3ae55de2b 100644
--- a/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.c
+++ b/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.c
@@ -2,7 +2,7 @@
This is an example of how a driver might export data to the HII protocol to be
later utilized by the Setup Protocol
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -1766,44 +1766,6 @@ DriverCallback (
return Status;
}
-
-/**
- Transfer the binary device path to string.
-
- @param DevicePath The device path info.
-
- @retval Device path string info.
-
-**/
-CHAR16 *
-GenerateDevicePathString (
- EFI_DEVICE_PATH_PROTOCOL *DevicePath
- )
-{
- CHAR16 *String;
- CHAR16 *TmpBuf;
- UINTN Index;
- UINT8 *Buffer;
- UINTN DevicePathSize;
-
- //
- // Compute the size of the device path in bytes
- //
- DevicePathSize = GetDevicePathSize (DevicePath);
-
- String = AllocateZeroPool ((DevicePathSize * 2 + 1) * sizeof (CHAR16));
- if (String == NULL) {
- return NULL;
- }
-
- TmpBuf = String;
- for (Index = 0, Buffer = (UINT8 *)DevicePath; Index < DevicePathSize; Index++) {
- TmpBuf += UnicodeValueToString (TmpBuf, PREFIX_ZERO | RADIX_HEX, *(Buffer++), 2);
- }
-
- return String;
-}
-
/**
Main entry for this driver.
@@ -1835,12 +1797,14 @@ DriverSampleInit (
MY_EFI_VARSTORE_DATA *VarStoreConfig;
EFI_INPUT_KEY HotKey;
EFI_FORM_BROWSER_EXTENSION_PROTOCOL *FormBrowserEx;
+ EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *PathToText;
//
// Initialize the local variables.
//
ConfigRequestHdr = NULL;
NewString = NULL;
+ PathToText = NULL;
//
// Initialize screen dimensions for SendForm().
@@ -1957,11 +1921,18 @@ DriverSampleInit (
}
PrivateData->HiiHandle[1] = HiiHandle[1];
+
+ Status = gBS->LocateProtocol (
+ &gEfiDevicePathToTextProtocolGuid,
+ NULL,
+ (VOID **) &PathToText
+ );
+ ASSERT_EFI_ERROR (Status);
//
// Update the device path string.
//
- NewString = GenerateDevicePathString((EFI_DEVICE_PATH_PROTOCOL*)&mHiiVendorDevicePath0);
+ NewString = PathToText->ConvertDevicePathToText((EFI_DEVICE_PATH_PROTOCOL*)&mHiiVendorDevicePath0, FALSE, FALSE);
if (HiiSetString (HiiHandle[0], STRING_TOKEN (STR_DEVICE_PATH), NewString, NULL) == 0) {
DriverSampleUnload (ImageHandle);
return EFI_OUT_OF_RESOURCES;
diff --git a/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.h b/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.h
index 07ace6485..cd546bf38 100644
--- a/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.h
+++ b/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.h
@@ -1,6 +1,6 @@
/** @file
-Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -32,6 +32,7 @@ Revision History
#include <Protocol/HiiDatabase.h>
#include <Protocol/HiiString.h>
#include <Protocol/FormBrowserEx.h>
+#include <Protocol/DevicePathToText.h>
#include <Guid/MdeModuleHii.h>
#include <Library/DebugLib.h>
diff --git a/MdeModulePkg/Universal/DriverSampleDxe/DriverSampleDxe.inf b/MdeModulePkg/Universal/DriverSampleDxe/DriverSampleDxe.inf
index bcc157442..36511e66d 100644
--- a/MdeModulePkg/Universal/DriverSampleDxe/DriverSampleDxe.inf
+++ b/MdeModulePkg/Universal/DriverSampleDxe/DriverSampleDxe.inf
@@ -2,7 +2,7 @@
# This is a sample driver which show how HII protocol, VFR and UNI files are used to
# create a driver which can be dipslayed and configured by a UEFI HII Form Browser.
#
-# Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -70,6 +70,7 @@
gEfiHiiDatabaseProtocolGuid ## CONSUMES
gEfiSimpleTextInputExProtocolGuid ## CONSUMES
gEfiFormBrowserExProtocolGuid ## CONSUMES
+ gEfiDevicePathToTextProtocolGuid ## CONSUMES
[Depex]
gEfiSimpleTextOutProtocolGuid AND gEfiHiiDatabaseProtocolGuid AND gEfiVariableArchProtocolGuid AND gEfiVariableWriteArchProtocolGuid
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c b/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c
index 3766ca12f..a8010671b 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c
@@ -1,7 +1,7 @@
/** @file
Utility functions for expression evaluation.
-Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -2470,22 +2470,21 @@ EvaluateExpression (
}
if (OpCode->DevicePath != 0) {
- StrPtr = GetToken (OpCode->DevicePath, FormSet->HiiHandle);
- if (StrPtr == NULL) {
- Value->Type = EFI_IFR_TYPE_UNDEFINED;
- break;
- }
-
- DevicePath = ConvertDevicePathFromText(StrPtr);
+ Value->Type = EFI_IFR_TYPE_UNDEFINED;
- if (!GetQuestionValueFromForm(DevicePath, NULL, &OpCode->Guid, Value->Value.u16, &QuestionVal)){
- Value->Type = EFI_IFR_TYPE_UNDEFINED;
- } else {
- Value = &QuestionVal;
+ StrPtr = GetToken (OpCode->DevicePath, FormSet->HiiHandle);
+ if (StrPtr != NULL && mPathFromText != NULL) {
+ DevicePath = mPathFromText->ConvertTextToDevicePath(StrPtr);
+ if (DevicePath != NULL && GetQuestionValueFromForm(DevicePath, NULL, &OpCode->Guid, Value->Value.u16, &QuestionVal)) {
+ Value = &QuestionVal;
+ }
+ if (DevicePath != NULL) {
+ FreePool (DevicePath);
+ }
}
- if (DevicePath != NULL) {
- FreePool (DevicePath);
+ if (StrPtr != NULL) {
+ FreePool (StrPtr);
}
} else if (CompareGuid (&OpCode->Guid, &gZeroGuid) != 0) {
if (!GetQuestionValueFromForm(NULL, FormSet->HiiHandle, &OpCode->Guid, Value->Value.u16, &QuestionVal)){
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Presentation.c b/MdeModulePkg/Universal/SetupBrowserDxe/Presentation.c
index 62811c751..ee8ab75a2 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/Presentation.c
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/Presentation.c
@@ -1,7 +1,7 @@
/** @file
Utility functions for UI presentation.
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -602,6 +602,7 @@ InitializeBrowserStrings (
gSaveChanges = GetToken (STRING_TOKEN (SAVE_CHANGES), gHiiHandle);
gOptionMismatch = GetToken (STRING_TOKEN (OPTION_MISMATCH), gHiiHandle);
gFormSuppress = GetToken (STRING_TOKEN (FORM_SUPPRESSED), gHiiHandle);
+ gProtocolNotFound = GetToken (STRING_TOKEN (PROTOCOL_NOT_FOUND), gHiiHandle);
return ;
}
@@ -642,6 +643,7 @@ FreeBrowserStrings (
FreePool (gSaveChanges);
FreePool (gOptionMismatch);
FreePool (gFormSuppress);
+ FreePool (gProtocolNotFound);
return ;
}
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Setup.c b/MdeModulePkg/Universal/SetupBrowserDxe/Setup.c
index bcc8e020f..15b943ffe 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/Setup.c
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/Setup.c
@@ -1,7 +1,7 @@
/** @file
Entry and initialization module for the browser.
-Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -32,6 +32,7 @@ SETUP_DRIVER_PRIVATE_DATA mPrivateData = {
EFI_HII_DATABASE_PROTOCOL *mHiiDatabase;
EFI_HII_STRING_PROTOCOL *mHiiString;
EFI_HII_CONFIG_ROUTING_PROTOCOL *mHiiConfigRouting;
+EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL *mPathFromText;
UINTN gBrowserContextCount = 0;
LIST_ENTRY gBrowserContextList = INITIALIZE_LIST_HEAD_VARIABLE (gBrowserContextList);
@@ -84,6 +85,7 @@ CHAR16 *gAdjustNumber;
CHAR16 *gSaveChanges;
CHAR16 *gOptionMismatch;
CHAR16 *gFormSuppress;
+CHAR16 *gProtocolNotFound;
CHAR16 *mUnknownString = L"!";
@@ -662,6 +664,12 @@ InitializeSetup (
);
ASSERT_EFI_ERROR (Status);
+ Status = gBS->LocateProtocol (
+ &gEfiDevicePathFromTextProtocolGuid,
+ NULL,
+ (VOID **) &mPathFromText
+ );
+
//
// Publish our HII data
//
@@ -4107,6 +4115,7 @@ SaveBrowserContext (
Context->HelpBlockWidth = gHelpBlockWidth;
Context->OldFormSet = gOldFormSet;
Context->MenuRefreshHead = gMenuRefreshHead;
+ Context->ProtocolNotFound = gProtocolNotFound;
CopyMem (&Context->ScreenDimensions, &gScreenDimensions, sizeof (gScreenDimensions));
CopyMem (&Context->MenuOption, &gMenuOption, sizeof (gMenuOption));
@@ -4184,6 +4193,7 @@ RestoreBrowserContext (
gHelpBlockWidth = Context->HelpBlockWidth;
gOldFormSet = Context->OldFormSet;
gMenuRefreshHead = Context->MenuRefreshHead;
+ gProtocolNotFound = Context->ProtocolNotFound;
CopyMem (&gScreenDimensions, &Context->ScreenDimensions, sizeof (gScreenDimensions));
CopyMem (&gMenuOption, &Context->MenuOption, sizeof (gMenuOption));
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Setup.h b/MdeModulePkg/Universal/SetupBrowserDxe/Setup.h
index e11cdc16d..8e32cb4e4 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/Setup.h
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/Setup.h
@@ -1,7 +1,7 @@
/** @file
Private MACRO, structure and function definitions for Setup Browser module.
-Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -30,6 +30,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#include <Protocol/HiiDatabase.h>
#include <Protocol/HiiString.h>
#include <Protocol/UserManager.h>
+#include <Protocol/DevicePathFromText.h>
#include <Guid/MdeModuleHii.h>
#include <Guid/HiiPlatformSetupFormset.h>
@@ -546,6 +547,7 @@ typedef struct {
CHAR16 *SaveChanges;
CHAR16 *OptionMismatch;
CHAR16 *FormSuppress;
+ CHAR16 *ProtocolNotFound;
CHAR16 PromptBlockWidth;
CHAR16 OptionBlockWidth;
CHAR16 HelpBlockWidth;
@@ -597,6 +599,7 @@ typedef enum {
extern EFI_HII_DATABASE_PROTOCOL *mHiiDatabase;
extern EFI_HII_STRING_PROTOCOL *mHiiString;
extern EFI_HII_CONFIG_ROUTING_PROTOCOL *mHiiConfigRouting;
+extern EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL *mPathFromText;
extern BANNER_DATA *gBannerData;
extern EFI_HII_HANDLE gFrontPageHandle;
@@ -647,6 +650,7 @@ extern CHAR16 *gAdjustNumber;
extern CHAR16 *gSaveChanges;
extern CHAR16 *gOptionMismatch;
extern CHAR16 *gFormSuppress;
+extern CHAR16 *gProtocolNotFound;
extern CHAR16 gPromptBlockWidth;
extern CHAR16 gOptionBlockWidth;
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf b/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
index 2edbd3ad1..2a4cda41e 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
@@ -1,7 +1,7 @@
## @file
# The DXE driver produces FORM BROWSER protocols defined in UEFI HII 2.1 specificatin.
#
-# Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -75,6 +75,7 @@
gEfiHiiDatabaseProtocolGuid ## CONSUMES
gEfiUnicodeCollation2ProtocolGuid ## CONSUMES
gEfiUserManagerProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiDevicePathFromTextProtocolGuid ## SOMETIMES_CONSUMES
[FeaturePcd]
gEfiMdeModulePkgTokenSpaceGuid.PcdFrameworkCompatibilitySupport ## CONSUMES
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserStr.uni b/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserStr.uni
index b155a5577..bb6414d20 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserStr.uni
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserStr.uni
Binary files differ
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Ui.c b/MdeModulePkg/Universal/SetupBrowserDxe/Ui.c
index b011ad39e..8ff90e144 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/Ui.c
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/Ui.c
@@ -1,7 +1,7 @@
/** @file
Utility functions for User Interface functions.
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -1507,36 +1507,34 @@ UpdateOptionSkipLines (
Row = 0;
OptionString = NULL;
+ Width = (UINT16) gOptionBlockWidth;
+ OriginalRow = 0;
+ GlyphWidth = 1;
+
ProcessOptions (Selection, MenuOption, FALSE, &OptionString);
+ if (OptionString == NULL) {
+ return;
+ }
- if (OptionString != NULL) {
- Width = (UINT16) gOptionBlockWidth;
-
- OriginalRow = Row;
- GlyphWidth = 1;
-
- for (Index = 0; GetLineByWidth (OptionString, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
+ for (Index = 0; GetLineByWidth (OptionString, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
+ //
+ // If there is more string to process print on the next row and increment the Skip value
+ //
+ if (StrLen (&OptionString[Index]) != 0) {
+ Row++;
//
- // If there is more string to process print on the next row and increment the Skip value
+ // Since the Number of lines for this menu entry may or may not be reflected accurately
+ // since the prompt might be 1 lines and option might be many, and vice versa, we need to do
+ // some testing to ensure we are keeping this in-sync.
//
- if (StrLen (&OptionString[Index]) != 0) {
- Row++;
- //
- // Since the Number of lines for this menu entry may or may not be reflected accurately
- // since the prompt might be 1 lines and option might be many, and vice versa, we need to do
- // some testing to ensure we are keeping this in-sync.
- //
- // If the difference in rows is greater than or equal to the skip value, increase the skip value
- //
- if ((Row - OriginalRow) >= MenuOption->Skip) {
- MenuOption->Skip++;
- }
+ // If the difference in rows is greater than or equal to the skip value, increase the skip value
+ //
+ if ((Row - OriginalRow) >= MenuOption->Skip) {
+ MenuOption->Skip++;
}
-
- FreePool (OutputString);
}
- Row = OriginalRow;
+ FreePool (OutputString);
}
if (OptionString != NULL) {
@@ -1612,6 +1610,10 @@ ValueIsScroll (
@return The row distance from current MenuOption to next selectable MenuOption.
+ @retval -1 Reach the begin of the menu, still can't find the selectable menu.
+ @retval Value Find the selectable menu, maybe the truly selectable, maybe the l
+ last menu showing at current form.
+
**/
INTN
MoveToNextStatement (
@@ -1632,41 +1634,56 @@ MoveToNextStatement (
while (TRUE) {
NextMenuOption = MENU_OPTION_FROM_LINK (Pos);
+ //
+ // NextMenuOption->Row == 0 means this menu has not calculate
+ // the NextMenuOption->Skip value yet, just calculate here.
+ //
if (NextMenuOption->Row == 0) {
UpdateOptionSkipLines (Selection, NextMenuOption);
}
if (GoUp && (PreMenuOption != NextMenuOption)) {
//
- // Current Position doesn't need to be caculated when go up.
- // Caculate distanct at first when go up
+ // In this case, still can't find the selectable menu,
+ // return the last one in the showing form.
//
if ((UINTN) Distance + NextMenuOption->Skip > GapToTop) {
NextMenuOption = PreMenuOption;
break;
}
+
+ //
+ // Current Position doesn't need to be caculated when go up.
+ // Caculate distanct at first when go up
+ //
Distance += NextMenuOption->Skip;
}
+
if (IsSelectable (NextMenuOption)) {
break;
}
+
+ //
+ // Arrive at begin of the menu list.
+ //
if ((GoUp ? Pos->BackLink : Pos->ForwardLink) == &gMenuOption) {
- //
- // Arrive at top.
- //
Distance = -1;
break;
}
+
if (!GoUp) {
//
- // Caculate distanct at later when go down
+ // In this case, still can't find the selectable menu,
+ // return the last one in the showing form.
//
if ((UINTN) Distance + NextMenuOption->Skip > GapToTop) {
NextMenuOption = PreMenuOption;
break;
}
+
Distance += NextMenuOption->Skip;
}
+
PreMenuOption = NextMenuOption;
Pos = (GoUp ? Pos->BackLink : Pos->ForwardLink);
}
@@ -1954,55 +1971,6 @@ FormSetGuidToHiiHandle (
}
/**
- Transfer the device path string to binary format.
-
- @param StringPtr The device path string info.
-
- @retval Device path binary info.
-
-**/
-EFI_DEVICE_PATH_PROTOCOL *
-ConvertDevicePathFromText (
- IN CHAR16 *StringPtr
- )
-{
- UINTN BufferSize;
- EFI_DEVICE_PATH_PROTOCOL *DevicePath;
- CHAR16 TemStr[2];
- UINT8 *DevicePathBuffer;
- UINTN Index;
- UINT8 DigitUint8;
-
- ASSERT (StringPtr != NULL);
-
- BufferSize = StrLen (StringPtr) / 2;
- DevicePath = AllocatePool (BufferSize);
- ASSERT (DevicePath != NULL);
-
- //
- // Convert from Device Path String to DevicePath Buffer in the reverse order.
- //
- DevicePathBuffer = (UINT8 *) DevicePath;
- for (Index = 0; StringPtr[Index] != L'\0'; Index ++) {
- TemStr[0] = StringPtr[Index];
- DigitUint8 = (UINT8) StrHexToUint64 (TemStr);
- if (DigitUint8 == 0 && TemStr[0] != L'0') {
- //
- // Invalid Hex Char as the tail.
- //
- break;
- }
- if ((Index & 1) == 0) {
- DevicePathBuffer [Index/2] = DigitUint8;
- } else {
- DevicePathBuffer [Index/2] = (UINT8) ((DevicePathBuffer [Index/2] << 4) + DigitUint8);
- }
- }
-
- return DevicePath;
-}
-
-/**
Process the goto op code, update the info in the selection structure.
@param Statement The statement belong to goto op code.
@@ -2047,16 +2015,32 @@ ProcessGotoOpCode (
if (Selection->Form->ModalForm) {
return Status;
}
+
//
// Goto another Hii Package list
//
- Selection->Action = UI_ACTION_REFRESH_FORMSET;
- DevicePath = ConvertDevicePathFromText (StringPtr);
-
- Selection->Handle = DevicePathToHiiHandle (DevicePath);
- FreePool (DevicePath);
- FreePool (StringPtr);
+ if (mPathFromText != NULL) {
+ DevicePath = mPathFromText->ConvertTextToDevicePath(StringPtr);
+ if (DevicePath != NULL) {
+ Selection->Handle = DevicePathToHiiHandle (DevicePath);
+ FreePool (DevicePath);
+ }
+ FreePool (StringPtr);
+ } else {
+ //
+ // Not found the EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL protocol.
+ //
+ do {
+ CreateDialog (4, TRUE, 0, NULL, &Key, gEmptyString, gProtocolNotFound, gPressEnter, gEmptyString);
+ } while (Key.UnicodeChar != CHAR_CARRIAGE_RETURN);
+ if (Repaint != NULL) {
+ *Repaint = TRUE;
+ }
+ FreePool (StringPtr);
+ return Status;
+ }
+ Selection->Action = UI_ACTION_REFRESH_FORMSET;
if (Selection->Handle == NULL) {
//
// If target Hii Handle not found, exit
@@ -2173,7 +2157,6 @@ UiDisplayMenu (
{
INTN SkipValue;
INTN Difference;
- INTN OldSkipValue;
UINTN DistanceValue;
UINTN Row;
UINTN Col;
@@ -2254,7 +2237,6 @@ UiDisplayMenu (
UpArrow = FALSE;
DownArrow = FALSE;
SkipValue = 0;
- OldSkipValue = 0;
MenuRefreshEntry = gMenuRefreshHead;
NextMenuOption = NULL;
@@ -2355,6 +2337,9 @@ UiDisplayMenu (
Temp = (UINTN) SkipValue;
Temp2 = (UINTN) SkipValue;
+ //
+ // 1. Clear the screen.
+ //
if (Selection->Form->ModalForm) {
ClearLines (
LocalScreen.LeftColumn + ModalSkipColumn,
@@ -2375,6 +2360,9 @@ UiDisplayMenu (
UiFreeRefreshList ();
MinRefreshInterval = 0;
+ //
+ // 2.Paint the menu.
+ //
for (Link = TopOfScreen; Link != &gMenuOption; Link = Link->ForwardLink) {
MenuOption = MENU_OPTION_FROM_LINK (Link);
MenuOption->Row = Row;
@@ -2414,7 +2402,13 @@ UiDisplayMenu (
);
}
+ //
+ // 2.1. Paint the description.
+ //
for (Index = 0; GetLineByWidth (MenuOption->Description, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
+ //
+ // Temp means need to skip how many lines from the start.
+ //
if ((Temp == 0) && (Row <= BottomRow)) {
PrintStringAt (MenuOption->Col, Row, OutputString);
}
@@ -2436,6 +2430,9 @@ UiDisplayMenu (
Temp = 0;
Row = OriginalRow;
+ //
+ // 2.2. Paint the option string.
+ //
Status = ProcessOptions (Selection, MenuOption, FALSE, &OptionString);
if (EFI_ERROR (Status)) {
//
@@ -2492,7 +2489,7 @@ UiDisplayMenu (
}
//
- // If Question has refresh guid, register the op-code.
+ // 2.4 Special process for Test opcode with test two.
//
if (!CompareGuid (&Statement->RefreshGuid, &gZeroGuid)) {
if (gMenuEventGuidRefreshHead == NULL) {
@@ -2600,11 +2597,10 @@ UiDisplayMenu (
gST->ConOut->SetAttribute (gST->ConOut, PcdGet8 (PcdBrowserFieldTextColor) | FIELD_BACKGROUND);
//
- // Need to handle the bottom of the display
+ // 3. Update the row info which will be used by next menu.
//
- if (MenuOption->Skip > 1) {
+ if (Link == TopOfScreen) {
Row += MenuOption->Skip - SkipValue;
- SkipValue = 0;
} else {
Row += MenuOption->Skip;
}
@@ -2656,6 +2652,16 @@ UiDisplayMenu (
// NewPos: Current menu option that need to hilight
//
ControlFlag = CfUpdateHelpString;
+ if (TopOfScreen == &MenuOption->Link) {
+ Temp = SkipValue;
+ } else {
+ Temp = 0;
+ }
+ if (NewPos == TopOfScreen) {
+ Temp2 = SkipValue;
+ } else {
+ Temp2 = 0;
+ }
if (InitializedFlag) {
InitializedFlag = FALSE;
MoveToNextStatement (Selection, FALSE, &NewPos, BottomRow - TopRow);
@@ -2688,7 +2694,7 @@ UiDisplayMenu (
SavedMenuOption = MENU_OPTION_FROM_LINK (Link);
Index += SavedMenuOption->Skip;
if (Link == TopOfScreen) {
- Index -= OldSkipValue;
+ Index -= SkipValue;
}
Link = Link->ForwardLink;
}
@@ -2746,7 +2752,6 @@ UiDisplayMenu (
//
SkipValue = 0;
TopOfScreen = Link;
- OldSkipValue = SkipValue;
} else {
//
// Check whether need to skip some line for menu shows at the top of the page.
@@ -2754,7 +2759,6 @@ UiDisplayMenu (
SkipValue = Index - BottomRow - 1;
if (SkipValue > 0 && SkipValue < (INTN) SavedMenuOption->Skip) {
TopOfScreen = Link;
- OldSkipValue = SkipValue;
} else {
SkipValue = 0;
TopOfScreen = Link->ForwardLink;
@@ -2796,17 +2800,22 @@ UiDisplayMenu (
GlyphWidth = 1;
for (Index = 0; GetLineByWidth (OptionString, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
- if (MenuOption->Row >= TopRow && MenuOption->Row <= BottomRow) {
+ if ((Temp == 0) && (MenuOption->Row >= TopRow) && (MenuOption->Row <= BottomRow)) {
PrintStringAt (MenuOption->OptCol, MenuOption->Row, OutputString);
}
//
// If there is more string to process print on the next row and increment the Skip value
//
if (StrLen (&OptionString[Index]) != 0) {
- MenuOption->Row++;
+ if (Temp == 0) {
+ MenuOption->Row++;
+ }
}
FreePool (OutputString);
+ if (Temp != 0) {
+ Temp--;
+ }
}
MenuOption->Row = OriginalRow;
@@ -2825,17 +2834,22 @@ UiDisplayMenu (
GlyphWidth = 1;
for (Index = 0; GetLineByWidth (MenuOption->Description, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
- if (MenuOption->Row >= TopRow && MenuOption->Row <= BottomRow) {
+ if ((Temp == 0) && (MenuOption->Row >= TopRow) && (MenuOption->Row <= BottomRow)) {
PrintStringAt (MenuOption->Col, MenuOption->Row, OutputString);
}
//
// If there is more string to process print on the next row and increment the Skip value
//
if (StrLen (&MenuOption->Description[Index]) != 0) {
- MenuOption->Row++;
+ if (Temp == 0) {
+ MenuOption->Row++;
+ }
}
FreePool (OutputString);
+ if (Temp != 0) {
+ Temp--;
+ }
}
MenuOption->Row = OriginalRow;
@@ -2897,17 +2911,22 @@ UiDisplayMenu (
GlyphWidth = 1;
for (Index = 0; GetLineByWidth (OptionString, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
- if (MenuOption->Row >= TopRow && MenuOption->Row <= BottomRow) {
+ if ((Temp2 == 0) && (MenuOption->Row >= TopRow) && (MenuOption->Row <= BottomRow) ) {
PrintStringAt (MenuOption->OptCol, MenuOption->Row, OutputString);
}
//
// If there is more string to process print on the next row and increment the Skip value
//
if (StrLen (&OptionString[Index]) != 0) {
+ if (Temp2 == 0) {
MenuOption->Row++;
+ }
}
FreePool (OutputString);
+ if (Temp2 != 0) {
+ Temp2--;
+ }
}
MenuOption->Row = OriginalRow;
@@ -2921,17 +2940,22 @@ UiDisplayMenu (
GlyphWidth = 1;
for (Index = 0; GetLineByWidth (MenuOption->Description, Width, &GlyphWidth, &Index, &OutputString) != 0x0000;) {
- if (MenuOption->Row >= TopRow && MenuOption->Row <= BottomRow) {
+ if ((Temp2 == 0) && (MenuOption->Row >= TopRow) && (MenuOption->Row <= BottomRow) ) {
PrintStringAt (MenuOption->Col, MenuOption->Row, OutputString);
}
//
// If there is more string to process print on the next row and increment the Skip value
//
if (StrLen (&MenuOption->Description[Index]) != 0) {
- MenuOption->Row++;
+ if (Temp2 == 0) {
+ MenuOption->Row++;
+ }
}
FreePool (OutputString);
+ if (Temp2 != 0) {
+ Temp2--;
+ }
}
MenuOption->Row = OriginalRow;
@@ -3446,7 +3470,6 @@ UiDisplayMenu (
TopOfScreen = NewPos;
Repaint = TRUE;
SkipValue = 0;
- OldSkipValue = 0;
} else if (!IsSelectable (NextMenuOption)) {
//
// Continue to go up until scroll to next page or the selectable option is found.
@@ -3475,9 +3498,15 @@ UiDisplayMenu (
break;
case CfUiPageUp:
+ //
+ // SkipValue means lines is skipped when show the top menu option.
+ //
ControlFlag = CfCheckSelection;
ASSERT(NewPos != NULL);
+ //
+ // Already at the first menu option, so do nothing.
+ //
if (NewPos->BackLink == &gMenuOption) {
NewLine = FALSE;
Repaint = FALSE;
@@ -3486,8 +3515,22 @@ UiDisplayMenu (
NewLine = TRUE;
Repaint = TRUE;
+
+ //
+ // SkipValue > (BottomRow - TopRow + 1) means current menu has more than one
+ // form of options to be show, so just update the SkipValue to show the next
+ // parts of options.
+ //
+ if (SkipValue > (INTN) (BottomRow - TopRow + 1)) {
+ SkipValue -= BottomRow - TopRow + 1;
+ break;
+ }
+
Link = TopOfScreen;
- Index = BottomRow;
+ //
+ // First minus the menu of the top screen, it's value is SkipValue.
+ //
+ Index = (BottomRow + 1) - SkipValue;
while ((Index >= TopRow) && (Link->BackLink != &gMenuOption)) {
Link = Link->BackLink;
PreviousMenuOption = MENU_OPTION_FROM_LINK (Link);
@@ -3495,13 +3538,13 @@ UiDisplayMenu (
UpdateOptionSkipLines (Selection, PreviousMenuOption);
}
if (Index < PreviousMenuOption->Skip) {
- Index = 0;
break;
}
Index = Index - PreviousMenuOption->Skip;
}
if ((Link->BackLink == &gMenuOption) && (Index >= TopRow)) {
+ SkipValue = 0;
if (TopOfScreen == &gMenuOption) {
TopOfScreen = gMenuOption.ForwardLink;
NewPos = gMenuOption.BackLink;
@@ -3520,10 +3563,13 @@ UiDisplayMenu (
MoveToNextStatement (Selection, FALSE, &NewPos, BottomRow - TopRow);
}
} else {
- if (Index + 1 < TopRow) {
+ if (Index >= TopRow) {
//
- // Back up the previous option.
+ // At here, only case "Index < PreviousMenuOption->Skip" can reach here.
//
+ SkipValue = PreviousMenuOption->Skip - (Index - TopRow);
+ } else {
+ SkipValue = PreviousMenuOption->Skip - (TopRow - Index);
Link = Link->ForwardLink;
}
@@ -3554,6 +3600,9 @@ UiDisplayMenu (
break;
case CfUiPageDown:
+ //
+ // SkipValue means lines is skipped when show the top menu option.
+ //
ControlFlag = CfCheckSelection;
ASSERT (NewPos != NULL);
@@ -3567,47 +3616,62 @@ UiDisplayMenu (
Repaint = TRUE;
Link = TopOfScreen;
NextMenuOption = MENU_OPTION_FROM_LINK (Link);
- Index = TopRow;
- while ((Index <= BottomRow) && (Link->ForwardLink != &gMenuOption)) {
- Index = Index + NextMenuOption->Skip;
+ Index = TopRow + NextMenuOption->Skip - SkipValue;
+ //
+ // Count to the menu option which will show at the top of the next form.
+ //
+ while ((Index <= BottomRow + 1) && (Link->ForwardLink != &gMenuOption)) {
Link = Link->ForwardLink;
NextMenuOption = MENU_OPTION_FROM_LINK (Link);
+ Index = Index + NextMenuOption->Skip;
}
- if ((Link->ForwardLink == &gMenuOption) && (Index <= BottomRow)) {
+ if ((Link->ForwardLink == &gMenuOption) && (Index <= BottomRow + 1)) {
//
// Finally we know that NewPos is the last MenuOption can be focused.
//
Repaint = FALSE;
MoveToNextStatement (Selection, TRUE, &Link, Index - TopRow);
+ SkipValue = 0;
} else {
- if (Index - 1 > BottomRow) {
+ //
+ // Calculate the skip line for top of screen menu.
+ //
+ if (Link == TopOfScreen) {
//
- // Back up the previous option.
+ // The top of screen menu option occupies the entire form.
//
- Link = Link->BackLink;
+ SkipValue += BottomRow - TopRow + 1;
+ } else {
+ SkipValue = NextMenuOption->Skip - (Index - (BottomRow + 1));
}
- //
- // There are more MenuOption needing scrolling down.
- //
+
TopOfScreen = Link;
MenuOption = NULL;
//
- // Move to the option in Next page.
+ // Move to the Next selectable menu.
//
MoveToNextStatement (Selection, FALSE, &Link, BottomRow - TopRow);
}
//
+ // Save the menu as the next highlight menu.
+ //
+ NewPos = Link;
+
+ //
// If we encounter a Date/Time op-code set, rewind to the first op-code of the set.
// Don't do this when we are already in the last page.
//
- NewPos = Link;
AdjustDateAndTimePosition (TRUE, &TopOfScreen);
AdjustDateAndTimePosition (TRUE, &NewPos);
break;
case CfUiDown:
+ //
+ // SkipValue means lines is skipped when show the top menu option.
+ // NewPos points to the menu which is highlighted now.
+ //
ControlFlag = CfCheckSelection;
//
// Since the behavior of hitting the down arrow on a Date/Time op-code is intended
@@ -3626,8 +3690,14 @@ UiDisplayMenu (
NewPos = NewPos->ForwardLink;
Difference = 0;
+ //
+ // Current menu not at the bottom of the form.
+ //
if (BottomRow >= MenuOption->Row + MenuOption->Skip) {
- Difference = MoveToNextStatement (Selection, FALSE, &NewPos, BottomRow - MenuOption->Row - MenuOption->Skip);
+ //
+ // Find the next selectable menu.
+ //
+ Difference = MoveToNextStatement (Selection, FALSE, &NewPos, BottomRow - MenuOption->Row - MenuOption->Skip);
//
// We hit the end of MenuOption that can be focused
// so we simply scroll to the first page.
@@ -3645,7 +3715,8 @@ UiDisplayMenu (
}
NewPos = gMenuOption.ForwardLink;
MoveToNextStatement (Selection, FALSE, &NewPos, BottomRow - TopRow);
-
+
+ SkipValue = 0;
//
// If we are at the end of the list and sitting on a Date/Time op, rewind to the head.
//
@@ -3655,11 +3726,9 @@ UiDisplayMenu (
}
}
NextMenuOption = MENU_OPTION_FROM_LINK (NewPos);
-
- //
- // An option might be multi-line, so we need to reflect that data in the overall skip value
- //
- UpdateOptionSkipLines (Selection, NextMenuOption);
+ if (NextMenuOption->Row == 0) {
+ UpdateOptionSkipLines (Selection, NextMenuOption);
+ }
DistanceValue = Difference + NextMenuOption->Skip;
Temp = MenuOption->Row + MenuOption->Skip + DistanceValue - 1;
@@ -3684,18 +3753,16 @@ UiDisplayMenu (
//
// If bottom op-code is more than one line or top op-code is more than one line
//
- if ((DistanceValue > 1) || (MenuOption->Skip > 1)) {
+ if ((DistanceValue > 1) || (SavedMenuOption->Skip > 1)) {
//
// Is the bottom op-code greater than or equal in size to the top op-code?
//
- if ((Temp - BottomRow) >= (SavedMenuOption->Skip - OldSkipValue)) {
+ if ((Temp - BottomRow) >= (SavedMenuOption->Skip - SkipValue)) {
//
// Skip the top op-code
//
TopOfScreen = TopOfScreen->ForwardLink;
- Difference = (Temp - BottomRow) - (SavedMenuOption->Skip - OldSkipValue);
-
- OldSkipValue = Difference;
+ Difference = (Temp - BottomRow) - (SavedMenuOption->Skip - SkipValue);
SavedMenuOption = MENU_OPTION_FROM_LINK (TopOfScreen);
@@ -3715,20 +3782,17 @@ UiDisplayMenu (
// SkipValue, set the skips to one less than what is required.
//
SkipValue = Difference - 1;
-
} else {
//
// Since we will act on this op-code in the next routine, and increment the
// SkipValue, set the skips to one less than what is required.
//
- SkipValue = OldSkipValue + (Temp - BottomRow) - 1;
+ SkipValue += (Temp - BottomRow) - 1;
}
} else {
- if ((OldSkipValue + 1) == (INTN) SavedMenuOption->Skip) {
+ if ((SkipValue + 1) == (INTN) SavedMenuOption->Skip) {
TopOfScreen = TopOfScreen->ForwardLink;
break;
- } else {
- SkipValue = OldSkipValue;
}
}
//
@@ -3750,7 +3814,6 @@ UiDisplayMenu (
} while (SavedMenuOption->Skip == 0);
Repaint = TRUE;
- OldSkipValue = SkipValue;
} else if (!IsSelectable (NextMenuOption)) {
//
// Continue to go down until scroll to next page or the selectable option is found.
@@ -3772,9 +3835,18 @@ UiDisplayMenu (
Repaint = TRUE;
MenuOption = NULL;
} else {
+ //
+ // Need to remove the current highlight menu.
+ // MenuOption saved the last highlight menu info.
+ //
MenuOption = MENU_OPTION_FROM_LINK (SavedListEntry);
}
+
+ SkipValue = 0;
NewLine = TRUE;
+ //
+ // Get the next highlight menu.
+ //
NewPos = gMenuOption.ForwardLink;
MoveToNextStatement (Selection, FALSE, &NewPos, BottomRow - TopRow);
}
diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Ui.h b/MdeModulePkg/Universal/SetupBrowserDxe/Ui.h
index ac016bbed..4c3b314f0 100644
--- a/MdeModulePkg/Universal/SetupBrowserDxe/Ui.h
+++ b/MdeModulePkg/Universal/SetupBrowserDxe/Ui.h
@@ -1,7 +1,7 @@
/** @file
Private structure, MACRO and function definitions for User Interface related functionalities.
-Copyright (c) 2004 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -1048,17 +1048,4 @@ EvaluateExpressionList (
IN FORM_BROWSER_FORM *Form OPTIONAL
);
-/**
- Transfer the device path string to binary format.
-
- @param StringPtr The device path string info.
-
- @retval Device path binary info.
-
-**/
-EFI_DEVICE_PATH_PROTOCOL *
-ConvertDevicePathFromText (
- IN CHAR16 *StringPtr
- );
-
#endif // _UI_H
diff --git a/MdeModulePkg/Universal/Variable/Pei/Variable.c b/MdeModulePkg/Universal/Variable/Pei/Variable.c
index 5040f8208..10ad3f51d 100644
--- a/MdeModulePkg/Universal/Variable/Pei/Variable.c
+++ b/MdeModulePkg/Universal/Variable/Pei/Variable.c
@@ -3,7 +3,7 @@
Implement ReadOnly Variable Services required by PEIM and install
PEI ReadOnly Varaiable2 PPI. These services operates the non volatile storage space.
-Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -430,6 +430,7 @@ FindVariableEx (
UINTN Index;
UINTN Offset;
BOOLEAN StopRecord;
+ VARIABLE_HEADER *InDeletedVariable;
if (VariableStoreHeader == NULL) {
return EFI_INVALID_PARAMETER;
@@ -446,6 +447,8 @@ FindVariableEx (
PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader);
PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader);
+ InDeletedVariable = NULL;
+
//
// No Variable Address equals zero, so 0 as initial value is safe.
//
@@ -461,15 +464,20 @@ FindVariableEx (
Offset += IndexTable->Index[Index];
MaxIndex = (VARIABLE_HEADER *) ((UINT8 *) IndexTable->StartPtr + Offset);
if (CompareWithValidVariable (MaxIndex, VariableName, VendorGuid, PtrTrack) == EFI_SUCCESS) {
- return EFI_SUCCESS;
+ if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ InDeletedVariable = PtrTrack->CurrPtr;
+ } else {
+ return EFI_SUCCESS;
+ }
}
}
if (IndexTable->GoneThrough != 0) {
//
- // If the table has all the existing variables indexed and we still cannot find it.
+ // If the table has all the existing variables indexed, return.
//
- return EFI_NOT_FOUND;
+ PtrTrack->CurrPtr = InDeletedVariable;
+ return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
}
}
@@ -490,11 +498,11 @@ FindVariableEx (
}
//
- // Find the variable by walk through non-volatile variable store
+ // Find the variable by walk through variable store
//
StopRecord = FALSE;
while ((Variable < PtrTrack->EndPtr) && IsValidVariableHeader (Variable)) {
- if (Variable->State == VAR_ADDED) {
+ if (Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
//
// Record Variable in VariableIndex HOB
//
@@ -513,7 +521,11 @@ FindVariableEx (
}
if (CompareWithValidVariable (Variable, VariableName, VendorGuid, PtrTrack) == EFI_SUCCESS) {
- return EFI_SUCCESS;
+ if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ InDeletedVariable = PtrTrack->CurrPtr;
+ } else {
+ return EFI_SUCCESS;
+ }
}
}
@@ -526,9 +538,9 @@ FindVariableEx (
IndexTable->GoneThrough = 1;
}
- PtrTrack->CurrPtr = NULL;
+ PtrTrack->CurrPtr = InDeletedVariable;
- return EFI_NOT_FOUND;
+ return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
}
/**
@@ -691,6 +703,8 @@ PeiGetNextVariableName (
VARIABLE_STORE_TYPE Type;
VARIABLE_POINTER_TRACK Variable;
VARIABLE_POINTER_TRACK VariableInHob;
+ VARIABLE_POINTER_TRACK VariablePtrTrack;
+ VARIABLE_INDEX_TABLE *IndexTable;
UINTN VarNameSize;
EFI_STATUS Status;
VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
@@ -752,7 +766,32 @@ PeiGetNextVariableName (
Variable.CurrPtr = Variable.StartPtr;
}
- if (Variable.CurrPtr->State == VAR_ADDED) {
+ if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ //
+ // If it is a IN_DELETED_TRANSITION variable,
+ // and there is also a same ADDED one at the same time,
+ // don't return it.
+ //
+ for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
+ if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
+ break;
+ }
+ }
+ ASSERT (Type < VariableStoreTypeMax);
+ GetVariableStore (Type, &IndexTable);
+ Status = FindVariableEx (
+ VariableStoreHeader[Type],
+ IndexTable,
+ GetVariableNamePtr (Variable.CurrPtr),
+ &Variable.CurrPtr->VendorGuid,
+ &VariablePtrTrack
+ );
+ if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
+ Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+ continue;
+ }
+ }
//
// Don't return NV variable when HOB overrides it
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index fad1cb323..8f10425eb 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -3,7 +3,7 @@
The common variable operation routines shared by DXE_RUNTIME variable
module and DXE_SMM variable module.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -504,7 +504,7 @@ GetEndPointer (
@param LastVariableOffset Offset of last variable.
@param IsVolatile The variable store is volatile or not;
if it is non-volatile, need FTW.
- @param UpdatingVariable Pointer to updating variable.
+ @param UpdatingPtrTrack Pointer to updating variable pointer track structure.
@param ReclaimAnyway If TRUE, do reclaim anyway.
@return EFI_OUT_OF_RESOURCES
@@ -517,7 +517,7 @@ Reclaim (
IN EFI_PHYSICAL_ADDRESS VariableBase,
OUT UINTN *LastVariableOffset,
IN BOOLEAN IsVolatile,
- IN VARIABLE_HEADER *UpdatingVariable,
+ IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack,
IN BOOLEAN ReclaimAnyway
)
{
@@ -542,6 +542,12 @@ Reclaim (
UINTN CommonVariableTotalSize;
UINTN HwErrVariableTotalSize;
BOOLEAN NeedDoReclaim;
+ VARIABLE_HEADER *UpdatingVariable;
+
+ UpdatingVariable = NULL;
+ if (UpdatingPtrTrack != NULL) {
+ UpdatingVariable = UpdatingPtrTrack->CurrPtr;
+ }
NeedDoReclaim = FALSE;
VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);
@@ -635,6 +641,8 @@ Reclaim (
if (UpdatingVariable != NULL) {
VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable;
CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize);
+ UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));
+ UpdatingPtrTrack->InDeletedTransitionPtr = NULL;
CurrPtr += VariableSize;
if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
HwErrVariableTotalSize += VariableSize;
@@ -667,7 +675,7 @@ Reclaim (
) {
Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
Point1 = (VOID *) GetVariableNamePtr (Variable);
- if (CompareMem (Point0, Point1, NameSizeOfVariable (AddedVariable)) == 0) {
+ if (CompareMem (Point0, Point1, NameSize) == 0) {
FoundAdded = TRUE;
break;
}
@@ -760,6 +768,8 @@ FindVariableEx (
VARIABLE_HEADER *InDeletedVariable;
VOID *Point;
+ PtrTrack->InDeletedTransitionPtr = NULL;
+
//
// Find the variable by walk through HOB, volatile and non-volatile variable store.
//
@@ -777,6 +787,7 @@ FindVariableEx (
if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
InDeletedVariable = PtrTrack->CurrPtr;
} else {
+ PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
return EFI_SUCCESS;
}
} else {
@@ -788,6 +799,7 @@ FindVariableEx (
if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
InDeletedVariable = PtrTrack->CurrPtr;
} else {
+ PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
return EFI_SUCCESS;
}
}
@@ -1320,7 +1332,7 @@ AutoUpdateLangVariable (
//
// Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.
//
- FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal, FALSE);
+ FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
Status = UpdateVariable (L"Lang", &gEfiGlobalVariableGuid, BestLang,
ISO_639_2_ENTRY_SIZE + 1, Attributes, &Variable);
@@ -1375,7 +1387,7 @@ AutoUpdateLangVariable (
@param[in] Data Variable data.
@param[in] DataSize Size of data. 0 means delete.
@param[in] Attributes Attribues of the variable.
- @param[in] CacheVariable The variable information which is used to keep track of variable usage.
+ @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.
@retval EFI_SUCCESS The update operation is success.
@retval EFI_OUT_OF_RESOURCES Variable region is full, can not write other data into this region.
@@ -1388,7 +1400,7 @@ UpdateVariable (
IN VOID *Data,
IN UINTN DataSize,
IN UINT32 Attributes OPTIONAL,
- IN VARIABLE_POINTER_TRACK *CacheVariable
+ IN OUT VARIABLE_POINTER_TRACK *CacheVariable
)
{
EFI_STATUS Status;
@@ -1402,7 +1414,6 @@ UpdateVariable (
BOOLEAN Volatile;
EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
UINT8 State;
- BOOLEAN Reclaimed;
VARIABLE_POINTER_TRACK *Variable;
VARIABLE_POINTER_TRACK NvVariable;
VARIABLE_STORE_HEADER *VariableStoreHeader;
@@ -1429,11 +1440,15 @@ UpdateVariable (
Variable->StartPtr = GetStartPointer (VariableStoreHeader);
Variable->EndPtr = GetEndPointer (VariableStoreHeader);
Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
+ if (CacheVariable->InDeletedTransitionPtr != NULL) {
+ Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
+ } else {
+ Variable->InDeletedTransitionPtr = NULL;
+ }
Variable->Volatile = FALSE;
}
Fvb = mVariableModuleGlobal->FvbInstance;
- Reclaimed = FALSE;
if (Variable->CurrPtr != NULL) {
//
@@ -1463,6 +1478,32 @@ UpdateVariable (
// causes it to be deleted.
//
if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {
+ if (Variable->InDeletedTransitionPtr != NULL) {
+ //
+ // Both ADDED and IN_DELETED_TRANSITION variable are present,
+ // set IN_DELETED_TRANSITION one to DELETED state first.
+ //
+ State = Variable->InDeletedTransitionPtr->State;
+ State &= VAR_DELETED;
+ Status = UpdateVariableStore (
+ &mVariableModuleGlobal->VariableGlobal,
+ Variable->Volatile,
+ FALSE,
+ Fvb,
+ (UINTN) &Variable->InDeletedTransitionPtr->State,
+ sizeof (UINT8),
+ &State
+ );
+ if (!EFI_ERROR (Status)) {
+ if (!Variable->Volatile) {
+ ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
+ CacheVariable->InDeletedTransitionPtr->State = State;
+ }
+ } else {
+ goto Done;
+ }
+ }
+
State = Variable->CurrPtr->State;
State &= VAR_DELETED;
@@ -1607,7 +1648,7 @@ UpdateVariable (
// Perform garbage collection & reclaim operation.
//
Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
- &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable->CurrPtr, FALSE);
+ &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable, FALSE);
if (EFI_ERROR (Status)) {
goto Done;
}
@@ -1621,7 +1662,10 @@ UpdateVariable (
Status = EFI_OUT_OF_RESOURCES;
goto Done;
}
- Reclaimed = TRUE;
+ if (Variable->CurrPtr != NULL) {
+ CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
+ CacheVariable->InDeletedTransitionPtr = NULL;
+ }
}
//
// Four steps
@@ -1722,7 +1766,7 @@ UpdateVariable (
// Perform garbage collection & reclaim operation.
//
Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
- &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable->CurrPtr, FALSE);
+ &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable, FALSE);
if (EFI_ERROR (Status)) {
goto Done;
}
@@ -1735,7 +1779,10 @@ UpdateVariable (
Status = EFI_OUT_OF_RESOURCES;
goto Done;
}
- Reclaimed = TRUE;
+ if (Variable->CurrPtr != NULL) {
+ CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
+ CacheVariable->InDeletedTransitionPtr = NULL;
+ }
}
NextVariable->State = VAR_ADDED;
@@ -1759,7 +1806,33 @@ UpdateVariable (
//
// Mark the old variable as deleted.
//
- if (!Reclaimed && !EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
+ if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
+ if (Variable->InDeletedTransitionPtr != NULL) {
+ //
+ // Both ADDED and IN_DELETED_TRANSITION old variable are present,
+ // set IN_DELETED_TRANSITION one to DELETED state first.
+ //
+ State = Variable->InDeletedTransitionPtr->State;
+ State &= VAR_DELETED;
+ Status = UpdateVariableStore (
+ &mVariableModuleGlobal->VariableGlobal,
+ Variable->Volatile,
+ FALSE,
+ Fvb,
+ (UINTN) &Variable->InDeletedTransitionPtr->State,
+ sizeof (UINT8),
+ &State
+ );
+ if (!EFI_ERROR (Status)) {
+ if (!Variable->Volatile) {
+ ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
+ CacheVariable->InDeletedTransitionPtr->State = State;
+ }
+ } else {
+ goto Done;
+ }
+ }
+
State = Variable->CurrPtr->State;
State &= VAR_DELETED;
@@ -1947,6 +2020,7 @@ VariableServiceGetNextVariableName (
VARIABLE_STORE_TYPE Type;
VARIABLE_POINTER_TRACK Variable;
VARIABLE_POINTER_TRACK VariableInHob;
+ VARIABLE_POINTER_TRACK VariablePtrTrack;
UINTN VarNameSize;
EFI_STATUS Status;
VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
@@ -2020,8 +2094,27 @@ VariableServiceGetNextVariableName (
//
// Variable is found
//
- if (Variable.CurrPtr->State == VAR_ADDED) {
- if ((AtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) {
+ if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
+ if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ //
+ // If it is a IN_DELETED_TRANSITION variable,
+ // and there is also a same ADDED one at the same time,
+ // don't return it.
+ //
+ VariablePtrTrack.StartPtr = Variable.StartPtr;
+ VariablePtrTrack.EndPtr = Variable.EndPtr;
+ Status = FindVariableEx (
+ GetVariableNamePtr (Variable.CurrPtr),
+ &Variable.CurrPtr->VendorGuid,
+ FALSE,
+ &VariablePtrTrack
+ );
+ if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
+ Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+ continue;
+ }
+ }
//
// Don't return NV variable when HOB overrides it
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
index cd88177db..8504ce05f 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h
@@ -3,7 +3,7 @@
The internal header file includes the common header files, defines
internal structure and functions used by Variable modules.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -56,6 +56,13 @@ typedef enum {
typedef struct {
VARIABLE_HEADER *CurrPtr;
+ //
+ // If both ADDED and IN_DELETED_TRANSITION variable are present,
+ // InDeletedTransitionPtr will point to the IN_DELETED_TRANSITION one.
+ // Otherwise, CurrPtr will point to the ADDED or IN_DELETED_TRANSITION one,
+ // and InDeletedTransitionPtr will be NULL at the same time.
+ //
+ VARIABLE_HEADER *InDeletedTransitionPtr;
VARIABLE_HEADER *EndPtr;
VARIABLE_HEADER *StartPtr;
BOOLEAN Volatile;
@@ -141,7 +148,7 @@ FtwVariableSpace (
@param[in] Attributes Attribues of the variable.
- @param[in] Variable The variable information that is used to keep track of variable usage.
+ @param[in, out] Variable The variable information that is used to keep track of variable usage.
@retval EFI_SUCCESS The update operation is success.
@@ -155,7 +162,7 @@ UpdateVariable (
IN VOID *Data,
IN UINTN DataSize,
IN UINT32 Attributes OPTIONAL,
- IN VARIABLE_POINTER_TRACK *Variable
+ IN OUT VARIABLE_POINTER_TRACK *Variable
);
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
index 442fe1dad..2a59ac16f 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c
@@ -4,7 +4,7 @@
and volatile storage space and install variable architecture protocol
based on SMM variable module.
-Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -42,7 +42,51 @@ EFI_SMM_COMMUNICATION_PROTOCOL *mSmmCommunication = NULL;
UINT8 *mVariableBuffer = NULL;
UINT8 *mVariableBufferPhysical = NULL;
UINTN mVariableBufferSize;
+EFI_LOCK mVariableServicesLock;
+/**
+ Acquires lock only at boot time. Simply returns at runtime.
+
+ This is a temperary function that will be removed when
+ EfiAcquireLock() in UefiLib can handle the call in UEFI
+ Runtimer driver in RT phase.
+ It calls EfiAcquireLock() at boot time, and simply returns
+ at runtime.
+
+ @param Lock A pointer to the lock to acquire.
+
+**/
+VOID
+AcquireLockOnlyAtBootTime (
+ IN EFI_LOCK *Lock
+ )
+{
+ if (!EfiAtRuntime ()) {
+ EfiAcquireLock (Lock);
+ }
+}
+
+/**
+ Releases lock only at boot time. Simply returns at runtime.
+
+ This is a temperary function which will be removed when
+ EfiReleaseLock() in UefiLib can handle the call in UEFI
+ Runtimer driver in RT phase.
+ It calls EfiReleaseLock() at boot time and simply returns
+ at runtime.
+
+ @param Lock A pointer to the lock to release.
+
+**/
+VOID
+ReleaseLockOnlyAtBootTime (
+ IN EFI_LOCK *Lock
+ )
+{
+ if (!EfiAtRuntime ()) {
+ EfiReleaseLock (Lock);
+ }
+}
/**
Initialize the communicate buffer using DataSize and Function.
@@ -153,15 +197,17 @@ RuntimeServiceGetVariable (
if ((*DataSize != 0) && (Data == NULL)) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
- // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize + DataSize.
+ // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
//
PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + StrSize (VariableName) + *DataSize;
Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmVariableHeader != NULL);
@@ -189,11 +235,13 @@ RuntimeServiceGetVariable (
}
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
CopyMem (Data, (UINT8 *)SmmVariableHeader->Name + SmmVariableHeader->NameSize, SmmVariableHeader->DataSize);
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
return Status;
}
@@ -226,7 +274,9 @@ RuntimeServiceGetNextVariableName (
if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
// SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
@@ -234,7 +284,7 @@ RuntimeServiceGetNextVariableName (
PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name) + *VariableNameSize;
Status = InitCommunicateBuffer ((VOID **)&SmmGetNextVariableName, PayloadSize, SMM_VARIABLE_FUNCTION_GET_NEXT_VARIABLE_NAME);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmGetNextVariableName != NULL);
@@ -252,12 +302,14 @@ RuntimeServiceGetNextVariableName (
//
*VariableNameSize = SmmGetNextVariableName->NameSize;
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
CopyGuid (VendorGuid, &SmmGetNextVariableName->Guid);
CopyMem (VariableName, SmmGetNextVariableName->Name, SmmGetNextVariableName->NameSize);
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
return Status;
}
@@ -302,7 +354,9 @@ RuntimeServiceSetVariable (
if (DataSize != 0 && Data == NULL) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
// SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
@@ -310,7 +364,7 @@ RuntimeServiceSetVariable (
PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + StrSize (VariableName) + DataSize;
Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_SET_VARIABLE);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmVariableHeader != NULL);
@@ -325,7 +379,9 @@ RuntimeServiceSetVariable (
// Send data to SMM.
//
Status = SendCommunicateBuffer (PayloadSize);
-
+
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
return Status;
}
@@ -363,7 +419,9 @@ RuntimeServiceQueryVariableInfo (
if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
// SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize;
@@ -371,7 +429,7 @@ RuntimeServiceQueryVariableInfo (
PayloadSize = sizeof (SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO);
Status = InitCommunicateBuffer ((VOID **)&SmmQueryVariableInfo, PayloadSize, SMM_VARIABLE_FUNCTION_QUERY_VARIABLE_INFO);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmQueryVariableInfo != NULL);
@@ -382,7 +440,7 @@ RuntimeServiceQueryVariableInfo (
//
Status = SendCommunicateBuffer (PayloadSize);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
//
@@ -391,8 +449,10 @@ RuntimeServiceQueryVariableInfo (
*MaximumVariableSize = SmmQueryVariableInfo->MaximumVariableSize;
*MaximumVariableStorageSize = SmmQueryVariableInfo->MaximumVariableStorageSize;
*RemainingVariableStorageSize = SmmQueryVariableInfo->RemainingVariableStorageSize;
-
- return EFI_SUCCESS;
+
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
+ return Status;
}
@@ -589,7 +649,9 @@ VariableSmmRuntimeInitialize (
VOID *SmmVariableWriteRegistration;
EFI_EVENT OnReadyToBootEvent;
EFI_EVENT ExitBootServiceEvent;
-
+
+ EfiInitializeLock (&mVariableServicesLock, TPL_NOTIFY);
+
//
// Smm variable service is ready
//
diff --git a/MdePkg/Library/BaseLib/Ia32/Thunk16.S b/MdePkg/Library/BaseLib/Ia32/Thunk16.S
index 0555cf1bf..8356c5a1c 100644
--- a/MdePkg/Library/BaseLib/Ia32/Thunk16.S
+++ b/MdePkg/Library/BaseLib/Ia32/Thunk16.S
@@ -1,6 +1,6 @@
#------------------------------------------------------------------------------
#
-# Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
@@ -175,7 +175,7 @@ ASM_PFX(InternalAsmThunk16):
andl $0x7ffffffe, %eax # clear PE, PG bits
movl %cr4, %ebp
mov %ebp, 0xfffffff1(%edx)
- andl $0x300, %ebp # clear all but PCE and OSFXSR bits
+ andl $0xffffffcf, %ebp # clear PAE, PSE bits
pushl $0x10
pop %ecx # ecx <- selector for data segments
lgdtl 0x20(%edx)
diff --git a/MdePkg/Library/BaseLib/Ia32/Thunk16.asm b/MdePkg/Library/BaseLib/Ia32/Thunk16.asm
index 6df0a4a46..3e84aedf3 100644
--- a/MdePkg/Library/BaseLib/Ia32/Thunk16.asm
+++ b/MdePkg/Library/BaseLib/Ia32/Thunk16.asm
@@ -3,7 +3,7 @@
;------------------------------------------------------------------------------
;
-; Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
@@ -237,7 +237,7 @@ InternalAsmThunk16 PROC USES ebp ebx esi edi ds es fs gs
and eax, 7ffffffeh ; clear PE, PG bits
mov ebp, cr4
mov [edx + (SavedCr4 - SavedCr0)], ebp
- and ebp, 300h ; clear all but PCE and OSFXSR bits
+ and ebp, NOT 30h ; clear PAE, PSE bits
push 10h
pop ecx ; ecx <- selector for data segments
lgdt fword ptr [edx + (_16Gdtr - SavedCr0)]
diff --git a/MdePkg/Library/BaseLib/X64/Thunk16.S b/MdePkg/Library/BaseLib/X64/Thunk16.S
index d037a7104..a521aff31 100644
--- a/MdePkg/Library/BaseLib/X64/Thunk16.S
+++ b/MdePkg/Library/BaseLib/X64/Thunk16.S
@@ -1,6 +1,6 @@
#------------------------------------------------------------------------------
#
-# Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
@@ -295,7 +295,7 @@ ASM_PFX(InternalAsmThunk16):
andl $0x7ffffffe,%eax # clear PE, PG bits
movq %cr4, %rbp
movl %ebp, (%rcx) # save CR4 in SavedCr4
- andl $0x300,%ebp # clear all but PCE and OSFXSR bits
+ andl $0xffffffcf,%ebp # clear PAE, PSE bits
movl %r8d, %esi # esi <- 16-bit stack segment
.byte 0x6a, DATA32
popq %rdx
diff --git a/MdePkg/Library/BaseLib/X64/Thunk16.asm b/MdePkg/Library/BaseLib/X64/Thunk16.asm
index 8b208fdb5..01051341f 100644
--- a/MdePkg/Library/BaseLib/X64/Thunk16.asm
+++ b/MdePkg/Library/BaseLib/X64/Thunk16.asm
@@ -3,7 +3,7 @@
;------------------------------------------------------------------------------
;
-; Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
@@ -282,7 +282,7 @@ InternalAsmThunk16 PROC USES rbp rbx rsi rdi
and eax, 7ffffffeh ; clear PE, PG bits
mov rbp, cr4
mov [rcx], ebp ; save CR4 in SavedCr4
- and ebp, 300h ; clear all but PCE and OSFXSR bits
+ and ebp, NOT 30h ; clear PAE, PSE bits
mov esi, r8d ; esi <- 16-bit stack segment
DB 6ah, DATA32 ; push DATA32
pop rdx ; rdx <- 32-bit data segment selector
diff --git a/MdePkg/Library/UefiLib/Console.c b/MdePkg/Library/UefiLib/Console.c
index dd4d5c544..73f991532 100644
--- a/MdePkg/Library/UefiLib/Console.c
+++ b/MdePkg/Library/UefiLib/Console.c
@@ -1,7 +1,7 @@
/** @file
This module provide help function for displaying unicode string.
- Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -332,8 +332,9 @@ UefiLibGetStringWidth (
//
// Advance to the null-terminator or to the first width directive
//
- for (;(String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0);
- Index++, Count = Count + IncrementValue) {
+ for (;(String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0); Index++) {
+ Count = Count + IncrementValue;
+
if (LimitLen && Count > MaxWidth) {
break;
}
@@ -347,7 +348,7 @@ UefiLibGetStringWidth (
}
if (LimitLen && Count > MaxWidth) {
- *Offset = Index - 1;
+ *Offset = Index;
break;
}
@@ -370,13 +371,6 @@ UefiLibGetStringWidth (
}
} while (String[Index] != 0);
- //
- // Increment by one to include the null-terminator in the size
- //
- if (!LimitLen) {
- Count++;
- }
-
return Count * sizeof (CHAR16);
}
@@ -420,6 +414,7 @@ CreatePopUp (
UINTN Length;
CHAR16 *Line;
UINTN EventIndex;
+ CHAR16 *TmpString;
//
// Determine the length of the longest line in the popup and the the total
@@ -520,10 +515,14 @@ CreatePopUp (
// Length > MaxLength
//
UefiLibGetStringWidth (String, TRUE, MaxLength, &Length);
- String[Length] = L'\0';
+ TmpString = AllocateZeroPool ((Length + 1) * sizeof (CHAR16));
+ ASSERT (TmpString != NULL);
+ StrnCpy(TmpString, String, Length - 3);
+ StrCat (TmpString, L"...");
ConOut->SetCursorPosition (ConOut, Column + 1, Row++);
- ConOut->OutputString (ConOut, String);
+ ConOut->OutputString (ConOut, TmpString);
+ FreePool (TmpString);
}
NumberOfLines--;
}
diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.c b/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.c
index 934c03ed8..d8c0ad0d2 100644
--- a/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.c
+++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.c
@@ -104,12 +104,6 @@ EfiDhcp6Start (
Instance->UdpSts = EFI_ALREADY_STARTED;
//
- // Need to clear initial time to make sure that elapsed-time
- // is set to 0 for first Solicit.
- //
- Instance->StartTime = 0;
-
- //
// Send the solicit message to start S.A.R.R process.
//
Status = Dhcp6SendSolicitMsg (Instance);
diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.h b/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.h
index 71b16b191..e3e755316 100644
--- a/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.h
+++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Impl.h
@@ -249,6 +249,10 @@ struct _DHCP6_INSTANCE {
volatile EFI_STATUS UdpSts;
BOOLEAN InDestroy;
BOOLEAN MediaPresent;
+ //
+ // StartTime is used to calculate the 'elapsed-time' option. Refer to RFC3315,
+ // the elapsed-time is amount of time since the client began its current DHCP transaction.
+ //
UINT64 StartTime;
};
diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c b/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c
index 0e83d0785..962d9387c 100644
--- a/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c
+++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c
@@ -593,6 +593,14 @@ Dhcp6UpdateIaInfo (
if (Instance->Config->IaDescriptor.Type == Dhcp6OptIana) {
T1 = NTOHL (ReadUnaligned32 ((UINT32 *) (Option + 8)));
T2 = NTOHL (ReadUnaligned32 ((UINT32 *) (Option + 12)));
+ //
+ // Refer to RFC3155 Chapter 22.4. If a client receives an IA_NA with T1 greater than T2,
+ // and both T1 and T2 are greater than 0, the client discards the IA_NA option and processes
+ // the remainder of the message as though the server had not included the invalid IA_NA option.
+ //
+ if (T1 > T2 && T2 > 0) {
+ return EFI_DEVICE_ERROR;
+ }
IaInnerOpt = Option + 16;
IaInnerLen = (UINT16) (NTOHS (ReadUnaligned16 ((UINT16 *) (Option + 2))) - 12);
} else {
@@ -697,7 +705,7 @@ Dhcp6SeekStsOption (
&Instance->Config->IaDescriptor
);
if (*Option == NULL) {
- return EFI_DEVICE_ERROR;
+ return EFI_SUCCESS;
}
//
@@ -949,7 +957,8 @@ Dhcp6SendSolicitMsg (
Cursor,
Instance->IaCb.Ia,
Instance->IaCb.T1,
- Instance->IaCb.T2
+ Instance->IaCb.T2,
+ Packet->Dhcp6.Header.MessageType
);
//
@@ -987,6 +996,10 @@ Dhcp6SendSolicitMsg (
// Dhcp6selecting.
//
Instance->IaCb.Ia->State = Dhcp6Selecting;
+ //
+ // Clear initial time for current transaction.
+ //
+ Instance->StartTime = 0;
Status = Dhcp6TransmitPacket (Instance, Packet, Elapsed);
@@ -1133,7 +1146,8 @@ Dhcp6SendRequestMsg (
Cursor,
Instance->IaCb.Ia,
Instance->IaCb.T1,
- Instance->IaCb.T2
+ Instance->IaCb.T2,
+ Packet->Dhcp6.Header.MessageType
);
//
@@ -1171,6 +1185,10 @@ Dhcp6SendRequestMsg (
// Dhcp6requesting.
//
Instance->IaCb.Ia->State = Dhcp6Requesting;
+ //
+ // Clear initial time for current transaction.
+ //
+ Instance->StartTime = 0;
Status = Dhcp6TransmitPacket (Instance, Packet, Elapsed);
@@ -1282,7 +1300,7 @@ Dhcp6SendDeclineMsg (
ServerId->Duid
);
- Cursor = Dhcp6AppendIaOption (Cursor, DecIa, 0, 0);
+ Cursor = Dhcp6AppendIaOption (Cursor, DecIa, 0, 0, Packet->Dhcp6.Header.MessageType);
//
// Determine the size/length of packet.
@@ -1305,6 +1323,10 @@ Dhcp6SendDeclineMsg (
// Dhcp6declining.
//
Instance->IaCb.Ia->State = Dhcp6Declining;
+ //
+ // Clear initial time for current transaction.
+ //
+ Instance->StartTime = 0;
Status = Dhcp6TransmitPacket (Instance, Packet, Elapsed);
@@ -1415,7 +1437,7 @@ Dhcp6SendReleaseMsg (
&Elapsed
);
- Cursor = Dhcp6AppendIaOption (Cursor, RelIa, 0, 0);
+ Cursor = Dhcp6AppendIaOption (Cursor, RelIa, 0, 0, Packet->Dhcp6.Header.MessageType);
//
// Determine the size/length of packet
@@ -1540,7 +1562,8 @@ Dhcp6SendRenewRebindMsg (
Cursor,
Instance->IaCb.Ia,
Instance->IaCb.T1,
- Instance->IaCb.T2
+ Instance->IaCb.T2,
+ Packet->Dhcp6.Header.MessageType
);
if (!RebindRequest) {
@@ -1612,6 +1635,10 @@ Dhcp6SendRenewRebindMsg (
//
Instance->IaCb.Ia->State = State;
Instance->IaCb.LeaseTime = (RebindRequest) ? Instance->IaCb.T2 : Instance->IaCb.T1;
+ //
+ // Clear initial time for current transaction.
+ //
+ Instance->StartTime = 0;
Status = Dhcp6TransmitPacket (Instance, Packet, Elapsed);
@@ -1844,6 +1871,11 @@ Dhcp6SendInfoRequestMsg (
//
Packet->Length += (UINT32) (Cursor - Packet->Dhcp6.Option);
ASSERT (Packet->Size > Packet->Length + 8);
+
+ //
+ // Clear initial time for current transaction.
+ //
+ Instance->StartTime = 0;
//
// Send info-request packet with no state.
@@ -1941,7 +1973,8 @@ Dhcp6SendConfirmMsg (
Cursor,
Instance->IaCb.Ia,
Instance->IaCb.T1,
- Instance->IaCb.T2
+ Instance->IaCb.T2,
+ Packet->Dhcp6.Header.MessageType
);
//
@@ -1978,6 +2011,10 @@ Dhcp6SendConfirmMsg (
// Dhcp6Confirming.
//
Instance->IaCb.Ia->State = Dhcp6Confirming;
+ //
+ // Clear initial time for current transaction.
+ //
+ Instance->StartTime = 0;
Status = Dhcp6TransmitPacket (Instance, Packet, Elapsed);
@@ -2020,6 +2057,8 @@ Dhcp6HandleReplyMsg (
ASSERT (Instance->IaCb.Ia != NULL);
ASSERT (Packet != NULL);
+ Status = EFI_SUCCESS;
+
if (Packet->Dhcp6.Header.MessageType != Dhcp6MsgReply) {
return EFI_DEVICE_ERROR;
}
@@ -2056,7 +2095,7 @@ Dhcp6HandleReplyMsg (
&Instance->Config->IaDescriptor
);
if (Option == NULL) {
- return EFI_DEVICE_ERROR;
+ return EFI_SUCCESS;
}
}
@@ -2070,19 +2109,6 @@ Dhcp6HandleReplyMsg (
}
//
- // Dequeue the sent packet from retransmit list since reply received.
- //
- Status = Dhcp6DequeueRetry (
- Instance,
- Packet->Dhcp6.Header.TransactionId,
- FALSE
- );
-
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- //
// When receive a valid reply packet in response to a decline/release packet,
// the client considers the decline/release event completed regardless of the
// status code.
@@ -2115,7 +2141,8 @@ Dhcp6HandleReplyMsg (
//
Instance->StartTime = 0;
- return EFI_SUCCESS;
+ Status = EFI_SUCCESS;
+ goto ON_EXIT;
}
//
@@ -2132,55 +2159,63 @@ Dhcp6HandleReplyMsg (
if (!EFI_ERROR (Status)) {
//
- // Reset start time for next exchange.
- //
- Instance->StartTime = 0;
-
- //
// No status code or no error status code means succeed to reply.
//
Status = Dhcp6UpdateIaInfo (Instance, Packet);
+ if (!EFI_ERROR (Status)) {
+ //
+ // Reset start time for next exchange.
+ //
+ Instance->StartTime = 0;
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- //
- // Set bound state and store the reply packet.
- //
- if (Instance->IaCb.Ia->ReplyPacket != NULL) {
- FreePool (Instance->IaCb.Ia->ReplyPacket);
- }
+ //
+ // Set bound state and store the reply packet.
+ //
+ if (Instance->IaCb.Ia->ReplyPacket != NULL) {
+ FreePool (Instance->IaCb.Ia->ReplyPacket);
+ }
- Instance->IaCb.Ia->ReplyPacket = AllocateZeroPool (Packet->Size);
+ Instance->IaCb.Ia->ReplyPacket = AllocateZeroPool (Packet->Size);
- if (Instance->IaCb.Ia->ReplyPacket == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
+ if (Instance->IaCb.Ia->ReplyPacket == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto ON_EXIT;
+ }
- CopyMem (Instance->IaCb.Ia->ReplyPacket, Packet, Packet->Size);
+ CopyMem (Instance->IaCb.Ia->ReplyPacket, Packet, Packet->Size);
- Instance->IaCb.Ia->State = Dhcp6Bound;
+ Instance->IaCb.Ia->State = Dhcp6Bound;
- //
- // For sync, set the success flag out of polling in start/renewrebind.
- //
- Instance->UdpSts = EFI_SUCCESS;
+ //
+ // For sync, set the success flag out of polling in start/renewrebind.
+ //
+ Instance->UdpSts = EFI_SUCCESS;
- //
- // Maybe this is a new round DHCP process due to some reason, such as NotOnLink
- // ReplyMsg for ConfirmMsg should triger new round to acquire new address. In that
- // case, clear old address.ValidLifetime and append to new address. Therefore, DHCP
- // consumers can be notified to flush old address.
- //
- Dhcp6AppendCacheIa (Instance);
+ //
+ // Maybe this is a new round DHCP process due to some reason, such as NotOnLink
+ // ReplyMsg for ConfirmMsg should triger new round to acquire new address. In that
+ // case, clear old address.ValidLifetime and append to new address. Therefore, DHCP
+ // consumers can be notified to flush old address.
+ //
+ Dhcp6AppendCacheIa (Instance);
- //
- // For async, signal the Ia event to inform Ia infomation update.
- //
- if (Instance->Config->IaInfoEvent != NULL) {
- gBS->SignalEvent (Instance->Config->IaInfoEvent);
+ //
+ // For async, signal the Ia event to inform Ia infomation update.
+ //
+ if (Instance->Config->IaInfoEvent != NULL) {
+ gBS->SignalEvent (Instance->Config->IaInfoEvent);
+ }
+ } else if (Status == EFI_NOT_FOUND) {
+ //
+ // Refer to RFC3315 Chapter 18.1.8, for each IA in the original Renew or Rebind message,
+ // the client sends a Renew or Rebind if the IA is not in the Reply message.
+ // Return EFI_SUCCESS so we can continue to restart the Renew/Rebind process.
+ //
+ return EFI_SUCCESS;
}
+
+ goto ON_EXIT;
+
} else if (Option != NULL) {
//
// Any error status code option is found.
@@ -2226,6 +2261,19 @@ Dhcp6HandleReplyMsg (
}
break;
+ case Dhcp6StsNoBinding:
+ if (Instance->IaCb.Ia->State == Dhcp6Renewing || Instance->IaCb.Ia->State == Dhcp6Rebinding) {
+ //
+ // Refer to RFC3315 Chapter 18.1.8, for each IA in the original Renew or Rebind message, the client
+ // sends a Request message if the IA contained a Status Code option with the NoBinding status.
+ //
+ Status = Dhcp6SendRequestMsg(Instance);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ }
+ break;
+
default:
//
// The other status code, just restart solicitation.
@@ -2235,6 +2283,18 @@ Dhcp6HandleReplyMsg (
}
return EFI_SUCCESS;
+
+ON_EXIT:
+
+ if (!EFI_ERROR(Status)) {
+ Status = Dhcp6DequeueRetry (
+ Instance,
+ Packet->Dhcp6.Header.TransactionId,
+ FALSE
+ );
+ }
+
+ return Status;
}
@@ -2378,17 +2438,13 @@ Dhcp6HandleAdvertiseMsg (
// display the associated status message to the user.
// See the details in the section-17.1.3 of rfc-3315.
//
- Option = Dhcp6SeekOption(
- Packet->Dhcp6.Option,
- Packet->Length - 4,
- Dhcp6OptStatusCode
+ Status = Dhcp6SeekStsOption (
+ Instance,
+ Packet,
+ &Option
);
-
- if (Option != NULL) {
- StsCode = NTOHS (ReadUnaligned16 ((UINT16 *) (Option + 4)));
- if (StsCode != Dhcp6StsSuccess) {
- return EFI_DEVICE_ERROR;
- }
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
}
//
diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c b/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c
index 4c3202868..32247c927 100644
--- a/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c
+++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.c
@@ -647,6 +647,75 @@ Dhcp6AppendOption (
return Buf;
}
+/**
+ Append the appointed IA Address option to Buf, and move Buf to the end.
+
+ @param[in, out] Buf The pointer to the position to append.
+ @param[in] IaAddr The pointer to the IA Address.
+ @param[in] MessageType Message type of DHCP6 package.
+
+ @return Buf The position to append the next option.
+
+**/
+UINT8 *
+Dhcp6AppendIaAddrOption (
+ IN OUT UINT8 *Buf,
+ IN EFI_DHCP6_IA_ADDRESS *IaAddr,
+ IN UINT32 MessageType
+)
+{
+
+ // The format of the IA Address option is:
+ //
+ // 0 1 2 3
+ // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ // | OPTION_IAADDR | option-len |
+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ // | |
+ // | IPv6 address |
+ // | |
+ // | |
+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ // | preferred-lifetime |
+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ // | valid-lifetime |
+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ // . .
+ // . IAaddr-options .
+ // . .
+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+ //
+ // Fill the value of Ia Address option type
+ //
+ WriteUnaligned16 ((UINT16 *) Buf, HTONS (Dhcp6OptIaAddr));
+ Buf += 2;
+
+ WriteUnaligned16 ((UINT16 *) Buf, HTONS (sizeof (EFI_DHCP6_IA_ADDRESS)));
+ Buf += 2;
+
+ CopyMem (Buf, &IaAddr->IpAddress, sizeof(EFI_IPv6_ADDRESS));
+ Buf += sizeof(EFI_IPv6_ADDRESS);
+
+ //
+ // Fill the value of preferred-lifetime and valid-lifetime.
+ // According to RFC3315 Chapter 18.1.2, the preferred-lifetime and valid-lifetime fields
+ // should set to 0 when initiate a Confirm message.
+ //
+ if (MessageType != Dhcp6MsgConfirm) {
+ WriteUnaligned32 ((UINT32 *) Buf, HTONL (IaAddr->PreferredLifetime));
+ }
+ Buf += 4;
+
+ if (MessageType != Dhcp6MsgConfirm) {
+ WriteUnaligned32 ((UINT32 *) Buf, HTONL (IaAddr->ValidLifetime));
+ }
+ Buf += 4;
+
+ return Buf;
+}
+
/**
Append the appointed Ia option to Buf, and move Buf to the end.
@@ -655,6 +724,7 @@ Dhcp6AppendOption (
@param[in] Ia The pointer to the Ia.
@param[in] T1 The time of T1.
@param[in] T2 The time of T2.
+ @param[in] MessageType Message type of DHCP6 package.
@return Buf The position to append the next Ia option.
@@ -664,13 +734,13 @@ Dhcp6AppendIaOption (
IN OUT UINT8 *Buf,
IN EFI_DHCP6_IA *Ia,
IN UINT32 T1,
- IN UINT32 T2
+ IN UINT32 T2,
+ IN UINT32 MessageType
)
{
UINT8 *AddrOpt;
UINT16 *Len;
UINTN Index;
- UINT16 Length;
//
// The format of IA_NA and IA_TA option:
@@ -713,9 +783,9 @@ Dhcp6AppendIaOption (
// Fill the value of t1 and t2 if iana, keep it 0xffffffff if no specified.
//
if (Ia->Descriptor.Type == Dhcp6OptIana) {
- WriteUnaligned32 ((UINT32 *) Buf, ((T1 != 0) ? T1 : 0xffffffff));
+ WriteUnaligned32 ((UINT32 *) Buf, HTONL ((T1 != 0) ? T1 : 0xffffffff));
Buf += 4;
- WriteUnaligned32 ((UINT32 *) Buf, ((T2 != 0) ? T2 : 0xffffffff));
+ WriteUnaligned32 ((UINT32 *) Buf, HTONL ((T2 != 0) ? T2 : 0xffffffff));
Buf += 4;
}
@@ -723,15 +793,8 @@ Dhcp6AppendIaOption (
// Fill all the addresses belong to the Ia
//
for (Index = 0; Index < Ia->IaAddressCount; Index++) {
-
- AddrOpt = (UINT8 *) Ia->IaAddress + Index * sizeof (EFI_DHCP6_IA_ADDRESS);
- Length = HTONS ((UINT16) sizeof (EFI_DHCP6_IA_ADDRESS));
- Buf = Dhcp6AppendOption (
- Buf,
- HTONS (Dhcp6OptIaAddr),
- Length,
- AddrOpt
- );
+ AddrOpt = (UINT8 *) Ia->IaAddress + Index * sizeof (EFI_DHCP6_IA_ADDRESS);
+ Buf = Dhcp6AppendIaAddrOption (Buf, (EFI_DHCP6_IA_ADDRESS *) AddrOpt, MessageType);
}
//
@@ -827,7 +890,7 @@ SetElapsedTime (
//
// Sentinel value of 0 means that this is the first DHCP packet that we are
- // sending and that we need to initialize the value. First DHCP Solicit
+ // sending and that we need to initialize the value. First DHCP message
// gets 0 elapsed-time. Otherwise, calculate based on StartTime.
//
if (Instance->StartTime == 0) {
@@ -934,10 +997,39 @@ Dhcp6SeekIaOption (
return Option;
}
+/**
+ Check whether the incoming IPv6 address in IaAddr is one of the maintained
+ addresses in the IA control blcok.
+
+ @param[in] IaAddr The pointer to the IA Address to be checked.
+ @param[in] CurrentIa The pointer to the IA in IA control block.
+
+ @retval TRUE Yes, this Address is already in IA control block.
+ @retval FALSE No, this Address is NOT in IA control block.
+
+**/
+BOOLEAN
+Dhcp6AddrIsInCurrentIa (
+ IN EFI_DHCP6_IA_ADDRESS *IaAddr,
+ IN EFI_DHCP6_IA *CurrentIa
+ )
+{
+ UINT32 Index;
+
+ ASSERT (IaAddr != NULL && CurrentIa != NULL);
+
+ for (Index = 0; Index < CurrentIa->IaAddressCount; Index++) {
+ if (EFI_IP6_EQUAL(&IaAddr->IpAddress, &CurrentIa->IaAddress[Index].IpAddress)) {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
/**
Parse the address option and update the address infomation.
+ @param[in] CurrentIa The pointer to the Ia Address in control blcok.
@param[in] IaInnerOpt The pointer to the buffer.
@param[in] IaInnerLen The length to parse.
@param[out] AddrNum The number of addresses.
@@ -946,6 +1038,7 @@ Dhcp6SeekIaOption (
**/
VOID
Dhcp6ParseAddrOption (
+ IN EFI_DHCP6_IA *CurrentIa,
IN UINT8 *IaInnerOpt,
IN UINT16 IaInnerLen,
OUT UINT32 *AddrNum,
@@ -956,6 +1049,8 @@ Dhcp6ParseAddrOption (
UINT16 DataLen;
UINT16 OpCode;
UINT32 ValidLt;
+ UINT32 PreferredLt;
+ EFI_DHCP6_IA_ADDRESS *IaAddr;
//
// The format of the IA Address option:
@@ -992,19 +1087,21 @@ Dhcp6ParseAddrOption (
while (Cursor < IaInnerOpt + IaInnerLen) {
//
- // Count the Ia address option with non-0 valid time.
+ // Refer to RFC3315 Chapter 18.1.8, we need to update lifetimes for any addresses in the IA option
+ // that the client already has recorded in the IA, and discard the Ia address option with 0 valid time.
//
OpCode = ReadUnaligned16 ((UINT16 *) Cursor);
- ValidLt = ReadUnaligned32 ((UINT32 *) (Cursor + 24));
- if (OpCode == HTONS (Dhcp6OptIaAddr) && ValidLt != 0) {
-
+ PreferredLt = NTOHL (ReadUnaligned32 ((UINT32 *) (Cursor + 20)));
+ ValidLt = NTOHL (ReadUnaligned32 ((UINT32 *) (Cursor + 24)));
+ IaAddr = (EFI_DHCP6_IA_ADDRESS *) (Cursor + 4);
+ if (OpCode == HTONS (Dhcp6OptIaAddr) && ValidLt >= PreferredLt &&
+ (Dhcp6AddrIsInCurrentIa(IaAddr, CurrentIa) || ValidLt !=0)) {
if (AddrBuf != NULL) {
- CopyMem (AddrBuf, Cursor + 4, sizeof (EFI_DHCP6_IA_ADDRESS));
- AddrBuf->PreferredLifetime = NTOHL (AddrBuf->PreferredLifetime);
- AddrBuf->ValidLifetime = NTOHL (AddrBuf->ValidLifetime);
+ CopyMem (AddrBuf, IaAddr, sizeof (EFI_DHCP6_IA_ADDRESS));
+ AddrBuf->PreferredLifetime = PreferredLt;
+ AddrBuf->ValidLifetime = ValidLt;
AddrBuf = (EFI_DHCP6_IA_ADDRESS *) ((UINT8 *) AddrBuf + sizeof (EFI_DHCP6_IA_ADDRESS));
}
-
(*AddrNum)++;
}
DataLen = NTOHS (ReadUnaligned16 ((UINT16 *) (Cursor + 2)));
@@ -1025,6 +1122,7 @@ Dhcp6ParseAddrOption (
@retval EFI_NOT_FOUND No valid IA option is found.
@retval EFI_SUCCESS Create an IA control block successfully.
@retval EFI_OUT_OF_RESOURCES Required system resources could not be allocated.
+ @retval EFI_DEVICE_ERROR An unexpected error.
**/
EFI_STATUS
@@ -1041,14 +1139,14 @@ Dhcp6GenerateIaCb (
EFI_DHCP6_IA *Ia;
if (Instance->IaCb.Ia == NULL) {
- return EFI_NOT_FOUND;
+ return EFI_DEVICE_ERROR;
}
//
// Calculate the number of addresses for this Ia, excluding the addresses with
// the value 0 of valid lifetime.
//
- Dhcp6ParseAddrOption (IaInnerOpt, IaInnerLen, &AddrNum, NULL);
+ Dhcp6ParseAddrOption (Instance->IaCb.Ia, IaInnerOpt, IaInnerLen, &AddrNum, NULL);
if (AddrNum == 0) {
return EFI_NOT_FOUND;
@@ -1070,7 +1168,7 @@ Dhcp6GenerateIaCb (
Ia->State = Instance->IaCb.Ia->State;
Ia->IaAddressCount = AddrNum;
CopyMem (&Ia->Descriptor, &Instance->Config->IaDescriptor, sizeof (EFI_DHCP6_IA_DESCRIPTOR));
- Dhcp6ParseAddrOption (IaInnerOpt, IaInnerLen, &AddrNum, Ia->IaAddress);
+ Dhcp6ParseAddrOption (Instance->IaCb.Ia, IaInnerOpt, IaInnerLen, &AddrNum, Ia->IaAddress);
//
// Free original IA resource.
diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.h b/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.h
index 2a44d0068..8c3151e30 100644
--- a/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.h
+++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Utility.h
@@ -192,6 +192,7 @@ Dhcp6AppendOption (
@param[in] Ia The pointer to the Ia.
@param[in] T1 The time of T1.
@param[in] T2 The time of T2.
+ @param[in] MessageType Message type of DHCP6 package.
@return Buf The position to append the next Ia option.
@@ -201,7 +202,8 @@ Dhcp6AppendIaOption (
IN OUT UINT8 *Buf,
IN EFI_DHCP6_IA *Ia,
IN UINT32 T1,
- IN UINT32 T2
+ IN UINT32 T2,
+ IN UINT32 MessageType
);
/**
@@ -274,6 +276,7 @@ Dhcp6SeekIaOption (
/**
Parse the address option and update the address info.
+ @param[in] CurrentIa The pointer to the Ia Address in control blcok.
@param[in] IaInnerOpt The pointer to the buffer.
@param[in] IaInnerLen The length to parse.
@param[out] AddrNum The number of addresses.
@@ -282,6 +285,7 @@ Dhcp6SeekIaOption (
**/
VOID
Dhcp6ParseAddrOption (
+ IN EFI_DHCP6_IA *CurrentIa,
IN UINT8 *IaInnerOpt,
IN UINT16 IaInnerLen,
OUT UINT32 *AddrNum,
@@ -300,6 +304,7 @@ Dhcp6ParseAddrOption (
@retval EFI_NOT_FOUND No valid IA option is found.
@retval EFI_SUCCESS Create an IA control block successfully.
@retval EFI_OUT_OF_RESOURCES Required system resources could not be allocated.
+ @retval EFI_DEVICE_ERROR An unexpected error.
**/
EFI_STATUS
diff --git a/NetworkPkg/Ip6Dxe/Ip6ConfigNv.c b/NetworkPkg/Ip6Dxe/Ip6ConfigNv.c
index d4f25d030..546cd8680 100644
--- a/NetworkPkg/Ip6Dxe/Ip6ConfigNv.c
+++ b/NetworkPkg/Ip6Dxe/Ip6ConfigNv.c
@@ -1,7 +1,7 @@
/** @file
Helper functions for configuring or obtaining the parameters relating to IP6.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -669,9 +669,8 @@ Error:
/**
This function converts the interface info to string and draws it to the IP6 UI.
- The interface information includes interface name, interface type, hardware address,
- address info, and route table information. The address information is also used as the
- content of manual addresses in IP6 UI.
+ The interface information includes interface name, interface type, hardware
+ address and route table information.
@param[in] IfInfo The pointer of EFI_IP6_CONFIG_INTERFACE_INFO.
@param[in] HiiHandle The handle that was previously registered in the
@@ -693,7 +692,6 @@ Ip6ConvertInterfaceInfoToString (
UINT32 Index;
UINTN Number;
CHAR16 *String;
- CHAR16 *LinkLocalStr;
CHAR16 PortString[ADDRESS_STR_MAX_SIZE];
CHAR16 FormatString[8];
EFI_STRING_ID StringId;
@@ -783,43 +781,6 @@ Ip6ConvertInterfaceInfoToString (
}
//
- // Print the host address Information.
- //
- Status = Ip6ConvertAddressListToString (
- PortString,
- HiiHandle,
- Ip6ConfigNvHostAddress,
- IfInfo->AddressInfo,
- IfInfo->AddressInfoCount
- );
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- //
- // Copy the Host Address Info to manual address field.
- // Do not copy the link local address.
- //
- LinkLocalStr = StrStr (PortString, IP6_LINK_LOCAL_PREFIX);
- if (LinkLocalStr != NULL) {
- Number = LinkLocalStr - PortString;
- if (Number > 0) {
- CopyMem (IfrNvData->ManualAddress, PortString, Number * sizeof (CHAR16));
- }
-
- while ((*LinkLocalStr != L' ') && (*LinkLocalStr != L'\0')) {
- LinkLocalStr++;
- }
-
- if (*LinkLocalStr != L'\0') {
- LinkLocalStr++;
- StrCat (IfrNvData->ManualAddress, LinkLocalStr);
- }
- } else {
- StrCpy (IfrNvData->ManualAddress, PortString);
- }
-
- //
// Print the route table information.
//
Status = Ip6ConvertAddressListToString (
@@ -1033,75 +994,6 @@ Ip6ConvertConfigNvDataToIfrNvData (
IfrNvData->DadTransmitCount = DadXmits.DupAddrDetectTransmits;
- //
- // Get DNS server list.
- //
- FreePool (Data);
- Data = NULL;
- DataSize = 0;
- Status = Ip6ConfigNvGetData (
- Ip6Config,
- Ip6ConfigDataTypeDnsServer,
- &DataSize,
- (VOID **) &Data
- );
-
- if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
- goto Exit;
- }
-
- if (DataSize > 0) {
- //
- // Convert the DNS server address to string and draw it to UI.
- //
- Status = Ip6ConvertAddressListToString (
- IfrNvData->DnsAddress,
- HiiHandle,
- Ip6ConfigNvDnsAddress,
- Data,
- DataSize / sizeof (EFI_IPv6_ADDRESS)
- );
- if (EFI_ERROR (Status)) {
- goto Exit;
- }
-
- FreePool (Data);
- Data = NULL;
- }
-
- //
- // Get gateway adderss list.
- //
- DataSize = 0;
- Status = Ip6ConfigNvGetData (
- Ip6Config,
- Ip6ConfigDataTypeGateway,
- &DataSize,
- (VOID **) &Data
- );
-
- if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
- goto Exit;
- }
-
- if (DataSize > 0) {
- //
- // Convert the gateway address to string and draw it to UI.
- //
- Status = Ip6ConvertAddressListToString (
- IfrNvData->GatewayAddress,
- HiiHandle,
- Ip6ConfigNvGatewayAddress,
- Data,
- DataSize / sizeof (EFI_IPv6_ADDRESS)
- );
- if (EFI_ERROR (Status)) {
- goto Exit;
- }
- }
-
- Status = EFI_SUCCESS;
-
Exit:
if (Data != NULL) {
FreePool (Data);
@@ -1112,8 +1004,7 @@ Exit:
/**
Convert IFR data into IP6 configuration data. The policy, alternative interface
- ID, and DAD transmit counts, and will be saved. If under manual policy, the configured
- manual address, gateway address, and DNS server address will be saved.
+ ID, and DAD transmit counts, and will be saved.
@param[in] IfrNvData The IFR NV data.
@param[in, out] Instance The IP6 config instance data.
@@ -1124,7 +1015,7 @@ Exit:
**/
EFI_STATUS
-Ip6ConvertIfrNvDataToConfigNvData (
+Ip6ConvertIfrNvDataToConfigNvDataGeneral (
IN IP6_CONFIG_IFR_NVDATA *IfrNvData,
IN OUT IP6_CONFIG_INSTANCE *Instance
)
@@ -1132,12 +1023,6 @@ Ip6ConvertIfrNvDataToConfigNvData (
IP6_CONFIG_NVDATA *Ip6NvData;
EFI_IP6_CONFIG_PROTOCOL *Ip6Config;
EFI_STATUS Status;
- EFI_IP6_CONFIG_MANUAL_ADDRESS *ManualAddress;
- EFI_IPv6_ADDRESS *Address;
- BOOLEAN IsAddressOk;
- EFI_EVENT SetAddressEvent;
- EFI_EVENT TimeoutEvent;
- UINTN DataSize;
if ((IfrNvData == NULL) || (Instance == NULL)) {
return EFI_INVALID_PARAMETER;
@@ -1197,11 +1082,67 @@ Ip6ConvertIfrNvDataToConfigNvData (
return Status;
}
+ return EFI_SUCCESS;
+}
+
+/**
+ Convert IFR data into IP6 configuration data. The policy, configured
+ manual address, gateway address, and DNS server address will be saved.
+
+ @param[in] IfrNvData The IFR NV data.
+ @param[in, out] Instance The IP6 config instance data.
+
+ @retval EFI_SUCCESS The operation finished successfully.
+ @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
+ @retval Others Other errors as indicated.
+
+**/
+EFI_STATUS
+Ip6ConvertIfrNvDataToConfigNvDataAdvanced (
+ IN IP6_CONFIG_IFR_NVDATA *IfrNvData,
+ IN OUT IP6_CONFIG_INSTANCE *Instance
+ )
+{
+ IP6_CONFIG_NVDATA *Ip6NvData;
+ EFI_IP6_CONFIG_PROTOCOL *Ip6Config;
+ EFI_STATUS Status;
+ EFI_IP6_CONFIG_MANUAL_ADDRESS *ManualAddress;
+ EFI_IPv6_ADDRESS *Address;
+ BOOLEAN IsAddressOk;
+ EFI_EVENT SetAddressEvent;
+ EFI_EVENT TimeoutEvent;
+ UINTN DataSize;
+
+ if ((IfrNvData == NULL) || (Instance == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
- if (Ip6NvData->Policy == Ip6ConfigPolicyAutomatic) {
+ if (IfrNvData->Policy == IP6_POLICY_AUTO) {
return EFI_SUCCESS;
}
+ NET_CHECK_SIGNATURE (Instance, IP6_CONFIG_INSTANCE_SIGNATURE);
+ Ip6NvData = &Instance->Ip6NvData;
+ Ip6Config = &Instance->Ip6Config;
+
+ //
+ // Update those fields which don't have INTERACTIVE attribute.
+ //
+ Ip6NvData->Policy = Ip6ConfigPolicyManual;
+
+ //
+ // Set the configured policy.
+ //
+ Status = Ip6Config->SetData (
+ Ip6Config,
+ Ip6ConfigDataTypePolicy,
+ sizeof (EFI_IP6_CONFIG_POLICY),
+ &Ip6NvData->Policy
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
//
// Create events & timers for asynchronous settings.
//
@@ -1358,6 +1299,7 @@ Exit:
return Status;
}
+
/**
This function allows the caller to request the current
configuration for one or more named elements. The resulting
@@ -1588,6 +1530,160 @@ Ip6FormRouteConfig (
}
/**
+ Display host addresses, route table, DNS addresses and gateway addresses in
+ "IPv6 Current Setting" page.
+
+ @param[in] Instance The IP6 config instance data.
+
+ @retval EFI_SUCCESS The operation finished successfully.
+ @retval Others Other errors as indicated.
+
+**/
+EFI_STATUS
+Ip6GetCurrentSetting (
+ IN IP6_CONFIG_INSTANCE *Instance
+ )
+{
+ EFI_IP6_CONFIG_PROTOCOL *Ip6Config;
+ EFI_HII_HANDLE HiiHandle;
+ EFI_IP6_CONFIG_INTERFACE_INFO *Data;
+ UINTN DataSize;
+ EFI_STATUS Status;
+ CHAR16 PortString[ADDRESS_STR_MAX_SIZE];
+ EFI_IP6_CONFIG_INTERFACE_INFO *IfInfo;
+
+
+ Ip6Config = &Instance->Ip6Config;
+ HiiHandle = Instance->CallbackInfo.RegisteredHandle;
+ Data = NULL;
+
+ //
+ // Get current interface info.
+ //
+ Status = Ip6ConfigNvGetData (
+ Ip6Config,
+ Ip6ConfigDataTypeInterfaceInfo,
+ &DataSize,
+ (VOID **) &Data
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Generate dynamic text opcode for host address and draw it.
+ //
+ IfInfo = (EFI_IP6_CONFIG_INTERFACE_INFO *) Data;
+ Status = Ip6ConvertAddressListToString (
+ PortString,
+ HiiHandle,
+ Ip6ConfigNvHostAddress,
+ IfInfo->AddressInfo,
+ IfInfo->AddressInfoCount
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (Data);
+ return Status;
+ }
+
+ //
+ // Generate the dynamic text opcode for route table and draw it.
+ //
+ Status = Ip6ConvertAddressListToString (
+ PortString,
+ HiiHandle,
+ Ip6ConfigNvRouteTable,
+ IfInfo->RouteTable,
+ IfInfo->RouteCount
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (Data);
+ return Status;
+ }
+
+ //
+ // Get DNS server list.
+ //
+ FreePool (Data);
+ DataSize = 0;
+ Data = NULL;
+ Status = Ip6ConfigNvGetData (
+ Ip6Config,
+ Ip6ConfigDataTypeDnsServer,
+ &DataSize,
+ (VOID **) &Data
+ );
+ if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
+ if (Data != NULL) {
+ FreePool (Data);
+ }
+ return Status;
+ }
+
+ if (DataSize > 0) {
+ //
+ // Generate the dynamic text opcode for DNS server and draw it.
+ //
+ Status = Ip6ConvertAddressListToString (
+ PortString,
+ HiiHandle,
+ Ip6ConfigNvDnsAddress,
+ Data,
+ DataSize / sizeof (EFI_IPv6_ADDRESS)
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (Data);
+ return Status;
+ }
+ }
+
+ //
+ // Get gateway adderss list.
+ //
+ if (Data != NULL) {
+ FreePool (Data);
+ }
+
+ DataSize = 0;
+ Data = NULL;
+ Status = Ip6ConfigNvGetData (
+ Ip6Config,
+ Ip6ConfigDataTypeGateway,
+ &DataSize,
+ (VOID **) &Data
+ );
+ if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
+ if (Data != NULL) {
+ FreePool (Data);
+ }
+ return Status;
+ }
+
+ if (DataSize > 0) {
+ //
+ // Generate the dynamic text opcode for gateway and draw it.
+ //
+ Status = Ip6ConvertAddressListToString (
+ PortString,
+ HiiHandle,
+ Ip6ConfigNvGatewayAddress,
+ Data,
+ DataSize / sizeof (EFI_IPv6_ADDRESS)
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (Data);
+ return Status;
+ }
+ }
+
+ if (Data != NULL) {
+ FreePool (Data);
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
This function is called to provide results data to the driver.
This data consists of a unique key that is used to identify
which data is either being passed back or being asked for.
@@ -1632,12 +1728,6 @@ Ip6FormCallback (
EFI_INPUT_KEY Key;
IP6_CONFIG_INSTANCE *Instance;
IP6_CONFIG_NVDATA *Ip6NvData;
- EFI_IP6_CONFIG_PROTOCOL *Ip6Config;
- EFI_IP6_CONFIG_INTERFACE_INFO *Data;
- UINTN DataSize;
- CHAR16 PortString[ADDRESS_STR_MAX_SIZE];
- EFI_HII_HANDLE HiiHandle;
- EFI_IP6_CONFIG_INTERFACE_INFO *IfInfo;
if (This == NULL) {
return EFI_INVALID_PARAMETER;
@@ -1676,135 +1766,7 @@ Ip6FormCallback (
if (Action == EFI_BROWSER_ACTION_CHANGING) {
switch (QuestionId) {
case KEY_GET_CURRENT_SETTING:
- Ip6Config = &Instance->Ip6Config;
- HiiHandle = Instance->CallbackInfo.RegisteredHandle;
- Data = NULL;
-
- //
- // Get current interface info.
- //
- Status = Ip6ConfigNvGetData (
- Ip6Config,
- Ip6ConfigDataTypeInterfaceInfo,
- &DataSize,
- (VOID **) &Data
- );
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- //
- // Generate dynamic text opcode for host address and draw it.
- //
- IfInfo = (EFI_IP6_CONFIG_INTERFACE_INFO *) Data;
- Status = Ip6ConvertAddressListToString (
- PortString,
- HiiHandle,
- Ip6ConfigNvHostAddress,
- IfInfo->AddressInfo,
- IfInfo->AddressInfoCount
- );
- if (EFI_ERROR (Status)) {
- FreePool (Data);
- return Status;
- }
-
- //
- // Generate the dynamic text opcode for route table and draw it.
- //
- Status = Ip6ConvertAddressListToString (
- PortString,
- HiiHandle,
- Ip6ConfigNvRouteTable,
- IfInfo->RouteTable,
- IfInfo->RouteCount
- );
- if (EFI_ERROR (Status)) {
- FreePool (Data);
- return Status;
- }
-
- //
- // Get DNS server list.
- //
- FreePool (Data);
- DataSize = 0;
- Data = NULL;
- Status = Ip6ConfigNvGetData (
- Ip6Config,
- Ip6ConfigDataTypeDnsServer,
- &DataSize,
- (VOID **) &Data
- );
- if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
- if (Data != NULL) {
- FreePool (Data);
- }
- return Status;
- }
-
- if (DataSize > 0) {
- //
- // Generate the dynamic text opcode for DNS server and draw it.
- //
- Status = Ip6ConvertAddressListToString (
- PortString,
- HiiHandle,
- Ip6ConfigNvDnsAddress,
- Data,
- DataSize / sizeof (EFI_IPv6_ADDRESS)
- );
- if (EFI_ERROR (Status)) {
- FreePool (Data);
- return Status;
- }
- }
-
- //
- // Get gateway adderss list.
- //
- if (Data != NULL) {
- FreePool (Data);
- }
-
- DataSize = 0;
- Data = NULL;
- Status = Ip6ConfigNvGetData (
- Ip6Config,
- Ip6ConfigDataTypeGateway,
- &DataSize,
- (VOID **) &Data
- );
- if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) {
- if (Data != NULL) {
- FreePool (Data);
- }
- return Status;
- }
-
- if (DataSize > 0) {
- //
- // Generate the dynamic text opcode for gateway and draw it.
- //
- Status = Ip6ConvertAddressListToString (
- PortString,
- HiiHandle,
- Ip6ConfigNvGatewayAddress,
- Data,
- DataSize / sizeof (EFI_IPv6_ADDRESS)
- );
- if (EFI_ERROR (Status)) {
- FreePool (Data);
- return Status;
- }
- }
-
- if (Data != NULL) {
- FreePool (Data);
- }
-
- Status = EFI_SUCCESS;
-
+ Status = Ip6GetCurrentSetting (Instance);
break;
default:
@@ -1813,6 +1775,13 @@ Ip6FormCallback (
} else if (Action == EFI_BROWSER_ACTION_CHANGED) {
switch (QuestionId) {
case KEY_SAVE_CONFIG_CHANGES:
+ Status = Ip6ConvertIfrNvDataToConfigNvDataAdvanced (IfrNvData, Instance);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Status = Ip6GetCurrentSetting (Instance);
+
*ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT;
break;
@@ -1829,7 +1798,7 @@ Ip6FormCallback (
break;
case KEY_SAVE_CHANGES:
- Status = Ip6ConvertIfrNvDataToConfigNvData (IfrNvData, Instance);
+ Status = Ip6ConvertIfrNvDataToConfigNvDataGeneral (IfrNvData, Instance);
if (EFI_ERROR (Status)) {
break;
}
diff --git a/NetworkPkg/Ip6Dxe/Ip6NvData.h b/NetworkPkg/Ip6Dxe/Ip6NvData.h
index b67e6249b..09177613f 100644
--- a/NetworkPkg/Ip6Dxe/Ip6NvData.h
+++ b/NetworkPkg/Ip6Dxe/Ip6NvData.h
@@ -1,7 +1,7 @@
/** @file
NVData structure used by the IP6 configuration component.
- Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -43,7 +43,7 @@
#define INTERFACE_ID_STR_MIN_SIZE 1
#define INTERFACE_ID_STR_MAX_SIZE 23
-#define INTERFACE_ID_STR_STORAGE 24
+#define INTERFACE_ID_STR_STORAGE 25
#define IP6_STR_MAX_SIZE 40
#define ADDRESS_STR_MIN_SIZE 2
#define ADDRESS_STR_MAX_SIZE 255
diff --git a/Omap35xxPkg/Flash/Flash.c b/Omap35xxPkg/Flash/Flash.c
index 0056acd6b..c63e0a339 100644
--- a/Omap35xxPkg/Flash/Flash.c
+++ b/Omap35xxPkg/Flash/Flash.c
@@ -1,780 +1,780 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "Flash.h"
-
-NAND_PART_INFO_TABLE gNandPartInfoTable[1] = {
- { 0x2C, 0xBA, 17, 11 }
-};
-
-NAND_FLASH_INFO *gNandFlashInfo = NULL;
-UINT8 *gEccCode;
-UINTN gNum512BytesChunks = 0;
-
-//
-
-// Device path for SemiHosting. It contains our autogened Caller ID GUID.
-
-//
-
-typedef struct {
-
- VENDOR_DEVICE_PATH Guid;
-
- EFI_DEVICE_PATH_PROTOCOL End;
-
-} FLASH_DEVICE_PATH;
-
-
-
-FLASH_DEVICE_PATH gDevicePath = {
-
- {
-
- { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, sizeof (VENDOR_DEVICE_PATH), 0 },
-
- EFI_CALLER_ID_GUID
-
- },
-
- { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, sizeof (EFI_DEVICE_PATH_PROTOCOL), 0}
-
-};
-
-
-
-//Actual page address = Column address + Page address + Block address.
-UINTN
-GetActualPageAddressInBytes (
- UINTN BlockIndex,
- UINTN PageIndex
-)
-{
- //BlockAddressStart = Start of the Block address in actual NAND
- //PageAddressStart = Start of the Page address in actual NAND
- return ((BlockIndex << gNandFlashInfo->BlockAddressStart) + (PageIndex << gNandFlashInfo->PageAddressStart));
-}
-
-VOID
-NandSendCommand (
- UINT8 Command
-)
-{
- MmioWrite16(GPMC_NAND_COMMAND_0, Command);
-}
-
-VOID
-NandSendAddress (
- UINT8 Address
-)
-{
- MmioWrite16(GPMC_NAND_ADDRESS_0, Address);
-}
-
-UINT16
-NandReadStatus (
- VOID
- )
-{
- //Send READ STATUS command
- NandSendCommand(READ_STATUS_CMD);
-
- //Read status.
- return MmioRead16(GPMC_NAND_DATA_0);
-}
-
-VOID
-NandSendAddressCycles (
- UINTN Address
-)
-{
- //Column address
- NandSendAddress(Address & 0xff);
- Address >>= 8;
-
- //Column address
- NandSendAddress(Address & 0x07);
- Address >>= 3;
-
- //Page and Block address
- NandSendAddress(Address & 0xff);
- Address >>= 8;
-
- //Block address
- NandSendAddress(Address & 0xff);
- Address >>= 8;
-
- //Block address
- NandSendAddress(Address & 0x01);
-}
-
-VOID
-GpmcInit (
- VOID
- )
-{
- //Enable Smart-idle mode.
- MmioWrite32 (GPMC_SYSCONFIG, SMARTIDLEMODE);
-
- //Set IRQSTATUS and IRQENABLE to the reset value
- MmioWrite32 (GPMC_IRQSTATUS, 0x0);
- MmioWrite32 (GPMC_IRQENABLE, 0x0);
-
- //Disable GPMC timeout control.
- MmioWrite32 (GPMC_TIMEOUT_CONTROL, TIMEOUTDISABLE);
-
- //Set WRITEPROTECT bit to enable write access.
- MmioWrite32 (GPMC_CONFIG, WRITEPROTECT_HIGH);
-
- //NOTE: Following GPMC_CONFIGi_0 register settings are taken from u-boot memory dump.
- MmioWrite32 (GPMC_CONFIG1_0, DEVICETYPE_NAND | DEVICESIZE_X16);
- MmioWrite32 (GPMC_CONFIG2_0, CSRDOFFTIME | CSWROFFTIME);
- MmioWrite32 (GPMC_CONFIG3_0, ADVRDOFFTIME | ADVWROFFTIME);
- MmioWrite32 (GPMC_CONFIG4_0, OEONTIME | OEOFFTIME | WEONTIME | WEOFFTIME);
- MmioWrite32 (GPMC_CONFIG5_0, RDCYCLETIME | WRCYCLETIME | RDACCESSTIME | PAGEBURSTACCESSTIME);
- MmioWrite32 (GPMC_CONFIG6_0, WRACCESSTIME | WRDATAONADMUXBUS | CYCLE2CYCLEDELAY | CYCLE2CYCLESAMECSEN);
- MmioWrite32 (GPMC_CONFIG7_0, MASKADDRESS_128MB | CSVALID | BASEADDRESS);
-}
-
-EFI_STATUS
-NandDetectPart (
- VOID
-)
-{
- UINT8 NandInfo = 0;
- UINT8 PartInfo[5];
- UINTN Index;
- BOOLEAN Found = FALSE;
-
- //Send READ ID command
- NandSendCommand(READ_ID_CMD);
-
- //Send one address cycle.
- NandSendAddress(0);
-
- //Read 5-bytes to idenfity code programmed into the NAND flash devices.
- //BYTE 0 = Manufacture ID
- //Byte 1 = Device ID
- //Byte 2, 3, 4 = Nand part specific information (Page size, Block size etc)
- for (Index = 0; Index < sizeof(PartInfo); Index++) {
- PartInfo[Index] = MmioRead16(GPMC_NAND_DATA_0);
- }
-
- //Check if the ManufactureId and DeviceId are part of the currently supported nand parts.
- for (Index = 0; Index < sizeof(gNandPartInfoTable)/sizeof(NAND_PART_INFO_TABLE); Index++) {
- if (gNandPartInfoTable[Index].ManufactureId == PartInfo[0] && gNandPartInfoTable[Index].DeviceId == PartInfo[1]) {
- gNandFlashInfo->BlockAddressStart = gNandPartInfoTable[Index].BlockAddressStart;
- gNandFlashInfo->PageAddressStart = gNandPartInfoTable[Index].PageAddressStart;
- Found = TRUE;
- break;
- }
- }
-
- if (Found == FALSE) {
- DEBUG ((EFI_D_ERROR, "Nand part is not currently supported. Manufacture id: %x, Device id: %x\n", PartInfo[0], PartInfo[1]));
- return EFI_NOT_FOUND;
- }
-
- //Populate NAND_FLASH_INFO based on the result of READ ID command.
- gNandFlashInfo->ManufactureId = PartInfo[0];
- gNandFlashInfo->DeviceId = PartInfo[1];
- NandInfo = PartInfo[3];
-
- if (PAGE_SIZE(NandInfo) == PAGE_SIZE_2K_VAL) {
- gNandFlashInfo->PageSize = PAGE_SIZE_2K;
- } else {
- DEBUG ((EFI_D_ERROR, "Unknown Page size.\n"));
- return EFI_DEVICE_ERROR;
- }
-
- if (SPARE_AREA_SIZE(NandInfo) == SPARE_AREA_SIZE_64B_VAL) {
- gNandFlashInfo->SparePageSize = SPARE_AREA_SIZE_64B;
- } else {
- DEBUG ((EFI_D_ERROR, "Unknown Spare area size.\n"));
- return EFI_DEVICE_ERROR;
- }
-
- if (BLOCK_SIZE(NandInfo) == BLOCK_SIZE_128K_VAL) {
- gNandFlashInfo->BlockSize = BLOCK_SIZE_128K;
- } else {
- DEBUG ((EFI_D_ERROR, "Unknown Block size.\n"));
- return EFI_DEVICE_ERROR;
- }
-
- if (ORGANIZATION(NandInfo) == ORGANIZATION_X8) {
- gNandFlashInfo->Organization = 0;
- } else if (ORGANIZATION(NandInfo) == ORGANIZATION_X16) {
- gNandFlashInfo->Organization = 1;
- }
-
- //Calculate total number of blocks.
- gNandFlashInfo->NumPagesPerBlock = DivU64x32(gNandFlashInfo->BlockSize, gNandFlashInfo->PageSize);
-
- return EFI_SUCCESS;
-}
-
-VOID
-NandConfigureEcc (
- VOID
- )
-{
- //Define ECC size 0 and size 1 to 512 bytes
- MmioWrite32 (GPMC_ECC_SIZE_CONFIG, (ECCSIZE0_512BYTES | ECCSIZE1_512BYTES));
-}
-
-VOID
-NandEnableEcc (
- VOID
- )
-{
- //Clear all the ECC result registers and select ECC result register 1
- MmioWrite32 (GPMC_ECC_CONTROL, (ECCCLEAR | ECCPOINTER_REG1));
-
- //Enable ECC engine on CS0
- MmioWrite32 (GPMC_ECC_CONFIG, (ECCENABLE | ECCCS_0 | ECC16B));
-}
-
-VOID
-NandDisableEcc (
- VOID
- )
-{
- //Turn off ECC engine.
- MmioWrite32 (GPMC_ECC_CONFIG, ECCDISABLE);
-}
-
-VOID
-NandCalculateEcc (
- VOID
- )
-{
- UINTN Index;
- UINTN EccResultRegister;
- UINTN EccResult;
-
- //Capture 32-bit ECC result for each 512-bytes chunk.
- //In our case PageSize is 2K so read ECC1-ECC4 result registers and
- //generate total of 12-bytes of ECC code for the particular page.
-
- EccResultRegister = GPMC_ECC1_RESULT;
-
- for (Index = 0; Index < gNum512BytesChunks; Index++) {
-
- EccResult = MmioRead32 (EccResultRegister);
-
- //Calculate ECC code from 32-bit ECC result value.
- //NOTE: Following calculation is not part of TRM. We got this information
- //from Beagleboard mailing list.
- gEccCode[Index * 3] = EccResult & 0xFF;
- gEccCode[(Index * 3) + 1] = (EccResult >> 16) & 0xFF;
- gEccCode[(Index * 3) + 2] = (((EccResult >> 20) & 0xF0) | ((EccResult >> 8) & 0x0F));
-
- //Point to next ECC result register.
- EccResultRegister += 4;
- }
-}
-
-EFI_STATUS
-NandReadPage (
- IN UINTN BlockIndex,
- IN UINTN PageIndex,
- OUT VOID *Buffer,
- OUT UINT8 *SpareBuffer
-)
-{
- UINTN Address;
- UINTN Index;
- UINTN NumMainAreaWords = (gNandFlashInfo->PageSize/2);
- UINTN NumSpareAreaWords = (gNandFlashInfo->SparePageSize/2);
- UINT16 *MainAreaWordBuffer = Buffer;
- UINT16 *SpareAreaWordBuffer = (UINT16 *)SpareBuffer;
- UINTN Timeout = MAX_RETRY_COUNT;
-
- //Generate device address in bytes to access specific block and page index
- Address = GetActualPageAddressInBytes(BlockIndex, PageIndex);
-
- //Send READ command
- NandSendCommand(PAGE_READ_CMD);
-
- //Send 5 Address cycles to access specific device address
- NandSendAddressCycles(Address);
-
- //Send READ CONFIRM command
- NandSendCommand(PAGE_READ_CONFIRM_CMD);
-
- //Poll till device is busy.
- while (Timeout) {
- if ((NandReadStatus() & NAND_READY) == NAND_READY) {
- break;
- }
- Timeout--;
- }
-
- if (Timeout == 0) {
- DEBUG ((EFI_D_ERROR, "Read page timed out.\n"));
- return EFI_TIMEOUT;
- }
-
- //Reissue READ command
- NandSendCommand(PAGE_READ_CMD);
-
- //Enable ECC engine.
- NandEnableEcc();
-
- //Read data into the buffer.
- for (Index = 0; Index < NumMainAreaWords; Index++) {
- *MainAreaWordBuffer++ = MmioRead16(GPMC_NAND_DATA_0);
- }
-
- //Read spare area into the buffer.
- for (Index = 0; Index < NumSpareAreaWords; Index++) {
- *SpareAreaWordBuffer++ = MmioRead16(GPMC_NAND_DATA_0);
- }
-
- //Calculate ECC.
- NandCalculateEcc();
-
- //Turn off ECC engine.
- NandDisableEcc();
-
- //Perform ECC correction.
- //Need to implement..
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-NandWritePage (
- IN UINTN BlockIndex,
- IN UINTN PageIndex,
- OUT VOID *Buffer,
- IN UINT8 *SpareBuffer
-)
-{
- UINTN Address;
- UINT16 *MainAreaWordBuffer = Buffer;
- UINT16 *SpareAreaWordBuffer = (UINT16 *)SpareBuffer;
- UINTN Index;
- UINTN NandStatus;
- UINTN Timeout = MAX_RETRY_COUNT;
-
- //Generate device address in bytes to access specific block and page index
- Address = GetActualPageAddressInBytes(BlockIndex, PageIndex);
-
- //Send SERIAL DATA INPUT command
- NandSendCommand(PROGRAM_PAGE_CMD);
-
- //Send 5 Address cycles to access specific device address
- NandSendAddressCycles(Address);
-
- //Enable ECC engine.
- NandEnableEcc();
-
- //Data input from Buffer
- for (Index = 0; Index < (gNandFlashInfo->PageSize/2); Index++) {
- MmioWrite16(GPMC_NAND_DATA_0, *MainAreaWordBuffer++);
-
- //After each write access, device has to wait to accept data.
- //Currently we may not be programming proper timing parameters to
- //the GPMC_CONFIGi_0 registers and we would need to figure that out.
- //Without following delay, page programming fails.
- gBS->Stall(1);
- }
-
- //Calculate ECC.
- NandCalculateEcc();
-
- //Turn off ECC engine.
- NandDisableEcc();
-
- //Prepare Spare area buffer with ECC codes.
- SetMem(SpareBuffer, gNandFlashInfo->SparePageSize, 0xFF);
- CopyMem(&SpareBuffer[ECC_POSITION], gEccCode, gNum512BytesChunks * 3);
-
- //Program spare area with calculated ECC.
- for (Index = 0; Index < (gNandFlashInfo->SparePageSize/2); Index++) {
- MmioWrite16(GPMC_NAND_DATA_0, *SpareAreaWordBuffer++);
- }
-
- //Send PROGRAM command
- NandSendCommand(PROGRAM_PAGE_CONFIRM_CMD);
-
- //Poll till device is busy.
- NandStatus = 0;
- while (Timeout) {
- NandStatus = NandReadStatus();
- if ((NandStatus & NAND_READY) == NAND_READY) {
- break;
- }
- Timeout--;
- }
-
- if (Timeout == 0) {
- DEBUG ((EFI_D_ERROR, "Program page timed out.\n"));
- return EFI_TIMEOUT;
- }
-
- //Bit0 indicates Pass/Fail status
- if (NandStatus & NAND_FAILURE) {
- return EFI_DEVICE_ERROR;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-NandEraseBlock (
- IN UINTN BlockIndex
-)
-{
- UINTN Address;
- UINTN NandStatus;
- UINTN Timeout = MAX_RETRY_COUNT;
-
- //Generate device address in bytes to access specific block and page index
- Address = GetActualPageAddressInBytes(BlockIndex, 0);
-
- //Send ERASE SETUP command
- NandSendCommand(BLOCK_ERASE_CMD);
-
- //Send 3 address cycles to device to access Page address and Block address
- Address >>= 11; //Ignore column addresses
-
- NandSendAddress(Address & 0xff);
- Address >>= 8;
-
- NandSendAddress(Address & 0xff);
- Address >>= 8;
-
- NandSendAddress(Address & 0xff);
-
- //Send ERASE CONFIRM command
- NandSendCommand(BLOCK_ERASE_CONFIRM_CMD);
-
- //Poll till device is busy.
- NandStatus = 0;
- while (Timeout) {
- NandStatus = NandReadStatus();
- if ((NandStatus & NAND_READY) == NAND_READY) {
- break;
- }
- Timeout--;
- gBS->Stall(1);
- }
-
- if (Timeout == 0) {
- DEBUG ((EFI_D_ERROR, "Erase block timed out for Block: %d.\n", BlockIndex));
- return EFI_TIMEOUT;
- }
-
- //Bit0 indicates Pass/Fail status
- if (NandStatus & NAND_FAILURE) {
- return EFI_DEVICE_ERROR;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-NandReadBlock (
- IN UINTN StartBlockIndex,
- IN UINTN EndBlockIndex,
- OUT VOID *Buffer,
- OUT VOID *SpareBuffer
-)
-{
- UINTN BlockIndex;
- UINTN PageIndex;
- EFI_STATUS Status = EFI_SUCCESS;
-
- for (BlockIndex = StartBlockIndex; BlockIndex <= EndBlockIndex; BlockIndex++) {
- //For each block read number of pages
- for (PageIndex = 0; PageIndex < gNandFlashInfo->NumPagesPerBlock; PageIndex++) {
- Status = NandReadPage(BlockIndex, PageIndex, Buffer, SpareBuffer);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- Buffer = ((UINT8 *)Buffer + gNandFlashInfo->PageSize);
- }
- }
-
- return Status;
-}
-
-EFI_STATUS
-NandWriteBlock (
- IN UINTN StartBlockIndex,
- IN UINTN EndBlockIndex,
- OUT VOID *Buffer,
- OUT VOID *SpareBuffer
- )
-{
- UINTN BlockIndex;
- UINTN PageIndex;
- EFI_STATUS Status = EFI_SUCCESS;
-
- for (BlockIndex = StartBlockIndex; BlockIndex <= EndBlockIndex; BlockIndex++) {
- //Page programming.
- for (PageIndex = 0; PageIndex < gNandFlashInfo->NumPagesPerBlock; PageIndex++) {
- Status = NandWritePage(BlockIndex, PageIndex, Buffer, SpareBuffer);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- Buffer = ((UINT8 *)Buffer + gNandFlashInfo->PageSize);
- }
- }
-
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-NandFlashReset (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN BOOLEAN ExtendedVerification
- )
-{
- UINTN BusyStall = 50; // microSeconds
- UINTN ResetBusyTimeout = (1000000 / BusyStall); // 1 Second
-
- //Send RESET command to device.
- NandSendCommand(RESET_CMD);
-
- //Wait for 1ms before we check status register.
- gBS->Stall(1000);
-
- //Check BIT#5 & BIT#6 in Status register to make sure RESET is done.
- while ((NandReadStatus() & NAND_RESET_STATUS) != NAND_RESET_STATUS) {
-
- //In case of extended verification, wait for extended amount of time
- //to make sure device is reset.
- if (ExtendedVerification) {
- if (ResetBusyTimeout == 0) {
- return EFI_DEVICE_ERROR;
- }
-
- gBS->Stall(BusyStall);
- ResetBusyTimeout--;
- }
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-EFIAPI
-NandFlashReadBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSize,
- OUT VOID *Buffer
- )
-{
- UINTN NumBlocks;
- UINTN EndBlockIndex;
- EFI_STATUS Status;
- UINT8 *SpareBuffer = NULL;
-
- if (Buffer == NULL) {
- Status = EFI_INVALID_PARAMETER;
- goto exit;
- }
-
- if (Lba > LAST_BLOCK) {
- Status = EFI_INVALID_PARAMETER;
- goto exit;
- }
-
- if ((BufferSize % gNandFlashInfo->BlockSize) != 0) {
- Status = EFI_BAD_BUFFER_SIZE;
- goto exit;
- }
-
- NumBlocks = DivU64x32(BufferSize, gNandFlashInfo->BlockSize);
- EndBlockIndex = ((UINTN)Lba + NumBlocks) - 1;
-
- SpareBuffer = (UINT8 *)AllocatePool(gNandFlashInfo->SparePageSize);
- if (SpareBuffer == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto exit;
- }
-
- //Read block
- Status = NandReadBlock((UINTN)Lba, EndBlockIndex, Buffer, SpareBuffer);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "Read block fails: %x\n", Status));
- goto exit;
- }
-
-exit:
- if (SpareBuffer != NULL) {
- FreePool (SpareBuffer);
- }
-
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-NandFlashWriteBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSize,
- IN VOID *Buffer
- )
-{
- UINTN BlockIndex;
- UINTN NumBlocks;
- UINTN EndBlockIndex;
- EFI_STATUS Status;
- UINT8 *SpareBuffer = NULL;
-
- if (Buffer == NULL) {
- Status = EFI_INVALID_PARAMETER;
- goto exit;
- }
-
- if (Lba > LAST_BLOCK) {
- Status = EFI_INVALID_PARAMETER;
- goto exit;
- }
-
- if ((BufferSize % gNandFlashInfo->BlockSize) != 0) {
- Status = EFI_BAD_BUFFER_SIZE;
- goto exit;
- }
-
- NumBlocks = DivU64x32(BufferSize, gNandFlashInfo->BlockSize);
- EndBlockIndex = ((UINTN)Lba + NumBlocks) - 1;
-
- SpareBuffer = (UINT8 *)AllocatePool(gNandFlashInfo->SparePageSize);
- if (SpareBuffer == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto exit;
- }
-
- // Erase block
- for (BlockIndex = (UINTN)Lba; BlockIndex <= EndBlockIndex; BlockIndex++) {
- Status = NandEraseBlock(BlockIndex);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "Erase block failed. Status: %x\n", Status));
- goto exit;
- }
- }
-
- // Program data
- Status = NandWriteBlock((UINTN)Lba, EndBlockIndex, Buffer, SpareBuffer);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "Block write fails: %x\n", Status));
- goto exit;
- }
-
-exit:
- if (SpareBuffer != NULL) {
- FreePool (SpareBuffer);
- }
-
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-NandFlashFlushBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This
- )
-{
- return EFI_SUCCESS;
-}
-
-
-
-EFI_BLOCK_IO_MEDIA gNandFlashMedia = {
- SIGNATURE_32('n','a','n','d'), // MediaId
- FALSE, // RemovableMedia
- TRUE, // MediaPresent
- FALSE, // LogicalPartition
- FALSE, // ReadOnly
- FALSE, // WriteCaching
- 0, // BlockSize
- 2, // IoAlign
- 0, // Pad
- 0 // LastBlock
-};
-
-EFI_BLOCK_IO_PROTOCOL BlockIo =
-{
- EFI_BLOCK_IO_INTERFACE_REVISION, // Revision
- &gNandFlashMedia, // *Media
- NandFlashReset, // Reset
- NandFlashReadBlocks, // ReadBlocks
- NandFlashWriteBlocks, // WriteBlocks
- NandFlashFlushBlocks // FlushBlocks
-};
-
-EFI_STATUS
-NandFlashInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
-
- gNandFlashInfo = (NAND_FLASH_INFO *)AllocateZeroPool (sizeof(NAND_FLASH_INFO));
-
- //Initialize GPMC module.
- GpmcInit();
-
- //Reset NAND part
- NandFlashReset(&BlockIo, FALSE);
-
- //Detect NAND part and populate gNandFlashInfo structure
- Status = NandDetectPart ();
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "Nand part id detection failure: Status: %x\n", Status));
- return Status;
- }
-
- //Count total number of 512Bytes chunk based on the page size.
- if (gNandFlashInfo->PageSize == PAGE_SIZE_512B) {
- gNum512BytesChunks = 1;
- } else if (gNandFlashInfo->PageSize == PAGE_SIZE_2K) {
- gNum512BytesChunks = 4;
- } else if (gNandFlashInfo->PageSize == PAGE_SIZE_4K) {
- gNum512BytesChunks = 8;
- }
-
- gEccCode = (UINT8 *)AllocatePool(gNum512BytesChunks * 3);
- if (gEccCode == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- //Configure ECC
- NandConfigureEcc ();
-
- //Patch EFI_BLOCK_IO_MEDIA structure.
- gNandFlashMedia.BlockSize = gNandFlashInfo->BlockSize;
- gNandFlashMedia.LastBlock = LAST_BLOCK;
-
- //Publish BlockIO.
- Status = gBS->InstallMultipleProtocolInterfaces (
- &ImageHandle,
- &gEfiBlockIoProtocolGuid, &BlockIo,
- &gEfiDevicePathProtocolGuid, &gDevicePath,
- NULL
- );
- return Status;
-}
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "Flash.h"
+
+NAND_PART_INFO_TABLE gNandPartInfoTable[1] = {
+ { 0x2C, 0xBA, 17, 11 }
+};
+
+NAND_FLASH_INFO *gNandFlashInfo = NULL;
+UINT8 *gEccCode;
+UINTN gNum512BytesChunks = 0;
+
+//
+
+// Device path for SemiHosting. It contains our autogened Caller ID GUID.
+
+//
+
+typedef struct {
+
+ VENDOR_DEVICE_PATH Guid;
+
+ EFI_DEVICE_PATH_PROTOCOL End;
+
+} FLASH_DEVICE_PATH;
+
+
+
+FLASH_DEVICE_PATH gDevicePath = {
+
+ {
+
+ { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, sizeof (VENDOR_DEVICE_PATH), 0 },
+
+ EFI_CALLER_ID_GUID
+
+ },
+
+ { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, sizeof (EFI_DEVICE_PATH_PROTOCOL), 0}
+
+};
+
+
+
+//Actual page address = Column address + Page address + Block address.
+UINTN
+GetActualPageAddressInBytes (
+ UINTN BlockIndex,
+ UINTN PageIndex
+)
+{
+ //BlockAddressStart = Start of the Block address in actual NAND
+ //PageAddressStart = Start of the Page address in actual NAND
+ return ((BlockIndex << gNandFlashInfo->BlockAddressStart) + (PageIndex << gNandFlashInfo->PageAddressStart));
+}
+
+VOID
+NandSendCommand (
+ UINT8 Command
+)
+{
+ MmioWrite16(GPMC_NAND_COMMAND_0, Command);
+}
+
+VOID
+NandSendAddress (
+ UINT8 Address
+)
+{
+ MmioWrite16(GPMC_NAND_ADDRESS_0, Address);
+}
+
+UINT16
+NandReadStatus (
+ VOID
+ )
+{
+ //Send READ STATUS command
+ NandSendCommand(READ_STATUS_CMD);
+
+ //Read status.
+ return MmioRead16(GPMC_NAND_DATA_0);
+}
+
+VOID
+NandSendAddressCycles (
+ UINTN Address
+)
+{
+ //Column address
+ NandSendAddress(Address & 0xff);
+ Address >>= 8;
+
+ //Column address
+ NandSendAddress(Address & 0x07);
+ Address >>= 3;
+
+ //Page and Block address
+ NandSendAddress(Address & 0xff);
+ Address >>= 8;
+
+ //Block address
+ NandSendAddress(Address & 0xff);
+ Address >>= 8;
+
+ //Block address
+ NandSendAddress(Address & 0x01);
+}
+
+VOID
+GpmcInit (
+ VOID
+ )
+{
+ //Enable Smart-idle mode.
+ MmioWrite32 (GPMC_SYSCONFIG, SMARTIDLEMODE);
+
+ //Set IRQSTATUS and IRQENABLE to the reset value
+ MmioWrite32 (GPMC_IRQSTATUS, 0x0);
+ MmioWrite32 (GPMC_IRQENABLE, 0x0);
+
+ //Disable GPMC timeout control.
+ MmioWrite32 (GPMC_TIMEOUT_CONTROL, TIMEOUTDISABLE);
+
+ //Set WRITEPROTECT bit to enable write access.
+ MmioWrite32 (GPMC_CONFIG, WRITEPROTECT_HIGH);
+
+ //NOTE: Following GPMC_CONFIGi_0 register settings are taken from u-boot memory dump.
+ MmioWrite32 (GPMC_CONFIG1_0, DEVICETYPE_NAND | DEVICESIZE_X16);
+ MmioWrite32 (GPMC_CONFIG2_0, CSRDOFFTIME | CSWROFFTIME);
+ MmioWrite32 (GPMC_CONFIG3_0, ADVRDOFFTIME | ADVWROFFTIME);
+ MmioWrite32 (GPMC_CONFIG4_0, OEONTIME | OEOFFTIME | WEONTIME | WEOFFTIME);
+ MmioWrite32 (GPMC_CONFIG5_0, RDCYCLETIME | WRCYCLETIME | RDACCESSTIME | PAGEBURSTACCESSTIME);
+ MmioWrite32 (GPMC_CONFIG6_0, WRACCESSTIME | WRDATAONADMUXBUS | CYCLE2CYCLEDELAY | CYCLE2CYCLESAMECSEN);
+ MmioWrite32 (GPMC_CONFIG7_0, MASKADDRESS_128MB | CSVALID | BASEADDRESS);
+}
+
+EFI_STATUS
+NandDetectPart (
+ VOID
+)
+{
+ UINT8 NandInfo = 0;
+ UINT8 PartInfo[5];
+ UINTN Index;
+ BOOLEAN Found = FALSE;
+
+ //Send READ ID command
+ NandSendCommand(READ_ID_CMD);
+
+ //Send one address cycle.
+ NandSendAddress(0);
+
+ //Read 5-bytes to idenfity code programmed into the NAND flash devices.
+ //BYTE 0 = Manufacture ID
+ //Byte 1 = Device ID
+ //Byte 2, 3, 4 = Nand part specific information (Page size, Block size etc)
+ for (Index = 0; Index < sizeof(PartInfo); Index++) {
+ PartInfo[Index] = MmioRead16(GPMC_NAND_DATA_0);
+ }
+
+ //Check if the ManufactureId and DeviceId are part of the currently supported nand parts.
+ for (Index = 0; Index < sizeof(gNandPartInfoTable)/sizeof(NAND_PART_INFO_TABLE); Index++) {
+ if (gNandPartInfoTable[Index].ManufactureId == PartInfo[0] && gNandPartInfoTable[Index].DeviceId == PartInfo[1]) {
+ gNandFlashInfo->BlockAddressStart = gNandPartInfoTable[Index].BlockAddressStart;
+ gNandFlashInfo->PageAddressStart = gNandPartInfoTable[Index].PageAddressStart;
+ Found = TRUE;
+ break;
+ }
+ }
+
+ if (Found == FALSE) {
+ DEBUG ((EFI_D_ERROR, "Nand part is not currently supported. Manufacture id: %x, Device id: %x\n", PartInfo[0], PartInfo[1]));
+ return EFI_NOT_FOUND;
+ }
+
+ //Populate NAND_FLASH_INFO based on the result of READ ID command.
+ gNandFlashInfo->ManufactureId = PartInfo[0];
+ gNandFlashInfo->DeviceId = PartInfo[1];
+ NandInfo = PartInfo[3];
+
+ if (PAGE_SIZE(NandInfo) == PAGE_SIZE_2K_VAL) {
+ gNandFlashInfo->PageSize = PAGE_SIZE_2K;
+ } else {
+ DEBUG ((EFI_D_ERROR, "Unknown Page size.\n"));
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (SPARE_AREA_SIZE(NandInfo) == SPARE_AREA_SIZE_64B_VAL) {
+ gNandFlashInfo->SparePageSize = SPARE_AREA_SIZE_64B;
+ } else {
+ DEBUG ((EFI_D_ERROR, "Unknown Spare area size.\n"));
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (BLOCK_SIZE(NandInfo) == BLOCK_SIZE_128K_VAL) {
+ gNandFlashInfo->BlockSize = BLOCK_SIZE_128K;
+ } else {
+ DEBUG ((EFI_D_ERROR, "Unknown Block size.\n"));
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (ORGANIZATION(NandInfo) == ORGANIZATION_X8) {
+ gNandFlashInfo->Organization = 0;
+ } else if (ORGANIZATION(NandInfo) == ORGANIZATION_X16) {
+ gNandFlashInfo->Organization = 1;
+ }
+
+ //Calculate total number of blocks.
+ gNandFlashInfo->NumPagesPerBlock = DivU64x32(gNandFlashInfo->BlockSize, gNandFlashInfo->PageSize);
+
+ return EFI_SUCCESS;
+}
+
+VOID
+NandConfigureEcc (
+ VOID
+ )
+{
+ //Define ECC size 0 and size 1 to 512 bytes
+ MmioWrite32 (GPMC_ECC_SIZE_CONFIG, (ECCSIZE0_512BYTES | ECCSIZE1_512BYTES));
+}
+
+VOID
+NandEnableEcc (
+ VOID
+ )
+{
+ //Clear all the ECC result registers and select ECC result register 1
+ MmioWrite32 (GPMC_ECC_CONTROL, (ECCCLEAR | ECCPOINTER_REG1));
+
+ //Enable ECC engine on CS0
+ MmioWrite32 (GPMC_ECC_CONFIG, (ECCENABLE | ECCCS_0 | ECC16B));
+}
+
+VOID
+NandDisableEcc (
+ VOID
+ )
+{
+ //Turn off ECC engine.
+ MmioWrite32 (GPMC_ECC_CONFIG, ECCDISABLE);
+}
+
+VOID
+NandCalculateEcc (
+ VOID
+ )
+{
+ UINTN Index;
+ UINTN EccResultRegister;
+ UINTN EccResult;
+
+ //Capture 32-bit ECC result for each 512-bytes chunk.
+ //In our case PageSize is 2K so read ECC1-ECC4 result registers and
+ //generate total of 12-bytes of ECC code for the particular page.
+
+ EccResultRegister = GPMC_ECC1_RESULT;
+
+ for (Index = 0; Index < gNum512BytesChunks; Index++) {
+
+ EccResult = MmioRead32 (EccResultRegister);
+
+ //Calculate ECC code from 32-bit ECC result value.
+ //NOTE: Following calculation is not part of TRM. We got this information
+ //from Beagleboard mailing list.
+ gEccCode[Index * 3] = EccResult & 0xFF;
+ gEccCode[(Index * 3) + 1] = (EccResult >> 16) & 0xFF;
+ gEccCode[(Index * 3) + 2] = (((EccResult >> 20) & 0xF0) | ((EccResult >> 8) & 0x0F));
+
+ //Point to next ECC result register.
+ EccResultRegister += 4;
+ }
+}
+
+EFI_STATUS
+NandReadPage (
+ IN UINTN BlockIndex,
+ IN UINTN PageIndex,
+ OUT VOID *Buffer,
+ OUT UINT8 *SpareBuffer
+)
+{
+ UINTN Address;
+ UINTN Index;
+ UINTN NumMainAreaWords = (gNandFlashInfo->PageSize/2);
+ UINTN NumSpareAreaWords = (gNandFlashInfo->SparePageSize/2);
+ UINT16 *MainAreaWordBuffer = Buffer;
+ UINT16 *SpareAreaWordBuffer = (UINT16 *)SpareBuffer;
+ UINTN Timeout = MAX_RETRY_COUNT;
+
+ //Generate device address in bytes to access specific block and page index
+ Address = GetActualPageAddressInBytes(BlockIndex, PageIndex);
+
+ //Send READ command
+ NandSendCommand(PAGE_READ_CMD);
+
+ //Send 5 Address cycles to access specific device address
+ NandSendAddressCycles(Address);
+
+ //Send READ CONFIRM command
+ NandSendCommand(PAGE_READ_CONFIRM_CMD);
+
+ //Poll till device is busy.
+ while (Timeout) {
+ if ((NandReadStatus() & NAND_READY) == NAND_READY) {
+ break;
+ }
+ Timeout--;
+ }
+
+ if (Timeout == 0) {
+ DEBUG ((EFI_D_ERROR, "Read page timed out.\n"));
+ return EFI_TIMEOUT;
+ }
+
+ //Reissue READ command
+ NandSendCommand(PAGE_READ_CMD);
+
+ //Enable ECC engine.
+ NandEnableEcc();
+
+ //Read data into the buffer.
+ for (Index = 0; Index < NumMainAreaWords; Index++) {
+ *MainAreaWordBuffer++ = MmioRead16(GPMC_NAND_DATA_0);
+ }
+
+ //Read spare area into the buffer.
+ for (Index = 0; Index < NumSpareAreaWords; Index++) {
+ *SpareAreaWordBuffer++ = MmioRead16(GPMC_NAND_DATA_0);
+ }
+
+ //Calculate ECC.
+ NandCalculateEcc();
+
+ //Turn off ECC engine.
+ NandDisableEcc();
+
+ //Perform ECC correction.
+ //Need to implement..
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+NandWritePage (
+ IN UINTN BlockIndex,
+ IN UINTN PageIndex,
+ OUT VOID *Buffer,
+ IN UINT8 *SpareBuffer
+)
+{
+ UINTN Address;
+ UINT16 *MainAreaWordBuffer = Buffer;
+ UINT16 *SpareAreaWordBuffer = (UINT16 *)SpareBuffer;
+ UINTN Index;
+ UINTN NandStatus;
+ UINTN Timeout = MAX_RETRY_COUNT;
+
+ //Generate device address in bytes to access specific block and page index
+ Address = GetActualPageAddressInBytes(BlockIndex, PageIndex);
+
+ //Send SERIAL DATA INPUT command
+ NandSendCommand(PROGRAM_PAGE_CMD);
+
+ //Send 5 Address cycles to access specific device address
+ NandSendAddressCycles(Address);
+
+ //Enable ECC engine.
+ NandEnableEcc();
+
+ //Data input from Buffer
+ for (Index = 0; Index < (gNandFlashInfo->PageSize/2); Index++) {
+ MmioWrite16(GPMC_NAND_DATA_0, *MainAreaWordBuffer++);
+
+ //After each write access, device has to wait to accept data.
+ //Currently we may not be programming proper timing parameters to
+ //the GPMC_CONFIGi_0 registers and we would need to figure that out.
+ //Without following delay, page programming fails.
+ gBS->Stall(1);
+ }
+
+ //Calculate ECC.
+ NandCalculateEcc();
+
+ //Turn off ECC engine.
+ NandDisableEcc();
+
+ //Prepare Spare area buffer with ECC codes.
+ SetMem(SpareBuffer, gNandFlashInfo->SparePageSize, 0xFF);
+ CopyMem(&SpareBuffer[ECC_POSITION], gEccCode, gNum512BytesChunks * 3);
+
+ //Program spare area with calculated ECC.
+ for (Index = 0; Index < (gNandFlashInfo->SparePageSize/2); Index++) {
+ MmioWrite16(GPMC_NAND_DATA_0, *SpareAreaWordBuffer++);
+ }
+
+ //Send PROGRAM command
+ NandSendCommand(PROGRAM_PAGE_CONFIRM_CMD);
+
+ //Poll till device is busy.
+ NandStatus = 0;
+ while (Timeout) {
+ NandStatus = NandReadStatus();
+ if ((NandStatus & NAND_READY) == NAND_READY) {
+ break;
+ }
+ Timeout--;
+ }
+
+ if (Timeout == 0) {
+ DEBUG ((EFI_D_ERROR, "Program page timed out.\n"));
+ return EFI_TIMEOUT;
+ }
+
+ //Bit0 indicates Pass/Fail status
+ if (NandStatus & NAND_FAILURE) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+NandEraseBlock (
+ IN UINTN BlockIndex
+)
+{
+ UINTN Address;
+ UINTN NandStatus;
+ UINTN Timeout = MAX_RETRY_COUNT;
+
+ //Generate device address in bytes to access specific block and page index
+ Address = GetActualPageAddressInBytes(BlockIndex, 0);
+
+ //Send ERASE SETUP command
+ NandSendCommand(BLOCK_ERASE_CMD);
+
+ //Send 3 address cycles to device to access Page address and Block address
+ Address >>= 11; //Ignore column addresses
+
+ NandSendAddress(Address & 0xff);
+ Address >>= 8;
+
+ NandSendAddress(Address & 0xff);
+ Address >>= 8;
+
+ NandSendAddress(Address & 0xff);
+
+ //Send ERASE CONFIRM command
+ NandSendCommand(BLOCK_ERASE_CONFIRM_CMD);
+
+ //Poll till device is busy.
+ NandStatus = 0;
+ while (Timeout) {
+ NandStatus = NandReadStatus();
+ if ((NandStatus & NAND_READY) == NAND_READY) {
+ break;
+ }
+ Timeout--;
+ gBS->Stall(1);
+ }
+
+ if (Timeout == 0) {
+ DEBUG ((EFI_D_ERROR, "Erase block timed out for Block: %d.\n", BlockIndex));
+ return EFI_TIMEOUT;
+ }
+
+ //Bit0 indicates Pass/Fail status
+ if (NandStatus & NAND_FAILURE) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+NandReadBlock (
+ IN UINTN StartBlockIndex,
+ IN UINTN EndBlockIndex,
+ OUT VOID *Buffer,
+ OUT VOID *SpareBuffer
+)
+{
+ UINTN BlockIndex;
+ UINTN PageIndex;
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ for (BlockIndex = StartBlockIndex; BlockIndex <= EndBlockIndex; BlockIndex++) {
+ //For each block read number of pages
+ for (PageIndex = 0; PageIndex < gNandFlashInfo->NumPagesPerBlock; PageIndex++) {
+ Status = NandReadPage(BlockIndex, PageIndex, Buffer, SpareBuffer);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ Buffer = ((UINT8 *)Buffer + gNandFlashInfo->PageSize);
+ }
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+NandWriteBlock (
+ IN UINTN StartBlockIndex,
+ IN UINTN EndBlockIndex,
+ OUT VOID *Buffer,
+ OUT VOID *SpareBuffer
+ )
+{
+ UINTN BlockIndex;
+ UINTN PageIndex;
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ for (BlockIndex = StartBlockIndex; BlockIndex <= EndBlockIndex; BlockIndex++) {
+ //Page programming.
+ for (PageIndex = 0; PageIndex < gNandFlashInfo->NumPagesPerBlock; PageIndex++) {
+ Status = NandWritePage(BlockIndex, PageIndex, Buffer, SpareBuffer);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ Buffer = ((UINT8 *)Buffer + gNandFlashInfo->PageSize);
+ }
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+NandFlashReset (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN BOOLEAN ExtendedVerification
+ )
+{
+ UINTN BusyStall = 50; // microSeconds
+ UINTN ResetBusyTimeout = (1000000 / BusyStall); // 1 Second
+
+ //Send RESET command to device.
+ NandSendCommand(RESET_CMD);
+
+ //Wait for 1ms before we check status register.
+ gBS->Stall(1000);
+
+ //Check BIT#5 & BIT#6 in Status register to make sure RESET is done.
+ while ((NandReadStatus() & NAND_RESET_STATUS) != NAND_RESET_STATUS) {
+
+ //In case of extended verification, wait for extended amount of time
+ //to make sure device is reset.
+ if (ExtendedVerification) {
+ if (ResetBusyTimeout == 0) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ gBS->Stall(BusyStall);
+ ResetBusyTimeout--;
+ }
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+NandFlashReadBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSize,
+ OUT VOID *Buffer
+ )
+{
+ UINTN NumBlocks;
+ UINTN EndBlockIndex;
+ EFI_STATUS Status;
+ UINT8 *SpareBuffer = NULL;
+
+ if (Buffer == NULL) {
+ Status = EFI_INVALID_PARAMETER;
+ goto exit;
+ }
+
+ if (Lba > LAST_BLOCK) {
+ Status = EFI_INVALID_PARAMETER;
+ goto exit;
+ }
+
+ if ((BufferSize % gNandFlashInfo->BlockSize) != 0) {
+ Status = EFI_BAD_BUFFER_SIZE;
+ goto exit;
+ }
+
+ NumBlocks = DivU64x32(BufferSize, gNandFlashInfo->BlockSize);
+ EndBlockIndex = ((UINTN)Lba + NumBlocks) - 1;
+
+ SpareBuffer = (UINT8 *)AllocatePool(gNandFlashInfo->SparePageSize);
+ if (SpareBuffer == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto exit;
+ }
+
+ //Read block
+ Status = NandReadBlock((UINTN)Lba, EndBlockIndex, Buffer, SpareBuffer);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "Read block fails: %x\n", Status));
+ goto exit;
+ }
+
+exit:
+ if (SpareBuffer != NULL) {
+ FreePool (SpareBuffer);
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+NandFlashWriteBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSize,
+ IN VOID *Buffer
+ )
+{
+ UINTN BlockIndex;
+ UINTN NumBlocks;
+ UINTN EndBlockIndex;
+ EFI_STATUS Status;
+ UINT8 *SpareBuffer = NULL;
+
+ if (Buffer == NULL) {
+ Status = EFI_INVALID_PARAMETER;
+ goto exit;
+ }
+
+ if (Lba > LAST_BLOCK) {
+ Status = EFI_INVALID_PARAMETER;
+ goto exit;
+ }
+
+ if ((BufferSize % gNandFlashInfo->BlockSize) != 0) {
+ Status = EFI_BAD_BUFFER_SIZE;
+ goto exit;
+ }
+
+ NumBlocks = DivU64x32(BufferSize, gNandFlashInfo->BlockSize);
+ EndBlockIndex = ((UINTN)Lba + NumBlocks) - 1;
+
+ SpareBuffer = (UINT8 *)AllocatePool(gNandFlashInfo->SparePageSize);
+ if (SpareBuffer == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto exit;
+ }
+
+ // Erase block
+ for (BlockIndex = (UINTN)Lba; BlockIndex <= EndBlockIndex; BlockIndex++) {
+ Status = NandEraseBlock(BlockIndex);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "Erase block failed. Status: %x\n", Status));
+ goto exit;
+ }
+ }
+
+ // Program data
+ Status = NandWriteBlock((UINTN)Lba, EndBlockIndex, Buffer, SpareBuffer);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "Block write fails: %x\n", Status));
+ goto exit;
+ }
+
+exit:
+ if (SpareBuffer != NULL) {
+ FreePool (SpareBuffer);
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+NandFlashFlushBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This
+ )
+{
+ return EFI_SUCCESS;
+}
+
+
+
+EFI_BLOCK_IO_MEDIA gNandFlashMedia = {
+ SIGNATURE_32('n','a','n','d'), // MediaId
+ FALSE, // RemovableMedia
+ TRUE, // MediaPresent
+ FALSE, // LogicalPartition
+ FALSE, // ReadOnly
+ FALSE, // WriteCaching
+ 0, // BlockSize
+ 2, // IoAlign
+ 0, // Pad
+ 0 // LastBlock
+};
+
+EFI_BLOCK_IO_PROTOCOL BlockIo =
+{
+ EFI_BLOCK_IO_INTERFACE_REVISION, // Revision
+ &gNandFlashMedia, // *Media
+ NandFlashReset, // Reset
+ NandFlashReadBlocks, // ReadBlocks
+ NandFlashWriteBlocks, // WriteBlocks
+ NandFlashFlushBlocks // FlushBlocks
+};
+
+EFI_STATUS
+NandFlashInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ gNandFlashInfo = (NAND_FLASH_INFO *)AllocateZeroPool (sizeof(NAND_FLASH_INFO));
+
+ //Initialize GPMC module.
+ GpmcInit();
+
+ //Reset NAND part
+ NandFlashReset(&BlockIo, FALSE);
+
+ //Detect NAND part and populate gNandFlashInfo structure
+ Status = NandDetectPart ();
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "Nand part id detection failure: Status: %x\n", Status));
+ return Status;
+ }
+
+ //Count total number of 512Bytes chunk based on the page size.
+ if (gNandFlashInfo->PageSize == PAGE_SIZE_512B) {
+ gNum512BytesChunks = 1;
+ } else if (gNandFlashInfo->PageSize == PAGE_SIZE_2K) {
+ gNum512BytesChunks = 4;
+ } else if (gNandFlashInfo->PageSize == PAGE_SIZE_4K) {
+ gNum512BytesChunks = 8;
+ }
+
+ gEccCode = (UINT8 *)AllocatePool(gNum512BytesChunks * 3);
+ if (gEccCode == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //Configure ECC
+ NandConfigureEcc ();
+
+ //Patch EFI_BLOCK_IO_MEDIA structure.
+ gNandFlashMedia.BlockSize = gNandFlashInfo->BlockSize;
+ gNandFlashMedia.LastBlock = LAST_BLOCK;
+
+ //Publish BlockIO.
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &ImageHandle,
+ &gEfiBlockIoProtocolGuid, &BlockIo,
+ &gEfiDevicePathProtocolGuid, &gDevicePath,
+ NULL
+ );
+ return Status;
+}
+
diff --git a/Omap35xxPkg/Flash/Flash.h b/Omap35xxPkg/Flash/Flash.h
index 9bfdba5d0..46ec4db9e 100644
--- a/Omap35xxPkg/Flash/Flash.h
+++ b/Omap35xxPkg/Flash/Flash.h
@@ -1,106 +1,106 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef FLASH_H
-#define FLASH_H
-
-#include <Uefi.h>
-
-#include <Library/BaseLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/IoLib.h>
-
-#include <Protocol/BlockIo.h>
-#include <Protocol/Cpu.h>
-#include <Omap3530/Omap3530.h>
-
-#define PAGE_SIZE(x) ((x) & 0x01)
-#define PAGE_SIZE_2K_VAL (0x01UL)
-
-#define SPARE_AREA_SIZE(x) (((x) >> 2) & 0x01)
-#define SPARE_AREA_SIZE_64B_VAL (0x1UL)
-
-#define BLOCK_SIZE(x) (((x) >> 4) & 0x01)
-#define BLOCK_SIZE_128K_VAL (0x01UL)
-
-#define ORGANIZATION(x) (((x) >> 6) & 0x01)
-#define ORGANIZATION_X8 (0x0UL)
-#define ORGANIZATION_X16 (0x1UL)
-
-#define PAGE_SIZE_512B (512)
-#define PAGE_SIZE_2K (2048)
-#define PAGE_SIZE_4K (4096)
-#define SPARE_AREA_SIZE_16B (16)
-#define SPARE_AREA_SIZE_64B (64)
-
-#define BLOCK_SIZE_16K (16*1024)
-#define BLOCK_SIZE_128K (128*1024)
-
-#define BLOCK_COUNT (2048)
-#define LAST_BLOCK (BLOCK_COUNT - 1)
-
-#define ECC_POSITION 2
-
-//List of commands.
-#define RESET_CMD 0xFF
-#define READ_ID_CMD 0x90
-
-#define READ_STATUS_CMD 0x70
-
-#define PAGE_READ_CMD 0x00
-#define PAGE_READ_CONFIRM_CMD 0x30
-
-#define BLOCK_ERASE_CMD 0x60
-#define BLOCK_ERASE_CONFIRM_CMD 0xD0
-
-#define PROGRAM_PAGE_CMD 0x80
-#define PROGRAM_PAGE_CONFIRM_CMD 0x10
-
-//Nand status register bit definition
-#define NAND_SUCCESS (0x0UL << 0)
-#define NAND_FAILURE BIT0
-
-#define NAND_BUSY (0x0UL << 6)
-#define NAND_READY BIT6
-
-#define NAND_RESET_STATUS (0x60UL << 0)
-
-#define MAX_RETRY_COUNT 1500
-
-
-typedef struct {
- UINT8 ManufactureId;
- UINT8 DeviceId;
- UINT8 BlockAddressStart; //Start of the Block address in actual NAND
- UINT8 PageAddressStart; //Start of the Page address in actual NAND
-} NAND_PART_INFO_TABLE;
-
-typedef struct {
- UINT8 ManufactureId;
- UINT8 DeviceId;
- UINT8 Organization; //x8 or x16
- UINT32 PageSize;
- UINT32 SparePageSize;
- UINT32 BlockSize;
- UINT32 NumPagesPerBlock;
- UINT8 BlockAddressStart; //Start of the Block address in actual NAND
- UINT8 PageAddressStart; //Start of the Page address in actual NAND
-} NAND_FLASH_INFO;
-
-#endif //FLASH_H
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef FLASH_H
+#define FLASH_H
+
+#include <Uefi.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/IoLib.h>
+
+#include <Protocol/BlockIo.h>
+#include <Protocol/Cpu.h>
+#include <Omap3530/Omap3530.h>
+
+#define PAGE_SIZE(x) ((x) & 0x01)
+#define PAGE_SIZE_2K_VAL (0x01UL)
+
+#define SPARE_AREA_SIZE(x) (((x) >> 2) & 0x01)
+#define SPARE_AREA_SIZE_64B_VAL (0x1UL)
+
+#define BLOCK_SIZE(x) (((x) >> 4) & 0x01)
+#define BLOCK_SIZE_128K_VAL (0x01UL)
+
+#define ORGANIZATION(x) (((x) >> 6) & 0x01)
+#define ORGANIZATION_X8 (0x0UL)
+#define ORGANIZATION_X16 (0x1UL)
+
+#define PAGE_SIZE_512B (512)
+#define PAGE_SIZE_2K (2048)
+#define PAGE_SIZE_4K (4096)
+#define SPARE_AREA_SIZE_16B (16)
+#define SPARE_AREA_SIZE_64B (64)
+
+#define BLOCK_SIZE_16K (16*1024)
+#define BLOCK_SIZE_128K (128*1024)
+
+#define BLOCK_COUNT (2048)
+#define LAST_BLOCK (BLOCK_COUNT - 1)
+
+#define ECC_POSITION 2
+
+//List of commands.
+#define RESET_CMD 0xFF
+#define READ_ID_CMD 0x90
+
+#define READ_STATUS_CMD 0x70
+
+#define PAGE_READ_CMD 0x00
+#define PAGE_READ_CONFIRM_CMD 0x30
+
+#define BLOCK_ERASE_CMD 0x60
+#define BLOCK_ERASE_CONFIRM_CMD 0xD0
+
+#define PROGRAM_PAGE_CMD 0x80
+#define PROGRAM_PAGE_CONFIRM_CMD 0x10
+
+//Nand status register bit definition
+#define NAND_SUCCESS (0x0UL << 0)
+#define NAND_FAILURE BIT0
+
+#define NAND_BUSY (0x0UL << 6)
+#define NAND_READY BIT6
+
+#define NAND_RESET_STATUS (0x60UL << 0)
+
+#define MAX_RETRY_COUNT 1500
+
+
+typedef struct {
+ UINT8 ManufactureId;
+ UINT8 DeviceId;
+ UINT8 BlockAddressStart; //Start of the Block address in actual NAND
+ UINT8 PageAddressStart; //Start of the Page address in actual NAND
+} NAND_PART_INFO_TABLE;
+
+typedef struct {
+ UINT8 ManufactureId;
+ UINT8 DeviceId;
+ UINT8 Organization; //x8 or x16
+ UINT32 PageSize;
+ UINT32 SparePageSize;
+ UINT32 BlockSize;
+ UINT32 NumPagesPerBlock;
+ UINT8 BlockAddressStart; //Start of the Block address in actual NAND
+ UINT8 PageAddressStart; //Start of the Page address in actual NAND
+} NAND_FLASH_INFO;
+
+#endif //FLASH_H
diff --git a/Omap35xxPkg/Flash/Flash.inf b/Omap35xxPkg/Flash/Flash.inf
index 1dfd5bcff..4f12a2748 100644
--- a/Omap35xxPkg/Flash/Flash.inf
+++ b/Omap35xxPkg/Flash/Flash.inf
@@ -1,48 +1,48 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = NandFlash
- FILE_GUID = 4d00ef14-c4e0-426b-81b7-30a00a14aad6
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = NandFlashInitialize
-
-
-[Sources.common]
- Flash.c
-
-[Packages]
- MdePkg/MdePkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- PcdLib
- UefiLib
- UefiDriverEntryPoint
- MemoryAllocationLib
- IoLib
-
-[Guids]
-
-[Protocols]
- gEfiBlockIoProtocolGuid
- gEfiCpuArchProtocolGuid
-
-[Pcd]
- gOmap35xxTokenSpaceGuid.PcdOmap35xxGpmcOffset
-
-[depex]
- TRUE \ No newline at end of file
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = NandFlash
+ FILE_GUID = 4d00ef14-c4e0-426b-81b7-30a00a14aad6
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = NandFlashInitialize
+
+
+[Sources.common]
+ Flash.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ PcdLib
+ UefiLib
+ UefiDriverEntryPoint
+ MemoryAllocationLib
+ IoLib
+
+[Guids]
+
+[Protocols]
+ gEfiBlockIoProtocolGuid
+ gEfiCpuArchProtocolGuid
+
+[Pcd]
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxGpmcOffset
+
+[depex]
+ TRUE \ No newline at end of file
diff --git a/Omap35xxPkg/Gpio/Gpio.c b/Omap35xxPkg/Gpio/Gpio.c
index 33786aeee..c64e6be7b 100644
--- a/Omap35xxPkg/Gpio/Gpio.c
+++ b/Omap35xxPkg/Gpio/Gpio.c
@@ -1,135 +1,135 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Uefi.h>
-
-#include <Library/IoLib.h>
-#include <Library/OmapLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-
-#include <Protocol/EmbeddedGpio.h>
-
-#include <Omap3530/Omap3530.h>
-
-EFI_STATUS
-Get (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- OUT UINTN *Value
- )
-{
- UINTN Port;
- UINTN Pin;
- UINT32 DataInRegister;
-
- if (Value == NULL)
- {
- return EFI_UNSUPPORTED;
- }
-
- Port = GPIO_PORT(Gpio);
- Pin = GPIO_PIN(Gpio);
-
- DataInRegister = GpioBase(Port) + GPIO_DATAIN;
-
- if (MmioRead32 (DataInRegister) & GPIO_DATAIN_MASK(Pin)) {
- *Value = 1;
- } else {
- *Value = 0;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-Set (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- IN EMBEDDED_GPIO_MODE Mode
- )
-{
- UINTN Port;
- UINTN Pin;
- UINT32 OutputEnableRegister;
- UINT32 SetDataOutRegister;
- UINT32 ClearDataOutRegister;
-
- Port = GPIO_PORT(Gpio);
- Pin = GPIO_PIN(Gpio);
-
- OutputEnableRegister = GpioBase(Port) + GPIO_OE;
- SetDataOutRegister = GpioBase(Port) + GPIO_SETDATAOUT;
- ClearDataOutRegister = GpioBase(Port) + GPIO_CLEARDATAOUT;
-
- switch (Mode)
- {
- case GPIO_MODE_INPUT:
- MmioAndThenOr32(OutputEnableRegister, ~GPIO_OE_MASK(Pin), GPIO_OE_INPUT(Pin));
- break;
-
- case GPIO_MODE_OUTPUT_0:
- MmioWrite32 (ClearDataOutRegister, GPIO_CLEARDATAOUT_BIT(Pin));
- MmioAndThenOr32(OutputEnableRegister, ~GPIO_OE_MASK(Pin), GPIO_OE_OUTPUT(Pin));
- break;
-
- case GPIO_MODE_OUTPUT_1:
- MmioWrite32 (SetDataOutRegister, GPIO_SETDATAOUT_BIT(Pin));
- MmioAndThenOr32(OutputEnableRegister, ~GPIO_OE_MASK(Pin), GPIO_OE_OUTPUT(Pin));
- break;
-
- default:
- return EFI_UNSUPPORTED;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-GetMode (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- OUT EMBEDDED_GPIO_MODE *Mode
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-SetPull (
- IN EMBEDDED_GPIO *This,
- IN EMBEDDED_GPIO_PIN Gpio,
- IN EMBEDDED_GPIO_PULL Direction
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-EMBEDDED_GPIO Gpio = {
- Get,
- Set,
- GetMode,
- SetPull
-};
-
-EFI_STATUS
-GpioInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
-
- Status = gBS->InstallMultipleProtocolInterfaces(&ImageHandle, &gEmbeddedGpioProtocolGuid, &Gpio, NULL);
- return Status;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Uefi.h>
+
+#include <Library/IoLib.h>
+#include <Library/OmapLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include <Protocol/EmbeddedGpio.h>
+
+#include <Omap3530/Omap3530.h>
+
+EFI_STATUS
+Get (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ OUT UINTN *Value
+ )
+{
+ UINTN Port;
+ UINTN Pin;
+ UINT32 DataInRegister;
+
+ if (Value == NULL)
+ {
+ return EFI_UNSUPPORTED;
+ }
+
+ Port = GPIO_PORT(Gpio);
+ Pin = GPIO_PIN(Gpio);
+
+ DataInRegister = GpioBase(Port) + GPIO_DATAIN;
+
+ if (MmioRead32 (DataInRegister) & GPIO_DATAIN_MASK(Pin)) {
+ *Value = 1;
+ } else {
+ *Value = 0;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+Set (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ IN EMBEDDED_GPIO_MODE Mode
+ )
+{
+ UINTN Port;
+ UINTN Pin;
+ UINT32 OutputEnableRegister;
+ UINT32 SetDataOutRegister;
+ UINT32 ClearDataOutRegister;
+
+ Port = GPIO_PORT(Gpio);
+ Pin = GPIO_PIN(Gpio);
+
+ OutputEnableRegister = GpioBase(Port) + GPIO_OE;
+ SetDataOutRegister = GpioBase(Port) + GPIO_SETDATAOUT;
+ ClearDataOutRegister = GpioBase(Port) + GPIO_CLEARDATAOUT;
+
+ switch (Mode)
+ {
+ case GPIO_MODE_INPUT:
+ MmioAndThenOr32(OutputEnableRegister, ~GPIO_OE_MASK(Pin), GPIO_OE_INPUT(Pin));
+ break;
+
+ case GPIO_MODE_OUTPUT_0:
+ MmioWrite32 (ClearDataOutRegister, GPIO_CLEARDATAOUT_BIT(Pin));
+ MmioAndThenOr32(OutputEnableRegister, ~GPIO_OE_MASK(Pin), GPIO_OE_OUTPUT(Pin));
+ break;
+
+ case GPIO_MODE_OUTPUT_1:
+ MmioWrite32 (SetDataOutRegister, GPIO_SETDATAOUT_BIT(Pin));
+ MmioAndThenOr32(OutputEnableRegister, ~GPIO_OE_MASK(Pin), GPIO_OE_OUTPUT(Pin));
+ break;
+
+ default:
+ return EFI_UNSUPPORTED;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+GetMode (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ OUT EMBEDDED_GPIO_MODE *Mode
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+SetPull (
+ IN EMBEDDED_GPIO *This,
+ IN EMBEDDED_GPIO_PIN Gpio,
+ IN EMBEDDED_GPIO_PULL Direction
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+EMBEDDED_GPIO Gpio = {
+ Get,
+ Set,
+ GetMode,
+ SetPull
+};
+
+EFI_STATUS
+GpioInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ Status = gBS->InstallMultipleProtocolInterfaces(&ImageHandle, &gEmbeddedGpioProtocolGuid, &Gpio, NULL);
+ return Status;
+}
diff --git a/Omap35xxPkg/Gpio/Gpio.inf b/Omap35xxPkg/Gpio/Gpio.inf
index c20346a4c..2069d2d73 100644
--- a/Omap35xxPkg/Gpio/Gpio.inf
+++ b/Omap35xxPkg/Gpio/Gpio.inf
@@ -1,45 +1,45 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = Gpio
- FILE_GUID = E7D9CAE1-6930-46E3-BDF9-0027446E7DF2
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = GpioInitialize
-
-
-[Sources.common]
- Gpio.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- IoLib
- UefiDriverEntryPoint
- OmapLib
-
-[Guids]
-
-[Protocols]
- gEmbeddedGpioProtocolGuid
-
-[Pcd]
-
-[depex]
- TRUE \ No newline at end of file
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = Gpio
+ FILE_GUID = E7D9CAE1-6930-46E3-BDF9-0027446E7DF2
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = GpioInitialize
+
+
+[Sources.common]
+ Gpio.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ IoLib
+ UefiDriverEntryPoint
+ OmapLib
+
+[Guids]
+
+[Protocols]
+ gEmbeddedGpioProtocolGuid
+
+[Pcd]
+
+[depex]
+ TRUE \ No newline at end of file
diff --git a/Omap35xxPkg/Include/Library/OmapDmaLib.h b/Omap35xxPkg/Include/Library/OmapDmaLib.h
index 0dc4468c9..f13b73379 100755
--- a/Omap35xxPkg/Include/Library/OmapDmaLib.h
+++ b/Omap35xxPkg/Include/Library/OmapDmaLib.h
@@ -1,25 +1,25 @@
-/** @file
-
- Abstractions for simple OMAP DMA.
- OMAP_DMA4 structure elements are described in the OMAP35xx TRM.
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP_DMA_LIB_H__
-#define __OMAP_DMA_LIB_H__
-
-
-// Example from DMA chapter of the OMAP35xx spec
+/** @file
+
+ Abstractions for simple OMAP DMA.
+ OMAP_DMA4 structure elements are described in the OMAP35xx TRM.
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP_DMA_LIB_H__
+#define __OMAP_DMA_LIB_H__
+
+
+// Example from DMA chapter of the OMAP35xx spec
typedef struct {
UINT8 DataType; // DMA4_CSDPi[1:0]
UINT8 ReadPortAccessType; // DMA4_CSDPi[8:7]
@@ -42,10 +42,10 @@ typedef struct {
UINT8 ReadPriority; // DMA4_CCRi[6]
UINT8 WritePriority; // DMA4_CCRi[23]
UINT8 ReadRequestNumber; // DMA4_CCRi[4:0]
- UINT8 WriteRequestNumber; // DMA4_CCRi[20:19]
-} OMAP_DMA4;
-
-
+ UINT8 WriteRequestNumber; // DMA4_CCRi[20:19]
+} OMAP_DMA4;
+
+
/**
Configure OMAP DMA Channel
@@ -56,14 +56,14 @@ typedef struct {
@retval EFI_INVALID_PARAMETER Channel is not valid
@retval EFI_DEVICE_ERROR The system hardware could not map the requested information.
-**/
-EFI_STATUS
-EFIAPI
-EnableDmaChannel (
- IN UINTN Channel,
- IN OMAP_DMA4 *Dma4
- );
-
+**/
+EFI_STATUS
+EFIAPI
+EnableDmaChannel (
+ IN UINTN Channel,
+ IN OMAP_DMA4 *Dma4
+ );
+
/**
Turn of DMA channel configured by EnableDma().
@@ -75,16 +75,16 @@ EnableDmaChannel (
@retval EFI_INVALID_PARAMETER Channel is not valid
@retval EFI_DEVICE_ERROR The system hardware could not map the requested information.
-**/
-EFI_STATUS
-EFIAPI
-DisableDmaChannel (
- IN UINTN Channel,
- IN UINT32 SuccessMask,
- IN UINT32 ErrorMask
- );
-
-
-
-#endif
-
+**/
+EFI_STATUS
+EFIAPI
+DisableDmaChannel (
+ IN UINTN Channel,
+ IN UINT32 SuccessMask,
+ IN UINT32 ErrorMask
+ );
+
+
+
+#endif
+
diff --git a/Omap35xxPkg/Include/Library/OmapLib.h b/Omap35xxPkg/Include/Library/OmapLib.h
index 419227515..80e5e0d2c 100644
--- a/Omap35xxPkg/Include/Library/OmapLib.h
+++ b/Omap35xxPkg/Include/Library/OmapLib.h
@@ -1,44 +1,44 @@
-/** @file
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAPLIB_H__
-#define __OMAPLIB_H__
-
-UINT32
-EFIAPI
-GpioBase (
- IN UINTN Port
- );
-
-UINT32
-EFIAPI
-TimerBase (
- IN UINTN Timer
- );
-
-UINTN
-EFIAPI
-InterruptVectorForTimer (
- IN UINTN TImer
- );
-
-UINT32
-EFIAPI
-UartBase (
- IN UINTN Uart
- );
-
-
-#endif // __OMAPLIB_H__
-
+/** @file
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAPLIB_H__
+#define __OMAPLIB_H__
+
+UINT32
+EFIAPI
+GpioBase (
+ IN UINTN Port
+ );
+
+UINT32
+EFIAPI
+TimerBase (
+ IN UINTN Timer
+ );
+
+UINTN
+EFIAPI
+InterruptVectorForTimer (
+ IN UINTN TImer
+ );
+
+UINT32
+EFIAPI
+UartBase (
+ IN UINTN Uart
+ );
+
+
+#endif // __OMAPLIB_H__
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530.h b/Omap35xxPkg/Include/Omap3530/Omap3530.h
index 1cf99eb03..4d3781576 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530.h
@@ -1,40 +1,40 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530_H__
-#define __OMAP3530_H__
-
-#include "Omap3530Gpio.h"
-#include "Omap3530Interrupt.h"
-#include "Omap3530Prcm.h"
-#include "Omap3530Timer.h"
-#include "Omap3530Uart.h"
-#include "Omap3530Usb.h"
-#include "Omap3530MMCHS.h"
-#include "Omap3530I2c.h"
-#include "Omap3530PadConfiguration.h"
-#include "Omap3530Gpmc.h"
-#include "Omap3530Dma.h"
-
-
-//CONTROL_PBIAS_LITE
-#define CONTROL_PBIAS_LITE 0x48002520
-#define PBIASLITEVMODE0 BIT0
-#define PBIASLITEPWRDNZ0 BIT1
-#define PBIASSPEEDCTRL0 BIT2
-#define PBIASLITEVMODE1 BIT8
-#define PBIASLITEWRDNZ1 BIT9
-
-#endif // __OMAP3530_H__
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530_H__
+#define __OMAP3530_H__
+
+#include "Omap3530Gpio.h"
+#include "Omap3530Interrupt.h"
+#include "Omap3530Prcm.h"
+#include "Omap3530Timer.h"
+#include "Omap3530Uart.h"
+#include "Omap3530Usb.h"
+#include "Omap3530MMCHS.h"
+#include "Omap3530I2c.h"
+#include "Omap3530PadConfiguration.h"
+#include "Omap3530Gpmc.h"
+#include "Omap3530Dma.h"
+
+
+//CONTROL_PBIAS_LITE
+#define CONTROL_PBIAS_LITE 0x48002520
+#define PBIASLITEVMODE0 BIT0
+#define PBIASLITEPWRDNZ0 BIT1
+#define PBIASSPEEDCTRL0 BIT2
+#define PBIASLITEVMODE1 BIT8
+#define PBIASLITEWRDNZ1 BIT9
+
+#endif // __OMAP3530_H__
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Dma.h b/Omap35xxPkg/Include/Omap3530/Omap3530Dma.h
index 242c32533..5db9a0797 100755
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Dma.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Dma.h
@@ -1,130 +1,130 @@
-/** @file
-
- Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530DMA_H__
-#define __OMAP3530DMA_H__
-
-
-#define DMA4_MAX_CHANNEL 31
-
-#define DMA4_IRQENABLE_L(_i) (0x48056018 + (0x4*(_i)))
-
-#define DMA4_CCR(_i) (0x48056080 + (0x60*(_i)))
-#define DMA4_CICR(_i) (0x48056088 + (0x60*(_i)))
-#define DMA4_CSR(_i) (0x4805608c + (0x60*(_i)))
-#define DMA4_CSDP(_i) (0x48056090 + (0x60*(_i)))
-#define DMA4_CEN(_i) (0x48056094 + (0x60*(_i)))
-#define DMA4_CFN(_i) (0x48056098 + (0x60*(_i)))
-#define DMA4_CSSA(_i) (0x4805609c + (0x60*(_i)))
-#define DMA4_CDSA(_i) (0x480560a0 + (0x60*(_i)))
-#define DMA4_CSEI(_i) (0x480560a4 + (0x60*(_i)))
-#define DMA4_CSFI(_i) (0x480560a8 + (0x60*(_i)))
-#define DMA4_CDEI(_i) (0x480560ac + (0x60*(_i)))
-#define DMA4_CDFI(_i) (0x480560b0 + (0x60*(_i)))
-
-#define DMA4_GCR (0x48056078)
-
-// Channel Source Destination parameters
-#define DMA4_CSDP_DATA_TYPE8 0
-#define DMA4_CSDP_DATA_TYPE16 1
-#define DMA4_CSDP_DATA_TYPE32 2
-
-#define DMA4_CSDP_SRC_PACKED BIT6
-#define DMA4_CSDP_SRC_NONPACKED 0
-
-#define DMA4_CSDP_SRC_BURST_EN (0x0 << 7)
-#define DMA4_CSDP_SRC_BURST_EN16 (0x1 << 7)
-#define DMA4_CSDP_SRC_BURST_EN32 (0x2 << 7)
-#define DMA4_CSDP_SRC_BURST_EN64 (0x3 << 7)
-
-#define DMA4_CSDP_DST_PACKED BIT13
-#define DMA4_CSDP_DST_NONPACKED 0
-
-#define DMA4_CSDP_BURST_EN (0x0 << 14)
-#define DMA4_CSDP_BURST_EN16 (0x1 << 14)
-#define DMA4_CSDP_BURST_EN32 (0x2 << 14)
-#define DMA4_CSDP_BURST_EN64 (0x3 << 14)
-
-#define DMA4_CSDP_WRITE_MODE_NONE_POSTED (0x0 << 16)
-#define DMA4_CSDP_WRITE_MODE_POSTED (0x1 << 16)
-#define DMA4_CSDP_WRITE_MODE_LAST_NON_POSTED (0x2 << 16)
-
-#define DMA4_CSDP_DST_ENDIAN_LOCK_LOCK BIT18
-#define DMA4_CSDP_DST_ENDIAN_LOCK_ADAPT 0
-
-#define DMA4_CSDP_DST_ENDIAN_BIG BIT19
-#define DMA4_CSDP_DST_ENDIAN_LITTLE 0
-
-#define DMA4_CSDP_SRC_ENDIAN_LOCK_LOCK BIT20
-#define DMA4_CSDP_SRC_ENDIAN_LOCK_ADAPT 0
-
-#define DMA4_CSDP_SRC_ENDIAN_BIG BIT21
-#define DMA4_CSDP_SRC_ENDIAN_LITTLE 0
-
-// Channel Control
-#define DMA4_CCR_SYNCHRO_CONTROL_MASK 0x1f
-
-#define DMA4_CCR_FS_ELEMENT (0 | 0)
-#define DMA4_CCR_FS_BLOCK (0 | BIT18)
-#define DMA4_CCR_FS_FRAME (BIT5 | 0)
-#define DMA4_CCR_FS_PACKET (BIT5 | BIT18)
-
-#define DMA4_CCR_READ_PRIORITY_HIGH BIT6
-#define DMA4_CCR_READ_PRIORITY_LOW 0
-
-#define DMA4_CCR_ENABLE BIT7
-#define DMA4_CCR_DISABLE 0
-
-#define DMA4_CCR_SUSPEND_SENSITIVE_IGNORE BIT8
-#define DMA4_CCR_SUSPEND_SENSITIVE 0
-
-#define DMA4_CCR_RD_ACTIVE BIT9
-#define DMA4_CCR_WR_ACTIVE BIT10
-
-#define DMA4_CCR_SRC_AMODE (0 | 0)
-#define DMA4_CCR_SRC_AMODE_POST_INC (0 | BIT12)
-#define DMA4_CCR_SRC_AMODE_SINGLE_INDEX (BIT13 | 0)
-#define DMA4_CCR_SRC_AMODE_DOUBLE_INDEX (BIT13 | BIT12)
-
-#define DMA4_CCR_DST_AMODE (0 | 0)
-#define DMA4_CCR_DST_AMODE_POST_INC (0 | BIT14)
-#define DMA4_CCR_DST_AMODE_SINGLE_INDEX (BIT15 | 0)
-#define DMA4_CCR_DST_AMODE_DOUBLE_INDEX (BIT15 | BIT14)
-
-#define DMA4_CCR_CONST_FILL_ENABLE BIT16
-#define DMA4_CCR_TRANSPARENT_COPY_ENABLE BIT17
-
-#define DMA4_CCR_SEL_SRC_DEST_SYNC_SOURCE BIT24
-
-#define DMA4_CSR_DROP BIT1
-#define DMA4_CSR_HALF BIT2
-#define DMA4_CSR_FRAME BIT3
-#define DMA4_CSR_LAST BIT4
-#define DMA4_CSR_BLOCK BIT5
-#define DMA4_CSR_SYNC BIT6
-#define DMA4_CSR_PKT BIT7
-#define DMA4_CSR_TRANS_ERR BIT8
-#define DMA4_CSR_SECURE_ERR BIT9
-#define DMA4_CSR_SUPERVISOR_ERR BIT10
-#define DMA4_CSR_MISALIGNED_ADRS_ERR BIT11
-#define DMA4_CSR_DRAIN_END BIT12
-#define DMA4_CSR_RESET 0x1FE
-#define DMA4_CSR_ERR (DMA4_CSR_TRANS_ERR | DMA4_CSR_SECURE_ERR | DMA4_CSR_SUPERVISOR_ERR | DMA4_CSR_MISALIGNED_ADRS_ERR)
-
-// same mapping as CSR except for SYNC. Enable all since we are polling
-#define DMA4_CICR_ENABLE_ALL 0x1FBE
-
-
-#endif
-
+/** @file
+
+ Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530DMA_H__
+#define __OMAP3530DMA_H__
+
+
+#define DMA4_MAX_CHANNEL 31
+
+#define DMA4_IRQENABLE_L(_i) (0x48056018 + (0x4*(_i)))
+
+#define DMA4_CCR(_i) (0x48056080 + (0x60*(_i)))
+#define DMA4_CICR(_i) (0x48056088 + (0x60*(_i)))
+#define DMA4_CSR(_i) (0x4805608c + (0x60*(_i)))
+#define DMA4_CSDP(_i) (0x48056090 + (0x60*(_i)))
+#define DMA4_CEN(_i) (0x48056094 + (0x60*(_i)))
+#define DMA4_CFN(_i) (0x48056098 + (0x60*(_i)))
+#define DMA4_CSSA(_i) (0x4805609c + (0x60*(_i)))
+#define DMA4_CDSA(_i) (0x480560a0 + (0x60*(_i)))
+#define DMA4_CSEI(_i) (0x480560a4 + (0x60*(_i)))
+#define DMA4_CSFI(_i) (0x480560a8 + (0x60*(_i)))
+#define DMA4_CDEI(_i) (0x480560ac + (0x60*(_i)))
+#define DMA4_CDFI(_i) (0x480560b0 + (0x60*(_i)))
+
+#define DMA4_GCR (0x48056078)
+
+// Channel Source Destination parameters
+#define DMA4_CSDP_DATA_TYPE8 0
+#define DMA4_CSDP_DATA_TYPE16 1
+#define DMA4_CSDP_DATA_TYPE32 2
+
+#define DMA4_CSDP_SRC_PACKED BIT6
+#define DMA4_CSDP_SRC_NONPACKED 0
+
+#define DMA4_CSDP_SRC_BURST_EN (0x0 << 7)
+#define DMA4_CSDP_SRC_BURST_EN16 (0x1 << 7)
+#define DMA4_CSDP_SRC_BURST_EN32 (0x2 << 7)
+#define DMA4_CSDP_SRC_BURST_EN64 (0x3 << 7)
+
+#define DMA4_CSDP_DST_PACKED BIT13
+#define DMA4_CSDP_DST_NONPACKED 0
+
+#define DMA4_CSDP_BURST_EN (0x0 << 14)
+#define DMA4_CSDP_BURST_EN16 (0x1 << 14)
+#define DMA4_CSDP_BURST_EN32 (0x2 << 14)
+#define DMA4_CSDP_BURST_EN64 (0x3 << 14)
+
+#define DMA4_CSDP_WRITE_MODE_NONE_POSTED (0x0 << 16)
+#define DMA4_CSDP_WRITE_MODE_POSTED (0x1 << 16)
+#define DMA4_CSDP_WRITE_MODE_LAST_NON_POSTED (0x2 << 16)
+
+#define DMA4_CSDP_DST_ENDIAN_LOCK_LOCK BIT18
+#define DMA4_CSDP_DST_ENDIAN_LOCK_ADAPT 0
+
+#define DMA4_CSDP_DST_ENDIAN_BIG BIT19
+#define DMA4_CSDP_DST_ENDIAN_LITTLE 0
+
+#define DMA4_CSDP_SRC_ENDIAN_LOCK_LOCK BIT20
+#define DMA4_CSDP_SRC_ENDIAN_LOCK_ADAPT 0
+
+#define DMA4_CSDP_SRC_ENDIAN_BIG BIT21
+#define DMA4_CSDP_SRC_ENDIAN_LITTLE 0
+
+// Channel Control
+#define DMA4_CCR_SYNCHRO_CONTROL_MASK 0x1f
+
+#define DMA4_CCR_FS_ELEMENT (0 | 0)
+#define DMA4_CCR_FS_BLOCK (0 | BIT18)
+#define DMA4_CCR_FS_FRAME (BIT5 | 0)
+#define DMA4_CCR_FS_PACKET (BIT5 | BIT18)
+
+#define DMA4_CCR_READ_PRIORITY_HIGH BIT6
+#define DMA4_CCR_READ_PRIORITY_LOW 0
+
+#define DMA4_CCR_ENABLE BIT7
+#define DMA4_CCR_DISABLE 0
+
+#define DMA4_CCR_SUSPEND_SENSITIVE_IGNORE BIT8
+#define DMA4_CCR_SUSPEND_SENSITIVE 0
+
+#define DMA4_CCR_RD_ACTIVE BIT9
+#define DMA4_CCR_WR_ACTIVE BIT10
+
+#define DMA4_CCR_SRC_AMODE (0 | 0)
+#define DMA4_CCR_SRC_AMODE_POST_INC (0 | BIT12)
+#define DMA4_CCR_SRC_AMODE_SINGLE_INDEX (BIT13 | 0)
+#define DMA4_CCR_SRC_AMODE_DOUBLE_INDEX (BIT13 | BIT12)
+
+#define DMA4_CCR_DST_AMODE (0 | 0)
+#define DMA4_CCR_DST_AMODE_POST_INC (0 | BIT14)
+#define DMA4_CCR_DST_AMODE_SINGLE_INDEX (BIT15 | 0)
+#define DMA4_CCR_DST_AMODE_DOUBLE_INDEX (BIT15 | BIT14)
+
+#define DMA4_CCR_CONST_FILL_ENABLE BIT16
+#define DMA4_CCR_TRANSPARENT_COPY_ENABLE BIT17
+
+#define DMA4_CCR_SEL_SRC_DEST_SYNC_SOURCE BIT24
+
+#define DMA4_CSR_DROP BIT1
+#define DMA4_CSR_HALF BIT2
+#define DMA4_CSR_FRAME BIT3
+#define DMA4_CSR_LAST BIT4
+#define DMA4_CSR_BLOCK BIT5
+#define DMA4_CSR_SYNC BIT6
+#define DMA4_CSR_PKT BIT7
+#define DMA4_CSR_TRANS_ERR BIT8
+#define DMA4_CSR_SECURE_ERR BIT9
+#define DMA4_CSR_SUPERVISOR_ERR BIT10
+#define DMA4_CSR_MISALIGNED_ADRS_ERR BIT11
+#define DMA4_CSR_DRAIN_END BIT12
+#define DMA4_CSR_RESET 0x1FE
+#define DMA4_CSR_ERR (DMA4_CSR_TRANS_ERR | DMA4_CSR_SECURE_ERR | DMA4_CSR_SUPERVISOR_ERR | DMA4_CSR_MISALIGNED_ADRS_ERR)
+
+// same mapping as CSR except for SYNC. Enable all since we are polling
+#define DMA4_CICR_ENABLE_ALL 0x1FBE
+
+
+#endif
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Gpio.h b/Omap35xxPkg/Include/Omap3530/Omap3530Gpio.h
index 94822d453..e45a0f23b 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Gpio.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Gpio.h
@@ -1,131 +1,131 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530GPIO_H__
-#define __OMAP3530GPIO_H__
-
-#define GPIO1_BASE (0x48310000)
-#define GPIO2_BASE (0x49050000)
-#define GPIO3_BASE (0x49052000)
-#define GPIO4_BASE (0x49054000)
-#define GPIO5_BASE (0x49056000)
-#define GPIO6_BASE (0x49058000)
-
-#define GPIO_SYSCONFIG (0x0010)
-#define GPIO_SYSSTATUS (0x0014)
-#define GPIO_IRQSTATUS1 (0x0018)
-#define GPIO_IRQENABLE1 (0x001C)
-#define GPIO_WAKEUPENABLE (0x0020)
-#define GPIO_IRQSTATUS2 (0x0028)
-#define GPIO_IRQENABLE2 (0x002C)
-#define GPIO_CTRL (0x0030)
-#define GPIO_OE (0x0034)
-#define GPIO_DATAIN (0x0038)
-#define GPIO_DATAOUT (0x003C)
-#define GPIO_LEVELDETECT0 (0x0040)
-#define GPIO_LEVELDETECT1 (0x0044)
-#define GPIO_RISINGDETECT (0x0048)
-#define GPIO_FALLINGDETECT (0x004C)
-#define GPIO_DEBOUNCENABLE (0x0050)
-#define GPIO_DEBOUNCINGTIME (0x0054)
-#define GPIO_CLEARIRQENABLE1 (0x0060)
-#define GPIO_SETIRQENABLE1 (0x0064)
-#define GPIO_CLEARIRQENABLE2 (0x0070)
-#define GPIO_SETIRQENABLE2 (0x0074)
-#define GPIO_CLEARWKUENA (0x0080)
-#define GPIO_SETWKUENA (0x0084)
-#define GPIO_CLEARDATAOUT (0x0090)
-#define GPIO_SETDATAOUT (0x0094)
-
-#define GPIO_SYSCONFIG_IDLEMODE_MASK (3UL << 3)
-#define GPIO_SYSCONFIG_IDLEMODE_FORCE (0UL << 3)
-#define GPIO_SYSCONFIG_IDLEMODE_NONE BIT3
-#define GPIO_SYSCONFIG_IDLEMODE_SMART (2UL << 3)
-#define GPIO_SYSCONFIG_ENAWAKEUP_MASK BIT2
-#define GPIO_SYSCONFIG_ENAWAKEUP_DISABLE (0UL << 2)
-#define GPIO_SYSCONFIG_ENAWAKEUP_ENABLE BIT2
-#define GPIO_SYSCONFIG_SOFTRESET_MASK BIT1
-#define GPIO_SYSCONFIG_SOFTRESET_NORMAL (0UL << 1)
-#define GPIO_SYSCONFIG_SOFTRESET_RESET BIT1
-#define GPIO_SYSCONFIG_AUTOIDLE_MASK BIT0
-#define GPIO_SYSCONFIG_AUTOIDLE_FREE_RUN (0UL << 0)
-#define GPIO_SYSCONFIG_AUTOIDLE_ON BIT0
-
-#define GPIO_SYSSTATUS_RESETDONE_MASK BIT0
-#define GPIO_SYSSTATUS_RESETDONE_ONGOING (0UL << 0)
-#define GPIO_SYSSTATUS_RESETDONE_COMPLETE BIT0
-
-#define GPIO_IRQSTATUS_MASK(x) (1UL << (x))
-#define GPIO_IRQSTATUS_NOT_TRIGGERED(x) (0UL << (x))
-#define GPIO_IRQSTATUS_TRIGGERED(x) (1UL << (x))
-#define GPIO_IRQSTATUS_CLEAR(x) (1UL << (x))
-
-#define GPIO_IRQENABLE_MASK(x) (1UL << (x))
-#define GPIO_IRQENABLE_DISABLE(x) (0UL << (x))
-#define GPIO_IRQENABLE_ENABLE(x) (1UL << (x))
-
-#define GPIO_WAKEUPENABLE_MASK(x) (1UL << (x))
-#define GPIO_WAKEUPENABLE_DISABLE(x) (0UL << (x))
-#define GPIO_WAKEUPENABLE_ENABLE(x) (1UL << (x))
-
-#define GPIO_CTRL_GATINGRATIO_MASK (3UL << 1)
-#define GPIO_CTRL_GATINGRATIO_DIV_1 (0UL << 1)
-#define GPIO_CTRL_GATINGRATIO_DIV_2 BIT1
-#define GPIO_CTRL_GATINGRATIO_DIV_4 (2UL << 1)
-#define GPIO_CTRL_GATINGRATIO_DIV_8 (3UL << 1)
-#define GPIO_CTRL_DISABLEMODULE_MASK BIT0
-#define GPIO_CTRL_DISABLEMODULE_ENABLE (0UL << 0)
-#define GPIO_CTRL_DISABLEMODULE_DISABLE BIT0
-
-#define GPIO_OE_MASK(x) (1UL << (x))
-#define GPIO_OE_OUTPUT(x) (0UL << (x))
-#define GPIO_OE_INPUT(x) (1UL << (x))
-
-#define GPIO_DATAIN_MASK(x) (1UL << (x))
-
-#define GPIO_DATAOUT_MASK(x) (1UL << (x))
-
-#define GPIO_LEVELDETECT_MASK(x) (1UL << (x))
-#define GPIO_LEVELDETECT_DISABLE(x) (0UL << (x))
-#define GPIO_LEVELDETECT_ENABLE(x) (1UL << (x))
-
-#define GPIO_RISINGDETECT_MASK(x) (1UL << (x))
-#define GPIO_RISINGDETECT_DISABLE(x) (0UL << (x))
-#define GPIO_RISINGDETECT_ENABLE(x) (1UL << (x))
-
-#define GPIO_FALLINGDETECT_MASK(x) (1UL << (x))
-#define GPIO_FALLINGDETECT_DISABLE(x) (0UL << (x))
-#define GPIO_FALLINGDETECT_ENABLE(x) (1UL << (x))
-
-#define GPIO_DEBOUNCENABLE_MASK(x) (1UL << (x))
-#define GPIO_DEBOUNCENABLE_DISABLE(x) (0UL << (x))
-#define GPIO_DEBOUNCENABLE_ENABLE(x) (1UL << (x))
-
-#define GPIO_DEBOUNCINGTIME_MASK (0xFF)
-#define GPIO_DEBOUNCINGTIME_US(x) ((((x) / 31) - 1) & GPIO_DEBOUNCINGTIME_MASK)
-
-#define GPIO_CLEARIRQENABLE_BIT(x) (1UL << (x))
-
-#define GPIO_SETIRQENABLE_BIT(x) (1UL << (x))
-
-#define GPIO_CLEARWKUENA_BIT(x) (1UL << (x))
-
-#define GPIO_SETWKUENA_BIT(x) (1UL << (x))
-
-#define GPIO_CLEARDATAOUT_BIT(x) (1UL << (x))
-
-#define GPIO_SETDATAOUT_BIT(x) (1UL << (x))
-
-#endif // __OMAP3530GPIO_H__
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530GPIO_H__
+#define __OMAP3530GPIO_H__
+
+#define GPIO1_BASE (0x48310000)
+#define GPIO2_BASE (0x49050000)
+#define GPIO3_BASE (0x49052000)
+#define GPIO4_BASE (0x49054000)
+#define GPIO5_BASE (0x49056000)
+#define GPIO6_BASE (0x49058000)
+
+#define GPIO_SYSCONFIG (0x0010)
+#define GPIO_SYSSTATUS (0x0014)
+#define GPIO_IRQSTATUS1 (0x0018)
+#define GPIO_IRQENABLE1 (0x001C)
+#define GPIO_WAKEUPENABLE (0x0020)
+#define GPIO_IRQSTATUS2 (0x0028)
+#define GPIO_IRQENABLE2 (0x002C)
+#define GPIO_CTRL (0x0030)
+#define GPIO_OE (0x0034)
+#define GPIO_DATAIN (0x0038)
+#define GPIO_DATAOUT (0x003C)
+#define GPIO_LEVELDETECT0 (0x0040)
+#define GPIO_LEVELDETECT1 (0x0044)
+#define GPIO_RISINGDETECT (0x0048)
+#define GPIO_FALLINGDETECT (0x004C)
+#define GPIO_DEBOUNCENABLE (0x0050)
+#define GPIO_DEBOUNCINGTIME (0x0054)
+#define GPIO_CLEARIRQENABLE1 (0x0060)
+#define GPIO_SETIRQENABLE1 (0x0064)
+#define GPIO_CLEARIRQENABLE2 (0x0070)
+#define GPIO_SETIRQENABLE2 (0x0074)
+#define GPIO_CLEARWKUENA (0x0080)
+#define GPIO_SETWKUENA (0x0084)
+#define GPIO_CLEARDATAOUT (0x0090)
+#define GPIO_SETDATAOUT (0x0094)
+
+#define GPIO_SYSCONFIG_IDLEMODE_MASK (3UL << 3)
+#define GPIO_SYSCONFIG_IDLEMODE_FORCE (0UL << 3)
+#define GPIO_SYSCONFIG_IDLEMODE_NONE BIT3
+#define GPIO_SYSCONFIG_IDLEMODE_SMART (2UL << 3)
+#define GPIO_SYSCONFIG_ENAWAKEUP_MASK BIT2
+#define GPIO_SYSCONFIG_ENAWAKEUP_DISABLE (0UL << 2)
+#define GPIO_SYSCONFIG_ENAWAKEUP_ENABLE BIT2
+#define GPIO_SYSCONFIG_SOFTRESET_MASK BIT1
+#define GPIO_SYSCONFIG_SOFTRESET_NORMAL (0UL << 1)
+#define GPIO_SYSCONFIG_SOFTRESET_RESET BIT1
+#define GPIO_SYSCONFIG_AUTOIDLE_MASK BIT0
+#define GPIO_SYSCONFIG_AUTOIDLE_FREE_RUN (0UL << 0)
+#define GPIO_SYSCONFIG_AUTOIDLE_ON BIT0
+
+#define GPIO_SYSSTATUS_RESETDONE_MASK BIT0
+#define GPIO_SYSSTATUS_RESETDONE_ONGOING (0UL << 0)
+#define GPIO_SYSSTATUS_RESETDONE_COMPLETE BIT0
+
+#define GPIO_IRQSTATUS_MASK(x) (1UL << (x))
+#define GPIO_IRQSTATUS_NOT_TRIGGERED(x) (0UL << (x))
+#define GPIO_IRQSTATUS_TRIGGERED(x) (1UL << (x))
+#define GPIO_IRQSTATUS_CLEAR(x) (1UL << (x))
+
+#define GPIO_IRQENABLE_MASK(x) (1UL << (x))
+#define GPIO_IRQENABLE_DISABLE(x) (0UL << (x))
+#define GPIO_IRQENABLE_ENABLE(x) (1UL << (x))
+
+#define GPIO_WAKEUPENABLE_MASK(x) (1UL << (x))
+#define GPIO_WAKEUPENABLE_DISABLE(x) (0UL << (x))
+#define GPIO_WAKEUPENABLE_ENABLE(x) (1UL << (x))
+
+#define GPIO_CTRL_GATINGRATIO_MASK (3UL << 1)
+#define GPIO_CTRL_GATINGRATIO_DIV_1 (0UL << 1)
+#define GPIO_CTRL_GATINGRATIO_DIV_2 BIT1
+#define GPIO_CTRL_GATINGRATIO_DIV_4 (2UL << 1)
+#define GPIO_CTRL_GATINGRATIO_DIV_8 (3UL << 1)
+#define GPIO_CTRL_DISABLEMODULE_MASK BIT0
+#define GPIO_CTRL_DISABLEMODULE_ENABLE (0UL << 0)
+#define GPIO_CTRL_DISABLEMODULE_DISABLE BIT0
+
+#define GPIO_OE_MASK(x) (1UL << (x))
+#define GPIO_OE_OUTPUT(x) (0UL << (x))
+#define GPIO_OE_INPUT(x) (1UL << (x))
+
+#define GPIO_DATAIN_MASK(x) (1UL << (x))
+
+#define GPIO_DATAOUT_MASK(x) (1UL << (x))
+
+#define GPIO_LEVELDETECT_MASK(x) (1UL << (x))
+#define GPIO_LEVELDETECT_DISABLE(x) (0UL << (x))
+#define GPIO_LEVELDETECT_ENABLE(x) (1UL << (x))
+
+#define GPIO_RISINGDETECT_MASK(x) (1UL << (x))
+#define GPIO_RISINGDETECT_DISABLE(x) (0UL << (x))
+#define GPIO_RISINGDETECT_ENABLE(x) (1UL << (x))
+
+#define GPIO_FALLINGDETECT_MASK(x) (1UL << (x))
+#define GPIO_FALLINGDETECT_DISABLE(x) (0UL << (x))
+#define GPIO_FALLINGDETECT_ENABLE(x) (1UL << (x))
+
+#define GPIO_DEBOUNCENABLE_MASK(x) (1UL << (x))
+#define GPIO_DEBOUNCENABLE_DISABLE(x) (0UL << (x))
+#define GPIO_DEBOUNCENABLE_ENABLE(x) (1UL << (x))
+
+#define GPIO_DEBOUNCINGTIME_MASK (0xFF)
+#define GPIO_DEBOUNCINGTIME_US(x) ((((x) / 31) - 1) & GPIO_DEBOUNCINGTIME_MASK)
+
+#define GPIO_CLEARIRQENABLE_BIT(x) (1UL << (x))
+
+#define GPIO_SETIRQENABLE_BIT(x) (1UL << (x))
+
+#define GPIO_CLEARWKUENA_BIT(x) (1UL << (x))
+
+#define GPIO_SETWKUENA_BIT(x) (1UL << (x))
+
+#define GPIO_CLEARDATAOUT_BIT(x) (1UL << (x))
+
+#define GPIO_SETDATAOUT_BIT(x) (1UL << (x))
+
+#endif // __OMAP3530GPIO_H__
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Gpmc.h b/Omap35xxPkg/Include/Omap3530/Omap3530Gpmc.h
index 6cdd5f511..6943d303e 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Gpmc.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Gpmc.h
@@ -1,107 +1,107 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530GPMC_H__
-#define __OMAP3530GPMC_H__
-
-#define GPMC_BASE (0x6E000000)
-
-//GPMC NAND definitions.
-#define GPMC_SYSCONFIG (GPMC_BASE + 0x10)
-#define SMARTIDLEMODE (0x2UL << 3)
-
-#define GPMC_SYSSTATUS (GPMC_BASE + 0x14)
-#define GPMC_IRQSTATUS (GPMC_BASE + 0x18)
-#define GPMC_IRQENABLE (GPMC_BASE + 0x1C)
-
-#define GPMC_TIMEOUT_CONTROL (GPMC_BASE + 0x40)
-#define TIMEOUTENABLE BIT0
-#define TIMEOUTDISABLE (0x0UL << 0)
-
-#define GPMC_ERR_ADDRESS (GPMC_BASE + 0x44)
-#define GPMC_ERR_TYPE (GPMC_BASE + 0x48)
-
-#define GPMC_CONFIG (GPMC_BASE + 0x50)
-#define WRITEPROTECT_HIGH BIT4
-#define WRITEPROTECT_LOW (0x0UL << 4)
-
-#define GPMC_STATUS (GPMC_BASE + 0x54)
-
-#define GPMC_CONFIG1_0 (GPMC_BASE + 0x60)
-#define DEVICETYPE_NOR (0x0UL << 10)
-#define DEVICETYPE_NAND (0x2UL << 10)
-#define DEVICESIZE_X8 (0x0UL << 12)
-#define DEVICESIZE_X16 BIT12
-
-#define GPMC_CONFIG2_0 (GPMC_BASE + 0x64)
-#define CSONTIME (0x0UL << 0)
-#define CSRDOFFTIME (0x14UL << 8)
-#define CSWROFFTIME (0x14UL << 16)
-
-#define GPMC_CONFIG3_0 (GPMC_BASE + 0x68)
-#define ADVRDOFFTIME (0x14UL << 8)
-#define ADVWROFFTIME (0x14UL << 16)
-
-#define GPMC_CONFIG4_0 (GPMC_BASE + 0x6C)
-#define OEONTIME BIT0
-#define OEOFFTIME (0xFUL << 8)
-#define WEONTIME BIT16
-#define WEOFFTIME (0xFUL << 24)
-
-#define GPMC_CONFIG5_0 (GPMC_BASE + 0x70)
-#define RDCYCLETIME (0x14UL << 0)
-#define WRCYCLETIME (0x14UL << 8)
-#define RDACCESSTIME (0xCUL << 16)
-#define PAGEBURSTACCESSTIME BIT24
-
-#define GPMC_CONFIG6_0 (GPMC_BASE + 0x74)
-#define CYCLE2CYCLESAMECSEN BIT7
-#define CYCLE2CYCLEDELAY (0xAUL << 8)
-#define WRDATAONADMUXBUS (0xFUL << 16)
-#define WRACCESSTIME BIT24
-
-#define GPMC_CONFIG7_0 (GPMC_BASE + 0x78)
-#define BASEADDRESS (0x30UL << 0)
-#define CSVALID BIT6
-#define MASKADDRESS_128MB (0x8UL << 8)
-
-#define GPMC_NAND_COMMAND_0 (GPMC_BASE + 0x7C)
-#define GPMC_NAND_ADDRESS_0 (GPMC_BASE + 0x80)
-#define GPMC_NAND_DATA_0 (GPMC_BASE + 0x84)
-
-#define GPMC_ECC_CONFIG (GPMC_BASE + 0x1F4)
-#define ECCENABLE BIT0
-#define ECCDISABLE (0x0UL << 0)
-#define ECCCS_0 (0x0UL << 1)
-#define ECC16B BIT7
-
-#define GPMC_ECC_CONTROL (GPMC_BASE + 0x1F8)
-#define ECCPOINTER_REG1 BIT0
-#define ECCCLEAR BIT8
-
-#define GPMC_ECC_SIZE_CONFIG (GPMC_BASE + 0x1FC)
-#define ECCSIZE0_512BYTES (0xFFUL << 12)
-#define ECCSIZE1_512BYTES (0xFFUL << 22)
-
-#define GPMC_ECC1_RESULT (GPMC_BASE + 0x200)
-#define GPMC_ECC2_RESULT (GPMC_BASE + 0x204)
-#define GPMC_ECC3_RESULT (GPMC_BASE + 0x208)
-#define GPMC_ECC4_RESULT (GPMC_BASE + 0x20C)
-#define GPMC_ECC5_RESULT (GPMC_BASE + 0x210)
-#define GPMC_ECC6_RESULT (GPMC_BASE + 0x214)
-#define GPMC_ECC7_RESULT (GPMC_BASE + 0x218)
-#define GPMC_ECC8_RESULT (GPMC_BASE + 0x21C)
-#define GPMC_ECC9_RESULT (GPMC_BASE + 0x220)
-
-#endif //__OMAP3530GPMC_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530GPMC_H__
+#define __OMAP3530GPMC_H__
+
+#define GPMC_BASE (0x6E000000)
+
+//GPMC NAND definitions.
+#define GPMC_SYSCONFIG (GPMC_BASE + 0x10)
+#define SMARTIDLEMODE (0x2UL << 3)
+
+#define GPMC_SYSSTATUS (GPMC_BASE + 0x14)
+#define GPMC_IRQSTATUS (GPMC_BASE + 0x18)
+#define GPMC_IRQENABLE (GPMC_BASE + 0x1C)
+
+#define GPMC_TIMEOUT_CONTROL (GPMC_BASE + 0x40)
+#define TIMEOUTENABLE BIT0
+#define TIMEOUTDISABLE (0x0UL << 0)
+
+#define GPMC_ERR_ADDRESS (GPMC_BASE + 0x44)
+#define GPMC_ERR_TYPE (GPMC_BASE + 0x48)
+
+#define GPMC_CONFIG (GPMC_BASE + 0x50)
+#define WRITEPROTECT_HIGH BIT4
+#define WRITEPROTECT_LOW (0x0UL << 4)
+
+#define GPMC_STATUS (GPMC_BASE + 0x54)
+
+#define GPMC_CONFIG1_0 (GPMC_BASE + 0x60)
+#define DEVICETYPE_NOR (0x0UL << 10)
+#define DEVICETYPE_NAND (0x2UL << 10)
+#define DEVICESIZE_X8 (0x0UL << 12)
+#define DEVICESIZE_X16 BIT12
+
+#define GPMC_CONFIG2_0 (GPMC_BASE + 0x64)
+#define CSONTIME (0x0UL << 0)
+#define CSRDOFFTIME (0x14UL << 8)
+#define CSWROFFTIME (0x14UL << 16)
+
+#define GPMC_CONFIG3_0 (GPMC_BASE + 0x68)
+#define ADVRDOFFTIME (0x14UL << 8)
+#define ADVWROFFTIME (0x14UL << 16)
+
+#define GPMC_CONFIG4_0 (GPMC_BASE + 0x6C)
+#define OEONTIME BIT0
+#define OEOFFTIME (0xFUL << 8)
+#define WEONTIME BIT16
+#define WEOFFTIME (0xFUL << 24)
+
+#define GPMC_CONFIG5_0 (GPMC_BASE + 0x70)
+#define RDCYCLETIME (0x14UL << 0)
+#define WRCYCLETIME (0x14UL << 8)
+#define RDACCESSTIME (0xCUL << 16)
+#define PAGEBURSTACCESSTIME BIT24
+
+#define GPMC_CONFIG6_0 (GPMC_BASE + 0x74)
+#define CYCLE2CYCLESAMECSEN BIT7
+#define CYCLE2CYCLEDELAY (0xAUL << 8)
+#define WRDATAONADMUXBUS (0xFUL << 16)
+#define WRACCESSTIME BIT24
+
+#define GPMC_CONFIG7_0 (GPMC_BASE + 0x78)
+#define BASEADDRESS (0x30UL << 0)
+#define CSVALID BIT6
+#define MASKADDRESS_128MB (0x8UL << 8)
+
+#define GPMC_NAND_COMMAND_0 (GPMC_BASE + 0x7C)
+#define GPMC_NAND_ADDRESS_0 (GPMC_BASE + 0x80)
+#define GPMC_NAND_DATA_0 (GPMC_BASE + 0x84)
+
+#define GPMC_ECC_CONFIG (GPMC_BASE + 0x1F4)
+#define ECCENABLE BIT0
+#define ECCDISABLE (0x0UL << 0)
+#define ECCCS_0 (0x0UL << 1)
+#define ECC16B BIT7
+
+#define GPMC_ECC_CONTROL (GPMC_BASE + 0x1F8)
+#define ECCPOINTER_REG1 BIT0
+#define ECCCLEAR BIT8
+
+#define GPMC_ECC_SIZE_CONFIG (GPMC_BASE + 0x1FC)
+#define ECCSIZE0_512BYTES (0xFFUL << 12)
+#define ECCSIZE1_512BYTES (0xFFUL << 22)
+
+#define GPMC_ECC1_RESULT (GPMC_BASE + 0x200)
+#define GPMC_ECC2_RESULT (GPMC_BASE + 0x204)
+#define GPMC_ECC3_RESULT (GPMC_BASE + 0x208)
+#define GPMC_ECC4_RESULT (GPMC_BASE + 0x20C)
+#define GPMC_ECC5_RESULT (GPMC_BASE + 0x210)
+#define GPMC_ECC6_RESULT (GPMC_BASE + 0x214)
+#define GPMC_ECC7_RESULT (GPMC_BASE + 0x218)
+#define GPMC_ECC8_RESULT (GPMC_BASE + 0x21C)
+#define GPMC_ECC9_RESULT (GPMC_BASE + 0x220)
+
+#endif //__OMAP3530GPMC_H__
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530I2c.h b/Omap35xxPkg/Include/Omap3530/Omap3530I2c.h
index 61e1bf5c0..31d4d5ea6 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530I2c.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530I2c.h
@@ -1,62 +1,62 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530I2C_H__
-#define __OMAP3530I2C_H__
-
-//I2C register definitions.
-#define I2C1BASE 0x48070000
-
-#define I2C_IE (I2C1BASE + 0x4)
-#define XRDY_IE BIT4
-#define RRDY_IE BIT3
-#define ARDY_IE BIT2
-#define NACK_IE BIT1
-
-#define I2C_STAT (I2C1BASE + 0x8)
-#define BB BIT12
-#define XRDY BIT4
-#define RRDY BIT3
-#define ARDY BIT2
-#define NACK BIT1
-
-#define I2C_WE (I2C1BASE + 0xC)
-#define I2C_SYSS (I2C1BASE + 0x10)
-#define I2C_BUF (I2C1BASE + 0x14)
-#define I2C_CNT (I2C1BASE + 0x18)
-#define I2C_DATA (I2C1BASE + 0x1C)
-#define I2C_SYSC (I2C1BASE + 0x20)
-
-#define I2C_CON (I2C1BASE + 0x24)
-#define STT BIT0
-#define STP BIT1
-#define XSA BIT8
-#define TRX BIT9
-#define MST BIT10
-#define I2C_EN BIT15
-
-#define I2C_OA0 (I2C1BASE + 0x28)
-#define I2C_SA (I2C1BASE + 0x2C)
-#define I2C_PSC (I2C1BASE + 0x30)
-#define I2C_SCLL (I2C1BASE + 0x34)
-#define I2C_SCLH (I2C1BASE + 0x38)
-#define I2C_SYSTEST (I2C1BASE + 0x3C)
-#define I2C_BUFSTAT (I2C1BASE + 0x40)
-#define I2C_OA1 (I2C1BASE + 0x44)
-#define I2C_OA2 (I2C1BASE + 0x48)
-#define I2C_OA3 (I2C1BASE + 0x4C)
-#define I2C_ACTOA (I2C1BASE + 0x50)
-#define I2C_SBLOCK (I2C1BASE + 0x54)
-
-#endif //__OMAP3530I2C_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530I2C_H__
+#define __OMAP3530I2C_H__
+
+//I2C register definitions.
+#define I2C1BASE 0x48070000
+
+#define I2C_IE (I2C1BASE + 0x4)
+#define XRDY_IE BIT4
+#define RRDY_IE BIT3
+#define ARDY_IE BIT2
+#define NACK_IE BIT1
+
+#define I2C_STAT (I2C1BASE + 0x8)
+#define BB BIT12
+#define XRDY BIT4
+#define RRDY BIT3
+#define ARDY BIT2
+#define NACK BIT1
+
+#define I2C_WE (I2C1BASE + 0xC)
+#define I2C_SYSS (I2C1BASE + 0x10)
+#define I2C_BUF (I2C1BASE + 0x14)
+#define I2C_CNT (I2C1BASE + 0x18)
+#define I2C_DATA (I2C1BASE + 0x1C)
+#define I2C_SYSC (I2C1BASE + 0x20)
+
+#define I2C_CON (I2C1BASE + 0x24)
+#define STT BIT0
+#define STP BIT1
+#define XSA BIT8
+#define TRX BIT9
+#define MST BIT10
+#define I2C_EN BIT15
+
+#define I2C_OA0 (I2C1BASE + 0x28)
+#define I2C_SA (I2C1BASE + 0x2C)
+#define I2C_PSC (I2C1BASE + 0x30)
+#define I2C_SCLL (I2C1BASE + 0x34)
+#define I2C_SCLH (I2C1BASE + 0x38)
+#define I2C_SYSTEST (I2C1BASE + 0x3C)
+#define I2C_BUFSTAT (I2C1BASE + 0x40)
+#define I2C_OA1 (I2C1BASE + 0x44)
+#define I2C_OA2 (I2C1BASE + 0x48)
+#define I2C_OA3 (I2C1BASE + 0x4C)
+#define I2C_ACTOA (I2C1BASE + 0x50)
+#define I2C_SBLOCK (I2C1BASE + 0x54)
+
+#endif //__OMAP3530I2C_H__
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Interrupt.h b/Omap35xxPkg/Include/Omap3530/Omap3530Interrupt.h
index 9d1036d0d..774d87301 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Interrupt.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Interrupt.h
@@ -1,48 +1,48 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530INTERRUPT_H__
-#define __OMAP3530INTERRUPT_H__
-
-#define INTERRUPT_BASE (0x48200000)
-
-#define INT_NROF_VECTORS (96)
-#define MAX_VECTOR (INT_NROF_VECTORS - 1)
-#define INTCPS_SYSCONFIG (INTERRUPT_BASE + 0x0010)
-#define INTCPS_SYSSTATUS (INTERRUPT_BASE + 0x0014)
-#define INTCPS_SIR_IRQ (INTERRUPT_BASE + 0x0040)
-#define INTCPS_SIR_IFQ (INTERRUPT_BASE + 0x0044)
-#define INTCPS_CONTROL (INTERRUPT_BASE + 0x0048)
-#define INTCPS_PROTECTION (INTERRUPT_BASE + 0x004C)
-#define INTCPS_IDLE (INTERRUPT_BASE + 0x0050)
-#define INTCPS_IRQ_PRIORITY (INTERRUPT_BASE + 0x0060)
-#define INTCPS_FIQ_PRIORITY (INTERRUPT_BASE + 0x0064)
-#define INTCPS_THRESHOLD (INTERRUPT_BASE + 0x0068)
-#define INTCPS_ITR(n) (INTERRUPT_BASE + 0x0080 + (0x20 * (n)))
-#define INTCPS_MIR(n) (INTERRUPT_BASE + 0x0084 + (0x20 * (n)))
-#define INTCPS_MIR_CLEAR(n) (INTERRUPT_BASE + 0x0088 + (0x20 * (n)))
-#define INTCPS_MIR_SET(n) (INTERRUPT_BASE + 0x008C + (0x20 * (n)))
-#define INTCPS_ISR_SET(n) (INTERRUPT_BASE + 0x0090 + (0x20 * (n)))
-#define INTCPS_ISR_CLEAR(n) (INTERRUPT_BASE + 0x0094 + (0x20 * (n)))
-#define INTCPS_PENDING_IRQ(n) (INTERRUPT_BASE + 0x0098 + (0x20 * (n)))
-#define INTCPS_PENDING_FIQ(n) (INTERRUPT_BASE + 0x009C + (0x20 * (n)))
-#define INTCPS_ILR(m) (INTERRUPT_BASE + 0x0100 + (0x04 * (m)))
-
-#define INTCPS_ILR_FIQ BIT0
-#define INTCPS_SIR_IRQ_MASK (0x7F)
-#define INTCPS_CONTROL_NEWIRQAGR BIT0
-#define INTCPS_CONTROL_NEWFIQAGR BIT1
-
-#endif // __OMAP3530INTERRUPT_H__
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530INTERRUPT_H__
+#define __OMAP3530INTERRUPT_H__
+
+#define INTERRUPT_BASE (0x48200000)
+
+#define INT_NROF_VECTORS (96)
+#define MAX_VECTOR (INT_NROF_VECTORS - 1)
+#define INTCPS_SYSCONFIG (INTERRUPT_BASE + 0x0010)
+#define INTCPS_SYSSTATUS (INTERRUPT_BASE + 0x0014)
+#define INTCPS_SIR_IRQ (INTERRUPT_BASE + 0x0040)
+#define INTCPS_SIR_IFQ (INTERRUPT_BASE + 0x0044)
+#define INTCPS_CONTROL (INTERRUPT_BASE + 0x0048)
+#define INTCPS_PROTECTION (INTERRUPT_BASE + 0x004C)
+#define INTCPS_IDLE (INTERRUPT_BASE + 0x0050)
+#define INTCPS_IRQ_PRIORITY (INTERRUPT_BASE + 0x0060)
+#define INTCPS_FIQ_PRIORITY (INTERRUPT_BASE + 0x0064)
+#define INTCPS_THRESHOLD (INTERRUPT_BASE + 0x0068)
+#define INTCPS_ITR(n) (INTERRUPT_BASE + 0x0080 + (0x20 * (n)))
+#define INTCPS_MIR(n) (INTERRUPT_BASE + 0x0084 + (0x20 * (n)))
+#define INTCPS_MIR_CLEAR(n) (INTERRUPT_BASE + 0x0088 + (0x20 * (n)))
+#define INTCPS_MIR_SET(n) (INTERRUPT_BASE + 0x008C + (0x20 * (n)))
+#define INTCPS_ISR_SET(n) (INTERRUPT_BASE + 0x0090 + (0x20 * (n)))
+#define INTCPS_ISR_CLEAR(n) (INTERRUPT_BASE + 0x0094 + (0x20 * (n)))
+#define INTCPS_PENDING_IRQ(n) (INTERRUPT_BASE + 0x0098 + (0x20 * (n)))
+#define INTCPS_PENDING_FIQ(n) (INTERRUPT_BASE + 0x009C + (0x20 * (n)))
+#define INTCPS_ILR(m) (INTERRUPT_BASE + 0x0100 + (0x04 * (m)))
+
+#define INTCPS_ILR_FIQ BIT0
+#define INTCPS_SIR_IRQ_MASK (0x7F)
+#define INTCPS_CONTROL_NEWIRQAGR BIT0
+#define INTCPS_CONTROL_NEWFIQAGR BIT1
+
+#endif // __OMAP3530INTERRUPT_H__
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530MMCHS.h b/Omap35xxPkg/Include/Omap3530/Omap3530MMCHS.h
index 1b3e734d6..5bebe6c50 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530MMCHS.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530MMCHS.h
@@ -1,214 +1,214 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530SDIO_H__
-#define __OMAP3530SDIO_H__
-
-//MMC/SD/SDIO1 register definitions.
-#define MMCHS1BASE 0x4809C000
-#define MMC_REFERENCE_CLK (96000000)
-
-#define MMCHS_SYSCONFIG (MMCHS1BASE + 0x10)
-#define SOFTRESET BIT1
-#define ENAWAKEUP BIT2
-
-#define MMCHS_SYSSTATUS (MMCHS1BASE + 0x14)
-#define RESETDONE_MASK BIT0
-#define RESETDONE BIT0
-
-#define MMCHS_CSRE (MMCHS1BASE + 0x24)
-#define MMCHS_SYSTEST (MMCHS1BASE + 0x28)
-
-#define MMCHS_CON (MMCHS1BASE + 0x2C)
-#define OD BIT0
-#define NOINIT (0x0UL << 1)
-#define INIT BIT1
-#define HR BIT2
-#define STR BIT3
-#define MODE BIT4
-#define DW8_1_4_BIT (0x0UL << 5)
-#define DW8_8_BIT BIT5
-#define MIT BIT6
-#define CDP BIT7
-#define WPP BIT8
-#define CTPL BIT11
-#define CEATA_OFF (0x0UL << 12)
-#define CEATA_ON BIT12
-
-#define MMCHS_PWCNT (MMCHS1BASE + 0x30)
-
-#define MMCHS_BLK (MMCHS1BASE + 0x104)
-#define BLEN_512BYTES (0x200UL << 0)
-
-#define MMCHS_ARG (MMCHS1BASE + 0x108)
-
-#define MMCHS_CMD (MMCHS1BASE + 0x10C)
-#define DE_ENABLE BIT0
-#define BCE_ENABLE BIT1
-#define ACEN_ENABLE BIT2
-#define DDIR_READ BIT4
-#define DDIR_WRITE (0x0UL << 4)
-#define MSBS_SGLEBLK (0x0UL << 5)
-#define MSBS_MULTBLK BIT5
-#define RSP_TYPE_MASK (0x3UL << 16)
-#define RSP_TYPE_136BITS BIT16
-#define RSP_TYPE_48BITS (0x2UL << 16)
-#define CCCE_ENABLE BIT19
-#define CICE_ENABLE BIT20
-#define DP_ENABLE BIT21
-#define INDX(CMD_INDX) ((CMD_INDX & 0x3F) << 24)
-
-#define MMCHS_RSP10 (MMCHS1BASE + 0x110)
-#define MMCHS_RSP32 (MMCHS1BASE + 0x114)
-#define MMCHS_RSP54 (MMCHS1BASE + 0x118)
-#define MMCHS_RSP76 (MMCHS1BASE + 0x11C)
-#define MMCHS_DATA (MMCHS1BASE + 0x120)
-
-#define MMCHS_PSTATE (MMCHS1BASE + 0x124)
-#define CMDI_MASK BIT0
-#define CMDI_ALLOWED (0x0UL << 0)
-#define CMDI_NOT_ALLOWED BIT0
-#define DATI_MASK BIT1
-#define DATI_ALLOWED (0x0UL << 1)
-#define DATI_NOT_ALLOWED BIT1
-
-#define MMCHS_HCTL (MMCHS1BASE + 0x128)
-#define DTW_1_BIT (0x0UL << 1)
-#define DTW_4_BIT BIT1
-#define SDBP_MASK BIT8
-#define SDBP_OFF (0x0UL << 8)
-#define SDBP_ON BIT8
-#define SDVS_1_8_V (0x5UL << 9)
-#define SDVS_3_0_V (0x6UL << 9)
-#define IWE BIT24
-
-#define MMCHS_SYSCTL (MMCHS1BASE + 0x12C)
-#define ICE BIT0
-#define ICS_MASK BIT1
-#define ICS BIT1
-#define CEN BIT2
-#define CLKD_MASK (0x3FFUL << 6)
-#define CLKD_80KHZ (0x258UL) //(96*1000/80)/2
-#define CLKD_400KHZ (0xF0UL)
-#define DTO_MASK (0xFUL << 16)
-#define DTO_VAL (0xEUL << 16)
-#define SRA BIT24
-#define SRC_MASK BIT25
-#define SRC BIT25
-#define SRD BIT26
-
-#define MMCHS_STAT (MMCHS1BASE + 0x130)
-#define CC BIT0
-#define TC BIT1
-#define BWR BIT4
-#define BRR BIT5
-#define ERRI BIT15
-#define CTO BIT16
-#define DTO BIT20
-#define DCRC BIT21
-#define DEB BIT22
-
-#define MMCHS_IE (MMCHS1BASE + 0x134)
-#define CC_EN BIT0
-#define TC_EN BIT1
-#define BWR_EN BIT4
-#define BRR_EN BIT5
-#define CTO_EN BIT16
-#define CCRC_EN BIT17
-#define CEB_EN BIT18
-#define CIE_EN BIT19
-#define DTO_EN BIT20
-#define DCRC_EN BIT21
-#define DEB_EN BIT22
-#define CERR_EN BIT28
-#define BADA_EN BIT29
-
-#define MMCHS_ISE (MMCHS1BASE + 0x138)
-#define CC_SIGEN BIT0
-#define TC_SIGEN BIT1
-#define BWR_SIGEN BIT4
-#define BRR_SIGEN BIT5
-#define CTO_SIGEN BIT16
-#define CCRC_SIGEN BIT17
-#define CEB_SIGEN BIT18
-#define CIE_SIGEN BIT19
-#define DTO_SIGEN BIT20
-#define DCRC_SIGEN BIT21
-#define DEB_SIGEN BIT22
-#define CERR_SIGEN BIT28
-#define BADA_SIGEN BIT29
-
-#define MMCHS_AC12 (MMCHS1BASE + 0x13C)
-
-#define MMCHS_CAPA (MMCHS1BASE + 0x140)
-#define VS30 BIT25
-#define VS18 BIT26
-
-#define MMCHS_CUR_CAPA (MMCHS1BASE + 0x148)
-#define MMCHS_REV (MMCHS1BASE + 0x1FC)
-
-#define CMD0 INDX(0)
-#define CMD0_INT_EN (CC_EN | CEB_EN)
-
-#define CMD1 (INDX(1) | RSP_TYPE_48BITS)
-#define CMD1_INT_EN (CC_EN | CEB_EN | CTO_EN)
-
-#define CMD2 (INDX(2) | CCCE_ENABLE | RSP_TYPE_136BITS)
-#define CMD2_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define CMD3 (INDX(3) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
-#define CMD3_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define CMD5 (INDX(5) | RSP_TYPE_48BITS)
-#define CMD5_INT_EN (CC_EN | CEB_EN | CTO_EN)
-
-#define CMD7 (INDX(7) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
-#define CMD7_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define CMD8 (INDX(8) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
-#define CMD8_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-//Reserved(0)[12:31], Supply voltage(1)[11:8], check pattern(0xCE)[7:0] = 0x1CE
-#define CMD8_ARG (0x0UL << 12 | BIT8 | 0xCEUL << 0)
-
-#define CMD9 (INDX(9) | CCCE_ENABLE | RSP_TYPE_136BITS)
-#define CMD9_INT_EN (CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define CMD16 (INDX(16) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
-#define CMD16_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define CMD17 (INDX(17) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | DDIR_READ)
-#define CMD17_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BRR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
-
-#define CMD18 (INDX(18) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | MSBS_MULTBLK | DDIR_READ | BCE_ENABLE | DE_ENABLE)
-#define CMD18_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BRR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
-
-#define CMD23 (INDX(23) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
-#define CMD23_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define CMD24 (INDX(24) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | DDIR_WRITE)
-#define CMD24_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BWR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
-
-#define CMD25 (INDX(25) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | MSBS_MULTBLK | DDIR_READ | BCE_ENABLE | DE_ENABLE)
-#define CMD25_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BRR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
-
-#define CMD55 (INDX(55) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
-#define CMD55_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define ACMD41 (INDX(41) | RSP_TYPE_48BITS)
-#define ACMD41_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#define ACMD6 (INDX(6) | RSP_TYPE_48BITS)
-#define ACMD6_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
-
-#endif //__OMAP3530SDIO_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530SDIO_H__
+#define __OMAP3530SDIO_H__
+
+//MMC/SD/SDIO1 register definitions.
+#define MMCHS1BASE 0x4809C000
+#define MMC_REFERENCE_CLK (96000000)
+
+#define MMCHS_SYSCONFIG (MMCHS1BASE + 0x10)
+#define SOFTRESET BIT1
+#define ENAWAKEUP BIT2
+
+#define MMCHS_SYSSTATUS (MMCHS1BASE + 0x14)
+#define RESETDONE_MASK BIT0
+#define RESETDONE BIT0
+
+#define MMCHS_CSRE (MMCHS1BASE + 0x24)
+#define MMCHS_SYSTEST (MMCHS1BASE + 0x28)
+
+#define MMCHS_CON (MMCHS1BASE + 0x2C)
+#define OD BIT0
+#define NOINIT (0x0UL << 1)
+#define INIT BIT1
+#define HR BIT2
+#define STR BIT3
+#define MODE BIT4
+#define DW8_1_4_BIT (0x0UL << 5)
+#define DW8_8_BIT BIT5
+#define MIT BIT6
+#define CDP BIT7
+#define WPP BIT8
+#define CTPL BIT11
+#define CEATA_OFF (0x0UL << 12)
+#define CEATA_ON BIT12
+
+#define MMCHS_PWCNT (MMCHS1BASE + 0x30)
+
+#define MMCHS_BLK (MMCHS1BASE + 0x104)
+#define BLEN_512BYTES (0x200UL << 0)
+
+#define MMCHS_ARG (MMCHS1BASE + 0x108)
+
+#define MMCHS_CMD (MMCHS1BASE + 0x10C)
+#define DE_ENABLE BIT0
+#define BCE_ENABLE BIT1
+#define ACEN_ENABLE BIT2
+#define DDIR_READ BIT4
+#define DDIR_WRITE (0x0UL << 4)
+#define MSBS_SGLEBLK (0x0UL << 5)
+#define MSBS_MULTBLK BIT5
+#define RSP_TYPE_MASK (0x3UL << 16)
+#define RSP_TYPE_136BITS BIT16
+#define RSP_TYPE_48BITS (0x2UL << 16)
+#define CCCE_ENABLE BIT19
+#define CICE_ENABLE BIT20
+#define DP_ENABLE BIT21
+#define INDX(CMD_INDX) ((CMD_INDX & 0x3F) << 24)
+
+#define MMCHS_RSP10 (MMCHS1BASE + 0x110)
+#define MMCHS_RSP32 (MMCHS1BASE + 0x114)
+#define MMCHS_RSP54 (MMCHS1BASE + 0x118)
+#define MMCHS_RSP76 (MMCHS1BASE + 0x11C)
+#define MMCHS_DATA (MMCHS1BASE + 0x120)
+
+#define MMCHS_PSTATE (MMCHS1BASE + 0x124)
+#define CMDI_MASK BIT0
+#define CMDI_ALLOWED (0x0UL << 0)
+#define CMDI_NOT_ALLOWED BIT0
+#define DATI_MASK BIT1
+#define DATI_ALLOWED (0x0UL << 1)
+#define DATI_NOT_ALLOWED BIT1
+
+#define MMCHS_HCTL (MMCHS1BASE + 0x128)
+#define DTW_1_BIT (0x0UL << 1)
+#define DTW_4_BIT BIT1
+#define SDBP_MASK BIT8
+#define SDBP_OFF (0x0UL << 8)
+#define SDBP_ON BIT8
+#define SDVS_1_8_V (0x5UL << 9)
+#define SDVS_3_0_V (0x6UL << 9)
+#define IWE BIT24
+
+#define MMCHS_SYSCTL (MMCHS1BASE + 0x12C)
+#define ICE BIT0
+#define ICS_MASK BIT1
+#define ICS BIT1
+#define CEN BIT2
+#define CLKD_MASK (0x3FFUL << 6)
+#define CLKD_80KHZ (0x258UL) //(96*1000/80)/2
+#define CLKD_400KHZ (0xF0UL)
+#define DTO_MASK (0xFUL << 16)
+#define DTO_VAL (0xEUL << 16)
+#define SRA BIT24
+#define SRC_MASK BIT25
+#define SRC BIT25
+#define SRD BIT26
+
+#define MMCHS_STAT (MMCHS1BASE + 0x130)
+#define CC BIT0
+#define TC BIT1
+#define BWR BIT4
+#define BRR BIT5
+#define ERRI BIT15
+#define CTO BIT16
+#define DTO BIT20
+#define DCRC BIT21
+#define DEB BIT22
+
+#define MMCHS_IE (MMCHS1BASE + 0x134)
+#define CC_EN BIT0
+#define TC_EN BIT1
+#define BWR_EN BIT4
+#define BRR_EN BIT5
+#define CTO_EN BIT16
+#define CCRC_EN BIT17
+#define CEB_EN BIT18
+#define CIE_EN BIT19
+#define DTO_EN BIT20
+#define DCRC_EN BIT21
+#define DEB_EN BIT22
+#define CERR_EN BIT28
+#define BADA_EN BIT29
+
+#define MMCHS_ISE (MMCHS1BASE + 0x138)
+#define CC_SIGEN BIT0
+#define TC_SIGEN BIT1
+#define BWR_SIGEN BIT4
+#define BRR_SIGEN BIT5
+#define CTO_SIGEN BIT16
+#define CCRC_SIGEN BIT17
+#define CEB_SIGEN BIT18
+#define CIE_SIGEN BIT19
+#define DTO_SIGEN BIT20
+#define DCRC_SIGEN BIT21
+#define DEB_SIGEN BIT22
+#define CERR_SIGEN BIT28
+#define BADA_SIGEN BIT29
+
+#define MMCHS_AC12 (MMCHS1BASE + 0x13C)
+
+#define MMCHS_CAPA (MMCHS1BASE + 0x140)
+#define VS30 BIT25
+#define VS18 BIT26
+
+#define MMCHS_CUR_CAPA (MMCHS1BASE + 0x148)
+#define MMCHS_REV (MMCHS1BASE + 0x1FC)
+
+#define CMD0 INDX(0)
+#define CMD0_INT_EN (CC_EN | CEB_EN)
+
+#define CMD1 (INDX(1) | RSP_TYPE_48BITS)
+#define CMD1_INT_EN (CC_EN | CEB_EN | CTO_EN)
+
+#define CMD2 (INDX(2) | CCCE_ENABLE | RSP_TYPE_136BITS)
+#define CMD2_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define CMD3 (INDX(3) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
+#define CMD3_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define CMD5 (INDX(5) | RSP_TYPE_48BITS)
+#define CMD5_INT_EN (CC_EN | CEB_EN | CTO_EN)
+
+#define CMD7 (INDX(7) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
+#define CMD7_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define CMD8 (INDX(8) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
+#define CMD8_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+//Reserved(0)[12:31], Supply voltage(1)[11:8], check pattern(0xCE)[7:0] = 0x1CE
+#define CMD8_ARG (0x0UL << 12 | BIT8 | 0xCEUL << 0)
+
+#define CMD9 (INDX(9) | CCCE_ENABLE | RSP_TYPE_136BITS)
+#define CMD9_INT_EN (CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define CMD16 (INDX(16) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
+#define CMD16_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define CMD17 (INDX(17) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | DDIR_READ)
+#define CMD17_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BRR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
+
+#define CMD18 (INDX(18) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | MSBS_MULTBLK | DDIR_READ | BCE_ENABLE | DE_ENABLE)
+#define CMD18_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BRR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
+
+#define CMD23 (INDX(23) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
+#define CMD23_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define CMD24 (INDX(24) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | DDIR_WRITE)
+#define CMD24_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BWR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
+
+#define CMD25 (INDX(25) | DP_ENABLE | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS | MSBS_MULTBLK | DDIR_READ | BCE_ENABLE | DE_ENABLE)
+#define CMD25_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | TC_EN | BRR_EN | CTO_EN | DTO_EN | DCRC_EN | DEB_EN | CEB_EN)
+
+#define CMD55 (INDX(55) | CICE_ENABLE | CCCE_ENABLE | RSP_TYPE_48BITS)
+#define CMD55_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define ACMD41 (INDX(41) | RSP_TYPE_48BITS)
+#define ACMD41_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#define ACMD6 (INDX(6) | RSP_TYPE_48BITS)
+#define ACMD6_INT_EN (CERR_EN | CIE_EN | CCRC_EN | CC_EN | CEB_EN | CTO_EN)
+
+#endif //__OMAP3530SDIO_H__
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530PadConfiguration.h b/Omap35xxPkg/Include/Omap3530/Omap3530PadConfiguration.h
index d23156cf0..1588e1d4d 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530PadConfiguration.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530PadConfiguration.h
@@ -1,303 +1,303 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530_PAD_CONFIGURATION_H__
-#define __OMAP3530_PAD_CONFIGURATION_H__
-
-#define SYSTEM_CONTROL_MODULE_BASE 0x48002000
-
-//Pin definition
-#define SDRC_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x030)
-#define SDRC_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x032)
-#define SDRC_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x034)
-#define SDRC_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x036)
-#define SDRC_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x038)
-#define SDRC_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x03A)
-#define SDRC_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x03C)
-#define SDRC_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x03E)
-#define SDRC_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x040)
-#define SDRC_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x042)
-#define SDRC_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x044)
-#define SDRC_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x046)
-#define SDRC_D12 (SYSTEM_CONTROL_MODULE_BASE + 0x048)
-#define SDRC_D13 (SYSTEM_CONTROL_MODULE_BASE + 0x04A)
-#define SDRC_D14 (SYSTEM_CONTROL_MODULE_BASE + 0x04C)
-#define SDRC_D15 (SYSTEM_CONTROL_MODULE_BASE + 0x04E)
-#define SDRC_D16 (SYSTEM_CONTROL_MODULE_BASE + 0x050)
-#define SDRC_D17 (SYSTEM_CONTROL_MODULE_BASE + 0x052)
-#define SDRC_D18 (SYSTEM_CONTROL_MODULE_BASE + 0x054)
-#define SDRC_D19 (SYSTEM_CONTROL_MODULE_BASE + 0x056)
-#define SDRC_D20 (SYSTEM_CONTROL_MODULE_BASE + 0x058)
-#define SDRC_D21 (SYSTEM_CONTROL_MODULE_BASE + 0x05A)
-#define SDRC_D22 (SYSTEM_CONTROL_MODULE_BASE + 0x05C)
-#define SDRC_D23 (SYSTEM_CONTROL_MODULE_BASE + 0x05E)
-#define SDRC_D24 (SYSTEM_CONTROL_MODULE_BASE + 0x060)
-#define SDRC_D25 (SYSTEM_CONTROL_MODULE_BASE + 0x062)
-#define SDRC_D26 (SYSTEM_CONTROL_MODULE_BASE + 0x064)
-#define SDRC_D27 (SYSTEM_CONTROL_MODULE_BASE + 0x066)
-#define SDRC_D28 (SYSTEM_CONTROL_MODULE_BASE + 0x068)
-#define SDRC_D29 (SYSTEM_CONTROL_MODULE_BASE + 0x06A)
-#define SDRC_D30 (SYSTEM_CONTROL_MODULE_BASE + 0x06C)
-#define SDRC_D31 (SYSTEM_CONTROL_MODULE_BASE + 0x06E)
-#define SDRC_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x070)
-#define SDRC_DQS0 (SYSTEM_CONTROL_MODULE_BASE + 0x072)
-#define SDRC_CKE0 (SYSTEM_CONTROL_MODULE_BASE + 0x262)
-#define SDRC_CKE1 (SYSTEM_CONTROL_MODULE_BASE + 0x264)
-#define SDRC_DQS1 (SYSTEM_CONTROL_MODULE_BASE + 0x074)
-#define SDRC_DQS2 (SYSTEM_CONTROL_MODULE_BASE + 0x076)
-#define SDRC_DQS3 (SYSTEM_CONTROL_MODULE_BASE + 0x078)
-#define GPMC_A1 (SYSTEM_CONTROL_MODULE_BASE + 0x07A)
-#define GPMC_A2 (SYSTEM_CONTROL_MODULE_BASE + 0x07C)
-#define GPMC_A3 (SYSTEM_CONTROL_MODULE_BASE + 0x07E)
-#define GPMC_A4 (SYSTEM_CONTROL_MODULE_BASE + 0x080)
-#define GPMC_A5 (SYSTEM_CONTROL_MODULE_BASE + 0x082)
-#define GPMC_A6 (SYSTEM_CONTROL_MODULE_BASE + 0x084)
-#define GPMC_A7 (SYSTEM_CONTROL_MODULE_BASE + 0x086)
-#define GPMC_A8 (SYSTEM_CONTROL_MODULE_BASE + 0x088)
-#define GPMC_A9 (SYSTEM_CONTROL_MODULE_BASE + 0x08A)
-#define GPMC_A10 (SYSTEM_CONTROL_MODULE_BASE + 0x08C)
-#define GPMC_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x08E)
-#define GPMC_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x090)
-#define GPMC_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x092)
-#define GPMC_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x094)
-#define GPMC_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x096)
-#define GPMC_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x098)
-#define GPMC_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x09A)
-#define GPMC_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x09C)
-#define GPMC_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x09E)
-#define GPMC_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x0A0)
-#define GPMC_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x0A2)
-#define GPMC_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x0A4)
-#define GPMC_D12 (SYSTEM_CONTROL_MODULE_BASE + 0x0A6)
-#define GPMC_D13 (SYSTEM_CONTROL_MODULE_BASE + 0x0A8)
-#define GPMC_D14 (SYSTEM_CONTROL_MODULE_BASE + 0x0AA)
-#define GPMC_D15 (SYSTEM_CONTROL_MODULE_BASE + 0x0AC)
-#define GPMC_NCS0 (SYSTEM_CONTROL_MODULE_BASE + 0x0AE)
-#define GPMC_NCS1 (SYSTEM_CONTROL_MODULE_BASE + 0x0B0)
-#define GPMC_NCS2 (SYSTEM_CONTROL_MODULE_BASE + 0x0B2)
-#define GPMC_NCS3 (SYSTEM_CONTROL_MODULE_BASE + 0x0B4)
-#define GPMC_NCS4 (SYSTEM_CONTROL_MODULE_BASE + 0x0B6)
-#define GPMC_NCS5 (SYSTEM_CONTROL_MODULE_BASE + 0x0B8)
-#define GPMC_NCS6 (SYSTEM_CONTROL_MODULE_BASE + 0x0BA)
-#define GPMC_NCS7 (SYSTEM_CONTROL_MODULE_BASE + 0x0BC)
-#define GPMC_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x0BE)
-#define GPMC_NADV_ALE (SYSTEM_CONTROL_MODULE_BASE + 0x0C0)
-#define GPMC_NOE (SYSTEM_CONTROL_MODULE_BASE + 0x0C2)
-#define GPMC_NWE (SYSTEM_CONTROL_MODULE_BASE + 0x0C4)
-#define GPMC_NBE0_CLE (SYSTEM_CONTROL_MODULE_BASE + 0x0C6)
-#define GPMC_NBE1 (SYSTEM_CONTROL_MODULE_BASE + 0x0C8)
-#define GPMC_NWP (SYSTEM_CONTROL_MODULE_BASE + 0x0CA)
-#define GPMC_WAIT0 (SYSTEM_CONTROL_MODULE_BASE + 0x0CC)
-#define GPMC_WAIT1 (SYSTEM_CONTROL_MODULE_BASE + 0x0CE)
-#define GPMC_WAIT2 (SYSTEM_CONTROL_MODULE_BASE + 0x0D0)
-#define GPMC_WAIT3 (SYSTEM_CONTROL_MODULE_BASE + 0x0D2)
-#define DSS_PCLK (SYSTEM_CONTROL_MODULE_BASE + 0x0D4)
-#define DSS_HSYNC (SYSTEM_CONTROL_MODULE_BASE + 0x0D6)
-#define DSS_PSYNC (SYSTEM_CONTROL_MODULE_BASE + 0x0D8)
-#define DSS_ACBIAS (SYSTEM_CONTROL_MODULE_BASE + 0x0DA)
-#define DSS_DATA0 (SYSTEM_CONTROL_MODULE_BASE + 0x0DC)
-#define DSS_DATA1 (SYSTEM_CONTROL_MODULE_BASE + 0x0DE)
-#define DSS_DATA2 (SYSTEM_CONTROL_MODULE_BASE + 0x0E0)
-#define DSS_DATA3 (SYSTEM_CONTROL_MODULE_BASE + 0x0E2)
-#define DSS_DATA4 (SYSTEM_CONTROL_MODULE_BASE + 0x0E4)
-#define DSS_DATA5 (SYSTEM_CONTROL_MODULE_BASE + 0x0E6)
-#define DSS_DATA6 (SYSTEM_CONTROL_MODULE_BASE + 0x0E8)
-#define DSS_DATA7 (SYSTEM_CONTROL_MODULE_BASE + 0x0EA)
-#define DSS_DATA8 (SYSTEM_CONTROL_MODULE_BASE + 0x0EC)
-#define DSS_DATA9 (SYSTEM_CONTROL_MODULE_BASE + 0x0EE)
-#define DSS_DATA10 (SYSTEM_CONTROL_MODULE_BASE + 0x0F0)
-#define DSS_DATA11 (SYSTEM_CONTROL_MODULE_BASE + 0x0F2)
-#define DSS_DATA12 (SYSTEM_CONTROL_MODULE_BASE + 0x0F4)
-#define DSS_DATA13 (SYSTEM_CONTROL_MODULE_BASE + 0x0F6)
-#define DSS_DATA14 (SYSTEM_CONTROL_MODULE_BASE + 0x0F8)
-#define DSS_DATA15 (SYSTEM_CONTROL_MODULE_BASE + 0x0FA)
-#define DSS_DATA16 (SYSTEM_CONTROL_MODULE_BASE + 0x0FC)
-#define DSS_DATA17 (SYSTEM_CONTROL_MODULE_BASE + 0x0FE)
-#define DSS_DATA18 (SYSTEM_CONTROL_MODULE_BASE + 0x100)
-#define DSS_DATA19 (SYSTEM_CONTROL_MODULE_BASE + 0x102)
-#define DSS_DATA20 (SYSTEM_CONTROL_MODULE_BASE + 0x104)
-#define DSS_DATA21 (SYSTEM_CONTROL_MODULE_BASE + 0x106)
-#define DSS_DATA22 (SYSTEM_CONTROL_MODULE_BASE + 0x108)
-#define DSS_DATA23 (SYSTEM_CONTROL_MODULE_BASE + 0x10A)
-#define CAM_HS (SYSTEM_CONTROL_MODULE_BASE + 0x10C)
-#define CAM_VS (SYSTEM_CONTROL_MODULE_BASE + 0x10E)
-#define CAM_XCLKA (SYSTEM_CONTROL_MODULE_BASE + 0x110)
-#define CAM_PCLK (SYSTEM_CONTROL_MODULE_BASE + 0x112)
-#define CAM_FLD (SYSTEM_CONTROL_MODULE_BASE + 0x114)
-#define CAM_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x116)
-#define CAM_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x118)
-#define CAM_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x11A)
-#define CAM_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x11C)
-#define CAM_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x11E)
-#define CAM_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x120)
-#define CAM_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x122)
-#define CAM_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x124)
-#define CAM_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x126)
-#define CAM_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x128)
-#define CAM_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x12A)
-#define CAM_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x12C)
-#define CAM_XCLKB (SYSTEM_CONTROL_MODULE_BASE + 0x12E)
-#define CAM_WEN (SYSTEM_CONTROL_MODULE_BASE + 0x130)
-#define CAM_STROBE (SYSTEM_CONTROL_MODULE_BASE + 0x132)
-#define CSI2_DX0 (SYSTEM_CONTROL_MODULE_BASE + 0x134)
-#define CSI2_DY0 (SYSTEM_CONTROL_MODULE_BASE + 0x136)
-#define CSI2_DX1 (SYSTEM_CONTROL_MODULE_BASE + 0x138)
-#define CSI2_DY1 (SYSTEM_CONTROL_MODULE_BASE + 0x13A)
-#define MCBSP2_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x13C)
-#define MCBSP2_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x13E)
-#define MCBSP2_DR (SYSTEM_CONTROL_MODULE_BASE + 0x140)
-#define MCBSP2_DX (SYSTEM_CONTROL_MODULE_BASE + 0x142)
-#define MMC1_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x144)
-#define MMC1_CMD (SYSTEM_CONTROL_MODULE_BASE + 0x146)
-#define MMC1_DAT0 (SYSTEM_CONTROL_MODULE_BASE + 0x148)
-#define MMC1_DAT1 (SYSTEM_CONTROL_MODULE_BASE + 0x14A)
-#define MMC1_DAT2 (SYSTEM_CONTROL_MODULE_BASE + 0x14C)
-#define MMC1_DAT3 (SYSTEM_CONTROL_MODULE_BASE + 0x14E)
-#define MMC1_DAT4 (SYSTEM_CONTROL_MODULE_BASE + 0x150)
-#define MMC1_DAT5 (SYSTEM_CONTROL_MODULE_BASE + 0x152)
-#define MMC1_DAT6 (SYSTEM_CONTROL_MODULE_BASE + 0x154)
-#define MMC1_DAT7 (SYSTEM_CONTROL_MODULE_BASE + 0x156)
-#define MMC2_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x158)
-#define MMC2_CMD (SYSTEM_CONTROL_MODULE_BASE + 0x15A)
-#define MMC2_DAT0 (SYSTEM_CONTROL_MODULE_BASE + 0x15C)
-#define MMC2_DAT1 (SYSTEM_CONTROL_MODULE_BASE + 0x15E)
-#define MMC2_DAT2 (SYSTEM_CONTROL_MODULE_BASE + 0x160)
-#define MMC2_DAT3 (SYSTEM_CONTROL_MODULE_BASE + 0x162)
-#define MMC2_DAT4 (SYSTEM_CONTROL_MODULE_BASE + 0x164)
-#define MMC2_DAT5 (SYSTEM_CONTROL_MODULE_BASE + 0x166)
-#define MMC2_DAT6 (SYSTEM_CONTROL_MODULE_BASE + 0x168)
-#define MMC2_DAT7 (SYSTEM_CONTROL_MODULE_BASE + 0x16A)
-#define MCBSP3_DX (SYSTEM_CONTROL_MODULE_BASE + 0x16C)
-#define MCBSP3_DR (SYSTEM_CONTROL_MODULE_BASE + 0x16E)
-#define MCBSP3_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x170)
-#define MCBSP3_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x172)
-#define UART2_CTS (SYSTEM_CONTROL_MODULE_BASE + 0x174)
-#define UART2_RTS (SYSTEM_CONTROL_MODULE_BASE + 0x176)
-#define UART2_TX (SYSTEM_CONTROL_MODULE_BASE + 0x178)
-#define UART2_RX (SYSTEM_CONTROL_MODULE_BASE + 0x17A)
-#define UART1_TX (SYSTEM_CONTROL_MODULE_BASE + 0x17C)
-#define UART1_RTS (SYSTEM_CONTROL_MODULE_BASE + 0x17E)
-#define UART1_CTS (SYSTEM_CONTROL_MODULE_BASE + 0x180)
-#define UART1_RX (SYSTEM_CONTROL_MODULE_BASE + 0x182)
-#define MCBSP4_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x184)
-#define MCBSP4_DR (SYSTEM_CONTROL_MODULE_BASE + 0x186)
-#define MCBSP4_DX (SYSTEM_CONTROL_MODULE_BASE + 0x188)
-#define MCBSP4_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x18A)
-#define MCBSP1_CLKR (SYSTEM_CONTROL_MODULE_BASE + 0x18C)
-#define MCBSP1_FSR (SYSTEM_CONTROL_MODULE_BASE + 0x18E)
-#define MCBSP1_DX (SYSTEM_CONTROL_MODULE_BASE + 0x190)
-#define MCBSP1_DR (SYSTEM_CONTROL_MODULE_BASE + 0x192)
-#define MCBSP1_CLKS (SYSTEM_CONTROL_MODULE_BASE + 0x194)
-#define MCBSP1_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x196)
-#define MCBSP1_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x198)
-#define UART3_CTS_RCTX (SYSTEM_CONTROL_MODULE_BASE + 0x19A)
-#define UART3_RTS_SD (SYSTEM_CONTROL_MODULE_BASE + 0x19C)
-#define UART3_RX_IRRX (SYSTEM_CONTROL_MODULE_BASE + 0x19E)
-#define UART3_TX_IRTX (SYSTEM_CONTROL_MODULE_BASE + 0x1A0)
-#define HSUSB0_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x1A2)
-#define HSUSB0_STP (SYSTEM_CONTROL_MODULE_BASE + 0x1A4)
-#define HSUSB0_DIR (SYSTEM_CONTROL_MODULE_BASE + 0x1A6)
-#define HSUSB0_NXT (SYSTEM_CONTROL_MODULE_BASE + 0x1A8)
-#define HSUSB0_DATA0 (SYSTEM_CONTROL_MODULE_BASE + 0x1AA)
-#define HSUSB0_DATA1 (SYSTEM_CONTROL_MODULE_BASE + 0x1AC)
-#define HSUSB0_DATA2 (SYSTEM_CONTROL_MODULE_BASE + 0x1AE)
-#define HSUSB0_DATA3 (SYSTEM_CONTROL_MODULE_BASE + 0x1B0)
-#define HSUSB0_DATA4 (SYSTEM_CONTROL_MODULE_BASE + 0x1B2)
-#define HSUSB0_DATA5 (SYSTEM_CONTROL_MODULE_BASE + 0x1B4)
-#define HSUSB0_DATA6 (SYSTEM_CONTROL_MODULE_BASE + 0x1B6)
-#define HSUSB0_DATA7 (SYSTEM_CONTROL_MODULE_BASE + 0x1B8)
-#define I2C1_SCL (SYSTEM_CONTROL_MODULE_BASE + 0x1BA)
-#define I2C1_SDA (SYSTEM_CONTROL_MODULE_BASE + 0x1BC)
-#define I2C2_SCL (SYSTEM_CONTROL_MODULE_BASE + 0x1BE)
-#define I2C2_SDA (SYSTEM_CONTROL_MODULE_BASE + 0x1C0)
-#define I2C3_SCL (SYSTEM_CONTROL_MODULE_BASE + 0x1C2)
-#define I2C3_SDA (SYSTEM_CONTROL_MODULE_BASE + 0x1C4)
-#define HDQ_SIO (SYSTEM_CONTROL_MODULE_BASE + 0x1C6)
-#define MCSPI1_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x1C8)
-#define MCSPI1_SIMO (SYSTEM_CONTROL_MODULE_BASE + 0x1CA)
-#define MCSPI1_SOMI (SYSTEM_CONTROL_MODULE_BASE + 0x1CC)
-#define MCSPI1_CS0 (SYSTEM_CONTROL_MODULE_BASE + 0x1CE)
-#define MCSPI1_CS1 (SYSTEM_CONTROL_MODULE_BASE + 0x1D0)
-#define MCSPI1_CS2 (SYSTEM_CONTROL_MODULE_BASE + 0x1D2)
-#define MCSPI1_CS3 (SYSTEM_CONTROL_MODULE_BASE + 0x1D4)
-#define MCSPI2_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x1D6)
-#define MCSPI2_SIMO (SYSTEM_CONTROL_MODULE_BASE + 0x1D8)
-#define MCSPI2_SOMI (SYSTEM_CONTROL_MODULE_BASE + 0x1DA)
-#define MCSPI2_CS0 (SYSTEM_CONTROL_MODULE_BASE + 0x1DC)
-#define MCSPI2_CS1 (SYSTEM_CONTROL_MODULE_BASE + 0x1DE)
-#define SYS_NIRQ (SYSTEM_CONTROL_MODULE_BASE + 0x1E0)
-#define SYS_CLKOUT2 (SYSTEM_CONTROL_MODULE_BASE + 0x1E2)
-#define ETK_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x5D8)
-#define ETK_CTL (SYSTEM_CONTROL_MODULE_BASE + 0x5DA)
-#define ETK_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x5DC)
-#define ETK_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x5DE)
-#define ETK_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x5E0)
-#define ETK_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x5E2)
-#define ETK_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x5E4)
-#define ETK_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x5E6)
-#define ETK_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x5E8)
-#define ETK_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x5EA)
-#define ETK_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x5EC)
-#define ETK_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x5EE)
-#define ETK_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x5F0)
-#define ETK_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x5F2)
-#define ETK_D12 (SYSTEM_CONTROL_MODULE_BASE + 0x5F4)
-#define ETK_D13 (SYSTEM_CONTROL_MODULE_BASE + 0x5F6)
-#define ETK_D14 (SYSTEM_CONTROL_MODULE_BASE + 0x5F8)
-#define ETK_D15 (SYSTEM_CONTROL_MODULE_BASE + 0x5FA)
-#define SYS_BOOT0 (SYSTEM_CONTROL_MODULE_BASE + 0xA0A)
-#define SYS_BOOT1 (SYSTEM_CONTROL_MODULE_BASE + 0xA0C)
-#define SYS_BOOT3 (SYSTEM_CONTROL_MODULE_BASE + 0xA10)
-#define SYS_BOOT4 (SYSTEM_CONTROL_MODULE_BASE + 0xA12)
-#define SYS_BOOT5 (SYSTEM_CONTROL_MODULE_BASE + 0xA14)
-#define SYS_BOOT6 (SYSTEM_CONTROL_MODULE_BASE + 0xA16)
-
-//Mux modes
-#define MUXMODE0 (0x0UL)
-#define MUXMODE1 (0x1UL)
-#define MUXMODE2 (0x2UL)
-#define MUXMODE3 (0x3UL)
-#define MUXMODE4 (0x4UL)
-#define MUXMODE5 (0x5UL)
-#define MUXMODE6 (0x6UL)
-#define MUXMODE7 (0x7UL)
-
-//Pad configuration register.
-#define PAD_CONFIG_MASK (0xFFFFUL)
-#define MUXMODE_OFFSET 0
-#define MUXMODE_MASK (0x7UL << MUXMODE_OFFSET)
-#define PULL_CONFIG_OFFSET 3
-#define PULL_CONFIG_MASK (0x3UL << PULL_CONFIG_OFFSET)
-#define INPUTENABLE_OFFSET 8
-#define INPUTENABLE_MASK (0x1UL << INPUTENABLE_OFFSET)
-#define OFFMODE_VALUE_OFFSET 9
-#define OFFMODE_VALUE_MASK (0x1FUL << OFFMODE_VALUE_OFFSET)
-#define WAKEUP_OFFSET 14
-#define WAKEUP_MASK (0x2UL << WAKEUP_OFFSET)
-
-#define PULL_DOWN_SELECTED ((0x0UL << 1) | BIT0)
-#define PULL_UP_SELECTED (BIT1 | BIT0)
-#define PULL_DISABLED (0x0UL << 0)
-
-#define OUTPUT (0x0UL) //Pin is configured in output only mode.
-#define INPUT (0x1UL) //Pin is configured in bi-directional mode.
-
-typedef struct {
- UINTN Pin;
- UINTN MuxMode;
- UINTN PullConfig;
- UINTN InputEnable;
-} PAD_CONFIGURATION;
-
-#endif //__OMAP3530_PAD_CONFIGURATION_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530_PAD_CONFIGURATION_H__
+#define __OMAP3530_PAD_CONFIGURATION_H__
+
+#define SYSTEM_CONTROL_MODULE_BASE 0x48002000
+
+//Pin definition
+#define SDRC_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x030)
+#define SDRC_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x032)
+#define SDRC_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x034)
+#define SDRC_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x036)
+#define SDRC_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x038)
+#define SDRC_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x03A)
+#define SDRC_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x03C)
+#define SDRC_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x03E)
+#define SDRC_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x040)
+#define SDRC_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x042)
+#define SDRC_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x044)
+#define SDRC_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x046)
+#define SDRC_D12 (SYSTEM_CONTROL_MODULE_BASE + 0x048)
+#define SDRC_D13 (SYSTEM_CONTROL_MODULE_BASE + 0x04A)
+#define SDRC_D14 (SYSTEM_CONTROL_MODULE_BASE + 0x04C)
+#define SDRC_D15 (SYSTEM_CONTROL_MODULE_BASE + 0x04E)
+#define SDRC_D16 (SYSTEM_CONTROL_MODULE_BASE + 0x050)
+#define SDRC_D17 (SYSTEM_CONTROL_MODULE_BASE + 0x052)
+#define SDRC_D18 (SYSTEM_CONTROL_MODULE_BASE + 0x054)
+#define SDRC_D19 (SYSTEM_CONTROL_MODULE_BASE + 0x056)
+#define SDRC_D20 (SYSTEM_CONTROL_MODULE_BASE + 0x058)
+#define SDRC_D21 (SYSTEM_CONTROL_MODULE_BASE + 0x05A)
+#define SDRC_D22 (SYSTEM_CONTROL_MODULE_BASE + 0x05C)
+#define SDRC_D23 (SYSTEM_CONTROL_MODULE_BASE + 0x05E)
+#define SDRC_D24 (SYSTEM_CONTROL_MODULE_BASE + 0x060)
+#define SDRC_D25 (SYSTEM_CONTROL_MODULE_BASE + 0x062)
+#define SDRC_D26 (SYSTEM_CONTROL_MODULE_BASE + 0x064)
+#define SDRC_D27 (SYSTEM_CONTROL_MODULE_BASE + 0x066)
+#define SDRC_D28 (SYSTEM_CONTROL_MODULE_BASE + 0x068)
+#define SDRC_D29 (SYSTEM_CONTROL_MODULE_BASE + 0x06A)
+#define SDRC_D30 (SYSTEM_CONTROL_MODULE_BASE + 0x06C)
+#define SDRC_D31 (SYSTEM_CONTROL_MODULE_BASE + 0x06E)
+#define SDRC_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x070)
+#define SDRC_DQS0 (SYSTEM_CONTROL_MODULE_BASE + 0x072)
+#define SDRC_CKE0 (SYSTEM_CONTROL_MODULE_BASE + 0x262)
+#define SDRC_CKE1 (SYSTEM_CONTROL_MODULE_BASE + 0x264)
+#define SDRC_DQS1 (SYSTEM_CONTROL_MODULE_BASE + 0x074)
+#define SDRC_DQS2 (SYSTEM_CONTROL_MODULE_BASE + 0x076)
+#define SDRC_DQS3 (SYSTEM_CONTROL_MODULE_BASE + 0x078)
+#define GPMC_A1 (SYSTEM_CONTROL_MODULE_BASE + 0x07A)
+#define GPMC_A2 (SYSTEM_CONTROL_MODULE_BASE + 0x07C)
+#define GPMC_A3 (SYSTEM_CONTROL_MODULE_BASE + 0x07E)
+#define GPMC_A4 (SYSTEM_CONTROL_MODULE_BASE + 0x080)
+#define GPMC_A5 (SYSTEM_CONTROL_MODULE_BASE + 0x082)
+#define GPMC_A6 (SYSTEM_CONTROL_MODULE_BASE + 0x084)
+#define GPMC_A7 (SYSTEM_CONTROL_MODULE_BASE + 0x086)
+#define GPMC_A8 (SYSTEM_CONTROL_MODULE_BASE + 0x088)
+#define GPMC_A9 (SYSTEM_CONTROL_MODULE_BASE + 0x08A)
+#define GPMC_A10 (SYSTEM_CONTROL_MODULE_BASE + 0x08C)
+#define GPMC_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x08E)
+#define GPMC_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x090)
+#define GPMC_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x092)
+#define GPMC_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x094)
+#define GPMC_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x096)
+#define GPMC_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x098)
+#define GPMC_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x09A)
+#define GPMC_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x09C)
+#define GPMC_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x09E)
+#define GPMC_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x0A0)
+#define GPMC_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x0A2)
+#define GPMC_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x0A4)
+#define GPMC_D12 (SYSTEM_CONTROL_MODULE_BASE + 0x0A6)
+#define GPMC_D13 (SYSTEM_CONTROL_MODULE_BASE + 0x0A8)
+#define GPMC_D14 (SYSTEM_CONTROL_MODULE_BASE + 0x0AA)
+#define GPMC_D15 (SYSTEM_CONTROL_MODULE_BASE + 0x0AC)
+#define GPMC_NCS0 (SYSTEM_CONTROL_MODULE_BASE + 0x0AE)
+#define GPMC_NCS1 (SYSTEM_CONTROL_MODULE_BASE + 0x0B0)
+#define GPMC_NCS2 (SYSTEM_CONTROL_MODULE_BASE + 0x0B2)
+#define GPMC_NCS3 (SYSTEM_CONTROL_MODULE_BASE + 0x0B4)
+#define GPMC_NCS4 (SYSTEM_CONTROL_MODULE_BASE + 0x0B6)
+#define GPMC_NCS5 (SYSTEM_CONTROL_MODULE_BASE + 0x0B8)
+#define GPMC_NCS6 (SYSTEM_CONTROL_MODULE_BASE + 0x0BA)
+#define GPMC_NCS7 (SYSTEM_CONTROL_MODULE_BASE + 0x0BC)
+#define GPMC_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x0BE)
+#define GPMC_NADV_ALE (SYSTEM_CONTROL_MODULE_BASE + 0x0C0)
+#define GPMC_NOE (SYSTEM_CONTROL_MODULE_BASE + 0x0C2)
+#define GPMC_NWE (SYSTEM_CONTROL_MODULE_BASE + 0x0C4)
+#define GPMC_NBE0_CLE (SYSTEM_CONTROL_MODULE_BASE + 0x0C6)
+#define GPMC_NBE1 (SYSTEM_CONTROL_MODULE_BASE + 0x0C8)
+#define GPMC_NWP (SYSTEM_CONTROL_MODULE_BASE + 0x0CA)
+#define GPMC_WAIT0 (SYSTEM_CONTROL_MODULE_BASE + 0x0CC)
+#define GPMC_WAIT1 (SYSTEM_CONTROL_MODULE_BASE + 0x0CE)
+#define GPMC_WAIT2 (SYSTEM_CONTROL_MODULE_BASE + 0x0D0)
+#define GPMC_WAIT3 (SYSTEM_CONTROL_MODULE_BASE + 0x0D2)
+#define DSS_PCLK (SYSTEM_CONTROL_MODULE_BASE + 0x0D4)
+#define DSS_HSYNC (SYSTEM_CONTROL_MODULE_BASE + 0x0D6)
+#define DSS_PSYNC (SYSTEM_CONTROL_MODULE_BASE + 0x0D8)
+#define DSS_ACBIAS (SYSTEM_CONTROL_MODULE_BASE + 0x0DA)
+#define DSS_DATA0 (SYSTEM_CONTROL_MODULE_BASE + 0x0DC)
+#define DSS_DATA1 (SYSTEM_CONTROL_MODULE_BASE + 0x0DE)
+#define DSS_DATA2 (SYSTEM_CONTROL_MODULE_BASE + 0x0E0)
+#define DSS_DATA3 (SYSTEM_CONTROL_MODULE_BASE + 0x0E2)
+#define DSS_DATA4 (SYSTEM_CONTROL_MODULE_BASE + 0x0E4)
+#define DSS_DATA5 (SYSTEM_CONTROL_MODULE_BASE + 0x0E6)
+#define DSS_DATA6 (SYSTEM_CONTROL_MODULE_BASE + 0x0E8)
+#define DSS_DATA7 (SYSTEM_CONTROL_MODULE_BASE + 0x0EA)
+#define DSS_DATA8 (SYSTEM_CONTROL_MODULE_BASE + 0x0EC)
+#define DSS_DATA9 (SYSTEM_CONTROL_MODULE_BASE + 0x0EE)
+#define DSS_DATA10 (SYSTEM_CONTROL_MODULE_BASE + 0x0F0)
+#define DSS_DATA11 (SYSTEM_CONTROL_MODULE_BASE + 0x0F2)
+#define DSS_DATA12 (SYSTEM_CONTROL_MODULE_BASE + 0x0F4)
+#define DSS_DATA13 (SYSTEM_CONTROL_MODULE_BASE + 0x0F6)
+#define DSS_DATA14 (SYSTEM_CONTROL_MODULE_BASE + 0x0F8)
+#define DSS_DATA15 (SYSTEM_CONTROL_MODULE_BASE + 0x0FA)
+#define DSS_DATA16 (SYSTEM_CONTROL_MODULE_BASE + 0x0FC)
+#define DSS_DATA17 (SYSTEM_CONTROL_MODULE_BASE + 0x0FE)
+#define DSS_DATA18 (SYSTEM_CONTROL_MODULE_BASE + 0x100)
+#define DSS_DATA19 (SYSTEM_CONTROL_MODULE_BASE + 0x102)
+#define DSS_DATA20 (SYSTEM_CONTROL_MODULE_BASE + 0x104)
+#define DSS_DATA21 (SYSTEM_CONTROL_MODULE_BASE + 0x106)
+#define DSS_DATA22 (SYSTEM_CONTROL_MODULE_BASE + 0x108)
+#define DSS_DATA23 (SYSTEM_CONTROL_MODULE_BASE + 0x10A)
+#define CAM_HS (SYSTEM_CONTROL_MODULE_BASE + 0x10C)
+#define CAM_VS (SYSTEM_CONTROL_MODULE_BASE + 0x10E)
+#define CAM_XCLKA (SYSTEM_CONTROL_MODULE_BASE + 0x110)
+#define CAM_PCLK (SYSTEM_CONTROL_MODULE_BASE + 0x112)
+#define CAM_FLD (SYSTEM_CONTROL_MODULE_BASE + 0x114)
+#define CAM_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x116)
+#define CAM_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x118)
+#define CAM_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x11A)
+#define CAM_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x11C)
+#define CAM_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x11E)
+#define CAM_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x120)
+#define CAM_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x122)
+#define CAM_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x124)
+#define CAM_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x126)
+#define CAM_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x128)
+#define CAM_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x12A)
+#define CAM_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x12C)
+#define CAM_XCLKB (SYSTEM_CONTROL_MODULE_BASE + 0x12E)
+#define CAM_WEN (SYSTEM_CONTROL_MODULE_BASE + 0x130)
+#define CAM_STROBE (SYSTEM_CONTROL_MODULE_BASE + 0x132)
+#define CSI2_DX0 (SYSTEM_CONTROL_MODULE_BASE + 0x134)
+#define CSI2_DY0 (SYSTEM_CONTROL_MODULE_BASE + 0x136)
+#define CSI2_DX1 (SYSTEM_CONTROL_MODULE_BASE + 0x138)
+#define CSI2_DY1 (SYSTEM_CONTROL_MODULE_BASE + 0x13A)
+#define MCBSP2_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x13C)
+#define MCBSP2_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x13E)
+#define MCBSP2_DR (SYSTEM_CONTROL_MODULE_BASE + 0x140)
+#define MCBSP2_DX (SYSTEM_CONTROL_MODULE_BASE + 0x142)
+#define MMC1_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x144)
+#define MMC1_CMD (SYSTEM_CONTROL_MODULE_BASE + 0x146)
+#define MMC1_DAT0 (SYSTEM_CONTROL_MODULE_BASE + 0x148)
+#define MMC1_DAT1 (SYSTEM_CONTROL_MODULE_BASE + 0x14A)
+#define MMC1_DAT2 (SYSTEM_CONTROL_MODULE_BASE + 0x14C)
+#define MMC1_DAT3 (SYSTEM_CONTROL_MODULE_BASE + 0x14E)
+#define MMC1_DAT4 (SYSTEM_CONTROL_MODULE_BASE + 0x150)
+#define MMC1_DAT5 (SYSTEM_CONTROL_MODULE_BASE + 0x152)
+#define MMC1_DAT6 (SYSTEM_CONTROL_MODULE_BASE + 0x154)
+#define MMC1_DAT7 (SYSTEM_CONTROL_MODULE_BASE + 0x156)
+#define MMC2_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x158)
+#define MMC2_CMD (SYSTEM_CONTROL_MODULE_BASE + 0x15A)
+#define MMC2_DAT0 (SYSTEM_CONTROL_MODULE_BASE + 0x15C)
+#define MMC2_DAT1 (SYSTEM_CONTROL_MODULE_BASE + 0x15E)
+#define MMC2_DAT2 (SYSTEM_CONTROL_MODULE_BASE + 0x160)
+#define MMC2_DAT3 (SYSTEM_CONTROL_MODULE_BASE + 0x162)
+#define MMC2_DAT4 (SYSTEM_CONTROL_MODULE_BASE + 0x164)
+#define MMC2_DAT5 (SYSTEM_CONTROL_MODULE_BASE + 0x166)
+#define MMC2_DAT6 (SYSTEM_CONTROL_MODULE_BASE + 0x168)
+#define MMC2_DAT7 (SYSTEM_CONTROL_MODULE_BASE + 0x16A)
+#define MCBSP3_DX (SYSTEM_CONTROL_MODULE_BASE + 0x16C)
+#define MCBSP3_DR (SYSTEM_CONTROL_MODULE_BASE + 0x16E)
+#define MCBSP3_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x170)
+#define MCBSP3_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x172)
+#define UART2_CTS (SYSTEM_CONTROL_MODULE_BASE + 0x174)
+#define UART2_RTS (SYSTEM_CONTROL_MODULE_BASE + 0x176)
+#define UART2_TX (SYSTEM_CONTROL_MODULE_BASE + 0x178)
+#define UART2_RX (SYSTEM_CONTROL_MODULE_BASE + 0x17A)
+#define UART1_TX (SYSTEM_CONTROL_MODULE_BASE + 0x17C)
+#define UART1_RTS (SYSTEM_CONTROL_MODULE_BASE + 0x17E)
+#define UART1_CTS (SYSTEM_CONTROL_MODULE_BASE + 0x180)
+#define UART1_RX (SYSTEM_CONTROL_MODULE_BASE + 0x182)
+#define MCBSP4_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x184)
+#define MCBSP4_DR (SYSTEM_CONTROL_MODULE_BASE + 0x186)
+#define MCBSP4_DX (SYSTEM_CONTROL_MODULE_BASE + 0x188)
+#define MCBSP4_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x18A)
+#define MCBSP1_CLKR (SYSTEM_CONTROL_MODULE_BASE + 0x18C)
+#define MCBSP1_FSR (SYSTEM_CONTROL_MODULE_BASE + 0x18E)
+#define MCBSP1_DX (SYSTEM_CONTROL_MODULE_BASE + 0x190)
+#define MCBSP1_DR (SYSTEM_CONTROL_MODULE_BASE + 0x192)
+#define MCBSP1_CLKS (SYSTEM_CONTROL_MODULE_BASE + 0x194)
+#define MCBSP1_FSX (SYSTEM_CONTROL_MODULE_BASE + 0x196)
+#define MCBSP1_CLKX (SYSTEM_CONTROL_MODULE_BASE + 0x198)
+#define UART3_CTS_RCTX (SYSTEM_CONTROL_MODULE_BASE + 0x19A)
+#define UART3_RTS_SD (SYSTEM_CONTROL_MODULE_BASE + 0x19C)
+#define UART3_RX_IRRX (SYSTEM_CONTROL_MODULE_BASE + 0x19E)
+#define UART3_TX_IRTX (SYSTEM_CONTROL_MODULE_BASE + 0x1A0)
+#define HSUSB0_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x1A2)
+#define HSUSB0_STP (SYSTEM_CONTROL_MODULE_BASE + 0x1A4)
+#define HSUSB0_DIR (SYSTEM_CONTROL_MODULE_BASE + 0x1A6)
+#define HSUSB0_NXT (SYSTEM_CONTROL_MODULE_BASE + 0x1A8)
+#define HSUSB0_DATA0 (SYSTEM_CONTROL_MODULE_BASE + 0x1AA)
+#define HSUSB0_DATA1 (SYSTEM_CONTROL_MODULE_BASE + 0x1AC)
+#define HSUSB0_DATA2 (SYSTEM_CONTROL_MODULE_BASE + 0x1AE)
+#define HSUSB0_DATA3 (SYSTEM_CONTROL_MODULE_BASE + 0x1B0)
+#define HSUSB0_DATA4 (SYSTEM_CONTROL_MODULE_BASE + 0x1B2)
+#define HSUSB0_DATA5 (SYSTEM_CONTROL_MODULE_BASE + 0x1B4)
+#define HSUSB0_DATA6 (SYSTEM_CONTROL_MODULE_BASE + 0x1B6)
+#define HSUSB0_DATA7 (SYSTEM_CONTROL_MODULE_BASE + 0x1B8)
+#define I2C1_SCL (SYSTEM_CONTROL_MODULE_BASE + 0x1BA)
+#define I2C1_SDA (SYSTEM_CONTROL_MODULE_BASE + 0x1BC)
+#define I2C2_SCL (SYSTEM_CONTROL_MODULE_BASE + 0x1BE)
+#define I2C2_SDA (SYSTEM_CONTROL_MODULE_BASE + 0x1C0)
+#define I2C3_SCL (SYSTEM_CONTROL_MODULE_BASE + 0x1C2)
+#define I2C3_SDA (SYSTEM_CONTROL_MODULE_BASE + 0x1C4)
+#define HDQ_SIO (SYSTEM_CONTROL_MODULE_BASE + 0x1C6)
+#define MCSPI1_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x1C8)
+#define MCSPI1_SIMO (SYSTEM_CONTROL_MODULE_BASE + 0x1CA)
+#define MCSPI1_SOMI (SYSTEM_CONTROL_MODULE_BASE + 0x1CC)
+#define MCSPI1_CS0 (SYSTEM_CONTROL_MODULE_BASE + 0x1CE)
+#define MCSPI1_CS1 (SYSTEM_CONTROL_MODULE_BASE + 0x1D0)
+#define MCSPI1_CS2 (SYSTEM_CONTROL_MODULE_BASE + 0x1D2)
+#define MCSPI1_CS3 (SYSTEM_CONTROL_MODULE_BASE + 0x1D4)
+#define MCSPI2_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x1D6)
+#define MCSPI2_SIMO (SYSTEM_CONTROL_MODULE_BASE + 0x1D8)
+#define MCSPI2_SOMI (SYSTEM_CONTROL_MODULE_BASE + 0x1DA)
+#define MCSPI2_CS0 (SYSTEM_CONTROL_MODULE_BASE + 0x1DC)
+#define MCSPI2_CS1 (SYSTEM_CONTROL_MODULE_BASE + 0x1DE)
+#define SYS_NIRQ (SYSTEM_CONTROL_MODULE_BASE + 0x1E0)
+#define SYS_CLKOUT2 (SYSTEM_CONTROL_MODULE_BASE + 0x1E2)
+#define ETK_CLK (SYSTEM_CONTROL_MODULE_BASE + 0x5D8)
+#define ETK_CTL (SYSTEM_CONTROL_MODULE_BASE + 0x5DA)
+#define ETK_D0 (SYSTEM_CONTROL_MODULE_BASE + 0x5DC)
+#define ETK_D1 (SYSTEM_CONTROL_MODULE_BASE + 0x5DE)
+#define ETK_D2 (SYSTEM_CONTROL_MODULE_BASE + 0x5E0)
+#define ETK_D3 (SYSTEM_CONTROL_MODULE_BASE + 0x5E2)
+#define ETK_D4 (SYSTEM_CONTROL_MODULE_BASE + 0x5E4)
+#define ETK_D5 (SYSTEM_CONTROL_MODULE_BASE + 0x5E6)
+#define ETK_D6 (SYSTEM_CONTROL_MODULE_BASE + 0x5E8)
+#define ETK_D7 (SYSTEM_CONTROL_MODULE_BASE + 0x5EA)
+#define ETK_D8 (SYSTEM_CONTROL_MODULE_BASE + 0x5EC)
+#define ETK_D9 (SYSTEM_CONTROL_MODULE_BASE + 0x5EE)
+#define ETK_D10 (SYSTEM_CONTROL_MODULE_BASE + 0x5F0)
+#define ETK_D11 (SYSTEM_CONTROL_MODULE_BASE + 0x5F2)
+#define ETK_D12 (SYSTEM_CONTROL_MODULE_BASE + 0x5F4)
+#define ETK_D13 (SYSTEM_CONTROL_MODULE_BASE + 0x5F6)
+#define ETK_D14 (SYSTEM_CONTROL_MODULE_BASE + 0x5F8)
+#define ETK_D15 (SYSTEM_CONTROL_MODULE_BASE + 0x5FA)
+#define SYS_BOOT0 (SYSTEM_CONTROL_MODULE_BASE + 0xA0A)
+#define SYS_BOOT1 (SYSTEM_CONTROL_MODULE_BASE + 0xA0C)
+#define SYS_BOOT3 (SYSTEM_CONTROL_MODULE_BASE + 0xA10)
+#define SYS_BOOT4 (SYSTEM_CONTROL_MODULE_BASE + 0xA12)
+#define SYS_BOOT5 (SYSTEM_CONTROL_MODULE_BASE + 0xA14)
+#define SYS_BOOT6 (SYSTEM_CONTROL_MODULE_BASE + 0xA16)
+
+//Mux modes
+#define MUXMODE0 (0x0UL)
+#define MUXMODE1 (0x1UL)
+#define MUXMODE2 (0x2UL)
+#define MUXMODE3 (0x3UL)
+#define MUXMODE4 (0x4UL)
+#define MUXMODE5 (0x5UL)
+#define MUXMODE6 (0x6UL)
+#define MUXMODE7 (0x7UL)
+
+//Pad configuration register.
+#define PAD_CONFIG_MASK (0xFFFFUL)
+#define MUXMODE_OFFSET 0
+#define MUXMODE_MASK (0x7UL << MUXMODE_OFFSET)
+#define PULL_CONFIG_OFFSET 3
+#define PULL_CONFIG_MASK (0x3UL << PULL_CONFIG_OFFSET)
+#define INPUTENABLE_OFFSET 8
+#define INPUTENABLE_MASK (0x1UL << INPUTENABLE_OFFSET)
+#define OFFMODE_VALUE_OFFSET 9
+#define OFFMODE_VALUE_MASK (0x1FUL << OFFMODE_VALUE_OFFSET)
+#define WAKEUP_OFFSET 14
+#define WAKEUP_MASK (0x2UL << WAKEUP_OFFSET)
+
+#define PULL_DOWN_SELECTED ((0x0UL << 1) | BIT0)
+#define PULL_UP_SELECTED (BIT1 | BIT0)
+#define PULL_DISABLED (0x0UL << 0)
+
+#define OUTPUT (0x0UL) //Pin is configured in output only mode.
+#define INPUT (0x1UL) //Pin is configured in bi-directional mode.
+
+typedef struct {
+ UINTN Pin;
+ UINTN MuxMode;
+ UINTN PullConfig;
+ UINTN InputEnable;
+} PAD_CONFIGURATION;
+
+#endif //__OMAP3530_PAD_CONFIGURATION_H__
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Prcm.h b/Omap35xxPkg/Include/Omap3530/Omap3530Prcm.h
index cd639e306..3a297d0a9 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Prcm.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Prcm.h
@@ -1,165 +1,165 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530PRCM_H__
-#define __OMAP3530PRCM_H__
-
-#define CM_FCLKEN1_CORE (0x48004A00)
-#define CM_FCLKEN3_CORE (0x48004A08)
-#define CM_ICLKEN1_CORE (0x48004A10)
-#define CM_ICLKEN3_CORE (0x48004A18)
-#define CM_CLKEN2_PLL (0x48004D04)
-#define CM_CLKSEL4_PLL (0x48004D4C)
-#define CM_CLKSEL5_PLL (0x48004D50)
-#define CM_FCLKEN_USBHOST (0x48005400)
-#define CM_ICLKEN_USBHOST (0x48005410)
-#define CM_CLKSTST_USBHOST (0x4800544c)
-
-//Wakeup clock defintion
-#define CM_FCLKEN_WKUP (0x48004C00)
-#define CM_ICLKEN_WKUP (0x48004C10)
-
-//Peripheral clock definition
-#define CM_FCLKEN_PER (0x48005000)
-#define CM_ICLKEN_PER (0x48005010)
-#define CM_CLKSEL_PER (0x48005040)
-
-//Reset management definition
-#define PRM_RSTCTRL (0x48307250)
-#define PRM_RSTST (0x48307258)
-
-//CORE clock
-#define CM_FCLKEN1_CORE_EN_I2C1_MASK BIT15
-#define CM_FCLKEN1_CORE_EN_I2C1_DISABLE (0UL << 15)
-#define CM_FCLKEN1_CORE_EN_I2C1_ENABLE BIT15
-
-#define CM_ICLKEN1_CORE_EN_I2C1_MASK BIT15
-#define CM_ICLKEN1_CORE_EN_I2C1_DISABLE (0UL << 15)
-#define CM_ICLKEN1_CORE_EN_I2C1_ENABLE BIT15
-
-#define CM_FCLKEN1_CORE_EN_MMC1_MASK BIT24
-#define CM_FCLKEN1_CORE_EN_MMC1_DISABLE (0UL << 24)
-#define CM_FCLKEN1_CORE_EN_MMC1_ENABLE BIT24
-
-#define CM_FCLKEN3_CORE_EN_USBTLL_MASK BIT2
-#define CM_FCLKEN3_CORE_EN_USBTLL_DISABLE (0UL << 2)
-#define CM_FCLKEN3_CORE_EN_USBTLL_ENABLE BIT2
-
-#define CM_ICLKEN1_CORE_EN_MMC1_MASK BIT24
-#define CM_ICLKEN1_CORE_EN_MMC1_DISABLE (0UL << 24)
-#define CM_ICLKEN1_CORE_EN_MMC1_ENABLE BIT24
-
-#define CM_ICLKEN3_CORE_EN_USBTLL_MASK BIT2
-#define CM_ICLKEN3_CORE_EN_USBTLL_DISABLE (0UL << 2)
-#define CM_ICLKEN3_CORE_EN_USBTLL_ENABLE BIT2
-
-#define CM_CLKEN_FREQSEL_075_100 (0x03UL << 4)
-#define CM_CLKEN_ENABLE (7UL << 0)
-
-#define CM_CLKSEL_PLL_MULT(x) (((x) & 0x07FF) << 8)
-#define CM_CLKSEL_PLL_DIV(x) ((((x) - 1) & 0x7F) << 0)
-
-#define CM_CLKSEL_DIV_120M(x) (((x) & 0x1F) << 0)
-
-#define CM_FCLKEN_USBHOST_EN_USBHOST2_MASK BIT1
-#define CM_FCLKEN_USBHOST_EN_USBHOST2_DISABLE (0UL << 1)
-#define CM_FCLKEN_USBHOST_EN_USBHOST2_ENABLE BIT1
-
-#define CM_FCLKEN_USBHOST_EN_USBHOST1_MASK BIT0
-#define CM_FCLKEN_USBHOST_EN_USBHOST1_DISABLE (0UL << 0)
-#define CM_FCLKEN_USBHOST_EN_USBHOST1_ENABLE BIT0
-
-#define CM_ICLKEN_USBHOST_EN_USBHOST_MASK BIT0
-#define CM_ICLKEN_USBHOST_EN_USBHOST_DISABLE (0UL << 0)
-#define CM_ICLKEN_USBHOST_EN_USBHOST_ENABLE BIT0
-
-//Wakeup functional clock
-#define CM_FCLKEN_WKUP_EN_GPIO1_DISABLE (0UL << 3)
-#define CM_FCLKEN_WKUP_EN_GPIO1_ENABLE BIT3
-
-#define CM_FCLKEN_WKUP_EN_WDT2_DISABLE (0UL << 5)
-#define CM_FCLKEN_WKUP_EN_WDT2_ENABLE BIT5
-
-//Wakeup interface clock
-#define CM_ICLKEN_WKUP_EN_GPIO1_DISABLE (0UL << 3)
-#define CM_ICLKEN_WKUP_EN_GPIO1_ENABLE BIT3
-
-#define CM_ICLKEN_WKUP_EN_WDT2_DISABLE (0UL << 5)
-#define CM_ICLKEN_WKUP_EN_WDT2_ENABLE BIT5
-
-//Peripheral functional clock
-#define CM_FCLKEN_PER_EN_GPT3_DISABLE (0UL << 4)
-#define CM_FCLKEN_PER_EN_GPT3_ENABLE BIT4
-
-#define CM_FCLKEN_PER_EN_GPT4_DISABLE (0UL << 5)
-#define CM_FCLKEN_PER_EN_GPT4_ENABLE BIT5
-
-#define CM_FCLKEN_PER_EN_UART3_DISABLE (0UL << 11)
-#define CM_FCLKEN_PER_EN_UART3_ENABLE BIT11
-
-#define CM_FCLKEN_PER_EN_GPIO2_DISABLE (0UL << 13)
-#define CM_FCLKEN_PER_EN_GPIO2_ENABLE BIT13
-
-#define CM_FCLKEN_PER_EN_GPIO3_DISABLE (0UL << 14)
-#define CM_FCLKEN_PER_EN_GPIO3_ENABLE BIT14
-
-#define CM_FCLKEN_PER_EN_GPIO4_DISABLE (0UL << 15)
-#define CM_FCLKEN_PER_EN_GPIO4_ENABLE BIT15
-
-#define CM_FCLKEN_PER_EN_GPIO5_DISABLE (0UL << 16)
-#define CM_FCLKEN_PER_EN_GPIO5_ENABLE BIT16
-
-#define CM_FCLKEN_PER_EN_GPIO6_DISABLE (0UL << 17)
-#define CM_FCLKEN_PER_EN_GPIO6_ENABLE BIT17
-
-//Peripheral interface clock
-#define CM_ICLKEN_PER_EN_GPT3_DISABLE (0UL << 4)
-#define CM_ICLKEN_PER_EN_GPT3_ENABLE BIT4
-
-#define CM_ICLKEN_PER_EN_GPT4_DISABLE (0UL << 5)
-#define CM_ICLKEN_PER_EN_GPT4_ENABLE BIT5
-
-#define CM_ICLKEN_PER_EN_UART3_DISABLE (0UL << 11)
-#define CM_ICLKEN_PER_EN_UART3_ENABLE BIT11
-
-#define CM_ICLKEN_PER_EN_GPIO2_DISABLE (0UL << 13)
-#define CM_ICLKEN_PER_EN_GPIO2_ENABLE BIT13
-
-#define CM_ICLKEN_PER_EN_GPIO3_DISABLE (0UL << 14)
-#define CM_ICLKEN_PER_EN_GPIO3_ENABLE BIT14
-
-#define CM_ICLKEN_PER_EN_GPIO4_DISABLE (0UL << 15)
-#define CM_ICLKEN_PER_EN_GPIO4_ENABLE BIT15
-
-#define CM_ICLKEN_PER_EN_GPIO5_DISABLE (0UL << 16)
-#define CM_ICLKEN_PER_EN_GPIO5_ENABLE BIT16
-
-#define CM_ICLKEN_PER_EN_GPIO6_DISABLE (0UL << 17)
-#define CM_ICLKEN_PER_EN_GPIO6_ENABLE BIT17
-
-//Timer source clock selection
-#define CM_CLKSEL_PER_CLKSEL_GPT3_32K (0UL << 1)
-#define CM_CLKSEL_PER_CLKSEL_GPT3_SYS BIT1
-
-#define CM_CLKSEL_PER_CLKSEL_GPT4_32K (0UL << 2)
-#define CM_CLKSEL_PER_CLKSEL_GPT4_SYS BIT2
-
-//Reset management (Global and Cold reset)
-#define RST_GS BIT1
-#define RST_DPLL3 BIT2
-#define GLOBAL_SW_RST BIT1
-#define GLOBAL_COLD_RST (0x0UL << 0)
-
-#endif // __OMAP3530PRCM_H__
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530PRCM_H__
+#define __OMAP3530PRCM_H__
+
+#define CM_FCLKEN1_CORE (0x48004A00)
+#define CM_FCLKEN3_CORE (0x48004A08)
+#define CM_ICLKEN1_CORE (0x48004A10)
+#define CM_ICLKEN3_CORE (0x48004A18)
+#define CM_CLKEN2_PLL (0x48004D04)
+#define CM_CLKSEL4_PLL (0x48004D4C)
+#define CM_CLKSEL5_PLL (0x48004D50)
+#define CM_FCLKEN_USBHOST (0x48005400)
+#define CM_ICLKEN_USBHOST (0x48005410)
+#define CM_CLKSTST_USBHOST (0x4800544c)
+
+//Wakeup clock defintion
+#define CM_FCLKEN_WKUP (0x48004C00)
+#define CM_ICLKEN_WKUP (0x48004C10)
+
+//Peripheral clock definition
+#define CM_FCLKEN_PER (0x48005000)
+#define CM_ICLKEN_PER (0x48005010)
+#define CM_CLKSEL_PER (0x48005040)
+
+//Reset management definition
+#define PRM_RSTCTRL (0x48307250)
+#define PRM_RSTST (0x48307258)
+
+//CORE clock
+#define CM_FCLKEN1_CORE_EN_I2C1_MASK BIT15
+#define CM_FCLKEN1_CORE_EN_I2C1_DISABLE (0UL << 15)
+#define CM_FCLKEN1_CORE_EN_I2C1_ENABLE BIT15
+
+#define CM_ICLKEN1_CORE_EN_I2C1_MASK BIT15
+#define CM_ICLKEN1_CORE_EN_I2C1_DISABLE (0UL << 15)
+#define CM_ICLKEN1_CORE_EN_I2C1_ENABLE BIT15
+
+#define CM_FCLKEN1_CORE_EN_MMC1_MASK BIT24
+#define CM_FCLKEN1_CORE_EN_MMC1_DISABLE (0UL << 24)
+#define CM_FCLKEN1_CORE_EN_MMC1_ENABLE BIT24
+
+#define CM_FCLKEN3_CORE_EN_USBTLL_MASK BIT2
+#define CM_FCLKEN3_CORE_EN_USBTLL_DISABLE (0UL << 2)
+#define CM_FCLKEN3_CORE_EN_USBTLL_ENABLE BIT2
+
+#define CM_ICLKEN1_CORE_EN_MMC1_MASK BIT24
+#define CM_ICLKEN1_CORE_EN_MMC1_DISABLE (0UL << 24)
+#define CM_ICLKEN1_CORE_EN_MMC1_ENABLE BIT24
+
+#define CM_ICLKEN3_CORE_EN_USBTLL_MASK BIT2
+#define CM_ICLKEN3_CORE_EN_USBTLL_DISABLE (0UL << 2)
+#define CM_ICLKEN3_CORE_EN_USBTLL_ENABLE BIT2
+
+#define CM_CLKEN_FREQSEL_075_100 (0x03UL << 4)
+#define CM_CLKEN_ENABLE (7UL << 0)
+
+#define CM_CLKSEL_PLL_MULT(x) (((x) & 0x07FF) << 8)
+#define CM_CLKSEL_PLL_DIV(x) ((((x) - 1) & 0x7F) << 0)
+
+#define CM_CLKSEL_DIV_120M(x) (((x) & 0x1F) << 0)
+
+#define CM_FCLKEN_USBHOST_EN_USBHOST2_MASK BIT1
+#define CM_FCLKEN_USBHOST_EN_USBHOST2_DISABLE (0UL << 1)
+#define CM_FCLKEN_USBHOST_EN_USBHOST2_ENABLE BIT1
+
+#define CM_FCLKEN_USBHOST_EN_USBHOST1_MASK BIT0
+#define CM_FCLKEN_USBHOST_EN_USBHOST1_DISABLE (0UL << 0)
+#define CM_FCLKEN_USBHOST_EN_USBHOST1_ENABLE BIT0
+
+#define CM_ICLKEN_USBHOST_EN_USBHOST_MASK BIT0
+#define CM_ICLKEN_USBHOST_EN_USBHOST_DISABLE (0UL << 0)
+#define CM_ICLKEN_USBHOST_EN_USBHOST_ENABLE BIT0
+
+//Wakeup functional clock
+#define CM_FCLKEN_WKUP_EN_GPIO1_DISABLE (0UL << 3)
+#define CM_FCLKEN_WKUP_EN_GPIO1_ENABLE BIT3
+
+#define CM_FCLKEN_WKUP_EN_WDT2_DISABLE (0UL << 5)
+#define CM_FCLKEN_WKUP_EN_WDT2_ENABLE BIT5
+
+//Wakeup interface clock
+#define CM_ICLKEN_WKUP_EN_GPIO1_DISABLE (0UL << 3)
+#define CM_ICLKEN_WKUP_EN_GPIO1_ENABLE BIT3
+
+#define CM_ICLKEN_WKUP_EN_WDT2_DISABLE (0UL << 5)
+#define CM_ICLKEN_WKUP_EN_WDT2_ENABLE BIT5
+
+//Peripheral functional clock
+#define CM_FCLKEN_PER_EN_GPT3_DISABLE (0UL << 4)
+#define CM_FCLKEN_PER_EN_GPT3_ENABLE BIT4
+
+#define CM_FCLKEN_PER_EN_GPT4_DISABLE (0UL << 5)
+#define CM_FCLKEN_PER_EN_GPT4_ENABLE BIT5
+
+#define CM_FCLKEN_PER_EN_UART3_DISABLE (0UL << 11)
+#define CM_FCLKEN_PER_EN_UART3_ENABLE BIT11
+
+#define CM_FCLKEN_PER_EN_GPIO2_DISABLE (0UL << 13)
+#define CM_FCLKEN_PER_EN_GPIO2_ENABLE BIT13
+
+#define CM_FCLKEN_PER_EN_GPIO3_DISABLE (0UL << 14)
+#define CM_FCLKEN_PER_EN_GPIO3_ENABLE BIT14
+
+#define CM_FCLKEN_PER_EN_GPIO4_DISABLE (0UL << 15)
+#define CM_FCLKEN_PER_EN_GPIO4_ENABLE BIT15
+
+#define CM_FCLKEN_PER_EN_GPIO5_DISABLE (0UL << 16)
+#define CM_FCLKEN_PER_EN_GPIO5_ENABLE BIT16
+
+#define CM_FCLKEN_PER_EN_GPIO6_DISABLE (0UL << 17)
+#define CM_FCLKEN_PER_EN_GPIO6_ENABLE BIT17
+
+//Peripheral interface clock
+#define CM_ICLKEN_PER_EN_GPT3_DISABLE (0UL << 4)
+#define CM_ICLKEN_PER_EN_GPT3_ENABLE BIT4
+
+#define CM_ICLKEN_PER_EN_GPT4_DISABLE (0UL << 5)
+#define CM_ICLKEN_PER_EN_GPT4_ENABLE BIT5
+
+#define CM_ICLKEN_PER_EN_UART3_DISABLE (0UL << 11)
+#define CM_ICLKEN_PER_EN_UART3_ENABLE BIT11
+
+#define CM_ICLKEN_PER_EN_GPIO2_DISABLE (0UL << 13)
+#define CM_ICLKEN_PER_EN_GPIO2_ENABLE BIT13
+
+#define CM_ICLKEN_PER_EN_GPIO3_DISABLE (0UL << 14)
+#define CM_ICLKEN_PER_EN_GPIO3_ENABLE BIT14
+
+#define CM_ICLKEN_PER_EN_GPIO4_DISABLE (0UL << 15)
+#define CM_ICLKEN_PER_EN_GPIO4_ENABLE BIT15
+
+#define CM_ICLKEN_PER_EN_GPIO5_DISABLE (0UL << 16)
+#define CM_ICLKEN_PER_EN_GPIO5_ENABLE BIT16
+
+#define CM_ICLKEN_PER_EN_GPIO6_DISABLE (0UL << 17)
+#define CM_ICLKEN_PER_EN_GPIO6_ENABLE BIT17
+
+//Timer source clock selection
+#define CM_CLKSEL_PER_CLKSEL_GPT3_32K (0UL << 1)
+#define CM_CLKSEL_PER_CLKSEL_GPT3_SYS BIT1
+
+#define CM_CLKSEL_PER_CLKSEL_GPT4_32K (0UL << 2)
+#define CM_CLKSEL_PER_CLKSEL_GPT4_SYS BIT2
+
+//Reset management (Global and Cold reset)
+#define RST_GS BIT1
+#define RST_DPLL3 BIT2
+#define GLOBAL_SW_RST BIT1
+#define GLOBAL_COLD_RST (0x0UL << 0)
+
+#endif // __OMAP3530PRCM_H__
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Timer.h b/Omap35xxPkg/Include/Omap3530/Omap3530Timer.h
index 5067aaafc..d66da8dc0 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Timer.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Timer.h
@@ -1,82 +1,82 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530TIMER_H__
-#define __OMAP3530TIMER_H__
-
-#define GPTIMER1_BASE (0x48313000)
-#define GPTIMER2_BASE (0x49032000)
-#define GPTIMER3_BASE (0x49034000)
-#define GPTIMER4_BASE (0x49036000)
-#define GPTIMER5_BASE (0x49038000)
-#define GPTIMER6_BASE (0x4903A000)
-#define GPTIMER7_BASE (0x4903C000)
-#define GPTIMER8_BASE (0x4903E000)
-#define GPTIMER9_BASE (0x49040000)
-#define GPTIMER10_BASE (0x48086000)
-#define GPTIMER11_BASE (0x48088000)
-#define GPTIMER12_BASE (0x48304000)
-#define WDTIMER2_BASE (0x48314000)
-
-#define GPTIMER_TIOCP_CFG (0x0010)
-#define GPTIMER_TISTAT (0x0014)
-#define GPTIMER_TISR (0x0018)
-#define GPTIMER_TIER (0x001C)
-#define GPTIMER_TWER (0x0020)
-#define GPTIMER_TCLR (0x0024)
-#define GPTIMER_TCRR (0x0028)
-#define GPTIMER_TLDR (0x002C)
-#define GPTIMER_TTGR (0x0030)
-#define GPTIMER_TWPS (0x0034)
-#define GPTIMER_TMAR (0x0038)
-#define GPTIMER_TCAR1 (0x003C)
-#define GPTIMER_TSICR (0x0040)
-#define GPTIMER_TCAR2 (0x0044)
-#define GPTIMER_TPIR (0x0048)
-#define GPTIMER_TNIR (0x004C)
-#define GPTIMER_TCVR (0x0050)
-#define GPTIMER_TOCR (0x0054)
-#define GPTIMER_TOWR (0x0058)
-
-#define WSPR (0x048)
-
-#define TISR_TCAR_IT_FLAG_MASK BIT2
-#define TISR_OVF_IT_FLAG_MASK BIT1
-#define TISR_MAT_IT_FLAG_MASK BIT0
-#define TISR_ALL_INTERRUPT_MASK (TISR_TCAR_IT_FLAG_MASK | TISR_OVF_IT_FLAG_MASK | TISR_MAT_IT_FLAG_MASK)
-
-#define TISR_TCAR_IT_FLAG_NOT_PENDING (0UL << 2)
-#define TISR_OVF_IT_FLAG_NOT_PENDING (0UL << 1)
-#define TISR_MAT_IT_FLAG_NOT_PENDING (0UL << 0)
-#define TISR_NO_INTERRUPTS_PENDING (TISR_TCAR_IT_FLAG_NOT_PENDING | TISR_OVF_IT_FLAG_NOT_PENDING | TISR_MAT_IT_FLAG_NOT_PENDING)
-
-#define TISR_TCAR_IT_FLAG_CLEAR BIT2
-#define TISR_OVF_IT_FLAG_CLEAR BIT1
-#define TISR_MAT_IT_FLAG_CLEAR BIT0
-#define TISR_CLEAR_ALL (TISR_TCAR_IT_FLAG_CLEAR | TISR_OVF_IT_FLAG_CLEAR | TISR_MAT_IT_FLAG_CLEAR)
-
-#define TCLR_AR_AUTORELOAD BIT1
-#define TCLR_AR_ONESHOT (0UL << 1)
-#define TCLR_ST_ON BIT0
-#define TCLR_ST_OFF (0UL << 0)
-
-#define TIER_TCAR_IT_ENABLE (BIT2
-#define TIER_TCAR_IT_DISABLE (0UL << 2)
-#define TIER_OVF_IT_ENABLE BIT1
-#define TIER_OVF_IT_DISABLE (0UL << 1)
-#define TIER_MAT_IT_ENABLE BIT0
-#define TIER_MAT_IT_DISABLE (0UL << 0)
-
-#endif // __OMAP3530TIMER_H__
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530TIMER_H__
+#define __OMAP3530TIMER_H__
+
+#define GPTIMER1_BASE (0x48313000)
+#define GPTIMER2_BASE (0x49032000)
+#define GPTIMER3_BASE (0x49034000)
+#define GPTIMER4_BASE (0x49036000)
+#define GPTIMER5_BASE (0x49038000)
+#define GPTIMER6_BASE (0x4903A000)
+#define GPTIMER7_BASE (0x4903C000)
+#define GPTIMER8_BASE (0x4903E000)
+#define GPTIMER9_BASE (0x49040000)
+#define GPTIMER10_BASE (0x48086000)
+#define GPTIMER11_BASE (0x48088000)
+#define GPTIMER12_BASE (0x48304000)
+#define WDTIMER2_BASE (0x48314000)
+
+#define GPTIMER_TIOCP_CFG (0x0010)
+#define GPTIMER_TISTAT (0x0014)
+#define GPTIMER_TISR (0x0018)
+#define GPTIMER_TIER (0x001C)
+#define GPTIMER_TWER (0x0020)
+#define GPTIMER_TCLR (0x0024)
+#define GPTIMER_TCRR (0x0028)
+#define GPTIMER_TLDR (0x002C)
+#define GPTIMER_TTGR (0x0030)
+#define GPTIMER_TWPS (0x0034)
+#define GPTIMER_TMAR (0x0038)
+#define GPTIMER_TCAR1 (0x003C)
+#define GPTIMER_TSICR (0x0040)
+#define GPTIMER_TCAR2 (0x0044)
+#define GPTIMER_TPIR (0x0048)
+#define GPTIMER_TNIR (0x004C)
+#define GPTIMER_TCVR (0x0050)
+#define GPTIMER_TOCR (0x0054)
+#define GPTIMER_TOWR (0x0058)
+
+#define WSPR (0x048)
+
+#define TISR_TCAR_IT_FLAG_MASK BIT2
+#define TISR_OVF_IT_FLAG_MASK BIT1
+#define TISR_MAT_IT_FLAG_MASK BIT0
+#define TISR_ALL_INTERRUPT_MASK (TISR_TCAR_IT_FLAG_MASK | TISR_OVF_IT_FLAG_MASK | TISR_MAT_IT_FLAG_MASK)
+
+#define TISR_TCAR_IT_FLAG_NOT_PENDING (0UL << 2)
+#define TISR_OVF_IT_FLAG_NOT_PENDING (0UL << 1)
+#define TISR_MAT_IT_FLAG_NOT_PENDING (0UL << 0)
+#define TISR_NO_INTERRUPTS_PENDING (TISR_TCAR_IT_FLAG_NOT_PENDING | TISR_OVF_IT_FLAG_NOT_PENDING | TISR_MAT_IT_FLAG_NOT_PENDING)
+
+#define TISR_TCAR_IT_FLAG_CLEAR BIT2
+#define TISR_OVF_IT_FLAG_CLEAR BIT1
+#define TISR_MAT_IT_FLAG_CLEAR BIT0
+#define TISR_CLEAR_ALL (TISR_TCAR_IT_FLAG_CLEAR | TISR_OVF_IT_FLAG_CLEAR | TISR_MAT_IT_FLAG_CLEAR)
+
+#define TCLR_AR_AUTORELOAD BIT1
+#define TCLR_AR_ONESHOT (0UL << 1)
+#define TCLR_ST_ON BIT0
+#define TCLR_ST_OFF (0UL << 0)
+
+#define TIER_TCAR_IT_ENABLE (BIT2
+#define TIER_TCAR_IT_DISABLE (0UL << 2)
+#define TIER_OVF_IT_ENABLE BIT1
+#define TIER_OVF_IT_DISABLE (0UL << 1)
+#define TIER_MAT_IT_ENABLE BIT0
+#define TIER_MAT_IT_DISABLE (0UL << 0)
+
+#endif // __OMAP3530TIMER_H__
+
diff --git a/Omap35xxPkg/Include/Omap3530/Omap3530Usb.h b/Omap35xxPkg/Include/Omap3530/Omap3530Usb.h
index 9cc17ebf3..5d64cafc5 100644
--- a/Omap35xxPkg/Include/Omap3530/Omap3530Usb.h
+++ b/Omap35xxPkg/Include/Omap3530/Omap3530Usb.h
@@ -1,48 +1,48 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3530USB_H__
-#define __OMAP3530USB_H__
-
-#define USB_BASE (0x48060000)
-
-#define UHH_SYSCONFIG (USB_BASE + 0x4010)
-#define UHH_HOSTCONFIG (USB_BASE + 0x4040)
-#define UHH_SYSSTATUS (USB_BASE + 0x4014)
-
-#define USB_EHCI_HCCAPBASE (USB_BASE + 0x4800)
-
-#define UHH_SYSCONFIG_MIDLEMODE_NO_STANDBY BIT12
-#define UHH_SYSCONFIG_CLOCKACTIVITY_ON BIT8
-#define UHH_SYSCONFIG_SIDLEMODE_NO_STANDBY BIT3
-#define UHH_SYSCONFIG_ENAWAKEUP_ENABLE BIT2
-#define UHH_SYSCONFIG_SOFTRESET BIT1
-#define UHH_SYSCONFIG_AUTOIDLE_ALWAYS_RUN (0UL << 0)
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3530USB_H__
+#define __OMAP3530USB_H__
+
+#define USB_BASE (0x48060000)
+
+#define UHH_SYSCONFIG (USB_BASE + 0x4010)
+#define UHH_HOSTCONFIG (USB_BASE + 0x4040)
+#define UHH_SYSSTATUS (USB_BASE + 0x4014)
+
+#define USB_EHCI_HCCAPBASE (USB_BASE + 0x4800)
+
+#define UHH_SYSCONFIG_MIDLEMODE_NO_STANDBY BIT12
+#define UHH_SYSCONFIG_CLOCKACTIVITY_ON BIT8
+#define UHH_SYSCONFIG_SIDLEMODE_NO_STANDBY BIT3
+#define UHH_SYSCONFIG_ENAWAKEUP_ENABLE BIT2
+#define UHH_SYSCONFIG_SOFTRESET BIT1
+#define UHH_SYSCONFIG_AUTOIDLE_ALWAYS_RUN (0UL << 0)
+
#define UHH_HOSTCONFIG_P3_CONNECT_STATUS_DISCONNECT (0UL << 10)
#define UHH_HOSTCONFIG_P2_CONNECT_STATUS_DISCONNECT (0UL << 9)
#define UHH_HOSTCONFIG_P1_CONNECT_STATUS_DISCONNECT (0UL << 8)
#define UHH_HOSTCONFIG_ENA_INCR_ALIGN_DISABLE (0UL << 5)
-#define UHH_HOSTCONFIG_ENA_INCR16_ENABLE BIT4
-#define UHH_HOSTCONFIG_ENA_INCR8_ENABLE BIT3
-#define UHH_HOSTCONFIG_ENA_INCR4_ENABLE BIT2
+#define UHH_HOSTCONFIG_ENA_INCR16_ENABLE BIT4
+#define UHH_HOSTCONFIG_ENA_INCR8_ENABLE BIT3
+#define UHH_HOSTCONFIG_ENA_INCR4_ENABLE BIT2
#define UHH_HOSTCONFIG_AUTOPPD_ON_OVERCUR_EN_ON (0UL << 1)
-#define UHH_HOSTCONFIG_P1_ULPI_BYPASS_ULPI_MODE (0UL << 0)
-
-#define UHH_SYSSTATUS_RESETDONE (BIT0 | BIT1 | BIT2)
-
-#endif // __OMAP3530USB_H__
-
-
-
+#define UHH_HOSTCONFIG_P1_ULPI_BYPASS_ULPI_MODE (0UL << 0)
+
+#define UHH_SYSSTATUS_RESETDONE (BIT0 | BIT1 | BIT2)
+
+#endif // __OMAP3530USB_H__
+
+
+
diff --git a/Omap35xxPkg/Include/TPS65950.h b/Omap35xxPkg/Include/TPS65950.h
index cd708d979..20df2319e 100644
--- a/Omap35xxPkg/Include/TPS65950.h
+++ b/Omap35xxPkg/Include/TPS65950.h
@@ -1,80 +1,80 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __TPS65950_H__
-#define __TPS65950_H__
-
-#define EXTERNAL_DEVICE_REGISTER_TO_SLAVE_ADDRESS(x) (((x) >> 8) & 0xFF)
-#define EXTERNAL_DEVICE_REGISTER_TO_REGISTER(x) ((x) & 0xFF)
-#define EXTERNAL_DEVICE_REGISTER(SlaveAddress, Register) (((SlaveAddress) & 0xFF) << 8 | ((Register) & 0xFF))
-
-// I2C Address group
-#define I2C_ADDR_GRP_ID1 0x48
-#define I2C_ADDR_GRP_ID2 0x49
-#define I2C_ADDR_GRP_ID3 0x4A
-#define I2C_ADDR_GRP_ID4 0x4B
-#define I2C_ADDR_GRP_ID5 0x12
-
-// MMC definitions.
-#define VMMC1_DEV_GRP 0x82
-#define DEV_GRP_P1 BIT5
-
-#define VMMC1_DEDICATED_REG 0x85
-#define VSEL_1_85V 0x0
-#define VSEL_2_85V 0x1
-#define VSEL_3_00V 0x2
-#define VSEL_3_15V 0x3
-
-#define TPS65950_GPIO_CTRL 0xaa //I2C_ADDR_GRP_ID2
-#define CARD_DETECT_ENABLE (BIT2 | BIT0) // GPIO ON + GPIO CD1 enabled
-
-
-#define GPIODATAIN1 0x98 //I2C_ADDR_GRP_ID2
-#define CARD_DETECT_BIT BIT0
-
-// LEDEN register
-#define LEDEN 0xEE
-#define LEDAON BIT0
-#define LEDBON BIT1
-#define LEDAPWM BIT4
-#define LEDBPWM BIT5
-
-// RTC registers
-#define SECONDS_REG 0x1C
-#define MINUTES_REG 0x1D
-#define HOURS_REG 0x1E
-#define DAYS_REG 0x1F
-#define MONTHS_REG 0x20
-#define YEARS_REG 0x21
-#define WEEKS_REG 0x22
-#define RTC_CTRL_REG 0x29
-
-// USB PHY power
-#define VAUX2_DEDICATED 0x79
-#define VAUX2_DEV_GRP 0x76
-
-#define VAUX_DEV_GRP_NONE 0x00
-#define VAUX_DEV_GRP_P1 0x20
-#define VAUX_DEV_GRP_P2 0x40
-#define VAUX_DEV_GRP_P3 0x80
-#define VAUX_DEDICATED_18V 0x05
-
-// Display subsystem
-#define VPLL2_DEDICATED 0x91
-#define VPLL2_DEV_GRP 0x8E
-
-#define GPIODATADIR1 0x9B
-#define SETGPIODATAOUT1 0xA4
-
-#endif //__TPS65950_H__
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __TPS65950_H__
+#define __TPS65950_H__
+
+#define EXTERNAL_DEVICE_REGISTER_TO_SLAVE_ADDRESS(x) (((x) >> 8) & 0xFF)
+#define EXTERNAL_DEVICE_REGISTER_TO_REGISTER(x) ((x) & 0xFF)
+#define EXTERNAL_DEVICE_REGISTER(SlaveAddress, Register) (((SlaveAddress) & 0xFF) << 8 | ((Register) & 0xFF))
+
+// I2C Address group
+#define I2C_ADDR_GRP_ID1 0x48
+#define I2C_ADDR_GRP_ID2 0x49
+#define I2C_ADDR_GRP_ID3 0x4A
+#define I2C_ADDR_GRP_ID4 0x4B
+#define I2C_ADDR_GRP_ID5 0x12
+
+// MMC definitions.
+#define VMMC1_DEV_GRP 0x82
+#define DEV_GRP_P1 BIT5
+
+#define VMMC1_DEDICATED_REG 0x85
+#define VSEL_1_85V 0x0
+#define VSEL_2_85V 0x1
+#define VSEL_3_00V 0x2
+#define VSEL_3_15V 0x3
+
+#define TPS65950_GPIO_CTRL 0xaa //I2C_ADDR_GRP_ID2
+#define CARD_DETECT_ENABLE (BIT2 | BIT0) // GPIO ON + GPIO CD1 enabled
+
+
+#define GPIODATAIN1 0x98 //I2C_ADDR_GRP_ID2
+#define CARD_DETECT_BIT BIT0
+
+// LEDEN register
+#define LEDEN 0xEE
+#define LEDAON BIT0
+#define LEDBON BIT1
+#define LEDAPWM BIT4
+#define LEDBPWM BIT5
+
+// RTC registers
+#define SECONDS_REG 0x1C
+#define MINUTES_REG 0x1D
+#define HOURS_REG 0x1E
+#define DAYS_REG 0x1F
+#define MONTHS_REG 0x20
+#define YEARS_REG 0x21
+#define WEEKS_REG 0x22
+#define RTC_CTRL_REG 0x29
+
+// USB PHY power
+#define VAUX2_DEDICATED 0x79
+#define VAUX2_DEV_GRP 0x76
+
+#define VAUX_DEV_GRP_NONE 0x00
+#define VAUX_DEV_GRP_P1 0x20
+#define VAUX_DEV_GRP_P2 0x40
+#define VAUX_DEV_GRP_P3 0x80
+#define VAUX_DEDICATED_18V 0x05
+
+// Display subsystem
+#define VPLL2_DEDICATED 0x91
+#define VPLL2_DEV_GRP 0x8E
+
+#define GPIODATADIR1 0x9B
+#define SETGPIODATAOUT1 0xA4
+
+#endif //__TPS65950_H__
diff --git a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c
index 38c84dd88..9541e7e90 100644
--- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c
+++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputBlt.c
@@ -1,445 +1,445 @@
-/** @file
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
- **/
-
-#include <PiDxe.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/MemoryAllocationLib.h>
-
-#include <Guid/GlobalVariable.h>
-
-#include "LcdGraphicsOutputDxe.h"
-
-extern BOOLEAN mDisplayInitialized;
-
-//
-// Function Definitions
-//
-
-STATIC
-EFI_STATUS
-VideoCopyNoHorizontalOverlap (
- IN UINTN BitsPerPixel,
- IN volatile VOID *FrameBufferBase,
- IN UINT32 HorizontalResolution,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- UINTN SourceLine;
- UINTN DestinationLine;
- UINTN WidthInBytes;
- UINTN LineCount;
- INTN Step;
- VOID *SourceAddr;
- VOID *DestinationAddr;
-
- if( DestinationY <= SourceY ) {
- // scrolling up (or horizontally but without overlap)
- SourceLine = SourceY;
- DestinationLine = DestinationY;
- Step = 1;
- } else {
- // scrolling down
- SourceLine = SourceY + Height;
- DestinationLine = DestinationY + Height;
- Step = -1;
- }
-
- WidthInBytes = Width * 2;
-
- for( LineCount = 0; LineCount < Height; LineCount++ ) {
- // Update the start addresses of source & destination using 16bit pointer arithmetic
- SourceAddr = (VOID *)((UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
- DestinationAddr = (VOID *)((UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
-
- // Copy the entire line Y from video ram to the temp buffer
- CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
-
- // Update the line numbers
- SourceLine += Step;
- DestinationLine += Step;
- }
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-VideoCopyHorizontalOverlap (
- IN UINTN BitsPerPixel,
- IN volatile VOID *FrameBufferBase,
- UINT32 HorizontalResolution,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
-
- UINT16 *PixelBuffer16bit;
- UINT16 *SourcePixel16bit;
- UINT16 *DestinationPixel16bit;
-
- UINT32 SourcePixelY;
- UINT32 DestinationPixelY;
- UINTN SizeIn16Bits;
-
- // Allocate a temporary buffer
- PixelBuffer16bit = (UINT16 *) AllocatePool((Height * Width) * sizeof(UINT16));
-
- if (PixelBuffer16bit == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto EXIT;
- }
-
- // Access each pixel inside the source area of the Video Memory and copy it to the temp buffer
-
- SizeIn16Bits = Width * 2;
-
- for (SourcePixelY = SourceY, DestinationPixel16bit = PixelBuffer16bit;
- SourcePixelY < SourceY + Height;
- SourcePixelY++, DestinationPixel16bit += Width)
- {
- // Calculate the source address:
- SourcePixel16bit = (UINT16 *)FrameBufferBase + SourcePixelY * HorizontalResolution + SourceX;
-
- // Copy the entire line Y from Video to the temp buffer
- CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
- }
-
- // Copy from the temp buffer into the destination area of the Video Memory
-
- for (DestinationPixelY = DestinationY, SourcePixel16bit = PixelBuffer16bit;
- DestinationPixelY < DestinationY + Height;
- DestinationPixelY++, SourcePixel16bit += Width)
- {
- // Calculate the target address:
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + (DestinationPixelY * HorizontalResolution + DestinationX);
-
- // Copy the entire line Y from the temp buffer to Video
- CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
- }
-
- // Free the allocated memory
- FreePool((VOID *) PixelBuffer16bit);
-
-
-EXIT:
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltVideoFill (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_PIXEL_BITMASK* PixelInformation;
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- VOID *FrameBufferBase;
- UINT16 *DestinationPixel16bit;
- UINT16 Pixel16bit;
- UINT32 DestinationPixelX;
- UINT32 DestinationLine;
-
- Status = EFI_SUCCESS;
- PixelInformation = &This->Mode->Info->PixelInformation;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
-
- // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
- Pixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
- );
-
- // Copy the SourcePixel into every pixel inside the target rectangle
- for (DestinationLine = DestinationY;
- DestinationLine < DestinationY + Height;
- DestinationLine++)
- {
- for (DestinationPixelX = DestinationX;
- DestinationPixelX < DestinationX + Width;
- DestinationPixelX++)
- {
- // Calculate the target address:
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- *DestinationPixel16bit = Pixel16bit;
- }
- }
-
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltVideoToBltBuffer (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- EFI_PIXEL_BITMASK *PixelInformation;
- EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiDestinationPixel;
- VOID *FrameBufferBase;
- UINT16 *SourcePixel16bit;
- UINT16 Pixel16bit;
- UINT32 SourcePixelX;
- UINT32 SourceLine;
- UINT32 DestinationPixelX;
- UINT32 DestinationLine;
- UINT32 BltBufferHorizontalResolution;
-
- Status = EFI_SUCCESS;
- PixelInformation = &This->Mode->Info->PixelInformation;
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
- // Delta is not zero and it is different from the width.
- // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
- BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
- } else {
- BltBufferHorizontalResolution = Width;
- }
-
- // Access each pixel inside the Video Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++)
- {
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
- EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
-
- // Snapshot the pixel from the video buffer once, to speed up the operation.
- // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
- Pixel16bit = *SourcePixel16bit;
-
- // Copy the pixel into the new target
- EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 8 );
- EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) >> 3 );
- EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 3 );
- }
- }
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltBufferToVideo (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- EFI_PIXEL_BITMASK *PixelInformation;
- EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel;
- VOID *FrameBufferBase;
- UINT16 *DestinationPixel16bit;
- UINT32 SourcePixelX;
- UINT32 SourceLine;
- UINT32 DestinationPixelX;
- UINT32 DestinationLine;
- UINT32 BltBufferHorizontalResolution;
-
- Status = EFI_SUCCESS;
- PixelInformation = &This->Mode->Info->PixelInformation;
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
- // Delta is not zero and it is different from the width.
- // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
- BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
- } else {
- BltBufferHorizontalResolution = Width;
- }
-
- // Access each pixel inside the BltBuffer Memory
- for (SourceLine = SourceY, DestinationLine = DestinationY;
- SourceLine < SourceY + Height;
- SourceLine++, DestinationLine++) {
-
- for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
- SourcePixelX < SourceX + Width;
- SourcePixelX++, DestinationPixelX++)
- {
- // Calculate the source and target addresses:
- EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
- DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
-
- // Copy the pixel into the new target
- // Only the most significant bits will be copied across:
- // To convert from 8 bits to 5 bits per pixel we throw away the 3 least significant bits
- *DestinationPixel16bit = (UINT16) (
- ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
- | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
- | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
- );
- }
- }
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-BltVideoToVideo (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- UINT32 HorizontalResolution;
- UINTN BitsPerPixel;
- VOID *FrameBufferBase;
-
- BitsPerPixel = 16;
-
- HorizontalResolution = This->Mode->Info->HorizontalResolution;
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- //
- // BltVideo to BltVideo:
- //
- // Source is the Video Memory,
- // Destination is the Video Memory
-
- FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
-
- // The UEFI spec currently states:
- // "There is no limitation on the overlapping of the source and destination rectangles"
- // Therefore, we must be careful to avoid overwriting the source data
- if( SourceY == DestinationY ) {
- // Copying within the same height, e.g. horizontal shift
- if( SourceX == DestinationX ) {
- // Nothing to do
- Status = EFI_SUCCESS;
- } else if( ((SourceX>DestinationX)?(SourceX - DestinationX):(DestinationX - SourceX)) < Width ) {
- // There is overlap
- Status = VideoCopyHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
- } else {
- // No overlap
- Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
- }
- } else {
- // Copying from different heights
- Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
- }
-
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsBlt (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
- )
-{
- EFI_STATUS Status;
- LCD_INSTANCE *Instance;
-
- Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
-
- if (!mDisplayInitialized) {
- InitializeDisplay (Instance);
- }
-
- switch (BltOperation) {
- case EfiBltVideoFill:
- Status = BltVideoFill (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiBltVideoToBltBuffer:
- Status = BltVideoToBltBuffer (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiBltBufferToVideo:
- Status = BltBufferToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiBltVideoToVideo:
- Status = BltVideoToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
- break;
-
- case EfiGraphicsOutputBltOperationMax:
- default:
- DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: Invalid Operation\n"));
- Status = EFI_INVALID_PARAMETER;
- break;
- }
-
- return Status;
-}
+/** @file
+
+ Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+ **/
+
+#include <PiDxe.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/MemoryAllocationLib.h>
+
+#include <Guid/GlobalVariable.h>
+
+#include "LcdGraphicsOutputDxe.h"
+
+extern BOOLEAN mDisplayInitialized;
+
+//
+// Function Definitions
+//
+
+STATIC
+EFI_STATUS
+VideoCopyNoHorizontalOverlap (
+ IN UINTN BitsPerPixel,
+ IN volatile VOID *FrameBufferBase,
+ IN UINT32 HorizontalResolution,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINTN SourceLine;
+ UINTN DestinationLine;
+ UINTN WidthInBytes;
+ UINTN LineCount;
+ INTN Step;
+ VOID *SourceAddr;
+ VOID *DestinationAddr;
+
+ if( DestinationY <= SourceY ) {
+ // scrolling up (or horizontally but without overlap)
+ SourceLine = SourceY;
+ DestinationLine = DestinationY;
+ Step = 1;
+ } else {
+ // scrolling down
+ SourceLine = SourceY + Height;
+ DestinationLine = DestinationY + Height;
+ Step = -1;
+ }
+
+ WidthInBytes = Width * 2;
+
+ for( LineCount = 0; LineCount < Height; LineCount++ ) {
+ // Update the start addresses of source & destination using 16bit pointer arithmetic
+ SourceAddr = (VOID *)((UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourceX );
+ DestinationAddr = (VOID *)((UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationX);
+
+ // Copy the entire line Y from video ram to the temp buffer
+ CopyMem( DestinationAddr, SourceAddr, WidthInBytes);
+
+ // Update the line numbers
+ SourceLine += Step;
+ DestinationLine += Step;
+ }
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+VideoCopyHorizontalOverlap (
+ IN UINTN BitsPerPixel,
+ IN volatile VOID *FrameBufferBase,
+ UINT32 HorizontalResolution,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ UINT16 *PixelBuffer16bit;
+ UINT16 *SourcePixel16bit;
+ UINT16 *DestinationPixel16bit;
+
+ UINT32 SourcePixelY;
+ UINT32 DestinationPixelY;
+ UINTN SizeIn16Bits;
+
+ // Allocate a temporary buffer
+ PixelBuffer16bit = (UINT16 *) AllocatePool((Height * Width) * sizeof(UINT16));
+
+ if (PixelBuffer16bit == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto EXIT;
+ }
+
+ // Access each pixel inside the source area of the Video Memory and copy it to the temp buffer
+
+ SizeIn16Bits = Width * 2;
+
+ for (SourcePixelY = SourceY, DestinationPixel16bit = PixelBuffer16bit;
+ SourcePixelY < SourceY + Height;
+ SourcePixelY++, DestinationPixel16bit += Width)
+ {
+ // Calculate the source address:
+ SourcePixel16bit = (UINT16 *)FrameBufferBase + SourcePixelY * HorizontalResolution + SourceX;
+
+ // Copy the entire line Y from Video to the temp buffer
+ CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
+ }
+
+ // Copy from the temp buffer into the destination area of the Video Memory
+
+ for (DestinationPixelY = DestinationY, SourcePixel16bit = PixelBuffer16bit;
+ DestinationPixelY < DestinationY + Height;
+ DestinationPixelY++, SourcePixel16bit += Width)
+ {
+ // Calculate the target address:
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + (DestinationPixelY * HorizontalResolution + DestinationX);
+
+ // Copy the entire line Y from the temp buffer to Video
+ CopyMem( (VOID *)DestinationPixel16bit, (CONST VOID *)SourcePixel16bit, SizeIn16Bits);
+ }
+
+ // Free the allocated memory
+ FreePool((VOID *) PixelBuffer16bit);
+
+
+EXIT:
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltVideoFill (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_PIXEL_BITMASK* PixelInformation;
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ VOID *FrameBufferBase;
+ UINT16 *DestinationPixel16bit;
+ UINT16 Pixel16bit;
+ UINT32 DestinationPixelX;
+ UINT32 DestinationLine;
+
+ Status = EFI_SUCCESS;
+ PixelInformation = &This->Mode->Info->PixelInformation;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+
+ // Convert the EFI pixel at the start of the BltBuffer(0,0) into a video display pixel
+ Pixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
+ );
+
+ // Copy the SourcePixel into every pixel inside the target rectangle
+ for (DestinationLine = DestinationY;
+ DestinationLine < DestinationY + Height;
+ DestinationLine++)
+ {
+ for (DestinationPixelX = DestinationX;
+ DestinationPixelX < DestinationX + Width;
+ DestinationPixelX++)
+ {
+ // Calculate the target address:
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ *DestinationPixel16bit = Pixel16bit;
+ }
+ }
+
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltVideoToBltBuffer (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ EFI_PIXEL_BITMASK *PixelInformation;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiDestinationPixel;
+ VOID *FrameBufferBase;
+ UINT16 *SourcePixel16bit;
+ UINT16 Pixel16bit;
+ UINT32 SourcePixelX;
+ UINT32 SourceLine;
+ UINT32 DestinationPixelX;
+ UINT32 DestinationLine;
+ UINT32 BltBufferHorizontalResolution;
+
+ Status = EFI_SUCCESS;
+ PixelInformation = &This->Mode->Info->PixelInformation;
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
+ // Delta is not zero and it is different from the width.
+ // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
+ BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
+ } else {
+ BltBufferHorizontalResolution = Width;
+ }
+
+ // Access each pixel inside the Video Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++)
+ {
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ SourcePixel16bit = (UINT16 *)FrameBufferBase + SourceLine * HorizontalResolution + SourcePixelX;
+ EfiDestinationPixel = BltBuffer + DestinationLine * BltBufferHorizontalResolution + DestinationPixelX;
+
+ // Snapshot the pixel from the video buffer once, to speed up the operation.
+ // If we were dereferencing the pointer, as it is volatile, we would perform 3 memory read operations.
+ Pixel16bit = *SourcePixel16bit;
+
+ // Copy the pixel into the new target
+ EfiDestinationPixel->Red = (UINT8) ( (Pixel16bit & PixelInformation->RedMask ) >> 8 );
+ EfiDestinationPixel->Green = (UINT8) ( (Pixel16bit & PixelInformation->GreenMask ) >> 3 );
+ EfiDestinationPixel->Blue = (UINT8) ( (Pixel16bit & PixelInformation->BlueMask ) << 3 );
+ }
+ }
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltBufferToVideo (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ EFI_PIXEL_BITMASK *PixelInformation;
+ EFI_GRAPHICS_OUTPUT_BLT_PIXEL *EfiSourcePixel;
+ VOID *FrameBufferBase;
+ UINT16 *DestinationPixel16bit;
+ UINT32 SourcePixelX;
+ UINT32 SourceLine;
+ UINT32 DestinationPixelX;
+ UINT32 DestinationLine;
+ UINT32 BltBufferHorizontalResolution;
+
+ Status = EFI_SUCCESS;
+ PixelInformation = &This->Mode->Info->PixelInformation;
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ if(( Delta != 0 ) && ( Delta != Width * sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL))) {
+ // Delta is not zero and it is different from the width.
+ // Divide it by the size of a pixel to find out the buffer's horizontal resolution.
+ BltBufferHorizontalResolution = (UINT32) (Delta / sizeof(EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
+ } else {
+ BltBufferHorizontalResolution = Width;
+ }
+
+ // Access each pixel inside the BltBuffer Memory
+ for (SourceLine = SourceY, DestinationLine = DestinationY;
+ SourceLine < SourceY + Height;
+ SourceLine++, DestinationLine++) {
+
+ for (SourcePixelX = SourceX, DestinationPixelX = DestinationX;
+ SourcePixelX < SourceX + Width;
+ SourcePixelX++, DestinationPixelX++)
+ {
+ // Calculate the source and target addresses:
+ EfiSourcePixel = BltBuffer + SourceLine * BltBufferHorizontalResolution + SourcePixelX;
+ DestinationPixel16bit = (UINT16 *)FrameBufferBase + DestinationLine * HorizontalResolution + DestinationPixelX;
+
+ // Copy the pixel into the new target
+ // Only the most significant bits will be copied across:
+ // To convert from 8 bits to 5 bits per pixel we throw away the 3 least significant bits
+ *DestinationPixel16bit = (UINT16) (
+ ( (EfiSourcePixel->Red << 8) & PixelInformation->RedMask )
+ | ( (EfiSourcePixel->Green << 3) & PixelInformation->GreenMask )
+ | ( (EfiSourcePixel->Blue >> 3) & PixelInformation->BlueMask )
+ );
+ }
+ }
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+BltVideoToVideo (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 HorizontalResolution;
+ UINTN BitsPerPixel;
+ VOID *FrameBufferBase;
+
+ BitsPerPixel = 16;
+
+ HorizontalResolution = This->Mode->Info->HorizontalResolution;
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ //
+ // BltVideo to BltVideo:
+ //
+ // Source is the Video Memory,
+ // Destination is the Video Memory
+
+ FrameBufferBase = (UINTN *)((UINTN)(This->Mode->FrameBufferBase));
+
+ // The UEFI spec currently states:
+ // "There is no limitation on the overlapping of the source and destination rectangles"
+ // Therefore, we must be careful to avoid overwriting the source data
+ if( SourceY == DestinationY ) {
+ // Copying within the same height, e.g. horizontal shift
+ if( SourceX == DestinationX ) {
+ // Nothing to do
+ Status = EFI_SUCCESS;
+ } else if( ((SourceX>DestinationX)?(SourceX - DestinationX):(DestinationX - SourceX)) < Width ) {
+ // There is overlap
+ Status = VideoCopyHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
+ } else {
+ // No overlap
+ Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
+ }
+ } else {
+ // Copying from different heights
+ Status = VideoCopyNoHorizontalOverlap (BitsPerPixel, FrameBufferBase, HorizontalResolution, SourceX, SourceY, DestinationX, DestinationY, Width, Height );
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsBlt (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+ )
+{
+ EFI_STATUS Status;
+ LCD_INSTANCE *Instance;
+
+ Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
+
+ if (!mDisplayInitialized) {
+ InitializeDisplay (Instance);
+ }
+
+ switch (BltOperation) {
+ case EfiBltVideoFill:
+ Status = BltVideoFill (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiBltVideoToBltBuffer:
+ Status = BltVideoToBltBuffer (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiBltBufferToVideo:
+ Status = BltBufferToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiBltVideoToVideo:
+ Status = BltVideoToVideo (This, BltBuffer, SourceX, SourceY, DestinationX, DestinationY, Width, Height, Delta);
+ break;
+
+ case EfiGraphicsOutputBltOperationMax:
+ default:
+ DEBUG((DEBUG_ERROR, "LcdGraphicsBlt: Invalid Operation\n"));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ }
+
+ return Status;
+}
diff --git a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c
index 6c20575cf..e30a679d8 100644
--- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c
+++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.c
@@ -1,403 +1,403 @@
-/** @file
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "LcdGraphicsOutputDxe.h"
-
-BOOLEAN mDisplayInitialized = FALSE;
-
-LCD_MODE LcdModes[] = {
- {
- 0, 640, 480,
- 9, 4,
- 96, 16, 48,
- 2, 10, 33
- },
- {
- 1, 800, 600,
- 11, 2,
- 120, 56, 64,
- 5, 37, 22
- },
- {
- 2, 1024, 768,
- 6, 2,
- 96, 16, 48,
- 2, 10, 33
- },
-};
-
-LCD_INSTANCE mLcdTemplate = {
- LCD_INSTANCE_SIGNATURE,
- NULL, // Handle
- { // ModeInfo
- 0, // Version
- 0, // HorizontalResolution
- 0, // VerticalResolution
- PixelBltOnly, // PixelFormat
- {
- 0xF800, //RedMask;
- 0x7E0, //GreenMask;
- 0x1F, //BlueMask;
- 0x0//ReservedMask
- }, // PixelInformation
- 0, // PixelsPerScanLine
- },
- { // Mode
- 3, // MaxMode;
- 0, // Mode;
- NULL, // Info;
- 0, // SizeOfInfo;
- 0, // FrameBufferBase;
- 0 // FrameBufferSize;
- },
- { // Gop
- LcdGraphicsQueryMode, // QueryMode
- LcdGraphicsSetMode, // SetMode
- LcdGraphicsBlt, // Blt
- NULL // *Mode
- },
- { // DevicePath
- {
- {
- HARDWARE_DEVICE_PATH, HW_VENDOR_DP,
- (UINT8) (sizeof(VENDOR_DEVICE_PATH)),
- (UINT8) ((sizeof(VENDOR_DEVICE_PATH)) >> 8),
- },
- // Hardware Device Path for Lcd
- EFI_CALLER_ID_GUID // Use the driver's GUID
- },
-
- {
- END_DEVICE_PATH_TYPE,
- END_ENTIRE_DEVICE_PATH_SUBTYPE,
- sizeof(EFI_DEVICE_PATH_PROTOCOL),
- 0
- }
- }
-};
-
-EFI_STATUS
-LcdInstanceContructor (
- OUT LCD_INSTANCE** NewInstance
- )
-{
- LCD_INSTANCE* Instance;
-
- Instance = AllocateCopyPool (sizeof(LCD_INSTANCE), &mLcdTemplate);
- if (Instance == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- Instance->Gop.Mode = &Instance->Mode;
- Instance->Mode.Info = &Instance->ModeInfo;
-
- *NewInstance = Instance;
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-LcdPlatformGetVram (
- OUT EFI_PHYSICAL_ADDRESS* VramBaseAddress,
- OUT UINTN* VramSize
- )
-{
- EFI_STATUS Status;
- EFI_CPU_ARCH_PROTOCOL *Cpu;
- UINTN MaxSize;
-
- MaxSize = 0x500000;
- *VramSize = MaxSize;
-
- // Allocate VRAM from DRAM
- Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, EFI_SIZE_TO_PAGES((MaxSize)), VramBaseAddress);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- // Ensure the Cpu architectural protocol is already installed
- Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&Cpu);
- ASSERT_EFI_ERROR(Status);
-
- // Mark the VRAM as un-cacheable. The VRAM is inside the DRAM, which is cacheable.
- Status = Cpu->SetMemoryAttributes (Cpu, *VramBaseAddress, *VramSize, EFI_MEMORY_UC);
- if (EFI_ERROR(Status)) {
- gBS->FreePool (VramBaseAddress);
- return Status;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-DssSetMode (
- UINT32 VramBaseAddress,
- UINTN ModeNumber
- )
-{
- // Make sure the interface clock is running
- MmioWrite32 (CM_ICLKEN_DSS, EN_DSS);
-
- // Stop the functional clocks
- MmioAnd32 (CM_FCLKEN_DSS, ~(EN_DSS1 | EN_DSS2 | EN_TV));
-
- // Program the DSS clock divisor
- MmioWrite32 (CM_CLKSEL_DSS, 0x1000 | (LcdModes[ModeNumber].DssDivisor));
-
- // Start the functional clocks
- MmioOr32 (CM_FCLKEN_DSS, (EN_DSS1 | EN_DSS2 | EN_TV));
-
- // Wait for DSS to stabilize
- gBS->Stall(1);
-
- // Reset the subsystem
- MmioWrite32(DSS_SYSCONFIG, DSS_SOFTRESET);
- while (!(MmioRead32 (DSS_SYSSTATUS) & DSS_RESETDONE));
-
- // Configure LCD parameters
- MmioWrite32 (DISPC_SIZE_LCD,
- ((LcdModes[ModeNumber].HorizontalResolution - 1)
- | ((LcdModes[ModeNumber].VerticalResolution - 1) << 16))
- );
- MmioWrite32 (DISPC_TIMING_H,
- ( (LcdModes[ModeNumber].HSync - 1)
- | ((LcdModes[ModeNumber].HFrontPorch - 1) << 8)
- | ((LcdModes[ModeNumber].HBackPorch - 1) << 20))
- );
- MmioWrite32 (DISPC_TIMING_V,
- ( (LcdModes[ModeNumber].VSync - 1)
- | ((LcdModes[ModeNumber].VFrontPorch - 1) << 8)
- | ((LcdModes[ModeNumber].VBackPorch - 1) << 20))
- );
-
- // Set the framebuffer to only load frames (no gamma tables)
- MmioAnd32 (DISPC_CONFIG, CLEARLOADMODE);
- MmioOr32 (DISPC_CONFIG, LOAD_FRAME_ONLY);
-
- // Divisor for the pixel clock
- MmioWrite32(DISPC_DIVISOR, ((1 << 16) | LcdModes[ModeNumber].DispcDivisor) );
-
- // Set up the graphics layer
- MmioWrite32 (DISPC_GFX_PRELD, 0x2D8);
- MmioWrite32 (DISPC_GFX_BA0, VramBaseAddress);
- MmioWrite32 (DISPC_GFX_SIZE,
- ((LcdModes[ModeNumber].HorizontalResolution - 1)
- | ((LcdModes[ModeNumber].VerticalResolution - 1) << 16))
- );
-
- MmioWrite32(DISPC_GFX_ATTR, (GFXENABLE | RGB16 | BURSTSIZE16));
-
- // Start it all
- MmioOr32 (DISPC_CONTROL, (LCDENABLE | ACTIVEMATRIX | DATALINES24 | BYPASS_MODE | LCDENABLESIGNAL));
- MmioOr32 (DISPC_CONTROL, GOLCD);
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-HwInitializeDisplay (
- UINTN VramBaseAddress,
- UINTN VramSize
- )
-{
- EFI_STATUS Status;
- UINT8 Data;
- EFI_TPL OldTpl;
- EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
-
- // Enable power lines used by TFP410
- Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
- ASSERT_EFI_ERROR (Status);
-
- OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
- Data = VAUX_DEV_GRP_P1;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VPLL2_DEV_GRP), 1, &Data);
- ASSERT_EFI_ERROR(Status);
-
- Data = VAUX_DEDICATED_18V;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VPLL2_DEDICATED), 1, &Data);
- ASSERT_EFI_ERROR (Status);
-
- // Power up TFP410 (set GPIO2 on TPS - for BeagleBoard-xM)
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATADIR1), 1, &Data);
- ASSERT_EFI_ERROR (Status);
- Data |= BIT2;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATADIR1), 1, &Data);
- ASSERT_EFI_ERROR (Status);
-
- Data = BIT2;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, SETGPIODATAOUT1), 1, &Data);
- ASSERT_EFI_ERROR (Status);
-
- gBS->RestoreTPL(OldTpl);
-
- // Power up TFP410 (set GPIO 170 - for older BeagleBoards)
- MmioAnd32 (GPIO6_BASE + GPIO_OE, ~BIT10);
- MmioOr32 (GPIO6_BASE + GPIO_SETDATAOUT, BIT10);
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-InitializeDisplay (
- IN LCD_INSTANCE* Instance
- )
-{
- EFI_STATUS Status;
- UINTN VramSize;
- EFI_PHYSICAL_ADDRESS VramBaseAddress;
-
- Status = LcdPlatformGetVram (&VramBaseAddress, &VramSize);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- Instance->Mode.FrameBufferBase = VramBaseAddress;
- Instance->Mode.FrameBufferSize = VramSize;
-
- Status = HwInitializeDisplay((UINTN)VramBaseAddress, VramSize);
- if (!EFI_ERROR (Status)) {
- mDisplayInitialized = TRUE;
- }
-
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsQueryMode (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN UINT32 ModeNumber,
- OUT UINTN *SizeOfInfo,
- OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
- )
-{
- LCD_INSTANCE *Instance;
-
- Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
-
- if (!mDisplayInitialized) {
- InitializeDisplay (Instance);
- }
-
- // Error checking
- if ( (This == NULL) || (Info == NULL) || (SizeOfInfo == NULL) || (ModeNumber >= This->Mode->MaxMode) ) {
- DEBUG((DEBUG_ERROR, "LcdGraphicsQueryMode: ERROR - For mode number %d : Invalid Parameter.\n", ModeNumber ));
- return EFI_INVALID_PARAMETER;
- }
-
- *Info = AllocateCopyPool(sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION), &Instance->ModeInfo);
- if (*Info == NULL) {
- return EFI_OUT_OF_RESOURCES;
- }
-
- *SizeOfInfo = sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
-
- (*Info)->Version = 0;
- (*Info)->HorizontalResolution = LcdModes[ModeNumber].HorizontalResolution;
- (*Info)->VerticalResolution = LcdModes[ModeNumber].VerticalResolution;
- (*Info)->PixelFormat = PixelBltOnly;
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsSetMode (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN UINT32 ModeNumber
- )
-{
- LCD_INSTANCE *Instance;
-
- Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
-
- if (ModeNumber >= Instance->Mode.MaxMode) {
- return EFI_UNSUPPORTED;
- }
-
- if (!mDisplayInitialized) {
- InitializeDisplay (Instance);
- }
-
- DssSetMode((UINT32)Instance->Mode.FrameBufferBase, ModeNumber);
-
- Instance->Mode.Mode = ModeNumber;
- Instance->ModeInfo.HorizontalResolution = LcdModes[ModeNumber].HorizontalResolution;
- Instance->ModeInfo.VerticalResolution = LcdModes[ModeNumber].VerticalResolution;
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsOutputDxeInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- LCD_INSTANCE* Instance;
-
- Status = LcdInstanceContructor (&Instance);
- if (EFI_ERROR(Status)) {
- goto EXIT;
- }
-
- // Install the Graphics Output Protocol and the Device Path
- Status = gBS->InstallMultipleProtocolInterfaces(
- &Instance->Handle,
- &gEfiGraphicsOutputProtocolGuid, &Instance->Gop,
- &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
- NULL
- );
-
- if (EFI_ERROR(Status)) {
- DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the protocol. Exit Status=%r\n", Status));
- goto EXIT;
- }
-
- // Register for an ExitBootServicesEvent
- // When ExitBootServices starts, this function here will make sure that the graphics driver will shut down properly,
- // i.e. it will free up all allocated memory and perform any necessary hardware re-configuration.
- /*Status = gBS->CreateEvent (
- EVT_SIGNAL_EXIT_BOOT_SERVICES,
- TPL_NOTIFY,
- LcdGraphicsExitBootServicesEvent, NULL,
- &Instance->ExitBootServicesEvent
- );
-
- if (EFI_ERROR(Status)) {
- DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the ExitBootServicesEvent handler. Exit Status=%r\n", Status));
- goto EXIT_ERROR_UNINSTALL_PROTOCOL;
- }*/
-
- // To get here, everything must be fine, so just exit
- goto EXIT;
-
-//EXIT_ERROR_UNINSTALL_PROTOCOL:
- /* The following function could return an error message,
- * however, to get here something must have gone wrong already,
- * so preserve the original error, i.e. don't change
- * the Status variable, even it fails to uninstall the protocol.
- */
-/* gBS->UninstallMultipleProtocolInterfaces (
- Instance->Handle,
- &gEfiGraphicsOutputProtocolGuid, &Instance->Gop, // Uninstall Graphics Output protocol
- &gEfiDevicePathProtocolGuid, &Instance->DevicePath, // Uninstall device path
- NULL
- );*/
-
-EXIT:
- return Status;
-
-}
+/** @file
+
+ Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "LcdGraphicsOutputDxe.h"
+
+BOOLEAN mDisplayInitialized = FALSE;
+
+LCD_MODE LcdModes[] = {
+ {
+ 0, 640, 480,
+ 9, 4,
+ 96, 16, 48,
+ 2, 10, 33
+ },
+ {
+ 1, 800, 600,
+ 11, 2,
+ 120, 56, 64,
+ 5, 37, 22
+ },
+ {
+ 2, 1024, 768,
+ 6, 2,
+ 96, 16, 48,
+ 2, 10, 33
+ },
+};
+
+LCD_INSTANCE mLcdTemplate = {
+ LCD_INSTANCE_SIGNATURE,
+ NULL, // Handle
+ { // ModeInfo
+ 0, // Version
+ 0, // HorizontalResolution
+ 0, // VerticalResolution
+ PixelBltOnly, // PixelFormat
+ {
+ 0xF800, //RedMask;
+ 0x7E0, //GreenMask;
+ 0x1F, //BlueMask;
+ 0x0//ReservedMask
+ }, // PixelInformation
+ 0, // PixelsPerScanLine
+ },
+ { // Mode
+ 3, // MaxMode;
+ 0, // Mode;
+ NULL, // Info;
+ 0, // SizeOfInfo;
+ 0, // FrameBufferBase;
+ 0 // FrameBufferSize;
+ },
+ { // Gop
+ LcdGraphicsQueryMode, // QueryMode
+ LcdGraphicsSetMode, // SetMode
+ LcdGraphicsBlt, // Blt
+ NULL // *Mode
+ },
+ { // DevicePath
+ {
+ {
+ HARDWARE_DEVICE_PATH, HW_VENDOR_DP,
+ (UINT8) (sizeof(VENDOR_DEVICE_PATH)),
+ (UINT8) ((sizeof(VENDOR_DEVICE_PATH)) >> 8),
+ },
+ // Hardware Device Path for Lcd
+ EFI_CALLER_ID_GUID // Use the driver's GUID
+ },
+
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ sizeof(EFI_DEVICE_PATH_PROTOCOL),
+ 0
+ }
+ }
+};
+
+EFI_STATUS
+LcdInstanceContructor (
+ OUT LCD_INSTANCE** NewInstance
+ )
+{
+ LCD_INSTANCE* Instance;
+
+ Instance = AllocateCopyPool (sizeof(LCD_INSTANCE), &mLcdTemplate);
+ if (Instance == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Instance->Gop.Mode = &Instance->Mode;
+ Instance->Mode.Info = &Instance->ModeInfo;
+
+ *NewInstance = Instance;
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+LcdPlatformGetVram (
+ OUT EFI_PHYSICAL_ADDRESS* VramBaseAddress,
+ OUT UINTN* VramSize
+ )
+{
+ EFI_STATUS Status;
+ EFI_CPU_ARCH_PROTOCOL *Cpu;
+ UINTN MaxSize;
+
+ MaxSize = 0x500000;
+ *VramSize = MaxSize;
+
+ // Allocate VRAM from DRAM
+ Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, EFI_SIZE_TO_PAGES((MaxSize)), VramBaseAddress);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ // Ensure the Cpu architectural protocol is already installed
+ Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&Cpu);
+ ASSERT_EFI_ERROR(Status);
+
+ // Mark the VRAM as un-cacheable. The VRAM is inside the DRAM, which is cacheable.
+ Status = Cpu->SetMemoryAttributes (Cpu, *VramBaseAddress, *VramSize, EFI_MEMORY_UC);
+ if (EFI_ERROR(Status)) {
+ gBS->FreePool (VramBaseAddress);
+ return Status;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+DssSetMode (
+ UINT32 VramBaseAddress,
+ UINTN ModeNumber
+ )
+{
+ // Make sure the interface clock is running
+ MmioWrite32 (CM_ICLKEN_DSS, EN_DSS);
+
+ // Stop the functional clocks
+ MmioAnd32 (CM_FCLKEN_DSS, ~(EN_DSS1 | EN_DSS2 | EN_TV));
+
+ // Program the DSS clock divisor
+ MmioWrite32 (CM_CLKSEL_DSS, 0x1000 | (LcdModes[ModeNumber].DssDivisor));
+
+ // Start the functional clocks
+ MmioOr32 (CM_FCLKEN_DSS, (EN_DSS1 | EN_DSS2 | EN_TV));
+
+ // Wait for DSS to stabilize
+ gBS->Stall(1);
+
+ // Reset the subsystem
+ MmioWrite32(DSS_SYSCONFIG, DSS_SOFTRESET);
+ while (!(MmioRead32 (DSS_SYSSTATUS) & DSS_RESETDONE));
+
+ // Configure LCD parameters
+ MmioWrite32 (DISPC_SIZE_LCD,
+ ((LcdModes[ModeNumber].HorizontalResolution - 1)
+ | ((LcdModes[ModeNumber].VerticalResolution - 1) << 16))
+ );
+ MmioWrite32 (DISPC_TIMING_H,
+ ( (LcdModes[ModeNumber].HSync - 1)
+ | ((LcdModes[ModeNumber].HFrontPorch - 1) << 8)
+ | ((LcdModes[ModeNumber].HBackPorch - 1) << 20))
+ );
+ MmioWrite32 (DISPC_TIMING_V,
+ ( (LcdModes[ModeNumber].VSync - 1)
+ | ((LcdModes[ModeNumber].VFrontPorch - 1) << 8)
+ | ((LcdModes[ModeNumber].VBackPorch - 1) << 20))
+ );
+
+ // Set the framebuffer to only load frames (no gamma tables)
+ MmioAnd32 (DISPC_CONFIG, CLEARLOADMODE);
+ MmioOr32 (DISPC_CONFIG, LOAD_FRAME_ONLY);
+
+ // Divisor for the pixel clock
+ MmioWrite32(DISPC_DIVISOR, ((1 << 16) | LcdModes[ModeNumber].DispcDivisor) );
+
+ // Set up the graphics layer
+ MmioWrite32 (DISPC_GFX_PRELD, 0x2D8);
+ MmioWrite32 (DISPC_GFX_BA0, VramBaseAddress);
+ MmioWrite32 (DISPC_GFX_SIZE,
+ ((LcdModes[ModeNumber].HorizontalResolution - 1)
+ | ((LcdModes[ModeNumber].VerticalResolution - 1) << 16))
+ );
+
+ MmioWrite32(DISPC_GFX_ATTR, (GFXENABLE | RGB16 | BURSTSIZE16));
+
+ // Start it all
+ MmioOr32 (DISPC_CONTROL, (LCDENABLE | ACTIVEMATRIX | DATALINES24 | BYPASS_MODE | LCDENABLESIGNAL));
+ MmioOr32 (DISPC_CONTROL, GOLCD);
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+HwInitializeDisplay (
+ UINTN VramBaseAddress,
+ UINTN VramSize
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data;
+ EFI_TPL OldTpl;
+ EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
+
+ // Enable power lines used by TFP410
+ Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
+ ASSERT_EFI_ERROR (Status);
+
+ OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
+ Data = VAUX_DEV_GRP_P1;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VPLL2_DEV_GRP), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+
+ Data = VAUX_DEDICATED_18V;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VPLL2_DEDICATED), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+
+ // Power up TFP410 (set GPIO2 on TPS - for BeagleBoard-xM)
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATADIR1), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+ Data |= BIT2;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATADIR1), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+
+ Data = BIT2;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, SETGPIODATAOUT1), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+
+ gBS->RestoreTPL(OldTpl);
+
+ // Power up TFP410 (set GPIO 170 - for older BeagleBoards)
+ MmioAnd32 (GPIO6_BASE + GPIO_OE, ~BIT10);
+ MmioOr32 (GPIO6_BASE + GPIO_SETDATAOUT, BIT10);
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+InitializeDisplay (
+ IN LCD_INSTANCE* Instance
+ )
+{
+ EFI_STATUS Status;
+ UINTN VramSize;
+ EFI_PHYSICAL_ADDRESS VramBaseAddress;
+
+ Status = LcdPlatformGetVram (&VramBaseAddress, &VramSize);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Instance->Mode.FrameBufferBase = VramBaseAddress;
+ Instance->Mode.FrameBufferSize = VramSize;
+
+ Status = HwInitializeDisplay((UINTN)VramBaseAddress, VramSize);
+ if (!EFI_ERROR (Status)) {
+ mDisplayInitialized = TRUE;
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsQueryMode (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN UINT32 ModeNumber,
+ OUT UINTN *SizeOfInfo,
+ OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
+ )
+{
+ LCD_INSTANCE *Instance;
+
+ Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
+
+ if (!mDisplayInitialized) {
+ InitializeDisplay (Instance);
+ }
+
+ // Error checking
+ if ( (This == NULL) || (Info == NULL) || (SizeOfInfo == NULL) || (ModeNumber >= This->Mode->MaxMode) ) {
+ DEBUG((DEBUG_ERROR, "LcdGraphicsQueryMode: ERROR - For mode number %d : Invalid Parameter.\n", ModeNumber ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *Info = AllocateCopyPool(sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION), &Instance->ModeInfo);
+ if (*Info == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ *SizeOfInfo = sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
+
+ (*Info)->Version = 0;
+ (*Info)->HorizontalResolution = LcdModes[ModeNumber].HorizontalResolution;
+ (*Info)->VerticalResolution = LcdModes[ModeNumber].VerticalResolution;
+ (*Info)->PixelFormat = PixelBltOnly;
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsSetMode (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN UINT32 ModeNumber
+ )
+{
+ LCD_INSTANCE *Instance;
+
+ Instance = LCD_INSTANCE_FROM_GOP_THIS(This);
+
+ if (ModeNumber >= Instance->Mode.MaxMode) {
+ return EFI_UNSUPPORTED;
+ }
+
+ if (!mDisplayInitialized) {
+ InitializeDisplay (Instance);
+ }
+
+ DssSetMode((UINT32)Instance->Mode.FrameBufferBase, ModeNumber);
+
+ Instance->Mode.Mode = ModeNumber;
+ Instance->ModeInfo.HorizontalResolution = LcdModes[ModeNumber].HorizontalResolution;
+ Instance->ModeInfo.VerticalResolution = LcdModes[ModeNumber].VerticalResolution;
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsOutputDxeInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ LCD_INSTANCE* Instance;
+
+ Status = LcdInstanceContructor (&Instance);
+ if (EFI_ERROR(Status)) {
+ goto EXIT;
+ }
+
+ // Install the Graphics Output Protocol and the Device Path
+ Status = gBS->InstallMultipleProtocolInterfaces(
+ &Instance->Handle,
+ &gEfiGraphicsOutputProtocolGuid, &Instance->Gop,
+ &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
+ NULL
+ );
+
+ if (EFI_ERROR(Status)) {
+ DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the protocol. Exit Status=%r\n", Status));
+ goto EXIT;
+ }
+
+ // Register for an ExitBootServicesEvent
+ // When ExitBootServices starts, this function here will make sure that the graphics driver will shut down properly,
+ // i.e. it will free up all allocated memory and perform any necessary hardware re-configuration.
+ /*Status = gBS->CreateEvent (
+ EVT_SIGNAL_EXIT_BOOT_SERVICES,
+ TPL_NOTIFY,
+ LcdGraphicsExitBootServicesEvent, NULL,
+ &Instance->ExitBootServicesEvent
+ );
+
+ if (EFI_ERROR(Status)) {
+ DEBUG((DEBUG_ERROR, "GraphicsOutputDxeInitialize: Can not install the ExitBootServicesEvent handler. Exit Status=%r\n", Status));
+ goto EXIT_ERROR_UNINSTALL_PROTOCOL;
+ }*/
+
+ // To get here, everything must be fine, so just exit
+ goto EXIT;
+
+//EXIT_ERROR_UNINSTALL_PROTOCOL:
+ /* The following function could return an error message,
+ * however, to get here something must have gone wrong already,
+ * so preserve the original error, i.e. don't change
+ * the Status variable, even it fails to uninstall the protocol.
+ */
+/* gBS->UninstallMultipleProtocolInterfaces (
+ Instance->Handle,
+ &gEfiGraphicsOutputProtocolGuid, &Instance->Gop, // Uninstall Graphics Output protocol
+ &gEfiDevicePathProtocolGuid, &Instance->DevicePath, // Uninstall device path
+ NULL
+ );*/
+
+EXIT:
+ return Status;
+
+}
diff --git a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h
index 39e69478a..520e28e67 100644
--- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h
+++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.h
@@ -1,157 +1,157 @@
-/** @file
-
- Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __OMAP3_DSS_GRAPHICS__
-#define __OMAP3_DSS_GRAPHICS__
-
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/DebugLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/IoLib.h>
-
-#include <Protocol/DevicePathToText.h>
-#include <Protocol/EmbeddedExternalDevice.h>
-#include <Protocol/Cpu.h>
-
-#include <Guid/GlobalVariable.h>
-
-#include <Omap3530/Omap3530.h>
-#include <TPS65950.h>
-
-typedef struct {
- VENDOR_DEVICE_PATH Guid;
- EFI_DEVICE_PATH_PROTOCOL End;
-} LCD_GRAPHICS_DEVICE_PATH;
-
-typedef struct {
- UINTN Signature;
- EFI_HANDLE Handle;
- EFI_GRAPHICS_OUTPUT_MODE_INFORMATION ModeInfo;
- EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE Mode;
- EFI_GRAPHICS_OUTPUT_PROTOCOL Gop;
- LCD_GRAPHICS_DEVICE_PATH DevicePath;
-// EFI_EVENT ExitBootServicesEvent;
-} LCD_INSTANCE;
-
-#define LCD_INSTANCE_SIGNATURE SIGNATURE_32('l', 'c', 'd', '0')
-#define LCD_INSTANCE_FROM_GOP_THIS(a) CR (a, LCD_INSTANCE, Gop, LCD_INSTANCE_SIGNATURE)
-
-typedef struct {
- UINTN Mode;
- UINTN HorizontalResolution;
- UINTN VerticalResolution;
-
- UINT32 DssDivisor;
- UINT32 DispcDivisor;
-
- UINT32 HSync;
- UINT32 HFrontPorch;
- UINT32 HBackPorch;
-
- UINT32 VSync;
- UINT32 VFrontPorch;
- UINT32 VBackPorch;
-} LCD_MODE;
-
-EFI_STATUS
-InitializeDisplay (
- IN LCD_INSTANCE* Instance
-);
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsQueryMode (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN UINT32 ModeNumber,
- OUT UINTN *SizeOfInfo,
- OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
-);
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsSetMode (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN UINT32 ModeNumber
-);
-
-EFI_STATUS
-EFIAPI
-LcdGraphicsBlt (
- IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
- IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
- IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
- IN UINTN SourceX,
- IN UINTN SourceY,
- IN UINTN DestinationX,
- IN UINTN DestinationY,
- IN UINTN Width,
- IN UINTN Height,
- IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
-);
-
-// HW registers
-#define CM_FCLKEN_DSS 0x48004E00
-#define CM_ICLKEN_DSS 0x48004E10
-
-#define DSS_CONTROL 0x48050040
-#define DSS_SYSCONFIG 0x48050010
-#define DSS_SYSSTATUS 0x48050014
-
-#define DISPC_CONTROL 0x48050440
-#define DISPC_CONFIG 0x48050444
-#define DISPC_SIZE_LCD 0x4805047C
-#define DISPC_TIMING_H 0x48050464
-#define DISPC_TIMING_V 0x48050468
-
-#define CM_CLKSEL_DSS 0x48004E40
-#define DISPC_DIVISOR 0x48050470
-#define DISPC_POL_FREQ 0x4805046C
-
-#define DISPC_GFX_TABLE_BA 0x480504B8
-#define DISPC_GFX_BA0 0x48050480
-#define DISPC_GFX_BA1 0x48050484
-#define DISPC_GFX_POS 0x48050488
-#define DISPC_GFX_SIZE 0x4805048C
-#define DISPC_GFX_ATTR 0x480504A0
-#define DISPC_GFX_PRELD 0x4805062C
-
-#define DISPC_DEFAULT_COLOR_0 0x4805044C
-
-//#define DISPC_IRQSTATUS
-
-// Bits
-#define EN_TV 0x4
-#define EN_DSS2 0x2
-#define EN_DSS1 0x1
-#define EN_DSS 0x1
-
-#define DSS_SOFTRESET 0x2
-#define DSS_RESETDONE 0x1
-
-#define BYPASS_MODE (BIT15 | BIT16)
-
-#define LCDENABLE BIT0
-#define ACTIVEMATRIX BIT3
-#define GOLCD BIT5
-#define DATALINES24 (BIT8 | BIT9)
-#define LCDENABLESIGNAL BIT28
-
-#define GFXENABLE BIT0
-#define RGB16 (0x6 << 1)
-#define BURSTSIZE16 (0x2 << 6)
-
-#define CLEARLOADMODE ~(BIT2 | BIT1)
-#define LOAD_FRAME_ONLY BIT2
-
-#endif
+/** @file
+
+ Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef __OMAP3_DSS_GRAPHICS__
+#define __OMAP3_DSS_GRAPHICS__
+
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/DebugLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/IoLib.h>
+
+#include <Protocol/DevicePathToText.h>
+#include <Protocol/EmbeddedExternalDevice.h>
+#include <Protocol/Cpu.h>
+
+#include <Guid/GlobalVariable.h>
+
+#include <Omap3530/Omap3530.h>
+#include <TPS65950.h>
+
+typedef struct {
+ VENDOR_DEVICE_PATH Guid;
+ EFI_DEVICE_PATH_PROTOCOL End;
+} LCD_GRAPHICS_DEVICE_PATH;
+
+typedef struct {
+ UINTN Signature;
+ EFI_HANDLE Handle;
+ EFI_GRAPHICS_OUTPUT_MODE_INFORMATION ModeInfo;
+ EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE Mode;
+ EFI_GRAPHICS_OUTPUT_PROTOCOL Gop;
+ LCD_GRAPHICS_DEVICE_PATH DevicePath;
+// EFI_EVENT ExitBootServicesEvent;
+} LCD_INSTANCE;
+
+#define LCD_INSTANCE_SIGNATURE SIGNATURE_32('l', 'c', 'd', '0')
+#define LCD_INSTANCE_FROM_GOP_THIS(a) CR (a, LCD_INSTANCE, Gop, LCD_INSTANCE_SIGNATURE)
+
+typedef struct {
+ UINTN Mode;
+ UINTN HorizontalResolution;
+ UINTN VerticalResolution;
+
+ UINT32 DssDivisor;
+ UINT32 DispcDivisor;
+
+ UINT32 HSync;
+ UINT32 HFrontPorch;
+ UINT32 HBackPorch;
+
+ UINT32 VSync;
+ UINT32 VFrontPorch;
+ UINT32 VBackPorch;
+} LCD_MODE;
+
+EFI_STATUS
+InitializeDisplay (
+ IN LCD_INSTANCE* Instance
+);
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsQueryMode (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN UINT32 ModeNumber,
+ OUT UINTN *SizeOfInfo,
+ OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
+);
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsSetMode (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN UINT32 ModeNumber
+);
+
+EFI_STATUS
+EFIAPI
+LcdGraphicsBlt (
+ IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
+ IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
+ IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
+ IN UINTN SourceX,
+ IN UINTN SourceY,
+ IN UINTN DestinationX,
+ IN UINTN DestinationY,
+ IN UINTN Width,
+ IN UINTN Height,
+ IN UINTN Delta OPTIONAL // Number of BYTES in a row of the BltBuffer
+);
+
+// HW registers
+#define CM_FCLKEN_DSS 0x48004E00
+#define CM_ICLKEN_DSS 0x48004E10
+
+#define DSS_CONTROL 0x48050040
+#define DSS_SYSCONFIG 0x48050010
+#define DSS_SYSSTATUS 0x48050014
+
+#define DISPC_CONTROL 0x48050440
+#define DISPC_CONFIG 0x48050444
+#define DISPC_SIZE_LCD 0x4805047C
+#define DISPC_TIMING_H 0x48050464
+#define DISPC_TIMING_V 0x48050468
+
+#define CM_CLKSEL_DSS 0x48004E40
+#define DISPC_DIVISOR 0x48050470
+#define DISPC_POL_FREQ 0x4805046C
+
+#define DISPC_GFX_TABLE_BA 0x480504B8
+#define DISPC_GFX_BA0 0x48050480
+#define DISPC_GFX_BA1 0x48050484
+#define DISPC_GFX_POS 0x48050488
+#define DISPC_GFX_SIZE 0x4805048C
+#define DISPC_GFX_ATTR 0x480504A0
+#define DISPC_GFX_PRELD 0x4805062C
+
+#define DISPC_DEFAULT_COLOR_0 0x4805044C
+
+//#define DISPC_IRQSTATUS
+
+// Bits
+#define EN_TV 0x4
+#define EN_DSS2 0x2
+#define EN_DSS1 0x1
+#define EN_DSS 0x1
+
+#define DSS_SOFTRESET 0x2
+#define DSS_RESETDONE 0x1
+
+#define BYPASS_MODE (BIT15 | BIT16)
+
+#define LCDENABLE BIT0
+#define ACTIVEMATRIX BIT3
+#define GOLCD BIT5
+#define DATALINES24 (BIT8 | BIT9)
+#define LCDENABLESIGNAL BIT28
+
+#define GFXENABLE BIT0
+#define RGB16 (0x6 << 1)
+#define BURSTSIZE16 (0x2 << 6)
+
+#define CLEARLOADMODE ~(BIT2 | BIT1)
+#define LOAD_FRAME_ONLY BIT2
+
+#endif
diff --git a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf
index f595bb39e..ac026f435 100644
--- a/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf
+++ b/Omap35xxPkg/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf
@@ -1,52 +1,52 @@
-#/** @file
-#
-# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = LcdGraphicsDxe
- FILE_GUID = E68088EF-D1A4-4336-C1DB-4D3A204730A6
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
- ENTRY_POINT = LcdGraphicsOutputDxeInitialize
-
-[Sources.common]
- LcdGraphicsOutputDxe.c
- LcdGraphicsOutputBlt.c
-
-[Packages]
- MdePkg/MdePkg.dec
- MdeModulePkg/MdeModulePkg.dec
- ArmPkg/ArmPkg.dec
- ArmPlatformPkg/ArmPlatformPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
-
-[LibraryClasses]
- ArmLib
- UefiLib
- BaseLib
- DebugLib
- TimerLib
- UefiDriverEntryPoint
- UefiBootServicesTableLib
- IoLib
- BaseMemoryLib
-
-[Protocols]
- gEfiDevicePathProtocolGuid
- gEfiGraphicsOutputProtocolGuid
- gEfiDevicePathToTextProtocolGuid
- gEmbeddedExternalDeviceProtocolGuid
-
-[Depex]
- gEfiCpuArchProtocolGuid AND gEfiTimerArchProtocolGuid
+#/** @file
+#
+# Copyright (c) 2011, ARM Ltd. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = LcdGraphicsDxe
+ FILE_GUID = E68088EF-D1A4-4336-C1DB-4D3A204730A6
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = LcdGraphicsOutputDxeInitialize
+
+[Sources.common]
+ LcdGraphicsOutputDxe.c
+ LcdGraphicsOutputBlt.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ ArmPkg/ArmPkg.dec
+ ArmPlatformPkg/ArmPlatformPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+
+[LibraryClasses]
+ ArmLib
+ UefiLib
+ BaseLib
+ DebugLib
+ TimerLib
+ UefiDriverEntryPoint
+ UefiBootServicesTableLib
+ IoLib
+ BaseMemoryLib
+
+[Protocols]
+ gEfiDevicePathProtocolGuid
+ gEfiGraphicsOutputProtocolGuid
+ gEfiDevicePathToTextProtocolGuid
+ gEmbeddedExternalDeviceProtocolGuid
+
+[Depex]
+ gEfiCpuArchProtocolGuid AND gEfiTimerArchProtocolGuid
diff --git a/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c b/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c
index 76c13d552..b3da7366a 100755
--- a/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c
+++ b/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.c
@@ -13,23 +13,23 @@
**/
#include <Base.h>
-#include <Library/BaseLib.h>
-#include <Library/IoLib.h>
-#include <Library/OmapLib.h>
+#include <Library/BaseLib.h>
+#include <Library/IoLib.h>
+#include <Library/OmapLib.h>
#include <Library/ArmLib.h>
-#include <Library/PcdLib.h>
+#include <Library/PcdLib.h>
-#include <Omap3530/Omap3530.h>
+#include <Omap3530/Omap3530.h>
volatile UINT32 gVector;
-
-// Cached registers
-volatile UINT32 gTISR;
-volatile UINT32 gTCLR;
-volatile UINT32 gTLDR;
-volatile UINT32 gTCRR;
-volatile UINT32 gTIER;
+
+// Cached registers
+volatile UINT32 gTISR;
+volatile UINT32 gTCLR;
+volatile UINT32 gTLDR;
+volatile UINT32 gTCRR;
+volatile UINT32 gTIER;
VOID
EnableInterruptSource (
@@ -80,15 +80,15 @@ DebugAgentTimerIntialize (
UINT32 TimerNumber;
TimerNumber = PcdGet32(PcdOmap35xxDebugAgentTimer);
- gVector = InterruptVectorForTimer (TimerNumber);
+ gVector = InterruptVectorForTimer (TimerNumber);
- // Set up the timer registers
- TimerBaseAddress = TimerBase (TimerNumber);
- gTISR = TimerBaseAddress + GPTIMER_TISR;
- gTCLR = TimerBaseAddress + GPTIMER_TCLR;
- gTLDR = TimerBaseAddress + GPTIMER_TLDR;
- gTCRR = TimerBaseAddress + GPTIMER_TCRR;
- gTIER = TimerBaseAddress + GPTIMER_TIER;
+ // Set up the timer registers
+ TimerBaseAddress = TimerBase (TimerNumber);
+ gTISR = TimerBaseAddress + GPTIMER_TISR;
+ gTCLR = TimerBaseAddress + GPTIMER_TCLR;
+ gTLDR = TimerBaseAddress + GPTIMER_TLDR;
+ gTCRR = TimerBaseAddress + GPTIMER_TCRR;
+ gTIER = TimerBaseAddress + GPTIMER_TIER;
if ((TimerNumber < 2) || (TimerNumber > 9)) {
// This code assumes one the General Purpose timers is used
@@ -113,31 +113,31 @@ DebugAgentTimerSetPeriod (
IN UINT32 TimerPeriodMilliseconds
)
{
- UINT64 TimerCount;
- INT32 LoadValue;
-
- if (TimerPeriodMilliseconds == 0) {
- // Turn off GPTIMER3
- MmioWrite32 (gTCLR, TCLR_ST_OFF);
-
- DisableInterruptSource ();
- } else {
- // Calculate required timer count
- TimerCount = DivU64x32(TimerPeriodMilliseconds * 1000000, PcdGet32(PcdDebugAgentTimerFreqNanoSeconds));
-
- // Set GPTIMER5 Load register
- LoadValue = (INT32) -TimerCount;
- MmioWrite32 (gTLDR, LoadValue);
- MmioWrite32 (gTCRR, LoadValue);
-
- // Enable Overflow interrupt
- MmioWrite32 (gTIER, TIER_TCAR_IT_DISABLE | TIER_OVF_IT_ENABLE | TIER_MAT_IT_DISABLE);
-
- // Turn on GPTIMER3, it will reload at overflow
- MmioWrite32 (gTCLR, TCLR_AR_AUTORELOAD | TCLR_ST_ON);
-
- EnableInterruptSource ();
- }
+ UINT64 TimerCount;
+ INT32 LoadValue;
+
+ if (TimerPeriodMilliseconds == 0) {
+ // Turn off GPTIMER3
+ MmioWrite32 (gTCLR, TCLR_ST_OFF);
+
+ DisableInterruptSource ();
+ } else {
+ // Calculate required timer count
+ TimerCount = DivU64x32(TimerPeriodMilliseconds * 1000000, PcdGet32(PcdDebugAgentTimerFreqNanoSeconds));
+
+ // Set GPTIMER5 Load register
+ LoadValue = (INT32) -TimerCount;
+ MmioWrite32 (gTLDR, LoadValue);
+ MmioWrite32 (gTCRR, LoadValue);
+
+ // Enable Overflow interrupt
+ MmioWrite32 (gTIER, TIER_TCAR_IT_DISABLE | TIER_OVF_IT_ENABLE | TIER_MAT_IT_DISABLE);
+
+ // Turn on GPTIMER3, it will reload at overflow
+ MmioWrite32 (gTCLR, TCLR_AR_AUTORELOAD | TCLR_ST_ON);
+
+ EnableInterruptSource ();
+ }
}
@@ -152,10 +152,10 @@ DebugAgentTimerEndOfInterrupt (
VOID
)
{
- // Clear all timer interrupts
- MmioWrite32 (gTISR, TISR_CLEAR_ALL);
-
- // Poll interrupt status bits to ensure clearing
+ // Clear all timer interrupts
+ MmioWrite32 (gTISR, TISR_CLEAR_ALL);
+
+ // Poll interrupt status bits to ensure clearing
while ((MmioRead32 (gTISR) & TISR_ALL_INTERRUPT_MASK) != TISR_NO_INTERRUPTS_PENDING);
MmioWrite32 (INTCPS_CONTROL, INTCPS_CONTROL_NEWFIQAGR);
@@ -163,4 +163,4 @@ DebugAgentTimerEndOfInterrupt (
}
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.inf b/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.inf
index e1685b58a..551aee538 100755
--- a/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.inf
+++ b/Omap35xxPkg/Library/DebugAgentTimerLib/DebugAgentTimerLib.inf
@@ -31,9 +31,9 @@
[Packages]
MdePkg/MdePkg.dec
EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
- ArmPkg/ArmPkg.dec
-
+ Omap35xxPkg/Omap35xxPkg.dec
+ ArmPkg/ArmPkg.dec
+
[LibraryClasses]
BaseLib
@@ -44,4 +44,4 @@
[Pcd]
gOmap35xxTokenSpaceGuid.PcdOmap35xxDebugAgentTimer
gOmap35xxTokenSpaceGuid.PcdDebugAgentTimerFreqNanoSeconds
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.c b/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.c
index b306355d5..54247e42e 100644
--- a/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.c
+++ b/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.c
@@ -1,102 +1,102 @@
-/** @file
- Basic serial IO abstaction for GDB
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Uefi.h>
-#include <Library/GdbSerialLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-#include <Library/DebugLib.h>
-#include <Library/OmapLib.h>
-#include <Omap3530/Omap3530.h>
-
-RETURN_STATUS
-EFIAPI
-GdbSerialLibConstructor (
- VOID
- )
-{
- return RETURN_SUCCESS;
-}
-
-RETURN_STATUS
-EFIAPI
-GdbSerialInit (
- IN UINT64 BaudRate,
- IN UINT8 Parity,
- IN UINT8 DataBits,
- IN UINT8 StopBits
- )
-{
- return RETURN_SUCCESS;
-}
-
-BOOLEAN
-EFIAPI
-GdbIsCharAvailable (
- VOID
- )
-{
- UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
-
- if ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_NOT_EMPTY) {
- return TRUE;
- } else {
- return FALSE;
- }
-}
-
-CHAR8
-EFIAPI
-GdbGetChar (
- VOID
- )
-{
- UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
- UINT32 RBR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_RBR_REG;
- CHAR8 Char;
-
- while ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_EMPTY);
- Char = MmioRead8(RBR);
-
- return Char;
-}
-
-VOID
-EFIAPI
-GdbPutChar (
- IN CHAR8 Char
- )
-{
- UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
- UINT32 THR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_THR_REG;
-
- while ((MmioRead8(LSR) & UART_LSR_TX_FIFO_E_MASK) == UART_LSR_TX_FIFO_E_NOT_EMPTY);
- MmioWrite8(THR, Char);
-}
-
-VOID
-GdbPutString (
- IN CHAR8 *String
- )
-{
- while (*String != '\0') {
- GdbPutChar (*String);
- String++;
- }
-}
-
-
-
-
+/** @file
+ Basic serial IO abstaction for GDB
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Uefi.h>
+#include <Library/GdbSerialLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+#include <Library/DebugLib.h>
+#include <Library/OmapLib.h>
+#include <Omap3530/Omap3530.h>
+
+RETURN_STATUS
+EFIAPI
+GdbSerialLibConstructor (
+ VOID
+ )
+{
+ return RETURN_SUCCESS;
+}
+
+RETURN_STATUS
+EFIAPI
+GdbSerialInit (
+ IN UINT64 BaudRate,
+ IN UINT8 Parity,
+ IN UINT8 DataBits,
+ IN UINT8 StopBits
+ )
+{
+ return RETURN_SUCCESS;
+}
+
+BOOLEAN
+EFIAPI
+GdbIsCharAvailable (
+ VOID
+ )
+{
+ UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
+
+ if ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_NOT_EMPTY) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+CHAR8
+EFIAPI
+GdbGetChar (
+ VOID
+ )
+{
+ UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
+ UINT32 RBR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_RBR_REG;
+ CHAR8 Char;
+
+ while ((MmioRead8(LSR) & UART_LSR_RX_FIFO_E_MASK) == UART_LSR_RX_FIFO_E_EMPTY);
+ Char = MmioRead8(RBR);
+
+ return Char;
+}
+
+VOID
+EFIAPI
+GdbPutChar (
+ IN CHAR8 Char
+ )
+{
+ UINT32 LSR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_LSR_REG;
+ UINT32 THR = UartBase(PcdGet32(PcdOmap35xxConsoleUart)) + UART_THR_REG;
+
+ while ((MmioRead8(LSR) & UART_LSR_TX_FIFO_E_MASK) == UART_LSR_TX_FIFO_E_NOT_EMPTY);
+ MmioWrite8(THR, Char);
+}
+
+VOID
+GdbPutString (
+ IN CHAR8 *String
+ )
+{
+ while (*String != '\0') {
+ GdbPutChar (*String);
+ String++;
+ }
+}
+
+
+
+
diff --git a/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.inf b/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.inf
index 7e949c2f9..3ab26bb90 100644
--- a/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.inf
+++ b/Omap35xxPkg/Library/GdbSerialLib/GdbSerialLib.inf
@@ -1,41 +1,41 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = GdbSerialLib
- FILE_GUID = E2423349-EF5D-439B-95F5-8B8D8E3B443F
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = GdbSerialLib
-
- CONSTRUCTOR = GdbSerialLibConstructor
-
-
-[Sources.common]
- GdbSerialLib.c
-
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- DebugLib
- IoLib
- OmapLib
-
-[FixedPcd]
- gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart
-
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = GdbSerialLib
+ FILE_GUID = E2423349-EF5D-439B-95F5-8B8D8E3B443F
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = GdbSerialLib
+
+ CONSTRUCTOR = GdbSerialLibConstructor
+
+
+[Sources.common]
+ GdbSerialLib.c
+
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ DebugLib
+ IoLib
+ OmapLib
+
+[FixedPcd]
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart
+
diff --git a/Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf b/Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
index 4356853bb..d94ddf986 100755
--- a/Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
+++ b/Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
@@ -47,4 +47,4 @@
[Pcd]
[Depex]
- gEfiCpuArchProtocolGuid \ No newline at end of file
+ gEfiCpuArchProtocolGuid \ No newline at end of file
diff --git a/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.c b/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.c
index e1d5c9ca1..0b9c70bc5 100755
--- a/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.c
+++ b/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.c
@@ -1,297 +1,297 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include <Uefi.h>
-
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiRuntimeServicesTableLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-
-#include <Protocol/RealTimeClock.h>
-#include <Protocol/EmbeddedExternalDevice.h>
-
-#include <Omap3530/Omap3530.h>
-#include <TPS65950.h>
-
-
-EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
-INT16 TimeZone = EFI_UNSPECIFIED_TIMEZONE;
-
-/**
- Returns the current time and date information, and the time-keeping capabilities
- of the hardware platform.
-
- @param Time A pointer to storage to receive a snapshot of the current time.
- @param Capabilities An optional pointer to a buffer to receive the real time clock
- device's capabilities.
-
- @retval EFI_SUCCESS The operation completed successfully.
- @retval EFI_INVALID_PARAMETER Time is NULL.
- @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error.
-
-**/
-EFI_STATUS
-EFIAPI
-LibGetTime (
- OUT EFI_TIME *Time,
- OUT EFI_TIME_CAPABILITIES *Capabilities
- )
-{
- EFI_STATUS Status;
- UINT8 Data;
- EFI_TPL OldTpl;
-
- if (Time == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
-
- /* Get time and date */
- ZeroMem(Time, sizeof(EFI_TIME));
-
- // Latch values
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, RTC_CTRL_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Data |= BIT6;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, RTC_CTRL_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- // Read registers
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, YEARS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Time->Year = 2000 + ((Data >> 4) & 0xF) * 10 + (Data & 0xF);
-
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MONTHS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Time->Month = ((Data >> 4) & 0x1) * 10 + (Data & 0xF);
-
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, DAYS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Time->Day = ((Data >> 4) & 0x3) * 10 + (Data & 0xF);
-
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, HOURS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Time->Hour = ((Data >> 4) & 0x3) * 10 + (Data & 0xF);
-
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MINUTES_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Time->Minute = ((Data >> 4) & 0x7) * 10 + (Data & 0xF);
-
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, SECONDS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
- Time->Second = ((Data >> 4) & 0x7) * 10 + (Data & 0xF);
-
- Time->TimeZone = TimeZone;
- // TODO: check what to use here
- Time->Daylight = EFI_TIME_ADJUST_DAYLIGHT;
-
- // Set capabilities
-
- // TODO: Set real capabilities
- if (Capabilities != NULL) {
- Capabilities->Resolution = 1;
- Capabilities->Accuracy = 50000000;
- Capabilities->SetsToZero = FALSE;
- }
-
-EXIT:
- gBS->RestoreTPL(OldTpl);
-
- return (Status == EFI_SUCCESS) ? Status : EFI_DEVICE_ERROR;
-}
-
-/**
- Sets the current local time and date information.
-
- @param Time A pointer to the current time.
-
- @retval EFI_SUCCESS The operation completed successfully.
- @retval EFI_INVALID_PARAMETER A time field is out of range.
- @retval EFI_DEVICE_ERROR The time could not be set due due to hardware error.
-
-**/
-EFI_STATUS
-EFIAPI
-LibSetTime (
- IN EFI_TIME *Time
- )
-{
- EFI_STATUS Status;
- UINT8 Data;
- UINT8 MonthDayCount[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
- EFI_TPL OldTpl;
-
- // Input validation according both to UEFI spec and hardware constraints
- // UEFI spec says valid year range is 1900-9999 but TPS only supports 2000-2099
- if ( (Time == NULL)
- || (Time->Year < 2000 || Time->Year > 2099)
- || (Time->Month < 1 || Time->Month > 12)
- || (Time->Day < 1 || Time->Day > MonthDayCount[Time->Month])
- || (Time->Hour > 23)
- || (Time->Minute > 59)
- || (Time->Second > 59)
- || (Time->Nanosecond > 999999999)
- || ((Time->TimeZone < -1440 || Time->TimeZone > 1440) && Time->TimeZone != 2047)
- ) {
- return EFI_INVALID_PARAMETER;
- }
-
- OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
-
- Data = Time->Year - 2000;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, YEARS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- Data = ((Time->Month / 10) << 4) | (Time->Month % 10);
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MONTHS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- Data = ((Time->Day / 10) << 4) | (Time->Day % 10);
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, DAYS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- Data = ((Time->Hour / 10) << 4) | (Time->Hour % 10);
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, HOURS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- Data = ((Time->Minute / 10) << 4) | (Time->Minute % 10);
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MINUTES_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- Data = ((Time->Second / 10) << 4) | (Time->Second % 10);
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, SECONDS_REG), 1, &Data);
- if (Status != EFI_SUCCESS) goto EXIT;
-
- TimeZone = Time->TimeZone;
-
-EXIT:
- gBS->RestoreTPL(OldTpl);
-
- return (Status == EFI_SUCCESS) ? Status : EFI_DEVICE_ERROR;
-}
-
-/**
- Returns the current wakeup alarm clock setting.
-
- @param Enabled Indicates if the alarm is currently enabled or disabled.
- @param Pending Indicates if the alarm signal is pending and requires acknowledgement.
- @param Time The current alarm setting.
-
- @retval EFI_SUCCESS The alarm settings were returned.
- @retval EFI_INVALID_PARAMETER Any parameter is NULL.
- @retval EFI_DEVICE_ERROR The wakeup time could not be retrieved due to a hardware error.
-
-**/
-EFI_STATUS
-EFIAPI
-LibGetWakeupTime (
- OUT BOOLEAN *Enabled,
- OUT BOOLEAN *Pending,
- OUT EFI_TIME *Time
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- Sets the system wakeup alarm clock time.
-
- @param Enabled Enable or disable the wakeup alarm.
- @param Time If Enable is TRUE, the time to set the wakeup alarm for.
-
- @retval EFI_SUCCESS If Enable is TRUE, then the wakeup alarm was enabled. If
- Enable is FALSE, then the wakeup alarm was disabled.
- @retval EFI_INVALID_PARAMETER A time field is out of range.
- @retval EFI_DEVICE_ERROR The wakeup time could not be set due to a hardware error.
- @retval EFI_UNSUPPORTED A wakeup timer is not supported on this platform.
-
-**/
-EFI_STATUS
-EFIAPI
-LibSetWakeupTime (
- IN BOOLEAN Enabled,
- OUT EFI_TIME *Time
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-/**
- This is the declaration of an EFI image entry point. This can be the entry point to an application
- written to this specification, an EFI boot service driver, or an EFI runtime driver.
-
- @param ImageHandle Handle that identifies the loaded image.
- @param SystemTable System Table for this image.
-
- @retval EFI_SUCCESS The operation completed successfully.
-
-**/
-EFI_STATUS
-EFIAPI
-LibRtcInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE Handle;
- UINT8 Data;
- EFI_TPL OldTpl;
-
- Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
- ASSERT_EFI_ERROR(Status);
-
- OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
- Data = 1;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, RTC_CTRL_REG), 1, &Data);
- ASSERT_EFI_ERROR(Status);
- gBS->RestoreTPL(OldTpl);
-
- // Setup the setters and getters
- gRT->GetTime = LibGetTime;
- gRT->SetTime = LibSetTime;
- gRT->GetWakeupTime = LibGetWakeupTime;
- gRT->SetWakeupTime = LibSetWakeupTime;
-
- // Install the protocol
- Handle = NULL;
- Status = gBS->InstallMultipleProtocolInterfaces (
- &Handle,
- &gEfiRealTimeClockArchProtocolGuid, NULL,
- NULL
- );
-
- return Status;
-}
-
-/**
- Fixup internal data so that EFI can be call in virtual mode.
- Call the passed in Child Notify event and convert any pointers in
- lib to virtual mode.
-
- @param[in] Event The Event that is being processed
- @param[in] Context Event Context
-**/
-VOID
-EFIAPI
-LibRtcVirtualNotifyEvent (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- return;
-}
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include <Uefi.h>
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+
+#include <Protocol/RealTimeClock.h>
+#include <Protocol/EmbeddedExternalDevice.h>
+
+#include <Omap3530/Omap3530.h>
+#include <TPS65950.h>
+
+
+EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
+INT16 TimeZone = EFI_UNSPECIFIED_TIMEZONE;
+
+/**
+ Returns the current time and date information, and the time-keeping capabilities
+ of the hardware platform.
+
+ @param Time A pointer to storage to receive a snapshot of the current time.
+ @param Capabilities An optional pointer to a buffer to receive the real time clock
+ device's capabilities.
+
+ @retval EFI_SUCCESS The operation completed successfully.
+ @retval EFI_INVALID_PARAMETER Time is NULL.
+ @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error.
+
+**/
+EFI_STATUS
+EFIAPI
+LibGetTime (
+ OUT EFI_TIME *Time,
+ OUT EFI_TIME_CAPABILITIES *Capabilities
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data;
+ EFI_TPL OldTpl;
+
+ if (Time == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
+
+ /* Get time and date */
+ ZeroMem(Time, sizeof(EFI_TIME));
+
+ // Latch values
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, RTC_CTRL_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Data |= BIT6;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, RTC_CTRL_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ // Read registers
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, YEARS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Time->Year = 2000 + ((Data >> 4) & 0xF) * 10 + (Data & 0xF);
+
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MONTHS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Time->Month = ((Data >> 4) & 0x1) * 10 + (Data & 0xF);
+
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, DAYS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Time->Day = ((Data >> 4) & 0x3) * 10 + (Data & 0xF);
+
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, HOURS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Time->Hour = ((Data >> 4) & 0x3) * 10 + (Data & 0xF);
+
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MINUTES_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Time->Minute = ((Data >> 4) & 0x7) * 10 + (Data & 0xF);
+
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, SECONDS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+ Time->Second = ((Data >> 4) & 0x7) * 10 + (Data & 0xF);
+
+ Time->TimeZone = TimeZone;
+ // TODO: check what to use here
+ Time->Daylight = EFI_TIME_ADJUST_DAYLIGHT;
+
+ // Set capabilities
+
+ // TODO: Set real capabilities
+ if (Capabilities != NULL) {
+ Capabilities->Resolution = 1;
+ Capabilities->Accuracy = 50000000;
+ Capabilities->SetsToZero = FALSE;
+ }
+
+EXIT:
+ gBS->RestoreTPL(OldTpl);
+
+ return (Status == EFI_SUCCESS) ? Status : EFI_DEVICE_ERROR;
+}
+
+/**
+ Sets the current local time and date information.
+
+ @param Time A pointer to the current time.
+
+ @retval EFI_SUCCESS The operation completed successfully.
+ @retval EFI_INVALID_PARAMETER A time field is out of range.
+ @retval EFI_DEVICE_ERROR The time could not be set due due to hardware error.
+
+**/
+EFI_STATUS
+EFIAPI
+LibSetTime (
+ IN EFI_TIME *Time
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data;
+ UINT8 MonthDayCount[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+ EFI_TPL OldTpl;
+
+ // Input validation according both to UEFI spec and hardware constraints
+ // UEFI spec says valid year range is 1900-9999 but TPS only supports 2000-2099
+ if ( (Time == NULL)
+ || (Time->Year < 2000 || Time->Year > 2099)
+ || (Time->Month < 1 || Time->Month > 12)
+ || (Time->Day < 1 || Time->Day > MonthDayCount[Time->Month])
+ || (Time->Hour > 23)
+ || (Time->Minute > 59)
+ || (Time->Second > 59)
+ || (Time->Nanosecond > 999999999)
+ || ((Time->TimeZone < -1440 || Time->TimeZone > 1440) && Time->TimeZone != 2047)
+ ) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
+
+ Data = Time->Year - 2000;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, YEARS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ Data = ((Time->Month / 10) << 4) | (Time->Month % 10);
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MONTHS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ Data = ((Time->Day / 10) << 4) | (Time->Day % 10);
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, DAYS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ Data = ((Time->Hour / 10) << 4) | (Time->Hour % 10);
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, HOURS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ Data = ((Time->Minute / 10) << 4) | (Time->Minute % 10);
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, MINUTES_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ Data = ((Time->Second / 10) << 4) | (Time->Second % 10);
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, SECONDS_REG), 1, &Data);
+ if (Status != EFI_SUCCESS) goto EXIT;
+
+ TimeZone = Time->TimeZone;
+
+EXIT:
+ gBS->RestoreTPL(OldTpl);
+
+ return (Status == EFI_SUCCESS) ? Status : EFI_DEVICE_ERROR;
+}
+
+/**
+ Returns the current wakeup alarm clock setting.
+
+ @param Enabled Indicates if the alarm is currently enabled or disabled.
+ @param Pending Indicates if the alarm signal is pending and requires acknowledgement.
+ @param Time The current alarm setting.
+
+ @retval EFI_SUCCESS The alarm settings were returned.
+ @retval EFI_INVALID_PARAMETER Any parameter is NULL.
+ @retval EFI_DEVICE_ERROR The wakeup time could not be retrieved due to a hardware error.
+
+**/
+EFI_STATUS
+EFIAPI
+LibGetWakeupTime (
+ OUT BOOLEAN *Enabled,
+ OUT BOOLEAN *Pending,
+ OUT EFI_TIME *Time
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Sets the system wakeup alarm clock time.
+
+ @param Enabled Enable or disable the wakeup alarm.
+ @param Time If Enable is TRUE, the time to set the wakeup alarm for.
+
+ @retval EFI_SUCCESS If Enable is TRUE, then the wakeup alarm was enabled. If
+ Enable is FALSE, then the wakeup alarm was disabled.
+ @retval EFI_INVALID_PARAMETER A time field is out of range.
+ @retval EFI_DEVICE_ERROR The wakeup time could not be set due to a hardware error.
+ @retval EFI_UNSUPPORTED A wakeup timer is not supported on this platform.
+
+**/
+EFI_STATUS
+EFIAPI
+LibSetWakeupTime (
+ IN BOOLEAN Enabled,
+ OUT EFI_TIME *Time
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ This is the declaration of an EFI image entry point. This can be the entry point to an application
+ written to this specification, an EFI boot service driver, or an EFI runtime driver.
+
+ @param ImageHandle Handle that identifies the loaded image.
+ @param SystemTable System Table for this image.
+
+ @retval EFI_SUCCESS The operation completed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+LibRtcInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+ UINT8 Data;
+ EFI_TPL OldTpl;
+
+ Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
+ ASSERT_EFI_ERROR(Status);
+
+ OldTpl = gBS->RaiseTPL(TPL_NOTIFY);
+ Data = 1;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, RTC_CTRL_REG), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+ gBS->RestoreTPL(OldTpl);
+
+ // Setup the setters and getters
+ gRT->GetTime = LibGetTime;
+ gRT->SetTime = LibSetTime;
+ gRT->GetWakeupTime = LibGetWakeupTime;
+ gRT->SetWakeupTime = LibSetWakeupTime;
+
+ // Install the protocol
+ Handle = NULL;
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Handle,
+ &gEfiRealTimeClockArchProtocolGuid, NULL,
+ NULL
+ );
+
+ return Status;
+}
+
+/**
+ Fixup internal data so that EFI can be call in virtual mode.
+ Call the passed in Child Notify event and convert any pointers in
+ lib to virtual mode.
+
+ @param[in] Event The Event that is being processed
+ @param[in] Context Event Context
+**/
+VOID
+EFIAPI
+LibRtcVirtualNotifyEvent (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ return;
+}
diff --git a/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.inf b/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.inf
index c62257df7..7c4911c38 100755
--- a/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.inf
+++ b/Omap35xxPkg/Library/RealTimeClockLib/RealTimeClockLib.inf
@@ -1,38 +1,38 @@
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = RealTimeClockLib
- FILE_GUID = EC1713DB-7DB5-4c99-8FE2-6F52F95A1132
- MODULE_TYPE = BASE
- VERSION_STRING = 1.0
- LIBRARY_CLASS = RealTimeClockLib
-
-[Sources.common]
- RealTimeClockLib.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- IoLib
- UefiLib
- DebugLib
- PcdLib
-
-[Protocols]
- gEmbeddedExternalDeviceProtocolGuid
-
-[depex]
- gEmbeddedExternalDeviceProtocolGuid
+# Copyright (c) 2011, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = RealTimeClockLib
+ FILE_GUID = EC1713DB-7DB5-4c99-8FE2-6F52F95A1132
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = RealTimeClockLib
+
+[Sources.common]
+ RealTimeClockLib.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ IoLib
+ UefiLib
+ DebugLib
+ PcdLib
+
+[Protocols]
+ gEmbeddedExternalDeviceProtocolGuid
+
+[depex]
+ gEmbeddedExternalDeviceProtocolGuid
diff --git a/Omap35xxPkg/MMCHSDxe/MMCHS.c b/Omap35xxPkg/MMCHSDxe/MMCHS.c
index 786bc8827..7d4e22f52 100644
--- a/Omap35xxPkg/MMCHSDxe/MMCHS.c
+++ b/Omap35xxPkg/MMCHSDxe/MMCHS.c
@@ -1,1495 +1,1495 @@
-/** @file
- MMC/SD Card driver for OMAP 35xx (SDIO not supported)
-
- This driver always produces a BlockIo protocol but it starts off with no Media
- present. A TimerCallBack detects when media is inserted or removed and after
- a media change event a call to BlockIo ReadBlocks/WriteBlocks will cause the
- media to be detected (or removed) and the BlockIo Media structure will get
- updated. No MMC/SD Card harward registers are updated until the first BlockIo
- ReadBlocks/WriteBlocks after media has been insterted (booting with a card
- plugged in counts as an insertion event).
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "MMCHS.h"
-
-EFI_BLOCK_IO_MEDIA gMMCHSMedia = {
- SIGNATURE_32('s','d','i','o'), // MediaId
- TRUE, // RemovableMedia
- FALSE, // MediaPresent
- FALSE, // LogicalPartition
- FALSE, // ReadOnly
- FALSE, // WriteCaching
- 512, // BlockSize
- 4, // IoAlign
- 0, // Pad
- 0 // LastBlock
-};
-
-typedef struct {
- VENDOR_DEVICE_PATH Mmc;
- EFI_DEVICE_PATH End;
-} MMCHS_DEVICE_PATH;
-
-MMCHS_DEVICE_PATH gMmcHsDevicePath = {
- {
- HARDWARE_DEVICE_PATH,
- HW_VENDOR_DP,
- (UINT8)(sizeof(VENDOR_DEVICE_PATH)),
- (UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8),
- 0xb615f1f5, 0x5088, 0x43cd, 0x80, 0x9c, 0xa1, 0x6e, 0x52, 0x48, 0x7d, 0x00
- },
- {
- END_DEVICE_PATH_TYPE,
- END_ENTIRE_DEVICE_PATH_SUBTYPE,
- sizeof (EFI_DEVICE_PATH_PROTOCOL),
- 0
- }
-};
-
-CARD_INFO gCardInfo;
-EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
-EFI_EVENT gTimerEvent;
-BOOLEAN gMediaChange = FALSE;
-
-//
-// Internal Functions
-//
-
-
-VOID
-ParseCardCIDData (
- UINT32 Response0,
- UINT32 Response1,
- UINT32 Response2,
- UINT32 Response3
- )
-{
- gCardInfo.CIDData.MDT = ((Response0 >> 8) & 0xFFF);
- gCardInfo.CIDData.PSN = (((Response0 >> 24) & 0xFF) | ((Response1 & 0xFFFFFF) << 8));
- gCardInfo.CIDData.PRV = ((Response1 >> 24) & 0xFF);
- gCardInfo.CIDData.PNM[4] = ((Response2) & 0xFF);
- gCardInfo.CIDData.PNM[3] = ((Response2 >> 8) & 0xFF);
- gCardInfo.CIDData.PNM[2] = ((Response2 >> 16) & 0xFF);
- gCardInfo.CIDData.PNM[1] = ((Response2 >> 24) & 0xFF);
- gCardInfo.CIDData.PNM[0] = ((Response3) & 0xFF);
- gCardInfo.CIDData.OID = ((Response3 >> 8) & 0xFFFF);
- gCardInfo.CIDData.MID = ((Response3 >> 24) & 0xFF);
-}
-
-
-VOID
-UpdateMMCHSClkFrequency (
- UINTN NewCLKD
- )
-{
- //Set Clock enable to 0x0 to not provide the clock to the card
- MmioAnd32 (MMCHS_SYSCTL, ~CEN);
-
- //Set new clock frequency.
- MmioAndThenOr32 (MMCHS_SYSCTL, ~CLKD_MASK, NewCLKD << 6);
-
- //Poll till Internal Clock Stable
- while ((MmioRead32 (MMCHS_SYSCTL) & ICS_MASK) != ICS);
-
- //Set Clock enable to 0x1 to provide the clock to the card
- MmioOr32 (MMCHS_SYSCTL, CEN);
-}
-
-
-EFI_STATUS
-SendCmd (
- UINTN Cmd,
- UINTN CmdInterruptEnableVal,
- UINTN CmdArgument
- )
-{
- UINTN MmcStatus;
- UINTN RetryCount = 0;
-
- //Check if command line is in use or not. Poll till command line is available.
- while ((MmioRead32 (MMCHS_PSTATE) & DATI_MASK) == DATI_NOT_ALLOWED);
-
- //Provide the block size.
- MmioWrite32 (MMCHS_BLK, BLEN_512BYTES);
-
- //Setting Data timeout counter value to max value.
- MmioAndThenOr32 (MMCHS_SYSCTL, ~DTO_MASK, DTO_VAL);
-
- //Clear Status register.
- MmioWrite32 (MMCHS_STAT, 0xFFFFFFFF);
-
- //Set command argument register
- MmioWrite32 (MMCHS_ARG, CmdArgument);
-
- //Enable interrupt enable events to occur
- MmioWrite32 (MMCHS_IE, CmdInterruptEnableVal);
-
- //Send a command
- MmioWrite32 (MMCHS_CMD, Cmd);
-
- //Check for the command status.
- while (RetryCount < MAX_RETRY_COUNT) {
- do {
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while (MmcStatus == 0);
-
- //Read status of command response
- if ((MmcStatus & ERRI) != 0) {
-
- //Perform soft-reset for mmci_cmd line.
- MmioOr32 (MMCHS_SYSCTL, SRC);
- while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
-
- DEBUG ((EFI_D_INFO, "MmcStatus: %x\n", MmcStatus));
- return EFI_DEVICE_ERROR;
- }
-
- //Check if command is completed.
- if ((MmcStatus & CC) == CC) {
- MmioWrite32 (MMCHS_STAT, CC);
- break;
- }
-
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-
-VOID
-GetBlockInformation (
- UINTN *BlockSize,
- UINTN *NumBlocks
- )
-{
- CSD_SDV2 *CsdSDV2Data;
- UINTN CardSize;
-
- if (gCardInfo.CardType == SD_CARD_2_HIGH) {
- CsdSDV2Data = (CSD_SDV2 *)&gCardInfo.CSDData;
-
- //Populate BlockSize.
- *BlockSize = (0x1UL << CsdSDV2Data->READ_BL_LEN);
-
- //Calculate Total number of blocks.
- CardSize = CsdSDV2Data->C_SIZELow16 | (CsdSDV2Data->C_SIZEHigh6 << 2);
- *NumBlocks = ((CardSize + 1) * 1024);
- } else {
- //Populate BlockSize.
- *BlockSize = (0x1UL << gCardInfo.CSDData.READ_BL_LEN);
-
- //Calculate Total number of blocks.
- CardSize = gCardInfo.CSDData.C_SIZELow2 | (gCardInfo.CSDData.C_SIZEHigh10 << 2);
- *NumBlocks = (CardSize + 1) * (1 << (gCardInfo.CSDData.C_SIZE_MULT + 2));
- }
-
- //For >=2G card, BlockSize may be 1K, but the transfer size is 512 bytes.
- if (*BlockSize > 512) {
- *NumBlocks = MultU64x32(*NumBlocks, *BlockSize/2);
- *BlockSize = 512;
- }
-
- DEBUG ((EFI_D_INFO, "Card type: %x, BlockSize: %x, NumBlocks: %x\n", gCardInfo.CardType, *BlockSize, *NumBlocks));
-}
-
-
-VOID
-CalculateCardCLKD (
- UINTN *ClockFrequencySelect
- )
-{
- UINT8 MaxDataTransferRate;
- UINTN TransferRateValue = 0;
- UINTN TimeValue = 0 ;
- UINTN Frequency = 0;
-
- MaxDataTransferRate = gCardInfo.CSDData.TRAN_SPEED;
-
- // For SD Cards we would need to send CMD6 to set
- // speeds abouve 25MHz. High Speed mode 50 MHz and up
-
- //Calculate Transfer rate unit (Bits 2:0 of TRAN_SPEED)
- switch (MaxDataTransferRate & 0x7) {
- case 0:
- TransferRateValue = 100 * 1000;
- break;
-
- case 1:
- TransferRateValue = 1 * 1000 * 1000;
- break;
-
- case 2:
- TransferRateValue = 10 * 1000 * 1000;
- break;
-
- case 3:
- TransferRateValue = 100 * 1000 * 1000;
- break;
-
- default:
- DEBUG((EFI_D_ERROR, "Invalid parameter.\n"));
- ASSERT(FALSE);
- }
-
- //Calculate Time value (Bits 6:3 of TRAN_SPEED)
- switch ((MaxDataTransferRate >> 3) & 0xF) {
- case 1:
- TimeValue = 10;
- break;
-
- case 2:
- TimeValue = 12;
- break;
-
- case 3:
- TimeValue = 13;
- break;
-
- case 4:
- TimeValue = 15;
- break;
-
- case 5:
- TimeValue = 20;
- break;
-
- case 6:
- TimeValue = 25;
- break;
-
- case 7:
- TimeValue = 30;
- break;
-
- case 8:
- TimeValue = 35;
- break;
-
- case 9:
- TimeValue = 40;
- break;
-
- case 10:
- TimeValue = 45;
- break;
-
- case 11:
- TimeValue = 50;
- break;
-
- case 12:
- TimeValue = 55;
- break;
-
- case 13:
- TimeValue = 60;
- break;
-
- case 14:
- TimeValue = 70;
- break;
-
- case 15:
- TimeValue = 80;
- break;
-
- default:
- DEBUG((EFI_D_ERROR, "Invalid parameter.\n"));
- ASSERT(FALSE);
- }
-
- Frequency = TransferRateValue * TimeValue/10;
-
- //Calculate Clock divider value to program in MMCHS_SYSCTL[CLKD] field.
- *ClockFrequencySelect = ((MMC_REFERENCE_CLK/Frequency) + 1);
-
- DEBUG ((EFI_D_INFO, "MaxDataTransferRate: 0x%x, Frequency: %d KHz, ClockFrequencySelect: %x\n", MaxDataTransferRate, Frequency/1000, *ClockFrequencySelect));
-}
-
-
-VOID
-GetCardConfigurationData (
- VOID
- )
-{
- UINTN BlockSize;
- UINTN NumBlocks;
- UINTN ClockFrequencySelect;
-
- //Calculate BlockSize and Total number of blocks in the detected card.
- GetBlockInformation(&BlockSize, &NumBlocks);
- gCardInfo.BlockSize = BlockSize;
- gCardInfo.NumBlocks = NumBlocks;
-
- //Calculate Card clock divider value.
- CalculateCardCLKD(&ClockFrequencySelect);
- gCardInfo.ClockFrequencySelect = ClockFrequencySelect;
-}
-
-
-EFI_STATUS
-InitializeMMCHS (
- VOID
- )
-{
- UINT8 Data = 0;
- EFI_STATUS Status;
-
- //Select Device group to belong to P1 device group in Power IC.
- Data = DEV_GRP_P1;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEV_GRP), 1, &Data);
- ASSERT_EFI_ERROR(Status);
-
- //Configure voltage regulator for MMC1 in Power IC to output 3.0 voltage.
- Data = VSEL_3_00V;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEDICATED_REG), 1, &Data);
- ASSERT_EFI_ERROR(Status);
-
- //After ramping up voltage, set VDDS stable bit to indicate that voltage level is stable.
- MmioOr32 (CONTROL_PBIAS_LITE, (PBIASLITEVMODE0 | PBIASLITEPWRDNZ0 | PBIASSPEEDCTRL0 | PBIASLITEVMODE1 | PBIASLITEWRDNZ1));
-
- // Enable WP GPIO
- MmioAndThenOr32 (GPIO1_BASE + GPIO_OE, ~BIT23, BIT23);
-
- // Enable Card Detect
- Data = CARD_DETECT_ENABLE;
- gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, TPS65950_GPIO_CTRL), 1, &Data);
-
-
- return Status;
-}
-
-
-EFI_STATUS
-PerformCardIdenfication (
- VOID
- )
-{
- EFI_STATUS Status;
- UINTN CmdArgument = 0;
- UINTN Response = 0;
- UINTN RetryCount = 0;
- BOOLEAN SDCmd8Supported = FALSE;
-
- //Enable interrupts.
- MmioWrite32 (MMCHS_IE, (BADA_EN | CERR_EN | DEB_EN | DCRC_EN | DTO_EN | CIE_EN |
- CEB_EN | CCRC_EN | CTO_EN | BRR_EN | BWR_EN | TC_EN | CC_EN));
-
- //Controller INIT procedure start.
- MmioOr32 (MMCHS_CON, INIT);
- MmioWrite32 (MMCHS_CMD, 0x00000000);
- while (!(MmioRead32 (MMCHS_STAT) & CC));
-
- //Wait for 1 ms
- gBS->Stall(1000);
-
- //Set CC bit to 0x1 to clear the flag
- MmioOr32 (MMCHS_STAT, CC);
-
- //Retry INIT procedure.
- MmioWrite32 (MMCHS_CMD, 0x00000000);
- while (!(MmioRead32 (MMCHS_STAT) & CC));
-
- //End initialization sequence
- MmioAnd32 (MMCHS_CON, ~INIT);
-
- MmioOr32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_ON));
-
- //Change clock frequency to 400KHz to fit protocol
- UpdateMMCHSClkFrequency(CLKD_400KHZ);
-
- MmioOr32 (MMCHS_CON, OD);
-
- //Send CMD0 command.
- Status = SendCmd (CMD0, CMD0_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "Cmd0 fails.\n"));
- return Status;
- }
-
- DEBUG ((EFI_D_INFO, "CMD0 response: %x\n", MmioRead32 (MMCHS_RSP10)));
-
- //Send CMD5 command.
- Status = SendCmd (CMD5, CMD5_INT_EN, CmdArgument);
- if (Status == EFI_SUCCESS) {
- DEBUG ((EFI_D_ERROR, "CMD5 Success. SDIO card. Follow SDIO card specification.\n"));
- DEBUG ((EFI_D_INFO, "CMD5 response: %x\n", MmioRead32 (MMCHS_RSP10)));
- //NOTE: Returning unsupported error for now. Need to implement SDIO specification.
- return EFI_UNSUPPORTED;
- } else {
- DEBUG ((EFI_D_INFO, "CMD5 fails. Not an SDIO card.\n"));
- }
-
- MmioOr32 (MMCHS_SYSCTL, SRC);
- gBS->Stall(1000);
- while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
-
- //Send CMD8 command. (New v2.00 command for Voltage check)
- //Only 2.7V - 3.6V is supported for SD2.0, only SD 2.0 card can pass.
- //MMC & SD1.1 card will fail this command.
- CmdArgument = CMD8_ARG;
- Status = SendCmd (CMD8, CMD8_INT_EN, CmdArgument);
- if (Status == EFI_SUCCESS) {
- Response = MmioRead32 (MMCHS_RSP10);
- DEBUG ((EFI_D_INFO, "CMD8 success. CMD8 response: %x\n", Response));
- if (Response != CmdArgument) {
- return EFI_DEVICE_ERROR;
- }
- DEBUG ((EFI_D_INFO, "Card is SD2.0\n"));
- SDCmd8Supported = TRUE; //Supports high capacity.
- } else {
- DEBUG ((EFI_D_INFO, "CMD8 fails. Not an SD2.0 card.\n"));
- }
-
- MmioOr32 (MMCHS_SYSCTL, SRC);
- gBS->Stall(1000);
- while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
-
- //Poll till card is busy
- while (RetryCount < MAX_RETRY_COUNT) {
- //Send CMD55 command.
- CmdArgument = 0;
- Status = SendCmd (CMD55, CMD55_INT_EN, CmdArgument);
- if (Status == EFI_SUCCESS) {
- DEBUG ((EFI_D_INFO, "CMD55 success. CMD55 response: %x\n", MmioRead32 (MMCHS_RSP10)));
- gCardInfo.CardType = SD_CARD;
- } else {
- DEBUG ((EFI_D_INFO, "CMD55 fails.\n"));
- gCardInfo.CardType = MMC_CARD;
- }
-
- //Send appropriate command for the card type which got detected.
- if (gCardInfo.CardType == SD_CARD) {
- CmdArgument = ((UINTN *) &(gCardInfo.OCRData))[0];
-
- //Set HCS bit.
- if (SDCmd8Supported) {
- CmdArgument |= HCS;
- }
-
- Status = SendCmd (ACMD41, ACMD41_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_INFO, "ACMD41 fails.\n"));
- return Status;
- }
- ((UINT32 *) &(gCardInfo.OCRData))[0] = MmioRead32 (MMCHS_RSP10);
- DEBUG ((EFI_D_INFO, "SD card detected. ACMD41 OCR: %x\n", ((UINT32 *) &(gCardInfo.OCRData))[0]));
- } else if (gCardInfo.CardType == MMC_CARD) {
- CmdArgument = 0;
- Status = SendCmd (CMD1, CMD1_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_INFO, "CMD1 fails.\n"));
- return Status;
- }
- Response = MmioRead32 (MMCHS_RSP10);
- DEBUG ((EFI_D_INFO, "MMC card detected.. CMD1 response: %x\n", Response));
-
- //NOTE: For now, I am skipping this since I only have an SD card.
- //Compare card OCR and host OCR (Section 22.6.1.3.2.4)
- return EFI_UNSUPPORTED; //For now, MMC is not supported.
- }
-
- //Poll the card until it is out of its power-up sequence.
- if (gCardInfo.OCRData.Busy == 1) {
-
- if (SDCmd8Supported) {
- gCardInfo.CardType = SD_CARD_2;
- }
-
- //Card is ready. Check CCS (Card capacity status) bit (bit#30).
- //SD 2.0 standard card will response with CCS 0, SD high capacity card will respond with CCS 1.
- if (gCardInfo.OCRData.AccessMode & BIT1) {
- gCardInfo.CardType = SD_CARD_2_HIGH;
- DEBUG ((EFI_D_INFO, "High capacity card.\n"));
- } else {
- DEBUG ((EFI_D_INFO, "Standard capacity card.\n"));
- }
-
- break;
- }
-
- gBS->Stall(1000);
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- DEBUG ((EFI_D_ERROR, "Timeout error. RetryCount: %d\n", RetryCount));
- return EFI_TIMEOUT;
- }
-
- //Read CID data.
- CmdArgument = 0;
- Status = SendCmd (CMD2, CMD2_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "CMD2 fails. Status: %x\n", Status));
- return Status;
- }
-
- DEBUG ((EFI_D_INFO, "CMD2 response: %x %x %x %x\n", MmioRead32 (MMCHS_RSP10), MmioRead32 (MMCHS_RSP32), MmioRead32 (MMCHS_RSP54), MmioRead32 (MMCHS_RSP76)));
-
- //Parse CID register data.
- ParseCardCIDData(MmioRead32 (MMCHS_RSP10), MmioRead32 (MMCHS_RSP32), MmioRead32 (MMCHS_RSP54), MmioRead32 (MMCHS_RSP76));
-
- //Read RCA
- CmdArgument = 0;
- Status = SendCmd (CMD3, CMD3_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "CMD3 fails. Status: %x\n", Status));
- return Status;
- }
-
- //Set RCA for the detected card. RCA is CMD3 response.
- gCardInfo.RCA = (MmioRead32 (MMCHS_RSP10) >> 16);
- DEBUG ((EFI_D_INFO, "CMD3 response: RCA %x\n", gCardInfo.RCA));
-
- //MMC Bus setting change after card identification.
- MmioAnd32 (MMCHS_CON, ~OD);
- MmioOr32 (MMCHS_HCTL, SDVS_3_0_V);
- UpdateMMCHSClkFrequency(CLKD_400KHZ); //Set the clock frequency to 400KHz.
-
- return EFI_SUCCESS;
-}
-
-
-EFI_STATUS
-GetCardSpecificData (
- VOID
- )
-{
- EFI_STATUS Status;
- UINTN CmdArgument;
-
- //Send CMD9 to retrieve CSD.
- CmdArgument = gCardInfo.RCA << 16;
- Status = SendCmd (CMD9, CMD9_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "CMD9 fails. Status: %x\n", Status));
- return Status;
- }
-
- //Populate 128-bit CSD register data.
- ((UINT32 *)&(gCardInfo.CSDData))[0] = MmioRead32 (MMCHS_RSP10);
- ((UINT32 *)&(gCardInfo.CSDData))[1] = MmioRead32 (MMCHS_RSP32);
- ((UINT32 *)&(gCardInfo.CSDData))[2] = MmioRead32 (MMCHS_RSP54);
- ((UINT32 *)&(gCardInfo.CSDData))[3] = MmioRead32 (MMCHS_RSP76);
-
- DEBUG ((EFI_D_INFO, "CMD9 response: %x %x %x %x\n", MmioRead32 (MMCHS_RSP10), MmioRead32 (MMCHS_RSP32), MmioRead32 (MMCHS_RSP54), MmioRead32 (MMCHS_RSP76)));
-
- //Calculate total number of blocks and max. data transfer rate supported by the detected card.
- GetCardConfigurationData();
-
- return Status;
-}
-
-
-EFI_STATUS
-PerformCardConfiguration (
- VOID
- )
-{
- UINTN CmdArgument = 0;
- EFI_STATUS Status;
-
- //Send CMD7
- CmdArgument = gCardInfo.RCA << 16;
- Status = SendCmd (CMD7, CMD7_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "CMD7 fails. Status: %x\n", Status));
- return Status;
- }
-
- if ((gCardInfo.CardType != UNKNOWN_CARD) && (gCardInfo.CardType != MMC_CARD)) {
- // We could read SCR register, but SD Card Phys spec stats any SD Card shall
- // set SCR.SD_BUS_WIDTHS to support 4-bit mode, so why bother?
-
- // Send ACMD6 (application specific commands must be prefixed with CMD55)
- Status = SendCmd (CMD55, CMD55_INT_EN, CmdArgument);
- if (!EFI_ERROR (Status)) {
- // set device into 4-bit data bus mode
- Status = SendCmd (ACMD6, ACMD6_INT_EN, 0x2);
- if (!EFI_ERROR (Status)) {
- // Set host controler into 4-bit mode
- MmioOr32 (MMCHS_HCTL, DTW_4_BIT);
- DEBUG ((EFI_D_INFO, "SD Memory Card set to 4-bit mode\n"));
- }
- }
- }
-
- //Send CMD16 to set the block length
- CmdArgument = gCardInfo.BlockSize;
- Status = SendCmd (CMD16, CMD16_INT_EN, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "CMD16 fails. Status: %x\n", Status));
- return Status;
- }
-
- //Change MMCHS clock frequency to what detected card can support.
- UpdateMMCHSClkFrequency(gCardInfo.ClockFrequencySelect);
-
- return EFI_SUCCESS;
-}
-
-
-EFI_STATUS
-ReadBlockData (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- OUT VOID *Buffer
- )
-{
- UINTN MmcStatus;
- UINTN *DataBuffer = Buffer;
- UINTN DataSize = This->Media->BlockSize/4;
- UINTN Count;
- UINTN RetryCount = 0;
-
- //Check controller status to make sure there is no error.
- while (RetryCount < MAX_RETRY_COUNT) {
- do {
- //Read Status.
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while(MmcStatus == 0);
-
- //Check if Buffer read ready (BRR) bit is set?
- if (MmcStatus & BRR) {
-
- //Clear BRR bit
- MmioOr32 (MMCHS_STAT, BRR);
-
- //Read block worth of data.
- for (Count = 0; Count < DataSize; Count++) {
- *DataBuffer++ = MmioRead32 (MMCHS_DATA);
- }
- break;
- }
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-
-EFI_STATUS
-WriteBlockData (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- OUT VOID *Buffer
- )
-{
- UINTN MmcStatus;
- UINTN *DataBuffer = Buffer;
- UINTN DataSize = This->Media->BlockSize/4;
- UINTN Count;
- UINTN RetryCount = 0;
-
- //Check controller status to make sure there is no error.
- while (RetryCount < MAX_RETRY_COUNT) {
- do {
- //Read Status.
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while(MmcStatus == 0);
-
- //Check if Buffer write ready (BWR) bit is set?
- if (MmcStatus & BWR) {
-
- //Clear BWR bit
- MmioOr32 (MMCHS_STAT, BWR);
-
- //Write block worth of data.
- for (Count = 0; Count < DataSize; Count++) {
- MmioWrite32 (MMCHS_DATA, *DataBuffer++);
- }
-
- break;
- }
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-DmaBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINTN Lba,
- IN OUT VOID *Buffer,
- IN UINTN BlockCount,
- IN OPERATION_TYPE OperationType
- )
-{
- EFI_STATUS Status;
- UINTN DmaSize = 0;
- UINTN Cmd = 0;
- UINTN CmdInterruptEnable;
- UINTN CmdArgument;
- VOID *BufferMap;
- EFI_PHYSICAL_ADDRESS BufferAddress;
- OMAP_DMA4 Dma4;
- DMA_MAP_OPERATION DmaOperation;
- EFI_STATUS MmcStatus;
- UINTN RetryCount = 0;
-
-CpuDeadLoop ();
- // Map passed in buffer for DMA xfer
- DmaSize = BlockCount * This->Media->BlockSize;
- Status = DmaMap (DmaOperation, Buffer, &DmaSize, &BufferAddress, &BufferMap);
- if (EFI_ERROR (Status)) {
- return Status;
- }
-
- ZeroMem (&DmaOperation, sizeof (DMA_MAP_OPERATION));
-
-
- Dma4.DataType = 2; // DMA4_CSDPi[1:0] 32-bit elements from MMCHS_DATA
-
- Dma4.SourceEndiansim = 0; // DMA4_CSDPi[21]
-
- Dma4.DestinationEndianism = 0; // DMA4_CSDPi[19]
-
- Dma4.SourcePacked = 0; // DMA4_CSDPi[6]
-
- Dma4.DestinationPacked = 0; // DMA4_CSDPi[13]
-
- Dma4.NumberOfElementPerFrame = This->Media->BlockSize/4; // DMA4_CENi (TRM 4K is optimum value)
-
- Dma4.NumberOfFramePerTransferBlock = BlockCount; // DMA4_CFNi
-
- Dma4.ReadPriority = 0; // DMA4_CCRi[6] Low priority read
-
- Dma4.WritePriority = 0; // DMA4_CCRi[23] Prefetech disabled
-
-
- //Populate the command information based on the operation type.
- if (OperationType == READ) {
- Cmd = CMD18; //Multiple block read
- CmdInterruptEnable = CMD18_INT_EN;
- DmaOperation = MapOperationBusMasterCommonBuffer;
-
- Dma4.ReadPortAccessType =0 ; // DMA4_CSDPi[8:7] Can not burst MMCHS_DATA reg
-
- Dma4.WritePortAccessType = 3; // DMA4_CSDPi[15:14] Memory burst 16x32
-
- Dma4.WriteMode = 1; // DMA4_CSDPi[17:16] Write posted
-
-
-
- Dma4.SourceStartAddress = MMCHS_DATA; // DMA4_CSSAi
-
- Dma4.DestinationStartAddress = (UINT32)BufferAddress; // DMA4_CDSAi
-
- Dma4.SourceElementIndex = 1; // DMA4_CSEi
-
- Dma4.SourceFrameIndex = 0x200; // DMA4_CSFi
-
- Dma4.DestinationElementIndex = 1; // DMA4_CDEi
-
- Dma4.DestinationFrameIndex = 0; // DMA4_CDFi
-
-
-
- Dma4.ReadPortAccessMode = 0; // DMA4_CCRi[13:12] Always read MMCHS_DATA
-
- Dma4.WritePortAccessMode = 1; // DMA4_CCRi[15:14] Post increment memory address
-
- Dma4.ReadRequestNumber = 0x1e; // DMA4_CCRi[4:0] Syncro with MMCA_DMA_RX (61)
-
- Dma4.WriteRequestNumber = 1; // DMA4_CCRi[20:19] Syncro upper 0x3e == 62 (one based)
-
- } else if (OperationType == WRITE) {
- Cmd = CMD25; //Multiple block write
- CmdInterruptEnable = CMD25_INT_EN;
- DmaOperation = MapOperationBusMasterRead;
-
- Dma4.ReadPortAccessType = 3; // DMA4_CSDPi[8:7] Memory burst 16x32
-
- Dma4.WritePortAccessType = 0; // DMA4_CSDPi[15:14] Can not burst MMCHS_DATA reg
-
- Dma4.WriteMode = 1; // DMA4_CSDPi[17:16] Write posted ???
-
-
-
- Dma4.SourceStartAddress = (UINT32)BufferAddress; // DMA4_CSSAi
-
- Dma4.DestinationStartAddress = MMCHS_DATA; // DMA4_CDSAi
-
- Dma4.SourceElementIndex = 1; // DMA4_CSEi
-
- Dma4.SourceFrameIndex = 0x200; // DMA4_CSFi
-
- Dma4.DestinationElementIndex = 1; // DMA4_CDEi
-
- Dma4.DestinationFrameIndex = 0; // DMA4_CDFi
-
-
-
- Dma4.ReadPortAccessMode = 1; // DMA4_CCRi[13:12] Post increment memory address
-
- Dma4.WritePortAccessMode = 0; // DMA4_CCRi[15:14] Always write MMCHS_DATA
-
- Dma4.ReadRequestNumber = 0x1d; // DMA4_CCRi[4:0] Syncro with MMCA_DMA_TX (60)
-
- Dma4.WriteRequestNumber = 1; // DMA4_CCRi[20:19] Syncro upper 0x3d == 61 (one based)
-
- } else {
- return EFI_INVALID_PARAMETER;
- }
-
-
- EnableDmaChannel (2, &Dma4);
-
-
- //Set command argument based on the card access mode (Byte mode or Block mode)
- if (gCardInfo.OCRData.AccessMode & BIT1) {
- CmdArgument = Lba;
- } else {
- CmdArgument = Lba * This->Media->BlockSize;
- }
-
- //Send Command.
- Status = SendCmd (Cmd, CmdInterruptEnable, CmdArgument);
- if (EFI_ERROR (Status)) {
- DEBUG ((EFI_D_ERROR, "CMD fails. Status: %x\n", Status));
- return Status;
- }
-
- //Check for the Transfer completion.
- while (RetryCount < MAX_RETRY_COUNT) {
- //Read Status
- do {
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while (MmcStatus == 0);
-
- //Check if Transfer complete (TC) bit is set?
- if (MmcStatus & TC) {
- break;
- } else {
- DEBUG ((EFI_D_ERROR, "MmcStatus for TC: %x\n", MmcStatus));
- //Check if DEB, DCRC or DTO interrupt occured.
- if ((MmcStatus & DEB) | (MmcStatus & DCRC) | (MmcStatus & DTO)) {
- //There was an error during the data transfer.
-
- //Set SRD bit to 1 and wait until it return to 0x0.
- MmioOr32 (MMCHS_SYSCTL, SRD);
- while((MmioRead32 (MMCHS_SYSCTL) & SRD) != 0x0);
-
- DisableDmaChannel (2, DMA4_CSR_BLOCK, DMA4_CSR_ERR);
- DmaUnmap (BufferMap);
- return EFI_DEVICE_ERROR;
- }
- }
- RetryCount++;
- }
-
- DisableDmaChannel (2, DMA4_CSR_BLOCK, DMA4_CSR_ERR);
- Status = DmaUnmap (BufferMap);
-
- if (RetryCount == MAX_RETRY_COUNT) {
- DEBUG ((EFI_D_ERROR, "TransferBlockData timed out.\n"));
- return EFI_TIMEOUT;
- }
-
- return Status;
-}
-
-
-EFI_STATUS
-TransferBlock (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINTN Lba,
- IN OUT VOID *Buffer,
- IN OPERATION_TYPE OperationType
- )
-{
- EFI_STATUS Status;
- UINTN MmcStatus;
- UINTN RetryCount = 0;
- UINTN Cmd = 0;
- UINTN CmdInterruptEnable = 0;
- UINTN CmdArgument = 0;
-
-
- //Populate the command information based on the operation type.
- if (OperationType == READ) {
- Cmd = CMD17; //Single block read
- CmdInterruptEnable = CMD18_INT_EN;
- } else if (OperationType == WRITE) {
- Cmd = CMD24; //Single block write
- CmdInterruptEnable = CMD24_INT_EN;
- }
-
- //Set command argument based on the card access mode (Byte mode or Block mode)
- if (gCardInfo.OCRData.AccessMode & BIT1) {
- CmdArgument = Lba;
- } else {
- CmdArgument = Lba * This->Media->BlockSize;
- }
-
- //Send Command.
- Status = SendCmd (Cmd, CmdInterruptEnable, CmdArgument);
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "CMD fails. Status: %x\n", Status));
- return Status;
- }
-
- //Read or Write data.
- if (OperationType == READ) {
- Status = ReadBlockData (This, Buffer);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "ReadBlockData fails.\n"));
- return Status;
- }
- } else if (OperationType == WRITE) {
- Status = WriteBlockData (This, Buffer);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "WriteBlockData fails.\n"));
- return Status;
- }
- }
-
- //Check for the Transfer completion.
- while (RetryCount < MAX_RETRY_COUNT) {
- //Read Status
- do {
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while (MmcStatus == 0);
-
- //Check if Transfer complete (TC) bit is set?
- if (MmcStatus & TC) {
- break;
- } else {
- DEBUG ((EFI_D_ERROR, "MmcStatus for TC: %x\n", MmcStatus));
- //Check if DEB, DCRC or DTO interrupt occured.
- if ((MmcStatus & DEB) | (MmcStatus & DCRC) | (MmcStatus & DTO)) {
- //There was an error during the data transfer.
-
- //Set SRD bit to 1 and wait until it return to 0x0.
- MmioOr32 (MMCHS_SYSCTL, SRD);
- while((MmioRead32 (MMCHS_SYSCTL) & SRD) != 0x0);
-
- return EFI_DEVICE_ERROR;
- }
- }
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- DEBUG ((EFI_D_ERROR, "TransferBlockData timed out.\n"));
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-BOOLEAN
-CardPresent (
- VOID
- )
-{
- EFI_STATUS Status;
- UINT8 Data;
-
- //
- // Card detect is a GPIO0 on the TPS65950
- //
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATAIN1), 1, &Data);
- if (EFI_ERROR (Status)) {
- return FALSE;
- }
-
- if ((Data & CARD_DETECT_BIT) == CARD_DETECT_BIT) {
- // No Card present
- return FALSE;
- } else {
- return TRUE;
- }
-}
-
-EFI_STATUS
-DetectCard (
- VOID
- )
-{
- EFI_STATUS Status;
-
- if (!CardPresent ()) {
- return EFI_NO_MEDIA;
- }
-
- //Initialize MMC host controller clocks.
- Status = InitializeMMCHS ();
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "Initialize MMC host controller fails. Status: %x\n", Status));
- return Status;
- }
-
- //Software reset of the MMCHS host controller.
- MmioWrite32 (MMCHS_SYSCONFIG, SOFTRESET);
- gBS->Stall(1000);
- while ((MmioRead32 (MMCHS_SYSSTATUS) & RESETDONE_MASK) != RESETDONE);
-
- //Soft reset for all.
- MmioWrite32 (MMCHS_SYSCTL, SRA);
- gBS->Stall(1000);
- while ((MmioRead32 (MMCHS_SYSCTL) & SRA) != 0x0);
-
- //Voltage capabilities initialization. Activate VS18 and VS30.
- MmioOr32 (MMCHS_CAPA, (VS30 | VS18));
-
- //Wakeup configuration
- MmioOr32 (MMCHS_SYSCONFIG, ENAWAKEUP);
- MmioOr32 (MMCHS_HCTL, IWE);
-
- //MMCHS Controller default initialization
- MmioOr32 (MMCHS_CON, (OD | DW8_1_4_BIT | CEATA_OFF));
-
- MmioWrite32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_OFF));
-
- //Enable internal clock
- MmioOr32 (MMCHS_SYSCTL, ICE);
-
- //Set the clock frequency to 80KHz.
- UpdateMMCHSClkFrequency (CLKD_80KHZ);
-
- //Enable SD bus power.
- MmioOr32 (MMCHS_HCTL, (SDBP_ON));
-
- //Poll till SD bus power bit is set.
- while ((MmioRead32 (MMCHS_HCTL) & SDBP_MASK) != SDBP_ON);
-
- //Card idenfication
- Status = PerformCardIdenfication ();
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "No MMC/SD card detected.\n"));
- return Status;
- }
-
- //Get CSD (Card specific data) for the detected card.
- Status = GetCardSpecificData();
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- //Configure the card in data transfer mode.
- Status = PerformCardConfiguration();
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- //Patch the Media structure.
- gMMCHSMedia.LastBlock = (gCardInfo.NumBlocks - 1);
- gMMCHSMedia.BlockSize = gCardInfo.BlockSize;
- gMMCHSMedia.ReadOnly = (MmioRead32 (GPIO1_BASE + GPIO_DATAIN) & BIT23) == BIT23;
- gMMCHSMedia.MediaPresent = TRUE;
- gMMCHSMedia.MediaId++;
-
- DEBUG ((EFI_D_INFO, "SD Card Media Change on Handle 0x%08x\n", gImageHandle));
-
- return Status;
-}
-
-#define MAX_MMCHS_TRANSFER_SIZE 0x4000
-
-EFI_STATUS
-SdReadWrite (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINTN Lba,
- OUT VOID *Buffer,
- IN UINTN BufferSize,
- IN OPERATION_TYPE OperationType
- )
-{
- EFI_STATUS Status = EFI_SUCCESS;
- UINTN RetryCount = 0;
- UINTN BlockCount;
- UINTN BytesToBeTranferedThisPass = 0;
- UINTN BytesRemainingToBeTransfered;
- EFI_TPL OldTpl;
-
- BOOLEAN Update;
-
-
-
- Update = FALSE;
-
- if (gMediaChange) {
- Update = TRUE;
- Status = DetectCard ();
- if (EFI_ERROR (Status)) {
- // We detected a removal
- gMMCHSMedia.MediaPresent = FALSE;
- gMMCHSMedia.LastBlock = 0;
- gMMCHSMedia.BlockSize = 512; // Should be zero but there is a bug in DiskIo
- gMMCHSMedia.ReadOnly = FALSE;
- }
- gMediaChange = FALSE;
- } else if (!gMMCHSMedia.MediaPresent) {
- Status = EFI_NO_MEDIA;
- goto Done;
- }
-
- if (Update) {
- DEBUG ((EFI_D_INFO, "SD Card ReinstallProtocolInterface ()\n"));
- gBS->ReinstallProtocolInterface (
- gImageHandle,
- &gEfiBlockIoProtocolGuid,
- &gBlockIo,
- &gBlockIo
- );
- return EFI_MEDIA_CHANGED;
- }
-
- if (EFI_ERROR (Status)) {
- goto Done;
- }
-
- if (Buffer == NULL) {
- Status = EFI_INVALID_PARAMETER;
- goto Done;
- }
-
- if (Lba > This->Media->LastBlock) {
- Status = EFI_INVALID_PARAMETER;
- goto Done;
- }
-
- if ((BufferSize % This->Media->BlockSize) != 0) {
- Status = EFI_BAD_BUFFER_SIZE;
- goto Done;
- }
-
- //Check if the data lines are not in use.
- while ((RetryCount++ < MAX_RETRY_COUNT) && ((MmioRead32 (MMCHS_PSTATE) & DATI_MASK) != DATI_ALLOWED));
- if (RetryCount == MAX_RETRY_COUNT) {
- Status = EFI_TIMEOUT;
- goto Done;
- }
-
- OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
-
- BytesRemainingToBeTransfered = BufferSize;
- while (BytesRemainingToBeTransfered > 0) {
-
- if (gMediaChange) {
- Status = EFI_NO_MEDIA;
- DEBUG ((EFI_D_INFO, "SdReadWrite() EFI_NO_MEDIA due to gMediaChange\n"));
- goto DoneRestoreTPL;
- }
-
- // Turn OFF DMA path until it is debugged
- // BytesToBeTranferedThisPass = (BytesToBeTranferedThisPass >= MAX_MMCHS_TRANSFER_SIZE) ? MAX_MMCHS_TRANSFER_SIZE : BytesRemainingToBeTransfered;
- BytesToBeTranferedThisPass = This->Media->BlockSize;
-
- BlockCount = BytesToBeTranferedThisPass/This->Media->BlockSize;
-
- if (BlockCount > 1) {
- Status = DmaBlocks (This, Lba, Buffer, BlockCount, OperationType);
- } else {
- //Transfer a block worth of data.
- Status = TransferBlock (This, Lba, Buffer, OperationType);
- }
-
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "TransferBlockData fails. %x\n", Status));
- goto DoneRestoreTPL;
- }
-
- BytesRemainingToBeTransfered -= BytesToBeTranferedThisPass;
- Lba += BlockCount;
- Buffer = (UINT8 *)Buffer + This->Media->BlockSize;
- }
-
-DoneRestoreTPL:
-
- gBS->RestoreTPL (OldTpl);
-
-Done:
-
- return Status;
-
-}
-
-
-/**
-
- Reset the Block Device.
-
-
-
- @param This Indicates a pointer to the calling context.
-
- @param ExtendedVerification Driver may perform diagnostics on reset.
-
-
-
- @retval EFI_SUCCESS The device was reset.
-
- @retval EFI_DEVICE_ERROR The device is not functioning properly and could
-
- not be reset.
-
-
-
-**/
-EFI_STATUS
-EFIAPI
-MMCHSReset (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN BOOLEAN ExtendedVerification
- )
-{
- return EFI_SUCCESS;
-}
-
-
-/**
-
- Read BufferSize bytes from Lba into Buffer.
-
-
-
- @param This Indicates a pointer to the calling context.
-
- @param MediaId Id of the media, changes every time the media is replaced.
-
- @param Lba The starting Logical Block Address to read from
-
- @param BufferSize Size of Buffer, must be a multiple of device block size.
-
- @param Buffer A pointer to the destination buffer for the data. The caller is
-
- responsible for either having implicit or explicit ownership of the buffer.
-
-
-
- @retval EFI_SUCCESS The data was read correctly from the device.
-
- @retval EFI_DEVICE_ERROR The device reported an error while performing the read.
-
- @retval EFI_NO_MEDIA There is no media in the device.
-
- @retval EFI_MEDIA_CHANGED The MediaId does not matched the current device.
-
- @retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
-
- @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
-
- or the buffer is not on proper alignment.
-
-EFI_STATUS
-
-**/
-EFI_STATUS
-EFIAPI
-MMCHSReadBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSize,
- OUT VOID *Buffer
- )
-{
- EFI_STATUS Status;
-
- //Perform Read operation.
- Status = SdReadWrite (This, (UINTN)Lba, Buffer, BufferSize, READ);
-
- return Status;
-
-}
-
-
-/**
-
- Write BufferSize bytes from Lba into Buffer.
-
-
-
- @param This Indicates a pointer to the calling context.
-
- @param MediaId The media ID that the write request is for.
-
- @param Lba The starting logical block address to be written. The caller is
-
- responsible for writing to only legitimate locations.
-
- @param BufferSize Size of Buffer, must be a multiple of device block size.
-
- @param Buffer A pointer to the source buffer for the data.
-
-
-
- @retval EFI_SUCCESS The data was written correctly to the device.
-
- @retval EFI_WRITE_PROTECTED The device can not be written to.
-
- @retval EFI_DEVICE_ERROR The device reported an error while performing the write.
-
- @retval EFI_NO_MEDIA There is no media in the device.
-
- @retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
-
- @retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
-
- @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
-
- or the buffer is not on proper alignment.
-
-
-
-**/
-EFI_STATUS
-EFIAPI
-MMCHSWriteBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This,
- IN UINT32 MediaId,
- IN EFI_LBA Lba,
- IN UINTN BufferSize,
- IN VOID *Buffer
- )
-{
- EFI_STATUS Status;
-
- //Perform write operation.
- Status = SdReadWrite (This, (UINTN)Lba, Buffer, BufferSize, WRITE);
-
-
- return Status;
-
-}
-
-
-/**
-
- Flush the Block Device.
-
-
-
- @param This Indicates a pointer to the calling context.
-
-
-
- @retval EFI_SUCCESS All outstanding data was written to the device
-
- @retval EFI_DEVICE_ERROR The device reported an error while writting back the data
-
- @retval EFI_NO_MEDIA There is no media in the device.
-
-
-
-**/
-EFI_STATUS
-EFIAPI
-MMCHSFlushBlocks (
- IN EFI_BLOCK_IO_PROTOCOL *This
- )
-{
- return EFI_SUCCESS;
-}
-
-
-EFI_BLOCK_IO_PROTOCOL gBlockIo = {
- EFI_BLOCK_IO_INTERFACE_REVISION, // Revision
- &gMMCHSMedia, // *Media
- MMCHSReset, // Reset
- MMCHSReadBlocks, // ReadBlocks
- MMCHSWriteBlocks, // WriteBlocks
- MMCHSFlushBlocks // FlushBlocks
-};
-
-
-/**
-
- Timer callback to convert card present hardware into a boolean that indicates
-
- a media change event has happened. If you just check the GPIO you could see
-
- card 1 and then check again after card 1 was removed and card 2 was inserted
-
- and you would still see media present. Thus you need the timer tick to catch
-
- the toggle event.
-
-
-
- @param Event Event whose notification function is being invoked.
-
- @param Context The pointer to the notification function's context,
-
- which is implementation-dependent. Not used.
-
-
-
-**/
-VOID
-EFIAPI
-TimerCallback (
- IN EFI_EVENT Event,
- IN VOID *Context
- )
-{
- BOOLEAN Present;
-
- Present = CardPresent ();
- if (gMMCHSMedia.MediaPresent) {
- if (!Present && !gMediaChange) {
- gMediaChange = TRUE;
- }
- } else {
- if (Present && !gMediaChange) {
- gMediaChange = TRUE;
- }
- }
-}
-
-
-EFI_STATUS
-EFIAPI
-MMCHSInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
-
- Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
- ASSERT_EFI_ERROR(Status);
-
- ZeroMem (&gCardInfo, sizeof (CARD_INFO));
-
- Status = gBS->CreateEvent (EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_CALLBACK, TimerCallback, NULL, &gTimerEvent);
- ASSERT_EFI_ERROR (Status);
-
- Status = gBS->SetTimer (gTimerEvent, TimerPeriodic, FixedPcdGet32 (PcdMmchsTimerFreq100NanoSeconds));
- ASSERT_EFI_ERROR (Status);
-
- //Publish BlockIO.
- Status = gBS->InstallMultipleProtocolInterfaces (
- &ImageHandle,
- &gEfiBlockIoProtocolGuid, &gBlockIo,
- &gEfiDevicePathProtocolGuid, &gMmcHsDevicePath,
- NULL
- );
- return Status;
-}
+/** @file
+ MMC/SD Card driver for OMAP 35xx (SDIO not supported)
+
+ This driver always produces a BlockIo protocol but it starts off with no Media
+ present. A TimerCallBack detects when media is inserted or removed and after
+ a media change event a call to BlockIo ReadBlocks/WriteBlocks will cause the
+ media to be detected (or removed) and the BlockIo Media structure will get
+ updated. No MMC/SD Card harward registers are updated until the first BlockIo
+ ReadBlocks/WriteBlocks after media has been insterted (booting with a card
+ plugged in counts as an insertion event).
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "MMCHS.h"
+
+EFI_BLOCK_IO_MEDIA gMMCHSMedia = {
+ SIGNATURE_32('s','d','i','o'), // MediaId
+ TRUE, // RemovableMedia
+ FALSE, // MediaPresent
+ FALSE, // LogicalPartition
+ FALSE, // ReadOnly
+ FALSE, // WriteCaching
+ 512, // BlockSize
+ 4, // IoAlign
+ 0, // Pad
+ 0 // LastBlock
+};
+
+typedef struct {
+ VENDOR_DEVICE_PATH Mmc;
+ EFI_DEVICE_PATH End;
+} MMCHS_DEVICE_PATH;
+
+MMCHS_DEVICE_PATH gMmcHsDevicePath = {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ (UINT8)(sizeof(VENDOR_DEVICE_PATH)),
+ (UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8),
+ 0xb615f1f5, 0x5088, 0x43cd, 0x80, 0x9c, 0xa1, 0x6e, 0x52, 0x48, 0x7d, 0x00
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ sizeof (EFI_DEVICE_PATH_PROTOCOL),
+ 0
+ }
+};
+
+CARD_INFO gCardInfo;
+EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
+EFI_EVENT gTimerEvent;
+BOOLEAN gMediaChange = FALSE;
+
+//
+// Internal Functions
+//
+
+
+VOID
+ParseCardCIDData (
+ UINT32 Response0,
+ UINT32 Response1,
+ UINT32 Response2,
+ UINT32 Response3
+ )
+{
+ gCardInfo.CIDData.MDT = ((Response0 >> 8) & 0xFFF);
+ gCardInfo.CIDData.PSN = (((Response0 >> 24) & 0xFF) | ((Response1 & 0xFFFFFF) << 8));
+ gCardInfo.CIDData.PRV = ((Response1 >> 24) & 0xFF);
+ gCardInfo.CIDData.PNM[4] = ((Response2) & 0xFF);
+ gCardInfo.CIDData.PNM[3] = ((Response2 >> 8) & 0xFF);
+ gCardInfo.CIDData.PNM[2] = ((Response2 >> 16) & 0xFF);
+ gCardInfo.CIDData.PNM[1] = ((Response2 >> 24) & 0xFF);
+ gCardInfo.CIDData.PNM[0] = ((Response3) & 0xFF);
+ gCardInfo.CIDData.OID = ((Response3 >> 8) & 0xFFFF);
+ gCardInfo.CIDData.MID = ((Response3 >> 24) & 0xFF);
+}
+
+
+VOID
+UpdateMMCHSClkFrequency (
+ UINTN NewCLKD
+ )
+{
+ //Set Clock enable to 0x0 to not provide the clock to the card
+ MmioAnd32 (MMCHS_SYSCTL, ~CEN);
+
+ //Set new clock frequency.
+ MmioAndThenOr32 (MMCHS_SYSCTL, ~CLKD_MASK, NewCLKD << 6);
+
+ //Poll till Internal Clock Stable
+ while ((MmioRead32 (MMCHS_SYSCTL) & ICS_MASK) != ICS);
+
+ //Set Clock enable to 0x1 to provide the clock to the card
+ MmioOr32 (MMCHS_SYSCTL, CEN);
+}
+
+
+EFI_STATUS
+SendCmd (
+ UINTN Cmd,
+ UINTN CmdInterruptEnableVal,
+ UINTN CmdArgument
+ )
+{
+ UINTN MmcStatus;
+ UINTN RetryCount = 0;
+
+ //Check if command line is in use or not. Poll till command line is available.
+ while ((MmioRead32 (MMCHS_PSTATE) & DATI_MASK) == DATI_NOT_ALLOWED);
+
+ //Provide the block size.
+ MmioWrite32 (MMCHS_BLK, BLEN_512BYTES);
+
+ //Setting Data timeout counter value to max value.
+ MmioAndThenOr32 (MMCHS_SYSCTL, ~DTO_MASK, DTO_VAL);
+
+ //Clear Status register.
+ MmioWrite32 (MMCHS_STAT, 0xFFFFFFFF);
+
+ //Set command argument register
+ MmioWrite32 (MMCHS_ARG, CmdArgument);
+
+ //Enable interrupt enable events to occur
+ MmioWrite32 (MMCHS_IE, CmdInterruptEnableVal);
+
+ //Send a command
+ MmioWrite32 (MMCHS_CMD, Cmd);
+
+ //Check for the command status.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ do {
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while (MmcStatus == 0);
+
+ //Read status of command response
+ if ((MmcStatus & ERRI) != 0) {
+
+ //Perform soft-reset for mmci_cmd line.
+ MmioOr32 (MMCHS_SYSCTL, SRC);
+ while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
+
+ DEBUG ((EFI_D_INFO, "MmcStatus: %x\n", MmcStatus));
+ return EFI_DEVICE_ERROR;
+ }
+
+ //Check if command is completed.
+ if ((MmcStatus & CC) == CC) {
+ MmioWrite32 (MMCHS_STAT, CC);
+ break;
+ }
+
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+VOID
+GetBlockInformation (
+ UINTN *BlockSize,
+ UINTN *NumBlocks
+ )
+{
+ CSD_SDV2 *CsdSDV2Data;
+ UINTN CardSize;
+
+ if (gCardInfo.CardType == SD_CARD_2_HIGH) {
+ CsdSDV2Data = (CSD_SDV2 *)&gCardInfo.CSDData;
+
+ //Populate BlockSize.
+ *BlockSize = (0x1UL << CsdSDV2Data->READ_BL_LEN);
+
+ //Calculate Total number of blocks.
+ CardSize = CsdSDV2Data->C_SIZELow16 | (CsdSDV2Data->C_SIZEHigh6 << 2);
+ *NumBlocks = ((CardSize + 1) * 1024);
+ } else {
+ //Populate BlockSize.
+ *BlockSize = (0x1UL << gCardInfo.CSDData.READ_BL_LEN);
+
+ //Calculate Total number of blocks.
+ CardSize = gCardInfo.CSDData.C_SIZELow2 | (gCardInfo.CSDData.C_SIZEHigh10 << 2);
+ *NumBlocks = (CardSize + 1) * (1 << (gCardInfo.CSDData.C_SIZE_MULT + 2));
+ }
+
+ //For >=2G card, BlockSize may be 1K, but the transfer size is 512 bytes.
+ if (*BlockSize > 512) {
+ *NumBlocks = MultU64x32(*NumBlocks, *BlockSize/2);
+ *BlockSize = 512;
+ }
+
+ DEBUG ((EFI_D_INFO, "Card type: %x, BlockSize: %x, NumBlocks: %x\n", gCardInfo.CardType, *BlockSize, *NumBlocks));
+}
+
+
+VOID
+CalculateCardCLKD (
+ UINTN *ClockFrequencySelect
+ )
+{
+ UINT8 MaxDataTransferRate;
+ UINTN TransferRateValue = 0;
+ UINTN TimeValue = 0 ;
+ UINTN Frequency = 0;
+
+ MaxDataTransferRate = gCardInfo.CSDData.TRAN_SPEED;
+
+ // For SD Cards we would need to send CMD6 to set
+ // speeds abouve 25MHz. High Speed mode 50 MHz and up
+
+ //Calculate Transfer rate unit (Bits 2:0 of TRAN_SPEED)
+ switch (MaxDataTransferRate & 0x7) {
+ case 0:
+ TransferRateValue = 100 * 1000;
+ break;
+
+ case 1:
+ TransferRateValue = 1 * 1000 * 1000;
+ break;
+
+ case 2:
+ TransferRateValue = 10 * 1000 * 1000;
+ break;
+
+ case 3:
+ TransferRateValue = 100 * 1000 * 1000;
+ break;
+
+ default:
+ DEBUG((EFI_D_ERROR, "Invalid parameter.\n"));
+ ASSERT(FALSE);
+ }
+
+ //Calculate Time value (Bits 6:3 of TRAN_SPEED)
+ switch ((MaxDataTransferRate >> 3) & 0xF) {
+ case 1:
+ TimeValue = 10;
+ break;
+
+ case 2:
+ TimeValue = 12;
+ break;
+
+ case 3:
+ TimeValue = 13;
+ break;
+
+ case 4:
+ TimeValue = 15;
+ break;
+
+ case 5:
+ TimeValue = 20;
+ break;
+
+ case 6:
+ TimeValue = 25;
+ break;
+
+ case 7:
+ TimeValue = 30;
+ break;
+
+ case 8:
+ TimeValue = 35;
+ break;
+
+ case 9:
+ TimeValue = 40;
+ break;
+
+ case 10:
+ TimeValue = 45;
+ break;
+
+ case 11:
+ TimeValue = 50;
+ break;
+
+ case 12:
+ TimeValue = 55;
+ break;
+
+ case 13:
+ TimeValue = 60;
+ break;
+
+ case 14:
+ TimeValue = 70;
+ break;
+
+ case 15:
+ TimeValue = 80;
+ break;
+
+ default:
+ DEBUG((EFI_D_ERROR, "Invalid parameter.\n"));
+ ASSERT(FALSE);
+ }
+
+ Frequency = TransferRateValue * TimeValue/10;
+
+ //Calculate Clock divider value to program in MMCHS_SYSCTL[CLKD] field.
+ *ClockFrequencySelect = ((MMC_REFERENCE_CLK/Frequency) + 1);
+
+ DEBUG ((EFI_D_INFO, "MaxDataTransferRate: 0x%x, Frequency: %d KHz, ClockFrequencySelect: %x\n", MaxDataTransferRate, Frequency/1000, *ClockFrequencySelect));
+}
+
+
+VOID
+GetCardConfigurationData (
+ VOID
+ )
+{
+ UINTN BlockSize;
+ UINTN NumBlocks;
+ UINTN ClockFrequencySelect;
+
+ //Calculate BlockSize and Total number of blocks in the detected card.
+ GetBlockInformation(&BlockSize, &NumBlocks);
+ gCardInfo.BlockSize = BlockSize;
+ gCardInfo.NumBlocks = NumBlocks;
+
+ //Calculate Card clock divider value.
+ CalculateCardCLKD(&ClockFrequencySelect);
+ gCardInfo.ClockFrequencySelect = ClockFrequencySelect;
+}
+
+
+EFI_STATUS
+InitializeMMCHS (
+ VOID
+ )
+{
+ UINT8 Data = 0;
+ EFI_STATUS Status;
+
+ //Select Device group to belong to P1 device group in Power IC.
+ Data = DEV_GRP_P1;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEV_GRP), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+
+ //Configure voltage regulator for MMC1 in Power IC to output 3.0 voltage.
+ Data = VSEL_3_00V;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEDICATED_REG), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+
+ //After ramping up voltage, set VDDS stable bit to indicate that voltage level is stable.
+ MmioOr32 (CONTROL_PBIAS_LITE, (PBIASLITEVMODE0 | PBIASLITEPWRDNZ0 | PBIASSPEEDCTRL0 | PBIASLITEVMODE1 | PBIASLITEWRDNZ1));
+
+ // Enable WP GPIO
+ MmioAndThenOr32 (GPIO1_BASE + GPIO_OE, ~BIT23, BIT23);
+
+ // Enable Card Detect
+ Data = CARD_DETECT_ENABLE;
+ gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, TPS65950_GPIO_CTRL), 1, &Data);
+
+
+ return Status;
+}
+
+
+EFI_STATUS
+PerformCardIdenfication (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN CmdArgument = 0;
+ UINTN Response = 0;
+ UINTN RetryCount = 0;
+ BOOLEAN SDCmd8Supported = FALSE;
+
+ //Enable interrupts.
+ MmioWrite32 (MMCHS_IE, (BADA_EN | CERR_EN | DEB_EN | DCRC_EN | DTO_EN | CIE_EN |
+ CEB_EN | CCRC_EN | CTO_EN | BRR_EN | BWR_EN | TC_EN | CC_EN));
+
+ //Controller INIT procedure start.
+ MmioOr32 (MMCHS_CON, INIT);
+ MmioWrite32 (MMCHS_CMD, 0x00000000);
+ while (!(MmioRead32 (MMCHS_STAT) & CC));
+
+ //Wait for 1 ms
+ gBS->Stall(1000);
+
+ //Set CC bit to 0x1 to clear the flag
+ MmioOr32 (MMCHS_STAT, CC);
+
+ //Retry INIT procedure.
+ MmioWrite32 (MMCHS_CMD, 0x00000000);
+ while (!(MmioRead32 (MMCHS_STAT) & CC));
+
+ //End initialization sequence
+ MmioAnd32 (MMCHS_CON, ~INIT);
+
+ MmioOr32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_ON));
+
+ //Change clock frequency to 400KHz to fit protocol
+ UpdateMMCHSClkFrequency(CLKD_400KHZ);
+
+ MmioOr32 (MMCHS_CON, OD);
+
+ //Send CMD0 command.
+ Status = SendCmd (CMD0, CMD0_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "Cmd0 fails.\n"));
+ return Status;
+ }
+
+ DEBUG ((EFI_D_INFO, "CMD0 response: %x\n", MmioRead32 (MMCHS_RSP10)));
+
+ //Send CMD5 command.
+ Status = SendCmd (CMD5, CMD5_INT_EN, CmdArgument);
+ if (Status == EFI_SUCCESS) {
+ DEBUG ((EFI_D_ERROR, "CMD5 Success. SDIO card. Follow SDIO card specification.\n"));
+ DEBUG ((EFI_D_INFO, "CMD5 response: %x\n", MmioRead32 (MMCHS_RSP10)));
+ //NOTE: Returning unsupported error for now. Need to implement SDIO specification.
+ return EFI_UNSUPPORTED;
+ } else {
+ DEBUG ((EFI_D_INFO, "CMD5 fails. Not an SDIO card.\n"));
+ }
+
+ MmioOr32 (MMCHS_SYSCTL, SRC);
+ gBS->Stall(1000);
+ while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
+
+ //Send CMD8 command. (New v2.00 command for Voltage check)
+ //Only 2.7V - 3.6V is supported for SD2.0, only SD 2.0 card can pass.
+ //MMC & SD1.1 card will fail this command.
+ CmdArgument = CMD8_ARG;
+ Status = SendCmd (CMD8, CMD8_INT_EN, CmdArgument);
+ if (Status == EFI_SUCCESS) {
+ Response = MmioRead32 (MMCHS_RSP10);
+ DEBUG ((EFI_D_INFO, "CMD8 success. CMD8 response: %x\n", Response));
+ if (Response != CmdArgument) {
+ return EFI_DEVICE_ERROR;
+ }
+ DEBUG ((EFI_D_INFO, "Card is SD2.0\n"));
+ SDCmd8Supported = TRUE; //Supports high capacity.
+ } else {
+ DEBUG ((EFI_D_INFO, "CMD8 fails. Not an SD2.0 card.\n"));
+ }
+
+ MmioOr32 (MMCHS_SYSCTL, SRC);
+ gBS->Stall(1000);
+ while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
+
+ //Poll till card is busy
+ while (RetryCount < MAX_RETRY_COUNT) {
+ //Send CMD55 command.
+ CmdArgument = 0;
+ Status = SendCmd (CMD55, CMD55_INT_EN, CmdArgument);
+ if (Status == EFI_SUCCESS) {
+ DEBUG ((EFI_D_INFO, "CMD55 success. CMD55 response: %x\n", MmioRead32 (MMCHS_RSP10)));
+ gCardInfo.CardType = SD_CARD;
+ } else {
+ DEBUG ((EFI_D_INFO, "CMD55 fails.\n"));
+ gCardInfo.CardType = MMC_CARD;
+ }
+
+ //Send appropriate command for the card type which got detected.
+ if (gCardInfo.CardType == SD_CARD) {
+ CmdArgument = ((UINTN *) &(gCardInfo.OCRData))[0];
+
+ //Set HCS bit.
+ if (SDCmd8Supported) {
+ CmdArgument |= HCS;
+ }
+
+ Status = SendCmd (ACMD41, ACMD41_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_INFO, "ACMD41 fails.\n"));
+ return Status;
+ }
+ ((UINT32 *) &(gCardInfo.OCRData))[0] = MmioRead32 (MMCHS_RSP10);
+ DEBUG ((EFI_D_INFO, "SD card detected. ACMD41 OCR: %x\n", ((UINT32 *) &(gCardInfo.OCRData))[0]));
+ } else if (gCardInfo.CardType == MMC_CARD) {
+ CmdArgument = 0;
+ Status = SendCmd (CMD1, CMD1_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_INFO, "CMD1 fails.\n"));
+ return Status;
+ }
+ Response = MmioRead32 (MMCHS_RSP10);
+ DEBUG ((EFI_D_INFO, "MMC card detected.. CMD1 response: %x\n", Response));
+
+ //NOTE: For now, I am skipping this since I only have an SD card.
+ //Compare card OCR and host OCR (Section 22.6.1.3.2.4)
+ return EFI_UNSUPPORTED; //For now, MMC is not supported.
+ }
+
+ //Poll the card until it is out of its power-up sequence.
+ if (gCardInfo.OCRData.Busy == 1) {
+
+ if (SDCmd8Supported) {
+ gCardInfo.CardType = SD_CARD_2;
+ }
+
+ //Card is ready. Check CCS (Card capacity status) bit (bit#30).
+ //SD 2.0 standard card will response with CCS 0, SD high capacity card will respond with CCS 1.
+ if (gCardInfo.OCRData.AccessMode & BIT1) {
+ gCardInfo.CardType = SD_CARD_2_HIGH;
+ DEBUG ((EFI_D_INFO, "High capacity card.\n"));
+ } else {
+ DEBUG ((EFI_D_INFO, "Standard capacity card.\n"));
+ }
+
+ break;
+ }
+
+ gBS->Stall(1000);
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ DEBUG ((EFI_D_ERROR, "Timeout error. RetryCount: %d\n", RetryCount));
+ return EFI_TIMEOUT;
+ }
+
+ //Read CID data.
+ CmdArgument = 0;
+ Status = SendCmd (CMD2, CMD2_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD2 fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ DEBUG ((EFI_D_INFO, "CMD2 response: %x %x %x %x\n", MmioRead32 (MMCHS_RSP10), MmioRead32 (MMCHS_RSP32), MmioRead32 (MMCHS_RSP54), MmioRead32 (MMCHS_RSP76)));
+
+ //Parse CID register data.
+ ParseCardCIDData(MmioRead32 (MMCHS_RSP10), MmioRead32 (MMCHS_RSP32), MmioRead32 (MMCHS_RSP54), MmioRead32 (MMCHS_RSP76));
+
+ //Read RCA
+ CmdArgument = 0;
+ Status = SendCmd (CMD3, CMD3_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD3 fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ //Set RCA for the detected card. RCA is CMD3 response.
+ gCardInfo.RCA = (MmioRead32 (MMCHS_RSP10) >> 16);
+ DEBUG ((EFI_D_INFO, "CMD3 response: RCA %x\n", gCardInfo.RCA));
+
+ //MMC Bus setting change after card identification.
+ MmioAnd32 (MMCHS_CON, ~OD);
+ MmioOr32 (MMCHS_HCTL, SDVS_3_0_V);
+ UpdateMMCHSClkFrequency(CLKD_400KHZ); //Set the clock frequency to 400KHz.
+
+ return EFI_SUCCESS;
+}
+
+
+EFI_STATUS
+GetCardSpecificData (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINTN CmdArgument;
+
+ //Send CMD9 to retrieve CSD.
+ CmdArgument = gCardInfo.RCA << 16;
+ Status = SendCmd (CMD9, CMD9_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD9 fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ //Populate 128-bit CSD register data.
+ ((UINT32 *)&(gCardInfo.CSDData))[0] = MmioRead32 (MMCHS_RSP10);
+ ((UINT32 *)&(gCardInfo.CSDData))[1] = MmioRead32 (MMCHS_RSP32);
+ ((UINT32 *)&(gCardInfo.CSDData))[2] = MmioRead32 (MMCHS_RSP54);
+ ((UINT32 *)&(gCardInfo.CSDData))[3] = MmioRead32 (MMCHS_RSP76);
+
+ DEBUG ((EFI_D_INFO, "CMD9 response: %x %x %x %x\n", MmioRead32 (MMCHS_RSP10), MmioRead32 (MMCHS_RSP32), MmioRead32 (MMCHS_RSP54), MmioRead32 (MMCHS_RSP76)));
+
+ //Calculate total number of blocks and max. data transfer rate supported by the detected card.
+ GetCardConfigurationData();
+
+ return Status;
+}
+
+
+EFI_STATUS
+PerformCardConfiguration (
+ VOID
+ )
+{
+ UINTN CmdArgument = 0;
+ EFI_STATUS Status;
+
+ //Send CMD7
+ CmdArgument = gCardInfo.RCA << 16;
+ Status = SendCmd (CMD7, CMD7_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD7 fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ if ((gCardInfo.CardType != UNKNOWN_CARD) && (gCardInfo.CardType != MMC_CARD)) {
+ // We could read SCR register, but SD Card Phys spec stats any SD Card shall
+ // set SCR.SD_BUS_WIDTHS to support 4-bit mode, so why bother?
+
+ // Send ACMD6 (application specific commands must be prefixed with CMD55)
+ Status = SendCmd (CMD55, CMD55_INT_EN, CmdArgument);
+ if (!EFI_ERROR (Status)) {
+ // set device into 4-bit data bus mode
+ Status = SendCmd (ACMD6, ACMD6_INT_EN, 0x2);
+ if (!EFI_ERROR (Status)) {
+ // Set host controler into 4-bit mode
+ MmioOr32 (MMCHS_HCTL, DTW_4_BIT);
+ DEBUG ((EFI_D_INFO, "SD Memory Card set to 4-bit mode\n"));
+ }
+ }
+ }
+
+ //Send CMD16 to set the block length
+ CmdArgument = gCardInfo.BlockSize;
+ Status = SendCmd (CMD16, CMD16_INT_EN, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD16 fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ //Change MMCHS clock frequency to what detected card can support.
+ UpdateMMCHSClkFrequency(gCardInfo.ClockFrequencySelect);
+
+ return EFI_SUCCESS;
+}
+
+
+EFI_STATUS
+ReadBlockData (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ OUT VOID *Buffer
+ )
+{
+ UINTN MmcStatus;
+ UINTN *DataBuffer = Buffer;
+ UINTN DataSize = This->Media->BlockSize/4;
+ UINTN Count;
+ UINTN RetryCount = 0;
+
+ //Check controller status to make sure there is no error.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ do {
+ //Read Status.
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while(MmcStatus == 0);
+
+ //Check if Buffer read ready (BRR) bit is set?
+ if (MmcStatus & BRR) {
+
+ //Clear BRR bit
+ MmioOr32 (MMCHS_STAT, BRR);
+
+ //Read block worth of data.
+ for (Count = 0; Count < DataSize; Count++) {
+ *DataBuffer++ = MmioRead32 (MMCHS_DATA);
+ }
+ break;
+ }
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+
+EFI_STATUS
+WriteBlockData (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ OUT VOID *Buffer
+ )
+{
+ UINTN MmcStatus;
+ UINTN *DataBuffer = Buffer;
+ UINTN DataSize = This->Media->BlockSize/4;
+ UINTN Count;
+ UINTN RetryCount = 0;
+
+ //Check controller status to make sure there is no error.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ do {
+ //Read Status.
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while(MmcStatus == 0);
+
+ //Check if Buffer write ready (BWR) bit is set?
+ if (MmcStatus & BWR) {
+
+ //Clear BWR bit
+ MmioOr32 (MMCHS_STAT, BWR);
+
+ //Write block worth of data.
+ for (Count = 0; Count < DataSize; Count++) {
+ MmioWrite32 (MMCHS_DATA, *DataBuffer++);
+ }
+
+ break;
+ }
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+DmaBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINTN Lba,
+ IN OUT VOID *Buffer,
+ IN UINTN BlockCount,
+ IN OPERATION_TYPE OperationType
+ )
+{
+ EFI_STATUS Status;
+ UINTN DmaSize = 0;
+ UINTN Cmd = 0;
+ UINTN CmdInterruptEnable;
+ UINTN CmdArgument;
+ VOID *BufferMap;
+ EFI_PHYSICAL_ADDRESS BufferAddress;
+ OMAP_DMA4 Dma4;
+ DMA_MAP_OPERATION DmaOperation;
+ EFI_STATUS MmcStatus;
+ UINTN RetryCount = 0;
+
+CpuDeadLoop ();
+ // Map passed in buffer for DMA xfer
+ DmaSize = BlockCount * This->Media->BlockSize;
+ Status = DmaMap (DmaOperation, Buffer, &DmaSize, &BufferAddress, &BufferMap);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ ZeroMem (&DmaOperation, sizeof (DMA_MAP_OPERATION));
+
+
+ Dma4.DataType = 2; // DMA4_CSDPi[1:0] 32-bit elements from MMCHS_DATA
+
+ Dma4.SourceEndiansim = 0; // DMA4_CSDPi[21]
+
+ Dma4.DestinationEndianism = 0; // DMA4_CSDPi[19]
+
+ Dma4.SourcePacked = 0; // DMA4_CSDPi[6]
+
+ Dma4.DestinationPacked = 0; // DMA4_CSDPi[13]
+
+ Dma4.NumberOfElementPerFrame = This->Media->BlockSize/4; // DMA4_CENi (TRM 4K is optimum value)
+
+ Dma4.NumberOfFramePerTransferBlock = BlockCount; // DMA4_CFNi
+
+ Dma4.ReadPriority = 0; // DMA4_CCRi[6] Low priority read
+
+ Dma4.WritePriority = 0; // DMA4_CCRi[23] Prefetech disabled
+
+
+ //Populate the command information based on the operation type.
+ if (OperationType == READ) {
+ Cmd = CMD18; //Multiple block read
+ CmdInterruptEnable = CMD18_INT_EN;
+ DmaOperation = MapOperationBusMasterCommonBuffer;
+
+ Dma4.ReadPortAccessType =0 ; // DMA4_CSDPi[8:7] Can not burst MMCHS_DATA reg
+
+ Dma4.WritePortAccessType = 3; // DMA4_CSDPi[15:14] Memory burst 16x32
+
+ Dma4.WriteMode = 1; // DMA4_CSDPi[17:16] Write posted
+
+
+
+ Dma4.SourceStartAddress = MMCHS_DATA; // DMA4_CSSAi
+
+ Dma4.DestinationStartAddress = (UINT32)BufferAddress; // DMA4_CDSAi
+
+ Dma4.SourceElementIndex = 1; // DMA4_CSEi
+
+ Dma4.SourceFrameIndex = 0x200; // DMA4_CSFi
+
+ Dma4.DestinationElementIndex = 1; // DMA4_CDEi
+
+ Dma4.DestinationFrameIndex = 0; // DMA4_CDFi
+
+
+
+ Dma4.ReadPortAccessMode = 0; // DMA4_CCRi[13:12] Always read MMCHS_DATA
+
+ Dma4.WritePortAccessMode = 1; // DMA4_CCRi[15:14] Post increment memory address
+
+ Dma4.ReadRequestNumber = 0x1e; // DMA4_CCRi[4:0] Syncro with MMCA_DMA_RX (61)
+
+ Dma4.WriteRequestNumber = 1; // DMA4_CCRi[20:19] Syncro upper 0x3e == 62 (one based)
+
+ } else if (OperationType == WRITE) {
+ Cmd = CMD25; //Multiple block write
+ CmdInterruptEnable = CMD25_INT_EN;
+ DmaOperation = MapOperationBusMasterRead;
+
+ Dma4.ReadPortAccessType = 3; // DMA4_CSDPi[8:7] Memory burst 16x32
+
+ Dma4.WritePortAccessType = 0; // DMA4_CSDPi[15:14] Can not burst MMCHS_DATA reg
+
+ Dma4.WriteMode = 1; // DMA4_CSDPi[17:16] Write posted ???
+
+
+
+ Dma4.SourceStartAddress = (UINT32)BufferAddress; // DMA4_CSSAi
+
+ Dma4.DestinationStartAddress = MMCHS_DATA; // DMA4_CDSAi
+
+ Dma4.SourceElementIndex = 1; // DMA4_CSEi
+
+ Dma4.SourceFrameIndex = 0x200; // DMA4_CSFi
+
+ Dma4.DestinationElementIndex = 1; // DMA4_CDEi
+
+ Dma4.DestinationFrameIndex = 0; // DMA4_CDFi
+
+
+
+ Dma4.ReadPortAccessMode = 1; // DMA4_CCRi[13:12] Post increment memory address
+
+ Dma4.WritePortAccessMode = 0; // DMA4_CCRi[15:14] Always write MMCHS_DATA
+
+ Dma4.ReadRequestNumber = 0x1d; // DMA4_CCRi[4:0] Syncro with MMCA_DMA_TX (60)
+
+ Dma4.WriteRequestNumber = 1; // DMA4_CCRi[20:19] Syncro upper 0x3d == 61 (one based)
+
+ } else {
+ return EFI_INVALID_PARAMETER;
+ }
+
+
+ EnableDmaChannel (2, &Dma4);
+
+
+ //Set command argument based on the card access mode (Byte mode or Block mode)
+ if (gCardInfo.OCRData.AccessMode & BIT1) {
+ CmdArgument = Lba;
+ } else {
+ CmdArgument = Lba * This->Media->BlockSize;
+ }
+
+ //Send Command.
+ Status = SendCmd (Cmd, CmdInterruptEnable, CmdArgument);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ //Check for the Transfer completion.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ //Read Status
+ do {
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while (MmcStatus == 0);
+
+ //Check if Transfer complete (TC) bit is set?
+ if (MmcStatus & TC) {
+ break;
+ } else {
+ DEBUG ((EFI_D_ERROR, "MmcStatus for TC: %x\n", MmcStatus));
+ //Check if DEB, DCRC or DTO interrupt occured.
+ if ((MmcStatus & DEB) | (MmcStatus & DCRC) | (MmcStatus & DTO)) {
+ //There was an error during the data transfer.
+
+ //Set SRD bit to 1 and wait until it return to 0x0.
+ MmioOr32 (MMCHS_SYSCTL, SRD);
+ while((MmioRead32 (MMCHS_SYSCTL) & SRD) != 0x0);
+
+ DisableDmaChannel (2, DMA4_CSR_BLOCK, DMA4_CSR_ERR);
+ DmaUnmap (BufferMap);
+ return EFI_DEVICE_ERROR;
+ }
+ }
+ RetryCount++;
+ }
+
+ DisableDmaChannel (2, DMA4_CSR_BLOCK, DMA4_CSR_ERR);
+ Status = DmaUnmap (BufferMap);
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ DEBUG ((EFI_D_ERROR, "TransferBlockData timed out.\n"));
+ return EFI_TIMEOUT;
+ }
+
+ return Status;
+}
+
+
+EFI_STATUS
+TransferBlock (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINTN Lba,
+ IN OUT VOID *Buffer,
+ IN OPERATION_TYPE OperationType
+ )
+{
+ EFI_STATUS Status;
+ UINTN MmcStatus;
+ UINTN RetryCount = 0;
+ UINTN Cmd = 0;
+ UINTN CmdInterruptEnable = 0;
+ UINTN CmdArgument = 0;
+
+
+ //Populate the command information based on the operation type.
+ if (OperationType == READ) {
+ Cmd = CMD17; //Single block read
+ CmdInterruptEnable = CMD18_INT_EN;
+ } else if (OperationType == WRITE) {
+ Cmd = CMD24; //Single block write
+ CmdInterruptEnable = CMD24_INT_EN;
+ }
+
+ //Set command argument based on the card access mode (Byte mode or Block mode)
+ if (gCardInfo.OCRData.AccessMode & BIT1) {
+ CmdArgument = Lba;
+ } else {
+ CmdArgument = Lba * This->Media->BlockSize;
+ }
+
+ //Send Command.
+ Status = SendCmd (Cmd, CmdInterruptEnable, CmdArgument);
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "CMD fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ //Read or Write data.
+ if (OperationType == READ) {
+ Status = ReadBlockData (This, Buffer);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "ReadBlockData fails.\n"));
+ return Status;
+ }
+ } else if (OperationType == WRITE) {
+ Status = WriteBlockData (This, Buffer);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "WriteBlockData fails.\n"));
+ return Status;
+ }
+ }
+
+ //Check for the Transfer completion.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ //Read Status
+ do {
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while (MmcStatus == 0);
+
+ //Check if Transfer complete (TC) bit is set?
+ if (MmcStatus & TC) {
+ break;
+ } else {
+ DEBUG ((EFI_D_ERROR, "MmcStatus for TC: %x\n", MmcStatus));
+ //Check if DEB, DCRC or DTO interrupt occured.
+ if ((MmcStatus & DEB) | (MmcStatus & DCRC) | (MmcStatus & DTO)) {
+ //There was an error during the data transfer.
+
+ //Set SRD bit to 1 and wait until it return to 0x0.
+ MmioOr32 (MMCHS_SYSCTL, SRD);
+ while((MmioRead32 (MMCHS_SYSCTL) & SRD) != 0x0);
+
+ return EFI_DEVICE_ERROR;
+ }
+ }
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ DEBUG ((EFI_D_ERROR, "TransferBlockData timed out.\n"));
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+BOOLEAN
+CardPresent (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data;
+
+ //
+ // Card detect is a GPIO0 on the TPS65950
+ //
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATAIN1), 1, &Data);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ if ((Data & CARD_DETECT_BIT) == CARD_DETECT_BIT) {
+ // No Card present
+ return FALSE;
+ } else {
+ return TRUE;
+ }
+}
+
+EFI_STATUS
+DetectCard (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+
+ if (!CardPresent ()) {
+ return EFI_NO_MEDIA;
+ }
+
+ //Initialize MMC host controller clocks.
+ Status = InitializeMMCHS ();
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "Initialize MMC host controller fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ //Software reset of the MMCHS host controller.
+ MmioWrite32 (MMCHS_SYSCONFIG, SOFTRESET);
+ gBS->Stall(1000);
+ while ((MmioRead32 (MMCHS_SYSSTATUS) & RESETDONE_MASK) != RESETDONE);
+
+ //Soft reset for all.
+ MmioWrite32 (MMCHS_SYSCTL, SRA);
+ gBS->Stall(1000);
+ while ((MmioRead32 (MMCHS_SYSCTL) & SRA) != 0x0);
+
+ //Voltage capabilities initialization. Activate VS18 and VS30.
+ MmioOr32 (MMCHS_CAPA, (VS30 | VS18));
+
+ //Wakeup configuration
+ MmioOr32 (MMCHS_SYSCONFIG, ENAWAKEUP);
+ MmioOr32 (MMCHS_HCTL, IWE);
+
+ //MMCHS Controller default initialization
+ MmioOr32 (MMCHS_CON, (OD | DW8_1_4_BIT | CEATA_OFF));
+
+ MmioWrite32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_OFF));
+
+ //Enable internal clock
+ MmioOr32 (MMCHS_SYSCTL, ICE);
+
+ //Set the clock frequency to 80KHz.
+ UpdateMMCHSClkFrequency (CLKD_80KHZ);
+
+ //Enable SD bus power.
+ MmioOr32 (MMCHS_HCTL, (SDBP_ON));
+
+ //Poll till SD bus power bit is set.
+ while ((MmioRead32 (MMCHS_HCTL) & SDBP_MASK) != SDBP_ON);
+
+ //Card idenfication
+ Status = PerformCardIdenfication ();
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "No MMC/SD card detected.\n"));
+ return Status;
+ }
+
+ //Get CSD (Card specific data) for the detected card.
+ Status = GetCardSpecificData();
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ //Configure the card in data transfer mode.
+ Status = PerformCardConfiguration();
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ //Patch the Media structure.
+ gMMCHSMedia.LastBlock = (gCardInfo.NumBlocks - 1);
+ gMMCHSMedia.BlockSize = gCardInfo.BlockSize;
+ gMMCHSMedia.ReadOnly = (MmioRead32 (GPIO1_BASE + GPIO_DATAIN) & BIT23) == BIT23;
+ gMMCHSMedia.MediaPresent = TRUE;
+ gMMCHSMedia.MediaId++;
+
+ DEBUG ((EFI_D_INFO, "SD Card Media Change on Handle 0x%08x\n", gImageHandle));
+
+ return Status;
+}
+
+#define MAX_MMCHS_TRANSFER_SIZE 0x4000
+
+EFI_STATUS
+SdReadWrite (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINTN Lba,
+ OUT VOID *Buffer,
+ IN UINTN BufferSize,
+ IN OPERATION_TYPE OperationType
+ )
+{
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINTN RetryCount = 0;
+ UINTN BlockCount;
+ UINTN BytesToBeTranferedThisPass = 0;
+ UINTN BytesRemainingToBeTransfered;
+ EFI_TPL OldTpl;
+
+ BOOLEAN Update;
+
+
+
+ Update = FALSE;
+
+ if (gMediaChange) {
+ Update = TRUE;
+ Status = DetectCard ();
+ if (EFI_ERROR (Status)) {
+ // We detected a removal
+ gMMCHSMedia.MediaPresent = FALSE;
+ gMMCHSMedia.LastBlock = 0;
+ gMMCHSMedia.BlockSize = 512; // Should be zero but there is a bug in DiskIo
+ gMMCHSMedia.ReadOnly = FALSE;
+ }
+ gMediaChange = FALSE;
+ } else if (!gMMCHSMedia.MediaPresent) {
+ Status = EFI_NO_MEDIA;
+ goto Done;
+ }
+
+ if (Update) {
+ DEBUG ((EFI_D_INFO, "SD Card ReinstallProtocolInterface ()\n"));
+ gBS->ReinstallProtocolInterface (
+ gImageHandle,
+ &gEfiBlockIoProtocolGuid,
+ &gBlockIo,
+ &gBlockIo
+ );
+ return EFI_MEDIA_CHANGED;
+ }
+
+ if (EFI_ERROR (Status)) {
+ goto Done;
+ }
+
+ if (Buffer == NULL) {
+ Status = EFI_INVALID_PARAMETER;
+ goto Done;
+ }
+
+ if (Lba > This->Media->LastBlock) {
+ Status = EFI_INVALID_PARAMETER;
+ goto Done;
+ }
+
+ if ((BufferSize % This->Media->BlockSize) != 0) {
+ Status = EFI_BAD_BUFFER_SIZE;
+ goto Done;
+ }
+
+ //Check if the data lines are not in use.
+ while ((RetryCount++ < MAX_RETRY_COUNT) && ((MmioRead32 (MMCHS_PSTATE) & DATI_MASK) != DATI_ALLOWED));
+ if (RetryCount == MAX_RETRY_COUNT) {
+ Status = EFI_TIMEOUT;
+ goto Done;
+ }
+
+ OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
+
+ BytesRemainingToBeTransfered = BufferSize;
+ while (BytesRemainingToBeTransfered > 0) {
+
+ if (gMediaChange) {
+ Status = EFI_NO_MEDIA;
+ DEBUG ((EFI_D_INFO, "SdReadWrite() EFI_NO_MEDIA due to gMediaChange\n"));
+ goto DoneRestoreTPL;
+ }
+
+ // Turn OFF DMA path until it is debugged
+ // BytesToBeTranferedThisPass = (BytesToBeTranferedThisPass >= MAX_MMCHS_TRANSFER_SIZE) ? MAX_MMCHS_TRANSFER_SIZE : BytesRemainingToBeTransfered;
+ BytesToBeTranferedThisPass = This->Media->BlockSize;
+
+ BlockCount = BytesToBeTranferedThisPass/This->Media->BlockSize;
+
+ if (BlockCount > 1) {
+ Status = DmaBlocks (This, Lba, Buffer, BlockCount, OperationType);
+ } else {
+ //Transfer a block worth of data.
+ Status = TransferBlock (This, Lba, Buffer, OperationType);
+ }
+
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "TransferBlockData fails. %x\n", Status));
+ goto DoneRestoreTPL;
+ }
+
+ BytesRemainingToBeTransfered -= BytesToBeTranferedThisPass;
+ Lba += BlockCount;
+ Buffer = (UINT8 *)Buffer + This->Media->BlockSize;
+ }
+
+DoneRestoreTPL:
+
+ gBS->RestoreTPL (OldTpl);
+
+Done:
+
+ return Status;
+
+}
+
+
+/**
+
+ Reset the Block Device.
+
+
+
+ @param This Indicates a pointer to the calling context.
+
+ @param ExtendedVerification Driver may perform diagnostics on reset.
+
+
+
+ @retval EFI_SUCCESS The device was reset.
+
+ @retval EFI_DEVICE_ERROR The device is not functioning properly and could
+
+ not be reset.
+
+
+
+**/
+EFI_STATUS
+EFIAPI
+MMCHSReset (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN BOOLEAN ExtendedVerification
+ )
+{
+ return EFI_SUCCESS;
+}
+
+
+/**
+
+ Read BufferSize bytes from Lba into Buffer.
+
+
+
+ @param This Indicates a pointer to the calling context.
+
+ @param MediaId Id of the media, changes every time the media is replaced.
+
+ @param Lba The starting Logical Block Address to read from
+
+ @param BufferSize Size of Buffer, must be a multiple of device block size.
+
+ @param Buffer A pointer to the destination buffer for the data. The caller is
+
+ responsible for either having implicit or explicit ownership of the buffer.
+
+
+
+ @retval EFI_SUCCESS The data was read correctly from the device.
+
+ @retval EFI_DEVICE_ERROR The device reported an error while performing the read.
+
+ @retval EFI_NO_MEDIA There is no media in the device.
+
+ @retval EFI_MEDIA_CHANGED The MediaId does not matched the current device.
+
+ @retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
+
+ @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
+
+ or the buffer is not on proper alignment.
+
+EFI_STATUS
+
+**/
+EFI_STATUS
+EFIAPI
+MMCHSReadBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSize,
+ OUT VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+
+ //Perform Read operation.
+ Status = SdReadWrite (This, (UINTN)Lba, Buffer, BufferSize, READ);
+
+ return Status;
+
+}
+
+
+/**
+
+ Write BufferSize bytes from Lba into Buffer.
+
+
+
+ @param This Indicates a pointer to the calling context.
+
+ @param MediaId The media ID that the write request is for.
+
+ @param Lba The starting logical block address to be written. The caller is
+
+ responsible for writing to only legitimate locations.
+
+ @param BufferSize Size of Buffer, must be a multiple of device block size.
+
+ @param Buffer A pointer to the source buffer for the data.
+
+
+
+ @retval EFI_SUCCESS The data was written correctly to the device.
+
+ @retval EFI_WRITE_PROTECTED The device can not be written to.
+
+ @retval EFI_DEVICE_ERROR The device reported an error while performing the write.
+
+ @retval EFI_NO_MEDIA There is no media in the device.
+
+ @retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
+
+ @retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
+
+ @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
+
+ or the buffer is not on proper alignment.
+
+
+
+**/
+EFI_STATUS
+EFIAPI
+MMCHSWriteBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This,
+ IN UINT32 MediaId,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSize,
+ IN VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+
+ //Perform write operation.
+ Status = SdReadWrite (This, (UINTN)Lba, Buffer, BufferSize, WRITE);
+
+
+ return Status;
+
+}
+
+
+/**
+
+ Flush the Block Device.
+
+
+
+ @param This Indicates a pointer to the calling context.
+
+
+
+ @retval EFI_SUCCESS All outstanding data was written to the device
+
+ @retval EFI_DEVICE_ERROR The device reported an error while writting back the data
+
+ @retval EFI_NO_MEDIA There is no media in the device.
+
+
+
+**/
+EFI_STATUS
+EFIAPI
+MMCHSFlushBlocks (
+ IN EFI_BLOCK_IO_PROTOCOL *This
+ )
+{
+ return EFI_SUCCESS;
+}
+
+
+EFI_BLOCK_IO_PROTOCOL gBlockIo = {
+ EFI_BLOCK_IO_INTERFACE_REVISION, // Revision
+ &gMMCHSMedia, // *Media
+ MMCHSReset, // Reset
+ MMCHSReadBlocks, // ReadBlocks
+ MMCHSWriteBlocks, // WriteBlocks
+ MMCHSFlushBlocks // FlushBlocks
+};
+
+
+/**
+
+ Timer callback to convert card present hardware into a boolean that indicates
+
+ a media change event has happened. If you just check the GPIO you could see
+
+ card 1 and then check again after card 1 was removed and card 2 was inserted
+
+ and you would still see media present. Thus you need the timer tick to catch
+
+ the toggle event.
+
+
+
+ @param Event Event whose notification function is being invoked.
+
+ @param Context The pointer to the notification function's context,
+
+ which is implementation-dependent. Not used.
+
+
+
+**/
+VOID
+EFIAPI
+TimerCallback (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ BOOLEAN Present;
+
+ Present = CardPresent ();
+ if (gMMCHSMedia.MediaPresent) {
+ if (!Present && !gMediaChange) {
+ gMediaChange = TRUE;
+ }
+ } else {
+ if (Present && !gMediaChange) {
+ gMediaChange = TRUE;
+ }
+ }
+}
+
+
+EFI_STATUS
+EFIAPI
+MMCHSInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
+ ASSERT_EFI_ERROR(Status);
+
+ ZeroMem (&gCardInfo, sizeof (CARD_INFO));
+
+ Status = gBS->CreateEvent (EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_CALLBACK, TimerCallback, NULL, &gTimerEvent);
+ ASSERT_EFI_ERROR (Status);
+
+ Status = gBS->SetTimer (gTimerEvent, TimerPeriodic, FixedPcdGet32 (PcdMmchsTimerFreq100NanoSeconds));
+ ASSERT_EFI_ERROR (Status);
+
+ //Publish BlockIO.
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &ImageHandle,
+ &gEfiBlockIoProtocolGuid, &gBlockIo,
+ &gEfiDevicePathProtocolGuid, &gMmcHsDevicePath,
+ NULL
+ );
+ return Status;
+}
diff --git a/Omap35xxPkg/MMCHSDxe/MMCHS.h b/Omap35xxPkg/MMCHSDxe/MMCHS.h
index 2cda5679b..e19607bae 100644
--- a/Omap35xxPkg/MMCHSDxe/MMCHS.h
+++ b/Omap35xxPkg/MMCHSDxe/MMCHS.h
@@ -15,28 +15,28 @@
#ifndef _MMCHS_H_
#define _MMCHS_H_
-#include <Uefi.h>
-
-#include <Library/BaseLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/OmapLib.h>
-#include <Library/OmapDmaLib.h>
-#include <Library/DmaLib.h>
-
+#include <Uefi.h>
+
+#include <Library/BaseLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/OmapLib.h>
+#include <Library/OmapDmaLib.h>
+#include <Library/DmaLib.h>
+
#include <Protocol/EmbeddedExternalDevice.h>
-#include <Protocol/BlockIo.h>
-#include <Protocol/DevicePath.h>
-
+#include <Protocol/BlockIo.h>
+#include <Protocol/DevicePath.h>
+
#include <Omap3530/Omap3530.h>
#include <TPS65950.h>
-#define MAX_RETRY_COUNT (100*5)
-
+#define MAX_RETRY_COUNT (100*5)
+
#define HCS BIT30 //Host capacity support/1 = Supporting high capacity
#define CCS BIT30 //Card capacity status/1 = High capacity card
typedef struct {
@@ -141,12 +141,12 @@ typedef struct {
UINT8 CSD_STRUCTURE: 2; // CSD structure [127:126]
}CSD_SDV2;
-typedef enum {
- UNKNOWN_CARD,
- MMC_CARD, //MMC card
- SD_CARD, //SD 1.1 card
- SD_CARD_2, //SD 2.0 or above standard card
- SD_CARD_2_HIGH //SD 2.0 or above high capacity card
+typedef enum {
+ UNKNOWN_CARD,
+ MMC_CARD, //MMC card
+ SD_CARD, //SD 1.1 card
+ SD_CARD_2, //SD 2.0 or above standard card
+ SD_CARD_2_HIGH //SD 2.0 or above high capacity card
} CARD_TYPE;
typedef enum {
@@ -165,9 +165,9 @@ typedef struct {
CSD CSDData;
} CARD_INFO;
-EFI_STATUS
-DetectCard (
- VOID
+EFI_STATUS
+DetectCard (
+ VOID
);
extern EFI_BLOCK_IO_PROTOCOL gBlockIo;
diff --git a/Omap35xxPkg/MMCHSDxe/MMCHS.inf b/Omap35xxPkg/MMCHSDxe/MMCHS.inf
index 0931112e9..cc753c2a2 100644
--- a/Omap35xxPkg/MMCHSDxe/MMCHS.inf
+++ b/Omap35xxPkg/MMCHSDxe/MMCHS.inf
@@ -1,54 +1,54 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = MMCHS
- FILE_GUID = 100c2cfa-b586-4198-9b4c-1683d195b1da
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = MMCHSInitialize
-
-
-[Sources.common]
- MMCHS.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- PcdLib
- UefiLib
- UefiDriverEntryPoint
- MemoryAllocationLib
- IoLib
- OmapDmaLib
- DmaLib
-
-[Guids]
-
-[Protocols]
- gEfiBlockIoProtocolGuid
- gEfiCpuArchProtocolGuid
- gEfiDevicePathProtocolGuid
- gEmbeddedExternalDeviceProtocolGuid
-
-[Pcd]
- gOmap35xxTokenSpaceGuid.PcdOmap35xxMMCHS1Base
- gOmap35xxTokenSpaceGuid.PcdMmchsTimerFreq100NanoSeconds
-
-[depex]
- gEmbeddedExternalDeviceProtocolGuid
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = MMCHS
+ FILE_GUID = 100c2cfa-b586-4198-9b4c-1683d195b1da
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = MMCHSInitialize
+
+
+[Sources.common]
+ MMCHS.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ PcdLib
+ UefiLib
+ UefiDriverEntryPoint
+ MemoryAllocationLib
+ IoLib
+ OmapDmaLib
+ DmaLib
+
+[Guids]
+
+[Protocols]
+ gEfiBlockIoProtocolGuid
+ gEfiCpuArchProtocolGuid
+ gEfiDevicePathProtocolGuid
+ gEmbeddedExternalDeviceProtocolGuid
+
+[Pcd]
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxMMCHS1Base
+ gOmap35xxTokenSpaceGuid.PcdMmchsTimerFreq100NanoSeconds
+
+[depex]
+ gEmbeddedExternalDeviceProtocolGuid
diff --git a/Omap35xxPkg/MmcHostDxe/MmcHostDxe.c b/Omap35xxPkg/MmcHostDxe/MmcHostDxe.c
index 17ebf8d70..0cbd82bd4 100755
--- a/Omap35xxPkg/MmcHostDxe/MmcHostDxe.c
+++ b/Omap35xxPkg/MmcHostDxe/MmcHostDxe.c
@@ -1,677 +1,677 @@
-/** @file
-*
-* Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#include "MmcHostDxe.h"
-
-EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
-UINT8 mMaxDataTransferRate = 0;
-UINT32 mRca = 0;
-BOOLEAN mBitModeSet = FALSE;
-
-
-typedef struct {
- VENDOR_DEVICE_PATH Mmc;
- EFI_DEVICE_PATH End;
-} MMCHS_DEVICE_PATH;
-
-MMCHS_DEVICE_PATH gMMCDevicePath = {
- {
- HARDWARE_DEVICE_PATH,
- HW_VENDOR_DP,
- (UINT8)(sizeof(VENDOR_DEVICE_PATH)),
- (UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8),
- 0xb615f1f5, 0x5088, 0x43cd, 0x80, 0x9c, 0xa1, 0x6e, 0x52, 0x48, 0x7d, 0x00
- },
- {
- END_DEVICE_PATH_TYPE,
- END_ENTIRE_DEVICE_PATH_SUBTYPE,
- sizeof (EFI_DEVICE_PATH_PROTOCOL),
- 0
- }
-};
-
-BOOLEAN
-IgnoreCommand (
- UINT32 Command
- )
-{
- switch(Command) {
- case MMC_CMD12:
- return TRUE;
- case MMC_CMD13:
- return TRUE;
- default:
- return FALSE;
- }
-}
-
-UINT32
-TranslateCommand (
- UINT32 Command
- )
-{
- UINT32 Translation;
-
- switch(Command) {
- case MMC_CMD2:
- Translation = CMD2;
- break;
- case MMC_CMD3:
- Translation = CMD3;
- break;
- /*case MMC_CMD6:
- Translation = CMD6;
- break;*/
- case MMC_CMD7:
- Translation = CMD7;
- break;
- case MMC_CMD8:
- Translation = CMD8;
- break;
- case MMC_CMD9:
- Translation = CMD9;
- break;
- /*case MMC_CMD12:
- Translation = CMD12;
- break;
- case MMC_CMD13:
- Translation = CMD13;
- break;*/
- case MMC_CMD16:
- Translation = CMD16;
- break;
- case MMC_CMD17:
- Translation = 0x113A0014;//CMD17;
- break;
- case MMC_CMD24:
- Translation = CMD24 | 4;
- break;
- case MMC_CMD55:
- Translation = CMD55;
- break;
- case MMC_ACMD41:
- Translation = ACMD41;
- break;
- default:
- Translation = Command;
- }
-
- return Translation;
-}
-
-VOID
-CalculateCardCLKD (
- UINTN *ClockFrequencySelect
- )
-{
- UINTN TransferRateValue = 0;
- UINTN TimeValue = 0 ;
- UINTN Frequency = 0;
-
- DEBUG ((DEBUG_BLKIO, "CalculateCardCLKD()\n"));
-
- // For SD Cards we would need to send CMD6 to set
- // speeds abouve 25MHz. High Speed mode 50 MHz and up
-
- // Calculate Transfer rate unit (Bits 2:0 of TRAN_SPEED)
- switch (mMaxDataTransferRate & 0x7) { // 2
- case 0:
- TransferRateValue = 100 * 1000;
- break;
-
- case 1:
- TransferRateValue = 1 * 1000 * 1000;
- break;
-
- case 2:
- TransferRateValue = 10 * 1000 * 1000;
- break;
-
- case 3:
- TransferRateValue = 100 * 1000 * 1000;
- break;
-
- default:
- DEBUG ((DEBUG_BLKIO, "Invalid parameter.\n"));
- ASSERT(FALSE);
- return;
- }
-
- //Calculate Time value (Bits 6:3 of TRAN_SPEED)
- switch ((mMaxDataTransferRate >> 3) & 0xF) { // 6
- case 1:
- TimeValue = 10;
- break;
-
- case 2:
- TimeValue = 12;
- break;
-
- case 3:
- TimeValue = 13;
- break;
-
- case 4:
- TimeValue = 15;
- break;
-
- case 5:
- TimeValue = 20;
- break;
-
- case 6:
- TimeValue = 25;
- break;
-
- case 7:
- TimeValue = 30;
- break;
-
- case 8:
- TimeValue = 35;
- break;
-
- case 9:
- TimeValue = 40;
- break;
-
- case 10:
- TimeValue = 45;
- break;
-
- case 11:
- TimeValue = 50;
- break;
-
- case 12:
- TimeValue = 55;
- break;
-
- case 13:
- TimeValue = 60;
- break;
-
- case 14:
- TimeValue = 70;
- break;
-
- case 15:
- TimeValue = 80;
- break;
-
- default:
- DEBUG ((DEBUG_BLKIO, "Invalid parameter.\n"));
- ASSERT(FALSE);
- return;
- }
-
- Frequency = TransferRateValue * TimeValue/10;
-
- // Calculate Clock divider value to program in MMCHS_SYSCTL[CLKD] field.
- *ClockFrequencySelect = ((MMC_REFERENCE_CLK/Frequency) + 1);
-
- DEBUG ((DEBUG_BLKIO, "mMaxDataTransferRate: 0x%x, Frequency: %d KHz, ClockFrequencySelect: %x\n", mMaxDataTransferRate, Frequency/1000, *ClockFrequencySelect));
-}
-
-VOID
-UpdateMMCHSClkFrequency (
- UINTN NewCLKD
- )
-{
- DEBUG ((DEBUG_BLKIO, "UpdateMMCHSClkFrequency()\n"));
-
- // Set Clock enable to 0x0 to not provide the clock to the card
- MmioAnd32 (MMCHS_SYSCTL, ~CEN);
-
- // Set new clock frequency.
- MmioAndThenOr32 (MMCHS_SYSCTL, ~CLKD_MASK, NewCLKD << 6);
-
- // Poll till Internal Clock Stable
- while ((MmioRead32 (MMCHS_SYSCTL) & ICS_MASK) != ICS);
-
- // Set Clock enable to 0x1 to provide the clock to the card
- MmioOr32 (MMCHS_SYSCTL, CEN);
-}
-
-EFI_STATUS
-InitializeMMCHS (
- VOID
- )
-{
- UINT8 Data;
- EFI_STATUS Status;
-
- DEBUG ((DEBUG_BLKIO, "InitializeMMCHS()\n"));
-
- // Select Device group to belong to P1 device group in Power IC.
- Data = DEV_GRP_P1;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEV_GRP), 1, &Data);
- ASSERT_EFI_ERROR(Status);
-
- // Configure voltage regulator for MMC1 in Power IC to output 3.0 voltage.
- Data = VSEL_3_00V;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEDICATED_REG), 1, &Data);
- ASSERT_EFI_ERROR(Status);
-
- // After ramping up voltage, set VDDS stable bit to indicate that voltage level is stable.
- MmioOr32 (CONTROL_PBIAS_LITE, (PBIASLITEVMODE0 | PBIASLITEPWRDNZ0 | PBIASSPEEDCTRL0 | PBIASLITEVMODE1 | PBIASLITEWRDNZ1));
-
- // Enable WP GPIO
- MmioAndThenOr32 (GPIO1_BASE + GPIO_OE, ~BIT23, BIT23);
-
- // Enable Card Detect
- Data = CARD_DETECT_ENABLE;
- gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, TPS65950_GPIO_CTRL), 1, &Data);
-
- return Status;
-}
-
-BOOLEAN
-MMCIsCardPresent (
- IN EFI_MMC_HOST_PROTOCOL *This
- )
-{
- EFI_STATUS Status;
- UINT8 Data;
-
- //
- // Card detect is a GPIO0 on the TPS65950
- //
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATAIN1), 1, &Data);
- if (EFI_ERROR (Status)) {
- return FALSE;
- }
-
- return !(Data & CARD_DETECT_BIT);
-}
-
-BOOLEAN
-MMCIsReadOnly (
- IN EFI_MMC_HOST_PROTOCOL *This
- )
-{
- /* Note:
- * On our BeagleBoard the SD card WP pin is always read as TRUE.
- * Probably something wrong with GPIO configuration.
- * BeagleBoard-xM uses microSD cards so there is no write protect at all.
- * Hence commenting out SD card WP pin read status.
- */
- //return (MmioRead32 (GPIO1_BASE + GPIO_DATAIN) & BIT23) == BIT23;
- return 0;
-
-}
-
-// TODO
-EFI_GUID mPL180MciDevicePathGuid = EFI_CALLER_ID_GUID;
-
-EFI_STATUS
-MMCBuildDevicePath (
- IN EFI_MMC_HOST_PROTOCOL *This,
- IN EFI_DEVICE_PATH_PROTOCOL **DevicePath
- )
-{
- EFI_DEVICE_PATH_PROTOCOL *NewDevicePathNode;
-
- NewDevicePathNode = CreateDeviceNode(HARDWARE_DEVICE_PATH,HW_VENDOR_DP,sizeof(VENDOR_DEVICE_PATH));
- CopyGuid(&((VENDOR_DEVICE_PATH*)NewDevicePathNode)->Guid,&mPL180MciDevicePathGuid);
- *DevicePath = NewDevicePathNode;
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-MMCSendCommand (
- IN EFI_MMC_HOST_PROTOCOL *This,
- IN MMC_CMD MmcCmd,
- IN UINT32 Argument
- )
-{
- UINTN MmcStatus;
- UINTN RetryCount = 0;
-
- if (IgnoreCommand(MmcCmd))
- return EFI_SUCCESS;
-
- MmcCmd = TranslateCommand(MmcCmd);
-
- //DEBUG ((EFI_D_ERROR, "MMCSendCommand(%d)\n", MmcCmd));
-
- // Check if command line is in use or not. Poll till command line is available.
- while ((MmioRead32 (MMCHS_PSTATE) & DATI_MASK) == DATI_NOT_ALLOWED);
-
- // Provide the block size.
- MmioWrite32 (MMCHS_BLK, BLEN_512BYTES);
-
- // Setting Data timeout counter value to max value.
- MmioAndThenOr32 (MMCHS_SYSCTL, ~DTO_MASK, DTO_VAL);
-
- // Clear Status register.
- MmioWrite32 (MMCHS_STAT, 0xFFFFFFFF);
-
- // Set command argument register
- MmioWrite32 (MMCHS_ARG, Argument);
-
- //TODO: fix this
- //Enable interrupt enable events to occur
- //MmioWrite32 (MMCHS_IE, CmdInterruptEnableVal);
-
- // Send a command
- MmioWrite32 (MMCHS_CMD, MmcCmd);
-
- // Check for the command status.
- while (RetryCount < MAX_RETRY_COUNT) {
- do {
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while (MmcStatus == 0);
-
- // Read status of command response
- if ((MmcStatus & ERRI) != 0) {
-
- // Perform soft-reset for mmci_cmd line.
- MmioOr32 (MMCHS_SYSCTL, SRC);
- while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
-
- //DEBUG ((EFI_D_INFO, "MmcStatus: 0x%x\n", MmcStatus));
- return EFI_DEVICE_ERROR;
- }
-
- // Check if command is completed.
- if ((MmcStatus & CC) == CC) {
- MmioWrite32 (MMCHS_STAT, CC);
- break;
- }
-
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- DEBUG ((DEBUG_BLKIO, "MMCSendCommand: Timeout\n"));
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-MMCNotifyState (
- IN EFI_MMC_HOST_PROTOCOL *This,
- IN MMC_STATE State
- )
-{
- EFI_STATUS Status;
- UINTN FreqSel;
-
- switch(State) {
- case MmcInvalidState:
- ASSERT(0);
- break;
- case MmcHwInitializationState:
- mBitModeSet = FALSE;
-
- DEBUG ((DEBUG_BLKIO, "MMCHwInitializationState()\n"));
- Status = InitializeMMCHS ();
- if (EFI_ERROR(Status)) {
- DEBUG ((DEBUG_BLKIO, "Initialize MMC host controller fails. Status: %x\n", Status));
- return Status;
- }
-
- // Software reset of the MMCHS host controller.
- MmioWrite32 (MMCHS_SYSCONFIG, SOFTRESET);
- gBS->Stall(1000);
- while ((MmioRead32 (MMCHS_SYSSTATUS) & RESETDONE_MASK) != RESETDONE);
-
- // Soft reset for all.
- MmioWrite32 (MMCHS_SYSCTL, SRA);
- gBS->Stall(1000);
- while ((MmioRead32 (MMCHS_SYSCTL) & SRA) != 0x0);
-
- //Voltage capabilities initialization. Activate VS18 and VS30.
- MmioOr32 (MMCHS_CAPA, (VS30 | VS18));
-
- // Wakeup configuration
- MmioOr32 (MMCHS_SYSCONFIG, ENAWAKEUP);
- MmioOr32 (MMCHS_HCTL, IWE);
-
- // MMCHS Controller default initialization
- MmioOr32 (MMCHS_CON, (OD | DW8_1_4_BIT | CEATA_OFF));
-
- MmioWrite32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_OFF));
-
- // Enable internal clock
- MmioOr32 (MMCHS_SYSCTL, ICE);
-
- // Set the clock frequency to 80KHz.
- UpdateMMCHSClkFrequency (CLKD_80KHZ);
-
- // Enable SD bus power.
- MmioOr32 (MMCHS_HCTL, (SDBP_ON));
-
- // Poll till SD bus power bit is set.
- while ((MmioRead32 (MMCHS_HCTL) & SDBP_MASK) != SDBP_ON);
-
- // Enable interrupts.
- MmioWrite32 (MMCHS_IE, (BADA_EN | CERR_EN | DEB_EN | DCRC_EN | DTO_EN | CIE_EN |
- CEB_EN | CCRC_EN | CTO_EN | BRR_EN | BWR_EN | TC_EN | CC_EN));
-
- // Controller INIT procedure start.
- MmioOr32 (MMCHS_CON, INIT);
- MmioWrite32 (MMCHS_CMD, 0x00000000);
- while (!(MmioRead32 (MMCHS_STAT) & CC));
-
- // Wait for 1 ms
- gBS->Stall (1000);
-
- // Set CC bit to 0x1 to clear the flag
- MmioOr32 (MMCHS_STAT, CC);
-
- // Retry INIT procedure.
- MmioWrite32 (MMCHS_CMD, 0x00000000);
- while (!(MmioRead32 (MMCHS_STAT) & CC));
-
- // End initialization sequence
- MmioAnd32 (MMCHS_CON, ~INIT);
-
- MmioOr32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_ON));
-
- // Change clock frequency to 400KHz to fit protocol
- UpdateMMCHSClkFrequency(CLKD_400KHZ);
-
- MmioOr32 (MMCHS_CON, OD);
- break;
- case MmcIdleState:
- break;
- case MmcReadyState:
- break;
- case MmcIdentificationState:
- break;
- case MmcStandByState:
- CalculateCardCLKD (&FreqSel);
- UpdateMMCHSClkFrequency (FreqSel);
- break;
- case MmcTransferState:
- if (!mBitModeSet) {
- Status = MMCSendCommand (This, CMD55, mRca << 16);
- if (!EFI_ERROR (Status)) {
- // Set device into 4-bit data bus mode
- Status = MMCSendCommand (This, ACMD6, 0x2);
- if (!EFI_ERROR (Status)) {
- // Set host controler into 4-bit mode
- MmioOr32 (MMCHS_HCTL, DTW_4_BIT);
- DEBUG ((DEBUG_BLKIO, "SD Memory Card set to 4-bit mode\n"));
- mBitModeSet = TRUE;
- }
- }
- }
- break;
- case MmcSendingDataState:
- break;
- case MmcReceiveDataState:
- break;
- case MmcProgrammingState:
- break;
- case MmcDisconnectState:
- default:
- ASSERT(0);
- }
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-MMCReceiveResponse (
- IN EFI_MMC_HOST_PROTOCOL *This,
- IN MMC_RESPONSE_TYPE Type,
- IN UINT32* Buffer
- )
-{
- if (Buffer == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- if (Type == MMC_RESPONSE_TYPE_R2) {
- Buffer[0] = MmioRead32 (MMCHS_RSP10);
- Buffer[1] = MmioRead32 (MMCHS_RSP32);
- Buffer[2] = MmioRead32 (MMCHS_RSP54);
- Buffer[3] = MmioRead32 (MMCHS_RSP76);
- } else {
- Buffer[0] = MmioRead32 (MMCHS_RSP10);
- }
-
- if (Type == MMC_RESPONSE_TYPE_CSD) {
- mMaxDataTransferRate = Buffer[3] & 0xFF;
- } else if (Type == MMC_RESPONSE_TYPE_RCA) {
- mRca = Buffer[0] >> 16;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-MMCReadBlockData (
- IN EFI_MMC_HOST_PROTOCOL *This,
- IN EFI_LBA Lba,
- IN UINTN Length,
- IN UINT32* Buffer
- )
-{
- UINTN MmcStatus;
- UINTN Count;
- UINTN RetryCount = 0;
-
- DEBUG ((DEBUG_BLKIO, "MMCReadBlockData(LBA: 0x%x, Length: 0x%x, Buffer: 0x%x)\n", Lba, Length, Buffer));
-
- // Check controller status to make sure there is no error.
- while (RetryCount < MAX_RETRY_COUNT) {
- do {
- // Read Status.
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while(MmcStatus == 0);
-
- // Check if Buffer read ready (BRR) bit is set?
- if (MmcStatus & BRR) {
-
- // Clear BRR bit
- MmioOr32 (MMCHS_STAT, BRR);
-
- for (Count = 0; Count < Length / 4; Count++) {
- *Buffer++ = MmioRead32(MMCHS_DATA);
- }
- break;
- }
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-MMCWriteBlockData (
- IN EFI_MMC_HOST_PROTOCOL *This,
- IN EFI_LBA Lba,
- IN UINTN Length,
- IN UINT32* Buffer
- )
-{
- UINTN MmcStatus;
- UINTN Count;
- UINTN RetryCount = 0;
-
- // Check controller status to make sure there is no error.
- while (RetryCount < MAX_RETRY_COUNT) {
- do {
- // Read Status.
- MmcStatus = MmioRead32 (MMCHS_STAT);
- } while(MmcStatus == 0);
-
- // Check if Buffer write ready (BWR) bit is set?
- if (MmcStatus & BWR) {
-
- // Clear BWR bit
- MmioOr32 (MMCHS_STAT, BWR);
-
- // Write block worth of data.
- for (Count = 0; Count < Length / 4; Count++) {
- MmioWrite32 (MMCHS_DATA, *Buffer++);
- }
-
- break;
- }
- RetryCount++;
- }
-
- if (RetryCount == MAX_RETRY_COUNT) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_MMC_HOST_PROTOCOL gMMCHost = {
- MMC_HOST_PROTOCOL_REVISION,
- MMCIsCardPresent,
- MMCIsReadOnly,
- MMCBuildDevicePath,
- MMCNotifyState,
- MMCSendCommand,
- MMCReceiveResponse,
- MMCReadBlockData,
- MMCWriteBlockData
-};
-
-EFI_STATUS
-MMCInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE Handle = NULL;
-
- DEBUG ((DEBUG_BLKIO, "MMCInitialize()\n"));
-
- Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
- ASSERT_EFI_ERROR(Status);
-
- Status = gBS->InstallMultipleProtocolInterfaces (
- &Handle,
- &gEfiMmcHostProtocolGuid, &gMMCHost,
- NULL
- );
- ASSERT_EFI_ERROR (Status);
-
- return Status;
-}
+/** @file
+*
+* Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#include "MmcHostDxe.h"
+
+EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
+UINT8 mMaxDataTransferRate = 0;
+UINT32 mRca = 0;
+BOOLEAN mBitModeSet = FALSE;
+
+
+typedef struct {
+ VENDOR_DEVICE_PATH Mmc;
+ EFI_DEVICE_PATH End;
+} MMCHS_DEVICE_PATH;
+
+MMCHS_DEVICE_PATH gMMCDevicePath = {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_VENDOR_DP,
+ (UINT8)(sizeof(VENDOR_DEVICE_PATH)),
+ (UINT8)((sizeof(VENDOR_DEVICE_PATH)) >> 8),
+ 0xb615f1f5, 0x5088, 0x43cd, 0x80, 0x9c, 0xa1, 0x6e, 0x52, 0x48, 0x7d, 0x00
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ sizeof (EFI_DEVICE_PATH_PROTOCOL),
+ 0
+ }
+};
+
+BOOLEAN
+IgnoreCommand (
+ UINT32 Command
+ )
+{
+ switch(Command) {
+ case MMC_CMD12:
+ return TRUE;
+ case MMC_CMD13:
+ return TRUE;
+ default:
+ return FALSE;
+ }
+}
+
+UINT32
+TranslateCommand (
+ UINT32 Command
+ )
+{
+ UINT32 Translation;
+
+ switch(Command) {
+ case MMC_CMD2:
+ Translation = CMD2;
+ break;
+ case MMC_CMD3:
+ Translation = CMD3;
+ break;
+ /*case MMC_CMD6:
+ Translation = CMD6;
+ break;*/
+ case MMC_CMD7:
+ Translation = CMD7;
+ break;
+ case MMC_CMD8:
+ Translation = CMD8;
+ break;
+ case MMC_CMD9:
+ Translation = CMD9;
+ break;
+ /*case MMC_CMD12:
+ Translation = CMD12;
+ break;
+ case MMC_CMD13:
+ Translation = CMD13;
+ break;*/
+ case MMC_CMD16:
+ Translation = CMD16;
+ break;
+ case MMC_CMD17:
+ Translation = 0x113A0014;//CMD17;
+ break;
+ case MMC_CMD24:
+ Translation = CMD24 | 4;
+ break;
+ case MMC_CMD55:
+ Translation = CMD55;
+ break;
+ case MMC_ACMD41:
+ Translation = ACMD41;
+ break;
+ default:
+ Translation = Command;
+ }
+
+ return Translation;
+}
+
+VOID
+CalculateCardCLKD (
+ UINTN *ClockFrequencySelect
+ )
+{
+ UINTN TransferRateValue = 0;
+ UINTN TimeValue = 0 ;
+ UINTN Frequency = 0;
+
+ DEBUG ((DEBUG_BLKIO, "CalculateCardCLKD()\n"));
+
+ // For SD Cards we would need to send CMD6 to set
+ // speeds abouve 25MHz. High Speed mode 50 MHz and up
+
+ // Calculate Transfer rate unit (Bits 2:0 of TRAN_SPEED)
+ switch (mMaxDataTransferRate & 0x7) { // 2
+ case 0:
+ TransferRateValue = 100 * 1000;
+ break;
+
+ case 1:
+ TransferRateValue = 1 * 1000 * 1000;
+ break;
+
+ case 2:
+ TransferRateValue = 10 * 1000 * 1000;
+ break;
+
+ case 3:
+ TransferRateValue = 100 * 1000 * 1000;
+ break;
+
+ default:
+ DEBUG ((DEBUG_BLKIO, "Invalid parameter.\n"));
+ ASSERT(FALSE);
+ return;
+ }
+
+ //Calculate Time value (Bits 6:3 of TRAN_SPEED)
+ switch ((mMaxDataTransferRate >> 3) & 0xF) { // 6
+ case 1:
+ TimeValue = 10;
+ break;
+
+ case 2:
+ TimeValue = 12;
+ break;
+
+ case 3:
+ TimeValue = 13;
+ break;
+
+ case 4:
+ TimeValue = 15;
+ break;
+
+ case 5:
+ TimeValue = 20;
+ break;
+
+ case 6:
+ TimeValue = 25;
+ break;
+
+ case 7:
+ TimeValue = 30;
+ break;
+
+ case 8:
+ TimeValue = 35;
+ break;
+
+ case 9:
+ TimeValue = 40;
+ break;
+
+ case 10:
+ TimeValue = 45;
+ break;
+
+ case 11:
+ TimeValue = 50;
+ break;
+
+ case 12:
+ TimeValue = 55;
+ break;
+
+ case 13:
+ TimeValue = 60;
+ break;
+
+ case 14:
+ TimeValue = 70;
+ break;
+
+ case 15:
+ TimeValue = 80;
+ break;
+
+ default:
+ DEBUG ((DEBUG_BLKIO, "Invalid parameter.\n"));
+ ASSERT(FALSE);
+ return;
+ }
+
+ Frequency = TransferRateValue * TimeValue/10;
+
+ // Calculate Clock divider value to program in MMCHS_SYSCTL[CLKD] field.
+ *ClockFrequencySelect = ((MMC_REFERENCE_CLK/Frequency) + 1);
+
+ DEBUG ((DEBUG_BLKIO, "mMaxDataTransferRate: 0x%x, Frequency: %d KHz, ClockFrequencySelect: %x\n", mMaxDataTransferRate, Frequency/1000, *ClockFrequencySelect));
+}
+
+VOID
+UpdateMMCHSClkFrequency (
+ UINTN NewCLKD
+ )
+{
+ DEBUG ((DEBUG_BLKIO, "UpdateMMCHSClkFrequency()\n"));
+
+ // Set Clock enable to 0x0 to not provide the clock to the card
+ MmioAnd32 (MMCHS_SYSCTL, ~CEN);
+
+ // Set new clock frequency.
+ MmioAndThenOr32 (MMCHS_SYSCTL, ~CLKD_MASK, NewCLKD << 6);
+
+ // Poll till Internal Clock Stable
+ while ((MmioRead32 (MMCHS_SYSCTL) & ICS_MASK) != ICS);
+
+ // Set Clock enable to 0x1 to provide the clock to the card
+ MmioOr32 (MMCHS_SYSCTL, CEN);
+}
+
+EFI_STATUS
+InitializeMMCHS (
+ VOID
+ )
+{
+ UINT8 Data;
+ EFI_STATUS Status;
+
+ DEBUG ((DEBUG_BLKIO, "InitializeMMCHS()\n"));
+
+ // Select Device group to belong to P1 device group in Power IC.
+ Data = DEV_GRP_P1;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEV_GRP), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+
+ // Configure voltage regulator for MMC1 in Power IC to output 3.0 voltage.
+ Data = VSEL_3_00V;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VMMC1_DEDICATED_REG), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+
+ // After ramping up voltage, set VDDS stable bit to indicate that voltage level is stable.
+ MmioOr32 (CONTROL_PBIAS_LITE, (PBIASLITEVMODE0 | PBIASLITEPWRDNZ0 | PBIASSPEEDCTRL0 | PBIASLITEVMODE1 | PBIASLITEWRDNZ1));
+
+ // Enable WP GPIO
+ MmioAndThenOr32 (GPIO1_BASE + GPIO_OE, ~BIT23, BIT23);
+
+ // Enable Card Detect
+ Data = CARD_DETECT_ENABLE;
+ gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, TPS65950_GPIO_CTRL), 1, &Data);
+
+ return Status;
+}
+
+BOOLEAN
+MMCIsCardPresent (
+ IN EFI_MMC_HOST_PROTOCOL *This
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data;
+
+ //
+ // Card detect is a GPIO0 on the TPS65950
+ //
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID2, GPIODATAIN1), 1, &Data);
+ if (EFI_ERROR (Status)) {
+ return FALSE;
+ }
+
+ return !(Data & CARD_DETECT_BIT);
+}
+
+BOOLEAN
+MMCIsReadOnly (
+ IN EFI_MMC_HOST_PROTOCOL *This
+ )
+{
+ /* Note:
+ * On our BeagleBoard the SD card WP pin is always read as TRUE.
+ * Probably something wrong with GPIO configuration.
+ * BeagleBoard-xM uses microSD cards so there is no write protect at all.
+ * Hence commenting out SD card WP pin read status.
+ */
+ //return (MmioRead32 (GPIO1_BASE + GPIO_DATAIN) & BIT23) == BIT23;
+ return 0;
+
+}
+
+// TODO
+EFI_GUID mPL180MciDevicePathGuid = EFI_CALLER_ID_GUID;
+
+EFI_STATUS
+MMCBuildDevicePath (
+ IN EFI_MMC_HOST_PROTOCOL *This,
+ IN EFI_DEVICE_PATH_PROTOCOL **DevicePath
+ )
+{
+ EFI_DEVICE_PATH_PROTOCOL *NewDevicePathNode;
+
+ NewDevicePathNode = CreateDeviceNode(HARDWARE_DEVICE_PATH,HW_VENDOR_DP,sizeof(VENDOR_DEVICE_PATH));
+ CopyGuid(&((VENDOR_DEVICE_PATH*)NewDevicePathNode)->Guid,&mPL180MciDevicePathGuid);
+ *DevicePath = NewDevicePathNode;
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+MMCSendCommand (
+ IN EFI_MMC_HOST_PROTOCOL *This,
+ IN MMC_CMD MmcCmd,
+ IN UINT32 Argument
+ )
+{
+ UINTN MmcStatus;
+ UINTN RetryCount = 0;
+
+ if (IgnoreCommand(MmcCmd))
+ return EFI_SUCCESS;
+
+ MmcCmd = TranslateCommand(MmcCmd);
+
+ //DEBUG ((EFI_D_ERROR, "MMCSendCommand(%d)\n", MmcCmd));
+
+ // Check if command line is in use or not. Poll till command line is available.
+ while ((MmioRead32 (MMCHS_PSTATE) & DATI_MASK) == DATI_NOT_ALLOWED);
+
+ // Provide the block size.
+ MmioWrite32 (MMCHS_BLK, BLEN_512BYTES);
+
+ // Setting Data timeout counter value to max value.
+ MmioAndThenOr32 (MMCHS_SYSCTL, ~DTO_MASK, DTO_VAL);
+
+ // Clear Status register.
+ MmioWrite32 (MMCHS_STAT, 0xFFFFFFFF);
+
+ // Set command argument register
+ MmioWrite32 (MMCHS_ARG, Argument);
+
+ //TODO: fix this
+ //Enable interrupt enable events to occur
+ //MmioWrite32 (MMCHS_IE, CmdInterruptEnableVal);
+
+ // Send a command
+ MmioWrite32 (MMCHS_CMD, MmcCmd);
+
+ // Check for the command status.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ do {
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while (MmcStatus == 0);
+
+ // Read status of command response
+ if ((MmcStatus & ERRI) != 0) {
+
+ // Perform soft-reset for mmci_cmd line.
+ MmioOr32 (MMCHS_SYSCTL, SRC);
+ while ((MmioRead32 (MMCHS_SYSCTL) & SRC));
+
+ //DEBUG ((EFI_D_INFO, "MmcStatus: 0x%x\n", MmcStatus));
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Check if command is completed.
+ if ((MmcStatus & CC) == CC) {
+ MmioWrite32 (MMCHS_STAT, CC);
+ break;
+ }
+
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ DEBUG ((DEBUG_BLKIO, "MMCSendCommand: Timeout\n"));
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+MMCNotifyState (
+ IN EFI_MMC_HOST_PROTOCOL *This,
+ IN MMC_STATE State
+ )
+{
+ EFI_STATUS Status;
+ UINTN FreqSel;
+
+ switch(State) {
+ case MmcInvalidState:
+ ASSERT(0);
+ break;
+ case MmcHwInitializationState:
+ mBitModeSet = FALSE;
+
+ DEBUG ((DEBUG_BLKIO, "MMCHwInitializationState()\n"));
+ Status = InitializeMMCHS ();
+ if (EFI_ERROR(Status)) {
+ DEBUG ((DEBUG_BLKIO, "Initialize MMC host controller fails. Status: %x\n", Status));
+ return Status;
+ }
+
+ // Software reset of the MMCHS host controller.
+ MmioWrite32 (MMCHS_SYSCONFIG, SOFTRESET);
+ gBS->Stall(1000);
+ while ((MmioRead32 (MMCHS_SYSSTATUS) & RESETDONE_MASK) != RESETDONE);
+
+ // Soft reset for all.
+ MmioWrite32 (MMCHS_SYSCTL, SRA);
+ gBS->Stall(1000);
+ while ((MmioRead32 (MMCHS_SYSCTL) & SRA) != 0x0);
+
+ //Voltage capabilities initialization. Activate VS18 and VS30.
+ MmioOr32 (MMCHS_CAPA, (VS30 | VS18));
+
+ // Wakeup configuration
+ MmioOr32 (MMCHS_SYSCONFIG, ENAWAKEUP);
+ MmioOr32 (MMCHS_HCTL, IWE);
+
+ // MMCHS Controller default initialization
+ MmioOr32 (MMCHS_CON, (OD | DW8_1_4_BIT | CEATA_OFF));
+
+ MmioWrite32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_OFF));
+
+ // Enable internal clock
+ MmioOr32 (MMCHS_SYSCTL, ICE);
+
+ // Set the clock frequency to 80KHz.
+ UpdateMMCHSClkFrequency (CLKD_80KHZ);
+
+ // Enable SD bus power.
+ MmioOr32 (MMCHS_HCTL, (SDBP_ON));
+
+ // Poll till SD bus power bit is set.
+ while ((MmioRead32 (MMCHS_HCTL) & SDBP_MASK) != SDBP_ON);
+
+ // Enable interrupts.
+ MmioWrite32 (MMCHS_IE, (BADA_EN | CERR_EN | DEB_EN | DCRC_EN | DTO_EN | CIE_EN |
+ CEB_EN | CCRC_EN | CTO_EN | BRR_EN | BWR_EN | TC_EN | CC_EN));
+
+ // Controller INIT procedure start.
+ MmioOr32 (MMCHS_CON, INIT);
+ MmioWrite32 (MMCHS_CMD, 0x00000000);
+ while (!(MmioRead32 (MMCHS_STAT) & CC));
+
+ // Wait for 1 ms
+ gBS->Stall (1000);
+
+ // Set CC bit to 0x1 to clear the flag
+ MmioOr32 (MMCHS_STAT, CC);
+
+ // Retry INIT procedure.
+ MmioWrite32 (MMCHS_CMD, 0x00000000);
+ while (!(MmioRead32 (MMCHS_STAT) & CC));
+
+ // End initialization sequence
+ MmioAnd32 (MMCHS_CON, ~INIT);
+
+ MmioOr32 (MMCHS_HCTL, (SDVS_3_0_V | DTW_1_BIT | SDBP_ON));
+
+ // Change clock frequency to 400KHz to fit protocol
+ UpdateMMCHSClkFrequency(CLKD_400KHZ);
+
+ MmioOr32 (MMCHS_CON, OD);
+ break;
+ case MmcIdleState:
+ break;
+ case MmcReadyState:
+ break;
+ case MmcIdentificationState:
+ break;
+ case MmcStandByState:
+ CalculateCardCLKD (&FreqSel);
+ UpdateMMCHSClkFrequency (FreqSel);
+ break;
+ case MmcTransferState:
+ if (!mBitModeSet) {
+ Status = MMCSendCommand (This, CMD55, mRca << 16);
+ if (!EFI_ERROR (Status)) {
+ // Set device into 4-bit data bus mode
+ Status = MMCSendCommand (This, ACMD6, 0x2);
+ if (!EFI_ERROR (Status)) {
+ // Set host controler into 4-bit mode
+ MmioOr32 (MMCHS_HCTL, DTW_4_BIT);
+ DEBUG ((DEBUG_BLKIO, "SD Memory Card set to 4-bit mode\n"));
+ mBitModeSet = TRUE;
+ }
+ }
+ }
+ break;
+ case MmcSendingDataState:
+ break;
+ case MmcReceiveDataState:
+ break;
+ case MmcProgrammingState:
+ break;
+ case MmcDisconnectState:
+ default:
+ ASSERT(0);
+ }
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+MMCReceiveResponse (
+ IN EFI_MMC_HOST_PROTOCOL *This,
+ IN MMC_RESPONSE_TYPE Type,
+ IN UINT32* Buffer
+ )
+{
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (Type == MMC_RESPONSE_TYPE_R2) {
+ Buffer[0] = MmioRead32 (MMCHS_RSP10);
+ Buffer[1] = MmioRead32 (MMCHS_RSP32);
+ Buffer[2] = MmioRead32 (MMCHS_RSP54);
+ Buffer[3] = MmioRead32 (MMCHS_RSP76);
+ } else {
+ Buffer[0] = MmioRead32 (MMCHS_RSP10);
+ }
+
+ if (Type == MMC_RESPONSE_TYPE_CSD) {
+ mMaxDataTransferRate = Buffer[3] & 0xFF;
+ } else if (Type == MMC_RESPONSE_TYPE_RCA) {
+ mRca = Buffer[0] >> 16;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+MMCReadBlockData (
+ IN EFI_MMC_HOST_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Length,
+ IN UINT32* Buffer
+ )
+{
+ UINTN MmcStatus;
+ UINTN Count;
+ UINTN RetryCount = 0;
+
+ DEBUG ((DEBUG_BLKIO, "MMCReadBlockData(LBA: 0x%x, Length: 0x%x, Buffer: 0x%x)\n", Lba, Length, Buffer));
+
+ // Check controller status to make sure there is no error.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ do {
+ // Read Status.
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while(MmcStatus == 0);
+
+ // Check if Buffer read ready (BRR) bit is set?
+ if (MmcStatus & BRR) {
+
+ // Clear BRR bit
+ MmioOr32 (MMCHS_STAT, BRR);
+
+ for (Count = 0; Count < Length / 4; Count++) {
+ *Buffer++ = MmioRead32(MMCHS_DATA);
+ }
+ break;
+ }
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+MMCWriteBlockData (
+ IN EFI_MMC_HOST_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Length,
+ IN UINT32* Buffer
+ )
+{
+ UINTN MmcStatus;
+ UINTN Count;
+ UINTN RetryCount = 0;
+
+ // Check controller status to make sure there is no error.
+ while (RetryCount < MAX_RETRY_COUNT) {
+ do {
+ // Read Status.
+ MmcStatus = MmioRead32 (MMCHS_STAT);
+ } while(MmcStatus == 0);
+
+ // Check if Buffer write ready (BWR) bit is set?
+ if (MmcStatus & BWR) {
+
+ // Clear BWR bit
+ MmioOr32 (MMCHS_STAT, BWR);
+
+ // Write block worth of data.
+ for (Count = 0; Count < Length / 4; Count++) {
+ MmioWrite32 (MMCHS_DATA, *Buffer++);
+ }
+
+ break;
+ }
+ RetryCount++;
+ }
+
+ if (RetryCount == MAX_RETRY_COUNT) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_MMC_HOST_PROTOCOL gMMCHost = {
+ MMC_HOST_PROTOCOL_REVISION,
+ MMCIsCardPresent,
+ MMCIsReadOnly,
+ MMCBuildDevicePath,
+ MMCNotifyState,
+ MMCSendCommand,
+ MMCReceiveResponse,
+ MMCReadBlockData,
+ MMCWriteBlockData
+};
+
+EFI_STATUS
+MMCInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle = NULL;
+
+ DEBUG ((DEBUG_BLKIO, "MMCInitialize()\n"));
+
+ Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
+ ASSERT_EFI_ERROR(Status);
+
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Handle,
+ &gEfiMmcHostProtocolGuid, &gMMCHost,
+ NULL
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ return Status;
+}
diff --git a/Omap35xxPkg/MmcHostDxe/MmcHostDxe.h b/Omap35xxPkg/MmcHostDxe/MmcHostDxe.h
index 940087f26..ec55234db 100755
--- a/Omap35xxPkg/MmcHostDxe/MmcHostDxe.h
+++ b/Omap35xxPkg/MmcHostDxe/MmcHostDxe.h
@@ -1,44 +1,44 @@
-/** @file
-*
-* Copyright (c) 2011, ARM Limited. All rights reserved.
-*
-* This program and the accompanying materials
-* are licensed and made available under the terms and conditions of the BSD License
-* which accompanies this distribution. The full text of the license may be found at
-* http://opensource.org/licenses/bsd-license.php
-*
-* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-*
-**/
-
-#ifndef _MMC_HOST_DXE_H_
-#define _MMC_HOST_DXE_H_
-
-#include <Uefi.h>
-
-#include <Library/BaseLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/DebugLib.h>
-#include <Library/DevicePathLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/OmapLib.h>
-#include <Library/OmapDmaLib.h>
-#include <Library/DmaLib.h>
-
-#include <Protocol/EmbeddedExternalDevice.h>
-#include <Protocol/BlockIo.h>
-#include <Protocol/DevicePath.h>
-#include <Protocol/MmcHost.h>
-
-#include <Omap3530/Omap3530.h>
-#include <TPS65950.h>
-
-#define MAX_RETRY_COUNT (100*5)
-
-extern EFI_BLOCK_IO_PROTOCOL gBlockIo;
-
-#endif
+/** @file
+*
+* Copyright (c) 2011, ARM Limited. All rights reserved.
+*
+* This program and the accompanying materials
+* are licensed and made available under the terms and conditions of the BSD License
+* which accompanies this distribution. The full text of the license may be found at
+* http://opensource.org/licenses/bsd-license.php
+*
+* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+*
+**/
+
+#ifndef _MMC_HOST_DXE_H_
+#define _MMC_HOST_DXE_H_
+
+#include <Uefi.h>
+
+#include <Library/BaseLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/OmapLib.h>
+#include <Library/OmapDmaLib.h>
+#include <Library/DmaLib.h>
+
+#include <Protocol/EmbeddedExternalDevice.h>
+#include <Protocol/BlockIo.h>
+#include <Protocol/DevicePath.h>
+#include <Protocol/MmcHost.h>
+
+#include <Omap3530/Omap3530.h>
+#include <TPS65950.h>
+
+#define MAX_RETRY_COUNT (100*5)
+
+extern EFI_BLOCK_IO_PROTOCOL gBlockIo;
+
+#endif
diff --git a/Omap35xxPkg/MmcHostDxe/MmcHostDxe.inf b/Omap35xxPkg/MmcHostDxe/MmcHostDxe.inf
index a15b6f703..8c95c0f2d 100755
--- a/Omap35xxPkg/MmcHostDxe/MmcHostDxe.inf
+++ b/Omap35xxPkg/MmcHostDxe/MmcHostDxe.inf
@@ -1,53 +1,53 @@
-# Copyright (c) 2011, ARM Limited. All rights reserved.
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = MMC
- FILE_GUID = 100c2cfa-b586-4198-9b4c-1683d195b1da
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = MMCInitialize
-
-
-[Sources.common]
- MmcHostDxe.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- PcdLib
- UefiLib
- UefiDriverEntryPoint
- MemoryAllocationLib
- IoLib
- OmapDmaLib
- DmaLib
-
-[Guids]
-
-[Protocols]
- gEfiBlockIoProtocolGuid
- gEfiCpuArchProtocolGuid
- gEfiDevicePathProtocolGuid
- gEmbeddedExternalDeviceProtocolGuid
- gEfiMmcHostProtocolGuid
-
-[Pcd]
- gOmap35xxTokenSpaceGuid.PcdOmap35xxMMCHS1Base
- gOmap35xxTokenSpaceGuid.PcdMmchsTimerFreq100NanoSeconds
-
-[depex]
- gEmbeddedExternalDeviceProtocolGuid
+# Copyright (c) 2011, ARM Limited. All rights reserved.
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = MMC
+ FILE_GUID = 100c2cfa-b586-4198-9b4c-1683d195b1da
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = MMCInitialize
+
+
+[Sources.common]
+ MmcHostDxe.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ PcdLib
+ UefiLib
+ UefiDriverEntryPoint
+ MemoryAllocationLib
+ IoLib
+ OmapDmaLib
+ DmaLib
+
+[Guids]
+
+[Protocols]
+ gEfiBlockIoProtocolGuid
+ gEfiCpuArchProtocolGuid
+ gEfiDevicePathProtocolGuid
+ gEmbeddedExternalDeviceProtocolGuid
+ gEfiMmcHostProtocolGuid
+
+[Pcd]
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxMMCHS1Base
+ gOmap35xxTokenSpaceGuid.PcdMmchsTimerFreq100NanoSeconds
+
+[depex]
+ gEmbeddedExternalDeviceProtocolGuid
diff --git a/Omap35xxPkg/Omap35xxPkg.dsc b/Omap35xxPkg/Omap35xxPkg.dsc
index 1666a683d..075dd6ae9 100644
--- a/Omap35xxPkg/Omap35xxPkg.dsc
+++ b/Omap35xxPkg/Omap35xxPkg.dsc
@@ -1,188 +1,188 @@
-#/** @file
-# Omap35xx SoC package.
-#
-# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
-#
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-################################################################################
-#
-# Defines Section - statements that will be processed to create a Makefile.
-#
-################################################################################
-[Defines]
- PLATFORM_NAME = Omap35xxPkg
- PLATFORM_GUID = D196A631-B7B7-4953-A3EE-0F773CBABF20
- PLATFORM_VERSION = 0.1
- DSC_SPECIFICATION = 0x00010005
- OUTPUT_DIRECTORY = Build/Omap35xxPkg
- SUPPORTED_ARCHITECTURES = ARM
- BUILD_TARGETS = DEBUG|RELEASE
- SKUID_IDENTIFIER = DEFAULT
- DEFINE TARGET_HACK = DEBUG
-
-
-[LibraryClasses.common]
- DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
-
- ArmLib|ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
-
- BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
- BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
-
- PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
-
- CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
- DefaultExceptioHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
- CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf
- PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
-
- RealTimeClockLib|EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
-
- IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
- OmapLib|Omap35xxPkg/Library/OmapLib/OmapLib.inf
- OmapDmaLib|Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
-
- MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
- UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
- UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
- DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
- UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
-
- DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
- UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
- UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
- DmaLib|ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
-
-#
-# Assume everything is fixed at build
-#
- PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
-
- UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf
-
- # UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
- UncachedMemoryAllocationLib|ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
-
- CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
-
-
-[LibraryClasses.common.DXE_DRIVER]
- DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
-
-
-[LibraryClasses.ARM]
- #
- # Note: This NULL library feature is not yet in the edk2/BaseTools, but it is checked in to
- # the BaseTools project. So you need to build with the BaseTools project util this feature gets synced.
- #
- NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
-
-
-[BuildOptions]
- XCODE:*_*_ARM_ARCHCC_FLAGS == -arch armv7 -march=armv7
- XCODE:*_*_ARM_ARCHASM_FLAGS == -arch armv7
- XCODE:*_*_ARM_ARCHDLINK_FLAGS == -arch armv7
-
- GCC:*_*_ARM_ARCHCC_FLAGS == -march=armv7-a -mthumb
- GCC:*_*_ARM_ARCHASM_FLAGS == -march=armv7-a
-
- RVCT:*_*_ARM_ARCHCC_FLAGS == --cpu 7-A
- RVCT:*_*_ARM_ARCHASM_FLAGS == --cpu 7-A
-
-
-################################################################################
-#
-# Pcd Section - list of all EDK II PCD Entries defined by this Platform
-#
-################################################################################
-
-
-[PcdsFixedAtBuild.common]
-
-# DEBUG_ASSERT_ENABLED 0x01
-# DEBUG_PRINT_ENABLED 0x02
-# DEBUG_CODE_ENABLED 0x04
-# CLEAR_MEMORY_ENABLED 0x08
-# ASSERT_BREAKPOINT_ENABLED 0x10
-# ASSERT_DEADLOOP_ENABLED 0x20
- gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f
-
-# DEBUG_INIT 0x00000001 // Initialization
-# DEBUG_WARN 0x00000002 // Warnings
-# DEBUG_LOAD 0x00000004 // Load events
-# DEBUG_FS 0x00000008 // EFI File system
-# DEBUG_POOL 0x00000010 // Alloc & Free's
-# DEBUG_PAGE 0x00000020 // Alloc & Free's
-# DEBUG_INFO 0x00000040 // Verbose
-# DEBUG_DISPATCH 0x00000080 // PEI/DXE Dispatchers
-# DEBUG_VARIABLE 0x00000100 // Variable
-# DEBUG_BM 0x00000400 // Boot Manager
-# DEBUG_BLKIO 0x00001000 // BlkIo Driver
-# DEBUG_NET 0x00004000 // SNI Driver
-# DEBUG_UNDI 0x00010000 // UNDI Driver
-# DEBUG_LOADFILE 0x00020000 // UNDI Driver
-# DEBUG_EVENT 0x00080000 // Event messages
-# DEBUG_ERROR 0x80000000 // Error
- gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000004
-
- gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07
-
- gEmbeddedTokenSpaceGuid.PcdPrePiTempMemorySize|0
- gEmbeddedTokenSpaceGuid.PcdPrePiBfvBaseAddress|0
- gEmbeddedTokenSpaceGuid.PcdPrePiBfvSize|0
- gEmbeddedTokenSpaceGuid.PcdFlashFvMainBase|0
- gEmbeddedTokenSpaceGuid.PcdFlashFvMainSize|0
- gEmbeddedTokenSpaceGuid.PcdPrePiHobBase|0x80001000
- gEmbeddedTokenSpaceGuid.PcdPrePiStackBase|0x87FE0000 # stack at top of memory
- gEmbeddedTokenSpaceGuid.PcdPrePiStackSize|0x20000 # 128K stack
- gArmTokenSpaceGuid.PcdCpuVectorBaseAddress|0x80000000
- gArmTokenSpaceGuid.PcdCpuResetAddress|0x80008000
-
- gOmap35xxTokenSpaceGuid.PcdOmap35xxGpmcOffset|0x6E000000
- gOmap35xxTokenSpaceGuid.PcdOmap35xxMMCHS1Base|0x4809C000
-
- # Console
- gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart|3
-
- # Timers
- gOmap35xxTokenSpaceGuid.PcdOmap35xxArchTimer|3
- gOmap35xxTokenSpaceGuid.PcdOmap35xxFreeTimer|4
- gEmbeddedTokenSpaceGuid.PcdTimerPeriod|100000
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterPeriodInNanoseconds|77
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterFrequencyInHz|13000000
-
- #
- # ARM Pcds
- #
- gArmTokenSpaceGuid.PcdArmUncachedMemoryMask|0x0000000040000000
-
-################################################################################
-#
-# Components Section - list of all EDK II Modules needed by this Platform
-#
-################################################################################
-[Components.common]
- Omap35xxPkg/Library/Omap35xxTimerLib/Omap35xxTimerLib.inf
- Omap35xxPkg/Library/OmapLib/OmapLib.inf
- Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
-
- Omap35xxPkg/Flash/Flash.inf
- Omap35xxPkg/MMCHSDxe/MMCHS.inf
- Omap35xxPkg/SmbusDxe/Smbus.inf
- Omap35xxPkg/Gpio/Gpio.inf
- Omap35xxPkg/InterruptDxe/InterruptDxe.inf
- Omap35xxPkg/TimerDxe/TimerDxe.inf
- Omap35xxPkg/TPS65950Dxe/TPS65950.inf
-
-
-
+#/** @file
+# Omap35xx SoC package.
+#
+# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
+#
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+ PLATFORM_NAME = Omap35xxPkg
+ PLATFORM_GUID = D196A631-B7B7-4953-A3EE-0F773CBABF20
+ PLATFORM_VERSION = 0.1
+ DSC_SPECIFICATION = 0x00010005
+ OUTPUT_DIRECTORY = Build/Omap35xxPkg
+ SUPPORTED_ARCHITECTURES = ARM
+ BUILD_TARGETS = DEBUG|RELEASE
+ SKUID_IDENTIFIER = DEFAULT
+ DEFINE TARGET_HACK = DEBUG
+
+
+[LibraryClasses.common]
+ DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
+
+ ArmLib|ArmPkg/Library/ArmLib/ArmV7/ArmV7Lib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+
+ BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+
+ CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
+ DefaultExceptioHandlerLib|ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf
+ CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf
+ PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
+
+ RealTimeClockLib|EmbeddedPkg/Library/TemplateRealTimeClockLib/TemplateRealTimeClockLib.inf
+
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ OmapLib|Omap35xxPkg/Library/OmapLib/OmapLib.inf
+ OmapDmaLib|Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
+
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
+ UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
+
+ DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
+ UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
+ UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
+ DmaLib|ArmPkg/Library/ArmDmaLib/ArmDmaLib.inf
+
+#
+# Assume everything is fixed at build
+#
+ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+
+ UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf
+
+ # UncachedMemoryAllocationLib|ArmPkg/Library/UncachedMemoryAllocationLib/UncachedMemoryAllocationLib.inf
+ UncachedMemoryAllocationLib|ArmPkg/Library/DebugUncachedMemoryAllocationLib/DebugUncachedMemoryAllocationLib.inf
+
+ CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
+
+
+[LibraryClasses.common.DXE_DRIVER]
+ DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
+
+
+[LibraryClasses.ARM]
+ #
+ # Note: This NULL library feature is not yet in the edk2/BaseTools, but it is checked in to
+ # the BaseTools project. So you need to build with the BaseTools project util this feature gets synced.
+ #
+ NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf
+
+
+[BuildOptions]
+ XCODE:*_*_ARM_ARCHCC_FLAGS == -arch armv7 -march=armv7
+ XCODE:*_*_ARM_ARCHASM_FLAGS == -arch armv7
+ XCODE:*_*_ARM_ARCHDLINK_FLAGS == -arch armv7
+
+ GCC:*_*_ARM_ARCHCC_FLAGS == -march=armv7-a -mthumb
+ GCC:*_*_ARM_ARCHASM_FLAGS == -march=armv7-a
+
+ RVCT:*_*_ARM_ARCHCC_FLAGS == --cpu 7-A
+ RVCT:*_*_ARM_ARCHASM_FLAGS == --cpu 7-A
+
+
+################################################################################
+#
+# Pcd Section - list of all EDK II PCD Entries defined by this Platform
+#
+################################################################################
+
+
+[PcdsFixedAtBuild.common]
+
+# DEBUG_ASSERT_ENABLED 0x01
+# DEBUG_PRINT_ENABLED 0x02
+# DEBUG_CODE_ENABLED 0x04
+# CLEAR_MEMORY_ENABLED 0x08
+# ASSERT_BREAKPOINT_ENABLED 0x10
+# ASSERT_DEADLOOP_ENABLED 0x20
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f
+
+# DEBUG_INIT 0x00000001 // Initialization
+# DEBUG_WARN 0x00000002 // Warnings
+# DEBUG_LOAD 0x00000004 // Load events
+# DEBUG_FS 0x00000008 // EFI File system
+# DEBUG_POOL 0x00000010 // Alloc & Free's
+# DEBUG_PAGE 0x00000020 // Alloc & Free's
+# DEBUG_INFO 0x00000040 // Verbose
+# DEBUG_DISPATCH 0x00000080 // PEI/DXE Dispatchers
+# DEBUG_VARIABLE 0x00000100 // Variable
+# DEBUG_BM 0x00000400 // Boot Manager
+# DEBUG_BLKIO 0x00001000 // BlkIo Driver
+# DEBUG_NET 0x00004000 // SNI Driver
+# DEBUG_UNDI 0x00010000 // UNDI Driver
+# DEBUG_LOADFILE 0x00020000 // UNDI Driver
+# DEBUG_EVENT 0x00080000 // Event messages
+# DEBUG_ERROR 0x80000000 // Error
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000004
+
+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07
+
+ gEmbeddedTokenSpaceGuid.PcdPrePiTempMemorySize|0
+ gEmbeddedTokenSpaceGuid.PcdPrePiBfvBaseAddress|0
+ gEmbeddedTokenSpaceGuid.PcdPrePiBfvSize|0
+ gEmbeddedTokenSpaceGuid.PcdFlashFvMainBase|0
+ gEmbeddedTokenSpaceGuid.PcdFlashFvMainSize|0
+ gEmbeddedTokenSpaceGuid.PcdPrePiHobBase|0x80001000
+ gEmbeddedTokenSpaceGuid.PcdPrePiStackBase|0x87FE0000 # stack at top of memory
+ gEmbeddedTokenSpaceGuid.PcdPrePiStackSize|0x20000 # 128K stack
+ gArmTokenSpaceGuid.PcdCpuVectorBaseAddress|0x80000000
+ gArmTokenSpaceGuid.PcdCpuResetAddress|0x80008000
+
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxGpmcOffset|0x6E000000
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxMMCHS1Base|0x4809C000
+
+ # Console
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxConsoleUart|3
+
+ # Timers
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxArchTimer|3
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxFreeTimer|4
+ gEmbeddedTokenSpaceGuid.PcdTimerPeriod|100000
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterPeriodInNanoseconds|77
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterFrequencyInHz|13000000
+
+ #
+ # ARM Pcds
+ #
+ gArmTokenSpaceGuid.PcdArmUncachedMemoryMask|0x0000000040000000
+
+################################################################################
+#
+# Components Section - list of all EDK II Modules needed by this Platform
+#
+################################################################################
+[Components.common]
+ Omap35xxPkg/Library/Omap35xxTimerLib/Omap35xxTimerLib.inf
+ Omap35xxPkg/Library/OmapLib/OmapLib.inf
+ Omap35xxPkg/Library/OmapDmaLib/OmapDmaLib.inf
+
+ Omap35xxPkg/Flash/Flash.inf
+ Omap35xxPkg/MMCHSDxe/MMCHS.inf
+ Omap35xxPkg/SmbusDxe/Smbus.inf
+ Omap35xxPkg/Gpio/Gpio.inf
+ Omap35xxPkg/InterruptDxe/InterruptDxe.inf
+ Omap35xxPkg/TimerDxe/TimerDxe.inf
+ Omap35xxPkg/TPS65950Dxe/TPS65950.inf
+
+
+
diff --git a/Omap35xxPkg/PciEmulation/PciEmulation.c b/Omap35xxPkg/PciEmulation/PciEmulation.c
index 6b5528cea..0cc0faa42 100644
--- a/Omap35xxPkg/PciEmulation/PciEmulation.c
+++ b/Omap35xxPkg/PciEmulation/PciEmulation.c
@@ -1,524 +1,524 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "PciEmulation.h"
-
-EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
-
-#define HOST_CONTROLLER_OPERATION_REG_SIZE 0x44
-
-typedef struct {
- ACPI_HID_DEVICE_PATH AcpiDevicePath;
- PCI_DEVICE_PATH PciDevicePath;
- EFI_DEVICE_PATH_PROTOCOL EndDevicePath;
-} EFI_PCI_IO_DEVICE_PATH;
-
-typedef struct {
- UINT32 Signature;
- EFI_PCI_IO_DEVICE_PATH DevicePath;
- EFI_PCI_IO_PROTOCOL PciIoProtocol;
- PCI_TYPE00 *ConfigSpace;
- PCI_ROOT_BRIDGE RootBridge;
- UINTN Segment;
-} EFI_PCI_IO_PRIVATE_DATA;
-
-#define EFI_PCI_IO_PRIVATE_DATA_SIGNATURE SIGNATURE_32('p', 'c', 'i', 'o')
-#define EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(a) CR(a, EFI_PCI_IO_PRIVATE_DATA, PciIoProtocol, EFI_PCI_IO_PRIVATE_DATA_SIGNATURE)
-
-EFI_PCI_IO_DEVICE_PATH PciIoDevicePathTemplate =
-{
- {
- { ACPI_DEVICE_PATH, ACPI_DP, sizeof (ACPI_HID_DEVICE_PATH), 0},
- EISA_PNP_ID(0x0A03), // HID
- 0 // UID
- },
- {
- { HARDWARE_DEVICE_PATH, HW_PCI_DP, sizeof (PCI_DEVICE_PATH), 0},
- 0,
- 0
- },
- { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, sizeof (EFI_DEVICE_PATH_PROTOCOL), 0}
-};
-
-STATIC
-VOID
-ConfigureUSBHost (
- VOID
- )
-{
- EFI_STATUS Status;
- UINT8 Data = 0;
-
- // Take USB host out of force-standby mode
- MmioWrite32 (UHH_SYSCONFIG, UHH_SYSCONFIG_MIDLEMODE_NO_STANDBY
- | UHH_SYSCONFIG_CLOCKACTIVITY_ON
- | UHH_SYSCONFIG_SIDLEMODE_NO_STANDBY
- | UHH_SYSCONFIG_ENAWAKEUP_ENABLE
- | UHH_SYSCONFIG_AUTOIDLE_ALWAYS_RUN);
- MmioWrite32 (UHH_HOSTCONFIG, UHH_HOSTCONFIG_P3_CONNECT_STATUS_DISCONNECT
- | UHH_HOSTCONFIG_P2_CONNECT_STATUS_DISCONNECT
- | UHH_HOSTCONFIG_P1_CONNECT_STATUS_DISCONNECT
- | UHH_HOSTCONFIG_ENA_INCR_ALIGN_DISABLE
- | UHH_HOSTCONFIG_ENA_INCR16_ENABLE
- | UHH_HOSTCONFIG_ENA_INCR8_ENABLE
- | UHH_HOSTCONFIG_ENA_INCR4_ENABLE
- | UHH_HOSTCONFIG_AUTOPPD_ON_OVERCUR_EN_ON
- | UHH_HOSTCONFIG_P1_ULPI_BYPASS_ULPI_MODE);
-
- // USB reset (GPIO 147 - Port 5 pin 19) output high
- MmioAnd32 (GPIO5_BASE + GPIO_OE, ~BIT19);
- MmioWrite32 (GPIO5_BASE + GPIO_SETDATAOUT, BIT19);
-
- // Get the Power IC protocol
- Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
- ASSERT_EFI_ERROR (Status);
-
- // Power the USB PHY
- Data = VAUX_DEV_GRP_P1;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VAUX2_DEV_GRP), 1, &Data);
- ASSERT_EFI_ERROR(Status);
-
- Data = VAUX_DEDICATED_18V;
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VAUX2_DEDICATED), 1, &Data);
- ASSERT_EFI_ERROR (Status);
-
- // Enable power to the USB hub
- Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID3, LEDEN), 1, &Data);
- ASSERT_EFI_ERROR (Status);
-
- // LEDAON controls the power to the USB host, PWM is disabled
- Data &= ~LEDAPWM;
- Data |= LEDAON;
-
- Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID3, LEDEN), 1, &Data);
- ASSERT_EFI_ERROR (Status);
-}
-
-
-EFI_STATUS
-PciIoPollMem (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 BarIndex,
- IN UINT64 Offset,
- IN UINT64 Mask,
- IN UINT64 Value,
- IN UINT64 Delay,
- OUT UINT64 *Result
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-PciIoPollIo (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 BarIndex,
- IN UINT64 Offset,
- IN UINT64 Mask,
- IN UINT64 Value,
- IN UINT64 Delay,
- OUT UINT64 *Result
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-PciIoMemRead (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 BarIndex,
- IN UINT64 Offset,
- IN UINTN Count,
- IN OUT VOID *Buffer
- )
-{
- EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
-
- return PciRootBridgeIoMemRead (&Private->RootBridge.Io,
- (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width,
- Private->ConfigSpace->Device.Bar[BarIndex] + Offset,
- Count,
- Buffer
- );
-}
-
-EFI_STATUS
-PciIoMemWrite (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 BarIndex,
- IN UINT64 Offset,
- IN UINTN Count,
- IN OUT VOID *Buffer
- )
-{
- EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
-
- return PciRootBridgeIoMemWrite (&Private->RootBridge.Io,
- (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width,
- Private->ConfigSpace->Device.Bar[BarIndex] + Offset,
- Count,
- Buffer
- );
-}
-
-EFI_STATUS
-PciIoIoRead (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 BarIndex,
- IN UINT64 Offset,
- IN UINTN Count,
- IN OUT VOID *Buffer
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-PciIoIoWrite (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 BarIndex,
- IN UINT64 Offset,
- IN UINTN Count,
- IN OUT VOID *Buffer
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-PciIoPciRead (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT32 Offset,
- IN UINTN Count,
- IN OUT VOID *Buffer
- )
-{
- EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
-
- return PciRootBridgeIoMemRW ((EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width,
- Count,
- TRUE,
- (PTR)(UINTN)Buffer,
- TRUE,
- (PTR)(UINTN)(((UINT8 *)Private->ConfigSpace) + Offset)
- );
-}
-
-EFI_STATUS
-PciIoPciWrite (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT32 Offset,
- IN UINTN Count,
- IN OUT VOID *Buffer
- )
-{
- EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
-
- return PciRootBridgeIoMemRW ((EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width,
- Count,
- TRUE,
- (PTR)(UINTN)(((UINT8 *)Private->ConfigSpace) + Offset),
- TRUE,
- (PTR)(UINTN)Buffer
- );
-}
-
-EFI_STATUS
-PciIoCopyMem (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
- IN UINT8 DestBarIndex,
- IN UINT64 DestOffset,
- IN UINT8 SrcBarIndex,
- IN UINT64 SrcOffset,
- IN UINTN Count
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-PciIoMap (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_OPERATION Operation,
- IN VOID *HostAddress,
- IN OUT UINTN *NumberOfBytes,
- OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
- OUT VOID **Mapping
- )
-{
- DMA_MAP_OPERATION DmaOperation;
-
- if (Operation == EfiPciIoOperationBusMasterRead) {
- DmaOperation = MapOperationBusMasterRead;
- } else if (Operation == EfiPciIoOperationBusMasterWrite) {
- DmaOperation = MapOperationBusMasterWrite;
- } else if (Operation == EfiPciIoOperationBusMasterCommonBuffer) {
- DmaOperation = MapOperationBusMasterCommonBuffer;
- } else {
- return EFI_INVALID_PARAMETER;
- }
- return DmaMap (DmaOperation, HostAddress, NumberOfBytes, DeviceAddress, Mapping);
-}
-
-EFI_STATUS
-PciIoUnmap (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN VOID *Mapping
- )
-{
- return DmaUnmap (Mapping);
-}
-
-EFI_STATUS
-PciIoAllocateBuffer (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_ALLOCATE_TYPE Type,
- IN EFI_MEMORY_TYPE MemoryType,
- IN UINTN Pages,
- OUT VOID **HostAddress,
- IN UINT64 Attributes
- )
-{
- if (Attributes & EFI_PCI_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) {
- // Check this
- return EFI_UNSUPPORTED;
- }
-
- return DmaAllocateBuffer (MemoryType, Pages, HostAddress);
-}
-
-
-EFI_STATUS
-PciIoFreeBuffer (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN UINTN Pages,
- IN VOID *HostAddress
- )
-{
- return DmaFreeBuffer (Pages, HostAddress);
-}
-
-
-EFI_STATUS
-PciIoFlush (
- IN EFI_PCI_IO_PROTOCOL *This
- )
-{
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-PciIoGetLocation (
- IN EFI_PCI_IO_PROTOCOL *This,
- OUT UINTN *SegmentNumber,
- OUT UINTN *BusNumber,
- OUT UINTN *DeviceNumber,
- OUT UINTN *FunctionNumber
- )
-{
- EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
-
- if (SegmentNumber != NULL) {
- *SegmentNumber = Private->Segment;
- }
-
- if (BusNumber != NULL) {
- *BusNumber = 0xff;
- }
-
- if (DeviceNumber != NULL) {
- *DeviceNumber = 0;
- }
-
- if (FunctionNumber != NULL) {
- *FunctionNumber = 0;
- }
-
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-PciIoAttributes (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation,
- IN UINT64 Attributes,
- OUT UINT64 *Result OPTIONAL
- )
-{
- switch (Operation) {
- case EfiPciIoAttributeOperationGet:
- case EfiPciIoAttributeOperationSupported:
- if (Result == NULL) {
- return EFI_INVALID_PARAMETER;
- }
- // We are not a real PCI device so just say things we kind of do
- *Result = EFI_PCI_IO_ATTRIBUTE_MEMORY | EFI_PCI_IO_ATTRIBUTE_BUS_MASTER | EFI_PCI_DEVICE_ENABLE;
- break;
-
- case EfiPciIoAttributeOperationSet:
- case EfiPciIoAttributeOperationEnable:
- case EfiPciIoAttributeOperationDisable:
- // Since we are not a real PCI device no enable/set or disable operations exist.
- return EFI_SUCCESS;
-
- default:
- ASSERT (FALSE);
- return EFI_INVALID_PARAMETER;
- };
- return EFI_SUCCESS;
-}
-
-EFI_STATUS
-PciIoGetBarAttributes (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN UINT8 BarIndex,
- OUT UINT64 *Supports, OPTIONAL
- OUT VOID **Resources OPTIONAL
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_STATUS
-PciIoSetBarAttributes (
- IN EFI_PCI_IO_PROTOCOL *This,
- IN UINT64 Attributes,
- IN UINT8 BarIndex,
- IN OUT UINT64 *Offset,
- IN OUT UINT64 *Length
- )
-{
- ASSERT (FALSE);
- return EFI_UNSUPPORTED;
-}
-
-EFI_PCI_IO_PROTOCOL PciIoTemplate =
-{
- PciIoPollMem,
- PciIoPollIo,
- PciIoMemRead,
- PciIoMemWrite,
- PciIoIoRead,
- PciIoIoWrite,
- PciIoPciRead,
- PciIoPciWrite,
- PciIoCopyMem,
- PciIoMap,
- PciIoUnmap,
- PciIoAllocateBuffer,
- PciIoFreeBuffer,
- PciIoFlush,
- PciIoGetLocation,
- PciIoAttributes,
- PciIoGetBarAttributes,
- PciIoSetBarAttributes,
- 0,
- 0
-};
-
-EFI_STATUS
-EFIAPI
-PciEmulationEntryPoint (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
- EFI_HANDLE Handle;
- EFI_PCI_IO_PRIVATE_DATA *Private;
- UINT8 CapabilityLength;
- UINT8 PhysicalPorts;
- UINTN Count;
-
-
- //Configure USB host for OMAP3530.
- ConfigureUSBHost();
-
- // Create a private structure
- Private = AllocatePool(sizeof(EFI_PCI_IO_PRIVATE_DATA));
- if (Private == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- return Status;
- }
-
- Private->Signature = EFI_PCI_IO_PRIVATE_DATA_SIGNATURE; // Fill in signature
- Private->RootBridge.Signature = PCI_ROOT_BRIDGE_SIGNATURE; // Fake Root Bridge structure needs a signature too
- Private->RootBridge.MemoryStart = USB_EHCI_HCCAPBASE; // Get the USB capability register base
- Private->Segment = 0; // Default to segment zero
-
- // Find out the capability register length and number of physical ports.
- CapabilityLength = MmioRead8(Private->RootBridge.MemoryStart);
- PhysicalPorts = (MmioRead32 (Private->RootBridge.MemoryStart + 0x4)) & 0x0000000F;
-
- // Calculate the total size of the USB registers.
- Private->RootBridge.MemorySize = CapabilityLength + (HOST_CONTROLLER_OPERATION_REG_SIZE + ((4 * PhysicalPorts) - 1));
-
- // Enable Port Power bit in Port status and control registers in EHCI register space.
- // Port Power Control (PPC) bit in the HCSPARAMS register is already set which indicates
- // host controller implementation includes port power control.
- for (Count = 0; Count < PhysicalPorts; Count++) {
- MmioOr32 ((Private->RootBridge.MemoryStart + CapabilityLength + HOST_CONTROLLER_OPERATION_REG_SIZE + 4*Count), 0x00001000);
- }
-
- // Create fake PCI config space.
- Private->ConfigSpace = AllocateZeroPool(sizeof(PCI_TYPE00));
- if (Private->ConfigSpace == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- FreePool(Private);
- return Status;
- }
-
- // Configure PCI config space
- Private->ConfigSpace->Hdr.VendorId = 0x3530;
- Private->ConfigSpace->Hdr.DeviceId = 0x3530;
- Private->ConfigSpace->Hdr.ClassCode[0] = 0x20;
- Private->ConfigSpace->Hdr.ClassCode[1] = 0x03;
- Private->ConfigSpace->Hdr.ClassCode[2] = 0x0C;
- Private->ConfigSpace->Device.Bar[0] = Private->RootBridge.MemoryStart;
-
- Handle = NULL;
-
- // Unique device path.
- CopyMem(&Private->DevicePath, &PciIoDevicePathTemplate, sizeof(PciIoDevicePathTemplate));
- Private->DevicePath.AcpiDevicePath.UID = 0;
-
- // Copy protocol structure
- CopyMem(&Private->PciIoProtocol, &PciIoTemplate, sizeof(PciIoTemplate));
-
- Status = gBS->InstallMultipleProtocolInterfaces(&Handle,
- &gEfiPciIoProtocolGuid, &Private->PciIoProtocol,
- &gEfiDevicePathProtocolGuid, &Private->DevicePath,
- NULL);
- if (EFI_ERROR(Status)) {
- DEBUG((EFI_D_ERROR, "PciEmulationEntryPoint InstallMultipleProtocolInterfaces() failed.\n"));
- }
-
- return Status;
-}
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include "PciEmulation.h"
+
+EMBEDDED_EXTERNAL_DEVICE *gTPS65950;
+
+#define HOST_CONTROLLER_OPERATION_REG_SIZE 0x44
+
+typedef struct {
+ ACPI_HID_DEVICE_PATH AcpiDevicePath;
+ PCI_DEVICE_PATH PciDevicePath;
+ EFI_DEVICE_PATH_PROTOCOL EndDevicePath;
+} EFI_PCI_IO_DEVICE_PATH;
+
+typedef struct {
+ UINT32 Signature;
+ EFI_PCI_IO_DEVICE_PATH DevicePath;
+ EFI_PCI_IO_PROTOCOL PciIoProtocol;
+ PCI_TYPE00 *ConfigSpace;
+ PCI_ROOT_BRIDGE RootBridge;
+ UINTN Segment;
+} EFI_PCI_IO_PRIVATE_DATA;
+
+#define EFI_PCI_IO_PRIVATE_DATA_SIGNATURE SIGNATURE_32('p', 'c', 'i', 'o')
+#define EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(a) CR(a, EFI_PCI_IO_PRIVATE_DATA, PciIoProtocol, EFI_PCI_IO_PRIVATE_DATA_SIGNATURE)
+
+EFI_PCI_IO_DEVICE_PATH PciIoDevicePathTemplate =
+{
+ {
+ { ACPI_DEVICE_PATH, ACPI_DP, sizeof (ACPI_HID_DEVICE_PATH), 0},
+ EISA_PNP_ID(0x0A03), // HID
+ 0 // UID
+ },
+ {
+ { HARDWARE_DEVICE_PATH, HW_PCI_DP, sizeof (PCI_DEVICE_PATH), 0},
+ 0,
+ 0
+ },
+ { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, sizeof (EFI_DEVICE_PATH_PROTOCOL), 0}
+};
+
+STATIC
+VOID
+ConfigureUSBHost (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data = 0;
+
+ // Take USB host out of force-standby mode
+ MmioWrite32 (UHH_SYSCONFIG, UHH_SYSCONFIG_MIDLEMODE_NO_STANDBY
+ | UHH_SYSCONFIG_CLOCKACTIVITY_ON
+ | UHH_SYSCONFIG_SIDLEMODE_NO_STANDBY
+ | UHH_SYSCONFIG_ENAWAKEUP_ENABLE
+ | UHH_SYSCONFIG_AUTOIDLE_ALWAYS_RUN);
+ MmioWrite32 (UHH_HOSTCONFIG, UHH_HOSTCONFIG_P3_CONNECT_STATUS_DISCONNECT
+ | UHH_HOSTCONFIG_P2_CONNECT_STATUS_DISCONNECT
+ | UHH_HOSTCONFIG_P1_CONNECT_STATUS_DISCONNECT
+ | UHH_HOSTCONFIG_ENA_INCR_ALIGN_DISABLE
+ | UHH_HOSTCONFIG_ENA_INCR16_ENABLE
+ | UHH_HOSTCONFIG_ENA_INCR8_ENABLE
+ | UHH_HOSTCONFIG_ENA_INCR4_ENABLE
+ | UHH_HOSTCONFIG_AUTOPPD_ON_OVERCUR_EN_ON
+ | UHH_HOSTCONFIG_P1_ULPI_BYPASS_ULPI_MODE);
+
+ // USB reset (GPIO 147 - Port 5 pin 19) output high
+ MmioAnd32 (GPIO5_BASE + GPIO_OE, ~BIT19);
+ MmioWrite32 (GPIO5_BASE + GPIO_SETDATAOUT, BIT19);
+
+ // Get the Power IC protocol
+ Status = gBS->LocateProtocol (&gEmbeddedExternalDeviceProtocolGuid, NULL, (VOID **)&gTPS65950);
+ ASSERT_EFI_ERROR (Status);
+
+ // Power the USB PHY
+ Data = VAUX_DEV_GRP_P1;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VAUX2_DEV_GRP), 1, &Data);
+ ASSERT_EFI_ERROR(Status);
+
+ Data = VAUX_DEDICATED_18V;
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID4, VAUX2_DEDICATED), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+
+ // Enable power to the USB hub
+ Status = gTPS65950->Read (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID3, LEDEN), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+
+ // LEDAON controls the power to the USB host, PWM is disabled
+ Data &= ~LEDAPWM;
+ Data |= LEDAON;
+
+ Status = gTPS65950->Write (gTPS65950, EXTERNAL_DEVICE_REGISTER(I2C_ADDR_GRP_ID3, LEDEN), 1, &Data);
+ ASSERT_EFI_ERROR (Status);
+}
+
+
+EFI_STATUS
+PciIoPollMem (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 BarIndex,
+ IN UINT64 Offset,
+ IN UINT64 Mask,
+ IN UINT64 Value,
+ IN UINT64 Delay,
+ OUT UINT64 *Result
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+PciIoPollIo (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 BarIndex,
+ IN UINT64 Offset,
+ IN UINT64 Mask,
+ IN UINT64 Value,
+ IN UINT64 Delay,
+ OUT UINT64 *Result
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+PciIoMemRead (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 BarIndex,
+ IN UINT64 Offset,
+ IN UINTN Count,
+ IN OUT VOID *Buffer
+ )
+{
+ EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
+
+ return PciRootBridgeIoMemRead (&Private->RootBridge.Io,
+ (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width,
+ Private->ConfigSpace->Device.Bar[BarIndex] + Offset,
+ Count,
+ Buffer
+ );
+}
+
+EFI_STATUS
+PciIoMemWrite (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 BarIndex,
+ IN UINT64 Offset,
+ IN UINTN Count,
+ IN OUT VOID *Buffer
+ )
+{
+ EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
+
+ return PciRootBridgeIoMemWrite (&Private->RootBridge.Io,
+ (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width,
+ Private->ConfigSpace->Device.Bar[BarIndex] + Offset,
+ Count,
+ Buffer
+ );
+}
+
+EFI_STATUS
+PciIoIoRead (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 BarIndex,
+ IN UINT64 Offset,
+ IN UINTN Count,
+ IN OUT VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+PciIoIoWrite (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 BarIndex,
+ IN UINT64 Offset,
+ IN UINTN Count,
+ IN OUT VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+PciIoPciRead (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT32 Offset,
+ IN UINTN Count,
+ IN OUT VOID *Buffer
+ )
+{
+ EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
+
+ return PciRootBridgeIoMemRW ((EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width,
+ Count,
+ TRUE,
+ (PTR)(UINTN)Buffer,
+ TRUE,
+ (PTR)(UINTN)(((UINT8 *)Private->ConfigSpace) + Offset)
+ );
+}
+
+EFI_STATUS
+PciIoPciWrite (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT32 Offset,
+ IN UINTN Count,
+ IN OUT VOID *Buffer
+ )
+{
+ EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
+
+ return PciRootBridgeIoMemRW ((EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width,
+ Count,
+ TRUE,
+ (PTR)(UINTN)(((UINT8 *)Private->ConfigSpace) + Offset),
+ TRUE,
+ (PTR)(UINTN)Buffer
+ );
+}
+
+EFI_STATUS
+PciIoCopyMem (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_WIDTH Width,
+ IN UINT8 DestBarIndex,
+ IN UINT64 DestOffset,
+ IN UINT8 SrcBarIndex,
+ IN UINT64 SrcOffset,
+ IN UINTN Count
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+PciIoMap (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_OPERATION Operation,
+ IN VOID *HostAddress,
+ IN OUT UINTN *NumberOfBytes,
+ OUT EFI_PHYSICAL_ADDRESS *DeviceAddress,
+ OUT VOID **Mapping
+ )
+{
+ DMA_MAP_OPERATION DmaOperation;
+
+ if (Operation == EfiPciIoOperationBusMasterRead) {
+ DmaOperation = MapOperationBusMasterRead;
+ } else if (Operation == EfiPciIoOperationBusMasterWrite) {
+ DmaOperation = MapOperationBusMasterWrite;
+ } else if (Operation == EfiPciIoOperationBusMasterCommonBuffer) {
+ DmaOperation = MapOperationBusMasterCommonBuffer;
+ } else {
+ return EFI_INVALID_PARAMETER;
+ }
+ return DmaMap (DmaOperation, HostAddress, NumberOfBytes, DeviceAddress, Mapping);
+}
+
+EFI_STATUS
+PciIoUnmap (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN VOID *Mapping
+ )
+{
+ return DmaUnmap (Mapping);
+}
+
+EFI_STATUS
+PciIoAllocateBuffer (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_ALLOCATE_TYPE Type,
+ IN EFI_MEMORY_TYPE MemoryType,
+ IN UINTN Pages,
+ OUT VOID **HostAddress,
+ IN UINT64 Attributes
+ )
+{
+ if (Attributes & EFI_PCI_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER) {
+ // Check this
+ return EFI_UNSUPPORTED;
+ }
+
+ return DmaAllocateBuffer (MemoryType, Pages, HostAddress);
+}
+
+
+EFI_STATUS
+PciIoFreeBuffer (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN UINTN Pages,
+ IN VOID *HostAddress
+ )
+{
+ return DmaFreeBuffer (Pages, HostAddress);
+}
+
+
+EFI_STATUS
+PciIoFlush (
+ IN EFI_PCI_IO_PROTOCOL *This
+ )
+{
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+PciIoGetLocation (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ OUT UINTN *SegmentNumber,
+ OUT UINTN *BusNumber,
+ OUT UINTN *DeviceNumber,
+ OUT UINTN *FunctionNumber
+ )
+{
+ EFI_PCI_IO_PRIVATE_DATA *Private = EFI_PCI_IO_PRIVATE_DATA_FROM_THIS(This);
+
+ if (SegmentNumber != NULL) {
+ *SegmentNumber = Private->Segment;
+ }
+
+ if (BusNumber != NULL) {
+ *BusNumber = 0xff;
+ }
+
+ if (DeviceNumber != NULL) {
+ *DeviceNumber = 0;
+ }
+
+ if (FunctionNumber != NULL) {
+ *FunctionNumber = 0;
+ }
+
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+PciIoAttributes (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation,
+ IN UINT64 Attributes,
+ OUT UINT64 *Result OPTIONAL
+ )
+{
+ switch (Operation) {
+ case EfiPciIoAttributeOperationGet:
+ case EfiPciIoAttributeOperationSupported:
+ if (Result == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ // We are not a real PCI device so just say things we kind of do
+ *Result = EFI_PCI_IO_ATTRIBUTE_MEMORY | EFI_PCI_IO_ATTRIBUTE_BUS_MASTER | EFI_PCI_DEVICE_ENABLE;
+ break;
+
+ case EfiPciIoAttributeOperationSet:
+ case EfiPciIoAttributeOperationEnable:
+ case EfiPciIoAttributeOperationDisable:
+ // Since we are not a real PCI device no enable/set or disable operations exist.
+ return EFI_SUCCESS;
+
+ default:
+ ASSERT (FALSE);
+ return EFI_INVALID_PARAMETER;
+ };
+ return EFI_SUCCESS;
+}
+
+EFI_STATUS
+PciIoGetBarAttributes (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN UINT8 BarIndex,
+ OUT UINT64 *Supports, OPTIONAL
+ OUT VOID **Resources OPTIONAL
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_STATUS
+PciIoSetBarAttributes (
+ IN EFI_PCI_IO_PROTOCOL *This,
+ IN UINT64 Attributes,
+ IN UINT8 BarIndex,
+ IN OUT UINT64 *Offset,
+ IN OUT UINT64 *Length
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+EFI_PCI_IO_PROTOCOL PciIoTemplate =
+{
+ PciIoPollMem,
+ PciIoPollIo,
+ PciIoMemRead,
+ PciIoMemWrite,
+ PciIoIoRead,
+ PciIoIoWrite,
+ PciIoPciRead,
+ PciIoPciWrite,
+ PciIoCopyMem,
+ PciIoMap,
+ PciIoUnmap,
+ PciIoAllocateBuffer,
+ PciIoFreeBuffer,
+ PciIoFlush,
+ PciIoGetLocation,
+ PciIoAttributes,
+ PciIoGetBarAttributes,
+ PciIoSetBarAttributes,
+ 0,
+ 0
+};
+
+EFI_STATUS
+EFIAPI
+PciEmulationEntryPoint (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+ EFI_PCI_IO_PRIVATE_DATA *Private;
+ UINT8 CapabilityLength;
+ UINT8 PhysicalPorts;
+ UINTN Count;
+
+
+ //Configure USB host for OMAP3530.
+ ConfigureUSBHost();
+
+ // Create a private structure
+ Private = AllocatePool(sizeof(EFI_PCI_IO_PRIVATE_DATA));
+ if (Private == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ return Status;
+ }
+
+ Private->Signature = EFI_PCI_IO_PRIVATE_DATA_SIGNATURE; // Fill in signature
+ Private->RootBridge.Signature = PCI_ROOT_BRIDGE_SIGNATURE; // Fake Root Bridge structure needs a signature too
+ Private->RootBridge.MemoryStart = USB_EHCI_HCCAPBASE; // Get the USB capability register base
+ Private->Segment = 0; // Default to segment zero
+
+ // Find out the capability register length and number of physical ports.
+ CapabilityLength = MmioRead8(Private->RootBridge.MemoryStart);
+ PhysicalPorts = (MmioRead32 (Private->RootBridge.MemoryStart + 0x4)) & 0x0000000F;
+
+ // Calculate the total size of the USB registers.
+ Private->RootBridge.MemorySize = CapabilityLength + (HOST_CONTROLLER_OPERATION_REG_SIZE + ((4 * PhysicalPorts) - 1));
+
+ // Enable Port Power bit in Port status and control registers in EHCI register space.
+ // Port Power Control (PPC) bit in the HCSPARAMS register is already set which indicates
+ // host controller implementation includes port power control.
+ for (Count = 0; Count < PhysicalPorts; Count++) {
+ MmioOr32 ((Private->RootBridge.MemoryStart + CapabilityLength + HOST_CONTROLLER_OPERATION_REG_SIZE + 4*Count), 0x00001000);
+ }
+
+ // Create fake PCI config space.
+ Private->ConfigSpace = AllocateZeroPool(sizeof(PCI_TYPE00));
+ if (Private->ConfigSpace == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ FreePool(Private);
+ return Status;
+ }
+
+ // Configure PCI config space
+ Private->ConfigSpace->Hdr.VendorId = 0x3530;
+ Private->ConfigSpace->Hdr.DeviceId = 0x3530;
+ Private->ConfigSpace->Hdr.ClassCode[0] = 0x20;
+ Private->ConfigSpace->Hdr.ClassCode[1] = 0x03;
+ Private->ConfigSpace->Hdr.ClassCode[2] = 0x0C;
+ Private->ConfigSpace->Device.Bar[0] = Private->RootBridge.MemoryStart;
+
+ Handle = NULL;
+
+ // Unique device path.
+ CopyMem(&Private->DevicePath, &PciIoDevicePathTemplate, sizeof(PciIoDevicePathTemplate));
+ Private->DevicePath.AcpiDevicePath.UID = 0;
+
+ // Copy protocol structure
+ CopyMem(&Private->PciIoProtocol, &PciIoTemplate, sizeof(PciIoTemplate));
+
+ Status = gBS->InstallMultipleProtocolInterfaces(&Handle,
+ &gEfiPciIoProtocolGuid, &Private->PciIoProtocol,
+ &gEfiDevicePathProtocolGuid, &Private->DevicePath,
+ NULL);
+ if (EFI_ERROR(Status)) {
+ DEBUG((EFI_D_ERROR, "PciEmulationEntryPoint InstallMultipleProtocolInterfaces() failed.\n"));
+ }
+
+ return Status;
+}
+
diff --git a/Omap35xxPkg/PciEmulation/PciEmulation.h b/Omap35xxPkg/PciEmulation/PciEmulation.h
index 7db4f330c..2a381f2f9 100644
--- a/Omap35xxPkg/PciEmulation/PciEmulation.h
+++ b/Omap35xxPkg/PciEmulation/PciEmulation.h
@@ -40,7 +40,7 @@
#include <IndustryStandard/Pci22.h>
#include <IndustryStandard/Acpi.h>
-#include <Omap3530/Omap3530.h>
+#include <Omap3530/Omap3530.h>
diff --git a/Omap35xxPkg/PciEmulation/PciEmulation.inf b/Omap35xxPkg/PciEmulation/PciEmulation.inf
index 8567b6938..ab3754179 100644
--- a/Omap35xxPkg/PciEmulation/PciEmulation.inf
+++ b/Omap35xxPkg/PciEmulation/PciEmulation.inf
@@ -54,4 +54,4 @@
[Depex]
gEfiMetronomeArchProtocolGuid AND
gEmbeddedExternalDeviceProtocolGuid
- \ No newline at end of file
+ \ No newline at end of file
diff --git a/Omap35xxPkg/SmbusDxe/Smbus.c b/Omap35xxPkg/SmbusDxe/Smbus.c
index 86dc65c87..3b88974ae 100644
--- a/Omap35xxPkg/SmbusDxe/Smbus.c
+++ b/Omap35xxPkg/SmbusDxe/Smbus.c
@@ -1,325 +1,325 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Uefi.h>
-#include <Omap3530/Omap3530.h>
-
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-
-#include <Protocol/SmbusHc.h>
-
-#define MAX_RETRY 1000
-
-//
-// Internal Functions
-//
-STATIC
-EFI_STATUS
-WaitForBusBusy (
- VOID
- )
-{
- UINTN Retry = 0;
-
- while (++Retry < MAX_RETRY && (MmioRead16(I2C_STAT) & BB) == 0x1);
-
- if (Retry == MAX_RETRY) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-PollForStatus(
- UINT16 StatusBit
- )
-{
- UINTN Retry = 0;
-
- while(Retry < MAX_RETRY) {
- if (MmioRead16(I2C_STAT) & StatusBit) {
- //Clear particular status bit from Status register.
- MmioOr16(I2C_STAT, StatusBit);
- break;
- }
- Retry++;
- }
-
- if (Retry == MAX_RETRY) {
- return EFI_TIMEOUT;
- }
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-ConfigureI2c (
- VOID
- )
-{
- //Program prescaler to obtain 12-MHz clock
- MmioWrite16(I2C_PSC, 0x0000);
-
- //Program SCLL and SCLH
- //NOTE: Following values are the register dump after U-Boot code executed.
- //We need to figure out how its calculated based on the I2C functional clock and I2C_PSC.
- MmioWrite16(I2C_SCLL, 0x0035);
- MmioWrite16(I2C_SCLH, 0x0035);
-
- //Take the I2C controller out of reset.
- MmioOr16(I2C_CON, I2C_EN);
-
- //Initialize the I2C controller.
-
- //Set I2C controller in Master mode.
- MmioOr16(I2C_CON, MST);
-
- //Enable interrupts for receive/transmit mode.
- MmioOr16(I2C_IE, (XRDY_IE | RRDY_IE | ARDY_IE | NACK_IE));
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-I2CReadOneByte (
- UINT8 *Data
- )
-{
- EFI_STATUS Status;
-
- //I2C bus status checking
- Status = WaitForBusBusy();
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- //Poll till Receive ready bit is set.
- Status = PollForStatus(RRDY);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- *Data = MmioRead8(I2C_DATA);
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-I2CWriteOneByte (
- UINT8 Data
- )
-{
- EFI_STATUS Status;
-
- //I2C bus status checking
- Status = WaitForBusBusy();
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- //Data transfer
- //Poll till Transmit ready bit is set
- Status = PollForStatus(XRDY);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- MmioWrite8(I2C_DATA, Data);
-
- //Wait and check if the NACK is not set.
- gBS->Stall(1000);
- if (MmioRead16(I2C_STAT) & NACK) {
- return EFI_DEVICE_ERROR;
- }
-
- return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-SmbusBlockRead (
- OUT UINT8 *Buffer,
- IN UINTN Length
- )
-{
- UINTN Index = 0;
- EFI_STATUS Status = EFI_SUCCESS;
-
- //Transfer configuration for receiving data.
- MmioWrite16(I2C_CNT, Length);
- //Need stop bit before sending data.
- MmioWrite16(I2C_CON, (I2C_EN | MST | STP | STT));
-
- while (Index < Length) {
- //Read a byte
- Status = I2CReadOneByte(&Buffer[Index++]);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- }
-
- //Transfer completion
- Status = PollForStatus(ARDY);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- return Status;
-}
-
-STATIC
-EFI_STATUS
-SmbusBlockWrite (
- IN UINT8 *Buffer,
- IN UINTN Length
- )
-{
- UINTN Index = 0;
- EFI_STATUS Status = EFI_SUCCESS;
-
- //Transfer configuration for transmitting data
- MmioWrite16(I2C_CNT, Length);
- MmioWrite16(I2C_CON, (I2C_EN | TRX | MST | STT | STP));
-
- while (Index < Length) {
- //Send a byte
- Status = I2CWriteOneByte(Buffer[Index++]);
- if (EFI_ERROR(Status)) {
- return Status;
- }
- }
-
- //Transfer completion
- Status = PollForStatus(ARDY);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- return Status;
-}
-
-//
-// Public Functions.
-//
-EFI_STATUS
-EFIAPI
-SmbusExecute (
- IN CONST EFI_SMBUS_HC_PROTOCOL *This,
- IN CONST EFI_SMBUS_DEVICE_ADDRESS SlaveAddress,
- IN CONST EFI_SMBUS_DEVICE_COMMAND Command,
- IN CONST EFI_SMBUS_OPERATION Operation,
- IN CONST BOOLEAN PecCheck,
- IN OUT UINTN *Length,
- IN OUT VOID *Buffer
- )
-{
- UINT8 *ByteBuffer = Buffer;
- EFI_STATUS Status = EFI_SUCCESS;
- UINT8 SlaveAddr = (UINT8)(SlaveAddress.SmbusDeviceAddress);
-
- if (PecCheck) {
- return EFI_UNSUPPORTED;
- }
-
- if ((Operation != EfiSmbusWriteBlock) && (Operation != EfiSmbusReadBlock)) {
- return EFI_UNSUPPORTED;
- }
-
- //Set the Slave address.
- MmioWrite16(I2C_SA, SlaveAddr);
-
- if (Operation == EfiSmbusReadBlock) {
- Status = SmbusBlockRead(ByteBuffer, *Length);
- } else if (Operation == EfiSmbusWriteBlock) {
- Status = SmbusBlockWrite(ByteBuffer, *Length);
- }
-
- return Status;
-}
-
-EFI_STATUS
-EFIAPI
-SmbusArpDevice (
- IN CONST EFI_SMBUS_HC_PROTOCOL *This,
- IN BOOLEAN ArpAll,
- IN EFI_SMBUS_UDID *SmbusUdid OPTIONAL,
- IN OUT EFI_SMBUS_DEVICE_ADDRESS *SlaveAddress OPTIONAL
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-
-EFI_STATUS
-EFIAPI
-SmbusGetArpMap (
- IN CONST EFI_SMBUS_HC_PROTOCOL *This,
- IN OUT UINTN *Length,
- IN OUT EFI_SMBUS_DEVICE_MAP **SmbusDeviceMap
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-
-EFI_STATUS
-EFIAPI
-SmbusNotify (
- IN CONST EFI_SMBUS_HC_PROTOCOL *This,
- IN CONST EFI_SMBUS_DEVICE_ADDRESS SlaveAddress,
- IN CONST UINTN Data,
- IN CONST EFI_SMBUS_NOTIFY_FUNCTION NotifyFunction
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-EFI_SMBUS_HC_PROTOCOL SmbusProtocol =
-{
- SmbusExecute,
- SmbusArpDevice,
- SmbusGetArpMap,
- SmbusNotify
-};
-
-EFI_STATUS
-InitializeSmbus (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_HANDLE Handle = NULL;
- EFI_STATUS Status;
-
- //Configure I2C controller.
- Status = ConfigureI2c();
- if (EFI_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "InitializeI2c fails.\n"));
- return Status;
- }
-
- // Install the SMBUS interface
- Status = gBS->InstallMultipleProtocolInterfaces(&Handle, &gEfiSmbusHcProtocolGuid, &SmbusProtocol, NULL);
- ASSERT_EFI_ERROR(Status);
-
- return Status;
-}
-
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Uefi.h>
+#include <Omap3530/Omap3530.h>
+
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include <Protocol/SmbusHc.h>
+
+#define MAX_RETRY 1000
+
+//
+// Internal Functions
+//
+STATIC
+EFI_STATUS
+WaitForBusBusy (
+ VOID
+ )
+{
+ UINTN Retry = 0;
+
+ while (++Retry < MAX_RETRY && (MmioRead16(I2C_STAT) & BB) == 0x1);
+
+ if (Retry == MAX_RETRY) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+PollForStatus(
+ UINT16 StatusBit
+ )
+{
+ UINTN Retry = 0;
+
+ while(Retry < MAX_RETRY) {
+ if (MmioRead16(I2C_STAT) & StatusBit) {
+ //Clear particular status bit from Status register.
+ MmioOr16(I2C_STAT, StatusBit);
+ break;
+ }
+ Retry++;
+ }
+
+ if (Retry == MAX_RETRY) {
+ return EFI_TIMEOUT;
+ }
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+ConfigureI2c (
+ VOID
+ )
+{
+ //Program prescaler to obtain 12-MHz clock
+ MmioWrite16(I2C_PSC, 0x0000);
+
+ //Program SCLL and SCLH
+ //NOTE: Following values are the register dump after U-Boot code executed.
+ //We need to figure out how its calculated based on the I2C functional clock and I2C_PSC.
+ MmioWrite16(I2C_SCLL, 0x0035);
+ MmioWrite16(I2C_SCLH, 0x0035);
+
+ //Take the I2C controller out of reset.
+ MmioOr16(I2C_CON, I2C_EN);
+
+ //Initialize the I2C controller.
+
+ //Set I2C controller in Master mode.
+ MmioOr16(I2C_CON, MST);
+
+ //Enable interrupts for receive/transmit mode.
+ MmioOr16(I2C_IE, (XRDY_IE | RRDY_IE | ARDY_IE | NACK_IE));
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+I2CReadOneByte (
+ UINT8 *Data
+ )
+{
+ EFI_STATUS Status;
+
+ //I2C bus status checking
+ Status = WaitForBusBusy();
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ //Poll till Receive ready bit is set.
+ Status = PollForStatus(RRDY);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ *Data = MmioRead8(I2C_DATA);
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+I2CWriteOneByte (
+ UINT8 Data
+ )
+{
+ EFI_STATUS Status;
+
+ //I2C bus status checking
+ Status = WaitForBusBusy();
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ //Data transfer
+ //Poll till Transmit ready bit is set
+ Status = PollForStatus(XRDY);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ MmioWrite8(I2C_DATA, Data);
+
+ //Wait and check if the NACK is not set.
+ gBS->Stall(1000);
+ if (MmioRead16(I2C_STAT) & NACK) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+SmbusBlockRead (
+ OUT UINT8 *Buffer,
+ IN UINTN Length
+ )
+{
+ UINTN Index = 0;
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ //Transfer configuration for receiving data.
+ MmioWrite16(I2C_CNT, Length);
+ //Need stop bit before sending data.
+ MmioWrite16(I2C_CON, (I2C_EN | MST | STP | STT));
+
+ while (Index < Length) {
+ //Read a byte
+ Status = I2CReadOneByte(&Buffer[Index++]);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ }
+
+ //Transfer completion
+ Status = PollForStatus(ARDY);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ return Status;
+}
+
+STATIC
+EFI_STATUS
+SmbusBlockWrite (
+ IN UINT8 *Buffer,
+ IN UINTN Length
+ )
+{
+ UINTN Index = 0;
+ EFI_STATUS Status = EFI_SUCCESS;
+
+ //Transfer configuration for transmitting data
+ MmioWrite16(I2C_CNT, Length);
+ MmioWrite16(I2C_CON, (I2C_EN | TRX | MST | STT | STP));
+
+ while (Index < Length) {
+ //Send a byte
+ Status = I2CWriteOneByte(Buffer[Index++]);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+ }
+
+ //Transfer completion
+ Status = PollForStatus(ARDY);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ return Status;
+}
+
+//
+// Public Functions.
+//
+EFI_STATUS
+EFIAPI
+SmbusExecute (
+ IN CONST EFI_SMBUS_HC_PROTOCOL *This,
+ IN CONST EFI_SMBUS_DEVICE_ADDRESS SlaveAddress,
+ IN CONST EFI_SMBUS_DEVICE_COMMAND Command,
+ IN CONST EFI_SMBUS_OPERATION Operation,
+ IN CONST BOOLEAN PecCheck,
+ IN OUT UINTN *Length,
+ IN OUT VOID *Buffer
+ )
+{
+ UINT8 *ByteBuffer = Buffer;
+ EFI_STATUS Status = EFI_SUCCESS;
+ UINT8 SlaveAddr = (UINT8)(SlaveAddress.SmbusDeviceAddress);
+
+ if (PecCheck) {
+ return EFI_UNSUPPORTED;
+ }
+
+ if ((Operation != EfiSmbusWriteBlock) && (Operation != EfiSmbusReadBlock)) {
+ return EFI_UNSUPPORTED;
+ }
+
+ //Set the Slave address.
+ MmioWrite16(I2C_SA, SlaveAddr);
+
+ if (Operation == EfiSmbusReadBlock) {
+ Status = SmbusBlockRead(ByteBuffer, *Length);
+ } else if (Operation == EfiSmbusWriteBlock) {
+ Status = SmbusBlockWrite(ByteBuffer, *Length);
+ }
+
+ return Status;
+}
+
+EFI_STATUS
+EFIAPI
+SmbusArpDevice (
+ IN CONST EFI_SMBUS_HC_PROTOCOL *This,
+ IN BOOLEAN ArpAll,
+ IN EFI_SMBUS_UDID *SmbusUdid OPTIONAL,
+ IN OUT EFI_SMBUS_DEVICE_ADDRESS *SlaveAddress OPTIONAL
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+
+EFI_STATUS
+EFIAPI
+SmbusGetArpMap (
+ IN CONST EFI_SMBUS_HC_PROTOCOL *This,
+ IN OUT UINTN *Length,
+ IN OUT EFI_SMBUS_DEVICE_MAP **SmbusDeviceMap
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+
+EFI_STATUS
+EFIAPI
+SmbusNotify (
+ IN CONST EFI_SMBUS_HC_PROTOCOL *This,
+ IN CONST EFI_SMBUS_DEVICE_ADDRESS SlaveAddress,
+ IN CONST UINTN Data,
+ IN CONST EFI_SMBUS_NOTIFY_FUNCTION NotifyFunction
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+EFI_SMBUS_HC_PROTOCOL SmbusProtocol =
+{
+ SmbusExecute,
+ SmbusArpDevice,
+ SmbusGetArpMap,
+ SmbusNotify
+};
+
+EFI_STATUS
+InitializeSmbus (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_HANDLE Handle = NULL;
+ EFI_STATUS Status;
+
+ //Configure I2C controller.
+ Status = ConfigureI2c();
+ if (EFI_ERROR(Status)) {
+ DEBUG ((EFI_D_ERROR, "InitializeI2c fails.\n"));
+ return Status;
+ }
+
+ // Install the SMBUS interface
+ Status = gBS->InstallMultipleProtocolInterfaces(&Handle, &gEfiSmbusHcProtocolGuid, &SmbusProtocol, NULL);
+ ASSERT_EFI_ERROR(Status);
+
+ return Status;
+}
+
diff --git a/Omap35xxPkg/SmbusDxe/Smbus.inf b/Omap35xxPkg/SmbusDxe/Smbus.inf
index 6a8a4e919..5a4e43ea2 100644
--- a/Omap35xxPkg/SmbusDxe/Smbus.inf
+++ b/Omap35xxPkg/SmbusDxe/Smbus.inf
@@ -1,45 +1,45 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = Smbus
- FILE_GUID = d5125e0f-1226-444f-a218-0085996ed5da
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = InitializeSmbus
-
-[Sources.common]
- Smbus.c
-
-[Packages]
- MdePkg/MdePkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- PcdLib
- UefiLib
- UefiDriverEntryPoint
- MemoryAllocationLib
- IoLib
-
-[Guids]
-
-[Protocols]
- gEfiSmbusHcProtocolGuid
-
-[Pcd]
-
-[depex]
- TRUE \ No newline at end of file
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = Smbus
+ FILE_GUID = d5125e0f-1226-444f-a218-0085996ed5da
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = InitializeSmbus
+
+[Sources.common]
+ Smbus.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ PcdLib
+ UefiLib
+ UefiDriverEntryPoint
+ MemoryAllocationLib
+ IoLib
+
+[Guids]
+
+[Protocols]
+ gEfiSmbusHcProtocolGuid
+
+[Pcd]
+
+[depex]
+ TRUE \ No newline at end of file
diff --git a/Omap35xxPkg/TPS65950Dxe/TPS65950.c b/Omap35xxPkg/TPS65950Dxe/TPS65950.c
index 6b76da507..ed19389d4 100644
--- a/Omap35xxPkg/TPS65950Dxe/TPS65950.c
+++ b/Omap35xxPkg/TPS65950Dxe/TPS65950.c
@@ -1,116 +1,116 @@
-/** @file
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include <Uefi.h>
-
-#include <TPS65950.h>
-
-#include <Library/BaseMemoryLib.h>
-#include <Library/DebugLib.h>
-#include <Library/MemoryAllocationLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-
-#include <Protocol/EmbeddedExternalDevice.h>
-#include <Protocol/SmbusHc.h>
-
-EFI_SMBUS_HC_PROTOCOL *Smbus;
-
-EFI_STATUS
-Read (
- IN EMBEDDED_EXTERNAL_DEVICE *This,
- IN UINTN Register,
- IN UINTN Length,
- OUT VOID *Buffer
- )
-{
- EFI_STATUS Status;
- EFI_SMBUS_DEVICE_ADDRESS SlaveAddress;
- UINT8 DeviceRegister;
- UINTN DeviceRegisterLength = 1;
-
- SlaveAddress.SmbusDeviceAddress = EXTERNAL_DEVICE_REGISTER_TO_SLAVE_ADDRESS(Register);
- DeviceRegister = (UINT8)EXTERNAL_DEVICE_REGISTER_TO_REGISTER(Register);
-
- //Write DeviceRegister.
- Status = Smbus->Execute(Smbus, SlaveAddress, 0, EfiSmbusWriteBlock, FALSE, &DeviceRegisterLength, &DeviceRegister);
- if (EFI_ERROR(Status)) {
- return Status;
- }
-
- //Read Data
- Status = Smbus->Execute(Smbus, SlaveAddress, 0, EfiSmbusReadBlock, FALSE, &Length, Buffer);
- return Status;
-}
-
-EFI_STATUS
-Write (
- IN EMBEDDED_EXTERNAL_DEVICE *This,
- IN UINTN Register,
- IN UINTN Length,
- IN VOID *Buffer
- )
-{
- EFI_STATUS Status;
- EFI_SMBUS_DEVICE_ADDRESS SlaveAddress;
- UINT8 DeviceRegister;
- UINTN DeviceBufferLength = Length + 1;
- UINT8 *DeviceBuffer;
-
- SlaveAddress.SmbusDeviceAddress = EXTERNAL_DEVICE_REGISTER_TO_SLAVE_ADDRESS(Register);
- DeviceRegister = (UINT8)EXTERNAL_DEVICE_REGISTER_TO_REGISTER(Register);
-
- //Prepare buffer for writing
- DeviceBuffer = (UINT8 *)AllocatePool(DeviceBufferLength);
- if (DeviceBuffer == NULL) {
- Status = EFI_OUT_OF_RESOURCES;
- goto exit;
- }
-
- //Set Device register followed by data to write.
- DeviceBuffer[0] = DeviceRegister;
- CopyMem(&DeviceBuffer[1], Buffer, Length);
-
- //Write Data
- Status = Smbus->Execute(Smbus, SlaveAddress, 0, EfiSmbusWriteBlock, FALSE, &DeviceBufferLength, DeviceBuffer);
- if (EFI_ERROR(Status)) {
- goto exit;
- }
-
-exit:
- if (DeviceBuffer) {
- FreePool(DeviceBuffer);
- }
-
- return Status;
-}
-
-EMBEDDED_EXTERNAL_DEVICE ExternalDevice = {
- Read,
- Write
-};
-
-EFI_STATUS
-TPS65950Initialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_STATUS Status;
-
- Status = gBS->LocateProtocol(&gEfiSmbusHcProtocolGuid, NULL, (VOID **)&Smbus);
- ASSERT_EFI_ERROR(Status);
-
- Status = gBS->InstallMultipleProtocolInterfaces(&ImageHandle, &gEmbeddedExternalDeviceProtocolGuid, &ExternalDevice, NULL);
- return Status;
-}
+/** @file
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <Uefi.h>
+
+#include <TPS65950.h>
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include <Protocol/EmbeddedExternalDevice.h>
+#include <Protocol/SmbusHc.h>
+
+EFI_SMBUS_HC_PROTOCOL *Smbus;
+
+EFI_STATUS
+Read (
+ IN EMBEDDED_EXTERNAL_DEVICE *This,
+ IN UINTN Register,
+ IN UINTN Length,
+ OUT VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+ EFI_SMBUS_DEVICE_ADDRESS SlaveAddress;
+ UINT8 DeviceRegister;
+ UINTN DeviceRegisterLength = 1;
+
+ SlaveAddress.SmbusDeviceAddress = EXTERNAL_DEVICE_REGISTER_TO_SLAVE_ADDRESS(Register);
+ DeviceRegister = (UINT8)EXTERNAL_DEVICE_REGISTER_TO_REGISTER(Register);
+
+ //Write DeviceRegister.
+ Status = Smbus->Execute(Smbus, SlaveAddress, 0, EfiSmbusWriteBlock, FALSE, &DeviceRegisterLength, &DeviceRegister);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ //Read Data
+ Status = Smbus->Execute(Smbus, SlaveAddress, 0, EfiSmbusReadBlock, FALSE, &Length, Buffer);
+ return Status;
+}
+
+EFI_STATUS
+Write (
+ IN EMBEDDED_EXTERNAL_DEVICE *This,
+ IN UINTN Register,
+ IN UINTN Length,
+ IN VOID *Buffer
+ )
+{
+ EFI_STATUS Status;
+ EFI_SMBUS_DEVICE_ADDRESS SlaveAddress;
+ UINT8 DeviceRegister;
+ UINTN DeviceBufferLength = Length + 1;
+ UINT8 *DeviceBuffer;
+
+ SlaveAddress.SmbusDeviceAddress = EXTERNAL_DEVICE_REGISTER_TO_SLAVE_ADDRESS(Register);
+ DeviceRegister = (UINT8)EXTERNAL_DEVICE_REGISTER_TO_REGISTER(Register);
+
+ //Prepare buffer for writing
+ DeviceBuffer = (UINT8 *)AllocatePool(DeviceBufferLength);
+ if (DeviceBuffer == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto exit;
+ }
+
+ //Set Device register followed by data to write.
+ DeviceBuffer[0] = DeviceRegister;
+ CopyMem(&DeviceBuffer[1], Buffer, Length);
+
+ //Write Data
+ Status = Smbus->Execute(Smbus, SlaveAddress, 0, EfiSmbusWriteBlock, FALSE, &DeviceBufferLength, DeviceBuffer);
+ if (EFI_ERROR(Status)) {
+ goto exit;
+ }
+
+exit:
+ if (DeviceBuffer) {
+ FreePool(DeviceBuffer);
+ }
+
+ return Status;
+}
+
+EMBEDDED_EXTERNAL_DEVICE ExternalDevice = {
+ Read,
+ Write
+};
+
+EFI_STATUS
+TPS65950Initialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ Status = gBS->LocateProtocol(&gEfiSmbusHcProtocolGuid, NULL, (VOID **)&Smbus);
+ ASSERT_EFI_ERROR(Status);
+
+ Status = gBS->InstallMultipleProtocolInterfaces(&ImageHandle, &gEmbeddedExternalDeviceProtocolGuid, &ExternalDevice, NULL);
+ return Status;
+}
diff --git a/Omap35xxPkg/TPS65950Dxe/TPS65950.inf b/Omap35xxPkg/TPS65950Dxe/TPS65950.inf
index d03326bd1..5fca7a356 100644
--- a/Omap35xxPkg/TPS65950Dxe/TPS65950.inf
+++ b/Omap35xxPkg/TPS65950Dxe/TPS65950.inf
@@ -1,48 +1,48 @@
-#/** @file
-#
-# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = TPS65950
- FILE_GUID = 71fe861a-5450-48b6-bfb0-b93522616f99
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = TPS65950Initialize
-
-
-[Sources.common]
- TPS65950.c
-
-[Packages]
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- Omap35xxPkg/Omap35xxPkg.dec
-
-[LibraryClasses]
- BaseMemoryLib
- PcdLib
- UefiLib
- UefiDriverEntryPoint
- MemoryAllocationLib
-
-[Guids]
-
-[Protocols]
- gEfiSmbusHcProtocolGuid
- gEmbeddedExternalDeviceProtocolGuid
-
-[Pcd]
-
-[depex]
- gEfiSmbusHcProtocolGuid
+#/** @file
+#
+# Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = TPS65950
+ FILE_GUID = 71fe861a-5450-48b6-bfb0-b93522616f99
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = TPS65950Initialize
+
+
+[Sources.common]
+ TPS65950.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ Omap35xxPkg/Omap35xxPkg.dec
+
+[LibraryClasses]
+ BaseMemoryLib
+ PcdLib
+ UefiLib
+ UefiDriverEntryPoint
+ MemoryAllocationLib
+
+[Guids]
+
+[Protocols]
+ gEfiSmbusHcProtocolGuid
+ gEmbeddedExternalDeviceProtocolGuid
+
+[Pcd]
+
+[depex]
+ gEfiSmbusHcProtocolGuid
diff --git a/Omap35xxPkg/TimerDxe/Timer.c b/Omap35xxPkg/TimerDxe/Timer.c
index d0ea97350..bc3d9b0ab 100644
--- a/Omap35xxPkg/TimerDxe/Timer.c
+++ b/Omap35xxPkg/TimerDxe/Timer.c
@@ -1,376 +1,376 @@
-/** @file
- Template for Timer Architecture Protocol driver of the ARM flavor
-
- Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-
- This program and the accompanying materials
- are licensed and made available under the terms and conditions of the BSD License
- which accompanies this distribution. The full text of the license may be found at
- http://opensource.org/licenses/bsd-license.php
-
- THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
- WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-
-#include <PiDxe.h>
-
-#include <Library/BaseLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BaseMemoryLib.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/UefiLib.h>
-#include <Library/PcdLib.h>
-#include <Library/IoLib.h>
-#include <Library/OmapLib.h>
-
-#include <Protocol/Timer.h>
-#include <Protocol/HardwareInterrupt.h>
-
-#include <Omap3530/Omap3530.h>
-
-
-// The notification function to call on every timer interrupt.
-volatile EFI_TIMER_NOTIFY mTimerNotifyFunction = (EFI_TIMER_NOTIFY)NULL;
-
-
-// The current period of the timer interrupt
-volatile UINT64 mTimerPeriod = 0;
-
-// Cached copy of the Hardware Interrupt protocol instance
-EFI_HARDWARE_INTERRUPT_PROTOCOL *gInterrupt = NULL;
-
-// Cached registers
-volatile UINT32 TISR;
-volatile UINT32 TCLR;
-volatile UINT32 TLDR;
-volatile UINT32 TCRR;
-volatile UINT32 TIER;
-
-// Cached interrupt vector
-volatile UINTN gVector;
-
-
-/**
-
- C Interrupt Handler calledin the interrupt context when Source interrupt is active.
-
-
- @param Source Source of the interrupt. Hardware routing off a specific platform defines
- what source means.
-
- @param SystemContext Pointer to system register context. Mostly used by debuggers and will
- update the system context after the return from the interrupt if
- modified. Don't change these values unless you know what you are doing
-
-**/
-VOID
-EFIAPI
-TimerInterruptHandler (
- IN HARDWARE_INTERRUPT_SOURCE Source,
- IN EFI_SYSTEM_CONTEXT SystemContext
- )
-{
- EFI_TPL OriginalTPL;
-
-
-
- //
- // DXE core uses this callback for the EFI timer tick. The DXE core uses locks
- // that raise to TPL_HIGH and then restore back to current level. Thus we need
- // to make sure TPL level is set to TPL_HIGH while we are handling the timer tick.
- //
- OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-
- if (mTimerNotifyFunction) {
- mTimerNotifyFunction(mTimerPeriod);
- }
-
- // Clear all timer interrupts
- MmioWrite32 (TISR, TISR_CLEAR_ALL);
-
- // Poll interrupt status bits to ensure clearing
- while ((MmioRead32 (TISR) & TISR_ALL_INTERRUPT_MASK) != TISR_NO_INTERRUPTS_PENDING);
-
- gBS->RestoreTPL (OriginalTPL);
-}
-
-/**
- This function registers the handler NotifyFunction so it is called every time
- the timer interrupt fires. It also passes the amount of time since the last
- handler call to the NotifyFunction. If NotifyFunction is NULL, then the
- handler is unregistered. If the handler is registered, then EFI_SUCCESS is
- returned. If the CPU does not support registering a timer interrupt handler,
- then EFI_UNSUPPORTED is returned. If an attempt is made to register a handler
- when a handler is already registered, then EFI_ALREADY_STARTED is returned.
- If an attempt is made to unregister a handler when a handler is not registered,
- then EFI_INVALID_PARAMETER is returned. If an error occurs attempting to
- register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
- is returned.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param NotifyFunction The function to call when a timer interrupt fires. This
- function executes at TPL_HIGH_LEVEL. The DXE Core will
- register a handler for the timer interrupt, so it can know
- how much time has passed. This information is used to
- signal timer based events. NULL will unregister the handler.
- @retval EFI_SUCCESS The timer handler was registered.
- @retval EFI_UNSUPPORTED The platform does not support timer interrupts.
- @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
- registered.
- @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
- previously registered.
- @retval EFI_DEVICE_ERROR The timer handler could not be registered.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverRegisterHandler (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- IN EFI_TIMER_NOTIFY NotifyFunction
- )
-{
- if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
- return EFI_INVALID_PARAMETER;
- }
-
- if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
- return EFI_ALREADY_STARTED;
- }
-
- mTimerNotifyFunction = NotifyFunction;
-
- return EFI_SUCCESS;
-}
-
-/**
-
- This function adjusts the period of timer interrupts to the value specified
- by TimerPeriod. If the timer period is updated, then the selected timer
- period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
- If an error occurs while attempting to update the timer period, then the
- timer hardware will be put back in its state prior to this call, and
- EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
- is disabled. This is not the same as disabling the CPU's interrupts.
- Instead, it must either turn off the timer hardware, or it must adjust the
- interrupt controller so that a CPU interrupt is not generated when the timer
- interrupt fires.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
- the timer hardware is not programmable, then EFI_UNSUPPORTED is
- returned. If the timer is programmable, then the timer period
- will be rounded up to the nearest timer period that is supported
- by the timer hardware. If TimerPeriod is set to 0, then the
- timer interrupts will be disabled.
-
-
- @retval EFI_SUCCESS The timer period was changed.
- @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
- @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverSetTimerPeriod (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- IN UINT64 TimerPeriod
- )
-{
- EFI_STATUS Status;
- UINT64 TimerCount;
- INT32 LoadValue;
-
- if (TimerPeriod == 0) {
- // Turn off GPTIMER3
- MmioWrite32 (TCLR, TCLR_ST_OFF);
-
- Status = gInterrupt->DisableInterruptSource(gInterrupt, gVector);
- } else {
- // Calculate required timer count
- TimerCount = DivU64x32(TimerPeriod * 100, PcdGet32(PcdEmbeddedPerformanceCounterPeriodInNanoseconds));
-
- // Set GPTIMER3 Load register
- LoadValue = (INT32) -TimerCount;
- MmioWrite32 (TLDR, LoadValue);
- MmioWrite32 (TCRR, LoadValue);
-
- // Enable Overflow interrupt
- MmioWrite32 (TIER, TIER_TCAR_IT_DISABLE | TIER_OVF_IT_ENABLE | TIER_MAT_IT_DISABLE);
-
- // Turn on GPTIMER3, it will reload at overflow
- MmioWrite32 (TCLR, TCLR_AR_AUTORELOAD | TCLR_ST_ON);
-
- Status = gInterrupt->EnableInterruptSource(gInterrupt, gVector);
- }
-
- //
- // Save the new timer period
- //
- mTimerPeriod = TimerPeriod;
- return Status;
-}
-
-
-/**
- This function retrieves the period of timer interrupts in 100 ns units,
- returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
- is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
- returned, then the timer is currently disabled.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
- @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
- 0 is returned, then the timer is currently disabled.
-
-
- @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
- @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverGetTimerPeriod (
- IN EFI_TIMER_ARCH_PROTOCOL *This,
- OUT UINT64 *TimerPeriod
- )
-{
- if (TimerPeriod == NULL) {
- return EFI_INVALID_PARAMETER;
- }
-
- *TimerPeriod = mTimerPeriod;
- return EFI_SUCCESS;
-}
-
-/**
- This function generates a soft timer interrupt. If the platform does not support soft
- timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
- If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
- service, then a soft timer interrupt will be generated. If the timer interrupt is
- enabled when this service is called, then the registered handler will be invoked. The
- registered handler should not be able to distinguish a hardware-generated timer
- interrupt from a software-generated timer interrupt.
-
- @param This The EFI_TIMER_ARCH_PROTOCOL instance.
-
- @retval EFI_SUCCESS The soft timer interrupt was generated.
- @retval EFI_UNSUPPORTED The platform does not support the generation of soft timer interrupts.
-
-**/
-EFI_STATUS
-EFIAPI
-TimerDriverGenerateSoftInterrupt (
- IN EFI_TIMER_ARCH_PROTOCOL *This
- )
-{
- return EFI_UNSUPPORTED;
-}
-
-
-/**
- Interface stucture for the Timer Architectural Protocol.
-
- @par Protocol Description:
- This protocol provides the services to initialize a periodic timer
- interrupt, and to register a handler that is called each time the timer
- interrupt fires. It may also provide a service to adjust the rate of the
- periodic timer interrupt. When a timer interrupt occurs, the handler is
- passed the amount of time that has passed since the previous timer
- interrupt.
-
- @param RegisterHandler
- Registers a handler that will be called each time the
- timer interrupt fires. TimerPeriod defines the minimum
- time between timer interrupts, so TimerPeriod will also
- be the minimum time between calls to the registered
- handler.
-
- @param SetTimerPeriod
- Sets the period of the timer interrupt in 100 nS units.
- This function is optional, and may return EFI_UNSUPPORTED.
- If this function is supported, then the timer period will
- be rounded up to the nearest supported timer period.
-
-
- @param GetTimerPeriod
- Retrieves the period of the timer interrupt in 100 nS units.
-
- @param GenerateSoftInterrupt
- Generates a soft timer interrupt that simulates the firing of
- the timer interrupt. This service can be used to invoke the registered handler if the timer interrupt has been masked for
- a period of time.
-
-**/
-EFI_TIMER_ARCH_PROTOCOL gTimer = {
- TimerDriverRegisterHandler,
- TimerDriverSetTimerPeriod,
- TimerDriverGetTimerPeriod,
- TimerDriverGenerateSoftInterrupt
-};
-
-
-/**
- Initialize the state information for the Timer Architectural Protocol and
- the Timer Debug support protocol that allows the debugger to break into a
- running program.
-
- @param ImageHandle of the loaded driver
- @param SystemTable Pointer to the System Table
-
- @retval EFI_SUCCESS Protocol registered
- @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
- @retval EFI_DEVICE_ERROR Hardware problems
-
-**/
-EFI_STATUS
-EFIAPI
-TimerInitialize (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
- )
-{
- EFI_HANDLE Handle = NULL;
- EFI_STATUS Status;
- UINT32 TimerBaseAddress;
-
- // Find the interrupt controller protocol. ASSERT if not found.
- Status = gBS->LocateProtocol (&gHardwareInterruptProtocolGuid, NULL, (VOID **)&gInterrupt);
- ASSERT_EFI_ERROR (Status);
-
- // Set up the timer registers
- TimerBaseAddress = TimerBase (FixedPcdGet32(PcdOmap35xxArchTimer));
- TISR = TimerBaseAddress + GPTIMER_TISR;
- TCLR = TimerBaseAddress + GPTIMER_TCLR;
- TLDR = TimerBaseAddress + GPTIMER_TLDR;
- TCRR = TimerBaseAddress + GPTIMER_TCRR;
- TIER = TimerBaseAddress + GPTIMER_TIER;
-
- // Disable the timer
- Status = TimerDriverSetTimerPeriod (&gTimer, 0);
- ASSERT_EFI_ERROR (Status);
-
- // Install interrupt handler
- gVector = InterruptVectorForTimer (FixedPcdGet32(PcdOmap35xxArchTimer));
- Status = gInterrupt->RegisterInterruptSource (gInterrupt, gVector, TimerInterruptHandler);
- ASSERT_EFI_ERROR (Status);
-
- // Turn on the functional clock for Timer
- MmioOr32 (CM_FCLKEN_PER, CM_FCLKEN_PER_EN_GPT3_ENABLE);
-
- // Set up default timer
- Status = TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod));
- ASSERT_EFI_ERROR (Status);
-
- // Install the Timer Architectural Protocol onto a new handle
- Status = gBS->InstallMultipleProtocolInterfaces (
- &Handle,
- &gEfiTimerArchProtocolGuid, &gTimer,
- NULL
- );
- ASSERT_EFI_ERROR(Status);
-
- return Status;
-}
-
+/** @file
+ Template for Timer Architecture Protocol driver of the ARM flavor
+
+ Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+
+#include <PiDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/UefiLib.h>
+#include <Library/PcdLib.h>
+#include <Library/IoLib.h>
+#include <Library/OmapLib.h>
+
+#include <Protocol/Timer.h>
+#include <Protocol/HardwareInterrupt.h>
+
+#include <Omap3530/Omap3530.h>
+
+
+// The notification function to call on every timer interrupt.
+volatile EFI_TIMER_NOTIFY mTimerNotifyFunction = (EFI_TIMER_NOTIFY)NULL;
+
+
+// The current period of the timer interrupt
+volatile UINT64 mTimerPeriod = 0;
+
+// Cached copy of the Hardware Interrupt protocol instance
+EFI_HARDWARE_INTERRUPT_PROTOCOL *gInterrupt = NULL;
+
+// Cached registers
+volatile UINT32 TISR;
+volatile UINT32 TCLR;
+volatile UINT32 TLDR;
+volatile UINT32 TCRR;
+volatile UINT32 TIER;
+
+// Cached interrupt vector
+volatile UINTN gVector;
+
+
+/**
+
+ C Interrupt Handler calledin the interrupt context when Source interrupt is active.
+
+
+ @param Source Source of the interrupt. Hardware routing off a specific platform defines
+ what source means.
+
+ @param SystemContext Pointer to system register context. Mostly used by debuggers and will
+ update the system context after the return from the interrupt if
+ modified. Don't change these values unless you know what you are doing
+
+**/
+VOID
+EFIAPI
+TimerInterruptHandler (
+ IN HARDWARE_INTERRUPT_SOURCE Source,
+ IN EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ EFI_TPL OriginalTPL;
+
+
+
+ //
+ // DXE core uses this callback for the EFI timer tick. The DXE core uses locks
+ // that raise to TPL_HIGH and then restore back to current level. Thus we need
+ // to make sure TPL level is set to TPL_HIGH while we are handling the timer tick.
+ //
+ OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+
+ if (mTimerNotifyFunction) {
+ mTimerNotifyFunction(mTimerPeriod);
+ }
+
+ // Clear all timer interrupts
+ MmioWrite32 (TISR, TISR_CLEAR_ALL);
+
+ // Poll interrupt status bits to ensure clearing
+ while ((MmioRead32 (TISR) & TISR_ALL_INTERRUPT_MASK) != TISR_NO_INTERRUPTS_PENDING);
+
+ gBS->RestoreTPL (OriginalTPL);
+}
+
+/**
+ This function registers the handler NotifyFunction so it is called every time
+ the timer interrupt fires. It also passes the amount of time since the last
+ handler call to the NotifyFunction. If NotifyFunction is NULL, then the
+ handler is unregistered. If the handler is registered, then EFI_SUCCESS is
+ returned. If the CPU does not support registering a timer interrupt handler,
+ then EFI_UNSUPPORTED is returned. If an attempt is made to register a handler
+ when a handler is already registered, then EFI_ALREADY_STARTED is returned.
+ If an attempt is made to unregister a handler when a handler is not registered,
+ then EFI_INVALID_PARAMETER is returned. If an error occurs attempting to
+ register the NotifyFunction with the timer interrupt, then EFI_DEVICE_ERROR
+ is returned.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param NotifyFunction The function to call when a timer interrupt fires. This
+ function executes at TPL_HIGH_LEVEL. The DXE Core will
+ register a handler for the timer interrupt, so it can know
+ how much time has passed. This information is used to
+ signal timer based events. NULL will unregister the handler.
+ @retval EFI_SUCCESS The timer handler was registered.
+ @retval EFI_UNSUPPORTED The platform does not support timer interrupts.
+ @retval EFI_ALREADY_STARTED NotifyFunction is not NULL, and a handler is already
+ registered.
+ @retval EFI_INVALID_PARAMETER NotifyFunction is NULL, and a handler was not
+ previously registered.
+ @retval EFI_DEVICE_ERROR The timer handler could not be registered.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverRegisterHandler (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ IN EFI_TIMER_NOTIFY NotifyFunction
+ )
+{
+ if ((NotifyFunction == NULL) && (mTimerNotifyFunction == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ((NotifyFunction != NULL) && (mTimerNotifyFunction != NULL)) {
+ return EFI_ALREADY_STARTED;
+ }
+
+ mTimerNotifyFunction = NotifyFunction;
+
+ return EFI_SUCCESS;
+}
+
+/**
+
+ This function adjusts the period of timer interrupts to the value specified
+ by TimerPeriod. If the timer period is updated, then the selected timer
+ period is stored in EFI_TIMER.TimerPeriod, and EFI_SUCCESS is returned. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is returned.
+ If an error occurs while attempting to update the timer period, then the
+ timer hardware will be put back in its state prior to this call, and
+ EFI_DEVICE_ERROR is returned. If TimerPeriod is 0, then the timer interrupt
+ is disabled. This is not the same as disabling the CPU's interrupts.
+ Instead, it must either turn off the timer hardware, or it must adjust the
+ interrupt controller so that a CPU interrupt is not generated when the timer
+ interrupt fires.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod The rate to program the timer interrupt in 100 nS units. If
+ the timer hardware is not programmable, then EFI_UNSUPPORTED is
+ returned. If the timer is programmable, then the timer period
+ will be rounded up to the nearest timer period that is supported
+ by the timer hardware. If TimerPeriod is set to 0, then the
+ timer interrupts will be disabled.
+
+
+ @retval EFI_SUCCESS The timer period was changed.
+ @retval EFI_UNSUPPORTED The platform cannot change the period of the timer interrupt.
+ @retval EFI_DEVICE_ERROR The timer period could not be changed due to a device error.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverSetTimerPeriod (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ IN UINT64 TimerPeriod
+ )
+{
+ EFI_STATUS Status;
+ UINT64 TimerCount;
+ INT32 LoadValue;
+
+ if (TimerPeriod == 0) {
+ // Turn off GPTIMER3
+ MmioWrite32 (TCLR, TCLR_ST_OFF);
+
+ Status = gInterrupt->DisableInterruptSource(gInterrupt, gVector);
+ } else {
+ // Calculate required timer count
+ TimerCount = DivU64x32(TimerPeriod * 100, PcdGet32(PcdEmbeddedPerformanceCounterPeriodInNanoseconds));
+
+ // Set GPTIMER3 Load register
+ LoadValue = (INT32) -TimerCount;
+ MmioWrite32 (TLDR, LoadValue);
+ MmioWrite32 (TCRR, LoadValue);
+
+ // Enable Overflow interrupt
+ MmioWrite32 (TIER, TIER_TCAR_IT_DISABLE | TIER_OVF_IT_ENABLE | TIER_MAT_IT_DISABLE);
+
+ // Turn on GPTIMER3, it will reload at overflow
+ MmioWrite32 (TCLR, TCLR_AR_AUTORELOAD | TCLR_ST_ON);
+
+ Status = gInterrupt->EnableInterruptSource(gInterrupt, gVector);
+ }
+
+ //
+ // Save the new timer period
+ //
+ mTimerPeriod = TimerPeriod;
+ return Status;
+}
+
+
+/**
+ This function retrieves the period of timer interrupts in 100 ns units,
+ returns that value in TimerPeriod, and returns EFI_SUCCESS. If TimerPeriod
+ is NULL, then EFI_INVALID_PARAMETER is returned. If a TimerPeriod of 0 is
+ returned, then the timer is currently disabled.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+ @param TimerPeriod A pointer to the timer period to retrieve in 100 ns units. If
+ 0 is returned, then the timer is currently disabled.
+
+
+ @retval EFI_SUCCESS The timer period was returned in TimerPeriod.
+ @retval EFI_INVALID_PARAMETER TimerPeriod is NULL.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGetTimerPeriod (
+ IN EFI_TIMER_ARCH_PROTOCOL *This,
+ OUT UINT64 *TimerPeriod
+ )
+{
+ if (TimerPeriod == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *TimerPeriod = mTimerPeriod;
+ return EFI_SUCCESS;
+}
+
+/**
+ This function generates a soft timer interrupt. If the platform does not support soft
+ timer interrupts, then EFI_UNSUPPORTED is returned. Otherwise, EFI_SUCCESS is returned.
+ If a handler has been registered through the EFI_TIMER_ARCH_PROTOCOL.RegisterHandler()
+ service, then a soft timer interrupt will be generated. If the timer interrupt is
+ enabled when this service is called, then the registered handler will be invoked. The
+ registered handler should not be able to distinguish a hardware-generated timer
+ interrupt from a software-generated timer interrupt.
+
+ @param This The EFI_TIMER_ARCH_PROTOCOL instance.
+
+ @retval EFI_SUCCESS The soft timer interrupt was generated.
+ @retval EFI_UNSUPPORTED The platform does not support the generation of soft timer interrupts.
+
+**/
+EFI_STATUS
+EFIAPI
+TimerDriverGenerateSoftInterrupt (
+ IN EFI_TIMER_ARCH_PROTOCOL *This
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+
+/**
+ Interface stucture for the Timer Architectural Protocol.
+
+ @par Protocol Description:
+ This protocol provides the services to initialize a periodic timer
+ interrupt, and to register a handler that is called each time the timer
+ interrupt fires. It may also provide a service to adjust the rate of the
+ periodic timer interrupt. When a timer interrupt occurs, the handler is
+ passed the amount of time that has passed since the previous timer
+ interrupt.
+
+ @param RegisterHandler
+ Registers a handler that will be called each time the
+ timer interrupt fires. TimerPeriod defines the minimum
+ time between timer interrupts, so TimerPeriod will also
+ be the minimum time between calls to the registered
+ handler.
+
+ @param SetTimerPeriod
+ Sets the period of the timer interrupt in 100 nS units.
+ This function is optional, and may return EFI_UNSUPPORTED.
+ If this function is supported, then the timer period will
+ be rounded up to the nearest supported timer period.
+
+
+ @param GetTimerPeriod
+ Retrieves the period of the timer interrupt in 100 nS units.
+
+ @param GenerateSoftInterrupt
+ Generates a soft timer interrupt that simulates the firing of
+ the timer interrupt. This service can be used to invoke the registered handler if the timer interrupt has been masked for
+ a period of time.
+
+**/
+EFI_TIMER_ARCH_PROTOCOL gTimer = {
+ TimerDriverRegisterHandler,
+ TimerDriverSetTimerPeriod,
+ TimerDriverGetTimerPeriod,
+ TimerDriverGenerateSoftInterrupt
+};
+
+
+/**
+ Initialize the state information for the Timer Architectural Protocol and
+ the Timer Debug support protocol that allows the debugger to break into a
+ running program.
+
+ @param ImageHandle of the loaded driver
+ @param SystemTable Pointer to the System Table
+
+ @retval EFI_SUCCESS Protocol registered
+ @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
+ @retval EFI_DEVICE_ERROR Hardware problems
+
+**/
+EFI_STATUS
+EFIAPI
+TimerInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_HANDLE Handle = NULL;
+ EFI_STATUS Status;
+ UINT32 TimerBaseAddress;
+
+ // Find the interrupt controller protocol. ASSERT if not found.
+ Status = gBS->LocateProtocol (&gHardwareInterruptProtocolGuid, NULL, (VOID **)&gInterrupt);
+ ASSERT_EFI_ERROR (Status);
+
+ // Set up the timer registers
+ TimerBaseAddress = TimerBase (FixedPcdGet32(PcdOmap35xxArchTimer));
+ TISR = TimerBaseAddress + GPTIMER_TISR;
+ TCLR = TimerBaseAddress + GPTIMER_TCLR;
+ TLDR = TimerBaseAddress + GPTIMER_TLDR;
+ TCRR = TimerBaseAddress + GPTIMER_TCRR;
+ TIER = TimerBaseAddress + GPTIMER_TIER;
+
+ // Disable the timer
+ Status = TimerDriverSetTimerPeriod (&gTimer, 0);
+ ASSERT_EFI_ERROR (Status);
+
+ // Install interrupt handler
+ gVector = InterruptVectorForTimer (FixedPcdGet32(PcdOmap35xxArchTimer));
+ Status = gInterrupt->RegisterInterruptSource (gInterrupt, gVector, TimerInterruptHandler);
+ ASSERT_EFI_ERROR (Status);
+
+ // Turn on the functional clock for Timer
+ MmioOr32 (CM_FCLKEN_PER, CM_FCLKEN_PER_EN_GPT3_ENABLE);
+
+ // Set up default timer
+ Status = TimerDriverSetTimerPeriod (&gTimer, FixedPcdGet32(PcdTimerPeriod));
+ ASSERT_EFI_ERROR (Status);
+
+ // Install the Timer Architectural Protocol onto a new handle
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Handle,
+ &gEfiTimerArchProtocolGuid, &gTimer,
+ NULL
+ );
+ ASSERT_EFI_ERROR(Status);
+
+ return Status;
+}
+
diff --git a/Omap35xxPkg/TimerDxe/TimerDxe.inf b/Omap35xxPkg/TimerDxe/TimerDxe.inf
index 6cfab7757..2c5a2f7a4 100644
--- a/Omap35xxPkg/TimerDxe/TimerDxe.inf
+++ b/Omap35xxPkg/TimerDxe/TimerDxe.inf
@@ -1,57 +1,57 @@
-#/** @file
-#
-# Component description file for Timer module
-#
-# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
-#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-#
-#**/
-
-[Defines]
- INF_VERSION = 0x00010005
- BASE_NAME = BeagleBoardTimerDxe
- FILE_GUID = 6ddbf08b-cfc9-43cc-9e81-0784ba312ca0
- MODULE_TYPE = DXE_DRIVER
- VERSION_STRING = 1.0
-
- ENTRY_POINT = TimerInitialize
-
-[Sources.common]
- Timer.c
-
-[Packages]
- Omap35xxPkg/Omap35xxPkg.dec
- MdePkg/MdePkg.dec
- EmbeddedPkg/EmbeddedPkg.dec
- ArmPkg/ArmPkg.dec
-
-[LibraryClasses]
- BaseLib
- UefiRuntimeServicesTableLib
- UefiLib
- UefiBootServicesTableLib
- BaseMemoryLib
- DebugLib
- UefiDriverEntryPoint
- IoLib
- OmapLib
-
-[Guids]
-
-[Protocols]
- gEfiTimerArchProtocolGuid
- gHardwareInterruptProtocolGuid
-
-[Pcd.common]
- gEmbeddedTokenSpaceGuid.PcdTimerPeriod
- gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterPeriodInNanoseconds
- gOmap35xxTokenSpaceGuid.PcdOmap35xxArchTimer
-
-[Depex]
- gHardwareInterruptProtocolGuid \ No newline at end of file
+#/** @file
+#
+# Component description file for Timer module
+#
+# Copyright (c) 2009, Apple Inc. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = BeagleBoardTimerDxe
+ FILE_GUID = 6ddbf08b-cfc9-43cc-9e81-0784ba312ca0
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+
+ ENTRY_POINT = TimerInitialize
+
+[Sources.common]
+ Timer.c
+
+[Packages]
+ Omap35xxPkg/Omap35xxPkg.dec
+ MdePkg/MdePkg.dec
+ EmbeddedPkg/EmbeddedPkg.dec
+ ArmPkg/ArmPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ UefiRuntimeServicesTableLib
+ UefiLib
+ UefiBootServicesTableLib
+ BaseMemoryLib
+ DebugLib
+ UefiDriverEntryPoint
+ IoLib
+ OmapLib
+
+[Guids]
+
+[Protocols]
+ gEfiTimerArchProtocolGuid
+ gHardwareInterruptProtocolGuid
+
+[Pcd.common]
+ gEmbeddedTokenSpaceGuid.PcdTimerPeriod
+ gEmbeddedTokenSpaceGuid.PcdEmbeddedPerformanceCounterPeriodInNanoseconds
+ gOmap35xxTokenSpaceGuid.PcdOmap35xxArchTimer
+
+[Depex]
+ gHardwareInterruptProtocolGuid \ No newline at end of file
diff --git a/OvmfPkg/Include/Library/LoadLinuxLib.h b/OvmfPkg/Include/Library/LoadLinuxLib.h
index d1064d239..36ee352e5 100644
--- a/OvmfPkg/Include/Library/LoadLinuxLib.h
+++ b/OvmfPkg/Include/Library/LoadLinuxLib.h
@@ -1,7 +1,7 @@
/** @file
Load/boot UEFI Linux.
- Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -95,6 +95,26 @@ LoadLinuxAllocateKernelSetupPages (
/**
+ Clears the uninitialised space before and after the struct setup_header
+ in the kernel setup image. The kernel requires that these be zeroed
+ unless explicitly initialised, so this function should be called after
+ the setup_header has been copied in from a bzImage, before setting up
+ anything else.
+
+ @param[in] KernelSetup - The kernel setup image
+
+ @retval EFI_SUCCESS - The Linux kernel setup was successfully initialized
+ @retval EFI_INVALID_PARAMETER - KernelSetup was NULL
+ @retval EFI_UNSUPPORTED - The Linux kernel is not supported
+
+**/
+EFI_STATUS
+EFIAPI
+LoadLinuxInitializeKernelSetup (
+ IN VOID *KernelSetup
+ );
+
+/**
Allocates pages for the kernel.
@param[in] KernelSetup - The kernel setup image
diff --git a/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.S b/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.S
index b8cd4ca51..f7440f74c 100644
--- a/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.S
+++ b/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.S
@@ -1,6 +1,6 @@
#------------------------------------------------------------------------------
#
-# Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -13,6 +13,7 @@
#------------------------------------------------------------------------------
ASM_GLOBAL ASM_PFX(JumpToKernel)
+ASM_GLOBAL ASM_PFX(JumpToUefiKernel)
#------------------------------------------------------------------------------
# VOID
@@ -27,3 +28,19 @@ ASM_PFX(JumpToKernel):
calll 0x4(%esp)
ret
+#------------------------------------------------------------------------------
+# VOID
+# EFIAPI
+# JumpToUefiKernel (
+# EFI_HANDLE ImageHandle,
+# EFI_SYSTEM_TABLE *SystemTable,
+# VOID *KernelBootParams,
+# VOID *KernelStart
+# );
+#------------------------------------------------------------------------------
+ASM_PFX(JumpToUefiKernel):
+ movl 0xc(%esp), %eax
+ movl 0x264(%eax), %eax
+ addl 0x10(%esp), %eax
+ jmp %eax
+
diff --git a/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.asm b/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.asm
index a8f3965f9..21d0c4e72 100644
--- a/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.asm
+++ b/OvmfPkg/Library/LoadLinuxLib/Ia32/JumpToKernel.asm
@@ -1,6 +1,6 @@
;------------------------------------------------------------------------------
;
-; Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
;
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
@@ -32,4 +32,23 @@ JumpToKernel PROC
JumpToKernel ENDP
+;------------------------------------------------------------------------------
+; VOID
+; EFIAPI
+; JumpToUefiKernel (
+; EFI_HANDLE ImageHandle,
+; EFI_SYSTEM_TABLE *SystemTable,
+; VOID *KernelBootParams,
+; VOID *KernelStart
+; );
+;------------------------------------------------------------------------------
+JumpToUefiKernel PROC
+
+ mov eax, [esp + 12]
+ mov eax, [eax + 264h]
+ add eax, [esp + 16]
+ jmp eax
+
+JumpToUefiKernel ENDP
+
END
diff --git a/OvmfPkg/Library/LoadLinuxLib/Linux.c b/OvmfPkg/Library/LoadLinuxLib/Linux.c
index 96c985bc2..862698a39 100644
--- a/OvmfPkg/Library/LoadLinuxLib/Linux.c
+++ b/OvmfPkg/Library/LoadLinuxLib/Linux.c
@@ -1,6 +1,6 @@
/** @file
- Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -60,7 +60,8 @@ LoadLinuxCheckKernelSetup (
if ((Bp->hdr.signature != 0xAA55) || // Check boot sector signature
(Bp->hdr.header != SETUP_HDR) ||
- (Bp->hdr.version < 0x205) // We only support relocatable kernels
+ (Bp->hdr.version < 0x205) || // We only support relocatable kernels
+ (!Bp->hdr.relocatable_kernel)
) {
return EFI_UNSUPPORTED;
} else {
@@ -118,6 +119,34 @@ LoadLinuxAllocateKernelSetupPages (
}
}
+EFI_STATUS
+EFIAPI
+LoadLinuxInitializeKernelSetup (
+ IN VOID *KernelSetup
+ )
+{
+ EFI_STATUS Status;
+ UINTN SetupEnd;
+ struct boot_params *Bp;
+
+ Status = BasicKernelSetupCheck (KernelSetup);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Bp = (struct boot_params*) KernelSetup;
+
+ SetupEnd = 0x202 + (Bp->hdr.jump & 0xff);
+
+ //
+ // Clear all but the setup_header
+ //
+ ZeroMem (KernelSetup, 0x1f1);
+ ZeroMem (((UINT8 *)KernelSetup) + SetupEnd, 4096 - SetupEnd);
+ DEBUG ((EFI_D_INFO, "Cleared kernel setup 0-0x1f1, 0x%x-0x1000\n", SetupEnd));
+
+ return EFI_SUCCESS;
+}
VOID*
EFIAPI
@@ -575,14 +604,11 @@ SetupGraphics (
STATIC
EFI_STATUS
SetupLinuxBootParams (
- IN VOID *Kernel,
IN OUT struct boot_params *Bp
)
{
SetupGraphics (Bp);
- Bp->hdr.code32_start = (UINT32)(UINTN) Kernel;
-
SetupLinuxMemmap (Bp);
return EFI_SUCCESS;
@@ -606,7 +632,7 @@ LoadLinux (
Bp = (struct boot_params *) KernelSetup;
- if (Bp->hdr.version < 0x205) {
+ if (Bp->hdr.version < 0x205 || !Bp->hdr.relocatable_kernel) {
//
// We only support relocatable kernels
//
@@ -615,7 +641,18 @@ LoadLinux (
InitLinuxDescriptorTables ();
- SetupLinuxBootParams (Kernel, (struct boot_params*) KernelSetup);
+ Bp->hdr.code32_start = (UINT32)(UINTN) Kernel;
+ if (Bp->hdr.version >= 0x20b && Bp->hdr.handover_offset &&
+ (Bp->hdr.load_flags & (sizeof(long) >> 1))) {
+ DEBUG ((EFI_D_INFO, "Jumping to kernel EFI handover point at ofs %x\n", Bp->hdr.handover_offset));
+
+ DisableInterrupts ();
+ JumpToUefiKernel ((VOID*) gImageHandle, (VOID*) gST, KernelSetup, Kernel);
+ }
+ //
+ // Old kernels without EFI handover protocol
+ //
+ SetupLinuxBootParams (KernelSetup);
DEBUG ((EFI_D_INFO, "Jumping to kernel\n"));
DisableInterrupts ();
diff --git a/OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.h b/OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.h
index f86979726..045cbf9b2 100644
--- a/OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.h
+++ b/OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.h
@@ -1,7 +1,7 @@
/** @file
Boot UEFI Linux.
- Copyright (c) 2008 - 2011, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2008 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
@@ -37,6 +37,15 @@ JumpToKernel (
);
VOID
+EFIAPI
+JumpToUefiKernel (
+ EFI_HANDLE ImageHandle,
+ EFI_SYSTEM_TABLE *SystemTable,
+ VOID *KernelBootParams,
+ VOID *KernelStart
+ );
+
+VOID
InitLinuxDescriptorTables (
VOID
);
diff --git a/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.S b/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.S
index 9ae755b06..06d0a1f55 100644
--- a/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.S
+++ b/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.S
@@ -1,6 +1,6 @@
#------------------------------------------------------------------------------
#
-# Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -13,6 +13,7 @@
#------------------------------------------------------------------------------
ASM_GLOBAL ASM_PFX(JumpToKernel)
+ASM_GLOBAL ASM_PFX(JumpToUefiKernel)
#------------------------------------------------------------------------------
# VOID
@@ -23,8 +24,68 @@ ASM_GLOBAL ASM_PFX(JumpToKernel)
# );
#------------------------------------------------------------------------------
ASM_PFX(JumpToKernel):
+
+ // Set up for executing kernel. BP in %esi, entry point on the stack
+ // (64-bit when the 'ret' will use it as 32-bit, but we're little-endian)
+ movq %rdx, %rsi
+ pushq %rcx
+
+ // Jump into the compatibility mode CS
+ pushq $0x10
+ leaq 1f(%rip), %rax
+ pushq %rax
+ .byte 0x48, 0xcb // retfq
+
+1: // Now in compatibility mode
+.code32
+ movl $0x18, %eax
+ movl %eax, %ds
+ movl %eax, %es
+ movl %eax, %fs
+ movl %eax, %gs
+ movl %eax, %ss
+
+ // Disable paging
+ movl %cr0, %eax
+ btcl $31, %eax
+ movl %eax, %cr0
+
+ // Disable long mode in EFER
+ movl $0x0c0000080, %ecx
+ rdmsr
+ btcl $8, %eax
+ wrmsr
+
+ // Disable PAE
+ movl %cr4, %eax
+ btcl $5, %eax
+ movl %eax, %cr4
+
+ // Zero registers and 'return' to kernel
+ xorl %ebp, %ebp
+ xorl %edi, %edi
+ xorl %ebx, %ebx
+ ret
+.code64
+
+#------------------------------------------------------------------------------
+# VOID
+# EFIAPI
+# JumpToUefiKernel (
+# EFI_HANDLE ImageHandle,
+# EFI_SYSTEM_TABLE *SystemTable,
+# VOID *KernelBootParams,
+# VOID *KernelStart
+# );
+#------------------------------------------------------------------------------
+ASM_PFX(JumpToUefiKernel):
+ movq %rcx, %rdi
movq %rdx, %rsi
- addq $0x200, %rcx
- callq %rcx
+ movq %r8, %rdx
+ xor %rax, %rax
+ movl 0x264(%r8), %eax
+ addq %rax, %r9
+ addq $0x200, %r9
+ callq %r9
ret
diff --git a/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.asm b/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.asm
index ed53321c2..fc07eab68 100644
--- a/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.asm
+++ b/OvmfPkg/Library/LoadLinuxLib/X64/JumpToKernel.asm
@@ -1,6 +1,6 @@
;------------------------------------------------------------------------------
;
-; Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
;
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
@@ -24,11 +24,72 @@
;------------------------------------------------------------------------------
JumpToKernel PROC
+ ; Set up for executing kernel. BP in %esi, entry point on the stack
+ ; (64-bit when the 'ret' will use it as 32-bit, but we're little-endian)
+ mov rsi, rdx
+ push rcx
+
+ ; Jump into the compatibility mode CS
+ push 10h
+ lea rax, @F
+ push rax
+ DB 048h, 0cbh ; retfq
+
+@@:
+ ; Now in compatibility mode.
+
+ DB 0b8h, 018h, 000h, 000h, 000h ; movl $0x18, %eax
+ DB 08eh, 0d8h ; movl %eax, %ds
+ DB 08eh, 0c0h ; movl %eax, %es
+ DB 08eh, 0e0h ; movl %eax, %fs
+ DB 08eh, 0e8h ; movl %eax, %gs
+ DB 08eh, 0d0h ; movl %eax, %ss
+
+ ; Disable paging
+ DB 00fh, 020h, 0c0h ; movl %cr0, %eax
+ DB 00fh, 0bah, 0f8h, 01fh ; btcl $31, %eax
+ DB 00fh, 022h, 0c0h ; movl %eax, %cr0
+
+ ; Disable long mode in EFER
+ DB 0b9h, 080h, 000h, 000h, 0c0h ; movl $0x0c0000080, %ecx
+ DB 00fh, 032h ; rdmsr
+ DB 00fh, 0bah, 0f8h, 008h ; btcl $8, %eax
+ DB 00fh, 030h ; wrmsr
+
+ ; Disable PAE
+ DB 00fh, 020h, 0e0h ; movl %cr4, %eax
+ DB 00fh, 0bah, 0f8h, 005h ; btcl $5, %eax
+ DB 00fh, 022h, 0e0h ; movl %eax, %cr4
+
+ DB 031h, 0edh ; xor %ebp, %ebp
+ DB 031h, 0ffh ; xor %edi, %edi
+ DB 031h, 0dbh ; xor %ebx, %ebx
+ DB 0c3h ; ret
+
+JumpToKernel ENDP
+
+;------------------------------------------------------------------------------
+; VOID
+; EFIAPI
+; JumpToUefiKernel (
+; EFI_HANDLE ImageHandle, // rcx
+; EFI_SYSTEM_TABLE *SystemTable, // rdx
+; VOID *KernelBootParams // r8
+; VOID *KernelStart, // r9
+; );
+;------------------------------------------------------------------------------
+JumpToUefiKernel PROC
+
+ mov rdi, rcx
mov rsi, rdx
- add rcx, 200h
- call rcx
+ mov rdx, r8
+ xor rax, rax
+ mov eax, [r8 + 264h]
+ add r9, rax
+ add r9, 200h
+ call r9
ret
-JumpToKernel ENDP
+JumpToUefiKernel ENDP
END
diff --git a/OvmfPkg/Library/PlatformBdsLib/QemuKernel.c b/OvmfPkg/Library/PlatformBdsLib/QemuKernel.c
index fa8bcbc9b..47ebed9f6 100644
--- a/OvmfPkg/Library/PlatformBdsLib/QemuKernel.c
+++ b/OvmfPkg/Library/PlatformBdsLib/QemuKernel.c
@@ -1,6 +1,6 @@
/** @file
- Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -78,6 +78,11 @@ TryRunningQemuKernel (
goto FreeAndReturn;
}
+ Status = LoadLinuxInitializeKernelSetup (SetupBuf);
+ if (EFI_ERROR (Status)) {
+ goto FreeAndReturn;
+ }
+
KernelInitialSize = LoadLinuxGetKernelSize (SetupBuf, KernelSize);
if (KernelInitialSize == 0) {
Status = EFI_UNSUPPORTED;
diff --git a/OvmfPkg/build.sh b/OvmfPkg/build.sh
index 61b3ff85c..f64ea9159 100755
--- a/OvmfPkg/build.sh
+++ b/OvmfPkg/build.sh
@@ -1,7 +1,7 @@
#!/bin/bash
#
# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -58,15 +58,20 @@ case `uname` in
echo Cygwin not fully supported yet.
;;
Darwin*)
- Major=$(uname -r | cut -f 1 -d '.')
- if [[ $Major == 9 ]]
- then
+ Major=$(uname -r | cut -f 1 -d '.')
+ case $Major in
+ 10)
+ TARGET_TOOLS=XCODE32
+ ;;
+ 1[12])
+ TARGET_TOOLS=XCLANG
+ ;;
+ *)
echo OvmfPkg requires Snow Leopard or later OS
exit 1
- else
- TARGET_TOOLS=XCODE32
- fi
- ;;
+ ;;
+ esac
+ ;;
Linux*)
gcc_version=$(gcc -v 2>&1 | tail -1 | awk '{print $3}')
case $gcc_version in
@@ -134,7 +139,16 @@ done
case $PROCESSOR in
IA32)
Processor=Ia32
- QEMU_COMMAND=qemu
+ if [ -x `which qemu-system-i386` ]; then
+ QEMU_COMMAND=qemu-system-i386
+ elif [ -x `which qemu-system-x86_64` ]; then
+ QEMU_COMMAND=qemu-system-x86_64
+ elif [ -x `which qemu` ]; then
+ QEMU_COMMAND=qemu
+ else
+ echo Unable to find QEMU for IA32 architecture!
+ exit 1
+ fi
;;
X64)
Processor=X64
diff --git a/PandaBoardPkg/Tools/chtool b/PandaBoardPkg/Tools/chtool
new file mode 100755
index 000000000..a18bdc9a9
--- /dev/null
+++ b/PandaBoardPkg/Tools/chtool
Binary files differ
diff --git a/PandaBoardPkg/build.sh b/PandaBoardPkg/build.sh
index 8002eac26..dc4b9067d 100755
--- a/PandaBoardPkg/build.sh
+++ b/PandaBoardPkg/build.sh
@@ -85,12 +85,23 @@ then
fi
TARGET=DEBUG
-for arg in "$@"
+BUILD_TARGET=DEBUG
+args=($@)
+
+for (( i=0; i<$#; i++ ))
do
- if [[ $arg == RELEASE ]];
- then
- TARGET=RELEASE
- fi
+ if [[ "${args[$i]}" == "-b" ]]
+ then
+ TARGET=${args[$i+1]}
+ BUILD_TARGET=$TARGET
+ if [[ "$TARGET" == "RELEASE" ]]
+ then
+ BUILD_TARGET="$BUILD_TARGET -D DEBUG_TARGET=RELEASE"
+ fi
+ i=$i+1
+ else
+ other_args="$other_args ${args[$i]}"
+ fi
done
BUILD_ROOT=$WORKSPACE/Build/PandaBoard/"$TARGET"_"$TARGET_TOOLS"
@@ -109,12 +120,7 @@ fi
#
# Build the edk2 PandaBoard code
#
-if [[ $TARGET == RELEASE ]]; then
- build -p $WORKSPACE/PandaBoardPkg/PandaBoardPkg.dsc -a ARM -t $TARGET_TOOLS -b $TARGET -D DEBUG_TARGET=RELEASE ${2:-} ${3:-} ${4:-} ${5:-} ${6:-} ${7:-} ${8:-}
-else
- build -p ${WORKSPACE:-}/PandaBoardPkg/PandaBoardPkg.dsc -a ARM -t $TARGET_TOOLS -b $TARGET ${1:-} ${2:-} ${3:-} ${4:-} ${5:-} ${6:-} ${7:-} ${8:-}
-fi
-
+build -p $WORKSPACE/PandaBoardPkg/PandaBoardPkg.dsc -a ARM -t $TARGET_TOOLS -b $BUILD_TARGET $other_args
for arg in "$@"
do
diff --git a/SamsungPlatformPkg/ArndaleBoardPkg/ArndaleBoardPkg.dsc.inc b/SamsungPlatformPkg/ArndaleBoardPkg/ArndaleBoardPkg.dsc.inc
index 04a18e9ea..671ef131a 100644
--- a/SamsungPlatformPkg/ArndaleBoardPkg/ArndaleBoardPkg.dsc.inc
+++ b/SamsungPlatformPkg/ArndaleBoardPkg/ArndaleBoardPkg.dsc.inc
@@ -296,11 +296,13 @@ ArmPlatformSecLib|ArmPlatformPkg/Library/ArmPlatformSecLibNull/ArmPlatformLibNul
# ARM OS Loader
#
gArmTokenSpaceGuid.PcdArmMachineType|2456
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"SD-MMC Booting"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(3A02E7FE-0649-4FB4-BE4F-A862CA1872A9)/HD(2,MBR,0x000A65DC,0x59B303,0x3B7C)/uImage"
- gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(3A02E7FE-0649-4FB4-BE4F-A862CA1872A9)/HD(2,MBR,0x000A65DC,0x59B303,0x3B7C)/exynos5250-arndale.dtb"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"root=/dev/mmcblk1p1 rw rootwait console=ttySAC2,115200n8 init --no-log"
- gArmPlatformTokenSpaceGuid.PcdDefaultBootType|2
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDescription|L"Linaro image on SD card"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootDevicePath|L"VenHw(3A02E7FE-0649-4FB4-BE4F-A862CA1872A9)/HD(2,MBR,0x00000000,0x2000,0x1A000)/uImage"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootInitrdPath|L"VenHw(3A02E7FE-0649-4FB4-BE4F-A862CA1872A9)/HD(2,MBR,0x00000000,0x2000,0x1A000)/uInitrd"
+ gArmPlatformTokenSpaceGuid.PcdDefaultFdtLocalDevicePath|L"VenHw(3A02E7FE-0649-4FB4-BE4F-A862CA1872A9)/HD(2,MBR,0x00000000,0x2000,0x1A000)/board.dtb"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootArgument|"root=/dev/mmcblk1p3 rw rootwait console=ttySAC2,115200n8 init --no-log"
+ gArmPlatformTokenSpaceGuid.PcdDefaultBootType|3
+ gArmPlatformTokenSpaceGuid.PcdFdtDevicePath|L"VenHw(3A02E7FE-0649-4FB4-BE4F-A862CA1872A9)/HD(2,MBR,0x00000000,0x2000,0x1A000)/board.dtb"
# Use the Serial console (ConIn & ConOut) and the Graphic driver (ConOut)
gArmPlatformTokenSpaceGuid.PcdDefaultConOutPaths|L"VenHw(D3987D4B-971A-435F-8CAF-4967EB627241)/Uart(115200,8,N,1)/VenPcAnsi();VenHw(9042A9DE-23DC-4A38-96FB-7ADED080516A)"
diff --git a/SamsungPlatformPkg/ArndaleBoardPkg/arndale-Exynos5250.dsc b/SamsungPlatformPkg/ArndaleBoardPkg/arndale-Exynos5250.dsc
index 6116f4eab..a545e8077 100755
--- a/SamsungPlatformPkg/ArndaleBoardPkg/arndale-Exynos5250.dsc
+++ b/SamsungPlatformPkg/ArndaleBoardPkg/arndale-Exynos5250.dsc
@@ -104,9 +104,12 @@
gArmTokenSpaceGuid.PcdFdSize|0x00200000 # Must be equal to gEmbeddedTokenSpaceGuid.PcdFlashFvMainSize
# System Memory (256MB)
- gArmTokenSpaceGuid.PcdSystemMemoryBase|0x50000000 #0x40000000
+ gArmTokenSpaceGuid.PcdSystemMemoryBase|0x40000000
gArmTokenSpaceGuid.PcdSystemMemorySize|0x50000000
+ #FDT offset
+ gArmTokenSpaceGuid.PcdArmLinuxFdtMaxOffset|0x9000000
+
# Size of the region used by UEFI in permanent memory (Reserved 64MB)
gArmPlatformTokenSpaceGuid.PcdSystemMemoryUefiRegionSize|0x04000000
diff --git a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/DisplayDxe/DisplayDxe.c b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/DisplayDxe/DisplayDxe.c
index b9029c45d..d1b5a3be6 100644
--- a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/DisplayDxe/DisplayDxe.c
+++ b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/DisplayDxe/DisplayDxe.c
@@ -529,7 +529,6 @@ DisplayBlt(
IN UINTN Delta OPTIONAL
)
{
- EFI_STATUS Status=EFI_SUCCESS;
UINT8 *VidBuf, *BltBuf, *VidBuf1;
UINTN i, j;
@@ -604,7 +603,7 @@ DisplayBlt(
break;
default:
- ASSERT_EFI_ERROR(Status);
+ ASSERT_EFI_ERROR(EFI_SUCCESS);
}
return EFI_SUCCESS;
diff --git a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/SDHCDxe_EVT1/SDHCDxe.c b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/SDHCDxe_EVT1/SDHCDxe.c
index 70dbae15d..0c3a219a4 100755
--- a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/SDHCDxe_EVT1/SDHCDxe.c
+++ b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/SDHCDxe_EVT1/SDHCDxe.c
@@ -118,7 +118,7 @@ MSHC_SendCmd (
UINTN CmdArgument
)
{
- UINTN MmcStatus;
+ UINTN MmcStatus = 0;
volatile UINTN RetryCount = 0;
int cmd_flags = 0;
int timeout=0;
@@ -246,13 +246,14 @@ static const UINT8 MultiFactor[16]={0, 10, 12, 13, 15, 20, 26, 30, 35, 40, 45, 5
void PrintCardInfo()
{
+#if !defined(MDEPKG_NDEBUG)
UINT8 TransSpeed = gCardInfo.CSDData.TRAN_SPEED;
DEBUG ((EFI_D_INFO, "SDHC::READ_BL_LEN %d\n", gCardInfo.CSDData.READ_BL_LEN));
DEBUG ((EFI_D_INFO, "SDHC::CSize %d\n", gCardInfo.CSDData.C_SIZELow2 | (gCardInfo.CSDData.C_SIZEHigh10 << 2)));
DEBUG ((EFI_D_INFO, "SDHC::MULTI %d\n", gCardInfo.CSDData.C_SIZE_MULT));
DEBUG ((EFI_D_INFO, "SDHC::Speed %d\n", (FreqUnit[TransSpeed&0x7]*MultiFactor[TransSpeed>>3])));
-
+#endif
}
@@ -599,7 +600,7 @@ ReadBlockData (
IN UINTN BlockCount
)
{
- EFI_STATUS Status;
+ EFI_STATUS Status = EFI_INVALID_PARAMETER;
UINTN DataSize = This->Media->BlockSize/4;
DEBUG ((EFI_D_INFO, "SDHC::ReadBlockData start \n"));
@@ -625,7 +626,7 @@ WriteBlockData (
IN UINTN BlockCount
)
{
- EFI_STATUS Status;
+ EFI_STATUS Status = EFI_INVALID_PARAMETER;
UINTN DataSize = This->Media->BlockSize/4;
if(MSHC_operation_mode == MSHC_FIFO)
diff --git a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.c b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.c
index c38001a5c..87f937924 100755
--- a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.c
+++ b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.c
@@ -123,7 +123,7 @@ MSHC_SendCmd (
UINTN CmdArgument
)
{
- UINTN MmcStatus;
+ UINTN MmcStatus = 0;
volatile UINTN RetryCount = 0;
int cmd_flags = 0;
int timeout=0;
@@ -580,7 +580,7 @@ ReadBlockData (
IN UINTN BlockCount
)
{
- EFI_STATUS Status;
+ EFI_STATUS Status = EFI_INVALID_PARAMETER;
UINTN DataSize = This->Media->BlockSize/4;
DEBUG ((EFI_D_INFO, "MSHC::ReadBlockData start \n"));
@@ -606,7 +606,7 @@ WriteBlockData (
IN UINTN BlockCount
)
{
- EFI_STATUS Status;
+ EFI_STATUS Status = EFI_INVALID_PARAMETER;
UINTN DataSize = This->Media->BlockSize/4;
if(MSHC_operation_mode == MSHC_FIFO)
@@ -840,7 +840,6 @@ DetectCard (
gSDMMCMedia.MediaId++;
UpdateMSHCClkFrequency(MSHC_CLK_50M);
- MSHC_EMMC_Boot_Open(); //do not close boot partition
DEBUG ((EFI_D_INFO, "SD Card Media Change on Handle 0x%08x\n", gImageHandle));
return Status;
diff --git a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.h b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.h
index 9bbf13a20..e410d669e 100755
--- a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.h
+++ b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Drivers/eMMCDxe/eMMCDxe.h
@@ -65,7 +65,7 @@ NV data for general purpose : 3400
#define BLEN_512BYTES (0x200)
#define BLKSIZE_1 (0x1)
-#define OM_EMMC 0x28
+#define OM_EMMC 0x8
#define MAX_RETRY_COUNT (100000)
#define MMC_REFERENCE_CLK (96000000)
diff --git a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Sec/SecEntryPoint.S b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Sec/SecEntryPoint.S
index a10eae12a..08a893cb0 100644
--- a/SamsungPlatformPkg/ExynosPkg/Exynos5250/Sec/SecEntryPoint.S
+++ b/SamsungPlatformPkg/ExynosPkg/Exynos5250/Sec/SecEntryPoint.S
@@ -198,7 +198,7 @@ _CopyFirmware:
ldr r1, [r0,#0x0]
bic r2, r1, #0xffffffc1
- cmp r2, #0x28
+ cmp r2, #0x8
beq _CopyFirmwareEMMC
/* SD/MMC BOOT */
diff --git a/SecurityPkg/Library/DxeTcgPhysicalPresenceLib/DxeTcgPhysicalPresenceLib.c b/SecurityPkg/Library/DxeTcgPhysicalPresenceLib/DxeTcgPhysicalPresenceLib.c
index 44845b0f8..3414cd2ea 100644
--- a/SecurityPkg/Library/DxeTcgPhysicalPresenceLib/DxeTcgPhysicalPresenceLib.c
+++ b/SecurityPkg/Library/DxeTcgPhysicalPresenceLib/DxeTcgPhysicalPresenceLib.c
@@ -8,7 +8,7 @@
ExecutePendingTpmRequest() will receive untrusted input and do validation.
-Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -1010,13 +1010,6 @@ ExecutePendingTpmRequest (
UINTN DataSize;
BOOLEAN RequestConfirmed;
- if (TcgPpData->PPRequest == PHYSICAL_PRESENCE_NO_ACTION) {
- //
- // No operation request
- //
- return;
- }
-
if (!HaveValidTpmRequest(TcgPpData, &RequestConfirmed)) {
//
// Invalid operation request.
@@ -1165,6 +1158,13 @@ TcgPhysicalPresenceLibProcessRequest (
DEBUG ((EFI_D_INFO, "[TPM] Flags=%x, PPRequest=%x\n", TcgPpData.Flags, TcgPpData.PPRequest));
+ if (TcgPpData.PPRequest == PHYSICAL_PRESENCE_NO_ACTION) {
+ //
+ // No operation request
+ //
+ return;
+ }
+
Status = GetTpmCapability (TcgProtocol, &LifetimeLock, &CmdEnable);
if (EFI_ERROR (Status)) {
return ;
diff --git a/SecurityPkg/VariableAuthenticated/Pei/Variable.c b/SecurityPkg/VariableAuthenticated/Pei/Variable.c
index d27f67907..38b9170aa 100644
--- a/SecurityPkg/VariableAuthenticated/Pei/Variable.c
+++ b/SecurityPkg/VariableAuthenticated/Pei/Variable.c
@@ -3,7 +3,7 @@
ReadOnly Varaiable2 PPI. These services operates the non-volatile
storage space.
-Copyright (c) 2009 - 2011, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -428,6 +428,7 @@ FindVariableEx (
UINTN Index;
UINTN Offset;
BOOLEAN StopRecord;
+ VARIABLE_HEADER *InDeletedVariable;
if (VariableStoreHeader == NULL) {
return EFI_INVALID_PARAMETER;
@@ -444,6 +445,8 @@ FindVariableEx (
PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader);
PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader);
+ InDeletedVariable = NULL;
+
//
// No Variable Address equals zero, so 0 as initial value is safe.
//
@@ -459,15 +462,20 @@ FindVariableEx (
Offset += IndexTable->Index[Index];
MaxIndex = (VARIABLE_HEADER *) ((UINT8 *) IndexTable->StartPtr + Offset);
if (CompareWithValidVariable (MaxIndex, VariableName, VendorGuid, PtrTrack) == EFI_SUCCESS) {
- return EFI_SUCCESS;
+ if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ InDeletedVariable = PtrTrack->CurrPtr;
+ } else {
+ return EFI_SUCCESS;
+ }
}
}
if (IndexTable->GoneThrough != 0) {
//
- // If the table has all the existing variables indexed and we still cannot find it.
+ // If the table has all the existing variables indexed, return.
//
- return EFI_NOT_FOUND;
+ PtrTrack->CurrPtr = InDeletedVariable;
+ return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
}
}
@@ -488,11 +496,11 @@ FindVariableEx (
}
//
- // Find the variable by walk through non-volatile variable store
+ // Find the variable by walk through variable store
//
StopRecord = FALSE;
while ((Variable < PtrTrack->EndPtr) && IsValidVariableHeader (Variable)) {
- if (Variable->State == VAR_ADDED) {
+ if (Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
//
// Record Variable in VariableIndex HOB
//
@@ -511,7 +519,11 @@ FindVariableEx (
}
if (CompareWithValidVariable (Variable, VariableName, VendorGuid, PtrTrack) == EFI_SUCCESS) {
- return EFI_SUCCESS;
+ if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ InDeletedVariable = PtrTrack->CurrPtr;
+ } else {
+ return EFI_SUCCESS;
+ }
}
}
@@ -524,9 +536,9 @@ FindVariableEx (
IndexTable->GoneThrough = 1;
}
- PtrTrack->CurrPtr = NULL;
+ PtrTrack->CurrPtr = InDeletedVariable;
- return EFI_NOT_FOUND;
+ return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;
}
/**
@@ -689,6 +701,8 @@ PeiGetNextVariableName (
VARIABLE_STORE_TYPE Type;
VARIABLE_POINTER_TRACK Variable;
VARIABLE_POINTER_TRACK VariableInHob;
+ VARIABLE_POINTER_TRACK VariablePtrTrack;
+ VARIABLE_INDEX_TABLE *IndexTable;
UINTN VarNameSize;
EFI_STATUS Status;
VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
@@ -750,7 +764,32 @@ PeiGetNextVariableName (
Variable.CurrPtr = Variable.StartPtr;
}
- if (Variable.CurrPtr->State == VAR_ADDED) {
+ if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ //
+ // If it is a IN_DELETED_TRANSITION variable,
+ // and there is also a same ADDED one at the same time,
+ // don't return it.
+ //
+ for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {
+ if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {
+ break;
+ }
+ }
+ ASSERT (Type < VariableStoreTypeMax);
+ GetVariableStore (Type, &IndexTable);
+ Status = FindVariableEx (
+ VariableStoreHeader[Type],
+ IndexTable,
+ GetVariableNamePtr (Variable.CurrPtr),
+ &Variable.CurrPtr->VendorGuid,
+ &VariablePtrTrack
+ );
+ if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
+ Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+ continue;
+ }
+ }
//
// Don't return NV variable when HOB overrides it
diff --git a/SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c b/SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
index 64ce968ac..8552d31b2 100644
--- a/SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
+++ b/SecurityPkg/VariableAuthenticated/RuntimeDxe/AuthService.c
@@ -15,7 +15,7 @@
They will do basic validation for authentication data structure, then call crypto library
to verify the signature.
-Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -356,30 +356,23 @@ AutenticatedVariableServiceInitialize (
DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_SECURE_BOOT_ENABLE_NAME, SecureBootEnable));
//
- // Check "CustomMode" variable's existence.
+ // Initialize "CustomMode" in STANDARD_SECURE_BOOT_MODE state.
//
FindVariable (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE);
- if (Variable.CurrPtr != NULL) {
- CustomMode = *(GetVariableDataPtr (Variable.CurrPtr));
- } else {
- //
- // "CustomMode" not exist, initialize it in STANDARD_SECURE_BOOT_MODE.
- //
- CustomMode = STANDARD_SECURE_BOOT_MODE;
- Status = UpdateVariable (
- EFI_CUSTOM_MODE_NAME,
- &gEfiCustomModeEnableGuid,
- &CustomMode,
- sizeof (UINT8),
- EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
- 0,
- 0,
- &Variable,
- NULL
- );
- if (EFI_ERROR (Status)) {
- return Status;
- }
+ CustomMode = STANDARD_SECURE_BOOT_MODE;
+ Status = UpdateVariable (
+ EFI_CUSTOM_MODE_NAME,
+ &gEfiCustomModeEnableGuid,
+ &CustomMode,
+ sizeof (UINT8),
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
+ 0,
+ 0,
+ &Variable,
+ NULL
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
}
DEBUG ((EFI_D_INFO, "Variable %s is %x\n", EFI_CUSTOM_MODE_NAME, CustomMode));
@@ -437,6 +430,8 @@ AddPubKeyInStore (
UINT32 Index;
VARIABLE_POINTER_TRACK Variable;
UINT8 *Ptr;
+ UINT8 *Data;
+ UINTN DataSize;
if (PubKey == NULL) {
return 0;
@@ -468,9 +463,45 @@ AddPubKeyInStore (
//
if (mPubKeyNumber == MAX_KEY_NUM) {
//
- // Notes: Database is full, need enhancement here, currently just return 0.
+ // Public key dadatase is full, try to reclaim invalid key.
//
- return 0;
+ if (AtRuntime ()) {
+ //
+ // NV storage can't reclaim at runtime.
+ //
+ return 0;
+ }
+
+ Status = Reclaim (
+ mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
+ &mVariableModuleGlobal->NonVolatileLastVariableOffset,
+ FALSE,
+ NULL,
+ TRUE,
+ TRUE
+ );
+ if (EFI_ERROR (Status)) {
+ return 0;
+ }
+
+ Status = FindVariable (
+ AUTHVAR_KEYDB_NAME,
+ &gEfiAuthenticatedVariableGuid,
+ &Variable,
+ &mVariableModuleGlobal->VariableGlobal,
+ FALSE
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ DataSize = DataSizeOfVariable (Variable.CurrPtr);
+ Data = GetVariableDataPtr (Variable.CurrPtr);
+ ASSERT ((DataSize != 0) && (Data != NULL));
+ CopyMem (mPubKeyStore, (UINT8 *) Data, DataSize);
+ mPubKeyNumber = (UINT32) (DataSize / EFI_CERT_TYPE_RSA2048_SIZE);
+
+ if (mPubKeyNumber == MAX_KEY_NUM) {
+ return 0;
+ }
}
CopyMem (mPubKeyStore + mPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE, PubKey, EFI_CERT_TYPE_RSA2048_SIZE);
diff --git a/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c b/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
index 5f023dfde..ce4f6e813 100644
--- a/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
+++ b/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
@@ -16,7 +16,7 @@
VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,
integer overflow. It should also check attribute to avoid authentication bypass.
-Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -511,21 +511,157 @@ GetEndPointer (
return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size);
}
+/**
+
+ Check the PubKeyIndex is a valid key or not.
+
+ This function will iterate the NV storage to see if this PubKeyIndex is still referenced
+ by any valid count-based auth variabe.
+
+ @param[in] PubKeyIndex Index of the public key in public key store.
+
+ @retval TRUE The PubKeyIndex is still in use.
+ @retval FALSE The PubKeyIndex is not referenced by any count-based auth variabe.
+
+**/
+BOOLEAN
+IsValidPubKeyIndex (
+ IN UINT32 PubKeyIndex
+ )
+{
+ VARIABLE_HEADER *Variable;
+
+ if (PubKeyIndex > mPubKeyNumber) {
+ return FALSE;
+ }
+
+ Variable = GetStartPointer (mNvVariableCache);
+
+ while (IsValidVariableHeader (Variable)) {
+ if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) &&
+ Variable->PubKeyIndex == PubKeyIndex) {
+ return TRUE;
+ }
+ Variable = GetNextVariablePtr (Variable);
+ }
+
+ return FALSE;
+}
/**
- Variable store garbage collection and reclaim operation.
+ Get the number of valid public key in PubKeyStore.
+
+ @param[in] PubKeyNumber Number of the public key in public key store.
- @param VariableBase Base address of variable store.
- @param LastVariableOffset Offset of last variable.
- @param IsVolatile The variable store is volatile or not;
- if it is non-volatile, need FTW.
- @param UpdatingVariable Pointer to updating variable.
- @param ReclaimAnyway If TRUE, do reclaim anyway.
+ @return Number of valid public key in PubKeyStore.
- @return EFI_OUT_OF_RESOURCES
- @return EFI_SUCCESS
- @return Others
+**/
+UINT32
+GetValidPubKeyNumber (
+ IN UINT32 PubKeyNumber
+ )
+{
+ UINT32 PubKeyIndex;
+ UINT32 Counter;
+
+ Counter = 0;
+
+ for (PubKeyIndex = 1; PubKeyIndex <= PubKeyNumber; PubKeyIndex++) {
+ if (IsValidPubKeyIndex (PubKeyIndex)) {
+ Counter++;
+ }
+ }
+
+ return Counter;
+}
+
+/**
+
+ Filter the useless key in public key store.
+
+ This function will find out all valid public keys in public key database, save them in new allocated
+ buffer NewPubKeyStore, and give the new PubKeyIndex. The caller is responsible for freeing buffer
+ NewPubKeyIndex and NewPubKeyStore with FreePool().
+
+ @param[in] PubKeyStore Point to the public key database.
+ @param[in] PubKeyNumber Number of the public key in PubKeyStore.
+ @param[out] NewPubKeyIndex Point to an array of new PubKeyIndex corresponds to NewPubKeyStore.
+ @param[out] NewPubKeyStore Saved all valid public keys in PubKeyStore.
+ @param[out] NewPubKeySize Buffer size of the NewPubKeyStore.
+
+ @retval EFI_SUCCESS Trim operation is complete successfully.
+ @retval EFI_OUT_OF_RESOURCES No enough memory resources, or no useless key in PubKeyStore.
+
+**/
+EFI_STATUS
+PubKeyStoreFilter (
+ IN UINT8 *PubKeyStore,
+ IN UINT32 PubKeyNumber,
+ OUT UINT32 **NewPubKeyIndex,
+ OUT UINT8 **NewPubKeyStore,
+ OUT UINT32 *NewPubKeySize
+ )
+{
+ UINT32 PubKeyIndex;
+ UINT32 CopiedKey;
+ UINT32 NewPubKeyNumber;
+
+ NewPubKeyNumber = GetValidPubKeyNumber (PubKeyNumber);
+ if (NewPubKeyNumber == PubKeyNumber) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ if (NewPubKeyNumber != 0) {
+ *NewPubKeySize = NewPubKeyNumber * EFI_CERT_TYPE_RSA2048_SIZE;
+ } else {
+ *NewPubKeySize = sizeof (UINT8);
+ }
+
+ *NewPubKeyStore = AllocatePool (*NewPubKeySize);
+ if (*NewPubKeyStore == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ *NewPubKeyIndex = AllocateZeroPool ((PubKeyNumber + 1) * sizeof (UINT32));
+ if (*NewPubKeyIndex == NULL) {
+ FreePool (*NewPubKeyStore);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ CopiedKey = 0;
+ for (PubKeyIndex = 1; PubKeyIndex <= PubKeyNumber; PubKeyIndex++) {
+ if (IsValidPubKeyIndex (PubKeyIndex)) {
+ CopyMem (
+ *NewPubKeyStore + CopiedKey * EFI_CERT_TYPE_RSA2048_SIZE,
+ PubKeyStore + (PubKeyIndex - 1) * EFI_CERT_TYPE_RSA2048_SIZE,
+ EFI_CERT_TYPE_RSA2048_SIZE
+ );
+ (*NewPubKeyIndex)[PubKeyIndex] = ++CopiedKey;
+ }
+ }
+ return EFI_SUCCESS;
+}
+
+/**
+
+ Variable store garbage collection and reclaim operation.
+
+ If ReclaimPubKeyStore is FALSE, reclaim variable space by deleting the obsoleted varaibles.
+ If ReclaimPubKeyStore is TRUE, reclaim invalid key in public key database and update the PubKeyIndex
+ for all the count-based authenticate variable in NV storage.
+
+ @param[in] VariableBase Base address of variable store.
+ @param[out] LastVariableOffset Offset of last variable.
+ @param[in] IsVolatile The variable store is volatile or not;
+ if it is non-volatile, need FTW.
+ @param[in, out] UpdatingPtrTrack Pointer to updating variable pointer track structure.
+ @param[in] ReclaimPubKeyStore Reclaim for public key database or not.
+ @param[in] ReclaimAnyway If TRUE, do reclaim anyway.
+
+ @return EFI_OUT_OF_RESOURCES No enough memory resources.
+ @return EFI_SUCCESS Reclaim operation has finished successfully.
+ @return Others Unexpect error happened during reclaim operation.
**/
EFI_STATUS
@@ -533,7 +669,8 @@ Reclaim (
IN EFI_PHYSICAL_ADDRESS VariableBase,
OUT UINTN *LastVariableOffset,
IN BOOLEAN IsVolatile,
- IN VARIABLE_HEADER *UpdatingVariable,
+ IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack,
+ IN BOOLEAN ReclaimPubKeyStore,
IN BOOLEAN ReclaimAnyway
)
{
@@ -557,14 +694,28 @@ Reclaim (
CHAR16 *UpdatingVariableNamePtr;
UINTN CommonVariableTotalSize;
UINTN HwErrVariableTotalSize;
+ UINT32 *NewPubKeyIndex;
+ UINT8 *NewPubKeyStore;
+ UINT32 NewPubKeySize;
+ VARIABLE_HEADER *PubKeyHeader;
BOOLEAN NeedDoReclaim;
+ VARIABLE_HEADER *UpdatingVariable;
+
+ UpdatingVariable = NULL;
+ if (UpdatingPtrTrack != NULL) {
+ UpdatingVariable = UpdatingPtrTrack->CurrPtr;
+ }
NeedDoReclaim = FALSE;
VariableStoreHeader = (VARIABLE_STORE_HEADER *) ((UINTN) VariableBase);
CommonVariableTotalSize = 0;
HwErrVariableTotalSize = 0;
-
+ NewPubKeyIndex = NULL;
+ NewPubKeyStore = NULL;
+ NewPubKeySize = 0;
+ PubKeyHeader = NULL;
+
//
// Start Pointers for the variable.
//
@@ -608,95 +759,91 @@ Reclaim (
CopyMem (ValidBuffer, VariableStoreHeader, sizeof (VARIABLE_STORE_HEADER));
CurrPtr = (UINT8 *) GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
- //
- // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
- //
- Variable = GetStartPointer (VariableStoreHeader);
- while (IsValidVariableHeader (Variable)) {
- NextVariable = GetNextVariablePtr (Variable);
- if (Variable->State == VAR_ADDED) {
- if (UpdatingVariable != NULL) {
- if (UpdatingVariable == Variable) {
- Variable = NextVariable;
- continue;
- }
-
- VariableNameSize = NameSizeOfVariable(Variable);
- UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);
+ if (ReclaimPubKeyStore) {
+ //
+ // Trim the PubKeyStore and get new PubKeyIndex.
+ //
+ Status = PubKeyStoreFilter (
+ mPubKeyStore,
+ mPubKeyNumber,
+ &NewPubKeyIndex,
+ &NewPubKeyStore,
+ &NewPubKeySize
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (ValidBuffer);
+ return Status;
+ }
- VariableNamePtr = GetVariableNamePtr (Variable);
- UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable);
- if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid) &&
- VariableNameSize == UpdatingVariableNameSize &&
- CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) {
+ //
+ // Refresh the PubKeyIndex for all valid variables (ADDED and IN_DELETED_TRANSITION).
+ //
+ Variable = GetStartPointer (mNvVariableCache);
+ while (IsValidVariableHeader (Variable)) {
+ NextVariable = GetNextVariablePtr (Variable);
+ if (Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ if ((StrCmp (GetVariableNamePtr (Variable), AUTHVAR_KEYDB_NAME) == 0) &&
+ (CompareGuid (&Variable->VendorGuid, &gEfiAuthenticatedVariableGuid))) {
+ //
+ // Skip the public key database, it will be reinstalled later.
+ //
+ PubKeyHeader = Variable;
Variable = NextVariable;
continue;
}
+
+ VariableSize = (UINTN) NextVariable - (UINTN) Variable;
+ CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
+ ((VARIABLE_HEADER*) CurrPtr)->PubKeyIndex = NewPubKeyIndex[Variable->PubKeyIndex];
+ CurrPtr += VariableSize;
+ if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+ HwErrVariableTotalSize += VariableSize;
+ } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+ CommonVariableTotalSize += VariableSize;
+ }
}
- VariableSize = (UINTN) NextVariable - (UINTN) Variable;
- CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
- CurrPtr += VariableSize;
- if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
- HwErrVariableTotalSize += VariableSize;
- } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
- CommonVariableTotalSize += VariableSize;
- }
- }
- Variable = NextVariable;
- }
-
- //
- // Reinstall the variable being updated if it is not NULL.
- //
- if (UpdatingVariable != NULL) {
- VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable;
- CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize);
- CurrPtr += VariableSize;
- if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
- HwErrVariableTotalSize += VariableSize;
- } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
- CommonVariableTotalSize += VariableSize;
+ Variable = NextVariable;
}
- }
- //
- // Reinstall all in delete transition variables.
- //
- Variable = GetStartPointer (VariableStoreHeader);
- while (IsValidVariableHeader (Variable)) {
- NextVariable = GetNextVariablePtr (Variable);
- if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ //
+ // Reinstall the new public key database.
+ //
+ ASSERT (PubKeyHeader != NULL);
+ CopyMem (CurrPtr, (UINT8*) PubKeyHeader, sizeof (VARIABLE_HEADER));
+ Variable = (VARIABLE_HEADER*) CurrPtr;
+ Variable->DataSize = NewPubKeySize;
+ StrCpy (GetVariableNamePtr (Variable), GetVariableNamePtr (PubKeyHeader));
+ CopyMem (GetVariableDataPtr (Variable), NewPubKeyStore, NewPubKeySize);
+ CurrPtr = (UINT8*) GetNextVariablePtr (Variable);
+ CommonVariableTotalSize += (UINTN) CurrPtr - (UINTN) Variable;
+ } else {
+ //
+ // Reinstall all ADDED variables as long as they are not identical to Updating Variable.
+ //
+ Variable = GetStartPointer (VariableStoreHeader);
+ while (IsValidVariableHeader (Variable)) {
+ NextVariable = GetNextVariablePtr (Variable);
+ if (Variable->State == VAR_ADDED) {
+ if (UpdatingVariable != NULL) {
+ if (UpdatingVariable == Variable) {
+ Variable = NextVariable;
+ continue;
+ }
- //
- // Buffer has cached all ADDED variable.
- // Per IN_DELETED variable, we have to guarantee that
- // no ADDED one in previous buffer.
- //
+ VariableNameSize = NameSizeOfVariable(Variable);
+ UpdatingVariableNameSize = NameSizeOfVariable(UpdatingVariable);
- FoundAdded = FALSE;
- AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
- while (IsValidVariableHeader (AddedVariable)) {
- NextAddedVariable = GetNextVariablePtr (AddedVariable);
- NameSize = NameSizeOfVariable (AddedVariable);
- if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) &&
- NameSize == NameSizeOfVariable (Variable)
- ) {
- Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
- Point1 = (VOID *) GetVariableNamePtr (Variable);
- if (CompareMem (Point0, Point1, NameSizeOfVariable (AddedVariable)) == 0) {
- FoundAdded = TRUE;
- break;
+ VariableNamePtr = GetVariableNamePtr (Variable);
+ UpdatingVariableNamePtr = GetVariableNamePtr (UpdatingVariable);
+ if (CompareGuid (&Variable->VendorGuid, &UpdatingVariable->VendorGuid) &&
+ VariableNameSize == UpdatingVariableNameSize &&
+ CompareMem (VariableNamePtr, UpdatingVariableNamePtr, VariableNameSize) == 0 ) {
+ Variable = NextVariable;
+ continue;
}
}
- AddedVariable = NextAddedVariable;
- }
- if (!FoundAdded) {
- //
- // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
- //
VariableSize = (UINTN) NextVariable - (UINTN) Variable;
CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
- ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;
CurrPtr += VariableSize;
if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
HwErrVariableTotalSize += VariableSize;
@@ -704,9 +851,74 @@ Reclaim (
CommonVariableTotalSize += VariableSize;
}
}
+ Variable = NextVariable;
}
- Variable = NextVariable;
+ //
+ // Reinstall the variable being updated if it is not NULL.
+ //
+ if (UpdatingVariable != NULL) {
+ VariableSize = (UINTN)(GetNextVariablePtr (UpdatingVariable)) - (UINTN)UpdatingVariable;
+ CopyMem (CurrPtr, (UINT8 *) UpdatingVariable, VariableSize);
+ UpdatingPtrTrack->CurrPtr = (VARIABLE_HEADER *)((UINTN)UpdatingPtrTrack->StartPtr + ((UINTN)CurrPtr - (UINTN)GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer)));
+ UpdatingPtrTrack->InDeletedTransitionPtr = NULL;
+ CurrPtr += VariableSize;
+ if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+ HwErrVariableTotalSize += VariableSize;
+ } else if ((!IsVolatile) && ((UpdatingVariable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+ CommonVariableTotalSize += VariableSize;
+ }
+ }
+
+ //
+ // Reinstall all in delete transition variables.
+ //
+ Variable = GetStartPointer (VariableStoreHeader);
+ while (IsValidVariableHeader (Variable)) {
+ NextVariable = GetNextVariablePtr (Variable);
+ if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+
+ //
+ // Buffer has cached all ADDED variable.
+ // Per IN_DELETED variable, we have to guarantee that
+ // no ADDED one in previous buffer.
+ //
+
+ FoundAdded = FALSE;
+ AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);
+ while (IsValidVariableHeader (AddedVariable)) {
+ NextAddedVariable = GetNextVariablePtr (AddedVariable);
+ NameSize = NameSizeOfVariable (AddedVariable);
+ if (CompareGuid (&AddedVariable->VendorGuid, &Variable->VendorGuid) &&
+ NameSize == NameSizeOfVariable (Variable)
+ ) {
+ Point0 = (VOID *) GetVariableNamePtr (AddedVariable);
+ Point1 = (VOID *) GetVariableNamePtr (Variable);
+ if (CompareMem (Point0, Point1, NameSize) == 0) {
+ FoundAdded = TRUE;
+ break;
+ }
+ }
+ AddedVariable = NextAddedVariable;
+ }
+ if (!FoundAdded) {
+ //
+ // Promote VAR_IN_DELETED_TRANSITION to VAR_ADDED.
+ //
+ VariableSize = (UINTN) NextVariable - (UINTN) Variable;
+ CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize);
+ ((VARIABLE_HEADER *) CurrPtr)->State = VAR_ADDED;
+ CurrPtr += VariableSize;
+ if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+ HwErrVariableTotalSize += VariableSize;
+ } else if ((!IsVolatile) && ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD)) {
+ CommonVariableTotalSize += VariableSize;
+ }
+ }
+ }
+
+ Variable = NextVariable;
+ }
}
if (IsVolatile) {
@@ -748,6 +960,14 @@ Reclaim (
*LastVariableOffset = (UINTN) NextVariable - (UINTN) VariableBase;
}
+ if (NewPubKeyStore != NULL) {
+ FreePool (NewPubKeyStore);
+ }
+
+ if (NewPubKeyIndex != NULL) {
+ FreePool (NewPubKeyIndex);
+ }
+
FreePool (ValidBuffer);
return Status;
@@ -776,6 +996,8 @@ FindVariableEx (
VARIABLE_HEADER *InDeletedVariable;
VOID *Point;
+ PtrTrack->InDeletedTransitionPtr = NULL;
+
//
// Find the variable by walk through HOB, volatile and non-volatile variable store.
//
@@ -793,6 +1015,7 @@ FindVariableEx (
if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
InDeletedVariable = PtrTrack->CurrPtr;
} else {
+ PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
return EFI_SUCCESS;
}
} else {
@@ -804,6 +1027,7 @@ FindVariableEx (
if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
InDeletedVariable = PtrTrack->CurrPtr;
} else {
+ PtrTrack->InDeletedTransitionPtr = InDeletedVariable;
return EFI_SUCCESS;
}
}
@@ -1395,7 +1619,7 @@ AutoUpdateLangVariable (
@param[in] Attributes Attributes of the variable.
@param[in] KeyIndex Index of associated public key.
@param[in] MonotonicCount Value of associated monotonic count.
- @param[in] CacheVariable The variable information which is used to keep track of variable usage.
+ @param[in, out] CacheVariable The variable information which is used to keep track of variable usage.
@param[in] TimeStamp Value of associated TimeStamp.
@retval EFI_SUCCESS The update operation is success.
@@ -1411,7 +1635,7 @@ UpdateVariable (
IN UINT32 Attributes OPTIONAL,
IN UINT32 KeyIndex OPTIONAL,
IN UINT64 MonotonicCount OPTIONAL,
- IN VARIABLE_POINTER_TRACK *CacheVariable,
+ IN OUT VARIABLE_POINTER_TRACK *CacheVariable,
IN EFI_TIME *TimeStamp OPTIONAL
)
{
@@ -1427,7 +1651,6 @@ UpdateVariable (
BOOLEAN Volatile;
EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb;
UINT8 State;
- BOOLEAN Reclaimed;
VARIABLE_POINTER_TRACK *Variable;
VARIABLE_POINTER_TRACK NvVariable;
VARIABLE_STORE_HEADER *VariableStoreHeader;
@@ -1467,11 +1690,15 @@ UpdateVariable (
Variable->StartPtr = GetStartPointer (VariableStoreHeader);
Variable->EndPtr = GetEndPointer (VariableStoreHeader);
Variable->CurrPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));
+ if (CacheVariable->InDeletedTransitionPtr != NULL) {
+ Variable->InDeletedTransitionPtr = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->InDeletedTransitionPtr - (UINTN)CacheVariable->StartPtr));
+ } else {
+ Variable->InDeletedTransitionPtr = NULL;
+ }
Variable->Volatile = FALSE;
}
Fvb = mVariableModuleGlobal->FvbInstance;
- Reclaimed = FALSE;
//
// Tricky part: Use scratch data area at the end of volatile variable store
@@ -1519,6 +1746,32 @@ UpdateVariable (
// not delete the variable.
//
if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {
+ if (Variable->InDeletedTransitionPtr != NULL) {
+ //
+ // Both ADDED and IN_DELETED_TRANSITION variable are present,
+ // set IN_DELETED_TRANSITION one to DELETED state first.
+ //
+ State = Variable->InDeletedTransitionPtr->State;
+ State &= VAR_DELETED;
+ Status = UpdateVariableStore (
+ &mVariableModuleGlobal->VariableGlobal,
+ Variable->Volatile,
+ FALSE,
+ Fvb,
+ (UINTN) &Variable->InDeletedTransitionPtr->State,
+ sizeof (UINT8),
+ &State
+ );
+ if (!EFI_ERROR (Status)) {
+ if (!Variable->Volatile) {
+ ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
+ CacheVariable->InDeletedTransitionPtr->State = State;
+ }
+ } else {
+ goto Done;
+ }
+ }
+
State = Variable->CurrPtr->State;
State &= VAR_DELETED;
@@ -1567,11 +1820,11 @@ UpdateVariable (
DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);
CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);
- if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) ||
- (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
+ if ((CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) &&
+ ((StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) || (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE1) == 0))) ||
+ (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {
//
- // For variables with the GUID EFI_IMAGE_SECURITY_DATABASE_GUID (i.e. where the data
- // buffer is formatted as EFI_SIGNATURE_LIST), the driver shall not perform an append of
+ // For variables with formatted as EFI_SIGNATURE_LIST, the driver shall not perform an append of
// EFI_SIGNATURE_DATA values that are already part of the existing variable value.
//
BufSize = AppendSignatureList (mStorageArea, Variable->CurrPtr->DataSize, Data, DataSize);
@@ -1744,8 +1997,14 @@ UpdateVariable (
//
// Perform garbage collection & reclaim operation.
//
- Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
- &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable->CurrPtr, FALSE);
+ Status = Reclaim (
+ mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,
+ &mVariableModuleGlobal->NonVolatileLastVariableOffset,
+ FALSE,
+ Variable,
+ FALSE,
+ FALSE
+ );
if (EFI_ERROR (Status)) {
goto Done;
}
@@ -1759,7 +2018,10 @@ UpdateVariable (
Status = EFI_OUT_OF_RESOURCES;
goto Done;
}
- Reclaimed = TRUE;
+ if (Variable->CurrPtr != NULL) {
+ CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
+ CacheVariable->InDeletedTransitionPtr = NULL;
+ }
}
//
// Four steps
@@ -1859,8 +2121,14 @@ UpdateVariable (
//
// Perform garbage collection & reclaim operation.
//
- Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
- &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable->CurrPtr, FALSE);
+ Status = Reclaim (
+ mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,
+ &mVariableModuleGlobal->VolatileLastVariableOffset,
+ TRUE,
+ Variable,
+ FALSE,
+ FALSE
+ );
if (EFI_ERROR (Status)) {
goto Done;
}
@@ -1873,7 +2141,10 @@ UpdateVariable (
Status = EFI_OUT_OF_RESOURCES;
goto Done;
}
- Reclaimed = TRUE;
+ if (Variable->CurrPtr != NULL) {
+ CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr));
+ CacheVariable->InDeletedTransitionPtr = NULL;
+ }
}
NextVariable->State = VAR_ADDED;
@@ -1897,7 +2168,33 @@ UpdateVariable (
//
// Mark the old variable as deleted.
//
- if (!Reclaimed && !EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
+ if (!EFI_ERROR (Status) && Variable->CurrPtr != NULL) {
+ if (Variable->InDeletedTransitionPtr != NULL) {
+ //
+ // Both ADDED and IN_DELETED_TRANSITION old variable are present,
+ // set IN_DELETED_TRANSITION one to DELETED state first.
+ //
+ State = Variable->InDeletedTransitionPtr->State;
+ State &= VAR_DELETED;
+ Status = UpdateVariableStore (
+ &mVariableModuleGlobal->VariableGlobal,
+ Variable->Volatile,
+ FALSE,
+ Fvb,
+ (UINTN) &Variable->InDeletedTransitionPtr->State,
+ sizeof (UINT8),
+ &State
+ );
+ if (!EFI_ERROR (Status)) {
+ if (!Variable->Volatile) {
+ ASSERT (CacheVariable->InDeletedTransitionPtr != NULL);
+ CacheVariable->InDeletedTransitionPtr->State = State;
+ }
+ } else {
+ goto Done;
+ }
+ }
+
State = Variable->CurrPtr->State;
State &= VAR_DELETED;
@@ -2119,6 +2416,7 @@ VariableServiceGetNextVariableName (
VARIABLE_STORE_TYPE Type;
VARIABLE_POINTER_TRACK Variable;
VARIABLE_POINTER_TRACK VariableInHob;
+ VARIABLE_POINTER_TRACK VariablePtrTrack;
UINTN VarNameSize;
EFI_STATUS Status;
VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax];
@@ -2192,8 +2490,27 @@ VariableServiceGetNextVariableName (
//
// Variable is found
//
- if (Variable.CurrPtr->State == VAR_ADDED) {
- if ((AtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) {
+ if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {
+ if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {
+ //
+ // If it is a IN_DELETED_TRANSITION variable,
+ // and there is also a same ADDED one at the same time,
+ // don't return it.
+ //
+ VariablePtrTrack.StartPtr = Variable.StartPtr;
+ VariablePtrTrack.EndPtr = Variable.EndPtr;
+ Status = FindVariableEx (
+ GetVariableNamePtr (Variable.CurrPtr),
+ &Variable.CurrPtr->VendorGuid,
+ FALSE,
+ &VariablePtrTrack
+ );
+ if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) {
+ Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);
+ continue;
+ }
+ }
//
// Don't return NV variable when HOB overrides it
@@ -2629,6 +2946,7 @@ ReclaimForOS(
&mVariableModuleGlobal->NonVolatileLastVariableOffset,
FALSE,
NULL,
+ FALSE,
FALSE
);
ASSERT_EFI_ERROR (Status);
@@ -2760,6 +3078,7 @@ VariableWriteServiceInitialize (
&mVariableModuleGlobal->NonVolatileLastVariableOffset,
FALSE,
NULL,
+ FALSE,
TRUE
);
if (EFI_ERROR (Status)) {
diff --git a/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.h b/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.h
index 6a51bcce2..8e292f36b 100644
--- a/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.h
+++ b/SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.h
@@ -2,7 +2,7 @@
The internal header file includes the common header files, defines
internal structure and functions used by Variable modules.
-Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -65,6 +65,13 @@ typedef enum {
typedef struct {
VARIABLE_HEADER *CurrPtr;
+ //
+ // If both ADDED and IN_DELETED_TRANSITION variable are present,
+ // InDeletedTransitionPtr will point to the IN_DELETED_TRANSITION one.
+ // Otherwise, CurrPtr will point to the ADDED or IN_DELETED_TRANSITION one,
+ // and InDeletedTransitionPtr will be NULL at the same time.
+ //
+ VARIABLE_HEADER *InDeletedTransitionPtr;
VARIABLE_HEADER *EndPtr;
VARIABLE_HEADER *StartPtr;
BOOLEAN Volatile;
@@ -209,7 +216,7 @@ DataSizeOfVariable (
@param[in] Attributes Attributes of the variable.
@param[in] KeyIndex Index of associated public key.
@param[in] MonotonicCount Value of associated monotonic count.
- @param[in] Variable The variable information that is used to keep track of variable usage.
+ @param[in, out] Variable The variable information that is used to keep track of variable usage.
@param[in] TimeStamp Value of associated TimeStamp.
@@ -226,7 +233,7 @@ UpdateVariable (
IN UINT32 Attributes OPTIONAL,
IN UINT32 KeyIndex OPTIONAL,
IN UINT64 MonotonicCount OPTIONAL,
- IN VARIABLE_POINTER_TRACK *Variable,
+ IN OUT VARIABLE_POINTER_TRACK *Variable,
IN EFI_TIME *TimeStamp OPTIONAL
);
@@ -367,6 +374,37 @@ VariableCommonInitialize (
);
/**
+
+ Variable store garbage collection and reclaim operation.
+
+ If ReclaimPubKeyStore is FALSE, reclaim variable space by deleting the obsoleted varaibles.
+ If ReclaimPubKeyStore is TRUE, reclaim invalid key in public key database and update the PubKeyIndex
+ for all the count-based authenticate variable in NV storage.
+
+ @param[in] VariableBase Base address of variable store.
+ @param[out] LastVariableOffset Offset of last variable.
+ @param[in] IsVolatile The variable store is volatile or not;
+ if it is non-volatile, need FTW.
+ @param[in, out] UpdatingPtrTrack Pointer to updating variable pointer track structure.
+ @param[in] ReclaimPubKeyStore Reclaim for public key database or not.
+ @param[in] ReclaimAnyway If TRUE, do reclaim anyway.
+
+ @return EFI_OUT_OF_RESOURCES No enough memory resources.
+ @return EFI_SUCCESS Reclaim operation has finished successfully.
+ @return Others Unexpect error happened during reclaim operation.
+
+**/
+EFI_STATUS
+Reclaim (
+ IN EFI_PHYSICAL_ADDRESS VariableBase,
+ OUT UINTN *LastVariableOffset,
+ IN BOOLEAN IsVolatile,
+ IN OUT VARIABLE_POINTER_TRACK *UpdatingPtrTrack,
+ IN BOOLEAN ReclaimPubKeyStore,
+ IN BOOLEAN ReclaimAnyway
+ );
+
+/**
This function reclaims variable storage if free size is below the threshold.
**/
diff --git a/SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableSmmRuntimeDxe.c b/SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableSmmRuntimeDxe.c
index 2ef44e3a1..a785476ff 100644
--- a/SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableSmmRuntimeDxe.c
+++ b/SecurityPkg/VariableAuthenticated/RuntimeDxe/VariableSmmRuntimeDxe.c
@@ -13,7 +13,7 @@
InitCommunicateBuffer() is really function to check the variable data size.
-Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -52,7 +52,51 @@ EFI_SMM_COMMUNICATION_PROTOCOL *mSmmCommunication = NULL;
UINT8 *mVariableBuffer = NULL;
UINT8 *mVariableBufferPhysical = NULL;
UINTN mVariableBufferSize;
+EFI_LOCK mVariableServicesLock;
+/**
+ Acquires lock only at boot time. Simply returns at runtime.
+
+ This is a temperary function that will be removed when
+ EfiAcquireLock() in UefiLib can handle the call in UEFI
+ Runtimer driver in RT phase.
+ It calls EfiAcquireLock() at boot time, and simply returns
+ at runtime.
+
+ @param Lock A pointer to the lock to acquire.
+
+**/
+VOID
+AcquireLockOnlyAtBootTime (
+ IN EFI_LOCK *Lock
+ )
+{
+ if (!EfiAtRuntime ()) {
+ EfiAcquireLock (Lock);
+ }
+}
+
+/**
+ Releases lock only at boot time. Simply returns at runtime.
+
+ This is a temperary function which will be removed when
+ EfiReleaseLock() in UefiLib can handle the call in UEFI
+ Runtimer driver in RT phase.
+ It calls EfiReleaseLock() at boot time and simply returns
+ at runtime.
+
+ @param Lock A pointer to the lock to release.
+
+**/
+VOID
+ReleaseLockOnlyAtBootTime (
+ IN EFI_LOCK *Lock
+ )
+{
+ if (!EfiAtRuntime ()) {
+ EfiReleaseLock (Lock);
+ }
+}
/**
Initialize the communicate buffer using DataSize and Function.
@@ -169,15 +213,17 @@ RuntimeServiceGetVariable (
if ((*DataSize != 0) && (Data == NULL)) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
- // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize + DataSize.
+ // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
//
PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + StrSize (VariableName) + *DataSize;
Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmVariableHeader != NULL);
@@ -205,11 +251,13 @@ RuntimeServiceGetVariable (
}
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
CopyMem (Data, (UINT8 *)SmmVariableHeader->Name + SmmVariableHeader->NameSize, SmmVariableHeader->DataSize);
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
return Status;
}
@@ -242,7 +290,9 @@ RuntimeServiceGetNextVariableName (
if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
// SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
@@ -250,7 +300,7 @@ RuntimeServiceGetNextVariableName (
PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME, Name) + *VariableNameSize;
Status = InitCommunicateBuffer ((VOID **)&SmmGetNextVariableName, PayloadSize, SMM_VARIABLE_FUNCTION_GET_NEXT_VARIABLE_NAME);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmGetNextVariableName != NULL);
@@ -268,12 +318,14 @@ RuntimeServiceGetNextVariableName (
//
*VariableNameSize = SmmGetNextVariableName->NameSize;
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
CopyGuid (VendorGuid, &SmmGetNextVariableName->Guid);
CopyMem (VariableName, SmmGetNextVariableName->Name, SmmGetNextVariableName->NameSize);
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
return Status;
}
@@ -321,7 +373,9 @@ RuntimeServiceSetVariable (
if (DataSize != 0 && Data == NULL) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
// SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize.
@@ -329,7 +383,7 @@ RuntimeServiceSetVariable (
PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + StrSize (VariableName) + DataSize;
Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_SET_VARIABLE);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmVariableHeader != NULL);
@@ -344,7 +398,9 @@ RuntimeServiceSetVariable (
// Send data to SMM.
//
Status = SendCommunicateBuffer (PayloadSize);
-
+
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
return Status;
}
@@ -382,7 +438,9 @@ RuntimeServiceQueryVariableInfo (
if(MaximumVariableStorageSize == NULL || RemainingVariableStorageSize == NULL || MaximumVariableSize == NULL || Attributes == 0) {
return EFI_INVALID_PARAMETER;
}
-
+
+ AcquireLockOnlyAtBootTime(&mVariableServicesLock);
+
//
// Init the communicate buffer. The buffer data size is:
// SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize;
@@ -390,7 +448,7 @@ RuntimeServiceQueryVariableInfo (
PayloadSize = sizeof (SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO);
Status = InitCommunicateBuffer ((VOID **)&SmmQueryVariableInfo, PayloadSize, SMM_VARIABLE_FUNCTION_QUERY_VARIABLE_INFO);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
ASSERT (SmmQueryVariableInfo != NULL);
@@ -401,7 +459,7 @@ RuntimeServiceQueryVariableInfo (
//
Status = SendCommunicateBuffer (PayloadSize);
if (EFI_ERROR (Status)) {
- return Status;
+ goto Done;
}
//
@@ -410,8 +468,10 @@ RuntimeServiceQueryVariableInfo (
*MaximumVariableSize = SmmQueryVariableInfo->MaximumVariableSize;
*MaximumVariableStorageSize = SmmQueryVariableInfo->MaximumVariableStorageSize;
*RemainingVariableStorageSize = SmmQueryVariableInfo->RemainingVariableStorageSize;
-
- return EFI_SUCCESS;
+
+Done:
+ ReleaseLockOnlyAtBootTime (&mVariableServicesLock);
+ return Status;
}
@@ -608,7 +668,9 @@ VariableSmmRuntimeInitialize (
VOID *SmmVariableWriteRegistration;
EFI_EVENT OnReadyToBootEvent;
EFI_EVENT ExitBootServiceEvent;
-
+
+ EfiInitializeLock (&mVariableServicesLock, TPL_NOTIFY);
+
//
// Smm variable service is ready
//
diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfig.vfr b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfig.vfr
index df7ff37a8..ae4b71bff 100644
--- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfig.vfr
+++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfig.vfr
@@ -1,7 +1,7 @@
/** @file
VFR file used by the SecureBoot configuration component.
-Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -32,7 +32,12 @@ formset
title = STRING_TOKEN(STR_SECUREBOOT_TITLE);
subtitle text = STRING_TOKEN(STR_NULL);
-
+
+ text
+ help = STRING_TOKEN(STR_SECURE_BOOT_STATE_HELP),
+ text = STRING_TOKEN(STR_SECURE_BOOT_STATE_PROMPT),
+ text = STRING_TOKEN(STR_SECURE_BOOT_STATE_CONTENT);
+
//
// Define of Check Box: Attempt Secure Boot
//
@@ -47,7 +52,7 @@ formset
// Display of Check Box: Attempt Secure Boot
//
grayoutif ideqval SECUREBOOT_CONFIGURATION.HideSecureBoot == 1;
- checkbox varid = SECUREBOOT_CONFIGURATION.SecureBootState,
+ checkbox varid = SECUREBOOT_CONFIGURATION.AttemptSecureBoot,
questionid = KEY_SECURE_BOOT_ENABLE,
prompt = STRING_TOKEN(STR_SECURE_BOOT_PROMPT),
help = STRING_TOKEN(STR_SECURE_BOOT_HELP),
diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
index c56a31176..51da86b6f 100644
--- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
+++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
@@ -1,7 +1,7 @@
/** @file
HII Config Access protocol implementation of SecureBoot configuration module.
-Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -253,6 +253,7 @@ DeleteVariable (
if (Variable == NULL) {
return EFI_SUCCESS;
}
+ FreePool (Variable);
Data = NULL;
DataSize = 0;
@@ -279,6 +280,31 @@ DeleteVariable (
}
/**
+
+ Set the platform secure boot mode into "Custom" or "Standard" mode.
+
+ @param[in] SecureBootMode New secure boot mode: STANDARD_SECURE_BOOT_MODE or
+ CUSTOM_SECURE_BOOT_MODE.
+
+ @return EFI_SUCCESS The platform has switched to the special mode successfully.
+ @return other Fail to operate the secure boot mode.
+
+**/
+EFI_STATUS
+SetSecureBootMode (
+ IN UINT8 SecureBootMode
+ )
+{
+ return gRT->SetVariable (
+ EFI_CUSTOM_MODE_NAME,
+ &gEfiCustomModeEnableGuid,
+ EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
+ sizeof (UINT8),
+ &SecureBootMode
+ );
+}
+
+/**
Generate the PK signature list from the X509 Certificate storing file (.cer)
@param[in] X509File FileHandle of X509 Certificate storing file.
@@ -380,6 +406,11 @@ EnrollPlatformKey (
PkCert = NULL;
+ Status = SetSecureBootMode(CUSTOM_SECURE_BOOT_MODE);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
//
// Parse the file's postfix. Only support DER encoded X.509 certificate files.
//
@@ -457,6 +488,11 @@ DeletePlatformKey (
{
EFI_STATUS Status;
+ Status = SetSecureBootMode(CUSTOM_SECURE_BOOT_MODE);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
Status = DeleteVariable (
EFI_PLATFORM_KEY_NAME,
&gEfiGlobalVariableGuid
@@ -766,11 +802,17 @@ EnrollKeyExchangeKey (
)
{
UINT16* FilePostFix;
+ EFI_STATUS Status;
if ((Private->FileContext->FileName == NULL) || (Private->SignatureGUID == NULL)) {
return EFI_INVALID_PARAMETER;
}
+ Status = SetSecureBootMode(CUSTOM_SECURE_BOOT_MODE);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
//
// Parse the file's postfix. Supports DER-encoded X509 certificate,
// and .pbk as RSA public key file.
@@ -1508,11 +1550,17 @@ EnrollSignatureDatabase (
)
{
UINT16* FilePostFix;
+ EFI_STATUS Status;
if ((Private->FileContext->FileName == NULL) || (Private->FileContext->FHandle == NULL) || (Private->SignatureGUID == NULL)) {
return EFI_INVALID_PARAMETER;
}
+ Status = SetSecureBootMode(CUSTOM_SECURE_BOOT_MODE);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
//
// Parse the file's postfix.
//
@@ -1659,6 +1707,8 @@ UpdateDeletePage (
//
// The signature type is not supported in current implementation.
//
+ ItemDataSize -= CertList->SignatureListSize;
+ CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
continue;
}
@@ -1756,6 +1806,11 @@ DeleteKeyExchangeKey (
Cert = NULL;
Attr = 0;
DeleteKekIndex = QuestionId - OPTION_DEL_KEK_QUESTION_ID;
+
+ Status = SetSecureBootMode(CUSTOM_SECURE_BOOT_MODE);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
//
// Get original KEK variable.
@@ -1944,6 +1999,11 @@ DeleteSignature (
Cert = NULL;
Attr = 0;
+ Status = SetSecureBootMode(CUSTOM_SECURE_BOOT_MODE);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
//
// Get original signature list data.
//
@@ -2103,23 +2163,25 @@ SecureBootExtractConfigFromVariable (
{
UINT8 *SecureBootEnable;
UINT8 *SetupMode;
- UINT8 *SecureBoot;
UINT8 *SecureBootMode;
SecureBootEnable = NULL;
SetupMode = NULL;
- SecureBoot = NULL;
SecureBootMode = NULL;
//
// If the SecureBootEnable Variable doesn't exist, hide the SecureBoot Enable/Disable
// Checkbox.
//
+ ConfigData->AttemptSecureBoot = FALSE;
GetVariable2 (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid, (VOID**)&SecureBootEnable, NULL);
if (SecureBootEnable == NULL) {
ConfigData->HideSecureBoot = TRUE;
} else {
ConfigData->HideSecureBoot = FALSE;
+ if ((*SecureBootEnable) == SECURE_BOOT_ENABLE) {
+ ConfigData->AttemptSecureBoot = TRUE;
+ }
}
//
@@ -2140,16 +2202,6 @@ SecureBootExtractConfigFromVariable (
} else {
ConfigData->HasPk = TRUE;
}
-
- //
- // If the value of SecureBoot variable is 1, the platform is operating in secure boot mode.
- //
- GetVariable2 (EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, (VOID**)&SecureBoot, NULL);
- if (SecureBoot != NULL && *SecureBoot == SECURE_BOOT_MODE_ENABLE) {
- ConfigData->SecureBootState = TRUE;
- } else {
- ConfigData->SecureBootState = FALSE;
- }
//
// Get the SecureBootMode from CustomMode variable.
@@ -2160,7 +2212,16 @@ SecureBootExtractConfigFromVariable (
} else {
ConfigData->SecureBootMode = *(SecureBootMode);
}
-
+
+ if (SecureBootEnable != NULL) {
+ FreePool (SecureBootEnable);
+ }
+ if (SetupMode != NULL) {
+ FreePool (SetupMode);
+ }
+ if (SecureBootMode != NULL) {
+ FreePool (SecureBootMode);
+ }
}
/**
@@ -2206,6 +2267,7 @@ SecureBootExtractConfig (
EFI_STRING ConfigRequestHdr;
SECUREBOOT_CONFIG_PRIVATE_DATA *PrivateData;
BOOLEAN AllocatedRequest;
+ UINT8 *SecureBoot;
if (Progress == NULL || Results == NULL) {
return EFI_INVALID_PARAMETER;
@@ -2215,6 +2277,7 @@ SecureBootExtractConfig (
ConfigRequestHdr = NULL;
ConfigRequest = NULL;
Size = 0;
+ SecureBoot = NULL;
ZeroMem (&Configuration, sizeof (Configuration));
PrivateData = SECUREBOOT_CONFIG_PRIVATE_FROM_THIS (This);
@@ -2228,6 +2291,19 @@ SecureBootExtractConfig (
// Get Configuration from Variable.
//
SecureBootExtractConfigFromVariable (&Configuration);
+
+ //
+ // Update current secure boot state.
+ //
+ GetVariable2 (EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, (VOID**)&SecureBoot, NULL);
+ if (SecureBoot != NULL && *SecureBoot == SECURE_BOOT_MODE_ENABLE) {
+ HiiSetString (PrivateData->HiiHandle, STRING_TOKEN (STR_SECURE_BOOT_STATE_CONTENT), L"Enabled", NULL);
+ } else {
+ HiiSetString (PrivateData->HiiHandle, STRING_TOKEN (STR_SECURE_BOOT_STATE_CONTENT), L"Disabled", NULL);
+ }
+ if (SecureBoot != NULL) {
+ FreePool (SecureBoot);
+ }
BufferSize = sizeof (SECUREBOOT_CONFIGURATION);
ConfigRequest = Request;
@@ -2355,15 +2431,21 @@ SecureBootCallback (
SECUREBOOT_CONFIGURATION *IfrNvData;
UINT16 LabelId;
UINT8 *SecureBootEnable;
+ UINT8 *SecureBootMode;
+ UINT8 *SetupMode;
CHAR16 PromptString[100];
SecureBootEnable = NULL;
+ SecureBootMode = NULL;
+ SetupMode = NULL;
if ((This == NULL) || (Value == NULL) || (ActionRequest == NULL)) {
return EFI_INVALID_PARAMETER;
}
- if ((Action != EFI_BROWSER_ACTION_CHANGED) && (Action != EFI_BROWSER_ACTION_CHANGING)) {
+ if ((Action != EFI_BROWSER_ACTION_CHANGED) &&
+ (Action != EFI_BROWSER_ACTION_CHANGING) &&
+ (Action != EFI_BROWSER_ACTION_FORM_CLOSE)) {
return EFI_UNSUPPORTED;
}
@@ -2388,6 +2470,7 @@ SecureBootCallback (
case KEY_SECURE_BOOT_ENABLE:
GetVariable2 (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid, (VOID**)&SecureBootEnable, NULL);
if (NULL != SecureBootEnable) {
+ FreePool (SecureBootEnable);
if (EFI_ERROR (SaveSecureBootVariable (Value->u8))) {
CreatePopUp (
EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE,
@@ -2400,11 +2483,10 @@ SecureBootCallback (
CreatePopUp (
EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE,
&Key,
- L"Secure boot configuration is changed, please reset the platform to take effect!",
+ L"Configuration changed, please reset the platform to take effect!",
NULL
);
}
- *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
}
break;
@@ -2461,10 +2543,26 @@ SecureBootCallback (
break;
case KEY_SECURE_BOOT_DELETE_PK:
- if (Value->u8) {
+ if (Value->u8) {
+ CreatePopUp (
+ EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE,
+ &Key,
+ L"Are you sure you want to delete PK? Secure boot will be disabled!",
+ L"Press 'Y' to delete PK and exit, 'N' to discard change and return",
+ NULL
+ );
+ if (Key.UnicodeChar == 'y' || Key.UnicodeChar == 'Y') {
Status = DeletePlatformKey ();
- *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
+ if (EFI_ERROR (Status)) {
+ CreatePopUp (
+ EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE,
+ &Key,
+ L"Only Physical Presence User could delete PK in custom mode!",
+ NULL
+ );
+ }
}
+ }
break;
case KEY_DELETE_KEK:
@@ -2547,7 +2645,7 @@ SecureBootCallback (
} else if (Action == EFI_BROWSER_ACTION_CHANGED) {
switch (QuestionId) {
case KEY_SECURE_BOOT_ENABLE:
- *ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
break;
case KEY_VALUE_SAVE_AND_EXIT_PK:
Status = EnrollPlatformKey (Private);
@@ -2588,8 +2686,8 @@ SecureBootCallback (
break;
case KEY_SECURE_BOOT_MODE:
- GetVariable2 (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, (VOID**)&SecureBootEnable, NULL);
- if (NULL != SecureBootEnable) {
+ GetVariable2 (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, (VOID**)&SecureBootMode, NULL);
+ if (NULL != SecureBootMode) {
Status = gRT->SetVariable (
EFI_CUSTOM_MODE_NAME,
&gEfiCustomModeEnableGuid,
@@ -2599,6 +2697,7 @@ SecureBootCallback (
);
*ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
IfrNvData->SecureBootMode = Value->u8;
+ FreePool (SecureBootMode);
}
break;
@@ -2619,11 +2718,33 @@ SecureBootCallback (
break;
case KEY_SECURE_BOOT_DELETE_PK:
- if (Value->u8) {
+ GetVariable2 (EFI_SETUP_MODE_NAME, &gEfiGlobalVariableGuid, (VOID**)&SetupMode, NULL);
+ if (SetupMode == NULL || (*SetupMode) == SETUP_MODE) {
+ IfrNvData->DeletePk = TRUE;
+ IfrNvData->HasPk = FALSE;
*ActionRequest = EFI_BROWSER_ACTION_REQUEST_SUBMIT;
+ } else {
+ IfrNvData->DeletePk = FALSE;
+ IfrNvData->HasPk = TRUE;
+ *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_APPLY;
+ }
+ if (SetupMode != NULL) {
+ FreePool (SetupMode);
}
break;
}
+ } else if (Action == EFI_BROWSER_ACTION_FORM_CLOSE) {
+ //
+ // Force the platform back to Standard Mode once user leave the setup screen.
+ //
+ GetVariable2 (EFI_CUSTOM_MODE_NAME, &gEfiCustomModeEnableGuid, (VOID**)&SecureBootMode, NULL);
+ if (NULL != SecureBootMode && *SecureBootMode == CUSTOM_SECURE_BOOT_MODE) {
+ IfrNvData->SecureBootMode = STANDARD_SECURE_BOOT_MODE;
+ SetSecureBootMode(STANDARD_SECURE_BOOT_MODE);
+ }
+ if (SecureBootMode != NULL) {
+ FreePool (SecureBootMode);
+ }
}
if (!EFI_ERROR (Status)) {
diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigNvData.h b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigNvData.h
index 6015dd636..ea4319290 100644
--- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigNvData.h
+++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigNvData.h
@@ -1,7 +1,7 @@
/** @file
Header file for NV data structure definition.
-Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -106,7 +106,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
// Nv Data structure referenced by IFR
//
typedef struct {
- BOOLEAN SecureBootState; //Secure Boot Disable/Enable;
+ BOOLEAN AttemptSecureBoot; //Attempt to enable/disable Secure Boot.
BOOLEAN HideSecureBoot; //Hiden Attempt Secure Boot
CHAR16 SignatureGuid[SECURE_BOOT_GUID_STORAGE_SIZE];
BOOLEAN PhysicalPresent; //If a Physical Present User;
diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigStrings.uni b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigStrings.uni
index ed4db131e..8a4cb36f7 100644
--- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigStrings.uni
+++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigStrings.uni
Binary files differ
diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c b/ShellPkg/Application/Shell/ShellParametersProtocol.c
index a01a5c6a7..067f6b7cf 100644
--- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
+++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
@@ -290,10 +290,10 @@ CreatePopulateInstallShellParametersProtocol (
//
// Build the full command line
//
- Status = SHELL_GET_ENVIRONMENT_VARIABLE(L"ShellOpt", &Size, &FullCommandLine);
+ Status = SHELL_GET_ENVIRONMENT_VARIABLE(L"ShellOpt", &Size, FullCommandLine);
if (Status == EFI_BUFFER_TOO_SMALL) {
FullCommandLine = AllocateZeroPool(Size + LoadedImage->LoadOptionsSize);
- Status = SHELL_GET_ENVIRONMENT_VARIABLE(L"ShellOpt", &Size, &FullCommandLine);
+ Status = SHELL_GET_ENVIRONMENT_VARIABLE(L"ShellOpt", &Size, FullCommandLine);
}
if (Status == EFI_NOT_FOUND) {
//
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c
index 3583dd3df..a1564d4f5 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/MainTextEditor.c
@@ -1502,7 +1502,7 @@ MainEditorInit (
//
// below will call the five components' init function
//
- Status = MainTitleBarInit (L"UEFI EDIT 2.0");
+ Status = MainTitleBarInit (L"UEFI EDIT");
if (EFI_ERROR (Status)) {
ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN(STR_EDIT_LIBEDITOR_TITLEBAR), gShellDebug1HiiHandle);
return EFI_LOAD_ERROR;
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c
index 446dac7e0..09213d897 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/MainHexEditor.c
@@ -1687,7 +1687,7 @@ HMainEditorInit (
//
// below will call the five components' init function
//
- Status = MainTitleBarInit (NULL);
+ Status = MainTitleBarInit (L"UEFI HEXEDIT");
if (EFI_ERROR (Status)) {
ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_HEXEDIT_LIBEDITOR_MAINEDITOR_TITLE), gShellDebug1HiiHandle);
return EFI_LOAD_ERROR;
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
index 3aea96b6e..9ae5a0c74 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
@@ -249,7 +249,7 @@ SmbiosPrintStructure (
PRINT_PENDING_STRING (Struct, Type0, BiosReleaseDate);
ShellPrintHiiEx(-1,-1,NULL,STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_BIOS_SIZE), gShellDebug1HiiHandle, 64 * (Struct->Type0->BiosSize + 1));
- DisplayBiosCharacteristics (*(UINT64 *) &(Struct->Type0->BiosCharacteristics), Option);
+ DisplayBiosCharacteristics (ReadUnaligned64 ((UINT64 *) (UINTN) &(Struct->Type0->BiosCharacteristics)), Option);
if (Struct->Hdr->Length > 0x12) {
DisplayBiosCharacteristicsExt1 (Struct->Type0->BIOSCharacteristicsExtensionBytes[0], Option);
@@ -416,7 +416,7 @@ SmbiosPrintStructure (
PRINT_STRUCT_VALUE_H (Struct, Type7, InstalledSize);
PRINT_STRUCT_VALUE_H (Struct, Type7, SupportedSRAMType);
PRINT_STRUCT_VALUE_H (Struct, Type7, CurrentSRAMType);
- DisplayCacheSRAMType (*(UINT16 *) &(Struct->Type7->CurrentSRAMType), Option);
+ DisplayCacheSRAMType (ReadUnaligned16 ((UINT16 *) (UINTN) &(Struct->Type7->CurrentSRAMType)), Option);
PRINT_STRUCT_VALUE_H (Struct, Type7, CacheSpeed);
DisplayCacheErrCorrectingType (Struct->Type7->ErrorCorrectionType, Option);
DisplayCacheSystemCacheType (Struct->Type7->SystemCacheType, Option);
@@ -633,7 +633,7 @@ SmbiosPrintStructure (
PRINT_PENDING_STRING (Struct, Type17, DeviceLocator);
PRINT_PENDING_STRING (Struct, Type17, BankLocator);
DisplayMemoryDeviceType (Struct->Type17->MemoryType, Option);
- DisplayMemoryDeviceTypeDetail (*(UINT16 *) &(Struct->Type17->TypeDetail), Option);
+ DisplayMemoryDeviceTypeDetail (ReadUnaligned16 ((UINT16 *) (UINTN) &(Struct->Type17->TypeDetail)), Option);
PRINT_STRUCT_VALUE_H (Struct, Type17, Speed);
PRINT_PENDING_STRING (Struct, Type17, Manufacturer);
PRINT_PENDING_STRING (Struct, Type17, SerialNumber);
diff --git a/ShellPkg/Library/UefiShellLib/UefiShellLib.c b/ShellPkg/Library/UefiShellLib/UefiShellLib.c
index 222bd98ac..103ddfbd5 100644
--- a/ShellPkg/Library/UefiShellLib/UefiShellLib.c
+++ b/ShellPkg/Library/UefiShellLib/UefiShellLib.c
@@ -486,6 +486,8 @@ ShellOpenFileByDevicePath(
EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *EfiSimpleFileSystemProtocol;
EFI_FILE_PROTOCOL *Handle1;
EFI_FILE_PROTOCOL *Handle2;
+ CHAR16 *FnafPathName;
+ UINTN PathLen;
if (FilePath == NULL || FileHandle == NULL || DeviceHandle == NULL) {
return (EFI_INVALID_PARAMETER);
@@ -552,12 +554,35 @@ ShellOpenFileByDevicePath(
Handle1 = NULL;
//
+ // File Name Alignment Fix (FNAF)
+ // Handle2->Open may be incapable of handling a unaligned CHAR16 data.
+ // The structure pointed to by FilePath may be not CHAR16 aligned.
+ // This code copies the potentially unaligned PathName data from the
+ // FilePath structure to the aligned FnafPathName for use in the
+ // calls to Handl2->Open.
+ //
+
+ //
+ // Determine length of PathName, in bytes.
+ //
+ PathLen = DevicePathNodeLength (*FilePath) - SIZE_OF_FILEPATH_DEVICE_PATH;
+
+ //
+ // Allocate memory for the aligned copy of the string Extra allocation is to allow for forced alignment
+ // Copy bytes from possibly unaligned location to aligned location
+ //
+ FnafPathName = AllocateCopyPool(PathLen, (UINT8 *)((FILEPATH_DEVICE_PATH*)*FilePath)->PathName);
+ if (FnafPathName == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
// Try to test opening an existing file
//
Status = Handle2->Open (
Handle2,
&Handle1,
- ((FILEPATH_DEVICE_PATH*)*FilePath)->PathName,
+ FnafPathName,
OpenMode &~EFI_FILE_MODE_CREATE,
0
);
@@ -569,11 +594,17 @@ ShellOpenFileByDevicePath(
Status = Handle2->Open (
Handle2,
&Handle1,
- ((FILEPATH_DEVICE_PATH*)*FilePath)->PathName,
+ FnafPathName,
OpenMode,
Attributes
);
}
+
+ //
+ // Free the alignment buffer
+ //
+ FreePool(FnafPathName);
+
//
// Close the last node
//
diff --git a/SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.c b/SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.c
new file mode 100644
index 000000000..99bb2fded
--- /dev/null
+++ b/SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.c
@@ -0,0 +1,101 @@
+/** @file
+ Initialize Debug Agent in DXE by invoking Debug Agent Library.
+
+Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PiDxe.h>
+#include <Guid/EventGroup.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/DebugAgentLib.h>
+
+EFI_EVENT mExitBootServiceEvent;
+
+/**
+ One notified function to disable Debug Timer interrupt when gBS->ExitBootServices() called.
+
+ @param[in] Event Pointer to this event
+ @param[in] Context Event hanlder private data
+
+**/
+VOID
+EFIAPI
+DisableDebugTimerExitBootService (
+ EFI_EVENT Event,
+ VOID *Context
+ )
+
+{
+ SaveAndSetDebugTimerInterrupt (FALSE);
+}
+
+/**
+ The Entry Point for Debug Agent Dxe driver.
+
+ It will invoke Debug Agent Library to enable source debugging feature in DXE phase.
+
+ @param[in] ImageHandle The firmware allocated handle for the EFI image.
+ @param[in] SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+ @retval other Some error occurs when initialzed Debug Agent.
+
+**/
+EFI_STATUS
+EFIAPI
+DebugAgentDxeInitialize(
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+
+ InitializeDebugAgent (DEBUG_AGENT_INIT_DXE_LOAD, &Status, NULL);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ //
+ // Create event to disable Debug Timer interrupt when exit boot service.
+ //
+ Status = gBS->CreateEventEx (
+ EVT_NOTIFY_SIGNAL,
+ TPL_NOTIFY,
+ DisableDebugTimerExitBootService,
+ NULL,
+ &gEfiEventExitBootServicesGuid,
+ &mExitBootServiceEvent
+ );
+ return Status;
+}
+
+/**
+ This is the unload handle for Debug Agent Dxe driver.
+
+ It will invoke Debug Agent Library to disable source debugging feature.
+
+ @param[in] ImageHandle The drivers' driver image.
+
+ @retval EFI_SUCCESS The image is unloaded.
+ @retval Others Failed to unload the image.
+
+**/
+EFI_STATUS
+EFIAPI
+DebugAgentDxeUnload (
+ IN EFI_HANDLE ImageHandle
+ )
+{
+ EFI_STATUS Status;
+
+ InitializeDebugAgent (DEBUG_AGENT_INIT_DXE_UNLOAD, &Status, NULL);
+
+ return Status;
+}
diff --git a/SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.inf b/SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.inf
new file mode 100644
index 000000000..114b708a8
--- /dev/null
+++ b/SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.inf
@@ -0,0 +1,48 @@
+## @file
+# Initialized Debug Agent in one separated DXE driver.
+#
+# This DXE driver will invoke Debug Agent Library to initialize the debug agent.
+#
+# Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DebugAgentDxe
+ FILE_GUID = 9727502C-034E-472b-8E1B-67BB28C6CFDB
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = DebugAgentDxeInitialize
+ UNLOAD_IMAGE = DebugAgentDxeUnload
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources]
+ DebugAgentDxe.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+
+[LibraryClasses]
+ UefiDriverEntryPoint
+ UefiBootServicesTableLib
+ DebugAgentLib
+
+[Guids]
+ gEfiEventExitBootServicesGuid ## SOMETIMES_CONSUMES ## Event
+
+[Depex]
+ TRUE
diff --git a/SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.c b/SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.c
new file mode 100644
index 000000000..df0ac87b4
--- /dev/null
+++ b/SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.c
@@ -0,0 +1,45 @@
+/** @file
+ Initialize Debug Agent in PEI by invoking Debug Agent Library.
+
+Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+This program and the accompanying materials
+are licensed and made available under the terms and conditions of the BSD License
+which accompanies this distribution. The full text of the license may be found at
+http://opensource.org/licenses/bsd-license.php
+
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PiPei.h>
+
+#include <Library/DebugAgentLib.h>
+
+/**
+ The Entry Point for Debug Agent PEI driver.
+
+ It will invoke Debug Agent Library to enable source debugging feature in PEI phase.
+
+ This function is the Entry point of the CPU I/O PEIM which installs CpuIoPpi.
+
+ @param[in] FileHandle Pointer to image file handle.
+ @param[in] PeiServices Pointer to PEI Services Table
+
+ @retval EFI_SUCCESS Debug Agent successfully initialized.
+ @retval other Some error occurs when initialzed Debug Agent.
+
+**/
+EFI_STATUS
+EFIAPI
+DebugAgentPeiInitialize (
+ IN EFI_PEI_FILE_HANDLE FileHandle,
+ IN CONST EFI_PEI_SERVICES **PeiServices
+ )
+{
+ EFI_STATUS Status;
+
+ InitializeDebugAgent (DEBUG_AGENT_INIT_PEI, &Status, NULL);
+
+ return Status;
+}
diff --git a/SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.inf b/SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.inf
new file mode 100644
index 000000000..d20a01206
--- /dev/null
+++ b/SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.inf
@@ -0,0 +1,44 @@
+## @file
+# Initialized Debug Agent in PEI phase.
+#
+# This PEIM will invoke Debug Agent Library to initialize the debug agent in
+# whole PEI phase.
+#
+# Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = DebugAgentPei
+ FILE_GUID = D9D114EF-F40B-4d48-AAA0-A3DC99C9F5BD
+ MODULE_TYPE = PEIM
+ VERSION_STRING = 1.0
+ ENTRY_POINT = DebugAgentPeiInitialize
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources]
+ DebugAgentPei.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+
+[LibraryClasses]
+ PeimEntryPoint
+ DebugAgentLib
+
+[Depex]
+ TRUE
diff --git a/SourceLevelDebugPkg/Include/ImageDebugSupport.h b/SourceLevelDebugPkg/Include/ImageDebugSupport.h
index 68299857a..511a12ce2 100644
--- a/SourceLevelDebugPkg/Include/ImageDebugSupport.h
+++ b/SourceLevelDebugPkg/Include/ImageDebugSupport.h
@@ -2,7 +2,7 @@
Public include file for Debug Agent Library instance and PE/COFF Extra
Action Library instance.
- Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -19,6 +19,7 @@
#define IO_PORT_BREAKPOINT_ADDRESS 0x84
#define IMAGE_LOAD_SIGNATURE SIGNATURE_32('L','O','A','D')
#define IMAGE_UNLOAD_SIGNATURE SIGNATURE_32('U','N','L','O')
+#define AGENT_HANDLER_SIGNATURE SIGNATURE_32('A','G','T','H')
#define DEBUG_AGENT_IMAGE_WAIT 0x00
#define DEBUG_AGENT_IMAGE_CONTINUE 0x01
diff --git a/SourceLevelDebugPkg/Include/TransferProtocol.h b/SourceLevelDebugPkg/Include/TransferProtocol.h
index bb7b07b4e..53e9f7cf3 100644
--- a/SourceLevelDebugPkg/Include/TransferProtocol.h
+++ b/SourceLevelDebugPkg/Include/TransferProtocol.h
@@ -2,7 +2,7 @@
Transfer protocol defintions used by debug agent and host. It is only
intended to be used by Debug related module implementation.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -21,25 +21,19 @@
//
// Current revision of transfer protocol
//
-#define DEBUG_AGENT_REVISION ((0 << 16) | 02)
+#define DEBUG_AGENT_REVISION ((0 << 16) | 03)
#define DEBUG_AGENT_CAPABILITIES 0
//
-// Definitions for break command.
-//
-#define DEBUG_STARTING_SYMBOL_BREAK (0xFC)
-
-//
// Definitions for attach command
//
-#define DEBUG_STARTING_SYMBOL_ATTACH (0xFA)
+#define DEBUG_STARTING_SYMBOL_ATTACH (0xFA)
//
// Definition for starting symbol of a normal debug packet. Choose a non-ASCII to avoid conflict with other serial output.
//
#define DEBUG_STARTING_SYMBOL_NORMAL (0xFE)
-
#pragma pack(1)
//
@@ -49,7 +43,8 @@ typedef struct {
UINT8 StartSymbol;
UINT8 Command;
UINT8 Length; // Length of Debug Packet including header and payload in byte
- UINT8 CheckSum;
+ UINT8 SequenceNo;
+ UINT16 Crc;
} DEBUG_PACKET_HEADER;
//
@@ -86,6 +81,7 @@ typedef struct {
#define DEBUG_COMMAND_DETACH (DEBUG_COMMAND_REQUEST | 0x16)
#define DEBUG_COMMAND_CPUID (DEBUG_COMMAND_REQUEST | 0x17)
#define DEBUG_COMMAND_SEARCH_SIGNATURE (DEBUG_COMMAND_REQUEST | 0x18)
+#define DEBUG_COMMAND_HALT (DEBUG_COMMAND_REQUEST | 0x19)
//
// TARGET initiated commands
@@ -94,6 +90,7 @@ typedef struct {
#define DEBUG_COMMAND_BREAK_POINT (DEBUG_COMMAND_REQUEST | 0x3E)
#define DEBUG_COMMAND_MEMORY_READY (DEBUG_COMMAND_REQUEST | 0x3D)
#define DEBUG_COMMAND_PRINT_MESSAGE (DEBUG_COMMAND_REQUEST | 0x3C)
+#define DEBUG_COMMAND_ATTACH_BREAK (DEBUG_COMMAND_REQUEST | 0x3B)
//
// Response commands
@@ -308,8 +305,9 @@ typedef struct {
//
// Supported keys
//
-#define DEBUG_AGENT_SETTING_SMM_ENTRY_BREAK 1
-#define DEBUG_AGENT_SETTING_PRINT_ERROR_LEVEL 2
+#define DEBUG_AGENT_SETTING_SMM_ENTRY_BREAK 1
+#define DEBUG_AGENT_SETTING_PRINT_ERROR_LEVEL 2
+#define DEBUG_AGENT_SETTING_BOOT_SCRIPT_ENTRY_BREAK 3
//
// Bitmask of print error level for debug message
//
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c
index 04dae3419..f4039f499 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c
@@ -4,7 +4,7 @@
read/write debug packet to communication with HOST based on transfer
protocol.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -18,12 +18,305 @@
#include "DebugAgent.h"
#include "Ia32/DebugException.h"
-#define INIT_BREAK_ACK_TIMEOUT (200 * 1000)
+CHAR8 mErrorMsgVersionAlert[] = "\rThe SourceLevelDebugPkg you are using requires a newer version of the Intel(R) UDK Debugger Tool.\r\n";
+CHAR8 mErrorMsgSendInitPacket[] = "\rSend INIT break packet and try to connect the HOST (Intel(R) UDK Debugger Tool v1.3) ...\r\n";
+CHAR8 mErrorMsgConnectOK[] = "HOST connection is successful!\r\n";
+CHAR8 mErrorMsgConnectFail[] = "HOST connection is failed!\r\n";
+CHAR8 mWarningMsgIngoreBreakpoint[] = "Ignore break point in SMM for SMI issued during DXE debugging!\r\n";
-CHAR8 mErrorMsgVersionAlert[] = "\rThe SourceLevelDebugPkg you are using requires a newer version of the Intel(R) UDK Debugger Tool.\r\n";
-CHAR8 mErrorMsgSendInitPacket[] = "\rSend INIT break packet to HOST ...\r\n";
-CHAR8 mErrorMsgConnectOK[] = "HOST connection is successful!\r\n";
-CHAR8 mErrorMsgConnectFail[] = "HOST connection is failed!\r\n";
+/**
+ Calculate CRC16 for target data.
+
+ @param[in] Data The target data.
+ @param[in] DataSize The target data size.
+ @param[in] Crc Initial CRC.
+
+ @return UINT16 The CRC16 value.
+
+**/
+UINT16
+CalculateCrc16 (
+ IN UINT8 *Data,
+ IN UINTN DataSize,
+ IN UINT16 Crc
+ )
+{
+ UINTN Index;
+ UINTN BitIndex;
+
+ for (Index = 0; Index < DataSize; Index++) {
+ Crc ^= Data[Index];
+ for (BitIndex = 0; BitIndex < 8; BitIndex++) {
+ if ((Crc & 0x8000) != 0) {
+ Crc <<= 1;
+ Crc ^= 0x1021;
+ } else {
+ Crc <<= 1;
+ }
+ }
+ }
+ return Crc;
+}
+
+
+/**
+ Read IDT entry to check if IDT entries are setup by Debug Agent.
+
+ @retval TRUE IDT entries were setup by Debug Agent.
+ @retval FALSE IDT entries were not setup by Debug Agent.
+
+**/
+BOOLEAN
+IsDebugAgentInitialzed (
+ VOID
+ )
+{
+ UINTN InterruptHandler;
+
+ InterruptHandler = (UINTN) GetExceptionHandlerInIdtEntry (0);
+ if (InterruptHandler >= 4 && *(UINT32 *)(InterruptHandler - 4) == AGENT_HANDLER_SIGNATURE) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+/**
+ Find and report module image info to HOST.
+
+ @param[in] AlignSize Image aligned size.
+
+**/
+VOID
+FindAndReportModuleImageInfo (
+ IN UINTN AlignSize
+ )
+{
+ UINTN Pe32Data;
+ EFI_IMAGE_DOS_HEADER *DosHdr;
+ EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
+ PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
+
+ //
+ // Find Image Base
+ //
+ Pe32Data = ((UINTN)mErrorMsgVersionAlert) & ~(AlignSize - 1);
+ while (Pe32Data != 0) {
+ DosHdr = (EFI_IMAGE_DOS_HEADER *) Pe32Data;
+ if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
+ //
+ // DOS image header is present, so read the PE header after the DOS image header.
+ // Check if address overflow firstly.
+ //
+ if ((MAX_ADDRESS - (UINTN)DosHdr->e_lfanew) > Pe32Data) {
+ Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)(Pe32Data + (UINTN)(DosHdr->e_lfanew));
+ if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) {
+ //
+ // It's PE image.
+ //
+ break;
+ }
+ }
+ } else {
+ //
+ // DOS image header is not present, TE header is at the image base.
+ //
+ Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data;
+ if ((Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) &&
+ ((Hdr.Te->Machine == IMAGE_FILE_MACHINE_I386) || Hdr.Te->Machine == IMAGE_FILE_MACHINE_X64)) {
+ //
+ // It's TE image, it TE header and Machine type match
+ //
+ break;
+ }
+ }
+
+ //
+ // Not found the image base, check the previous aligned address
+ //
+ Pe32Data -= AlignSize;
+ }
+
+ ImageContext.ImageAddress = Pe32Data;
+ ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageContext.ImageAddress);
+ PeCoffLoaderRelocateImageExtraAction (&ImageContext);
+}
+
+/**
+ Trigger one software interrupt to debug agent to handle it.
+
+ @param[in] Signature Software interrupt signature.
+
+**/
+VOID
+TriggerSoftInterrupt (
+ IN UINT32 Signature
+ )
+{
+ UINTN Dr0;
+ UINTN Dr1;
+
+ //
+ // Save Debug Register State
+ //
+ Dr0 = AsmReadDr0 ();
+ Dr1 = AsmReadDr1 ();
+
+ //
+ // DR0 = Signature
+ //
+ AsmWriteDr0 (SOFT_INTERRUPT_SIGNATURE);
+ AsmWriteDr1 (Signature);
+
+ //
+ // Do INT3 to communicate with HOST side
+ //
+ CpuBreakpoint ();
+
+ //
+ // Restore Debug Register State only when Host didn't change it inside exception handler.
+ // Dr registers can only be changed by setting the HW breakpoint.
+ //
+ AsmWriteDr0 (Dr0);
+ AsmWriteDr1 (Dr1);
+
+}
+
+/**
+ Caculate Mailbox checksum and update the checksum field.
+
+ @param[in] Mailbox Debug Agent Mailbox pointer.
+
+**/
+VOID
+UpdateMailboxChecksum (
+ IN DEBUG_AGENT_MAILBOX *Mailbox
+ )
+{
+ Mailbox->CheckSum = CalculateCheckSum8 ((UINT8 *)Mailbox, sizeof (DEBUG_AGENT_MAILBOX) - 2);
+}
+
+/**
+ Verify Mailbox checksum.
+
+ If checksum error, print debug message and run init dead loop.
+
+ @param[in] Mailbox Debug Agent Mailbox pointer.
+
+**/
+VOID
+VerifyMailboxChecksum (
+ IN DEBUG_AGENT_MAILBOX *Mailbox
+ )
+{
+ UINT8 CheckSum;
+
+ CheckSum = CalculateCheckSum8 ((UINT8 *) Mailbox, sizeof (DEBUG_AGENT_MAILBOX) - 2);
+ //
+ // The checksum updating process may be disturbed by hardware SMI, we need to check CheckSum field
+ // and ToBeCheckSum field to validate the mail box.
+ //
+ if (CheckSum != Mailbox->CheckSum && CheckSum != Mailbox->ToBeCheckSum) {
+ DEBUG ((EFI_D_ERROR, "DebugAgent: Mailbox checksum error, stack or heap crashed!\n"));
+ DEBUG ((EFI_D_ERROR, "DebugAgent: CheckSum = %x, Mailbox->CheckSum = %x, Mailbox->ToBeCheckSum = %x\n", CheckSum, Mailbox->CheckSum, Mailbox->ToBeCheckSum));
+ CpuDeadLoop ();
+ }
+}
+
+/**
+ Update Mailbox content by index.
+
+ @param[in] Mailbox Debug Agent Mailbox pointer.
+ @param[in] Index Mailbox content index.
+ @param[in] Value Value to be set into Mailbox.
+
+**/
+VOID
+UpdateMailboxContent (
+ IN DEBUG_AGENT_MAILBOX *Mailbox,
+ IN UINTN Index,
+ IN UINT64 Value
+ )
+{
+ AcquireMpSpinLock (&mDebugMpContext.MailboxSpinLock);
+ switch (Index) {
+ case DEBUG_MAILBOX_DEBUG_FLAG_INDEX:
+ Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->DebugFlag.Uint64, sizeof(UINT64))
+ - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT64));
+ Mailbox->DebugFlag.Uint64 = Value;
+ break;
+ case DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX:
+ Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->DebugPortHandle, sizeof(UINTN))
+ - CalculateSum8 ((UINT8 *)&Value, sizeof(UINTN));
+ Mailbox->DebugPortHandle = (UINTN) Value;
+ break;
+ case DEBUG_MAILBOX_EXCEPTION_BUFFER_POINTER_INDEX:
+ Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->ExceptionBufferPointer, sizeof(UINTN))
+ - CalculateSum8 ((UINT8 *)&Value, sizeof(UINTN));
+ Mailbox->ExceptionBufferPointer = (UINTN) Value;
+ break;
+ case DEBUG_MAILBOX_LAST_ACK:
+ Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->LastAck, sizeof(UINT8))
+ - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT8));
+ Mailbox->LastAck = (UINT8) Value;
+ break;
+ case DEBUG_MAILBOX_SEQUENCE_NO_INDEX:
+ Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->SequenceNo, sizeof(UINT8))
+ - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT8));
+ Mailbox->SequenceNo = (UINT8) Value;
+ break;
+ case DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX:
+ Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->HostSequenceNo, sizeof(UINT8))
+ - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT8));
+ Mailbox->HostSequenceNo = (UINT8) Value;
+ break;
+ }
+ UpdateMailboxChecksum (Mailbox);
+ ReleaseMpSpinLock (&mDebugMpContext.MailboxSpinLock);
+}
+/**
+ Set debug flag in mailbox.
+
+ @param[in] FlagMask Debug flag mask value.
+ @param[in] FlagValue Debug flag value.
+
+**/
+VOID
+SetDebugFlag (
+ IN UINT64 FlagMask,
+ IN UINT32 FlagValue
+ )
+{
+ DEBUG_AGENT_MAILBOX *Mailbox;
+ UINT64 Data64;
+
+ Mailbox = GetMailboxPointer ();
+ Data64 = (Mailbox->DebugFlag.Uint64 & ~FlagMask) |
+ (LShiftU64 ((UINT64)FlagValue, LowBitSet64 (FlagMask)) & FlagMask);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_FLAG_INDEX, Data64);
+}
+
+/**
+ Get debug flag in mailbox.
+
+ @param[in] FlagMask Debug flag mask value.
+
+ @return Debug flag value.
+
+**/
+UINT32
+GetDebugFlag (
+ IN UINT64 FlagMask
+ )
+{
+ DEBUG_AGENT_MAILBOX *Mailbox;
+ UINT32 DebugFlag;
+
+ Mailbox = GetMailboxPointer ();
+ DebugFlag = (UINT32) RShiftU64 (Mailbox->DebugFlag.Uint64 & FlagMask, LowBitSet64 (FlagMask));
+
+ return DebugFlag;
+}
/**
Send a debug message packet to the debug port.
@@ -46,8 +339,12 @@ SendDebugMsgPacket (
DebugHeader.StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL;
DebugHeader.Command = DEBUG_COMMAND_PRINT_MESSAGE;
DebugHeader.Length = sizeof (DEBUG_PACKET_HEADER) + (UINT8) Length;
- DebugHeader.CheckSum = 0;
- DebugHeader.CheckSum = CalculateCheckSum8 ((UINT8 *)&DebugHeader, sizeof (DEBUG_PACKET_HEADER));
+ DebugHeader.SequenceNo = 0xEE;
+ DebugHeader.Crc = 0;
+ DebugHeader.Crc = CalculateCrc16 (
+ (UINT8 *)Buffer, Length,
+ CalculateCrc16 ((UINT8 *)&DebugHeader, sizeof (DEBUG_PACKET_HEADER), 0)
+ );
DebugPortWriteBuffer (Handle, (UINT8 *)&DebugHeader, sizeof (DEBUG_PACKET_HEADER));
DebugPortWriteBuffer (Handle, (UINT8 *)Buffer, Length);
@@ -73,15 +370,13 @@ DebugAgentMsgPrint (
...
)
{
- DEBUG_AGENT_MAILBOX *Mailbox;
CHAR8 Buffer[DEBUG_DATA_MAXIMUM_REAL_DATA];
VA_LIST Marker;
- Mailbox = GetMailboxPointer ();
//
// Check driver debug mask value and global mask
//
- if ((ErrorLevel & Mailbox->DebugFlag.PrintErrorLevel) == 0) {
+ if ((ErrorLevel & GetDebugFlag (DEBUG_AGENT_FLAG_PRINT_ERROR_LEVEL)) == 0) {
return;
}
@@ -119,16 +414,14 @@ DebugAgentDataMsgPrint (
IN UINT8 Length
)
{
- DEBUG_AGENT_MAILBOX *Mailbox;
CHAR8 Buffer[DEBUG_DATA_MAXIMUM_REAL_DATA];
CHAR8 *DestBuffer;
UINTN Index;
- Mailbox = GetMailboxPointer ();
//
// Check driver debug mask value and global mask
//
- if ((ErrorLevel & Mailbox->DebugFlag.PrintErrorLevel) == 0) {
+ if ((ErrorLevel & GetDebugFlag (DEBUG_AGENT_FLAG_PRINT_ERROR_LEVEL)) == 0) {
return;
}
@@ -152,7 +445,7 @@ DebugAgentDataMsgPrint (
DestBuffer += AsciiSPrint (DestBuffer, DEBUG_DATA_MAXIMUM_REAL_DATA - (DestBuffer - Buffer), "%02x ", Data[Index]);
Index ++;
if (Index >= Length) {
- //s
+ //
// The last character of debug message has been foramtted in buffer
//
DestBuffer += AsciiSPrint(DestBuffer, DEBUG_DATA_MAXIMUM_REAL_DATA - (DestBuffer - Buffer), "]\n");
@@ -162,6 +455,46 @@ DebugAgentDataMsgPrint (
}
}
+/**
+ Read remaing debug packet except for the start symbol
+
+ @param[in] Handle Pointer to Debug Port handle.
+ @param[in, out] DebugHeader Debug header buffer including start symbol.
+
+ @retval EFI_SUCCESS Read the symbol in BreakSymbol.
+ @retval EFI_CRC_ERROR CRC check fail.
+ @retval EFI_TIMEOUT Timeout occurs when reading debug packet.
+
+**/
+EFI_STATUS
+ReadRemainingBreakPacket (
+ IN DEBUG_PORT_HANDLE Handle,
+ IN OUT DEBUG_PACKET_HEADER *DebugHeader
+ )
+{
+ UINT16 Crc;
+ //
+ // Has received start symbol, try to read the rest part
+ //
+ if (DebugPortReadBuffer (Handle, &DebugHeader->Command, sizeof (DEBUG_PACKET_HEADER) - 1, READ_PACKET_TIMEOUT) == 0) {
+ //
+ // Timeout occur, exit
+ //
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Timeout in Debug Timer interrupt\n");
+ return EFI_TIMEOUT;
+ }
+
+ Crc = DebugHeader->Crc;
+ DebugHeader->Crc = 0;
+ if (CalculateCrc16 ((UINT8 *)DebugHeader, DebugHeader->Length, 0) != Crc) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Debug Timer CRC (%x) against (%x)\n", Crc, CalculateCrc16 ((UINT8 *) &DebugHeader, DebugHeader->Length, 0));
+ DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *)DebugHeader, DebugHeader->Length);
+ return EFI_CRC_ERROR;
+ }
+
+ UpdateMailboxContent (GetMailboxPointer(), DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, DebugHeader->SequenceNo);
+ return EFI_SUCCESS;
+}
/**
Check if HOST is attached based on Mailbox.
@@ -175,7 +508,7 @@ IsHostAttached (
VOID
)
{
- return (BOOLEAN) (GetMailboxPointer ()->DebugFlag.HostAttached == 1);
+ return (BOOLEAN) (GetDebugFlag (DEBUG_AGENT_FLAG_HOST_ATTACHED) == 1);
}
/**
@@ -190,7 +523,7 @@ SetHostAttached (
)
{
DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Attach status is %d\n", Attached);
- GetMailboxPointer ()->DebugFlag.HostAttached = Attached;
+ SetDebugFlag (DEBUG_AGENT_FLAG_HOST_ATTACHED, (UINT32)Attached);
}
/**
@@ -208,17 +541,17 @@ SetDebugSetting (
)
{
RETURN_STATUS Status;
- DEBUG_AGENT_MAILBOX *Mailbox;
-
- Mailbox = GetMailboxPointer ();
Status = RETURN_SUCCESS;
switch (DebugSetting->Key) {
case DEBUG_AGENT_SETTING_SMM_ENTRY_BREAK:
- Mailbox->DebugFlag.BreakOnNextSmi = DebugSetting->Value;
+ SetDebugFlag (DEBUG_AGENT_FLAG_BREAK_ON_NEXT_SMI, DebugSetting->Value);
break;
case DEBUG_AGENT_SETTING_PRINT_ERROR_LEVEL:
- Mailbox->DebugFlag.PrintErrorLevel = DebugSetting->Value;
+ SetDebugFlag (DEBUG_AGENT_FLAG_PRINT_ERROR_LEVEL, DebugSetting->Value);
+ break;
+ case DEBUG_AGENT_SETTING_BOOT_SCRIPT_ENTRY_BREAK:
+ SetDebugFlag (DEBUG_AGENT_FLAG_BREAK_BOOT_SCRIPT, DebugSetting->Value);
break;
default:
Status = RETURN_UNSUPPORTED;
@@ -446,11 +779,13 @@ ArchReadRegisterBuffer (
Send the packet without data to HOST.
@param[in] CommandType Type of Command.
+ @param[in] SequenceNo Sequence number.
**/
VOID
SendPacketWithoutData (
- IN UINT8 CommandType
+ IN UINT8 CommandType,
+ IN UINT8 SequenceNo
)
{
DEBUG_PACKET_HEADER DebugHeader;
@@ -461,8 +796,9 @@ SendPacketWithoutData (
DebugHeader.StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL;
DebugHeader.Command = CommandType;
DebugHeader.Length = sizeof (DEBUG_PACKET_HEADER);
- DebugHeader.CheckSum = 0;
- DebugHeader.CheckSum = CalculateCheckSum8 ((UINT8 *)&DebugHeader, sizeof (DEBUG_PACKET_HEADER));
+ DebugHeader.SequenceNo = SequenceNo;
+ DebugHeader.Crc = 0;
+ DebugHeader.Crc = CalculateCrc16 ((UINT8 *)&DebugHeader, sizeof (DEBUG_PACKET_HEADER), 0);
DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, TRUE, (UINT8 *) &DebugHeader, DebugHeader.Length);
DebugPortWriteBuffer (Handle, (UINT8 *) &DebugHeader, DebugHeader.Length);
@@ -479,104 +815,142 @@ SendAckPacket (
IN UINT8 AckCommand
)
{
+ UINT8 SequenceNo;
+ DEBUG_AGENT_MAILBOX *Mailbox;
+
if (AckCommand != DEBUG_COMMAND_OK) {
+ //
+ // This is not ACK OK packet
+ //
DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "Send ACK(%d)\n", AckCommand);
}
- SendPacketWithoutData (AckCommand);
+ Mailbox = GetMailboxPointer();
+ SequenceNo = Mailbox->HostSequenceNo;
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "SendAckPacket: SequenceNo = %x\n", SequenceNo);
+ SendPacketWithoutData (AckCommand, SequenceNo);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_LAST_ACK, AckCommand);
}
/**
- Receive acknowledge packet from HOST in specified time.
+ Receive valid packet from HOST.
- @param[out] Ack Returned acknowlege type from HOST.
- @param[in] Timeout Time out value to wait for acknowlege from HOST.
- The unit is microsecond.
- @param[out] BreakReceived If BreakReceived is not NULL,
- TRUE is retured if break-in symbol received.
- FALSE is retured if break-in symbol not received.
- @param[out] CheckSumStatus If CheckSumStatus is not NULL,
- RETURN_SUCCESS CheckSum is OK.
- RETURN_NOT_FOUND Not find the CheckSum field.
+ @param[out] InputPacket Buffer to receive packet.
+ @param[out] BreakReceived TRUE means break-in symbol received.
+ FALSE means break-in symbol not received.
+ @param[out] IncompatibilityFlag If IncompatibilityFlag is not NULL, return
+ TRUE: Compatible packet received.
+ FALSE: Incompatible packet received.
+ @param[in] Timeout Time out value to wait for acknowlege from HOST.
+ The unit is microsecond.
+ @param[in] SkipStartSymbol TRUE: Skip time out when reading start symbol.
+ FALSE: Does not Skip time out when reading start symbol.
- @retval RETRUEN_SUCCESS Succeed to receive acknowlege packet from HOST,
- the type of acknowlege packet saved in Ack.
- @retval RETURN_TIMEOUT Specified timeout value was up.
+ @retval RETURN_SUCCESS A valid package was reveived in InputPacket.
+ @retval RETURN_TIMEOUT Timeout occurs.
**/
RETURN_STATUS
-ReceiveAckPacket (
- OUT UINT8 *Ack,
- IN UINTN Timeout,
- OUT BOOLEAN *BreakReceived, OPTIONAL
- OUT RETURN_STATUS *CheckSumStatus OPTIONAL
+ReceivePacket (
+ OUT UINT8 *InputPacket,
+ OUT BOOLEAN *BreakReceived,
+ OUT BOOLEAN *IncompatibilityFlag, OPTIONAL
+ IN UINTN Timeout,
+ IN BOOLEAN SkipStartSymbol
)
{
- DEBUG_PACKET_HEADER DebugHeader;
- DEBUG_PORT_HANDLE Handle;
+ DEBUG_PACKET_HEADER *DebugHeader;
+ UINTN Received;
+ DEBUG_PORT_HANDLE Handle;
+ UINT16 Crc;
+ UINTN TimeoutForStartSymbol;
Handle = GetDebugPortHandle();
-
+ if (SkipStartSymbol) {
+ TimeoutForStartSymbol = 0;
+ } else {
+ TimeoutForStartSymbol = Timeout;
+ }
+
+ DebugHeader = (DEBUG_PACKET_HEADER *) InputPacket;
while (TRUE) {
- if (DebugPortReadBuffer (Handle, (UINT8 *) &DebugHeader.StartSymbol, sizeof (DebugHeader.StartSymbol), Timeout) == 0) {
+ //
+ // Find the valid start symbol
+ //
+ Received = DebugPortReadBuffer (Handle, &DebugHeader->StartSymbol, sizeof (DebugHeader->StartSymbol), TimeoutForStartSymbol);
+ if (Received < sizeof (DebugHeader->StartSymbol)) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "DebugPortReadBuffer(StartSymbol) timeout\n");
return RETURN_TIMEOUT;
}
- if (DebugHeader.StartSymbol == DEBUG_STARTING_SYMBOL_BREAK) {
- if (BreakReceived != NULL) {
- SendAckPacket (DEBUG_COMMAND_HALT_DEFERRED);
- *BreakReceived = TRUE;
- }
- }
- if (DebugHeader.StartSymbol == DEBUG_STARTING_SYMBOL_NORMAL) {
- break;
+
+ if (DebugHeader->StartSymbol != DEBUG_STARTING_SYMBOL_NORMAL) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Invalid start symbol received [%02x]\n", DebugHeader->StartSymbol);
+ continue;
}
- DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "Invalid start symbol received [%02x]\n", DebugHeader.StartSymbol);
- }
- //
- // Read ACK packet header till field Length (not including StartSymbol and CheckSum)
- //
- DebugHeader.Length = 0;
- if (DebugPortReadBuffer (
- Handle,
- (UINT8 *)&DebugHeader.Command,
- OFFSET_OF (DEBUG_PACKET_HEADER, Length) + sizeof (DebugHeader.Length) - sizeof (DebugHeader.StartSymbol),
- Timeout
- ) == 0) {
- return RETURN_TIMEOUT;
- }
- if (DebugHeader.Length == 0) {
//
- // The CheckSum field does not exist
+ // Read Package header till field Length
//
- if (CheckSumStatus != NULL) {
- *CheckSumStatus = RETURN_NOT_FOUND;
- }
- } else {
- if (CheckSumStatus != NULL) {
- *CheckSumStatus = RETURN_SUCCESS;
- }
- if (DebugPortReadBuffer (Handle, &DebugHeader.CheckSum, sizeof (DebugHeader.CheckSum), Timeout) == 0) {
+ Received = DebugPortReadBuffer (
+ Handle,
+ &DebugHeader->Command,
+ OFFSET_OF (DEBUG_PACKET_HEADER, Length) + sizeof (DebugHeader->Length) - sizeof (DebugHeader->StartSymbol),
+ Timeout
+ );
+ if (Received == 0) {
+ DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "DebugPortReadBuffer(Command) timeout\n");
return RETURN_TIMEOUT;
}
+ if (DebugHeader->Length < sizeof (DEBUG_PACKET_HEADER)) {
+ if (IncompatibilityFlag != NULL) {
+ //
+ // This is one old version debug packet format, set Incompatibility flag
+ //
+ *IncompatibilityFlag = TRUE;
+ } else {
+ //
+ // Skip the bad small packet
+ //
+ continue;
+ }
+ } else {
+ //
+ // Read the payload data include the CRC field
+ //
+ Received = DebugPortReadBuffer (Handle, &DebugHeader->SequenceNo, (UINT8) (DebugHeader->Length - OFFSET_OF (DEBUG_PACKET_HEADER, SequenceNo)), Timeout);
+ if (Received == 0) {
+ DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "DebugPortReadBuffer(SequenceNo) timeout\n");
+ return RETURN_TIMEOUT;
+ }
+ //
+ // Calculate the CRC of Debug Packet
+ //
+ Crc = DebugHeader->Crc;
+ DebugHeader->Crc = 0;
+ if (Crc == CalculateCrc16 ((UINT8 *) DebugHeader, DebugHeader->Length, 0)) {
+ break;
+ }
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "CRC Error (received CRC is %x)\n", Crc);
+ DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *) DebugHeader, DebugHeader->Length);
+ }
}
- DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *)&DebugHeader, DebugHeader.Length);
- *Ack = DebugHeader.Command;
+ DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *) DebugHeader, DebugHeader->Length);
+
return RETURN_SUCCESS;
}
/**
Receive acknowledge packet OK from HOST in specified time.
- @param[in] Command The command type issued by TARGET.
- @param[in] Timeout Time out value to wait for acknowlege from HOST.
- The unit is microsecond.
- @param[out] BreakReceived If BreakReceived is not NULL,
- TRUE is retured if break-in symbol received.
- FALSE is retured if break-in symbol not received.
- @param[out] CheckSumStatus If CheckSumStatus is not NULL,
- RETURN_SUCCESS CheckSum is OK.
- RETURN_NOT_FOUND Not find the CheckSum field.
+ @param[in] Command The command type issued by TARGET.
+ @param[in] Timeout Time out value to wait for acknowlege from HOST.
+ The unit is microsecond.
+ @param[out] BreakReceived If BreakReceived is not NULL,
+ TRUE is retured if break-in symbol received.
+ FALSE is retured if break-in symbol not received.
+ @param[out] IncompatibilityFlag If IncompatibilityFlag is not NULL, return
+ TRUE: Compatible packet received.
+ FALSE: Incompatible packet received.
@retval RETRUEN_SUCCESS Succeed to receive acknowlege packet from HOST,
the type of acknowlege packet saved in Ack.
@@ -588,109 +962,56 @@ SendCommandAndWaitForAckOK (
IN UINT8 Command,
IN UINTN Timeout,
OUT BOOLEAN *BreakReceived, OPTIONAL
- OUT RETURN_STATUS *CheckSumStatus OPTIONAL
+ OUT BOOLEAN *IncompatibilityFlag OPTIONAL
)
{
RETURN_STATUS Status;
- UINT8 Ack;
-
- while (TRUE) {
- SendPacketWithoutData (Command);
- while (TRUE) {
- Status = ReceiveAckPacket (&Ack, Timeout, BreakReceived, CheckSumStatus);
- if (Status == RETURN_SUCCESS && Ack == DEBUG_COMMAND_RESEND) {
- //
- // Resend the last command
- //
- break;
- }
- if ((Status == RETURN_SUCCESS && Ack == DEBUG_COMMAND_OK) ||
- Status == RETURN_TIMEOUT) {
- //
- // Received Ack OK or timeout
- //
- return Status;
- }
- }
- }
-}
-
-/**
- Receive valid packet from HOST.
-
- @param[out] InputPacket Buffer to receive packet.
- @param[out] BreakReceived TRUE means break-in symbol received.
- FALSE means break-in symbol not received.
-
- @retval RETURN_SUCCESS A valid package was reveived in InputPacket.
- @retval RETURN_TIMEOUT Timeout occurs.
-
-**/
-RETURN_STATUS
-ReceivePacket (
- OUT UINT8 *InputPacket,
- OUT BOOLEAN *BreakReceived
- )
-{
- DEBUG_PACKET_HEADER *DebugHeader;
- UINTN Received;
- DEBUG_PORT_HANDLE Handle;
- UINT8 CheckSum;
-
- Handle = GetDebugPortHandle();
-
- DebugHeader = (DEBUG_PACKET_HEADER *) InputPacket;
- while (TRUE) {
- //
- // Find the valid start symbol
- //
- DebugPortReadBuffer (Handle, &DebugHeader->StartSymbol, sizeof (DebugHeader->StartSymbol), 0);
-
- if (DebugHeader->StartSymbol == DEBUG_STARTING_SYMBOL_BREAK) {
- *BreakReceived = TRUE;
- SendAckPacket (DEBUG_COMMAND_HALT_DEFERRED);
- }
-
- if (DebugHeader->StartSymbol != DEBUG_STARTING_SYMBOL_NORMAL) {
- DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "Invalid start symbol received [%02x]\n", DebugHeader->StartSymbol);
+ UINT8 InputPacketBuffer[DEBUG_DATA_UPPER_LIMIT];
+ DEBUG_PACKET_HEADER *DebugHeader;
+ UINT8 SequenceNo;
+ UINT8 HostSequenceNo;
+ UINT8 RetryCount;
+
+ RetryCount = 3;
+ DebugHeader = (DEBUG_PACKET_HEADER *) InputPacketBuffer;
+ Status = RETURN_TIMEOUT;
+ while (RetryCount > 0) {
+ SequenceNo = GetMailboxPointer()->SequenceNo;
+ HostSequenceNo = GetMailboxPointer()->HostSequenceNo;
+ SendPacketWithoutData (Command, SequenceNo);
+ Status = ReceivePacket ((UINT8 *) DebugHeader, BreakReceived, IncompatibilityFlag, Timeout, FALSE);
+ if (Status == RETURN_TIMEOUT) {
+ if (Command == DEBUG_COMMAND_INIT_BREAK) {
+ RetryCount--;
+ } else {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Timeout when waiting for ACK packet.\n");
+ }
continue;
}
-
- //
- // Read Package header except for checksum
- //
- Received = DebugPortReadBuffer (
- Handle,
- &DebugHeader->Command,
- OFFSET_OF (DEBUG_PACKET_HEADER, Length) + sizeof (DebugHeader->Length) - sizeof (DebugHeader->StartSymbol),
- 0
- );
- if (Received == 0) {
- return RETURN_TIMEOUT;
- }
-
+ ASSERT_EFI_ERROR (Status);
//
- // Read the payload data include the checksum
+ // Status == RETURN_SUCCESS
//
- Received = DebugPortReadBuffer (Handle, &DebugHeader->CheckSum, DebugHeader->Length - OFFSET_OF (DEBUG_PACKET_HEADER, CheckSum), 0);
- if (Received == 0) {
- return RETURN_TIMEOUT;
+ if (DebugHeader->Command == DEBUG_COMMAND_OK && DebugHeader->SequenceNo == SequenceNo) {
+ //
+ // Received Ack OK
+ //
+ UpdateMailboxContent (GetMailboxPointer(), DEBUG_MAILBOX_SEQUENCE_NO_INDEX, ++SequenceNo);
+ return Status;
}
- //
- // Calculate the checksum of Debug Packet
- //
- CheckSum = CalculateCheckSum8 ((UINT8 *) DebugHeader, DebugHeader->Length);
- if (CheckSum == 0) {
- break;
+ if (DebugHeader->Command == DEBUG_COMMAND_GO && (DebugHeader->SequenceNo == HostSequenceNo || Command == DEBUG_COMMAND_INIT_BREAK)) {
+ //
+ // Received Old GO
+ //
+ if (Command == DEBUG_COMMAND_INIT_BREAK) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Receive GO() in last boot\n");
+ }
+ SendPacketWithoutData (DEBUG_COMMAND_OK, DebugHeader->SequenceNo);
}
- DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "CheckSum Error (Caculated checksum is %x, received checksum is %x\n", CheckSum, DebugHeader->CheckSum);
- DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Send DEBUG_COMMAND_RESEND command.\n");
- SendAckPacket (DEBUG_COMMAND_RESEND);
}
- DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *) DebugHeader, DebugHeader->Length);
-
- return RETURN_SUCCESS;
+ ASSERT (Command == DEBUG_COMMAND_INIT_BREAK);
+ return Status;
}
/**
@@ -773,7 +1094,7 @@ GetBreakCause (
default:
if (Vector < 20) {
- if (GetMailboxPointer()->DebugFlag.SteppingFlag == 1) {
+ if (GetDebugFlag (DEBUG_AGENT_FLAG_STEPPING) == 1) {
//
// If stepping command is executing
//
@@ -789,28 +1110,28 @@ GetBreakCause (
}
/**
- Send command packet with data to HOST.
+ Send packet with response data to HOST.
- @param[in] Command Command type.
@param[in] Data Pointer to response data buffer.
@param[in] DataSize Size of response data in byte.
@retval RETURN_SUCCESS Response data was sent successfully.
- @retval RETURN_DEVICE_ERROR Cannot receive DEBUG_COMMAND_OK from HOST.
**/
RETURN_STATUS
-SendCommandWithDataPacket (
- IN UINT8 Command,
+SendDataResponsePacket (
IN UINT8 *Data,
IN UINT16 DataSize
)
{
+ RETURN_STATUS Status;
DEBUG_PACKET_HEADER *DebugHeader;
BOOLEAN LastPacket;
- UINT8 Ack;
+ DEBUG_PACKET_HEADER *AckDebugHeader;
UINT8 DebugPacket[DEBUG_DATA_UPPER_LIMIT];
+ UINT8 InputPacketBuffer[DEBUG_DATA_UPPER_LIMIT];
DEBUG_PORT_HANDLE Handle;
+ UINT8 SequenceNo;
Handle = GetDebugPortHandle();
@@ -818,84 +1139,67 @@ SendCommandWithDataPacket (
DebugHeader->StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL;
while (TRUE) {
+ SequenceNo = GetMailboxPointer()->HostSequenceNo;
if (DataSize <= DEBUG_DATA_MAXIMUM_REAL_DATA) {
LastPacket = TRUE;
- DebugHeader->Command = Command;
- DebugHeader->Length = (UINT8) (DataSize + sizeof (DEBUG_PACKET_HEADER));
- DebugHeader->CheckSum = 0;
+ DebugHeader->Command = DEBUG_COMMAND_OK;
+ DebugHeader->Length = (UINT8) (DataSize + sizeof (DEBUG_PACKET_HEADER));
+ DebugHeader->SequenceNo = SequenceNo;
+ DebugHeader->Crc = 0;
CopyMem (DebugHeader + 1, Data, DataSize);
} else {
LastPacket = FALSE;
- DebugHeader->Command = DEBUG_COMMAND_IN_PROGRESS;
- DebugHeader->Length = DEBUG_DATA_MAXIMUM_REAL_DATA + sizeof (DEBUG_PACKET_HEADER);
- DebugHeader->CheckSum = 0;
+ DebugHeader->Command = DEBUG_COMMAND_IN_PROGRESS;
+ DebugHeader->Length = DEBUG_DATA_MAXIMUM_REAL_DATA + sizeof (DEBUG_PACKET_HEADER);
+ DebugHeader->SequenceNo = SequenceNo;
+ DebugHeader->Crc = 0;
CopyMem (DebugHeader + 1, Data, DEBUG_DATA_MAXIMUM_REAL_DATA);
}
//
// Calculate and fill the checksum
//
- DebugHeader->CheckSum = CalculateCheckSum8 ((UINT8 *) DebugHeader, DebugHeader->Length);
+ DebugHeader->Crc = CalculateCrc16 ((UINT8 *) DebugHeader, DebugHeader->Length, 0);
DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, TRUE, (UINT8 *) DebugHeader, DebugHeader->Length);
DebugPortWriteBuffer (Handle, (UINT8 *) DebugHeader, DebugHeader->Length);
- ReceiveAckPacket(&Ack, 0, NULL, NULL);
- switch (Ack) {
- case DEBUG_COMMAND_RESEND:
- //
- // Send the packet again
- //
- DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Received DEBUG_COMMAND_RESEND.\n");
- break;
-
- case DEBUG_COMMAND_CONTINUE:
- //
- // Send the rest packet
- //
- Data += DEBUG_DATA_MAXIMUM_REAL_DATA;
- DataSize -= DEBUG_DATA_MAXIMUM_REAL_DATA;
- break;
-
- case DEBUG_COMMAND_OK:
- if (LastPacket) {
+ while (TRUE) {
+ Status = ReceivePacket (InputPacketBuffer, NULL, NULL, READ_PACKET_TIMEOUT, FALSE);
+ if (Status == RETURN_TIMEOUT) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Timeout in SendDataResponsePacket()\n");
+ break;
+ }
+ AckDebugHeader = (DEBUG_PACKET_HEADER *) InputPacketBuffer;
+ SequenceNo = AckDebugHeader->SequenceNo;
+ if (AckDebugHeader->Command == DEBUG_COMMAND_OK &&
+ SequenceNo == DebugHeader->SequenceNo &&
+ LastPacket) {
//
// If this is the last packet, return RETURN_SUCCESS.
//
return RETURN_SUCCESS;
- } else {
- return RETURN_DEVICE_ERROR;
}
-
- default:
- return RETURN_DEVICE_ERROR;
-
+ if ((SequenceNo == (UINT8) (DebugHeader->SequenceNo + 1)) && (AckDebugHeader->Command == DEBUG_COMMAND_CONTINUE)) {
+ //
+ // Send the rest packet
+ //
+ Data += DEBUG_DATA_MAXIMUM_REAL_DATA;
+ DataSize -= DEBUG_DATA_MAXIMUM_REAL_DATA;
+ UpdateMailboxContent (GetMailboxPointer(), DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, (UINT8) SequenceNo);
+ break;
+ }
+ if (SequenceNo >= DebugHeader->SequenceNo) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Received one old or new command(SequenceNo is %x, last SequenceNo is %x)\n", SequenceNo, DebugHeader->SequenceNo);
+ break;
+ }
}
}
}
/**
- Send packet with response data to HOST.
-
- @param[in] Data Pointer to response data buffer.
- @param[in] DataSize Size of response data in byte.
-
- @retval RETURN_SUCCESS Response data was sent successfully.
- @retval RETURN_DEVICE_ERROR Cannot receive DEBUG_COMMAND_OK from HOST.
-
-**/
-RETURN_STATUS
-SendDataResponsePacket (
- IN UINT8 *Data,
- IN UINT16 DataSize
- )
-{
- return SendCommandWithDataPacket (DEBUG_COMMAND_OK, Data, DataSize);
-}
-
-/**
Send break cause packet to HOST.
@param[in] Vector Vector value of exception or interrutp.
@@ -927,6 +1231,7 @@ SendBreakCausePacket (
If received acknowlege, check the revision of HOST.
Set Attach Flag if attach successfully.
+ @param[in] BreakCause Break cause of this break event.
@param[in] Timeout Time out value to wait for acknowlege from HOST.
The unit is microsecond.
@param[out] BreakReceived If BreakReceived is not NULL,
@@ -935,42 +1240,45 @@ SendBreakCausePacket (
**/
RETURN_STATUS
AttachHost (
+ IN UINT8 BreakCause,
IN UINTN Timeout,
OUT BOOLEAN *BreakReceived
)
{
RETURN_STATUS Status;
DEBUG_PORT_HANDLE Handle;
- RETURN_STATUS CheckSumStatus;
+ BOOLEAN IncompatibilityFlag;
+ IncompatibilityFlag = FALSE;
Handle = GetDebugPortHandle();
//
// Send init break and wait ack in Timeout
//
DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgSendInitPacket, AsciiStrLen (mErrorMsgSendInitPacket));
- Status = SendCommandAndWaitForAckOK (DEBUG_COMMAND_INIT_BREAK, Timeout, BreakReceived, &CheckSumStatus);
- if (RETURN_ERROR (Status)) {
- DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgConnectFail, AsciiStrLen (mErrorMsgConnectFail));
- return Status;
+ if (BreakCause == DEBUG_DATA_BREAK_CAUSE_SYSTEM_RESET) {
+ Status = SendCommandAndWaitForAckOK (DEBUG_COMMAND_INIT_BREAK, Timeout, BreakReceived, &IncompatibilityFlag);
+ } else {
+ Status = SendCommandAndWaitForAckOK (DEBUG_COMMAND_ATTACH_BREAK, Timeout, BreakReceived, &IncompatibilityFlag);
}
-
- if (CheckSumStatus == RETURN_NOT_FOUND) {
+ if (IncompatibilityFlag) {
//
- // If the CheckSum field does not exist in Debug Packet,
- // the HOST should be running with 0.1 transfer protocol.
- // It could be UDK Debugger for Windows v1.1 or for Linux v0.8.
+ // If the incompatible Debug Packet received, the HOST should be running transfer protocol before DEBUG_AGENT_REVISION.
+ // It could be UDK Debugger for Windows v1.1/v1.2 or for Linux v0.8/v1.2.
//
DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgVersionAlert, AsciiStrLen (mErrorMsgVersionAlert));
CpuDeadLoop ();
}
-
- DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgConnectOK, AsciiStrLen (mErrorMsgConnectOK));
- //
- // Set Attach flag
- //
- SetHostAttached (TRUE);
-
+
+ if (RETURN_ERROR (Status)) {
+ DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgConnectFail, AsciiStrLen (mErrorMsgConnectFail));
+ } else {
+ DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgConnectOK, AsciiStrLen (mErrorMsgConnectOK));
+ //
+ // Set Attach flag
+ //
+ SetHostAttached (TRUE);
+ }
return Status;
}
@@ -978,7 +1286,8 @@ AttachHost (
Send Break point packet to HOST.
Only the first breaking processor could sent BREAK_POINT packet.
-
+
+ @param[in] BreakCause Break cause of this break event.
@param[in] ProcessorIndex Processor index value.
@param[out] BreakReceived If BreakReceived is not NULL,
TRUE is retured if break-in symbol received.
@@ -987,6 +1296,7 @@ AttachHost (
**/
VOID
SendBreakPacketToHost (
+ IN UINT8 BreakCause,
IN UINT32 ProcessorIndex,
OUT BOOLEAN *BreakReceived
)
@@ -998,7 +1308,7 @@ SendBreakPacketToHost (
if (IsHostAttached ()) {
DebugAgentMsgPrint (DEBUG_AGENT_INFO, "processor[%x]:Send Break Packet to HOST.\n", ProcessorIndex);
- SendCommandAndWaitForAckOK (DEBUG_COMMAND_BREAK_POINT, 0, BreakReceived, NULL);
+ SendCommandAndWaitForAckOK (DEBUG_COMMAND_BREAK_POINT, READ_PACKET_TIMEOUT, BreakReceived, NULL);
} else {
DebugAgentMsgPrint (DEBUG_AGENT_INFO, "processor[%x]:Try to attach HOST.\n", ProcessorIndex);
//
@@ -1015,7 +1325,7 @@ SendBreakPacketToHost (
//
// Try to attach HOST
//
- while (AttachHost (0, NULL) != RETURN_SUCCESS);
+ while (AttachHost (BreakCause, 0, NULL) != RETURN_SUCCESS);
}
}
@@ -1065,12 +1375,13 @@ CommandCommunication (
DEBUG_PORT_HANDLE Handle;
DEBUG_AGENT_EXCEPTION_BUFFER AgentExceptionBuffer;
UINT32 IssuedViewPoint;
+ DEBUG_AGENT_MAILBOX *Mailbox;
ProcessorIndex = 0;
IssuedViewPoint = 0;
HaltDeferred = BreakReceived;
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
ProcessorIndex = GetProcessorIndex ();
SetCpuStopFlagByIndex (ProcessorIndex, TRUE);
if (mDebugMpContext.ViewPointIndex == ProcessorIndex) {
@@ -1085,14 +1396,14 @@ CommandCommunication (
//
// Set AgentInProgress Flag.
//
- GetMailboxPointer()->DebugFlag.AgentInProgress = 1;
+ SetDebugFlag (DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS, 1);
}
Handle = GetDebugPortHandle();
while (TRUE) {
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
//
// Check if the current processor is HOST view point
//
@@ -1114,35 +1425,44 @@ CommandCommunication (
}
}
- AcquireDebugPortControl ();
+ AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
- Status = ReceivePacket (InputPacketBuffer, &BreakReceived);
+ DebugHeader =(DEBUG_PACKET_HEADER *) InputPacketBuffer;
- if (BreakReceived) {
- HaltDeferred = TRUE;
- BreakReceived = FALSE;
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "TARGET: Try to get command from HOST...\n");
+ Status = ReceivePacket ((UINT8 *)DebugHeader, &BreakReceived, NULL, READ_PACKET_TIMEOUT, TRUE);
+ if (Status != RETURN_SUCCESS || (DebugHeader->Command & DEBUG_COMMAND_RESPONSE) != 0) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Get command[%x] sequenceno[%x] returned status is [%x] \n", DebugHeader->Command, DebugHeader->SequenceNo, Status);
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Get command failed or it's response packet not expected! \n");
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
+ continue;
}
- if (Status != RETURN_SUCCESS) {
- ReleaseDebugPortControl ();
+ Mailbox = GetMailboxPointer ();
+ if (DebugHeader->SequenceNo == Mailbox->HostSequenceNo) {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Receive one old command[%x] agaist command[%x]\n", DebugHeader->SequenceNo, Mailbox->HostSequenceNo);
+ SendAckPacket (Mailbox->LastAck);
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
+ continue;
+ } else if (DebugHeader->SequenceNo == (UINT8) (Mailbox->HostSequenceNo + 1)) {
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, (UINT8) DebugHeader->SequenceNo);
+ } else {
+ DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Receive one invalid comamnd[%x] agaist command[%x]\n", DebugHeader->SequenceNo, Mailbox->HostSequenceNo);
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
continue;
}
-
- Data8 = 1;
-
- DebugHeader =(DEBUG_PACKET_HEADER *) InputPacketBuffer;
-
- GetMailboxPointer()->ExceptionBufferPointer = (UINT64)(UINTN) &AgentExceptionBuffer.JumpBuffer;
+
//
// Save CPU content before executing HOST commond
//
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_EXCEPTION_BUFFER_POINTER_INDEX, (UINT64)(UINTN) &AgentExceptionBuffer.JumpBuffer);
if (SetJump (&AgentExceptionBuffer.JumpBuffer) != 0) {
//
// If HOST command failed, continue to wait for HOST's next command
// If needed, agent could send exception info to HOST.
//
SendAckPacket (DEBUG_COMMAND_ABORT);
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
continue;
}
@@ -1150,9 +1470,18 @@ CommandCommunication (
switch (DebugHeader->Command) {
+ case DEBUG_COMMAND_HALT:
+ SendAckPacket (DEBUG_COMMAND_HALT_DEFERRED);
+ HaltDeferred = TRUE;
+ BreakReceived = FALSE;
+ Status = RETURN_SUCCESS;
+ break;
+
case DEBUG_COMMAND_RESET:
SendAckPacket (DEBUG_COMMAND_OK);
- ReleaseDebugPortControl ();
+ SendAckPacket (DEBUG_COMMAND_OK);
+ SendAckPacket (DEBUG_COMMAND_OK);
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
ResetCold ();
//
@@ -1160,6 +1489,9 @@ CommandCommunication (
// PCD can be used if 2 seconds isn't long enough for some platforms.
//
MicroSecondDelay (2000000);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, Mailbox->HostSequenceNo + 1);
+ SendAckPacket (DEBUG_COMMAND_TIMEOUT);
+ SendAckPacket (DEBUG_COMMAND_TIMEOUT);
SendAckPacket (DEBUG_COMMAND_TIMEOUT);
break;
@@ -1176,13 +1508,13 @@ CommandCommunication (
//
// Clear Stepping Flag
//
- GetMailboxPointer()->DebugFlag.SteppingFlag = 0;
+ SetDebugFlag (DEBUG_AGENT_FLAG_STEPPING, 0);
if (!HaltDeferred) {
//
// If no HALT command received when being in-active mode
//
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
Data32 = FindNextPendingBreakCpu ();
if (Data32 != -1) {
//
@@ -1200,11 +1532,11 @@ CommandCommunication (
//
// Send break packet to HOST to let HOST break again
//
- SendBreakPacketToHost (0, &BreakReceived);
+ SendBreakPacketToHost (DEBUG_DATA_BREAK_CAUSE_UNKNOWN, mDebugMpContext.BreakAtCpuIndex, &BreakReceived);
//
// Continue to run into loop to read command packet from HOST
//
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
break;
}
@@ -1240,8 +1572,12 @@ CommandCommunication (
//
SendAckPacket (DEBUG_COMMAND_OK);
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
+ if (!IsHostAttached()) {
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_SEQUENCE_NO_INDEX, 0);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, 0);
+ }
return;
} else {
@@ -1257,7 +1593,7 @@ CommandCommunication (
case DEBUG_COMMAND_BREAK_CAUSE:
- if (MultiProcessorDebugSupport && ProcessorIndex != mDebugMpContext.BreakAtCpuIndex) {
+ if (MultiProcessorDebugSupport() && ProcessorIndex != mDebugMpContext.BreakAtCpuIndex) {
Status = SendBreakCausePacket (DEBUG_TIMER_VECTOR, CpuContext);
} else {
@@ -1291,8 +1627,8 @@ CommandCommunication (
//
// Set Stepping Flag
//
- GetMailboxPointer()->DebugFlag.SteppingFlag = 1;
- ReleaseDebugPortControl ();
+ SetDebugFlag (DEBUG_AGENT_FLAG_STEPPING, 1);
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
//
// Executing stepping command directly without sending ACK packet,
// ACK packet will be sent after stepping done.
@@ -1424,7 +1760,7 @@ CommandCommunication (
case DEBUG_COMMAND_SET_VIEWPOINT:
SetViewPoint = (DEBUG_DATA_SET_VIEWPOINT *) (DebugHeader + 1);
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
if (IsCpuStopped (SetViewPoint->ViewPoint)) {
SetDebugViewPoint (SetViewPoint->ViewPoint);
SendAckPacket (DEBUG_COMMAND_OK);
@@ -1449,7 +1785,7 @@ CommandCommunication (
break;
case DEBUG_COMMAND_MEMORY_READY:
- Data8 = (UINT8) GetMailboxPointer ()->DebugFlag.MemoryReady;
+ Data8 = (UINT8) GetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY);
SendDataResponsePacket (&Data8, (UINT16) sizeof (UINT8));
break;
@@ -1517,7 +1853,7 @@ CommandCommunication (
SendAckPacket (DEBUG_COMMAND_ABORT);
}
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
CpuPause ();
}
}
@@ -1552,7 +1888,17 @@ InterruptProcess (
IssuedViewPoint = 0;
BreakReceived = FALSE;
- if (MultiProcessorDebugSupport) {
+ if (mSkipBreakpoint) {
+ //
+ // If Skip Breakpoint flag is set, means communication is disturbed by hardware SMI, we need to ignore the break points in SMM
+ //
+ if ((Vector == DEBUG_INT1_VECTOR) || (Vector == DEBUG_INT3_VECTOR)) {
+ DebugPortWriteBuffer (GetDebugPortHandle(), (UINT8 *) mWarningMsgIngoreBreakpoint, AsciiStrLen (mWarningMsgIngoreBreakpoint));
+ return;
+ }
+ }
+
+ if (MultiProcessorDebugSupport()) {
ProcessorIndex = GetProcessorIndex ();
//
// If this processor has alreay halted before, need to check it later
@@ -1562,22 +1908,22 @@ InterruptProcess (
}
}
- if (IssuedViewPoint == ProcessorIndex) {
+ if (IssuedViewPoint == ProcessorIndex && GetDebugFlag (DEBUG_AGENT_FLAG_STEPPING) != 1) {
//
// Check if this exception is issued by Debug Agent itself
// If yes, fill the debug agent exception buffer and LongJump() back to
// the saved CPU content in CommandCommunication()
//
- if (GetMailboxPointer()->DebugFlag.AgentInProgress == 1) {
+ if (GetDebugFlag (DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS) == 1) {
DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "Debug agent meet one Exception, ExceptionNum is %d.\n", Vector);
ExceptionBuffer = (DEBUG_AGENT_EXCEPTION_BUFFER *) (UINTN) GetMailboxPointer()->ExceptionBufferPointer;
ExceptionBuffer->ExceptionContent.ExceptionNum = (UINT8) Vector;
ExceptionBuffer->ExceptionContent.ExceptionData = (UINT32) CpuContext->ExceptionData;
- LongJump ((BASE_LIBRARY_JUMP_BUFFER *)(UINTN)(GetMailboxPointer()->ExceptionBufferPointer), 1);
+ LongJump ((BASE_LIBRARY_JUMP_BUFFER *)(UINTN)(ExceptionBuffer), 1);
}
}
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
//
// If RUN commmand is executing, wait for it done.
//
@@ -1586,16 +1932,14 @@ InterruptProcess (
}
}
- Handle = GetDebugPortHandle();
-
+ Handle = GetDebugPortHandle();
+ BreakCause = GetBreakCause (Vector, CpuContext);
switch (Vector) {
case DEBUG_INT1_VECTOR:
case DEBUG_INT3_VECTOR:
- BreakCause = GetBreakCause (Vector, CpuContext);
-
switch (BreakCause) {
case DEBUG_DATA_BREAK_CAUSE_SYSTEM_RESET:
- if (AttachHost (INIT_BREAK_ACK_TIMEOUT, &BreakReceived) != RETURN_SUCCESS) {
+ if (AttachHost (BreakCause, READ_PACKET_TIMEOUT, &BreakReceived) != RETURN_SUCCESS) {
//
// Try to connect HOST, return if fails
//
@@ -1608,7 +1952,7 @@ InterruptProcess (
//
// Stepping is finished, send Ack package.
//
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
mDebugMpContext.BreakAtCpuIndex = ProcessorIndex;
}
SendAckPacket (DEBUG_COMMAND_OK);
@@ -1619,7 +1963,7 @@ InterruptProcess (
//
// Memory is ready
//
- SendCommandAndWaitForAckOK (DEBUG_COMMAND_MEMORY_READY, 0, &BreakReceived, NULL);
+ SendCommandAndWaitForAckOK (DEBUG_COMMAND_MEMORY_READY, READ_PACKET_TIMEOUT, &BreakReceived, NULL);
CommandCommunication (Vector, CpuContext, BreakReceived);
break;
@@ -1647,14 +1991,14 @@ InterruptProcess (
//
// Send Break packet to HOST
//
- AcquireDebugPortControl ();
+ AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
//
// Only the first breaking processor could send BREAK_POINT to HOST
//
if (IsFirstBreakProcessor (ProcessorIndex)) {
- SendBreakPacketToHost (ProcessorIndex, &BreakReceived);
+ SendBreakPacketToHost (BreakCause, ProcessorIndex, &BreakReceived);
}
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
if (Vector == DEBUG_INT3_VECTOR) {
//
@@ -1681,9 +2025,9 @@ InterruptProcess (
case DEBUG_TIMER_VECTOR:
- AcquireDebugPortControl ();
+ AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
if (IsBsp (ProcessorIndex)) {
//
// If current processor is BSP, check Apic timer's init count if changed,
@@ -1697,7 +2041,7 @@ InterruptProcess (
}
if (!IsBsp (ProcessorIndex) || mDebugMpContext.IpiSentByAp) {
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
//
// If current processor is not BSP or this is one IPI sent by AP
//
@@ -1725,8 +2069,10 @@ InterruptProcess (
if (DebugReadBreakSymbol (Handle, &InputCharacter) == EFI_NOT_FOUND) {
break;
}
+
if ((!IsHostAttached () && (InputCharacter == DEBUG_STARTING_SYMBOL_ATTACH)) ||
- (IsHostAttached () && (InputCharacter == DEBUG_STARTING_SYMBOL_BREAK))
+ (IsHostAttached () && (InputCharacter == DEBUG_COMMAND_HALT)) ||
+ (IsHostAttached () && (InputCharacter == DEBUG_COMMAND_GO))
) {
DebugAgentMsgPrint (DEBUG_AGENT_VERBOSE, "Received data [%02x]\n", InputCharacter);
//
@@ -1734,25 +2080,32 @@ InterruptProcess (
//
SendAckPacket (DEBUG_COMMAND_OK);
+ //
+ // If receive GO command in Debug Timer, means HOST may lost ACK packet before.
+ //
+ if (InputCharacter == DEBUG_COMMAND_GO) {
+ break;
+ }
+
if (!IsHostAttached ()) {
//
// Try to attach HOST, if no ack received after 200ms, return
//
- if (AttachHost (INIT_BREAK_ACK_TIMEOUT, &BreakReceived) != RETURN_SUCCESS) {
+ if (AttachHost (BreakCause, READ_PACKET_TIMEOUT, &BreakReceived) != RETURN_SUCCESS) {
break;
}
}
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
if(FindNextPendingBreakCpu () != -1) {
SetCpuBreakFlagByIndex (ProcessorIndex, TRUE);
} else {
HaltOtherProcessors (ProcessorIndex);
}
}
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
CommandCommunication (Vector, CpuContext, BreakReceived);
- AcquireDebugPortControl ();
+ AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
break;
}
}
@@ -1762,19 +2115,17 @@ InterruptProcess (
//
SendApicEoi ();
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
break;
default:
-
if (Vector <= DEBUG_EXCEPT_SIMD) {
- BreakCause = GetBreakCause (Vector, CpuContext);
if (BreakCause == DEBUG_DATA_BREAK_CAUSE_STEPPING) {
//
// Stepping is finished, send Ack package.
//
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
mDebugMpContext.BreakAtCpuIndex = ProcessorIndex;
}
SendAckPacket (DEBUG_COMMAND_OK);
@@ -1782,14 +2133,14 @@ InterruptProcess (
//
// Exception occurs, send Break packet to HOST
//
- AcquireDebugPortControl ();
+ AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
//
// Only the first breaking processor could send BREAK_POINT to HOST
//
if (IsFirstBreakProcessor (ProcessorIndex)) {
- SendBreakPacketToHost (ProcessorIndex, &BreakReceived);
+ SendBreakPacketToHost (BreakCause, ProcessorIndex, &BreakReceived);
}
- ReleaseDebugPortControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock);
}
CommandCommunication (Vector, CpuContext, BreakReceived);
@@ -1797,7 +2148,7 @@ InterruptProcess (
break;
}
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
//
// Clear flag and wait for all processors run here
//
@@ -1814,11 +2165,11 @@ InterruptProcess (
}
}
- if (IssuedViewPoint == ProcessorIndex) {
+ if (IssuedViewPoint == ProcessorIndex && GetDebugFlag (DEBUG_AGENT_FLAG_STEPPING) != 1) {
//
- // Clean up AgentInProgress flag
+ // If the command is not stepping, clean up AgentInProgress flag
//
- GetMailboxPointer()->DebugFlag.AgentInProgress = 0;
+ SetDebugFlag (DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS, 0);
}
return;
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h
index 61448448d..5eb50d038 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h
@@ -1,7 +1,7 @@
/** @file
Command header of for Debug Agent library instance.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -32,6 +32,8 @@
#include <Library/DebugLib.h>
#include <Library/TimerLib.h>
#include <Library/PrintLib.h>
+#include <Library/PeCoffGetEntryPointLib.h>
+#include <Library/PeCoffExtraActionLib.h>
#include <TransferProtocol.h>
#include <ImageDebugSupport.h>
@@ -40,11 +42,24 @@
#include "DebugTimer.h"
#include "ArchDebugSupport.h"
+//
+// These macros may be already defined in DebugAgentLib.h
+//
+#define DEBUG_AGENT_INIT_PEI 9
+#define DEBUG_AGENT_INIT_DXE_LOAD 10
+#define DEBUG_AGENT_INIT_DXE_UNLOAD 11
+#define DEBUG_AGENT_INIT_THUNK_PEI_IA32TOX64 12
+
#define DEBUG_INT1_VECTOR 1
#define DEBUG_INT3_VECTOR 3
#define DEBUG_TIMER_VECTOR 32
#define DEBUG_MAILBOX_VECTOR 33
+//
+// Timeout value for reading packet (unit is microsecond)
+//
+#define READ_PACKET_TIMEOUT (500 * 1000)
+
#define SOFT_INTERRUPT_SIGNATURE SIGNATURE_32('S','O','F','T')
#define SYSTEM_RESET_SIGNATURE SIGNATURE_32('S','Y','S','R')
#define MEMORY_READY_SIGNATURE SIGNATURE_32('M','E','M','R')
@@ -53,6 +68,8 @@ extern UINTN Exception0Handle;
extern UINTN TimerInterruptHandle;
extern UINT16 ExceptionStubHeaderSize;
+extern BOOLEAN mSkipBreakpoint;
+
//
// CPU exception information issued by debug agent
//
@@ -67,23 +84,44 @@ typedef struct {
DEBUG_DATA_RESPONSE_GET_EXCEPTION ExceptionContent;
} DEBUG_AGENT_EXCEPTION_BUFFER;
-#pragma pack(1)
-typedef struct {
- //
- // Lower 32 bits to store the status of DebugAgent
- //
- UINT32 HostAttached : 1; // 1: HOST is attached
- UINT32 AgentInProgress : 1; // 1: Debug Agent is communicating with HOST
- UINT32 MemoryReady : 1; // 1: Memory is ready
- UINT32 SteppingFlag : 1; // 1: Agent is running stepping command
- UINT32 Reserved1 : 28;
+#define DEBUG_AGENT_FLAG_HOST_ATTACHED BIT0
+#define DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS BIT1
+#define DEBUG_AGENT_FLAG_MEMORY_READY BIT2
+#define DEBUG_AGENT_FLAG_STEPPING BIT3
+#define DEBUG_AGENT_FLAG_CHECK_MAILBOX_IN_HOB BIT4
+#define DEBUG_AGENT_FLAG_BREAK_ON_NEXT_SMI BIT32
+#define DEBUG_AGENT_FLAG_PRINT_ERROR_LEVEL (BIT33|BIT34|BIT35|BIT36)
+#define DEBUG_AGENT_FLAG_BREAK_BOOT_SCRIPT BIT37
+
+#define DEBUG_MAILBOX_DEBUG_FLAG_INDEX 1
+#define DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX 2
+#define DEBUG_MAILBOX_EXCEPTION_BUFFER_POINTER_INDEX 3
+#define DEBUG_MAILBOX_LAST_ACK 4
+#define DEBUG_MAILBOX_SEQUENCE_NO_INDEX 5
+#define DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX 6
- //
- // Higher 32bits to control the behavior of DebugAgent
- //
- UINT32 BreakOnNextSmi : 1; // 1: Break on next SMI
- UINT32 PrintErrorLevel : 8; // Bitmask of print error level for debug message
- UINT32 Reserved2 : 23;
+#pragma pack(1)
+typedef union {
+ struct {
+ //
+ // Lower 32 bits to store the status of DebugAgent
+ //
+ UINT32 HostAttached : 1; // 1: HOST is attached
+ UINT32 AgentInProgress : 1; // 1: Debug Agent is communicating with HOST
+ UINT32 MemoryReady : 1; // 1: Memory is ready
+ UINT32 SteppingFlag : 1; // 1: Agent is running stepping command
+ UINT32 CheckMailboxInHob : 1; // 1: Need to check mailbox saved in HOB
+ UINT32 SendingPacket : 1; // 1: TARGET is sending debug packet to HOST
+ UINT32 Reserved1 : 26;
+ //
+ // Higher 32bits to control the behavior of DebugAgent
+ //
+ UINT32 BreakOnNextSmi : 1; // 1: Break on next SMI
+ UINT32 PrintErrorLevel : 4; // Bitmask of print error level for debug message
+ UINT32 BreakOnBootScript : 1; // 1: Break before executing boot script
+ UINT32 Reserved2 : 26;
+ } Bits;
+ UINT64 Uint64;
} DEBUG_AGENT_FLAG;
typedef struct {
@@ -93,9 +131,29 @@ typedef struct {
// Pointer to DEBUG_AGENT_EXCEPTION_BUFFER
//
UINT64 ExceptionBufferPointer;
+ UINT8 LastAck; // The last ack packet type
+ UINT8 SequenceNo;
+ UINT8 HostSequenceNo;
+ UINT8 CheckSum; // Mailbox checksum
+ UINT8 ToBeCheckSum; // To be Mailbox checksum at the next
} DEBUG_AGENT_MAILBOX;
#pragma pack()
+///
+/// Byte packed structure for an IA-32 Interrupt Gate Descriptor.
+///
+typedef union {
+ struct {
+ UINT32 OffsetLow:16; ///< Offset bits 15..0.
+ UINT32 Selector:16; ///< Selector.
+ UINT32 Reserved_0:8; ///< Reserved.
+ UINT32 GateType:8; ///< Gate Type. See #defines above.
+ UINT32 OffsetHigh:16; ///< Offset bits 31..16.
+ } Bits;
+ UINT64 Uint64;
+} IA32_IDT_ENTRY;
+
+
typedef union {
struct {
UINT32 LimitLow : 16;
@@ -116,22 +174,6 @@ typedef union {
} IA32_GDT;
/**
- Caller provided function to be invoked at the end of DebugPortInitialize().
-
- Refer to the descrption for DebugPortInitialize() for more details.
-
- @param[in] Context The first input argument of DebugPortInitialize().
- @param[in] DebugPortHandle Debug port handle created by Debug Communication Libary.
-
-**/
-VOID
-EFIAPI
-InitializeDebugAgentPhase2 (
- IN VOID *Context,
- IN DEBUG_PORT_HANDLE DebugPortHandle
- );
-
-/**
Initialize IDT entries to support source level debug.
**/
@@ -242,5 +284,184 @@ DebugAgentMsgPrint (
IN CHAR8 *Format,
...
);
+
+/**
+ Trigger one software interrupt to debug agent to handle it.
+
+ @param[in] Signature Software interrupt signature.
+
+**/
+VOID
+TriggerSoftInterrupt (
+ IN UINT32 Signature
+ );
+
+/**
+ Check if debug agent support multi-processor.
+
+ @retval TRUE Multi-processor is supported.
+ @retval FALSE Multi-processor is not supported.
+
+**/
+BOOLEAN
+MultiProcessorDebugSupport (
+ VOID
+ );
+
+/**
+ Find and report module image info to HOST.
+
+ @param[in] AlignSize Image aligned size.
+
+**/
+VOID
+FindAndReportModuleImageInfo (
+ IN UINTN AlignSize
+ );
+
+/**
+ Read IDT entry to check if IDT entries are setup by Debug Agent.
+
+ @retval TRUE IDT entries were setup by Debug Agent.
+ @retval FALSE IDT entries were not setup by Debug Agent.
+
+**/
+BOOLEAN
+IsDebugAgentInitialzed (
+ VOID
+ );
+
+/**
+ Caculate Mailbox checksum and update the checksum field.
+
+ @param[in] Mailbox Debug Agent Mailbox pointer.
+
+**/
+VOID
+UpdateMailboxChecksum (
+ IN DEBUG_AGENT_MAILBOX *Mailbox
+ );
+
+/**
+ Verify Mailbox checksum.
+
+ If checksum error, print debug message and run init dead loop.
+
+ @param[in] Mailbox Debug Agent Mailbox pointer.
+
+**/
+VOID
+VerifyMailboxChecksum (
+ IN DEBUG_AGENT_MAILBOX *Mailbox
+ );
+
+/**
+ Set debug flag in mailbox.
+
+ @param[in] FlagMask Debug flag mask value.
+ @param[in] FlagValue Debug flag value.
+
+**/
+VOID
+SetDebugFlag (
+ IN UINT64 FlagMask,
+ IN UINT32 FlagValue
+ );
+
+/**
+ Get debug flag in mailbox.
+
+ @param[in] FlagMask Debug flag mask value.
+
+ @return Debug flag value.
+
+**/
+UINT32
+GetDebugFlag (
+ IN UINT64 FlagMask
+ );
+
+/**
+ Update Mailbox content by index.
+
+ @param[in] Mailbox Debug Agent Mailbox pointer.
+ @param[in] Index Mailbox content index.
+ @param[in] Value Value to be set into mail box.
+
+**/
+VOID
+UpdateMailboxContent (
+ IN DEBUG_AGENT_MAILBOX *Mailbox,
+ IN UINTN Index,
+ IN UINT64 Value
+ );
+
+/**
+ Retrieve exception handler from IDT table by ExceptionNum.
+
+ @param[in] ExceptionNum Exception number
+
+ @return Exception handler
+
+**/
+VOID *
+GetExceptionHandlerInIdtEntry (
+ IN UINTN ExceptionNum
+ );
+
+/**
+ Set exception handler in IDT table by ExceptionNum.
+
+ @param[in] ExceptionNum Exception number
+ @param[in] ExceptionHandler Exception Handler to be set
+
+**/
+VOID
+SetExceptionHandlerInIdtEntry (
+ IN UINTN ExceptionNum,
+ IN VOID *ExceptionHandler
+ );
+
+/**
+ Prints a debug message to the debug output device if the specified error level is enabled.
+
+ If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function
+ GetDebugPrintErrorLevel (), then print the message specified by Format and the
+ associated variable argument list to the debug output device.
+
+ If Format is NULL, then ASSERT().
+
+ @param[in] ErrorLevel The error level of the debug message.
+ @param[in] IsSend Flag of debug message to declare that the data is being sent or being received.
+ @param[in] Data Variable argument list whose contents are accessed
+ @param[in] Length based on the format string specified by Format.
+
+**/
+VOID
+EFIAPI
+DebugAgentDataMsgPrint (
+ IN UINT8 ErrorLevel,
+ IN BOOLEAN IsSend,
+ IN UINT8 *Data,
+ IN UINT8 Length
+ );
+
+/**
+ Read remaing debug packet except for the start symbol
+
+ @param[in] Handle Pointer to Debug Port handle.
+ @param[in, out] DebugHeader Debug header buffer including start symbol.
+
+ @retval EFI_SUCCESS Read the symbol in BreakSymbol.
+ @retval EFI_CRC_ERROR CRC check fail.
+ @retval EFI_TIMEOUT Timeout occurs when reading debug packet.
+
+**/
+EFI_STATUS
+ReadRemainingBreakPacket (
+ IN DEBUG_PORT_HANDLE Handle,
+ IN OUT DEBUG_PACKET_HEADER *DebugHeader
+ );
+
#endif
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.c
index d7df6ad20..6c729986c 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.c
@@ -1,7 +1,7 @@
/** @file
Multi-Processor support functions implementation.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -14,27 +14,30 @@
#include "DebugAgent.h"
-DEBUG_MP_CONTEXT volatile mDebugMpContext = {0,0,{0},{0},0,0,0,0,FALSE,FALSE};
+DEBUG_MP_CONTEXT volatile mDebugMpContext = {0,0,0,{0},{0},0,0,0,0,FALSE,FALSE};
DEBUG_CPU_DATA volatile mDebugCpuData = {0};
/**
- Acquire access control on debug port.
+ Acquire a spin lock when Multi-processor supported.
It will block in the function if cannot get the access control.
+ If Multi-processor is not supported, return directly.
+
+ @param[in, out] MpSpinLock A pointer to the spin lock.
**/
VOID
-AcquireDebugPortControl (
- VOID
+AcquireMpSpinLock (
+ IN OUT SPIN_LOCK *MpSpinLock
)
{
- if (!MultiProcessorDebugSupport) {
+ if (!MultiProcessorDebugSupport()) {
return;
}
while (TRUE) {
- if (AcquireSpinLockOrFail (&mDebugMpContext.DebugPortSpinLock)) {
+ if (AcquireSpinLockOrFail (MpSpinLock)) {
break;
}
CpuPause ();
@@ -43,51 +46,21 @@ AcquireDebugPortControl (
}
/**
- Release access control on debug port.
-
-**/
-VOID
-ReleaseDebugPortControl (
- VOID
- )
-{
- if (!MultiProcessorDebugSupport) {
- return;
- }
-
- ReleaseSpinLock (&mDebugMpContext.DebugPortSpinLock);
-}
-
-/**
- Acquire access control on MP context.
+ Release a spin lock when Multi-processor supported.
- It will block in the function if cannot get the access control.
+ @param[in, out] MpSpinLock A pointer to the spin lock.
**/
VOID
-AcquireMpContextControl (
- VOID
+ReleaseMpSpinLock (
+ IN OUT SPIN_LOCK *MpSpinLock
)
{
- while (TRUE) {
- if (AcquireSpinLockOrFail (&mDebugMpContext.MpContextSpinLock)) {
- break;
- }
- CpuPause ();
- continue;
+ if (!MultiProcessorDebugSupport()) {
+ return;
}
-}
-/**
- Release access control on MP context.
-
-**/
-VOID
-ReleaseMpContextControl (
- VOID
- )
-{
- ReleaseSpinLock (&mDebugMpContext.MpContextSpinLock);
+ ReleaseSpinLock (MpSpinLock);
}
/**
@@ -136,7 +109,7 @@ GetProcessorIndex (
LocalApicID = (UINT16) GetApicId ();
- AcquireMpContextControl ();
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
for (Index = 0; Index < mDebugCpuData.CpuCount; Index ++) {
if (mDebugCpuData.ApicID[Index] == LocalApicID) {
@@ -149,7 +122,7 @@ GetProcessorIndex (
mDebugCpuData.CpuCount ++ ;
}
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
return Index;
}
@@ -170,9 +143,9 @@ IsBsp (
{
if (AsmMsrBitFieldRead64 (MSR_IA32_APIC_BASE_ADDRESS, 8, 8) == 1) {
if (mDebugMpContext.BspIndex != ProcessorIndex) {
- AcquireMpContextControl ();
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
mDebugMpContext.BspIndex = ProcessorIndex;
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
}
return TRUE;
} else {
@@ -197,7 +170,7 @@ SetCpuStopFlagByIndex (
UINT8 Value;
UINTN Index;
- AcquireMpContextControl ();
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
Value = mDebugMpContext.CpuStopStatusMask[ProcessorIndex / 8];
Index = ProcessorIndex % 8;
@@ -208,7 +181,7 @@ SetCpuStopFlagByIndex (
}
mDebugMpContext.CpuStopStatusMask[ProcessorIndex / 8] = Value;
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
}
/**
@@ -228,7 +201,7 @@ SetCpuBreakFlagByIndex (
UINT8 Value;
UINTN Index;
- AcquireMpContextControl ();
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
Value = mDebugMpContext.CpuBreakMask[ProcessorIndex / 8];
Index = ProcessorIndex % 8;
@@ -239,7 +212,7 @@ SetCpuBreakFlagByIndex (
}
mDebugMpContext.CpuBreakMask[ProcessorIndex / 8] = Value;
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
}
/**
@@ -279,11 +252,9 @@ SetCpuRunningFlag (
IN BOOLEAN RunningFlag
)
{
- AcquireMpContextControl ();
-
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
mDebugMpContext.RunCommandSet = RunningFlag;
-
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
}
/**
@@ -297,11 +268,9 @@ SetDebugViewPoint (
IN UINT32 ProcessorIndex
)
{
- AcquireMpContextControl ();
-
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
mDebugMpContext.ViewPointIndex = ProcessorIndex;
-
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
}
/**
@@ -316,11 +285,9 @@ SetIpiSentByApFlag (
IN BOOLEAN IpiSentByApFlag
)
{
- AcquireMpContextControl ();
-
+ AcquireMpSpinLock (&mDebugMpContext.MpContextSpinLock);
mDebugMpContext.IpiSentByAp = IpiSentByApFlag;
-
- ReleaseMpContextControl ();
+ ReleaseMpSpinLock (&mDebugMpContext.MpContextSpinLock);
}
/**
@@ -384,7 +351,7 @@ IsFirstBreakProcessor (
IN UINT32 ProcessorIndex
)
{
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
if (mDebugMpContext.BreakAtCpuIndex != (UINT32) -1) {
//
// The current processor is not the first breaking one.
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.h b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.h
index 183887cc9..5bb50960c 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.h
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugMp.h
@@ -1,7 +1,7 @@
/** @file
Header file for Multi-Processor support.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -25,6 +25,7 @@ typedef struct {
typedef struct {
SPIN_LOCK MpContextSpinLock; ///< Lock for writting MP context
SPIN_LOCK DebugPortSpinLock; ///< Lock for access debug port
+ SPIN_LOCK MailboxSpinLock; ///< Lock for accessing mail box
UINT8 CpuBreakMask[DEBUG_CPU_MAX_COUNT/8]; ///< Bitmask of all breaking CPUs
UINT8 CpuStopStatusMask[DEBUG_CPU_MAX_COUNT/8]; ///< Bitmask of CPU stop status
UINT32 ViewPointIndex; ///< Current view point to be debugged
@@ -35,7 +36,6 @@ typedef struct {
BOOLEAN RunCommandSet; ///< TRUE: RUN commmand is executing. FALSE : RUN command has been executed.
} DEBUG_MP_CONTEXT;
-extern CONST BOOLEAN MultiProcessorDebugSupport;
extern DEBUG_MP_CONTEXT volatile mDebugMpContext;
extern DEBUG_CPU_DATA volatile mDebugCpuData;
@@ -62,43 +62,28 @@ GetProcessorIndex (
);
/**
- Acquire access control on MP context.
+ Acquire a spin lock when Multi-processor supported.
It will block in the function if cannot get the access control.
+ If Multi-processor is not supported, return directly.
-**/
-VOID
-AcquireMpContextControl (
- VOID
- );
-
-/**
- Release access control on MP context.
+ @param[in, out] MpSpinLock A pointer to the spin lock.
**/
VOID
-ReleaseMpContextControl (
- VOID
+AcquireMpSpinLock (
+ IN OUT SPIN_LOCK *MpSpinLock
);
/**
- Acquire access control on debug port.
-
- It will block in the function if cannot get the access control.
-
-**/
-VOID
-AcquireDebugPortControl (
- VOID
- );
+ Release a spin lock when Multi-processor supported.
-/**
- Release access control on debug port.
+ @param[in, out] MpSpinLock A pointer to the spin lock.
**/
VOID
-ReleaseDebugPortControl (
- VOID
+ReleaseMpSpinLock (
+ IN OUT SPIN_LOCK *MpSpinLock
);
/**
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugTimer.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugTimer.c
index d473df867..01fc4841f 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugTimer.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugTimer.c
@@ -1,7 +1,7 @@
/** @file
Code for debug timer to support debug agent library implementation.
- Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -41,7 +41,7 @@ InitializeDebugTimer (
InitializeApicTimer (ApicTimerDivisor, InitialCount, TRUE, DEBUG_TIMER_VECTOR);
- if (MultiProcessorDebugSupport) {
+ if (MultiProcessorDebugSupport()) {
mDebugMpContext.DebugTimerInitCount = InitialCount;
}
}
@@ -65,19 +65,26 @@ SaveAndSetDebugTimerInterrupt (
IN BOOLEAN EnableStatus
)
{
- BOOLEAN OldInterruptState;
BOOLEAN OldDebugTimerInterruptState;
- OldInterruptState = SaveAndDisableInterrupts ();
OldDebugTimerInterruptState = GetApicTimerInterruptState ();
- if (EnableStatus) {
- EnableApicTimerInterrupt ();
- } else {
- DisableApicTimerInterrupt ();
+ if (OldDebugTimerInterruptState != EnableStatus) {
+ if (EnableStatus) {
+ EnableApicTimerInterrupt ();
+ } else {
+ DisableApicTimerInterrupt ();
+ }
+ //
+ // Validate the Debug Timer interrupt state
+ // This will make additional delay after Local Apic Timer interrupt state is changed.
+ // Thus, CPU could handle the potential pending interrupt of Local Apic timer.
+ //
+ while (GetApicTimerInterruptState () != EnableStatus) {
+ CpuPause ();
+ }
}
-
- SetInterruptState (OldInterruptState);
+
return OldDebugTimerInterruptState;
}
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/ArchDebugSupport.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/ArchDebugSupport.c
index 52ed647a2..9bd8fca6b 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/ArchDebugSupport.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/ArchDebugSupport.c
@@ -1,7 +1,7 @@
/** @file
Supporting functions for IA32 architecture.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -39,17 +39,17 @@ InitializeDebugIdt (
IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
for (Index = 0; Index < 20; Index ++) {
- if ((PcdGet32 (PcdExceptionsIgnoredByDebugger) & (1 << Index)) != 0) {
+ if (((PcdGet32 (PcdExceptionsIgnoredByDebugger) & ~(BIT1 | BIT3)) & (1 << Index)) != 0) {
//
- // If the exception is masked to be reserved, skip it
+ // If the exception is masked to be reserved except for INT1 and INT3, skip it
//
continue;
}
InterruptHandler = (UINTN)&Exception0Handle + Index * ExceptionStubHeaderSize;
IdtEntry[Index].Bits.OffsetLow = (UINT16)(UINTN)InterruptHandler;
IdtEntry[Index].Bits.OffsetHigh = (UINT16)((UINTN)InterruptHandler >> 16);
- IdtEntry[Index].Bits.Selector = CodeSegment;
- IdtEntry[Index].Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
+ IdtEntry[Index].Bits.Selector = CodeSegment;
+ IdtEntry[Index].Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
}
InterruptHandler = (UINTN) &TimerInterruptHandle;
@@ -63,3 +63,49 @@ InitializeDebugIdt (
//
AsmWriteCr4 (AsmReadCr4 () | BIT3);
}
+
+/**
+ Retrieve exception handler from IDT table by ExceptionNum.
+
+ @param[in] ExceptionNum Exception number
+
+ @return Exception handler
+
+**/
+VOID *
+GetExceptionHandlerInIdtEntry (
+ IN UINTN ExceptionNum
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ IA32_DESCRIPTOR IdtDescriptor;
+
+ AsmReadIdtr (&IdtDescriptor);
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
+
+ return (VOID *) (((UINTN)IdtEntry[ExceptionNum].Bits.OffsetLow) |
+ (((UINTN)IdtEntry[ExceptionNum].Bits.OffsetHigh) << 16));
+}
+
+/**
+ Set exception handler in IDT table by ExceptionNum.
+
+ @param[in] ExceptionNum Exception number
+ @param[in] ExceptionHandler Exception Handler to be set
+
+**/
+VOID
+SetExceptionHandlerInIdtEntry (
+ IN UINTN ExceptionNum,
+ IN VOID *ExceptionHandler
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ IA32_DESCRIPTOR IdtDescriptor;
+
+ AsmReadIdtr (&IdtDescriptor);
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
+
+ IdtEntry[ExceptionNum].Bits.OffsetLow = (UINT16)(UINTN)ExceptionHandler;
+ IdtEntry[ExceptionNum].Bits.OffsetHigh = (UINT16)((UINTN)ExceptionHandler >> 16);
+}
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.S b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.S
index cfeeea047..e05317aaf 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.S
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.S
@@ -1,6 +1,6 @@
#------------------------------------------------------------------------------
#
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
@@ -33,6 +33,7 @@ ASM_PFX(ExceptionStubHeaderSize): .word ASM_PFX(Exception1Handle) - ASM_PFX
.text
+.byte 0x41, 0x47, 0x54, 0x48 # AGENT_HANDLER_SIGNATURE SIGNATURE_32('A','G','T','H')
ASM_PFX(Exception0Handle):
cli
pushl %eax
@@ -259,7 +260,7 @@ NoExtrPush:
pushl %eax
## clear Dr7 while executing debugger itself
xorl %eax,%eax
-# movl %eax, %dr7
+ movl %eax, %dr7
movl %dr6, %eax
pushl %eax
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.asm b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.asm
index 6f3b3bc3d..c80a33ba6 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.asm
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/Ia32/AsmFuncs.asm
@@ -1,6 +1,6 @@
;------------------------------------------------------------------------------
;
-; Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
@@ -39,6 +39,7 @@ CommonEntryAddr DD CommonEntry
.code
+db 41h, 47h, 54h, 48h ; AGENT_HANDLER_SIGNATURE SIGNATURE_32('A','G','T','H')
Exception0Handle:
cli
push eax
@@ -259,7 +260,7 @@ NoExtrPush:
;; clear Dr7 while executing debugger itself
xor eax, eax
- ;; mov dr7, eax
+ mov dr7, eax
;; Dr6
mov eax, dr6
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/ArchDebugSupport.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/ArchDebugSupport.c
index 9803f0f76..60d3eb8bb 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/ArchDebugSupport.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/ArchDebugSupport.c
@@ -1,7 +1,7 @@
/** @file
Supporting functions for X64 architecture.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -39,9 +39,9 @@ InitializeDebugIdt (
IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
for (Index = 0; Index < 20; Index ++) {
- if ((PcdGet32 (PcdExceptionsIgnoredByDebugger) & (1 << Index)) != 0) {
+ if (((PcdGet32 (PcdExceptionsIgnoredByDebugger) & ~(BIT1 | BIT3)) & (1 << Index)) != 0) {
//
- // If the exception is masked to be reserved, skip it
+ // If the exception is masked to be reserved except for INT1 and INT3, skip it
//
continue;
}
@@ -65,3 +65,51 @@ InitializeDebugIdt (
//
AsmWriteCr4 (AsmReadCr4 () | BIT3);
}
+
+/**
+ Retrieve exception handler from IDT table by ExceptionNum.
+
+ @param[in] ExceptionNum Exception number
+
+ @return Exception handler
+
+**/
+VOID *
+GetExceptionHandlerInIdtEntry (
+ IN UINTN ExceptionNum
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ IA32_DESCRIPTOR IdtDescriptor;
+
+ AsmReadIdtr (&IdtDescriptor);
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
+
+ return (VOID *) (IdtEntry[ExceptionNum].Bits.OffsetLow |
+ (((UINTN)IdtEntry[ExceptionNum].Bits.OffsetHigh) << 16) |
+ (((UINTN)IdtEntry[ExceptionNum].Bits.OffsetUpper) << 32));
+}
+
+/**
+ Set exception handler in IDT table by ExceptionNum.
+
+ @param[in] ExceptionNum Exception number
+ @param[in] ExceptionHandler Exception Handler to be set
+
+**/
+VOID
+SetExceptionHandlerInIdtEntry (
+ IN UINTN ExceptionNum,
+ IN VOID *ExceptionHandler
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ IA32_DESCRIPTOR IdtDescriptor;
+
+ AsmReadIdtr (&IdtDescriptor);
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
+
+ IdtEntry[ExceptionNum].Bits.OffsetLow = (UINT16)(UINTN)ExceptionHandler;
+ IdtEntry[ExceptionNum].Bits.OffsetHigh = (UINT16)((UINTN)ExceptionHandler >> 16);
+ IdtEntry[ExceptionNum].Bits.OffsetUpper = (UINT32)((UINTN)ExceptionHandler >> 32);
+}
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.S b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.S
index 3de9767db..e7c3ed746 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.S
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.S
@@ -1,6 +1,6 @@
#------------------------------------------------------------------------------
#
-# Copyright (c) 2006 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
@@ -35,6 +35,7 @@ ASM_PFX(ExceptionStubHeaderSize): .word ASM_PFX(Exception1Handle) - ASM_PFX
.text
+.byte 0x41, 0x47, 0x54, 0x48 # AGENT_HANDLER_SIGNATURE SIGNATURE_32('A','G','T','H')
ASM_PFX(Exception0Handle):
cli
pushq %rcx
@@ -280,7 +281,7 @@ NoExtrPush:
pushq %rax
## clear Dr7 while executing debugger itself
xorq %rax, %rax
-#debug movq %rax, %dr7
+ movq %rax, %dr7
movq %dr6, %rax
pushq %rax
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.asm b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.asm
index 16d73a412..23abcc762 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.asm
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/X64/AsmFuncs.asm
@@ -1,6 +1,6 @@
;------------------------------------------------------------------------------
;
-; Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
@@ -33,6 +33,7 @@ CommonEntryAddr dq CommonEntry ;
.code
+db 41h, 47h, 54h, 48h ; AGENT_HANDLER_SIGNATURE SIGNATURE_32('A','G','T','H')
Exception0Handle:
cli
push rcx
@@ -198,7 +199,7 @@ NoExtrPush:
push rax
mov rax, cr2
push rax
- push 0 ; cr0 will not saved???
+ push 0
mov rax, cr0
push rax
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.c b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.c
index f8e3f6c1a..35c6acfd9 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.c
@@ -1,7 +1,7 @@
/** @file
Debug Agent library implementition for Dxe Core and Dxr modules.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -15,57 +15,51 @@
#include "DxeDebugAgentLib.h"
DEBUG_AGENT_MAILBOX mMailbox;
-DEBUG_AGENT_MAILBOX *mMailboxPointer;
+DEBUG_AGENT_MAILBOX *mMailboxPointer = NULL;
IA32_IDT_GATE_DESCRIPTOR mIdtEntryTable[33];
-BOOLEAN mDxeCoreFlag = FALSE;
-CONST BOOLEAN MultiProcessorDebugSupport = TRUE;
+BOOLEAN mDxeCoreFlag = FALSE;
+BOOLEAN mMultiProcessorDebugSupport = FALSE;
+VOID *mSavedIdtTable = NULL;
+UINTN mSaveIdtTableSize = 0;
+BOOLEAN mDebugAgentInitialized = FALSE;
+BOOLEAN mSkipBreakpoint = FALSE;
/**
- Constructor allocates the NVS memory to store Mailbox and install configuration table
- in system table to store its pointer.
+ Check if debug agent support multi-processor.
- @param[in] ImageHandle The firmware allocated handle for the EFI image.
- @param[in] SystemTable A pointer to the EFI System Table.
+ @retval TRUE Multi-processor is supported.
+ @retval FALSE Multi-processor is not supported.
+
+**/
+BOOLEAN
+MultiProcessorDebugSupport (
+ VOID
+ )
+{
+ return mMultiProcessorDebugSupport;
+}
- @retval RETURN_SUCCESS Allocate the global memory space to store guid and function tables.
+/**
+ Internal constructor worker function.
+
+ It will register one callback function on EFI PCD Protocol.
+ It will allocate the NVS memory to store Mailbox and install configuration table
+ in system table to store its pointer.
**/
-RETURN_STATUS
-EFIAPI
-DxeDebugAgentLibConstructor (
- IN EFI_HANDLE ImageHandle,
- IN EFI_SYSTEM_TABLE *SystemTable
+VOID
+InternalConstructorWorker (
+ VOID
)
{
EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS Address;
- EFI_EVENT Event;
- VOID *EventRegistration;
-
- if (!mDxeCoreFlag) {
- return RETURN_SUCCESS;
- }
-
- Status = gBS->CreateEvent (
- EVT_NOTIFY_SIGNAL,
- TPL_CALLBACK,
- InstallSerialIoNotification,
- NULL,
- &Event
- );
- ASSERT_EFI_ERROR (Status);
+ BOOLEAN DebugTimerInterruptState;
//
- // Register for protocol notifications on this event
+ // Install EFI Serial IO protocol on debug port
//
-
- Status = gBS->RegisterProtocolNotify (
- &gEfiPcdProtocolGuid,
- Event,
- &EventRegistration
- );
-
- ASSERT_EFI_ERROR (Status);
+ InstallSerialIo ();
Address = 0;
Status = gBS->AllocatePages (
@@ -76,18 +70,67 @@ DxeDebugAgentLibConstructor (
);
ASSERT_EFI_ERROR (Status);
+ DebugTimerInterruptState = SaveAndSetDebugTimerInterrupt (FALSE);
CopyMem (
(UINT8 *) (UINTN) Address,
- (UINT8 *) (UINTN) mMailboxPointer,
+ (UINT8 *) (UINTN) GetMailboxPointer (),
sizeof (DEBUG_AGENT_MAILBOX)
);
+ DebugTimerInterruptState = SaveAndSetDebugTimerInterrupt (DebugTimerInterruptState);
mMailboxPointer = (DEBUG_AGENT_MAILBOX *) (UINTN) Address;
Status = gBS->InstallConfigurationTable (&gEfiDebugAgentGuid, (VOID *) mMailboxPointer);
ASSERT_EFI_ERROR (Status);
+}
+
+/**
+ Debug Agent constructor function.
+
+ @param[in] ImageHandle The firmware allocated handle for the EFI image.
+ @param[in] SystemTable A pointer to the EFI System Table.
+
+ @retval RETURN_SUCCESS When this function completed.
+
+**/
+RETURN_STATUS
+EFIAPI
+DxeDebugAgentLibConstructor (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ if (mDxeCoreFlag) {
+ //
+ // Invoke internal constructor function only when DXE core links this library instance
+ //
+ InternalConstructorWorker ();
+ }
+
+ return RETURN_SUCCESS;
+}
+
+/**
+ Get the pointer to Mailbox from the configuration table.
+
+ @return Pointer to Mailbox.
+
+**/
+DEBUG_AGENT_MAILBOX *
+GetMailboxFromConfigurationTable (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ DEBUG_AGENT_MAILBOX *Mailbox;
- return Status;
+ Status = EfiGetSystemConfigurationTable (&gEfiDebugAgentGuid, (VOID **) &Mailbox);
+ if (Status == EFI_SUCCESS && Mailbox != NULL) {
+ VerifyMailboxChecksum (Mailbox);
+ return Mailbox;
+ } else {
+ return NULL;
+ }
}
/**
@@ -104,13 +147,18 @@ GetMailboxFromHob (
)
{
EFI_HOB_GUID_TYPE *GuidHob;
+ UINT64 *MailboxLocation;
+ DEBUG_AGENT_MAILBOX *Mailbox;
GuidHob = GetNextGuidHob (&gEfiDebugAgentGuid, HobStart);
if (GuidHob == NULL) {
return NULL;
}
+ MailboxLocation = (UINT64 *) (GET_GUID_HOB_DATA(GuidHob));
+ Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocation);
+ VerifyMailboxChecksum (Mailbox);
- return (DEBUG_AGENT_MAILBOX *) (GET_GUID_HOB_DATA(GuidHob));
+ return Mailbox;
}
/**
@@ -124,6 +172,9 @@ GetMailboxPointer (
VOID
)
{
+ AcquireMpSpinLock (&mDebugMpContext.MailboxSpinLock);
+ VerifyMailboxChecksum (mMailboxPointer);
+ ReleaseMpSpinLock (&mDebugMpContext.MailboxSpinLock);
return mMailboxPointer;
}
@@ -138,10 +189,86 @@ GetDebugPortHandle (
VOID
)
{
- return (DEBUG_PORT_HANDLE) (UINTN)(mMailboxPointer->DebugPortHandle);
+ return (DEBUG_PORT_HANDLE) (UINTN)(GetMailboxPointer ()->DebugPortHandle);
+}
+
+/**
+ Worker function to setup IDT table and initialize the IDT entries.
+
+ @param[in] Mailbox Pointer to Mailbox.
+
+**/
+VOID
+SetupDebugAgentEnviroment (
+ IN DEBUG_AGENT_MAILBOX *Mailbox
+ )
+{
+ IA32_DESCRIPTOR Idtr;
+ UINT16 IdtEntryCount;
+ UINT64 DebugPortHandle;
+
+ if (mMultiProcessorDebugSupport) {
+ InitializeSpinLock (&mDebugMpContext.MpContextSpinLock);
+ InitializeSpinLock (&mDebugMpContext.DebugPortSpinLock);
+ InitializeSpinLock (&mDebugMpContext.MailboxSpinLock);
+ //
+ // Clear Break CPU index value
+ //
+ mDebugMpContext.BreakAtCpuIndex = (UINT32) -1;
+ }
+
+ //
+ // Get original IDT address and size.
+ //
+ AsmReadIdtr ((IA32_DESCRIPTOR *) &Idtr);
+ IdtEntryCount = (UINT16) ((Idtr.Limit + 1) / sizeof (IA32_IDT_GATE_DESCRIPTOR));
+ if (IdtEntryCount < 33) {
+ Idtr.Limit = (UINT16) (sizeof (IA32_IDT_GATE_DESCRIPTOR) * 33 - 1);
+ Idtr.Base = (UINTN) &mIdtEntryTable;
+ ZeroMem (&mIdtEntryTable, Idtr.Limit + 1);
+ AsmWriteIdtr ((IA32_DESCRIPTOR *) &Idtr);
+ }
+
+ //
+ // Initialize the IDT table entries to support source level debug.
+ //
+ InitializeDebugIdt ();
+
+ if (Mailbox != NULL) {
+ //
+ // If Mailbox exists, copy it into one global variable,
+ //
+ CopyMem (&mMailbox, Mailbox, sizeof (DEBUG_AGENT_MAILBOX));
+ } else {
+ ZeroMem (&mMailbox, sizeof (DEBUG_AGENT_MAILBOX));
+ }
+
+ mMailboxPointer = &mMailbox;
+ //
+ // Initialize debug communication port
+ //
+ DebugPortHandle = (UINT64) (UINTN)DebugPortInitialize ((VOID *)(UINTN)mMailboxPointer->DebugPortHandle, NULL);
+ UpdateMailboxContent (mMailboxPointer, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);
+
+ if (Mailbox == NULL) {
+ //
+ // Trigger one software interrupt to inform HOST
+ //
+ TriggerSoftInterrupt (SYSTEM_RESET_SIGNATURE);
+ SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);
+ //
+ // Memory has been ready
+ //
+ if (IsHostAttached ()) {
+ //
+ // Trigger one software interrupt to inform HOST
+ //
+ TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);
+ }
+ }
}
-
+
/**
Initialize debug agent.
@@ -167,105 +294,207 @@ InitializeDebugAgent (
IN DEBUG_AGENT_CONTINUE Function OPTIONAL
)
{
+ UINT64 *MailboxLocation;
DEBUG_AGENT_MAILBOX *Mailbox;
- IA32_DESCRIPTOR Idtr;
- UINT16 IdtEntryCount;
BOOLEAN InterruptStatus;
+ VOID *HobList;
+ IA32_DESCRIPTOR IdtDescriptor;
+ IA32_DESCRIPTOR *Ia32Idtr;
+ IA32_IDT_ENTRY *Ia32IdtEntry;
- if (InitFlag != DEBUG_AGENT_INIT_DXE_CORE &&
- InitFlag != DEBUG_AGENT_INIT_S3 &&
- InitFlag != DEBUG_AGENT_INIT_DXE_AP) {
- return;
+ if (InitFlag == DEBUG_AGENT_INIT_DXE_AP) {
+ //
+ // Invoked by AP, enable interrupt to let AP could receive IPI from other processors
+ //
+ EnableInterrupts ();
+ return ;
}
+ //
+ // Disable Debug Timer interrupt
+ //
+ SaveAndSetDebugTimerInterrupt (FALSE);
//
// Save and disable original interrupt status
//
InterruptStatus = SaveAndDisableInterrupts ();
- if (InitFlag == DEBUG_AGENT_INIT_DXE_CORE) {
+ //
+ // Try to get mailbox firstly
+ //
+ HobList = NULL;
+ Mailbox = NULL;
+ MailboxLocation = NULL;
+
+ switch (InitFlag) {
+
+ case DEBUG_AGENT_INIT_DXE_LOAD:
//
- // Try to get Mailbox from GUIDed HOB.
+ // Check if Debug Agent has been initialized before
//
- mDxeCoreFlag = TRUE;
- Mailbox = GetMailboxFromHob (Context);
-
+ if (IsDebugAgentInitialzed ()) {
+ DEBUG ((EFI_D_INFO, "Debug Agent: The former agent will be overwritten by the new one!\n"));
+ }
+
+ mMultiProcessorDebugSupport = TRUE;
//
- // Clear Break CPU index value
+ // Save original IDT table
+ //
+ AsmReadIdtr (&IdtDescriptor);
+ mSaveIdtTableSize = IdtDescriptor.Limit + 1;
+ mSavedIdtTable = AllocateCopyPool (mSaveIdtTableSize, (VOID *) IdtDescriptor.Base);
+ //
+ // Initialize Debug Timer hardware
+ //
+ InitializeDebugTimer ();
+ //
+ // Check if Debug Agent initialized in DXE phase
+ //
+ Mailbox = GetMailboxFromConfigurationTable ();
+ if (Mailbox == NULL) {
+ //
+ // Try to get mailbox from GUIDed HOB build in PEI
+ //
+ HobList = GetHobList ();
+ Mailbox = GetMailboxFromHob (HobList);
+ }
+ //
+ // Set up IDT table and prepare for IDT entries
+ //
+ SetupDebugAgentEnviroment (Mailbox);
+ //
+ // For DEBUG_AGENT_INIT_S3, needn't to install configuration table and EFI Serial IO protocol
+ // For DEBUG_AGENT_INIT_DXE_CORE, InternalConstructorWorker() will invoked in Constructor()
+ //
+ InternalConstructorWorker ();
+ //
+ // Enable interrupt to receive Debug Timer interrupt
//
- mDebugMpContext.BreakAtCpuIndex = (UINT32) -1;
-
- } else if (InitFlag == DEBUG_AGENT_INIT_DXE_AP) {
-
EnableInterrupts ();
- return;
+ mDebugAgentInitialized = TRUE;
+ FindAndReportModuleImageInfo (SIZE_4KB);
+
+ *(EFI_STATUS *)Context = EFI_SUCCESS;
+
+ if (gST->ConOut != NULL) {
+ Print (L"Debug Agent: Initialized successfully!\r\n");
+ Print (L"If the Debug Port is serial port, please make sure this serial port isn't connected by ISA Serial driver\r\n");
+ Print (L"You could do the following steps to disconnect the serial port:\r\n");
+ Print (L"1: Shell> drivers\r\n");
+ Print (L" ...\r\n");
+ Print (L" V VERSION E G G #D #C DRIVER NAME IMAGE NAME\r\n");
+ Print (L" == ======== = = = == == =================================== ===================\r\n");
+ Print (L" 8F 0000000A B - - 1 14 PCI Bus Driver PciBusDxe\r\n");
+ Print (L" 91 00000010 ? - - - - ATA Bus Driver AtaBusDxe\r\n");
+ Print (L" ...\r\n");
+ Print (L" A7 0000000A B - - 1 1 ISA Serial Driver IsaSerialDxe\r\n");
+ Print (L" ...\r\n");
+ Print (L"2: Shell> dh -d A7\r\n");
+ Print (L" A7: Image(IsaSerialDxe) ImageDevPath (..9FB3-11D4-9A3A-0090273FC14D))DriverBinding ComponentName ComponentName2\r\n");
+ Print (L" Driver Name : ISA Serial Driver\r\n");
+ Print (L" Image Name : FvFile(93B80003-9FB3-11D4-9A3A-0090273FC14D)\r\n");
+ Print (L" Driver Version : 0000000A\r\n");
+ Print (L" Driver Type : BUS\r\n");
+ Print (L" Configuration : NO\r\n");
+ Print (L" Diagnostics : NO\r\n");
+ Print (L" Managing :\r\n");
+ Print (L" Ctrl[EA] : PciRoot(0x0)/Pci(0x1F,0x0)/Serial(0x0)\r\n");
+ Print (L" Child[EB] : PciRoot(0x0)/Pci(0x1F,0x0)/Serial(0x0)/Uart(115200,8,N,1)\r\n");
+ Print (L"3: Shell> disconnect EA\r\n");
+ Print (L"4: Shell> load -nc DebugAgentDxe.efi\r\n\r\n");
+ }
+ break;
+
+ case DEBUG_AGENT_INIT_DXE_UNLOAD:
+ if (mDebugAgentInitialized) {
+ if (IsHostAttached ()) {
+ Print (L"Debug Agent: Host is still connected, please de-attach TARGET firstly!\r\n");
+ *(EFI_STATUS *)Context = EFI_ACCESS_DENIED;
+ //
+ // Enable Debug Timer interrupt again
+ //
+ SaveAndSetDebugTimerInterrupt (TRUE);
+ } else {
+ //
+ // Restore original IDT table
+ //
+ AsmReadIdtr (&IdtDescriptor);
+ IdtDescriptor.Limit = (UINT16) (mSaveIdtTableSize - 1);
+ CopyMem ((VOID *) IdtDescriptor.Base, mSavedIdtTable, mSaveIdtTableSize);
+ AsmWriteIdtr (&IdtDescriptor);
+ FreePool (mSavedIdtTable);
+ mDebugAgentInitialized = FALSE;
+ *(EFI_STATUS *)Context = EFI_SUCCESS;
+ }
+ } else {
+ Print (L"Debug Agent: It hasn't been initialized, cannot unload it!\r\n");
+ *(EFI_STATUS *)Context = EFI_NOT_STARTED;
+ }
- } else {
//
- // If it is in S3 path, needn't to install configuration table.
+ // Restore interrupt state.
//
- Mailbox = NULL;
- }
+ SetInterruptState (InterruptStatus);
+ break;
- if (Mailbox != NULL) {
+ case DEBUG_AGENT_INIT_DXE_CORE:
+ mDxeCoreFlag = TRUE;
+ mMultiProcessorDebugSupport = TRUE;
//
- // If Mailbox exists, copy it into one global variable.
+ // Initialize Debug Timer hardware
//
- CopyMem (&mMailbox, Mailbox, sizeof (DEBUG_AGENT_MAILBOX));
- } else {
+ InitializeDebugTimer ();
//
- // If Mailbox not exists, used the local Mailbox.
+ // Try to get mailbox from GUIDed HOB build in PEI
//
- ZeroMem (&mMailbox, sizeof (DEBUG_AGENT_MAILBOX));
- }
-
- mMailboxPointer = &mMailbox;
-
- //
- // Get original IDT address and size.
- //
- AsmReadIdtr ((IA32_DESCRIPTOR *) &Idtr);
- IdtEntryCount = (UINT16) ((Idtr.Limit + 1) / sizeof (IA32_IDT_GATE_DESCRIPTOR));
- if (IdtEntryCount < 33) {
- Idtr.Limit = (UINT16) (sizeof (IA32_IDT_GATE_DESCRIPTOR) * 33 - 1);
- Idtr.Base = (UINTN) &mIdtEntryTable;
- ZeroMem (&mIdtEntryTable, Idtr.Limit + 1);
- AsmWriteIdtr ((IA32_DESCRIPTOR *) &Idtr);
- }
+ HobList = Context;
+ Mailbox = GetMailboxFromHob (HobList);
+ //
+ // Set up IDT table and prepare for IDT entries
+ //
+ SetupDebugAgentEnviroment (Mailbox);
+ //
+ // Enable interrupt to receive Debug Timer interrupt
+ //
+ EnableInterrupts ();
- //
- // Initialize the IDT table entries to support source level debug.
- //
- InitializeDebugIdt ();
+ break;
- //
- // Initialize debug communication port
- //
- mMailboxPointer->DebugPortHandle = (UINT64) (UINTN)DebugPortInitialize ((VOID *)(UINTN)mMailbox.DebugPortHandle, NULL);
+ case DEBUG_AGENT_INIT_S3:
- InitializeSpinLock (&mDebugMpContext.MpContextSpinLock);
- InitializeSpinLock (&mDebugMpContext.DebugPortSpinLock);
-
- if (InitFlag == DEBUG_AGENT_INIT_DXE_CORE) {
+ if (Context != NULL) {
+ Ia32Idtr = (IA32_DESCRIPTOR *) Context;
+ Ia32IdtEntry = (IA32_IDT_ENTRY *)(Ia32Idtr->Base);
+ MailboxLocation = (UINT64 *) (UINTN) (Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow +
+ (Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh << 16));
+ Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocation);
+ VerifyMailboxChecksum (Mailbox);
+ }
//
- // Initialize Debug Timer hardware and enable interrupt.
+ // Set up IDT table and prepare for IDT entries
//
- InitializeDebugTimer ();
- EnableInterrupts ();
-
- return;
- } else {
+ SetupDebugAgentEnviroment (Mailbox);
//
- // Disable Debug Timer interrupt in S3 path.
+ // Disable interrupt
//
- SaveAndSetDebugTimerInterrupt (FALSE);
-
+ DisableInterrupts ();
+ FindAndReportModuleImageInfo (SIZE_4KB);
+ if (GetDebugFlag (DEBUG_AGENT_FLAG_BREAK_BOOT_SCRIPT) == 1) {
+ //
+ // If Boot Script entry break is set, code will be break at here.
+ //
+ CpuBreakpoint ();
+ }
+ break;
+
+ default:
//
- // Restore interrupt state.
+ // Only DEBUG_AGENT_INIT_PREMEM_SEC and DEBUG_AGENT_INIT_POSTMEM_SEC are allowed for this
+ // Debug Agent library instance.
//
- SetInterruptState (InterruptStatus);
+ DEBUG ((EFI_D_ERROR, "Debug Agent: The InitFlag value is not allowed!\n"));
+ CpuDeadLoop ();
+ break;
}
-
}
-
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.h b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.h
index ab561812c..536fb71dc 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.h
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/DxeDebugAgentLib.h
@@ -1,7 +1,7 @@
/** @file
Header file for Dxe Core Debug Agent Library instance.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -24,22 +24,17 @@
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/DevicePathLib.h>
+#include <Library/MemoryAllocationLib.h>
#include "DebugAgent.h"
/**
- Notification function on EFI PCD protocol to install EFI Serial IO protocol based
- on Debug Communication Library.
-
- @param[in] Event The event of notify protocol.
- @param[in] Context Notify event context.
+ Install EFI Serial IO protocol based on Debug Communication Library.
**/
VOID
-EFIAPI
-InstallSerialIoNotification (
- IN EFI_EVENT Event,
- IN VOID *Context
+InstallSerialIo (
+ VOID
);
#endif
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c
index 0cb7c5255..9b181e3ac 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c
@@ -1,7 +1,7 @@
/** @file
Install Serial IO Protocol that layers on top of a Debug Communication Library instance.
- Copyright (c) 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2012 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -149,11 +149,11 @@ SerialRead (
EFI_SERIAL_IO_MODE mSerialIoMode = {
SERIAL_PORT_DEFAULT_CONTROL_MASK,
SERIAL_PORT_DEFAULT_TIMEOUT,
- 0, // BaudRate
+ 0, // default BaudRate
SERIAL_PORT_DEFAULT_RECEIVE_FIFO_DEPTH,
- 0, // DataBits
- 0, // Parity
- 0 // StopBits
+ 0, // default DataBits
+ 0, // default Parity
+ 0 // default StopBits
};
//
@@ -204,10 +204,10 @@ SERIAL_IO_DEVICE_PATH mSerialIoDevicePath = {
}
},
0,
- 0, // BaudRate
- 0, // DataBits
- 0, // Parity
- 0, // StopBits
+ 0, // default BaudRate
+ 0, // default DataBits
+ 0, // default Parity
+ 0, // default StopBits
},
{
END_DEVICE_PATH_TYPE,
@@ -357,34 +357,15 @@ DebugTerminalFifoRemove (
}
/**
- Notification function on EFI PCD protocol to install EFI Serial IO protocol based
- on Debug Communication Library.
-
- @param[in] Event The event of notify protocol.
- @param[in] Context Notify event context.
+ Install EFI Serial IO protocol based on Debug Communication Library.
**/
VOID
-EFIAPI
-InstallSerialIoNotification (
- IN EFI_EVENT Event,
- IN VOID *Context
+InstallSerialIo (
+ VOID
)
{
- EFI_STATUS Status;
-
- //
- // Get Debug Port parameters from PCDs
- //
- mSerialIoDevicePath.UartDevicePath.BaudRate = PcdGet64 (PcdUartDefaultBaudRate);
- mSerialIoDevicePath.UartDevicePath.DataBits = PcdGet8 (PcdUartDefaultDataBits);
- mSerialIoDevicePath.UartDevicePath.Parity = PcdGet8 (PcdUartDefaultParity);
- mSerialIoDevicePath.UartDevicePath.StopBits = PcdGet8 (PcdUartDefaultStopBits);
-
- mSerialIoMode.BaudRate = mSerialIoDevicePath.UartDevicePath.BaudRate;
- mSerialIoMode.DataBits = mSerialIoDevicePath.UartDevicePath.DataBits;
- mSerialIoMode.Parity = mSerialIoDevicePath.UartDevicePath.Parity;
- mSerialIoMode.StopBits = mSerialIoDevicePath.UartDevicePath.StopBits;
+ EFI_STATUS Status;
Status = gBS->InstallMultipleProtocolInterfaces (
&mSerialIoHandle,
@@ -448,22 +429,10 @@ SerialSetAttributes (
)
{
//
- // The Debug Communication Library does not support changing communications parameters, so unless
- // the request is to use the default value or the value the Debug Communication Library is already
- // using, then return EFI_INVALID_PARAMETER.
+ // The Debug Communication Library CAN NOT change communications parameters (if it has)
+ // actually. Because it also has no any idea on what parameters are based on, we cannot
+ // check the input parameters (like BaudRate, Parity, DataBits and StopBits).
//
- if (BaudRate != 0 && BaudRate != PcdGet64 (PcdUartDefaultBaudRate)) {
- return EFI_INVALID_PARAMETER;
- }
- if (Parity != DefaultParity && Parity != PcdGet8 (PcdUartDefaultParity)) {
- return EFI_INVALID_PARAMETER;
- }
- if (DataBits != 0 && DataBits != PcdGet8 (PcdUartDefaultDataBits)) {
- return EFI_INVALID_PARAMETER;
- }
- if (StopBits != DefaultStopBits && StopBits != PcdGet8 (PcdUartDefaultStopBits)) {
- return EFI_INVALID_PARAMETER;
- }
//
// Update the Timeout value in the mode structure based on the request.
@@ -536,7 +505,18 @@ SerialGetControl (
)
{
DEBUG_PORT_HANDLE Handle;
+ BOOLEAN DebugTimerInterruptState;
+ EFI_TPL Tpl;
+ //
+ // Raise TPL to prevent recursion from EFI timer interrupts
+ //
+ Tpl = gBS->RaiseTPL (TPL_NOTIFY);
+
+ //
+ // Save and disable Debug Timer interrupt to avoid it to access Debug Port
+ //
+ DebugTimerInterruptState = SaveAndSetDebugTimerInterrupt (FALSE);
Handle = GetDebugPortHandle ();
//
@@ -552,6 +532,17 @@ SerialGetControl (
if (!IsDebugTermianlFifoEmpty (&mSerialFifoForTerminal) || DebugPortPollBuffer (Handle)) {
*Control &= ~EFI_SERIAL_INPUT_BUFFER_EMPTY;
}
+
+ //
+ // Restore Debug Timer interrupt
+ //
+ SaveAndSetDebugTimerInterrupt (DebugTimerInterruptState);
+
+ //
+ // Restore to original TPL
+ //
+ gBS->RestoreTPL (Tpl);
+
return EFI_SUCCESS;
}
@@ -577,7 +568,18 @@ SerialWrite (
)
{
DEBUG_PORT_HANDLE Handle;
+ BOOLEAN DebugTimerInterruptState;
+ EFI_TPL Tpl;
+ //
+ // Raise TPL to prevent recursion from EFI timer interrupts
+ //
+ Tpl = gBS->RaiseTPL (TPL_NOTIFY);
+
+ //
+ // Save and disable Debug Timer interrupt to avoid it to access Debug Port
+ //
+ DebugTimerInterruptState = SaveAndSetDebugTimerInterrupt (FALSE);
Handle = GetDebugPortHandle ();
if ((mSerialIoMode.ControlMask & EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE) != 0) {
@@ -593,6 +595,17 @@ SerialWrite (
} else {
*BufferSize = DebugPortWriteBuffer (Handle, Buffer, *BufferSize);
}
+
+ //
+ // Restore Debug Timer interrupt
+ //
+ SaveAndSetDebugTimerInterrupt (DebugTimerInterruptState);
+
+ //
+ // Restore to original TPL
+ //
+ gBS->RestoreTPL (Tpl);
+
return EFI_SUCCESS;
}
@@ -620,17 +633,24 @@ SerialRead (
EFI_STATUS Status;
UINTN Index;
UINT8 *Uint8Buffer;
- BOOLEAN OldInterruptState;
+ BOOLEAN DebugTimerInterruptState;
+ EFI_TPL Tpl;
DEBUG_PORT_HANDLE Handle;
- UINT8 Data;
-
- Handle = GetDebugPortHandle ();
+ DEBUG_PACKET_HEADER DebugHeader;
+ UINT8 *Data8;
//
- // Save and disable Debug Timer interrupt to avoid it to access Debug Port
+ // Raise TPL to prevent recursion from EFI timer interrupts
//
- OldInterruptState = SaveAndSetDebugTimerInterrupt (FALSE);
+ Tpl = gBS->RaiseTPL (TPL_NOTIFY);
+ //
+ // Save and disable Debug Timer interrupt to avoid it to access Debug Port
+ //
+ DebugTimerInterruptState = SaveAndSetDebugTimerInterrupt (FALSE);
+ Handle = GetDebugPortHandle ();
+
+ Data8 = (UINT8 *) &DebugHeader;
Uint8Buffer = (UINT8 *)Buffer;
if ((mSerialIoMode.ControlMask & EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE) != 0) {
if ((mLoopbackBuffer & SERIAL_PORT_LOOPBACK_BUFFER_FULL) == 0) {
@@ -644,9 +664,9 @@ SerialRead (
//
// Read input character from terminal FIFO firstly
//
- Status = DebugTerminalFifoRemove (&mSerialFifoForTerminal, &Data);
+ Status = DebugTerminalFifoRemove (&mSerialFifoForTerminal, Data8);
if (Status == EFI_SUCCESS) {
- *Uint8Buffer = Data;
+ *Uint8Buffer = *Data8;
Uint8Buffer ++;
continue;
}
@@ -656,16 +676,25 @@ SerialRead (
if (!DebugPortPollBuffer (Handle)) {
break;
}
- DebugPortReadBuffer (Handle, &Data, 1, 0);
+ DebugPortReadBuffer (Handle, Data8, 1, 0);
- if (Data== DEBUG_STARTING_SYMBOL_ATTACH ||
- Data == DEBUG_STARTING_SYMBOL_BREAK) {
+ if (*Data8 == DEBUG_STARTING_SYMBOL_ATTACH) {
//
// Add the debug symbol into Debug FIFO
//
- DebugTerminalFifoAdd (&mSerialFifoForDebug, Data);
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Terminal Timer attach symbol received %x", *Data8);
+ DebugTerminalFifoAdd (&mSerialFifoForDebug, *Data8);
+ } else if (*Data8 == DEBUG_STARTING_SYMBOL_NORMAL) {
+ Status = ReadRemainingBreakPacket (Handle, &DebugHeader);
+ if (Status == EFI_SUCCESS) {
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Terminal Timer break symbol received %x", DebugHeader.Command);
+ DebugTerminalFifoAdd (&mSerialFifoForDebug, DebugHeader.Command);
+ }
+ if (Status == EFI_TIMEOUT) {
+ continue;
+ }
} else {
- *Uint8Buffer = Data;
+ *Uint8Buffer = *Data8;
Uint8Buffer ++;
}
}
@@ -675,7 +704,12 @@ SerialRead (
//
// Restore Debug Timer interrupt
//
- SaveAndSetDebugTimerInterrupt (OldInterruptState);
+ SaveAndSetDebugTimerInterrupt (DebugTimerInterruptState);
+
+ //
+ // Restore to original TPL
+ //
+ gBS->RestoreTPL (Tpl);
return EFI_SUCCESS;
}
@@ -691,36 +725,90 @@ SerialRead (
**/
EFI_STATUS
-DebugReadBreakSymbol (
+DebugReadBreakFromDebugPort (
IN DEBUG_PORT_HANDLE Handle,
OUT UINT8 *BreakSymbol
)
{
- EFI_STATUS Status;
- UINT8 Data;
+ EFI_STATUS Status;
+ DEBUG_PACKET_HEADER DebugHeader;
+ UINT8 *Data8;
- Status = DebugTerminalFifoRemove (&mSerialFifoForDebug, &Data);
- if (Status != EFI_SUCCESS) {
+ *BreakSymbol = 0;
+ //
+ // If Debug Port buffer has data, read it till it was break symbol or Debug Port buffer empty.
+ //
+ Data8 = (UINT8 *) &DebugHeader;
+ while (TRUE) {
+ //
+ // If start symbol is not received
+ //
if (!DebugPortPollBuffer (Handle)) {
//
- // No data in Debug Port buffer.
+ // If no data in Debug Port, exit
//
- return EFI_NOT_FOUND;
+ break;
+ }
+ //
+ // Try to read the start symbol
+ //
+ DebugPortReadBuffer (Handle, Data8, 1, 0);
+ if (*Data8 == DEBUG_STARTING_SYMBOL_ATTACH) {
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Debug Timer attach symbol received %x", *Data8);
+ *BreakSymbol = *Data8;
+ return EFI_SUCCESS;
+ }
+ if (*Data8 == DEBUG_STARTING_SYMBOL_NORMAL) {
+ Status = ReadRemainingBreakPacket (Handle, &DebugHeader);
+ if (Status == EFI_SUCCESS) {
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Debug Timer break symbol received %x", DebugHeader.Command);
+ *BreakSymbol = DebugHeader.Command;
+ return EFI_SUCCESS;
+ }
+ if (Status == EFI_TIMEOUT) {
+ break;
+ }
} else {
//
- // Read one character from Debug Port.
+ // Add to Terminal FIFO
//
- DebugPortReadBuffer (Handle, &Data, 1, 0);
- if ((Data != DEBUG_STARTING_SYMBOL_ATTACH) && (Data != DEBUG_STARTING_SYMBOL_BREAK)) {
- //
- // If the data is not Break symbol, add it into Terminal FIFO
- //
- DebugTerminalFifoAdd (&mSerialFifoForTerminal, Data);
- return EFI_NOT_FOUND;
- }
+ DebugTerminalFifoAdd (&mSerialFifoForTerminal, *Data8);
}
}
- *BreakSymbol = Data;
- return EFI_SUCCESS;
+ return EFI_NOT_FOUND;
+}
+
+/**
+ Read the Attach/Break-in symbols.
+
+ @param[in] Handle Pointer to Debug Port handle.
+ @param[out] BreakSymbol Returned break symbol.
+
+ @retval EFI_SUCCESS Read the symbol in BreakSymbol.
+ @retval EFI_NOT_FOUND No read the break symbol.
+
+**/
+EFI_STATUS
+DebugReadBreakSymbol (
+ IN DEBUG_PORT_HANDLE Handle,
+ OUT UINT8 *BreakSymbol
+ )
+{
+ EFI_STATUS Status;
+ UINT8 Data8;
+
+ //
+ // Read break symbol from debug FIFO firstly
+ //
+ Status = DebugTerminalFifoRemove (&mSerialFifoForDebug, &Data8);
+ if (Status == EFI_SUCCESS) {
+ *BreakSymbol = Data8;
+ return EFI_SUCCESS;
+ } else {
+ //
+ // Read Break symbol from debug port
+ //
+ return DebugReadBreakFromDebugPort (Handle, BreakSymbol);
+ }
}
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
index 434d21a9f..f73385ce7 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
+++ b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
@@ -1,7 +1,7 @@
## @file
# Debug Agent library instance for Dxe Core and Dxe modules.
#
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -75,6 +75,9 @@
LocalApicLib
TimerLib
PrintLib
+ PeCoffGetEntryPointLib
+ PeCoffExtraActionLib
+ MemoryAllocationLib
[Guids]
gEfiDebugAgentGuid ## PRODUCES ## Configuration Table
@@ -83,13 +86,8 @@
[Protocols]
gEfiSerialIoProtocolGuid ## PRODUCES
gEfiDevicePathProtocolGuid ## PRODUCES
- gEfiPcdProtocolGuid ## NOTIFY
[Pcd]
gEfiMdePkgTokenSpaceGuid.PcdFSBClock ## CONSUMES
- gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate ## CONSUMES
- gEfiMdePkgTokenSpaceGuid.PcdUartDefaultDataBits ## CONSUMES
- gEfiMdePkgTokenSpaceGuid.PcdUartDefaultParity ## CONSUMES
- gEfiMdePkgTokenSpaceGuid.PcdUartDefaultStopBits ## CONSUMES
gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdExceptionsIgnoredByDebugger ## CONSUMES
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.c b/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.c
index ea702e654..49c8268e0 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.c
@@ -1,7 +1,7 @@
/** @file
SEC Core Debug Agent Library instance implementition.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -14,7 +14,30 @@
#include "SecPeiDebugAgentLib.h"
-CONST BOOLEAN MultiProcessorDebugSupport = FALSE;
+BOOLEAN mSkipBreakpoint = FALSE;
+
+EFI_PEI_NOTIFY_DESCRIPTOR mMemoryDiscoveredNotifyList[1] = {
+ {
+ (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
+ &gEfiPeiMemoryDiscoveredPpiGuid,
+ DebugAgentCallbackMemoryDiscoveredPpi
+ }
+};
+
+/**
+ Check if debug agent support multi-processor.
+
+ @retval TRUE Multi-processor is supported.
+ @retval FALSE Multi-processor is not supported.
+
+**/
+BOOLEAN
+MultiProcessorDebugSupport (
+ VOID
+ )
+{
+ return FALSE;
+}
/**
Read the Attach/Break-in symbols from the debug port.
@@ -32,14 +55,44 @@ DebugReadBreakSymbol (
OUT UINT8 *BreakSymbol
)
{
+ EFI_STATUS Status;
+ DEBUG_PACKET_HEADER DebugHeader;
+ UINT8 *Data8;
+
*BreakSymbol = 0;
//
- // If Debug Port buffer has data, read it till it was break symbol or Debug Port buffer emty.
+ // If Debug Port buffer has data, read it till it was break symbol or Debug Port buffer empty.
//
- while (DebugPortPollBuffer (Handle)) {
- DebugPortReadBuffer (Handle, BreakSymbol, 1, 0);
- if (*BreakSymbol == DEBUG_STARTING_SYMBOL_ATTACH || *BreakSymbol == DEBUG_STARTING_SYMBOL_BREAK) {
+ Data8 = (UINT8 *) &DebugHeader;
+ while (TRUE) {
+ //
+ // If start symbol is not received
+ //
+ if (!DebugPortPollBuffer (Handle)) {
+ //
+ // If no data in Debug Port, exit
+ //
+ break;
+ }
+ //
+ // Try to read the start symbol
+ //
+ DebugPortReadBuffer (Handle, Data8, 1, 0);
+ if (*Data8 == DEBUG_STARTING_SYMBOL_ATTACH) {
+ *BreakSymbol = *Data8;
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Debug Timer attach symbol received %x", *BreakSymbol);
return EFI_SUCCESS;
+ }
+ if (*Data8 == DEBUG_STARTING_SYMBOL_NORMAL) {
+ Status = ReadRemainingBreakPacket (Handle, &DebugHeader);
+ if (Status == EFI_SUCCESS) {
+ *BreakSymbol = DebugHeader.Command;
+ DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Debug Timer break symbol received %x", *BreakSymbol);
+ return EFI_SUCCESS;
+ }
+ if (Status == EFI_TIMEOUT) {
+ break;
+ }
}
}
@@ -47,67 +100,56 @@ DebugReadBreakSymbol (
}
/**
- Get pointer to Mailbox from IDT entry before memory is ready.
+ Get the pointer to location saved Mailbox pointer from IDT entry.
**/
VOID *
-GetMailboxPointerInIdtEntry (
+GetLocationSavedMailboxPointerInIdtEntry (
VOID
)
{
- IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
- IA32_DESCRIPTOR IdtDescriptor;
- UINTN Mailbox;
-
- AsmReadIdtr (&IdtDescriptor);
- IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
+ UINTN *MailboxLocation;
- Mailbox = IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow + (IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh << 16);
- return (VOID *) Mailbox;
+ MailboxLocation = (UINTN *) GetExceptionHandlerInIdtEntry (DEBUG_MAILBOX_VECTOR);
+ //
+ // *MailboxLocation is the pointer to Mailbox
+ //
+ VerifyMailboxChecksum ((DEBUG_AGENT_MAILBOX *) (*MailboxLocation));
+ return MailboxLocation;
}
/**
Set the pointer of Mailbox into IDT entry before memory is ready.
- @param[in] Mailbox The pointer of Mailbox.
+ @param[in] MailboxLocation Pointer to location saved Mailbox pointer.
**/
VOID
-SetMailboxPointerInIdtEntry (
- IN VOID *Mailbox
+SetLocationSavedMailboxPointerInIdtEntry (
+ IN VOID *MailboxLocation
)
{
- IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
- IA32_DESCRIPTOR IdtDescriptor;
-
- AsmReadIdtr (&IdtDescriptor);
- IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;
-
- IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow = (UINT16)(UINTN)Mailbox;
- IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh = (UINT16)((UINTN)Mailbox >> 16);
+ SetExceptionHandlerInIdtEntry (DEBUG_MAILBOX_VECTOR, MailboxLocation);
}
/**
- Get the pointer to Mailbox from IDT entry and build the Mailbox into GUIDed Hob
- after memory is ready.
+ Get the location of Mailbox pointer from the GUIDed HOB.
- @return Pointer to Mailbox.
+ @return Pointer to the location saved Mailbox pointer.
**/
-DEBUG_AGENT_MAILBOX *
-BuildMailboxHob (
+UINT64 *
+GetMailboxLocationFromHob (
VOID
)
{
- DEBUG_AGENT_MAILBOX *Mailbox;
-
- Mailbox = (DEBUG_AGENT_MAILBOX *) GetMailboxPointerInIdtEntry ();
+ EFI_HOB_GUID_TYPE *GuidHob;
- return BuildGuidDataHob (
- &gEfiDebugAgentGuid,
- Mailbox,
- sizeof (DEBUG_AGENT_MAILBOX)
- );
+ GuidHob = GetFirstGuidHob (&gEfiDebugAgentGuid);
+ if (GuidHob == NULL) {
+ return NULL;
+ }
+ return (UINT64 *) (GET_GUID_HOB_DATA(GuidHob));
}
/**
@@ -121,7 +163,49 @@ GetMailboxPointer (
VOID
)
{
- return (DEBUG_AGENT_MAILBOX *) GetMailboxPointerInIdtEntry ();
+ UINT64 DebugPortHandle;
+ UINT64 *MailboxLocationInIdt;
+ UINT64 *MailboxLocationInHob;
+ DEBUG_AGENT_MAILBOX *Mailbox;
+
+ //
+ // Get mailbox from IDT entry firstly
+ //
+ MailboxLocationInIdt = GetLocationSavedMailboxPointerInIdtEntry ();
+ Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocationInIdt);
+ //
+ // Check if mailbox was setup in PEI firstly, cannot used GetDebugFlag() to
+ // get CheckMailboxInHob flag to avoid GetMailboxPointer() nesting.
+ //
+ if (Mailbox->DebugFlag.Bits.CheckMailboxInHob != 1) {
+ //
+ // If mailbox in IDT entry has already been the final one
+ //
+ return Mailbox;
+ }
+
+ MailboxLocationInHob = GetMailboxLocationFromHob ();
+ //
+ // Compare mailbox in IDT enry with mailbox in HOB
+ //
+ if (MailboxLocationInHob != MailboxLocationInIdt && MailboxLocationInHob != NULL) {
+ Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocationInHob);
+ //
+ // Fix up Debug Port handler and save new mailbox in IDT entry
+ //
+ Mailbox = (DEBUG_AGENT_MAILBOX *)((UINTN)Mailbox + ((UINTN)(MailboxLocationInHob) - (UINTN)MailboxLocationInIdt));
+ DebugPortHandle = (UINT64)((UINTN)Mailbox->DebugPortHandle + ((UINTN)(MailboxLocationInHob) - (UINTN)MailboxLocationInIdt));
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);
+ *MailboxLocationInHob = (UINT64)(UINTN)Mailbox;
+ SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationInHob);
+ //
+ // Clean CheckMailboxInHob flag
+ //
+ Mailbox->DebugFlag.Bits.CheckMailboxInHob = 0;
+ UpdateMailboxChecksum (Mailbox);
+ }
+
+ return Mailbox;
}
/**
@@ -137,49 +221,59 @@ GetDebugPortHandle (
{
DEBUG_AGENT_MAILBOX *DebugAgentMailbox;
- DebugAgentMailbox = (DEBUG_AGENT_MAILBOX *)GetMailboxPointerInIdtEntry ();
+ DebugAgentMailbox = GetMailboxPointer ();
return (DEBUG_PORT_HANDLE) (UINTN)(DebugAgentMailbox->DebugPortHandle);
}
/**
- Trigger one software interrupt to debug agent to handle it.
+ Debug Agent provided notify callback function on Memory Discovered PPI.
+
+ @param[in] PeiServices Indirect reference to the PEI Services Table.
+ @param[in] NotifyDescriptor Address of the notification descriptor data structure.
+ @param[in] Ppi Address of the PPI that was installed.
- @param Signature Software interrupt signature.
+ @retval EFI_SUCCESS If the function completed successfully.
**/
-VOID
-TriggerSoftInterrupt (
- UINT32 Signature
+EFI_STATUS
+EFIAPI
+DebugAgentCallbackMemoryDiscoveredPpi (
+ IN EFI_PEI_SERVICES **PeiServices,
+ IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor,
+ IN VOID *Ppi
)
{
- UINTN Dr0;
- UINTN Dr1;
-
+ DEBUG_AGENT_MAILBOX *Mailbox;
+ BOOLEAN InterruptStatus;
+
//
- // Save Debug Register State
+ // Save and disable original interrupt status
//
- Dr0 = AsmReadDr0 ();
- Dr1 = AsmReadDr1 ();
-
+ InterruptStatus = SaveAndDisableInterrupts ();
+
//
- // DR0 = Signature
+ // Set physical memory ready flag
//
- AsmWriteDr0 (SOFT_INTERRUPT_SIGNATURE);
- AsmWriteDr1 (Signature);
+ Mailbox = GetMailboxPointer ();
+ SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);
//
- // Do INT3 to communicate with HOST side
+ // Memory has been ready
//
- CpuBreakpoint ();
+ if (IsHostAttached ()) {
+ //
+ // Trigger one software interrupt to inform HOST
+ //
+ TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);
+ }
//
- // Restore Debug Register State only when Host didn't change it inside exception handler.
- // Dr registers can only be changed by setting the HW breakpoint.
+ // Restore interrupt state.
//
- AsmWriteDr0 (Dr0);
- AsmWriteDr1 (Dr1);
-
+ SetInterruptState (InterruptStatus);
+
+ return EFI_SUCCESS;
}
/**
@@ -225,7 +319,13 @@ InitializeDebugAgent (
DEBUG_AGENT_MAILBOX MailboxInStack;
DEBUG_AGENT_PHASE2_CONTEXT Phase2Context;
DEBUG_AGENT_CONTEXT_POSTMEM_SEC *DebugAgentContext;
-
+ EFI_STATUS Status;
+ IA32_DESCRIPTOR *Ia32Idtr;
+ IA32_IDT_ENTRY *Ia32IdtEntry;
+ UINT64 DebugPortHandle;
+ UINT64 MailboxLocation;
+ UINT64 *MailboxLocationPointer;
+
DisableInterrupts ();
switch (InitFlag) {
@@ -234,20 +334,20 @@ InitializeDebugAgent (
InitializeDebugIdt ();
+ MailboxLocation = (UINT64)(UINTN)&MailboxInStack;
Mailbox = &MailboxInStack;
ZeroMem ((VOID *) Mailbox, sizeof (DEBUG_AGENT_MAILBOX));
-
//
// Get and save debug port handle and set the length of memory block.
//
- SetMailboxPointerInIdtEntry ((VOID *) Mailbox);
+ SetLocationSavedMailboxPointerInIdtEntry (&MailboxLocation);
+ SetDebugFlag (DEBUG_AGENT_FLAG_PRINT_ERROR_LEVEL, DEBUG_AGENT_ERROR);
InitializeDebugTimer ();
Phase2Context.Context = Context;
Phase2Context.Function = Function;
DebugPortInitialize ((VOID *) &Phase2Context, InitializeDebugAgentPhase2);
-
//
// If reaches here, it means Debug Port initialization failed.
//
@@ -256,34 +356,123 @@ InitializeDebugAgent (
break;
case DEBUG_AGENT_INIT_POSTMEM_SEC:
-
+ Mailbox = GetMailboxPointer ();
//
// Memory has been ready
//
- if (IsHostAttached()) {
+ SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);
+ if (IsHostAttached ()) {
//
// Trigger one software interrupt to inform HOST
//
TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);
}
+ //
+ // Fix up Debug Port handle address and mailbox address
+ //
DebugAgentContext = (DEBUG_AGENT_CONTEXT_POSTMEM_SEC *) Context;
+ DebugPortHandle = (UINT64)(UINT32)(Mailbox->DebugPortHandle + DebugAgentContext->StackMigrateOffset);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);
+ Mailbox = (DEBUG_AGENT_MAILBOX *) ((UINTN) Mailbox + DebugAgentContext->StackMigrateOffset);
+ MailboxLocation = (UINT64)(UINTN)Mailbox;
+ //
+ // Build mailbox location in HOB and fix-up its address
+ //
+ MailboxLocationPointer = BuildGuidDataHob (
+ &gEfiDebugAgentGuid,
+ &MailboxLocation,
+ sizeof (UINT64)
+ );
+ MailboxLocationPointer = (UINT64 *) ((UINTN) MailboxLocationPointer + DebugAgentContext->HeapMigrateOffset);
+ //
+ // Update IDT entry to save the location saved mailbox pointer
+ //
+ SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationPointer);
+ //
+ // Enable CPU interrupts so debug timer interrupts can be delivered
+ //
+ EnableInterrupts ();
+
+ break;
+
+ case DEBUG_AGENT_INIT_PEI:
+ //
+ // Check if Debug Agent has initialized before
+ //
+ if (IsDebugAgentInitialzed()) {
+ DEBUG ((EFI_D_WARN, "Debug Agent: It has already initialized in SEC Core!\n"));
+ break;
+ }
+ //
+ // Set up IDT entries
+ //
+ InitializeDebugIdt ();
+ //
+ // Build mailbox in HOB and setup Mailbox Set In Pei flag
+ //
+ Mailbox = AllocateZeroPool (sizeof (DEBUG_AGENT_MAILBOX));
+ MailboxLocation = (UINT64)(UINTN)Mailbox;
+ MailboxLocationPointer = BuildGuidDataHob (
+ &gEfiDebugAgentGuid,
+ &MailboxLocation,
+ sizeof (UINT64)
+ );
- Mailbox = (DEBUG_AGENT_MAILBOX *) GetMailboxPointerInIdtEntry ();
- Mailbox->DebugPortHandle = (UINT64)(UINT32)(Mailbox->DebugPortHandle + DebugAgentContext->StackMigrateOffset);
- Mailbox->DebugFlag.MemoryReady = 1;
+ InitializeDebugTimer ();
+ //
+ // Update IDT entry to save the location pointer saved mailbox pointer
+ //
+ SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationPointer);
+ //
+ // Register for a callback once memory has been initialized.
+ // If memery has been ready, the callback funtion will be invoked immediately
+ //
+ Status = PeiServicesNotifyPpi (&mMemoryDiscoveredNotifyList[0]);
+ ASSERT_EFI_ERROR (Status);
+ //
+ // Set HOB check flag if memory has not been ready yet
+ //
+ if (GetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY) == 0) {
+ SetDebugFlag (DEBUG_AGENT_FLAG_CHECK_MAILBOX_IN_HOB, 1);
+ }
- Mailbox = BuildMailboxHob ();
- Mailbox = (DEBUG_AGENT_MAILBOX *) ((UINTN) Mailbox + DebugAgentContext->HeapMigrateOffset);
+ Phase2Context.Context = Context;
+ Phase2Context.Function = Function;
+ DebugPortInitialize ((VOID *) &Phase2Context, InitializeDebugAgentPhase2);
- SetMailboxPointerInIdtEntry ((VOID *) Mailbox);
+ FindAndReportModuleImageInfo (4);
- EnableInterrupts ();
+ break;
+ case DEBUG_AGENT_INIT_THUNK_PEI_IA32TOX64:
+ if (Context == NULL) {
+ DEBUG ((EFI_D_ERROR, "DebugAgent: Input parameter Context cannot be NULL!\n"));
+ CpuDeadLoop ();
+ } else {
+ Ia32Idtr = (IA32_DESCRIPTOR *) Context;
+ Ia32IdtEntry = (IA32_IDT_ENTRY *)(Ia32Idtr->Base);
+ MailboxLocationPointer = (UINT64 *) (UINTN) (Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow +
+ (Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh << 16));
+ Mailbox = (DEBUG_AGENT_MAILBOX *) (UINTN)(*MailboxLocationPointer);
+ VerifyMailboxChecksum (Mailbox);
+
+ DebugPortHandle = (UINT64) (UINTN)DebugPortInitialize ((VOID *)(UINTN)Mailbox->DebugPortHandle, NULL);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);
+ //
+ // Set up IDT entries
+ //
+ InitializeDebugIdt ();
+ //
+ // Update IDT entry to save location pointer saved the mailbox pointer
+ //
+ SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationPointer);
+
+ FindAndReportModuleImageInfo (4);
+ }
break;
default:
-
//
// Only DEBUG_AGENT_INIT_PREMEM_SEC and DEBUG_AGENT_INIT_POSTMEM_SEC are allowed for this
// Debug Agent library instance.
@@ -294,6 +483,8 @@ InitializeDebugAgent (
}
+ EnableInterrupts ();
+
//
// If Function is not NULL, invoke it always whatever debug agent was initialized sucesssfully or not.
//
@@ -319,11 +510,22 @@ InitializeDebugAgentPhase2 (
)
{
DEBUG_AGENT_PHASE2_CONTEXT *Phase2Context;
+ UINT64 *MailboxLocation;
DEBUG_AGENT_MAILBOX *Mailbox;
EFI_SEC_PEI_HAND_OFF *SecCoreData;
+ UINT16 BufferSize;
+ UINT64 NewDebugPortHandle;
- Mailbox = GetMailboxPointerInIdtEntry ();
- Mailbox->DebugPortHandle = (UINT64) (UINTN)DebugPortHandle;
+ Phase2Context = (DEBUG_AGENT_PHASE2_CONTEXT *) Context;
+ MailboxLocation = GetLocationSavedMailboxPointerInIdtEntry ();
+ Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocation);
+ BufferSize = PcdGet16(PcdDebugPortHandleBufferSize);
+ if (Phase2Context->Function == NULL && DebugPortHandle != NULL && BufferSize != 0) {
+ NewDebugPortHandle = (UINT64)(UINTN)AllocateCopyPool (BufferSize, DebugPortHandle);
+ } else {
+ NewDebugPortHandle = (UINT64)(UINTN)DebugPortHandle;
+ }
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, NewDebugPortHandle);
//
// Trigger one software interrupt to inform HOST
@@ -334,9 +536,9 @@ InitializeDebugAgentPhase2 (
// If Temporary RAM region is below 128 MB, then send message to
// host to disable low memory filtering.
//
- Phase2Context = (DEBUG_AGENT_PHASE2_CONTEXT *) Context;
SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Phase2Context->Context;
if ((UINTN)SecCoreData->TemporaryRamBase < BASE_128MB && IsHostAttached ()) {
+ SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);
TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);
}
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.h b/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.h
index 9ca5e87fb..68bfbf7ca 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.h
+++ b/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.h
@@ -1,7 +1,7 @@
/** @file
Header file for Sec Core Debug Agent Library instance.
- Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -16,7 +16,9 @@
#define _SEC_CORE_DEBUG_AGENT_LIB_H_
#include <PiPei.h>
-
+#include <Ppi/MemoryDiscovered.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/MemoryAllocationLib.h>
#include "DebugAgent.h"
typedef struct {
@@ -24,5 +26,39 @@ typedef struct {
DEBUG_AGENT_CONTINUE Function;
} DEBUG_AGENT_PHASE2_CONTEXT;
+/**
+ Caller provided function to be invoked at the end of DebugPortInitialize().
+
+ Refer to the descrption for DebugPortInitialize() for more details.
+
+ @param[in] Context The first input argument of DebugPortInitialize().
+ @param[in] DebugPortHandle Debug port handle created by Debug Communication Libary.
+
+**/
+VOID
+EFIAPI
+InitializeDebugAgentPhase2 (
+ IN VOID *Context,
+ IN DEBUG_PORT_HANDLE DebugPortHandle
+ );
+
+/**
+ Debug Agent provided notify callback function on Memory Discovered PPI.
+
+ @param[in] PeiServices Indirect reference to the PEI Services Table.
+ @param[in] NotifyDescriptor Address of the notification descriptor data structure.
+ @param[in] Ppi Address of the PPI that was installed.
+
+ @retval EFI_SUCCESS If the function completed successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+DebugAgentCallbackMemoryDiscoveredPpi (
+ IN EFI_PEI_SERVICES **PeiServices,
+ IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor,
+ IN VOID *Ppi
+ );
+
#endif
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf b/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
index 577a635a4..b81fc16d1 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
+++ b/SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
@@ -1,7 +1,7 @@
## @file
# Debug Agent library instance for SEC Core and PEI modules.
#
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -70,6 +70,13 @@
DebugLib
TimerLib
PrintLib
+ PeiServicesLib
+ MemoryAllocationLib
+ PeCoffGetEntryPointLib
+ PeCoffExtraActionLib
+
+[Ppis]
+ gEfiPeiMemoryDiscoveredPpiGuid
[Guids]
gEfiDebugAgentGuid ## PRODUCES ## HOB
@@ -77,4 +84,5 @@
[Pcd]
gEfiMdePkgTokenSpaceGuid.PcdFSBClock ## CONSUMES
gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdExceptionsIgnoredByDebugger ## CONSUMES
+ gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugPortHandleBufferSize ## CONSUMES
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgent/SmmDebugAgentLib.c b/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgent/SmmDebugAgentLib.c
index 3326c0a05..145fee0fa 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgent/SmmDebugAgentLib.c
+++ b/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgent/SmmDebugAgentLib.c
@@ -1,7 +1,7 @@
/** @file
Debug Agent library implementition.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -17,7 +17,25 @@
DEBUG_AGENT_MAILBOX *mMailboxPointer = NULL;
DEBUG_AGENT_MAILBOX mLocalMailbox;
UINTN mSavedDebugRegisters[6];
-CONST BOOLEAN MultiProcessorDebugSupport = FALSE;
+IA32_IDT_GATE_DESCRIPTOR mIdtEntryTable[33];
+BOOLEAN mSkipBreakpoint = FALSE;
+
+CHAR8 mWarningMsgIgnoreSmmEntryBreak[] = "Ignore smmentrybreak setting for SMI issued during DXE debugging!\r\n";
+
+/**
+ Check if debug agent support multi-processor.
+
+ @retval TRUE Multi-processor is supported.
+ @retval FALSE Multi-processor is not supported.
+
+**/
+BOOLEAN
+MultiProcessorDebugSupport (
+ VOID
+ )
+{
+ return FALSE;
+}
/**
Read the Attach/Break-in symbols from the debug port.
@@ -42,6 +60,32 @@ DebugReadBreakSymbol (
}
/**
+ Get the pointer to Mailbox from the GUIDed HOB.
+
+ @return Pointer to Mailbox.
+
+**/
+DEBUG_AGENT_MAILBOX *
+GetMailboxFromHob (
+ VOID
+ )
+{
+ EFI_HOB_GUID_TYPE *GuidHob;
+ UINT64 *MailboxLocation;
+ DEBUG_AGENT_MAILBOX *Mailbox;
+
+ GuidHob = GetFirstGuidHob (&gEfiDebugAgentGuid);
+ if (GuidHob == NULL) {
+ return NULL;
+ }
+ MailboxLocation = (UINT64 *) (GET_GUID_HOB_DATA(GuidHob));
+ Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocation);
+ VerifyMailboxChecksum (Mailbox);
+
+ return Mailbox;
+}
+
+/**
Get Debug Agent Mailbox pointer.
@return Mailbox pointer.
@@ -52,6 +96,7 @@ GetMailboxPointer (
VOID
)
{
+ VerifyMailboxChecksum (mMailboxPointer);
return mMailboxPointer;
}
@@ -66,7 +111,7 @@ GetDebugPortHandle (
VOID
)
{
- return (DEBUG_PORT_HANDLE) (UINTN)(mMailboxPointer->DebugPortHandle);
+ return (DEBUG_PORT_HANDLE) (UINTN)(GetMailboxPointer()->DebugPortHandle);
}
/**
@@ -134,16 +179,76 @@ InitializeDebugAgent (
IN DEBUG_AGENT_CONTINUE Function OPTIONAL
)
{
- EFI_STATUS Status;
- UINT64 DebugPortHandle;
+ EFI_STATUS Status;
+ UINT64 DebugPortHandle;
+ IA32_IDT_GATE_DESCRIPTOR IdtEntry[33];
+ IA32_DESCRIPTOR IdtDescriptor;
+ IA32_DESCRIPTOR *Ia32Idtr;
+ IA32_IDT_ENTRY *Ia32IdtEntry;
+ IA32_DESCRIPTOR Idtr;
+ UINT16 IdtEntryCount;
+ DEBUG_AGENT_MAILBOX *Mailbox;
+ UINT64 *MailboxLocation;
switch (InitFlag) {
case DEBUG_AGENT_INIT_SMM:
- Status = EfiGetSystemConfigurationTable (&gEfiDebugAgentGuid, (VOID **) &mMailboxPointer);
- if (EFI_ERROR (Status) || mMailboxPointer == NULL) {
- ZeroMem (&mLocalMailbox, sizeof (DEBUG_AGENT_MAILBOX));
- mMailboxPointer = &mLocalMailbox;
+ //
+ // Check if Debug Agent initialized in DXE phase
+ //
+ Status = EfiGetSystemConfigurationTable (&gEfiDebugAgentGuid, (VOID **) &Mailbox);
+ if (Status == EFI_SUCCESS && Mailbox != NULL) {
+ VerifyMailboxChecksum (Mailbox);
+ mMailboxPointer = Mailbox;
+ break;
}
+ //
+ // Check if Debug Agent initialized in SEC/PEI phase
+ //
+ Mailbox = GetMailboxFromHob ();
+ if (Mailbox != NULL) {
+ mMailboxPointer = Mailbox;
+ break;
+ }
+ //
+ // Debug Agent was not initialized before, uset the local mailbox.
+ //
+ ZeroMem (&mLocalMailbox, sizeof (DEBUG_AGENT_MAILBOX));
+ Mailbox = &mLocalMailbox;
+ //
+ // Save original IDT entries
+ //
+ AsmReadIdtr (&IdtDescriptor);
+ CopyMem (&IdtEntry, (VOID *)IdtDescriptor.Base, 33 * sizeof(IA32_IDT_GATE_DESCRIPTOR));
+ //
+ // Initialized Debug Agent
+ //
+ InitializeDebugIdt ();
+ DebugPortHandle = (UINT64) (UINTN)DebugPortInitialize ((DEBUG_PORT_HANDLE) (UINTN)Mailbox->DebugPortHandle, NULL);
+ UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);
+ mMailboxPointer = Mailbox;
+ //
+ // Trigger one software interrupt to inform HOST
+ //
+ TriggerSoftInterrupt (SYSTEM_RESET_SIGNATURE);
+
+ SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);
+ //
+ // Memory has been ready
+ //
+ if (IsHostAttached ()) {
+ //
+ // Trigger one software interrupt to inform HOST
+ //
+ TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);
+ }
+ //
+ // Find and report PE/COFF image info to HOST
+ //
+ FindAndReportModuleImageInfo (SIZE_4KB);
+ //
+ // Restore saved IDT entries
+ //
+ CopyMem ((VOID *)IdtDescriptor.Base, &IdtEntry, 33 * sizeof(IA32_IDT_GATE_DESCRIPTOR));
break;
@@ -151,14 +256,24 @@ InitializeDebugAgent (
SaveDebugRegister ();
InitializeDebugIdt ();
- if (mMailboxPointer != NULL) {
+ Mailbox = GetMailboxPointer ();
+ if (GetDebugFlag (DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS) == 1) {
//
- // Initialize debug communication port
+ // If Debug Agent has been communicaton state with HOST, we need skip
+ // any break points set in SMM, set Skip Breakpoint flag
//
- DebugPortHandle = (UINT64) (UINTN)DebugPortInitialize ((DEBUG_PORT_HANDLE) (UINTN)mMailboxPointer->DebugPortHandle, NULL);
- mMailboxPointer->DebugPortHandle = DebugPortHandle;
-
- if (mMailboxPointer->DebugFlag.BreakOnNextSmi == 1) {
+ mSkipBreakpoint = TRUE;
+ }
+ if (GetDebugFlag (DEBUG_AGENT_FLAG_BREAK_ON_NEXT_SMI) == 1) {
+ if (mSkipBreakpoint) {
+ //
+ // Print warning message if ignore smm entry break
+ //
+ DebugPortWriteBuffer ((DEBUG_PORT_HANDLE) (UINTN)Mailbox->DebugPortHandle,
+ (UINT8 *)mWarningMsgIgnoreSmmEntryBreak,
+ AsciiStrLen (mWarningMsgIgnoreSmmEntryBreak)
+ );
+ } else {
//
// If SMM entry break is set, SMM code will be break at here.
//
@@ -168,8 +283,56 @@ InitializeDebugAgent (
break;
case DEBUG_AGENT_INIT_EXIT_SMI:
+ Mailbox = GetMailboxPointer ();
+ //
+ // Clear Skip Breakpoint flag
+ //
+ mSkipBreakpoint = FALSE;
RestoreDebugRegister ();
break;
+
+ case DEBUG_AGENT_INIT_THUNK_PEI_IA32TOX64:
+ if (Context == NULL) {
+ DEBUG ((EFI_D_ERROR, "DebugAgent: Input parameter Context cannot be NULL!\n"));
+ CpuDeadLoop ();
+ } else {
+ Ia32Idtr = (IA32_DESCRIPTOR *) Context;
+ Ia32IdtEntry = (IA32_IDT_ENTRY *)(Ia32Idtr->Base);
+ MailboxLocation = (UINT64 *) (UINTN) (Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow +
+ (Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh << 16));
+ mMailboxPointer = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocation);
+ VerifyMailboxChecksum (mMailboxPointer);
+ //
+ // Get original IDT address and size.
+ //
+ AsmReadIdtr ((IA32_DESCRIPTOR *) &Idtr);
+ IdtEntryCount = (UINT16) ((Idtr.Limit + 1) / sizeof (IA32_IDT_GATE_DESCRIPTOR));
+ if (IdtEntryCount < 33) {
+ Idtr.Limit = (UINT16) (sizeof (IA32_IDT_GATE_DESCRIPTOR) * 33 - 1);
+ Idtr.Base = (UINTN) &mIdtEntryTable;
+ ZeroMem (&mIdtEntryTable, Idtr.Limit + 1);
+ AsmWriteIdtr ((IA32_DESCRIPTOR *) &Idtr);
+ }
+
+ InitializeDebugIdt ();
+ //
+ // Initialize Debug Timer hardware and enable interrupt.
+ //
+ InitializeDebugTimer ();
+ EnableInterrupts ();
+
+ FindAndReportModuleImageInfo (SIZE_4KB);
+ }
+ break;
+
+ default:
+ //
+ // Only DEBUG_AGENT_INIT_PREMEM_SEC and DEBUG_AGENT_INIT_POSTMEM_SEC are allowed for this
+ // Debug Agent library instance.
+ //
+ DEBUG ((EFI_D_ERROR, "Debug Agent: The InitFlag value is not allowed!\n"));
+ CpuDeadLoop ();
+ break;
}
}
diff --git a/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf b/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf
index f62d9975c..9ed314d40 100644
--- a/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf
+++ b/SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf
@@ -1,7 +1,7 @@
## @file
# Debug Agent library instance for SMM modules.
#
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -15,7 +15,7 @@
[Defines]
INF_VERSION = 0x00010005
- BASE_NAME = SecDebugAgentLib
+ BASE_NAME = SmmDebugAgentLib
FILE_GUID = CB07D74C-598F-4268-A5D1-644FB4A481E8
MODULE_TYPE = DXE_SMM_DRIVER
VERSION_STRING = 0.7
@@ -69,11 +69,14 @@
LocalApicLib
TimerLib
PrintLib
+ PeCoffExtraActionLib
+ PeCoffGetEntryPointLib
[Guids]
gEfiDebugAgentGuid ## CONSUMES ## Configuration Table
[Pcd]
- gEfiMdePkgTokenSpaceGuid.PcdFSBClock ## CONSUMES
- gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdExceptionsIgnoredByDebugger ## CONSUMES
+ gEfiMdePkgTokenSpaceGuid.PcdFSBClock ## CONSUMES
+ ## Skip Page Fault exception (14) by default in SMM
+ gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdExceptionsIgnoredByDebugger|0x00004000 ## CONSUMES
diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c b/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c
index dd88e7d69..952321659 100644
--- a/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c
+++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c
@@ -1,7 +1,7 @@
/** @file
Debug Port Library implementation based on serial port.
- Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -18,6 +18,80 @@
#include <Library/SerialPortLib.h>
#include <Library/TimerLib.h>
#include <Library/DebugLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+
+#pragma pack(1)
+//
+// The internal data structure of DEBUG_PORT_HANDLE, which stores some
+// important datum which are used across various phases.
+//
+typedef struct _SERIAL_DEBUG_PORT_HANDLE{
+ //
+ // Timter settings
+ //
+ UINT64 TimerFrequency;
+ UINT64 TimerCycle;
+ BOOLEAN TimerCountDown;
+} SERIAL_DEBUG_PORT_HANDLE;
+#pragma pack()
+
+//
+// The global variable which can be used after memory is ready.
+//
+SERIAL_DEBUG_PORT_HANDLE mSerialDebugPortHandle;
+
+/**
+ Check if the timer is timeout.
+
+ @param[in] SerialDebugPortHandle Pointer to Serial Debug port handle
+ @param[in] Timer The start timer from the begin.
+ @param[in] TimeoutTicker Ticker number need time out.
+
+ @return TRUE Timer time out occurs.
+ @retval FALSE Timer does not time out.
+
+**/
+BOOLEAN
+IsTimerTimeout (
+ IN SERIAL_DEBUG_PORT_HANDLE *SerialDebugPortHandle,
+ IN UINT64 Timer,
+ IN UINT64 TimeoutTicker
+ )
+{
+ UINT64 CurrentTimer;
+ UINT64 Delta;
+
+ CurrentTimer = GetPerformanceCounter ();
+
+ if (SerialDebugPortHandle->TimerCountDown) {
+ //
+ // The timer counter counts down. Check for roll over condition.
+ //
+ if (CurrentTimer < Timer) {
+ Delta = Timer - CurrentTimer;
+ } else {
+ //
+ // Handle one roll-over.
+ //
+ Delta = SerialDebugPortHandle->TimerCycle - (CurrentTimer - Timer);
+ }
+ } else {
+ //
+ // The timer counter counts up. Check for roll over condition.
+ //
+ if (CurrentTimer > Timer) {
+ Delta = CurrentTimer - Timer;
+ } else {
+ //
+ // Handle one roll-over.
+ //
+ Delta = SerialDebugPortHandle->TimerCycle - (Timer - CurrentTimer);
+ }
+ }
+
+ return (BOOLEAN) (Delta >= TimeoutTicker);
+}
/**
Initialize the debug port.
@@ -62,7 +136,42 @@ DebugPortInitialize (
IN DEBUG_PORT_CONTINUE Function
)
{
- RETURN_STATUS Status;
+ RETURN_STATUS Status;
+ SERIAL_DEBUG_PORT_HANDLE Handle;
+ SERIAL_DEBUG_PORT_HANDLE *SerialDebugPortHandle;
+ UINT64 TimerStartValue;
+ UINT64 TimerEndValue;
+
+ //
+ // Validate the PCD PcdDebugPortHandleBufferSize value
+ //
+ ASSERT (PcdGet16 (PcdDebugPortHandleBufferSize) == sizeof (SERIAL_DEBUG_PORT_HANDLE));
+
+ if (Context != NULL && Function == NULL) {
+ SerialDebugPortHandle = (SERIAL_DEBUG_PORT_HANDLE *)Context;
+ } else {
+ ZeroMem (&Handle, sizeof (SERIAL_DEBUG_PORT_HANDLE));
+ SerialDebugPortHandle = &Handle;
+ }
+ SerialDebugPortHandle->TimerFrequency = GetPerformanceCounterProperties (
+ &TimerStartValue,
+ &TimerEndValue
+ );
+ DEBUG ((EFI_D_INFO, "Serial Debug Port: TimerFrequency = 0x%lx\n", SerialDebugPortHandle->TimerFrequency));
+ DEBUG ((EFI_D_INFO, "Serial Debug Port: TimerStartValue = 0x%lx\n", TimerStartValue));
+ DEBUG ((EFI_D_INFO, "Serial Debug Port: TimerEndValue = 0x%lx\n", TimerEndValue));
+
+ if (TimerEndValue < TimerStartValue) {
+ SerialDebugPortHandle->TimerCountDown = TRUE;
+ SerialDebugPortHandle->TimerCycle = TimerStartValue - TimerEndValue;
+ } else {
+ SerialDebugPortHandle->TimerCountDown = FALSE;
+ SerialDebugPortHandle->TimerCycle = TimerEndValue - TimerStartValue;
+ }
+
+ if (Function == NULL && Context != NULL) {
+ return (DEBUG_PORT_HANDLE *) Context;
+ }
Status = SerialPortInitialize ();
if (RETURN_ERROR(Status)) {
@@ -70,10 +179,12 @@ DebugPortInitialize (
}
if (Function != NULL) {
- Function (Context, NULL);
+ Function (Context, SerialDebugPortHandle);
+ } else {
+ CopyMem(&mSerialDebugPortHandle, SerialDebugPortHandle, sizeof (SERIAL_DEBUG_PORT_HANDLE));
}
- return NULL;
+ return (DEBUG_PORT_HANDLE)(UINTN)&mSerialDebugPortHandle;
}
/**
@@ -102,25 +213,62 @@ DebugPortReadBuffer (
IN UINTN Timeout
)
{
- UINTN Index;
- INTN Elapsed;
-
- for (Index = 0; Index < NumberOfBytes; Index ++) {
- Elapsed = (INTN) Timeout;
- while (TRUE) {
- if (SerialPortPoll () || Timeout == 0) {
- SerialPortRead (Buffer + Index, 1);
- break;
- }
- MicroSecondDelay (1000);
- Elapsed -= 1000;
- if (Elapsed < 0) {
+ SERIAL_DEBUG_PORT_HANDLE *SerialDebugPortHandle;
+ UINTN Index;
+ UINT64 Begin;
+ UINT64 TimeoutTicker;
+ UINT64 TimerRound;
+
+ //
+ // If Handle is NULL, it means memory is ready for use.
+ // Use global variable to store handle value.
+ //
+ if (Handle == NULL) {
+ SerialDebugPortHandle = &mSerialDebugPortHandle;
+ } else {
+ SerialDebugPortHandle = (SERIAL_DEBUG_PORT_HANDLE *)Handle;
+ }
+
+ Begin = 0;
+ TimeoutTicker = 0;
+ TimerRound = 0;
+ if (Timeout != 0) {
+ Begin = GetPerformanceCounter ();
+ TimeoutTicker = DivU64x32 (
+ MultU64x64 (
+ SerialDebugPortHandle->TimerFrequency,
+ Timeout
+ ),
+ 1000000u
+ );
+ TimerRound = DivU64x64Remainder (
+ TimeoutTicker,
+ DivU64x32 (SerialDebugPortHandle->TimerCycle, 2),
+ &TimeoutTicker
+ );
+ }
+ Index = 0;
+ while (Index < NumberOfBytes) {
+ if (SerialPortPoll () || Timeout == 0) {
+ SerialPortRead (Buffer + Index, 1);
+ Index ++;
+ continue;
+ }
+ if (TimerRound == 0) {
+ if (IsTimerTimeout (SerialDebugPortHandle, Begin, TimeoutTicker)) {
+ //
+ // If time out occurs.
+ //
return 0;
}
+ } else {
+ if (IsTimerTimeout (SerialDebugPortHandle, Begin, DivU64x32 (SerialDebugPortHandle->TimerCycle, 2))) {
+ TimerRound --;
+ }
}
}
- return NumberOfBytes;
+ return Index;
}
/**
diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf b/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
index 6d36cefd7..6ee5ddcce 100644
--- a/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
+++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
@@ -1,7 +1,7 @@
## @file
# Debug Communication Library instance based on serila port.
#
-# Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -36,4 +36,10 @@
SerialPortLib
TimerLib
DebugLib
-
+ BaseMemoryLib
+ BaseLib
+
+[PCD]
+ ## The value of data buffer size used for Serial debug port handle.
+ ## It should be equal to sizeof (SERIAL_DEBUG_PORT_HANDLE).
+ gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugPortHandleBufferSize|17
diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c
index aafd52d3c..c08d45b78 100644
--- a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c
+++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c
@@ -1,7 +1,7 @@
/** @file
Debug Port Library implementation based on usb debug port.
- Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -147,6 +147,12 @@ typedef struct _USB_DEBUG_PORT_HANDLE{
// The data buffer. Maximum length is 8 bytes.
//
UINT8 Data[8];
+ //
+ // Timter settings
+ //
+ UINT64 TimerFrequency;
+ UINT64 TimerCycle;
+ BOOLEAN TimerCountDown;
} USB_DEBUG_PORT_HANDLE;
#pragma pack()
@@ -156,6 +162,58 @@ typedef struct _USB_DEBUG_PORT_HANDLE{
USB_DEBUG_PORT_HANDLE mUsbDebugPortHandle;
/**
+ Check if the timer is timeout.
+
+ @param[in] UsbDebugPortHandle Pointer to USB Debug port handle
+ @param[in] Timer The start timer from the begin.
+ @param[in] TimeoutTicker Ticker number need time out.
+
+ @return TRUE Timer time out occurs.
+ @retval FALSE Timer does not time out.
+
+**/
+BOOLEAN
+IsTimerTimeout (
+ IN USB_DEBUG_PORT_HANDLE *UsbDebugPortHandle,
+ IN UINT64 Timer,
+ IN UINT64 TimeoutTicker
+ )
+{
+ UINT64 CurrentTimer;
+ UINT64 Delta;
+
+ CurrentTimer = GetPerformanceCounter ();
+
+ if (UsbDebugPortHandle->TimerCountDown) {
+ //
+ // The timer counter counts down. Check for roll over condition.
+ //
+ if (CurrentTimer < Timer) {
+ Delta = Timer - CurrentTimer;
+ } else {
+ //
+ // Handle one roll-over.
+ //
+ Delta = UsbDebugPortHandle->TimerCycle - (CurrentTimer - Timer);
+ }
+ } else {
+ //
+ // The timer counter counts up. Check for roll over condition.
+ //
+ if (CurrentTimer > Timer) {
+ Delta = CurrentTimer - Timer;
+ } else {
+ //
+ // Handle one roll-over.
+ //
+ Delta = UsbDebugPortHandle->TimerCycle - (Timer - CurrentTimer);
+ }
+ }
+
+ return (BOOLEAN) (Delta >= TimeoutTicker);
+}
+
+/**
Calculate the usb debug port bar address.
@param DebugPortOffset Get usb debug port offset in the usb debug port memory space.
@@ -617,28 +675,21 @@ InitializeUsbDebugHardware (
if (((MmioRead32((UINTN)&UsbDebugPortRegister->ControlStatus) & (USB_DEBUG_PORT_OWNER | USB_DEBUG_PORT_IN_USE))
!= (USB_DEBUG_PORT_OWNER | USB_DEBUG_PORT_IN_USE)) || (Handle->Initialized == USBDBG_RESET)) {
//
- // If the host controller is not halted, then halt it.
- //
- if ((MmioRead32((UINTN)UsbStatus) & BIT12) == 0) {
- MmioAnd32((UINTN)UsbCmd, (UINT32)~BIT0);
- while ((MmioRead32((UINTN)UsbStatus) & BIT12) == 0);
- }
- //
- // reset the host controller.
- //
- MmioOr32((UINTN)UsbCmd, BIT1);
+ // If the host controller is halted, then reset and restart it.
//
- // ensure that the host controller is reset.
- //
- while (MmioRead32((UINTN)UsbCmd) & BIT1);
+ if ((MmioRead32((UINTN)UsbStatus) & BIT12) != 0) {
+ //
+ // reset the host controller.
+ //
+ MmioOr32((UINTN)UsbCmd, BIT1);
+ //
+ // ensure that the host controller is reset.
+ //
+ while ((MmioRead32((UINTN)UsbCmd) & BIT1) != 0);
- //
- // Start the host controller if it's not running
- //
- if (MmioRead32((UINTN)UsbStatus) & BIT12) {
MmioOr32((UINTN)UsbCmd, BIT0);
// ensure that the host controller is started (HALTED bit must be cleared)
- while (MmioRead32((UINTN)UsbStatus) & BIT12);
+ while ((MmioRead32((UINTN)UsbStatus) & BIT12) != 0);
}
//
@@ -780,6 +831,9 @@ DebugPortReadBuffer (
UINTN Remaining;
UINT8 Index;
UINT8 Length;
+ UINT64 Begin;
+ UINT64 TimeoutTicker;
+ UINT64 TimerRound;
if (NumberOfBytes == 0 || Buffer == NULL) {
return 0;
@@ -834,14 +888,43 @@ DebugPortReadBuffer (
//
// If Timeout is equal to 0, then it means it should always wait until all datum required are received.
//
- if (Timeout == 0) {
- Timeout = 0xFFFFFFFF;
+ Begin = 0;
+ TimeoutTicker = 0;
+ TimerRound = 0;
+ if (Timeout != 0) {
+ Begin = GetPerformanceCounter ();
+ TimeoutTicker = DivU64x32 (
+ MultU64x64 (
+ UsbDebugPortHandle->TimerFrequency,
+ Timeout
+ ),
+ 1000000u
+ );
+ TimerRound = DivU64x64Remainder (
+ TimeoutTicker,
+ DivU64x32 (UsbDebugPortHandle->TimerCycle, 2),
+ &TimeoutTicker
+ );
}
//
// Read remaining data by executing one or more usb debug transfer transactions at usb debug port hw.
//
- while ((Total < NumberOfBytes) && (Timeout != 0)) {
+ while (Total < NumberOfBytes) {
+ if (Timeout != 0) {
+ if (TimerRound == 0) {
+ if (IsTimerTimeout (UsbDebugPortHandle, Begin, TimeoutTicker)) {
+ //
+ // If time out occurs.
+ //
+ return 0;
+ }
+ } else {
+ if (IsTimerTimeout (UsbDebugPortHandle, Begin, DivU64x32 (UsbDebugPortHandle->TimerCycle, 2))) {
+ TimerRound --;
+ }
+ }
+ }
Remaining = NumberOfBytes - Total;
if (Remaining >= USB_DEBUG_PORT_MAX_PACKET_SIZE) {
Status = UsbDebugPortIn(UsbDebugPortRegister, Buffer + Total, &Received, INPUT_PID, 0x7f, 0x82, UsbDebugPortHandle->BulkInToggle);
@@ -850,46 +933,44 @@ DebugPortReadBuffer (
return Total;
}
} else {
- Status = UsbDebugPortIn(UsbDebugPortRegister, &UsbDebugPortHandle->Data[0], &Received, INPUT_PID, 0x7f, 0x82, UsbDebugPortHandle->BulkInToggle);
+ Status = UsbDebugPortIn(UsbDebugPortRegister, &UsbDebugPortHandle->Data[0], &Received, INPUT_PID, 0x7f, 0x82, UsbDebugPortHandle->BulkInToggle);
- if (RETURN_ERROR(Status)) {
- return Total;
- }
+ if (RETURN_ERROR(Status)) {
+ return Total;
+ }
- UsbDebugPortHandle->DataCount = Received;
+ UsbDebugPortHandle->DataCount = Received;
- if (Remaining <= Received) {
- Length = (UINT8)Remaining;
- } else {
- Length = (UINT8)Received;
- }
+ if (Remaining <= Received) {
+ Length = (UINT8)Remaining;
+ } else {
+ Length = (UINT8)Received;
+ }
- //
- // Copy required data from the data buffer to user buffer.
- //
- for (Index = 0; Index < Length; Index++) {
- (Buffer + Total)[Index] = UsbDebugPortHandle->Data[Index];
- UsbDebugPortHandle->DataCount--;
- }
+ //
+ // Copy required data from the data buffer to user buffer.
+ //
+ for (Index = 0; Index < Length; Index++) {
+ (Buffer + Total)[Index] = UsbDebugPortHandle->Data[Index];
+ UsbDebugPortHandle->DataCount--;
+ }
- //
- // reorder the data buffer to make available data arranged from the beginning of the data buffer.
- //
- for (Index = 0; Index < Received - Length; Index++) {
- if (Length + Index >= 8) {
- return 0;
- }
- UsbDebugPortHandle->Data[Index] = UsbDebugPortHandle->Data[Length + Index];
+ //
+ // reorder the data buffer to make available data arranged from the beginning of the data buffer.
+ //
+ for (Index = 0; Index < Received - Length; Index++) {
+ if (Length + Index >= 8) {
+ return 0;
}
- //
- // fixup the real received length in Buffer.
- //
- Received = Length;
+ UsbDebugPortHandle->Data[Index] = UsbDebugPortHandle->Data[Length + Index];
}
- UsbDebugPortHandle->BulkInToggle ^= 1;
-
- Total += Received;
- Timeout -= 100;
+ //
+ // fixup the real received length in Buffer.
+ //
+ Received = Length;
+ }
+ UsbDebugPortHandle->BulkInToggle ^= 1;
+ Total += Received;
}
return Total;
@@ -1118,11 +1199,40 @@ DebugPortInitialize (
{
RETURN_STATUS Status;
USB_DEBUG_PORT_HANDLE Handle;
- if (Function == NULL && Context != NULL) {
- return (DEBUG_PORT_HANDLE *) Context;
+ USB_DEBUG_PORT_HANDLE *UsbDebugPortHandle;
+ UINT64 TimerStartValue;
+ UINT64 TimerEndValue;
+ //
+ // Validate the PCD PcdDebugPortHandleBufferSize value
+ //
+ ASSERT (PcdGet16 (PcdDebugPortHandleBufferSize) == sizeof (USB_DEBUG_PORT_HANDLE));
+
+ if (Function == NULL && Context != NULL) {
+ UsbDebugPortHandle = (USB_DEBUG_PORT_HANDLE *)Context;
+ } else {
+ ZeroMem(&Handle, sizeof (USB_DEBUG_PORT_HANDLE));
+ UsbDebugPortHandle = &Handle;
}
- ZeroMem(&Handle, sizeof (USB_DEBUG_PORT_HANDLE));
+ UsbDebugPortHandle->TimerFrequency = GetPerformanceCounterProperties (
+ &TimerStartValue,
+ &TimerEndValue
+ );
+ DEBUG ((EFI_D_INFO, "USB Debug Port: TimerFrequency = 0x%lx\n", UsbDebugPortHandle->TimerFrequency));
+ DEBUG ((EFI_D_INFO, "USB Debug Port: TimerStartValue = 0x%lx\n", TimerStartValue));
+ DEBUG ((EFI_D_INFO, "USB Debug Port: TimerEndValue = 0x%lx\n", TimerEndValue));
+
+ if (TimerEndValue < TimerStartValue) {
+ UsbDebugPortHandle->TimerCountDown = TRUE;
+ UsbDebugPortHandle->TimerCycle = TimerStartValue - TimerEndValue;
+ } else {
+ UsbDebugPortHandle->TimerCountDown = FALSE;
+ UsbDebugPortHandle->TimerCycle = TimerEndValue - TimerStartValue;
+ }
+
+ if (Function == NULL && Context != NULL) {
+ return (DEBUG_PORT_HANDLE *) Context;
+ }
Status = CalculateUsbDebugPortBar(&Handle.DebugPortOffset, &Handle.DebugPortBarNumber);
if (RETURN_ERROR (Status)) {
@@ -1156,7 +1266,7 @@ DebugPortInitialize (
DEBUG ((EFI_D_ERROR, "UsbDbg: Start EHCI debug port initialization!\n"));
Status = InitializeUsbDebugHardware (&Handle);
if (RETURN_ERROR(Status)) {
- DEBUG ((EFI_D_ERROR, "UsbDbg: Initialization failed, please check if USB debug cable is plugged into EHCI debug port correctly!\n"));
+ DEBUG ((EFI_D_ERROR, "UsbDbg: Failed, please check if USB debug cable is plugged into EHCI debug port correctly!\n"));
goto Exit;
}
}
diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.inf b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.inf
index 61e8a7f1d..37e365a7a 100644
--- a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.inf
+++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.inf
@@ -1,7 +1,7 @@
## @file
# Debug Communication Library instance based on usb debug port.
#
-# Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -44,6 +44,9 @@
## The pci address of ehci host controller, in which usb debug feature is enabled.
## The format of pci address please refer to SourceLevelDebugPkg.dec
gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdUsbEhciPciAddress
+ ## The value of data buffer size used for USB debug port handle.
+ ## It should be equal to sizeof (USB_DEBUG_PORT_HANDLE).
+ gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugPortHandleBufferSize|40
[LibraryClasses]
TimerLib
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.S b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.S
new file mode 100644
index 000000000..69c903788
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.S
@@ -0,0 +1,28 @@
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php.
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+# Module Name:
+#
+# IntHandler.S
+#
+# Abstract:
+#
+# Assembly interrupt handler function.
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(AsmInterruptHandle)
+
+.text
+ASM_PFX(AsmInterruptHandle):
+ cli
+ movb $1, %al
+ iretl
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.asm b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.asm
new file mode 100644
index 000000000..ce9c03b49
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandler.asm
@@ -0,0 +1,33 @@
+;------------------------------------------------------------------------------
+;
+; Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+; This program and the accompanying materials
+; are licensed and made available under the terms and conditions of the BSD License
+; which accompanies this distribution. The full text of the license may be found at
+; http://opensource.org/licenses/bsd-license.php.
+;
+; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+;
+; Module Name:
+;
+; IntHandler.asm
+;
+; Abstract:
+;
+; Assembly interrupt handler function.
+;
+;------------------------------------------------------------------------------
+
+
+.686p
+.model flat,c
+
+public AsmInterruptHandle
+
+.code
+AsmInterruptHandle:
+ cli
+ mov al, 1
+ iretd
+END
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c
new file mode 100644
index 000000000..b2d4c37a9
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c
@@ -0,0 +1,96 @@
+/** @file
+ Ia32 arch functions to access IDT vector.
+
+ Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php.
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PeCoffExtraActionLib.h>
+
+/**
+ Read IDT entry to check if IDT entries are setup by Debug Agent.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+
+ @retval TRUE IDT entries were setup by Debug Agent.
+ @retval FALSE IDT entries were not setuo by Debug Agent.
+
+**/
+BOOLEAN
+CheckDebugAgentHandler (
+ IN IA32_DESCRIPTOR *IdtDescriptor
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ UINTN InterruptHandler;
+
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor->Base;
+ if (IdtEntry == NULL) {
+ return FALSE;
+ }
+
+ InterruptHandler = IdtEntry[0].Bits.OffsetLow + (IdtEntry[0].Bits.OffsetHigh << 16);
+ if (InterruptHandler >= 4 && *(UINT32 *)(InterruptHandler - 4) == AGENT_HANDLER_SIGNATURE) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+/**
+ Save IDT entry for INT1 and update it.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+ @param[out] SavedIdtEntry Original IDT entry returned.
+
+**/
+VOID
+SaveAndUpdateIdtEntry1 (
+ IN IA32_DESCRIPTOR *IdtDescriptor,
+ OUT IA32_IDT_GATE_DESCRIPTOR *SavedIdtEntry
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ UINT16 CodeSegment;
+ UINTN InterruptHandler;
+
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor->Base;
+ CopyMem (SavedIdtEntry, &IdtEntry[1], sizeof (IA32_IDT_GATE_DESCRIPTOR));
+
+ //
+ // Use current CS as the segment selector of interrupt gate in IDT
+ //
+ CodeSegment = AsmReadCs ();
+
+ InterruptHandler = (UINTN) &AsmInterruptHandle;
+ IdtEntry[1].Bits.OffsetLow = (UINT16)(UINTN)InterruptHandler;
+ IdtEntry[1].Bits.OffsetHigh = (UINT16)((UINTN)InterruptHandler >> 16);
+ IdtEntry[1].Bits.Selector = CodeSegment;
+ IdtEntry[1].Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
+}
+
+/**
+ Restore IDT entry for INT1.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+ @param[in] RestoredIdtEntry IDT entry to be restored.
+
+**/
+VOID
+RestoreIdtEntry1 (
+ IN IA32_DESCRIPTOR *IdtDescriptor,
+ IN IA32_IDT_GATE_DESCRIPTOR *RestoredIdtEntry
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor->Base;
+ CopyMem (&IdtEntry[1], RestoredIdtEntry, sizeof (IA32_IDT_GATE_DESCRIPTOR));
+}
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.c b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.c
index 7b551f20e..c28d7930a 100644
--- a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.c
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.c
@@ -1,7 +1,7 @@
/** @file
PE/Coff Extra Action library instances.
- Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
@@ -12,17 +12,7 @@
**/
-#include <Base.h>
-#include <Library/PeCoffExtraActionLib.h>
-#include <Library/DebugLib.h>
-#include <Library/BaseLib.h>
-#include <Library/IoLib.h>
-#include <Library/PcdLib.h>
-
-#include <ImageDebugSupport.h>
-
-#define DEBUG_LOAD_IMAGE_METHOD_IO_HW_BREAKPOINT 1
-#define DEBUG_LOAD_IMAGE_METHOD_SOFT_INT3 2
+#include <PeCoffExtraActionLib.h>
/**
Check if the hardware breakpoint in Drx is enabled by checking the Lx and Gx bit in Dr7.
@@ -62,16 +52,19 @@ PeCoffLoaderExtraActionCommon (
IN UINTN Signature
)
{
- BOOLEAN InterruptState;
- UINTN Dr0;
- UINTN Dr1;
- UINTN Dr2;
- UINTN Dr3;
- UINTN Dr7;
- UINTN Cr4;
- UINTN NewDr7;
- UINT8 LoadImageMethod;
- UINT8 DebugAgentStatus;
+ BOOLEAN InterruptState;
+ UINTN Dr0;
+ UINTN Dr1;
+ UINTN Dr2;
+ UINTN Dr3;
+ UINTN Dr7;
+ UINTN Cr4;
+ UINTN NewDr7;
+ UINT8 LoadImageMethod;
+ UINT8 DebugAgentStatus;
+ IA32_DESCRIPTOR IdtDescriptor;
+ IA32_IDT_GATE_DESCRIPTOR OriginalIdtEntry;
+ BOOLEAN IdtEntryHooked;
ASSERT (ImageContext != NULL);
@@ -84,6 +77,23 @@ PeCoffLoaderExtraActionCommon (
//
InterruptState = SaveAndDisableInterrupts ();
+ IdtEntryHooked = FALSE;
+ LoadImageMethod = PcdGet8 (PcdDebugLoadImageMethod);
+ AsmReadIdtr (&IdtDescriptor);
+ if (!CheckDebugAgentHandler (&IdtDescriptor)) {
+ if (LoadImageMethod == DEBUG_LOAD_IMAGE_METHOD_SOFT_INT3) {
+ //
+ // Do not trigger INT3 if Debug Agent did not setup IDT entries.
+ //
+ return;
+ }
+ //
+ // Save and update IDT entry for INT1
+ //
+ SaveAndUpdateIdtEntry1 (&IdtDescriptor, &OriginalIdtEntry);
+ IdtEntryHooked = TRUE;
+ }
+
//
// Save Debug Register State
//
@@ -108,7 +118,6 @@ PeCoffLoaderExtraActionCommon (
AsmWriteDr2 ((UINTN) ImageContext);
AsmWriteDr3 (IO_PORT_BREAKPOINT_ADDRESS);
- LoadImageMethod = PcdGet8 (PcdDebugLoadImageMethod);
if (LoadImageMethod == DEBUG_LOAD_IMAGE_METHOD_IO_HW_BREAKPOINT) {
AsmWriteDr7 (0x20000480);
AsmWriteCr4 (Cr4 | BIT3);
@@ -156,6 +165,12 @@ PeCoffLoaderExtraActionCommon (
AsmWriteDr7 (Dr7);
}
//
+ // Restore original IDT entry for INT1 if it was hooked.
+ //
+ if (IdtEntryHooked) {
+ RestoreIdtEntry1 (&IdtDescriptor, &OriginalIdtEntry);
+ }
+ //
// Restore the interrupt state
//
SetInterruptState (InterruptState);
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h
new file mode 100644
index 000000000..36aebf16d
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h
@@ -0,0 +1,74 @@
+/** @file
+ PE/Coff Extra Action library instances, it will report image debug info.
+
+ Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php.
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#ifndef _PE_COFF_EXTRA_ACTION_LIB_H_
+#define _PE_COFF_EXTRA_ACTION_LIB_H_
+
+#include <Base.h>
+#include <Library/PeCoffExtraActionLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/BaseMemoryLib.h>
+
+#include <ImageDebugSupport.h>
+
+#define DEBUG_LOAD_IMAGE_METHOD_IO_HW_BREAKPOINT 1
+#define DEBUG_LOAD_IMAGE_METHOD_SOFT_INT3 2
+
+extern UINTN AsmInterruptHandle;
+
+/**
+ Read IDT entry to check if IDT entries are setup by Debug Agent.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+
+ @retval TRUE IDT entries were setup by Debug Agent.
+ @retval FALSE IDT entries were not setuo by Debug Agent.
+
+**/
+BOOLEAN
+CheckDebugAgentHandler (
+ IN IA32_DESCRIPTOR *IdtDescriptor
+ );
+
+/**
+ Save IDT entry for INT1 and update it.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+ @param[out] SavedIdtEntry Original IDT entry returned.
+
+**/
+VOID
+SaveAndUpdateIdtEntry1 (
+ IN IA32_DESCRIPTOR *IdtDescriptor,
+ OUT IA32_IDT_GATE_DESCRIPTOR *SavedIdtEntry
+ );
+
+/**
+ Restore IDT entry for INT1.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+ @param[in] RestoredIdtEntry IDT entry to be restored.
+
+**/
+VOID
+RestoreIdtEntry1 (
+ IN IA32_DESCRIPTOR *IdtDescriptor,
+ IN IA32_IDT_GATE_DESCRIPTOR *RestoredIdtEntry
+ );
+
+#endif
+
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
index e3712afac..fa485bcf1 100644
--- a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
@@ -1,7 +1,7 @@
## @file
# PeCoffExtraAction Library to support source level debug.
#
-# Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -28,8 +28,19 @@
#
[Sources.common]
+ PeCoffExtraActionLib.h
PeCoffExtraActionLib.c
+[Sources.IA32]
+ Ia32/IntHandlerFuncs.c
+ Ia32/IntHandler.asm | MSFT
+ Ia32/IntHandler.S | GCC
+
+[Sources.X64]
+ X64/IntHandlerFuncs.c
+ X64/IntHandler.asm | MSFT
+ X64/IntHandler.S | GCC
+
[Packages]
MdePkg/MdePkg.dec
SourceLevelDebugPkg/SourceLevelDebugPkg.dec
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.S b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.S
new file mode 100644
index 000000000..108b40cf6
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.S
@@ -0,0 +1,28 @@
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+# This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution. The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php.
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+# Module Name:
+#
+# IntHandler.S
+#
+# Abstract:
+#
+# Assembly interrupt handler function.
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(AsmInterruptHandle)
+
+.text
+ASM_PFX(AsmInterruptHandle):
+ cli
+ movb $1, %al
+ iretq
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.asm b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.asm
new file mode 100644
index 000000000..93f4d6f17
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandler.asm
@@ -0,0 +1,29 @@
+;------------------------------------------------------------------------------
+;
+; Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+; This program and the accompanying materials
+; are licensed and made available under the terms and conditions of the BSD License
+; which accompanies this distribution. The full text of the license may be found at
+; http://opensource.org/licenses/bsd-license.php.
+;
+; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+;
+; Module Name:
+;
+; IntHandler.asm
+;
+; Abstract:
+;
+; Assembly interrupt handler function.
+;
+;------------------------------------------------------------------------------
+
+public AsmInterruptHandle
+
+.code
+AsmInterruptHandle:
+ cli
+ mov al, 1
+ iretq
+END
diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c
new file mode 100644
index 000000000..c9041de76
--- /dev/null
+++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c
@@ -0,0 +1,98 @@
+/** @file
+ X64 arch function to access IDT vector.
+
+ Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
+ This program and the accompanying materials
+ are licensed and made available under the terms and conditions of the BSD License
+ which accompanies this distribution. The full text of the license may be found at
+ http://opensource.org/licenses/bsd-license.php.
+
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+**/
+
+#include <PeCoffExtraActionLib.h>
+
+/**
+ Read IDT entry to check if IDT entries are setup by Debug Agent.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+
+ @retval TRUE IDT entries were setup by Debug Agent.
+ @retval FALSE IDT entries were not setuo by Debug Agent.
+
+**/
+BOOLEAN
+CheckDebugAgentHandler (
+ IN IA32_DESCRIPTOR *IdtDescriptor
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ UINTN InterruptHandler;
+
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor->Base;
+ if (IdtEntry == NULL) {
+ return FALSE;
+ }
+
+ InterruptHandler = IdtEntry[0].Bits.OffsetLow + (((UINTN)IdtEntry[0].Bits.OffsetHigh) << 16) +
+ (((UINTN)IdtEntry[0].Bits.OffsetUpper) << 32);
+ if (InterruptHandler >= 4 && *(UINT32 *)(InterruptHandler - 4) == AGENT_HANDLER_SIGNATURE) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+/**
+ Save IDT entry for INT1 and update it.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+ @param[out] SavedIdtEntry Original IDT entry returned.
+
+**/
+VOID
+SaveAndUpdateIdtEntry1 (
+ IN IA32_DESCRIPTOR *IdtDescriptor,
+ OUT IA32_IDT_GATE_DESCRIPTOR *SavedIdtEntry
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+ UINT16 CodeSegment;
+ UINTN InterruptHandler;
+
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor->Base;
+ CopyMem (SavedIdtEntry, &IdtEntry[1], sizeof (IA32_IDT_GATE_DESCRIPTOR));
+
+ //
+ // Use current CS as the segment selector of interrupt gate in IDT
+ //
+ CodeSegment = AsmReadCs ();
+
+ InterruptHandler = (UINTN) &AsmInterruptHandle;
+ IdtEntry[1].Bits.OffsetLow = (UINT16)(UINTN)InterruptHandler;
+ IdtEntry[1].Bits.OffsetHigh = (UINT16)((UINTN)InterruptHandler >> 16);
+ IdtEntry[1].Bits.OffsetUpper = (UINT32)((UINTN)InterruptHandler >> 32);
+ IdtEntry[1].Bits.Selector = CodeSegment;
+ IdtEntry[1].Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32;
+}
+
+/**
+ Restore IDT entry for INT1.
+
+ @param[in] IdtDescriptor Pointer to IDT Descriptor.
+ @param[in] RestoredIdtEntry IDT entry to be restored.
+
+**/
+VOID
+RestoreIdtEntry1 (
+ IN IA32_DESCRIPTOR *IdtDescriptor,
+ IN IA32_IDT_GATE_DESCRIPTOR *RestoredIdtEntry
+ )
+{
+ IA32_IDT_GATE_DESCRIPTOR *IdtEntry;
+
+ IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor->Base;
+ CopyMem (&IdtEntry[1], RestoredIdtEntry, sizeof (IA32_IDT_GATE_DESCRIPTOR));
+}
diff --git a/SourceLevelDebugPkg/SourceLevelDebugPkg.dec b/SourceLevelDebugPkg/SourceLevelDebugPkg.dec
index 34d700652..5146b9e22 100644
--- a/SourceLevelDebugPkg/SourceLevelDebugPkg.dec
+++ b/SourceLevelDebugPkg/SourceLevelDebugPkg.dec
@@ -7,7 +7,7 @@
# and host, PeCoffExtraActionLib instance to report symbol path information,
# etc.
#
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials are licensed and made available under
# the terms and conditions of the BSD License that accompanies this distribution.
# The full text of the license may be found at
@@ -22,7 +22,7 @@
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = SourceLevelDebugPkg
PACKAGE_GUID = DBF00C27-D8D7-443d-918B-4E85CDA1373B
- PACKAGE_VERSION = 0.80
+ PACKAGE_VERSION = 0.85
[Includes]
Include
@@ -72,3 +72,7 @@
## 1: Use I/O Port 84 to issue hardware break point
## 2: Use INT3 to issue software break point
gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x1|UINT8|0x00000005
+
+ ## The data buffer size used by debug port in debug communication library.
+ gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugPortHandleBufferSize|0x0|UINT16|0x00000006
+
diff --git a/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc b/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc
index 461cbf885..3d9c36428 100644
--- a/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc
+++ b/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc
@@ -2,7 +2,7 @@
#
# Source Level Debug Package.
#
-# Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
@@ -22,7 +22,7 @@
[Defines]
PLATFORM_NAME = SourceLevelDebugPkg
PLATFORM_GUID = 38C85805-883F-4ee8-A854-95B966ED73AA
- PLATFORM_VERSION = 0.80
+ PLATFORM_VERSION = 0.85
DSC_SPECIFICATION = 0x00010005
OUTPUT_DIRECTORY = Build/SourceLevelDebugPkg
SUPPORTED_ARCHITECTURES = IA32|X64
@@ -30,13 +30,43 @@
SKUID_IDENTIFIER = DEFAULT
[LibraryClasses.common]
- DebugLib|MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf
+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf
BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
- TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf
PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
+ LocalApicLib|UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf
+ PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+ SerialPortLib|MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf
+ PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
+ TimerLib|UefiCpuPkg/Library/SecPeiDxeTimerLibUefiCpu/SecPeiDxeTimerLibUefiCpu.inf
+ ResetSystemLib|PcAtChipsetPkg/Library/ResetSystemLib/ResetSystemLib.inf
+
+ PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf
+
DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
+ #DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.inf
+
+[LibraryClasses.common.PEIM]
+ PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
+ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
+ PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
+ HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
+ MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
+ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
+
+[LibraryClasses.common.DXE_DRIVER]
+ UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
+ UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
+ UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
+ UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
###################################################################################################
#
@@ -64,4 +94,5 @@
SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf
-
+ SourceLevelDebugPkg/DebugAgentPei/DebugAgentPei.inf
+ SourceLevelDebugPkg/DebugAgentDxe/DebugAgentDxe.inf
diff --git a/StdLib/ISSUES.txt b/StdLib/ISSUES.txt
new file mode 100644
index 000000000..f2b695e47
--- /dev/null
+++ b/StdLib/ISSUES.txt
@@ -0,0 +1,54 @@
+ Status Key:
+ Open Problem is unresolved and final disposition unknown.
+ Verified Problem has been reproduced.
+ Understood Root cause of problem is understood.
+ Document Problem is to be fixed through improved documentation.
+ Fixed Problem has been resolved and changes committed.
+
+SocketLib
+=============
+ Category TOOLs Reported Status
+ ------------------------ -------- -------------- -----------
+
+StdLib Issues
+=============
+ Category TOOLs Reported Status
+ ------------------------ -------- -------------- -----------
+1: Compilation Error vs2010 2012 Understood
+ stdlib\libc\gdtoa\strtod.c(825) : warning C4789: destination of memory copy is too small
+
+2: Compilation Error ALL 2012 Fixed 1/2012
+ StdLib/LibC/Uefi/SysCalls.c: In function 'utimes': error: 'va_start' used in function with fixed args
+
+3: Usage Clarification 2012 Understood/Document
+ Clarify that the current StdLib may not be used for developing drivers.
+
+4: Execution/Compile errors 2012 Understood
+ Mismatch in use of EFIAPI between declaration and definition of some functions.
+
+5: Error message Quality during execution 2012 Verified
+ Performing filesystem operations when a filesystem driver has not been
+ linked into the application results in hangs or error messages that are
+ misleading or unclear as to the cause.
+
+6: Application error return 2012 Verified
+ On error, applications will sometimes return large positive numbers.
+
+7: Compilation Error GCC46 Jan, 2013 Fixed 1/2013
+ StdLib/LibC/Containers/Queues/Fifo.c:508:27: error: assignment from incompatible pointer type
+
+8: Compilation Error
+ StdLib\LibC\Uefi\InteractiveIO\IIOutilities.c Jan. 2013 Fixed 1/2013
+ IIO_CursorDelta: Declaration return type differs from definition return type.
+
+9: chdir/cwd not in EFI Shell 2012 Understood
+ The chdir and getcwd functions only work if one is using the UEFI Shell.
+
+10: No current volume/directory at app. startup. 2012 Understood
+ If the Shell does not have a current volume or directory, file operations
+ may hang or fail.
+
+PosixLib
+=============
+ Category TOOLs Reported Status
+ ------------------------ -------- -------------- -----------
diff --git a/StdLib/Include/Containers/Fifo.h b/StdLib/Include/Containers/Fifo.h
index 3b232fec2..69dd55b03 100644
--- a/StdLib/Include/Containers/Fifo.h
+++ b/StdLib/Include/Containers/Fifo.h
@@ -151,8 +151,10 @@ typedef size_t (EFIAPI *cFIFO_Flush) (cFIFO *Self, size_t NumToFlush);
/** Remove the most recent element from the FIFO.
@param[in] Self Pointer to the FIFO instance.
+
+ @return Returns the number of elements remaining in the FIFO.
**/
-typedef void (EFIAPI *cFIFO_Truncate) (cFIFO *Self);
+typedef size_t (EFIAPI *cFIFO_Truncate) (cFIFO *Self);
/** Cleanly delete a FIFO instance.
diff --git a/StdLib/LibC/Uefi/InteractiveIO/IIOutilities.c b/StdLib/LibC/Uefi/InteractiveIO/IIOutilities.c
index 2da062884..1c978eae7 100644
--- a/StdLib/LibC/Uefi/InteractiveIO/IIOutilities.c
+++ b/StdLib/LibC/Uefi/InteractiveIO/IIOutilities.c
@@ -263,8 +263,10 @@ IIO_GetOutputSize (
@param[in] EndXY Pointer to the ending coordinate pair.
@return Returns the difference between the starting and ending coordinates.
+ The return value is positive if the coordinates contained in EndXY
+ are larger than StartXY, otherwise the return value is negative.
**/
-UINT32
+int
EFIAPI
IIO_CursorDelta (
cIIO *This,
@@ -272,17 +274,15 @@ IIO_CursorDelta (
CURSOR_XY *EndXY
)
{
- INT32 ColumnDelta;
- INT32 RowDelta;
+ int ColumnDelta;
+ int RowDelta;
RowDelta = (int)EndXY->Row - (int)StartXY->Row;
assert(RowDelta >= 0); // assert if EndXY is NOT after StartXY
- ColumnDelta = (INT32)((This->MaxColumn * RowDelta) + EndXY->Column);
- ColumnDelta -= (INT32)StartXY->Column;
-
- assert(ColumnDelta >= 0); // assert if EndXY is NOT after StartXY
+ ColumnDelta = (int)((This->MaxColumn * RowDelta) + EndXY->Column);
+ ColumnDelta -= (int)StartXY->Column;
- return (UINT32)ColumnDelta;
+ return ColumnDelta;
}